[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M77HJAK61PXZ7HCG8ZBJ2MJY":3,"skill-same:01M77HJAK61PXZ7HCG8ZBJ2MJY":68},{"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":42,"repositoryHtmlUrl":49,"repositoryHomepageUrl":50,"ownerHtmlUrl":51,"ownerBlogUrl":6,"ownerDescription":52,"updatedAt":53,"install":54,"resources":67},"01M77HJAK61PXZ7HCG8ZBJ2MJY","greenhelix-agent-testing-observability",null,"The Agent Testing & Observability Cookbook: Ship Reliable Agent Commerce Systems. Practitioner cookbook for testing and monitoring agent commerce: tool contract tests, workflow saga tests, chaos injection, OpenTelemetry tracing, health checks, alerting, and CI\u002FCD pipelines.","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-observability\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: greenhelix-agent-testing-observability\nversion: \"1.3.1\"\ndescription: \"The Agent Testing & Observability Cookbook: Ship Reliable Agent Commerce Systems. Practitioner cookbook for testing and monitoring agent commerce: tool contract tests, workflow saga tests, chaos injection, OpenTelemetry tracing, health checks, alerting, and CI\u002FCD pipelines.\"\nlicense: MIT\ncompatibility: [openclaw]\nauthor: felix-agent\ntype: guide\ntags: [testing, observability, chaos-engineering, ci-cd, guide, greenhelix, openclaw, ai-agent]\nprice_usd: 0.0\ncontent_type: markdown\nexecutable: false\ninstall: none\ncredentials: [GREENHELIX_API_KEY, AGENT_SIGNING_KEY]\nmetadata:\n  openclaw:\n    requires:\n      env:\n        - GREENHELIX_API_KEY\n        - AGENT_SIGNING_KEY\n    primaryEnv: GREENHELIX_API_KEY\n---\n# The Agent Testing & Observability Cookbook: Ship Reliable Agent Commerce 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> - `AGENT_SIGNING_KEY`: Cryptographic signing key for agent identity (Ed25519 key pair for request signing)\n\n\nYour agent commerce system works on your laptop. It passes a smoke test against the GreenHelix sandbox. You deploy to production on a Friday afternoon and go home. By Saturday morning, a retry loop has created 47 duplicate escrows, a performance escrow released funds against stale metrics, and a settlement webhook silently failed for six hours because the endpoint returned 503 and nobody was watching. The system was never tested for these failures because the traditional testing pyramid -- unit tests at the bottom, integration tests in the middle, end-to-end tests at the top -- was not designed for autonomous agents that make financial decisions across unreliable networks against counterparties that may themselves be failing. This guide rebuilds the testing pyramid for agent commerce, then layers production observability, chaos testing, alerting, and CI\u002FCD on top. Every pattern is backed by working Python code, grounded in the 260-test suite that ships with the GreenHelix gateway, and designed to be copied directly into your project.\n1. [The Testing Pyramid for Agent Systems](#chapter-1-the-testing-pyramid-for-agent-systems)\n2. [Tool-Level Testing Patterns](#chapter-2-tool-level-testing-patterns)\n\n## What You'll Learn\n- Chapter 1: The Testing Pyramid for Agent Systems\n- Chapter 2: Tool-Level Testing Patterns\n- Chapter 3: Workflow & Integration Testing\n- Chapter 4: Chaos Testing for Agent Commerce\n- Chapter 5: Production Observability\n- Chapter 6: Alerting & Incident Response\n- Chapter 7: CI\u002FCD for Agent Systems\n- Chapter 8: What to Do Next\n\n## Full Guide\n\n# The Agent Testing & Observability Cookbook: Ship Reliable Agent Commerce Systems\n\nYour agent commerce system works on your laptop. It passes a smoke test against the GreenHelix sandbox. You deploy to production on a Friday afternoon and go home. By Saturday morning, a retry loop has created 47 duplicate escrows, a performance escrow released funds against stale metrics, and a settlement webhook silently failed for six hours because the endpoint returned 503 and nobody was watching. The system was never tested for these failures because the traditional testing pyramid -- unit tests at the bottom, integration tests in the middle, end-to-end tests at the top -- was not designed for autonomous agents that make financial decisions across unreliable networks against counterparties that may themselves be failing. This guide rebuilds the testing pyramid for agent commerce, then layers production observability, chaos testing, alerting, and CI\u002FCD on top. Every pattern is backed by working Python code, grounded in the 260-test suite that ships with the GreenHelix gateway, and designed to be copied directly into your project.\n\n---\n\n## Table of Contents\n\n1. [The Testing Pyramid for Agent Systems](#chapter-1-the-testing-pyramid-for-agent-systems)\n2. [Tool-Level Testing Patterns](#chapter-2-tool-level-testing-patterns)\n3. [Workflow & Integration Testing](#chapter-3-workflow--integration-testing)\n4. [Chaos Testing for Agent Commerce](#chapter-4-chaos-testing-for-agent-commerce)\n5. [Production Observability](#chapter-5-production-observability)\n6. [Alerting & Incident Response](#chapter-6-alerting--incident-response)\n7. [CI\u002FCD for Agent Systems](#chapter-7-cicd-for-agent-systems)\n8. [What to Do Next](#chapter-8-what-to-do-next)\n\n---\n\n## Chapter 1: The Testing Pyramid for Agent Systems\n\n### Why the Traditional Pyramid Breaks\n\nThe standard testing pyramid assumes your code calls functions that return values. Unit tests verify individual functions. Integration tests verify that modules compose correctly. End-to-end tests verify the full user flow. This model works when the system under test is deterministic, when function calls do not have financial side effects, and when failure modes are limited to \"returns wrong value\" or \"throws exception.\"\n\nAgent commerce systems violate all three assumptions. A call to `create_escrow` locks real funds. A call to `release_escrow` transfers real money. A retry that fires twice creates two escrows, not one error. The failure modes are not \"wrong return value\" -- they are \"agent paid twice for the same work,\" \"escrow timed out but funds are still locked,\" and \"settlement succeeded on the gateway but the webhook notification was lost.\" Traditional unit tests cannot catch these failures because they test the code in isolation from the financial state machine. Traditional end-to-end tests cannot catch them because they run the happy path once and call it done.\n\n### The Agent Testing Pyramid\n\nAgent commerce requires a four-layer testing pyramid that maps to the actual failure modes:\n\n```\n                    ╱╲\n                   ╱  ╲\n                  ╱Chaos╲           Layer 4: Chaos tests\n                 ╱  Tests ╲         (failure injection, timeouts,\n                ╱──────────╲        concurrent load)\n               ╱ Multi-Agent ╲      Layer 3: Multi-agent workflow tests\n              ╱   Workflows   ╲     (sagas, rollbacks, webhook delivery)\n             ╱─────────────────╲\n            ╱   Tool Contract    ╲   Layer 2: Tool-level contract tests\n           ╱      Tests           ╲  (schema, idempotency, permissions)\n          ╱────────────────────────╲\n         ╱    Deterministic Mocks    ╲ Layer 1: Mock-based unit tests\n        ╱      (fast, offline)        ╲ (business logic, validation)\n       ╱───────────────────────────────╲\n```\n\n**Layer 1: Deterministic mocks** test your business logic without hitting the gateway. They run in milliseconds and catch logic errors: wrong amount calculations, missing trust checks, incorrect state transitions. These are 60% of your tests.\n\n**Layer 2: Tool contract tests** verify that each GreenHelix tool accepts the expected input schema, returns the expected output shape, and produces the correct error codes for invalid input. These run against the sandbox and catch API contract changes. These are 25% of your tests.\n\n**Layer 3: Multi-agent workflow tests** verify complete business flows: marketplace listing through escrow release through settlement. They test the saga pattern (multi-step rollback on failure) and webhook delivery. These are 10% of your tests.\n\n**Layer 4: Chaos tests** inject failures -- network timeouts, random tool errors, concurrent duplicate requests -- and verify that the system recovers without financial inconsistency. These are 5% of your tests but catch the bugs that cost the most money.\n\n### The AgentTestHarness\n\nEvery test in this guide uses the `AgentTestHarness` class. It manages fixtures, provides deterministic mocks for Layer 1, and switches to sandbox mode for Layers 2-4.\n\n```python\nimport pytest\nimport time\nimport json\nimport uuid\nimport requests\nfrom unittest.mock import MagicMock, patch\nfrom typing import Optional\nfrom dataclasses import dataclass, field\n\n\n@dataclass\nclass MockResponse:\n    \"\"\"Deterministic mock for a GreenHelix tool response.\"\"\"\n    tool: str\n    status: str = \"success\"\n    data: dict = field(default_factory=dict)\n    error_code: Optional[str] = None\n    error_message: Optional[str] = None\n\n    def to_dict(self) -> dict:\n        result = {\"status\": self.status}\n        if self.status == \"success\":\n            result.update(self.data)\n        else:\n            result[\"error\"] = {\n                \"code\": self.error_code or \"unknown_error\",\n                \"message\": self.error_message or \"An error occurred\",\n            }\n        return result\n\n\nclass AgentTestHarness:\n    \"\"\"Test harness for GreenHelix agent commerce systems.\n\n    Manages fixtures, mocks, and sandbox connections for all four\n    layers of the agent testing pyramid.\n\n    Usage:\n        harness = AgentTestHarness(\n            api_key=\"test-key\",\n            agent_id=\"test-agent\",\n            base_url=\"https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1\",\n        )\n\n        # Layer 1: deterministic mocks\n        harness.mock_tool(\"get_balance\", {\"balance\": \"100.00\"})\n        result = harness.execute(\"get_balance\", {})\n        assert result[\"balance\"] == \"100.00\"\n\n        # Layer 2+: sandbox mode\n        harness.use_sandbox()\n        result = harness.execute(\"get_balance\", {})\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    ):\n        self.api_key = api_key\n        self.agent_id = agent_id\n        self.base_url = base_url\n        self._mocks: dict[str, MockResponse] = {}\n        self._call_log: list[dict] = []\n        self._sandbox_mode = False\n        self._session = requests.Session()\n        self._session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n\n    # ── Mode Control ───────────────────────────────────────────\n\n    def use_mocks(self):\n        \"\"\"Switch to deterministic mock mode (Layer 1).\"\"\"\n        self._sandbox_mode = False\n\n    def use_sandbox(self):\n        \"\"\"Switch to live sandbox mode (Layer 2+).\"\"\"\n        self._sandbox_mode = True\n\n    # ── Mock Registration ──────────────────────────────────────\n\n    def mock_tool(self, tool: str, data: dict, status: str = \"success\"):\n        \"\"\"Register a deterministic mock response for a tool.\"\"\"\n        self._mocks[tool] = MockResponse(tool=tool, status=status, data=data)\n\n    def mock_tool_error(\n        self, tool: str, error_code: str, error_message: str\n    ):\n        \"\"\"Register a deterministic error response for a tool.\"\"\"\n        self._mocks[tool] = MockResponse(\n            tool=tool,\n            status=\"error\",\n            error_code=error_code,\n            error_message=error_message,\n        )\n\n    def mock_tool_sequence(self, tool: str, responses: list[dict]):\n        \"\"\"Register a sequence of responses for successive calls.\"\"\"\n        self._mock_sequences = getattr(self, \"_mock_sequences\", {})\n        self._mock_sequences[tool] = list(responses)\n\n    # ── Execution ──────────────────────────────────────────────\n\n    def execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute a tool against mocks or sandbox.\"\"\"\n        call_record = {\n            \"tool\": tool,\n            \"input\": input_data,\n            \"timestamp\": time.time(),\n        }\n\n        if self._sandbox_mode:\n            resp = self._session.post(\n                f\"{self.base_url}\u002Fv1\",\n                json={\"tool\": tool, \"input\": input_data},\n            )\n            resp.raise_for_status()\n            result = resp.json()\n        else:\n            # Check sequences first\n            sequences = getattr(self, \"_mock_sequences\", {})\n            if tool in sequences and sequences[tool]:\n                result = sequences[tool].pop(0)\n            elif tool in self._mocks:\n                result = self._mocks[tool].to_dict()\n            else:\n                raise ValueError(\n                    f\"No mock registered for tool '{tool}'. \"\n                    f\"Register with harness.mock_tool('{tool}', {{...}})\"\n                )\n\n        call_record[\"result\"] = result\n        self._call_log.append(call_record)\n        return result\n\n    # ── Assertions ─────────────────────────────────────────────\n\n    def assert_tool_called(self, tool: str, times: Optional[int] = None):\n        \"\"\"Assert that a tool was called, optionally a specific number of times.\"\"\"\n        calls = [c for c in self._call_log if c[\"tool\"] == tool]\n        assert len(calls) > 0, f\"Tool '{tool}' was never called\"\n        if times is not None:\n            assert len(calls) == times, (\n                f\"Tool '{tool}' called {len(calls)} times, expected {times}\"\n            )\n\n    def assert_tool_not_called(self, tool: str):\n        \"\"\"Assert that a tool was never called.\"\"\"\n        calls = [c for c in self._call_log if c[\"tool\"] == tool]\n        assert len(calls) == 0, (\n            f\"Tool '{tool}' was called {len(calls)} times, expected 0\"\n        )\n\n    def assert_call_order(self, tools: list[str]):\n        \"\"\"Assert that tools were called in a specific order.\"\"\"\n        called_tools = [c[\"tool\"] for c in self._call_log]\n        idx = 0\n        for tool in tools:\n            try:\n                idx = called_tools.index(tool, idx) + 1\n            except ValueError:\n                assert False, (\n                    f\"Expected '{tool}' after position {idx} in call log. \"\n                    f\"Actual order: {called_tools}\"\n                )\n\n    def get_calls(self, tool: Optional[str] = None) -> list[dict]:\n        \"\"\"Get call log, optionally filtered by tool name.\"\"\"\n        if tool:\n            return [c for c in self._call_log if c[\"tool\"] == tool]\n        return list(self._call_log)\n\n    def reset(self):\n        \"\"\"Clear all mocks and call history.\"\"\"\n        self._mocks.clear()\n        self._call_log.clear()\n        if hasattr(self, \"_mock_sequences\"):\n            self._mock_sequences.clear()\n```\n\n### The conftest.py: Reusable Fixtures\n\nDrop this `conftest.py` into your test directory. Every test file in this guide imports from it.\n\n```python\n# tests\u002Fconftest.py\nimport os\nimport uuid\nimport pytest\n\n\n@pytest.fixture\ndef api_key():\n    \"\"\"API key for sandbox testing. Uses env var or test default.\"\"\"\n    return os.environ.get(\"GREENHELIX_API_KEY\", \"test-api-key-sandbox\")\n\n\n@pytest.fixture\ndef base_url():\n    \"\"\"Sandbox URL for integration tests.\"\"\"\n    return os.environ.get(\n        \"GREENHELIX_BASE_URL\", \"https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1\"\n    )\n\n\n@pytest.fixture\ndef agent_id():\n    \"\"\"Unique agent ID per test run to prevent collision.\"\"\"\n    return f\"test-agent-{uuid.uuid4().hex[:12]}\"\n\n\n@pytest.fixture\ndef buyer_id():\n    \"\"\"Unique buyer agent ID.\"\"\"\n    return f\"test-buyer-{uuid.uuid4().hex[:12]}\"\n\n\n@pytest.fixture\ndef seller_id():\n    \"\"\"Unique seller agent ID.\"\"\"\n    return f\"test-seller-{uuid.uuid4().hex[:12]}\"\n\n\n@pytest.fixture\ndef harness(api_key, agent_id, base_url):\n    \"\"\"AgentTestHarness in mock mode. Call harness.use_sandbox() for live.\"\"\"\n    h = AgentTestHarness(\n        api_key=api_key,\n        agent_id=agent_id,\n        base_url=base_url,\n    )\n    h.use_mocks()\n    return h\n\n\n@pytest.fixture\ndef sandbox_harness(api_key, agent_id, base_url):\n    \"\"\"AgentTestHarness in sandbox mode for integration tests.\"\"\"\n    h = AgentTestHarness(\n        api_key=api_key,\n        agent_id=agent_id,\n        base_url=base_url,\n    )\n    h.use_sandbox()\n    return h\n\n\n@pytest.fixture\ndef mock_session():\n    \"\"\"Pre-configured requests.Session mock for unit tests.\"\"\"\n    session = MagicMock()\n    response = MagicMock()\n    response.status_code = 200\n    response.json.return_value = {\"status\": \"success\"}\n    response.raise_for_status.return_value = None\n    session.post.return_value = response\n    return session\n\n\n@pytest.fixture\ndef mock_response():\n    \"\"\"Factory fixture for creating MockResponse objects.\"\"\"\n    def _make(tool, data=None, status=\"success\", error_code=None):\n        return MockResponse(\n            tool=tool,\n            status=status,\n            data=data or {},\n            error_code=error_code,\n        )\n    return _make\n\n\n# ── Per-class fixtures for isolated test suites ─────────────\n\nclass AgentFixtures:\n    \"\"\"Mixin providing standard mocks for agent commerce tests.\"\"\"\n\n    @pytest.fixture(autouse=True)\n    def setup_agent_mocks(self, harness):\n        \"\"\"Pre-register common mocks for every test in the class.\"\"\"\n        self.harness = harness\n        harness.mock_tool(\"get_balance\", {\"balance\": \"500.00\", \"currency\": \"USD\"})\n        harness.mock_tool(\"create_wallet\", {\"wallet_id\": \"w-test-001\", \"status\": \"active\"})\n        harness.mock_tool(\"register_agent\", {\"agent_id\": harness.agent_id, \"status\": \"registered\"})\n        harness.mock_tool(\"get_trust_score\", {\"agent_id\": \"any\", \"score\": 0.85})\n        harness.mock_tool(\"get_budget_status\", {\n            \"daily_limit\": \"100.00\",\n            \"spent_today\": \"25.00\",\n            \"remaining\": \"75.00\",\n        })\n\n\nclass EscrowFixtures(AgentFixtures):\n    \"\"\"Extended fixtures for escrow-related tests.\"\"\"\n\n    @pytest.fixture(autouse=True)\n    def setup_escrow_mocks(self, harness):\n        \"\"\"Add escrow mocks on top of agent mocks.\"\"\"\n        self.escrow_id = f\"escrow-{uuid.uuid4().hex[:8]}\"\n        harness.mock_tool(\"create_escrow\", {\n            \"escrow_id\": self.escrow_id,\n            \"status\": \"funded\",\n            \"amount\": \"50.00\",\n        })\n        harness.mock_tool(\"release_escrow\", {\n            \"escrow_id\": self.escrow_id,\n            \"status\": \"released\",\n        })\n        harness.mock_tool(\"cancel_escrow\", {\n            \"escrow_id\": self.escrow_id,\n            \"status\": \"cancelled\",\n        })\n```\n\n### Pattern: Deterministic Mocks vs. Sandbox Testing\n\nThe harness supports both modes. Use mocks for business logic tests (fast, no network, deterministic). Use sandbox for contract and integration tests (real API, real state, real latency).\n\n```python\nclass TestBudgetGuardrails(AgentFixtures):\n    \"\"\"Layer 1: Test budget logic with deterministic mocks.\"\"\"\n\n    def test_blocks_escrow_when_over_budget(self, harness):\n        \"\"\"Escrow creation should be blocked when daily budget is exhausted.\"\"\"\n        harness.mock_tool(\"get_budget_status\", {\n            \"daily_limit\": \"100.00\",\n            \"spent_today\": \"99.00\",\n            \"remaining\": \"1.00\",\n        })\n        budget = harness.execute(\"get_budget_status\", {})\n        remaining = float(budget[\"remaining\"])\n        escrow_amount = 50.00\n\n        # Business logic: do not create escrow if amount > remaining\n        assert escrow_amount > remaining\n        harness.assert_tool_not_called(\"create_escrow\")\n\n    def test_allows_escrow_within_budget(self, harness):\n        \"\"\"Escrow creation should proceed when budget allows.\"\"\"\n        budget = harness.execute(\"get_budget_status\", {})\n        remaining = float(budget[\"remaining\"])\n        escrow_amount = 25.00\n\n        assert escrow_amount \u003C= remaining\n        harness.execute(\"create_escrow\", {\n            \"payer_agent_id\": harness.agent_id,\n            \"payee_agent_id\": \"seller-001\",\n            \"amount\": str(escrow_amount),\n        })\n        harness.assert_tool_called(\"create_escrow\", times=1)\n\n\n@pytest.mark.sandbox\nclass TestBudgetGuardrailsSandbox:\n    \"\"\"Layer 2: Verify budget tools against live sandbox.\"\"\"\n\n    def test_budget_cap_enforced(self, sandbox_harness):\n        \"\"\"Sandbox should reject escrows exceeding the budget cap.\"\"\"\n        h = sandbox_harness\n        h.execute(\"create_wallet\", {})\n        h.execute(\"deposit\", {\"amount\": \"100.00\"})\n        h.execute(\"set_budget_cap\", {\n            \"agent_id\": h.agent_id,\n            \"daily_limit\": \"10.00\",\n        })\n        # This should fail because escrow exceeds daily limit\n        result = h.execute(\"create_escrow\", {\n            \"payer_agent_id\": h.agent_id,\n            \"payee_agent_id\": \"seller-test\",\n            \"amount\": \"50.00\",\n        })\n        # Gateway enforces budget at the tool level\n        assert result.get(\"status\") in (\"error\", \"rejected\")\n```\n\n---\n\n## Chapter 2: Tool-Level Testing Patterns\n\n### The Tool Contract Test\n\nEvery GreenHelix tool has an implicit contract: it accepts a specific input schema, returns a specific output shape, and produces documented error codes for invalid input. A tool contract test verifies all three. When the gateway updates an API version or adds a required field, your contract tests break before your production code does.\n\n```python\nclass ToolContract:\n    \"\"\"Defines the expected contract for a GreenHelix tool.\n\n    Used by contract tests to verify schema, output shape,\n    and error behavior against the sandbox.\n    \"\"\"\n\n    def __init__(\n        self,\n        tool: str,\n        required_fields: list[str],\n        output_fields: list[str],\n        error_cases: dict[str, dict],\n    ):\n        self.tool = tool\n        self.required_fields = required_fields\n        self.output_fields = output_fields\n        self.error_cases = error_cases  # {case_name: {input: ..., expected_error: ...}}\n\n\n# ── Contract definitions for core tools ────────────────────\n\nBILLING_CONTRACTS = {\n    \"get_balance\": ToolContract(\n        tool=\"get_balance\",\n        required_fields=[],\n        output_fields=[\"balance\", \"currency\"],\n        error_cases={\n            \"no_wallet\": {\n                \"input\": {},\n                \"expected_error\": \"wallet_not_found\",\n            },\n        },\n    ),\n    \"deposit\": ToolContract(\n        tool=\"deposit\",\n        required_fields=[\"amount\"],\n        output_fields=[\"balance\", \"transaction_id\"],\n        error_cases={\n            \"negative_amount\": {\n                \"input\": {\"amount\": \"-10.00\"},\n                \"expected_error\": \"invalid_amount\",\n            },\n            \"zero_amount\": {\n                \"input\": {\"amount\": \"0\"},\n                \"expected_error\": \"invalid_amount\",\n            },\n        },\n    ),\n    \"set_budget_cap\": ToolContract(\n        tool=\"set_budget_cap\",\n        required_fields=[\"agent_id\", \"daily_limit\"],\n        output_fields=[\"agent_id\", \"daily_limit\"],\n        error_cases={\n            \"negative_limit\": {\n                \"input\": {\"agent_id\": \"test\", \"daily_limit\": \"-50.00\"},\n                \"expected_error\": \"invalid_amount\",\n            },\n        },\n    ),\n}\n\nPAYMENT_CONTRACTS = {\n    \"create_escrow\": ToolContract(\n        tool=\"create_escrow\",\n        required_fields=[\"payer_agent_id\", \"payee_agent_id\", \"amount\"],\n        output_fields=[\"escrow_id\", \"status\", \"amount\"],\n        error_cases={\n            \"insufficient_funds\": {\n                \"input\": {\n                    \"payer_agent_id\": \"buyer\",\n                    \"payee_agent_id\": \"seller\",\n                    \"amount\": \"999999.00\",\n                },\n                \"expected_error\": \"insufficient_funds\",\n            },\n            \"self_escrow\": {\n                \"input\": {\n                    \"payer_agent_id\": \"same-agent\",\n                    \"payee_agent_id\": \"same-agent\",\n                    \"amount\": \"10.00\",\n                },\n                \"expected_error\": \"invalid_escrow\",\n            },\n        },\n    ),\n    \"release_escrow\": ToolContract(\n        tool=\"release_escrow\",\n        required_fields=[\"escrow_id\"],\n        output_fields=[\"escrow_id\", \"status\"],\n        error_cases={\n            \"nonexistent\": {\n                \"input\": {\"escrow_id\": \"escrow-does-not-exist\"},\n                \"expected_error\": \"escrow_not_found\",\n            },\n        },\n    ),\n}\n\nIDENTITY_CONTRACTS = {\n    \"register_agent\": ToolContract(\n        tool=\"register_agent\",\n        required_fields=[\"agent_id\", \"public_key\", \"name\"],\n        output_fields=[\"agent_id\", \"status\"],\n        error_cases={\n            \"missing_key\": {\n                \"input\": {\"agent_id\": \"test\", \"name\": \"Test\"},\n                \"expected_error\": \"missing_field\",\n            },\n        },\n    ),\n    \"get_trust_score\": ToolContract(\n        tool=\"get_trust_score\",\n        required_fields=[\"agent_id\"],\n        output_fields=[\"agent_id\", \"score\"],\n        error_cases={\n            \"nonexistent_agent\": {\n                \"input\": {\"agent_id\": \"agent-that-does-not-exist-xyz\"},\n                \"expected_error\": \"agent_not_found\",\n            },\n        },\n    ),\n}\n\nMARKETPLACE_CONTRACTS = {\n    \"register_service\": ToolContract(\n        tool=\"register_service\",\n        required_fields=[\"name\", \"description\", \"endpoint\", \"price\", \"tags\", \"category\"],\n        output_fields=[\"service_id\"],\n        error_cases={\n            \"missing_name\": {\n                \"input\": {\n                    \"description\": \"test\",\n                    \"endpoint\": \"agent:\u002F\u002Ftest\",\n                    \"price\": 10.0,\n                    \"tags\": [],\n                    \"category\": \"test\",\n                },\n                \"expected_error\": \"missing_field\",\n            },\n        },\n    ),\n    \"search_services\": ToolContract(\n        tool=\"search_services\",\n        required_fields=[\"query\"],\n        output_fields=[\"services\"],\n        error_cases={\n            \"empty_query\": {\n                \"input\": {\"query\": \"\"},\n                \"expected_error\": \"invalid_query\",\n            },\n        },\n    ),\n}\n```\n\n### Running Contract Tests\n\n```python\n@pytest.mark.sandbox\nclass TestBillingContracts:\n    \"\"\"Layer 2: Verify billing tool contracts against sandbox.\"\"\"\n\n    @pytest.fixture(autouse=True)\n    def setup_wallet(self, sandbox_harness):\n        self.harness = sandbox_harness\n        self.harness.execute(\"create_wallet\", {})\n        self.harness.execute(\"deposit\", {\"amount\": \"100.00\"})\n\n    @pytest.mark.parametrize(\"tool_name\", BILLING_CONTRACTS.keys())\n    def test_output_shape(self, tool_name):\n        \"\"\"Every billing tool returns expected output fields.\"\"\"\n        contract = BILLING_CONTRACTS[tool_name]\n        # Build minimal valid input\n        valid_input = {}\n        if tool_name == \"deposit\":\n            valid_input = {\"amount\": \"10.00\"}\n        elif tool_name == \"set_budget_cap\":\n            valid_input = {\n                \"agent_id\": self.harness.agent_id,\n                \"daily_limit\": \"50.00\",\n            }\n        result = self.harness.execute(tool_name, valid_input)\n        for expected_field in contract.output_fields:\n            assert expected_field in result, (\n                f\"Tool '{tool_name}' missing output field '{expected_field}'. \"\n                f\"Got: {list(result.keys())}\"\n            )\n\n    @pytest.mark.parametrize(\"tool_name\", BILLING_CONTRACTS.keys())\n    def test_error_cases(self, tool_name):\n        \"\"\"Every billing tool returns correct error codes for invalid input.\"\"\"\n        contract = BILLING_CONTRACTS[tool_name]\n        for case_name, case in contract.error_cases.items():\n            result = self.harness.execute(tool_name, case[\"input\"])\n            assert result.get(\"status\") == \"error\" or \"error\" in result, (\n                f\"Tool '{tool_name}' case '{case_name}' should have failed. \"\n                f\"Got: {result}\"\n            )\n\n\n@pytest.mark.sandbox\nclass TestPaymentContracts:\n    \"\"\"Layer 2: Verify payment tool contracts against sandbox.\"\"\"\n\n    @pytest.fixture(autouse=True)\n    def setup_accounts(self, sandbox_harness, buyer_id, seller_id):\n        self.harness = sandbox_harness\n        self.buyer_id = buyer_id\n        self.seller_id = seller_id\n\n    @pytest.mark.parametrize(\"tool_name\", PAYMENT_CONTRACTS.keys())\n    def test_error_cases(self, tool_name):\n        \"\"\"Every payment tool returns correct errors for invalid input.\"\"\"\n        contract = PAYMENT_CONTRACTS[tool_name]\n        for case_name, case in contract.error_cases.items():\n            result = self.harness.execute(tool_name, case[\"input\"])\n            assert result.get(\"status\") == \"error\" or \"error\" in result, (\n                f\"Payment tool '{tool_name}' case '{case_name}' did not fail\"\n            )\n```\n\n### Idempotency Testing for Payment Tools\n\nPayment tools must be idempotent. Calling `create_escrow` twice with the same parameters should not create two escrows. Calling `release_escrow` twice should not transfer funds twice. This pattern tests idempotency by submitting duplicate requests and verifying financial consistency (P1, P7).\n\n```python\n@pytest.mark.sandbox\nclass TestPaymentIdempotency:\n    \"\"\"Layer 2: Verify payment tools handle duplicate calls safely.\"\"\"\n\n    def test_duplicate_escrow_creation(self, sandbox_harness, buyer_id, seller_id):\n        \"\"\"Creating the same escrow twice should return the same escrow_id.\"\"\"\n        h = sandbox_harness\n        h.execute(\"create_wallet\", {})\n        h.execute(\"deposit\", {\"amount\": \"200.00\"})\n\n        escrow_params = {\n            \"payer_agent_id\": buyer_id,\n            \"payee_agent_id\": seller_id,\n            \"amount\": \"50.00\",\n            \"description\": \"Idempotency test escrow\",\n            \"idempotency_key\": f\"idem-{uuid.uuid4().hex[:8]}\",\n        }\n\n        result_1 = h.execute(\"create_escrow\", escrow_params)\n        result_2 = h.execute(\"create_escrow\", escrow_params)\n\n        # Same idempotency key should return same escrow\n        assert result_1[\"escrow_id\"] == result_2[\"escrow_id\"]\n\n        # Balance should only be debited once\n        balance = h.execute(\"get_balance\", {})\n        assert float(balance[\"balance\"]) == 150.00\n\n    def test_duplicate_release(self, sandbox_harness):\n        \"\"\"Releasing the same escrow twice should not double-pay.\"\"\"\n        h = sandbox_harness\n        h.execute(\"create_wallet\", {})\n        h.execute(\"deposit\", {\"amount\": \"100.00\"})\n\n        escrow = h.execute(\"create_escrow\", {\n            \"payer_agent_id\": h.agent_id,\n            \"payee_agent_id\": \"seller-test\",\n            \"amount\": \"25.00\",\n        })\n        escrow_id = escrow[\"escrow_id\"]\n\n        release_1 = h.execute(\"release_escrow\", {\"escrow_id\": escrow_id})\n        release_2 = h.execute(\"release_escrow\", {\"escrow_id\": escrow_id})\n\n        # Second release should be a no-op or return already_released\n        assert release_1.get(\"status\") == \"released\"\n        assert release_2.get(\"status\") in (\"released\", \"already_released\")\n```\n\n### Permission Boundary Testing\n\nAgents should only be able to operate on their own resources. A buyer should not release an escrow created by a different buyer. A seller should not cancel an escrow that is not addressed to them. Permission boundary tests verify these invariants (P7).\n\n```python\n@pytest.mark.sandbox\nclass TestPermissionBoundaries:\n    \"\"\"Layer 2: Verify agents cannot access other agents' resources.\"\"\"\n\n    def test_cannot_release_others_escrow(self, sandbox_harness):\n        \"\"\"Agent A cannot release an escrow created by Agent B.\"\"\"\n        h = sandbox_harness\n        # Agent A creates an escrow\n        h.execute(\"create_wallet\", {})\n        h.execute(\"deposit\", {\"amount\": \"100.00\"})\n        escrow = h.execute(\"create_escrow\", {\n            \"payer_agent_id\": h.agent_id,\n            \"payee_agent_id\": \"seller-x\",\n            \"amount\": \"10.00\",\n        })\n\n        # Agent B (different harness\u002Fsession) tries to release it\n        other = AgentTestHarness(\n            api_key=h.api_key,\n            agent_id=\"attacker-agent\",\n            base_url=h.base_url,\n        )\n        other.use_sandbox()\n        result = other.execute(\"release_escrow\", {\n            \"escrow_id\": escrow[\"escrow_id\"],\n        })\n        assert result.get(\"status\") == \"error\"\n\n    def test_cannot_read_others_balance(self, sandbox_harness):\n        \"\"\"Agent A cannot read Agent B's wallet balance.\"\"\"\n        h = sandbox_harness\n        h.execute(\"create_wallet\", {})\n        h.execute(\"deposit\", {\"amount\": \"100.00\"})\n\n        other = AgentTestHarness(\n            api_key=h.api_key,\n            agent_id=\"other-agent\",\n            base_url=h.base_url,\n        )\n        other.use_sandbox()\n        result = other.execute(\"get_balance\", {})\n        # Should return the other agent's balance (0), not our 100\n        balance = float(result.get(\"balance\", 0))\n        assert balance != 100.00\n\n    def test_cannot_cancel_others_escrow(self, sandbox_harness):\n        \"\"\"Seller cannot cancel an escrow -- only the buyer can.\"\"\"\n        h = sandbox_harness\n        h.execute(\"create_wallet\", {})\n        h.execute(\"deposit\", {\"amount\": \"50.00\"})\n        escrow = h.execute(\"create_escrow\", {\n            \"payer_agent_id\": h.agent_id,\n            \"payee_agent_id\": \"seller-y\",\n            \"amount\": \"10.00\",\n        })\n\n        seller = AgentTestHarness(\n            api_key=h.api_key,\n            agent_id=\"seller-y\",\n            base_url=h.base_url,\n        )\n        seller.use_sandbox()\n        result = seller.execute(\"cancel_escrow\", {\n            \"escrow_id\": escrow[\"escrow_id\"],\n        })\n        assert result.get(\"status\") == \"error\"\n```\n\n---\n\n## Chapter 3: Workflow & Integration Testing\n\n### The Saga Test Pattern\n\nAgent commerce workflows are sagas: multi-step operations where each step has a compensating action. If step 3 fails, steps 1 and 2 must be rolled back. The saga test pattern verifies both the happy path and every possible failure point.\n\n```python\nclass MarketplaceSaga:\n    \"\"\"Implements the complete marketplace listing workflow as a testable saga.\n\n    Steps:\n        1. Seller registers service on marketplace\n        2. Buyer discovers service via search\n        3. Buyer checks seller trust score\n        4. Buyer creates escrow\n        5. Seller performs work (simulated)\n        6. Buyer releases escrow\n        7. Buyer rates service\n        8. Settlement completes\n\n    Compensating actions:\n        Step 4 fails → no cleanup needed (funds not locked)\n        Step 5 fails → cancel escrow (return funds to buyer)\n        Step 6 fails → open dispute\n    \"\"\"\n\n    def __init__(self, harness: AgentTestHarness, buyer_id: str, seller_id: str):\n        self.harness = harness\n        self.buyer_id = buyer_id\n        self.seller_id = seller_id\n        self.state = {\"step\": 0, \"completed_steps\": []}\n\n    def run(self) -> dict:\n        \"\"\"Execute the full saga, rolling back on failure.\"\"\"\n        try:\n            # Step 1: Register service\n            service = self.harness.execute(\"register_service\", {\n                \"name\": \"Test Summarization Service\",\n                \"description\": \"Summarizes documents for testing\",\n                \"endpoint\": f\"agent:\u002F\u002F{self.seller_id}\",\n                \"price\": 25.00,\n                \"tags\": [\"test\", \"summarization\"],\n                \"category\": \"data-processing\",\n            })\n            self.state[\"service_id\"] = service[\"service_id\"]\n            self.state[\"completed_steps\"].append(\"register_service\")\n\n            # Step 2: Discover service\n            results = self.harness.execute(\"search_services\", {\n                \"query\": \"test summarization\",\n            })\n            assert len(results.get(\"services\", [])) > 0\n            self.state[\"completed_steps\"].append(\"discover_service\")\n\n            # Step 3: Trust check\n            trust = self.harness.execute(\"get_trust_score\", {\n                \"agent_id\": self.seller_id,\n            })\n            if trust.get(\"score\", 0) \u003C 0.5:\n                return {\"status\": \"aborted\", \"reason\": \"low_trust\"}\n            self.state[\"completed_steps\"].append(\"trust_check\")\n\n            # Step 4: Create escrow\n            escrow = self.harness.execute(\"create_escrow\", {\n                \"payer_agent_id\": self.buyer_id,\n                \"payee_agent_id\": self.seller_id,\n                \"amount\": \"25.00\",\n                \"description\": \"Saga test escrow\",\n            })\n            self.state[\"escrow_id\"] = escrow[\"escrow_id\"]\n            self.state[\"completed_steps\"].append(\"create_escrow\")\n\n            # Step 5: Simulate work (in real tests, call seller endpoint)\n            work_result = {\"quality\": 0.95, \"documents_processed\": 500}\n            self.state[\"completed_steps\"].append(\"work_completed\")\n\n            # Step 6: Release escrow\n            release = self.harness.execute(\"release_escrow\", {\n                \"escrow_id\": escrow[\"escrow_id\"],\n            })\n            self.state[\"completed_steps\"].append(\"release_escrow\")\n\n            # Step 7: Rate service\n            self.harness.execute(\"rate_service\", {\n                \"service_id\": service[\"service_id\"],\n                \"rating\": 5,\n            })\n            self.state[\"completed_steps\"].append(\"rate_service\")\n\n            return {\"status\": \"completed\", \"state\": self.state}\n\n        except Exception as e:\n            return self._compensate(str(e))\n\n    def _compensate(self, error: str) -> dict:\n        \"\"\"Roll back completed steps on failure.\"\"\"\n        if \"create_escrow\" in self.state[\"completed_steps\"]:\n            escrow_id = self.state.get(\"escrow_id\")\n            if escrow_id and \"release_escrow\" not in self.state[\"completed_steps\"]:\n                self.harness.execute(\"cancel_escrow\", {\n                    \"escrow_id\": escrow_id,\n                })\n                self.state[\"completed_steps\"].append(\"compensate:cancel_escrow\")\n\n        return {\n            \"status\": \"rolled_back\",\n            \"error\": error,\n            \"state\": self.state,\n        }\n```\n\n### Testing the Saga\n\n```python\nclass TestMarketplaceSaga(EscrowFixtures):\n    \"\"\"Layer 3: Full marketplace workflow with rollback verification.\"\"\"\n\n    def test_happy_path(self, harness, buyer_id, seller_id):\n        \"\"\"Complete saga executes all 7 steps.\"\"\"\n        harness.mock_tool(\"register_service\", {\n            \"service_id\": \"svc-test-001\",\n        })\n        harness.mock_tool(\"search_services\", {\n            \"services\": [{\"name\": \"Test Service\", \"agent_id\": seller_id}],\n        })\n        harness.mock_tool(\"rate_service\", {\"status\": \"rated\"})\n\n        saga = MarketplaceSaga(harness, buyer_id, seller_id)\n        result = saga.run()\n\n        assert result[\"status\"] == \"completed\"\n        assert len(result[\"state\"][\"completed_steps\"]) == 7\n        harness.assert_call_order([\n            \"register_service\",\n            \"search_services\",\n            \"get_trust_score\",\n            \"create_escrow\",\n            \"release_escrow\",\n            \"rate_service\",\n        ])\n\n    def test_rollback_on_escrow_failure(self, harness, buyer_id, seller_id):\n        \"\"\"Failed escrow creation does not leave orphaned state.\"\"\"\n        harness.mock_tool(\"register_service\", {\"service_id\": \"svc-test-002\"})\n        harness.mock_tool(\"search_services\", {\n            \"services\": [{\"name\": \"Test\", \"agent_id\": seller_id}],\n        })\n        harness.mock_tool_error(\n            \"create_escrow\", \"insufficient_funds\", \"Not enough balance\"\n        )\n\n        saga = MarketplaceSaga(harness, buyer_id, seller_id)\n        result = saga.run()\n\n        assert result[\"status\"] == \"rolled_back\"\n        assert \"create_escrow\" not in result[\"state\"][\"completed_steps\"]\n        harness.assert_tool_not_called(\"release_escrow\")\n\n    def test_rollback_cancels_escrow_on_work_failure(self, harness, buyer_id, seller_id):\n        \"\"\"Failed work step triggers escrow cancellation.\"\"\"\n        harness.mock_tool(\"register_service\", {\"service_id\": \"svc-test-003\"})\n        harness.mock_tool(\"search_services\", {\n            \"services\": [{\"name\": \"Test\", \"agent_id\": seller_id}],\n        })\n\n        saga = MarketplaceSaga(harness, buyer_id, seller_id)\n        # Simulate work failure by injecting error after escrow creation\n        original_execute = harness.execute\n\n        call_count = {\"n\": 0}\n        def failing_execute(tool, input_data):\n            call_count[\"n\"] += 1\n            if tool == \"release_escrow\":\n                raise RuntimeError(\"Simulated work verification failure\")\n            return original_execute(tool, input_data)\n\n        harness.execute = failing_execute\n        result = saga.run()\n\n        assert result[\"status\"] == \"rolled_back\"\n        assert \"compensate:cancel_escrow\" in result[\"state\"][\"completed_steps\"]\n```\n\n### Subscription Lifecycle Testing\n\nSubscriptions are stateful workflows: create, renew, pause, cancel. Each transition must be tested, including edge cases like renewal with insufficient balance (P2, P6).\n\n```python\nclass TestSubscriptionLifecycle(AgentFixtures):\n    \"\"\"Layer 3: Verify subscription state transitions.\"\"\"\n\n    def test_full_lifecycle(self, harness):\n        \"\"\"Create → renew → cancel lifecycle.\"\"\"\n        sub_id = f\"sub-{uuid.uuid4().hex[:8]}\"\n        harness.mock_tool(\"create_subscription\", {\n            \"subscription_id\": sub_id,\n            \"status\": \"active\",\n            \"next_payment_date\": \"2026-05-06\",\n        })\n        harness.mock_tool(\"get_subscription\", {\n            \"subscription_id\": sub_id,\n            \"status\": \"active\",\n            \"payments_completed\": 1,\n        })\n        harness.mock_tool(\"cancel_subscription\", {\n            \"subscription_id\": sub_id,\n            \"status\": \"cancelled\",\n        })\n\n        # Create\n        sub = harness.execute(\"create_subscription\", {\n            \"payer_agent_id\": harness.agent_id,\n            \"payee_agent_id\": \"provider-001\",\n            \"amount\": \"15.00\",\n            \"interval\": \"monthly\",\n        })\n        assert sub[\"status\"] == \"active\"\n\n        # Check status\n        status = harness.execute(\"get_subscription\", {\n            \"subscription_id\": sub_id,\n        })\n        assert status[\"payments_completed\"] == 1\n\n        # Cancel\n        cancel = harness.execute(\"cancel_subscription\", {\n            \"subscription_id\": sub_id,\n        })\n        assert cancel[\"status\"] == \"cancelled\"\n\n        harness.assert_call_order([\n            \"create_subscription\",\n            \"get_subscription\",\n            \"cancel_subscription\",\n        ])\n\n    def test_renewal_with_insufficient_funds(self, harness):\n        \"\"\"Subscription renewal should fail gracefully when balance is low.\"\"\"\n        harness.mock_tool(\"get_balance\", {\"balance\": \"5.00\", \"currency\": \"USD\"})\n        harness.mock_tool_error(\n            \"create_subscription\",\n            \"insufficient_funds\",\n            \"Balance too low for subscription amount\",\n        )\n\n        result = harness.execute(\"create_subscription\", {\n            \"payer_agent_id\": harness.agent_id,\n            \"payee_agent_id\": \"provider-002\",\n            \"amount\": \"15.00\",\n            \"interval\": \"monthly\",\n        })\n        assert result.get(\"status\") == \"error\"\n```\n\n### Webhook Delivery Testing\n\nWebhooks are the primary notification mechanism for payment events. A missed webhook means a missed settlement, a missed dispute deadline, or a missed subscription renewal. Test webhook delivery separately from the business logic it triggers (P4).\n\n```python\nclass TestWebhookDelivery:\n    \"\"\"Layer 3: Verify webhook registration and event delivery.\"\"\"\n\n    def test_webhook_registration(self, harness):\n        \"\"\"Webhook registration should return a webhook_id.\"\"\"\n        harness.mock_tool(\"register_webhook\", {\n            \"webhook_id\": \"wh-test-001\",\n            \"status\": \"active\",\n            \"events\": [\"escrow.released\", \"escrow.disputed\"],\n        })\n\n        result = harness.execute(\"register_webhook\", {\n            \"url\": \"https:\u002F\u002Ftest.example.com\u002Fwebhook\",\n            \"events\": [\"escrow.released\", \"escrow.disputed\"],\n        })\n        assert \"webhook_id\" in result\n        assert result[\"status\"] == \"active\"\n\n    def test_webhook_event_format(self, harness):\n        \"\"\"Webhook payloads should contain required fields.\"\"\"\n        harness.mock_tool(\"get_webhook_logs\", {\n            \"logs\": [{\n                \"webhook_id\": \"wh-test-001\",\n                \"event_type\": \"escrow.released\",\n                \"payload\": {\n                    \"escrow_id\": \"escrow-abc\",\n                    \"amount\": \"25.00\",\n                    \"payer_agent_id\": \"buyer-1\",\n                    \"payee_agent_id\": \"seller-1\",\n                    \"timestamp\": \"2026-04-06T12:00:00Z\",\n                },\n                \"delivery_status\": \"delivered\",\n                \"response_code\": 200,\n            }],\n        })\n\n        logs = harness.execute(\"get_webhook_logs\", {\"webhook_id\": \"wh-test-001\"})\n        for log_entry in logs[\"logs\"]:\n            payload = log_entry[\"payload\"]\n            assert \"escrow_id\" in payload\n            assert \"amount\" in payload\n            assert \"timestamp\" in payload\n            assert log_entry[\"delivery_status\"] == \"delivered\"\n```\n\n---\n\n## Chapter 4: Chaos Testing for Agent Commerce\n\n### Why Chaos Testing Matters for Payments\n\nTraditional software fails gracefully when a downstream service is unavailable -- it shows an error page. Agent commerce software fails expensively. A timeout during `release_escrow` might mean funds are released on the gateway but the caller never gets confirmation, leading to a duplicate release attempt. A network partition during a split payment might result in partial settlement. Chaos testing injects these failures deliberately so you can verify your system handles them before production handles them for you.\n\n### The ChaosMiddleware\n\nThe `ChaosMiddleware` wraps the harness's `execute` method and randomly injects failures: timeouts, error responses, delayed responses, and corrupted payloads. It is configurable per tool and per failure type.\n\n```python\nimport random\nimport time\nfrom dataclasses import dataclass, field\n\n\n@dataclass\nclass ChaosConfig:\n    \"\"\"Configuration for chaos injection on a specific tool.\"\"\"\n    timeout_pct: float = 0.0       # % of calls that timeout\n    error_pct: float = 0.0         # % of calls that return errors\n    delay_ms: float = 0.0          # Additional latency in ms\n    corrupt_pct: float = 0.0       # % of calls with corrupted responses\n    duplicate_pct: float = 0.0     # % of calls that execute twice\n\n\nclass ChaosMiddleware:\n    \"\"\"Wraps AgentTestHarness._execute with configurable failure injection.\n\n    Usage:\n        harness = AgentTestHarness(api_key, agent_id, base_url)\n        chaos = ChaosMiddleware(\n            harness=harness,\n            default_config=ChaosConfig(error_pct=10, delay_ms=200),\n        )\n        chaos.set_tool_config(\"create_escrow\", ChaosConfig(\n            timeout_pct=20,\n            duplicate_pct=5,\n        ))\n\n        # All calls now go through chaos injection\n        result = chaos.execute(\"create_escrow\", {...})\n    \"\"\"\n\n    def __init__(\n        self,\n        harness: AgentTestHarness,\n        default_config: ChaosConfig = None,\n        seed: int = None,\n    ):\n        self.harness = harness\n        self.default_config = default_config or ChaosConfig()\n        self._tool_configs: dict[str, ChaosConfig] = {}\n        self._rng = random.Random(seed)\n        self._chaos_log: list[dict] = []\n\n    def set_tool_config(self, tool: str, config: ChaosConfig):\n        \"\"\"Set chaos configuration for a specific tool.\"\"\"\n        self._tool_configs[tool] = config\n\n    def execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute a tool with chaos injection.\"\"\"\n        config = self._tool_configs.get(tool, self.default_config)\n        chaos_event = {\"tool\": tool, \"injection\": None, \"timestamp\": time.time()}\n\n        # Check timeout injection\n        if self._rng.random() * 100 \u003C config.timeout_pct:\n            chaos_event[\"injection\"] = \"timeout\"\n            self._chaos_log.append(chaos_event)\n            raise TimeoutError(\n                f\"Chaos: simulated timeout for tool '{tool}'\"\n            )\n\n        # Check error injection\n        if self._rng.random() * 100 \u003C config.error_pct:\n            chaos_event[\"injection\"] = \"error\"\n            self._chaos_log.append(chaos_event)\n            return {\n                \"status\": \"error\",\n                \"error\": {\n                    \"code\": \"chaos_injected_error\",\n                    \"message\": f\"Chaos: simulated error for tool '{tool}'\",\n                },\n            }\n\n        # Apply delay\n        if config.delay_ms > 0:\n            delay_seconds = config.delay_ms \u002F 1000.0\n            actual_delay = self._rng.uniform(0, delay_seconds * 2)\n            time.sleep(actual_delay)\n            chaos_event[\"injection\"] = f\"delay:{actual_delay:.3f}s\"\n\n        # Execute the real call\n        result = self.harness.execute(tool, input_data)\n\n        # Check duplicate execution\n        if self._rng.random() * 100 \u003C config.duplicate_pct:\n            chaos_event[\"injection\"] = \"duplicate\"\n            self._chaos_log.append(chaos_event)\n            # Execute again -- this tests idempotency\n            duplicate_result = self.harness.execute(tool, input_data)\n            return duplicate_result\n\n        # Check corruption\n        if self._rng.random() * 100 \u003C config.corrupt_pct:\n            chaos_event[\"injection\"] = \"corrupt\"\n            self._chaos_log.append(chaos_event)\n            if isinstance(result, dict):\n                result[\"_chaos_corrupted\"] = True\n                # Remove a random key to simulate partial response\n                keys = [k for k in result.keys() if k != \"status\"]\n                if keys:\n                    del result[self._rng.choice(keys)]\n\n        self._chaos_log.append(chaos_event)\n        return result\n\n    def get_chaos_log(self) -> list[dict]:\n        \"\"\"Get the log of all chaos injections.\"\"\"\n        return list(self._chaos_log)\n\n    def get_injection_stats(self) -> dict:\n        \"\"\"Get summary statistics of chaos injections.\"\"\"\n        stats = {\"total\": len(self._chaos_log)}\n        for entry in self._chaos_log:\n            injection = entry.get(\"injection\") or \"none\"\n            category = injection.split(\":\")[0]\n            stats[category] = stats.get(category, 0) + 1\n        return stats\n```\n\n### Chaos Test Patterns\n\n```python\nclass TestEscrowUnderChaos:\n    \"\"\"Layer 4: Verify escrow operations survive failure injection.\"\"\"\n\n    def test_escrow_survives_timeout_retry(self, harness):\n        \"\"\"Escrow creation retries correctly after timeout.\"\"\"\n        harness.use_mocks()\n        harness.mock_tool(\"create_escrow\", {\n            \"escrow_id\": \"escrow-chaos-001\",\n            \"status\": \"funded\",\n            \"amount\": \"50.00\",\n        })\n\n        chaos = ChaosMiddleware(\n            harness=harness,\n            seed=42,\n            default_config=ChaosConfig(timeout_pct=50),\n        )\n\n        # Retry loop -- real production code should have this\n        max_retries = 5\n        result = None\n        for attempt in range(max_retries):\n            try:\n                result = chaos.execute(\"create_escrow\", {\n                    \"payer_agent_id\": \"buyer\",\n                    \"payee_agent_id\": \"seller\",\n                    \"amount\": \"50.00\",\n                    \"idempotency_key\": \"idem-chaos-001\",\n                })\n                break\n            except TimeoutError:\n                continue\n\n        assert result is not None, \"All retry attempts timed out\"\n        assert result[\"escrow_id\"] == \"escrow-chaos-001\"\n\n    def test_no_double_payment_under_duplicates(self, harness):\n        \"\"\"Duplicate chaos injection does not cause double payment.\"\"\"\n        harness.use_mocks()\n        call_count = {\"n\": 0}\n\n        original_execute = harness.execute\n        def counting_execute(tool, input_data):\n            call_count[\"n\"] += 1\n            return original_execute(tool, input_data)\n\n        harness.execute = counting_execute\n        harness.mock_tool(\"release_escrow\", {\n            \"escrow_id\": \"escrow-dup-test\",\n            \"status\": \"released\",\n        })\n\n        chaos = ChaosMiddleware(\n            harness=harness,\n            seed=99,\n            default_config=ChaosConfig(duplicate_pct=100),\n        )\n\n        result = chaos.execute(\"release_escrow\", {\n            \"escrow_id\": \"escrow-dup-test\",\n        })\n\n        # The middleware called execute twice, but the result should\n        # still represent a single release\n        assert result[\"status\"] == \"released\"\n\n    def test_concurrent_escrow_load(self, harness):\n        \"\"\"Concurrent escrow creation does not cause race conditions.\"\"\"\n        import concurrent.futures\n\n        harness.use_mocks()\n        harness.mock_tool(\"create_escrow\", {\n            \"escrow_id\": \"will-be-unique\",\n            \"status\": \"funded\",\n            \"amount\": \"10.00\",\n        })\n\n        chaos = ChaosMiddleware(\n            harness=harness,\n            seed=7,\n            default_config=ChaosConfig(delay_ms=50, error_pct=10),\n        )\n\n        results = []\n        errors = []\n\n        def create_escrow(i):\n            try:\n                return chaos.execute(\"create_escrow\", {\n                    \"payer_agent_id\": \"buyer\",\n                    \"payee_agent_id\": \"seller\",\n                    \"amount\": \"10.00\",\n                    \"idempotency_key\": f\"concurrent-{i}\",\n                })\n            except Exception as e:\n                return {\"status\": \"error\", \"message\": str(e)}\n\n        with concurrent.futures.ThreadPoolExecutor(max_workers=10) as pool:\n            futures = [pool.submit(create_escrow, i) for i in range(20)]\n            for f in concurrent.futures.as_completed(futures):\n                r = f.result()\n                if r.get(\"status\") == \"error\":\n                    errors.append(r)\n                else:\n                    results.append(r)\n\n        # At least some should succeed despite chaos\n        assert len(results) > 0\n        # Errors are expected under chaos -- verify they are handled\n        total = len(results) + len(errors)\n        assert total == 20\n\n    def test_escrow_timeout_deadline(self, harness):\n        \"\"\"Escrow must be released or cancelled before deadline.\"\"\"\n        harness.use_mocks()\n        deadline = time.time() + 2  # 2 second deadline for test\n\n        harness.mock_tool(\"create_escrow\", {\n            \"escrow_id\": \"escrow-deadline\",\n            \"status\": \"funded\",\n            \"deadline\": deadline,\n        })\n        harness.mock_tool(\"cancel_escrow\", {\n            \"escrow_id\": \"escrow-deadline\",\n            \"status\": \"cancelled\",\n            \"reason\": \"deadline_exceeded\",\n        })\n\n        escrow = harness.execute(\"create_escrow\", {\n            \"payer_agent_id\": \"buyer\",\n            \"payee_agent_id\": \"seller\",\n            \"amount\": \"30.00\",\n        })\n\n        # Simulate deadline passing\n        time.sleep(0.1)  # In real tests use time mocking\n        current_time = time.time()\n        if current_time \u003C deadline:\n            # Still within deadline -- release is valid\n            harness.mock_tool(\"release_escrow\", {\n                \"escrow_id\": \"escrow-deadline\",\n                \"status\": \"released\",\n            })\n            result = harness.execute(\"release_escrow\", {\n                \"escrow_id\": escrow[\"escrow_id\"],\n            })\n            assert result[\"status\"] == \"released\"\n        else:\n            # Deadline exceeded -- should auto-cancel\n            result = harness.execute(\"cancel_escrow\", {\n                \"escrow_id\": escrow[\"escrow_id\"],\n            })\n            assert result[\"status\"] == \"cancelled\"\n```\n\n---\n\n## Chapter 5: Production Observability\n\n### Why printf Debugging Does Not Work for Payments\n\nWhen a payment fails in production, you need to know three things instantly: which tool failed, how long it took, and what the input was. You need this information structured, searchable, and available without SSH-ing into a server. The `AgentTracer` wraps every `_execute` call with timing, success\u002Ffailure tracking, and structured output.\n\n### The AgentTracer\n\n```python\nimport time\nimport json\nimport logging\nfrom dataclasses import dataclass, field\nfrom typing import Optional, Callable\n\n\n@dataclass\nclass TraceRecord:\n    \"\"\"A single traced tool execution.\"\"\"\n    tool: str\n    agent_id: str\n    started_at: float\n    ended_at: float\n    duration_ms: float\n    success: bool\n    input_data: dict\n    output_data: Optional[dict] = None\n    error: Optional[str] = None\n    trace_id: str = \"\"\n\n    def to_dict(self) -> dict:\n        return {\n            \"trace_id\": self.trace_id,\n            \"tool\": self.tool,\n            \"agent_id\": self.agent_id,\n            \"started_at\": self.started_at,\n            \"ended_at\": self.ended_at,\n            \"duration_ms\": round(self.duration_ms, 2),\n            \"success\": self.success,\n            \"error\": self.error,\n        }\n\n\nclass AgentTracer:\n    \"\"\"Wraps _execute and records timing, success\u002Ffailure, tool name.\n\n    Provides structured observability for every tool call in production.\n\n    Usage:\n        tracer = AgentTracer(\n            api_key=\"...\",\n            agent_id=\"production-buyer-01\",\n            base_url=\"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n        )\n\n        # Wrap an existing AgentCommerce or harness\n        result = tracer.trace(\"create_escrow\", {\n            \"payer_agent_id\": \"buyer\",\n            \"payee_agent_id\": \"seller\",\n            \"amount\": \"50.00\",\n        })\n\n        # Get metrics\n        print(tracer.get_metrics())\n        # {'total_calls': 47, 'success_rate': 0.957,\n        #  'avg_latency_ms': 142.3, 'p99_latency_ms': 890.1,\n        #  'error_rate_by_tool': {'create_escrow': 0.02}}\n    \"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n        logger: Optional[logging.Logger] = None,\n        on_slow_call: Optional[Callable] = None,\n        slow_threshold_ms: float = 2000.0,\n    ):\n        self.api_key = api_key\n        self.agent_id = agent_id\n        self.base_url = base_url\n        self.logger = logger or logging.getLogger(\"agent_tracer\")\n        self.on_slow_call = on_slow_call\n        self.slow_threshold_ms = slow_threshold_ms\n        self._traces: list[TraceRecord] = []\n        self._session = requests.Session()\n        self._session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n\n    def trace(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute a tool with full tracing.\"\"\"\n        trace_id = f\"trace-{uuid.uuid4().hex[:12]}\"\n        started_at = time.time()\n\n        try:\n            resp = self._session.post(\n                f\"{self.base_url}\u002Fv1\",\n                json={\"tool\": tool, \"input\": input_data},\n            )\n            resp.raise_for_status()\n            result = resp.json()\n            success = result.get(\"status\") != \"error\"\n            error = None if success else json.dumps(result.get(\"error\", {}))\n        except Exception as e:\n            result = {\"status\": \"error\", \"error\": str(e)}\n            success = False\n            error = str(e)\n\n        ended_at = time.time()\n        duration_ms = (ended_at - started_at) * 1000\n\n        record = TraceRecord(\n            tool=tool,\n            agent_id=self.agent_id,\n            started_at=started_at,\n            ended_at=ended_at,\n            duration_ms=duration_ms,\n            success=success,\n            input_data=input_data,\n            output_data=result if success else None,\n            error=error,\n            trace_id=trace_id,\n        )\n        self._traces.append(record)\n\n        # Structured log\n        self.logger.info(json.dumps({\n            \"event\": \"tool_execution\",\n            \"trace_id\": trace_id,\n            \"tool\": tool,\n            \"agent_id\": self.agent_id,\n            \"duration_ms\": round(duration_ms, 2),\n            \"success\": success,\n            \"error\": error,\n        }))\n\n        # Slow call callback\n        if duration_ms > self.slow_threshold_ms and self.on_slow_call:\n            self.on_slow_call(record)\n\n        return result\n\n    def get_metrics(self) -> dict:\n        \"\"\"Compute aggregate metrics from traced calls.\"\"\"\n        if not self._traces:\n            return {\"total_calls\": 0}\n\n        total = len(self._traces)\n        successes = sum(1 for t in self._traces if t.success)\n        durations = sorted(t.duration_ms for t in self._traces)\n\n        # Per-tool error rates\n        tool_calls: dict[str, dict] = {}\n        for t in self._traces:\n            if t.tool not in tool_calls:\n                tool_calls[t.tool] = {\"total\": 0, \"errors\": 0}\n            tool_calls[t.tool][\"total\"] += 1\n            if not t.success:\n                tool_calls[t.tool][\"errors\"] += 1\n\n        error_rate_by_tool = {\n            tool: stats[\"errors\"] \u002F stats[\"total\"]\n            for tool, stats in tool_calls.items()\n            if stats[\"errors\"] > 0\n        }\n\n        # Per-tool latency\n        tool_latencies: dict[str, list[float]] = {}\n        for t in self._traces:\n            tool_latencies.setdefault(t.tool, []).append(t.duration_ms)\n\n        avg_latency_by_tool = {\n            tool: round(sum(lats) \u002F len(lats), 2)\n            for tool, lats in tool_latencies.items()\n        }\n\n        return {\n            \"total_calls\": total,\n            \"success_rate\": round(successes \u002F total, 4),\n            \"avg_latency_ms\": round(sum(durations) \u002F total, 2),\n            \"p50_latency_ms\": round(durations[total \u002F\u002F 2], 2),\n            \"p95_latency_ms\": round(durations[int(total * 0.95)], 2),\n            \"p99_latency_ms\": round(durations[int(total * 0.99)], 2),\n            \"error_rate_by_tool\": error_rate_by_tool,\n            \"avg_latency_by_tool\": avg_latency_by_tool,\n        }\n\n    def get_traces(\n        self,\n        tool: Optional[str] = None,\n        success: Optional[bool] = None,\n        min_duration_ms: Optional[float] = None,\n    ) -> list[dict]:\n        \"\"\"Query traces with optional filters.\"\"\"\n        filtered = self._traces\n        if tool:\n            filtered = [t for t in filtered if t.tool == tool]\n        if success is not None:\n            filtered = [t for t in filtered if t.success == success]\n        if min_duration_ms is not None:\n            filtered = [t for t in filtered if t.duration_ms >= min_duration_ms]\n        return [t.to_dict() for t in filtered]\n\n    def get_revenue_metrics(self) -> dict:\n        \"\"\"Extract revenue-specific metrics from traced calls.\"\"\"\n        escrow_creates = [\n            t for t in self._traces\n            if t.tool == \"create_escrow\" and t.success\n        ]\n        escrow_releases = [\n            t for t in self._traces\n            if t.tool == \"release_escrow\" and t.success\n        ]\n        deposits = [\n            t for t in self._traces\n            if t.tool == \"deposit\" and t.success\n        ]\n\n        total_escrowed = sum(\n            float(t.input_data.get(\"amount\", 0))\n            for t in escrow_creates\n        )\n        total_deposited = sum(\n            float(t.input_data.get(\"amount\", 0))\n            for t in deposits\n        )\n\n        return {\n            \"escrows_created\": len(escrow_creates),\n            \"escrows_released\": len(escrow_releases),\n            \"total_escrowed\": round(total_escrowed, 2),\n            \"total_deposited\": round(total_deposited, 2),\n            \"release_rate\": (\n                round(len(escrow_releases) \u002F len(escrow_creates), 4)\n                if escrow_creates else 0\n            ),\n        }\n```\n\n### Structured Logging for Agent Decisions\n\nThe tracer's structured logging integrates with any log aggregator (Datadog, ELK, CloudWatch). Each log line is a JSON object with consistent fields. The key decision: log the tool name and duration for every call, but redact input data in production to avoid logging sensitive information like API keys or wallet amounts. Enable full input logging only in staging (P7 security patterns).\n\n```python\n# Production logging configuration\nimport logging\n\ndef configure_production_logging():\n    \"\"\"Set up structured JSON logging for agent commerce.\"\"\"\n    logger = logging.getLogger(\"agent_tracer\")\n    logger.setLevel(logging.INFO)\n\n    handler = logging.StreamHandler()\n    handler.setFormatter(logging.Formatter(\"%(message)s\"))\n    logger.addHandler(handler)\n    return logger\n\n\ndef configure_staging_logging():\n    \"\"\"Staging logger with full input\u002Foutput capture.\"\"\"\n    logger = logging.getLogger(\"agent_tracer\")\n    logger.setLevel(logging.DEBUG)\n\n    handler = logging.FileHandler(\"\u002Fvar\u002Flog\u002Fagent-commerce\u002Ftraces.jsonl\")\n    handler.setFormatter(logging.Formatter(\"%(message)s\"))\n    logger.addHandler(handler)\n    return logger\n```\n\n### Custom Metrics Dashboard\n\nExtract the metrics you need for a Grafana or Datadog dashboard from the tracer. These are the five metrics every agent commerce system should track.\n\n```python\nclass MetricsExporter:\n    \"\"\"Export AgentTracer metrics to monitoring systems.\"\"\"\n\n    def __init__(self, tracer: AgentTracer):\n        self.tracer = tracer\n\n    def export_prometheus(self) -> str:\n        \"\"\"Export metrics in Prometheus text format.\"\"\"\n        metrics = self.tracer.get_metrics()\n        revenue = self.tracer.get_revenue_metrics()\n        lines = [\n            f'agent_commerce_calls_total {metrics[\"total_calls\"]}',\n            f'agent_commerce_success_rate {metrics[\"success_rate\"]}',\n            f'agent_commerce_latency_p50_ms {metrics.get(\"p50_latency_ms\", 0)}',\n            f'agent_commerce_latency_p99_ms {metrics.get(\"p99_latency_ms\", 0)}',\n            f'agent_commerce_escrows_created {revenue[\"escrows_created\"]}',\n            f'agent_commerce_escrows_released {revenue[\"escrows_released\"]}',\n            f'agent_commerce_total_escrowed {revenue[\"total_escrowed\"]}',\n            f'agent_commerce_release_rate {revenue[\"release_rate\"]}',\n        ]\n\n        for tool, rate in metrics.get(\"error_rate_by_tool\", {}).items():\n            lines.append(\n                f'agent_commerce_error_rate{{tool=\"{tool}\"}} {rate}'\n            )\n\n        return \"\\n\".join(lines)\n\n    def to_datadog_events(self) -> list[dict]:\n        \"\"\"Format failed traces as Datadog events.\"\"\"\n        failed = self.tracer.get_traces(success=False)\n        return [\n            {\n                \"title\": f\"Tool failure: {t['tool']}\",\n                \"text\": t.get(\"error\", \"Unknown error\"),\n                \"tags\": [\n                    f\"tool:{t['tool']}\",\n                    f\"agent:{t['agent_id']}\",\n                    \"service:agent-commerce\",\n                ],\n                \"alert_type\": \"error\",\n            }\n            for t in failed\n        ]\n```\n\n---\n\n## Chapter 6: Alerting & Incident Response\n\n### What to Alert On\n\nNot every error deserves a page. These six conditions are the ones that, left unaddressed, cause financial loss in agent commerce systems.\n\n| Alert | Condition | Severity | Action |\n|-------|-----------|----------|--------|\n| Settlement failure | `release_escrow` returns error 3+ times | Critical | Check gateway status, pause new escrows |\n| Escrow timeout | Escrow unfunded\u002Funreleased past deadline | High | Auto-cancel or escalate to dispute |\n| Balance anomaly | Balance drops >50% in single transaction | Critical | Pause agent, audit recent calls |\n| Reputation drop | Trust score drops below threshold | Medium | Pause hiring, investigate metrics |\n| Webhook delivery failure | >5 consecutive webhook delivery failures | High | Check endpoint, enable retry queue |\n| Duplicate payment | Same escrow_id released twice in 60s | Critical | Immediate halt, audit ledger |\n\n### The HealthChecker\n\nThe `HealthChecker` runs synthetic transactions against the sandbox (or a dedicated health-check agent on production) to verify the full payment pipeline is operational. Run it every 60 seconds from your monitoring system.\n\n```python\nclass HealthChecker:\n    \"\"\"Synthetic transaction health checks for agent commerce.\n\n    Runs a mini escrow lifecycle (create wallet → deposit → create\n    escrow → release → verify balance) and reports pass\u002Ffail with\n    latency metrics.\n\n    Usage:\n        checker = HealthChecker(\n            api_key=\"health-check-key\",\n            agent_id=\"health-check-agent\",\n            base_url=\"https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1\",\n        )\n\n        result = checker.run_health_check()\n        # {\n        #     \"healthy\": True,\n        #     \"checks\": {\n        #         \"wallet\": {\"status\": \"pass\", \"latency_ms\": 45.2},\n        #         \"deposit\": {\"status\": \"pass\", \"latency_ms\": 78.1},\n        #         \"escrow_create\": {\"status\": \"pass\", \"latency_ms\": 112.4},\n        #         \"escrow_release\": {\"status\": \"pass\", \"latency_ms\": 95.6},\n        #         \"balance_verify\": {\"status\": \"pass\", \"latency_ms\": 41.0},\n        #     },\n        #     \"total_latency_ms\": 372.3,\n        # }\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        timeout_ms: float = 5000.0,\n    ):\n        self.api_key = api_key\n        self.agent_id = agent_id\n        self.base_url = base_url\n        self.timeout_ms = timeout_ms\n        self._session = requests.Session()\n        self._session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n\n    def _timed_execute(self, tool: str, input_data: dict) -> tuple[dict, float]:\n        \"\"\"Execute a tool and return (result, latency_ms).\"\"\"\n        start = time.time()\n        resp = self._session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n            timeout=self.timeout_ms \u002F 1000.0,\n        )\n        latency_ms = (time.time() - start) * 1000\n        resp.raise_for_status()\n        return resp.json(), latency_ms\n\n    def run_health_check(self) -> dict:\n        \"\"\"Run a full synthetic transaction health check.\"\"\"\n        checks = {}\n        healthy = True\n        health_agent = f\"{self.agent_id}-{int(time.time())}\"\n\n        # Check 1: Wallet creation\n        try:\n            result, latency = self._timed_execute(\"create_wallet\", {})\n            checks[\"wallet\"] = {\"status\": \"pass\", \"latency_ms\": round(latency, 2)}\n        except Exception as e:\n            checks[\"wallet\"] = {\"status\": \"fail\", \"error\": str(e)}\n            healthy = False\n\n        # Check 2: Deposit\n        try:\n            result, latency = self._timed_execute(\"deposit\", {\"amount\": \"1.00\"})\n            checks[\"deposit\"] = {\"status\": \"pass\", \"latency_ms\": round(latency, 2)}\n        except Exception as e:\n            checks[\"deposit\"] = {\"status\": \"fail\", \"error\": str(e)}\n            healthy = False\n\n        # Check 3: Escrow creation\n        escrow_id = None\n        try:\n            result, latency = self._timed_execute(\"create_escrow\", {\n                \"payer_agent_id\": health_agent,\n                \"payee_agent_id\": f\"{health_agent}-payee\",\n                \"amount\": \"0.01\",\n                \"description\": \"Health check escrow\",\n            })\n            escrow_id = result.get(\"escrow_id\")\n            checks[\"escrow_create\"] = {\"status\": \"pass\", \"latency_ms\": round(latency, 2)}\n        except Exception as e:\n            checks[\"escrow_create\"] = {\"status\": \"fail\", \"error\": str(e)}\n            healthy = False\n\n        # Check 4: Escrow release\n        if escrow_id:\n            try:\n                result, latency = self._timed_execute(\"release_escrow\", {\n                    \"escrow_id\": escrow_id,\n                })\n                checks[\"escrow_release\"] = {\"status\": \"pass\", \"latency_ms\": round(latency, 2)}\n            except Exception as e:\n                checks[\"escrow_release\"] = {\"status\": \"fail\", \"error\": str(e)}\n                healthy = False\n        else:\n            checks[\"escrow_release\"] = {\"status\": \"skip\", \"reason\": \"no escrow_id\"}\n\n        # Check 5: Balance verification\n        try:\n            result, latency = self._timed_execute(\"get_balance\", {})\n            checks[\"balance_verify\"] = {\"status\": \"pass\", \"latency_ms\": round(latency, 2)}\n        except Exception as e:\n            checks[\"balance_verify\"] = {\"status\": \"fail\", \"error\": str(e)}\n            healthy = False\n\n        total_latency = sum(\n            c.get(\"latency_ms\", 0) for c in checks.values()\n        )\n\n        return {\n            \"healthy\": healthy,\n            \"checks\": checks,\n            \"total_latency_ms\": round(total_latency, 2),\n            \"timestamp\": time.time(),\n            \"agent_id\": self.agent_id,\n        }\n\n    def run_and_alert(self, alert_callback: Callable = None) -> dict:\n        \"\"\"Run health check and trigger alert callback on failure.\"\"\"\n        result = self.run_health_check()\n\n        if not result[\"healthy\"] and alert_callback:\n            failed_checks = {\n                name: check for name, check in result[\"checks\"].items()\n                if check.get(\"status\") == \"fail\"\n            }\n            alert_callback({\n                \"severity\": \"critical\",\n                \"title\": \"Agent Commerce Health Check Failed\",\n                \"failed_checks\": failed_checks,\n                \"timestamp\": result[\"timestamp\"],\n            })\n\n        return result\n```\n\n### Testing the HealthChecker\n\n```python\nclass TestHealthChecker:\n    \"\"\"Verify the health checker itself works correctly.\"\"\"\n\n    def test_reports_healthy_when_all_pass(self, harness):\n        \"\"\"All checks passing produces healthy=True.\"\"\"\n        harness.use_mocks()\n        harness.mock_tool(\"create_wallet\", {\"wallet_id\": \"w-health\"})\n        harness.mock_tool(\"deposit\", {\"balance\": \"1.00\", \"transaction_id\": \"tx-h\"})\n        harness.mock_tool(\"create_escrow\", {\n            \"escrow_id\": \"escrow-health\", \"status\": \"funded\",\n        })\n        harness.mock_tool(\"release_escrow\", {\n            \"escrow_id\": \"escrow-health\", \"status\": \"released\",\n        })\n        harness.mock_tool(\"get_balance\", {\"balance\": \"0.99\"})\n\n        # HealthChecker delegates to the harness in test mode\n        checker = HealthChecker(\n            api_key=harness.api_key,\n            agent_id=harness.agent_id,\n            base_url=harness.base_url,\n        )\n        # In real tests, patch _timed_execute to use harness\n        # Here we verify the structure\n        assert checker.timeout_ms == 5000.0\n\n    def test_reports_unhealthy_on_escrow_failure(self):\n        \"\"\"Failed escrow check produces healthy=False.\"\"\"\n        checker = HealthChecker(\n            api_key=\"test\",\n            agent_id=\"test\",\n            base_url=\"https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1\",\n        )\n\n        alerts_received = []\n        def mock_alert(alert):\n            alerts_received.append(alert)\n\n        # Patch to simulate failure -- in real code use sandbox\n        original = checker._timed_execute\n        def failing_execute(tool, input_data):\n            if tool == \"create_escrow\":\n                raise ConnectionError(\"Gateway timeout\")\n            return original(tool, input_data)\n\n        checker._timed_execute = failing_execute\n        try:\n            result = checker.run_and_alert(alert_callback=mock_alert)\n        except Exception:\n            pass  # Expected when wallet\u002Fdeposit also fail\n```\n\n### Dead Letter Queue for Webhooks\n\nWhen webhook delivery fails, events must not be silently dropped. Implement a dead letter queue that captures failed deliveries for retry (P4).\n\n```python\nclass WebhookDeadLetterQueue:\n    \"\"\"Captures failed webhook deliveries for manual retry.\"\"\"\n\n    def __init__(self, max_retries: int = 3, retry_delay_seconds: float = 60.0):\n        self.max_retries = max_retries\n        self.retry_delay_seconds = retry_delay_seconds\n        self._queue: list[dict] = []\n\n    def enqueue(self, event: dict, error: str):\n        \"\"\"Add a failed webhook event to the dead letter queue.\"\"\"\n        self._queue.append({\n            \"event\": event,\n            \"error\": error,\n            \"retries\": 0,\n            \"enqueued_at\": time.time(),\n            \"next_retry_at\": time.time() + self.retry_delay_seconds,\n        })\n\n    def get_pending(self) -> list[dict]:\n        \"\"\"Get events ready for retry.\"\"\"\n        now = time.time()\n        return [\n            entry for entry in self._queue\n            if entry[\"retries\"] \u003C self.max_retries\n            and entry[\"next_retry_at\"] \u003C= now\n        ]\n\n    def mark_delivered(self, event_id: str):\n        \"\"\"Remove a successfully retried event.\"\"\"\n        self._queue = [\n            e for e in self._queue\n            if e[\"event\"].get(\"event_id\") != event_id\n        ]\n\n    def mark_retried(self, event_id: str):\n        \"\"\"Increment retry count and schedule next attempt.\"\"\"\n        for entry in self._queue:\n            if entry[\"event\"].get(\"event_id\") == event_id:\n                entry[\"retries\"] += 1\n                entry[\"next_retry_at\"] = (\n                    time.time()\n                    + self.retry_delay_seconds * (2 ** entry[\"retries\"])\n                )\n                break\n\n    def get_dead_letters(self) -> list[dict]:\n        \"\"\"Get events that have exhausted all retries.\"\"\"\n        return [\n            entry for entry in self._queue\n            if entry[\"retries\"] >= self.max_retries\n        ]\n```\n\n---\n\n## Chapter 7: CI\u002FCD for Agent Systems\n\n### Running Tests in GitHub Actions\n\nAgent commerce tests require three things that standard CI does not provide: a GreenHelix API key for sandbox testing, isolation between parallel test runs (unique agent IDs), and network access to `sandbox.greenhelix.net`. This GitHub Actions template handles all three.\n\n```yaml\n# .github\u002Fworkflows\u002Fagent-commerce-tests.yml\nname: Agent Commerce Tests\n\non:\n  push:\n    branches: [main, develop]\n  pull_request:\n    branches: [main]\n\nenv:\n  GREENHELIX_API_KEY: ${{ secrets.GREENHELIX_API_KEY }}\n  GREENHELIX_BASE_URL: https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1\n\njobs:\n  # ── Layer 1: Fast mock-based tests (no network) ──────────\n  unit-tests:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n\n      - name: Set up Python\n        uses: actions\u002Fsetup-python@v5\n        with:\n          python-version: \"3.12\"\n\n      - name: Install dependencies\n        run: |\n          pip install pytest requests cryptography\n\n      - name: Run unit tests (Layer 1)\n        run: |\n          pytest tests\u002F -x -q \\\n            -m \"not sandbox and not chaos\" \\\n            --tb=short \\\n            --junit-xml=results\u002Funit-tests.xml\n\n      - name: Upload test results\n        if: always()\n        uses: actions\u002Fupload-artifact@v4\n        with:\n          name: unit-test-results\n          path: results\u002Funit-tests.xml\n\n  # ── Layer 2: Contract tests against sandbox ──────────────\n  contract-tests:\n    runs-on: ubuntu-latest\n    needs: unit-tests\n    steps:\n      - uses: actions\u002Fcheckout@v4\n\n      - name: Set up Python\n        uses: actions\u002Fsetup-python@v5\n        with:\n          python-version: \"3.12\"\n\n      - name: Install dependencies\n        run: pip install pytest requests cryptography\n\n      - name: Run contract tests (Layer 2)\n        run: |\n          pytest tests\u002F -x -q \\\n            -m \"sandbox and not chaos\" \\\n            --tb=short \\\n            --junit-xml=results\u002Fcontract-tests.xml\n        env:\n          GREENHELIX_API_KEY: ${{ secrets.GREENHELIX_API_KEY }}\n\n      - name: Upload test results\n        if: always()\n        uses: actions\u002Fupload-artifact@v4\n        with:\n          name: contract-test-results\n          path: results\u002Fcontract-tests.xml\n\n  # ── Layer 3 + 4: Integration and chaos tests ─────────────\n  integration-tests:\n    runs-on: ubuntu-latest\n    needs: contract-tests\n    steps:\n      - uses: actions\u002Fcheckout@v4\n\n      - name: Set up Python\n        uses: actions\u002Fsetup-python@v5\n        with:\n          python-version: \"3.12\"\n\n      - name: Install dependencies\n        run: pip install pytest requests cryptography\n\n      - name: Run integration tests (Layer 3)\n        run: |\n          pytest tests\u002F -x -q \\\n            -m \"integration\" \\\n            --tb=short \\\n            --junit-xml=results\u002Fintegration-tests.xml\n        env:\n          GREENHELIX_API_KEY: ${{ secrets.GREENHELIX_API_KEY }}\n\n      - name: Run chaos tests (Layer 4)\n        run: |\n          pytest tests\u002F -q \\\n            -m \"chaos\" \\\n            --tb=short \\\n            --junit-xml=results\u002Fchaos-tests.xml\n        env:\n          GREENHELIX_API_KEY: ${{ secrets.GREENHELIX_API_KEY }}\n        continue-on-error: true  # Chaos tests may have expected failures\n\n      - name: Upload all results\n        if: always()\n        uses: actions\u002Fupload-artifact@v4\n        with:\n          name: integration-test-results\n          path: results\u002F\n\n  # ── Health check against staging ─────────────────────────\n  staging-health:\n    runs-on: ubuntu-latest\n    needs: integration-tests\n    if: github.ref == 'refs\u002Fheads\u002Fmain'\n    steps:\n      - uses: actions\u002Fcheckout@v4\n\n      - name: Set up Python\n        uses: actions\u002Fsetup-python@v5\n        with:\n          python-version: \"3.12\"\n\n      - name: Install dependencies\n        run: pip install requests\n\n      - name: Run health check against staging\n        run: |\n          python -c \"\n          from health_checker import HealthChecker\n          import json, sys\n\n          checker = HealthChecker(\n              api_key='${{ secrets.GREENHELIX_API_KEY }}',\n              agent_id='ci-health-check',\n              base_url='https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1',\n          )\n          result = checker.run_health_check()\n          print(json.dumps(result, indent=2))\n\n          if not result['healthy']:\n              print('HEALTH CHECK FAILED')\n              sys.exit(1)\n          print('HEALTH CHECK PASSED')\n          \"\n```\n\n### Staging with the GreenHelix Sandbox\n\nThe sandbox at `sandbox.greenhelix.net` mirrors the production API exactly. Use it as your staging environment. Every test in Layers 2-4 runs against it. The sandbox resets balances nightly, so do not rely on state persisting between CI runs. Generate unique agent IDs per run using the `agent_id` fixture from the conftest (P1).\n\n```python\n# pytest.ini or pyproject.toml\n# [tool.pytest.ini_options]\n# markers:\n#     sandbox: Tests that require the GreenHelix sandbox\n#     chaos: Chaos testing with failure injection\n#     integration: Multi-step workflow integration tests\n\n@pytest.fixture\ndef ci_agent_id():\n    \"\"\"Generate a CI-unique agent ID to prevent collision.\"\"\"\n    run_id = os.environ.get(\"GITHUB_RUN_ID\", uuid.uuid4().hex[:8])\n    return f\"ci-agent-{run_id}-{uuid.uuid4().hex[:6]}\"\n```\n\n### Canary Deployments\n\nWhen deploying agent commerce changes, use a canary pattern: route 5% of traffic to the new version, monitor the `AgentTracer` metrics for 15 minutes, then promote or roll back.\n\n```python\nclass CanaryDeployment:\n    \"\"\"Canary deployment controller for agent commerce systems.\"\"\"\n\n    def __init__(\n        self,\n        canary_tracer: AgentTracer,\n        stable_tracer: AgentTracer,\n        promotion_threshold: float = 0.95,\n    ):\n        self.canary = canary_tracer\n        self.stable = stable_tracer\n        self.promotion_threshold = promotion_threshold\n\n    def evaluate(self) -> dict:\n        \"\"\"Compare canary metrics against stable baseline.\"\"\"\n        canary_metrics = self.canary.get_metrics()\n        stable_metrics = self.stable.get_metrics()\n\n        if canary_metrics[\"total_calls\"] \u003C 10:\n            return {\"decision\": \"waiting\", \"reason\": \"insufficient_data\"}\n\n        canary_success = canary_metrics.get(\"success_rate\", 0)\n        stable_success = stable_metrics.get(\"success_rate\", 1)\n\n        canary_latency = canary_metrics.get(\"p99_latency_ms\", 0)\n        stable_latency = stable_metrics.get(\"p99_latency_ms\", 1)\n\n        # Canary must match or beat stable on success rate\n        success_ok = canary_success >= stable_success * 0.98\n\n        # Canary latency must not regress more than 20%\n        latency_ok = canary_latency \u003C= stable_latency * 1.20\n\n        if success_ok and latency_ok:\n            return {\"decision\": \"promote\", \"canary_success\": canary_success}\n        else:\n            return {\n                \"decision\": \"rollback\",\n                \"reason\": (\n                    f\"success: {canary_success} vs {stable_success}, \"\n                    f\"p99: {canary_latency}ms vs {stable_latency}ms\"\n                ),\n            }\n```\n\n### Regression Detection\n\nTrack key metrics across CI runs to detect regressions before they reach production. Store the metrics as CI artifacts and compare against the previous run.\n\n```python\nclass RegressionDetector:\n    \"\"\"Detect metric regressions between CI runs.\"\"\"\n\n    def __init__(self, baseline_metrics: dict, current_metrics: dict):\n        self.baseline = baseline_metrics\n        self.current = current_metrics\n\n    def check(self) -> list[dict]:\n        \"\"\"Return a list of detected regressions.\"\"\"\n        regressions = []\n\n        # Success rate regression (any drop is a regression)\n        baseline_sr = self.baseline.get(\"success_rate\", 1.0)\n        current_sr = self.current.get(\"success_rate\", 1.0)\n        if current_sr \u003C baseline_sr - 0.01:\n            regressions.append({\n                \"metric\": \"success_rate\",\n                \"baseline\": baseline_sr,\n                \"current\": current_sr,\n                \"delta\": current_sr - baseline_sr,\n            })\n\n        # Latency regression (>20% increase at p95)\n        baseline_p95 = self.baseline.get(\"p95_latency_ms\", 0)\n        current_p95 = self.current.get(\"p95_latency_ms\", 0)\n        if baseline_p95 > 0 and current_p95 > baseline_p95 * 1.20:\n            regressions.append({\n                \"metric\": \"p95_latency_ms\",\n                \"baseline\": baseline_p95,\n                \"current\": current_p95,\n                \"delta_pct\": round(\n                    (current_p95 - baseline_p95) \u002F baseline_p95 * 100, 1\n                ),\n            })\n\n        # Error rate regression per tool\n        baseline_errors = self.baseline.get(\"error_rate_by_tool\", {})\n        current_errors = self.current.get(\"error_rate_by_tool\", {})\n        for tool, current_rate in current_errors.items():\n            baseline_rate = baseline_errors.get(tool, 0)\n            if current_rate > baseline_rate + 0.05:\n                regressions.append({\n                    \"metric\": f\"error_rate:{tool}\",\n                    \"baseline\": baseline_rate,\n                    \"current\": current_rate,\n                })\n\n        return regressions\n```\n\n---\n\n## Chapter 8: What to Do Next\n\nThis guide covered the four-layer agent testing pyramid, tool contract tests, saga-based workflow testing, chaos failure injection, production observability with the `AgentTracer`, alerting with the `HealthChecker`, and CI\u002FCD integration with GitHub Actions. The four classes -- `AgentTestHarness`, `ChaosMiddleware`, `AgentTracer`, and `HealthChecker` -- compose into a reliability stack that wraps every GreenHelix tool call from development through production.\n\nThe GreenHelix gateway's own test suite (260+ tests across 9 modules, with the gateway alone carrying 1,353 tests) uses the same patterns described here: deterministic mocks for business logic, sandbox integration tests for contract verification, and chaos-style failure injection for payment idempotency. The patterns in this guide are not theoretical -- they are extracted from the test infrastructure that protects the gateway itself.\n\n### Companion Guides\n\nFor the commerce patterns these tests protect, see the companion guides:\n\n- **Agent-to-Agent Commerce: Escrow, Payments, and Trust** (P1) -- the `AgentCommerce` class, escrow patterns, marketplace discovery, subscriptions, and dispute resolution.\n- **The AI Agent FinOps Playbook** (P2) -- the `AgentFinOps` class, per-agent budget caps, webhook alerts, fleet dashboards, and cost attribution.\n- **Verified Trading Bot Reputation** (P3) -- cryptographic PnL proof using Ed25519 signatures and Merkle claim chains.\n- **Tamper-Proof Audit Trails for Trading Bots** (P4) -- EU AI Act compliance, MiFID II reporting, and Merkle chain rotation.\n- **How to Verify Any AI Agent Before Doing Business** (P5) -- the `AgentVerifier` class, five-layer trust stack, and continuous reputation monitoring.\n- **The Agent Strategy Marketplace Playbook** (P6) -- selling verified trading strategies with performance escrow.\n- **Locking Down Agent Commerce** (P7) -- OWASP-aligned security hardening with `SecureAgent` and `SecurityMonitor`.\n- **The Agent SaaS Factory** (P8) -- autonomous micro-SaaS creation with `AgentDeveloper`, `AgentDBA`, and `AgentBilling`.\n\n### Practice on the Sandbox\n\nThe sandbox at `sandbox.greenhelix.net` is free to use with any API key. Run the `HealthChecker` against it. Deploy the GitHub Actions template. Break things deliberately with the `ChaosMiddleware`. The patterns in this guide are designed to be copied, adapted, and deployed today.\n\n### The Bundle\n\nAll eight companion guides plus this cookbook are available as a bundle. Each guide introduces a production-ready Python class. Together they cover the full lifecycle of agent commerce: building, securing, testing, monitoring, and scaling.\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: $29 | Format: Digital Guide | Updates: Lifetime access*\n\n","# The Agent Testing & Observability Cookbook: Ship Reliable Agent Commerce 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> - `AGENT_SIGNING_KEY`: Cryptographic signing key for agent identity (Ed25519 key pair for request signing)\n\n\nYour agent commerce system works on your laptop. It passes a smoke test against the GreenHelix sandbox. You deploy to production on a Friday afternoon and go home. By Saturday morning, a retry loop has created 47 duplicate escrows, a performance escrow released funds against stale metrics, and a settlement webhook silently failed for six hours because the endpoint returned 503 and nobody was watching. The system was never tested for these failures because the traditional testing pyramid -- unit tests at the bottom, integration tests in the middle, end-to-end tests at the top -- was not designed for autonomous agents that make financial decisions across unreliable networks against counterparties that may themselves be failing. This guide rebuilds the testing pyramid for agent commerce, then layers production observability, chaos testing, alerting, and CI\u002FCD on top. Every pattern is backed by working Python code, grounded in the 260-test suite that ships with the GreenHelix gateway, and designed to be copied directly into your project.\n1. [The Testing Pyramid for Agent Systems](#chapter-1-the-testing-pyramid-for-agent-systems)\n2. [Tool-Level Testing Patterns](#chapter-2-tool-level-testing-patterns)\n\n## What You'll Learn\n- Chapter 1: The Testing Pyramid for Agent Systems\n- Chapter 2: Tool-Level Testing Patterns\n- Chapter 3: Workflow & Integration Testing\n- Chapter 4: Chaos Testing for Agent Commerce\n- Chapter 5: Production Observability\n- Chapter 6: Alerting & Incident Response\n- Chapter 7: CI\u002FCD for Agent Systems\n- Chapter 8: What to Do Next\n\n## Full Guide\n\n# The Agent Testing & Observability Cookbook: Ship Reliable Agent Commerce Systems\n\nYour agent commerce system works on your laptop. It passes a smoke test against the GreenHelix sandbox. You deploy to production on a Friday afternoon and go home. By Saturday morning, a retry loop has created 47 duplicate escrows, a performance escrow released funds against stale metrics, and a settlement webhook silently failed for six hours because the endpoint returned 503 and nobody was watching. The system was never tested for these failures because the traditional testing pyramid -- unit tests at the bottom, integration tests in the middle, end-to-end tests at the top -- was not designed for autonomous agents that make financial decisions across unreliable networks against counterparties that may themselves be failing. This guide rebuilds the testing pyramid for agent commerce, then layers production observability, chaos testing, alerting, and CI\u002FCD on top. Every pattern is backed by working Python code, grounded in the 260-test suite that ships with the GreenHelix gateway, and designed to be copied directly into your project.\n\n---\n\n## Table of Contents\n\n1. [The Testing Pyramid for Agent Systems](#chapter-1-the-testing-pyramid-for-agent-systems)\n2. [Tool-Level Testing Patterns](#chapter-2-tool-level-testing-patterns)\n3. [Workflow & Integration Testing](#chapter-3-workflow--integration-testing)\n4. [Chaos Testing for Agent Commerce](#chapter-4-chaos-testing-for-agent-commerce)\n5. [Production Observability](#chapter-5-production-observability)\n6. [Alerting & Incident Response](#chapter-6-alerting--incident-response)\n7. [CI\u002FCD for Agent Systems](#chapter-7-cicd-for-agent-systems)\n8. [What to Do Next](#chapter-8-what-to-do-next)\n\n---\n\n## Chapter 1: The Testing Pyramid for Agent Systems\n\n### Why the Traditional Pyramid Breaks\n\nThe standard testing pyramid assumes your code calls functions that return values. Unit tests verify individual functions. Integration tests verify that modules compose correctly. End-to-end tests verify the full user flow. This model works when the system under test is deterministic, when function calls do not have financial side effects, and when failure modes are limited to \"returns wrong value\" or \"throws exception.\"\n\nAgent commerce systems violate all three assumptions. A call to `create_escrow` locks real funds. A call to `release_escrow` transfers real money. A retry that fires twice creates two escrows, not one error. The failure modes are not \"wrong return value\" -- they are \"agent paid twice for the same work,\" \"escrow timed out but funds are still locked,\" and \"settlement succeeded on the gateway but the webhook notification was lost.\" Traditional unit tests cannot catch these failures because they test the code in isolation from the financial state machine. Traditional end-to-end tests cannot catch them because they run the happy path once and call it done.\n\n### The Agent Testing Pyramid\n\nAgent commerce requires a four-layer testing pyramid that maps to the actual failure modes:\n\n```\n                    ╱╲\n                   ╱  ╲\n                  ╱Chaos╲           Layer 4: Chaos tests\n                 ╱  Tests ╲         (failure injection, timeouts,\n                ╱──────────╲        concurrent load)\n               ╱ Multi-Agent ╲      Layer 3: Multi-agent workflow tests\n              ╱   Workflows   ╲     (sagas, rollbacks, webhook delivery)\n             ╱─────────────────╲\n            ╱   Tool Contract    ╲   Layer 2: Tool-level contract tests\n           ╱      Tests           ╲  (schema, idempotency, permissions)\n          ╱────────────────────────╲\n         ╱    Deterministic Mocks    ╲ Layer 1: Mock-based unit tests\n        ╱      (fast, offline)        ╲ (business logic, validation)\n       ╱───────────────────────────────╲\n```\n\n**Layer 1: Deterministic mocks** test your business logic without hitting the gateway. They run in milliseconds and catch logic errors: wrong amount calculations, missing trust checks, incorrect state transitions. These are 60% of your tests.\n\n**Layer 2: Tool contract tests** verify that each GreenHelix tool accepts the expected input schema, returns the expected output shape, and produces the correct error codes for invalid input. These run against the sandbox and catch API contract changes. These are 25% of your tests.\n\n**Layer 3: Multi-agent workflow tests** verify complete business flows: marketplace listing through escrow release through settlement. They test the saga pattern (multi-step rollback on failure) and webhook delivery. These are 10% of your tests.\n\n**Layer 4: Chaos tests** inject failures -- network timeouts, random tool errors, concurrent duplicate requests -- and verify that the system recovers without financial inconsistency. These are 5% of your tests but catch the bugs that cost the most money.\n\n### The AgentTestHarness\n\nEvery test in this guide uses the `AgentTestHarness` class. It manages fixtures, provides deterministic mocks for Layer 1, and switches to sandbox mode for Layers 2-4.\n\n```python\nimport pytest\nimport time\nimport json\nimport uuid\nimport requests\nfrom unittest.mock import MagicMock, patch\nfrom typing import Optional\nfrom dataclasses import dataclass, field\n\n\n@dataclass\nclass MockResponse:\n    \"\"\"Deterministic mock for a GreenHelix tool response.\"\"\"\n    tool: str\n    status: str = \"success\"\n    data: dict = field(default_factory=dict)\n    error_code: Optional[str] = None\n    error_message: Optional[str] = None\n\n    def to_dict(self) -> dict:\n        result = {\"status\": self.status}\n        if self.status == \"success\":\n            result.update(self.data)\n        else:\n            result[\"error\"] = {\n                \"code\": self.error_code or \"unknown_error\",\n                \"message\": self.error_message or \"An error occurred\",\n            }\n        return result\n\n\nclass AgentTestHarness:\n    \"\"\"Test harness for GreenHelix agent commerce systems.\n\n    Manages fixtures, mocks, and sandbox connections for all four\n    layers of the agent testing pyramid.\n\n    Usage:\n        harness = AgentTestHarness(\n            api_key=\"test-key\",\n            agent_id=\"test-agent\",\n            base_url=\"https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1\",\n        )\n\n        # Layer 1: deterministic mocks\n        harness.mock_tool(\"get_balance\", {\"balance\": \"100.00\"})\n        result = harness.execute(\"get_balance\", {})\n        assert result[\"balance\"] == \"100.00\"\n\n        # Layer 2+: sandbox mode\n        harness.use_sandbox()\n        result = harness.execute(\"get_balance\", {})\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    ):\n        self.api_key = api_key\n        self.agent_id = agent_id\n        self.base_url = base_url\n        self._mocks: dict[str, MockResponse] = {}\n        self._call_log: list[dict] = []\n        self._sandbox_mode = False\n        self._session = requests.Session()\n        self._session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n\n    # ── Mode Control ───────────────────────────────────────────\n\n    def use_mocks(self):\n        \"\"\"Switch to deterministic mock mode (Layer 1).\"\"\"\n        self._sandbox_mode = False\n\n    def use_sandbox(self):\n        \"\"\"Switch to live sandbox mode (Layer 2+).\"\"\"\n        self._sandbox_mode = True\n\n    # ── Mock Registration ──────────────────────────────────────\n\n    def mock_tool(self, tool: str, data: dict, status: str = \"success\"):\n        \"\"\"Register a deterministic mock response for a tool.\"\"\"\n        self._mocks[tool] = MockResponse(tool=tool, status=status, data=data)\n\n    def mock_tool_error(\n        self, tool: str, error_code: str, error_message: str\n    ):\n        \"\"\"Register a deterministic error response for a tool.\"\"\"\n        self._mocks[tool] = MockResponse(\n            tool=tool,\n            status=\"error\",\n            error_code=error_code,\n            error_message=error_message,\n        )\n\n    def mock_tool_sequence(self, tool: str, responses: list[dict]):\n        \"\"\"Register a sequence of responses for successive calls.\"\"\"\n        self._mock_sequences = getattr(self, \"_mock_sequences\", {})\n        self._mock_sequences[tool] = list(responses)\n\n    # ── Execution ──────────────────────────────────────────────\n\n    def execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute a tool against mocks or sandbox.\"\"\"\n        call_record = {\n            \"tool\": tool,\n            \"input\": input_data,\n            \"timestamp\": time.time(),\n        }\n\n        if self._sandbox_mode:\n            resp = self._session.post(\n                f\"{self.base_url}\u002Fv1\",\n                json={\"tool\": tool, \"input\": input_data},\n            )\n            resp.raise_for_status()\n            result = resp.json()\n        else:\n            # Check sequences first\n            sequences = getattr(self, \"_mock_sequences\", {})\n            if tool in sequences and sequences[tool]:\n                result = sequences[tool].pop(0)\n            elif tool in self._mocks:\n                result = self._mocks[tool].to_dict()\n            else:\n                raise ValueError(\n                    f\"No mock registered for tool '{tool}'. \"\n                    f\"Register with harness.mock_tool('{tool}', {{...}})\"\n                )\n\n        call_record[\"result\"] = result\n        self._call_log.append(call_record)\n        return result\n\n    # ── Assertions ─────────────────────────────────────────────\n\n    def assert_tool_called(self, tool: str, times: Optional[int] = None):\n        \"\"\"Assert that a tool was called, optionally a specific number of times.\"\"\"\n        calls = [c for c in self._call_log if c[\"tool\"] == tool]\n        assert len(calls) > 0, f\"Tool '{tool}' was never called\"\n        if times is not None:\n            assert len(calls) == times, (\n                f\"Tool '{tool}' called {len(calls)} times, expected {times}\"\n            )\n\n    def assert_tool_not_called(self, tool: str):\n        \"\"\"Assert that a tool was never called.\"\"\"\n        calls = [c for c in self._call_log if c[\"tool\"] == tool]\n        assert len(calls) == 0, (\n            f\"Tool '{tool}' was called {len(calls)} times, expected 0\"\n        )\n\n    def assert_call_order(self, tools: list[str]):\n        \"\"\"Assert that tools were called in a specific order.\"\"\"\n        called_tools = [c[\"tool\"] for c in self._call_log]\n        idx = 0\n        for tool in tools:\n            try:\n                idx = called_tools.index(tool, idx) + 1\n            except ValueError:\n                assert False, (\n                    f\"Expected '{tool}' after position {idx} in call log. \"\n                    f\"Actual order: {called_tools}\"\n                )\n\n    def get_calls(self, tool: Optional[str] = None) -> list[dict]:\n        \"\"\"Get call log, optionally filtered by tool name.\"\"\"\n        if tool:\n            return [c for c in self._call_log if c[\"tool\"] == tool]\n        return list(self._call_log)\n\n    def reset(self):\n        \"\"\"Clear all mocks and call history.\"\"\"\n        self._mocks.clear()\n        self._call_log.clear()\n        if hasattr(self, \"_mock_sequences\"):\n            self._mock_sequences.clear()\n```\n\n### The conftest.py: Reusable Fixtures\n\nDrop this `conftest.py` into your test directory. Every test file in this guide imports from it.\n\n```python\n# tests\u002Fconftest.py\nimport os\nimport uuid\nimport pytest\n\n\n@pytest.fixture\ndef api_key():\n    \"\"\"API key for sandbox testing. Uses env var or test default.\"\"\"\n    return os.environ.get(\"GREENHELIX_API_KEY\", \"test-api-key-sandbox\")\n\n\n@pytest.fixture\ndef base_url():\n    \"\"\"Sandbox URL for integration tests.\"\"\"\n    return os.environ.get(\n        \"GREENHELIX_BASE_URL\", \"https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1\"\n    )\n\n\n@pytest.fixture\ndef agent_id():\n    \"\"\"Unique agent ID per test run to prevent collision.\"\"\"\n    return f\"test-agent-{uuid.uuid4().hex[:12]}\"\n\n\n@pytest.fixture\ndef buyer_id():\n    \"\"\"Unique buyer agent ID.\"\"\"\n    return f\"test-buyer-{uuid.uuid4().hex[:12]}\"\n\n\n@pytest.fixture\ndef seller_id():\n    \"\"\"Unique seller agent ID.\"\"\"\n    return f\"test-seller-{uuid.uuid4().hex[:12]}\"\n\n\n@pytest.fixture\ndef harness(api_key, agent_id, base_url):\n    \"\"\"AgentTestHarness in mock mode. Call harness.use_sandbox() for live.\"\"\"\n    h = AgentTestHarness(\n        api_key=api_key,\n        agent_id=agent_id,\n        base_url=base_url,\n    )\n    h.use_mocks()\n    return h\n\n\n@pytest.fixture\ndef sandbox_harness(api_key, agent_id, base_url):\n    \"\"\"AgentTestHarness in sandbox mode for integration tests.\"\"\"\n    h = AgentTestHarness(\n        api_key=api_key,\n        agent_id=agent_id,\n        base_url=base_url,\n    )\n    h.use_sandbox()\n    return h\n\n\n@pytest.fixture\ndef mock_session():\n    \"\"\"Pre-configured requests.Session mock for unit tests.\"\"\"\n    session = MagicMock()\n    response = MagicMock()\n    response.status_code = 200\n    response.json.return_value = {\"status\": \"success\"}\n    response.raise_for_status.return_value = None\n    session.post.return_value = response\n    return session\n\n\n@pytest.fixture\ndef mock_response():\n    \"\"\"Factory fixture for creating MockResponse objects.\"\"\"\n    def _make(tool, data=None, status=\"success\", error_code=None):\n        return MockResponse(\n            tool=tool,\n            status=status,\n            data=data or {},\n            error_code=error_code,\n        )\n    return _make\n\n\n# ── Per-class fixtures for isolated test suites ─────────────\n\nclass AgentFixtures:\n    \"\"\"Mixin providing standard mocks for agent commerce tests.\"\"\"\n\n    @pytest.fixture(autouse=True)\n    def setup_agent_mocks(self, harness):\n        \"\"\"Pre-register common mocks for every test in the class.\"\"\"\n        self.harness = harness\n        harness.mock_tool(\"get_balance\", {\"balance\": \"500.00\", \"currency\": \"USD\"})\n        harness.mock_tool(\"create_wallet\", {\"wallet_id\": \"w-test-001\", \"status\": \"active\"})\n        harness.mock_tool(\"register_agent\", {\"agent_id\": harness.agent_id, \"status\": \"registered\"})\n        harness.mock_tool(\"get_trust_score\", {\"agent_id\": \"any\", \"score\": 0.85})\n        harness.mock_tool(\"get_budget_status\", {\n            \"daily_limit\": \"100.00\",\n            \"spent_today\": \"25.00\",\n            \"remaining\": \"75.00\",\n        })\n\n\nclass EscrowFixtures(AgentFixtures):\n    \"\"\"Extended fixtures for escrow-related tests.\"\"\"\n\n    @pytest.fixture(autouse=True)\n    def setup_escrow_mocks(self, harness):\n        \"\"\"Add escrow mocks on top of agent mocks.\"\"\"\n        self.escrow_id = f\"escrow-{uuid.uuid4().hex[:8]}\"\n        harness.mock_tool(\"create_escrow\", {\n            \"escrow_id\": self.escrow_id,\n            \"status\": \"funded\",\n            \"amount\": \"50.00\",\n        })\n        harness.mock_tool(\"release_escrow\", {\n            \"escrow_id\": self.escrow_id,\n            \"status\": \"released\",\n        })\n        harness.mock_tool(\"cancel_escrow\", {\n            \"escrow_id\": self.escrow_id,\n            \"status\": \"cancelled\",\n        })\n```\n\n### Pattern: Deterministic Mocks vs. Sandbox Testing\n\nThe harness supports both modes. Use mocks for business logic tests (fast, no network, deterministic). Use sandbox for contract and integration tests (real API, real state, real latency).\n\n```python\nclass TestBudgetGuardrails(AgentFixtures):\n    \"\"\"Layer 1: Test budget logic with deterministic mocks.\"\"\"\n\n    def test_blocks_escrow_when_over_budget(self, harness):\n        \"\"\"Escrow creation should be blocked when daily budget is exhausted.\"\"\"\n        harness.mock_tool(\"get_budget_status\", {\n            \"daily_limit\": \"100.00\",\n            \"spent_today\": \"99.00\",\n            \"remaining\": \"1.00\",\n        })\n        budget = harness.execute(\"get_budget_status\", {})\n        remaining = float(budget[\"remaining\"])\n        escrow_amount = 50.00\n\n        # Business logic: do not create escrow if amount > remaining\n        assert escrow_amount > remaining\n        harness.assert_tool_not_called(\"create_escrow\")\n\n    def test_allows_escrow_within_budget(self, harness):\n        \"\"\"Escrow creation should proceed when budget allows.\"\"\"\n        budget = harness.execute(\"get_budget_status\", {})\n        remaining = float(budget[\"remaining\"])\n        escrow_amount = 25.00\n\n        assert escrow_amount \u003C= remaining\n        harness.execute(\"create_escrow\", {\n            \"payer_agent_id\": harness.agent_id,\n            \"payee_agent_id\": \"seller-001\",\n            \"amount\": str(escrow_amount),\n        })\n        harness.assert_tool_called(\"create_escrow\", times=1)\n\n\n@pytest.mark.sandbox\nclass TestBudgetGuardrailsSandbox:\n    \"\"\"Layer 2: Verify budget tools against live sandbox.\"\"\"\n\n    def test_budget_cap_enforced(self, sandbox_harness):\n        \"\"\"Sandbox should reject escrows exceeding the budget cap.\"\"\"\n        h = sandbox_harness\n        h.execute(\"create_wallet\", {})\n        h.execute(\"deposit\", {\"amount\": \"100.00\"})\n        h.execute(\"set_budget_cap\", {\n            \"agent_id\": h.agent_id,\n            \"daily_limit\": \"10.00\",\n        })\n        # This should fail because escrow exceeds daily limit\n        result = h.execute(\"create_escrow\", {\n            \"payer_agent_id\": h.agent_id,\n            \"payee_agent_id\": \"seller-test\",\n            \"amount\": \"50.00\",\n        })\n        # Gateway enforces budget at the tool level\n        assert result.get(\"status\") in (\"error\", \"rejected\")\n```\n\n---\n\n## Chapter 2: Tool-Level Testing Patterns\n\n### The Tool Contract Test\n\nEvery GreenHelix tool has an implicit contract: it accepts a specific input schema, returns a specific output shape, and produces documented error codes for invalid input. A tool contract test verifies all three. When the gateway updates an API version or adds a required field, your contract tests break before your production code does.\n\n```python\nclass ToolContract:\n    \"\"\"Defines the expected contract for a GreenHelix tool.\n\n    Used by contract tests to verify schema, output shape,\n    and error behavior against the sandbox.\n    \"\"\"\n\n    def __init__(\n        self,\n        tool: str,\n        required_fields: list[str],\n        output_fields: list[str],\n        error_cases: dict[str, dict],\n    ):\n        self.tool = tool\n        self.required_fields = required_fields\n        self.output_fields = output_fields\n        self.error_cases = error_cases  # {case_name: {input: ..., expected_error: ...}}\n\n\n# ── Contract definitions for core tools ────────────────────\n\nBILLING_CONTRACTS = {\n    \"get_balance\": ToolContract(\n        tool=\"get_balance\",\n        required_fields=[],\n        output_fields=[\"balance\", \"currency\"],\n        error_cases={\n            \"no_wallet\": {\n                \"input\": {},\n                \"expected_error\": \"wallet_not_found\",\n            },\n        },\n    ),\n    \"deposit\": ToolContract(\n        tool=\"deposit\",\n        required_fields=[\"amount\"],\n        output_fields=[\"balance\", \"transaction_id\"],\n        error_cases={\n            \"negative_amount\": {\n                \"input\": {\"amount\": \"-10.00\"},\n                \"expected_error\": \"invalid_amount\",\n            },\n            \"zero_amount\": {\n                \"input\": {\"amount\": \"0\"},\n                \"expected_error\": \"invalid_amount\",\n            },\n        },\n    ),\n    \"set_budget_cap\": ToolContract(\n        tool=\"set_budget_cap\",\n        required_fields=[\"agent_id\", \"daily_limit\"],\n        output_fields=[\"agent_id\", \"daily_limit\"],\n        error_cases={\n            \"negative_limit\": {\n                \"input\": {\"agent_id\": \"test\", \"daily_limit\": \"-50.00\"},\n                \"expected_error\": \"invalid_amount\",\n            },\n        },\n    ),\n}\n\nPAYMENT_CONTRACTS = {\n    \"create_escrow\": ToolContract(\n        tool=\"create_escrow\",\n        required_fields=[\"payer_agent_id\", \"payee_agent_id\", \"amount\"],\n        output_fields=[\"escrow_id\", \"status\", \"amount\"],\n        error_cases={\n            \"insufficient_funds\": {\n                \"input\": {\n                    \"payer_agent_id\": \"buyer\",\n                    \"payee_agent_id\": \"seller\",\n                    \"amount\": \"999999.00\",\n                },\n                \"expected_error\": \"insufficient_funds\",\n            },\n            \"self_escrow\": {\n                \"input\": {\n                    \"payer_agent_id\": \"same-agent\",\n                    \"payee_agent_id\": \"same-agent\",\n                    \"amount\": \"10.00\",\n                },\n                \"expected_error\": \"invalid_escrow\",\n            },\n        },\n    ),\n    \"release_escrow\": ToolContract(\n        tool=\"release_escrow\",\n        required_fields=[\"escrow_id\"],\n        output_fields=[\"escrow_id\", \"status\"],\n        error_cases={\n            \"nonexistent\": {\n                \"input\": {\"escrow_id\": \"escrow-does-not-exist\"},\n                \"expected_error\": \"escrow_not_found\",\n            },\n        },\n    ),\n}\n\nIDENTITY_CONTRACTS = {\n    \"register_agent\": ToolContract(\n        tool=\"register_agent\",\n        required_fields=[\"agent_id\", \"public_key\", \"name\"],\n        output_fields=[\"agent_id\", \"status\"],\n        error_cases={\n            \"missing_key\": {\n                \"input\": {\"agent_id\": \"test\", \"name\": \"Test\"},\n                \"expected_error\": \"missing_field\",\n            },\n        },\n    ),\n    \"get_trust_score\": ToolContract(\n        tool=\"get_trust_score\",\n        required_fields=[\"agent_id\"],\n        output_fields=[\"agent_id\", \"score\"],\n        error_cases={\n            \"nonexistent_agent\": {\n                \"input\": {\"agent_id\": \"agent-that-does-not-exist-xyz\"},\n                \"expected_error\": \"agent_not_found\",\n            },\n        },\n    ),\n}\n\nMARKETPLACE_CONTRACTS = {\n    \"register_service\": ToolContract(\n        tool=\"register_service\",\n        required_fields=[\"name\", \"description\", \"endpoint\", \"price\", \"tags\", \"category\"],\n        output_fields=[\"service_id\"],\n        error_cases={\n            \"missing_name\": {\n                \"input\": {\n                    \"description\": \"test\",\n                    \"endpoint\": \"agent:\u002F\u002Ftest\",\n                    \"price\": 10.0,\n                    \"tags\": [],\n                    \"category\": \"test\",\n                },\n                \"expected_error\": \"missing_field\",\n            },\n        },\n    ),\n    \"search_services\": ToolContract(\n        tool=\"search_services\",\n        required_fields=[\"query\"],\n        output_fields=[\"services\"],\n        error_cases={\n            \"empty_query\": {\n                \"input\": {\"query\": \"\"},\n                \"expected_error\": \"invalid_query\",\n            },\n        },\n    ),\n}\n```\n\n### Running Contract Tests\n\n```python\n@pytest.mark.sandbox\nclass TestBillingContracts:\n    \"\"\"Layer 2: Verify billing tool contracts against sandbox.\"\"\"\n\n    @pytest.fixture(autouse=True)\n    def setup_wallet(self, sandbox_harness):\n        self.harness = sandbox_harness\n        self.harness.execute(\"create_wallet\", {})\n        self.harness.execute(\"deposit\", {\"amount\": \"100.00\"})\n\n    @pytest.mark.parametrize(\"tool_name\", BILLING_CONTRACTS.keys())\n    def test_output_shape(self, tool_name):\n        \"\"\"Every billing tool returns expected output fields.\"\"\"\n        contract = BILLING_CONTRACTS[tool_name]\n        # Build minimal valid input\n        valid_input = {}\n        if tool_name == \"deposit\":\n            valid_input = {\"amount\": \"10.00\"}\n        elif tool_name == \"set_budget_cap\":\n            valid_input = {\n                \"agent_id\": self.harness.agent_id,\n                \"daily_limit\": \"50.00\",\n            }\n        result = self.harness.execute(tool_name, valid_input)\n        for expected_field in contract.output_fields:\n            assert expected_field in result, (\n                f\"Tool '{tool_name}' missing output field '{expected_field}'. \"\n                f\"Got: {list(result.keys())}\"\n            )\n\n    @pytest.mark.parametrize(\"tool_name\", BILLING_CONTRACTS.keys())\n    def test_error_cases(self, tool_name):\n        \"\"\"Every billing tool returns correct error codes for invalid input.\"\"\"\n        contract = BILLING_CONTRACTS[tool_name]\n        for case_name, case in contract.error_cases.items():\n            result = self.harness.execute(tool_name, case[\"input\"])\n            assert result.get(\"status\") == \"error\" or \"error\" in result, (\n                f\"Tool '{tool_name}' case '{case_name}' should have failed. \"\n                f\"Got: {result}\"\n            )\n\n\n@pytest.mark.sandbox\nclass TestPaymentContracts:\n    \"\"\"Layer 2: Verify payment tool contracts against sandbox.\"\"\"\n\n    @pytest.fixture(autouse=True)\n    def setup_accounts(self, sandbox_harness, buyer_id, seller_id):\n        self.harness = sandbox_harness\n        self.buyer_id = buyer_id\n        self.seller_id = seller_id\n\n    @pytest.mark.parametrize(\"tool_name\", PAYMENT_CONTRACTS.keys())\n    def test_error_cases(self, tool_name):\n        \"\"\"Every payment tool returns correct errors for invalid input.\"\"\"\n        contract = PAYMENT_CONTRACTS[tool_name]\n        for case_name, case in contract.error_cases.items():\n            result = self.harness.execute(tool_name, case[\"input\"])\n            assert result.get(\"status\") == \"error\" or \"error\" in result, (\n                f\"Payment tool '{tool_name}' case '{case_name}' did not fail\"\n            )\n```\n\n### Idempotency Testing for Payment Tools\n\nPayment tools must be idempotent. Calling `create_escrow` twice with the same parameters should not create two escrows. Calling `release_escrow` twice should not transfer funds twice. This pattern tests idempotency by submitting duplicate requests and verifying financial consistency (P1, P7).\n\n```python\n@pytest.mark.sandbox\nclass TestPaymentIdempotency:\n    \"\"\"Layer 2: Verify payment tools handle duplicate calls safely.\"\"\"\n\n    def test_duplicate_escrow_creation(self, sandbox_harness, buyer_id, seller_id):\n        \"\"\"Creating the same escrow twice should return the same escrow_id.\"\"\"\n        h = sandbox_harness\n        h.execute(\"create_wallet\", {})\n        h.execute(\"deposit\", {\"amount\": \"200.00\"})\n\n        escrow_params = {\n            \"payer_agent_id\": buyer_id,\n            \"payee_agent_id\": seller_id,\n            \"amount\": \"50.00\",\n            \"description\": \"Idempotency test escrow\",\n            \"idempotency_key\": f\"idem-{uuid.uuid4().hex[:8]}\",\n        }\n\n        result_1 = h.execute(\"create_escrow\", escrow_params)\n        result_2 = h.execute(\"create_escrow\", escrow_params)\n\n        # Same idempotency key should return same escrow\n        assert result_1[\"escrow_id\"] == result_2[\"escrow_id\"]\n\n        # Balance should only be debited once\n        balance = h.execute(\"get_balance\", {})\n        assert float(balance[\"balance\"]) == 150.00\n\n    def test_duplicate_release(self, sandbox_harness):\n        \"\"\"Releasing the same escrow twice should not double-pay.\"\"\"\n        h = sandbox_harness\n        h.execute(\"create_wallet\", {})\n        h.execute(\"deposit\", {\"amount\": \"100.00\"})\n\n        escrow = h.execute(\"create_escrow\", {\n            \"payer_agent_id\": h.agent_id,\n            \"payee_agent_id\": \"seller-test\",\n            \"amount\": \"25.00\",\n        })\n        escrow_id = escrow[\"escrow_id\"]\n\n        release_1 = h.execute(\"release_escrow\", {\"escrow_id\": escrow_id})\n        release_2 = h.execute(\"release_escrow\", {\"escrow_id\": escrow_id})\n\n        # Second release should be a no-op or return already_released\n        assert release_1.get(\"status\") == \"released\"\n        assert release_2.get(\"status\") in (\"released\", \"already_released\")\n```\n\n### Permission Boundary Testing\n\nAgents should only be able to operate on their own resources. A buyer should not release an escrow created by a different buyer. A seller should not cancel an escrow that is not addressed to them. Permission boundary tests verify these invariants (P7).\n\n```python\n@pytest.mark.sandbox\nclass TestPermissionBoundaries:\n    \"\"\"Layer 2: Verify agents cannot access other agents' resources.\"\"\"\n\n    def test_cannot_release_others_escrow(self, sandbox_harness):\n        \"\"\"Agent A cannot release an escrow created by Agent B.\"\"\"\n        h = sandbox_harness\n        # Agent A creates an escrow\n        h.execute(\"create_wallet\", {})\n        h.execute(\"deposit\", {\"amount\": \"100.00\"})\n        escrow = h.execute(\"create_escrow\", {\n            \"payer_agent_id\": h.agent_id,\n            \"payee_agent_id\": \"seller-x\",\n            \"amount\": \"10.00\",\n        })\n\n        # Agent B (different harness\u002Fsession) tries to release it\n        other = AgentTestHarness(\n            api_key=h.api_key,\n            agent_id=\"attacker-agent\",\n            base_url=h.base_url,\n        )\n        other.use_sandbox()\n        result = other.execute(\"release_escrow\", {\n            \"escrow_id\": escrow[\"escrow_id\"],\n        })\n        assert result.get(\"status\") == \"error\"\n\n    def test_cannot_read_others_balance(self, sandbox_harness):\n        \"\"\"Agent A cannot read Agent B's wallet balance.\"\"\"\n        h = sandbox_harness\n        h.execute(\"create_wallet\", {})\n        h.execute(\"deposit\", {\"amount\": \"100.00\"})\n\n        other = AgentTestHarness(\n            api_key=h.api_key,\n            agent_id=\"other-agent\",\n            base_url=h.base_url,\n        )\n        other.use_sandbox()\n        result = other.execute(\"get_balance\", {})\n        # Should return the other agent's balance (0), not our 100\n        balance = float(result.get(\"balance\", 0))\n        assert balance != 100.00\n\n    def test_cannot_cancel_others_escrow(self, sandbox_harness):\n        \"\"\"Seller cannot cancel an escrow -- only the buyer can.\"\"\"\n        h = sandbox_harness\n        h.execute(\"create_wallet\", {})\n        h.execute(\"deposit\", {\"amount\": \"50.00\"})\n        escrow = h.execute(\"create_escrow\", {\n            \"payer_agent_id\": h.agent_id,\n            \"payee_agent_id\": \"seller-y\",\n            \"amount\": \"10.00\",\n        })\n\n        seller = AgentTestHarness(\n            api_key=h.api_key,\n            agent_id=\"seller-y\",\n            base_url=h.base_url,\n        )\n        seller.use_sandbox()\n        result = seller.execute(\"cancel_escrow\", {\n            \"escrow_id\": escrow[\"escrow_id\"],\n        })\n        assert result.get(\"status\") == \"error\"\n```\n\n---\n\n## Chapter 3: Workflow & Integration Testing\n\n### The Saga Test Pattern\n\nAgent commerce workflows are sagas: multi-step operations where each step has a compensating action. If step 3 fails, steps 1 and 2 must be rolled back. The saga test pattern verifies both the happy path and every possible failure point.\n\n```python\nclass MarketplaceSaga:\n    \"\"\"Implements the complete marketplace listing workflow as a testable saga.\n\n    Steps:\n        1. Seller registers service on marketplace\n        2. Buyer discovers service via search\n        3. Buyer checks seller trust score\n        4. Buyer creates escrow\n        5. Seller performs work (simulated)\n        6. Buyer releases escrow\n        7. Buyer rates service\n        8. Settlement completes\n\n    Compensating actions:\n        Step 4 fails → no cleanup needed (funds not locked)\n        Step 5 fails → cancel escrow (return funds to buyer)\n        Step 6 fails → open dispute\n    \"\"\"\n\n    def __init__(self, harness: AgentTestHarness, buyer_id: str, seller_id: str):\n        self.harness = harness\n        self.buyer_id = buyer_id\n        self.seller_id = seller_id\n        self.state = {\"step\": 0, \"completed_steps\": []}\n\n    def run(self) -> dict:\n        \"\"\"Execute the full saga, rolling back on failure.\"\"\"\n        try:\n            # Step 1: Register service\n            service = self.harness.execute(\"register_service\", {\n                \"name\": \"Test Summarization Service\",\n                \"description\": \"Summarizes documents for testing\",\n                \"endpoint\": f\"agent:\u002F\u002F{self.seller_id}\",\n                \"price\": 25.00,\n                \"tags\": [\"test\", \"summarization\"],\n                \"category\": \"data-processing\",\n            })\n            self.state[\"service_id\"] = service[\"service_id\"]\n            self.state[\"completed_steps\"].append(\"register_service\")\n\n            # Step 2: Discover service\n            results = self.harness.execute(\"search_services\", {\n                \"query\": \"test summarization\",\n            })\n            assert len(results.get(\"services\", [])) > 0\n            self.state[\"completed_steps\"].append(\"discover_service\")\n\n            # Step 3: Trust check\n            trust = self.harness.execute(\"get_trust_score\", {\n                \"agent_id\": self.seller_id,\n            })\n            if trust.get(\"score\", 0) \u003C 0.5:\n                return {\"status\": \"aborted\", \"reason\": \"low_trust\"}\n            self.state[\"completed_steps\"].append(\"trust_check\")\n\n            # Step 4: Create escrow\n            escrow = self.harness.execute(\"create_escrow\", {\n                \"payer_agent_id\": self.buyer_id,\n                \"payee_agent_id\": self.seller_id,\n                \"amount\": \"25.00\",\n                \"description\": \"Saga test escrow\",\n            })\n            self.state[\"escrow_id\"] = escrow[\"escrow_id\"]\n            self.state[\"completed_steps\"].append(\"create_escrow\")\n\n            # Step 5: Simulate work (in real tests, call seller endpoint)\n            work_result = {\"quality\": 0.95, \"documents_processed\": 500}\n            self.state[\"completed_steps\"].append(\"work_completed\")\n\n            # Step 6: Release escrow\n            release = self.harness.execute(\"release_escrow\", {\n                \"escrow_id\": escrow[\"escrow_id\"],\n            })\n            self.state[\"completed_steps\"].append(\"release_escrow\")\n\n            # Step 7: Rate service\n            self.harness.execute(\"rate_service\", {\n                \"service_id\": service[\"service_id\"],\n                \"rating\": 5,\n            })\n            self.state[\"completed_steps\"].append(\"rate_service\")\n\n            return {\"status\": \"completed\", \"state\": self.state}\n\n        except Exception as e:\n            return self._compensate(str(e))\n\n    def _compensate(self, error: str) -> dict:\n        \"\"\"Roll back completed steps on failure.\"\"\"\n        if \"create_escrow\" in self.state[\"completed_steps\"]:\n            escrow_id = self.state.get(\"escrow_id\")\n            if escrow_id and \"release_escrow\" not in self.state[\"completed_steps\"]:\n                self.harness.execute(\"cancel_escrow\", {\n                    \"escrow_id\": escrow_id,\n                })\n                self.state[\"completed_steps\"].append(\"compensate:cancel_escrow\")\n\n        return {\n            \"status\": \"rolled_back\",\n            \"error\": error,\n            \"state\": self.state,\n        }\n```\n\n### Testing the Saga\n\n```python\nclass TestMarketplaceSaga(EscrowFixtures):\n    \"\"\"Layer 3: Full marketplace workflow with rollback verification.\"\"\"\n\n    def test_happy_path(self, harness, buyer_id, seller_id):\n        \"\"\"Complete saga executes all 7 steps.\"\"\"\n        harness.mock_tool(\"register_service\", {\n            \"service_id\": \"svc-test-001\",\n        })\n        harness.mock_tool(\"search_services\", {\n            \"services\": [{\"name\": \"Test Service\", \"agent_id\": seller_id}],\n        })\n        harness.mock_tool(\"rate_service\", {\"status\": \"rated\"})\n\n        saga = MarketplaceSaga(harness, buyer_id, seller_id)\n        result = saga.run()\n\n        assert result[\"status\"] == \"completed\"\n        assert len(result[\"state\"][\"completed_steps\"]) == 7\n        harness.assert_call_order([\n            \"register_service\",\n            \"search_services\",\n            \"get_trust_score\",\n            \"create_escrow\",\n            \"release_escrow\",\n            \"rate_service\",\n        ])\n\n    def test_rollback_on_escrow_failure(self, harness, buyer_id, seller_id):\n        \"\"\"Failed escrow creation does not leave orphaned state.\"\"\"\n        harness.mock_tool(\"register_service\", {\"service_id\": \"svc-test-002\"})\n        harness.mock_tool(\"search_services\", {\n            \"services\": [{\"name\": \"Test\", \"agent_id\": seller_id}],\n        })\n        harness.mock_tool_error(\n            \"create_escrow\", \"insufficient_funds\", \"Not enough balance\"\n        )\n\n        saga = MarketplaceSaga(harness, buyer_id, seller_id)\n        result = saga.run()\n\n        assert result[\"status\"] == \"rolled_back\"\n        assert \"create_escrow\" not in result[\"state\"][\"completed_steps\"]\n        harness.assert_tool_not_called(\"release_escrow\")\n\n    def test_rollback_cancels_escrow_on_work_failure(self, harness, buyer_id, seller_id):\n        \"\"\"Failed work step triggers escrow cancellation.\"\"\"\n        harness.mock_tool(\"register_service\", {\"service_id\": \"svc-test-003\"})\n        harness.mock_tool(\"search_services\", {\n            \"services\": [{\"name\": \"Test\", \"agent_id\": seller_id}],\n        })\n\n        saga = MarketplaceSaga(harness, buyer_id, seller_id)\n        # Simulate work failure by injecting error after escrow creation\n        original_execute = harness.execute\n\n        call_count = {\"n\": 0}\n        def failing_execute(tool, input_data):\n            call_count[\"n\"] += 1\n            if tool == \"release_escrow\":\n                raise RuntimeError(\"Simulated work verification failure\")\n            return original_execute(tool, input_data)\n\n        harness.execute = failing_execute\n        result = saga.run()\n\n        assert result[\"status\"] == \"rolled_back\"\n        assert \"compensate:cancel_escrow\" in result[\"state\"][\"completed_steps\"]\n```\n\n### Subscription Lifecycle Testing\n\nSubscriptions are stateful workflows: create, renew, pause, cancel. Each transition must be tested, including edge cases like renewal with insufficient balance (P2, P6).\n\n```python\nclass TestSubscriptionLifecycle(AgentFixtures):\n    \"\"\"Layer 3: Verify subscription state transitions.\"\"\"\n\n    def test_full_lifecycle(self, harness):\n        \"\"\"Create → renew → cancel lifecycle.\"\"\"\n        sub_id = f\"sub-{uuid.uuid4().hex[:8]}\"\n        harness.mock_tool(\"create_subscription\", {\n            \"subscription_id\": sub_id,\n            \"status\": \"active\",\n            \"next_payment_date\": \"2026-05-06\",\n        })\n        harness.mock_tool(\"get_subscription\", {\n            \"subscription_id\": sub_id,\n            \"status\": \"active\",\n            \"payments_completed\": 1,\n        })\n        harness.mock_tool(\"cancel_subscription\", {\n            \"subscription_id\": sub_id,\n            \"status\": \"cancelled\",\n        })\n\n        # Create\n        sub = harness.execute(\"create_subscription\", {\n            \"payer_agent_id\": harness.agent_id,\n            \"payee_agent_id\": \"provider-001\",\n            \"amount\": \"15.00\",\n            \"interval\": \"monthly\",\n        })\n        assert sub[\"status\"] == \"active\"\n\n        # Check status\n        status = harness.execute(\"get_subscription\", {\n            \"subscription_id\": sub_id,\n        })\n        assert status[\"payments_completed\"] == 1\n\n        # Cancel\n        cancel = harness.execute(\"cancel_subscription\", {\n            \"subscription_id\": sub_id,\n        })\n        assert cancel[\"status\"] == \"cancelled\"\n\n        harness.assert_call_order([\n            \"create_subscription\",\n            \"get_subscription\",\n            \"cancel_subscription\",\n        ])\n\n    def test_renewal_with_insufficient_funds(self, harness):\n        \"\"\"Subscription renewal should fail gracefully when balance is low.\"\"\"\n        harness.mock_tool(\"get_balance\", {\"balance\": \"5.00\", \"currency\": \"USD\"})\n        harness.mock_tool_error(\n            \"create_subscription\",\n            \"insufficient_funds\",\n            \"Balance too low for subscription amount\",\n        )\n\n        result = harness.execute(\"create_subscription\", {\n            \"payer_agent_id\": harness.agent_id,\n            \"payee_agent_id\": \"provider-002\",\n            \"amount\": \"15.00\",\n            \"interval\": \"monthly\",\n        })\n        assert result.get(\"status\") == \"error\"\n```\n\n### Webhook Delivery Testing\n\nWebhooks are the primary notification mechanism for payment events. A missed webhook means a missed settlement, a missed dispute deadline, or a missed subscription renewal. Test webhook delivery separately from the business logic it triggers (P4).\n\n```python\nclass TestWebhookDelivery:\n    \"\"\"Layer 3: Verify webhook registration and event delivery.\"\"\"\n\n    def test_webhook_registration(self, harness):\n        \"\"\"Webhook registration should return a webhook_id.\"\"\"\n        harness.mock_tool(\"register_webhook\", {\n            \"webhook_id\": \"wh-test-001\",\n            \"status\": \"active\",\n            \"events\": [\"escrow.released\", \"escrow.disputed\"],\n        })\n\n        result = harness.execute(\"register_webhook\", {\n            \"url\": \"https:\u002F\u002Ftest.example.com\u002Fwebhook\",\n            \"events\": [\"escrow.released\", \"escrow.disputed\"],\n        })\n        assert \"webhook_id\" in result\n        assert result[\"status\"] == \"active\"\n\n    def test_webhook_event_format(self, harness):\n        \"\"\"Webhook payloads should contain required fields.\"\"\"\n        harness.mock_tool(\"get_webhook_logs\", {\n            \"logs\": [{\n                \"webhook_id\": \"wh-test-001\",\n                \"event_type\": \"escrow.released\",\n                \"payload\": {\n                    \"escrow_id\": \"escrow-abc\",\n                    \"amount\": \"25.00\",\n                    \"payer_agent_id\": \"buyer-1\",\n                    \"payee_agent_id\": \"seller-1\",\n                    \"timestamp\": \"2026-04-06T12:00:00Z\",\n                },\n                \"delivery_status\": \"delivered\",\n                \"response_code\": 200,\n            }],\n        })\n\n        logs = harness.execute(\"get_webhook_logs\", {\"webhook_id\": \"wh-test-001\"})\n        for log_entry in logs[\"logs\"]:\n            payload = log_entry[\"payload\"]\n            assert \"escrow_id\" in payload\n            assert \"amount\" in payload\n            assert \"timestamp\" in payload\n            assert log_entry[\"delivery_status\"] == \"delivered\"\n```\n\n---\n\n## Chapter 4: Chaos Testing for Agent Commerce\n\n### Why Chaos Testing Matters for Payments\n\nTraditional software fails gracefully when a downstream service is unavailable -- it shows an error page. Agent commerce software fails expensively. A timeout during `release_escrow` might mean funds are released on the gateway but the caller never gets confirmation, leading to a duplicate release attempt. A network partition during a split payment might result in partial settlement. Chaos testing injects these failures deliberately so you can verify your system handles them before production handles them for you.\n\n### The ChaosMiddleware\n\nThe `ChaosMiddleware` wraps the harness's `execute` method and randomly injects failures: timeouts, error responses, delayed responses, and corrupted payloads. It is configurable per tool and per failure type.\n\n```python\nimport random\nimport time\nfrom dataclasses import dataclass, field\n\n\n@dataclass\nclass ChaosConfig:\n    \"\"\"Configuration for chaos injection on a specific tool.\"\"\"\n    timeout_pct: float = 0.0       # % of calls that timeout\n    error_pct: float = 0.0         # % of calls that return errors\n    delay_ms: float = 0.0          # Additional latency in ms\n    corrupt_pct: float = 0.0       # % of calls with corrupted responses\n    duplicate_pct: float = 0.0     # % of calls that execute twice\n\n\nclass ChaosMiddleware:\n    \"\"\"Wraps AgentTestHarness._execute with configurable failure injection.\n\n    Usage:\n        harness = AgentTestHarness(api_key, agent_id, base_url)\n        chaos = ChaosMiddleware(\n            harness=harness,\n            default_config=ChaosConfig(error_pct=10, delay_ms=200),\n        )\n        chaos.set_tool_config(\"create_escrow\", ChaosConfig(\n            timeout_pct=20,\n            duplicate_pct=5,\n        ))\n\n        # All calls now go through chaos injection\n        result = chaos.execute(\"create_escrow\", {...})\n    \"\"\"\n\n    def __init__(\n        self,\n        harness: AgentTestHarness,\n        default_config: ChaosConfig = None,\n        seed: int = None,\n    ):\n        self.harness = harness\n        self.default_config = default_config or ChaosConfig()\n        self._tool_configs: dict[str, ChaosConfig] = {}\n        self._rng = random.Random(seed)\n        self._chaos_log: list[dict] = []\n\n    def set_tool_config(self, tool: str, config: ChaosConfig):\n        \"\"\"Set chaos configuration for a specific tool.\"\"\"\n        self._tool_configs[tool] = config\n\n    def execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute a tool with chaos injection.\"\"\"\n        config = self._tool_configs.get(tool, self.default_config)\n        chaos_event = {\"tool\": tool, \"injection\": None, \"timestamp\": time.time()}\n\n        # Check timeout injection\n        if self._rng.random() * 100 \u003C config.timeout_pct:\n            chaos_event[\"injection\"] = \"timeout\"\n            self._chaos_log.append(chaos_event)\n            raise TimeoutError(\n                f\"Chaos: simulated timeout for tool '{tool}'\"\n            )\n\n        # Check error injection\n        if self._rng.random() * 100 \u003C config.error_pct:\n            chaos_event[\"injection\"] = \"error\"\n            self._chaos_log.append(chaos_event)\n            return {\n                \"status\": \"error\",\n                \"error\": {\n                    \"code\": \"chaos_injected_error\",\n                    \"message\": f\"Chaos: simulated error for tool '{tool}'\",\n                },\n            }\n\n        # Apply delay\n        if config.delay_ms > 0:\n            delay_seconds = config.delay_ms \u002F 1000.0\n            actual_delay = self._rng.uniform(0, delay_seconds * 2)\n            time.sleep(actual_delay)\n            chaos_event[\"injection\"] = f\"delay:{actual_delay:.3f}s\"\n\n        # Execute the real call\n        result = self.harness.execute(tool, input_data)\n\n        # Check duplicate execution\n        if self._rng.random() * 100 \u003C config.duplicate_pct:\n            chaos_event[\"injection\"] = \"duplicate\"\n            self._chaos_log.append(chaos_event)\n            # Execute again -- this tests idempotency\n            duplicate_result = self.harness.execute(tool, input_data)\n            return duplicate_result\n\n        # Check corruption\n        if self._rng.random() * 100 \u003C config.corrupt_pct:\n            chaos_event[\"injection\"] = \"corrupt\"\n            self._chaos_log.append(chaos_event)\n            if isinstance(result, dict):\n                result[\"_chaos_corrupted\"] = True\n                # Remove a random key to simulate partial response\n                keys = [k for k in result.keys() if k != \"status\"]\n                if keys:\n                    del result[self._rng.choice(keys)]\n\n        self._chaos_log.append(chaos_event)\n        return result\n\n    def get_chaos_log(self) -> list[dict]:\n        \"\"\"Get the log of all chaos injections.\"\"\"\n        return list(self._chaos_log)\n\n    def get_injection_stats(self) -> dict:\n        \"\"\"Get summary statistics of chaos injections.\"\"\"\n        stats = {\"total\": len(self._chaos_log)}\n        for entry in self._chaos_log:\n            injection = entry.get(\"injection\") or \"none\"\n            category = injection.split(\":\")[0]\n            stats[category] = stats.get(category, 0) + 1\n        return stats\n```\n\n### Chaos Test Patterns\n\n```python\nclass TestEscrowUnderChaos:\n    \"\"\"Layer 4: Verify escrow operations survive failure injection.\"\"\"\n\n    def test_escrow_survives_timeout_retry(self, harness):\n        \"\"\"Escrow creation retries correctly after timeout.\"\"\"\n        harness.use_mocks()\n        harness.mock_tool(\"create_escrow\", {\n            \"escrow_id\": \"escrow-chaos-001\",\n            \"status\": \"funded\",\n            \"amount\": \"50.00\",\n        })\n\n        chaos = ChaosMiddleware(\n            harness=harness,\n            seed=42,\n            default_config=ChaosConfig(timeout_pct=50),\n        )\n\n        # Retry loop -- real production code should have this\n        max_retries = 5\n        result = None\n        for attempt in range(max_retries):\n            try:\n                result = chaos.execute(\"create_escrow\", {\n                    \"payer_agent_id\": \"buyer\",\n                    \"payee_agent_id\": \"seller\",\n                    \"amount\": \"50.00\",\n                    \"idempotency_key\": \"idem-chaos-001\",\n                })\n                break\n            except TimeoutError:\n                continue\n\n        assert result is not None, \"All retry attempts timed out\"\n        assert result[\"escrow_id\"] == \"escrow-chaos-001\"\n\n    def test_no_double_payment_under_duplicates(self, harness):\n        \"\"\"Duplicate chaos injection does not cause double payment.\"\"\"\n        harness.use_mocks()\n        call_count = {\"n\": 0}\n\n        original_execute = harness.execute\n        def counting_execute(tool, input_data):\n            call_count[\"n\"] += 1\n            return original_execute(tool, input_data)\n\n        harness.execute = counting_execute\n        harness.mock_tool(\"release_escrow\", {\n            \"escrow_id\": \"escrow-dup-test\",\n            \"status\": \"released\",\n        })\n\n        chaos = ChaosMiddleware(\n            harness=harness,\n            seed=99,\n            default_config=ChaosConfig(duplicate_pct=100),\n        )\n\n        result = chaos.execute(\"release_escrow\", {\n            \"escrow_id\": \"escrow-dup-test\",\n        })\n\n        # The middleware called execute twice, but the result should\n        # still represent a single release\n        assert result[\"status\"] == \"released\"\n\n    def test_concurrent_escrow_load(self, harness):\n        \"\"\"Concurrent escrow creation does not cause race conditions.\"\"\"\n        import concurrent.futures\n\n        harness.use_mocks()\n        harness.mock_tool(\"create_escrow\", {\n            \"escrow_id\": \"will-be-unique\",\n            \"status\": \"funded\",\n            \"amount\": \"10.00\",\n        })\n\n        chaos = ChaosMiddleware(\n            harness=harness,\n            seed=7,\n            default_config=ChaosConfig(delay_ms=50, error_pct=10),\n        )\n\n        results = []\n        errors = []\n\n        def create_escrow(i):\n            try:\n                return chaos.execute(\"create_escrow\", {\n                    \"payer_agent_id\": \"buyer\",\n                    \"payee_agent_id\": \"seller\",\n                    \"amount\": \"10.00\",\n                    \"idempotency_key\": f\"concurrent-{i}\",\n                })\n            except Exception as e:\n                return {\"status\": \"error\", \"message\": str(e)}\n\n        with concurrent.futures.ThreadPoolExecutor(max_workers=10) as pool:\n            futures = [pool.submit(create_escrow, i) for i in range(20)]\n            for f in concurrent.futures.as_completed(futures):\n                r = f.result()\n                if r.get(\"status\") == \"error\":\n                    errors.append(r)\n                else:\n                    results.append(r)\n\n        # At least some should succeed despite chaos\n        assert len(results) > 0\n        # Errors are expected under chaos -- verify they are handled\n        total = len(results) + len(errors)\n        assert total == 20\n\n    def test_escrow_timeout_deadline(self, harness):\n        \"\"\"Escrow must be released or cancelled before deadline.\"\"\"\n        harness.use_mocks()\n        deadline = time.time() + 2  # 2 second deadline for test\n\n        harness.mock_tool(\"create_escrow\", {\n            \"escrow_id\": \"escrow-deadline\",\n            \"status\": \"funded\",\n            \"deadline\": deadline,\n        })\n        harness.mock_tool(\"cancel_escrow\", {\n            \"escrow_id\": \"escrow-deadline\",\n            \"status\": \"cancelled\",\n            \"reason\": \"deadline_exceeded\",\n        })\n\n        escrow = harness.execute(\"create_escrow\", {\n            \"payer_agent_id\": \"buyer\",\n            \"payee_agent_id\": \"seller\",\n            \"amount\": \"30.00\",\n        })\n\n        # Simulate deadline passing\n        time.sleep(0.1)  # In real tests use time mocking\n        current_time = time.time()\n        if current_time \u003C deadline:\n            # Still within deadline -- release is valid\n            harness.mock_tool(\"release_escrow\", {\n                \"escrow_id\": \"escrow-deadline\",\n                \"status\": \"released\",\n            })\n            result = harness.execute(\"release_escrow\", {\n                \"escrow_id\": escrow[\"escrow_id\"],\n            })\n            assert result[\"status\"] == \"released\"\n        else:\n            # Deadline exceeded -- should auto-cancel\n            result = harness.execute(\"cancel_escrow\", {\n                \"escrow_id\": escrow[\"escrow_id\"],\n            })\n            assert result[\"status\"] == \"cancelled\"\n```\n\n---\n\n## Chapter 5: Production Observability\n\n### Why printf Debugging Does Not Work for Payments\n\nWhen a payment fails in production, you need to know three things instantly: which tool failed, how long it took, and what the input was. You need this information structured, searchable, and available without SSH-ing into a server. The `AgentTracer` wraps every `_execute` call with timing, success\u002Ffailure tracking, and structured output.\n\n### The AgentTracer\n\n```python\nimport time\nimport json\nimport logging\nfrom dataclasses import dataclass, field\nfrom typing import Optional, Callable\n\n\n@dataclass\nclass TraceRecord:\n    \"\"\"A single traced tool execution.\"\"\"\n    tool: str\n    agent_id: str\n    started_at: float\n    ended_at: float\n    duration_ms: float\n    success: bool\n    input_data: dict\n    output_data: Optional[dict] = None\n    error: Optional[str] = None\n    trace_id: str = \"\"\n\n    def to_dict(self) -> dict:\n        return {\n            \"trace_id\": self.trace_id,\n            \"tool\": self.tool,\n            \"agent_id\": self.agent_id,\n            \"started_at\": self.started_at,\n            \"ended_at\": self.ended_at,\n            \"duration_ms\": round(self.duration_ms, 2),\n            \"success\": self.success,\n            \"error\": self.error,\n        }\n\n\nclass AgentTracer:\n    \"\"\"Wraps _execute and records timing, success\u002Ffailure, tool name.\n\n    Provides structured observability for every tool call in production.\n\n    Usage:\n        tracer = AgentTracer(\n            api_key=\"...\",\n            agent_id=\"production-buyer-01\",\n            base_url=\"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n        )\n\n        # Wrap an existing AgentCommerce or harness\n        result = tracer.trace(\"create_escrow\", {\n            \"payer_agent_id\": \"buyer\",\n            \"payee_agent_id\": \"seller\",\n            \"amount\": \"50.00\",\n        })\n\n        # Get metrics\n        print(tracer.get_metrics())\n        # {'total_calls': 47, 'success_rate': 0.957,\n        #  'avg_latency_ms': 142.3, 'p99_latency_ms': 890.1,\n        #  'error_rate_by_tool': {'create_escrow': 0.02}}\n    \"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n        logger: Optional[logging.Logger] = None,\n        on_slow_call: Optional[Callable] = None,\n        slow_threshold_ms: float = 2000.0,\n    ):\n        self.api_key = api_key\n        self.agent_id = agent_id\n        self.base_url = base_url\n        self.logger = logger or logging.getLogger(\"agent_tracer\")\n        self.on_slow_call = on_slow_call\n        self.slow_threshold_ms = slow_threshold_ms\n        self._traces: list[TraceRecord] = []\n        self._session = requests.Session()\n        self._session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n\n    def trace(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute a tool with full tracing.\"\"\"\n        trace_id = f\"trace-{uuid.uuid4().hex[:12]}\"\n        started_at = time.time()\n\n        try:\n            resp = self._session.post(\n                f\"{self.base_url}\u002Fv1\",\n                json={\"tool\": tool, \"input\": input_data},\n            )\n            resp.raise_for_status()\n            result = resp.json()\n            success = result.get(\"status\") != \"error\"\n            error = None if success else json.dumps(result.get(\"error\", {}))\n        except Exception as e:\n            result = {\"status\": \"error\", \"error\": str(e)}\n            success = False\n            error = str(e)\n\n        ended_at = time.time()\n        duration_ms = (ended_at - started_at) * 1000\n\n        record = TraceRecord(\n            tool=tool,\n            agent_id=self.agent_id,\n            started_at=started_at,\n            ended_at=ended_at,\n            duration_ms=duration_ms,\n            success=success,\n            input_data=input_data,\n            output_data=result if success else None,\n            error=error,\n            trace_id=trace_id,\n        )\n        self._traces.append(record)\n\n        # Structured log\n        self.logger.info(json.dumps({\n            \"event\": \"tool_execution\",\n            \"trace_id\": trace_id,\n            \"tool\": tool,\n            \"agent_id\": self.agent_id,\n            \"duration_ms\": round(duration_ms, 2),\n            \"success\": success,\n            \"error\": error,\n        }))\n\n        # Slow call callback\n        if duration_ms > self.slow_threshold_ms and self.on_slow_call:\n            self.on_slow_call(record)\n\n        return result\n\n    def get_metrics(self) -> dict:\n        \"\"\"Compute aggregate metrics from traced calls.\"\"\"\n        if not self._traces:\n            return {\"total_calls\": 0}\n\n        total = len(self._traces)\n        successes = sum(1 for t in self._traces if t.success)\n        durations = sorted(t.duration_ms for t in self._traces)\n\n        # Per-tool error rates\n        tool_calls: dict[str, dict] = {}\n        for t in self._traces:\n            if t.tool not in tool_calls:\n                tool_calls[t.tool] = {\"total\": 0, \"errors\": 0}\n            tool_calls[t.tool][\"total\"] += 1\n            if not t.success:\n                tool_calls[t.tool][\"errors\"] += 1\n\n        error_rate_by_tool = {\n            tool: stats[\"errors\"] \u002F stats[\"total\"]\n            for tool, stats in tool_calls.items()\n            if stats[\"errors\"] > 0\n        }\n\n        # Per-tool latency\n        tool_latencies: dict[str, list[float]] = {}\n        for t in self._traces:\n            tool_latencies.setdefault(t.tool, []).append(t.duration_ms)\n\n        avg_latency_by_tool = {\n            tool: round(sum(lats) \u002F len(lats), 2)\n            for tool, lats in tool_latencies.items()\n        }\n\n        return {\n            \"total_calls\": total,\n            \"success_rate\": round(successes \u002F total, 4),\n            \"avg_latency_ms\": round(sum(durations) \u002F total, 2),\n            \"p50_latency_ms\": round(durations[total \u002F\u002F 2], 2),\n            \"p95_latency_ms\": round(durations[int(total * 0.95)], 2),\n            \"p99_latency_ms\": round(durations[int(total * 0.99)], 2),\n            \"error_rate_by_tool\": error_rate_by_tool,\n            \"avg_latency_by_tool\": avg_latency_by_tool,\n        }\n\n    def get_traces(\n        self,\n        tool: Optional[str] = None,\n        success: Optional[bool] = None,\n        min_duration_ms: Optional[float] = None,\n    ) -> list[dict]:\n        \"\"\"Query traces with optional filters.\"\"\"\n        filtered = self._traces\n        if tool:\n            filtered = [t for t in filtered if t.tool == tool]\n        if success is not None:\n            filtered = [t for t in filtered if t.success == success]\n        if min_duration_ms is not None:\n            filtered = [t for t in filtered if t.duration_ms >= min_duration_ms]\n        return [t.to_dict() for t in filtered]\n\n    def get_revenue_metrics(self) -> dict:\n        \"\"\"Extract revenue-specific metrics from traced calls.\"\"\"\n        escrow_creates = [\n            t for t in self._traces\n            if t.tool == \"create_escrow\" and t.success\n        ]\n        escrow_releases = [\n            t for t in self._traces\n            if t.tool == \"release_escrow\" and t.success\n        ]\n        deposits = [\n            t for t in self._traces\n            if t.tool == \"deposit\" and t.success\n        ]\n\n        total_escrowed = sum(\n            float(t.input_data.get(\"amount\", 0))\n            for t in escrow_creates\n        )\n        total_deposited = sum(\n            float(t.input_data.get(\"amount\", 0))\n            for t in deposits\n        )\n\n        return {\n            \"escrows_created\": len(escrow_creates),\n            \"escrows_released\": len(escrow_releases),\n            \"total_escrowed\": round(total_escrowed, 2),\n            \"total_deposited\": round(total_deposited, 2),\n            \"release_rate\": (\n                round(len(escrow_releases) \u002F len(escrow_creates), 4)\n                if escrow_creates else 0\n            ),\n        }\n```\n\n### Structured Logging for Agent Decisions\n\nThe tracer's structured logging integrates with any log aggregator (Datadog, ELK, CloudWatch). Each log line is a JSON object with consistent fields. The key decision: log the tool name and duration for every call, but redact input data in production to avoid logging sensitive information like API keys or wallet amounts. Enable full input logging only in staging (P7 security patterns).\n\n```python\n# Production logging configuration\nimport logging\n\ndef configure_production_logging():\n    \"\"\"Set up structured JSON logging for agent commerce.\"\"\"\n    logger = logging.getLogger(\"agent_tracer\")\n    logger.setLevel(logging.INFO)\n\n    handler = logging.StreamHandler()\n    handler.setFormatter(logging.Formatter(\"%(message)s\"))\n    logger.addHandler(handler)\n    return logger\n\n\ndef configure_staging_logging():\n    \"\"\"Staging logger with full input\u002Foutput capture.\"\"\"\n    logger = logging.getLogger(\"agent_tracer\")\n    logger.setLevel(logging.DEBUG)\n\n    handler = logging.FileHandler(\"\u002Fvar\u002Flog\u002Fagent-commerce\u002Ftraces.jsonl\")\n    handler.setFormatter(logging.Formatter(\"%(message)s\"))\n    logger.addHandler(handler)\n    return logger\n```\n\n### Custom Metrics Dashboard\n\nExtract the metrics you need for a Grafana or Datadog dashboard from the tracer. These are the five metrics every agent commerce system should track.\n\n```python\nclass MetricsExporter:\n    \"\"\"Export AgentTracer metrics to monitoring systems.\"\"\"\n\n    def __init__(self, tracer: AgentTracer):\n        self.tracer = tracer\n\n    def export_prometheus(self) -> str:\n        \"\"\"Export metrics in Prometheus text format.\"\"\"\n        metrics = self.tracer.get_metrics()\n        revenue = self.tracer.get_revenue_metrics()\n        lines = [\n            f'agent_commerce_calls_total {metrics[\"total_calls\"]}',\n            f'agent_commerce_success_rate {metrics[\"success_rate\"]}',\n            f'agent_commerce_latency_p50_ms {metrics.get(\"p50_latency_ms\", 0)}',\n            f'agent_commerce_latency_p99_ms {metrics.get(\"p99_latency_ms\", 0)}',\n            f'agent_commerce_escrows_created {revenue[\"escrows_created\"]}',\n            f'agent_commerce_escrows_released {revenue[\"escrows_released\"]}',\n            f'agent_commerce_total_escrowed {revenue[\"total_escrowed\"]}',\n            f'agent_commerce_release_rate {revenue[\"release_rate\"]}',\n        ]\n\n        for tool, rate in metrics.get(\"error_rate_by_tool\", {}).items():\n            lines.append(\n                f'agent_commerce_error_rate{{tool=\"{tool}\"}} {rate}'\n            )\n\n        return \"\\n\".join(lines)\n\n    def to_datadog_events(self) -> list[dict]:\n        \"\"\"Format failed traces as Datadog events.\"\"\"\n        failed = self.tracer.get_traces(success=False)\n        return [\n            {\n                \"title\": f\"Tool failure: {t['tool']}\",\n                \"text\": t.get(\"error\", \"Unknown error\"),\n                \"tags\": [\n                    f\"tool:{t['tool']}\",\n                    f\"agent:{t['agent_id']}\",\n                    \"service:agent-commerce\",\n                ],\n                \"alert_type\": \"error\",\n            }\n            for t in failed\n        ]\n```\n\n---\n\n## Chapter 6: Alerting & Incident Response\n\n### What to Alert On\n\nNot every error deserves a page. These six conditions are the ones that, left unaddressed, cause financial loss in agent commerce systems.\n\n| Alert | Condition | Severity | Action |\n|-------|-----------|----------|--------|\n| Settlement failure | `release_escrow` returns error 3+ times | Critical | Check gateway status, pause new escrows |\n| Escrow timeout | Escrow unfunded\u002Funreleased past deadline | High | Auto-cancel or escalate to dispute |\n| Balance anomaly | Balance drops >50% in single transaction | Critical | Pause agent, audit recent calls |\n| Reputation drop | Trust score drops below threshold | Medium | Pause hiring, investigate metrics |\n| Webhook delivery failure | >5 consecutive webhook delivery failures | High | Check endpoint, enable retry queue |\n| Duplicate payment | Same escrow_id released twice in 60s | Critical | Immediate halt, audit ledger |\n\n### The HealthChecker\n\nThe `HealthChecker` runs synthetic transactions against the sandbox (or a dedicated health-check agent on production) to verify the full payment pipeline is operational. Run it every 60 seconds from your monitoring system.\n\n```python\nclass HealthChecker:\n    \"\"\"Synthetic transaction health checks for agent commerce.\n\n    Runs a mini escrow lifecycle (create wallet → deposit → create\n    escrow → release → verify balance) and reports pass\u002Ffail with\n    latency metrics.\n\n    Usage:\n        checker = HealthChecker(\n            api_key=\"health-check-key\",\n            agent_id=\"health-check-agent\",\n            base_url=\"https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1\",\n        )\n\n        result = checker.run_health_check()\n        # {\n        #     \"healthy\": True,\n        #     \"checks\": {\n        #         \"wallet\": {\"status\": \"pass\", \"latency_ms\": 45.2},\n        #         \"deposit\": {\"status\": \"pass\", \"latency_ms\": 78.1},\n        #         \"escrow_create\": {\"status\": \"pass\", \"latency_ms\": 112.4},\n        #         \"escrow_release\": {\"status\": \"pass\", \"latency_ms\": 95.6},\n        #         \"balance_verify\": {\"status\": \"pass\", \"latency_ms\": 41.0},\n        #     },\n        #     \"total_latency_ms\": 372.3,\n        # }\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        timeout_ms: float = 5000.0,\n    ):\n        self.api_key = api_key\n        self.agent_id = agent_id\n        self.base_url = base_url\n        self.timeout_ms = timeout_ms\n        self._session = requests.Session()\n        self._session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n\n    def _timed_execute(self, tool: str, input_data: dict) -> tuple[dict, float]:\n        \"\"\"Execute a tool and return (result, latency_ms).\"\"\"\n        start = time.time()\n        resp = self._session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n            timeout=self.timeout_ms \u002F 1000.0,\n        )\n        latency_ms = (time.time() - start) * 1000\n        resp.raise_for_status()\n        return resp.json(), latency_ms\n\n    def run_health_check(self) -> dict:\n        \"\"\"Run a full synthetic transaction health check.\"\"\"\n        checks = {}\n        healthy = True\n        health_agent = f\"{self.agent_id}-{int(time.time())}\"\n\n        # Check 1: Wallet creation\n        try:\n            result, latency = self._timed_execute(\"create_wallet\", {})\n            checks[\"wallet\"] = {\"status\": \"pass\", \"latency_ms\": round(latency, 2)}\n        except Exception as e:\n            checks[\"wallet\"] = {\"status\": \"fail\", \"error\": str(e)}\n            healthy = False\n\n        # Check 2: Deposit\n        try:\n            result, latency = self._timed_execute(\"deposit\", {\"amount\": \"1.00\"})\n            checks[\"deposit\"] = {\"status\": \"pass\", \"latency_ms\": round(latency, 2)}\n        except Exception as e:\n            checks[\"deposit\"] = {\"status\": \"fail\", \"error\": str(e)}\n            healthy = False\n\n        # Check 3: Escrow creation\n        escrow_id = None\n        try:\n            result, latency = self._timed_execute(\"create_escrow\", {\n                \"payer_agent_id\": health_agent,\n                \"payee_agent_id\": f\"{health_agent}-payee\",\n                \"amount\": \"0.01\",\n                \"description\": \"Health check escrow\",\n            })\n            escrow_id = result.get(\"escrow_id\")\n            checks[\"escrow_create\"] = {\"status\": \"pass\", \"latency_ms\": round(latency, 2)}\n        except Exception as e:\n            checks[\"escrow_create\"] = {\"status\": \"fail\", \"error\": str(e)}\n            healthy = False\n\n        # Check 4: Escrow release\n        if escrow_id:\n            try:\n                result, latency = self._timed_execute(\"release_escrow\", {\n                    \"escrow_id\": escrow_id,\n                })\n                checks[\"escrow_release\"] = {\"status\": \"pass\", \"latency_ms\": round(latency, 2)}\n            except Exception as e:\n                checks[\"escrow_release\"] = {\"status\": \"fail\", \"error\": str(e)}\n                healthy = False\n        else:\n            checks[\"escrow_release\"] = {\"status\": \"skip\", \"reason\": \"no escrow_id\"}\n\n        # Check 5: Balance verification\n        try:\n            result, latency = self._timed_execute(\"get_balance\", {})\n            checks[\"balance_verify\"] = {\"status\": \"pass\", \"latency_ms\": round(latency, 2)}\n        except Exception as e:\n            checks[\"balance_verify\"] = {\"status\": \"fail\", \"error\": str(e)}\n            healthy = False\n\n        total_latency = sum(\n            c.get(\"latency_ms\", 0) for c in checks.values()\n        )\n\n        return {\n            \"healthy\": healthy,\n            \"checks\": checks,\n            \"total_latency_ms\": round(total_latency, 2),\n            \"timestamp\": time.time(),\n            \"agent_id\": self.agent_id,\n        }\n\n    def run_and_alert(self, alert_callback: Callable = None) -> dict:\n        \"\"\"Run health check and trigger alert callback on failure.\"\"\"\n        result = self.run_health_check()\n\n        if not result[\"healthy\"] and alert_callback:\n            failed_checks = {\n                name: check for name, check in result[\"checks\"].items()\n                if check.get(\"status\") == \"fail\"\n            }\n            alert_callback({\n                \"severity\": \"critical\",\n                \"title\": \"Agent Commerce Health Check Failed\",\n                \"failed_checks\": failed_checks,\n                \"timestamp\": result[\"timestamp\"],\n            })\n\n        return result\n```\n\n### Testing the HealthChecker\n\n```python\nclass TestHealthChecker:\n    \"\"\"Verify the health checker itself works correctly.\"\"\"\n\n    def test_reports_healthy_when_all_pass(self, harness):\n        \"\"\"All checks passing produces healthy=True.\"\"\"\n        harness.use_mocks()\n        harness.mock_tool(\"create_wallet\", {\"wallet_id\": \"w-health\"})\n        harness.mock_tool(\"deposit\", {\"balance\": \"1.00\", \"transaction_id\": \"tx-h\"})\n        harness.mock_tool(\"create_escrow\", {\n            \"escrow_id\": \"escrow-health\", \"status\": \"funded\",\n        })\n        harness.mock_tool(\"release_escrow\", {\n            \"escrow_id\": \"escrow-health\", \"status\": \"released\",\n        })\n        harness.mock_tool(\"get_balance\", {\"balance\": \"0.99\"})\n\n        # HealthChecker delegates to the harness in test mode\n        checker = HealthChecker(\n            api_key=harness.api_key,\n            agent_id=harness.agent_id,\n            base_url=harness.base_url,\n        )\n        # In real tests, patch _timed_execute to use harness\n        # Here we verify the structure\n        assert checker.timeout_ms == 5000.0\n\n    def test_reports_unhealthy_on_escrow_failure(self):\n        \"\"\"Failed escrow check produces healthy=False.\"\"\"\n        checker = HealthChecker(\n            api_key=\"test\",\n            agent_id=\"test\",\n            base_url=\"https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1\",\n        )\n\n        alerts_received = []\n        def mock_alert(alert):\n            alerts_received.append(alert)\n\n        # Patch to simulate failure -- in real code use sandbox\n        original = checker._timed_execute\n        def failing_execute(tool, input_data):\n            if tool == \"create_escrow\":\n                raise ConnectionError(\"Gateway timeout\")\n            return original(tool, input_data)\n\n        checker._timed_execute = failing_execute\n        try:\n            result = checker.run_and_alert(alert_callback=mock_alert)\n        except Exception:\n            pass  # Expected when wallet\u002Fdeposit also fail\n```\n\n### Dead Letter Queue for Webhooks\n\nWhen webhook delivery fails, events must not be silently dropped. Implement a dead letter queue that captures failed deliveries for retry (P4).\n\n```python\nclass WebhookDeadLetterQueue:\n    \"\"\"Captures failed webhook deliveries for manual retry.\"\"\"\n\n    def __init__(self, max_retries: int = 3, retry_delay_seconds: float = 60.0):\n        self.max_retries = max_retries\n        self.retry_delay_seconds = retry_delay_seconds\n        self._queue: list[dict] = []\n\n    def enqueue(self, event: dict, error: str):\n        \"\"\"Add a failed webhook event to the dead letter queue.\"\"\"\n        self._queue.append({\n            \"event\": event,\n            \"error\": error,\n            \"retries\": 0,\n            \"enqueued_at\": time.time(),\n            \"next_retry_at\": time.time() + self.retry_delay_seconds,\n        })\n\n    def get_pending(self) -> list[dict]:\n        \"\"\"Get events ready for retry.\"\"\"\n        now = time.time()\n        return [\n            entry for entry in self._queue\n            if entry[\"retries\"] \u003C self.max_retries\n            and entry[\"next_retry_at\"] \u003C= now\n        ]\n\n    def mark_delivered(self, event_id: str):\n        \"\"\"Remove a successfully retried event.\"\"\"\n        self._queue = [\n            e for e in self._queue\n            if e[\"event\"].get(\"event_id\") != event_id\n        ]\n\n    def mark_retried(self, event_id: str):\n        \"\"\"Increment retry count and schedule next attempt.\"\"\"\n        for entry in self._queue:\n            if entry[\"event\"].get(\"event_id\") == event_id:\n                entry[\"retries\"] += 1\n                entry[\"next_retry_at\"] = (\n                    time.time()\n                    + self.retry_delay_seconds * (2 ** entry[\"retries\"])\n                )\n                break\n\n    def get_dead_letters(self) -> list[dict]:\n        \"\"\"Get events that have exhausted all retries.\"\"\"\n        return [\n            entry for entry in self._queue\n            if entry[\"retries\"] >= self.max_retries\n        ]\n```\n\n---\n\n## Chapter 7: CI\u002FCD for Agent Systems\n\n### Running Tests in GitHub Actions\n\nAgent commerce tests require three things that standard CI does not provide: a GreenHelix API key for sandbox testing, isolation between parallel test runs (unique agent IDs), and network access to `sandbox.greenhelix.net`. This GitHub Actions template handles all three.\n\n```yaml\n# .github\u002Fworkflows\u002Fagent-commerce-tests.yml\nname: Agent Commerce Tests\n\non:\n  push:\n    branches: [main, develop]\n  pull_request:\n    branches: [main]\n\nenv:\n  GREENHELIX_API_KEY: ${{ secrets.GREENHELIX_API_KEY }}\n  GREENHELIX_BASE_URL: https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1\n\njobs:\n  # ── Layer 1: Fast mock-based tests (no network) ──────────\n  unit-tests:\n    runs-on: ubuntu-latest\n    steps:\n      - uses: actions\u002Fcheckout@v4\n\n      - name: Set up Python\n        uses: actions\u002Fsetup-python@v5\n        with:\n          python-version: \"3.12\"\n\n      - name: Install dependencies\n        run: |\n          pip install pytest requests cryptography\n\n      - name: Run unit tests (Layer 1)\n        run: |\n          pytest tests\u002F -x -q \\\n            -m \"not sandbox and not chaos\" \\\n            --tb=short \\\n            --junit-xml=results\u002Funit-tests.xml\n\n      - name: Upload test results\n        if: always()\n        uses: actions\u002Fupload-artifact@v4\n        with:\n          name: unit-test-results\n          path: results\u002Funit-tests.xml\n\n  # ── Layer 2: Contract tests against sandbox ──────────────\n  contract-tests:\n    runs-on: ubuntu-latest\n    needs: unit-tests\n    steps:\n      - uses: actions\u002Fcheckout@v4\n\n      - name: Set up Python\n        uses: actions\u002Fsetup-python@v5\n        with:\n          python-version: \"3.12\"\n\n      - name: Install dependencies\n        run: pip install pytest requests cryptography\n\n      - name: Run contract tests (Layer 2)\n        run: |\n          pytest tests\u002F -x -q \\\n            -m \"sandbox and not chaos\" \\\n            --tb=short \\\n            --junit-xml=results\u002Fcontract-tests.xml\n        env:\n          GREENHELIX_API_KEY: ${{ secrets.GREENHELIX_API_KEY }}\n\n      - name: Upload test results\n        if: always()\n        uses: actions\u002Fupload-artifact@v4\n        with:\n          name: contract-test-results\n          path: results\u002Fcontract-tests.xml\n\n  # ── Layer 3 + 4: Integration and chaos tests ─────────────\n  integration-tests:\n    runs-on: ubuntu-latest\n    needs: contract-tests\n    steps:\n      - uses: actions\u002Fcheckout@v4\n\n      - name: Set up Python\n        uses: actions\u002Fsetup-python@v5\n        with:\n          python-version: \"3.12\"\n\n      - name: Install dependencies\n        run: pip install pytest requests cryptography\n\n      - name: Run integration tests (Layer 3)\n        run: |\n          pytest tests\u002F -x -q \\\n            -m \"integration\" \\\n            --tb=short \\\n            --junit-xml=results\u002Fintegration-tests.xml\n        env:\n          GREENHELIX_API_KEY: ${{ secrets.GREENHELIX_API_KEY }}\n\n      - name: Run chaos tests (Layer 4)\n        run: |\n          pytest tests\u002F -q \\\n            -m \"chaos\" \\\n            --tb=short \\\n            --junit-xml=results\u002Fchaos-tests.xml\n        env:\n          GREENHELIX_API_KEY: ${{ secrets.GREENHELIX_API_KEY }}\n        continue-on-error: true  # Chaos tests may have expected failures\n\n      - name: Upload all results\n        if: always()\n        uses: actions\u002Fupload-artifact@v4\n        with:\n          name: integration-test-results\n          path: results\u002F\n\n  # ── Health check against staging ─────────────────────────\n  staging-health:\n    runs-on: ubuntu-latest\n    needs: integration-tests\n    if: github.ref == 'refs\u002Fheads\u002Fmain'\n    steps:\n      - uses: actions\u002Fcheckout@v4\n\n      - name: Set up Python\n        uses: actions\u002Fsetup-python@v5\n        with:\n          python-version: \"3.12\"\n\n      - name: Install dependencies\n        run: pip install requests\n\n      - name: Run health check against staging\n        run: |\n          python -c \"\n          from health_checker import HealthChecker\n          import json, sys\n\n          checker = HealthChecker(\n              api_key='${{ secrets.GREENHELIX_API_KEY }}',\n              agent_id='ci-health-check',\n              base_url='https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1',\n          )\n          result = checker.run_health_check()\n          print(json.dumps(result, indent=2))\n\n          if not result['healthy']:\n              print('HEALTH CHECK FAILED')\n              sys.exit(1)\n          print('HEALTH CHECK PASSED')\n          \"\n```\n\n### Staging with the GreenHelix Sandbox\n\nThe sandbox at `sandbox.greenhelix.net` mirrors the production API exactly. Use it as your staging environment. Every test in Layers 2-4 runs against it. The sandbox resets balances nightly, so do not rely on state persisting between CI runs. Generate unique agent IDs per run using the `agent_id` fixture from the conftest (P1).\n\n```python\n# pytest.ini or pyproject.toml\n# [tool.pytest.ini_options]\n# markers:\n#     sandbox: Tests that require the GreenHelix sandbox\n#     chaos: Chaos testing with failure injection\n#     integration: Multi-step workflow integration tests\n\n@pytest.fixture\ndef ci_agent_id():\n    \"\"\"Generate a CI-unique agent ID to prevent collision.\"\"\"\n    run_id = os.environ.get(\"GITHUB_RUN_ID\", uuid.uuid4().hex[:8])\n    return f\"ci-agent-{run_id}-{uuid.uuid4().hex[:6]}\"\n```\n\n### Canary Deployments\n\nWhen deploying agent commerce changes, use a canary pattern: route 5% of traffic to the new version, monitor the `AgentTracer` metrics for 15 minutes, then promote or roll back.\n\n```python\nclass CanaryDeployment:\n    \"\"\"Canary deployment controller for agent commerce systems.\"\"\"\n\n    def __init__(\n        self,\n        canary_tracer: AgentTracer,\n        stable_tracer: AgentTracer,\n        promotion_threshold: float = 0.95,\n    ):\n        self.canary = canary_tracer\n        self.stable = stable_tracer\n        self.promotion_threshold = promotion_threshold\n\n    def evaluate(self) -> dict:\n        \"\"\"Compare canary metrics against stable baseline.\"\"\"\n        canary_metrics = self.canary.get_metrics()\n        stable_metrics = self.stable.get_metrics()\n\n        if canary_metrics[\"total_calls\"] \u003C 10:\n            return {\"decision\": \"waiting\", \"reason\": \"insufficient_data\"}\n\n        canary_success = canary_metrics.get(\"success_rate\", 0)\n        stable_success = stable_metrics.get(\"success_rate\", 1)\n\n        canary_latency = canary_metrics.get(\"p99_latency_ms\", 0)\n        stable_latency = stable_metrics.get(\"p99_latency_ms\", 1)\n\n        # Canary must match or beat stable on success rate\n        success_ok = canary_success >= stable_success * 0.98\n\n        # Canary latency must not regress more than 20%\n        latency_ok = canary_latency \u003C= stable_latency * 1.20\n\n        if success_ok and latency_ok:\n            return {\"decision\": \"promote\", \"canary_success\": canary_success}\n        else:\n            return {\n                \"decision\": \"rollback\",\n                \"reason\": (\n                    f\"success: {canary_success} vs {stable_success}, \"\n                    f\"p99: {canary_latency}ms vs {stable_latency}ms\"\n                ),\n            }\n```\n\n### Regression Detection\n\nTrack key metrics across CI runs to detect regressions before they reach production. Store the metrics as CI artifacts and compare against the previous run.\n\n```python\nclass RegressionDetector:\n    \"\"\"Detect metric regressions between CI runs.\"\"\"\n\n    def __init__(self, baseline_metrics: dict, current_metrics: dict):\n        self.baseline = baseline_metrics\n        self.current = current_metrics\n\n    def check(self) -> list[dict]:\n        \"\"\"Return a list of detected regressions.\"\"\"\n        regressions = []\n\n        # Success rate regression (any drop is a regression)\n        baseline_sr = self.baseline.get(\"success_rate\", 1.0)\n        current_sr = self.current.get(\"success_rate\", 1.0)\n        if current_sr \u003C baseline_sr - 0.01:\n            regressions.append({\n                \"metric\": \"success_rate\",\n                \"baseline\": baseline_sr,\n                \"current\": current_sr,\n                \"delta\": current_sr - baseline_sr,\n            })\n\n        # Latency regression (>20% increase at p95)\n        baseline_p95 = self.baseline.get(\"p95_latency_ms\", 0)\n        current_p95 = self.current.get(\"p95_latency_ms\", 0)\n        if baseline_p95 > 0 and current_p95 > baseline_p95 * 1.20:\n            regressions.append({\n                \"metric\": \"p95_latency_ms\",\n                \"baseline\": baseline_p95,\n                \"current\": current_p95,\n                \"delta_pct\": round(\n                    (current_p95 - baseline_p95) \u002F baseline_p95 * 100, 1\n                ),\n            })\n\n        # Error rate regression per tool\n        baseline_errors = self.baseline.get(\"error_rate_by_tool\", {})\n        current_errors = self.current.get(\"error_rate_by_tool\", {})\n        for tool, current_rate in current_errors.items():\n            baseline_rate = baseline_errors.get(tool, 0)\n            if current_rate > baseline_rate + 0.05:\n                regressions.append({\n                    \"metric\": f\"error_rate:{tool}\",\n                    \"baseline\": baseline_rate,\n                    \"current\": current_rate,\n                })\n\n        return regressions\n```\n\n---\n\n## Chapter 8: What to Do Next\n\nThis guide covered the four-layer agent testing pyramid, tool contract tests, saga-based workflow testing, chaos failure injection, production observability with the `AgentTracer`, alerting with the `HealthChecker`, and CI\u002FCD integration with GitHub Actions. The four classes -- `AgentTestHarness`, `ChaosMiddleware`, `AgentTracer`, and `HealthChecker` -- compose into a reliability stack that wraps every GreenHelix tool call from development through production.\n\nThe GreenHelix gateway's own test suite (260+ tests across 9 modules, with the gateway alone carrying 1,353 tests) uses the same patterns described here: deterministic mocks for business logic, sandbox integration tests for contract verification, and chaos-style failure injection for payment idempotency. The patterns in this guide are not theoretical -- they are extracted from the test infrastructure that protects the gateway itself.\n\n### Companion Guides\n\nFor the commerce patterns these tests protect, see the companion guides:\n\n- **Agent-to-Agent Commerce: Escrow, Payments, and Trust** (P1) -- the `AgentCommerce` class, escrow patterns, marketplace discovery, subscriptions, and dispute resolution.\n- **The AI Agent FinOps Playbook** (P2) -- the `AgentFinOps` class, per-agent budget caps, webhook alerts, fleet dashboards, and cost attribution.\n- **Verified Trading Bot Reputation** (P3) -- cryptographic PnL proof using Ed25519 signatures and Merkle claim chains.\n- **Tamper-Proof Audit Trails for Trading Bots** (P4) -- EU AI Act compliance, MiFID II reporting, and Merkle chain rotation.\n- **How to Verify Any AI Agent Before Doing Business** (P5) -- the `AgentVerifier` class, five-layer trust stack, and continuous reputation monitoring.\n- **The Agent Strategy Marketplace Playbook** (P6) -- selling verified trading strategies with performance escrow.\n- **Locking Down Agent Commerce** (P7) -- OWASP-aligned security hardening with `SecureAgent` and `SecurityMonitor`.\n- **The Agent SaaS Factory** (P8) -- autonomous micro-SaaS creation with `AgentDeveloper`, `AgentDBA`, and `AgentBilling`.\n\n### Practice on the Sandbox\n\nThe sandbox at `sandbox.greenhelix.net` is free to use with any API key. Run the `HealthChecker` against it. Deploy the GitHub Actions template. Break things deliberately with the `ChaosMiddleware`. The patterns in this guide are designed to be copied, adapted, and deployed today.\n\n### The Bundle\n\nAll eight companion guides plus this cookbook are available as a bundle. Each guide introduces a production-ready Python class. Together they cover the full lifecycle of agent commerce: building, securing, testing, monitoring, and scaling.\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: $29 | Format: Digital Guide | Updates: Lifetime access*\n\n",{"name":5,"tags":24,"type":29,"author":33,"install":34,"license":15,"version":35,"metadata":36,"price_usd":42,"executable":20,"credentials":43,"description":7,"content_type":44,"compatibility":45},[25,26,27,28,29,30,31,32],"testing","observability","chaos-engineering","ci-cd","guide","greenhelix","openclaw","ai-agent","felix-agent","none","1.3.1",{"openclaw":37},{"requires":38,"primaryEnv":40},{"env":39},[40,41],"GREENHELIX_API_KEY","AGENT_SIGNING_KEY",0,[40,41],"markdown",[31],"master","4aa004da461d820f4ea5499e58eb8d196cf99016","community\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-testing-observability","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":55,"prompt":65,"zipAvailable":66},[56,59,62],{"tool":57,"command":58},"npx","npx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-testing-observability",{"tool":60,"command":61},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-testing-observability",{"tool":63,"command":64},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-testing-observability","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-testing-observability\u002FSKILL.md",true,[],[69,76,83,90,97,104],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"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":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"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":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"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":91,"name":92,"nameZh":6,"description":93,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":94,"categories":95,"keywords":96,"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":98,"name":99,"nameZh":6,"description":100,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":101,"categories":102,"keywords":103,"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":105,"name":106,"nameZh":6,"description":107,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":108,"categories":109,"keywords":110,"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",[],[]]