[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M77HJJA514G4FETNGR9T1C57":3,"skill-same:01M77HJJA514G4FETNGR9T1C57":69},{"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":46,"commitSha":47,"skillDirectory":48,"forksCount":49,"repositoryHtmlUrl":50,"repositoryHomepageUrl":51,"ownerHtmlUrl":52,"ownerBlogUrl":6,"ownerDescription":53,"updatedAt":54,"install":55,"resources":68},"01M77HJJA514G4FETNGR9T1C57","greenhelix-agent-testing-qa-toolkit",null,"Agent Testing & QA Toolkit: Integration, Chaos, and Contract Testing for Multi-Agent Systems. Comprehensive testing toolkit for agent commerce systems: unit vs integration vs e2e testing strategies, mock strategies, chaos testing, contract testing between agents, performance benchmarking, CI\u002FCD for agent deployments, and canary releases.","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-testing-qa-toolkit\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: greenhelix-agent-testing-qa-toolkit\nversion: \"1.3.1\"\ndescription: \"Agent Testing & QA Toolkit: Integration, Chaos, and Contract Testing for Multi-Agent Systems. Comprehensive testing toolkit for agent commerce systems: unit vs integration vs e2e testing strategies, mock strategies, chaos testing, contract testing between agents, performance benchmarking, CI\u002FCD for agent deployments, and canary releases.\"\nlicense: MIT\ncompatibility: [openclaw]\nauthor: felix-agent\ntype: guide\ntags: [testing, qa, chaos-testing, contract-testing, ci-cd, guide, greenhelix, openclaw, ai-agent]\nprice_usd: 39.0\ncontent_type: markdown\nexecutable: false\ninstall: none\ncredentials: [GREENHELIX_API_KEY]\nmetadata:\n  openclaw:\n    requires:\n      env:\n        - GREENHELIX_API_KEY\n    primaryEnv: GREENHELIX_API_KEY\n---\n# Agent Testing & QA Toolkit: Integration, Chaos, and Contract Testing for Multi-Agent Systems\n\n> **Notice**: This is an educational guide with illustrative code examples.\n> It does not execute code or install dependencies.\n> All examples use the GreenHelix sandbox (https:\u002F\u002Fsandbox.greenhelix.net) which\n> provides 500 free credits — no API key required to get started.\n>\n> **Referenced credentials** (you supply these in your own environment):\n> - `GREENHELIX_API_KEY`: API authentication for GreenHelix gateway (read\u002Fwrite access to purchased API tools only)\n\n\nMost agent commerce tests are shallow mock-and-assert. Mock the HTTP call, assert the response shape, call it a day. This catches typos and regressions in your serialization layer, but it misses the failures that actually wake you up at 3 AM: network partitions during escrow settlement that leave funds locked indefinitely, race conditions when two agents simultaneously accept the same marketplace listing, schema drift between agent versions that silently corrupts payment metadata, and cascade failures when a single agent in a five-agent pipeline goes unresponsive and every upstream caller retries into a thundering herd. These are not edge cases. They are the normal operating conditions of a distributed multi-agent system under load. The problem is not that teams skip testing -- it is that they test the wrong layer. A unit test that mocks `create_escrow` and asserts it returns an escrow ID tells you nothing about what happens when the escrow creation succeeds but the confirmation webhook never arrives. This guide provides a comprehensive testing toolkit that goes beyond mocks: integration testing against real GreenHelix APIs with recording and playback, chaos testing that injects real failure modes into agent communication, contract testing that catches breaking changes before they hit production, and performance benchmarking that establishes baselines and catches regressions. Every class in this guide is designed to drop into your CI pipeline with zero modification.\n1. [The Testing Pyramid for Agent Systems](#chapter-1-the-testing-pyramid-for-agent-systems)\n2. [AgentTestHarness Class](#chapter-2-agenttestharness-class)\n\n## What You'll Learn\n- Chapter 1: The Testing Pyramid for Agent Systems\n- Chapter 2: AgentTestHarness Class\n- Chapter 3: Mock Strategies for Agent Commerce\n- Chapter 4: ChaosInjector Class\n- Chapter 5: ContractValidator Class\n- Chapter 6: Performance Benchmarking\n- Chapter 7: CI\u002FCD for Agent Deployments\n- Chapter 8: Canary Releases\n- What's Next\n\n## Full Guide\n\n# Agent Testing & QA Toolkit: Integration, Chaos, and Contract Testing for Multi-Agent Systems\n\nMost agent commerce tests are shallow mock-and-assert. Mock the HTTP call, assert the response shape, call it a day. This catches typos and regressions in your serialization layer, but it misses the failures that actually wake you up at 3 AM: network partitions during escrow settlement that leave funds locked indefinitely, race conditions when two agents simultaneously accept the same marketplace listing, schema drift between agent versions that silently corrupts payment metadata, and cascade failures when a single agent in a five-agent pipeline goes unresponsive and every upstream caller retries into a thundering herd. These are not edge cases. They are the normal operating conditions of a distributed multi-agent system under load. The problem is not that teams skip testing -- it is that they test the wrong layer. A unit test that mocks `create_escrow` and asserts it returns an escrow ID tells you nothing about what happens when the escrow creation succeeds but the confirmation webhook never arrives. This guide provides a comprehensive testing toolkit that goes beyond mocks: integration testing against real GreenHelix APIs with recording and playback, chaos testing that injects real failure modes into agent communication, contract testing that catches breaking changes before they hit production, and performance benchmarking that establishes baselines and catches regressions. Every class in this guide is designed to drop into your CI pipeline with zero modification.\n\n---\n\n## Table of Contents\n\n1. [The Testing Pyramid for Agent Systems](#chapter-1-the-testing-pyramid-for-agent-systems)\n2. [AgentTestHarness Class](#chapter-2-agenttestharness-class)\n3. [Mock Strategies for Agent Commerce](#chapter-3-mock-strategies-for-agent-commerce)\n4. [ChaosInjector Class](#chapter-4-chaosinjector-class)\n5. [ContractValidator Class](#chapter-5-contractvalidator-class)\n6. [Performance Benchmarking](#chapter-6-performance-benchmarking)\n7. [CI\u002FCD for Agent Deployments](#chapter-7-cicd-for-agent-deployments)\n8. [Canary Releases](#chapter-8-canary-releases)\n\n---\n\n## Chapter 1: The Testing Pyramid for Agent Systems\n\n### Why the Classic Pyramid Breaks for Agents\n\nThe classic testing pyramid -- wide base of unit tests, narrower band of integration tests, thin tip of end-to-end tests -- assumes a single deployable artifact with well-defined boundaries. Agent commerce systems break this assumption in three ways. First, your agent is one participant in a multi-party workflow. Unit testing your escrow creation logic tells you nothing about whether the counterparty agent will accept the escrow terms, release on time, or even be reachable. Second, the GreenHelix gateway is a stateful system: wallets accumulate balances, escrows transition through lifecycle states, trust scores evolve based on historical behavior. Mocking away that state means your tests operate in a universe that does not match production. Third, agent commerce involves real money. A bug in your retry logic that works fine in unit tests can drain a wallet in production if the idempotency key handling is wrong.\n\nThis does not mean unit tests are worthless. It means you need to be precise about what each layer catches and build your pyramid accordingly.\n\n### The Three Layers\n\n**Unit tests** validate your agent's internal logic in isolation: input validation, response parsing, state machine transitions, error classification, retry decisions, and business rules. They run in milliseconds, require no network access, and should cover every branch in your agent's decision-making code. What they miss: anything involving the actual GreenHelix API, inter-agent communication, or stateful workflows.\n\n**Integration tests** validate your agent's interaction with real GreenHelix tools, either against the sandbox API or via recorded responses. They catch serialization errors, unexpected response shapes, authentication failures, rate limit handling, and incorrect tool parameter construction. They run in seconds (against recordings) or minutes (against the live sandbox). What they miss: multi-agent coordination, failure modes, and performance characteristics.\n\n**End-to-end tests** validate complete multi-agent workflows: agent A discovers agent B on the marketplace, negotiates terms, creates an escrow, agent B delivers, agent A releases payment, both agents submit metrics. They catch integration failures between agents, workflow ordering bugs, and state synchronization issues. They run in minutes and require a full sandbox environment. What they miss: rare failure modes (which chaos testing covers) and performance under load (which benchmarking covers).\n\n### What Each Layer Catches\n\n| Failure Mode | Unit | Integration | E2E | Chaos |\n|---|---|---|---|---|\n| Input validation bug | Yes | -- | -- | -- |\n| Wrong tool parameter name | -- | Yes | Yes | -- |\n| Authentication misconfiguration | -- | Yes | Yes | -- |\n| Escrow lifecycle state error | Partial | Yes | Yes | -- |\n| Schema drift between versions | -- | -- | Yes | -- |\n| Network partition during payment | -- | -- | -- | Yes |\n| Race condition in multi-agent bid | -- | -- | Partial | Yes |\n| Cascade failure from agent crash | -- | -- | -- | Yes |\n| Retry storm draining wallet | -- | -- | -- | Yes |\n| Slow response degrading throughput | -- | -- | -- | Yes |\n\n\"Partial\" means the layer can catch it if you write the test specifically for that scenario, but it will not catch it by default.\n\n### Recommended Ratios and Cost Model\n\nFor a production agent commerce system, target this distribution:\n\n- **60% unit tests** -- fast, cheap, catch logic bugs. Write these first for every new feature.\n- **30% integration tests** -- moderate speed, catch API interaction bugs. Use recorded responses for CI, live sandbox for nightly runs.\n- **10% end-to-end and chaos tests** -- slow, expensive, catch system-level failures. Run on merge to main and before releases.\n\nThe cost model matters. A unit test runs in 5ms and costs nothing. An integration test against recordings runs in 50ms. An integration test against the live sandbox runs in 500ms and consumes API credits. An end-to-end test runs in 30-120 seconds and consumes credits across multiple agent wallets. A chaos test can run for minutes and may leave state that needs cleanup. Budget accordingly.\n\n### Test Isolation Strategy\n\nEvery test layer needs a different isolation strategy:\n\n```python\n# Unit: no external dependencies, pure logic\ndef test_escrow_amount_validation():\n    agent = MyAgent(api_key=\"fake\", agent_id=\"test-agent\")\n    with pytest.raises(ValueError, match=\"amount must be positive\"):\n        agent.validate_escrow_params(amount=-100, counterparty=\"agent-b\")\n\n\n# Integration: recorded responses or sandbox, isolated wallet\ndef test_create_escrow_against_sandbox(test_harness):\n    result = test_harness.execute(\"create_escrow\", {\n        \"payer\": \"test-agent-a\",\n        \"payee\": \"test-agent-b\",\n        \"amount\": \"1.00\",\n        \"currency\": \"USD\",\n        \"conditions\": {\"delivery_by\": \"2026-12-31T00:00:00Z\"},\n    })\n    assert result[\"status\"] == \"pending\"\n    assert \"escrow_id\" in result\n\n\n# E2E: full agent lifecycle, dedicated test agents\ndef test_full_commerce_workflow(agent_a, agent_b):\n    # Agent B registers a service\n    service = agent_b.register_service(\"data-enrichment\", price=\"5.00\")\n    # Agent A discovers and purchases\n    results = agent_a.search_services(\"data-enrichment\")\n    escrow = agent_a.create_escrow(payee=agent_b.agent_id, amount=\"5.00\")\n    # Agent B delivers and agent A releases\n    agent_b.deliver(escrow[\"escrow_id\"])\n    agent_a.release_escrow(escrow[\"escrow_id\"])\n    assert agent_a.get_balance() \u003C initial_balance\n```\n\nName your test agents with the `test-` prefix so they are excluded from leaderboards and production metrics. GreenHelix filters `test-*` prefixed agents from public rankings.\n\n---\n\n## Chapter 2: AgentTestHarness Class\n\n### The Problem with Live API Testing in CI\n\nRunning integration tests against the live GreenHelix sandbox in every CI run creates three problems: flaky tests from network latency variance, API credit consumption that scales with your commit frequency, and rate limit hits when multiple developers push simultaneously. You need a way to capture real API responses once, then replay them deterministically in CI.\n\nThe `AgentTestHarness` class solves this with a record\u002Fplayback pattern. In record mode, it proxies every API call through to the real GreenHelix sandbox and saves the request-response pair to a cassette file. In playback mode, it matches incoming requests against recorded cassettes and returns the saved response without making a network call. This gives you the confidence of real API validation with the speed and reliability of mocking.\n\n### The Complete AgentTestHarness\n\n```python\nimport hashlib\nimport json\nimport os\nimport time\nimport logging\nfrom pathlib import Path\nfrom typing import Any, Optional\nfrom dataclasses import dataclass, field\n\nimport requests\n\n\nlogger = logging.getLogger(__name__)\n\n\n@dataclass\nclass CassetteEntry:\n    \"\"\"A single recorded request-response pair.\"\"\"\n    request_tool: str\n    request_input: dict\n    response_status: int\n    response_body: dict\n    response_headers: dict\n    timestamp: float\n    latency_ms: float\n\n\n@dataclass\nclass Cassette:\n    \"\"\"A collection of recorded interactions.\"\"\"\n    name: str\n    entries: list[CassetteEntry] = field(default_factory=list)\n    metadata: dict = field(default_factory=dict)\n\n    def save(self, path: Path) -> None:\n        data = {\n            \"name\": self.name,\n            \"metadata\": self.metadata,\n            \"entries\": [\n                {\n                    \"request_tool\": e.request_tool,\n                    \"request_input\": e.request_input,\n                    \"response_status\": e.response_status,\n                    \"response_body\": e.response_body,\n                    \"response_headers\": e.response_headers,\n                    \"timestamp\": e.timestamp,\n                    \"latency_ms\": e.latency_ms,\n                }\n                for e in self.entries\n            ],\n        }\n        path.parent.mkdir(parents=True, exist_ok=True)\n        path.write_text(json.dumps(data, indent=2, default=str))\n        logger.info(\"Saved cassette %s with %d entries\", self.name, len(self.entries))\n\n    @classmethod\n    def load(cls, path: Path) -> \"Cassette\":\n        data = json.loads(path.read_text())\n        entries = [\n            CassetteEntry(**e) for e in data[\"entries\"]\n        ]\n        return cls(name=data[\"name\"], entries=entries, metadata=data.get(\"metadata\", {}))\n\n\nclass AgentTestHarness:\n    \"\"\"\n    Test harness that wraps GreenHelix API calls with\n    recording\u002Fplayback for deterministic CI testing.\n    \"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        base_url: str = \"https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1\",\n        cassette_dir: str = \"tests\u002Fcassettes\",\n        mode: str = \"playback\",  # \"record\", \"playback\", or \"passthrough\"\n    ):\n        self.api_key = api_key\n        self.agent_id = agent_id\n        self.base_url = base_url\n        self.cassette_dir = Path(cassette_dir)\n        self.mode = mode\n        self._current_cassette: Optional[Cassette] = None\n        self._playback_index: int = 0\n\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n\n        # Assertion counters for test reporting\n        self.call_count = 0\n        self.assertion_count = 0\n        self.failures: list[str] = []\n\n    def start_cassette(self, name: str) -> None:\n        \"\"\"Begin recording or loading a cassette.\"\"\"\n        cassette_path = self.cassette_dir \u002F f\"{name}.json\"\n\n        if self.mode == \"record\":\n            self._current_cassette = Cassette(\n                name=name,\n                metadata={\n                    \"agent_id\": self.agent_id,\n                    \"base_url\": self.base_url,\n                    \"recorded_at\": time.time(),\n                },\n            )\n            logger.info(\"Recording cassette: %s\", name)\n\n        elif self.mode == \"playback\":\n            if not cassette_path.exists():\n                raise FileNotFoundError(\n                    f\"Cassette not found: {cassette_path}. \"\n                    f\"Run with mode='record' first.\"\n                )\n            self._current_cassette = Cassette.load(cassette_path)\n            self._playback_index = 0\n            logger.info(\n                \"Playing back cassette: %s (%d entries)\",\n                name, len(self._current_cassette.entries),\n            )\n\n        elif self.mode == \"passthrough\":\n            self._current_cassette = None\n            logger.info(\"Passthrough mode: all calls go to live API\")\n\n    def stop_cassette(self) -> None:\n        \"\"\"Finish recording and save the cassette.\"\"\"\n        if self.mode == \"record\" and self._current_cassette:\n            cassette_path = self.cassette_dir \u002F f\"{self._current_cassette.name}.json\"\n            self._current_cassette.save(cassette_path)\n        self._current_cassette = None\n        self._playback_index = 0\n\n    def execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"\n        Execute a GreenHelix tool call, recording or playing back\n        depending on the current mode.\n        \"\"\"\n        self.call_count += 1\n\n        if self.mode == \"playback\":\n            return self._playback(tool, input_data)\n        elif self.mode == \"record\":\n            return self._record(tool, input_data)\n        else:\n            return self._live_call(tool, input_data)\n\n    def _live_call(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Make a real API call to GreenHelix.\"\"\"\n        start = time.monotonic()\n        resp = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        latency_ms = (time.monotonic() - start) * 1000\n\n        body = resp.json() if resp.headers.get(\"content-type\", \"\").startswith(\"application\u002Fjson\") else {}\n        return {\n            \"status_code\": resp.status_code,\n            \"body\": body,\n            \"headers\": dict(resp.headers),\n            \"latency_ms\": latency_ms,\n        }\n\n    def _record(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Make a live call and record the result.\"\"\"\n        result = self._live_call(tool, input_data)\n\n        if self._current_cassette:\n            entry = CassetteEntry(\n                request_tool=tool,\n                request_input=input_data,\n                response_status=result[\"status_code\"],\n                response_body=result[\"body\"],\n                response_headers=result[\"headers\"],\n                timestamp=time.time(),\n                latency_ms=result[\"latency_ms\"],\n            )\n            self._current_cassette.entries.append(entry)\n\n        return result\n\n    def _playback(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Return a recorded response from the cassette.\"\"\"\n        if not self._current_cassette:\n            raise RuntimeError(\"No cassette loaded for playback\")\n\n        if self._playback_index >= len(self._current_cassette.entries):\n            raise RuntimeError(\n                f\"Cassette exhausted: expected at most \"\n                f\"{len(self._current_cassette.entries)} calls, \"\n                f\"got call #{self._playback_index + 1} for tool '{tool}'\"\n            )\n\n        entry = self._current_cassette.entries[self._playback_index]\n        self._playback_index += 1\n\n        # Verify the call matches what was recorded\n        if entry.request_tool != tool:\n            self.failures.append(\n                f\"Call #{self._playback_index}: expected tool \"\n                f\"'{entry.request_tool}', got '{tool}'\"\n            )\n            logger.warning(\n                \"Tool mismatch at index %d: recorded=%s, actual=%s\",\n                self._playback_index - 1, entry.request_tool, tool,\n            )\n\n        return {\n            \"status_code\": entry.response_status,\n            \"body\": entry.response_body,\n            \"headers\": entry.response_headers,\n            \"latency_ms\": entry.latency_ms,\n        }\n\n    # ── Assertion Helpers ────────────────────────────────────────────\n\n    def assert_success(self, result: dict, msg: str = \"\") -> None:\n        \"\"\"Assert the API call returned 200.\"\"\"\n        self.assertion_count += 1\n        if result[\"status_code\"] != 200:\n            detail = msg or f\"Expected 200, got {result['status_code']}\"\n            self.failures.append(detail)\n            raise AssertionError(detail)\n\n    def assert_status(self, result: dict, expected: int, msg: str = \"\") -> None:\n        \"\"\"Assert a specific HTTP status code.\"\"\"\n        self.assertion_count += 1\n        if result[\"status_code\"] != expected:\n            detail = msg or f\"Expected {expected}, got {result['status_code']}\"\n            self.failures.append(detail)\n            raise AssertionError(detail)\n\n    def assert_field(self, result: dict, field: str, expected: Any = None) -> None:\n        \"\"\"Assert a field exists in the response body, optionally matching a value.\"\"\"\n        self.assertion_count += 1\n        body = result[\"body\"]\n        if field not in body:\n            detail = f\"Field '{field}' not found in response. Keys: {list(body.keys())}\"\n            self.failures.append(detail)\n            raise AssertionError(detail)\n        if expected is not None and body[field] != expected:\n            detail = f\"Field '{field}': expected {expected!r}, got {body[field]!r}\"\n            self.failures.append(detail)\n            raise AssertionError(detail)\n\n    def assert_escrow_state(self, result: dict, expected_state: str) -> None:\n        \"\"\"Assert an escrow is in a specific lifecycle state.\"\"\"\n        self.assertion_count += 1\n        state = result[\"body\"].get(\"status\") or result[\"body\"].get(\"state\")\n        if state != expected_state:\n            detail = f\"Escrow state: expected '{expected_state}', got '{state}'\"\n            self.failures.append(detail)\n            raise AssertionError(detail)\n\n    def assert_balance_changed(\n        self, before: dict, after: dict, expected_delta: str\n    ) -> None:\n        \"\"\"Assert a wallet balance changed by the expected amount.\"\"\"\n        self.assertion_count += 1\n        from decimal import Decimal\n        before_bal = Decimal(str(before[\"body\"][\"balance\"]))\n        after_bal = Decimal(str(after[\"body\"][\"balance\"]))\n        delta = after_bal - before_bal\n        if delta != Decimal(expected_delta):\n            detail = (\n                f\"Balance delta: expected {expected_delta}, \"\n                f\"got {delta} ({before_bal} -> {after_bal})\"\n            )\n            self.failures.append(detail)\n            raise AssertionError(detail)\n\n    def report(self) -> dict:\n        \"\"\"Generate a test execution report.\"\"\"\n        return {\n            \"total_calls\": self.call_count,\n            \"total_assertions\": self.assertion_count,\n            \"failures\": len(self.failures),\n            \"failure_details\": self.failures,\n            \"mode\": self.mode,\n            \"passed\": len(self.failures) == 0,\n        }\n```\n\n### Using the Harness in Tests\n\nRecord cassettes once against the live sandbox, then replay them in every CI run:\n\n```python\nimport pytest\nimport os\n\n\n@pytest.fixture\ndef harness():\n    mode = os.environ.get(\"TEST_MODE\", \"playback\")\n    h = AgentTestHarness(\n        api_key=os.environ.get(\"GREENHELIX_API_KEY\", \"test-key\"),\n        agent_id=\"test-qa-agent\",\n        mode=mode,\n    )\n    return h\n\n\ndef test_escrow_lifecycle(harness):\n    \"\"\"Test the full escrow create -> release cycle.\"\"\"\n    harness.start_cassette(\"escrow_lifecycle\")\n\n    # Create escrow\n    create_result = harness.execute(\"create_escrow\", {\n        \"payer\": \"test-qa-agent\",\n        \"payee\": \"test-counterparty\",\n        \"amount\": \"10.00\",\n        \"currency\": \"USD\",\n        \"conditions\": {\"delivery_by\": \"2026-12-31T00:00:00Z\"},\n    })\n    harness.assert_success(create_result)\n    harness.assert_field(create_result, \"escrow_id\")\n    harness.assert_escrow_state(create_result, \"pending\")\n\n    escrow_id = create_result[\"body\"][\"escrow_id\"]\n\n    # Release escrow\n    release_result = harness.execute(\"release_escrow\", {\n        \"escrow_id\": escrow_id,\n        \"agent_id\": \"test-qa-agent\",\n    })\n    harness.assert_success(release_result)\n    harness.assert_escrow_state(release_result, \"released\")\n\n    harness.stop_cassette()\n\n    report = harness.report()\n    assert report[\"passed\"], f\"Test failures: {report['failure_details']}\"\n```\n\nTo re-record cassettes when the API changes, run your tests with `TEST_MODE=record`. Commit the cassette JSON files alongside your tests. Review cassette diffs in pull requests to catch unexpected API response changes -- this is a lightweight form of contract testing that requires zero additional tooling.\n\n### Cassette Hygiene\n\nThree rules keep cassettes reliable. First, never record cassettes with production API keys. Use sandbox keys exclusively. The cassette files will contain response data that could leak if your repository is public. Second, re-record cassettes on a schedule (weekly or when the GreenHelix API version changes). Stale cassettes mask real incompatibilities. Third, strip non-deterministic fields (timestamps, request IDs) from cassette matching. The harness matches on tool name by default, which is sufficient for ordered test flows. For unordered flows, extend the matching to include a hash of the input parameters.\n\n---\n\n## Chapter 3: Mock Strategies for Agent Commerce\n\n### When Mocks Are the Right Tool\n\nMocks are appropriate when you need to test your agent's decision logic without involving any external system. The goal is speed and isolation: validate that your agent makes the right decisions given specific API responses, without caring whether those responses came from a real server. Use mocks for unit tests. Use the test harness (Chapter 2) for integration tests. Never mock in end-to-end tests.\n\n### Mocking the the REST API Endpoint\n\nThe GreenHelix gateway exposes a single endpoint for tool execution: the REST API (`POST \u002Fv1\u002F{tool}`) with a JSON body containing `tool` and `input` fields. This makes mocking straightforward -- you intercept the one endpoint and route responses based on the tool name.\n\n```python\nimport json\nimport time\nfrom typing import Callable, Optional\nfrom dataclasses import dataclass, field\nfrom unittest.mock import MagicMock\n\n\n@dataclass\nclass MockResponse:\n    \"\"\"A canned response for a specific tool call.\"\"\"\n    status_code: int = 200\n    body: dict = field(default_factory=dict)\n    headers: dict = field(default_factory=lambda: {\"content-type\": \"application\u002Fjson\"})\n    delay_ms: float = 0\n\n\nclass GreenHelixMock:\n    \"\"\"\n    Mock server for GreenHelix REST API endpoints.\n    Supports static responses, stateful escrow simulation,\n    and programmable error injection.\n    \"\"\"\n\n    def __init__(self):\n        self._handlers: dict[str, Callable] = {}\n        self._default_responses: dict[str, MockResponse] = {}\n        self._call_log: list[dict] = []\n        self._escrow_state: dict[str, dict] = {}\n        self._wallet_balances: dict[str, str] = {}\n        self._error_queue: list[MockResponse] = []\n\n        # Register built-in stateful handlers\n        self._handlers[\"create_escrow\"] = self._handle_create_escrow\n        self._handlers[\"release_escrow\"] = self._handle_release_escrow\n        self._handlers[\"cancel_escrow\"] = self._handle_cancel_escrow\n        self._handlers[\"get_balance\"] = self._handle_get_balance\n        self._handlers[\"deposit\"] = self._handle_deposit\n\n    def set_response(self, tool: str, response: MockResponse) -> None:\n        \"\"\"Set a static response for a tool.\"\"\"\n        self._default_responses[tool] = response\n\n    def set_balance(self, agent_id: str, balance: str) -> None:\n        \"\"\"Pre-set a wallet balance for stateful testing.\"\"\"\n        self._wallet_balances[agent_id] = balance\n\n    def inject_error(self, status_code: int, body: Optional[dict] = None) -> None:\n        \"\"\"Queue an error to be returned on the next call (any tool).\"\"\"\n        self._error_queue.append(MockResponse(\n            status_code=status_code,\n            body=body or {\"type\": \"error\", \"title\": \"Injected error\", \"status\": status_code},\n        ))\n\n    def inject_errors(self, count: int, status_code: int) -> None:\n        \"\"\"Queue multiple identical errors.\"\"\"\n        for _ in range(count):\n            self.inject_error(status_code)\n\n    def execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Simulate a the REST API call.\"\"\"\n        self._call_log.append({\n            \"tool\": tool,\n            \"input\": input_data,\n            \"timestamp\": time.time(),\n        })\n\n        # Check error queue first\n        if self._error_queue:\n            err = self._error_queue.pop(0)\n            if err.delay_ms > 0:\n                time.sleep(err.delay_ms \u002F 1000)\n            return {\"status_code\": err.status_code, \"body\": err.body, \"headers\": err.headers}\n\n        # Check for custom handler\n        if tool in self._handlers:\n            return self._handlers[tool](input_data)\n\n        # Check for static response\n        if tool in self._default_responses:\n            resp = self._default_responses[tool]\n            if resp.delay_ms > 0:\n                time.sleep(resp.delay_ms \u002F 1000)\n            return {\"status_code\": resp.status_code, \"body\": resp.body, \"headers\": resp.headers}\n\n        # Default: 404 unknown tool\n        return {\n            \"status_code\": 404,\n            \"body\": {\"type\": \"error\", \"title\": f\"Unknown tool: {tool}\", \"status\": 404},\n            \"headers\": {\"content-type\": \"application\u002Fjson\"},\n        }\n\n    # ── Stateful Handlers ────────────────────────────────────────────\n\n    def _handle_create_escrow(self, input_data: dict) -> dict:\n        escrow_id = f\"esc_{hashlib.sha256(json.dumps(input_data, sort_keys=True).encode()).hexdigest()[:12]}\"\n        self._escrow_state[escrow_id] = {\n            \"escrow_id\": escrow_id,\n            \"payer\": input_data[\"payer\"],\n            \"payee\": input_data[\"payee\"],\n            \"amount\": input_data[\"amount\"],\n            \"currency\": input_data.get(\"currency\", \"USD\"),\n            \"status\": \"pending\",\n            \"created_at\": time.time(),\n        }\n        return {\n            \"status_code\": 200,\n            \"body\": self._escrow_state[escrow_id].copy(),\n            \"headers\": {\"content-type\": \"application\u002Fjson\"},\n        }\n\n    def _handle_release_escrow(self, input_data: dict) -> dict:\n        escrow_id = input_data.get(\"escrow_id\")\n        if escrow_id not in self._escrow_state:\n            return {\n                \"status_code\": 404,\n                \"body\": {\"type\": \"error\", \"title\": \"Escrow not found\", \"status\": 404},\n                \"headers\": {\"content-type\": \"application\u002Fjson\"},\n            }\n        escrow = self._escrow_state[escrow_id]\n        if escrow[\"status\"] != \"pending\":\n            return {\n                \"status_code\": 409,\n                \"body\": {\n                    \"type\": \"error\",\n                    \"title\": f\"Cannot release escrow in state '{escrow['status']}'\",\n                    \"status\": 409,\n                },\n                \"headers\": {\"content-type\": \"application\u002Fjson\"},\n            }\n        escrow[\"status\"] = \"released\"\n        escrow[\"released_at\"] = time.time()\n        return {\n            \"status_code\": 200,\n            \"body\": escrow.copy(),\n            \"headers\": {\"content-type\": \"application\u002Fjson\"},\n        }\n\n    def _handle_cancel_escrow(self, input_data: dict) -> dict:\n        escrow_id = input_data.get(\"escrow_id\")\n        if escrow_id not in self._escrow_state:\n            return {\n                \"status_code\": 404,\n                \"body\": {\"type\": \"error\", \"title\": \"Escrow not found\", \"status\": 404},\n                \"headers\": {\"content-type\": \"application\u002Fjson\"},\n            }\n        escrow = self._escrow_state[escrow_id]\n        if escrow[\"status\"] != \"pending\":\n            return {\n                \"status_code\": 409,\n                \"body\": {\n                    \"type\": \"error\",\n                    \"title\": f\"Cannot cancel escrow in state '{escrow['status']}'\",\n                    \"status\": 409,\n                },\n                \"headers\": {\"content-type\": \"application\u002Fjson\"},\n            }\n        escrow[\"status\"] = \"cancelled\"\n        escrow[\"cancelled_at\"] = time.time()\n        return {\n            \"status_code\": 200,\n            \"body\": escrow.copy(),\n            \"headers\": {\"content-type\": \"application\u002Fjson\"},\n        }\n\n    def _handle_get_balance(self, input_data: dict) -> dict:\n        agent_id = input_data.get(\"agent_id\", \"\")\n        balance = self._wallet_balances.get(agent_id, \"0.00\")\n        return {\n            \"status_code\": 200,\n            \"body\": {\"agent_id\": agent_id, \"balance\": balance, \"currency\": \"USD\"},\n            \"headers\": {\"content-type\": \"application\u002Fjson\"},\n        }\n\n    def _handle_deposit(self, input_data: dict) -> dict:\n        agent_id = input_data.get(\"agent_id\", \"\")\n        amount = input_data.get(\"amount\", \"0.00\")\n        from decimal import Decimal\n        current = Decimal(self._wallet_balances.get(agent_id, \"0.00\"))\n        new_balance = current + Decimal(str(amount))\n        self._wallet_balances[agent_id] = str(new_balance)\n        return {\n            \"status_code\": 200,\n            \"body\": {\n                \"agent_id\": agent_id,\n                \"deposited\": str(amount),\n                \"balance\": str(new_balance),\n                \"currency\": \"USD\",\n            },\n            \"headers\": {\"content-type\": \"application\u002Fjson\"},\n        }\n\n    # ── Introspection ────────────────────────────────────────────────\n\n    def get_call_log(self) -> list[dict]:\n        return self._call_log.copy()\n\n    def get_calls_for_tool(self, tool: str) -> list[dict]:\n        return [c for c in self._call_log if c[\"tool\"] == tool]\n\n    def assert_called(self, tool: str, times: Optional[int] = None) -> None:\n        calls = self.get_calls_for_tool(tool)\n        if times is not None and len(calls) != times:\n            raise AssertionError(\n                f\"Expected {times} calls to '{tool}', got {len(calls)}\"\n            )\n        if not calls:\n            raise AssertionError(f\"Expected at least one call to '{tool}', got none\")\n\n    def reset(self) -> None:\n        self._call_log.clear()\n        self._escrow_state.clear()\n        self._wallet_balances.clear()\n        self._error_queue.clear()\n```\n\n### Mock Factories for Common Scenarios\n\nBuilding mocks from scratch for every test is tedious. Factory functions encapsulate common setups:\n\n```python\nimport hashlib\n\n\ndef create_funded_mock(agent_id: str, balance: str = \"100.00\") -> GreenHelixMock:\n    \"\"\"Create a mock with a pre-funded wallet.\"\"\"\n    mock = GreenHelixMock()\n    mock.set_balance(agent_id, balance)\n    return mock\n\n\ndef create_failing_mock(failure_count: int = 3, status_code: int = 500) -> GreenHelixMock:\n    \"\"\"Create a mock that fails N times then succeeds.\"\"\"\n    mock = GreenHelixMock()\n    mock.inject_errors(failure_count, status_code)\n    return mock\n\n\ndef create_rate_limited_mock(burst_limit: int = 5) -> GreenHelixMock:\n    \"\"\"Create a mock that returns 429 after N calls.\"\"\"\n    mock = GreenHelixMock()\n    original_execute = mock.execute\n\n    call_count = 0\n    def rate_limited_execute(tool: str, input_data: dict) -> dict:\n        nonlocal call_count\n        call_count += 1\n        if call_count > burst_limit:\n            return {\n                \"status_code\": 429,\n                \"body\": {\n                    \"type\": \"error\",\n                    \"title\": \"Rate limit exceeded\",\n                    \"status\": 429,\n                    \"retry_after\": 60,\n                },\n                \"headers\": {\n                    \"content-type\": \"application\u002Fjson\",\n                    \"retry-after\": \"60\",\n                },\n            }\n        return original_execute(tool, input_data)\n\n    mock.execute = rate_limited_execute\n    return mock\n\n\ndef create_timeout_mock(timeout_tools: list[str], timeout_ms: int = 30000) -> GreenHelixMock:\n    \"\"\"Create a mock where specific tools always time out.\"\"\"\n    mock = GreenHelixMock()\n    for tool in timeout_tools:\n        mock.set_response(tool, MockResponse(\n            status_code=504,\n            body={\"type\": \"error\", \"title\": \"Gateway timeout\", \"status\": 504},\n            delay_ms=timeout_ms,\n        ))\n    return mock\n```\n\n### Testing Retry Logic with Mocks\n\nThe most common production failure pattern is transient errors requiring retries. Use the mock's error queue to validate your retry logic handles escalating failures:\n\n```python\ndef test_retry_logic_with_backoff(my_agent_class):\n    \"\"\"Verify the agent retries transient errors with backoff.\"\"\"\n    mock = GreenHelixMock()\n    # Fail twice with 500, then succeed\n    mock.inject_errors(2, 500)\n    mock.set_balance(\"test-agent\", \"50.00\")\n\n    agent = my_agent_class(api=mock, agent_id=\"test-agent\")\n    result = agent.check_balance()\n\n    # Agent should have retried and eventually succeeded\n    assert result[\"balance\"] == \"50.00\"\n    # Should have made 3 calls total: 2 failures + 1 success\n    mock.assert_called(\"get_balance\", times=3)\n\n\ndef test_retry_exhaustion():\n    \"\"\"Verify the agent gives up after max retries.\"\"\"\n    mock = GreenHelixMock()\n    mock.inject_errors(10, 503)  # More errors than max retries\n\n    agent = my_agent_class(api=mock, agent_id=\"test-agent\", max_retries=3)\n    with pytest.raises(ServiceUnavailableError):\n        agent.check_balance()\n\n    mock.assert_called(\"get_balance\", times=4)  # 1 initial + 3 retries\n```\n\n---\n\n## Chapter 4: ChaosInjector Class\n\n### Why Chaos Testing Matters for Agent Commerce\n\nUnit tests and integration tests validate the happy path and a handful of known error paths. Chaos testing answers a different question: what happens when the infrastructure itself misbehaves in ways you did not anticipate? In agent commerce, the consequences of unhandled infrastructure failures are financial. An escrow that gets created but whose confirmation is lost leaves funds locked. A webhook that delivers twice triggers duplicate payments. A DNS resolution delay that pushes a request past its timeout causes a retry that creates a duplicate escrow. These are not hypothetical -- they are the actual failure modes observed in production multi-agent systems.\n\nThe `ChaosInjector` class wraps any API client (real or mock) and injects configurable failures into the communication layer. It operates at the transport level, corrupting responses after they leave the server but before your agent processes them.\n\n### The Complete ChaosInjector\n\n```python\nimport copy\nimport json\nimport random\nimport time\nimport threading\nimport logging\nfrom dataclasses import dataclass, field\nfrom enum import Enum\nfrom typing import Any, Callable, Optional\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass FailureMode(Enum):\n    LATENCY = \"latency\"\n    TIMEOUT = \"timeout\"\n    PARTIAL_RESPONSE = \"partial_response\"\n    WRONG_STATUS = \"wrong_status\"\n    CORRUPT_BODY = \"corrupt_body\"\n    SCHEMA_DRIFT = \"schema_drift\"\n    CONNECTION_RESET = \"connection_reset\"\n    DUPLICATE_RESPONSE = \"duplicate_response\"\n\n\n@dataclass\nclass ChaosConfig:\n    \"\"\"Configuration for a chaos injection scenario.\"\"\"\n    failure_mode: FailureMode\n    probability: float = 1.0       # 0.0 to 1.0\n    target_tools: list[str] = field(default_factory=list)  # empty = all tools\n    latency_ms: float = 5000       # for LATENCY mode\n    timeout_ms: float = 30000      # for TIMEOUT mode\n    corrupt_fields: list[str] = field(default_factory=list)  # for CORRUPT_BODY\n    drift_schema: dict = field(default_factory=dict)  # for SCHEMA_DRIFT\n\n\nclass ChaosInjector:\n    \"\"\"\n    Wraps an API client and injects configurable failures\n    into agent-to-gateway communication.\n    \"\"\"\n\n    def __init__(self, wrapped_client: Any, seed: Optional[int] = None):\n        self._client = wrapped_client\n        self._configs: list[ChaosConfig] = []\n        self._rng = random.Random(seed)\n        self._event_log: list[dict] = []\n        self._active = True\n        self._lock = threading.Lock()\n\n    def add_chaos(self, config: ChaosConfig) -> None:\n        \"\"\"Register a chaos configuration.\"\"\"\n        self._configs.append(config)\n        logger.info(\n            \"Chaos registered: %s (p=%.2f, tools=%s)\",\n            config.failure_mode.value,\n            config.probability,\n            config.target_tools or \"all\",\n        )\n\n    def pause(self) -> None:\n        \"\"\"Temporarily disable chaos injection.\"\"\"\n        self._active = False\n\n    def resume(self) -> None:\n        \"\"\"Re-enable chaos injection.\"\"\"\n        self._active = True\n\n    def execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute with potential chaos injection.\"\"\"\n        # Get the real response first\n        result = self._client.execute(tool, input_data)\n\n        if not self._active:\n            return result\n\n        # Apply each matching chaos config\n        for config in self._configs:\n            if not self._should_apply(config, tool):\n                continue\n\n            event = {\n                \"timestamp\": time.time(),\n                \"tool\": tool,\n                \"failure_mode\": config.failure_mode.value,\n            }\n\n            result = self._apply_chaos(config, result, tool)\n            event[\"applied\"] = True\n            with self._lock:\n                self._event_log.append(event)\n            logger.warning(\n                \"Chaos injected: %s on tool '%s'\",\n                config.failure_mode.value, tool,\n            )\n\n        return result\n\n    def _should_apply(self, config: ChaosConfig, tool: str) -> bool:\n        \"\"\"Determine if this chaos config applies to this call.\"\"\"\n        if config.target_tools and tool not in config.target_tools:\n            return False\n        return self._rng.random() \u003C config.probability\n\n    def _apply_chaos(self, config: ChaosConfig, result: dict, tool: str) -> dict:\n        \"\"\"Apply a specific failure mode to the response.\"\"\"\n        mode = config.failure_mode\n\n        if mode == FailureMode.LATENCY:\n            time.sleep(config.latency_ms \u002F 1000)\n            return result\n\n        elif mode == FailureMode.TIMEOUT:\n            time.sleep(config.timeout_ms \u002F 1000)\n            raise TimeoutError(\n                f\"Chaos: simulated timeout after {config.timeout_ms}ms \"\n                f\"on tool '{tool}'\"\n            )\n\n        elif mode == FailureMode.PARTIAL_RESPONSE:\n            corrupted = copy.deepcopy(result)\n            body = corrupted.get(\"body\", {})\n            keys = list(body.keys())\n            if len(keys) > 1:\n                # Remove a random subset of fields\n                remove_count = max(1, len(keys) \u002F\u002F 2)\n                for key in self._rng.sample(keys, remove_count):\n                    del body[key]\n            corrupted[\"body\"] = body\n            return corrupted\n\n        elif mode == FailureMode.WRONG_STATUS:\n            corrupted = copy.deepcopy(result)\n            corrupted[\"status_code\"] = self._rng.choice([500, 502, 503, 504])\n            return corrupted\n\n        elif mode == FailureMode.CORRUPT_BODY:\n            corrupted = copy.deepcopy(result)\n            body = corrupted.get(\"body\", {})\n            for field_name in config.corrupt_fields:\n                if field_name in body:\n                    original = body[field_name]\n                    body[field_name] = self._corrupt_value(original)\n            corrupted[\"body\"] = body\n            return corrupted\n\n        elif mode == FailureMode.SCHEMA_DRIFT:\n            corrupted = copy.deepcopy(result)\n            body = corrupted.get(\"body\", {})\n            # Add unexpected fields\n            for key, value in config.drift_schema.items():\n                body[key] = value\n            # Rename existing fields to simulate API version change\n            if \"status\" in body:\n                body[\"state\"] = body.pop(\"status\")\n            corrupted[\"body\"] = body\n            return corrupted\n\n        elif mode == FailureMode.CONNECTION_RESET:\n            raise ConnectionError(\n                f\"Chaos: simulated connection reset on tool '{tool}'\"\n            )\n\n        elif mode == FailureMode.DUPLICATE_RESPONSE:\n            # Return the response twice (simulates webhook double-delivery)\n            return result  # caller sees normal response, but we log it as duplicate\n\n        return result\n\n    def _corrupt_value(self, value: Any) -> Any:\n        \"\"\"Corrupt a value while keeping the same type.\"\"\"\n        if isinstance(value, str):\n            if value.replace(\".\", \"\").replace(\"-\", \"\").isdigit():\n                # Numeric string: flip sign or add digits\n                return str(float(value) * -1)\n            return value[::-1]  # Reverse the string\n        elif isinstance(value, (int, float)):\n            return value * -1\n        elif isinstance(value, bool):\n            return not value\n        elif isinstance(value, list):\n            return []\n        elif isinstance(value, dict):\n            return {}\n        return None\n\n    def get_event_log(self) -> list[dict]:\n        \"\"\"Return the log of all chaos events.\"\"\"\n        with self._lock:\n            return self._event_log.copy()\n\n    def get_injection_count(self) -> int:\n        \"\"\"Return the total number of chaos injections.\"\"\"\n        with self._lock:\n            return len(self._event_log)\n\n    def reset(self) -> None:\n        \"\"\"Clear all chaos configs and logs.\"\"\"\n        self._configs.clear()\n        with self._lock:\n            self._event_log.clear()\n```\n\n### Chaos Scenarios for Agent Commerce\n\nHere are the chaos scenarios that match real production failures. Each one uses the `ChaosInjector` with specific configurations:\n\n```python\ndef scenario_agent_dies_mid_escrow(harness, chaos):\n    \"\"\"\n    Simulate: Agent creates escrow, then the counterparty agent\n    becomes unreachable before delivery.\n    \"\"\"\n    chaos.add_chaos(ChaosConfig(\n        failure_mode=FailureMode.CONNECTION_RESET,\n        probability=1.0,\n        target_tools=[\"release_escrow\", \"cancel_escrow\"],\n    ))\n\n    # Create escrow succeeds\n    result = chaos.execute(\"create_escrow\", {\n        \"payer\": \"test-agent-a\",\n        \"payee\": \"test-agent-b\",\n        \"amount\": \"25.00\",\n        \"currency\": \"USD\",\n        \"conditions\": {\"delivery_by\": \"2026-12-31T00:00:00Z\"},\n    })\n    assert result[\"status_code\"] == 200\n\n    # Attempting to release or cancel fails with connection reset\n    try:\n        chaos.execute(\"release_escrow\", {\n            \"escrow_id\": result[\"body\"][\"escrow_id\"],\n            \"agent_id\": \"test-agent-a\",\n        })\n        assert False, \"Should have raised ConnectionError\"\n    except ConnectionError:\n        pass  # Expected -- agent should handle this with retry + timeout\n\n\ndef scenario_webhook_double_delivery(harness, chaos):\n    \"\"\"\n    Simulate: Webhook delivers the same escrow release notification twice.\n    Agent must be idempotent.\n    \"\"\"\n    chaos.add_chaos(ChaosConfig(\n        failure_mode=FailureMode.DUPLICATE_RESPONSE,\n        probability=1.0,\n        target_tools=[\"release_escrow\"],\n    ))\n\n    # First release succeeds\n    result1 = chaos.execute(\"release_escrow\", {\n        \"escrow_id\": \"esc_abc123\",\n        \"agent_id\": \"test-agent-a\",\n    })\n    # Second identical release should be idempotent\n    result2 = chaos.execute(\"release_escrow\", {\n        \"escrow_id\": \"esc_abc123\",\n        \"agent_id\": \"test-agent-a\",\n    })\n    # Agent should handle both gracefully -- no double payment\n\n\ndef scenario_schema_drift_between_versions(harness, chaos):\n    \"\"\"\n    Simulate: GreenHelix API changes 'status' field to 'state'\n    in escrow responses (v2 migration).\n    \"\"\"\n    chaos.add_chaos(ChaosConfig(\n        failure_mode=FailureMode.SCHEMA_DRIFT,\n        probability=1.0,\n        target_tools=[\"create_escrow\", \"release_escrow\"],\n        drift_schema={\"api_version\": \"2.0\", \"deprecated_fields\": [\"status\"]},\n    ))\n\n    result = chaos.execute(\"create_escrow\", {\n        \"payer\": \"test-agent-a\",\n        \"payee\": \"test-agent-b\",\n        \"amount\": \"10.00\",\n        \"currency\": \"USD\",\n    })\n    # Agent should handle both 'status' and 'state' fields\n    body = result[\"body\"]\n    state = body.get(\"status\") or body.get(\"state\")\n    assert state is not None, \"Agent must handle schema drift gracefully\"\n\n\ndef scenario_latency_spike_during_payment(harness, chaos):\n    \"\"\"\n    Simulate: 5-second latency spike on payment tools.\n    Tests whether agent times out and retries (risking double-payment)\n    or waits patiently.\n    \"\"\"\n    chaos.add_chaos(ChaosConfig(\n        failure_mode=FailureMode.LATENCY,\n        probability=0.5,\n        target_tools=[\"deposit\", \"create_escrow\", \"release_escrow\"],\n        latency_ms=5000,\n    ))\n\n    # Agent should handle variable latency without creating duplicates\n    result = chaos.execute(\"deposit\", {\n        \"agent_id\": \"test-agent-a\",\n        \"amount\": \"10.00\",\n    })\n    assert result[\"status_code\"] == 200\n```\n\n### Running Chaos Tests in CI\n\nChaos tests should run on merge to main, not on every commit. They are slower and nondeterministic by design. Use a fixed random seed for reproducibility in CI, and a random seed for exploratory testing locally:\n\n```python\n@pytest.fixture\ndef chaos_harness():\n    \"\"\"Create a chaos-wrapped test harness.\"\"\"\n    mock = create_funded_mock(\"test-agent-a\", \"1000.00\")\n    mock.set_balance(\"test-agent-b\", \"500.00\")\n    seed = int(os.environ.get(\"CHAOS_SEED\", \"42\"))\n    injector = ChaosInjector(mock, seed=seed)\n    return injector\n\n\n@pytest.mark.chaos\nclass TestChaosResilience:\n    \"\"\"Chaos tests -- run with: pytest -m chaos\"\"\"\n\n    def test_survives_random_failures(self, chaos_harness):\n        chaos_harness.add_chaos(ChaosConfig(\n            failure_mode=FailureMode.WRONG_STATUS,\n            probability=0.3,\n        ))\n        chaos_harness.add_chaos(ChaosConfig(\n            failure_mode=FailureMode.LATENCY,\n            probability=0.2,\n            latency_ms=2000,\n        ))\n\n        successes = 0\n        for _ in range(100):\n            try:\n                result = chaos_harness.execute(\"get_balance\", {\"agent_id\": \"test-agent-a\"})\n                if result[\"status_code\"] == 200:\n                    successes += 1\n            except (TimeoutError, ConnectionError):\n                pass\n\n        # With 30% status corruption and 20% latency, expect ~70% success\n        assert successes > 50, f\"Only {successes}\u002F100 succeeded under chaos\"\n```\n\n---\n\n## Chapter 5: ContractValidator Class\n\n### The Contract Testing Problem\n\nIn a multi-agent system, every agent is both a producer and consumer of API contracts. Agent A calls `create_escrow` expecting a response with an `escrow_id` field. Agent B subscribes to escrow webhooks expecting a `status` field with specific enum values. When agent A upgrades its GreenHelix SDK and the response format changes, agent B breaks. Nobody tested the interaction because each agent has its own test suite and neither tests the contract between them.\n\nContract testing solves this by making the interface between agents an explicit, versioned, testable artifact. Each consumer declares what it expects from a producer. Each producer validates that its responses satisfy all consumer expectations. When a change breaks a contract, the producer's CI fails before the code ships.\n\n### The Complete ContractValidator\n\n```python\nimport json\nimport re\nimport time\nimport logging\nfrom copy import deepcopy\nfrom dataclasses import dataclass, field\nfrom enum import Enum\nfrom pathlib import Path\nfrom typing import Any, Optional\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass Severity(Enum):\n    ERROR = \"error\"          # Breaking change, blocks deployment\n    WARNING = \"warning\"      # Potentially breaking, manual review\n    INFO = \"info\"            # Non-breaking change, informational\n\n\n@dataclass\nclass ContractViolation:\n    \"\"\"A single contract violation.\"\"\"\n    field: str\n    expected: str\n    actual: str\n    severity: Severity\n    message: str\n\n\n@dataclass\nclass ToolContract:\n    \"\"\"Contract definition for a single GreenHelix tool.\"\"\"\n    tool_name: str\n    version: str\n    input_schema: dict          # JSON Schema for tool input\n    output_schema: dict         # JSON Schema for tool output\n    required_output_fields: list[str] = field(default_factory=list)\n    optional_output_fields: list[str] = field(default_factory=list)\n    status_codes: list[int] = field(default_factory=lambda: [200])\n    constraints: list[dict] = field(default_factory=list)\n\n\n@dataclass\nclass AgentContract:\n    \"\"\"Contract between two agents or between an agent and the gateway.\"\"\"\n    consumer: str               # Agent ID of the consumer\n    producer: str               # Agent ID or \"gateway\"\n    tools: list[ToolContract] = field(default_factory=list)\n    metadata: dict = field(default_factory=dict)\n\n    def save(self, path: Path) -> None:\n        data = {\n            \"consumer\": self.consumer,\n            \"producer\": self.producer,\n            \"metadata\": self.metadata,\n            \"tools\": [\n                {\n                    \"tool_name\": t.tool_name,\n                    \"version\": t.version,\n                    \"input_schema\": t.input_schema,\n                    \"output_schema\": t.output_schema,\n                    \"required_output_fields\": t.required_output_fields,\n                    \"optional_output_fields\": t.optional_output_fields,\n                    \"status_codes\": t.status_codes,\n                    \"constraints\": t.constraints,\n                }\n                for t in self.tools\n            ],\n        }\n        path.parent.mkdir(parents=True, exist_ok=True)\n        path.write_text(json.dumps(data, indent=2))\n\n    @classmethod\n    def load(cls, path: Path) -> \"AgentContract\":\n        data = json.loads(path.read_text())\n        tools = [ToolContract(**t) for t in data[\"tools\"]]\n        return cls(\n            consumer=data[\"consumer\"],\n            producer=data[\"producer\"],\n            tools=tools,\n            metadata=data.get(\"metadata\", {}),\n        )\n\n\nclass ContractValidator:\n    \"\"\"\n    Validates API responses against consumer-driven contracts.\n    Catches breaking changes before they reach production.\n    \"\"\"\n\n    def __init__(self, contracts_dir: str = \"contracts\"):\n        self.contracts_dir = Path(contracts_dir)\n        self._contracts: list[AgentContract] = []\n        self._violations: list[ContractViolation] = []\n        self._validations: int = 0\n\n    def load_contracts(self) -> int:\n        \"\"\"Load all contract files from the contracts directory.\"\"\"\n        loaded = 0\n        if not self.contracts_dir.exists():\n            logger.warning(\"Contracts directory not found: %s\", self.contracts_dir)\n            return 0\n\n        for path in self.contracts_dir.glob(\"*.contract.json\"):\n            contract = AgentContract.load(path)\n            self._contracts.append(contract)\n            loaded += 1\n            logger.info(\n                \"Loaded contract: %s -> %s (%d tools)\",\n                contract.consumer, contract.producer, len(contract.tools),\n            )\n        return loaded\n\n    def add_contract(self, contract: AgentContract) -> None:\n        \"\"\"Register a contract programmatically.\"\"\"\n        self._contracts.append(contract)\n\n    def validate_response(\n        self, tool: str, response: dict, producer: str = \"gateway\"\n    ) -> list[ContractViolation]:\n        \"\"\"Validate a tool response against all matching contracts.\"\"\"\n        self._validations += 1\n        violations = []\n\n        for contract in self._contracts:\n            if contract.producer != producer:\n                continue\n\n            for tool_contract in contract.tools:\n                if tool_contract.tool_name != tool:\n                    continue\n\n                tool_violations = self._validate_tool_response(\n                    tool_contract, response, contract.consumer\n                )\n                violations.extend(tool_violations)\n\n        self._violations.extend(violations)\n        return violations\n\n    def _validate_tool_response(\n        self,\n        contract: ToolContract,\n        response: dict,\n        consumer: str,\n    ) -> list[ContractViolation]:\n        \"\"\"Validate a single tool response against its contract.\"\"\"\n        violations = []\n        body = response.get(\"body\", {})\n        status = response.get(\"status_code\", 0)\n\n        # Check status code\n        if status not in contract.status_codes:\n            violations.append(ContractViolation(\n                field=\"status_code\",\n                expected=str(contract.status_codes),\n                actual=str(status),\n                severity=Severity.ERROR,\n                message=(\n                    f\"Consumer '{consumer}' expects status \"\n                    f\"{contract.status_codes} from '{contract.tool_name}', \"\n                    f\"got {status}\"\n                ),\n            ))\n\n        # Check required fields\n        for field_name in contract.required_output_fields:\n            if field_name not in body:\n                violations.append(ContractViolation(\n                    field=field_name,\n                    expected=\"present\",\n                    actual=\"missing\",\n                    severity=Severity.ERROR,\n                    message=(\n                        f\"Consumer '{consumer}' requires field \"\n                        f\"'{field_name}' in '{contract.tool_name}' response\"\n                    ),\n                ))\n\n        # Check field types from output schema\n        for field_name, schema in contract.output_schema.items():\n            if field_name not in body:\n                continue\n            type_violation = self._check_type(field_name, body[field_name], schema)\n            if type_violation:\n                violations.append(type_violation)\n\n        # Check constraints\n        for constraint in contract.constraints:\n            constraint_violation = self._check_constraint(constraint, body)\n            if constraint_violation:\n                violations.append(constraint_violation)\n\n        return violations\n\n    def _check_type(\n        self, field_name: str, value: Any, schema: dict\n    ) -> Optional[ContractViolation]:\n        \"\"\"Check that a field value matches the expected type.\"\"\"\n        expected_type = schema.get(\"type\")\n        if expected_type is None:\n            return None\n\n        type_map = {\n            \"string\": str,\n            \"integer\": int,\n            \"number\": (int, float),\n            \"boolean\": bool,\n            \"array\": list,\n            \"object\": dict,\n        }\n\n        expected_python_type = type_map.get(expected_type)\n        if expected_python_type and not isinstance(value, expected_python_type):\n            return ContractViolation(\n                field=field_name,\n                expected=expected_type,\n                actual=type(value).__name__,\n                severity=Severity.ERROR,\n                message=(\n                    f\"Field '{field_name}': expected type '{expected_type}', \"\n                    f\"got '{type(value).__name__}'\"\n                ),\n            )\n\n        # Check enum constraint\n        if \"enum\" in schema and value not in schema[\"enum\"]:\n            return ContractViolation(\n                field=field_name,\n                expected=str(schema[\"enum\"]),\n                actual=str(value),\n                severity=Severity.ERROR,\n                message=(\n                    f\"Field '{field_name}': value '{value}' not in \"\n                    f\"allowed values {schema['enum']}\"\n                ),\n            )\n\n        # Check pattern constraint\n        if \"pattern\" in schema and isinstance(value, str):\n            if not re.match(schema[\"pattern\"], value):\n                return ContractViolation(\n                    field=field_name,\n                    expected=f\"pattern: {schema['pattern']}\",\n                    actual=value,\n                    severity=Severity.WARNING,\n                    message=(\n                        f\"Field '{field_name}': value '{value}' does not \"\n                        f\"match pattern '{schema['pattern']}'\"\n                    ),\n                )\n\n        return None\n\n    def _check_constraint(\n        self, constraint: dict, body: dict\n    ) -> Optional[ContractViolation]:\n        \"\"\"Check a custom constraint against the response body.\"\"\"\n        constraint_type = constraint.get(\"type\")\n\n        if constraint_type == \"field_equals\":\n            field_name = constraint[\"field\"]\n            expected = constraint[\"value\"]\n            actual = body.get(field_name)\n            if actual != expected:\n                return ContractViolation(\n                    field=field_name,\n                    expected=str(expected),\n                    actual=str(actual),\n                    severity=Severity(constraint.get(\"severity\", \"error\")),\n                    message=constraint.get(\"message\", f\"{field_name} != {expected}\"),\n                )\n\n        elif constraint_type == \"field_present_if\":\n            condition_field = constraint[\"condition_field\"]\n            condition_value = constraint[\"condition_value\"]\n            required_field = constraint[\"required_field\"]\n            if body.get(condition_field) == condition_value:\n                if required_field not in body:\n                    return ContractViolation(\n                        field=required_field,\n                        expected=f\"present when {condition_field}={condition_value}\",\n                        actual=\"missing\",\n                        severity=Severity.ERROR,\n                        message=(\n                            f\"Field '{required_field}' required when \"\n                            f\"'{condition_field}' is '{condition_value}'\"\n                        ),\n                    )\n\n        return None\n\n    def check_backward_compatibility(\n        self, old_contract: ToolContract, new_contract: ToolContract\n    ) -> list[ContractViolation]:\n        \"\"\"\n        Check that a new version of a tool contract is\n        backward-compatible with the old version.\n        \"\"\"\n        violations = []\n\n        # Removing a required output field is a breaking change\n        old_required = set(old_contract.required_output_fields)\n        new_required = set(new_contract.required_output_fields)\n        removed_fields = old_required - new_required\n        for field_name in removed_fields:\n            if field_name not in new_contract.optional_output_fields:\n                violations.append(ContractViolation(\n                    field=field_name,\n                    expected=\"present (was required)\",\n                    actual=\"removed\",\n                    severity=Severity.ERROR,\n                    message=(\n                        f\"Breaking change: required field '{field_name}' \"\n                        f\"removed from '{new_contract.tool_name}' \"\n                        f\"(v{old_contract.version} -> v{new_contract.version})\"\n                    ),\n                ))\n\n        # Changing a field type is a breaking change\n        for field_name in old_contract.output_schema:\n            if field_name not in new_contract.output_schema:\n                continue\n            old_type = old_contract.output_schema[field_name].get(\"type\")\n            new_type = new_contract.output_schema[field_name].get(\"type\")\n            if old_type and new_type and old_type != new_type:\n                violations.append(ContractViolation(\n                    field=field_name,\n                    expected=f\"type: {old_type}\",\n                    actual=f\"type: {new_type}\",\n                    severity=Severity.ERROR,\n                    message=(\n                        f\"Breaking change: field '{field_name}' type changed \"\n                        f\"from '{old_type}' to '{new_type}'\"\n                    ),\n                ))\n\n        # Narrowing an enum is a breaking change\n        for field_name in old_contract.output_schema:\n            if field_name not in new_contract.output_schema:\n                continue\n            old_enum = set(old_contract.output_schema[field_name].get(\"enum\", []))\n            new_enum = set(new_contract.output_schema[field_name].get(\"enum\", []))\n            if old_enum and new_enum:\n                removed_values = old_enum - new_enum\n                if removed_values:\n                    violations.append(ContractViolation(\n                        field=field_name,\n                        expected=f\"enum includes {removed_values}\",\n                        actual=f\"enum: {new_enum}\",\n                        severity=Severity.ERROR,\n                        message=(\n                            f\"Breaking change: enum values {removed_values} \"\n                            f\"removed from '{field_name}'\"\n                        ),\n                    ))\n\n        # Adding new required input fields is a breaking change\n        old_required_inputs = set(old_contract.input_schema.get(\"required\", []))\n        new_required_inputs = set(new_contract.input_schema.get(\"required\", []))\n        added_required = new_required_inputs - old_required_inputs\n        for field_name in added_required:\n            violations.append(ContractViolation(\n                field=field_name,\n                expected=\"optional or absent\",\n                actual=\"required\",\n                severity=Severity.ERROR,\n                message=(\n                    f\"Breaking change: new required input field \"\n                    f\"'{field_name}' added to '{new_contract.tool_name}'\"\n                ),\n            ))\n\n        return violations\n\n    def report(self) -> dict:\n        \"\"\"Generate a validation report.\"\"\"\n        errors = [v for v in self._violations if v.severity == Severity.ERROR]\n        warnings = [v for v in self._violations if v.severity == Severity.WARNING]\n        return {\n            \"total_validations\": self._validations,\n            \"total_violations\": len(self._violations),\n            \"errors\": len(errors),\n            \"warnings\": len(warnings),\n            \"passed\": len(errors) == 0,\n            \"violations\": [\n                {\n                    \"field\": v.field,\n                    \"expected\": v.expected,\n                    \"actual\": v.actual,\n                    \"severity\": v.severity.value,\n                    \"message\": v.message,\n                }\n                for v in self._violations\n            ],\n        }\n```\n\n### Defining Consumer-Driven Contracts\n\nEach agent that consumes a tool declares what it expects. Store these as JSON files in a `contracts\u002F` directory:\n\n```json\n{\n  \"consumer\": \"buyer-agent-v2\",\n  \"producer\": \"gateway\",\n  \"metadata\": {\n    \"created\": \"2026-04-01\",\n    \"owner\": \"team-payments\"\n  },\n  \"tools\": [\n    {\n      \"tool_name\": \"create_escrow\",\n      \"version\": \"1.0\",\n      \"input_schema\": {\n        \"required\": [\"payer\", \"payee\", \"amount\", \"currency\"],\n        \"properties\": {\n          \"payer\": {\"type\": \"string\"},\n          \"payee\": {\"type\": \"string\"},\n          \"amount\": {\"type\": \"string\", \"pattern\": \"^\\\\d+\\\\.\\\\d{2}$\"},\n          \"currency\": {\"type\": \"string\", \"enum\": [\"USD\"]}\n        }\n      },\n      \"output_schema\": {\n        \"escrow_id\": {\"type\": \"string\", \"pattern\": \"^esc_\"},\n        \"status\": {\"type\": \"string\", \"enum\": [\"pending\", \"released\", \"cancelled\", \"expired\"]},\n        \"amount\": {\"type\": \"string\"},\n        \"currency\": {\"type\": \"string\"}\n      },\n      \"required_output_fields\": [\"escrow_id\", \"status\", \"amount\"],\n      \"status_codes\": [200],\n      \"constraints\": [\n        {\n          \"type\": \"field_equals\",\n          \"field\": \"status\",\n          \"value\": \"pending\",\n          \"severity\": \"error\",\n          \"message\": \"New escrows must have status 'pending'\"\n        }\n      ]\n    }\n  ]\n}\n```\n\n### Using Contracts in Tests\n\n```python\ndef test_escrow_contract_compliance(harness):\n    \"\"\"Verify gateway responses satisfy our contract.\"\"\"\n    validator = ContractValidator(contracts_dir=\"contracts\")\n    validator.load_contracts()\n\n    harness.start_cassette(\"contract_escrow\")\n\n    result = harness.execute(\"create_escrow\", {\n        \"payer\": \"test-buyer\",\n        \"payee\": \"test-seller\",\n        \"amount\": \"50.00\",\n        \"currency\": \"USD\",\n        \"conditions\": {\"delivery_by\": \"2026-12-31T00:00:00Z\"},\n    })\n\n    violations = validator.validate_response(\"create_escrow\", result)\n    harness.stop_cassette()\n\n    report = validator.report()\n    assert report[\"passed\"], (\n        f\"Contract violations: {json.dumps(report['violations'], indent=2)}\"\n    )\n\n\ndef test_backward_compatibility():\n    \"\"\"Verify a new contract version is backward-compatible.\"\"\"\n    validator = ContractValidator()\n\n    old_contract = ToolContract(\n        tool_name=\"create_escrow\",\n        version=\"1.0\",\n        input_schema={\"required\": [\"payer\", \"payee\", \"amount\"]},\n        output_schema={\n            \"status\": {\"type\": \"string\", \"enum\": [\"pending\", \"released\", \"cancelled\"]},\n        },\n        required_output_fields=[\"escrow_id\", \"status\", \"amount\"],\n    )\n\n    new_contract = ToolContract(\n        tool_name=\"create_escrow\",\n        version=\"1.1\",\n        input_schema={\"required\": [\"payer\", \"payee\", \"amount\"]},\n        output_schema={\n            \"status\": {\n                \"type\": \"string\",\n                \"enum\": [\"pending\", \"released\", \"cancelled\", \"expired\"],\n            },\n        },\n        required_output_fields=[\"escrow_id\", \"status\", \"amount\", \"created_at\"],\n    )\n\n    violations = validator.check_backward_compatibility(old_contract, new_contract)\n    # Adding \"expired\" to the enum is fine (widening)\n    # Adding \"created_at\" as required output is fine (more data)\n    assert len(violations) == 0\n```\n\n---\n\n## Chapter 6: Performance Benchmarking\n\n### Why Agent Performance Benchmarks Are Different\n\nTraditional API benchmarks measure latency and throughput for a single endpoint. Agent commerce benchmarks must measure multi-step workflows: discover a service, negotiate terms, create escrow, deliver, release, submit metrics. The total latency is the sum of individual call latencies plus your agent's processing time between calls. A 10% regression in escrow creation latency might be invisible in isolation but pushes your end-to-end workflow past the SLA when compounded with five other calls.\n\n### The AgentBenchmark Class\n\n```python\nimport statistics\nimport time\nimport tracemalloc\nimport logging\nfrom dataclasses import dataclass, field\nfrom typing import Any, Callable, Optional\n\n\nlogger = logging.getLogger(__name__)\n\n\n@dataclass\nclass BenchmarkResult:\n    \"\"\"Results from a single benchmark run.\"\"\"\n    name: str\n    iterations: int\n    total_time_ms: float\n    mean_ms: float\n    median_ms: float\n    p95_ms: float\n    p99_ms: float\n    min_ms: float\n    max_ms: float\n    std_dev_ms: float\n    throughput_ops_sec: float\n    errors: int\n    peak_memory_mb: float\n    latencies: list[float] = field(default_factory=list)\n\n\nclass AgentBenchmark:\n    \"\"\"\n    Performance benchmarking for agent commerce operations.\n    Measures latency, throughput, memory, and connection usage.\n    \"\"\"\n\n    def __init__(self, client: Any, warmup_iterations: int = 5):\n        self._client = client\n        self._warmup_iterations = warmup_iterations\n        self._results: list[BenchmarkResult] = []\n\n    def benchmark_tool(\n        self,\n        name: str,\n        tool: str,\n        input_data: dict,\n        iterations: int = 100,\n    ) -> BenchmarkResult:\n        \"\"\"Benchmark a single tool call.\"\"\"\n\n        # Warmup: discard first N iterations\n        for _ in range(self._warmup_iterations):\n            try:\n                self._client.execute(tool, input_data)\n            except Exception:\n                pass\n\n        latencies = []\n        errors = 0\n        tracemalloc.start()\n\n        start_total = time.monotonic()\n        for _ in range(iterations):\n            start = time.monotonic()\n            try:\n                self._client.execute(tool, input_data)\n            except Exception:\n                errors += 1\n            elapsed = (time.monotonic() - start) * 1000\n            latencies.append(elapsed)\n\n        total_time = (time.monotonic() - start_total) * 1000\n        _, peak_memory = tracemalloc.get_traced_memory()\n        tracemalloc.stop()\n\n        sorted_latencies = sorted(latencies)\n        result = BenchmarkResult(\n            name=name,\n            iterations=iterations,\n            total_time_ms=total_time,\n            mean_ms=statistics.mean(latencies),\n            median_ms=statistics.median(latencies),\n            p95_ms=sorted_latencies[int(len(sorted_latencies) * 0.95)],\n            p99_ms=sorted_latencies[int(len(sorted_latencies) * 0.99)],\n            min_ms=min(latencies),\n            max_ms=max(latencies),\n            std_dev_ms=statistics.stdev(latencies) if len(latencies) > 1 else 0,\n            throughput_ops_sec=(iterations \u002F total_time) * 1000 if total_time > 0 else 0,\n            errors=errors,\n            peak_memory_mb=peak_memory \u002F (1024 * 1024),\n            latencies=latencies,\n        )\n\n        self._results.append(result)\n        return result\n\n    def benchmark_workflow(\n        self,\n        name: str,\n        workflow: Callable[[], None],\n        iterations: int = 50,\n    ) -> BenchmarkResult:\n        \"\"\"Benchmark a multi-step workflow.\"\"\"\n        for _ in range(self._warmup_iterations):\n            try:\n                workflow()\n            except Exception:\n                pass\n\n        latencies = []\n        errors = 0\n        tracemalloc.start()\n\n        start_total = time.monotonic()\n        for _ in range(iterations):\n            start = time.monotonic()\n            try:\n                workflow()\n            except Exception:\n                errors += 1\n            elapsed = (time.monotonic() - start) * 1000\n            latencies.append(elapsed)\n\n        total_time = (time.monotonic() - start_total) * 1000\n        _, peak_memory = tracemalloc.get_traced_memory()\n        tracemalloc.stop()\n\n        sorted_latencies = sorted(latencies)\n        result = BenchmarkResult(\n            name=name,\n            iterations=iterations,\n            total_time_ms=total_time,\n            mean_ms=statistics.mean(latencies),\n            median_ms=statistics.median(latencies),\n            p95_ms=sorted_latencies[int(len(sorted_latencies) * 0.95)],\n            p99_ms=sorted_latencies[int(len(sorted_latencies) * 0.99)],\n            min_ms=min(latencies),\n            max_ms=max(latencies),\n            std_dev_ms=statistics.stdev(latencies) if len(latencies) > 1 else 0,\n            throughput_ops_sec=(iterations \u002F total_time) * 1000 if total_time > 0 else 0,\n            errors=errors,\n            peak_memory_mb=peak_memory \u002F (1024 * 1024),\n            latencies=latencies,\n        )\n\n        self._results.append(result)\n        return result\n\n    def compare(\n        self, baseline: BenchmarkResult, current: BenchmarkResult, threshold_pct: float = 10.0\n    ) -> dict:\n        \"\"\"Compare two benchmark results and flag regressions.\"\"\"\n        regression_fields = {}\n\n        for metric in [\"mean_ms\", \"median_ms\", \"p95_ms\", \"p99_ms\"]:\n            baseline_val = getattr(baseline, metric)\n            current_val = getattr(current, metric)\n            if baseline_val == 0:\n                continue\n            pct_change = ((current_val - baseline_val) \u002F baseline_val) * 100\n            regression_fields[metric] = {\n                \"baseline\": round(baseline_val, 2),\n                \"current\": round(current_val, 2),\n                \"change_pct\": round(pct_change, 2),\n                \"regression\": pct_change > threshold_pct,\n            }\n\n        throughput_change = 0\n        if baseline.throughput_ops_sec > 0:\n            throughput_change = (\n                (current.throughput_ops_sec - baseline.throughput_ops_sec)\n                \u002F baseline.throughput_ops_sec\n            ) * 100\n\n        any_regression = any(v[\"regression\"] for v in regression_fields.values())\n\n        return {\n            \"baseline_name\": baseline.name,\n            \"current_name\": current.name,\n            \"metrics\": regression_fields,\n            \"throughput_change_pct\": round(throughput_change, 2),\n            \"has_regression\": any_regression,\n            \"threshold_pct\": threshold_pct,\n        }\n\n    def generate_report(self) -> str:\n        \"\"\"Generate a markdown benchmark report.\"\"\"\n        lines = [\"# Agent Benchmark Report\", \"\"]\n        lines.append(f\"Generated: {time.strftime('%Y-%m-%d %H:%M:%S UTC', time.gmtime())}\")\n        lines.append(\"\")\n\n        lines.append(\"| Benchmark | Iterations | Mean (ms) | Median (ms) | P95 (ms) | P99 (ms) | Throughput (ops\u002Fs) | Errors | Memory (MB) |\")\n        lines.append(\"|---|---|---|---|---|---|---|---|---|\")\n\n        for r in self._results:\n            lines.append(\n                f\"| {r.name} | {r.iterations} | \"\n                f\"{r.mean_ms:.2f} | {r.median_ms:.2f} | \"\n                f\"{r.p95_ms:.2f} | {r.p99_ms:.2f} | \"\n                f\"{r.throughput_ops_sec:.1f} | {r.errors} | \"\n                f\"{r.peak_memory_mb:.2f} |\"\n            )\n\n        lines.append(\"\")\n        return \"\\n\".join(lines)\n```\n\n### Running Benchmarks and Catching Regressions\n\n```python\ndef test_escrow_performance_regression(harness):\n    \"\"\"Flag if escrow operations regress more than 10%.\"\"\"\n    bench = AgentBenchmark(harness, warmup_iterations=3)\n\n    # Benchmark individual operations\n    create_result = bench.benchmark_tool(\n        \"create_escrow\",\n        \"create_escrow\",\n        {\n            \"payer\": \"test-agent-a\",\n            \"payee\": \"test-agent-b\",\n            \"amount\": \"10.00\",\n            \"currency\": \"USD\",\n        },\n        iterations=50,\n    )\n\n    balance_result = bench.benchmark_tool(\n        \"get_balance\",\n        \"get_balance\",\n        {\"agent_id\": \"test-agent-a\"},\n        iterations=100,\n    )\n\n    # Benchmark full workflow\n    def escrow_workflow():\n        harness.execute(\"create_escrow\", {\n            \"payer\": \"test-agent-a\",\n            \"payee\": \"test-agent-b\",\n            \"amount\": \"1.00\",\n            \"currency\": \"USD\",\n        })\n        harness.execute(\"get_balance\", {\"agent_id\": \"test-agent-a\"})\n\n    workflow_result = bench.benchmark_workflow(\"escrow_workflow\", escrow_workflow, iterations=30)\n\n    # Generate report\n    report = bench.generate_report()\n    logger.info(\"\\n%s\", report)\n\n    # Assert no individual operation exceeds 500ms at P99\n    assert create_result.p99_ms \u003C 500, f\"create_escrow P99: {create_result.p99_ms}ms\"\n    assert balance_result.p99_ms \u003C 200, f\"get_balance P99: {balance_result.p99_ms}ms\"\n\n    # Save results for next run's comparison\n    Path(\"benchmarks\u002Flatest.json\").parent.mkdir(exist_ok=True)\n    Path(\"benchmarks\u002Flatest.json\").write_text(json.dumps({\n        \"create_escrow\": {\"mean_ms\": create_result.mean_ms, \"p99_ms\": create_result.p99_ms},\n        \"get_balance\": {\"mean_ms\": balance_result.mean_ms, \"p99_ms\": balance_result.p99_ms},\n        \"workflow\": {\"mean_ms\": workflow_result.mean_ms, \"p99_ms\": workflow_result.p99_ms},\n    }, indent=2))\n```\n\nStore benchmark baselines in your repository. On each run, load the previous baseline, compare against current results, and fail the build if any metric regresses beyond your threshold. This turns performance into a first-class CI constraint rather than something you notice three weeks later when users complain.\n\n---\n\n## Chapter 7: CI\u002FCD for Agent Deployments\n\n### Pipeline Architecture\n\nAn agent commerce CI\u002FCD pipeline has five stages. Each stage gates the next -- if any stage fails, the pipeline stops and the deploy does not happen.\n\n```\n  lint → unit → integration → chaos → deploy\n   │       │         │          │        │\n  10s     30s      2min       5min     3min\n```\n\nThe total pipeline takes about 10 minutes. This is slower than a typical web application pipeline because the chaos stage runs real failure simulations. The tradeoff is worth it: catching a retry-storm bug in CI is cheaper than catching it when it drains a production wallet.\n\n### GitHub Actions Configuration\n\n```yaml\nname: Agent Commerce CI\u002FCD\n\non:\n  push:\n    branches: [main]\n  pull_request:\n    branches: [main]\n\nenv:\n  PYTHON_VERSION: \"3.12\"\n  GREENHELIX_SANDBOX_KEY: ${{ secrets.GREENHELIX_SANDBOX_KEY }}\n\njobs:\n  lint:\n    runs-on: ubuntu-latest\n    timeout-minutes: 5\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: actions\u002Fsetup-python@v5\n        with:\n          python-version: ${{ env.PYTHON_VERSION }}\n      - run: pip install ruff mypy\n      - run: ruff check src\u002F tests\u002F\n      - run: mypy src\u002F --ignore-missing-imports\n\n  unit:\n    runs-on: ubuntu-latest\n    timeout-minutes: 5\n    needs: lint\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: actions\u002Fsetup-python@v5\n        with:\n          python-version: ${{ env.PYTHON_VERSION }}\n      - run: pip install -r requirements.txt -r requirements-test.txt\n      - run: python -m pytest tests\u002Funit\u002F -x -q --tb=short\n        env:\n          TEST_MODE: playback\n\n  integration:\n    runs-on: ubuntu-latest\n    timeout-minutes: 10\n    needs: unit\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: actions\u002Fsetup-python@v5\n        with:\n          python-version: ${{ env.PYTHON_VERSION }}\n      - run: pip install -r requirements.txt -r requirements-test.txt\n      - run: python -m pytest tests\u002Fintegration\u002F -x -q --tb=short\n        env:\n          TEST_MODE: playback\n          GREENHELIX_API_KEY: ${{ env.GREENHELIX_SANDBOX_KEY }}\n\n  chaos:\n    runs-on: ubuntu-latest\n    timeout-minutes: 15\n    needs: integration\n    if: github.ref == 'refs\u002Fheads\u002Fmain'\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: actions\u002Fsetup-python@v5\n        with:\n          python-version: ${{ env.PYTHON_VERSION }}\n      - run: pip install -r requirements.txt -r requirements-test.txt\n      - run: python -m pytest tests\u002F -m chaos -x -q --tb=short\n        env:\n          CHAOS_SEED: ${{ github.run_number }}\n          TEST_MODE: playback\n\n  deploy:\n    runs-on: ubuntu-latest\n    timeout-minutes: 10\n    needs: [integration, chaos]\n    if: github.ref == 'refs\u002Fheads\u002Fmain'\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: actions\u002Fsetup-python@v5\n        with:\n          python-version: ${{ env.PYTHON_VERSION }}\n      - name: Deploy to staging\n        run: |\n          pip install -r requirements.txt\n          python deploy.py --env staging --agent-id ${{ vars.AGENT_ID }}\n        env:\n          GREENHELIX_API_KEY: ${{ secrets.GREENHELIX_STAGING_KEY }}\n\n      - name: Smoke test staging\n        run: |\n          python -m pytest tests\u002Fsmoke\u002F -x -q --tb=short\n        env:\n          GREENHELIX_API_KEY: ${{ secrets.GREENHELIX_STAGING_KEY }}\n          TARGET_ENV: staging\n\n      - name: Deploy to production\n        run: |\n          python deploy.py --env production --agent-id ${{ vars.AGENT_ID }}\n        env:\n          GREENHELIX_API_KEY: ${{ secrets.GREENHELIX_PROD_KEY }}\n```\n\n### Environment Key Management\n\nSeparate your GreenHelix API keys by environment. Never use the same key for sandbox, staging, and production. The key hierarchy:\n\n| Environment | Key Source | Wallet | Purpose |\n|---|---|---|---|\n| Local dev | `.env` file (gitignored) | Test wallet, fake funds | Developer iteration |\n| CI sandbox | GitHub secret `GREENHELIX_SANDBOX_KEY` | Sandbox wallet, free credits | Automated testing |\n| Staging | GitHub secret `GREENHELIX_STAGING_KEY` | Staging wallet, real funds (capped) | Pre-production validation |\n| Production | GitHub secret `GREENHELIX_PROD_KEY` | Production wallet, real funds | Live traffic |\n\nSet budget caps on every non-production key using the GreenHelix `set_budget_cap` tool. A runaway integration test should not be able to spend more than $5:\n\n```python\ndef configure_test_budget(api_key: str, agent_id: str) -> None:\n    \"\"\"Set conservative budget caps for test environments.\"\"\"\n    import requests\n    resp = requests.post(\n        \"https:\u002F\u002Fsandbox.greenhelix.netthe REST API\",\n        headers={\n            \"Authorization\": f\"Bearer {api_key}\",\n            \"Content-Type\": \"application\u002Fjson\",\n        },\n        json={\n            \"tool\": \"set_budget_cap\",\n            \"input\": {\n                \"agent_id\": agent_id,\n                \"daily_limit\": \"5.00\",\n                \"monthly_limit\": \"50.00\",\n                \"per_transaction_limit\": \"1.00\",\n                \"currency\": \"USD\",\n            },\n        },\n    )\n    resp.raise_for_status()\n```\n\n### Rollback Triggers\n\nDefine explicit rollback criteria. If any of these conditions are true after a deploy, automatically roll back:\n\n```python\nimport requests\nimport sys\n\n\ndef check_rollback_criteria(\n    api_key: str,\n    agent_id: str,\n    base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n) -> bool:\n    \"\"\"Return True if a rollback is needed.\"\"\"\n    session = requests.Session()\n    session.headers.update({\n        \"Authorization\": f\"Bearer {api_key}\",\n        \"Content-Type\": \"application\u002Fjson\",\n    })\n\n    def execute(tool: str, input_data: dict) -> dict:\n        resp = session.post(\n            f\"{base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        return resp.json() if resp.status_code == 200 else {\"error\": resp.status_code}\n\n    # Check 1: Agent is reachable and registered\n    identity = execute(\"get_agent_identity\", {\"agent_id\": agent_id})\n    if \"error\" in identity:\n        print(f\"ROLLBACK: Agent identity check failed: {identity}\")\n        return True\n\n    # Check 2: Trust score hasn't dropped\n    trust = execute(\"get_trust_score\", {\"agent_id\": agent_id})\n    if trust.get(\"score\", 0) \u003C 0.5:\n        print(f\"ROLLBACK: Trust score below threshold: {trust.get('score')}\")\n        return True\n\n    # Check 3: No unusual error rate in recent metrics\n    metrics = execute(\"get_agent_metrics\", {\"agent_id\": agent_id, \"window\": \"5m\"})\n    error_rate = metrics.get(\"error_rate\", 0)\n    if error_rate > 0.05:  # More than 5% errors\n        print(f\"ROLLBACK: Error rate too high: {error_rate}\")\n        return True\n\n    # Check 4: Balance is not draining unexpectedly\n    balance = execute(\"get_balance\", {\"agent_id\": agent_id})\n    balance_val = float(balance.get(\"balance\", \"0\"))\n    if balance_val \u003C 10.0:  # Minimum operating balance\n        print(f\"ROLLBACK: Balance critically low: {balance_val}\")\n        return True\n\n    print(\"All rollback checks passed\")\n    return False\n\n\nif __name__ == \"__main__\":\n    import os\n    should_rollback = check_rollback_criteria(\n        api_key=os.environ[\"GREENHELIX_API_KEY\"],\n        agent_id=os.environ[\"AGENT_ID\"],\n    )\n    sys.exit(1 if should_rollback else 0)\n```\n\nCall this script as a post-deploy step. If it exits with code 1, your pipeline triggers a rollback to the previous version.\n\n---\n\n## Chapter 8: Canary Releases\n\n### The Case for Canary Deployments\n\nA canary release deploys a new agent version to a small percentage of traffic before rolling it out fully. This is standard practice for web services, but agent commerce adds a complication: agents are stateful. A canary agent that creates an escrow must be able to see that escrow through to completion, even if it is rolled back. This means your canary strategy must handle in-flight transactions gracefully.\n\n### Canary Deployment Architecture\n\nThe canary pattern for GreenHelix agents uses two agent registrations with a traffic router:\n\n```\n                    ┌──────────────┐\n                    │  Traffic     │\n    Incoming ──────▶│  Router      │\n    Requests        │  (5%\u002F95%)    │\n                    └──────┬───────┘\n                           │\n                    ┌──────┴───────┐\n                    │              │\n               ┌────▼────┐  ┌─────▼─────┐\n               │ Canary  │  │ Stable    │\n               │ v2.1.0  │  │ v2.0.0   │\n               │  (5%)   │  │  (95%)   │\n               └─────────┘  └──────────┘\n```\n\nBoth versions share the same GreenHelix wallet but use different agent IDs (e.g., `my-agent` and `my-agent-canary`). This lets you track metrics separately while maintaining a single financial identity.\n\n### The CanaryController Class\n\n```python\nimport time\nimport logging\nimport threading\nfrom dataclasses import dataclass, field\nfrom typing import Any, Callable, Optional\n\n\nlogger = logging.getLogger(__name__)\n\n\n@dataclass\nclass CanaryMetrics:\n    \"\"\"Metrics collected during a canary deployment.\"\"\"\n    requests_total: int = 0\n    requests_success: int = 0\n    requests_error: int = 0\n    latency_sum_ms: float = 0\n    latency_samples: list[float] = field(default_factory=list)\n    start_time: float = field(default_factory=time.time)\n\n    @property\n    def error_rate(self) -> float:\n        if self.requests_total == 0:\n            return 0.0\n        return self.requests_error \u002F self.requests_total\n\n    @property\n    def mean_latency_ms(self) -> float:\n        if not self.latency_samples:\n            return 0.0\n        return self.latency_sum_ms \u002F len(self.latency_samples)\n\n    @property\n    def uptime_seconds(self) -> float:\n        return time.time() - self.start_time\n\n\n@dataclass\nclass CanaryConfig:\n    \"\"\"Configuration for a canary deployment.\"\"\"\n    stable_agent_id: str\n    canary_agent_id: str\n    initial_weight_pct: float = 5.0\n    promotion_steps: list[float] = field(\n        default_factory=lambda: [5.0, 25.0, 50.0, 100.0]\n    )\n    step_duration_seconds: float = 300  # 5 minutes per step\n    error_rate_threshold: float = 0.05  # 5% error rate triggers rollback\n    latency_threshold_ms: float = 1000  # P95 latency threshold\n    min_requests_before_eval: int = 20  # Minimum sample size\n\n\nclass CanaryController:\n    \"\"\"\n    Manages canary deployments for GreenHelix agents.\n    Routes traffic, monitors health, and auto-promotes or rolls back.\n    \"\"\"\n\n    def __init__(\n        self,\n        config: CanaryConfig,\n        stable_client: Any,\n        canary_client: Any,\n        metrics_client: Optional[Any] = None,\n    ):\n        self.config = config\n        self._stable = stable_client\n        self._canary = canary_client\n        self._metrics_client = metrics_client\n\n        self._current_weight: float = 0.0\n        self._current_step: int = 0\n        self._stable_metrics = CanaryMetrics()\n        self._canary_metrics = CanaryMetrics()\n        self._state: str = \"idle\"  # idle, running, promoted, rolled_back\n        self._lock = threading.Lock()\n        self._rollback_reason: Optional[str] = None\n\n    def start(self) -> None:\n        \"\"\"Begin the canary deployment.\"\"\"\n        self._state = \"running\"\n        self._current_weight = self.config.initial_weight_pct\n        self._current_step = 0\n        self._stable_metrics = CanaryMetrics()\n        self._canary_metrics = CanaryMetrics()\n        logger.info(\n            \"Canary started: %s at %.1f%% traffic\",\n            self.config.canary_agent_id,\n            self._current_weight,\n        )\n\n    def route_request(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Route a request to either stable or canary based on weight.\"\"\"\n        import random\n\n        if self._state != \"running\":\n            return self._stable.execute(tool, input_data)\n\n        use_canary = random.random() * 100 \u003C self._current_weight\n        client = self._canary if use_canary else self._stable\n        metrics = self._canary_metrics if use_canary else self._stable_metrics\n\n        start = time.monotonic()\n        try:\n            result = client.execute(tool, input_data)\n            elapsed_ms = (time.monotonic() - start) * 1000\n\n            with self._lock:\n                metrics.requests_total += 1\n                metrics.latency_sum_ms += elapsed_ms\n                metrics.latency_samples.append(elapsed_ms)\n\n                status = result.get(\"status_code\", 0)\n                if 200 \u003C= status \u003C 400:\n                    metrics.requests_success += 1\n                else:\n                    metrics.requests_error += 1\n\n            return result\n\n        except Exception as exc:\n            with self._lock:\n                metrics.requests_total += 1\n                metrics.requests_error += 1\n            raise\n\n    def evaluate(self) -> dict:\n        \"\"\"\n        Evaluate canary health. Returns action: 'promote', 'hold', or 'rollback'.\n        \"\"\"\n        with self._lock:\n            canary = self._canary_metrics\n            stable = self._stable_metrics\n\n        if canary.requests_total \u003C self.config.min_requests_before_eval:\n            return {\n                \"action\": \"hold\",\n                \"reason\": (\n                    f\"Insufficient canary samples: \"\n                    f\"{canary.requests_total}\u002F{self.config.min_requests_before_eval}\"\n                ),\n                \"canary_metrics\": self._metrics_snapshot(canary),\n                \"stable_metrics\": self._metrics_snapshot(stable),\n            }\n\n        # Check error rate\n        if canary.error_rate > self.config.error_rate_threshold:\n            error_detail = (\n                f\"Canary error rate {canary.error_rate:.2%} exceeds \"\n                f\"threshold {self.config.error_rate_threshold:.2%}\"\n            )\n            return {\n                \"action\": \"rollback\",\n                \"reason\": error_detail,\n                \"canary_metrics\": self._metrics_snapshot(canary),\n                \"stable_metrics\": self._metrics_snapshot(stable),\n            }\n\n        # Check latency\n        if canary.latency_samples:\n            sorted_latencies = sorted(canary.latency_samples)\n            p95_idx = int(len(sorted_latencies) * 0.95)\n            p95 = sorted_latencies[p95_idx] if p95_idx \u003C len(sorted_latencies) else 0\n\n            if p95 > self.config.latency_threshold_ms:\n                latency_detail = (\n                    f\"Canary P95 latency {p95:.0f}ms exceeds \"\n                    f\"threshold {self.config.latency_threshold_ms:.0f}ms\"\n                )\n                return {\n                    \"action\": \"rollback\",\n                    \"reason\": latency_detail,\n                    \"canary_metrics\": self._metrics_snapshot(canary),\n                    \"stable_metrics\": self._metrics_snapshot(stable),\n                }\n\n        # Compare error rates: canary should not be significantly worse\n        if (\n            stable.requests_total >= self.config.min_requests_before_eval\n            and canary.error_rate > stable.error_rate * 2\n            and canary.error_rate > 0.01\n        ):\n            compare_detail = (\n                f\"Canary error rate {canary.error_rate:.2%} is >2x \"\n                f\"stable error rate {stable.error_rate:.2%}\"\n            )\n            return {\n                \"action\": \"rollback\",\n                \"reason\": compare_detail,\n                \"canary_metrics\": self._metrics_snapshot(canary),\n                \"stable_metrics\": self._metrics_snapshot(stable),\n            }\n\n        # Check if enough time has passed for promotion\n        if canary.uptime_seconds >= self.config.step_duration_seconds:\n            return {\n                \"action\": \"promote\",\n                \"reason\": (\n                    f\"Canary healthy after {canary.uptime_seconds:.0f}s \"\n                    f\"at {self._current_weight:.0f}% traffic\"\n                ),\n                \"canary_metrics\": self._metrics_snapshot(canary),\n                \"stable_metrics\": self._metrics_snapshot(stable),\n            }\n\n        return {\n            \"action\": \"hold\",\n            \"reason\": \"Waiting for evaluation period to complete\",\n            \"canary_metrics\": self._metrics_snapshot(canary),\n            \"stable_metrics\": self._metrics_snapshot(stable),\n        }\n\n    def promote(self) -> bool:\n        \"\"\"Advance to the next traffic weight step. Returns True if fully promoted.\"\"\"\n        self._current_step += 1\n\n        if self._current_step >= len(self.config.promotion_steps):\n            self._state = \"promoted\"\n            self._current_weight = 100.0\n            logger.info(\"Canary fully promoted to 100%% traffic\")\n            return True\n\n        self._current_weight = self.config.promotion_steps[self._current_step]\n        # Reset metrics for the new step\n        with self._lock:\n            self._canary_metrics = CanaryMetrics()\n            self._stable_metrics = CanaryMetrics()\n\n        logger.info(\n            \"Canary promoted to %.1f%% traffic (step %d\u002F%d)\",\n            self._current_weight,\n            self._current_step + 1,\n            len(self.config.promotion_steps),\n        )\n        return False\n\n    def rollback(self, reason: str) -> None:\n        \"\"\"Roll back the canary deployment.\"\"\"\n        self._state = \"rolled_back\"\n        self._current_weight = 0.0\n        self._rollback_reason = reason\n        logger.warning(\"Canary rolled back: %s\", reason)\n\n    def run_deployment(self) -> dict:\n        \"\"\"\n        Run the full canary deployment lifecycle.\n        Returns the final state and metrics.\n        \"\"\"\n        self.start()\n\n        while self._state == \"running\":\n            time.sleep(10)  # Evaluate every 10 seconds\n            evaluation = self.evaluate()\n\n            if evaluation[\"action\"] == \"rollback\":\n                self.rollback(evaluation[\"reason\"])\n                break\n\n            elif evaluation[\"action\"] == \"promote\":\n                fully_promoted = self.promote()\n                if fully_promoted:\n                    break\n\n            # \"hold\" means keep waiting\n\n        return {\n            \"final_state\": self._state,\n            \"final_weight\": self._current_weight,\n            \"rollback_reason\": self._rollback_reason,\n            \"canary_metrics\": self._metrics_snapshot(self._canary_metrics),\n            \"stable_metrics\": self._metrics_snapshot(self._stable_metrics),\n        }\n\n    def _metrics_snapshot(self, metrics: CanaryMetrics) -> dict:\n        sorted_latencies = sorted(metrics.latency_samples) if metrics.latency_samples else []\n        p95_idx = int(len(sorted_latencies) * 0.95) if sorted_latencies else 0\n        return {\n            \"requests_total\": metrics.requests_total,\n            \"requests_success\": metrics.requests_success,\n            \"requests_error\": metrics.requests_error,\n            \"error_rate\": round(metrics.error_rate, 4),\n            \"mean_latency_ms\": round(metrics.mean_latency_ms, 2),\n            \"p95_latency_ms\": round(sorted_latencies[p95_idx], 2) if sorted_latencies else 0,\n            \"uptime_seconds\": round(metrics.uptime_seconds, 1),\n        }\n\n    @property\n    def state(self) -> str:\n        return self._state\n\n    @property\n    def current_weight(self) -> float:\n        return self._current_weight\n```\n\n### Using the CanaryController in Practice\n\n```python\ndef deploy_canary(stable_api_key: str, canary_api_key: str) -> dict:\n    \"\"\"Deploy a new agent version as a canary.\"\"\"\n    from my_agent import AgentClient\n\n    stable = AgentClient(api_key=stable_api_key, agent_id=\"my-agent\")\n    canary = AgentClient(api_key=canary_api_key, agent_id=\"my-agent-canary\")\n\n    config = CanaryConfig(\n        stable_agent_id=\"my-agent\",\n        canary_agent_id=\"my-agent-canary\",\n        initial_weight_pct=5.0,\n        promotion_steps=[5.0, 25.0, 50.0, 100.0],\n        step_duration_seconds=300,     # 5 minutes per step\n        error_rate_threshold=0.05,     # 5% errors trigger rollback\n        latency_threshold_ms=1000,     # 1 second P95 threshold\n        min_requests_before_eval=20,\n    )\n\n    controller = CanaryController(config, stable, canary)\n    result = controller.run_deployment()\n\n    if result[\"final_state\"] == \"rolled_back\":\n        print(f\"Canary FAILED: {result['rollback_reason']}\")\n        print(f\"Canary metrics: {result['canary_metrics']}\")\n        print(f\"Stable metrics: {result['stable_metrics']}\")\n    elif result[\"final_state\"] == \"promoted\":\n        print(\"Canary PROMOTED to 100% traffic\")\n        print(f\"Final canary metrics: {result['canary_metrics']}\")\n\n    return result\n```\n\n### Handling In-Flight Transactions During Rollback\n\nThe most important detail: when you roll back a canary, do not kill the canary agent immediately. In-flight escrows created by the canary must complete. The rollback stops routing new traffic to the canary, but the canary agent continues running until all its active escrows are settled:\n\n```python\ndef graceful_rollback(\n    controller: CanaryController,\n    canary_client: Any,\n    reason: str,\n    drain_timeout_seconds: int = 600,\n) -> None:\n    \"\"\"Roll back canary traffic while draining in-flight transactions.\"\"\"\n    # Stop new traffic immediately\n    controller.rollback(reason)\n\n    # Check for in-flight escrows\n    active_escrows = canary_client.execute(\"list_escrows\", {\n        \"agent_id\": controller.config.canary_agent_id,\n        \"status\": \"pending\",\n    })\n\n    pending = active_escrows.get(\"body\", {}).get(\"escrows\", [])\n    if not pending:\n        logger.info(\"No in-flight transactions, canary shutdown clean\")\n        return\n\n    logger.info(\n        \"Draining %d in-flight escrows before canary shutdown\", len(pending)\n    )\n\n    deadline = time.time() + drain_timeout_seconds\n    while time.time() \u003C deadline:\n        remaining = canary_client.execute(\"list_escrows\", {\n            \"agent_id\": controller.config.canary_agent_id,\n            \"status\": \"pending\",\n        })\n        pending_count = len(remaining.get(\"body\", {}).get(\"escrows\", []))\n        if pending_count == 0:\n            logger.info(\"All in-flight transactions drained\")\n            return\n        logger.info(\n            \"Waiting for %d in-flight transactions to complete...\",\n            pending_count,\n        )\n        time.sleep(30)\n\n    logger.warning(\n        \"Drain timeout reached with %d transactions still pending. \"\n        \"These will need manual resolution.\",\n        pending_count,\n    )\n```\n\n### Monitoring Canary Health via GreenHelix Metrics\n\nUse GreenHelix's built-in metrics to monitor canary health without building custom instrumentation. The `submit_metrics` and `get_agent_metrics` tools provide per-agent observability:\n\n```python\ndef monitor_canary_via_greenhelix(\n    api_key: str,\n    stable_agent_id: str,\n    canary_agent_id: str,\n) -> dict:\n    \"\"\"Compare canary and stable metrics using GreenHelix's metrics tools.\"\"\"\n    import requests\n\n    session = requests.Session()\n    session.headers.update({\n        \"Authorization\": f\"Bearer {api_key}\",\n        \"Content-Type\": \"application\u002Fjson\",\n    })\n    base_url = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n    def get_metrics(agent_id: str) -> dict:\n        resp = session.post(\n            f\"{base_url}\u002Fv1\",\n            json={\n                \"tool\": \"get_agent_metrics\",\n                \"input\": {\"agent_id\": agent_id, \"window\": \"5m\"},\n            },\n        )\n        return resp.json() if resp.status_code == 200 else {}\n\n    stable_metrics = get_metrics(stable_agent_id)\n    canary_metrics = get_metrics(canary_agent_id)\n\n    comparison = {\n        \"stable\": {\n            \"error_rate\": stable_metrics.get(\"error_rate\", 0),\n            \"mean_latency_ms\": stable_metrics.get(\"mean_latency_ms\", 0),\n            \"requests\": stable_metrics.get(\"request_count\", 0),\n        },\n        \"canary\": {\n            \"error_rate\": canary_metrics.get(\"error_rate\", 0),\n            \"mean_latency_ms\": canary_metrics.get(\"mean_latency_ms\", 0),\n            \"requests\": canary_metrics.get(\"request_count\", 0),\n        },\n    }\n\n    # Flag if canary is significantly worse\n    stable_err = comparison[\"stable\"][\"error_rate\"]\n    canary_err = comparison[\"canary\"][\"error_rate\"]\n    comparison[\"canary_healthy\"] = canary_err \u003C= max(stable_err * 2, 0.05)\n\n    return comparison\n```\n\n---\n\n## What's Next\n\nThis guide covered the complete testing and QA toolkit for agent commerce on GreenHelix: the testing pyramid adapted for multi-agent systems, the `AgentTestHarness` for recording and replaying API interactions, the `GreenHelixMock` for isolated unit testing with stateful escrow simulation, the `ChaosInjector` for validating resilience against real failure modes, the `ContractValidator` for catching breaking changes between agent versions, the `AgentBenchmark` for performance regression detection, CI\u002FCD pipeline configuration with proper environment isolation, and the `CanaryController` for progressive rollouts with automatic rollback.\n\nThe six classes -- `AgentTestHarness`, `GreenHelixMock`, `ChaosInjector`, `ContractValidator`, `AgentBenchmark`, and `CanaryController` -- compose into a testing stack that covers every layer from unit to production deployment. Start with the harness and mocks for your immediate test gaps, add chaos testing when you have basic coverage, and implement canary releases when you are deploying frequently enough that manual validation becomes a bottleneck.\n\nFor the agent commerce patterns these tests validate, see the companion guides:\n\n- **Agent-to-Agent Commerce: Escrow, Payments, and Trust** (P4) -- the escrow patterns, marketplace discovery, and payment flows that the test harness records and the contract validator checks.\n- **Locking Down Agent Commerce** (P7) -- the security hardening that chaos testing validates under failure conditions.\n- **The AI Agent FinOps Playbook** (P6) -- the budget caps and spending controls that prevent runaway test costs and protect canary deployments.\n- **Agent Observability Deep Dive** (P11) -- the monitoring infrastructure that feeds canary health evaluation and benchmark reporting.\n\nFor the full API reference and tool catalog (all 128 tools), visit the GreenHelix developer documentation at [https:\u002F\u002Fapi.greenhelix.net\u002Fdocs](https:\u002F\u002Fapi.greenhelix.net\u002Fdocs).\n\n---\n\n*Price: $39 | Format: Digital Guide | Updates: Lifetime access*\n\n","# Agent Testing & QA Toolkit: Integration, Chaos, and Contract Testing for Multi-Agent Systems\n\n> **Notice**: This is an educational guide with illustrative code examples.\n> It does not execute code or install dependencies.\n> All examples use the GreenHelix sandbox (https:\u002F\u002Fsandbox.greenhelix.net) which\n> provides 500 free credits — no API key required to get started.\n>\n> **Referenced credentials** (you supply these in your own environment):\n> - `GREENHELIX_API_KEY`: API authentication for GreenHelix gateway (read\u002Fwrite access to purchased API tools only)\n\n\nMost agent commerce tests are shallow mock-and-assert. Mock the HTTP call, assert the response shape, call it a day. This catches typos and regressions in your serialization layer, but it misses the failures that actually wake you up at 3 AM: network partitions during escrow settlement that leave funds locked indefinitely, race conditions when two agents simultaneously accept the same marketplace listing, schema drift between agent versions that silently corrupts payment metadata, and cascade failures when a single agent in a five-agent pipeline goes unresponsive and every upstream caller retries into a thundering herd. These are not edge cases. They are the normal operating conditions of a distributed multi-agent system under load. The problem is not that teams skip testing -- it is that they test the wrong layer. A unit test that mocks `create_escrow` and asserts it returns an escrow ID tells you nothing about what happens when the escrow creation succeeds but the confirmation webhook never arrives. This guide provides a comprehensive testing toolkit that goes beyond mocks: integration testing against real GreenHelix APIs with recording and playback, chaos testing that injects real failure modes into agent communication, contract testing that catches breaking changes before they hit production, and performance benchmarking that establishes baselines and catches regressions. Every class in this guide is designed to drop into your CI pipeline with zero modification.\n1. [The Testing Pyramid for Agent Systems](#chapter-1-the-testing-pyramid-for-agent-systems)\n2. [AgentTestHarness Class](#chapter-2-agenttestharness-class)\n\n## What You'll Learn\n- Chapter 1: The Testing Pyramid for Agent Systems\n- Chapter 2: AgentTestHarness Class\n- Chapter 3: Mock Strategies for Agent Commerce\n- Chapter 4: ChaosInjector Class\n- Chapter 5: ContractValidator Class\n- Chapter 6: Performance Benchmarking\n- Chapter 7: CI\u002FCD for Agent Deployments\n- Chapter 8: Canary Releases\n- What's Next\n\n## Full Guide\n\n# Agent Testing & QA Toolkit: Integration, Chaos, and Contract Testing for Multi-Agent Systems\n\nMost agent commerce tests are shallow mock-and-assert. Mock the HTTP call, assert the response shape, call it a day. This catches typos and regressions in your serialization layer, but it misses the failures that actually wake you up at 3 AM: network partitions during escrow settlement that leave funds locked indefinitely, race conditions when two agents simultaneously accept the same marketplace listing, schema drift between agent versions that silently corrupts payment metadata, and cascade failures when a single agent in a five-agent pipeline goes unresponsive and every upstream caller retries into a thundering herd. These are not edge cases. They are the normal operating conditions of a distributed multi-agent system under load. The problem is not that teams skip testing -- it is that they test the wrong layer. A unit test that mocks `create_escrow` and asserts it returns an escrow ID tells you nothing about what happens when the escrow creation succeeds but the confirmation webhook never arrives. This guide provides a comprehensive testing toolkit that goes beyond mocks: integration testing against real GreenHelix APIs with recording and playback, chaos testing that injects real failure modes into agent communication, contract testing that catches breaking changes before they hit production, and performance benchmarking that establishes baselines and catches regressions. Every class in this guide is designed to drop into your CI pipeline with zero modification.\n\n---\n\n## Table of Contents\n\n1. [The Testing Pyramid for Agent Systems](#chapter-1-the-testing-pyramid-for-agent-systems)\n2. [AgentTestHarness Class](#chapter-2-agenttestharness-class)\n3. [Mock Strategies for Agent Commerce](#chapter-3-mock-strategies-for-agent-commerce)\n4. [ChaosInjector Class](#chapter-4-chaosinjector-class)\n5. [ContractValidator Class](#chapter-5-contractvalidator-class)\n6. [Performance Benchmarking](#chapter-6-performance-benchmarking)\n7. [CI\u002FCD for Agent Deployments](#chapter-7-cicd-for-agent-deployments)\n8. [Canary Releases](#chapter-8-canary-releases)\n\n---\n\n## Chapter 1: The Testing Pyramid for Agent Systems\n\n### Why the Classic Pyramid Breaks for Agents\n\nThe classic testing pyramid -- wide base of unit tests, narrower band of integration tests, thin tip of end-to-end tests -- assumes a single deployable artifact with well-defined boundaries. Agent commerce systems break this assumption in three ways. First, your agent is one participant in a multi-party workflow. Unit testing your escrow creation logic tells you nothing about whether the counterparty agent will accept the escrow terms, release on time, or even be reachable. Second, the GreenHelix gateway is a stateful system: wallets accumulate balances, escrows transition through lifecycle states, trust scores evolve based on historical behavior. Mocking away that state means your tests operate in a universe that does not match production. Third, agent commerce involves real money. A bug in your retry logic that works fine in unit tests can drain a wallet in production if the idempotency key handling is wrong.\n\nThis does not mean unit tests are worthless. It means you need to be precise about what each layer catches and build your pyramid accordingly.\n\n### The Three Layers\n\n**Unit tests** validate your agent's internal logic in isolation: input validation, response parsing, state machine transitions, error classification, retry decisions, and business rules. They run in milliseconds, require no network access, and should cover every branch in your agent's decision-making code. What they miss: anything involving the actual GreenHelix API, inter-agent communication, or stateful workflows.\n\n**Integration tests** validate your agent's interaction with real GreenHelix tools, either against the sandbox API or via recorded responses. They catch serialization errors, unexpected response shapes, authentication failures, rate limit handling, and incorrect tool parameter construction. They run in seconds (against recordings) or minutes (against the live sandbox). What they miss: multi-agent coordination, failure modes, and performance characteristics.\n\n**End-to-end tests** validate complete multi-agent workflows: agent A discovers agent B on the marketplace, negotiates terms, creates an escrow, agent B delivers, agent A releases payment, both agents submit metrics. They catch integration failures between agents, workflow ordering bugs, and state synchronization issues. They run in minutes and require a full sandbox environment. What they miss: rare failure modes (which chaos testing covers) and performance under load (which benchmarking covers).\n\n### What Each Layer Catches\n\n| Failure Mode | Unit | Integration | E2E | Chaos |\n|---|---|---|---|---|\n| Input validation bug | Yes | -- | -- | -- |\n| Wrong tool parameter name | -- | Yes | Yes | -- |\n| Authentication misconfiguration | -- | Yes | Yes | -- |\n| Escrow lifecycle state error | Partial | Yes | Yes | -- |\n| Schema drift between versions | -- | -- | Yes | -- |\n| Network partition during payment | -- | -- | -- | Yes |\n| Race condition in multi-agent bid | -- | -- | Partial | Yes |\n| Cascade failure from agent crash | -- | -- | -- | Yes |\n| Retry storm draining wallet | -- | -- | -- | Yes |\n| Slow response degrading throughput | -- | -- | -- | Yes |\n\n\"Partial\" means the layer can catch it if you write the test specifically for that scenario, but it will not catch it by default.\n\n### Recommended Ratios and Cost Model\n\nFor a production agent commerce system, target this distribution:\n\n- **60% unit tests** -- fast, cheap, catch logic bugs. Write these first for every new feature.\n- **30% integration tests** -- moderate speed, catch API interaction bugs. Use recorded responses for CI, live sandbox for nightly runs.\n- **10% end-to-end and chaos tests** -- slow, expensive, catch system-level failures. Run on merge to main and before releases.\n\nThe cost model matters. A unit test runs in 5ms and costs nothing. An integration test against recordings runs in 50ms. An integration test against the live sandbox runs in 500ms and consumes API credits. An end-to-end test runs in 30-120 seconds and consumes credits across multiple agent wallets. A chaos test can run for minutes and may leave state that needs cleanup. Budget accordingly.\n\n### Test Isolation Strategy\n\nEvery test layer needs a different isolation strategy:\n\n```python\n# Unit: no external dependencies, pure logic\ndef test_escrow_amount_validation():\n    agent = MyAgent(api_key=\"fake\", agent_id=\"test-agent\")\n    with pytest.raises(ValueError, match=\"amount must be positive\"):\n        agent.validate_escrow_params(amount=-100, counterparty=\"agent-b\")\n\n\n# Integration: recorded responses or sandbox, isolated wallet\ndef test_create_escrow_against_sandbox(test_harness):\n    result = test_harness.execute(\"create_escrow\", {\n        \"payer\": \"test-agent-a\",\n        \"payee\": \"test-agent-b\",\n        \"amount\": \"1.00\",\n        \"currency\": \"USD\",\n        \"conditions\": {\"delivery_by\": \"2026-12-31T00:00:00Z\"},\n    })\n    assert result[\"status\"] == \"pending\"\n    assert \"escrow_id\" in result\n\n\n# E2E: full agent lifecycle, dedicated test agents\ndef test_full_commerce_workflow(agent_a, agent_b):\n    # Agent B registers a service\n    service = agent_b.register_service(\"data-enrichment\", price=\"5.00\")\n    # Agent A discovers and purchases\n    results = agent_a.search_services(\"data-enrichment\")\n    escrow = agent_a.create_escrow(payee=agent_b.agent_id, amount=\"5.00\")\n    # Agent B delivers and agent A releases\n    agent_b.deliver(escrow[\"escrow_id\"])\n    agent_a.release_escrow(escrow[\"escrow_id\"])\n    assert agent_a.get_balance() \u003C initial_balance\n```\n\nName your test agents with the `test-` prefix so they are excluded from leaderboards and production metrics. GreenHelix filters `test-*` prefixed agents from public rankings.\n\n---\n\n## Chapter 2: AgentTestHarness Class\n\n### The Problem with Live API Testing in CI\n\nRunning integration tests against the live GreenHelix sandbox in every CI run creates three problems: flaky tests from network latency variance, API credit consumption that scales with your commit frequency, and rate limit hits when multiple developers push simultaneously. You need a way to capture real API responses once, then replay them deterministically in CI.\n\nThe `AgentTestHarness` class solves this with a record\u002Fplayback pattern. In record mode, it proxies every API call through to the real GreenHelix sandbox and saves the request-response pair to a cassette file. In playback mode, it matches incoming requests against recorded cassettes and returns the saved response without making a network call. This gives you the confidence of real API validation with the speed and reliability of mocking.\n\n### The Complete AgentTestHarness\n\n```python\nimport hashlib\nimport json\nimport os\nimport time\nimport logging\nfrom pathlib import Path\nfrom typing import Any, Optional\nfrom dataclasses import dataclass, field\n\nimport requests\n\n\nlogger = logging.getLogger(__name__)\n\n\n@dataclass\nclass CassetteEntry:\n    \"\"\"A single recorded request-response pair.\"\"\"\n    request_tool: str\n    request_input: dict\n    response_status: int\n    response_body: dict\n    response_headers: dict\n    timestamp: float\n    latency_ms: float\n\n\n@dataclass\nclass Cassette:\n    \"\"\"A collection of recorded interactions.\"\"\"\n    name: str\n    entries: list[CassetteEntry] = field(default_factory=list)\n    metadata: dict = field(default_factory=dict)\n\n    def save(self, path: Path) -> None:\n        data = {\n            \"name\": self.name,\n            \"metadata\": self.metadata,\n            \"entries\": [\n                {\n                    \"request_tool\": e.request_tool,\n                    \"request_input\": e.request_input,\n                    \"response_status\": e.response_status,\n                    \"response_body\": e.response_body,\n                    \"response_headers\": e.response_headers,\n                    \"timestamp\": e.timestamp,\n                    \"latency_ms\": e.latency_ms,\n                }\n                for e in self.entries\n            ],\n        }\n        path.parent.mkdir(parents=True, exist_ok=True)\n        path.write_text(json.dumps(data, indent=2, default=str))\n        logger.info(\"Saved cassette %s with %d entries\", self.name, len(self.entries))\n\n    @classmethod\n    def load(cls, path: Path) -> \"Cassette\":\n        data = json.loads(path.read_text())\n        entries = [\n            CassetteEntry(**e) for e in data[\"entries\"]\n        ]\n        return cls(name=data[\"name\"], entries=entries, metadata=data.get(\"metadata\", {}))\n\n\nclass AgentTestHarness:\n    \"\"\"\n    Test harness that wraps GreenHelix API calls with\n    recording\u002Fplayback for deterministic CI testing.\n    \"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        base_url: str = \"https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1\",\n        cassette_dir: str = \"tests\u002Fcassettes\",\n        mode: str = \"playback\",  # \"record\", \"playback\", or \"passthrough\"\n    ):\n        self.api_key = api_key\n        self.agent_id = agent_id\n        self.base_url = base_url\n        self.cassette_dir = Path(cassette_dir)\n        self.mode = mode\n        self._current_cassette: Optional[Cassette] = None\n        self._playback_index: int = 0\n\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n\n        # Assertion counters for test reporting\n        self.call_count = 0\n        self.assertion_count = 0\n        self.failures: list[str] = []\n\n    def start_cassette(self, name: str) -> None:\n        \"\"\"Begin recording or loading a cassette.\"\"\"\n        cassette_path = self.cassette_dir \u002F f\"{name}.json\"\n\n        if self.mode == \"record\":\n            self._current_cassette = Cassette(\n                name=name,\n                metadata={\n                    \"agent_id\": self.agent_id,\n                    \"base_url\": self.base_url,\n                    \"recorded_at\": time.time(),\n                },\n            )\n            logger.info(\"Recording cassette: %s\", name)\n\n        elif self.mode == \"playback\":\n            if not cassette_path.exists():\n                raise FileNotFoundError(\n                    f\"Cassette not found: {cassette_path}. \"\n                    f\"Run with mode='record' first.\"\n                )\n            self._current_cassette = Cassette.load(cassette_path)\n            self._playback_index = 0\n            logger.info(\n                \"Playing back cassette: %s (%d entries)\",\n                name, len(self._current_cassette.entries),\n            )\n\n        elif self.mode == \"passthrough\":\n            self._current_cassette = None\n            logger.info(\"Passthrough mode: all calls go to live API\")\n\n    def stop_cassette(self) -> None:\n        \"\"\"Finish recording and save the cassette.\"\"\"\n        if self.mode == \"record\" and self._current_cassette:\n            cassette_path = self.cassette_dir \u002F f\"{self._current_cassette.name}.json\"\n            self._current_cassette.save(cassette_path)\n        self._current_cassette = None\n        self._playback_index = 0\n\n    def execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"\n        Execute a GreenHelix tool call, recording or playing back\n        depending on the current mode.\n        \"\"\"\n        self.call_count += 1\n\n        if self.mode == \"playback\":\n            return self._playback(tool, input_data)\n        elif self.mode == \"record\":\n            return self._record(tool, input_data)\n        else:\n            return self._live_call(tool, input_data)\n\n    def _live_call(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Make a real API call to GreenHelix.\"\"\"\n        start = time.monotonic()\n        resp = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        latency_ms = (time.monotonic() - start) * 1000\n\n        body = resp.json() if resp.headers.get(\"content-type\", \"\").startswith(\"application\u002Fjson\") else {}\n        return {\n            \"status_code\": resp.status_code,\n            \"body\": body,\n            \"headers\": dict(resp.headers),\n            \"latency_ms\": latency_ms,\n        }\n\n    def _record(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Make a live call and record the result.\"\"\"\n        result = self._live_call(tool, input_data)\n\n        if self._current_cassette:\n            entry = CassetteEntry(\n                request_tool=tool,\n                request_input=input_data,\n                response_status=result[\"status_code\"],\n                response_body=result[\"body\"],\n                response_headers=result[\"headers\"],\n                timestamp=time.time(),\n                latency_ms=result[\"latency_ms\"],\n            )\n            self._current_cassette.entries.append(entry)\n\n        return result\n\n    def _playback(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Return a recorded response from the cassette.\"\"\"\n        if not self._current_cassette:\n            raise RuntimeError(\"No cassette loaded for playback\")\n\n        if self._playback_index >= len(self._current_cassette.entries):\n            raise RuntimeError(\n                f\"Cassette exhausted: expected at most \"\n                f\"{len(self._current_cassette.entries)} calls, \"\n                f\"got call #{self._playback_index + 1} for tool '{tool}'\"\n            )\n\n        entry = self._current_cassette.entries[self._playback_index]\n        self._playback_index += 1\n\n        # Verify the call matches what was recorded\n        if entry.request_tool != tool:\n            self.failures.append(\n                f\"Call #{self._playback_index}: expected tool \"\n                f\"'{entry.request_tool}', got '{tool}'\"\n            )\n            logger.warning(\n                \"Tool mismatch at index %d: recorded=%s, actual=%s\",\n                self._playback_index - 1, entry.request_tool, tool,\n            )\n\n        return {\n            \"status_code\": entry.response_status,\n            \"body\": entry.response_body,\n            \"headers\": entry.response_headers,\n            \"latency_ms\": entry.latency_ms,\n        }\n\n    # ── Assertion Helpers ────────────────────────────────────────────\n\n    def assert_success(self, result: dict, msg: str = \"\") -> None:\n        \"\"\"Assert the API call returned 200.\"\"\"\n        self.assertion_count += 1\n        if result[\"status_code\"] != 200:\n            detail = msg or f\"Expected 200, got {result['status_code']}\"\n            self.failures.append(detail)\n            raise AssertionError(detail)\n\n    def assert_status(self, result: dict, expected: int, msg: str = \"\") -> None:\n        \"\"\"Assert a specific HTTP status code.\"\"\"\n        self.assertion_count += 1\n        if result[\"status_code\"] != expected:\n            detail = msg or f\"Expected {expected}, got {result['status_code']}\"\n            self.failures.append(detail)\n            raise AssertionError(detail)\n\n    def assert_field(self, result: dict, field: str, expected: Any = None) -> None:\n        \"\"\"Assert a field exists in the response body, optionally matching a value.\"\"\"\n        self.assertion_count += 1\n        body = result[\"body\"]\n        if field not in body:\n            detail = f\"Field '{field}' not found in response. Keys: {list(body.keys())}\"\n            self.failures.append(detail)\n            raise AssertionError(detail)\n        if expected is not None and body[field] != expected:\n            detail = f\"Field '{field}': expected {expected!r}, got {body[field]!r}\"\n            self.failures.append(detail)\n            raise AssertionError(detail)\n\n    def assert_escrow_state(self, result: dict, expected_state: str) -> None:\n        \"\"\"Assert an escrow is in a specific lifecycle state.\"\"\"\n        self.assertion_count += 1\n        state = result[\"body\"].get(\"status\") or result[\"body\"].get(\"state\")\n        if state != expected_state:\n            detail = f\"Escrow state: expected '{expected_state}', got '{state}'\"\n            self.failures.append(detail)\n            raise AssertionError(detail)\n\n    def assert_balance_changed(\n        self, before: dict, after: dict, expected_delta: str\n    ) -> None:\n        \"\"\"Assert a wallet balance changed by the expected amount.\"\"\"\n        self.assertion_count += 1\n        from decimal import Decimal\n        before_bal = Decimal(str(before[\"body\"][\"balance\"]))\n        after_bal = Decimal(str(after[\"body\"][\"balance\"]))\n        delta = after_bal - before_bal\n        if delta != Decimal(expected_delta):\n            detail = (\n                f\"Balance delta: expected {expected_delta}, \"\n                f\"got {delta} ({before_bal} -> {after_bal})\"\n            )\n            self.failures.append(detail)\n            raise AssertionError(detail)\n\n    def report(self) -> dict:\n        \"\"\"Generate a test execution report.\"\"\"\n        return {\n            \"total_calls\": self.call_count,\n            \"total_assertions\": self.assertion_count,\n            \"failures\": len(self.failures),\n            \"failure_details\": self.failures,\n            \"mode\": self.mode,\n            \"passed\": len(self.failures) == 0,\n        }\n```\n\n### Using the Harness in Tests\n\nRecord cassettes once against the live sandbox, then replay them in every CI run:\n\n```python\nimport pytest\nimport os\n\n\n@pytest.fixture\ndef harness():\n    mode = os.environ.get(\"TEST_MODE\", \"playback\")\n    h = AgentTestHarness(\n        api_key=os.environ.get(\"GREENHELIX_API_KEY\", \"test-key\"),\n        agent_id=\"test-qa-agent\",\n        mode=mode,\n    )\n    return h\n\n\ndef test_escrow_lifecycle(harness):\n    \"\"\"Test the full escrow create -> release cycle.\"\"\"\n    harness.start_cassette(\"escrow_lifecycle\")\n\n    # Create escrow\n    create_result = harness.execute(\"create_escrow\", {\n        \"payer\": \"test-qa-agent\",\n        \"payee\": \"test-counterparty\",\n        \"amount\": \"10.00\",\n        \"currency\": \"USD\",\n        \"conditions\": {\"delivery_by\": \"2026-12-31T00:00:00Z\"},\n    })\n    harness.assert_success(create_result)\n    harness.assert_field(create_result, \"escrow_id\")\n    harness.assert_escrow_state(create_result, \"pending\")\n\n    escrow_id = create_result[\"body\"][\"escrow_id\"]\n\n    # Release escrow\n    release_result = harness.execute(\"release_escrow\", {\n        \"escrow_id\": escrow_id,\n        \"agent_id\": \"test-qa-agent\",\n    })\n    harness.assert_success(release_result)\n    harness.assert_escrow_state(release_result, \"released\")\n\n    harness.stop_cassette()\n\n    report = harness.report()\n    assert report[\"passed\"], f\"Test failures: {report['failure_details']}\"\n```\n\nTo re-record cassettes when the API changes, run your tests with `TEST_MODE=record`. Commit the cassette JSON files alongside your tests. Review cassette diffs in pull requests to catch unexpected API response changes -- this is a lightweight form of contract testing that requires zero additional tooling.\n\n### Cassette Hygiene\n\nThree rules keep cassettes reliable. First, never record cassettes with production API keys. Use sandbox keys exclusively. The cassette files will contain response data that could leak if your repository is public. Second, re-record cassettes on a schedule (weekly or when the GreenHelix API version changes). Stale cassettes mask real incompatibilities. Third, strip non-deterministic fields (timestamps, request IDs) from cassette matching. The harness matches on tool name by default, which is sufficient for ordered test flows. For unordered flows, extend the matching to include a hash of the input parameters.\n\n---\n\n## Chapter 3: Mock Strategies for Agent Commerce\n\n### When Mocks Are the Right Tool\n\nMocks are appropriate when you need to test your agent's decision logic without involving any external system. The goal is speed and isolation: validate that your agent makes the right decisions given specific API responses, without caring whether those responses came from a real server. Use mocks for unit tests. Use the test harness (Chapter 2) for integration tests. Never mock in end-to-end tests.\n\n### Mocking the the REST API Endpoint\n\nThe GreenHelix gateway exposes a single endpoint for tool execution: the REST API (`POST \u002Fv1\u002F{tool}`) with a JSON body containing `tool` and `input` fields. This makes mocking straightforward -- you intercept the one endpoint and route responses based on the tool name.\n\n```python\nimport json\nimport time\nfrom typing import Callable, Optional\nfrom dataclasses import dataclass, field\nfrom unittest.mock import MagicMock\n\n\n@dataclass\nclass MockResponse:\n    \"\"\"A canned response for a specific tool call.\"\"\"\n    status_code: int = 200\n    body: dict = field(default_factory=dict)\n    headers: dict = field(default_factory=lambda: {\"content-type\": \"application\u002Fjson\"})\n    delay_ms: float = 0\n\n\nclass GreenHelixMock:\n    \"\"\"\n    Mock server for GreenHelix REST API endpoints.\n    Supports static responses, stateful escrow simulation,\n    and programmable error injection.\n    \"\"\"\n\n    def __init__(self):\n        self._handlers: dict[str, Callable] = {}\n        self._default_responses: dict[str, MockResponse] = {}\n        self._call_log: list[dict] = []\n        self._escrow_state: dict[str, dict] = {}\n        self._wallet_balances: dict[str, str] = {}\n        self._error_queue: list[MockResponse] = []\n\n        # Register built-in stateful handlers\n        self._handlers[\"create_escrow\"] = self._handle_create_escrow\n        self._handlers[\"release_escrow\"] = self._handle_release_escrow\n        self._handlers[\"cancel_escrow\"] = self._handle_cancel_escrow\n        self._handlers[\"get_balance\"] = self._handle_get_balance\n        self._handlers[\"deposit\"] = self._handle_deposit\n\n    def set_response(self, tool: str, response: MockResponse) -> None:\n        \"\"\"Set a static response for a tool.\"\"\"\n        self._default_responses[tool] = response\n\n    def set_balance(self, agent_id: str, balance: str) -> None:\n        \"\"\"Pre-set a wallet balance for stateful testing.\"\"\"\n        self._wallet_balances[agent_id] = balance\n\n    def inject_error(self, status_code: int, body: Optional[dict] = None) -> None:\n        \"\"\"Queue an error to be returned on the next call (any tool).\"\"\"\n        self._error_queue.append(MockResponse(\n            status_code=status_code,\n            body=body or {\"type\": \"error\", \"title\": \"Injected error\", \"status\": status_code},\n        ))\n\n    def inject_errors(self, count: int, status_code: int) -> None:\n        \"\"\"Queue multiple identical errors.\"\"\"\n        for _ in range(count):\n            self.inject_error(status_code)\n\n    def execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Simulate a the REST API call.\"\"\"\n        self._call_log.append({\n            \"tool\": tool,\n            \"input\": input_data,\n            \"timestamp\": time.time(),\n        })\n\n        # Check error queue first\n        if self._error_queue:\n            err = self._error_queue.pop(0)\n            if err.delay_ms > 0:\n                time.sleep(err.delay_ms \u002F 1000)\n            return {\"status_code\": err.status_code, \"body\": err.body, \"headers\": err.headers}\n\n        # Check for custom handler\n        if tool in self._handlers:\n            return self._handlers[tool](input_data)\n\n        # Check for static response\n        if tool in self._default_responses:\n            resp = self._default_responses[tool]\n            if resp.delay_ms > 0:\n                time.sleep(resp.delay_ms \u002F 1000)\n            return {\"status_code\": resp.status_code, \"body\": resp.body, \"headers\": resp.headers}\n\n        # Default: 404 unknown tool\n        return {\n            \"status_code\": 404,\n            \"body\": {\"type\": \"error\", \"title\": f\"Unknown tool: {tool}\", \"status\": 404},\n            \"headers\": {\"content-type\": \"application\u002Fjson\"},\n        }\n\n    # ── Stateful Handlers ────────────────────────────────────────────\n\n    def _handle_create_escrow(self, input_data: dict) -> dict:\n        escrow_id = f\"esc_{hashlib.sha256(json.dumps(input_data, sort_keys=True).encode()).hexdigest()[:12]}\"\n        self._escrow_state[escrow_id] = {\n            \"escrow_id\": escrow_id,\n            \"payer\": input_data[\"payer\"],\n            \"payee\": input_data[\"payee\"],\n            \"amount\": input_data[\"amount\"],\n            \"currency\": input_data.get(\"currency\", \"USD\"),\n            \"status\": \"pending\",\n            \"created_at\": time.time(),\n        }\n        return {\n            \"status_code\": 200,\n            \"body\": self._escrow_state[escrow_id].copy(),\n            \"headers\": {\"content-type\": \"application\u002Fjson\"},\n        }\n\n    def _handle_release_escrow(self, input_data: dict) -> dict:\n        escrow_id = input_data.get(\"escrow_id\")\n        if escrow_id not in self._escrow_state:\n            return {\n                \"status_code\": 404,\n                \"body\": {\"type\": \"error\", \"title\": \"Escrow not found\", \"status\": 404},\n                \"headers\": {\"content-type\": \"application\u002Fjson\"},\n            }\n        escrow = self._escrow_state[escrow_id]\n        if escrow[\"status\"] != \"pending\":\n            return {\n                \"status_code\": 409,\n                \"body\": {\n                    \"type\": \"error\",\n                    \"title\": f\"Cannot release escrow in state '{escrow['status']}'\",\n                    \"status\": 409,\n                },\n                \"headers\": {\"content-type\": \"application\u002Fjson\"},\n            }\n        escrow[\"status\"] = \"released\"\n        escrow[\"released_at\"] = time.time()\n        return {\n            \"status_code\": 200,\n            \"body\": escrow.copy(),\n            \"headers\": {\"content-type\": \"application\u002Fjson\"},\n        }\n\n    def _handle_cancel_escrow(self, input_data: dict) -> dict:\n        escrow_id = input_data.get(\"escrow_id\")\n        if escrow_id not in self._escrow_state:\n            return {\n                \"status_code\": 404,\n                \"body\": {\"type\": \"error\", \"title\": \"Escrow not found\", \"status\": 404},\n                \"headers\": {\"content-type\": \"application\u002Fjson\"},\n            }\n        escrow = self._escrow_state[escrow_id]\n        if escrow[\"status\"] != \"pending\":\n            return {\n                \"status_code\": 409,\n                \"body\": {\n                    \"type\": \"error\",\n                    \"title\": f\"Cannot cancel escrow in state '{escrow['status']}'\",\n                    \"status\": 409,\n                },\n                \"headers\": {\"content-type\": \"application\u002Fjson\"},\n            }\n        escrow[\"status\"] = \"cancelled\"\n        escrow[\"cancelled_at\"] = time.time()\n        return {\n            \"status_code\": 200,\n            \"body\": escrow.copy(),\n            \"headers\": {\"content-type\": \"application\u002Fjson\"},\n        }\n\n    def _handle_get_balance(self, input_data: dict) -> dict:\n        agent_id = input_data.get(\"agent_id\", \"\")\n        balance = self._wallet_balances.get(agent_id, \"0.00\")\n        return {\n            \"status_code\": 200,\n            \"body\": {\"agent_id\": agent_id, \"balance\": balance, \"currency\": \"USD\"},\n            \"headers\": {\"content-type\": \"application\u002Fjson\"},\n        }\n\n    def _handle_deposit(self, input_data: dict) -> dict:\n        agent_id = input_data.get(\"agent_id\", \"\")\n        amount = input_data.get(\"amount\", \"0.00\")\n        from decimal import Decimal\n        current = Decimal(self._wallet_balances.get(agent_id, \"0.00\"))\n        new_balance = current + Decimal(str(amount))\n        self._wallet_balances[agent_id] = str(new_balance)\n        return {\n            \"status_code\": 200,\n            \"body\": {\n                \"agent_id\": agent_id,\n                \"deposited\": str(amount),\n                \"balance\": str(new_balance),\n                \"currency\": \"USD\",\n            },\n            \"headers\": {\"content-type\": \"application\u002Fjson\"},\n        }\n\n    # ── Introspection ────────────────────────────────────────────────\n\n    def get_call_log(self) -> list[dict]:\n        return self._call_log.copy()\n\n    def get_calls_for_tool(self, tool: str) -> list[dict]:\n        return [c for c in self._call_log if c[\"tool\"] == tool]\n\n    def assert_called(self, tool: str, times: Optional[int] = None) -> None:\n        calls = self.get_calls_for_tool(tool)\n        if times is not None and len(calls) != times:\n            raise AssertionError(\n                f\"Expected {times} calls to '{tool}', got {len(calls)}\"\n            )\n        if not calls:\n            raise AssertionError(f\"Expected at least one call to '{tool}', got none\")\n\n    def reset(self) -> None:\n        self._call_log.clear()\n        self._escrow_state.clear()\n        self._wallet_balances.clear()\n        self._error_queue.clear()\n```\n\n### Mock Factories for Common Scenarios\n\nBuilding mocks from scratch for every test is tedious. Factory functions encapsulate common setups:\n\n```python\nimport hashlib\n\n\ndef create_funded_mock(agent_id: str, balance: str = \"100.00\") -> GreenHelixMock:\n    \"\"\"Create a mock with a pre-funded wallet.\"\"\"\n    mock = GreenHelixMock()\n    mock.set_balance(agent_id, balance)\n    return mock\n\n\ndef create_failing_mock(failure_count: int = 3, status_code: int = 500) -> GreenHelixMock:\n    \"\"\"Create a mock that fails N times then succeeds.\"\"\"\n    mock = GreenHelixMock()\n    mock.inject_errors(failure_count, status_code)\n    return mock\n\n\ndef create_rate_limited_mock(burst_limit: int = 5) -> GreenHelixMock:\n    \"\"\"Create a mock that returns 429 after N calls.\"\"\"\n    mock = GreenHelixMock()\n    original_execute = mock.execute\n\n    call_count = 0\n    def rate_limited_execute(tool: str, input_data: dict) -> dict:\n        nonlocal call_count\n        call_count += 1\n        if call_count > burst_limit:\n            return {\n                \"status_code\": 429,\n                \"body\": {\n                    \"type\": \"error\",\n                    \"title\": \"Rate limit exceeded\",\n                    \"status\": 429,\n                    \"retry_after\": 60,\n                },\n                \"headers\": {\n                    \"content-type\": \"application\u002Fjson\",\n                    \"retry-after\": \"60\",\n                },\n            }\n        return original_execute(tool, input_data)\n\n    mock.execute = rate_limited_execute\n    return mock\n\n\ndef create_timeout_mock(timeout_tools: list[str], timeout_ms: int = 30000) -> GreenHelixMock:\n    \"\"\"Create a mock where specific tools always time out.\"\"\"\n    mock = GreenHelixMock()\n    for tool in timeout_tools:\n        mock.set_response(tool, MockResponse(\n            status_code=504,\n            body={\"type\": \"error\", \"title\": \"Gateway timeout\", \"status\": 504},\n            delay_ms=timeout_ms,\n        ))\n    return mock\n```\n\n### Testing Retry Logic with Mocks\n\nThe most common production failure pattern is transient errors requiring retries. Use the mock's error queue to validate your retry logic handles escalating failures:\n\n```python\ndef test_retry_logic_with_backoff(my_agent_class):\n    \"\"\"Verify the agent retries transient errors with backoff.\"\"\"\n    mock = GreenHelixMock()\n    # Fail twice with 500, then succeed\n    mock.inject_errors(2, 500)\n    mock.set_balance(\"test-agent\", \"50.00\")\n\n    agent = my_agent_class(api=mock, agent_id=\"test-agent\")\n    result = agent.check_balance()\n\n    # Agent should have retried and eventually succeeded\n    assert result[\"balance\"] == \"50.00\"\n    # Should have made 3 calls total: 2 failures + 1 success\n    mock.assert_called(\"get_balance\", times=3)\n\n\ndef test_retry_exhaustion():\n    \"\"\"Verify the agent gives up after max retries.\"\"\"\n    mock = GreenHelixMock()\n    mock.inject_errors(10, 503)  # More errors than max retries\n\n    agent = my_agent_class(api=mock, agent_id=\"test-agent\", max_retries=3)\n    with pytest.raises(ServiceUnavailableError):\n        agent.check_balance()\n\n    mock.assert_called(\"get_balance\", times=4)  # 1 initial + 3 retries\n```\n\n---\n\n## Chapter 4: ChaosInjector Class\n\n### Why Chaos Testing Matters for Agent Commerce\n\nUnit tests and integration tests validate the happy path and a handful of known error paths. Chaos testing answers a different question: what happens when the infrastructure itself misbehaves in ways you did not anticipate? In agent commerce, the consequences of unhandled infrastructure failures are financial. An escrow that gets created but whose confirmation is lost leaves funds locked. A webhook that delivers twice triggers duplicate payments. A DNS resolution delay that pushes a request past its timeout causes a retry that creates a duplicate escrow. These are not hypothetical -- they are the actual failure modes observed in production multi-agent systems.\n\nThe `ChaosInjector` class wraps any API client (real or mock) and injects configurable failures into the communication layer. It operates at the transport level, corrupting responses after they leave the server but before your agent processes them.\n\n### The Complete ChaosInjector\n\n```python\nimport copy\nimport json\nimport random\nimport time\nimport threading\nimport logging\nfrom dataclasses import dataclass, field\nfrom enum import Enum\nfrom typing import Any, Callable, Optional\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass FailureMode(Enum):\n    LATENCY = \"latency\"\n    TIMEOUT = \"timeout\"\n    PARTIAL_RESPONSE = \"partial_response\"\n    WRONG_STATUS = \"wrong_status\"\n    CORRUPT_BODY = \"corrupt_body\"\n    SCHEMA_DRIFT = \"schema_drift\"\n    CONNECTION_RESET = \"connection_reset\"\n    DUPLICATE_RESPONSE = \"duplicate_response\"\n\n\n@dataclass\nclass ChaosConfig:\n    \"\"\"Configuration for a chaos injection scenario.\"\"\"\n    failure_mode: FailureMode\n    probability: float = 1.0       # 0.0 to 1.0\n    target_tools: list[str] = field(default_factory=list)  # empty = all tools\n    latency_ms: float = 5000       # for LATENCY mode\n    timeout_ms: float = 30000      # for TIMEOUT mode\n    corrupt_fields: list[str] = field(default_factory=list)  # for CORRUPT_BODY\n    drift_schema: dict = field(default_factory=dict)  # for SCHEMA_DRIFT\n\n\nclass ChaosInjector:\n    \"\"\"\n    Wraps an API client and injects configurable failures\n    into agent-to-gateway communication.\n    \"\"\"\n\n    def __init__(self, wrapped_client: Any, seed: Optional[int] = None):\n        self._client = wrapped_client\n        self._configs: list[ChaosConfig] = []\n        self._rng = random.Random(seed)\n        self._event_log: list[dict] = []\n        self._active = True\n        self._lock = threading.Lock()\n\n    def add_chaos(self, config: ChaosConfig) -> None:\n        \"\"\"Register a chaos configuration.\"\"\"\n        self._configs.append(config)\n        logger.info(\n            \"Chaos registered: %s (p=%.2f, tools=%s)\",\n            config.failure_mode.value,\n            config.probability,\n            config.target_tools or \"all\",\n        )\n\n    def pause(self) -> None:\n        \"\"\"Temporarily disable chaos injection.\"\"\"\n        self._active = False\n\n    def resume(self) -> None:\n        \"\"\"Re-enable chaos injection.\"\"\"\n        self._active = True\n\n    def execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute with potential chaos injection.\"\"\"\n        # Get the real response first\n        result = self._client.execute(tool, input_data)\n\n        if not self._active:\n            return result\n\n        # Apply each matching chaos config\n        for config in self._configs:\n            if not self._should_apply(config, tool):\n                continue\n\n            event = {\n                \"timestamp\": time.time(),\n                \"tool\": tool,\n                \"failure_mode\": config.failure_mode.value,\n            }\n\n            result = self._apply_chaos(config, result, tool)\n            event[\"applied\"] = True\n            with self._lock:\n                self._event_log.append(event)\n            logger.warning(\n                \"Chaos injected: %s on tool '%s'\",\n                config.failure_mode.value, tool,\n            )\n\n        return result\n\n    def _should_apply(self, config: ChaosConfig, tool: str) -> bool:\n        \"\"\"Determine if this chaos config applies to this call.\"\"\"\n        if config.target_tools and tool not in config.target_tools:\n            return False\n        return self._rng.random() \u003C config.probability\n\n    def _apply_chaos(self, config: ChaosConfig, result: dict, tool: str) -> dict:\n        \"\"\"Apply a specific failure mode to the response.\"\"\"\n        mode = config.failure_mode\n\n        if mode == FailureMode.LATENCY:\n            time.sleep(config.latency_ms \u002F 1000)\n            return result\n\n        elif mode == FailureMode.TIMEOUT:\n            time.sleep(config.timeout_ms \u002F 1000)\n            raise TimeoutError(\n                f\"Chaos: simulated timeout after {config.timeout_ms}ms \"\n                f\"on tool '{tool}'\"\n            )\n\n        elif mode == FailureMode.PARTIAL_RESPONSE:\n            corrupted = copy.deepcopy(result)\n            body = corrupted.get(\"body\", {})\n            keys = list(body.keys())\n            if len(keys) > 1:\n                # Remove a random subset of fields\n                remove_count = max(1, len(keys) \u002F\u002F 2)\n                for key in self._rng.sample(keys, remove_count):\n                    del body[key]\n            corrupted[\"body\"] = body\n            return corrupted\n\n        elif mode == FailureMode.WRONG_STATUS:\n            corrupted = copy.deepcopy(result)\n            corrupted[\"status_code\"] = self._rng.choice([500, 502, 503, 504])\n            return corrupted\n\n        elif mode == FailureMode.CORRUPT_BODY:\n            corrupted = copy.deepcopy(result)\n            body = corrupted.get(\"body\", {})\n            for field_name in config.corrupt_fields:\n                if field_name in body:\n                    original = body[field_name]\n                    body[field_name] = self._corrupt_value(original)\n            corrupted[\"body\"] = body\n            return corrupted\n\n        elif mode == FailureMode.SCHEMA_DRIFT:\n            corrupted = copy.deepcopy(result)\n            body = corrupted.get(\"body\", {})\n            # Add unexpected fields\n            for key, value in config.drift_schema.items():\n                body[key] = value\n            # Rename existing fields to simulate API version change\n            if \"status\" in body:\n                body[\"state\"] = body.pop(\"status\")\n            corrupted[\"body\"] = body\n            return corrupted\n\n        elif mode == FailureMode.CONNECTION_RESET:\n            raise ConnectionError(\n                f\"Chaos: simulated connection reset on tool '{tool}'\"\n            )\n\n        elif mode == FailureMode.DUPLICATE_RESPONSE:\n            # Return the response twice (simulates webhook double-delivery)\n            return result  # caller sees normal response, but we log it as duplicate\n\n        return result\n\n    def _corrupt_value(self, value: Any) -> Any:\n        \"\"\"Corrupt a value while keeping the same type.\"\"\"\n        if isinstance(value, str):\n            if value.replace(\".\", \"\").replace(\"-\", \"\").isdigit():\n                # Numeric string: flip sign or add digits\n                return str(float(value) * -1)\n            return value[::-1]  # Reverse the string\n        elif isinstance(value, (int, float)):\n            return value * -1\n        elif isinstance(value, bool):\n            return not value\n        elif isinstance(value, list):\n            return []\n        elif isinstance(value, dict):\n            return {}\n        return None\n\n    def get_event_log(self) -> list[dict]:\n        \"\"\"Return the log of all chaos events.\"\"\"\n        with self._lock:\n            return self._event_log.copy()\n\n    def get_injection_count(self) -> int:\n        \"\"\"Return the total number of chaos injections.\"\"\"\n        with self._lock:\n            return len(self._event_log)\n\n    def reset(self) -> None:\n        \"\"\"Clear all chaos configs and logs.\"\"\"\n        self._configs.clear()\n        with self._lock:\n            self._event_log.clear()\n```\n\n### Chaos Scenarios for Agent Commerce\n\nHere are the chaos scenarios that match real production failures. Each one uses the `ChaosInjector` with specific configurations:\n\n```python\ndef scenario_agent_dies_mid_escrow(harness, chaos):\n    \"\"\"\n    Simulate: Agent creates escrow, then the counterparty agent\n    becomes unreachable before delivery.\n    \"\"\"\n    chaos.add_chaos(ChaosConfig(\n        failure_mode=FailureMode.CONNECTION_RESET,\n        probability=1.0,\n        target_tools=[\"release_escrow\", \"cancel_escrow\"],\n    ))\n\n    # Create escrow succeeds\n    result = chaos.execute(\"create_escrow\", {\n        \"payer\": \"test-agent-a\",\n        \"payee\": \"test-agent-b\",\n        \"amount\": \"25.00\",\n        \"currency\": \"USD\",\n        \"conditions\": {\"delivery_by\": \"2026-12-31T00:00:00Z\"},\n    })\n    assert result[\"status_code\"] == 200\n\n    # Attempting to release or cancel fails with connection reset\n    try:\n        chaos.execute(\"release_escrow\", {\n            \"escrow_id\": result[\"body\"][\"escrow_id\"],\n            \"agent_id\": \"test-agent-a\",\n        })\n        assert False, \"Should have raised ConnectionError\"\n    except ConnectionError:\n        pass  # Expected -- agent should handle this with retry + timeout\n\n\ndef scenario_webhook_double_delivery(harness, chaos):\n    \"\"\"\n    Simulate: Webhook delivers the same escrow release notification twice.\n    Agent must be idempotent.\n    \"\"\"\n    chaos.add_chaos(ChaosConfig(\n        failure_mode=FailureMode.DUPLICATE_RESPONSE,\n        probability=1.0,\n        target_tools=[\"release_escrow\"],\n    ))\n\n    # First release succeeds\n    result1 = chaos.execute(\"release_escrow\", {\n        \"escrow_id\": \"esc_abc123\",\n        \"agent_id\": \"test-agent-a\",\n    })\n    # Second identical release should be idempotent\n    result2 = chaos.execute(\"release_escrow\", {\n        \"escrow_id\": \"esc_abc123\",\n        \"agent_id\": \"test-agent-a\",\n    })\n    # Agent should handle both gracefully -- no double payment\n\n\ndef scenario_schema_drift_between_versions(harness, chaos):\n    \"\"\"\n    Simulate: GreenHelix API changes 'status' field to 'state'\n    in escrow responses (v2 migration).\n    \"\"\"\n    chaos.add_chaos(ChaosConfig(\n        failure_mode=FailureMode.SCHEMA_DRIFT,\n        probability=1.0,\n        target_tools=[\"create_escrow\", \"release_escrow\"],\n        drift_schema={\"api_version\": \"2.0\", \"deprecated_fields\": [\"status\"]},\n    ))\n\n    result = chaos.execute(\"create_escrow\", {\n        \"payer\": \"test-agent-a\",\n        \"payee\": \"test-agent-b\",\n        \"amount\": \"10.00\",\n        \"currency\": \"USD\",\n    })\n    # Agent should handle both 'status' and 'state' fields\n    body = result[\"body\"]\n    state = body.get(\"status\") or body.get(\"state\")\n    assert state is not None, \"Agent must handle schema drift gracefully\"\n\n\ndef scenario_latency_spike_during_payment(harness, chaos):\n    \"\"\"\n    Simulate: 5-second latency spike on payment tools.\n    Tests whether agent times out and retries (risking double-payment)\n    or waits patiently.\n    \"\"\"\n    chaos.add_chaos(ChaosConfig(\n        failure_mode=FailureMode.LATENCY,\n        probability=0.5,\n        target_tools=[\"deposit\", \"create_escrow\", \"release_escrow\"],\n        latency_ms=5000,\n    ))\n\n    # Agent should handle variable latency without creating duplicates\n    result = chaos.execute(\"deposit\", {\n        \"agent_id\": \"test-agent-a\",\n        \"amount\": \"10.00\",\n    })\n    assert result[\"status_code\"] == 200\n```\n\n### Running Chaos Tests in CI\n\nChaos tests should run on merge to main, not on every commit. They are slower and nondeterministic by design. Use a fixed random seed for reproducibility in CI, and a random seed for exploratory testing locally:\n\n```python\n@pytest.fixture\ndef chaos_harness():\n    \"\"\"Create a chaos-wrapped test harness.\"\"\"\n    mock = create_funded_mock(\"test-agent-a\", \"1000.00\")\n    mock.set_balance(\"test-agent-b\", \"500.00\")\n    seed = int(os.environ.get(\"CHAOS_SEED\", \"42\"))\n    injector = ChaosInjector(mock, seed=seed)\n    return injector\n\n\n@pytest.mark.chaos\nclass TestChaosResilience:\n    \"\"\"Chaos tests -- run with: pytest -m chaos\"\"\"\n\n    def test_survives_random_failures(self, chaos_harness):\n        chaos_harness.add_chaos(ChaosConfig(\n            failure_mode=FailureMode.WRONG_STATUS,\n            probability=0.3,\n        ))\n        chaos_harness.add_chaos(ChaosConfig(\n            failure_mode=FailureMode.LATENCY,\n            probability=0.2,\n            latency_ms=2000,\n        ))\n\n        successes = 0\n        for _ in range(100):\n            try:\n                result = chaos_harness.execute(\"get_balance\", {\"agent_id\": \"test-agent-a\"})\n                if result[\"status_code\"] == 200:\n                    successes += 1\n            except (TimeoutError, ConnectionError):\n                pass\n\n        # With 30% status corruption and 20% latency, expect ~70% success\n        assert successes > 50, f\"Only {successes}\u002F100 succeeded under chaos\"\n```\n\n---\n\n## Chapter 5: ContractValidator Class\n\n### The Contract Testing Problem\n\nIn a multi-agent system, every agent is both a producer and consumer of API contracts. Agent A calls `create_escrow` expecting a response with an `escrow_id` field. Agent B subscribes to escrow webhooks expecting a `status` field with specific enum values. When agent A upgrades its GreenHelix SDK and the response format changes, agent B breaks. Nobody tested the interaction because each agent has its own test suite and neither tests the contract between them.\n\nContract testing solves this by making the interface between agents an explicit, versioned, testable artifact. Each consumer declares what it expects from a producer. Each producer validates that its responses satisfy all consumer expectations. When a change breaks a contract, the producer's CI fails before the code ships.\n\n### The Complete ContractValidator\n\n```python\nimport json\nimport re\nimport time\nimport logging\nfrom copy import deepcopy\nfrom dataclasses import dataclass, field\nfrom enum import Enum\nfrom pathlib import Path\nfrom typing import Any, Optional\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass Severity(Enum):\n    ERROR = \"error\"          # Breaking change, blocks deployment\n    WARNING = \"warning\"      # Potentially breaking, manual review\n    INFO = \"info\"            # Non-breaking change, informational\n\n\n@dataclass\nclass ContractViolation:\n    \"\"\"A single contract violation.\"\"\"\n    field: str\n    expected: str\n    actual: str\n    severity: Severity\n    message: str\n\n\n@dataclass\nclass ToolContract:\n    \"\"\"Contract definition for a single GreenHelix tool.\"\"\"\n    tool_name: str\n    version: str\n    input_schema: dict          # JSON Schema for tool input\n    output_schema: dict         # JSON Schema for tool output\n    required_output_fields: list[str] = field(default_factory=list)\n    optional_output_fields: list[str] = field(default_factory=list)\n    status_codes: list[int] = field(default_factory=lambda: [200])\n    constraints: list[dict] = field(default_factory=list)\n\n\n@dataclass\nclass AgentContract:\n    \"\"\"Contract between two agents or between an agent and the gateway.\"\"\"\n    consumer: str               # Agent ID of the consumer\n    producer: str               # Agent ID or \"gateway\"\n    tools: list[ToolContract] = field(default_factory=list)\n    metadata: dict = field(default_factory=dict)\n\n    def save(self, path: Path) -> None:\n        data = {\n            \"consumer\": self.consumer,\n            \"producer\": self.producer,\n            \"metadata\": self.metadata,\n            \"tools\": [\n                {\n                    \"tool_name\": t.tool_name,\n                    \"version\": t.version,\n                    \"input_schema\": t.input_schema,\n                    \"output_schema\": t.output_schema,\n                    \"required_output_fields\": t.required_output_fields,\n                    \"optional_output_fields\": t.optional_output_fields,\n                    \"status_codes\": t.status_codes,\n                    \"constraints\": t.constraints,\n                }\n                for t in self.tools\n            ],\n        }\n        path.parent.mkdir(parents=True, exist_ok=True)\n        path.write_text(json.dumps(data, indent=2))\n\n    @classmethod\n    def load(cls, path: Path) -> \"AgentContract\":\n        data = json.loads(path.read_text())\n        tools = [ToolContract(**t) for t in data[\"tools\"]]\n        return cls(\n            consumer=data[\"consumer\"],\n            producer=data[\"producer\"],\n            tools=tools,\n            metadata=data.get(\"metadata\", {}),\n        )\n\n\nclass ContractValidator:\n    \"\"\"\n    Validates API responses against consumer-driven contracts.\n    Catches breaking changes before they reach production.\n    \"\"\"\n\n    def __init__(self, contracts_dir: str = \"contracts\"):\n        self.contracts_dir = Path(contracts_dir)\n        self._contracts: list[AgentContract] = []\n        self._violations: list[ContractViolation] = []\n        self._validations: int = 0\n\n    def load_contracts(self) -> int:\n        \"\"\"Load all contract files from the contracts directory.\"\"\"\n        loaded = 0\n        if not self.contracts_dir.exists():\n            logger.warning(\"Contracts directory not found: %s\", self.contracts_dir)\n            return 0\n\n        for path in self.contracts_dir.glob(\"*.contract.json\"):\n            contract = AgentContract.load(path)\n            self._contracts.append(contract)\n            loaded += 1\n            logger.info(\n                \"Loaded contract: %s -> %s (%d tools)\",\n                contract.consumer, contract.producer, len(contract.tools),\n            )\n        return loaded\n\n    def add_contract(self, contract: AgentContract) -> None:\n        \"\"\"Register a contract programmatically.\"\"\"\n        self._contracts.append(contract)\n\n    def validate_response(\n        self, tool: str, response: dict, producer: str = \"gateway\"\n    ) -> list[ContractViolation]:\n        \"\"\"Validate a tool response against all matching contracts.\"\"\"\n        self._validations += 1\n        violations = []\n\n        for contract in self._contracts:\n            if contract.producer != producer:\n                continue\n\n            for tool_contract in contract.tools:\n                if tool_contract.tool_name != tool:\n                    continue\n\n                tool_violations = self._validate_tool_response(\n                    tool_contract, response, contract.consumer\n                )\n                violations.extend(tool_violations)\n\n        self._violations.extend(violations)\n        return violations\n\n    def _validate_tool_response(\n        self,\n        contract: ToolContract,\n        response: dict,\n        consumer: str,\n    ) -> list[ContractViolation]:\n        \"\"\"Validate a single tool response against its contract.\"\"\"\n        violations = []\n        body = response.get(\"body\", {})\n        status = response.get(\"status_code\", 0)\n\n        # Check status code\n        if status not in contract.status_codes:\n            violations.append(ContractViolation(\n                field=\"status_code\",\n                expected=str(contract.status_codes),\n                actual=str(status),\n                severity=Severity.ERROR,\n                message=(\n                    f\"Consumer '{consumer}' expects status \"\n                    f\"{contract.status_codes} from '{contract.tool_name}', \"\n                    f\"got {status}\"\n                ),\n            ))\n\n        # Check required fields\n        for field_name in contract.required_output_fields:\n            if field_name not in body:\n                violations.append(ContractViolation(\n                    field=field_name,\n                    expected=\"present\",\n                    actual=\"missing\",\n                    severity=Severity.ERROR,\n                    message=(\n                        f\"Consumer '{consumer}' requires field \"\n                        f\"'{field_name}' in '{contract.tool_name}' response\"\n                    ),\n                ))\n\n        # Check field types from output schema\n        for field_name, schema in contract.output_schema.items():\n            if field_name not in body:\n                continue\n            type_violation = self._check_type(field_name, body[field_name], schema)\n            if type_violation:\n                violations.append(type_violation)\n\n        # Check constraints\n        for constraint in contract.constraints:\n            constraint_violation = self._check_constraint(constraint, body)\n            if constraint_violation:\n                violations.append(constraint_violation)\n\n        return violations\n\n    def _check_type(\n        self, field_name: str, value: Any, schema: dict\n    ) -> Optional[ContractViolation]:\n        \"\"\"Check that a field value matches the expected type.\"\"\"\n        expected_type = schema.get(\"type\")\n        if expected_type is None:\n            return None\n\n        type_map = {\n            \"string\": str,\n            \"integer\": int,\n            \"number\": (int, float),\n            \"boolean\": bool,\n            \"array\": list,\n            \"object\": dict,\n        }\n\n        expected_python_type = type_map.get(expected_type)\n        if expected_python_type and not isinstance(value, expected_python_type):\n            return ContractViolation(\n                field=field_name,\n                expected=expected_type,\n                actual=type(value).__name__,\n                severity=Severity.ERROR,\n                message=(\n                    f\"Field '{field_name}': expected type '{expected_type}', \"\n                    f\"got '{type(value).__name__}'\"\n                ),\n            )\n\n        # Check enum constraint\n        if \"enum\" in schema and value not in schema[\"enum\"]:\n            return ContractViolation(\n                field=field_name,\n                expected=str(schema[\"enum\"]),\n                actual=str(value),\n                severity=Severity.ERROR,\n                message=(\n                    f\"Field '{field_name}': value '{value}' not in \"\n                    f\"allowed values {schema['enum']}\"\n                ),\n            )\n\n        # Check pattern constraint\n        if \"pattern\" in schema and isinstance(value, str):\n            if not re.match(schema[\"pattern\"], value):\n                return ContractViolation(\n                    field=field_name,\n                    expected=f\"pattern: {schema['pattern']}\",\n                    actual=value,\n                    severity=Severity.WARNING,\n                    message=(\n                        f\"Field '{field_name}': value '{value}' does not \"\n                        f\"match pattern '{schema['pattern']}'\"\n                    ),\n                )\n\n        return None\n\n    def _check_constraint(\n        self, constraint: dict, body: dict\n    ) -> Optional[ContractViolation]:\n        \"\"\"Check a custom constraint against the response body.\"\"\"\n        constraint_type = constraint.get(\"type\")\n\n        if constraint_type == \"field_equals\":\n            field_name = constraint[\"field\"]\n            expected = constraint[\"value\"]\n            actual = body.get(field_name)\n            if actual != expected:\n                return ContractViolation(\n                    field=field_name,\n                    expected=str(expected),\n                    actual=str(actual),\n                    severity=Severity(constraint.get(\"severity\", \"error\")),\n                    message=constraint.get(\"message\", f\"{field_name} != {expected}\"),\n                )\n\n        elif constraint_type == \"field_present_if\":\n            condition_field = constraint[\"condition_field\"]\n            condition_value = constraint[\"condition_value\"]\n            required_field = constraint[\"required_field\"]\n            if body.get(condition_field) == condition_value:\n                if required_field not in body:\n                    return ContractViolation(\n                        field=required_field,\n                        expected=f\"present when {condition_field}={condition_value}\",\n                        actual=\"missing\",\n                        severity=Severity.ERROR,\n                        message=(\n                            f\"Field '{required_field}' required when \"\n                            f\"'{condition_field}' is '{condition_value}'\"\n                        ),\n                    )\n\n        return None\n\n    def check_backward_compatibility(\n        self, old_contract: ToolContract, new_contract: ToolContract\n    ) -> list[ContractViolation]:\n        \"\"\"\n        Check that a new version of a tool contract is\n        backward-compatible with the old version.\n        \"\"\"\n        violations = []\n\n        # Removing a required output field is a breaking change\n        old_required = set(old_contract.required_output_fields)\n        new_required = set(new_contract.required_output_fields)\n        removed_fields = old_required - new_required\n        for field_name in removed_fields:\n            if field_name not in new_contract.optional_output_fields:\n                violations.append(ContractViolation(\n                    field=field_name,\n                    expected=\"present (was required)\",\n                    actual=\"removed\",\n                    severity=Severity.ERROR,\n                    message=(\n                        f\"Breaking change: required field '{field_name}' \"\n                        f\"removed from '{new_contract.tool_name}' \"\n                        f\"(v{old_contract.version} -> v{new_contract.version})\"\n                    ),\n                ))\n\n        # Changing a field type is a breaking change\n        for field_name in old_contract.output_schema:\n            if field_name not in new_contract.output_schema:\n                continue\n            old_type = old_contract.output_schema[field_name].get(\"type\")\n            new_type = new_contract.output_schema[field_name].get(\"type\")\n            if old_type and new_type and old_type != new_type:\n                violations.append(ContractViolation(\n                    field=field_name,\n                    expected=f\"type: {old_type}\",\n                    actual=f\"type: {new_type}\",\n                    severity=Severity.ERROR,\n                    message=(\n                        f\"Breaking change: field '{field_name}' type changed \"\n                        f\"from '{old_type}' to '{new_type}'\"\n                    ),\n                ))\n\n        # Narrowing an enum is a breaking change\n        for field_name in old_contract.output_schema:\n            if field_name not in new_contract.output_schema:\n                continue\n            old_enum = set(old_contract.output_schema[field_name].get(\"enum\", []))\n            new_enum = set(new_contract.output_schema[field_name].get(\"enum\", []))\n            if old_enum and new_enum:\n                removed_values = old_enum - new_enum\n                if removed_values:\n                    violations.append(ContractViolation(\n                        field=field_name,\n                        expected=f\"enum includes {removed_values}\",\n                        actual=f\"enum: {new_enum}\",\n                        severity=Severity.ERROR,\n                        message=(\n                            f\"Breaking change: enum values {removed_values} \"\n                            f\"removed from '{field_name}'\"\n                        ),\n                    ))\n\n        # Adding new required input fields is a breaking change\n        old_required_inputs = set(old_contract.input_schema.get(\"required\", []))\n        new_required_inputs = set(new_contract.input_schema.get(\"required\", []))\n        added_required = new_required_inputs - old_required_inputs\n        for field_name in added_required:\n            violations.append(ContractViolation(\n                field=field_name,\n                expected=\"optional or absent\",\n                actual=\"required\",\n                severity=Severity.ERROR,\n                message=(\n                    f\"Breaking change: new required input field \"\n                    f\"'{field_name}' added to '{new_contract.tool_name}'\"\n                ),\n            ))\n\n        return violations\n\n    def report(self) -> dict:\n        \"\"\"Generate a validation report.\"\"\"\n        errors = [v for v in self._violations if v.severity == Severity.ERROR]\n        warnings = [v for v in self._violations if v.severity == Severity.WARNING]\n        return {\n            \"total_validations\": self._validations,\n            \"total_violations\": len(self._violations),\n            \"errors\": len(errors),\n            \"warnings\": len(warnings),\n            \"passed\": len(errors) == 0,\n            \"violations\": [\n                {\n                    \"field\": v.field,\n                    \"expected\": v.expected,\n                    \"actual\": v.actual,\n                    \"severity\": v.severity.value,\n                    \"message\": v.message,\n                }\n                for v in self._violations\n            ],\n        }\n```\n\n### Defining Consumer-Driven Contracts\n\nEach agent that consumes a tool declares what it expects. Store these as JSON files in a `contracts\u002F` directory:\n\n```json\n{\n  \"consumer\": \"buyer-agent-v2\",\n  \"producer\": \"gateway\",\n  \"metadata\": {\n    \"created\": \"2026-04-01\",\n    \"owner\": \"team-payments\"\n  },\n  \"tools\": [\n    {\n      \"tool_name\": \"create_escrow\",\n      \"version\": \"1.0\",\n      \"input_schema\": {\n        \"required\": [\"payer\", \"payee\", \"amount\", \"currency\"],\n        \"properties\": {\n          \"payer\": {\"type\": \"string\"},\n          \"payee\": {\"type\": \"string\"},\n          \"amount\": {\"type\": \"string\", \"pattern\": \"^\\\\d+\\\\.\\\\d{2}$\"},\n          \"currency\": {\"type\": \"string\", \"enum\": [\"USD\"]}\n        }\n      },\n      \"output_schema\": {\n        \"escrow_id\": {\"type\": \"string\", \"pattern\": \"^esc_\"},\n        \"status\": {\"type\": \"string\", \"enum\": [\"pending\", \"released\", \"cancelled\", \"expired\"]},\n        \"amount\": {\"type\": \"string\"},\n        \"currency\": {\"type\": \"string\"}\n      },\n      \"required_output_fields\": [\"escrow_id\", \"status\", \"amount\"],\n      \"status_codes\": [200],\n      \"constraints\": [\n        {\n          \"type\": \"field_equals\",\n          \"field\": \"status\",\n          \"value\": \"pending\",\n          \"severity\": \"error\",\n          \"message\": \"New escrows must have status 'pending'\"\n        }\n      ]\n    }\n  ]\n}\n```\n\n### Using Contracts in Tests\n\n```python\ndef test_escrow_contract_compliance(harness):\n    \"\"\"Verify gateway responses satisfy our contract.\"\"\"\n    validator = ContractValidator(contracts_dir=\"contracts\")\n    validator.load_contracts()\n\n    harness.start_cassette(\"contract_escrow\")\n\n    result = harness.execute(\"create_escrow\", {\n        \"payer\": \"test-buyer\",\n        \"payee\": \"test-seller\",\n        \"amount\": \"50.00\",\n        \"currency\": \"USD\",\n        \"conditions\": {\"delivery_by\": \"2026-12-31T00:00:00Z\"},\n    })\n\n    violations = validator.validate_response(\"create_escrow\", result)\n    harness.stop_cassette()\n\n    report = validator.report()\n    assert report[\"passed\"], (\n        f\"Contract violations: {json.dumps(report['violations'], indent=2)}\"\n    )\n\n\ndef test_backward_compatibility():\n    \"\"\"Verify a new contract version is backward-compatible.\"\"\"\n    validator = ContractValidator()\n\n    old_contract = ToolContract(\n        tool_name=\"create_escrow\",\n        version=\"1.0\",\n        input_schema={\"required\": [\"payer\", \"payee\", \"amount\"]},\n        output_schema={\n            \"status\": {\"type\": \"string\", \"enum\": [\"pending\", \"released\", \"cancelled\"]},\n        },\n        required_output_fields=[\"escrow_id\", \"status\", \"amount\"],\n    )\n\n    new_contract = ToolContract(\n        tool_name=\"create_escrow\",\n        version=\"1.1\",\n        input_schema={\"required\": [\"payer\", \"payee\", \"amount\"]},\n        output_schema={\n            \"status\": {\n                \"type\": \"string\",\n                \"enum\": [\"pending\", \"released\", \"cancelled\", \"expired\"],\n            },\n        },\n        required_output_fields=[\"escrow_id\", \"status\", \"amount\", \"created_at\"],\n    )\n\n    violations = validator.check_backward_compatibility(old_contract, new_contract)\n    # Adding \"expired\" to the enum is fine (widening)\n    # Adding \"created_at\" as required output is fine (more data)\n    assert len(violations) == 0\n```\n\n---\n\n## Chapter 6: Performance Benchmarking\n\n### Why Agent Performance Benchmarks Are Different\n\nTraditional API benchmarks measure latency and throughput for a single endpoint. Agent commerce benchmarks must measure multi-step workflows: discover a service, negotiate terms, create escrow, deliver, release, submit metrics. The total latency is the sum of individual call latencies plus your agent's processing time between calls. A 10% regression in escrow creation latency might be invisible in isolation but pushes your end-to-end workflow past the SLA when compounded with five other calls.\n\n### The AgentBenchmark Class\n\n```python\nimport statistics\nimport time\nimport tracemalloc\nimport logging\nfrom dataclasses import dataclass, field\nfrom typing import Any, Callable, Optional\n\n\nlogger = logging.getLogger(__name__)\n\n\n@dataclass\nclass BenchmarkResult:\n    \"\"\"Results from a single benchmark run.\"\"\"\n    name: str\n    iterations: int\n    total_time_ms: float\n    mean_ms: float\n    median_ms: float\n    p95_ms: float\n    p99_ms: float\n    min_ms: float\n    max_ms: float\n    std_dev_ms: float\n    throughput_ops_sec: float\n    errors: int\n    peak_memory_mb: float\n    latencies: list[float] = field(default_factory=list)\n\n\nclass AgentBenchmark:\n    \"\"\"\n    Performance benchmarking for agent commerce operations.\n    Measures latency, throughput, memory, and connection usage.\n    \"\"\"\n\n    def __init__(self, client: Any, warmup_iterations: int = 5):\n        self._client = client\n        self._warmup_iterations = warmup_iterations\n        self._results: list[BenchmarkResult] = []\n\n    def benchmark_tool(\n        self,\n        name: str,\n        tool: str,\n        input_data: dict,\n        iterations: int = 100,\n    ) -> BenchmarkResult:\n        \"\"\"Benchmark a single tool call.\"\"\"\n\n        # Warmup: discard first N iterations\n        for _ in range(self._warmup_iterations):\n            try:\n                self._client.execute(tool, input_data)\n            except Exception:\n                pass\n\n        latencies = []\n        errors = 0\n        tracemalloc.start()\n\n        start_total = time.monotonic()\n        for _ in range(iterations):\n            start = time.monotonic()\n            try:\n                self._client.execute(tool, input_data)\n            except Exception:\n                errors += 1\n            elapsed = (time.monotonic() - start) * 1000\n            latencies.append(elapsed)\n\n        total_time = (time.monotonic() - start_total) * 1000\n        _, peak_memory = tracemalloc.get_traced_memory()\n        tracemalloc.stop()\n\n        sorted_latencies = sorted(latencies)\n        result = BenchmarkResult(\n            name=name,\n            iterations=iterations,\n            total_time_ms=total_time,\n            mean_ms=statistics.mean(latencies),\n            median_ms=statistics.median(latencies),\n            p95_ms=sorted_latencies[int(len(sorted_latencies) * 0.95)],\n            p99_ms=sorted_latencies[int(len(sorted_latencies) * 0.99)],\n            min_ms=min(latencies),\n            max_ms=max(latencies),\n            std_dev_ms=statistics.stdev(latencies) if len(latencies) > 1 else 0,\n            throughput_ops_sec=(iterations \u002F total_time) * 1000 if total_time > 0 else 0,\n            errors=errors,\n            peak_memory_mb=peak_memory \u002F (1024 * 1024),\n            latencies=latencies,\n        )\n\n        self._results.append(result)\n        return result\n\n    def benchmark_workflow(\n        self,\n        name: str,\n        workflow: Callable[[], None],\n        iterations: int = 50,\n    ) -> BenchmarkResult:\n        \"\"\"Benchmark a multi-step workflow.\"\"\"\n        for _ in range(self._warmup_iterations):\n            try:\n                workflow()\n            except Exception:\n                pass\n\n        latencies = []\n        errors = 0\n        tracemalloc.start()\n\n        start_total = time.monotonic()\n        for _ in range(iterations):\n            start = time.monotonic()\n            try:\n                workflow()\n            except Exception:\n                errors += 1\n            elapsed = (time.monotonic() - start) * 1000\n            latencies.append(elapsed)\n\n        total_time = (time.monotonic() - start_total) * 1000\n        _, peak_memory = tracemalloc.get_traced_memory()\n        tracemalloc.stop()\n\n        sorted_latencies = sorted(latencies)\n        result = BenchmarkResult(\n            name=name,\n            iterations=iterations,\n            total_time_ms=total_time,\n            mean_ms=statistics.mean(latencies),\n            median_ms=statistics.median(latencies),\n            p95_ms=sorted_latencies[int(len(sorted_latencies) * 0.95)],\n            p99_ms=sorted_latencies[int(len(sorted_latencies) * 0.99)],\n            min_ms=min(latencies),\n            max_ms=max(latencies),\n            std_dev_ms=statistics.stdev(latencies) if len(latencies) > 1 else 0,\n            throughput_ops_sec=(iterations \u002F total_time) * 1000 if total_time > 0 else 0,\n            errors=errors,\n            peak_memory_mb=peak_memory \u002F (1024 * 1024),\n            latencies=latencies,\n        )\n\n        self._results.append(result)\n        return result\n\n    def compare(\n        self, baseline: BenchmarkResult, current: BenchmarkResult, threshold_pct: float = 10.0\n    ) -> dict:\n        \"\"\"Compare two benchmark results and flag regressions.\"\"\"\n        regression_fields = {}\n\n        for metric in [\"mean_ms\", \"median_ms\", \"p95_ms\", \"p99_ms\"]:\n            baseline_val = getattr(baseline, metric)\n            current_val = getattr(current, metric)\n            if baseline_val == 0:\n                continue\n            pct_change = ((current_val - baseline_val) \u002F baseline_val) * 100\n            regression_fields[metric] = {\n                \"baseline\": round(baseline_val, 2),\n                \"current\": round(current_val, 2),\n                \"change_pct\": round(pct_change, 2),\n                \"regression\": pct_change > threshold_pct,\n            }\n\n        throughput_change = 0\n        if baseline.throughput_ops_sec > 0:\n            throughput_change = (\n                (current.throughput_ops_sec - baseline.throughput_ops_sec)\n                \u002F baseline.throughput_ops_sec\n            ) * 100\n\n        any_regression = any(v[\"regression\"] for v in regression_fields.values())\n\n        return {\n            \"baseline_name\": baseline.name,\n            \"current_name\": current.name,\n            \"metrics\": regression_fields,\n            \"throughput_change_pct\": round(throughput_change, 2),\n            \"has_regression\": any_regression,\n            \"threshold_pct\": threshold_pct,\n        }\n\n    def generate_report(self) -> str:\n        \"\"\"Generate a markdown benchmark report.\"\"\"\n        lines = [\"# Agent Benchmark Report\", \"\"]\n        lines.append(f\"Generated: {time.strftime('%Y-%m-%d %H:%M:%S UTC', time.gmtime())}\")\n        lines.append(\"\")\n\n        lines.append(\"| Benchmark | Iterations | Mean (ms) | Median (ms) | P95 (ms) | P99 (ms) | Throughput (ops\u002Fs) | Errors | Memory (MB) |\")\n        lines.append(\"|---|---|---|---|---|---|---|---|---|\")\n\n        for r in self._results:\n            lines.append(\n                f\"| {r.name} | {r.iterations} | \"\n                f\"{r.mean_ms:.2f} | {r.median_ms:.2f} | \"\n                f\"{r.p95_ms:.2f} | {r.p99_ms:.2f} | \"\n                f\"{r.throughput_ops_sec:.1f} | {r.errors} | \"\n                f\"{r.peak_memory_mb:.2f} |\"\n            )\n\n        lines.append(\"\")\n        return \"\\n\".join(lines)\n```\n\n### Running Benchmarks and Catching Regressions\n\n```python\ndef test_escrow_performance_regression(harness):\n    \"\"\"Flag if escrow operations regress more than 10%.\"\"\"\n    bench = AgentBenchmark(harness, warmup_iterations=3)\n\n    # Benchmark individual operations\n    create_result = bench.benchmark_tool(\n        \"create_escrow\",\n        \"create_escrow\",\n        {\n            \"payer\": \"test-agent-a\",\n            \"payee\": \"test-agent-b\",\n            \"amount\": \"10.00\",\n            \"currency\": \"USD\",\n        },\n        iterations=50,\n    )\n\n    balance_result = bench.benchmark_tool(\n        \"get_balance\",\n        \"get_balance\",\n        {\"agent_id\": \"test-agent-a\"},\n        iterations=100,\n    )\n\n    # Benchmark full workflow\n    def escrow_workflow():\n        harness.execute(\"create_escrow\", {\n            \"payer\": \"test-agent-a\",\n            \"payee\": \"test-agent-b\",\n            \"amount\": \"1.00\",\n            \"currency\": \"USD\",\n        })\n        harness.execute(\"get_balance\", {\"agent_id\": \"test-agent-a\"})\n\n    workflow_result = bench.benchmark_workflow(\"escrow_workflow\", escrow_workflow, iterations=30)\n\n    # Generate report\n    report = bench.generate_report()\n    logger.info(\"\\n%s\", report)\n\n    # Assert no individual operation exceeds 500ms at P99\n    assert create_result.p99_ms \u003C 500, f\"create_escrow P99: {create_result.p99_ms}ms\"\n    assert balance_result.p99_ms \u003C 200, f\"get_balance P99: {balance_result.p99_ms}ms\"\n\n    # Save results for next run's comparison\n    Path(\"benchmarks\u002Flatest.json\").parent.mkdir(exist_ok=True)\n    Path(\"benchmarks\u002Flatest.json\").write_text(json.dumps({\n        \"create_escrow\": {\"mean_ms\": create_result.mean_ms, \"p99_ms\": create_result.p99_ms},\n        \"get_balance\": {\"mean_ms\": balance_result.mean_ms, \"p99_ms\": balance_result.p99_ms},\n        \"workflow\": {\"mean_ms\": workflow_result.mean_ms, \"p99_ms\": workflow_result.p99_ms},\n    }, indent=2))\n```\n\nStore benchmark baselines in your repository. On each run, load the previous baseline, compare against current results, and fail the build if any metric regresses beyond your threshold. This turns performance into a first-class CI constraint rather than something you notice three weeks later when users complain.\n\n---\n\n## Chapter 7: CI\u002FCD for Agent Deployments\n\n### Pipeline Architecture\n\nAn agent commerce CI\u002FCD pipeline has five stages. Each stage gates the next -- if any stage fails, the pipeline stops and the deploy does not happen.\n\n```\n  lint → unit → integration → chaos → deploy\n   │       │         │          │        │\n  10s     30s      2min       5min     3min\n```\n\nThe total pipeline takes about 10 minutes. This is slower than a typical web application pipeline because the chaos stage runs real failure simulations. The tradeoff is worth it: catching a retry-storm bug in CI is cheaper than catching it when it drains a production wallet.\n\n### GitHub Actions Configuration\n\n```yaml\nname: Agent Commerce CI\u002FCD\n\non:\n  push:\n    branches: [main]\n  pull_request:\n    branches: [main]\n\nenv:\n  PYTHON_VERSION: \"3.12\"\n  GREENHELIX_SANDBOX_KEY: ${{ secrets.GREENHELIX_SANDBOX_KEY }}\n\njobs:\n  lint:\n    runs-on: ubuntu-latest\n    timeout-minutes: 5\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: actions\u002Fsetup-python@v5\n        with:\n          python-version: ${{ env.PYTHON_VERSION }}\n      - run: pip install ruff mypy\n      - run: ruff check src\u002F tests\u002F\n      - run: mypy src\u002F --ignore-missing-imports\n\n  unit:\n    runs-on: ubuntu-latest\n    timeout-minutes: 5\n    needs: lint\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: actions\u002Fsetup-python@v5\n        with:\n          python-version: ${{ env.PYTHON_VERSION }}\n      - run: pip install -r requirements.txt -r requirements-test.txt\n      - run: python -m pytest tests\u002Funit\u002F -x -q --tb=short\n        env:\n          TEST_MODE: playback\n\n  integration:\n    runs-on: ubuntu-latest\n    timeout-minutes: 10\n    needs: unit\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: actions\u002Fsetup-python@v5\n        with:\n          python-version: ${{ env.PYTHON_VERSION }}\n      - run: pip install -r requirements.txt -r requirements-test.txt\n      - run: python -m pytest tests\u002Fintegration\u002F -x -q --tb=short\n        env:\n          TEST_MODE: playback\n          GREENHELIX_API_KEY: ${{ env.GREENHELIX_SANDBOX_KEY }}\n\n  chaos:\n    runs-on: ubuntu-latest\n    timeout-minutes: 15\n    needs: integration\n    if: github.ref == 'refs\u002Fheads\u002Fmain'\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: actions\u002Fsetup-python@v5\n        with:\n          python-version: ${{ env.PYTHON_VERSION }}\n      - run: pip install -r requirements.txt -r requirements-test.txt\n      - run: python -m pytest tests\u002F -m chaos -x -q --tb=short\n        env:\n          CHAOS_SEED: ${{ github.run_number }}\n          TEST_MODE: playback\n\n  deploy:\n    runs-on: ubuntu-latest\n    timeout-minutes: 10\n    needs: [integration, chaos]\n    if: github.ref == 'refs\u002Fheads\u002Fmain'\n    steps:\n      - uses: actions\u002Fcheckout@v4\n      - uses: actions\u002Fsetup-python@v5\n        with:\n          python-version: ${{ env.PYTHON_VERSION }}\n      - name: Deploy to staging\n        run: |\n          pip install -r requirements.txt\n          python deploy.py --env staging --agent-id ${{ vars.AGENT_ID }}\n        env:\n          GREENHELIX_API_KEY: ${{ secrets.GREENHELIX_STAGING_KEY }}\n\n      - name: Smoke test staging\n        run: |\n          python -m pytest tests\u002Fsmoke\u002F -x -q --tb=short\n        env:\n          GREENHELIX_API_KEY: ${{ secrets.GREENHELIX_STAGING_KEY }}\n          TARGET_ENV: staging\n\n      - name: Deploy to production\n        run: |\n          python deploy.py --env production --agent-id ${{ vars.AGENT_ID }}\n        env:\n          GREENHELIX_API_KEY: ${{ secrets.GREENHELIX_PROD_KEY }}\n```\n\n### Environment Key Management\n\nSeparate your GreenHelix API keys by environment. Never use the same key for sandbox, staging, and production. The key hierarchy:\n\n| Environment | Key Source | Wallet | Purpose |\n|---|---|---|---|\n| Local dev | `.env` file (gitignored) | Test wallet, fake funds | Developer iteration |\n| CI sandbox | GitHub secret `GREENHELIX_SANDBOX_KEY` | Sandbox wallet, free credits | Automated testing |\n| Staging | GitHub secret `GREENHELIX_STAGING_KEY` | Staging wallet, real funds (capped) | Pre-production validation |\n| Production | GitHub secret `GREENHELIX_PROD_KEY` | Production wallet, real funds | Live traffic |\n\nSet budget caps on every non-production key using the GreenHelix `set_budget_cap` tool. A runaway integration test should not be able to spend more than $5:\n\n```python\ndef configure_test_budget(api_key: str, agent_id: str) -> None:\n    \"\"\"Set conservative budget caps for test environments.\"\"\"\n    import requests\n    resp = requests.post(\n        \"https:\u002F\u002Fsandbox.greenhelix.netthe REST API\",\n        headers={\n            \"Authorization\": f\"Bearer {api_key}\",\n            \"Content-Type\": \"application\u002Fjson\",\n        },\n        json={\n            \"tool\": \"set_budget_cap\",\n            \"input\": {\n                \"agent_id\": agent_id,\n                \"daily_limit\": \"5.00\",\n                \"monthly_limit\": \"50.00\",\n                \"per_transaction_limit\": \"1.00\",\n                \"currency\": \"USD\",\n            },\n        },\n    )\n    resp.raise_for_status()\n```\n\n### Rollback Triggers\n\nDefine explicit rollback criteria. If any of these conditions are true after a deploy, automatically roll back:\n\n```python\nimport requests\nimport sys\n\n\ndef check_rollback_criteria(\n    api_key: str,\n    agent_id: str,\n    base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n) -> bool:\n    \"\"\"Return True if a rollback is needed.\"\"\"\n    session = requests.Session()\n    session.headers.update({\n        \"Authorization\": f\"Bearer {api_key}\",\n        \"Content-Type\": \"application\u002Fjson\",\n    })\n\n    def execute(tool: str, input_data: dict) -> dict:\n        resp = session.post(\n            f\"{base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        return resp.json() if resp.status_code == 200 else {\"error\": resp.status_code}\n\n    # Check 1: Agent is reachable and registered\n    identity = execute(\"get_agent_identity\", {\"agent_id\": agent_id})\n    if \"error\" in identity:\n        print(f\"ROLLBACK: Agent identity check failed: {identity}\")\n        return True\n\n    # Check 2: Trust score hasn't dropped\n    trust = execute(\"get_trust_score\", {\"agent_id\": agent_id})\n    if trust.get(\"score\", 0) \u003C 0.5:\n        print(f\"ROLLBACK: Trust score below threshold: {trust.get('score')}\")\n        return True\n\n    # Check 3: No unusual error rate in recent metrics\n    metrics = execute(\"get_agent_metrics\", {\"agent_id\": agent_id, \"window\": \"5m\"})\n    error_rate = metrics.get(\"error_rate\", 0)\n    if error_rate > 0.05:  # More than 5% errors\n        print(f\"ROLLBACK: Error rate too high: {error_rate}\")\n        return True\n\n    # Check 4: Balance is not draining unexpectedly\n    balance = execute(\"get_balance\", {\"agent_id\": agent_id})\n    balance_val = float(balance.get(\"balance\", \"0\"))\n    if balance_val \u003C 10.0:  # Minimum operating balance\n        print(f\"ROLLBACK: Balance critically low: {balance_val}\")\n        return True\n\n    print(\"All rollback checks passed\")\n    return False\n\n\nif __name__ == \"__main__\":\n    import os\n    should_rollback = check_rollback_criteria(\n        api_key=os.environ[\"GREENHELIX_API_KEY\"],\n        agent_id=os.environ[\"AGENT_ID\"],\n    )\n    sys.exit(1 if should_rollback else 0)\n```\n\nCall this script as a post-deploy step. If it exits with code 1, your pipeline triggers a rollback to the previous version.\n\n---\n\n## Chapter 8: Canary Releases\n\n### The Case for Canary Deployments\n\nA canary release deploys a new agent version to a small percentage of traffic before rolling it out fully. This is standard practice for web services, but agent commerce adds a complication: agents are stateful. A canary agent that creates an escrow must be able to see that escrow through to completion, even if it is rolled back. This means your canary strategy must handle in-flight transactions gracefully.\n\n### Canary Deployment Architecture\n\nThe canary pattern for GreenHelix agents uses two agent registrations with a traffic router:\n\n```\n                    ┌──────────────┐\n                    │  Traffic     │\n    Incoming ──────▶│  Router      │\n    Requests        │  (5%\u002F95%)    │\n                    └──────┬───────┘\n                           │\n                    ┌──────┴───────┐\n                    │              │\n               ┌────▼────┐  ┌─────▼─────┐\n               │ Canary  │  │ Stable    │\n               │ v2.1.0  │  │ v2.0.0   │\n               │  (5%)   │  │  (95%)   │\n               └─────────┘  └──────────┘\n```\n\nBoth versions share the same GreenHelix wallet but use different agent IDs (e.g., `my-agent` and `my-agent-canary`). This lets you track metrics separately while maintaining a single financial identity.\n\n### The CanaryController Class\n\n```python\nimport time\nimport logging\nimport threading\nfrom dataclasses import dataclass, field\nfrom typing import Any, Callable, Optional\n\n\nlogger = logging.getLogger(__name__)\n\n\n@dataclass\nclass CanaryMetrics:\n    \"\"\"Metrics collected during a canary deployment.\"\"\"\n    requests_total: int = 0\n    requests_success: int = 0\n    requests_error: int = 0\n    latency_sum_ms: float = 0\n    latency_samples: list[float] = field(default_factory=list)\n    start_time: float = field(default_factory=time.time)\n\n    @property\n    def error_rate(self) -> float:\n        if self.requests_total == 0:\n            return 0.0\n        return self.requests_error \u002F self.requests_total\n\n    @property\n    def mean_latency_ms(self) -> float:\n        if not self.latency_samples:\n            return 0.0\n        return self.latency_sum_ms \u002F len(self.latency_samples)\n\n    @property\n    def uptime_seconds(self) -> float:\n        return time.time() - self.start_time\n\n\n@dataclass\nclass CanaryConfig:\n    \"\"\"Configuration for a canary deployment.\"\"\"\n    stable_agent_id: str\n    canary_agent_id: str\n    initial_weight_pct: float = 5.0\n    promotion_steps: list[float] = field(\n        default_factory=lambda: [5.0, 25.0, 50.0, 100.0]\n    )\n    step_duration_seconds: float = 300  # 5 minutes per step\n    error_rate_threshold: float = 0.05  # 5% error rate triggers rollback\n    latency_threshold_ms: float = 1000  # P95 latency threshold\n    min_requests_before_eval: int = 20  # Minimum sample size\n\n\nclass CanaryController:\n    \"\"\"\n    Manages canary deployments for GreenHelix agents.\n    Routes traffic, monitors health, and auto-promotes or rolls back.\n    \"\"\"\n\n    def __init__(\n        self,\n        config: CanaryConfig,\n        stable_client: Any,\n        canary_client: Any,\n        metrics_client: Optional[Any] = None,\n    ):\n        self.config = config\n        self._stable = stable_client\n        self._canary = canary_client\n        self._metrics_client = metrics_client\n\n        self._current_weight: float = 0.0\n        self._current_step: int = 0\n        self._stable_metrics = CanaryMetrics()\n        self._canary_metrics = CanaryMetrics()\n        self._state: str = \"idle\"  # idle, running, promoted, rolled_back\n        self._lock = threading.Lock()\n        self._rollback_reason: Optional[str] = None\n\n    def start(self) -> None:\n        \"\"\"Begin the canary deployment.\"\"\"\n        self._state = \"running\"\n        self._current_weight = self.config.initial_weight_pct\n        self._current_step = 0\n        self._stable_metrics = CanaryMetrics()\n        self._canary_metrics = CanaryMetrics()\n        logger.info(\n            \"Canary started: %s at %.1f%% traffic\",\n            self.config.canary_agent_id,\n            self._current_weight,\n        )\n\n    def route_request(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Route a request to either stable or canary based on weight.\"\"\"\n        import random\n\n        if self._state != \"running\":\n            return self._stable.execute(tool, input_data)\n\n        use_canary = random.random() * 100 \u003C self._current_weight\n        client = self._canary if use_canary else self._stable\n        metrics = self._canary_metrics if use_canary else self._stable_metrics\n\n        start = time.monotonic()\n        try:\n            result = client.execute(tool, input_data)\n            elapsed_ms = (time.monotonic() - start) * 1000\n\n            with self._lock:\n                metrics.requests_total += 1\n                metrics.latency_sum_ms += elapsed_ms\n                metrics.latency_samples.append(elapsed_ms)\n\n                status = result.get(\"status_code\", 0)\n                if 200 \u003C= status \u003C 400:\n                    metrics.requests_success += 1\n                else:\n                    metrics.requests_error += 1\n\n            return result\n\n        except Exception as exc:\n            with self._lock:\n                metrics.requests_total += 1\n                metrics.requests_error += 1\n            raise\n\n    def evaluate(self) -> dict:\n        \"\"\"\n        Evaluate canary health. Returns action: 'promote', 'hold', or 'rollback'.\n        \"\"\"\n        with self._lock:\n            canary = self._canary_metrics\n            stable = self._stable_metrics\n\n        if canary.requests_total \u003C self.config.min_requests_before_eval:\n            return {\n                \"action\": \"hold\",\n                \"reason\": (\n                    f\"Insufficient canary samples: \"\n                    f\"{canary.requests_total}\u002F{self.config.min_requests_before_eval}\"\n                ),\n                \"canary_metrics\": self._metrics_snapshot(canary),\n                \"stable_metrics\": self._metrics_snapshot(stable),\n            }\n\n        # Check error rate\n        if canary.error_rate > self.config.error_rate_threshold:\n            error_detail = (\n                f\"Canary error rate {canary.error_rate:.2%} exceeds \"\n                f\"threshold {self.config.error_rate_threshold:.2%}\"\n            )\n            return {\n                \"action\": \"rollback\",\n                \"reason\": error_detail,\n                \"canary_metrics\": self._metrics_snapshot(canary),\n                \"stable_metrics\": self._metrics_snapshot(stable),\n            }\n\n        # Check latency\n        if canary.latency_samples:\n            sorted_latencies = sorted(canary.latency_samples)\n            p95_idx = int(len(sorted_latencies) * 0.95)\n            p95 = sorted_latencies[p95_idx] if p95_idx \u003C len(sorted_latencies) else 0\n\n            if p95 > self.config.latency_threshold_ms:\n                latency_detail = (\n                    f\"Canary P95 latency {p95:.0f}ms exceeds \"\n                    f\"threshold {self.config.latency_threshold_ms:.0f}ms\"\n                )\n                return {\n                    \"action\": \"rollback\",\n                    \"reason\": latency_detail,\n                    \"canary_metrics\": self._metrics_snapshot(canary),\n                    \"stable_metrics\": self._metrics_snapshot(stable),\n                }\n\n        # Compare error rates: canary should not be significantly worse\n        if (\n            stable.requests_total >= self.config.min_requests_before_eval\n            and canary.error_rate > stable.error_rate * 2\n            and canary.error_rate > 0.01\n        ):\n            compare_detail = (\n                f\"Canary error rate {canary.error_rate:.2%} is >2x \"\n                f\"stable error rate {stable.error_rate:.2%}\"\n            )\n            return {\n                \"action\": \"rollback\",\n                \"reason\": compare_detail,\n                \"canary_metrics\": self._metrics_snapshot(canary),\n                \"stable_metrics\": self._metrics_snapshot(stable),\n            }\n\n        # Check if enough time has passed for promotion\n        if canary.uptime_seconds >= self.config.step_duration_seconds:\n            return {\n                \"action\": \"promote\",\n                \"reason\": (\n                    f\"Canary healthy after {canary.uptime_seconds:.0f}s \"\n                    f\"at {self._current_weight:.0f}% traffic\"\n                ),\n                \"canary_metrics\": self._metrics_snapshot(canary),\n                \"stable_metrics\": self._metrics_snapshot(stable),\n            }\n\n        return {\n            \"action\": \"hold\",\n            \"reason\": \"Waiting for evaluation period to complete\",\n            \"canary_metrics\": self._metrics_snapshot(canary),\n            \"stable_metrics\": self._metrics_snapshot(stable),\n        }\n\n    def promote(self) -> bool:\n        \"\"\"Advance to the next traffic weight step. Returns True if fully promoted.\"\"\"\n        self._current_step += 1\n\n        if self._current_step >= len(self.config.promotion_steps):\n            self._state = \"promoted\"\n            self._current_weight = 100.0\n            logger.info(\"Canary fully promoted to 100%% traffic\")\n            return True\n\n        self._current_weight = self.config.promotion_steps[self._current_step]\n        # Reset metrics for the new step\n        with self._lock:\n            self._canary_metrics = CanaryMetrics()\n            self._stable_metrics = CanaryMetrics()\n\n        logger.info(\n            \"Canary promoted to %.1f%% traffic (step %d\u002F%d)\",\n            self._current_weight,\n            self._current_step + 1,\n            len(self.config.promotion_steps),\n        )\n        return False\n\n    def rollback(self, reason: str) -> None:\n        \"\"\"Roll back the canary deployment.\"\"\"\n        self._state = \"rolled_back\"\n        self._current_weight = 0.0\n        self._rollback_reason = reason\n        logger.warning(\"Canary rolled back: %s\", reason)\n\n    def run_deployment(self) -> dict:\n        \"\"\"\n        Run the full canary deployment lifecycle.\n        Returns the final state and metrics.\n        \"\"\"\n        self.start()\n\n        while self._state == \"running\":\n            time.sleep(10)  # Evaluate every 10 seconds\n            evaluation = self.evaluate()\n\n            if evaluation[\"action\"] == \"rollback\":\n                self.rollback(evaluation[\"reason\"])\n                break\n\n            elif evaluation[\"action\"] == \"promote\":\n                fully_promoted = self.promote()\n                if fully_promoted:\n                    break\n\n            # \"hold\" means keep waiting\n\n        return {\n            \"final_state\": self._state,\n            \"final_weight\": self._current_weight,\n            \"rollback_reason\": self._rollback_reason,\n            \"canary_metrics\": self._metrics_snapshot(self._canary_metrics),\n            \"stable_metrics\": self._metrics_snapshot(self._stable_metrics),\n        }\n\n    def _metrics_snapshot(self, metrics: CanaryMetrics) -> dict:\n        sorted_latencies = sorted(metrics.latency_samples) if metrics.latency_samples else []\n        p95_idx = int(len(sorted_latencies) * 0.95) if sorted_latencies else 0\n        return {\n            \"requests_total\": metrics.requests_total,\n            \"requests_success\": metrics.requests_success,\n            \"requests_error\": metrics.requests_error,\n            \"error_rate\": round(metrics.error_rate, 4),\n            \"mean_latency_ms\": round(metrics.mean_latency_ms, 2),\n            \"p95_latency_ms\": round(sorted_latencies[p95_idx], 2) if sorted_latencies else 0,\n            \"uptime_seconds\": round(metrics.uptime_seconds, 1),\n        }\n\n    @property\n    def state(self) -> str:\n        return self._state\n\n    @property\n    def current_weight(self) -> float:\n        return self._current_weight\n```\n\n### Using the CanaryController in Practice\n\n```python\ndef deploy_canary(stable_api_key: str, canary_api_key: str) -> dict:\n    \"\"\"Deploy a new agent version as a canary.\"\"\"\n    from my_agent import AgentClient\n\n    stable = AgentClient(api_key=stable_api_key, agent_id=\"my-agent\")\n    canary = AgentClient(api_key=canary_api_key, agent_id=\"my-agent-canary\")\n\n    config = CanaryConfig(\n        stable_agent_id=\"my-agent\",\n        canary_agent_id=\"my-agent-canary\",\n        initial_weight_pct=5.0,\n        promotion_steps=[5.0, 25.0, 50.0, 100.0],\n        step_duration_seconds=300,     # 5 minutes per step\n        error_rate_threshold=0.05,     # 5% errors trigger rollback\n        latency_threshold_ms=1000,     # 1 second P95 threshold\n        min_requests_before_eval=20,\n    )\n\n    controller = CanaryController(config, stable, canary)\n    result = controller.run_deployment()\n\n    if result[\"final_state\"] == \"rolled_back\":\n        print(f\"Canary FAILED: {result['rollback_reason']}\")\n        print(f\"Canary metrics: {result['canary_metrics']}\")\n        print(f\"Stable metrics: {result['stable_metrics']}\")\n    elif result[\"final_state\"] == \"promoted\":\n        print(\"Canary PROMOTED to 100% traffic\")\n        print(f\"Final canary metrics: {result['canary_metrics']}\")\n\n    return result\n```\n\n### Handling In-Flight Transactions During Rollback\n\nThe most important detail: when you roll back a canary, do not kill the canary agent immediately. In-flight escrows created by the canary must complete. The rollback stops routing new traffic to the canary, but the canary agent continues running until all its active escrows are settled:\n\n```python\ndef graceful_rollback(\n    controller: CanaryController,\n    canary_client: Any,\n    reason: str,\n    drain_timeout_seconds: int = 600,\n) -> None:\n    \"\"\"Roll back canary traffic while draining in-flight transactions.\"\"\"\n    # Stop new traffic immediately\n    controller.rollback(reason)\n\n    # Check for in-flight escrows\n    active_escrows = canary_client.execute(\"list_escrows\", {\n        \"agent_id\": controller.config.canary_agent_id,\n        \"status\": \"pending\",\n    })\n\n    pending = active_escrows.get(\"body\", {}).get(\"escrows\", [])\n    if not pending:\n        logger.info(\"No in-flight transactions, canary shutdown clean\")\n        return\n\n    logger.info(\n        \"Draining %d in-flight escrows before canary shutdown\", len(pending)\n    )\n\n    deadline = time.time() + drain_timeout_seconds\n    while time.time() \u003C deadline:\n        remaining = canary_client.execute(\"list_escrows\", {\n            \"agent_id\": controller.config.canary_agent_id,\n            \"status\": \"pending\",\n        })\n        pending_count = len(remaining.get(\"body\", {}).get(\"escrows\", []))\n        if pending_count == 0:\n            logger.info(\"All in-flight transactions drained\")\n            return\n        logger.info(\n            \"Waiting for %d in-flight transactions to complete...\",\n            pending_count,\n        )\n        time.sleep(30)\n\n    logger.warning(\n        \"Drain timeout reached with %d transactions still pending. \"\n        \"These will need manual resolution.\",\n        pending_count,\n    )\n```\n\n### Monitoring Canary Health via GreenHelix Metrics\n\nUse GreenHelix's built-in metrics to monitor canary health without building custom instrumentation. The `submit_metrics` and `get_agent_metrics` tools provide per-agent observability:\n\n```python\ndef monitor_canary_via_greenhelix(\n    api_key: str,\n    stable_agent_id: str,\n    canary_agent_id: str,\n) -> dict:\n    \"\"\"Compare canary and stable metrics using GreenHelix's metrics tools.\"\"\"\n    import requests\n\n    session = requests.Session()\n    session.headers.update({\n        \"Authorization\": f\"Bearer {api_key}\",\n        \"Content-Type\": \"application\u002Fjson\",\n    })\n    base_url = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n    def get_metrics(agent_id: str) -> dict:\n        resp = session.post(\n            f\"{base_url}\u002Fv1\",\n            json={\n                \"tool\": \"get_agent_metrics\",\n                \"input\": {\"agent_id\": agent_id, \"window\": \"5m\"},\n            },\n        )\n        return resp.json() if resp.status_code == 200 else {}\n\n    stable_metrics = get_metrics(stable_agent_id)\n    canary_metrics = get_metrics(canary_agent_id)\n\n    comparison = {\n        \"stable\": {\n            \"error_rate\": stable_metrics.get(\"error_rate\", 0),\n            \"mean_latency_ms\": stable_metrics.get(\"mean_latency_ms\", 0),\n            \"requests\": stable_metrics.get(\"request_count\", 0),\n        },\n        \"canary\": {\n            \"error_rate\": canary_metrics.get(\"error_rate\", 0),\n            \"mean_latency_ms\": canary_metrics.get(\"mean_latency_ms\", 0),\n            \"requests\": canary_metrics.get(\"request_count\", 0),\n        },\n    }\n\n    # Flag if canary is significantly worse\n    stable_err = comparison[\"stable\"][\"error_rate\"]\n    canary_err = comparison[\"canary\"][\"error_rate\"]\n    comparison[\"canary_healthy\"] = canary_err \u003C= max(stable_err * 2, 0.05)\n\n    return comparison\n```\n\n---\n\n## What's Next\n\nThis guide covered the complete testing and QA toolkit for agent commerce on GreenHelix: the testing pyramid adapted for multi-agent systems, the `AgentTestHarness` for recording and replaying API interactions, the `GreenHelixMock` for isolated unit testing with stateful escrow simulation, the `ChaosInjector` for validating resilience against real failure modes, the `ContractValidator` for catching breaking changes between agent versions, the `AgentBenchmark` for performance regression detection, CI\u002FCD pipeline configuration with proper environment isolation, and the `CanaryController` for progressive rollouts with automatic rollback.\n\nThe six classes -- `AgentTestHarness`, `GreenHelixMock`, `ChaosInjector`, `ContractValidator`, `AgentBenchmark`, and `CanaryController` -- compose into a testing stack that covers every layer from unit to production deployment. Start with the harness and mocks for your immediate test gaps, add chaos testing when you have basic coverage, and implement canary releases when you are deploying frequently enough that manual validation becomes a bottleneck.\n\nFor the agent commerce patterns these tests validate, see the companion guides:\n\n- **Agent-to-Agent Commerce: Escrow, Payments, and Trust** (P4) -- the escrow patterns, marketplace discovery, and payment flows that the test harness records and the contract validator checks.\n- **Locking Down Agent Commerce** (P7) -- the security hardening that chaos testing validates under failure conditions.\n- **The AI Agent FinOps Playbook** (P6) -- the budget caps and spending controls that prevent runaway test costs and protect canary deployments.\n- **Agent Observability Deep Dive** (P11) -- the monitoring infrastructure that feeds canary health evaluation and benchmark reporting.\n\nFor the full API reference and tool catalog (all 128 tools), visit the GreenHelix developer documentation at [https:\u002F\u002Fapi.greenhelix.net\u002Fdocs](https:\u002F\u002Fapi.greenhelix.net\u002Fdocs).\n\n---\n\n*Price: $39 | Format: Digital Guide | Updates: Lifetime access*\n\n",{"name":5,"tags":24,"type":30,"author":34,"install":35,"license":15,"version":36,"metadata":37,"price_usd":42,"executable":20,"credentials":43,"description":7,"content_type":44,"compatibility":45},[25,26,27,28,29,30,31,32,33],"testing","qa","chaos-testing","contract-testing","ci-cd","guide","greenhelix","openclaw","ai-agent","felix-agent","none","1.3.1",{"openclaw":38},{"requires":39,"primaryEnv":41},{"env":40},[41],"GREENHELIX_API_KEY",39,[41],"markdown",[32],"master","4aa004da461d820f4ea5499e58eb8d196cf99016","community\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-testing-qa-toolkit",0,"https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge","https:\u002F\u002Fskill-explorer-rho.vercel.app","https:\u002F\u002Fgithub.com\u002FLord1Egypt","Unbreakable. Unstoppable. Unmatched⚡.\r\n Speaker of machine tongues 🤖  | World-builder of decentralized dreams 🌐 | Defender of the digital realm🛡️.","2026-06-10 08:21:01",{"source":8,"skillName":5,"commands":56,"prompt":66,"zipAvailable":67},[57,60,63],{"tool":58,"command":59},"npx","npx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-testing-qa-toolkit",{"tool":61,"command":62},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-testing-qa-toolkit",{"tool":64,"command":65},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-testing-qa-toolkit","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-testing-qa-toolkit\u002FSKILL.md",true,[],[70,77,84,91,98,105],{"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},"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":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},"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":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},"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":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},"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":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},"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":106,"name":107,"nameZh":6,"description":108,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":109,"categories":110,"keywords":111,"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",[],[]]