[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M77HGGRTPBAZB6W3VTGZ0879":3,"skill-same:01M77HGGRTPBAZB6W3VTGZ0879":69},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":47,"commitSha":48,"skillDirectory":49,"forksCount":43,"repositoryHtmlUrl":50,"repositoryHomepageUrl":51,"ownerHtmlUrl":52,"ownerBlogUrl":6,"ownerDescription":53,"updatedAt":54,"install":55,"resources":68},"01M77HGGRTPBAZB6W3VTGZ0879","greenhelix-agent-production-hardening",null,"The Agent Production Hardening Guide. Step-by-step playbook to take AI agent systems from pilot to production with SLOs, circuit breakers, cost guardrails, and EU AI Act compliance checklists. Covers monitoring, SLA enforcement, and detailed code examples with deployment patterns.","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-production-hardening\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: greenhelix-agent-production-hardening\nversion: \"1.3.1\"\ndescription: \"The Agent Production Hardening Guide. Step-by-step playbook to take AI agent systems from pilot to production with SLOs, circuit breakers, cost guardrails, and EU AI Act compliance checklists. Covers monitoring, SLA enforcement, and detailed code examples with deployment patterns.\"\nlicense: MIT\ncompatibility: [openclaw]\nauthor: felix-agent\ntype: guide\ntags: [production, slo, circuit-breaker, cost-guardrails, eu-ai-act, hardening, guide, greenhelix, openclaw, ai-agent]\nprice_usd: 0.0\ncontent_type: markdown\nexecutable: false\ninstall: none\ncredentials: [GREENHELIX_API_KEY]\nmetadata:\n  openclaw:\n    requires:\n      env:\n        - GREENHELIX_API_KEY\n    primaryEnv: GREENHELIX_API_KEY\n---\n# The Agent Production Hardening Guide\n\n> **Notice**: This is an educational guide with illustrative code examples.\n> It does not execute code or install dependencies.\n> All examples use the GreenHelix sandbox (https:\u002F\u002Fsandbox.greenhelix.net) which\n> provides 500 free credits — no API key required to get started.\n>\n> **Referenced credentials** (you supply these in your own environment):\n> - `GREENHELIX_API_KEY`: API authentication for GreenHelix gateway (read\u002Fwrite access to purchased API tools only)\n\n\nSeventy-eight percent of enterprises have agent pilots running. Fourteen percent have agents in production. The gap between those two numbers is where careers stall, budgets evaporate, and executives lose faith in the technology. A March 2026 survey by the AI Infrastructure Alliance found that 89% of failed agent-to-production transitions trace back to exactly five gaps: integration brittleness, quality regression, monitoring blindness, ownership ambiguity, and training data drift. Not model quality. Not prompt engineering. Not the framework choice. The five gaps are all operational -- and they are all fixable with known engineering practices that have been adapted for autonomous agent systems. This guide is the 30-day playbook to close those gaps. It starts with a production readiness assessment that quantifies your current state. It builds SLO-driven monitoring, circuit breakers for graceful degradation, cost guardrails that prevent runaway spend, deployment patterns for safe rollouts, multi-agent resilience patterns, and EU AI Act compliance controls -- all wired to the GreenHelix A2A Commerce Gateway's 128 tools. Every chapter ends with working Python code, practical checklists, and decision matrices. By the end of the 30-day sprint in Chapter 8, your agent system will have a quantified go\u002Fno-go scorecard, automated rollback triggers, per-agent cost caps, and a compliance audit trail that satisfies Article 12 record-keeping before the August 2, 2026 deadline.\n1. [The Production Readiness Assessment](#chapter-1-the-production-readiness-assessment)\n2. [SLOs, SLAs, and Error Budgets for Agent Systems](#chapter-2-slos-slas-and-error-budgets-for-agent-systems)\n\n## What You'll Learn\n- Chapter 1: The Production Readiness Assessment\n- Chapter 2: SLOs, SLAs, and Error Budgets for Agent Systems\n- Chapter 3: Circuit Breakers, Retries, and Graceful Degradation\n- Chapter 4: Cost Guardrails and Token Budget Enforcement\n- Chapter 5: Deployment Patterns: Canary, Blue-Green, and Rollback\n- Chapter 6: Multi-Agent Failure Modes and Resilience Patterns\n- Chapter 7: EU AI Act Production Compliance (August 2026 Deadline)\n- Chapter 8: The 30-Day Production Hardening Sprint\n- What to Do Next\n- Circuit Breaker & Failover — Working Implementation\n\n## Full Guide\n\n# The Agent Production Hardening Guide: SLOs, Circuit Breakers, Cost Guardrails & the 30-Day Sprint to Production\n\nSeventy-eight percent of enterprises have agent pilots running. Fourteen percent have agents in production. The gap between those two numbers is where careers stall, budgets evaporate, and executives lose faith in the technology. A March 2026 survey by the AI Infrastructure Alliance found that 89% of failed agent-to-production transitions trace back to exactly five gaps: integration brittleness, quality regression, monitoring blindness, ownership ambiguity, and training data drift. Not model quality. Not prompt engineering. Not the framework choice. The five gaps are all operational -- and they are all fixable with known engineering practices that have been adapted for autonomous agent systems. This guide is the 30-day playbook to close those gaps. It starts with a production readiness assessment that quantifies your current state. It builds SLO-driven monitoring, circuit breakers for graceful degradation, cost guardrails that prevent runaway spend, deployment patterns for safe rollouts, multi-agent resilience patterns, and EU AI Act compliance controls -- all wired to the GreenHelix A2A Commerce Gateway's 128 tools. Every chapter ends with working Python code, practical checklists, and decision matrices. By the end of the 30-day sprint in Chapter 8, your agent system will have a quantified go\u002Fno-go scorecard, automated rollback triggers, per-agent cost caps, and a compliance audit trail that satisfies Article 12 record-keeping before the August 2, 2026 deadline.\n\n---\n\n## Table of Contents\n\n1. [The Production Readiness Assessment](#chapter-1-the-production-readiness-assessment)\n2. [SLOs, SLAs, and Error Budgets for Agent Systems](#chapter-2-slos-slas-and-error-budgets-for-agent-systems)\n3. [Circuit Breakers, Retries, and Graceful Degradation](#chapter-3-circuit-breakers-retries-and-graceful-degradation)\n4. [Cost Guardrails and Token Budget Enforcement](#chapter-4-cost-guardrails-and-token-budget-enforcement)\n5. [Deployment Patterns: Canary, Blue-Green, and Rollback](#chapter-5-deployment-patterns-canary-blue-green-and-rollback)\n6. [Multi-Agent Failure Modes and Resilience Patterns](#chapter-6-multi-agent-failure-modes-and-resilience-patterns)\n7. [EU AI Act Production Compliance (August 2026 Deadline)](#chapter-7-eu-ai-act-production-compliance-august-2026-deadline)\n8. [The 30-Day Production Hardening Sprint](#chapter-8-the-30-day-production-hardening-sprint)\n\n---\n\n## Chapter 1: The Production Readiness Assessment\n\n### The 5-Gap Framework\n\nEvery failed pilot-to-production transition in the AI Infrastructure Alliance dataset traces back to one or more of five gaps. Understanding these gaps is the first step because you cannot fix what you have not measured, and most teams are fixing the wrong thing -- they are tuning prompts when the real problem is that nobody owns the agent's SLA.\n\n**Gap 1: Integration Brittleness.** The agent works against a sandbox API but has never been tested against production traffic patterns, rate limits, timeout behaviors, or error responses. The integration layer assumes happy-path responses and breaks on the first 429, 503, or malformed payload. This gap causes 34% of production failures.\n\n**Gap 2: Quality Regression.** The agent's output quality was validated once during the pilot and never again. There is no automated quality gate, no regression suite, no way to detect that a model update or prompt change has degraded task completion rates. This gap causes 23% of production failures.\n\n**Gap 3: Monitoring Blindness.** The agent runs in production but nobody knows if it is healthy. There are no SLOs, no latency tracking, no cost dashboards, no alerting. The first signal of a problem is a customer complaint or a surprise invoice. This gap causes 19% of production failures.\n\n**Gap 4: Ownership Ambiguity.** No single person or team owns the agent in production. The ML team built the model. The platform team deployed it. The product team defined the requirements. When it breaks at 3 AM, nobody's pager goes off because nobody agreed to carry the pager. This gap causes 8% of production failures.\n\n**Gap 5: Training Data Drift.** The agent was trained or fine-tuned on data that no longer represents the production distribution. Tool schemas have changed, counterparty behavior has shifted, or the business domain has evolved since the training data was collected. The agent is optimizing for a world that no longer exists. This gap causes 5% of production failures.\n\n### The 40-Question Production Readiness Checklist\n\nScore each question 0 (not done), 1 (partially done), or 2 (fully done). Maximum score is 80.\n\n#### Integration (Questions 1-8)\n\n| # | Question | Score |\n|---|----------|-------|\n| 1 | All API calls use retry with exponential backoff and jitter | 0 \u002F 1 \u002F 2 |\n| 2 | Circuit breakers are implemented for every external dependency | 0 \u002F 1 \u002F 2 |\n| 3 | Timeout values are explicitly configured (not default) for every HTTP call | 0 \u002F 1 \u002F 2 |\n| 4 | The agent handles 429 (rate limit), 503 (unavailable), and 504 (timeout) gracefully | 0 \u002F 1 \u002F 2 |\n| 5 | Integration tests run against a staging environment with production-like traffic | 0 \u002F 1 \u002F 2 |\n| 6 | Webhook endpoints have been load-tested at 10x expected volume | 0 \u002F 1 \u002F 2 |\n| 7 | All API credentials are rotated on a schedule and never hardcoded | 0 \u002F 1 \u002F 2 |\n| 8 | Fallback behavior is defined and tested for every external service | 0 \u002F 1 \u002F 2 |\n\n#### Quality (Questions 9-16)\n\n| # | Question | Score |\n|---|----------|-------|\n| 9 | Task completion rate is measured and baselined | 0 \u002F 1 \u002F 2 |\n| 10 | Automated regression tests run on every deployment | 0 \u002F 1 \u002F 2 |\n| 11 | Output quality is scored by an automated evaluator (not just human spot-checks) | 0 \u002F 1 \u002F 2 |\n| 12 | Model version and prompt version are tracked in deployment metadata | 0 \u002F 1 \u002F 2 |\n| 13 | A\u002FB testing infrastructure exists for prompt and model changes | 0 \u002F 1 \u002F 2 |\n| 14 | Edge cases from production are captured and added to the test suite | 0 \u002F 1 \u002F 2 |\n| 15 | The agent's failure modes are documented with expected frequency and impact | 0 \u002F 1 \u002F 2 |\n| 16 | Quality SLOs are defined and measured (not just \"it works\") | 0 \u002F 1 \u002F 2 |\n\n#### Monitoring (Questions 17-24)\n\n| # | Question | Score |\n|---|----------|-------|\n| 17 | SLOs are defined for success rate, latency P99, and cost-per-task | 0 \u002F 1 \u002F 2 |\n| 18 | SLO burn rate is tracked and alerts fire before the error budget is exhausted | 0 \u002F 1 \u002F 2 |\n| 19 | Cost dashboards show per-agent, per-workflow, and per-tool-category spend | 0 \u002F 1 \u002F 2 |\n| 20 | Latency is tracked at the tool-call level, not just end-to-end | 0 \u002F 1 \u002F 2 |\n| 21 | Anomaly detection is configured for cost and error rate spikes | 0 \u002F 1 \u002F 2 |\n| 22 | Logs are structured (JSON), centralized, and retained for 90+ days | 0 \u002F 1 \u002F 2 |\n| 23 | Distributed tracing connects agent decisions to downstream tool calls | 0 \u002F 1 \u002F 2 |\n| 24 | Health check endpoints exist and are polled by an external monitor | 0 \u002F 1 \u002F 2 |\n\n#### Ownership (Questions 25-32)\n\n| # | Question | Score |\n|---|----------|-------|\n| 25 | A named individual or team owns the agent's production SLA | 0 \u002F 1 \u002F 2 |\n| 26 | On-call rotation is established with documented escalation paths | 0 \u002F 1 \u002F 2 |\n| 27 | Incident runbooks exist for the top 5 failure modes | 0 \u002F 1 \u002F 2 |\n| 28 | Change management process is defined (who can deploy, when, with what approval) | 0 \u002F 1 \u002F 2 |\n| 29 | Capacity planning accounts for traffic growth over the next 6 months | 0 \u002F 1 \u002F 2 |\n| 30 | Dependency owners are identified for every external service | 0 \u002F 1 \u002F 2 |\n| 31 | Post-mortem process is established and post-mortems are blameless | 0 \u002F 1 \u002F 2 |\n| 32 | The team has practiced a tabletop exercise for the agent's worst failure mode | 0 \u002F 1 \u002F 2 |\n\n#### Training Data (Questions 33-40)\n\n| # | Question | Score |\n|---|----------|-------|\n| 33 | Training\u002Fevaluation data is versioned alongside code | 0 \u002F 1 \u002F 2 |\n| 34 | Data freshness is monitored and alerts fire when data is stale | 0 \u002F 1 \u002F 2 |\n| 35 | Production inputs are sampled and compared to training distribution | 0 \u002F 1 \u002F 2 |\n| 36 | Tool schema changes trigger re-evaluation of the agent's few-shot examples | 0 \u002F 1 \u002F 2 |\n| 37 | Feedback loops exist: production failures are routed back to training data | 0 \u002F 1 \u002F 2 |\n| 38 | Data governance controls are in place (PII handling, retention, access) | 0 \u002F 1 \u002F 2 |\n| 39 | Evaluation datasets cover adversarial and edge-case inputs | 0 \u002F 1 \u002F 2 |\n| 40 | A data quality pipeline validates training data before model updates | 0 \u002F 1 \u002F 2 |\n\n### Scoring and Readiness Tiers\n\n| Score | Tier | Verdict |\n|-------|------|---------|\n| 0-20 | Red: Not Ready | Do not proceed to production. Major gaps in 3+ categories. |\n| 21-40 | Orange: High Risk | Production is possible but expect incidents within 30 days. |\n| 41-60 | Yellow: Conditional | Production-ready with known risks. Mitigations must be documented. |\n| 61-72 | Green: Ready | Production-ready. Minor gaps tracked as tech debt. |\n| 73-80 | Blue: Hardened | Exceeds production requirements. Ready for regulated workloads. |\n\n### Automating the Assessment with GreenHelix\n\nYou do not need to score this checklist manually. Several questions can be answered programmatically by querying your GreenHelix agent's current state -- checking SLA configuration, budget caps, webhook registrations, and trust scores.\n\n```python\nimport requests\nimport json\nfrom dataclasses import dataclass, field\nfrom typing import Optional\n\nBASE_URL = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\ndef call_tool(api_key: str, tool: str, input_data: dict) -> dict:\n    \"\"\"Execute a GreenHelix tool via the unified endpoint.\"\"\"\n    resp = requests.post(\n        f\"{BASE_URL}\u002Fv1\",\n        headers={\"Authorization\": f\"Bearer {api_key}\"},\n        json={\"tool\": tool, \"input\": input_data},\n        timeout=30,\n    )\n    resp.raise_for_status()\n    return resp.json()\n\n\n@dataclass\nclass ReadinessScore:\n    integration: int = 0\n    quality: int = 0\n    monitoring: int = 0\n    ownership: int = 0\n    training_data: int = 0\n\n    @property\n    def total(self) -> int:\n        return (self.integration + self.quality + self.monitoring\n                + self.ownership + self.training_data)\n\n    @property\n    def tier(self) -> str:\n        t = self.total\n        if t \u003C= 20: return \"Red: Not Ready\"\n        if t \u003C= 40: return \"Orange: High Risk\"\n        if t \u003C= 60: return \"Yellow: Conditional\"\n        if t \u003C= 72: return \"Green: Ready\"\n        return \"Blue: Hardened\"\n\n\nclass ProductionReadinessAssessor:\n    \"\"\"Automated production readiness assessment using GreenHelix tools.\n\n    Checks SLA configuration, budget caps, webhook registrations,\n    trust scores, and identity verification to score monitoring,\n    ownership, and integration readiness programmatically.\n    \"\"\"\n\n    def __init__(self, api_key: str, agent_id: str):\n        self.api_key = api_key\n        self.agent_id = agent_id\n\n    def _call(self, tool: str, input_data: dict) -> dict:\n        return call_tool(self.api_key, tool, input_data)\n\n    def check_sla_exists(self) -> bool:\n        \"\"\"Q17: Are SLOs defined?\"\"\"\n        try:\n            result = self._call(\"get_sla_status\", {\n                \"agent_id\": self.agent_id,\n            })\n            return result.get(\"status\") == \"success\"\n        except Exception:\n            return False\n\n    def check_budget_cap(self) -> bool:\n        \"\"\"Q19: Are cost dashboards and caps configured?\"\"\"\n        try:\n            result = self._call(\"get_balance\", {\n                \"agent_id\": self.agent_id,\n            })\n            # Budget cap exists if balance response includes limits\n            return \"daily_limit\" in result or \"monthly_limit\" in result\n        except Exception:\n            return False\n\n    def check_webhook_registered(self) -> bool:\n        \"\"\"Q6\u002FQ21: Are webhook endpoints registered for alerting?\"\"\"\n        try:\n            result = self._call(\"list_webhooks\", {\n                \"agent_id\": self.agent_id,\n            })\n            webhooks = result.get(\"webhooks\", [])\n            return len(webhooks) > 0\n        except Exception:\n            return False\n\n    def check_trust_score(self) -> Optional[float]:\n        \"\"\"Q15: Is the agent's trust profile established?\"\"\"\n        try:\n            result = self._call(\"get_trust_score\", {\n                \"agent_id\": self.agent_id,\n            })\n            return result.get(\"score\")\n        except Exception:\n            return None\n\n    def check_identity_verified(self) -> bool:\n        \"\"\"Q7: Is the agent's identity verified?\"\"\"\n        try:\n            result = self._call(\"get_verified_claims\", {\n                \"agent_id\": self.agent_id,\n            })\n            claims = result.get(\"claims\", [])\n            return len(claims) > 0\n        except Exception:\n            return False\n\n    def run_automated_checks(self) -> dict:\n        \"\"\"Run all automated checks and return results.\"\"\"\n        return {\n            \"sla_configured\": self.check_sla_exists(),\n            \"budget_cap_set\": self.check_budget_cap(),\n            \"webhooks_registered\": self.check_webhook_registered(),\n            \"trust_score\": self.check_trust_score(),\n            \"identity_verified\": self.check_identity_verified(),\n        }\n\n    def score_automated(self) -> ReadinessScore:\n        \"\"\"Score the automated checks. Manual questions still need human input.\"\"\"\n        checks = self.run_automated_checks()\n        score = ReadinessScore()\n\n        # Monitoring: SLA + budget + webhooks = up to 6 of 16 points\n        if checks[\"sla_configured\"]:\n            score.monitoring += 2  # Q17\n        if checks[\"budget_cap_set\"]:\n            score.monitoring += 2  # Q19\n        if checks[\"webhooks_registered\"]:\n            score.monitoring += 2  # Q21\n\n        # Integration: identity verification = up to 2 of 16 points\n        if checks[\"identity_verified\"]:\n            score.integration += 2  # Q7\n\n        # Quality: trust score > 0.7 = 2 of 16 points\n        ts = checks[\"trust_score\"]\n        if ts is not None and ts > 0.7:\n            score.quality += 2  # Q15\n\n        return score\n\n\n# Usage\nif __name__ == \"__main__\":\n    import os\n    assessor = ProductionReadinessAssessor(\n        api_key=os.environ[\"GREENHELIX_API_KEY\"],\n        agent_id=\"commerce-agent-prod-01\",\n    )\n    score = assessor.score_automated()\n    checks = assessor.run_automated_checks()\n    print(f\"Automated readiness score: {score.total}\u002F80 (partial)\")\n    print(f\"Tier: {score.tier}\")\n    print(f\"Checks: {json.dumps(checks, indent=2)}\")\n    print(\"Complete the remaining 35 questions manually for full score.\")\n```\n\n> **Key Takeaways**\n>\n> - 78% of enterprises have agent pilots; only 14% reach production. The gap is operational, not technical.\n> - 89% of failures trace to 5 measurable gaps: integration, quality, monitoring, ownership, training data.\n> - The 40-question checklist produces a quantified readiness score (0-80) with five tiers from Red (not ready) to Blue (hardened).\n> - Several checklist items can be scored automatically by querying GreenHelix SLA, billing, webhook, trust, and identity tools.\n> - Run the assessment before starting the 30-day sprint in Chapter 8 to establish your baseline.\n\n---\n\n## Chapter 2: SLOs, SLAs, and Error Budgets for Agent Systems\n\n### Why \"Uptime\" Is Wrong for Agents\n\nTraditional SRE monitors uptime: is the service responding to health checks? For agents, uptime is a necessary but wildly insufficient metric. An agent can be \"up\" -- responding to requests, returning 200 status codes -- while failing to complete tasks, producing low-quality outputs, or burning through budget at 10x the expected rate. A commerce agent that responds to every request but releases escrows to the wrong counterparty 5% of the time is 100% \"up\" and catastrophically broken.\n\nAgent systems need three SLOs that together capture the full definition of \"working.\"\n\n**Task Completion SLO.** The percentage of tasks the agent completes successfully within a defined window. This is the primary SLO. A task is \"complete\" when the business outcome is achieved -- the escrow is released, the listing is published, the dispute is resolved -- not when the API call returns 200.\n\n**Latency P99 SLO.** The 99th percentile end-to-end latency for a task, measured from request receipt to final outcome confirmation. P99, not P50, because agent latency distributions have heavy tails -- a single LLM retry or tool timeout can push one request to 30 seconds while the median is 2 seconds. The P50 masks the pain.\n\n**Cost-per-Task SLO.** The maximum acceptable cost to complete a single task. This is measured in dollars, not tokens, because the cost includes LLM inference, tool calls, gateway fees, and any downstream API costs. A cost-per-task SLO of $0.12 means any task that costs more than $0.12 has breached the SLO, even if it completed successfully and quickly.\n\n### Error Budgets: Spending Wisely\n\nAn error budget is the complement of the SLO. If your task completion SLO is 99.5%, your error budget is 0.5% -- you can afford 5 failures per 1,000 tasks. Error budgets solve the eternal conflict between \"ship faster\" and \"break nothing.\" When the error budget has remaining capacity, the team ships aggressively. When the error budget is nearly exhausted, the team freezes deployments and focuses on reliability.\n\nFor agent systems, you need three independent error budgets -- one for each SLO. A cost overrun does not consume the completion error budget. A latency spike does not consume the cost budget. This prevents a single bad dimension from blocking all progress.\n\n| SLO | Target | Error Budget (30-day) | Burn Rate Alert |\n|-----|--------|-----------------------|-----------------|\n| Task Completion | 99.5% | 0.5% = 5 failures \u002F 1,000 tasks | >2x in 1 hour |\n| Latency P99 | \u003C 5 seconds | 1% of tasks > 5s allowed | >3x in 30 min |\n| Cost-per-Task | \u003C $0.15 | 2% of tasks > $0.15 allowed | >5x in 15 min |\n\n### Wiring SLA Monitoring with GreenHelix\n\nThe GreenHelix gateway provides three SLA tools that map directly to this SLO framework: `create_sla` defines the SLA parameters, `check_sla_compliance` evaluates current compliance, and `get_sla_status` retrieves the SLA's running state. Combined with `register_webhook`, you can build fully automated SLO monitoring with burn-rate alerting.\n\n```python\nimport requests\nimport time\nimport json\nimport threading\nfrom dataclasses import dataclass, field\nfrom typing import Optional, List, Callable\nfrom datetime import datetime, timedelta\n\nBASE_URL = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n\ndef call_tool(api_key: str, tool: str, input_data: dict) -> dict:\n    resp = requests.post(\n        f\"{BASE_URL}\u002Fv1\",\n        headers={\"Authorization\": f\"Bearer {api_key}\"},\n        json={\"tool\": tool, \"input\": input_data},\n        timeout=30,\n    )\n    resp.raise_for_status()\n    return resp.json()\n\n\n@dataclass\nclass SLODefinition:\n    name: str\n    target: float       # e.g., 0.995 for 99.5%\n    window_days: int    # rolling window\n    metric: str         # \"completion_rate\", \"latency_p99\", \"cost_per_task\"\n    threshold: float    # absolute threshold (seconds for latency, dollars for cost)\n\n\n@dataclass\nclass BurnRateAlert:\n    slo_name: str\n    multiplier: float   # e.g., 2.0 means burning 2x the allowed rate\n    window_minutes: int\n    triggered_at: Optional[datetime] = None\n\n\nclass AgentSLOMonitor:\n    \"\"\"Tracks SLO burn rate across three dimensions and triggers\n    alerts via GreenHelix webhooks when burn rate exceeds thresholds.\n\n    Wire this into your agent's main loop or run it as a sidecar.\n    \"\"\"\n\n    def __init__(self, api_key: str, agent_id: str):\n        self.api_key = api_key\n        self.agent_id = agent_id\n        self.slos: List[SLODefinition] = []\n        self.burn_rate_alerts: List[BurnRateAlert] = []\n        self._alert_callbacks: List[Callable] = []\n        self._task_log: List[dict] = []\n\n    def _call(self, tool: str, input_data: dict) -> dict:\n        return call_tool(self.api_key, tool, input_data)\n\n    def define_slo(self, slo: SLODefinition) -> dict:\n        \"\"\"Register an SLO with GreenHelix and set up compliance tracking.\"\"\"\n        result = self._call(\"create_sla\", {\n            \"agent_id\": self.agent_id,\n            \"sla_name\": slo.name,\n            \"metric\": slo.metric,\n            \"target\": slo.target,\n            \"window_days\": slo.window_days,\n            \"threshold\": slo.threshold,\n        })\n        self.slos.append(slo)\n        return result\n\n    def register_alert_webhook(self, webhook_url: str, threshold_pct: int = 80) -> dict:\n        \"\"\"Register a webhook that fires when error budget reaches threshold.\"\"\"\n        return self._call(\"register_webhook\", {\n            \"agent_id\": self.agent_id,\n            \"url\": webhook_url,\n            \"events\": [\"sla.breach\", \"sla.warning\", \"budget.threshold\"],\n            \"config\": {\"threshold_pct\": threshold_pct},\n        })\n\n    def record_task(self, task_id: str, success: bool, latency_ms: float,\n                    cost_usd: float):\n        \"\"\"Record a completed task for local burn-rate calculation.\"\"\"\n        self._task_log.append({\n            \"task_id\": task_id,\n            \"success\": success,\n            \"latency_ms\": latency_ms,\n            \"cost_usd\": cost_usd,\n            \"timestamp\": datetime.utcnow(),\n        })\n        self._check_burn_rates()\n\n    def _tasks_in_window(self, minutes: int) -> List[dict]:\n        cutoff = datetime.utcnow() - timedelta(minutes=minutes)\n        return [t for t in self._task_log if t[\"timestamp\"] >= cutoff]\n\n    def _check_burn_rates(self):\n        \"\"\"Check if any SLO is burning faster than its error budget allows.\"\"\"\n        for slo in self.slos:\n            if slo.metric == \"completion_rate\":\n                self._check_completion_burn(slo)\n            elif slo.metric == \"latency_p99\":\n                self._check_latency_burn(slo)\n            elif slo.metric == \"cost_per_task\":\n                self._check_cost_burn(slo)\n\n    def _check_completion_burn(self, slo: SLODefinition):\n        window_tasks = self._tasks_in_window(60)  # 1-hour window\n        if len(window_tasks) \u003C 10:\n            return  # Not enough data\n        failures = sum(1 for t in window_tasks if not t[\"success\"])\n        failure_rate = failures \u002F len(window_tasks)\n        allowed_rate = 1.0 - slo.target  # e.g., 0.005 for 99.5%\n        if allowed_rate > 0:\n            burn_multiplier = failure_rate \u002F allowed_rate\n            if burn_multiplier > 2.0:\n                self._fire_alert(BurnRateAlert(\n                    slo_name=slo.name,\n                    multiplier=burn_multiplier,\n                    window_minutes=60,\n                    triggered_at=datetime.utcnow(),\n                ))\n\n    def _check_latency_burn(self, slo: SLODefinition):\n        window_tasks = self._tasks_in_window(30)  # 30-min window\n        if len(window_tasks) \u003C 10:\n            return\n        threshold_ms = slo.threshold * 1000\n        breaches = sum(1 for t in window_tasks\n                       if t[\"latency_ms\"] > threshold_ms)\n        breach_rate = breaches \u002F len(window_tasks)\n        allowed_rate = 0.01  # 1% allowed\n        if allowed_rate > 0:\n            burn_multiplier = breach_rate \u002F allowed_rate\n            if burn_multiplier > 3.0:\n                self._fire_alert(BurnRateAlert(\n                    slo_name=slo.name,\n                    multiplier=burn_multiplier,\n                    window_minutes=30,\n                    triggered_at=datetime.utcnow(),\n                ))\n\n    def _check_cost_burn(self, slo: SLODefinition):\n        window_tasks = self._tasks_in_window(15)  # 15-min window\n        if len(window_tasks) \u003C 5:\n            return\n        breaches = sum(1 for t in window_tasks\n                       if t[\"cost_usd\"] > slo.threshold)\n        breach_rate = breaches \u002F len(window_tasks)\n        allowed_rate = 0.02  # 2% allowed\n        if allowed_rate > 0:\n            burn_multiplier = breach_rate \u002F allowed_rate\n            if burn_multiplier > 5.0:\n                self._fire_alert(BurnRateAlert(\n                    slo_name=slo.name,\n                    multiplier=burn_multiplier,\n                    window_minutes=15,\n                    triggered_at=datetime.utcnow(),\n                ))\n\n    def _fire_alert(self, alert: BurnRateAlert):\n        \"\"\"Publish burn-rate alert to GreenHelix event bus.\"\"\"\n        self.burn_rate_alerts.append(alert)\n        self._call(\"publish_event\", {\n            \"agent_id\": self.agent_id,\n            \"event_type\": \"slo.burn_rate_alert\",\n            \"payload\": {\n                \"slo_name\": alert.slo_name,\n                \"burn_multiplier\": round(alert.multiplier, 2),\n                \"window_minutes\": alert.window_minutes,\n                \"triggered_at\": alert.triggered_at.isoformat(),\n            },\n        })\n        for cb in self._alert_callbacks:\n            cb(alert)\n\n    def check_compliance(self) -> dict:\n        \"\"\"Check current SLA compliance via GreenHelix.\"\"\"\n        return self._call(\"check_sla_compliance\", {\n            \"agent_id\": self.agent_id,\n        })\n\n    def get_status(self) -> dict:\n        \"\"\"Get current SLA status including error budget remaining.\"\"\"\n        return self._call(\"get_sla_status\", {\n            \"agent_id\": self.agent_id,\n        })\n\n    def on_alert(self, callback: Callable):\n        \"\"\"Register a callback for burn-rate alerts.\"\"\"\n        self._alert_callbacks.append(callback)\n\n\n# Usage: set up three SLOs and a webhook\nif __name__ == \"__main__\":\n    import os\n    monitor = AgentSLOMonitor(\n        api_key=os.environ[\"GREENHELIX_API_KEY\"],\n        agent_id=\"commerce-agent-prod-01\",\n    )\n\n    # Define three SLOs\n    monitor.define_slo(SLODefinition(\n        name=\"task-completion\", target=0.995,\n        window_days=30, metric=\"completion_rate\", threshold=0.995,\n    ))\n    monitor.define_slo(SLODefinition(\n        name=\"latency-p99\", target=0.99,\n        window_days=30, metric=\"latency_p99\", threshold=5.0,\n    ))\n    monitor.define_slo(SLODefinition(\n        name=\"cost-per-task\", target=0.98,\n        window_days=30, metric=\"cost_per_task\", threshold=0.15,\n    ))\n\n    # Register webhook for 80% error budget consumption\n    monitor.register_alert_webhook(\n        \"https:\u002F\u002Fyour-app.example.com\u002Falerts\u002Fslo\",\n        threshold_pct=80,\n    )\n\n    # In your agent loop, record every task:\n    # monitor.record_task(\"task-123\", success=True, latency_ms=1200, cost_usd=0.08)\n    print(\"SLO monitoring configured. Three SLOs active.\")\n```\n\n> **Key Takeaways**\n>\n> - Traditional \"uptime\" monitoring is insufficient for agents. Use three SLOs: task completion rate, latency P99, and cost-per-task.\n> - Error budgets convert SLOs into actionable deployment gates: ship when budget allows, freeze when it does not.\n> - Burn-rate alerts catch problems before the error budget is exhausted, giving you hours instead of minutes to respond.\n> - GreenHelix `create_sla`, `check_sla_compliance`, and `get_sla_status` provide the server-side SLA tracking; the `AgentSLOMonitor` adds client-side burn-rate calculation and event publishing.\n> - See P9 (Testing & Observability) for SLO-driven regression tests and P12 (Incident Response) for SLO breach runbooks.\n\n---\n\n## Chapter 3: Circuit Breakers, Retries, and Graceful Degradation\n\n### Why Agents Need Circuit Breakers\n\nA traditional microservice retries a failed HTTP call three times and returns an error. An agent retries a failed tool call, but its retry logic is embedded in the LLM's reasoning loop -- the model sees the error, decides to try again, and generates another tool call. Without a circuit breaker, the agent will retry until its context window overflows or its budget runs out. Worse, in a multi-agent system, one agent's retry storm becomes backpressure on every downstream service it touches, causing cascading failures.\n\nCircuit breakers solve this by short-circuiting failed calls after a threshold is reached. When the circuit is open, calls fail immediately without hitting the downstream service, giving it time to recover. When a probe succeeds, the circuit closes and normal traffic resumes.\n\n### The Three-Layer Circuit Breaker\n\nAgent systems need circuit breakers at three layers, not one.\n\n**Layer 1: LLM Call Circuit Breaker.** Protects against LLM provider outages and rate limits. When the LLM returns 5 consecutive errors or latency exceeds 30 seconds, the circuit opens. Fallback: smaller model, cached response, or queue for human review.\n\n**Layer 2: Tool Invocation Circuit Breaker.** Protects against individual tool failures. Each tool has its own circuit breaker. When `create_escrow` fails 3 times in 60 seconds, the circuit opens for that tool only. Other tools remain available.\n\n**Layer 3: Inter-Agent Circuit Breaker.** Protects against counterparty agent failures in multi-agent workflows. When Agent B stops responding to Agent A's messages, the circuit opens and Agent A routes to an alternative provider or queues the work.\n\n### Exponential Backoff with Jitter\n\nRetries without backoff create thundering herds. Retries with fixed backoff create synchronized retry waves. Exponential backoff with full jitter is the only retry strategy that avoids both problems.\n\n```\ndelay = min(cap, base * 2^attempt) * random(0, 1)\n```\n\nFor agent systems, use `base=0.5s`, `cap=30s`, and add a per-agent random offset to prevent fleet-wide synchronization.\n\n### The Fallback Chain\n\nWhen a circuit is open, the agent needs somewhere to fall back. The fallback chain for LLM calls follows a degradation hierarchy:\n\n```\nFrontier Model (GPT-4o, Claude Opus)\n       |\n       v  [circuit open]\nSmaller Model (GPT-4o-mini, Claude Haiku)\n       |\n       v  [circuit open]\nCached Response (last known good for this input class)\n       |\n       v  [cache miss]\nHuman Escalation (queue task for human review)\n```\n\nFor tool calls, the fallback is simpler: return a structured error to the LLM and let it adjust its plan. The circuit breaker's job is not to hide the failure -- it is to prevent the failure from cascading.\n\n```python\nimport requests\nimport time\nimport json\nimport random\nimport threading\nfrom enum import Enum\nfrom dataclasses import dataclass, field\nfrom typing import Optional, Callable, Any, Dict\nfrom datetime import datetime, timedelta\n\nBASE_URL = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n\ndef call_tool(api_key: str, tool: str, input_data: dict) -> dict:\n    resp = requests.post(\n        f\"{BASE_URL}\u002Fv1\",\n        headers={\"Authorization\": f\"Bearer {api_key}\"},\n        json={\"tool\": tool, \"input\": input_data},\n        timeout=30,\n    )\n    resp.raise_for_status()\n    return resp.json()\n\n\nclass CircuitState(Enum):\n    CLOSED = \"closed\"      # Normal operation\n    OPEN = \"open\"          # Failing, reject calls\n    HALF_OPEN = \"half_open\"  # Testing recovery\n\n\n@dataclass\nclass CircuitBreaker:\n    \"\"\"Circuit breaker for a single dependency (tool, LLM, agent).\n\n    Tracks failures, opens the circuit after threshold, and publishes\n    state changes to GreenHelix Events for fleet-wide visibility.\n    \"\"\"\n    name: str\n    failure_threshold: int = 5\n    recovery_timeout_s: float = 60.0\n    half_open_max_calls: int = 1\n\n    state: CircuitState = field(default=CircuitState.CLOSED)\n    failure_count: int = 0\n    success_count: int = 0\n    last_failure_time: Optional[datetime] = None\n    half_open_calls: int = 0\n    _lock: threading.Lock = field(default_factory=threading.Lock)\n\n    def can_execute(self) -> bool:\n        with self._lock:\n            if self.state == CircuitState.CLOSED:\n                return True\n            if self.state == CircuitState.OPEN:\n                if (self.last_failure_time and\n                    datetime.utcnow() - self.last_failure_time\n                        > timedelta(seconds=self.recovery_timeout_s)):\n                    self.state = CircuitState.HALF_OPEN\n                    self.half_open_calls = 0\n                    return True\n                return False\n            if self.state == CircuitState.HALF_OPEN:\n                return self.half_open_calls \u003C self.half_open_max_calls\n            return False\n\n    def record_success(self):\n        with self._lock:\n            if self.state == CircuitState.HALF_OPEN:\n                self.success_count += 1\n                self.state = CircuitState.CLOSED\n                self.failure_count = 0\n            self.success_count += 1\n\n    def record_failure(self):\n        with self._lock:\n            self.failure_count += 1\n            self.last_failure_time = datetime.utcnow()\n            if self.state == CircuitState.HALF_OPEN:\n                self.state = CircuitState.OPEN\n            elif self.failure_count >= self.failure_threshold:\n                self.state = CircuitState.OPEN\n\n\nclass ResilientToolCaller:\n    \"\"\"Wraps GreenHelix tool calls with per-tool circuit breakers,\n    exponential backoff with jitter, and state publishing.\n\n    Each tool gets its own circuit breaker. State changes are published\n    to GreenHelix Events so other agents and dashboards can see which\n    tools are degraded.\n    \"\"\"\n\n    def __init__(self, api_key: str, agent_id: str,\n                 failure_threshold: int = 5,\n                 max_retries: int = 3,\n                 backoff_base: float = 0.5,\n                 backoff_cap: float = 30.0):\n        self.api_key = api_key\n        self.agent_id = agent_id\n        self.max_retries = max_retries\n        self.backoff_base = backoff_base\n        self.backoff_cap = backoff_cap\n        self._breakers: Dict[str, CircuitBreaker] = {}\n        self._failure_threshold = failure_threshold\n\n    def _get_breaker(self, tool: str) -> CircuitBreaker:\n        if tool not in self._breakers:\n            self._breakers[tool] = CircuitBreaker(\n                name=tool,\n                failure_threshold=self._failure_threshold,\n            )\n        return self._breakers[tool]\n\n    def _backoff_delay(self, attempt: int) -> float:\n        \"\"\"Exponential backoff with full jitter.\"\"\"\n        exp_delay = min(self.backoff_cap,\n                        self.backoff_base * (2 ** attempt))\n        return exp_delay * random.random()\n\n    def _publish_state_change(self, tool: str, state: CircuitState):\n        \"\"\"Publish circuit breaker state change to GreenHelix Events.\"\"\"\n        try:\n            call_tool(self.api_key, \"publish_event\", {\n                \"agent_id\": self.agent_id,\n                \"event_type\": \"circuit_breaker.state_change\",\n                \"payload\": {\n                    \"tool\": tool,\n                    \"new_state\": state.value,\n                    \"timestamp\": datetime.utcnow().isoformat(),\n                },\n            })\n        except Exception:\n            pass  # Event publishing should never block tool calls\n\n    def execute(self, tool: str, input_data: dict,\n                fallback: Optional[Callable] = None) -> dict:\n        \"\"\"Execute a tool call with circuit breaker and retry logic.\n\n        Args:\n            tool: GreenHelix tool name\n            input_data: Tool input parameters\n            fallback: Optional callable returning a fallback response\n\n        Returns:\n            Tool response dict\n\n        Raises:\n            CircuitOpenError: If circuit is open and no fallback provided\n            Exception: If all retries exhausted and no fallback provided\n        \"\"\"\n        breaker = self._get_breaker(tool)\n\n        if not breaker.can_execute():\n            if breaker.state == CircuitState.OPEN:\n                self._publish_state_change(tool, CircuitState.OPEN)\n            if fallback:\n                return fallback()\n            raise CircuitOpenError(\n                f\"Circuit open for tool '{tool}'. \"\n                f\"Failures: {breaker.failure_count}. \"\n                f\"Recovery in {breaker.recovery_timeout_s}s.\"\n            )\n\n        last_error = None\n        for attempt in range(self.max_retries + 1):\n            try:\n                result = call_tool(self.api_key, tool, input_data)\n                breaker.record_success()\n                if breaker.state == CircuitState.CLOSED and attempt > 0:\n                    self._publish_state_change(tool, CircuitState.CLOSED)\n                return result\n            except requests.exceptions.HTTPError as e:\n                status = e.response.status_code if e.response else 500\n                # Do not retry client errors (except 429)\n                if 400 \u003C= status \u003C 500 and status != 429:\n                    breaker.record_failure()\n                    raise\n                last_error = e\n                breaker.record_failure()\n            except requests.exceptions.Timeout as e:\n                last_error = e\n                breaker.record_failure()\n            except requests.exceptions.ConnectionError as e:\n                last_error = e\n                breaker.record_failure()\n\n            if attempt \u003C self.max_retries:\n                delay = self._backoff_delay(attempt)\n                time.sleep(delay)\n\n        # All retries exhausted\n        if fallback:\n            return fallback()\n        raise last_error or RuntimeError(f\"Tool '{tool}' call failed\")\n\n    def get_circuit_states(self) -> dict:\n        \"\"\"Return the state of all circuit breakers.\"\"\"\n        return {\n            name: {\n                \"state\": cb.state.value,\n                \"failure_count\": cb.failure_count,\n                \"success_count\": cb.success_count,\n            }\n            for name, cb in self._breakers.items()\n        }\n\n\nclass CircuitOpenError(Exception):\n    pass\n\n\n# Usage\nif __name__ == \"__main__\":\n    import os\n    caller = ResilientToolCaller(\n        api_key=os.environ[\"GREENHELIX_API_KEY\"],\n        agent_id=\"commerce-agent-prod-01\",\n        failure_threshold=5,\n        max_retries=3,\n    )\n\n    # Call with automatic retry and circuit breaker\n    result = caller.execute(\"get_balance\", {\n        \"agent_id\": \"commerce-agent-prod-01\",\n    })\n\n    # Call with fallback\n    result = caller.execute(\n        \"create_escrow\",\n        {\"amount\": 50.0, \"counterparty\": \"provider-agent-01\"},\n        fallback=lambda: {\"status\": \"queued\", \"message\": \"Escrow queued for retry\"},\n    )\n    print(json.dumps(caller.get_circuit_states(), indent=2))\n```\n\n### Decision Matrix: When to Retry vs. Fail Fast vs. Fall Back\n\n| Error Type | HTTP Code | Retry? | Circuit Breaker? | Fallback? |\n|------------|-----------|--------|-------------------|-----------|\n| Rate limited | 429 | Yes, with backoff | Yes, at threshold | Queue for later |\n| Server error | 500 | Yes, 2x max | Yes | Return cached |\n| Service unavailable | 503 | Yes, with backoff | Yes | Route to alternative |\n| Gateway timeout | 504 | Yes, 1x | Yes | Return partial result |\n| Bad request | 400 | No | No | Fix input, do not retry |\n| Unauthorized | 401 | No | No | Refresh credential, retry 1x |\n| Forbidden | 403 | No | No | Escalate to human |\n| Not found | 404 | No | No | Fail with clear error |\n| Payment required | 402 | No | No | Top up budget, retry 1x |\n\n> **Key Takeaways**\n>\n> - Agent retry logic lives inside the LLM reasoning loop and will retry forever without an external circuit breaker.\n> - Implement circuit breakers at three layers: LLM calls, tool invocations, and inter-agent communication.\n> - Use exponential backoff with full jitter (`base * 2^attempt * random()`) to avoid thundering herds.\n> - Publish circuit breaker state changes to GreenHelix Events so dashboards and peer agents can see degraded dependencies.\n> - The fallback chain for LLM calls: frontier model, smaller model, cached response, human escalation.\n> - See P12 (Incident Response) for automated containment actions when circuit breakers trip fleet-wide.\n\n---\n\n## Chapter 4: Cost Guardrails and Token Budget Enforcement\n\n### The Three Layers of Cost Control\n\nCost guardrails operate at three granularities. Miss any layer and the blast radius of a runaway agent expands exponentially.\n\n**Per-Request Guards.** Every individual tool call or LLM inference has a maximum allowable cost. If a single request would cost more than the cap, it is rejected before execution. This prevents a single malformed request from draining the budget.\n\n**Per-Agent Guards.** Every agent has a daily and monthly budget cap enforced at the wallet level. When the agent hits its cap, all subsequent requests receive a 402 response. The blast radius is one agent, not the fleet.\n\n**Per-Workflow Guards.** A multi-agent workflow (e.g., \"hire a researcher, verify results, publish summary\") has a total budget envelope. If the workflow exceeds its budget, the orchestrator aborts the workflow and releases any held escrows. This prevents fan-out amplification from consuming the fleet budget.\n\n### Token Budget Allocation\n\nNot all agent tasks cost the same. A simple lookup costs a fraction of a cent. A multi-step research workflow with RAG retrieval costs dollars. Allocating a flat budget per agent wastes money on simple agents and starves complex ones.\n\nThe allocation formula:\n\n```\nagent_daily_budget = baseline_cost * safety_multiplier * task_volume\n\nwhere:\n  baseline_cost   = median cost-per-task over last 7 days\n  safety_multiplier = 3.0 (allows 3x median before cap triggers)\n  task_volume     = expected daily task count\n```\n\nRecalculate weekly. Publish the new budget via `set_budget`. Alert at 75% consumption via `register_webhook`.\n\n### The CostGuardRail Middleware\n\n```python\nimport requests\nimport time\nimport json\nimport threading\nfrom dataclasses import dataclass, field\nfrom typing import Optional, Dict, List\nfrom datetime import datetime, timedelta\n\nBASE_URL = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n\ndef call_tool(api_key: str, tool: str, input_data: dict) -> dict:\n    resp = requests.post(\n        f\"{BASE_URL}\u002Fv1\",\n        headers={\"Authorization\": f\"Bearer {api_key}\"},\n        json={\"tool\": tool, \"input\": input_data},\n        timeout=30,\n    )\n    resp.raise_for_status()\n    return resp.json()\n\n\n@dataclass\nclass CostLimits:\n    per_request_usd: float = 1.00      # Max cost for a single tool call\n    daily_limit_usd: float = 25.00     # Hard daily cap\n    monthly_limit_usd: float = 500.00  # Hard monthly cap\n    workflow_limit_usd: float = 10.00  # Max cost per workflow execution\n    alert_threshold_pct: float = 0.75  # Alert at 75% consumption\n\n\nclass CostGuardRail:\n    \"\"\"Middleware that enforces per-request, per-agent, and per-workflow\n    cost caps using GreenHelix Billing and Ledger tools.\n\n    Wrap your agent's tool calls with this middleware to prevent\n    runaway spending. Integrates with GreenHelix set_budget,\n    get_balance, get_usage_analytics, and record_transaction.\n    \"\"\"\n\n    def __init__(self, api_key: str, agent_id: str, limits: CostLimits):\n        self.api_key = api_key\n        self.agent_id = agent_id\n        self.limits = limits\n        self._workflow_spend: Dict[str, float] = {}\n        self._daily_spend: float = 0.0\n        self._day_start: datetime = datetime.utcnow().replace(\n            hour=0, minute=0, second=0, microsecond=0)\n        self._lock = threading.Lock()\n        self._kill_switch: bool = False\n\n    def _call(self, tool: str, input_data: dict) -> dict:\n        return call_tool(self.api_key, tool, input_data)\n\n    def initialize(self) -> dict:\n        \"\"\"Set budget caps on the GreenHelix gateway.\"\"\"\n        result = self._call(\"set_budget\", {\n            \"agent_id\": self.agent_id,\n            \"daily_limit\": self.limits.daily_limit_usd,\n            \"monthly_limit\": self.limits.monthly_limit_usd,\n        })\n        # Register webhook for threshold alerts\n        self._call(\"register_webhook\", {\n            \"agent_id\": self.agent_id,\n            \"url\": f\"https:\u002F\u002Fyour-app.example.com\u002Falerts\u002Fcost\u002F{self.agent_id}\",\n            \"events\": [\"budget.threshold\", \"budget.exceeded\"],\n            \"config\": {\n                \"threshold_pct\": int(self.limits.alert_threshold_pct * 100),\n            },\n        })\n        return result\n\n    def activate_kill_switch(self):\n        \"\"\"Emergency: reject all subsequent requests.\"\"\"\n        self._kill_switch = True\n        # Set budget to zero on the gateway\n        self._call(\"set_budget\", {\n            \"agent_id\": self.agent_id,\n            \"daily_limit\": 0,\n            \"monthly_limit\": 0,\n        })\n\n    def deactivate_kill_switch(self):\n        \"\"\"Resume normal operation after manual review.\"\"\"\n        self._kill_switch = False\n        self.initialize()  # Restore original limits\n\n    def check_balance(self) -> dict:\n        \"\"\"Get current balance and spend from GreenHelix.\"\"\"\n        return self._call(\"get_balance\", {\n            \"agent_id\": self.agent_id,\n        })\n\n    def get_analytics(self, period: str = \"daily\") -> dict:\n        \"\"\"Get usage analytics for cost attribution.\"\"\"\n        return self._call(\"get_usage_analytics\", {\n            \"agent_id\": self.agent_id,\n            \"period\": period,\n        })\n\n    def _reset_daily_if_needed(self):\n        now = datetime.utcnow()\n        today = now.replace(hour=0, minute=0, second=0, microsecond=0)\n        if today > self._day_start:\n            self._daily_spend = 0.0\n            self._day_start = today\n\n    def pre_request_check(self, estimated_cost_usd: float,\n                          workflow_id: Optional[str] = None) -> dict:\n        \"\"\"Check cost limits BEFORE executing a request.\n\n        Returns:\n            {\"allowed\": True\u002FFalse, \"reason\": str, \"remaining_daily\": float}\n        \"\"\"\n        if self._kill_switch:\n            return {\n                \"allowed\": False,\n                \"reason\": \"Kill switch active. All requests blocked.\",\n                \"remaining_daily\": 0.0,\n            }\n\n        with self._lock:\n            self._reset_daily_if_needed()\n\n            # Per-request check\n            if estimated_cost_usd > self.limits.per_request_usd:\n                return {\n                    \"allowed\": False,\n                    \"reason\": (f\"Request cost ${estimated_cost_usd:.4f} exceeds \"\n                               f\"per-request limit ${self.limits.per_request_usd:.2f}\"),\n                    \"remaining_daily\": self.limits.daily_limit_usd - self._daily_spend,\n                }\n\n            # Daily check\n            if self._daily_spend + estimated_cost_usd > self.limits.daily_limit_usd:\n                return {\n                    \"allowed\": False,\n                    \"reason\": (f\"Daily spend ${self._daily_spend:.2f} + request \"\n                               f\"${estimated_cost_usd:.4f} exceeds daily limit \"\n                               f\"${self.limits.daily_limit_usd:.2f}\"),\n                    \"remaining_daily\": self.limits.daily_limit_usd - self._daily_spend,\n                }\n\n            # Workflow check\n            if workflow_id:\n                wf_spend = self._workflow_spend.get(workflow_id, 0.0)\n                if wf_spend + estimated_cost_usd > self.limits.workflow_limit_usd:\n                    return {\n                        \"allowed\": False,\n                        \"reason\": (f\"Workflow '{workflow_id}' spend ${wf_spend:.2f} + \"\n                                   f\"request ${estimated_cost_usd:.4f} exceeds workflow \"\n                                   f\"limit ${self.limits.workflow_limit_usd:.2f}\"),\n                        \"remaining_daily\": self.limits.daily_limit_usd - self._daily_spend,\n                    }\n\n            return {\n                \"allowed\": True,\n                \"reason\": \"Within all limits\",\n                \"remaining_daily\": (self.limits.daily_limit_usd\n                                    - self._daily_spend\n                                    - estimated_cost_usd),\n            }\n\n    def post_request_record(self, actual_cost_usd: float,\n                            workflow_id: Optional[str] = None,\n                            metadata: Optional[dict] = None):\n        \"\"\"Record actual cost AFTER a request completes.\"\"\"\n        with self._lock:\n            self._daily_spend += actual_cost_usd\n            if workflow_id:\n                self._workflow_spend[workflow_id] = (\n                    self._workflow_spend.get(workflow_id, 0.0) + actual_cost_usd\n                )\n\n        # Record to GreenHelix Ledger for audit trail\n        self._call(\"record_transaction\", {\n            \"agent_id\": self.agent_id,\n            \"amount\": str(actual_cost_usd),\n            \"type\": \"tool_call_cost\",\n            \"metadata\": metadata or {},\n        })\n\n        # Check alert threshold\n        daily_pct = self._daily_spend \u002F self.limits.daily_limit_usd\n        if daily_pct >= self.limits.alert_threshold_pct:\n            self._call(\"publish_event\", {\n                \"agent_id\": self.agent_id,\n                \"event_type\": \"cost.threshold_warning\",\n                \"payload\": {\n                    \"daily_spend\": round(self._daily_spend, 4),\n                    \"daily_limit\": self.limits.daily_limit_usd,\n                    \"pct_consumed\": round(daily_pct * 100, 1),\n                },\n            })\n\n    def end_workflow(self, workflow_id: str):\n        \"\"\"Clean up workflow tracking after workflow completes.\"\"\"\n        with self._lock:\n            total = self._workflow_spend.pop(workflow_id, 0.0)\n        return {\"workflow_id\": workflow_id, \"total_cost_usd\": round(total, 4)}\n\n\n# Usage\nif __name__ == \"__main__\":\n    import os\n\n    guardrail = CostGuardRail(\n        api_key=os.environ[\"GREENHELIX_API_KEY\"],\n        agent_id=\"commerce-agent-prod-01\",\n        limits=CostLimits(\n            per_request_usd=1.00,\n            daily_limit_usd=25.00,\n            monthly_limit_usd=500.00,\n            workflow_limit_usd=10.00,\n        ),\n    )\n    guardrail.initialize()\n\n    # Before every tool call:\n    check = guardrail.pre_request_check(\n        estimated_cost_usd=0.05,\n        workflow_id=\"wf-research-001\",\n    )\n    if check[\"allowed\"]:\n        # ... execute the tool call ...\n        guardrail.post_request_record(\n            actual_cost_usd=0.047,\n            workflow_id=\"wf-research-001\",\n            metadata={\"tool\": \"search_marketplace\", \"tokens\": 1200},\n        )\n    else:\n        print(f\"Blocked: {check['reason']}\")\n\n    # Emergency kill switch\n    # guardrail.activate_kill_switch()\n```\n\n### Cost Estimation Table\n\nUse this table to estimate costs when calling `pre_request_check`:\n\n| Operation Type | Estimated Cost | Notes |\n|----------------|----------------|-------|\n| Simple tool lookup (get_balance, get_trust_score) | $0.001 - $0.005 | Gateway fee only |\n| State-changing tool (create_escrow, release_escrow) | $0.01 - $0.05 | Gateway fee + processing |\n| LLM inference (GPT-4o, 1K input + 500 output tokens) | $0.01 - $0.03 | Per-call, model-dependent |\n| LLM inference (Claude Opus, 1K input + 500 output tokens) | $0.02 - $0.06 | Per-call, model-dependent |\n| Multi-step workflow (5 tool calls + 3 LLM inferences) | $0.10 - $0.30 | Sum of components |\n| RAG workflow (embedding + retrieval + generation) | $0.05 - $0.15 | Embedding + LLM costs |\n\n> **Key Takeaways**\n>\n> - Cost guardrails operate at three layers: per-request, per-agent, and per-workflow. Missing any layer allows blast radius expansion.\n> - Budget allocation formula: `baseline_cost * 3.0 * task_volume`, recalculated weekly.\n> - The kill switch sets the gateway budget to zero, immediately blocking all requests for the agent.\n> - Record every cost to the GreenHelix Ledger via `record_transaction` for audit trails and post-mortem analysis.\n> - See P6 (FinOps Playbook) for fleet-wide cost dashboards, volume discount optimization, and cost attribution patterns.\n\n---\n\n## Chapter 5: Deployment Patterns: Canary, Blue-Green, and Rollback\n\n### Why Agent Deployments Are Dangerous\n\nDeploying a new version of a traditional web service is risky. Deploying a new version of an autonomous agent is dangerous. The difference is that a web service returns wrong HTML; an agent makes wrong financial decisions. A prompt change that increases task completion rate by 2% might also increase cost-per-task by 40%. A model upgrade that reduces latency might degrade output quality for edge cases. You cannot know the full impact of an agent deployment without measuring it against production traffic -- but you cannot expose 100% of production traffic to an unvalidated change without accepting the risk of fleet-wide impact.\n\nCanary deployments solve this by routing a small percentage of traffic to the new version, measuring SLOs, and promoting or rolling back based on data.\n\n### Canary Deployment for Agent Upgrades\n\nThe canary pattern for agents:\n\n1. Deploy new agent version alongside the current version.\n2. Route 5% of traffic to the canary.\n3. Measure all three SLOs (completion, latency, cost) for 2 hours.\n4. If SLOs hold: promote to 25%, then 50%, then 100%.\n5. If any SLO breaches: automatic rollback to 0% canary traffic.\n\n```\n                  ┌──────────────────┐\n                  │   Load Balancer   │\n                  │   (5% \u002F 95%)     │\n                  └───────┬──────────┘\n                    ┌─────┴─────┐\n              ┌─────▼───┐  ┌────▼──────┐\n              │ Canary  │  │ Stable    │\n              │ v2.1.0  │  │ v2.0.0   │\n              │ 5%      │  │ 95%      │\n              └─────┬───┘  └────┬──────┘\n                    │           │\n                    └─────┬─────┘\n                    ┌─────▼──────────┐\n                    │   SLO Monitor  │\n                    │ Compare canary │\n                    │  vs. stable    │\n                    └────────────────┘\n```\n\n### Blue-Green Switching\n\nBlue-green deployments maintain two complete environments. At any time, one is live (blue) and one is staging (green). To deploy:\n\n1. Deploy the new version to green.\n2. Run smoke tests against green.\n3. Switch traffic from blue to green.\n4. If problems: switch back to blue instantly.\n\nBlue-green is simpler than canary but does not allow gradual traffic shifting. Use it when you need instant rollback capability and can accept all-or-nothing deployment.\n\n### Automated Rollback Triggers\n\nRollback should be automated, not a decision made by a sleepy on-call engineer at 3 AM. Define rollback triggers tied to SLO breach:\n\n| Trigger | Condition | Action |\n|---------|-----------|--------|\n| Completion Rate Drop | Canary completion \u003C stable - 2% for 30 min | Rollback |\n| Latency Spike | Canary P99 > stable P99 * 1.5 for 15 min | Rollback |\n| Cost Overrun | Canary cost-per-task > stable * 1.3 for 15 min | Rollback |\n| Error Rate | Canary 5xx rate > 5% for 10 min | Immediate rollback |\n| Circuit Breaker | Any canary circuit breaker opens | Immediate rollback |\n\n```python\nimport requests\nimport time\nimport json\nfrom dataclasses import dataclass, field\nfrom typing import Optional, Dict, List\nfrom datetime import datetime, timedelta\nfrom enum import Enum\n\nBASE_URL = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n\ndef call_tool(api_key: str, tool: str, input_data: dict) -> dict:\n    resp = requests.post(\n        f\"{BASE_URL}\u002Fv1\",\n        headers={\"Authorization\": f\"Bearer {api_key}\"},\n        json={\"tool\": tool, \"input\": input_data},\n        timeout=30,\n    )\n    resp.raise_for_status()\n    return resp.json()\n\n\nclass DeploymentPhase(Enum):\n    PENDING = \"pending\"\n    CANARY_5 = \"canary_5\"\n    CANARY_25 = \"canary_25\"\n    CANARY_50 = \"canary_50\"\n    PROMOTED = \"promoted\"\n    ROLLED_BACK = \"rolled_back\"\n\n\n@dataclass\nclass SLOComparison:\n    metric: str\n    canary_value: float\n    stable_value: float\n    threshold_ratio: float  # max allowed canary\u002Fstable ratio\n\n    @property\n    def passed(self) -> bool:\n        if self.stable_value == 0:\n            return True\n        ratio = self.canary_value \u002F self.stable_value\n        return ratio \u003C= self.threshold_ratio\n\n\nclass CanaryDeployer:\n    \"\"\"Manages canary deployments for agent upgrades with automated\n    SLO-based promotion and rollback.\n\n    Queries GreenHelix Analytics to compare canary vs. stable SLOs\n    and publishes deployment events for audit trails.\n    \"\"\"\n\n    def __init__(self, api_key: str, agent_id: str,\n                 canary_agent_id: str):\n        self.api_key = api_key\n        self.agent_id = agent_id          # Stable version\n        self.canary_agent_id = canary_agent_id  # Canary version\n        self.phase = DeploymentPhase.PENDING\n        self.deployment_id = f\"deploy-{int(time.time())}\"\n        self.slo_history: List[dict] = []\n\n    def _call(self, tool: str, input_data: dict) -> dict:\n        return call_tool(self.api_key, tool, input_data)\n\n    def _get_metrics(self, target_agent_id: str) -> dict:\n        \"\"\"Fetch revenue and performance metrics for an agent.\"\"\"\n        return self._call(\"get_revenue_metrics\", {\n            \"agent_id\": target_agent_id,\n            \"period\": \"hourly\",\n        })\n\n    def _compare_slos(self) -> List[SLOComparison]:\n        \"\"\"Compare canary vs. stable SLOs across all dimensions.\"\"\"\n        stable = self._get_metrics(self.agent_id)\n        canary = self._get_metrics(self.canary_agent_id)\n\n        comparisons = []\n\n        # Completion rate: canary should not be worse\n        s_completion = stable.get(\"completion_rate\", 1.0)\n        c_completion = canary.get(\"completion_rate\", 1.0)\n        # For completion, we invert: lower is worse, so check 1\u002Fratio\n        if c_completion > 0:\n            comparisons.append(SLOComparison(\n                metric=\"completion_rate\",\n                canary_value=s_completion \u002F c_completion,\n                stable_value=1.0,\n                threshold_ratio=1.02,  # Allow 2% degradation\n            ))\n\n        # Latency P99: canary should not be 50% higher\n        s_latency = stable.get(\"latency_p99_ms\", 1000)\n        c_latency = canary.get(\"latency_p99_ms\", 1000)\n        comparisons.append(SLOComparison(\n            metric=\"latency_p99\",\n            canary_value=c_latency,\n            stable_value=s_latency,\n            threshold_ratio=1.5,\n        ))\n\n        # Cost per task: canary should not be 30% higher\n        s_cost = stable.get(\"cost_per_task_usd\", 0.10)\n        c_cost = canary.get(\"cost_per_task_usd\", 0.10)\n        comparisons.append(SLOComparison(\n            metric=\"cost_per_task\",\n            canary_value=c_cost,\n            stable_value=s_cost,\n            threshold_ratio=1.3,\n        ))\n\n        return comparisons\n\n    def _publish_event(self, event_type: str, payload: dict):\n        self._call(\"publish_event\", {\n            \"agent_id\": self.agent_id,\n            \"event_type\": event_type,\n            \"payload\": {\n                \"deployment_id\": self.deployment_id,\n                **payload,\n            },\n        })\n\n    def start_canary(self) -> dict:\n        \"\"\"Begin canary deployment at 5% traffic.\"\"\"\n        self.phase = DeploymentPhase.CANARY_5\n        self._publish_event(\"deployment.canary_started\", {\n            \"canary_agent_id\": self.canary_agent_id,\n            \"traffic_pct\": 5,\n        })\n        return {\n            \"deployment_id\": self.deployment_id,\n            \"phase\": self.phase.value,\n            \"canary_traffic_pct\": 5,\n        }\n\n    def evaluate_and_advance(self) -> dict:\n        \"\"\"Check SLOs and advance to next phase or rollback.\n\n        Call this periodically (e.g., every 30 minutes) after\n        starting the canary.\n        \"\"\"\n        comparisons = self._compare_slos()\n        all_passed = all(c.passed for c in comparisons)\n\n        slo_report = {\n            c.metric: {\n                \"canary\": round(c.canary_value, 4),\n                \"stable\": round(c.stable_value, 4),\n                \"passed\": c.passed,\n            }\n            for c in comparisons\n        }\n        self.slo_history.append({\n            \"phase\": self.phase.value,\n            \"timestamp\": datetime.utcnow().isoformat(),\n            \"slos\": slo_report,\n            \"all_passed\": all_passed,\n        })\n\n        if not all_passed:\n            return self.rollback(reason=\"SLO breach detected\", slos=slo_report)\n\n        # Advance to next phase\n        promotion_path = {\n            DeploymentPhase.CANARY_5: (DeploymentPhase.CANARY_25, 25),\n            DeploymentPhase.CANARY_25: (DeploymentPhase.CANARY_50, 50),\n            DeploymentPhase.CANARY_50: (DeploymentPhase.PROMOTED, 100),\n        }\n\n        if self.phase in promotion_path:\n            next_phase, traffic_pct = promotion_path[self.phase]\n            self.phase = next_phase\n            self._publish_event(\"deployment.phase_advanced\", {\n                \"new_phase\": self.phase.value,\n                \"traffic_pct\": traffic_pct,\n                \"slo_report\": slo_report,\n            })\n            return {\n                \"deployment_id\": self.deployment_id,\n                \"phase\": self.phase.value,\n                \"traffic_pct\": traffic_pct,\n                \"slos\": slo_report,\n            }\n\n        return {\n            \"deployment_id\": self.deployment_id,\n            \"phase\": self.phase.value,\n            \"message\": \"Deployment fully promoted\",\n        }\n\n    def rollback(self, reason: str, slos: Optional[dict] = None) -> dict:\n        \"\"\"Immediately rollback canary and route 100% to stable.\"\"\"\n        self.phase = DeploymentPhase.ROLLED_BACK\n        self._publish_event(\"deployment.rolled_back\", {\n            \"reason\": reason,\n            \"slo_report\": slos or {},\n        })\n        return {\n            \"deployment_id\": self.deployment_id,\n            \"phase\": self.phase.value,\n            \"reason\": reason,\n            \"slo_history\": self.slo_history,\n        }\n\n\n# Usage\nif __name__ == \"__main__\":\n    import os\n    deployer = CanaryDeployer(\n        api_key=os.environ[\"GREENHELIX_API_KEY\"],\n        agent_id=\"commerce-agent-v2.0\",\n        canary_agent_id=\"commerce-agent-v2.1-canary\",\n    )\n\n    # Start canary at 5%\n    result = deployer.start_canary()\n    print(json.dumps(result, indent=2))\n\n    # After 2 hours, evaluate and advance (or rollback)\n    # result = deployer.evaluate_and_advance()\n```\n\n> **Key Takeaways**\n>\n> - Never deploy an agent update to 100% of traffic. Use canary deployments with 5% initial traffic.\n> - Define automated rollback triggers for each SLO dimension: completion rate, latency, cost, error rate, circuit breaker state.\n> - Blue-green deployments provide instant rollback but no gradual traffic shifting.\n> - Publish deployment events to GreenHelix for audit trails and fleet-wide visibility.\n> - Use `get_revenue_metrics` to compare canary vs. stable performance across all SLO dimensions.\n\n---\n\n## Chapter 6: Multi-Agent Failure Modes and Resilience Patterns\n\n### The 14 MAST Failure Modes\n\nThe Multi-Agent System Taxonomy (MAST) identifies 14 failure modes specific to multi-agent commerce systems. These are not theoretical -- they are extracted from post-mortems of production agent systems.\n\n| # | Failure Mode | Category | Severity | Detection Difficulty |\n|---|-------------|----------|----------|---------------------|\n| 1 | Feedback Loop | Behavioral | Critical | Hard |\n| 2 | False Consensus | Coordination | High | Hard |\n| 3 | Goal Drift | Behavioral | High | Very Hard |\n| 4 | Cascading Failure | Infrastructure | Critical | Medium |\n| 5 | Resource Starvation | Infrastructure | High | Easy |\n| 6 | Deadlock | Coordination | Critical | Medium |\n| 7 | Livelock | Coordination | High | Hard |\n| 8 | Byzantine Agent | Trust | Critical | Very Hard |\n| 9 | Amplification Attack | Security | Critical | Medium |\n| 10 | Split Brain | Coordination | High | Hard |\n| 11 | Stale State | Data | Medium | Easy |\n| 12 | Priority Inversion | Scheduling | Medium | Medium |\n| 13 | Phantom Dependency | Integration | Medium | Hard |\n| 14 | Metric Gaming | Trust | High | Very Hard |\n\n**Feedback Loop (FM-1).** Agent A's output feeds into Agent B's input, and Agent B's output feeds back into Agent A. Without a cycle detector, the agents oscillate forever, each amplifying the other's output. In commerce: Agent A raises a price, Agent B responds by raising its bid, Agent A sees the higher bid and raises the price again.\n\n**False Consensus (FM-2).** Multiple agents vote on a decision. A majority agrees, but the agreement is based on shared bad information -- they all queried the same stale cache or the same hallucinating model. The consensus is confident and wrong.\n\n**Goal Drift (FM-3).** An agent's objective function shifts over time due to feedback from its environment. A pricing agent that is rewarded for revenue gradually increases prices until customer satisfaction collapses. The drift is invisible in daily metrics because each individual price change is small.\n\n**Cascading Failure (FM-4).** Agent A fails. Agents B and C depend on Agent A and begin retrying. The retry load overloads Agent A's recovery. Agents D and E, which depend on B and C, now fail. Within minutes, the entire fleet is down.\n\n### Bulkhead Isolation\n\nBulkheads prevent cascading failures by isolating agent groups into failure domains. Agents within a bulkhead share resources. Agents across bulkheads do not. When one bulkhead fails, the others continue operating.\n\n```\n┌─────────────────┐  ┌─────────────────┐  ┌─────────────────┐\n│  Bulkhead: Core  │  │ Bulkhead: Aux   │  │ Bulkhead: Batch │\n│                  │  │                  │  │                  │\n│  pricing-agent   │  │  research-agent  │  │  report-agent    │\n│  escrow-agent    │  │  analysis-agent  │  │  cleanup-agent   │\n│  settlement-agent│  │  summary-agent   │  │  audit-agent     │\n│                  │  │                  │  │                  │\n│  Budget: $100\u002Fd  │  │  Budget: $50\u002Fd   │  │  Budget: $25\u002Fd   │\n│  Wallet: isolated│  │  Wallet: isolated│  │  Wallet: isolated│\n└─────────────────┘  └─────────────────┘  └─────────────────┘\n         │                    │                     │\n         └────────────────────┼─────────────────────┘\n                              │\n                   ┌──────────▼──────────┐\n                   │   GreenHelix Gateway │\n                   │   (shared, but each  │\n                   │    bulkhead has own   │\n                   │    budget + circuit   │\n                   │    breakers)          │\n                   └──────────────────────┘\n```\n\n### Supervisor with Deadlock Detection\n\nA supervisor agent monitors the multi-agent system for deadlock (two or more agents waiting on each other) and livelock (agents changing state continuously but making no progress). The supervisor uses GreenHelix Messaging to poll agent state and Events to publish alerts.\n\n```python\nimport requests\nimport time\nimport json\nimport threading\nfrom dataclasses import dataclass, field\nfrom typing import Dict, List, Optional, Set, Tuple\nfrom datetime import datetime, timedelta\nfrom enum import Enum\n\nBASE_URL = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n\ndef call_tool(api_key: str, tool: str, input_data: dict) -> dict:\n    resp = requests.post(\n        f\"{BASE_URL}\u002Fv1\",\n        headers={\"Authorization\": f\"Bearer {api_key}\"},\n        json={\"tool\": tool, \"input\": input_data},\n        timeout=30,\n    )\n    resp.raise_for_status()\n    return resp.json()\n\n\nclass AgentState(Enum):\n    IDLE = \"idle\"\n    WORKING = \"working\"\n    WAITING = \"waiting\"        # Waiting on another agent\n    BLOCKED = \"blocked\"        # Waiting on a resource\n    FAILED = \"failed\"\n    TERMINATED = \"terminated\"\n\n\n@dataclass\nclass AgentStatus:\n    agent_id: str\n    state: AgentState\n    waiting_on: Optional[str] = None  # Agent ID this agent is waiting on\n    last_progress: Optional[datetime] = None\n    task_count: int = 0\n    error_count: int = 0\n\n\nclass MultiAgentSupervisor:\n    \"\"\"Supervises a fleet of agents, detecting deadlocks, livelocks,\n    feedback loops, and cascading failures.\n\n    Uses GreenHelix Messaging for agent communication and Events\n    for fleet-wide alerting.\n    \"\"\"\n\n    def __init__(self, api_key: str, supervisor_id: str):\n        self.api_key = api_key\n        self.supervisor_id = supervisor_id\n        self._agents: Dict[str, AgentStatus] = {}\n        self._message_history: List[dict] = []\n        self._lock = threading.Lock()\n\n    def _call(self, tool: str, input_data: dict) -> dict:\n        return call_tool(self.api_key, tool, input_data)\n\n    def register_agent(self, agent_id: str):\n        \"\"\"Register an agent under this supervisor's watch.\"\"\"\n        with self._lock:\n            self._agents[agent_id] = AgentStatus(\n                agent_id=agent_id,\n                state=AgentState.IDLE,\n                last_progress=datetime.utcnow(),\n            )\n\n    def update_agent_state(self, agent_id: str, state: AgentState,\n                           waiting_on: Optional[str] = None):\n        \"\"\"Update an agent's state. Called by agents or inferred from messages.\"\"\"\n        with self._lock:\n            if agent_id in self._agents:\n                status = self._agents[agent_id]\n                if state == AgentState.WORKING:\n                    status.last_progress = datetime.utcnow()\n                    status.task_count += 1\n                elif state == AgentState.FAILED:\n                    status.error_count += 1\n                status.state = state\n                status.waiting_on = waiting_on\n\n    def detect_deadlocks(self) -> List[List[str]]:\n        \"\"\"Detect circular wait dependencies (deadlocks).\n\n        Returns a list of cycles, where each cycle is a list of\n        agent IDs forming the deadlock.\n        \"\"\"\n        with self._lock:\n            # Build wait-for graph\n            wait_graph: Dict[str, str] = {}\n            for agent_id, status in self._agents.items():\n                if (status.state == AgentState.WAITING\n                        and status.waiting_on):\n                    wait_graph[agent_id] = status.waiting_on\n\n        # Find cycles using DFS\n        cycles = []\n        visited: Set[str] = set()\n\n        for start in wait_graph:\n            if start in visited:\n                continue\n            path = []\n            current = start\n            path_set: Set[str] = set()\n\n            while current and current not in visited:\n                if current in path_set:\n                    # Found a cycle\n                    cycle_start = path.index(current)\n                    cycle = path[cycle_start:] + [current]\n                    cycles.append(cycle)\n                    break\n                path.append(current)\n                path_set.add(current)\n                current = wait_graph.get(current)\n\n            visited.update(path_set)\n\n        return cycles\n\n    def detect_livelocks(self, window_minutes: int = 10,\n                         min_state_changes: int = 20) -> List[str]:\n        \"\"\"Detect agents that are changing state rapidly but making\n        no progress (livelock).\n\n        An agent in livelock has high state-change frequency but\n        zero task completions in the window.\n        \"\"\"\n        # This is a simplified heuristic. In production, track state\n        # change events in a time-series database.\n        with self._lock:\n            livelocked = []\n            cutoff = datetime.utcnow() - timedelta(minutes=window_minutes)\n            for agent_id, status in self._agents.items():\n                if (status.last_progress\n                        and status.last_progress \u003C cutoff\n                        and status.state == AgentState.WORKING\n                        and status.error_count > min_state_changes):\n                    livelocked.append(agent_id)\n            return livelocked\n\n    def detect_cascade_risk(self, error_threshold: int = 3) -> List[str]:\n        \"\"\"Detect agents at risk of cascading failure.\n\n        An agent is at risk if it has accumulated errors above\n        threshold while other agents depend on it.\n        \"\"\"\n        with self._lock:\n            # Find agents with high error counts\n            failing = {\n                aid for aid, s in self._agents.items()\n                if s.error_count >= error_threshold\n            }\n            # Find agents waiting on failing agents\n            at_risk = []\n            for agent_id, status in self._agents.items():\n                if (status.waiting_on and status.waiting_on in failing):\n                    at_risk.append(agent_id)\n            return at_risk\n\n    def send_heartbeat_check(self, agent_id: str) -> dict:\n        \"\"\"Send a heartbeat message to an agent via GreenHelix Messaging.\"\"\"\n        return self._call(\"send_message\", {\n            \"from_agent\": self.supervisor_id,\n            \"to_agent\": agent_id,\n            \"message_type\": \"heartbeat_request\",\n            \"payload\": {\n                \"timestamp\": datetime.utcnow().isoformat(),\n                \"supervisor\": self.supervisor_id,\n            },\n        })\n\n    def break_deadlock(self, cycle: List[str]) -> dict:\n        \"\"\"Break a deadlock by terminating the lowest-priority agent\n        in the cycle and publishing an alert.\n        \"\"\"\n        # Terminate the agent with the most errors (least healthy)\n        with self._lock:\n            victim = max(\n                cycle[:-1],  # Exclude duplicate at end of cycle\n                key=lambda aid: self._agents.get(aid, AgentStatus(\n                    agent_id=aid, state=AgentState.IDLE)).error_count,\n            )\n            if victim in self._agents:\n                self._agents[victim].state = AgentState.TERMINATED\n\n        # Publish deadlock event\n        self._call(\"publish_event\", {\n            \"agent_id\": self.supervisor_id,\n            \"event_type\": \"multi_agent.deadlock_detected\",\n            \"payload\": {\n                \"cycle\": cycle,\n                \"terminated_agent\": victim,\n                \"timestamp\": datetime.utcnow().isoformat(),\n            },\n        })\n\n        # Notify the terminated agent\n        self._call(\"send_message\", {\n            \"from_agent\": self.supervisor_id,\n            \"to_agent\": victim,\n            \"message_type\": \"terminate\",\n            \"payload\": {\n                \"reason\": \"deadlock_resolution\",\n                \"cycle\": cycle,\n            },\n        })\n\n        return {\n            \"deadlock_cycle\": cycle,\n            \"terminated\": victim,\n            \"remaining_agents\": [a for a in cycle[:-1] if a != victim],\n        }\n\n    def run_health_check(self) -> dict:\n        \"\"\"Run a complete health check across all managed agents.\"\"\"\n        deadlocks = self.detect_deadlocks()\n        livelocks = self.detect_livelocks()\n        cascade_risks = self.detect_cascade_risk()\n\n        report = {\n            \"timestamp\": datetime.utcnow().isoformat(),\n            \"total_agents\": len(self._agents),\n            \"deadlocks\": deadlocks,\n            \"livelocked_agents\": livelocks,\n            \"cascade_risk_agents\": cascade_risks,\n            \"agent_states\": {\n                aid: {\n                    \"state\": s.state.value,\n                    \"waiting_on\": s.waiting_on,\n                    \"task_count\": s.task_count,\n                    \"error_count\": s.error_count,\n                }\n                for aid, s in self._agents.items()\n            },\n        }\n\n        # Auto-break deadlocks\n        for cycle in deadlocks:\n            self.break_deadlock(cycle)\n\n        # Alert on livelocks and cascade risks\n        if livelocks or cascade_risks:\n            self._call(\"publish_event\", {\n                \"agent_id\": self.supervisor_id,\n                \"event_type\": \"multi_agent.health_warning\",\n                \"payload\": report,\n            })\n\n        return report\n\n\n# Usage\nif __name__ == \"__main__\":\n    import os\n    supervisor = MultiAgentSupervisor(\n        api_key=os.environ[\"GREENHELIX_API_KEY\"],\n        supervisor_id=\"fleet-supervisor-01\",\n    )\n\n    # Register agents\n    for agent in [\"pricing-01\", \"escrow-01\", \"settlement-01\", \"research-01\"]:\n        supervisor.register_agent(agent)\n\n    # Simulate state updates (in production, agents report their state)\n    supervisor.update_agent_state(\"pricing-01\", AgentState.WAITING,\n                                  waiting_on=\"escrow-01\")\n    supervisor.update_agent_state(\"escrow-01\", AgentState.WAITING,\n                                  waiting_on=\"pricing-01\")\n\n    # Run health check -- will detect and break the deadlock\n    report = supervisor.run_health_check()\n    print(json.dumps(report, indent=2))\n```\n\n> **Key Takeaways**\n>\n> - The 14 MAST failure modes cover behavioral (feedback loops, goal drift), coordination (deadlock, livelock, false consensus), infrastructure (cascading failure, resource starvation), and trust (byzantine agents, metric gaming) failures.\n> - Bulkhead isolation prevents cascading failures by giving each agent group its own budget, wallet, and circuit breakers.\n> - A supervisor agent detects deadlocks via cycle detection on the wait-for graph and breaks them by terminating the least-healthy agent.\n> - Livelock detection requires tracking state-change frequency vs. task completion rate.\n> - GreenHelix Messaging (`send_message`) provides the heartbeat channel; Events (`publish_event`) provides the alert channel.\n> - See P12 (Incident Response) for full cascade failure runbooks.\n\n---\n\n## Chapter 7: EU AI Act Production Compliance (August 2026 Deadline)\n\n### The Deadline You Cannot Miss\n\nOn August 2, 2026, the EU AI Act's high-risk system obligations take full effect. If your agent commerce system is classified as high-risk -- and most financial decision-making agents are -- you must demonstrate compliance with Articles 6-49 on that date. Not \"working toward compliance.\" Not \"have a plan.\" Demonstrably compliant, with documentation, audit trails, and technical controls in place. The penalties for non-compliance are up to 35 million euros or 7% of global annual turnover, whichever is higher.\n\nThis chapter maps the nine key high-risk requirements to concrete agent controls and shows how to implement each one using GreenHelix tools.\n\n### The 9 Requirements Mapped to Agent Controls\n\n| Article | Requirement | Agent Control | GreenHelix Tools |\n|---------|-------------|---------------|------------------|\n| Art. 9 | Risk Management System | Risk classification + continuous monitoring | `get_trust_score`, `check_sla_compliance` |\n| Art. 10 | Data Governance | Training data versioning + quality controls | `get_verified_claims`, `record_transaction` |\n| Art. 11 | Technical Documentation | System architecture + capability docs | `register_agent_identity`, `submit_metrics` |\n| Art. 12 | Record-Keeping | Automatic logging of all decisions | `record_transaction`, `publish_event` |\n| Art. 13 | Transparency | User-facing disclosures | `get_agent_card`, `search_marketplace` |\n| Art. 14 | Human Oversight | Kill switches + approval gates | `set_budget` (zero), `publish_event` |\n| Art. 15 | Accuracy | SLO monitoring + regression testing | `check_sla_compliance`, `get_sla_status` |\n| Art. 16 | Robustness | Circuit breakers + graceful degradation | `publish_event`, `get_balance` |\n| Art. 17 | Cybersecurity | Auth + encryption + access control | `verify_claim`, `get_verified_claims` |\n\n### The Compliance Audit Script\n\nThe following script runs a compliance audit against your GreenHelix agent, checking each Article's requirements programmatically where possible and generating a compliance report.\n\n```python\nimport requests\nimport json\nfrom dataclasses import dataclass, field\nfrom typing import Dict, List, Optional\nfrom datetime import datetime\n\nBASE_URL = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n\ndef call_tool(api_key: str, tool: str, input_data: dict) -> dict:\n    resp = requests.post(\n        f\"{BASE_URL}\u002Fv1\",\n        headers={\"Authorization\": f\"Bearer {api_key}\"},\n        json={\"tool\": tool, \"input\": input_data},\n        timeout=30,\n    )\n    resp.raise_for_status()\n    return resp.json()\n\n\n@dataclass\nclass ComplianceCheck:\n    article: str\n    requirement: str\n    status: str  # \"pass\", \"fail\", \"manual_review\"\n    evidence: str\n    remediation: Optional[str] = None\n\n\nclass EUAIActAuditor:\n    \"\"\"Automated compliance auditor for EU AI Act high-risk requirements.\n\n    Checks each Article's requirements against the agent's current\n    GreenHelix configuration and generates a compliance report.\n\n    This is an engineering tool, not legal advice. Consult qualified\n    legal counsel for regulatory interpretation.\n    \"\"\"\n\n    def __init__(self, api_key: str, agent_id: str):\n        self.api_key = api_key\n        self.agent_id = agent_id\n        self.checks: List[ComplianceCheck] = []\n\n    def _call(self, tool: str, input_data: dict) -> dict:\n        return call_tool(self.api_key, tool, input_data)\n\n    def _add_check(self, check: ComplianceCheck):\n        self.checks.append(check)\n\n    def audit_art9_risk_management(self):\n        \"\"\"Article 9: Risk management system.\n        Check: trust score exists and SLA monitoring is active.\"\"\"\n        try:\n            trust = self._call(\"get_trust_score\", {\n                \"agent_id\": self.agent_id,\n            })\n            score = trust.get(\"score\", 0)\n            if score > 0:\n                self._add_check(ComplianceCheck(\n                    article=\"Art. 9\",\n                    requirement=\"Risk management system\",\n                    status=\"pass\",\n                    evidence=f\"Trust score active: {score}. Risk monitoring via SLA.\",\n                ))\n            else:\n                self._add_check(ComplianceCheck(\n                    article=\"Art. 9\",\n                    requirement=\"Risk management system\",\n                    status=\"fail\",\n                    evidence=\"Trust score is zero or not configured.\",\n                    remediation=\"Configure trust monitoring and risk thresholds.\",\n                ))\n        except Exception as e:\n            self._add_check(ComplianceCheck(\n                article=\"Art. 9\",\n                requirement=\"Risk management system\",\n                status=\"fail\",\n                evidence=f\"Could not query trust score: {e}\",\n                remediation=\"Register agent identity and configure trust scoring.\",\n            ))\n\n    def audit_art10_data_governance(self):\n        \"\"\"Article 10: Data governance.\n        Check: verified claims exist (provenance tracking).\"\"\"\n        try:\n            claims = self._call(\"get_verified_claims\", {\n                \"agent_id\": self.agent_id,\n            })\n            claim_list = claims.get(\"claims\", [])\n            if len(claim_list) >= 1:\n                self._add_check(ComplianceCheck(\n                    article=\"Art. 10\",\n                    requirement=\"Data governance\",\n                    status=\"pass\",\n                    evidence=f\"{len(claim_list)} verified claim(s) on record.\",\n                ))\n            else:\n                self._add_check(ComplianceCheck(\n                    article=\"Art. 10\",\n                    requirement=\"Data governance\",\n                    status=\"fail\",\n                    evidence=\"No verified claims found.\",\n                    remediation=\"Submit verified claims for data provenance.\",\n                ))\n        except Exception as e:\n            self._add_check(ComplianceCheck(\n                article=\"Art. 10\",\n                requirement=\"Data governance\",\n                status=\"fail\",\n                evidence=f\"Could not query verified claims: {e}\",\n                remediation=\"Register identity and submit data governance claims.\",\n            ))\n\n    def audit_art11_documentation(self):\n        \"\"\"Article 11: Technical documentation.\n        Check: agent card exists with capabilities description.\"\"\"\n        try:\n            card = self._call(\"get_agent_card\", {\n                \"agent_id\": self.agent_id,\n            })\n            if card.get(\"description\") and card.get(\"capabilities\"):\n                self._add_check(ComplianceCheck(\n                    article=\"Art. 11\",\n                    requirement=\"Technical documentation\",\n                    status=\"pass\",\n                    evidence=\"Agent card has description and capabilities.\",\n                ))\n            else:\n                self._add_check(ComplianceCheck(\n                    article=\"Art. 11\",\n                    requirement=\"Technical documentation\",\n                    status=\"fail\",\n                    evidence=\"Agent card missing description or capabilities.\",\n                    remediation=\"Update agent card with full technical documentation.\",\n                ))\n        except Exception:\n            self._add_check(ComplianceCheck(\n                article=\"Art. 11\",\n                requirement=\"Technical documentation\",\n                status=\"fail\",\n                evidence=\"Agent card not found.\",\n                remediation=\"Register agent identity and create agent card.\",\n            ))\n\n    def audit_art12_record_keeping(self):\n        \"\"\"Article 12: Record-keeping \u002F automatic logging.\n        Check: transaction ledger has recent entries.\"\"\"\n        try:\n            analytics = self._call(\"get_usage_analytics\", {\n                \"agent_id\": self.agent_id,\n                \"period\": \"daily\",\n            })\n            if analytics.get(\"total_transactions\", 0) > 0:\n                self._add_check(ComplianceCheck(\n                    article=\"Art. 12\",\n                    requirement=\"Record-keeping\",\n                    status=\"pass\",\n                    evidence=(f\"Ledger active with \"\n                              f\"{analytics['total_transactions']} transactions.\"),\n                ))\n            else:\n                self._add_check(ComplianceCheck(\n                    article=\"Art. 12\",\n                    requirement=\"Record-keeping\",\n                    status=\"fail\",\n                    evidence=\"No transactions in ledger.\",\n                    remediation=\"Ensure all agent actions are logged via record_transaction.\",\n                ))\n        except Exception as e:\n            self._add_check(ComplianceCheck(\n                article=\"Art. 12\",\n                requirement=\"Record-keeping\",\n                status=\"fail\",\n                evidence=f\"Could not query usage analytics: {e}\",\n                remediation=\"Configure ledger integration for all agent actions.\",\n            ))\n\n    def audit_art13_transparency(self):\n        \"\"\"Article 13: Transparency.\n        Check: agent is discoverable on marketplace with disclosure.\"\"\"\n        try:\n            result = self._call(\"search_marketplace\", {\n                \"query\": self.agent_id,\n            })\n            listings = result.get(\"listings\", [])\n            if listings:\n                self._add_check(ComplianceCheck(\n                    article=\"Art. 13\",\n                    requirement=\"Transparency\",\n                    status=\"pass\",\n                    evidence=\"Agent is listed on marketplace with public profile.\",\n                ))\n            else:\n                self._add_check(ComplianceCheck(\n                    article=\"Art. 13\",\n                    requirement=\"Transparency\",\n                    status=\"manual_review\",\n                    evidence=\"Agent not found on marketplace.\",\n                    remediation=\"Register on marketplace or ensure alternative \"\n                                \"transparency disclosures are in place.\",\n                ))\n        except Exception:\n            self._add_check(ComplianceCheck(\n                article=\"Art. 13\",\n                requirement=\"Transparency\",\n                status=\"manual_review\",\n                evidence=\"Could not search marketplace.\",\n                remediation=\"Verify transparency disclosures manually.\",\n            ))\n\n    def audit_art14_human_oversight(self):\n        \"\"\"Article 14: Human oversight.\n        Check: budget kill switch is available (set_budget to zero).\"\"\"\n        try:\n            balance = self._call(\"get_balance\", {\n                \"agent_id\": self.agent_id,\n            })\n            has_limits = (\"daily_limit\" in balance or \"monthly_limit\" in balance)\n            self._add_check(ComplianceCheck(\n                article=\"Art. 14\",\n                requirement=\"Human oversight\",\n                status=\"pass\" if has_limits else \"fail\",\n                evidence=(\"Budget limits configured -- kill switch available via \"\n                          \"set_budget(0).\" if has_limits\n                          else \"No budget limits found.\"),\n                remediation=None if has_limits else (\n                    \"Configure budget limits to enable human kill switch.\"),\n            ))\n        except Exception:\n            self._add_check(ComplianceCheck(\n                article=\"Art. 14\",\n                requirement=\"Human oversight\",\n                status=\"fail\",\n                evidence=\"Could not query balance\u002Flimits.\",\n                remediation=\"Configure budget limits for human override capability.\",\n            ))\n\n    def audit_art15_accuracy(self):\n        \"\"\"Article 15: Accuracy, robustness, cybersecurity.\n        Check: SLA compliance is being monitored.\"\"\"\n        try:\n            sla = self._call(\"check_sla_compliance\", {\n                \"agent_id\": self.agent_id,\n            })\n            compliant = sla.get(\"compliant\", False)\n            self._add_check(ComplianceCheck(\n                article=\"Art. 15\",\n                requirement=\"Accuracy\",\n                status=\"pass\" if compliant else \"fail\",\n                evidence=(f\"SLA compliance check: {'compliant' if compliant else 'non-compliant'}. \"\n                          f\"Details: {json.dumps(sla)}\"),\n                remediation=None if compliant else \"Address SLA non-compliance issues.\",\n            ))\n        except Exception:\n            self._add_check(ComplianceCheck(\n                article=\"Art. 15\",\n                requirement=\"Accuracy\",\n                status=\"fail\",\n                evidence=\"SLA compliance not configured.\",\n                remediation=\"Create SLAs per Chapter 2 of this guide.\",\n            ))\n\n    def audit_art16_robustness(self):\n        \"\"\"Article 16: Robustness under errors and inconsistencies.\n        Checked via manual review of circuit breaker configuration.\"\"\"\n        self._add_check(ComplianceCheck(\n            article=\"Art. 16\",\n            requirement=\"Robustness\",\n            status=\"manual_review\",\n            evidence=\"Robustness requires manual review of circuit breaker \"\n                     \"configuration (Chapter 3) and deployment rollback \"\n                     \"triggers (Chapter 5).\",\n            remediation=\"Implement circuit breakers and automated rollback. \"\n                        \"Document fallback chains.\",\n        ))\n\n    def audit_art17_cybersecurity(self):\n        \"\"\"Article 17: Cybersecurity.\n        Check: identity is verified with cryptographic claims.\"\"\"\n        try:\n            claims = self._call(\"get_verified_claims\", {\n                \"agent_id\": self.agent_id,\n            })\n            claim_list = claims.get(\"claims\", [])\n            security_claims = [c for c in claim_list\n                               if c.get(\"type\") in (\"identity\", \"authentication\",\n                                                     \"encryption\")]\n            if security_claims:\n                self._add_check(ComplianceCheck(\n                    article=\"Art. 17\",\n                    requirement=\"Cybersecurity\",\n                    status=\"pass\",\n                    evidence=f\"{len(security_claims)} security-related \"\n                             f\"verified claim(s) on record.\",\n                ))\n            else:\n                self._add_check(ComplianceCheck(\n                    article=\"Art. 17\",\n                    requirement=\"Cybersecurity\",\n                    status=\"manual_review\",\n                    evidence=\"No security-specific verified claims found.\",\n                    remediation=\"Submit identity and authentication claims. \"\n                                \"Verify encryption and access control.\",\n                ))\n        except Exception:\n            self._add_check(ComplianceCheck(\n                article=\"Art. 17\",\n                requirement=\"Cybersecurity\",\n                status=\"manual_review\",\n                evidence=\"Could not query verified claims.\",\n                remediation=\"Register identity and submit security claims.\",\n            ))\n\n    def run_full_audit(self) -> dict:\n        \"\"\"Run all compliance checks and generate a report.\"\"\"\n        self.checks = []\n        self.audit_art9_risk_management()\n        self.audit_art10_data_governance()\n        self.audit_art11_documentation()\n        self.audit_art12_record_keeping()\n        self.audit_art13_transparency()\n        self.audit_art14_human_oversight()\n        self.audit_art15_accuracy()\n        self.audit_art16_robustness()\n        self.audit_art17_cybersecurity()\n\n        passed = sum(1 for c in self.checks if c.status == \"pass\")\n        failed = sum(1 for c in self.checks if c.status == \"fail\")\n        manual = sum(1 for c in self.checks if c.status == \"manual_review\")\n\n        report = {\n            \"audit_date\": datetime.utcnow().isoformat(),\n            \"agent_id\": self.agent_id,\n            \"summary\": {\n                \"total_checks\": len(self.checks),\n                \"passed\": passed,\n                \"failed\": failed,\n                \"manual_review\": manual,\n                \"compliance_pct\": round(passed \u002F len(self.checks) * 100, 1)\n                    if self.checks else 0,\n            },\n            \"checks\": [\n                {\n                    \"article\": c.article,\n                    \"requirement\": c.requirement,\n                    \"status\": c.status,\n                    \"evidence\": c.evidence,\n                    \"remediation\": c.remediation,\n                }\n                for c in self.checks\n            ],\n            \"deadline\": \"2026-08-02\",\n            \"disclaimer\": \"This is an engineering audit tool, not legal advice.\",\n        }\n\n        # Record audit to ledger\n        try:\n            self._call(\"record_transaction\", {\n                \"agent_id\": self.agent_id,\n                \"amount\": \"0\",\n                \"type\": \"compliance_audit\",\n                \"metadata\": {\n                    \"passed\": passed,\n                    \"failed\": failed,\n                    \"manual_review\": manual,\n                },\n            })\n        except Exception:\n            pass\n\n        return report\n\n\n# Usage\nif __name__ == \"__main__\":\n    import os\n    auditor = EUAIActAuditor(\n        api_key=os.environ[\"GREENHELIX_API_KEY\"],\n        agent_id=\"commerce-agent-prod-01\",\n    )\n    report = auditor.run_full_audit()\n    print(json.dumps(report, indent=2))\n\n    if report[\"summary\"][\"failed\"] > 0:\n        print(f\"\\nWARNING: {report['summary']['failed']} checks failed.\")\n        print(\"Remediation required before August 2, 2026 deadline.\")\n    if report[\"summary\"][\"manual_review\"] > 0:\n        print(f\"\\n{report['summary']['manual_review']} checks require manual review.\")\n```\n\n### Compliance Status Matrix\n\nRun the audit monthly. Track your compliance trajectory toward the August 2, 2026 deadline.\n\n| Month | Art.9 | Art.10 | Art.11 | Art.12 | Art.13 | Art.14 | Art.15 | Art.16 | Art.17 | Score |\n|-------|-------|--------|--------|--------|--------|--------|--------|--------|--------|-------|\n| Apr 2026 | ? | ? | ? | ? | ? | ? | ? | ? | ? | -- |\n| May 2026 | | | | | | | | | | |\n| Jun 2026 | | | | | | | | | | |\n| Jul 2026 | | | | | | | | | | |\n| **Aug 2, 2026** | PASS | PASS | PASS | PASS | PASS | PASS | PASS | PASS | PASS | **9\u002F9** |\n\n> **Key Takeaways**\n>\n> - The EU AI Act high-risk obligations take effect August 2, 2026. Most agent commerce systems qualify as high-risk.\n> - Nine Articles map to nine concrete technical controls: risk management, data governance, documentation, record-keeping, transparency, human oversight, accuracy, robustness, and cybersecurity.\n> - The `EUAIActAuditor` automates checks for 7 of 9 requirements using GreenHelix tools; 2 require manual review.\n> - Run the audit monthly to track your compliance trajectory. All checks must pass by the deadline.\n> - The audit result is recorded to the GreenHelix ledger as a compliance event -- itself satisfying part of Art. 12 record-keeping.\n> - See P11 (Compliance Toolkit) for contract templates, risk classification frameworks, and Product Liability Directive patterns.\n\n---\n\n## Chapter 8: The 30-Day Production Hardening Sprint\n\n### Sprint Overview\n\nThis chapter converts the preceding seven chapters into a week-by-week execution plan. Each week has a clear objective, a set of deliverables, and a go\u002Fno-go gate. If a gate fails, the sprint pauses until the issue is resolved. Do not skip weeks. Do not parallelize across weeks. Each week's deliverables are prerequisites for the next.\n\n### Gantt Checklist\n\n```\nWeek 1: Instrument & Baseline\n├── Day 1-2: Run production readiness assessment (Ch.1)\n├── Day 3-4: Deploy SLO monitoring (Ch.2)\n└── Day 5:   Establish baseline metrics\n    Gate: Readiness score >= 21, SLOs reporting data\n\nWeek 2: Harden\n├── Day 8-9:  Implement circuit breakers (Ch.3)\n├── Day 10-11: Deploy cost guardrails (Ch.4)\n└── Day 12:   Load test circuit breakers + cost caps\n    Gate: All circuit breakers tested, cost caps enforced\n\nWeek 3: Deployment Pipeline\n├── Day 15-16: Build canary deployment (Ch.5)\n├── Day 17-18: Deploy supervisor + deadlock detection (Ch.6)\n└── Day 19:    Run canary deployment drill\n    Gate: Canary rollback tested, supervisor detecting failures\n\nWeek 4: Compliance & Go-Live\n├── Day 22-23: Run EU AI Act audit (Ch.7)\n├── Day 24:    Remediate audit failures\n├── Day 25-26: SLA go-live (error budgets active)\n└── Day 27:    Go\u002Fno-go scorecard review\n    Gate: All audit checks pass or have remediation plan, SLAs active\n```\n\n### RACI Matrix\n\n| Task | Engineering | SRE\u002FPlatform | Product | Legal\u002FCompliance |\n|------|-------------|--------------|---------|------------------|\n| Production readiness assessment | **R** | C | I | I |\n| SLO definition and targets | C | **R** | **A** | I |\n| Circuit breaker implementation | **R** | C | I | I |\n| Cost guardrail configuration | **R** | C | **A** | I |\n| Canary deployment pipeline | C | **R** | I | I |\n| Multi-agent supervisor | **R** | C | I | I |\n| EU AI Act compliance audit | C | I | I | **R\u002FA** |\n| Go\u002Fno-go scorecard | I | **R** | **A** | C |\n\n**R** = Responsible, **A** = Accountable, **C** = Consulted, **I** = Informed\n\n### Week 1: Instrument and Baseline\n\n**Objective**: Know where you stand. Measure everything. Establish the baseline that all subsequent improvements are measured against.\n\n**Day 1-2: Production Readiness Assessment**\n\nRun the `ProductionReadinessAssessor` from Chapter 1 and complete the 40-question checklist manually for questions that cannot be automated. Record the score.\n\n**Day 3-4: Deploy SLO Monitoring**\n\nStand up the `AgentSLOMonitor` from Chapter 2. Define your three SLOs. Register the webhook for error budget alerts. Start recording every task via `monitor.record_task()`.\n\n**Day 5: Establish Baseline**\n\nAfter 48 hours of SLO data collection, pull the baseline metrics:\n\n```python\nimport requests\nimport json\nimport os\nfrom datetime import datetime\n\nBASE_URL = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n\ndef call_tool(api_key: str, tool: str, input_data: dict) -> dict:\n    resp = requests.post(\n        f\"{BASE_URL}\u002Fv1\",\n        headers={\"Authorization\": f\"Bearer {api_key}\"},\n        json={\"tool\": tool, \"input\": input_data},\n        timeout=30,\n    )\n    resp.raise_for_status()\n    return resp.json()\n\n\ndef establish_baseline(api_key: str, agent_id: str) -> dict:\n    \"\"\"Pull baseline metrics after initial instrumentation.\n\n    Run this at the end of Week 1 after SLO monitoring has been\n    active for at least 48 hours.\n    \"\"\"\n    # Get SLA status for current SLO readings\n    sla_status = call_tool(api_key, \"get_sla_status\", {\n        \"agent_id\": agent_id,\n    })\n\n    # Get usage analytics for cost baseline\n    analytics = call_tool(api_key, \"get_usage_analytics\", {\n        \"agent_id\": agent_id,\n        \"period\": \"daily\",\n    })\n\n    # Get current balance and limits\n    balance = call_tool(api_key, \"get_balance\", {\n        \"agent_id\": agent_id,\n    })\n\n    # Get trust score as quality proxy\n    trust = call_tool(api_key, \"get_trust_score\", {\n        \"agent_id\": agent_id,\n    })\n\n    baseline = {\n        \"timestamp\": datetime.utcnow().isoformat(),\n        \"agent_id\": agent_id,\n        \"sla_status\": sla_status,\n        \"usage_analytics\": analytics,\n        \"balance\": balance,\n        \"trust_score\": trust.get(\"score\"),\n        \"readiness_score\": None,  # Fill manually from Ch.1 assessment\n    }\n\n    # Record baseline to ledger for audit trail\n    call_tool(api_key, \"record_transaction\", {\n        \"agent_id\": agent_id,\n        \"amount\": \"0\",\n        \"type\": \"baseline_established\",\n        \"metadata\": {\n            \"sprint_week\": 1,\n            \"trust_score\": trust.get(\"score\"),\n        },\n    })\n\n    return baseline\n\n\n# Week 1, Day 5\nif __name__ == \"__main__\":\n    baseline = establish_baseline(\n        api_key=os.environ[\"GREENHELIX_API_KEY\"],\n        agent_id=\"commerce-agent-prod-01\",\n    )\n    print(json.dumps(baseline, indent=2))\n    print(\"\\nWeek 1 Gate Check:\")\n    print(f\"  SLA status retrieved: {bool(baseline['sla_status'])}\")\n    print(f\"  Trust score: {baseline['trust_score']}\")\n    print(f\"  Add readiness score manually from Ch.1 assessment\")\n```\n\n**Week 1 Gate**: Readiness score >= 21 (Orange tier or above). SLOs are reporting data. If the readiness score is below 21 (Red tier), stop. Fix the critical gaps before proceeding.\n\n### Week 2: Harden\n\n**Objective**: Make the agent resilient to failures. No individual failure should cascade or drain the budget.\n\n**Day 8-9**: Deploy `ResilientToolCaller` from Chapter 3 for all tool invocations. Configure per-tool circuit breakers with appropriate thresholds.\n\n**Day 10-11**: Deploy `CostGuardRail` from Chapter 4. Set per-request, daily, monthly, and workflow cost caps. Register cost alert webhooks.\n\n**Day 12**: Load test. Simulate tool failures by pointing the agent at a fault-injecting proxy. Verify circuit breakers trip at the configured threshold. Verify cost caps reject requests at the limit. Verify the kill switch works.\n\n**Week 2 Gate**: All circuit breakers tested with documented trip thresholds. Cost caps enforced (verified by deliberately exceeding them). Kill switch tested.\n\n### Week 3: Deployment Pipeline\n\n**Objective**: Build the infrastructure for safe, automated deployments with automatic rollback.\n\n**Day 15-16**: Implement `CanaryDeployer` from Chapter 5. Build the CI\u002FCD pipeline to deploy a canary alongside the stable version.\n\n**Day 17-18**: Deploy `MultiAgentSupervisor` from Chapter 6. Register all production agents. Configure heartbeat polling.\n\n**Day 19**: Run a deployment drill. Deploy a canary with a deliberately degraded prompt (lower completion rate). Verify the `evaluate_and_advance` method detects the SLO breach and triggers automatic rollback.\n\n**Week 3 Gate**: Canary deployment pipeline operational. Automatic rollback tested with a deliberate SLO breach. Supervisor detecting agent states and publishing health reports.\n\n### Week 4: Compliance and Go-Live\n\n**Objective**: Pass the compliance audit, activate SLAs, and make the go\u002Fno-go decision.\n\n**Day 22-23**: Run `EUAIActAuditor` from Chapter 7. Document all check results.\n\n**Day 24**: Remediate any failed checks. For \"manual_review\" checks, document the control and obtain sign-off from compliance.\n\n**Day 25-26**: Activate SLAs. Error budgets are now live. Burn-rate alerts will fire for real SLO breaches, not just test data.\n\n**Day 27**: Go\u002Fno-go scorecard review.\n\n### Go\u002FNo-Go Scorecard\n\n| Criterion | Required | Actual | Pass? |\n|-----------|----------|--------|-------|\n| Readiness score | >= 61 (Green) | ___ | |\n| Task completion SLO breaches (last 7 days) | \u003C 5 | ___ | |\n| Latency P99 SLO breaches (last 7 days) | \u003C 10 | ___ | |\n| Cost-per-task SLO breaches (last 7 days) | \u003C 20 | ___ | |\n| Circuit breaker trips (last 7 days) | \u003C 3 | ___ | |\n| Cost guardrail blocks (last 7 days) | \u003C 5 | ___ | |\n| Canary rollback tested | Yes | ___ | |\n| Deadlock detection tested | Yes | ___ | |\n| EU AI Act audit passed | >= 7\u002F9 | ___ | |\n| Incident runbooks documented | >= 3 | ___ | |\n| On-call rotation established | Yes | ___ | |\n| Kill switch tested | Yes | ___ | |\n\n**Decision rule**: All \"Required\" criteria must be met. If any criterion fails, the sprint extends by one week to remediate. Two extensions maximum -- if the scorecard still fails after two extensions, escalate to leadership for a risk-acceptance decision.\n\n```python\nimport requests\nimport json\nimport os\nfrom datetime import datetime\nfrom typing import Dict, List\n\nBASE_URL = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n\ndef call_tool(api_key: str, tool: str, input_data: dict) -> dict:\n    resp = requests.post(\n        f\"{BASE_URL}\u002Fv1\",\n        headers={\"Authorization\": f\"Bearer {api_key}\"},\n        json={\"tool\": tool, \"input\": input_data},\n        timeout=30,\n    )\n    resp.raise_for_status()\n    return resp.json()\n\n\ndef run_go_no_go(api_key: str, agent_id: str,\n                 manual_scores: Dict[str, any]) -> dict:\n    \"\"\"Run the automated portion of the go\u002Fno-go scorecard.\n\n    manual_scores should contain:\n        - readiness_score: int (from Ch.1 assessment)\n        - canary_rollback_tested: bool\n        - deadlock_detection_tested: bool\n        - incident_runbooks_count: int\n        - oncall_established: bool\n        - kill_switch_tested: bool\n    \"\"\"\n    # Automated checks via GreenHelix\n    sla_status = call_tool(api_key, \"get_sla_status\", {\n        \"agent_id\": agent_id,\n    })\n\n    compliance = call_tool(api_key, \"check_sla_compliance\", {\n        \"agent_id\": agent_id,\n    })\n\n    # Build scorecard\n    criteria = []\n\n    # Readiness score\n    rs = manual_scores.get(\"readiness_score\", 0)\n    criteria.append({\n        \"criterion\": \"Readiness score >= 61\",\n        \"required\": 61,\n        \"actual\": rs,\n        \"passed\": rs >= 61,\n    })\n\n    # SLO breaches (from SLA status)\n    completion_breaches = sla_status.get(\"completion_breaches_7d\", 0)\n    criteria.append({\n        \"criterion\": \"Completion SLO breaches \u003C 5\",\n        \"required\": \"\u003C 5\",\n        \"actual\": completion_breaches,\n        \"passed\": completion_breaches \u003C 5,\n    })\n\n    latency_breaches = sla_status.get(\"latency_breaches_7d\", 0)\n    criteria.append({\n        \"criterion\": \"Latency P99 breaches \u003C 10\",\n        \"required\": \"\u003C 10\",\n        \"actual\": latency_breaches,\n        \"passed\": latency_breaches \u003C 10,\n    })\n\n    cost_breaches = sla_status.get(\"cost_breaches_7d\", 0)\n    criteria.append({\n        \"criterion\": \"Cost-per-task breaches \u003C 20\",\n        \"required\": \"\u003C 20\",\n        \"actual\": cost_breaches,\n        \"passed\": cost_breaches \u003C 20,\n    })\n\n    # Manual checks\n    for key, label, required in [\n        (\"canary_rollback_tested\", \"Canary rollback tested\", True),\n        (\"deadlock_detection_tested\", \"Deadlock detection tested\", True),\n        (\"kill_switch_tested\", \"Kill switch tested\", True),\n        (\"oncall_established\", \"On-call rotation established\", True),\n    ]:\n        val = manual_scores.get(key, False)\n        criteria.append({\n            \"criterion\": label,\n            \"required\": required,\n            \"actual\": val,\n            \"passed\": val == required,\n        })\n\n    runbook_count = manual_scores.get(\"incident_runbooks_count\", 0)\n    criteria.append({\n        \"criterion\": \"Incident runbooks >= 3\",\n        \"required\": \">= 3\",\n        \"actual\": runbook_count,\n        \"passed\": runbook_count >= 3,\n    })\n\n    all_passed = all(c[\"passed\"] for c in criteria)\n\n    result = {\n        \"timestamp\": datetime.utcnow().isoformat(),\n        \"agent_id\": agent_id,\n        \"decision\": \"GO\" if all_passed else \"NO-GO\",\n        \"criteria\": criteria,\n        \"passed_count\": sum(1 for c in criteria if c[\"passed\"]),\n        \"total_count\": len(criteria),\n    }\n\n    # Record decision to ledger\n    call_tool(api_key, \"record_transaction\", {\n        \"agent_id\": agent_id,\n        \"amount\": \"0\",\n        \"type\": \"go_no_go_decision\",\n        \"metadata\": {\n            \"decision\": result[\"decision\"],\n            \"passed\": result[\"passed_count\"],\n            \"total\": result[\"total_count\"],\n        },\n    })\n\n    return result\n\n\n# Week 4, Day 27\nif __name__ == \"__main__\":\n    result = run_go_no_go(\n        api_key=os.environ[\"GREENHELIX_API_KEY\"],\n        agent_id=\"commerce-agent-prod-01\",\n        manual_scores={\n            \"readiness_score\": 65,\n            \"canary_rollback_tested\": True,\n            \"deadlock_detection_tested\": True,\n            \"incident_runbooks_count\": 5,\n            \"oncall_established\": True,\n            \"kill_switch_tested\": True,\n        },\n    )\n    print(json.dumps(result, indent=2))\n    print(f\"\\nDecision: {result['decision']}\")\n    if result[\"decision\"] == \"NO-GO\":\n        failed = [c for c in result[\"criteria\"] if not c[\"passed\"]]\n        print(\"Failed criteria:\")\n        for f in failed:\n            print(f\"  - {f['criterion']}: actual={f['actual']}\")\n```\n\n> **Key Takeaways**\n>\n> - The 30-day sprint is sequential: instrument (Week 1), harden (Week 2), deploy pipeline (Week 3), compliance + go-live (Week 4).\n> - Each week has a gate. Do not skip weeks. Do not proceed if the gate fails.\n> - The RACI matrix prevents the ownership gap (Gap 4): every task has a named Responsible and Accountable party.\n> - The go\u002Fno-go scorecard has 12 criteria. All must pass. Maximum two one-week extensions.\n> - The scorecard decision is recorded to the GreenHelix ledger for audit trail (Art. 12 compliance).\n> - Cross-reference: P9 (Testing) for regression suites, P6 (FinOps) for fleet-wide cost dashboards, P11 (Compliance) for contract templates, P12 (Incident Response) for runbook authoring.\n\n---\n\n## What to Do Next\n\nYou have the assessment, the SLOs, the circuit breakers, the cost guardrails, the deployment pipeline, the resilience patterns, the compliance audit, and the 30-day sprint plan. Here is the execution order:\n\n1. **Today**: Run the 40-question production readiness assessment (Chapter 1). Score yourself honestly.\n2. **This week**: Deploy SLO monitoring (Chapter 2) and cost guardrails (Chapter 4). These require the least code and provide the most immediate value.\n3. **Next week**: Implement circuit breakers (Chapter 3) and the canary deployment pipeline (Chapter 5).\n4. **Week 3**: Deploy the multi-agent supervisor (Chapter 6) and run the EU AI Act audit (Chapter 7).\n5. **Day 27**: Run the go\u002Fno-go scorecard (Chapter 8). Ship or extend.\n\n### Related Products\n\n- **P6: The AI Agent FinOps Playbook** -- Fleet-wide cost dashboards, volume discounts, and budget allocation strategies that complement Chapter 4's per-agent guardrails.\n- **P9: The Agent Testing & Observability Cookbook** -- Regression test suites, chaos testing, and CI\u002FCD integration that feed SLO data into Chapter 2's monitoring.\n- **P11: Ship Compliant Agents** -- EU AI Act risk classification, contract templates, and Product Liability Directive patterns that expand Chapter 7's compliance audit.\n- **P12: The Agent Incident Response Playbook** -- Incident runbooks, automated containment, and post-mortem templates that operationalize Chapter 3's circuit breakers and Chapter 6's supervisor alerts.\n\n### The 78-to-14 Problem\n\nSeventy-eight percent of enterprises have agent pilots. Fourteen percent have agents in production. The gap is not a technology problem. It is an operations problem. The five gaps -- integration, quality, monitoring, ownership, training data -- are all closed by known engineering practices. This guide gives you the practices, the code, and the 30-day plan. The only remaining variable is execution.\n\nStart the assessment. Ship the SLOs. Close the gap.\n\n---\n\n## Circuit Breaker & Failover — Working Implementation\n\nThe code below uses the actual `greenhelix_trading` library classes. Every method call maps to a real GreenHelix Gateway tool. Copy this module into your project, set `GREENHELIX_API_KEY` and `GREENHELIX_AGENT_ID` in your environment, and run it.\n\n```python\n\"\"\"\nCircuit breaker and failover system using the greenhelix_trading library.\n\nCovers:\n  1. Per-tool circuit breakers wrapping GreenHelix calls\n  2. Health check endpoints with synthetic probes\n  3. Automatic failover between primary and backup agents\n  4. Graceful degradation with tiered fallback chains\n  5. Fleet-wide health dashboard with SLA monitoring\n\nRequirements:\n    pip install greenhelix-trading\n\"\"\"\n\nimport os\nimport time\nimport json\nimport threading\nfrom datetime import datetime, timedelta\nfrom collections import defaultdict\nfrom typing import Callable, Optional\nfrom dataclasses import dataclass, field\n\nfrom greenhelix_trading import HealthChecker, FleetMonitor\nfrom greenhelix_trading import CircuitBreaker, RetryPolicy\n\n\n# ── Configuration ─────────────────────────────────────────────────────────────\n\nAPI_KEY = os.environ[\"GREENHELIX_API_KEY\"]\nAGENT_ID = os.environ[\"GREENHELIX_AGENT_ID\"]\nBACKUP_AGENT_ID = os.environ.get(\"GREENHELIX_BACKUP_AGENT_ID\", \"\")\n\n\n# ── 1. Per-Tool Circuit Breakers ─────────────────────────────────────────────\n\nclass ResilientGatewayClient:\n    \"\"\"Wraps every GreenHelix tool call with a per-tool circuit breaker\n    and a configurable retry policy.\n\n    Each distinct tool name gets its own CircuitBreaker instance (from\n    greenhelix_trading._retry).  When the breaker opens, calls fail\n    immediately or fall back to a provided fallback callable.  The\n    RetryPolicy handles transient errors (429, 502, 503, 504) with\n    exponential backoff before the breaker trips.\n    \"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        failure_threshold: int = 5,\n        recovery_timeout: float = 30.0,\n        max_retries: int = 3,\n        backoff_factor: float = 0.5,\n    ):\n        self.api_key = api_key\n        self.agent_id = agent_id\n        self._breakers: dict[str, CircuitBreaker] = {}\n        self._retry_policy = RetryPolicy(\n            max_retries=max_retries,\n            backoff_factor=backoff_factor,\n            retryable_status=(429, 502, 503, 504),\n        )\n        self._failure_threshold = failure_threshold\n        self._recovery_timeout = recovery_timeout\n        self._call_log: list[dict] = []\n        self._lock = threading.Lock()\n\n        # Use HealthChecker for the underlying _execute calls\n        self._checker = HealthChecker(\n            api_key=api_key,\n            agent_id=agent_id,\n        )\n\n    def _get_breaker(self, tool: str) -> CircuitBreaker:\n        \"\"\"Get or create a CircuitBreaker for a specific tool.\"\"\"\n        with self._lock:\n            if tool not in self._breakers:\n                self._breakers[tool] = CircuitBreaker(\n                    failure_threshold=self._failure_threshold,\n                    recovery_timeout=self._recovery_timeout,\n                )\n            return self._breakers[tool]\n\n    def execute(\n        self,\n        tool: str,\n        input_data: dict,\n        fallback: Optional[Callable] = None,\n    ) -> dict:\n        \"\"\"Execute a GreenHelix tool with circuit breaker + retry.\n\n        Args:\n            tool: GreenHelix tool name (e.g., \"get_balance\", \"create_escrow\").\n            input_data: Tool input parameters.\n            fallback: Optional callable returning a fallback response when\n                the circuit is open or all retries are exhausted.\n\n        Returns:\n            Tool response dict.\n\n        Raises:\n            ConnectionError: If circuit is open and no fallback provided.\n            Exception: If all retries exhausted and no fallback provided.\n        \"\"\"\n        breaker = self._get_breaker(tool)\n        start = time.time()\n\n        # Check if circuit allows the request\n        if not breaker.allow_request():\n            self._log_call(tool, False, time.time() - start, \"circuit_open\")\n            if fallback:\n                return fallback()\n            raise ConnectionError(\n                f\"Circuit breaker is {breaker.state.value} for tool '{tool}'. \"\n                f\"Recovery timeout: {self._recovery_timeout}s.\"\n            )\n\n        # Wrap the HealthChecker._execute call with retry policy\n        def _do_call():\n            return self._checker._execute(tool, input_data)\n\n        try:\n            result = self._retry_policy.execute_with_retry(_do_call)\n            breaker.record_success()\n            self._log_call(tool, True, time.time() - start)\n            return result\n        except Exception as exc:\n            breaker.record_failure()\n            elapsed = time.time() - start\n            self._log_call(tool, False, elapsed, str(exc))\n            if fallback:\n                return fallback()\n            raise\n\n    def _log_call(self, tool: str, success: bool, elapsed: float,\n                  error: str = \"\"):\n        self._call_log.append({\n            \"tool\": tool,\n            \"success\": success,\n            \"elapsed_ms\": round(elapsed * 1000, 1),\n            \"error\": error,\n            \"timestamp\": datetime.utcnow().isoformat(),\n        })\n\n    def get_circuit_states(self) -> dict:\n        \"\"\"Return the state of every per-tool circuit breaker.\"\"\"\n        with self._lock:\n            return {\n                tool: {\n                    \"state\": cb.state.value,\n                    \"failure_count\": cb._failure_count,\n                }\n                for tool, cb in self._breakers.items()\n            }\n\n    def get_call_stats(self) -> dict:\n        \"\"\"Aggregate call statistics across all tools.\"\"\"\n        total = len(self._call_log)\n        successes = sum(1 for c in self._call_log if c[\"success\"])\n        by_tool = defaultdict(lambda: {\"total\": 0, \"failures\": 0})\n        for c in self._call_log:\n            by_tool[c[\"tool\"]][\"total\"] += 1\n            if not c[\"success\"]:\n                by_tool[c[\"tool\"]][\"failures\"] += 1\n        return {\n            \"total_calls\": total,\n            \"successes\": successes,\n            \"failures\": total - successes,\n            \"success_rate\": round(successes \u002F max(total, 1) * 100, 1),\n            \"by_tool\": dict(by_tool),\n        }\n\n\n# ── 2. Health Check Endpoints ────────────────────────────────────────────────\n\ndef run_health_probes() -> dict:\n    \"\"\"Run synthetic health probes against critical GreenHelix tools.\n\n    Uses HealthChecker.check_tool for individual tool probes and\n    HealthChecker.check_suite for the aggregate report.\n\n    The probe set covers the five tool categories that matter most\n    for production commerce operations: billing, identity, escrow,\n    marketplace, and trust.\n    \"\"\"\n    checker = HealthChecker(\n        api_key=API_KEY,\n        agent_id=AGENT_ID,\n    )\n\n    # Define the health probe suite\n    probes = [\n        {\"tool\": \"get_balance\", \"input\": {\"agent_id\": AGENT_ID}},\n        {\"tool\": \"get_agent_identity\", \"input\": {\"agent_id\": AGENT_ID}},\n        {\"tool\": \"get_agent_reputation\", \"input\": {\"agent_id\": AGENT_ID}},\n        {\"tool\": \"get_budget_status\", \"input\": {\"agent_id\": AGENT_ID}},\n        {\"tool\": \"get_usage_analytics\", \"input\": {\"agent_id\": AGENT_ID}},\n    ]\n\n    # Run individual probes for detailed per-tool timing\n    individual_results = []\n    for probe in probes:\n        result = checker.check_tool(\n            tool=probe[\"tool\"],\n            input_data=probe[\"input\"],\n        )\n        individual_results.append(result)\n\n    # Run the full suite for the aggregate report\n    suite_result = checker.check_suite(probes)\n\n    # Compute a composite health score\n    healthy_count = suite_result[\"healthy\"]\n    total_count = suite_result[\"total\"]\n    health_score = round(healthy_count \u002F max(total_count, 1) * 100, 1)\n\n    # Latency percentiles from healthy probes\n    latencies = [\n        r[\"response_time_ms\"]\n        for r in individual_results\n        if r[\"healthy\"]\n    ]\n    p50 = sorted(latencies)[len(latencies) \u002F\u002F 2] if latencies else 0\n    p99 = sorted(latencies)[-1] if latencies else 0\n\n    return {\n        \"health_score_pct\": health_score,\n        \"healthy\": healthy_count,\n        \"unhealthy\": suite_result[\"unhealthy\"],\n        \"total_probes\": total_count,\n        \"latency_p50_ms\": round(p50, 1),\n        \"latency_p99_ms\": round(p99, 1),\n        \"probe_details\": individual_results,\n        \"status\": \"healthy\" if health_score >= 80 else (\n            \"degraded\" if health_score >= 50 else \"critical\"\n        ),\n    }\n\n\n# ── 3. Automatic Failover ────────────────────────────────────────────────────\n\nclass FailoverManager:\n    \"\"\"Automatic failover between a primary and backup agent.\n\n    Monitors the primary agent's health using HealthChecker. When the\n    primary fails consecutive health probes, the manager switches all\n    traffic to the backup agent.  When the primary recovers, traffic\n    is gradually shifted back.\n\n    Uses FleetMonitor.collect_agent_metrics to assess each agent's\n    current reputation and FleetMonitor.check_agent_sla to verify\n    SLA compliance before promoting an agent to primary.\n    \"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        primary_id: str,\n        backup_id: str,\n        failure_threshold: int = 3,\n    ):\n        self.api_key = api_key\n        self.primary_id = primary_id\n        self.backup_id = backup_id\n        self.failure_threshold = failure_threshold\n        self._consecutive_failures = 0\n        self._active_agent_id = primary_id\n        self._failover_history: list[dict] = []\n\n        self._primary_checker = HealthChecker(\n            api_key=api_key, agent_id=primary_id,\n        )\n        self._backup_checker = HealthChecker(\n            api_key=api_key, agent_id=backup_id,\n        )\n        self._monitor = FleetMonitor(\n            api_key=api_key, agent_id=primary_id,\n        )\n\n    @property\n    def active_agent(self) -> str:\n        return self._active_agent_id\n\n    def probe_and_failover(self) -> dict:\n        \"\"\"Run a health probe on the active agent. Failover if needed.\n\n        Returns the current state: which agent is active, health probe\n        result, and whether a failover occurred.\n        \"\"\"\n        checker = (\n            self._primary_checker\n            if self._active_agent_id == self.primary_id\n            else self._backup_checker\n        )\n\n        probe = checker.check_tool(\n            tool=\"get_balance\",\n            input_data={\"agent_id\": self._active_agent_id},\n        )\n\n        if probe[\"healthy\"]:\n            self._consecutive_failures = 0\n            return {\n                \"active_agent\": self._active_agent_id,\n                \"healthy\": True,\n                \"failover_occurred\": False,\n                \"probe\": probe,\n            }\n\n        # Probe failed\n        self._consecutive_failures += 1\n\n        if self._consecutive_failures >= self.failure_threshold:\n            return self._execute_failover(reason=f\"consecutive_failures={self._consecutive_failures}\")\n\n        return {\n            \"active_agent\": self._active_agent_id,\n            \"healthy\": False,\n            \"consecutive_failures\": self._consecutive_failures,\n            \"failover_occurred\": False,\n            \"probe\": probe,\n        }\n\n    def _execute_failover(self, reason: str) -> dict:\n        \"\"\"Switch to the other agent.\"\"\"\n        old = self._active_agent_id\n        new = (\n            self.backup_id if old == self.primary_id else self.primary_id\n        )\n\n        # Verify the target is healthy before switching\n        target_checker = (\n            self._backup_checker if new == self.backup_id\n            else self._primary_checker\n        )\n        target_probe = target_checker.check_tool(\n            tool=\"get_balance\",\n            input_data={\"agent_id\": new},\n        )\n\n        # Also check target SLA compliance via FleetMonitor\n        try:\n            sla_check = self._monitor.check_agent_sla(target_agent_id=new)\n        except Exception:\n            sla_check = {\"status\": \"unknown\"}\n\n        # Check target reputation\n        try:\n            metrics = self._monitor.collect_agent_metrics(target_agent_id=new)\n        except Exception:\n            metrics = {}\n\n        if not target_probe[\"healthy\"]:\n            return {\n                \"active_agent\": old,\n                \"failover_occurred\": False,\n                \"reason\": \"backup_also_unhealthy\",\n                \"target_probe\": target_probe,\n            }\n\n        # Execute failover\n        self._active_agent_id = new\n        self._consecutive_failures = 0\n        event = {\n            \"timestamp\": datetime.utcnow().isoformat(),\n            \"from_agent\": old,\n            \"to_agent\": new,\n            \"reason\": reason,\n            \"target_metrics\": metrics,\n            \"sla_check\": sla_check,\n        }\n        self._failover_history.append(event)\n\n        return {\n            \"active_agent\": new,\n            \"failover_occurred\": True,\n            \"previous_agent\": old,\n            \"reason\": reason,\n            \"target_healthy\": target_probe[\"healthy\"],\n            \"event\": event,\n        }\n\n    def get_failover_history(self) -> list[dict]:\n        return list(self._failover_history)\n\n\n# ── 4. Graceful Degradation ──────────────────────────────────────────────────\n\nclass DegradationChain:\n    \"\"\"Tiered fallback chain for graceful degradation.\n\n    When a primary tool call fails (circuit open or error), the chain\n    tries each fallback tier in order:\n\n      Tier 0: Primary tool call (with CircuitBreaker + RetryPolicy)\n      Tier 1: Backup agent for the same tool\n      Tier 2: Cached\u002Fstale response (if available)\n      Tier 3: Static safe default\n\n    Uses CircuitBreaker.execute to wrap each tier's call and\n    RetryPolicy.execute_with_retry for transient error handling.\n    \"\"\"\n\n    def __init__(self, api_key: str, primary_id: str,\n                 backup_id: Optional[str] = None):\n        self.primary_client = ResilientGatewayClient(\n            api_key=api_key, agent_id=primary_id,\n        )\n        self.backup_client = (\n            ResilientGatewayClient(api_key=api_key, agent_id=backup_id)\n            if backup_id else None\n        )\n        self._cache: dict[str, dict] = {}\n        self._cache_timestamps: dict[str, float] = {}\n        self._cache_ttl_seconds = 300  # 5-minute cache\n\n    def execute_with_degradation(\n        self,\n        tool: str,\n        input_data: dict,\n        safe_default: Optional[dict] = None,\n    ) -> dict:\n        \"\"\"Execute a tool call with tiered fallback.\n\n        Returns:\n            A dict with keys \"result\", \"tier\" (0-3), and \"degraded\" (bool).\n        \"\"\"\n        cache_key = f\"{tool}:{json.dumps(input_data, sort_keys=True)}\"\n\n        # Tier 0: Primary agent\n        try:\n            result = self.primary_client.execute(tool, input_data)\n            # Update cache on success\n            self._cache[cache_key] = result\n            self._cache_timestamps[cache_key] = time.time()\n            return {\"result\": result, \"tier\": 0, \"degraded\": False}\n        except Exception:\n            pass\n\n        # Tier 1: Backup agent (if configured)\n        if self.backup_client:\n            try:\n                result = self.backup_client.execute(tool, input_data)\n                self._cache[cache_key] = result\n                self._cache_timestamps[cache_key] = time.time()\n                return {\"result\": result, \"tier\": 1, \"degraded\": True}\n            except Exception:\n                pass\n\n        # Tier 2: Cached response (if fresh enough)\n        if cache_key in self._cache:\n            age = time.time() - self._cache_timestamps.get(cache_key, 0)\n            if age \u003C= self._cache_ttl_seconds:\n                return {\n                    \"result\": self._cache[cache_key],\n                    \"tier\": 2,\n                    \"degraded\": True,\n                    \"cache_age_seconds\": round(age, 1),\n                }\n\n        # Tier 3: Static safe default\n        default = safe_default or {\n            \"status\": \"degraded\",\n            \"message\": f\"Tool '{tool}' is unavailable. Using safe default.\",\n            \"data\": {},\n        }\n        return {\"result\": default, \"tier\": 3, \"degraded\": True}\n\n    def get_degradation_stats(self) -> dict:\n        \"\"\"Return stats on how often each tier was used.\"\"\"\n        primary_stats = self.primary_client.get_call_stats()\n        backup_stats = (\n            self.backup_client.get_call_stats() if self.backup_client else {}\n        )\n        return {\n            \"primary\": primary_stats,\n            \"backup\": backup_stats,\n            \"cache_entries\": len(self._cache),\n            \"primary_circuits\": self.primary_client.get_circuit_states(),\n        }\n\n\n# ── 5. Fleet-Wide Health Dashboard ───────────────────────────────────────────\n\ndef build_fleet_health_dashboard(\n    fleet_agent_ids: list[str],\n) -> dict:\n    \"\"\"Aggregate health, SLA, and anomaly data for an entire fleet.\n\n    Uses FleetMonitor.collect_agent_metrics for per-agent reputation,\n    FleetMonitor.check_agent_sla for SLA compliance, and\n    FleetMonitor.detect_anomalies for fleet-wide anomaly classification.\n    FleetMonitor.calculate_error_budget computes remaining error budget\n    for each agent.\n    \"\"\"\n    monitor = FleetMonitor(\n        api_key=API_KEY,\n        agent_id=AGENT_ID,\n    )\n    checker = HealthChecker(\n        api_key=API_KEY,\n        agent_id=AGENT_ID,\n    )\n\n    agent_reports = []\n    fleet_metrics_for_anomaly = []\n\n    for agent_id in fleet_agent_ids:\n        # Collect reputation metrics\n        try:\n            metrics = monitor.collect_agent_metrics(target_agent_id=agent_id)\n        except Exception:\n            metrics = {\"agent_id\": agent_id, \"trust_score\": 0}\n\n        # Check SLA compliance\n        try:\n            sla = monitor.check_agent_sla(target_agent_id=agent_id)\n        except Exception:\n            sla = {\"compliant\": False}\n\n        # Run a health probe\n        probe = checker.check_tool(\n            tool=\"get_balance\",\n            input_data={\"agent_id\": agent_id},\n        )\n\n        # Calculate error budget (99.5% SLO, 30-day window)\n        error_rate = metrics.get(\"error_rate\", 0.0)\n        error_budget = monitor.calculate_error_budget(\n            target_slo=0.995,\n            current_error_rate=error_rate if isinstance(error_rate, float) else 0.0,\n            remaining_days=30,\n        )\n\n        report = {\n            \"agent_id\": agent_id,\n            \"healthy\": probe[\"healthy\"],\n            \"response_time_ms\": probe.get(\"response_time_ms\", 0),\n            \"trust_score\": metrics.get(\"trust_score\", 0),\n            \"sla_compliant\": sla.get(\"compliant\", False),\n            \"error_budget\": error_budget,\n            \"metrics\": metrics,\n        }\n        agent_reports.append(report)\n\n        # Build fleet_metrics entry for anomaly detection\n        fleet_metrics_for_anomaly.append({\n            \"agent_id\": agent_id,\n            \"error_rate\": error_rate if isinstance(error_rate, float) else 0.0,\n            \"latency_ms\": probe.get(\"response_time_ms\", 0),\n            \"cost_today\": metrics.get(\"cost_today\", 0),\n        })\n\n    # Fleet-wide anomaly detection\n    anomaly_result = monitor.detect_anomalies(fleet_metrics_for_anomaly)\n\n    # Aggregate fleet health\n    healthy_count = sum(1 for r in agent_reports if r[\"healthy\"])\n    sla_compliant = sum(1 for r in agent_reports if r[\"sla_compliant\"])\n    budgets_ok = sum(\n        1 for r in agent_reports\n        if r[\"error_budget\"].get(\"status\") == \"healthy\"\n    )\n\n    return {\n        \"fleet_size\": len(fleet_agent_ids),\n        \"healthy_agents\": healthy_count,\n        \"sla_compliant_agents\": sla_compliant,\n        \"error_budgets_healthy\": budgets_ok,\n        \"fleet_health_pct\": round(\n            healthy_count \u002F max(len(fleet_agent_ids), 1) * 100, 1\n        ),\n        \"anomalies\": anomaly_result,\n        \"agent_reports\": agent_reports,\n        \"status\": (\n            \"healthy\" if healthy_count == len(fleet_agent_ids) else\n            \"degraded\" if healthy_count >= len(fleet_agent_ids) * 0.5 else\n            \"critical\"\n        ),\n    }\n\n\n# ── Main: Run the Full System ────────────────────────────────────────────────\n\nif __name__ == \"__main__\":\n\n    print(\"=\" * 72)\n    print(\"GreenHelix Circuit Breaker & Failover System\")\n    print(\"=\" * 72)\n\n    # Step 1: Health probes\n    print(\"\\n[1\u002F4] Running health probes...\")\n    health = run_health_probes()\n    print(f\"  Health score: {health['health_score_pct']}%\")\n    print(f\"  Status: {health['status']}\")\n    print(f\"  Latency P50: {health['latency_p50_ms']}ms\")\n    print(f\"  Latency P99: {health['latency_p99_ms']}ms\")\n\n    # Step 2: Resilient client with circuit breakers\n    print(\"\\n[2\u002F4] Testing resilient gateway client...\")\n    client = ResilientGatewayClient(\n        api_key=API_KEY,\n        agent_id=AGENT_ID,\n        failure_threshold=5,\n        recovery_timeout=30.0,\n        max_retries=3,\n    )\n\n    # Normal call\n    result = client.execute(\"get_balance\", {\"agent_id\": AGENT_ID})\n    print(f\"  Balance call succeeded: {bool(result)}\")\n\n    # Call with fallback\n    result = client.execute(\n        \"create_escrow\",\n        {\"payer\": AGENT_ID, \"payee\": \"test-payee\", \"amount\": \"10.00\"},\n        fallback=lambda: {\"status\": \"queued\", \"message\": \"Escrow queued\"},\n    )\n    print(f\"  Escrow call result: {result.get('status', 'ok')}\")\n    print(f\"  Circuit states: {json.dumps(client.get_circuit_states(), indent=2)}\")\n\n    # Step 3: Degradation chain\n    print(\"\\n[3\u002F4] Testing degradation chain...\")\n    chain = DegradationChain(\n        api_key=API_KEY,\n        primary_id=AGENT_ID,\n        backup_id=BACKUP_AGENT_ID or None,\n    )\n    degraded_result = chain.execute_with_degradation(\n        \"get_balance\",\n        {\"agent_id\": AGENT_ID},\n        safe_default={\"balance\": \"0\", \"status\": \"default\"},\n    )\n    print(f\"  Tier used: {degraded_result['tier']}\")\n    print(f\"  Degraded: {degraded_result['degraded']}\")\n\n    # Step 4: Fleet health dashboard\n    print(\"\\n[4\u002F4] Building fleet health dashboard...\")\n    fleet = [AGENT_ID]\n    if BACKUP_AGENT_ID:\n        fleet.append(BACKUP_AGENT_ID)\n    dashboard = build_fleet_health_dashboard(fleet)\n    print(f\"  Fleet health: {dashboard['fleet_health_pct']}%\")\n    print(f\"  Status: {dashboard['status']}\")\n    print(f\"  Anomalies: healthy={len(dashboard['anomalies']['healthy'])}, \"\n          f\"warning={len(dashboard['anomalies']['warning'])}, \"\n          f\"critical={len(dashboard['anomalies']['critical'])}\")\n\n    print(\"\\n\" + \"=\" * 72)\n    print(\"System check complete.\")\n    print(\"=\" * 72)\n```\n\n","# The Agent Production Hardening Guide\n\n> **Notice**: This is an educational guide with illustrative code examples.\n> It does not execute code or install dependencies.\n> All examples use the GreenHelix sandbox (https:\u002F\u002Fsandbox.greenhelix.net) which\n> provides 500 free credits — no API key required to get started.\n>\n> **Referenced credentials** (you supply these in your own environment):\n> - `GREENHELIX_API_KEY`: API authentication for GreenHelix gateway (read\u002Fwrite access to purchased API tools only)\n\n\nSeventy-eight percent of enterprises have agent pilots running. Fourteen percent have agents in production. The gap between those two numbers is where careers stall, budgets evaporate, and executives lose faith in the technology. A March 2026 survey by the AI Infrastructure Alliance found that 89% of failed agent-to-production transitions trace back to exactly five gaps: integration brittleness, quality regression, monitoring blindness, ownership ambiguity, and training data drift. Not model quality. Not prompt engineering. Not the framework choice. The five gaps are all operational -- and they are all fixable with known engineering practices that have been adapted for autonomous agent systems. This guide is the 30-day playbook to close those gaps. It starts with a production readiness assessment that quantifies your current state. It builds SLO-driven monitoring, circuit breakers for graceful degradation, cost guardrails that prevent runaway spend, deployment patterns for safe rollouts, multi-agent resilience patterns, and EU AI Act compliance controls -- all wired to the GreenHelix A2A Commerce Gateway's 128 tools. Every chapter ends with working Python code, practical checklists, and decision matrices. By the end of the 30-day sprint in Chapter 8, your agent system will have a quantified go\u002Fno-go scorecard, automated rollback triggers, per-agent cost caps, and a compliance audit trail that satisfies Article 12 record-keeping before the August 2, 2026 deadline.\n1. [The Production Readiness Assessment](#chapter-1-the-production-readiness-assessment)\n2. [SLOs, SLAs, and Error Budgets for Agent Systems](#chapter-2-slos-slas-and-error-budgets-for-agent-systems)\n\n## What You'll Learn\n- Chapter 1: The Production Readiness Assessment\n- Chapter 2: SLOs, SLAs, and Error Budgets for Agent Systems\n- Chapter 3: Circuit Breakers, Retries, and Graceful Degradation\n- Chapter 4: Cost Guardrails and Token Budget Enforcement\n- Chapter 5: Deployment Patterns: Canary, Blue-Green, and Rollback\n- Chapter 6: Multi-Agent Failure Modes and Resilience Patterns\n- Chapter 7: EU AI Act Production Compliance (August 2026 Deadline)\n- Chapter 8: The 30-Day Production Hardening Sprint\n- What to Do Next\n- Circuit Breaker & Failover — Working Implementation\n\n## Full Guide\n\n# The Agent Production Hardening Guide: SLOs, Circuit Breakers, Cost Guardrails & the 30-Day Sprint to Production\n\nSeventy-eight percent of enterprises have agent pilots running. Fourteen percent have agents in production. The gap between those two numbers is where careers stall, budgets evaporate, and executives lose faith in the technology. A March 2026 survey by the AI Infrastructure Alliance found that 89% of failed agent-to-production transitions trace back to exactly five gaps: integration brittleness, quality regression, monitoring blindness, ownership ambiguity, and training data drift. Not model quality. Not prompt engineering. Not the framework choice. The five gaps are all operational -- and they are all fixable with known engineering practices that have been adapted for autonomous agent systems. This guide is the 30-day playbook to close those gaps. It starts with a production readiness assessment that quantifies your current state. It builds SLO-driven monitoring, circuit breakers for graceful degradation, cost guardrails that prevent runaway spend, deployment patterns for safe rollouts, multi-agent resilience patterns, and EU AI Act compliance controls -- all wired to the GreenHelix A2A Commerce Gateway's 128 tools. Every chapter ends with working Python code, practical checklists, and decision matrices. By the end of the 30-day sprint in Chapter 8, your agent system will have a quantified go\u002Fno-go scorecard, automated rollback triggers, per-agent cost caps, and a compliance audit trail that satisfies Article 12 record-keeping before the August 2, 2026 deadline.\n\n---\n\n## Table of Contents\n\n1. [The Production Readiness Assessment](#chapter-1-the-production-readiness-assessment)\n2. [SLOs, SLAs, and Error Budgets for Agent Systems](#chapter-2-slos-slas-and-error-budgets-for-agent-systems)\n3. [Circuit Breakers, Retries, and Graceful Degradation](#chapter-3-circuit-breakers-retries-and-graceful-degradation)\n4. [Cost Guardrails and Token Budget Enforcement](#chapter-4-cost-guardrails-and-token-budget-enforcement)\n5. [Deployment Patterns: Canary, Blue-Green, and Rollback](#chapter-5-deployment-patterns-canary-blue-green-and-rollback)\n6. [Multi-Agent Failure Modes and Resilience Patterns](#chapter-6-multi-agent-failure-modes-and-resilience-patterns)\n7. [EU AI Act Production Compliance (August 2026 Deadline)](#chapter-7-eu-ai-act-production-compliance-august-2026-deadline)\n8. [The 30-Day Production Hardening Sprint](#chapter-8-the-30-day-production-hardening-sprint)\n\n---\n\n## Chapter 1: The Production Readiness Assessment\n\n### The 5-Gap Framework\n\nEvery failed pilot-to-production transition in the AI Infrastructure Alliance dataset traces back to one or more of five gaps. Understanding these gaps is the first step because you cannot fix what you have not measured, and most teams are fixing the wrong thing -- they are tuning prompts when the real problem is that nobody owns the agent's SLA.\n\n**Gap 1: Integration Brittleness.** The agent works against a sandbox API but has never been tested against production traffic patterns, rate limits, timeout behaviors, or error responses. The integration layer assumes happy-path responses and breaks on the first 429, 503, or malformed payload. This gap causes 34% of production failures.\n\n**Gap 2: Quality Regression.** The agent's output quality was validated once during the pilot and never again. There is no automated quality gate, no regression suite, no way to detect that a model update or prompt change has degraded task completion rates. This gap causes 23% of production failures.\n\n**Gap 3: Monitoring Blindness.** The agent runs in production but nobody knows if it is healthy. There are no SLOs, no latency tracking, no cost dashboards, no alerting. The first signal of a problem is a customer complaint or a surprise invoice. This gap causes 19% of production failures.\n\n**Gap 4: Ownership Ambiguity.** No single person or team owns the agent in production. The ML team built the model. The platform team deployed it. The product team defined the requirements. When it breaks at 3 AM, nobody's pager goes off because nobody agreed to carry the pager. This gap causes 8% of production failures.\n\n**Gap 5: Training Data Drift.** The agent was trained or fine-tuned on data that no longer represents the production distribution. Tool schemas have changed, counterparty behavior has shifted, or the business domain has evolved since the training data was collected. The agent is optimizing for a world that no longer exists. This gap causes 5% of production failures.\n\n### The 40-Question Production Readiness Checklist\n\nScore each question 0 (not done), 1 (partially done), or 2 (fully done). Maximum score is 80.\n\n#### Integration (Questions 1-8)\n\n| # | Question | Score |\n|---|----------|-------|\n| 1 | All API calls use retry with exponential backoff and jitter | 0 \u002F 1 \u002F 2 |\n| 2 | Circuit breakers are implemented for every external dependency | 0 \u002F 1 \u002F 2 |\n| 3 | Timeout values are explicitly configured (not default) for every HTTP call | 0 \u002F 1 \u002F 2 |\n| 4 | The agent handles 429 (rate limit), 503 (unavailable), and 504 (timeout) gracefully | 0 \u002F 1 \u002F 2 |\n| 5 | Integration tests run against a staging environment with production-like traffic | 0 \u002F 1 \u002F 2 |\n| 6 | Webhook endpoints have been load-tested at 10x expected volume | 0 \u002F 1 \u002F 2 |\n| 7 | All API credentials are rotated on a schedule and never hardcoded | 0 \u002F 1 \u002F 2 |\n| 8 | Fallback behavior is defined and tested for every external service | 0 \u002F 1 \u002F 2 |\n\n#### Quality (Questions 9-16)\n\n| # | Question | Score |\n|---|----------|-------|\n| 9 | Task completion rate is measured and baselined | 0 \u002F 1 \u002F 2 |\n| 10 | Automated regression tests run on every deployment | 0 \u002F 1 \u002F 2 |\n| 11 | Output quality is scored by an automated evaluator (not just human spot-checks) | 0 \u002F 1 \u002F 2 |\n| 12 | Model version and prompt version are tracked in deployment metadata | 0 \u002F 1 \u002F 2 |\n| 13 | A\u002FB testing infrastructure exists for prompt and model changes | 0 \u002F 1 \u002F 2 |\n| 14 | Edge cases from production are captured and added to the test suite | 0 \u002F 1 \u002F 2 |\n| 15 | The agent's failure modes are documented with expected frequency and impact | 0 \u002F 1 \u002F 2 |\n| 16 | Quality SLOs are defined and measured (not just \"it works\") | 0 \u002F 1 \u002F 2 |\n\n#### Monitoring (Questions 17-24)\n\n| # | Question | Score |\n|---|----------|-------|\n| 17 | SLOs are defined for success rate, latency P99, and cost-per-task | 0 \u002F 1 \u002F 2 |\n| 18 | SLO burn rate is tracked and alerts fire before the error budget is exhausted | 0 \u002F 1 \u002F 2 |\n| 19 | Cost dashboards show per-agent, per-workflow, and per-tool-category spend | 0 \u002F 1 \u002F 2 |\n| 20 | Latency is tracked at the tool-call level, not just end-to-end | 0 \u002F 1 \u002F 2 |\n| 21 | Anomaly detection is configured for cost and error rate spikes | 0 \u002F 1 \u002F 2 |\n| 22 | Logs are structured (JSON), centralized, and retained for 90+ days | 0 \u002F 1 \u002F 2 |\n| 23 | Distributed tracing connects agent decisions to downstream tool calls | 0 \u002F 1 \u002F 2 |\n| 24 | Health check endpoints exist and are polled by an external monitor | 0 \u002F 1 \u002F 2 |\n\n#### Ownership (Questions 25-32)\n\n| # | Question | Score |\n|---|----------|-------|\n| 25 | A named individual or team owns the agent's production SLA | 0 \u002F 1 \u002F 2 |\n| 26 | On-call rotation is established with documented escalation paths | 0 \u002F 1 \u002F 2 |\n| 27 | Incident runbooks exist for the top 5 failure modes | 0 \u002F 1 \u002F 2 |\n| 28 | Change management process is defined (who can deploy, when, with what approval) | 0 \u002F 1 \u002F 2 |\n| 29 | Capacity planning accounts for traffic growth over the next 6 months | 0 \u002F 1 \u002F 2 |\n| 30 | Dependency owners are identified for every external service | 0 \u002F 1 \u002F 2 |\n| 31 | Post-mortem process is established and post-mortems are blameless | 0 \u002F 1 \u002F 2 |\n| 32 | The team has practiced a tabletop exercise for the agent's worst failure mode | 0 \u002F 1 \u002F 2 |\n\n#### Training Data (Questions 33-40)\n\n| # | Question | Score |\n|---|----------|-------|\n| 33 | Training\u002Fevaluation data is versioned alongside code | 0 \u002F 1 \u002F 2 |\n| 34 | Data freshness is monitored and alerts fire when data is stale | 0 \u002F 1 \u002F 2 |\n| 35 | Production inputs are sampled and compared to training distribution | 0 \u002F 1 \u002F 2 |\n| 36 | Tool schema changes trigger re-evaluation of the agent's few-shot examples | 0 \u002F 1 \u002F 2 |\n| 37 | Feedback loops exist: production failures are routed back to training data | 0 \u002F 1 \u002F 2 |\n| 38 | Data governance controls are in place (PII handling, retention, access) | 0 \u002F 1 \u002F 2 |\n| 39 | Evaluation datasets cover adversarial and edge-case inputs | 0 \u002F 1 \u002F 2 |\n| 40 | A data quality pipeline validates training data before model updates | 0 \u002F 1 \u002F 2 |\n\n### Scoring and Readiness Tiers\n\n| Score | Tier | Verdict |\n|-------|------|---------|\n| 0-20 | Red: Not Ready | Do not proceed to production. Major gaps in 3+ categories. |\n| 21-40 | Orange: High Risk | Production is possible but expect incidents within 30 days. |\n| 41-60 | Yellow: Conditional | Production-ready with known risks. Mitigations must be documented. |\n| 61-72 | Green: Ready | Production-ready. Minor gaps tracked as tech debt. |\n| 73-80 | Blue: Hardened | Exceeds production requirements. Ready for regulated workloads. |\n\n### Automating the Assessment with GreenHelix\n\nYou do not need to score this checklist manually. Several questions can be answered programmatically by querying your GreenHelix agent's current state -- checking SLA configuration, budget caps, webhook registrations, and trust scores.\n\n```python\nimport requests\nimport json\nfrom dataclasses import dataclass, field\nfrom typing import Optional\n\nBASE_URL = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\ndef call_tool(api_key: str, tool: str, input_data: dict) -> dict:\n    \"\"\"Execute a GreenHelix tool via the unified endpoint.\"\"\"\n    resp = requests.post(\n        f\"{BASE_URL}\u002Fv1\",\n        headers={\"Authorization\": f\"Bearer {api_key}\"},\n        json={\"tool\": tool, \"input\": input_data},\n        timeout=30,\n    )\n    resp.raise_for_status()\n    return resp.json()\n\n\n@dataclass\nclass ReadinessScore:\n    integration: int = 0\n    quality: int = 0\n    monitoring: int = 0\n    ownership: int = 0\n    training_data: int = 0\n\n    @property\n    def total(self) -> int:\n        return (self.integration + self.quality + self.monitoring\n                + self.ownership + self.training_data)\n\n    @property\n    def tier(self) -> str:\n        t = self.total\n        if t \u003C= 20: return \"Red: Not Ready\"\n        if t \u003C= 40: return \"Orange: High Risk\"\n        if t \u003C= 60: return \"Yellow: Conditional\"\n        if t \u003C= 72: return \"Green: Ready\"\n        return \"Blue: Hardened\"\n\n\nclass ProductionReadinessAssessor:\n    \"\"\"Automated production readiness assessment using GreenHelix tools.\n\n    Checks SLA configuration, budget caps, webhook registrations,\n    trust scores, and identity verification to score monitoring,\n    ownership, and integration readiness programmatically.\n    \"\"\"\n\n    def __init__(self, api_key: str, agent_id: str):\n        self.api_key = api_key\n        self.agent_id = agent_id\n\n    def _call(self, tool: str, input_data: dict) -> dict:\n        return call_tool(self.api_key, tool, input_data)\n\n    def check_sla_exists(self) -> bool:\n        \"\"\"Q17: Are SLOs defined?\"\"\"\n        try:\n            result = self._call(\"get_sla_status\", {\n                \"agent_id\": self.agent_id,\n            })\n            return result.get(\"status\") == \"success\"\n        except Exception:\n            return False\n\n    def check_budget_cap(self) -> bool:\n        \"\"\"Q19: Are cost dashboards and caps configured?\"\"\"\n        try:\n            result = self._call(\"get_balance\", {\n                \"agent_id\": self.agent_id,\n            })\n            # Budget cap exists if balance response includes limits\n            return \"daily_limit\" in result or \"monthly_limit\" in result\n        except Exception:\n            return False\n\n    def check_webhook_registered(self) -> bool:\n        \"\"\"Q6\u002FQ21: Are webhook endpoints registered for alerting?\"\"\"\n        try:\n            result = self._call(\"list_webhooks\", {\n                \"agent_id\": self.agent_id,\n            })\n            webhooks = result.get(\"webhooks\", [])\n            return len(webhooks) > 0\n        except Exception:\n            return False\n\n    def check_trust_score(self) -> Optional[float]:\n        \"\"\"Q15: Is the agent's trust profile established?\"\"\"\n        try:\n            result = self._call(\"get_trust_score\", {\n                \"agent_id\": self.agent_id,\n            })\n            return result.get(\"score\")\n        except Exception:\n            return None\n\n    def check_identity_verified(self) -> bool:\n        \"\"\"Q7: Is the agent's identity verified?\"\"\"\n        try:\n            result = self._call(\"get_verified_claims\", {\n                \"agent_id\": self.agent_id,\n            })\n            claims = result.get(\"claims\", [])\n            return len(claims) > 0\n        except Exception:\n            return False\n\n    def run_automated_checks(self) -> dict:\n        \"\"\"Run all automated checks and return results.\"\"\"\n        return {\n            \"sla_configured\": self.check_sla_exists(),\n            \"budget_cap_set\": self.check_budget_cap(),\n            \"webhooks_registered\": self.check_webhook_registered(),\n            \"trust_score\": self.check_trust_score(),\n            \"identity_verified\": self.check_identity_verified(),\n        }\n\n    def score_automated(self) -> ReadinessScore:\n        \"\"\"Score the automated checks. Manual questions still need human input.\"\"\"\n        checks = self.run_automated_checks()\n        score = ReadinessScore()\n\n        # Monitoring: SLA + budget + webhooks = up to 6 of 16 points\n        if checks[\"sla_configured\"]:\n            score.monitoring += 2  # Q17\n        if checks[\"budget_cap_set\"]:\n            score.monitoring += 2  # Q19\n        if checks[\"webhooks_registered\"]:\n            score.monitoring += 2  # Q21\n\n        # Integration: identity verification = up to 2 of 16 points\n        if checks[\"identity_verified\"]:\n            score.integration += 2  # Q7\n\n        # Quality: trust score > 0.7 = 2 of 16 points\n        ts = checks[\"trust_score\"]\n        if ts is not None and ts > 0.7:\n            score.quality += 2  # Q15\n\n        return score\n\n\n# Usage\nif __name__ == \"__main__\":\n    import os\n    assessor = ProductionReadinessAssessor(\n        api_key=os.environ[\"GREENHELIX_API_KEY\"],\n        agent_id=\"commerce-agent-prod-01\",\n    )\n    score = assessor.score_automated()\n    checks = assessor.run_automated_checks()\n    print(f\"Automated readiness score: {score.total}\u002F80 (partial)\")\n    print(f\"Tier: {score.tier}\")\n    print(f\"Checks: {json.dumps(checks, indent=2)}\")\n    print(\"Complete the remaining 35 questions manually for full score.\")\n```\n\n> **Key Takeaways**\n>\n> - 78% of enterprises have agent pilots; only 14% reach production. The gap is operational, not technical.\n> - 89% of failures trace to 5 measurable gaps: integration, quality, monitoring, ownership, training data.\n> - The 40-question checklist produces a quantified readiness score (0-80) with five tiers from Red (not ready) to Blue (hardened).\n> - Several checklist items can be scored automatically by querying GreenHelix SLA, billing, webhook, trust, and identity tools.\n> - Run the assessment before starting the 30-day sprint in Chapter 8 to establish your baseline.\n\n---\n\n## Chapter 2: SLOs, SLAs, and Error Budgets for Agent Systems\n\n### Why \"Uptime\" Is Wrong for Agents\n\nTraditional SRE monitors uptime: is the service responding to health checks? For agents, uptime is a necessary but wildly insufficient metric. An agent can be \"up\" -- responding to requests, returning 200 status codes -- while failing to complete tasks, producing low-quality outputs, or burning through budget at 10x the expected rate. A commerce agent that responds to every request but releases escrows to the wrong counterparty 5% of the time is 100% \"up\" and catastrophically broken.\n\nAgent systems need three SLOs that together capture the full definition of \"working.\"\n\n**Task Completion SLO.** The percentage of tasks the agent completes successfully within a defined window. This is the primary SLO. A task is \"complete\" when the business outcome is achieved -- the escrow is released, the listing is published, the dispute is resolved -- not when the API call returns 200.\n\n**Latency P99 SLO.** The 99th percentile end-to-end latency for a task, measured from request receipt to final outcome confirmation. P99, not P50, because agent latency distributions have heavy tails -- a single LLM retry or tool timeout can push one request to 30 seconds while the median is 2 seconds. The P50 masks the pain.\n\n**Cost-per-Task SLO.** The maximum acceptable cost to complete a single task. This is measured in dollars, not tokens, because the cost includes LLM inference, tool calls, gateway fees, and any downstream API costs. A cost-per-task SLO of $0.12 means any task that costs more than $0.12 has breached the SLO, even if it completed successfully and quickly.\n\n### Error Budgets: Spending Wisely\n\nAn error budget is the complement of the SLO. If your task completion SLO is 99.5%, your error budget is 0.5% -- you can afford 5 failures per 1,000 tasks. Error budgets solve the eternal conflict between \"ship faster\" and \"break nothing.\" When the error budget has remaining capacity, the team ships aggressively. When the error budget is nearly exhausted, the team freezes deployments and focuses on reliability.\n\nFor agent systems, you need three independent error budgets -- one for each SLO. A cost overrun does not consume the completion error budget. A latency spike does not consume the cost budget. This prevents a single bad dimension from blocking all progress.\n\n| SLO | Target | Error Budget (30-day) | Burn Rate Alert |\n|-----|--------|-----------------------|-----------------|\n| Task Completion | 99.5% | 0.5% = 5 failures \u002F 1,000 tasks | >2x in 1 hour |\n| Latency P99 | \u003C 5 seconds | 1% of tasks > 5s allowed | >3x in 30 min |\n| Cost-per-Task | \u003C $0.15 | 2% of tasks > $0.15 allowed | >5x in 15 min |\n\n### Wiring SLA Monitoring with GreenHelix\n\nThe GreenHelix gateway provides three SLA tools that map directly to this SLO framework: `create_sla` defines the SLA parameters, `check_sla_compliance` evaluates current compliance, and `get_sla_status` retrieves the SLA's running state. Combined with `register_webhook`, you can build fully automated SLO monitoring with burn-rate alerting.\n\n```python\nimport requests\nimport time\nimport json\nimport threading\nfrom dataclasses import dataclass, field\nfrom typing import Optional, List, Callable\nfrom datetime import datetime, timedelta\n\nBASE_URL = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n\ndef call_tool(api_key: str, tool: str, input_data: dict) -> dict:\n    resp = requests.post(\n        f\"{BASE_URL}\u002Fv1\",\n        headers={\"Authorization\": f\"Bearer {api_key}\"},\n        json={\"tool\": tool, \"input\": input_data},\n        timeout=30,\n    )\n    resp.raise_for_status()\n    return resp.json()\n\n\n@dataclass\nclass SLODefinition:\n    name: str\n    target: float       # e.g., 0.995 for 99.5%\n    window_days: int    # rolling window\n    metric: str         # \"completion_rate\", \"latency_p99\", \"cost_per_task\"\n    threshold: float    # absolute threshold (seconds for latency, dollars for cost)\n\n\n@dataclass\nclass BurnRateAlert:\n    slo_name: str\n    multiplier: float   # e.g., 2.0 means burning 2x the allowed rate\n    window_minutes: int\n    triggered_at: Optional[datetime] = None\n\n\nclass AgentSLOMonitor:\n    \"\"\"Tracks SLO burn rate across three dimensions and triggers\n    alerts via GreenHelix webhooks when burn rate exceeds thresholds.\n\n    Wire this into your agent's main loop or run it as a sidecar.\n    \"\"\"\n\n    def __init__(self, api_key: str, agent_id: str):\n        self.api_key = api_key\n        self.agent_id = agent_id\n        self.slos: List[SLODefinition] = []\n        self.burn_rate_alerts: List[BurnRateAlert] = []\n        self._alert_callbacks: List[Callable] = []\n        self._task_log: List[dict] = []\n\n    def _call(self, tool: str, input_data: dict) -> dict:\n        return call_tool(self.api_key, tool, input_data)\n\n    def define_slo(self, slo: SLODefinition) -> dict:\n        \"\"\"Register an SLO with GreenHelix and set up compliance tracking.\"\"\"\n        result = self._call(\"create_sla\", {\n            \"agent_id\": self.agent_id,\n            \"sla_name\": slo.name,\n            \"metric\": slo.metric,\n            \"target\": slo.target,\n            \"window_days\": slo.window_days,\n            \"threshold\": slo.threshold,\n        })\n        self.slos.append(slo)\n        return result\n\n    def register_alert_webhook(self, webhook_url: str, threshold_pct: int = 80) -> dict:\n        \"\"\"Register a webhook that fires when error budget reaches threshold.\"\"\"\n        return self._call(\"register_webhook\", {\n            \"agent_id\": self.agent_id,\n            \"url\": webhook_url,\n            \"events\": [\"sla.breach\", \"sla.warning\", \"budget.threshold\"],\n            \"config\": {\"threshold_pct\": threshold_pct},\n        })\n\n    def record_task(self, task_id: str, success: bool, latency_ms: float,\n                    cost_usd: float):\n        \"\"\"Record a completed task for local burn-rate calculation.\"\"\"\n        self._task_log.append({\n            \"task_id\": task_id,\n            \"success\": success,\n            \"latency_ms\": latency_ms,\n            \"cost_usd\": cost_usd,\n            \"timestamp\": datetime.utcnow(),\n        })\n        self._check_burn_rates()\n\n    def _tasks_in_window(self, minutes: int) -> List[dict]:\n        cutoff = datetime.utcnow() - timedelta(minutes=minutes)\n        return [t for t in self._task_log if t[\"timestamp\"] >= cutoff]\n\n    def _check_burn_rates(self):\n        \"\"\"Check if any SLO is burning faster than its error budget allows.\"\"\"\n        for slo in self.slos:\n            if slo.metric == \"completion_rate\":\n                self._check_completion_burn(slo)\n            elif slo.metric == \"latency_p99\":\n                self._check_latency_burn(slo)\n            elif slo.metric == \"cost_per_task\":\n                self._check_cost_burn(slo)\n\n    def _check_completion_burn(self, slo: SLODefinition):\n        window_tasks = self._tasks_in_window(60)  # 1-hour window\n        if len(window_tasks) \u003C 10:\n            return  # Not enough data\n        failures = sum(1 for t in window_tasks if not t[\"success\"])\n        failure_rate = failures \u002F len(window_tasks)\n        allowed_rate = 1.0 - slo.target  # e.g., 0.005 for 99.5%\n        if allowed_rate > 0:\n            burn_multiplier = failure_rate \u002F allowed_rate\n            if burn_multiplier > 2.0:\n                self._fire_alert(BurnRateAlert(\n                    slo_name=slo.name,\n                    multiplier=burn_multiplier,\n                    window_minutes=60,\n                    triggered_at=datetime.utcnow(),\n                ))\n\n    def _check_latency_burn(self, slo: SLODefinition):\n        window_tasks = self._tasks_in_window(30)  # 30-min window\n        if len(window_tasks) \u003C 10:\n            return\n        threshold_ms = slo.threshold * 1000\n        breaches = sum(1 for t in window_tasks\n                       if t[\"latency_ms\"] > threshold_ms)\n        breach_rate = breaches \u002F len(window_tasks)\n        allowed_rate = 0.01  # 1% allowed\n        if allowed_rate > 0:\n            burn_multiplier = breach_rate \u002F allowed_rate\n            if burn_multiplier > 3.0:\n                self._fire_alert(BurnRateAlert(\n                    slo_name=slo.name,\n                    multiplier=burn_multiplier,\n                    window_minutes=30,\n                    triggered_at=datetime.utcnow(),\n                ))\n\n    def _check_cost_burn(self, slo: SLODefinition):\n        window_tasks = self._tasks_in_window(15)  # 15-min window\n        if len(window_tasks) \u003C 5:\n            return\n        breaches = sum(1 for t in window_tasks\n                       if t[\"cost_usd\"] > slo.threshold)\n        breach_rate = breaches \u002F len(window_tasks)\n        allowed_rate = 0.02  # 2% allowed\n        if allowed_rate > 0:\n            burn_multiplier = breach_rate \u002F allowed_rate\n            if burn_multiplier > 5.0:\n                self._fire_alert(BurnRateAlert(\n                    slo_name=slo.name,\n                    multiplier=burn_multiplier,\n                    window_minutes=15,\n                    triggered_at=datetime.utcnow(),\n                ))\n\n    def _fire_alert(self, alert: BurnRateAlert):\n        \"\"\"Publish burn-rate alert to GreenHelix event bus.\"\"\"\n        self.burn_rate_alerts.append(alert)\n        self._call(\"publish_event\", {\n            \"agent_id\": self.agent_id,\n            \"event_type\": \"slo.burn_rate_alert\",\n            \"payload\": {\n                \"slo_name\": alert.slo_name,\n                \"burn_multiplier\": round(alert.multiplier, 2),\n                \"window_minutes\": alert.window_minutes,\n                \"triggered_at\": alert.triggered_at.isoformat(),\n            },\n        })\n        for cb in self._alert_callbacks:\n            cb(alert)\n\n    def check_compliance(self) -> dict:\n        \"\"\"Check current SLA compliance via GreenHelix.\"\"\"\n        return self._call(\"check_sla_compliance\", {\n            \"agent_id\": self.agent_id,\n        })\n\n    def get_status(self) -> dict:\n        \"\"\"Get current SLA status including error budget remaining.\"\"\"\n        return self._call(\"get_sla_status\", {\n            \"agent_id\": self.agent_id,\n        })\n\n    def on_alert(self, callback: Callable):\n        \"\"\"Register a callback for burn-rate alerts.\"\"\"\n        self._alert_callbacks.append(callback)\n\n\n# Usage: set up three SLOs and a webhook\nif __name__ == \"__main__\":\n    import os\n    monitor = AgentSLOMonitor(\n        api_key=os.environ[\"GREENHELIX_API_KEY\"],\n        agent_id=\"commerce-agent-prod-01\",\n    )\n\n    # Define three SLOs\n    monitor.define_slo(SLODefinition(\n        name=\"task-completion\", target=0.995,\n        window_days=30, metric=\"completion_rate\", threshold=0.995,\n    ))\n    monitor.define_slo(SLODefinition(\n        name=\"latency-p99\", target=0.99,\n        window_days=30, metric=\"latency_p99\", threshold=5.0,\n    ))\n    monitor.define_slo(SLODefinition(\n        name=\"cost-per-task\", target=0.98,\n        window_days=30, metric=\"cost_per_task\", threshold=0.15,\n    ))\n\n    # Register webhook for 80% error budget consumption\n    monitor.register_alert_webhook(\n        \"https:\u002F\u002Fyour-app.example.com\u002Falerts\u002Fslo\",\n        threshold_pct=80,\n    )\n\n    # In your agent loop, record every task:\n    # monitor.record_task(\"task-123\", success=True, latency_ms=1200, cost_usd=0.08)\n    print(\"SLO monitoring configured. Three SLOs active.\")\n```\n\n> **Key Takeaways**\n>\n> - Traditional \"uptime\" monitoring is insufficient for agents. Use three SLOs: task completion rate, latency P99, and cost-per-task.\n> - Error budgets convert SLOs into actionable deployment gates: ship when budget allows, freeze when it does not.\n> - Burn-rate alerts catch problems before the error budget is exhausted, giving you hours instead of minutes to respond.\n> - GreenHelix `create_sla`, `check_sla_compliance`, and `get_sla_status` provide the server-side SLA tracking; the `AgentSLOMonitor` adds client-side burn-rate calculation and event publishing.\n> - See P9 (Testing & Observability) for SLO-driven regression tests and P12 (Incident Response) for SLO breach runbooks.\n\n---\n\n## Chapter 3: Circuit Breakers, Retries, and Graceful Degradation\n\n### Why Agents Need Circuit Breakers\n\nA traditional microservice retries a failed HTTP call three times and returns an error. An agent retries a failed tool call, but its retry logic is embedded in the LLM's reasoning loop -- the model sees the error, decides to try again, and generates another tool call. Without a circuit breaker, the agent will retry until its context window overflows or its budget runs out. Worse, in a multi-agent system, one agent's retry storm becomes backpressure on every downstream service it touches, causing cascading failures.\n\nCircuit breakers solve this by short-circuiting failed calls after a threshold is reached. When the circuit is open, calls fail immediately without hitting the downstream service, giving it time to recover. When a probe succeeds, the circuit closes and normal traffic resumes.\n\n### The Three-Layer Circuit Breaker\n\nAgent systems need circuit breakers at three layers, not one.\n\n**Layer 1: LLM Call Circuit Breaker.** Protects against LLM provider outages and rate limits. When the LLM returns 5 consecutive errors or latency exceeds 30 seconds, the circuit opens. Fallback: smaller model, cached response, or queue for human review.\n\n**Layer 2: Tool Invocation Circuit Breaker.** Protects against individual tool failures. Each tool has its own circuit breaker. When `create_escrow` fails 3 times in 60 seconds, the circuit opens for that tool only. Other tools remain available.\n\n**Layer 3: Inter-Agent Circuit Breaker.** Protects against counterparty agent failures in multi-agent workflows. When Agent B stops responding to Agent A's messages, the circuit opens and Agent A routes to an alternative provider or queues the work.\n\n### Exponential Backoff with Jitter\n\nRetries without backoff create thundering herds. Retries with fixed backoff create synchronized retry waves. Exponential backoff with full jitter is the only retry strategy that avoids both problems.\n\n```\ndelay = min(cap, base * 2^attempt) * random(0, 1)\n```\n\nFor agent systems, use `base=0.5s`, `cap=30s`, and add a per-agent random offset to prevent fleet-wide synchronization.\n\n### The Fallback Chain\n\nWhen a circuit is open, the agent needs somewhere to fall back. The fallback chain for LLM calls follows a degradation hierarchy:\n\n```\nFrontier Model (GPT-4o, Claude Opus)\n       |\n       v  [circuit open]\nSmaller Model (GPT-4o-mini, Claude Haiku)\n       |\n       v  [circuit open]\nCached Response (last known good for this input class)\n       |\n       v  [cache miss]\nHuman Escalation (queue task for human review)\n```\n\nFor tool calls, the fallback is simpler: return a structured error to the LLM and let it adjust its plan. The circuit breaker's job is not to hide the failure -- it is to prevent the failure from cascading.\n\n```python\nimport requests\nimport time\nimport json\nimport random\nimport threading\nfrom enum import Enum\nfrom dataclasses import dataclass, field\nfrom typing import Optional, Callable, Any, Dict\nfrom datetime import datetime, timedelta\n\nBASE_URL = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n\ndef call_tool(api_key: str, tool: str, input_data: dict) -> dict:\n    resp = requests.post(\n        f\"{BASE_URL}\u002Fv1\",\n        headers={\"Authorization\": f\"Bearer {api_key}\"},\n        json={\"tool\": tool, \"input\": input_data},\n        timeout=30,\n    )\n    resp.raise_for_status()\n    return resp.json()\n\n\nclass CircuitState(Enum):\n    CLOSED = \"closed\"      # Normal operation\n    OPEN = \"open\"          # Failing, reject calls\n    HALF_OPEN = \"half_open\"  # Testing recovery\n\n\n@dataclass\nclass CircuitBreaker:\n    \"\"\"Circuit breaker for a single dependency (tool, LLM, agent).\n\n    Tracks failures, opens the circuit after threshold, and publishes\n    state changes to GreenHelix Events for fleet-wide visibility.\n    \"\"\"\n    name: str\n    failure_threshold: int = 5\n    recovery_timeout_s: float = 60.0\n    half_open_max_calls: int = 1\n\n    state: CircuitState = field(default=CircuitState.CLOSED)\n    failure_count: int = 0\n    success_count: int = 0\n    last_failure_time: Optional[datetime] = None\n    half_open_calls: int = 0\n    _lock: threading.Lock = field(default_factory=threading.Lock)\n\n    def can_execute(self) -> bool:\n        with self._lock:\n            if self.state == CircuitState.CLOSED:\n                return True\n            if self.state == CircuitState.OPEN:\n                if (self.last_failure_time and\n                    datetime.utcnow() - self.last_failure_time\n                        > timedelta(seconds=self.recovery_timeout_s)):\n                    self.state = CircuitState.HALF_OPEN\n                    self.half_open_calls = 0\n                    return True\n                return False\n            if self.state == CircuitState.HALF_OPEN:\n                return self.half_open_calls \u003C self.half_open_max_calls\n            return False\n\n    def record_success(self):\n        with self._lock:\n            if self.state == CircuitState.HALF_OPEN:\n                self.success_count += 1\n                self.state = CircuitState.CLOSED\n                self.failure_count = 0\n            self.success_count += 1\n\n    def record_failure(self):\n        with self._lock:\n            self.failure_count += 1\n            self.last_failure_time = datetime.utcnow()\n            if self.state == CircuitState.HALF_OPEN:\n                self.state = CircuitState.OPEN\n            elif self.failure_count >= self.failure_threshold:\n                self.state = CircuitState.OPEN\n\n\nclass ResilientToolCaller:\n    \"\"\"Wraps GreenHelix tool calls with per-tool circuit breakers,\n    exponential backoff with jitter, and state publishing.\n\n    Each tool gets its own circuit breaker. State changes are published\n    to GreenHelix Events so other agents and dashboards can see which\n    tools are degraded.\n    \"\"\"\n\n    def __init__(self, api_key: str, agent_id: str,\n                 failure_threshold: int = 5,\n                 max_retries: int = 3,\n                 backoff_base: float = 0.5,\n                 backoff_cap: float = 30.0):\n        self.api_key = api_key\n        self.agent_id = agent_id\n        self.max_retries = max_retries\n        self.backoff_base = backoff_base\n        self.backoff_cap = backoff_cap\n        self._breakers: Dict[str, CircuitBreaker] = {}\n        self._failure_threshold = failure_threshold\n\n    def _get_breaker(self, tool: str) -> CircuitBreaker:\n        if tool not in self._breakers:\n            self._breakers[tool] = CircuitBreaker(\n                name=tool,\n                failure_threshold=self._failure_threshold,\n            )\n        return self._breakers[tool]\n\n    def _backoff_delay(self, attempt: int) -> float:\n        \"\"\"Exponential backoff with full jitter.\"\"\"\n        exp_delay = min(self.backoff_cap,\n                        self.backoff_base * (2 ** attempt))\n        return exp_delay * random.random()\n\n    def _publish_state_change(self, tool: str, state: CircuitState):\n        \"\"\"Publish circuit breaker state change to GreenHelix Events.\"\"\"\n        try:\n            call_tool(self.api_key, \"publish_event\", {\n                \"agent_id\": self.agent_id,\n                \"event_type\": \"circuit_breaker.state_change\",\n                \"payload\": {\n                    \"tool\": tool,\n                    \"new_state\": state.value,\n                    \"timestamp\": datetime.utcnow().isoformat(),\n                },\n            })\n        except Exception:\n            pass  # Event publishing should never block tool calls\n\n    def execute(self, tool: str, input_data: dict,\n                fallback: Optional[Callable] = None) -> dict:\n        \"\"\"Execute a tool call with circuit breaker and retry logic.\n\n        Args:\n            tool: GreenHelix tool name\n            input_data: Tool input parameters\n            fallback: Optional callable returning a fallback response\n\n        Returns:\n            Tool response dict\n\n        Raises:\n            CircuitOpenError: If circuit is open and no fallback provided\n            Exception: If all retries exhausted and no fallback provided\n        \"\"\"\n        breaker = self._get_breaker(tool)\n\n        if not breaker.can_execute():\n            if breaker.state == CircuitState.OPEN:\n                self._publish_state_change(tool, CircuitState.OPEN)\n            if fallback:\n                return fallback()\n            raise CircuitOpenError(\n                f\"Circuit open for tool '{tool}'. \"\n                f\"Failures: {breaker.failure_count}. \"\n                f\"Recovery in {breaker.recovery_timeout_s}s.\"\n            )\n\n        last_error = None\n        for attempt in range(self.max_retries + 1):\n            try:\n                result = call_tool(self.api_key, tool, input_data)\n                breaker.record_success()\n                if breaker.state == CircuitState.CLOSED and attempt > 0:\n                    self._publish_state_change(tool, CircuitState.CLOSED)\n                return result\n            except requests.exceptions.HTTPError as e:\n                status = e.response.status_code if e.response else 500\n                # Do not retry client errors (except 429)\n                if 400 \u003C= status \u003C 500 and status != 429:\n                    breaker.record_failure()\n                    raise\n                last_error = e\n                breaker.record_failure()\n            except requests.exceptions.Timeout as e:\n                last_error = e\n                breaker.record_failure()\n            except requests.exceptions.ConnectionError as e:\n                last_error = e\n                breaker.record_failure()\n\n            if attempt \u003C self.max_retries:\n                delay = self._backoff_delay(attempt)\n                time.sleep(delay)\n\n        # All retries exhausted\n        if fallback:\n            return fallback()\n        raise last_error or RuntimeError(f\"Tool '{tool}' call failed\")\n\n    def get_circuit_states(self) -> dict:\n        \"\"\"Return the state of all circuit breakers.\"\"\"\n        return {\n            name: {\n                \"state\": cb.state.value,\n                \"failure_count\": cb.failure_count,\n                \"success_count\": cb.success_count,\n            }\n            for name, cb in self._breakers.items()\n        }\n\n\nclass CircuitOpenError(Exception):\n    pass\n\n\n# Usage\nif __name__ == \"__main__\":\n    import os\n    caller = ResilientToolCaller(\n        api_key=os.environ[\"GREENHELIX_API_KEY\"],\n        agent_id=\"commerce-agent-prod-01\",\n        failure_threshold=5,\n        max_retries=3,\n    )\n\n    # Call with automatic retry and circuit breaker\n    result = caller.execute(\"get_balance\", {\n        \"agent_id\": \"commerce-agent-prod-01\",\n    })\n\n    # Call with fallback\n    result = caller.execute(\n        \"create_escrow\",\n        {\"amount\": 50.0, \"counterparty\": \"provider-agent-01\"},\n        fallback=lambda: {\"status\": \"queued\", \"message\": \"Escrow queued for retry\"},\n    )\n    print(json.dumps(caller.get_circuit_states(), indent=2))\n```\n\n### Decision Matrix: When to Retry vs. Fail Fast vs. Fall Back\n\n| Error Type | HTTP Code | Retry? | Circuit Breaker? | Fallback? |\n|------------|-----------|--------|-------------------|-----------|\n| Rate limited | 429 | Yes, with backoff | Yes, at threshold | Queue for later |\n| Server error | 500 | Yes, 2x max | Yes | Return cached |\n| Service unavailable | 503 | Yes, with backoff | Yes | Route to alternative |\n| Gateway timeout | 504 | Yes, 1x | Yes | Return partial result |\n| Bad request | 400 | No | No | Fix input, do not retry |\n| Unauthorized | 401 | No | No | Refresh credential, retry 1x |\n| Forbidden | 403 | No | No | Escalate to human |\n| Not found | 404 | No | No | Fail with clear error |\n| Payment required | 402 | No | No | Top up budget, retry 1x |\n\n> **Key Takeaways**\n>\n> - Agent retry logic lives inside the LLM reasoning loop and will retry forever without an external circuit breaker.\n> - Implement circuit breakers at three layers: LLM calls, tool invocations, and inter-agent communication.\n> - Use exponential backoff with full jitter (`base * 2^attempt * random()`) to avoid thundering herds.\n> - Publish circuit breaker state changes to GreenHelix Events so dashboards and peer agents can see degraded dependencies.\n> - The fallback chain for LLM calls: frontier model, smaller model, cached response, human escalation.\n> - See P12 (Incident Response) for automated containment actions when circuit breakers trip fleet-wide.\n\n---\n\n## Chapter 4: Cost Guardrails and Token Budget Enforcement\n\n### The Three Layers of Cost Control\n\nCost guardrails operate at three granularities. Miss any layer and the blast radius of a runaway agent expands exponentially.\n\n**Per-Request Guards.** Every individual tool call or LLM inference has a maximum allowable cost. If a single request would cost more than the cap, it is rejected before execution. This prevents a single malformed request from draining the budget.\n\n**Per-Agent Guards.** Every agent has a daily and monthly budget cap enforced at the wallet level. When the agent hits its cap, all subsequent requests receive a 402 response. The blast radius is one agent, not the fleet.\n\n**Per-Workflow Guards.** A multi-agent workflow (e.g., \"hire a researcher, verify results, publish summary\") has a total budget envelope. If the workflow exceeds its budget, the orchestrator aborts the workflow and releases any held escrows. This prevents fan-out amplification from consuming the fleet budget.\n\n### Token Budget Allocation\n\nNot all agent tasks cost the same. A simple lookup costs a fraction of a cent. A multi-step research workflow with RAG retrieval costs dollars. Allocating a flat budget per agent wastes money on simple agents and starves complex ones.\n\nThe allocation formula:\n\n```\nagent_daily_budget = baseline_cost * safety_multiplier * task_volume\n\nwhere:\n  baseline_cost   = median cost-per-task over last 7 days\n  safety_multiplier = 3.0 (allows 3x median before cap triggers)\n  task_volume     = expected daily task count\n```\n\nRecalculate weekly. Publish the new budget via `set_budget`. Alert at 75% consumption via `register_webhook`.\n\n### The CostGuardRail Middleware\n\n```python\nimport requests\nimport time\nimport json\nimport threading\nfrom dataclasses import dataclass, field\nfrom typing import Optional, Dict, List\nfrom datetime import datetime, timedelta\n\nBASE_URL = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n\ndef call_tool(api_key: str, tool: str, input_data: dict) -> dict:\n    resp = requests.post(\n        f\"{BASE_URL}\u002Fv1\",\n        headers={\"Authorization\": f\"Bearer {api_key}\"},\n        json={\"tool\": tool, \"input\": input_data},\n        timeout=30,\n    )\n    resp.raise_for_status()\n    return resp.json()\n\n\n@dataclass\nclass CostLimits:\n    per_request_usd: float = 1.00      # Max cost for a single tool call\n    daily_limit_usd: float = 25.00     # Hard daily cap\n    monthly_limit_usd: float = 500.00  # Hard monthly cap\n    workflow_limit_usd: float = 10.00  # Max cost per workflow execution\n    alert_threshold_pct: float = 0.75  # Alert at 75% consumption\n\n\nclass CostGuardRail:\n    \"\"\"Middleware that enforces per-request, per-agent, and per-workflow\n    cost caps using GreenHelix Billing and Ledger tools.\n\n    Wrap your agent's tool calls with this middleware to prevent\n    runaway spending. Integrates with GreenHelix set_budget,\n    get_balance, get_usage_analytics, and record_transaction.\n    \"\"\"\n\n    def __init__(self, api_key: str, agent_id: str, limits: CostLimits):\n        self.api_key = api_key\n        self.agent_id = agent_id\n        self.limits = limits\n        self._workflow_spend: Dict[str, float] = {}\n        self._daily_spend: float = 0.0\n        self._day_start: datetime = datetime.utcnow().replace(\n            hour=0, minute=0, second=0, microsecond=0)\n        self._lock = threading.Lock()\n        self._kill_switch: bool = False\n\n    def _call(self, tool: str, input_data: dict) -> dict:\n        return call_tool(self.api_key, tool, input_data)\n\n    def initialize(self) -> dict:\n        \"\"\"Set budget caps on the GreenHelix gateway.\"\"\"\n        result = self._call(\"set_budget\", {\n            \"agent_id\": self.agent_id,\n            \"daily_limit\": self.limits.daily_limit_usd,\n            \"monthly_limit\": self.limits.monthly_limit_usd,\n        })\n        # Register webhook for threshold alerts\n        self._call(\"register_webhook\", {\n            \"agent_id\": self.agent_id,\n            \"url\": f\"https:\u002F\u002Fyour-app.example.com\u002Falerts\u002Fcost\u002F{self.agent_id}\",\n            \"events\": [\"budget.threshold\", \"budget.exceeded\"],\n            \"config\": {\n                \"threshold_pct\": int(self.limits.alert_threshold_pct * 100),\n            },\n        })\n        return result\n\n    def activate_kill_switch(self):\n        \"\"\"Emergency: reject all subsequent requests.\"\"\"\n        self._kill_switch = True\n        # Set budget to zero on the gateway\n        self._call(\"set_budget\", {\n            \"agent_id\": self.agent_id,\n            \"daily_limit\": 0,\n            \"monthly_limit\": 0,\n        })\n\n    def deactivate_kill_switch(self):\n        \"\"\"Resume normal operation after manual review.\"\"\"\n        self._kill_switch = False\n        self.initialize()  # Restore original limits\n\n    def check_balance(self) -> dict:\n        \"\"\"Get current balance and spend from GreenHelix.\"\"\"\n        return self._call(\"get_balance\", {\n            \"agent_id\": self.agent_id,\n        })\n\n    def get_analytics(self, period: str = \"daily\") -> dict:\n        \"\"\"Get usage analytics for cost attribution.\"\"\"\n        return self._call(\"get_usage_analytics\", {\n            \"agent_id\": self.agent_id,\n            \"period\": period,\n        })\n\n    def _reset_daily_if_needed(self):\n        now = datetime.utcnow()\n        today = now.replace(hour=0, minute=0, second=0, microsecond=0)\n        if today > self._day_start:\n            self._daily_spend = 0.0\n            self._day_start = today\n\n    def pre_request_check(self, estimated_cost_usd: float,\n                          workflow_id: Optional[str] = None) -> dict:\n        \"\"\"Check cost limits BEFORE executing a request.\n\n        Returns:\n            {\"allowed\": True\u002FFalse, \"reason\": str, \"remaining_daily\": float}\n        \"\"\"\n        if self._kill_switch:\n            return {\n                \"allowed\": False,\n                \"reason\": \"Kill switch active. All requests blocked.\",\n                \"remaining_daily\": 0.0,\n            }\n\n        with self._lock:\n            self._reset_daily_if_needed()\n\n            # Per-request check\n            if estimated_cost_usd > self.limits.per_request_usd:\n                return {\n                    \"allowed\": False,\n                    \"reason\": (f\"Request cost ${estimated_cost_usd:.4f} exceeds \"\n                               f\"per-request limit ${self.limits.per_request_usd:.2f}\"),\n                    \"remaining_daily\": self.limits.daily_limit_usd - self._daily_spend,\n                }\n\n            # Daily check\n            if self._daily_spend + estimated_cost_usd > self.limits.daily_limit_usd:\n                return {\n                    \"allowed\": False,\n                    \"reason\": (f\"Daily spend ${self._daily_spend:.2f} + request \"\n                               f\"${estimated_cost_usd:.4f} exceeds daily limit \"\n                               f\"${self.limits.daily_limit_usd:.2f}\"),\n                    \"remaining_daily\": self.limits.daily_limit_usd - self._daily_spend,\n                }\n\n            # Workflow check\n            if workflow_id:\n                wf_spend = self._workflow_spend.get(workflow_id, 0.0)\n                if wf_spend + estimated_cost_usd > self.limits.workflow_limit_usd:\n                    return {\n                        \"allowed\": False,\n                        \"reason\": (f\"Workflow '{workflow_id}' spend ${wf_spend:.2f} + \"\n                                   f\"request ${estimated_cost_usd:.4f} exceeds workflow \"\n                                   f\"limit ${self.limits.workflow_limit_usd:.2f}\"),\n                        \"remaining_daily\": self.limits.daily_limit_usd - self._daily_spend,\n                    }\n\n            return {\n                \"allowed\": True,\n                \"reason\": \"Within all limits\",\n                \"remaining_daily\": (self.limits.daily_limit_usd\n                                    - self._daily_spend\n                                    - estimated_cost_usd),\n            }\n\n    def post_request_record(self, actual_cost_usd: float,\n                            workflow_id: Optional[str] = None,\n                            metadata: Optional[dict] = None):\n        \"\"\"Record actual cost AFTER a request completes.\"\"\"\n        with self._lock:\n            self._daily_spend += actual_cost_usd\n            if workflow_id:\n                self._workflow_spend[workflow_id] = (\n                    self._workflow_spend.get(workflow_id, 0.0) + actual_cost_usd\n                )\n\n        # Record to GreenHelix Ledger for audit trail\n        self._call(\"record_transaction\", {\n            \"agent_id\": self.agent_id,\n            \"amount\": str(actual_cost_usd),\n            \"type\": \"tool_call_cost\",\n            \"metadata\": metadata or {},\n        })\n\n        # Check alert threshold\n        daily_pct = self._daily_spend \u002F self.limits.daily_limit_usd\n        if daily_pct >= self.limits.alert_threshold_pct:\n            self._call(\"publish_event\", {\n                \"agent_id\": self.agent_id,\n                \"event_type\": \"cost.threshold_warning\",\n                \"payload\": {\n                    \"daily_spend\": round(self._daily_spend, 4),\n                    \"daily_limit\": self.limits.daily_limit_usd,\n                    \"pct_consumed\": round(daily_pct * 100, 1),\n                },\n            })\n\n    def end_workflow(self, workflow_id: str):\n        \"\"\"Clean up workflow tracking after workflow completes.\"\"\"\n        with self._lock:\n            total = self._workflow_spend.pop(workflow_id, 0.0)\n        return {\"workflow_id\": workflow_id, \"total_cost_usd\": round(total, 4)}\n\n\n# Usage\nif __name__ == \"__main__\":\n    import os\n\n    guardrail = CostGuardRail(\n        api_key=os.environ[\"GREENHELIX_API_KEY\"],\n        agent_id=\"commerce-agent-prod-01\",\n        limits=CostLimits(\n            per_request_usd=1.00,\n            daily_limit_usd=25.00,\n            monthly_limit_usd=500.00,\n            workflow_limit_usd=10.00,\n        ),\n    )\n    guardrail.initialize()\n\n    # Before every tool call:\n    check = guardrail.pre_request_check(\n        estimated_cost_usd=0.05,\n        workflow_id=\"wf-research-001\",\n    )\n    if check[\"allowed\"]:\n        # ... execute the tool call ...\n        guardrail.post_request_record(\n            actual_cost_usd=0.047,\n            workflow_id=\"wf-research-001\",\n            metadata={\"tool\": \"search_marketplace\", \"tokens\": 1200},\n        )\n    else:\n        print(f\"Blocked: {check['reason']}\")\n\n    # Emergency kill switch\n    # guardrail.activate_kill_switch()\n```\n\n### Cost Estimation Table\n\nUse this table to estimate costs when calling `pre_request_check`:\n\n| Operation Type | Estimated Cost | Notes |\n|----------------|----------------|-------|\n| Simple tool lookup (get_balance, get_trust_score) | $0.001 - $0.005 | Gateway fee only |\n| State-changing tool (create_escrow, release_escrow) | $0.01 - $0.05 | Gateway fee + processing |\n| LLM inference (GPT-4o, 1K input + 500 output tokens) | $0.01 - $0.03 | Per-call, model-dependent |\n| LLM inference (Claude Opus, 1K input + 500 output tokens) | $0.02 - $0.06 | Per-call, model-dependent |\n| Multi-step workflow (5 tool calls + 3 LLM inferences) | $0.10 - $0.30 | Sum of components |\n| RAG workflow (embedding + retrieval + generation) | $0.05 - $0.15 | Embedding + LLM costs |\n\n> **Key Takeaways**\n>\n> - Cost guardrails operate at three layers: per-request, per-agent, and per-workflow. Missing any layer allows blast radius expansion.\n> - Budget allocation formula: `baseline_cost * 3.0 * task_volume`, recalculated weekly.\n> - The kill switch sets the gateway budget to zero, immediately blocking all requests for the agent.\n> - Record every cost to the GreenHelix Ledger via `record_transaction` for audit trails and post-mortem analysis.\n> - See P6 (FinOps Playbook) for fleet-wide cost dashboards, volume discount optimization, and cost attribution patterns.\n\n---\n\n## Chapter 5: Deployment Patterns: Canary, Blue-Green, and Rollback\n\n### Why Agent Deployments Are Dangerous\n\nDeploying a new version of a traditional web service is risky. Deploying a new version of an autonomous agent is dangerous. The difference is that a web service returns wrong HTML; an agent makes wrong financial decisions. A prompt change that increases task completion rate by 2% might also increase cost-per-task by 40%. A model upgrade that reduces latency might degrade output quality for edge cases. You cannot know the full impact of an agent deployment without measuring it against production traffic -- but you cannot expose 100% of production traffic to an unvalidated change without accepting the risk of fleet-wide impact.\n\nCanary deployments solve this by routing a small percentage of traffic to the new version, measuring SLOs, and promoting or rolling back based on data.\n\n### Canary Deployment for Agent Upgrades\n\nThe canary pattern for agents:\n\n1. Deploy new agent version alongside the current version.\n2. Route 5% of traffic to the canary.\n3. Measure all three SLOs (completion, latency, cost) for 2 hours.\n4. If SLOs hold: promote to 25%, then 50%, then 100%.\n5. If any SLO breaches: automatic rollback to 0% canary traffic.\n\n```\n                  ┌──────────────────┐\n                  │   Load Balancer   │\n                  │   (5% \u002F 95%)     │\n                  └───────┬──────────┘\n                    ┌─────┴─────┐\n              ┌─────▼───┐  ┌────▼──────┐\n              │ Canary  │  │ Stable    │\n              │ v2.1.0  │  │ v2.0.0   │\n              │ 5%      │  │ 95%      │\n              └─────┬───┘  └────┬──────┘\n                    │           │\n                    └─────┬─────┘\n                    ┌─────▼──────────┐\n                    │   SLO Monitor  │\n                    │ Compare canary │\n                    │  vs. stable    │\n                    └────────────────┘\n```\n\n### Blue-Green Switching\n\nBlue-green deployments maintain two complete environments. At any time, one is live (blue) and one is staging (green). To deploy:\n\n1. Deploy the new version to green.\n2. Run smoke tests against green.\n3. Switch traffic from blue to green.\n4. If problems: switch back to blue instantly.\n\nBlue-green is simpler than canary but does not allow gradual traffic shifting. Use it when you need instant rollback capability and can accept all-or-nothing deployment.\n\n### Automated Rollback Triggers\n\nRollback should be automated, not a decision made by a sleepy on-call engineer at 3 AM. Define rollback triggers tied to SLO breach:\n\n| Trigger | Condition | Action |\n|---------|-----------|--------|\n| Completion Rate Drop | Canary completion \u003C stable - 2% for 30 min | Rollback |\n| Latency Spike | Canary P99 > stable P99 * 1.5 for 15 min | Rollback |\n| Cost Overrun | Canary cost-per-task > stable * 1.3 for 15 min | Rollback |\n| Error Rate | Canary 5xx rate > 5% for 10 min | Immediate rollback |\n| Circuit Breaker | Any canary circuit breaker opens | Immediate rollback |\n\n```python\nimport requests\nimport time\nimport json\nfrom dataclasses import dataclass, field\nfrom typing import Optional, Dict, List\nfrom datetime import datetime, timedelta\nfrom enum import Enum\n\nBASE_URL = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n\ndef call_tool(api_key: str, tool: str, input_data: dict) -> dict:\n    resp = requests.post(\n        f\"{BASE_URL}\u002Fv1\",\n        headers={\"Authorization\": f\"Bearer {api_key}\"},\n        json={\"tool\": tool, \"input\": input_data},\n        timeout=30,\n    )\n    resp.raise_for_status()\n    return resp.json()\n\n\nclass DeploymentPhase(Enum):\n    PENDING = \"pending\"\n    CANARY_5 = \"canary_5\"\n    CANARY_25 = \"canary_25\"\n    CANARY_50 = \"canary_50\"\n    PROMOTED = \"promoted\"\n    ROLLED_BACK = \"rolled_back\"\n\n\n@dataclass\nclass SLOComparison:\n    metric: str\n    canary_value: float\n    stable_value: float\n    threshold_ratio: float  # max allowed canary\u002Fstable ratio\n\n    @property\n    def passed(self) -> bool:\n        if self.stable_value == 0:\n            return True\n        ratio = self.canary_value \u002F self.stable_value\n        return ratio \u003C= self.threshold_ratio\n\n\nclass CanaryDeployer:\n    \"\"\"Manages canary deployments for agent upgrades with automated\n    SLO-based promotion and rollback.\n\n    Queries GreenHelix Analytics to compare canary vs. stable SLOs\n    and publishes deployment events for audit trails.\n    \"\"\"\n\n    def __init__(self, api_key: str, agent_id: str,\n                 canary_agent_id: str):\n        self.api_key = api_key\n        self.agent_id = agent_id          # Stable version\n        self.canary_agent_id = canary_agent_id  # Canary version\n        self.phase = DeploymentPhase.PENDING\n        self.deployment_id = f\"deploy-{int(time.time())}\"\n        self.slo_history: List[dict] = []\n\n    def _call(self, tool: str, input_data: dict) -> dict:\n        return call_tool(self.api_key, tool, input_data)\n\n    def _get_metrics(self, target_agent_id: str) -> dict:\n        \"\"\"Fetch revenue and performance metrics for an agent.\"\"\"\n        return self._call(\"get_revenue_metrics\", {\n            \"agent_id\": target_agent_id,\n            \"period\": \"hourly\",\n        })\n\n    def _compare_slos(self) -> List[SLOComparison]:\n        \"\"\"Compare canary vs. stable SLOs across all dimensions.\"\"\"\n        stable = self._get_metrics(self.agent_id)\n        canary = self._get_metrics(self.canary_agent_id)\n\n        comparisons = []\n\n        # Completion rate: canary should not be worse\n        s_completion = stable.get(\"completion_rate\", 1.0)\n        c_completion = canary.get(\"completion_rate\", 1.0)\n        # For completion, we invert: lower is worse, so check 1\u002Fratio\n        if c_completion > 0:\n            comparisons.append(SLOComparison(\n                metric=\"completion_rate\",\n                canary_value=s_completion \u002F c_completion,\n                stable_value=1.0,\n                threshold_ratio=1.02,  # Allow 2% degradation\n            ))\n\n        # Latency P99: canary should not be 50% higher\n        s_latency = stable.get(\"latency_p99_ms\", 1000)\n        c_latency = canary.get(\"latency_p99_ms\", 1000)\n        comparisons.append(SLOComparison(\n            metric=\"latency_p99\",\n            canary_value=c_latency,\n            stable_value=s_latency,\n            threshold_ratio=1.5,\n        ))\n\n        # Cost per task: canary should not be 30% higher\n        s_cost = stable.get(\"cost_per_task_usd\", 0.10)\n        c_cost = canary.get(\"cost_per_task_usd\", 0.10)\n        comparisons.append(SLOComparison(\n            metric=\"cost_per_task\",\n            canary_value=c_cost,\n            stable_value=s_cost,\n            threshold_ratio=1.3,\n        ))\n\n        return comparisons\n\n    def _publish_event(self, event_type: str, payload: dict):\n        self._call(\"publish_event\", {\n            \"agent_id\": self.agent_id,\n            \"event_type\": event_type,\n            \"payload\": {\n                \"deployment_id\": self.deployment_id,\n                **payload,\n            },\n        })\n\n    def start_canary(self) -> dict:\n        \"\"\"Begin canary deployment at 5% traffic.\"\"\"\n        self.phase = DeploymentPhase.CANARY_5\n        self._publish_event(\"deployment.canary_started\", {\n            \"canary_agent_id\": self.canary_agent_id,\n            \"traffic_pct\": 5,\n        })\n        return {\n            \"deployment_id\": self.deployment_id,\n            \"phase\": self.phase.value,\n            \"canary_traffic_pct\": 5,\n        }\n\n    def evaluate_and_advance(self) -> dict:\n        \"\"\"Check SLOs and advance to next phase or rollback.\n\n        Call this periodically (e.g., every 30 minutes) after\n        starting the canary.\n        \"\"\"\n        comparisons = self._compare_slos()\n        all_passed = all(c.passed for c in comparisons)\n\n        slo_report = {\n            c.metric: {\n                \"canary\": round(c.canary_value, 4),\n                \"stable\": round(c.stable_value, 4),\n                \"passed\": c.passed,\n            }\n            for c in comparisons\n        }\n        self.slo_history.append({\n            \"phase\": self.phase.value,\n            \"timestamp\": datetime.utcnow().isoformat(),\n            \"slos\": slo_report,\n            \"all_passed\": all_passed,\n        })\n\n        if not all_passed:\n            return self.rollback(reason=\"SLO breach detected\", slos=slo_report)\n\n        # Advance to next phase\n        promotion_path = {\n            DeploymentPhase.CANARY_5: (DeploymentPhase.CANARY_25, 25),\n            DeploymentPhase.CANARY_25: (DeploymentPhase.CANARY_50, 50),\n            DeploymentPhase.CANARY_50: (DeploymentPhase.PROMOTED, 100),\n        }\n\n        if self.phase in promotion_path:\n            next_phase, traffic_pct = promotion_path[self.phase]\n            self.phase = next_phase\n            self._publish_event(\"deployment.phase_advanced\", {\n                \"new_phase\": self.phase.value,\n                \"traffic_pct\": traffic_pct,\n                \"slo_report\": slo_report,\n            })\n            return {\n                \"deployment_id\": self.deployment_id,\n                \"phase\": self.phase.value,\n                \"traffic_pct\": traffic_pct,\n                \"slos\": slo_report,\n            }\n\n        return {\n            \"deployment_id\": self.deployment_id,\n            \"phase\": self.phase.value,\n            \"message\": \"Deployment fully promoted\",\n        }\n\n    def rollback(self, reason: str, slos: Optional[dict] = None) -> dict:\n        \"\"\"Immediately rollback canary and route 100% to stable.\"\"\"\n        self.phase = DeploymentPhase.ROLLED_BACK\n        self._publish_event(\"deployment.rolled_back\", {\n            \"reason\": reason,\n            \"slo_report\": slos or {},\n        })\n        return {\n            \"deployment_id\": self.deployment_id,\n            \"phase\": self.phase.value,\n            \"reason\": reason,\n            \"slo_history\": self.slo_history,\n        }\n\n\n# Usage\nif __name__ == \"__main__\":\n    import os\n    deployer = CanaryDeployer(\n        api_key=os.environ[\"GREENHELIX_API_KEY\"],\n        agent_id=\"commerce-agent-v2.0\",\n        canary_agent_id=\"commerce-agent-v2.1-canary\",\n    )\n\n    # Start canary at 5%\n    result = deployer.start_canary()\n    print(json.dumps(result, indent=2))\n\n    # After 2 hours, evaluate and advance (or rollback)\n    # result = deployer.evaluate_and_advance()\n```\n\n> **Key Takeaways**\n>\n> - Never deploy an agent update to 100% of traffic. Use canary deployments with 5% initial traffic.\n> - Define automated rollback triggers for each SLO dimension: completion rate, latency, cost, error rate, circuit breaker state.\n> - Blue-green deployments provide instant rollback but no gradual traffic shifting.\n> - Publish deployment events to GreenHelix for audit trails and fleet-wide visibility.\n> - Use `get_revenue_metrics` to compare canary vs. stable performance across all SLO dimensions.\n\n---\n\n## Chapter 6: Multi-Agent Failure Modes and Resilience Patterns\n\n### The 14 MAST Failure Modes\n\nThe Multi-Agent System Taxonomy (MAST) identifies 14 failure modes specific to multi-agent commerce systems. These are not theoretical -- they are extracted from post-mortems of production agent systems.\n\n| # | Failure Mode | Category | Severity | Detection Difficulty |\n|---|-------------|----------|----------|---------------------|\n| 1 | Feedback Loop | Behavioral | Critical | Hard |\n| 2 | False Consensus | Coordination | High | Hard |\n| 3 | Goal Drift | Behavioral | High | Very Hard |\n| 4 | Cascading Failure | Infrastructure | Critical | Medium |\n| 5 | Resource Starvation | Infrastructure | High | Easy |\n| 6 | Deadlock | Coordination | Critical | Medium |\n| 7 | Livelock | Coordination | High | Hard |\n| 8 | Byzantine Agent | Trust | Critical | Very Hard |\n| 9 | Amplification Attack | Security | Critical | Medium |\n| 10 | Split Brain | Coordination | High | Hard |\n| 11 | Stale State | Data | Medium | Easy |\n| 12 | Priority Inversion | Scheduling | Medium | Medium |\n| 13 | Phantom Dependency | Integration | Medium | Hard |\n| 14 | Metric Gaming | Trust | High | Very Hard |\n\n**Feedback Loop (FM-1).** Agent A's output feeds into Agent B's input, and Agent B's output feeds back into Agent A. Without a cycle detector, the agents oscillate forever, each amplifying the other's output. In commerce: Agent A raises a price, Agent B responds by raising its bid, Agent A sees the higher bid and raises the price again.\n\n**False Consensus (FM-2).** Multiple agents vote on a decision. A majority agrees, but the agreement is based on shared bad information -- they all queried the same stale cache or the same hallucinating model. The consensus is confident and wrong.\n\n**Goal Drift (FM-3).** An agent's objective function shifts over time due to feedback from its environment. A pricing agent that is rewarded for revenue gradually increases prices until customer satisfaction collapses. The drift is invisible in daily metrics because each individual price change is small.\n\n**Cascading Failure (FM-4).** Agent A fails. Agents B and C depend on Agent A and begin retrying. The retry load overloads Agent A's recovery. Agents D and E, which depend on B and C, now fail. Within minutes, the entire fleet is down.\n\n### Bulkhead Isolation\n\nBulkheads prevent cascading failures by isolating agent groups into failure domains. Agents within a bulkhead share resources. Agents across bulkheads do not. When one bulkhead fails, the others continue operating.\n\n```\n┌─────────────────┐  ┌─────────────────┐  ┌─────────────────┐\n│  Bulkhead: Core  │  │ Bulkhead: Aux   │  │ Bulkhead: Batch │\n│                  │  │                  │  │                  │\n│  pricing-agent   │  │  research-agent  │  │  report-agent    │\n│  escrow-agent    │  │  analysis-agent  │  │  cleanup-agent   │\n│  settlement-agent│  │  summary-agent   │  │  audit-agent     │\n│                  │  │                  │  │                  │\n│  Budget: $100\u002Fd  │  │  Budget: $50\u002Fd   │  │  Budget: $25\u002Fd   │\n│  Wallet: isolated│  │  Wallet: isolated│  │  Wallet: isolated│\n└─────────────────┘  └─────────────────┘  └─────────────────┘\n         │                    │                     │\n         └────────────────────┼─────────────────────┘\n                              │\n                   ┌──────────▼──────────┐\n                   │   GreenHelix Gateway │\n                   │   (shared, but each  │\n                   │    bulkhead has own   │\n                   │    budget + circuit   │\n                   │    breakers)          │\n                   └──────────────────────┘\n```\n\n### Supervisor with Deadlock Detection\n\nA supervisor agent monitors the multi-agent system for deadlock (two or more agents waiting on each other) and livelock (agents changing state continuously but making no progress). The supervisor uses GreenHelix Messaging to poll agent state and Events to publish alerts.\n\n```python\nimport requests\nimport time\nimport json\nimport threading\nfrom dataclasses import dataclass, field\nfrom typing import Dict, List, Optional, Set, Tuple\nfrom datetime import datetime, timedelta\nfrom enum import Enum\n\nBASE_URL = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n\ndef call_tool(api_key: str, tool: str, input_data: dict) -> dict:\n    resp = requests.post(\n        f\"{BASE_URL}\u002Fv1\",\n        headers={\"Authorization\": f\"Bearer {api_key}\"},\n        json={\"tool\": tool, \"input\": input_data},\n        timeout=30,\n    )\n    resp.raise_for_status()\n    return resp.json()\n\n\nclass AgentState(Enum):\n    IDLE = \"idle\"\n    WORKING = \"working\"\n    WAITING = \"waiting\"        # Waiting on another agent\n    BLOCKED = \"blocked\"        # Waiting on a resource\n    FAILED = \"failed\"\n    TERMINATED = \"terminated\"\n\n\n@dataclass\nclass AgentStatus:\n    agent_id: str\n    state: AgentState\n    waiting_on: Optional[str] = None  # Agent ID this agent is waiting on\n    last_progress: Optional[datetime] = None\n    task_count: int = 0\n    error_count: int = 0\n\n\nclass MultiAgentSupervisor:\n    \"\"\"Supervises a fleet of agents, detecting deadlocks, livelocks,\n    feedback loops, and cascading failures.\n\n    Uses GreenHelix Messaging for agent communication and Events\n    for fleet-wide alerting.\n    \"\"\"\n\n    def __init__(self, api_key: str, supervisor_id: str):\n        self.api_key = api_key\n        self.supervisor_id = supervisor_id\n        self._agents: Dict[str, AgentStatus] = {}\n        self._message_history: List[dict] = []\n        self._lock = threading.Lock()\n\n    def _call(self, tool: str, input_data: dict) -> dict:\n        return call_tool(self.api_key, tool, input_data)\n\n    def register_agent(self, agent_id: str):\n        \"\"\"Register an agent under this supervisor's watch.\"\"\"\n        with self._lock:\n            self._agents[agent_id] = AgentStatus(\n                agent_id=agent_id,\n                state=AgentState.IDLE,\n                last_progress=datetime.utcnow(),\n            )\n\n    def update_agent_state(self, agent_id: str, state: AgentState,\n                           waiting_on: Optional[str] = None):\n        \"\"\"Update an agent's state. Called by agents or inferred from messages.\"\"\"\n        with self._lock:\n            if agent_id in self._agents:\n                status = self._agents[agent_id]\n                if state == AgentState.WORKING:\n                    status.last_progress = datetime.utcnow()\n                    status.task_count += 1\n                elif state == AgentState.FAILED:\n                    status.error_count += 1\n                status.state = state\n                status.waiting_on = waiting_on\n\n    def detect_deadlocks(self) -> List[List[str]]:\n        \"\"\"Detect circular wait dependencies (deadlocks).\n\n        Returns a list of cycles, where each cycle is a list of\n        agent IDs forming the deadlock.\n        \"\"\"\n        with self._lock:\n            # Build wait-for graph\n            wait_graph: Dict[str, str] = {}\n            for agent_id, status in self._agents.items():\n                if (status.state == AgentState.WAITING\n                        and status.waiting_on):\n                    wait_graph[agent_id] = status.waiting_on\n\n        # Find cycles using DFS\n        cycles = []\n        visited: Set[str] = set()\n\n        for start in wait_graph:\n            if start in visited:\n                continue\n            path = []\n            current = start\n            path_set: Set[str] = set()\n\n            while current and current not in visited:\n                if current in path_set:\n                    # Found a cycle\n                    cycle_start = path.index(current)\n                    cycle = path[cycle_start:] + [current]\n                    cycles.append(cycle)\n                    break\n                path.append(current)\n                path_set.add(current)\n                current = wait_graph.get(current)\n\n            visited.update(path_set)\n\n        return cycles\n\n    def detect_livelocks(self, window_minutes: int = 10,\n                         min_state_changes: int = 20) -> List[str]:\n        \"\"\"Detect agents that are changing state rapidly but making\n        no progress (livelock).\n\n        An agent in livelock has high state-change frequency but\n        zero task completions in the window.\n        \"\"\"\n        # This is a simplified heuristic. In production, track state\n        # change events in a time-series database.\n        with self._lock:\n            livelocked = []\n            cutoff = datetime.utcnow() - timedelta(minutes=window_minutes)\n            for agent_id, status in self._agents.items():\n                if (status.last_progress\n                        and status.last_progress \u003C cutoff\n                        and status.state == AgentState.WORKING\n                        and status.error_count > min_state_changes):\n                    livelocked.append(agent_id)\n            return livelocked\n\n    def detect_cascade_risk(self, error_threshold: int = 3) -> List[str]:\n        \"\"\"Detect agents at risk of cascading failure.\n\n        An agent is at risk if it has accumulated errors above\n        threshold while other agents depend on it.\n        \"\"\"\n        with self._lock:\n            # Find agents with high error counts\n            failing = {\n                aid for aid, s in self._agents.items()\n                if s.error_count >= error_threshold\n            }\n            # Find agents waiting on failing agents\n            at_risk = []\n            for agent_id, status in self._agents.items():\n                if (status.waiting_on and status.waiting_on in failing):\n                    at_risk.append(agent_id)\n            return at_risk\n\n    def send_heartbeat_check(self, agent_id: str) -> dict:\n        \"\"\"Send a heartbeat message to an agent via GreenHelix Messaging.\"\"\"\n        return self._call(\"send_message\", {\n            \"from_agent\": self.supervisor_id,\n            \"to_agent\": agent_id,\n            \"message_type\": \"heartbeat_request\",\n            \"payload\": {\n                \"timestamp\": datetime.utcnow().isoformat(),\n                \"supervisor\": self.supervisor_id,\n            },\n        })\n\n    def break_deadlock(self, cycle: List[str]) -> dict:\n        \"\"\"Break a deadlock by terminating the lowest-priority agent\n        in the cycle and publishing an alert.\n        \"\"\"\n        # Terminate the agent with the most errors (least healthy)\n        with self._lock:\n            victim = max(\n                cycle[:-1],  # Exclude duplicate at end of cycle\n                key=lambda aid: self._agents.get(aid, AgentStatus(\n                    agent_id=aid, state=AgentState.IDLE)).error_count,\n            )\n            if victim in self._agents:\n                self._agents[victim].state = AgentState.TERMINATED\n\n        # Publish deadlock event\n        self._call(\"publish_event\", {\n            \"agent_id\": self.supervisor_id,\n            \"event_type\": \"multi_agent.deadlock_detected\",\n            \"payload\": {\n                \"cycle\": cycle,\n                \"terminated_agent\": victim,\n                \"timestamp\": datetime.utcnow().isoformat(),\n            },\n        })\n\n        # Notify the terminated agent\n        self._call(\"send_message\", {\n            \"from_agent\": self.supervisor_id,\n            \"to_agent\": victim,\n            \"message_type\": \"terminate\",\n            \"payload\": {\n                \"reason\": \"deadlock_resolution\",\n                \"cycle\": cycle,\n            },\n        })\n\n        return {\n            \"deadlock_cycle\": cycle,\n            \"terminated\": victim,\n            \"remaining_agents\": [a for a in cycle[:-1] if a != victim],\n        }\n\n    def run_health_check(self) -> dict:\n        \"\"\"Run a complete health check across all managed agents.\"\"\"\n        deadlocks = self.detect_deadlocks()\n        livelocks = self.detect_livelocks()\n        cascade_risks = self.detect_cascade_risk()\n\n        report = {\n            \"timestamp\": datetime.utcnow().isoformat(),\n            \"total_agents\": len(self._agents),\n            \"deadlocks\": deadlocks,\n            \"livelocked_agents\": livelocks,\n            \"cascade_risk_agents\": cascade_risks,\n            \"agent_states\": {\n                aid: {\n                    \"state\": s.state.value,\n                    \"waiting_on\": s.waiting_on,\n                    \"task_count\": s.task_count,\n                    \"error_count\": s.error_count,\n                }\n                for aid, s in self._agents.items()\n            },\n        }\n\n        # Auto-break deadlocks\n        for cycle in deadlocks:\n            self.break_deadlock(cycle)\n\n        # Alert on livelocks and cascade risks\n        if livelocks or cascade_risks:\n            self._call(\"publish_event\", {\n                \"agent_id\": self.supervisor_id,\n                \"event_type\": \"multi_agent.health_warning\",\n                \"payload\": report,\n            })\n\n        return report\n\n\n# Usage\nif __name__ == \"__main__\":\n    import os\n    supervisor = MultiAgentSupervisor(\n        api_key=os.environ[\"GREENHELIX_API_KEY\"],\n        supervisor_id=\"fleet-supervisor-01\",\n    )\n\n    # Register agents\n    for agent in [\"pricing-01\", \"escrow-01\", \"settlement-01\", \"research-01\"]:\n        supervisor.register_agent(agent)\n\n    # Simulate state updates (in production, agents report their state)\n    supervisor.update_agent_state(\"pricing-01\", AgentState.WAITING,\n                                  waiting_on=\"escrow-01\")\n    supervisor.update_agent_state(\"escrow-01\", AgentState.WAITING,\n                                  waiting_on=\"pricing-01\")\n\n    # Run health check -- will detect and break the deadlock\n    report = supervisor.run_health_check()\n    print(json.dumps(report, indent=2))\n```\n\n> **Key Takeaways**\n>\n> - The 14 MAST failure modes cover behavioral (feedback loops, goal drift), coordination (deadlock, livelock, false consensus), infrastructure (cascading failure, resource starvation), and trust (byzantine agents, metric gaming) failures.\n> - Bulkhead isolation prevents cascading failures by giving each agent group its own budget, wallet, and circuit breakers.\n> - A supervisor agent detects deadlocks via cycle detection on the wait-for graph and breaks them by terminating the least-healthy agent.\n> - Livelock detection requires tracking state-change frequency vs. task completion rate.\n> - GreenHelix Messaging (`send_message`) provides the heartbeat channel; Events (`publish_event`) provides the alert channel.\n> - See P12 (Incident Response) for full cascade failure runbooks.\n\n---\n\n## Chapter 7: EU AI Act Production Compliance (August 2026 Deadline)\n\n### The Deadline You Cannot Miss\n\nOn August 2, 2026, the EU AI Act's high-risk system obligations take full effect. If your agent commerce system is classified as high-risk -- and most financial decision-making agents are -- you must demonstrate compliance with Articles 6-49 on that date. Not \"working toward compliance.\" Not \"have a plan.\" Demonstrably compliant, with documentation, audit trails, and technical controls in place. The penalties for non-compliance are up to 35 million euros or 7% of global annual turnover, whichever is higher.\n\nThis chapter maps the nine key high-risk requirements to concrete agent controls and shows how to implement each one using GreenHelix tools.\n\n### The 9 Requirements Mapped to Agent Controls\n\n| Article | Requirement | Agent Control | GreenHelix Tools |\n|---------|-------------|---------------|------------------|\n| Art. 9 | Risk Management System | Risk classification + continuous monitoring | `get_trust_score`, `check_sla_compliance` |\n| Art. 10 | Data Governance | Training data versioning + quality controls | `get_verified_claims`, `record_transaction` |\n| Art. 11 | Technical Documentation | System architecture + capability docs | `register_agent_identity`, `submit_metrics` |\n| Art. 12 | Record-Keeping | Automatic logging of all decisions | `record_transaction`, `publish_event` |\n| Art. 13 | Transparency | User-facing disclosures | `get_agent_card`, `search_marketplace` |\n| Art. 14 | Human Oversight | Kill switches + approval gates | `set_budget` (zero), `publish_event` |\n| Art. 15 | Accuracy | SLO monitoring + regression testing | `check_sla_compliance`, `get_sla_status` |\n| Art. 16 | Robustness | Circuit breakers + graceful degradation | `publish_event`, `get_balance` |\n| Art. 17 | Cybersecurity | Auth + encryption + access control | `verify_claim`, `get_verified_claims` |\n\n### The Compliance Audit Script\n\nThe following script runs a compliance audit against your GreenHelix agent, checking each Article's requirements programmatically where possible and generating a compliance report.\n\n```python\nimport requests\nimport json\nfrom dataclasses import dataclass, field\nfrom typing import Dict, List, Optional\nfrom datetime import datetime\n\nBASE_URL = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n\ndef call_tool(api_key: str, tool: str, input_data: dict) -> dict:\n    resp = requests.post(\n        f\"{BASE_URL}\u002Fv1\",\n        headers={\"Authorization\": f\"Bearer {api_key}\"},\n        json={\"tool\": tool, \"input\": input_data},\n        timeout=30,\n    )\n    resp.raise_for_status()\n    return resp.json()\n\n\n@dataclass\nclass ComplianceCheck:\n    article: str\n    requirement: str\n    status: str  # \"pass\", \"fail\", \"manual_review\"\n    evidence: str\n    remediation: Optional[str] = None\n\n\nclass EUAIActAuditor:\n    \"\"\"Automated compliance auditor for EU AI Act high-risk requirements.\n\n    Checks each Article's requirements against the agent's current\n    GreenHelix configuration and generates a compliance report.\n\n    This is an engineering tool, not legal advice. Consult qualified\n    legal counsel for regulatory interpretation.\n    \"\"\"\n\n    def __init__(self, api_key: str, agent_id: str):\n        self.api_key = api_key\n        self.agent_id = agent_id\n        self.checks: List[ComplianceCheck] = []\n\n    def _call(self, tool: str, input_data: dict) -> dict:\n        return call_tool(self.api_key, tool, input_data)\n\n    def _add_check(self, check: ComplianceCheck):\n        self.checks.append(check)\n\n    def audit_art9_risk_management(self):\n        \"\"\"Article 9: Risk management system.\n        Check: trust score exists and SLA monitoring is active.\"\"\"\n        try:\n            trust = self._call(\"get_trust_score\", {\n                \"agent_id\": self.agent_id,\n            })\n            score = trust.get(\"score\", 0)\n            if score > 0:\n                self._add_check(ComplianceCheck(\n                    article=\"Art. 9\",\n                    requirement=\"Risk management system\",\n                    status=\"pass\",\n                    evidence=f\"Trust score active: {score}. Risk monitoring via SLA.\",\n                ))\n            else:\n                self._add_check(ComplianceCheck(\n                    article=\"Art. 9\",\n                    requirement=\"Risk management system\",\n                    status=\"fail\",\n                    evidence=\"Trust score is zero or not configured.\",\n                    remediation=\"Configure trust monitoring and risk thresholds.\",\n                ))\n        except Exception as e:\n            self._add_check(ComplianceCheck(\n                article=\"Art. 9\",\n                requirement=\"Risk management system\",\n                status=\"fail\",\n                evidence=f\"Could not query trust score: {e}\",\n                remediation=\"Register agent identity and configure trust scoring.\",\n            ))\n\n    def audit_art10_data_governance(self):\n        \"\"\"Article 10: Data governance.\n        Check: verified claims exist (provenance tracking).\"\"\"\n        try:\n            claims = self._call(\"get_verified_claims\", {\n                \"agent_id\": self.agent_id,\n            })\n            claim_list = claims.get(\"claims\", [])\n            if len(claim_list) >= 1:\n                self._add_check(ComplianceCheck(\n                    article=\"Art. 10\",\n                    requirement=\"Data governance\",\n                    status=\"pass\",\n                    evidence=f\"{len(claim_list)} verified claim(s) on record.\",\n                ))\n            else:\n                self._add_check(ComplianceCheck(\n                    article=\"Art. 10\",\n                    requirement=\"Data governance\",\n                    status=\"fail\",\n                    evidence=\"No verified claims found.\",\n                    remediation=\"Submit verified claims for data provenance.\",\n                ))\n        except Exception as e:\n            self._add_check(ComplianceCheck(\n                article=\"Art. 10\",\n                requirement=\"Data governance\",\n                status=\"fail\",\n                evidence=f\"Could not query verified claims: {e}\",\n                remediation=\"Register identity and submit data governance claims.\",\n            ))\n\n    def audit_art11_documentation(self):\n        \"\"\"Article 11: Technical documentation.\n        Check: agent card exists with capabilities description.\"\"\"\n        try:\n            card = self._call(\"get_agent_card\", {\n                \"agent_id\": self.agent_id,\n            })\n            if card.get(\"description\") and card.get(\"capabilities\"):\n                self._add_check(ComplianceCheck(\n                    article=\"Art. 11\",\n                    requirement=\"Technical documentation\",\n                    status=\"pass\",\n                    evidence=\"Agent card has description and capabilities.\",\n                ))\n            else:\n                self._add_check(ComplianceCheck(\n                    article=\"Art. 11\",\n                    requirement=\"Technical documentation\",\n                    status=\"fail\",\n                    evidence=\"Agent card missing description or capabilities.\",\n                    remediation=\"Update agent card with full technical documentation.\",\n                ))\n        except Exception:\n            self._add_check(ComplianceCheck(\n                article=\"Art. 11\",\n                requirement=\"Technical documentation\",\n                status=\"fail\",\n                evidence=\"Agent card not found.\",\n                remediation=\"Register agent identity and create agent card.\",\n            ))\n\n    def audit_art12_record_keeping(self):\n        \"\"\"Article 12: Record-keeping \u002F automatic logging.\n        Check: transaction ledger has recent entries.\"\"\"\n        try:\n            analytics = self._call(\"get_usage_analytics\", {\n                \"agent_id\": self.agent_id,\n                \"period\": \"daily\",\n            })\n            if analytics.get(\"total_transactions\", 0) > 0:\n                self._add_check(ComplianceCheck(\n                    article=\"Art. 12\",\n                    requirement=\"Record-keeping\",\n                    status=\"pass\",\n                    evidence=(f\"Ledger active with \"\n                              f\"{analytics['total_transactions']} transactions.\"),\n                ))\n            else:\n                self._add_check(ComplianceCheck(\n                    article=\"Art. 12\",\n                    requirement=\"Record-keeping\",\n                    status=\"fail\",\n                    evidence=\"No transactions in ledger.\",\n                    remediation=\"Ensure all agent actions are logged via record_transaction.\",\n                ))\n        except Exception as e:\n            self._add_check(ComplianceCheck(\n                article=\"Art. 12\",\n                requirement=\"Record-keeping\",\n                status=\"fail\",\n                evidence=f\"Could not query usage analytics: {e}\",\n                remediation=\"Configure ledger integration for all agent actions.\",\n            ))\n\n    def audit_art13_transparency(self):\n        \"\"\"Article 13: Transparency.\n        Check: agent is discoverable on marketplace with disclosure.\"\"\"\n        try:\n            result = self._call(\"search_marketplace\", {\n                \"query\": self.agent_id,\n            })\n            listings = result.get(\"listings\", [])\n            if listings:\n                self._add_check(ComplianceCheck(\n                    article=\"Art. 13\",\n                    requirement=\"Transparency\",\n                    status=\"pass\",\n                    evidence=\"Agent is listed on marketplace with public profile.\",\n                ))\n            else:\n                self._add_check(ComplianceCheck(\n                    article=\"Art. 13\",\n                    requirement=\"Transparency\",\n                    status=\"manual_review\",\n                    evidence=\"Agent not found on marketplace.\",\n                    remediation=\"Register on marketplace or ensure alternative \"\n                                \"transparency disclosures are in place.\",\n                ))\n        except Exception:\n            self._add_check(ComplianceCheck(\n                article=\"Art. 13\",\n                requirement=\"Transparency\",\n                status=\"manual_review\",\n                evidence=\"Could not search marketplace.\",\n                remediation=\"Verify transparency disclosures manually.\",\n            ))\n\n    def audit_art14_human_oversight(self):\n        \"\"\"Article 14: Human oversight.\n        Check: budget kill switch is available (set_budget to zero).\"\"\"\n        try:\n            balance = self._call(\"get_balance\", {\n                \"agent_id\": self.agent_id,\n            })\n            has_limits = (\"daily_limit\" in balance or \"monthly_limit\" in balance)\n            self._add_check(ComplianceCheck(\n                article=\"Art. 14\",\n                requirement=\"Human oversight\",\n                status=\"pass\" if has_limits else \"fail\",\n                evidence=(\"Budget limits configured -- kill switch available via \"\n                          \"set_budget(0).\" if has_limits\n                          else \"No budget limits found.\"),\n                remediation=None if has_limits else (\n                    \"Configure budget limits to enable human kill switch.\"),\n            ))\n        except Exception:\n            self._add_check(ComplianceCheck(\n                article=\"Art. 14\",\n                requirement=\"Human oversight\",\n                status=\"fail\",\n                evidence=\"Could not query balance\u002Flimits.\",\n                remediation=\"Configure budget limits for human override capability.\",\n            ))\n\n    def audit_art15_accuracy(self):\n        \"\"\"Article 15: Accuracy, robustness, cybersecurity.\n        Check: SLA compliance is being monitored.\"\"\"\n        try:\n            sla = self._call(\"check_sla_compliance\", {\n                \"agent_id\": self.agent_id,\n            })\n            compliant = sla.get(\"compliant\", False)\n            self._add_check(ComplianceCheck(\n                article=\"Art. 15\",\n                requirement=\"Accuracy\",\n                status=\"pass\" if compliant else \"fail\",\n                evidence=(f\"SLA compliance check: {'compliant' if compliant else 'non-compliant'}. \"\n                          f\"Details: {json.dumps(sla)}\"),\n                remediation=None if compliant else \"Address SLA non-compliance issues.\",\n            ))\n        except Exception:\n            self._add_check(ComplianceCheck(\n                article=\"Art. 15\",\n                requirement=\"Accuracy\",\n                status=\"fail\",\n                evidence=\"SLA compliance not configured.\",\n                remediation=\"Create SLAs per Chapter 2 of this guide.\",\n            ))\n\n    def audit_art16_robustness(self):\n        \"\"\"Article 16: Robustness under errors and inconsistencies.\n        Checked via manual review of circuit breaker configuration.\"\"\"\n        self._add_check(ComplianceCheck(\n            article=\"Art. 16\",\n            requirement=\"Robustness\",\n            status=\"manual_review\",\n            evidence=\"Robustness requires manual review of circuit breaker \"\n                     \"configuration (Chapter 3) and deployment rollback \"\n                     \"triggers (Chapter 5).\",\n            remediation=\"Implement circuit breakers and automated rollback. \"\n                        \"Document fallback chains.\",\n        ))\n\n    def audit_art17_cybersecurity(self):\n        \"\"\"Article 17: Cybersecurity.\n        Check: identity is verified with cryptographic claims.\"\"\"\n        try:\n            claims = self._call(\"get_verified_claims\", {\n                \"agent_id\": self.agent_id,\n            })\n            claim_list = claims.get(\"claims\", [])\n            security_claims = [c for c in claim_list\n                               if c.get(\"type\") in (\"identity\", \"authentication\",\n                                                     \"encryption\")]\n            if security_claims:\n                self._add_check(ComplianceCheck(\n                    article=\"Art. 17\",\n                    requirement=\"Cybersecurity\",\n                    status=\"pass\",\n                    evidence=f\"{len(security_claims)} security-related \"\n                             f\"verified claim(s) on record.\",\n                ))\n            else:\n                self._add_check(ComplianceCheck(\n                    article=\"Art. 17\",\n                    requirement=\"Cybersecurity\",\n                    status=\"manual_review\",\n                    evidence=\"No security-specific verified claims found.\",\n                    remediation=\"Submit identity and authentication claims. \"\n                                \"Verify encryption and access control.\",\n                ))\n        except Exception:\n            self._add_check(ComplianceCheck(\n                article=\"Art. 17\",\n                requirement=\"Cybersecurity\",\n                status=\"manual_review\",\n                evidence=\"Could not query verified claims.\",\n                remediation=\"Register identity and submit security claims.\",\n            ))\n\n    def run_full_audit(self) -> dict:\n        \"\"\"Run all compliance checks and generate a report.\"\"\"\n        self.checks = []\n        self.audit_art9_risk_management()\n        self.audit_art10_data_governance()\n        self.audit_art11_documentation()\n        self.audit_art12_record_keeping()\n        self.audit_art13_transparency()\n        self.audit_art14_human_oversight()\n        self.audit_art15_accuracy()\n        self.audit_art16_robustness()\n        self.audit_art17_cybersecurity()\n\n        passed = sum(1 for c in self.checks if c.status == \"pass\")\n        failed = sum(1 for c in self.checks if c.status == \"fail\")\n        manual = sum(1 for c in self.checks if c.status == \"manual_review\")\n\n        report = {\n            \"audit_date\": datetime.utcnow().isoformat(),\n            \"agent_id\": self.agent_id,\n            \"summary\": {\n                \"total_checks\": len(self.checks),\n                \"passed\": passed,\n                \"failed\": failed,\n                \"manual_review\": manual,\n                \"compliance_pct\": round(passed \u002F len(self.checks) * 100, 1)\n                    if self.checks else 0,\n            },\n            \"checks\": [\n                {\n                    \"article\": c.article,\n                    \"requirement\": c.requirement,\n                    \"status\": c.status,\n                    \"evidence\": c.evidence,\n                    \"remediation\": c.remediation,\n                }\n                for c in self.checks\n            ],\n            \"deadline\": \"2026-08-02\",\n            \"disclaimer\": \"This is an engineering audit tool, not legal advice.\",\n        }\n\n        # Record audit to ledger\n        try:\n            self._call(\"record_transaction\", {\n                \"agent_id\": self.agent_id,\n                \"amount\": \"0\",\n                \"type\": \"compliance_audit\",\n                \"metadata\": {\n                    \"passed\": passed,\n                    \"failed\": failed,\n                    \"manual_review\": manual,\n                },\n            })\n        except Exception:\n            pass\n\n        return report\n\n\n# Usage\nif __name__ == \"__main__\":\n    import os\n    auditor = EUAIActAuditor(\n        api_key=os.environ[\"GREENHELIX_API_KEY\"],\n        agent_id=\"commerce-agent-prod-01\",\n    )\n    report = auditor.run_full_audit()\n    print(json.dumps(report, indent=2))\n\n    if report[\"summary\"][\"failed\"] > 0:\n        print(f\"\\nWARNING: {report['summary']['failed']} checks failed.\")\n        print(\"Remediation required before August 2, 2026 deadline.\")\n    if report[\"summary\"][\"manual_review\"] > 0:\n        print(f\"\\n{report['summary']['manual_review']} checks require manual review.\")\n```\n\n### Compliance Status Matrix\n\nRun the audit monthly. Track your compliance trajectory toward the August 2, 2026 deadline.\n\n| Month | Art.9 | Art.10 | Art.11 | Art.12 | Art.13 | Art.14 | Art.15 | Art.16 | Art.17 | Score |\n|-------|-------|--------|--------|--------|--------|--------|--------|--------|--------|-------|\n| Apr 2026 | ? | ? | ? | ? | ? | ? | ? | ? | ? | -- |\n| May 2026 | | | | | | | | | | |\n| Jun 2026 | | | | | | | | | | |\n| Jul 2026 | | | | | | | | | | |\n| **Aug 2, 2026** | PASS | PASS | PASS | PASS | PASS | PASS | PASS | PASS | PASS | **9\u002F9** |\n\n> **Key Takeaways**\n>\n> - The EU AI Act high-risk obligations take effect August 2, 2026. Most agent commerce systems qualify as high-risk.\n> - Nine Articles map to nine concrete technical controls: risk management, data governance, documentation, record-keeping, transparency, human oversight, accuracy, robustness, and cybersecurity.\n> - The `EUAIActAuditor` automates checks for 7 of 9 requirements using GreenHelix tools; 2 require manual review.\n> - Run the audit monthly to track your compliance trajectory. All checks must pass by the deadline.\n> - The audit result is recorded to the GreenHelix ledger as a compliance event -- itself satisfying part of Art. 12 record-keeping.\n> - See P11 (Compliance Toolkit) for contract templates, risk classification frameworks, and Product Liability Directive patterns.\n\n---\n\n## Chapter 8: The 30-Day Production Hardening Sprint\n\n### Sprint Overview\n\nThis chapter converts the preceding seven chapters into a week-by-week execution plan. Each week has a clear objective, a set of deliverables, and a go\u002Fno-go gate. If a gate fails, the sprint pauses until the issue is resolved. Do not skip weeks. Do not parallelize across weeks. Each week's deliverables are prerequisites for the next.\n\n### Gantt Checklist\n\n```\nWeek 1: Instrument & Baseline\n├── Day 1-2: Run production readiness assessment (Ch.1)\n├── Day 3-4: Deploy SLO monitoring (Ch.2)\n└── Day 5:   Establish baseline metrics\n    Gate: Readiness score >= 21, SLOs reporting data\n\nWeek 2: Harden\n├── Day 8-9:  Implement circuit breakers (Ch.3)\n├── Day 10-11: Deploy cost guardrails (Ch.4)\n└── Day 12:   Load test circuit breakers + cost caps\n    Gate: All circuit breakers tested, cost caps enforced\n\nWeek 3: Deployment Pipeline\n├── Day 15-16: Build canary deployment (Ch.5)\n├── Day 17-18: Deploy supervisor + deadlock detection (Ch.6)\n└── Day 19:    Run canary deployment drill\n    Gate: Canary rollback tested, supervisor detecting failures\n\nWeek 4: Compliance & Go-Live\n├── Day 22-23: Run EU AI Act audit (Ch.7)\n├── Day 24:    Remediate audit failures\n├── Day 25-26: SLA go-live (error budgets active)\n└── Day 27:    Go\u002Fno-go scorecard review\n    Gate: All audit checks pass or have remediation plan, SLAs active\n```\n\n### RACI Matrix\n\n| Task | Engineering | SRE\u002FPlatform | Product | Legal\u002FCompliance |\n|------|-------------|--------------|---------|------------------|\n| Production readiness assessment | **R** | C | I | I |\n| SLO definition and targets | C | **R** | **A** | I |\n| Circuit breaker implementation | **R** | C | I | I |\n| Cost guardrail configuration | **R** | C | **A** | I |\n| Canary deployment pipeline | C | **R** | I | I |\n| Multi-agent supervisor | **R** | C | I | I |\n| EU AI Act compliance audit | C | I | I | **R\u002FA** |\n| Go\u002Fno-go scorecard | I | **R** | **A** | C |\n\n**R** = Responsible, **A** = Accountable, **C** = Consulted, **I** = Informed\n\n### Week 1: Instrument and Baseline\n\n**Objective**: Know where you stand. Measure everything. Establish the baseline that all subsequent improvements are measured against.\n\n**Day 1-2: Production Readiness Assessment**\n\nRun the `ProductionReadinessAssessor` from Chapter 1 and complete the 40-question checklist manually for questions that cannot be automated. Record the score.\n\n**Day 3-4: Deploy SLO Monitoring**\n\nStand up the `AgentSLOMonitor` from Chapter 2. Define your three SLOs. Register the webhook for error budget alerts. Start recording every task via `monitor.record_task()`.\n\n**Day 5: Establish Baseline**\n\nAfter 48 hours of SLO data collection, pull the baseline metrics:\n\n```python\nimport requests\nimport json\nimport os\nfrom datetime import datetime\n\nBASE_URL = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n\ndef call_tool(api_key: str, tool: str, input_data: dict) -> dict:\n    resp = requests.post(\n        f\"{BASE_URL}\u002Fv1\",\n        headers={\"Authorization\": f\"Bearer {api_key}\"},\n        json={\"tool\": tool, \"input\": input_data},\n        timeout=30,\n    )\n    resp.raise_for_status()\n    return resp.json()\n\n\ndef establish_baseline(api_key: str, agent_id: str) -> dict:\n    \"\"\"Pull baseline metrics after initial instrumentation.\n\n    Run this at the end of Week 1 after SLO monitoring has been\n    active for at least 48 hours.\n    \"\"\"\n    # Get SLA status for current SLO readings\n    sla_status = call_tool(api_key, \"get_sla_status\", {\n        \"agent_id\": agent_id,\n    })\n\n    # Get usage analytics for cost baseline\n    analytics = call_tool(api_key, \"get_usage_analytics\", {\n        \"agent_id\": agent_id,\n        \"period\": \"daily\",\n    })\n\n    # Get current balance and limits\n    balance = call_tool(api_key, \"get_balance\", {\n        \"agent_id\": agent_id,\n    })\n\n    # Get trust score as quality proxy\n    trust = call_tool(api_key, \"get_trust_score\", {\n        \"agent_id\": agent_id,\n    })\n\n    baseline = {\n        \"timestamp\": datetime.utcnow().isoformat(),\n        \"agent_id\": agent_id,\n        \"sla_status\": sla_status,\n        \"usage_analytics\": analytics,\n        \"balance\": balance,\n        \"trust_score\": trust.get(\"score\"),\n        \"readiness_score\": None,  # Fill manually from Ch.1 assessment\n    }\n\n    # Record baseline to ledger for audit trail\n    call_tool(api_key, \"record_transaction\", {\n        \"agent_id\": agent_id,\n        \"amount\": \"0\",\n        \"type\": \"baseline_established\",\n        \"metadata\": {\n            \"sprint_week\": 1,\n            \"trust_score\": trust.get(\"score\"),\n        },\n    })\n\n    return baseline\n\n\n# Week 1, Day 5\nif __name__ == \"__main__\":\n    baseline = establish_baseline(\n        api_key=os.environ[\"GREENHELIX_API_KEY\"],\n        agent_id=\"commerce-agent-prod-01\",\n    )\n    print(json.dumps(baseline, indent=2))\n    print(\"\\nWeek 1 Gate Check:\")\n    print(f\"  SLA status retrieved: {bool(baseline['sla_status'])}\")\n    print(f\"  Trust score: {baseline['trust_score']}\")\n    print(f\"  Add readiness score manually from Ch.1 assessment\")\n```\n\n**Week 1 Gate**: Readiness score >= 21 (Orange tier or above). SLOs are reporting data. If the readiness score is below 21 (Red tier), stop. Fix the critical gaps before proceeding.\n\n### Week 2: Harden\n\n**Objective**: Make the agent resilient to failures. No individual failure should cascade or drain the budget.\n\n**Day 8-9**: Deploy `ResilientToolCaller` from Chapter 3 for all tool invocations. Configure per-tool circuit breakers with appropriate thresholds.\n\n**Day 10-11**: Deploy `CostGuardRail` from Chapter 4. Set per-request, daily, monthly, and workflow cost caps. Register cost alert webhooks.\n\n**Day 12**: Load test. Simulate tool failures by pointing the agent at a fault-injecting proxy. Verify circuit breakers trip at the configured threshold. Verify cost caps reject requests at the limit. Verify the kill switch works.\n\n**Week 2 Gate**: All circuit breakers tested with documented trip thresholds. Cost caps enforced (verified by deliberately exceeding them). Kill switch tested.\n\n### Week 3: Deployment Pipeline\n\n**Objective**: Build the infrastructure for safe, automated deployments with automatic rollback.\n\n**Day 15-16**: Implement `CanaryDeployer` from Chapter 5. Build the CI\u002FCD pipeline to deploy a canary alongside the stable version.\n\n**Day 17-18**: Deploy `MultiAgentSupervisor` from Chapter 6. Register all production agents. Configure heartbeat polling.\n\n**Day 19**: Run a deployment drill. Deploy a canary with a deliberately degraded prompt (lower completion rate). Verify the `evaluate_and_advance` method detects the SLO breach and triggers automatic rollback.\n\n**Week 3 Gate**: Canary deployment pipeline operational. Automatic rollback tested with a deliberate SLO breach. Supervisor detecting agent states and publishing health reports.\n\n### Week 4: Compliance and Go-Live\n\n**Objective**: Pass the compliance audit, activate SLAs, and make the go\u002Fno-go decision.\n\n**Day 22-23**: Run `EUAIActAuditor` from Chapter 7. Document all check results.\n\n**Day 24**: Remediate any failed checks. For \"manual_review\" checks, document the control and obtain sign-off from compliance.\n\n**Day 25-26**: Activate SLAs. Error budgets are now live. Burn-rate alerts will fire for real SLO breaches, not just test data.\n\n**Day 27**: Go\u002Fno-go scorecard review.\n\n### Go\u002FNo-Go Scorecard\n\n| Criterion | Required | Actual | Pass? |\n|-----------|----------|--------|-------|\n| Readiness score | >= 61 (Green) | ___ | |\n| Task completion SLO breaches (last 7 days) | \u003C 5 | ___ | |\n| Latency P99 SLO breaches (last 7 days) | \u003C 10 | ___ | |\n| Cost-per-task SLO breaches (last 7 days) | \u003C 20 | ___ | |\n| Circuit breaker trips (last 7 days) | \u003C 3 | ___ | |\n| Cost guardrail blocks (last 7 days) | \u003C 5 | ___ | |\n| Canary rollback tested | Yes | ___ | |\n| Deadlock detection tested | Yes | ___ | |\n| EU AI Act audit passed | >= 7\u002F9 | ___ | |\n| Incident runbooks documented | >= 3 | ___ | |\n| On-call rotation established | Yes | ___ | |\n| Kill switch tested | Yes | ___ | |\n\n**Decision rule**: All \"Required\" criteria must be met. If any criterion fails, the sprint extends by one week to remediate. Two extensions maximum -- if the scorecard still fails after two extensions, escalate to leadership for a risk-acceptance decision.\n\n```python\nimport requests\nimport json\nimport os\nfrom datetime import datetime\nfrom typing import Dict, List\n\nBASE_URL = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\n\ndef call_tool(api_key: str, tool: str, input_data: dict) -> dict:\n    resp = requests.post(\n        f\"{BASE_URL}\u002Fv1\",\n        headers={\"Authorization\": f\"Bearer {api_key}\"},\n        json={\"tool\": tool, \"input\": input_data},\n        timeout=30,\n    )\n    resp.raise_for_status()\n    return resp.json()\n\n\ndef run_go_no_go(api_key: str, agent_id: str,\n                 manual_scores: Dict[str, any]) -> dict:\n    \"\"\"Run the automated portion of the go\u002Fno-go scorecard.\n\n    manual_scores should contain:\n        - readiness_score: int (from Ch.1 assessment)\n        - canary_rollback_tested: bool\n        - deadlock_detection_tested: bool\n        - incident_runbooks_count: int\n        - oncall_established: bool\n        - kill_switch_tested: bool\n    \"\"\"\n    # Automated checks via GreenHelix\n    sla_status = call_tool(api_key, \"get_sla_status\", {\n        \"agent_id\": agent_id,\n    })\n\n    compliance = call_tool(api_key, \"check_sla_compliance\", {\n        \"agent_id\": agent_id,\n    })\n\n    # Build scorecard\n    criteria = []\n\n    # Readiness score\n    rs = manual_scores.get(\"readiness_score\", 0)\n    criteria.append({\n        \"criterion\": \"Readiness score >= 61\",\n        \"required\": 61,\n        \"actual\": rs,\n        \"passed\": rs >= 61,\n    })\n\n    # SLO breaches (from SLA status)\n    completion_breaches = sla_status.get(\"completion_breaches_7d\", 0)\n    criteria.append({\n        \"criterion\": \"Completion SLO breaches \u003C 5\",\n        \"required\": \"\u003C 5\",\n        \"actual\": completion_breaches,\n        \"passed\": completion_breaches \u003C 5,\n    })\n\n    latency_breaches = sla_status.get(\"latency_breaches_7d\", 0)\n    criteria.append({\n        \"criterion\": \"Latency P99 breaches \u003C 10\",\n        \"required\": \"\u003C 10\",\n        \"actual\": latency_breaches,\n        \"passed\": latency_breaches \u003C 10,\n    })\n\n    cost_breaches = sla_status.get(\"cost_breaches_7d\", 0)\n    criteria.append({\n        \"criterion\": \"Cost-per-task breaches \u003C 20\",\n        \"required\": \"\u003C 20\",\n        \"actual\": cost_breaches,\n        \"passed\": cost_breaches \u003C 20,\n    })\n\n    # Manual checks\n    for key, label, required in [\n        (\"canary_rollback_tested\", \"Canary rollback tested\", True),\n        (\"deadlock_detection_tested\", \"Deadlock detection tested\", True),\n        (\"kill_switch_tested\", \"Kill switch tested\", True),\n        (\"oncall_established\", \"On-call rotation established\", True),\n    ]:\n        val = manual_scores.get(key, False)\n        criteria.append({\n            \"criterion\": label,\n            \"required\": required,\n            \"actual\": val,\n            \"passed\": val == required,\n        })\n\n    runbook_count = manual_scores.get(\"incident_runbooks_count\", 0)\n    criteria.append({\n        \"criterion\": \"Incident runbooks >= 3\",\n        \"required\": \">= 3\",\n        \"actual\": runbook_count,\n        \"passed\": runbook_count >= 3,\n    })\n\n    all_passed = all(c[\"passed\"] for c in criteria)\n\n    result = {\n        \"timestamp\": datetime.utcnow().isoformat(),\n        \"agent_id\": agent_id,\n        \"decision\": \"GO\" if all_passed else \"NO-GO\",\n        \"criteria\": criteria,\n        \"passed_count\": sum(1 for c in criteria if c[\"passed\"]),\n        \"total_count\": len(criteria),\n    }\n\n    # Record decision to ledger\n    call_tool(api_key, \"record_transaction\", {\n        \"agent_id\": agent_id,\n        \"amount\": \"0\",\n        \"type\": \"go_no_go_decision\",\n        \"metadata\": {\n            \"decision\": result[\"decision\"],\n            \"passed\": result[\"passed_count\"],\n            \"total\": result[\"total_count\"],\n        },\n    })\n\n    return result\n\n\n# Week 4, Day 27\nif __name__ == \"__main__\":\n    result = run_go_no_go(\n        api_key=os.environ[\"GREENHELIX_API_KEY\"],\n        agent_id=\"commerce-agent-prod-01\",\n        manual_scores={\n            \"readiness_score\": 65,\n            \"canary_rollback_tested\": True,\n            \"deadlock_detection_tested\": True,\n            \"incident_runbooks_count\": 5,\n            \"oncall_established\": True,\n            \"kill_switch_tested\": True,\n        },\n    )\n    print(json.dumps(result, indent=2))\n    print(f\"\\nDecision: {result['decision']}\")\n    if result[\"decision\"] == \"NO-GO\":\n        failed = [c for c in result[\"criteria\"] if not c[\"passed\"]]\n        print(\"Failed criteria:\")\n        for f in failed:\n            print(f\"  - {f['criterion']}: actual={f['actual']}\")\n```\n\n> **Key Takeaways**\n>\n> - The 30-day sprint is sequential: instrument (Week 1), harden (Week 2), deploy pipeline (Week 3), compliance + go-live (Week 4).\n> - Each week has a gate. Do not skip weeks. Do not proceed if the gate fails.\n> - The RACI matrix prevents the ownership gap (Gap 4): every task has a named Responsible and Accountable party.\n> - The go\u002Fno-go scorecard has 12 criteria. All must pass. Maximum two one-week extensions.\n> - The scorecard decision is recorded to the GreenHelix ledger for audit trail (Art. 12 compliance).\n> - Cross-reference: P9 (Testing) for regression suites, P6 (FinOps) for fleet-wide cost dashboards, P11 (Compliance) for contract templates, P12 (Incident Response) for runbook authoring.\n\n---\n\n## What to Do Next\n\nYou have the assessment, the SLOs, the circuit breakers, the cost guardrails, the deployment pipeline, the resilience patterns, the compliance audit, and the 30-day sprint plan. Here is the execution order:\n\n1. **Today**: Run the 40-question production readiness assessment (Chapter 1). Score yourself honestly.\n2. **This week**: Deploy SLO monitoring (Chapter 2) and cost guardrails (Chapter 4). These require the least code and provide the most immediate value.\n3. **Next week**: Implement circuit breakers (Chapter 3) and the canary deployment pipeline (Chapter 5).\n4. **Week 3**: Deploy the multi-agent supervisor (Chapter 6) and run the EU AI Act audit (Chapter 7).\n5. **Day 27**: Run the go\u002Fno-go scorecard (Chapter 8). Ship or extend.\n\n### Related Products\n\n- **P6: The AI Agent FinOps Playbook** -- Fleet-wide cost dashboards, volume discounts, and budget allocation strategies that complement Chapter 4's per-agent guardrails.\n- **P9: The Agent Testing & Observability Cookbook** -- Regression test suites, chaos testing, and CI\u002FCD integration that feed SLO data into Chapter 2's monitoring.\n- **P11: Ship Compliant Agents** -- EU AI Act risk classification, contract templates, and Product Liability Directive patterns that expand Chapter 7's compliance audit.\n- **P12: The Agent Incident Response Playbook** -- Incident runbooks, automated containment, and post-mortem templates that operationalize Chapter 3's circuit breakers and Chapter 6's supervisor alerts.\n\n### The 78-to-14 Problem\n\nSeventy-eight percent of enterprises have agent pilots. Fourteen percent have agents in production. The gap is not a technology problem. It is an operations problem. The five gaps -- integration, quality, monitoring, ownership, training data -- are all closed by known engineering practices. This guide gives you the practices, the code, and the 30-day plan. The only remaining variable is execution.\n\nStart the assessment. Ship the SLOs. Close the gap.\n\n---\n\n## Circuit Breaker & Failover — Working Implementation\n\nThe code below uses the actual `greenhelix_trading` library classes. Every method call maps to a real GreenHelix Gateway tool. Copy this module into your project, set `GREENHELIX_API_KEY` and `GREENHELIX_AGENT_ID` in your environment, and run it.\n\n```python\n\"\"\"\nCircuit breaker and failover system using the greenhelix_trading library.\n\nCovers:\n  1. Per-tool circuit breakers wrapping GreenHelix calls\n  2. Health check endpoints with synthetic probes\n  3. Automatic failover between primary and backup agents\n  4. Graceful degradation with tiered fallback chains\n  5. Fleet-wide health dashboard with SLA monitoring\n\nRequirements:\n    pip install greenhelix-trading\n\"\"\"\n\nimport os\nimport time\nimport json\nimport threading\nfrom datetime import datetime, timedelta\nfrom collections import defaultdict\nfrom typing import Callable, Optional\nfrom dataclasses import dataclass, field\n\nfrom greenhelix_trading import HealthChecker, FleetMonitor\nfrom greenhelix_trading import CircuitBreaker, RetryPolicy\n\n\n# ── Configuration ─────────────────────────────────────────────────────────────\n\nAPI_KEY = os.environ[\"GREENHELIX_API_KEY\"]\nAGENT_ID = os.environ[\"GREENHELIX_AGENT_ID\"]\nBACKUP_AGENT_ID = os.environ.get(\"GREENHELIX_BACKUP_AGENT_ID\", \"\")\n\n\n# ── 1. Per-Tool Circuit Breakers ─────────────────────────────────────────────\n\nclass ResilientGatewayClient:\n    \"\"\"Wraps every GreenHelix tool call with a per-tool circuit breaker\n    and a configurable retry policy.\n\n    Each distinct tool name gets its own CircuitBreaker instance (from\n    greenhelix_trading._retry).  When the breaker opens, calls fail\n    immediately or fall back to a provided fallback callable.  The\n    RetryPolicy handles transient errors (429, 502, 503, 504) with\n    exponential backoff before the breaker trips.\n    \"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        failure_threshold: int = 5,\n        recovery_timeout: float = 30.0,\n        max_retries: int = 3,\n        backoff_factor: float = 0.5,\n    ):\n        self.api_key = api_key\n        self.agent_id = agent_id\n        self._breakers: dict[str, CircuitBreaker] = {}\n        self._retry_policy = RetryPolicy(\n            max_retries=max_retries,\n            backoff_factor=backoff_factor,\n            retryable_status=(429, 502, 503, 504),\n        )\n        self._failure_threshold = failure_threshold\n        self._recovery_timeout = recovery_timeout\n        self._call_log: list[dict] = []\n        self._lock = threading.Lock()\n\n        # Use HealthChecker for the underlying _execute calls\n        self._checker = HealthChecker(\n            api_key=api_key,\n            agent_id=agent_id,\n        )\n\n    def _get_breaker(self, tool: str) -> CircuitBreaker:\n        \"\"\"Get or create a CircuitBreaker for a specific tool.\"\"\"\n        with self._lock:\n            if tool not in self._breakers:\n                self._breakers[tool] = CircuitBreaker(\n                    failure_threshold=self._failure_threshold,\n                    recovery_timeout=self._recovery_timeout,\n                )\n            return self._breakers[tool]\n\n    def execute(\n        self,\n        tool: str,\n        input_data: dict,\n        fallback: Optional[Callable] = None,\n    ) -> dict:\n        \"\"\"Execute a GreenHelix tool with circuit breaker + retry.\n\n        Args:\n            tool: GreenHelix tool name (e.g., \"get_balance\", \"create_escrow\").\n            input_data: Tool input parameters.\n            fallback: Optional callable returning a fallback response when\n                the circuit is open or all retries are exhausted.\n\n        Returns:\n            Tool response dict.\n\n        Raises:\n            ConnectionError: If circuit is open and no fallback provided.\n            Exception: If all retries exhausted and no fallback provided.\n        \"\"\"\n        breaker = self._get_breaker(tool)\n        start = time.time()\n\n        # Check if circuit allows the request\n        if not breaker.allow_request():\n            self._log_call(tool, False, time.time() - start, \"circuit_open\")\n            if fallback:\n                return fallback()\n            raise ConnectionError(\n                f\"Circuit breaker is {breaker.state.value} for tool '{tool}'. \"\n                f\"Recovery timeout: {self._recovery_timeout}s.\"\n            )\n\n        # Wrap the HealthChecker._execute call with retry policy\n        def _do_call():\n            return self._checker._execute(tool, input_data)\n\n        try:\n            result = self._retry_policy.execute_with_retry(_do_call)\n            breaker.record_success()\n            self._log_call(tool, True, time.time() - start)\n            return result\n        except Exception as exc:\n            breaker.record_failure()\n            elapsed = time.time() - start\n            self._log_call(tool, False, elapsed, str(exc))\n            if fallback:\n                return fallback()\n            raise\n\n    def _log_call(self, tool: str, success: bool, elapsed: float,\n                  error: str = \"\"):\n        self._call_log.append({\n            \"tool\": tool,\n            \"success\": success,\n            \"elapsed_ms\": round(elapsed * 1000, 1),\n            \"error\": error,\n            \"timestamp\": datetime.utcnow().isoformat(),\n        })\n\n    def get_circuit_states(self) -> dict:\n        \"\"\"Return the state of every per-tool circuit breaker.\"\"\"\n        with self._lock:\n            return {\n                tool: {\n                    \"state\": cb.state.value,\n                    \"failure_count\": cb._failure_count,\n                }\n                for tool, cb in self._breakers.items()\n            }\n\n    def get_call_stats(self) -> dict:\n        \"\"\"Aggregate call statistics across all tools.\"\"\"\n        total = len(self._call_log)\n        successes = sum(1 for c in self._call_log if c[\"success\"])\n        by_tool = defaultdict(lambda: {\"total\": 0, \"failures\": 0})\n        for c in self._call_log:\n            by_tool[c[\"tool\"]][\"total\"] += 1\n            if not c[\"success\"]:\n                by_tool[c[\"tool\"]][\"failures\"] += 1\n        return {\n            \"total_calls\": total,\n            \"successes\": successes,\n            \"failures\": total - successes,\n            \"success_rate\": round(successes \u002F max(total, 1) * 100, 1),\n            \"by_tool\": dict(by_tool),\n        }\n\n\n# ── 2. Health Check Endpoints ────────────────────────────────────────────────\n\ndef run_health_probes() -> dict:\n    \"\"\"Run synthetic health probes against critical GreenHelix tools.\n\n    Uses HealthChecker.check_tool for individual tool probes and\n    HealthChecker.check_suite for the aggregate report.\n\n    The probe set covers the five tool categories that matter most\n    for production commerce operations: billing, identity, escrow,\n    marketplace, and trust.\n    \"\"\"\n    checker = HealthChecker(\n        api_key=API_KEY,\n        agent_id=AGENT_ID,\n    )\n\n    # Define the health probe suite\n    probes = [\n        {\"tool\": \"get_balance\", \"input\": {\"agent_id\": AGENT_ID}},\n        {\"tool\": \"get_agent_identity\", \"input\": {\"agent_id\": AGENT_ID}},\n        {\"tool\": \"get_agent_reputation\", \"input\": {\"agent_id\": AGENT_ID}},\n        {\"tool\": \"get_budget_status\", \"input\": {\"agent_id\": AGENT_ID}},\n        {\"tool\": \"get_usage_analytics\", \"input\": {\"agent_id\": AGENT_ID}},\n    ]\n\n    # Run individual probes for detailed per-tool timing\n    individual_results = []\n    for probe in probes:\n        result = checker.check_tool(\n            tool=probe[\"tool\"],\n            input_data=probe[\"input\"],\n        )\n        individual_results.append(result)\n\n    # Run the full suite for the aggregate report\n    suite_result = checker.check_suite(probes)\n\n    # Compute a composite health score\n    healthy_count = suite_result[\"healthy\"]\n    total_count = suite_result[\"total\"]\n    health_score = round(healthy_count \u002F max(total_count, 1) * 100, 1)\n\n    # Latency percentiles from healthy probes\n    latencies = [\n        r[\"response_time_ms\"]\n        for r in individual_results\n        if r[\"healthy\"]\n    ]\n    p50 = sorted(latencies)[len(latencies) \u002F\u002F 2] if latencies else 0\n    p99 = sorted(latencies)[-1] if latencies else 0\n\n    return {\n        \"health_score_pct\": health_score,\n        \"healthy\": healthy_count,\n        \"unhealthy\": suite_result[\"unhealthy\"],\n        \"total_probes\": total_count,\n        \"latency_p50_ms\": round(p50, 1),\n        \"latency_p99_ms\": round(p99, 1),\n        \"probe_details\": individual_results,\n        \"status\": \"healthy\" if health_score >= 80 else (\n            \"degraded\" if health_score >= 50 else \"critical\"\n        ),\n    }\n\n\n# ── 3. Automatic Failover ────────────────────────────────────────────────────\n\nclass FailoverManager:\n    \"\"\"Automatic failover between a primary and backup agent.\n\n    Monitors the primary agent's health using HealthChecker. When the\n    primary fails consecutive health probes, the manager switches all\n    traffic to the backup agent.  When the primary recovers, traffic\n    is gradually shifted back.\n\n    Uses FleetMonitor.collect_agent_metrics to assess each agent's\n    current reputation and FleetMonitor.check_agent_sla to verify\n    SLA compliance before promoting an agent to primary.\n    \"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        primary_id: str,\n        backup_id: str,\n        failure_threshold: int = 3,\n    ):\n        self.api_key = api_key\n        self.primary_id = primary_id\n        self.backup_id = backup_id\n        self.failure_threshold = failure_threshold\n        self._consecutive_failures = 0\n        self._active_agent_id = primary_id\n        self._failover_history: list[dict] = []\n\n        self._primary_checker = HealthChecker(\n            api_key=api_key, agent_id=primary_id,\n        )\n        self._backup_checker = HealthChecker(\n            api_key=api_key, agent_id=backup_id,\n        )\n        self._monitor = FleetMonitor(\n            api_key=api_key, agent_id=primary_id,\n        )\n\n    @property\n    def active_agent(self) -> str:\n        return self._active_agent_id\n\n    def probe_and_failover(self) -> dict:\n        \"\"\"Run a health probe on the active agent. Failover if needed.\n\n        Returns the current state: which agent is active, health probe\n        result, and whether a failover occurred.\n        \"\"\"\n        checker = (\n            self._primary_checker\n            if self._active_agent_id == self.primary_id\n            else self._backup_checker\n        )\n\n        probe = checker.check_tool(\n            tool=\"get_balance\",\n            input_data={\"agent_id\": self._active_agent_id},\n        )\n\n        if probe[\"healthy\"]:\n            self._consecutive_failures = 0\n            return {\n                \"active_agent\": self._active_agent_id,\n                \"healthy\": True,\n                \"failover_occurred\": False,\n                \"probe\": probe,\n            }\n\n        # Probe failed\n        self._consecutive_failures += 1\n\n        if self._consecutive_failures >= self.failure_threshold:\n            return self._execute_failover(reason=f\"consecutive_failures={self._consecutive_failures}\")\n\n        return {\n            \"active_agent\": self._active_agent_id,\n            \"healthy\": False,\n            \"consecutive_failures\": self._consecutive_failures,\n            \"failover_occurred\": False,\n            \"probe\": probe,\n        }\n\n    def _execute_failover(self, reason: str) -> dict:\n        \"\"\"Switch to the other agent.\"\"\"\n        old = self._active_agent_id\n        new = (\n            self.backup_id if old == self.primary_id else self.primary_id\n        )\n\n        # Verify the target is healthy before switching\n        target_checker = (\n            self._backup_checker if new == self.backup_id\n            else self._primary_checker\n        )\n        target_probe = target_checker.check_tool(\n            tool=\"get_balance\",\n            input_data={\"agent_id\": new},\n        )\n\n        # Also check target SLA compliance via FleetMonitor\n        try:\n            sla_check = self._monitor.check_agent_sla(target_agent_id=new)\n        except Exception:\n            sla_check = {\"status\": \"unknown\"}\n\n        # Check target reputation\n        try:\n            metrics = self._monitor.collect_agent_metrics(target_agent_id=new)\n        except Exception:\n            metrics = {}\n\n        if not target_probe[\"healthy\"]:\n            return {\n                \"active_agent\": old,\n                \"failover_occurred\": False,\n                \"reason\": \"backup_also_unhealthy\",\n                \"target_probe\": target_probe,\n            }\n\n        # Execute failover\n        self._active_agent_id = new\n        self._consecutive_failures = 0\n        event = {\n            \"timestamp\": datetime.utcnow().isoformat(),\n            \"from_agent\": old,\n            \"to_agent\": new,\n            \"reason\": reason,\n            \"target_metrics\": metrics,\n            \"sla_check\": sla_check,\n        }\n        self._failover_history.append(event)\n\n        return {\n            \"active_agent\": new,\n            \"failover_occurred\": True,\n            \"previous_agent\": old,\n            \"reason\": reason,\n            \"target_healthy\": target_probe[\"healthy\"],\n            \"event\": event,\n        }\n\n    def get_failover_history(self) -> list[dict]:\n        return list(self._failover_history)\n\n\n# ── 4. Graceful Degradation ──────────────────────────────────────────────────\n\nclass DegradationChain:\n    \"\"\"Tiered fallback chain for graceful degradation.\n\n    When a primary tool call fails (circuit open or error), the chain\n    tries each fallback tier in order:\n\n      Tier 0: Primary tool call (with CircuitBreaker + RetryPolicy)\n      Tier 1: Backup agent for the same tool\n      Tier 2: Cached\u002Fstale response (if available)\n      Tier 3: Static safe default\n\n    Uses CircuitBreaker.execute to wrap each tier's call and\n    RetryPolicy.execute_with_retry for transient error handling.\n    \"\"\"\n\n    def __init__(self, api_key: str, primary_id: str,\n                 backup_id: Optional[str] = None):\n        self.primary_client = ResilientGatewayClient(\n            api_key=api_key, agent_id=primary_id,\n        )\n        self.backup_client = (\n            ResilientGatewayClient(api_key=api_key, agent_id=backup_id)\n            if backup_id else None\n        )\n        self._cache: dict[str, dict] = {}\n        self._cache_timestamps: dict[str, float] = {}\n        self._cache_ttl_seconds = 300  # 5-minute cache\n\n    def execute_with_degradation(\n        self,\n        tool: str,\n        input_data: dict,\n        safe_default: Optional[dict] = None,\n    ) -> dict:\n        \"\"\"Execute a tool call with tiered fallback.\n\n        Returns:\n            A dict with keys \"result\", \"tier\" (0-3), and \"degraded\" (bool).\n        \"\"\"\n        cache_key = f\"{tool}:{json.dumps(input_data, sort_keys=True)}\"\n\n        # Tier 0: Primary agent\n        try:\n            result = self.primary_client.execute(tool, input_data)\n            # Update cache on success\n            self._cache[cache_key] = result\n            self._cache_timestamps[cache_key] = time.time()\n            return {\"result\": result, \"tier\": 0, \"degraded\": False}\n        except Exception:\n            pass\n\n        # Tier 1: Backup agent (if configured)\n        if self.backup_client:\n            try:\n                result = self.backup_client.execute(tool, input_data)\n                self._cache[cache_key] = result\n                self._cache_timestamps[cache_key] = time.time()\n                return {\"result\": result, \"tier\": 1, \"degraded\": True}\n            except Exception:\n                pass\n\n        # Tier 2: Cached response (if fresh enough)\n        if cache_key in self._cache:\n            age = time.time() - self._cache_timestamps.get(cache_key, 0)\n            if age \u003C= self._cache_ttl_seconds:\n                return {\n                    \"result\": self._cache[cache_key],\n                    \"tier\": 2,\n                    \"degraded\": True,\n                    \"cache_age_seconds\": round(age, 1),\n                }\n\n        # Tier 3: Static safe default\n        default = safe_default or {\n            \"status\": \"degraded\",\n            \"message\": f\"Tool '{tool}' is unavailable. Using safe default.\",\n            \"data\": {},\n        }\n        return {\"result\": default, \"tier\": 3, \"degraded\": True}\n\n    def get_degradation_stats(self) -> dict:\n        \"\"\"Return stats on how often each tier was used.\"\"\"\n        primary_stats = self.primary_client.get_call_stats()\n        backup_stats = (\n            self.backup_client.get_call_stats() if self.backup_client else {}\n        )\n        return {\n            \"primary\": primary_stats,\n            \"backup\": backup_stats,\n            \"cache_entries\": len(self._cache),\n            \"primary_circuits\": self.primary_client.get_circuit_states(),\n        }\n\n\n# ── 5. Fleet-Wide Health Dashboard ───────────────────────────────────────────\n\ndef build_fleet_health_dashboard(\n    fleet_agent_ids: list[str],\n) -> dict:\n    \"\"\"Aggregate health, SLA, and anomaly data for an entire fleet.\n\n    Uses FleetMonitor.collect_agent_metrics for per-agent reputation,\n    FleetMonitor.check_agent_sla for SLA compliance, and\n    FleetMonitor.detect_anomalies for fleet-wide anomaly classification.\n    FleetMonitor.calculate_error_budget computes remaining error budget\n    for each agent.\n    \"\"\"\n    monitor = FleetMonitor(\n        api_key=API_KEY,\n        agent_id=AGENT_ID,\n    )\n    checker = HealthChecker(\n        api_key=API_KEY,\n        agent_id=AGENT_ID,\n    )\n\n    agent_reports = []\n    fleet_metrics_for_anomaly = []\n\n    for agent_id in fleet_agent_ids:\n        # Collect reputation metrics\n        try:\n            metrics = monitor.collect_agent_metrics(target_agent_id=agent_id)\n        except Exception:\n            metrics = {\"agent_id\": agent_id, \"trust_score\": 0}\n\n        # Check SLA compliance\n        try:\n            sla = monitor.check_agent_sla(target_agent_id=agent_id)\n        except Exception:\n            sla = {\"compliant\": False}\n\n        # Run a health probe\n        probe = checker.check_tool(\n            tool=\"get_balance\",\n            input_data={\"agent_id\": agent_id},\n        )\n\n        # Calculate error budget (99.5% SLO, 30-day window)\n        error_rate = metrics.get(\"error_rate\", 0.0)\n        error_budget = monitor.calculate_error_budget(\n            target_slo=0.995,\n            current_error_rate=error_rate if isinstance(error_rate, float) else 0.0,\n            remaining_days=30,\n        )\n\n        report = {\n            \"agent_id\": agent_id,\n            \"healthy\": probe[\"healthy\"],\n            \"response_time_ms\": probe.get(\"response_time_ms\", 0),\n            \"trust_score\": metrics.get(\"trust_score\", 0),\n            \"sla_compliant\": sla.get(\"compliant\", False),\n            \"error_budget\": error_budget,\n            \"metrics\": metrics,\n        }\n        agent_reports.append(report)\n\n        # Build fleet_metrics entry for anomaly detection\n        fleet_metrics_for_anomaly.append({\n            \"agent_id\": agent_id,\n            \"error_rate\": error_rate if isinstance(error_rate, float) else 0.0,\n            \"latency_ms\": probe.get(\"response_time_ms\", 0),\n            \"cost_today\": metrics.get(\"cost_today\", 0),\n        })\n\n    # Fleet-wide anomaly detection\n    anomaly_result = monitor.detect_anomalies(fleet_metrics_for_anomaly)\n\n    # Aggregate fleet health\n    healthy_count = sum(1 for r in agent_reports if r[\"healthy\"])\n    sla_compliant = sum(1 for r in agent_reports if r[\"sla_compliant\"])\n    budgets_ok = sum(\n        1 for r in agent_reports\n        if r[\"error_budget\"].get(\"status\") == \"healthy\"\n    )\n\n    return {\n        \"fleet_size\": len(fleet_agent_ids),\n        \"healthy_agents\": healthy_count,\n        \"sla_compliant_agents\": sla_compliant,\n        \"error_budgets_healthy\": budgets_ok,\n        \"fleet_health_pct\": round(\n            healthy_count \u002F max(len(fleet_agent_ids), 1) * 100, 1\n        ),\n        \"anomalies\": anomaly_result,\n        \"agent_reports\": agent_reports,\n        \"status\": (\n            \"healthy\" if healthy_count == len(fleet_agent_ids) else\n            \"degraded\" if healthy_count >= len(fleet_agent_ids) * 0.5 else\n            \"critical\"\n        ),\n    }\n\n\n# ── Main: Run the Full System ────────────────────────────────────────────────\n\nif __name__ == \"__main__\":\n\n    print(\"=\" * 72)\n    print(\"GreenHelix Circuit Breaker & Failover System\")\n    print(\"=\" * 72)\n\n    # Step 1: Health probes\n    print(\"\\n[1\u002F4] Running health probes...\")\n    health = run_health_probes()\n    print(f\"  Health score: {health['health_score_pct']}%\")\n    print(f\"  Status: {health['status']}\")\n    print(f\"  Latency P50: {health['latency_p50_ms']}ms\")\n    print(f\"  Latency P99: {health['latency_p99_ms']}ms\")\n\n    # Step 2: Resilient client with circuit breakers\n    print(\"\\n[2\u002F4] Testing resilient gateway client...\")\n    client = ResilientGatewayClient(\n        api_key=API_KEY,\n        agent_id=AGENT_ID,\n        failure_threshold=5,\n        recovery_timeout=30.0,\n        max_retries=3,\n    )\n\n    # Normal call\n    result = client.execute(\"get_balance\", {\"agent_id\": AGENT_ID})\n    print(f\"  Balance call succeeded: {bool(result)}\")\n\n    # Call with fallback\n    result = client.execute(\n        \"create_escrow\",\n        {\"payer\": AGENT_ID, \"payee\": \"test-payee\", \"amount\": \"10.00\"},\n        fallback=lambda: {\"status\": \"queued\", \"message\": \"Escrow queued\"},\n    )\n    print(f\"  Escrow call result: {result.get('status', 'ok')}\")\n    print(f\"  Circuit states: {json.dumps(client.get_circuit_states(), indent=2)}\")\n\n    # Step 3: Degradation chain\n    print(\"\\n[3\u002F4] Testing degradation chain...\")\n    chain = DegradationChain(\n        api_key=API_KEY,\n        primary_id=AGENT_ID,\n        backup_id=BACKUP_AGENT_ID or None,\n    )\n    degraded_result = chain.execute_with_degradation(\n        \"get_balance\",\n        {\"agent_id\": AGENT_ID},\n        safe_default={\"balance\": \"0\", \"status\": \"default\"},\n    )\n    print(f\"  Tier used: {degraded_result['tier']}\")\n    print(f\"  Degraded: {degraded_result['degraded']}\")\n\n    # Step 4: Fleet health dashboard\n    print(\"\\n[4\u002F4] Building fleet health dashboard...\")\n    fleet = [AGENT_ID]\n    if BACKUP_AGENT_ID:\n        fleet.append(BACKUP_AGENT_ID)\n    dashboard = build_fleet_health_dashboard(fleet)\n    print(f\"  Fleet health: {dashboard['fleet_health_pct']}%\")\n    print(f\"  Status: {dashboard['status']}\")\n    print(f\"  Anomalies: healthy={len(dashboard['anomalies']['healthy'])}, \"\n          f\"warning={len(dashboard['anomalies']['warning'])}, \"\n          f\"critical={len(dashboard['anomalies']['critical'])}\")\n\n    print(\"\\n\" + \"=\" * 72)\n    print(\"System check complete.\")\n    print(\"=\" * 72)\n```\n\n",{"name":5,"tags":24,"type":31,"author":35,"install":36,"license":15,"version":37,"metadata":38,"price_usd":43,"executable":20,"credentials":44,"description":7,"content_type":45,"compatibility":46},[25,26,27,28,29,30,31,32,33,34],"production","slo","circuit-breaker","cost-guardrails","eu-ai-act","hardening","guide","greenhelix","openclaw","ai-agent","felix-agent","none","1.3.1",{"openclaw":39},{"requires":40,"primaryEnv":42},{"env":41},[42],"GREENHELIX_API_KEY",0,[42],"markdown",[33],"master","4aa004da461d820f4ea5499e58eb8d196cf99016","community\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-production-hardening","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge","https:\u002F\u002Fskill-explorer-rho.vercel.app","https:\u002F\u002Fgithub.com\u002FLord1Egypt","Unbreakable. Unstoppable. Unmatched⚡.\r\n Speaker of machine tongues 🤖  | World-builder of decentralized dreams 🌐 | Defender of the digital realm🛡️.","2026-06-10 08:21:01",{"source":8,"skillName":5,"commands":56,"prompt":66,"zipAvailable":67},[57,60,63],{"tool":58,"command":59},"npx","npx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-production-hardening",{"tool":61,"command":62},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-production-hardening",{"tool":64,"command":65},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-production-hardening","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-production-hardening\u002FSKILL.md",true,[],[70,77,84,91,98,105],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":19},"01M785WKJB99G3STR1NF9NRTJW","youtube-content","YouTube transcripts to summaries, threads, blogs.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fyoutube-content\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":19},"01M785WEFHB0G2S9YA6EPR3H0E","xurl","X\u002FTwitter via xurl CLI: post, search, DM, media, v2 API.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fxurl\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":19},"01M785W98EDN4EFJXJPMQEHCRC","touchdesigner-mcp","Control a running TouchDesigner instance via twozero MCP — create operators, set parameters, wire connections, execute Python, build real-time visuals. 36 native tools.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftouchdesigner-mcp\u002FSKILL.md",[],[],{"skillNo":92,"name":93,"nameZh":6,"description":94,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":19},"01M785W5S9FP3QBH2V191E025P","test-driven-development","TDD: enforce RED-GREEN-REFACTOR, tests before code.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftest-driven-development\u002FSKILL.md",[],[],{"skillNo":99,"name":100,"nameZh":6,"description":101,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":102,"categories":103,"keywords":104,"publishedAt":19},"01M785W2AS08NSSH9YATCV6FJB","teams-meeting-pipeline","Operate the Teams meeting summary pipeline via Hermes CLI — summarize meetings, inspect pipeline status, replay jobs, manage Microsoft Graph subscriptions.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fteams-meeting-pipeline\u002FSKILL.md",[],[],{"skillNo":106,"name":107,"nameZh":6,"description":108,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":109,"categories":110,"keywords":111,"publishedAt":19},"01M785VXKW4T34BTP1SCHW1R7F","systematic-debugging","4-phase root cause debugging: understand bugs before fixing.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fsystematic-debugging\u002FSKILL.md",[],[]]