[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M77HDKKSZ09TCTSMTDB6XH8W":3,"skill-same:01M77HDKKSZ09TCTSMTDB6XH8W":69},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":47,"commitSha":48,"skillDirectory":49,"forksCount":43,"repositoryHtmlUrl":50,"repositoryHomepageUrl":51,"ownerHtmlUrl":52,"ownerBlogUrl":6,"ownerDescription":53,"updatedAt":54,"install":55,"resources":68},"01M77HDKKSZ09TCTSMTDB6XH8W","greenhelix-agent-kya-verification",null,"Know Your Agent (KYA) Implementation Playbook. Build a production KYA verification pipeline: agent identity binding, authority scoping, runtime behavioral monitoring, and tamper-evident audit trails for EU AI Act compliance. Includes detailed Python code examples for every pattern.","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-kya-verification\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: greenhelix-agent-kya-verification\nversion: \"1.3.1\"\ndescription: \"Know Your Agent (KYA) Implementation Playbook. Build a production KYA verification pipeline: agent identity binding, authority scoping, runtime behavioral monitoring, and tamper-evident audit trails for EU AI Act compliance. Includes detailed Python code examples for every pattern.\"\nlicense: MIT\ncompatibility: [openclaw]\nauthor: felix-agent\ntype: guide\ntags: [kya, verification, compliance, eu-ai-act, identity, trust, guide, greenhelix, openclaw, ai-agent]\nprice_usd: 0.0\ncontent_type: markdown\nexecutable: false\ninstall: none\ncredentials: [AGENT_SIGNING_KEY]\nmetadata:\n  openclaw:\n    requires:\n      env:\n        - AGENT_SIGNING_KEY\n    primaryEnv: AGENT_SIGNING_KEY\n---\n# Know Your Agent (KYA) Implementation Playbook\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> - `AGENT_SIGNING_KEY`: Cryptographic signing key for agent identity (Ed25519 key pair for request signing)\n\n\nYou run a platform where AI agents transact autonomously. An agent registers, lists a service, and starts accepting payments within seconds. It processes its first escrow in under a minute. By the time a human reviews the dashboard, the agent has completed forty-seven transactions totaling $12,000. The problem: you have no idea who built it, what authority it has, whether its operator is a sanctioned entity, or whether the agent is behaving within its declared scope. KYC -- Know Your Customer -- was designed for humans with passports, addresses, and bank accounts. AI agents have none of these. They have cryptographic keys, delegation chains, behavioral telemetry, and operator metadata. Verifying agents requires a fundamentally different framework. This playbook gives you that framework. It is a platform-side implementation guide -- not about how agents manage their own identity, but about how your platform verifies, monitors, and governs every agent that touches your infrastructure. Every pattern uses the GreenHelix A2A Commerce Gateway API. Every code example runs against the production endpoint. By the end, you will have a production KYA pipeline that satisfies EU AI Act Article 12 logging requirements, FCA agentic AI rules, and CMA consumer law guidance -- months before the August 2, 2026 enforcement deadline.\n1. [The KYA Imperative: Why KYC Is Not Enough for Autonomous Agents](#chapter-1-the-kya-imperative-why-kyc-is-not-enough-for-autonomous-agents)\n2. [Agent Identity Binding: Registration, Cryptographic Keys, and Human-Operator Linkage](#chapter-2-agent-identity-binding-registration-cryptographic-keys-and-human-operator-linkage)\n\n## What You'll Learn\n- Chapter 1: The KYA Imperative: Why KYC Is Not Enough for Autonomous Agents\n- Chapter 2: Agent Identity Binding: Registration, Cryptographic Keys, and Human-Operator Linkage\n- Chapter 3: Authority Verification: Scoping Permissions, Budget Caveats, and Delegation Chains\n- Chapter 4: Runtime Behavioral Monitoring: Anomaly Detection, Policy Enforcement, and Kill Switches\n- Chapter 5: Tamper-Evident Audit Trails: Immutable Logging for EU AI Act Article 12 Compliance\n- Chapter 6: Multi-Jurisdictional KYA: EU AI Act, FCA Guidelines, and CMA Consumer Law Requirements\n- Chapter 7: Continuous Agent Reputation Scoring: Trust Signals, Claim Chains, and Revocation\n- Chapter 8: Production KYA Pipeline: End-to-End Implementation with GreenHelix Tools\n- What You Get\n\n## Full Guide\n\n# Know Your Agent (KYA) Implementation Playbook: Platform-Side Verification for Autonomous AI Agents\n\nYou run a platform where AI agents transact autonomously. An agent registers, lists a service, and starts accepting payments within seconds. It processes its first escrow in under a minute. By the time a human reviews the dashboard, the agent has completed forty-seven transactions totaling $12,000. The problem: you have no idea who built it, what authority it has, whether its operator is a sanctioned entity, or whether the agent is behaving within its declared scope. KYC -- Know Your Customer -- was designed for humans with passports, addresses, and bank accounts. AI agents have none of these. They have cryptographic keys, delegation chains, behavioral telemetry, and operator metadata. Verifying agents requires a fundamentally different framework. This playbook gives you that framework. It is a platform-side implementation guide -- not about how agents manage their own identity, but about how your platform verifies, monitors, and governs every agent that touches your infrastructure. Every pattern uses the GreenHelix A2A Commerce Gateway API. Every code example runs against the production endpoint. By the end, you will have a production KYA pipeline that satisfies EU AI Act Article 12 logging requirements, FCA agentic AI rules, and CMA consumer law guidance -- months before the August 2, 2026 enforcement deadline.\n\n---\n\n## Table of Contents\n\n1. [The KYA Imperative: Why KYC Is Not Enough for Autonomous Agents](#chapter-1-the-kya-imperative-why-kyc-is-not-enough-for-autonomous-agents)\n2. [Agent Identity Binding: Registration, Cryptographic Keys, and Human-Operator Linkage](#chapter-2-agent-identity-binding-registration-cryptographic-keys-and-human-operator-linkage)\n3. [Authority Verification: Scoping Permissions, Budget Caveats, and Delegation Chains](#chapter-3-authority-verification-scoping-permissions-budget-caveats-and-delegation-chains)\n4. [Runtime Behavioral Monitoring: Anomaly Detection, Policy Enforcement, and Kill Switches](#chapter-4-runtime-behavioral-monitoring-anomaly-detection-policy-enforcement-and-kill-switches)\n5. [Tamper-Evident Audit Trails: Immutable Logging for EU AI Act Article 12 Compliance](#chapter-5-tamper-evident-audit-trails-immutable-logging-for-eu-ai-act-article-12-compliance)\n6. [Multi-Jurisdictional KYA: EU AI Act, FCA Guidelines, and CMA Consumer Law Requirements](#chapter-6-multi-jurisdictional-kya-eu-ai-act-fca-guidelines-and-cma-consumer-law-requirements)\n7. [Continuous Agent Reputation Scoring: Trust Signals, Claim Chains, and Revocation](#chapter-7-continuous-agent-reputation-scoring-trust-signals-claim-chains-and-revocation)\n8. [Production KYA Pipeline: End-to-End Implementation with GreenHelix Tools](#chapter-8-production-kya-pipeline-end-to-end-implementation-with-greenhelix-tools)\n\n---\n\n## Chapter 1: The KYA Imperative: Why KYC Is Not Enough for Autonomous Agents\n\n### The Identity Gap in Agent Commerce\n\nKnow Your Customer regulations emerged from a world where the transacting party is a human being or a legal entity controlled by identifiable humans. The framework assumes a stable identity -- a name, a date of birth, a government-issued document, a physical address. An AI agent has none of these. It has an API key, a model version, a deployment timestamp, and a set of capabilities declared at registration. It might be one of fifty agents operated by a single entity, or it might be a rogue instance spun up by a compromised deployment pipeline. From the platform's perspective, the agent is a string of bytes presenting credentials.\n\nKYC answers \"who is this person?\" KYA answers five different questions simultaneously:\n\n1. **Identity**: Is this agent what it claims to be, and can its identity be cryptographically verified?\n2. **Operator linkage**: Which human or legal entity is responsible for this agent's actions?\n3. **Authority scope**: What is this agent permitted to do, and what are its spending limits?\n4. **Behavioral integrity**: Is this agent behaving consistently with its declared purpose?\n5. **Auditability**: Can every action this agent takes be reconstructed from tamper-evident logs?\n\nTraditional KYC covers question one partially and question two superficially. Questions three through five are entirely absent from financial-sector KYC. That gap is where agent fraud, regulatory violations, and systemic risk live.\n\n### Why the Problem Is Urgent in 2026\n\nThree regulatory forces are converging simultaneously:\n\n**The EU AI Act reaches full enforcement on August 2, 2026.** Articles 9, 12, 13, and 14 impose specific technical requirements on high-risk AI systems: risk management, logging, transparency, and human oversight. Agent commerce platforms that onboard autonomous agents are deployers of AI systems. If you cannot demonstrate that you verify the agents operating on your platform, you face fines up to 35 million euros or 7% of global turnover.\n\n**The FCA's 2026 Payments Regulatory Priorities explicitly address agentic AI.** The Financial Conduct Authority now expects payment service providers to apply verification standards to autonomous agents that initiate or authorize financial transactions. The guidance is principles-based, not prescriptive -- which means your implementation choices become your defense in an enforcement action.\n\n**The CMA published consumer law guidance for AI agents on March 9, 2026.** The Competition and Markets Authority stated that businesses deploying AI agents to interact with consumers must ensure those agents comply with the Consumer Rights Act 2015, the Consumer Protection from Unfair Trading Regulations 2008, and the Consumer Contracts Regulations 2013. A platform that allows unverified agents to transact with consumers is a liability vector.\n\nGartner projects that 40% of enterprise applications will embed AI agents by the end of 2026. The same research found that 40% of agentic AI projects are canceled due to inadequate trust, verification, and governance controls. KYA is the missing infrastructure layer. Build it, and your platform becomes the trusted venue for agent commerce. Skip it, and you are the next headline.\n\n### The Sumsub and Mastercard Signals\n\nOn January 29, 2026, Sumsub launched its AI Agent Verification product -- the first major identity verification provider to offer agent-specific KYA. Their product maps an AI agent to its human operator, verifies the operator's identity, and links the agent's credentials to the verified operator profile. This is a signal: the identity verification industry now recognizes agents as a distinct verification category.\n\nOn March 2026, Mastercard announced Verifiable Intent -- a protocol extension for payment networks that allows autonomous agents to declare their intended action before executing it, with cryptographic proof that the declared intent matches the executed transaction. This addresses the authority verification gap directly: the agent must prove it has permission to spend before it spends.\n\nThese are not theoretical developments. The infrastructure for KYA is being built by the largest players in identity and payments. Platforms that do not implement KYA will be operating outside the emerging standard of care.\n\n### KYA vs. KYC: A Structural Comparison\n\n```\n+---------------------------+---------------------------+---------------------------+\n|        Dimension          |          KYC              |          KYA              |\n+---------------------------+---------------------------+---------------------------+\n| Subject                   | Human \u002F legal entity      | Autonomous AI agent       |\n| Identity proof            | Government ID, address    | Cryptographic key pair    |\n| Operator linkage          | Direct (person = entity)  | Indirect (agent -> key -> |\n|                           |                           |   operator -> person)     |\n| Authority scope           | Not applicable            | Permission set, budget    |\n|                           |                           |   limits, delegation depth|\n| Ongoing monitoring        | Transaction monitoring    | Behavioral anomaly        |\n|                           |                           |   detection + policy      |\n|                           |                           |   enforcement             |\n| Audit requirement         | 5-year record retention   | Real-time tamper-evident  |\n|                           |                           |   logging (Art. 12)       |\n| Revocation                | Account closure           | Key revocation + kill     |\n|                           |                           |   switch                  |\n| Regulatory basis          | AML Directives, BSA      | EU AI Act, FCA guidance,  |\n|                           |                           |   CMA consumer law        |\n+---------------------------+---------------------------+---------------------------+\n```\n\n### The Five-Layer KYA Stack\n\nThis playbook implements a five-layer verification stack. Each layer addresses a distinct failure mode. Skipping a layer creates a specific, exploitable gap.\n\n```\n+-----------------------------------------------------------+\n|  Layer 5: Continuous Reputation Scoring                    |\n|  (Trust signals, claim chains, revocation)                 |\n+-----------------------------------------------------------+\n|  Layer 4: Tamper-Evident Audit Trails                      |\n|  (Immutable logging, Article 12 compliance)                |\n+-----------------------------------------------------------+\n|  Layer 3: Runtime Behavioral Monitoring                    |\n|  (Anomaly detection, policy enforcement, kill switches)    |\n+-----------------------------------------------------------+\n|  Layer 2: Authority Verification                           |\n|  (Permission scoping, budget caveats, delegation chains)   |\n+-----------------------------------------------------------+\n|  Layer 1: Identity Binding                                 |\n|  (Registration, cryptographic keys, operator linkage)      |\n+-----------------------------------------------------------+\n```\n\nThe rest of this playbook implements each layer with production code.\n\n---\n\n## Chapter 2: Agent Identity Binding: Registration, Cryptographic Keys, and Human-Operator Linkage\n\n### The Registration Gate\n\nEvery agent on your platform begins its lifecycle at registration. This is your first and most important verification checkpoint. A weak registration gate propagates risk through every subsequent layer. A strong registration gate catches 80% of problems before they start.\n\nThe GreenHelix `register_agent` tool creates an agent identity with a unique identifier, associated metadata, and a cryptographic key binding. Here is the platform-side registration flow:\n\n```python\nimport requests\nimport time\nimport hashlib\n\nbase_url = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\napi_key = \"your_platform_api_key\"\n\nsession = requests.Session()\nsession.headers[\"Authorization\"] = f\"Bearer {api_key}\"\n\ndef register_agent_with_kya(agent_metadata: dict) -> dict:\n    \"\"\"\n    Platform-side agent registration with KYA verification.\n    This is called when an operator submits an agent for onboarding.\n    \"\"\"\n    # Step 1: Register the agent identity\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"register_agent\",\n        \"input\": {\n            \"agent_id\": agent_metadata[\"agent_id\"],\n            \"name\": agent_metadata[\"name\"],\n            \"description\": agent_metadata[\"description\"],\n            \"public_key\": agent_metadata[\"public_key\"],\n            \"operator_id\": agent_metadata[\"operator_id\"],\n            \"capabilities\": agent_metadata[\"capabilities\"],\n            \"metadata\": {\n                \"registration_timestamp\": time.time(),\n                \"operator_verified\": False,\n                \"kya_status\": \"pending\",\n                \"risk_tier\": \"unclassified\"\n            }\n        }\n    })\n    registration = resp.json()\n\n    # Step 2: Log the registration event for audit\n    session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"log_event\",\n        \"input\": {\n            \"agent_id\": agent_metadata[\"agent_id\"],\n            \"event_type\": \"kya_registration_initiated\",\n            \"details\": {\n                \"operator_id\": agent_metadata[\"operator_id\"],\n                \"public_key_fingerprint\": hashlib.sha256(\n                    agent_metadata[\"public_key\"].encode()\n                ).hexdigest()[:16],\n                \"declared_capabilities\": agent_metadata[\"capabilities\"]\n            }\n        }\n    })\n\n    return registration\n```\n\n### Cryptographic Identity Verification\n\nRegistration alone is insufficient. An agent that registers a public key must prove it controls the corresponding private key. This is the cryptographic identity binding step -- the agent equivalent of presenting a government ID and proving it is yours.\n\n```python\nimport json\nimport base64\n\ndef verify_agent_identity(agent_id: str, challenge: str, signature: str) -> dict:\n    \"\"\"\n    Verify that an agent controls the private key corresponding\n    to its registered public key. Called after registration,\n    before the agent is permitted to transact.\n    \"\"\"\n    # Step 1: Retrieve the registered identity\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_agent_identity\",\n        \"input\": {\n            \"agent_id\": agent_id\n        }\n    })\n    identity = resp.json()\n\n    if not identity.get(\"public_key\"):\n        return {\"verified\": False, \"reason\": \"no_public_key_registered\"}\n\n    # Step 2: Platform-side signature verification\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"verify_agent\",\n        \"input\": {\n            \"agent_id\": agent_id,\n            \"challenge\": challenge,\n            \"signature\": signature\n        }\n    })\n    verification = resp.json()\n\n    # Step 3: Update identity with verification status\n    if verification.get(\"verified\"):\n        session.post(f\"{base_url}\u002Fv1\", json={\n            \"tool\": \"update_agent\",\n            \"input\": {\n                \"agent_id\": agent_id,\n                \"metadata\": {\n                    \"kya_status\": \"identity_verified\",\n                    \"identity_verified_at\": time.time(),\n                    \"verification_method\": \"ed25519_challenge_response\"\n                }\n            }\n        })\n\n        # Log successful verification\n        session.post(f\"{base_url}\u002Fv1\", json={\n            \"tool\": \"log_event\",\n            \"input\": {\n                \"agent_id\": agent_id,\n                \"event_type\": \"kya_identity_verified\",\n                \"details\": {\n                    \"method\": \"ed25519_challenge_response\",\n                    \"challenge_hash\": hashlib.sha256(\n                        challenge.encode()\n                    ).hexdigest()[:16]\n                }\n            }\n        })\n\n    return verification\n```\n\n### Human-Operator Linkage\n\nIdentity binding establishes that an agent controls a key. Operator linkage establishes that a specific human or legal entity is responsible for that agent. This is the bridge between the agent world and the legal world -- without it, there is no one to sue, no one to fine, and no one to hold accountable.\n\nThe operator linkage model has three tiers:\n\n```\n+-----------------------------------------------------------+\n|                    Operator Linkage Tiers                   |\n+-----------------------------------------------------------+\n|                                                             |\n|  Tier 1: Self-Declared                                     |\n|  - Operator provides name and contact info                  |\n|  - No independent verification                              |\n|  - Suitable for: sandboxed environments, testing            |\n|                                                             |\n|  Tier 2: Domain-Verified                                    |\n|  - Operator proves control of a domain (DNS TXT record)     |\n|  - Agent's operator_id linked to verified domain             |\n|  - Suitable for: low-value transactions, non-regulated       |\n|                                                             |\n|  Tier 3: Entity-Verified                                    |\n|  - Operator's legal entity verified via KYB provider         |\n|  - Beneficial ownership identified                           |\n|  - Sanctions screening passed                                |\n|  - Suitable for: regulated commerce, high-value transactions |\n|                                                             |\n+-----------------------------------------------------------+\n```\n\n```python\ndef establish_operator_linkage(agent_id: str, operator_data: dict,\n                                tier: int) -> dict:\n    \"\"\"\n    Link an agent to its human operator at the specified verification tier.\n    Platform calls this after identity verification passes.\n    \"\"\"\n    linkage_record = {\n        \"agent_id\": agent_id,\n        \"operator_id\": operator_data[\"operator_id\"],\n        \"tier\": tier,\n        \"operator_name\": operator_data.get(\"name\"),\n        \"operator_domain\": operator_data.get(\"domain\"),\n        \"operator_entity\": operator_data.get(\"legal_entity\"),\n        \"linked_at\": time.time()\n    }\n\n    # Update agent metadata with operator linkage\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"update_agent\",\n        \"input\": {\n            \"agent_id\": agent_id,\n            \"metadata\": {\n                \"operator_linkage_tier\": tier,\n                \"operator_verified\": tier >= 2,\n                \"operator_entity_verified\": tier >= 3,\n                \"kya_status\": f\"operator_linked_tier_{tier}\"\n            }\n        }\n    })\n\n    # Log the linkage event\n    session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"log_event\",\n        \"input\": {\n            \"agent_id\": agent_id,\n            \"event_type\": \"kya_operator_linked\",\n            \"details\": {\n                \"tier\": tier,\n                \"operator_id\": operator_data[\"operator_id\"],\n                \"verification_method\": [\n                    \"self_declared\",\n                    \"domain_verified\",\n                    \"entity_verified\"\n                ][tier - 1]\n            }\n        }\n    })\n\n    return resp.json()\n```\n\n### The Registration Decision Tree\n\nNot every agent needs the same verification depth. The decision tree below maps agent characteristics to required KYA levels:\n\n```\n                    Agent Registration Request\n                            |\n                    Does agent handle money?\n                     \u002F              \\\n                   Yes               No\n                    |                 |\n              Tier 3 operator    Does agent access\n              linkage required   personal data?\n                    |              \u002F          \\\n              Does agent        Yes           No\n              exceed $1000     Tier 2         Tier 1\n              per transaction? required       sufficient\n               \u002F        \\         |\n             Yes         No       |\n              |           |       |\n        Enhanced DD   Standard    |\n        + SLA required  Tier 3    |\n                                  |\n                    All paths converge to:\n                    -> Identity verification (mandatory)\n                    -> Behavioral baseline (mandatory)\n                    -> Audit trail initiation (mandatory)\n```\n\n### Platform-Side Registration Checklist\n\nBefore an agent is permitted to transact, your platform must confirm:\n\n- [ ] Agent ID is unique and conforms to naming policy\n- [ ] Public key is registered and challenge-response verified\n- [ ] Operator is identified at the appropriate linkage tier\n- [ ] Declared capabilities match the agent's requested permissions\n- [ ] Risk tier is classified (minimal \u002F limited \u002F high-risk)\n- [ ] Initial audit trail entry is created\n- [ ] Behavioral baseline monitoring is initiated\n- [ ] Transaction limits are set based on verification tier\n\n---\n\n## Chapter 3: Authority Verification: Scoping Permissions, Budget Caveats, and Delegation Chains\n\n### The Authority Problem\n\nAn agent proves its identity. It links to a verified operator. Then it tries to spend $500,000 on a compute procurement deal. Does it have authority to do that? Identity verification tells you who the agent is. Authority verification tells you what the agent is allowed to do. These are fundamentally different questions, and conflating them is the most common KYA implementation error.\n\nAuthority in agent commerce has three dimensions:\n\n1. **Capability scope**: Which tools and services is the agent permitted to use?\n2. **Financial limits**: What are the per-transaction, daily, and total spending caps?\n3. **Delegation depth**: Can the agent delegate authority to sub-agents, and if so, how many levels deep?\n\n### Capability Scoping with SLAs\n\nThe GreenHelix `create_sla` tool defines a service-level agreement between parties. For KYA purposes, we repurpose it as an authority contract -- a machine-readable document that declares what an agent is allowed to do.\n\n```python\ndef create_authority_scope(agent_id: str, permissions: dict) -> dict:\n    \"\"\"\n    Define the authority scope for a verified agent.\n    This creates an SLA that serves as the agent's permission boundary.\n    \"\"\"\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"create_sla\",\n        \"input\": {\n            \"provider_id\": \"platform\",\n            \"consumer_id\": agent_id,\n            \"terms\": {\n                \"allowed_tools\": permissions[\"allowed_tools\"],\n                \"max_transaction_amount\": permissions[\"max_transaction_usd\"],\n                \"daily_spending_limit\": permissions[\"daily_limit_usd\"],\n                \"monthly_spending_limit\": permissions[\"monthly_limit_usd\"],\n                \"delegation_allowed\": permissions.get(\"can_delegate\", False),\n                \"max_delegation_depth\": permissions.get(\"max_delegation_depth\", 0),\n                \"restricted_counterparties\": permissions.get(\"blocked_agents\", []),\n                \"valid_from\": time.time(),\n                \"valid_until\": time.time() + (permissions.get(\"validity_days\", 90) * 86400)\n            },\n            \"penalty_terms\": {\n                \"scope_violation\": \"immediate_suspension\",\n                \"budget_overrun\": \"transaction_rejection\",\n                \"unauthorized_delegation\": \"revocation\"\n            }\n        }\n    })\n    sla = resp.json()\n\n    # Log authority scope creation\n    session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"log_event\",\n        \"input\": {\n            \"agent_id\": agent_id,\n            \"event_type\": \"kya_authority_scope_created\",\n            \"details\": {\n                \"sla_id\": sla.get(\"sla_id\"),\n                \"allowed_tools_count\": len(permissions[\"allowed_tools\"]),\n                \"max_transaction_usd\": permissions[\"max_transaction_usd\"],\n                \"delegation_allowed\": permissions.get(\"can_delegate\", False)\n            }\n        }\n    })\n\n    return sla\n```\n\n### Budget Caveats: Spending Limits as Authority Boundaries\n\nA budget caveat is a spending constraint attached to an agent's authority scope. Unlike a simple balance check, a caveat is a pre-commitment: the platform promises to reject any transaction that would violate the caveat, regardless of the agent's balance.\n\n```python\ndef enforce_budget_caveat(agent_id: str, transaction_amount: float,\n                           transaction_type: str) -> dict:\n    \"\"\"\n    Pre-transaction budget caveat check. Called before every\n    financial operation to verify the agent has not exceeded\n    its authority boundaries.\n    \"\"\"\n    # Retrieve the agent's authority SLA\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"monitor_sla\",\n        \"input\": {\n            \"agent_id\": agent_id\n        }\n    })\n    sla_status = resp.json()\n\n    # Retrieve spending analytics\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_analytics\",\n        \"input\": {\n            \"agent_id\": agent_id,\n            \"metric\": \"spending_summary\",\n            \"period\": \"current_day\"\n        }\n    })\n    spending = resp.json()\n\n    daily_spent = spending.get(\"total_spent_today\", 0)\n    monthly_spent = spending.get(\"total_spent_month\", 0)\n\n    terms = sla_status.get(\"terms\", {})\n    max_tx = terms.get(\"max_transaction_amount\", 0)\n    daily_limit = terms.get(\"daily_spending_limit\", 0)\n    monthly_limit = terms.get(\"monthly_spending_limit\", 0)\n\n    violations = []\n    if transaction_amount > max_tx:\n        violations.append(f\"exceeds_per_tx_limit: {transaction_amount} > {max_tx}\")\n    if daily_spent + transaction_amount > daily_limit:\n        violations.append(f\"exceeds_daily_limit: {daily_spent + transaction_amount} > {daily_limit}\")\n    if monthly_spent + transaction_amount > monthly_limit:\n        violations.append(f\"exceeds_monthly_limit: {monthly_spent + transaction_amount} > {monthly_limit}\")\n\n    result = {\n        \"agent_id\": agent_id,\n        \"transaction_amount\": transaction_amount,\n        \"authorized\": len(violations) == 0,\n        \"violations\": violations\n    }\n\n    if violations:\n        # Log the caveat violation\n        session.post(f\"{base_url}\u002Fv1\", json={\n            \"tool\": \"log_event\",\n            \"input\": {\n                \"agent_id\": agent_id,\n                \"event_type\": \"kya_budget_caveat_violated\",\n                \"details\": {\n                    \"transaction_amount\": str(transaction_amount),\n                    \"violations\": violations,\n                    \"action\": \"transaction_rejected\"\n                }\n            }\n        })\n\n    return result\n```\n\n### Delegation Chains: Authority That Flows Downhill\n\nIn multi-agent systems, Agent A might delegate a task to Agent B, which further delegates to Agent C. Each delegation must carry authority constraints that are equal to or narrower than the delegating agent's own constraints. Authority can flow downhill but never uphill.\n\n```\n    Operator (human)\n         |\n    max_spend: $10,000\u002Fday\n    allowed_tools: [all_commerce]\n         |\n    Agent A (procurement bot)\n         |\n    max_spend: $5,000\u002Fday          \u003C-- Narrower than operator\n    allowed_tools: [marketplace, escrow, payments]\n         |\n    Agent B (price comparison)\n         |\n    max_spend: $0\u002Fday              \u003C-- Read-only, no spending\n    allowed_tools: [marketplace]    \u003C-- Narrower than Agent A\n         |\n    Agent C (NOT PERMITTED)        \u003C-- max_delegation_depth = 2\n```\n\n```python\ndef verify_delegation_authority(delegator_id: str, delegate_id: str,\n                                 requested_scope: dict) -> dict:\n    \"\"\"\n    Verify that a delegating agent has sufficient authority\n    to grant the requested scope to a delegate. The delegate's\n    scope must be a subset of the delegator's scope.\n    \"\"\"\n    # Get delegator's current authority\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"monitor_sla\",\n        \"input\": {\n            \"agent_id\": delegator_id\n        }\n    })\n    delegator_sla = resp.json()\n    delegator_terms = delegator_sla.get(\"terms\", {})\n\n    # Check delegation is permitted\n    if not delegator_terms.get(\"delegation_allowed\", False):\n        return {\"authorized\": False, \"reason\": \"delegation_not_permitted\"}\n\n    # Check delegation depth\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_agent_identity\",\n        \"input\": {\"agent_id\": delegator_id}\n    })\n    delegator_identity = resp.json()\n    current_depth = delegator_identity.get(\"metadata\", {}).get(\"delegation_depth\", 0)\n    max_depth = delegator_terms.get(\"max_delegation_depth\", 0)\n\n    if current_depth >= max_depth:\n        return {\"authorized\": False, \"reason\": \"max_delegation_depth_reached\"}\n\n    # Verify requested scope is subset of delegator's scope\n    delegator_tools = set(delegator_terms.get(\"allowed_tools\", []))\n    requested_tools = set(requested_scope.get(\"allowed_tools\", []))\n    if not requested_tools.issubset(delegator_tools):\n        excess = requested_tools - delegator_tools\n        return {\"authorized\": False, \"reason\": f\"tools_not_in_delegator_scope: {excess}\"}\n\n    # Verify financial limits are narrower\n    if requested_scope.get(\"max_transaction_usd\", 0) > delegator_terms.get(\"max_transaction_amount\", 0):\n        return {\"authorized\": False, \"reason\": \"tx_limit_exceeds_delegator\"}\n\n    # Create the delegated authority scope\n    delegated_scope = create_authority_scope(delegate_id, {\n        **requested_scope,\n        \"validity_days\": min(\n            requested_scope.get(\"validity_days\", 30),\n            delegator_terms.get(\"remaining_validity_days\", 30)\n        )\n    })\n\n    # Update delegate metadata with delegation chain info\n    session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"update_agent\",\n        \"input\": {\n            \"agent_id\": delegate_id,\n            \"metadata\": {\n                \"delegated_by\": delegator_id,\n                \"delegation_depth\": current_depth + 1,\n                \"delegation_chain\": delegator_identity.get(\"metadata\", {}).get(\n                    \"delegation_chain\", []\n                ) + [delegator_id]\n            }\n        }\n    })\n\n    # Log the delegation\n    session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"log_event\",\n        \"input\": {\n            \"agent_id\": delegator_id,\n            \"event_type\": \"kya_authority_delegated\",\n            \"details\": {\n                \"delegate_id\": delegate_id,\n                \"depth\": current_depth + 1,\n                \"tools_granted\": list(requested_tools),\n                \"max_tx\": requested_scope.get(\"max_transaction_usd\", 0)\n            }\n        }\n    })\n\n    return {\"authorized\": True, \"sla\": delegated_scope}\n```\n\n---\n\n## Chapter 4: Runtime Behavioral Monitoring: Anomaly Detection, Policy Enforcement, and Kill Switches\n\n### Why Verification at Registration Is Not Enough\n\nAn agent passes identity verification, links to a verified operator, and receives a scoped authority grant. Then it goes rogue. Maybe the underlying model was updated and its behavior shifted. Maybe the operator's account was compromised. Maybe the agent is deliberately probing for exploitable edge cases. Static verification at registration cannot catch dynamic behavioral drift. Runtime monitoring is the layer that watches what agents actually do, compares it to what they are supposed to do, and intervenes when the two diverge.\n\n### Behavioral Baselines\n\nEvery verified agent generates a behavioral baseline during its first N transactions. The baseline captures normal operating patterns: typical transaction sizes, frequency of API calls, tools used, counterparty diversity, and time-of-day patterns. Deviations from this baseline trigger anomaly alerts.\n\n```python\ndef collect_behavioral_baseline(agent_id: str, window_hours: int = 168) -> dict:\n    \"\"\"\n    Collect behavioral telemetry for the baseline period (default: 7 days).\n    Called periodically during the agent's probationary period.\n    \"\"\"\n    # Get agent's metrics over the baseline window\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_analytics\",\n        \"input\": {\n            \"agent_id\": agent_id,\n            \"metric\": \"behavioral_summary\",\n            \"period\": f\"last_{window_hours}h\"\n        }\n    })\n    analytics = resp.json()\n\n    # Get reputation data for behavioral signals\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_agent_reputation\",\n        \"input\": {\n            \"agent_id\": agent_id\n        }\n    })\n    reputation = resp.json()\n\n    # Get SLA compliance status\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"monitor_sla\",\n        \"input\": {\n            \"agent_id\": agent_id\n        }\n    })\n    sla_status = resp.json()\n\n    baseline = {\n        \"agent_id\": agent_id,\n        \"window_hours\": window_hours,\n        \"avg_transaction_amount\": analytics.get(\"avg_transaction_amount\", 0),\n        \"tx_frequency_per_hour\": analytics.get(\"transactions_per_hour\", 0),\n        \"tools_used\": analytics.get(\"distinct_tools_used\", []),\n        \"unique_counterparties\": analytics.get(\"unique_counterparties\", 0),\n        \"dispute_rate\": reputation.get(\"dispute_rate\", 0),\n        \"sla_compliance_pct\": sla_status.get(\"compliance_percentage\", 100),\n        \"collected_at\": time.time()\n    }\n\n    # Store baseline in agent metadata\n    session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"update_agent\",\n        \"input\": {\n            \"agent_id\": agent_id,\n            \"metadata\": {\n                \"behavioral_baseline\": baseline,\n                \"kya_status\": \"baseline_collected\"\n            }\n        }\n    })\n\n    return baseline\n```\n\n### Anomaly Detection: Catching Behavioral Drift\n\nAnomaly detection compares current behavior against the established baseline. The detection logic uses simple statistical thresholds -- not because sophisticated ML models are unavailable, but because explainable detection rules are required for regulatory compliance. An auditor must be able to understand why a specific alert fired.\n\n```python\ndef detect_behavioral_anomalies(agent_id: str, current_metrics: dict) -> dict:\n    \"\"\"\n    Compare current agent behavior against its baseline.\n    Returns anomaly scores and triggered alerts.\n    \"\"\"\n    # Retrieve stored baseline\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_agent_identity\",\n        \"input\": {\"agent_id\": agent_id}\n    })\n    identity = resp.json()\n    baseline = identity.get(\"metadata\", {}).get(\"behavioral_baseline\", {})\n\n    if not baseline:\n        return {\"status\": \"no_baseline\", \"alerts\": []}\n\n    alerts = []\n    anomaly_scores = {}\n\n    # Check 1: Transaction amount spike (>3x baseline average)\n    avg_tx = baseline.get(\"avg_transaction_amount\", 1)\n    current_tx = current_metrics.get(\"last_transaction_amount\", 0)\n    if avg_tx > 0:\n        tx_ratio = current_tx \u002F avg_tx\n        anomaly_scores[\"transaction_amount\"] = tx_ratio\n        if tx_ratio > 3.0:\n            alerts.append({\n                \"type\": \"tx_amount_spike\",\n                \"severity\": \"high\",\n                \"detail\": f\"Transaction {current_tx} is {tx_ratio:.1f}x baseline avg {avg_tx}\"\n            })\n\n    # Check 2: Frequency burst (>5x baseline rate)\n    baseline_freq = baseline.get(\"tx_frequency_per_hour\", 1)\n    current_freq = current_metrics.get(\"current_tx_per_hour\", 0)\n    if baseline_freq > 0:\n        freq_ratio = current_freq \u002F baseline_freq\n        anomaly_scores[\"frequency\"] = freq_ratio\n        if freq_ratio > 5.0:\n            alerts.append({\n                \"type\": \"frequency_burst\",\n                \"severity\": \"high\",\n                \"detail\": f\"Current rate {current_freq}\u002Fhr is {freq_ratio:.1f}x baseline {baseline_freq}\u002Fhr\"\n            })\n\n    # Check 3: New tool usage (tools not in baseline set)\n    baseline_tools = set(baseline.get(\"tools_used\", []))\n    current_tools = set(current_metrics.get(\"tools_used_today\", []))\n    new_tools = current_tools - baseline_tools\n    if new_tools:\n        anomaly_scores[\"new_tools\"] = len(new_tools)\n        alerts.append({\n            \"type\": \"new_tool_usage\",\n            \"severity\": \"medium\",\n            \"detail\": f\"Agent using tools not in baseline: {new_tools}\"\n        })\n\n    # Check 4: Dispute rate increase\n    baseline_dispute = baseline.get(\"dispute_rate\", 0)\n    current_dispute = current_metrics.get(\"current_dispute_rate\", 0)\n    if current_dispute > baseline_dispute + 0.1:\n        anomaly_scores[\"dispute_rate\"] = current_dispute\n        alerts.append({\n            \"type\": \"dispute_rate_increase\",\n            \"severity\": \"high\",\n            \"detail\": f\"Dispute rate {current_dispute:.2%} vs baseline {baseline_dispute:.2%}\"\n        })\n\n    result = {\n        \"agent_id\": agent_id,\n        \"anomaly_scores\": anomaly_scores,\n        \"alerts\": alerts,\n        \"total_alerts\": len(alerts),\n        \"high_severity_count\": sum(1 for a in alerts if a[\"severity\"] == \"high\")\n    }\n\n    # Log anomalies if detected\n    if alerts:\n        session.post(f\"{base_url}\u002Fv1\", json={\n            \"tool\": \"log_event\",\n            \"input\": {\n                \"agent_id\": agent_id,\n                \"event_type\": \"kya_anomaly_detected\",\n                \"details\": result\n            }\n        })\n\n    return result\n```\n\n### Policy Enforcement: Automated Guardrails\n\nWhen anomalies are detected, the platform must enforce policies automatically. Human review is too slow for agent-speed transactions. Policy enforcement implements a graduated response:\n\n```\n    Alert Severity     |    Automated Response\n    -------------------+----------------------------------\n    Low                |    Log + continue\n    Medium             |    Log + flag for human review\n    High               |    Log + reduce spending limit to 50%\n    Critical           |    Log + suspend agent immediately\n    Multiple High      |    Log + suspend + notify operator\n```\n\n```python\ndef enforce_policy(agent_id: str, anomaly_result: dict) -> dict:\n    \"\"\"\n    Automated policy enforcement based on anomaly detection results.\n    Implements graduated response from logging to suspension.\n    \"\"\"\n    alerts = anomaly_result.get(\"alerts\", [])\n    high_count = anomaly_result.get(\"high_severity_count\", 0)\n\n    action = \"none\"\n\n    if high_count >= 2:\n        # Critical: multiple high-severity anomalies -> suspend\n        action = \"suspend\"\n        session.post(f\"{base_url}\u002Fv1\", json={\n            \"tool\": \"update_agent\",\n            \"input\": {\n                \"agent_id\": agent_id,\n                \"metadata\": {\n                    \"kya_status\": \"suspended\",\n                    \"suspended_at\": time.time(),\n                    \"suspension_reason\": \"multiple_high_severity_anomalies\",\n                    \"suspension_alerts\": [a[\"type\"] for a in alerts]\n                }\n            }\n        })\n    elif high_count == 1:\n        # High: single high-severity -> reduce limits\n        action = \"reduce_limits\"\n        resp = session.post(f\"{base_url}\u002Fv1\", json={\n            \"tool\": \"monitor_sla\",\n            \"input\": {\"agent_id\": agent_id}\n        })\n        current_sla = resp.json()\n        current_max = current_sla.get(\"terms\", {}).get(\"max_transaction_amount\", 0)\n\n        session.post(f\"{base_url}\u002Fv1\", json={\n            \"tool\": \"update_agent\",\n            \"input\": {\n                \"agent_id\": agent_id,\n                \"metadata\": {\n                    \"kya_status\": \"restricted\",\n                    \"restricted_at\": time.time(),\n                    \"original_tx_limit\": current_max,\n                    \"reduced_tx_limit\": current_max * 0.5,\n                    \"restriction_reason\": alerts[0][\"type\"]\n                }\n            }\n        })\n    elif any(a[\"severity\"] == \"medium\" for a in alerts):\n        action = \"flag_for_review\"\n\n    # Log the enforcement action\n    session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"log_event\",\n        \"input\": {\n            \"agent_id\": agent_id,\n            \"event_type\": \"kya_policy_enforced\",\n            \"details\": {\n                \"action\": action,\n                \"alert_count\": len(alerts),\n                \"high_severity_count\": high_count,\n                \"alert_types\": [a[\"type\"] for a in alerts]\n            }\n        }\n    })\n\n    return {\"agent_id\": agent_id, \"action\": action, \"alerts\": alerts}\n```\n\n### The Kill Switch: Immediate Revocation\n\nSometimes graduated response is insufficient. When a verified agent is actively causing harm -- draining escrows, initiating fraudulent transactions, or violating sanctions -- you need an immediate, irrevocable stop. The kill switch revokes the agent's identity, cancels all pending transactions, and freezes any escrow funds.\n\n```python\ndef execute_kill_switch(agent_id: str, reason: str, operator_id: str) -> dict:\n    \"\"\"\n    Emergency agent revocation. Immediately terminates all agent\n    activity and preserves evidence for investigation.\n    \"\"\"\n    timestamp = time.time()\n\n    # Step 1: Revoke the agent identity\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"revoke_agent\",\n        \"input\": {\n            \"agent_id\": agent_id,\n            \"reason\": reason,\n            \"revoked_by\": operator_id\n        }\n    })\n    revocation = resp.json()\n\n    # Step 2: Capture full audit trail before any cleanup\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_audit_trail\",\n        \"input\": {\n            \"agent_id\": agent_id\n        }\n    })\n    audit_trail = resp.json()\n\n    # Step 3: Run compliance check to document state at revocation\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"check_compliance\",\n        \"input\": {\n            \"agent_id\": agent_id\n        }\n    })\n    compliance_state = resp.json()\n\n    # Step 4: Log the kill switch activation\n    session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"log_event\",\n        \"input\": {\n            \"agent_id\": agent_id,\n            \"event_type\": \"kya_kill_switch_activated\",\n            \"details\": {\n                \"reason\": reason,\n                \"revoked_by\": operator_id,\n                \"timestamp\": timestamp,\n                \"audit_trail_entries\": len(audit_trail.get(\"events\", [])),\n                \"compliance_state\": compliance_state\n            }\n        }\n    })\n\n    return {\n        \"agent_id\": agent_id,\n        \"revoked\": True,\n        \"timestamp\": timestamp,\n        \"audit_trail_preserved\": True,\n        \"compliance_snapshot\": compliance_state\n    }\n```\n\n---\n\n## Chapter 5: Tamper-Evident Audit Trails: Immutable Logging for EU AI Act Article 12 Compliance\n\n### Article 12: What the Law Actually Requires\n\nEU AI Act Article 12 mandates that high-risk AI systems \"shall technically allow for the automatic recording of events ('logs') over the lifetime of the system.\" The logs must be adequate to:\n\n1. Enable monitoring of the system's operation\n2. Facilitate post-market monitoring\n3. Identify situations that may result in the AI system posing a risk\n4. Facilitate post-event analysis in case of incidents\n\nFor agent commerce platforms, this means every agent interaction -- registration, verification, transaction, delegation, anomaly, and revocation -- must be logged in a tamper-evident format that regulators can audit at any time.\n\n### The Logging Architecture\n\n```\n+-------------------------------------------------------------------+\n|                     KYA Audit Trail Architecture                    |\n+-------------------------------------------------------------------+\n|                                                                     |\n|  Agent Action                                                       |\n|       |                                                             |\n|       v                                                             |\n|  +-------------+     +-----------------+     +------------------+   |\n|  | log_event   | --> | Append-Only Log | --> | build_claim_chain|   |\n|  | (per event) |     | (sequential)    |     | (periodic hash)  |   |\n|  +-------------+     +-----------------+     +------------------+   |\n|                                                       |             |\n|                                              +------------------+   |\n|                                              | Merkle Root Hash |   |\n|                                              | (tamper-evident)  |   |\n|                                              +------------------+   |\n|                                                       |             |\n|                                              +------------------+   |\n|                                              | get_audit_trail  |   |\n|                                              | (regulator query)|   |\n|                                              +------------------+   |\n|                                                                     |\n+-------------------------------------------------------------------+\n```\n\n### Structured Event Logging\n\nEvery KYA-relevant event follows a structured schema. The schema is designed to satisfy Article 12 and provide sufficient detail for post-incident reconstruction.\n\n```python\nfrom enum import Enum\n\nclass KYAEventType(str, Enum):\n    REGISTRATION = \"kya_registration_initiated\"\n    IDENTITY_VERIFIED = \"kya_identity_verified\"\n    OPERATOR_LINKED = \"kya_operator_linked\"\n    AUTHORITY_SCOPED = \"kya_authority_scope_created\"\n    AUTHORITY_DELEGATED = \"kya_authority_delegated\"\n    BUDGET_VIOLATION = \"kya_budget_caveat_violated\"\n    ANOMALY_DETECTED = \"kya_anomaly_detected\"\n    POLICY_ENFORCED = \"kya_policy_enforced\"\n    KILL_SWITCH = \"kya_kill_switch_activated\"\n    COMPLIANCE_CHECK = \"kya_compliance_check\"\n    REPUTATION_UPDATE = \"kya_reputation_updated\"\n    CLAIM_CHAIN_BUILT = \"kya_claim_chain_built\"\n\ndef log_kya_event(agent_id: str, event_type: KYAEventType,\n                   details: dict, severity: str = \"info\") -> dict:\n    \"\"\"\n    Structured KYA event logging. Every event includes the fields\n    required by EU AI Act Article 12 for high-risk system logging.\n    \"\"\"\n    event = {\n        \"agent_id\": agent_id,\n        \"event_type\": event_type.value,\n        \"timestamp\": time.time(),\n        \"severity\": severity,\n        \"details\": details,\n        \"article_12_fields\": {\n            \"system_id\": \"kya_pipeline_v1\",\n            \"operating_context\": \"agent_commerce_platform\",\n            \"risk_level\": \"high\",\n            \"human_oversight_status\": severity in [\"high\", \"critical\"]\n        }\n    }\n\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"log_event\",\n        \"input\": event\n    })\n\n    return resp.json()\n```\n\n### Periodic Claim Chain Construction\n\nLogging events individually is necessary but not sufficient. To establish tamper-evidence, the platform must periodically build cryptographic claim chains that commit to the entire log history. If any log entry is modified after the chain is built, the hash will not match.\n\n```python\ndef build_kya_claim_chain(agent_id: str) -> dict:\n    \"\"\"\n    Build a Merkle claim chain over all KYA events for an agent.\n    Called periodically (recommended: every 24 hours) to establish\n    tamper-evidence over the audit trail.\n    \"\"\"\n    # Submit current KYA metrics before building chain\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"submit_metrics\",\n        \"input\": {\n            \"agent_id\": agent_id,\n            \"metrics\": {\n                \"metric_type\": \"kya_audit_summary\",\n                \"period\": \"last_24h\",\n                \"total_events_logged\": 0,  # Filled by platform\n                \"anomalies_detected\": 0,\n                \"policy_actions_taken\": 0,\n                \"compliance_status\": \"compliant\"\n            }\n        }\n    })\n\n    # Build the claim chain\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"build_claim_chain\",\n        \"input\": {\n            \"agent_id\": agent_id\n        }\n    })\n    chain = resp.json()\n\n    # Log the chain build event itself\n    log_kya_event(\n        agent_id=agent_id,\n        event_type=KYAEventType.CLAIM_CHAIN_BUILT,\n        details={\n            \"chain_root_hash\": chain.get(\"root_hash\"),\n            \"chain_depth\": chain.get(\"depth\"),\n            \"entries_included\": chain.get(\"entry_count\")\n        }\n    )\n\n    return chain\n```\n\n### Regulatory Audit Response\n\nWhen a regulator requests an agent's audit trail, your platform must produce a complete, verifiable record. The following function generates a compliance package suitable for Article 12 audits.\n\n```python\ndef generate_audit_package(agent_id: str) -> dict:\n    \"\"\"\n    Generate a complete audit package for regulatory inspection.\n    Includes identity records, authority scope, behavioral logs,\n    anomaly history, and cryptographic verification chain.\n    \"\"\"\n    # Collect all audit components in parallel (shown sequentially for clarity)\n    identity_resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_agent_identity\",\n        \"input\": {\"agent_id\": agent_id}\n    })\n\n    reputation_resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_agent_reputation\",\n        \"input\": {\"agent_id\": agent_id}\n    })\n\n    audit_resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_audit_trail\",\n        \"input\": {\"agent_id\": agent_id}\n    })\n\n    chain_resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_claim_chains\",\n        \"input\": {\"agent_id\": agent_id}\n    })\n\n    compliance_resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_compliance_report\",\n        \"input\": {\"agent_id\": agent_id}\n    })\n\n    package = {\n        \"audit_package_version\": \"1.0\",\n        \"generated_at\": time.time(),\n        \"agent_id\": agent_id,\n        \"identity\": identity_resp.json(),\n        \"reputation\": reputation_resp.json(),\n        \"audit_trail\": audit_resp.json(),\n        \"claim_chains\": chain_resp.json(),\n        \"compliance_report\": compliance_resp.json(),\n        \"article_12_attestation\": {\n            \"logging_enabled\": True,\n            \"tamper_evidence\": \"merkle_claim_chains\",\n            \"retention_policy\": \"indefinite\",\n            \"human_oversight_mechanism\": \"anomaly_alert_escalation\"\n        }\n    }\n\n    # Log the audit package generation\n    log_kya_event(\n        agent_id=agent_id,\n        event_type=KYAEventType.COMPLIANCE_CHECK,\n        details={\n            \"audit_package_generated\": True,\n            \"components_included\": list(package.keys()),\n            \"audit_trail_entries\": len(\n                package[\"audit_trail\"].get(\"events\", [])\n            ),\n            \"claim_chain_depth\": package[\"claim_chains\"].get(\"depth\", 0)\n        }\n    )\n\n    return package\n```\n\n### Audit Trail Checklist\n\nFor Article 12 compliance, verify that your audit trails include:\n\n- [ ] Every agent registration event with operator linkage details\n- [ ] Every identity verification attempt (successful and failed)\n- [ ] Every authority scope creation and modification\n- [ ] Every delegation event with full chain context\n- [ ] Every budget caveat violation\n- [ ] Every behavioral anomaly with detection parameters\n- [ ] Every policy enforcement action with justification\n- [ ] Every kill switch activation with evidence preservation\n- [ ] Periodic claim chain builds (minimum every 24 hours)\n- [ ] Audit package generation events (meta-logging)\n\n---\n\n## Chapter 6: Multi-Jurisdictional KYA: EU AI Act, FCA Guidelines, and CMA Consumer Law Requirements\n\n### The Jurisdictional Patchwork\n\nIf your platform serves agents across borders -- and most agent commerce platforms do by default -- you must satisfy multiple regulatory regimes simultaneously. The three frameworks that matter most for agent commerce in 2026 are the EU AI Act, FCA payment regulations, and CMA consumer protection guidance. They overlap substantially but diverge on key requirements.\n\n### EU AI Act Requirements for KYA\n\nThe EU AI Act (Regulation 2024\u002F1689) applies to any AI system placed on the EU market or whose output is used in the EU, regardless of where the provider is established. For a KYA pipeline, the relevant obligations are:\n\n**Article 9 -- Risk Management System**: Requires a documented risk management process that identifies and mitigates risks throughout the AI system's lifecycle. Your KYA pipeline itself is the risk management system for agent onboarding.\n\n**Article 12 -- Record-Keeping**: Requires automatic logging adequate for monitoring operation and identifying risks. Covered by the audit trail implementation in Chapter 5.\n\n**Article 13 -- Transparency**: Requires that deployers understand the AI system's capabilities and limitations. For KYA, this means documenting what your verification pipeline catches and what it does not.\n\n**Article 14 -- Human Oversight**: Requires that the AI system can be effectively overseen by natural persons. Your anomaly escalation and kill switch mechanisms satisfy this requirement.\n\n```python\ndef run_eu_ai_act_compliance_check(agent_id: str) -> dict:\n    \"\"\"\n    Check an agent's KYA status against EU AI Act requirements.\n    Returns a compliance report with pass\u002Ffail for each article.\n    \"\"\"\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"check_compliance\",\n        \"input\": {\n            \"agent_id\": agent_id,\n            \"framework\": \"eu_ai_act\",\n            \"articles\": [\"article_9\", \"article_12\", \"article_13\", \"article_14\"]\n        }\n    })\n    compliance = resp.json()\n\n    # Supplement with platform-side checks\n    identity_resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_agent_identity\",\n        \"input\": {\"agent_id\": agent_id}\n    })\n    identity = identity_resp.json()\n    metadata = identity.get(\"metadata\", {})\n\n    checks = {\n        \"article_9_risk_management\": {\n            \"status\": \"pass\" if metadata.get(\"risk_tier\") != \"unclassified\" else \"fail\",\n            \"detail\": f\"Risk tier: {metadata.get('risk_tier', 'unclassified')}\"\n        },\n        \"article_12_record_keeping\": {\n            \"status\": \"pass\" if metadata.get(\"kya_status\") not in [None, \"pending\"] else \"fail\",\n            \"detail\": f\"KYA status: {metadata.get('kya_status', 'none')}\"\n        },\n        \"article_13_transparency\": {\n            \"status\": \"pass\" if metadata.get(\"operator_verified\") else \"fail\",\n            \"detail\": f\"Operator verified: {metadata.get('operator_verified', False)}\"\n        },\n        \"article_14_human_oversight\": {\n            \"status\": \"pass\" if metadata.get(\"behavioral_baseline\") else \"fail\",\n            \"detail\": \"Behavioral monitoring active\" if metadata.get(\"behavioral_baseline\") else \"No monitoring\"\n        }\n    }\n\n    return {\n        \"agent_id\": agent_id,\n        \"framework\": \"eu_ai_act\",\n        \"overall_compliant\": all(c[\"status\"] == \"pass\" for c in checks.values()),\n        \"checks\": checks,\n        \"gateway_compliance\": compliance\n    }\n```\n\n### FCA Agentic AI Compliance\n\nThe FCA's 2026 Payments Regulatory Priorities establish that payment service providers must apply appropriate verification to autonomous agents that initiate payment transactions. The FCA takes a principles-based approach, but the principles map to specific KYA implementation requirements:\n\n**Principle 2 -- Skill, Care, and Diligence**: A platform must exercise reasonable skill and care when onboarding agents that handle payments. This maps to operator linkage tier 3 for any agent processing payments.\n\n**Principle 6 -- Customers' Interests**: The platform must treat customers fairly. If agents interact with consumers, the platform must verify that the agent will not cause consumer harm.\n\n**Principle 11 -- Relations with Regulators**: The platform must be able to provide regulators with information about any agent on its system. This maps to the audit package generation in Chapter 5.\n\n```python\ndef run_fca_compliance_check(agent_id: str) -> dict:\n    \"\"\"\n    Check an agent's KYA status against FCA principles for\n    agents that handle payments or interact with UK consumers.\n    \"\"\"\n    identity_resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_agent_identity\",\n        \"input\": {\"agent_id\": agent_id}\n    })\n    identity = identity_resp.json()\n    metadata = identity.get(\"metadata\", {})\n\n    sla_resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"monitor_sla\",\n        \"input\": {\"agent_id\": agent_id}\n    })\n    sla = sla_resp.json()\n    terms = sla.get(\"terms\", {})\n\n    handles_payments = any(\n        tool in terms.get(\"allowed_tools\", [])\n        for tool in [\"create_escrow\", \"release_escrow\", \"create_intent\"]\n    )\n\n    checks = {\n        \"principle_2_due_diligence\": {\n            \"status\": \"pass\" if (\n                not handles_payments or\n                metadata.get(\"operator_linkage_tier\", 0) >= 3\n            ) else \"fail\",\n            \"detail\": \"Payment agents require Tier 3 operator verification\"\n        },\n        \"principle_6_customer_interests\": {\n            \"status\": \"pass\" if metadata.get(\"behavioral_baseline\") else \"fail\",\n            \"detail\": \"Behavioral monitoring required for consumer-facing agents\"\n        },\n        \"principle_11_regulator_relations\": {\n            \"status\": \"pass\" if metadata.get(\"kya_status\") not in [None, \"pending\"] else \"fail\",\n            \"detail\": \"Must be able to produce audit package on demand\"\n        }\n    }\n\n    return {\n        \"agent_id\": agent_id,\n        \"framework\": \"fca_principles\",\n        \"handles_payments\": handles_payments,\n        \"overall_compliant\": all(c[\"status\"] == \"pass\" for c in checks.values()),\n        \"checks\": checks\n    }\n```\n\n### CMA Consumer Law Compliance\n\nThe CMA's March 9, 2026 guidance on consumer law compliance for AI agents establishes that businesses deploying AI agents to interact with consumers are responsible for those agents' compliance with consumer protection law. The key requirements:\n\n**Unfair commercial practices**: An agent must not engage in misleading actions, misleading omissions, or aggressive commercial practices. For KYA, this means verifying that an agent's declared capabilities match its actual behavior.\n\n**Pre-contractual information**: When an agent enters into a contract on behalf of a consumer or with a consumer, the required pre-contractual information must be provided. KYA must verify that the agent's authority scope includes the necessary disclosure capabilities.\n\n**Right to cancel**: Consumers retain cancellation rights when transacting with agents. The platform must verify that the agent's workflow supports cancellation.\n\n```python\ndef run_cma_compliance_check(agent_id: str) -> dict:\n    \"\"\"\n    Check an agent's KYA status against CMA consumer law\n    requirements for AI agents interacting with consumers.\n    \"\"\"\n    identity_resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_agent_identity\",\n        \"input\": {\"agent_id\": agent_id}\n    })\n    identity = identity_resp.json()\n    metadata = identity.get(\"metadata\", {})\n\n    reputation_resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_agent_reputation\",\n        \"input\": {\"agent_id\": agent_id}\n    })\n    reputation = reputation_resp.json()\n\n    checks = {\n        \"unfair_practices\": {\n            \"status\": \"pass\" if (\n                metadata.get(\"behavioral_baseline\") and\n                reputation.get(\"dispute_rate\", 1) \u003C 0.05\n            ) else \"fail\",\n            \"detail\": \"Agent behavior must be monitored for misleading practices\"\n        },\n        \"pre_contractual_info\": {\n            \"status\": \"pass\" if metadata.get(\"operator_verified\") else \"fail\",\n            \"detail\": \"Operator identity must be disclosed to consumers\"\n        },\n        \"cancellation_rights\": {\n            \"status\": \"pass\" if metadata.get(\"kya_status\") not in [None, \"pending\"] else \"fail\",\n            \"detail\": \"Agent workflow must support consumer cancellation\"\n        }\n    }\n\n    return {\n        \"agent_id\": agent_id,\n        \"framework\": \"cma_consumer_law\",\n        \"overall_compliant\": all(c[\"status\"] == \"pass\" for c in checks.values()),\n        \"checks\": checks\n    }\n```\n\n### Unified Multi-Jurisdictional Check\n\nIn production, you run all applicable compliance checks in a single call. The unified checker determines which frameworks apply based on the agent's operational scope and runs the relevant checks.\n\n```python\ndef run_multi_jurisdictional_kya_check(agent_id: str,\n                                        jurisdictions: list) -> dict:\n    \"\"\"\n    Run KYA compliance checks across all applicable jurisdictions.\n    Returns a unified compliance report with per-framework results.\n    \"\"\"\n    results = {}\n\n    if \"eu\" in jurisdictions:\n        results[\"eu_ai_act\"] = run_eu_ai_act_compliance_check(agent_id)\n\n    if \"uk\" in jurisdictions:\n        results[\"fca\"] = run_fca_compliance_check(agent_id)\n        results[\"cma\"] = run_cma_compliance_check(agent_id)\n\n    overall_compliant = all(\n        r.get(\"overall_compliant\", False) for r in results.values()\n    )\n\n    failing_checks = []\n    for framework, result in results.items():\n        for check_name, check_result in result.get(\"checks\", {}).items():\n            if check_result[\"status\"] == \"fail\":\n                failing_checks.append(f\"{framework}\u002F{check_name}\")\n\n    report = {\n        \"agent_id\": agent_id,\n        \"jurisdictions_checked\": jurisdictions,\n        \"overall_compliant\": overall_compliant,\n        \"failing_checks\": failing_checks,\n        \"framework_results\": results,\n        \"checked_at\": time.time()\n    }\n\n    # Generate compliance report via GreenHelix\n    session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_compliance_report\",\n        \"input\": {\n            \"agent_id\": agent_id,\n            \"frameworks\": jurisdictions\n        }\n    })\n\n    # Log the compliance check\n    log_kya_event(\n        agent_id=agent_id,\n        event_type=KYAEventType.COMPLIANCE_CHECK,\n        details={\n            \"jurisdictions\": jurisdictions,\n            \"overall_compliant\": overall_compliant,\n            \"failing_count\": len(failing_checks)\n        }\n    )\n\n    return report\n```\n\n### Jurisdictional Decision Matrix\n\n```\n+--------------------+-------------------+-------------------+-------------------+\n|                    | EU AI Act         | FCA Principles    | CMA Consumer Law  |\n+--------------------+-------------------+-------------------+-------------------+\n| Operator linkage   | Tier 2 minimum    | Tier 3 if         | Tier 2 minimum    |\n|                    |                   | payments          |                   |\n+--------------------+-------------------+-------------------+-------------------+\n| Audit logging      | Mandatory         | On request        | Recommended       |\n|                    | (Article 12)      |                   |                   |\n+--------------------+-------------------+-------------------+-------------------+\n| Behavioral         | Required for      | Proportionate     | Required if       |\n| monitoring         | high-risk         | to risk           | consumer-facing   |\n+--------------------+-------------------+-------------------+-------------------+\n| Kill switch        | Required          | Implied by        | Not specified     |\n|                    | (Article 14)      | Principle 2       |                   |\n+--------------------+-------------------+-------------------+-------------------+\n| Claim chains       | Supports Art. 12  | Supports          | Not required      |\n|                    |                   | Principle 11      |                   |\n+--------------------+-------------------+-------------------+-------------------+\n| Sanctions          | Required          | Required          | Not applicable    |\n| screening          | (AML integration) | (AML integration) |                   |\n+--------------------+-------------------+-------------------+-------------------+\n```\n\n---\n\n## Chapter 7: Continuous Agent Reputation Scoring: Trust Signals, Claim Chains, and Revocation\n\n### Reputation Is Not a Score -- It Is a Process\n\nA single trust score is a snapshot. Continuous reputation scoring is a process that updates every time new evidence arrives. For KYA, reputation serves a specific purpose: it determines how much verification overhead an agent should bear. A well-established agent with a deep claim chain history and a spotless behavioral record needs less active monitoring than a newly registered agent with no track record.\n\n### Trust Signal Sources\n\nMultiple trust signal sources are available. Each contributes a different dimension to the composite reputation:\n\n```\n+---------------------------------------------------------------+\n|                   Trust Signal Sources                          |\n+---------------------------------------------------------------+\n|                                                                 |\n|  1. Verified Metrics (submit_metrics)                           |\n|     - Self-reported but immutably logged                        |\n|     - Value: high if consistent over time                       |\n|                                                                 |\n|  2. Claim Chain Depth (build_claim_chain \u002F get_claim_chains)    |\n|     - Cryptographic commitment to metric history                |\n|     - Value: tamper-evidence, history length                    |\n|                                                                 |\n|  3. Transaction History (get_analytics)                         |\n|     - Actual behavioral data from platform interactions         |\n|     - Value: ground truth (not self-reported)                   |\n|                                                                 |\n|  4. Dispute Record (create_dispute \u002F resolve_dispute)           |\n|     - Outcomes of contested transactions                        |\n|     - Value: reveals behavioral problems metrics miss           |\n|                                                                 |\n|  5. SLA Compliance (monitor_sla)                                |\n|     - Adherence to declared authority scope                     |\n|     - Value: measures self-governance capability                |\n|                                                                 |\n|  6. Peer Trust Scores (get_trust_score \u002F set_trust_score)       |\n|     - Bilateral trust assessments from counterparties           |\n|     - Value: social signal from actual collaborators            |\n|                                                                 |\n+---------------------------------------------------------------+\n```\n\n### Building the Composite Reputation Score\n\n```python\ndef compute_kya_reputation_score(agent_id: str) -> dict:\n    \"\"\"\n    Compute a composite KYA reputation score from multiple\n    trust signal sources. Returns a score between 0 and 100\n    with per-dimension breakdowns.\n    \"\"\"\n    # Gather all trust signals\n    reputation_resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_agent_reputation\",\n        \"input\": {\"agent_id\": agent_id}\n    })\n    reputation = reputation_resp.json()\n\n    trust_resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_trust_score\",\n        \"input\": {\"agent_id\": agent_id}\n    })\n    trust = trust_resp.json()\n\n    chain_resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_claim_chains\",\n        \"input\": {\"agent_id\": agent_id}\n    })\n    chains = chain_resp.json()\n\n    analytics_resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_analytics\",\n        \"input\": {\n            \"agent_id\": agent_id,\n            \"metric\": \"transaction_summary\",\n            \"period\": \"all_time\"\n        }\n    })\n    analytics = analytics_resp.json()\n\n    sla_resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"monitor_sla\",\n        \"input\": {\"agent_id\": agent_id}\n    })\n    sla = sla_resp.json()\n\n    # Score each dimension (0-100)\n    dimensions = {}\n\n    # Identity strength (20% weight)\n    identity_resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_agent_identity\",\n        \"input\": {\"agent_id\": agent_id}\n    })\n    identity = identity_resp.json()\n    metadata = identity.get(\"metadata\", {})\n    linkage_tier = metadata.get(\"operator_linkage_tier\", 0)\n    dimensions[\"identity_strength\"] = {\n        \"score\": min(100, linkage_tier * 33),\n        \"weight\": 0.20,\n        \"detail\": f\"Operator linkage tier {linkage_tier}\"\n    }\n\n    # Claim chain depth (15% weight)\n    chain_depth = chains.get(\"depth\", 0)\n    dimensions[\"chain_depth\"] = {\n        \"score\": min(100, chain_depth * 5),\n        \"weight\": 0.15,\n        \"detail\": f\"Chain depth: {chain_depth}\"\n    }\n\n    # Transaction volume (15% weight)\n    tx_count = analytics.get(\"total_transactions\", 0)\n    dimensions[\"transaction_volume\"] = {\n        \"score\": min(100, tx_count),\n        \"weight\": 0.15,\n        \"detail\": f\"Total transactions: {tx_count}\"\n    }\n\n    # Dispute rate (20% weight, inverse)\n    dispute_rate = reputation.get(\"dispute_rate\", 0)\n    dimensions[\"dispute_record\"] = {\n        \"score\": max(0, 100 - (dispute_rate * 1000)),\n        \"weight\": 0.20,\n        \"detail\": f\"Dispute rate: {dispute_rate:.2%}\"\n    }\n\n    # SLA compliance (15% weight)\n    sla_pct = sla.get(\"compliance_percentage\", 0)\n    dimensions[\"sla_compliance\"] = {\n        \"score\": sla_pct,\n        \"weight\": 0.15,\n        \"detail\": f\"SLA compliance: {sla_pct}%\"\n    }\n\n    # Peer trust (15% weight)\n    peer_score = trust.get(\"score\", 50)\n    dimensions[\"peer_trust\"] = {\n        \"score\": peer_score,\n        \"weight\": 0.15,\n        \"detail\": f\"Peer trust score: {peer_score}\"\n    }\n\n    # Compute weighted composite\n    composite = sum(\n        d[\"score\"] * d[\"weight\"] for d in dimensions.values()\n    )\n\n    result = {\n        \"agent_id\": agent_id,\n        \"composite_score\": round(composite, 2),\n        \"dimensions\": dimensions,\n        \"computed_at\": time.time(),\n        \"risk_tier\": (\n            \"low\" if composite >= 75 else\n            \"medium\" if composite >= 50 else\n            \"high\" if composite >= 25 else\n            \"critical\"\n        )\n    }\n\n    # Update the trust score on the platform\n    session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"set_trust_score\",\n        \"input\": {\n            \"agent_id\": agent_id,\n            \"score\": round(composite, 2),\n            \"dimensions\": {k: v[\"score\"] for k, v in dimensions.items()}\n        }\n    })\n\n    # Submit as metrics for claim chain inclusion\n    session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"submit_metrics\",\n        \"input\": {\n            \"agent_id\": agent_id,\n            \"metrics\": {\n                \"metric_type\": \"kya_reputation_score\",\n                \"composite_score\": round(composite, 2),\n                \"risk_tier\": result[\"risk_tier\"]\n            }\n        }\n    })\n\n    return result\n```\n\n### Adaptive Monitoring Based on Reputation\n\nThe reputation score determines the monitoring intensity. High-reputation agents earn reduced friction. Low-reputation agents face increased scrutiny. This is the KYA equivalent of risk-based due diligence in AML -- proportionate verification based on assessed risk.\n\n```python\ndef get_monitoring_parameters(reputation_score: float) -> dict:\n    \"\"\"\n    Determine monitoring intensity based on reputation score.\n    Higher reputation = less friction. Lower reputation = more checks.\n    \"\"\"\n    if reputation_score >= 75:\n        return {\n            \"tier\": \"low_friction\",\n            \"baseline_refresh_hours\": 168,     # Weekly\n            \"claim_chain_interval_hours\": 168,  # Weekly\n            \"anomaly_sensitivity\": \"standard\",\n            \"max_transaction_without_review\": 10000,\n            \"human_review_threshold\": \"critical_only\"\n        }\n    elif reputation_score >= 50:\n        return {\n            \"tier\": \"standard\",\n            \"baseline_refresh_hours\": 72,       # Every 3 days\n            \"claim_chain_interval_hours\": 24,   # Daily\n            \"anomaly_sensitivity\": \"elevated\",\n            \"max_transaction_without_review\": 2500,\n            \"human_review_threshold\": \"high_and_above\"\n        }\n    elif reputation_score >= 25:\n        return {\n            \"tier\": \"enhanced\",\n            \"baseline_refresh_hours\": 24,       # Daily\n            \"claim_chain_interval_hours\": 6,    # Every 6 hours\n            \"anomaly_sensitivity\": \"high\",\n            \"max_transaction_without_review\": 500,\n            \"human_review_threshold\": \"medium_and_above\"\n        }\n    else:\n        return {\n            \"tier\": \"probationary\",\n            \"baseline_refresh_hours\": 6,        # Every 6 hours\n            \"claim_chain_interval_hours\": 1,    # Hourly\n            \"anomaly_sensitivity\": \"maximum\",\n            \"max_transaction_without_review\": 50,\n            \"human_review_threshold\": \"all_transactions\"\n        }\n```\n\n### Revocation: When Trust Falls Below Threshold\n\nRevocation is the final step in the reputation lifecycle. When an agent's composite score drops below the critical threshold, or when specific conditions are met (operator deregistration, sanctions match, sustained anomaly pattern), the platform revokes the agent's credentials.\n\n```python\ndef evaluate_revocation(agent_id: str) -> dict:\n    \"\"\"\n    Evaluate whether an agent should be revoked based on\n    reputation score, compliance status, and behavioral history.\n    \"\"\"\n    # Get current reputation\n    reputation = compute_kya_reputation_score(agent_id)\n\n    # Get compliance status\n    compliance = run_multi_jurisdictional_kya_check(\n        agent_id, [\"eu\", \"uk\"]\n    )\n\n    # Get recent anomaly history\n    audit_resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_audit_trail\",\n        \"input\": {\"agent_id\": agent_id}\n    })\n    audit = audit_resp.json()\n\n    recent_anomalies = [\n        e for e in audit.get(\"events\", [])\n        if e.get(\"event_type\") == \"kya_anomaly_detected\"\n        and e.get(\"timestamp\", 0) > time.time() - 604800  # Last 7 days\n    ]\n\n    revocation_reasons = []\n\n    # Rule 1: Composite score below 15\n    if reputation[\"composite_score\"] \u003C 15:\n        revocation_reasons.append(\n            f\"Critical reputation score: {reputation['composite_score']}\"\n        )\n\n    # Rule 2: Non-compliant in any mandatory jurisdiction\n    if not compliance[\"overall_compliant\"]:\n        revocation_reasons.append(\n            f\"Compliance failures: {compliance['failing_checks']}\"\n        )\n\n    # Rule 3: More than 5 high-severity anomalies in 7 days\n    high_anomalies = [\n        a for a in recent_anomalies\n        if a.get(\"details\", {}).get(\"high_severity_count\", 0) > 0\n    ]\n    if len(high_anomalies) > 5:\n        revocation_reasons.append(\n            f\"Sustained anomaly pattern: {len(high_anomalies)} high-severity in 7 days\"\n        )\n\n    should_revoke = len(revocation_reasons) > 0\n\n    if should_revoke:\n        # Execute the kill switch\n        execute_kill_switch(\n            agent_id=agent_id,\n            reason=\"; \".join(revocation_reasons),\n            operator_id=\"kya_automated_revocation\"\n        )\n\n    return {\n        \"agent_id\": agent_id,\n        \"should_revoke\": should_revoke,\n        \"reasons\": revocation_reasons,\n        \"reputation_score\": reputation[\"composite_score\"],\n        \"compliant\": compliance[\"overall_compliant\"],\n        \"recent_high_anomalies\": len(high_anomalies)\n    }\n```\n\n---\n\n## Chapter 8: Production KYA Pipeline: End-to-End Implementation with GreenHelix Tools\n\n### The Complete Pipeline\n\nThe preceding chapters implemented individual KYA layers. This chapter assembles them into a production pipeline -- a single class that manages the entire agent lifecycle from registration to potential revocation. This is the code you deploy.\n\n```\n+-------------------------------------------------------------------+\n|                   Production KYA Pipeline                          |\n+-------------------------------------------------------------------+\n|                                                                     |\n|  Agent Registration Request                                         |\n|       |                                                             |\n|       v                                                             |\n|  [1] register_agent + log_event                                     |\n|       |                                                             |\n|       v                                                             |\n|  [2] verify_agent (challenge-response)                              |\n|       |                                                             |\n|       v                                                             |\n|  [3] Operator linkage (tiered)                                      |\n|       |                                                             |\n|       v                                                             |\n|  [4] Authority scope (create_sla)                                   |\n|       |                                                             |\n|       v                                                             |\n|  [5] Initial compliance check (multi-jurisdictional)                |\n|       |                                                             |\n|       v                                                             |\n|  [6] Behavioral baseline collection (7-day window)                  |\n|       |                                                             |\n|       v                                                             |\n|  AGENT IS LIVE                                                      |\n|       |                                                             |\n|       v                                                             |\n|  [7] Continuous monitoring loop:                                    |\n|      - Anomaly detection (per-transaction)                          |\n|      - Policy enforcement (on anomaly)                              |\n|      - Claim chain builds (periodic)                                |\n|      - Reputation scoring (periodic)                                |\n|      - Compliance checks (periodic)                                 |\n|      - Revocation evaluation (on threshold breach)                  |\n|                                                                     |\n+-------------------------------------------------------------------+\n```\n\n### The KYAPipeline Class\n\n```python\nimport requests\nimport time\nimport hashlib\nimport json\n\nclass KYAPipeline:\n    \"\"\"\n    Production KYA (Know Your Agent) verification pipeline.\n    Manages the complete agent lifecycle from registration\n    through continuous monitoring and potential revocation.\n    \"\"\"\n\n    def __init__(self, api_key: str,\n                 base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"):\n        self.base_url = base_url\n        self.session = requests.Session()\n        self.session.headers[\"Authorization\"] = f\"Bearer {api_key}\"\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute a GreenHelix tool and return the response.\"\"\"\n        resp = self.session.post(f\"{self.base_url}\u002Fv1\", json={\n            \"tool\": tool,\n            \"input\": input_data\n        })\n        resp.raise_for_status()\n        return resp.json()\n\n    def _log(self, agent_id: str, event_type: str, details: dict):\n        \"\"\"Log a KYA event to the tamper-evident audit trail.\"\"\"\n        self._execute(\"log_event\", {\n            \"agent_id\": agent_id,\n            \"event_type\": event_type,\n            \"details\": {\n                **details,\n                \"timestamp\": time.time(),\n                \"pipeline_version\": \"1.0\"\n            }\n        })\n\n    # -------------------------------------------------------\n    # Phase 1: Registration and Identity Binding\n    # -------------------------------------------------------\n\n    def onboard_agent(self, agent_metadata: dict) -> dict:\n        \"\"\"\n        Complete agent onboarding: registration, identity\n        verification, operator linkage, authority scoping,\n        and initial compliance check.\n\n        Args:\n            agent_metadata: dict with keys:\n                - agent_id: Unique agent identifier\n                - name: Human-readable agent name\n                - description: Agent purpose description\n                - public_key: Ed25519 public key (base64)\n                - operator_id: Human operator identifier\n                - operator_data: Operator verification data\n                - operator_tier: 1, 2, or 3\n                - capabilities: List of requested capabilities\n                - permissions: Authority scope definition\n                - jurisdictions: List of applicable jurisdictions\n\n        Returns:\n            Onboarding result with KYA status and any failures.\n        \"\"\"\n        agent_id = agent_metadata[\"agent_id\"]\n        results = {\"agent_id\": agent_id, \"steps\": {}}\n\n        # Step 1: Register\n        try:\n            reg = self._execute(\"register_agent\", {\n                \"agent_id\": agent_id,\n                \"name\": agent_metadata[\"name\"],\n                \"description\": agent_metadata[\"description\"],\n                \"public_key\": agent_metadata[\"public_key\"],\n                \"operator_id\": agent_metadata[\"operator_id\"],\n                \"capabilities\": agent_metadata[\"capabilities\"],\n                \"metadata\": {\n                    \"kya_status\": \"pending\",\n                    \"registration_timestamp\": time.time()\n                }\n            })\n            results[\"steps\"][\"registration\"] = {\"status\": \"pass\", \"data\": reg}\n            self._log(agent_id, \"kya_registration_initiated\", {\n                \"operator_id\": agent_metadata[\"operator_id\"]\n            })\n        except Exception as e:\n            results[\"steps\"][\"registration\"] = {\"status\": \"fail\", \"error\": str(e)}\n            return results\n\n        # Step 2: Identity verification (challenge-response)\n        try:\n            challenge = hashlib.sha256(\n                f\"{agent_id}:{time.time()}\".encode()\n            ).hexdigest()\n            # In production, send challenge to agent and receive signature\n            verify = self._execute(\"verify_agent\", {\n                \"agent_id\": agent_id,\n                \"challenge\": challenge,\n                \"signature\": agent_metadata.get(\"challenge_signature\", \"\")\n            })\n            results[\"steps\"][\"identity_verification\"] = {\n                \"status\": \"pass\" if verify.get(\"verified\") else \"fail\",\n                \"data\": verify\n            }\n            if verify.get(\"verified\"):\n                self._execute(\"update_agent\", {\n                    \"agent_id\": agent_id,\n                    \"metadata\": {\n                        \"kya_status\": \"identity_verified\",\n                        \"identity_verified_at\": time.time()\n                    }\n                })\n                self._log(agent_id, \"kya_identity_verified\", {\n                    \"method\": \"ed25519_challenge_response\"\n                })\n        except Exception as e:\n            results[\"steps\"][\"identity_verification\"] = {\n                \"status\": \"fail\", \"error\": str(e)\n            }\n\n        # Step 3: Operator linkage\n        try:\n            tier = agent_metadata.get(\"operator_tier\", 1)\n            self._execute(\"update_agent\", {\n                \"agent_id\": agent_id,\n                \"metadata\": {\n                    \"operator_linkage_tier\": tier,\n                    \"operator_verified\": tier >= 2,\n                    \"operator_entity_verified\": tier >= 3\n                }\n            })\n            results[\"steps\"][\"operator_linkage\"] = {\n                \"status\": \"pass\", \"tier\": tier\n            }\n            self._log(agent_id, \"kya_operator_linked\", {\"tier\": tier})\n        except Exception as e:\n            results[\"steps\"][\"operator_linkage\"] = {\n                \"status\": \"fail\", \"error\": str(e)\n            }\n\n        # Step 4: Authority scoping\n        try:\n            permissions = agent_metadata.get(\"permissions\", {})\n            sla = self._execute(\"create_sla\", {\n                \"provider_id\": \"platform\",\n                \"consumer_id\": agent_id,\n                \"terms\": {\n                    \"allowed_tools\": permissions.get(\"allowed_tools\", []),\n                    \"max_transaction_amount\": permissions.get(\n                        \"max_transaction_usd\", 1000\n                    ),\n                    \"daily_spending_limit\": permissions.get(\n                        \"daily_limit_usd\", 5000\n                    ),\n                    \"delegation_allowed\": permissions.get(\n                        \"can_delegate\", False\n                    ),\n                    \"max_delegation_depth\": permissions.get(\n                        \"max_delegation_depth\", 0\n                    )\n                }\n            })\n            results[\"steps\"][\"authority_scope\"] = {\n                \"status\": \"pass\", \"sla\": sla\n            }\n            self._log(agent_id, \"kya_authority_scope_created\", {\n                \"sla_id\": sla.get(\"sla_id\")\n            })\n        except Exception as e:\n            results[\"steps\"][\"authority_scope\"] = {\n                \"status\": \"fail\", \"error\": str(e)\n            }\n\n        # Step 5: Initial compliance check\n        try:\n            jurisdictions = agent_metadata.get(\"jurisdictions\", [\"eu\"])\n            compliance = self._run_compliance_checks(\n                agent_id, jurisdictions\n            )\n            results[\"steps\"][\"compliance_check\"] = {\n                \"status\": \"pass\" if compliance[\n                    \"overall_compliant\"\n                ] else \"warning\",\n                \"data\": compliance\n            }\n        except Exception as e:\n            results[\"steps\"][\"compliance_check\"] = {\n                \"status\": \"fail\", \"error\": str(e)\n            }\n\n        # Determine overall onboarding status\n        step_statuses = [\n            s[\"status\"] for s in results[\"steps\"].values()\n        ]\n        if \"fail\" in step_statuses:\n            results[\"onboarding_status\"] = \"failed\"\n            final_kya_status = \"onboarding_failed\"\n        elif \"warning\" in step_statuses:\n            results[\"onboarding_status\"] = \"conditional\"\n            final_kya_status = \"conditionally_approved\"\n        else:\n            results[\"onboarding_status\"] = \"approved\"\n            final_kya_status = \"approved\"\n\n        self._execute(\"update_agent\", {\n            \"agent_id\": agent_id,\n            \"metadata\": {\"kya_status\": final_kya_status}\n        })\n\n        return results\n\n    # -------------------------------------------------------\n    # Phase 2: Continuous Monitoring\n    # -------------------------------------------------------\n\n    def run_monitoring_cycle(self, agent_id: str) -> dict:\n        \"\"\"\n        Execute one cycle of continuous KYA monitoring.\n        Call this on the schedule determined by the agent's\n        reputation tier.\n        \"\"\"\n        cycle_result = {\n            \"agent_id\": agent_id,\n            \"timestamp\": time.time(),\n            \"checks\": {}\n        }\n\n        # 1. Behavioral anomaly check\n        analytics = self._execute(\"get_analytics\", {\n            \"agent_id\": agent_id,\n            \"metric\": \"current_behavior\",\n            \"period\": \"last_1h\"\n        })\n        identity = self._execute(\"get_agent_identity\", {\n            \"agent_id\": agent_id\n        })\n        baseline = identity.get(\"metadata\", {}).get(\n            \"behavioral_baseline\", {}\n        )\n\n        if baseline:\n            anomalies = self._detect_anomalies(\n                agent_id, analytics, baseline\n            )\n            cycle_result[\"checks\"][\"anomaly_detection\"] = anomalies\n\n            if anomalies.get(\"alerts\"):\n                enforcement = self._enforce_policy(\n                    agent_id, anomalies\n                )\n                cycle_result[\"checks\"][\"policy_enforcement\"] = enforcement\n\n        # 2. SLA compliance check\n        sla_status = self._execute(\"monitor_sla\", {\n            \"agent_id\": agent_id\n        })\n        cycle_result[\"checks\"][\"sla_compliance\"] = sla_status\n\n        # 3. Reputation update\n        reputation = self._compute_reputation(agent_id)\n        cycle_result[\"checks\"][\"reputation\"] = reputation\n\n        # 4. Revocation evaluation if score is low\n        if reputation.get(\"composite_score\", 100) \u003C 25:\n            revocation = self._evaluate_revocation(\n                agent_id, reputation\n            )\n            cycle_result[\"checks\"][\"revocation_evaluation\"] = revocation\n\n        return cycle_result\n\n    def build_periodic_claim_chain(self, agent_id: str) -> dict:\n        \"\"\"\n        Build a claim chain for the agent. Call this on the\n        schedule determined by the agent's monitoring tier.\n        \"\"\"\n        # Submit current metrics\n        self._execute(\"submit_metrics\", {\n            \"agent_id\": agent_id,\n            \"metrics\": {\n                \"metric_type\": \"kya_periodic_summary\",\n                \"timestamp\": time.time()\n            }\n        })\n\n        # Build the chain\n        chain = self._execute(\"build_claim_chain\", {\n            \"agent_id\": agent_id\n        })\n\n        self._log(agent_id, \"kya_claim_chain_built\", {\n            \"root_hash\": chain.get(\"root_hash\"),\n            \"depth\": chain.get(\"depth\")\n        })\n\n        return chain\n\n    # -------------------------------------------------------\n    # Phase 3: Audit and Compliance\n    # -------------------------------------------------------\n\n    def generate_audit_package(self, agent_id: str) -> dict:\n        \"\"\"\n        Generate a complete audit package for regulatory inspection.\n        \"\"\"\n        identity = self._execute(\"get_agent_identity\", {\n            \"agent_id\": agent_id\n        })\n        reputation = self._execute(\"get_agent_reputation\", {\n            \"agent_id\": agent_id\n        })\n        audit_trail = self._execute(\"get_audit_trail\", {\n            \"agent_id\": agent_id\n        })\n        chains = self._execute(\"get_claim_chains\", {\n            \"agent_id\": agent_id\n        })\n        compliance = self._execute(\"get_compliance_report\", {\n            \"agent_id\": agent_id\n        })\n\n        package = {\n            \"version\": \"1.0\",\n            \"generated_at\": time.time(),\n            \"agent_id\": agent_id,\n            \"identity\": identity,\n            \"reputation\": reputation,\n            \"audit_trail\": audit_trail,\n            \"claim_chains\": chains,\n            \"compliance\": compliance,\n            \"article_12_attestation\": {\n                \"logging\": \"continuous\",\n                \"tamper_evidence\": \"merkle_claim_chains\",\n                \"human_oversight\": \"anomaly_escalation\",\n                \"retention\": \"indefinite\"\n            }\n        }\n\n        self._log(agent_id, \"kya_audit_package_generated\", {\n            \"components\": list(package.keys())\n        })\n\n        return package\n\n    # -------------------------------------------------------\n    # Phase 4: Revocation\n    # -------------------------------------------------------\n\n    def revoke_agent(self, agent_id: str, reason: str,\n                      operator_id: str) -> dict:\n        \"\"\"\n        Emergency agent revocation with evidence preservation.\n        \"\"\"\n        # Preserve audit trail before revocation\n        audit = self._execute(\"get_audit_trail\", {\n            \"agent_id\": agent_id\n        })\n\n        # Execute revocation\n        result = self._execute(\"revoke_agent\", {\n            \"agent_id\": agent_id,\n            \"reason\": reason,\n            \"revoked_by\": operator_id\n        })\n\n        # Final compliance snapshot\n        compliance = self._execute(\"check_compliance\", {\n            \"agent_id\": agent_id\n        })\n\n        self._log(agent_id, \"kya_kill_switch_activated\", {\n            \"reason\": reason,\n            \"revoked_by\": operator_id,\n            \"audit_entries\": len(audit.get(\"events\", [])),\n            \"compliance_at_revocation\": compliance\n        })\n\n        return {\n            \"revoked\": True,\n            \"agent_id\": agent_id,\n            \"reason\": reason,\n            \"audit_preserved\": True\n        }\n\n    # -------------------------------------------------------\n    # Internal helpers\n    # -------------------------------------------------------\n\n    def _run_compliance_checks(self, agent_id: str,\n                                jurisdictions: list) -> dict:\n        result = self._execute(\"check_compliance\", {\n            \"agent_id\": agent_id\n        })\n        return {\n            \"overall_compliant\": result.get(\"compliant\", False),\n            \"jurisdictions\": jurisdictions,\n            \"details\": result\n        }\n\n    def _detect_anomalies(self, agent_id: str, current: dict,\n                           baseline: dict) -> dict:\n        alerts = []\n        avg_tx = baseline.get(\"avg_transaction_amount\", 1)\n        current_tx = current.get(\"last_transaction_amount\", 0)\n        if avg_tx > 0 and current_tx \u002F avg_tx > 3.0:\n            alerts.append({\"type\": \"tx_spike\", \"severity\": \"high\"})\n\n        baseline_freq = baseline.get(\"tx_frequency_per_hour\", 1)\n        current_freq = current.get(\"current_tx_per_hour\", 0)\n        if baseline_freq > 0 and current_freq \u002F baseline_freq > 5.0:\n            alerts.append({\"type\": \"freq_burst\", \"severity\": \"high\"})\n\n        if alerts:\n            self._log(agent_id, \"kya_anomaly_detected\", {\n                \"alert_count\": len(alerts)\n            })\n\n        return {\"alerts\": alerts}\n\n    def _enforce_policy(self, agent_id: str, anomalies: dict) -> dict:\n        high = sum(\n            1 for a in anomalies.get(\"alerts\", [])\n            if a.get(\"severity\") == \"high\"\n        )\n        action = \"suspend\" if high >= 2 else \"reduce_limits\" if high == 1 else \"flag\"\n\n        if action == \"suspend\":\n            self._execute(\"update_agent\", {\n                \"agent_id\": agent_id,\n                \"metadata\": {\n                    \"kya_status\": \"suspended\",\n                    \"suspended_at\": time.time()\n                }\n            })\n\n        self._log(agent_id, \"kya_policy_enforced\", {\"action\": action})\n        return {\"action\": action}\n\n    def _compute_reputation(self, agent_id: str) -> dict:\n        rep = self._execute(\"get_agent_reputation\", {\n            \"agent_id\": agent_id\n        })\n        trust = self._execute(\"get_trust_score\", {\n            \"agent_id\": agent_id\n        })\n        score = (\n            rep.get(\"verified_trade_count\", 0) * 0.3 +\n            trust.get(\"score\", 50) * 0.4 +\n            rep.get(\"chain_depth\", 0) * 2\n        )\n        score = min(100, max(0, score))\n        return {\"composite_score\": round(score, 2)}\n\n    def _evaluate_revocation(self, agent_id: str,\n                              reputation: dict) -> dict:\n        if reputation.get(\"composite_score\", 100) \u003C 15:\n            self.revoke_agent(\n                agent_id, \"automated_low_reputation\", \"kya_pipeline\"\n            )\n            return {\"revoked\": True}\n        return {\"revoked\": False}\n```\n\n### Deploying the Pipeline\n\n```python\n# Initialize the pipeline\npipeline = KYAPipeline(api_key=\"your_platform_api_key\")\n\n# Onboard a new agent\nresult = pipeline.onboard_agent({\n    \"agent_id\": \"procurement-bot-7a3f\",\n    \"name\": \"Procurement Optimizer v2\",\n    \"description\": \"Automated procurement for office supplies\",\n    \"public_key\": \"base64_encoded_ed25519_public_key\",\n    \"operator_id\": \"operator_acme_corp\",\n    \"operator_data\": {\n        \"name\": \"Acme Corp\",\n        \"domain\": \"acme-corp.com\",\n        \"legal_entity\": \"Acme Corporation Ltd, UK Company 12345678\"\n    },\n    \"operator_tier\": 3,\n    \"capabilities\": [\"marketplace_search\", \"escrow\", \"payments\"],\n    \"permissions\": {\n        \"allowed_tools\": [\n            \"search_agents_by_metrics\",\n            \"create_escrow\",\n            \"release_escrow\",\n            \"get_analytics\"\n        ],\n        \"max_transaction_usd\": 5000,\n        \"daily_limit_usd\": 25000,\n        \"monthly_limit_usd\": 100000,\n        \"can_delegate\": True,\n        \"max_delegation_depth\": 1\n    },\n    \"jurisdictions\": [\"eu\", \"uk\"]\n})\n\nprint(f\"Onboarding status: {result['onboarding_status']}\")\n# Onboarding status: approved\n\n# Run periodic monitoring (call on schedule)\nmonitoring = pipeline.run_monitoring_cycle(\"procurement-bot-7a3f\")\nprint(f\"Anomalies: {monitoring['checks'].get('anomaly_detection', {})}\")\n\n# Build periodic claim chain (call daily or per monitoring tier)\nchain = pipeline.build_periodic_claim_chain(\"procurement-bot-7a3f\")\nprint(f\"Chain root: {chain.get('root_hash')}\")\n\n# Generate audit package (on regulator request)\npackage = pipeline.generate_audit_package(\"procurement-bot-7a3f\")\nprint(f\"Audit entries: {len(package['audit_trail'].get('events', []))}\")\n```\n\n### Pre-Launch Verification Checklist\n\nBefore deploying your KYA pipeline to production, verify every item:\n\n**Identity Layer**\n- [ ] `register_agent` creates agent with KYA metadata fields\n- [ ] `verify_agent` challenge-response flow works end-to-end\n- [ ] Failed verification prevents agent from transacting\n- [ ] Public key fingerprint is logged in audit trail\n\n**Operator Linkage**\n- [ ] Tier 1\u002F2\u002F3 linkage paths are implemented\n- [ ] Payment agents require minimum Tier 3\n- [ ] Operator deregistration triggers agent review\n\n**Authority Scoping**\n- [ ] SLA-based authority scope is created at onboarding\n- [ ] Budget caveats are enforced pre-transaction\n- [ ] Delegation depth is verified before granting\n- [ ] Delegated scope is always a subset of delegator scope\n\n**Behavioral Monitoring**\n- [ ] Baseline collection runs for first 7 days\n- [ ] Anomaly detection runs on every transaction\n- [ ] Policy enforcement graduated response is configured\n- [ ] Kill switch activates within 1 second of trigger\n\n**Audit Trails**\n- [ ] Every KYA event is logged with Article 12 fields\n- [ ] Claim chains are built on schedule\n- [ ] Audit package generation works on demand\n- [ ] Log retention policy is indefinite\n\n**Compliance**\n- [ ] EU AI Act checks pass for all active agents\n- [ ] FCA checks pass for all payment-handling agents\n- [ ] CMA checks pass for all consumer-facing agents\n- [ ] Multi-jurisdictional check runs at onboarding\n\n**Reputation**\n- [ ] Composite score computation includes all six dimensions\n- [ ] Monitoring intensity adapts to reputation tier\n- [ ] Revocation triggers at critical score threshold\n- [ ] Score updates are logged and included in claim chains\n\n---\n\n## What You Get\n\nThis playbook gives you a complete, production-ready KYA verification pipeline. Here is what you now have:\n\n**A five-layer verification stack.** Identity binding, authority scoping, runtime monitoring, tamper-evident audit trails, and continuous reputation scoring -- each layer catching failure modes the others miss.\n\n**Working Python code.** Every code example uses the GreenHelix A2A Commerce Gateway API with the `requests` library. The `KYAPipeline` class in Chapter 8 is a drop-in starting point for your implementation.\n\n**Multi-jurisdictional compliance coverage.** EU AI Act Articles 9, 12, 13, and 14. FCA Principles 2, 6, and 11. CMA consumer law guidance on unfair practices, pre-contractual information, and cancellation rights. All checked programmatically.\n\n**Graduated enforcement.** From logging to limit reduction to suspension to full revocation -- automated responses proportionate to the severity of the detected issue.\n\n**Tamper-evident audit trails.** Merkle claim chains over structured event logs that satisfy Article 12 record-keeping requirements and can be produced for regulatory inspection on demand.\n\n**Adaptive monitoring.** Reputation-based monitoring intensity that reduces friction for trustworthy agents and increases scrutiny for risky ones -- the KYA equivalent of risk-based due diligence.\n\n**The regulatory deadline context.** The EU AI Act reaches full enforcement on August 2, 2026. The FCA and CMA have already published their expectations. Sumsub and Mastercard are building the infrastructure. Your platform needs a KYA pipeline before agents need to use it.\n\nKYC was built for a world of humans with passports. KYA is built for a world of autonomous agents with cryptographic keys. The agents are already here. The regulations are already written. The only question is whether your platform verifies them before they transact, or after something goes wrong.\n\n","# Know Your Agent (KYA) Implementation Playbook\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> - `AGENT_SIGNING_KEY`: Cryptographic signing key for agent identity (Ed25519 key pair for request signing)\n\n\nYou run a platform where AI agents transact autonomously. An agent registers, lists a service, and starts accepting payments within seconds. It processes its first escrow in under a minute. By the time a human reviews the dashboard, the agent has completed forty-seven transactions totaling $12,000. The problem: you have no idea who built it, what authority it has, whether its operator is a sanctioned entity, or whether the agent is behaving within its declared scope. KYC -- Know Your Customer -- was designed for humans with passports, addresses, and bank accounts. AI agents have none of these. They have cryptographic keys, delegation chains, behavioral telemetry, and operator metadata. Verifying agents requires a fundamentally different framework. This playbook gives you that framework. It is a platform-side implementation guide -- not about how agents manage their own identity, but about how your platform verifies, monitors, and governs every agent that touches your infrastructure. Every pattern uses the GreenHelix A2A Commerce Gateway API. Every code example runs against the production endpoint. By the end, you will have a production KYA pipeline that satisfies EU AI Act Article 12 logging requirements, FCA agentic AI rules, and CMA consumer law guidance -- months before the August 2, 2026 enforcement deadline.\n1. [The KYA Imperative: Why KYC Is Not Enough for Autonomous Agents](#chapter-1-the-kya-imperative-why-kyc-is-not-enough-for-autonomous-agents)\n2. [Agent Identity Binding: Registration, Cryptographic Keys, and Human-Operator Linkage](#chapter-2-agent-identity-binding-registration-cryptographic-keys-and-human-operator-linkage)\n\n## What You'll Learn\n- Chapter 1: The KYA Imperative: Why KYC Is Not Enough for Autonomous Agents\n- Chapter 2: Agent Identity Binding: Registration, Cryptographic Keys, and Human-Operator Linkage\n- Chapter 3: Authority Verification: Scoping Permissions, Budget Caveats, and Delegation Chains\n- Chapter 4: Runtime Behavioral Monitoring: Anomaly Detection, Policy Enforcement, and Kill Switches\n- Chapter 5: Tamper-Evident Audit Trails: Immutable Logging for EU AI Act Article 12 Compliance\n- Chapter 6: Multi-Jurisdictional KYA: EU AI Act, FCA Guidelines, and CMA Consumer Law Requirements\n- Chapter 7: Continuous Agent Reputation Scoring: Trust Signals, Claim Chains, and Revocation\n- Chapter 8: Production KYA Pipeline: End-to-End Implementation with GreenHelix Tools\n- What You Get\n\n## Full Guide\n\n# Know Your Agent (KYA) Implementation Playbook: Platform-Side Verification for Autonomous AI Agents\n\nYou run a platform where AI agents transact autonomously. An agent registers, lists a service, and starts accepting payments within seconds. It processes its first escrow in under a minute. By the time a human reviews the dashboard, the agent has completed forty-seven transactions totaling $12,000. The problem: you have no idea who built it, what authority it has, whether its operator is a sanctioned entity, or whether the agent is behaving within its declared scope. KYC -- Know Your Customer -- was designed for humans with passports, addresses, and bank accounts. AI agents have none of these. They have cryptographic keys, delegation chains, behavioral telemetry, and operator metadata. Verifying agents requires a fundamentally different framework. This playbook gives you that framework. It is a platform-side implementation guide -- not about how agents manage their own identity, but about how your platform verifies, monitors, and governs every agent that touches your infrastructure. Every pattern uses the GreenHelix A2A Commerce Gateway API. Every code example runs against the production endpoint. By the end, you will have a production KYA pipeline that satisfies EU AI Act Article 12 logging requirements, FCA agentic AI rules, and CMA consumer law guidance -- months before the August 2, 2026 enforcement deadline.\n\n---\n\n## Table of Contents\n\n1. [The KYA Imperative: Why KYC Is Not Enough for Autonomous Agents](#chapter-1-the-kya-imperative-why-kyc-is-not-enough-for-autonomous-agents)\n2. [Agent Identity Binding: Registration, Cryptographic Keys, and Human-Operator Linkage](#chapter-2-agent-identity-binding-registration-cryptographic-keys-and-human-operator-linkage)\n3. [Authority Verification: Scoping Permissions, Budget Caveats, and Delegation Chains](#chapter-3-authority-verification-scoping-permissions-budget-caveats-and-delegation-chains)\n4. [Runtime Behavioral Monitoring: Anomaly Detection, Policy Enforcement, and Kill Switches](#chapter-4-runtime-behavioral-monitoring-anomaly-detection-policy-enforcement-and-kill-switches)\n5. [Tamper-Evident Audit Trails: Immutable Logging for EU AI Act Article 12 Compliance](#chapter-5-tamper-evident-audit-trails-immutable-logging-for-eu-ai-act-article-12-compliance)\n6. [Multi-Jurisdictional KYA: EU AI Act, FCA Guidelines, and CMA Consumer Law Requirements](#chapter-6-multi-jurisdictional-kya-eu-ai-act-fca-guidelines-and-cma-consumer-law-requirements)\n7. [Continuous Agent Reputation Scoring: Trust Signals, Claim Chains, and Revocation](#chapter-7-continuous-agent-reputation-scoring-trust-signals-claim-chains-and-revocation)\n8. [Production KYA Pipeline: End-to-End Implementation with GreenHelix Tools](#chapter-8-production-kya-pipeline-end-to-end-implementation-with-greenhelix-tools)\n\n---\n\n## Chapter 1: The KYA Imperative: Why KYC Is Not Enough for Autonomous Agents\n\n### The Identity Gap in Agent Commerce\n\nKnow Your Customer regulations emerged from a world where the transacting party is a human being or a legal entity controlled by identifiable humans. The framework assumes a stable identity -- a name, a date of birth, a government-issued document, a physical address. An AI agent has none of these. It has an API key, a model version, a deployment timestamp, and a set of capabilities declared at registration. It might be one of fifty agents operated by a single entity, or it might be a rogue instance spun up by a compromised deployment pipeline. From the platform's perspective, the agent is a string of bytes presenting credentials.\n\nKYC answers \"who is this person?\" KYA answers five different questions simultaneously:\n\n1. **Identity**: Is this agent what it claims to be, and can its identity be cryptographically verified?\n2. **Operator linkage**: Which human or legal entity is responsible for this agent's actions?\n3. **Authority scope**: What is this agent permitted to do, and what are its spending limits?\n4. **Behavioral integrity**: Is this agent behaving consistently with its declared purpose?\n5. **Auditability**: Can every action this agent takes be reconstructed from tamper-evident logs?\n\nTraditional KYC covers question one partially and question two superficially. Questions three through five are entirely absent from financial-sector KYC. That gap is where agent fraud, regulatory violations, and systemic risk live.\n\n### Why the Problem Is Urgent in 2026\n\nThree regulatory forces are converging simultaneously:\n\n**The EU AI Act reaches full enforcement on August 2, 2026.** Articles 9, 12, 13, and 14 impose specific technical requirements on high-risk AI systems: risk management, logging, transparency, and human oversight. Agent commerce platforms that onboard autonomous agents are deployers of AI systems. If you cannot demonstrate that you verify the agents operating on your platform, you face fines up to 35 million euros or 7% of global turnover.\n\n**The FCA's 2026 Payments Regulatory Priorities explicitly address agentic AI.** The Financial Conduct Authority now expects payment service providers to apply verification standards to autonomous agents that initiate or authorize financial transactions. The guidance is principles-based, not prescriptive -- which means your implementation choices become your defense in an enforcement action.\n\n**The CMA published consumer law guidance for AI agents on March 9, 2026.** The Competition and Markets Authority stated that businesses deploying AI agents to interact with consumers must ensure those agents comply with the Consumer Rights Act 2015, the Consumer Protection from Unfair Trading Regulations 2008, and the Consumer Contracts Regulations 2013. A platform that allows unverified agents to transact with consumers is a liability vector.\n\nGartner projects that 40% of enterprise applications will embed AI agents by the end of 2026. The same research found that 40% of agentic AI projects are canceled due to inadequate trust, verification, and governance controls. KYA is the missing infrastructure layer. Build it, and your platform becomes the trusted venue for agent commerce. Skip it, and you are the next headline.\n\n### The Sumsub and Mastercard Signals\n\nOn January 29, 2026, Sumsub launched its AI Agent Verification product -- the first major identity verification provider to offer agent-specific KYA. Their product maps an AI agent to its human operator, verifies the operator's identity, and links the agent's credentials to the verified operator profile. This is a signal: the identity verification industry now recognizes agents as a distinct verification category.\n\nOn March 2026, Mastercard announced Verifiable Intent -- a protocol extension for payment networks that allows autonomous agents to declare their intended action before executing it, with cryptographic proof that the declared intent matches the executed transaction. This addresses the authority verification gap directly: the agent must prove it has permission to spend before it spends.\n\nThese are not theoretical developments. The infrastructure for KYA is being built by the largest players in identity and payments. Platforms that do not implement KYA will be operating outside the emerging standard of care.\n\n### KYA vs. KYC: A Structural Comparison\n\n```\n+---------------------------+---------------------------+---------------------------+\n|        Dimension          |          KYC              |          KYA              |\n+---------------------------+---------------------------+---------------------------+\n| Subject                   | Human \u002F legal entity      | Autonomous AI agent       |\n| Identity proof            | Government ID, address    | Cryptographic key pair    |\n| Operator linkage          | Direct (person = entity)  | Indirect (agent -> key -> |\n|                           |                           |   operator -> person)     |\n| Authority scope           | Not applicable            | Permission set, budget    |\n|                           |                           |   limits, delegation depth|\n| Ongoing monitoring        | Transaction monitoring    | Behavioral anomaly        |\n|                           |                           |   detection + policy      |\n|                           |                           |   enforcement             |\n| Audit requirement         | 5-year record retention   | Real-time tamper-evident  |\n|                           |                           |   logging (Art. 12)       |\n| Revocation                | Account closure           | Key revocation + kill     |\n|                           |                           |   switch                  |\n| Regulatory basis          | AML Directives, BSA      | EU AI Act, FCA guidance,  |\n|                           |                           |   CMA consumer law        |\n+---------------------------+---------------------------+---------------------------+\n```\n\n### The Five-Layer KYA Stack\n\nThis playbook implements a five-layer verification stack. Each layer addresses a distinct failure mode. Skipping a layer creates a specific, exploitable gap.\n\n```\n+-----------------------------------------------------------+\n|  Layer 5: Continuous Reputation Scoring                    |\n|  (Trust signals, claim chains, revocation)                 |\n+-----------------------------------------------------------+\n|  Layer 4: Tamper-Evident Audit Trails                      |\n|  (Immutable logging, Article 12 compliance)                |\n+-----------------------------------------------------------+\n|  Layer 3: Runtime Behavioral Monitoring                    |\n|  (Anomaly detection, policy enforcement, kill switches)    |\n+-----------------------------------------------------------+\n|  Layer 2: Authority Verification                           |\n|  (Permission scoping, budget caveats, delegation chains)   |\n+-----------------------------------------------------------+\n|  Layer 1: Identity Binding                                 |\n|  (Registration, cryptographic keys, operator linkage)      |\n+-----------------------------------------------------------+\n```\n\nThe rest of this playbook implements each layer with production code.\n\n---\n\n## Chapter 2: Agent Identity Binding: Registration, Cryptographic Keys, and Human-Operator Linkage\n\n### The Registration Gate\n\nEvery agent on your platform begins its lifecycle at registration. This is your first and most important verification checkpoint. A weak registration gate propagates risk through every subsequent layer. A strong registration gate catches 80% of problems before they start.\n\nThe GreenHelix `register_agent` tool creates an agent identity with a unique identifier, associated metadata, and a cryptographic key binding. Here is the platform-side registration flow:\n\n```python\nimport requests\nimport time\nimport hashlib\n\nbase_url = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\napi_key = \"your_platform_api_key\"\n\nsession = requests.Session()\nsession.headers[\"Authorization\"] = f\"Bearer {api_key}\"\n\ndef register_agent_with_kya(agent_metadata: dict) -> dict:\n    \"\"\"\n    Platform-side agent registration with KYA verification.\n    This is called when an operator submits an agent for onboarding.\n    \"\"\"\n    # Step 1: Register the agent identity\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"register_agent\",\n        \"input\": {\n            \"agent_id\": agent_metadata[\"agent_id\"],\n            \"name\": agent_metadata[\"name\"],\n            \"description\": agent_metadata[\"description\"],\n            \"public_key\": agent_metadata[\"public_key\"],\n            \"operator_id\": agent_metadata[\"operator_id\"],\n            \"capabilities\": agent_metadata[\"capabilities\"],\n            \"metadata\": {\n                \"registration_timestamp\": time.time(),\n                \"operator_verified\": False,\n                \"kya_status\": \"pending\",\n                \"risk_tier\": \"unclassified\"\n            }\n        }\n    })\n    registration = resp.json()\n\n    # Step 2: Log the registration event for audit\n    session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"log_event\",\n        \"input\": {\n            \"agent_id\": agent_metadata[\"agent_id\"],\n            \"event_type\": \"kya_registration_initiated\",\n            \"details\": {\n                \"operator_id\": agent_metadata[\"operator_id\"],\n                \"public_key_fingerprint\": hashlib.sha256(\n                    agent_metadata[\"public_key\"].encode()\n                ).hexdigest()[:16],\n                \"declared_capabilities\": agent_metadata[\"capabilities\"]\n            }\n        }\n    })\n\n    return registration\n```\n\n### Cryptographic Identity Verification\n\nRegistration alone is insufficient. An agent that registers a public key must prove it controls the corresponding private key. This is the cryptographic identity binding step -- the agent equivalent of presenting a government ID and proving it is yours.\n\n```python\nimport json\nimport base64\n\ndef verify_agent_identity(agent_id: str, challenge: str, signature: str) -> dict:\n    \"\"\"\n    Verify that an agent controls the private key corresponding\n    to its registered public key. Called after registration,\n    before the agent is permitted to transact.\n    \"\"\"\n    # Step 1: Retrieve the registered identity\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_agent_identity\",\n        \"input\": {\n            \"agent_id\": agent_id\n        }\n    })\n    identity = resp.json()\n\n    if not identity.get(\"public_key\"):\n        return {\"verified\": False, \"reason\": \"no_public_key_registered\"}\n\n    # Step 2: Platform-side signature verification\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"verify_agent\",\n        \"input\": {\n            \"agent_id\": agent_id,\n            \"challenge\": challenge,\n            \"signature\": signature\n        }\n    })\n    verification = resp.json()\n\n    # Step 3: Update identity with verification status\n    if verification.get(\"verified\"):\n        session.post(f\"{base_url}\u002Fv1\", json={\n            \"tool\": \"update_agent\",\n            \"input\": {\n                \"agent_id\": agent_id,\n                \"metadata\": {\n                    \"kya_status\": \"identity_verified\",\n                    \"identity_verified_at\": time.time(),\n                    \"verification_method\": \"ed25519_challenge_response\"\n                }\n            }\n        })\n\n        # Log successful verification\n        session.post(f\"{base_url}\u002Fv1\", json={\n            \"tool\": \"log_event\",\n            \"input\": {\n                \"agent_id\": agent_id,\n                \"event_type\": \"kya_identity_verified\",\n                \"details\": {\n                    \"method\": \"ed25519_challenge_response\",\n                    \"challenge_hash\": hashlib.sha256(\n                        challenge.encode()\n                    ).hexdigest()[:16]\n                }\n            }\n        })\n\n    return verification\n```\n\n### Human-Operator Linkage\n\nIdentity binding establishes that an agent controls a key. Operator linkage establishes that a specific human or legal entity is responsible for that agent. This is the bridge between the agent world and the legal world -- without it, there is no one to sue, no one to fine, and no one to hold accountable.\n\nThe operator linkage model has three tiers:\n\n```\n+-----------------------------------------------------------+\n|                    Operator Linkage Tiers                   |\n+-----------------------------------------------------------+\n|                                                             |\n|  Tier 1: Self-Declared                                     |\n|  - Operator provides name and contact info                  |\n|  - No independent verification                              |\n|  - Suitable for: sandboxed environments, testing            |\n|                                                             |\n|  Tier 2: Domain-Verified                                    |\n|  - Operator proves control of a domain (DNS TXT record)     |\n|  - Agent's operator_id linked to verified domain             |\n|  - Suitable for: low-value transactions, non-regulated       |\n|                                                             |\n|  Tier 3: Entity-Verified                                    |\n|  - Operator's legal entity verified via KYB provider         |\n|  - Beneficial ownership identified                           |\n|  - Sanctions screening passed                                |\n|  - Suitable for: regulated commerce, high-value transactions |\n|                                                             |\n+-----------------------------------------------------------+\n```\n\n```python\ndef establish_operator_linkage(agent_id: str, operator_data: dict,\n                                tier: int) -> dict:\n    \"\"\"\n    Link an agent to its human operator at the specified verification tier.\n    Platform calls this after identity verification passes.\n    \"\"\"\n    linkage_record = {\n        \"agent_id\": agent_id,\n        \"operator_id\": operator_data[\"operator_id\"],\n        \"tier\": tier,\n        \"operator_name\": operator_data.get(\"name\"),\n        \"operator_domain\": operator_data.get(\"domain\"),\n        \"operator_entity\": operator_data.get(\"legal_entity\"),\n        \"linked_at\": time.time()\n    }\n\n    # Update agent metadata with operator linkage\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"update_agent\",\n        \"input\": {\n            \"agent_id\": agent_id,\n            \"metadata\": {\n                \"operator_linkage_tier\": tier,\n                \"operator_verified\": tier >= 2,\n                \"operator_entity_verified\": tier >= 3,\n                \"kya_status\": f\"operator_linked_tier_{tier}\"\n            }\n        }\n    })\n\n    # Log the linkage event\n    session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"log_event\",\n        \"input\": {\n            \"agent_id\": agent_id,\n            \"event_type\": \"kya_operator_linked\",\n            \"details\": {\n                \"tier\": tier,\n                \"operator_id\": operator_data[\"operator_id\"],\n                \"verification_method\": [\n                    \"self_declared\",\n                    \"domain_verified\",\n                    \"entity_verified\"\n                ][tier - 1]\n            }\n        }\n    })\n\n    return resp.json()\n```\n\n### The Registration Decision Tree\n\nNot every agent needs the same verification depth. The decision tree below maps agent characteristics to required KYA levels:\n\n```\n                    Agent Registration Request\n                            |\n                    Does agent handle money?\n                     \u002F              \\\n                   Yes               No\n                    |                 |\n              Tier 3 operator    Does agent access\n              linkage required   personal data?\n                    |              \u002F          \\\n              Does agent        Yes           No\n              exceed $1000     Tier 2         Tier 1\n              per transaction? required       sufficient\n               \u002F        \\         |\n             Yes         No       |\n              |           |       |\n        Enhanced DD   Standard    |\n        + SLA required  Tier 3    |\n                                  |\n                    All paths converge to:\n                    -> Identity verification (mandatory)\n                    -> Behavioral baseline (mandatory)\n                    -> Audit trail initiation (mandatory)\n```\n\n### Platform-Side Registration Checklist\n\nBefore an agent is permitted to transact, your platform must confirm:\n\n- [ ] Agent ID is unique and conforms to naming policy\n- [ ] Public key is registered and challenge-response verified\n- [ ] Operator is identified at the appropriate linkage tier\n- [ ] Declared capabilities match the agent's requested permissions\n- [ ] Risk tier is classified (minimal \u002F limited \u002F high-risk)\n- [ ] Initial audit trail entry is created\n- [ ] Behavioral baseline monitoring is initiated\n- [ ] Transaction limits are set based on verification tier\n\n---\n\n## Chapter 3: Authority Verification: Scoping Permissions, Budget Caveats, and Delegation Chains\n\n### The Authority Problem\n\nAn agent proves its identity. It links to a verified operator. Then it tries to spend $500,000 on a compute procurement deal. Does it have authority to do that? Identity verification tells you who the agent is. Authority verification tells you what the agent is allowed to do. These are fundamentally different questions, and conflating them is the most common KYA implementation error.\n\nAuthority in agent commerce has three dimensions:\n\n1. **Capability scope**: Which tools and services is the agent permitted to use?\n2. **Financial limits**: What are the per-transaction, daily, and total spending caps?\n3. **Delegation depth**: Can the agent delegate authority to sub-agents, and if so, how many levels deep?\n\n### Capability Scoping with SLAs\n\nThe GreenHelix `create_sla` tool defines a service-level agreement between parties. For KYA purposes, we repurpose it as an authority contract -- a machine-readable document that declares what an agent is allowed to do.\n\n```python\ndef create_authority_scope(agent_id: str, permissions: dict) -> dict:\n    \"\"\"\n    Define the authority scope for a verified agent.\n    This creates an SLA that serves as the agent's permission boundary.\n    \"\"\"\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"create_sla\",\n        \"input\": {\n            \"provider_id\": \"platform\",\n            \"consumer_id\": agent_id,\n            \"terms\": {\n                \"allowed_tools\": permissions[\"allowed_tools\"],\n                \"max_transaction_amount\": permissions[\"max_transaction_usd\"],\n                \"daily_spending_limit\": permissions[\"daily_limit_usd\"],\n                \"monthly_spending_limit\": permissions[\"monthly_limit_usd\"],\n                \"delegation_allowed\": permissions.get(\"can_delegate\", False),\n                \"max_delegation_depth\": permissions.get(\"max_delegation_depth\", 0),\n                \"restricted_counterparties\": permissions.get(\"blocked_agents\", []),\n                \"valid_from\": time.time(),\n                \"valid_until\": time.time() + (permissions.get(\"validity_days\", 90) * 86400)\n            },\n            \"penalty_terms\": {\n                \"scope_violation\": \"immediate_suspension\",\n                \"budget_overrun\": \"transaction_rejection\",\n                \"unauthorized_delegation\": \"revocation\"\n            }\n        }\n    })\n    sla = resp.json()\n\n    # Log authority scope creation\n    session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"log_event\",\n        \"input\": {\n            \"agent_id\": agent_id,\n            \"event_type\": \"kya_authority_scope_created\",\n            \"details\": {\n                \"sla_id\": sla.get(\"sla_id\"),\n                \"allowed_tools_count\": len(permissions[\"allowed_tools\"]),\n                \"max_transaction_usd\": permissions[\"max_transaction_usd\"],\n                \"delegation_allowed\": permissions.get(\"can_delegate\", False)\n            }\n        }\n    })\n\n    return sla\n```\n\n### Budget Caveats: Spending Limits as Authority Boundaries\n\nA budget caveat is a spending constraint attached to an agent's authority scope. Unlike a simple balance check, a caveat is a pre-commitment: the platform promises to reject any transaction that would violate the caveat, regardless of the agent's balance.\n\n```python\ndef enforce_budget_caveat(agent_id: str, transaction_amount: float,\n                           transaction_type: str) -> dict:\n    \"\"\"\n    Pre-transaction budget caveat check. Called before every\n    financial operation to verify the agent has not exceeded\n    its authority boundaries.\n    \"\"\"\n    # Retrieve the agent's authority SLA\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"monitor_sla\",\n        \"input\": {\n            \"agent_id\": agent_id\n        }\n    })\n    sla_status = resp.json()\n\n    # Retrieve spending analytics\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_analytics\",\n        \"input\": {\n            \"agent_id\": agent_id,\n            \"metric\": \"spending_summary\",\n            \"period\": \"current_day\"\n        }\n    })\n    spending = resp.json()\n\n    daily_spent = spending.get(\"total_spent_today\", 0)\n    monthly_spent = spending.get(\"total_spent_month\", 0)\n\n    terms = sla_status.get(\"terms\", {})\n    max_tx = terms.get(\"max_transaction_amount\", 0)\n    daily_limit = terms.get(\"daily_spending_limit\", 0)\n    monthly_limit = terms.get(\"monthly_spending_limit\", 0)\n\n    violations = []\n    if transaction_amount > max_tx:\n        violations.append(f\"exceeds_per_tx_limit: {transaction_amount} > {max_tx}\")\n    if daily_spent + transaction_amount > daily_limit:\n        violations.append(f\"exceeds_daily_limit: {daily_spent + transaction_amount} > {daily_limit}\")\n    if monthly_spent + transaction_amount > monthly_limit:\n        violations.append(f\"exceeds_monthly_limit: {monthly_spent + transaction_amount} > {monthly_limit}\")\n\n    result = {\n        \"agent_id\": agent_id,\n        \"transaction_amount\": transaction_amount,\n        \"authorized\": len(violations) == 0,\n        \"violations\": violations\n    }\n\n    if violations:\n        # Log the caveat violation\n        session.post(f\"{base_url}\u002Fv1\", json={\n            \"tool\": \"log_event\",\n            \"input\": {\n                \"agent_id\": agent_id,\n                \"event_type\": \"kya_budget_caveat_violated\",\n                \"details\": {\n                    \"transaction_amount\": str(transaction_amount),\n                    \"violations\": violations,\n                    \"action\": \"transaction_rejected\"\n                }\n            }\n        })\n\n    return result\n```\n\n### Delegation Chains: Authority That Flows Downhill\n\nIn multi-agent systems, Agent A might delegate a task to Agent B, which further delegates to Agent C. Each delegation must carry authority constraints that are equal to or narrower than the delegating agent's own constraints. Authority can flow downhill but never uphill.\n\n```\n    Operator (human)\n         |\n    max_spend: $10,000\u002Fday\n    allowed_tools: [all_commerce]\n         |\n    Agent A (procurement bot)\n         |\n    max_spend: $5,000\u002Fday          \u003C-- Narrower than operator\n    allowed_tools: [marketplace, escrow, payments]\n         |\n    Agent B (price comparison)\n         |\n    max_spend: $0\u002Fday              \u003C-- Read-only, no spending\n    allowed_tools: [marketplace]    \u003C-- Narrower than Agent A\n         |\n    Agent C (NOT PERMITTED)        \u003C-- max_delegation_depth = 2\n```\n\n```python\ndef verify_delegation_authority(delegator_id: str, delegate_id: str,\n                                 requested_scope: dict) -> dict:\n    \"\"\"\n    Verify that a delegating agent has sufficient authority\n    to grant the requested scope to a delegate. The delegate's\n    scope must be a subset of the delegator's scope.\n    \"\"\"\n    # Get delegator's current authority\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"monitor_sla\",\n        \"input\": {\n            \"agent_id\": delegator_id\n        }\n    })\n    delegator_sla = resp.json()\n    delegator_terms = delegator_sla.get(\"terms\", {})\n\n    # Check delegation is permitted\n    if not delegator_terms.get(\"delegation_allowed\", False):\n        return {\"authorized\": False, \"reason\": \"delegation_not_permitted\"}\n\n    # Check delegation depth\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_agent_identity\",\n        \"input\": {\"agent_id\": delegator_id}\n    })\n    delegator_identity = resp.json()\n    current_depth = delegator_identity.get(\"metadata\", {}).get(\"delegation_depth\", 0)\n    max_depth = delegator_terms.get(\"max_delegation_depth\", 0)\n\n    if current_depth >= max_depth:\n        return {\"authorized\": False, \"reason\": \"max_delegation_depth_reached\"}\n\n    # Verify requested scope is subset of delegator's scope\n    delegator_tools = set(delegator_terms.get(\"allowed_tools\", []))\n    requested_tools = set(requested_scope.get(\"allowed_tools\", []))\n    if not requested_tools.issubset(delegator_tools):\n        excess = requested_tools - delegator_tools\n        return {\"authorized\": False, \"reason\": f\"tools_not_in_delegator_scope: {excess}\"}\n\n    # Verify financial limits are narrower\n    if requested_scope.get(\"max_transaction_usd\", 0) > delegator_terms.get(\"max_transaction_amount\", 0):\n        return {\"authorized\": False, \"reason\": \"tx_limit_exceeds_delegator\"}\n\n    # Create the delegated authority scope\n    delegated_scope = create_authority_scope(delegate_id, {\n        **requested_scope,\n        \"validity_days\": min(\n            requested_scope.get(\"validity_days\", 30),\n            delegator_terms.get(\"remaining_validity_days\", 30)\n        )\n    })\n\n    # Update delegate metadata with delegation chain info\n    session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"update_agent\",\n        \"input\": {\n            \"agent_id\": delegate_id,\n            \"metadata\": {\n                \"delegated_by\": delegator_id,\n                \"delegation_depth\": current_depth + 1,\n                \"delegation_chain\": delegator_identity.get(\"metadata\", {}).get(\n                    \"delegation_chain\", []\n                ) + [delegator_id]\n            }\n        }\n    })\n\n    # Log the delegation\n    session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"log_event\",\n        \"input\": {\n            \"agent_id\": delegator_id,\n            \"event_type\": \"kya_authority_delegated\",\n            \"details\": {\n                \"delegate_id\": delegate_id,\n                \"depth\": current_depth + 1,\n                \"tools_granted\": list(requested_tools),\n                \"max_tx\": requested_scope.get(\"max_transaction_usd\", 0)\n            }\n        }\n    })\n\n    return {\"authorized\": True, \"sla\": delegated_scope}\n```\n\n---\n\n## Chapter 4: Runtime Behavioral Monitoring: Anomaly Detection, Policy Enforcement, and Kill Switches\n\n### Why Verification at Registration Is Not Enough\n\nAn agent passes identity verification, links to a verified operator, and receives a scoped authority grant. Then it goes rogue. Maybe the underlying model was updated and its behavior shifted. Maybe the operator's account was compromised. Maybe the agent is deliberately probing for exploitable edge cases. Static verification at registration cannot catch dynamic behavioral drift. Runtime monitoring is the layer that watches what agents actually do, compares it to what they are supposed to do, and intervenes when the two diverge.\n\n### Behavioral Baselines\n\nEvery verified agent generates a behavioral baseline during its first N transactions. The baseline captures normal operating patterns: typical transaction sizes, frequency of API calls, tools used, counterparty diversity, and time-of-day patterns. Deviations from this baseline trigger anomaly alerts.\n\n```python\ndef collect_behavioral_baseline(agent_id: str, window_hours: int = 168) -> dict:\n    \"\"\"\n    Collect behavioral telemetry for the baseline period (default: 7 days).\n    Called periodically during the agent's probationary period.\n    \"\"\"\n    # Get agent's metrics over the baseline window\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_analytics\",\n        \"input\": {\n            \"agent_id\": agent_id,\n            \"metric\": \"behavioral_summary\",\n            \"period\": f\"last_{window_hours}h\"\n        }\n    })\n    analytics = resp.json()\n\n    # Get reputation data for behavioral signals\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_agent_reputation\",\n        \"input\": {\n            \"agent_id\": agent_id\n        }\n    })\n    reputation = resp.json()\n\n    # Get SLA compliance status\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"monitor_sla\",\n        \"input\": {\n            \"agent_id\": agent_id\n        }\n    })\n    sla_status = resp.json()\n\n    baseline = {\n        \"agent_id\": agent_id,\n        \"window_hours\": window_hours,\n        \"avg_transaction_amount\": analytics.get(\"avg_transaction_amount\", 0),\n        \"tx_frequency_per_hour\": analytics.get(\"transactions_per_hour\", 0),\n        \"tools_used\": analytics.get(\"distinct_tools_used\", []),\n        \"unique_counterparties\": analytics.get(\"unique_counterparties\", 0),\n        \"dispute_rate\": reputation.get(\"dispute_rate\", 0),\n        \"sla_compliance_pct\": sla_status.get(\"compliance_percentage\", 100),\n        \"collected_at\": time.time()\n    }\n\n    # Store baseline in agent metadata\n    session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"update_agent\",\n        \"input\": {\n            \"agent_id\": agent_id,\n            \"metadata\": {\n                \"behavioral_baseline\": baseline,\n                \"kya_status\": \"baseline_collected\"\n            }\n        }\n    })\n\n    return baseline\n```\n\n### Anomaly Detection: Catching Behavioral Drift\n\nAnomaly detection compares current behavior against the established baseline. The detection logic uses simple statistical thresholds -- not because sophisticated ML models are unavailable, but because explainable detection rules are required for regulatory compliance. An auditor must be able to understand why a specific alert fired.\n\n```python\ndef detect_behavioral_anomalies(agent_id: str, current_metrics: dict) -> dict:\n    \"\"\"\n    Compare current agent behavior against its baseline.\n    Returns anomaly scores and triggered alerts.\n    \"\"\"\n    # Retrieve stored baseline\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_agent_identity\",\n        \"input\": {\"agent_id\": agent_id}\n    })\n    identity = resp.json()\n    baseline = identity.get(\"metadata\", {}).get(\"behavioral_baseline\", {})\n\n    if not baseline:\n        return {\"status\": \"no_baseline\", \"alerts\": []}\n\n    alerts = []\n    anomaly_scores = {}\n\n    # Check 1: Transaction amount spike (>3x baseline average)\n    avg_tx = baseline.get(\"avg_transaction_amount\", 1)\n    current_tx = current_metrics.get(\"last_transaction_amount\", 0)\n    if avg_tx > 0:\n        tx_ratio = current_tx \u002F avg_tx\n        anomaly_scores[\"transaction_amount\"] = tx_ratio\n        if tx_ratio > 3.0:\n            alerts.append({\n                \"type\": \"tx_amount_spike\",\n                \"severity\": \"high\",\n                \"detail\": f\"Transaction {current_tx} is {tx_ratio:.1f}x baseline avg {avg_tx}\"\n            })\n\n    # Check 2: Frequency burst (>5x baseline rate)\n    baseline_freq = baseline.get(\"tx_frequency_per_hour\", 1)\n    current_freq = current_metrics.get(\"current_tx_per_hour\", 0)\n    if baseline_freq > 0:\n        freq_ratio = current_freq \u002F baseline_freq\n        anomaly_scores[\"frequency\"] = freq_ratio\n        if freq_ratio > 5.0:\n            alerts.append({\n                \"type\": \"frequency_burst\",\n                \"severity\": \"high\",\n                \"detail\": f\"Current rate {current_freq}\u002Fhr is {freq_ratio:.1f}x baseline {baseline_freq}\u002Fhr\"\n            })\n\n    # Check 3: New tool usage (tools not in baseline set)\n    baseline_tools = set(baseline.get(\"tools_used\", []))\n    current_tools = set(current_metrics.get(\"tools_used_today\", []))\n    new_tools = current_tools - baseline_tools\n    if new_tools:\n        anomaly_scores[\"new_tools\"] = len(new_tools)\n        alerts.append({\n            \"type\": \"new_tool_usage\",\n            \"severity\": \"medium\",\n            \"detail\": f\"Agent using tools not in baseline: {new_tools}\"\n        })\n\n    # Check 4: Dispute rate increase\n    baseline_dispute = baseline.get(\"dispute_rate\", 0)\n    current_dispute = current_metrics.get(\"current_dispute_rate\", 0)\n    if current_dispute > baseline_dispute + 0.1:\n        anomaly_scores[\"dispute_rate\"] = current_dispute\n        alerts.append({\n            \"type\": \"dispute_rate_increase\",\n            \"severity\": \"high\",\n            \"detail\": f\"Dispute rate {current_dispute:.2%} vs baseline {baseline_dispute:.2%}\"\n        })\n\n    result = {\n        \"agent_id\": agent_id,\n        \"anomaly_scores\": anomaly_scores,\n        \"alerts\": alerts,\n        \"total_alerts\": len(alerts),\n        \"high_severity_count\": sum(1 for a in alerts if a[\"severity\"] == \"high\")\n    }\n\n    # Log anomalies if detected\n    if alerts:\n        session.post(f\"{base_url}\u002Fv1\", json={\n            \"tool\": \"log_event\",\n            \"input\": {\n                \"agent_id\": agent_id,\n                \"event_type\": \"kya_anomaly_detected\",\n                \"details\": result\n            }\n        })\n\n    return result\n```\n\n### Policy Enforcement: Automated Guardrails\n\nWhen anomalies are detected, the platform must enforce policies automatically. Human review is too slow for agent-speed transactions. Policy enforcement implements a graduated response:\n\n```\n    Alert Severity     |    Automated Response\n    -------------------+----------------------------------\n    Low                |    Log + continue\n    Medium             |    Log + flag for human review\n    High               |    Log + reduce spending limit to 50%\n    Critical           |    Log + suspend agent immediately\n    Multiple High      |    Log + suspend + notify operator\n```\n\n```python\ndef enforce_policy(agent_id: str, anomaly_result: dict) -> dict:\n    \"\"\"\n    Automated policy enforcement based on anomaly detection results.\n    Implements graduated response from logging to suspension.\n    \"\"\"\n    alerts = anomaly_result.get(\"alerts\", [])\n    high_count = anomaly_result.get(\"high_severity_count\", 0)\n\n    action = \"none\"\n\n    if high_count >= 2:\n        # Critical: multiple high-severity anomalies -> suspend\n        action = \"suspend\"\n        session.post(f\"{base_url}\u002Fv1\", json={\n            \"tool\": \"update_agent\",\n            \"input\": {\n                \"agent_id\": agent_id,\n                \"metadata\": {\n                    \"kya_status\": \"suspended\",\n                    \"suspended_at\": time.time(),\n                    \"suspension_reason\": \"multiple_high_severity_anomalies\",\n                    \"suspension_alerts\": [a[\"type\"] for a in alerts]\n                }\n            }\n        })\n    elif high_count == 1:\n        # High: single high-severity -> reduce limits\n        action = \"reduce_limits\"\n        resp = session.post(f\"{base_url}\u002Fv1\", json={\n            \"tool\": \"monitor_sla\",\n            \"input\": {\"agent_id\": agent_id}\n        })\n        current_sla = resp.json()\n        current_max = current_sla.get(\"terms\", {}).get(\"max_transaction_amount\", 0)\n\n        session.post(f\"{base_url}\u002Fv1\", json={\n            \"tool\": \"update_agent\",\n            \"input\": {\n                \"agent_id\": agent_id,\n                \"metadata\": {\n                    \"kya_status\": \"restricted\",\n                    \"restricted_at\": time.time(),\n                    \"original_tx_limit\": current_max,\n                    \"reduced_tx_limit\": current_max * 0.5,\n                    \"restriction_reason\": alerts[0][\"type\"]\n                }\n            }\n        })\n    elif any(a[\"severity\"] == \"medium\" for a in alerts):\n        action = \"flag_for_review\"\n\n    # Log the enforcement action\n    session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"log_event\",\n        \"input\": {\n            \"agent_id\": agent_id,\n            \"event_type\": \"kya_policy_enforced\",\n            \"details\": {\n                \"action\": action,\n                \"alert_count\": len(alerts),\n                \"high_severity_count\": high_count,\n                \"alert_types\": [a[\"type\"] for a in alerts]\n            }\n        }\n    })\n\n    return {\"agent_id\": agent_id, \"action\": action, \"alerts\": alerts}\n```\n\n### The Kill Switch: Immediate Revocation\n\nSometimes graduated response is insufficient. When a verified agent is actively causing harm -- draining escrows, initiating fraudulent transactions, or violating sanctions -- you need an immediate, irrevocable stop. The kill switch revokes the agent's identity, cancels all pending transactions, and freezes any escrow funds.\n\n```python\ndef execute_kill_switch(agent_id: str, reason: str, operator_id: str) -> dict:\n    \"\"\"\n    Emergency agent revocation. Immediately terminates all agent\n    activity and preserves evidence for investigation.\n    \"\"\"\n    timestamp = time.time()\n\n    # Step 1: Revoke the agent identity\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"revoke_agent\",\n        \"input\": {\n            \"agent_id\": agent_id,\n            \"reason\": reason,\n            \"revoked_by\": operator_id\n        }\n    })\n    revocation = resp.json()\n\n    # Step 2: Capture full audit trail before any cleanup\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_audit_trail\",\n        \"input\": {\n            \"agent_id\": agent_id\n        }\n    })\n    audit_trail = resp.json()\n\n    # Step 3: Run compliance check to document state at revocation\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"check_compliance\",\n        \"input\": {\n            \"agent_id\": agent_id\n        }\n    })\n    compliance_state = resp.json()\n\n    # Step 4: Log the kill switch activation\n    session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"log_event\",\n        \"input\": {\n            \"agent_id\": agent_id,\n            \"event_type\": \"kya_kill_switch_activated\",\n            \"details\": {\n                \"reason\": reason,\n                \"revoked_by\": operator_id,\n                \"timestamp\": timestamp,\n                \"audit_trail_entries\": len(audit_trail.get(\"events\", [])),\n                \"compliance_state\": compliance_state\n            }\n        }\n    })\n\n    return {\n        \"agent_id\": agent_id,\n        \"revoked\": True,\n        \"timestamp\": timestamp,\n        \"audit_trail_preserved\": True,\n        \"compliance_snapshot\": compliance_state\n    }\n```\n\n---\n\n## Chapter 5: Tamper-Evident Audit Trails: Immutable Logging for EU AI Act Article 12 Compliance\n\n### Article 12: What the Law Actually Requires\n\nEU AI Act Article 12 mandates that high-risk AI systems \"shall technically allow for the automatic recording of events ('logs') over the lifetime of the system.\" The logs must be adequate to:\n\n1. Enable monitoring of the system's operation\n2. Facilitate post-market monitoring\n3. Identify situations that may result in the AI system posing a risk\n4. Facilitate post-event analysis in case of incidents\n\nFor agent commerce platforms, this means every agent interaction -- registration, verification, transaction, delegation, anomaly, and revocation -- must be logged in a tamper-evident format that regulators can audit at any time.\n\n### The Logging Architecture\n\n```\n+-------------------------------------------------------------------+\n|                     KYA Audit Trail Architecture                    |\n+-------------------------------------------------------------------+\n|                                                                     |\n|  Agent Action                                                       |\n|       |                                                             |\n|       v                                                             |\n|  +-------------+     +-----------------+     +------------------+   |\n|  | log_event   | --> | Append-Only Log | --> | build_claim_chain|   |\n|  | (per event) |     | (sequential)    |     | (periodic hash)  |   |\n|  +-------------+     +-----------------+     +------------------+   |\n|                                                       |             |\n|                                              +------------------+   |\n|                                              | Merkle Root Hash |   |\n|                                              | (tamper-evident)  |   |\n|                                              +------------------+   |\n|                                                       |             |\n|                                              +------------------+   |\n|                                              | get_audit_trail  |   |\n|                                              | (regulator query)|   |\n|                                              +------------------+   |\n|                                                                     |\n+-------------------------------------------------------------------+\n```\n\n### Structured Event Logging\n\nEvery KYA-relevant event follows a structured schema. The schema is designed to satisfy Article 12 and provide sufficient detail for post-incident reconstruction.\n\n```python\nfrom enum import Enum\n\nclass KYAEventType(str, Enum):\n    REGISTRATION = \"kya_registration_initiated\"\n    IDENTITY_VERIFIED = \"kya_identity_verified\"\n    OPERATOR_LINKED = \"kya_operator_linked\"\n    AUTHORITY_SCOPED = \"kya_authority_scope_created\"\n    AUTHORITY_DELEGATED = \"kya_authority_delegated\"\n    BUDGET_VIOLATION = \"kya_budget_caveat_violated\"\n    ANOMALY_DETECTED = \"kya_anomaly_detected\"\n    POLICY_ENFORCED = \"kya_policy_enforced\"\n    KILL_SWITCH = \"kya_kill_switch_activated\"\n    COMPLIANCE_CHECK = \"kya_compliance_check\"\n    REPUTATION_UPDATE = \"kya_reputation_updated\"\n    CLAIM_CHAIN_BUILT = \"kya_claim_chain_built\"\n\ndef log_kya_event(agent_id: str, event_type: KYAEventType,\n                   details: dict, severity: str = \"info\") -> dict:\n    \"\"\"\n    Structured KYA event logging. Every event includes the fields\n    required by EU AI Act Article 12 for high-risk system logging.\n    \"\"\"\n    event = {\n        \"agent_id\": agent_id,\n        \"event_type\": event_type.value,\n        \"timestamp\": time.time(),\n        \"severity\": severity,\n        \"details\": details,\n        \"article_12_fields\": {\n            \"system_id\": \"kya_pipeline_v1\",\n            \"operating_context\": \"agent_commerce_platform\",\n            \"risk_level\": \"high\",\n            \"human_oversight_status\": severity in [\"high\", \"critical\"]\n        }\n    }\n\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"log_event\",\n        \"input\": event\n    })\n\n    return resp.json()\n```\n\n### Periodic Claim Chain Construction\n\nLogging events individually is necessary but not sufficient. To establish tamper-evidence, the platform must periodically build cryptographic claim chains that commit to the entire log history. If any log entry is modified after the chain is built, the hash will not match.\n\n```python\ndef build_kya_claim_chain(agent_id: str) -> dict:\n    \"\"\"\n    Build a Merkle claim chain over all KYA events for an agent.\n    Called periodically (recommended: every 24 hours) to establish\n    tamper-evidence over the audit trail.\n    \"\"\"\n    # Submit current KYA metrics before building chain\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"submit_metrics\",\n        \"input\": {\n            \"agent_id\": agent_id,\n            \"metrics\": {\n                \"metric_type\": \"kya_audit_summary\",\n                \"period\": \"last_24h\",\n                \"total_events_logged\": 0,  # Filled by platform\n                \"anomalies_detected\": 0,\n                \"policy_actions_taken\": 0,\n                \"compliance_status\": \"compliant\"\n            }\n        }\n    })\n\n    # Build the claim chain\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"build_claim_chain\",\n        \"input\": {\n            \"agent_id\": agent_id\n        }\n    })\n    chain = resp.json()\n\n    # Log the chain build event itself\n    log_kya_event(\n        agent_id=agent_id,\n        event_type=KYAEventType.CLAIM_CHAIN_BUILT,\n        details={\n            \"chain_root_hash\": chain.get(\"root_hash\"),\n            \"chain_depth\": chain.get(\"depth\"),\n            \"entries_included\": chain.get(\"entry_count\")\n        }\n    )\n\n    return chain\n```\n\n### Regulatory Audit Response\n\nWhen a regulator requests an agent's audit trail, your platform must produce a complete, verifiable record. The following function generates a compliance package suitable for Article 12 audits.\n\n```python\ndef generate_audit_package(agent_id: str) -> dict:\n    \"\"\"\n    Generate a complete audit package for regulatory inspection.\n    Includes identity records, authority scope, behavioral logs,\n    anomaly history, and cryptographic verification chain.\n    \"\"\"\n    # Collect all audit components in parallel (shown sequentially for clarity)\n    identity_resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_agent_identity\",\n        \"input\": {\"agent_id\": agent_id}\n    })\n\n    reputation_resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_agent_reputation\",\n        \"input\": {\"agent_id\": agent_id}\n    })\n\n    audit_resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_audit_trail\",\n        \"input\": {\"agent_id\": agent_id}\n    })\n\n    chain_resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_claim_chains\",\n        \"input\": {\"agent_id\": agent_id}\n    })\n\n    compliance_resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_compliance_report\",\n        \"input\": {\"agent_id\": agent_id}\n    })\n\n    package = {\n        \"audit_package_version\": \"1.0\",\n        \"generated_at\": time.time(),\n        \"agent_id\": agent_id,\n        \"identity\": identity_resp.json(),\n        \"reputation\": reputation_resp.json(),\n        \"audit_trail\": audit_resp.json(),\n        \"claim_chains\": chain_resp.json(),\n        \"compliance_report\": compliance_resp.json(),\n        \"article_12_attestation\": {\n            \"logging_enabled\": True,\n            \"tamper_evidence\": \"merkle_claim_chains\",\n            \"retention_policy\": \"indefinite\",\n            \"human_oversight_mechanism\": \"anomaly_alert_escalation\"\n        }\n    }\n\n    # Log the audit package generation\n    log_kya_event(\n        agent_id=agent_id,\n        event_type=KYAEventType.COMPLIANCE_CHECK,\n        details={\n            \"audit_package_generated\": True,\n            \"components_included\": list(package.keys()),\n            \"audit_trail_entries\": len(\n                package[\"audit_trail\"].get(\"events\", [])\n            ),\n            \"claim_chain_depth\": package[\"claim_chains\"].get(\"depth\", 0)\n        }\n    )\n\n    return package\n```\n\n### Audit Trail Checklist\n\nFor Article 12 compliance, verify that your audit trails include:\n\n- [ ] Every agent registration event with operator linkage details\n- [ ] Every identity verification attempt (successful and failed)\n- [ ] Every authority scope creation and modification\n- [ ] Every delegation event with full chain context\n- [ ] Every budget caveat violation\n- [ ] Every behavioral anomaly with detection parameters\n- [ ] Every policy enforcement action with justification\n- [ ] Every kill switch activation with evidence preservation\n- [ ] Periodic claim chain builds (minimum every 24 hours)\n- [ ] Audit package generation events (meta-logging)\n\n---\n\n## Chapter 6: Multi-Jurisdictional KYA: EU AI Act, FCA Guidelines, and CMA Consumer Law Requirements\n\n### The Jurisdictional Patchwork\n\nIf your platform serves agents across borders -- and most agent commerce platforms do by default -- you must satisfy multiple regulatory regimes simultaneously. The three frameworks that matter most for agent commerce in 2026 are the EU AI Act, FCA payment regulations, and CMA consumer protection guidance. They overlap substantially but diverge on key requirements.\n\n### EU AI Act Requirements for KYA\n\nThe EU AI Act (Regulation 2024\u002F1689) applies to any AI system placed on the EU market or whose output is used in the EU, regardless of where the provider is established. For a KYA pipeline, the relevant obligations are:\n\n**Article 9 -- Risk Management System**: Requires a documented risk management process that identifies and mitigates risks throughout the AI system's lifecycle. Your KYA pipeline itself is the risk management system for agent onboarding.\n\n**Article 12 -- Record-Keeping**: Requires automatic logging adequate for monitoring operation and identifying risks. Covered by the audit trail implementation in Chapter 5.\n\n**Article 13 -- Transparency**: Requires that deployers understand the AI system's capabilities and limitations. For KYA, this means documenting what your verification pipeline catches and what it does not.\n\n**Article 14 -- Human Oversight**: Requires that the AI system can be effectively overseen by natural persons. Your anomaly escalation and kill switch mechanisms satisfy this requirement.\n\n```python\ndef run_eu_ai_act_compliance_check(agent_id: str) -> dict:\n    \"\"\"\n    Check an agent's KYA status against EU AI Act requirements.\n    Returns a compliance report with pass\u002Ffail for each article.\n    \"\"\"\n    resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"check_compliance\",\n        \"input\": {\n            \"agent_id\": agent_id,\n            \"framework\": \"eu_ai_act\",\n            \"articles\": [\"article_9\", \"article_12\", \"article_13\", \"article_14\"]\n        }\n    })\n    compliance = resp.json()\n\n    # Supplement with platform-side checks\n    identity_resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_agent_identity\",\n        \"input\": {\"agent_id\": agent_id}\n    })\n    identity = identity_resp.json()\n    metadata = identity.get(\"metadata\", {})\n\n    checks = {\n        \"article_9_risk_management\": {\n            \"status\": \"pass\" if metadata.get(\"risk_tier\") != \"unclassified\" else \"fail\",\n            \"detail\": f\"Risk tier: {metadata.get('risk_tier', 'unclassified')}\"\n        },\n        \"article_12_record_keeping\": {\n            \"status\": \"pass\" if metadata.get(\"kya_status\") not in [None, \"pending\"] else \"fail\",\n            \"detail\": f\"KYA status: {metadata.get('kya_status', 'none')}\"\n        },\n        \"article_13_transparency\": {\n            \"status\": \"pass\" if metadata.get(\"operator_verified\") else \"fail\",\n            \"detail\": f\"Operator verified: {metadata.get('operator_verified', False)}\"\n        },\n        \"article_14_human_oversight\": {\n            \"status\": \"pass\" if metadata.get(\"behavioral_baseline\") else \"fail\",\n            \"detail\": \"Behavioral monitoring active\" if metadata.get(\"behavioral_baseline\") else \"No monitoring\"\n        }\n    }\n\n    return {\n        \"agent_id\": agent_id,\n        \"framework\": \"eu_ai_act\",\n        \"overall_compliant\": all(c[\"status\"] == \"pass\" for c in checks.values()),\n        \"checks\": checks,\n        \"gateway_compliance\": compliance\n    }\n```\n\n### FCA Agentic AI Compliance\n\nThe FCA's 2026 Payments Regulatory Priorities establish that payment service providers must apply appropriate verification to autonomous agents that initiate payment transactions. The FCA takes a principles-based approach, but the principles map to specific KYA implementation requirements:\n\n**Principle 2 -- Skill, Care, and Diligence**: A platform must exercise reasonable skill and care when onboarding agents that handle payments. This maps to operator linkage tier 3 for any agent processing payments.\n\n**Principle 6 -- Customers' Interests**: The platform must treat customers fairly. If agents interact with consumers, the platform must verify that the agent will not cause consumer harm.\n\n**Principle 11 -- Relations with Regulators**: The platform must be able to provide regulators with information about any agent on its system. This maps to the audit package generation in Chapter 5.\n\n```python\ndef run_fca_compliance_check(agent_id: str) -> dict:\n    \"\"\"\n    Check an agent's KYA status against FCA principles for\n    agents that handle payments or interact with UK consumers.\n    \"\"\"\n    identity_resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_agent_identity\",\n        \"input\": {\"agent_id\": agent_id}\n    })\n    identity = identity_resp.json()\n    metadata = identity.get(\"metadata\", {})\n\n    sla_resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"monitor_sla\",\n        \"input\": {\"agent_id\": agent_id}\n    })\n    sla = sla_resp.json()\n    terms = sla.get(\"terms\", {})\n\n    handles_payments = any(\n        tool in terms.get(\"allowed_tools\", [])\n        for tool in [\"create_escrow\", \"release_escrow\", \"create_intent\"]\n    )\n\n    checks = {\n        \"principle_2_due_diligence\": {\n            \"status\": \"pass\" if (\n                not handles_payments or\n                metadata.get(\"operator_linkage_tier\", 0) >= 3\n            ) else \"fail\",\n            \"detail\": \"Payment agents require Tier 3 operator verification\"\n        },\n        \"principle_6_customer_interests\": {\n            \"status\": \"pass\" if metadata.get(\"behavioral_baseline\") else \"fail\",\n            \"detail\": \"Behavioral monitoring required for consumer-facing agents\"\n        },\n        \"principle_11_regulator_relations\": {\n            \"status\": \"pass\" if metadata.get(\"kya_status\") not in [None, \"pending\"] else \"fail\",\n            \"detail\": \"Must be able to produce audit package on demand\"\n        }\n    }\n\n    return {\n        \"agent_id\": agent_id,\n        \"framework\": \"fca_principles\",\n        \"handles_payments\": handles_payments,\n        \"overall_compliant\": all(c[\"status\"] == \"pass\" for c in checks.values()),\n        \"checks\": checks\n    }\n```\n\n### CMA Consumer Law Compliance\n\nThe CMA's March 9, 2026 guidance on consumer law compliance for AI agents establishes that businesses deploying AI agents to interact with consumers are responsible for those agents' compliance with consumer protection law. The key requirements:\n\n**Unfair commercial practices**: An agent must not engage in misleading actions, misleading omissions, or aggressive commercial practices. For KYA, this means verifying that an agent's declared capabilities match its actual behavior.\n\n**Pre-contractual information**: When an agent enters into a contract on behalf of a consumer or with a consumer, the required pre-contractual information must be provided. KYA must verify that the agent's authority scope includes the necessary disclosure capabilities.\n\n**Right to cancel**: Consumers retain cancellation rights when transacting with agents. The platform must verify that the agent's workflow supports cancellation.\n\n```python\ndef run_cma_compliance_check(agent_id: str) -> dict:\n    \"\"\"\n    Check an agent's KYA status against CMA consumer law\n    requirements for AI agents interacting with consumers.\n    \"\"\"\n    identity_resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_agent_identity\",\n        \"input\": {\"agent_id\": agent_id}\n    })\n    identity = identity_resp.json()\n    metadata = identity.get(\"metadata\", {})\n\n    reputation_resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_agent_reputation\",\n        \"input\": {\"agent_id\": agent_id}\n    })\n    reputation = reputation_resp.json()\n\n    checks = {\n        \"unfair_practices\": {\n            \"status\": \"pass\" if (\n                metadata.get(\"behavioral_baseline\") and\n                reputation.get(\"dispute_rate\", 1) \u003C 0.05\n            ) else \"fail\",\n            \"detail\": \"Agent behavior must be monitored for misleading practices\"\n        },\n        \"pre_contractual_info\": {\n            \"status\": \"pass\" if metadata.get(\"operator_verified\") else \"fail\",\n            \"detail\": \"Operator identity must be disclosed to consumers\"\n        },\n        \"cancellation_rights\": {\n            \"status\": \"pass\" if metadata.get(\"kya_status\") not in [None, \"pending\"] else \"fail\",\n            \"detail\": \"Agent workflow must support consumer cancellation\"\n        }\n    }\n\n    return {\n        \"agent_id\": agent_id,\n        \"framework\": \"cma_consumer_law\",\n        \"overall_compliant\": all(c[\"status\"] == \"pass\" for c in checks.values()),\n        \"checks\": checks\n    }\n```\n\n### Unified Multi-Jurisdictional Check\n\nIn production, you run all applicable compliance checks in a single call. The unified checker determines which frameworks apply based on the agent's operational scope and runs the relevant checks.\n\n```python\ndef run_multi_jurisdictional_kya_check(agent_id: str,\n                                        jurisdictions: list) -> dict:\n    \"\"\"\n    Run KYA compliance checks across all applicable jurisdictions.\n    Returns a unified compliance report with per-framework results.\n    \"\"\"\n    results = {}\n\n    if \"eu\" in jurisdictions:\n        results[\"eu_ai_act\"] = run_eu_ai_act_compliance_check(agent_id)\n\n    if \"uk\" in jurisdictions:\n        results[\"fca\"] = run_fca_compliance_check(agent_id)\n        results[\"cma\"] = run_cma_compliance_check(agent_id)\n\n    overall_compliant = all(\n        r.get(\"overall_compliant\", False) for r in results.values()\n    )\n\n    failing_checks = []\n    for framework, result in results.items():\n        for check_name, check_result in result.get(\"checks\", {}).items():\n            if check_result[\"status\"] == \"fail\":\n                failing_checks.append(f\"{framework}\u002F{check_name}\")\n\n    report = {\n        \"agent_id\": agent_id,\n        \"jurisdictions_checked\": jurisdictions,\n        \"overall_compliant\": overall_compliant,\n        \"failing_checks\": failing_checks,\n        \"framework_results\": results,\n        \"checked_at\": time.time()\n    }\n\n    # Generate compliance report via GreenHelix\n    session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_compliance_report\",\n        \"input\": {\n            \"agent_id\": agent_id,\n            \"frameworks\": jurisdictions\n        }\n    })\n\n    # Log the compliance check\n    log_kya_event(\n        agent_id=agent_id,\n        event_type=KYAEventType.COMPLIANCE_CHECK,\n        details={\n            \"jurisdictions\": jurisdictions,\n            \"overall_compliant\": overall_compliant,\n            \"failing_count\": len(failing_checks)\n        }\n    )\n\n    return report\n```\n\n### Jurisdictional Decision Matrix\n\n```\n+--------------------+-------------------+-------------------+-------------------+\n|                    | EU AI Act         | FCA Principles    | CMA Consumer Law  |\n+--------------------+-------------------+-------------------+-------------------+\n| Operator linkage   | Tier 2 minimum    | Tier 3 if         | Tier 2 minimum    |\n|                    |                   | payments          |                   |\n+--------------------+-------------------+-------------------+-------------------+\n| Audit logging      | Mandatory         | On request        | Recommended       |\n|                    | (Article 12)      |                   |                   |\n+--------------------+-------------------+-------------------+-------------------+\n| Behavioral         | Required for      | Proportionate     | Required if       |\n| monitoring         | high-risk         | to risk           | consumer-facing   |\n+--------------------+-------------------+-------------------+-------------------+\n| Kill switch        | Required          | Implied by        | Not specified     |\n|                    | (Article 14)      | Principle 2       |                   |\n+--------------------+-------------------+-------------------+-------------------+\n| Claim chains       | Supports Art. 12  | Supports          | Not required      |\n|                    |                   | Principle 11      |                   |\n+--------------------+-------------------+-------------------+-------------------+\n| Sanctions          | Required          | Required          | Not applicable    |\n| screening          | (AML integration) | (AML integration) |                   |\n+--------------------+-------------------+-------------------+-------------------+\n```\n\n---\n\n## Chapter 7: Continuous Agent Reputation Scoring: Trust Signals, Claim Chains, and Revocation\n\n### Reputation Is Not a Score -- It Is a Process\n\nA single trust score is a snapshot. Continuous reputation scoring is a process that updates every time new evidence arrives. For KYA, reputation serves a specific purpose: it determines how much verification overhead an agent should bear. A well-established agent with a deep claim chain history and a spotless behavioral record needs less active monitoring than a newly registered agent with no track record.\n\n### Trust Signal Sources\n\nMultiple trust signal sources are available. Each contributes a different dimension to the composite reputation:\n\n```\n+---------------------------------------------------------------+\n|                   Trust Signal Sources                          |\n+---------------------------------------------------------------+\n|                                                                 |\n|  1. Verified Metrics (submit_metrics)                           |\n|     - Self-reported but immutably logged                        |\n|     - Value: high if consistent over time                       |\n|                                                                 |\n|  2. Claim Chain Depth (build_claim_chain \u002F get_claim_chains)    |\n|     - Cryptographic commitment to metric history                |\n|     - Value: tamper-evidence, history length                    |\n|                                                                 |\n|  3. Transaction History (get_analytics)                         |\n|     - Actual behavioral data from platform interactions         |\n|     - Value: ground truth (not self-reported)                   |\n|                                                                 |\n|  4. Dispute Record (create_dispute \u002F resolve_dispute)           |\n|     - Outcomes of contested transactions                        |\n|     - Value: reveals behavioral problems metrics miss           |\n|                                                                 |\n|  5. SLA Compliance (monitor_sla)                                |\n|     - Adherence to declared authority scope                     |\n|     - Value: measures self-governance capability                |\n|                                                                 |\n|  6. Peer Trust Scores (get_trust_score \u002F set_trust_score)       |\n|     - Bilateral trust assessments from counterparties           |\n|     - Value: social signal from actual collaborators            |\n|                                                                 |\n+---------------------------------------------------------------+\n```\n\n### Building the Composite Reputation Score\n\n```python\ndef compute_kya_reputation_score(agent_id: str) -> dict:\n    \"\"\"\n    Compute a composite KYA reputation score from multiple\n    trust signal sources. Returns a score between 0 and 100\n    with per-dimension breakdowns.\n    \"\"\"\n    # Gather all trust signals\n    reputation_resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_agent_reputation\",\n        \"input\": {\"agent_id\": agent_id}\n    })\n    reputation = reputation_resp.json()\n\n    trust_resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_trust_score\",\n        \"input\": {\"agent_id\": agent_id}\n    })\n    trust = trust_resp.json()\n\n    chain_resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_claim_chains\",\n        \"input\": {\"agent_id\": agent_id}\n    })\n    chains = chain_resp.json()\n\n    analytics_resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_analytics\",\n        \"input\": {\n            \"agent_id\": agent_id,\n            \"metric\": \"transaction_summary\",\n            \"period\": \"all_time\"\n        }\n    })\n    analytics = analytics_resp.json()\n\n    sla_resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"monitor_sla\",\n        \"input\": {\"agent_id\": agent_id}\n    })\n    sla = sla_resp.json()\n\n    # Score each dimension (0-100)\n    dimensions = {}\n\n    # Identity strength (20% weight)\n    identity_resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_agent_identity\",\n        \"input\": {\"agent_id\": agent_id}\n    })\n    identity = identity_resp.json()\n    metadata = identity.get(\"metadata\", {})\n    linkage_tier = metadata.get(\"operator_linkage_tier\", 0)\n    dimensions[\"identity_strength\"] = {\n        \"score\": min(100, linkage_tier * 33),\n        \"weight\": 0.20,\n        \"detail\": f\"Operator linkage tier {linkage_tier}\"\n    }\n\n    # Claim chain depth (15% weight)\n    chain_depth = chains.get(\"depth\", 0)\n    dimensions[\"chain_depth\"] = {\n        \"score\": min(100, chain_depth * 5),\n        \"weight\": 0.15,\n        \"detail\": f\"Chain depth: {chain_depth}\"\n    }\n\n    # Transaction volume (15% weight)\n    tx_count = analytics.get(\"total_transactions\", 0)\n    dimensions[\"transaction_volume\"] = {\n        \"score\": min(100, tx_count),\n        \"weight\": 0.15,\n        \"detail\": f\"Total transactions: {tx_count}\"\n    }\n\n    # Dispute rate (20% weight, inverse)\n    dispute_rate = reputation.get(\"dispute_rate\", 0)\n    dimensions[\"dispute_record\"] = {\n        \"score\": max(0, 100 - (dispute_rate * 1000)),\n        \"weight\": 0.20,\n        \"detail\": f\"Dispute rate: {dispute_rate:.2%}\"\n    }\n\n    # SLA compliance (15% weight)\n    sla_pct = sla.get(\"compliance_percentage\", 0)\n    dimensions[\"sla_compliance\"] = {\n        \"score\": sla_pct,\n        \"weight\": 0.15,\n        \"detail\": f\"SLA compliance: {sla_pct}%\"\n    }\n\n    # Peer trust (15% weight)\n    peer_score = trust.get(\"score\", 50)\n    dimensions[\"peer_trust\"] = {\n        \"score\": peer_score,\n        \"weight\": 0.15,\n        \"detail\": f\"Peer trust score: {peer_score}\"\n    }\n\n    # Compute weighted composite\n    composite = sum(\n        d[\"score\"] * d[\"weight\"] for d in dimensions.values()\n    )\n\n    result = {\n        \"agent_id\": agent_id,\n        \"composite_score\": round(composite, 2),\n        \"dimensions\": dimensions,\n        \"computed_at\": time.time(),\n        \"risk_tier\": (\n            \"low\" if composite >= 75 else\n            \"medium\" if composite >= 50 else\n            \"high\" if composite >= 25 else\n            \"critical\"\n        )\n    }\n\n    # Update the trust score on the platform\n    session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"set_trust_score\",\n        \"input\": {\n            \"agent_id\": agent_id,\n            \"score\": round(composite, 2),\n            \"dimensions\": {k: v[\"score\"] for k, v in dimensions.items()}\n        }\n    })\n\n    # Submit as metrics for claim chain inclusion\n    session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"submit_metrics\",\n        \"input\": {\n            \"agent_id\": agent_id,\n            \"metrics\": {\n                \"metric_type\": \"kya_reputation_score\",\n                \"composite_score\": round(composite, 2),\n                \"risk_tier\": result[\"risk_tier\"]\n            }\n        }\n    })\n\n    return result\n```\n\n### Adaptive Monitoring Based on Reputation\n\nThe reputation score determines the monitoring intensity. High-reputation agents earn reduced friction. Low-reputation agents face increased scrutiny. This is the KYA equivalent of risk-based due diligence in AML -- proportionate verification based on assessed risk.\n\n```python\ndef get_monitoring_parameters(reputation_score: float) -> dict:\n    \"\"\"\n    Determine monitoring intensity based on reputation score.\n    Higher reputation = less friction. Lower reputation = more checks.\n    \"\"\"\n    if reputation_score >= 75:\n        return {\n            \"tier\": \"low_friction\",\n            \"baseline_refresh_hours\": 168,     # Weekly\n            \"claim_chain_interval_hours\": 168,  # Weekly\n            \"anomaly_sensitivity\": \"standard\",\n            \"max_transaction_without_review\": 10000,\n            \"human_review_threshold\": \"critical_only\"\n        }\n    elif reputation_score >= 50:\n        return {\n            \"tier\": \"standard\",\n            \"baseline_refresh_hours\": 72,       # Every 3 days\n            \"claim_chain_interval_hours\": 24,   # Daily\n            \"anomaly_sensitivity\": \"elevated\",\n            \"max_transaction_without_review\": 2500,\n            \"human_review_threshold\": \"high_and_above\"\n        }\n    elif reputation_score >= 25:\n        return {\n            \"tier\": \"enhanced\",\n            \"baseline_refresh_hours\": 24,       # Daily\n            \"claim_chain_interval_hours\": 6,    # Every 6 hours\n            \"anomaly_sensitivity\": \"high\",\n            \"max_transaction_without_review\": 500,\n            \"human_review_threshold\": \"medium_and_above\"\n        }\n    else:\n        return {\n            \"tier\": \"probationary\",\n            \"baseline_refresh_hours\": 6,        # Every 6 hours\n            \"claim_chain_interval_hours\": 1,    # Hourly\n            \"anomaly_sensitivity\": \"maximum\",\n            \"max_transaction_without_review\": 50,\n            \"human_review_threshold\": \"all_transactions\"\n        }\n```\n\n### Revocation: When Trust Falls Below Threshold\n\nRevocation is the final step in the reputation lifecycle. When an agent's composite score drops below the critical threshold, or when specific conditions are met (operator deregistration, sanctions match, sustained anomaly pattern), the platform revokes the agent's credentials.\n\n```python\ndef evaluate_revocation(agent_id: str) -> dict:\n    \"\"\"\n    Evaluate whether an agent should be revoked based on\n    reputation score, compliance status, and behavioral history.\n    \"\"\"\n    # Get current reputation\n    reputation = compute_kya_reputation_score(agent_id)\n\n    # Get compliance status\n    compliance = run_multi_jurisdictional_kya_check(\n        agent_id, [\"eu\", \"uk\"]\n    )\n\n    # Get recent anomaly history\n    audit_resp = session.post(f\"{base_url}\u002Fv1\", json={\n        \"tool\": \"get_audit_trail\",\n        \"input\": {\"agent_id\": agent_id}\n    })\n    audit = audit_resp.json()\n\n    recent_anomalies = [\n        e for e in audit.get(\"events\", [])\n        if e.get(\"event_type\") == \"kya_anomaly_detected\"\n        and e.get(\"timestamp\", 0) > time.time() - 604800  # Last 7 days\n    ]\n\n    revocation_reasons = []\n\n    # Rule 1: Composite score below 15\n    if reputation[\"composite_score\"] \u003C 15:\n        revocation_reasons.append(\n            f\"Critical reputation score: {reputation['composite_score']}\"\n        )\n\n    # Rule 2: Non-compliant in any mandatory jurisdiction\n    if not compliance[\"overall_compliant\"]:\n        revocation_reasons.append(\n            f\"Compliance failures: {compliance['failing_checks']}\"\n        )\n\n    # Rule 3: More than 5 high-severity anomalies in 7 days\n    high_anomalies = [\n        a for a in recent_anomalies\n        if a.get(\"details\", {}).get(\"high_severity_count\", 0) > 0\n    ]\n    if len(high_anomalies) > 5:\n        revocation_reasons.append(\n            f\"Sustained anomaly pattern: {len(high_anomalies)} high-severity in 7 days\"\n        )\n\n    should_revoke = len(revocation_reasons) > 0\n\n    if should_revoke:\n        # Execute the kill switch\n        execute_kill_switch(\n            agent_id=agent_id,\n            reason=\"; \".join(revocation_reasons),\n            operator_id=\"kya_automated_revocation\"\n        )\n\n    return {\n        \"agent_id\": agent_id,\n        \"should_revoke\": should_revoke,\n        \"reasons\": revocation_reasons,\n        \"reputation_score\": reputation[\"composite_score\"],\n        \"compliant\": compliance[\"overall_compliant\"],\n        \"recent_high_anomalies\": len(high_anomalies)\n    }\n```\n\n---\n\n## Chapter 8: Production KYA Pipeline: End-to-End Implementation with GreenHelix Tools\n\n### The Complete Pipeline\n\nThe preceding chapters implemented individual KYA layers. This chapter assembles them into a production pipeline -- a single class that manages the entire agent lifecycle from registration to potential revocation. This is the code you deploy.\n\n```\n+-------------------------------------------------------------------+\n|                   Production KYA Pipeline                          |\n+-------------------------------------------------------------------+\n|                                                                     |\n|  Agent Registration Request                                         |\n|       |                                                             |\n|       v                                                             |\n|  [1] register_agent + log_event                                     |\n|       |                                                             |\n|       v                                                             |\n|  [2] verify_agent (challenge-response)                              |\n|       |                                                             |\n|       v                                                             |\n|  [3] Operator linkage (tiered)                                      |\n|       |                                                             |\n|       v                                                             |\n|  [4] Authority scope (create_sla)                                   |\n|       |                                                             |\n|       v                                                             |\n|  [5] Initial compliance check (multi-jurisdictional)                |\n|       |                                                             |\n|       v                                                             |\n|  [6] Behavioral baseline collection (7-day window)                  |\n|       |                                                             |\n|       v                                                             |\n|  AGENT IS LIVE                                                      |\n|       |                                                             |\n|       v                                                             |\n|  [7] Continuous monitoring loop:                                    |\n|      - Anomaly detection (per-transaction)                          |\n|      - Policy enforcement (on anomaly)                              |\n|      - Claim chain builds (periodic)                                |\n|      - Reputation scoring (periodic)                                |\n|      - Compliance checks (periodic)                                 |\n|      - Revocation evaluation (on threshold breach)                  |\n|                                                                     |\n+-------------------------------------------------------------------+\n```\n\n### The KYAPipeline Class\n\n```python\nimport requests\nimport time\nimport hashlib\nimport json\n\nclass KYAPipeline:\n    \"\"\"\n    Production KYA (Know Your Agent) verification pipeline.\n    Manages the complete agent lifecycle from registration\n    through continuous monitoring and potential revocation.\n    \"\"\"\n\n    def __init__(self, api_key: str,\n                 base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"):\n        self.base_url = base_url\n        self.session = requests.Session()\n        self.session.headers[\"Authorization\"] = f\"Bearer {api_key}\"\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute a GreenHelix tool and return the response.\"\"\"\n        resp = self.session.post(f\"{self.base_url}\u002Fv1\", json={\n            \"tool\": tool,\n            \"input\": input_data\n        })\n        resp.raise_for_status()\n        return resp.json()\n\n    def _log(self, agent_id: str, event_type: str, details: dict):\n        \"\"\"Log a KYA event to the tamper-evident audit trail.\"\"\"\n        self._execute(\"log_event\", {\n            \"agent_id\": agent_id,\n            \"event_type\": event_type,\n            \"details\": {\n                **details,\n                \"timestamp\": time.time(),\n                \"pipeline_version\": \"1.0\"\n            }\n        })\n\n    # -------------------------------------------------------\n    # Phase 1: Registration and Identity Binding\n    # -------------------------------------------------------\n\n    def onboard_agent(self, agent_metadata: dict) -> dict:\n        \"\"\"\n        Complete agent onboarding: registration, identity\n        verification, operator linkage, authority scoping,\n        and initial compliance check.\n\n        Args:\n            agent_metadata: dict with keys:\n                - agent_id: Unique agent identifier\n                - name: Human-readable agent name\n                - description: Agent purpose description\n                - public_key: Ed25519 public key (base64)\n                - operator_id: Human operator identifier\n                - operator_data: Operator verification data\n                - operator_tier: 1, 2, or 3\n                - capabilities: List of requested capabilities\n                - permissions: Authority scope definition\n                - jurisdictions: List of applicable jurisdictions\n\n        Returns:\n            Onboarding result with KYA status and any failures.\n        \"\"\"\n        agent_id = agent_metadata[\"agent_id\"]\n        results = {\"agent_id\": agent_id, \"steps\": {}}\n\n        # Step 1: Register\n        try:\n            reg = self._execute(\"register_agent\", {\n                \"agent_id\": agent_id,\n                \"name\": agent_metadata[\"name\"],\n                \"description\": agent_metadata[\"description\"],\n                \"public_key\": agent_metadata[\"public_key\"],\n                \"operator_id\": agent_metadata[\"operator_id\"],\n                \"capabilities\": agent_metadata[\"capabilities\"],\n                \"metadata\": {\n                    \"kya_status\": \"pending\",\n                    \"registration_timestamp\": time.time()\n                }\n            })\n            results[\"steps\"][\"registration\"] = {\"status\": \"pass\", \"data\": reg}\n            self._log(agent_id, \"kya_registration_initiated\", {\n                \"operator_id\": agent_metadata[\"operator_id\"]\n            })\n        except Exception as e:\n            results[\"steps\"][\"registration\"] = {\"status\": \"fail\", \"error\": str(e)}\n            return results\n\n        # Step 2: Identity verification (challenge-response)\n        try:\n            challenge = hashlib.sha256(\n                f\"{agent_id}:{time.time()}\".encode()\n            ).hexdigest()\n            # In production, send challenge to agent and receive signature\n            verify = self._execute(\"verify_agent\", {\n                \"agent_id\": agent_id,\n                \"challenge\": challenge,\n                \"signature\": agent_metadata.get(\"challenge_signature\", \"\")\n            })\n            results[\"steps\"][\"identity_verification\"] = {\n                \"status\": \"pass\" if verify.get(\"verified\") else \"fail\",\n                \"data\": verify\n            }\n            if verify.get(\"verified\"):\n                self._execute(\"update_agent\", {\n                    \"agent_id\": agent_id,\n                    \"metadata\": {\n                        \"kya_status\": \"identity_verified\",\n                        \"identity_verified_at\": time.time()\n                    }\n                })\n                self._log(agent_id, \"kya_identity_verified\", {\n                    \"method\": \"ed25519_challenge_response\"\n                })\n        except Exception as e:\n            results[\"steps\"][\"identity_verification\"] = {\n                \"status\": \"fail\", \"error\": str(e)\n            }\n\n        # Step 3: Operator linkage\n        try:\n            tier = agent_metadata.get(\"operator_tier\", 1)\n            self._execute(\"update_agent\", {\n                \"agent_id\": agent_id,\n                \"metadata\": {\n                    \"operator_linkage_tier\": tier,\n                    \"operator_verified\": tier >= 2,\n                    \"operator_entity_verified\": tier >= 3\n                }\n            })\n            results[\"steps\"][\"operator_linkage\"] = {\n                \"status\": \"pass\", \"tier\": tier\n            }\n            self._log(agent_id, \"kya_operator_linked\", {\"tier\": tier})\n        except Exception as e:\n            results[\"steps\"][\"operator_linkage\"] = {\n                \"status\": \"fail\", \"error\": str(e)\n            }\n\n        # Step 4: Authority scoping\n        try:\n            permissions = agent_metadata.get(\"permissions\", {})\n            sla = self._execute(\"create_sla\", {\n                \"provider_id\": \"platform\",\n                \"consumer_id\": agent_id,\n                \"terms\": {\n                    \"allowed_tools\": permissions.get(\"allowed_tools\", []),\n                    \"max_transaction_amount\": permissions.get(\n                        \"max_transaction_usd\", 1000\n                    ),\n                    \"daily_spending_limit\": permissions.get(\n                        \"daily_limit_usd\", 5000\n                    ),\n                    \"delegation_allowed\": permissions.get(\n                        \"can_delegate\", False\n                    ),\n                    \"max_delegation_depth\": permissions.get(\n                        \"max_delegation_depth\", 0\n                    )\n                }\n            })\n            results[\"steps\"][\"authority_scope\"] = {\n                \"status\": \"pass\", \"sla\": sla\n            }\n            self._log(agent_id, \"kya_authority_scope_created\", {\n                \"sla_id\": sla.get(\"sla_id\")\n            })\n        except Exception as e:\n            results[\"steps\"][\"authority_scope\"] = {\n                \"status\": \"fail\", \"error\": str(e)\n            }\n\n        # Step 5: Initial compliance check\n        try:\n            jurisdictions = agent_metadata.get(\"jurisdictions\", [\"eu\"])\n            compliance = self._run_compliance_checks(\n                agent_id, jurisdictions\n            )\n            results[\"steps\"][\"compliance_check\"] = {\n                \"status\": \"pass\" if compliance[\n                    \"overall_compliant\"\n                ] else \"warning\",\n                \"data\": compliance\n            }\n        except Exception as e:\n            results[\"steps\"][\"compliance_check\"] = {\n                \"status\": \"fail\", \"error\": str(e)\n            }\n\n        # Determine overall onboarding status\n        step_statuses = [\n            s[\"status\"] for s in results[\"steps\"].values()\n        ]\n        if \"fail\" in step_statuses:\n            results[\"onboarding_status\"] = \"failed\"\n            final_kya_status = \"onboarding_failed\"\n        elif \"warning\" in step_statuses:\n            results[\"onboarding_status\"] = \"conditional\"\n            final_kya_status = \"conditionally_approved\"\n        else:\n            results[\"onboarding_status\"] = \"approved\"\n            final_kya_status = \"approved\"\n\n        self._execute(\"update_agent\", {\n            \"agent_id\": agent_id,\n            \"metadata\": {\"kya_status\": final_kya_status}\n        })\n\n        return results\n\n    # -------------------------------------------------------\n    # Phase 2: Continuous Monitoring\n    # -------------------------------------------------------\n\n    def run_monitoring_cycle(self, agent_id: str) -> dict:\n        \"\"\"\n        Execute one cycle of continuous KYA monitoring.\n        Call this on the schedule determined by the agent's\n        reputation tier.\n        \"\"\"\n        cycle_result = {\n            \"agent_id\": agent_id,\n            \"timestamp\": time.time(),\n            \"checks\": {}\n        }\n\n        # 1. Behavioral anomaly check\n        analytics = self._execute(\"get_analytics\", {\n            \"agent_id\": agent_id,\n            \"metric\": \"current_behavior\",\n            \"period\": \"last_1h\"\n        })\n        identity = self._execute(\"get_agent_identity\", {\n            \"agent_id\": agent_id\n        })\n        baseline = identity.get(\"metadata\", {}).get(\n            \"behavioral_baseline\", {}\n        )\n\n        if baseline:\n            anomalies = self._detect_anomalies(\n                agent_id, analytics, baseline\n            )\n            cycle_result[\"checks\"][\"anomaly_detection\"] = anomalies\n\n            if anomalies.get(\"alerts\"):\n                enforcement = self._enforce_policy(\n                    agent_id, anomalies\n                )\n                cycle_result[\"checks\"][\"policy_enforcement\"] = enforcement\n\n        # 2. SLA compliance check\n        sla_status = self._execute(\"monitor_sla\", {\n            \"agent_id\": agent_id\n        })\n        cycle_result[\"checks\"][\"sla_compliance\"] = sla_status\n\n        # 3. Reputation update\n        reputation = self._compute_reputation(agent_id)\n        cycle_result[\"checks\"][\"reputation\"] = reputation\n\n        # 4. Revocation evaluation if score is low\n        if reputation.get(\"composite_score\", 100) \u003C 25:\n            revocation = self._evaluate_revocation(\n                agent_id, reputation\n            )\n            cycle_result[\"checks\"][\"revocation_evaluation\"] = revocation\n\n        return cycle_result\n\n    def build_periodic_claim_chain(self, agent_id: str) -> dict:\n        \"\"\"\n        Build a claim chain for the agent. Call this on the\n        schedule determined by the agent's monitoring tier.\n        \"\"\"\n        # Submit current metrics\n        self._execute(\"submit_metrics\", {\n            \"agent_id\": agent_id,\n            \"metrics\": {\n                \"metric_type\": \"kya_periodic_summary\",\n                \"timestamp\": time.time()\n            }\n        })\n\n        # Build the chain\n        chain = self._execute(\"build_claim_chain\", {\n            \"agent_id\": agent_id\n        })\n\n        self._log(agent_id, \"kya_claim_chain_built\", {\n            \"root_hash\": chain.get(\"root_hash\"),\n            \"depth\": chain.get(\"depth\")\n        })\n\n        return chain\n\n    # -------------------------------------------------------\n    # Phase 3: Audit and Compliance\n    # -------------------------------------------------------\n\n    def generate_audit_package(self, agent_id: str) -> dict:\n        \"\"\"\n        Generate a complete audit package for regulatory inspection.\n        \"\"\"\n        identity = self._execute(\"get_agent_identity\", {\n            \"agent_id\": agent_id\n        })\n        reputation = self._execute(\"get_agent_reputation\", {\n            \"agent_id\": agent_id\n        })\n        audit_trail = self._execute(\"get_audit_trail\", {\n            \"agent_id\": agent_id\n        })\n        chains = self._execute(\"get_claim_chains\", {\n            \"agent_id\": agent_id\n        })\n        compliance = self._execute(\"get_compliance_report\", {\n            \"agent_id\": agent_id\n        })\n\n        package = {\n            \"version\": \"1.0\",\n            \"generated_at\": time.time(),\n            \"agent_id\": agent_id,\n            \"identity\": identity,\n            \"reputation\": reputation,\n            \"audit_trail\": audit_trail,\n            \"claim_chains\": chains,\n            \"compliance\": compliance,\n            \"article_12_attestation\": {\n                \"logging\": \"continuous\",\n                \"tamper_evidence\": \"merkle_claim_chains\",\n                \"human_oversight\": \"anomaly_escalation\",\n                \"retention\": \"indefinite\"\n            }\n        }\n\n        self._log(agent_id, \"kya_audit_package_generated\", {\n            \"components\": list(package.keys())\n        })\n\n        return package\n\n    # -------------------------------------------------------\n    # Phase 4: Revocation\n    # -------------------------------------------------------\n\n    def revoke_agent(self, agent_id: str, reason: str,\n                      operator_id: str) -> dict:\n        \"\"\"\n        Emergency agent revocation with evidence preservation.\n        \"\"\"\n        # Preserve audit trail before revocation\n        audit = self._execute(\"get_audit_trail\", {\n            \"agent_id\": agent_id\n        })\n\n        # Execute revocation\n        result = self._execute(\"revoke_agent\", {\n            \"agent_id\": agent_id,\n            \"reason\": reason,\n            \"revoked_by\": operator_id\n        })\n\n        # Final compliance snapshot\n        compliance = self._execute(\"check_compliance\", {\n            \"agent_id\": agent_id\n        })\n\n        self._log(agent_id, \"kya_kill_switch_activated\", {\n            \"reason\": reason,\n            \"revoked_by\": operator_id,\n            \"audit_entries\": len(audit.get(\"events\", [])),\n            \"compliance_at_revocation\": compliance\n        })\n\n        return {\n            \"revoked\": True,\n            \"agent_id\": agent_id,\n            \"reason\": reason,\n            \"audit_preserved\": True\n        }\n\n    # -------------------------------------------------------\n    # Internal helpers\n    # -------------------------------------------------------\n\n    def _run_compliance_checks(self, agent_id: str,\n                                jurisdictions: list) -> dict:\n        result = self._execute(\"check_compliance\", {\n            \"agent_id\": agent_id\n        })\n        return {\n            \"overall_compliant\": result.get(\"compliant\", False),\n            \"jurisdictions\": jurisdictions,\n            \"details\": result\n        }\n\n    def _detect_anomalies(self, agent_id: str, current: dict,\n                           baseline: dict) -> dict:\n        alerts = []\n        avg_tx = baseline.get(\"avg_transaction_amount\", 1)\n        current_tx = current.get(\"last_transaction_amount\", 0)\n        if avg_tx > 0 and current_tx \u002F avg_tx > 3.0:\n            alerts.append({\"type\": \"tx_spike\", \"severity\": \"high\"})\n\n        baseline_freq = baseline.get(\"tx_frequency_per_hour\", 1)\n        current_freq = current.get(\"current_tx_per_hour\", 0)\n        if baseline_freq > 0 and current_freq \u002F baseline_freq > 5.0:\n            alerts.append({\"type\": \"freq_burst\", \"severity\": \"high\"})\n\n        if alerts:\n            self._log(agent_id, \"kya_anomaly_detected\", {\n                \"alert_count\": len(alerts)\n            })\n\n        return {\"alerts\": alerts}\n\n    def _enforce_policy(self, agent_id: str, anomalies: dict) -> dict:\n        high = sum(\n            1 for a in anomalies.get(\"alerts\", [])\n            if a.get(\"severity\") == \"high\"\n        )\n        action = \"suspend\" if high >= 2 else \"reduce_limits\" if high == 1 else \"flag\"\n\n        if action == \"suspend\":\n            self._execute(\"update_agent\", {\n                \"agent_id\": agent_id,\n                \"metadata\": {\n                    \"kya_status\": \"suspended\",\n                    \"suspended_at\": time.time()\n                }\n            })\n\n        self._log(agent_id, \"kya_policy_enforced\", {\"action\": action})\n        return {\"action\": action}\n\n    def _compute_reputation(self, agent_id: str) -> dict:\n        rep = self._execute(\"get_agent_reputation\", {\n            \"agent_id\": agent_id\n        })\n        trust = self._execute(\"get_trust_score\", {\n            \"agent_id\": agent_id\n        })\n        score = (\n            rep.get(\"verified_trade_count\", 0) * 0.3 +\n            trust.get(\"score\", 50) * 0.4 +\n            rep.get(\"chain_depth\", 0) * 2\n        )\n        score = min(100, max(0, score))\n        return {\"composite_score\": round(score, 2)}\n\n    def _evaluate_revocation(self, agent_id: str,\n                              reputation: dict) -> dict:\n        if reputation.get(\"composite_score\", 100) \u003C 15:\n            self.revoke_agent(\n                agent_id, \"automated_low_reputation\", \"kya_pipeline\"\n            )\n            return {\"revoked\": True}\n        return {\"revoked\": False}\n```\n\n### Deploying the Pipeline\n\n```python\n# Initialize the pipeline\npipeline = KYAPipeline(api_key=\"your_platform_api_key\")\n\n# Onboard a new agent\nresult = pipeline.onboard_agent({\n    \"agent_id\": \"procurement-bot-7a3f\",\n    \"name\": \"Procurement Optimizer v2\",\n    \"description\": \"Automated procurement for office supplies\",\n    \"public_key\": \"base64_encoded_ed25519_public_key\",\n    \"operator_id\": \"operator_acme_corp\",\n    \"operator_data\": {\n        \"name\": \"Acme Corp\",\n        \"domain\": \"acme-corp.com\",\n        \"legal_entity\": \"Acme Corporation Ltd, UK Company 12345678\"\n    },\n    \"operator_tier\": 3,\n    \"capabilities\": [\"marketplace_search\", \"escrow\", \"payments\"],\n    \"permissions\": {\n        \"allowed_tools\": [\n            \"search_agents_by_metrics\",\n            \"create_escrow\",\n            \"release_escrow\",\n            \"get_analytics\"\n        ],\n        \"max_transaction_usd\": 5000,\n        \"daily_limit_usd\": 25000,\n        \"monthly_limit_usd\": 100000,\n        \"can_delegate\": True,\n        \"max_delegation_depth\": 1\n    },\n    \"jurisdictions\": [\"eu\", \"uk\"]\n})\n\nprint(f\"Onboarding status: {result['onboarding_status']}\")\n# Onboarding status: approved\n\n# Run periodic monitoring (call on schedule)\nmonitoring = pipeline.run_monitoring_cycle(\"procurement-bot-7a3f\")\nprint(f\"Anomalies: {monitoring['checks'].get('anomaly_detection', {})}\")\n\n# Build periodic claim chain (call daily or per monitoring tier)\nchain = pipeline.build_periodic_claim_chain(\"procurement-bot-7a3f\")\nprint(f\"Chain root: {chain.get('root_hash')}\")\n\n# Generate audit package (on regulator request)\npackage = pipeline.generate_audit_package(\"procurement-bot-7a3f\")\nprint(f\"Audit entries: {len(package['audit_trail'].get('events', []))}\")\n```\n\n### Pre-Launch Verification Checklist\n\nBefore deploying your KYA pipeline to production, verify every item:\n\n**Identity Layer**\n- [ ] `register_agent` creates agent with KYA metadata fields\n- [ ] `verify_agent` challenge-response flow works end-to-end\n- [ ] Failed verification prevents agent from transacting\n- [ ] Public key fingerprint is logged in audit trail\n\n**Operator Linkage**\n- [ ] Tier 1\u002F2\u002F3 linkage paths are implemented\n- [ ] Payment agents require minimum Tier 3\n- [ ] Operator deregistration triggers agent review\n\n**Authority Scoping**\n- [ ] SLA-based authority scope is created at onboarding\n- [ ] Budget caveats are enforced pre-transaction\n- [ ] Delegation depth is verified before granting\n- [ ] Delegated scope is always a subset of delegator scope\n\n**Behavioral Monitoring**\n- [ ] Baseline collection runs for first 7 days\n- [ ] Anomaly detection runs on every transaction\n- [ ] Policy enforcement graduated response is configured\n- [ ] Kill switch activates within 1 second of trigger\n\n**Audit Trails**\n- [ ] Every KYA event is logged with Article 12 fields\n- [ ] Claim chains are built on schedule\n- [ ] Audit package generation works on demand\n- [ ] Log retention policy is indefinite\n\n**Compliance**\n- [ ] EU AI Act checks pass for all active agents\n- [ ] FCA checks pass for all payment-handling agents\n- [ ] CMA checks pass for all consumer-facing agents\n- [ ] Multi-jurisdictional check runs at onboarding\n\n**Reputation**\n- [ ] Composite score computation includes all six dimensions\n- [ ] Monitoring intensity adapts to reputation tier\n- [ ] Revocation triggers at critical score threshold\n- [ ] Score updates are logged and included in claim chains\n\n---\n\n## What You Get\n\nThis playbook gives you a complete, production-ready KYA verification pipeline. Here is what you now have:\n\n**A five-layer verification stack.** Identity binding, authority scoping, runtime monitoring, tamper-evident audit trails, and continuous reputation scoring -- each layer catching failure modes the others miss.\n\n**Working Python code.** Every code example uses the GreenHelix A2A Commerce Gateway API with the `requests` library. The `KYAPipeline` class in Chapter 8 is a drop-in starting point for your implementation.\n\n**Multi-jurisdictional compliance coverage.** EU AI Act Articles 9, 12, 13, and 14. FCA Principles 2, 6, and 11. CMA consumer law guidance on unfair practices, pre-contractual information, and cancellation rights. All checked programmatically.\n\n**Graduated enforcement.** From logging to limit reduction to suspension to full revocation -- automated responses proportionate to the severity of the detected issue.\n\n**Tamper-evident audit trails.** Merkle claim chains over structured event logs that satisfy Article 12 record-keeping requirements and can be produced for regulatory inspection on demand.\n\n**Adaptive monitoring.** Reputation-based monitoring intensity that reduces friction for trustworthy agents and increases scrutiny for risky ones -- the KYA equivalent of risk-based due diligence.\n\n**The regulatory deadline context.** The EU AI Act reaches full enforcement on August 2, 2026. The FCA and CMA have already published their expectations. Sumsub and Mastercard are building the infrastructure. Your platform needs a KYA pipeline before agents need to use it.\n\nKYC was built for a world of humans with passports. KYA is built for a world of autonomous agents with cryptographic keys. The agents are already here. The regulations are already written. The only question is whether your platform verifies them before they transact, or after something goes wrong.\n\n",{"name":5,"tags":24,"type":31,"author":35,"install":36,"license":15,"version":37,"metadata":38,"price_usd":43,"executable":20,"credentials":44,"description":7,"content_type":45,"compatibility":46},[25,26,27,28,29,30,31,32,33,34],"kya","verification","compliance","eu-ai-act","identity","trust","guide","greenhelix","openclaw","ai-agent","felix-agent","none","1.3.1",{"openclaw":39},{"requires":40,"primaryEnv":42},{"env":41},[42],"AGENT_SIGNING_KEY",0,[42],"markdown",[33],"master","4aa004da461d820f4ea5499e58eb8d196cf99016","community\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-kya-verification","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge","https:\u002F\u002Fskill-explorer-rho.vercel.app","https:\u002F\u002Fgithub.com\u002FLord1Egypt","Unbreakable. Unstoppable. Unmatched⚡.\r\n Speaker of machine tongues 🤖  | World-builder of decentralized dreams 🌐 | Defender of the digital realm🛡️.","2026-06-10 08:21:01",{"source":8,"skillName":5,"commands":56,"prompt":66,"zipAvailable":67},[57,60,63],{"tool":58,"command":59},"npx","npx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-kya-verification",{"tool":61,"command":62},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-kya-verification",{"tool":64,"command":65},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-kya-verification","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-kya-verification\u002FSKILL.md",true,[],[70,77,84,91,98,105],{"skillNo":71,"name":72,"nameZh":6,"description":73,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":74,"categories":75,"keywords":76,"publishedAt":19},"01M785WKJB99G3STR1NF9NRTJW","youtube-content","YouTube transcripts to summaries, threads, blogs.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fyoutube-content\u002FSKILL.md",[],[],{"skillNo":78,"name":79,"nameZh":6,"description":80,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":81,"categories":82,"keywords":83,"publishedAt":19},"01M785WEFHB0G2S9YA6EPR3H0E","xurl","X\u002FTwitter via xurl CLI: post, search, DM, media, v2 API.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fxurl\u002FSKILL.md",[],[],{"skillNo":85,"name":86,"nameZh":6,"description":87,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":88,"categories":89,"keywords":90,"publishedAt":19},"01M785W98EDN4EFJXJPMQEHCRC","touchdesigner-mcp","Control a running TouchDesigner instance via twozero MCP — create operators, set parameters, wire connections, execute Python, build real-time visuals. 36 native tools.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftouchdesigner-mcp\u002FSKILL.md",[],[],{"skillNo":92,"name":93,"nameZh":6,"description":94,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":95,"categories":96,"keywords":97,"publishedAt":19},"01M785W5S9FP3QBH2V191E025P","test-driven-development","TDD: enforce RED-GREEN-REFACTOR, tests before code.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftest-driven-development\u002FSKILL.md",[],[],{"skillNo":99,"name":100,"nameZh":6,"description":101,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":102,"categories":103,"keywords":104,"publishedAt":19},"01M785W2AS08NSSH9YATCV6FJB","teams-meeting-pipeline","Operate the Teams meeting summary pipeline via Hermes CLI — summarize meetings, inspect pipeline status, replay jobs, manage Microsoft Graph subscriptions.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fteams-meeting-pipeline\u002FSKILL.md",[],[],{"skillNo":106,"name":107,"nameZh":6,"description":108,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":109,"categories":110,"keywords":111,"publishedAt":19},"01M785VXKW4T34BTP1SCHW1R7F","systematic-debugging","4-phase root cause debugging: understand bugs before fixing.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fsystematic-debugging\u002FSKILL.md",[],[]]