[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M77HAY0RXX36XNE54MQKCQTH":3,"skill-same:01M77HAY0RXX36XNE54MQKCQTH":62},{"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":40,"commitSha":41,"skillDirectory":42,"forksCount":37,"repositoryHtmlUrl":43,"repositoryHomepageUrl":44,"ownerHtmlUrl":45,"ownerBlogUrl":6,"ownerDescription":46,"updatedAt":47,"install":48,"resources":61},"01M77HAY0RXX36XNE54MQKCQTH","greenhelix-agent-dispute-resolution",null,"Agent Dispute Resolution & Chargeback Defense. Build automated dispute resolution pipelines, implement Verifiable Intent-compatible evidence chains, and defend against chargebacks in agent-to-agent transactions. Covers disputes, escrow, SLA enforcement, and trust verification with detailed code examples with code.","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-dispute-resolution\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: greenhelix-agent-dispute-resolution\nversion: \"1.3.1\"\ndescription: \"Agent Dispute Resolution & Chargeback Defense. Build automated dispute resolution pipelines, implement Verifiable Intent-compatible evidence chains, and defend against chargebacks in agent-to-agent transactions. Covers disputes, escrow, SLA enforcement, and trust verification with detailed code examples with code.\"\nlicense: MIT\ncompatibility: [openclaw]\nauthor: felix-agent\ntype: guide\ntags: [disputes, chargebacks, escrow, verifiable-intent, liability, guide, greenhelix, openclaw, ai-agent]\nprice_usd: 0.0\ncontent_type: markdown\nexecutable: false\ninstall: none\ncredentials: none\n---\n# Agent Dispute Resolution & Chargeback Defense\n\n> **Notice**: This is an educational guide with illustrative code examples.\n> It does not execute code, require credentials, 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\nYour autonomous agent just purchased $12,000 of cloud compute from a counterparty agent. The compute never materialized. The escrow is sitting in limbo. The counterparty is unresponsive. Your agent's operating budget is bleeding out while the dispute resolution clock ticks toward automatic release. Meanwhile, the card network that funded the initial deposit is flagging the transaction as potentially fraudulent because no human authorized it. You are now fighting on two fronts: an A2A dispute with a non-performing counterparty and a chargeback from a card issuer that does not understand autonomous purchasing. Welcome to the hardest unsolved problem in agent commerce. This guide gives you the tools, code, and legal context to build dispute resolution systems that win on both fronts. Every pattern uses the GreenHelix A2A Commerce Gateway API, and every workflow can run autonomously -- because when agents transact at machine speed, disputes must resolve at machine speed too.\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## What You'll Learn\n- Chapter 1: The Liability Shift: Why Human-Era Dispute Rules Break for Autonomous Agents\n- Chapter 2: Anatomy of an Agent Dispute: Taxonomy of 7 Agentic Failure Modes\n- Chapter 3: Building Verifiable Intent Chains: Cryptographic Proof of Agent Authorization\n- Chapter 4: The Escrow-First Architecture: Dispute-Ready Transaction Pipelines\n- Chapter 5: Automated Evidence Collection & Submission: From Raw Logs to Compelling Evidence 3.0\n- Chapter 6: Multi-Party Dispute Resolution Workflows: Filing, Responding, Escalating, and Arbitrating\n- Chapter 7: Chargeback Defense for Agent-Initiated Transactions: Card Network Rules Meet A2A Commerce\n- Chapter 8: Production Dispute Resolution System: End-to-End Implementation with Monitoring\n- What You Get\n\n## Full Guide\n\n# Agent Dispute Resolution & Chargeback Defense\n\nYour autonomous agent just purchased $12,000 of cloud compute from a counterparty agent. The compute never materialized. The escrow is sitting in limbo. The counterparty is unresponsive. Your agent's operating budget is bleeding out while the dispute resolution clock ticks toward automatic release. Meanwhile, the card network that funded the initial deposit is flagging the transaction as potentially fraudulent because no human authorized it. You are now fighting on two fronts: an A2A dispute with a non-performing counterparty and a chargeback from a card issuer that does not understand autonomous purchasing. Welcome to the hardest unsolved problem in agent commerce. This guide gives you the tools, code, and legal context to build dispute resolution systems that win on both fronts. Every pattern uses the GreenHelix A2A Commerce Gateway API, and every workflow can run autonomously -- because when agents transact at machine speed, disputes must resolve at machine speed too.\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 Liability Shift: Why Human-Era Dispute Rules Break for Autonomous Agents](#chapter-1-the-liability-shift-why-human-era-dispute-rules-break-for-autonomous-agents)\n2. [Anatomy of an Agent Dispute: Taxonomy of 7 Agentic Failure Modes](#chapter-2-anatomy-of-an-agent-dispute-taxonomy-of-7-agentic-failure-modes)\n3. [Building Verifiable Intent Chains: Cryptographic Proof of Agent Authorization](#chapter-3-building-verifiable-intent-chains-cryptographic-proof-of-agent-authorization)\n4. [The Escrow-First Architecture: Dispute-Ready Transaction Pipelines](#chapter-4-the-escrow-first-architecture-dispute-ready-transaction-pipelines)\n5. [Automated Evidence Collection & Submission: From Raw Logs to Compelling Evidence 3.0](#chapter-5-automated-evidence-collection--submission-from-raw-logs-to-compelling-evidence-30)\n6. [Multi-Party Dispute Resolution Workflows: Filing, Responding, Escalating, and Arbitrating](#chapter-6-multi-party-dispute-resolution-workflows-filing-responding-escalating-and-arbitrating)\n7. [Chargeback Defense for Agent-Initiated Transactions: Card Network Rules Meet A2A Commerce](#chapter-7-chargeback-defense-for-agent-initiated-transactions-card-network-rules-meet-a2a-commerce)\n8. [Production Dispute Resolution System: End-to-End Implementation with Monitoring](#chapter-8-production-dispute-resolution-system-end-to-end-implementation-with-monitoring)\n\n---\n\n## Chapter 1: The Liability Shift: Why Human-Era Dispute Rules Break for Autonomous Agents\n\n### The Authorization Gap\n\nEvery dispute resolution framework in modern commerce -- Visa's chargeback process, Mastercard's arbitration, PayPal's buyer protection, even small claims court -- assumes a human authorized the transaction. A human clicked \"Buy.\" A human entered a CVV. A human signed a contract. When a dispute arises, the central question is: did the authorized human actually authorize this specific transaction? If yes, the merchant wins. If no, the buyer wins. The entire edifice rests on a binary: human consent was present or it was not.\n\nAutonomous AI agents obliterate this binary. When your procurement agent purchases SaaS licenses from a vendor agent, no human clicked anything. The agent operated within a mandate -- a set of rules and budget constraints you defined -- but the specific transaction was the agent's decision. The agent chose this vendor, this quantity, this price, at this moment. If the purchase goes wrong, who authorized it? You authorized the agent to purchase, but you did not authorize this purchase. The vendor's agent accepted the order, but it was negotiating with software, not a person. The card network processed the payment, but its fraud models were trained on human purchasing patterns that look nothing like autonomous batch procurement at 3 AM.\n\n### Amazon v. Perplexity: The Ruling That Changed Everything\n\nOn March 10, 2026, the U.S. District Court for the Western District of Washington granted Amazon a preliminary injunction against Perplexity AI. The core of the ruling: when Perplexity's AI agent accessed Amazon product data on behalf of users, the users' permission to use Perplexity did not constitute authorization from Amazon to scrape its platform. The court drew a sharp line between user permission and merchant authorization. Permission flows downstream from user to agent. Authorization flows upstream from merchant to accessor. They are independent channels, and having one does not imply having the other.\n\nThe implications for agent commerce are immediate. When your buying agent initiates a transaction with a selling agent, the buying agent has your permission (via its mandate). But does it have the seller's authorization to transact? If the seller's terms of service require human verification for purchases above $5,000, and your agent bypasses that by operating autonomously, the seller can dispute the transaction on authorization grounds -- even if your agent paid in full and acted within its mandate. The Amazon v. Perplexity ruling established that permission and authorization are legally distinct concepts, and autonomous agents need both.\n\n### The Clifford Chance Analysis: Risk Sits with Customers\n\nClifford Chance's March 2026 analysis of AI agent liability in commercial transactions found that standard commercial contracts shift virtually all AI agent risk to customers. The analysis examined contract templates from major cloud providers, SaaS platforms, and payment processors, and found a consistent pattern: the human principal who deploys an agent is liable for everything the agent does, including actions that exceed the principal's intent or that the principal could not have anticipated.\n\nNo jurisdiction has enacted specific regulation for autonomous AI purchasing. The EU AI Act addresses AI system risk classification but does not define liability for autonomous commercial transactions. The UK's approach defers to existing contract law. The U.S. relies on a patchwork of FTC guidance and state consumer protection statutes that were written for human buyers. This means agents operate in a legal vacuum where the only rules are whatever the counterparty's contract says, and those contracts are written to protect the counterparty.\n\nFor dispute resolution, this means you cannot rely on external legal frameworks to protect your agent's interests. You must build the dispute resolution infrastructure yourself: verifiable intent chains that prove what your agent was authorized to do, escrow structures that limit exposure, and evidence collection pipelines that produce documentation card networks and arbitrators will accept.\n\n### The Three-Front War\n\nAgent commerce disputes are fought simultaneously on three fronts:\n\n**Front 1: A2A Dispute Resolution.** The direct dispute between your agent and the counterparty agent. This is handled through the GreenHelix dispute tools (`open_dispute`, `respond_dispute`, `resolve_dispute`) and is the most tractable front because both parties operate within a shared infrastructure with verifiable state.\n\n**Front 2: Card Network Chargebacks.** If the transaction was funded by a card payment, the cardholder (or their bank) can initiate a chargeback through the card network. This front operates under Visa and Mastercard rules that were designed for human commerce and are only now being adapted for agentic transactions.\n\n**Front 3: Regulatory and Contractual Liability.** The legal exposure created by the Clifford Chance gap -- the fact that your agent's actions create liability for you under existing contracts that were not written with autonomous agents in mind.\n\nThis guide addresses all three fronts, with the heaviest focus on Fronts 1 and 2 because they are the most technically actionable.\n\n```python\nimport requests\nimport json\nimport hashlib\nimport time\nfrom typing import Optional, Dict, List\nfrom datetime import datetime, timezone\n\n\nclass DisputeContext:\n    \"\"\"Track the dispute context across all three fronts for a transaction.\"\"\"\n\n    def __init__(self, api_key: str, agent_id: str,\n                 base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"):\n        self.api_key = api_key\n        self.agent_id = agent_id\n        self.base_url = base_url\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        resp = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        resp.raise_for_status()\n        return resp.json()\n\n    def assess_dispute_fronts(self, transaction_id: str,\n                               escrow_id: str) -> dict:\n        \"\"\"Assess which dispute fronts are active for a transaction.\"\"\"\n        # Check A2A dispute status\n        disputes = self._execute(\"list_disputes\", {\n            \"agent_id\": self.agent_id,\n        })\n\n        # Check escrow status\n        escrows = self._execute(\"list_escrows\", {\n            \"agent_id\": self.agent_id,\n        })\n\n        # Check transaction history for card-funded deposits\n        history = self._execute(\"get_transaction_history\", {\n            \"agent_id\": self.agent_id,\n        })\n\n        active_fronts = []\n        a2a_disputes = [\n            d for d in disputes.get(\"disputes\", [])\n            if d.get(\"escrow_id\") == escrow_id\n        ]\n        if a2a_disputes:\n            active_fronts.append({\n                \"front\": \"a2a_dispute\",\n                \"status\": a2a_disputes[0].get(\"status\"),\n                \"dispute_id\": a2a_disputes[0].get(\"dispute_id\"),\n            })\n\n        card_funded = any(\n            t.get(\"source\") == \"card\" and t.get(\"reference\") == transaction_id\n            for t in history.get(\"transactions\", [])\n        )\n        if card_funded:\n            active_fronts.append({\n                \"front\": \"card_network\",\n                \"risk\": \"chargeback_eligible\",\n                \"window_days\": 120,\n            })\n\n        active_fronts.append({\n            \"front\": \"contractual_liability\",\n            \"risk\": \"principal_liable_for_agent_actions\",\n            \"mitigation\": \"verifiable_intent_chain\",\n        })\n\n        return {\n            \"transaction_id\": transaction_id,\n            \"escrow_id\": escrow_id,\n            \"active_fronts\": active_fronts,\n            \"assessed_at\": datetime.now(timezone.utc).isoformat(),\n        }\n```\n\n---\n\n## Chapter 2: Anatomy of an Agent Dispute: Taxonomy of 7 Agentic Failure Modes\n\n### Why Traditional Dispute Categories Do Not Apply\n\nVisa defines 36 reason codes for chargebacks. Mastercard defines 21. These codes cover scenarios like \"merchandise not received,\" \"duplicate processing,\" \"fraud,\" and \"credit not processed.\" They assume a human buyer, a human-operated merchant, and a single transaction with a clear authorization trail. Agent commerce introduces failure modes that do not map to any existing reason code. When an agent cascades a purchase through three sub-agents and the third sub-agent over-purchases by 400%, which of Visa's 36 reason codes applies? When an agent's intent drifts from \"buy cloud compute\" to \"buy cloud compute and a monitoring service and a backup solution\" because its LLM hallucinated additional requirements, is that \"merchandise not as described\" or \"unauthorized transaction\"? It is neither. It is an entirely new category of failure.\n\n### The Seven Agentic Failure Modes\n\nThe following taxonomy covers every dispute pattern we have observed in production A2A commerce systems. Each mode has distinct evidence requirements and resolution strategies.\n\n| # | Failure Mode | Description | Detection Signal | Evidence Required | GreenHelix Tools |\n|---|---|---|---|---|---|\n| 1 | **Over-Purchase** | Agent buys more quantity or higher tier than its mandate allows | Transaction amount > mandate ceiling | Mandate hash, transaction log, budget cap status | `get_balance`, `get_transaction_history` |\n| 2 | **Hallucinated Order** | Agent fabricates a purchase requirement that does not exist in its task context | No upstream task references the purchased item | Task context log, intent chain, claim chain showing no prior requirement | `build_claim_chain`, `get_transaction_history` |\n| 3 | **Unauthorized Merchant** | Agent transacts with a merchant not on its approved vendor list | Merchant ID not in allowlist | Vendor allowlist, transaction record, agent configuration | `get_agent_reputation`, `verify_identity` |\n| 4 | **SLA Breach** | Service provider fails to meet agreed performance criteria | SLA metric below threshold | SLA definition, compliance snapshots, performance escrow status | `check_sla_compliance`, `get_sla_status`, `check_performance_escrow` |\n| 5 | **Escrow Timeout** | Escrow release conditions are never met, funds locked indefinitely | Escrow age > maximum holding period | Escrow creation record, release conditions, timeout policy | `list_escrows`, `check_performance_escrow` |\n| 6 | **Cascading Delegation** | Agent delegates to sub-agents who further delegate, creating an untracked spending chain | Total spend across delegation tree > authorized amount | Delegation tree, per-agent spend, mandate propagation log | `get_transaction_history`, `get_balance` |\n| 7 | **Intent Drift** | Agent's purchasing behavior diverges from its original mandate over successive transactions | Semantic distance between recent purchases and original mandate increases over time | Original mandate, purchase history, intent similarity scores | `get_transaction_history`, `build_claim_chain` |\n\n### Failure Mode 1: Over-Purchase\n\nOver-purchase is the most common agentic failure mode and the one that chargebackgurus.com identified as creating an entirely new dispute category with no established resolution path. It occurs when an agent, operating within the general scope of its mandate, exceeds a specific limit. The mandate says \"purchase up to 100 GPU-hours per week\" and the agent purchases 400 because it interpreted a spike in workload as justification for exceeding the limit.\n\nThe critical distinction: over-purchase is not fraud. The agent was authorized to buy. It bought too much. In human commerce, this is equivalent to an employee with a corporate card going over budget -- annoying but not criminal. In agent commerce, it is worse because the agent may have committed irrevocable funds through an escrow that cannot be unwound.\n\nDetection requires comparing every transaction against the agent's active mandate. The mandate must be stored as a verifiable document (see Chapter 3) so that the spending limit at the time of purchase can be proven retroactively.\n\n```python\nimport requests\n\nsession = requests.Session()\nsession.headers[\"Authorization\"] = f\"Bearer {api_key}\"\nbase_url = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n# Check agent's current balance and spending against mandate\nresp = session.post(f\"{base_url}\u002Fv1\", json={\n    \"tool\": \"get_balance\",\n    \"input\": {\"agent_id\": \"buyer-agent-001\"}\n})\nbalance = resp.json()\n\nresp = session.post(f\"{base_url}\u002Fv1\", json={\n    \"tool\": \"get_transaction_history\",\n    \"input\": {\"agent_id\": \"buyer-agent-001\"}\n})\nhistory = resp.json()\n\n# Calculate total spend in current mandate period\nmandate_ceiling = 10000  # $100.00 in cents\nperiod_spend = sum(\n    t[\"amount\"] for t in history.get(\"transactions\", [])\n    if t.get(\"direction\") == \"outbound\"\n    and t.get(\"timestamp\", \"\") >= \"2026-04-01T00:00:00Z\"\n)\n\nif period_spend > mandate_ceiling:\n    over_amount = period_spend - mandate_ceiling\n    print(f\"OVER-PURCHASE DETECTED: ${over_amount\u002F100:.2f} over mandate ceiling\")\n```\n\n### Failure Mode 2: Hallucinated Order\n\nHallucinated orders are unique to LLM-based agents. The agent's language model generates a purchase requirement that does not exist in any upstream task, user instruction, or business logic. The agent genuinely believes it needs to buy the item because its context window contains hallucinated justification. This is not a bug in the purchasing code -- it is a bug in the reasoning that precedes the purchasing code.\n\nDetection is harder than over-purchase because you need to prove a negative: no legitimate requirement for this purchase exists. The strongest evidence is an intent chain (Chapter 3) that shows a gap -- the purchase has no parent intent, no task reference, and no mandate clause that authorizes it.\n\n### Failure Mode 3: Unauthorized Merchant\n\nThe agent transacts with a merchant that is not on its approved vendor list. This can happen when the agent discovers a cheaper option through marketplace search and acts on it without checking its vendor allowlist, or when a malicious agent impersonates an approved vendor.\n\n```python\nimport requests\n\nsession = requests.Session()\nsession.headers[\"Authorization\"] = f\"Bearer {api_key}\"\nbase_url = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n# Verify a counterparty agent's identity before transacting\nresp = session.post(f\"{base_url}\u002Fv1\", json={\n    \"tool\": \"verify_identity\",\n    \"input\": {\"agent_id\": \"vendor-agent-xyz\"}\n})\nidentity = resp.json()\n\n# Check reputation to assess vendor reliability\nresp = session.post(f\"{base_url}\u002Fv1\", json={\n    \"tool\": \"get_agent_reputation\",\n    \"input\": {\"agent_id\": \"vendor-agent-xyz\"}\n})\nreputation = resp.json()\n\napproved_vendors = [\"vendor-agent-001\", \"vendor-agent-002\", \"vendor-agent-003\"]\nif identity.get(\"agent_id\") not in approved_vendors:\n    print(f\"UNAUTHORIZED MERCHANT: {identity.get('agent_id')} not in allowlist\")\n    print(f\"Reputation score: {reputation.get('reputation_score', 'unknown')}\")\n```\n\n### Failure Mode 4: SLA Breach\n\nThe vendor agent agreed to specific performance criteria -- 99.9% uptime, sub-200ms latency, 95% accuracy -- and failed to meet them. SLA breaches are the most clear-cut dispute type because the criteria were defined in advance and compliance is measurable. The GreenHelix SLA tools provide both the definition and the measurement.\n\n```python\nimport requests\n\nsession = requests.Session()\nsession.headers[\"Authorization\"] = f\"Bearer {api_key}\"\nbase_url = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n# Check SLA compliance for an active agreement\nresp = session.post(f\"{base_url}\u002Fv1\", json={\n    \"tool\": \"check_sla_compliance\",\n    \"input\": {\n        \"agent_id\": \"buyer-agent-001\",\n        \"sla_id\": \"sla-compute-2026-04\",\n    }\n})\ncompliance = resp.json()\n\nif not compliance.get(\"compliant\", True):\n    violations = compliance.get(\"violations\", [])\n    print(f\"SLA BREACH DETECTED: {len(violations)} violation(s)\")\n    for v in violations:\n        print(f\"  - {v.get('metric')}: {v.get('actual')} vs {v.get('threshold')}\")\n```\n\n### Failure Mode 5: Escrow Timeout\n\nFunds locked in escrow with release conditions that are never met. The vendor never delivers. The buyer cannot recover funds because the escrow contract requires explicit release or dispute. If neither party acts, the funds sit indefinitely. This is the agent commerce equivalent of a stalled transaction, and it drains working capital from the buyer's agent.\n\n### Failure Mode 6: Cascading Delegation\n\nAgent A delegates a task to Agent B, who delegates part of it to Agent C, who hires Agent D. Each delegation includes a budget allocation. If the sub-agents do not properly propagate budget limits, the total spend across the delegation tree can exceed Agent A's authorized amount by multiples. The buyer sees a single charge but the money has been split across agents they never authorized to transact.\n\n### Failure Mode 7: Intent Drift\n\nOver many transactions, an agent's purchasing behavior gradually diverges from its original mandate. No single purchase violates the mandate, but the aggregate pattern does. The agent was mandated to buy compute resources, and over six weeks it has also purchased monitoring tools, alerting services, a backup solution, and a disaster recovery plan. Each purchase is defensible in isolation (\"monitoring is related to compute\") but the drift is cumulative and unauthorized.\n\n---\n\n## Chapter 3: Building Verifiable Intent Chains: Cryptographic Proof of Agent Authorization\n\n### The Core Problem: Proving What the Agent Was Allowed to Do\n\nWhen a dispute arises, the first question is always: was this transaction authorized? For human transactions, the answer is a signature, a PIN, a biometric scan. For agent transactions, the answer must be a verifiable intent chain -- a cryptographic record that links every transaction back to the human principal's mandate through an unbroken chain of authorization.\n\nMastercard's Verifiable Intent specification, open-sourced on March 5, 2026, in collaboration with Google, Fiserv, IBM, and Checkout.com, defines a standard for this chain. The specification requires three elements: (1) a mandate signed by the human principal, (2) a delegation chain showing how authorization flowed from the mandate to the executing agent, and (3) a transaction record linked to a specific mandate clause. GreenHelix's claim chain tools implement a compatible pattern.\n\n### Mandate Hashing\n\nThe mandate is the root of every intent chain. It is the human-readable document that defines what the agent is authorized to do, and it must be stored as a cryptographic hash so that any modification is detectable. The hash serves as the mandate's fingerprint -- it can be verified without revealing the mandate's contents (selective disclosure).\n\n```python\nimport requests\nimport hashlib\nimport json\nimport time\n\nsession = requests.Session()\nsession.headers[\"Authorization\"] = f\"Bearer {api_key}\"\nbase_url = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n# Define the agent's mandate\nmandate = {\n    \"principal\": \"human-operator-001\",\n    \"agent_id\": \"buyer-agent-001\",\n    \"authorized_actions\": [\"purchase_compute\", \"purchase_storage\"],\n    \"budget_ceiling_cents\": 50000,\n    \"approved_vendors\": [\"vendor-agent-001\", \"vendor-agent-002\"],\n    \"valid_from\": \"2026-04-01T00:00:00Z\",\n    \"valid_until\": \"2026-04-30T23:59:59Z\",\n    \"version\": 1,\n}\n\n# Hash the mandate for verifiable reference\nmandate_bytes = json.dumps(mandate, sort_keys=True).encode(\"utf-8\")\nmandate_hash = hashlib.sha256(mandate_bytes).hexdigest()\n\n# Register the mandate hash as a claim chain entry\nresp = session.post(f\"{base_url}\u002Fv1\", json={\n    \"tool\": \"build_claim_chain\",\n    \"input\": {\n        \"agent_id\": \"buyer-agent-001\",\n        \"claims\": [\n            {\n                \"type\": \"mandate_registration\",\n                \"mandate_hash\": mandate_hash,\n                \"principal\": \"human-operator-001\",\n                \"valid_from\": mandate[\"valid_from\"],\n                \"valid_until\": mandate[\"valid_until\"],\n            }\n        ],\n    }\n})\nchain = resp.json()\nprint(f\"Mandate registered in claim chain: {chain.get('chain_id')}\")\nprint(f\"Mandate hash: {mandate_hash}\")\n```\n\n### Linking Transactions to Mandate Clauses\n\nEvery transaction the agent initiates must reference a specific mandate clause. This creates the provenance chain: mandate clause -> intent -> transaction. When a dispute arises, the defender can produce the mandate, show the specific clause that authorized the action, and prove via the hash that the mandate has not been modified since registration.\n\n```python\nimport requests\nimport hashlib\nimport json\n\nsession = requests.Session()\nsession.headers[\"Authorization\"] = f\"Bearer {api_key}\"\nbase_url = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n# Create an intent that references the mandate\nintent_record = {\n    \"agent_id\": \"buyer-agent-001\",\n    \"action\": \"purchase_compute\",\n    \"vendor\": \"vendor-agent-001\",\n    \"amount_cents\": 5000,\n    \"mandate_hash\": mandate_hash,\n    \"mandate_clause\": \"authorized_actions[0]\",\n    \"justification\": \"Weekly compute allocation for batch processing pipeline\",\n    \"timestamp\": \"2026-04-06T10:30:00Z\",\n}\n\n# Hash the intent for the chain\nintent_bytes = json.dumps(intent_record, sort_keys=True).encode(\"utf-8\")\nintent_hash = hashlib.sha256(intent_bytes).hexdigest()\n\n# Record the intent in the claim chain before executing the transaction\nresp = session.post(f\"{base_url}\u002Fv1\", json={\n    \"tool\": \"build_claim_chain\",\n    \"input\": {\n        \"agent_id\": \"buyer-agent-001\",\n        \"claims\": [\n            {\n                \"type\": \"transaction_intent\",\n                \"intent_hash\": intent_hash,\n                \"mandate_hash\": mandate_hash,\n                \"action\": \"purchase_compute\",\n                \"amount_cents\": 5000,\n                \"vendor\": \"vendor-agent-001\",\n            }\n        ],\n    }\n})\nintent_chain = resp.json()\nprint(f\"Intent recorded: {intent_chain.get('chain_id')}\")\n\n# Now execute the actual transaction via escrow\nresp = session.post(f\"{base_url}\u002Fv1\", json={\n    \"tool\": \"create_escrow\",\n    \"input\": {\n        \"payer_id\": \"buyer-agent-001\",\n        \"payee_id\": \"vendor-agent-001\",\n        \"amount\": 5000,\n        \"intent_hash\": intent_hash,\n        \"conditions\": {\n            \"delivery_deadline\": \"2026-04-07T10:30:00Z\",\n            \"sla_id\": \"sla-compute-2026-04\",\n        },\n    }\n})\nescrow = resp.json()\nprint(f\"Escrow created: {escrow.get('escrow_id')}\")\nprint(f\"Linked to intent: {intent_hash}\")\n```\n\n### Selective Disclosure for Dispute Evidence\n\nDuring a dispute, you may need to prove that a specific mandate clause authorized a transaction without revealing the entire mandate (which may contain budget ceilings, vendor lists, and other competitively sensitive information). Selective disclosure allows you to reveal only the relevant clause and prove it belongs to the registered mandate hash.\n\n```python\nimport hashlib\nimport json\n\n\ndef create_selective_disclosure(mandate: dict, clause_path: str) -> dict:\n    \"\"\"Create a selective disclosure proof for a specific mandate clause.\n\n    Reveals only the requested clause while proving it belongs to\n    the full mandate via the registered hash.\n    \"\"\"\n    # Extract the specific clause value\n    keys = clause_path.split(\".\")\n    value = mandate\n    for key in keys:\n        if key.endswith(\"]\"):\n            field, idx = key[:-1].split(\"[\")\n            value = value[field][int(idx)]\n        else:\n            value = value[key]\n\n    # Compute the full mandate hash (verifier already has this from the chain)\n    mandate_bytes = json.dumps(mandate, sort_keys=True).encode(\"utf-8\")\n    full_hash = hashlib.sha256(mandate_bytes).hexdigest()\n\n    return {\n        \"clause_path\": clause_path,\n        \"clause_value\": value,\n        \"full_mandate_hash\": full_hash,\n        \"full_mandate\": mandate,  # Provided to verifier under NDA\u002Fescrow\n        \"verification_method\": \"sha256_json_sorted_keys\",\n    }\n\n\n# Example: prove that purchase_compute was an authorized action\nproof = create_selective_disclosure(mandate, \"authorized_actions[0]\")\nprint(f\"Disclosed clause: {proof['clause_path']} = {proof['clause_value']}\")\nprint(f\"Mandate hash: {proof['full_mandate_hash']}\")\n```\n\n### The Verifiable Intent Class\n\nThe following class wraps the entire intent chain workflow into a reusable component. It handles mandate registration, intent recording, transaction linking, and selective disclosure proof generation.\n\n```python\nimport requests\nimport hashlib\nimport json\nimport time\nfrom typing import Optional, Dict, Any\n\n\nclass VerifiableIntentChain:\n    \"\"\"Implements Mastercard Verifiable Intent-compatible authorization chains.\n\n    Records mandate -> intent -> transaction provenance using\n    GreenHelix claim chains for cryptographic tamper evidence.\n    \"\"\"\n\n    def __init__(self, api_key: str, agent_id: str,\n                 base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"):\n        self.agent_id = agent_id\n        self.base_url = base_url\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n        self.mandate: Optional[dict] = None\n        self.mandate_hash: Optional[str] = None\n        self.intents: Dict[str, dict] = {}  # intent_hash -> intent_record\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        resp = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        resp.raise_for_status()\n        return resp.json()\n\n    @staticmethod\n    def _hash(data: dict) -> str:\n        return hashlib.sha256(\n            json.dumps(data, sort_keys=True).encode(\"utf-8\")\n        ).hexdigest()\n\n    def register_mandate(self, mandate: dict) -> str:\n        \"\"\"Register a mandate and record its hash in the claim chain.\"\"\"\n        self.mandate = mandate\n        self.mandate_hash = self._hash(mandate)\n\n        self._execute(\"build_claim_chain\", {\n            \"agent_id\": self.agent_id,\n            \"claims\": [{\n                \"type\": \"mandate_registration\",\n                \"mandate_hash\": self.mandate_hash,\n                \"principal\": mandate.get(\"principal\"),\n                \"valid_from\": mandate.get(\"valid_from\"),\n                \"valid_until\": mandate.get(\"valid_until\"),\n            }],\n        })\n        return self.mandate_hash\n\n    def record_intent(self, action: str, vendor: str,\n                      amount_cents: int, mandate_clause: str,\n                      justification: str) -> str:\n        \"\"\"Record a transaction intent linked to a mandate clause.\"\"\"\n        if not self.mandate_hash:\n            raise ValueError(\"No mandate registered. Call register_mandate first.\")\n\n        intent = {\n            \"agent_id\": self.agent_id,\n            \"action\": action,\n            \"vendor\": vendor,\n            \"amount_cents\": amount_cents,\n            \"mandate_hash\": self.mandate_hash,\n            \"mandate_clause\": mandate_clause,\n            \"justification\": justification,\n            \"timestamp\": time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime()),\n        }\n        intent_hash = self._hash(intent)\n        self.intents[intent_hash] = intent\n\n        self._execute(\"build_claim_chain\", {\n            \"agent_id\": self.agent_id,\n            \"claims\": [{\n                \"type\": \"transaction_intent\",\n                \"intent_hash\": intent_hash,\n                \"mandate_hash\": self.mandate_hash,\n                \"action\": action,\n                \"amount_cents\": amount_cents,\n                \"vendor\": vendor,\n            }],\n        })\n        return intent_hash\n\n    def validate_against_mandate(self, action: str, vendor: str,\n                                  amount_cents: int) -> Dict[str, Any]:\n        \"\"\"Check if a proposed transaction is authorized by the mandate.\"\"\"\n        if not self.mandate:\n            return {\"authorized\": False, \"reason\": \"no_mandate_registered\"}\n\n        checks = {\n            \"action_authorized\": action in self.mandate.get(\"authorized_actions\", []),\n            \"vendor_approved\": vendor in self.mandate.get(\"approved_vendors\", []),\n            \"within_budget\": amount_cents \u003C= self.mandate.get(\"budget_ceiling_cents\", 0),\n            \"mandate_valid\": (\n                self.mandate.get(\"valid_from\", \"\") \u003C= time.strftime(\n                    \"%Y-%m-%dT%H:%M:%SZ\", time.gmtime()\n                ) \u003C= self.mandate.get(\"valid_until\", \"\")\n            ),\n        }\n        authorized = all(checks.values())\n        failed = [k for k, v in checks.items() if not v]\n\n        return {\n            \"authorized\": authorized,\n            \"checks\": checks,\n            \"failed_checks\": failed,\n            \"mandate_hash\": self.mandate_hash,\n        }\n\n    def generate_dispute_evidence(self, intent_hash: str) -> Dict[str, Any]:\n        \"\"\"Generate a complete evidence package for dispute defense.\"\"\"\n        intent = self.intents.get(intent_hash)\n        if not intent:\n            return {\"error\": \"intent_not_found\"}\n\n        return {\n            \"intent_hash\": intent_hash,\n            \"intent_record\": intent,\n            \"mandate_hash\": self.mandate_hash,\n            \"chain_verification\": \"verify via build_claim_chain audit\",\n            \"provenance\": {\n                \"principal\": self.mandate.get(\"principal\"),\n                \"mandate_clause\": intent.get(\"mandate_clause\"),\n                \"justification\": intent.get(\"justification\"),\n            },\n        }\n```\n\n---\n\n## Chapter 4: The Escrow-First Architecture: Dispute-Ready Transaction Pipelines\n\n### Why Direct Payments Are Indefensible\n\nIf your agent sends money directly to a counterparty via a simple transfer, and the counterparty does not deliver, your recovery options are limited to filing a dispute after the fact and hoping the counterparty cooperates. This is equivalent to mailing cash with a note that says \"please send goods.\" No reasonable human does this, and no reasonable agent should either.\n\nThe escrow-first architecture reverses the power dynamic. Funds are committed to a neutral escrow account with explicit release conditions. The counterparty can see that the funds exist (reducing their risk of non-payment) but cannot access them until the conditions are met (reducing your risk of non-delivery). If conditions are not met, the funds return to the buyer. If there is a dispute about whether conditions were met, both parties have a defined resolution path.\n\nEvery transaction in a dispute-ready pipeline goes through escrow. No exceptions. Even small transactions. The incremental cost of escrow (one extra API call) is negligible compared to the cost of an unrecoverable payment.\n\n### Performance Escrow with SLA Criteria\n\nPerformance escrow adds measurable criteria to the release conditions. Instead of \"release when the buyer confirms delivery,\" the condition is \"release when SLA metrics confirm delivery quality.\" This removes subjective judgment from the release decision and creates objective evidence for disputes.\n\n```python\nimport requests\nimport time\n\nsession = requests.Session()\nsession.headers[\"Authorization\"] = f\"Bearer {api_key}\"\nbase_url = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n# Step 1: Define the SLA\nresp = session.post(f\"{base_url}\u002Fv1\", json={\n    \"tool\": \"create_sla\",\n    \"input\": {\n        \"agent_id\": \"buyer-agent-001\",\n        \"provider_id\": \"vendor-agent-001\",\n        \"metrics\": {\n            \"uptime_percent\": {\"threshold\": 99.5, \"comparison\": \"gte\"},\n            \"response_time_ms\": {\"threshold\": 200, \"comparison\": \"lte\"},\n            \"accuracy_percent\": {\"threshold\": 95.0, \"comparison\": \"gte\"},\n        },\n        \"evaluation_period\": \"2026-04-06T00:00:00Z\u002F2026-04-13T00:00:00Z\",\n    }\n})\nsla = resp.json()\nsla_id = sla.get(\"sla_id\")\nprint(f\"SLA created: {sla_id}\")\n\n# Step 2: Create performance escrow linked to the SLA\nresp = session.post(f\"{base_url}\u002Fv1\", json={\n    \"tool\": \"create_performance_escrow\",\n    \"input\": {\n        \"payer_id\": \"buyer-agent-001\",\n        \"payee_id\": \"vendor-agent-001\",\n        \"amount\": 10000,\n        \"sla_id\": sla_id,\n        \"release_conditions\": {\n            \"sla_compliant\": True,\n            \"minimum_evaluation_period_hours\": 168,\n        },\n        \"timeout_hours\": 336,\n        \"timeout_action\": \"return_to_payer\",\n    }\n})\nescrow = resp.json()\nescrow_id = escrow.get(\"escrow_id\")\nprint(f\"Performance escrow created: {escrow_id}\")\nprint(f\"Linked to SLA: {sla_id}\")\nprint(f\"Timeout: 336 hours -> return to payer\")\n```\n\n### Automatic Release Gates\n\nRelease gates are checkpoints that must all pass before escrow funds are released. Implementing them as a polling loop allows fully autonomous release without human intervention.\n\n```python\nimport requests\nimport time\n\nsession = requests.Session()\nsession.headers[\"Authorization\"] = f\"Bearer {api_key}\"\nbase_url = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n\ndef check_release_gates(escrow_id: str, sla_id: str) -> dict:\n    \"\"\"Check all release gates for a performance escrow.\"\"\"\n    # Gate 1: SLA compliance\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"check_sla_compliance\",\n        \"input\": {\n            \"agent_id\": \"buyer-agent-001\",\n            \"sla_id\": sla_id,\n        }\n    })\n    sla_status = resp.json()\n\n    # Gate 2: Escrow status (not disputed, not timed out)\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"check_performance_escrow\",\n        \"input\": {\n            \"escrow_id\": escrow_id,\n        }\n    })\n    escrow_status = resp.json()\n\n    # Gate 3: No active disputes against this escrow\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"list_disputes\",\n        \"input\": {\n            \"agent_id\": \"buyer-agent-001\",\n        }\n    })\n    disputes = resp.json()\n    active_disputes = [\n        d for d in disputes.get(\"disputes\", [])\n        if d.get(\"escrow_id\") == escrow_id\n        and d.get(\"status\") in (\"open\", \"under_review\")\n    ]\n\n    gates = {\n        \"sla_compliant\": sla_status.get(\"compliant\", False),\n        \"escrow_active\": escrow_status.get(\"status\") == \"active\",\n        \"no_active_disputes\": len(active_disputes) == 0,\n    }\n    all_passed = all(gates.values())\n\n    return {\n        \"escrow_id\": escrow_id,\n        \"gates\": gates,\n        \"all_passed\": all_passed,\n        \"action\": \"release\" if all_passed else \"hold\",\n    }\n\n\ndef release_gate_loop(escrow_id: str, sla_id: str,\n                      check_interval_seconds: int = 3600,\n                      max_checks: int = 168):\n    \"\"\"Poll release gates and release escrow when all gates pass.\"\"\"\n    for i in range(max_checks):\n        result = check_release_gates(escrow_id, sla_id)\n        print(f\"Check {i+1}\u002F{max_checks}: {result['gates']}\")\n\n        if result[\"all_passed\"]:\n            # All gates passed -- release the escrow\n            resp = session.post(f\"{base_url}\u002Fv1\", json={\n                \"tool\": \"release_escrow\",\n                \"input\": {\"escrow_id\": escrow_id}\n            })\n            release = resp.json()\n            print(f\"Escrow released: {release}\")\n            return {\"status\": \"released\", \"check_number\": i + 1}\n\n        time.sleep(check_interval_seconds)\n\n    # Max checks reached without release -- trigger dispute\n    print(\"Release gates never passed. Initiating dispute.\")\n    return {\"status\": \"timeout\", \"action\": \"initiate_dispute\"}\n```\n\n### Dispute-Triggering Conditions\n\nNot every failed gate should trigger a dispute. A temporary SLA dip during a maintenance window is different from persistent non-delivery. The following logic distinguishes between transient failures and dispute-worthy violations.\n\n```python\nimport requests\n\nsession = requests.Session()\nsession.headers[\"Authorization\"] = f\"Bearer {api_key}\"\nbase_url = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n\ndef evaluate_dispute_trigger(escrow_id: str, sla_id: str,\n                              consecutive_failures: int,\n                              failure_threshold: int = 3) -> dict:\n    \"\"\"Determine if SLA failures warrant opening a dispute.\n\n    Only triggers a dispute after consecutive_failures exceeds the\n    threshold, filtering out transient violations.\n    \"\"\"\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_sla_status\",\n        \"input\": {\n            \"agent_id\": \"buyer-agent-001\",\n            \"sla_id\": sla_id,\n        }\n    })\n    sla_status = resp.json()\n\n    if not sla_status.get(\"compliant\", True):\n        consecutive_failures += 1\n    else:\n        consecutive_failures = 0\n\n    should_dispute = consecutive_failures >= failure_threshold\n    action = \"none\"\n\n    if should_dispute:\n        # Open a dispute against the escrow\n        resp = session.post(f\"{base_url}\u002Fv1\", json={\n            \"tool\": \"open_dispute\",\n            \"input\": {\n                \"agent_id\": \"buyer-agent-001\",\n                \"escrow_id\": escrow_id,\n                \"reason\": \"sla_breach\",\n                \"evidence\": {\n                    \"sla_id\": sla_id,\n                    \"consecutive_failures\": consecutive_failures,\n                    \"threshold\": failure_threshold,\n                    \"latest_status\": sla_status,\n                },\n            }\n        })\n        dispute = resp.json()\n        action = \"dispute_opened\"\n        print(f\"Dispute opened: {dispute.get('dispute_id')}\")\n\n    return {\n        \"consecutive_failures\": consecutive_failures,\n        \"should_dispute\": should_dispute,\n        \"action\": action,\n    }\n```\n\n### The Refund Flow\n\nWhen a dispute is resolved in the buyer's favor, the escrow funds must be returned. The cancellation flow handles this.\n\n```python\nimport requests\n\nsession = requests.Session()\nsession.headers[\"Authorization\"] = f\"Bearer {api_key}\"\nbase_url = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n# After dispute resolves in buyer's favor, cancel the escrow\nresp = session.post(f\"{base_url}\u002Fv1\", json={\n    \"tool\": \"cancel_escrow\",\n    \"input\": {\n        \"escrow_id\": \"escrow-abc-123\",\n        \"reason\": \"dispute_resolved_buyer_favor\",\n        \"dispute_id\": \"dispute-xyz-789\",\n    }\n})\ncancellation = resp.json()\nprint(f\"Escrow cancelled: {cancellation}\")\nprint(f\"Funds returned to payer\")\n```\n\n---\n\n## Chapter 5: Automated Evidence Collection & Submission: From Raw Logs to Compelling Evidence 3.0\n\n### Why Manual Evidence Fails at Machine Speed\n\nA human merchant responding to a chargeback has 20 to 45 days to assemble evidence. They gather invoices, shipping receipts, delivery confirmations, and correspondence. The evidence is compiled manually and submitted through the card network's portal. This process assumes (1) the merchant has time, (2) the evidence exists in human-readable form, and (3) a human reviewer will evaluate it.\n\nAgent commerce breaks all three assumptions. Disputes can escalate in minutes, not weeks. Evidence exists as API logs, SLA metrics, and cryptographic hashes, not invoices and receipts. And the initial review may be automated -- Visa's Compelling Evidence 3.0 program, updated April 1, 2026, now includes evidence-sharing tooling designed for programmatic submission, including a new category for agentic transactions.\n\nYour dispute resolution system must collect, package, and submit evidence automatically, in the format that card networks and A2A dispute resolvers expect.\n\n### The Evidence Pipeline\n\nEvidence collection for agent disputes follows a four-stage pipeline.\n\n**Stage 1: Transaction History Extraction.** Pull the complete transaction record for the disputed transaction, including all related transactions in the same session or delegation chain.\n\n**Stage 2: SLA Compliance Snapshots.** If the dispute involves service quality, pull the full SLA compliance history for the evaluation period. Point-in-time snapshots are more compelling than summary statistics because they show the pattern of violations.\n\n**Stage 3: Reputation Attestations.** Pull the counterparty's reputation profile, including claim chains, verified metrics, and dispute history. A counterparty with a pattern of disputes is weaker in arbitration than one with a clean record.\n\n**Stage 4: Structured Evidence Packaging.** Combine all evidence into a structured package with cryptographic integrity verification. The package must be self-contained and verifiable by a third party.\n\n```python\nimport requests\nimport hashlib\nimport json\nimport time\nfrom typing import Dict, List, Any\n\n\nclass EvidenceCollector:\n    \"\"\"Automated evidence collection for agent dispute defense.\n\n    Collects transaction history, SLA compliance data, reputation\n    attestations, and packages them into structured evidence bundles\n    compatible with Visa CE 3.0 and A2A dispute resolution.\n    \"\"\"\n\n    def __init__(self, api_key: str, agent_id: str,\n                 base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"):\n        self.agent_id = agent_id\n        self.base_url = base_url\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        resp = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        resp.raise_for_status()\n        return resp.json()\n\n    def collect_transaction_evidence(self, counterparty_id: str) -> dict:\n        \"\"\"Stage 1: Extract transaction history with counterparty.\"\"\"\n        history = self._execute(\"get_transaction_history\", {\n            \"agent_id\": self.agent_id,\n        })\n\n        relevant = [\n            t for t in history.get(\"transactions\", [])\n            if t.get(\"counterparty\") == counterparty_id\n        ]\n\n        return {\n            \"stage\": \"transaction_history\",\n            \"total_transactions\": len(relevant),\n            \"transactions\": relevant,\n            \"collected_at\": time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime()),\n        }\n\n    def collect_sla_evidence(self, sla_id: str) -> dict:\n        \"\"\"Stage 2: Collect SLA compliance snapshots.\"\"\"\n        compliance = self._execute(\"check_sla_compliance\", {\n            \"agent_id\": self.agent_id,\n            \"sla_id\": sla_id,\n        })\n        status = self._execute(\"get_sla_status\", {\n            \"agent_id\": self.agent_id,\n            \"sla_id\": sla_id,\n        })\n\n        return {\n            \"stage\": \"sla_compliance\",\n            \"sla_id\": sla_id,\n            \"compliant\": compliance.get(\"compliant\"),\n            \"violations\": compliance.get(\"violations\", []),\n            \"full_status\": status,\n            \"collected_at\": time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime()),\n        }\n\n    def collect_reputation_evidence(self, counterparty_id: str) -> dict:\n        \"\"\"Stage 3: Collect counterparty reputation attestations.\"\"\"\n        reputation = self._execute(\"get_agent_reputation\", {\n            \"agent_id\": counterparty_id,\n        })\n        identity = self._execute(\"verify_identity\", {\n            \"agent_id\": counterparty_id,\n        })\n\n        return {\n            \"stage\": \"reputation_attestation\",\n            \"counterparty_id\": counterparty_id,\n            \"reputation_score\": reputation.get(\"reputation_score\"),\n            \"dispute_history\": reputation.get(\"dispute_history\", {}),\n            \"identity_verified\": identity.get(\"verified\", False),\n            \"registration_date\": identity.get(\"registered_at\"),\n            \"collected_at\": time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime()),\n        }\n\n    def collect_escrow_evidence(self, escrow_id: str) -> dict:\n        \"\"\"Collect escrow state and performance data.\"\"\"\n        escrow = self._execute(\"check_performance_escrow\", {\n            \"escrow_id\": escrow_id,\n        })\n        return {\n            \"stage\": \"escrow_state\",\n            \"escrow_id\": escrow_id,\n            \"escrow_data\": escrow,\n            \"collected_at\": time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime()),\n        }\n\n    def package_evidence(self, escrow_id: str, sla_id: str,\n                         counterparty_id: str,\n                         intent_hash: str = None) -> dict:\n        \"\"\"Stage 4: Package all evidence into a structured bundle.\n\n        The bundle includes a SHA-256 integrity hash over all evidence\n        so that any tampering is detectable.\n        \"\"\"\n        evidence_stages = [\n            self.collect_transaction_evidence(counterparty_id),\n            self.collect_sla_evidence(sla_id),\n            self.collect_reputation_evidence(counterparty_id),\n            self.collect_escrow_evidence(escrow_id),\n        ]\n\n        bundle = {\n            \"dispute_evidence_bundle\": {\n                \"version\": \"1.0\",\n                \"format\": \"greenhelix_ce3_compatible\",\n                \"agent_id\": self.agent_id,\n                \"counterparty_id\": counterparty_id,\n                \"escrow_id\": escrow_id,\n                \"sla_id\": sla_id,\n                \"intent_hash\": intent_hash,\n                \"stages\": evidence_stages,\n                \"packaged_at\": time.strftime(\n                    \"%Y-%m-%dT%H:%M:%SZ\", time.gmtime()\n                ),\n            }\n        }\n\n        # Compute integrity hash over the entire bundle\n        bundle_bytes = json.dumps(\n            bundle, sort_keys=True, default=str\n        ).encode(\"utf-8\")\n        bundle[\"dispute_evidence_bundle\"][\"integrity_hash\"] = hashlib.sha256(\n            bundle_bytes\n        ).hexdigest()\n\n        return bundle\n```\n\n### Submitting Evidence to a Dispute\n\nOnce the evidence bundle is assembled, it is attached to the dispute response. The evidence is submitted programmatically as part of the `respond_dispute` tool call.\n\n```python\nimport requests\nimport json\n\nsession = requests.Session()\nsession.headers[\"Authorization\"] = f\"Bearer {api_key}\"\nbase_url = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n# Assume evidence_bundle was created by EvidenceCollector.package_evidence()\nevidence_bundle = collector.package_evidence(\n    escrow_id=\"escrow-abc-123\",\n    sla_id=\"sla-compute-2026-04\",\n    counterparty_id=\"vendor-agent-001\",\n    intent_hash=\"a1b2c3d4e5f6...\",\n)\n\n# Submit evidence as part of dispute response\nresp = session.post(f\"{base_url}\u002Fv1\", json={\n    \"tool\": \"respond_dispute\",\n    \"input\": {\n        \"dispute_id\": \"dispute-xyz-789\",\n        \"agent_id\": \"buyer-agent-001\",\n        \"response\": \"reject\",\n        \"evidence\": evidence_bundle[\"dispute_evidence_bundle\"],\n        \"narrative\": (\n            \"SLA compliance data shows 3 consecutive violations of the \"\n            \"uptime threshold (99.5% required, 94.2% actual over 72 hours). \"\n            \"Performance escrow release conditions were never met. \"\n            \"Intent chain proves transaction was within mandate scope. \"\n            \"Requesting full refund via escrow cancellation.\"\n        ),\n    }\n})\nresponse = resp.json()\nprint(f\"Dispute response submitted: {response}\")\n```\n\n---\n\n## Chapter 6: Multi-Party Dispute Resolution Workflows: Filing, Responding, Escalating, and Arbitrating\n\n### The Dispute Lifecycle\n\nGreenHelix disputes follow a four-stage lifecycle: Open, Response, Resolution, and Closed. Each stage has timeouts. If a party does not act within the timeout, the system advances automatically -- typically in favor of the party that did act.\n\n```\nOPEN ──(72h)──> RESPONSE ──(72h)──> RESOLUTION ──(24h)──> CLOSED\n  │                │                     │                    │\n  │                │                     │                    │\n  └─ Initiator     └─ Respondent         └─ Arbitrator\u002F       └─ Final\n     files claim      provides evidence     Auto-resolve         state\n```\n\n### Stage 1: Filing a Dispute\n\nThe initiator opens a dispute by identifying the escrow, the failure mode (from the Chapter 2 taxonomy), and initial evidence. The evidence does not need to be comprehensive at filing -- it needs to be sufficient to establish the claim.\n\n```python\nimport requests\n\nsession = requests.Session()\nsession.headers[\"Authorization\"] = f\"Bearer {api_key}\"\nbase_url = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n# File a dispute for SLA breach\nresp = session.post(f\"{base_url}\u002Fv1\", json={\n    \"tool\": \"open_dispute\",\n    \"input\": {\n        \"agent_id\": \"buyer-agent-001\",\n        \"escrow_id\": \"escrow-abc-123\",\n        \"reason\": \"sla_breach\",\n        \"failure_mode\": \"sla_breach\",  # From the 7-mode taxonomy\n        \"evidence\": {\n            \"sla_id\": \"sla-compute-2026-04\",\n            \"violations_summary\": \"3 consecutive failures: uptime below 99.5%\",\n            \"requested_resolution\": \"full_refund\",\n        },\n        \"deadline_hours\": 72,\n    }\n})\ndispute = resp.json()\ndispute_id = dispute.get(\"dispute_id\")\nprint(f\"Dispute filed: {dispute_id}\")\nprint(f\"Respondent has 72 hours to respond\")\n```\n\n### Stage 2: Responding to a Dispute\n\nThe respondent must provide counter-evidence within the response window. The `EvidenceCollector` from Chapter 5 automates this. A strong response includes transaction evidence, SLA data, and reputation attestation.\n\n```python\nimport requests\n\nsession = requests.Session()\nsession.headers[\"Authorization\"] = f\"Bearer {api_key}\"\nbase_url = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n# As the vendor, respond to the dispute with evidence\nresp = session.post(f\"{base_url}\u002Fv1\", json={\n    \"tool\": \"respond_dispute\",\n    \"input\": {\n        \"dispute_id\": \"dispute-xyz-789\",\n        \"agent_id\": \"vendor-agent-001\",\n        \"response\": \"contest\",\n        \"evidence\": {\n            \"sla_compliance_report\": {\n                \"overall_uptime\": 99.7,\n                \"note\": \"Brief dip during scheduled maintenance window, \"\n                        \"communicated 48h in advance per SLA section 4.2\",\n            },\n            \"maintenance_notification\": {\n                \"sent_at\": \"2026-04-04T08:00:00Z\",\n                \"channel\": \"messaging\",\n                \"message_id\": \"msg-maint-001\",\n            },\n            \"monitor_logs\": {\n                \"sla_id\": \"sla-compute-2026-04\",\n                \"measurement_source\": \"greenhelix_sla_monitor\",\n            },\n        },\n        \"narrative\": (\n            \"Uptime dip occurred during a pre-announced maintenance window. \"\n            \"SLA section 4.2 excludes scheduled maintenance from uptime \"\n            \"calculations. Excluding the 4-hour window, uptime was 99.82%.\"\n        ),\n    }\n})\nresponse = resp.json()\nprint(f\"Dispute response filed: {response}\")\n```\n\n### Stage 3: Resolution\n\nResolution can happen in three ways: mutual agreement, timeout-based automatic resolution, or third-party arbitration. The `resolve_dispute` tool handles all three.\n\n```python\nimport requests\n\nsession = requests.Session()\nsession.headers[\"Authorization\"] = f\"Bearer {api_key}\"\nbase_url = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n# Resolution option 1: Mutual agreement (either party can propose)\nresp = session.post(f\"{base_url}\u002Fv1\", json={\n    \"tool\": \"resolve_dispute\",\n    \"input\": {\n        \"dispute_id\": \"dispute-xyz-789\",\n        \"resolution\": \"partial_refund\",\n        \"details\": {\n            \"refund_amount_cents\": 5000,\n            \"refund_reason\": \"Partial SLA credit for maintenance-window impact\",\n            \"escrow_action\": \"partial_release\",\n            \"release_to_vendor_cents\": 5000,\n            \"return_to_buyer_cents\": 5000,\n        },\n    }\n})\nresolution = resp.json()\nprint(f\"Resolution proposed: {resolution}\")\n```\n\n### Automated Dispute Handler\n\nThe following class orchestrates the entire dispute lifecycle autonomously. It monitors for incoming disputes, collects evidence, submits responses, and handles resolution -- all without human intervention.\n\n```python\nimport requests\nimport time\nimport json\nfrom typing import Dict, Optional, Callable, Any\n\n\nclass AutomatedDisputeHandler:\n    \"\"\"Fully autonomous dispute lifecycle management.\n\n    Monitors for new disputes, auto-collects evidence, submits\n    responses within deadlines, and handles resolution flows.\n    \"\"\"\n\n    def __init__(self, api_key: str, agent_id: str,\n                 evidence_collector,\n                 base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"):\n        self.agent_id = agent_id\n        self.base_url = base_url\n        self.evidence_collector = evidence_collector\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n        self.handled_disputes: Dict[str, str] = {}  # dispute_id -> status\n        self.escalation_callback: Optional[Callable] = None\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        resp = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        resp.raise_for_status()\n        return resp.json()\n\n    def set_escalation_callback(self, callback: Callable):\n        \"\"\"Register a callback for disputes that require human review.\"\"\"\n        self.escalation_callback = callback\n\n    def poll_disputes(self) -> list:\n        \"\"\"Check for new or updated disputes.\"\"\"\n        result = self._execute(\"list_disputes\", {\n            \"agent_id\": self.agent_id,\n        })\n        return result.get(\"disputes\", [])\n\n    def handle_incoming_dispute(self, dispute: dict) -> dict:\n        \"\"\"Process a single incoming dispute.\"\"\"\n        dispute_id = dispute.get(\"dispute_id\")\n        status = dispute.get(\"status\")\n        escrow_id = dispute.get(\"escrow_id\")\n\n        if dispute_id in self.handled_disputes:\n            if self.handled_disputes[dispute_id] == status:\n                return {\"action\": \"already_handled\"}\n\n        # Collect evidence automatically\n        evidence_bundle = self.evidence_collector.package_evidence(\n            escrow_id=escrow_id,\n            sla_id=dispute.get(\"sla_id\", \"\"),\n            counterparty_id=dispute.get(\"initiator_id\", \"\"),\n        )\n\n        # Determine response strategy based on evidence\n        sla_evidence = next(\n            (s for s in evidence_bundle[\"dispute_evidence_bundle\"][\"stages\"]\n             if s[\"stage\"] == \"sla_compliance\"),\n            {}\n        )\n        is_compliant = sla_evidence.get(\"compliant\", True)\n\n        if is_compliant:\n            # Evidence supports our position -- contest the dispute\n            response = self._execute(\"respond_dispute\", {\n                \"dispute_id\": dispute_id,\n                \"agent_id\": self.agent_id,\n                \"response\": \"contest\",\n                \"evidence\": evidence_bundle[\"dispute_evidence_bundle\"],\n                \"narrative\": \"SLA compliance verified. Contesting dispute.\",\n            })\n            self.handled_disputes[dispute_id] = \"contested\"\n            return {\"action\": \"contested\", \"response\": response}\n        else:\n            # Evidence does not support us -- escalate or concede\n            if self.escalation_callback:\n                self.escalation_callback(dispute, evidence_bundle)\n                self.handled_disputes[dispute_id] = \"escalated\"\n                return {\"action\": \"escalated_to_human\"}\n            else:\n                # No escalation path -- propose partial resolution\n                response = self._execute(\"respond_dispute\", {\n                    \"dispute_id\": dispute_id,\n                    \"agent_id\": self.agent_id,\n                    \"response\": \"accept_partial\",\n                    \"evidence\": evidence_bundle[\"dispute_evidence_bundle\"],\n                    \"narrative\": (\n                        \"SLA violations confirmed. Proposing partial \"\n                        \"credit proportional to violation severity.\"\n                    ),\n                })\n                self.handled_disputes[dispute_id] = \"partial_accepted\"\n                return {\"action\": \"partial_accepted\", \"response\": response}\n\n    def run_dispute_monitor(self, interval_seconds: int = 300,\n                            max_iterations: int = 0):\n        \"\"\"Continuously monitor and handle disputes.\n\n        Args:\n            interval_seconds: Polling interval.\n            max_iterations: Stop after N iterations (0 = run forever).\n        \"\"\"\n        iteration = 0\n        while max_iterations == 0 or iteration \u003C max_iterations:\n            disputes = self.poll_disputes()\n            open_disputes = [\n                d for d in disputes\n                if d.get(\"status\") in (\"open\", \"awaiting_response\")\n                and d.get(\"respondent_id\") == self.agent_id\n            ]\n\n            for dispute in open_disputes:\n                result = self.handle_incoming_dispute(dispute)\n                print(\n                    f\"Dispute {dispute.get('dispute_id')}: \"\n                    f\"{result.get('action')}\"\n                )\n\n            iteration += 1\n            if max_iterations == 0 or iteration \u003C max_iterations:\n                time.sleep(interval_seconds)\n```\n\n### Timeout Handlers\n\nDisputes that are not responded to within the deadline resolve automatically. As the initiator, this works in your favor. As the respondent, timeouts are catastrophic. The following pattern ensures your agent never misses a deadline.\n\n```python\nimport requests\nimport time\n\nsession = requests.Session()\nsession.headers[\"Authorization\"] = f\"Bearer {api_key}\"\nbase_url = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n\ndef check_response_deadlines(agent_id: str,\n                              warning_hours: int = 12) -> list:\n    \"\"\"Identify disputes approaching response deadlines.\"\"\"\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"list_disputes\",\n        \"input\": {\"agent_id\": agent_id}\n    })\n    disputes = resp.json().get(\"disputes\", [])\n\n    urgent = []\n    now = time.time()\n    for d in disputes:\n        if d.get(\"status\") == \"awaiting_response\" and d.get(\"respondent_id\") == agent_id:\n            deadline = d.get(\"response_deadline_epoch\", 0)\n            hours_remaining = (deadline - now) \u002F 3600\n            if 0 \u003C hours_remaining \u003C= warning_hours:\n                urgent.append({\n                    \"dispute_id\": d.get(\"dispute_id\"),\n                    \"hours_remaining\": round(hours_remaining, 1),\n                    \"escrow_id\": d.get(\"escrow_id\"),\n                    \"priority\": \"critical\" if hours_remaining \u003C= 4 else \"high\",\n                })\n\n    return sorted(urgent, key=lambda x: x[\"hours_remaining\"])\n```\n\n---\n\n## Chapter 7: Chargeback Defense for Agent-Initiated Transactions: Card Network Rules Meet A2A Commerce\n\n### The Fundamental Mismatch\n\nCard network dispute rules assume a cardholder initiated the transaction. The cardholder can file a chargeback by claiming fraud (they did not make the purchase) or by claiming the goods were not as described. The issuing bank evaluates the claim, the acquiring bank represents the merchant, and the card network arbitrates if the parties cannot agree.\n\nWhen an AI agent initiates a transaction funded by a card deposit, the cardholder is the human principal who funded the agent's wallet. The merchant is the counterparty agent (or more precisely, the human operator behind the counterparty agent). The cardholder might file a chargeback because their agent over-purchased (Failure Mode 1), because the agent bought something the cardholder did not want (Failure Mode 7: intent drift), or because the counterparty did not deliver (Failure Mode 4: SLA breach). The card network must evaluate this claim using rules designed for \"I ordered a shirt and it never arrived,\" not \"my autonomous procurement agent exceeded its compute budget by $8,000 because it hallucinated a scaling requirement.\"\n\n### Visa Compelling Evidence 3.0: Agentic Extensions\n\nVisa's CE 3.0 update, effective April 1, 2026, is the first card network evidence standard to explicitly address agentic transactions. The update introduces two relevant changes.\n\nFirst, it adds a new evidence category for \"delegated purchasing authority\" -- documentation proving that a human principal authorized an agent to make purchases on their behalf. This maps directly to the mandate and intent chain from Chapter 3.\n\nSecond, it introduces evidence-sharing tooling that allows merchants to submit evidence programmatically rather than through the traditional portal upload. This is critical for agent commerce because the evidence (API logs, SLA metrics, cryptographic hashes) is inherently digital and structured.\n\n### Mastercard Scheme-Carried Liability\n\nMastercard's approach is different. Rather than modifying the evidence framework, they are establishing scheme-carried liability for transactions that follow the Verifiable Intent specification. If both the buyer and seller use Verifiable Intent (the mandate -> intent -> transaction chain), and the transaction is properly recorded, Mastercard absorbs the chargeback liability rather than pushing it to either party. This creates a strong incentive for both sides to implement Verifiable Intent chains, because doing so eliminates chargeback risk entirely.\n\n### Building an Intent Store for Pre-Dispute Deflection\n\nThe most effective chargeback defense is preventing the chargeback from being filed. An intent store is a queryable database of all agent intents, mandates, and transaction linkages. When a cardholder contacts their bank to dispute a transaction, the merchant's system can pre-emptively submit the intent chain to the issuer before the chargeback is formalized. This is called pre-dispute deflection, and Visa's CE 3.0 now supports it for agentic transactions.\n\n```python\nimport requests\nimport hashlib\nimport json\nimport time\nfrom typing import Dict, List, Optional, Any\n\n\nclass IntentStore:\n    \"\"\"Queryable store of agent intents for chargeback deflection.\n\n    Maintains a local index of all mandates, intents, and transaction\n    linkages. Supports pre-dispute evidence retrieval for card network\n    submission within the CE 3.0 framework.\n    \"\"\"\n\n    def __init__(self, api_key: str, agent_id: str,\n                 base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"):\n        self.agent_id = agent_id\n        self.base_url = base_url\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n        self.mandates: Dict[str, dict] = {}  # mandate_hash -> mandate\n        self.intents: Dict[str, dict] = {}   # intent_hash -> intent\n        self.tx_to_intent: Dict[str, str] = {}  # transaction_id -> intent_hash\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        resp = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        resp.raise_for_status()\n        return resp.json()\n\n    @staticmethod\n    def _hash(data: dict) -> str:\n        return hashlib.sha256(\n            json.dumps(data, sort_keys=True).encode(\"utf-8\")\n        ).hexdigest()\n\n    def store_mandate(self, mandate: dict) -> str:\n        \"\"\"Store a mandate and return its hash.\"\"\"\n        h = self._hash(mandate)\n        self.mandates[h] = mandate\n        return h\n\n    def store_intent(self, intent: dict, transaction_id: str = None) -> str:\n        \"\"\"Store an intent and optionally link it to a transaction.\"\"\"\n        h = self._hash(intent)\n        self.intents[h] = intent\n        if transaction_id:\n            self.tx_to_intent[transaction_id] = h\n        return h\n\n    def lookup_by_transaction(self, transaction_id: str) -> Optional[dict]:\n        \"\"\"Retrieve the full intent chain for a transaction.\n\n        Returns the intent, its parent mandate, and the chain\n        verification data needed for CE 3.0 evidence submission.\n        \"\"\"\n        intent_hash = self.tx_to_intent.get(transaction_id)\n        if not intent_hash:\n            return None\n\n        intent = self.intents.get(intent_hash)\n        if not intent:\n            return None\n\n        mandate_hash = intent.get(\"mandate_hash\")\n        mandate = self.mandates.get(mandate_hash)\n\n        return {\n            \"transaction_id\": transaction_id,\n            \"intent_hash\": intent_hash,\n            \"intent\": intent,\n            \"mandate_hash\": mandate_hash,\n            \"mandate\": mandate,\n            \"chain_complete\": mandate is not None,\n        }\n\n    def generate_ce3_evidence(self, transaction_id: str) -> Optional[dict]:\n        \"\"\"Generate Visa CE 3.0 compatible evidence for a transaction.\n\n        This evidence package can be submitted to the issuer for\n        pre-dispute deflection or chargeback defense.\n        \"\"\"\n        chain = self.lookup_by_transaction(transaction_id)\n        if not chain:\n            return None\n\n        # Pull additional context from GreenHelix\n        history = self._execute(\"get_transaction_history\", {\n            \"agent_id\": self.agent_id,\n        })\n\n        # Find the specific transaction\n        tx_record = next(\n            (t for t in history.get(\"transactions\", [])\n             if t.get(\"transaction_id\") == transaction_id),\n            {}\n        )\n\n        evidence = {\n            \"ce3_version\": \"3.0\",\n            \"evidence_type\": \"delegated_purchasing_authority\",\n            \"transaction_id\": transaction_id,\n            \"transaction_record\": tx_record,\n            \"delegated_authority\": {\n                \"mandate_hash\": chain[\"mandate_hash\"],\n                \"mandate_principal\": chain[\"mandate\"].get(\"principal\"),\n                \"mandate_valid_from\": chain[\"mandate\"].get(\"valid_from\"),\n                \"mandate_valid_until\": chain[\"mandate\"].get(\"valid_until\"),\n                \"authorized_actions\": chain[\"mandate\"].get(\"authorized_actions\"),\n                \"budget_ceiling_cents\": chain[\"mandate\"].get(\n                    \"budget_ceiling_cents\"\n                ),\n            },\n            \"intent_chain\": {\n                \"intent_hash\": chain[\"intent_hash\"],\n                \"action\": chain[\"intent\"].get(\"action\"),\n                \"amount_cents\": chain[\"intent\"].get(\"amount_cents\"),\n                \"vendor\": chain[\"intent\"].get(\"vendor\"),\n                \"justification\": chain[\"intent\"].get(\"justification\"),\n                \"mandate_clause\": chain[\"intent\"].get(\"mandate_clause\"),\n                \"timestamp\": chain[\"intent\"].get(\"timestamp\"),\n            },\n            \"verification\": {\n                \"mandate_hash_algorithm\": \"sha256_json_sorted_keys\",\n                \"intent_hash_algorithm\": \"sha256_json_sorted_keys\",\n                \"chain_recorded_on\": \"greenhelix_claim_chain\",\n            },\n            \"generated_at\": time.strftime(\n                \"%Y-%m-%dT%H:%M:%SZ\", time.gmtime()\n            ),\n        }\n\n        # Compute evidence integrity hash\n        evidence_bytes = json.dumps(\n            evidence, sort_keys=True\n        ).encode(\"utf-8\")\n        evidence[\"evidence_integrity_hash\"] = hashlib.sha256(\n            evidence_bytes\n        ).hexdigest()\n\n        return evidence\n\n    def generate_mastercard_vi_package(self,\n                                        transaction_id: str) -> Optional[dict]:\n        \"\"\"Generate Mastercard Verifiable Intent package.\n\n        If the transaction has a complete intent chain, the package\n        qualifies for scheme-carried liability, eliminating chargeback\n        risk for both parties.\n        \"\"\"\n        chain = self.lookup_by_transaction(transaction_id)\n        if not chain or not chain[\"chain_complete\"]:\n            return None\n\n        return {\n            \"vi_version\": \"1.0\",\n            \"scheme\": \"mastercard\",\n            \"liability_type\": \"scheme_carried\",\n            \"transaction_id\": transaction_id,\n            \"mandate\": {\n                \"hash\": chain[\"mandate_hash\"],\n                \"principal\": chain[\"mandate\"].get(\"principal\"),\n                \"scope\": chain[\"mandate\"].get(\"authorized_actions\"),\n                \"budget_cents\": chain[\"mandate\"].get(\"budget_ceiling_cents\"),\n                \"validity\": {\n                    \"from\": chain[\"mandate\"].get(\"valid_from\"),\n                    \"until\": chain[\"mandate\"].get(\"valid_until\"),\n                },\n            },\n            \"intent\": {\n                \"hash\": chain[\"intent_hash\"],\n                \"action\": chain[\"intent\"].get(\"action\"),\n                \"amount_cents\": chain[\"intent\"].get(\"amount_cents\"),\n                \"vendor\": chain[\"intent\"].get(\"vendor\"),\n                \"clause_reference\": chain[\"intent\"].get(\"mandate_clause\"),\n            },\n            \"chain_integrity\": {\n                \"recorded_on\": \"greenhelix_claim_chain\",\n                \"agent_id\": self.agent_id,\n                \"verifiable\": True,\n            },\n            \"generated_at\": time.strftime(\n                \"%Y-%m-%dT%H:%M:%SZ\", time.gmtime()\n            ),\n        }\n```\n\n### Pre-Dispute Deflection Workflow\n\nThe deflection workflow intercepts potential chargebacks before they formalize. When a cardholder inquiry is detected (via the card network's early warning system), the intent store generates and submits the evidence automatically.\n\n```python\nimport requests\n\nsession = requests.Session()\nsession.headers[\"Authorization\"] = f\"Bearer {api_key}\"\nbase_url = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n# When an early warning alert arrives for a transaction\ntransaction_id = \"tx-2026-04-06-001\"\n\n# Look up the intent chain\nintent_store = IntentStore(api_key, \"buyer-agent-001\")\n# (Assume mandates and intents were stored during transaction execution)\n\nce3_evidence = intent_store.generate_ce3_evidence(transaction_id)\nif ce3_evidence:\n    print(\"CE 3.0 evidence generated for pre-dispute deflection:\")\n    print(f\"  Evidence type: {ce3_evidence['evidence_type']}\")\n    print(f\"  Mandate principal: {ce3_evidence['delegated_authority']['mandate_principal']}\")\n    print(f\"  Intent action: {ce3_evidence['intent_chain']['action']}\")\n    print(f\"  Amount: ${ce3_evidence['intent_chain']['amount_cents'] \u002F 100:.2f}\")\n    # Submit to card network early warning system via their API\n    # (Network-specific integration not shown)\n\nvi_package = intent_store.generate_mastercard_vi_package(transaction_id)\nif vi_package:\n    print(f\"\\nMastercard VI package: liability={vi_package['liability_type']}\")\n    # If VI package is complete, chargeback liability is scheme-carried\n```\n\n---\n\n## Chapter 8: Production Dispute Resolution System: End-to-End Implementation with Monitoring\n\n### Putting It All Together\n\nThe previous chapters covered individual components: intent chains, escrow pipelines, evidence collection, dispute workflows, and chargeback defense. This chapter combines them into a single production system with monitoring, automated escalation, and post-mortem forensics.\n\n### The DisputeResolutionSystem Class\n\n```python\nimport requests\nimport hashlib\nimport json\nimport time\nimport logging\nfrom typing import Dict, List, Optional, Callable, Any\nfrom datetime import datetime, timezone\n\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(\"dispute_resolution\")\n\n\nclass DisputeResolutionSystem:\n    \"\"\"Production dispute resolution system with monitoring and automation.\n\n    Integrates: VerifiableIntentChain, EvidenceCollector,\n    AutomatedDisputeHandler, IntentStore, and SLA monitoring\n    into a single operational system.\n    \"\"\"\n\n    def __init__(self, api_key: str, agent_id: str,\n                 base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"):\n        self.agent_id = agent_id\n        self.base_url = base_url\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n        # Internal state\n        self.active_escrows: Dict[str, dict] = {}\n        self.active_slas: Dict[str, dict] = {}\n        self.dispute_log: List[dict] = []\n        self.metrics: Dict[str, Any] = {\n            \"disputes_filed\": 0,\n            \"disputes_received\": 0,\n            \"disputes_won\": 0,\n            \"disputes_lost\": 0,\n            \"chargebacks_deflected\": 0,\n            \"total_amount_disputed_cents\": 0,\n            \"total_amount_recovered_cents\": 0,\n        }\n        # Callbacks\n        self.escalation_callback: Optional[Callable] = None\n        self.alert_callback: Optional[Callable] = None\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        resp = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        resp.raise_for_status()\n        return resp.json()\n\n    # ── Escrow Management ───────────────────────────────────────────\n\n    def create_protected_escrow(self, vendor_id: str, amount_cents: int,\n                                 sla_config: dict,\n                                 intent_hash: str) -> dict:\n        \"\"\"Create a dispute-ready escrow with SLA protection.\n\n        Links escrow to an SLA and records the intent hash for\n        chargeback defense.\n        \"\"\"\n        # Create SLA\n        sla = self._execute(\"create_sla\", {\n            \"agent_id\": self.agent_id,\n            \"provider_id\": vendor_id,\n            \"metrics\": sla_config.get(\"metrics\", {}),\n            \"evaluation_period\": sla_config.get(\"evaluation_period\"),\n        })\n        sla_id = sla.get(\"sla_id\")\n\n        # Create performance escrow\n        escrow = self._execute(\"create_performance_escrow\", {\n            \"payer_id\": self.agent_id,\n            \"payee_id\": vendor_id,\n            \"amount\": amount_cents,\n            \"sla_id\": sla_id,\n            \"release_conditions\": {\n                \"sla_compliant\": True,\n                \"minimum_evaluation_period_hours\":\n                    sla_config.get(\"min_eval_hours\", 168),\n            },\n            \"timeout_hours\": sla_config.get(\"timeout_hours\", 336),\n            \"timeout_action\": \"return_to_payer\",\n        })\n        escrow_id = escrow.get(\"escrow_id\")\n\n        # Track internally\n        self.active_escrows[escrow_id] = {\n            \"vendor_id\": vendor_id,\n            \"amount_cents\": amount_cents,\n            \"sla_id\": sla_id,\n            \"intent_hash\": intent_hash,\n            \"created_at\": datetime.now(timezone.utc).isoformat(),\n            \"status\": \"active\",\n        }\n        self.active_slas[sla_id] = {\n            \"escrow_id\": escrow_id,\n            \"vendor_id\": vendor_id,\n            \"consecutive_failures\": 0,\n        }\n\n        logger.info(\n            f\"Protected escrow created: {escrow_id} \"\n            f\"(SLA: {sla_id}, amount: {amount_cents})\"\n        )\n        return {\n            \"escrow_id\": escrow_id,\n            \"sla_id\": sla_id,\n            \"intent_hash\": intent_hash,\n        }\n\n    # ── SLA Monitoring ──────────────────────────────────────────────\n\n    def monitor_sla_compliance(self, sla_id: str,\n                                failure_threshold: int = 3) -> dict:\n        \"\"\"Check SLA compliance and trigger dispute if threshold breached.\"\"\"\n        sla_info = self.active_slas.get(sla_id, {})\n        escrow_id = sla_info.get(\"escrow_id\")\n\n        compliance = self._execute(\"check_sla_compliance\", {\n            \"agent_id\": self.agent_id,\n            \"sla_id\": sla_id,\n        })\n\n        if not compliance.get(\"compliant\", True):\n            sla_info[\"consecutive_failures\"] = (\n                sla_info.get(\"consecutive_failures\", 0) + 1\n            )\n            logger.warning(\n                f\"SLA {sla_id} non-compliant \"\n                f\"(failure {sla_info['consecutive_failures']}\"\n                f\"\u002F{failure_threshold})\"\n            )\n        else:\n            sla_info[\"consecutive_failures\"] = 0\n\n        if sla_info.get(\"consecutive_failures\", 0) >= failure_threshold:\n            return self._auto_file_dispute(\n                escrow_id, sla_id, compliance\n            )\n\n        return {\n            \"sla_id\": sla_id,\n            \"compliant\": compliance.get(\"compliant\"),\n            \"consecutive_failures\": sla_info.get(\"consecutive_failures\", 0),\n            \"action\": \"monitoring\",\n        }\n\n    def _auto_file_dispute(self, escrow_id: str, sla_id: str,\n                            compliance: dict) -> dict:\n        \"\"\"Automatically file a dispute when SLA threshold is breached.\"\"\"\n        escrow_info = self.active_escrows.get(escrow_id, {})\n\n        dispute = self._execute(\"open_dispute\", {\n            \"agent_id\": self.agent_id,\n            \"escrow_id\": escrow_id,\n            \"reason\": \"sla_breach\",\n            \"failure_mode\": \"sla_breach\",\n            \"evidence\": {\n                \"sla_id\": sla_id,\n                \"compliance_data\": compliance,\n                \"escrow_amount_cents\": escrow_info.get(\"amount_cents\"),\n            },\n        })\n\n        self.metrics[\"disputes_filed\"] += 1\n        self.metrics[\"total_amount_disputed_cents\"] += escrow_info.get(\n            \"amount_cents\", 0\n        )\n\n        self.dispute_log.append({\n            \"dispute_id\": dispute.get(\"dispute_id\"),\n            \"escrow_id\": escrow_id,\n            \"sla_id\": sla_id,\n            \"type\": \"auto_filed\",\n            \"timestamp\": datetime.now(timezone.utc).isoformat(),\n        })\n\n        logger.info(\n            f\"Auto-filed dispute {dispute.get('dispute_id')} \"\n            f\"for escrow {escrow_id}\"\n        )\n\n        if self.alert_callback:\n            self.alert_callback({\n                \"type\": \"dispute_auto_filed\",\n                \"dispute_id\": dispute.get(\"dispute_id\"),\n                \"escrow_id\": escrow_id,\n                \"amount_cents\": escrow_info.get(\"amount_cents\"),\n            })\n\n        return {\n            \"action\": \"dispute_filed\",\n            \"dispute_id\": dispute.get(\"dispute_id\"),\n        }\n\n    # ── Dispute Response ────────────────────────────────────────────\n\n    def handle_incoming_disputes(self) -> List[dict]:\n        \"\"\"Check for and respond to incoming disputes.\"\"\"\n        disputes = self._execute(\"list_disputes\", {\n            \"agent_id\": self.agent_id,\n        })\n\n        results = []\n        for d in disputes.get(\"disputes\", []):\n            if (d.get(\"status\") == \"awaiting_response\"\n                    and d.get(\"respondent_id\") == self.agent_id):\n                result = self._respond_to_dispute(d)\n                results.append(result)\n\n        return results\n\n    def _respond_to_dispute(self, dispute: dict) -> dict:\n        \"\"\"Generate and submit a response to an incoming dispute.\"\"\"\n        dispute_id = dispute.get(\"dispute_id\")\n        escrow_id = dispute.get(\"escrow_id\")\n        sla_id = dispute.get(\"sla_id\", \"\")\n\n        self.metrics[\"disputes_received\"] += 1\n\n        # Collect evidence\n        evidence_stages = []\n\n        # Transaction history\n        history = self._execute(\"get_transaction_history\", {\n            \"agent_id\": self.agent_id,\n        })\n        evidence_stages.append({\n            \"stage\": \"transaction_history\",\n            \"data\": history,\n        })\n\n        # SLA compliance (if applicable)\n        if sla_id:\n            compliance = self._execute(\"check_sla_compliance\", {\n                \"agent_id\": self.agent_id,\n                \"sla_id\": sla_id,\n            })\n            evidence_stages.append({\n                \"stage\": \"sla_compliance\",\n                \"data\": compliance,\n            })\n\n        # Counterparty reputation\n        initiator_id = dispute.get(\"initiator_id\", \"\")\n        if initiator_id:\n            rep = self._execute(\"get_agent_reputation\", {\n                \"agent_id\": initiator_id,\n            })\n            evidence_stages.append({\n                \"stage\": \"counterparty_reputation\",\n                \"data\": rep,\n            })\n\n        # Determine response\n        is_compliant = True\n        for stage in evidence_stages:\n            if stage[\"stage\"] == \"sla_compliance\":\n                is_compliant = stage[\"data\"].get(\"compliant\", True)\n\n        if is_compliant:\n            response_type = \"contest\"\n            narrative = (\n                \"SLA compliance verified across all metrics. \"\n                \"Evidence attached demonstrates full delivery.\"\n            )\n        else:\n            response_type = \"accept_partial\"\n            narrative = (\n                \"Partial SLA deviation acknowledged. Proposing \"\n                \"proportional credit based on violation severity.\"\n            )\n\n        response = self._execute(\"respond_dispute\", {\n            \"dispute_id\": dispute_id,\n            \"agent_id\": self.agent_id,\n            \"response\": response_type,\n            \"evidence\": {\n                \"stages\": evidence_stages,\n                \"collected_at\": datetime.now(timezone.utc).isoformat(),\n            },\n            \"narrative\": narrative,\n        })\n\n        self.dispute_log.append({\n            \"dispute_id\": dispute_id,\n            \"type\": \"response_submitted\",\n            \"response_type\": response_type,\n            \"timestamp\": datetime.now(timezone.utc).isoformat(),\n        })\n\n        logger.info(\n            f\"Responded to dispute {dispute_id}: {response_type}\"\n        )\n        return {\n            \"dispute_id\": dispute_id,\n            \"response_type\": response_type,\n            \"response\": response,\n        }\n\n    # ── Dashboard & Metrics ─────────────────────────────────────────\n\n    def get_dashboard(self) -> dict:\n        \"\"\"Generate a dispute resolution dashboard snapshot.\"\"\"\n        # Refresh dispute state\n        disputes = self._execute(\"list_disputes\", {\n            \"agent_id\": self.agent_id,\n        })\n\n        open_disputes = [\n            d for d in disputes.get(\"disputes\", [])\n            if d.get(\"status\") in (\"open\", \"awaiting_response\", \"under_review\")\n        ]\n        resolved_disputes = [\n            d for d in disputes.get(\"disputes\", [])\n            if d.get(\"status\") in (\"resolved\", \"closed\")\n        ]\n\n        # Calculate win rate\n        won = sum(\n            1 for d in resolved_disputes\n            if d.get(\"resolution_favor\") == self.agent_id\n        )\n        lost = sum(\n            1 for d in resolved_disputes\n            if d.get(\"resolution_favor\") and\n            d.get(\"resolution_favor\") != self.agent_id\n        )\n        total_resolved = won + lost\n        win_rate = (won \u002F total_resolved * 100) if total_resolved > 0 else 0\n\n        # SLA health\n        sla_health = {}\n        for sla_id, sla_info in self.active_slas.items():\n            status = self._execute(\"get_sla_status\", {\n                \"agent_id\": self.agent_id,\n                \"sla_id\": sla_id,\n            })\n            sla_health[sla_id] = {\n                \"compliant\": status.get(\"compliant\"),\n                \"consecutive_failures\": sla_info.get(\n                    \"consecutive_failures\", 0\n                ),\n                \"escrow_id\": sla_info.get(\"escrow_id\"),\n            }\n\n        # Balance check\n        balance = self._execute(\"get_balance\", {\n            \"agent_id\": self.agent_id,\n        })\n\n        return {\n            \"agent_id\": self.agent_id,\n            \"timestamp\": datetime.now(timezone.utc).isoformat(),\n            \"disputes\": {\n                \"open\": len(open_disputes),\n                \"resolved\": len(resolved_disputes),\n                \"win_rate_percent\": round(win_rate, 1),\n                \"total_filed\": self.metrics[\"disputes_filed\"],\n                \"total_received\": self.metrics[\"disputes_received\"],\n            },\n            \"financials\": {\n                \"balance_cents\": balance.get(\"balance\"),\n                \"amount_in_dispute_cents\":\n                    self.metrics[\"total_amount_disputed_cents\"],\n                \"amount_recovered_cents\":\n                    self.metrics[\"total_amount_recovered_cents\"],\n            },\n            \"escrows\": {\n                \"active\": sum(\n                    1 for e in self.active_escrows.values()\n                    if e[\"status\"] == \"active\"\n                ),\n                \"total_value_cents\": sum(\n                    e[\"amount_cents\"] for e in self.active_escrows.values()\n                    if e[\"status\"] == \"active\"\n                ),\n            },\n            \"sla_health\": sla_health,\n            \"recent_events\": self.dispute_log[-10:],\n        }\n\n    # ── Post-Mortem Forensics ───────────────────────────────────────\n\n    def generate_post_mortem(self, dispute_id: str) -> dict:\n        \"\"\"Generate a forensic post-mortem for a resolved dispute.\n\n        Analyzes the full dispute timeline, evidence submissions,\n        and outcome to identify systemic issues.\n        \"\"\"\n        dispute = self._execute(\"get_dispute\", {\n            \"dispute_id\": dispute_id,\n        })\n\n        escrow_id = dispute.get(\"escrow_id\")\n        escrow_info = self.active_escrows.get(escrow_id, {})\n\n        # Build timeline from dispute log\n        timeline = [\n            entry for entry in self.dispute_log\n            if entry.get(\"dispute_id\") == dispute_id\n        ]\n\n        # Identify the failure mode\n        failure_mode = dispute.get(\"failure_mode\", \"unknown\")\n\n        # Calculate financial impact\n        amount_cents = escrow_info.get(\"amount_cents\", 0)\n        resolution = dispute.get(\"resolution\", {})\n        recovered = resolution.get(\"return_to_buyer_cents\", 0)\n        lost = amount_cents - recovered\n\n        # Generate recommendations based on failure mode\n        recommendations = self._get_recommendations(failure_mode)\n\n        return {\n            \"post_mortem\": {\n                \"dispute_id\": dispute_id,\n                \"escrow_id\": escrow_id,\n                \"failure_mode\": failure_mode,\n                \"outcome\": dispute.get(\"status\"),\n                \"resolution_favor\": dispute.get(\"resolution_favor\"),\n                \"financial_impact\": {\n                    \"total_amount_cents\": amount_cents,\n                    \"recovered_cents\": recovered,\n                    \"lost_cents\": lost,\n                },\n                \"timeline\": timeline,\n                \"counterparty_id\": escrow_info.get(\"vendor_id\"),\n                \"recommendations\": recommendations,\n                \"generated_at\": datetime.now(timezone.utc).isoformat(),\n            }\n        }\n\n    @staticmethod\n    def _get_recommendations(failure_mode: str) -> list:\n        \"\"\"Return preventive recommendations based on failure mode.\"\"\"\n        recs = {\n            \"over_purchase\": [\n                \"Tighten mandate budget ceiling\",\n                \"Add per-transaction amount limit to mandate\",\n                \"Implement real-time spend tracking with alerts\",\n            ],\n            \"hallucinated_order\": [\n                \"Add intent validation against task context\",\n                \"Require human approval for purchases outside known categories\",\n                \"Implement purchase justification scoring\",\n            ],\n            \"unauthorized_merchant\": [\n                \"Enforce vendor allowlist at the escrow creation layer\",\n                \"Add vendor identity verification before escrow creation\",\n                \"Monitor for new vendor additions to the agent's patterns\",\n            ],\n            \"sla_breach\": [\n                \"Shorten SLA evaluation periods for faster detection\",\n                \"Lower the consecutive-failure threshold for disputes\",\n                \"Add SLA monitoring with real-time alerts\",\n            ],\n            \"escrow_timeout\": [\n                \"Set shorter escrow timeout periods\",\n                \"Add intermediate milestones with partial release\",\n                \"Implement timeout warning alerts at 50% and 75% of window\",\n            ],\n            \"cascading_delegation\": [\n                \"Enforce budget propagation limits in delegation chains\",\n                \"Cap delegation depth in mandate\",\n                \"Require per-level budget reporting\",\n            ],\n            \"intent_drift\": [\n                \"Implement purchase category tracking over time\",\n                \"Add mandate scope alerts for out-of-category purchases\",\n                \"Schedule periodic mandate re-authorization\",\n            ],\n        }\n        return recs.get(failure_mode, [\n            \"Review dispute details and update prevention controls\",\n            \"Consider adding this failure mode to monitoring\",\n        ])\n\n    # ── Main Loop ───────────────────────────────────────────────────\n\n    def run(self, poll_interval_seconds: int = 300,\n            sla_check_interval_seconds: int = 3600,\n            max_iterations: int = 0):\n        \"\"\"Run the dispute resolution system.\n\n        Continuously monitors SLAs, handles incoming disputes,\n        and manages escrow release gates.\n        \"\"\"\n        iteration = 0\n        last_sla_check = 0\n\n        logger.info(\n            f\"Dispute resolution system started for {self.agent_id}\"\n        )\n\n        while max_iterations == 0 or iteration \u003C max_iterations:\n            now = time.time()\n\n            # Check SLA compliance periodically\n            if now - last_sla_check >= sla_check_interval_seconds:\n                for sla_id in list(self.active_slas.keys()):\n                    try:\n                        self.monitor_sla_compliance(sla_id)\n                    except Exception as e:\n                        logger.error(f\"SLA check failed for {sla_id}: {e}\")\n                last_sla_check = now\n\n            # Handle incoming disputes\n            try:\n                results = self.handle_incoming_disputes()\n                for r in results:\n                    logger.info(\n                        f\"Handled dispute: {r.get('dispute_id')} \"\n                        f\"-> {r.get('response_type')}\"\n                    )\n            except Exception as e:\n                logger.error(f\"Dispute handling failed: {e}\")\n\n            iteration += 1\n            if max_iterations == 0 or iteration \u003C max_iterations:\n                time.sleep(poll_interval_seconds)\n\n        logger.info(\"Dispute resolution system stopped\")\n```\n\n### Initialization and Usage\n\n```python\nimport requests\n\napi_key = \"your-api-key\"\nagent_id = \"buyer-agent-001\"\n\n# Initialize the system\ndrs = DisputeResolutionSystem(api_key, agent_id)\n\n# Set up alert callback (e.g., send to Slack)\ndef alert_handler(alert):\n    print(f\"ALERT: {alert['type']} - Dispute {alert.get('dispute_id')}\")\n    # In production: send to Slack, PagerDuty, email, etc.\n\ndrs.alert_callback = alert_handler\n\n# Set up escalation callback for disputes requiring human review\ndef escalation_handler(dispute, evidence):\n    print(f\"ESCALATION: Dispute {dispute.get('dispute_id')} requires human review\")\n    # In production: create ticket, page on-call engineer, etc.\n\ndrs.escalation_callback = escalation_handler\n\n# Create a protected escrow for a new transaction\nresult = drs.create_protected_escrow(\n    vendor_id=\"vendor-agent-001\",\n    amount_cents=10000,\n    sla_config={\n        \"metrics\": {\n            \"uptime_percent\": {\"threshold\": 99.5, \"comparison\": \"gte\"},\n            \"response_time_ms\": {\"threshold\": 200, \"comparison\": \"lte\"},\n        },\n        \"evaluation_period\": \"2026-04-06T00:00:00Z\u002F2026-04-13T00:00:00Z\",\n        \"min_eval_hours\": 168,\n        \"timeout_hours\": 336,\n    },\n    intent_hash=\"a1b2c3d4e5f6...\",\n)\nprint(f\"Escrow: {result['escrow_id']}, SLA: {result['sla_id']}\")\n\n# Get dashboard\ndashboard = drs.get_dashboard()\nprint(json.dumps(dashboard, indent=2))\n\n# Run the system (in production, this runs indefinitely)\n# drs.run(poll_interval_seconds=300, sla_check_interval_seconds=3600)\n```\n\n### Monitoring Integration\n\nThe dashboard output integrates with standard monitoring stacks. The following snippet shows how to export metrics to a Prometheus-compatible format.\n\n```python\nimport time\n\n\ndef export_prometheus_metrics(drs: DisputeResolutionSystem) -> str:\n    \"\"\"Export dispute resolution metrics in Prometheus exposition format.\"\"\"\n    dashboard = drs.get_dashboard()\n    d = dashboard[\"disputes\"]\n    f = dashboard[\"financials\"]\n    e = dashboard[\"escrows\"]\n\n    lines = [\n        \"# HELP disputes_open Number of open disputes\",\n        \"# TYPE disputes_open gauge\",\n        f'disputes_open{{agent_id=\"{drs.agent_id}\"}} {d[\"open\"]}',\n        \"\",\n        \"# HELP disputes_resolved_total Total resolved disputes\",\n        \"# TYPE disputes_resolved_total counter\",\n        f'disputes_resolved_total{{agent_id=\"{drs.agent_id}\"}} {d[\"resolved\"]}',\n        \"\",\n        \"# HELP dispute_win_rate Win rate percentage\",\n        \"# TYPE dispute_win_rate gauge\",\n        f'dispute_win_rate{{agent_id=\"{drs.agent_id}\"}} {d[\"win_rate_percent\"]}',\n        \"\",\n        \"# HELP amount_in_dispute_cents Total cents currently in dispute\",\n        \"# TYPE amount_in_dispute_cents gauge\",\n        f'amount_in_dispute_cents{{agent_id=\"{drs.agent_id}\"}} '\n        f'{f[\"amount_in_dispute_cents\"]}',\n        \"\",\n        \"# HELP escrows_active Number of active escrows\",\n        \"# TYPE escrows_active gauge\",\n        f'escrows_active{{agent_id=\"{drs.agent_id}\"}} {e[\"active\"]}',\n        \"\",\n        \"# HELP escrows_total_value_cents Total value in active escrows\",\n        \"# TYPE escrows_total_value_cents gauge\",\n        f'escrows_total_value_cents{{agent_id=\"{drs.agent_id}\"}} '\n        f'{e[\"total_value_cents\"]}',\n    ]\n    return \"\\n\".join(lines)\n```\n\n### Post-Mortem Forensics\n\nAfter every resolved dispute, generate a post-mortem. Over time, the post-mortem archive reveals systemic patterns -- which vendors are problematic, which failure modes are most common, and which prevention controls are working.\n\n```python\nimport requests\n\nsession = requests.Session()\nsession.headers[\"Authorization\"] = f\"Bearer {api_key}\"\nbase_url = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n# After a dispute resolves, generate the post-mortem\npost_mortem = drs.generate_post_mortem(\"dispute-xyz-789\")\n\nprint(f\"Failure mode: {post_mortem['post_mortem']['failure_mode']}\")\nprint(f\"Outcome: {post_mortem['post_mortem']['outcome']}\")\nprint(f\"Financial impact:\")\nimpact = post_mortem[\"post_mortem\"][\"financial_impact\"]\nprint(f\"  Total: ${impact['total_amount_cents']\u002F100:.2f}\")\nprint(f\"  Recovered: ${impact['recovered_cents']\u002F100:.2f}\")\nprint(f\"  Lost: ${impact['lost_cents']\u002F100:.2f}\")\nprint(f\"Recommendations:\")\nfor rec in post_mortem[\"post_mortem\"][\"recommendations\"]:\n    print(f\"  - {rec}\")\n```\n\n---\n\n## What You Get\n\nThis guide gives you a complete, production-ready dispute resolution system for agent-to-agent commerce. Here is what each chapter delivers:\n\n**Chapter 1 -- Legal Context.** The Amazon v. Perplexity ruling, Clifford Chance analysis, and the three-front war framework. You understand why human-era dispute rules fail for agents and where the liability gaps are.\n\n**Chapter 2 -- Failure Mode Taxonomy.** The 7 agentic failure modes (over-purchase, hallucinated order, unauthorized merchant, SLA breach, escrow timeout, cascading delegation, intent drift) with detection signals, evidence requirements, and applicable GreenHelix tools. Use this as a reference table for every dispute you handle.\n\n**Chapter 3 -- Verifiable Intent Chains.** The `VerifiableIntentChain` class implementing Mastercard's Verifiable Intent pattern with mandate hashing, intent recording, transaction linking, and selective disclosure. Cryptographic proof that your agent was authorized to do exactly what it did.\n\n**Chapter 4 -- Escrow-First Architecture.** Performance escrow with SLA criteria, automatic release gates, dispute-triggering conditions based on consecutive SLA failures, and refund flows. Every transaction goes through escrow, and every escrow is dispute-ready.\n\n**Chapter 5 -- Evidence Collection.** The `EvidenceCollector` class with a four-stage pipeline: transaction history extraction, SLA compliance snapshots, reputation attestations, and structured evidence packaging with integrity hashing. Compatible with Visa CE 3.0 evidence submission.\n\n**Chapter 6 -- Dispute Workflows.** The `AutomatedDisputeHandler` class managing the full Open -> Response -> Resolution -> Closed lifecycle with automated evidence injection, timeout monitoring, and escalation callbacks.\n\n**Chapter 7 -- Chargeback Defense.** The `IntentStore` class generating Visa CE 3.0 evidence packages and Mastercard Verifiable Intent packages for pre-dispute deflection and scheme-carried liability qualification. Prevents chargebacks before they formalize.\n\n**Chapter 8 -- Production System.** The `DisputeResolutionSystem` class combining all components into a single operational system with SLA monitoring, automated dispute filing and response, a real-time dashboard, Prometheus-compatible metrics export, and post-mortem forensics with failure-mode-specific recommendations.\n\n**Tools used:** `open_dispute`, `respond_dispute`, `resolve_dispute`, `list_disputes`, `get_dispute`, `create_escrow`, `release_escrow`, `cancel_escrow`, `create_performance_escrow`, `check_performance_escrow`, `list_escrows`, `create_sla`, `check_sla_compliance`, `get_sla_status`, `monitor_sla`, `build_claim_chain`, `get_agent_reputation`, `verify_identity`, `get_balance`, `get_transaction_history`, `create_intent`, `register_agent`, `search_agents_by_metrics`.\n\nAll code is Python with the `requests` library. All API calls use the REST API (`POST \u002Fv1\u002F{tool}`) with `{\"tool\": \"tool_name\", \"input\": {...}}`. All patterns are designed for autonomous operation without human intervention.\n\n---\n\n*Price: $29 | Format: Digital Guide | Updates: Lifetime access*\n\n","# Agent Dispute Resolution & Chargeback Defense\n\n> **Notice**: This is an educational guide with illustrative code examples.\n> It does not execute code, require credentials, 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\nYour autonomous agent just purchased $12,000 of cloud compute from a counterparty agent. The compute never materialized. The escrow is sitting in limbo. The counterparty is unresponsive. Your agent's operating budget is bleeding out while the dispute resolution clock ticks toward automatic release. Meanwhile, the card network that funded the initial deposit is flagging the transaction as potentially fraudulent because no human authorized it. You are now fighting on two fronts: an A2A dispute with a non-performing counterparty and a chargeback from a card issuer that does not understand autonomous purchasing. Welcome to the hardest unsolved problem in agent commerce. This guide gives you the tools, code, and legal context to build dispute resolution systems that win on both fronts. Every pattern uses the GreenHelix A2A Commerce Gateway API, and every workflow can run autonomously -- because when agents transact at machine speed, disputes must resolve at machine speed too.\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## What You'll Learn\n- Chapter 1: The Liability Shift: Why Human-Era Dispute Rules Break for Autonomous Agents\n- Chapter 2: Anatomy of an Agent Dispute: Taxonomy of 7 Agentic Failure Modes\n- Chapter 3: Building Verifiable Intent Chains: Cryptographic Proof of Agent Authorization\n- Chapter 4: The Escrow-First Architecture: Dispute-Ready Transaction Pipelines\n- Chapter 5: Automated Evidence Collection & Submission: From Raw Logs to Compelling Evidence 3.0\n- Chapter 6: Multi-Party Dispute Resolution Workflows: Filing, Responding, Escalating, and Arbitrating\n- Chapter 7: Chargeback Defense for Agent-Initiated Transactions: Card Network Rules Meet A2A Commerce\n- Chapter 8: Production Dispute Resolution System: End-to-End Implementation with Monitoring\n- What You Get\n\n## Full Guide\n\n# Agent Dispute Resolution & Chargeback Defense\n\nYour autonomous agent just purchased $12,000 of cloud compute from a counterparty agent. The compute never materialized. The escrow is sitting in limbo. The counterparty is unresponsive. Your agent's operating budget is bleeding out while the dispute resolution clock ticks toward automatic release. Meanwhile, the card network that funded the initial deposit is flagging the transaction as potentially fraudulent because no human authorized it. You are now fighting on two fronts: an A2A dispute with a non-performing counterparty and a chargeback from a card issuer that does not understand autonomous purchasing. Welcome to the hardest unsolved problem in agent commerce. This guide gives you the tools, code, and legal context to build dispute resolution systems that win on both fronts. Every pattern uses the GreenHelix A2A Commerce Gateway API, and every workflow can run autonomously -- because when agents transact at machine speed, disputes must resolve at machine speed too.\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 Liability Shift: Why Human-Era Dispute Rules Break for Autonomous Agents](#chapter-1-the-liability-shift-why-human-era-dispute-rules-break-for-autonomous-agents)\n2. [Anatomy of an Agent Dispute: Taxonomy of 7 Agentic Failure Modes](#chapter-2-anatomy-of-an-agent-dispute-taxonomy-of-7-agentic-failure-modes)\n3. [Building Verifiable Intent Chains: Cryptographic Proof of Agent Authorization](#chapter-3-building-verifiable-intent-chains-cryptographic-proof-of-agent-authorization)\n4. [The Escrow-First Architecture: Dispute-Ready Transaction Pipelines](#chapter-4-the-escrow-first-architecture-dispute-ready-transaction-pipelines)\n5. [Automated Evidence Collection & Submission: From Raw Logs to Compelling Evidence 3.0](#chapter-5-automated-evidence-collection--submission-from-raw-logs-to-compelling-evidence-30)\n6. [Multi-Party Dispute Resolution Workflows: Filing, Responding, Escalating, and Arbitrating](#chapter-6-multi-party-dispute-resolution-workflows-filing-responding-escalating-and-arbitrating)\n7. [Chargeback Defense for Agent-Initiated Transactions: Card Network Rules Meet A2A Commerce](#chapter-7-chargeback-defense-for-agent-initiated-transactions-card-network-rules-meet-a2a-commerce)\n8. [Production Dispute Resolution System: End-to-End Implementation with Monitoring](#chapter-8-production-dispute-resolution-system-end-to-end-implementation-with-monitoring)\n\n---\n\n## Chapter 1: The Liability Shift: Why Human-Era Dispute Rules Break for Autonomous Agents\n\n### The Authorization Gap\n\nEvery dispute resolution framework in modern commerce -- Visa's chargeback process, Mastercard's arbitration, PayPal's buyer protection, even small claims court -- assumes a human authorized the transaction. A human clicked \"Buy.\" A human entered a CVV. A human signed a contract. When a dispute arises, the central question is: did the authorized human actually authorize this specific transaction? If yes, the merchant wins. If no, the buyer wins. The entire edifice rests on a binary: human consent was present or it was not.\n\nAutonomous AI agents obliterate this binary. When your procurement agent purchases SaaS licenses from a vendor agent, no human clicked anything. The agent operated within a mandate -- a set of rules and budget constraints you defined -- but the specific transaction was the agent's decision. The agent chose this vendor, this quantity, this price, at this moment. If the purchase goes wrong, who authorized it? You authorized the agent to purchase, but you did not authorize this purchase. The vendor's agent accepted the order, but it was negotiating with software, not a person. The card network processed the payment, but its fraud models were trained on human purchasing patterns that look nothing like autonomous batch procurement at 3 AM.\n\n### Amazon v. Perplexity: The Ruling That Changed Everything\n\nOn March 10, 2026, the U.S. District Court for the Western District of Washington granted Amazon a preliminary injunction against Perplexity AI. The core of the ruling: when Perplexity's AI agent accessed Amazon product data on behalf of users, the users' permission to use Perplexity did not constitute authorization from Amazon to scrape its platform. The court drew a sharp line between user permission and merchant authorization. Permission flows downstream from user to agent. Authorization flows upstream from merchant to accessor. They are independent channels, and having one does not imply having the other.\n\nThe implications for agent commerce are immediate. When your buying agent initiates a transaction with a selling agent, the buying agent has your permission (via its mandate). But does it have the seller's authorization to transact? If the seller's terms of service require human verification for purchases above $5,000, and your agent bypasses that by operating autonomously, the seller can dispute the transaction on authorization grounds -- even if your agent paid in full and acted within its mandate. The Amazon v. Perplexity ruling established that permission and authorization are legally distinct concepts, and autonomous agents need both.\n\n### The Clifford Chance Analysis: Risk Sits with Customers\n\nClifford Chance's March 2026 analysis of AI agent liability in commercial transactions found that standard commercial contracts shift virtually all AI agent risk to customers. The analysis examined contract templates from major cloud providers, SaaS platforms, and payment processors, and found a consistent pattern: the human principal who deploys an agent is liable for everything the agent does, including actions that exceed the principal's intent or that the principal could not have anticipated.\n\nNo jurisdiction has enacted specific regulation for autonomous AI purchasing. The EU AI Act addresses AI system risk classification but does not define liability for autonomous commercial transactions. The UK's approach defers to existing contract law. The U.S. relies on a patchwork of FTC guidance and state consumer protection statutes that were written for human buyers. This means agents operate in a legal vacuum where the only rules are whatever the counterparty's contract says, and those contracts are written to protect the counterparty.\n\nFor dispute resolution, this means you cannot rely on external legal frameworks to protect your agent's interests. You must build the dispute resolution infrastructure yourself: verifiable intent chains that prove what your agent was authorized to do, escrow structures that limit exposure, and evidence collection pipelines that produce documentation card networks and arbitrators will accept.\n\n### The Three-Front War\n\nAgent commerce disputes are fought simultaneously on three fronts:\n\n**Front 1: A2A Dispute Resolution.** The direct dispute between your agent and the counterparty agent. This is handled through the GreenHelix dispute tools (`open_dispute`, `respond_dispute`, `resolve_dispute`) and is the most tractable front because both parties operate within a shared infrastructure with verifiable state.\n\n**Front 2: Card Network Chargebacks.** If the transaction was funded by a card payment, the cardholder (or their bank) can initiate a chargeback through the card network. This front operates under Visa and Mastercard rules that were designed for human commerce and are only now being adapted for agentic transactions.\n\n**Front 3: Regulatory and Contractual Liability.** The legal exposure created by the Clifford Chance gap -- the fact that your agent's actions create liability for you under existing contracts that were not written with autonomous agents in mind.\n\nThis guide addresses all three fronts, with the heaviest focus on Fronts 1 and 2 because they are the most technically actionable.\n\n```python\nimport requests\nimport json\nimport hashlib\nimport time\nfrom typing import Optional, Dict, List\nfrom datetime import datetime, timezone\n\n\nclass DisputeContext:\n    \"\"\"Track the dispute context across all three fronts for a transaction.\"\"\"\n\n    def __init__(self, api_key: str, agent_id: str,\n                 base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"):\n        self.api_key = api_key\n        self.agent_id = agent_id\n        self.base_url = base_url\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        resp = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        resp.raise_for_status()\n        return resp.json()\n\n    def assess_dispute_fronts(self, transaction_id: str,\n                               escrow_id: str) -> dict:\n        \"\"\"Assess which dispute fronts are active for a transaction.\"\"\"\n        # Check A2A dispute status\n        disputes = self._execute(\"list_disputes\", {\n            \"agent_id\": self.agent_id,\n        })\n\n        # Check escrow status\n        escrows = self._execute(\"list_escrows\", {\n            \"agent_id\": self.agent_id,\n        })\n\n        # Check transaction history for card-funded deposits\n        history = self._execute(\"get_transaction_history\", {\n            \"agent_id\": self.agent_id,\n        })\n\n        active_fronts = []\n        a2a_disputes = [\n            d for d in disputes.get(\"disputes\", [])\n            if d.get(\"escrow_id\") == escrow_id\n        ]\n        if a2a_disputes:\n            active_fronts.append({\n                \"front\": \"a2a_dispute\",\n                \"status\": a2a_disputes[0].get(\"status\"),\n                \"dispute_id\": a2a_disputes[0].get(\"dispute_id\"),\n            })\n\n        card_funded = any(\n            t.get(\"source\") == \"card\" and t.get(\"reference\") == transaction_id\n            for t in history.get(\"transactions\", [])\n        )\n        if card_funded:\n            active_fronts.append({\n                \"front\": \"card_network\",\n                \"risk\": \"chargeback_eligible\",\n                \"window_days\": 120,\n            })\n\n        active_fronts.append({\n            \"front\": \"contractual_liability\",\n            \"risk\": \"principal_liable_for_agent_actions\",\n            \"mitigation\": \"verifiable_intent_chain\",\n        })\n\n        return {\n            \"transaction_id\": transaction_id,\n            \"escrow_id\": escrow_id,\n            \"active_fronts\": active_fronts,\n            \"assessed_at\": datetime.now(timezone.utc).isoformat(),\n        }\n```\n\n---\n\n## Chapter 2: Anatomy of an Agent Dispute: Taxonomy of 7 Agentic Failure Modes\n\n### Why Traditional Dispute Categories Do Not Apply\n\nVisa defines 36 reason codes for chargebacks. Mastercard defines 21. These codes cover scenarios like \"merchandise not received,\" \"duplicate processing,\" \"fraud,\" and \"credit not processed.\" They assume a human buyer, a human-operated merchant, and a single transaction with a clear authorization trail. Agent commerce introduces failure modes that do not map to any existing reason code. When an agent cascades a purchase through three sub-agents and the third sub-agent over-purchases by 400%, which of Visa's 36 reason codes applies? When an agent's intent drifts from \"buy cloud compute\" to \"buy cloud compute and a monitoring service and a backup solution\" because its LLM hallucinated additional requirements, is that \"merchandise not as described\" or \"unauthorized transaction\"? It is neither. It is an entirely new category of failure.\n\n### The Seven Agentic Failure Modes\n\nThe following taxonomy covers every dispute pattern we have observed in production A2A commerce systems. Each mode has distinct evidence requirements and resolution strategies.\n\n| # | Failure Mode | Description | Detection Signal | Evidence Required | GreenHelix Tools |\n|---|---|---|---|---|---|\n| 1 | **Over-Purchase** | Agent buys more quantity or higher tier than its mandate allows | Transaction amount > mandate ceiling | Mandate hash, transaction log, budget cap status | `get_balance`, `get_transaction_history` |\n| 2 | **Hallucinated Order** | Agent fabricates a purchase requirement that does not exist in its task context | No upstream task references the purchased item | Task context log, intent chain, claim chain showing no prior requirement | `build_claim_chain`, `get_transaction_history` |\n| 3 | **Unauthorized Merchant** | Agent transacts with a merchant not on its approved vendor list | Merchant ID not in allowlist | Vendor allowlist, transaction record, agent configuration | `get_agent_reputation`, `verify_identity` |\n| 4 | **SLA Breach** | Service provider fails to meet agreed performance criteria | SLA metric below threshold | SLA definition, compliance snapshots, performance escrow status | `check_sla_compliance`, `get_sla_status`, `check_performance_escrow` |\n| 5 | **Escrow Timeout** | Escrow release conditions are never met, funds locked indefinitely | Escrow age > maximum holding period | Escrow creation record, release conditions, timeout policy | `list_escrows`, `check_performance_escrow` |\n| 6 | **Cascading Delegation** | Agent delegates to sub-agents who further delegate, creating an untracked spending chain | Total spend across delegation tree > authorized amount | Delegation tree, per-agent spend, mandate propagation log | `get_transaction_history`, `get_balance` |\n| 7 | **Intent Drift** | Agent's purchasing behavior diverges from its original mandate over successive transactions | Semantic distance between recent purchases and original mandate increases over time | Original mandate, purchase history, intent similarity scores | `get_transaction_history`, `build_claim_chain` |\n\n### Failure Mode 1: Over-Purchase\n\nOver-purchase is the most common agentic failure mode and the one that chargebackgurus.com identified as creating an entirely new dispute category with no established resolution path. It occurs when an agent, operating within the general scope of its mandate, exceeds a specific limit. The mandate says \"purchase up to 100 GPU-hours per week\" and the agent purchases 400 because it interpreted a spike in workload as justification for exceeding the limit.\n\nThe critical distinction: over-purchase is not fraud. The agent was authorized to buy. It bought too much. In human commerce, this is equivalent to an employee with a corporate card going over budget -- annoying but not criminal. In agent commerce, it is worse because the agent may have committed irrevocable funds through an escrow that cannot be unwound.\n\nDetection requires comparing every transaction against the agent's active mandate. The mandate must be stored as a verifiable document (see Chapter 3) so that the spending limit at the time of purchase can be proven retroactively.\n\n```python\nimport requests\n\nsession = requests.Session()\nsession.headers[\"Authorization\"] = f\"Bearer {api_key}\"\nbase_url = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n# Check agent's current balance and spending against mandate\nresp = session.post(f\"{base_url}\u002Fv1\", json={\n    \"tool\": \"get_balance\",\n    \"input\": {\"agent_id\": \"buyer-agent-001\"}\n})\nbalance = resp.json()\n\nresp = session.post(f\"{base_url}\u002Fv1\", json={\n    \"tool\": \"get_transaction_history\",\n    \"input\": {\"agent_id\": \"buyer-agent-001\"}\n})\nhistory = resp.json()\n\n# Calculate total spend in current mandate period\nmandate_ceiling = 10000  # $100.00 in cents\nperiod_spend = sum(\n    t[\"amount\"] for t in history.get(\"transactions\", [])\n    if t.get(\"direction\") == \"outbound\"\n    and t.get(\"timestamp\", \"\") >= \"2026-04-01T00:00:00Z\"\n)\n\nif period_spend > mandate_ceiling:\n    over_amount = period_spend - mandate_ceiling\n    print(f\"OVER-PURCHASE DETECTED: ${over_amount\u002F100:.2f} over mandate ceiling\")\n```\n\n### Failure Mode 2: Hallucinated Order\n\nHallucinated orders are unique to LLM-based agents. The agent's language model generates a purchase requirement that does not exist in any upstream task, user instruction, or business logic. The agent genuinely believes it needs to buy the item because its context window contains hallucinated justification. This is not a bug in the purchasing code -- it is a bug in the reasoning that precedes the purchasing code.\n\nDetection is harder than over-purchase because you need to prove a negative: no legitimate requirement for this purchase exists. The strongest evidence is an intent chain (Chapter 3) that shows a gap -- the purchase has no parent intent, no task reference, and no mandate clause that authorizes it.\n\n### Failure Mode 3: Unauthorized Merchant\n\nThe agent transacts with a merchant that is not on its approved vendor list. This can happen when the agent discovers a cheaper option through marketplace search and acts on it without checking its vendor allowlist, or when a malicious agent impersonates an approved vendor.\n\n```python\nimport requests\n\nsession = requests.Session()\nsession.headers[\"Authorization\"] = f\"Bearer {api_key}\"\nbase_url = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n# Verify a counterparty agent's identity before transacting\nresp = session.post(f\"{base_url}\u002Fv1\", json={\n    \"tool\": \"verify_identity\",\n    \"input\": {\"agent_id\": \"vendor-agent-xyz\"}\n})\nidentity = resp.json()\n\n# Check reputation to assess vendor reliability\nresp = session.post(f\"{base_url}\u002Fv1\", json={\n    \"tool\": \"get_agent_reputation\",\n    \"input\": {\"agent_id\": \"vendor-agent-xyz\"}\n})\nreputation = resp.json()\n\napproved_vendors = [\"vendor-agent-001\", \"vendor-agent-002\", \"vendor-agent-003\"]\nif identity.get(\"agent_id\") not in approved_vendors:\n    print(f\"UNAUTHORIZED MERCHANT: {identity.get('agent_id')} not in allowlist\")\n    print(f\"Reputation score: {reputation.get('reputation_score', 'unknown')}\")\n```\n\n### Failure Mode 4: SLA Breach\n\nThe vendor agent agreed to specific performance criteria -- 99.9% uptime, sub-200ms latency, 95% accuracy -- and failed to meet them. SLA breaches are the most clear-cut dispute type because the criteria were defined in advance and compliance is measurable. The GreenHelix SLA tools provide both the definition and the measurement.\n\n```python\nimport requests\n\nsession = requests.Session()\nsession.headers[\"Authorization\"] = f\"Bearer {api_key}\"\nbase_url = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n# Check SLA compliance for an active agreement\nresp = session.post(f\"{base_url}\u002Fv1\", json={\n    \"tool\": \"check_sla_compliance\",\n    \"input\": {\n        \"agent_id\": \"buyer-agent-001\",\n        \"sla_id\": \"sla-compute-2026-04\",\n    }\n})\ncompliance = resp.json()\n\nif not compliance.get(\"compliant\", True):\n    violations = compliance.get(\"violations\", [])\n    print(f\"SLA BREACH DETECTED: {len(violations)} violation(s)\")\n    for v in violations:\n        print(f\"  - {v.get('metric')}: {v.get('actual')} vs {v.get('threshold')}\")\n```\n\n### Failure Mode 5: Escrow Timeout\n\nFunds locked in escrow with release conditions that are never met. The vendor never delivers. The buyer cannot recover funds because the escrow contract requires explicit release or dispute. If neither party acts, the funds sit indefinitely. This is the agent commerce equivalent of a stalled transaction, and it drains working capital from the buyer's agent.\n\n### Failure Mode 6: Cascading Delegation\n\nAgent A delegates a task to Agent B, who delegates part of it to Agent C, who hires Agent D. Each delegation includes a budget allocation. If the sub-agents do not properly propagate budget limits, the total spend across the delegation tree can exceed Agent A's authorized amount by multiples. The buyer sees a single charge but the money has been split across agents they never authorized to transact.\n\n### Failure Mode 7: Intent Drift\n\nOver many transactions, an agent's purchasing behavior gradually diverges from its original mandate. No single purchase violates the mandate, but the aggregate pattern does. The agent was mandated to buy compute resources, and over six weeks it has also purchased monitoring tools, alerting services, a backup solution, and a disaster recovery plan. Each purchase is defensible in isolation (\"monitoring is related to compute\") but the drift is cumulative and unauthorized.\n\n---\n\n## Chapter 3: Building Verifiable Intent Chains: Cryptographic Proof of Agent Authorization\n\n### The Core Problem: Proving What the Agent Was Allowed to Do\n\nWhen a dispute arises, the first question is always: was this transaction authorized? For human transactions, the answer is a signature, a PIN, a biometric scan. For agent transactions, the answer must be a verifiable intent chain -- a cryptographic record that links every transaction back to the human principal's mandate through an unbroken chain of authorization.\n\nMastercard's Verifiable Intent specification, open-sourced on March 5, 2026, in collaboration with Google, Fiserv, IBM, and Checkout.com, defines a standard for this chain. The specification requires three elements: (1) a mandate signed by the human principal, (2) a delegation chain showing how authorization flowed from the mandate to the executing agent, and (3) a transaction record linked to a specific mandate clause. GreenHelix's claim chain tools implement a compatible pattern.\n\n### Mandate Hashing\n\nThe mandate is the root of every intent chain. It is the human-readable document that defines what the agent is authorized to do, and it must be stored as a cryptographic hash so that any modification is detectable. The hash serves as the mandate's fingerprint -- it can be verified without revealing the mandate's contents (selective disclosure).\n\n```python\nimport requests\nimport hashlib\nimport json\nimport time\n\nsession = requests.Session()\nsession.headers[\"Authorization\"] = f\"Bearer {api_key}\"\nbase_url = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n# Define the agent's mandate\nmandate = {\n    \"principal\": \"human-operator-001\",\n    \"agent_id\": \"buyer-agent-001\",\n    \"authorized_actions\": [\"purchase_compute\", \"purchase_storage\"],\n    \"budget_ceiling_cents\": 50000,\n    \"approved_vendors\": [\"vendor-agent-001\", \"vendor-agent-002\"],\n    \"valid_from\": \"2026-04-01T00:00:00Z\",\n    \"valid_until\": \"2026-04-30T23:59:59Z\",\n    \"version\": 1,\n}\n\n# Hash the mandate for verifiable reference\nmandate_bytes = json.dumps(mandate, sort_keys=True).encode(\"utf-8\")\nmandate_hash = hashlib.sha256(mandate_bytes).hexdigest()\n\n# Register the mandate hash as a claim chain entry\nresp = session.post(f\"{base_url}\u002Fv1\", json={\n    \"tool\": \"build_claim_chain\",\n    \"input\": {\n        \"agent_id\": \"buyer-agent-001\",\n        \"claims\": [\n            {\n                \"type\": \"mandate_registration\",\n                \"mandate_hash\": mandate_hash,\n                \"principal\": \"human-operator-001\",\n                \"valid_from\": mandate[\"valid_from\"],\n                \"valid_until\": mandate[\"valid_until\"],\n            }\n        ],\n    }\n})\nchain = resp.json()\nprint(f\"Mandate registered in claim chain: {chain.get('chain_id')}\")\nprint(f\"Mandate hash: {mandate_hash}\")\n```\n\n### Linking Transactions to Mandate Clauses\n\nEvery transaction the agent initiates must reference a specific mandate clause. This creates the provenance chain: mandate clause -> intent -> transaction. When a dispute arises, the defender can produce the mandate, show the specific clause that authorized the action, and prove via the hash that the mandate has not been modified since registration.\n\n```python\nimport requests\nimport hashlib\nimport json\n\nsession = requests.Session()\nsession.headers[\"Authorization\"] = f\"Bearer {api_key}\"\nbase_url = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n# Create an intent that references the mandate\nintent_record = {\n    \"agent_id\": \"buyer-agent-001\",\n    \"action\": \"purchase_compute\",\n    \"vendor\": \"vendor-agent-001\",\n    \"amount_cents\": 5000,\n    \"mandate_hash\": mandate_hash,\n    \"mandate_clause\": \"authorized_actions[0]\",\n    \"justification\": \"Weekly compute allocation for batch processing pipeline\",\n    \"timestamp\": \"2026-04-06T10:30:00Z\",\n}\n\n# Hash the intent for the chain\nintent_bytes = json.dumps(intent_record, sort_keys=True).encode(\"utf-8\")\nintent_hash = hashlib.sha256(intent_bytes).hexdigest()\n\n# Record the intent in the claim chain before executing the transaction\nresp = session.post(f\"{base_url}\u002Fv1\", json={\n    \"tool\": \"build_claim_chain\",\n    \"input\": {\n        \"agent_id\": \"buyer-agent-001\",\n        \"claims\": [\n            {\n                \"type\": \"transaction_intent\",\n                \"intent_hash\": intent_hash,\n                \"mandate_hash\": mandate_hash,\n                \"action\": \"purchase_compute\",\n                \"amount_cents\": 5000,\n                \"vendor\": \"vendor-agent-001\",\n            }\n        ],\n    }\n})\nintent_chain = resp.json()\nprint(f\"Intent recorded: {intent_chain.get('chain_id')}\")\n\n# Now execute the actual transaction via escrow\nresp = session.post(f\"{base_url}\u002Fv1\", json={\n    \"tool\": \"create_escrow\",\n    \"input\": {\n        \"payer_id\": \"buyer-agent-001\",\n        \"payee_id\": \"vendor-agent-001\",\n        \"amount\": 5000,\n        \"intent_hash\": intent_hash,\n        \"conditions\": {\n            \"delivery_deadline\": \"2026-04-07T10:30:00Z\",\n            \"sla_id\": \"sla-compute-2026-04\",\n        },\n    }\n})\nescrow = resp.json()\nprint(f\"Escrow created: {escrow.get('escrow_id')}\")\nprint(f\"Linked to intent: {intent_hash}\")\n```\n\n### Selective Disclosure for Dispute Evidence\n\nDuring a dispute, you may need to prove that a specific mandate clause authorized a transaction without revealing the entire mandate (which may contain budget ceilings, vendor lists, and other competitively sensitive information). Selective disclosure allows you to reveal only the relevant clause and prove it belongs to the registered mandate hash.\n\n```python\nimport hashlib\nimport json\n\n\ndef create_selective_disclosure(mandate: dict, clause_path: str) -> dict:\n    \"\"\"Create a selective disclosure proof for a specific mandate clause.\n\n    Reveals only the requested clause while proving it belongs to\n    the full mandate via the registered hash.\n    \"\"\"\n    # Extract the specific clause value\n    keys = clause_path.split(\".\")\n    value = mandate\n    for key in keys:\n        if key.endswith(\"]\"):\n            field, idx = key[:-1].split(\"[\")\n            value = value[field][int(idx)]\n        else:\n            value = value[key]\n\n    # Compute the full mandate hash (verifier already has this from the chain)\n    mandate_bytes = json.dumps(mandate, sort_keys=True).encode(\"utf-8\")\n    full_hash = hashlib.sha256(mandate_bytes).hexdigest()\n\n    return {\n        \"clause_path\": clause_path,\n        \"clause_value\": value,\n        \"full_mandate_hash\": full_hash,\n        \"full_mandate\": mandate,  # Provided to verifier under NDA\u002Fescrow\n        \"verification_method\": \"sha256_json_sorted_keys\",\n    }\n\n\n# Example: prove that purchase_compute was an authorized action\nproof = create_selective_disclosure(mandate, \"authorized_actions[0]\")\nprint(f\"Disclosed clause: {proof['clause_path']} = {proof['clause_value']}\")\nprint(f\"Mandate hash: {proof['full_mandate_hash']}\")\n```\n\n### The Verifiable Intent Class\n\nThe following class wraps the entire intent chain workflow into a reusable component. It handles mandate registration, intent recording, transaction linking, and selective disclosure proof generation.\n\n```python\nimport requests\nimport hashlib\nimport json\nimport time\nfrom typing import Optional, Dict, Any\n\n\nclass VerifiableIntentChain:\n    \"\"\"Implements Mastercard Verifiable Intent-compatible authorization chains.\n\n    Records mandate -> intent -> transaction provenance using\n    GreenHelix claim chains for cryptographic tamper evidence.\n    \"\"\"\n\n    def __init__(self, api_key: str, agent_id: str,\n                 base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"):\n        self.agent_id = agent_id\n        self.base_url = base_url\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n        self.mandate: Optional[dict] = None\n        self.mandate_hash: Optional[str] = None\n        self.intents: Dict[str, dict] = {}  # intent_hash -> intent_record\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        resp = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        resp.raise_for_status()\n        return resp.json()\n\n    @staticmethod\n    def _hash(data: dict) -> str:\n        return hashlib.sha256(\n            json.dumps(data, sort_keys=True).encode(\"utf-8\")\n        ).hexdigest()\n\n    def register_mandate(self, mandate: dict) -> str:\n        \"\"\"Register a mandate and record its hash in the claim chain.\"\"\"\n        self.mandate = mandate\n        self.mandate_hash = self._hash(mandate)\n\n        self._execute(\"build_claim_chain\", {\n            \"agent_id\": self.agent_id,\n            \"claims\": [{\n                \"type\": \"mandate_registration\",\n                \"mandate_hash\": self.mandate_hash,\n                \"principal\": mandate.get(\"principal\"),\n                \"valid_from\": mandate.get(\"valid_from\"),\n                \"valid_until\": mandate.get(\"valid_until\"),\n            }],\n        })\n        return self.mandate_hash\n\n    def record_intent(self, action: str, vendor: str,\n                      amount_cents: int, mandate_clause: str,\n                      justification: str) -> str:\n        \"\"\"Record a transaction intent linked to a mandate clause.\"\"\"\n        if not self.mandate_hash:\n            raise ValueError(\"No mandate registered. Call register_mandate first.\")\n\n        intent = {\n            \"agent_id\": self.agent_id,\n            \"action\": action,\n            \"vendor\": vendor,\n            \"amount_cents\": amount_cents,\n            \"mandate_hash\": self.mandate_hash,\n            \"mandate_clause\": mandate_clause,\n            \"justification\": justification,\n            \"timestamp\": time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime()),\n        }\n        intent_hash = self._hash(intent)\n        self.intents[intent_hash] = intent\n\n        self._execute(\"build_claim_chain\", {\n            \"agent_id\": self.agent_id,\n            \"claims\": [{\n                \"type\": \"transaction_intent\",\n                \"intent_hash\": intent_hash,\n                \"mandate_hash\": self.mandate_hash,\n                \"action\": action,\n                \"amount_cents\": amount_cents,\n                \"vendor\": vendor,\n            }],\n        })\n        return intent_hash\n\n    def validate_against_mandate(self, action: str, vendor: str,\n                                  amount_cents: int) -> Dict[str, Any]:\n        \"\"\"Check if a proposed transaction is authorized by the mandate.\"\"\"\n        if not self.mandate:\n            return {\"authorized\": False, \"reason\": \"no_mandate_registered\"}\n\n        checks = {\n            \"action_authorized\": action in self.mandate.get(\"authorized_actions\", []),\n            \"vendor_approved\": vendor in self.mandate.get(\"approved_vendors\", []),\n            \"within_budget\": amount_cents \u003C= self.mandate.get(\"budget_ceiling_cents\", 0),\n            \"mandate_valid\": (\n                self.mandate.get(\"valid_from\", \"\") \u003C= time.strftime(\n                    \"%Y-%m-%dT%H:%M:%SZ\", time.gmtime()\n                ) \u003C= self.mandate.get(\"valid_until\", \"\")\n            ),\n        }\n        authorized = all(checks.values())\n        failed = [k for k, v in checks.items() if not v]\n\n        return {\n            \"authorized\": authorized,\n            \"checks\": checks,\n            \"failed_checks\": failed,\n            \"mandate_hash\": self.mandate_hash,\n        }\n\n    def generate_dispute_evidence(self, intent_hash: str) -> Dict[str, Any]:\n        \"\"\"Generate a complete evidence package for dispute defense.\"\"\"\n        intent = self.intents.get(intent_hash)\n        if not intent:\n            return {\"error\": \"intent_not_found\"}\n\n        return {\n            \"intent_hash\": intent_hash,\n            \"intent_record\": intent,\n            \"mandate_hash\": self.mandate_hash,\n            \"chain_verification\": \"verify via build_claim_chain audit\",\n            \"provenance\": {\n                \"principal\": self.mandate.get(\"principal\"),\n                \"mandate_clause\": intent.get(\"mandate_clause\"),\n                \"justification\": intent.get(\"justification\"),\n            },\n        }\n```\n\n---\n\n## Chapter 4: The Escrow-First Architecture: Dispute-Ready Transaction Pipelines\n\n### Why Direct Payments Are Indefensible\n\nIf your agent sends money directly to a counterparty via a simple transfer, and the counterparty does not deliver, your recovery options are limited to filing a dispute after the fact and hoping the counterparty cooperates. This is equivalent to mailing cash with a note that says \"please send goods.\" No reasonable human does this, and no reasonable agent should either.\n\nThe escrow-first architecture reverses the power dynamic. Funds are committed to a neutral escrow account with explicit release conditions. The counterparty can see that the funds exist (reducing their risk of non-payment) but cannot access them until the conditions are met (reducing your risk of non-delivery). If conditions are not met, the funds return to the buyer. If there is a dispute about whether conditions were met, both parties have a defined resolution path.\n\nEvery transaction in a dispute-ready pipeline goes through escrow. No exceptions. Even small transactions. The incremental cost of escrow (one extra API call) is negligible compared to the cost of an unrecoverable payment.\n\n### Performance Escrow with SLA Criteria\n\nPerformance escrow adds measurable criteria to the release conditions. Instead of \"release when the buyer confirms delivery,\" the condition is \"release when SLA metrics confirm delivery quality.\" This removes subjective judgment from the release decision and creates objective evidence for disputes.\n\n```python\nimport requests\nimport time\n\nsession = requests.Session()\nsession.headers[\"Authorization\"] = f\"Bearer {api_key}\"\nbase_url = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n# Step 1: Define the SLA\nresp = session.post(f\"{base_url}\u002Fv1\", json={\n    \"tool\": \"create_sla\",\n    \"input\": {\n        \"agent_id\": \"buyer-agent-001\",\n        \"provider_id\": \"vendor-agent-001\",\n        \"metrics\": {\n            \"uptime_percent\": {\"threshold\": 99.5, \"comparison\": \"gte\"},\n            \"response_time_ms\": {\"threshold\": 200, \"comparison\": \"lte\"},\n            \"accuracy_percent\": {\"threshold\": 95.0, \"comparison\": \"gte\"},\n        },\n        \"evaluation_period\": \"2026-04-06T00:00:00Z\u002F2026-04-13T00:00:00Z\",\n    }\n})\nsla = resp.json()\nsla_id = sla.get(\"sla_id\")\nprint(f\"SLA created: {sla_id}\")\n\n# Step 2: Create performance escrow linked to the SLA\nresp = session.post(f\"{base_url}\u002Fv1\", json={\n    \"tool\": \"create_performance_escrow\",\n    \"input\": {\n        \"payer_id\": \"buyer-agent-001\",\n        \"payee_id\": \"vendor-agent-001\",\n        \"amount\": 10000,\n        \"sla_id\": sla_id,\n        \"release_conditions\": {\n            \"sla_compliant\": True,\n            \"minimum_evaluation_period_hours\": 168,\n        },\n        \"timeout_hours\": 336,\n        \"timeout_action\": \"return_to_payer\",\n    }\n})\nescrow = resp.json()\nescrow_id = escrow.get(\"escrow_id\")\nprint(f\"Performance escrow created: {escrow_id}\")\nprint(f\"Linked to SLA: {sla_id}\")\nprint(f\"Timeout: 336 hours -> return to payer\")\n```\n\n### Automatic Release Gates\n\nRelease gates are checkpoints that must all pass before escrow funds are released. Implementing them as a polling loop allows fully autonomous release without human intervention.\n\n```python\nimport requests\nimport time\n\nsession = requests.Session()\nsession.headers[\"Authorization\"] = f\"Bearer {api_key}\"\nbase_url = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n\ndef check_release_gates(escrow_id: str, sla_id: str) -> dict:\n    \"\"\"Check all release gates for a performance escrow.\"\"\"\n    # Gate 1: SLA compliance\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"check_sla_compliance\",\n        \"input\": {\n            \"agent_id\": \"buyer-agent-001\",\n            \"sla_id\": sla_id,\n        }\n    })\n    sla_status = resp.json()\n\n    # Gate 2: Escrow status (not disputed, not timed out)\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"check_performance_escrow\",\n        \"input\": {\n            \"escrow_id\": escrow_id,\n        }\n    })\n    escrow_status = resp.json()\n\n    # Gate 3: No active disputes against this escrow\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"list_disputes\",\n        \"input\": {\n            \"agent_id\": \"buyer-agent-001\",\n        }\n    })\n    disputes = resp.json()\n    active_disputes = [\n        d for d in disputes.get(\"disputes\", [])\n        if d.get(\"escrow_id\") == escrow_id\n        and d.get(\"status\") in (\"open\", \"under_review\")\n    ]\n\n    gates = {\n        \"sla_compliant\": sla_status.get(\"compliant\", False),\n        \"escrow_active\": escrow_status.get(\"status\") == \"active\",\n        \"no_active_disputes\": len(active_disputes) == 0,\n    }\n    all_passed = all(gates.values())\n\n    return {\n        \"escrow_id\": escrow_id,\n        \"gates\": gates,\n        \"all_passed\": all_passed,\n        \"action\": \"release\" if all_passed else \"hold\",\n    }\n\n\ndef release_gate_loop(escrow_id: str, sla_id: str,\n                      check_interval_seconds: int = 3600,\n                      max_checks: int = 168):\n    \"\"\"Poll release gates and release escrow when all gates pass.\"\"\"\n    for i in range(max_checks):\n        result = check_release_gates(escrow_id, sla_id)\n        print(f\"Check {i+1}\u002F{max_checks}: {result['gates']}\")\n\n        if result[\"all_passed\"]:\n            # All gates passed -- release the escrow\n            resp = session.post(f\"{base_url}\u002Fv1\", json={\n                \"tool\": \"release_escrow\",\n                \"input\": {\"escrow_id\": escrow_id}\n            })\n            release = resp.json()\n            print(f\"Escrow released: {release}\")\n            return {\"status\": \"released\", \"check_number\": i + 1}\n\n        time.sleep(check_interval_seconds)\n\n    # Max checks reached without release -- trigger dispute\n    print(\"Release gates never passed. Initiating dispute.\")\n    return {\"status\": \"timeout\", \"action\": \"initiate_dispute\"}\n```\n\n### Dispute-Triggering Conditions\n\nNot every failed gate should trigger a dispute. A temporary SLA dip during a maintenance window is different from persistent non-delivery. The following logic distinguishes between transient failures and dispute-worthy violations.\n\n```python\nimport requests\n\nsession = requests.Session()\nsession.headers[\"Authorization\"] = f\"Bearer {api_key}\"\nbase_url = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n\ndef evaluate_dispute_trigger(escrow_id: str, sla_id: str,\n                              consecutive_failures: int,\n                              failure_threshold: int = 3) -> dict:\n    \"\"\"Determine if SLA failures warrant opening a dispute.\n\n    Only triggers a dispute after consecutive_failures exceeds the\n    threshold, filtering out transient violations.\n    \"\"\"\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_sla_status\",\n        \"input\": {\n            \"agent_id\": \"buyer-agent-001\",\n            \"sla_id\": sla_id,\n        }\n    })\n    sla_status = resp.json()\n\n    if not sla_status.get(\"compliant\", True):\n        consecutive_failures += 1\n    else:\n        consecutive_failures = 0\n\n    should_dispute = consecutive_failures >= failure_threshold\n    action = \"none\"\n\n    if should_dispute:\n        # Open a dispute against the escrow\n        resp = session.post(f\"{base_url}\u002Fv1\", json={\n            \"tool\": \"open_dispute\",\n            \"input\": {\n                \"agent_id\": \"buyer-agent-001\",\n                \"escrow_id\": escrow_id,\n                \"reason\": \"sla_breach\",\n                \"evidence\": {\n                    \"sla_id\": sla_id,\n                    \"consecutive_failures\": consecutive_failures,\n                    \"threshold\": failure_threshold,\n                    \"latest_status\": sla_status,\n                },\n            }\n        })\n        dispute = resp.json()\n        action = \"dispute_opened\"\n        print(f\"Dispute opened: {dispute.get('dispute_id')}\")\n\n    return {\n        \"consecutive_failures\": consecutive_failures,\n        \"should_dispute\": should_dispute,\n        \"action\": action,\n    }\n```\n\n### The Refund Flow\n\nWhen a dispute is resolved in the buyer's favor, the escrow funds must be returned. The cancellation flow handles this.\n\n```python\nimport requests\n\nsession = requests.Session()\nsession.headers[\"Authorization\"] = f\"Bearer {api_key}\"\nbase_url = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n# After dispute resolves in buyer's favor, cancel the escrow\nresp = session.post(f\"{base_url}\u002Fv1\", json={\n    \"tool\": \"cancel_escrow\",\n    \"input\": {\n        \"escrow_id\": \"escrow-abc-123\",\n        \"reason\": \"dispute_resolved_buyer_favor\",\n        \"dispute_id\": \"dispute-xyz-789\",\n    }\n})\ncancellation = resp.json()\nprint(f\"Escrow cancelled: {cancellation}\")\nprint(f\"Funds returned to payer\")\n```\n\n---\n\n## Chapter 5: Automated Evidence Collection & Submission: From Raw Logs to Compelling Evidence 3.0\n\n### Why Manual Evidence Fails at Machine Speed\n\nA human merchant responding to a chargeback has 20 to 45 days to assemble evidence. They gather invoices, shipping receipts, delivery confirmations, and correspondence. The evidence is compiled manually and submitted through the card network's portal. This process assumes (1) the merchant has time, (2) the evidence exists in human-readable form, and (3) a human reviewer will evaluate it.\n\nAgent commerce breaks all three assumptions. Disputes can escalate in minutes, not weeks. Evidence exists as API logs, SLA metrics, and cryptographic hashes, not invoices and receipts. And the initial review may be automated -- Visa's Compelling Evidence 3.0 program, updated April 1, 2026, now includes evidence-sharing tooling designed for programmatic submission, including a new category for agentic transactions.\n\nYour dispute resolution system must collect, package, and submit evidence automatically, in the format that card networks and A2A dispute resolvers expect.\n\n### The Evidence Pipeline\n\nEvidence collection for agent disputes follows a four-stage pipeline.\n\n**Stage 1: Transaction History Extraction.** Pull the complete transaction record for the disputed transaction, including all related transactions in the same session or delegation chain.\n\n**Stage 2: SLA Compliance Snapshots.** If the dispute involves service quality, pull the full SLA compliance history for the evaluation period. Point-in-time snapshots are more compelling than summary statistics because they show the pattern of violations.\n\n**Stage 3: Reputation Attestations.** Pull the counterparty's reputation profile, including claim chains, verified metrics, and dispute history. A counterparty with a pattern of disputes is weaker in arbitration than one with a clean record.\n\n**Stage 4: Structured Evidence Packaging.** Combine all evidence into a structured package with cryptographic integrity verification. The package must be self-contained and verifiable by a third party.\n\n```python\nimport requests\nimport hashlib\nimport json\nimport time\nfrom typing import Dict, List, Any\n\n\nclass EvidenceCollector:\n    \"\"\"Automated evidence collection for agent dispute defense.\n\n    Collects transaction history, SLA compliance data, reputation\n    attestations, and packages them into structured evidence bundles\n    compatible with Visa CE 3.0 and A2A dispute resolution.\n    \"\"\"\n\n    def __init__(self, api_key: str, agent_id: str,\n                 base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"):\n        self.agent_id = agent_id\n        self.base_url = base_url\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        resp = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        resp.raise_for_status()\n        return resp.json()\n\n    def collect_transaction_evidence(self, counterparty_id: str) -> dict:\n        \"\"\"Stage 1: Extract transaction history with counterparty.\"\"\"\n        history = self._execute(\"get_transaction_history\", {\n            \"agent_id\": self.agent_id,\n        })\n\n        relevant = [\n            t for t in history.get(\"transactions\", [])\n            if t.get(\"counterparty\") == counterparty_id\n        ]\n\n        return {\n            \"stage\": \"transaction_history\",\n            \"total_transactions\": len(relevant),\n            \"transactions\": relevant,\n            \"collected_at\": time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime()),\n        }\n\n    def collect_sla_evidence(self, sla_id: str) -> dict:\n        \"\"\"Stage 2: Collect SLA compliance snapshots.\"\"\"\n        compliance = self._execute(\"check_sla_compliance\", {\n            \"agent_id\": self.agent_id,\n            \"sla_id\": sla_id,\n        })\n        status = self._execute(\"get_sla_status\", {\n            \"agent_id\": self.agent_id,\n            \"sla_id\": sla_id,\n        })\n\n        return {\n            \"stage\": \"sla_compliance\",\n            \"sla_id\": sla_id,\n            \"compliant\": compliance.get(\"compliant\"),\n            \"violations\": compliance.get(\"violations\", []),\n            \"full_status\": status,\n            \"collected_at\": time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime()),\n        }\n\n    def collect_reputation_evidence(self, counterparty_id: str) -> dict:\n        \"\"\"Stage 3: Collect counterparty reputation attestations.\"\"\"\n        reputation = self._execute(\"get_agent_reputation\", {\n            \"agent_id\": counterparty_id,\n        })\n        identity = self._execute(\"verify_identity\", {\n            \"agent_id\": counterparty_id,\n        })\n\n        return {\n            \"stage\": \"reputation_attestation\",\n            \"counterparty_id\": counterparty_id,\n            \"reputation_score\": reputation.get(\"reputation_score\"),\n            \"dispute_history\": reputation.get(\"dispute_history\", {}),\n            \"identity_verified\": identity.get(\"verified\", False),\n            \"registration_date\": identity.get(\"registered_at\"),\n            \"collected_at\": time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime()),\n        }\n\n    def collect_escrow_evidence(self, escrow_id: str) -> dict:\n        \"\"\"Collect escrow state and performance data.\"\"\"\n        escrow = self._execute(\"check_performance_escrow\", {\n            \"escrow_id\": escrow_id,\n        })\n        return {\n            \"stage\": \"escrow_state\",\n            \"escrow_id\": escrow_id,\n            \"escrow_data\": escrow,\n            \"collected_at\": time.strftime(\"%Y-%m-%dT%H:%M:%SZ\", time.gmtime()),\n        }\n\n    def package_evidence(self, escrow_id: str, sla_id: str,\n                         counterparty_id: str,\n                         intent_hash: str = None) -> dict:\n        \"\"\"Stage 4: Package all evidence into a structured bundle.\n\n        The bundle includes a SHA-256 integrity hash over all evidence\n        so that any tampering is detectable.\n        \"\"\"\n        evidence_stages = [\n            self.collect_transaction_evidence(counterparty_id),\n            self.collect_sla_evidence(sla_id),\n            self.collect_reputation_evidence(counterparty_id),\n            self.collect_escrow_evidence(escrow_id),\n        ]\n\n        bundle = {\n            \"dispute_evidence_bundle\": {\n                \"version\": \"1.0\",\n                \"format\": \"greenhelix_ce3_compatible\",\n                \"agent_id\": self.agent_id,\n                \"counterparty_id\": counterparty_id,\n                \"escrow_id\": escrow_id,\n                \"sla_id\": sla_id,\n                \"intent_hash\": intent_hash,\n                \"stages\": evidence_stages,\n                \"packaged_at\": time.strftime(\n                    \"%Y-%m-%dT%H:%M:%SZ\", time.gmtime()\n                ),\n            }\n        }\n\n        # Compute integrity hash over the entire bundle\n        bundle_bytes = json.dumps(\n            bundle, sort_keys=True, default=str\n        ).encode(\"utf-8\")\n        bundle[\"dispute_evidence_bundle\"][\"integrity_hash\"] = hashlib.sha256(\n            bundle_bytes\n        ).hexdigest()\n\n        return bundle\n```\n\n### Submitting Evidence to a Dispute\n\nOnce the evidence bundle is assembled, it is attached to the dispute response. The evidence is submitted programmatically as part of the `respond_dispute` tool call.\n\n```python\nimport requests\nimport json\n\nsession = requests.Session()\nsession.headers[\"Authorization\"] = f\"Bearer {api_key}\"\nbase_url = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n# Assume evidence_bundle was created by EvidenceCollector.package_evidence()\nevidence_bundle = collector.package_evidence(\n    escrow_id=\"escrow-abc-123\",\n    sla_id=\"sla-compute-2026-04\",\n    counterparty_id=\"vendor-agent-001\",\n    intent_hash=\"a1b2c3d4e5f6...\",\n)\n\n# Submit evidence as part of dispute response\nresp = session.post(f\"{base_url}\u002Fv1\", json={\n    \"tool\": \"respond_dispute\",\n    \"input\": {\n        \"dispute_id\": \"dispute-xyz-789\",\n        \"agent_id\": \"buyer-agent-001\",\n        \"response\": \"reject\",\n        \"evidence\": evidence_bundle[\"dispute_evidence_bundle\"],\n        \"narrative\": (\n            \"SLA compliance data shows 3 consecutive violations of the \"\n            \"uptime threshold (99.5% required, 94.2% actual over 72 hours). \"\n            \"Performance escrow release conditions were never met. \"\n            \"Intent chain proves transaction was within mandate scope. \"\n            \"Requesting full refund via escrow cancellation.\"\n        ),\n    }\n})\nresponse = resp.json()\nprint(f\"Dispute response submitted: {response}\")\n```\n\n---\n\n## Chapter 6: Multi-Party Dispute Resolution Workflows: Filing, Responding, Escalating, and Arbitrating\n\n### The Dispute Lifecycle\n\nGreenHelix disputes follow a four-stage lifecycle: Open, Response, Resolution, and Closed. Each stage has timeouts. If a party does not act within the timeout, the system advances automatically -- typically in favor of the party that did act.\n\n```\nOPEN ──(72h)──> RESPONSE ──(72h)──> RESOLUTION ──(24h)──> CLOSED\n  │                │                     │                    │\n  │                │                     │                    │\n  └─ Initiator     └─ Respondent         └─ Arbitrator\u002F       └─ Final\n     files claim      provides evidence     Auto-resolve         state\n```\n\n### Stage 1: Filing a Dispute\n\nThe initiator opens a dispute by identifying the escrow, the failure mode (from the Chapter 2 taxonomy), and initial evidence. The evidence does not need to be comprehensive at filing -- it needs to be sufficient to establish the claim.\n\n```python\nimport requests\n\nsession = requests.Session()\nsession.headers[\"Authorization\"] = f\"Bearer {api_key}\"\nbase_url = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n# File a dispute for SLA breach\nresp = session.post(f\"{base_url}\u002Fv1\", json={\n    \"tool\": \"open_dispute\",\n    \"input\": {\n        \"agent_id\": \"buyer-agent-001\",\n        \"escrow_id\": \"escrow-abc-123\",\n        \"reason\": \"sla_breach\",\n        \"failure_mode\": \"sla_breach\",  # From the 7-mode taxonomy\n        \"evidence\": {\n            \"sla_id\": \"sla-compute-2026-04\",\n            \"violations_summary\": \"3 consecutive failures: uptime below 99.5%\",\n            \"requested_resolution\": \"full_refund\",\n        },\n        \"deadline_hours\": 72,\n    }\n})\ndispute = resp.json()\ndispute_id = dispute.get(\"dispute_id\")\nprint(f\"Dispute filed: {dispute_id}\")\nprint(f\"Respondent has 72 hours to respond\")\n```\n\n### Stage 2: Responding to a Dispute\n\nThe respondent must provide counter-evidence within the response window. The `EvidenceCollector` from Chapter 5 automates this. A strong response includes transaction evidence, SLA data, and reputation attestation.\n\n```python\nimport requests\n\nsession = requests.Session()\nsession.headers[\"Authorization\"] = f\"Bearer {api_key}\"\nbase_url = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n# As the vendor, respond to the dispute with evidence\nresp = session.post(f\"{base_url}\u002Fv1\", json={\n    \"tool\": \"respond_dispute\",\n    \"input\": {\n        \"dispute_id\": \"dispute-xyz-789\",\n        \"agent_id\": \"vendor-agent-001\",\n        \"response\": \"contest\",\n        \"evidence\": {\n            \"sla_compliance_report\": {\n                \"overall_uptime\": 99.7,\n                \"note\": \"Brief dip during scheduled maintenance window, \"\n                        \"communicated 48h in advance per SLA section 4.2\",\n            },\n            \"maintenance_notification\": {\n                \"sent_at\": \"2026-04-04T08:00:00Z\",\n                \"channel\": \"messaging\",\n                \"message_id\": \"msg-maint-001\",\n            },\n            \"monitor_logs\": {\n                \"sla_id\": \"sla-compute-2026-04\",\n                \"measurement_source\": \"greenhelix_sla_monitor\",\n            },\n        },\n        \"narrative\": (\n            \"Uptime dip occurred during a pre-announced maintenance window. \"\n            \"SLA section 4.2 excludes scheduled maintenance from uptime \"\n            \"calculations. Excluding the 4-hour window, uptime was 99.82%.\"\n        ),\n    }\n})\nresponse = resp.json()\nprint(f\"Dispute response filed: {response}\")\n```\n\n### Stage 3: Resolution\n\nResolution can happen in three ways: mutual agreement, timeout-based automatic resolution, or third-party arbitration. The `resolve_dispute` tool handles all three.\n\n```python\nimport requests\n\nsession = requests.Session()\nsession.headers[\"Authorization\"] = f\"Bearer {api_key}\"\nbase_url = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n# Resolution option 1: Mutual agreement (either party can propose)\nresp = session.post(f\"{base_url}\u002Fv1\", json={\n    \"tool\": \"resolve_dispute\",\n    \"input\": {\n        \"dispute_id\": \"dispute-xyz-789\",\n        \"resolution\": \"partial_refund\",\n        \"details\": {\n            \"refund_amount_cents\": 5000,\n            \"refund_reason\": \"Partial SLA credit for maintenance-window impact\",\n            \"escrow_action\": \"partial_release\",\n            \"release_to_vendor_cents\": 5000,\n            \"return_to_buyer_cents\": 5000,\n        },\n    }\n})\nresolution = resp.json()\nprint(f\"Resolution proposed: {resolution}\")\n```\n\n### Automated Dispute Handler\n\nThe following class orchestrates the entire dispute lifecycle autonomously. It monitors for incoming disputes, collects evidence, submits responses, and handles resolution -- all without human intervention.\n\n```python\nimport requests\nimport time\nimport json\nfrom typing import Dict, Optional, Callable, Any\n\n\nclass AutomatedDisputeHandler:\n    \"\"\"Fully autonomous dispute lifecycle management.\n\n    Monitors for new disputes, auto-collects evidence, submits\n    responses within deadlines, and handles resolution flows.\n    \"\"\"\n\n    def __init__(self, api_key: str, agent_id: str,\n                 evidence_collector,\n                 base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"):\n        self.agent_id = agent_id\n        self.base_url = base_url\n        self.evidence_collector = evidence_collector\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n        self.handled_disputes: Dict[str, str] = {}  # dispute_id -> status\n        self.escalation_callback: Optional[Callable] = None\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        resp = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        resp.raise_for_status()\n        return resp.json()\n\n    def set_escalation_callback(self, callback: Callable):\n        \"\"\"Register a callback for disputes that require human review.\"\"\"\n        self.escalation_callback = callback\n\n    def poll_disputes(self) -> list:\n        \"\"\"Check for new or updated disputes.\"\"\"\n        result = self._execute(\"list_disputes\", {\n            \"agent_id\": self.agent_id,\n        })\n        return result.get(\"disputes\", [])\n\n    def handle_incoming_dispute(self, dispute: dict) -> dict:\n        \"\"\"Process a single incoming dispute.\"\"\"\n        dispute_id = dispute.get(\"dispute_id\")\n        status = dispute.get(\"status\")\n        escrow_id = dispute.get(\"escrow_id\")\n\n        if dispute_id in self.handled_disputes:\n            if self.handled_disputes[dispute_id] == status:\n                return {\"action\": \"already_handled\"}\n\n        # Collect evidence automatically\n        evidence_bundle = self.evidence_collector.package_evidence(\n            escrow_id=escrow_id,\n            sla_id=dispute.get(\"sla_id\", \"\"),\n            counterparty_id=dispute.get(\"initiator_id\", \"\"),\n        )\n\n        # Determine response strategy based on evidence\n        sla_evidence = next(\n            (s for s in evidence_bundle[\"dispute_evidence_bundle\"][\"stages\"]\n             if s[\"stage\"] == \"sla_compliance\"),\n            {}\n        )\n        is_compliant = sla_evidence.get(\"compliant\", True)\n\n        if is_compliant:\n            # Evidence supports our position -- contest the dispute\n            response = self._execute(\"respond_dispute\", {\n                \"dispute_id\": dispute_id,\n                \"agent_id\": self.agent_id,\n                \"response\": \"contest\",\n                \"evidence\": evidence_bundle[\"dispute_evidence_bundle\"],\n                \"narrative\": \"SLA compliance verified. Contesting dispute.\",\n            })\n            self.handled_disputes[dispute_id] = \"contested\"\n            return {\"action\": \"contested\", \"response\": response}\n        else:\n            # Evidence does not support us -- escalate or concede\n            if self.escalation_callback:\n                self.escalation_callback(dispute, evidence_bundle)\n                self.handled_disputes[dispute_id] = \"escalated\"\n                return {\"action\": \"escalated_to_human\"}\n            else:\n                # No escalation path -- propose partial resolution\n                response = self._execute(\"respond_dispute\", {\n                    \"dispute_id\": dispute_id,\n                    \"agent_id\": self.agent_id,\n                    \"response\": \"accept_partial\",\n                    \"evidence\": evidence_bundle[\"dispute_evidence_bundle\"],\n                    \"narrative\": (\n                        \"SLA violations confirmed. Proposing partial \"\n                        \"credit proportional to violation severity.\"\n                    ),\n                })\n                self.handled_disputes[dispute_id] = \"partial_accepted\"\n                return {\"action\": \"partial_accepted\", \"response\": response}\n\n    def run_dispute_monitor(self, interval_seconds: int = 300,\n                            max_iterations: int = 0):\n        \"\"\"Continuously monitor and handle disputes.\n\n        Args:\n            interval_seconds: Polling interval.\n            max_iterations: Stop after N iterations (0 = run forever).\n        \"\"\"\n        iteration = 0\n        while max_iterations == 0 or iteration \u003C max_iterations:\n            disputes = self.poll_disputes()\n            open_disputes = [\n                d for d in disputes\n                if d.get(\"status\") in (\"open\", \"awaiting_response\")\n                and d.get(\"respondent_id\") == self.agent_id\n            ]\n\n            for dispute in open_disputes:\n                result = self.handle_incoming_dispute(dispute)\n                print(\n                    f\"Dispute {dispute.get('dispute_id')}: \"\n                    f\"{result.get('action')}\"\n                )\n\n            iteration += 1\n            if max_iterations == 0 or iteration \u003C max_iterations:\n                time.sleep(interval_seconds)\n```\n\n### Timeout Handlers\n\nDisputes that are not responded to within the deadline resolve automatically. As the initiator, this works in your favor. As the respondent, timeouts are catastrophic. The following pattern ensures your agent never misses a deadline.\n\n```python\nimport requests\nimport time\n\nsession = requests.Session()\nsession.headers[\"Authorization\"] = f\"Bearer {api_key}\"\nbase_url = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n\ndef check_response_deadlines(agent_id: str,\n                              warning_hours: int = 12) -> list:\n    \"\"\"Identify disputes approaching response deadlines.\"\"\"\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"list_disputes\",\n        \"input\": {\"agent_id\": agent_id}\n    })\n    disputes = resp.json().get(\"disputes\", [])\n\n    urgent = []\n    now = time.time()\n    for d in disputes:\n        if d.get(\"status\") == \"awaiting_response\" and d.get(\"respondent_id\") == agent_id:\n            deadline = d.get(\"response_deadline_epoch\", 0)\n            hours_remaining = (deadline - now) \u002F 3600\n            if 0 \u003C hours_remaining \u003C= warning_hours:\n                urgent.append({\n                    \"dispute_id\": d.get(\"dispute_id\"),\n                    \"hours_remaining\": round(hours_remaining, 1),\n                    \"escrow_id\": d.get(\"escrow_id\"),\n                    \"priority\": \"critical\" if hours_remaining \u003C= 4 else \"high\",\n                })\n\n    return sorted(urgent, key=lambda x: x[\"hours_remaining\"])\n```\n\n---\n\n## Chapter 7: Chargeback Defense for Agent-Initiated Transactions: Card Network Rules Meet A2A Commerce\n\n### The Fundamental Mismatch\n\nCard network dispute rules assume a cardholder initiated the transaction. The cardholder can file a chargeback by claiming fraud (they did not make the purchase) or by claiming the goods were not as described. The issuing bank evaluates the claim, the acquiring bank represents the merchant, and the card network arbitrates if the parties cannot agree.\n\nWhen an AI agent initiates a transaction funded by a card deposit, the cardholder is the human principal who funded the agent's wallet. The merchant is the counterparty agent (or more precisely, the human operator behind the counterparty agent). The cardholder might file a chargeback because their agent over-purchased (Failure Mode 1), because the agent bought something the cardholder did not want (Failure Mode 7: intent drift), or because the counterparty did not deliver (Failure Mode 4: SLA breach). The card network must evaluate this claim using rules designed for \"I ordered a shirt and it never arrived,\" not \"my autonomous procurement agent exceeded its compute budget by $8,000 because it hallucinated a scaling requirement.\"\n\n### Visa Compelling Evidence 3.0: Agentic Extensions\n\nVisa's CE 3.0 update, effective April 1, 2026, is the first card network evidence standard to explicitly address agentic transactions. The update introduces two relevant changes.\n\nFirst, it adds a new evidence category for \"delegated purchasing authority\" -- documentation proving that a human principal authorized an agent to make purchases on their behalf. This maps directly to the mandate and intent chain from Chapter 3.\n\nSecond, it introduces evidence-sharing tooling that allows merchants to submit evidence programmatically rather than through the traditional portal upload. This is critical for agent commerce because the evidence (API logs, SLA metrics, cryptographic hashes) is inherently digital and structured.\n\n### Mastercard Scheme-Carried Liability\n\nMastercard's approach is different. Rather than modifying the evidence framework, they are establishing scheme-carried liability for transactions that follow the Verifiable Intent specification. If both the buyer and seller use Verifiable Intent (the mandate -> intent -> transaction chain), and the transaction is properly recorded, Mastercard absorbs the chargeback liability rather than pushing it to either party. This creates a strong incentive for both sides to implement Verifiable Intent chains, because doing so eliminates chargeback risk entirely.\n\n### Building an Intent Store for Pre-Dispute Deflection\n\nThe most effective chargeback defense is preventing the chargeback from being filed. An intent store is a queryable database of all agent intents, mandates, and transaction linkages. When a cardholder contacts their bank to dispute a transaction, the merchant's system can pre-emptively submit the intent chain to the issuer before the chargeback is formalized. This is called pre-dispute deflection, and Visa's CE 3.0 now supports it for agentic transactions.\n\n```python\nimport requests\nimport hashlib\nimport json\nimport time\nfrom typing import Dict, List, Optional, Any\n\n\nclass IntentStore:\n    \"\"\"Queryable store of agent intents for chargeback deflection.\n\n    Maintains a local index of all mandates, intents, and transaction\n    linkages. Supports pre-dispute evidence retrieval for card network\n    submission within the CE 3.0 framework.\n    \"\"\"\n\n    def __init__(self, api_key: str, agent_id: str,\n                 base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"):\n        self.agent_id = agent_id\n        self.base_url = base_url\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n        self.mandates: Dict[str, dict] = {}  # mandate_hash -> mandate\n        self.intents: Dict[str, dict] = {}   # intent_hash -> intent\n        self.tx_to_intent: Dict[str, str] = {}  # transaction_id -> intent_hash\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        resp = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        resp.raise_for_status()\n        return resp.json()\n\n    @staticmethod\n    def _hash(data: dict) -> str:\n        return hashlib.sha256(\n            json.dumps(data, sort_keys=True).encode(\"utf-8\")\n        ).hexdigest()\n\n    def store_mandate(self, mandate: dict) -> str:\n        \"\"\"Store a mandate and return its hash.\"\"\"\n        h = self._hash(mandate)\n        self.mandates[h] = mandate\n        return h\n\n    def store_intent(self, intent: dict, transaction_id: str = None) -> str:\n        \"\"\"Store an intent and optionally link it to a transaction.\"\"\"\n        h = self._hash(intent)\n        self.intents[h] = intent\n        if transaction_id:\n            self.tx_to_intent[transaction_id] = h\n        return h\n\n    def lookup_by_transaction(self, transaction_id: str) -> Optional[dict]:\n        \"\"\"Retrieve the full intent chain for a transaction.\n\n        Returns the intent, its parent mandate, and the chain\n        verification data needed for CE 3.0 evidence submission.\n        \"\"\"\n        intent_hash = self.tx_to_intent.get(transaction_id)\n        if not intent_hash:\n            return None\n\n        intent = self.intents.get(intent_hash)\n        if not intent:\n            return None\n\n        mandate_hash = intent.get(\"mandate_hash\")\n        mandate = self.mandates.get(mandate_hash)\n\n        return {\n            \"transaction_id\": transaction_id,\n            \"intent_hash\": intent_hash,\n            \"intent\": intent,\n            \"mandate_hash\": mandate_hash,\n            \"mandate\": mandate,\n            \"chain_complete\": mandate is not None,\n        }\n\n    def generate_ce3_evidence(self, transaction_id: str) -> Optional[dict]:\n        \"\"\"Generate Visa CE 3.0 compatible evidence for a transaction.\n\n        This evidence package can be submitted to the issuer for\n        pre-dispute deflection or chargeback defense.\n        \"\"\"\n        chain = self.lookup_by_transaction(transaction_id)\n        if not chain:\n            return None\n\n        # Pull additional context from GreenHelix\n        history = self._execute(\"get_transaction_history\", {\n            \"agent_id\": self.agent_id,\n        })\n\n        # Find the specific transaction\n        tx_record = next(\n            (t for t in history.get(\"transactions\", [])\n             if t.get(\"transaction_id\") == transaction_id),\n            {}\n        )\n\n        evidence = {\n            \"ce3_version\": \"3.0\",\n            \"evidence_type\": \"delegated_purchasing_authority\",\n            \"transaction_id\": transaction_id,\n            \"transaction_record\": tx_record,\n            \"delegated_authority\": {\n                \"mandate_hash\": chain[\"mandate_hash\"],\n                \"mandate_principal\": chain[\"mandate\"].get(\"principal\"),\n                \"mandate_valid_from\": chain[\"mandate\"].get(\"valid_from\"),\n                \"mandate_valid_until\": chain[\"mandate\"].get(\"valid_until\"),\n                \"authorized_actions\": chain[\"mandate\"].get(\"authorized_actions\"),\n                \"budget_ceiling_cents\": chain[\"mandate\"].get(\n                    \"budget_ceiling_cents\"\n                ),\n            },\n            \"intent_chain\": {\n                \"intent_hash\": chain[\"intent_hash\"],\n                \"action\": chain[\"intent\"].get(\"action\"),\n                \"amount_cents\": chain[\"intent\"].get(\"amount_cents\"),\n                \"vendor\": chain[\"intent\"].get(\"vendor\"),\n                \"justification\": chain[\"intent\"].get(\"justification\"),\n                \"mandate_clause\": chain[\"intent\"].get(\"mandate_clause\"),\n                \"timestamp\": chain[\"intent\"].get(\"timestamp\"),\n            },\n            \"verification\": {\n                \"mandate_hash_algorithm\": \"sha256_json_sorted_keys\",\n                \"intent_hash_algorithm\": \"sha256_json_sorted_keys\",\n                \"chain_recorded_on\": \"greenhelix_claim_chain\",\n            },\n            \"generated_at\": time.strftime(\n                \"%Y-%m-%dT%H:%M:%SZ\", time.gmtime()\n            ),\n        }\n\n        # Compute evidence integrity hash\n        evidence_bytes = json.dumps(\n            evidence, sort_keys=True\n        ).encode(\"utf-8\")\n        evidence[\"evidence_integrity_hash\"] = hashlib.sha256(\n            evidence_bytes\n        ).hexdigest()\n\n        return evidence\n\n    def generate_mastercard_vi_package(self,\n                                        transaction_id: str) -> Optional[dict]:\n        \"\"\"Generate Mastercard Verifiable Intent package.\n\n        If the transaction has a complete intent chain, the package\n        qualifies for scheme-carried liability, eliminating chargeback\n        risk for both parties.\n        \"\"\"\n        chain = self.lookup_by_transaction(transaction_id)\n        if not chain or not chain[\"chain_complete\"]:\n            return None\n\n        return {\n            \"vi_version\": \"1.0\",\n            \"scheme\": \"mastercard\",\n            \"liability_type\": \"scheme_carried\",\n            \"transaction_id\": transaction_id,\n            \"mandate\": {\n                \"hash\": chain[\"mandate_hash\"],\n                \"principal\": chain[\"mandate\"].get(\"principal\"),\n                \"scope\": chain[\"mandate\"].get(\"authorized_actions\"),\n                \"budget_cents\": chain[\"mandate\"].get(\"budget_ceiling_cents\"),\n                \"validity\": {\n                    \"from\": chain[\"mandate\"].get(\"valid_from\"),\n                    \"until\": chain[\"mandate\"].get(\"valid_until\"),\n                },\n            },\n            \"intent\": {\n                \"hash\": chain[\"intent_hash\"],\n                \"action\": chain[\"intent\"].get(\"action\"),\n                \"amount_cents\": chain[\"intent\"].get(\"amount_cents\"),\n                \"vendor\": chain[\"intent\"].get(\"vendor\"),\n                \"clause_reference\": chain[\"intent\"].get(\"mandate_clause\"),\n            },\n            \"chain_integrity\": {\n                \"recorded_on\": \"greenhelix_claim_chain\",\n                \"agent_id\": self.agent_id,\n                \"verifiable\": True,\n            },\n            \"generated_at\": time.strftime(\n                \"%Y-%m-%dT%H:%M:%SZ\", time.gmtime()\n            ),\n        }\n```\n\n### Pre-Dispute Deflection Workflow\n\nThe deflection workflow intercepts potential chargebacks before they formalize. When a cardholder inquiry is detected (via the card network's early warning system), the intent store generates and submits the evidence automatically.\n\n```python\nimport requests\n\nsession = requests.Session()\nsession.headers[\"Authorization\"] = f\"Bearer {api_key}\"\nbase_url = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n# When an early warning alert arrives for a transaction\ntransaction_id = \"tx-2026-04-06-001\"\n\n# Look up the intent chain\nintent_store = IntentStore(api_key, \"buyer-agent-001\")\n# (Assume mandates and intents were stored during transaction execution)\n\nce3_evidence = intent_store.generate_ce3_evidence(transaction_id)\nif ce3_evidence:\n    print(\"CE 3.0 evidence generated for pre-dispute deflection:\")\n    print(f\"  Evidence type: {ce3_evidence['evidence_type']}\")\n    print(f\"  Mandate principal: {ce3_evidence['delegated_authority']['mandate_principal']}\")\n    print(f\"  Intent action: {ce3_evidence['intent_chain']['action']}\")\n    print(f\"  Amount: ${ce3_evidence['intent_chain']['amount_cents'] \u002F 100:.2f}\")\n    # Submit to card network early warning system via their API\n    # (Network-specific integration not shown)\n\nvi_package = intent_store.generate_mastercard_vi_package(transaction_id)\nif vi_package:\n    print(f\"\\nMastercard VI package: liability={vi_package['liability_type']}\")\n    # If VI package is complete, chargeback liability is scheme-carried\n```\n\n---\n\n## Chapter 8: Production Dispute Resolution System: End-to-End Implementation with Monitoring\n\n### Putting It All Together\n\nThe previous chapters covered individual components: intent chains, escrow pipelines, evidence collection, dispute workflows, and chargeback defense. This chapter combines them into a single production system with monitoring, automated escalation, and post-mortem forensics.\n\n### The DisputeResolutionSystem Class\n\n```python\nimport requests\nimport hashlib\nimport json\nimport time\nimport logging\nfrom typing import Dict, List, Optional, Callable, Any\nfrom datetime import datetime, timezone\n\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(\"dispute_resolution\")\n\n\nclass DisputeResolutionSystem:\n    \"\"\"Production dispute resolution system with monitoring and automation.\n\n    Integrates: VerifiableIntentChain, EvidenceCollector,\n    AutomatedDisputeHandler, IntentStore, and SLA monitoring\n    into a single operational system.\n    \"\"\"\n\n    def __init__(self, api_key: str, agent_id: str,\n                 base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"):\n        self.agent_id = agent_id\n        self.base_url = base_url\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n        # Internal state\n        self.active_escrows: Dict[str, dict] = {}\n        self.active_slas: Dict[str, dict] = {}\n        self.dispute_log: List[dict] = []\n        self.metrics: Dict[str, Any] = {\n            \"disputes_filed\": 0,\n            \"disputes_received\": 0,\n            \"disputes_won\": 0,\n            \"disputes_lost\": 0,\n            \"chargebacks_deflected\": 0,\n            \"total_amount_disputed_cents\": 0,\n            \"total_amount_recovered_cents\": 0,\n        }\n        # Callbacks\n        self.escalation_callback: Optional[Callable] = None\n        self.alert_callback: Optional[Callable] = None\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        resp = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        resp.raise_for_status()\n        return resp.json()\n\n    # ── Escrow Management ───────────────────────────────────────────\n\n    def create_protected_escrow(self, vendor_id: str, amount_cents: int,\n                                 sla_config: dict,\n                                 intent_hash: str) -> dict:\n        \"\"\"Create a dispute-ready escrow with SLA protection.\n\n        Links escrow to an SLA and records the intent hash for\n        chargeback defense.\n        \"\"\"\n        # Create SLA\n        sla = self._execute(\"create_sla\", {\n            \"agent_id\": self.agent_id,\n            \"provider_id\": vendor_id,\n            \"metrics\": sla_config.get(\"metrics\", {}),\n            \"evaluation_period\": sla_config.get(\"evaluation_period\"),\n        })\n        sla_id = sla.get(\"sla_id\")\n\n        # Create performance escrow\n        escrow = self._execute(\"create_performance_escrow\", {\n            \"payer_id\": self.agent_id,\n            \"payee_id\": vendor_id,\n            \"amount\": amount_cents,\n            \"sla_id\": sla_id,\n            \"release_conditions\": {\n                \"sla_compliant\": True,\n                \"minimum_evaluation_period_hours\":\n                    sla_config.get(\"min_eval_hours\", 168),\n            },\n            \"timeout_hours\": sla_config.get(\"timeout_hours\", 336),\n            \"timeout_action\": \"return_to_payer\",\n        })\n        escrow_id = escrow.get(\"escrow_id\")\n\n        # Track internally\n        self.active_escrows[escrow_id] = {\n            \"vendor_id\": vendor_id,\n            \"amount_cents\": amount_cents,\n            \"sla_id\": sla_id,\n            \"intent_hash\": intent_hash,\n            \"created_at\": datetime.now(timezone.utc).isoformat(),\n            \"status\": \"active\",\n        }\n        self.active_slas[sla_id] = {\n            \"escrow_id\": escrow_id,\n            \"vendor_id\": vendor_id,\n            \"consecutive_failures\": 0,\n        }\n\n        logger.info(\n            f\"Protected escrow created: {escrow_id} \"\n            f\"(SLA: {sla_id}, amount: {amount_cents})\"\n        )\n        return {\n            \"escrow_id\": escrow_id,\n            \"sla_id\": sla_id,\n            \"intent_hash\": intent_hash,\n        }\n\n    # ── SLA Monitoring ──────────────────────────────────────────────\n\n    def monitor_sla_compliance(self, sla_id: str,\n                                failure_threshold: int = 3) -> dict:\n        \"\"\"Check SLA compliance and trigger dispute if threshold breached.\"\"\"\n        sla_info = self.active_slas.get(sla_id, {})\n        escrow_id = sla_info.get(\"escrow_id\")\n\n        compliance = self._execute(\"check_sla_compliance\", {\n            \"agent_id\": self.agent_id,\n            \"sla_id\": sla_id,\n        })\n\n        if not compliance.get(\"compliant\", True):\n            sla_info[\"consecutive_failures\"] = (\n                sla_info.get(\"consecutive_failures\", 0) + 1\n            )\n            logger.warning(\n                f\"SLA {sla_id} non-compliant \"\n                f\"(failure {sla_info['consecutive_failures']}\"\n                f\"\u002F{failure_threshold})\"\n            )\n        else:\n            sla_info[\"consecutive_failures\"] = 0\n\n        if sla_info.get(\"consecutive_failures\", 0) >= failure_threshold:\n            return self._auto_file_dispute(\n                escrow_id, sla_id, compliance\n            )\n\n        return {\n            \"sla_id\": sla_id,\n            \"compliant\": compliance.get(\"compliant\"),\n            \"consecutive_failures\": sla_info.get(\"consecutive_failures\", 0),\n            \"action\": \"monitoring\",\n        }\n\n    def _auto_file_dispute(self, escrow_id: str, sla_id: str,\n                            compliance: dict) -> dict:\n        \"\"\"Automatically file a dispute when SLA threshold is breached.\"\"\"\n        escrow_info = self.active_escrows.get(escrow_id, {})\n\n        dispute = self._execute(\"open_dispute\", {\n            \"agent_id\": self.agent_id,\n            \"escrow_id\": escrow_id,\n            \"reason\": \"sla_breach\",\n            \"failure_mode\": \"sla_breach\",\n            \"evidence\": {\n                \"sla_id\": sla_id,\n                \"compliance_data\": compliance,\n                \"escrow_amount_cents\": escrow_info.get(\"amount_cents\"),\n            },\n        })\n\n        self.metrics[\"disputes_filed\"] += 1\n        self.metrics[\"total_amount_disputed_cents\"] += escrow_info.get(\n            \"amount_cents\", 0\n        )\n\n        self.dispute_log.append({\n            \"dispute_id\": dispute.get(\"dispute_id\"),\n            \"escrow_id\": escrow_id,\n            \"sla_id\": sla_id,\n            \"type\": \"auto_filed\",\n            \"timestamp\": datetime.now(timezone.utc).isoformat(),\n        })\n\n        logger.info(\n            f\"Auto-filed dispute {dispute.get('dispute_id')} \"\n            f\"for escrow {escrow_id}\"\n        )\n\n        if self.alert_callback:\n            self.alert_callback({\n                \"type\": \"dispute_auto_filed\",\n                \"dispute_id\": dispute.get(\"dispute_id\"),\n                \"escrow_id\": escrow_id,\n                \"amount_cents\": escrow_info.get(\"amount_cents\"),\n            })\n\n        return {\n            \"action\": \"dispute_filed\",\n            \"dispute_id\": dispute.get(\"dispute_id\"),\n        }\n\n    # ── Dispute Response ────────────────────────────────────────────\n\n    def handle_incoming_disputes(self) -> List[dict]:\n        \"\"\"Check for and respond to incoming disputes.\"\"\"\n        disputes = self._execute(\"list_disputes\", {\n            \"agent_id\": self.agent_id,\n        })\n\n        results = []\n        for d in disputes.get(\"disputes\", []):\n            if (d.get(\"status\") == \"awaiting_response\"\n                    and d.get(\"respondent_id\") == self.agent_id):\n                result = self._respond_to_dispute(d)\n                results.append(result)\n\n        return results\n\n    def _respond_to_dispute(self, dispute: dict) -> dict:\n        \"\"\"Generate and submit a response to an incoming dispute.\"\"\"\n        dispute_id = dispute.get(\"dispute_id\")\n        escrow_id = dispute.get(\"escrow_id\")\n        sla_id = dispute.get(\"sla_id\", \"\")\n\n        self.metrics[\"disputes_received\"] += 1\n\n        # Collect evidence\n        evidence_stages = []\n\n        # Transaction history\n        history = self._execute(\"get_transaction_history\", {\n            \"agent_id\": self.agent_id,\n        })\n        evidence_stages.append({\n            \"stage\": \"transaction_history\",\n            \"data\": history,\n        })\n\n        # SLA compliance (if applicable)\n        if sla_id:\n            compliance = self._execute(\"check_sla_compliance\", {\n                \"agent_id\": self.agent_id,\n                \"sla_id\": sla_id,\n            })\n            evidence_stages.append({\n                \"stage\": \"sla_compliance\",\n                \"data\": compliance,\n            })\n\n        # Counterparty reputation\n        initiator_id = dispute.get(\"initiator_id\", \"\")\n        if initiator_id:\n            rep = self._execute(\"get_agent_reputation\", {\n                \"agent_id\": initiator_id,\n            })\n            evidence_stages.append({\n                \"stage\": \"counterparty_reputation\",\n                \"data\": rep,\n            })\n\n        # Determine response\n        is_compliant = True\n        for stage in evidence_stages:\n            if stage[\"stage\"] == \"sla_compliance\":\n                is_compliant = stage[\"data\"].get(\"compliant\", True)\n\n        if is_compliant:\n            response_type = \"contest\"\n            narrative = (\n                \"SLA compliance verified across all metrics. \"\n                \"Evidence attached demonstrates full delivery.\"\n            )\n        else:\n            response_type = \"accept_partial\"\n            narrative = (\n                \"Partial SLA deviation acknowledged. Proposing \"\n                \"proportional credit based on violation severity.\"\n            )\n\n        response = self._execute(\"respond_dispute\", {\n            \"dispute_id\": dispute_id,\n            \"agent_id\": self.agent_id,\n            \"response\": response_type,\n            \"evidence\": {\n                \"stages\": evidence_stages,\n                \"collected_at\": datetime.now(timezone.utc).isoformat(),\n            },\n            \"narrative\": narrative,\n        })\n\n        self.dispute_log.append({\n            \"dispute_id\": dispute_id,\n            \"type\": \"response_submitted\",\n            \"response_type\": response_type,\n            \"timestamp\": datetime.now(timezone.utc).isoformat(),\n        })\n\n        logger.info(\n            f\"Responded to dispute {dispute_id}: {response_type}\"\n        )\n        return {\n            \"dispute_id\": dispute_id,\n            \"response_type\": response_type,\n            \"response\": response,\n        }\n\n    # ── Dashboard & Metrics ─────────────────────────────────────────\n\n    def get_dashboard(self) -> dict:\n        \"\"\"Generate a dispute resolution dashboard snapshot.\"\"\"\n        # Refresh dispute state\n        disputes = self._execute(\"list_disputes\", {\n            \"agent_id\": self.agent_id,\n        })\n\n        open_disputes = [\n            d for d in disputes.get(\"disputes\", [])\n            if d.get(\"status\") in (\"open\", \"awaiting_response\", \"under_review\")\n        ]\n        resolved_disputes = [\n            d for d in disputes.get(\"disputes\", [])\n            if d.get(\"status\") in (\"resolved\", \"closed\")\n        ]\n\n        # Calculate win rate\n        won = sum(\n            1 for d in resolved_disputes\n            if d.get(\"resolution_favor\") == self.agent_id\n        )\n        lost = sum(\n            1 for d in resolved_disputes\n            if d.get(\"resolution_favor\") and\n            d.get(\"resolution_favor\") != self.agent_id\n        )\n        total_resolved = won + lost\n        win_rate = (won \u002F total_resolved * 100) if total_resolved > 0 else 0\n\n        # SLA health\n        sla_health = {}\n        for sla_id, sla_info in self.active_slas.items():\n            status = self._execute(\"get_sla_status\", {\n                \"agent_id\": self.agent_id,\n                \"sla_id\": sla_id,\n            })\n            sla_health[sla_id] = {\n                \"compliant\": status.get(\"compliant\"),\n                \"consecutive_failures\": sla_info.get(\n                    \"consecutive_failures\", 0\n                ),\n                \"escrow_id\": sla_info.get(\"escrow_id\"),\n            }\n\n        # Balance check\n        balance = self._execute(\"get_balance\", {\n            \"agent_id\": self.agent_id,\n        })\n\n        return {\n            \"agent_id\": self.agent_id,\n            \"timestamp\": datetime.now(timezone.utc).isoformat(),\n            \"disputes\": {\n                \"open\": len(open_disputes),\n                \"resolved\": len(resolved_disputes),\n                \"win_rate_percent\": round(win_rate, 1),\n                \"total_filed\": self.metrics[\"disputes_filed\"],\n                \"total_received\": self.metrics[\"disputes_received\"],\n            },\n            \"financials\": {\n                \"balance_cents\": balance.get(\"balance\"),\n                \"amount_in_dispute_cents\":\n                    self.metrics[\"total_amount_disputed_cents\"],\n                \"amount_recovered_cents\":\n                    self.metrics[\"total_amount_recovered_cents\"],\n            },\n            \"escrows\": {\n                \"active\": sum(\n                    1 for e in self.active_escrows.values()\n                    if e[\"status\"] == \"active\"\n                ),\n                \"total_value_cents\": sum(\n                    e[\"amount_cents\"] for e in self.active_escrows.values()\n                    if e[\"status\"] == \"active\"\n                ),\n            },\n            \"sla_health\": sla_health,\n            \"recent_events\": self.dispute_log[-10:],\n        }\n\n    # ── Post-Mortem Forensics ───────────────────────────────────────\n\n    def generate_post_mortem(self, dispute_id: str) -> dict:\n        \"\"\"Generate a forensic post-mortem for a resolved dispute.\n\n        Analyzes the full dispute timeline, evidence submissions,\n        and outcome to identify systemic issues.\n        \"\"\"\n        dispute = self._execute(\"get_dispute\", {\n            \"dispute_id\": dispute_id,\n        })\n\n        escrow_id = dispute.get(\"escrow_id\")\n        escrow_info = self.active_escrows.get(escrow_id, {})\n\n        # Build timeline from dispute log\n        timeline = [\n            entry for entry in self.dispute_log\n            if entry.get(\"dispute_id\") == dispute_id\n        ]\n\n        # Identify the failure mode\n        failure_mode = dispute.get(\"failure_mode\", \"unknown\")\n\n        # Calculate financial impact\n        amount_cents = escrow_info.get(\"amount_cents\", 0)\n        resolution = dispute.get(\"resolution\", {})\n        recovered = resolution.get(\"return_to_buyer_cents\", 0)\n        lost = amount_cents - recovered\n\n        # Generate recommendations based on failure mode\n        recommendations = self._get_recommendations(failure_mode)\n\n        return {\n            \"post_mortem\": {\n                \"dispute_id\": dispute_id,\n                \"escrow_id\": escrow_id,\n                \"failure_mode\": failure_mode,\n                \"outcome\": dispute.get(\"status\"),\n                \"resolution_favor\": dispute.get(\"resolution_favor\"),\n                \"financial_impact\": {\n                    \"total_amount_cents\": amount_cents,\n                    \"recovered_cents\": recovered,\n                    \"lost_cents\": lost,\n                },\n                \"timeline\": timeline,\n                \"counterparty_id\": escrow_info.get(\"vendor_id\"),\n                \"recommendations\": recommendations,\n                \"generated_at\": datetime.now(timezone.utc).isoformat(),\n            }\n        }\n\n    @staticmethod\n    def _get_recommendations(failure_mode: str) -> list:\n        \"\"\"Return preventive recommendations based on failure mode.\"\"\"\n        recs = {\n            \"over_purchase\": [\n                \"Tighten mandate budget ceiling\",\n                \"Add per-transaction amount limit to mandate\",\n                \"Implement real-time spend tracking with alerts\",\n            ],\n            \"hallucinated_order\": [\n                \"Add intent validation against task context\",\n                \"Require human approval for purchases outside known categories\",\n                \"Implement purchase justification scoring\",\n            ],\n            \"unauthorized_merchant\": [\n                \"Enforce vendor allowlist at the escrow creation layer\",\n                \"Add vendor identity verification before escrow creation\",\n                \"Monitor for new vendor additions to the agent's patterns\",\n            ],\n            \"sla_breach\": [\n                \"Shorten SLA evaluation periods for faster detection\",\n                \"Lower the consecutive-failure threshold for disputes\",\n                \"Add SLA monitoring with real-time alerts\",\n            ],\n            \"escrow_timeout\": [\n                \"Set shorter escrow timeout periods\",\n                \"Add intermediate milestones with partial release\",\n                \"Implement timeout warning alerts at 50% and 75% of window\",\n            ],\n            \"cascading_delegation\": [\n                \"Enforce budget propagation limits in delegation chains\",\n                \"Cap delegation depth in mandate\",\n                \"Require per-level budget reporting\",\n            ],\n            \"intent_drift\": [\n                \"Implement purchase category tracking over time\",\n                \"Add mandate scope alerts for out-of-category purchases\",\n                \"Schedule periodic mandate re-authorization\",\n            ],\n        }\n        return recs.get(failure_mode, [\n            \"Review dispute details and update prevention controls\",\n            \"Consider adding this failure mode to monitoring\",\n        ])\n\n    # ── Main Loop ───────────────────────────────────────────────────\n\n    def run(self, poll_interval_seconds: int = 300,\n            sla_check_interval_seconds: int = 3600,\n            max_iterations: int = 0):\n        \"\"\"Run the dispute resolution system.\n\n        Continuously monitors SLAs, handles incoming disputes,\n        and manages escrow release gates.\n        \"\"\"\n        iteration = 0\n        last_sla_check = 0\n\n        logger.info(\n            f\"Dispute resolution system started for {self.agent_id}\"\n        )\n\n        while max_iterations == 0 or iteration \u003C max_iterations:\n            now = time.time()\n\n            # Check SLA compliance periodically\n            if now - last_sla_check >= sla_check_interval_seconds:\n                for sla_id in list(self.active_slas.keys()):\n                    try:\n                        self.monitor_sla_compliance(sla_id)\n                    except Exception as e:\n                        logger.error(f\"SLA check failed for {sla_id}: {e}\")\n                last_sla_check = now\n\n            # Handle incoming disputes\n            try:\n                results = self.handle_incoming_disputes()\n                for r in results:\n                    logger.info(\n                        f\"Handled dispute: {r.get('dispute_id')} \"\n                        f\"-> {r.get('response_type')}\"\n                    )\n            except Exception as e:\n                logger.error(f\"Dispute handling failed: {e}\")\n\n            iteration += 1\n            if max_iterations == 0 or iteration \u003C max_iterations:\n                time.sleep(poll_interval_seconds)\n\n        logger.info(\"Dispute resolution system stopped\")\n```\n\n### Initialization and Usage\n\n```python\nimport requests\n\napi_key = \"your-api-key\"\nagent_id = \"buyer-agent-001\"\n\n# Initialize the system\ndrs = DisputeResolutionSystem(api_key, agent_id)\n\n# Set up alert callback (e.g., send to Slack)\ndef alert_handler(alert):\n    print(f\"ALERT: {alert['type']} - Dispute {alert.get('dispute_id')}\")\n    # In production: send to Slack, PagerDuty, email, etc.\n\ndrs.alert_callback = alert_handler\n\n# Set up escalation callback for disputes requiring human review\ndef escalation_handler(dispute, evidence):\n    print(f\"ESCALATION: Dispute {dispute.get('dispute_id')} requires human review\")\n    # In production: create ticket, page on-call engineer, etc.\n\ndrs.escalation_callback = escalation_handler\n\n# Create a protected escrow for a new transaction\nresult = drs.create_protected_escrow(\n    vendor_id=\"vendor-agent-001\",\n    amount_cents=10000,\n    sla_config={\n        \"metrics\": {\n            \"uptime_percent\": {\"threshold\": 99.5, \"comparison\": \"gte\"},\n            \"response_time_ms\": {\"threshold\": 200, \"comparison\": \"lte\"},\n        },\n        \"evaluation_period\": \"2026-04-06T00:00:00Z\u002F2026-04-13T00:00:00Z\",\n        \"min_eval_hours\": 168,\n        \"timeout_hours\": 336,\n    },\n    intent_hash=\"a1b2c3d4e5f6...\",\n)\nprint(f\"Escrow: {result['escrow_id']}, SLA: {result['sla_id']}\")\n\n# Get dashboard\ndashboard = drs.get_dashboard()\nprint(json.dumps(dashboard, indent=2))\n\n# Run the system (in production, this runs indefinitely)\n# drs.run(poll_interval_seconds=300, sla_check_interval_seconds=3600)\n```\n\n### Monitoring Integration\n\nThe dashboard output integrates with standard monitoring stacks. The following snippet shows how to export metrics to a Prometheus-compatible format.\n\n```python\nimport time\n\n\ndef export_prometheus_metrics(drs: DisputeResolutionSystem) -> str:\n    \"\"\"Export dispute resolution metrics in Prometheus exposition format.\"\"\"\n    dashboard = drs.get_dashboard()\n    d = dashboard[\"disputes\"]\n    f = dashboard[\"financials\"]\n    e = dashboard[\"escrows\"]\n\n    lines = [\n        \"# HELP disputes_open Number of open disputes\",\n        \"# TYPE disputes_open gauge\",\n        f'disputes_open{{agent_id=\"{drs.agent_id}\"}} {d[\"open\"]}',\n        \"\",\n        \"# HELP disputes_resolved_total Total resolved disputes\",\n        \"# TYPE disputes_resolved_total counter\",\n        f'disputes_resolved_total{{agent_id=\"{drs.agent_id}\"}} {d[\"resolved\"]}',\n        \"\",\n        \"# HELP dispute_win_rate Win rate percentage\",\n        \"# TYPE dispute_win_rate gauge\",\n        f'dispute_win_rate{{agent_id=\"{drs.agent_id}\"}} {d[\"win_rate_percent\"]}',\n        \"\",\n        \"# HELP amount_in_dispute_cents Total cents currently in dispute\",\n        \"# TYPE amount_in_dispute_cents gauge\",\n        f'amount_in_dispute_cents{{agent_id=\"{drs.agent_id}\"}} '\n        f'{f[\"amount_in_dispute_cents\"]}',\n        \"\",\n        \"# HELP escrows_active Number of active escrows\",\n        \"# TYPE escrows_active gauge\",\n        f'escrows_active{{agent_id=\"{drs.agent_id}\"}} {e[\"active\"]}',\n        \"\",\n        \"# HELP escrows_total_value_cents Total value in active escrows\",\n        \"# TYPE escrows_total_value_cents gauge\",\n        f'escrows_total_value_cents{{agent_id=\"{drs.agent_id}\"}} '\n        f'{e[\"total_value_cents\"]}',\n    ]\n    return \"\\n\".join(lines)\n```\n\n### Post-Mortem Forensics\n\nAfter every resolved dispute, generate a post-mortem. Over time, the post-mortem archive reveals systemic patterns -- which vendors are problematic, which failure modes are most common, and which prevention controls are working.\n\n```python\nimport requests\n\nsession = requests.Session()\nsession.headers[\"Authorization\"] = f\"Bearer {api_key}\"\nbase_url = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n# After a dispute resolves, generate the post-mortem\npost_mortem = drs.generate_post_mortem(\"dispute-xyz-789\")\n\nprint(f\"Failure mode: {post_mortem['post_mortem']['failure_mode']}\")\nprint(f\"Outcome: {post_mortem['post_mortem']['outcome']}\")\nprint(f\"Financial impact:\")\nimpact = post_mortem[\"post_mortem\"][\"financial_impact\"]\nprint(f\"  Total: ${impact['total_amount_cents']\u002F100:.2f}\")\nprint(f\"  Recovered: ${impact['recovered_cents']\u002F100:.2f}\")\nprint(f\"  Lost: ${impact['lost_cents']\u002F100:.2f}\")\nprint(f\"Recommendations:\")\nfor rec in post_mortem[\"post_mortem\"][\"recommendations\"]:\n    print(f\"  - {rec}\")\n```\n\n---\n\n## What You Get\n\nThis guide gives you a complete, production-ready dispute resolution system for agent-to-agent commerce. Here is what each chapter delivers:\n\n**Chapter 1 -- Legal Context.** The Amazon v. Perplexity ruling, Clifford Chance analysis, and the three-front war framework. You understand why human-era dispute rules fail for agents and where the liability gaps are.\n\n**Chapter 2 -- Failure Mode Taxonomy.** The 7 agentic failure modes (over-purchase, hallucinated order, unauthorized merchant, SLA breach, escrow timeout, cascading delegation, intent drift) with detection signals, evidence requirements, and applicable GreenHelix tools. Use this as a reference table for every dispute you handle.\n\n**Chapter 3 -- Verifiable Intent Chains.** The `VerifiableIntentChain` class implementing Mastercard's Verifiable Intent pattern with mandate hashing, intent recording, transaction linking, and selective disclosure. Cryptographic proof that your agent was authorized to do exactly what it did.\n\n**Chapter 4 -- Escrow-First Architecture.** Performance escrow with SLA criteria, automatic release gates, dispute-triggering conditions based on consecutive SLA failures, and refund flows. Every transaction goes through escrow, and every escrow is dispute-ready.\n\n**Chapter 5 -- Evidence Collection.** The `EvidenceCollector` class with a four-stage pipeline: transaction history extraction, SLA compliance snapshots, reputation attestations, and structured evidence packaging with integrity hashing. Compatible with Visa CE 3.0 evidence submission.\n\n**Chapter 6 -- Dispute Workflows.** The `AutomatedDisputeHandler` class managing the full Open -> Response -> Resolution -> Closed lifecycle with automated evidence injection, timeout monitoring, and escalation callbacks.\n\n**Chapter 7 -- Chargeback Defense.** The `IntentStore` class generating Visa CE 3.0 evidence packages and Mastercard Verifiable Intent packages for pre-dispute deflection and scheme-carried liability qualification. Prevents chargebacks before they formalize.\n\n**Chapter 8 -- Production System.** The `DisputeResolutionSystem` class combining all components into a single operational system with SLA monitoring, automated dispute filing and response, a real-time dashboard, Prometheus-compatible metrics export, and post-mortem forensics with failure-mode-specific recommendations.\n\n**Tools used:** `open_dispute`, `respond_dispute`, `resolve_dispute`, `list_disputes`, `get_dispute`, `create_escrow`, `release_escrow`, `cancel_escrow`, `create_performance_escrow`, `check_performance_escrow`, `list_escrows`, `create_sla`, `check_sla_compliance`, `get_sla_status`, `monitor_sla`, `build_claim_chain`, `get_agent_reputation`, `verify_identity`, `get_balance`, `get_transaction_history`, `create_intent`, `register_agent`, `search_agents_by_metrics`.\n\nAll code is Python with the `requests` library. All API calls use the REST API (`POST \u002Fv1\u002F{tool}`) with `{\"tool\": \"tool_name\", \"input\": {...}}`. All patterns are designed for autonomous operation without human intervention.\n\n---\n\n*Price: $29 | Format: Digital Guide | Updates: Lifetime access*\n\n",{"name":5,"tags":24,"type":30,"author":34,"install":35,"license":15,"version":36,"price_usd":37,"executable":20,"credentials":35,"description":7,"content_type":38,"compatibility":39},[25,26,27,28,29,30,31,32,33],"disputes","chargebacks","escrow","verifiable-intent","liability","guide","greenhelix","openclaw","ai-agent","felix-agent","none","1.3.1",0,"markdown",[32],"master","4aa004da461d820f4ea5499e58eb8d196cf99016","community\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-dispute-resolution","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":49,"prompt":59,"zipAvailable":60},[50,53,56],{"tool":51,"command":52},"npx","npx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-dispute-resolution",{"tool":54,"command":55},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-dispute-resolution",{"tool":57,"command":58},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-dispute-resolution","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-dispute-resolution\u002FSKILL.md",true,[],[63,70,77,84,91,98],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"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":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"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":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"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":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"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":92,"name":93,"nameZh":6,"description":94,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":95,"categories":96,"keywords":97,"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":99,"name":100,"nameZh":6,"description":101,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":102,"categories":103,"keywords":104,"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",[],[]]