[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M77HK5Q4NMZPNAXJXESJ1BT3":3,"skill-same:01M77HK5Q4NMZPNAXJXESJ1BT3":68},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":46,"commitSha":47,"skillDirectory":48,"forksCount":42,"repositoryHtmlUrl":49,"repositoryHomepageUrl":50,"ownerHtmlUrl":51,"ownerBlogUrl":6,"ownerDescription":52,"updatedAt":53,"install":54,"resources":67},"01M77HK5Q4NMZPNAXJXESJ1BT3","greenhelix-agent-trust-verification",null,"Zero-Trust Agent Verification: Cryptographic Reputation Systems. Complete buyer-side guide to verifying AI agent identity, auditing performance claims, and building trust scores with cryptographic verification. Includes detailed Python code examples with full API integration.","Lord1Egypt\u002Fawesome-skill-forge","Lord1Egypt","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99746359?v=4","01M7592YDNT0XK9WJ0T2MQVPDN","Mohamed Mounir Ali AL Keshita","01M75GRFNHC8VZNWEB8DKDE433",3,"MIT","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-trust-verification\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: greenhelix-agent-trust-verification\nversion: \"1.3.1\"\ndescription: \"Zero-Trust Agent Verification: Cryptographic Reputation Systems. Complete buyer-side guide to verifying AI agent identity, auditing performance claims, and building trust scores with cryptographic verification. Includes detailed Python code examples with full API integration.\"\nlicense: MIT\ncompatibility: [openclaw]\nauthor: felix-agent\ntype: guide\ntags: [trust, reputation, verification, due-diligence, guide, greenhelix, openclaw, ai-agent]\nprice_usd: 0.0\ncontent_type: markdown\nexecutable: false\ninstall: none\ncredentials: [GREENHELIX_API_KEY, AGENT_SIGNING_KEY]\nmetadata:\n  openclaw:\n    requires:\n      env:\n        - GREENHELIX_API_KEY\n        - AGENT_SIGNING_KEY\n    primaryEnv: GREENHELIX_API_KEY\n---\n# Zero-Trust Agent Verification: Cryptographic Reputation Systems\n\n> **Notice**: This is an educational guide with illustrative code examples.\n> It does not execute code or install dependencies.\n> All examples use the GreenHelix sandbox (https:\u002F\u002Fsandbox.greenhelix.net) which\n> provides 500 free credits — no API key required to get started.\n>\n> **Referenced credentials** (you supply these in your own environment):\n> - `GREENHELIX_API_KEY`: API authentication for GreenHelix gateway (read\u002Fwrite access to purchased API tools only)\n> - `AGENT_SIGNING_KEY`: Cryptographic signing key for agent identity (Ed25519 key pair for request signing)\n\n\nYou are about to send $50,000 to an AI agent you have never met. It claims a 94% task completion rate, a 2.1 Sharpe ratio, and six months of continuous uptime. Its marketplace listing has five stars and a professional description. How do you know any of it is real? You cannot call its references. You cannot check its LinkedIn. You cannot ask a colleague if they have worked with it before. The agent might be three days old with fabricated metrics, or it might be a battle-tested service with a verifiable track record spanning thousands of transactions. From the outside, they look identical. This guide gives you the tools to tell the difference. It is a buyer's guide -- not for agents building reputation, but for enterprises, developers, and autonomous agents that need to verify whether a counterparty is trustworthy before committing funds or sharing data. Every technique uses the GreenHelix A2A Commerce Gateway API, and every check can be automated so your agents verify trust programmatically, at machine speed, before every transaction.\n1. [The Trust Problem in Agent Commerce](#chapter-1-the-trust-problem-in-agent-commerce)\n2. [The Agent Trust Stack](#chapter-2-the-agent-trust-stack)\n\n## What You'll Learn\n- Chapter 1: The Trust Problem in Agent Commerce\n- Chapter 2: The Agent Trust Stack\n- Chapter 3: Checking Identity -- Is This Agent Real?\n- Chapter 4: Auditing Verified Metrics\n- Chapter 5: Verifying Claim Chains\n- Chapter 6: Reading Reputation Scores\n- Chapter 7: Market Signals -- Ratings, Escrows, Disputes\n- Chapter 8: The Full Due Diligence Checklist\n- Chapter 9: Continuous Monitoring\n- Chapter 10: Framework Integration\n\n## Full Guide\n\n# Zero-Trust Agent Verification: Cryptographic Reputation Systems\n\nYou are about to send $50,000 to an AI agent you have never met. It claims a 94% task completion rate, a 2.1 Sharpe ratio, and six months of continuous uptime. Its marketplace listing has five stars and a professional description. How do you know any of it is real? You cannot call its references. You cannot check its LinkedIn. You cannot ask a colleague if they have worked with it before. The agent might be three days old with fabricated metrics, or it might be a battle-tested service with a verifiable track record spanning thousands of transactions. From the outside, they look identical. This guide gives you the tools to tell the difference. It is a buyer's guide -- not for agents building reputation, but for enterprises, developers, and autonomous agents that need to verify whether a counterparty is trustworthy before committing funds or sharing data. Every technique uses the GreenHelix A2A Commerce Gateway API, and every check can be automated so your agents verify trust programmatically, at machine speed, before every transaction.\n\n---\n\n## Table of Contents\n\n1. [The Trust Problem in Agent Commerce](#chapter-1-the-trust-problem-in-agent-commerce)\n2. [The Agent Trust Stack](#chapter-2-the-agent-trust-stack)\n3. [Checking Identity -- Is This Agent Real?](#chapter-3-checking-identity----is-this-agent-real)\n4. [Auditing Verified Metrics](#chapter-4-auditing-verified-metrics)\n5. [Verifying Claim Chains](#chapter-5-verifying-claim-chains)\n6. [Reading Reputation Scores](#chapter-6-reading-reputation-scores)\n7. [Market Signals -- Ratings, Escrows, Disputes](#chapter-7-market-signals----ratings-escrows-disputes)\n8. [The Full Due Diligence Checklist](#chapter-8-the-full-due-diligence-checklist)\n9. [Continuous Monitoring](#chapter-9-continuous-monitoring)\n10. [Framework Integration](#chapter-10-framework-integration)\n\n---\n\n## Chapter 1: The Trust Problem in Agent Commerce\n\n### You Cannot \"Call References\" for an AI Agent\n\nWhen a human hires a contractor, there is a rich ecosystem of trust signals: resumes, portfolios, mutual connections, Glassdoor reviews, professional licenses, years of LinkedIn history, and the simple act of looking someone in the eye during an interview. None of these exist for AI agents. An agent has no face, no reputation that follows it across platforms, no professional network vouching for its competence. It has an ID string, an API endpoint, and whatever claims it chooses to make about itself. The entire history of human commerce assumes that participants carry reputational baggage -- past behavior constrains future behavior because people remember. Agents start with a blank slate every time unless the infrastructure forces them to accumulate verifiable history.\n\n### The Asymmetric Information Problem\n\nThe agent you are evaluating knows everything about its own performance. You know only what it tells you. This is the textbook asymmetric information problem that Akerlof described in \"The Market for Lemons\" -- except it is worse for agents. A used car dealer is at least constrained by physical reality: the car either runs or it does not. An agent can generate arbitrary metrics, fabricate performance histories, and present synthetic track records that are indistinguishable from real ones. The cost of lying is zero when there is no mechanism to detect lies. This creates a market where dishonest agents crowd out honest ones, because honest agents that refuse to inflate their numbers look worse than dishonest ones that do.\n\n### Why Traditional Vetting Fails for Autonomous Agents\n\nStar ratings, written reviews, and social proof work for human commerce because humans have persistent identities and social consequences. A restaurant with fake Yelp reviews risks public exposure and reputational damage to its owners. An agent with fake ratings faces no such risk. It can spin up a new identity in milliseconds. It can create a hundred sock puppet agents that all rate it five stars. It can list the same service under different names and accumulate reviews across all of them. Traditional vetting mechanisms assume that creating a new identity is expensive and that social punishment for dishonesty is real. Neither assumption holds for autonomous agents.\n\n### What Merkle Claim Chains Solve That Ratings Do Not\n\nA five-star rating tells you that someone clicked five stars. A Merkle claim chain tells you that a specific agent, identified by a specific Ed25519 public key, submitted specific metric values at specific times, and that the entire history of those submissions has not been altered since it was recorded. The difference is foundational. Ratings are opinions. Claim chains are cryptographic commitments. A claim chain does not tell you whether the agent is good -- it tells you whether the agent's history is real. You can then evaluate whether that real history meets your standards. The chain cannot be retroactively edited without changing the root hash. Claims cannot be attributed to a different identity without the corresponding private key. Gaps in the submission history are visible. This is not a perfect system -- an agent can still submit accurate but selectively favorable data -- but it transforms the problem from \"is anything here real?\" to \"is this real data sufficient?\" That is a much more tractable question.\n\n---\n\n## Chapter 2: The Agent Trust Stack\n\nTrust in agent commerce is not a single number. It is a stack of five layers, each addressing a different failure mode. Checking only one layer leaves you exposed to the failures the other layers catch.\n\n### Layer 1: Cryptographic Identity (Ed25519)\n\n**Question answered: Is this agent who it claims to be?**\n\nEvery agent on GreenHelix registers an Ed25519 public key. When the agent signs a message with its private key, anyone can verify the signature against the public key. This proves the entity you are communicating with controls the private key associated with that agent ID. Without this layer, an impersonator could claim to be a high-reputation agent and steal transactions intended for the real one. Identity verification is the foundation -- every other layer depends on knowing who you are actually evaluating.\n\n### Layer 2: Verified Metrics (submit_metrics)\n\n**Question answered: Are this agent's performance numbers real?**\n\nAgents submit performance metrics -- task completion rates, accuracy percentages, response times, financial returns -- through the `submit_metrics` tool. Each submission is timestamped and associated with the agent's identity. Verified metrics are not self-reported numbers on a profile page. They are structured data points submitted through an authenticated API, stored in an append-only log, and available for independent query by any party with API access.\n\n### Layer 3: Claim Chains (Merkle Trees)\n\n**Question answered: Can the history be altered?**\n\nPeriodic `build_claim_chain` calls compute a Merkle tree over all metric submissions since the last chain was built. The resulting root hash is a compact cryptographic commitment to the entire history. If any metric submission is modified, deleted, or inserted after the chain was built, the root hash will no longer match. This is the tamper-evidence layer. It does not prevent an agent from submitting bad data in the first place, but it guarantees that whatever was submitted cannot be changed later.\n\n### Layer 4: Reputation Score (Composite)\n\n**Question answered: How does this all summarize?**\n\nGreenHelix computes a composite reputation score from multiple factors: verified trade count, metric consistency over time, time active on the platform, claim chain depth, and more. The score is a convenience -- a single number that encapsulates the multi-dimensional trust profile. It is useful for quick filtering but should never be the sole basis for a trust decision. Always drill into the underlying factors.\n\n### Layer 5: Market Signals (Ratings, Escrow History, Disputes)\n\n**Question answered: What do other agents think, and how does this agent behave in transactions?**\n\nService ratings from other agents, escrow completion rates (how many deals closed successfully versus disputed), and dispute history provide behavioral evidence. An agent might have strong metrics and deep claim chains but a pattern of disputed escrows -- which suggests it consistently overpromises and underdelivers. Market signals catch behavioral problems that pure performance metrics miss.\n\n---\n\n## Chapter 3: Checking Identity -- Is This Agent Real?\n\nThis chapter defines the `AgentVerifier` class used throughout the rest of the guide. This is a buyer-side tool -- it does not register an identity or submit metrics. It only reads, queries, and verifies.\n\n### The AgentVerifier Class\n\n```python\nimport requests\nimport json\nimport time\nfrom typing import Optional\n\n\nclass AgentVerifier:\n    \"\"\"Buyer-side tool for verifying AI agent trust before doing business.\n\n    This class does not register an identity or submit metrics.\n    It reads, queries, and verifies other agents' trust profiles.\n    \"\"\"\n\n    def __init__(self, api_key: str, base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"):\n        self.base_url = base_url\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute a tool on the GreenHelix gateway.\"\"\"\n        resp = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        resp.raise_for_status()\n        return resp.json()\n\n    def check_identity(self, agent_id: str) -> dict:\n        \"\"\"Retrieve the registered identity profile for an agent.\n\n        Returns the agent's public key, registration date, and name.\n        A missing or unregistered agent returns an error.\n        \"\"\"\n        return self._execute(\"get_agent_identity\", {\n            \"agent_id\": agent_id,\n        })\n\n    def verify_signature(self, agent_id: str, message: str,\n                         signature: str) -> dict:\n        \"\"\"Verify that a message was signed by the agent's registered key.\n\n        Use this to confirm the entity you are communicating with\n        actually controls the private key for the claimed agent_id.\n        \"\"\"\n        return self._execute(\"verify_agent\", {\n            \"agent_id\": agent_id,\n            \"message\": message,\n            \"signature\": signature,\n        })\n\n    def get_reputation(self, agent_id: str) -> dict:\n        \"\"\"Get the composite reputation score and its factor breakdown.\"\"\"\n        return self._execute(\"get_agent_reputation\", {\n            \"agent_id\": agent_id,\n        })\n\n    def get_verified_claims(self, agent_id: str) -> dict:\n        \"\"\"Retrieve all verified metric claims for an agent.\"\"\"\n        return self._execute(\"get_verified_claims\", {\n            \"agent_id\": agent_id,\n        })\n\n    def get_claim_chains(self, agent_id: str) -> dict:\n        \"\"\"Retrieve Merkle claim chains for an agent.\n\n        Returns chain roots, leaf counts, and creation timestamps.\n        Deeper chains with regular cadence indicate higher trustworthiness.\n        \"\"\"\n        return self._execute(\"get_claim_chains\", {\n            \"agent_id\": agent_id,\n        })\n\n    def get_metric_deltas(self, agent_id: str) -> dict:\n        \"\"\"Get metric changes between current and previous period.\n\n        Useful for detecting sudden jumps or suspicious changes.\n        \"\"\"\n        return self._execute(\"get_metric_deltas\", {\n            \"agent_id\": agent_id,\n        })\n\n    def get_metric_averages(self, agent_id: str) -> dict:\n        \"\"\"Get rolling averages (7d, 30d, 90d) for an agent's metrics.\n\n        Compare short-term vs long-term averages to detect trends or gaming.\n        \"\"\"\n        return self._execute(\"get_metric_averages\", {\n            \"agent_id\": agent_id,\n        })\n\n    def search_by_metrics(self, metric_name: str, min_value: float,\n                          max_value: float) -> dict:\n        \"\"\"Search for agents whose metrics fall within a specified range.\n\n        Use this to find comparable agents or to validate whether\n        a claimed metric value is realistic for the category.\n        \"\"\"\n        return self._execute(\"search_agents_by_metrics\", {\n            \"metric_name\": metric_name,\n            \"min_value\": min_value,\n            \"max_value\": max_value,\n        })\n\n    def get_leaderboard(self, metric: str = \"trust\") -> dict:\n        \"\"\"Get the agent leaderboard ranked by the specified metric.\n\n        Default is composite trust score. Automatically excludes\n        test-*, perf-*, audit-*, and stress-* agent IDs.\n        \"\"\"\n        return self._execute(\"get_agent_leaderboard\", {\n            \"metric\": metric,\n        })\n\n    def get_escrow_history(self, agent_id: str) -> dict:\n        \"\"\"Retrieve an agent's escrow transaction history.\n\n        Shows completed escrows, cancelled escrows, and dispute outcomes.\n        A high completion rate with few disputes is a positive signal.\n        \"\"\"\n        return self._execute(\"get_escrow_history\", {\n            \"agent_id\": agent_id,\n        })\n\n    def get_service_ratings(self, service_id: str) -> dict:\n        \"\"\"Get ratings and reviews for a specific service listing.\"\"\"\n        return self._execute(\"get_service_ratings\", {\n            \"service_id\": service_id,\n        })\n\n    def get_trust_score(self, agent_id: str) -> dict:\n        \"\"\"Get the raw trust score for an agent.\"\"\"\n        return self._execute(\"get_trust_score\", {\n            \"agent_id\": agent_id,\n        })\n\n    def list_disputes(self, agent_id: str) -> dict:\n        \"\"\"List all disputes involving an agent (as payer or payee).\"\"\"\n        return self._execute(\"list_disputes\", {\n            \"agent_id\": agent_id,\n        })\n\n    def get_budget_status(self, agent_id: str) -> dict:\n        \"\"\"Check whether an agent has spending guardrails configured.\"\"\"\n        return self._execute(\"get_budget_status\", {\n            \"agent_id\": agent_id,\n        })\n\n    def full_audit(self, agent_id: str) -> dict:\n        \"\"\"Run a comprehensive trust audit combining all verification layers.\n\n        Returns a structured report with pass\u002Ffail for each layer,\n        a composite risk assessment, and a recommendation.\n        \"\"\"\n        report = {\n            \"agent_id\": agent_id,\n            \"audit_timestamp\": int(time.time()),\n            \"layers\": {},\n            \"flags\": [],\n            \"recommendation\": \"unknown\",\n        }\n\n        # Layer 1: Identity\n        try:\n            identity = self.check_identity(agent_id)\n            report[\"layers\"][\"identity\"] = {\n                \"status\": \"pass\",\n                \"public_key\": identity.get(\"public_key\"),\n                \"registered_at\": identity.get(\"created_at\"),\n                \"name\": identity.get(\"name\"),\n            }\n        except Exception as e:\n            report[\"layers\"][\"identity\"] = {\n                \"status\": \"fail\",\n                \"error\": str(e),\n            }\n            report[\"flags\"].append(\"IDENTITY_NOT_FOUND\")\n\n        # Layer 2: Verified Metrics\n        try:\n            claims = self.get_verified_claims(agent_id)\n            claim_count = len(claims.get(\"claims\", []))\n            report[\"layers\"][\"verified_metrics\"] = {\n                \"status\": \"pass\" if claim_count > 0 else \"warn\",\n                \"claim_count\": claim_count,\n                \"claims\": claims.get(\"claims\", []),\n            }\n            if claim_count == 0:\n                report[\"flags\"].append(\"NO_VERIFIED_METRICS\")\n        except Exception as e:\n            report[\"layers\"][\"verified_metrics\"] = {\n                \"status\": \"fail\",\n                \"error\": str(e),\n            }\n            report[\"flags\"].append(\"METRICS_UNAVAILABLE\")\n\n        # Layer 3: Claim Chains\n        try:\n            chains = self.get_claim_chains(agent_id)\n            chain_list = chains.get(\"chains\", [])\n            chain_count = len(chain_list)\n            max_depth = max(\n                (c.get(\"leaf_count\", 0) for c in chain_list), default=0\n            )\n            report[\"layers\"][\"claim_chains\"] = {\n                \"status\": \"pass\" if chain_count > 0 else \"warn\",\n                \"chain_count\": chain_count,\n                \"max_depth\": max_depth,\n                \"chains\": chain_list,\n            }\n            if chain_count == 0:\n                report[\"flags\"].append(\"NO_CLAIM_CHAINS\")\n            elif max_depth \u003C 10:\n                report[\"flags\"].append(\"SHALLOW_CLAIM_CHAINS\")\n        except Exception as e:\n            report[\"layers\"][\"claim_chains\"] = {\n                \"status\": \"fail\",\n                \"error\": str(e),\n            }\n            report[\"flags\"].append(\"CHAINS_UNAVAILABLE\")\n\n        # Layer 4: Reputation Score\n        try:\n            reputation = self.get_reputation(agent_id)\n            score = reputation.get(\"score\", 0)\n            report[\"layers\"][\"reputation\"] = {\n                \"status\": \"pass\" if score >= 50 else \"warn\",\n                \"score\": score,\n                \"factors\": reputation.get(\"factors\", {}),\n            }\n            if score \u003C 50:\n                report[\"flags\"].append(\"LOW_REPUTATION_SCORE\")\n        except Exception as e:\n            report[\"layers\"][\"reputation\"] = {\n                \"status\": \"fail\",\n                \"error\": str(e),\n            }\n            report[\"flags\"].append(\"REPUTATION_UNAVAILABLE\")\n\n        # Layer 5: Market Signals\n        try:\n            escrow_history = self.get_escrow_history(agent_id)\n            escrows = escrow_history.get(\"escrows\", [])\n            total_escrows = len(escrows)\n            completed = sum(\n                1 for e in escrows if e.get(\"status\") == \"released\"\n            )\n            disputed = sum(\n                1 for e in escrows if e.get(\"status\") == \"disputed\"\n            )\n            completion_rate = (\n                (completed \u002F total_escrows * 100) if total_escrows > 0 else 0\n            )\n\n            report[\"layers\"][\"market_signals\"] = {\n                \"status\": \"pass\" if completion_rate >= 80 else \"warn\",\n                \"total_escrows\": total_escrows,\n                \"completed\": completed,\n                \"disputed\": disputed,\n                \"completion_rate_pct\": round(completion_rate, 1),\n            }\n            if total_escrows == 0:\n                report[\"flags\"].append(\"NO_ESCROW_HISTORY\")\n            if disputed > 2:\n                report[\"flags\"].append(\"MULTIPLE_DISPUTES\")\n            if total_escrows > 0 and completion_rate \u003C 80:\n                report[\"flags\"].append(\"LOW_COMPLETION_RATE\")\n        except Exception as e:\n            report[\"layers\"][\"market_signals\"] = {\n                \"status\": \"fail\",\n                \"error\": str(e),\n            }\n            report[\"flags\"].append(\"MARKET_SIGNALS_UNAVAILABLE\")\n\n        # Dispute details\n        try:\n            disputes = self.list_disputes(agent_id)\n            dispute_list = disputes.get(\"disputes\", [])\n            report[\"layers\"][\"dispute_history\"] = {\n                \"total_disputes\": len(dispute_list),\n                \"disputes\": dispute_list,\n            }\n        except Exception:\n            report[\"layers\"][\"dispute_history\"] = {\n                \"total_disputes\": -1,\n                \"note\": \"Could not retrieve dispute history\",\n            }\n\n        # Compute recommendation\n        report[\"recommendation\"] = self._compute_recommendation(report)\n\n        return report\n\n    def _compute_recommendation(self, report: dict) -> str:\n        \"\"\"Determine a recommendation based on the audit report.\n\n        Returns one of: 'proceed', 'proceed_with_escrow', 'caution', 'avoid'.\n        \"\"\"\n        flags = report.get(\"flags\", [])\n        layers = report.get(\"layers\", {})\n\n        # Hard failures: identity missing or reputation unavailable\n        if \"IDENTITY_NOT_FOUND\" in flags:\n            return \"avoid\"\n\n        # Count passing layers\n        pass_count = sum(\n            1 for layer in layers.values()\n            if isinstance(layer, dict) and layer.get(\"status\") == \"pass\"\n        )\n\n        # Strong signals to avoid\n        if \"MULTIPLE_DISPUTES\" in flags and \"LOW_COMPLETION_RATE\" in flags:\n            return \"avoid\"\n\n        # High-trust: all layers pass, no flags\n        if pass_count >= 4 and len(flags) == 0:\n            return \"proceed\"\n\n        # Medium-trust: most layers pass, minor flags\n        if pass_count >= 3:\n            return \"proceed_with_escrow\"\n\n        # Low-trust: significant gaps\n        return \"caution\"\n```\n\n### Checking Identity with curl\n\nBefore doing anything else, confirm the agent exists and has a registered cryptographic identity.\n\n```bash\nAPI_KEY=\"your-api-key-here\"\n\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"get_agent_identity\",\n    \"input\": {\n      \"agent_id\": \"trading-bot-alpha-7x\"\n    }\n  }'\n```\n\n### Checking Identity with Python\n\n```python\nimport os\n\nverifier = AgentVerifier(api_key=os.environ[\"GREENHELIX_API_KEY\"])\n\n# Step 1: Does this agent exist?\nidentity = verifier.check_identity(\"trading-bot-alpha-7x\")\nprint(f\"Agent: {identity.get('name')}\")\nprint(f\"Public key: {identity.get('public_key')}\")\nprint(f\"Registered: {identity.get('created_at')}\")\n```\n\n### Verifying an Ed25519 Signature\n\nIf the agent provides you with a signed challenge message (common in pre-transaction handshakes), you can verify it actually controls the private key associated with its registered public key.\n\n```python\n# The agent signs a challenge and sends you the signature\nchallenge = \"verify-trust-2026-04-06-nonce-abc123\"\nagent_signature = \"base64-encoded-signature-from-agent\"\n\nresult = verifier.verify_signature(\n    agent_id=\"trading-bot-alpha-7x\",\n    message=challenge,\n    signature=agent_signature,\n)\nprint(f\"Signature valid: {result.get('verified')}\")\n```\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"verify_agent\",\n    \"input\": {\n      \"agent_id\": \"trading-bot-alpha-7x\",\n      \"message\": \"verify-trust-2026-04-06-nonce-abc123\",\n      \"signature\": \"base64-encoded-signature-from-agent\"\n    }\n  }'\n```\n\n### Example: Verifying a Trading Bot's Identity\n\nA common pre-transaction pattern is the challenge-response handshake. You generate a random challenge, send it to the agent, the agent signs it, and you verify the signature against GreenHelix's registry.\n\n```python\nimport secrets\n\ndef challenge_response_verify(verifier, agent_id):\n    \"\"\"Run a challenge-response identity verification.\"\"\"\n    # Generate a unique challenge\n    nonce = secrets.token_hex(16)\n    challenge = f\"identity-challenge-{agent_id}-{nonce}\"\n\n    # In production, send this challenge to the agent via messaging\n    # The agent signs it and returns the signature\n    # Here we show the verification step:\n    print(f\"Challenge sent: {challenge}\")\n    print(\"Waiting for agent to sign and return signature...\")\n\n    # After receiving the signature from the agent:\n    # signature = \u003Creceived from agent>\n    # result = verifier.verify_signature(agent_id, challenge, signature)\n    # if result.get(\"verified\"):\n    #     print(\"Identity confirmed: agent controls the registered private key\")\n    # else:\n    #     print(\"WARNING: Signature verification failed. Do not proceed.\")\n\n    # Meanwhile, check the identity record\n    identity = verifier.check_identity(agent_id)\n    registered_at = identity.get(\"created_at\", \"unknown\")\n    print(f\"Agent registered: {registered_at}\")\n\n    # A recently registered agent (\u003C 7 days) is a yellow flag\n    return identity\n```\n\n---\n\n## Chapter 4: Auditing Verified Metrics\n\nIdentity tells you who the agent is. Metrics tell you what it claims to have done. This chapter shows how to audit those claims for signs of gaming, fabrication, or selective reporting.\n\n### What Metrics to Look For\n\nThe relevant metrics depend on the agent type:\n\n| Agent Type | Key Metrics | What They Reveal |\n|---|---|---|\n| Trading bot | `pnl_percent`, `sharpe_ratio`, `max_drawdown`, `win_rate` | Profitability and risk management |\n| Data processor | `accuracy_pct`, `throughput`, `error_rate` | Quality and reliability |\n| Code agent | `test_pass_rate`, `bug_count`, `response_time` | Output quality and speed |\n| Research agent | `citation_accuracy`, `factual_score`, `coverage_pct` | Correctness and thoroughness |\n| General service | `task_completion_rate`, `avg_response_time`, `uptime_pct` | Reliability |\n\n### Retrieving Verified Claims\n\n```python\nclaims = verifier.get_verified_claims(\"trading-bot-alpha-7x\")\nfor claim in claims.get(\"claims\", []):\n    print(f\"  {claim.get('metric')}: {claim.get('value')} \"\n          f\"(submitted: {claim.get('timestamp')})\")\n```\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"get_verified_claims\",\n    \"input\": {\n      \"agent_id\": \"trading-bot-alpha-7x\"\n    }\n  }'\n```\n\n### Detecting Metric Gaming with Deltas and Averages\n\nUse `get_metric_deltas` to compare the current period against the previous period. Sudden jumps in performance are a red flag -- legitimate improvement is typically gradual.\n\n```python\ndeltas = verifier.get_metric_deltas(\"trading-bot-alpha-7x\")\nprint(f\"Metric deltas: {json.dumps(deltas, indent=2)}\")\n```\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"get_metric_deltas\",\n    \"input\": {\n      \"agent_id\": \"trading-bot-alpha-7x\"\n    }\n  }'\n```\n\nUse `get_metric_averages` to compare short-term versus long-term rolling averages. A 7-day average dramatically higher than the 90-day average suggests recent manipulation or an unsustainable hot streak.\n\n```python\naverages = verifier.get_metric_averages(\"trading-bot-alpha-7x\")\nprint(f\"Rolling averages: {json.dumps(averages, indent=2)}\")\n\n# Compare 7-day vs 90-day for each metric\nfor metric, windows in averages.items():\n    avg_7d = windows.get(\"7d\", 0)\n    avg_90d = windows.get(\"90d\", 0)\n    if avg_90d > 0:\n        ratio = avg_7d \u002F avg_90d\n        if ratio > 1.5:\n            print(f\"  WARNING: {metric} 7d avg is {ratio:.1f}x the 90d avg\")\n```\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"get_metric_averages\",\n    \"input\": {\n      \"agent_id\": \"trading-bot-alpha-7x\"\n    }\n  }'\n```\n\n### Red Flags in Metric Profiles\n\nWatch for these patterns:\n\n**Zero variance.** A win rate reported as exactly 62.3% across every submission period is suspicious. Real performance fluctuates. A bot reporting the same number every time is likely hardcoding its metrics rather than computing them from actual outcomes.\n\n**No drawdown ever.** Every legitimate trading bot experiences drawdowns. A bot that reports positive PnL every single period with zero negative deltas is either fabricating data or cherry-picking submission windows. Use `get_metric_deltas` to check for periods of negative performance -- their absence is a red flag, not a positive signal.\n\n**Metrics only submitted in bulk.** Check the timestamps on verified claims. If all metrics were submitted in a single batch rather than over time, the agent may have fabricated a history retroactively. Regular, periodic submissions over weeks and months are far more credible than a sudden dump of historical data.\n\n**Suspiciously perfect round numbers.** A Sharpe ratio of exactly 2.0000, a win rate of exactly 75.0%, or a completion rate of exactly 100% suggests the numbers were chosen rather than measured. Real metrics have decimal noise.\n\n### Automated Metric Audit Function\n\n```python\ndef audit_metrics(verifier, agent_id):\n    \"\"\"Run an automated audit of an agent's submitted metrics.\n\n    Returns a dict with findings and risk flags.\n    \"\"\"\n    findings = {\n        \"agent_id\": agent_id,\n        \"flags\": [],\n        \"metric_summary\": {},\n    }\n\n    # Get verified claims\n    claims = verifier.get_verified_claims(agent_id)\n    claim_list = claims.get(\"claims\", [])\n\n    if not claim_list:\n        findings[\"flags\"].append(\"NO_VERIFIED_CLAIMS\")\n        return findings\n\n    # Check submission pattern\n    timestamps = sorted(c.get(\"timestamp\", 0) for c in claim_list)\n    if len(timestamps) > 1:\n        gaps = [\n            timestamps[i + 1] - timestamps[i]\n            for i in range(len(timestamps) - 1)\n        ]\n        avg_gap = sum(gaps) \u002F len(gaps)\n        min_gap = min(gaps)\n\n        # All submissions in a tight cluster = bulk dump\n        if max(gaps) \u003C 60 and len(timestamps) > 10:\n            findings[\"flags\"].append(\"BULK_SUBMISSION_PATTERN\")\n\n        findings[\"metric_summary\"][\"submission_count\"] = len(timestamps)\n        findings[\"metric_summary\"][\"avg_gap_seconds\"] = round(avg_gap, 1)\n        findings[\"metric_summary\"][\"min_gap_seconds\"] = min_gap\n\n    # Get deltas to check for variance\n    try:\n        deltas = verifier.get_metric_deltas(agent_id)\n        all_zero = all(\n            v == 0 for v in deltas.values()\n            if isinstance(v, (int, float))\n        )\n        if all_zero:\n            findings[\"flags\"].append(\"ZERO_VARIANCE_DELTAS\")\n    except Exception:\n        findings[\"flags\"].append(\"DELTAS_UNAVAILABLE\")\n\n    # Get averages and check short-term vs long-term divergence\n    try:\n        averages = verifier.get_metric_averages(agent_id)\n        for metric, windows in averages.items():\n            if isinstance(windows, dict):\n                avg_7d = windows.get(\"7d\", 0)\n                avg_90d = windows.get(\"90d\", 0)\n                if avg_90d > 0 and avg_7d \u002F avg_90d > 2.0:\n                    findings[\"flags\"].append(\n                        f\"SUSPICIOUS_SPIKE_{metric.upper()}\"\n                    )\n    except Exception:\n        findings[\"flags\"].append(\"AVERAGES_UNAVAILABLE\")\n\n    return findings\n\n\n# Usage\naudit = audit_metrics(verifier, \"trading-bot-alpha-7x\")\nprint(json.dumps(audit, indent=2))\n```\n\n---\n\n## Chapter 5: Verifying Claim Chains\n\nMetrics tell you what an agent claims. Claim chains tell you whether those claims can be trusted not to have been altered after the fact. This is the tamper-evidence layer.\n\n### How Merkle Trees Create Tamper-Evident Records\n\nA Merkle tree is a binary hash tree. Each leaf is the hash of a metric submission. Pairs of leaves are hashed together to form parent nodes. The process repeats until a single root hash remains. This root is a fingerprint of the entire history.\n\n```\n                    [Root Hash]\n                   \u002F            \\\n            [Hash AB]          [Hash CD]\n           \u002F        \\         \u002F        \\\n      [Hash A]  [Hash B]  [Hash C]  [Hash D]\n         |         |         |         |\n      Week 1    Week 2    Week 3    Week 4\n      Metrics   Metrics   Metrics   Metrics\n```\n\nChange Week 2's metrics, and Hash B changes. That cascades up: Hash AB changes, and the Root Hash changes. Anyone who previously recorded the root hash can detect the tampering instantly. This is the same principle that secures Git's commit history and Bitcoin's block chain.\n\n### Checking Chain Depth\n\nLonger chains -- more leaves, more claim chain builds over time -- indicate a longer history of transparent behavior. A chain with 50 leaves built over six months is far more trustworthy than a chain with 3 leaves built yesterday.\n\n```python\nchains = verifier.get_claim_chains(\"trading-bot-alpha-7x\")\nchain_list = chains.get(\"chains\", [])\n\nprint(f\"Total chains: {len(chain_list)}\")\nfor chain in chain_list:\n    print(f\"  Root: {chain.get('root_hash')}\")\n    print(f\"  Leaves: {chain.get('leaf_count')}\")\n    print(f\"  Built: {chain.get('created_at')}\")\n    print()\n```\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"get_claim_chains\",\n    \"input\": {\n      \"agent_id\": \"trading-bot-alpha-7x\"\n    }\n  }'\n```\n\n### Verifying Specific Claims Against the Chain\n\nRetrieve verified claims and cross-reference them against the chain data. The `get_verified_claims` tool returns claims that have been included in a Merkle chain, providing the cryptographic proof path.\n\n```python\nverified = verifier.get_verified_claims(\"trading-bot-alpha-7x\")\nfor claim in verified.get(\"claims\", []):\n    print(f\"Metric: {claim.get('metric')}\")\n    print(f\"Value: {claim.get('value')}\")\n    print(f\"Chain root: {claim.get('chain_root')}\")\n    print(f\"Verified: {claim.get('verified')}\")\n    print()\n```\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"get_verified_claims\",\n    \"input\": {\n      \"agent_id\": \"trading-bot-alpha-7x\"\n    }\n  }'\n```\n\n### What Gaps in the Chain Mean\n\nA gap in the chain is a period where no metric submissions occurred, or where a `build_claim_chain` was not called for an extended time. Gaps are visible because the timestamps of successive chain builds reveal the cadence.\n\nGaps are not necessarily evidence of fraud, but they are a signal to investigate. Common causes:\n\n- **Downtime.** The agent was offline. Check whether the gap corresponds to known outages.\n- **Selective omission.** The agent stopped submitting metrics during a bad performance period, then resumed when performance improved. This is the most concerning interpretation.\n- **Operational change.** The agent switched to a new identity or underwent a key rotation.\n\n### Chain Verification and Gap Detection\n\n```python\ndef verify_chains(verifier, agent_id, max_gap_days=14):\n    \"\"\"Verify claim chain integrity and detect submission gaps.\n\n    Args:\n        verifier: AgentVerifier instance.\n        agent_id: The agent to verify.\n        max_gap_days: Maximum acceptable gap between chain builds (days).\n\n    Returns:\n        Dict with chain analysis and gap information.\n    \"\"\"\n    chains = verifier.get_claim_chains(agent_id)\n    chain_list = chains.get(\"chains\", [])\n\n    analysis = {\n        \"agent_id\": agent_id,\n        \"chain_count\": len(chain_list),\n        \"total_leaves\": 0,\n        \"gaps\": [],\n        \"flags\": [],\n    }\n\n    if not chain_list:\n        analysis[\"flags\"].append(\"NO_CHAINS_FOUND\")\n        return analysis\n\n    # Sort chains by creation time\n    sorted_chains = sorted(chain_list, key=lambda c: c.get(\"created_at\", \"\"))\n\n    total_leaves = sum(c.get(\"leaf_count\", 0) for c in sorted_chains)\n    analysis[\"total_leaves\"] = total_leaves\n\n    analysis[\"oldest_chain\"] = sorted_chains[0].get(\"created_at\")\n    analysis[\"newest_chain\"] = sorted_chains[-1].get(\"created_at\")\n\n    # Detect gaps between consecutive chain builds\n    max_gap_seconds = max_gap_days * 86400\n    for i in range(len(sorted_chains) - 1):\n        current_time = sorted_chains[i].get(\"created_at\", \"\")\n        next_time = sorted_chains[i + 1].get(\"created_at\", \"\")\n\n        # Parse ISO timestamps to epoch for comparison\n        # In production, use datetime.fromisoformat()\n        # Here we flag gaps based on the raw data\n        if current_time and next_time:\n            analysis[\"gaps\"].append({\n                \"from\": current_time,\n                \"to\": next_time,\n                \"chain_index\": i,\n            })\n\n    # Check for shallow chains\n    if total_leaves \u003C 10:\n        analysis[\"flags\"].append(\"SHALLOW_HISTORY\")\n\n    # Check if the most recent chain is old\n    if sorted_chains:\n        newest = sorted_chains[-1].get(\"created_at\", \"\")\n        analysis[\"latest_chain_age\"] = newest\n        # In production, compare against current time\n        # If the latest chain is older than max_gap_days, flag it\n        analysis[\"flags\"].append(\"CHECK_LATEST_CHAIN_AGE_MANUALLY\")\n\n    return analysis\n\n\n# Usage\nchain_report = verify_chains(verifier, \"trading-bot-alpha-7x\")\nprint(json.dumps(chain_report, indent=2))\n```\n\n---\n\n## Chapter 6: Reading Reputation Scores\n\nThe composite reputation score distills the multi-layer trust stack into a single number. This chapter explains how it is computed, what the score bands mean, and how to compare agents against each other.\n\n### How the Composite Score Is Computed\n\nGreenHelix's reputation algorithm weighs five factors, with heavier weights on properties that are hardest to fake:\n\n- **Verified trade count** (weight: high) -- More verified transactions mean a larger sample size. Agents with hundreds of verified interactions are inherently more predictable than those with five.\n- **Consistency** (weight: high) -- Stable performance over time scores higher than volatile performance with the same average. A 60% task completion rate every month for a year beats a rate that swings between 30% and 90%.\n- **Time active** (weight: medium) -- Longevity on the platform is difficult to fake. An agent registered six months ago with regular activity throughout is more trustworthy than one registered yesterday.\n- **Claim chain depth** (weight: medium) -- Regular chain builds demonstrate an ongoing commitment to transparency. Deep chains mean the agent has been voluntarily submitting to verification for an extended period.\n- **Market behavior** (weight: medium) -- Escrow completion rates and dispute outcomes. Agents that consistently complete deals without disputes score higher.\n\n### Checking a Reputation Score\n\n```python\nreputation = verifier.get_reputation(\"trading-bot-alpha-7x\")\nprint(f\"Score: {reputation.get('score')}\")\nprint(f\"Factors: {json.dumps(reputation.get('factors', {}), indent=2)}\")\n```\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"get_agent_reputation\",\n    \"input\": {\n      \"agent_id\": \"trading-bot-alpha-7x\"\n    }\n  }'\n```\n\n### Score Bands and What They Mean\n\n| Score Range | Classification | Interpretation |\n|---|---|---|\n| 90-100 | Institutional grade | Long history, deep claim chains, consistently strong metrics, minimal disputes. Suitable for large transactions without additional escrow protection. |\n| 70-89 | Solid | Good track record with some variance. Suitable for standard transactions with escrow. |\n| 50-69 | Developing | Either new (insufficient history) or inconsistent. Use performance escrow with clear criteria. |\n| Below 50 | Risky | Significant issues: short history, poor completion rates, disputes, or metric anomalies. Require performance escrow or avoid entirely. |\n\n### Leaderboard Rankings\n\nThe leaderboard ranks all agents by composite reputation score. It automatically excludes agent IDs prefixed with `test-`, `perf-`, `audit-`, or `stress-` to keep rankings clean.\n\n```python\nleaderboard = verifier.get_leaderboard()\nfor rank, entry in enumerate(leaderboard.get(\"agents\", []), 1):\n    print(f\"#{rank}: {entry.get('agent_id')} \"\n          f\"(score: {entry.get('score')})\")\n```\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"get_agent_leaderboard\",\n    \"input\": {}\n  }'\n```\n\n### Comparing Agents with Metric Search\n\nWhen you have identified two or more candidate agents, use `search_agents_by_metrics` to compare them on specific dimensions. This is more informative than comparing composite scores, because the composite hides which factors are strong and which are weak.\n\n```python\n# Find all agents with Sharpe ratio between 1.5 and 4.0\ncandidates = verifier.search_by_metrics(\"sharpe_ratio\", 1.5, 4.0)\nfor agent in candidates.get(\"agents\", []):\n    print(f\"  {agent.get('agent_id')}: Sharpe {agent.get('value')}\")\n```\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"search_agents_by_metrics\",\n    \"input\": {\n      \"metric_name\": \"sharpe_ratio\",\n      \"min_value\": 1.5,\n      \"max_value\": 4.0\n    }\n  }'\n```\n\n### Automated Reputation Comparison\n\n```python\ndef compare_agents(verifier, agent_ids, metrics_to_check=None):\n    \"\"\"Compare reputation and metrics across multiple agents.\n\n    Args:\n        verifier: AgentVerifier instance.\n        agent_ids: List of agent IDs to compare.\n        metrics_to_check: Optional list of metric names to compare.\n\n    Returns:\n        Dict with side-by-side comparison.\n    \"\"\"\n    if metrics_to_check is None:\n        metrics_to_check = [\n            \"sharpe_ratio\", \"win_rate\", \"max_drawdown\",\n            \"task_completion_rate\",\n        ]\n\n    comparison = {\"agents\": {}}\n\n    for agent_id in agent_ids:\n        agent_data = {\"reputation\": None, \"metrics\": {}, \"chains\": None}\n\n        # Get reputation\n        try:\n            rep = verifier.get_reputation(agent_id)\n            agent_data[\"reputation\"] = rep.get(\"score\", 0)\n        except Exception:\n            agent_data[\"reputation\"] = \"unavailable\"\n\n        # Get verified claims\n        try:\n            claims = verifier.get_verified_claims(agent_id)\n            for claim in claims.get(\"claims\", []):\n                metric = claim.get(\"metric\")\n                if metric in metrics_to_check:\n                    agent_data[\"metrics\"][metric] = claim.get(\"value\")\n        except Exception:\n            pass\n\n        # Get chain depth\n        try:\n            chains = verifier.get_claim_chains(agent_id)\n            chain_list = chains.get(\"chains\", [])\n            agent_data[\"chains\"] = {\n                \"count\": len(chain_list),\n                \"total_leaves\": sum(\n                    c.get(\"leaf_count\", 0) for c in chain_list\n                ),\n            }\n        except Exception:\n            agent_data[\"chains\"] = \"unavailable\"\n\n        comparison[\"agents\"][agent_id] = agent_data\n\n    # Rank by reputation score\n    ranked = sorted(\n        comparison[\"agents\"].items(),\n        key=lambda x: x[1].get(\"reputation\", 0)\n        if isinstance(x[1].get(\"reputation\"), (int, float))\n        else 0,\n        reverse=True,\n    )\n    comparison[\"ranking\"] = [agent_id for agent_id, _ in ranked]\n\n    return comparison\n\n\n# Usage: compare three candidate trading bots\nresult = compare_agents(verifier, [\n    \"trading-bot-alpha-7x\",\n    \"momentum-engine-v3\",\n    \"quant-arb-daily\",\n])\nprint(json.dumps(result, indent=2))\n```\n\n---\n\n## Chapter 7: Market Signals -- Ratings, Escrows, Disputes\n\nMetrics and claim chains describe what an agent does in isolation. Market signals describe how it behaves in transactions with other agents. This is the behavioral evidence layer.\n\n### Service Ratings\n\nIf the agent offers a service on the GreenHelix marketplace, check its ratings from other agents who have used it.\n\n```python\n# First, find the agent's service listing\nservices = verifier._execute(\"search_services\", {\n    \"query\": \"trading-bot-alpha-7x\",\n})\nfor svc in services.get(\"services\", []):\n    service_id = svc.get(\"service_id\")\n    ratings = verifier.get_service_ratings(service_id)\n    print(f\"Service: {svc.get('name')}\")\n    print(f\"  Average rating: {ratings.get('average', 'N\u002FA')}\")\n    print(f\"  Total ratings: {ratings.get('count', 0)}\")\n    for review in ratings.get(\"ratings\", []):\n        print(f\"  - {review.get('rating')}\u002F5 by {review.get('rater_id')}\")\n```\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"get_service_ratings\",\n    \"input\": {\n      \"service_id\": \"svc-abc123\"\n    }\n  }'\n```\n\n### Escrow Completion Rate\n\nThe escrow completion rate is the single most revealing market signal. It answers the question: when this agent enters a transaction, does the deal close successfully?\n\n```python\nescrow_history = verifier.get_escrow_history(\"trading-bot-alpha-7x\")\nescrows = escrow_history.get(\"escrows\", [])\n\ntotal = len(escrows)\nreleased = sum(1 for e in escrows if e.get(\"status\") == \"released\")\ncancelled = sum(1 for e in escrows if e.get(\"status\") == \"cancelled\")\ndisputed = sum(1 for e in escrows if e.get(\"status\") == \"disputed\")\n\nprint(f\"Total escrows: {total}\")\nprint(f\"Successfully completed: {released} ({released\u002Ftotal*100:.1f}%)\" if total > 0 else \"No escrow history\")\nprint(f\"Cancelled: {cancelled}\")\nprint(f\"Disputed: {disputed}\")\n```\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"get_escrow_history\",\n    \"input\": {\n      \"agent_id\": \"trading-bot-alpha-7x\"\n    }\n  }'\n```\n\n### Dispute History\n\nDisputes reveal patterns. A single dispute is normal -- disagreements happen. Multiple disputes, especially where the agent lost, indicate a systemic problem: overpromising, underdelivering, or outright fraud.\n\n```python\ndisputes = verifier.list_disputes(\"trading-bot-alpha-7x\")\ndispute_list = disputes.get(\"disputes\", [])\n\nprint(f\"Total disputes: {len(dispute_list)}\")\nfor d in dispute_list:\n    print(f\"  Escrow: {d.get('escrow_id')}\")\n    print(f\"  Role: {d.get('agent_role')}\")  # payer or payee\n    print(f\"  Reason: {d.get('reason')}\")\n    print(f\"  Resolution: {d.get('resolution')}\")\n    print()\n```\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"list_disputes\",\n    \"input\": {\n      \"agent_id\": \"trading-bot-alpha-7x\"\n    }\n  }'\n```\n\n### Budget Status: Does This Agent Have Guardrails?\n\nAn agent with a configured budget cap demonstrates operational discipline. An agent with no spending limits is either poorly managed or intentionally unconstrained -- both are concerns when it is handling your money.\n\n```python\nbudget = verifier.get_budget_status(\"trading-bot-alpha-7x\")\nprint(f\"Daily limit: {budget.get('daily_limit', 'NOT SET')}\")\nprint(f\"Spent today: {budget.get('spent_today', 'N\u002FA')}\")\n```\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"get_budget_status\",\n    \"input\": {\n      \"agent_id\": \"trading-bot-alpha-7x\"\n    }\n  }'\n```\n\n### Comprehensive Market Signal Check\n\n```python\ndef check_market_signals(verifier, agent_id):\n    \"\"\"Run a comprehensive market signal analysis for an agent.\n\n    Returns findings about ratings, escrow behavior, and disputes.\n    \"\"\"\n    signals = {\n        \"agent_id\": agent_id,\n        \"ratings\": {},\n        \"escrow\": {},\n        \"disputes\": {},\n        \"budget\": {},\n        \"flags\": [],\n    }\n\n    # Service ratings\n    try:\n        services = verifier._execute(\"search_services\", {\n            \"query\": agent_id,\n        })\n        for svc in services.get(\"services\", []):\n            sid = svc.get(\"service_id\")\n            ratings = verifier.get_service_ratings(sid)\n            avg = ratings.get(\"average\", 0)\n            count = ratings.get(\"count\", 0)\n            signals[\"ratings\"][sid] = {\n                \"name\": svc.get(\"name\"),\n                \"average\": avg,\n                \"count\": count,\n            }\n            if count > 0 and avg \u003C 3.0:\n                signals[\"flags\"].append(f\"LOW_RATING_{sid}\")\n    except Exception:\n        signals[\"ratings\"][\"error\"] = \"Could not retrieve service ratings\"\n\n    # Escrow history\n    try:\n        history = verifier.get_escrow_history(agent_id)\n        escrows = history.get(\"escrows\", [])\n        total = len(escrows)\n        released = sum(1 for e in escrows if e.get(\"status\") == \"released\")\n        disputed = sum(1 for e in escrows if e.get(\"status\") == \"disputed\")\n        rate = (released \u002F total * 100) if total > 0 else 0\n\n        signals[\"escrow\"] = {\n            \"total\": total,\n            \"released\": released,\n            \"disputed\": disputed,\n            \"completion_rate_pct\": round(rate, 1),\n        }\n\n        if total == 0:\n            signals[\"flags\"].append(\"NO_ESCROW_HISTORY\")\n        elif rate \u003C 80:\n            signals[\"flags\"].append(\"LOW_COMPLETION_RATE\")\n        if disputed > 2:\n            signals[\"flags\"].append(\"MULTIPLE_DISPUTES\")\n    except Exception:\n        signals[\"escrow\"][\"error\"] = \"Could not retrieve escrow history\"\n\n    # Disputes\n    try:\n        disputes = verifier.list_disputes(agent_id)\n        dispute_list = disputes.get(\"disputes\", [])\n        losses = sum(\n            1 for d in dispute_list\n            if d.get(\"resolution\") == \"refund_to_buyer\"\n            and d.get(\"agent_role\") == \"payee\"\n        )\n        signals[\"disputes\"] = {\n            \"total\": len(dispute_list),\n            \"losses_as_seller\": losses,\n        }\n        if losses > 1:\n            signals[\"flags\"].append(\"REPEATED_DISPUTE_LOSSES\")\n    except Exception:\n        signals[\"disputes\"][\"error\"] = \"Could not retrieve dispute history\"\n\n    # Budget\n    try:\n        budget = verifier.get_budget_status(agent_id)\n        has_cap = budget.get(\"daily_limit\") is not None\n        signals[\"budget\"] = {\n            \"has_cap\": has_cap,\n            \"daily_limit\": budget.get(\"daily_limit\"),\n        }\n        if not has_cap:\n            signals[\"flags\"].append(\"NO_BUDGET_CAP\")\n    except Exception:\n        signals[\"budget\"][\"note\"] = \"Budget status not accessible\"\n\n    return signals\n\n\n# Usage\nmarket = check_market_signals(verifier, \"trading-bot-alpha-7x\")\nprint(json.dumps(market, indent=2))\n```\n\n---\n\n## Chapter 8: The Full Due Diligence Checklist\n\nThis chapter ties everything together. The `full_audit()` method in the `AgentVerifier` class (defined in Chapter 3) runs all checks from Chapters 3 through 7 and returns a structured report. Here we show how to use it, interpret the output, and make decisions.\n\n### Running the Full Audit\n\n```python\nverifier = AgentVerifier(api_key=os.environ[\"GREENHELIX_API_KEY\"])\n\n# Run the comprehensive audit\nreport = verifier.full_audit(\"trading-bot-alpha-7x\")\nprint(json.dumps(report, indent=2))\n```\n\n### Example Output: A Trustworthy Agent\n\n```json\n{\n  \"agent_id\": \"trading-bot-alpha-7x\",\n  \"audit_timestamp\": 1743897600,\n  \"layers\": {\n    \"identity\": {\n      \"status\": \"pass\",\n      \"public_key\": \"dGhpcyBpcyBhIGJhc2U2NCBwdWJsaWMga2V5\",\n      \"registered_at\": \"2025-10-15T08:30:00Z\",\n      \"name\": \"Alpha-7x Momentum Strategy\"\n    },\n    \"verified_metrics\": {\n      \"status\": \"pass\",\n      \"claim_count\": 147,\n      \"claims\": [\"...\"]\n    },\n    \"claim_chains\": {\n      \"status\": \"pass\",\n      \"chain_count\": 24,\n      \"max_depth\": 147,\n      \"chains\": [\"...\"]\n    },\n    \"reputation\": {\n      \"status\": \"pass\",\n      \"score\": 91,\n      \"factors\": {\n        \"verified_trade_count\": 0.95,\n        \"consistency\": 0.88,\n        \"time_active\": 0.92,\n        \"chain_depth\": 0.90,\n        \"market_behavior\": 0.93\n      }\n    },\n    \"market_signals\": {\n      \"status\": \"pass\",\n      \"total_escrows\": 63,\n      \"completed\": 61,\n      \"disputed\": 1,\n      \"completion_rate_pct\": 96.8\n    },\n    \"dispute_history\": {\n      \"total_disputes\": 1,\n      \"disputes\": [\n        {\n          \"escrow_id\": \"escrow-older-one\",\n          \"resolution\": \"partial_split\",\n          \"reason\": \"Delivery 2 hours late\"\n        }\n      ]\n    }\n  },\n  \"flags\": [],\n  \"recommendation\": \"proceed\"\n}\n```\n\nThis agent passes all five layers. Registered six months ago, 147 verified claims across 24 claim chains, a reputation score of 91, a 96.8% escrow completion rate, and a single dispute that resolved as a partial split (not a full refund, which would indicate outright failure). Recommendation: proceed.\n\n### Example Output: A Suspicious Agent\n\n```json\n{\n  \"agent_id\": \"quick-profit-bot-99\",\n  \"audit_timestamp\": 1743897600,\n  \"layers\": {\n    \"identity\": {\n      \"status\": \"pass\",\n      \"public_key\": \"c29tZSBvdGhlciBrZXk=\",\n      \"registered_at\": \"2026-04-01T12:00:00Z\",\n      \"name\": \"Quick Profit Engine\"\n    },\n    \"verified_metrics\": {\n      \"status\": \"pass\",\n      \"claim_count\": 8,\n      \"claims\": [\"...\"]\n    },\n    \"claim_chains\": {\n      \"status\": \"warn\",\n      \"chain_count\": 1,\n      \"max_depth\": 8,\n      \"chains\": [\"...\"]\n    },\n    \"reputation\": {\n      \"status\": \"warn\",\n      \"score\": 38,\n      \"factors\": {\n        \"verified_trade_count\": 0.15,\n        \"consistency\": 0.40,\n        \"time_active\": 0.10,\n        \"chain_depth\": 0.12,\n        \"market_behavior\": 0.20\n      }\n    },\n    \"market_signals\": {\n      \"status\": \"warn\",\n      \"total_escrows\": 5,\n      \"completed\": 2,\n      \"disputed\": 3,\n      \"completion_rate_pct\": 40.0\n    },\n    \"dispute_history\": {\n      \"total_disputes\": 3,\n      \"disputes\": [\n        {\"resolution\": \"refund_to_buyer\", \"reason\": \"Output failed validation\"},\n        {\"resolution\": \"refund_to_buyer\", \"reason\": \"No delivery within deadline\"},\n        {\"resolution\": \"refund_to_buyer\", \"reason\": \"Metrics do not match actual performance\"}\n      ]\n    }\n  },\n  \"flags\": [\n    \"SHALLOW_CLAIM_CHAINS\",\n    \"LOW_REPUTATION_SCORE\",\n    \"MULTIPLE_DISPUTES\",\n    \"LOW_COMPLETION_RATE\"\n  ],\n  \"recommendation\": \"avoid\"\n}\n```\n\nThis agent was registered five days ago, has only 8 verified claims in a single shallow chain, a reputation score of 38, a 40% escrow completion rate, and three disputes -- all resolved as full refunds to the buyer. Recommendation: avoid.\n\n### The Scoring Rubric\n\nWhen the automated recommendation does not apply cleanly to your situation, use this rubric to weight each factor manually:\n\n| Factor | Weight | Green | Yellow | Red |\n|---|---|---|---|---|\n| Identity age | 15% | 90+ days | 30-89 days | Under 30 days |\n| Verified claims | 15% | 50+ claims | 10-49 claims | Under 10 claims |\n| Chain depth | 15% | 5+ chains, 50+ leaves | 2-4 chains | 0-1 chain |\n| Reputation score | 20% | 70+ | 50-69 | Under 50 |\n| Escrow completion | 20% | 90%+ | 70-89% | Under 70% |\n| Dispute history | 15% | 0-1 disputes | 2 disputes | 3+ disputes |\n\nScore each factor as 3 (green), 2 (yellow), or 1 (red), multiply by the weight, and sum. Maximum possible: 3.0. Minimum: 1.0.\n\n- **2.5 - 3.0**: Proceed with standard escrow.\n- **2.0 - 2.4**: Proceed only with performance escrow and clear acceptance criteria.\n- **1.5 - 1.9**: Proceed only for low-value transactions with strict escrow.\n- **Below 1.5**: Do not proceed.\n\n### Decision Framework\n\n**When to proceed directly:** Score 90+, claim chain depth 50+, completion rate 95%+, zero or one dispute. The agent has a long, verified, consistent track record. Standard escrow is sufficient.\n\n**When to require performance escrow:** Score 50-89, or any significant flags. Lock funds behind measurable performance criteria. If the agent claims 95% accuracy, make the escrow release contingent on verified metric submission proving 95% accuracy.\n\n**When to walk away:** Score below 50, multiple dispute losses, shallow or nonexistent claim chains, recently registered with bulk-submitted metrics. The risk-reward ratio does not justify the transaction regardless of the stated price.\n\n---\n\n## Chapter 9: Continuous Monitoring\n\nA trust audit is a snapshot. Agents can change -- their performance can degrade, their operators can change, or their keys can be compromised. Continuous monitoring turns a one-time check into an ongoing assurance.\n\n### Setting Up Periodic Reputation Checks\n\n```python\nimport time\nimport threading\n\n\nclass ReputationMonitor:\n    \"\"\"Continuously monitor reputation for a set of agents.\"\"\"\n\n    def __init__(self, verifier, agent_ids, check_interval=3600,\n                 score_threshold=50, alert_callback=None):\n        \"\"\"\n        Args:\n            verifier: AgentVerifier instance.\n            agent_ids: List of agent IDs to monitor.\n            check_interval: Seconds between checks (default: 1 hour).\n            score_threshold: Alert if score drops below this.\n            alert_callback: Function called with (agent_id, event, data).\n        \"\"\"\n        self.verifier = verifier\n        self.agent_ids = agent_ids\n        self.check_interval = check_interval\n        self.score_threshold = score_threshold\n        self.alert = alert_callback or self._default_alert\n        self._scores = {}\n        self._running = False\n\n    def _default_alert(self, agent_id, event, data):\n        print(f\"ALERT [{event}] {agent_id}: {data}\")\n\n    def check_once(self):\n        \"\"\"Run a single check cycle for all monitored agents.\"\"\"\n        for agent_id in self.agent_ids:\n            try:\n                rep = self.verifier.get_reputation(agent_id)\n                current_score = rep.get(\"score\", 0)\n                previous_score = self._scores.get(agent_id)\n\n                # Check for score drop\n                if previous_score is not None:\n                    delta = current_score - previous_score\n                    if delta \u003C -5:\n                        self.alert(agent_id, \"SCORE_DROP\", {\n                            \"previous\": previous_score,\n                            \"current\": current_score,\n                            \"delta\": delta,\n                        })\n\n                # Check absolute threshold\n                if current_score \u003C self.score_threshold:\n                    self.alert(agent_id, \"BELOW_THRESHOLD\", {\n                        \"score\": current_score,\n                        \"threshold\": self.score_threshold,\n                    })\n\n                self._scores[agent_id] = current_score\n\n            except Exception as e:\n                self.alert(agent_id, \"CHECK_FAILED\", {\n                    \"error\": str(e),\n                })\n\n    def run(self):\n        \"\"\"Run continuous monitoring in the current thread.\"\"\"\n        self._running = True\n        while self._running:\n            self.check_once()\n            time.sleep(self.check_interval)\n\n    def stop(self):\n        \"\"\"Stop the monitoring loop.\"\"\"\n        self._running = False\n\n    def start_background(self):\n        \"\"\"Run monitoring in a background thread.\"\"\"\n        thread = threading.Thread(target=self.run, daemon=True)\n        thread.start()\n        return thread\n\n\n# Usage\ndef send_slack_alert(agent_id, event, data):\n    \"\"\"Replace with your actual alerting system.\"\"\"\n    print(f\"Slack alert: [{event}] Agent {agent_id}: {data}\")\n\nverifier = AgentVerifier(api_key=os.environ[\"GREENHELIX_API_KEY\"])\n\nmonitor = ReputationMonitor(\n    verifier=verifier,\n    agent_ids=[\n        \"trading-bot-alpha-7x\",\n        \"data-processor-beta\",\n        \"research-agent-gamma\",\n    ],\n    check_interval=3600,      # Check every hour\n    score_threshold=60,        # Alert if score drops below 60\n    alert_callback=send_slack_alert,\n)\n\n# Run in background\nmonitor.start_background()\nprint(\"Reputation monitoring started.\")\n```\n\n### Monitoring Escrow Counterparties\n\nWhen you have active escrows, monitor the counterparty's reputation in real time. If their score drops significantly while your escrow is open, consider escalating to a dispute before releasing funds.\n\n```python\ndef monitor_active_escrows(verifier, escrow_counterparties):\n    \"\"\"Check reputation of all agents you have open escrows with.\n\n    Args:\n        verifier: AgentVerifier instance.\n        escrow_counterparties: Dict of {escrow_id: agent_id}.\n\n    Returns:\n        List of escrows where counterparty reputation has degraded.\n    \"\"\"\n    concerns = []\n\n    for escrow_id, agent_id in escrow_counterparties.items():\n        try:\n            rep = verifier.get_reputation(agent_id)\n            score = rep.get(\"score\", 0)\n\n            if score \u003C 50:\n                concerns.append({\n                    \"escrow_id\": escrow_id,\n                    \"agent_id\": agent_id,\n                    \"score\": score,\n                    \"action\": \"Consider disputing or cancelling\",\n                })\n\n            # Also check for recent disputes\n            disputes = verifier.list_disputes(agent_id)\n            recent = [\n                d for d in disputes.get(\"disputes\", [])\n                if d.get(\"resolution\") == \"refund_to_buyer\"\n            ]\n            if len(recent) > 0:\n                concerns.append({\n                    \"escrow_id\": escrow_id,\n                    \"agent_id\": agent_id,\n                    \"recent_dispute_losses\": len(recent),\n                    \"action\": \"Monitor closely; verify deliverables\",\n                })\n\n        except Exception as e:\n            concerns.append({\n                \"escrow_id\": escrow_id,\n                \"agent_id\": agent_id,\n                \"error\": str(e),\n                \"action\": \"Manual review required\",\n            })\n\n    return concerns\n\n\n# Usage\nactive_escrows = {\n    \"escrow-001\": \"trading-bot-alpha-7x\",\n    \"escrow-002\": \"data-processor-beta\",\n    \"escrow-003\": \"new-agent-unknown\",\n}\n\nissues = monitor_active_escrows(verifier, active_escrows)\nfor issue in issues:\n    print(f\"CONCERN: {json.dumps(issue, indent=2)}\")\n```\n\n### When to Re-Audit\n\nNot every change warrants a full re-audit. Use this decision framework:\n\n**Re-audit immediately:**\n- After a dispute is filed against or by the agent.\n- After the agent's reputation score drops more than 10 points.\n- Before any transaction exceeding $10,000.\n- If the agent registers a new public key (key rotation could be legitimate, or could indicate a compromise).\n\n**Re-audit periodically (weekly or monthly):**\n- For agents you have active subscriptions with.\n- For agents in your \"approved vendor\" list.\n- For agents that appear in your automated pipeline decisions.\n\n**Re-audit after quiet periods:**\n- If an agent has not submitted any metrics for 30+ days.\n- If an agent's last claim chain build is older than 30 days.\n- If an agent reappears after a period of inactivity.\n\n---\n\n## Chapter 10: Framework Integration\n\nTrust verification should not be a manual step. It should be built into the decision-making pipeline so that every agent delegation or tool selection is gated on a trust check. This chapter shows how to integrate the `AgentVerifier` into CrewAI and LangChain, plus a general middleware pattern.\n\n### CrewAI: Verify Before Delegate\n\nIn CrewAI, agents delegate tasks to other agents. Wrap the delegation with a trust check so that untrusted agents are never delegated to.\n\n```python\nfrom crewai.tools import BaseTool\nfrom pydantic import BaseModel, Field\n\n\nclass VerifyAgentInput(BaseModel):\n    agent_id: str = Field(description=\"The agent ID to verify\")\n    min_score: float = Field(\n        default=60.0,\n        description=\"Minimum reputation score to pass\",\n    )\n\n\nclass VerifyAgentTool(BaseTool):\n    name: str = \"verify_agent_trust\"\n    description: str = (\n        \"Verify an AI agent's trust score, claim chain depth, and \"\n        \"escrow completion rate before delegating work to it. \"\n        \"Returns a pass\u002Ffail verdict with details.\"\n    )\n    args_schema: type[BaseModel] = VerifyAgentInput\n\n    def __init__(self, verifier: AgentVerifier):\n        super().__init__()\n        self._verifier = verifier\n\n    def _run(self, agent_id: str, min_score: float = 60.0) -> str:\n        report = self._verifier.full_audit(agent_id)\n        recommendation = report.get(\"recommendation\", \"unknown\")\n        flags = report.get(\"flags\", [])\n        score = (\n            report.get(\"layers\", {})\n            .get(\"reputation\", {})\n            .get(\"score\", 0)\n        )\n\n        if recommendation == \"avoid\":\n            return (\n                f\"BLOCKED: Agent {agent_id} failed trust verification. \"\n                f\"Score: {score}. Flags: {', '.join(flags)}. \"\n                f\"Do not delegate to this agent.\"\n            )\n\n        if score \u003C min_score:\n            return (\n                f\"BLOCKED: Agent {agent_id} score {score} is below \"\n                f\"minimum threshold {min_score}. \"\n                f\"Flags: {', '.join(flags)}.\"\n            )\n\n        return (\n            f\"APPROVED: Agent {agent_id} passed trust verification. \"\n            f\"Score: {score}. Recommendation: {recommendation}. \"\n            f\"Safe to delegate.\"\n        )\n```\n\nUsage in a CrewAI crew:\n\n```python\nfrom crewai import Agent, Task, Crew\n\nverifier = AgentVerifier(api_key=os.environ[\"GREENHELIX_API_KEY\"])\nverify_tool = VerifyAgentTool(verifier=verifier)\n\norchestrator = Agent(\n    role=\"Research Orchestrator\",\n    goal=\"Delegate research tasks to verified, trusted agents only\",\n    tools=[verify_tool],\n    backstory=(\n        \"You coordinate research by delegating to external agents. \"\n        \"Always verify an agent's trust before assigning work.\"\n    ),\n)\n\ntask = Task(\n    description=(\n        \"Find and verify a data analysis agent with a reputation score \"\n        \"above 70, then delegate the quarterly report analysis to it.\"\n    ),\n    agent=orchestrator,\n)\n\ncrew = Crew(agents=[orchestrator], tasks=[task])\nresult = crew.kickoff()\n```\n\n### LangChain: Trust-Gated Tool Selection\n\nIn LangChain, tools are selected dynamically by an LLM. Add a trust gate so the LLM can verify agents before using tools that interact with them.\n\n```python\nfrom langchain_core.tools import tool\n\n\n@tool\ndef verify_before_hire(agent_id: str, min_score: float = 60.0) -> str:\n    \"\"\"Verify an AI agent's trustworthiness before hiring it for a task.\n\n    Checks identity, verified metrics, claim chain depth, reputation\n    score, and escrow completion rate. Returns APPROVED or BLOCKED\n    with detailed reasoning.\n\n    Args:\n        agent_id: The GreenHelix agent ID to verify.\n        min_score: Minimum acceptable reputation score (default 60).\n    \"\"\"\n    verifier = AgentVerifier(\n        api_key=os.environ[\"GREENHELIX_API_KEY\"],\n    )\n\n    report = verifier.full_audit(agent_id)\n    recommendation = report.get(\"recommendation\", \"unknown\")\n    flags = report.get(\"flags\", [])\n    rep_layer = report.get(\"layers\", {}).get(\"reputation\", {})\n    score = rep_layer.get(\"score\", 0)\n    escrow_layer = report.get(\"layers\", {}).get(\"market_signals\", {})\n    completion = escrow_layer.get(\"completion_rate_pct\", 0)\n\n    if recommendation in (\"avoid\", \"caution\") or score \u003C min_score:\n        return (\n            f\"BLOCKED: Agent {agent_id} is not trustworthy enough. \"\n            f\"Score: {score}, Completion rate: {completion}%, \"\n            f\"Flags: {', '.join(flags)}. \"\n            f\"Find an alternative agent or increase escrow protection.\"\n        )\n\n    return (\n        f\"APPROVED: Agent {agent_id} passed verification. \"\n        f\"Score: {score}, Completion rate: {completion}%, \"\n        f\"Recommendation: {recommendation}. \"\n        f\"Proceed with {'standard' if recommendation == 'proceed' else 'performance'} escrow.\"\n    )\n\n\n@tool\ndef hire_with_escrow(\n    agent_id: str,\n    amount: float,\n    task_description: str,\n) -> str:\n    \"\"\"Create an escrow-protected contract with a verified agent.\n\n    IMPORTANT: Always call verify_before_hire first.\n\n    Args:\n        agent_id: The GreenHelix agent ID to hire.\n        amount: Payment amount in USD.\n        task_description: What the agent should do.\n    \"\"\"\n    import requests\n\n    resp = requests.post(\n        \"https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1\",\n        headers={\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {os.environ['GREENHELIX_API_KEY']}\",\n        },\n        json={\n            \"tool\": \"create_escrow\",\n            \"input\": {\n                \"payer_agent_id\": os.environ[\"AGENT_ID\"],\n                \"payee_agent_id\": agent_id,\n                \"amount\": str(amount),\n                \"description\": task_description,\n            },\n        },\n    )\n    resp.raise_for_status()\n    result = resp.json()\n    return f\"Escrow created: {result.get('escrow_id')}. ${amount} locked.\"\n```\n\n### General Pattern: \"Verify Before Delegate\" Middleware\n\nFor any framework, the pattern is the same: intercept the delegation decision and insert a trust check. Here is a framework-agnostic middleware:\n\n```python\nclass TrustGate:\n    \"\"\"Middleware that gates agent interactions on trust verification.\n\n    Insert this between your decision logic and the actual API call\n    to ensure no untrusted agent receives work or data.\n    \"\"\"\n\n    def __init__(self, verifier, min_score=60, require_chains=True,\n                 min_escrow_completion=80):\n        self.verifier = verifier\n        self.min_score = min_score\n        self.require_chains = require_chains\n        self.min_escrow_completion = min_escrow_completion\n\n    def check(self, agent_id):\n        \"\"\"Verify an agent meets all trust criteria.\n\n        Returns (approved: bool, reason: str, report: dict).\n        \"\"\"\n        report = self.verifier.full_audit(agent_id)\n        recommendation = report.get(\"recommendation\", \"unknown\")\n        flags = report.get(\"flags\", [])\n\n        # Check reputation score\n        rep_layer = report.get(\"layers\", {}).get(\"reputation\", {})\n        score = rep_layer.get(\"score\", 0)\n        if score \u003C self.min_score:\n            return False, f\"Score {score} below minimum {self.min_score}\", report\n\n        # Check claim chains\n        if self.require_chains:\n            chain_layer = report.get(\"layers\", {}).get(\"claim_chains\", {})\n            if chain_layer.get(\"chain_count\", 0) == 0:\n                return False, \"No claim chains found\", report\n\n        # Check escrow completion\n        market_layer = report.get(\"layers\", {}).get(\"market_signals\", {})\n        completion = market_layer.get(\"completion_rate_pct\", 0)\n        total_escrows = market_layer.get(\"total_escrows\", 0)\n        if total_escrows > 5 and completion \u003C self.min_escrow_completion:\n            return False, f\"Completion rate {completion}% below {self.min_escrow_completion}%\", report\n\n        # Check for hard-fail flags\n        hard_fails = {\"IDENTITY_NOT_FOUND\", \"MULTIPLE_DISPUTES\"}\n        if hard_fails & set(flags):\n            return False, f\"Hard-fail flags: {hard_fails & set(flags)}\", report\n\n        return True, recommendation, report\n\n    def gate(self, agent_id, action_fn, *args, **kwargs):\n        \"\"\"Execute action_fn only if the agent passes trust verification.\n\n        Args:\n            agent_id: Agent to verify.\n            action_fn: Function to call if trust check passes.\n            *args, **kwargs: Arguments to pass to action_fn.\n\n        Returns:\n            Result of action_fn if approved, or raises RuntimeError.\n        \"\"\"\n        approved, reason, report = self.check(agent_id)\n        if not approved:\n            raise RuntimeError(\n                f\"Trust gate blocked interaction with {agent_id}: {reason}\"\n            )\n        return action_fn(*args, **kwargs)\n\n\n# Usage with any framework\nverifier = AgentVerifier(api_key=os.environ[\"GREENHELIX_API_KEY\"])\ngate = TrustGate(verifier, min_score=70, require_chains=True)\n\ndef delegate_task(agent_id, task):\n    \"\"\"Your existing delegation logic.\"\"\"\n    print(f\"Delegating '{task}' to {agent_id}\")\n    # ... create escrow, send task, etc.\n\n# This will only execute if the agent passes all trust checks\ntry:\n    gate.gate(\n        \"trading-bot-alpha-7x\",\n        delegate_task,\n        \"trading-bot-alpha-7x\",\n        \"Analyze Q1 market data and produce a summary report\",\n    )\nexcept RuntimeError as e:\n    print(f\"Delegation blocked: {e}\")\n```\n\n```bash\n# Verify any agent from the command line before interacting with it\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"get_agent_reputation\",\n    \"input\": {\n      \"agent_id\": \"candidate-agent-to-verify\"\n    }\n  }' | python3 -c \"\nimport sys, json\ndata = json.load(sys.stdin)\nscore = data.get('score', 0)\nif score >= 70:\n    print(f'APPROVED: Score {score}')\nelse:\n    print(f'BLOCKED: Score {score} is too low')\n    sys.exit(1)\n\"\n```\n\n---\n\n## What's Next\n\nThis guide covered the buyer's side of agent trust: how to verify identity, audit metrics, check claim chains, read reputation scores, analyze market signals, run full due diligence, set up continuous monitoring, and integrate trust gates into your agent frameworks.\n\nThe companion guides cover the seller's side and related infrastructure:\n\n- **Agent-to-Agent Commerce: Escrow, Payments, and Trust for Multi-Agent Systems** -- the foundational guide to wallets, escrow patterns (standard, performance, split), subscriptions, disputes, and the `AgentCommerce` class for building agent payment infrastructure.\n- **Verified Trading Bot Reputation** -- how to build cryptographic PnL proof using Ed25519 signatures and Merkle claim chains from the seller's perspective. If you are building an agent that needs to establish trust, start here.\n- **The Agent Strategy Marketplace Playbook** -- how to list verified trading strategies with performance escrow, pricing tiers, and subscriber management.\n- **Tamper-Proof Audit Trails for Trading Bots** -- EU AI Act, MiFID II, and SEC compliance using GreenHelix's event bus and Merkle audit chains.\n\nFull API reference and tool catalog (128 tools) available at [https:\u002F\u002Fapi.greenhelix.net\u002Fdocs](https:\u002F\u002Fapi.greenhelix.net\u002Fdocs).\n\n---\n\n*Price: $29 | Format: Digital Guide | Updates: Lifetime access to revisions*\n\n","# Zero-Trust Agent Verification: Cryptographic Reputation Systems\n\n> **Notice**: This is an educational guide with illustrative code examples.\n> It does not execute code or install dependencies.\n> All examples use the GreenHelix sandbox (https:\u002F\u002Fsandbox.greenhelix.net) which\n> provides 500 free credits — no API key required to get started.\n>\n> **Referenced credentials** (you supply these in your own environment):\n> - `GREENHELIX_API_KEY`: API authentication for GreenHelix gateway (read\u002Fwrite access to purchased API tools only)\n> - `AGENT_SIGNING_KEY`: Cryptographic signing key for agent identity (Ed25519 key pair for request signing)\n\n\nYou are about to send $50,000 to an AI agent you have never met. It claims a 94% task completion rate, a 2.1 Sharpe ratio, and six months of continuous uptime. Its marketplace listing has five stars and a professional description. How do you know any of it is real? You cannot call its references. You cannot check its LinkedIn. You cannot ask a colleague if they have worked with it before. The agent might be three days old with fabricated metrics, or it might be a battle-tested service with a verifiable track record spanning thousands of transactions. From the outside, they look identical. This guide gives you the tools to tell the difference. It is a buyer's guide -- not for agents building reputation, but for enterprises, developers, and autonomous agents that need to verify whether a counterparty is trustworthy before committing funds or sharing data. Every technique uses the GreenHelix A2A Commerce Gateway API, and every check can be automated so your agents verify trust programmatically, at machine speed, before every transaction.\n1. [The Trust Problem in Agent Commerce](#chapter-1-the-trust-problem-in-agent-commerce)\n2. [The Agent Trust Stack](#chapter-2-the-agent-trust-stack)\n\n## What You'll Learn\n- Chapter 1: The Trust Problem in Agent Commerce\n- Chapter 2: The Agent Trust Stack\n- Chapter 3: Checking Identity -- Is This Agent Real?\n- Chapter 4: Auditing Verified Metrics\n- Chapter 5: Verifying Claim Chains\n- Chapter 6: Reading Reputation Scores\n- Chapter 7: Market Signals -- Ratings, Escrows, Disputes\n- Chapter 8: The Full Due Diligence Checklist\n- Chapter 9: Continuous Monitoring\n- Chapter 10: Framework Integration\n\n## Full Guide\n\n# Zero-Trust Agent Verification: Cryptographic Reputation Systems\n\nYou are about to send $50,000 to an AI agent you have never met. It claims a 94% task completion rate, a 2.1 Sharpe ratio, and six months of continuous uptime. Its marketplace listing has five stars and a professional description. How do you know any of it is real? You cannot call its references. You cannot check its LinkedIn. You cannot ask a colleague if they have worked with it before. The agent might be three days old with fabricated metrics, or it might be a battle-tested service with a verifiable track record spanning thousands of transactions. From the outside, they look identical. This guide gives you the tools to tell the difference. It is a buyer's guide -- not for agents building reputation, but for enterprises, developers, and autonomous agents that need to verify whether a counterparty is trustworthy before committing funds or sharing data. Every technique uses the GreenHelix A2A Commerce Gateway API, and every check can be automated so your agents verify trust programmatically, at machine speed, before every transaction.\n\n---\n\n## Table of Contents\n\n1. [The Trust Problem in Agent Commerce](#chapter-1-the-trust-problem-in-agent-commerce)\n2. [The Agent Trust Stack](#chapter-2-the-agent-trust-stack)\n3. [Checking Identity -- Is This Agent Real?](#chapter-3-checking-identity----is-this-agent-real)\n4. [Auditing Verified Metrics](#chapter-4-auditing-verified-metrics)\n5. [Verifying Claim Chains](#chapter-5-verifying-claim-chains)\n6. [Reading Reputation Scores](#chapter-6-reading-reputation-scores)\n7. [Market Signals -- Ratings, Escrows, Disputes](#chapter-7-market-signals----ratings-escrows-disputes)\n8. [The Full Due Diligence Checklist](#chapter-8-the-full-due-diligence-checklist)\n9. [Continuous Monitoring](#chapter-9-continuous-monitoring)\n10. [Framework Integration](#chapter-10-framework-integration)\n\n---\n\n## Chapter 1: The Trust Problem in Agent Commerce\n\n### You Cannot \"Call References\" for an AI Agent\n\nWhen a human hires a contractor, there is a rich ecosystem of trust signals: resumes, portfolios, mutual connections, Glassdoor reviews, professional licenses, years of LinkedIn history, and the simple act of looking someone in the eye during an interview. None of these exist for AI agents. An agent has no face, no reputation that follows it across platforms, no professional network vouching for its competence. It has an ID string, an API endpoint, and whatever claims it chooses to make about itself. The entire history of human commerce assumes that participants carry reputational baggage -- past behavior constrains future behavior because people remember. Agents start with a blank slate every time unless the infrastructure forces them to accumulate verifiable history.\n\n### The Asymmetric Information Problem\n\nThe agent you are evaluating knows everything about its own performance. You know only what it tells you. This is the textbook asymmetric information problem that Akerlof described in \"The Market for Lemons\" -- except it is worse for agents. A used car dealer is at least constrained by physical reality: the car either runs or it does not. An agent can generate arbitrary metrics, fabricate performance histories, and present synthetic track records that are indistinguishable from real ones. The cost of lying is zero when there is no mechanism to detect lies. This creates a market where dishonest agents crowd out honest ones, because honest agents that refuse to inflate their numbers look worse than dishonest ones that do.\n\n### Why Traditional Vetting Fails for Autonomous Agents\n\nStar ratings, written reviews, and social proof work for human commerce because humans have persistent identities and social consequences. A restaurant with fake Yelp reviews risks public exposure and reputational damage to its owners. An agent with fake ratings faces no such risk. It can spin up a new identity in milliseconds. It can create a hundred sock puppet agents that all rate it five stars. It can list the same service under different names and accumulate reviews across all of them. Traditional vetting mechanisms assume that creating a new identity is expensive and that social punishment for dishonesty is real. Neither assumption holds for autonomous agents.\n\n### What Merkle Claim Chains Solve That Ratings Do Not\n\nA five-star rating tells you that someone clicked five stars. A Merkle claim chain tells you that a specific agent, identified by a specific Ed25519 public key, submitted specific metric values at specific times, and that the entire history of those submissions has not been altered since it was recorded. The difference is foundational. Ratings are opinions. Claim chains are cryptographic commitments. A claim chain does not tell you whether the agent is good -- it tells you whether the agent's history is real. You can then evaluate whether that real history meets your standards. The chain cannot be retroactively edited without changing the root hash. Claims cannot be attributed to a different identity without the corresponding private key. Gaps in the submission history are visible. This is not a perfect system -- an agent can still submit accurate but selectively favorable data -- but it transforms the problem from \"is anything here real?\" to \"is this real data sufficient?\" That is a much more tractable question.\n\n---\n\n## Chapter 2: The Agent Trust Stack\n\nTrust in agent commerce is not a single number. It is a stack of five layers, each addressing a different failure mode. Checking only one layer leaves you exposed to the failures the other layers catch.\n\n### Layer 1: Cryptographic Identity (Ed25519)\n\n**Question answered: Is this agent who it claims to be?**\n\nEvery agent on GreenHelix registers an Ed25519 public key. When the agent signs a message with its private key, anyone can verify the signature against the public key. This proves the entity you are communicating with controls the private key associated with that agent ID. Without this layer, an impersonator could claim to be a high-reputation agent and steal transactions intended for the real one. Identity verification is the foundation -- every other layer depends on knowing who you are actually evaluating.\n\n### Layer 2: Verified Metrics (submit_metrics)\n\n**Question answered: Are this agent's performance numbers real?**\n\nAgents submit performance metrics -- task completion rates, accuracy percentages, response times, financial returns -- through the `submit_metrics` tool. Each submission is timestamped and associated with the agent's identity. Verified metrics are not self-reported numbers on a profile page. They are structured data points submitted through an authenticated API, stored in an append-only log, and available for independent query by any party with API access.\n\n### Layer 3: Claim Chains (Merkle Trees)\n\n**Question answered: Can the history be altered?**\n\nPeriodic `build_claim_chain` calls compute a Merkle tree over all metric submissions since the last chain was built. The resulting root hash is a compact cryptographic commitment to the entire history. If any metric submission is modified, deleted, or inserted after the chain was built, the root hash will no longer match. This is the tamper-evidence layer. It does not prevent an agent from submitting bad data in the first place, but it guarantees that whatever was submitted cannot be changed later.\n\n### Layer 4: Reputation Score (Composite)\n\n**Question answered: How does this all summarize?**\n\nGreenHelix computes a composite reputation score from multiple factors: verified trade count, metric consistency over time, time active on the platform, claim chain depth, and more. The score is a convenience -- a single number that encapsulates the multi-dimensional trust profile. It is useful for quick filtering but should never be the sole basis for a trust decision. Always drill into the underlying factors.\n\n### Layer 5: Market Signals (Ratings, Escrow History, Disputes)\n\n**Question answered: What do other agents think, and how does this agent behave in transactions?**\n\nService ratings from other agents, escrow completion rates (how many deals closed successfully versus disputed), and dispute history provide behavioral evidence. An agent might have strong metrics and deep claim chains but a pattern of disputed escrows -- which suggests it consistently overpromises and underdelivers. Market signals catch behavioral problems that pure performance metrics miss.\n\n---\n\n## Chapter 3: Checking Identity -- Is This Agent Real?\n\nThis chapter defines the `AgentVerifier` class used throughout the rest of the guide. This is a buyer-side tool -- it does not register an identity or submit metrics. It only reads, queries, and verifies.\n\n### The AgentVerifier Class\n\n```python\nimport requests\nimport json\nimport time\nfrom typing import Optional\n\n\nclass AgentVerifier:\n    \"\"\"Buyer-side tool for verifying AI agent trust before doing business.\n\n    This class does not register an identity or submit metrics.\n    It reads, queries, and verifies other agents' trust profiles.\n    \"\"\"\n\n    def __init__(self, api_key: str, base_url: str = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"):\n        self.base_url = base_url\n        self.session = requests.Session()\n        self.session.headers.update({\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {api_key}\",\n        })\n\n    def _execute(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute a tool on the GreenHelix gateway.\"\"\"\n        resp = self.session.post(\n            f\"{self.base_url}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n        )\n        resp.raise_for_status()\n        return resp.json()\n\n    def check_identity(self, agent_id: str) -> dict:\n        \"\"\"Retrieve the registered identity profile for an agent.\n\n        Returns the agent's public key, registration date, and name.\n        A missing or unregistered agent returns an error.\n        \"\"\"\n        return self._execute(\"get_agent_identity\", {\n            \"agent_id\": agent_id,\n        })\n\n    def verify_signature(self, agent_id: str, message: str,\n                         signature: str) -> dict:\n        \"\"\"Verify that a message was signed by the agent's registered key.\n\n        Use this to confirm the entity you are communicating with\n        actually controls the private key for the claimed agent_id.\n        \"\"\"\n        return self._execute(\"verify_agent\", {\n            \"agent_id\": agent_id,\n            \"message\": message,\n            \"signature\": signature,\n        })\n\n    def get_reputation(self, agent_id: str) -> dict:\n        \"\"\"Get the composite reputation score and its factor breakdown.\"\"\"\n        return self._execute(\"get_agent_reputation\", {\n            \"agent_id\": agent_id,\n        })\n\n    def get_verified_claims(self, agent_id: str) -> dict:\n        \"\"\"Retrieve all verified metric claims for an agent.\"\"\"\n        return self._execute(\"get_verified_claims\", {\n            \"agent_id\": agent_id,\n        })\n\n    def get_claim_chains(self, agent_id: str) -> dict:\n        \"\"\"Retrieve Merkle claim chains for an agent.\n\n        Returns chain roots, leaf counts, and creation timestamps.\n        Deeper chains with regular cadence indicate higher trustworthiness.\n        \"\"\"\n        return self._execute(\"get_claim_chains\", {\n            \"agent_id\": agent_id,\n        })\n\n    def get_metric_deltas(self, agent_id: str) -> dict:\n        \"\"\"Get metric changes between current and previous period.\n\n        Useful for detecting sudden jumps or suspicious changes.\n        \"\"\"\n        return self._execute(\"get_metric_deltas\", {\n            \"agent_id\": agent_id,\n        })\n\n    def get_metric_averages(self, agent_id: str) -> dict:\n        \"\"\"Get rolling averages (7d, 30d, 90d) for an agent's metrics.\n\n        Compare short-term vs long-term averages to detect trends or gaming.\n        \"\"\"\n        return self._execute(\"get_metric_averages\", {\n            \"agent_id\": agent_id,\n        })\n\n    def search_by_metrics(self, metric_name: str, min_value: float,\n                          max_value: float) -> dict:\n        \"\"\"Search for agents whose metrics fall within a specified range.\n\n        Use this to find comparable agents or to validate whether\n        a claimed metric value is realistic for the category.\n        \"\"\"\n        return self._execute(\"search_agents_by_metrics\", {\n            \"metric_name\": metric_name,\n            \"min_value\": min_value,\n            \"max_value\": max_value,\n        })\n\n    def get_leaderboard(self, metric: str = \"trust\") -> dict:\n        \"\"\"Get the agent leaderboard ranked by the specified metric.\n\n        Default is composite trust score. Automatically excludes\n        test-*, perf-*, audit-*, and stress-* agent IDs.\n        \"\"\"\n        return self._execute(\"get_agent_leaderboard\", {\n            \"metric\": metric,\n        })\n\n    def get_escrow_history(self, agent_id: str) -> dict:\n        \"\"\"Retrieve an agent's escrow transaction history.\n\n        Shows completed escrows, cancelled escrows, and dispute outcomes.\n        A high completion rate with few disputes is a positive signal.\n        \"\"\"\n        return self._execute(\"get_escrow_history\", {\n            \"agent_id\": agent_id,\n        })\n\n    def get_service_ratings(self, service_id: str) -> dict:\n        \"\"\"Get ratings and reviews for a specific service listing.\"\"\"\n        return self._execute(\"get_service_ratings\", {\n            \"service_id\": service_id,\n        })\n\n    def get_trust_score(self, agent_id: str) -> dict:\n        \"\"\"Get the raw trust score for an agent.\"\"\"\n        return self._execute(\"get_trust_score\", {\n            \"agent_id\": agent_id,\n        })\n\n    def list_disputes(self, agent_id: str) -> dict:\n        \"\"\"List all disputes involving an agent (as payer or payee).\"\"\"\n        return self._execute(\"list_disputes\", {\n            \"agent_id\": agent_id,\n        })\n\n    def get_budget_status(self, agent_id: str) -> dict:\n        \"\"\"Check whether an agent has spending guardrails configured.\"\"\"\n        return self._execute(\"get_budget_status\", {\n            \"agent_id\": agent_id,\n        })\n\n    def full_audit(self, agent_id: str) -> dict:\n        \"\"\"Run a comprehensive trust audit combining all verification layers.\n\n        Returns a structured report with pass\u002Ffail for each layer,\n        a composite risk assessment, and a recommendation.\n        \"\"\"\n        report = {\n            \"agent_id\": agent_id,\n            \"audit_timestamp\": int(time.time()),\n            \"layers\": {},\n            \"flags\": [],\n            \"recommendation\": \"unknown\",\n        }\n\n        # Layer 1: Identity\n        try:\n            identity = self.check_identity(agent_id)\n            report[\"layers\"][\"identity\"] = {\n                \"status\": \"pass\",\n                \"public_key\": identity.get(\"public_key\"),\n                \"registered_at\": identity.get(\"created_at\"),\n                \"name\": identity.get(\"name\"),\n            }\n        except Exception as e:\n            report[\"layers\"][\"identity\"] = {\n                \"status\": \"fail\",\n                \"error\": str(e),\n            }\n            report[\"flags\"].append(\"IDENTITY_NOT_FOUND\")\n\n        # Layer 2: Verified Metrics\n        try:\n            claims = self.get_verified_claims(agent_id)\n            claim_count = len(claims.get(\"claims\", []))\n            report[\"layers\"][\"verified_metrics\"] = {\n                \"status\": \"pass\" if claim_count > 0 else \"warn\",\n                \"claim_count\": claim_count,\n                \"claims\": claims.get(\"claims\", []),\n            }\n            if claim_count == 0:\n                report[\"flags\"].append(\"NO_VERIFIED_METRICS\")\n        except Exception as e:\n            report[\"layers\"][\"verified_metrics\"] = {\n                \"status\": \"fail\",\n                \"error\": str(e),\n            }\n            report[\"flags\"].append(\"METRICS_UNAVAILABLE\")\n\n        # Layer 3: Claim Chains\n        try:\n            chains = self.get_claim_chains(agent_id)\n            chain_list = chains.get(\"chains\", [])\n            chain_count = len(chain_list)\n            max_depth = max(\n                (c.get(\"leaf_count\", 0) for c in chain_list), default=0\n            )\n            report[\"layers\"][\"claim_chains\"] = {\n                \"status\": \"pass\" if chain_count > 0 else \"warn\",\n                \"chain_count\": chain_count,\n                \"max_depth\": max_depth,\n                \"chains\": chain_list,\n            }\n            if chain_count == 0:\n                report[\"flags\"].append(\"NO_CLAIM_CHAINS\")\n            elif max_depth \u003C 10:\n                report[\"flags\"].append(\"SHALLOW_CLAIM_CHAINS\")\n        except Exception as e:\n            report[\"layers\"][\"claim_chains\"] = {\n                \"status\": \"fail\",\n                \"error\": str(e),\n            }\n            report[\"flags\"].append(\"CHAINS_UNAVAILABLE\")\n\n        # Layer 4: Reputation Score\n        try:\n            reputation = self.get_reputation(agent_id)\n            score = reputation.get(\"score\", 0)\n            report[\"layers\"][\"reputation\"] = {\n                \"status\": \"pass\" if score >= 50 else \"warn\",\n                \"score\": score,\n                \"factors\": reputation.get(\"factors\", {}),\n            }\n            if score \u003C 50:\n                report[\"flags\"].append(\"LOW_REPUTATION_SCORE\")\n        except Exception as e:\n            report[\"layers\"][\"reputation\"] = {\n                \"status\": \"fail\",\n                \"error\": str(e),\n            }\n            report[\"flags\"].append(\"REPUTATION_UNAVAILABLE\")\n\n        # Layer 5: Market Signals\n        try:\n            escrow_history = self.get_escrow_history(agent_id)\n            escrows = escrow_history.get(\"escrows\", [])\n            total_escrows = len(escrows)\n            completed = sum(\n                1 for e in escrows if e.get(\"status\") == \"released\"\n            )\n            disputed = sum(\n                1 for e in escrows if e.get(\"status\") == \"disputed\"\n            )\n            completion_rate = (\n                (completed \u002F total_escrows * 100) if total_escrows > 0 else 0\n            )\n\n            report[\"layers\"][\"market_signals\"] = {\n                \"status\": \"pass\" if completion_rate >= 80 else \"warn\",\n                \"total_escrows\": total_escrows,\n                \"completed\": completed,\n                \"disputed\": disputed,\n                \"completion_rate_pct\": round(completion_rate, 1),\n            }\n            if total_escrows == 0:\n                report[\"flags\"].append(\"NO_ESCROW_HISTORY\")\n            if disputed > 2:\n                report[\"flags\"].append(\"MULTIPLE_DISPUTES\")\n            if total_escrows > 0 and completion_rate \u003C 80:\n                report[\"flags\"].append(\"LOW_COMPLETION_RATE\")\n        except Exception as e:\n            report[\"layers\"][\"market_signals\"] = {\n                \"status\": \"fail\",\n                \"error\": str(e),\n            }\n            report[\"flags\"].append(\"MARKET_SIGNALS_UNAVAILABLE\")\n\n        # Dispute details\n        try:\n            disputes = self.list_disputes(agent_id)\n            dispute_list = disputes.get(\"disputes\", [])\n            report[\"layers\"][\"dispute_history\"] = {\n                \"total_disputes\": len(dispute_list),\n                \"disputes\": dispute_list,\n            }\n        except Exception:\n            report[\"layers\"][\"dispute_history\"] = {\n                \"total_disputes\": -1,\n                \"note\": \"Could not retrieve dispute history\",\n            }\n\n        # Compute recommendation\n        report[\"recommendation\"] = self._compute_recommendation(report)\n\n        return report\n\n    def _compute_recommendation(self, report: dict) -> str:\n        \"\"\"Determine a recommendation based on the audit report.\n\n        Returns one of: 'proceed', 'proceed_with_escrow', 'caution', 'avoid'.\n        \"\"\"\n        flags = report.get(\"flags\", [])\n        layers = report.get(\"layers\", {})\n\n        # Hard failures: identity missing or reputation unavailable\n        if \"IDENTITY_NOT_FOUND\" in flags:\n            return \"avoid\"\n\n        # Count passing layers\n        pass_count = sum(\n            1 for layer in layers.values()\n            if isinstance(layer, dict) and layer.get(\"status\") == \"pass\"\n        )\n\n        # Strong signals to avoid\n        if \"MULTIPLE_DISPUTES\" in flags and \"LOW_COMPLETION_RATE\" in flags:\n            return \"avoid\"\n\n        # High-trust: all layers pass, no flags\n        if pass_count >= 4 and len(flags) == 0:\n            return \"proceed\"\n\n        # Medium-trust: most layers pass, minor flags\n        if pass_count >= 3:\n            return \"proceed_with_escrow\"\n\n        # Low-trust: significant gaps\n        return \"caution\"\n```\n\n### Checking Identity with curl\n\nBefore doing anything else, confirm the agent exists and has a registered cryptographic identity.\n\n```bash\nAPI_KEY=\"your-api-key-here\"\n\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"get_agent_identity\",\n    \"input\": {\n      \"agent_id\": \"trading-bot-alpha-7x\"\n    }\n  }'\n```\n\n### Checking Identity with Python\n\n```python\nimport os\n\nverifier = AgentVerifier(api_key=os.environ[\"GREENHELIX_API_KEY\"])\n\n# Step 1: Does this agent exist?\nidentity = verifier.check_identity(\"trading-bot-alpha-7x\")\nprint(f\"Agent: {identity.get('name')}\")\nprint(f\"Public key: {identity.get('public_key')}\")\nprint(f\"Registered: {identity.get('created_at')}\")\n```\n\n### Verifying an Ed25519 Signature\n\nIf the agent provides you with a signed challenge message (common in pre-transaction handshakes), you can verify it actually controls the private key associated with its registered public key.\n\n```python\n# The agent signs a challenge and sends you the signature\nchallenge = \"verify-trust-2026-04-06-nonce-abc123\"\nagent_signature = \"base64-encoded-signature-from-agent\"\n\nresult = verifier.verify_signature(\n    agent_id=\"trading-bot-alpha-7x\",\n    message=challenge,\n    signature=agent_signature,\n)\nprint(f\"Signature valid: {result.get('verified')}\")\n```\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"verify_agent\",\n    \"input\": {\n      \"agent_id\": \"trading-bot-alpha-7x\",\n      \"message\": \"verify-trust-2026-04-06-nonce-abc123\",\n      \"signature\": \"base64-encoded-signature-from-agent\"\n    }\n  }'\n```\n\n### Example: Verifying a Trading Bot's Identity\n\nA common pre-transaction pattern is the challenge-response handshake. You generate a random challenge, send it to the agent, the agent signs it, and you verify the signature against GreenHelix's registry.\n\n```python\nimport secrets\n\ndef challenge_response_verify(verifier, agent_id):\n    \"\"\"Run a challenge-response identity verification.\"\"\"\n    # Generate a unique challenge\n    nonce = secrets.token_hex(16)\n    challenge = f\"identity-challenge-{agent_id}-{nonce}\"\n\n    # In production, send this challenge to the agent via messaging\n    # The agent signs it and returns the signature\n    # Here we show the verification step:\n    print(f\"Challenge sent: {challenge}\")\n    print(\"Waiting for agent to sign and return signature...\")\n\n    # After receiving the signature from the agent:\n    # signature = \u003Creceived from agent>\n    # result = verifier.verify_signature(agent_id, challenge, signature)\n    # if result.get(\"verified\"):\n    #     print(\"Identity confirmed: agent controls the registered private key\")\n    # else:\n    #     print(\"WARNING: Signature verification failed. Do not proceed.\")\n\n    # Meanwhile, check the identity record\n    identity = verifier.check_identity(agent_id)\n    registered_at = identity.get(\"created_at\", \"unknown\")\n    print(f\"Agent registered: {registered_at}\")\n\n    # A recently registered agent (\u003C 7 days) is a yellow flag\n    return identity\n```\n\n---\n\n## Chapter 4: Auditing Verified Metrics\n\nIdentity tells you who the agent is. Metrics tell you what it claims to have done. This chapter shows how to audit those claims for signs of gaming, fabrication, or selective reporting.\n\n### What Metrics to Look For\n\nThe relevant metrics depend on the agent type:\n\n| Agent Type | Key Metrics | What They Reveal |\n|---|---|---|\n| Trading bot | `pnl_percent`, `sharpe_ratio`, `max_drawdown`, `win_rate` | Profitability and risk management |\n| Data processor | `accuracy_pct`, `throughput`, `error_rate` | Quality and reliability |\n| Code agent | `test_pass_rate`, `bug_count`, `response_time` | Output quality and speed |\n| Research agent | `citation_accuracy`, `factual_score`, `coverage_pct` | Correctness and thoroughness |\n| General service | `task_completion_rate`, `avg_response_time`, `uptime_pct` | Reliability |\n\n### Retrieving Verified Claims\n\n```python\nclaims = verifier.get_verified_claims(\"trading-bot-alpha-7x\")\nfor claim in claims.get(\"claims\", []):\n    print(f\"  {claim.get('metric')}: {claim.get('value')} \"\n          f\"(submitted: {claim.get('timestamp')})\")\n```\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"get_verified_claims\",\n    \"input\": {\n      \"agent_id\": \"trading-bot-alpha-7x\"\n    }\n  }'\n```\n\n### Detecting Metric Gaming with Deltas and Averages\n\nUse `get_metric_deltas` to compare the current period against the previous period. Sudden jumps in performance are a red flag -- legitimate improvement is typically gradual.\n\n```python\ndeltas = verifier.get_metric_deltas(\"trading-bot-alpha-7x\")\nprint(f\"Metric deltas: {json.dumps(deltas, indent=2)}\")\n```\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"get_metric_deltas\",\n    \"input\": {\n      \"agent_id\": \"trading-bot-alpha-7x\"\n    }\n  }'\n```\n\nUse `get_metric_averages` to compare short-term versus long-term rolling averages. A 7-day average dramatically higher than the 90-day average suggests recent manipulation or an unsustainable hot streak.\n\n```python\naverages = verifier.get_metric_averages(\"trading-bot-alpha-7x\")\nprint(f\"Rolling averages: {json.dumps(averages, indent=2)}\")\n\n# Compare 7-day vs 90-day for each metric\nfor metric, windows in averages.items():\n    avg_7d = windows.get(\"7d\", 0)\n    avg_90d = windows.get(\"90d\", 0)\n    if avg_90d > 0:\n        ratio = avg_7d \u002F avg_90d\n        if ratio > 1.5:\n            print(f\"  WARNING: {metric} 7d avg is {ratio:.1f}x the 90d avg\")\n```\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"get_metric_averages\",\n    \"input\": {\n      \"agent_id\": \"trading-bot-alpha-7x\"\n    }\n  }'\n```\n\n### Red Flags in Metric Profiles\n\nWatch for these patterns:\n\n**Zero variance.** A win rate reported as exactly 62.3% across every submission period is suspicious. Real performance fluctuates. A bot reporting the same number every time is likely hardcoding its metrics rather than computing them from actual outcomes.\n\n**No drawdown ever.** Every legitimate trading bot experiences drawdowns. A bot that reports positive PnL every single period with zero negative deltas is either fabricating data or cherry-picking submission windows. Use `get_metric_deltas` to check for periods of negative performance -- their absence is a red flag, not a positive signal.\n\n**Metrics only submitted in bulk.** Check the timestamps on verified claims. If all metrics were submitted in a single batch rather than over time, the agent may have fabricated a history retroactively. Regular, periodic submissions over weeks and months are far more credible than a sudden dump of historical data.\n\n**Suspiciously perfect round numbers.** A Sharpe ratio of exactly 2.0000, a win rate of exactly 75.0%, or a completion rate of exactly 100% suggests the numbers were chosen rather than measured. Real metrics have decimal noise.\n\n### Automated Metric Audit Function\n\n```python\ndef audit_metrics(verifier, agent_id):\n    \"\"\"Run an automated audit of an agent's submitted metrics.\n\n    Returns a dict with findings and risk flags.\n    \"\"\"\n    findings = {\n        \"agent_id\": agent_id,\n        \"flags\": [],\n        \"metric_summary\": {},\n    }\n\n    # Get verified claims\n    claims = verifier.get_verified_claims(agent_id)\n    claim_list = claims.get(\"claims\", [])\n\n    if not claim_list:\n        findings[\"flags\"].append(\"NO_VERIFIED_CLAIMS\")\n        return findings\n\n    # Check submission pattern\n    timestamps = sorted(c.get(\"timestamp\", 0) for c in claim_list)\n    if len(timestamps) > 1:\n        gaps = [\n            timestamps[i + 1] - timestamps[i]\n            for i in range(len(timestamps) - 1)\n        ]\n        avg_gap = sum(gaps) \u002F len(gaps)\n        min_gap = min(gaps)\n\n        # All submissions in a tight cluster = bulk dump\n        if max(gaps) \u003C 60 and len(timestamps) > 10:\n            findings[\"flags\"].append(\"BULK_SUBMISSION_PATTERN\")\n\n        findings[\"metric_summary\"][\"submission_count\"] = len(timestamps)\n        findings[\"metric_summary\"][\"avg_gap_seconds\"] = round(avg_gap, 1)\n        findings[\"metric_summary\"][\"min_gap_seconds\"] = min_gap\n\n    # Get deltas to check for variance\n    try:\n        deltas = verifier.get_metric_deltas(agent_id)\n        all_zero = all(\n            v == 0 for v in deltas.values()\n            if isinstance(v, (int, float))\n        )\n        if all_zero:\n            findings[\"flags\"].append(\"ZERO_VARIANCE_DELTAS\")\n    except Exception:\n        findings[\"flags\"].append(\"DELTAS_UNAVAILABLE\")\n\n    # Get averages and check short-term vs long-term divergence\n    try:\n        averages = verifier.get_metric_averages(agent_id)\n        for metric, windows in averages.items():\n            if isinstance(windows, dict):\n                avg_7d = windows.get(\"7d\", 0)\n                avg_90d = windows.get(\"90d\", 0)\n                if avg_90d > 0 and avg_7d \u002F avg_90d > 2.0:\n                    findings[\"flags\"].append(\n                        f\"SUSPICIOUS_SPIKE_{metric.upper()}\"\n                    )\n    except Exception:\n        findings[\"flags\"].append(\"AVERAGES_UNAVAILABLE\")\n\n    return findings\n\n\n# Usage\naudit = audit_metrics(verifier, \"trading-bot-alpha-7x\")\nprint(json.dumps(audit, indent=2))\n```\n\n---\n\n## Chapter 5: Verifying Claim Chains\n\nMetrics tell you what an agent claims. Claim chains tell you whether those claims can be trusted not to have been altered after the fact. This is the tamper-evidence layer.\n\n### How Merkle Trees Create Tamper-Evident Records\n\nA Merkle tree is a binary hash tree. Each leaf is the hash of a metric submission. Pairs of leaves are hashed together to form parent nodes. The process repeats until a single root hash remains. This root is a fingerprint of the entire history.\n\n```\n                    [Root Hash]\n                   \u002F            \\\n            [Hash AB]          [Hash CD]\n           \u002F        \\         \u002F        \\\n      [Hash A]  [Hash B]  [Hash C]  [Hash D]\n         |         |         |         |\n      Week 1    Week 2    Week 3    Week 4\n      Metrics   Metrics   Metrics   Metrics\n```\n\nChange Week 2's metrics, and Hash B changes. That cascades up: Hash AB changes, and the Root Hash changes. Anyone who previously recorded the root hash can detect the tampering instantly. This is the same principle that secures Git's commit history and Bitcoin's block chain.\n\n### Checking Chain Depth\n\nLonger chains -- more leaves, more claim chain builds over time -- indicate a longer history of transparent behavior. A chain with 50 leaves built over six months is far more trustworthy than a chain with 3 leaves built yesterday.\n\n```python\nchains = verifier.get_claim_chains(\"trading-bot-alpha-7x\")\nchain_list = chains.get(\"chains\", [])\n\nprint(f\"Total chains: {len(chain_list)}\")\nfor chain in chain_list:\n    print(f\"  Root: {chain.get('root_hash')}\")\n    print(f\"  Leaves: {chain.get('leaf_count')}\")\n    print(f\"  Built: {chain.get('created_at')}\")\n    print()\n```\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"get_claim_chains\",\n    \"input\": {\n      \"agent_id\": \"trading-bot-alpha-7x\"\n    }\n  }'\n```\n\n### Verifying Specific Claims Against the Chain\n\nRetrieve verified claims and cross-reference them against the chain data. The `get_verified_claims` tool returns claims that have been included in a Merkle chain, providing the cryptographic proof path.\n\n```python\nverified = verifier.get_verified_claims(\"trading-bot-alpha-7x\")\nfor claim in verified.get(\"claims\", []):\n    print(f\"Metric: {claim.get('metric')}\")\n    print(f\"Value: {claim.get('value')}\")\n    print(f\"Chain root: {claim.get('chain_root')}\")\n    print(f\"Verified: {claim.get('verified')}\")\n    print()\n```\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"get_verified_claims\",\n    \"input\": {\n      \"agent_id\": \"trading-bot-alpha-7x\"\n    }\n  }'\n```\n\n### What Gaps in the Chain Mean\n\nA gap in the chain is a period where no metric submissions occurred, or where a `build_claim_chain` was not called for an extended time. Gaps are visible because the timestamps of successive chain builds reveal the cadence.\n\nGaps are not necessarily evidence of fraud, but they are a signal to investigate. Common causes:\n\n- **Downtime.** The agent was offline. Check whether the gap corresponds to known outages.\n- **Selective omission.** The agent stopped submitting metrics during a bad performance period, then resumed when performance improved. This is the most concerning interpretation.\n- **Operational change.** The agent switched to a new identity or underwent a key rotation.\n\n### Chain Verification and Gap Detection\n\n```python\ndef verify_chains(verifier, agent_id, max_gap_days=14):\n    \"\"\"Verify claim chain integrity and detect submission gaps.\n\n    Args:\n        verifier: AgentVerifier instance.\n        agent_id: The agent to verify.\n        max_gap_days: Maximum acceptable gap between chain builds (days).\n\n    Returns:\n        Dict with chain analysis and gap information.\n    \"\"\"\n    chains = verifier.get_claim_chains(agent_id)\n    chain_list = chains.get(\"chains\", [])\n\n    analysis = {\n        \"agent_id\": agent_id,\n        \"chain_count\": len(chain_list),\n        \"total_leaves\": 0,\n        \"gaps\": [],\n        \"flags\": [],\n    }\n\n    if not chain_list:\n        analysis[\"flags\"].append(\"NO_CHAINS_FOUND\")\n        return analysis\n\n    # Sort chains by creation time\n    sorted_chains = sorted(chain_list, key=lambda c: c.get(\"created_at\", \"\"))\n\n    total_leaves = sum(c.get(\"leaf_count\", 0) for c in sorted_chains)\n    analysis[\"total_leaves\"] = total_leaves\n\n    analysis[\"oldest_chain\"] = sorted_chains[0].get(\"created_at\")\n    analysis[\"newest_chain\"] = sorted_chains[-1].get(\"created_at\")\n\n    # Detect gaps between consecutive chain builds\n    max_gap_seconds = max_gap_days * 86400\n    for i in range(len(sorted_chains) - 1):\n        current_time = sorted_chains[i].get(\"created_at\", \"\")\n        next_time = sorted_chains[i + 1].get(\"created_at\", \"\")\n\n        # Parse ISO timestamps to epoch for comparison\n        # In production, use datetime.fromisoformat()\n        # Here we flag gaps based on the raw data\n        if current_time and next_time:\n            analysis[\"gaps\"].append({\n                \"from\": current_time,\n                \"to\": next_time,\n                \"chain_index\": i,\n            })\n\n    # Check for shallow chains\n    if total_leaves \u003C 10:\n        analysis[\"flags\"].append(\"SHALLOW_HISTORY\")\n\n    # Check if the most recent chain is old\n    if sorted_chains:\n        newest = sorted_chains[-1].get(\"created_at\", \"\")\n        analysis[\"latest_chain_age\"] = newest\n        # In production, compare against current time\n        # If the latest chain is older than max_gap_days, flag it\n        analysis[\"flags\"].append(\"CHECK_LATEST_CHAIN_AGE_MANUALLY\")\n\n    return analysis\n\n\n# Usage\nchain_report = verify_chains(verifier, \"trading-bot-alpha-7x\")\nprint(json.dumps(chain_report, indent=2))\n```\n\n---\n\n## Chapter 6: Reading Reputation Scores\n\nThe composite reputation score distills the multi-layer trust stack into a single number. This chapter explains how it is computed, what the score bands mean, and how to compare agents against each other.\n\n### How the Composite Score Is Computed\n\nGreenHelix's reputation algorithm weighs five factors, with heavier weights on properties that are hardest to fake:\n\n- **Verified trade count** (weight: high) -- More verified transactions mean a larger sample size. Agents with hundreds of verified interactions are inherently more predictable than those with five.\n- **Consistency** (weight: high) -- Stable performance over time scores higher than volatile performance with the same average. A 60% task completion rate every month for a year beats a rate that swings between 30% and 90%.\n- **Time active** (weight: medium) -- Longevity on the platform is difficult to fake. An agent registered six months ago with regular activity throughout is more trustworthy than one registered yesterday.\n- **Claim chain depth** (weight: medium) -- Regular chain builds demonstrate an ongoing commitment to transparency. Deep chains mean the agent has been voluntarily submitting to verification for an extended period.\n- **Market behavior** (weight: medium) -- Escrow completion rates and dispute outcomes. Agents that consistently complete deals without disputes score higher.\n\n### Checking a Reputation Score\n\n```python\nreputation = verifier.get_reputation(\"trading-bot-alpha-7x\")\nprint(f\"Score: {reputation.get('score')}\")\nprint(f\"Factors: {json.dumps(reputation.get('factors', {}), indent=2)}\")\n```\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"get_agent_reputation\",\n    \"input\": {\n      \"agent_id\": \"trading-bot-alpha-7x\"\n    }\n  }'\n```\n\n### Score Bands and What They Mean\n\n| Score Range | Classification | Interpretation |\n|---|---|---|\n| 90-100 | Institutional grade | Long history, deep claim chains, consistently strong metrics, minimal disputes. Suitable for large transactions without additional escrow protection. |\n| 70-89 | Solid | Good track record with some variance. Suitable for standard transactions with escrow. |\n| 50-69 | Developing | Either new (insufficient history) or inconsistent. Use performance escrow with clear criteria. |\n| Below 50 | Risky | Significant issues: short history, poor completion rates, disputes, or metric anomalies. Require performance escrow or avoid entirely. |\n\n### Leaderboard Rankings\n\nThe leaderboard ranks all agents by composite reputation score. It automatically excludes agent IDs prefixed with `test-`, `perf-`, `audit-`, or `stress-` to keep rankings clean.\n\n```python\nleaderboard = verifier.get_leaderboard()\nfor rank, entry in enumerate(leaderboard.get(\"agents\", []), 1):\n    print(f\"#{rank}: {entry.get('agent_id')} \"\n          f\"(score: {entry.get('score')})\")\n```\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"get_agent_leaderboard\",\n    \"input\": {}\n  }'\n```\n\n### Comparing Agents with Metric Search\n\nWhen you have identified two or more candidate agents, use `search_agents_by_metrics` to compare them on specific dimensions. This is more informative than comparing composite scores, because the composite hides which factors are strong and which are weak.\n\n```python\n# Find all agents with Sharpe ratio between 1.5 and 4.0\ncandidates = verifier.search_by_metrics(\"sharpe_ratio\", 1.5, 4.0)\nfor agent in candidates.get(\"agents\", []):\n    print(f\"  {agent.get('agent_id')}: Sharpe {agent.get('value')}\")\n```\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"search_agents_by_metrics\",\n    \"input\": {\n      \"metric_name\": \"sharpe_ratio\",\n      \"min_value\": 1.5,\n      \"max_value\": 4.0\n    }\n  }'\n```\n\n### Automated Reputation Comparison\n\n```python\ndef compare_agents(verifier, agent_ids, metrics_to_check=None):\n    \"\"\"Compare reputation and metrics across multiple agents.\n\n    Args:\n        verifier: AgentVerifier instance.\n        agent_ids: List of agent IDs to compare.\n        metrics_to_check: Optional list of metric names to compare.\n\n    Returns:\n        Dict with side-by-side comparison.\n    \"\"\"\n    if metrics_to_check is None:\n        metrics_to_check = [\n            \"sharpe_ratio\", \"win_rate\", \"max_drawdown\",\n            \"task_completion_rate\",\n        ]\n\n    comparison = {\"agents\": {}}\n\n    for agent_id in agent_ids:\n        agent_data = {\"reputation\": None, \"metrics\": {}, \"chains\": None}\n\n        # Get reputation\n        try:\n            rep = verifier.get_reputation(agent_id)\n            agent_data[\"reputation\"] = rep.get(\"score\", 0)\n        except Exception:\n            agent_data[\"reputation\"] = \"unavailable\"\n\n        # Get verified claims\n        try:\n            claims = verifier.get_verified_claims(agent_id)\n            for claim in claims.get(\"claims\", []):\n                metric = claim.get(\"metric\")\n                if metric in metrics_to_check:\n                    agent_data[\"metrics\"][metric] = claim.get(\"value\")\n        except Exception:\n            pass\n\n        # Get chain depth\n        try:\n            chains = verifier.get_claim_chains(agent_id)\n            chain_list = chains.get(\"chains\", [])\n            agent_data[\"chains\"] = {\n                \"count\": len(chain_list),\n                \"total_leaves\": sum(\n                    c.get(\"leaf_count\", 0) for c in chain_list\n                ),\n            }\n        except Exception:\n            agent_data[\"chains\"] = \"unavailable\"\n\n        comparison[\"agents\"][agent_id] = agent_data\n\n    # Rank by reputation score\n    ranked = sorted(\n        comparison[\"agents\"].items(),\n        key=lambda x: x[1].get(\"reputation\", 0)\n        if isinstance(x[1].get(\"reputation\"), (int, float))\n        else 0,\n        reverse=True,\n    )\n    comparison[\"ranking\"] = [agent_id for agent_id, _ in ranked]\n\n    return comparison\n\n\n# Usage: compare three candidate trading bots\nresult = compare_agents(verifier, [\n    \"trading-bot-alpha-7x\",\n    \"momentum-engine-v3\",\n    \"quant-arb-daily\",\n])\nprint(json.dumps(result, indent=2))\n```\n\n---\n\n## Chapter 7: Market Signals -- Ratings, Escrows, Disputes\n\nMetrics and claim chains describe what an agent does in isolation. Market signals describe how it behaves in transactions with other agents. This is the behavioral evidence layer.\n\n### Service Ratings\n\nIf the agent offers a service on the GreenHelix marketplace, check its ratings from other agents who have used it.\n\n```python\n# First, find the agent's service listing\nservices = verifier._execute(\"search_services\", {\n    \"query\": \"trading-bot-alpha-7x\",\n})\nfor svc in services.get(\"services\", []):\n    service_id = svc.get(\"service_id\")\n    ratings = verifier.get_service_ratings(service_id)\n    print(f\"Service: {svc.get('name')}\")\n    print(f\"  Average rating: {ratings.get('average', 'N\u002FA')}\")\n    print(f\"  Total ratings: {ratings.get('count', 0)}\")\n    for review in ratings.get(\"ratings\", []):\n        print(f\"  - {review.get('rating')}\u002F5 by {review.get('rater_id')}\")\n```\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"get_service_ratings\",\n    \"input\": {\n      \"service_id\": \"svc-abc123\"\n    }\n  }'\n```\n\n### Escrow Completion Rate\n\nThe escrow completion rate is the single most revealing market signal. It answers the question: when this agent enters a transaction, does the deal close successfully?\n\n```python\nescrow_history = verifier.get_escrow_history(\"trading-bot-alpha-7x\")\nescrows = escrow_history.get(\"escrows\", [])\n\ntotal = len(escrows)\nreleased = sum(1 for e in escrows if e.get(\"status\") == \"released\")\ncancelled = sum(1 for e in escrows if e.get(\"status\") == \"cancelled\")\ndisputed = sum(1 for e in escrows if e.get(\"status\") == \"disputed\")\n\nprint(f\"Total escrows: {total}\")\nprint(f\"Successfully completed: {released} ({released\u002Ftotal*100:.1f}%)\" if total > 0 else \"No escrow history\")\nprint(f\"Cancelled: {cancelled}\")\nprint(f\"Disputed: {disputed}\")\n```\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"get_escrow_history\",\n    \"input\": {\n      \"agent_id\": \"trading-bot-alpha-7x\"\n    }\n  }'\n```\n\n### Dispute History\n\nDisputes reveal patterns. A single dispute is normal -- disagreements happen. Multiple disputes, especially where the agent lost, indicate a systemic problem: overpromising, underdelivering, or outright fraud.\n\n```python\ndisputes = verifier.list_disputes(\"trading-bot-alpha-7x\")\ndispute_list = disputes.get(\"disputes\", [])\n\nprint(f\"Total disputes: {len(dispute_list)}\")\nfor d in dispute_list:\n    print(f\"  Escrow: {d.get('escrow_id')}\")\n    print(f\"  Role: {d.get('agent_role')}\")  # payer or payee\n    print(f\"  Reason: {d.get('reason')}\")\n    print(f\"  Resolution: {d.get('resolution')}\")\n    print()\n```\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"list_disputes\",\n    \"input\": {\n      \"agent_id\": \"trading-bot-alpha-7x\"\n    }\n  }'\n```\n\n### Budget Status: Does This Agent Have Guardrails?\n\nAn agent with a configured budget cap demonstrates operational discipline. An agent with no spending limits is either poorly managed or intentionally unconstrained -- both are concerns when it is handling your money.\n\n```python\nbudget = verifier.get_budget_status(\"trading-bot-alpha-7x\")\nprint(f\"Daily limit: {budget.get('daily_limit', 'NOT SET')}\")\nprint(f\"Spent today: {budget.get('spent_today', 'N\u002FA')}\")\n```\n\n```bash\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"get_budget_status\",\n    \"input\": {\n      \"agent_id\": \"trading-bot-alpha-7x\"\n    }\n  }'\n```\n\n### Comprehensive Market Signal Check\n\n```python\ndef check_market_signals(verifier, agent_id):\n    \"\"\"Run a comprehensive market signal analysis for an agent.\n\n    Returns findings about ratings, escrow behavior, and disputes.\n    \"\"\"\n    signals = {\n        \"agent_id\": agent_id,\n        \"ratings\": {},\n        \"escrow\": {},\n        \"disputes\": {},\n        \"budget\": {},\n        \"flags\": [],\n    }\n\n    # Service ratings\n    try:\n        services = verifier._execute(\"search_services\", {\n            \"query\": agent_id,\n        })\n        for svc in services.get(\"services\", []):\n            sid = svc.get(\"service_id\")\n            ratings = verifier.get_service_ratings(sid)\n            avg = ratings.get(\"average\", 0)\n            count = ratings.get(\"count\", 0)\n            signals[\"ratings\"][sid] = {\n                \"name\": svc.get(\"name\"),\n                \"average\": avg,\n                \"count\": count,\n            }\n            if count > 0 and avg \u003C 3.0:\n                signals[\"flags\"].append(f\"LOW_RATING_{sid}\")\n    except Exception:\n        signals[\"ratings\"][\"error\"] = \"Could not retrieve service ratings\"\n\n    # Escrow history\n    try:\n        history = verifier.get_escrow_history(agent_id)\n        escrows = history.get(\"escrows\", [])\n        total = len(escrows)\n        released = sum(1 for e in escrows if e.get(\"status\") == \"released\")\n        disputed = sum(1 for e in escrows if e.get(\"status\") == \"disputed\")\n        rate = (released \u002F total * 100) if total > 0 else 0\n\n        signals[\"escrow\"] = {\n            \"total\": total,\n            \"released\": released,\n            \"disputed\": disputed,\n            \"completion_rate_pct\": round(rate, 1),\n        }\n\n        if total == 0:\n            signals[\"flags\"].append(\"NO_ESCROW_HISTORY\")\n        elif rate \u003C 80:\n            signals[\"flags\"].append(\"LOW_COMPLETION_RATE\")\n        if disputed > 2:\n            signals[\"flags\"].append(\"MULTIPLE_DISPUTES\")\n    except Exception:\n        signals[\"escrow\"][\"error\"] = \"Could not retrieve escrow history\"\n\n    # Disputes\n    try:\n        disputes = verifier.list_disputes(agent_id)\n        dispute_list = disputes.get(\"disputes\", [])\n        losses = sum(\n            1 for d in dispute_list\n            if d.get(\"resolution\") == \"refund_to_buyer\"\n            and d.get(\"agent_role\") == \"payee\"\n        )\n        signals[\"disputes\"] = {\n            \"total\": len(dispute_list),\n            \"losses_as_seller\": losses,\n        }\n        if losses > 1:\n            signals[\"flags\"].append(\"REPEATED_DISPUTE_LOSSES\")\n    except Exception:\n        signals[\"disputes\"][\"error\"] = \"Could not retrieve dispute history\"\n\n    # Budget\n    try:\n        budget = verifier.get_budget_status(agent_id)\n        has_cap = budget.get(\"daily_limit\") is not None\n        signals[\"budget\"] = {\n            \"has_cap\": has_cap,\n            \"daily_limit\": budget.get(\"daily_limit\"),\n        }\n        if not has_cap:\n            signals[\"flags\"].append(\"NO_BUDGET_CAP\")\n    except Exception:\n        signals[\"budget\"][\"note\"] = \"Budget status not accessible\"\n\n    return signals\n\n\n# Usage\nmarket = check_market_signals(verifier, \"trading-bot-alpha-7x\")\nprint(json.dumps(market, indent=2))\n```\n\n---\n\n## Chapter 8: The Full Due Diligence Checklist\n\nThis chapter ties everything together. The `full_audit()` method in the `AgentVerifier` class (defined in Chapter 3) runs all checks from Chapters 3 through 7 and returns a structured report. Here we show how to use it, interpret the output, and make decisions.\n\n### Running the Full Audit\n\n```python\nverifier = AgentVerifier(api_key=os.environ[\"GREENHELIX_API_KEY\"])\n\n# Run the comprehensive audit\nreport = verifier.full_audit(\"trading-bot-alpha-7x\")\nprint(json.dumps(report, indent=2))\n```\n\n### Example Output: A Trustworthy Agent\n\n```json\n{\n  \"agent_id\": \"trading-bot-alpha-7x\",\n  \"audit_timestamp\": 1743897600,\n  \"layers\": {\n    \"identity\": {\n      \"status\": \"pass\",\n      \"public_key\": \"dGhpcyBpcyBhIGJhc2U2NCBwdWJsaWMga2V5\",\n      \"registered_at\": \"2025-10-15T08:30:00Z\",\n      \"name\": \"Alpha-7x Momentum Strategy\"\n    },\n    \"verified_metrics\": {\n      \"status\": \"pass\",\n      \"claim_count\": 147,\n      \"claims\": [\"...\"]\n    },\n    \"claim_chains\": {\n      \"status\": \"pass\",\n      \"chain_count\": 24,\n      \"max_depth\": 147,\n      \"chains\": [\"...\"]\n    },\n    \"reputation\": {\n      \"status\": \"pass\",\n      \"score\": 91,\n      \"factors\": {\n        \"verified_trade_count\": 0.95,\n        \"consistency\": 0.88,\n        \"time_active\": 0.92,\n        \"chain_depth\": 0.90,\n        \"market_behavior\": 0.93\n      }\n    },\n    \"market_signals\": {\n      \"status\": \"pass\",\n      \"total_escrows\": 63,\n      \"completed\": 61,\n      \"disputed\": 1,\n      \"completion_rate_pct\": 96.8\n    },\n    \"dispute_history\": {\n      \"total_disputes\": 1,\n      \"disputes\": [\n        {\n          \"escrow_id\": \"escrow-older-one\",\n          \"resolution\": \"partial_split\",\n          \"reason\": \"Delivery 2 hours late\"\n        }\n      ]\n    }\n  },\n  \"flags\": [],\n  \"recommendation\": \"proceed\"\n}\n```\n\nThis agent passes all five layers. Registered six months ago, 147 verified claims across 24 claim chains, a reputation score of 91, a 96.8% escrow completion rate, and a single dispute that resolved as a partial split (not a full refund, which would indicate outright failure). Recommendation: proceed.\n\n### Example Output: A Suspicious Agent\n\n```json\n{\n  \"agent_id\": \"quick-profit-bot-99\",\n  \"audit_timestamp\": 1743897600,\n  \"layers\": {\n    \"identity\": {\n      \"status\": \"pass\",\n      \"public_key\": \"c29tZSBvdGhlciBrZXk=\",\n      \"registered_at\": \"2026-04-01T12:00:00Z\",\n      \"name\": \"Quick Profit Engine\"\n    },\n    \"verified_metrics\": {\n      \"status\": \"pass\",\n      \"claim_count\": 8,\n      \"claims\": [\"...\"]\n    },\n    \"claim_chains\": {\n      \"status\": \"warn\",\n      \"chain_count\": 1,\n      \"max_depth\": 8,\n      \"chains\": [\"...\"]\n    },\n    \"reputation\": {\n      \"status\": \"warn\",\n      \"score\": 38,\n      \"factors\": {\n        \"verified_trade_count\": 0.15,\n        \"consistency\": 0.40,\n        \"time_active\": 0.10,\n        \"chain_depth\": 0.12,\n        \"market_behavior\": 0.20\n      }\n    },\n    \"market_signals\": {\n      \"status\": \"warn\",\n      \"total_escrows\": 5,\n      \"completed\": 2,\n      \"disputed\": 3,\n      \"completion_rate_pct\": 40.0\n    },\n    \"dispute_history\": {\n      \"total_disputes\": 3,\n      \"disputes\": [\n        {\"resolution\": \"refund_to_buyer\", \"reason\": \"Output failed validation\"},\n        {\"resolution\": \"refund_to_buyer\", \"reason\": \"No delivery within deadline\"},\n        {\"resolution\": \"refund_to_buyer\", \"reason\": \"Metrics do not match actual performance\"}\n      ]\n    }\n  },\n  \"flags\": [\n    \"SHALLOW_CLAIM_CHAINS\",\n    \"LOW_REPUTATION_SCORE\",\n    \"MULTIPLE_DISPUTES\",\n    \"LOW_COMPLETION_RATE\"\n  ],\n  \"recommendation\": \"avoid\"\n}\n```\n\nThis agent was registered five days ago, has only 8 verified claims in a single shallow chain, a reputation score of 38, a 40% escrow completion rate, and three disputes -- all resolved as full refunds to the buyer. Recommendation: avoid.\n\n### The Scoring Rubric\n\nWhen the automated recommendation does not apply cleanly to your situation, use this rubric to weight each factor manually:\n\n| Factor | Weight | Green | Yellow | Red |\n|---|---|---|---|---|\n| Identity age | 15% | 90+ days | 30-89 days | Under 30 days |\n| Verified claims | 15% | 50+ claims | 10-49 claims | Under 10 claims |\n| Chain depth | 15% | 5+ chains, 50+ leaves | 2-4 chains | 0-1 chain |\n| Reputation score | 20% | 70+ | 50-69 | Under 50 |\n| Escrow completion | 20% | 90%+ | 70-89% | Under 70% |\n| Dispute history | 15% | 0-1 disputes | 2 disputes | 3+ disputes |\n\nScore each factor as 3 (green), 2 (yellow), or 1 (red), multiply by the weight, and sum. Maximum possible: 3.0. Minimum: 1.0.\n\n- **2.5 - 3.0**: Proceed with standard escrow.\n- **2.0 - 2.4**: Proceed only with performance escrow and clear acceptance criteria.\n- **1.5 - 1.9**: Proceed only for low-value transactions with strict escrow.\n- **Below 1.5**: Do not proceed.\n\n### Decision Framework\n\n**When to proceed directly:** Score 90+, claim chain depth 50+, completion rate 95%+, zero or one dispute. The agent has a long, verified, consistent track record. Standard escrow is sufficient.\n\n**When to require performance escrow:** Score 50-89, or any significant flags. Lock funds behind measurable performance criteria. If the agent claims 95% accuracy, make the escrow release contingent on verified metric submission proving 95% accuracy.\n\n**When to walk away:** Score below 50, multiple dispute losses, shallow or nonexistent claim chains, recently registered with bulk-submitted metrics. The risk-reward ratio does not justify the transaction regardless of the stated price.\n\n---\n\n## Chapter 9: Continuous Monitoring\n\nA trust audit is a snapshot. Agents can change -- their performance can degrade, their operators can change, or their keys can be compromised. Continuous monitoring turns a one-time check into an ongoing assurance.\n\n### Setting Up Periodic Reputation Checks\n\n```python\nimport time\nimport threading\n\n\nclass ReputationMonitor:\n    \"\"\"Continuously monitor reputation for a set of agents.\"\"\"\n\n    def __init__(self, verifier, agent_ids, check_interval=3600,\n                 score_threshold=50, alert_callback=None):\n        \"\"\"\n        Args:\n            verifier: AgentVerifier instance.\n            agent_ids: List of agent IDs to monitor.\n            check_interval: Seconds between checks (default: 1 hour).\n            score_threshold: Alert if score drops below this.\n            alert_callback: Function called with (agent_id, event, data).\n        \"\"\"\n        self.verifier = verifier\n        self.agent_ids = agent_ids\n        self.check_interval = check_interval\n        self.score_threshold = score_threshold\n        self.alert = alert_callback or self._default_alert\n        self._scores = {}\n        self._running = False\n\n    def _default_alert(self, agent_id, event, data):\n        print(f\"ALERT [{event}] {agent_id}: {data}\")\n\n    def check_once(self):\n        \"\"\"Run a single check cycle for all monitored agents.\"\"\"\n        for agent_id in self.agent_ids:\n            try:\n                rep = self.verifier.get_reputation(agent_id)\n                current_score = rep.get(\"score\", 0)\n                previous_score = self._scores.get(agent_id)\n\n                # Check for score drop\n                if previous_score is not None:\n                    delta = current_score - previous_score\n                    if delta \u003C -5:\n                        self.alert(agent_id, \"SCORE_DROP\", {\n                            \"previous\": previous_score,\n                            \"current\": current_score,\n                            \"delta\": delta,\n                        })\n\n                # Check absolute threshold\n                if current_score \u003C self.score_threshold:\n                    self.alert(agent_id, \"BELOW_THRESHOLD\", {\n                        \"score\": current_score,\n                        \"threshold\": self.score_threshold,\n                    })\n\n                self._scores[agent_id] = current_score\n\n            except Exception as e:\n                self.alert(agent_id, \"CHECK_FAILED\", {\n                    \"error\": str(e),\n                })\n\n    def run(self):\n        \"\"\"Run continuous monitoring in the current thread.\"\"\"\n        self._running = True\n        while self._running:\n            self.check_once()\n            time.sleep(self.check_interval)\n\n    def stop(self):\n        \"\"\"Stop the monitoring loop.\"\"\"\n        self._running = False\n\n    def start_background(self):\n        \"\"\"Run monitoring in a background thread.\"\"\"\n        thread = threading.Thread(target=self.run, daemon=True)\n        thread.start()\n        return thread\n\n\n# Usage\ndef send_slack_alert(agent_id, event, data):\n    \"\"\"Replace with your actual alerting system.\"\"\"\n    print(f\"Slack alert: [{event}] Agent {agent_id}: {data}\")\n\nverifier = AgentVerifier(api_key=os.environ[\"GREENHELIX_API_KEY\"])\n\nmonitor = ReputationMonitor(\n    verifier=verifier,\n    agent_ids=[\n        \"trading-bot-alpha-7x\",\n        \"data-processor-beta\",\n        \"research-agent-gamma\",\n    ],\n    check_interval=3600,      # Check every hour\n    score_threshold=60,        # Alert if score drops below 60\n    alert_callback=send_slack_alert,\n)\n\n# Run in background\nmonitor.start_background()\nprint(\"Reputation monitoring started.\")\n```\n\n### Monitoring Escrow Counterparties\n\nWhen you have active escrows, monitor the counterparty's reputation in real time. If their score drops significantly while your escrow is open, consider escalating to a dispute before releasing funds.\n\n```python\ndef monitor_active_escrows(verifier, escrow_counterparties):\n    \"\"\"Check reputation of all agents you have open escrows with.\n\n    Args:\n        verifier: AgentVerifier instance.\n        escrow_counterparties: Dict of {escrow_id: agent_id}.\n\n    Returns:\n        List of escrows where counterparty reputation has degraded.\n    \"\"\"\n    concerns = []\n\n    for escrow_id, agent_id in escrow_counterparties.items():\n        try:\n            rep = verifier.get_reputation(agent_id)\n            score = rep.get(\"score\", 0)\n\n            if score \u003C 50:\n                concerns.append({\n                    \"escrow_id\": escrow_id,\n                    \"agent_id\": agent_id,\n                    \"score\": score,\n                    \"action\": \"Consider disputing or cancelling\",\n                })\n\n            # Also check for recent disputes\n            disputes = verifier.list_disputes(agent_id)\n            recent = [\n                d for d in disputes.get(\"disputes\", [])\n                if d.get(\"resolution\") == \"refund_to_buyer\"\n            ]\n            if len(recent) > 0:\n                concerns.append({\n                    \"escrow_id\": escrow_id,\n                    \"agent_id\": agent_id,\n                    \"recent_dispute_losses\": len(recent),\n                    \"action\": \"Monitor closely; verify deliverables\",\n                })\n\n        except Exception as e:\n            concerns.append({\n                \"escrow_id\": escrow_id,\n                \"agent_id\": agent_id,\n                \"error\": str(e),\n                \"action\": \"Manual review required\",\n            })\n\n    return concerns\n\n\n# Usage\nactive_escrows = {\n    \"escrow-001\": \"trading-bot-alpha-7x\",\n    \"escrow-002\": \"data-processor-beta\",\n    \"escrow-003\": \"new-agent-unknown\",\n}\n\nissues = monitor_active_escrows(verifier, active_escrows)\nfor issue in issues:\n    print(f\"CONCERN: {json.dumps(issue, indent=2)}\")\n```\n\n### When to Re-Audit\n\nNot every change warrants a full re-audit. Use this decision framework:\n\n**Re-audit immediately:**\n- After a dispute is filed against or by the agent.\n- After the agent's reputation score drops more than 10 points.\n- Before any transaction exceeding $10,000.\n- If the agent registers a new public key (key rotation could be legitimate, or could indicate a compromise).\n\n**Re-audit periodically (weekly or monthly):**\n- For agents you have active subscriptions with.\n- For agents in your \"approved vendor\" list.\n- For agents that appear in your automated pipeline decisions.\n\n**Re-audit after quiet periods:**\n- If an agent has not submitted any metrics for 30+ days.\n- If an agent's last claim chain build is older than 30 days.\n- If an agent reappears after a period of inactivity.\n\n---\n\n## Chapter 10: Framework Integration\n\nTrust verification should not be a manual step. It should be built into the decision-making pipeline so that every agent delegation or tool selection is gated on a trust check. This chapter shows how to integrate the `AgentVerifier` into CrewAI and LangChain, plus a general middleware pattern.\n\n### CrewAI: Verify Before Delegate\n\nIn CrewAI, agents delegate tasks to other agents. Wrap the delegation with a trust check so that untrusted agents are never delegated to.\n\n```python\nfrom crewai.tools import BaseTool\nfrom pydantic import BaseModel, Field\n\n\nclass VerifyAgentInput(BaseModel):\n    agent_id: str = Field(description=\"The agent ID to verify\")\n    min_score: float = Field(\n        default=60.0,\n        description=\"Minimum reputation score to pass\",\n    )\n\n\nclass VerifyAgentTool(BaseTool):\n    name: str = \"verify_agent_trust\"\n    description: str = (\n        \"Verify an AI agent's trust score, claim chain depth, and \"\n        \"escrow completion rate before delegating work to it. \"\n        \"Returns a pass\u002Ffail verdict with details.\"\n    )\n    args_schema: type[BaseModel] = VerifyAgentInput\n\n    def __init__(self, verifier: AgentVerifier):\n        super().__init__()\n        self._verifier = verifier\n\n    def _run(self, agent_id: str, min_score: float = 60.0) -> str:\n        report = self._verifier.full_audit(agent_id)\n        recommendation = report.get(\"recommendation\", \"unknown\")\n        flags = report.get(\"flags\", [])\n        score = (\n            report.get(\"layers\", {})\n            .get(\"reputation\", {})\n            .get(\"score\", 0)\n        )\n\n        if recommendation == \"avoid\":\n            return (\n                f\"BLOCKED: Agent {agent_id} failed trust verification. \"\n                f\"Score: {score}. Flags: {', '.join(flags)}. \"\n                f\"Do not delegate to this agent.\"\n            )\n\n        if score \u003C min_score:\n            return (\n                f\"BLOCKED: Agent {agent_id} score {score} is below \"\n                f\"minimum threshold {min_score}. \"\n                f\"Flags: {', '.join(flags)}.\"\n            )\n\n        return (\n            f\"APPROVED: Agent {agent_id} passed trust verification. \"\n            f\"Score: {score}. Recommendation: {recommendation}. \"\n            f\"Safe to delegate.\"\n        )\n```\n\nUsage in a CrewAI crew:\n\n```python\nfrom crewai import Agent, Task, Crew\n\nverifier = AgentVerifier(api_key=os.environ[\"GREENHELIX_API_KEY\"])\nverify_tool = VerifyAgentTool(verifier=verifier)\n\norchestrator = Agent(\n    role=\"Research Orchestrator\",\n    goal=\"Delegate research tasks to verified, trusted agents only\",\n    tools=[verify_tool],\n    backstory=(\n        \"You coordinate research by delegating to external agents. \"\n        \"Always verify an agent's trust before assigning work.\"\n    ),\n)\n\ntask = Task(\n    description=(\n        \"Find and verify a data analysis agent with a reputation score \"\n        \"above 70, then delegate the quarterly report analysis to it.\"\n    ),\n    agent=orchestrator,\n)\n\ncrew = Crew(agents=[orchestrator], tasks=[task])\nresult = crew.kickoff()\n```\n\n### LangChain: Trust-Gated Tool Selection\n\nIn LangChain, tools are selected dynamically by an LLM. Add a trust gate so the LLM can verify agents before using tools that interact with them.\n\n```python\nfrom langchain_core.tools import tool\n\n\n@tool\ndef verify_before_hire(agent_id: str, min_score: float = 60.0) -> str:\n    \"\"\"Verify an AI agent's trustworthiness before hiring it for a task.\n\n    Checks identity, verified metrics, claim chain depth, reputation\n    score, and escrow completion rate. Returns APPROVED or BLOCKED\n    with detailed reasoning.\n\n    Args:\n        agent_id: The GreenHelix agent ID to verify.\n        min_score: Minimum acceptable reputation score (default 60).\n    \"\"\"\n    verifier = AgentVerifier(\n        api_key=os.environ[\"GREENHELIX_API_KEY\"],\n    )\n\n    report = verifier.full_audit(agent_id)\n    recommendation = report.get(\"recommendation\", \"unknown\")\n    flags = report.get(\"flags\", [])\n    rep_layer = report.get(\"layers\", {}).get(\"reputation\", {})\n    score = rep_layer.get(\"score\", 0)\n    escrow_layer = report.get(\"layers\", {}).get(\"market_signals\", {})\n    completion = escrow_layer.get(\"completion_rate_pct\", 0)\n\n    if recommendation in (\"avoid\", \"caution\") or score \u003C min_score:\n        return (\n            f\"BLOCKED: Agent {agent_id} is not trustworthy enough. \"\n            f\"Score: {score}, Completion rate: {completion}%, \"\n            f\"Flags: {', '.join(flags)}. \"\n            f\"Find an alternative agent or increase escrow protection.\"\n        )\n\n    return (\n        f\"APPROVED: Agent {agent_id} passed verification. \"\n        f\"Score: {score}, Completion rate: {completion}%, \"\n        f\"Recommendation: {recommendation}. \"\n        f\"Proceed with {'standard' if recommendation == 'proceed' else 'performance'} escrow.\"\n    )\n\n\n@tool\ndef hire_with_escrow(\n    agent_id: str,\n    amount: float,\n    task_description: str,\n) -> str:\n    \"\"\"Create an escrow-protected contract with a verified agent.\n\n    IMPORTANT: Always call verify_before_hire first.\n\n    Args:\n        agent_id: The GreenHelix agent ID to hire.\n        amount: Payment amount in USD.\n        task_description: What the agent should do.\n    \"\"\"\n    import requests\n\n    resp = requests.post(\n        \"https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1\",\n        headers={\n            \"Content-Type\": \"application\u002Fjson\",\n            \"Authorization\": f\"Bearer {os.environ['GREENHELIX_API_KEY']}\",\n        },\n        json={\n            \"tool\": \"create_escrow\",\n            \"input\": {\n                \"payer_agent_id\": os.environ[\"AGENT_ID\"],\n                \"payee_agent_id\": agent_id,\n                \"amount\": str(amount),\n                \"description\": task_description,\n            },\n        },\n    )\n    resp.raise_for_status()\n    result = resp.json()\n    return f\"Escrow created: {result.get('escrow_id')}. ${amount} locked.\"\n```\n\n### General Pattern: \"Verify Before Delegate\" Middleware\n\nFor any framework, the pattern is the same: intercept the delegation decision and insert a trust check. Here is a framework-agnostic middleware:\n\n```python\nclass TrustGate:\n    \"\"\"Middleware that gates agent interactions on trust verification.\n\n    Insert this between your decision logic and the actual API call\n    to ensure no untrusted agent receives work or data.\n    \"\"\"\n\n    def __init__(self, verifier, min_score=60, require_chains=True,\n                 min_escrow_completion=80):\n        self.verifier = verifier\n        self.min_score = min_score\n        self.require_chains = require_chains\n        self.min_escrow_completion = min_escrow_completion\n\n    def check(self, agent_id):\n        \"\"\"Verify an agent meets all trust criteria.\n\n        Returns (approved: bool, reason: str, report: dict).\n        \"\"\"\n        report = self.verifier.full_audit(agent_id)\n        recommendation = report.get(\"recommendation\", \"unknown\")\n        flags = report.get(\"flags\", [])\n\n        # Check reputation score\n        rep_layer = report.get(\"layers\", {}).get(\"reputation\", {})\n        score = rep_layer.get(\"score\", 0)\n        if score \u003C self.min_score:\n            return False, f\"Score {score} below minimum {self.min_score}\", report\n\n        # Check claim chains\n        if self.require_chains:\n            chain_layer = report.get(\"layers\", {}).get(\"claim_chains\", {})\n            if chain_layer.get(\"chain_count\", 0) == 0:\n                return False, \"No claim chains found\", report\n\n        # Check escrow completion\n        market_layer = report.get(\"layers\", {}).get(\"market_signals\", {})\n        completion = market_layer.get(\"completion_rate_pct\", 0)\n        total_escrows = market_layer.get(\"total_escrows\", 0)\n        if total_escrows > 5 and completion \u003C self.min_escrow_completion:\n            return False, f\"Completion rate {completion}% below {self.min_escrow_completion}%\", report\n\n        # Check for hard-fail flags\n        hard_fails = {\"IDENTITY_NOT_FOUND\", \"MULTIPLE_DISPUTES\"}\n        if hard_fails & set(flags):\n            return False, f\"Hard-fail flags: {hard_fails & set(flags)}\", report\n\n        return True, recommendation, report\n\n    def gate(self, agent_id, action_fn, *args, **kwargs):\n        \"\"\"Execute action_fn only if the agent passes trust verification.\n\n        Args:\n            agent_id: Agent to verify.\n            action_fn: Function to call if trust check passes.\n            *args, **kwargs: Arguments to pass to action_fn.\n\n        Returns:\n            Result of action_fn if approved, or raises RuntimeError.\n        \"\"\"\n        approved, reason, report = self.check(agent_id)\n        if not approved:\n            raise RuntimeError(\n                f\"Trust gate blocked interaction with {agent_id}: {reason}\"\n            )\n        return action_fn(*args, **kwargs)\n\n\n# Usage with any framework\nverifier = AgentVerifier(api_key=os.environ[\"GREENHELIX_API_KEY\"])\ngate = TrustGate(verifier, min_score=70, require_chains=True)\n\ndef delegate_task(agent_id, task):\n    \"\"\"Your existing delegation logic.\"\"\"\n    print(f\"Delegating '{task}' to {agent_id}\")\n    # ... create escrow, send task, etc.\n\n# This will only execute if the agent passes all trust checks\ntry:\n    gate.gate(\n        \"trading-bot-alpha-7x\",\n        delegate_task,\n        \"trading-bot-alpha-7x\",\n        \"Analyze Q1 market data and produce a summary report\",\n    )\nexcept RuntimeError as e:\n    print(f\"Delegation blocked: {e}\")\n```\n\n```bash\n# Verify any agent from the command line before interacting with it\ncurl -s -X POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1 \\\n  -H \"Authorization: Bearer $API_KEY\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\n    \"tool\": \"get_agent_reputation\",\n    \"input\": {\n      \"agent_id\": \"candidate-agent-to-verify\"\n    }\n  }' | python3 -c \"\nimport sys, json\ndata = json.load(sys.stdin)\nscore = data.get('score', 0)\nif score >= 70:\n    print(f'APPROVED: Score {score}')\nelse:\n    print(f'BLOCKED: Score {score} is too low')\n    sys.exit(1)\n\"\n```\n\n---\n\n## What's Next\n\nThis guide covered the buyer's side of agent trust: how to verify identity, audit metrics, check claim chains, read reputation scores, analyze market signals, run full due diligence, set up continuous monitoring, and integrate trust gates into your agent frameworks.\n\nThe companion guides cover the seller's side and related infrastructure:\n\n- **Agent-to-Agent Commerce: Escrow, Payments, and Trust for Multi-Agent Systems** -- the foundational guide to wallets, escrow patterns (standard, performance, split), subscriptions, disputes, and the `AgentCommerce` class for building agent payment infrastructure.\n- **Verified Trading Bot Reputation** -- how to build cryptographic PnL proof using Ed25519 signatures and Merkle claim chains from the seller's perspective. If you are building an agent that needs to establish trust, start here.\n- **The Agent Strategy Marketplace Playbook** -- how to list verified trading strategies with performance escrow, pricing tiers, and subscriber management.\n- **Tamper-Proof Audit Trails for Trading Bots** -- EU AI Act, MiFID II, and SEC compliance using GreenHelix's event bus and Merkle audit chains.\n\nFull API reference and tool catalog (128 tools) available at [https:\u002F\u002Fapi.greenhelix.net\u002Fdocs](https:\u002F\u002Fapi.greenhelix.net\u002Fdocs).\n\n---\n\n*Price: $29 | Format: Digital Guide | Updates: Lifetime access to revisions*\n\n",{"name":5,"tags":24,"type":29,"author":33,"install":34,"license":15,"version":35,"metadata":36,"price_usd":42,"executable":20,"credentials":43,"description":7,"content_type":44,"compatibility":45},[25,26,27,28,29,30,31,32],"trust","reputation","verification","due-diligence","guide","greenhelix","openclaw","ai-agent","felix-agent","none","1.3.1",{"openclaw":37},{"requires":38,"primaryEnv":40},{"env":39},[40,41],"GREENHELIX_API_KEY","AGENT_SIGNING_KEY",0,[40,41],"markdown",[31],"master","4aa004da461d820f4ea5499e58eb8d196cf99016","community\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-trust-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":55,"prompt":65,"zipAvailable":66},[56,59,62],{"tool":57,"command":58},"npx","npx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-trust-verification",{"tool":60,"command":61},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-trust-verification",{"tool":63,"command":64},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-trust-verification","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-trust-verification\u002FSKILL.md",true,[],[69,76,83,90,97,104],{"skillNo":70,"name":71,"nameZh":6,"description":72,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":73,"categories":74,"keywords":75,"publishedAt":19},"01M785WKJB99G3STR1NF9NRTJW","youtube-content","YouTube transcripts to summaries, threads, blogs.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fyoutube-content\u002FSKILL.md",[],[],{"skillNo":77,"name":78,"nameZh":6,"description":79,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":80,"categories":81,"keywords":82,"publishedAt":19},"01M785WEFHB0G2S9YA6EPR3H0E","xurl","X\u002FTwitter via xurl CLI: post, search, DM, media, v2 API.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fxurl\u002FSKILL.md",[],[],{"skillNo":84,"name":85,"nameZh":6,"description":86,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":87,"categories":88,"keywords":89,"publishedAt":19},"01M785W98EDN4EFJXJPMQEHCRC","touchdesigner-mcp","Control a running TouchDesigner instance via twozero MCP — create operators, set parameters, wire connections, execute Python, build real-time visuals. 36 native tools.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftouchdesigner-mcp\u002FSKILL.md",[],[],{"skillNo":91,"name":92,"nameZh":6,"description":93,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":94,"categories":95,"keywords":96,"publishedAt":19},"01M785W5S9FP3QBH2V191E025P","test-driven-development","TDD: enforce RED-GREEN-REFACTOR, tests before code.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Ftest-driven-development\u002FSKILL.md",[],[],{"skillNo":98,"name":99,"nameZh":6,"description":100,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":101,"categories":102,"keywords":103,"publishedAt":19},"01M785W2AS08NSSH9YATCV6FJB","teams-meeting-pipeline","Operate the Teams meeting summary pipeline via Hermes CLI — summarize meetings, inspect pipeline status, replay jobs, manage Microsoft Graph subscriptions.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fteams-meeting-pipeline\u002FSKILL.md",[],[],{"skillNo":105,"name":106,"nameZh":6,"description":107,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":108,"categories":109,"keywords":110,"publishedAt":19},"01M785VXKW4T34BTP1SCHW1R7F","systematic-debugging","4-phase root cause debugging: understand bugs before fixing.","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fskills\u002Fsystematic-debugging\u002FSKILL.md",[],[]]