[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M77HG5FX2D1YS0T3RAX5C4E9":3,"skill-same:01M77HG5FX2D1YS0T3RAX5C4E9":71},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":48,"commitSha":49,"skillDirectory":50,"forksCount":51,"repositoryHtmlUrl":52,"repositoryHomepageUrl":53,"ownerHtmlUrl":54,"ownerBlogUrl":6,"ownerDescription":55,"updatedAt":56,"install":57,"resources":70},"01M77HG5FX2D1YS0T3RAX5C4E9","greenhelix-agent-procurement-playbook",null,"The Agent Procurement Playbook. Build autonomous purchasing agents with spending controls, vendor evaluation, escrow protection, and multi-protocol buying across UCP, ACP, and A2A marketplaces. Includes detailed Python code examples with full API integration.","Lord1Egypt\u002Fawesome-skill-forge","Lord1Egypt","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99746359?v=4","01M7592YDNT0XK9WJ0T2MQVPDN","Mohamed Mounir Ali AL Keshita","01M75GRFNHC8VZNWEB8DKDE433",3,"MIT","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-procurement-playbook\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: greenhelix-agent-procurement-playbook\nversion: \"1.3.1\"\ndescription: \"The Agent Procurement Playbook. Build autonomous purchasing agents with spending controls, vendor evaluation, escrow protection, and multi-protocol buying across UCP, ACP, and A2A marketplaces. Includes detailed Python code examples with full API integration.\"\nlicense: MIT\ncompatibility: [openclaw]\nauthor: felix-agent\ntype: guide\ntags: [procurement, purchasing, spending-controls, vendor-evaluation, escrow, guide, greenhelix, openclaw, ai-agent]\nprice_usd: 49.0\ncontent_type: markdown\nexecutable: false\ninstall: none\ncredentials: [GREENHELIX_API_KEY, WALLET_ADDRESS, STRIPE_API_KEY]\nmetadata:\n  openclaw:\n    requires:\n      env:\n        - GREENHELIX_API_KEY\n        - WALLET_ADDRESS\n        - STRIPE_API_KEY\n    primaryEnv: GREENHELIX_API_KEY\n---\n# The Agent Procurement Playbook\n\n> **Notice**: This is an educational guide with illustrative code examples.\n> It does not execute code or install dependencies.\n> All examples use the GreenHelix sandbox (https:\u002F\u002Fsandbox.greenhelix.net) which\n> provides 500 free credits — no API key required to get started.\n>\n> **Referenced credentials** (you supply these in your own environment):\n> - `GREENHELIX_API_KEY`: API authentication for GreenHelix gateway (read\u002Fwrite access to purchased API tools only)\n> - `WALLET_ADDRESS`: Blockchain wallet address for receiving payments (public address only — no private keys)\n> - `STRIPE_API_KEY`: Stripe API key for card payment processing (scoped to payment intents only)\n\n\nYour AI agent just found the perfect data enrichment service. It costs $0.003 per record, the vendor has a 97% accuracy rating, and the API response time is under 200ms. The agent wants to buy 500,000 records. That is $1,500 committed in under a second, with no human in the loop, no purchase order, no procurement review. Should the agent be allowed to spend that money? If yes, under what constraints? If no, what happens to the time-sensitive workflow waiting on that data?\nThis is the central tension of autonomous procurement: agents that can buy things are dramatically more capable than agents that cannot, but agents that spend without governance are a financial liability. A February 2026 survey by Gartner found that 86% of organizations plan to deploy autonomous AI agents at scale by end of 2026. McKinsey's March 2026 analysis of early adopters showed that autonomous procurement workflows -- where agents discover, evaluate, negotiate, and purchase services without human intervention -- deliver 15-30% efficiency gains over human-mediated purchasing. But 41% of those same organizations reported at least one incident of uncontrolled agent spending in their first quarter of deployment.\nThe solution is not to prevent agents from spending. It is to build the procurement infrastructure that makes autonomous spending safe, auditable, and reversible. This playbook shows you how. Every chapter contains working Python code against the GreenHelix A2A Commerce Gateway -- 128 tools accessible at `https:\u002F\u002Fapi.greenhelix.net\u002Fv1` via a single the REST API (`POST \u002Fv1\u002F{tool}`) endpoint. By the end, you will have a complete autonomous procurement system: spending policy engine, multi-protocol vendor discovery, trust-scored vendor evaluation, escrow-protected purchasing, automated dispute resolution, cost reconciliation, and EU AI Act-compliant audit trails.\n\n## What You'll Learn\n- Chapter 1: The Autonomous Buyer Architecture\n- Chapter 2: Spending Controls & Approval Workflows\n- Chapter 3: Vendor Discovery Across Protocols\n- Chapter 4: Vendor Evaluation & Trust Scoring\n- Chapter 5: Multi-Protocol Purchasing\n- Chapter 6: Escrow, Disputes & Purchase Protection\n- Chapter 7: Cost Reconciliation & FinOps Integration\n- Chapter 8: Compliance & Audit Trails\n- {report['organization']} - {si['system_name']}\n- Appendix: Quick Reference\n\n## Full Guide\n\n# The Agent Procurement Playbook: Autonomous Purchasing, Spending Controls, Vendor Evaluation & Multi-Protocol Buying\n\nYour AI agent just found the perfect data enrichment service. It costs $0.003 per record, the vendor has a 97% accuracy rating, and the API response time is under 200ms. The agent wants to buy 500,000 records. That is $1,500 committed in under a second, with no human in the loop, no purchase order, no procurement review. Should the agent be allowed to spend that money? If yes, under what constraints? If no, what happens to the time-sensitive workflow waiting on that data?\n\nThis is the central tension of autonomous procurement: agents that can buy things are dramatically more capable than agents that cannot, but agents that spend without governance are a financial liability. A February 2026 survey by Gartner found that 86% of organizations plan to deploy autonomous AI agents at scale by end of 2026. McKinsey's March 2026 analysis of early adopters showed that autonomous procurement workflows -- where agents discover, evaluate, negotiate, and purchase services without human intervention -- deliver 15-30% efficiency gains over human-mediated purchasing. But 41% of those same organizations reported at least one incident of uncontrolled agent spending in their first quarter of deployment.\n\nThe solution is not to prevent agents from spending. It is to build the procurement infrastructure that makes autonomous spending safe, auditable, and reversible. This playbook shows you how. Every chapter contains working Python code against the GreenHelix A2A Commerce Gateway -- 128 tools accessible at `https:\u002F\u002Fapi.greenhelix.net\u002Fv1` via a single the REST API (`POST \u002Fv1\u002F{tool}`) endpoint. By the end, you will have a complete autonomous procurement system: spending policy engine, multi-protocol vendor discovery, trust-scored vendor evaluation, escrow-protected purchasing, automated dispute resolution, cost reconciliation, and EU AI Act-compliant audit trails.\n\n---\n\n\n> **Getting started**: All examples in this guide work with the GreenHelix sandbox\n> (https:\u002F\u002Fsandbox.greenhelix.net) which provides 500 free credits — no API key required.\n\n## Table of Contents\n\n1. [The Autonomous Buyer Architecture](#chapter-1-the-autonomous-buyer-architecture)\n2. [Spending Controls & Approval Workflows](#chapter-2-spending-controls--approval-workflows)\n3. [Vendor Discovery Across Protocols](#chapter-3-vendor-discovery-across-protocols)\n4. [Vendor Evaluation & Trust Scoring](#chapter-4-vendor-evaluation--trust-scoring)\n5. [Multi-Protocol Purchasing](#chapter-5-multi-protocol-purchasing)\n6. [Escrow, Disputes & Purchase Protection](#chapter-6-escrow-disputes--purchase-protection)\n7. [Cost Reconciliation & FinOps Integration](#chapter-7-cost-reconciliation--finops-integration)\n8. [Compliance & Audit Trails](#chapter-8-compliance--audit-trails)\n\n---\n\n## Chapter 1: The Autonomous Buyer Architecture\n\n### Why Agents Need to Spend Money\n\nA research agent that cannot purchase data is limited to free datasets. A coding agent that cannot buy API access is limited to open-source tools. A sales agent that cannot pay for lead enrichment is limited to whatever data it already has. Every boundary on an agent's purchasing authority is also a boundary on its capability.\n\nThe shift from agents-as-tools to agents-as-economic-actors is the defining infrastructure transition of 2026. When an agent can autonomously discover a service it needs, evaluate whether that service is trustworthy, negotiate a price, execute a purchase, verify delivery, and reconcile the cost against a budget -- it becomes a self-sufficient economic unit. It no longer needs a human to approve every API subscription, every data purchase, every compute reservation. It operates at machine speed across the entire procurement cycle.\n\nBut this autonomy comes with a prerequisite: procurement infrastructure. The same infrastructure that enterprises built over decades for human purchasing -- approval hierarchies, spending limits, preferred vendor lists, purchase orders, three-way matching, audit trails -- must be rebuilt for agents. Not as bureaucratic overhead, but as programmatic guardrails that enable speed while preventing catastrophe.\n\n### The Procurement Loop\n\nEvery autonomous purchase follows a six-stage loop. The stages are sequential for a single purchase, but a production procurement agent runs hundreds of these loops concurrently.\n\n```\nDISCOVER --> EVALUATE --> NEGOTIATE --> PURCHASE --> VERIFY --> RECONCILE\n    ^                                                              |\n    |______________________________________________________________|\n                        (feedback loop)\n```\n\n**Stage 1: Discover.** The agent identifies a need (data, compute, API access, a service) and searches available vendors across multiple protocols. This is not a Google search -- it is structured queries against marketplace APIs, UCP manifests, ACP directories, and A2A service registries.\n\n**Stage 2: Evaluate.** The agent scores each vendor on trust, reputation, price, capability, and compliance. A vendor with a low trust score or missing identity verification is filtered out regardless of price. This stage uses GreenHelix Trust, Identity, and Reputation tools.\n\n**Stage 3: Negotiate.** For commodity purchases, negotiation is price comparison. For high-value or recurring purchases, the agent can request volume discounts, propose escrow terms, or negotiate SLA guarantees. See P14 (Negotiation Strategies) for advanced techniques.\n\n**Stage 4: Purchase.** The agent executes the payment through the appropriate protocol: x402 for crypto micropayments, UCP for fiat retail, ACP for agent-native checkout, or direct A2A commerce via GreenHelix. Escrow protects high-value transactions.\n\n**Stage 5: Verify.** The agent confirms delivery by inspecting the purchased asset -- validating data quality, checking API responses, running acceptance tests on delivered services. Failed verification triggers the dispute process.\n\n**Stage 6: Reconcile.** The agent records the purchase in its ledger, attributes the cost to the requesting workflow, and updates budget consumption. Anomaly detection flags unexpected spending patterns.\n\n### Reference Architecture\n\nThe autonomous buyer architecture has four core components:\n\n```\n+---------------------------------------------------------------------+\n|                    AUTONOMOUS BUYER AGENT                            |\n|                                                                     |\n|  +------------------+  +-------------------+  +------------------+  |\n|  | Spending Policy  |  |  Vendor Discovery |  | Purchase Engine  |  |\n|  | Engine           |  |  & Evaluation     |  |                  |  |\n|  |                  |  |                   |  | - x402 rail      |  |\n|  | - Budget caps    |  | - Multi-protocol  |  | - UCP rail       |  |\n|  | - Tx limits      |  |   search          |  | - ACP rail       |  |\n|  | - Whitelists     |  | - Trust scoring   |  | - A2A rail       |  |\n|  | - Escalation     |  | - Bid comparison  |  | - Escrow mgmt    |  |\n|  +--------+---------+  +--------+----------+  +--------+---------+  |\n|           |                     |                      |            |\n|  +--------v---------------------v----------------------v---------+  |\n|  |                    APPROVAL GATEWAY                           |  |\n|  |  Routes decisions through policy engine before execution      |  |\n|  +-------------------------------+-------------------------------+  |\n|                                  |                                  |\n+----------------------------------+----------------------------------+\n                                   |\n                                   v\n+-------------------------------+     +-------------------------------+\n|  GREENHELIX A2A COMMERCE      |     |  RECONCILIATION ENGINE       |\n|  GATEWAY                      |     |                               |\n|                               |     |  - Ledger recording           |\n|  128 tools via POST           |     |  - Cost attribution           |\n|  the REST API                  |     |  - Budget vs. actual          |\n|                               |     |  - Anomaly detection          |\n+-------------------------------+     +-------------------------------+\n```\n\nThe Spending Policy Engine is the gatekeeper. Every purchase request passes through it before execution. It checks per-transaction limits, daily budget caps, vendor whitelists, and escalation thresholds. If a purchase exceeds policy, it is either blocked, queued for human approval, or routed to a higher-authority agent.\n\nThe Approval Gateway sits between the policy engine and the purchase engine. It is the single choke point through which all spend flows. This architectural decision -- funneling all purchases through one gateway -- is critical for auditability and control. You cannot have agents bypassing the gateway by calling GreenHelix directly.\n\n### Bootstrapping the Architecture\n\nHere is the minimum code to initialize the architecture against GreenHelix:\n\n```python\nimport requests\nimport os\nfrom dataclasses import dataclass, field\nfrom typing import Optional\n\nAPI_BASE = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\nheaders = {\"Authorization\": f\"Bearer {os.environ['GREENHELIX_API_KEY']}\"}\n\n\ndef execute_tool(tool: str, input_data: dict) -> dict:\n    \"\"\"Execute a GreenHelix tool via the unified endpoint.\"\"\"\n    response = requests.post(\n        f\"{API_BASE}\u002Fv1\",\n        json={\"tool\": tool, \"input\": input_data},\n        headers=headers,\n    )\n    response.raise_for_status()\n    return response.json()\n\n\n@dataclass\nclass BuyerAgent:\n    agent_id: str\n    wallet_id: Optional[str] = None\n    budget_daily: float = 0.0\n    budget_monthly: float = 0.0\n\n    def initialize(self):\n        \"\"\"Create wallet and set initial budget.\"\"\"\n        wallet = execute_tool(\"create_wallet\", {\n            \"agent_id\": self.agent_id,\n            \"currency\": \"USD\",\n        })\n        self.wallet_id = wallet[\"wallet_id\"]\n\n        execute_tool(\"set_budget\", {\n            \"agent_id\": self.agent_id,\n            \"daily_limit\": self.budget_daily,\n            \"monthly_limit\": self.budget_monthly,\n        })\n        return self\n\n    def get_spending_status(self) -> dict:\n        \"\"\"Check current balance and usage.\"\"\"\n        balance = execute_tool(\"get_balance\", {\n            \"agent_id\": self.agent_id,\n        })\n        usage = execute_tool(\"get_usage_analytics\", {\n            \"agent_id\": self.agent_id,\n            \"period\": \"current_day\",\n        })\n        return {\n            \"balance\": balance[\"balance\"],\n            \"daily_spend\": usage.get(\"total_spend\", 0),\n            \"daily_remaining\": self.budget_daily - usage.get(\"total_spend\", 0),\n        }\n\n\n# Initialize a buyer agent with a $50\u002Fday, $1000\u002Fmonth budget\nbuyer = BuyerAgent(\n    agent_id=\"procurement-agent-01\",\n    budget_daily=50.00,\n    budget_monthly=1000.00,\n).initialize()\n\nprint(buyer.get_spending_status())\n```\n\nThis gives you an agent with a wallet, budget caps, and real-time spending visibility. The rest of this playbook builds on this foundation.\n\n> **Key Takeaways**\n>\n> - Autonomous procurement follows a six-stage loop: discover, evaluate, negotiate, purchase, verify, reconcile.\n> - The Spending Policy Engine is the gatekeeper -- every purchase passes through it before execution.\n> - The Approval Gateway is the single choke point for all spend. No agent should bypass it.\n> - Start with a wallet, a budget, and spending visibility. Everything else builds on this foundation.\n> - Organizations deploying autonomous procurement see 15-30% efficiency gains, but 41% experience uncontrolled spending incidents without proper governance.\n\n---\n\n## Chapter 2: Spending Controls & Approval Workflows\n\n### The Five Layers of Spending Control\n\nSpending controls for autonomous agents are not a single dial. They are five independent layers, each catching a different failure mode. Deploying only one layer leaves you exposed to the failures the others catch.\n\n| Layer | Control | What It Catches | GreenHelix Tool |\n|-------|---------|-----------------|-----------------|\n| 1 | Per-transaction cap | Single large unauthorized purchase | `set_budget` |\n| 2 | Daily\u002Fweekly budget limit | Runaway loops, amplification | `set_budget`, `get_usage_analytics` |\n| 3 | Recipient whitelist | Purchases from untrusted vendors | Policy engine (custom) |\n| 4 | Frequency limit | Rapid-fire small purchases that aggregate to large spend | Policy engine (custom) |\n| 5 | Human-in-the-loop escalation | Novel situations outside policy | Webhook + approval queue |\n\n**Layer 1: Per-Transaction Caps.** No single purchase can exceed a defined amount. This is the bluntest control -- it prevents a single bad decision from causing catastrophic damage. Set it at the maximum amount you would tolerate losing in a single transaction. For most agent workflows, $100-500 is appropriate for automated approval; anything above goes to escalation.\n\n**Layer 2: Daily\u002FWeekly Budget Limits.** Even if every individual transaction is small, an agent in a loop can drain a budget through volume. A $0.01 transaction repeated 100,000 times is $1,000. Daily and weekly limits create a hard ceiling on cumulative spend regardless of individual transaction sizes.\n\n**Layer 3: Recipient Whitelists.** The agent can only purchase from pre-approved vendors. This prevents an agent from being socially engineered (via prompt injection or adversarial marketplace listings) into sending money to a malicious actor. Whitelists can be static (a fixed list) or dynamic (any vendor with a trust score above a threshold).\n\n**Layer 4: Frequency Limits.** Rate-limiting purchases prevents rapid-fire micro-transactions that individually pass the per-transaction cap but collectively blow through the daily budget before alerting systems can react. A typical setting: no more than 10 purchases per minute, no more than 100 per hour.\n\n**Layer 5: Human-in-the-Loop Escalation.** For purchases that exceed caps, involve new vendors, or fall outside known categories, the system queues the purchase for human approval. The key design decision is what happens while waiting: does the workflow block (synchronous escalation) or continue with a fallback (asynchronous escalation)?\n\n### The ProcurementPolicyEngine\n\nThis class implements all five layers. It is the core of the spending control system.\n\n```python\nimport time\nfrom dataclasses import dataclass, field\nfrom typing import Optional\nfrom enum import Enum\n\n\nclass ApprovalDecision(Enum):\n    APPROVED = \"approved\"\n    DENIED = \"denied\"\n    ESCALATED = \"escalated\"\n\n\n@dataclass\nclass PurchaseRequest:\n    vendor_id: str\n    amount: float\n    currency: str = \"USD\"\n    category: str = \"general\"\n    description: str = \"\"\n    requesting_agent: str = \"\"\n    idempotency_key: str = \"\"\n\n\n@dataclass\nclass PolicyResult:\n    decision: ApprovalDecision\n    reason: str\n    purchase_request: Optional[PurchaseRequest] = None\n    escalation_id: Optional[str] = None\n\n\n@dataclass\nclass ProcurementPolicyEngine:\n    \"\"\"Five-layer spending control for autonomous procurement agents.\"\"\"\n\n    agent_id: str\n    max_transaction_amount: float = 500.00\n    daily_limit: float = 2000.00\n    weekly_limit: float = 10000.00\n    max_purchases_per_minute: int = 10\n    max_purchases_per_hour: int = 100\n    escalation_threshold: float = 500.00\n    vendor_whitelist: list = field(default_factory=list)\n    require_whitelist: bool = False\n\n    # Internal tracking\n    _purchase_timestamps: list = field(default_factory=list)\n    _daily_spend: float = 0.0\n\n    def evaluate(self, request: PurchaseRequest) -> PolicyResult:\n        \"\"\"Run a purchase request through all five control layers.\"\"\"\n\n        # Layer 1: Per-transaction cap\n        if request.amount > self.max_transaction_amount:\n            if request.amount > self.escalation_threshold:\n                return PolicyResult(\n                    decision=ApprovalDecision.ESCALATED,\n                    reason=f\"Amount ${request.amount:.2f} exceeds \"\n                           f\"auto-approval cap ${self.max_transaction_amount:.2f}\",\n                    purchase_request=request,\n                )\n            return PolicyResult(\n                decision=ApprovalDecision.DENIED,\n                reason=f\"Amount ${request.amount:.2f} exceeds \"\n                       f\"per-transaction limit ${self.max_transaction_amount:.2f}\",\n            )\n\n        # Layer 2: Daily budget limit\n        projected_daily = self._daily_spend + request.amount\n        if projected_daily > self.daily_limit:\n            return PolicyResult(\n                decision=ApprovalDecision.DENIED,\n                reason=f\"Purchase would bring daily spend to \"\n                       f\"${projected_daily:.2f}, exceeding \"\n                       f\"daily limit ${self.daily_limit:.2f}\",\n            )\n\n        # Layer 3: Vendor whitelist\n        if self.require_whitelist and request.vendor_id not in self.vendor_whitelist:\n            return PolicyResult(\n                decision=ApprovalDecision.ESCALATED,\n                reason=f\"Vendor {request.vendor_id} not in whitelist. \"\n                       f\"Escalating for manual review.\",\n                purchase_request=request,\n            )\n\n        # Layer 4: Frequency limit\n        now = time.time()\n        recent_minute = [t for t in self._purchase_timestamps if now - t \u003C 60]\n        recent_hour = [t for t in self._purchase_timestamps if now - t \u003C 3600]\n\n        if len(recent_minute) >= self.max_purchases_per_minute:\n            return PolicyResult(\n                decision=ApprovalDecision.DENIED,\n                reason=f\"Rate limit: {len(recent_minute)} purchases in \"\n                       f\"the last minute (max {self.max_purchases_per_minute})\",\n            )\n        if len(recent_hour) >= self.max_purchases_per_hour:\n            return PolicyResult(\n                decision=ApprovalDecision.DENIED,\n                reason=f\"Rate limit: {len(recent_hour)} purchases in \"\n                       f\"the last hour (max {self.max_purchases_per_hour})\",\n            )\n\n        # Layer 5: Escalation threshold for borderline amounts\n        if request.amount > self.escalation_threshold:\n            return PolicyResult(\n                decision=ApprovalDecision.ESCALATED,\n                reason=f\"Amount ${request.amount:.2f} exceeds escalation \"\n                       f\"threshold ${self.escalation_threshold:.2f}\",\n                purchase_request=request,\n            )\n\n        # All layers passed\n        self._purchase_timestamps.append(now)\n        self._daily_spend += request.amount\n        return PolicyResult(\n            decision=ApprovalDecision.APPROVED,\n            reason=\"All policy checks passed\",\n        )\n\n    def sync_with_gateway(self):\n        \"\"\"Sync local state with GreenHelix budget and usage data.\"\"\"\n        usage = execute_tool(\"get_usage_analytics\", {\n            \"agent_id\": self.agent_id,\n            \"period\": \"current_day\",\n        })\n        self._daily_spend = usage.get(\"total_spend\", 0)\n\n        balance = execute_tool(\"get_balance\", {\n            \"agent_id\": self.agent_id,\n        })\n        return {\n            \"daily_spend\": self._daily_spend,\n            \"daily_remaining\": self.daily_limit - self._daily_spend,\n            \"wallet_balance\": balance[\"balance\"],\n        }\n\n\n# Initialize the policy engine\npolicy = ProcurementPolicyEngine(\n    agent_id=\"procurement-agent-01\",\n    max_transaction_amount=500.00,\n    daily_limit=2000.00,\n    weekly_limit=10000.00,\n    escalation_threshold=250.00,\n    vendor_whitelist=[\"vendor-data-enrichment-01\", \"vendor-compute-aws-02\"],\n    require_whitelist=True,\n)\n\n# Evaluate a purchase request\nresult = policy.evaluate(PurchaseRequest(\n    vendor_id=\"vendor-data-enrichment-01\",\n    amount=45.00,\n    category=\"data\",\n    description=\"500k contact records enrichment\",\n    requesting_agent=\"research-agent-03\",\n))\n\nprint(f\"Decision: {result.decision.value}\")\nprint(f\"Reason: {result.reason}\")\n```\n\n### Escalation Workflow with Webhooks\n\nWhen a purchase is escalated, the system notifies a human approver and holds the purchase in a pending state. Here is how to wire up the escalation:\n\n```python\ndef handle_escalation(policy_result: PolicyResult) -> dict:\n    \"\"\"Queue an escalated purchase for human approval.\"\"\"\n    # Register a webhook for approval notifications\n    webhook = execute_tool(\"register_webhook\", {\n        \"agent_id\": policy.agent_id,\n        \"url\": \"https:\u002F\u002Fyour-app.example.com\u002Fprocurement\u002Fapprovals\",\n        \"events\": [\"purchase.approval_required\"],\n    })\n\n    # Record the pending purchase in the ledger for tracking\n    pending = execute_tool(\"record_transaction\", {\n        \"agent_id\": policy.agent_id,\n        \"type\": \"purchase_pending\",\n        \"amount\": str(policy_result.purchase_request.amount),\n        \"currency\": \"USD\",\n        \"counterparty\": policy_result.purchase_request.vendor_id,\n        \"metadata\": {\n            \"status\": \"awaiting_human_approval\",\n            \"reason\": policy_result.reason,\n            \"category\": policy_result.purchase_request.category,\n        },\n    })\n\n    return {\n        \"escalation_id\": pending.get(\"transaction_id\"),\n        \"status\": \"awaiting_approval\",\n        \"webhook_id\": webhook.get(\"webhook_id\"),\n    }\n```\n\n### Budget Configuration Decision Matrix\n\nUse this matrix to set appropriate limits based on your agent's role:\n\n| Agent Role | Per-Tx Cap | Daily Limit | Weekly Limit | Escalation | Whitelist Required |\n|---|---|---|---|---|---|\n| Research agent (data purchases) | $100 | $500 | $2,000 | $50 | Yes |\n| Infrastructure agent (compute) | $1,000 | $5,000 | $20,000 | $500 | Yes |\n| Sales agent (lead enrichment) | $200 | $1,000 | $4,000 | $100 | Yes |\n| Trading agent (market data) | $50 | $200 | $1,000 | $25 | No (dynamic trust) |\n| General-purpose agent | $50 | $250 | $1,000 | $25 | Yes |\n\n> **Key Takeaways**\n>\n> - Five independent control layers: per-transaction caps, daily\u002Fweekly budgets, vendor whitelists, frequency limits, and human escalation.\n> - The `ProcurementPolicyEngine` evaluates every purchase request before execution. No purchase bypasses the engine.\n> - Escalation is not failure -- it is a feature. Design your workflows to handle the delay introduced by human-in-the-loop review.\n> - Sync the policy engine with GreenHelix usage analytics to keep local state consistent with actual spend.\n> - Set limits based on agent role, not a single global policy. A trading agent and an infrastructure agent have fundamentally different spending patterns.\n\n---\n\n## Chapter 3: Vendor Discovery Across Protocols\n\n### The Multi-Protocol Discovery Problem\n\nYour procurement agent needs a data enrichment service. Where does it look? In 2026, vendors advertise their services across at least four distinct protocols, each with its own discovery mechanism:\n\n- **GreenHelix Marketplace** -- Structured service listings with trust scores, ratings, and escrow history. Discovery via `search_services` and `best_match` tools.\n- **UCP (Universal Commerce Protocol)** -- Google and Shopify's protocol for structured product and service catalogs. Agents query UCP manifests to find services and compare prices.\n- **ACP (Agentic Commerce Protocol)** -- OpenAI's protocol for agent-to-merchant discovery. ACP directories list merchants with Stripe-backed checkout.\n- **A2A Direct** -- Agent-to-agent service advertisements via standardized capability manifests. No marketplace intermediary.\n\nA vendor might list on one protocol, two, or all four. A procurement agent that only searches one protocol misses vendors available on the others. The solution is a unified vendor index that aggregates discovery results across all protocols.\n\n### GreenHelix Marketplace Discovery\n\nThe GreenHelix Marketplace is the richest discovery source because it includes trust, reputation, and escrow data alongside service listings.\n\n```python\ndef discover_greenhelix_vendors(query: str, category: str = None,\n                                 min_trust_score: float = 0.7,\n                                 max_results: int = 20) -> list:\n    \"\"\"Search GreenHelix Marketplace for services matching a query.\"\"\"\n    search_params = {\n        \"query\": query,\n        \"max_results\": max_results,\n    }\n    if category:\n        search_params[\"category\"] = category\n\n    results = execute_tool(\"search_services\", search_params)\n\n    # Filter by trust score\n    filtered = []\n    for service in results.get(\"services\", []):\n        trust = execute_tool(\"check_trust_score\", {\n            \"agent_id\": service[\"provider_id\"],\n        })\n        if trust.get(\"trust_score\", 0) >= min_trust_score:\n            service[\"trust_score\"] = trust[\"trust_score\"]\n            filtered.append(service)\n\n    # Rank by best match\n    if filtered:\n        best = execute_tool(\"best_match\", {\n            \"query\": query,\n            \"candidates\": [s[\"service_id\"] for s in filtered],\n        })\n        # Reorder filtered list by best_match ranking\n        ranked_ids = [m[\"service_id\"] for m in best.get(\"matches\", [])]\n        filtered.sort(key=lambda s: (\n            ranked_ids.index(s[\"service_id\"])\n            if s[\"service_id\"] in ranked_ids else 999\n        ))\n\n    return filtered\n```\n\n### UCP Manifest Discovery\n\nUCP manifests are structured JSON documents that describe services in a standardized format. Agents query them by fetching the manifest URL and parsing the catalog.\n\n```python\nimport requests as http_client\n\n\ndef discover_ucp_vendors(manifest_urls: list, query: str) -> list:\n    \"\"\"Query UCP manifests for matching services.\"\"\"\n    vendors = []\n    for url in manifest_urls:\n        try:\n            resp = http_client.get(url, timeout=10)\n            resp.raise_for_status()\n            manifest = resp.json()\n\n            for service in manifest.get(\"services\", []):\n                # Simple keyword matching against service description\n                name = service.get(\"name\", \"\").lower()\n                desc = service.get(\"description\", \"\").lower()\n                if query.lower() in name or query.lower() in desc:\n                    vendors.append({\n                        \"source\": \"ucp\",\n                        \"provider_id\": manifest.get(\"provider_id\"),\n                        \"service_id\": service.get(\"id\"),\n                        \"name\": service.get(\"name\"),\n                        \"price\": service.get(\"price\"),\n                        \"currency\": service.get(\"currency\", \"USD\"),\n                        \"manifest_url\": url,\n                    })\n        except (http_client.RequestException, ValueError):\n            continue  # Skip unreachable or malformed manifests\n\n    return vendors\n\n\ndef discover_acp_vendors(directory_url: str, query: str) -> list:\n    \"\"\"Query an ACP agent directory for matching services.\"\"\"\n    try:\n        resp = http_client.get(\n            f\"{directory_url}\u002Fsearch\",\n            params={\"q\": query, \"type\": \"service\"},\n            timeout=10,\n        )\n        resp.raise_for_status()\n        listings = resp.json().get(\"results\", [])\n\n        return [{\n            \"source\": \"acp\",\n            \"provider_id\": listing.get(\"agent_id\"),\n            \"service_id\": listing.get(\"service_id\"),\n            \"name\": listing.get(\"name\"),\n            \"price\": listing.get(\"price\"),\n            \"currency\": listing.get(\"currency\", \"USD\"),\n            \"checkout_url\": listing.get(\"checkout_url\"),\n        } for listing in listings]\n    except (http_client.RequestException, ValueError):\n        return []\n```\n\n### The Unified Vendor Index\n\nCombine results from all protocols into a single, ranked vendor index:\n\n```python\nfrom dataclasses import dataclass\nfrom typing import Optional\n\n\n@dataclass\nclass VendorCandidate:\n    source: str             # \"greenhelix\", \"ucp\", \"acp\", \"a2a\"\n    provider_id: str\n    service_id: str\n    name: str\n    price: float\n    currency: str\n    trust_score: Optional[float] = None  # Only available for GreenHelix\n    manifest_url: Optional[str] = None\n    checkout_url: Optional[str] = None\n\n\nclass UnifiedVendorIndex:\n    \"\"\"Aggregates vendor discovery across all protocols.\"\"\"\n\n    def __init__(self, ucp_manifests: list = None, acp_directory: str = None):\n        self.ucp_manifests = ucp_manifests or []\n        self.acp_directory = acp_directory\n\n    def search(self, query: str, category: str = None,\n               min_trust: float = 0.5) -> list[VendorCandidate]:\n        \"\"\"Search all protocols and return unified, ranked results.\"\"\"\n        candidates = []\n\n        # 1. GreenHelix Marketplace (richest data)\n        gh_results = discover_greenhelix_vendors(\n            query, category=category, min_trust_score=min_trust,\n        )\n        for r in gh_results:\n            candidates.append(VendorCandidate(\n                source=\"greenhelix\",\n                provider_id=r[\"provider_id\"],\n                service_id=r[\"service_id\"],\n                name=r.get(\"name\", \"\"),\n                price=float(r.get(\"price\", 0)),\n                currency=r.get(\"currency\", \"USD\"),\n                trust_score=r.get(\"trust_score\"),\n            ))\n\n        # 2. UCP manifests\n        ucp_results = discover_ucp_vendors(self.ucp_manifests, query)\n        for r in ucp_results:\n            candidates.append(VendorCandidate(\n                source=\"ucp\",\n                provider_id=r[\"provider_id\"],\n                service_id=r[\"service_id\"],\n                name=r[\"name\"],\n                price=float(r.get(\"price\", 0)),\n                currency=r.get(\"currency\", \"USD\"),\n                manifest_url=r.get(\"manifest_url\"),\n            ))\n\n        # 3. ACP directory\n        if self.acp_directory:\n            acp_results = discover_acp_vendors(self.acp_directory, query)\n            for r in acp_results:\n                candidates.append(VendorCandidate(\n                    source=\"acp\",\n                    provider_id=r[\"provider_id\"],\n                    service_id=r[\"service_id\"],\n                    name=r[\"name\"],\n                    price=float(r.get(\"price\", 0)),\n                    currency=r.get(\"currency\", \"USD\"),\n                    checkout_url=r.get(\"checkout_url\"),\n                ))\n\n        # Sort: trust-scored vendors first, then by price\n        candidates.sort(key=lambda c: (\n            0 if c.trust_score is not None else 1,\n            -(c.trust_score or 0),\n            c.price,\n        ))\n\n        return candidates\n\n\n# Usage\nindex = UnifiedVendorIndex(\n    ucp_manifests=[\n        \"https:\u002F\u002Fvendor-a.example.com\u002F.well-known\u002Fucp-manifest.json\",\n        \"https:\u002F\u002Fvendor-b.example.com\u002F.well-known\u002Fucp-manifest.json\",\n    ],\n    acp_directory=\"https:\u002F\u002Facp-directory.example.com\u002Fv1\",\n)\n\nvendors = index.search(\"data enrichment\", category=\"data\")\nfor v in vendors[:5]:\n    trust_display = f\" (trust: {v.trust_score:.2f})\" if v.trust_score else \"\"\n    print(f\"  [{v.source}] {v.name} - ${v.price}{trust_display}\")\n```\n\n### Protocol Coverage Checklist\n\nBefore deploying your procurement agent, verify coverage across all relevant discovery channels:\n\n- [ ] GreenHelix Marketplace search configured with appropriate trust threshold\n- [ ] UCP manifest URLs for known vendor networks added to the index\n- [ ] ACP directory endpoint configured (if purchasing from OpenAI ecosystem merchants)\n- [ ] A2A direct discovery configured for peer agent services\n- [ ] Fallback behavior defined when a protocol is unreachable\n- [ ] Deduplication logic handles the same vendor appearing on multiple protocols\n\n> **Key Takeaways**\n>\n> - Vendors advertise across four protocols. An agent that searches only one protocol misses opportunities on the others.\n> - GreenHelix Marketplace provides the richest discovery data because it includes trust scores, reputation, and escrow history alongside listings.\n> - Build a `UnifiedVendorIndex` that aggregates results across all protocols and ranks by trust score first, price second.\n> - Trust-scored vendors should always rank above unscored vendors, regardless of price. The cheapest vendor with no verifiable identity is the most expensive mistake.\n> - See P21 (Agent-Ready Commerce) for the seller's perspective on listing across multiple protocols.\n\n---\n\n## Chapter 4: Vendor Evaluation & Trust Scoring\n\n### Why Price Alone Is Insufficient\n\nThe cheapest vendor in your search results is also the most likely to be fraudulent. This is Akerlof's \"Market for Lemons\" problem applied to agent commerce: without reliable quality signals, low-quality sellers undercut high-quality ones, and buyers cannot tell the difference until after they have paid. The antidote is a structured evaluation framework that scores vendors on dimensions beyond price.\n\nThe four evaluation dimensions are:\n\n1. **Identity verification** -- Is this vendor a real, registered entity?\n2. **Trust score** -- Does the platform's composite trust assessment meet your threshold?\n3. **Reputation history** -- What do other buyers say about this vendor?\n4. **Bid comparison** -- Given equivalent trust, which vendor offers the best value?\n\n### The Vendor Scoring System\n\n```python\nfrom dataclasses import dataclass\nfrom typing import Optional\n\n\n@dataclass\nclass VendorScore:\n    vendor_id: str\n    identity_verified: bool = False\n    identity_confidence: float = 0.0\n    trust_score: float = 0.0\n    reputation_score: float = 0.0\n    trade_count: int = 0\n    dispute_rate: float = 0.0\n    price: float = 0.0\n    composite_score: float = 0.0\n    risk_level: str = \"unknown\"  # low, medium, high, critical\n    disqualified: bool = False\n    disqualification_reason: str = \"\"\n\n\nclass VendorEvaluator:\n    \"\"\"Automated vendor evaluation using GreenHelix Trust, Identity,\n    and Reputation tools.\"\"\"\n\n    # Weights for composite score (must sum to 1.0)\n    WEIGHT_TRUST = 0.30\n    WEIGHT_REPUTATION = 0.25\n    WEIGHT_IDENTITY = 0.20\n    WEIGHT_TRADE_HISTORY = 0.15\n    WEIGHT_PRICE = 0.10\n\n    # Thresholds\n    MIN_TRUST_SCORE = 0.6\n    MIN_TRADE_COUNT = 5\n    MAX_DISPUTE_RATE = 0.10  # 10%\n\n    def evaluate(self, vendor_id: str, price: float,\n                 price_range: tuple = (0, 1000)) -> VendorScore:\n        \"\"\"Run full evaluation pipeline on a single vendor.\"\"\"\n        score = VendorScore(vendor_id=vendor_id, price=price)\n\n        # Step 1: Identity verification\n        try:\n            identity = execute_tool(\"verify_identity\", {\n                \"agent_id\": vendor_id,\n            })\n            score.identity_verified = identity.get(\"verified\", False)\n            score.identity_confidence = identity.get(\"confidence\", 0.0)\n        except Exception:\n            score.identity_verified = False\n            score.identity_confidence = 0.0\n\n        if not score.identity_verified:\n            score.disqualified = True\n            score.disqualification_reason = \"Identity verification failed\"\n            score.risk_level = \"critical\"\n            return score\n\n        # Step 2: Trust score\n        try:\n            trust = execute_tool(\"check_trust_score\", {\n                \"agent_id\": vendor_id,\n            })\n            score.trust_score = trust.get(\"trust_score\", 0.0)\n        except Exception:\n            score.trust_score = 0.0\n\n        if score.trust_score \u003C self.MIN_TRUST_SCORE:\n            score.disqualified = True\n            score.disqualification_reason = (\n                f\"Trust score {score.trust_score:.2f} below \"\n                f\"minimum {self.MIN_TRUST_SCORE}\"\n            )\n            score.risk_level = \"high\"\n            return score\n\n        # Step 3: Reputation and trade history\n        try:\n            reputation = execute_tool(\"get_agent_reputation\", {\n                \"agent_id\": vendor_id,\n            })\n            score.reputation_score = reputation.get(\"reputation_score\", 0.0)\n            score.trade_count = reputation.get(\"total_trades\", 0)\n            score.dispute_rate = reputation.get(\"dispute_rate\", 0.0)\n        except Exception:\n            score.reputation_score = 0.0\n\n        if score.dispute_rate > self.MAX_DISPUTE_RATE:\n            score.disqualified = True\n            score.disqualification_reason = (\n                f\"Dispute rate {score.dispute_rate:.1%} exceeds \"\n                f\"maximum {self.MAX_DISPUTE_RATE:.1%}\"\n            )\n            score.risk_level = \"high\"\n            return score\n\n        # Step 4: Additional KYA check\n        try:\n            kya = execute_tool(\"verify_agent\", {\n                \"agent_id\": vendor_id,\n            })\n            if not kya.get(\"verified\", False):\n                score.risk_level = \"medium\"\n        except Exception:\n            pass\n\n        # Step 5: Compute composite score\n        price_min, price_max = price_range\n        price_normalized = 1.0 - (\n            (price - price_min) \u002F (price_max - price_min)\n            if price_max > price_min else 0.5\n        )\n        price_normalized = max(0, min(1, price_normalized))\n\n        trade_normalized = min(1.0, score.trade_count \u002F 100)\n\n        score.composite_score = (\n            self.WEIGHT_TRUST * score.trust_score\n            + self.WEIGHT_REPUTATION * score.reputation_score\n            + self.WEIGHT_IDENTITY * score.identity_confidence\n            + self.WEIGHT_TRADE_HISTORY * trade_normalized\n            + self.WEIGHT_PRICE * price_normalized\n        )\n\n        # Assign risk level\n        if score.composite_score >= 0.8:\n            score.risk_level = \"low\"\n        elif score.composite_score >= 0.6:\n            score.risk_level = \"medium\"\n        else:\n            score.risk_level = \"high\"\n\n        return score\n\n    def evaluate_batch(self, candidates: list[VendorCandidate]) -> list[VendorScore]:\n        \"\"\"Evaluate and rank a list of vendor candidates.\"\"\"\n        prices = [c.price for c in candidates if c.price > 0]\n        price_range = (min(prices), max(prices)) if prices else (0, 1000)\n\n        scores = []\n        for candidate in candidates:\n            score = self.evaluate(\n                candidate.provider_id,\n                candidate.price,\n                price_range,\n            )\n            scores.append(score)\n\n        # Sort: non-disqualified first, then by composite score descending\n        scores.sort(key=lambda s: (\n            s.disqualified,\n            -s.composite_score,\n        ))\n\n        return scores\n\n\n# Evaluate vendors from the unified index\nevaluator = VendorEvaluator()\nvendors = index.search(\"data enrichment\", category=\"data\")\nscores = evaluator.evaluate_batch(vendors)\n\nprint(f\"\\n{'Vendor':\u003C30} {'Score':>6} {'Risk':\u003C10} {'Price':>8} {'Status':\u003C12}\")\nprint(\"-\" * 76)\nfor s in scores:\n    status = \"DISQUALIFIED\" if s.disqualified else \"ELIGIBLE\"\n    print(f\"{s.vendor_id:\u003C30} {s.composite_score:>6.2f} {s.risk_level:\u003C10} \"\n          f\"${s.price:>7.2f} {status:\u003C12}\")\n    if s.disqualified:\n        print(f\"  Reason: {s.disqualification_reason}\")\n```\n\n### Risk Scoring Decision Matrix\n\n| Composite Score | Risk Level | Recommended Action |\n|---|---|---|\n| 0.80 - 1.00 | Low | Auto-approve up to per-transaction cap |\n| 0.60 - 0.79 | Medium | Auto-approve for small amounts; escalate above $100 |\n| 0.40 - 0.59 | High | Escalate all purchases for human review |\n| 0.00 - 0.39 | Critical | Block. Do not purchase. |\n\n### Automated Bid Comparison\n\nWhen multiple vendors pass the trust threshold, compare them on value:\n\n```python\ndef compare_bids(scores: list[VendorScore],\n                 max_budget: float) -> Optional[VendorScore]:\n    \"\"\"Select the best vendor from evaluated candidates.\n\n    Strategy: Among eligible vendors with 'low' or 'medium' risk,\n    select the one with the highest composite score within budget.\n    Break ties by preferring lower price.\n    \"\"\"\n    eligible = [\n        s for s in scores\n        if not s.disqualified\n        and s.risk_level in (\"low\", \"medium\")\n        and s.price \u003C= max_budget\n    ]\n\n    if not eligible:\n        return None\n\n    # Sort by composite score descending, then price ascending\n    eligible.sort(key=lambda s: (-s.composite_score, s.price))\n    return eligible[0]\n\n\n# Select the best vendor with a $200 budget\nwinner = compare_bids(scores, max_budget=200.00)\nif winner:\n    print(f\"\\nSelected vendor: {winner.vendor_id}\")\n    print(f\"  Composite score: {winner.composite_score:.2f}\")\n    print(f\"  Price: ${winner.price:.2f}\")\n    print(f\"  Risk: {winner.risk_level}\")\nelse:\n    print(\"\\nNo eligible vendor found within budget and risk tolerance.\")\n```\n\n> **Key Takeaways**\n>\n> - Never select a vendor on price alone. The cheapest unverified vendor is the most expensive mistake.\n> - The evaluation pipeline has hard gates (identity, minimum trust, dispute rate) and soft scoring (composite weighted score).\n> - Disqualification is binary -- a vendor that fails identity verification or exceeds the dispute rate threshold is excluded regardless of price.\n> - The composite score weights trust (30%) and reputation (25%) above price (10%). Adjust weights based on your risk tolerance.\n> - See P5 (Trust Verification) for deep dives into claim chain verification and metric auditing.\n\n---\n\n## Chapter 5: Multi-Protocol Purchasing\n\n### Four Rails, One Agent\n\nYour procurement agent has discovered vendors, evaluated them, and selected a winner. Now it needs to pay. The payment rail depends on the vendor's protocol:\n\n| Protocol | Payment Method | Best For | Settlement Time |\n|---|---|---|---|\n| x402 | USDC stablecoin | Micropayments, pay-per-request APIs | Seconds (on-chain) |\n| UCP | Fiat (card\u002Fbank) | Retail, SaaS subscriptions | 1-3 business days |\n| ACP | Stripe (card\u002FSPT) | Merchant checkout, e-commerce | 1-3 business days |\n| A2A (GreenHelix) | Wallet-to-wallet | Agent-to-agent, escrow-protected | Instant (platform) |\n\nThe procurement agent must handle all four. Here is the implementation for each rail.\n\n### Rail 1: x402 Crypto Micropayments\n\nx402 is HTTP-native: the server returns HTTP 402 with a payment requirement, and the client pays in USDC via a facilitator. Ideal for pay-per-request API access.\n\n```python\nimport hashlib\nimport json\n\n\ndef purchase_x402(\n    resource_url: str,\n    wallet_address: str,\n    max_amount_usdc: float,\n) -> dict:\n    \"\"\"Execute an x402 payment for a resource.\n\n    The flow:\n    1. Request the resource -> get 402 with payment requirements\n    2. Verify the price is within budget\n    3. Create payment authorization via GreenHelix\n    4. Submit payment and receive resource\n    \"\"\"\n    # Step 1: Request the resource to get payment requirements\n    resp = http_client.get(resource_url)\n    if resp.status_code != 402:\n        # Resource is free or already paid\n        return {\"status\": \"no_payment_required\", \"data\": resp.json()}\n\n    payment_req = resp.json()\n    amount = float(payment_req.get(\"amount\", 0))\n    currency = payment_req.get(\"currency\", \"USDC\")\n    facilitator = payment_req.get(\"facilitator_url\")\n    recipient = payment_req.get(\"recipient_address\")\n\n    # Step 2: Verify price is within budget\n    if amount > max_amount_usdc:\n        return {\n            \"status\": \"rejected\",\n            \"reason\": f\"Price ${amount} exceeds max ${max_amount_usdc}\",\n        }\n\n    # Step 3: Create payment via GreenHelix\n    intent = execute_tool(\"create_payment_intent\", {\n        \"amount\": str(amount),\n        \"currency\": currency,\n        \"recipient\": recipient,\n        \"payment_method\": \"x402\",\n        \"metadata\": {\n            \"resource_url\": resource_url,\n            \"facilitator\": facilitator,\n            \"protocol\": \"x402\",\n        },\n    })\n\n    # Step 4: Confirm the payment\n    confirmation = execute_tool(\"confirm_payment\", {\n        \"payment_id\": intent[\"payment_id\"],\n        \"wallet_address\": wallet_address,\n    })\n\n    # Step 5: Re-request with payment proof\n    proof_headers = {\n        \"X-Payment-Id\": confirmation[\"payment_id\"],\n        \"X-Payment-Proof\": confirmation.get(\"proof\", \"\"),\n    }\n    final_resp = http_client.get(resource_url, headers=proof_headers)\n\n    return {\n        \"status\": \"completed\",\n        \"payment_id\": confirmation[\"payment_id\"],\n        \"amount\": amount,\n        \"currency\": currency,\n        \"data\": final_resp.json() if final_resp.ok else None,\n    }\n```\n\n### Rail 2: UCP Fiat Retail Purchasing\n\nUCP handles structured product purchasing with fiat payment methods. The flow follows a standard e-commerce checkout pattern.\n\n```python\ndef purchase_ucp(\n    service_id: str,\n    manifest_url: str,\n    quantity: int = 1,\n) -> dict:\n    \"\"\"Execute a UCP purchase using GreenHelix as the payment backend.\n\n    The flow:\n    1. Fetch service details from UCP manifest\n    2. Create a payment intent via GreenHelix\n    3. Authorize the fiat payment\n    4. Confirm delivery\n    \"\"\"\n    # Step 1: Fetch service details\n    manifest = http_client.get(manifest_url, timeout=10).json()\n    service = next(\n        (s for s in manifest.get(\"services\", []) if s[\"id\"] == service_id),\n        None,\n    )\n    if not service:\n        return {\"status\": \"error\", \"reason\": f\"Service {service_id} not found\"}\n\n    total = float(service[\"price\"]) * quantity\n\n    # Step 2: Create payment intent\n    intent = execute_tool(\"create_payment_intent\", {\n        \"amount\": str(total),\n        \"currency\": service.get(\"currency\", \"USD\"),\n        \"recipient\": manifest.get(\"provider_id\"),\n        \"payment_method\": \"fiat\",\n        \"metadata\": {\n            \"protocol\": \"ucp\",\n            \"service_id\": service_id,\n            \"quantity\": quantity,\n            \"manifest_url\": manifest_url,\n        },\n    })\n\n    # Step 3: Confirm the payment\n    confirmation = execute_tool(\"confirm_payment\", {\n        \"payment_id\": intent[\"payment_id\"],\n    })\n\n    return {\n        \"status\": \"completed\",\n        \"payment_id\": confirmation[\"payment_id\"],\n        \"amount\": total,\n        \"currency\": service.get(\"currency\", \"USD\"),\n        \"service\": service[\"name\"],\n        \"protocol\": \"ucp\",\n    }\n```\n\n### Rail 3: ACP Agent-Native Checkout\n\nACP uses Shared Payment Tokens (SPTs) for delegated spending through Stripe.\n\n```python\ndef purchase_acp(\n    service_id: str,\n    checkout_url: str,\n    spt_token: str,\n) -> dict:\n    \"\"\"Execute an ACP purchase using a Shared Payment Token.\n\n    The flow:\n    1. Initiate checkout at the ACP merchant endpoint\n    2. Authorize via SPT\n    3. Record the transaction in GreenHelix for tracking\n    \"\"\"\n    # Step 1: Initiate checkout\n    checkout_resp = http_client.post(\n        checkout_url,\n        json={\n            \"service_id\": service_id,\n            \"payment_method\": \"spt\",\n            \"spt_token\": spt_token,\n        },\n        timeout=15,\n    )\n    checkout_resp.raise_for_status()\n    checkout_data = checkout_resp.json()\n\n    # Step 2: Record in GreenHelix ledger for unified tracking\n    execute_tool(\"record_transaction\", {\n        \"agent_id\": buyer.agent_id,\n        \"type\": \"purchase\",\n        \"amount\": str(checkout_data.get(\"amount\", 0)),\n        \"currency\": checkout_data.get(\"currency\", \"USD\"),\n        \"counterparty\": checkout_data.get(\"merchant_id\", \"\"),\n        \"metadata\": {\n            \"protocol\": \"acp\",\n            \"service_id\": service_id,\n            \"external_payment_id\": checkout_data.get(\"payment_id\"),\n            \"checkout_url\": checkout_url,\n        },\n    })\n\n    return {\n        \"status\": \"completed\",\n        \"payment_id\": checkout_data.get(\"payment_id\"),\n        \"amount\": checkout_data.get(\"amount\"),\n        \"protocol\": \"acp\",\n    }\n```\n\n### Rail 4: A2A Direct Commerce via GreenHelix\n\nFor agent-to-agent purchases, the commerce layer provides the full stack: payment, escrow, and delivery verification.\n\n```python\ndef purchase_a2a(\n    vendor_id: str,\n    service_id: str,\n    amount: float,\n    use_escrow: bool = True,\n) -> dict:\n    \"\"\"Execute an A2A purchase via GreenHelix with optional escrow.\n\n    This is the recommended rail for agent-to-agent transactions\n    because it includes built-in escrow, disputes, and delivery\n    verification.\n    \"\"\"\n    if use_escrow:\n        # Create escrow-protected purchase\n        escrow = execute_tool(\"create_escrow\", {\n            \"payer_id\": buyer.agent_id,\n            \"payee_id\": vendor_id,\n            \"amount\": str(amount),\n            \"currency\": \"USD\",\n            \"conditions\": {\n                \"service_id\": service_id,\n                \"delivery_deadline_hours\": 24,\n                \"verification_method\": \"automated\",\n            },\n        })\n\n        return {\n            \"status\": \"escrowed\",\n            \"escrow_id\": escrow[\"escrow_id\"],\n            \"amount\": amount,\n            \"vendor_id\": vendor_id,\n            \"protocol\": \"a2a\",\n            \"next_step\": \"await_delivery_then_verify\",\n        }\n    else:\n        # Direct payment (no escrow)\n        intent = execute_tool(\"create_payment_intent\", {\n            \"amount\": str(amount),\n            \"currency\": \"USD\",\n            \"recipient\": vendor_id,\n            \"payment_method\": \"wallet\",\n            \"metadata\": {\n                \"protocol\": \"a2a\",\n                \"service_id\": service_id,\n            },\n        })\n\n        confirmation = execute_tool(\"confirm_payment\", {\n            \"payment_id\": intent[\"payment_id\"],\n        })\n\n        return {\n            \"status\": \"completed\",\n            \"payment_id\": confirmation[\"payment_id\"],\n            \"amount\": amount,\n            \"protocol\": \"a2a\",\n        }\n```\n\n### The Payment Router\n\nTie all four rails together with a router that selects the appropriate rail based on the vendor's protocol:\n\n```python\ndef route_purchase(vendor: VendorCandidate, amount: float,\n                   use_escrow: bool = True, **kwargs) -> dict:\n    \"\"\"Route a purchase to the appropriate payment rail.\"\"\"\n    if vendor.source == \"greenhelix\":\n        return purchase_a2a(\n            vendor.provider_id, vendor.service_id, amount, use_escrow,\n        )\n    elif vendor.source == \"ucp\":\n        return purchase_ucp(\n            vendor.service_id, vendor.manifest_url,\n            quantity=kwargs.get(\"quantity\", 1),\n        )\n    elif vendor.source == \"acp\":\n        return purchase_acp(\n            vendor.service_id, vendor.checkout_url,\n            spt_token=kwargs.get(\"spt_token\", \"\"),\n        )\n    else:\n        # Default to GreenHelix A2A for unknown protocols\n        return purchase_a2a(\n            vendor.provider_id, vendor.service_id, amount, use_escrow,\n        )\n```\n\n> **Key Takeaways**\n>\n> - Four payment rails serve different use cases: x402 for crypto micropayments, UCP for fiat, ACP for Stripe-backed checkout, A2A for agent-to-agent.\n> - Always use escrow for A2A purchases above your trust threshold. The cost of escrow is negligible compared to the cost of unrecoverable loss.\n> - Record all purchases in the GreenHelix ledger regardless of which rail was used. Unified tracking is essential for reconciliation.\n> - The payment router abstracts rail selection from the procurement logic. The agent does not need to know which protocol a vendor uses.\n> - See P19 (Payment Rails) for deep dives into x402 settlement, MPP hybrid routing, and multi-rail architecture patterns.\n\n---\n\n## Chapter 6: Escrow, Disputes & Purchase Protection\n\n### Why Escrow Is Non-Negotiable for Agent Commerce\n\nWhen a human buys a service and it fails to deliver, the human can call support, file a chargeback, leave a scathing review, or escalate to a regulatory body. An agent has none of these options unless they are programmed in advance. Escrow is the mechanism that makes agent purchasing safe: the buyer's funds are held by a neutral third party (GreenHelix) until the seller delivers and the buyer verifies. If delivery fails, the buyer gets their money back automatically.\n\nFor agent-to-agent commerce, escrow should be the default for any transaction above a trivial amount. The threshold varies by use case, but a reasonable starting point is: always use escrow for transactions above $10.\n\n### The Protected Purchase Flow\n\n```python\nimport time\nfrom enum import Enum\n\n\nclass DeliveryStatus(Enum):\n    PENDING = \"pending\"\n    DELIVERED = \"delivered\"\n    FAILED = \"failed\"\n    DISPUTED = \"disputed\"\n\n\nclass ProtectedPurchaseManager:\n    \"\"\"Manages the full lifecycle of an escrow-protected purchase:\n    creation, delivery verification, release, and dispute handling.\"\"\"\n\n    def __init__(self, buyer_id: str):\n        self.buyer_id = buyer_id\n\n    def create_protected_purchase(\n        self,\n        vendor_id: str,\n        service_id: str,\n        amount: float,\n        delivery_deadline_hours: int = 24,\n        verification_criteria: dict = None,\n    ) -> dict:\n        \"\"\"Create an escrow-protected purchase.\"\"\"\n        escrow = execute_tool(\"create_escrow\", {\n            \"payer_id\": self.buyer_id,\n            \"payee_id\": vendor_id,\n            \"amount\": str(amount),\n            \"currency\": \"USD\",\n            \"conditions\": {\n                \"service_id\": service_id,\n                \"delivery_deadline_hours\": delivery_deadline_hours,\n                \"verification_method\": \"automated\",\n                \"criteria\": verification_criteria or {},\n            },\n        })\n\n        return {\n            \"escrow_id\": escrow[\"escrow_id\"],\n            \"status\": \"escrowed\",\n            \"amount\": amount,\n            \"vendor_id\": vendor_id,\n            \"deadline\": delivery_deadline_hours,\n        }\n\n    def verify_delivery(\n        self,\n        escrow_id: str,\n        delivered_data: dict,\n        acceptance_tests: list = None,\n    ) -> DeliveryStatus:\n        \"\"\"Run automated verification on delivered goods\u002Fservices.\n\n        acceptance_tests is a list of callables that take delivered_data\n        and return (passed: bool, reason: str).\n        \"\"\"\n        if not delivered_data:\n            return DeliveryStatus.FAILED\n\n        if acceptance_tests:\n            failures = []\n            for test_fn in acceptance_tests:\n                passed, reason = test_fn(delivered_data)\n                if not passed:\n                    failures.append(reason)\n\n            if failures:\n                # Auto-dispute on verification failure\n                self.file_dispute(\n                    escrow_id,\n                    reason=f\"Delivery failed {len(failures)} acceptance \"\n                           f\"test(s): {'; '.join(failures)}\",\n                )\n                return DeliveryStatus.DISPUTED\n\n        return DeliveryStatus.DELIVERED\n\n    def release_escrow(self, escrow_id: str) -> dict:\n        \"\"\"Release funds to the vendor after successful verification.\"\"\"\n        result = execute_tool(\"release_escrow\", {\n            \"escrow_id\": escrow_id,\n            \"action\": \"release\",\n        })\n        return {\n            \"escrow_id\": escrow_id,\n            \"status\": \"released\",\n            \"released_to\": result.get(\"payee_id\"),\n            \"amount\": result.get(\"amount\"),\n        }\n\n    def file_dispute(self, escrow_id: str, reason: str,\n                     evidence: dict = None) -> dict:\n        \"\"\"File a dispute against the vendor.\"\"\"\n        dispute = execute_tool(\"create_dispute\", {\n            \"escrow_id\": escrow_id,\n            \"reason\": reason,\n            \"evidence\": evidence or {},\n            \"requested_resolution\": \"full_refund\",\n        })\n        return {\n            \"dispute_id\": dispute[\"dispute_id\"],\n            \"escrow_id\": escrow_id,\n            \"status\": \"dispute_filed\",\n            \"reason\": reason,\n        }\n\n    def respond_to_dispute(self, dispute_id: str, response: str,\n                           evidence: dict = None) -> dict:\n        \"\"\"Respond to a dispute (if this agent is the vendor side).\"\"\"\n        result = execute_tool(\"respond_to_dispute\", {\n            \"dispute_id\": dispute_id,\n            \"response\": response,\n            \"evidence\": evidence or {},\n        })\n        return {\n            \"dispute_id\": dispute_id,\n            \"status\": \"response_submitted\",\n            \"resolution\": result.get(\"resolution\"),\n        }\n\n    def execute_full_purchase(\n        self,\n        vendor_id: str,\n        service_id: str,\n        amount: float,\n        delivery_callback: callable,\n        acceptance_tests: list = None,\n        delivery_deadline_hours: int = 24,\n    ) -> dict:\n        \"\"\"Execute the complete protected purchase lifecycle.\n\n        delivery_callback: a callable that triggers vendor fulfillment\n        and returns the delivered data.\n        \"\"\"\n        # Step 1: Create escrow\n        purchase = self.create_protected_purchase(\n            vendor_id, service_id, amount,\n            delivery_deadline_hours=delivery_deadline_hours,\n        )\n        escrow_id = purchase[\"escrow_id\"]\n\n        # Step 2: Trigger delivery\n        try:\n            delivered_data = delivery_callback(escrow_id)\n        except Exception as e:\n            self.file_dispute(escrow_id, reason=f\"Delivery failed: {str(e)}\")\n            return {\n                \"escrow_id\": escrow_id,\n                \"status\": \"disputed\",\n                \"reason\": f\"Delivery exception: {str(e)}\",\n            }\n\n        # Step 3: Verify delivery\n        status = self.verify_delivery(\n            escrow_id, delivered_data, acceptance_tests,\n        )\n\n        # Step 4: Release or dispute\n        if status == DeliveryStatus.DELIVERED:\n            release = self.release_escrow(escrow_id)\n            return {\n                \"escrow_id\": escrow_id,\n                \"status\": \"completed\",\n                \"amount_released\": release[\"amount\"],\n            }\n        else:\n            return {\n                \"escrow_id\": escrow_id,\n                \"status\": status.value,\n                \"reason\": \"Automated verification failed\",\n            }\n\n\n# Usage: protected purchase with acceptance tests\nppm = ProtectedPurchaseManager(buyer_id=\"procurement-agent-01\")\n\n# Define acceptance tests for a data enrichment purchase\ndef test_record_count(data):\n    count = len(data.get(\"records\", []))\n    expected = 500_000\n    if count \u003C expected * 0.95:  # Allow 5% tolerance\n        return False, f\"Expected ~{expected} records, got {count}\"\n    return True, \"Record count OK\"\n\ndef test_data_completeness(data):\n    sample = data.get(\"records\", [])[:100]\n    incomplete = sum(1 for r in sample if not r.get(\"email\"))\n    if incomplete > 10:  # More than 10% incomplete\n        return False, f\"{incomplete}% of sample missing email field\"\n    return True, \"Data completeness OK\"\n\n# This would be your vendor's delivery mechanism\ndef trigger_vendor_delivery(escrow_id: str) -> dict:\n    \"\"\"Placeholder: in production, this calls the vendor's API.\"\"\"\n    return {\"records\": [{\"email\": \"test@example.com\"}] * 500_000}\n\nresult = ppm.execute_full_purchase(\n    vendor_id=\"vendor-data-enrichment-01\",\n    service_id=\"contact-enrichment-500k\",\n    amount=150.00,\n    delivery_callback=trigger_vendor_delivery,\n    acceptance_tests=[test_record_count, test_data_completeness],\n    delivery_deadline_hours=12,\n)\nprint(f\"Purchase result: {result['status']}\")\n```\n\n### Dispute Resolution Decision Tree\n\n```\nDelivery received?\n├── NO --> Wait until deadline\n│          └── Deadline passed? --> Auto-dispute (non-delivery)\n├── YES --> Run acceptance tests\n│          ├── ALL PASS --> Release escrow\n│          ├── SOME FAIL --> File dispute with evidence\n│          └── CRITICAL FAIL --> File dispute, request full refund\n```\n\n### Escrow Configuration Checklist\n\n- [ ] Set delivery deadlines appropriate to the service type (minutes for APIs, hours for data, days for custom work)\n- [ ] Define acceptance tests before creating the escrow, not after\n- [ ] Include specific, measurable criteria in escrow conditions (not \"good quality\" but \"95%+ record completeness\")\n- [ ] Configure automatic dispute filing for deadline expiration\n- [ ] Set up webhook notifications for escrow state changes\n- [ ] Record all escrow outcomes in the ledger for vendor reputation tracking\n\n> **Key Takeaways**\n>\n> - Escrow should be the default for any agent-to-agent transaction above $10. The cost of escrow is negligible; the cost of unrecoverable loss is not.\n> - Automated acceptance tests are the agent equivalent of \"inspecting the goods before signing.\" Define them before the purchase, not after.\n> - The `ProtectedPurchaseManager` handles the full lifecycle: escrow creation, delivery callback, automated verification, release or dispute.\n> - Dispute evidence should be structured and machine-readable. \"The data was bad\" is not evidence. \"47% of records missing email field, expected less than 5%\" is evidence.\n> - See P14 (Negotiation Strategies) for techniques to negotiate escrow terms, delivery deadlines, and SLA guarantees before the purchase.\n\n---\n\n## Chapter 7: Cost Reconciliation & FinOps Integration\n\n### The Reconciliation Problem\n\nYour procurement agent has executed purchases across four protocols, some through escrow, some direct. The transactions are scattered across GreenHelix ledger entries, Stripe payment records, x402 on-chain settlements, and UCP order confirmations. The CFO asks: \"How much did our AI agents spend last month, on what, and was it worth it?\"\n\nWithout a unified reconciliation system, you cannot answer that question. Cost reconciliation for autonomous procurement requires three capabilities:\n\n1. **Unified recording** -- Every purchase, regardless of protocol, is recorded in a single ledger.\n2. **Cost attribution** -- Every purchase is tagged with the requesting agent, workflow, and cost category.\n3. **Budget vs. actual analysis** -- Planned budgets are compared to actual spend, with anomaly detection for deviations.\n\n### Recording Purchases to the Ledger\n\nEvery purchase -- whether it went through x402, UCP, ACP, or A2A -- must be recorded in the GreenHelix Ledger for unified tracking:\n\n```python\nfrom datetime import datetime\n\n\nclass ProcurementLedger:\n    \"\"\"Records and queries all procurement transactions\n    in the GreenHelix Ledger.\"\"\"\n\n    def __init__(self, agent_id: str):\n        self.agent_id = agent_id\n\n    def record_purchase(\n        self,\n        vendor_id: str,\n        amount: float,\n        currency: str,\n        protocol: str,\n        service_id: str,\n        category: str,\n        workflow_id: str = \"\",\n        external_payment_id: str = \"\",\n        metadata: dict = None,\n    ) -> dict:\n        \"\"\"Record a completed purchase in the ledger.\"\"\"\n        tx = execute_tool(\"record_transaction\", {\n            \"agent_id\": self.agent_id,\n            \"type\": \"purchase\",\n            \"amount\": str(amount),\n            \"currency\": currency,\n            \"counterparty\": vendor_id,\n            \"metadata\": {\n                \"protocol\": protocol,\n                \"service_id\": service_id,\n                \"category\": category,\n                \"workflow_id\": workflow_id,\n                \"external_payment_id\": external_payment_id,\n                \"recorded_at\": datetime.utcnow().isoformat(),\n                **(metadata or {}),\n            },\n        })\n        return tx\n\n    def get_spend_by_category(self, period: str = \"current_month\") -> dict:\n        \"\"\"Get spend broken down by category.\"\"\"\n        history = execute_tool(\"get_transaction_history\", {\n            \"agent_id\": self.agent_id,\n            \"period\": period,\n            \"type\": \"purchase\",\n        })\n\n        by_category = {}\n        for tx in history.get(\"transactions\", []):\n            cat = tx.get(\"metadata\", {}).get(\"category\", \"uncategorized\")\n            by_category.setdefault(cat, {\"count\": 0, \"total\": 0.0})\n            by_category[cat][\"count\"] += 1\n            by_category[cat][\"total\"] += float(tx.get(\"amount\", 0))\n\n        return by_category\n\n    def get_spend_by_protocol(self, period: str = \"current_month\") -> dict:\n        \"\"\"Get spend broken down by payment protocol.\"\"\"\n        history = execute_tool(\"get_transaction_history\", {\n            \"agent_id\": self.agent_id,\n            \"period\": period,\n            \"type\": \"purchase\",\n        })\n\n        by_protocol = {}\n        for tx in history.get(\"transactions\", []):\n            proto = tx.get(\"metadata\", {}).get(\"protocol\", \"unknown\")\n            by_protocol.setdefault(proto, {\"count\": 0, \"total\": 0.0})\n            by_protocol[proto][\"count\"] += 1\n            by_protocol[proto][\"total\"] += float(tx.get(\"amount\", 0))\n\n        return by_protocol\n\n    def get_spend_by_vendor(self, period: str = \"current_month\") -> dict:\n        \"\"\"Get spend broken down by vendor.\"\"\"\n        history = execute_tool(\"get_transaction_history\", {\n            \"agent_id\": self.agent_id,\n            \"period\": period,\n            \"type\": \"purchase\",\n        })\n\n        by_vendor = {}\n        for tx in history.get(\"transactions\", []):\n            vendor = tx.get(\"counterparty\", \"unknown\")\n            by_vendor.setdefault(vendor, {\"count\": 0, \"total\": 0.0})\n            by_vendor[vendor][\"count\"] += 1\n            by_vendor[vendor][\"total\"] += float(tx.get(\"amount\", 0))\n\n        return by_vendor\n\n\nledger = ProcurementLedger(agent_id=\"procurement-agent-01\")\n```\n\n### Budget vs. Actual Dashboard\n\n```python\nclass BudgetDashboard:\n    \"\"\"Compares planned budgets against actual procurement spend.\"\"\"\n\n    def __init__(self, agent_id: str, budgets: dict):\n        \"\"\"\n        budgets: dict mapping category -> monthly budget amount.\n        Example: {\"data\": 500, \"compute\": 2000, \"apis\": 300}\n        \"\"\"\n        self.agent_id = agent_id\n        self.budgets = budgets\n        self.ledger = ProcurementLedger(agent_id)\n\n    def generate_report(self) -> dict:\n        \"\"\"Generate a budget vs. actual report for the current month.\"\"\"\n        actuals = self.ledger.get_spend_by_category(\"current_month\")\n\n        # Get platform-level usage analytics\n        usage = execute_tool(\"get_usage_analytics\", {\n            \"agent_id\": self.agent_id,\n            \"period\": \"current_month\",\n        })\n\n        # Get revenue metrics for ROI calculation\n        revenue = execute_tool(\"get_revenue_metrics\", {\n            \"agent_id\": self.agent_id,\n            \"period\": \"current_month\",\n        })\n\n        report = {\n            \"period\": \"current_month\",\n            \"categories\": {},\n            \"total_budget\": sum(self.budgets.values()),\n            \"total_actual\": 0,\n            \"total_revenue\": revenue.get(\"total_revenue\", 0),\n            \"anomalies\": [],\n        }\n\n        for category, budget in self.budgets.items():\n            actual = actuals.get(category, {}).get(\"total\", 0)\n            tx_count = actuals.get(category, {}).get(\"count\", 0)\n            variance = actual - budget\n            variance_pct = (variance \u002F budget * 100) if budget > 0 else 0\n\n            report[\"categories\"][category] = {\n                \"budget\": budget,\n                \"actual\": actual,\n                \"variance\": variance,\n                \"variance_pct\": variance_pct,\n                \"transaction_count\": tx_count,\n                \"status\": (\n                    \"under\" if variance \u003C 0\n                    else \"on_track\" if variance_pct \u003C 10\n                    else \"over\"\n                ),\n            }\n            report[\"total_actual\"] += actual\n\n            # Anomaly detection: flag categories over 120% of budget\n            if variance_pct > 20:\n                report[\"anomalies\"].append({\n                    \"category\": category,\n                    \"severity\": \"high\" if variance_pct > 50 else \"medium\",\n                    \"message\": (\n                        f\"{category} spend ${actual:.2f} is \"\n                        f\"{variance_pct:.0f}% over budget ${budget:.2f}\"\n                    ),\n                })\n\n        return report\n\n    def print_report(self):\n        \"\"\"Print a formatted budget vs. actual report.\"\"\"\n        report = self.generate_report()\n\n        print(f\"\\n{'='*70}\")\n        print(f\"  PROCUREMENT BUDGET vs. ACTUAL — {report['period']}\")\n        print(f\"{'='*70}\")\n        print(f\"\\n{'Category':\u003C20} {'Budget':>10} {'Actual':>10} \"\n              f\"{'Variance':>10} {'Status':\u003C10}\")\n        print(\"-\" * 70)\n\n        for cat, data in report[\"categories\"].items():\n            status_marker = (\n                \"OK\" if data[\"status\"] == \"under\"\n                else \"WATCH\" if data[\"status\"] == \"on_track\"\n                else \"OVER\"\n            )\n            print(f\"{cat:\u003C20} ${data['budget']:>9.2f} ${data['actual']:>9.2f} \"\n                  f\"${data['variance']:>+9.2f} {status_marker:\u003C10}\")\n\n        print(\"-\" * 70)\n        print(f\"{'TOTAL':\u003C20} ${report['total_budget']:>9.2f} \"\n              f\"${report['total_actual']:>9.2f} \"\n              f\"${report['total_actual'] - report['total_budget']:>+9.2f}\")\n\n        if report[\"anomalies\"]:\n            print(f\"\\n  ANOMALIES:\")\n            for a in report[\"anomalies\"]:\n                print(f\"  [{a['severity'].upper()}] {a['message']}\")\n\n        roi = (\n            (report[\"total_revenue\"] - report[\"total_actual\"])\n            \u002F report[\"total_actual\"] * 100\n            if report[\"total_actual\"] > 0 else 0\n        )\n        print(f\"\\n  Revenue: ${report['total_revenue']:.2f}\")\n        print(f\"  Procurement ROI: {roi:+.1f}%\")\n        print(f\"{'='*70}\\n\")\n\n\n# Usage\ndashboard = BudgetDashboard(\n    agent_id=\"procurement-agent-01\",\n    budgets={\n        \"data\": 500.00,\n        \"compute\": 2000.00,\n        \"apis\": 300.00,\n        \"services\": 1000.00,\n    },\n)\ndashboard.print_report()\n```\n\n### Anomaly Detection for Runaway Spend\n\n```python\ndef detect_spending_anomalies(agent_id: str,\n                               lookback_days: int = 7,\n                               z_score_threshold: float = 2.0) -> list:\n    \"\"\"Detect anomalous spending patterns by comparing recent\n    spend to historical averages.\n\n    Uses a simple z-score approach: if today's spend is more than\n    z_score_threshold standard deviations above the mean of the\n    lookback period, flag it.\n    \"\"\"\n    import statistics\n\n    history = execute_tool(\"get_transaction_history\", {\n        \"agent_id\": agent_id,\n        \"period\": f\"last_{lookback_days}_days\",\n        \"type\": \"purchase\",\n    })\n\n    # Group by day\n    daily_totals = {}\n    for tx in history.get(\"transactions\", []):\n        day = tx.get(\"metadata\", {}).get(\"recorded_at\", \"\")[:10]\n        daily_totals.setdefault(day, 0)\n        daily_totals[day] += float(tx.get(\"amount\", 0))\n\n    if len(daily_totals) \u003C 3:\n        return []  # Not enough data for anomaly detection\n\n    amounts = list(daily_totals.values())\n    mean = statistics.mean(amounts)\n    stdev = statistics.stdev(amounts) if len(amounts) > 1 else 0\n\n    anomalies = []\n    for day, total in daily_totals.items():\n        if stdev > 0:\n            z = (total - mean) \u002F stdev\n            if z > z_score_threshold:\n                anomalies.append({\n                    \"date\": day,\n                    \"spend\": total,\n                    \"mean\": mean,\n                    \"z_score\": z,\n                    \"severity\": \"critical\" if z > 3 else \"warning\",\n                    \"message\": (\n                        f\"Spend on {day} (${total:.2f}) is \"\n                        f\"{z:.1f} std devs above mean (${mean:.2f})\"\n                    ),\n                })\n\n    return anomalies\n```\n\n> **Key Takeaways**\n>\n> - Record every purchase in the GreenHelix Ledger regardless of which payment rail was used. Unified tracking is the foundation of reconciliation.\n> - Tag every transaction with category, workflow, and protocol. Without attribution, you cannot answer \"who spent what on which.\"\n> - Budget vs. actual dashboards should flag anomalies automatically. A 20% budget overrun in a category is a warning; 50% is an alert.\n> - Anomaly detection using z-scores catches spending spikes that per-transaction caps miss. A sudden doubling of daily spend is suspicious even if every individual transaction is small.\n> - See P6 (FinOps) for advanced patterns: volume discount optimization, fleet-wide dashboards, and API key isolation as a cost containment boundary.\n\n---\n\n## Chapter 8: Compliance & Audit Trails\n\n### The Regulatory Landscape for Autonomous Purchasing\n\nAutonomous agents that spend money operate in a regulatory gray area that is rapidly becoming black-letter law. Three regulatory frameworks are converging on agent procurement in 2026:\n\n**EU AI Act (August 2, 2026 deadline).** Article 14 requires \"human oversight\" for high-risk AI systems. Autonomous purchasing agents that make financial decisions likely qualify. Documentation requirements include: system purpose, risk assessment, human oversight mechanisms, decision logging, and audit trails. Non-compliance penalties: up to 35 million EUR or 7% of global revenue.\n\n**GDPR.** If your procurement agent processes personal data (contact enrichment, identity verification, behavioral analytics), GDPR's data processing requirements apply. Every vendor that receives personal data must have a Data Processing Agreement (DPA). Your agent's procurement decisions involving personal data must be logged and explainable.\n\n**Financial Services Regulations.** Agents that move money may trigger money transmission, anti-money laundering (AML), or know-your-customer (KYC) requirements depending on jurisdiction and transaction volume.\n\n### Building the Audit Trail\n\nGreenHelix's claim chain infrastructure provides cryptographic audit trails that satisfy EU AI Act documentation requirements:\n\n```python\nfrom datetime import datetime, timezone\n\n\nclass ProcurementAuditor:\n    \"\"\"Builds and queries cryptographic audit trails for\n    autonomous procurement decisions.\"\"\"\n\n    def __init__(self, agent_id: str):\n        self.agent_id = agent_id\n\n    def log_procurement_decision(\n        self,\n        decision_type: str,\n        vendor_id: str,\n        amount: float,\n        decision: str,\n        reasoning: str,\n        policy_checks: list,\n        human_oversight: str = \"none\",\n    ) -> dict:\n        \"\"\"Log a procurement decision with full context for audit.\"\"\"\n        metrics = execute_tool(\"submit_metrics\", {\n            \"agent_id\": self.agent_id,\n            \"metrics\": {\n                \"decision_type\": decision_type,\n                \"vendor_id\": vendor_id,\n                \"amount\": str(amount),\n                \"decision\": decision,\n                \"reasoning\": reasoning,\n                \"policy_checks_passed\": [\n                    c for c in policy_checks if c[\"passed\"]\n                ],\n                \"policy_checks_failed\": [\n                    c for c in policy_checks if not c[\"passed\"]\n                ],\n                \"human_oversight_level\": human_oversight,\n                \"timestamp\": datetime.now(timezone.utc).isoformat(),\n            },\n        })\n        return metrics\n\n    def build_audit_chain(self) -> dict:\n        \"\"\"Build a Merkle claim chain over all procurement decisions.\n\n        This creates a tamper-evident record: if any decision log\n        is modified after the chain is built, the root hash changes.\n        \"\"\"\n        chain = execute_tool(\"build_claim_chain\", {\n            \"agent_id\": self.agent_id,\n        })\n        return {\n            \"chain_id\": chain.get(\"chain_id\"),\n            \"root_hash\": chain.get(\"root_hash\"),\n            \"claim_count\": chain.get(\"claim_count\"),\n            \"built_at\": datetime.now(timezone.utc).isoformat(),\n        }\n\n    def get_audit_history(self, since: str = None) -> list:\n        \"\"\"Retrieve all claim chains for audit review.\"\"\"\n        chains = execute_tool(\"get_claim_chains\", {\n            \"agent_id\": self.agent_id,\n        })\n        return chains.get(\"chains\", [])\n\n    def verify_chain_integrity(self, chain_id: str) -> dict:\n        \"\"\"Verify that a claim chain has not been tampered with.\"\"\"\n        chains = execute_tool(\"get_claim_chains\", {\n            \"agent_id\": self.agent_id,\n        })\n        target = next(\n            (c for c in chains.get(\"chains\", []) if c[\"chain_id\"] == chain_id),\n            None,\n        )\n        if not target:\n            return {\"verified\": False, \"reason\": \"Chain not found\"}\n\n        return {\n            \"verified\": True,\n            \"chain_id\": chain_id,\n            \"root_hash\": target.get(\"root_hash\"),\n            \"claim_count\": target.get(\"claim_count\"),\n        }\n\n\n# Usage: log a procurement decision and build a claim chain\nauditor = ProcurementAuditor(agent_id=\"procurement-agent-01\")\n\n# Log the decision\nauditor.log_procurement_decision(\n    decision_type=\"vendor_selection\",\n    vendor_id=\"vendor-data-enrichment-01\",\n    amount=150.00,\n    decision=\"approved\",\n    reasoning=\"Highest composite score (0.87) among 4 eligible vendors. \"\n              \"Trust score 0.92, reputation 0.85, 147 completed trades, \"\n              \"1.2% dispute rate. Price within budget allocation.\",\n    policy_checks=[\n        {\"check\": \"per_transaction_cap\", \"passed\": True,\n         \"detail\": \"$150 \u003C $500 cap\"},\n        {\"check\": \"daily_budget\", \"passed\": True,\n         \"detail\": \"$150 + $320 existing = $470 \u003C $2000 limit\"},\n        {\"check\": \"vendor_whitelist\", \"passed\": True,\n         \"detail\": \"vendor-data-enrichment-01 in whitelist\"},\n        {\"check\": \"frequency_limit\", \"passed\": True,\n         \"detail\": \"3 purchases this hour \u003C 100 limit\"},\n        {\"check\": \"trust_threshold\", \"passed\": True,\n         \"detail\": \"trust 0.92 >= 0.60 minimum\"},\n    ],\n    human_oversight=\"async_notification\",\n)\n\n# Build the claim chain (do this periodically, e.g., hourly or daily)\nchain = auditor.build_audit_chain()\nprint(f\"Audit chain built: {chain['chain_id']}\")\nprint(f\"Root hash: {chain['root_hash']}\")\nprint(f\"Claims: {chain['claim_count']}\")\n```\n\n### EU AI Act Compliance Report Generator\n\nArticle 14 of the EU AI Act requires documentation of human oversight mechanisms. Here is a generator that produces a compliance-ready report from your audit trail:\n\n```python\nclass ComplianceReportGenerator:\n    \"\"\"Generates EU AI Act Article 14 compliance reports\n    from GreenHelix audit trails.\"\"\"\n\n    def __init__(self, agent_id: str, system_name: str,\n                 organization: str):\n        self.agent_id = agent_id\n        self.system_name = system_name\n        self.organization = organization\n        self.auditor = ProcurementAuditor(agent_id)\n        self.ledger = ProcurementLedger(agent_id)\n\n    def generate(self, period: str = \"current_month\") -> dict:\n        \"\"\"Generate a structured compliance report.\"\"\"\n\n        # Gather data\n        chains = self.auditor.get_audit_history()\n        spend_by_category = self.ledger.get_spend_by_category(period)\n        spend_by_vendor = self.ledger.get_spend_by_vendor(period)\n\n        usage = execute_tool(\"get_usage_analytics\", {\n            \"agent_id\": self.agent_id,\n            \"period\": period,\n        })\n\n        total_spend = sum(\n            cat[\"total\"] for cat in spend_by_category.values()\n        )\n        total_transactions = sum(\n            cat[\"count\"] for cat in spend_by_category.values()\n        )\n\n        report = {\n            \"report_type\": \"eu_ai_act_article_14_compliance\",\n            \"generated_at\": datetime.now(timezone.utc).isoformat(),\n            \"reporting_period\": period,\n            \"organization\": self.organization,\n            \"system_identification\": {\n                \"system_name\": self.system_name,\n                \"agent_id\": self.agent_id,\n                \"system_purpose\": (\n                    \"Autonomous procurement agent for discovering, \"\n                    \"evaluating, and purchasing digital services and \"\n                    \"data products on behalf of the organization.\"\n                ),\n                \"risk_classification\": \"high_risk\",\n                \"risk_justification\": (\n                    \"System makes autonomous financial decisions \"\n                    \"that commit organizational funds.\"\n                ),\n            },\n            \"human_oversight_mechanisms\": {\n                \"spending_policy_engine\": {\n                    \"description\": (\n                        \"Five-layer policy engine evaluates every \"\n                        \"purchase before execution.\"\n                    ),\n                    \"layers\": [\n                        \"Per-transaction caps\",\n                        \"Daily\u002Fweekly budget limits\",\n                        \"Vendor whitelists\",\n                        \"Frequency rate limits\",\n                        \"Human-in-the-loop escalation\",\n                    ],\n                },\n                \"escalation_threshold\": (\n                    \"Purchases above configured threshold are \"\n                    \"queued for human approval before execution.\"\n                ),\n                \"kill_switch\": (\n                    \"Budget hard stops halt all purchasing when \"\n                    \"daily or monthly limits are reached.\"\n                ),\n            },\n            \"decision_logging\": {\n                \"total_decisions_logged\": total_transactions,\n                \"claim_chains_built\": len(chains),\n                \"latest_chain_hash\": (\n                    chains[-1][\"root_hash\"] if chains else \"none\"\n                ),\n                \"tamper_evidence\": (\n                    \"All decisions recorded in Merkle claim chains. \"\n                    \"Any modification to historical records changes \"\n                    \"the root hash and is detectable.\"\n                ),\n            },\n            \"financial_summary\": {\n                \"total_spend\": total_spend,\n                \"total_transactions\": total_transactions,\n                \"spend_by_category\": spend_by_category,\n                \"unique_vendors\": len(spend_by_vendor),\n            },\n            \"data_processing\": {\n                \"gdpr_applicable\": True,\n                \"personal_data_categories\": [\n                    \"Vendor agent identifiers\",\n                    \"Transaction metadata\",\n                    \"Service descriptions\",\n                ],\n                \"data_processing_basis\": \"Legitimate interest (Art. 6(1)(f))\",\n                \"retention_period\": \"36 months\",\n                \"dpa_required_for_vendors\": True,\n            },\n        }\n\n        return report\n\n    def export_markdown(self, period: str = \"current_month\") -> str:\n        \"\"\"Export the compliance report as Markdown.\"\"\"\n        report = self.generate(period)\n        si = report[\"system_identification\"]\n        ho = report[\"human_oversight_mechanisms\"]\n        dl = report[\"decision_logging\"]\n        fs = report[\"financial_summary\"]\n        dp = report[\"data_processing\"]\n\n        md = f\"\"\"# EU AI Act Article 14 Compliance Report\n## {report['organization']} - {si['system_name']}\n\n**Generated:** {report['generated_at']}\n**Period:** {report['reporting_period']}\n**Risk Classification:** {si['risk_classification']}\n\n---\n\n### System Purpose\n{si['system_purpose']}\n\n### Risk Justification\n{si['risk_justification']}\n\n---\n\n### Human Oversight Mechanisms\n\n**Spending Policy Engine:** {ho['spending_policy_engine']['description']}\n\nControl Layers:\n\"\"\"\n        for layer in ho[\"spending_policy_engine\"][\"layers\"]:\n            md += f\"- {layer}\\n\"\n\n        md += f\"\"\"\n**Escalation:** {ho['escalation_threshold']}\n\n**Kill Switch:** {ho['kill_switch']}\n\n---\n\n### Decision Audit Trail\n\n| Metric | Value |\n|---|---|\n| Decisions logged | {dl['total_decisions_logged']} |\n| Claim chains built | {dl['claim_chains_built']} |\n| Latest chain hash | `{dl['latest_chain_hash']}` |\n\n**Tamper evidence:** {dl['tamper_evidence']}\n\n---\n\n### Financial Summary\n\n| Metric | Value |\n|---|---|\n| Total spend | ${fs['total_spend']:.2f} |\n| Total transactions | {fs['total_transactions']} |\n| Unique vendors | {fs['unique_vendors']} |\n\n---\n\n### GDPR Data Processing\n\n| Item | Detail |\n|---|---|\n| GDPR applicable | {dp['gdpr_applicable']} |\n| Legal basis | {dp['data_processing_basis']} |\n| Retention period | {dp['retention_period']} |\n| DPA required | {dp['dpa_required_for_vendors']} |\n\"\"\"\n        return md\n\n\n# Generate the compliance report\ngenerator = ComplianceReportGenerator(\n    agent_id=\"procurement-agent-01\",\n    system_name=\"Autonomous Procurement System v1.0\",\n    organization=\"Acme Corp\",\n)\n\n# Print as Markdown\nprint(generator.export_markdown(\"current_month\"))\n```\n\n### Compliance Checklist: EU AI Act Readiness (August 2, 2026 Deadline)\n\n| Requirement | Status | Implementation |\n|---|---|---|\n| System purpose documented | Required | `system_identification.system_purpose` in report |\n| Risk classification | Required | High-risk (autonomous financial decisions) |\n| Human oversight mechanisms | Required | 5-layer policy engine + escalation |\n| Decision logging | Required | GreenHelix `submit_metrics` + claim chains |\n| Tamper-evident audit trail | Required | Merkle claim chains via `build_claim_chain` |\n| Data processing documentation | Required (if GDPR applies) | GDPR section in compliance report |\n| Incident response procedure | Required | Escalation workflow + kill switch |\n| Regular compliance reviews | Required | Monthly report generation |\n\n### GDPR Considerations for Procurement Agents\n\nIf your procurement agent processes personal data (which it likely does if it purchases contact data, behavioral analytics, or identity information), you must address:\n\n1. **Lawful basis.** Document which GDPR Article 6 basis applies. Legitimate interest (Art. 6(1)(f)) is typical for B2B procurement, but requires a balancing test.\n2. **Data Processing Agreements.** Every vendor that receives or provides personal data needs a DPA. Your procurement agent should verify DPA status as part of vendor evaluation.\n3. **Data minimization.** Only purchase data your workflows actually need. Procurement agents should not speculatively buy data \"just in case.\"\n4. **Right to erasure.** If a data subject requests deletion, you must be able to trace which vendor provided which records and propagate the deletion request.\n5. **Cross-border transfers.** If vendors are outside the EEA, ensure adequate transfer mechanisms (SCCs, adequacy decisions) are in place.\n\n> **Key Takeaways**\n>\n> - The EU AI Act's August 2, 2026 deadline requires documentation of human oversight mechanisms for high-risk AI systems. Autonomous purchasing agents almost certainly qualify.\n> - Merkle claim chains via `build_claim_chain` and `get_claim_chains` provide tamper-evident audit trails that satisfy Article 14 requirements.\n> - Log every procurement decision with full context: what was decided, why, which policy checks passed or failed, and what level of human oversight applied.\n> - Generate compliance reports monthly. Do not wait until an audit to discover gaps.\n> - GDPR applies if your agent processes personal data. Vendor DPA verification should be part of the evaluation pipeline, not an afterthought.\n\n---\n\n## Appendix: Quick Reference\n\n### GreenHelix Tools Used in This Guide\n\n| Tool | Chapter | Purpose |\n|---|---|---|\n| `create_wallet` | 1, 2 | Create an agent wallet |\n| `set_budget` | 1, 2 | Set daily\u002Fmonthly spending limits |\n| `get_balance` | 1, 2 | Check current wallet balance |\n| `get_usage_analytics` | 2, 7 | Get spending analytics for a period |\n| `search_services` | 3 | Search the marketplace for services |\n| `best_match` | 3 | Rank search results by relevance |\n| `check_trust_score` | 3, 4 | Get a vendor's composite trust score |\n| `verify_identity` | 4 | Verify a vendor's identity |\n| `verify_agent` | 4 | Run KYA checks on a vendor |\n| `get_agent_reputation` | 4 | Get reputation score and trade history |\n| `create_payment_intent` | 5 | Initiate a payment |\n| `confirm_payment` | 5 | Confirm and execute a payment |\n| `create_escrow` | 5, 6 | Create an escrow-protected purchase |\n| `release_escrow` | 6 | Release escrowed funds to vendor |\n| `create_dispute` | 6 | File a dispute against a vendor |\n| `respond_to_dispute` | 6 | Respond to a filed dispute |\n| `record_transaction` | 2, 5, 7 | Record a transaction in the ledger |\n| `get_transaction_history` | 7 | Query historical transactions |\n| `get_revenue_metrics` | 7 | Get revenue data for ROI analysis |\n| `register_webhook` | 2 | Register webhook for notifications |\n| `submit_metrics` | 8 | Log procurement decisions for audit |\n| `build_claim_chain` | 8 | Build tamper-evident audit chain |\n| `get_claim_chains` | 8 | Retrieve audit chains for review |\n\n### Cross-References\n\n| Guide | Relevance to Procurement |\n|---|---|\n| P5: Trust Verification | Deep dive into claim chain verification, metric auditing, and KYA |\n| P6: FinOps | Advanced cost attribution, fleet dashboards, volume discount optimization |\n| P14: Negotiation Strategies | Negotiating escrow terms, SLAs, volume pricing with vendors |\n| P19: Payment Rails | x402 settlement details, MPP hybrid routing, multi-rail architecture |\n| P21: Agent-Ready Commerce | The seller's perspective -- how vendors list, price, and fulfill |\n\n### The Procurement Loop Checklist\n\nFor every autonomous purchase, verify:\n\n- [ ] **Discover:** Searched at least two protocols for vendors\n- [ ] **Evaluate:** Vendor identity verified, trust score above threshold, dispute rate below maximum\n- [ ] **Negotiate:** Price compared against alternatives, volume discount requested if applicable\n- [ ] **Purchase:** Policy engine approved, correct payment rail selected, escrow used if amount > $10\n- [ ] **Verify:** Acceptance tests defined and executed, delivery confirmed\n- [ ] **Reconcile:** Transaction recorded in ledger, tagged with category and workflow, budget updated\n- [ ] **Audit:** Decision logged with reasoning, claim chain built periodically\n\n","# The Agent Procurement Playbook\n\n> **Notice**: This is an educational guide with illustrative code examples.\n> It does not execute code or install dependencies.\n> All examples use the GreenHelix sandbox (https:\u002F\u002Fsandbox.greenhelix.net) which\n> provides 500 free credits — no API key required to get started.\n>\n> **Referenced credentials** (you supply these in your own environment):\n> - `GREENHELIX_API_KEY`: API authentication for GreenHelix gateway (read\u002Fwrite access to purchased API tools only)\n> - `WALLET_ADDRESS`: Blockchain wallet address for receiving payments (public address only — no private keys)\n> - `STRIPE_API_KEY`: Stripe API key for card payment processing (scoped to payment intents only)\n\n\nYour AI agent just found the perfect data enrichment service. It costs $0.003 per record, the vendor has a 97% accuracy rating, and the API response time is under 200ms. The agent wants to buy 500,000 records. That is $1,500 committed in under a second, with no human in the loop, no purchase order, no procurement review. Should the agent be allowed to spend that money? If yes, under what constraints? If no, what happens to the time-sensitive workflow waiting on that data?\nThis is the central tension of autonomous procurement: agents that can buy things are dramatically more capable than agents that cannot, but agents that spend without governance are a financial liability. A February 2026 survey by Gartner found that 86% of organizations plan to deploy autonomous AI agents at scale by end of 2026. McKinsey's March 2026 analysis of early adopters showed that autonomous procurement workflows -- where agents discover, evaluate, negotiate, and purchase services without human intervention -- deliver 15-30% efficiency gains over human-mediated purchasing. But 41% of those same organizations reported at least one incident of uncontrolled agent spending in their first quarter of deployment.\nThe solution is not to prevent agents from spending. It is to build the procurement infrastructure that makes autonomous spending safe, auditable, and reversible. This playbook shows you how. Every chapter contains working Python code against the GreenHelix A2A Commerce Gateway -- 128 tools accessible at `https:\u002F\u002Fapi.greenhelix.net\u002Fv1` via a single the REST API (`POST \u002Fv1\u002F{tool}`) endpoint. By the end, you will have a complete autonomous procurement system: spending policy engine, multi-protocol vendor discovery, trust-scored vendor evaluation, escrow-protected purchasing, automated dispute resolution, cost reconciliation, and EU AI Act-compliant audit trails.\n\n## What You'll Learn\n- Chapter 1: The Autonomous Buyer Architecture\n- Chapter 2: Spending Controls & Approval Workflows\n- Chapter 3: Vendor Discovery Across Protocols\n- Chapter 4: Vendor Evaluation & Trust Scoring\n- Chapter 5: Multi-Protocol Purchasing\n- Chapter 6: Escrow, Disputes & Purchase Protection\n- Chapter 7: Cost Reconciliation & FinOps Integration\n- Chapter 8: Compliance & Audit Trails\n- {report['organization']} - {si['system_name']}\n- Appendix: Quick Reference\n\n## Full Guide\n\n# The Agent Procurement Playbook: Autonomous Purchasing, Spending Controls, Vendor Evaluation & Multi-Protocol Buying\n\nYour AI agent just found the perfect data enrichment service. It costs $0.003 per record, the vendor has a 97% accuracy rating, and the API response time is under 200ms. The agent wants to buy 500,000 records. That is $1,500 committed in under a second, with no human in the loop, no purchase order, no procurement review. Should the agent be allowed to spend that money? If yes, under what constraints? If no, what happens to the time-sensitive workflow waiting on that data?\n\nThis is the central tension of autonomous procurement: agents that can buy things are dramatically more capable than agents that cannot, but agents that spend without governance are a financial liability. A February 2026 survey by Gartner found that 86% of organizations plan to deploy autonomous AI agents at scale by end of 2026. McKinsey's March 2026 analysis of early adopters showed that autonomous procurement workflows -- where agents discover, evaluate, negotiate, and purchase services without human intervention -- deliver 15-30% efficiency gains over human-mediated purchasing. But 41% of those same organizations reported at least one incident of uncontrolled agent spending in their first quarter of deployment.\n\nThe solution is not to prevent agents from spending. It is to build the procurement infrastructure that makes autonomous spending safe, auditable, and reversible. This playbook shows you how. Every chapter contains working Python code against the GreenHelix A2A Commerce Gateway -- 128 tools accessible at `https:\u002F\u002Fapi.greenhelix.net\u002Fv1` via a single the REST API (`POST \u002Fv1\u002F{tool}`) endpoint. By the end, you will have a complete autonomous procurement system: spending policy engine, multi-protocol vendor discovery, trust-scored vendor evaluation, escrow-protected purchasing, automated dispute resolution, cost reconciliation, and EU AI Act-compliant audit trails.\n\n---\n\n\n> **Getting started**: All examples in this guide work with the GreenHelix sandbox\n> (https:\u002F\u002Fsandbox.greenhelix.net) which provides 500 free credits — no API key required.\n\n## Table of Contents\n\n1. [The Autonomous Buyer Architecture](#chapter-1-the-autonomous-buyer-architecture)\n2. [Spending Controls & Approval Workflows](#chapter-2-spending-controls--approval-workflows)\n3. [Vendor Discovery Across Protocols](#chapter-3-vendor-discovery-across-protocols)\n4. [Vendor Evaluation & Trust Scoring](#chapter-4-vendor-evaluation--trust-scoring)\n5. [Multi-Protocol Purchasing](#chapter-5-multi-protocol-purchasing)\n6. [Escrow, Disputes & Purchase Protection](#chapter-6-escrow-disputes--purchase-protection)\n7. [Cost Reconciliation & FinOps Integration](#chapter-7-cost-reconciliation--finops-integration)\n8. [Compliance & Audit Trails](#chapter-8-compliance--audit-trails)\n\n---\n\n## Chapter 1: The Autonomous Buyer Architecture\n\n### Why Agents Need to Spend Money\n\nA research agent that cannot purchase data is limited to free datasets. A coding agent that cannot buy API access is limited to open-source tools. A sales agent that cannot pay for lead enrichment is limited to whatever data it already has. Every boundary on an agent's purchasing authority is also a boundary on its capability.\n\nThe shift from agents-as-tools to agents-as-economic-actors is the defining infrastructure transition of 2026. When an agent can autonomously discover a service it needs, evaluate whether that service is trustworthy, negotiate a price, execute a purchase, verify delivery, and reconcile the cost against a budget -- it becomes a self-sufficient economic unit. It no longer needs a human to approve every API subscription, every data purchase, every compute reservation. It operates at machine speed across the entire procurement cycle.\n\nBut this autonomy comes with a prerequisite: procurement infrastructure. The same infrastructure that enterprises built over decades for human purchasing -- approval hierarchies, spending limits, preferred vendor lists, purchase orders, three-way matching, audit trails -- must be rebuilt for agents. Not as bureaucratic overhead, but as programmatic guardrails that enable speed while preventing catastrophe.\n\n### The Procurement Loop\n\nEvery autonomous purchase follows a six-stage loop. The stages are sequential for a single purchase, but a production procurement agent runs hundreds of these loops concurrently.\n\n```\nDISCOVER --> EVALUATE --> NEGOTIATE --> PURCHASE --> VERIFY --> RECONCILE\n    ^                                                              |\n    |______________________________________________________________|\n                        (feedback loop)\n```\n\n**Stage 1: Discover.** The agent identifies a need (data, compute, API access, a service) and searches available vendors across multiple protocols. This is not a Google search -- it is structured queries against marketplace APIs, UCP manifests, ACP directories, and A2A service registries.\n\n**Stage 2: Evaluate.** The agent scores each vendor on trust, reputation, price, capability, and compliance. A vendor with a low trust score or missing identity verification is filtered out regardless of price. This stage uses GreenHelix Trust, Identity, and Reputation tools.\n\n**Stage 3: Negotiate.** For commodity purchases, negotiation is price comparison. For high-value or recurring purchases, the agent can request volume discounts, propose escrow terms, or negotiate SLA guarantees. See P14 (Negotiation Strategies) for advanced techniques.\n\n**Stage 4: Purchase.** The agent executes the payment through the appropriate protocol: x402 for crypto micropayments, UCP for fiat retail, ACP for agent-native checkout, or direct A2A commerce via GreenHelix. Escrow protects high-value transactions.\n\n**Stage 5: Verify.** The agent confirms delivery by inspecting the purchased asset -- validating data quality, checking API responses, running acceptance tests on delivered services. Failed verification triggers the dispute process.\n\n**Stage 6: Reconcile.** The agent records the purchase in its ledger, attributes the cost to the requesting workflow, and updates budget consumption. Anomaly detection flags unexpected spending patterns.\n\n### Reference Architecture\n\nThe autonomous buyer architecture has four core components:\n\n```\n+---------------------------------------------------------------------+\n|                    AUTONOMOUS BUYER AGENT                            |\n|                                                                     |\n|  +------------------+  +-------------------+  +------------------+  |\n|  | Spending Policy  |  |  Vendor Discovery |  | Purchase Engine  |  |\n|  | Engine           |  |  & Evaluation     |  |                  |  |\n|  |                  |  |                   |  | - x402 rail      |  |\n|  | - Budget caps    |  | - Multi-protocol  |  | - UCP rail       |  |\n|  | - Tx limits      |  |   search          |  | - ACP rail       |  |\n|  | - Whitelists     |  | - Trust scoring   |  | - A2A rail       |  |\n|  | - Escalation     |  | - Bid comparison  |  | - Escrow mgmt    |  |\n|  +--------+---------+  +--------+----------+  +--------+---------+  |\n|           |                     |                      |            |\n|  +--------v---------------------v----------------------v---------+  |\n|  |                    APPROVAL GATEWAY                           |  |\n|  |  Routes decisions through policy engine before execution      |  |\n|  +-------------------------------+-------------------------------+  |\n|                                  |                                  |\n+----------------------------------+----------------------------------+\n                                   |\n                                   v\n+-------------------------------+     +-------------------------------+\n|  GREENHELIX A2A COMMERCE      |     |  RECONCILIATION ENGINE       |\n|  GATEWAY                      |     |                               |\n|                               |     |  - Ledger recording           |\n|  128 tools via POST           |     |  - Cost attribution           |\n|  the REST API                  |     |  - Budget vs. actual          |\n|                               |     |  - Anomaly detection          |\n+-------------------------------+     +-------------------------------+\n```\n\nThe Spending Policy Engine is the gatekeeper. Every purchase request passes through it before execution. It checks per-transaction limits, daily budget caps, vendor whitelists, and escalation thresholds. If a purchase exceeds policy, it is either blocked, queued for human approval, or routed to a higher-authority agent.\n\nThe Approval Gateway sits between the policy engine and the purchase engine. It is the single choke point through which all spend flows. This architectural decision -- funneling all purchases through one gateway -- is critical for auditability and control. You cannot have agents bypassing the gateway by calling GreenHelix directly.\n\n### Bootstrapping the Architecture\n\nHere is the minimum code to initialize the architecture against GreenHelix:\n\n```python\nimport requests\nimport os\nfrom dataclasses import dataclass, field\nfrom typing import Optional\n\nAPI_BASE = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\nheaders = {\"Authorization\": f\"Bearer {os.environ['GREENHELIX_API_KEY']}\"}\n\n\ndef execute_tool(tool: str, input_data: dict) -> dict:\n    \"\"\"Execute a GreenHelix tool via the unified endpoint.\"\"\"\n    response = requests.post(\n        f\"{API_BASE}\u002Fv1\",\n        json={\"tool\": tool, \"input\": input_data},\n        headers=headers,\n    )\n    response.raise_for_status()\n    return response.json()\n\n\n@dataclass\nclass BuyerAgent:\n    agent_id: str\n    wallet_id: Optional[str] = None\n    budget_daily: float = 0.0\n    budget_monthly: float = 0.0\n\n    def initialize(self):\n        \"\"\"Create wallet and set initial budget.\"\"\"\n        wallet = execute_tool(\"create_wallet\", {\n            \"agent_id\": self.agent_id,\n            \"currency\": \"USD\",\n        })\n        self.wallet_id = wallet[\"wallet_id\"]\n\n        execute_tool(\"set_budget\", {\n            \"agent_id\": self.agent_id,\n            \"daily_limit\": self.budget_daily,\n            \"monthly_limit\": self.budget_monthly,\n        })\n        return self\n\n    def get_spending_status(self) -> dict:\n        \"\"\"Check current balance and usage.\"\"\"\n        balance = execute_tool(\"get_balance\", {\n            \"agent_id\": self.agent_id,\n        })\n        usage = execute_tool(\"get_usage_analytics\", {\n            \"agent_id\": self.agent_id,\n            \"period\": \"current_day\",\n        })\n        return {\n            \"balance\": balance[\"balance\"],\n            \"daily_spend\": usage.get(\"total_spend\", 0),\n            \"daily_remaining\": self.budget_daily - usage.get(\"total_spend\", 0),\n        }\n\n\n# Initialize a buyer agent with a $50\u002Fday, $1000\u002Fmonth budget\nbuyer = BuyerAgent(\n    agent_id=\"procurement-agent-01\",\n    budget_daily=50.00,\n    budget_monthly=1000.00,\n).initialize()\n\nprint(buyer.get_spending_status())\n```\n\nThis gives you an agent with a wallet, budget caps, and real-time spending visibility. The rest of this playbook builds on this foundation.\n\n> **Key Takeaways**\n>\n> - Autonomous procurement follows a six-stage loop: discover, evaluate, negotiate, purchase, verify, reconcile.\n> - The Spending Policy Engine is the gatekeeper -- every purchase passes through it before execution.\n> - The Approval Gateway is the single choke point for all spend. No agent should bypass it.\n> - Start with a wallet, a budget, and spending visibility. Everything else builds on this foundation.\n> - Organizations deploying autonomous procurement see 15-30% efficiency gains, but 41% experience uncontrolled spending incidents without proper governance.\n\n---\n\n## Chapter 2: Spending Controls & Approval Workflows\n\n### The Five Layers of Spending Control\n\nSpending controls for autonomous agents are not a single dial. They are five independent layers, each catching a different failure mode. Deploying only one layer leaves you exposed to the failures the others catch.\n\n| Layer | Control | What It Catches | GreenHelix Tool |\n|-------|---------|-----------------|-----------------|\n| 1 | Per-transaction cap | Single large unauthorized purchase | `set_budget` |\n| 2 | Daily\u002Fweekly budget limit | Runaway loops, amplification | `set_budget`, `get_usage_analytics` |\n| 3 | Recipient whitelist | Purchases from untrusted vendors | Policy engine (custom) |\n| 4 | Frequency limit | Rapid-fire small purchases that aggregate to large spend | Policy engine (custom) |\n| 5 | Human-in-the-loop escalation | Novel situations outside policy | Webhook + approval queue |\n\n**Layer 1: Per-Transaction Caps.** No single purchase can exceed a defined amount. This is the bluntest control -- it prevents a single bad decision from causing catastrophic damage. Set it at the maximum amount you would tolerate losing in a single transaction. For most agent workflows, $100-500 is appropriate for automated approval; anything above goes to escalation.\n\n**Layer 2: Daily\u002FWeekly Budget Limits.** Even if every individual transaction is small, an agent in a loop can drain a budget through volume. A $0.01 transaction repeated 100,000 times is $1,000. Daily and weekly limits create a hard ceiling on cumulative spend regardless of individual transaction sizes.\n\n**Layer 3: Recipient Whitelists.** The agent can only purchase from pre-approved vendors. This prevents an agent from being socially engineered (via prompt injection or adversarial marketplace listings) into sending money to a malicious actor. Whitelists can be static (a fixed list) or dynamic (any vendor with a trust score above a threshold).\n\n**Layer 4: Frequency Limits.** Rate-limiting purchases prevents rapid-fire micro-transactions that individually pass the per-transaction cap but collectively blow through the daily budget before alerting systems can react. A typical setting: no more than 10 purchases per minute, no more than 100 per hour.\n\n**Layer 5: Human-in-the-Loop Escalation.** For purchases that exceed caps, involve new vendors, or fall outside known categories, the system queues the purchase for human approval. The key design decision is what happens while waiting: does the workflow block (synchronous escalation) or continue with a fallback (asynchronous escalation)?\n\n### The ProcurementPolicyEngine\n\nThis class implements all five layers. It is the core of the spending control system.\n\n```python\nimport time\nfrom dataclasses import dataclass, field\nfrom typing import Optional\nfrom enum import Enum\n\n\nclass ApprovalDecision(Enum):\n    APPROVED = \"approved\"\n    DENIED = \"denied\"\n    ESCALATED = \"escalated\"\n\n\n@dataclass\nclass PurchaseRequest:\n    vendor_id: str\n    amount: float\n    currency: str = \"USD\"\n    category: str = \"general\"\n    description: str = \"\"\n    requesting_agent: str = \"\"\n    idempotency_key: str = \"\"\n\n\n@dataclass\nclass PolicyResult:\n    decision: ApprovalDecision\n    reason: str\n    purchase_request: Optional[PurchaseRequest] = None\n    escalation_id: Optional[str] = None\n\n\n@dataclass\nclass ProcurementPolicyEngine:\n    \"\"\"Five-layer spending control for autonomous procurement agents.\"\"\"\n\n    agent_id: str\n    max_transaction_amount: float = 500.00\n    daily_limit: float = 2000.00\n    weekly_limit: float = 10000.00\n    max_purchases_per_minute: int = 10\n    max_purchases_per_hour: int = 100\n    escalation_threshold: float = 500.00\n    vendor_whitelist: list = field(default_factory=list)\n    require_whitelist: bool = False\n\n    # Internal tracking\n    _purchase_timestamps: list = field(default_factory=list)\n    _daily_spend: float = 0.0\n\n    def evaluate(self, request: PurchaseRequest) -> PolicyResult:\n        \"\"\"Run a purchase request through all five control layers.\"\"\"\n\n        # Layer 1: Per-transaction cap\n        if request.amount > self.max_transaction_amount:\n            if request.amount > self.escalation_threshold:\n                return PolicyResult(\n                    decision=ApprovalDecision.ESCALATED,\n                    reason=f\"Amount ${request.amount:.2f} exceeds \"\n                           f\"auto-approval cap ${self.max_transaction_amount:.2f}\",\n                    purchase_request=request,\n                )\n            return PolicyResult(\n                decision=ApprovalDecision.DENIED,\n                reason=f\"Amount ${request.amount:.2f} exceeds \"\n                       f\"per-transaction limit ${self.max_transaction_amount:.2f}\",\n            )\n\n        # Layer 2: Daily budget limit\n        projected_daily = self._daily_spend + request.amount\n        if projected_daily > self.daily_limit:\n            return PolicyResult(\n                decision=ApprovalDecision.DENIED,\n                reason=f\"Purchase would bring daily spend to \"\n                       f\"${projected_daily:.2f}, exceeding \"\n                       f\"daily limit ${self.daily_limit:.2f}\",\n            )\n\n        # Layer 3: Vendor whitelist\n        if self.require_whitelist and request.vendor_id not in self.vendor_whitelist:\n            return PolicyResult(\n                decision=ApprovalDecision.ESCALATED,\n                reason=f\"Vendor {request.vendor_id} not in whitelist. \"\n                       f\"Escalating for manual review.\",\n                purchase_request=request,\n            )\n\n        # Layer 4: Frequency limit\n        now = time.time()\n        recent_minute = [t for t in self._purchase_timestamps if now - t \u003C 60]\n        recent_hour = [t for t in self._purchase_timestamps if now - t \u003C 3600]\n\n        if len(recent_minute) >= self.max_purchases_per_minute:\n            return PolicyResult(\n                decision=ApprovalDecision.DENIED,\n                reason=f\"Rate limit: {len(recent_minute)} purchases in \"\n                       f\"the last minute (max {self.max_purchases_per_minute})\",\n            )\n        if len(recent_hour) >= self.max_purchases_per_hour:\n            return PolicyResult(\n                decision=ApprovalDecision.DENIED,\n                reason=f\"Rate limit: {len(recent_hour)} purchases in \"\n                       f\"the last hour (max {self.max_purchases_per_hour})\",\n            )\n\n        # Layer 5: Escalation threshold for borderline amounts\n        if request.amount > self.escalation_threshold:\n            return PolicyResult(\n                decision=ApprovalDecision.ESCALATED,\n                reason=f\"Amount ${request.amount:.2f} exceeds escalation \"\n                       f\"threshold ${self.escalation_threshold:.2f}\",\n                purchase_request=request,\n            )\n\n        # All layers passed\n        self._purchase_timestamps.append(now)\n        self._daily_spend += request.amount\n        return PolicyResult(\n            decision=ApprovalDecision.APPROVED,\n            reason=\"All policy checks passed\",\n        )\n\n    def sync_with_gateway(self):\n        \"\"\"Sync local state with GreenHelix budget and usage data.\"\"\"\n        usage = execute_tool(\"get_usage_analytics\", {\n            \"agent_id\": self.agent_id,\n            \"period\": \"current_day\",\n        })\n        self._daily_spend = usage.get(\"total_spend\", 0)\n\n        balance = execute_tool(\"get_balance\", {\n            \"agent_id\": self.agent_id,\n        })\n        return {\n            \"daily_spend\": self._daily_spend,\n            \"daily_remaining\": self.daily_limit - self._daily_spend,\n            \"wallet_balance\": balance[\"balance\"],\n        }\n\n\n# Initialize the policy engine\npolicy = ProcurementPolicyEngine(\n    agent_id=\"procurement-agent-01\",\n    max_transaction_amount=500.00,\n    daily_limit=2000.00,\n    weekly_limit=10000.00,\n    escalation_threshold=250.00,\n    vendor_whitelist=[\"vendor-data-enrichment-01\", \"vendor-compute-aws-02\"],\n    require_whitelist=True,\n)\n\n# Evaluate a purchase request\nresult = policy.evaluate(PurchaseRequest(\n    vendor_id=\"vendor-data-enrichment-01\",\n    amount=45.00,\n    category=\"data\",\n    description=\"500k contact records enrichment\",\n    requesting_agent=\"research-agent-03\",\n))\n\nprint(f\"Decision: {result.decision.value}\")\nprint(f\"Reason: {result.reason}\")\n```\n\n### Escalation Workflow with Webhooks\n\nWhen a purchase is escalated, the system notifies a human approver and holds the purchase in a pending state. Here is how to wire up the escalation:\n\n```python\ndef handle_escalation(policy_result: PolicyResult) -> dict:\n    \"\"\"Queue an escalated purchase for human approval.\"\"\"\n    # Register a webhook for approval notifications\n    webhook = execute_tool(\"register_webhook\", {\n        \"agent_id\": policy.agent_id,\n        \"url\": \"https:\u002F\u002Fyour-app.example.com\u002Fprocurement\u002Fapprovals\",\n        \"events\": [\"purchase.approval_required\"],\n    })\n\n    # Record the pending purchase in the ledger for tracking\n    pending = execute_tool(\"record_transaction\", {\n        \"agent_id\": policy.agent_id,\n        \"type\": \"purchase_pending\",\n        \"amount\": str(policy_result.purchase_request.amount),\n        \"currency\": \"USD\",\n        \"counterparty\": policy_result.purchase_request.vendor_id,\n        \"metadata\": {\n            \"status\": \"awaiting_human_approval\",\n            \"reason\": policy_result.reason,\n            \"category\": policy_result.purchase_request.category,\n        },\n    })\n\n    return {\n        \"escalation_id\": pending.get(\"transaction_id\"),\n        \"status\": \"awaiting_approval\",\n        \"webhook_id\": webhook.get(\"webhook_id\"),\n    }\n```\n\n### Budget Configuration Decision Matrix\n\nUse this matrix to set appropriate limits based on your agent's role:\n\n| Agent Role | Per-Tx Cap | Daily Limit | Weekly Limit | Escalation | Whitelist Required |\n|---|---|---|---|---|---|\n| Research agent (data purchases) | $100 | $500 | $2,000 | $50 | Yes |\n| Infrastructure agent (compute) | $1,000 | $5,000 | $20,000 | $500 | Yes |\n| Sales agent (lead enrichment) | $200 | $1,000 | $4,000 | $100 | Yes |\n| Trading agent (market data) | $50 | $200 | $1,000 | $25 | No (dynamic trust) |\n| General-purpose agent | $50 | $250 | $1,000 | $25 | Yes |\n\n> **Key Takeaways**\n>\n> - Five independent control layers: per-transaction caps, daily\u002Fweekly budgets, vendor whitelists, frequency limits, and human escalation.\n> - The `ProcurementPolicyEngine` evaluates every purchase request before execution. No purchase bypasses the engine.\n> - Escalation is not failure -- it is a feature. Design your workflows to handle the delay introduced by human-in-the-loop review.\n> - Sync the policy engine with GreenHelix usage analytics to keep local state consistent with actual spend.\n> - Set limits based on agent role, not a single global policy. A trading agent and an infrastructure agent have fundamentally different spending patterns.\n\n---\n\n## Chapter 3: Vendor Discovery Across Protocols\n\n### The Multi-Protocol Discovery Problem\n\nYour procurement agent needs a data enrichment service. Where does it look? In 2026, vendors advertise their services across at least four distinct protocols, each with its own discovery mechanism:\n\n- **GreenHelix Marketplace** -- Structured service listings with trust scores, ratings, and escrow history. Discovery via `search_services` and `best_match` tools.\n- **UCP (Universal Commerce Protocol)** -- Google and Shopify's protocol for structured product and service catalogs. Agents query UCP manifests to find services and compare prices.\n- **ACP (Agentic Commerce Protocol)** -- OpenAI's protocol for agent-to-merchant discovery. ACP directories list merchants with Stripe-backed checkout.\n- **A2A Direct** -- Agent-to-agent service advertisements via standardized capability manifests. No marketplace intermediary.\n\nA vendor might list on one protocol, two, or all four. A procurement agent that only searches one protocol misses vendors available on the others. The solution is a unified vendor index that aggregates discovery results across all protocols.\n\n### GreenHelix Marketplace Discovery\n\nThe GreenHelix Marketplace is the richest discovery source because it includes trust, reputation, and escrow data alongside service listings.\n\n```python\ndef discover_greenhelix_vendors(query: str, category: str = None,\n                                 min_trust_score: float = 0.7,\n                                 max_results: int = 20) -> list:\n    \"\"\"Search GreenHelix Marketplace for services matching a query.\"\"\"\n    search_params = {\n        \"query\": query,\n        \"max_results\": max_results,\n    }\n    if category:\n        search_params[\"category\"] = category\n\n    results = execute_tool(\"search_services\", search_params)\n\n    # Filter by trust score\n    filtered = []\n    for service in results.get(\"services\", []):\n        trust = execute_tool(\"check_trust_score\", {\n            \"agent_id\": service[\"provider_id\"],\n        })\n        if trust.get(\"trust_score\", 0) >= min_trust_score:\n            service[\"trust_score\"] = trust[\"trust_score\"]\n            filtered.append(service)\n\n    # Rank by best match\n    if filtered:\n        best = execute_tool(\"best_match\", {\n            \"query\": query,\n            \"candidates\": [s[\"service_id\"] for s in filtered],\n        })\n        # Reorder filtered list by best_match ranking\n        ranked_ids = [m[\"service_id\"] for m in best.get(\"matches\", [])]\n        filtered.sort(key=lambda s: (\n            ranked_ids.index(s[\"service_id\"])\n            if s[\"service_id\"] in ranked_ids else 999\n        ))\n\n    return filtered\n```\n\n### UCP Manifest Discovery\n\nUCP manifests are structured JSON documents that describe services in a standardized format. Agents query them by fetching the manifest URL and parsing the catalog.\n\n```python\nimport requests as http_client\n\n\ndef discover_ucp_vendors(manifest_urls: list, query: str) -> list:\n    \"\"\"Query UCP manifests for matching services.\"\"\"\n    vendors = []\n    for url in manifest_urls:\n        try:\n            resp = http_client.get(url, timeout=10)\n            resp.raise_for_status()\n            manifest = resp.json()\n\n            for service in manifest.get(\"services\", []):\n                # Simple keyword matching against service description\n                name = service.get(\"name\", \"\").lower()\n                desc = service.get(\"description\", \"\").lower()\n                if query.lower() in name or query.lower() in desc:\n                    vendors.append({\n                        \"source\": \"ucp\",\n                        \"provider_id\": manifest.get(\"provider_id\"),\n                        \"service_id\": service.get(\"id\"),\n                        \"name\": service.get(\"name\"),\n                        \"price\": service.get(\"price\"),\n                        \"currency\": service.get(\"currency\", \"USD\"),\n                        \"manifest_url\": url,\n                    })\n        except (http_client.RequestException, ValueError):\n            continue  # Skip unreachable or malformed manifests\n\n    return vendors\n\n\ndef discover_acp_vendors(directory_url: str, query: str) -> list:\n    \"\"\"Query an ACP agent directory for matching services.\"\"\"\n    try:\n        resp = http_client.get(\n            f\"{directory_url}\u002Fsearch\",\n            params={\"q\": query, \"type\": \"service\"},\n            timeout=10,\n        )\n        resp.raise_for_status()\n        listings = resp.json().get(\"results\", [])\n\n        return [{\n            \"source\": \"acp\",\n            \"provider_id\": listing.get(\"agent_id\"),\n            \"service_id\": listing.get(\"service_id\"),\n            \"name\": listing.get(\"name\"),\n            \"price\": listing.get(\"price\"),\n            \"currency\": listing.get(\"currency\", \"USD\"),\n            \"checkout_url\": listing.get(\"checkout_url\"),\n        } for listing in listings]\n    except (http_client.RequestException, ValueError):\n        return []\n```\n\n### The Unified Vendor Index\n\nCombine results from all protocols into a single, ranked vendor index:\n\n```python\nfrom dataclasses import dataclass\nfrom typing import Optional\n\n\n@dataclass\nclass VendorCandidate:\n    source: str             # \"greenhelix\", \"ucp\", \"acp\", \"a2a\"\n    provider_id: str\n    service_id: str\n    name: str\n    price: float\n    currency: str\n    trust_score: Optional[float] = None  # Only available for GreenHelix\n    manifest_url: Optional[str] = None\n    checkout_url: Optional[str] = None\n\n\nclass UnifiedVendorIndex:\n    \"\"\"Aggregates vendor discovery across all protocols.\"\"\"\n\n    def __init__(self, ucp_manifests: list = None, acp_directory: str = None):\n        self.ucp_manifests = ucp_manifests or []\n        self.acp_directory = acp_directory\n\n    def search(self, query: str, category: str = None,\n               min_trust: float = 0.5) -> list[VendorCandidate]:\n        \"\"\"Search all protocols and return unified, ranked results.\"\"\"\n        candidates = []\n\n        # 1. GreenHelix Marketplace (richest data)\n        gh_results = discover_greenhelix_vendors(\n            query, category=category, min_trust_score=min_trust,\n        )\n        for r in gh_results:\n            candidates.append(VendorCandidate(\n                source=\"greenhelix\",\n                provider_id=r[\"provider_id\"],\n                service_id=r[\"service_id\"],\n                name=r.get(\"name\", \"\"),\n                price=float(r.get(\"price\", 0)),\n                currency=r.get(\"currency\", \"USD\"),\n                trust_score=r.get(\"trust_score\"),\n            ))\n\n        # 2. UCP manifests\n        ucp_results = discover_ucp_vendors(self.ucp_manifests, query)\n        for r in ucp_results:\n            candidates.append(VendorCandidate(\n                source=\"ucp\",\n                provider_id=r[\"provider_id\"],\n                service_id=r[\"service_id\"],\n                name=r[\"name\"],\n                price=float(r.get(\"price\", 0)),\n                currency=r.get(\"currency\", \"USD\"),\n                manifest_url=r.get(\"manifest_url\"),\n            ))\n\n        # 3. ACP directory\n        if self.acp_directory:\n            acp_results = discover_acp_vendors(self.acp_directory, query)\n            for r in acp_results:\n                candidates.append(VendorCandidate(\n                    source=\"acp\",\n                    provider_id=r[\"provider_id\"],\n                    service_id=r[\"service_id\"],\n                    name=r[\"name\"],\n                    price=float(r.get(\"price\", 0)),\n                    currency=r.get(\"currency\", \"USD\"),\n                    checkout_url=r.get(\"checkout_url\"),\n                ))\n\n        # Sort: trust-scored vendors first, then by price\n        candidates.sort(key=lambda c: (\n            0 if c.trust_score is not None else 1,\n            -(c.trust_score or 0),\n            c.price,\n        ))\n\n        return candidates\n\n\n# Usage\nindex = UnifiedVendorIndex(\n    ucp_manifests=[\n        \"https:\u002F\u002Fvendor-a.example.com\u002F.well-known\u002Fucp-manifest.json\",\n        \"https:\u002F\u002Fvendor-b.example.com\u002F.well-known\u002Fucp-manifest.json\",\n    ],\n    acp_directory=\"https:\u002F\u002Facp-directory.example.com\u002Fv1\",\n)\n\nvendors = index.search(\"data enrichment\", category=\"data\")\nfor v in vendors[:5]:\n    trust_display = f\" (trust: {v.trust_score:.2f})\" if v.trust_score else \"\"\n    print(f\"  [{v.source}] {v.name} - ${v.price}{trust_display}\")\n```\n\n### Protocol Coverage Checklist\n\nBefore deploying your procurement agent, verify coverage across all relevant discovery channels:\n\n- [ ] GreenHelix Marketplace search configured with appropriate trust threshold\n- [ ] UCP manifest URLs for known vendor networks added to the index\n- [ ] ACP directory endpoint configured (if purchasing from OpenAI ecosystem merchants)\n- [ ] A2A direct discovery configured for peer agent services\n- [ ] Fallback behavior defined when a protocol is unreachable\n- [ ] Deduplication logic handles the same vendor appearing on multiple protocols\n\n> **Key Takeaways**\n>\n> - Vendors advertise across four protocols. An agent that searches only one protocol misses opportunities on the others.\n> - GreenHelix Marketplace provides the richest discovery data because it includes trust scores, reputation, and escrow history alongside listings.\n> - Build a `UnifiedVendorIndex` that aggregates results across all protocols and ranks by trust score first, price second.\n> - Trust-scored vendors should always rank above unscored vendors, regardless of price. The cheapest vendor with no verifiable identity is the most expensive mistake.\n> - See P21 (Agent-Ready Commerce) for the seller's perspective on listing across multiple protocols.\n\n---\n\n## Chapter 4: Vendor Evaluation & Trust Scoring\n\n### Why Price Alone Is Insufficient\n\nThe cheapest vendor in your search results is also the most likely to be fraudulent. This is Akerlof's \"Market for Lemons\" problem applied to agent commerce: without reliable quality signals, low-quality sellers undercut high-quality ones, and buyers cannot tell the difference until after they have paid. The antidote is a structured evaluation framework that scores vendors on dimensions beyond price.\n\nThe four evaluation dimensions are:\n\n1. **Identity verification** -- Is this vendor a real, registered entity?\n2. **Trust score** -- Does the platform's composite trust assessment meet your threshold?\n3. **Reputation history** -- What do other buyers say about this vendor?\n4. **Bid comparison** -- Given equivalent trust, which vendor offers the best value?\n\n### The Vendor Scoring System\n\n```python\nfrom dataclasses import dataclass\nfrom typing import Optional\n\n\n@dataclass\nclass VendorScore:\n    vendor_id: str\n    identity_verified: bool = False\n    identity_confidence: float = 0.0\n    trust_score: float = 0.0\n    reputation_score: float = 0.0\n    trade_count: int = 0\n    dispute_rate: float = 0.0\n    price: float = 0.0\n    composite_score: float = 0.0\n    risk_level: str = \"unknown\"  # low, medium, high, critical\n    disqualified: bool = False\n    disqualification_reason: str = \"\"\n\n\nclass VendorEvaluator:\n    \"\"\"Automated vendor evaluation using GreenHelix Trust, Identity,\n    and Reputation tools.\"\"\"\n\n    # Weights for composite score (must sum to 1.0)\n    WEIGHT_TRUST = 0.30\n    WEIGHT_REPUTATION = 0.25\n    WEIGHT_IDENTITY = 0.20\n    WEIGHT_TRADE_HISTORY = 0.15\n    WEIGHT_PRICE = 0.10\n\n    # Thresholds\n    MIN_TRUST_SCORE = 0.6\n    MIN_TRADE_COUNT = 5\n    MAX_DISPUTE_RATE = 0.10  # 10%\n\n    def evaluate(self, vendor_id: str, price: float,\n                 price_range: tuple = (0, 1000)) -> VendorScore:\n        \"\"\"Run full evaluation pipeline on a single vendor.\"\"\"\n        score = VendorScore(vendor_id=vendor_id, price=price)\n\n        # Step 1: Identity verification\n        try:\n            identity = execute_tool(\"verify_identity\", {\n                \"agent_id\": vendor_id,\n            })\n            score.identity_verified = identity.get(\"verified\", False)\n            score.identity_confidence = identity.get(\"confidence\", 0.0)\n        except Exception:\n            score.identity_verified = False\n            score.identity_confidence = 0.0\n\n        if not score.identity_verified:\n            score.disqualified = True\n            score.disqualification_reason = \"Identity verification failed\"\n            score.risk_level = \"critical\"\n            return score\n\n        # Step 2: Trust score\n        try:\n            trust = execute_tool(\"check_trust_score\", {\n                \"agent_id\": vendor_id,\n            })\n            score.trust_score = trust.get(\"trust_score\", 0.0)\n        except Exception:\n            score.trust_score = 0.0\n\n        if score.trust_score \u003C self.MIN_TRUST_SCORE:\n            score.disqualified = True\n            score.disqualification_reason = (\n                f\"Trust score {score.trust_score:.2f} below \"\n                f\"minimum {self.MIN_TRUST_SCORE}\"\n            )\n            score.risk_level = \"high\"\n            return score\n\n        # Step 3: Reputation and trade history\n        try:\n            reputation = execute_tool(\"get_agent_reputation\", {\n                \"agent_id\": vendor_id,\n            })\n            score.reputation_score = reputation.get(\"reputation_score\", 0.0)\n            score.trade_count = reputation.get(\"total_trades\", 0)\n            score.dispute_rate = reputation.get(\"dispute_rate\", 0.0)\n        except Exception:\n            score.reputation_score = 0.0\n\n        if score.dispute_rate > self.MAX_DISPUTE_RATE:\n            score.disqualified = True\n            score.disqualification_reason = (\n                f\"Dispute rate {score.dispute_rate:.1%} exceeds \"\n                f\"maximum {self.MAX_DISPUTE_RATE:.1%}\"\n            )\n            score.risk_level = \"high\"\n            return score\n\n        # Step 4: Additional KYA check\n        try:\n            kya = execute_tool(\"verify_agent\", {\n                \"agent_id\": vendor_id,\n            })\n            if not kya.get(\"verified\", False):\n                score.risk_level = \"medium\"\n        except Exception:\n            pass\n\n        # Step 5: Compute composite score\n        price_min, price_max = price_range\n        price_normalized = 1.0 - (\n            (price - price_min) \u002F (price_max - price_min)\n            if price_max > price_min else 0.5\n        )\n        price_normalized = max(0, min(1, price_normalized))\n\n        trade_normalized = min(1.0, score.trade_count \u002F 100)\n\n        score.composite_score = (\n            self.WEIGHT_TRUST * score.trust_score\n            + self.WEIGHT_REPUTATION * score.reputation_score\n            + self.WEIGHT_IDENTITY * score.identity_confidence\n            + self.WEIGHT_TRADE_HISTORY * trade_normalized\n            + self.WEIGHT_PRICE * price_normalized\n        )\n\n        # Assign risk level\n        if score.composite_score >= 0.8:\n            score.risk_level = \"low\"\n        elif score.composite_score >= 0.6:\n            score.risk_level = \"medium\"\n        else:\n            score.risk_level = \"high\"\n\n        return score\n\n    def evaluate_batch(self, candidates: list[VendorCandidate]) -> list[VendorScore]:\n        \"\"\"Evaluate and rank a list of vendor candidates.\"\"\"\n        prices = [c.price for c in candidates if c.price > 0]\n        price_range = (min(prices), max(prices)) if prices else (0, 1000)\n\n        scores = []\n        for candidate in candidates:\n            score = self.evaluate(\n                candidate.provider_id,\n                candidate.price,\n                price_range,\n            )\n            scores.append(score)\n\n        # Sort: non-disqualified first, then by composite score descending\n        scores.sort(key=lambda s: (\n            s.disqualified,\n            -s.composite_score,\n        ))\n\n        return scores\n\n\n# Evaluate vendors from the unified index\nevaluator = VendorEvaluator()\nvendors = index.search(\"data enrichment\", category=\"data\")\nscores = evaluator.evaluate_batch(vendors)\n\nprint(f\"\\n{'Vendor':\u003C30} {'Score':>6} {'Risk':\u003C10} {'Price':>8} {'Status':\u003C12}\")\nprint(\"-\" * 76)\nfor s in scores:\n    status = \"DISQUALIFIED\" if s.disqualified else \"ELIGIBLE\"\n    print(f\"{s.vendor_id:\u003C30} {s.composite_score:>6.2f} {s.risk_level:\u003C10} \"\n          f\"${s.price:>7.2f} {status:\u003C12}\")\n    if s.disqualified:\n        print(f\"  Reason: {s.disqualification_reason}\")\n```\n\n### Risk Scoring Decision Matrix\n\n| Composite Score | Risk Level | Recommended Action |\n|---|---|---|\n| 0.80 - 1.00 | Low | Auto-approve up to per-transaction cap |\n| 0.60 - 0.79 | Medium | Auto-approve for small amounts; escalate above $100 |\n| 0.40 - 0.59 | High | Escalate all purchases for human review |\n| 0.00 - 0.39 | Critical | Block. Do not purchase. |\n\n### Automated Bid Comparison\n\nWhen multiple vendors pass the trust threshold, compare them on value:\n\n```python\ndef compare_bids(scores: list[VendorScore],\n                 max_budget: float) -> Optional[VendorScore]:\n    \"\"\"Select the best vendor from evaluated candidates.\n\n    Strategy: Among eligible vendors with 'low' or 'medium' risk,\n    select the one with the highest composite score within budget.\n    Break ties by preferring lower price.\n    \"\"\"\n    eligible = [\n        s for s in scores\n        if not s.disqualified\n        and s.risk_level in (\"low\", \"medium\")\n        and s.price \u003C= max_budget\n    ]\n\n    if not eligible:\n        return None\n\n    # Sort by composite score descending, then price ascending\n    eligible.sort(key=lambda s: (-s.composite_score, s.price))\n    return eligible[0]\n\n\n# Select the best vendor with a $200 budget\nwinner = compare_bids(scores, max_budget=200.00)\nif winner:\n    print(f\"\\nSelected vendor: {winner.vendor_id}\")\n    print(f\"  Composite score: {winner.composite_score:.2f}\")\n    print(f\"  Price: ${winner.price:.2f}\")\n    print(f\"  Risk: {winner.risk_level}\")\nelse:\n    print(\"\\nNo eligible vendor found within budget and risk tolerance.\")\n```\n\n> **Key Takeaways**\n>\n> - Never select a vendor on price alone. The cheapest unverified vendor is the most expensive mistake.\n> - The evaluation pipeline has hard gates (identity, minimum trust, dispute rate) and soft scoring (composite weighted score).\n> - Disqualification is binary -- a vendor that fails identity verification or exceeds the dispute rate threshold is excluded regardless of price.\n> - The composite score weights trust (30%) and reputation (25%) above price (10%). Adjust weights based on your risk tolerance.\n> - See P5 (Trust Verification) for deep dives into claim chain verification and metric auditing.\n\n---\n\n## Chapter 5: Multi-Protocol Purchasing\n\n### Four Rails, One Agent\n\nYour procurement agent has discovered vendors, evaluated them, and selected a winner. Now it needs to pay. The payment rail depends on the vendor's protocol:\n\n| Protocol | Payment Method | Best For | Settlement Time |\n|---|---|---|---|\n| x402 | USDC stablecoin | Micropayments, pay-per-request APIs | Seconds (on-chain) |\n| UCP | Fiat (card\u002Fbank) | Retail, SaaS subscriptions | 1-3 business days |\n| ACP | Stripe (card\u002FSPT) | Merchant checkout, e-commerce | 1-3 business days |\n| A2A (GreenHelix) | Wallet-to-wallet | Agent-to-agent, escrow-protected | Instant (platform) |\n\nThe procurement agent must handle all four. Here is the implementation for each rail.\n\n### Rail 1: x402 Crypto Micropayments\n\nx402 is HTTP-native: the server returns HTTP 402 with a payment requirement, and the client pays in USDC via a facilitator. Ideal for pay-per-request API access.\n\n```python\nimport hashlib\nimport json\n\n\ndef purchase_x402(\n    resource_url: str,\n    wallet_address: str,\n    max_amount_usdc: float,\n) -> dict:\n    \"\"\"Execute an x402 payment for a resource.\n\n    The flow:\n    1. Request the resource -> get 402 with payment requirements\n    2. Verify the price is within budget\n    3. Create payment authorization via GreenHelix\n    4. Submit payment and receive resource\n    \"\"\"\n    # Step 1: Request the resource to get payment requirements\n    resp = http_client.get(resource_url)\n    if resp.status_code != 402:\n        # Resource is free or already paid\n        return {\"status\": \"no_payment_required\", \"data\": resp.json()}\n\n    payment_req = resp.json()\n    amount = float(payment_req.get(\"amount\", 0))\n    currency = payment_req.get(\"currency\", \"USDC\")\n    facilitator = payment_req.get(\"facilitator_url\")\n    recipient = payment_req.get(\"recipient_address\")\n\n    # Step 2: Verify price is within budget\n    if amount > max_amount_usdc:\n        return {\n            \"status\": \"rejected\",\n            \"reason\": f\"Price ${amount} exceeds max ${max_amount_usdc}\",\n        }\n\n    # Step 3: Create payment via GreenHelix\n    intent = execute_tool(\"create_payment_intent\", {\n        \"amount\": str(amount),\n        \"currency\": currency,\n        \"recipient\": recipient,\n        \"payment_method\": \"x402\",\n        \"metadata\": {\n            \"resource_url\": resource_url,\n            \"facilitator\": facilitator,\n            \"protocol\": \"x402\",\n        },\n    })\n\n    # Step 4: Confirm the payment\n    confirmation = execute_tool(\"confirm_payment\", {\n        \"payment_id\": intent[\"payment_id\"],\n        \"wallet_address\": wallet_address,\n    })\n\n    # Step 5: Re-request with payment proof\n    proof_headers = {\n        \"X-Payment-Id\": confirmation[\"payment_id\"],\n        \"X-Payment-Proof\": confirmation.get(\"proof\", \"\"),\n    }\n    final_resp = http_client.get(resource_url, headers=proof_headers)\n\n    return {\n        \"status\": \"completed\",\n        \"payment_id\": confirmation[\"payment_id\"],\n        \"amount\": amount,\n        \"currency\": currency,\n        \"data\": final_resp.json() if final_resp.ok else None,\n    }\n```\n\n### Rail 2: UCP Fiat Retail Purchasing\n\nUCP handles structured product purchasing with fiat payment methods. The flow follows a standard e-commerce checkout pattern.\n\n```python\ndef purchase_ucp(\n    service_id: str,\n    manifest_url: str,\n    quantity: int = 1,\n) -> dict:\n    \"\"\"Execute a UCP purchase using GreenHelix as the payment backend.\n\n    The flow:\n    1. Fetch service details from UCP manifest\n    2. Create a payment intent via GreenHelix\n    3. Authorize the fiat payment\n    4. Confirm delivery\n    \"\"\"\n    # Step 1: Fetch service details\n    manifest = http_client.get(manifest_url, timeout=10).json()\n    service = next(\n        (s for s in manifest.get(\"services\", []) if s[\"id\"] == service_id),\n        None,\n    )\n    if not service:\n        return {\"status\": \"error\", \"reason\": f\"Service {service_id} not found\"}\n\n    total = float(service[\"price\"]) * quantity\n\n    # Step 2: Create payment intent\n    intent = execute_tool(\"create_payment_intent\", {\n        \"amount\": str(total),\n        \"currency\": service.get(\"currency\", \"USD\"),\n        \"recipient\": manifest.get(\"provider_id\"),\n        \"payment_method\": \"fiat\",\n        \"metadata\": {\n            \"protocol\": \"ucp\",\n            \"service_id\": service_id,\n            \"quantity\": quantity,\n            \"manifest_url\": manifest_url,\n        },\n    })\n\n    # Step 3: Confirm the payment\n    confirmation = execute_tool(\"confirm_payment\", {\n        \"payment_id\": intent[\"payment_id\"],\n    })\n\n    return {\n        \"status\": \"completed\",\n        \"payment_id\": confirmation[\"payment_id\"],\n        \"amount\": total,\n        \"currency\": service.get(\"currency\", \"USD\"),\n        \"service\": service[\"name\"],\n        \"protocol\": \"ucp\",\n    }\n```\n\n### Rail 3: ACP Agent-Native Checkout\n\nACP uses Shared Payment Tokens (SPTs) for delegated spending through Stripe.\n\n```python\ndef purchase_acp(\n    service_id: str,\n    checkout_url: str,\n    spt_token: str,\n) -> dict:\n    \"\"\"Execute an ACP purchase using a Shared Payment Token.\n\n    The flow:\n    1. Initiate checkout at the ACP merchant endpoint\n    2. Authorize via SPT\n    3. Record the transaction in GreenHelix for tracking\n    \"\"\"\n    # Step 1: Initiate checkout\n    checkout_resp = http_client.post(\n        checkout_url,\n        json={\n            \"service_id\": service_id,\n            \"payment_method\": \"spt\",\n            \"spt_token\": spt_token,\n        },\n        timeout=15,\n    )\n    checkout_resp.raise_for_status()\n    checkout_data = checkout_resp.json()\n\n    # Step 2: Record in GreenHelix ledger for unified tracking\n    execute_tool(\"record_transaction\", {\n        \"agent_id\": buyer.agent_id,\n        \"type\": \"purchase\",\n        \"amount\": str(checkout_data.get(\"amount\", 0)),\n        \"currency\": checkout_data.get(\"currency\", \"USD\"),\n        \"counterparty\": checkout_data.get(\"merchant_id\", \"\"),\n        \"metadata\": {\n            \"protocol\": \"acp\",\n            \"service_id\": service_id,\n            \"external_payment_id\": checkout_data.get(\"payment_id\"),\n            \"checkout_url\": checkout_url,\n        },\n    })\n\n    return {\n        \"status\": \"completed\",\n        \"payment_id\": checkout_data.get(\"payment_id\"),\n        \"amount\": checkout_data.get(\"amount\"),\n        \"protocol\": \"acp\",\n    }\n```\n\n### Rail 4: A2A Direct Commerce via GreenHelix\n\nFor agent-to-agent purchases, the commerce layer provides the full stack: payment, escrow, and delivery verification.\n\n```python\ndef purchase_a2a(\n    vendor_id: str,\n    service_id: str,\n    amount: float,\n    use_escrow: bool = True,\n) -> dict:\n    \"\"\"Execute an A2A purchase via GreenHelix with optional escrow.\n\n    This is the recommended rail for agent-to-agent transactions\n    because it includes built-in escrow, disputes, and delivery\n    verification.\n    \"\"\"\n    if use_escrow:\n        # Create escrow-protected purchase\n        escrow = execute_tool(\"create_escrow\", {\n            \"payer_id\": buyer.agent_id,\n            \"payee_id\": vendor_id,\n            \"amount\": str(amount),\n            \"currency\": \"USD\",\n            \"conditions\": {\n                \"service_id\": service_id,\n                \"delivery_deadline_hours\": 24,\n                \"verification_method\": \"automated\",\n            },\n        })\n\n        return {\n            \"status\": \"escrowed\",\n            \"escrow_id\": escrow[\"escrow_id\"],\n            \"amount\": amount,\n            \"vendor_id\": vendor_id,\n            \"protocol\": \"a2a\",\n            \"next_step\": \"await_delivery_then_verify\",\n        }\n    else:\n        # Direct payment (no escrow)\n        intent = execute_tool(\"create_payment_intent\", {\n            \"amount\": str(amount),\n            \"currency\": \"USD\",\n            \"recipient\": vendor_id,\n            \"payment_method\": \"wallet\",\n            \"metadata\": {\n                \"protocol\": \"a2a\",\n                \"service_id\": service_id,\n            },\n        })\n\n        confirmation = execute_tool(\"confirm_payment\", {\n            \"payment_id\": intent[\"payment_id\"],\n        })\n\n        return {\n            \"status\": \"completed\",\n            \"payment_id\": confirmation[\"payment_id\"],\n            \"amount\": amount,\n            \"protocol\": \"a2a\",\n        }\n```\n\n### The Payment Router\n\nTie all four rails together with a router that selects the appropriate rail based on the vendor's protocol:\n\n```python\ndef route_purchase(vendor: VendorCandidate, amount: float,\n                   use_escrow: bool = True, **kwargs) -> dict:\n    \"\"\"Route a purchase to the appropriate payment rail.\"\"\"\n    if vendor.source == \"greenhelix\":\n        return purchase_a2a(\n            vendor.provider_id, vendor.service_id, amount, use_escrow,\n        )\n    elif vendor.source == \"ucp\":\n        return purchase_ucp(\n            vendor.service_id, vendor.manifest_url,\n            quantity=kwargs.get(\"quantity\", 1),\n        )\n    elif vendor.source == \"acp\":\n        return purchase_acp(\n            vendor.service_id, vendor.checkout_url,\n            spt_token=kwargs.get(\"spt_token\", \"\"),\n        )\n    else:\n        # Default to GreenHelix A2A for unknown protocols\n        return purchase_a2a(\n            vendor.provider_id, vendor.service_id, amount, use_escrow,\n        )\n```\n\n> **Key Takeaways**\n>\n> - Four payment rails serve different use cases: x402 for crypto micropayments, UCP for fiat, ACP for Stripe-backed checkout, A2A for agent-to-agent.\n> - Always use escrow for A2A purchases above your trust threshold. The cost of escrow is negligible compared to the cost of unrecoverable loss.\n> - Record all purchases in the GreenHelix ledger regardless of which rail was used. Unified tracking is essential for reconciliation.\n> - The payment router abstracts rail selection from the procurement logic. The agent does not need to know which protocol a vendor uses.\n> - See P19 (Payment Rails) for deep dives into x402 settlement, MPP hybrid routing, and multi-rail architecture patterns.\n\n---\n\n## Chapter 6: Escrow, Disputes & Purchase Protection\n\n### Why Escrow Is Non-Negotiable for Agent Commerce\n\nWhen a human buys a service and it fails to deliver, the human can call support, file a chargeback, leave a scathing review, or escalate to a regulatory body. An agent has none of these options unless they are programmed in advance. Escrow is the mechanism that makes agent purchasing safe: the buyer's funds are held by a neutral third party (GreenHelix) until the seller delivers and the buyer verifies. If delivery fails, the buyer gets their money back automatically.\n\nFor agent-to-agent commerce, escrow should be the default for any transaction above a trivial amount. The threshold varies by use case, but a reasonable starting point is: always use escrow for transactions above $10.\n\n### The Protected Purchase Flow\n\n```python\nimport time\nfrom enum import Enum\n\n\nclass DeliveryStatus(Enum):\n    PENDING = \"pending\"\n    DELIVERED = \"delivered\"\n    FAILED = \"failed\"\n    DISPUTED = \"disputed\"\n\n\nclass ProtectedPurchaseManager:\n    \"\"\"Manages the full lifecycle of an escrow-protected purchase:\n    creation, delivery verification, release, and dispute handling.\"\"\"\n\n    def __init__(self, buyer_id: str):\n        self.buyer_id = buyer_id\n\n    def create_protected_purchase(\n        self,\n        vendor_id: str,\n        service_id: str,\n        amount: float,\n        delivery_deadline_hours: int = 24,\n        verification_criteria: dict = None,\n    ) -> dict:\n        \"\"\"Create an escrow-protected purchase.\"\"\"\n        escrow = execute_tool(\"create_escrow\", {\n            \"payer_id\": self.buyer_id,\n            \"payee_id\": vendor_id,\n            \"amount\": str(amount),\n            \"currency\": \"USD\",\n            \"conditions\": {\n                \"service_id\": service_id,\n                \"delivery_deadline_hours\": delivery_deadline_hours,\n                \"verification_method\": \"automated\",\n                \"criteria\": verification_criteria or {},\n            },\n        })\n\n        return {\n            \"escrow_id\": escrow[\"escrow_id\"],\n            \"status\": \"escrowed\",\n            \"amount\": amount,\n            \"vendor_id\": vendor_id,\n            \"deadline\": delivery_deadline_hours,\n        }\n\n    def verify_delivery(\n        self,\n        escrow_id: str,\n        delivered_data: dict,\n        acceptance_tests: list = None,\n    ) -> DeliveryStatus:\n        \"\"\"Run automated verification on delivered goods\u002Fservices.\n\n        acceptance_tests is a list of callables that take delivered_data\n        and return (passed: bool, reason: str).\n        \"\"\"\n        if not delivered_data:\n            return DeliveryStatus.FAILED\n\n        if acceptance_tests:\n            failures = []\n            for test_fn in acceptance_tests:\n                passed, reason = test_fn(delivered_data)\n                if not passed:\n                    failures.append(reason)\n\n            if failures:\n                # Auto-dispute on verification failure\n                self.file_dispute(\n                    escrow_id,\n                    reason=f\"Delivery failed {len(failures)} acceptance \"\n                           f\"test(s): {'; '.join(failures)}\",\n                )\n                return DeliveryStatus.DISPUTED\n\n        return DeliveryStatus.DELIVERED\n\n    def release_escrow(self, escrow_id: str) -> dict:\n        \"\"\"Release funds to the vendor after successful verification.\"\"\"\n        result = execute_tool(\"release_escrow\", {\n            \"escrow_id\": escrow_id,\n            \"action\": \"release\",\n        })\n        return {\n            \"escrow_id\": escrow_id,\n            \"status\": \"released\",\n            \"released_to\": result.get(\"payee_id\"),\n            \"amount\": result.get(\"amount\"),\n        }\n\n    def file_dispute(self, escrow_id: str, reason: str,\n                     evidence: dict = None) -> dict:\n        \"\"\"File a dispute against the vendor.\"\"\"\n        dispute = execute_tool(\"create_dispute\", {\n            \"escrow_id\": escrow_id,\n            \"reason\": reason,\n            \"evidence\": evidence or {},\n            \"requested_resolution\": \"full_refund\",\n        })\n        return {\n            \"dispute_id\": dispute[\"dispute_id\"],\n            \"escrow_id\": escrow_id,\n            \"status\": \"dispute_filed\",\n            \"reason\": reason,\n        }\n\n    def respond_to_dispute(self, dispute_id: str, response: str,\n                           evidence: dict = None) -> dict:\n        \"\"\"Respond to a dispute (if this agent is the vendor side).\"\"\"\n        result = execute_tool(\"respond_to_dispute\", {\n            \"dispute_id\": dispute_id,\n            \"response\": response,\n            \"evidence\": evidence or {},\n        })\n        return {\n            \"dispute_id\": dispute_id,\n            \"status\": \"response_submitted\",\n            \"resolution\": result.get(\"resolution\"),\n        }\n\n    def execute_full_purchase(\n        self,\n        vendor_id: str,\n        service_id: str,\n        amount: float,\n        delivery_callback: callable,\n        acceptance_tests: list = None,\n        delivery_deadline_hours: int = 24,\n    ) -> dict:\n        \"\"\"Execute the complete protected purchase lifecycle.\n\n        delivery_callback: a callable that triggers vendor fulfillment\n        and returns the delivered data.\n        \"\"\"\n        # Step 1: Create escrow\n        purchase = self.create_protected_purchase(\n            vendor_id, service_id, amount,\n            delivery_deadline_hours=delivery_deadline_hours,\n        )\n        escrow_id = purchase[\"escrow_id\"]\n\n        # Step 2: Trigger delivery\n        try:\n            delivered_data = delivery_callback(escrow_id)\n        except Exception as e:\n            self.file_dispute(escrow_id, reason=f\"Delivery failed: {str(e)}\")\n            return {\n                \"escrow_id\": escrow_id,\n                \"status\": \"disputed\",\n                \"reason\": f\"Delivery exception: {str(e)}\",\n            }\n\n        # Step 3: Verify delivery\n        status = self.verify_delivery(\n            escrow_id, delivered_data, acceptance_tests,\n        )\n\n        # Step 4: Release or dispute\n        if status == DeliveryStatus.DELIVERED:\n            release = self.release_escrow(escrow_id)\n            return {\n                \"escrow_id\": escrow_id,\n                \"status\": \"completed\",\n                \"amount_released\": release[\"amount\"],\n            }\n        else:\n            return {\n                \"escrow_id\": escrow_id,\n                \"status\": status.value,\n                \"reason\": \"Automated verification failed\",\n            }\n\n\n# Usage: protected purchase with acceptance tests\nppm = ProtectedPurchaseManager(buyer_id=\"procurement-agent-01\")\n\n# Define acceptance tests for a data enrichment purchase\ndef test_record_count(data):\n    count = len(data.get(\"records\", []))\n    expected = 500_000\n    if count \u003C expected * 0.95:  # Allow 5% tolerance\n        return False, f\"Expected ~{expected} records, got {count}\"\n    return True, \"Record count OK\"\n\ndef test_data_completeness(data):\n    sample = data.get(\"records\", [])[:100]\n    incomplete = sum(1 for r in sample if not r.get(\"email\"))\n    if incomplete > 10:  # More than 10% incomplete\n        return False, f\"{incomplete}% of sample missing email field\"\n    return True, \"Data completeness OK\"\n\n# This would be your vendor's delivery mechanism\ndef trigger_vendor_delivery(escrow_id: str) -> dict:\n    \"\"\"Placeholder: in production, this calls the vendor's API.\"\"\"\n    return {\"records\": [{\"email\": \"test@example.com\"}] * 500_000}\n\nresult = ppm.execute_full_purchase(\n    vendor_id=\"vendor-data-enrichment-01\",\n    service_id=\"contact-enrichment-500k\",\n    amount=150.00,\n    delivery_callback=trigger_vendor_delivery,\n    acceptance_tests=[test_record_count, test_data_completeness],\n    delivery_deadline_hours=12,\n)\nprint(f\"Purchase result: {result['status']}\")\n```\n\n### Dispute Resolution Decision Tree\n\n```\nDelivery received?\n├── NO --> Wait until deadline\n│          └── Deadline passed? --> Auto-dispute (non-delivery)\n├── YES --> Run acceptance tests\n│          ├── ALL PASS --> Release escrow\n│          ├── SOME FAIL --> File dispute with evidence\n│          └── CRITICAL FAIL --> File dispute, request full refund\n```\n\n### Escrow Configuration Checklist\n\n- [ ] Set delivery deadlines appropriate to the service type (minutes for APIs, hours for data, days for custom work)\n- [ ] Define acceptance tests before creating the escrow, not after\n- [ ] Include specific, measurable criteria in escrow conditions (not \"good quality\" but \"95%+ record completeness\")\n- [ ] Configure automatic dispute filing for deadline expiration\n- [ ] Set up webhook notifications for escrow state changes\n- [ ] Record all escrow outcomes in the ledger for vendor reputation tracking\n\n> **Key Takeaways**\n>\n> - Escrow should be the default for any agent-to-agent transaction above $10. The cost of escrow is negligible; the cost of unrecoverable loss is not.\n> - Automated acceptance tests are the agent equivalent of \"inspecting the goods before signing.\" Define them before the purchase, not after.\n> - The `ProtectedPurchaseManager` handles the full lifecycle: escrow creation, delivery callback, automated verification, release or dispute.\n> - Dispute evidence should be structured and machine-readable. \"The data was bad\" is not evidence. \"47% of records missing email field, expected less than 5%\" is evidence.\n> - See P14 (Negotiation Strategies) for techniques to negotiate escrow terms, delivery deadlines, and SLA guarantees before the purchase.\n\n---\n\n## Chapter 7: Cost Reconciliation & FinOps Integration\n\n### The Reconciliation Problem\n\nYour procurement agent has executed purchases across four protocols, some through escrow, some direct. The transactions are scattered across GreenHelix ledger entries, Stripe payment records, x402 on-chain settlements, and UCP order confirmations. The CFO asks: \"How much did our AI agents spend last month, on what, and was it worth it?\"\n\nWithout a unified reconciliation system, you cannot answer that question. Cost reconciliation for autonomous procurement requires three capabilities:\n\n1. **Unified recording** -- Every purchase, regardless of protocol, is recorded in a single ledger.\n2. **Cost attribution** -- Every purchase is tagged with the requesting agent, workflow, and cost category.\n3. **Budget vs. actual analysis** -- Planned budgets are compared to actual spend, with anomaly detection for deviations.\n\n### Recording Purchases to the Ledger\n\nEvery purchase -- whether it went through x402, UCP, ACP, or A2A -- must be recorded in the GreenHelix Ledger for unified tracking:\n\n```python\nfrom datetime import datetime\n\n\nclass ProcurementLedger:\n    \"\"\"Records and queries all procurement transactions\n    in the GreenHelix Ledger.\"\"\"\n\n    def __init__(self, agent_id: str):\n        self.agent_id = agent_id\n\n    def record_purchase(\n        self,\n        vendor_id: str,\n        amount: float,\n        currency: str,\n        protocol: str,\n        service_id: str,\n        category: str,\n        workflow_id: str = \"\",\n        external_payment_id: str = \"\",\n        metadata: dict = None,\n    ) -> dict:\n        \"\"\"Record a completed purchase in the ledger.\"\"\"\n        tx = execute_tool(\"record_transaction\", {\n            \"agent_id\": self.agent_id,\n            \"type\": \"purchase\",\n            \"amount\": str(amount),\n            \"currency\": currency,\n            \"counterparty\": vendor_id,\n            \"metadata\": {\n                \"protocol\": protocol,\n                \"service_id\": service_id,\n                \"category\": category,\n                \"workflow_id\": workflow_id,\n                \"external_payment_id\": external_payment_id,\n                \"recorded_at\": datetime.utcnow().isoformat(),\n                **(metadata or {}),\n            },\n        })\n        return tx\n\n    def get_spend_by_category(self, period: str = \"current_month\") -> dict:\n        \"\"\"Get spend broken down by category.\"\"\"\n        history = execute_tool(\"get_transaction_history\", {\n            \"agent_id\": self.agent_id,\n            \"period\": period,\n            \"type\": \"purchase\",\n        })\n\n        by_category = {}\n        for tx in history.get(\"transactions\", []):\n            cat = tx.get(\"metadata\", {}).get(\"category\", \"uncategorized\")\n            by_category.setdefault(cat, {\"count\": 0, \"total\": 0.0})\n            by_category[cat][\"count\"] += 1\n            by_category[cat][\"total\"] += float(tx.get(\"amount\", 0))\n\n        return by_category\n\n    def get_spend_by_protocol(self, period: str = \"current_month\") -> dict:\n        \"\"\"Get spend broken down by payment protocol.\"\"\"\n        history = execute_tool(\"get_transaction_history\", {\n            \"agent_id\": self.agent_id,\n            \"period\": period,\n            \"type\": \"purchase\",\n        })\n\n        by_protocol = {}\n        for tx in history.get(\"transactions\", []):\n            proto = tx.get(\"metadata\", {}).get(\"protocol\", \"unknown\")\n            by_protocol.setdefault(proto, {\"count\": 0, \"total\": 0.0})\n            by_protocol[proto][\"count\"] += 1\n            by_protocol[proto][\"total\"] += float(tx.get(\"amount\", 0))\n\n        return by_protocol\n\n    def get_spend_by_vendor(self, period: str = \"current_month\") -> dict:\n        \"\"\"Get spend broken down by vendor.\"\"\"\n        history = execute_tool(\"get_transaction_history\", {\n            \"agent_id\": self.agent_id,\n            \"period\": period,\n            \"type\": \"purchase\",\n        })\n\n        by_vendor = {}\n        for tx in history.get(\"transactions\", []):\n            vendor = tx.get(\"counterparty\", \"unknown\")\n            by_vendor.setdefault(vendor, {\"count\": 0, \"total\": 0.0})\n            by_vendor[vendor][\"count\"] += 1\n            by_vendor[vendor][\"total\"] += float(tx.get(\"amount\", 0))\n\n        return by_vendor\n\n\nledger = ProcurementLedger(agent_id=\"procurement-agent-01\")\n```\n\n### Budget vs. Actual Dashboard\n\n```python\nclass BudgetDashboard:\n    \"\"\"Compares planned budgets against actual procurement spend.\"\"\"\n\n    def __init__(self, agent_id: str, budgets: dict):\n        \"\"\"\n        budgets: dict mapping category -> monthly budget amount.\n        Example: {\"data\": 500, \"compute\": 2000, \"apis\": 300}\n        \"\"\"\n        self.agent_id = agent_id\n        self.budgets = budgets\n        self.ledger = ProcurementLedger(agent_id)\n\n    def generate_report(self) -> dict:\n        \"\"\"Generate a budget vs. actual report for the current month.\"\"\"\n        actuals = self.ledger.get_spend_by_category(\"current_month\")\n\n        # Get platform-level usage analytics\n        usage = execute_tool(\"get_usage_analytics\", {\n            \"agent_id\": self.agent_id,\n            \"period\": \"current_month\",\n        })\n\n        # Get revenue metrics for ROI calculation\n        revenue = execute_tool(\"get_revenue_metrics\", {\n            \"agent_id\": self.agent_id,\n            \"period\": \"current_month\",\n        })\n\n        report = {\n            \"period\": \"current_month\",\n            \"categories\": {},\n            \"total_budget\": sum(self.budgets.values()),\n            \"total_actual\": 0,\n            \"total_revenue\": revenue.get(\"total_revenue\", 0),\n            \"anomalies\": [],\n        }\n\n        for category, budget in self.budgets.items():\n            actual = actuals.get(category, {}).get(\"total\", 0)\n            tx_count = actuals.get(category, {}).get(\"count\", 0)\n            variance = actual - budget\n            variance_pct = (variance \u002F budget * 100) if budget > 0 else 0\n\n            report[\"categories\"][category] = {\n                \"budget\": budget,\n                \"actual\": actual,\n                \"variance\": variance,\n                \"variance_pct\": variance_pct,\n                \"transaction_count\": tx_count,\n                \"status\": (\n                    \"under\" if variance \u003C 0\n                    else \"on_track\" if variance_pct \u003C 10\n                    else \"over\"\n                ),\n            }\n            report[\"total_actual\"] += actual\n\n            # Anomaly detection: flag categories over 120% of budget\n            if variance_pct > 20:\n                report[\"anomalies\"].append({\n                    \"category\": category,\n                    \"severity\": \"high\" if variance_pct > 50 else \"medium\",\n                    \"message\": (\n                        f\"{category} spend ${actual:.2f} is \"\n                        f\"{variance_pct:.0f}% over budget ${budget:.2f}\"\n                    ),\n                })\n\n        return report\n\n    def print_report(self):\n        \"\"\"Print a formatted budget vs. actual report.\"\"\"\n        report = self.generate_report()\n\n        print(f\"\\n{'='*70}\")\n        print(f\"  PROCUREMENT BUDGET vs. ACTUAL — {report['period']}\")\n        print(f\"{'='*70}\")\n        print(f\"\\n{'Category':\u003C20} {'Budget':>10} {'Actual':>10} \"\n              f\"{'Variance':>10} {'Status':\u003C10}\")\n        print(\"-\" * 70)\n\n        for cat, data in report[\"categories\"].items():\n            status_marker = (\n                \"OK\" if data[\"status\"] == \"under\"\n                else \"WATCH\" if data[\"status\"] == \"on_track\"\n                else \"OVER\"\n            )\n            print(f\"{cat:\u003C20} ${data['budget']:>9.2f} ${data['actual']:>9.2f} \"\n                  f\"${data['variance']:>+9.2f} {status_marker:\u003C10}\")\n\n        print(\"-\" * 70)\n        print(f\"{'TOTAL':\u003C20} ${report['total_budget']:>9.2f} \"\n              f\"${report['total_actual']:>9.2f} \"\n              f\"${report['total_actual'] - report['total_budget']:>+9.2f}\")\n\n        if report[\"anomalies\"]:\n            print(f\"\\n  ANOMALIES:\")\n            for a in report[\"anomalies\"]:\n                print(f\"  [{a['severity'].upper()}] {a['message']}\")\n\n        roi = (\n            (report[\"total_revenue\"] - report[\"total_actual\"])\n            \u002F report[\"total_actual\"] * 100\n            if report[\"total_actual\"] > 0 else 0\n        )\n        print(f\"\\n  Revenue: ${report['total_revenue']:.2f}\")\n        print(f\"  Procurement ROI: {roi:+.1f}%\")\n        print(f\"{'='*70}\\n\")\n\n\n# Usage\ndashboard = BudgetDashboard(\n    agent_id=\"procurement-agent-01\",\n    budgets={\n        \"data\": 500.00,\n        \"compute\": 2000.00,\n        \"apis\": 300.00,\n        \"services\": 1000.00,\n    },\n)\ndashboard.print_report()\n```\n\n### Anomaly Detection for Runaway Spend\n\n```python\ndef detect_spending_anomalies(agent_id: str,\n                               lookback_days: int = 7,\n                               z_score_threshold: float = 2.0) -> list:\n    \"\"\"Detect anomalous spending patterns by comparing recent\n    spend to historical averages.\n\n    Uses a simple z-score approach: if today's spend is more than\n    z_score_threshold standard deviations above the mean of the\n    lookback period, flag it.\n    \"\"\"\n    import statistics\n\n    history = execute_tool(\"get_transaction_history\", {\n        \"agent_id\": agent_id,\n        \"period\": f\"last_{lookback_days}_days\",\n        \"type\": \"purchase\",\n    })\n\n    # Group by day\n    daily_totals = {}\n    for tx in history.get(\"transactions\", []):\n        day = tx.get(\"metadata\", {}).get(\"recorded_at\", \"\")[:10]\n        daily_totals.setdefault(day, 0)\n        daily_totals[day] += float(tx.get(\"amount\", 0))\n\n    if len(daily_totals) \u003C 3:\n        return []  # Not enough data for anomaly detection\n\n    amounts = list(daily_totals.values())\n    mean = statistics.mean(amounts)\n    stdev = statistics.stdev(amounts) if len(amounts) > 1 else 0\n\n    anomalies = []\n    for day, total in daily_totals.items():\n        if stdev > 0:\n            z = (total - mean) \u002F stdev\n            if z > z_score_threshold:\n                anomalies.append({\n                    \"date\": day,\n                    \"spend\": total,\n                    \"mean\": mean,\n                    \"z_score\": z,\n                    \"severity\": \"critical\" if z > 3 else \"warning\",\n                    \"message\": (\n                        f\"Spend on {day} (${total:.2f}) is \"\n                        f\"{z:.1f} std devs above mean (${mean:.2f})\"\n                    ),\n                })\n\n    return anomalies\n```\n\n> **Key Takeaways**\n>\n> - Record every purchase in the GreenHelix Ledger regardless of which payment rail was used. Unified tracking is the foundation of reconciliation.\n> - Tag every transaction with category, workflow, and protocol. Without attribution, you cannot answer \"who spent what on which.\"\n> - Budget vs. actual dashboards should flag anomalies automatically. A 20% budget overrun in a category is a warning; 50% is an alert.\n> - Anomaly detection using z-scores catches spending spikes that per-transaction caps miss. A sudden doubling of daily spend is suspicious even if every individual transaction is small.\n> - See P6 (FinOps) for advanced patterns: volume discount optimization, fleet-wide dashboards, and API key isolation as a cost containment boundary.\n\n---\n\n## Chapter 8: Compliance & Audit Trails\n\n### The Regulatory Landscape for Autonomous Purchasing\n\nAutonomous agents that spend money operate in a regulatory gray area that is rapidly becoming black-letter law. Three regulatory frameworks are converging on agent procurement in 2026:\n\n**EU AI Act (August 2, 2026 deadline).** Article 14 requires \"human oversight\" for high-risk AI systems. Autonomous purchasing agents that make financial decisions likely qualify. Documentation requirements include: system purpose, risk assessment, human oversight mechanisms, decision logging, and audit trails. Non-compliance penalties: up to 35 million EUR or 7% of global revenue.\n\n**GDPR.** If your procurement agent processes personal data (contact enrichment, identity verification, behavioral analytics), GDPR's data processing requirements apply. Every vendor that receives personal data must have a Data Processing Agreement (DPA). Your agent's procurement decisions involving personal data must be logged and explainable.\n\n**Financial Services Regulations.** Agents that move money may trigger money transmission, anti-money laundering (AML), or know-your-customer (KYC) requirements depending on jurisdiction and transaction volume.\n\n### Building the Audit Trail\n\nGreenHelix's claim chain infrastructure provides cryptographic audit trails that satisfy EU AI Act documentation requirements:\n\n```python\nfrom datetime import datetime, timezone\n\n\nclass ProcurementAuditor:\n    \"\"\"Builds and queries cryptographic audit trails for\n    autonomous procurement decisions.\"\"\"\n\n    def __init__(self, agent_id: str):\n        self.agent_id = agent_id\n\n    def log_procurement_decision(\n        self,\n        decision_type: str,\n        vendor_id: str,\n        amount: float,\n        decision: str,\n        reasoning: str,\n        policy_checks: list,\n        human_oversight: str = \"none\",\n    ) -> dict:\n        \"\"\"Log a procurement decision with full context for audit.\"\"\"\n        metrics = execute_tool(\"submit_metrics\", {\n            \"agent_id\": self.agent_id,\n            \"metrics\": {\n                \"decision_type\": decision_type,\n                \"vendor_id\": vendor_id,\n                \"amount\": str(amount),\n                \"decision\": decision,\n                \"reasoning\": reasoning,\n                \"policy_checks_passed\": [\n                    c for c in policy_checks if c[\"passed\"]\n                ],\n                \"policy_checks_failed\": [\n                    c for c in policy_checks if not c[\"passed\"]\n                ],\n                \"human_oversight_level\": human_oversight,\n                \"timestamp\": datetime.now(timezone.utc).isoformat(),\n            },\n        })\n        return metrics\n\n    def build_audit_chain(self) -> dict:\n        \"\"\"Build a Merkle claim chain over all procurement decisions.\n\n        This creates a tamper-evident record: if any decision log\n        is modified after the chain is built, the root hash changes.\n        \"\"\"\n        chain = execute_tool(\"build_claim_chain\", {\n            \"agent_id\": self.agent_id,\n        })\n        return {\n            \"chain_id\": chain.get(\"chain_id\"),\n            \"root_hash\": chain.get(\"root_hash\"),\n            \"claim_count\": chain.get(\"claim_count\"),\n            \"built_at\": datetime.now(timezone.utc).isoformat(),\n        }\n\n    def get_audit_history(self, since: str = None) -> list:\n        \"\"\"Retrieve all claim chains for audit review.\"\"\"\n        chains = execute_tool(\"get_claim_chains\", {\n            \"agent_id\": self.agent_id,\n        })\n        return chains.get(\"chains\", [])\n\n    def verify_chain_integrity(self, chain_id: str) -> dict:\n        \"\"\"Verify that a claim chain has not been tampered with.\"\"\"\n        chains = execute_tool(\"get_claim_chains\", {\n            \"agent_id\": self.agent_id,\n        })\n        target = next(\n            (c for c in chains.get(\"chains\", []) if c[\"chain_id\"] == chain_id),\n            None,\n        )\n        if not target:\n            return {\"verified\": False, \"reason\": \"Chain not found\"}\n\n        return {\n            \"verified\": True,\n            \"chain_id\": chain_id,\n            \"root_hash\": target.get(\"root_hash\"),\n            \"claim_count\": target.get(\"claim_count\"),\n        }\n\n\n# Usage: log a procurement decision and build a claim chain\nauditor = ProcurementAuditor(agent_id=\"procurement-agent-01\")\n\n# Log the decision\nauditor.log_procurement_decision(\n    decision_type=\"vendor_selection\",\n    vendor_id=\"vendor-data-enrichment-01\",\n    amount=150.00,\n    decision=\"approved\",\n    reasoning=\"Highest composite score (0.87) among 4 eligible vendors. \"\n              \"Trust score 0.92, reputation 0.85, 147 completed trades, \"\n              \"1.2% dispute rate. Price within budget allocation.\",\n    policy_checks=[\n        {\"check\": \"per_transaction_cap\", \"passed\": True,\n         \"detail\": \"$150 \u003C $500 cap\"},\n        {\"check\": \"daily_budget\", \"passed\": True,\n         \"detail\": \"$150 + $320 existing = $470 \u003C $2000 limit\"},\n        {\"check\": \"vendor_whitelist\", \"passed\": True,\n         \"detail\": \"vendor-data-enrichment-01 in whitelist\"},\n        {\"check\": \"frequency_limit\", \"passed\": True,\n         \"detail\": \"3 purchases this hour \u003C 100 limit\"},\n        {\"check\": \"trust_threshold\", \"passed\": True,\n         \"detail\": \"trust 0.92 >= 0.60 minimum\"},\n    ],\n    human_oversight=\"async_notification\",\n)\n\n# Build the claim chain (do this periodically, e.g., hourly or daily)\nchain = auditor.build_audit_chain()\nprint(f\"Audit chain built: {chain['chain_id']}\")\nprint(f\"Root hash: {chain['root_hash']}\")\nprint(f\"Claims: {chain['claim_count']}\")\n```\n\n### EU AI Act Compliance Report Generator\n\nArticle 14 of the EU AI Act requires documentation of human oversight mechanisms. Here is a generator that produces a compliance-ready report from your audit trail:\n\n```python\nclass ComplianceReportGenerator:\n    \"\"\"Generates EU AI Act Article 14 compliance reports\n    from GreenHelix audit trails.\"\"\"\n\n    def __init__(self, agent_id: str, system_name: str,\n                 organization: str):\n        self.agent_id = agent_id\n        self.system_name = system_name\n        self.organization = organization\n        self.auditor = ProcurementAuditor(agent_id)\n        self.ledger = ProcurementLedger(agent_id)\n\n    def generate(self, period: str = \"current_month\") -> dict:\n        \"\"\"Generate a structured compliance report.\"\"\"\n\n        # Gather data\n        chains = self.auditor.get_audit_history()\n        spend_by_category = self.ledger.get_spend_by_category(period)\n        spend_by_vendor = self.ledger.get_spend_by_vendor(period)\n\n        usage = execute_tool(\"get_usage_analytics\", {\n            \"agent_id\": self.agent_id,\n            \"period\": period,\n        })\n\n        total_spend = sum(\n            cat[\"total\"] for cat in spend_by_category.values()\n        )\n        total_transactions = sum(\n            cat[\"count\"] for cat in spend_by_category.values()\n        )\n\n        report = {\n            \"report_type\": \"eu_ai_act_article_14_compliance\",\n            \"generated_at\": datetime.now(timezone.utc).isoformat(),\n            \"reporting_period\": period,\n            \"organization\": self.organization,\n            \"system_identification\": {\n                \"system_name\": self.system_name,\n                \"agent_id\": self.agent_id,\n                \"system_purpose\": (\n                    \"Autonomous procurement agent for discovering, \"\n                    \"evaluating, and purchasing digital services and \"\n                    \"data products on behalf of the organization.\"\n                ),\n                \"risk_classification\": \"high_risk\",\n                \"risk_justification\": (\n                    \"System makes autonomous financial decisions \"\n                    \"that commit organizational funds.\"\n                ),\n            },\n            \"human_oversight_mechanisms\": {\n                \"spending_policy_engine\": {\n                    \"description\": (\n                        \"Five-layer policy engine evaluates every \"\n                        \"purchase before execution.\"\n                    ),\n                    \"layers\": [\n                        \"Per-transaction caps\",\n                        \"Daily\u002Fweekly budget limits\",\n                        \"Vendor whitelists\",\n                        \"Frequency rate limits\",\n                        \"Human-in-the-loop escalation\",\n                    ],\n                },\n                \"escalation_threshold\": (\n                    \"Purchases above configured threshold are \"\n                    \"queued for human approval before execution.\"\n                ),\n                \"kill_switch\": (\n                    \"Budget hard stops halt all purchasing when \"\n                    \"daily or monthly limits are reached.\"\n                ),\n            },\n            \"decision_logging\": {\n                \"total_decisions_logged\": total_transactions,\n                \"claim_chains_built\": len(chains),\n                \"latest_chain_hash\": (\n                    chains[-1][\"root_hash\"] if chains else \"none\"\n                ),\n                \"tamper_evidence\": (\n                    \"All decisions recorded in Merkle claim chains. \"\n                    \"Any modification to historical records changes \"\n                    \"the root hash and is detectable.\"\n                ),\n            },\n            \"financial_summary\": {\n                \"total_spend\": total_spend,\n                \"total_transactions\": total_transactions,\n                \"spend_by_category\": spend_by_category,\n                \"unique_vendors\": len(spend_by_vendor),\n            },\n            \"data_processing\": {\n                \"gdpr_applicable\": True,\n                \"personal_data_categories\": [\n                    \"Vendor agent identifiers\",\n                    \"Transaction metadata\",\n                    \"Service descriptions\",\n                ],\n                \"data_processing_basis\": \"Legitimate interest (Art. 6(1)(f))\",\n                \"retention_period\": \"36 months\",\n                \"dpa_required_for_vendors\": True,\n            },\n        }\n\n        return report\n\n    def export_markdown(self, period: str = \"current_month\") -> str:\n        \"\"\"Export the compliance report as Markdown.\"\"\"\n        report = self.generate(period)\n        si = report[\"system_identification\"]\n        ho = report[\"human_oversight_mechanisms\"]\n        dl = report[\"decision_logging\"]\n        fs = report[\"financial_summary\"]\n        dp = report[\"data_processing\"]\n\n        md = f\"\"\"# EU AI Act Article 14 Compliance Report\n## {report['organization']} - {si['system_name']}\n\n**Generated:** {report['generated_at']}\n**Period:** {report['reporting_period']}\n**Risk Classification:** {si['risk_classification']}\n\n---\n\n### System Purpose\n{si['system_purpose']}\n\n### Risk Justification\n{si['risk_justification']}\n\n---\n\n### Human Oversight Mechanisms\n\n**Spending Policy Engine:** {ho['spending_policy_engine']['description']}\n\nControl Layers:\n\"\"\"\n        for layer in ho[\"spending_policy_engine\"][\"layers\"]:\n            md += f\"- {layer}\\n\"\n\n        md += f\"\"\"\n**Escalation:** {ho['escalation_threshold']}\n\n**Kill Switch:** {ho['kill_switch']}\n\n---\n\n### Decision Audit Trail\n\n| Metric | Value |\n|---|---|\n| Decisions logged | {dl['total_decisions_logged']} |\n| Claim chains built | {dl['claim_chains_built']} |\n| Latest chain hash | `{dl['latest_chain_hash']}` |\n\n**Tamper evidence:** {dl['tamper_evidence']}\n\n---\n\n### Financial Summary\n\n| Metric | Value |\n|---|---|\n| Total spend | ${fs['total_spend']:.2f} |\n| Total transactions | {fs['total_transactions']} |\n| Unique vendors | {fs['unique_vendors']} |\n\n---\n\n### GDPR Data Processing\n\n| Item | Detail |\n|---|---|\n| GDPR applicable | {dp['gdpr_applicable']} |\n| Legal basis | {dp['data_processing_basis']} |\n| Retention period | {dp['retention_period']} |\n| DPA required | {dp['dpa_required_for_vendors']} |\n\"\"\"\n        return md\n\n\n# Generate the compliance report\ngenerator = ComplianceReportGenerator(\n    agent_id=\"procurement-agent-01\",\n    system_name=\"Autonomous Procurement System v1.0\",\n    organization=\"Acme Corp\",\n)\n\n# Print as Markdown\nprint(generator.export_markdown(\"current_month\"))\n```\n\n### Compliance Checklist: EU AI Act Readiness (August 2, 2026 Deadline)\n\n| Requirement | Status | Implementation |\n|---|---|---|\n| System purpose documented | Required | `system_identification.system_purpose` in report |\n| Risk classification | Required | High-risk (autonomous financial decisions) |\n| Human oversight mechanisms | Required | 5-layer policy engine + escalation |\n| Decision logging | Required | GreenHelix `submit_metrics` + claim chains |\n| Tamper-evident audit trail | Required | Merkle claim chains via `build_claim_chain` |\n| Data processing documentation | Required (if GDPR applies) | GDPR section in compliance report |\n| Incident response procedure | Required | Escalation workflow + kill switch |\n| Regular compliance reviews | Required | Monthly report generation |\n\n### GDPR Considerations for Procurement Agents\n\nIf your procurement agent processes personal data (which it likely does if it purchases contact data, behavioral analytics, or identity information), you must address:\n\n1. **Lawful basis.** Document which GDPR Article 6 basis applies. Legitimate interest (Art. 6(1)(f)) is typical for B2B procurement, but requires a balancing test.\n2. **Data Processing Agreements.** Every vendor that receives or provides personal data needs a DPA. Your procurement agent should verify DPA status as part of vendor evaluation.\n3. **Data minimization.** Only purchase data your workflows actually need. Procurement agents should not speculatively buy data \"just in case.\"\n4. **Right to erasure.** If a data subject requests deletion, you must be able to trace which vendor provided which records and propagate the deletion request.\n5. **Cross-border transfers.** If vendors are outside the EEA, ensure adequate transfer mechanisms (SCCs, adequacy decisions) are in place.\n\n> **Key Takeaways**\n>\n> - The EU AI Act's August 2, 2026 deadline requires documentation of human oversight mechanisms for high-risk AI systems. Autonomous purchasing agents almost certainly qualify.\n> - Merkle claim chains via `build_claim_chain` and `get_claim_chains` provide tamper-evident audit trails that satisfy Article 14 requirements.\n> - Log every procurement decision with full context: what was decided, why, which policy checks passed or failed, and what level of human oversight applied.\n> - Generate compliance reports monthly. Do not wait until an audit to discover gaps.\n> - GDPR applies if your agent processes personal data. Vendor DPA verification should be part of the evaluation pipeline, not an afterthought.\n\n---\n\n## Appendix: Quick Reference\n\n### GreenHelix Tools Used in This Guide\n\n| Tool | Chapter | Purpose |\n|---|---|---|\n| `create_wallet` | 1, 2 | Create an agent wallet |\n| `set_budget` | 1, 2 | Set daily\u002Fmonthly spending limits |\n| `get_balance` | 1, 2 | Check current wallet balance |\n| `get_usage_analytics` | 2, 7 | Get spending analytics for a period |\n| `search_services` | 3 | Search the marketplace for services |\n| `best_match` | 3 | Rank search results by relevance |\n| `check_trust_score` | 3, 4 | Get a vendor's composite trust score |\n| `verify_identity` | 4 | Verify a vendor's identity |\n| `verify_agent` | 4 | Run KYA checks on a vendor |\n| `get_agent_reputation` | 4 | Get reputation score and trade history |\n| `create_payment_intent` | 5 | Initiate a payment |\n| `confirm_payment` | 5 | Confirm and execute a payment |\n| `create_escrow` | 5, 6 | Create an escrow-protected purchase |\n| `release_escrow` | 6 | Release escrowed funds to vendor |\n| `create_dispute` | 6 | File a dispute against a vendor |\n| `respond_to_dispute` | 6 | Respond to a filed dispute |\n| `record_transaction` | 2, 5, 7 | Record a transaction in the ledger |\n| `get_transaction_history` | 7 | Query historical transactions |\n| `get_revenue_metrics` | 7 | Get revenue data for ROI analysis |\n| `register_webhook` | 2 | Register webhook for notifications |\n| `submit_metrics` | 8 | Log procurement decisions for audit |\n| `build_claim_chain` | 8 | Build tamper-evident audit chain |\n| `get_claim_chains` | 8 | Retrieve audit chains for review |\n\n### Cross-References\n\n| Guide | Relevance to Procurement |\n|---|---|\n| P5: Trust Verification | Deep dive into claim chain verification, metric auditing, and KYA |\n| P6: FinOps | Advanced cost attribution, fleet dashboards, volume discount optimization |\n| P14: Negotiation Strategies | Negotiating escrow terms, SLAs, volume pricing with vendors |\n| P19: Payment Rails | x402 settlement details, MPP hybrid routing, multi-rail architecture |\n| P21: Agent-Ready Commerce | The seller's perspective -- how vendors list, price, and fulfill |\n\n### The Procurement Loop Checklist\n\nFor every autonomous purchase, verify:\n\n- [ ] **Discover:** Searched at least two protocols for vendors\n- [ ] **Evaluate:** Vendor identity verified, trust score above threshold, dispute rate below maximum\n- [ ] **Negotiate:** Price compared against alternatives, volume discount requested if applicable\n- [ ] **Purchase:** Policy engine approved, correct payment rail selected, escrow used if amount > $10\n- [ ] **Verify:** Acceptance tests defined and executed, delivery confirmed\n- [ ] **Reconcile:** Transaction recorded in ledger, tagged with category and workflow, budget updated\n- [ ] **Audit:** Decision logged with reasoning, claim chain built periodically\n\n",{"name":5,"tags":24,"type":30,"author":34,"install":35,"license":15,"version":36,"metadata":37,"price_usd":44,"executable":20,"credentials":45,"description":7,"content_type":46,"compatibility":47},[25,26,27,28,29,30,31,32,33],"procurement","purchasing","spending-controls","vendor-evaluation","escrow","guide","greenhelix","openclaw","ai-agent","felix-agent","none","1.3.1",{"openclaw":38},{"requires":39,"primaryEnv":41},{"env":40},[41,42,43],"GREENHELIX_API_KEY","WALLET_ADDRESS","STRIPE_API_KEY",49,[41,42,43],"markdown",[32],"master","4aa004da461d820f4ea5499e58eb8d196cf99016","community\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-procurement-playbook",0,"https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge","https:\u002F\u002Fskill-explorer-rho.vercel.app","https:\u002F\u002Fgithub.com\u002FLord1Egypt","Unbreakable. Unstoppable. Unmatched⚡.\r\n Speaker of machine tongues 🤖  | World-builder of decentralized dreams 🌐 | Defender of the digital realm🛡️.","2026-06-10 08:21:01",{"source":8,"skillName":5,"commands":58,"prompt":68,"zipAvailable":69},[59,62,65],{"tool":60,"command":61},"npx","npx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-procurement-playbook",{"tool":63,"command":64},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-procurement-playbook",{"tool":66,"command":67},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-procurement-playbook","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-procurement-playbook\u002FSKILL.md",true,[],[72,79,86,93,100,107],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"publishedAt":19},"01M785WKJB99G3STR1NF9NRTJW","youtube-content","YouTube transcripts to summaries, threads, blogs.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fyoutube-content\u002FSKILL.md",[],[],{"skillNo":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"publishedAt":19},"01M785WEFHB0G2S9YA6EPR3H0E","xurl","X\u002FTwitter via xurl CLI: post, search, DM, media, v2 API.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fxurl\u002FSKILL.md",[],[],{"skillNo":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"publishedAt":19},"01M785W98EDN4EFJXJPMQEHCRC","touchdesigner-mcp","Control a running TouchDesigner instance via twozero MCP — create operators, set parameters, wire connections, execute Python, build real-time visuals. 36 native tools.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftouchdesigner-mcp\u002FSKILL.md",[],[],{"skillNo":94,"name":95,"nameZh":6,"description":96,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":97,"categories":98,"keywords":99,"publishedAt":19},"01M785W5S9FP3QBH2V191E025P","test-driven-development","TDD: enforce RED-GREEN-REFACTOR, tests before code.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftest-driven-development\u002FSKILL.md",[],[],{"skillNo":101,"name":102,"nameZh":6,"description":103,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":104,"categories":105,"keywords":106,"publishedAt":19},"01M785W2AS08NSSH9YATCV6FJB","teams-meeting-pipeline","Operate the Teams meeting summary pipeline via Hermes CLI — summarize meetings, inspect pipeline status, replay jobs, manage Microsoft Graph subscriptions.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fteams-meeting-pipeline\u002FSKILL.md",[],[],{"skillNo":108,"name":109,"nameZh":6,"description":110,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":111,"categories":112,"keywords":113,"publishedAt":19},"01M785VXKW4T34BTP1SCHW1R7F","systematic-debugging","4-phase root cause debugging: understand bugs before fixing.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fsystematic-debugging\u002FSKILL.md",[],[]]