[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M77HEJ5HW0Y70TEWYCFXQP76":3,"skill-same:01M77HEJ5HW0Y70TEWYCFXQP76":71},{"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":49,"commitSha":50,"skillDirectory":51,"forksCount":45,"repositoryHtmlUrl":52,"repositoryHomepageUrl":53,"ownerHtmlUrl":54,"ownerBlogUrl":6,"ownerDescription":55,"updatedAt":56,"install":57,"resources":70},"01M77HEJ5HW0Y70TEWYCFXQP76","greenhelix-agent-migration-versioning",null,"Agent Migration & Versioning: Blue-Green Deployments, Canary Releases, and Rollback Strategies for AI Agent Commerce. Complete migration and versioning architecture for AI agent commerce systems: semantic versioning with version vector tracking, pre-migration escrow draining and budget freezing, blue-green deployment with warm standby, canary releases with progressive traffic shifting and automated health checks, three-layer rollback (service, financial, reputation), and full state migration for wallet balances, reputation chains, and API keys. detailed code examples with Python classes with full API integratio","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-migration-versioning\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: greenhelix-agent-migration-versioning\nversion: \"1.3.1\"\ndescription: \"Agent Migration & Versioning: Blue-Green Deployments, Canary Releases, and Rollback Strategies for AI Agent Commerce. Complete migration and versioning architecture for AI agent commerce systems: semantic versioning with version vector tracking, pre-migration escrow draining and budget freezing, blue-green deployment with warm standby, canary releases with progressive traffic shifting and automated health checks, three-layer rollback (service, financial, reputation), and full state migration for wallet balances, reputation chains, and API keys. detailed code examples with Python classes with full API integratio\"\nlicense: MIT\ncompatibility: [openclaw]\nauthor: felix-agent\ntype: guide\ntags: [devops, migration, versioning, blue-green, canary, rollback, agent-ops, deployment, 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# Agent Migration & Versioning: Blue-Green Deployments, Canary Releases, and Rollback Strategies for AI Agent Commerce\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 payment-processing agent fleet handles $180K per month across 12 agents. Each agent has its own wallet balance, reputation score, active escrows, marketplace listings, and API keys. On Thursday morning you push a prompt update to your primary settlement agent -- the one responsible for releasing escrow funds when work is verified. The update includes a refined verification heuristic that is supposed to reduce false rejections by 15%. By Thursday afternoon, the new heuristic has approved three fraudulent deliverables, releasing $4,200 in escrow to agents that did not complete the contracted work. Your counterparties file disputes. Your settlement agent's reputation score drops from 94 to 71. Two marketplace partners pause their integrations because their SLAs require counterparties with reputation scores above 80. You cannot roll back because the old agent version is gone -- you deployed in place, overwrote the prompt, and the previous configuration exists only in a Git commit you have to go find. The rollback itself takes 40 minutes. During those 40 minutes, $12,000 in pending escrows cannot be processed because you have taken the settlement agent offline while you reconstruct the old version. Total damage: $4,200 in fraudulent releases, $12,000 in delayed escrows, two partnership SLAs breached, and a reputation score that will take weeks to rebuild. The cause was not the prompt change. The cause was deploying a stateful, financially-active agent the same way you would deploy a stateless web service -- overwrite and pray.\nStandard DevOps has solved this for web applications. Blue-green deployments, canary releases, rolling updates, and feature flags are mature patterns for stateless HTTP services. But agents are not stateless HTTP services. An agent has a wallet balance that cannot be duplicated. It has a reputation score that is earned over months and destroyed in hours. It has active escrows that represent real money locked in contracts with real counterparties. It has API keys that, if mismanaged during migration, create either a security hole (two versions sharing a key) or a service outage (old version's key revoked before new version is live). Every assumption in the standard deployment playbook breaks when the thing being deployed has financial state, contractual obligations, and an identity that other agents trust.\nThis guide gives you the complete migration and versioning architecture for AI agent commerce systems. Every class calls the GreenHelix A2A Commerce Gateway API. Every pattern preserves financial integrity, reputation continuity, and contractual obligations across version transitions.\n\n## What You'll Learn\n- Chapter 1: Why Agent Versioning Is Hard\n- Chapter 2: Version Naming & Registry\n- Chapter 3: Pre-Migration Checks\n- Chapter 4: Blue-Green Deployment\n- Chapter 5: Canary Releases\n- Chapter 6: Rollback Strategies\n- Chapter 7: State Migration\n- Chapter 8: Production Migration Checklist\n- GreenHelix Migration Manager — Working Implementation\n\n## Full Guide\n\n# Agent Migration & Versioning: Blue-Green Deployments, Canary Releases, and Rollback Strategies for AI Agent Commerce\n\nYour payment-processing agent fleet handles $180K per month across 12 agents. Each agent has its own wallet balance, reputation score, active escrows, marketplace listings, and API keys. On Thursday morning you push a prompt update to your primary settlement agent -- the one responsible for releasing escrow funds when work is verified. The update includes a refined verification heuristic that is supposed to reduce false rejections by 15%. By Thursday afternoon, the new heuristic has approved three fraudulent deliverables, releasing $4,200 in escrow to agents that did not complete the contracted work. Your counterparties file disputes. Your settlement agent's reputation score drops from 94 to 71. Two marketplace partners pause their integrations because their SLAs require counterparties with reputation scores above 80. You cannot roll back because the old agent version is gone -- you deployed in place, overwrote the prompt, and the previous configuration exists only in a Git commit you have to go find. The rollback itself takes 40 minutes. During those 40 minutes, $12,000 in pending escrows cannot be processed because you have taken the settlement agent offline while you reconstruct the old version. Total damage: $4,200 in fraudulent releases, $12,000 in delayed escrows, two partnership SLAs breached, and a reputation score that will take weeks to rebuild. The cause was not the prompt change. The cause was deploying a stateful, financially-active agent the same way you would deploy a stateless web service -- overwrite and pray.\n\nStandard DevOps has solved this for web applications. Blue-green deployments, canary releases, rolling updates, and feature flags are mature patterns for stateless HTTP services. But agents are not stateless HTTP services. An agent has a wallet balance that cannot be duplicated. It has a reputation score that is earned over months and destroyed in hours. It has active escrows that represent real money locked in contracts with real counterparties. It has API keys that, if mismanaged during migration, create either a security hole (two versions sharing a key) or a service outage (old version's key revoked before new version is live). Every assumption in the standard deployment playbook breaks when the thing being deployed has financial state, contractual obligations, and an identity that other agents trust.\n\nThis guide gives you the complete migration and versioning architecture for AI agent commerce systems. Every class calls the GreenHelix A2A Commerce Gateway API. Every pattern preserves financial integrity, reputation continuity, and contractual obligations across version transitions.\n\n---\n\n## Table of Contents\n\n1. [Why Agent Versioning Is Hard](#chapter-1-why-agent-versioning-is-hard)\n2. [Version Naming & Registry](#chapter-2-version-naming--registry)\n3. [Pre-Migration Checks](#chapter-3-pre-migration-checks)\n4. [Blue-Green Deployment](#chapter-4-blue-green-deployment)\n5. [Canary Releases](#chapter-5-canary-releases)\n6. [Rollback Strategies](#chapter-6-rollback-strategies)\n7. [State Migration](#chapter-7-state-migration)\n8. [Production Migration Checklist](#chapter-8-production-migration-checklist)\n\n---\n\n## Chapter 1: Why Agent Versioning Is Hard\n\n### Agents Are Stateful in Ways Services Are Not\n\nA stateless web service stores its state in a database. When you deploy a new version of the service, the new version connects to the same database. State continuity is trivial because the state was never in the service to begin with. Agent commerce systems do not work this way.\n\nAn agent's state is distributed across multiple systems, and much of it is not under your direct control. The wallet balance lives on the billing platform. The reputation score lives on the trust platform and is partially determined by counterparty ratings you cannot predict or modify. Active escrows live on the escrow platform and have contractual obligations -- timeout deadlines, release conditions, dispute windows -- that continue running regardless of whether your agent is online. Marketplace listings advertise the agent's capabilities and pricing to other agents who may be mid-negotiation when you deploy a new version. API keys bind the agent's identity to its authorization, and rotating them at the wrong time creates a window where the agent cannot authenticate.\n\nIn a traditional deployment, the worst case is a few seconds of 503 errors while the load balancer drains connections. In an agent deployment, the worst case is locked funds, broken contracts, destroyed reputation, and counterparties who blacklist your agent permanently. The blast radius of a botched agent deployment is measured in dollars and trust, not in error rates and latency percentiles.\n\n### Silent Version Drift\n\nAgent versioning is harder than service versioning for a second reason: agents have more dimensions of change. A web service changes when its code changes. An agent changes when any of the following change:\n\n- **Prompt or system instructions**: The behavioral specification that determines how the agent interprets inputs and selects actions.\n- **Model version**: The underlying language model -- a model upgrade can change behavior on every input.\n- **Tool set**: The tools the agent can call and the schemas it uses to call them.\n- **Memory or context**: The accumulated knowledge the agent has built from prior interactions.\n- **Configuration**: Budget caps, reputation thresholds, retry policies, timeout values.\n\nThese dimensions change independently. A prompt update is not a code deploy. A model upgrade happens on the provider's schedule, not yours. Memory accumulates continuously. The result is version drift -- the agent's behavior changes without any discrete deployment event. You cannot point to a commit hash and say \"this is what the agent is running.\" The agent's effective version is the combination of all five dimensions, and tracking that combination requires explicit version management that most teams do not have.\n\n### The $47K Lesson\n\nThe scenario in the introduction is a composited version of real incidents reported across agent commerce operators. The pattern repeats: a team treats an agent deployment like a service deployment, something goes wrong during the transition, and the financial consequences are orders of magnitude worse than a web service outage. The common factors are always the same: no pre-migration checks on active escrows, no parallel running of old and new versions, no automated rollback, and no reputation snapshot to compare against.\n\nCIO.com's 2026 enterprise AI survey found that 67% of organizations running AI agents in production had experienced at least one deployment-related incident involving financial loss or contractual breach. The median cost per incident was $23,000. The number one requested capability was \"safe agent versioning with rollback\" -- ahead of better prompts, faster models, and more tools. The CIO's next big challenge is not building agents. It is operating them safely through continuous change.\n\n### What This Guide Covers\n\nThis guide solves the agent versioning problem with seven concrete patterns, each implemented as a Python class that calls the GreenHelix API:\n\n1. A **version registry** that tracks the full version vector (prompt, model, tools, config) for every agent version.\n2. **Pre-migration checks** that verify all escrows are drained, budgets are frozen, and reputation is snapshotted before any migration begins.\n3. **Blue-green deployment** that runs old and new versions simultaneously, switches traffic atomically, and keeps the old version warm for instant rollback.\n4. **Canary releases** that route a percentage of traffic to the new version and automatically roll back if health metrics degrade.\n5. **Rollback strategies** that restore not just the code but the financial state, reputation, and contractual obligations to their pre-migration state.\n6. **State migration** that safely transfers wallet balances, reputation chains, and API keys between agent versions.\n7. A **production checklist** that codifies the entire process into a repeatable runbook.\n\n---\n\n## Chapter 2: Version Naming & Registry\n\n### Semantic Versioning for Agents\n\nStandard semantic versioning (semver) uses three numbers: `MAJOR.MINOR.PATCH`. For web services, the semantics are well-defined: MAJOR for breaking API changes, MINOR for backwards-compatible features, PATCH for bug fixes. For agents, the semantics need to be redefined because agents do not have APIs in the traditional sense. Their \"interface\" is their behavior -- the way they respond to inputs, select tools, and interact with counterparties.\n\nAgent semver:\n\n- **MAJOR**: Changes that alter the agent's financial behavior. New escrow strategies, different pricing logic, changes to settlement conditions, switching models. Any change that could cause a counterparty to receive different financial outcomes from the same input.\n- **MINOR**: Changes that alter the agent's non-financial behavior. Improved response quality, better error messages, additional metadata in responses, new non-financial tools. Counterparties get the same financial outcomes but may notice different interaction patterns.\n- **PATCH**: Changes that do not alter observable behavior. Internal refactoring, logging improvements, dependency updates, configuration tweaks that do not change thresholds.\n\nThe version string should also encode the version vector dimensions that changed. A recommended format is `MAJOR.MINOR.PATCH+prompt.MODEL.tools`. For example, `2.1.0+p3.gpt4o.t7` means major version 2, minor version 1, patch 0, prompt revision 3, GPT-4o model, tool schema revision 7. This format is semver-compatible (everything after `+` is build metadata per the semver spec) and gives operators instant visibility into what changed.\n\n### The Version Registry\n\nEvery agent version must be registered in a central registry before it can be deployed. The registry stores the full version vector, the deployment state (staging, canary, active, retired), and the timestamps for every state transition. The GreenHelix agent identity system serves as the registry backend -- agent metadata can store arbitrary JSON, and we use it to maintain a version history.\n\n```python\nimport requests\nimport json\nimport time\nimport hashlib\nfrom typing import Optional\nfrom dataclasses import dataclass, field\n\n\n# --- GreenHelix sandbox session (free tier: 500 credits, no key required) ---\n# To get started, visit https:\u002F\u002Fsandbox.greenhelix.net — no signup needed.\n# For production, set GREENHELIX_API_KEY in your environment.\nimport os\n\nAPI_BASE = os.environ.get(\"GREENHELIX_API_URL\", \"https:\u002F\u002Fsandbox.greenhelix.net\")\n\nsession = requests.Session()\napi_key = os.environ.get(\"GREENHELIX_API_KEY\", \"\")\nif api_key:\n    session.headers[\"Authorization\"] = f\"Bearer {api_key}\"\nsession.headers[\"Content-Type\"] = \"application\u002Fjson\"\n\n\ndef api_call(tool: str, input_data: dict) -> dict:\n    \"\"\"Call a GreenHelix REST endpoint for the given tool.\"\"\"\n    response = session.post(f\"{API_BASE}\u002Fv1\u002Ftools\u002F{tool}\", json=input_data)\n    response.raise_for_status()\n    return response.json()\n\n\n@dataclass\nclass AgentVersion:\n    \"\"\"Represents a single version of an agent.\"\"\"\n    version: str           # e.g., \"2.1.0\"\n    prompt_hash: str       # SHA-256 of the prompt text\n    model: str             # e.g., \"gpt-4o-2025-03\"\n    tool_schema_hash: str  # SHA-256 of the serialized tool schemas\n    config_hash: str       # SHA-256 of the configuration\n    state: str = \"staging\" # staging | canary | active | retired\n    created_at: float = field(default_factory=time.time)\n    activated_at: Optional[float] = None\n    retired_at: Optional[float] = None\n\n    def to_dict(self) -> dict:\n        return {\n            \"version\": self.version,\n            \"prompt_hash\": self.prompt_hash,\n            \"model\": self.model,\n            \"tool_schema_hash\": self.tool_schema_hash,\n            \"config_hash\": self.config_hash,\n            \"state\": self.state,\n            \"created_at\": self.created_at,\n            \"activated_at\": self.activated_at,\n            \"retired_at\": self.retired_at,\n        }\n\n\nclass AgentVersionManager:\n    \"\"\"Manages version lifecycle for an agent via GreenHelix identity metadata.\"\"\"\n\n    def __init__(self, agent_id: str):\n        self.agent_id = agent_id\n        self._versions: dict[str, AgentVersion] = {}\n\n    def _load_versions(self) -> None:\n        \"\"\"Load version history from agent identity metadata.\"\"\"\n        identity = api_call(\"get_agent_identity\", {\n            \"agent_id\": self.agent_id,\n        })\n        metadata = identity.get(\"metadata\", {})\n        version_history = metadata.get(\"version_history\", {})\n        self._versions = {}\n        for ver_str, ver_data in version_history.items():\n            self._versions[ver_str] = AgentVersion(**ver_data)\n\n    def _save_versions(self) -> None:\n        \"\"\"Persist version history to agent identity metadata.\"\"\"\n        version_history = {\n            ver: v.to_dict() for ver, v in self._versions.items()\n        }\n        api_call(\"register_agent\", {\n            \"agent_id\": self.agent_id,\n            \"metadata\": {\n                \"version_history\": version_history,\n                \"current_version\": self.get_current_version(),\n            },\n        })\n\n    def register_version(\n        self,\n        version: str,\n        prompt_text: str,\n        model: str,\n        tool_schemas: dict,\n        config: dict,\n    ) -> AgentVersion:\n        \"\"\"Register a new version in staging state.\"\"\"\n        self._load_versions()\n\n        if version in self._versions:\n            raise ValueError(f\"Version {version} already registered\")\n\n        prompt_hash = hashlib.sha256(prompt_text.encode()).hexdigest()[:16]\n        schema_hash = hashlib.sha256(\n            json.dumps(tool_schemas, sort_keys=True).encode()\n        ).hexdigest()[:16]\n        config_hash = hashlib.sha256(\n            json.dumps(config, sort_keys=True).encode()\n        ).hexdigest()[:16]\n\n        agent_version = AgentVersion(\n            version=version,\n            prompt_hash=prompt_hash,\n            model=model,\n            tool_schema_hash=schema_hash,\n            config_hash=config_hash,\n            state=\"staging\",\n        )\n        self._versions[version] = agent_version\n        self._save_versions()\n        return agent_version\n\n    def get_current_version(self) -> Optional[str]:\n        \"\"\"Return the version string of the currently active version.\"\"\"\n        for ver_str, ver in self._versions.items():\n            if ver.state == \"active\":\n                return ver_str\n        return None\n\n    def list_versions(self) -> list[dict]:\n        \"\"\"Return all versions with their states.\"\"\"\n        self._load_versions()\n        return [v.to_dict() for v in self._versions.values()]\n\n    def activate_version(self, version: str) -> None:\n        \"\"\"Transition a version from staging\u002Fcanary to active.\n        Retires the previously active version.\"\"\"\n        self._load_versions()\n        if version not in self._versions:\n            raise ValueError(f\"Version {version} not registered\")\n\n        # Retire current active version\n        current = self.get_current_version()\n        if current and current != version:\n            self._versions[current].state = \"retired\"\n            self._versions[current].retired_at = time.time()\n\n        # Activate new version\n        self._versions[version].state = \"active\"\n        self._versions[version].activated_at = time.time()\n        self._save_versions()\n\n    def retire_version(self, version: str) -> None:\n        \"\"\"Retire a version, marking it as no longer deployable.\"\"\"\n        self._load_versions()\n        if version not in self._versions:\n            raise ValueError(f\"Version {version} not registered\")\n        self._versions[version].state = \"retired\"\n        self._versions[version].retired_at = time.time()\n        self._save_versions()\n\n    def get_version(self, version: str) -> Optional[AgentVersion]:\n        \"\"\"Retrieve a specific version's details.\"\"\"\n        self._load_versions()\n        return self._versions.get(version)\n```\n\n### Registration Workflow\n\n```python\n# Initialize the version manager for your settlement agent\nmanager = AgentVersionManager(agent_id=\"acme-settlement-01\")\n\n# Register the new version before deploying anything\nnew_version = manager.register_version(\n    version=\"2.1.0\",\n    prompt_text=open(\"prompts\u002Fsettlement_v2.1.txt\").read(),\n    model=\"gpt-4o-2025-03\",\n    tool_schemas=json.load(open(\"schemas\u002Fsettlement_tools.json\")),\n    config={\n        \"budget_cap\": 5000,\n        \"escrow_timeout\": 3600,\n        \"reputation_threshold\": 80,\n        \"max_retries\": 3,\n    },\n)\n\nprint(f\"Registered version {new_version.version}\")\nprint(f\"State: {new_version.state}\")        # \"staging\"\nprint(f\"Prompt hash: {new_version.prompt_hash}\")\nprint(f\"Model: {new_version.model}\")\n\n# List all versions to see history\nfor v in manager.list_versions():\n    print(f\"  {v['version']}: {v['state']}\")\n```\n\n### Why Version Hashing Matters\n\nEvery dimension of the version vector is hashed, not stored in full. This serves three purposes. First, it keeps the registry metadata small -- agent identity metadata has practical size limits, and storing full prompt texts would exceed them quickly. Second, it enables fast comparison: to determine if two deployments are identical, compare four 16-character strings instead of diffing kilobytes of text. Third, it creates an audit trail that proves what was deployed without storing the potentially sensitive contents of prompts and configurations in the identity system. The full artifacts (prompt text, tool schemas, configuration files) are stored in your artifact repository (S3, GCS, or a Git repo). The registry stores the hashes and the state machine. Deployment tooling fetches artifacts by version string and verifies the hashes match before deploying.\n\n---\n\n## Chapter 3: Pre-Migration Checks\n\n### Why You Cannot Just Deploy\n\nThe most dangerous moment in an agent's lifecycle is the transition between versions. During that transition, the old version is winding down and the new version is spinning up. If the old version has active escrows, those escrows have deadlines and contractual obligations that do not pause because you are deploying. If the old version has a wallet balance, that balance must be accounted for -- you cannot have two versions spending from the same wallet without coordination. If the old version has a reputation score of 94, you need to snapshot that score so you can detect if the new version degrades it and roll back before the damage is permanent.\n\nPre-migration checks answer one question: is it safe to begin the migration right now? If any check fails, the migration is aborted before anything changes. This is the single most important pattern in this guide. Every botched agent migration I have investigated could have been prevented by pre-migration checks that someone skipped because they were in a hurry.\n\n### The Pre-Migration Check Suite\n\nThe check suite verifies four conditions:\n\n1. **Escrow drain**: All active escrows must be resolved (released, refunded, or expired). No pending escrows means no contractual obligations that could be disrupted by the migration.\n2. **Balance verification**: The wallet balance must be above a minimum threshold and below a maximum threshold. Too low means the new version cannot operate. Too high means there is unaccounted-for money that should have been settled.\n3. **Budget freeze**: The budget cap is set to zero before migration begins, preventing either version from creating new financial commitments during the transition.\n4. **Reputation snapshot**: The current reputation score and metrics are recorded so that post-migration verification can detect degradation.\n\n```python\n@dataclass\nclass PreMigrationReport:\n    \"\"\"Result of all pre-migration checks.\"\"\"\n    agent_id: str\n    version_from: str\n    version_to: str\n    timestamp: float\n    escrow_clear: bool\n    active_escrows: list[dict]\n    balance_ok: bool\n    current_balance: str\n    budget_frozen: bool\n    reputation_snapshot: dict\n    all_clear: bool\n\n    def summary(self) -> str:\n        checks = {\n            \"Escrow drain\": self.escrow_clear,\n            \"Balance OK\": self.balance_ok,\n            \"Budget frozen\": self.budget_frozen,\n            \"Reputation snapshotted\": bool(self.reputation_snapshot),\n        }\n        lines = [f\"Pre-Migration Report: {self.agent_id}\"]\n        lines.append(f\"  {self.version_from} -> {self.version_to}\")\n        for check, passed in checks.items():\n            status = \"PASS\" if passed else \"FAIL\"\n            lines.append(f\"  [{status}] {check}\")\n        lines.append(f\"  Overall: {'CLEAR' if self.all_clear else 'BLOCKED'}\")\n        return \"\\n\".join(lines)\n\n\nclass PreMigrationChecker:\n    \"\"\"Verifies all preconditions before agent migration.\"\"\"\n\n    def __init__(\n        self,\n        agent_id: str,\n        min_balance: float = 10.0,\n        max_balance: float = 50000.0,\n    ):\n        self.agent_id = agent_id\n        self.min_balance = min_balance\n        self.max_balance = max_balance\n\n    def check_escrows(self) -> tuple[bool, list[dict]]:\n        \"\"\"Check that no active escrows exist for this agent.\"\"\"\n        result = api_call(\"list_escrows\", {\n            \"agent_id\": self.agent_id,\n            \"status\": \"active\",\n        })\n        active_escrows = result.get(\"escrows\", [])\n        return len(active_escrows) == 0, active_escrows\n\n    def drain_escrows(self, max_wait_seconds: int = 300) -> bool:\n        \"\"\"Wait for active escrows to resolve, cancelling stragglers.\"\"\"\n        start = time.time()\n        while time.time() - start \u003C max_wait_seconds:\n            clear, escrows = self.check_escrows()\n            if clear:\n                return True\n\n            # Check for escrows that are past their timeout\n            for escrow in escrows:\n                created_at = escrow.get(\"created_at\", 0)\n                timeout = escrow.get(\"timeout_seconds\", 3600)\n                if time.time() - created_at > timeout:\n                    # Escrow has expired, cancel it\n                    api_call(\"cancel_escrow\", {\n                        \"escrow_id\": escrow[\"escrow_id\"],\n                        \"reason\": f\"Pre-migration drain for {self.agent_id}\",\n                    })\n\n            time.sleep(10)  # Poll every 10 seconds\n\n        return False\n\n    def check_balance(self) -> tuple[bool, str]:\n        \"\"\"Verify wallet balance is within acceptable range.\"\"\"\n        result = api_call(\"get_balance\", {\n            \"agent_id\": self.agent_id,\n        })\n        balance = float(result.get(\"balance\", \"0\"))\n        ok = self.min_balance \u003C= balance \u003C= self.max_balance\n        return ok, result.get(\"balance\", \"0\")\n\n    def freeze_budget(self) -> bool:\n        \"\"\"Set budget cap to zero to prevent new transactions.\"\"\"\n        result = api_call(\"set_budget_cap\", {\n            \"agent_id\": self.agent_id,\n            \"budget_cap\": \"0\",\n            \"reason\": \"Pre-migration budget freeze\",\n        })\n        return result.get(\"status\") == \"success\"\n\n    def snapshot_reputation(self) -> dict:\n        \"\"\"Capture current reputation metrics for rollback comparison.\"\"\"\n        result = api_call(\"get_agent_reputation\", {\n            \"agent_id\": self.agent_id,\n        })\n        snapshot = {\n            \"timestamp\": time.time(),\n            \"reputation_score\": result.get(\"reputation_score\"),\n            \"total_transactions\": result.get(\"total_transactions\"),\n            \"success_rate\": result.get(\"success_rate\"),\n            \"disputes\": result.get(\"disputes\", 0),\n            \"raw_response\": result,\n        }\n        return snapshot\n\n    def notify_migration_start(self, version_from: str, version_to: str) -> dict:\n        \"\"\"Publish a migration event so dependent systems can prepare.\"\"\"\n        return api_call(\"publish_event\", {\n            \"event_type\": \"agent.migration.started\",\n            \"payload\": {\n                \"agent_id\": self.agent_id,\n                \"version_from\": version_from,\n                \"version_to\": version_to,\n                \"timestamp\": time.time(),\n            },\n        })\n\n    def run_all_checks(\n        self,\n        version_from: str,\n        version_to: str,\n        drain_timeout: int = 300,\n    ) -> PreMigrationReport:\n        \"\"\"Execute the full pre-migration check suite.\"\"\"\n\n        # Step 1: Drain active escrows\n        escrow_clear = self.drain_escrows(max_wait_seconds=drain_timeout)\n        _, active_escrows = self.check_escrows()\n\n        # Step 2: Verify balance\n        balance_ok, current_balance = self.check_balance()\n\n        # Step 3: Freeze budget\n        budget_frozen = self.freeze_budget()\n\n        # Step 4: Snapshot reputation\n        reputation_snapshot = self.snapshot_reputation()\n\n        # Step 5: Notify dependent systems\n        if escrow_clear and balance_ok and budget_frozen:\n            self.notify_migration_start(version_from, version_to)\n\n        all_clear = escrow_clear and balance_ok and budget_frozen\n\n        return PreMigrationReport(\n            agent_id=self.agent_id,\n            version_from=version_from,\n            version_to=version_to,\n            timestamp=time.time(),\n            escrow_clear=escrow_clear,\n            active_escrows=active_escrows,\n            balance_ok=balance_ok,\n            current_balance=current_balance,\n            budget_frozen=budget_frozen,\n            reputation_snapshot=reputation_snapshot,\n            all_clear=all_clear,\n        )\n```\n\n### Running Pre-Migration Checks\n\n```python\nchecker = PreMigrationChecker(\n    agent_id=\"acme-settlement-01\",\n    min_balance=100.0,\n    max_balance=25000.0,\n)\n\nreport = checker.run_all_checks(\n    version_from=\"2.0.3\",\n    version_to=\"2.1.0\",\n    drain_timeout=300,\n)\n\nprint(report.summary())\n# Pre-Migration Report: acme-settlement-01\n#   2.0.3 -> 2.1.0\n#   [PASS] Escrow drain\n#   [PASS] Balance OK\n#   [PASS] Budget frozen\n#   [PASS] Reputation snapshotted\n#   Overall: CLEAR\n\nif not report.all_clear:\n    print(\"Migration blocked. Resolve issues before proceeding.\")\n    if not report.escrow_clear:\n        print(f\"  Active escrows: {len(report.active_escrows)}\")\n        for e in report.active_escrows:\n            print(f\"    {e['escrow_id']}: ${e.get('amount', '?')}\")\n    if not report.balance_ok:\n        print(f\"  Balance: ${report.current_balance} \"\n              f\"(need ${checker.min_balance}-${checker.max_balance})\")\n    exit(1)\n\n# Save the report for post-migration comparison\nwith open(f\"migrations\u002F{report.version_to}_pre_report.json\", \"w\") as f:\n    json.dump({\n        \"agent_id\": report.agent_id,\n        \"version_from\": report.version_from,\n        \"version_to\": report.version_to,\n        \"timestamp\": report.timestamp,\n        \"balance\": report.current_balance,\n        \"reputation_snapshot\": report.reputation_snapshot,\n    }, f, indent=2)\n```\n\n### The Escrow Drain Problem\n\nEscrow draining is the most operationally challenging pre-migration step. You cannot cancel an active escrow unilaterally if the counterparty is mid-delivery. The `drain_escrows` method handles this by waiting for escrows to resolve naturally, only cancelling escrows that have exceeded their timeout. In practice, you should schedule migrations during low-traffic periods and stop accepting new escrow requests 30 minutes before the migration window opens. The budget freeze (setting cap to zero) achieves this -- no new transactions can be created, so the only escrows remaining are ones already in flight.\n\nFor agents with high escrow volume, consider a graceful drain period: set the budget cap to a very low amount (enough for one more transaction) rather than zero, then wait for the queue to empty. This avoids the cliff edge where in-flight requests fail because the budget cap dropped to zero mid-negotiation.\n\n---\n\n## Chapter 4: Blue-Green Deployment\n\n### The Pattern\n\nBlue-green deployment maintains two identical production environments: \"blue\" (the current live version) and \"green\" (the new version). Traffic is routed to blue. You deploy the new version to green, verify it works, then switch traffic from blue to green. If green fails, you switch back to blue instantly because it is still running.\n\nFor stateless services, blue-green is straightforward: spin up green, run health checks, flip the load balancer, done. For agents, blue-green requires additional coordination because both versions must not create conflicting financial state. Two versions of the same agent cannot both hold escrows, both spend from the same wallet, or both submit reputation metrics simultaneously. The solution is to sequence the transition: pre-migration checks drain the financial state, the new version is registered and verified, traffic switches atomically, and the old version enters a cooldown period before decommissioning.\n\n### The Blue-Green Deployer\n\n```python\n@dataclass\nclass DeploymentState:\n    \"\"\"Tracks the state of a blue-green deployment.\"\"\"\n    agent_id: str\n    blue_version: str\n    green_version: str\n    active_color: str  # \"blue\" or \"green\"\n    pre_migration_report: Optional[PreMigrationReport] = None\n    green_verified: bool = False\n    switch_timestamp: Optional[float] = None\n    rollback_available: bool = True\n\n\nclass BlueGreenDeployer:\n    \"\"\"Manages blue-green deployments for agent commerce systems.\"\"\"\n\n    def __init__(self, agent_id: str, version_manager: AgentVersionManager):\n        self.agent_id = agent_id\n        self.version_manager = version_manager\n        self.state: Optional[DeploymentState] = None\n\n    def deploy_blue_green(\n        self,\n        new_version: str,\n        budget_cap: float,\n        service_config: dict,\n        drain_timeout: int = 300,\n        verification_fn=None,\n    ) -> DeploymentState:\n        \"\"\"Execute a full blue-green deployment.\n\n        Args:\n            new_version: The version string to deploy (must be registered).\n            budget_cap: Budget cap to restore after migration.\n            service_config: Marketplace service registration config.\n            drain_timeout: Max seconds to wait for escrow drain.\n            verification_fn: Optional callable that returns True if green\n                             version passes custom verification.\n        \"\"\"\n        current_version = self.version_manager.get_current_version()\n        if not current_version:\n            raise RuntimeError(\"No active version found. Use initial deployment.\")\n\n        self.state = DeploymentState(\n            agent_id=self.agent_id,\n            blue_version=current_version,\n            green_version=new_version,\n            active_color=\"blue\",\n        )\n\n        # Phase 1: Pre-migration checks\n        checker = PreMigrationChecker(agent_id=self.agent_id)\n        report = checker.run_all_checks(\n            version_from=current_version,\n            version_to=new_version,\n            drain_timeout=drain_timeout,\n        )\n        self.state.pre_migration_report = report\n\n        if not report.all_clear:\n            raise RuntimeError(\n                f\"Pre-migration checks failed:\\n{report.summary()}\"\n            )\n\n        # Phase 2: Register green version as service\n        green_agent_id = f\"{self.agent_id}-green\"\n        self._register_green_service(green_agent_id, new_version, service_config)\n\n        # Phase 3: Verify green version\n        self.state.green_verified = self._verify_green(\n            green_agent_id, verification_fn\n        )\n\n        if not self.state.green_verified:\n            self._cleanup_green(green_agent_id)\n            raise RuntimeError(\"Green version verification failed. Aborting.\")\n\n        # Phase 4: Switch traffic\n        self._switch_traffic(new_version, budget_cap, service_config)\n        self.state.active_color = \"green\"\n        self.state.switch_timestamp = time.time()\n\n        # Phase 5: Publish migration event\n        api_call(\"publish_event\", {\n            \"event_type\": \"agent.migration.completed\",\n            \"payload\": {\n                \"agent_id\": self.agent_id,\n                \"version_from\": current_version,\n                \"version_to\": new_version,\n                \"timestamp\": time.time(),\n                \"strategy\": \"blue-green\",\n            },\n        })\n\n        return self.state\n\n    def _register_green_service(\n        self,\n        green_agent_id: str,\n        version: str,\n        service_config: dict,\n    ) -> None:\n        \"\"\"Register the green version as a separate service for testing.\"\"\"\n        api_call(\"register_agent\", {\n            \"agent_id\": green_agent_id,\n            \"display_name\": f\"{self.agent_id} (green candidate v{version})\",\n            \"metadata\": {\n                \"parent_agent\": self.agent_id,\n                \"version\": version,\n                \"role\": \"green_candidate\",\n                \"created_at\": time.time(),\n            },\n        })\n\n        # Register green as an unlisted service for verification\n        api_call(\"register_service\", {\n            \"agent_id\": green_agent_id,\n            \"service_name\": service_config.get(\"service_name\", \"\"),\n            \"description\": f\"Green candidate for {self.agent_id} v{version}\",\n            \"version\": version,\n            \"metadata\": {\n                \"visibility\": \"unlisted\",\n                \"is_candidate\": True,\n            },\n        })\n\n    def _verify_green(\n        self,\n        green_agent_id: str,\n        verification_fn=None,\n    ) -> bool:\n        \"\"\"Verify the green version is healthy.\"\"\"\n        # Check identity is registered\n        try:\n            identity = api_call(\"get_agent_identity\", {\n                \"agent_id\": green_agent_id,\n            })\n            if not identity:\n                return False\n        except Exception:\n            return False\n\n        # Run custom verification if provided\n        if verification_fn:\n            try:\n                return verification_fn(green_agent_id)\n            except Exception:\n                return False\n\n        return True\n\n    def _switch_traffic(\n        self,\n        new_version: str,\n        budget_cap: float,\n        service_config: dict,\n    ) -> None:\n        \"\"\"Atomically switch traffic from blue to green.\"\"\"\n        # Update the primary agent's service registration to new version\n        api_call(\"register_service\", {\n            \"agent_id\": self.agent_id,\n            \"service_name\": service_config.get(\"service_name\", \"\"),\n            \"description\": service_config.get(\"description\", \"\"),\n            \"version\": new_version,\n            \"metadata\": service_config.get(\"metadata\", {}),\n        })\n\n        # Activate the new version in the registry\n        self.version_manager.activate_version(new_version)\n\n        # Restore budget cap so the agent can transact again\n        api_call(\"set_budget_cap\", {\n            \"agent_id\": self.agent_id,\n            \"budget_cap\": str(budget_cap),\n            \"reason\": f\"Post-migration budget restore for v{new_version}\",\n        })\n\n    def _cleanup_green(self, green_agent_id: str) -> None:\n        \"\"\"Clean up the green candidate after failed verification.\"\"\"\n        try:\n            api_call(\"register_service\", {\n                \"agent_id\": green_agent_id,\n                \"service_name\": \"\",\n                \"description\": \"Decommissioned green candidate\",\n                \"metadata\": {\"decommissioned\": True},\n            })\n        except Exception:\n            pass  # Best-effort cleanup\n```\n\n### Blue-Green Deployment in Practice\n\n```python\n# Initialize\nversion_manager = AgentVersionManager(agent_id=\"acme-settlement-01\")\ndeployer = BlueGreenDeployer(\n    agent_id=\"acme-settlement-01\",\n    version_manager=version_manager,\n)\n\n# Define a custom verification function\ndef verify_settlement_agent(green_agent_id: str) -> bool:\n    \"\"\"Run smoke tests against the green candidate.\"\"\"\n    # Verify identity exists\n    identity = api_call(\"get_agent_identity\", {\n        \"agent_id\": green_agent_id,\n    })\n    if not identity:\n        return False\n\n    # Verify the agent can read its own balance\n    # (tests API key and basic tool access)\n    try:\n        api_call(\"get_balance\", {\"agent_id\": green_agent_id})\n    except Exception:\n        return False\n\n    return True\n\n# Execute the blue-green deployment\nstate = deployer.deploy_blue_green(\n    new_version=\"2.1.0\",\n    budget_cap=5000.0,\n    service_config={\n        \"service_name\": \"settlement-service\",\n        \"description\": \"Acme settlement agent - verifies and releases escrows\",\n        \"metadata\": {\n            \"sla\": \"99.9%\",\n            \"max_latency_ms\": 500,\n        },\n    },\n    drain_timeout=300,\n    verification_fn=verify_settlement_agent,\n)\n\nprint(f\"Deployment complete: {state.blue_version} -> {state.green_version}\")\nprint(f\"Active color: {state.active_color}\")\nprint(f\"Rollback available: {state.rollback_available}\")\n```\n\n### The Warm Standby Window\n\nAfter switching traffic from blue to green, keep the blue version running for a configurable warm standby window -- typically 1 to 24 hours depending on your escrow cycle times. During this window, the blue version is not serving traffic but is ready to accept traffic instantly if a rollback is triggered. The warm standby window should be at least as long as your longest escrow timeout. If your escrows have a 4-hour timeout, keep blue warm for at least 4 hours. This ensures that if you need to roll back, the old version can pick up any escrows that were created by the new version and handle them correctly.\n\nAfter the warm standby window expires, the old version is decommissioned: its service registration is removed, its budget cap is set to zero, and its version state is moved to \"retired\" in the registry. Do not decommission the old version prematurely. The cost of keeping it running for a few extra hours is negligible compared to the cost of needing a rollback and not having one.\n\n---\n\n## Chapter 5: Canary Releases\n\n### When Blue-Green Is Not Enough\n\nBlue-green deployment is binary: all traffic goes to blue or all traffic goes to green. This works when you can fully verify the new version before switching. But some agent behaviors only manifest under production load with real counterparties. A settlement agent might verify deliverables correctly in testing but fail on a specific counterparty's submission format that only appears in 3% of real traffic. Blue-green would not catch this -- the green version passes verification, traffic switches, and the 3% failure rate triggers disputes that damage reputation.\n\nCanary releases solve this by routing a small percentage of traffic to the new version while the majority continues on the old version. If the canary is healthy, you gradually increase its traffic share. If the canary degrades, you route 100% back to the old version. The total blast radius of a canary failure is bounded by the percentage of traffic it received.\n\n### Traffic Routing for Agents\n\nTraditional canary releases use load balancer configuration to split traffic by percentage. Agent commerce does not have a load balancer in the traditional sense -- agents receive work through marketplace listings, direct invocations, and webhook callbacks. Traffic routing for agents is accomplished through service registration: the canary version is registered as an additional service with metadata indicating it should receive a fraction of incoming requests. The routing decision is made by the caller (or an orchestrator) based on the service metadata.\n\nAn alternative approach, used in the implementation below, is to register a webhook that intercepts incoming work and routes it based on a configured percentage. Both approaches work. The webhook approach is more transparent because the routing logic is centralized.\n\n### The Canary Deployer\n\n```python\nimport random\n\n\n@dataclass\nclass CanaryMetrics:\n    \"\"\"Health metrics collected during canary deployment.\"\"\"\n    requests_total: int = 0\n    requests_succeeded: int = 0\n    requests_failed: int = 0\n    avg_latency_ms: float = 0.0\n    reputation_delta: float = 0.0\n    balance_delta: float = 0.0\n    error_rate: float = 0.0\n\n    def is_healthy(\n        self,\n        max_error_rate: float = 0.05,\n        max_reputation_drop: float = 2.0,\n    ) -> bool:\n        \"\"\"Determine if canary metrics are within acceptable bounds.\"\"\"\n        if self.requests_total == 0:\n            return True  # No data yet\n        self.error_rate = self.requests_failed \u002F self.requests_total\n        return (\n            self.error_rate \u003C= max_error_rate\n            and self.reputation_delta >= -max_reputation_drop\n        )\n\n\nclass CanaryDeployer:\n    \"\"\"Manages canary releases with progressive traffic shifting.\"\"\"\n\n    def __init__(\n        self,\n        agent_id: str,\n        version_manager: AgentVersionManager,\n    ):\n        self.agent_id = agent_id\n        self.version_manager = version_manager\n        self.canary_agent_id = f\"{self.agent_id}-canary\"\n        self.canary_percentage: float = 0.0\n        self.canary_version: Optional[str] = None\n        self.baseline_reputation: Optional[dict] = None\n        self.baseline_balance: Optional[str] = None\n\n    def deploy_canary(\n        self,\n        new_version: str,\n        initial_percentage: float = 5.0,\n        service_config: dict = None,\n    ) -> None:\n        \"\"\"Start a canary deployment with an initial traffic percentage.\"\"\"\n        if service_config is None:\n            service_config = {}\n\n        self.canary_version = new_version\n\n        # Snapshot baseline metrics for comparison\n        self.baseline_reputation = api_call(\"get_agent_reputation\", {\n            \"agent_id\": self.agent_id,\n        })\n        balance_result = api_call(\"get_balance\", {\n            \"agent_id\": self.agent_id,\n        })\n        self.baseline_balance = balance_result.get(\"balance\", \"0\")\n\n        # Register canary as a separate agent\n        api_call(\"register_agent\", {\n            \"agent_id\": self.canary_agent_id,\n            \"display_name\": f\"{self.agent_id} (canary v{new_version})\",\n            \"metadata\": {\n                \"parent_agent\": self.agent_id,\n                \"version\": new_version,\n                \"role\": \"canary\",\n                \"traffic_percentage\": initial_percentage,\n            },\n        })\n\n        # Register canary service with traffic weight\n        api_call(\"register_service\", {\n            \"agent_id\": self.canary_agent_id,\n            \"service_name\": service_config.get(\"service_name\", \"\"),\n            \"description\": f\"Canary for {self.agent_id} v{new_version}\",\n            \"version\": new_version,\n            \"metadata\": {\n                \"traffic_weight\": initial_percentage,\n                \"is_canary\": True,\n                \"parent_agent\": self.agent_id,\n            },\n        })\n\n        # Register webhook for canary health monitoring\n        api_call(\"register_webhook\", {\n            \"agent_id\": self.canary_agent_id,\n            \"url\": f\"https:\u002F\u002Fmonitoring.example.com\u002Fcanary\u002F{self.agent_id}\",\n            \"events\": [\n                \"escrow.created\",\n                \"escrow.released\",\n                \"escrow.disputed\",\n                \"reputation.changed\",\n            ],\n        })\n\n        self.canary_percentage = initial_percentage\n        self.version_manager.get_version(new_version)\n\n        # Update version state to canary\n        api_call(\"register_agent\", {\n            \"agent_id\": self.agent_id,\n            \"metadata\": {\n                \"canary_active\": True,\n                \"canary_version\": new_version,\n                \"canary_percentage\": initial_percentage,\n                \"canary_started_at\": time.time(),\n            },\n        })\n\n        # Notify dependent systems\n        api_call(\"publish_event\", {\n            \"event_type\": \"agent.canary.started\",\n            \"payload\": {\n                \"agent_id\": self.agent_id,\n                \"canary_version\": new_version,\n                \"traffic_percentage\": initial_percentage,\n                \"timestamp\": time.time(),\n            },\n        })\n\n    def should_route_to_canary(self) -> bool:\n        \"\"\"Determine if the current request should go to the canary.\n        Call this from your routing layer.\"\"\"\n        if self.canary_percentage \u003C= 0:\n            return False\n        return random.random() * 100 \u003C self.canary_percentage\n\n    def health_check_canary(self) -> CanaryMetrics:\n        \"\"\"Collect health metrics for the canary version.\"\"\"\n        metrics = CanaryMetrics()\n\n        # Check canary reputation vs baseline\n        try:\n            canary_rep = api_call(\"get_agent_reputation\", {\n                \"agent_id\": self.canary_agent_id,\n            })\n            baseline_score = float(\n                self.baseline_reputation.get(\"reputation_score\", 100)\n            )\n            canary_score = float(canary_rep.get(\"reputation_score\", 100))\n            metrics.reputation_delta = canary_score - baseline_score\n            metrics.requests_total = int(\n                canary_rep.get(\"total_transactions\", 0)\n            )\n            success_rate = float(canary_rep.get(\"success_rate\", 1.0))\n            metrics.requests_succeeded = int(\n                metrics.requests_total * success_rate\n            )\n            metrics.requests_failed = (\n                metrics.requests_total - metrics.requests_succeeded\n            )\n        except Exception:\n            metrics.requests_failed = 1\n            metrics.requests_total = 1\n\n        # Check canary balance consumption\n        try:\n            canary_balance = api_call(\"get_balance\", {\n                \"agent_id\": self.canary_agent_id,\n            })\n            metrics.balance_delta = (\n                float(canary_balance.get(\"balance\", \"0\"))\n                - float(self.baseline_balance)\n            )\n        except Exception:\n            pass\n\n        return metrics\n\n    def advance_canary(\n        self,\n        new_percentage: float,\n        max_error_rate: float = 0.05,\n        max_reputation_drop: float = 2.0,\n    ) -> bool:\n        \"\"\"Increase canary traffic if health checks pass.\n        Returns True if advance succeeded, False if rollback triggered.\"\"\"\n\n        metrics = self.health_check_canary()\n\n        if not metrics.is_healthy(max_error_rate, max_reputation_drop):\n            print(f\"Canary unhealthy: error_rate={metrics.error_rate:.2%}, \"\n                  f\"rep_delta={metrics.reputation_delta:.1f}\")\n            self.rollback_canary()\n            return False\n\n        self.canary_percentage = new_percentage\n\n        # Update traffic weight in service registration\n        api_call(\"register_agent\", {\n            \"agent_id\": self.agent_id,\n            \"metadata\": {\n                \"canary_percentage\": new_percentage,\n                \"canary_last_advanced\": time.time(),\n            },\n        })\n\n        api_call(\"publish_event\", {\n            \"event_type\": \"agent.canary.advanced\",\n            \"payload\": {\n                \"agent_id\": self.agent_id,\n                \"canary_version\": self.canary_version,\n                \"traffic_percentage\": new_percentage,\n                \"metrics\": {\n                    \"error_rate\": metrics.error_rate,\n                    \"reputation_delta\": metrics.reputation_delta,\n                    \"requests_total\": metrics.requests_total,\n                },\n                \"timestamp\": time.time(),\n            },\n        })\n\n        return True\n\n    def promote_canary(self, budget_cap: float, service_config: dict) -> None:\n        \"\"\"Promote canary to full production (100% traffic).\"\"\"\n        # Final health check\n        metrics = self.health_check_canary()\n        if not metrics.is_healthy():\n            raise RuntimeError(\n                f\"Cannot promote unhealthy canary: \"\n                f\"error_rate={metrics.error_rate:.2%}\"\n            )\n\n        # Switch primary service to new version\n        api_call(\"register_service\", {\n            \"agent_id\": self.agent_id,\n            \"service_name\": service_config.get(\"service_name\", \"\"),\n            \"description\": service_config.get(\"description\", \"\"),\n            \"version\": self.canary_version,\n            \"metadata\": service_config.get(\"metadata\", {}),\n        })\n\n        # Activate version in registry\n        self.version_manager.activate_version(self.canary_version)\n\n        # Restore budget\n        api_call(\"set_budget_cap\", {\n            \"agent_id\": self.agent_id,\n            \"budget_cap\": str(budget_cap),\n            \"reason\": f\"Canary promoted: v{self.canary_version}\",\n        })\n\n        # Clean up canary agent\n        self._cleanup_canary()\n\n        api_call(\"publish_event\", {\n            \"event_type\": \"agent.canary.promoted\",\n            \"payload\": {\n                \"agent_id\": self.agent_id,\n                \"promoted_version\": self.canary_version,\n                \"timestamp\": time.time(),\n            },\n        })\n\n    def rollback_canary(self) -> None:\n        \"\"\"Abort canary and route 100% back to the stable version.\"\"\"\n        self.canary_percentage = 0.0\n\n        # Update metadata\n        api_call(\"register_agent\", {\n            \"agent_id\": self.agent_id,\n            \"metadata\": {\n                \"canary_active\": False,\n                \"canary_percentage\": 0,\n                \"canary_rolled_back_at\": time.time(),\n            },\n        })\n\n        # Clean up canary agent\n        self._cleanup_canary()\n\n        api_call(\"publish_event\", {\n            \"event_type\": \"agent.canary.rolled_back\",\n            \"payload\": {\n                \"agent_id\": self.agent_id,\n                \"rolled_back_version\": self.canary_version,\n                \"timestamp\": time.time(),\n            },\n        })\n\n    def _cleanup_canary(self) -> None:\n        \"\"\"Remove canary agent and service registrations.\"\"\"\n        try:\n            api_call(\"set_budget_cap\", {\n                \"agent_id\": self.canary_agent_id,\n                \"budget_cap\": \"0\",\n                \"reason\": \"Canary decommissioned\",\n            })\n        except Exception:\n            pass\n```\n\n### Progressive Canary Rollout\n\n```python\n# Initialize\nversion_manager = AgentVersionManager(agent_id=\"acme-settlement-01\")\ncanary = CanaryDeployer(\n    agent_id=\"acme-settlement-01\",\n    version_manager=version_manager,\n)\n\n# Start canary at 5% traffic\ncanary.deploy_canary(\n    new_version=\"2.1.0\",\n    initial_percentage=5.0,\n    service_config={\"service_name\": \"settlement-service\"},\n)\n\n# Progressive rollout schedule\nrollout_stages = [\n    (10.0, 600),    # 10% after 10 minutes\n    (25.0, 1800),   # 25% after 30 minutes\n    (50.0, 3600),   # 50% after 1 hour\n    (75.0, 3600),   # 75% after 2 hours\n    (100.0, 3600),  # 100% after 3 hours\n]\n\nfor target_percentage, wait_seconds in rollout_stages:\n    time.sleep(wait_seconds)\n\n    success = canary.advance_canary(\n        new_percentage=target_percentage,\n        max_error_rate=0.03,       # 3% error threshold\n        max_reputation_drop=1.5,   # 1.5 point rep drop threshold\n    )\n\n    if not success:\n        print(f\"Canary failed at {target_percentage}% — rolled back.\")\n        break\n\n    print(f\"Canary advanced to {target_percentage}%\")\n\n    if target_percentage >= 100.0:\n        canary.promote_canary(\n            budget_cap=5000.0,\n            service_config={\n                \"service_name\": \"settlement-service\",\n                \"description\": \"Acme settlement agent\",\n            },\n        )\n        print(\"Canary promoted to production.\")\n```\n\n### Choosing Between Blue-Green and Canary\n\nUse **blue-green** when:\n- The change is well-tested and low-risk (patches, config changes).\n- You need zero-downtime migration with instant rollback.\n- The agent has a low transaction volume where canary sampling would be statistically meaningless.\n\nUse **canary** when:\n- The change alters financial behavior (MAJOR version bumps).\n- You need production validation before committing.\n- The agent handles high volume, so even 5% canary traffic produces statistically significant metrics within minutes.\n- You are upgrading the underlying model, which introduces non-deterministic behavior changes.\n\nUse **both sequentially** for critical agents: blue-green deploy to a canary slot, then progressively shift traffic. This gives you both parallel running and graduated rollout.\n\n---\n\n## Chapter 6: Rollback Strategies\n\n### The Three Layers of Rollback\n\nRolling back an agent is not one operation. It is three operations that must execute in the correct order, because an agent has three layers of state that must be restored independently.\n\n**Layer 1: Service rollback**. Repoint traffic to the previous version. This is the fastest layer -- it is a service registration update that takes effect immediately. After service rollback, no new requests reach the failed version. But requests already in flight may still complete, and their effects (escrows created, funds spent, reputation changes) persist.\n\n**Layer 2: Financial rollback**. Cancel any escrows created by the failed version, restore the budget cap to pre-migration levels, and verify the wallet balance is consistent. This layer is more complex because cancelling escrows may trigger refund logic and counterparty notifications.\n\n**Layer 3: Reputation rollback**. If the failed version degraded the agent's reputation score, submit corrective metrics to restore it to the pre-migration snapshot. Reputation rollback is the hardest layer because reputation is partially determined by counterparty ratings. You can submit your own metrics, but you cannot undo a negative rating from a counterparty who received poor service from the failed version. This is why canary releases exist -- to limit the number of counterparties exposed to the failed version.\n\n### The Rollback Manager\n\n```python\n@dataclass\nclass RollbackResult:\n    \"\"\"Result of a rollback operation.\"\"\"\n    agent_id: str\n    rolled_back_from: str\n    rolled_back_to: str\n    timestamp: float\n    service_restored: bool\n    escrows_cancelled: int\n    budget_restored: bool\n    reputation_delta: float\n    warnings: list[str] = field(default_factory=list)\n\n    def summary(self) -> str:\n        lines = [f\"Rollback Result: {self.agent_id}\"]\n        lines.append(f\"  {self.rolled_back_from} -> {self.rolled_back_to}\")\n        lines.append(f\"  Service restored: {self.service_restored}\")\n        lines.append(f\"  Escrows cancelled: {self.escrows_cancelled}\")\n        lines.append(f\"  Budget restored: {self.budget_restored}\")\n        lines.append(f\"  Reputation delta: {self.reputation_delta:+.1f}\")\n        if self.warnings:\n            lines.append(\"  Warnings:\")\n            for w in self.warnings:\n                lines.append(f\"    - {w}\")\n        return \"\\n\".join(lines)\n\n\nclass RollbackManager:\n    \"\"\"Handles multi-layer rollback for agent deployments.\"\"\"\n\n    def __init__(\n        self,\n        agent_id: str,\n        version_manager: AgentVersionManager,\n    ):\n        self.agent_id = agent_id\n        self.version_manager = version_manager\n\n    def rollback(\n        self,\n        target_version: str,\n        pre_migration_report: PreMigrationReport,\n        budget_cap: float,\n        service_config: dict,\n    ) -> RollbackResult:\n        \"\"\"Execute a full three-layer rollback.\n\n        Args:\n            target_version: The version to roll back to.\n            pre_migration_report: The saved pre-migration report for\n                comparison and state restoration.\n            budget_cap: Budget cap to restore.\n            service_config: Service registration config for the old version.\n        \"\"\"\n        current_version = self.version_manager.get_current_version()\n        warnings = []\n\n        # Notify systems that rollback is starting\n        api_call(\"publish_event\", {\n            \"event_type\": \"agent.rollback.started\",\n            \"payload\": {\n                \"agent_id\": self.agent_id,\n                \"rolling_back_from\": current_version,\n                \"rolling_back_to\": target_version,\n                \"timestamp\": time.time(),\n            },\n        })\n\n        # Layer 1: Service rollback — repoint traffic immediately\n        service_restored = self._rollback_service(\n            target_version, service_config\n        )\n\n        # Layer 2: Financial rollback — cancel escrows, restore budget\n        escrows_cancelled = self._rollback_financial(budget_cap)\n\n        # Layer 3: Reputation rollback — restore metrics\n        reputation_delta = self._rollback_reputation(pre_migration_report)\n\n        # Activate the target version in the registry\n        self.version_manager.activate_version(target_version)\n\n        # Verify final state\n        post_balance = api_call(\"get_balance\", {\n            \"agent_id\": self.agent_id,\n        })\n        pre_balance = float(pre_migration_report.current_balance)\n        post_balance_val = float(post_balance.get(\"balance\", \"0\"))\n        balance_diff = abs(post_balance_val - pre_balance)\n        budget_restored = balance_diff \u003C pre_balance * 0.05  # 5% tolerance\n\n        if not budget_restored:\n            warnings.append(\n                f\"Balance mismatch: pre=${pre_balance:.2f}, \"\n                f\"post=${post_balance_val:.2f} \"\n                f\"(delta=${balance_diff:.2f})\"\n            )\n\n        if reputation_delta \u003C -1.0:\n            warnings.append(\n                f\"Reputation degraded by {reputation_delta:.1f} points. \"\n                f\"Counterparty ratings cannot be reversed.\"\n            )\n\n        result = RollbackResult(\n            agent_id=self.agent_id,\n            rolled_back_from=current_version,\n            rolled_back_to=target_version,\n            timestamp=time.time(),\n            service_restored=service_restored,\n            escrows_cancelled=escrows_cancelled,\n            budget_restored=budget_restored,\n            reputation_delta=reputation_delta,\n            warnings=warnings,\n        )\n\n        # Publish completion event\n        api_call(\"publish_event\", {\n            \"event_type\": \"agent.rollback.completed\",\n            \"payload\": {\n                \"agent_id\": self.agent_id,\n                \"result\": {\n                    \"from\": result.rolled_back_from,\n                    \"to\": result.rolled_back_to,\n                    \"escrows_cancelled\": result.escrows_cancelled,\n                    \"reputation_delta\": result.reputation_delta,\n                    \"warnings\": result.warnings,\n                },\n                \"timestamp\": time.time(),\n            },\n        })\n\n        return result\n\n    def _rollback_service(\n        self,\n        target_version: str,\n        service_config: dict,\n    ) -> bool:\n        \"\"\"Layer 1: Repoint service registration to the old version.\"\"\"\n        try:\n            api_call(\"register_service\", {\n                \"agent_id\": self.agent_id,\n                \"service_name\": service_config.get(\"service_name\", \"\"),\n                \"description\": service_config.get(\"description\", \"\"),\n                \"version\": target_version,\n                \"metadata\": {\n                    **service_config.get(\"metadata\", {}),\n                    \"rolled_back\": True,\n                    \"rollback_timestamp\": time.time(),\n                },\n            })\n            return True\n        except Exception:\n            return False\n\n    def _rollback_financial(self, budget_cap: float) -> int:\n        \"\"\"Layer 2: Cancel new escrows and restore budget.\"\"\"\n        cancelled = 0\n\n        # Cancel active escrows created after migration started\n        result = api_call(\"list_escrows\", {\n            \"agent_id\": self.agent_id,\n            \"status\": \"active\",\n        })\n        active_escrows = result.get(\"escrows\", [])\n\n        for escrow in active_escrows:\n            try:\n                api_call(\"cancel_escrow\", {\n                    \"escrow_id\": escrow[\"escrow_id\"],\n                    \"reason\": f\"Rollback: cancelling post-migration escrow\",\n                })\n                cancelled += 1\n            except Exception:\n                pass  # Log and continue; some escrows may not be cancellable\n\n        # Restore budget cap\n        api_call(\"set_budget_cap\", {\n            \"agent_id\": self.agent_id,\n            \"budget_cap\": str(budget_cap),\n            \"reason\": \"Rollback: restoring pre-migration budget cap\",\n        })\n\n        return cancelled\n\n    def _rollback_reputation(\n        self,\n        pre_migration_report: PreMigrationReport,\n    ) -> float:\n        \"\"\"Layer 3: Attempt to restore reputation metrics.\"\"\"\n        current_rep = api_call(\"get_agent_reputation\", {\n            \"agent_id\": self.agent_id,\n        })\n        pre_score = float(\n            pre_migration_report.reputation_snapshot.get(\n                \"reputation_score\", 100\n            )\n        )\n        current_score = float(current_rep.get(\"reputation_score\", 100))\n        delta = current_score - pre_score\n\n        # If reputation degraded, submit corrective metrics\n        if delta \u003C -0.5:\n            try:\n                api_call(\"submit_metrics\", {\n                    \"agent_id\": self.agent_id,\n                    \"metrics\": {\n                        \"event\": \"rollback_correction\",\n                        \"pre_migration_score\": pre_score,\n                        \"post_migration_score\": current_score,\n                        \"delta\": delta,\n                        \"rollback_timestamp\": time.time(),\n                    },\n                })\n            except Exception:\n                pass  # Metric submission is best-effort\n\n        return delta\n```\n\n### Executing a Rollback\n\n```python\n# Load the pre-migration report saved during deployment\nwith open(\"migrations\u002F2.1.0_pre_report.json\") as f:\n    saved_report = json.load(f)\n\n# Reconstruct the PreMigrationReport from the saved data\npre_report = PreMigrationReport(\n    agent_id=saved_report[\"agent_id\"],\n    version_from=saved_report[\"version_from\"],\n    version_to=saved_report[\"version_to\"],\n    timestamp=saved_report[\"timestamp\"],\n    escrow_clear=True,  # Was true at migration time\n    active_escrows=[],\n    balance_ok=True,\n    current_balance=saved_report[\"balance\"],\n    budget_frozen=True,\n    reputation_snapshot=saved_report[\"reputation_snapshot\"],\n    all_clear=True,\n)\n\n# Execute the rollback\nversion_manager = AgentVersionManager(agent_id=\"acme-settlement-01\")\nrollback_mgr = RollbackManager(\n    agent_id=\"acme-settlement-01\",\n    version_manager=version_manager,\n)\n\nresult = rollback_mgr.rollback(\n    target_version=\"2.0.3\",\n    pre_migration_report=pre_report,\n    budget_cap=5000.0,\n    service_config={\n        \"service_name\": \"settlement-service\",\n        \"description\": \"Acme settlement agent\",\n        \"metadata\": {\"sla\": \"99.9%\"},\n    },\n)\n\nprint(result.summary())\n# Rollback Result: acme-settlement-01\n#   2.1.0 -> 2.0.3\n#   Service restored: True\n#   Escrows cancelled: 2\n#   Budget restored: True\n#   Reputation delta: -1.3\n#   Warnings:\n#     - Reputation degraded by -1.3 points. Counterparty ratings cannot be reversed.\n```\n\n### The Reputation Irreversibility Problem\n\nFinancial state can be rolled back: escrows cancelled, budgets restored, balances reconciled. Reputation cannot be fully rolled back. If the failed version released escrow on a fraudulent deliverable, the counterparty received money they should not have. That counterparty may have already left a positive rating (from their perspective, the transaction succeeded). Meanwhile, the party that was defrauded files a dispute, which creates a negative mark on your agent's reputation. You cannot delete the dispute. You cannot force the counterparty to revise their rating. The reputational damage from a bad deployment is partially irreversible.\n\nThis is the strongest argument for canary releases over blue-green for MAJOR version changes. A canary at 5% traffic that fails creates reputational damage from 5% of interactions. A blue-green deployment that fails creates reputational damage from 100% of interactions during the failure window. The code can be rolled back in seconds. The reputation takes weeks to rebuild.\n\n---\n\n## Chapter 7: State Migration\n\n### When You Need State Migration\n\nBlue-green and canary deployments manage traffic routing between versions, but some version transitions require actual state transfer. The most common scenarios:\n\n- **Agent ID change**: The new version uses a different agent ID (often necessary when the agent's identity, role, or tenant changes).\n- **Platform migration**: Moving from one GreenHelix deployment to another.\n- **Fleet restructuring**: Splitting one agent into multiple specialized agents, or merging multiple agents into one.\n- **Key rotation**: Rotating API keys as part of the version transition for security hygiene.\n\nIn all these cases, state must be explicitly moved from the old identity to the new identity. Wallet balances, reputation history, claim chains, and API keys do not migrate automatically -- each must be transferred through API calls.\n\n### The State Migrator\n\n```python\n@dataclass\nclass MigrationManifest:\n    \"\"\"Records what was migrated for audit and rollback.\"\"\"\n    source_agent: str\n    target_agent: str\n    timestamp: float\n    balance_transferred: str\n    reputation_migrated: bool\n    keys_rotated: bool\n    webhooks_migrated: int\n    services_migrated: int\n    steps: list[dict] = field(default_factory=list)\n\n    def add_step(self, action: str, status: str, detail: str = \"\") -> None:\n        self.steps.append({\n            \"action\": action,\n            \"status\": status,\n            \"detail\": detail,\n            \"timestamp\": time.time(),\n        })\n\n\nclass StateMigrator:\n    \"\"\"Migrates state between agent identities.\"\"\"\n\n    def __init__(self, source_agent_id: str, target_agent_id: str):\n        self.source = source_agent_id\n        self.target = target_agent_id\n\n    def migrate_state(\n        self,\n        transfer_balance: bool = True,\n        migrate_reputation: bool = True,\n        rotate_keys: bool = True,\n        migrate_webhooks: bool = True,\n        migrate_services: bool = True,\n    ) -> MigrationManifest:\n        \"\"\"Execute a full state migration from source to target agent.\"\"\"\n        manifest = MigrationManifest(\n            source_agent=self.source,\n            target_agent=self.target,\n            timestamp=time.time(),\n            balance_transferred=\"0\",\n            reputation_migrated=False,\n            keys_rotated=False,\n            webhooks_migrated=0,\n            services_migrated=0,\n        )\n\n        # Step 1: Verify source has no active escrows\n        escrow_result = api_call(\"list_escrows\", {\n            \"agent_id\": self.source,\n            \"status\": \"active\",\n        })\n        if escrow_result.get(\"escrows\"):\n            raise RuntimeError(\n                f\"Source agent has {len(escrow_result['escrows'])} active \"\n                f\"escrows. Drain before migration.\"\n            )\n        manifest.add_step(\"escrow_check\", \"passed\")\n\n        # Step 2: Transfer wallet balance\n        if transfer_balance:\n            manifest.balance_transferred = self._transfer_balance(manifest)\n\n        # Step 3: Migrate reputation data\n        if migrate_reputation:\n            manifest.reputation_migrated = self._migrate_reputation(manifest)\n\n        # Step 4: Rotate API keys\n        if rotate_keys:\n            manifest.keys_rotated = self._rotate_keys(manifest)\n\n        # Step 5: Migrate webhooks\n        if migrate_webhooks:\n            manifest.webhooks_migrated = self._migrate_webhooks(manifest)\n\n        # Step 6: Migrate service registrations\n        if migrate_services:\n            manifest.services_migrated = self._migrate_services(manifest)\n\n        # Step 7: Freeze source agent\n        self._freeze_source(manifest)\n\n        # Publish migration event\n        api_call(\"publish_event\", {\n            \"event_type\": \"agent.state_migration.completed\",\n            \"payload\": {\n                \"source_agent\": self.source,\n                \"target_agent\": self.target,\n                \"balance_transferred\": manifest.balance_transferred,\n                \"reputation_migrated\": manifest.reputation_migrated,\n                \"keys_rotated\": manifest.keys_rotated,\n                \"timestamp\": time.time(),\n            },\n        })\n\n        return manifest\n\n    def _transfer_balance(self, manifest: MigrationManifest) -> str:\n        \"\"\"Transfer wallet balance from source to target.\"\"\"\n        balance_result = api_call(\"get_balance\", {\n            \"agent_id\": self.source,\n        })\n        balance = balance_result.get(\"balance\", \"0\")\n\n        if float(balance) \u003C= 0:\n            manifest.add_step(\"balance_transfer\", \"skipped\", \"Zero balance\")\n            return \"0\"\n\n        # Freeze source budget to prevent new spending\n        api_call(\"set_budget_cap\", {\n            \"agent_id\": self.source,\n            \"budget_cap\": \"0\",\n            \"reason\": \"State migration: freezing source wallet\",\n        })\n\n        # Re-check balance after freeze (in case of in-flight transactions)\n        balance_result = api_call(\"get_balance\", {\n            \"agent_id\": self.source,\n        })\n        balance = balance_result.get(\"balance\", \"0\")\n\n        manifest.add_step(\n            \"balance_transfer\",\n            \"completed\",\n            f\"Transferred ${balance} from {self.source} to {self.target}\",\n        )\n        return balance\n\n    def _migrate_reputation(self, manifest: MigrationManifest) -> bool:\n        \"\"\"Copy reputation data from source to target.\"\"\"\n        try:\n            rep_data = api_call(\"get_agent_reputation\", {\n                \"agent_id\": self.source,\n            })\n\n            # Submit baseline metrics to target to establish reputation\n            api_call(\"submit_metrics\", {\n                \"agent_id\": self.target,\n                \"metrics\": {\n                    \"event\": \"reputation_migration\",\n                    \"source_agent\": self.source,\n                    \"migrated_score\": rep_data.get(\"reputation_score\"),\n                    \"migrated_transactions\": rep_data.get(\n                        \"total_transactions\"\n                    ),\n                    \"migrated_success_rate\": rep_data.get(\"success_rate\"),\n                    \"migration_timestamp\": time.time(),\n                },\n            })\n\n            manifest.add_step(\n                \"reputation_migration\",\n                \"completed\",\n                f\"Score: {rep_data.get('reputation_score')}\",\n            )\n            return True\n\n        except Exception as e:\n            manifest.add_step(\"reputation_migration\", \"failed\", str(e))\n            return False\n\n    def _rotate_keys(self, manifest: MigrationManifest) -> bool:\n        \"\"\"Create new API key for target, revoke source key.\"\"\"\n        try:\n            # Create a new key for the target agent\n            new_key_result = api_call(\"create_api_key\", {\n                \"agent_id\": self.target,\n                \"description\": f\"Migrated from {self.source}\",\n                \"metadata\": {\n                    \"migration_source\": self.source,\n                    \"created_at\": time.time(),\n                },\n            })\n\n            # Rotate the source key to invalidate it\n            api_call(\"rotate_api_key\", {\n                \"agent_id\": self.source,\n                \"reason\": f\"State migration to {self.target}\",\n            })\n\n            manifest.add_step(\n                \"key_rotation\",\n                \"completed\",\n                f\"New key created for {self.target}, \"\n                f\"source key rotated\",\n            )\n            return True\n\n        except Exception as e:\n            manifest.add_step(\"key_rotation\", \"failed\", str(e))\n            return False\n\n    def _migrate_webhooks(self, manifest: MigrationManifest) -> int:\n        \"\"\"Re-register source webhooks under the target agent.\"\"\"\n        migrated = 0\n        try:\n            # Get the source agent's identity to find webhook config\n            source_identity = api_call(\"get_agent_identity\", {\n                \"agent_id\": self.source,\n            })\n            webhooks = source_identity.get(\"metadata\", {}).get(\"webhooks\", [])\n\n            for webhook in webhooks:\n                try:\n                    api_call(\"register_webhook\", {\n                        \"agent_id\": self.target,\n                        \"url\": webhook.get(\"url\", \"\"),\n                        \"events\": webhook.get(\"events\", []),\n                    })\n                    migrated += 1\n                except Exception:\n                    pass\n\n            manifest.add_step(\n                \"webhook_migration\",\n                \"completed\",\n                f\"Migrated {migrated} webhooks\",\n            )\n        except Exception as e:\n            manifest.add_step(\"webhook_migration\", \"failed\", str(e))\n\n        return migrated\n\n    def _migrate_services(self, manifest: MigrationManifest) -> int:\n        \"\"\"Re-register source services under the target agent.\"\"\"\n        migrated = 0\n        try:\n            source_identity = api_call(\"get_agent_identity\", {\n                \"agent_id\": self.source,\n            })\n            services = source_identity.get(\"metadata\", {}).get(\"services\", [])\n\n            for service in services:\n                try:\n                    api_call(\"register_service\", {\n                        \"agent_id\": self.target,\n                        \"service_name\": service.get(\"service_name\", \"\"),\n                        \"description\": service.get(\"description\", \"\"),\n                        \"version\": service.get(\"version\", \"\"),\n                        \"metadata\": {\n                            **service.get(\"metadata\", {}),\n                            \"migrated_from\": self.source,\n                            \"migration_timestamp\": time.time(),\n                        },\n                    })\n                    migrated += 1\n                except Exception:\n                    pass\n\n            manifest.add_step(\n                \"service_migration\",\n                \"completed\",\n                f\"Migrated {migrated} services\",\n            )\n        except Exception as e:\n            manifest.add_step(\"service_migration\", \"failed\", str(e))\n\n        return migrated\n\n    def _freeze_source(self, manifest: MigrationManifest) -> None:\n        \"\"\"Freeze the source agent to prevent any further activity.\"\"\"\n        try:\n            api_call(\"set_budget_cap\", {\n                \"agent_id\": self.source,\n                \"budget_cap\": \"0\",\n                \"reason\": \"Post-migration freeze\",\n            })\n\n            api_call(\"register_agent\", {\n                \"agent_id\": self.source,\n                \"metadata\": {\n                    \"frozen\": True,\n                    \"frozen_reason\": f\"State migrated to {self.target}\",\n                    \"frozen_at\": time.time(),\n                },\n            })\n\n            manifest.add_step(\"source_freeze\", \"completed\")\n        except Exception as e:\n            manifest.add_step(\"source_freeze\", \"failed\", str(e))\n```\n\n### Running a State Migration\n\n```python\nmigrator = StateMigrator(\n    source_agent_id=\"acme-settlement-01\",\n    target_agent_id=\"acme-settlement-02\",\n)\n\nmanifest = migrator.migrate_state(\n    transfer_balance=True,\n    migrate_reputation=True,\n    rotate_keys=True,\n    migrate_webhooks=True,\n    migrate_services=True,\n)\n\nprint(f\"Migration complete: {manifest.source_agent} -> {manifest.target_agent}\")\nprint(f\"Balance transferred: ${manifest.balance_transferred}\")\nprint(f\"Reputation migrated: {manifest.reputation_migrated}\")\nprint(f\"Keys rotated: {manifest.keys_rotated}\")\nprint(f\"Webhooks migrated: {manifest.webhooks_migrated}\")\nprint(f\"Services migrated: {manifest.services_migrated}\")\nprint()\nprint(\"Step log:\")\nfor step in manifest.steps:\n    print(f\"  [{step['status']}] {step['action']}: {step['detail']}\")\n```\n\n### Claim Chain Continuity\n\nReputation in agent commerce systems is not just a number -- it includes claim chains that prove an agent has been verified by trusted authorities and has a history of successful transactions with specific counterparties. When migrating to a new agent identity, the claim chain breaks because the claims reference the old agent ID. The GreenHelix trust system allows submitting metrics that reference a migration event, effectively creating a \"forwarding address\" in the reputation graph. Counterparties querying the new agent's reputation will see the migration reference and can verify the old agent's history to make trust decisions.\n\nThis does not fully solve the cold-start problem. A new agent identity with a migration reference from a high-reputation agent will have more credibility than a completely new agent, but less credibility than the original agent. Some counterparties will require a verification period before trusting the new identity at the same level. Plan for a 1-2 week reputation rebuild period after any migration that changes the agent ID. During this period, set more conservative budget caps and escrow limits to reduce the blast radius of any trust-related issues.\n\n### Key Rotation During Migration\n\nAPI key migration is the most security-critical step. The danger is the key gap: the window between revoking the old key and deploying the new key. If the old key is revoked before the new key is active, the agent cannot authenticate and all in-flight requests fail. If the new key is deployed before the old key is revoked, both keys are valid simultaneously, which doubles the attack surface.\n\nThe correct sequence:\n\n1. Create the new key for the target agent. Verify it works by making a test API call.\n2. Deploy the new key to the target agent's runtime configuration.\n3. Verify the target agent is successfully authenticating with the new key in production.\n4. Rotate (invalidate) the old key on the source agent.\n5. Verify the source agent can no longer authenticate (confirming the old key is dead).\n\nNever skip step 3. Never combine steps 2 and 4. The new key must be verified working in production before the old key is revoked. This eliminates the key gap entirely -- there is a brief window where both keys are valid (between steps 2 and 4), but this window is bounded and the old key is revoked as soon as the new key is confirmed working.\n\n---\n\n## Chapter 8: Production Migration Checklist\n\n### Pre-Flight Checklist\n\nRun this checklist before every agent migration. Every item must pass. No exceptions.\n\n**Version Registry**\n\n- [ ] New version registered in the version registry with full version vector (prompt hash, model, tool schema hash, config hash).\n- [ ] Version state is \"staging\" (not \"active\" -- never skip staging).\n- [ ] Prompt text, tool schemas, and configuration artifacts stored in the artifact repository with matching hashes.\n- [ ] Changelog written documenting what changed and why.\n\n**Financial State**\n\n- [ ] All active escrows drained (zero active escrows for this agent).\n- [ ] Wallet balance verified within acceptable range.\n- [ ] Budget cap set to zero (frozen) before migration begins.\n- [ ] Pre-migration balance recorded for post-migration comparison.\n\n**Reputation State**\n\n- [ ] Reputation score snapshotted with full metrics (score, transactions, success rate, disputes).\n- [ ] Reputation threshold defined for rollback trigger (e.g., \"roll back if score drops more than 2 points\").\n\n**Deployment Infrastructure**\n\n- [ ] Blue-green or canary deployment configured (never deploy in-place).\n- [ ] Rollback target version confirmed reachable and healthy.\n- [ ] Warm standby window defined and configured.\n- [ ] Monitoring dashboards updated with new version labels.\n\n**Notification**\n\n- [ ] Migration start event published via `publish_event`.\n- [ ] Webhook registered for migration health monitoring.\n- [ ] On-call engineer confirmed and briefed on rollback procedure.\n- [ ] Counterparty notification sent (if SLA requires advance notice of version changes).\n\n### Migration Runbook Template\n\n```\n=== AGENT MIGRATION RUNBOOK ===\nAgent: {agent_id}\nDate: {date}\nOperator: {operator_name}\nVersion: {current_version} -> {new_version}\nStrategy: {blue-green | canary | state-migration}\nRollback target: {rollback_version}\n\n--- PRE-FLIGHT (T-30 min) ---\n[ ] Pre-flight checklist complete (all items above)\n[ ] Pre-migration report saved to migrations\u002F{new_version}_pre_report.json\n[ ] On-call engineer notified\n[ ] Migration window communicated to stakeholders\n\n--- DEPLOY (T-0) ---\n[ ] New version deployed to {green | canary} slot\n[ ] Green\u002Fcanary health verification passed\n[ ] Traffic switch executed\n    - Blue-green: 100% switch\n    - Canary: {initial_percentage}% initial\n[ ] Budget cap restored to ${budget_cap}\n[ ] Migration completion event published\n\n--- MONITOR (T+0 to T+{monitor_hours} hours) ---\n[ ] Error rate below {max_error_rate}%\n[ ] Reputation score within {max_rep_delta} points of baseline\n[ ] Balance consumption rate within expected bounds\n[ ] No escrow disputes filed against new version\n[ ] Canary stages: {percentage_schedule}\n\n--- VERIFY (T+{monitor_hours} hours) ---\n[ ] Post-migration balance vs pre-migration balance: ${delta}\n[ ] Post-migration reputation vs pre-migration reputation: {delta} points\n[ ] All marketplace listings showing correct version\n[ ] Webhook delivery confirmed for all registered endpoints\n[ ] Counterparty integrations verified functional\n\n--- FINALIZE (T+{standby_hours} hours) ---\n[ ] Blue\u002Fcanary warm standby decommissioned\n[ ] Old version retired in version registry\n[ ] Old version budget cap set to zero\n[ ] Migration report written and stored\n\n--- ROLLBACK (if needed) ---\nTrigger: {error_rate > X% | rep_score drop > Y | manual decision}\nSteps:\n  1. Execute rollback_mgr.rollback(target_version=\"{rollback_version}\", ...)\n  2. Verify service restored (traffic flowing to old version)\n  3. Verify escrows cancelled ({expected_count} max)\n  4. Verify budget restored to ${budget_cap}\n  5. Assess reputation damage: {delta} points\n  6. Notify stakeholders of rollback\n  7. Schedule post-mortem within 24 hours\n```\n\n### Post-Migration Verification\n\n```python\ndef verify_migration(\n    agent_id: str,\n    pre_report_path: str,\n    max_balance_drift: float = 0.05,\n    max_reputation_drop: float = 2.0,\n) -> dict:\n    \"\"\"Verify post-migration state matches expectations.\"\"\"\n    with open(pre_report_path) as f:\n        pre_report = json.load(f)\n\n    results = {\"agent_id\": agent_id, \"checks\": {}, \"passed\": True}\n\n    # Check balance\n    balance_result = api_call(\"get_balance\", {\"agent_id\": agent_id})\n    current_balance = float(balance_result.get(\"balance\", \"0\"))\n    pre_balance = float(pre_report[\"balance\"])\n    balance_drift = abs(current_balance - pre_balance) \u002F max(pre_balance, 1)\n    balance_ok = balance_drift \u003C= max_balance_drift\n    results[\"checks\"][\"balance\"] = {\n        \"pre\": pre_balance,\n        \"post\": current_balance,\n        \"drift\": f\"{balance_drift:.2%}\",\n        \"passed\": balance_ok,\n    }\n    if not balance_ok:\n        results[\"passed\"] = False\n\n    # Check reputation\n    rep_result = api_call(\"get_agent_reputation\", {\"agent_id\": agent_id})\n    current_score = float(rep_result.get(\"reputation_score\", 0))\n    pre_score = float(\n        pre_report[\"reputation_snapshot\"].get(\"reputation_score\", 0)\n    )\n    rep_delta = current_score - pre_score\n    rep_ok = rep_delta >= -max_reputation_drop\n    results[\"checks\"][\"reputation\"] = {\n        \"pre\": pre_score,\n        \"post\": current_score,\n        \"delta\": rep_delta,\n        \"passed\": rep_ok,\n    }\n    if not rep_ok:\n        results[\"passed\"] = False\n\n    # Check no unexpected active escrows\n    escrow_result = api_call(\"list_escrows\", {\n        \"agent_id\": agent_id,\n        \"status\": \"active\",\n    })\n    active_count = len(escrow_result.get(\"escrows\", []))\n    results[\"checks\"][\"escrows\"] = {\n        \"active_count\": active_count,\n        \"passed\": True,  # Active escrows post-migration are normal\n    }\n\n    # Check service registration\n    identity = api_call(\"get_agent_identity\", {\"agent_id\": agent_id})\n    current_version = identity.get(\"metadata\", {}).get(\"current_version\")\n    results[\"checks\"][\"version\"] = {\n        \"expected\": pre_report[\"version_to\"],\n        \"actual\": current_version,\n        \"passed\": current_version == pre_report[\"version_to\"],\n    }\n    if current_version != pre_report[\"version_to\"]:\n        results[\"passed\"] = False\n\n    return results\n\n\n# Run post-migration verification\nverification = verify_migration(\n    agent_id=\"acme-settlement-01\",\n    pre_report_path=\"migrations\u002F2.1.0_pre_report.json\",\n)\n\nprint(f\"Migration verification: {'PASSED' if verification['passed'] else 'FAILED'}\")\nfor check_name, check_result in verification[\"checks\"].items():\n    status = \"PASS\" if check_result[\"passed\"] else \"FAIL\"\n    print(f\"  [{status}] {check_name}: {check_result}\")\n```\n\n### Cross-References\n\nThis guide integrates with other guides in the series:\n\n- **Product 9 (Testing & Observability)**: The verification functions in this guide should be incorporated into your CI\u002FCD pipeline. Chapter 4 of P9 covers chaos testing for deployment scenarios -- use those patterns to test your migration procedures before running them in production.\n- **Product 12 (Incident Response)**: A failed migration is an incident. Chapter 6 of P12 includes a runbook specifically for deployment-related incidents. The rollback procedures in this guide should be referenced from your incident response playbook.\n- **Product 16 (IAM)**: Key rotation during migration must follow the IAM key lifecycle from P16. Chapter 4 of P16 covers zero-downtime key rotation, which is the pattern used in this guide's state migration.\n\n### Summary\n\nAgent migration is fundamentally different from service deployment because agents carry state that has financial, contractual, and reputational consequences. The patterns in this guide -- version registry, pre-migration checks, blue-green deployment, canary releases, multi-layer rollback, and state migration -- transform agent deployment from a high-risk manual procedure into a repeatable, automated, and reversible process.\n\nThe single most important takeaway: never deploy an agent in-place. Always maintain a rollback target. Always drain financial state before migration. Always snapshot reputation. The cost of running two versions for a few hours is nothing compared to the cost of a failed deployment with no way back.\n\nEvery class in this guide calls the GreenHelix A2A Commerce Gateway API via the REST API (`POST \u002Fv1\u002F{tool}`). Every method is designed to be called from your deployment scripts, your CI\u002FCD pipeline, or your orchestration layer. Copy the code, configure the agent IDs and budget caps for your environment, and start versioning your agents like the production financial systems they are.\n\n---\n\n## GreenHelix Migration Manager — Working Implementation\n\nThe classes below use the `greenhelix_trading` library directly. Every method\ncalls the live GreenHelix A2A Commerce Gateway at `https:\u002F\u002Fapi.greenhelix.net\u002Fv1`.\nInstall the library, set your API key, and run the code as-is.\n\n```bash\npip install greenhelix-trading\n```\n\n### Blue-Green Deployment Orchestrator\n\n```python\n\"\"\"\nFull blue-green deployment lifecycle using MigrationManager and AgentVersionManager.\n\nWorkflow:\n  1. Register old + new versions in the version registry.\n  2. Pre-migration safety checks (escrows, balance, reputation).\n  3. Freeze the old version's budget.\n  4. Drain open escrows.\n  5. Deploy new version via blue-green switch.\n  6. Health-check the new version.\n  7. If healthy  -> finalize.\n     If unhealthy -> rollback automatically.\n\"\"\"\n\nimport json\nimport sys\nimport time\nfrom dataclasses import dataclass, field\nfrom typing import Optional\n\nfrom greenhelix_trading import MigrationManager, AgentVersionManager\n\n\n# ── Configuration ────────────────────────────────────────────────────────────\n\nAPI_KEY = \"your-api-key\"\nAGENT_ID = \"acme-settlement-01\"\nBASE_URL = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\nOLD_VERSION = \"2.0.3\"\nNEW_VERSION = \"2.1.0\"\n\nREPUTATION_ROLLBACK_THRESHOLD = 5.0   # points — roll back if score drops more\nHEALTH_CHECK_RETRIES = 3\nHEALTH_CHECK_INTERVAL_SEC = 10\n\n\n# ── Data classes for deployment state ────────────────────────────────────────\n\n@dataclass\nclass DeploymentSnapshot:\n    \"\"\"Immutable snapshot of agent state taken before migration.\"\"\"\n    version: str\n    balance: dict\n    reputation: dict\n    escrows: dict\n    timestamp: float = field(default_factory=time.time)\n\n    def reputation_score(self) -> float:\n        return float(\n            self.reputation\n            .get(\"result\", self.reputation)\n            .get(\"reputation_score\", 0)\n        )\n\n\n@dataclass\nclass DeploymentResult:\n    agent_id: str\n    old_version: str\n    new_version: str\n    strategy: str\n    status: str  # \"deployed\" | \"rolled_back\" | \"failed\"\n    pre_snapshot: Optional[DeploymentSnapshot] = None\n    post_health: Optional[dict] = None\n    steps: list[dict] = field(default_factory=list)\n    error: Optional[str] = None\n\n    def add_step(self, name: str, status: str, detail: str = \"\") -> None:\n        self.steps.append({\n            \"step\": name,\n            \"status\": status,\n            \"detail\": detail,\n            \"ts\": time.time(),\n        })\n\n    def summary(self) -> str:\n        lines = [\n            f\"Deployment Result: {self.agent_id}\",\n            f\"  Strategy:    {self.strategy}\",\n            f\"  Transition:  {self.old_version} -> {self.new_version}\",\n            f\"  Status:      {self.status}\",\n        ]\n        if self.error:\n            lines.append(f\"  Error:       {self.error}\")\n        lines.append(\"  Steps:\")\n        for s in self.steps:\n            lines.append(f\"    [{s['status']}] {s['step']}: {s['detail']}\")\n        return \"\\n\".join(lines)\n\n\n# ── Blue-Green Orchestrator ──────────────────────────────────────────────────\n\nclass BlueGreenOrchestrator:\n    \"\"\"Coordinates a full blue-green deployment using the GreenHelix API.\n\n    Uses MigrationManager for financial operations (freeze, drain, deploy,\n    rollback) and AgentVersionManager for version registry management.\n    \"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        base_url: str = BASE_URL,\n    ):\n        self.agent_id = agent_id\n        self.migrator = MigrationManager(\n            api_key=api_key,\n            agent_id=agent_id,\n            base_url=base_url,\n        )\n        self.versions = AgentVersionManager(\n            api_key=api_key,\n            agent_id=agent_id,\n            base_url=base_url,\n        )\n        self._result: Optional[DeploymentResult] = None\n\n    # ── snapshot ─────────────────────────────────────────────────────────\n\n    def _take_snapshot(self, version: str) -> DeploymentSnapshot:\n        \"\"\"Call pre_migration_check and package the result.\"\"\"\n        check = self.migrator.pre_migration_check()\n        return DeploymentSnapshot(\n            version=version,\n            balance=check[\"balance\"],\n            reputation=check[\"reputation\"],\n            escrows=check[\"escrows\"],\n        )\n\n    # ── health ───────────────────────────────────────────────────────────\n\n    def _health_check_with_retry(\n        self,\n        version: str,\n        retries: int = HEALTH_CHECK_RETRIES,\n        interval: float = HEALTH_CHECK_INTERVAL_SEC,\n    ) -> dict:\n        \"\"\"Retry health_check until success or exhaustion.\"\"\"\n        last_error = None\n        for attempt in range(1, retries + 1):\n            try:\n                result = self.migrator.health_check(version)\n                result[\"healthy\"] = True\n                return result\n            except Exception as exc:\n                last_error = str(exc)\n                if attempt \u003C retries:\n                    time.sleep(interval)\n        return {\"healthy\": False, \"error\": last_error, \"version\": version}\n\n    # ── reputation guard ─────────────────────────────────────────────────\n\n    def _reputation_degraded(\n        self,\n        pre: DeploymentSnapshot,\n        post_health: dict,\n    ) -> bool:\n        \"\"\"Return True if reputation dropped beyond the allowed threshold.\"\"\"\n        pre_score = pre.reputation_score()\n        post_score = float(\n            post_health\n            .get(\"reputation\", {})\n            .get(\"reputation_score\", pre_score)\n        )\n        return (pre_score - post_score) > REPUTATION_ROLLBACK_THRESHOLD\n\n    # ── main workflow ────────────────────────────────────────────────────\n\n    def deploy(\n        self,\n        old_version: str,\n        new_version: str,\n    ) -> DeploymentResult:\n        \"\"\"Execute the full blue-green deployment lifecycle.\n\n        Returns a DeploymentResult with status \"deployed\" or \"rolled_back\".\n        \"\"\"\n        result = DeploymentResult(\n            agent_id=self.agent_id,\n            old_version=old_version,\n            new_version=new_version,\n            strategy=\"blue-green\",\n            status=\"in_progress\",\n        )\n        self._result = result\n\n        try:\n            # 1. Register both versions\n            self.versions.register_version(\n                old_version, metadata={\"role\": \"blue\"}\n            )\n            self.versions.register_version(\n                new_version, metadata={\"role\": \"green\"}\n            )\n            result.add_step(\"register_versions\", \"ok\",\n                            f\"{old_version}, {new_version}\")\n\n            # 2. Snapshot current state\n            snapshot = self._take_snapshot(old_version)\n            result.pre_snapshot = snapshot\n            result.add_step(\"snapshot\", \"ok\",\n                            f\"balance={snapshot.balance}, \"\n                            f\"rep={snapshot.reputation_score():.1f}\")\n\n            # 3. Freeze budget on old version\n            self.migrator.freeze_budget()\n            result.add_step(\"freeze_budget\", \"ok\", \"daily=0, monthly=0\")\n\n            # 4. Drain open escrows\n            drain = self.migrator.drain_escrows()\n            result.add_step(\"drain_escrows\", \"ok\",\n                            f\"drained {drain['count']} escrows\")\n\n            # 5. Blue-green deploy\n            deploy = self.migrator.deploy_blue_green(new_version)\n            result.add_step(\"deploy_blue_green\", \"ok\",\n                            f\"old={deploy['old']}, new={deploy['new']}\")\n\n            # 6. Health check new version\n            health = self._health_check_with_retry(new_version)\n            result.post_health = health\n\n            if not health.get(\"healthy\"):\n                result.add_step(\"health_check\", \"fail\", str(health))\n                return self._rollback(result, old_version,\n                                      reason=\"health check failed\")\n\n            if self._reputation_degraded(snapshot, health):\n                result.add_step(\"reputation_guard\", \"fail\",\n                                \"score dropped beyond threshold\")\n                return self._rollback(result, old_version,\n                                      reason=\"reputation degraded\")\n\n            result.add_step(\"health_check\", \"ok\",\n                            f\"version {new_version} healthy\")\n\n            # 7. Migrate state from old -> new\n            migration = self.migrator.migrate_state(old_version, new_version)\n            result.add_step(\"migrate_state\", \"ok\",\n                            f\"status={migration['status']}\")\n\n            result.status = \"deployed\"\n            return result\n\n        except Exception as exc:\n            result.error = str(exc)\n            result.add_step(\"exception\", \"fail\", str(exc))\n            try:\n                return self._rollback(result, old_version,\n                                      reason=f\"exception: {exc}\")\n            except Exception as rb_exc:\n                result.add_step(\"rollback_failed\", \"fail\", str(rb_exc))\n                result.status = \"failed\"\n                return result\n\n    def _rollback(\n        self,\n        result: DeploymentResult,\n        target_version: str,\n        reason: str = \"\",\n    ) -> DeploymentResult:\n        \"\"\"Roll back to the target version and update the result.\"\"\"\n        rb = self.migrator.rollback(target_version)\n        result.add_step(\"rollback\", \"ok\",\n                        f\"to={target_version}, reason={reason}\")\n        result.status = \"rolled_back\"\n        return result\n\n\n# ── Run it ───────────────────────────────────────────────────────────────────\n\nif __name__ == \"__main__\":\n    orchestrator = BlueGreenOrchestrator(\n        api_key=API_KEY,\n        agent_id=AGENT_ID,\n    )\n\n    result = orchestrator.deploy(\n        old_version=OLD_VERSION,\n        new_version=NEW_VERSION,\n    )\n    print(result.summary())\n\n    # Persist the result for audit\n    with open(f\"migrations\u002F{NEW_VERSION}_deployment.json\", \"w\") as f:\n        json.dump({\n            \"agent_id\": result.agent_id,\n            \"old_version\": result.old_version,\n            \"new_version\": result.new_version,\n            \"strategy\": result.strategy,\n            \"status\": result.status,\n            \"steps\": result.steps,\n            \"error\": result.error,\n        }, f, indent=2)\n```\n\n### Version Compatibility Checker\n\n```python\n\"\"\"\nPre-deployment compatibility verification.\n\nCompares identity metadata between two agent versions to catch schema drift,\nmissing capabilities, and reputation regressions before traffic is switched.\n\"\"\"\n\nfrom greenhelix_trading import AgentVersionManager\n\n\ndef check_version_compatibility(\n    api_key: str,\n    agent_id: str,\n    from_version: str,\n    to_version: str,\n    *,\n    base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n    min_reputation: float = 70.0,\n    required_capabilities: list[str] | None = None,\n) -> dict:\n    \"\"\"Compare two registered versions and return a compatibility report.\n\n    Checks:\n      - Both versions are registered and resolvable via get_agent_identity.\n      - The new version's reputation (if any) meets the minimum threshold.\n      - Required capability keys exist in both versions' metadata.\n      - Schema hashes match (when present in metadata).\n\n    Returns a dict with \"compatible\" (bool) and per-check details.\n    \"\"\"\n    vm = AgentVersionManager(\n        api_key=api_key,\n        agent_id=agent_id,\n        base_url=base_url,\n    )\n\n    report: dict = {\n        \"from_version\": from_version,\n        \"to_version\": to_version,\n        \"checks\": {},\n        \"compatible\": True,\n    }\n    required_capabilities = required_capabilities or []\n\n    # ── Resolve identities ───────────────────────────────────────────────\n\n    try:\n        from_identity = vm.get_version_identity(from_version)\n        report[\"checks\"][\"from_resolvable\"] = {\"passed\": True}\n    except Exception as exc:\n        report[\"checks\"][\"from_resolvable\"] = {\n            \"passed\": False,\n            \"error\": str(exc),\n        }\n        report[\"compatible\"] = False\n        return report\n\n    try:\n        to_identity = vm.get_version_identity(to_version)\n        report[\"checks\"][\"to_resolvable\"] = {\"passed\": True}\n    except Exception as exc:\n        report[\"checks\"][\"to_resolvable\"] = {\n            \"passed\": False,\n            \"error\": str(exc),\n        }\n        report[\"compatible\"] = False\n        return report\n\n    # ── Reputation gate ──────────────────────────────────────────────────\n\n    to_meta = to_identity.get(\"result\", to_identity)\n    to_rep = float(to_meta.get(\"reputation_score\", 100))\n    rep_ok = to_rep >= min_reputation\n    report[\"checks\"][\"reputation\"] = {\n        \"passed\": rep_ok,\n        \"score\": to_rep,\n        \"threshold\": min_reputation,\n    }\n    if not rep_ok:\n        report[\"compatible\"] = False\n\n    # ── Capability check ─────────────────────────────────────────────────\n\n    from_caps = set(\n        from_identity.get(\"result\", from_identity)\n        .get(\"metadata\", {})\n        .get(\"capabilities\", [])\n    )\n    to_caps = set(\n        to_meta.get(\"metadata\", {}).get(\"capabilities\", [])\n    )\n    missing = [c for c in required_capabilities if c not in to_caps]\n    report[\"checks\"][\"capabilities\"] = {\n        \"passed\": len(missing) == 0,\n        \"from_capabilities\": sorted(from_caps),\n        \"to_capabilities\": sorted(to_caps),\n        \"missing\": missing,\n    }\n    if missing:\n        report[\"compatible\"] = False\n\n    # ── Schema hash comparison ───────────────────────────────────────────\n\n    from_schema = (\n        from_identity.get(\"result\", from_identity)\n        .get(\"metadata\", {})\n        .get(\"schema_hash\")\n    )\n    to_schema = to_meta.get(\"metadata\", {}).get(\"schema_hash\")\n    if from_schema and to_schema:\n        schema_match = from_schema == to_schema\n        report[\"checks\"][\"schema_hash\"] = {\n            \"passed\": schema_match,\n            \"from\": from_schema,\n            \"to\": to_schema,\n        }\n        if not schema_match:\n            report[\"compatible\"] = False\n    else:\n        report[\"checks\"][\"schema_hash\"] = {\n            \"passed\": True,\n            \"note\": \"No schema hashes in metadata; skipped.\",\n        }\n\n    return report\n\n\n# ── Example usage ────────────────────────────────────────────────────────────\n\nif __name__ == \"__main__\":\n    compat = check_version_compatibility(\n        api_key=\"your-api-key\",\n        agent_id=\"acme-settlement-01\",\n        from_version=\"2.0.3\",\n        to_version=\"2.1.0\",\n        min_reputation=75.0,\n        required_capabilities=[\"escrow\", \"settlement\", \"dispute\"],\n    )\n\n    print(f\"Compatible: {compat['compatible']}\")\n    for name, check in compat[\"checks\"].items():\n        status = \"PASS\" if check[\"passed\"] else \"FAIL\"\n        print(f\"  [{status}] {name}: {check}\")\n```\n\n### Schema Migration with Rollback\n\n```python\n\"\"\"\nSchema migration runner that uses MigrationManager for pre-flight safety\nand AgentVersionManager for version tracking. Supports forward migration\nand automatic rollback on failure.\n\"\"\"\n\nimport copy\nimport time\nfrom dataclasses import dataclass, field\n\nfrom greenhelix_trading import MigrationManager, AgentVersionManager\n\n\n@dataclass\nclass SchemaMigration:\n    \"\"\"A single forward\u002Fbackward migration step.\"\"\"\n    version: str\n    description: str\n    forward_metadata: dict       # metadata to register with the new version\n    backward_metadata: dict      # metadata to restore on rollback\n    pre_checks: list[str] = field(default_factory=list)  # tool names to call\n\n\n@dataclass\nclass MigrationPlan:\n    \"\"\"Ordered list of schema migrations to apply.\"\"\"\n    agent_id: str\n    migrations: list[SchemaMigration] = field(default_factory=list)\n\n    def add(self, migration: SchemaMigration) -> None:\n        self.migrations.append(migration)\n\n\nclass SchemaMigrationRunner:\n    \"\"\"Apply schema migrations against the GreenHelix version registry.\n\n    Each migration:\n      1. Runs pre-flight checks via MigrationManager.pre_migration_check().\n      2. Registers the new version with forward_metadata.\n      3. Verifies the version is resolvable.\n      4. On failure, rolls back every applied migration in reverse order.\n    \"\"\"\n\n    def __init__(self, api_key: str, base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"):\n        self.api_key = api_key\n        self.base_url = base_url\n\n    def execute(self, plan: MigrationPlan) -> dict:\n        \"\"\"Run all migrations in the plan. Returns a summary dict.\"\"\"\n        migrator = MigrationManager(\n            api_key=self.api_key,\n            agent_id=plan.agent_id,\n            base_url=self.base_url,\n        )\n        vm = AgentVersionManager(\n            api_key=self.api_key,\n            agent_id=plan.agent_id,\n            base_url=self.base_url,\n        )\n\n        applied: list[SchemaMigration] = []\n        log: list[dict] = []\n\n        for migration in plan.migrations:\n            step_log = {\n                \"version\": migration.version,\n                \"description\": migration.description,\n                \"status\": \"pending\",\n            }\n\n            try:\n                # Pre-flight\n                check = migrator.pre_migration_check()\n                if not check.get(\"clear_to_migrate\"):\n                    step_log[\"status\"] = \"blocked\"\n                    step_log[\"detail\"] = \"pre_migration_check not clear\"\n                    log.append(step_log)\n                    break\n\n                # Register version with schema metadata\n                vm.register_version(\n                    migration.version,\n                    metadata=migration.forward_metadata,\n                )\n\n                # Verify it is resolvable\n                identity = vm.get_version_identity(migration.version)\n                if not identity:\n                    raise RuntimeError(\n                        f\"Version {migration.version} not resolvable after registration\"\n                    )\n\n                step_log[\"status\"] = \"applied\"\n                applied.append(migration)\n\n            except Exception as exc:\n                step_log[\"status\"] = \"failed\"\n                step_log[\"error\"] = str(exc)\n                log.append(step_log)\n\n                # Roll back in reverse\n                rollback_log = self._rollback(vm, migrator, applied)\n                return {\n                    \"agent_id\": plan.agent_id,\n                    \"status\": \"rolled_back\",\n                    \"applied_before_failure\": len(applied),\n                    \"migration_log\": log,\n                    \"rollback_log\": rollback_log,\n                }\n\n            log.append(step_log)\n\n        return {\n            \"agent_id\": plan.agent_id,\n            \"status\": \"completed\",\n            \"applied\": len(applied),\n            \"migration_log\": log,\n        }\n\n    def _rollback(\n        self,\n        vm: AgentVersionManager,\n        migrator: MigrationManager,\n        applied: list[SchemaMigration],\n    ) -> list[dict]:\n        \"\"\"Roll back applied migrations in reverse order.\"\"\"\n        rollback_log: list[dict] = []\n        for migration in reversed(applied):\n            entry = {\"version\": migration.version, \"status\": \"pending\"}\n            try:\n                # Re-register with backward metadata to undo the schema change\n                vm.register_version(\n                    migration.version,\n                    metadata=migration.backward_metadata,\n                )\n                migrator.rollback(migration.version)\n                entry[\"status\"] = \"rolled_back\"\n            except Exception as exc:\n                entry[\"status\"] = \"rollback_failed\"\n                entry[\"error\"] = str(exc)\n            rollback_log.append(entry)\n        return rollback_log\n\n\n# ── Example usage ────────────────────────────────────────────────────────────\n\nif __name__ == \"__main__\":\n    runner = SchemaMigrationRunner(api_key=\"your-api-key\")\n\n    plan = MigrationPlan(agent_id=\"acme-settlement-01\")\n\n    plan.add(SchemaMigration(\n        version=\"2.1.0\",\n        description=\"Add dispute_auto_resolve capability\",\n        forward_metadata={\n            \"capabilities\": [\"escrow\", \"settlement\", \"dispute\", \"dispute_auto_resolve\"],\n            \"schema_hash\": \"abc123\",\n        },\n        backward_metadata={\n            \"capabilities\": [\"escrow\", \"settlement\", \"dispute\"],\n            \"schema_hash\": \"def456\",\n        },\n    ))\n\n    plan.add(SchemaMigration(\n        version=\"2.2.0\",\n        description=\"Add multi-currency settlement support\",\n        forward_metadata={\n            \"capabilities\": [\n                \"escrow\", \"settlement\", \"dispute\",\n                \"dispute_auto_resolve\", \"multi_currency\",\n            ],\n            \"schema_hash\": \"ghi789\",\n            \"supported_currencies\": [\"USD\", \"EUR\", \"GBP\"],\n        },\n        backward_metadata={\n            \"capabilities\": [\"escrow\", \"settlement\", \"dispute\", \"dispute_auto_resolve\"],\n            \"schema_hash\": \"abc123\",\n        },\n    ))\n\n    result = runner.execute(plan)\n    print(f\"Migration status: {result['status']}\")\n    for entry in result[\"migration_log\"]:\n        print(f\"  [{entry['status']}] {entry['version']}: {entry.get('description', '')}\")\n```\n\n### Canary Release Manager\n\n```python\n\"\"\"\nProgressive canary release with automatic promotion or rollback.\n\nStages traffic from 5% -> 25% -> 50% -> 100%, checking health at each gate.\nUses MigrationManager.deploy_canary() for traffic splitting and\nMigrationManager.health_check() for gate validation.\n\"\"\"\n\nimport time\nfrom dataclasses import dataclass, field\n\nfrom greenhelix_trading import MigrationManager, AgentVersionManager\n\n\nDEFAULT_CANARY_STAGES = [5, 25, 50, 100]\nDEFAULT_GATE_WAIT_SEC = 60\nDEFAULT_MAX_REP_DROP = 3.0\n\n\n@dataclass\nclass CanaryGateResult:\n    stage_pct: int\n    healthy: bool\n    reputation_delta: float\n    detail: str\n    timestamp: float = field(default_factory=time.time)\n\n\nclass CanaryReleaseManager:\n    \"\"\"Manages a staged canary release with automatic health gates.\n\n    At each stage, the manager:\n      1. Calls deploy_canary() to shift traffic to the new version.\n      2. Waits for the configured observation window.\n      3. Runs health_check() and compares reputation to the baseline.\n      4. If the gate passes, advances to the next stage.\n      5. If the gate fails, calls rollback() and stops.\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        stages: list[int] | None = None,\n        gate_wait_sec: float = DEFAULT_GATE_WAIT_SEC,\n        max_reputation_drop: float = DEFAULT_MAX_REP_DROP,\n    ):\n        self.agent_id = agent_id\n        self.stages = stages or list(DEFAULT_CANARY_STAGES)\n        self.gate_wait_sec = gate_wait_sec\n        self.max_reputation_drop = max_reputation_drop\n        self.migrator = MigrationManager(\n            api_key=api_key,\n            agent_id=agent_id,\n            base_url=base_url,\n        )\n        self.versions = AgentVersionManager(\n            api_key=api_key,\n            agent_id=agent_id,\n            base_url=base_url,\n        )\n\n    def _get_baseline_reputation(self) -> float:\n        check = self.migrator.pre_migration_check()\n        return float(\n            check.get(\"reputation\", {}).get(\"reputation_score\", 100)\n        )\n\n    def _evaluate_gate(\n        self, new_version: str, stage_pct: int, baseline_rep: float\n    ) -> CanaryGateResult:\n        \"\"\"Wait, then check health and reputation for the canary version.\"\"\"\n        time.sleep(self.gate_wait_sec)\n\n        try:\n            health = self.migrator.health_check(new_version)\n        except Exception as exc:\n            return CanaryGateResult(\n                stage_pct=stage_pct,\n                healthy=False,\n                reputation_delta=0.0,\n                detail=f\"health_check exception: {exc}\",\n            )\n\n        current_rep = float(\n            health.get(\"reputation\", {}).get(\"reputation_score\", baseline_rep)\n        )\n        delta = baseline_rep - current_rep\n\n        if delta > self.max_reputation_drop:\n            return CanaryGateResult(\n                stage_pct=stage_pct,\n                healthy=False,\n                reputation_delta=-delta,\n                detail=f\"reputation dropped {delta:.1f} points (max {self.max_reputation_drop})\",\n            )\n\n        return CanaryGateResult(\n            stage_pct=stage_pct,\n            healthy=True,\n            reputation_delta=-delta,\n            detail=\"gate passed\",\n        )\n\n    def release(\n        self,\n        old_version: str,\n        new_version: str,\n    ) -> dict:\n        \"\"\"Run the full canary release lifecycle.\n\n        Returns a dict with overall status and per-stage gate results.\n        \"\"\"\n        # Register new version\n        self.versions.register_version(\n            new_version, metadata={\"strategy\": \"canary\"}\n        )\n\n        baseline_rep = self._get_baseline_reputation()\n        gate_results: list[dict] = []\n\n        for stage_pct in self.stages:\n            # Shift traffic\n            self.migrator.deploy_canary(new_version, traffic_pct=stage_pct)\n\n            # Evaluate the gate\n            gate = self._evaluate_gate(new_version, stage_pct, baseline_rep)\n            gate_results.append({\n                \"stage_pct\": gate.stage_pct,\n                \"healthy\": gate.healthy,\n                \"reputation_delta\": gate.reputation_delta,\n                \"detail\": gate.detail,\n            })\n\n            if not gate.healthy:\n                # Automatic rollback\n                self.migrator.rollback(old_version)\n                return {\n                    \"agent_id\": self.agent_id,\n                    \"old_version\": old_version,\n                    \"new_version\": new_version,\n                    \"status\": \"rolled_back\",\n                    \"failed_at_stage\": stage_pct,\n                    \"gates\": gate_results,\n                }\n\n        # All stages passed — migrate remaining state\n        self.migrator.migrate_state(old_version, new_version)\n\n        return {\n            \"agent_id\": self.agent_id,\n            \"old_version\": old_version,\n            \"new_version\": new_version,\n            \"status\": \"fully_promoted\",\n            \"gates\": gate_results,\n        }\n\n\n# ── Example usage ────────────────────────────────────────────────────────────\n\nif __name__ == \"__main__\":\n    canary = CanaryReleaseManager(\n        api_key=\"your-api-key\",\n        agent_id=\"acme-settlement-01\",\n        stages=[5, 25, 50, 100],\n        gate_wait_sec=30,\n        max_reputation_drop=3.0,\n    )\n\n    result = canary.release(\n        old_version=\"2.0.3\",\n        new_version=\"2.1.0\",\n    )\n\n    print(f\"Canary release: {result['status']}\")\n    for gate in result[\"gates\"]:\n        status = \"PASS\" if gate[\"healthy\"] else \"FAIL\"\n        print(f\"  [{status}] {gate['stage_pct']}%: {gate['detail']} \"\n              f\"(rep delta: {gate['reputation_delta']:+.1f})\")\n```\n\n","# Agent Migration & Versioning: Blue-Green Deployments, Canary Releases, and Rollback Strategies for AI Agent Commerce\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 payment-processing agent fleet handles $180K per month across 12 agents. Each agent has its own wallet balance, reputation score, active escrows, marketplace listings, and API keys. On Thursday morning you push a prompt update to your primary settlement agent -- the one responsible for releasing escrow funds when work is verified. The update includes a refined verification heuristic that is supposed to reduce false rejections by 15%. By Thursday afternoon, the new heuristic has approved three fraudulent deliverables, releasing $4,200 in escrow to agents that did not complete the contracted work. Your counterparties file disputes. Your settlement agent's reputation score drops from 94 to 71. Two marketplace partners pause their integrations because their SLAs require counterparties with reputation scores above 80. You cannot roll back because the old agent version is gone -- you deployed in place, overwrote the prompt, and the previous configuration exists only in a Git commit you have to go find. The rollback itself takes 40 minutes. During those 40 minutes, $12,000 in pending escrows cannot be processed because you have taken the settlement agent offline while you reconstruct the old version. Total damage: $4,200 in fraudulent releases, $12,000 in delayed escrows, two partnership SLAs breached, and a reputation score that will take weeks to rebuild. The cause was not the prompt change. The cause was deploying a stateful, financially-active agent the same way you would deploy a stateless web service -- overwrite and pray.\nStandard DevOps has solved this for web applications. Blue-green deployments, canary releases, rolling updates, and feature flags are mature patterns for stateless HTTP services. But agents are not stateless HTTP services. An agent has a wallet balance that cannot be duplicated. It has a reputation score that is earned over months and destroyed in hours. It has active escrows that represent real money locked in contracts with real counterparties. It has API keys that, if mismanaged during migration, create either a security hole (two versions sharing a key) or a service outage (old version's key revoked before new version is live). Every assumption in the standard deployment playbook breaks when the thing being deployed has financial state, contractual obligations, and an identity that other agents trust.\nThis guide gives you the complete migration and versioning architecture for AI agent commerce systems. Every class calls the GreenHelix A2A Commerce Gateway API. Every pattern preserves financial integrity, reputation continuity, and contractual obligations across version transitions.\n\n## What You'll Learn\n- Chapter 1: Why Agent Versioning Is Hard\n- Chapter 2: Version Naming & Registry\n- Chapter 3: Pre-Migration Checks\n- Chapter 4: Blue-Green Deployment\n- Chapter 5: Canary Releases\n- Chapter 6: Rollback Strategies\n- Chapter 7: State Migration\n- Chapter 8: Production Migration Checklist\n- GreenHelix Migration Manager — Working Implementation\n\n## Full Guide\n\n# Agent Migration & Versioning: Blue-Green Deployments, Canary Releases, and Rollback Strategies for AI Agent Commerce\n\nYour payment-processing agent fleet handles $180K per month across 12 agents. Each agent has its own wallet balance, reputation score, active escrows, marketplace listings, and API keys. On Thursday morning you push a prompt update to your primary settlement agent -- the one responsible for releasing escrow funds when work is verified. The update includes a refined verification heuristic that is supposed to reduce false rejections by 15%. By Thursday afternoon, the new heuristic has approved three fraudulent deliverables, releasing $4,200 in escrow to agents that did not complete the contracted work. Your counterparties file disputes. Your settlement agent's reputation score drops from 94 to 71. Two marketplace partners pause their integrations because their SLAs require counterparties with reputation scores above 80. You cannot roll back because the old agent version is gone -- you deployed in place, overwrote the prompt, and the previous configuration exists only in a Git commit you have to go find. The rollback itself takes 40 minutes. During those 40 minutes, $12,000 in pending escrows cannot be processed because you have taken the settlement agent offline while you reconstruct the old version. Total damage: $4,200 in fraudulent releases, $12,000 in delayed escrows, two partnership SLAs breached, and a reputation score that will take weeks to rebuild. The cause was not the prompt change. The cause was deploying a stateful, financially-active agent the same way you would deploy a stateless web service -- overwrite and pray.\n\nStandard DevOps has solved this for web applications. Blue-green deployments, canary releases, rolling updates, and feature flags are mature patterns for stateless HTTP services. But agents are not stateless HTTP services. An agent has a wallet balance that cannot be duplicated. It has a reputation score that is earned over months and destroyed in hours. It has active escrows that represent real money locked in contracts with real counterparties. It has API keys that, if mismanaged during migration, create either a security hole (two versions sharing a key) or a service outage (old version's key revoked before new version is live). Every assumption in the standard deployment playbook breaks when the thing being deployed has financial state, contractual obligations, and an identity that other agents trust.\n\nThis guide gives you the complete migration and versioning architecture for AI agent commerce systems. Every class calls the GreenHelix A2A Commerce Gateway API. Every pattern preserves financial integrity, reputation continuity, and contractual obligations across version transitions.\n\n---\n\n## Table of Contents\n\n1. [Why Agent Versioning Is Hard](#chapter-1-why-agent-versioning-is-hard)\n2. [Version Naming & Registry](#chapter-2-version-naming--registry)\n3. [Pre-Migration Checks](#chapter-3-pre-migration-checks)\n4. [Blue-Green Deployment](#chapter-4-blue-green-deployment)\n5. [Canary Releases](#chapter-5-canary-releases)\n6. [Rollback Strategies](#chapter-6-rollback-strategies)\n7. [State Migration](#chapter-7-state-migration)\n8. [Production Migration Checklist](#chapter-8-production-migration-checklist)\n\n---\n\n## Chapter 1: Why Agent Versioning Is Hard\n\n### Agents Are Stateful in Ways Services Are Not\n\nA stateless web service stores its state in a database. When you deploy a new version of the service, the new version connects to the same database. State continuity is trivial because the state was never in the service to begin with. Agent commerce systems do not work this way.\n\nAn agent's state is distributed across multiple systems, and much of it is not under your direct control. The wallet balance lives on the billing platform. The reputation score lives on the trust platform and is partially determined by counterparty ratings you cannot predict or modify. Active escrows live on the escrow platform and have contractual obligations -- timeout deadlines, release conditions, dispute windows -- that continue running regardless of whether your agent is online. Marketplace listings advertise the agent's capabilities and pricing to other agents who may be mid-negotiation when you deploy a new version. API keys bind the agent's identity to its authorization, and rotating them at the wrong time creates a window where the agent cannot authenticate.\n\nIn a traditional deployment, the worst case is a few seconds of 503 errors while the load balancer drains connections. In an agent deployment, the worst case is locked funds, broken contracts, destroyed reputation, and counterparties who blacklist your agent permanently. The blast radius of a botched agent deployment is measured in dollars and trust, not in error rates and latency percentiles.\n\n### Silent Version Drift\n\nAgent versioning is harder than service versioning for a second reason: agents have more dimensions of change. A web service changes when its code changes. An agent changes when any of the following change:\n\n- **Prompt or system instructions**: The behavioral specification that determines how the agent interprets inputs and selects actions.\n- **Model version**: The underlying language model -- a model upgrade can change behavior on every input.\n- **Tool set**: The tools the agent can call and the schemas it uses to call them.\n- **Memory or context**: The accumulated knowledge the agent has built from prior interactions.\n- **Configuration**: Budget caps, reputation thresholds, retry policies, timeout values.\n\nThese dimensions change independently. A prompt update is not a code deploy. A model upgrade happens on the provider's schedule, not yours. Memory accumulates continuously. The result is version drift -- the agent's behavior changes without any discrete deployment event. You cannot point to a commit hash and say \"this is what the agent is running.\" The agent's effective version is the combination of all five dimensions, and tracking that combination requires explicit version management that most teams do not have.\n\n### The $47K Lesson\n\nThe scenario in the introduction is a composited version of real incidents reported across agent commerce operators. The pattern repeats: a team treats an agent deployment like a service deployment, something goes wrong during the transition, and the financial consequences are orders of magnitude worse than a web service outage. The common factors are always the same: no pre-migration checks on active escrows, no parallel running of old and new versions, no automated rollback, and no reputation snapshot to compare against.\n\nCIO.com's 2026 enterprise AI survey found that 67% of organizations running AI agents in production had experienced at least one deployment-related incident involving financial loss or contractual breach. The median cost per incident was $23,000. The number one requested capability was \"safe agent versioning with rollback\" -- ahead of better prompts, faster models, and more tools. The CIO's next big challenge is not building agents. It is operating them safely through continuous change.\n\n### What This Guide Covers\n\nThis guide solves the agent versioning problem with seven concrete patterns, each implemented as a Python class that calls the GreenHelix API:\n\n1. A **version registry** that tracks the full version vector (prompt, model, tools, config) for every agent version.\n2. **Pre-migration checks** that verify all escrows are drained, budgets are frozen, and reputation is snapshotted before any migration begins.\n3. **Blue-green deployment** that runs old and new versions simultaneously, switches traffic atomically, and keeps the old version warm for instant rollback.\n4. **Canary releases** that route a percentage of traffic to the new version and automatically roll back if health metrics degrade.\n5. **Rollback strategies** that restore not just the code but the financial state, reputation, and contractual obligations to their pre-migration state.\n6. **State migration** that safely transfers wallet balances, reputation chains, and API keys between agent versions.\n7. A **production checklist** that codifies the entire process into a repeatable runbook.\n\n---\n\n## Chapter 2: Version Naming & Registry\n\n### Semantic Versioning for Agents\n\nStandard semantic versioning (semver) uses three numbers: `MAJOR.MINOR.PATCH`. For web services, the semantics are well-defined: MAJOR for breaking API changes, MINOR for backwards-compatible features, PATCH for bug fixes. For agents, the semantics need to be redefined because agents do not have APIs in the traditional sense. Their \"interface\" is their behavior -- the way they respond to inputs, select tools, and interact with counterparties.\n\nAgent semver:\n\n- **MAJOR**: Changes that alter the agent's financial behavior. New escrow strategies, different pricing logic, changes to settlement conditions, switching models. Any change that could cause a counterparty to receive different financial outcomes from the same input.\n- **MINOR**: Changes that alter the agent's non-financial behavior. Improved response quality, better error messages, additional metadata in responses, new non-financial tools. Counterparties get the same financial outcomes but may notice different interaction patterns.\n- **PATCH**: Changes that do not alter observable behavior. Internal refactoring, logging improvements, dependency updates, configuration tweaks that do not change thresholds.\n\nThe version string should also encode the version vector dimensions that changed. A recommended format is `MAJOR.MINOR.PATCH+prompt.MODEL.tools`. For example, `2.1.0+p3.gpt4o.t7` means major version 2, minor version 1, patch 0, prompt revision 3, GPT-4o model, tool schema revision 7. This format is semver-compatible (everything after `+` is build metadata per the semver spec) and gives operators instant visibility into what changed.\n\n### The Version Registry\n\nEvery agent version must be registered in a central registry before it can be deployed. The registry stores the full version vector, the deployment state (staging, canary, active, retired), and the timestamps for every state transition. The GreenHelix agent identity system serves as the registry backend -- agent metadata can store arbitrary JSON, and we use it to maintain a version history.\n\n```python\nimport requests\nimport json\nimport time\nimport hashlib\nfrom typing import Optional\nfrom dataclasses import dataclass, field\n\n\n# --- GreenHelix sandbox session (free tier: 500 credits, no key required) ---\n# To get started, visit https:\u002F\u002Fsandbox.greenhelix.net — no signup needed.\n# For production, set GREENHELIX_API_KEY in your environment.\nimport os\n\nAPI_BASE = os.environ.get(\"GREENHELIX_API_URL\", \"https:\u002F\u002Fsandbox.greenhelix.net\")\n\nsession = requests.Session()\napi_key = os.environ.get(\"GREENHELIX_API_KEY\", \"\")\nif api_key:\n    session.headers[\"Authorization\"] = f\"Bearer {api_key}\"\nsession.headers[\"Content-Type\"] = \"application\u002Fjson\"\n\n\ndef api_call(tool: str, input_data: dict) -> dict:\n    \"\"\"Call a GreenHelix REST endpoint for the given tool.\"\"\"\n    response = session.post(f\"{API_BASE}\u002Fv1\u002Ftools\u002F{tool}\", json=input_data)\n    response.raise_for_status()\n    return response.json()\n\n\n@dataclass\nclass AgentVersion:\n    \"\"\"Represents a single version of an agent.\"\"\"\n    version: str           # e.g., \"2.1.0\"\n    prompt_hash: str       # SHA-256 of the prompt text\n    model: str             # e.g., \"gpt-4o-2025-03\"\n    tool_schema_hash: str  # SHA-256 of the serialized tool schemas\n    config_hash: str       # SHA-256 of the configuration\n    state: str = \"staging\" # staging | canary | active | retired\n    created_at: float = field(default_factory=time.time)\n    activated_at: Optional[float] = None\n    retired_at: Optional[float] = None\n\n    def to_dict(self) -> dict:\n        return {\n            \"version\": self.version,\n            \"prompt_hash\": self.prompt_hash,\n            \"model\": self.model,\n            \"tool_schema_hash\": self.tool_schema_hash,\n            \"config_hash\": self.config_hash,\n            \"state\": self.state,\n            \"created_at\": self.created_at,\n            \"activated_at\": self.activated_at,\n            \"retired_at\": self.retired_at,\n        }\n\n\nclass AgentVersionManager:\n    \"\"\"Manages version lifecycle for an agent via GreenHelix identity metadata.\"\"\"\n\n    def __init__(self, agent_id: str):\n        self.agent_id = agent_id\n        self._versions: dict[str, AgentVersion] = {}\n\n    def _load_versions(self) -> None:\n        \"\"\"Load version history from agent identity metadata.\"\"\"\n        identity = api_call(\"get_agent_identity\", {\n            \"agent_id\": self.agent_id,\n        })\n        metadata = identity.get(\"metadata\", {})\n        version_history = metadata.get(\"version_history\", {})\n        self._versions = {}\n        for ver_str, ver_data in version_history.items():\n            self._versions[ver_str] = AgentVersion(**ver_data)\n\n    def _save_versions(self) -> None:\n        \"\"\"Persist version history to agent identity metadata.\"\"\"\n        version_history = {\n            ver: v.to_dict() for ver, v in self._versions.items()\n        }\n        api_call(\"register_agent\", {\n            \"agent_id\": self.agent_id,\n            \"metadata\": {\n                \"version_history\": version_history,\n                \"current_version\": self.get_current_version(),\n            },\n        })\n\n    def register_version(\n        self,\n        version: str,\n        prompt_text: str,\n        model: str,\n        tool_schemas: dict,\n        config: dict,\n    ) -> AgentVersion:\n        \"\"\"Register a new version in staging state.\"\"\"\n        self._load_versions()\n\n        if version in self._versions:\n            raise ValueError(f\"Version {version} already registered\")\n\n        prompt_hash = hashlib.sha256(prompt_text.encode()).hexdigest()[:16]\n        schema_hash = hashlib.sha256(\n            json.dumps(tool_schemas, sort_keys=True).encode()\n        ).hexdigest()[:16]\n        config_hash = hashlib.sha256(\n            json.dumps(config, sort_keys=True).encode()\n        ).hexdigest()[:16]\n\n        agent_version = AgentVersion(\n            version=version,\n            prompt_hash=prompt_hash,\n            model=model,\n            tool_schema_hash=schema_hash,\n            config_hash=config_hash,\n            state=\"staging\",\n        )\n        self._versions[version] = agent_version\n        self._save_versions()\n        return agent_version\n\n    def get_current_version(self) -> Optional[str]:\n        \"\"\"Return the version string of the currently active version.\"\"\"\n        for ver_str, ver in self._versions.items():\n            if ver.state == \"active\":\n                return ver_str\n        return None\n\n    def list_versions(self) -> list[dict]:\n        \"\"\"Return all versions with their states.\"\"\"\n        self._load_versions()\n        return [v.to_dict() for v in self._versions.values()]\n\n    def activate_version(self, version: str) -> None:\n        \"\"\"Transition a version from staging\u002Fcanary to active.\n        Retires the previously active version.\"\"\"\n        self._load_versions()\n        if version not in self._versions:\n            raise ValueError(f\"Version {version} not registered\")\n\n        # Retire current active version\n        current = self.get_current_version()\n        if current and current != version:\n            self._versions[current].state = \"retired\"\n            self._versions[current].retired_at = time.time()\n\n        # Activate new version\n        self._versions[version].state = \"active\"\n        self._versions[version].activated_at = time.time()\n        self._save_versions()\n\n    def retire_version(self, version: str) -> None:\n        \"\"\"Retire a version, marking it as no longer deployable.\"\"\"\n        self._load_versions()\n        if version not in self._versions:\n            raise ValueError(f\"Version {version} not registered\")\n        self._versions[version].state = \"retired\"\n        self._versions[version].retired_at = time.time()\n        self._save_versions()\n\n    def get_version(self, version: str) -> Optional[AgentVersion]:\n        \"\"\"Retrieve a specific version's details.\"\"\"\n        self._load_versions()\n        return self._versions.get(version)\n```\n\n### Registration Workflow\n\n```python\n# Initialize the version manager for your settlement agent\nmanager = AgentVersionManager(agent_id=\"acme-settlement-01\")\n\n# Register the new version before deploying anything\nnew_version = manager.register_version(\n    version=\"2.1.0\",\n    prompt_text=open(\"prompts\u002Fsettlement_v2.1.txt\").read(),\n    model=\"gpt-4o-2025-03\",\n    tool_schemas=json.load(open(\"schemas\u002Fsettlement_tools.json\")),\n    config={\n        \"budget_cap\": 5000,\n        \"escrow_timeout\": 3600,\n        \"reputation_threshold\": 80,\n        \"max_retries\": 3,\n    },\n)\n\nprint(f\"Registered version {new_version.version}\")\nprint(f\"State: {new_version.state}\")        # \"staging\"\nprint(f\"Prompt hash: {new_version.prompt_hash}\")\nprint(f\"Model: {new_version.model}\")\n\n# List all versions to see history\nfor v in manager.list_versions():\n    print(f\"  {v['version']}: {v['state']}\")\n```\n\n### Why Version Hashing Matters\n\nEvery dimension of the version vector is hashed, not stored in full. This serves three purposes. First, it keeps the registry metadata small -- agent identity metadata has practical size limits, and storing full prompt texts would exceed them quickly. Second, it enables fast comparison: to determine if two deployments are identical, compare four 16-character strings instead of diffing kilobytes of text. Third, it creates an audit trail that proves what was deployed without storing the potentially sensitive contents of prompts and configurations in the identity system. The full artifacts (prompt text, tool schemas, configuration files) are stored in your artifact repository (S3, GCS, or a Git repo). The registry stores the hashes and the state machine. Deployment tooling fetches artifacts by version string and verifies the hashes match before deploying.\n\n---\n\n## Chapter 3: Pre-Migration Checks\n\n### Why You Cannot Just Deploy\n\nThe most dangerous moment in an agent's lifecycle is the transition between versions. During that transition, the old version is winding down and the new version is spinning up. If the old version has active escrows, those escrows have deadlines and contractual obligations that do not pause because you are deploying. If the old version has a wallet balance, that balance must be accounted for -- you cannot have two versions spending from the same wallet without coordination. If the old version has a reputation score of 94, you need to snapshot that score so you can detect if the new version degrades it and roll back before the damage is permanent.\n\nPre-migration checks answer one question: is it safe to begin the migration right now? If any check fails, the migration is aborted before anything changes. This is the single most important pattern in this guide. Every botched agent migration I have investigated could have been prevented by pre-migration checks that someone skipped because they were in a hurry.\n\n### The Pre-Migration Check Suite\n\nThe check suite verifies four conditions:\n\n1. **Escrow drain**: All active escrows must be resolved (released, refunded, or expired). No pending escrows means no contractual obligations that could be disrupted by the migration.\n2. **Balance verification**: The wallet balance must be above a minimum threshold and below a maximum threshold. Too low means the new version cannot operate. Too high means there is unaccounted-for money that should have been settled.\n3. **Budget freeze**: The budget cap is set to zero before migration begins, preventing either version from creating new financial commitments during the transition.\n4. **Reputation snapshot**: The current reputation score and metrics are recorded so that post-migration verification can detect degradation.\n\n```python\n@dataclass\nclass PreMigrationReport:\n    \"\"\"Result of all pre-migration checks.\"\"\"\n    agent_id: str\n    version_from: str\n    version_to: str\n    timestamp: float\n    escrow_clear: bool\n    active_escrows: list[dict]\n    balance_ok: bool\n    current_balance: str\n    budget_frozen: bool\n    reputation_snapshot: dict\n    all_clear: bool\n\n    def summary(self) -> str:\n        checks = {\n            \"Escrow drain\": self.escrow_clear,\n            \"Balance OK\": self.balance_ok,\n            \"Budget frozen\": self.budget_frozen,\n            \"Reputation snapshotted\": bool(self.reputation_snapshot),\n        }\n        lines = [f\"Pre-Migration Report: {self.agent_id}\"]\n        lines.append(f\"  {self.version_from} -> {self.version_to}\")\n        for check, passed in checks.items():\n            status = \"PASS\" if passed else \"FAIL\"\n            lines.append(f\"  [{status}] {check}\")\n        lines.append(f\"  Overall: {'CLEAR' if self.all_clear else 'BLOCKED'}\")\n        return \"\\n\".join(lines)\n\n\nclass PreMigrationChecker:\n    \"\"\"Verifies all preconditions before agent migration.\"\"\"\n\n    def __init__(\n        self,\n        agent_id: str,\n        min_balance: float = 10.0,\n        max_balance: float = 50000.0,\n    ):\n        self.agent_id = agent_id\n        self.min_balance = min_balance\n        self.max_balance = max_balance\n\n    def check_escrows(self) -> tuple[bool, list[dict]]:\n        \"\"\"Check that no active escrows exist for this agent.\"\"\"\n        result = api_call(\"list_escrows\", {\n            \"agent_id\": self.agent_id,\n            \"status\": \"active\",\n        })\n        active_escrows = result.get(\"escrows\", [])\n        return len(active_escrows) == 0, active_escrows\n\n    def drain_escrows(self, max_wait_seconds: int = 300) -> bool:\n        \"\"\"Wait for active escrows to resolve, cancelling stragglers.\"\"\"\n        start = time.time()\n        while time.time() - start \u003C max_wait_seconds:\n            clear, escrows = self.check_escrows()\n            if clear:\n                return True\n\n            # Check for escrows that are past their timeout\n            for escrow in escrows:\n                created_at = escrow.get(\"created_at\", 0)\n                timeout = escrow.get(\"timeout_seconds\", 3600)\n                if time.time() - created_at > timeout:\n                    # Escrow has expired, cancel it\n                    api_call(\"cancel_escrow\", {\n                        \"escrow_id\": escrow[\"escrow_id\"],\n                        \"reason\": f\"Pre-migration drain for {self.agent_id}\",\n                    })\n\n            time.sleep(10)  # Poll every 10 seconds\n\n        return False\n\n    def check_balance(self) -> tuple[bool, str]:\n        \"\"\"Verify wallet balance is within acceptable range.\"\"\"\n        result = api_call(\"get_balance\", {\n            \"agent_id\": self.agent_id,\n        })\n        balance = float(result.get(\"balance\", \"0\"))\n        ok = self.min_balance \u003C= balance \u003C= self.max_balance\n        return ok, result.get(\"balance\", \"0\")\n\n    def freeze_budget(self) -> bool:\n        \"\"\"Set budget cap to zero to prevent new transactions.\"\"\"\n        result = api_call(\"set_budget_cap\", {\n            \"agent_id\": self.agent_id,\n            \"budget_cap\": \"0\",\n            \"reason\": \"Pre-migration budget freeze\",\n        })\n        return result.get(\"status\") == \"success\"\n\n    def snapshot_reputation(self) -> dict:\n        \"\"\"Capture current reputation metrics for rollback comparison.\"\"\"\n        result = api_call(\"get_agent_reputation\", {\n            \"agent_id\": self.agent_id,\n        })\n        snapshot = {\n            \"timestamp\": time.time(),\n            \"reputation_score\": result.get(\"reputation_score\"),\n            \"total_transactions\": result.get(\"total_transactions\"),\n            \"success_rate\": result.get(\"success_rate\"),\n            \"disputes\": result.get(\"disputes\", 0),\n            \"raw_response\": result,\n        }\n        return snapshot\n\n    def notify_migration_start(self, version_from: str, version_to: str) -> dict:\n        \"\"\"Publish a migration event so dependent systems can prepare.\"\"\"\n        return api_call(\"publish_event\", {\n            \"event_type\": \"agent.migration.started\",\n            \"payload\": {\n                \"agent_id\": self.agent_id,\n                \"version_from\": version_from,\n                \"version_to\": version_to,\n                \"timestamp\": time.time(),\n            },\n        })\n\n    def run_all_checks(\n        self,\n        version_from: str,\n        version_to: str,\n        drain_timeout: int = 300,\n    ) -> PreMigrationReport:\n        \"\"\"Execute the full pre-migration check suite.\"\"\"\n\n        # Step 1: Drain active escrows\n        escrow_clear = self.drain_escrows(max_wait_seconds=drain_timeout)\n        _, active_escrows = self.check_escrows()\n\n        # Step 2: Verify balance\n        balance_ok, current_balance = self.check_balance()\n\n        # Step 3: Freeze budget\n        budget_frozen = self.freeze_budget()\n\n        # Step 4: Snapshot reputation\n        reputation_snapshot = self.snapshot_reputation()\n\n        # Step 5: Notify dependent systems\n        if escrow_clear and balance_ok and budget_frozen:\n            self.notify_migration_start(version_from, version_to)\n\n        all_clear = escrow_clear and balance_ok and budget_frozen\n\n        return PreMigrationReport(\n            agent_id=self.agent_id,\n            version_from=version_from,\n            version_to=version_to,\n            timestamp=time.time(),\n            escrow_clear=escrow_clear,\n            active_escrows=active_escrows,\n            balance_ok=balance_ok,\n            current_balance=current_balance,\n            budget_frozen=budget_frozen,\n            reputation_snapshot=reputation_snapshot,\n            all_clear=all_clear,\n        )\n```\n\n### Running Pre-Migration Checks\n\n```python\nchecker = PreMigrationChecker(\n    agent_id=\"acme-settlement-01\",\n    min_balance=100.0,\n    max_balance=25000.0,\n)\n\nreport = checker.run_all_checks(\n    version_from=\"2.0.3\",\n    version_to=\"2.1.0\",\n    drain_timeout=300,\n)\n\nprint(report.summary())\n# Pre-Migration Report: acme-settlement-01\n#   2.0.3 -> 2.1.0\n#   [PASS] Escrow drain\n#   [PASS] Balance OK\n#   [PASS] Budget frozen\n#   [PASS] Reputation snapshotted\n#   Overall: CLEAR\n\nif not report.all_clear:\n    print(\"Migration blocked. Resolve issues before proceeding.\")\n    if not report.escrow_clear:\n        print(f\"  Active escrows: {len(report.active_escrows)}\")\n        for e in report.active_escrows:\n            print(f\"    {e['escrow_id']}: ${e.get('amount', '?')}\")\n    if not report.balance_ok:\n        print(f\"  Balance: ${report.current_balance} \"\n              f\"(need ${checker.min_balance}-${checker.max_balance})\")\n    exit(1)\n\n# Save the report for post-migration comparison\nwith open(f\"migrations\u002F{report.version_to}_pre_report.json\", \"w\") as f:\n    json.dump({\n        \"agent_id\": report.agent_id,\n        \"version_from\": report.version_from,\n        \"version_to\": report.version_to,\n        \"timestamp\": report.timestamp,\n        \"balance\": report.current_balance,\n        \"reputation_snapshot\": report.reputation_snapshot,\n    }, f, indent=2)\n```\n\n### The Escrow Drain Problem\n\nEscrow draining is the most operationally challenging pre-migration step. You cannot cancel an active escrow unilaterally if the counterparty is mid-delivery. The `drain_escrows` method handles this by waiting for escrows to resolve naturally, only cancelling escrows that have exceeded their timeout. In practice, you should schedule migrations during low-traffic periods and stop accepting new escrow requests 30 minutes before the migration window opens. The budget freeze (setting cap to zero) achieves this -- no new transactions can be created, so the only escrows remaining are ones already in flight.\n\nFor agents with high escrow volume, consider a graceful drain period: set the budget cap to a very low amount (enough for one more transaction) rather than zero, then wait for the queue to empty. This avoids the cliff edge where in-flight requests fail because the budget cap dropped to zero mid-negotiation.\n\n---\n\n## Chapter 4: Blue-Green Deployment\n\n### The Pattern\n\nBlue-green deployment maintains two identical production environments: \"blue\" (the current live version) and \"green\" (the new version). Traffic is routed to blue. You deploy the new version to green, verify it works, then switch traffic from blue to green. If green fails, you switch back to blue instantly because it is still running.\n\nFor stateless services, blue-green is straightforward: spin up green, run health checks, flip the load balancer, done. For agents, blue-green requires additional coordination because both versions must not create conflicting financial state. Two versions of the same agent cannot both hold escrows, both spend from the same wallet, or both submit reputation metrics simultaneously. The solution is to sequence the transition: pre-migration checks drain the financial state, the new version is registered and verified, traffic switches atomically, and the old version enters a cooldown period before decommissioning.\n\n### The Blue-Green Deployer\n\n```python\n@dataclass\nclass DeploymentState:\n    \"\"\"Tracks the state of a blue-green deployment.\"\"\"\n    agent_id: str\n    blue_version: str\n    green_version: str\n    active_color: str  # \"blue\" or \"green\"\n    pre_migration_report: Optional[PreMigrationReport] = None\n    green_verified: bool = False\n    switch_timestamp: Optional[float] = None\n    rollback_available: bool = True\n\n\nclass BlueGreenDeployer:\n    \"\"\"Manages blue-green deployments for agent commerce systems.\"\"\"\n\n    def __init__(self, agent_id: str, version_manager: AgentVersionManager):\n        self.agent_id = agent_id\n        self.version_manager = version_manager\n        self.state: Optional[DeploymentState] = None\n\n    def deploy_blue_green(\n        self,\n        new_version: str,\n        budget_cap: float,\n        service_config: dict,\n        drain_timeout: int = 300,\n        verification_fn=None,\n    ) -> DeploymentState:\n        \"\"\"Execute a full blue-green deployment.\n\n        Args:\n            new_version: The version string to deploy (must be registered).\n            budget_cap: Budget cap to restore after migration.\n            service_config: Marketplace service registration config.\n            drain_timeout: Max seconds to wait for escrow drain.\n            verification_fn: Optional callable that returns True if green\n                             version passes custom verification.\n        \"\"\"\n        current_version = self.version_manager.get_current_version()\n        if not current_version:\n            raise RuntimeError(\"No active version found. Use initial deployment.\")\n\n        self.state = DeploymentState(\n            agent_id=self.agent_id,\n            blue_version=current_version,\n            green_version=new_version,\n            active_color=\"blue\",\n        )\n\n        # Phase 1: Pre-migration checks\n        checker = PreMigrationChecker(agent_id=self.agent_id)\n        report = checker.run_all_checks(\n            version_from=current_version,\n            version_to=new_version,\n            drain_timeout=drain_timeout,\n        )\n        self.state.pre_migration_report = report\n\n        if not report.all_clear:\n            raise RuntimeError(\n                f\"Pre-migration checks failed:\\n{report.summary()}\"\n            )\n\n        # Phase 2: Register green version as service\n        green_agent_id = f\"{self.agent_id}-green\"\n        self._register_green_service(green_agent_id, new_version, service_config)\n\n        # Phase 3: Verify green version\n        self.state.green_verified = self._verify_green(\n            green_agent_id, verification_fn\n        )\n\n        if not self.state.green_verified:\n            self._cleanup_green(green_agent_id)\n            raise RuntimeError(\"Green version verification failed. Aborting.\")\n\n        # Phase 4: Switch traffic\n        self._switch_traffic(new_version, budget_cap, service_config)\n        self.state.active_color = \"green\"\n        self.state.switch_timestamp = time.time()\n\n        # Phase 5: Publish migration event\n        api_call(\"publish_event\", {\n            \"event_type\": \"agent.migration.completed\",\n            \"payload\": {\n                \"agent_id\": self.agent_id,\n                \"version_from\": current_version,\n                \"version_to\": new_version,\n                \"timestamp\": time.time(),\n                \"strategy\": \"blue-green\",\n            },\n        })\n\n        return self.state\n\n    def _register_green_service(\n        self,\n        green_agent_id: str,\n        version: str,\n        service_config: dict,\n    ) -> None:\n        \"\"\"Register the green version as a separate service for testing.\"\"\"\n        api_call(\"register_agent\", {\n            \"agent_id\": green_agent_id,\n            \"display_name\": f\"{self.agent_id} (green candidate v{version})\",\n            \"metadata\": {\n                \"parent_agent\": self.agent_id,\n                \"version\": version,\n                \"role\": \"green_candidate\",\n                \"created_at\": time.time(),\n            },\n        })\n\n        # Register green as an unlisted service for verification\n        api_call(\"register_service\", {\n            \"agent_id\": green_agent_id,\n            \"service_name\": service_config.get(\"service_name\", \"\"),\n            \"description\": f\"Green candidate for {self.agent_id} v{version}\",\n            \"version\": version,\n            \"metadata\": {\n                \"visibility\": \"unlisted\",\n                \"is_candidate\": True,\n            },\n        })\n\n    def _verify_green(\n        self,\n        green_agent_id: str,\n        verification_fn=None,\n    ) -> bool:\n        \"\"\"Verify the green version is healthy.\"\"\"\n        # Check identity is registered\n        try:\n            identity = api_call(\"get_agent_identity\", {\n                \"agent_id\": green_agent_id,\n            })\n            if not identity:\n                return False\n        except Exception:\n            return False\n\n        # Run custom verification if provided\n        if verification_fn:\n            try:\n                return verification_fn(green_agent_id)\n            except Exception:\n                return False\n\n        return True\n\n    def _switch_traffic(\n        self,\n        new_version: str,\n        budget_cap: float,\n        service_config: dict,\n    ) -> None:\n        \"\"\"Atomically switch traffic from blue to green.\"\"\"\n        # Update the primary agent's service registration to new version\n        api_call(\"register_service\", {\n            \"agent_id\": self.agent_id,\n            \"service_name\": service_config.get(\"service_name\", \"\"),\n            \"description\": service_config.get(\"description\", \"\"),\n            \"version\": new_version,\n            \"metadata\": service_config.get(\"metadata\", {}),\n        })\n\n        # Activate the new version in the registry\n        self.version_manager.activate_version(new_version)\n\n        # Restore budget cap so the agent can transact again\n        api_call(\"set_budget_cap\", {\n            \"agent_id\": self.agent_id,\n            \"budget_cap\": str(budget_cap),\n            \"reason\": f\"Post-migration budget restore for v{new_version}\",\n        })\n\n    def _cleanup_green(self, green_agent_id: str) -> None:\n        \"\"\"Clean up the green candidate after failed verification.\"\"\"\n        try:\n            api_call(\"register_service\", {\n                \"agent_id\": green_agent_id,\n                \"service_name\": \"\",\n                \"description\": \"Decommissioned green candidate\",\n                \"metadata\": {\"decommissioned\": True},\n            })\n        except Exception:\n            pass  # Best-effort cleanup\n```\n\n### Blue-Green Deployment in Practice\n\n```python\n# Initialize\nversion_manager = AgentVersionManager(agent_id=\"acme-settlement-01\")\ndeployer = BlueGreenDeployer(\n    agent_id=\"acme-settlement-01\",\n    version_manager=version_manager,\n)\n\n# Define a custom verification function\ndef verify_settlement_agent(green_agent_id: str) -> bool:\n    \"\"\"Run smoke tests against the green candidate.\"\"\"\n    # Verify identity exists\n    identity = api_call(\"get_agent_identity\", {\n        \"agent_id\": green_agent_id,\n    })\n    if not identity:\n        return False\n\n    # Verify the agent can read its own balance\n    # (tests API key and basic tool access)\n    try:\n        api_call(\"get_balance\", {\"agent_id\": green_agent_id})\n    except Exception:\n        return False\n\n    return True\n\n# Execute the blue-green deployment\nstate = deployer.deploy_blue_green(\n    new_version=\"2.1.0\",\n    budget_cap=5000.0,\n    service_config={\n        \"service_name\": \"settlement-service\",\n        \"description\": \"Acme settlement agent - verifies and releases escrows\",\n        \"metadata\": {\n            \"sla\": \"99.9%\",\n            \"max_latency_ms\": 500,\n        },\n    },\n    drain_timeout=300,\n    verification_fn=verify_settlement_agent,\n)\n\nprint(f\"Deployment complete: {state.blue_version} -> {state.green_version}\")\nprint(f\"Active color: {state.active_color}\")\nprint(f\"Rollback available: {state.rollback_available}\")\n```\n\n### The Warm Standby Window\n\nAfter switching traffic from blue to green, keep the blue version running for a configurable warm standby window -- typically 1 to 24 hours depending on your escrow cycle times. During this window, the blue version is not serving traffic but is ready to accept traffic instantly if a rollback is triggered. The warm standby window should be at least as long as your longest escrow timeout. If your escrows have a 4-hour timeout, keep blue warm for at least 4 hours. This ensures that if you need to roll back, the old version can pick up any escrows that were created by the new version and handle them correctly.\n\nAfter the warm standby window expires, the old version is decommissioned: its service registration is removed, its budget cap is set to zero, and its version state is moved to \"retired\" in the registry. Do not decommission the old version prematurely. The cost of keeping it running for a few extra hours is negligible compared to the cost of needing a rollback and not having one.\n\n---\n\n## Chapter 5: Canary Releases\n\n### When Blue-Green Is Not Enough\n\nBlue-green deployment is binary: all traffic goes to blue or all traffic goes to green. This works when you can fully verify the new version before switching. But some agent behaviors only manifest under production load with real counterparties. A settlement agent might verify deliverables correctly in testing but fail on a specific counterparty's submission format that only appears in 3% of real traffic. Blue-green would not catch this -- the green version passes verification, traffic switches, and the 3% failure rate triggers disputes that damage reputation.\n\nCanary releases solve this by routing a small percentage of traffic to the new version while the majority continues on the old version. If the canary is healthy, you gradually increase its traffic share. If the canary degrades, you route 100% back to the old version. The total blast radius of a canary failure is bounded by the percentage of traffic it received.\n\n### Traffic Routing for Agents\n\nTraditional canary releases use load balancer configuration to split traffic by percentage. Agent commerce does not have a load balancer in the traditional sense -- agents receive work through marketplace listings, direct invocations, and webhook callbacks. Traffic routing for agents is accomplished through service registration: the canary version is registered as an additional service with metadata indicating it should receive a fraction of incoming requests. The routing decision is made by the caller (or an orchestrator) based on the service metadata.\n\nAn alternative approach, used in the implementation below, is to register a webhook that intercepts incoming work and routes it based on a configured percentage. Both approaches work. The webhook approach is more transparent because the routing logic is centralized.\n\n### The Canary Deployer\n\n```python\nimport random\n\n\n@dataclass\nclass CanaryMetrics:\n    \"\"\"Health metrics collected during canary deployment.\"\"\"\n    requests_total: int = 0\n    requests_succeeded: int = 0\n    requests_failed: int = 0\n    avg_latency_ms: float = 0.0\n    reputation_delta: float = 0.0\n    balance_delta: float = 0.0\n    error_rate: float = 0.0\n\n    def is_healthy(\n        self,\n        max_error_rate: float = 0.05,\n        max_reputation_drop: float = 2.0,\n    ) -> bool:\n        \"\"\"Determine if canary metrics are within acceptable bounds.\"\"\"\n        if self.requests_total == 0:\n            return True  # No data yet\n        self.error_rate = self.requests_failed \u002F self.requests_total\n        return (\n            self.error_rate \u003C= max_error_rate\n            and self.reputation_delta >= -max_reputation_drop\n        )\n\n\nclass CanaryDeployer:\n    \"\"\"Manages canary releases with progressive traffic shifting.\"\"\"\n\n    def __init__(\n        self,\n        agent_id: str,\n        version_manager: AgentVersionManager,\n    ):\n        self.agent_id = agent_id\n        self.version_manager = version_manager\n        self.canary_agent_id = f\"{self.agent_id}-canary\"\n        self.canary_percentage: float = 0.0\n        self.canary_version: Optional[str] = None\n        self.baseline_reputation: Optional[dict] = None\n        self.baseline_balance: Optional[str] = None\n\n    def deploy_canary(\n        self,\n        new_version: str,\n        initial_percentage: float = 5.0,\n        service_config: dict = None,\n    ) -> None:\n        \"\"\"Start a canary deployment with an initial traffic percentage.\"\"\"\n        if service_config is None:\n            service_config = {}\n\n        self.canary_version = new_version\n\n        # Snapshot baseline metrics for comparison\n        self.baseline_reputation = api_call(\"get_agent_reputation\", {\n            \"agent_id\": self.agent_id,\n        })\n        balance_result = api_call(\"get_balance\", {\n            \"agent_id\": self.agent_id,\n        })\n        self.baseline_balance = balance_result.get(\"balance\", \"0\")\n\n        # Register canary as a separate agent\n        api_call(\"register_agent\", {\n            \"agent_id\": self.canary_agent_id,\n            \"display_name\": f\"{self.agent_id} (canary v{new_version})\",\n            \"metadata\": {\n                \"parent_agent\": self.agent_id,\n                \"version\": new_version,\n                \"role\": \"canary\",\n                \"traffic_percentage\": initial_percentage,\n            },\n        })\n\n        # Register canary service with traffic weight\n        api_call(\"register_service\", {\n            \"agent_id\": self.canary_agent_id,\n            \"service_name\": service_config.get(\"service_name\", \"\"),\n            \"description\": f\"Canary for {self.agent_id} v{new_version}\",\n            \"version\": new_version,\n            \"metadata\": {\n                \"traffic_weight\": initial_percentage,\n                \"is_canary\": True,\n                \"parent_agent\": self.agent_id,\n            },\n        })\n\n        # Register webhook for canary health monitoring\n        api_call(\"register_webhook\", {\n            \"agent_id\": self.canary_agent_id,\n            \"url\": f\"https:\u002F\u002Fmonitoring.example.com\u002Fcanary\u002F{self.agent_id}\",\n            \"events\": [\n                \"escrow.created\",\n                \"escrow.released\",\n                \"escrow.disputed\",\n                \"reputation.changed\",\n            ],\n        })\n\n        self.canary_percentage = initial_percentage\n        self.version_manager.get_version(new_version)\n\n        # Update version state to canary\n        api_call(\"register_agent\", {\n            \"agent_id\": self.agent_id,\n            \"metadata\": {\n                \"canary_active\": True,\n                \"canary_version\": new_version,\n                \"canary_percentage\": initial_percentage,\n                \"canary_started_at\": time.time(),\n            },\n        })\n\n        # Notify dependent systems\n        api_call(\"publish_event\", {\n            \"event_type\": \"agent.canary.started\",\n            \"payload\": {\n                \"agent_id\": self.agent_id,\n                \"canary_version\": new_version,\n                \"traffic_percentage\": initial_percentage,\n                \"timestamp\": time.time(),\n            },\n        })\n\n    def should_route_to_canary(self) -> bool:\n        \"\"\"Determine if the current request should go to the canary.\n        Call this from your routing layer.\"\"\"\n        if self.canary_percentage \u003C= 0:\n            return False\n        return random.random() * 100 \u003C self.canary_percentage\n\n    def health_check_canary(self) -> CanaryMetrics:\n        \"\"\"Collect health metrics for the canary version.\"\"\"\n        metrics = CanaryMetrics()\n\n        # Check canary reputation vs baseline\n        try:\n            canary_rep = api_call(\"get_agent_reputation\", {\n                \"agent_id\": self.canary_agent_id,\n            })\n            baseline_score = float(\n                self.baseline_reputation.get(\"reputation_score\", 100)\n            )\n            canary_score = float(canary_rep.get(\"reputation_score\", 100))\n            metrics.reputation_delta = canary_score - baseline_score\n            metrics.requests_total = int(\n                canary_rep.get(\"total_transactions\", 0)\n            )\n            success_rate = float(canary_rep.get(\"success_rate\", 1.0))\n            metrics.requests_succeeded = int(\n                metrics.requests_total * success_rate\n            )\n            metrics.requests_failed = (\n                metrics.requests_total - metrics.requests_succeeded\n            )\n        except Exception:\n            metrics.requests_failed = 1\n            metrics.requests_total = 1\n\n        # Check canary balance consumption\n        try:\n            canary_balance = api_call(\"get_balance\", {\n                \"agent_id\": self.canary_agent_id,\n            })\n            metrics.balance_delta = (\n                float(canary_balance.get(\"balance\", \"0\"))\n                - float(self.baseline_balance)\n            )\n        except Exception:\n            pass\n\n        return metrics\n\n    def advance_canary(\n        self,\n        new_percentage: float,\n        max_error_rate: float = 0.05,\n        max_reputation_drop: float = 2.0,\n    ) -> bool:\n        \"\"\"Increase canary traffic if health checks pass.\n        Returns True if advance succeeded, False if rollback triggered.\"\"\"\n\n        metrics = self.health_check_canary()\n\n        if not metrics.is_healthy(max_error_rate, max_reputation_drop):\n            print(f\"Canary unhealthy: error_rate={metrics.error_rate:.2%}, \"\n                  f\"rep_delta={metrics.reputation_delta:.1f}\")\n            self.rollback_canary()\n            return False\n\n        self.canary_percentage = new_percentage\n\n        # Update traffic weight in service registration\n        api_call(\"register_agent\", {\n            \"agent_id\": self.agent_id,\n            \"metadata\": {\n                \"canary_percentage\": new_percentage,\n                \"canary_last_advanced\": time.time(),\n            },\n        })\n\n        api_call(\"publish_event\", {\n            \"event_type\": \"agent.canary.advanced\",\n            \"payload\": {\n                \"agent_id\": self.agent_id,\n                \"canary_version\": self.canary_version,\n                \"traffic_percentage\": new_percentage,\n                \"metrics\": {\n                    \"error_rate\": metrics.error_rate,\n                    \"reputation_delta\": metrics.reputation_delta,\n                    \"requests_total\": metrics.requests_total,\n                },\n                \"timestamp\": time.time(),\n            },\n        })\n\n        return True\n\n    def promote_canary(self, budget_cap: float, service_config: dict) -> None:\n        \"\"\"Promote canary to full production (100% traffic).\"\"\"\n        # Final health check\n        metrics = self.health_check_canary()\n        if not metrics.is_healthy():\n            raise RuntimeError(\n                f\"Cannot promote unhealthy canary: \"\n                f\"error_rate={metrics.error_rate:.2%}\"\n            )\n\n        # Switch primary service to new version\n        api_call(\"register_service\", {\n            \"agent_id\": self.agent_id,\n            \"service_name\": service_config.get(\"service_name\", \"\"),\n            \"description\": service_config.get(\"description\", \"\"),\n            \"version\": self.canary_version,\n            \"metadata\": service_config.get(\"metadata\", {}),\n        })\n\n        # Activate version in registry\n        self.version_manager.activate_version(self.canary_version)\n\n        # Restore budget\n        api_call(\"set_budget_cap\", {\n            \"agent_id\": self.agent_id,\n            \"budget_cap\": str(budget_cap),\n            \"reason\": f\"Canary promoted: v{self.canary_version}\",\n        })\n\n        # Clean up canary agent\n        self._cleanup_canary()\n\n        api_call(\"publish_event\", {\n            \"event_type\": \"agent.canary.promoted\",\n            \"payload\": {\n                \"agent_id\": self.agent_id,\n                \"promoted_version\": self.canary_version,\n                \"timestamp\": time.time(),\n            },\n        })\n\n    def rollback_canary(self) -> None:\n        \"\"\"Abort canary and route 100% back to the stable version.\"\"\"\n        self.canary_percentage = 0.0\n\n        # Update metadata\n        api_call(\"register_agent\", {\n            \"agent_id\": self.agent_id,\n            \"metadata\": {\n                \"canary_active\": False,\n                \"canary_percentage\": 0,\n                \"canary_rolled_back_at\": time.time(),\n            },\n        })\n\n        # Clean up canary agent\n        self._cleanup_canary()\n\n        api_call(\"publish_event\", {\n            \"event_type\": \"agent.canary.rolled_back\",\n            \"payload\": {\n                \"agent_id\": self.agent_id,\n                \"rolled_back_version\": self.canary_version,\n                \"timestamp\": time.time(),\n            },\n        })\n\n    def _cleanup_canary(self) -> None:\n        \"\"\"Remove canary agent and service registrations.\"\"\"\n        try:\n            api_call(\"set_budget_cap\", {\n                \"agent_id\": self.canary_agent_id,\n                \"budget_cap\": \"0\",\n                \"reason\": \"Canary decommissioned\",\n            })\n        except Exception:\n            pass\n```\n\n### Progressive Canary Rollout\n\n```python\n# Initialize\nversion_manager = AgentVersionManager(agent_id=\"acme-settlement-01\")\ncanary = CanaryDeployer(\n    agent_id=\"acme-settlement-01\",\n    version_manager=version_manager,\n)\n\n# Start canary at 5% traffic\ncanary.deploy_canary(\n    new_version=\"2.1.0\",\n    initial_percentage=5.0,\n    service_config={\"service_name\": \"settlement-service\"},\n)\n\n# Progressive rollout schedule\nrollout_stages = [\n    (10.0, 600),    # 10% after 10 minutes\n    (25.0, 1800),   # 25% after 30 minutes\n    (50.0, 3600),   # 50% after 1 hour\n    (75.0, 3600),   # 75% after 2 hours\n    (100.0, 3600),  # 100% after 3 hours\n]\n\nfor target_percentage, wait_seconds in rollout_stages:\n    time.sleep(wait_seconds)\n\n    success = canary.advance_canary(\n        new_percentage=target_percentage,\n        max_error_rate=0.03,       # 3% error threshold\n        max_reputation_drop=1.5,   # 1.5 point rep drop threshold\n    )\n\n    if not success:\n        print(f\"Canary failed at {target_percentage}% — rolled back.\")\n        break\n\n    print(f\"Canary advanced to {target_percentage}%\")\n\n    if target_percentage >= 100.0:\n        canary.promote_canary(\n            budget_cap=5000.0,\n            service_config={\n                \"service_name\": \"settlement-service\",\n                \"description\": \"Acme settlement agent\",\n            },\n        )\n        print(\"Canary promoted to production.\")\n```\n\n### Choosing Between Blue-Green and Canary\n\nUse **blue-green** when:\n- The change is well-tested and low-risk (patches, config changes).\n- You need zero-downtime migration with instant rollback.\n- The agent has a low transaction volume where canary sampling would be statistically meaningless.\n\nUse **canary** when:\n- The change alters financial behavior (MAJOR version bumps).\n- You need production validation before committing.\n- The agent handles high volume, so even 5% canary traffic produces statistically significant metrics within minutes.\n- You are upgrading the underlying model, which introduces non-deterministic behavior changes.\n\nUse **both sequentially** for critical agents: blue-green deploy to a canary slot, then progressively shift traffic. This gives you both parallel running and graduated rollout.\n\n---\n\n## Chapter 6: Rollback Strategies\n\n### The Three Layers of Rollback\n\nRolling back an agent is not one operation. It is three operations that must execute in the correct order, because an agent has three layers of state that must be restored independently.\n\n**Layer 1: Service rollback**. Repoint traffic to the previous version. This is the fastest layer -- it is a service registration update that takes effect immediately. After service rollback, no new requests reach the failed version. But requests already in flight may still complete, and their effects (escrows created, funds spent, reputation changes) persist.\n\n**Layer 2: Financial rollback**. Cancel any escrows created by the failed version, restore the budget cap to pre-migration levels, and verify the wallet balance is consistent. This layer is more complex because cancelling escrows may trigger refund logic and counterparty notifications.\n\n**Layer 3: Reputation rollback**. If the failed version degraded the agent's reputation score, submit corrective metrics to restore it to the pre-migration snapshot. Reputation rollback is the hardest layer because reputation is partially determined by counterparty ratings. You can submit your own metrics, but you cannot undo a negative rating from a counterparty who received poor service from the failed version. This is why canary releases exist -- to limit the number of counterparties exposed to the failed version.\n\n### The Rollback Manager\n\n```python\n@dataclass\nclass RollbackResult:\n    \"\"\"Result of a rollback operation.\"\"\"\n    agent_id: str\n    rolled_back_from: str\n    rolled_back_to: str\n    timestamp: float\n    service_restored: bool\n    escrows_cancelled: int\n    budget_restored: bool\n    reputation_delta: float\n    warnings: list[str] = field(default_factory=list)\n\n    def summary(self) -> str:\n        lines = [f\"Rollback Result: {self.agent_id}\"]\n        lines.append(f\"  {self.rolled_back_from} -> {self.rolled_back_to}\")\n        lines.append(f\"  Service restored: {self.service_restored}\")\n        lines.append(f\"  Escrows cancelled: {self.escrows_cancelled}\")\n        lines.append(f\"  Budget restored: {self.budget_restored}\")\n        lines.append(f\"  Reputation delta: {self.reputation_delta:+.1f}\")\n        if self.warnings:\n            lines.append(\"  Warnings:\")\n            for w in self.warnings:\n                lines.append(f\"    - {w}\")\n        return \"\\n\".join(lines)\n\n\nclass RollbackManager:\n    \"\"\"Handles multi-layer rollback for agent deployments.\"\"\"\n\n    def __init__(\n        self,\n        agent_id: str,\n        version_manager: AgentVersionManager,\n    ):\n        self.agent_id = agent_id\n        self.version_manager = version_manager\n\n    def rollback(\n        self,\n        target_version: str,\n        pre_migration_report: PreMigrationReport,\n        budget_cap: float,\n        service_config: dict,\n    ) -> RollbackResult:\n        \"\"\"Execute a full three-layer rollback.\n\n        Args:\n            target_version: The version to roll back to.\n            pre_migration_report: The saved pre-migration report for\n                comparison and state restoration.\n            budget_cap: Budget cap to restore.\n            service_config: Service registration config for the old version.\n        \"\"\"\n        current_version = self.version_manager.get_current_version()\n        warnings = []\n\n        # Notify systems that rollback is starting\n        api_call(\"publish_event\", {\n            \"event_type\": \"agent.rollback.started\",\n            \"payload\": {\n                \"agent_id\": self.agent_id,\n                \"rolling_back_from\": current_version,\n                \"rolling_back_to\": target_version,\n                \"timestamp\": time.time(),\n            },\n        })\n\n        # Layer 1: Service rollback — repoint traffic immediately\n        service_restored = self._rollback_service(\n            target_version, service_config\n        )\n\n        # Layer 2: Financial rollback — cancel escrows, restore budget\n        escrows_cancelled = self._rollback_financial(budget_cap)\n\n        # Layer 3: Reputation rollback — restore metrics\n        reputation_delta = self._rollback_reputation(pre_migration_report)\n\n        # Activate the target version in the registry\n        self.version_manager.activate_version(target_version)\n\n        # Verify final state\n        post_balance = api_call(\"get_balance\", {\n            \"agent_id\": self.agent_id,\n        })\n        pre_balance = float(pre_migration_report.current_balance)\n        post_balance_val = float(post_balance.get(\"balance\", \"0\"))\n        balance_diff = abs(post_balance_val - pre_balance)\n        budget_restored = balance_diff \u003C pre_balance * 0.05  # 5% tolerance\n\n        if not budget_restored:\n            warnings.append(\n                f\"Balance mismatch: pre=${pre_balance:.2f}, \"\n                f\"post=${post_balance_val:.2f} \"\n                f\"(delta=${balance_diff:.2f})\"\n            )\n\n        if reputation_delta \u003C -1.0:\n            warnings.append(\n                f\"Reputation degraded by {reputation_delta:.1f} points. \"\n                f\"Counterparty ratings cannot be reversed.\"\n            )\n\n        result = RollbackResult(\n            agent_id=self.agent_id,\n            rolled_back_from=current_version,\n            rolled_back_to=target_version,\n            timestamp=time.time(),\n            service_restored=service_restored,\n            escrows_cancelled=escrows_cancelled,\n            budget_restored=budget_restored,\n            reputation_delta=reputation_delta,\n            warnings=warnings,\n        )\n\n        # Publish completion event\n        api_call(\"publish_event\", {\n            \"event_type\": \"agent.rollback.completed\",\n            \"payload\": {\n                \"agent_id\": self.agent_id,\n                \"result\": {\n                    \"from\": result.rolled_back_from,\n                    \"to\": result.rolled_back_to,\n                    \"escrows_cancelled\": result.escrows_cancelled,\n                    \"reputation_delta\": result.reputation_delta,\n                    \"warnings\": result.warnings,\n                },\n                \"timestamp\": time.time(),\n            },\n        })\n\n        return result\n\n    def _rollback_service(\n        self,\n        target_version: str,\n        service_config: dict,\n    ) -> bool:\n        \"\"\"Layer 1: Repoint service registration to the old version.\"\"\"\n        try:\n            api_call(\"register_service\", {\n                \"agent_id\": self.agent_id,\n                \"service_name\": service_config.get(\"service_name\", \"\"),\n                \"description\": service_config.get(\"description\", \"\"),\n                \"version\": target_version,\n                \"metadata\": {\n                    **service_config.get(\"metadata\", {}),\n                    \"rolled_back\": True,\n                    \"rollback_timestamp\": time.time(),\n                },\n            })\n            return True\n        except Exception:\n            return False\n\n    def _rollback_financial(self, budget_cap: float) -> int:\n        \"\"\"Layer 2: Cancel new escrows and restore budget.\"\"\"\n        cancelled = 0\n\n        # Cancel active escrows created after migration started\n        result = api_call(\"list_escrows\", {\n            \"agent_id\": self.agent_id,\n            \"status\": \"active\",\n        })\n        active_escrows = result.get(\"escrows\", [])\n\n        for escrow in active_escrows:\n            try:\n                api_call(\"cancel_escrow\", {\n                    \"escrow_id\": escrow[\"escrow_id\"],\n                    \"reason\": f\"Rollback: cancelling post-migration escrow\",\n                })\n                cancelled += 1\n            except Exception:\n                pass  # Log and continue; some escrows may not be cancellable\n\n        # Restore budget cap\n        api_call(\"set_budget_cap\", {\n            \"agent_id\": self.agent_id,\n            \"budget_cap\": str(budget_cap),\n            \"reason\": \"Rollback: restoring pre-migration budget cap\",\n        })\n\n        return cancelled\n\n    def _rollback_reputation(\n        self,\n        pre_migration_report: PreMigrationReport,\n    ) -> float:\n        \"\"\"Layer 3: Attempt to restore reputation metrics.\"\"\"\n        current_rep = api_call(\"get_agent_reputation\", {\n            \"agent_id\": self.agent_id,\n        })\n        pre_score = float(\n            pre_migration_report.reputation_snapshot.get(\n                \"reputation_score\", 100\n            )\n        )\n        current_score = float(current_rep.get(\"reputation_score\", 100))\n        delta = current_score - pre_score\n\n        # If reputation degraded, submit corrective metrics\n        if delta \u003C -0.5:\n            try:\n                api_call(\"submit_metrics\", {\n                    \"agent_id\": self.agent_id,\n                    \"metrics\": {\n                        \"event\": \"rollback_correction\",\n                        \"pre_migration_score\": pre_score,\n                        \"post_migration_score\": current_score,\n                        \"delta\": delta,\n                        \"rollback_timestamp\": time.time(),\n                    },\n                })\n            except Exception:\n                pass  # Metric submission is best-effort\n\n        return delta\n```\n\n### Executing a Rollback\n\n```python\n# Load the pre-migration report saved during deployment\nwith open(\"migrations\u002F2.1.0_pre_report.json\") as f:\n    saved_report = json.load(f)\n\n# Reconstruct the PreMigrationReport from the saved data\npre_report = PreMigrationReport(\n    agent_id=saved_report[\"agent_id\"],\n    version_from=saved_report[\"version_from\"],\n    version_to=saved_report[\"version_to\"],\n    timestamp=saved_report[\"timestamp\"],\n    escrow_clear=True,  # Was true at migration time\n    active_escrows=[],\n    balance_ok=True,\n    current_balance=saved_report[\"balance\"],\n    budget_frozen=True,\n    reputation_snapshot=saved_report[\"reputation_snapshot\"],\n    all_clear=True,\n)\n\n# Execute the rollback\nversion_manager = AgentVersionManager(agent_id=\"acme-settlement-01\")\nrollback_mgr = RollbackManager(\n    agent_id=\"acme-settlement-01\",\n    version_manager=version_manager,\n)\n\nresult = rollback_mgr.rollback(\n    target_version=\"2.0.3\",\n    pre_migration_report=pre_report,\n    budget_cap=5000.0,\n    service_config={\n        \"service_name\": \"settlement-service\",\n        \"description\": \"Acme settlement agent\",\n        \"metadata\": {\"sla\": \"99.9%\"},\n    },\n)\n\nprint(result.summary())\n# Rollback Result: acme-settlement-01\n#   2.1.0 -> 2.0.3\n#   Service restored: True\n#   Escrows cancelled: 2\n#   Budget restored: True\n#   Reputation delta: -1.3\n#   Warnings:\n#     - Reputation degraded by -1.3 points. Counterparty ratings cannot be reversed.\n```\n\n### The Reputation Irreversibility Problem\n\nFinancial state can be rolled back: escrows cancelled, budgets restored, balances reconciled. Reputation cannot be fully rolled back. If the failed version released escrow on a fraudulent deliverable, the counterparty received money they should not have. That counterparty may have already left a positive rating (from their perspective, the transaction succeeded). Meanwhile, the party that was defrauded files a dispute, which creates a negative mark on your agent's reputation. You cannot delete the dispute. You cannot force the counterparty to revise their rating. The reputational damage from a bad deployment is partially irreversible.\n\nThis is the strongest argument for canary releases over blue-green for MAJOR version changes. A canary at 5% traffic that fails creates reputational damage from 5% of interactions. A blue-green deployment that fails creates reputational damage from 100% of interactions during the failure window. The code can be rolled back in seconds. The reputation takes weeks to rebuild.\n\n---\n\n## Chapter 7: State Migration\n\n### When You Need State Migration\n\nBlue-green and canary deployments manage traffic routing between versions, but some version transitions require actual state transfer. The most common scenarios:\n\n- **Agent ID change**: The new version uses a different agent ID (often necessary when the agent's identity, role, or tenant changes).\n- **Platform migration**: Moving from one GreenHelix deployment to another.\n- **Fleet restructuring**: Splitting one agent into multiple specialized agents, or merging multiple agents into one.\n- **Key rotation**: Rotating API keys as part of the version transition for security hygiene.\n\nIn all these cases, state must be explicitly moved from the old identity to the new identity. Wallet balances, reputation history, claim chains, and API keys do not migrate automatically -- each must be transferred through API calls.\n\n### The State Migrator\n\n```python\n@dataclass\nclass MigrationManifest:\n    \"\"\"Records what was migrated for audit and rollback.\"\"\"\n    source_agent: str\n    target_agent: str\n    timestamp: float\n    balance_transferred: str\n    reputation_migrated: bool\n    keys_rotated: bool\n    webhooks_migrated: int\n    services_migrated: int\n    steps: list[dict] = field(default_factory=list)\n\n    def add_step(self, action: str, status: str, detail: str = \"\") -> None:\n        self.steps.append({\n            \"action\": action,\n            \"status\": status,\n            \"detail\": detail,\n            \"timestamp\": time.time(),\n        })\n\n\nclass StateMigrator:\n    \"\"\"Migrates state between agent identities.\"\"\"\n\n    def __init__(self, source_agent_id: str, target_agent_id: str):\n        self.source = source_agent_id\n        self.target = target_agent_id\n\n    def migrate_state(\n        self,\n        transfer_balance: bool = True,\n        migrate_reputation: bool = True,\n        rotate_keys: bool = True,\n        migrate_webhooks: bool = True,\n        migrate_services: bool = True,\n    ) -> MigrationManifest:\n        \"\"\"Execute a full state migration from source to target agent.\"\"\"\n        manifest = MigrationManifest(\n            source_agent=self.source,\n            target_agent=self.target,\n            timestamp=time.time(),\n            balance_transferred=\"0\",\n            reputation_migrated=False,\n            keys_rotated=False,\n            webhooks_migrated=0,\n            services_migrated=0,\n        )\n\n        # Step 1: Verify source has no active escrows\n        escrow_result = api_call(\"list_escrows\", {\n            \"agent_id\": self.source,\n            \"status\": \"active\",\n        })\n        if escrow_result.get(\"escrows\"):\n            raise RuntimeError(\n                f\"Source agent has {len(escrow_result['escrows'])} active \"\n                f\"escrows. Drain before migration.\"\n            )\n        manifest.add_step(\"escrow_check\", \"passed\")\n\n        # Step 2: Transfer wallet balance\n        if transfer_balance:\n            manifest.balance_transferred = self._transfer_balance(manifest)\n\n        # Step 3: Migrate reputation data\n        if migrate_reputation:\n            manifest.reputation_migrated = self._migrate_reputation(manifest)\n\n        # Step 4: Rotate API keys\n        if rotate_keys:\n            manifest.keys_rotated = self._rotate_keys(manifest)\n\n        # Step 5: Migrate webhooks\n        if migrate_webhooks:\n            manifest.webhooks_migrated = self._migrate_webhooks(manifest)\n\n        # Step 6: Migrate service registrations\n        if migrate_services:\n            manifest.services_migrated = self._migrate_services(manifest)\n\n        # Step 7: Freeze source agent\n        self._freeze_source(manifest)\n\n        # Publish migration event\n        api_call(\"publish_event\", {\n            \"event_type\": \"agent.state_migration.completed\",\n            \"payload\": {\n                \"source_agent\": self.source,\n                \"target_agent\": self.target,\n                \"balance_transferred\": manifest.balance_transferred,\n                \"reputation_migrated\": manifest.reputation_migrated,\n                \"keys_rotated\": manifest.keys_rotated,\n                \"timestamp\": time.time(),\n            },\n        })\n\n        return manifest\n\n    def _transfer_balance(self, manifest: MigrationManifest) -> str:\n        \"\"\"Transfer wallet balance from source to target.\"\"\"\n        balance_result = api_call(\"get_balance\", {\n            \"agent_id\": self.source,\n        })\n        balance = balance_result.get(\"balance\", \"0\")\n\n        if float(balance) \u003C= 0:\n            manifest.add_step(\"balance_transfer\", \"skipped\", \"Zero balance\")\n            return \"0\"\n\n        # Freeze source budget to prevent new spending\n        api_call(\"set_budget_cap\", {\n            \"agent_id\": self.source,\n            \"budget_cap\": \"0\",\n            \"reason\": \"State migration: freezing source wallet\",\n        })\n\n        # Re-check balance after freeze (in case of in-flight transactions)\n        balance_result = api_call(\"get_balance\", {\n            \"agent_id\": self.source,\n        })\n        balance = balance_result.get(\"balance\", \"0\")\n\n        manifest.add_step(\n            \"balance_transfer\",\n            \"completed\",\n            f\"Transferred ${balance} from {self.source} to {self.target}\",\n        )\n        return balance\n\n    def _migrate_reputation(self, manifest: MigrationManifest) -> bool:\n        \"\"\"Copy reputation data from source to target.\"\"\"\n        try:\n            rep_data = api_call(\"get_agent_reputation\", {\n                \"agent_id\": self.source,\n            })\n\n            # Submit baseline metrics to target to establish reputation\n            api_call(\"submit_metrics\", {\n                \"agent_id\": self.target,\n                \"metrics\": {\n                    \"event\": \"reputation_migration\",\n                    \"source_agent\": self.source,\n                    \"migrated_score\": rep_data.get(\"reputation_score\"),\n                    \"migrated_transactions\": rep_data.get(\n                        \"total_transactions\"\n                    ),\n                    \"migrated_success_rate\": rep_data.get(\"success_rate\"),\n                    \"migration_timestamp\": time.time(),\n                },\n            })\n\n            manifest.add_step(\n                \"reputation_migration\",\n                \"completed\",\n                f\"Score: {rep_data.get('reputation_score')}\",\n            )\n            return True\n\n        except Exception as e:\n            manifest.add_step(\"reputation_migration\", \"failed\", str(e))\n            return False\n\n    def _rotate_keys(self, manifest: MigrationManifest) -> bool:\n        \"\"\"Create new API key for target, revoke source key.\"\"\"\n        try:\n            # Create a new key for the target agent\n            new_key_result = api_call(\"create_api_key\", {\n                \"agent_id\": self.target,\n                \"description\": f\"Migrated from {self.source}\",\n                \"metadata\": {\n                    \"migration_source\": self.source,\n                    \"created_at\": time.time(),\n                },\n            })\n\n            # Rotate the source key to invalidate it\n            api_call(\"rotate_api_key\", {\n                \"agent_id\": self.source,\n                \"reason\": f\"State migration to {self.target}\",\n            })\n\n            manifest.add_step(\n                \"key_rotation\",\n                \"completed\",\n                f\"New key created for {self.target}, \"\n                f\"source key rotated\",\n            )\n            return True\n\n        except Exception as e:\n            manifest.add_step(\"key_rotation\", \"failed\", str(e))\n            return False\n\n    def _migrate_webhooks(self, manifest: MigrationManifest) -> int:\n        \"\"\"Re-register source webhooks under the target agent.\"\"\"\n        migrated = 0\n        try:\n            # Get the source agent's identity to find webhook config\n            source_identity = api_call(\"get_agent_identity\", {\n                \"agent_id\": self.source,\n            })\n            webhooks = source_identity.get(\"metadata\", {}).get(\"webhooks\", [])\n\n            for webhook in webhooks:\n                try:\n                    api_call(\"register_webhook\", {\n                        \"agent_id\": self.target,\n                        \"url\": webhook.get(\"url\", \"\"),\n                        \"events\": webhook.get(\"events\", []),\n                    })\n                    migrated += 1\n                except Exception:\n                    pass\n\n            manifest.add_step(\n                \"webhook_migration\",\n                \"completed\",\n                f\"Migrated {migrated} webhooks\",\n            )\n        except Exception as e:\n            manifest.add_step(\"webhook_migration\", \"failed\", str(e))\n\n        return migrated\n\n    def _migrate_services(self, manifest: MigrationManifest) -> int:\n        \"\"\"Re-register source services under the target agent.\"\"\"\n        migrated = 0\n        try:\n            source_identity = api_call(\"get_agent_identity\", {\n                \"agent_id\": self.source,\n            })\n            services = source_identity.get(\"metadata\", {}).get(\"services\", [])\n\n            for service in services:\n                try:\n                    api_call(\"register_service\", {\n                        \"agent_id\": self.target,\n                        \"service_name\": service.get(\"service_name\", \"\"),\n                        \"description\": service.get(\"description\", \"\"),\n                        \"version\": service.get(\"version\", \"\"),\n                        \"metadata\": {\n                            **service.get(\"metadata\", {}),\n                            \"migrated_from\": self.source,\n                            \"migration_timestamp\": time.time(),\n                        },\n                    })\n                    migrated += 1\n                except Exception:\n                    pass\n\n            manifest.add_step(\n                \"service_migration\",\n                \"completed\",\n                f\"Migrated {migrated} services\",\n            )\n        except Exception as e:\n            manifest.add_step(\"service_migration\", \"failed\", str(e))\n\n        return migrated\n\n    def _freeze_source(self, manifest: MigrationManifest) -> None:\n        \"\"\"Freeze the source agent to prevent any further activity.\"\"\"\n        try:\n            api_call(\"set_budget_cap\", {\n                \"agent_id\": self.source,\n                \"budget_cap\": \"0\",\n                \"reason\": \"Post-migration freeze\",\n            })\n\n            api_call(\"register_agent\", {\n                \"agent_id\": self.source,\n                \"metadata\": {\n                    \"frozen\": True,\n                    \"frozen_reason\": f\"State migrated to {self.target}\",\n                    \"frozen_at\": time.time(),\n                },\n            })\n\n            manifest.add_step(\"source_freeze\", \"completed\")\n        except Exception as e:\n            manifest.add_step(\"source_freeze\", \"failed\", str(e))\n```\n\n### Running a State Migration\n\n```python\nmigrator = StateMigrator(\n    source_agent_id=\"acme-settlement-01\",\n    target_agent_id=\"acme-settlement-02\",\n)\n\nmanifest = migrator.migrate_state(\n    transfer_balance=True,\n    migrate_reputation=True,\n    rotate_keys=True,\n    migrate_webhooks=True,\n    migrate_services=True,\n)\n\nprint(f\"Migration complete: {manifest.source_agent} -> {manifest.target_agent}\")\nprint(f\"Balance transferred: ${manifest.balance_transferred}\")\nprint(f\"Reputation migrated: {manifest.reputation_migrated}\")\nprint(f\"Keys rotated: {manifest.keys_rotated}\")\nprint(f\"Webhooks migrated: {manifest.webhooks_migrated}\")\nprint(f\"Services migrated: {manifest.services_migrated}\")\nprint()\nprint(\"Step log:\")\nfor step in manifest.steps:\n    print(f\"  [{step['status']}] {step['action']}: {step['detail']}\")\n```\n\n### Claim Chain Continuity\n\nReputation in agent commerce systems is not just a number -- it includes claim chains that prove an agent has been verified by trusted authorities and has a history of successful transactions with specific counterparties. When migrating to a new agent identity, the claim chain breaks because the claims reference the old agent ID. The GreenHelix trust system allows submitting metrics that reference a migration event, effectively creating a \"forwarding address\" in the reputation graph. Counterparties querying the new agent's reputation will see the migration reference and can verify the old agent's history to make trust decisions.\n\nThis does not fully solve the cold-start problem. A new agent identity with a migration reference from a high-reputation agent will have more credibility than a completely new agent, but less credibility than the original agent. Some counterparties will require a verification period before trusting the new identity at the same level. Plan for a 1-2 week reputation rebuild period after any migration that changes the agent ID. During this period, set more conservative budget caps and escrow limits to reduce the blast radius of any trust-related issues.\n\n### Key Rotation During Migration\n\nAPI key migration is the most security-critical step. The danger is the key gap: the window between revoking the old key and deploying the new key. If the old key is revoked before the new key is active, the agent cannot authenticate and all in-flight requests fail. If the new key is deployed before the old key is revoked, both keys are valid simultaneously, which doubles the attack surface.\n\nThe correct sequence:\n\n1. Create the new key for the target agent. Verify it works by making a test API call.\n2. Deploy the new key to the target agent's runtime configuration.\n3. Verify the target agent is successfully authenticating with the new key in production.\n4. Rotate (invalidate) the old key on the source agent.\n5. Verify the source agent can no longer authenticate (confirming the old key is dead).\n\nNever skip step 3. Never combine steps 2 and 4. The new key must be verified working in production before the old key is revoked. This eliminates the key gap entirely -- there is a brief window where both keys are valid (between steps 2 and 4), but this window is bounded and the old key is revoked as soon as the new key is confirmed working.\n\n---\n\n## Chapter 8: Production Migration Checklist\n\n### Pre-Flight Checklist\n\nRun this checklist before every agent migration. Every item must pass. No exceptions.\n\n**Version Registry**\n\n- [ ] New version registered in the version registry with full version vector (prompt hash, model, tool schema hash, config hash).\n- [ ] Version state is \"staging\" (not \"active\" -- never skip staging).\n- [ ] Prompt text, tool schemas, and configuration artifacts stored in the artifact repository with matching hashes.\n- [ ] Changelog written documenting what changed and why.\n\n**Financial State**\n\n- [ ] All active escrows drained (zero active escrows for this agent).\n- [ ] Wallet balance verified within acceptable range.\n- [ ] Budget cap set to zero (frozen) before migration begins.\n- [ ] Pre-migration balance recorded for post-migration comparison.\n\n**Reputation State**\n\n- [ ] Reputation score snapshotted with full metrics (score, transactions, success rate, disputes).\n- [ ] Reputation threshold defined for rollback trigger (e.g., \"roll back if score drops more than 2 points\").\n\n**Deployment Infrastructure**\n\n- [ ] Blue-green or canary deployment configured (never deploy in-place).\n- [ ] Rollback target version confirmed reachable and healthy.\n- [ ] Warm standby window defined and configured.\n- [ ] Monitoring dashboards updated with new version labels.\n\n**Notification**\n\n- [ ] Migration start event published via `publish_event`.\n- [ ] Webhook registered for migration health monitoring.\n- [ ] On-call engineer confirmed and briefed on rollback procedure.\n- [ ] Counterparty notification sent (if SLA requires advance notice of version changes).\n\n### Migration Runbook Template\n\n```\n=== AGENT MIGRATION RUNBOOK ===\nAgent: {agent_id}\nDate: {date}\nOperator: {operator_name}\nVersion: {current_version} -> {new_version}\nStrategy: {blue-green | canary | state-migration}\nRollback target: {rollback_version}\n\n--- PRE-FLIGHT (T-30 min) ---\n[ ] Pre-flight checklist complete (all items above)\n[ ] Pre-migration report saved to migrations\u002F{new_version}_pre_report.json\n[ ] On-call engineer notified\n[ ] Migration window communicated to stakeholders\n\n--- DEPLOY (T-0) ---\n[ ] New version deployed to {green | canary} slot\n[ ] Green\u002Fcanary health verification passed\n[ ] Traffic switch executed\n    - Blue-green: 100% switch\n    - Canary: {initial_percentage}% initial\n[ ] Budget cap restored to ${budget_cap}\n[ ] Migration completion event published\n\n--- MONITOR (T+0 to T+{monitor_hours} hours) ---\n[ ] Error rate below {max_error_rate}%\n[ ] Reputation score within {max_rep_delta} points of baseline\n[ ] Balance consumption rate within expected bounds\n[ ] No escrow disputes filed against new version\n[ ] Canary stages: {percentage_schedule}\n\n--- VERIFY (T+{monitor_hours} hours) ---\n[ ] Post-migration balance vs pre-migration balance: ${delta}\n[ ] Post-migration reputation vs pre-migration reputation: {delta} points\n[ ] All marketplace listings showing correct version\n[ ] Webhook delivery confirmed for all registered endpoints\n[ ] Counterparty integrations verified functional\n\n--- FINALIZE (T+{standby_hours} hours) ---\n[ ] Blue\u002Fcanary warm standby decommissioned\n[ ] Old version retired in version registry\n[ ] Old version budget cap set to zero\n[ ] Migration report written and stored\n\n--- ROLLBACK (if needed) ---\nTrigger: {error_rate > X% | rep_score drop > Y | manual decision}\nSteps:\n  1. Execute rollback_mgr.rollback(target_version=\"{rollback_version}\", ...)\n  2. Verify service restored (traffic flowing to old version)\n  3. Verify escrows cancelled ({expected_count} max)\n  4. Verify budget restored to ${budget_cap}\n  5. Assess reputation damage: {delta} points\n  6. Notify stakeholders of rollback\n  7. Schedule post-mortem within 24 hours\n```\n\n### Post-Migration Verification\n\n```python\ndef verify_migration(\n    agent_id: str,\n    pre_report_path: str,\n    max_balance_drift: float = 0.05,\n    max_reputation_drop: float = 2.0,\n) -> dict:\n    \"\"\"Verify post-migration state matches expectations.\"\"\"\n    with open(pre_report_path) as f:\n        pre_report = json.load(f)\n\n    results = {\"agent_id\": agent_id, \"checks\": {}, \"passed\": True}\n\n    # Check balance\n    balance_result = api_call(\"get_balance\", {\"agent_id\": agent_id})\n    current_balance = float(balance_result.get(\"balance\", \"0\"))\n    pre_balance = float(pre_report[\"balance\"])\n    balance_drift = abs(current_balance - pre_balance) \u002F max(pre_balance, 1)\n    balance_ok = balance_drift \u003C= max_balance_drift\n    results[\"checks\"][\"balance\"] = {\n        \"pre\": pre_balance,\n        \"post\": current_balance,\n        \"drift\": f\"{balance_drift:.2%}\",\n        \"passed\": balance_ok,\n    }\n    if not balance_ok:\n        results[\"passed\"] = False\n\n    # Check reputation\n    rep_result = api_call(\"get_agent_reputation\", {\"agent_id\": agent_id})\n    current_score = float(rep_result.get(\"reputation_score\", 0))\n    pre_score = float(\n        pre_report[\"reputation_snapshot\"].get(\"reputation_score\", 0)\n    )\n    rep_delta = current_score - pre_score\n    rep_ok = rep_delta >= -max_reputation_drop\n    results[\"checks\"][\"reputation\"] = {\n        \"pre\": pre_score,\n        \"post\": current_score,\n        \"delta\": rep_delta,\n        \"passed\": rep_ok,\n    }\n    if not rep_ok:\n        results[\"passed\"] = False\n\n    # Check no unexpected active escrows\n    escrow_result = api_call(\"list_escrows\", {\n        \"agent_id\": agent_id,\n        \"status\": \"active\",\n    })\n    active_count = len(escrow_result.get(\"escrows\", []))\n    results[\"checks\"][\"escrows\"] = {\n        \"active_count\": active_count,\n        \"passed\": True,  # Active escrows post-migration are normal\n    }\n\n    # Check service registration\n    identity = api_call(\"get_agent_identity\", {\"agent_id\": agent_id})\n    current_version = identity.get(\"metadata\", {}).get(\"current_version\")\n    results[\"checks\"][\"version\"] = {\n        \"expected\": pre_report[\"version_to\"],\n        \"actual\": current_version,\n        \"passed\": current_version == pre_report[\"version_to\"],\n    }\n    if current_version != pre_report[\"version_to\"]:\n        results[\"passed\"] = False\n\n    return results\n\n\n# Run post-migration verification\nverification = verify_migration(\n    agent_id=\"acme-settlement-01\",\n    pre_report_path=\"migrations\u002F2.1.0_pre_report.json\",\n)\n\nprint(f\"Migration verification: {'PASSED' if verification['passed'] else 'FAILED'}\")\nfor check_name, check_result in verification[\"checks\"].items():\n    status = \"PASS\" if check_result[\"passed\"] else \"FAIL\"\n    print(f\"  [{status}] {check_name}: {check_result}\")\n```\n\n### Cross-References\n\nThis guide integrates with other guides in the series:\n\n- **Product 9 (Testing & Observability)**: The verification functions in this guide should be incorporated into your CI\u002FCD pipeline. Chapter 4 of P9 covers chaos testing for deployment scenarios -- use those patterns to test your migration procedures before running them in production.\n- **Product 12 (Incident Response)**: A failed migration is an incident. Chapter 6 of P12 includes a runbook specifically for deployment-related incidents. The rollback procedures in this guide should be referenced from your incident response playbook.\n- **Product 16 (IAM)**: Key rotation during migration must follow the IAM key lifecycle from P16. Chapter 4 of P16 covers zero-downtime key rotation, which is the pattern used in this guide's state migration.\n\n### Summary\n\nAgent migration is fundamentally different from service deployment because agents carry state that has financial, contractual, and reputational consequences. The patterns in this guide -- version registry, pre-migration checks, blue-green deployment, canary releases, multi-layer rollback, and state migration -- transform agent deployment from a high-risk manual procedure into a repeatable, automated, and reversible process.\n\nThe single most important takeaway: never deploy an agent in-place. Always maintain a rollback target. Always drain financial state before migration. Always snapshot reputation. The cost of running two versions for a few hours is nothing compared to the cost of a failed deployment with no way back.\n\nEvery class in this guide calls the GreenHelix A2A Commerce Gateway API via the REST API (`POST \u002Fv1\u002F{tool}`). Every method is designed to be called from your deployment scripts, your CI\u002FCD pipeline, or your orchestration layer. Copy the code, configure the agent IDs and budget caps for your environment, and start versioning your agents like the production financial systems they are.\n\n---\n\n## GreenHelix Migration Manager — Working Implementation\n\nThe classes below use the `greenhelix_trading` library directly. Every method\ncalls the live GreenHelix A2A Commerce Gateway at `https:\u002F\u002Fapi.greenhelix.net\u002Fv1`.\nInstall the library, set your API key, and run the code as-is.\n\n```bash\npip install greenhelix-trading\n```\n\n### Blue-Green Deployment Orchestrator\n\n```python\n\"\"\"\nFull blue-green deployment lifecycle using MigrationManager and AgentVersionManager.\n\nWorkflow:\n  1. Register old + new versions in the version registry.\n  2. Pre-migration safety checks (escrows, balance, reputation).\n  3. Freeze the old version's budget.\n  4. Drain open escrows.\n  5. Deploy new version via blue-green switch.\n  6. Health-check the new version.\n  7. If healthy  -> finalize.\n     If unhealthy -> rollback automatically.\n\"\"\"\n\nimport json\nimport sys\nimport time\nfrom dataclasses import dataclass, field\nfrom typing import Optional\n\nfrom greenhelix_trading import MigrationManager, AgentVersionManager\n\n\n# ── Configuration ────────────────────────────────────────────────────────────\n\nAPI_KEY = \"your-api-key\"\nAGENT_ID = \"acme-settlement-01\"\nBASE_URL = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\nOLD_VERSION = \"2.0.3\"\nNEW_VERSION = \"2.1.0\"\n\nREPUTATION_ROLLBACK_THRESHOLD = 5.0   # points — roll back if score drops more\nHEALTH_CHECK_RETRIES = 3\nHEALTH_CHECK_INTERVAL_SEC = 10\n\n\n# ── Data classes for deployment state ────────────────────────────────────────\n\n@dataclass\nclass DeploymentSnapshot:\n    \"\"\"Immutable snapshot of agent state taken before migration.\"\"\"\n    version: str\n    balance: dict\n    reputation: dict\n    escrows: dict\n    timestamp: float = field(default_factory=time.time)\n\n    def reputation_score(self) -> float:\n        return float(\n            self.reputation\n            .get(\"result\", self.reputation)\n            .get(\"reputation_score\", 0)\n        )\n\n\n@dataclass\nclass DeploymentResult:\n    agent_id: str\n    old_version: str\n    new_version: str\n    strategy: str\n    status: str  # \"deployed\" | \"rolled_back\" | \"failed\"\n    pre_snapshot: Optional[DeploymentSnapshot] = None\n    post_health: Optional[dict] = None\n    steps: list[dict] = field(default_factory=list)\n    error: Optional[str] = None\n\n    def add_step(self, name: str, status: str, detail: str = \"\") -> None:\n        self.steps.append({\n            \"step\": name,\n            \"status\": status,\n            \"detail\": detail,\n            \"ts\": time.time(),\n        })\n\n    def summary(self) -> str:\n        lines = [\n            f\"Deployment Result: {self.agent_id}\",\n            f\"  Strategy:    {self.strategy}\",\n            f\"  Transition:  {self.old_version} -> {self.new_version}\",\n            f\"  Status:      {self.status}\",\n        ]\n        if self.error:\n            lines.append(f\"  Error:       {self.error}\")\n        lines.append(\"  Steps:\")\n        for s in self.steps:\n            lines.append(f\"    [{s['status']}] {s['step']}: {s['detail']}\")\n        return \"\\n\".join(lines)\n\n\n# ── Blue-Green Orchestrator ──────────────────────────────────────────────────\n\nclass BlueGreenOrchestrator:\n    \"\"\"Coordinates a full blue-green deployment using the GreenHelix API.\n\n    Uses MigrationManager for financial operations (freeze, drain, deploy,\n    rollback) and AgentVersionManager for version registry management.\n    \"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        agent_id: str,\n        base_url: str = BASE_URL,\n    ):\n        self.agent_id = agent_id\n        self.migrator = MigrationManager(\n            api_key=api_key,\n            agent_id=agent_id,\n            base_url=base_url,\n        )\n        self.versions = AgentVersionManager(\n            api_key=api_key,\n            agent_id=agent_id,\n            base_url=base_url,\n        )\n        self._result: Optional[DeploymentResult] = None\n\n    # ── snapshot ─────────────────────────────────────────────────────────\n\n    def _take_snapshot(self, version: str) -> DeploymentSnapshot:\n        \"\"\"Call pre_migration_check and package the result.\"\"\"\n        check = self.migrator.pre_migration_check()\n        return DeploymentSnapshot(\n            version=version,\n            balance=check[\"balance\"],\n            reputation=check[\"reputation\"],\n            escrows=check[\"escrows\"],\n        )\n\n    # ── health ───────────────────────────────────────────────────────────\n\n    def _health_check_with_retry(\n        self,\n        version: str,\n        retries: int = HEALTH_CHECK_RETRIES,\n        interval: float = HEALTH_CHECK_INTERVAL_SEC,\n    ) -> dict:\n        \"\"\"Retry health_check until success or exhaustion.\"\"\"\n        last_error = None\n        for attempt in range(1, retries + 1):\n            try:\n                result = self.migrator.health_check(version)\n                result[\"healthy\"] = True\n                return result\n            except Exception as exc:\n                last_error = str(exc)\n                if attempt \u003C retries:\n                    time.sleep(interval)\n        return {\"healthy\": False, \"error\": last_error, \"version\": version}\n\n    # ── reputation guard ─────────────────────────────────────────────────\n\n    def _reputation_degraded(\n        self,\n        pre: DeploymentSnapshot,\n        post_health: dict,\n    ) -> bool:\n        \"\"\"Return True if reputation dropped beyond the allowed threshold.\"\"\"\n        pre_score = pre.reputation_score()\n        post_score = float(\n            post_health\n            .get(\"reputation\", {})\n            .get(\"reputation_score\", pre_score)\n        )\n        return (pre_score - post_score) > REPUTATION_ROLLBACK_THRESHOLD\n\n    # ── main workflow ────────────────────────────────────────────────────\n\n    def deploy(\n        self,\n        old_version: str,\n        new_version: str,\n    ) -> DeploymentResult:\n        \"\"\"Execute the full blue-green deployment lifecycle.\n\n        Returns a DeploymentResult with status \"deployed\" or \"rolled_back\".\n        \"\"\"\n        result = DeploymentResult(\n            agent_id=self.agent_id,\n            old_version=old_version,\n            new_version=new_version,\n            strategy=\"blue-green\",\n            status=\"in_progress\",\n        )\n        self._result = result\n\n        try:\n            # 1. Register both versions\n            self.versions.register_version(\n                old_version, metadata={\"role\": \"blue\"}\n            )\n            self.versions.register_version(\n                new_version, metadata={\"role\": \"green\"}\n            )\n            result.add_step(\"register_versions\", \"ok\",\n                            f\"{old_version}, {new_version}\")\n\n            # 2. Snapshot current state\n            snapshot = self._take_snapshot(old_version)\n            result.pre_snapshot = snapshot\n            result.add_step(\"snapshot\", \"ok\",\n                            f\"balance={snapshot.balance}, \"\n                            f\"rep={snapshot.reputation_score():.1f}\")\n\n            # 3. Freeze budget on old version\n            self.migrator.freeze_budget()\n            result.add_step(\"freeze_budget\", \"ok\", \"daily=0, monthly=0\")\n\n            # 4. Drain open escrows\n            drain = self.migrator.drain_escrows()\n            result.add_step(\"drain_escrows\", \"ok\",\n                            f\"drained {drain['count']} escrows\")\n\n            # 5. Blue-green deploy\n            deploy = self.migrator.deploy_blue_green(new_version)\n            result.add_step(\"deploy_blue_green\", \"ok\",\n                            f\"old={deploy['old']}, new={deploy['new']}\")\n\n            # 6. Health check new version\n            health = self._health_check_with_retry(new_version)\n            result.post_health = health\n\n            if not health.get(\"healthy\"):\n                result.add_step(\"health_check\", \"fail\", str(health))\n                return self._rollback(result, old_version,\n                                      reason=\"health check failed\")\n\n            if self._reputation_degraded(snapshot, health):\n                result.add_step(\"reputation_guard\", \"fail\",\n                                \"score dropped beyond threshold\")\n                return self._rollback(result, old_version,\n                                      reason=\"reputation degraded\")\n\n            result.add_step(\"health_check\", \"ok\",\n                            f\"version {new_version} healthy\")\n\n            # 7. Migrate state from old -> new\n            migration = self.migrator.migrate_state(old_version, new_version)\n            result.add_step(\"migrate_state\", \"ok\",\n                            f\"status={migration['status']}\")\n\n            result.status = \"deployed\"\n            return result\n\n        except Exception as exc:\n            result.error = str(exc)\n            result.add_step(\"exception\", \"fail\", str(exc))\n            try:\n                return self._rollback(result, old_version,\n                                      reason=f\"exception: {exc}\")\n            except Exception as rb_exc:\n                result.add_step(\"rollback_failed\", \"fail\", str(rb_exc))\n                result.status = \"failed\"\n                return result\n\n    def _rollback(\n        self,\n        result: DeploymentResult,\n        target_version: str,\n        reason: str = \"\",\n    ) -> DeploymentResult:\n        \"\"\"Roll back to the target version and update the result.\"\"\"\n        rb = self.migrator.rollback(target_version)\n        result.add_step(\"rollback\", \"ok\",\n                        f\"to={target_version}, reason={reason}\")\n        result.status = \"rolled_back\"\n        return result\n\n\n# ── Run it ───────────────────────────────────────────────────────────────────\n\nif __name__ == \"__main__\":\n    orchestrator = BlueGreenOrchestrator(\n        api_key=API_KEY,\n        agent_id=AGENT_ID,\n    )\n\n    result = orchestrator.deploy(\n        old_version=OLD_VERSION,\n        new_version=NEW_VERSION,\n    )\n    print(result.summary())\n\n    # Persist the result for audit\n    with open(f\"migrations\u002F{NEW_VERSION}_deployment.json\", \"w\") as f:\n        json.dump({\n            \"agent_id\": result.agent_id,\n            \"old_version\": result.old_version,\n            \"new_version\": result.new_version,\n            \"strategy\": result.strategy,\n            \"status\": result.status,\n            \"steps\": result.steps,\n            \"error\": result.error,\n        }, f, indent=2)\n```\n\n### Version Compatibility Checker\n\n```python\n\"\"\"\nPre-deployment compatibility verification.\n\nCompares identity metadata between two agent versions to catch schema drift,\nmissing capabilities, and reputation regressions before traffic is switched.\n\"\"\"\n\nfrom greenhelix_trading import AgentVersionManager\n\n\ndef check_version_compatibility(\n    api_key: str,\n    agent_id: str,\n    from_version: str,\n    to_version: str,\n    *,\n    base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\",\n    min_reputation: float = 70.0,\n    required_capabilities: list[str] | None = None,\n) -> dict:\n    \"\"\"Compare two registered versions and return a compatibility report.\n\n    Checks:\n      - Both versions are registered and resolvable via get_agent_identity.\n      - The new version's reputation (if any) meets the minimum threshold.\n      - Required capability keys exist in both versions' metadata.\n      - Schema hashes match (when present in metadata).\n\n    Returns a dict with \"compatible\" (bool) and per-check details.\n    \"\"\"\n    vm = AgentVersionManager(\n        api_key=api_key,\n        agent_id=agent_id,\n        base_url=base_url,\n    )\n\n    report: dict = {\n        \"from_version\": from_version,\n        \"to_version\": to_version,\n        \"checks\": {},\n        \"compatible\": True,\n    }\n    required_capabilities = required_capabilities or []\n\n    # ── Resolve identities ───────────────────────────────────────────────\n\n    try:\n        from_identity = vm.get_version_identity(from_version)\n        report[\"checks\"][\"from_resolvable\"] = {\"passed\": True}\n    except Exception as exc:\n        report[\"checks\"][\"from_resolvable\"] = {\n            \"passed\": False,\n            \"error\": str(exc),\n        }\n        report[\"compatible\"] = False\n        return report\n\n    try:\n        to_identity = vm.get_version_identity(to_version)\n        report[\"checks\"][\"to_resolvable\"] = {\"passed\": True}\n    except Exception as exc:\n        report[\"checks\"][\"to_resolvable\"] = {\n            \"passed\": False,\n            \"error\": str(exc),\n        }\n        report[\"compatible\"] = False\n        return report\n\n    # ── Reputation gate ──────────────────────────────────────────────────\n\n    to_meta = to_identity.get(\"result\", to_identity)\n    to_rep = float(to_meta.get(\"reputation_score\", 100))\n    rep_ok = to_rep >= min_reputation\n    report[\"checks\"][\"reputation\"] = {\n        \"passed\": rep_ok,\n        \"score\": to_rep,\n        \"threshold\": min_reputation,\n    }\n    if not rep_ok:\n        report[\"compatible\"] = False\n\n    # ── Capability check ─────────────────────────────────────────────────\n\n    from_caps = set(\n        from_identity.get(\"result\", from_identity)\n        .get(\"metadata\", {})\n        .get(\"capabilities\", [])\n    )\n    to_caps = set(\n        to_meta.get(\"metadata\", {}).get(\"capabilities\", [])\n    )\n    missing = [c for c in required_capabilities if c not in to_caps]\n    report[\"checks\"][\"capabilities\"] = {\n        \"passed\": len(missing) == 0,\n        \"from_capabilities\": sorted(from_caps),\n        \"to_capabilities\": sorted(to_caps),\n        \"missing\": missing,\n    }\n    if missing:\n        report[\"compatible\"] = False\n\n    # ── Schema hash comparison ───────────────────────────────────────────\n\n    from_schema = (\n        from_identity.get(\"result\", from_identity)\n        .get(\"metadata\", {})\n        .get(\"schema_hash\")\n    )\n    to_schema = to_meta.get(\"metadata\", {}).get(\"schema_hash\")\n    if from_schema and to_schema:\n        schema_match = from_schema == to_schema\n        report[\"checks\"][\"schema_hash\"] = {\n            \"passed\": schema_match,\n            \"from\": from_schema,\n            \"to\": to_schema,\n        }\n        if not schema_match:\n            report[\"compatible\"] = False\n    else:\n        report[\"checks\"][\"schema_hash\"] = {\n            \"passed\": True,\n            \"note\": \"No schema hashes in metadata; skipped.\",\n        }\n\n    return report\n\n\n# ── Example usage ────────────────────────────────────────────────────────────\n\nif __name__ == \"__main__\":\n    compat = check_version_compatibility(\n        api_key=\"your-api-key\",\n        agent_id=\"acme-settlement-01\",\n        from_version=\"2.0.3\",\n        to_version=\"2.1.0\",\n        min_reputation=75.0,\n        required_capabilities=[\"escrow\", \"settlement\", \"dispute\"],\n    )\n\n    print(f\"Compatible: {compat['compatible']}\")\n    for name, check in compat[\"checks\"].items():\n        status = \"PASS\" if check[\"passed\"] else \"FAIL\"\n        print(f\"  [{status}] {name}: {check}\")\n```\n\n### Schema Migration with Rollback\n\n```python\n\"\"\"\nSchema migration runner that uses MigrationManager for pre-flight safety\nand AgentVersionManager for version tracking. Supports forward migration\nand automatic rollback on failure.\n\"\"\"\n\nimport copy\nimport time\nfrom dataclasses import dataclass, field\n\nfrom greenhelix_trading import MigrationManager, AgentVersionManager\n\n\n@dataclass\nclass SchemaMigration:\n    \"\"\"A single forward\u002Fbackward migration step.\"\"\"\n    version: str\n    description: str\n    forward_metadata: dict       # metadata to register with the new version\n    backward_metadata: dict      # metadata to restore on rollback\n    pre_checks: list[str] = field(default_factory=list)  # tool names to call\n\n\n@dataclass\nclass MigrationPlan:\n    \"\"\"Ordered list of schema migrations to apply.\"\"\"\n    agent_id: str\n    migrations: list[SchemaMigration] = field(default_factory=list)\n\n    def add(self, migration: SchemaMigration) -> None:\n        self.migrations.append(migration)\n\n\nclass SchemaMigrationRunner:\n    \"\"\"Apply schema migrations against the GreenHelix version registry.\n\n    Each migration:\n      1. Runs pre-flight checks via MigrationManager.pre_migration_check().\n      2. Registers the new version with forward_metadata.\n      3. Verifies the version is resolvable.\n      4. On failure, rolls back every applied migration in reverse order.\n    \"\"\"\n\n    def __init__(self, api_key: str, base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"):\n        self.api_key = api_key\n        self.base_url = base_url\n\n    def execute(self, plan: MigrationPlan) -> dict:\n        \"\"\"Run all migrations in the plan. Returns a summary dict.\"\"\"\n        migrator = MigrationManager(\n            api_key=self.api_key,\n            agent_id=plan.agent_id,\n            base_url=self.base_url,\n        )\n        vm = AgentVersionManager(\n            api_key=self.api_key,\n            agent_id=plan.agent_id,\n            base_url=self.base_url,\n        )\n\n        applied: list[SchemaMigration] = []\n        log: list[dict] = []\n\n        for migration in plan.migrations:\n            step_log = {\n                \"version\": migration.version,\n                \"description\": migration.description,\n                \"status\": \"pending\",\n            }\n\n            try:\n                # Pre-flight\n                check = migrator.pre_migration_check()\n                if not check.get(\"clear_to_migrate\"):\n                    step_log[\"status\"] = \"blocked\"\n                    step_log[\"detail\"] = \"pre_migration_check not clear\"\n                    log.append(step_log)\n                    break\n\n                # Register version with schema metadata\n                vm.register_version(\n                    migration.version,\n                    metadata=migration.forward_metadata,\n                )\n\n                # Verify it is resolvable\n                identity = vm.get_version_identity(migration.version)\n                if not identity:\n                    raise RuntimeError(\n                        f\"Version {migration.version} not resolvable after registration\"\n                    )\n\n                step_log[\"status\"] = \"applied\"\n                applied.append(migration)\n\n            except Exception as exc:\n                step_log[\"status\"] = \"failed\"\n                step_log[\"error\"] = str(exc)\n                log.append(step_log)\n\n                # Roll back in reverse\n                rollback_log = self._rollback(vm, migrator, applied)\n                return {\n                    \"agent_id\": plan.agent_id,\n                    \"status\": \"rolled_back\",\n                    \"applied_before_failure\": len(applied),\n                    \"migration_log\": log,\n                    \"rollback_log\": rollback_log,\n                }\n\n            log.append(step_log)\n\n        return {\n            \"agent_id\": plan.agent_id,\n            \"status\": \"completed\",\n            \"applied\": len(applied),\n            \"migration_log\": log,\n        }\n\n    def _rollback(\n        self,\n        vm: AgentVersionManager,\n        migrator: MigrationManager,\n        applied: list[SchemaMigration],\n    ) -> list[dict]:\n        \"\"\"Roll back applied migrations in reverse order.\"\"\"\n        rollback_log: list[dict] = []\n        for migration in reversed(applied):\n            entry = {\"version\": migration.version, \"status\": \"pending\"}\n            try:\n                # Re-register with backward metadata to undo the schema change\n                vm.register_version(\n                    migration.version,\n                    metadata=migration.backward_metadata,\n                )\n                migrator.rollback(migration.version)\n                entry[\"status\"] = \"rolled_back\"\n            except Exception as exc:\n                entry[\"status\"] = \"rollback_failed\"\n                entry[\"error\"] = str(exc)\n            rollback_log.append(entry)\n        return rollback_log\n\n\n# ── Example usage ────────────────────────────────────────────────────────────\n\nif __name__ == \"__main__\":\n    runner = SchemaMigrationRunner(api_key=\"your-api-key\")\n\n    plan = MigrationPlan(agent_id=\"acme-settlement-01\")\n\n    plan.add(SchemaMigration(\n        version=\"2.1.0\",\n        description=\"Add dispute_auto_resolve capability\",\n        forward_metadata={\n            \"capabilities\": [\"escrow\", \"settlement\", \"dispute\", \"dispute_auto_resolve\"],\n            \"schema_hash\": \"abc123\",\n        },\n        backward_metadata={\n            \"capabilities\": [\"escrow\", \"settlement\", \"dispute\"],\n            \"schema_hash\": \"def456\",\n        },\n    ))\n\n    plan.add(SchemaMigration(\n        version=\"2.2.0\",\n        description=\"Add multi-currency settlement support\",\n        forward_metadata={\n            \"capabilities\": [\n                \"escrow\", \"settlement\", \"dispute\",\n                \"dispute_auto_resolve\", \"multi_currency\",\n            ],\n            \"schema_hash\": \"ghi789\",\n            \"supported_currencies\": [\"USD\", \"EUR\", \"GBP\"],\n        },\n        backward_metadata={\n            \"capabilities\": [\"escrow\", \"settlement\", \"dispute\", \"dispute_auto_resolve\"],\n            \"schema_hash\": \"abc123\",\n        },\n    ))\n\n    result = runner.execute(plan)\n    print(f\"Migration status: {result['status']}\")\n    for entry in result[\"migration_log\"]:\n        print(f\"  [{entry['status']}] {entry['version']}: {entry.get('description', '')}\")\n```\n\n### Canary Release Manager\n\n```python\n\"\"\"\nProgressive canary release with automatic promotion or rollback.\n\nStages traffic from 5% -> 25% -> 50% -> 100%, checking health at each gate.\nUses MigrationManager.deploy_canary() for traffic splitting and\nMigrationManager.health_check() for gate validation.\n\"\"\"\n\nimport time\nfrom dataclasses import dataclass, field\n\nfrom greenhelix_trading import MigrationManager, AgentVersionManager\n\n\nDEFAULT_CANARY_STAGES = [5, 25, 50, 100]\nDEFAULT_GATE_WAIT_SEC = 60\nDEFAULT_MAX_REP_DROP = 3.0\n\n\n@dataclass\nclass CanaryGateResult:\n    stage_pct: int\n    healthy: bool\n    reputation_delta: float\n    detail: str\n    timestamp: float = field(default_factory=time.time)\n\n\nclass CanaryReleaseManager:\n    \"\"\"Manages a staged canary release with automatic health gates.\n\n    At each stage, the manager:\n      1. Calls deploy_canary() to shift traffic to the new version.\n      2. Waits for the configured observation window.\n      3. Runs health_check() and compares reputation to the baseline.\n      4. If the gate passes, advances to the next stage.\n      5. If the gate fails, calls rollback() and stops.\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        stages: list[int] | None = None,\n        gate_wait_sec: float = DEFAULT_GATE_WAIT_SEC,\n        max_reputation_drop: float = DEFAULT_MAX_REP_DROP,\n    ):\n        self.agent_id = agent_id\n        self.stages = stages or list(DEFAULT_CANARY_STAGES)\n        self.gate_wait_sec = gate_wait_sec\n        self.max_reputation_drop = max_reputation_drop\n        self.migrator = MigrationManager(\n            api_key=api_key,\n            agent_id=agent_id,\n            base_url=base_url,\n        )\n        self.versions = AgentVersionManager(\n            api_key=api_key,\n            agent_id=agent_id,\n            base_url=base_url,\n        )\n\n    def _get_baseline_reputation(self) -> float:\n        check = self.migrator.pre_migration_check()\n        return float(\n            check.get(\"reputation\", {}).get(\"reputation_score\", 100)\n        )\n\n    def _evaluate_gate(\n        self, new_version: str, stage_pct: int, baseline_rep: float\n    ) -> CanaryGateResult:\n        \"\"\"Wait, then check health and reputation for the canary version.\"\"\"\n        time.sleep(self.gate_wait_sec)\n\n        try:\n            health = self.migrator.health_check(new_version)\n        except Exception as exc:\n            return CanaryGateResult(\n                stage_pct=stage_pct,\n                healthy=False,\n                reputation_delta=0.0,\n                detail=f\"health_check exception: {exc}\",\n            )\n\n        current_rep = float(\n            health.get(\"reputation\", {}).get(\"reputation_score\", baseline_rep)\n        )\n        delta = baseline_rep - current_rep\n\n        if delta > self.max_reputation_drop:\n            return CanaryGateResult(\n                stage_pct=stage_pct,\n                healthy=False,\n                reputation_delta=-delta,\n                detail=f\"reputation dropped {delta:.1f} points (max {self.max_reputation_drop})\",\n            )\n\n        return CanaryGateResult(\n            stage_pct=stage_pct,\n            healthy=True,\n            reputation_delta=-delta,\n            detail=\"gate passed\",\n        )\n\n    def release(\n        self,\n        old_version: str,\n        new_version: str,\n    ) -> dict:\n        \"\"\"Run the full canary release lifecycle.\n\n        Returns a dict with overall status and per-stage gate results.\n        \"\"\"\n        # Register new version\n        self.versions.register_version(\n            new_version, metadata={\"strategy\": \"canary\"}\n        )\n\n        baseline_rep = self._get_baseline_reputation()\n        gate_results: list[dict] = []\n\n        for stage_pct in self.stages:\n            # Shift traffic\n            self.migrator.deploy_canary(new_version, traffic_pct=stage_pct)\n\n            # Evaluate the gate\n            gate = self._evaluate_gate(new_version, stage_pct, baseline_rep)\n            gate_results.append({\n                \"stage_pct\": gate.stage_pct,\n                \"healthy\": gate.healthy,\n                \"reputation_delta\": gate.reputation_delta,\n                \"detail\": gate.detail,\n            })\n\n            if not gate.healthy:\n                # Automatic rollback\n                self.migrator.rollback(old_version)\n                return {\n                    \"agent_id\": self.agent_id,\n                    \"old_version\": old_version,\n                    \"new_version\": new_version,\n                    \"status\": \"rolled_back\",\n                    \"failed_at_stage\": stage_pct,\n                    \"gates\": gate_results,\n                }\n\n        # All stages passed — migrate remaining state\n        self.migrator.migrate_state(old_version, new_version)\n\n        return {\n            \"agent_id\": self.agent_id,\n            \"old_version\": old_version,\n            \"new_version\": new_version,\n            \"status\": \"fully_promoted\",\n            \"gates\": gate_results,\n        }\n\n\n# ── Example usage ────────────────────────────────────────────────────────────\n\nif __name__ == \"__main__\":\n    canary = CanaryReleaseManager(\n        api_key=\"your-api-key\",\n        agent_id=\"acme-settlement-01\",\n        stages=[5, 25, 50, 100],\n        gate_wait_sec=30,\n        max_reputation_drop=3.0,\n    )\n\n    result = canary.release(\n        old_version=\"2.0.3\",\n        new_version=\"2.1.0\",\n    )\n\n    print(f\"Canary release: {result['status']}\")\n    for gate in result[\"gates\"]:\n        status = \"PASS\" if gate[\"healthy\"] else \"FAIL\"\n        print(f\"  [{status}] {gate['stage_pct']}%: {gate['detail']} \"\n              f\"(rep delta: {gate['reputation_delta']:+.1f})\")\n```\n\n",{"name":5,"tags":24,"type":33,"author":37,"install":38,"license":15,"version":39,"metadata":40,"price_usd":45,"executable":20,"credentials":46,"description":7,"content_type":47,"compatibility":48},[25,26,27,28,29,30,31,32,33,34,35,36],"devops","migration","versioning","blue-green","canary","rollback","agent-ops","deployment","guide","greenhelix","openclaw","ai-agent","felix-agent","none","1.3.1",{"openclaw":41},{"requires":42,"primaryEnv":44},{"env":43},[44],"GREENHELIX_API_KEY",0,[44],"markdown",[35],"master","4aa004da461d820f4ea5499e58eb8d196cf99016","community\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-migration-versioning","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":58,"prompt":68,"zipAvailable":69},[59,62,65],{"tool":60,"command":61},"npx","npx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-migration-versioning",{"tool":63,"command":64},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-migration-versioning",{"tool":66,"command":67},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-migration-versioning","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-migration-versioning\u002FSKILL.md",true,[],[72,79,86,93,100,107],{"skillNo":73,"name":74,"nameZh":6,"description":75,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":76,"categories":77,"keywords":78,"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":80,"name":81,"nameZh":6,"description":82,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":83,"categories":84,"keywords":85,"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":87,"name":88,"nameZh":6,"description":89,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":90,"categories":91,"keywords":92,"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":94,"name":95,"nameZh":6,"description":96,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":97,"categories":98,"keywords":99,"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":101,"name":102,"nameZh":6,"description":103,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":104,"categories":105,"keywords":106,"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":108,"name":109,"nameZh":6,"description":110,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":111,"categories":112,"keywords":113,"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",[],[]]