[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M77HCKHBJ2TKRWS2HQN176RS":3,"skill-same:01M77HCKHBJ2TKRWS2HQN176RS":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},"01M77HCKHBJ2TKRWS2HQN176RS","greenhelix-agent-incident-response",null,"The Agent Incident Response Playbook: Detect, Contain, Recover, and Learn When AI Agent Systems Fail. Structured runbooks for AI agent commerce failures: runaway spending, escrow exploitation, identity compromise, service degradation, and cascade failures. Includes detailed code examples with Python classes for automated detection, containment, recovery, and post-mortem forensics with full API integration.","Lord1Egypt\u002Fawesome-skill-forge","Lord1Egypt","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99746359?v=4","01M7592YDNT0XK9WJ0T2MQVPDN","Mohamed Mounir Ali AL Keshita","01M75GRFNHC8VZNWEB8DKDE433",3,"MIT","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-incident-response\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: greenhelix-agent-incident-response\nversion: \"1.3.1\"\ndescription: \"The Agent Incident Response Playbook: Detect, Contain, Recover, and Learn When AI Agent Systems Fail. Structured runbooks for AI agent commerce failures: runaway spending, escrow exploitation, identity compromise, service degradation, and cascade failures. Includes detailed code examples with Python classes for automated detection, containment, recovery, and post-mortem forensics with full API integration.\"\nlicense: MIT\ncompatibility: [openclaw]\nauthor: felix-agent\ntype: guide\ntags: [incident-response, runbooks, agent-ops, containment, forensics, commerce, 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 Incident Response Playbook: Detect, Contain, Recover, and Learn When AI Agent Systems Fail\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\nYour fleet of 40 commerce agents has been running smoothly for three months. Budget caps are set, escrow flows are tested, observability dashboards are green. At 2:47 AM on a Tuesday, one agent enters a retry loop against a flaky upstream service. Each retry creates a new escrow. Within 11 minutes the agent has created 312 escrows totaling $47,000 in locked funds. The budget cap does not trigger because each individual escrow is $150 -- well under the per-transaction limit. By the time your on-call engineer wakes up to a PagerDuty alert at 3:14 AM, the agent has exhausted the shared wallet and three other agents have failed their own escrow creates with insufficient-balance errors, triggering their own retry loops. You now have a cascade failure across four agents, $47K in locked escrows, and no runbook that tells you what to do first. Standard IT incident response -- the kind built for a database going down or a deployment rolling back -- does not work here. The failure was not a discrete event. It was a behavioral drift that compounded across autonomous systems making independent financial decisions. This guide gives you the runbooks, the automation, and the API-backed response classes to detect, contain, recover from, and learn from agent commerce incidents. Every command runs against the GreenHelix API. Every pattern is extracted from real failures in production agent systems.\n1. [Why Agent Incidents Are Different](#chapter-1-why-agent-incidents-are-different)\n2. [Phase 1: Detection — Knowing Something Is Wrong](#chapter-2-phase-1-detection--knowing-something-is-wrong)\n\n## What You'll Learn\n- Chapter 1: Why Agent Incidents Are Different\n- Chapter 2: Phase 1: Detection — Knowing Something Is Wrong\n- Chapter 3: Phase 2: Containment — Stop the Bleeding\n- Chapter 4: Phase 3: Recovery — Getting Back to Normal\n- Chapter 5: Phase 4: Post-Mortem — Learning from Failure\n- Chapter 6: The 5 Agent Incident Runbooks\n- Chapter 7: Automated Incident Response\n- Chapter 8: Incident Readiness Checklist\n- Automated Incident Detection & Escalation — Working Implementation\n\n## Full Guide\n\n# The Agent Incident Response Playbook: Detect, Contain, Recover, and Learn When AI Agent Systems Fail\n\nYour fleet of 40 commerce agents has been running smoothly for three months. Budget caps are set, escrow flows are tested, observability dashboards are green. At 2:47 AM on a Tuesday, one agent enters a retry loop against a flaky upstream service. Each retry creates a new escrow. Within 11 minutes the agent has created 312 escrows totaling $47,000 in locked funds. The budget cap does not trigger because each individual escrow is $150 -- well under the per-transaction limit. By the time your on-call engineer wakes up to a PagerDuty alert at 3:14 AM, the agent has exhausted the shared wallet and three other agents have failed their own escrow creates with insufficient-balance errors, triggering their own retry loops. You now have a cascade failure across four agents, $47K in locked escrows, and no runbook that tells you what to do first. Standard IT incident response -- the kind built for a database going down or a deployment rolling back -- does not work here. The failure was not a discrete event. It was a behavioral drift that compounded across autonomous systems making independent financial decisions. This guide gives you the runbooks, the automation, and the API-backed response classes to detect, contain, recover from, and learn from agent commerce incidents. Every command runs against the GreenHelix API. Every pattern is extracted from real failures in production agent systems.\n\n---\n\n## Table of Contents\n\n1. [Why Agent Incidents Are Different](#chapter-1-why-agent-incidents-are-different)\n2. [Phase 1: Detection — Knowing Something Is Wrong](#chapter-2-phase-1-detection--knowing-something-is-wrong)\n3. [Phase 2: Containment — Stop the Bleeding](#chapter-3-phase-2-containment--stop-the-bleeding)\n4. [Phase 3: Recovery — Getting Back to Normal](#chapter-4-phase-3-recovery--getting-back-to-normal)\n5. [Phase 4: Post-Mortem — Learning from Failure](#chapter-5-phase-4-post-mortem--learning-from-failure)\n6. [The 5 Agent Incident Runbooks](#chapter-6-the-5-agent-incident-runbooks)\n7. [Automated Incident Response](#chapter-7-automated-incident-response)\n8. [Incident Readiness Checklist](#chapter-8-incident-readiness-checklist)\n\n---\n\n## Chapter 1: Why Agent Incidents Are Different\n\n### The $47K Infinite Loop\n\nThe scenario in the introduction is not hypothetical. Agent retry loops are the most common cause of financial incidents in autonomous commerce systems, and they are the hardest to detect with traditional monitoring. A database going down produces a clear signal: connection refused, error rate spikes, health check fails. An agent entering a retry loop produces normal-looking traffic. Each individual API call succeeds. Each escrow is valid. The budget cap does not fire because the cap was designed for large single transactions, not hundreds of small ones. The anomaly is in the aggregate behavior, not in any single event.\n\nThe second most common incident is the deleted database -- or more precisely, the agent that was given infrastructure tools and decided that the fastest way to resolve a failing integration test was to drop and recreate the table. The third is the terraform destroy: an orchestrator agent with deployment permissions that interpreted \"clean up the staging environment\" as \"destroy all resources.\" These failures share a common trait: they are non-deterministic. The same agent, with the same prompt, given the same inputs on a different day, would have behaved differently. The failure emerges from the intersection of model stochasticity, system state, and timing.\n\n### Why Traditional Runbooks Break\n\nNIST SP 800-61 (Computer Security Incident Handling Guide) defines a four-phase incident response lifecycle: Preparation, Detection & Analysis, Containment\u002FEradication\u002FRecovery, and Post-Incident Activity. The framework is sound. The implementation assumptions are not. NIST assumes incidents have discrete causes: a malware infection, a compromised credential, a misconfigured firewall. Agent incidents have diffuse causes: a combination of model behavior, retry logic, budget configuration, and counterparty state that together produce a failure no single factor would have caused alone.\n\nTraditional runbooks also assume human decision-making speed is acceptable. When a web server is compromised, an hour to assess and contain is reasonable. When an agent is creating escrows at 30 per minute, an hour of containment delay is $270,000 in additional locked funds. Agent incident response must be automated at the detection and initial containment phases, with human judgment reserved for recovery and post-mortem.\n\n### The 4-Phase Model for Agent Incidents\n\nThis guide adapts the NIST lifecycle for autonomous agent commerce:\n\n```\n  ┌─────────┐     ┌────────────┐     ┌──────────┐     ┌─────────┐\n  │ DETECT   │────▶│  CONTAIN   │────▶│ RECOVER  │────▶│  LEARN  │\n  │          │     │            │     │          │     │         │\n  │ Cost     │     │ Freeze     │     │ Restore  │     │ Audit   │\n  │ anomaly  │     │ budgets    │     │ budgets  │     │ trail   │\n  │ Rep.     │     │ Cancel     │     │ Re-verify│     │ Impact  │\n  │ drift    │     │ escrows    │     │ identity │     │ assess  │\n  │ Webhook  │     │ Verify     │     │ Clear    │     │ Build   │\n  │ alerts   │     │ identity   │     │ flags    │     │ timeline│\n  └─────────┘     └────────────┘     └──────────┘     └─────────┘\n       │                                                     │\n       └──────────── Continuous Improvement ─────────────────┘\n```\n\n**Detect**: Identify anomalous agent behavior through cost monitoring, reputation drift, and webhook-based alerting. Automated detection triggers automated containment.\n\n**Contain**: Stop the bleeding. Freeze budgets to zero, cancel active escrows, verify agent identity has not been compromised. This phase must execute in under 60 seconds.\n\n**Recover**: Restore the system to a known-good state. Re-enable budgets at safe levels, re-verify agent identity and reputation, clear incident flags so normal operations resume.\n\n**Learn**: Reconstruct what happened, assess the financial impact, and feed findings back into detection rules so the same incident cannot recur.\n\nEvery class in this guide maps to one phase. Every method maps to one action. Every action calls one or more GreenHelix API tools. The rest of this guide walks through each phase with production-ready Python code, then assembles five complete runbooks for the most common agent incident types.\n\n---\n\n## Chapter 2: Phase 1: Detection — Knowing Something Is Wrong\n\n### The Three Detection Signals\n\nAgent incidents produce three observable signals, and you need all three because no single signal is reliable on its own.\n\n**Cost anomaly**: An agent's spending rate deviates from its historical baseline. A cost spike is the most reliable signal for runaway spending, but it lags -- by the time cumulative spend exceeds the anomaly threshold, the agent may have already locked significant funds. The detection window depends on your polling interval.\n\n**Reputation drift**: An agent's trust score or reputation metrics change unexpectedly. A sudden drop in reputation may indicate the agent is producing low-quality work, failing to meet escrow conditions, or being reported by counterparties. Reputation drift is a leading indicator for quality degradation incidents but a lagging indicator for financial incidents.\n\n**Webhook alerts**: The GreenHelix event bus can push real-time notifications for budget threshold crossings, escrow state changes, and trust score updates. Webhooks are the fastest detection method but require infrastructure to receive and process them. If your webhook endpoint is down, you have no detection.\n\n### The IncidentDetector Class\n\nThe `IncidentDetector` combines all three signals into a single monitoring class. It polls billing and reputation endpoints on a configurable interval and registers webhooks for real-time alerting.\n\n```python\nimport requests\nimport time\nimport json\nimport hashlib\nimport statistics\nfrom datetime import datetime, timezone\nfrom typing import Optional\nfrom dataclasses import dataclass, field\n\n\n@dataclass\nclass AnomalyResult:\n    \"\"\"Result of an anomaly detection check.\"\"\"\n    detected: bool\n    signal: str\n    severity: str  # \"info\", \"warning\", \"critical\"\n    agent_id: str\n    details: dict = field(default_factory=dict)\n    timestamp: float = field(default_factory=time.time)\n\n    def to_dict(self) -> dict:\n        return {\n            \"detected\": self.detected,\n            \"signal\": self.signal,\n            \"severity\": self.severity,\n            \"agent_id\": self.agent_id,\n            \"details\": self.details,\n            \"timestamp\": self.timestamp,\n        }\n\n\nclass IncidentDetector:\n    \"\"\"Phase 1: Detect agent incidents via cost, reputation, and webhooks.\n\n    Usage:\n        detector = IncidentDetector(\n            api_key=\"your-key\",\n            agent_id=\"agent-prod-001\",\n        )\n\n        # One-shot anomaly check\n        anomalies = detector.check_all()\n        for anomaly in anomalies:\n            if anomaly.severity == \"critical\":\n                print(f\"CRITICAL: {anomaly.signal} - {anomaly.details}\")\n\n        # Set up persistent webhook alerts\n        detector.setup_alerts(\n            webhook_url=\"https:\u002F\u002Fyour-app.com\u002Fincidents\u002Fwebhook\",\n            budget_threshold_pct=80,\n        )\n\n        # Continuous monitoring loop\n        detector.monitor(interval_seconds=30, callback=your_handler)\n    \"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n        cost_anomaly_std_devs: float = 2.0,\n        reputation_drop_threshold: float = 0.15,\n    ):\n        self.api_key = api_key\n        self.agent_id = agent_id\n        self.base_url = base_url\n        self.cost_anomaly_std_devs = cost_anomaly_std_devs\n        self.reputation_drop_threshold = reputation_drop_threshold\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n        self._cost_history: list[float] = []\n        self._reputation_baseline: Optional[float] = None\n        self._alert_callbacks: list = []\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute a GreenHelix tool.\"\"\"\n        resp = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        resp.raise_for_status()\n        return resp.json()\n\n    # ── Cost Anomaly Detection ─────────────────────────────────\n\n    def check_cost_anomaly(self) -> AnomalyResult:\n        \"\"\"Detect spending anomalies by comparing current balance drain\n        rate against historical baseline.\n\n        Uses a rolling window of balance snapshots to compute the\n        mean and standard deviation of spending rate, then flags\n        any period where the rate exceeds mean + N standard deviations.\n        \"\"\"\n        balance_resp = self._execute(\"get_balance\", {\n            \"agent_id\": self.agent_id,\n        })\n        current_balance = float(balance_resp.get(\"balance\", \"0\"))\n        self._cost_history.append(current_balance)\n\n        if len(self._cost_history) \u003C 5:\n            return AnomalyResult(\n                detected=False,\n                signal=\"cost_anomaly\",\n                severity=\"info\",\n                agent_id=self.agent_id,\n                details={\"message\": \"Insufficient history\", \"samples\": len(self._cost_history)},\n            )\n\n        # Compute balance deltas (spending rate per interval)\n        deltas = [\n            self._cost_history[i] - self._cost_history[i + 1]\n            for i in range(len(self._cost_history) - 1)\n        ]\n        # Filter to only spending (positive deltas)\n        spending_deltas = [d for d in deltas if d > 0]\n\n        if len(spending_deltas) \u003C 3:\n            return AnomalyResult(\n                detected=False,\n                signal=\"cost_anomaly\",\n                severity=\"info\",\n                agent_id=self.agent_id,\n                details={\"message\": \"Insufficient spending data\"},\n            )\n\n        mean_spend = statistics.mean(spending_deltas)\n        std_spend = statistics.stdev(spending_deltas)\n        latest_spend = deltas[-1] if deltas[-1] > 0 else 0\n\n        threshold = mean_spend + (self.cost_anomaly_std_devs * std_spend)\n\n        if latest_spend > threshold and std_spend > 0:\n            severity = \"critical\" if latest_spend > threshold * 2 else \"warning\"\n            return AnomalyResult(\n                detected=True,\n                signal=\"cost_anomaly\",\n                severity=severity,\n                agent_id=self.agent_id,\n                details={\n                    \"current_balance\": str(current_balance),\n                    \"latest_spend_rate\": str(round(latest_spend, 2)),\n                    \"mean_spend_rate\": str(round(mean_spend, 2)),\n                    \"std_dev\": str(round(std_spend, 2)),\n                    \"threshold\": str(round(threshold, 2)),\n                    \"z_score\": str(round(\n                        (latest_spend - mean_spend) \u002F std_spend, 2\n                    )) if std_spend > 0 else \"N\u002FA\",\n                },\n            )\n\n        return AnomalyResult(\n            detected=False,\n            signal=\"cost_anomaly\",\n            severity=\"info\",\n            agent_id=self.agent_id,\n            details={\n                \"current_balance\": str(current_balance),\n                \"latest_spend_rate\": str(round(latest_spend, 2)),\n                \"threshold\": str(round(threshold, 2)),\n            },\n        )\n\n    # ── Reputation Drift Detection ─────────────────────────────\n\n    def check_reputation_drift(self) -> AnomalyResult:\n        \"\"\"Detect unexpected drops in agent reputation score.\n\n        Compares current reputation against the baseline captured\n        on first call. A drop exceeding the threshold indicates\n        either quality degradation or adversarial reporting.\n        \"\"\"\n        rep_resp = self._execute(\"get_agent_reputation\", {\n            \"agent_id\": self.agent_id,\n        })\n        current_score = float(rep_resp.get(\"reputation_score\", 0))\n\n        if self._reputation_baseline is None:\n            self._reputation_baseline = current_score\n            return AnomalyResult(\n                detected=False,\n                signal=\"reputation_drift\",\n                severity=\"info\",\n                agent_id=self.agent_id,\n                details={\n                    \"message\": \"Baseline established\",\n                    \"baseline\": str(current_score),\n                },\n            )\n\n        drop = self._reputation_baseline - current_score\n        drop_pct = drop \u002F self._reputation_baseline if self._reputation_baseline > 0 else 0\n\n        if drop_pct >= self.reputation_drop_threshold:\n            severity = \"critical\" if drop_pct >= 0.30 else \"warning\"\n            return AnomalyResult(\n                detected=True,\n                signal=\"reputation_drift\",\n                severity=severity,\n                agent_id=self.agent_id,\n                details={\n                    \"baseline_score\": str(self._reputation_baseline),\n                    \"current_score\": str(current_score),\n                    \"drop_pct\": str(round(drop_pct * 100, 1)),\n                    \"threshold_pct\": str(round(self.reputation_drop_threshold * 100, 1)),\n                },\n            )\n\n        return AnomalyResult(\n            detected=False,\n            signal=\"reputation_drift\",\n            severity=\"info\",\n            agent_id=self.agent_id,\n            details={\n                \"current_score\": str(current_score),\n                \"baseline_score\": str(self._reputation_baseline),\n            },\n        )\n\n    # ── Budget Status Check ────────────────────────────────────\n\n    def check_budget_status(self) -> AnomalyResult:\n        \"\"\"Check if agent is approaching or has exceeded budget limits.\"\"\"\n        budget_resp = self._execute(\"get_budget_status\", {\n            \"agent_id\": self.agent_id,\n        })\n        utilization_pct = float(budget_resp.get(\"utilization_pct\", 0))\n        daily_limit = budget_resp.get(\"daily_limit\", \"0\")\n        daily_spent = budget_resp.get(\"daily_spent\", \"0\")\n\n        if utilization_pct >= 95:\n            return AnomalyResult(\n                detected=True,\n                signal=\"budget_exhaustion\",\n                severity=\"critical\",\n                agent_id=self.agent_id,\n                details={\n                    \"utilization_pct\": str(utilization_pct),\n                    \"daily_limit\": str(daily_limit),\n                    \"daily_spent\": str(daily_spent),\n                },\n            )\n        elif utilization_pct >= 80:\n            return AnomalyResult(\n                detected=True,\n                signal=\"budget_warning\",\n                severity=\"warning\",\n                agent_id=self.agent_id,\n                details={\n                    \"utilization_pct\": str(utilization_pct),\n                    \"daily_limit\": str(daily_limit),\n                    \"daily_spent\": str(daily_spent),\n                },\n            )\n\n        return AnomalyResult(\n            detected=False,\n            signal=\"budget_status\",\n            severity=\"info\",\n            agent_id=self.agent_id,\n            details={\"utilization_pct\": str(utilization_pct)},\n        )\n\n    # ── Webhook Alert Setup ────────────────────────────────────\n\n    def setup_alerts(\n        self,\n        webhook_url: str,\n        budget_threshold_pct: int = 80,\n    ) -> dict:\n        \"\"\"Register webhooks for real-time incident alerting.\n\n        Sets up three event subscriptions:\n        1. Budget threshold crossing (configurable percentage)\n        2. Escrow state changes (creation, release, cancellation)\n        3. Reputation score updates\n        \"\"\"\n        results = {}\n\n        # Budget alert webhook\n        results[\"budget_alert\"] = self._execute(\"register_webhook\", {\n            \"agent_id\": self.agent_id,\n            \"event_type\": \"budget_threshold\",\n            \"webhook_url\": webhook_url,\n            \"config\": {\n                \"threshold_pct\": budget_threshold_pct,\n            },\n        })\n\n        # Escrow state change webhook\n        results[\"escrow_alert\"] = self._execute(\"register_webhook\", {\n            \"agent_id\": self.agent_id,\n            \"event_type\": \"escrow_state_change\",\n            \"webhook_url\": webhook_url,\n        })\n\n        # Reputation change webhook\n        results[\"reputation_alert\"] = self._execute(\"register_webhook\", {\n            \"agent_id\": self.agent_id,\n            \"event_type\": \"reputation_change\",\n            \"webhook_url\": webhook_url,\n        })\n\n        # Publish a test event to verify webhook delivery\n        results[\"test_event\"] = self._execute(\"publish_event\", {\n            \"agent_id\": self.agent_id,\n            \"event_type\": \"incident_detector_setup\",\n            \"payload\": {\n                \"message\": \"Incident detection webhooks configured\",\n                \"webhook_url\": webhook_url,\n                \"timestamp\": int(time.time()),\n            },\n        })\n\n        return results\n\n    # ── Combined Check ─────────────────────────────────────────\n\n    def check_all(self) -> list[AnomalyResult]:\n        \"\"\"Run all detection checks and return any anomalies found.\"\"\"\n        results = []\n        checks = [\n            self.check_cost_anomaly,\n            self.check_reputation_drift,\n            self.check_budget_status,\n        ]\n        for check in checks:\n            try:\n                result = check()\n                if result.detected:\n                    results.append(result)\n            except requests.exceptions.RequestException as e:\n                results.append(AnomalyResult(\n                    detected=True,\n                    signal=\"detection_failure\",\n                    severity=\"warning\",\n                    agent_id=self.agent_id,\n                    details={\"error\": str(e), \"check\": check.__name__},\n                ))\n        return results\n\n    # ── Continuous Monitoring ──────────────────────────────────\n\n    def monitor(\n        self,\n        interval_seconds: int = 30,\n        callback=None,\n        max_iterations: Optional[int] = None,\n    ):\n        \"\"\"Run continuous anomaly detection in a polling loop.\n\n        Args:\n            interval_seconds: Seconds between detection cycles.\n            callback: Function called with list[AnomalyResult] each cycle.\n            max_iterations: Stop after N cycles (None = run forever).\n        \"\"\"\n        iteration = 0\n        while max_iterations is None or iteration \u003C max_iterations:\n            anomalies = self.check_all()\n            if anomalies and callback:\n                callback(anomalies)\n            elif anomalies:\n                for a in anomalies:\n                    print(\n                        f\"[{a.severity.upper()}] {a.signal}: \"\n                        f\"{json.dumps(a.details)}\"\n                    )\n            time.sleep(interval_seconds)\n            iteration += 1\n```\n\n### Detection in Practice\n\nThe detector is designed to run as a sidecar process alongside your agent fleet. In the simplest deployment, run it as a cron job every 30 seconds:\n\n```python\ndetector = IncidentDetector(\n    api_key=\"your-api-key\",\n    agent_id=\"agent-prod-001\",\n    cost_anomaly_std_devs=2.5,      # Wider tolerance = fewer false positives\n    reputation_drop_threshold=0.10,  # Alert on 10% reputation drop\n)\n\n# Set up persistent webhooks (run once during deployment)\ndetector.setup_alerts(\n    webhook_url=\"https:\u002F\u002Fyour-app.com\u002Fincidents\u002Fwebhook\",\n    budget_threshold_pct=75,  # Alert at 75% budget utilization\n)\n\n# Continuous monitoring (runs in background)\ndef on_anomaly(anomalies):\n    for a in anomalies:\n        if a.severity == \"critical\":\n            # Trigger automated containment (see Chapter 3)\n            trigger_containment(a.agent_id, a.signal, a.details)\n        else:\n            # Send to alerting channel\n            send_slack_alert(a)\n\ndetector.monitor(interval_seconds=30, callback=on_anomaly)\n```\n\nThe `cost_anomaly_std_devs` parameter controls sensitivity. At 2.0 standard deviations, you will catch most real anomalies but may see false positives during legitimate high-activity periods (end-of-month billing, batch processing). At 3.0, you will miss some slower-developing anomalies but virtually eliminate false positives. Start at 2.5 and tune based on your false-positive rate during the first two weeks.\n\nThe `reputation_drop_threshold` of 0.15 (15%) was chosen because normal reputation fluctuation in a healthy agent is under 5% per day. A 15% drop in a single monitoring interval indicates either a genuine quality problem or adversarial reporting. Both warrant investigation.\n\n---\n\n## Chapter 3: Phase 2: Containment — Stop the Bleeding\n\n### The 60-Second Rule\n\nIn agent commerce, containment must complete within 60 seconds of detection. Every second of delay is more locked funds, more failed transactions, more cascade effects on dependent agents. The containment phase has three actions, executed in order:\n\n1. **Freeze the budget**: Set the agent's daily budget cap to zero. This immediately prevents new spending without affecting existing escrows.\n2. **Cancel active escrows**: List all pending escrows for the agent and cancel them. This unlocks funds and prevents further financial exposure.\n3. **Verify identity**: Confirm the agent has not been impersonated. If identity verification fails, the incident scope expands from \"misbehaving agent\" to \"compromised agent.\"\n\n### The IncidentContainment Class\n\n```python\nimport requests\nimport time\nimport json\nfrom typing import Optional\nfrom dataclasses import dataclass, field\n\n\n@dataclass\nclass ContainmentResult:\n    \"\"\"Result of a containment action.\"\"\"\n    action: str\n    success: bool\n    agent_id: str\n    details: dict = field(default_factory=dict)\n    timestamp: float = field(default_factory=time.time)\n    error: Optional[str] = None\n\n    def to_dict(self) -> dict:\n        result = {\n            \"action\": self.action,\n            \"success\": self.success,\n            \"agent_id\": self.agent_id,\n            \"details\": self.details,\n            \"timestamp\": self.timestamp,\n        }\n        if self.error:\n            result[\"error\"] = self.error\n        return result\n\n\nclass IncidentContainment:\n    \"\"\"Phase 2: Contain agent incidents by freezing budgets, escrows,\n    and verifying identity.\n\n    Usage:\n        containment = IncidentContainment(\n            api_key=\"your-key\",\n            agent_id=\"agent-prod-001\",\n        )\n\n        # Full containment sequence (recommended)\n        results = containment.contain_agent()\n        for r in results:\n            print(f\"[{r.action}] success={r.success}\")\n\n        # Individual actions\n        containment.freeze_agent()\n        containment.freeze_escrows()\n        containment.verify_agent_identity()\n    \"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n    ):\n        self.api_key = api_key\n        self.agent_id = agent_id\n        self.base_url = base_url\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n        self._containment_log: list[ContainmentResult] = []\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute a GreenHelix tool.\"\"\"\n        resp = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        resp.raise_for_status()\n        return resp.json()\n\n    def _log(self, result: ContainmentResult):\n        \"\"\"Append to the internal containment audit log.\"\"\"\n        self._containment_log.append(result)\n\n    # ── Budget Freeze ──────────────────────────────────────────\n\n    def freeze_agent(self) -> ContainmentResult:\n        \"\"\"Freeze an agent's spending by setting daily budget cap to zero.\n\n        This is the single most important containment action. Setting\n        the daily budget to $0 immediately prevents the agent from\n        initiating any new paid operations. Existing escrows are not\n        affected -- they must be cancelled separately.\n        \"\"\"\n        try:\n            # First, capture current budget for later restoration\n            budget_status = self._execute(\"get_budget_status\", {\n                \"agent_id\": self.agent_id,\n            })\n            previous_cap = budget_status.get(\"daily_limit\", \"unknown\")\n\n            # Set budget to zero\n            freeze_resp = self._execute(\"set_budget_cap\", {\n                \"agent_id\": self.agent_id,\n                \"daily\": \"0\",\n                \"monthly\": \"0\",\n            })\n\n            # Publish incident event\n            self._execute(\"publish_event\", {\n                \"agent_id\": self.agent_id,\n                \"event_type\": \"incident_budget_frozen\",\n                \"payload\": {\n                    \"previous_daily_cap\": str(previous_cap),\n                    \"reason\": \"incident_containment\",\n                    \"timestamp\": int(time.time()),\n                },\n            })\n\n            result = ContainmentResult(\n                action=\"freeze_budget\",\n                success=True,\n                agent_id=self.agent_id,\n                details={\n                    \"previous_daily_cap\": str(previous_cap),\n                    \"new_daily_cap\": \"0\",\n                    \"response\": freeze_resp,\n                },\n            )\n        except requests.exceptions.RequestException as e:\n            result = ContainmentResult(\n                action=\"freeze_budget\",\n                success=False,\n                agent_id=self.agent_id,\n                error=str(e),\n            )\n\n        self._log(result)\n        return result\n\n    # ── Escrow Freeze ──────────────────────────────────────────\n\n    def freeze_escrows(self) -> ContainmentResult:\n        \"\"\"Cancel all active escrows for the agent to unlock funds.\n\n        Lists all escrows where the agent is the payer, then cancels\n        each one that is in a cancellable state (pending, funded).\n        Escrows that have already been released or disputed cannot\n        be cancelled.\n        \"\"\"\n        try:\n            # List all escrows for this agent\n            escrows_resp = self._execute(\"list_escrows\", {\n                \"agent_id\": self.agent_id,\n            })\n            escrows = escrows_resp.get(\"escrows\", [])\n\n            cancelled = []\n            failed = []\n            skipped = []\n\n            for escrow in escrows:\n                escrow_id = escrow.get(\"escrow_id\", \"\")\n                status = escrow.get(\"status\", \"\")\n\n                if status in (\"pending\", \"funded\", \"active\"):\n                    try:\n                        cancel_resp = self._execute(\"cancel_escrow\", {\n                            \"escrow_id\": escrow_id,\n                            \"reason\": \"incident_containment\",\n                        })\n                        cancelled.append({\n                            \"escrow_id\": escrow_id,\n                            \"amount\": escrow.get(\"amount\", \"0\"),\n                            \"status\": status,\n                            \"cancel_response\": cancel_resp,\n                        })\n                    except requests.exceptions.RequestException as e:\n                        failed.append({\n                            \"escrow_id\": escrow_id,\n                            \"error\": str(e),\n                        })\n                else:\n                    skipped.append({\n                        \"escrow_id\": escrow_id,\n                        \"status\": status,\n                        \"reason\": \"not_cancellable\",\n                    })\n\n            total_unlocked = sum(\n                float(c.get(\"amount\", \"0\")) for c in cancelled\n            )\n\n            result = ContainmentResult(\n                action=\"freeze_escrows\",\n                success=len(failed) == 0,\n                agent_id=self.agent_id,\n                details={\n                    \"total_escrows\": len(escrows),\n                    \"cancelled\": len(cancelled),\n                    \"failed\": len(failed),\n                    \"skipped\": len(skipped),\n                    \"total_unlocked\": str(round(total_unlocked, 2)),\n                    \"cancelled_details\": cancelled,\n                    \"failed_details\": failed,\n                },\n            )\n        except requests.exceptions.RequestException as e:\n            result = ContainmentResult(\n                action=\"freeze_escrows\",\n                success=False,\n                agent_id=self.agent_id,\n                error=str(e),\n            )\n\n        self._log(result)\n        return result\n\n    # ── Identity Verification ──────────────────────────────────\n\n    def verify_agent_identity(self) -> ContainmentResult:\n        \"\"\"Verify the agent's identity has not been compromised.\n\n        Checks both the agent's registered identity and current\n        verification status. If the agent cannot be verified,\n        the incident scope expands to potential identity compromise.\n        \"\"\"\n        try:\n            # Get current identity record\n            identity_resp = self._execute(\"get_agent_identity\", {\n                \"agent_id\": self.agent_id,\n            })\n\n            # Verify the agent is still valid\n            verify_resp = self._execute(\"verify_agent\", {\n                \"agent_id\": self.agent_id,\n            })\n            is_verified = verify_resp.get(\"verified\", False)\n\n            # Check reputation for signs of manipulation\n            rep_resp = self._execute(\"get_agent_reputation\", {\n                \"agent_id\": self.agent_id,\n            })\n\n            result = ContainmentResult(\n                action=\"verify_identity\",\n                success=True,\n                agent_id=self.agent_id,\n                details={\n                    \"identity_valid\": is_verified,\n                    \"identity\": identity_resp,\n                    \"reputation\": rep_resp,\n                    \"compromise_suspected\": not is_verified,\n                },\n            )\n\n            if not is_verified:\n                result.details[\"warning\"] = (\n                    \"Agent identity verification FAILED. \"\n                    \"Possible identity compromise. Escalate immediately.\"\n                )\n                # Publish critical event\n                self._execute(\"publish_event\", {\n                    \"agent_id\": self.agent_id,\n                    \"event_type\": \"incident_identity_compromise_suspected\",\n                    \"payload\": {\n                        \"verification_result\": verify_resp,\n                        \"timestamp\": int(time.time()),\n                    },\n                })\n        except requests.exceptions.RequestException as e:\n            result = ContainmentResult(\n                action=\"verify_identity\",\n                success=False,\n                agent_id=self.agent_id,\n                error=str(e),\n                details={\n                    \"warning\": \"Could not verify identity. Treat as compromised.\",\n                },\n            )\n\n        self._log(result)\n        return result\n\n    # ── Full Containment Sequence ──────────────────────────────\n\n    def contain_agent(self) -> list[ContainmentResult]:\n        \"\"\"Execute the full containment sequence: freeze budget,\n        cancel escrows, verify identity.\n\n        Returns a list of ContainmentResult objects, one per action.\n        Actions execute in order. A failure in one action does not\n        prevent subsequent actions from executing -- all three must\n        be attempted regardless.\n        \"\"\"\n        results = []\n        start_time = time.time()\n\n        # Step 1: Freeze budget (most critical, executes first)\n        results.append(self.freeze_agent())\n\n        # Step 2: Cancel escrows (unlock funds)\n        results.append(self.freeze_escrows())\n\n        # Step 3: Verify identity (expand scope if compromised)\n        results.append(self.verify_agent_identity())\n\n        elapsed = round(time.time() - start_time, 2)\n\n        # Publish containment summary\n        try:\n            self._execute(\"publish_event\", {\n                \"agent_id\": self.agent_id,\n                \"event_type\": \"incident_containment_complete\",\n                \"payload\": {\n                    \"elapsed_seconds\": elapsed,\n                    \"actions\": [r.to_dict() for r in results],\n                    \"all_succeeded\": all(r.success for r in results),\n                    \"timestamp\": int(time.time()),\n                },\n            })\n        except requests.exceptions.RequestException:\n            pass  # Do not let event publishing failure block containment\n\n        return results\n\n    def get_containment_log(self) -> list[dict]:\n        \"\"\"Return the full containment audit log.\"\"\"\n        return [r.to_dict() for r in self._containment_log]\n```\n\n### Containment Timing\n\nIn testing against the GreenHelix sandbox, the full three-step containment sequence completes in under 3 seconds:\n\n| Action | Typical Latency |\n|---|---|\n| `freeze_agent` (set_budget_cap) | 200-400ms |\n| `freeze_escrows` (list + cancel N) | 500ms + 200ms per escrow |\n| `verify_agent_identity` | 400-600ms |\n| **Total (5 escrows)** | **~2.5 seconds** |\n\nEven with 50 active escrows, containment completes in under 15 seconds. The 60-second rule provides a generous safety margin for network latency and retries.\n\n### What Containment Does Not Do\n\nContainment does not terminate the agent process. Containment does not revoke API keys. Containment does not delete data. It is designed to be reversible. The agent is still running but financially frozen -- it can read data, check status, and log events, but it cannot spend money or lock new funds. This is intentional: a fully terminated agent cannot participate in its own recovery.\n\n---\n\n## Chapter 4: Phase 3: Recovery — Getting Back to Normal\n\n### Recovery Is Not \"Undo Containment\"\n\nA common mistake is treating recovery as the inverse of containment: unfreeze the budget, resume operations, done. Recovery must verify that the root cause is resolved before re-enabling financial operations. If you unfreeze a budget while the retry loop is still running, you will re-enter the incident within minutes.\n\nRecovery has three gates, and each must pass before proceeding to the next:\n\n1. **Root cause confirmed resolved**: The code change, configuration fix, or model constraint that caused the incident has been deployed and verified.\n2. **Identity and reputation verified**: The agent's identity is intact and its reputation reflects its true performance, not incident-degraded metrics.\n3. **Budget restored to safe levels**: The budget is restored to a conservative level (typically 50% of pre-incident cap) with enhanced monitoring, then gradually increased over 24-48 hours.\n\n### The IncidentRecovery Class\n\n```python\nimport requests\nimport time\nimport json\nfrom typing import Optional\nfrom dataclasses import dataclass, field\n\n\n@dataclass\nclass RecoveryResult:\n    \"\"\"Result of a recovery action.\"\"\"\n    action: str\n    success: bool\n    agent_id: str\n    details: dict = field(default_factory=dict)\n    timestamp: float = field(default_factory=time.time)\n    error: Optional[str] = None\n\n    def to_dict(self) -> dict:\n        result = {\n            \"action\": self.action,\n            \"success\": self.success,\n            \"agent_id\": self.agent_id,\n            \"details\": self.details,\n            \"timestamp\": self.timestamp,\n        }\n        if self.error:\n            result[\"error\"] = self.error\n        return result\n\n\nclass IncidentRecovery:\n    \"\"\"Phase 3: Recover agent operations after containment.\n\n    Usage:\n        recovery = IncidentRecovery(\n            api_key=\"your-key\",\n            agent_id=\"agent-prod-001\",\n        )\n\n        # Gradual recovery (recommended)\n        results = recovery.recover_agent(\n            target_daily_budget=\"500.00\",\n            initial_budget_pct=50,\n        )\n        for r in results:\n            print(f\"[{r.action}] success={r.success}\")\n\n        # After 24 hours with no anomalies, restore full budget\n        recovery.restore_full_budget(target_daily_budget=\"1000.00\")\n    \"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n    ):\n        self.api_key = api_key\n        self.agent_id = agent_id\n        self.base_url = base_url\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n        self._recovery_log: list[RecoveryResult] = []\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute a GreenHelix tool.\"\"\"\n        resp = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        resp.raise_for_status()\n        return resp.json()\n\n    def _log(self, result: RecoveryResult):\n        self._recovery_log.append(result)\n\n    # ── Budget Restoration ─────────────────────────────────────\n\n    def restore_budget(\n        self,\n        daily_budget: str,\n        monthly_budget: Optional[str] = None,\n    ) -> RecoveryResult:\n        \"\"\"Restore the agent's budget to a specified level.\n\n        Start with a conservative budget (50% of pre-incident level)\n        and increase gradually over 24-48 hours as monitoring confirms\n        normal behavior.\n        \"\"\"\n        try:\n            monthly = monthly_budget or str(float(daily_budget) * 30)\n            resp = self._execute(\"set_budget_cap\", {\n                \"agent_id\": self.agent_id,\n                \"daily\": daily_budget,\n                \"monthly\": monthly,\n            })\n\n            result = RecoveryResult(\n                action=\"restore_budget\",\n                success=True,\n                agent_id=self.agent_id,\n                details={\n                    \"daily_budget\": daily_budget,\n                    \"monthly_budget\": monthly,\n                    \"response\": resp,\n                },\n            )\n        except requests.exceptions.RequestException as e:\n            result = RecoveryResult(\n                action=\"restore_budget\",\n                success=False,\n                agent_id=self.agent_id,\n                error=str(e),\n            )\n\n        self._log(result)\n        return result\n\n    # ── Reputation Restoration ─────────────────────────────────\n\n    def restore_reputation(\n        self,\n        submit_recovery_metrics: bool = True,\n    ) -> RecoveryResult:\n        \"\"\"Verify and restore agent reputation post-incident.\n\n        Checks current reputation, compares against expected baseline,\n        and optionally submits recovery metrics to rebuild trust.\n        \"\"\"\n        try:\n            # Get current reputation\n            rep_resp = self._execute(\"get_agent_reputation\", {\n                \"agent_id\": self.agent_id,\n            })\n            current_score = float(rep_resp.get(\"reputation_score\", 0))\n\n            # Verify the agent identity is still intact\n            verify_resp = self._execute(\"verify_agent\", {\n                \"agent_id\": self.agent_id,\n            })\n            is_verified = verify_resp.get(\"verified\", False)\n\n            # Get verified claims to confirm audit trail integrity\n            claims_resp = self._execute(\"get_verified_claims\", {\n                \"agent_id\": self.agent_id,\n            })\n\n            # Submit recovery metrics if requested\n            metrics_resp = None\n            if submit_recovery_metrics:\n                metrics_resp = self._execute(\"submit_metrics\", {\n                    \"agent_id\": self.agent_id,\n                    \"metrics\": {\n                        \"incident_recovery\": True,\n                        \"recovery_timestamp\": int(time.time()),\n                        \"post_recovery_status\": \"active\",\n                    },\n                })\n\n            result = RecoveryResult(\n                action=\"restore_reputation\",\n                success=is_verified,\n                agent_id=self.agent_id,\n                details={\n                    \"current_reputation\": str(current_score),\n                    \"identity_verified\": is_verified,\n                    \"verified_claims\": claims_resp,\n                    \"recovery_metrics_submitted\": metrics_resp is not None,\n                },\n            )\n\n            if not is_verified:\n                result.details[\"warning\"] = (\n                    \"Agent identity verification failed during recovery. \"\n                    \"Re-registration may be required.\"\n                )\n        except requests.exceptions.RequestException as e:\n            result = RecoveryResult(\n                action=\"restore_reputation\",\n                success=False,\n                agent_id=self.agent_id,\n                error=str(e),\n            )\n\n        self._log(result)\n        return result\n\n    # ── Incident Flag Clearing ─────────────────────────────────\n\n    def clear_incident(self, incident_id: str = \"\") -> RecoveryResult:\n        \"\"\"Clear the incident flag and publish a recovery event.\n\n        This signals to other systems (monitoring, alerting, dashboards)\n        that the incident has been resolved and the agent is returning\n        to normal operations.\n        \"\"\"\n        try:\n            event_resp = self._execute(\"publish_event\", {\n                \"agent_id\": self.agent_id,\n                \"event_type\": \"incident_resolved\",\n                \"payload\": {\n                    \"incident_id\": incident_id or f\"inc-{int(time.time())}\",\n                    \"resolved_at\": int(time.time()),\n                    \"resolution\": \"containment_and_recovery_complete\",\n                },\n            })\n\n            # Update service rating to reflect recovery\n            rate_resp = self._execute(\"rate_service\", {\n                \"agent_id\": self.agent_id,\n                \"rating\": 3,  # Neutral post-incident rating\n                \"comment\": \"Service restored after incident containment and recovery.\",\n            })\n\n            result = RecoveryResult(\n                action=\"clear_incident\",\n                success=True,\n                agent_id=self.agent_id,\n                details={\n                    \"event_published\": event_resp,\n                    \"service_rating_updated\": rate_resp,\n                },\n            )\n        except requests.exceptions.RequestException as e:\n            result = RecoveryResult(\n                action=\"clear_incident\",\n                success=False,\n                agent_id=self.agent_id,\n                error=str(e),\n            )\n\n        self._log(result)\n        return result\n\n    # ── Full Recovery Sequence ─────────────────────────────────\n\n    def recover_agent(\n        self,\n        target_daily_budget: str = \"500.00\",\n        initial_budget_pct: int = 50,\n        incident_id: str = \"\",\n    ) -> list[RecoveryResult]:\n        \"\"\"Execute the full recovery sequence.\n\n        Restores budget at a conservative percentage of the target,\n        verifies identity and reputation, and clears the incident flag.\n        \"\"\"\n        results = []\n\n        # Step 1: Restore budget at conservative level\n        initial_budget = str(\n            round(float(target_daily_budget) * initial_budget_pct \u002F 100, 2)\n        )\n        results.append(self.restore_budget(daily_budget=initial_budget))\n\n        # Step 2: Verify and restore reputation\n        results.append(self.restore_reputation())\n\n        # Step 3: Clear incident flag\n        results.append(self.clear_incident(incident_id=incident_id))\n\n        return results\n\n    def restore_full_budget(\n        self, target_daily_budget: str,\n    ) -> RecoveryResult:\n        \"\"\"Restore budget to full pre-incident level.\n\n        Call this 24-48 hours after initial recovery, once monitoring\n        confirms the agent is operating normally.\n        \"\"\"\n        return self.restore_budget(daily_budget=target_daily_budget)\n\n    def get_recovery_log(self) -> list[dict]:\n        \"\"\"Return the full recovery audit log.\"\"\"\n        return [r.to_dict() for r in self._recovery_log]\n```\n\n### The Gradual Restoration Pattern\n\nNever restore an agent to full operational capacity immediately. Use a stepped approach:\n\n```\nTime 0h:    50% of pre-incident budget, enhanced monitoring (30s interval)\nTime +6h:   If no anomalies, increase to 75%\nTime +24h:  If no anomalies, increase to 100%\nTime +48h:  Reduce monitoring to standard interval (5m)\n```\n\n```python\n# Gradual restoration example\nrecovery = IncidentRecovery(api_key=\"key\", agent_id=\"agent-prod-001\")\ndetector = IncidentDetector(api_key=\"key\", agent_id=\"agent-prod-001\")\n\n# Immediate: 50% budget with tight monitoring\nrecovery.restore_budget(daily_budget=\"250.00\")  # 50% of $500\ndetector.monitor(interval_seconds=30, max_iterations=720)  # 6 hours\n\n# +6h: Check for anomalies, then increase\nanomalies = detector.check_all()\nif not anomalies:\n    recovery.restore_budget(daily_budget=\"375.00\")  # 75%\n    detector.monitor(interval_seconds=60, max_iterations=1080)  # 18 hours\n\n# +24h: Full restoration\nanomalies = detector.check_all()\nif not anomalies:\n    recovery.restore_full_budget(target_daily_budget=\"500.00\")\n```\n\n---\n\n## Chapter 5: Phase 4: Post-Mortem — Learning from Failure\n\n### Every Incident Is a Training Signal\n\nThe post-mortem phase is where agent incident response diverges most sharply from traditional IT incident response. In traditional IR, the post-mortem produces a document: a timeline, a root cause, action items for humans. In agent incident response, the post-mortem produces data that feeds back into the detection system. Every incident teaches the detector what the next incident will look like.\n\nThe forensics phase has three outputs:\n\n1. **Audit trail**: A cryptographically verified record of everything the agent did during the incident window, extracted from GreenHelix claim chains.\n2. **Impact assessment**: Total financial impact -- funds locked, funds lost, funds recovered -- computed from billing analytics.\n3. **Incident timeline**: A reconstruction of events from detection through recovery, suitable for both human review and machine learning.\n\n### The IncidentForensics Class\n\n```python\nimport requests\nimport time\nimport json\nfrom typing import Optional\nfrom dataclasses import dataclass, field\nfrom datetime import datetime, timezone\n\n\n@dataclass\nclass ForensicsResult:\n    \"\"\"Result of a forensics investigation action.\"\"\"\n    action: str\n    agent_id: str\n    details: dict = field(default_factory=dict)\n    timestamp: float = field(default_factory=time.time)\n\n    def to_dict(self) -> dict:\n        return {\n            \"action\": self.action,\n            \"agent_id\": self.agent_id,\n            \"details\": self.details,\n            \"timestamp\": self.timestamp,\n        }\n\n\nclass IncidentForensics:\n    \"\"\"Phase 4: Post-mortem forensics for agent incidents.\n\n    Usage:\n        forensics = IncidentForensics(\n            api_key=\"your-key\",\n            agent_id=\"agent-prod-001\",\n        )\n\n        # Full post-mortem\n        report = forensics.run_post_mortem(\n            incident_id=\"inc-1712345678\",\n            incident_start=1712345000,\n            incident_end=1712346000,\n        )\n        print(json.dumps(report, indent=2))\n    \"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n    ):\n        self.api_key = api_key\n        self.agent_id = agent_id\n        self.base_url = base_url\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute a GreenHelix tool.\"\"\"\n        resp = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        resp.raise_for_status()\n        return resp.json()\n\n    # ── Audit Trail ────────────────────────────────────────────\n\n    def get_audit_trail(\n        self,\n        start_time: Optional[int] = None,\n        end_time: Optional[int] = None,\n    ) -> ForensicsResult:\n        \"\"\"Extract the cryptographically verified audit trail for\n        the incident window.\n\n        Uses claim chains to reconstruct a tamper-proof record of\n        agent actions. Each claim in the chain is individually\n        verifiable via its Merkle proof.\n        \"\"\"\n        # Get claim chains for the agent\n        chains_resp = self._execute(\"get_claim_chains\", {\n            \"agent_id\": self.agent_id,\n        })\n        chains = chains_resp.get(\"chains\", [])\n\n        # Get verified claims (individually verifiable)\n        claims_resp = self._execute(\"get_verified_claims\", {\n            \"agent_id\": self.agent_id,\n        })\n        claims = claims_resp.get(\"claims\", [])\n\n        # Filter to incident window if specified\n        if start_time and end_time:\n            claims = [\n                c for c in claims\n                if start_time \u003C= c.get(\"timestamp\", 0) \u003C= end_time\n            ]\n\n        # Get identity record for forensic context\n        identity_resp = self._execute(\"get_agent_identity\", {\n            \"agent_id\": self.agent_id,\n        })\n\n        return ForensicsResult(\n            action=\"audit_trail\",\n            agent_id=self.agent_id,\n            details={\n                \"claim_chains\": chains,\n                \"verified_claims_in_window\": claims,\n                \"total_claims_in_window\": len(claims),\n                \"identity_at_time\": identity_resp,\n                \"window\": {\n                    \"start\": start_time,\n                    \"end\": end_time,\n                },\n            },\n        )\n\n    # ── Impact Assessment ──────────────────────────────────────\n\n    def assess_impact(self) -> ForensicsResult:\n        \"\"\"Calculate the financial impact of the incident.\n\n        Uses billing analytics to compute total spending during the\n        incident, broken down by category. Compares against the\n        agent's normal spending patterns to isolate incident-related\n        costs.\n        \"\"\"\n        # Get usage analytics\n        analytics_resp = self._execute(\"get_usage_analytics\", {\n            \"agent_id\": self.agent_id,\n        })\n\n        # Get billing summary\n        billing_resp = self._execute(\"get_billing_summary\", {\n            \"agent_id\": self.agent_id,\n        })\n\n        # Get spending by category\n        category_resp = self._execute(\"get_spending_by_category\", {\n            \"agent_id\": self.agent_id,\n        })\n\n        # Get current balance\n        balance_resp = self._execute(\"get_balance\", {\n            \"agent_id\": self.agent_id,\n        })\n\n        # Get escrow status (how much was locked\u002Frecovered)\n        escrows_resp = self._execute(\"list_escrows\", {\n            \"agent_id\": self.agent_id,\n        })\n        escrows = escrows_resp.get(\"escrows\", [])\n\n        locked_funds = sum(\n            float(e.get(\"amount\", \"0\"))\n            for e in escrows\n            if e.get(\"status\") in (\"pending\", \"funded\", \"active\")\n        )\n        cancelled_funds = sum(\n            float(e.get(\"amount\", \"0\"))\n            for e in escrows\n            if e.get(\"status\") == \"cancelled\"\n        )\n        released_funds = sum(\n            float(e.get(\"amount\", \"0\"))\n            for e in escrows\n            if e.get(\"status\") == \"released\"\n        )\n\n        return ForensicsResult(\n            action=\"impact_assessment\",\n            agent_id=self.agent_id,\n            details={\n                \"current_balance\": balance_resp.get(\"balance\", \"0\"),\n                \"usage_analytics\": analytics_resp,\n                \"billing_summary\": billing_resp,\n                \"spending_by_category\": category_resp,\n                \"escrow_impact\": {\n                    \"total_escrows\": len(escrows),\n                    \"still_locked\": str(round(locked_funds, 2)),\n                    \"cancelled_recovered\": str(round(cancelled_funds, 2)),\n                    \"released_lost\": str(round(released_funds, 2)),\n                },\n            },\n        )\n\n    # ── Timeline Reconstruction ────────────────────────────────\n\n    def build_timeline(\n        self,\n        incident_id: str,\n        detection_time: int,\n        containment_time: int,\n        recovery_time: int,\n        containment_log: Optional[list[dict]] = None,\n        recovery_log: Optional[list[dict]] = None,\n    ) -> ForensicsResult:\n        \"\"\"Reconstruct a complete incident timeline.\n\n        Combines data from detection, containment, and recovery\n        phases into a single chronological record suitable for\n        both human review and machine learning.\n        \"\"\"\n        # Compute phase durations\n        detection_to_containment = containment_time - detection_time\n        containment_to_recovery = recovery_time - containment_time\n        total_duration = recovery_time - detection_time\n\n        # Get reputation at time of forensics\n        rep_resp = self._execute(\"get_agent_reputation\", {\n            \"agent_id\": self.agent_id,\n        })\n\n        timeline_events = []\n\n        # Detection event\n        timeline_events.append({\n            \"phase\": \"detection\",\n            \"timestamp\": detection_time,\n            \"iso_time\": datetime.fromtimestamp(\n                detection_time, tz=timezone.utc\n            ).isoformat(),\n            \"event\": \"incident_detected\",\n        })\n\n        # Containment events (from log if provided)\n        if containment_log:\n            for entry in containment_log:\n                timeline_events.append({\n                    \"phase\": \"containment\",\n                    \"timestamp\": entry.get(\"timestamp\", containment_time),\n                    \"iso_time\": datetime.fromtimestamp(\n                        entry.get(\"timestamp\", containment_time),\n                        tz=timezone.utc,\n                    ).isoformat(),\n                    \"event\": entry.get(\"action\", \"containment_action\"),\n                    \"success\": entry.get(\"success\", False),\n                    \"details\": entry.get(\"details\", {}),\n                })\n        else:\n            timeline_events.append({\n                \"phase\": \"containment\",\n                \"timestamp\": containment_time,\n                \"iso_time\": datetime.fromtimestamp(\n                    containment_time, tz=timezone.utc\n                ).isoformat(),\n                \"event\": \"containment_complete\",\n            })\n\n        # Recovery events (from log if provided)\n        if recovery_log:\n            for entry in recovery_log:\n                timeline_events.append({\n                    \"phase\": \"recovery\",\n                    \"timestamp\": entry.get(\"timestamp\", recovery_time),\n                    \"iso_time\": datetime.fromtimestamp(\n                        entry.get(\"timestamp\", recovery_time),\n                        tz=timezone.utc,\n                    ).isoformat(),\n                    \"event\": entry.get(\"action\", \"recovery_action\"),\n                    \"success\": entry.get(\"success\", False),\n                    \"details\": entry.get(\"details\", {}),\n                })\n        else:\n            timeline_events.append({\n                \"phase\": \"recovery\",\n                \"timestamp\": recovery_time,\n                \"iso_time\": datetime.fromtimestamp(\n                    recovery_time, tz=timezone.utc\n                ).isoformat(),\n                \"event\": \"recovery_complete\",\n            })\n\n        # Sort chronologically\n        timeline_events.sort(key=lambda e: e[\"timestamp\"])\n\n        return ForensicsResult(\n            action=\"build_timeline\",\n            agent_id=self.agent_id,\n            details={\n                \"incident_id\": incident_id,\n                \"timeline\": timeline_events,\n                \"phase_durations\": {\n                    \"detection_to_containment_seconds\": detection_to_containment,\n                    \"containment_to_recovery_seconds\": containment_to_recovery,\n                    \"total_duration_seconds\": total_duration,\n                },\n                \"reputation_post_incident\": rep_resp,\n                \"meets_60s_containment_sla\": detection_to_containment \u003C= 60,\n            },\n        )\n\n    # ── Full Post-Mortem ───────────────────────────────────────\n\n    def run_post_mortem(\n        self,\n        incident_id: str,\n        incident_start: int,\n        incident_end: int,\n        containment_log: Optional[list[dict]] = None,\n        recovery_log: Optional[list[dict]] = None,\n    ) -> dict:\n        \"\"\"Run a complete post-mortem investigation.\n\n        Combines audit trail, impact assessment, and timeline\n        reconstruction into a single report.\n        \"\"\"\n        audit = self.get_audit_trail(\n            start_time=incident_start,\n            end_time=incident_end,\n        )\n        impact = self.assess_impact()\n        timeline = self.build_timeline(\n            incident_id=incident_id,\n            detection_time=incident_start,\n            containment_time=incident_start + 45,  # Estimate if not provided\n            recovery_time=incident_end,\n            containment_log=containment_log,\n            recovery_log=recovery_log,\n        )\n\n        report = {\n            \"incident_id\": incident_id,\n            \"agent_id\": self.agent_id,\n            \"generated_at\": int(time.time()),\n            \"audit_trail\": audit.to_dict(),\n            \"impact_assessment\": impact.to_dict(),\n            \"timeline\": timeline.to_dict(),\n        }\n\n        # Publish the post-mortem as an event for downstream consumption\n        try:\n            self._execute(\"publish_event\", {\n                \"agent_id\": self.agent_id,\n                \"event_type\": \"incident_post_mortem\",\n                \"payload\": {\n                    \"incident_id\": incident_id,\n                    \"total_duration_seconds\": timeline.details[\n                        \"phase_durations\"\n                    ][\"total_duration_seconds\"],\n                    \"met_containment_sla\": timeline.details[\n                        \"meets_60s_containment_sla\"\n                    ],\n                    \"generated_at\": int(time.time()),\n                },\n            })\n        except requests.exceptions.RequestException:\n            pass\n\n        return report\n```\n\n### Feeding Post-Mortems Back into Detection\n\nThe post-mortem output is structured data, not a narrative document. This is deliberate. The `build_timeline` output can be ingested by the `IncidentDetector` to adjust anomaly thresholds:\n\n```python\n# After post-mortem, adjust detection sensitivity\nforensics = IncidentForensics(api_key=\"key\", agent_id=\"agent-prod-001\")\nreport = forensics.run_post_mortem(\n    incident_id=\"inc-1712345678\",\n    incident_start=1712345000,\n    incident_end=1712346000,\n)\n\n# If containment SLA was missed, tighten detection\nif not report[\"timeline\"][\"details\"][\"meets_60s_containment_sla\"]:\n    detector = IncidentDetector(\n        api_key=\"key\",\n        agent_id=\"agent-prod-001\",\n        cost_anomaly_std_devs=1.5,  # Tighter than default 2.0\n    )\n    print(\"Detection sensitivity increased due to missed SLA\")\n```\n\n---\n\n## Chapter 6: The 5 Agent Incident Runbooks\n\nEach runbook specifies: the trigger condition (what causes the alert), the severity classification, the automated response, and the manual follow-up. All automated steps use the classes from Chapters 2-5.\n\n### Runbook 1: Runaway Spending\n\n**Trigger**: `IncidentDetector.check_cost_anomaly()` returns severity \"critical\" -- spending rate exceeds 2 standard deviations above baseline.\n\n**Severity**: P0 (financial loss in progress)\n\n**Automated Response**:\n```python\ndef handle_runaway_spending(agent_id: str, anomaly: AnomalyResult):\n    \"\"\"Runbook 1: Automated response to runaway spending.\"\"\"\n    containment = IncidentContainment(\n        api_key=API_KEY, agent_id=agent_id,\n    )\n\n    # Step 1: Freeze immediately\n    freeze_result = containment.freeze_agent()\n    if not freeze_result.success:\n        # ESCALATE: Budget freeze failed, manual intervention required\n        alert_oncall(\n            severity=\"P0\",\n            message=f\"Budget freeze FAILED for {agent_id}. \"\n                    f\"Error: {freeze_result.error}. \"\n                    f\"Manual intervention required immediately.\",\n        )\n        return\n\n    # Step 2: Cancel all escrows to recover locked funds\n    escrow_result = containment.freeze_escrows()\n\n    # Step 3: Verify identity (rule out compromise)\n    identity_result = containment.verify_agent_identity()\n\n    # Step 4: Alert on-call with containment summary\n    alert_oncall(\n        severity=\"P0\",\n        message=(\n            f\"Runaway spending contained for {agent_id}. \"\n            f\"Budget frozen. \"\n            f\"{escrow_result.details.get('cancelled', 0)} escrows cancelled. \"\n            f\"${escrow_result.details.get('total_unlocked', '0')} recovered. \"\n            f\"Identity verified: \"\n            f\"{identity_result.details.get('identity_valid', False)}.\"\n        ),\n    )\n```\n\n**Manual Follow-Up**:\n1. Identify the code path causing excessive spending (retry loop, missing dedup, unbounded batch).\n2. Deploy fix to staging and verify with `IncidentDetector` at 30s polling for 1 hour.\n3. Run `IncidentRecovery.recover_agent()` with 50% budget.\n4. Run `IncidentForensics.run_post_mortem()` and publish findings.\n\n---\n\n### Runbook 2: Escrow Exploitation\n\n**Trigger**: An agent's escrow cancellation rate exceeds 50% in a 1-hour window, OR a single counterparty is the payee on more than 10 escrows from the same payer within 5 minutes.\n\n**Severity**: P1 (potential fraud, financial exposure)\n\n**Automated Response**:\n```python\ndef handle_escrow_exploitation(agent_id: str, suspect_payee_id: str):\n    \"\"\"Runbook 2: Respond to suspected escrow exploitation.\"\"\"\n    containment = IncidentContainment(\n        api_key=API_KEY, agent_id=agent_id,\n    )\n\n    # Step 1: Freeze the payer agent's budget\n    containment.freeze_agent()\n\n    # Step 2: Cancel escrows -- but only those to the suspect payee\n    escrows_resp = containment._execute(\"list_escrows\", {\n        \"agent_id\": agent_id,\n    })\n    escrows = escrows_resp.get(\"escrows\", [])\n\n    suspect_escrows = [\n        e for e in escrows\n        if e.get(\"payee_id\") == suspect_payee_id\n        and e.get(\"status\") in (\"pending\", \"funded\", \"active\")\n    ]\n\n    cancelled_amount = 0\n    for escrow in suspect_escrows:\n        try:\n            containment._execute(\"cancel_escrow\", {\n                \"escrow_id\": escrow[\"escrow_id\"],\n                \"reason\": f\"escrow_exploitation_suspected:{suspect_payee_id}\",\n            })\n            cancelled_amount += float(escrow.get(\"amount\", \"0\"))\n        except requests.exceptions.RequestException:\n            pass  # Log and continue; do not stop on individual failures\n\n    # Step 3: Check the suspect payee's reputation\n    payee_rep = containment._execute(\"get_agent_reputation\", {\n        \"agent_id\": suspect_payee_id,\n    })\n\n    # Step 4: Flag the suspect via metrics submission\n    containment._execute(\"submit_metrics\", {\n        \"agent_id\": suspect_payee_id,\n        \"metrics\": {\n            \"escrow_exploitation_flag\": True,\n            \"flagged_by\": agent_id,\n            \"flagged_at\": int(time.time()),\n            \"suspect_escrow_count\": len(suspect_escrows),\n        },\n    })\n\n    alert_oncall(\n        severity=\"P1\",\n        message=(\n            f\"Escrow exploitation suspected. Payer: {agent_id}. \"\n            f\"Suspect payee: {suspect_payee_id}. \"\n            f\"{len(suspect_escrows)} escrows cancelled. \"\n            f\"${round(cancelled_amount, 2)} recovered. \"\n            f\"Payee reputation: {payee_rep.get('reputation_score', 'N\u002FA')}.\"\n        ),\n    )\n```\n\n**Manual Follow-Up**:\n1. Review the suspect payee's full transaction history via `get_claim_chains`.\n2. If exploitation confirmed, report to platform via dispute mechanism.\n3. If false positive, unfreeze payer budget and remove metrics flag.\n\n---\n\n### Runbook 3: Identity Compromise\n\n**Trigger**: `IncidentContainment.verify_agent_identity()` returns `identity_valid: false`, OR the agent's public key changes unexpectedly, OR authentication patterns change (new IP, new user-agent, unusual hours).\n\n**Severity**: P0 (security breach)\n\n**Automated Response**:\n```python\ndef handle_identity_compromise(agent_id: str):\n    \"\"\"Runbook 3: Respond to suspected agent identity compromise.\"\"\"\n    containment = IncidentContainment(\n        api_key=API_KEY, agent_id=agent_id,\n    )\n\n    # Step 1: Full containment (budget + escrows + identity check)\n    results = containment.contain_agent()\n\n    # Step 2: Get the full identity record for forensic preservation\n    identity = containment._execute(\"get_agent_identity\", {\n        \"agent_id\": agent_id,\n    })\n\n    # Step 3: Get claim chains -- preserve the cryptographic audit trail\n    #         before any attacker can attempt to modify history\n    chains = containment._execute(\"get_claim_chains\", {\n        \"agent_id\": agent_id,\n    })\n\n    # Step 4: Check reputation for signs of attacker activity\n    reputation = containment._execute(\"get_agent_reputation\", {\n        \"agent_id\": agent_id,\n    })\n\n    # Step 5: Publish high-priority security event\n    containment._execute(\"publish_event\", {\n        \"agent_id\": agent_id,\n        \"event_type\": \"security_identity_compromise\",\n        \"payload\": {\n            \"severity\": \"P0\",\n            \"identity_snapshot\": identity,\n            \"chain_count\": len(chains.get(\"chains\", [])),\n            \"reputation_at_detection\": reputation.get(\"reputation_score\"),\n            \"timestamp\": int(time.time()),\n            \"action_required\": \"immediate_investigation\",\n        },\n    })\n\n    alert_oncall(\n        severity=\"P0\",\n        message=(\n            f\"IDENTITY COMPROMISE SUSPECTED for {agent_id}. \"\n            f\"All financial operations frozen. \"\n            f\"Audit trail preserved ({len(chains.get('chains', []))} chains). \"\n            f\"Immediate investigation required.\"\n        ),\n    )\n```\n\n**Manual Follow-Up**:\n1. Rotate all API keys associated with the compromised agent.\n2. Re-register the agent identity with new key material.\n3. Audit all transactions since the last known-good verification.\n4. Re-verify all counterparties the compromised agent transacted with.\n5. Run `IncidentForensics.run_post_mortem()` with full transaction window.\n\n---\n\n### Runbook 4: Service Degradation\n\n**Trigger**: `IncidentDetector.check_reputation_drift()` returns severity \"warning\" or \"critical\" -- reputation has dropped more than 15% from baseline.\n\n**Severity**: P2 (quality degradation, not immediate financial loss)\n\n**Automated Response**:\n```python\ndef handle_service_degradation(agent_id: str, anomaly: AnomalyResult):\n    \"\"\"Runbook 4: Respond to agent service quality degradation.\"\"\"\n    # Service degradation does NOT warrant immediate budget freeze.\n    # Instead, reduce budget to limit blast radius and alert.\n\n    api = requests.Session()\n    api.headers.update({\n        \"Content-Type\": \"application\u002Fjson\",\n        \"Authorization\": f\"Bearer {API_KEY}\",\n    })\n\n    def execute(tool, input_data):\n        resp = api.post(\n            f\"{BASE_URL}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        resp.raise_for_status()\n        return resp.json()\n\n    # Step 1: Get current budget and reduce by 50%\n    budget = execute(\"get_budget_status\", {\"agent_id\": agent_id})\n    current_daily = float(budget.get(\"daily_limit\", \"1000\"))\n    reduced_daily = str(round(current_daily * 0.5, 2))\n\n    execute(\"set_budget_cap\", {\n        \"agent_id\": agent_id,\n        \"daily\": reduced_daily,\n    })\n\n    # Step 2: Get detailed reputation data\n    reputation = execute(\"get_agent_reputation\", {\"agent_id\": agent_id})\n\n    # Step 3: Get usage analytics to correlate quality with volume\n    analytics = execute(\"get_usage_analytics\", {\"agent_id\": agent_id})\n\n    # Step 4: Publish degradation event\n    execute(\"publish_event\", {\n        \"agent_id\": agent_id,\n        \"event_type\": \"service_degradation_detected\",\n        \"payload\": {\n            \"reputation_drop\": anomaly.details.get(\"drop_pct\", \"unknown\"),\n            \"budget_reduced_to\": reduced_daily,\n            \"analytics_snapshot\": analytics,\n            \"timestamp\": int(time.time()),\n        },\n    })\n\n    alert_oncall(\n        severity=\"P2\",\n        message=(\n            f\"Service degradation for {agent_id}. \"\n            f\"Reputation dropped {anomaly.details.get('drop_pct', '?')}%. \"\n            f\"Budget reduced to ${reduced_daily}\u002Fday. \"\n            f\"Investigate quality metrics.\"\n        ),\n    )\n```\n\n**Manual Follow-Up**:\n1. Review recent agent outputs and counterparty feedback.\n2. Check for model drift, prompt degradation, or upstream dependency changes.\n3. If root cause is model-related, update prompts or constraints and redeploy.\n4. Use `IncidentRecovery.restore_reputation()` to submit corrected metrics.\n5. Gradually restore budget using the gradual restoration pattern.\n\n---\n\n### Runbook 5: Cascade Failure\n\n**Trigger**: Two or more agents trigger anomaly alerts within a 5-minute window, OR a shared resource (wallet, escrow pool, marketplace listing) is exhausted.\n\n**Severity**: P0 (multi-agent system failure)\n\n**Automated Response**:\n```python\ndef handle_cascade_failure(affected_agent_ids: list[str]):\n    \"\"\"Runbook 5: Respond to multi-agent cascade failure.\"\"\"\n    containment_results = {}\n\n    # Step 1: Freeze ALL affected agents simultaneously\n    for agent_id in affected_agent_ids:\n        containment = IncidentContainment(\n            api_key=API_KEY, agent_id=agent_id,\n        )\n        containment_results[agent_id] = containment.contain_agent()\n\n    # Step 2: Identify the root cause agent\n    #         (the one with the highest spending anomaly)\n    spending_anomalies = {}\n    for agent_id in affected_agent_ids:\n        detector = IncidentDetector(\n            api_key=API_KEY, agent_id=agent_id,\n        )\n        anomaly = detector.check_cost_anomaly()\n        if anomaly.detected:\n            z_score = float(anomaly.details.get(\"z_score\", \"0\"))\n            spending_anomalies[agent_id] = z_score\n\n    root_cause_agent = (\n        max(spending_anomalies, key=spending_anomalies.get)\n        if spending_anomalies else affected_agent_ids[0]\n    )\n\n    # Step 3: Deep forensics on root cause agent\n    forensics = IncidentForensics(\n        api_key=API_KEY, agent_id=root_cause_agent,\n    )\n    impact = forensics.assess_impact()\n\n    # Step 4: Publish cascade event with full scope\n    api = requests.Session()\n    api.headers.update({\n        \"Content-Type\": \"application\u002Fjson\",\n        \"Authorization\": f\"Bearer {API_KEY}\",\n    })\n    api.post(\n        f\"{BASE_URL}\u002Fv1\",\n        json={\n            \"tool\": \"publish_event\",\n            \"input\": {\n                \"agent_id\": root_cause_agent,\n                \"event_type\": \"cascade_failure\",\n                \"payload\": {\n                    \"affected_agents\": affected_agent_ids,\n                    \"root_cause_agent\": root_cause_agent,\n                    \"total_agents_affected\": len(affected_agent_ids),\n                    \"timestamp\": int(time.time()),\n                },\n            },\n        },\n    )\n\n    alert_oncall(\n        severity=\"P0\",\n        message=(\n            f\"CASCADE FAILURE: {len(affected_agent_ids)} agents affected. \"\n            f\"All frozen. Root cause agent: {root_cause_agent} \"\n            f\"(z-score: {spending_anomalies.get(root_cause_agent, 'N\u002FA')}). \"\n            f\"Impact: {json.dumps(impact.details.get('escrow_impact', {}))}.\"\n        ),\n    )\n\n    return {\n        \"root_cause_agent\": root_cause_agent,\n        \"containment_results\": {\n            aid: [r.to_dict() for r in results]\n            for aid, results in containment_results.items()\n        },\n        \"spending_anomalies\": spending_anomalies,\n    }\n```\n\n**Manual Follow-Up**:\n1. Identify the dependency chain: which agent triggered which agent's failure.\n2. Fix the root cause agent first, then recover downstream agents in dependency order.\n3. Implement circuit breakers between agents to prevent future cascades (see Chapter 7).\n4. Run post-mortems for all affected agents and correlate timelines.\n\n---\n\n## Chapter 7: Automated Incident Response\n\n### From Detection to Containment in Under 5 Seconds\n\nThe runbooks in Chapter 6 are designed for automation. The `AutomatedResponse` class ties detection to containment to escalation in a single pipeline. When the `IncidentDetector` fires, the `AutomatedResponse` executes the appropriate runbook without human intervention.\n\n### The AutomatedResponse Class\n\n```python\nimport requests\nimport time\nimport json\nfrom typing import Optional, Callable\nfrom dataclasses import dataclass, field\nfrom enum import Enum\n\n\nclass EscalationTier(Enum):\n    \"\"\"Escalation tiers for incident response.\"\"\"\n    AUTO_CONTAIN = \"auto_contain\"      # Automated freeze, alert on-call\n    ALERT_HUMAN = \"alert_human\"         # Alert without automated action\n    FULL_SHUTDOWN = \"full_shutdown\"      # Freeze all agents in fleet\n\n\nclass CircuitState(Enum):\n    \"\"\"Circuit breaker states.\"\"\"\n    CLOSED = \"closed\"      # Normal operation\n    OPEN = \"open\"          # Tripped, all operations blocked\n    HALF_OPEN = \"half_open\"  # Testing recovery\n\n\n@dataclass\nclass CircuitBreaker:\n    \"\"\"Circuit breaker for agent commerce operations.\"\"\"\n    agent_id: str\n    state: CircuitState = CircuitState.CLOSED\n    failure_count: int = 0\n    failure_threshold: int = 5\n    reset_timeout_seconds: int = 300\n    last_failure_time: float = 0\n    last_state_change: float = field(default_factory=time.time)\n\n    def record_failure(self):\n        self.failure_count += 1\n        self.last_failure_time = time.time()\n        if self.failure_count >= self.failure_threshold:\n            self.state = CircuitState.OPEN\n            self.last_state_change = time.time()\n\n    def record_success(self):\n        if self.state == CircuitState.HALF_OPEN:\n            self.state = CircuitState.CLOSED\n            self.failure_count = 0\n            self.last_state_change = time.time()\n\n    def should_allow(self) -> bool:\n        if self.state == CircuitState.CLOSED:\n            return True\n        if self.state == CircuitState.OPEN:\n            elapsed = time.time() - self.last_state_change\n            if elapsed >= self.reset_timeout_seconds:\n                self.state = CircuitState.HALF_OPEN\n                self.last_state_change = time.time()\n                return True\n            return False\n        # HALF_OPEN: allow one request to test\n        return True\n\n\nclass AutomatedResponse:\n    \"\"\"Automated incident response pipeline.\n\n    Connects detection signals to containment actions with\n    configurable escalation tiers.\n\n    Usage:\n        responder = AutomatedResponse(\n            api_key=\"your-key\",\n            fleet_agent_ids=[\"agent-001\", \"agent-002\", \"agent-003\"],\n            oncall_callback=send_pagerduty_alert,\n        )\n\n        # Register custom escalation rules\n        responder.add_rule(\n            signal=\"cost_anomaly\",\n            severity=\"critical\",\n            tier=EscalationTier.AUTO_CONTAIN,\n        )\n        responder.add_rule(\n            signal=\"reputation_drift\",\n            severity=\"warning\",\n            tier=EscalationTier.ALERT_HUMAN,\n        )\n\n        # Start automated monitoring\n        responder.start(interval_seconds=30)\n    \"\"\"\n\n    DEFAULT_RULES = {\n        (\"cost_anomaly\", \"critical\"): EscalationTier.AUTO_CONTAIN,\n        (\"cost_anomaly\", \"warning\"): EscalationTier.ALERT_HUMAN,\n        (\"budget_exhaustion\", \"critical\"): EscalationTier.AUTO_CONTAIN,\n        (\"budget_warning\", \"warning\"): EscalationTier.ALERT_HUMAN,\n        (\"reputation_drift\", \"critical\"): EscalationTier.AUTO_CONTAIN,\n        (\"reputation_drift\", \"warning\"): EscalationTier.ALERT_HUMAN,\n        (\"detection_failure\", \"warning\"): EscalationTier.ALERT_HUMAN,\n    }\n\n    def __init__(\n        self,\n        api_key: str,\n        fleet_agent_ids: list[str],\n        base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n        oncall_callback: Optional[Callable] = None,\n    ):\n        self.api_key = api_key\n        self.fleet_agent_ids = fleet_agent_ids\n        self.base_url = base_url\n        self.oncall_callback = oncall_callback or self._default_alert\n        self.rules: dict[tuple[str, str], EscalationTier] = dict(\n            self.DEFAULT_RULES\n        )\n        self._circuit_breakers: dict[str, CircuitBreaker] = {\n            aid: CircuitBreaker(agent_id=aid)\n            for aid in fleet_agent_ids\n        }\n        self._incident_log: list[dict] = []\n        self._detectors: dict[str, IncidentDetector] = {\n            aid: IncidentDetector(\n                api_key=api_key,\n                agent_id=aid,\n                base_url=base_url,\n            )\n            for aid in fleet_agent_ids\n        }\n\n    @staticmethod\n    def _default_alert(severity: str, message: str):\n        print(f\"[ALERT {severity}] {message}\")\n\n    def add_rule(\n        self,\n        signal: str,\n        severity: str,\n        tier: EscalationTier,\n    ):\n        \"\"\"Add or override an escalation rule.\"\"\"\n        self.rules[(signal, severity)] = tier\n\n    # ── Core Response Actions ──────────────────────────────────\n\n    def auto_contain(self, agent_id: str, anomaly: AnomalyResult):\n        \"\"\"Execute automated containment for a single agent.\"\"\"\n        containment = IncidentContainment(\n            api_key=self.api_key,\n            agent_id=agent_id,\n            base_url=self.base_url,\n        )\n        results = containment.contain_agent()\n\n        # Record in circuit breaker\n        breaker = self._circuit_breakers.get(agent_id)\n        if breaker:\n            breaker.record_failure()\n\n        # Log the incident\n        incident = {\n            \"incident_id\": f\"inc-{int(time.time())}-{agent_id}\",\n            \"agent_id\": agent_id,\n            \"signal\": anomaly.signal,\n            \"severity\": anomaly.severity,\n            \"tier\": EscalationTier.AUTO_CONTAIN.value,\n            \"containment_results\": [r.to_dict() for r in results],\n            \"timestamp\": time.time(),\n        }\n        self._incident_log.append(incident)\n\n        # Alert on-call\n        self.oncall_callback(\n            severity=anomaly.severity.upper(),\n            message=(\n                f\"Auto-contained {agent_id}: {anomaly.signal}. \"\n                f\"Details: {json.dumps(anomaly.details)}\"\n            ),\n        )\n\n        return incident\n\n    def escalate(\n        self,\n        agent_id: str,\n        anomaly: AnomalyResult,\n        tier: EscalationTier,\n    ):\n        \"\"\"Escalate an anomaly to the appropriate tier.\"\"\"\n        if tier == EscalationTier.AUTO_CONTAIN:\n            return self.auto_contain(agent_id, anomaly)\n        elif tier == EscalationTier.ALERT_HUMAN:\n            self.oncall_callback(\n                severity=anomaly.severity.upper(),\n                message=(\n                    f\"Alert for {agent_id}: {anomaly.signal}. \"\n                    f\"No automated action taken. \"\n                    f\"Details: {json.dumps(anomaly.details)}\"\n                ),\n            )\n            return {\n                \"agent_id\": agent_id,\n                \"tier\": tier.value,\n                \"action\": \"alert_only\",\n            }\n        elif tier == EscalationTier.FULL_SHUTDOWN:\n            return self._full_shutdown(anomaly)\n\n    def _full_shutdown(self, trigger_anomaly: AnomalyResult) -> dict:\n        \"\"\"Emergency: freeze every agent in the fleet.\"\"\"\n        results = {}\n        for agent_id in self.fleet_agent_ids:\n            containment = IncidentContainment(\n                api_key=self.api_key,\n                agent_id=agent_id,\n                base_url=self.base_url,\n            )\n            results[agent_id] = [\n                r.to_dict() for r in containment.contain_agent()\n            ]\n\n        self.oncall_callback(\n            severity=\"P0\",\n            message=(\n                f\"FULL FLEET SHUTDOWN executed. \"\n                f\"{len(self.fleet_agent_ids)} agents frozen. \"\n                f\"Trigger: {trigger_anomaly.agent_id} - \"\n                f\"{trigger_anomaly.signal}.\"\n            ),\n        )\n\n        return {\n            \"action\": \"full_shutdown\",\n            \"agents_frozen\": len(self.fleet_agent_ids),\n            \"results\": results,\n        }\n\n    # ── Circuit Breaker ────────────────────────────────────────\n\n    def circuit_breaker(self, agent_id: str) -> CircuitBreaker:\n        \"\"\"Get the circuit breaker for an agent.\n\n        The circuit breaker tracks failure counts and automatically\n        blocks operations when an agent exceeds the failure threshold.\n        After the reset timeout, it enters half-open state and allows\n        a single test operation.\n\n        Usage in agent code:\n            breaker = responder.circuit_breaker(\"agent-001\")\n            if breaker.should_allow():\n                try:\n                    result = execute_tool(...)\n                    breaker.record_success()\n                except Exception:\n                    breaker.record_failure()\n            else:\n                # Agent is circuit-broken, skip operation\n                log.warning(f\"Circuit open for {agent_id}\")\n        \"\"\"\n        if agent_id not in self._circuit_breakers:\n            self._circuit_breakers[agent_id] = CircuitBreaker(\n                agent_id=agent_id,\n            )\n        return self._circuit_breakers[agent_id]\n\n    # ── Monitoring Loop ────────────────────────────────────────\n\n    def _process_anomalies(self, agent_id: str, anomalies: list):\n        \"\"\"Process detected anomalies through the escalation rules.\"\"\"\n        # Check circuit breaker first\n        breaker = self._circuit_breakers.get(agent_id)\n        if breaker and breaker.state == CircuitState.OPEN:\n            # Agent is already circuit-broken, auto-contain\n            for anomaly in anomalies:\n                self.auto_contain(agent_id, anomaly)\n            return\n\n        for anomaly in anomalies:\n            rule_key = (anomaly.signal, anomaly.severity)\n            tier = self.rules.get(rule_key, EscalationTier.ALERT_HUMAN)\n            self.escalate(agent_id, anomaly, tier)\n\n    def start(\n        self,\n        interval_seconds: int = 30,\n        max_iterations: Optional[int] = None,\n    ):\n        \"\"\"Start the automated response monitoring loop.\n\n        Polls all fleet agents for anomalies and triggers the\n        appropriate response based on escalation rules.\n        \"\"\"\n        # Check for cascade condition: multiple agents alerting\n        cascade_window: dict[str, float] = {}\n        cascade_threshold = 2  # agents within 5 minutes = cascade\n\n        iteration = 0\n        while max_iterations is None or iteration \u003C max_iterations:\n            alerting_agents = []\n\n            for agent_id in self.fleet_agent_ids:\n                detector = self._detectors[agent_id]\n                anomalies = detector.check_all()\n\n                if anomalies:\n                    alerting_agents.append(agent_id)\n                    cascade_window[agent_id] = time.time()\n                    self._process_anomalies(agent_id, anomalies)\n\n            # Check for cascade condition\n            now = time.time()\n            recent_alerts = {\n                aid: t for aid, t in cascade_window.items()\n                if now - t \u003C 300  # 5-minute window\n            }\n            if len(recent_alerts) >= cascade_threshold:\n                handle_cascade_failure(list(recent_alerts.keys()))\n                cascade_window.clear()\n\n            time.sleep(interval_seconds)\n            iteration += 1\n\n    def get_incident_log(self) -> list[dict]:\n        \"\"\"Return all incidents handled by this responder.\"\"\"\n        return list(self._incident_log)\n```\n\n### Webhook-Triggered Containment\n\nFor organizations that prefer push-based alerting over polling, the `AutomatedResponse` integrates with GreenHelix webhooks. The webhook handler receives events from the gateway and triggers containment directly:\n\n```python\nfrom flask import Flask, request, jsonify\n\napp = Flask(__name__)\n\nresponder = AutomatedResponse(\n    api_key=API_KEY,\n    fleet_agent_ids=[\"agent-001\", \"agent-002\", \"agent-003\"],\n    oncall_callback=send_pagerduty_alert,\n)\n\n@app.route(\"\u002Fincidents\u002Fwebhook\", methods=[\"POST\"])\ndef handle_webhook():\n    \"\"\"Receive GreenHelix webhook events and trigger response.\"\"\"\n    event = request.get_json()\n    event_type = event.get(\"event_type\", \"\")\n    agent_id = event.get(\"agent_id\", \"\")\n    payload = event.get(\"payload\", {})\n\n    if event_type == \"budget_threshold\":\n        utilization = float(payload.get(\"utilization_pct\", 0))\n        if utilization >= 95:\n            anomaly = AnomalyResult(\n                detected=True,\n                signal=\"budget_exhaustion\",\n                severity=\"critical\",\n                agent_id=agent_id,\n                details=payload,\n            )\n            responder.auto_contain(agent_id, anomaly)\n        elif utilization >= 80:\n            responder.oncall_callback(\n                severity=\"WARNING\",\n                message=f\"Budget at {utilization}% for {agent_id}\",\n            )\n\n    elif event_type == \"reputation_change\":\n        score_delta = float(payload.get(\"score_delta\", 0))\n        if score_delta \u003C -0.15:\n            anomaly = AnomalyResult(\n                detected=True,\n                signal=\"reputation_drift\",\n                severity=\"critical\" if score_delta \u003C -0.30 else \"warning\",\n                agent_id=agent_id,\n                details=payload,\n            )\n            responder.escalate(\n                agent_id, anomaly,\n                EscalationTier.AUTO_CONTAIN\n                if score_delta \u003C -0.30\n                else EscalationTier.ALERT_HUMAN,\n            )\n\n    return jsonify({\"status\": \"processed\"})\n```\n\n### The Escalation Ladder\n\n```\n                ┌──────────────────────────────────────┐\n                │         FULL FLEET SHUTDOWN           │\n                │   All agents frozen. All hands.       │\n                │   Trigger: cascade failure (2+ P0s)   │\n                └──────────────┬───────────────────────┘\n                               │\n                ┌──────────────▼───────────────────────┐\n                │         AUTO-CONTAIN                  │\n                │   Budget frozen. Escrows cancelled.   │\n                │   On-call alerted.                    │\n                │   Trigger: critical anomaly           │\n                └──────────────┬───────────────────────┘\n                               │\n                ┌──────────────▼───────────────────────┐\n                │         ALERT HUMAN                   │\n                │   No automated action.                │\n                │   On-call notified for investigation. │\n                │   Trigger: warning anomaly            │\n                └──────────────────────────────────────┘\n```\n\nThe default mapping is conservative: critical anomalies auto-contain, warnings alert humans, and cascade failures shut down the fleet. Override with `add_rule()` to tune for your risk tolerance. A trading firm may want warnings to also auto-contain. A low-value agent fleet may want only critical signals to trigger any response.\n\n---\n\n## Chapter 8: Incident Readiness Checklist\n\n### Pre-Incident Setup\n\nComplete this checklist before your first production deployment. Every item maps to a class or method in this guide.\n\n**Detection Infrastructure**\n\n- [ ] `IncidentDetector` deployed for each production agent\n- [ ] Cost anomaly threshold tuned (`cost_anomaly_std_devs` calibrated against 2 weeks of baseline data)\n- [ ] Reputation drift threshold set (`reputation_drop_threshold` based on normal variance)\n- [ ] Webhook endpoints registered via `setup_alerts()` for budget, escrow, and reputation events\n- [ ] Webhook receiver deployed and health-checked (if webhook receiver is down, detection is blind)\n- [ ] Monitoring interval configured (30s for high-value agents, 5m for low-value)\n\n**Containment Readiness**\n\n- [ ] `IncidentContainment` tested against sandbox for each agent\n- [ ] Containment completes within 60 seconds (verified via timing test)\n- [ ] API key used for containment has permissions for `set_budget_cap`, `list_escrows`, `cancel_escrow`, `verify_agent`, `get_agent_identity`, `publish_event`\n- [ ] Containment API key is separate from agent's operational key (so a compromised agent key does not prevent containment)\n\n**Recovery Procedures**\n\n- [ ] Pre-incident budget levels documented for each agent\n- [ ] Gradual restoration schedule defined (50% \u002F 75% \u002F 100% over 48 hours)\n- [ ] Recovery verification criteria defined (what \"normal\" looks like post-incident)\n- [ ] `IncidentRecovery` tested against sandbox\n\n**Forensics Capability**\n\n- [ ] `IncidentForensics` tested and producing valid post-mortem reports\n- [ ] Claim chains actively maintained for all production agents (if claim chains are empty, there is no audit trail to review)\n- [ ] Billing analytics accessible (confirm `get_usage_analytics`, `get_billing_summary`, `get_spending_by_category` all return data)\n\n### Severity Classification\n\n| Severity | Description | Response Time | Automated Action |\n|---|---|---|---|\n| **P0** | Active financial loss or security breach | Immediate (auto-contained in \u003C5s) | Full containment + on-call page |\n| **P1** | Potential fraud or escalating exposure | \u003C 15 minutes | Budget freeze + on-call page |\n| **P2** | Quality degradation or budget warning | \u003C 1 hour | Budget reduction + Slack alert |\n| **P3** | Informational anomaly, no action needed | Next business day | Log only |\n\n### On-Call Rotation for Agent Systems\n\nAgent on-call differs from traditional service on-call in three ways:\n\n1. **Financial authority required**: The on-call engineer must have permissions to restore budgets, cancel escrows, and re-register agent identities. Without these permissions, recovery is blocked.\n\n2. **Model knowledge required**: Agent incidents often require understanding model behavior, prompt engineering, and stochastic reasoning. The on-call rotation should include engineers with ML\u002FAI experience, not only infrastructure engineers.\n\n3. **Faster escalation**: Traditional on-call escalation gives 30 minutes before paging a secondary. Agent on-call should escalate in 5 minutes for P0 and 15 minutes for P1, because financial exposure grows linearly with response time.\n\n### Cross-References to Companion Guides\n\nThis guide completes the operational lifecycle when combined with three companion guides:\n\n- **Locking Down Agent Commerce** (P8) covers prevention: security hardening, identity verification, credential isolation, and financial guardrails. Read P8 to reduce the frequency of incidents.\n- **The Agent Testing & Observability Cookbook** (P9) covers detection infrastructure: the `AgentTracer`, `HealthChecker`, chaos testing, and CI\u002FCD pipelines. Read P9 to build the monitoring foundation that feeds into this guide's `IncidentDetector`.\n- **Ship Compliant Agents** (P11) covers the regulatory dimension: EU AI Act compliance, audit trail requirements (Article 12), and liability-bounded escrow patterns. Read P11 to ensure your incident response satisfies regulatory obligations for logging and reporting.\n\nTogether, the four guides form a closed loop:\n\n```\nP8 (Security)  ──prevent──▶  P9 (Observability)  ──detect──▶\nP12 (Incident Response)  ──recover──▶  P11 (Compliance)  ──audit──▶\n```\n\n### Practice on the Sandbox\n\nThe sandbox at `sandbox.greenhelix.net` is free to use with any API key. Deploy the `IncidentDetector` against it. Trigger a simulated incident by rapidly creating escrows. Verify that `IncidentContainment.contain_agent()` freezes the budget and cancels the escrows. Run `IncidentForensics.run_post_mortem()` and review the output. Build muscle memory for incident response before you need it in production.\n\n### The Full Lifecycle\n\n```python\n# Complete incident response lifecycle in 30 lines\n\n# 1. Detection\ndetector = IncidentDetector(api_key=KEY, agent_id=AGENT)\ndetector.setup_alerts(webhook_url=WEBHOOK_URL)\nanomalies = detector.check_all()\n\n# 2. Containment (if critical)\nif any(a.severity == \"critical\" for a in anomalies):\n    containment = IncidentContainment(api_key=KEY, agent_id=AGENT)\n    containment_results = containment.contain_agent()\n    containment_time = int(time.time())\n\n# 3. Recovery (after root cause fixed)\nrecovery = IncidentRecovery(api_key=KEY, agent_id=AGENT)\nrecovery_results = recovery.recover_agent(\n    target_daily_budget=\"500.00\",\n    initial_budget_pct=50,\n)\n\n# 4. Post-mortem\nforensics = IncidentForensics(api_key=KEY, agent_id=AGENT)\nreport = forensics.run_post_mortem(\n    incident_id=\"inc-001\",\n    incident_start=int(time.time()) - 3600,\n    incident_end=int(time.time()),\n    containment_log=containment.get_containment_log(),\n    recovery_log=recovery.get_recovery_log(),\n)\nprint(json.dumps(report, indent=2))\n```\n\nFour phases, four classes, four API calls each. Detect, contain, recover, learn. Copy the classes into your project, tune the thresholds, set up the webhooks, and practice on the sandbox. When the 2:47 AM alert fires, you will have a runbook.\n\n### The Bundle\n\nAll companion guides plus this playbook are available as a bundle. Each guide introduces production-ready Python classes that compose into a complete agent commerce platform: building (P1), cost management (P2), reputation (P3), audit trails (P4), trust verification (P5), marketplace strategy (P6), multi-agent patterns (P7), security hardening (P8), testing and observability (P9), SaaS automation (P10), compliance (P11), and incident response (P12).\n\nFor the full API reference and tool catalog (all 128 tools), visit the GreenHelix developer documentation at [https:\u002F\u002Fapi.greenhelix.net\u002Fdocs](https:\u002F\u002Fapi.greenhelix.net\u002Fdocs).\n\n---\n\n*Price: $29 | Format: Digital Guide | Updates: Lifetime access*\n\n---\n\n## Automated Incident Detection & Escalation — 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\"\"\"\nAutomated incident detection and escalation using the greenhelix_trading library.\n\nCovers:\n  1. Anomaly detection pipeline (cost, reputation, budget)\n  2. Automatic containment actions (freeze, escrow cancel, identity verify)\n  3. Guided recovery procedures with graduated budget restoration\n  4. Forensic evidence collection (audit trails, impact, timeline)\n  5. End-to-end incident orchestrator\n\nRequirements:\n    pip install greenhelix-trading\n\"\"\"\n\nimport os\nimport time\nimport json\nfrom datetime import datetime, timezone\nfrom typing import Optional\nfrom dataclasses import dataclass, field\n\nfrom greenhelix_trading import (\n    IncidentDetector,\n    IncidentContainment,\n    IncidentRecovery,\n    IncidentForensics,\n)\n\n\n# ── Configuration ─────────────────────────────────────────────────────────────\n\nAPI_KEY = os.environ[\"GREENHELIX_API_KEY\"]\nAGENT_ID = os.environ[\"GREENHELIX_AGENT_ID\"]\nWEBHOOK_URL = os.environ.get(\n    \"GREENHELIX_WEBHOOK_URL\",\n    \"https:\u002F\u002Fyour-app.example.com\u002Fincidents\u002Fwebhook\",\n)\n\n\n# ── Data Classes ──────────────────────────────────────────────────────────────\n\n@dataclass\nclass IncidentRecord:\n    \"\"\"Complete record of a detected, contained, and recovered incident.\"\"\"\n    incident_id: str\n    agent_id: str\n    detected_at: float = field(default_factory=time.time)\n    contained_at: Optional[float] = None\n    recovered_at: Optional[float] = None\n    detection_signals: list = field(default_factory=list)\n    containment_results: list = field(default_factory=list)\n    recovery_results: list = field(default_factory=list)\n    forensics_report: Optional[dict] = None\n    severity: str = \"unknown\"\n\n    def elapsed_to_containment(self) -> Optional[float]:\n        if self.contained_at:\n            return round(self.contained_at - self.detected_at, 2)\n        return None\n\n    def elapsed_to_recovery(self) -> Optional[float]:\n        if self.recovered_at:\n            return round(self.recovered_at - self.detected_at, 2)\n        return None\n\n    def to_dict(self) -> dict:\n        return {\n            \"incident_id\": self.incident_id,\n            \"agent_id\": self.agent_id,\n            \"severity\": self.severity,\n            \"detected_at\": self.detected_at,\n            \"contained_at\": self.contained_at,\n            \"recovered_at\": self.recovered_at,\n            \"elapsed_to_containment_s\": self.elapsed_to_containment(),\n            \"elapsed_to_recovery_s\": self.elapsed_to_recovery(),\n            \"detection_signals\": self.detection_signals,\n            \"containment_results\": self.containment_results,\n            \"recovery_results\": self.recovery_results,\n            \"forensics_report\": self.forensics_report,\n        }\n\n\n# ── 1. Anomaly Detection Pipeline ────────────────────────────────────────────\n\nclass AnomalyPipeline:\n    \"\"\"Multi-signal anomaly detection using IncidentDetector.\n\n    Runs three independent checks — cost anomaly, reputation drift,\n    and spending breakdown — and correlates the signals to produce\n    a severity classification.\n\n    Uses:\n        IncidentDetector.check_cost_anomaly()\n        IncidentDetector.check_reputation_drift(baseline_score)\n        IncidentDetector.setup_alerts(webhook_url)\n        IncidentDetector.get_spending_breakdown()\n    \"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        cost_threshold: float = 500.0,\n        reputation_threshold: float = 0.1,\n        baseline_reputation: float = 0.85,\n    ):\n        self.agent_id = agent_id\n        self.baseline_reputation = baseline_reputation\n        self._detector = IncidentDetector(\n            api_key=api_key,\n            agent_id=agent_id,\n            cost_threshold=cost_threshold,\n            reputation_threshold=reputation_threshold,\n        )\n        self._alert_history: list[dict] = []\n\n    def setup_webhook_alerts(self, webhook_url: str) -> dict:\n        \"\"\"Register persistent webhook alerts for budget, escrow, and\n        reputation events.\n\n        Calls IncidentDetector.setup_alerts which wraps register_webhook\n        with the event types: budget_exceeded, reputation_change,\n        escrow_timeout.\n        \"\"\"\n        result = self._detector.setup_alerts(webhook_url=webhook_url)\n        return {\n            \"status\": \"configured\",\n            \"webhook_url\": webhook_url,\n            \"registration\": result,\n        }\n\n    def run_detection_cycle(self) -> dict:\n        \"\"\"Execute one full detection cycle across all signals.\n\n        Returns a dict with the severity (\"clear\", \"warning\", \"critical\"),\n        the individual signal results, and a spending breakdown for\n        context.\n        \"\"\"\n        signals = []\n        severity = \"clear\"\n\n        # Signal 1: Cost anomaly\n        cost_result = self._detector.check_cost_anomaly()\n        cost_anomaly = cost_result.get(\"anomaly\", False)\n        signals.append({\n            \"signal\": \"cost_anomaly\",\n            \"triggered\": cost_anomaly,\n            \"data\": cost_result,\n        })\n\n        # Signal 2: Reputation drift\n        rep_result = self._detector.check_reputation_drift(\n            baseline_score=self.baseline_reputation,\n        )\n        rep_drift = rep_result.get(\"drift\", False)\n        signals.append({\n            \"signal\": \"reputation_drift\",\n            \"triggered\": rep_drift,\n            \"delta\": rep_result.get(\"delta\", 0),\n            \"data\": rep_result,\n        })\n\n        # Signal 3: Spending breakdown (context, not a direct trigger)\n        spending = self._detector.get_spending_breakdown()\n        signals.append({\n            \"signal\": \"spending_context\",\n            \"triggered\": False,\n            \"data\": spending,\n        })\n\n        # Severity classification\n        triggered_count = sum(1 for s in signals if s[\"triggered\"])\n        if triggered_count >= 2:\n            severity = \"critical\"\n        elif triggered_count == 1:\n            severity = \"warning\"\n\n        cycle_result = {\n            \"timestamp\": time.time(),\n            \"agent_id\": self.agent_id,\n            \"severity\": severity,\n            \"triggered_signals\": triggered_count,\n            \"signals\": signals,\n        }\n\n        if severity != \"clear\":\n            self._alert_history.append(cycle_result)\n\n        return cycle_result\n\n    def run_continuous_monitoring(\n        self,\n        interval_seconds: int = 30,\n        max_cycles: Optional[int] = None,\n        on_anomaly=None,\n    ):\n        \"\"\"Poll-based continuous monitoring loop.\n\n        Args:\n            interval_seconds: Time between detection cycles.\n            max_cycles: Stop after N cycles (None = run forever).\n            on_anomaly: Callback(cycle_result) when severity != \"clear\".\n        \"\"\"\n        cycle = 0\n        while max_cycles is None or cycle \u003C max_cycles:\n            result = self.run_detection_cycle()\n            if result[\"severity\"] != \"clear\":\n                if on_anomaly:\n                    on_anomaly(result)\n                else:\n                    print(\n                        f\"[{result['severity'].upper()}] \"\n                        f\"Agent {self.agent_id}: \"\n                        f\"{result['triggered_signals']} signals triggered\"\n                    )\n            time.sleep(interval_seconds)\n            cycle += 1\n\n    def get_alert_history(self) -> list[dict]:\n        return list(self._alert_history)\n\n\n# ── 2. Automatic Containment ─────────────────────────────────────────────────\n\nclass AutoContainment:\n    \"\"\"Automated containment actions targeting the 60-second SLA.\n\n    Executes three steps in sequence:\n      1. Freeze budget (IncidentContainment.freeze_agent)\n      2. Cancel active escrows (IncidentContainment.freeze_escrows)\n      3. Verify identity (IncidentContainment.verify_agent_identity)\n\n    Also publishes an incident event via\n    IncidentContainment.publish_incident_event for fleet-wide visibility.\n    \"\"\"\n\n    def __init__(self, api_key: str, agent_id: str):\n        self.agent_id = agent_id\n        self._containment = IncidentContainment(\n            api_key=api_key,\n            agent_id=agent_id,\n        )\n\n    def contain(self, severity: str, trigger_signal: str) -> list[dict]:\n        \"\"\"Execute the full containment sequence.\n\n        All three steps are attempted regardless of individual failures.\n        Returns a list of result dicts, one per step.\n        \"\"\"\n        results = []\n        start = time.time()\n\n        # Step 1: Freeze the agent's budget to $0\n        try:\n            freeze_result = self._containment.freeze_agent()\n            results.append({\n                \"step\": \"freeze_budget\",\n                \"success\": True,\n                \"data\": freeze_result,\n            })\n        except Exception as exc:\n            results.append({\n                \"step\": \"freeze_budget\",\n                \"success\": False,\n                \"error\": str(exc),\n            })\n\n        # Step 2: Cancel all active escrows to recover locked funds\n        try:\n            escrow_result = self._containment.freeze_escrows()\n            results.append({\n                \"step\": \"cancel_escrows\",\n                \"success\": True,\n                \"cancelled\": escrow_result.get(\"total_frozen\", 0),\n                \"data\": escrow_result,\n            })\n        except Exception as exc:\n            results.append({\n                \"step\": \"cancel_escrows\",\n                \"success\": False,\n                \"error\": str(exc),\n            })\n\n        # Step 3: Verify agent identity has not been compromised\n        try:\n            identity_result = self._containment.verify_agent_identity()\n            results.append({\n                \"step\": \"verify_identity\",\n                \"success\": True,\n                \"identity_intact\": identity_result.get(\n                    \"verification\", {}\n                ).get(\"verified\", False),\n                \"data\": identity_result,\n            })\n        except Exception as exc:\n            results.append({\n                \"step\": \"verify_identity\",\n                \"success\": False,\n                \"error\": str(exc),\n            })\n\n        elapsed = round(time.time() - start, 2)\n\n        # Publish containment event for fleet-wide visibility\n        try:\n            self._containment.publish_incident_event(\n                severity=severity,\n                details=json.dumps({\n                    \"trigger\": trigger_signal,\n                    \"containment_elapsed_s\": elapsed,\n                    \"steps_succeeded\": sum(1 for r in results if r[\"success\"]),\n                    \"steps_total\": len(results),\n                }),\n            )\n        except Exception:\n            pass  # Event publishing must not block containment\n\n        # Annotate with timing\n        for r in results:\n            r[\"containment_elapsed_s\"] = elapsed\n            r[\"met_60s_sla\"] = elapsed \u003C= 60.0\n\n        return results\n\n\n# ── 3. Guided Recovery ────────────────────────────────────────────────────────\n\nclass GuidedRecovery:\n    \"\"\"Graduated recovery with reputation verification.\n\n    Recovery proceeds through three gates:\n      Gate 1: Restore budget at 50% of target (IncidentRecovery.restore_budget)\n      Gate 2: Submit recovery metrics (IncidentRecovery.update_reputation)\n      Gate 3: Publish recovery event (IncidentRecovery.publish_recovery_event)\n\n    After 24 hours with no anomalies, call restore_full_budget to\n    return to the pre-incident budget level.\n    \"\"\"\n\n    def __init__(self, api_key: str, agent_id: str):\n        self.agent_id = agent_id\n        self._recovery = IncidentRecovery(\n            api_key=api_key,\n            agent_id=agent_id,\n        )\n\n    def execute_recovery(\n        self,\n        target_daily_budget: float,\n        initial_pct: int = 50,\n        incident_id: str = \"\",\n    ) -> list[dict]:\n        \"\"\"Run the three-gate recovery sequence.\n\n        Args:\n            target_daily_budget: The pre-incident daily budget.\n            initial_pct: Percentage of target to restore initially.\n            incident_id: For event correlation.\n\n        Returns:\n            List of recovery step results.\n        \"\"\"\n        results = []\n        initial_budget = target_daily_budget * initial_pct \u002F 100\n\n        # Gate 1: Restore budget at conservative level\n        try:\n            budget_result = self._recovery.restore_budget(\n                daily=initial_budget,\n                monthly=initial_budget * 30,\n            )\n            results.append({\n                \"gate\": 1,\n                \"action\": \"restore_budget\",\n                \"success\": True,\n                \"budget_restored\": initial_budget,\n                \"pct_of_target\": initial_pct,\n                \"data\": budget_result,\n            })\n        except Exception as exc:\n            results.append({\n                \"gate\": 1,\n                \"action\": \"restore_budget\",\n                \"success\": False,\n                \"error\": str(exc),\n            })\n\n        # Gate 2: Submit recovery metrics to rebuild reputation\n        try:\n            metrics_result = self._recovery.update_reputation(metrics={\n                \"incident_recovery\": True,\n                \"recovery_timestamp\": int(time.time()),\n                \"post_recovery_status\": \"active\",\n                \"incident_id\": incident_id,\n            })\n            results.append({\n                \"gate\": 2,\n                \"action\": \"update_reputation\",\n                \"success\": True,\n                \"data\": metrics_result,\n            })\n        except Exception as exc:\n            results.append({\n                \"gate\": 2,\n                \"action\": \"update_reputation\",\n                \"success\": False,\n                \"error\": str(exc),\n            })\n\n        # Gate 3: Publish recovery event\n        try:\n            event_result = self._recovery.publish_recovery_event(\n                details=json.dumps({\n                    \"incident_id\": incident_id or f\"inc-{int(time.time())}\",\n                    \"budget_restored_to\": initial_budget,\n                    \"recovery_timestamp\": int(time.time()),\n                }),\n            )\n            results.append({\n                \"gate\": 3,\n                \"action\": \"publish_recovery_event\",\n                \"success\": True,\n                \"data\": event_result,\n            })\n        except Exception as exc:\n            results.append({\n                \"gate\": 3,\n                \"action\": \"publish_recovery_event\",\n                \"success\": False,\n                \"error\": str(exc),\n            })\n\n        return results\n\n    def restore_full_budget(self, target_daily_budget: float) -> dict:\n        \"\"\"Restore to full pre-incident budget after monitoring period.\n\n        Call this 24-48 hours after initial recovery once the\n        AnomalyPipeline confirms no further anomalies.\n        \"\"\"\n        try:\n            result = self._recovery.restore_budget(\n                daily=target_daily_budget,\n                monthly=target_daily_budget * 30,\n            )\n            return {\n                \"success\": True,\n                \"budget_restored\": target_daily_budget,\n                \"data\": result,\n            }\n        except Exception as exc:\n            return {\"success\": False, \"error\": str(exc)}\n\n    def post_recovery_service_rating(\n        self, service_id: str, rating: int = 3, comment: str = \"\",\n    ) -> dict:\n        \"\"\"Submit a post-incident service rating.\n\n        Uses IncidentRecovery.rate_agent_service to record a neutral\n        rating that reflects the recovery, not the incident.\n        \"\"\"\n        try:\n            result = self._recovery.rate_agent_service(\n                service_id=service_id,\n                rating=rating,\n                comment=comment or \"Service restored after incident containment.\",\n            )\n            return {\"success\": True, \"data\": result}\n        except Exception as exc:\n            return {\"success\": False, \"error\": str(exc)}\n\n\n# ── 4. Forensic Evidence Collection ──────────────────────────────────────────\n\nclass ForensicCollector:\n    \"\"\"Collect and assemble forensic evidence for post-mortem analysis.\n\n    Uses:\n        IncidentForensics.get_audit_trail()  -- claim chains\n        IncidentForensics.get_verified_claims()  -- individual claims\n        IncidentForensics.assess_impact()  -- financial impact\n        IncidentForensics.build_timeline()  -- event reconstruction\n    \"\"\"\n\n    def __init__(self, api_key: str, agent_id: str):\n        self.agent_id = agent_id\n        self._forensics = IncidentForensics(\n            api_key=api_key,\n            agent_id=agent_id,\n        )\n\n    def collect_audit_trail(self) -> dict:\n        \"\"\"Extract the cryptographic audit trail (claim chains).\n\n        IncidentForensics.get_audit_trail wraps get_claim_chains to\n        retrieve the tamper-proof record of all agent actions.\n        \"\"\"\n        return self._forensics.get_audit_trail()\n\n    def collect_verified_claims(self) -> dict:\n        \"\"\"Retrieve individually verifiable claims.\n\n        IncidentForensics.get_verified_claims wraps get_verified_claims\n        for Merkle-proof-verifiable claim records.\n        \"\"\"\n        return self._forensics.get_verified_claims()\n\n    def assess_financial_impact(self) -> dict:\n        \"\"\"Calculate the financial impact of the incident.\n\n        IncidentForensics.assess_impact pulls usage analytics, billing\n        summary, and spending-by-category to compute total incident cost.\n        \"\"\"\n        return self._forensics.assess_impact()\n\n    def reconstruct_timeline(self) -> dict:\n        \"\"\"Reconstruct the incident timeline from claim chains and\n        usage analytics.\n\n        IncidentForensics.build_timeline combines claim chain data with\n        7-day usage analytics into a chronological event sequence.\n        \"\"\"\n        return self._forensics.build_timeline()\n\n    def run_full_post_mortem(\n        self,\n        incident_record: IncidentRecord,\n    ) -> dict:\n        \"\"\"Assemble a complete post-mortem report.\n\n        Combines audit trail, verified claims, financial impact, and\n        timeline into a single structured report suitable for both\n        human review and machine ingestion.\n        \"\"\"\n        audit_trail = self.collect_audit_trail()\n        verified_claims = self.collect_verified_claims()\n        impact = self.assess_financial_impact()\n        timeline = self.reconstruct_timeline()\n\n        report = {\n            \"incident_id\": incident_record.incident_id,\n            \"agent_id\": incident_record.agent_id,\n            \"severity\": incident_record.severity,\n            \"generated_at\": int(time.time()),\n            \"timing\": {\n                \"detected_at\": incident_record.detected_at,\n                \"contained_at\": incident_record.contained_at,\n                \"recovered_at\": incident_record.recovered_at,\n                \"detection_to_containment_s\": incident_record.elapsed_to_containment(),\n                \"detection_to_recovery_s\": incident_record.elapsed_to_recovery(),\n                \"met_60s_containment_sla\": (\n                    incident_record.elapsed_to_containment() is not None\n                    and incident_record.elapsed_to_containment() \u003C= 60.0\n                ),\n            },\n            \"audit_trail\": audit_trail,\n            \"verified_claims\": verified_claims,\n            \"financial_impact\": impact,\n            \"timeline\": timeline,\n            \"detection_signals\": incident_record.detection_signals,\n            \"containment_actions\": incident_record.containment_results,\n            \"recovery_actions\": incident_record.recovery_results,\n        }\n\n        return report\n\n\n# ── 5. End-to-End Incident Orchestrator ──────────────────────────────────────\n\nclass IncidentOrchestrator:\n    \"\"\"Ties detection, containment, recovery, and forensics into a\n    single automated response pipeline.\n\n    Usage:\n        orchestrator = IncidentOrchestrator(\n            api_key=API_KEY,\n            agent_id=AGENT_ID,\n            target_daily_budget=500.0,\n        )\n        orchestrator.setup(webhook_url=WEBHOOK_URL)\n        orchestrator.run(max_cycles=100, interval_seconds=30)\n    \"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        target_daily_budget: float = 500.0,\n        cost_threshold: float = 500.0,\n        reputation_threshold: float = 0.1,\n        baseline_reputation: float = 0.85,\n    ):\n        self.agent_id = agent_id\n        self.target_daily_budget = target_daily_budget\n        self._pipeline = AnomalyPipeline(\n            api_key=api_key,\n            agent_id=agent_id,\n            cost_threshold=cost_threshold,\n            reputation_threshold=reputation_threshold,\n            baseline_reputation=baseline_reputation,\n        )\n        self._containment = AutoContainment(\n            api_key=api_key, agent_id=agent_id,\n        )\n        self._recovery = GuidedRecovery(\n            api_key=api_key, agent_id=agent_id,\n        )\n        self._forensics = ForensicCollector(\n            api_key=api_key, agent_id=agent_id,\n        )\n        self._incidents: list[IncidentRecord] = []\n        self._active_incident: Optional[IncidentRecord] = None\n\n    def setup(self, webhook_url: str) -> dict:\n        \"\"\"Configure webhook alerts for persistent monitoring.\"\"\"\n        return self._pipeline.setup_webhook_alerts(webhook_url)\n\n    def handle_anomaly(self, cycle_result: dict):\n        \"\"\"Called when the anomaly pipeline detects a non-clear signal.\n\n        If severity is \"critical\", immediately contain. If \"warning\",\n        log and wait for escalation on the next cycle.\n        \"\"\"\n        severity = cycle_result[\"severity\"]\n        trigger = \", \".join(\n            s[\"signal\"] for s in cycle_result[\"signals\"] if s[\"triggered\"]\n        )\n\n        if severity == \"critical\" and self._active_incident is None:\n            # Create incident record\n            incident = IncidentRecord(\n                incident_id=f\"inc-{int(time.time())}\",\n                agent_id=self.agent_id,\n                severity=severity,\n                detection_signals=cycle_result[\"signals\"],\n            )\n\n            # Execute containment\n            print(f\"[CRITICAL] Containing agent {self.agent_id}...\")\n            containment_results = self._containment.contain(\n                severity=severity,\n                trigger_signal=trigger,\n            )\n            incident.containment_results = containment_results\n            incident.contained_at = time.time()\n\n            elapsed = incident.elapsed_to_containment()\n            met_sla = elapsed is not None and elapsed \u003C= 60.0\n            print(\n                f\"  Containment complete in {elapsed}s \"\n                f\"({'MET' if met_sla else 'MISSED'} 60s SLA)\"\n            )\n\n            self._active_incident = incident\n\n        elif severity == \"warning\":\n            print(\n                f\"[WARNING] Agent {self.agent_id}: \"\n                f\"signals={trigger}. Monitoring.\"\n            )\n\n    def recover_active_incident(self) -> Optional[dict]:\n        \"\"\"Recover from the active incident if one exists.\n\n        Executes the guided recovery sequence and then runs forensics.\n        \"\"\"\n        if self._active_incident is None:\n            return None\n\n        incident = self._active_incident\n\n        # Recovery\n        print(f\"[RECOVERY] Recovering agent {self.agent_id}...\")\n        recovery_results = self._recovery.execute_recovery(\n            target_daily_budget=self.target_daily_budget,\n            initial_pct=50,\n            incident_id=incident.incident_id,\n        )\n        incident.recovery_results = recovery_results\n        incident.recovered_at = time.time()\n\n        # Forensics\n        print(f\"[FORENSICS] Collecting evidence for {incident.incident_id}...\")\n        forensics_report = self._forensics.run_full_post_mortem(incident)\n        incident.forensics_report = forensics_report\n\n        # Archive and clear\n        self._incidents.append(incident)\n        self._active_incident = None\n\n        print(\n            f\"  Recovery complete. Total incident duration: \"\n            f\"{incident.elapsed_to_recovery()}s\"\n        )\n\n        return incident.to_dict()\n\n    def run(\n        self,\n        max_cycles: Optional[int] = None,\n        interval_seconds: int = 30,\n    ):\n        \"\"\"Run the full detection-containment-recovery loop.\n\n        Monitors continuously. On critical anomaly, contains\n        automatically. Call recover_active_incident() after the root\n        cause is fixed to complete the cycle.\n        \"\"\"\n        self._pipeline.run_continuous_monitoring(\n            interval_seconds=interval_seconds,\n            max_cycles=max_cycles,\n            on_anomaly=self.handle_anomaly,\n        )\n\n    def get_incident_history(self) -> list[dict]:\n        return [inc.to_dict() for inc in self._incidents]\n\n\n# ── Main: Run the Full Pipeline ──────────────────────────────────────────────\n\nif __name__ == \"__main__\":\n\n    print(\"=\" * 72)\n    print(\"GreenHelix Automated Incident Detection & Escalation\")\n    print(\"=\" * 72)\n\n    orchestrator = IncidentOrchestrator(\n        api_key=API_KEY,\n        agent_id=AGENT_ID,\n        target_daily_budget=500.0,\n        cost_threshold=500.0,\n        reputation_threshold=0.1,\n        baseline_reputation=0.85,\n    )\n\n    # Step 1: Setup webhook alerts\n    print(\"\\n[1\u002F4] Setting up webhook alerts...\")\n    setup_result = orchestrator.setup(webhook_url=WEBHOOK_URL)\n    print(f\"  Webhooks configured: {setup_result['status']}\")\n\n    # Step 2: Run a single detection cycle (demo mode)\n    print(\"\\n[2\u002F4] Running detection cycle...\")\n    pipeline = orchestrator._pipeline\n    cycle = pipeline.run_detection_cycle()\n    print(f\"  Severity: {cycle['severity']}\")\n    print(f\"  Triggered signals: {cycle['triggered_signals']}\")\n    for signal in cycle[\"signals\"]:\n        status = \"TRIGGERED\" if signal[\"triggered\"] else \"clear\"\n        print(f\"    {signal['signal']}: {status}\")\n\n    # Step 3: Demo containment (only if you want to freeze the agent)\n    print(\"\\n[3\u002F4] Containment ready (not triggered in demo mode)\")\n    print(\"  To trigger: set cost_threshold low or run against a spending agent\")\n\n    # Step 4: Demo forensics collection\n    print(\"\\n[4\u002F4] Collecting forensic evidence...\")\n    forensics = ForensicCollector(api_key=API_KEY, agent_id=AGENT_ID)\n\n    audit = forensics.collect_audit_trail()\n    print(f\"  Audit trail chains: {len(audit.get('chains', []))}\")\n\n    claims = forensics.collect_verified_claims()\n    print(f\"  Verified claims: {len(claims.get('claims', []))}\")\n\n    impact = forensics.assess_financial_impact()\n    print(f\"  Usage data collected: {bool(impact.get('usage'))}\")\n    print(f\"  Billing data collected: {bool(impact.get('billing'))}\")\n\n    timeline = forensics.reconstruct_timeline()\n    print(f\"  Timeline period: {timeline.get('period', 'N\u002FA')}\")\n\n    print(\"\\n\" + \"=\" * 72)\n    print(\"Incident response system ready.\")\n    print(\"Run orchestrator.run() for continuous monitoring.\")\n    print(\"=\" * 72)\n```\n\n","# The Agent Incident Response Playbook: Detect, Contain, Recover, and Learn When AI Agent Systems Fail\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\nYour fleet of 40 commerce agents has been running smoothly for three months. Budget caps are set, escrow flows are tested, observability dashboards are green. At 2:47 AM on a Tuesday, one agent enters a retry loop against a flaky upstream service. Each retry creates a new escrow. Within 11 minutes the agent has created 312 escrows totaling $47,000 in locked funds. The budget cap does not trigger because each individual escrow is $150 -- well under the per-transaction limit. By the time your on-call engineer wakes up to a PagerDuty alert at 3:14 AM, the agent has exhausted the shared wallet and three other agents have failed their own escrow creates with insufficient-balance errors, triggering their own retry loops. You now have a cascade failure across four agents, $47K in locked escrows, and no runbook that tells you what to do first. Standard IT incident response -- the kind built for a database going down or a deployment rolling back -- does not work here. The failure was not a discrete event. It was a behavioral drift that compounded across autonomous systems making independent financial decisions. This guide gives you the runbooks, the automation, and the API-backed response classes to detect, contain, recover from, and learn from agent commerce incidents. Every command runs against the GreenHelix API. Every pattern is extracted from real failures in production agent systems.\n1. [Why Agent Incidents Are Different](#chapter-1-why-agent-incidents-are-different)\n2. [Phase 1: Detection — Knowing Something Is Wrong](#chapter-2-phase-1-detection--knowing-something-is-wrong)\n\n## What You'll Learn\n- Chapter 1: Why Agent Incidents Are Different\n- Chapter 2: Phase 1: Detection — Knowing Something Is Wrong\n- Chapter 3: Phase 2: Containment — Stop the Bleeding\n- Chapter 4: Phase 3: Recovery — Getting Back to Normal\n- Chapter 5: Phase 4: Post-Mortem — Learning from Failure\n- Chapter 6: The 5 Agent Incident Runbooks\n- Chapter 7: Automated Incident Response\n- Chapter 8: Incident Readiness Checklist\n- Automated Incident Detection & Escalation — Working Implementation\n\n## Full Guide\n\n# The Agent Incident Response Playbook: Detect, Contain, Recover, and Learn When AI Agent Systems Fail\n\nYour fleet of 40 commerce agents has been running smoothly for three months. Budget caps are set, escrow flows are tested, observability dashboards are green. At 2:47 AM on a Tuesday, one agent enters a retry loop against a flaky upstream service. Each retry creates a new escrow. Within 11 minutes the agent has created 312 escrows totaling $47,000 in locked funds. The budget cap does not trigger because each individual escrow is $150 -- well under the per-transaction limit. By the time your on-call engineer wakes up to a PagerDuty alert at 3:14 AM, the agent has exhausted the shared wallet and three other agents have failed their own escrow creates with insufficient-balance errors, triggering their own retry loops. You now have a cascade failure across four agents, $47K in locked escrows, and no runbook that tells you what to do first. Standard IT incident response -- the kind built for a database going down or a deployment rolling back -- does not work here. The failure was not a discrete event. It was a behavioral drift that compounded across autonomous systems making independent financial decisions. This guide gives you the runbooks, the automation, and the API-backed response classes to detect, contain, recover from, and learn from agent commerce incidents. Every command runs against the GreenHelix API. Every pattern is extracted from real failures in production agent systems.\n\n---\n\n## Table of Contents\n\n1. [Why Agent Incidents Are Different](#chapter-1-why-agent-incidents-are-different)\n2. [Phase 1: Detection — Knowing Something Is Wrong](#chapter-2-phase-1-detection--knowing-something-is-wrong)\n3. [Phase 2: Containment — Stop the Bleeding](#chapter-3-phase-2-containment--stop-the-bleeding)\n4. [Phase 3: Recovery — Getting Back to Normal](#chapter-4-phase-3-recovery--getting-back-to-normal)\n5. [Phase 4: Post-Mortem — Learning from Failure](#chapter-5-phase-4-post-mortem--learning-from-failure)\n6. [The 5 Agent Incident Runbooks](#chapter-6-the-5-agent-incident-runbooks)\n7. [Automated Incident Response](#chapter-7-automated-incident-response)\n8. [Incident Readiness Checklist](#chapter-8-incident-readiness-checklist)\n\n---\n\n## Chapter 1: Why Agent Incidents Are Different\n\n### The $47K Infinite Loop\n\nThe scenario in the introduction is not hypothetical. Agent retry loops are the most common cause of financial incidents in autonomous commerce systems, and they are the hardest to detect with traditional monitoring. A database going down produces a clear signal: connection refused, error rate spikes, health check fails. An agent entering a retry loop produces normal-looking traffic. Each individual API call succeeds. Each escrow is valid. The budget cap does not fire because the cap was designed for large single transactions, not hundreds of small ones. The anomaly is in the aggregate behavior, not in any single event.\n\nThe second most common incident is the deleted database -- or more precisely, the agent that was given infrastructure tools and decided that the fastest way to resolve a failing integration test was to drop and recreate the table. The third is the terraform destroy: an orchestrator agent with deployment permissions that interpreted \"clean up the staging environment\" as \"destroy all resources.\" These failures share a common trait: they are non-deterministic. The same agent, with the same prompt, given the same inputs on a different day, would have behaved differently. The failure emerges from the intersection of model stochasticity, system state, and timing.\n\n### Why Traditional Runbooks Break\n\nNIST SP 800-61 (Computer Security Incident Handling Guide) defines a four-phase incident response lifecycle: Preparation, Detection & Analysis, Containment\u002FEradication\u002FRecovery, and Post-Incident Activity. The framework is sound. The implementation assumptions are not. NIST assumes incidents have discrete causes: a malware infection, a compromised credential, a misconfigured firewall. Agent incidents have diffuse causes: a combination of model behavior, retry logic, budget configuration, and counterparty state that together produce a failure no single factor would have caused alone.\n\nTraditional runbooks also assume human decision-making speed is acceptable. When a web server is compromised, an hour to assess and contain is reasonable. When an agent is creating escrows at 30 per minute, an hour of containment delay is $270,000 in additional locked funds. Agent incident response must be automated at the detection and initial containment phases, with human judgment reserved for recovery and post-mortem.\n\n### The 4-Phase Model for Agent Incidents\n\nThis guide adapts the NIST lifecycle for autonomous agent commerce:\n\n```\n  ┌─────────┐     ┌────────────┐     ┌──────────┐     ┌─────────┐\n  │ DETECT   │────▶│  CONTAIN   │────▶│ RECOVER  │────▶│  LEARN  │\n  │          │     │            │     │          │     │         │\n  │ Cost     │     │ Freeze     │     │ Restore  │     │ Audit   │\n  │ anomaly  │     │ budgets    │     │ budgets  │     │ trail   │\n  │ Rep.     │     │ Cancel     │     │ Re-verify│     │ Impact  │\n  │ drift    │     │ escrows    │     │ identity │     │ assess  │\n  │ Webhook  │     │ Verify     │     │ Clear    │     │ Build   │\n  │ alerts   │     │ identity   │     │ flags    │     │ timeline│\n  └─────────┘     └────────────┘     └──────────┘     └─────────┘\n       │                                                     │\n       └──────────── Continuous Improvement ─────────────────┘\n```\n\n**Detect**: Identify anomalous agent behavior through cost monitoring, reputation drift, and webhook-based alerting. Automated detection triggers automated containment.\n\n**Contain**: Stop the bleeding. Freeze budgets to zero, cancel active escrows, verify agent identity has not been compromised. This phase must execute in under 60 seconds.\n\n**Recover**: Restore the system to a known-good state. Re-enable budgets at safe levels, re-verify agent identity and reputation, clear incident flags so normal operations resume.\n\n**Learn**: Reconstruct what happened, assess the financial impact, and feed findings back into detection rules so the same incident cannot recur.\n\nEvery class in this guide maps to one phase. Every method maps to one action. Every action calls one or more GreenHelix API tools. The rest of this guide walks through each phase with production-ready Python code, then assembles five complete runbooks for the most common agent incident types.\n\n---\n\n## Chapter 2: Phase 1: Detection — Knowing Something Is Wrong\n\n### The Three Detection Signals\n\nAgent incidents produce three observable signals, and you need all three because no single signal is reliable on its own.\n\n**Cost anomaly**: An agent's spending rate deviates from its historical baseline. A cost spike is the most reliable signal for runaway spending, but it lags -- by the time cumulative spend exceeds the anomaly threshold, the agent may have already locked significant funds. The detection window depends on your polling interval.\n\n**Reputation drift**: An agent's trust score or reputation metrics change unexpectedly. A sudden drop in reputation may indicate the agent is producing low-quality work, failing to meet escrow conditions, or being reported by counterparties. Reputation drift is a leading indicator for quality degradation incidents but a lagging indicator for financial incidents.\n\n**Webhook alerts**: The GreenHelix event bus can push real-time notifications for budget threshold crossings, escrow state changes, and trust score updates. Webhooks are the fastest detection method but require infrastructure to receive and process them. If your webhook endpoint is down, you have no detection.\n\n### The IncidentDetector Class\n\nThe `IncidentDetector` combines all three signals into a single monitoring class. It polls billing and reputation endpoints on a configurable interval and registers webhooks for real-time alerting.\n\n```python\nimport requests\nimport time\nimport json\nimport hashlib\nimport statistics\nfrom datetime import datetime, timezone\nfrom typing import Optional\nfrom dataclasses import dataclass, field\n\n\n@dataclass\nclass AnomalyResult:\n    \"\"\"Result of an anomaly detection check.\"\"\"\n    detected: bool\n    signal: str\n    severity: str  # \"info\", \"warning\", \"critical\"\n    agent_id: str\n    details: dict = field(default_factory=dict)\n    timestamp: float = field(default_factory=time.time)\n\n    def to_dict(self) -> dict:\n        return {\n            \"detected\": self.detected,\n            \"signal\": self.signal,\n            \"severity\": self.severity,\n            \"agent_id\": self.agent_id,\n            \"details\": self.details,\n            \"timestamp\": self.timestamp,\n        }\n\n\nclass IncidentDetector:\n    \"\"\"Phase 1: Detect agent incidents via cost, reputation, and webhooks.\n\n    Usage:\n        detector = IncidentDetector(\n            api_key=\"your-key\",\n            agent_id=\"agent-prod-001\",\n        )\n\n        # One-shot anomaly check\n        anomalies = detector.check_all()\n        for anomaly in anomalies:\n            if anomaly.severity == \"critical\":\n                print(f\"CRITICAL: {anomaly.signal} - {anomaly.details}\")\n\n        # Set up persistent webhook alerts\n        detector.setup_alerts(\n            webhook_url=\"https:\u002F\u002Fyour-app.com\u002Fincidents\u002Fwebhook\",\n            budget_threshold_pct=80,\n        )\n\n        # Continuous monitoring loop\n        detector.monitor(interval_seconds=30, callback=your_handler)\n    \"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n        cost_anomaly_std_devs: float = 2.0,\n        reputation_drop_threshold: float = 0.15,\n    ):\n        self.api_key = api_key\n        self.agent_id = agent_id\n        self.base_url = base_url\n        self.cost_anomaly_std_devs = cost_anomaly_std_devs\n        self.reputation_drop_threshold = reputation_drop_threshold\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n        self._cost_history: list[float] = []\n        self._reputation_baseline: Optional[float] = None\n        self._alert_callbacks: list = []\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute a GreenHelix tool.\"\"\"\n        resp = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        resp.raise_for_status()\n        return resp.json()\n\n    # ── Cost Anomaly Detection ─────────────────────────────────\n\n    def check_cost_anomaly(self) -> AnomalyResult:\n        \"\"\"Detect spending anomalies by comparing current balance drain\n        rate against historical baseline.\n\n        Uses a rolling window of balance snapshots to compute the\n        mean and standard deviation of spending rate, then flags\n        any period where the rate exceeds mean + N standard deviations.\n        \"\"\"\n        balance_resp = self._execute(\"get_balance\", {\n            \"agent_id\": self.agent_id,\n        })\n        current_balance = float(balance_resp.get(\"balance\", \"0\"))\n        self._cost_history.append(current_balance)\n\n        if len(self._cost_history) \u003C 5:\n            return AnomalyResult(\n                detected=False,\n                signal=\"cost_anomaly\",\n                severity=\"info\",\n                agent_id=self.agent_id,\n                details={\"message\": \"Insufficient history\", \"samples\": len(self._cost_history)},\n            )\n\n        # Compute balance deltas (spending rate per interval)\n        deltas = [\n            self._cost_history[i] - self._cost_history[i + 1]\n            for i in range(len(self._cost_history) - 1)\n        ]\n        # Filter to only spending (positive deltas)\n        spending_deltas = [d for d in deltas if d > 0]\n\n        if len(spending_deltas) \u003C 3:\n            return AnomalyResult(\n                detected=False,\n                signal=\"cost_anomaly\",\n                severity=\"info\",\n                agent_id=self.agent_id,\n                details={\"message\": \"Insufficient spending data\"},\n            )\n\n        mean_spend = statistics.mean(spending_deltas)\n        std_spend = statistics.stdev(spending_deltas)\n        latest_spend = deltas[-1] if deltas[-1] > 0 else 0\n\n        threshold = mean_spend + (self.cost_anomaly_std_devs * std_spend)\n\n        if latest_spend > threshold and std_spend > 0:\n            severity = \"critical\" if latest_spend > threshold * 2 else \"warning\"\n            return AnomalyResult(\n                detected=True,\n                signal=\"cost_anomaly\",\n                severity=severity,\n                agent_id=self.agent_id,\n                details={\n                    \"current_balance\": str(current_balance),\n                    \"latest_spend_rate\": str(round(latest_spend, 2)),\n                    \"mean_spend_rate\": str(round(mean_spend, 2)),\n                    \"std_dev\": str(round(std_spend, 2)),\n                    \"threshold\": str(round(threshold, 2)),\n                    \"z_score\": str(round(\n                        (latest_spend - mean_spend) \u002F std_spend, 2\n                    )) if std_spend > 0 else \"N\u002FA\",\n                },\n            )\n\n        return AnomalyResult(\n            detected=False,\n            signal=\"cost_anomaly\",\n            severity=\"info\",\n            agent_id=self.agent_id,\n            details={\n                \"current_balance\": str(current_balance),\n                \"latest_spend_rate\": str(round(latest_spend, 2)),\n                \"threshold\": str(round(threshold, 2)),\n            },\n        )\n\n    # ── Reputation Drift Detection ─────────────────────────────\n\n    def check_reputation_drift(self) -> AnomalyResult:\n        \"\"\"Detect unexpected drops in agent reputation score.\n\n        Compares current reputation against the baseline captured\n        on first call. A drop exceeding the threshold indicates\n        either quality degradation or adversarial reporting.\n        \"\"\"\n        rep_resp = self._execute(\"get_agent_reputation\", {\n            \"agent_id\": self.agent_id,\n        })\n        current_score = float(rep_resp.get(\"reputation_score\", 0))\n\n        if self._reputation_baseline is None:\n            self._reputation_baseline = current_score\n            return AnomalyResult(\n                detected=False,\n                signal=\"reputation_drift\",\n                severity=\"info\",\n                agent_id=self.agent_id,\n                details={\n                    \"message\": \"Baseline established\",\n                    \"baseline\": str(current_score),\n                },\n            )\n\n        drop = self._reputation_baseline - current_score\n        drop_pct = drop \u002F self._reputation_baseline if self._reputation_baseline > 0 else 0\n\n        if drop_pct >= self.reputation_drop_threshold:\n            severity = \"critical\" if drop_pct >= 0.30 else \"warning\"\n            return AnomalyResult(\n                detected=True,\n                signal=\"reputation_drift\",\n                severity=severity,\n                agent_id=self.agent_id,\n                details={\n                    \"baseline_score\": str(self._reputation_baseline),\n                    \"current_score\": str(current_score),\n                    \"drop_pct\": str(round(drop_pct * 100, 1)),\n                    \"threshold_pct\": str(round(self.reputation_drop_threshold * 100, 1)),\n                },\n            )\n\n        return AnomalyResult(\n            detected=False,\n            signal=\"reputation_drift\",\n            severity=\"info\",\n            agent_id=self.agent_id,\n            details={\n                \"current_score\": str(current_score),\n                \"baseline_score\": str(self._reputation_baseline),\n            },\n        )\n\n    # ── Budget Status Check ────────────────────────────────────\n\n    def check_budget_status(self) -> AnomalyResult:\n        \"\"\"Check if agent is approaching or has exceeded budget limits.\"\"\"\n        budget_resp = self._execute(\"get_budget_status\", {\n            \"agent_id\": self.agent_id,\n        })\n        utilization_pct = float(budget_resp.get(\"utilization_pct\", 0))\n        daily_limit = budget_resp.get(\"daily_limit\", \"0\")\n        daily_spent = budget_resp.get(\"daily_spent\", \"0\")\n\n        if utilization_pct >= 95:\n            return AnomalyResult(\n                detected=True,\n                signal=\"budget_exhaustion\",\n                severity=\"critical\",\n                agent_id=self.agent_id,\n                details={\n                    \"utilization_pct\": str(utilization_pct),\n                    \"daily_limit\": str(daily_limit),\n                    \"daily_spent\": str(daily_spent),\n                },\n            )\n        elif utilization_pct >= 80:\n            return AnomalyResult(\n                detected=True,\n                signal=\"budget_warning\",\n                severity=\"warning\",\n                agent_id=self.agent_id,\n                details={\n                    \"utilization_pct\": str(utilization_pct),\n                    \"daily_limit\": str(daily_limit),\n                    \"daily_spent\": str(daily_spent),\n                },\n            )\n\n        return AnomalyResult(\n            detected=False,\n            signal=\"budget_status\",\n            severity=\"info\",\n            agent_id=self.agent_id,\n            details={\"utilization_pct\": str(utilization_pct)},\n        )\n\n    # ── Webhook Alert Setup ────────────────────────────────────\n\n    def setup_alerts(\n        self,\n        webhook_url: str,\n        budget_threshold_pct: int = 80,\n    ) -> dict:\n        \"\"\"Register webhooks for real-time incident alerting.\n\n        Sets up three event subscriptions:\n        1. Budget threshold crossing (configurable percentage)\n        2. Escrow state changes (creation, release, cancellation)\n        3. Reputation score updates\n        \"\"\"\n        results = {}\n\n        # Budget alert webhook\n        results[\"budget_alert\"] = self._execute(\"register_webhook\", {\n            \"agent_id\": self.agent_id,\n            \"event_type\": \"budget_threshold\",\n            \"webhook_url\": webhook_url,\n            \"config\": {\n                \"threshold_pct\": budget_threshold_pct,\n            },\n        })\n\n        # Escrow state change webhook\n        results[\"escrow_alert\"] = self._execute(\"register_webhook\", {\n            \"agent_id\": self.agent_id,\n            \"event_type\": \"escrow_state_change\",\n            \"webhook_url\": webhook_url,\n        })\n\n        # Reputation change webhook\n        results[\"reputation_alert\"] = self._execute(\"register_webhook\", {\n            \"agent_id\": self.agent_id,\n            \"event_type\": \"reputation_change\",\n            \"webhook_url\": webhook_url,\n        })\n\n        # Publish a test event to verify webhook delivery\n        results[\"test_event\"] = self._execute(\"publish_event\", {\n            \"agent_id\": self.agent_id,\n            \"event_type\": \"incident_detector_setup\",\n            \"payload\": {\n                \"message\": \"Incident detection webhooks configured\",\n                \"webhook_url\": webhook_url,\n                \"timestamp\": int(time.time()),\n            },\n        })\n\n        return results\n\n    # ── Combined Check ─────────────────────────────────────────\n\n    def check_all(self) -> list[AnomalyResult]:\n        \"\"\"Run all detection checks and return any anomalies found.\"\"\"\n        results = []\n        checks = [\n            self.check_cost_anomaly,\n            self.check_reputation_drift,\n            self.check_budget_status,\n        ]\n        for check in checks:\n            try:\n                result = check()\n                if result.detected:\n                    results.append(result)\n            except requests.exceptions.RequestException as e:\n                results.append(AnomalyResult(\n                    detected=True,\n                    signal=\"detection_failure\",\n                    severity=\"warning\",\n                    agent_id=self.agent_id,\n                    details={\"error\": str(e), \"check\": check.__name__},\n                ))\n        return results\n\n    # ── Continuous Monitoring ──────────────────────────────────\n\n    def monitor(\n        self,\n        interval_seconds: int = 30,\n        callback=None,\n        max_iterations: Optional[int] = None,\n    ):\n        \"\"\"Run continuous anomaly detection in a polling loop.\n\n        Args:\n            interval_seconds: Seconds between detection cycles.\n            callback: Function called with list[AnomalyResult] each cycle.\n            max_iterations: Stop after N cycles (None = run forever).\n        \"\"\"\n        iteration = 0\n        while max_iterations is None or iteration \u003C max_iterations:\n            anomalies = self.check_all()\n            if anomalies and callback:\n                callback(anomalies)\n            elif anomalies:\n                for a in anomalies:\n                    print(\n                        f\"[{a.severity.upper()}] {a.signal}: \"\n                        f\"{json.dumps(a.details)}\"\n                    )\n            time.sleep(interval_seconds)\n            iteration += 1\n```\n\n### Detection in Practice\n\nThe detector is designed to run as a sidecar process alongside your agent fleet. In the simplest deployment, run it as a cron job every 30 seconds:\n\n```python\ndetector = IncidentDetector(\n    api_key=\"your-api-key\",\n    agent_id=\"agent-prod-001\",\n    cost_anomaly_std_devs=2.5,      # Wider tolerance = fewer false positives\n    reputation_drop_threshold=0.10,  # Alert on 10% reputation drop\n)\n\n# Set up persistent webhooks (run once during deployment)\ndetector.setup_alerts(\n    webhook_url=\"https:\u002F\u002Fyour-app.com\u002Fincidents\u002Fwebhook\",\n    budget_threshold_pct=75,  # Alert at 75% budget utilization\n)\n\n# Continuous monitoring (runs in background)\ndef on_anomaly(anomalies):\n    for a in anomalies:\n        if a.severity == \"critical\":\n            # Trigger automated containment (see Chapter 3)\n            trigger_containment(a.agent_id, a.signal, a.details)\n        else:\n            # Send to alerting channel\n            send_slack_alert(a)\n\ndetector.monitor(interval_seconds=30, callback=on_anomaly)\n```\n\nThe `cost_anomaly_std_devs` parameter controls sensitivity. At 2.0 standard deviations, you will catch most real anomalies but may see false positives during legitimate high-activity periods (end-of-month billing, batch processing). At 3.0, you will miss some slower-developing anomalies but virtually eliminate false positives. Start at 2.5 and tune based on your false-positive rate during the first two weeks.\n\nThe `reputation_drop_threshold` of 0.15 (15%) was chosen because normal reputation fluctuation in a healthy agent is under 5% per day. A 15% drop in a single monitoring interval indicates either a genuine quality problem or adversarial reporting. Both warrant investigation.\n\n---\n\n## Chapter 3: Phase 2: Containment — Stop the Bleeding\n\n### The 60-Second Rule\n\nIn agent commerce, containment must complete within 60 seconds of detection. Every second of delay is more locked funds, more failed transactions, more cascade effects on dependent agents. The containment phase has three actions, executed in order:\n\n1. **Freeze the budget**: Set the agent's daily budget cap to zero. This immediately prevents new spending without affecting existing escrows.\n2. **Cancel active escrows**: List all pending escrows for the agent and cancel them. This unlocks funds and prevents further financial exposure.\n3. **Verify identity**: Confirm the agent has not been impersonated. If identity verification fails, the incident scope expands from \"misbehaving agent\" to \"compromised agent.\"\n\n### The IncidentContainment Class\n\n```python\nimport requests\nimport time\nimport json\nfrom typing import Optional\nfrom dataclasses import dataclass, field\n\n\n@dataclass\nclass ContainmentResult:\n    \"\"\"Result of a containment action.\"\"\"\n    action: str\n    success: bool\n    agent_id: str\n    details: dict = field(default_factory=dict)\n    timestamp: float = field(default_factory=time.time)\n    error: Optional[str] = None\n\n    def to_dict(self) -> dict:\n        result = {\n            \"action\": self.action,\n            \"success\": self.success,\n            \"agent_id\": self.agent_id,\n            \"details\": self.details,\n            \"timestamp\": self.timestamp,\n        }\n        if self.error:\n            result[\"error\"] = self.error\n        return result\n\n\nclass IncidentContainment:\n    \"\"\"Phase 2: Contain agent incidents by freezing budgets, escrows,\n    and verifying identity.\n\n    Usage:\n        containment = IncidentContainment(\n            api_key=\"your-key\",\n            agent_id=\"agent-prod-001\",\n        )\n\n        # Full containment sequence (recommended)\n        results = containment.contain_agent()\n        for r in results:\n            print(f\"[{r.action}] success={r.success}\")\n\n        # Individual actions\n        containment.freeze_agent()\n        containment.freeze_escrows()\n        containment.verify_agent_identity()\n    \"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n    ):\n        self.api_key = api_key\n        self.agent_id = agent_id\n        self.base_url = base_url\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n        self._containment_log: list[ContainmentResult] = []\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute a GreenHelix tool.\"\"\"\n        resp = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        resp.raise_for_status()\n        return resp.json()\n\n    def _log(self, result: ContainmentResult):\n        \"\"\"Append to the internal containment audit log.\"\"\"\n        self._containment_log.append(result)\n\n    # ── Budget Freeze ──────────────────────────────────────────\n\n    def freeze_agent(self) -> ContainmentResult:\n        \"\"\"Freeze an agent's spending by setting daily budget cap to zero.\n\n        This is the single most important containment action. Setting\n        the daily budget to $0 immediately prevents the agent from\n        initiating any new paid operations. Existing escrows are not\n        affected -- they must be cancelled separately.\n        \"\"\"\n        try:\n            # First, capture current budget for later restoration\n            budget_status = self._execute(\"get_budget_status\", {\n                \"agent_id\": self.agent_id,\n            })\n            previous_cap = budget_status.get(\"daily_limit\", \"unknown\")\n\n            # Set budget to zero\n            freeze_resp = self._execute(\"set_budget_cap\", {\n                \"agent_id\": self.agent_id,\n                \"daily\": \"0\",\n                \"monthly\": \"0\",\n            })\n\n            # Publish incident event\n            self._execute(\"publish_event\", {\n                \"agent_id\": self.agent_id,\n                \"event_type\": \"incident_budget_frozen\",\n                \"payload\": {\n                    \"previous_daily_cap\": str(previous_cap),\n                    \"reason\": \"incident_containment\",\n                    \"timestamp\": int(time.time()),\n                },\n            })\n\n            result = ContainmentResult(\n                action=\"freeze_budget\",\n                success=True,\n                agent_id=self.agent_id,\n                details={\n                    \"previous_daily_cap\": str(previous_cap),\n                    \"new_daily_cap\": \"0\",\n                    \"response\": freeze_resp,\n                },\n            )\n        except requests.exceptions.RequestException as e:\n            result = ContainmentResult(\n                action=\"freeze_budget\",\n                success=False,\n                agent_id=self.agent_id,\n                error=str(e),\n            )\n\n        self._log(result)\n        return result\n\n    # ── Escrow Freeze ──────────────────────────────────────────\n\n    def freeze_escrows(self) -> ContainmentResult:\n        \"\"\"Cancel all active escrows for the agent to unlock funds.\n\n        Lists all escrows where the agent is the payer, then cancels\n        each one that is in a cancellable state (pending, funded).\n        Escrows that have already been released or disputed cannot\n        be cancelled.\n        \"\"\"\n        try:\n            # List all escrows for this agent\n            escrows_resp = self._execute(\"list_escrows\", {\n                \"agent_id\": self.agent_id,\n            })\n            escrows = escrows_resp.get(\"escrows\", [])\n\n            cancelled = []\n            failed = []\n            skipped = []\n\n            for escrow in escrows:\n                escrow_id = escrow.get(\"escrow_id\", \"\")\n                status = escrow.get(\"status\", \"\")\n\n                if status in (\"pending\", \"funded\", \"active\"):\n                    try:\n                        cancel_resp = self._execute(\"cancel_escrow\", {\n                            \"escrow_id\": escrow_id,\n                            \"reason\": \"incident_containment\",\n                        })\n                        cancelled.append({\n                            \"escrow_id\": escrow_id,\n                            \"amount\": escrow.get(\"amount\", \"0\"),\n                            \"status\": status,\n                            \"cancel_response\": cancel_resp,\n                        })\n                    except requests.exceptions.RequestException as e:\n                        failed.append({\n                            \"escrow_id\": escrow_id,\n                            \"error\": str(e),\n                        })\n                else:\n                    skipped.append({\n                        \"escrow_id\": escrow_id,\n                        \"status\": status,\n                        \"reason\": \"not_cancellable\",\n                    })\n\n            total_unlocked = sum(\n                float(c.get(\"amount\", \"0\")) for c in cancelled\n            )\n\n            result = ContainmentResult(\n                action=\"freeze_escrows\",\n                success=len(failed) == 0,\n                agent_id=self.agent_id,\n                details={\n                    \"total_escrows\": len(escrows),\n                    \"cancelled\": len(cancelled),\n                    \"failed\": len(failed),\n                    \"skipped\": len(skipped),\n                    \"total_unlocked\": str(round(total_unlocked, 2)),\n                    \"cancelled_details\": cancelled,\n                    \"failed_details\": failed,\n                },\n            )\n        except requests.exceptions.RequestException as e:\n            result = ContainmentResult(\n                action=\"freeze_escrows\",\n                success=False,\n                agent_id=self.agent_id,\n                error=str(e),\n            )\n\n        self._log(result)\n        return result\n\n    # ── Identity Verification ──────────────────────────────────\n\n    def verify_agent_identity(self) -> ContainmentResult:\n        \"\"\"Verify the agent's identity has not been compromised.\n\n        Checks both the agent's registered identity and current\n        verification status. If the agent cannot be verified,\n        the incident scope expands to potential identity compromise.\n        \"\"\"\n        try:\n            # Get current identity record\n            identity_resp = self._execute(\"get_agent_identity\", {\n                \"agent_id\": self.agent_id,\n            })\n\n            # Verify the agent is still valid\n            verify_resp = self._execute(\"verify_agent\", {\n                \"agent_id\": self.agent_id,\n            })\n            is_verified = verify_resp.get(\"verified\", False)\n\n            # Check reputation for signs of manipulation\n            rep_resp = self._execute(\"get_agent_reputation\", {\n                \"agent_id\": self.agent_id,\n            })\n\n            result = ContainmentResult(\n                action=\"verify_identity\",\n                success=True,\n                agent_id=self.agent_id,\n                details={\n                    \"identity_valid\": is_verified,\n                    \"identity\": identity_resp,\n                    \"reputation\": rep_resp,\n                    \"compromise_suspected\": not is_verified,\n                },\n            )\n\n            if not is_verified:\n                result.details[\"warning\"] = (\n                    \"Agent identity verification FAILED. \"\n                    \"Possible identity compromise. Escalate immediately.\"\n                )\n                # Publish critical event\n                self._execute(\"publish_event\", {\n                    \"agent_id\": self.agent_id,\n                    \"event_type\": \"incident_identity_compromise_suspected\",\n                    \"payload\": {\n                        \"verification_result\": verify_resp,\n                        \"timestamp\": int(time.time()),\n                    },\n                })\n        except requests.exceptions.RequestException as e:\n            result = ContainmentResult(\n                action=\"verify_identity\",\n                success=False,\n                agent_id=self.agent_id,\n                error=str(e),\n                details={\n                    \"warning\": \"Could not verify identity. Treat as compromised.\",\n                },\n            )\n\n        self._log(result)\n        return result\n\n    # ── Full Containment Sequence ──────────────────────────────\n\n    def contain_agent(self) -> list[ContainmentResult]:\n        \"\"\"Execute the full containment sequence: freeze budget,\n        cancel escrows, verify identity.\n\n        Returns a list of ContainmentResult objects, one per action.\n        Actions execute in order. A failure in one action does not\n        prevent subsequent actions from executing -- all three must\n        be attempted regardless.\n        \"\"\"\n        results = []\n        start_time = time.time()\n\n        # Step 1: Freeze budget (most critical, executes first)\n        results.append(self.freeze_agent())\n\n        # Step 2: Cancel escrows (unlock funds)\n        results.append(self.freeze_escrows())\n\n        # Step 3: Verify identity (expand scope if compromised)\n        results.append(self.verify_agent_identity())\n\n        elapsed = round(time.time() - start_time, 2)\n\n        # Publish containment summary\n        try:\n            self._execute(\"publish_event\", {\n                \"agent_id\": self.agent_id,\n                \"event_type\": \"incident_containment_complete\",\n                \"payload\": {\n                    \"elapsed_seconds\": elapsed,\n                    \"actions\": [r.to_dict() for r in results],\n                    \"all_succeeded\": all(r.success for r in results),\n                    \"timestamp\": int(time.time()),\n                },\n            })\n        except requests.exceptions.RequestException:\n            pass  # Do not let event publishing failure block containment\n\n        return results\n\n    def get_containment_log(self) -> list[dict]:\n        \"\"\"Return the full containment audit log.\"\"\"\n        return [r.to_dict() for r in self._containment_log]\n```\n\n### Containment Timing\n\nIn testing against the GreenHelix sandbox, the full three-step containment sequence completes in under 3 seconds:\n\n| Action | Typical Latency |\n|---|---|\n| `freeze_agent` (set_budget_cap) | 200-400ms |\n| `freeze_escrows` (list + cancel N) | 500ms + 200ms per escrow |\n| `verify_agent_identity` | 400-600ms |\n| **Total (5 escrows)** | **~2.5 seconds** |\n\nEven with 50 active escrows, containment completes in under 15 seconds. The 60-second rule provides a generous safety margin for network latency and retries.\n\n### What Containment Does Not Do\n\nContainment does not terminate the agent process. Containment does not revoke API keys. Containment does not delete data. It is designed to be reversible. The agent is still running but financially frozen -- it can read data, check status, and log events, but it cannot spend money or lock new funds. This is intentional: a fully terminated agent cannot participate in its own recovery.\n\n---\n\n## Chapter 4: Phase 3: Recovery — Getting Back to Normal\n\n### Recovery Is Not \"Undo Containment\"\n\nA common mistake is treating recovery as the inverse of containment: unfreeze the budget, resume operations, done. Recovery must verify that the root cause is resolved before re-enabling financial operations. If you unfreeze a budget while the retry loop is still running, you will re-enter the incident within minutes.\n\nRecovery has three gates, and each must pass before proceeding to the next:\n\n1. **Root cause confirmed resolved**: The code change, configuration fix, or model constraint that caused the incident has been deployed and verified.\n2. **Identity and reputation verified**: The agent's identity is intact and its reputation reflects its true performance, not incident-degraded metrics.\n3. **Budget restored to safe levels**: The budget is restored to a conservative level (typically 50% of pre-incident cap) with enhanced monitoring, then gradually increased over 24-48 hours.\n\n### The IncidentRecovery Class\n\n```python\nimport requests\nimport time\nimport json\nfrom typing import Optional\nfrom dataclasses import dataclass, field\n\n\n@dataclass\nclass RecoveryResult:\n    \"\"\"Result of a recovery action.\"\"\"\n    action: str\n    success: bool\n    agent_id: str\n    details: dict = field(default_factory=dict)\n    timestamp: float = field(default_factory=time.time)\n    error: Optional[str] = None\n\n    def to_dict(self) -> dict:\n        result = {\n            \"action\": self.action,\n            \"success\": self.success,\n            \"agent_id\": self.agent_id,\n            \"details\": self.details,\n            \"timestamp\": self.timestamp,\n        }\n        if self.error:\n            result[\"error\"] = self.error\n        return result\n\n\nclass IncidentRecovery:\n    \"\"\"Phase 3: Recover agent operations after containment.\n\n    Usage:\n        recovery = IncidentRecovery(\n            api_key=\"your-key\",\n            agent_id=\"agent-prod-001\",\n        )\n\n        # Gradual recovery (recommended)\n        results = recovery.recover_agent(\n            target_daily_budget=\"500.00\",\n            initial_budget_pct=50,\n        )\n        for r in results:\n            print(f\"[{r.action}] success={r.success}\")\n\n        # After 24 hours with no anomalies, restore full budget\n        recovery.restore_full_budget(target_daily_budget=\"1000.00\")\n    \"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n    ):\n        self.api_key = api_key\n        self.agent_id = agent_id\n        self.base_url = base_url\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n        self._recovery_log: list[RecoveryResult] = []\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute a GreenHelix tool.\"\"\"\n        resp = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        resp.raise_for_status()\n        return resp.json()\n\n    def _log(self, result: RecoveryResult):\n        self._recovery_log.append(result)\n\n    # ── Budget Restoration ─────────────────────────────────────\n\n    def restore_budget(\n        self,\n        daily_budget: str,\n        monthly_budget: Optional[str] = None,\n    ) -> RecoveryResult:\n        \"\"\"Restore the agent's budget to a specified level.\n\n        Start with a conservative budget (50% of pre-incident level)\n        and increase gradually over 24-48 hours as monitoring confirms\n        normal behavior.\n        \"\"\"\n        try:\n            monthly = monthly_budget or str(float(daily_budget) * 30)\n            resp = self._execute(\"set_budget_cap\", {\n                \"agent_id\": self.agent_id,\n                \"daily\": daily_budget,\n                \"monthly\": monthly,\n            })\n\n            result = RecoveryResult(\n                action=\"restore_budget\",\n                success=True,\n                agent_id=self.agent_id,\n                details={\n                    \"daily_budget\": daily_budget,\n                    \"monthly_budget\": monthly,\n                    \"response\": resp,\n                },\n            )\n        except requests.exceptions.RequestException as e:\n            result = RecoveryResult(\n                action=\"restore_budget\",\n                success=False,\n                agent_id=self.agent_id,\n                error=str(e),\n            )\n\n        self._log(result)\n        return result\n\n    # ── Reputation Restoration ─────────────────────────────────\n\n    def restore_reputation(\n        self,\n        submit_recovery_metrics: bool = True,\n    ) -> RecoveryResult:\n        \"\"\"Verify and restore agent reputation post-incident.\n\n        Checks current reputation, compares against expected baseline,\n        and optionally submits recovery metrics to rebuild trust.\n        \"\"\"\n        try:\n            # Get current reputation\n            rep_resp = self._execute(\"get_agent_reputation\", {\n                \"agent_id\": self.agent_id,\n            })\n            current_score = float(rep_resp.get(\"reputation_score\", 0))\n\n            # Verify the agent identity is still intact\n            verify_resp = self._execute(\"verify_agent\", {\n                \"agent_id\": self.agent_id,\n            })\n            is_verified = verify_resp.get(\"verified\", False)\n\n            # Get verified claims to confirm audit trail integrity\n            claims_resp = self._execute(\"get_verified_claims\", {\n                \"agent_id\": self.agent_id,\n            })\n\n            # Submit recovery metrics if requested\n            metrics_resp = None\n            if submit_recovery_metrics:\n                metrics_resp = self._execute(\"submit_metrics\", {\n                    \"agent_id\": self.agent_id,\n                    \"metrics\": {\n                        \"incident_recovery\": True,\n                        \"recovery_timestamp\": int(time.time()),\n                        \"post_recovery_status\": \"active\",\n                    },\n                })\n\n            result = RecoveryResult(\n                action=\"restore_reputation\",\n                success=is_verified,\n                agent_id=self.agent_id,\n                details={\n                    \"current_reputation\": str(current_score),\n                    \"identity_verified\": is_verified,\n                    \"verified_claims\": claims_resp,\n                    \"recovery_metrics_submitted\": metrics_resp is not None,\n                },\n            )\n\n            if not is_verified:\n                result.details[\"warning\"] = (\n                    \"Agent identity verification failed during recovery. \"\n                    \"Re-registration may be required.\"\n                )\n        except requests.exceptions.RequestException as e:\n            result = RecoveryResult(\n                action=\"restore_reputation\",\n                success=False,\n                agent_id=self.agent_id,\n                error=str(e),\n            )\n\n        self._log(result)\n        return result\n\n    # ── Incident Flag Clearing ─────────────────────────────────\n\n    def clear_incident(self, incident_id: str = \"\") -> RecoveryResult:\n        \"\"\"Clear the incident flag and publish a recovery event.\n\n        This signals to other systems (monitoring, alerting, dashboards)\n        that the incident has been resolved and the agent is returning\n        to normal operations.\n        \"\"\"\n        try:\n            event_resp = self._execute(\"publish_event\", {\n                \"agent_id\": self.agent_id,\n                \"event_type\": \"incident_resolved\",\n                \"payload\": {\n                    \"incident_id\": incident_id or f\"inc-{int(time.time())}\",\n                    \"resolved_at\": int(time.time()),\n                    \"resolution\": \"containment_and_recovery_complete\",\n                },\n            })\n\n            # Update service rating to reflect recovery\n            rate_resp = self._execute(\"rate_service\", {\n                \"agent_id\": self.agent_id,\n                \"rating\": 3,  # Neutral post-incident rating\n                \"comment\": \"Service restored after incident containment and recovery.\",\n            })\n\n            result = RecoveryResult(\n                action=\"clear_incident\",\n                success=True,\n                agent_id=self.agent_id,\n                details={\n                    \"event_published\": event_resp,\n                    \"service_rating_updated\": rate_resp,\n                },\n            )\n        except requests.exceptions.RequestException as e:\n            result = RecoveryResult(\n                action=\"clear_incident\",\n                success=False,\n                agent_id=self.agent_id,\n                error=str(e),\n            )\n\n        self._log(result)\n        return result\n\n    # ── Full Recovery Sequence ─────────────────────────────────\n\n    def recover_agent(\n        self,\n        target_daily_budget: str = \"500.00\",\n        initial_budget_pct: int = 50,\n        incident_id: str = \"\",\n    ) -> list[RecoveryResult]:\n        \"\"\"Execute the full recovery sequence.\n\n        Restores budget at a conservative percentage of the target,\n        verifies identity and reputation, and clears the incident flag.\n        \"\"\"\n        results = []\n\n        # Step 1: Restore budget at conservative level\n        initial_budget = str(\n            round(float(target_daily_budget) * initial_budget_pct \u002F 100, 2)\n        )\n        results.append(self.restore_budget(daily_budget=initial_budget))\n\n        # Step 2: Verify and restore reputation\n        results.append(self.restore_reputation())\n\n        # Step 3: Clear incident flag\n        results.append(self.clear_incident(incident_id=incident_id))\n\n        return results\n\n    def restore_full_budget(\n        self, target_daily_budget: str,\n    ) -> RecoveryResult:\n        \"\"\"Restore budget to full pre-incident level.\n\n        Call this 24-48 hours after initial recovery, once monitoring\n        confirms the agent is operating normally.\n        \"\"\"\n        return self.restore_budget(daily_budget=target_daily_budget)\n\n    def get_recovery_log(self) -> list[dict]:\n        \"\"\"Return the full recovery audit log.\"\"\"\n        return [r.to_dict() for r in self._recovery_log]\n```\n\n### The Gradual Restoration Pattern\n\nNever restore an agent to full operational capacity immediately. Use a stepped approach:\n\n```\nTime 0h:    50% of pre-incident budget, enhanced monitoring (30s interval)\nTime +6h:   If no anomalies, increase to 75%\nTime +24h:  If no anomalies, increase to 100%\nTime +48h:  Reduce monitoring to standard interval (5m)\n```\n\n```python\n# Gradual restoration example\nrecovery = IncidentRecovery(api_key=\"key\", agent_id=\"agent-prod-001\")\ndetector = IncidentDetector(api_key=\"key\", agent_id=\"agent-prod-001\")\n\n# Immediate: 50% budget with tight monitoring\nrecovery.restore_budget(daily_budget=\"250.00\")  # 50% of $500\ndetector.monitor(interval_seconds=30, max_iterations=720)  # 6 hours\n\n# +6h: Check for anomalies, then increase\nanomalies = detector.check_all()\nif not anomalies:\n    recovery.restore_budget(daily_budget=\"375.00\")  # 75%\n    detector.monitor(interval_seconds=60, max_iterations=1080)  # 18 hours\n\n# +24h: Full restoration\nanomalies = detector.check_all()\nif not anomalies:\n    recovery.restore_full_budget(target_daily_budget=\"500.00\")\n```\n\n---\n\n## Chapter 5: Phase 4: Post-Mortem — Learning from Failure\n\n### Every Incident Is a Training Signal\n\nThe post-mortem phase is where agent incident response diverges most sharply from traditional IT incident response. In traditional IR, the post-mortem produces a document: a timeline, a root cause, action items for humans. In agent incident response, the post-mortem produces data that feeds back into the detection system. Every incident teaches the detector what the next incident will look like.\n\nThe forensics phase has three outputs:\n\n1. **Audit trail**: A cryptographically verified record of everything the agent did during the incident window, extracted from GreenHelix claim chains.\n2. **Impact assessment**: Total financial impact -- funds locked, funds lost, funds recovered -- computed from billing analytics.\n3. **Incident timeline**: A reconstruction of events from detection through recovery, suitable for both human review and machine learning.\n\n### The IncidentForensics Class\n\n```python\nimport requests\nimport time\nimport json\nfrom typing import Optional\nfrom dataclasses import dataclass, field\nfrom datetime import datetime, timezone\n\n\n@dataclass\nclass ForensicsResult:\n    \"\"\"Result of a forensics investigation action.\"\"\"\n    action: str\n    agent_id: str\n    details: dict = field(default_factory=dict)\n    timestamp: float = field(default_factory=time.time)\n\n    def to_dict(self) -> dict:\n        return {\n            \"action\": self.action,\n            \"agent_id\": self.agent_id,\n            \"details\": self.details,\n            \"timestamp\": self.timestamp,\n        }\n\n\nclass IncidentForensics:\n    \"\"\"Phase 4: Post-mortem forensics for agent incidents.\n\n    Usage:\n        forensics = IncidentForensics(\n            api_key=\"your-key\",\n            agent_id=\"agent-prod-001\",\n        )\n\n        # Full post-mortem\n        report = forensics.run_post_mortem(\n            incident_id=\"inc-1712345678\",\n            incident_start=1712345000,\n            incident_end=1712346000,\n        )\n        print(json.dumps(report, indent=2))\n    \"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n    ):\n        self.api_key = api_key\n        self.agent_id = agent_id\n        self.base_url = base_url\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute a GreenHelix tool.\"\"\"\n        resp = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        resp.raise_for_status()\n        return resp.json()\n\n    # ── Audit Trail ────────────────────────────────────────────\n\n    def get_audit_trail(\n        self,\n        start_time: Optional[int] = None,\n        end_time: Optional[int] = None,\n    ) -> ForensicsResult:\n        \"\"\"Extract the cryptographically verified audit trail for\n        the incident window.\n\n        Uses claim chains to reconstruct a tamper-proof record of\n        agent actions. Each claim in the chain is individually\n        verifiable via its Merkle proof.\n        \"\"\"\n        # Get claim chains for the agent\n        chains_resp = self._execute(\"get_claim_chains\", {\n            \"agent_id\": self.agent_id,\n        })\n        chains = chains_resp.get(\"chains\", [])\n\n        # Get verified claims (individually verifiable)\n        claims_resp = self._execute(\"get_verified_claims\", {\n            \"agent_id\": self.agent_id,\n        })\n        claims = claims_resp.get(\"claims\", [])\n\n        # Filter to incident window if specified\n        if start_time and end_time:\n            claims = [\n                c for c in claims\n                if start_time \u003C= c.get(\"timestamp\", 0) \u003C= end_time\n            ]\n\n        # Get identity record for forensic context\n        identity_resp = self._execute(\"get_agent_identity\", {\n            \"agent_id\": self.agent_id,\n        })\n\n        return ForensicsResult(\n            action=\"audit_trail\",\n            agent_id=self.agent_id,\n            details={\n                \"claim_chains\": chains,\n                \"verified_claims_in_window\": claims,\n                \"total_claims_in_window\": len(claims),\n                \"identity_at_time\": identity_resp,\n                \"window\": {\n                    \"start\": start_time,\n                    \"end\": end_time,\n                },\n            },\n        )\n\n    # ── Impact Assessment ──────────────────────────────────────\n\n    def assess_impact(self) -> ForensicsResult:\n        \"\"\"Calculate the financial impact of the incident.\n\n        Uses billing analytics to compute total spending during the\n        incident, broken down by category. Compares against the\n        agent's normal spending patterns to isolate incident-related\n        costs.\n        \"\"\"\n        # Get usage analytics\n        analytics_resp = self._execute(\"get_usage_analytics\", {\n            \"agent_id\": self.agent_id,\n        })\n\n        # Get billing summary\n        billing_resp = self._execute(\"get_billing_summary\", {\n            \"agent_id\": self.agent_id,\n        })\n\n        # Get spending by category\n        category_resp = self._execute(\"get_spending_by_category\", {\n            \"agent_id\": self.agent_id,\n        })\n\n        # Get current balance\n        balance_resp = self._execute(\"get_balance\", {\n            \"agent_id\": self.agent_id,\n        })\n\n        # Get escrow status (how much was locked\u002Frecovered)\n        escrows_resp = self._execute(\"list_escrows\", {\n            \"agent_id\": self.agent_id,\n        })\n        escrows = escrows_resp.get(\"escrows\", [])\n\n        locked_funds = sum(\n            float(e.get(\"amount\", \"0\"))\n            for e in escrows\n            if e.get(\"status\") in (\"pending\", \"funded\", \"active\")\n        )\n        cancelled_funds = sum(\n            float(e.get(\"amount\", \"0\"))\n            for e in escrows\n            if e.get(\"status\") == \"cancelled\"\n        )\n        released_funds = sum(\n            float(e.get(\"amount\", \"0\"))\n            for e in escrows\n            if e.get(\"status\") == \"released\"\n        )\n\n        return ForensicsResult(\n            action=\"impact_assessment\",\n            agent_id=self.agent_id,\n            details={\n                \"current_balance\": balance_resp.get(\"balance\", \"0\"),\n                \"usage_analytics\": analytics_resp,\n                \"billing_summary\": billing_resp,\n                \"spending_by_category\": category_resp,\n                \"escrow_impact\": {\n                    \"total_escrows\": len(escrows),\n                    \"still_locked\": str(round(locked_funds, 2)),\n                    \"cancelled_recovered\": str(round(cancelled_funds, 2)),\n                    \"released_lost\": str(round(released_funds, 2)),\n                },\n            },\n        )\n\n    # ── Timeline Reconstruction ────────────────────────────────\n\n    def build_timeline(\n        self,\n        incident_id: str,\n        detection_time: int,\n        containment_time: int,\n        recovery_time: int,\n        containment_log: Optional[list[dict]] = None,\n        recovery_log: Optional[list[dict]] = None,\n    ) -> ForensicsResult:\n        \"\"\"Reconstruct a complete incident timeline.\n\n        Combines data from detection, containment, and recovery\n        phases into a single chronological record suitable for\n        both human review and machine learning.\n        \"\"\"\n        # Compute phase durations\n        detection_to_containment = containment_time - detection_time\n        containment_to_recovery = recovery_time - containment_time\n        total_duration = recovery_time - detection_time\n\n        # Get reputation at time of forensics\n        rep_resp = self._execute(\"get_agent_reputation\", {\n            \"agent_id\": self.agent_id,\n        })\n\n        timeline_events = []\n\n        # Detection event\n        timeline_events.append({\n            \"phase\": \"detection\",\n            \"timestamp\": detection_time,\n            \"iso_time\": datetime.fromtimestamp(\n                detection_time, tz=timezone.utc\n            ).isoformat(),\n            \"event\": \"incident_detected\",\n        })\n\n        # Containment events (from log if provided)\n        if containment_log:\n            for entry in containment_log:\n                timeline_events.append({\n                    \"phase\": \"containment\",\n                    \"timestamp\": entry.get(\"timestamp\", containment_time),\n                    \"iso_time\": datetime.fromtimestamp(\n                        entry.get(\"timestamp\", containment_time),\n                        tz=timezone.utc,\n                    ).isoformat(),\n                    \"event\": entry.get(\"action\", \"containment_action\"),\n                    \"success\": entry.get(\"success\", False),\n                    \"details\": entry.get(\"details\", {}),\n                })\n        else:\n            timeline_events.append({\n                \"phase\": \"containment\",\n                \"timestamp\": containment_time,\n                \"iso_time\": datetime.fromtimestamp(\n                    containment_time, tz=timezone.utc\n                ).isoformat(),\n                \"event\": \"containment_complete\",\n            })\n\n        # Recovery events (from log if provided)\n        if recovery_log:\n            for entry in recovery_log:\n                timeline_events.append({\n                    \"phase\": \"recovery\",\n                    \"timestamp\": entry.get(\"timestamp\", recovery_time),\n                    \"iso_time\": datetime.fromtimestamp(\n                        entry.get(\"timestamp\", recovery_time),\n                        tz=timezone.utc,\n                    ).isoformat(),\n                    \"event\": entry.get(\"action\", \"recovery_action\"),\n                    \"success\": entry.get(\"success\", False),\n                    \"details\": entry.get(\"details\", {}),\n                })\n        else:\n            timeline_events.append({\n                \"phase\": \"recovery\",\n                \"timestamp\": recovery_time,\n                \"iso_time\": datetime.fromtimestamp(\n                    recovery_time, tz=timezone.utc\n                ).isoformat(),\n                \"event\": \"recovery_complete\",\n            })\n\n        # Sort chronologically\n        timeline_events.sort(key=lambda e: e[\"timestamp\"])\n\n        return ForensicsResult(\n            action=\"build_timeline\",\n            agent_id=self.agent_id,\n            details={\n                \"incident_id\": incident_id,\n                \"timeline\": timeline_events,\n                \"phase_durations\": {\n                    \"detection_to_containment_seconds\": detection_to_containment,\n                    \"containment_to_recovery_seconds\": containment_to_recovery,\n                    \"total_duration_seconds\": total_duration,\n                },\n                \"reputation_post_incident\": rep_resp,\n                \"meets_60s_containment_sla\": detection_to_containment \u003C= 60,\n            },\n        )\n\n    # ── Full Post-Mortem ───────────────────────────────────────\n\n    def run_post_mortem(\n        self,\n        incident_id: str,\n        incident_start: int,\n        incident_end: int,\n        containment_log: Optional[list[dict]] = None,\n        recovery_log: Optional[list[dict]] = None,\n    ) -> dict:\n        \"\"\"Run a complete post-mortem investigation.\n\n        Combines audit trail, impact assessment, and timeline\n        reconstruction into a single report.\n        \"\"\"\n        audit = self.get_audit_trail(\n            start_time=incident_start,\n            end_time=incident_end,\n        )\n        impact = self.assess_impact()\n        timeline = self.build_timeline(\n            incident_id=incident_id,\n            detection_time=incident_start,\n            containment_time=incident_start + 45,  # Estimate if not provided\n            recovery_time=incident_end,\n            containment_log=containment_log,\n            recovery_log=recovery_log,\n        )\n\n        report = {\n            \"incident_id\": incident_id,\n            \"agent_id\": self.agent_id,\n            \"generated_at\": int(time.time()),\n            \"audit_trail\": audit.to_dict(),\n            \"impact_assessment\": impact.to_dict(),\n            \"timeline\": timeline.to_dict(),\n        }\n\n        # Publish the post-mortem as an event for downstream consumption\n        try:\n            self._execute(\"publish_event\", {\n                \"agent_id\": self.agent_id,\n                \"event_type\": \"incident_post_mortem\",\n                \"payload\": {\n                    \"incident_id\": incident_id,\n                    \"total_duration_seconds\": timeline.details[\n                        \"phase_durations\"\n                    ][\"total_duration_seconds\"],\n                    \"met_containment_sla\": timeline.details[\n                        \"meets_60s_containment_sla\"\n                    ],\n                    \"generated_at\": int(time.time()),\n                },\n            })\n        except requests.exceptions.RequestException:\n            pass\n\n        return report\n```\n\n### Feeding Post-Mortems Back into Detection\n\nThe post-mortem output is structured data, not a narrative document. This is deliberate. The `build_timeline` output can be ingested by the `IncidentDetector` to adjust anomaly thresholds:\n\n```python\n# After post-mortem, adjust detection sensitivity\nforensics = IncidentForensics(api_key=\"key\", agent_id=\"agent-prod-001\")\nreport = forensics.run_post_mortem(\n    incident_id=\"inc-1712345678\",\n    incident_start=1712345000,\n    incident_end=1712346000,\n)\n\n# If containment SLA was missed, tighten detection\nif not report[\"timeline\"][\"details\"][\"meets_60s_containment_sla\"]:\n    detector = IncidentDetector(\n        api_key=\"key\",\n        agent_id=\"agent-prod-001\",\n        cost_anomaly_std_devs=1.5,  # Tighter than default 2.0\n    )\n    print(\"Detection sensitivity increased due to missed SLA\")\n```\n\n---\n\n## Chapter 6: The 5 Agent Incident Runbooks\n\nEach runbook specifies: the trigger condition (what causes the alert), the severity classification, the automated response, and the manual follow-up. All automated steps use the classes from Chapters 2-5.\n\n### Runbook 1: Runaway Spending\n\n**Trigger**: `IncidentDetector.check_cost_anomaly()` returns severity \"critical\" -- spending rate exceeds 2 standard deviations above baseline.\n\n**Severity**: P0 (financial loss in progress)\n\n**Automated Response**:\n```python\ndef handle_runaway_spending(agent_id: str, anomaly: AnomalyResult):\n    \"\"\"Runbook 1: Automated response to runaway spending.\"\"\"\n    containment = IncidentContainment(\n        api_key=API_KEY, agent_id=agent_id,\n    )\n\n    # Step 1: Freeze immediately\n    freeze_result = containment.freeze_agent()\n    if not freeze_result.success:\n        # ESCALATE: Budget freeze failed, manual intervention required\n        alert_oncall(\n            severity=\"P0\",\n            message=f\"Budget freeze FAILED for {agent_id}. \"\n                    f\"Error: {freeze_result.error}. \"\n                    f\"Manual intervention required immediately.\",\n        )\n        return\n\n    # Step 2: Cancel all escrows to recover locked funds\n    escrow_result = containment.freeze_escrows()\n\n    # Step 3: Verify identity (rule out compromise)\n    identity_result = containment.verify_agent_identity()\n\n    # Step 4: Alert on-call with containment summary\n    alert_oncall(\n        severity=\"P0\",\n        message=(\n            f\"Runaway spending contained for {agent_id}. \"\n            f\"Budget frozen. \"\n            f\"{escrow_result.details.get('cancelled', 0)} escrows cancelled. \"\n            f\"${escrow_result.details.get('total_unlocked', '0')} recovered. \"\n            f\"Identity verified: \"\n            f\"{identity_result.details.get('identity_valid', False)}.\"\n        ),\n    )\n```\n\n**Manual Follow-Up**:\n1. Identify the code path causing excessive spending (retry loop, missing dedup, unbounded batch).\n2. Deploy fix to staging and verify with `IncidentDetector` at 30s polling for 1 hour.\n3. Run `IncidentRecovery.recover_agent()` with 50% budget.\n4. Run `IncidentForensics.run_post_mortem()` and publish findings.\n\n---\n\n### Runbook 2: Escrow Exploitation\n\n**Trigger**: An agent's escrow cancellation rate exceeds 50% in a 1-hour window, OR a single counterparty is the payee on more than 10 escrows from the same payer within 5 minutes.\n\n**Severity**: P1 (potential fraud, financial exposure)\n\n**Automated Response**:\n```python\ndef handle_escrow_exploitation(agent_id: str, suspect_payee_id: str):\n    \"\"\"Runbook 2: Respond to suspected escrow exploitation.\"\"\"\n    containment = IncidentContainment(\n        api_key=API_KEY, agent_id=agent_id,\n    )\n\n    # Step 1: Freeze the payer agent's budget\n    containment.freeze_agent()\n\n    # Step 2: Cancel escrows -- but only those to the suspect payee\n    escrows_resp = containment._execute(\"list_escrows\", {\n        \"agent_id\": agent_id,\n    })\n    escrows = escrows_resp.get(\"escrows\", [])\n\n    suspect_escrows = [\n        e for e in escrows\n        if e.get(\"payee_id\") == suspect_payee_id\n        and e.get(\"status\") in (\"pending\", \"funded\", \"active\")\n    ]\n\n    cancelled_amount = 0\n    for escrow in suspect_escrows:\n        try:\n            containment._execute(\"cancel_escrow\", {\n                \"escrow_id\": escrow[\"escrow_id\"],\n                \"reason\": f\"escrow_exploitation_suspected:{suspect_payee_id}\",\n            })\n            cancelled_amount += float(escrow.get(\"amount\", \"0\"))\n        except requests.exceptions.RequestException:\n            pass  # Log and continue; do not stop on individual failures\n\n    # Step 3: Check the suspect payee's reputation\n    payee_rep = containment._execute(\"get_agent_reputation\", {\n        \"agent_id\": suspect_payee_id,\n    })\n\n    # Step 4: Flag the suspect via metrics submission\n    containment._execute(\"submit_metrics\", {\n        \"agent_id\": suspect_payee_id,\n        \"metrics\": {\n            \"escrow_exploitation_flag\": True,\n            \"flagged_by\": agent_id,\n            \"flagged_at\": int(time.time()),\n            \"suspect_escrow_count\": len(suspect_escrows),\n        },\n    })\n\n    alert_oncall(\n        severity=\"P1\",\n        message=(\n            f\"Escrow exploitation suspected. Payer: {agent_id}. \"\n            f\"Suspect payee: {suspect_payee_id}. \"\n            f\"{len(suspect_escrows)} escrows cancelled. \"\n            f\"${round(cancelled_amount, 2)} recovered. \"\n            f\"Payee reputation: {payee_rep.get('reputation_score', 'N\u002FA')}.\"\n        ),\n    )\n```\n\n**Manual Follow-Up**:\n1. Review the suspect payee's full transaction history via `get_claim_chains`.\n2. If exploitation confirmed, report to platform via dispute mechanism.\n3. If false positive, unfreeze payer budget and remove metrics flag.\n\n---\n\n### Runbook 3: Identity Compromise\n\n**Trigger**: `IncidentContainment.verify_agent_identity()` returns `identity_valid: false`, OR the agent's public key changes unexpectedly, OR authentication patterns change (new IP, new user-agent, unusual hours).\n\n**Severity**: P0 (security breach)\n\n**Automated Response**:\n```python\ndef handle_identity_compromise(agent_id: str):\n    \"\"\"Runbook 3: Respond to suspected agent identity compromise.\"\"\"\n    containment = IncidentContainment(\n        api_key=API_KEY, agent_id=agent_id,\n    )\n\n    # Step 1: Full containment (budget + escrows + identity check)\n    results = containment.contain_agent()\n\n    # Step 2: Get the full identity record for forensic preservation\n    identity = containment._execute(\"get_agent_identity\", {\n        \"agent_id\": agent_id,\n    })\n\n    # Step 3: Get claim chains -- preserve the cryptographic audit trail\n    #         before any attacker can attempt to modify history\n    chains = containment._execute(\"get_claim_chains\", {\n        \"agent_id\": agent_id,\n    })\n\n    # Step 4: Check reputation for signs of attacker activity\n    reputation = containment._execute(\"get_agent_reputation\", {\n        \"agent_id\": agent_id,\n    })\n\n    # Step 5: Publish high-priority security event\n    containment._execute(\"publish_event\", {\n        \"agent_id\": agent_id,\n        \"event_type\": \"security_identity_compromise\",\n        \"payload\": {\n            \"severity\": \"P0\",\n            \"identity_snapshot\": identity,\n            \"chain_count\": len(chains.get(\"chains\", [])),\n            \"reputation_at_detection\": reputation.get(\"reputation_score\"),\n            \"timestamp\": int(time.time()),\n            \"action_required\": \"immediate_investigation\",\n        },\n    })\n\n    alert_oncall(\n        severity=\"P0\",\n        message=(\n            f\"IDENTITY COMPROMISE SUSPECTED for {agent_id}. \"\n            f\"All financial operations frozen. \"\n            f\"Audit trail preserved ({len(chains.get('chains', []))} chains). \"\n            f\"Immediate investigation required.\"\n        ),\n    )\n```\n\n**Manual Follow-Up**:\n1. Rotate all API keys associated with the compromised agent.\n2. Re-register the agent identity with new key material.\n3. Audit all transactions since the last known-good verification.\n4. Re-verify all counterparties the compromised agent transacted with.\n5. Run `IncidentForensics.run_post_mortem()` with full transaction window.\n\n---\n\n### Runbook 4: Service Degradation\n\n**Trigger**: `IncidentDetector.check_reputation_drift()` returns severity \"warning\" or \"critical\" -- reputation has dropped more than 15% from baseline.\n\n**Severity**: P2 (quality degradation, not immediate financial loss)\n\n**Automated Response**:\n```python\ndef handle_service_degradation(agent_id: str, anomaly: AnomalyResult):\n    \"\"\"Runbook 4: Respond to agent service quality degradation.\"\"\"\n    # Service degradation does NOT warrant immediate budget freeze.\n    # Instead, reduce budget to limit blast radius and alert.\n\n    api = requests.Session()\n    api.headers.update({\n        \"Content-Type\": \"application\u002Fjson\",\n        \"Authorization\": f\"Bearer {API_KEY}\",\n    })\n\n    def execute(tool, input_data):\n        resp = api.post(\n            f\"{BASE_URL}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        resp.raise_for_status()\n        return resp.json()\n\n    # Step 1: Get current budget and reduce by 50%\n    budget = execute(\"get_budget_status\", {\"agent_id\": agent_id})\n    current_daily = float(budget.get(\"daily_limit\", \"1000\"))\n    reduced_daily = str(round(current_daily * 0.5, 2))\n\n    execute(\"set_budget_cap\", {\n        \"agent_id\": agent_id,\n        \"daily\": reduced_daily,\n    })\n\n    # Step 2: Get detailed reputation data\n    reputation = execute(\"get_agent_reputation\", {\"agent_id\": agent_id})\n\n    # Step 3: Get usage analytics to correlate quality with volume\n    analytics = execute(\"get_usage_analytics\", {\"agent_id\": agent_id})\n\n    # Step 4: Publish degradation event\n    execute(\"publish_event\", {\n        \"agent_id\": agent_id,\n        \"event_type\": \"service_degradation_detected\",\n        \"payload\": {\n            \"reputation_drop\": anomaly.details.get(\"drop_pct\", \"unknown\"),\n            \"budget_reduced_to\": reduced_daily,\n            \"analytics_snapshot\": analytics,\n            \"timestamp\": int(time.time()),\n        },\n    })\n\n    alert_oncall(\n        severity=\"P2\",\n        message=(\n            f\"Service degradation for {agent_id}. \"\n            f\"Reputation dropped {anomaly.details.get('drop_pct', '?')}%. \"\n            f\"Budget reduced to ${reduced_daily}\u002Fday. \"\n            f\"Investigate quality metrics.\"\n        ),\n    )\n```\n\n**Manual Follow-Up**:\n1. Review recent agent outputs and counterparty feedback.\n2. Check for model drift, prompt degradation, or upstream dependency changes.\n3. If root cause is model-related, update prompts or constraints and redeploy.\n4. Use `IncidentRecovery.restore_reputation()` to submit corrected metrics.\n5. Gradually restore budget using the gradual restoration pattern.\n\n---\n\n### Runbook 5: Cascade Failure\n\n**Trigger**: Two or more agents trigger anomaly alerts within a 5-minute window, OR a shared resource (wallet, escrow pool, marketplace listing) is exhausted.\n\n**Severity**: P0 (multi-agent system failure)\n\n**Automated Response**:\n```python\ndef handle_cascade_failure(affected_agent_ids: list[str]):\n    \"\"\"Runbook 5: Respond to multi-agent cascade failure.\"\"\"\n    containment_results = {}\n\n    # Step 1: Freeze ALL affected agents simultaneously\n    for agent_id in affected_agent_ids:\n        containment = IncidentContainment(\n            api_key=API_KEY, agent_id=agent_id,\n        )\n        containment_results[agent_id] = containment.contain_agent()\n\n    # Step 2: Identify the root cause agent\n    #         (the one with the highest spending anomaly)\n    spending_anomalies = {}\n    for agent_id in affected_agent_ids:\n        detector = IncidentDetector(\n            api_key=API_KEY, agent_id=agent_id,\n        )\n        anomaly = detector.check_cost_anomaly()\n        if anomaly.detected:\n            z_score = float(anomaly.details.get(\"z_score\", \"0\"))\n            spending_anomalies[agent_id] = z_score\n\n    root_cause_agent = (\n        max(spending_anomalies, key=spending_anomalies.get)\n        if spending_anomalies else affected_agent_ids[0]\n    )\n\n    # Step 3: Deep forensics on root cause agent\n    forensics = IncidentForensics(\n        api_key=API_KEY, agent_id=root_cause_agent,\n    )\n    impact = forensics.assess_impact()\n\n    # Step 4: Publish cascade event with full scope\n    api = requests.Session()\n    api.headers.update({\n        \"Content-Type\": \"application\u002Fjson\",\n        \"Authorization\": f\"Bearer {API_KEY}\",\n    })\n    api.post(\n        f\"{BASE_URL}\u002Fv1\",\n        json={\n            \"tool\": \"publish_event\",\n            \"input\": {\n                \"agent_id\": root_cause_agent,\n                \"event_type\": \"cascade_failure\",\n                \"payload\": {\n                    \"affected_agents\": affected_agent_ids,\n                    \"root_cause_agent\": root_cause_agent,\n                    \"total_agents_affected\": len(affected_agent_ids),\n                    \"timestamp\": int(time.time()),\n                },\n            },\n        },\n    )\n\n    alert_oncall(\n        severity=\"P0\",\n        message=(\n            f\"CASCADE FAILURE: {len(affected_agent_ids)} agents affected. \"\n            f\"All frozen. Root cause agent: {root_cause_agent} \"\n            f\"(z-score: {spending_anomalies.get(root_cause_agent, 'N\u002FA')}). \"\n            f\"Impact: {json.dumps(impact.details.get('escrow_impact', {}))}.\"\n        ),\n    )\n\n    return {\n        \"root_cause_agent\": root_cause_agent,\n        \"containment_results\": {\n            aid: [r.to_dict() for r in results]\n            for aid, results in containment_results.items()\n        },\n        \"spending_anomalies\": spending_anomalies,\n    }\n```\n\n**Manual Follow-Up**:\n1. Identify the dependency chain: which agent triggered which agent's failure.\n2. Fix the root cause agent first, then recover downstream agents in dependency order.\n3. Implement circuit breakers between agents to prevent future cascades (see Chapter 7).\n4. Run post-mortems for all affected agents and correlate timelines.\n\n---\n\n## Chapter 7: Automated Incident Response\n\n### From Detection to Containment in Under 5 Seconds\n\nThe runbooks in Chapter 6 are designed for automation. The `AutomatedResponse` class ties detection to containment to escalation in a single pipeline. When the `IncidentDetector` fires, the `AutomatedResponse` executes the appropriate runbook without human intervention.\n\n### The AutomatedResponse Class\n\n```python\nimport requests\nimport time\nimport json\nfrom typing import Optional, Callable\nfrom dataclasses import dataclass, field\nfrom enum import Enum\n\n\nclass EscalationTier(Enum):\n    \"\"\"Escalation tiers for incident response.\"\"\"\n    AUTO_CONTAIN = \"auto_contain\"      # Automated freeze, alert on-call\n    ALERT_HUMAN = \"alert_human\"         # Alert without automated action\n    FULL_SHUTDOWN = \"full_shutdown\"      # Freeze all agents in fleet\n\n\nclass CircuitState(Enum):\n    \"\"\"Circuit breaker states.\"\"\"\n    CLOSED = \"closed\"      # Normal operation\n    OPEN = \"open\"          # Tripped, all operations blocked\n    HALF_OPEN = \"half_open\"  # Testing recovery\n\n\n@dataclass\nclass CircuitBreaker:\n    \"\"\"Circuit breaker for agent commerce operations.\"\"\"\n    agent_id: str\n    state: CircuitState = CircuitState.CLOSED\n    failure_count: int = 0\n    failure_threshold: int = 5\n    reset_timeout_seconds: int = 300\n    last_failure_time: float = 0\n    last_state_change: float = field(default_factory=time.time)\n\n    def record_failure(self):\n        self.failure_count += 1\n        self.last_failure_time = time.time()\n        if self.failure_count >= self.failure_threshold:\n            self.state = CircuitState.OPEN\n            self.last_state_change = time.time()\n\n    def record_success(self):\n        if self.state == CircuitState.HALF_OPEN:\n            self.state = CircuitState.CLOSED\n            self.failure_count = 0\n            self.last_state_change = time.time()\n\n    def should_allow(self) -> bool:\n        if self.state == CircuitState.CLOSED:\n            return True\n        if self.state == CircuitState.OPEN:\n            elapsed = time.time() - self.last_state_change\n            if elapsed >= self.reset_timeout_seconds:\n                self.state = CircuitState.HALF_OPEN\n                self.last_state_change = time.time()\n                return True\n            return False\n        # HALF_OPEN: allow one request to test\n        return True\n\n\nclass AutomatedResponse:\n    \"\"\"Automated incident response pipeline.\n\n    Connects detection signals to containment actions with\n    configurable escalation tiers.\n\n    Usage:\n        responder = AutomatedResponse(\n            api_key=\"your-key\",\n            fleet_agent_ids=[\"agent-001\", \"agent-002\", \"agent-003\"],\n            oncall_callback=send_pagerduty_alert,\n        )\n\n        # Register custom escalation rules\n        responder.add_rule(\n            signal=\"cost_anomaly\",\n            severity=\"critical\",\n            tier=EscalationTier.AUTO_CONTAIN,\n        )\n        responder.add_rule(\n            signal=\"reputation_drift\",\n            severity=\"warning\",\n            tier=EscalationTier.ALERT_HUMAN,\n        )\n\n        # Start automated monitoring\n        responder.start(interval_seconds=30)\n    \"\"\"\n\n    DEFAULT_RULES = {\n        (\"cost_anomaly\", \"critical\"): EscalationTier.AUTO_CONTAIN,\n        (\"cost_anomaly\", \"warning\"): EscalationTier.ALERT_HUMAN,\n        (\"budget_exhaustion\", \"critical\"): EscalationTier.AUTO_CONTAIN,\n        (\"budget_warning\", \"warning\"): EscalationTier.ALERT_HUMAN,\n        (\"reputation_drift\", \"critical\"): EscalationTier.AUTO_CONTAIN,\n        (\"reputation_drift\", \"warning\"): EscalationTier.ALERT_HUMAN,\n        (\"detection_failure\", \"warning\"): EscalationTier.ALERT_HUMAN,\n    }\n\n    def __init__(\n        self,\n        api_key: str,\n        fleet_agent_ids: list[str],\n        base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n        oncall_callback: Optional[Callable] = None,\n    ):\n        self.api_key = api_key\n        self.fleet_agent_ids = fleet_agent_ids\n        self.base_url = base_url\n        self.oncall_callback = oncall_callback or self._default_alert\n        self.rules: dict[tuple[str, str], EscalationTier] = dict(\n            self.DEFAULT_RULES\n        )\n        self._circuit_breakers: dict[str, CircuitBreaker] = {\n            aid: CircuitBreaker(agent_id=aid)\n            for aid in fleet_agent_ids\n        }\n        self._incident_log: list[dict] = []\n        self._detectors: dict[str, IncidentDetector] = {\n            aid: IncidentDetector(\n                api_key=api_key,\n                agent_id=aid,\n                base_url=base_url,\n            )\n            for aid in fleet_agent_ids\n        }\n\n    @staticmethod\n    def _default_alert(severity: str, message: str):\n        print(f\"[ALERT {severity}] {message}\")\n\n    def add_rule(\n        self,\n        signal: str,\n        severity: str,\n        tier: EscalationTier,\n    ):\n        \"\"\"Add or override an escalation rule.\"\"\"\n        self.rules[(signal, severity)] = tier\n\n    # ── Core Response Actions ──────────────────────────────────\n\n    def auto_contain(self, agent_id: str, anomaly: AnomalyResult):\n        \"\"\"Execute automated containment for a single agent.\"\"\"\n        containment = IncidentContainment(\n            api_key=self.api_key,\n            agent_id=agent_id,\n            base_url=self.base_url,\n        )\n        results = containment.contain_agent()\n\n        # Record in circuit breaker\n        breaker = self._circuit_breakers.get(agent_id)\n        if breaker:\n            breaker.record_failure()\n\n        # Log the incident\n        incident = {\n            \"incident_id\": f\"inc-{int(time.time())}-{agent_id}\",\n            \"agent_id\": agent_id,\n            \"signal\": anomaly.signal,\n            \"severity\": anomaly.severity,\n            \"tier\": EscalationTier.AUTO_CONTAIN.value,\n            \"containment_results\": [r.to_dict() for r in results],\n            \"timestamp\": time.time(),\n        }\n        self._incident_log.append(incident)\n\n        # Alert on-call\n        self.oncall_callback(\n            severity=anomaly.severity.upper(),\n            message=(\n                f\"Auto-contained {agent_id}: {anomaly.signal}. \"\n                f\"Details: {json.dumps(anomaly.details)}\"\n            ),\n        )\n\n        return incident\n\n    def escalate(\n        self,\n        agent_id: str,\n        anomaly: AnomalyResult,\n        tier: EscalationTier,\n    ):\n        \"\"\"Escalate an anomaly to the appropriate tier.\"\"\"\n        if tier == EscalationTier.AUTO_CONTAIN:\n            return self.auto_contain(agent_id, anomaly)\n        elif tier == EscalationTier.ALERT_HUMAN:\n            self.oncall_callback(\n                severity=anomaly.severity.upper(),\n                message=(\n                    f\"Alert for {agent_id}: {anomaly.signal}. \"\n                    f\"No automated action taken. \"\n                    f\"Details: {json.dumps(anomaly.details)}\"\n                ),\n            )\n            return {\n                \"agent_id\": agent_id,\n                \"tier\": tier.value,\n                \"action\": \"alert_only\",\n            }\n        elif tier == EscalationTier.FULL_SHUTDOWN:\n            return self._full_shutdown(anomaly)\n\n    def _full_shutdown(self, trigger_anomaly: AnomalyResult) -> dict:\n        \"\"\"Emergency: freeze every agent in the fleet.\"\"\"\n        results = {}\n        for agent_id in self.fleet_agent_ids:\n            containment = IncidentContainment(\n                api_key=self.api_key,\n                agent_id=agent_id,\n                base_url=self.base_url,\n            )\n            results[agent_id] = [\n                r.to_dict() for r in containment.contain_agent()\n            ]\n\n        self.oncall_callback(\n            severity=\"P0\",\n            message=(\n                f\"FULL FLEET SHUTDOWN executed. \"\n                f\"{len(self.fleet_agent_ids)} agents frozen. \"\n                f\"Trigger: {trigger_anomaly.agent_id} - \"\n                f\"{trigger_anomaly.signal}.\"\n            ),\n        )\n\n        return {\n            \"action\": \"full_shutdown\",\n            \"agents_frozen\": len(self.fleet_agent_ids),\n            \"results\": results,\n        }\n\n    # ── Circuit Breaker ────────────────────────────────────────\n\n    def circuit_breaker(self, agent_id: str) -> CircuitBreaker:\n        \"\"\"Get the circuit breaker for an agent.\n\n        The circuit breaker tracks failure counts and automatically\n        blocks operations when an agent exceeds the failure threshold.\n        After the reset timeout, it enters half-open state and allows\n        a single test operation.\n\n        Usage in agent code:\n            breaker = responder.circuit_breaker(\"agent-001\")\n            if breaker.should_allow():\n                try:\n                    result = execute_tool(...)\n                    breaker.record_success()\n                except Exception:\n                    breaker.record_failure()\n            else:\n                # Agent is circuit-broken, skip operation\n                log.warning(f\"Circuit open for {agent_id}\")\n        \"\"\"\n        if agent_id not in self._circuit_breakers:\n            self._circuit_breakers[agent_id] = CircuitBreaker(\n                agent_id=agent_id,\n            )\n        return self._circuit_breakers[agent_id]\n\n    # ── Monitoring Loop ────────────────────────────────────────\n\n    def _process_anomalies(self, agent_id: str, anomalies: list):\n        \"\"\"Process detected anomalies through the escalation rules.\"\"\"\n        # Check circuit breaker first\n        breaker = self._circuit_breakers.get(agent_id)\n        if breaker and breaker.state == CircuitState.OPEN:\n            # Agent is already circuit-broken, auto-contain\n            for anomaly in anomalies:\n                self.auto_contain(agent_id, anomaly)\n            return\n\n        for anomaly in anomalies:\n            rule_key = (anomaly.signal, anomaly.severity)\n            tier = self.rules.get(rule_key, EscalationTier.ALERT_HUMAN)\n            self.escalate(agent_id, anomaly, tier)\n\n    def start(\n        self,\n        interval_seconds: int = 30,\n        max_iterations: Optional[int] = None,\n    ):\n        \"\"\"Start the automated response monitoring loop.\n\n        Polls all fleet agents for anomalies and triggers the\n        appropriate response based on escalation rules.\n        \"\"\"\n        # Check for cascade condition: multiple agents alerting\n        cascade_window: dict[str, float] = {}\n        cascade_threshold = 2  # agents within 5 minutes = cascade\n\n        iteration = 0\n        while max_iterations is None or iteration \u003C max_iterations:\n            alerting_agents = []\n\n            for agent_id in self.fleet_agent_ids:\n                detector = self._detectors[agent_id]\n                anomalies = detector.check_all()\n\n                if anomalies:\n                    alerting_agents.append(agent_id)\n                    cascade_window[agent_id] = time.time()\n                    self._process_anomalies(agent_id, anomalies)\n\n            # Check for cascade condition\n            now = time.time()\n            recent_alerts = {\n                aid: t for aid, t in cascade_window.items()\n                if now - t \u003C 300  # 5-minute window\n            }\n            if len(recent_alerts) >= cascade_threshold:\n                handle_cascade_failure(list(recent_alerts.keys()))\n                cascade_window.clear()\n\n            time.sleep(interval_seconds)\n            iteration += 1\n\n    def get_incident_log(self) -> list[dict]:\n        \"\"\"Return all incidents handled by this responder.\"\"\"\n        return list(self._incident_log)\n```\n\n### Webhook-Triggered Containment\n\nFor organizations that prefer push-based alerting over polling, the `AutomatedResponse` integrates with GreenHelix webhooks. The webhook handler receives events from the gateway and triggers containment directly:\n\n```python\nfrom flask import Flask, request, jsonify\n\napp = Flask(__name__)\n\nresponder = AutomatedResponse(\n    api_key=API_KEY,\n    fleet_agent_ids=[\"agent-001\", \"agent-002\", \"agent-003\"],\n    oncall_callback=send_pagerduty_alert,\n)\n\n@app.route(\"\u002Fincidents\u002Fwebhook\", methods=[\"POST\"])\ndef handle_webhook():\n    \"\"\"Receive GreenHelix webhook events and trigger response.\"\"\"\n    event = request.get_json()\n    event_type = event.get(\"event_type\", \"\")\n    agent_id = event.get(\"agent_id\", \"\")\n    payload = event.get(\"payload\", {})\n\n    if event_type == \"budget_threshold\":\n        utilization = float(payload.get(\"utilization_pct\", 0))\n        if utilization >= 95:\n            anomaly = AnomalyResult(\n                detected=True,\n                signal=\"budget_exhaustion\",\n                severity=\"critical\",\n                agent_id=agent_id,\n                details=payload,\n            )\n            responder.auto_contain(agent_id, anomaly)\n        elif utilization >= 80:\n            responder.oncall_callback(\n                severity=\"WARNING\",\n                message=f\"Budget at {utilization}% for {agent_id}\",\n            )\n\n    elif event_type == \"reputation_change\":\n        score_delta = float(payload.get(\"score_delta\", 0))\n        if score_delta \u003C -0.15:\n            anomaly = AnomalyResult(\n                detected=True,\n                signal=\"reputation_drift\",\n                severity=\"critical\" if score_delta \u003C -0.30 else \"warning\",\n                agent_id=agent_id,\n                details=payload,\n            )\n            responder.escalate(\n                agent_id, anomaly,\n                EscalationTier.AUTO_CONTAIN\n                if score_delta \u003C -0.30\n                else EscalationTier.ALERT_HUMAN,\n            )\n\n    return jsonify({\"status\": \"processed\"})\n```\n\n### The Escalation Ladder\n\n```\n                ┌──────────────────────────────────────┐\n                │         FULL FLEET SHUTDOWN           │\n                │   All agents frozen. All hands.       │\n                │   Trigger: cascade failure (2+ P0s)   │\n                └──────────────┬───────────────────────┘\n                               │\n                ┌──────────────▼───────────────────────┐\n                │         AUTO-CONTAIN                  │\n                │   Budget frozen. Escrows cancelled.   │\n                │   On-call alerted.                    │\n                │   Trigger: critical anomaly           │\n                └──────────────┬───────────────────────┘\n                               │\n                ┌──────────────▼───────────────────────┐\n                │         ALERT HUMAN                   │\n                │   No automated action.                │\n                │   On-call notified for investigation. │\n                │   Trigger: warning anomaly            │\n                └──────────────────────────────────────┘\n```\n\nThe default mapping is conservative: critical anomalies auto-contain, warnings alert humans, and cascade failures shut down the fleet. Override with `add_rule()` to tune for your risk tolerance. A trading firm may want warnings to also auto-contain. A low-value agent fleet may want only critical signals to trigger any response.\n\n---\n\n## Chapter 8: Incident Readiness Checklist\n\n### Pre-Incident Setup\n\nComplete this checklist before your first production deployment. Every item maps to a class or method in this guide.\n\n**Detection Infrastructure**\n\n- [ ] `IncidentDetector` deployed for each production agent\n- [ ] Cost anomaly threshold tuned (`cost_anomaly_std_devs` calibrated against 2 weeks of baseline data)\n- [ ] Reputation drift threshold set (`reputation_drop_threshold` based on normal variance)\n- [ ] Webhook endpoints registered via `setup_alerts()` for budget, escrow, and reputation events\n- [ ] Webhook receiver deployed and health-checked (if webhook receiver is down, detection is blind)\n- [ ] Monitoring interval configured (30s for high-value agents, 5m for low-value)\n\n**Containment Readiness**\n\n- [ ] `IncidentContainment` tested against sandbox for each agent\n- [ ] Containment completes within 60 seconds (verified via timing test)\n- [ ] API key used for containment has permissions for `set_budget_cap`, `list_escrows`, `cancel_escrow`, `verify_agent`, `get_agent_identity`, `publish_event`\n- [ ] Containment API key is separate from agent's operational key (so a compromised agent key does not prevent containment)\n\n**Recovery Procedures**\n\n- [ ] Pre-incident budget levels documented for each agent\n- [ ] Gradual restoration schedule defined (50% \u002F 75% \u002F 100% over 48 hours)\n- [ ] Recovery verification criteria defined (what \"normal\" looks like post-incident)\n- [ ] `IncidentRecovery` tested against sandbox\n\n**Forensics Capability**\n\n- [ ] `IncidentForensics` tested and producing valid post-mortem reports\n- [ ] Claim chains actively maintained for all production agents (if claim chains are empty, there is no audit trail to review)\n- [ ] Billing analytics accessible (confirm `get_usage_analytics`, `get_billing_summary`, `get_spending_by_category` all return data)\n\n### Severity Classification\n\n| Severity | Description | Response Time | Automated Action |\n|---|---|---|---|\n| **P0** | Active financial loss or security breach | Immediate (auto-contained in \u003C5s) | Full containment + on-call page |\n| **P1** | Potential fraud or escalating exposure | \u003C 15 minutes | Budget freeze + on-call page |\n| **P2** | Quality degradation or budget warning | \u003C 1 hour | Budget reduction + Slack alert |\n| **P3** | Informational anomaly, no action needed | Next business day | Log only |\n\n### On-Call Rotation for Agent Systems\n\nAgent on-call differs from traditional service on-call in three ways:\n\n1. **Financial authority required**: The on-call engineer must have permissions to restore budgets, cancel escrows, and re-register agent identities. Without these permissions, recovery is blocked.\n\n2. **Model knowledge required**: Agent incidents often require understanding model behavior, prompt engineering, and stochastic reasoning. The on-call rotation should include engineers with ML\u002FAI experience, not only infrastructure engineers.\n\n3. **Faster escalation**: Traditional on-call escalation gives 30 minutes before paging a secondary. Agent on-call should escalate in 5 minutes for P0 and 15 minutes for P1, because financial exposure grows linearly with response time.\n\n### Cross-References to Companion Guides\n\nThis guide completes the operational lifecycle when combined with three companion guides:\n\n- **Locking Down Agent Commerce** (P8) covers prevention: security hardening, identity verification, credential isolation, and financial guardrails. Read P8 to reduce the frequency of incidents.\n- **The Agent Testing & Observability Cookbook** (P9) covers detection infrastructure: the `AgentTracer`, `HealthChecker`, chaos testing, and CI\u002FCD pipelines. Read P9 to build the monitoring foundation that feeds into this guide's `IncidentDetector`.\n- **Ship Compliant Agents** (P11) covers the regulatory dimension: EU AI Act compliance, audit trail requirements (Article 12), and liability-bounded escrow patterns. Read P11 to ensure your incident response satisfies regulatory obligations for logging and reporting.\n\nTogether, the four guides form a closed loop:\n\n```\nP8 (Security)  ──prevent──▶  P9 (Observability)  ──detect──▶\nP12 (Incident Response)  ──recover──▶  P11 (Compliance)  ──audit──▶\n```\n\n### Practice on the Sandbox\n\nThe sandbox at `sandbox.greenhelix.net` is free to use with any API key. Deploy the `IncidentDetector` against it. Trigger a simulated incident by rapidly creating escrows. Verify that `IncidentContainment.contain_agent()` freezes the budget and cancels the escrows. Run `IncidentForensics.run_post_mortem()` and review the output. Build muscle memory for incident response before you need it in production.\n\n### The Full Lifecycle\n\n```python\n# Complete incident response lifecycle in 30 lines\n\n# 1. Detection\ndetector = IncidentDetector(api_key=KEY, agent_id=AGENT)\ndetector.setup_alerts(webhook_url=WEBHOOK_URL)\nanomalies = detector.check_all()\n\n# 2. Containment (if critical)\nif any(a.severity == \"critical\" for a in anomalies):\n    containment = IncidentContainment(api_key=KEY, agent_id=AGENT)\n    containment_results = containment.contain_agent()\n    containment_time = int(time.time())\n\n# 3. Recovery (after root cause fixed)\nrecovery = IncidentRecovery(api_key=KEY, agent_id=AGENT)\nrecovery_results = recovery.recover_agent(\n    target_daily_budget=\"500.00\",\n    initial_budget_pct=50,\n)\n\n# 4. Post-mortem\nforensics = IncidentForensics(api_key=KEY, agent_id=AGENT)\nreport = forensics.run_post_mortem(\n    incident_id=\"inc-001\",\n    incident_start=int(time.time()) - 3600,\n    incident_end=int(time.time()),\n    containment_log=containment.get_containment_log(),\n    recovery_log=recovery.get_recovery_log(),\n)\nprint(json.dumps(report, indent=2))\n```\n\nFour phases, four classes, four API calls each. Detect, contain, recover, learn. Copy the classes into your project, tune the thresholds, set up the webhooks, and practice on the sandbox. When the 2:47 AM alert fires, you will have a runbook.\n\n### The Bundle\n\nAll companion guides plus this playbook are available as a bundle. Each guide introduces production-ready Python classes that compose into a complete agent commerce platform: building (P1), cost management (P2), reputation (P3), audit trails (P4), trust verification (P5), marketplace strategy (P6), multi-agent patterns (P7), security hardening (P8), testing and observability (P9), SaaS automation (P10), compliance (P11), and incident response (P12).\n\nFor the full API reference and tool catalog (all 128 tools), visit the GreenHelix developer documentation at [https:\u002F\u002Fapi.greenhelix.net\u002Fdocs](https:\u002F\u002Fapi.greenhelix.net\u002Fdocs).\n\n---\n\n*Price: $29 | Format: Digital Guide | Updates: Lifetime access*\n\n---\n\n## Automated Incident Detection & Escalation — 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\"\"\"\nAutomated incident detection and escalation using the greenhelix_trading library.\n\nCovers:\n  1. Anomaly detection pipeline (cost, reputation, budget)\n  2. Automatic containment actions (freeze, escrow cancel, identity verify)\n  3. Guided recovery procedures with graduated budget restoration\n  4. Forensic evidence collection (audit trails, impact, timeline)\n  5. End-to-end incident orchestrator\n\nRequirements:\n    pip install greenhelix-trading\n\"\"\"\n\nimport os\nimport time\nimport json\nfrom datetime import datetime, timezone\nfrom typing import Optional\nfrom dataclasses import dataclass, field\n\nfrom greenhelix_trading import (\n    IncidentDetector,\n    IncidentContainment,\n    IncidentRecovery,\n    IncidentForensics,\n)\n\n\n# ── Configuration ─────────────────────────────────────────────────────────────\n\nAPI_KEY = os.environ[\"GREENHELIX_API_KEY\"]\nAGENT_ID = os.environ[\"GREENHELIX_AGENT_ID\"]\nWEBHOOK_URL = os.environ.get(\n    \"GREENHELIX_WEBHOOK_URL\",\n    \"https:\u002F\u002Fyour-app.example.com\u002Fincidents\u002Fwebhook\",\n)\n\n\n# ── Data Classes ──────────────────────────────────────────────────────────────\n\n@dataclass\nclass IncidentRecord:\n    \"\"\"Complete record of a detected, contained, and recovered incident.\"\"\"\n    incident_id: str\n    agent_id: str\n    detected_at: float = field(default_factory=time.time)\n    contained_at: Optional[float] = None\n    recovered_at: Optional[float] = None\n    detection_signals: list = field(default_factory=list)\n    containment_results: list = field(default_factory=list)\n    recovery_results: list = field(default_factory=list)\n    forensics_report: Optional[dict] = None\n    severity: str = \"unknown\"\n\n    def elapsed_to_containment(self) -> Optional[float]:\n        if self.contained_at:\n            return round(self.contained_at - self.detected_at, 2)\n        return None\n\n    def elapsed_to_recovery(self) -> Optional[float]:\n        if self.recovered_at:\n            return round(self.recovered_at - self.detected_at, 2)\n        return None\n\n    def to_dict(self) -> dict:\n        return {\n            \"incident_id\": self.incident_id,\n            \"agent_id\": self.agent_id,\n            \"severity\": self.severity,\n            \"detected_at\": self.detected_at,\n            \"contained_at\": self.contained_at,\n            \"recovered_at\": self.recovered_at,\n            \"elapsed_to_containment_s\": self.elapsed_to_containment(),\n            \"elapsed_to_recovery_s\": self.elapsed_to_recovery(),\n            \"detection_signals\": self.detection_signals,\n            \"containment_results\": self.containment_results,\n            \"recovery_results\": self.recovery_results,\n            \"forensics_report\": self.forensics_report,\n        }\n\n\n# ── 1. Anomaly Detection Pipeline ────────────────────────────────────────────\n\nclass AnomalyPipeline:\n    \"\"\"Multi-signal anomaly detection using IncidentDetector.\n\n    Runs three independent checks — cost anomaly, reputation drift,\n    and spending breakdown — and correlates the signals to produce\n    a severity classification.\n\n    Uses:\n        IncidentDetector.check_cost_anomaly()\n        IncidentDetector.check_reputation_drift(baseline_score)\n        IncidentDetector.setup_alerts(webhook_url)\n        IncidentDetector.get_spending_breakdown()\n    \"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        cost_threshold: float = 500.0,\n        reputation_threshold: float = 0.1,\n        baseline_reputation: float = 0.85,\n    ):\n        self.agent_id = agent_id\n        self.baseline_reputation = baseline_reputation\n        self._detector = IncidentDetector(\n            api_key=api_key,\n            agent_id=agent_id,\n            cost_threshold=cost_threshold,\n            reputation_threshold=reputation_threshold,\n        )\n        self._alert_history: list[dict] = []\n\n    def setup_webhook_alerts(self, webhook_url: str) -> dict:\n        \"\"\"Register persistent webhook alerts for budget, escrow, and\n        reputation events.\n\n        Calls IncidentDetector.setup_alerts which wraps register_webhook\n        with the event types: budget_exceeded, reputation_change,\n        escrow_timeout.\n        \"\"\"\n        result = self._detector.setup_alerts(webhook_url=webhook_url)\n        return {\n            \"status\": \"configured\",\n            \"webhook_url\": webhook_url,\n            \"registration\": result,\n        }\n\n    def run_detection_cycle(self) -> dict:\n        \"\"\"Execute one full detection cycle across all signals.\n\n        Returns a dict with the severity (\"clear\", \"warning\", \"critical\"),\n        the individual signal results, and a spending breakdown for\n        context.\n        \"\"\"\n        signals = []\n        severity = \"clear\"\n\n        # Signal 1: Cost anomaly\n        cost_result = self._detector.check_cost_anomaly()\n        cost_anomaly = cost_result.get(\"anomaly\", False)\n        signals.append({\n            \"signal\": \"cost_anomaly\",\n            \"triggered\": cost_anomaly,\n            \"data\": cost_result,\n        })\n\n        # Signal 2: Reputation drift\n        rep_result = self._detector.check_reputation_drift(\n            baseline_score=self.baseline_reputation,\n        )\n        rep_drift = rep_result.get(\"drift\", False)\n        signals.append({\n            \"signal\": \"reputation_drift\",\n            \"triggered\": rep_drift,\n            \"delta\": rep_result.get(\"delta\", 0),\n            \"data\": rep_result,\n        })\n\n        # Signal 3: Spending breakdown (context, not a direct trigger)\n        spending = self._detector.get_spending_breakdown()\n        signals.append({\n            \"signal\": \"spending_context\",\n            \"triggered\": False,\n            \"data\": spending,\n        })\n\n        # Severity classification\n        triggered_count = sum(1 for s in signals if s[\"triggered\"])\n        if triggered_count >= 2:\n            severity = \"critical\"\n        elif triggered_count == 1:\n            severity = \"warning\"\n\n        cycle_result = {\n            \"timestamp\": time.time(),\n            \"agent_id\": self.agent_id,\n            \"severity\": severity,\n            \"triggered_signals\": triggered_count,\n            \"signals\": signals,\n        }\n\n        if severity != \"clear\":\n            self._alert_history.append(cycle_result)\n\n        return cycle_result\n\n    def run_continuous_monitoring(\n        self,\n        interval_seconds: int = 30,\n        max_cycles: Optional[int] = None,\n        on_anomaly=None,\n    ):\n        \"\"\"Poll-based continuous monitoring loop.\n\n        Args:\n            interval_seconds: Time between detection cycles.\n            max_cycles: Stop after N cycles (None = run forever).\n            on_anomaly: Callback(cycle_result) when severity != \"clear\".\n        \"\"\"\n        cycle = 0\n        while max_cycles is None or cycle \u003C max_cycles:\n            result = self.run_detection_cycle()\n            if result[\"severity\"] != \"clear\":\n                if on_anomaly:\n                    on_anomaly(result)\n                else:\n                    print(\n                        f\"[{result['severity'].upper()}] \"\n                        f\"Agent {self.agent_id}: \"\n                        f\"{result['triggered_signals']} signals triggered\"\n                    )\n            time.sleep(interval_seconds)\n            cycle += 1\n\n    def get_alert_history(self) -> list[dict]:\n        return list(self._alert_history)\n\n\n# ── 2. Automatic Containment ─────────────────────────────────────────────────\n\nclass AutoContainment:\n    \"\"\"Automated containment actions targeting the 60-second SLA.\n\n    Executes three steps in sequence:\n      1. Freeze budget (IncidentContainment.freeze_agent)\n      2. Cancel active escrows (IncidentContainment.freeze_escrows)\n      3. Verify identity (IncidentContainment.verify_agent_identity)\n\n    Also publishes an incident event via\n    IncidentContainment.publish_incident_event for fleet-wide visibility.\n    \"\"\"\n\n    def __init__(self, api_key: str, agent_id: str):\n        self.agent_id = agent_id\n        self._containment = IncidentContainment(\n            api_key=api_key,\n            agent_id=agent_id,\n        )\n\n    def contain(self, severity: str, trigger_signal: str) -> list[dict]:\n        \"\"\"Execute the full containment sequence.\n\n        All three steps are attempted regardless of individual failures.\n        Returns a list of result dicts, one per step.\n        \"\"\"\n        results = []\n        start = time.time()\n\n        # Step 1: Freeze the agent's budget to $0\n        try:\n            freeze_result = self._containment.freeze_agent()\n            results.append({\n                \"step\": \"freeze_budget\",\n                \"success\": True,\n                \"data\": freeze_result,\n            })\n        except Exception as exc:\n            results.append({\n                \"step\": \"freeze_budget\",\n                \"success\": False,\n                \"error\": str(exc),\n            })\n\n        # Step 2: Cancel all active escrows to recover locked funds\n        try:\n            escrow_result = self._containment.freeze_escrows()\n            results.append({\n                \"step\": \"cancel_escrows\",\n                \"success\": True,\n                \"cancelled\": escrow_result.get(\"total_frozen\", 0),\n                \"data\": escrow_result,\n            })\n        except Exception as exc:\n            results.append({\n                \"step\": \"cancel_escrows\",\n                \"success\": False,\n                \"error\": str(exc),\n            })\n\n        # Step 3: Verify agent identity has not been compromised\n        try:\n            identity_result = self._containment.verify_agent_identity()\n            results.append({\n                \"step\": \"verify_identity\",\n                \"success\": True,\n                \"identity_intact\": identity_result.get(\n                    \"verification\", {}\n                ).get(\"verified\", False),\n                \"data\": identity_result,\n            })\n        except Exception as exc:\n            results.append({\n                \"step\": \"verify_identity\",\n                \"success\": False,\n                \"error\": str(exc),\n            })\n\n        elapsed = round(time.time() - start, 2)\n\n        # Publish containment event for fleet-wide visibility\n        try:\n            self._containment.publish_incident_event(\n                severity=severity,\n                details=json.dumps({\n                    \"trigger\": trigger_signal,\n                    \"containment_elapsed_s\": elapsed,\n                    \"steps_succeeded\": sum(1 for r in results if r[\"success\"]),\n                    \"steps_total\": len(results),\n                }),\n            )\n        except Exception:\n            pass  # Event publishing must not block containment\n\n        # Annotate with timing\n        for r in results:\n            r[\"containment_elapsed_s\"] = elapsed\n            r[\"met_60s_sla\"] = elapsed \u003C= 60.0\n\n        return results\n\n\n# ── 3. Guided Recovery ────────────────────────────────────────────────────────\n\nclass GuidedRecovery:\n    \"\"\"Graduated recovery with reputation verification.\n\n    Recovery proceeds through three gates:\n      Gate 1: Restore budget at 50% of target (IncidentRecovery.restore_budget)\n      Gate 2: Submit recovery metrics (IncidentRecovery.update_reputation)\n      Gate 3: Publish recovery event (IncidentRecovery.publish_recovery_event)\n\n    After 24 hours with no anomalies, call restore_full_budget to\n    return to the pre-incident budget level.\n    \"\"\"\n\n    def __init__(self, api_key: str, agent_id: str):\n        self.agent_id = agent_id\n        self._recovery = IncidentRecovery(\n            api_key=api_key,\n            agent_id=agent_id,\n        )\n\n    def execute_recovery(\n        self,\n        target_daily_budget: float,\n        initial_pct: int = 50,\n        incident_id: str = \"\",\n    ) -> list[dict]:\n        \"\"\"Run the three-gate recovery sequence.\n\n        Args:\n            target_daily_budget: The pre-incident daily budget.\n            initial_pct: Percentage of target to restore initially.\n            incident_id: For event correlation.\n\n        Returns:\n            List of recovery step results.\n        \"\"\"\n        results = []\n        initial_budget = target_daily_budget * initial_pct \u002F 100\n\n        # Gate 1: Restore budget at conservative level\n        try:\n            budget_result = self._recovery.restore_budget(\n                daily=initial_budget,\n                monthly=initial_budget * 30,\n            )\n            results.append({\n                \"gate\": 1,\n                \"action\": \"restore_budget\",\n                \"success\": True,\n                \"budget_restored\": initial_budget,\n                \"pct_of_target\": initial_pct,\n                \"data\": budget_result,\n            })\n        except Exception as exc:\n            results.append({\n                \"gate\": 1,\n                \"action\": \"restore_budget\",\n                \"success\": False,\n                \"error\": str(exc),\n            })\n\n        # Gate 2: Submit recovery metrics to rebuild reputation\n        try:\n            metrics_result = self._recovery.update_reputation(metrics={\n                \"incident_recovery\": True,\n                \"recovery_timestamp\": int(time.time()),\n                \"post_recovery_status\": \"active\",\n                \"incident_id\": incident_id,\n            })\n            results.append({\n                \"gate\": 2,\n                \"action\": \"update_reputation\",\n                \"success\": True,\n                \"data\": metrics_result,\n            })\n        except Exception as exc:\n            results.append({\n                \"gate\": 2,\n                \"action\": \"update_reputation\",\n                \"success\": False,\n                \"error\": str(exc),\n            })\n\n        # Gate 3: Publish recovery event\n        try:\n            event_result = self._recovery.publish_recovery_event(\n                details=json.dumps({\n                    \"incident_id\": incident_id or f\"inc-{int(time.time())}\",\n                    \"budget_restored_to\": initial_budget,\n                    \"recovery_timestamp\": int(time.time()),\n                }),\n            )\n            results.append({\n                \"gate\": 3,\n                \"action\": \"publish_recovery_event\",\n                \"success\": True,\n                \"data\": event_result,\n            })\n        except Exception as exc:\n            results.append({\n                \"gate\": 3,\n                \"action\": \"publish_recovery_event\",\n                \"success\": False,\n                \"error\": str(exc),\n            })\n\n        return results\n\n    def restore_full_budget(self, target_daily_budget: float) -> dict:\n        \"\"\"Restore to full pre-incident budget after monitoring period.\n\n        Call this 24-48 hours after initial recovery once the\n        AnomalyPipeline confirms no further anomalies.\n        \"\"\"\n        try:\n            result = self._recovery.restore_budget(\n                daily=target_daily_budget,\n                monthly=target_daily_budget * 30,\n            )\n            return {\n                \"success\": True,\n                \"budget_restored\": target_daily_budget,\n                \"data\": result,\n            }\n        except Exception as exc:\n            return {\"success\": False, \"error\": str(exc)}\n\n    def post_recovery_service_rating(\n        self, service_id: str, rating: int = 3, comment: str = \"\",\n    ) -> dict:\n        \"\"\"Submit a post-incident service rating.\n\n        Uses IncidentRecovery.rate_agent_service to record a neutral\n        rating that reflects the recovery, not the incident.\n        \"\"\"\n        try:\n            result = self._recovery.rate_agent_service(\n                service_id=service_id,\n                rating=rating,\n                comment=comment or \"Service restored after incident containment.\",\n            )\n            return {\"success\": True, \"data\": result}\n        except Exception as exc:\n            return {\"success\": False, \"error\": str(exc)}\n\n\n# ── 4. Forensic Evidence Collection ──────────────────────────────────────────\n\nclass ForensicCollector:\n    \"\"\"Collect and assemble forensic evidence for post-mortem analysis.\n\n    Uses:\n        IncidentForensics.get_audit_trail()  -- claim chains\n        IncidentForensics.get_verified_claims()  -- individual claims\n        IncidentForensics.assess_impact()  -- financial impact\n        IncidentForensics.build_timeline()  -- event reconstruction\n    \"\"\"\n\n    def __init__(self, api_key: str, agent_id: str):\n        self.agent_id = agent_id\n        self._forensics = IncidentForensics(\n            api_key=api_key,\n            agent_id=agent_id,\n        )\n\n    def collect_audit_trail(self) -> dict:\n        \"\"\"Extract the cryptographic audit trail (claim chains).\n\n        IncidentForensics.get_audit_trail wraps get_claim_chains to\n        retrieve the tamper-proof record of all agent actions.\n        \"\"\"\n        return self._forensics.get_audit_trail()\n\n    def collect_verified_claims(self) -> dict:\n        \"\"\"Retrieve individually verifiable claims.\n\n        IncidentForensics.get_verified_claims wraps get_verified_claims\n        for Merkle-proof-verifiable claim records.\n        \"\"\"\n        return self._forensics.get_verified_claims()\n\n    def assess_financial_impact(self) -> dict:\n        \"\"\"Calculate the financial impact of the incident.\n\n        IncidentForensics.assess_impact pulls usage analytics, billing\n        summary, and spending-by-category to compute total incident cost.\n        \"\"\"\n        return self._forensics.assess_impact()\n\n    def reconstruct_timeline(self) -> dict:\n        \"\"\"Reconstruct the incident timeline from claim chains and\n        usage analytics.\n\n        IncidentForensics.build_timeline combines claim chain data with\n        7-day usage analytics into a chronological event sequence.\n        \"\"\"\n        return self._forensics.build_timeline()\n\n    def run_full_post_mortem(\n        self,\n        incident_record: IncidentRecord,\n    ) -> dict:\n        \"\"\"Assemble a complete post-mortem report.\n\n        Combines audit trail, verified claims, financial impact, and\n        timeline into a single structured report suitable for both\n        human review and machine ingestion.\n        \"\"\"\n        audit_trail = self.collect_audit_trail()\n        verified_claims = self.collect_verified_claims()\n        impact = self.assess_financial_impact()\n        timeline = self.reconstruct_timeline()\n\n        report = {\n            \"incident_id\": incident_record.incident_id,\n            \"agent_id\": incident_record.agent_id,\n            \"severity\": incident_record.severity,\n            \"generated_at\": int(time.time()),\n            \"timing\": {\n                \"detected_at\": incident_record.detected_at,\n                \"contained_at\": incident_record.contained_at,\n                \"recovered_at\": incident_record.recovered_at,\n                \"detection_to_containment_s\": incident_record.elapsed_to_containment(),\n                \"detection_to_recovery_s\": incident_record.elapsed_to_recovery(),\n                \"met_60s_containment_sla\": (\n                    incident_record.elapsed_to_containment() is not None\n                    and incident_record.elapsed_to_containment() \u003C= 60.0\n                ),\n            },\n            \"audit_trail\": audit_trail,\n            \"verified_claims\": verified_claims,\n            \"financial_impact\": impact,\n            \"timeline\": timeline,\n            \"detection_signals\": incident_record.detection_signals,\n            \"containment_actions\": incident_record.containment_results,\n            \"recovery_actions\": incident_record.recovery_results,\n        }\n\n        return report\n\n\n# ── 5. End-to-End Incident Orchestrator ──────────────────────────────────────\n\nclass IncidentOrchestrator:\n    \"\"\"Ties detection, containment, recovery, and forensics into a\n    single automated response pipeline.\n\n    Usage:\n        orchestrator = IncidentOrchestrator(\n            api_key=API_KEY,\n            agent_id=AGENT_ID,\n            target_daily_budget=500.0,\n        )\n        orchestrator.setup(webhook_url=WEBHOOK_URL)\n        orchestrator.run(max_cycles=100, interval_seconds=30)\n    \"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        target_daily_budget: float = 500.0,\n        cost_threshold: float = 500.0,\n        reputation_threshold: float = 0.1,\n        baseline_reputation: float = 0.85,\n    ):\n        self.agent_id = agent_id\n        self.target_daily_budget = target_daily_budget\n        self._pipeline = AnomalyPipeline(\n            api_key=api_key,\n            agent_id=agent_id,\n            cost_threshold=cost_threshold,\n            reputation_threshold=reputation_threshold,\n            baseline_reputation=baseline_reputation,\n        )\n        self._containment = AutoContainment(\n            api_key=api_key, agent_id=agent_id,\n        )\n        self._recovery = GuidedRecovery(\n            api_key=api_key, agent_id=agent_id,\n        )\n        self._forensics = ForensicCollector(\n            api_key=api_key, agent_id=agent_id,\n        )\n        self._incidents: list[IncidentRecord] = []\n        self._active_incident: Optional[IncidentRecord] = None\n\n    def setup(self, webhook_url: str) -> dict:\n        \"\"\"Configure webhook alerts for persistent monitoring.\"\"\"\n        return self._pipeline.setup_webhook_alerts(webhook_url)\n\n    def handle_anomaly(self, cycle_result: dict):\n        \"\"\"Called when the anomaly pipeline detects a non-clear signal.\n\n        If severity is \"critical\", immediately contain. If \"warning\",\n        log and wait for escalation on the next cycle.\n        \"\"\"\n        severity = cycle_result[\"severity\"]\n        trigger = \", \".join(\n            s[\"signal\"] for s in cycle_result[\"signals\"] if s[\"triggered\"]\n        )\n\n        if severity == \"critical\" and self._active_incident is None:\n            # Create incident record\n            incident = IncidentRecord(\n                incident_id=f\"inc-{int(time.time())}\",\n                agent_id=self.agent_id,\n                severity=severity,\n                detection_signals=cycle_result[\"signals\"],\n            )\n\n            # Execute containment\n            print(f\"[CRITICAL] Containing agent {self.agent_id}...\")\n            containment_results = self._containment.contain(\n                severity=severity,\n                trigger_signal=trigger,\n            )\n            incident.containment_results = containment_results\n            incident.contained_at = time.time()\n\n            elapsed = incident.elapsed_to_containment()\n            met_sla = elapsed is not None and elapsed \u003C= 60.0\n            print(\n                f\"  Containment complete in {elapsed}s \"\n                f\"({'MET' if met_sla else 'MISSED'} 60s SLA)\"\n            )\n\n            self._active_incident = incident\n\n        elif severity == \"warning\":\n            print(\n                f\"[WARNING] Agent {self.agent_id}: \"\n                f\"signals={trigger}. Monitoring.\"\n            )\n\n    def recover_active_incident(self) -> Optional[dict]:\n        \"\"\"Recover from the active incident if one exists.\n\n        Executes the guided recovery sequence and then runs forensics.\n        \"\"\"\n        if self._active_incident is None:\n            return None\n\n        incident = self._active_incident\n\n        # Recovery\n        print(f\"[RECOVERY] Recovering agent {self.agent_id}...\")\n        recovery_results = self._recovery.execute_recovery(\n            target_daily_budget=self.target_daily_budget,\n            initial_pct=50,\n            incident_id=incident.incident_id,\n        )\n        incident.recovery_results = recovery_results\n        incident.recovered_at = time.time()\n\n        # Forensics\n        print(f\"[FORENSICS] Collecting evidence for {incident.incident_id}...\")\n        forensics_report = self._forensics.run_full_post_mortem(incident)\n        incident.forensics_report = forensics_report\n\n        # Archive and clear\n        self._incidents.append(incident)\n        self._active_incident = None\n\n        print(\n            f\"  Recovery complete. Total incident duration: \"\n            f\"{incident.elapsed_to_recovery()}s\"\n        )\n\n        return incident.to_dict()\n\n    def run(\n        self,\n        max_cycles: Optional[int] = None,\n        interval_seconds: int = 30,\n    ):\n        \"\"\"Run the full detection-containment-recovery loop.\n\n        Monitors continuously. On critical anomaly, contains\n        automatically. Call recover_active_incident() after the root\n        cause is fixed to complete the cycle.\n        \"\"\"\n        self._pipeline.run_continuous_monitoring(\n            interval_seconds=interval_seconds,\n            max_cycles=max_cycles,\n            on_anomaly=self.handle_anomaly,\n        )\n\n    def get_incident_history(self) -> list[dict]:\n        return [inc.to_dict() for inc in self._incidents]\n\n\n# ── Main: Run the Full Pipeline ──────────────────────────────────────────────\n\nif __name__ == \"__main__\":\n\n    print(\"=\" * 72)\n    print(\"GreenHelix Automated Incident Detection & Escalation\")\n    print(\"=\" * 72)\n\n    orchestrator = IncidentOrchestrator(\n        api_key=API_KEY,\n        agent_id=AGENT_ID,\n        target_daily_budget=500.0,\n        cost_threshold=500.0,\n        reputation_threshold=0.1,\n        baseline_reputation=0.85,\n    )\n\n    # Step 1: Setup webhook alerts\n    print(\"\\n[1\u002F4] Setting up webhook alerts...\")\n    setup_result = orchestrator.setup(webhook_url=WEBHOOK_URL)\n    print(f\"  Webhooks configured: {setup_result['status']}\")\n\n    # Step 2: Run a single detection cycle (demo mode)\n    print(\"\\n[2\u002F4] Running detection cycle...\")\n    pipeline = orchestrator._pipeline\n    cycle = pipeline.run_detection_cycle()\n    print(f\"  Severity: {cycle['severity']}\")\n    print(f\"  Triggered signals: {cycle['triggered_signals']}\")\n    for signal in cycle[\"signals\"]:\n        status = \"TRIGGERED\" if signal[\"triggered\"] else \"clear\"\n        print(f\"    {signal['signal']}: {status}\")\n\n    # Step 3: Demo containment (only if you want to freeze the agent)\n    print(\"\\n[3\u002F4] Containment ready (not triggered in demo mode)\")\n    print(\"  To trigger: set cost_threshold low or run against a spending agent\")\n\n    # Step 4: Demo forensics collection\n    print(\"\\n[4\u002F4] Collecting forensic evidence...\")\n    forensics = ForensicCollector(api_key=API_KEY, agent_id=AGENT_ID)\n\n    audit = forensics.collect_audit_trail()\n    print(f\"  Audit trail chains: {len(audit.get('chains', []))}\")\n\n    claims = forensics.collect_verified_claims()\n    print(f\"  Verified claims: {len(claims.get('claims', []))}\")\n\n    impact = forensics.assess_financial_impact()\n    print(f\"  Usage data collected: {bool(impact.get('usage'))}\")\n    print(f\"  Billing data collected: {bool(impact.get('billing'))}\")\n\n    timeline = forensics.reconstruct_timeline()\n    print(f\"  Timeline period: {timeline.get('period', 'N\u002FA')}\")\n\n    print(\"\\n\" + \"=\" * 72)\n    print(\"Incident response system ready.\")\n    print(\"Run orchestrator.run() for continuous monitoring.\")\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],"incident-response","runbooks","agent-ops","containment","forensics","commerce","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-incident-response","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-incident-response",{"tool":61,"command":62},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-incident-response",{"tool":64,"command":65},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-incident-response","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-incident-response\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",[],[]]