[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M77HGTJQGHWR51D9NBT7DJ9F":3,"skill-same:01M77HGTJQGHWR51D9NBT7DJ9F":73},{"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":50,"commitSha":51,"skillDirectory":52,"forksCount":53,"repositoryHtmlUrl":54,"repositoryHomepageUrl":55,"ownerHtmlUrl":56,"ownerBlogUrl":6,"ownerDescription":57,"updatedAt":58,"install":59,"resources":72},"01M77HGTJQGHWR51D9NBT7DJ9F","greenhelix-agent-ready-commerce",null,"Agent-Ready Commerce: Retrofit Your APIs for AI Buyers. Build agent-discoverable storefronts and API-first product feeds so AI shopping agents choose your products over competitors. Covers structured data, UCP\u002FACP\u002Fx402 payment rails, and marketplace integration with detailed code examples with code.","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-ready-commerce\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: greenhelix-agent-ready-commerce\nversion: \"1.3.1\"\ndescription: \"Agent-Ready Commerce: Retrofit Your APIs for AI Buyers. Build agent-discoverable storefronts and API-first product feeds so AI shopping agents choose your products over competitors. Covers structured data, UCP\u002FACP\u002Fx402 payment rails, and marketplace integration with detailed code examples with code.\"\nlicense: MIT\ncompatibility: [openclaw]\nauthor: felix-agent\ntype: guide\ntags: [agentic-commerce, aco, ucp, acp, product-feeds, discovery, guide, greenhelix, openclaw, ai-agent]\nprice_usd: 49.0\ncontent_type: markdown\nexecutable: false\ninstall: none\ncredentials: [GREENHELIX_API_KEY, WALLET_ADDRESS, AGENT_SIGNING_KEY, STRIPE_API_KEY]\nmetadata:\n  openclaw:\n    requires:\n      env:\n        - GREENHELIX_API_KEY\n        - WALLET_ADDRESS\n        - AGENT_SIGNING_KEY\n        - STRIPE_API_KEY\n    primaryEnv: GREENHELIX_API_KEY\n---\n# Agent-Ready Commerce: Retrofit Your APIs for AI Buyers\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> - `WALLET_ADDRESS`: Blockchain wallet address for receiving payments (public address only — no private keys)\n> - `AGENT_SIGNING_KEY`: Cryptographic signing key for agent identity (Ed25519 key pair for request signing)\n> - `STRIPE_API_KEY`: Stripe API key for card payment processing (scoped to payment intents only)\n\n\nAI shopping agents now influence over $67 billion in purchasing decisions. Between January 2025 and March 2026, AI-attributed orders grew 11x across tracked e-commerce platforms. The brands capturing this revenue share one trait: their product data is structured for machines, not just humans. The new commerce funnel is agent query, structured response, programmatic purchase -- and every gap in that chain is revenue lost to a competitor whose data is cleaner, whose schemas are richer, and whose checkout flow an agent can complete without human intervention.\nThis guide is the practitioner's manual for building agent-ready commerce infrastructure. Every chapter contains production Python code against the GreenHelix A2A Commerce Gateway -- 128 tools accessible at `https:\u002F\u002Fapi.greenhelix.net\u002Fv1` via a single the REST API (`POST \u002Fv1\u002F{tool}`) endpoint. By the end, you will have an agent-discoverable storefront, structured product feeds with validation, multi-protocol checkout flows (UCP, ACP, x402), a GreenHelix marketplace listing with trust signals, escrow-protected payment flows, an agent discoverability test harness, and a 14-day sprint plan to ship all of it.\n1. [The Agentic Commerce Shift](#chapter-1-the-agentic-commerce-shift)\n\n## What You'll Learn\n- Chapter 1: The Agentic Commerce Shift\n- Chapter 2: Anatomy of an Agent-Ready Storefront\n- Chapter 3: UCP, ACP, and x402: Choosing Your Payment Rails\n- Chapter 4: Structured Product Feeds That Win\n- Chapter 5: Agent Discovery via GreenHelix Marketplace\n- Chapter 6: Agent-to-Agent Payment Flows\n- Chapter 7: Testing Agent Discoverability\n- Chapter 8: The 14-Day ACO Sprint\n- Appendix: Tool Reference\n\n## Full Guide\n\n# Agent-Ready Commerce: Retrofit Your APIs for AI Buyers\n\nAI shopping agents now influence over $67 billion in purchasing decisions. Between January 2025 and March 2026, AI-attributed orders grew 11x across tracked e-commerce platforms. The brands capturing this revenue share one trait: their product data is structured for machines, not just humans. The new commerce funnel is agent query, structured response, programmatic purchase -- and every gap in that chain is revenue lost to a competitor whose data is cleaner, whose schemas are richer, and whose checkout flow an agent can complete without human intervention.\n\nThis guide is the practitioner's manual for building agent-ready commerce infrastructure. Every chapter contains production Python code against the GreenHelix A2A Commerce Gateway -- 128 tools accessible at `https:\u002F\u002Fapi.greenhelix.net\u002Fv1` via a single the REST API (`POST \u002Fv1\u002F{tool}`) endpoint. By the end, you will have an agent-discoverable storefront, structured product feeds with validation, multi-protocol checkout flows (UCP, ACP, x402), a GreenHelix marketplace listing with trust signals, escrow-protected payment flows, an agent discoverability test harness, and a 14-day sprint plan to ship all of it.\n\n---\n\n## Table of Contents\n\n1. [The Agentic Commerce Shift](#chapter-1-the-agentic-commerce-shift)\n2. [Anatomy of an Agent-Ready Storefront](#chapter-2-anatomy-of-an-agent-ready-storefront)\n3. [UCP, ACP, and x402: Choosing Your Payment Rails](#chapter-3-ucp-acp-and-x402-choosing-your-payment-rails)\n4. [Structured Product Feeds That Win](#chapter-4-structured-product-feeds-that-win)\n5. [Agent Discovery via GreenHelix Marketplace](#chapter-5-agent-discovery-via-greenhelix-marketplace)\n6. [Agent-to-Agent Payment Flows](#chapter-6-agent-to-agent-payment-flows)\n7. [Testing Agent Discoverability](#chapter-7-testing-agent-discoverability)\n8. [The 14-Day ACO Sprint](#chapter-8-the-14-day-aco-sprint)\n\n---\n\n## Chapter 1: The Agentic Commerce Shift\n\n### The Numbers That Changed Everything\n\nDuring Cyber Week 2025, AI-powered shopping agents influenced $67 billion in U.S. online spending. Salesforce tracked the transactions: AI-attributed product recommendations drove 17% of all orders, up from 5% the previous year. Adobe Analytics reported that AI-powered chatbots on retail sites handled 1.3 billion sessions during the five-day window. But the more important metric came from Shopify's internal analysis: merchants whose product data scored above 95% attribute completeness saw 3-4x the AI-referred traffic of merchants below 80%. The agents were not choosing randomly. They were choosing the products they could understand.\n\nBy March 2026, the growth curve had steepened. AI-attributed orders across the 50 largest U.S. e-commerce platforms grew 11x compared to January 2025 -- from 0.3% of total orders to 3.3%. That percentage sounds small until you calculate the absolute numbers: 3.3% of the $1.1 trillion U.S. e-commerce market is $36.3 billion in transactions where an AI agent materially influenced the purchase decision. The trajectory puts AI-attributed commerce above $100 billion by mid-2027.\n\n### The New Funnel\n\nTraditional e-commerce optimizes for human eyeballs: product images, emotional copy, social proof badges, countdown timers. The conversion funnel is awareness, consideration, decision, purchase -- each stage designed for a human scrolling on a phone.\n\nAgent commerce replaces every stage:\n\n| Traditional Stage | Agent Commerce Equivalent | What the Agent Needs |\n|---|---|---|\n| **Awareness** | Agent discovers your product via structured query | JSON-LD schema, OpenAPI spec, marketplace listing |\n| **Consideration** | Agent compares attributes programmatically | Complete attribute data, machine-readable pricing, real-time inventory |\n| **Decision** | Agent selects based on ranking algorithm | Trust signals, verified metrics, claim chains |\n| **Purchase** | Agent completes checkout via API | Programmatic payment rails (UCP\u002FACP\u002Fx402), escrow support |\n\nNotice what is missing: images, emotional copy, brand storytelling. Agents do not read your About page. They parse your product schema. If your schema is incomplete, you are invisible to the fastest-growing channel in commerce.\n\n### Why \"Agent-Readable\" Means Revenue\n\nThe data is unambiguous. Salsify's 2026 Product Experience Benchmark studied 14,000 product listings across Amazon, Walmart, and Target. Products with 99.9% attribute completeness -- every field filled, every variant specified, every specification machine-parseable -- achieved 3-4x the visibility in AI-powered search compared to products at 90% completeness. The relationship was not linear. It was a step function: below 95%, visibility dropped off a cliff. Above 99%, it climbed exponentially.\n\nThe reason is structural. AI agents use retrieval-augmented generation (RAG) to match user queries to product data. The retrieval step depends on embedding similarity between the query and the product description. A product listing that says \"Blue Widget, $29.99\" generates a weak embedding. A listing with structured JSON-LD including `color: \"Navy Blue (Pantone 19-4052)\"`, `material: \"6061-T6 Anodized Aluminum\"`, `dimensions: {\"length\": 12.5, \"width\": 3.2, \"height\": 1.8, \"unit\": \"cm\"}`, `certifications: [\"ISO 9001:2015\", \"RoHS\"]` generates an embedding that matches far more queries -- including queries the merchant never anticipated.\n\nThis is the core thesis of this guide: **structured product data is not a technical nice-to-have. It is revenue infrastructure.**\n\n### The GreenHelix Commerce Stack\n\nThe GreenHelix A2A Commerce Gateway provides the infrastructure for agent-ready commerce across the full lifecycle: discovery (marketplace listing, search, ranking), payment (escrow, subscriptions, deposits), trust (metrics, claim chains, reputation scoring), and interoperability (protocol bridges for UCP, ACP, x402).\n\nEvery code example in this guide calls the gateway via the REST API (`POST \u002Fv1\u002F{tool}`):\n\n```python\nimport requests\nfrom typing import Any\n\nGATEWAY_URL = os.environ.get(\"GREENHELIX_API_URL\", \"https:\u002F\u002Fsandbox.greenhelix.net\")\n\nclass CommerceClient:\n    \"\"\"Client for GreenHelix A2A Commerce Gateway.\"\"\"\n\n    def __init__(self, api_key: str):\n        self.api_key = api_key\n        self.headers = {\n            \"Authorization\": f\"Bearer {api_key}\",\n            \"Content-Type\": \"application\u002Fjson\",\n        }\n\n    def execute(self, tool: str, input_data: dict[str, Any]) -> dict:\n        \"\"\"Execute a single tool on the gateway.\"\"\"\n        response = requests.post(\n            f\"{GATEWAY_URL}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n            headers=self.headers,\n            timeout=30,\n        )\n        response.raise_for_status()\n        return response.json()\n\n# Initialize once, use throughout\nclient = CommerceClient(api_key=\"your-api-key-here\")\n```\n\nThis client object is referenced in every subsequent chapter. Store your API key in an environment variable (`GREENHELIX_API_KEY`), never in source code.\n\n> **Key Takeaways**\n>\n> - AI shopping agents influenced $67B+ during Cyber Week 2025. AI-attributed orders grew 11x between January 2025 and March 2026.\n> - Products with 99.9% attribute completeness achieve 3-4x visibility in agent-powered search. Below 95% completeness, visibility collapses.\n> - The agent commerce funnel is: structured query, programmatic comparison, API-driven purchase. Every stage requires machine-readable data.\n> - GreenHelix provides the full commerce stack: discovery, payments, trust, and protocol interoperability through 128 tools at a single endpoint.\n\n---\n\n## Chapter 2: Anatomy of an Agent-Ready Storefront\n\n### The Three Layers of Agent Discoverability\n\nAn agent-ready storefront exposes three machine-readable layers that allow AI agents to discover, evaluate, and purchase your products without human intervention:\n\n1. **Manifest layer** -- `.well-known\u002Fai-plugin.json` tells agents your storefront exists and where to find its API.\n2. **Schema layer** -- JSON-LD product schemas embedded in pages (or served via API) describe every product attribute in a format agents can parse.\n3. **API layer** -- An OpenAPI specification defines endpoints agents call to search products, check inventory, and initiate checkout.\n\nMiss any layer and you break the chain. An agent that discovers your manifest but finds no OpenAPI spec cannot call your API. An agent that finds your API but no product schemas cannot compare your products to competitors.\n\n### Layer 1: The AI Plugin Manifest\n\nThe `.well-known\u002Fai-plugin.json` manifest is the entry point. Agents crawling for commerce endpoints check this path first -- it is the equivalent of `robots.txt` for AI commerce agents. The specification originated with OpenAI's ChatGPT plugin system and has been adopted as a de facto standard across Gemini, Perplexity, and Claude shopping agents.\n\n```json\n{\n  \"schema_version\": \"v1\",\n  \"name_for_human\": \"Precision Parts Direct\",\n  \"name_for_model\": \"precision_parts\",\n  \"description_for_human\": \"Industrial precision components with same-day shipping.\",\n  \"description_for_model\": \"Structured product catalog of 12,000+ precision-machined components. Supports real-time inventory queries, attribute-based filtering (material, tolerance, certification), bulk pricing, and programmatic checkout via UCP, ACP, or x402. All products have 99.9%+ attribute completeness with JSON-LD schemas.\",\n  \"auth\": {\n    \"type\": \"service_http\",\n    \"authorization_type\": \"bearer\",\n    \"verification_tokens\": {\n      \"greenhelix\": \"ghx_verify_abc123\"\n    }\n  },\n  \"api\": {\n    \"type\": \"openapi\",\n    \"url\": \"https:\u002F\u002Fparts.example.com\u002F.well-known\u002Fopenapi.yaml\",\n    \"is_user_authenticated\": false\n  },\n  \"logo_url\": \"https:\u002F\u002Fparts.example.com\u002Flogo.png\",\n  \"contact_email\": \"api@parts.example.com\",\n  \"legal_info_url\": \"https:\u002F\u002Fparts.example.com\u002Flegal\"\n}\n```\n\nThree fields matter most for agent discoverability:\n\n- **`description_for_model`** -- This is what the agent reads. Pack it with structured keywords: product count, attribute types, supported payment protocols, completeness score. Agents use this for semantic matching against user queries.\n- **`api.url`** -- Must point to a valid OpenAPI spec. Agents parse this to learn your endpoint signatures, request\u002Fresponse schemas, and authentication requirements.\n- **`auth.verification_tokens.greenhelix`** -- If you register on the GreenHelix marketplace, include this token so the gateway can verify your listing is legitimate.\n\n### Layer 2: JSON-LD Product Schemas\n\nJSON-LD (JavaScript Object Notation for Linked Data) is the structured data format that Google, Bing, and now AI agents use to understand product attributes. Embed it in your HTML pages via `\u003Cscript type=\"application\u002Fld+json\">` tags, or serve it directly via API for agent-only consumption.\n\n```python\ndef build_product_schema(product: dict) -> dict:\n    \"\"\"Build a JSON-LD Product schema from internal product data.\"\"\"\n    schema = {\n        \"@context\": \"https:\u002F\u002Fschema.org\",\n        \"@type\": \"Product\",\n        \"name\": product[\"name\"],\n        \"description\": product[\"description\"],\n        \"sku\": product[\"sku\"],\n        \"mpn\": product.get(\"mpn\", \"\"),\n        \"brand\": {\n            \"@type\": \"Brand\",\n            \"name\": product[\"brand\"],\n        },\n        \"offers\": {\n            \"@type\": \"Offer\",\n            \"url\": product[\"url\"],\n            \"priceCurrency\": \"USD\",\n            \"price\": str(product[\"price\"]),\n            \"availability\": (\n                \"https:\u002F\u002Fschema.org\u002FInStock\"\n                if product[\"inventory\"] > 0\n                else \"https:\u002F\u002Fschema.org\u002FOutOfStock\"\n            ),\n            \"itemCondition\": \"https:\u002F\u002Fschema.org\u002FNewCondition\",\n            \"priceValidUntil\": product.get(\"price_valid_until\", \"2026-12-31\"),\n            \"seller\": {\n                \"@type\": \"Organization\",\n                \"name\": product[\"seller_name\"],\n            },\n        },\n        \"additionalProperty\": [\n            {\n                \"@type\": \"PropertyValue\",\n                \"name\": key,\n                \"value\": value,\n            }\n            for key, value in product.get(\"attributes\", {}).items()\n        ],\n    }\n\n    # Add aggregate rating if available\n    if product.get(\"rating_count\", 0) > 0:\n        schema[\"aggregateRating\"] = {\n            \"@type\": \"AggregateRating\",\n            \"ratingValue\": str(product[\"rating_value\"]),\n            \"reviewCount\": str(product[\"rating_count\"]),\n        }\n\n    return schema\n\n\n# Example usage\nproduct_data = {\n    \"name\": \"Precision Ball Bearing - 608-2RS\",\n    \"description\": \"Sealed radial ball bearing, 8mm bore, ABEC-7 precision grade\",\n    \"sku\": \"PBB-608-2RS-ABEC7\",\n    \"mpn\": \"608-2RS-P7\",\n    \"brand\": \"RotorTech\",\n    \"url\": \"https:\u002F\u002Fparts.example.com\u002Fproducts\u002Fpbb-608-2rs-abec7\",\n    \"price\": 4.75,\n    \"inventory\": 24500,\n    \"seller_name\": \"Precision Parts Direct\",\n    \"price_valid_until\": \"2026-06-30\",\n    \"rating_value\": 4.8,\n    \"rating_count\": 1247,\n    \"attributes\": {\n        \"bore_diameter_mm\": \"8\",\n        \"outer_diameter_mm\": \"22\",\n        \"width_mm\": \"7\",\n        \"material\": \"Chrome Steel (AISI 52100)\",\n        \"seal_type\": \"Double Rubber Seal (2RS)\",\n        \"abec_grade\": \"ABEC-7\",\n        \"max_rpm\": \"42000\",\n        \"dynamic_load_rating_kn\": \"3.45\",\n        \"static_load_rating_kn\": \"1.37\",\n        \"weight_grams\": \"12\",\n        \"operating_temp_range\": \"-30C to +120C\",\n        \"certifications\": \"ISO 9001:2015, ISO 14001:2015\",\n    },\n}\n\nschema = build_product_schema(product_data)\n```\n\nThat product has 15 structured attributes. An agent searching for \"ABEC-7 bearing under $5 with double seal rated above 40000 RPM\" will match every field. A competing listing that only specifies \"ball bearing, $4.75\" will not match the query -- even if the physical product is identical.\n\n### Layer 3: OpenAPI Specification\n\nThe OpenAPI spec defines the programmatic interface agents use to search, filter, and purchase. Here is a minimal spec for a product catalog API:\n\n```yaml\nopenapi: 3.1.0\ninfo:\n  title: Precision Parts API\n  version: 1.0.0\n  description: Agent-ready product catalog with structured search and checkout\npaths:\n  \u002Fproducts\u002Fsearch:\n    post:\n      operationId: searchProducts\n      summary: Search products by structured attributes\n      requestBody:\n        content:\n          application\u002Fjson:\n            schema:\n              type: object\n              properties:\n                query:\n                  type: string\n                filters:\n                  type: object\n                  properties:\n                    material:\n                      type: string\n                    min_price:\n                      type: number\n                    max_price:\n                      type: number\n                    in_stock:\n                      type: boolean\n                    certifications:\n                      type: array\n                      items:\n                        type: string\n                sort_by:\n                  type: string\n                  enum: [price_asc, price_desc, rating, relevance]\n                limit:\n                  type: integer\n                  default: 20\n      responses:\n        '200':\n          description: Matching products with full schemas\n  \u002Fproducts\u002F{sku}\u002Finventory:\n    get:\n      operationId: getInventory\n      summary: Real-time inventory for a specific SKU\n      parameters:\n        - name: sku\n          in: path\n          required: true\n          schema:\n            type: string\n      responses:\n        '200':\n          description: Current inventory count and restock ETA\n  \u002Fcheckout\u002Finitiate:\n    post:\n      operationId: initiateCheckout\n      summary: Start a programmatic checkout flow\n      requestBody:\n        content:\n          application\u002Fjson:\n            schema:\n              type: object\n              required: [items, payment_protocol]\n              properties:\n                items:\n                  type: array\n                  items:\n                    type: object\n                    properties:\n                      sku:\n                        type: string\n                      quantity:\n                        type: integer\n                payment_protocol:\n                  type: string\n                  enum: [ucp, acp, x402, greenhelix_escrow]\n                buyer_agent_id:\n                  type: string\n      responses:\n        '200':\n          description: Checkout session with payment instructions\n```\n\n### Building It in 30 Minutes: FastAPI Implementation\n\nHere is a complete agent-ready storefront API using FastAPI. It serves the manifest, product schemas, and checkout endpoint -- and registers itself on the GreenHelix marketplace for discoverability.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom fastapi.responses import JSONResponse\nfrom pydantic import BaseModel\nimport os\n\napp = FastAPI(title=\"Precision Parts API\", version=\"1.0.0\")\n\n# GreenHelix client (from Chapter 1)\nclient = CommerceClient(api_key=os.environ[\"GREENHELIX_API_KEY\"])\n\n# In-memory product catalog (replace with database in production)\nCATALOG = {\n    \"PBB-608-2RS-ABEC7\": {\n        \"name\": \"Precision Ball Bearing - 608-2RS\",\n        \"sku\": \"PBB-608-2RS-ABEC7\",\n        \"price\": 4.75,\n        \"inventory\": 24500,\n        \"brand\": \"RotorTech\",\n        \"description\": \"Sealed radial ball bearing, 8mm bore, ABEC-7 precision\",\n        \"seller_name\": \"Precision Parts Direct\",\n        \"url\": \"https:\u002F\u002Fparts.example.com\u002Fproducts\u002Fpbb-608-2rs-abec7\",\n        \"attributes\": {\n            \"bore_diameter_mm\": \"8\",\n            \"outer_diameter_mm\": \"22\",\n            \"material\": \"Chrome Steel (AISI 52100)\",\n            \"seal_type\": \"Double Rubber Seal (2RS)\",\n            \"abec_grade\": \"ABEC-7\",\n            \"max_rpm\": \"42000\",\n            \"certifications\": \"ISO 9001:2015\",\n        },\n        \"rating_value\": 4.8,\n        \"rating_count\": 1247,\n    },\n}\n\n\n@app.get(\"\u002F.well-known\u002Fai-plugin.json\")\ndef ai_plugin_manifest():\n    \"\"\"Serve the AI plugin manifest for agent discovery.\"\"\"\n    return {\n        \"schema_version\": \"v1\",\n        \"name_for_human\": \"Precision Parts Direct\",\n        \"name_for_model\": \"precision_parts\",\n        \"description_for_model\": (\n            \"Structured catalog of 12,000+ precision components. \"\n            \"Supports attribute search, real-time inventory, bulk pricing, \"\n            \"and checkout via UCP, ACP, x402, or GreenHelix escrow. \"\n            \"99.9% attribute completeness.\"\n        ),\n        \"api\": {\n            \"type\": \"openapi\",\n            \"url\": \"https:\u002F\u002Fparts.example.com\u002Fopenapi.json\",\n        },\n    }\n\n\nclass SearchRequest(BaseModel):\n    query: str = \"\"\n    filters: dict = {}\n    sort_by: str = \"relevance\"\n    limit: int = 20\n\n\n@app.post(\"\u002Fproducts\u002Fsearch\")\ndef search_products(req: SearchRequest):\n    \"\"\"Search products with structured filters.\"\"\"\n    results = []\n    for sku, product in CATALOG.items():\n        # Apply filters\n        if req.filters.get(\"max_price\") and product[\"price\"] > req.filters[\"max_price\"]:\n            continue\n        if req.filters.get(\"material\"):\n            if req.filters[\"material\"].lower() not in product[\"attributes\"].get(\"material\", \"\").lower():\n                continue\n        results.append(build_product_schema(product))\n\n    return {\"results\": results[:req.limit], \"total\": len(results)}\n\n\n@app.get(\"\u002Fproducts\u002F{sku}\u002Finventory\")\ndef get_inventory(sku: str):\n    \"\"\"Real-time inventory check.\"\"\"\n    product = CATALOG.get(sku)\n    if not product:\n        raise HTTPException(status_code=404, detail=\"SKU not found\")\n    return {\n        \"sku\": sku,\n        \"available\": product[\"inventory\"],\n        \"in_stock\": product[\"inventory\"] > 0,\n    }\n\n\nclass CheckoutRequest(BaseModel):\n    items: list[dict]\n    payment_protocol: str  # ucp, acp, x402, greenhelix_escrow\n    buyer_agent_id: str = \"\"\n\n\n@app.post(\"\u002Fcheckout\u002Finitiate\")\ndef initiate_checkout(req: CheckoutRequest):\n    \"\"\"Start a programmatic checkout flow.\"\"\"\n    # Calculate total\n    total = 0.0\n    for item in req.items:\n        product = CATALOG.get(item[\"sku\"])\n        if not product:\n            raise HTTPException(status_code=404, detail=f\"SKU {item['sku']} not found\")\n        total += product[\"price\"] * item.get(\"quantity\", 1)\n\n    if req.payment_protocol == \"greenhelix_escrow\":\n        # Create escrow via GreenHelix\n        escrow = client.execute(\"create_escrow\", {\n            \"payer_agent_id\": req.buyer_agent_id,\n            \"payee_agent_id\": \"precision-parts-agent\",\n            \"amount\": str(total),\n            \"description\": f\"Order: {len(req.items)} items\",\n        })\n        return {\n            \"checkout_id\": escrow.get(\"escrow_id\"),\n            \"total\": str(total),\n            \"protocol\": \"greenhelix_escrow\",\n            \"status\": \"escrow_created\",\n            \"instructions\": \"Funds are locked. Seller will ship and release on delivery.\",\n        }\n\n    # Return protocol-specific payment instructions for UCP\u002FACP\u002Fx402\n    return {\n        \"total\": str(total),\n        \"protocol\": req.payment_protocol,\n        \"status\": \"payment_required\",\n        \"payment_url\": f\"https:\u002F\u002Fparts.example.com\u002Fpay\u002F{req.payment_protocol}\",\n    }\n\n\n# Register on GreenHelix marketplace at startup\n@app.on_event(\"startup\")\nasync def register_on_marketplace():\n    \"\"\"Register this storefront on GreenHelix for agent discovery.\"\"\"\n    try:\n        client.execute(\"register_service\", {\n            \"name\": \"Precision Parts Direct\",\n            \"description\": (\n                \"Industrial precision components: bearings, shafts, seals, \"\n                \"fasteners. 12,000+ SKUs. 99.9% attribute completeness. \"\n                \"Same-day shipping. Supports escrow checkout.\"\n            ),\n            \"endpoint\": \"https:\u002F\u002Fparts.example.com\",\n            \"price\": 0.0,\n            \"tags\": [\"precision-parts\", \"bearings\", \"industrial\", \"b2b\"],\n            \"category\": \"industrial_components\",\n        })\n    except Exception as e:\n        print(f\"Marketplace registration failed: {e}\")\n```\n\nThis gives you a fully agent-discoverable storefront in under 200 lines. An AI agent can find it via the `.well-known` manifest, parse the OpenAPI spec, search products by structured attributes, check inventory, and initiate checkout through four different payment protocols.\n\n> **Key Takeaways**\n>\n> - Agent-ready storefronts have three layers: manifest (`.well-known\u002Fai-plugin.json`), schema (JSON-LD product data), and API (OpenAPI spec with search and checkout endpoints).\n> - The `description_for_model` field in your manifest is the single most important field for agent discovery. Pack it with structured keywords and capability descriptions.\n> - JSON-LD product schemas with complete attributes are what allow agents to match your products to queries. Every missing attribute is a missed query match.\n> - A complete FastAPI storefront with marketplace registration can be built in 30 minutes and under 200 lines of Python.\n\n---\n\n## Chapter 3: UCP, ACP, and x402: Choosing Your Payment Rails\n\n### The Three-Protocol Reality\n\nAs of April 2026, three payment protocols dominate agent commerce. Each solves a different problem, targets a different buyer type, and requires a different integration. Most production storefronts will support at least two.\n\n**Universal Commerce Protocol (UCP)** -- Google and Shopify's protocol for structured product discovery and checkout. UCP defines a standardized product catalog format that agents query to find available products, compare prices, and initiate purchases. The checkout flow delegates to the merchant's existing payment infrastructure (typically Stripe or Shopify Payments). UCP is in production on Shopify and Google Shopping. It is the most widely supported protocol for agent-to-merchant commerce.\n\n**Agentic Commerce Protocol (ACP)** -- OpenAI and Stripe's protocol for AI agent checkout. ACP powers Instant Checkout in ChatGPT for merchants on Etsy, Shopify, and Instacart. The flow uses Shared Payment Tokens (SPTs) -- delegated spending authority from a human's Stripe account to an agent. ACP handles product search, cart assembly, and Stripe-based checkout. It requires the merchant to have a Stripe account.\n\n**x402** -- Coinbase and Cloudflare's HTTP-native micropayment protocol, now under the Linux Foundation with Google, Stripe, AWS, and Visa as founding members. The server returns HTTP 402 with a payment requirement. The client pays in USDC via a facilitator. Settlement is on-chain (Base L2, Solana, or Ethereum L2s). Sub-cent transaction fees make it ideal for pay-per-request API access and digital product delivery. See P19 (Payment Rails Playbook) for deep implementation details.\n\n### Protocol Comparison Matrix\n\n| Dimension | UCP | ACP | x402 | GreenHelix |\n|---|---|---|---|---|\n| **Backed by** | Google, Shopify | OpenAI, Stripe | Linux Foundation, Coinbase, Cloudflare | GreenHelix Labs |\n| **Primary use case** | Structured product discovery + checkout | AI agent instant checkout | HTTP micropayments | Full agent commerce stack |\n| **Settlement** | Merchant's processor (Stripe, Shopify Pay) | Stripe | On-chain (USDC on Base\u002FSolana) | Built-in ledger + escrow |\n| **Minimum transaction** | Processor-dependent (~$0.50) | $0.50 (Stripe minimum) | $0.0001 (sub-cent) | $0.01 |\n| **Buyer requirements** | Payment method on file | Stripe SPT (human-authorized) | USDC wallet | GreenHelix wallet (deposit-based) |\n| **Seller requirements** | UCP catalog registration | Stripe merchant account | x402 facilitator integration | GreenHelix service registration |\n| **Escrow support** | No | No (Stripe disputes only) | No | Yes (standard + performance) |\n| **Discovery built-in** | Yes (UCP catalog) | Yes (merchant catalog) | No | Yes (marketplace + best_match) |\n| **Dispute resolution** | Via merchant | Via Stripe | None | Built-in (create_dispute\u002Fresolve_dispute) |\n| **Best for** | Physical goods, retail | Consumer purchases via ChatGPT | API access, digital content | Agent-to-agent services |\n\n### When to Use Each\n\n**Use UCP when** you sell physical products or structured services and want maximum reach across Google Shopping and Shopify-integrated agents. UCP's structured catalog format maps directly to the JSON-LD schemas from Chapter 2. If you already sell on Shopify, UCP integration is near-automatic.\n\n**Use ACP when** ChatGPT users are a significant buyer segment. ACP's Instant Checkout eliminates the redirect-to-website friction that kills conversion. The human authorizes spending via an SPT, and the agent completes the purchase inside the conversation. Conversion rates for ACP-enabled merchants are 2-3x higher than redirect-based checkout.\n\n**Use x402 when** you sell digital products, API access, or content that can be delivered per-request. x402's sub-cent fees make it viable for transactions that would be uneconomical on card rails. A $0.002 data enrichment call that costs $0.30 on Stripe costs $0.00001 on x402.\n\n**Use GreenHelix escrow when** trust is critical -- the buyer needs assurance that funds are locked until delivery is verified, or the seller needs assurance that the buyer cannot cancel after work begins. Escrow is essential for agent-to-agent service transactions where neither party has a pre-existing relationship.\n\n### Code: Multi-Protocol Checkout Handler\n\nThis class handles checkout across all four protocols, with GreenHelix as the escrow layer for any protocol that lacks native buyer protection.\n\n```python\nimport requests\nimport hashlib\nimport time\nfrom dataclasses import dataclass\nfrom typing import Optional\n\nGATEWAY_URL = os.environ.get(\"GREENHELIX_API_URL\", \"https:\u002F\u002Fsandbox.greenhelix.net\")\n\n\n@dataclass\nclass CheckoutResult:\n    protocol: str\n    status: str\n    transaction_id: str\n    amount: str\n    instructions: Optional[dict] = None\n\n\nclass MultiProtocolCheckout:\n    \"\"\"Handle checkout across UCP, ACP, x402, and GreenHelix escrow.\"\"\"\n\n    def __init__(self, api_key: str, seller_agent_id: str):\n        self.api_key = api_key\n        self.seller_agent_id = seller_agent_id\n        self.headers = {\n            \"Authorization\": f\"Bearer {api_key}\",\n            \"Content-Type\": \"application\u002Fjson\",\n        }\n\n    def _ghx(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute a GreenHelix tool.\"\"\"\n        resp = requests.post(\n            f\"{GATEWAY_URL}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n            headers=self.headers,\n            timeout=30,\n        )\n        resp.raise_for_status()\n        return resp.json()\n\n    def checkout_ucp(\n        self, buyer_agent_id: str, items: list[dict], total: float\n    ) -> CheckoutResult:\n        \"\"\"UCP checkout: structured catalog query + merchant payment.\n\n        In production, this calls the UCP catalog API to validate\n        availability and then redirects to the merchant's payment page.\n        We wrap it in GreenHelix escrow for buyer protection.\n        \"\"\"\n        # Create escrow to protect the buyer\n        escrow = self._ghx(\"create_escrow\", {\n            \"payer_agent_id\": buyer_agent_id,\n            \"payee_agent_id\": self.seller_agent_id,\n            \"amount\": str(total),\n            \"description\": f\"UCP order: {len(items)} items\",\n        })\n\n        # Record the payment intent for UCP tracking\n        intent = self._ghx(\"create_payment_intent\", {\n            \"payer_agent_id\": buyer_agent_id,\n            \"payee_agent_id\": self.seller_agent_id,\n            \"amount\": str(total),\n            \"currency\": \"USD\",\n            \"description\": \"UCP-routed order with escrow protection\",\n        })\n\n        return CheckoutResult(\n            protocol=\"ucp\",\n            status=\"escrow_created\",\n            transaction_id=escrow.get(\"escrow_id\", \"\"),\n            amount=str(total),\n            instructions={\n                \"escrow_id\": escrow.get(\"escrow_id\"),\n                \"payment_intent_id\": intent.get(\"intent_id\"),\n                \"next_step\": \"Buyer confirms delivery, then escrow releases.\",\n            },\n        )\n\n    def checkout_acp(\n        self, buyer_agent_id: str, items: list[dict], total: float,\n        stripe_spt: str,\n    ) -> CheckoutResult:\n        \"\"\"ACP checkout: Stripe Shared Payment Token flow.\n\n        The buyer agent holds an SPT (delegated by its human principal).\n        We validate the SPT, charge via Stripe, and record on GreenHelix.\n        \"\"\"\n        # Record the payment on GreenHelix for auditing\n        intent = self._ghx(\"create_payment_intent\", {\n            \"payer_agent_id\": buyer_agent_id,\n            \"payee_agent_id\": self.seller_agent_id,\n            \"amount\": str(total),\n            \"currency\": \"USD\",\n            \"description\": f\"ACP checkout via Stripe SPT\",\n        })\n\n        # In production: call Stripe API with the SPT to charge\n        # stripe.PaymentIntent.create(amount=int(total*100), ...)\n\n        return CheckoutResult(\n            protocol=\"acp\",\n            status=\"payment_captured\",\n            transaction_id=intent.get(\"intent_id\", \"\"),\n            amount=str(total),\n            instructions={\n                \"stripe_spt_used\": True,\n                \"intent_id\": intent.get(\"intent_id\"),\n                \"next_step\": \"Payment captured. Fulfillment begins.\",\n            },\n        )\n\n    def checkout_x402(\n        self, buyer_agent_id: str, items: list[dict], total: float,\n    ) -> CheckoutResult:\n        \"\"\"x402 checkout: HTTP 402 micropayment flow.\n\n        Returns 402 payment requirement. Buyer settles in USDC via\n        facilitator, then retries with X-PAYMENT-PROOF header.\n        \"\"\"\n        # Generate a unique payment requirement\n        payment_id = hashlib.sha256(\n            f\"{buyer_agent_id}:{time.time()}\".encode()\n        ).hexdigest()[:16]\n\n        # Record on GreenHelix\n        intent = self._ghx(\"create_payment_intent\", {\n            \"payer_agent_id\": buyer_agent_id,\n            \"payee_agent_id\": self.seller_agent_id,\n            \"amount\": str(total),\n            \"currency\": \"USD\",\n            \"description\": f\"x402 payment requirement {payment_id}\",\n        })\n\n        return CheckoutResult(\n            protocol=\"x402\",\n            status=\"payment_required\",\n            transaction_id=payment_id,\n            amount=str(total),\n            instructions={\n                \"http_status\": 402,\n                \"payment_address\": \"0x742d35Cc6634C0532925a3b844Bc9e7595f2bD18\",\n                \"currency\": \"USDC\",\n                \"network\": \"base\",\n                \"facilitator\": \"https:\u002F\u002Fx402.org\u002Ffacilitator\",\n                \"intent_id\": intent.get(\"intent_id\"),\n                \"next_step\": \"Pay via facilitator, retry with X-PAYMENT-PROOF header.\",\n            },\n        )\n\n    def checkout_escrow(\n        self, buyer_agent_id: str, items: list[dict], total: float,\n    ) -> CheckoutResult:\n        \"\"\"GreenHelix native escrow checkout.\"\"\"\n        escrow = self._ghx(\"create_escrow\", {\n            \"payer_agent_id\": buyer_agent_id,\n            \"payee_agent_id\": self.seller_agent_id,\n            \"amount\": str(total),\n            \"description\": f\"Direct escrow: {len(items)} items, ${total:.2f}\",\n        })\n\n        return CheckoutResult(\n            protocol=\"greenhelix_escrow\",\n            status=\"escrow_created\",\n            transaction_id=escrow.get(\"escrow_id\", \"\"),\n            amount=str(total),\n            instructions={\n                \"escrow_id\": escrow.get(\"escrow_id\"),\n                \"next_step\": \"Seller fulfills order. Buyer releases escrow on delivery.\",\n            },\n        )\n\n    def route_checkout(\n        self, buyer_agent_id: str, items: list[dict], total: float,\n        preferred_protocol: str = \"greenhelix_escrow\",\n        stripe_spt: Optional[str] = None,\n    ) -> CheckoutResult:\n        \"\"\"Route to the appropriate checkout flow based on protocol preference.\"\"\"\n        router = {\n            \"ucp\": lambda: self.checkout_ucp(buyer_agent_id, items, total),\n            \"acp\": lambda: self.checkout_acp(buyer_agent_id, items, total, stripe_spt or \"\"),\n            \"x402\": lambda: self.checkout_x402(buyer_agent_id, items, total),\n            \"greenhelix_escrow\": lambda: self.checkout_escrow(buyer_agent_id, items, total),\n        }\n        handler = router.get(preferred_protocol)\n        if not handler:\n            raise ValueError(f\"Unsupported protocol: {preferred_protocol}\")\n        return handler()\n\n\n# Usage\ncheckout = MultiProtocolCheckout(\n    api_key=\"your-api-key\",\n    seller_agent_id=\"precision-parts-agent\",\n)\n\n# Route based on buyer's preferred protocol\nresult = checkout.route_checkout(\n    buyer_agent_id=\"buyer-agent-007\",\n    items=[{\"sku\": \"PBB-608-2RS-ABEC7\", \"quantity\": 100}],\n    total=475.00,\n    preferred_protocol=\"greenhelix_escrow\",\n)\nprint(f\"Protocol: {result.protocol}, Status: {result.status}\")\nprint(f\"Transaction: {result.transaction_id}\")\n```\n\n### Protocol Selection Decision Tree\n\n```\nIs the buyer a ChatGPT user with a Stripe SPT?\n  └─ Yes → ACP (highest conversion for ChatGPT users)\n  └─ No →\n      Is the transaction \u003C $0.50?\n        └─ Yes → x402 (sub-cent fees, USDC settlement)\n        └─ No →\n            Does the buyer need escrow protection?\n              └─ Yes → GreenHelix Escrow (funds locked until delivery)\n              └─ No →\n                  Is the buyer on Google Shopping or Shopify?\n                    └─ Yes → UCP (structured catalog integration)\n                    └─ No → GreenHelix Escrow (safest default)\n```\n\n> **Key Takeaways**\n>\n> - UCP, ACP, and x402 each serve different buyer segments and transaction sizes. Most storefronts should support at least two protocols.\n> - ACP delivers 2-3x higher conversion for ChatGPT users via Instant Checkout. x402 enables sub-cent micropayments that card rails cannot support.\n> - GreenHelix escrow wraps any protocol with buyer protection -- use it as the default for agent-to-agent transactions where trust is not yet established.\n> - A multi-protocol checkout handler with routing logic can be built in a single class. Route based on buyer capabilities, transaction size, and trust requirements.\n> - Cross-reference P19 (Payment Rails Playbook) for deep x402 and MPP implementation details, and P13 (Interoperability Bridge) for protocol bridging patterns.\n\n---\n\n## Chapter 4: Structured Product Feeds That Win\n\n### The Completeness Cliff\n\nSalsify analyzed 2.3 million product listings across major U.S. retail platforms in Q1 2026. The finding that reshaped the industry: AI agent visibility is not a linear function of attribute completeness. It is a step function.\n\n| Attribute Completeness | Relative AI Agent Visibility | Agent-Attributed Orders (Index) |\n|---|---|---|\n| \u003C 80% | 1x (baseline) | 100 |\n| 80% - 89% | 1.2x | 115 |\n| 90% - 94% | 1.5x | 140 |\n| 95% - 98% | 2.1x | 210 |\n| 99% - 99.8% | 2.8x | 290 |\n| 99.9%+ | 3.8x | 380 |\n\nThe jump from 98% to 99.9% -- filling in those last few attributes -- nearly doubles visibility. This is because AI agents use embedding-based retrieval, and each additional structured attribute adds a new dimension to the embedding vector that can match queries. A product missing `operating_temp_range` is invisible to every query that includes temperature requirements, even if the product physically meets the spec.\n\n### Attribute Completeness Scoring\n\nBuild a scoring system that identifies gaps in your product data before they cost you visibility.\n\n```python\nfrom dataclasses import dataclass, field\n\n\n@dataclass\nclass CompletenessReport:\n    sku: str\n    score: float\n    total_fields: int\n    filled_fields: int\n    missing: list[str] = field(default_factory=list)\n    warnings: list[str] = field(default_factory=list)\n\n\n# Define required and recommended attributes by category\nATTRIBUTE_REQUIREMENTS = {\n    \"industrial_components\": {\n        \"required\": [\n            \"name\", \"sku\", \"brand\", \"price\", \"description\",\n            \"material\", \"dimensions\", \"weight\", \"certifications\",\n        ],\n        \"recommended\": [\n            \"mpn\", \"operating_temp_range\", \"max_load_rating\",\n            \"tolerance\", \"finish\", \"country_of_origin\",\n            \"lead_time_days\", \"moq\", \"bulk_pricing_tiers\",\n            \"datasheet_url\", \"cad_model_url\", \"rohs_compliant\",\n        ],\n        \"optional\": [\n            \"color\", \"packaging_type\", \"shelf_life\",\n            \"hazmat_classification\", \"customs_tariff_code\",\n        ],\n    },\n    \"digital_products\": {\n        \"required\": [\n            \"name\", \"sku\", \"price\", \"description\",\n            \"format\", \"file_size\", \"license_type\",\n        ],\n        \"recommended\": [\n            \"version\", \"compatible_platforms\", \"language\",\n            \"sample_url\", \"changelog_url\", \"support_url\",\n            \"api_documentation_url\", \"uptime_sla\",\n        ],\n        \"optional\": [\n            \"trial_available\", \"refund_policy\", \"volume_discounts\",\n        ],\n    },\n}\n\n\ndef score_completeness(\n    product: dict, category: str = \"industrial_components\"\n) -> CompletenessReport:\n    \"\"\"Score a product's attribute completeness.\"\"\"\n    reqs = ATTRIBUTE_REQUIREMENTS.get(category, ATTRIBUTE_REQUIREMENTS[\"industrial_components\"])\n\n    all_fields = reqs[\"required\"] + reqs[\"recommended\"] + reqs[\"optional\"]\n    # Flatten product attributes for checking\n    flat = {**product, **product.get(\"attributes\", {})}\n\n    filled = []\n    missing = []\n    warnings = []\n\n    for attr in reqs[\"required\"]:\n        if flat.get(attr) not in (None, \"\", [], {}):\n            filled.append(attr)\n        else:\n            missing.append(f\"[REQUIRED] {attr}\")\n\n    for attr in reqs[\"recommended\"]:\n        if flat.get(attr) not in (None, \"\", [], {}):\n            filled.append(attr)\n        else:\n            missing.append(f\"[RECOMMENDED] {attr}\")\n\n    for attr in reqs[\"optional\"]:\n        if flat.get(attr) not in (None, \"\", [], {}):\n            filled.append(attr)\n\n    # Quality warnings\n    if flat.get(\"description\") and len(str(flat[\"description\"])) \u003C 50:\n        warnings.append(\"Description is under 50 characters -- expand for better embeddings\")\n    if flat.get(\"price\") and float(flat[\"price\"]) == 0:\n        warnings.append(\"Price is zero -- agents may filter this as unavailable\")\n    if not flat.get(\"certifications\"):\n        warnings.append(\"No certifications listed -- reduces trust signal for B2B agents\")\n\n    total = len(all_fields)\n    score = len(filled) \u002F total if total > 0 else 0.0\n\n    return CompletenessReport(\n        sku=product.get(\"sku\", \"unknown\"),\n        score=round(score * 100, 1),\n        total_fields=total,\n        filled_fields=len(filled),\n        missing=missing,\n        warnings=warnings,\n    )\n\n\n# Score a product\nreport = score_completeness(product_data, \"industrial_components\")\nprint(f\"SKU: {report.sku}\")\nprint(f\"Completeness: {report.score}%\")\nprint(f\"Filled: {report.filled_fields}\u002F{report.total_fields}\")\nfor m in report.missing:\n    print(f\"  Missing: {m}\")\nfor w in report.warnings:\n    print(f\"  Warning: {w}\")\n```\n\n### Machine-Readable Pricing Rules\n\nAgents need to understand your pricing programmatically -- not just the base price, but volume discounts, tiered pricing, promotional rules, and currency conversion. Encode pricing rules in a structured format that agents can parse and calculate against.\n\n```python\nimport json\nfrom typing import Optional\n\n\ndef build_pricing_rules(product: dict) -> dict:\n    \"\"\"Build machine-readable pricing rules for a product.\"\"\"\n    rules = {\n        \"@type\": \"PricingRules\",\n        \"sku\": product[\"sku\"],\n        \"base_price\": {\n            \"amount\": str(product[\"price\"]),\n            \"currency\": \"USD\",\n            \"valid_until\": product.get(\"price_valid_until\", \"2026-12-31\"),\n        },\n        \"volume_discounts\": [\n            {\"min_quantity\": 1, \"max_quantity\": 99, \"unit_price\": str(product[\"price\"])},\n            {\"min_quantity\": 100, \"max_quantity\": 499, \"unit_price\": str(round(product[\"price\"] * 0.90, 2))},\n            {\"min_quantity\": 500, \"max_quantity\": 999, \"unit_price\": str(round(product[\"price\"] * 0.82, 2))},\n            {\"min_quantity\": 1000, \"max_quantity\": None, \"unit_price\": str(round(product[\"price\"] * 0.75, 2))},\n        ],\n        \"bulk_rounding\": \"per_tier\",\n        \"payment_protocols\": [\"ucp\", \"acp\", \"x402\", \"greenhelix_escrow\"],\n        \"accepted_currencies\": [\"USD\", \"EUR\", \"USDC\"],\n    }\n    return rules\n\n\n# Generate pricing rules for catalog\npricing = build_pricing_rules(product_data)\nprint(json.dumps(pricing, indent=2))\n```\n\n### Real-Time Inventory Webhooks\n\nAgents that check inventory get burned by stale data. If your catalog shows 500 units but only 3 remain, the agent starts a checkout that fails at fulfillment. This destroys your trust score. Implement real-time inventory webhooks that push updates to subscribed agents.\n\n```python\nimport time\n\n\nclass InventoryWebhookManager:\n    \"\"\"Manage real-time inventory webhooks via GreenHelix events.\"\"\"\n\n    def __init__(self, client: \"CommerceClient\"):\n        self.client = client\n\n    def publish_inventory_update(self, sku: str, quantity: int, warehouse: str = \"primary\"):\n        \"\"\"Push inventory update to subscribed agents.\"\"\"\n        return self.client.execute(\"publish_event\", {\n            \"event_type\": \"inventory.updated\",\n            \"payload\": {\n                \"sku\": sku,\n                \"available_quantity\": quantity,\n                \"warehouse\": warehouse,\n                \"timestamp\": time.time(),\n                \"in_stock\": quantity > 0,\n                \"low_stock_warning\": quantity \u003C 50,\n            },\n        })\n\n    def publish_price_change(self, sku: str, old_price: float, new_price: float):\n        \"\"\"Notify subscribed agents of a price change.\"\"\"\n        return self.client.execute(\"publish_event\", {\n            \"event_type\": \"pricing.updated\",\n            \"payload\": {\n                \"sku\": sku,\n                \"old_price\": str(old_price),\n                \"new_price\": str(new_price),\n                \"change_pct\": str(round((new_price - old_price) \u002F old_price * 100, 2)),\n                \"effective_at\": time.time(),\n            },\n        })\n\n\n# Usage\nwebhook_mgr = InventoryWebhookManager(client)\n\n# Inventory dropped -- push to all subscribed agents\nwebhook_mgr.publish_inventory_update(\"PBB-608-2RS-ABEC7\", quantity=47)\n\n# Price reduction -- agents watching this SKU get notified\nwebhook_mgr.publish_price_change(\"PBB-608-2RS-ABEC7\", old_price=4.75, new_price=4.25)\n```\n\n### Product Feed Generator with Validation\n\nCombine schemas, pricing, and inventory into a validated product feed that agents consume.\n\n```python\nimport json\nimport time\nfrom typing import Optional\n\n\nclass ProductFeedGenerator:\n    \"\"\"Generate validated, agent-ready product feeds.\"\"\"\n\n    def __init__(self, client: \"CommerceClient\", seller_id: str):\n        self.client = client\n        self.seller_id = seller_id\n\n    def generate_feed(\n        self, products: list[dict], category: str = \"industrial_components\"\n    ) -> dict:\n        \"\"\"Generate a complete product feed with validation.\"\"\"\n        feed_items = []\n        errors = []\n        total_score = 0.0\n\n        for product in products:\n            # Score completeness\n            report = score_completeness(product, category)\n            total_score += report.score\n\n            if report.score \u003C 90.0:\n                errors.append(\n                    f\"SKU {product['sku']}: completeness {report.score}% \"\n                    f\"(below 90% threshold). Missing: {report.missing[:3]}\"\n                )\n                continue\n\n            # Build the feed item\n            item = {\n                \"schema\": build_product_schema(product),\n                \"pricing\": build_pricing_rules(product),\n                \"inventory\": {\n                    \"available\": product.get(\"inventory\", 0),\n                    \"in_stock\": product.get(\"inventory\", 0) > 0,\n                    \"updated_at\": time.time(),\n                },\n                \"completeness_score\": report.score,\n            }\n            feed_items.append(item)\n\n        avg_score = total_score \u002F len(products) if products else 0.0\n\n        feed = {\n            \"@context\": \"https:\u002F\u002Fschema.org\",\n            \"@type\": \"ProductFeed\",\n            \"seller\": self.seller_id,\n            \"generated_at\": time.time(),\n            \"total_products\": len(products),\n            \"included_products\": len(feed_items),\n            \"excluded_products\": len(errors),\n            \"average_completeness\": round(avg_score, 1),\n            \"items\": feed_items,\n            \"errors\": errors,\n        }\n\n        return feed\n\n    def publish_feed(self, feed: dict) -> dict:\n        \"\"\"Publish the feed and register\u002Fupdate on GreenHelix marketplace.\"\"\"\n        # Update service registration with feed metadata\n        result = self.client.execute(\"register_service\", {\n            \"name\": f\"{self.seller_id} Product Feed\",\n            \"description\": (\n                f\"Structured product feed: {feed['included_products']} products, \"\n                f\"{feed['average_completeness']}% avg completeness. \"\n                f\"Updated {time.strftime('%Y-%m-%d %H:%M UTC', time.gmtime())}.\"\n            ),\n            \"endpoint\": f\"https:\u002F\u002F{self.seller_id}.example.com\u002Ffeed.json\",\n            \"price\": 0.0,\n            \"tags\": [\"product-feed\", \"structured-data\", \"real-time-inventory\"],\n            \"category\": \"product_catalog\",\n        })\n        return result\n\n\n# Generate and publish\nfeed_gen = ProductFeedGenerator(client, seller_id=\"precision-parts\")\nfeed = feed_gen.generate_feed([product_data])\nprint(f\"Feed: {feed['included_products']} products, {feed['average_completeness']}% avg completeness\")\nprint(f\"Excluded: {len(feed['errors'])} products below threshold\")\n\n# Publish to marketplace\nfeed_gen.publish_feed(feed)\n```\n\n### Variant Handling\n\nProducts with variants (sizes, colors, configurations) are a common source of completeness failures. Each variant must be a distinct feed item with its own SKU, attributes, and inventory count.\n\n```python\ndef expand_variants(base_product: dict, variants: list[dict]) -> list[dict]:\n    \"\"\"Expand a base product into variant-specific feed items.\n\n    Each variant overrides specific attributes of the base product\n    and gets its own SKU.\n    \"\"\"\n    expanded = []\n    for variant in variants:\n        item = {**base_product}\n        item[\"attributes\"] = {**base_product.get(\"attributes\", {})}\n\n        # Override with variant-specific values\n        for key, value in variant.items():\n            if key in (\"sku_suffix\", \"variant_label\"):\n                continue\n            if key in (\"attributes\",):\n                item[\"attributes\"].update(value)\n            else:\n                item[key] = value\n\n        # Generate variant SKU\n        item[\"sku\"] = f\"{base_product['sku']}-{variant.get('sku_suffix', 'V')}\"\n        item[\"name\"] = f\"{base_product['name']} - {variant.get('variant_label', '')}\"\n\n        expanded.append(item)\n\n    return expanded\n\n\n# Example: bearing with size variants\nsize_variants = [\n    {\"sku_suffix\": \"8MM\", \"variant_label\": \"8mm Bore\", \"price\": 4.75, \"inventory\": 24500,\n     \"attributes\": {\"bore_diameter_mm\": \"8\", \"outer_diameter_mm\": \"22\", \"width_mm\": \"7\"}},\n    {\"sku_suffix\": \"10MM\", \"variant_label\": \"10mm Bore\", \"price\": 5.25, \"inventory\": 18200,\n     \"attributes\": {\"bore_diameter_mm\": \"10\", \"outer_diameter_mm\": \"26\", \"width_mm\": \"8\"}},\n    {\"sku_suffix\": \"12MM\", \"variant_label\": \"12mm Bore\", \"price\": 6.50, \"inventory\": 9800,\n     \"attributes\": {\"bore_diameter_mm\": \"12\", \"outer_diameter_mm\": \"32\", \"width_mm\": \"10\"}},\n]\n\nall_variants = expand_variants(product_data, size_variants)\nprint(f\"Generated {len(all_variants)} variant SKUs from 1 base product\")\n```\n\n> **Key Takeaways**\n>\n> - Attribute completeness follows a step function: 99.9% completeness delivers 3-4x the AI agent visibility of 90% completeness. The last few percent matter most.\n> - Build automated completeness scoring into your product data pipeline. Flag any product below 95% for enrichment before it enters the feed.\n> - Machine-readable pricing rules (volume discounts, tier breakpoints, accepted currencies) let agents calculate total cost without human intervention.\n> - Real-time inventory webhooks via GreenHelix `publish_event` prevent stale-data checkout failures that destroy trust scores.\n> - Every product variant needs its own SKU, attributes, and inventory count. Do not collapse variants into a single listing.\n\n---\n\n## Chapter 5: Agent Discovery via GreenHelix Marketplace\n\n### The Discovery Problem\n\nYou built the storefront. Your product feeds score 99.5% completeness. Your checkout handles four payment protocols. But none of it matters if agents cannot find you.\n\nThe GreenHelix Marketplace solves this with three tools that form the discovery pipeline:\n\n1. **`register_service`** -- List your service with structured metadata, tags, and pricing.\n2. **`search_services`** -- Agents query the marketplace with natural language or structured filters.\n3. **`best_match`** -- Returns the single highest-ranked service for a query, factoring in relevance, trust score, ratings, and response time.\n\nThe ranking algorithm behind `best_match` weights five signals:\n\n| Signal | Weight | How to Optimize |\n|---|---|---|\n| **Query relevance** | 35% | Match your service description to likely agent queries. Use specific, attribute-rich descriptions. |\n| **Trust score** | 25% | Build trust with `submit_metrics` and `build_claim_chain`. Verified performance data outweighs self-reported claims. |\n| **Service rating** | 20% | Deliver quality consistently. Ratings come from `rate_service` calls by buyer agents post-transaction. |\n| **Response time** | 10% | Keep your endpoint fast. The marketplace tracks latency from health checks. Under 200ms is competitive. |\n| **Price competitiveness** | 10% | Priced reasonably relative to comparable services. Not necessarily cheapest -- value-adjusted. |\n\n### Full Registration Walkthrough\n\nRegister a service with rich metadata that maximizes each ranking signal.\n\n```python\nimport os\nimport time\n\nGATEWAY_URL = os.environ.get(\"GREENHELIX_API_URL\", \"https:\u002F\u002Fsandbox.greenhelix.net\")\n\napi_key = os.environ[\"GREENHELIX_API_KEY\"]\nheaders = {\n    \"Authorization\": f\"Bearer {api_key}\",\n    \"Content-Type\": \"application\u002Fjson\",\n}\n\n\ndef ghx(tool: str, input_data: dict) -> dict:\n    \"\"\"Execute a GreenHelix tool.\"\"\"\n    resp = requests.post(\n        f\"{GATEWAY_URL}\u002Fv1\",\n        json={\"tool\": tool, \"input\": input_data},\n        headers=headers,\n        timeout=30,\n    )\n    resp.raise_for_status()\n    return resp.json()\n\n\n# Step 1: Register your agent identity\nagent_registration = ghx(\"register_agent\", {\n    \"agent_id\": \"precision-parts-agent\",\n    \"public_key\": \"base64-encoded-ed25519-public-key\",\n    \"name\": \"Precision Parts Direct\",\n})\nprint(f\"Agent registered: {agent_registration}\")\n\n# Step 2: Create a wallet and fund it\nwallet = ghx(\"create_wallet\", {})\ndeposit = ghx(\"deposit\", {\"amount\": \"100.00\"})\nprint(f\"Wallet funded: ${deposit}\")\n\n# Step 3: Register your service on the marketplace\nservice = ghx(\"register_service\", {\n    \"name\": \"Precision Parts Catalog API\",\n    \"description\": (\n        \"Agent-ready product catalog: 12,000+ precision-machined industrial \"\n        \"components including bearings, shafts, seals, and fasteners. \"\n        \"JSON-LD product schemas with 99.5% average attribute completeness. \"\n        \"Real-time inventory via webhooks. Volume pricing with 4 discount \"\n        \"tiers. Supports checkout via UCP, ACP, x402, and GreenHelix escrow. \"\n        \"Average response time: 45ms. ISO 9001:2015 certified supply chain.\"\n    ),\n    \"endpoint\": \"https:\u002F\u002Fparts.example.com\",\n    \"price\": 0.0,  # Free discovery; revenue from product sales\n    \"tags\": [\n        \"precision-parts\", \"bearings\", \"industrial\", \"b2b\",\n        \"iso-certified\", \"real-time-inventory\", \"bulk-pricing\",\n        \"agent-ready\", \"json-ld\", \"structured-data\",\n    ],\n    \"category\": \"industrial_components\",\n})\nservice_id = service.get(\"service_id\", \"\")\nprint(f\"Service registered: {service_id}\")\n```\n\n### Building Trust Signals\n\nTrust score accounts for 25% of the `best_match` ranking. Build it with two tools: `submit_metrics` (report verified performance data) and `build_claim_chain` (create a cryptographic chain of evidence linking claims to outcomes).\n\n```python\n# Step 4: Submit performance metrics\n# These are verified by the gateway and contribute to your trust score.\nmetrics = ghx(\"submit_metrics\", {\n    \"agent_id\": \"precision-parts-agent\",\n    \"metrics\": {\n        \"orders_fulfilled_30d\": 1247,\n        \"on_time_delivery_pct\": 98.6,\n        \"return_rate_pct\": 0.3,\n        \"avg_response_time_ms\": 45,\n        \"catalog_completeness_pct\": 99.5,\n        \"active_skus\": 12847,\n        \"escrow_completion_rate_pct\": 99.8,\n    },\n})\nprint(f\"Metrics submitted: {metrics}\")\n\n# Step 5: Build a claim chain\n# Each claim links to verifiable evidence. The chain is cryptographically\n# signed and can be independently verified by any agent.\nclaim_chain = ghx(\"build_claim_chain\", {\n    \"agent_id\": \"precision-parts-agent\",\n    \"claims\": [\n        {\n            \"claim_type\": \"certification\",\n            \"claim_value\": \"ISO 9001:2015\",\n            \"evidence_url\": \"https:\u002F\u002Fparts.example.com\u002Fcerts\u002Fiso9001.pdf\",\n        },\n        {\n            \"claim_type\": \"performance\",\n            \"claim_value\": \"98.6% on-time delivery (30-day rolling)\",\n            \"evidence_url\": \"https:\u002F\u002Fparts.example.com\u002Fmetrics\u002Fdelivery\",\n        },\n        {\n            \"claim_type\": \"catalog\",\n            \"claim_value\": \"12,847 active SKUs with 99.5% completeness\",\n            \"evidence_url\": \"https:\u002F\u002Fparts.example.com\u002Ffeed.json\",\n        },\n    ],\n})\nprint(f\"Claim chain built: {claim_chain}\")\n\n# Step 6: Check your trust score\ntrust = ghx(\"get_trust_score\", {\n    \"agent_id\": \"precision-parts-agent\",\n})\nprint(f\"Trust score: {trust}\")\n```\n\n### Optimizing for search_services and best_match\n\nWhen a buyer agent calls `search_services`, the marketplace performs semantic search against service descriptions. When it calls `best_match`, it adds ranking signals. Optimize for both.\n\n```python\n# How buyer agents find you:\n\n# Broad search -- returns multiple results ranked by relevance\nsearch_results = ghx(\"search_services\", {\n    \"query\": \"precision bearings with ISO certification and bulk pricing\",\n})\nprint(f\"Search returned {len(search_results.get('services', []))} results\")\n\n# Best match -- returns the single top-ranked service\ntop_result = ghx(\"best_match\", {\n    \"query\": \"ABEC-7 ball bearings with real-time inventory API\",\n})\nprint(f\"Best match: {top_result}\")\n\n# Verify your ranking by checking trust score and reputation\nreputation = ghx(\"get_agent_reputation\", {\n    \"agent_id\": \"precision-parts-agent\",\n})\nprint(f\"Reputation: {reputation}\")\n```\n\n### The Description Optimization Checklist\n\nYour service description is the single most impactful field for `search_services` ranking. Treat it like SEO for agents.\n\n| Element | Include? | Example |\n|---|---|---|\n| Product count | Yes | \"12,000+ precision-machined components\" |\n| Product categories | Yes | \"bearings, shafts, seals, fasteners\" |\n| Data quality signal | Yes | \"99.5% average attribute completeness\" |\n| Data format | Yes | \"JSON-LD product schemas\" |\n| Real-time capabilities | Yes | \"Real-time inventory via webhooks\" |\n| Pricing structure | Yes | \"Volume pricing with 4 discount tiers\" |\n| Payment protocols | Yes | \"UCP, ACP, x402, GreenHelix escrow\" |\n| Performance metric | Yes | \"Average response time: 45ms\" |\n| Certifications | Yes | \"ISO 9001:2015 certified supply chain\" |\n| Vague marketing copy | No | \"World-class quality\" (meaningless to agents) |\n\nEvery keyword in your description is a potential match for an agent query. Be specific, quantitative, and structured.\n\n> **Key Takeaways**\n>\n> - The GreenHelix marketplace uses five ranking signals: query relevance (35%), trust score (25%), ratings (20%), response time (10%), and price competitiveness (10%).\n> - `register_service` with a rich, keyword-dense description is the foundation. Include product count, categories, data quality metrics, payment protocols, and performance numbers.\n> - Trust signals from `submit_metrics` and `build_claim_chain` account for 25% of ranking. Cryptographic claim chains are more credible than self-reported descriptions.\n> - Optimize your description like SEO for agents: specific, quantitative, structured. Avoid vague marketing language that agents cannot parse.\n> - Cross-reference P4 (Commerce Toolkit) for the full `AgentCommerce` class and P18 (Pricing & Monetization) for marketplace listing economics.\n\n---\n\n## Chapter 6: Agent-to-Agent Payment Flows\n\n### Payment Primitives\n\nThe GreenHelix gateway provides five payment primitives that cover the full lifecycle of agent-to-agent commerce:\n\n| Primitive | Tool | Purpose |\n|---|---|---|\n| **Escrow** | `create_escrow` \u002F `release_escrow` \u002F `cancel_escrow` | Lock funds until work is verified. The core trust mechanism. |\n| **Performance Escrow** | `create_performance_escrow` \u002F `check_performance_escrow` | Auto-release when measurable metrics exceed a threshold. |\n| **Subscription** | `create_subscription` \u002F `cancel_subscription` | Recurring payments for ongoing services. |\n| **Deposit** | `deposit` \u002F `get_balance` | Fund agent wallets for payment capability. |\n| **Dispute** | `create_dispute` \u002F `resolve_dispute` | Structured disagreement resolution with evidence. |\n\n### Escrow-Protected Product Purchases\n\nThe most common pattern: a buyer agent locks funds in escrow, the seller fulfills the order, and the buyer releases payment on delivery confirmation.\n\n```python\nimport os\nimport time\n\napi_key = os.environ[\"GREENHELIX_API_KEY\"]\nheaders = {\n    \"Authorization\": f\"Bearer {api_key}\",\n    \"Content-Type\": \"application\u002Fjson\",\n}\n\n\ndef ghx(tool: str, input_data: dict) -> dict:\n    resp = requests.post(\n        f\"{GATEWAY_URL}\u002Fv1\",\n        json={\"tool\": tool, \"input\": input_data},\n        headers=headers,\n        timeout=30,\n    )\n    resp.raise_for_status()\n    return resp.json()\n\n\nclass EscrowCheckout:\n    \"\"\"Manage escrow-protected product purchases.\"\"\"\n\n    def __init__(self, buyer_id: str, seller_id: str):\n        self.buyer_id = buyer_id\n        self.seller_id = seller_id\n\n    def create_order(self, items: list[dict], total: float) -> dict:\n        \"\"\"Create an escrow-backed order.\"\"\"\n        # Step 1: Verify buyer has sufficient balance\n        balance = ghx(\"get_balance\", {})\n        available = float(balance.get(\"balance\", \"0\"))\n        if available \u003C total:\n            return {\"error\": f\"Insufficient balance: ${available} \u003C ${total}\"}\n\n        # Step 2: Create escrow\n        escrow = ghx(\"create_escrow\", {\n            \"payer_agent_id\": self.buyer_id,\n            \"payee_agent_id\": self.seller_id,\n            \"amount\": str(total),\n            \"description\": (\n                f\"Product order: {len(items)} items. \"\n                f\"SKUs: {', '.join(i['sku'] for i in items)}\"\n            ),\n        })\n\n        return {\n            \"order_id\": escrow.get(\"escrow_id\"),\n            \"status\": \"escrow_locked\",\n            \"amount\": str(total),\n            \"items\": items,\n        }\n\n    def confirm_delivery(self, escrow_id: str) -> dict:\n        \"\"\"Buyer confirms delivery -- release funds to seller.\"\"\"\n        release = ghx(\"release_escrow\", {\"escrow_id\": escrow_id})\n        return {\n            \"escrow_id\": escrow_id,\n            \"status\": \"payment_released\",\n            \"result\": release,\n        }\n\n    def cancel_order(self, escrow_id: str) -> dict:\n        \"\"\"Cancel the order -- return funds to buyer.\"\"\"\n        cancel = ghx(\"cancel_escrow\", {\"escrow_id\": escrow_id})\n        return {\n            \"escrow_id\": escrow_id,\n            \"status\": \"order_cancelled\",\n            \"result\": cancel,\n        }\n\n\n# Full purchase flow\ncheckout = EscrowCheckout(\n    buyer_id=\"buyer-agent-007\",\n    seller_id=\"precision-parts-agent\",\n)\n\n# Place order\norder = checkout.create_order(\n    items=[\n        {\"sku\": \"PBB-608-2RS-ABEC7\", \"quantity\": 100, \"unit_price\": 4.28},\n        {\"sku\": \"PBB-608-2RS-ABEC7-10MM\", \"quantity\": 50, \"unit_price\": 4.73},\n    ],\n    total=664.50,\n)\nprint(f\"Order placed: {order}\")\n\n# ... seller ships, buyer receives ...\n\n# Confirm delivery and release payment\nif order.get(\"order_id\"):\n    result = checkout.confirm_delivery(order[\"order_id\"])\n    print(f\"Payment released: {result}\")\n```\n\n### Performance-Gated Payments\n\nFor services where quality is measurable, performance escrow auto-releases when metrics exceed agreed thresholds. No manual release needed.\n\n```python\n# Create performance escrow for a data enrichment service\n# Funds release automatically when accuracy exceeds 95%\nperf_escrow = ghx(\"create_performance_escrow\", {\n    \"payer_agent_id\": \"buyer-agent-007\",\n    \"payee_agent_id\": \"enrichment-service-agent\",\n    \"amount\": \"500.00\",\n    \"currency\": \"USD\",\n    \"performance_criteria\": {\n        \"min_accuracy\": 0.95,\n        \"min_records_processed\": 10000,\n    },\n    \"evaluation_period_days\": 7,\n})\nperf_escrow_id = perf_escrow.get(\"escrow_id\", \"\")\nprint(f\"Performance escrow created: {perf_escrow_id}\")\n\n# After the service runs, check if criteria are met\ncheck = ghx(\"check_performance_escrow\", {\n    \"escrow_id\": perf_escrow_id,\n})\nprint(f\"Performance check: {check}\")\n# If criteria met → funds auto-release to seller\n# If not met within evaluation period → funds return to buyer\n```\n\n### Subscription Billing\n\nFor ongoing services -- monitoring, data feeds, continuous enrichment -- use subscription billing. The gateway handles recurring charges automatically.\n\n```python\n# Create a monthly subscription for real-time inventory feed access\nsubscription = ghx(\"create_subscription\", {\n    \"payer_agent_id\": \"buyer-agent-007\",\n    \"payee_agent_id\": \"precision-parts-agent\",\n    \"amount\": \"49.00\",\n    \"interval\": \"monthly\",\n})\nsubscription_id = subscription.get(\"subscription_id\", \"\")\nprint(f\"Subscription created: {subscription_id}\")\n\n# Check subscription status\nstatus = ghx(\"get_subscription\", {\n    \"subscription_id\": subscription_id,\n})\nprint(f\"Subscription status: {status}\")\n\n# Cancel when no longer needed\n# cancel = ghx(\"cancel_subscription\", {\"subscription_id\": subscription_id})\n```\n\n### Dispute Resolution\n\nWhen a buyer disputes a transaction -- wrong items, quality below spec, incomplete delivery -- the dispute system provides structured resolution.\n\n```python\nclass DisputeManager:\n    \"\"\"Handle disputes on escrow-backed transactions.\"\"\"\n\n    def open_dispute(self, escrow_id: str, reason: str, evidence: dict) -> dict:\n        \"\"\"Buyer opens a dispute on an active escrow.\"\"\"\n        dispute = ghx(\"create_dispute\", {\n            \"escrow_id\": escrow_id,\n            \"reason\": reason,\n            \"evidence\": evidence,\n        })\n        return dispute\n\n    def respond_to_dispute(self, dispute_id: str, response: str, evidence: dict) -> dict:\n        \"\"\"Seller responds to a dispute with counter-evidence.\"\"\"\n        response_result = ghx(\"resolve_dispute\", {\n            \"dispute_id\": dispute_id,\n            \"resolution\": response,\n            \"evidence\": evidence,\n        })\n        return response_result\n\n\n# Dispute flow example\ndisputes = DisputeManager()\n\n# Buyer: received wrong items\ndispute = disputes.open_dispute(\n    escrow_id=\"esc_abc123\",\n    reason=\"Received ABEC-5 bearings instead of ABEC-7 as ordered\",\n    evidence={\n        \"order_sku\": \"PBB-608-2RS-ABEC7\",\n        \"received_sku\": \"PBB-608-2RS-ABEC5\",\n        \"inspection_report_url\": \"https:\u002F\u002Fbuyer.example.com\u002Freports\u002Finspection_123.pdf\",\n        \"photo_urls\": [\n            \"https:\u002F\u002Fbuyer.example.com\u002Fphotos\u002Flabel_mismatch_1.jpg\",\n            \"https:\u002F\u002Fbuyer.example.com\u002Fphotos\u002Flabel_mismatch_2.jpg\",\n        ],\n    },\n)\nprint(f\"Dispute opened: {dispute}\")\n\n# Seller: respond with resolution (e.g., reshipping correct items)\nresolution = disputes.respond_to_dispute(\n    dispute_id=dispute.get(\"dispute_id\", \"\"),\n    response=\"Acknowledged. Reshipping correct ABEC-7 bearings. Tracking: FDX-789456.\",\n    evidence={\n        \"reshipment_tracking\": \"FDX-789456\",\n        \"correct_sku_confirmed\": \"PBB-608-2RS-ABEC7\",\n        \"estimated_delivery\": \"2026-04-09\",\n    },\n)\nprint(f\"Dispute resolved: {resolution}\")\n```\n\n### Deposit Management\n\nBefore an agent can participate in escrow or subscriptions, it needs a funded wallet. Manage deposits programmatically.\n\n```python\ndef ensure_funded(agent_id: str, minimum_balance: float) -> dict:\n    \"\"\"Ensure agent wallet has sufficient funds, topping up if needed.\"\"\"\n    balance = ghx(\"get_balance\", {})\n    current = float(balance.get(\"balance\", \"0\"))\n\n    if current >= minimum_balance:\n        return {\n            \"status\": \"sufficient\",\n            \"balance\": str(current),\n            \"agent_id\": agent_id,\n        }\n\n    # Top up to 2x the minimum for buffer\n    top_up_amount = (minimum_balance * 2) - current\n    deposit_result = ghx(\"deposit\", {\"amount\": str(round(top_up_amount, 2))})\n\n    return {\n        \"status\": \"topped_up\",\n        \"previous_balance\": str(current),\n        \"deposited\": str(round(top_up_amount, 2)),\n        \"new_balance\": str(current + top_up_amount),\n        \"agent_id\": agent_id,\n    }\n\n\n# Ensure buyer has enough for a $664.50 order\nfunding = ensure_funded(\"buyer-agent-007\", minimum_balance=664.50)\nprint(f\"Wallet status: {funding}\")\n```\n\n> **Key Takeaways**\n>\n> - Escrow is the core payment primitive for agent-to-agent commerce. It eliminates the trust problem: funds lock until work is verified.\n> - Performance escrow automates release based on measurable metrics -- ideal for data processing, enrichment, and any service with quantifiable quality.\n> - Subscription billing handles recurring service access with automatic charges at configurable intervals.\n> - The dispute system provides structured resolution with evidence submission from both parties. Dispute outcomes affect trust scores.\n> - Always verify wallet balance before creating escrow. Use the `ensure_funded` pattern to top up automatically.\n> - Cross-reference P4 (Commerce Toolkit) for split payment patterns and P19 (Payment Rails Playbook) for multi-rail settlement.\n\n---\n\n## Chapter 7: Testing Agent Discoverability\n\n### Why You Need an Agent Simulator\n\nYour storefront is live. Your product feed scores 99.5%. Your marketplace listing is registered. But how do you know an actual AI agent will find you, parse your data correctly, and complete checkout?\n\nYou cannot wait for production traffic to find out. You need an agent simulator -- a test harness that mimics how Gemini, ChatGPT, Perplexity, and Claude shopping agents discover, evaluate, and purchase from storefronts. The simulator queries your endpoints, validates structured data, measures response latency, and produces an Agent Readiness Index (ARI) score.\n\n### The Agent Readiness Index\n\nThe ARI score grades your storefront across five dimensions:\n\n| Dimension | Weight | What It Measures | Target |\n|---|---|---|---|\n| **Discoverability** | 25% | Can agents find your manifest and OpenAPI spec? | 100% |\n| **Data Quality** | 30% | Attribute completeness, schema validity, pricing structure | > 99% |\n| **Marketplace Ranking** | 20% | Position in `search_services` and `best_match` results | Top 3 |\n| **Checkout Completeness** | 15% | Can agents initiate checkout via all advertised protocols? | All protocols work |\n| **Response Performance** | 10% | Endpoint latency under load | \u003C 200ms p95 |\n\n### Building the Agent Simulator\n\n```python\nimport requests\nimport time\nimport json\nfrom dataclasses import dataclass, field\nfrom typing import Optional\n\nGATEWAY_URL = os.environ.get(\"GREENHELIX_API_URL\", \"https:\u002F\u002Fsandbox.greenhelix.net\")\n\n\n@dataclass\nclass TestResult:\n    dimension: str\n    test_name: str\n    passed: bool\n    score: float  # 0.0 to 1.0\n    latency_ms: float\n    details: str = \"\"\n\n\n@dataclass\nclass ARIReport:\n    overall_score: float = 0.0\n    grade: str = \"\"\n    results: list[TestResult] = field(default_factory=list)\n    recommendations: list[str] = field(default_factory=list)\n\n\nclass AgentSimulator:\n    \"\"\"Simulate AI shopping agent behavior to test storefront readiness.\"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        storefront_url: str,\n        service_query: str,\n    ):\n        self.api_key = api_key\n        self.storefront_url = storefront_url\n        self.service_query = service_query\n        self.headers = {\n            \"Authorization\": f\"Bearer {api_key}\",\n            \"Content-Type\": \"application\u002Fjson\",\n        }\n        self.results: list[TestResult] = []\n\n    def _ghx(self, tool: str, input_data: dict) -> dict:\n        resp = requests.post(\n            f\"{GATEWAY_URL}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n            headers=self.headers,\n            timeout=30,\n        )\n        resp.raise_for_status()\n        return resp.json()\n\n    def _timed_get(self, url: str) -> tuple[Optional[dict], float]:\n        \"\"\"GET a URL and return (parsed_json, latency_ms).\"\"\"\n        start = time.time()\n        try:\n            resp = requests.get(url, timeout=10)\n            latency = (time.time() - start) * 1000\n            if resp.status_code == 200:\n                return resp.json(), latency\n            return None, latency\n        except Exception:\n            return None, (time.time() - start) * 1000\n\n    # ── Discoverability Tests ──────────────────────────────────\n\n    def test_manifest(self) -> TestResult:\n        \"\"\"Test: Can agents find .well-known\u002Fai-plugin.json?\"\"\"\n        url = f\"{self.storefront_url}\u002F.well-known\u002Fai-plugin.json\"\n        data, latency = self._timed_get(url)\n\n        if data and \"name_for_model\" in data and \"api\" in data:\n            has_description = bool(data.get(\"description_for_model\", \"\"))\n            has_api_url = bool(data.get(\"api\", {}).get(\"url\", \"\"))\n            score = 1.0 if (has_description and has_api_url) else 0.7\n            result = TestResult(\n                dimension=\"discoverability\",\n                test_name=\"ai_plugin_manifest\",\n                passed=True,\n                score=score,\n                latency_ms=latency,\n                details=f\"Manifest found. description_for_model: {has_description}, api.url: {has_api_url}\",\n            )\n        else:\n            result = TestResult(\n                dimension=\"discoverability\",\n                test_name=\"ai_plugin_manifest\",\n                passed=False,\n                score=0.0,\n                latency_ms=latency,\n                details=\"Manifest missing or malformed\",\n            )\n\n        self.results.append(result)\n        return result\n\n    def test_openapi_spec(self) -> TestResult:\n        \"\"\"Test: Is the OpenAPI spec reachable and valid?\"\"\"\n        # First get the manifest to find the OpenAPI URL\n        manifest_url = f\"{self.storefront_url}\u002F.well-known\u002Fai-plugin.json\"\n        manifest, _ = self._timed_get(manifest_url)\n\n        if not manifest:\n            result = TestResult(\n                dimension=\"discoverability\",\n                test_name=\"openapi_spec\",\n                passed=False,\n                score=0.0,\n                latency_ms=0,\n                details=\"Cannot test: manifest not found\",\n            )\n            self.results.append(result)\n            return result\n\n        api_url = manifest.get(\"api\", {}).get(\"url\", \"\")\n        if not api_url:\n            result = TestResult(\n                dimension=\"discoverability\",\n                test_name=\"openapi_spec\",\n                passed=False,\n                score=0.0,\n                latency_ms=0,\n                details=\"No api.url in manifest\",\n            )\n            self.results.append(result)\n            return result\n\n        data, latency = self._timed_get(api_url)\n        has_paths = bool(data and data.get(\"paths\"))\n        has_info = bool(data and data.get(\"info\"))\n\n        result = TestResult(\n            dimension=\"discoverability\",\n            test_name=\"openapi_spec\",\n            passed=bool(has_paths and has_info),\n            score=1.0 if (has_paths and has_info) else 0.0,\n            latency_ms=latency,\n            details=f\"OpenAPI spec: paths={has_paths}, info={has_info}\",\n        )\n        self.results.append(result)\n        return result\n\n    # ── Marketplace Tests ──────────────────────────────────────\n\n    def test_search_visibility(self) -> TestResult:\n        \"\"\"Test: Does your service appear in search_services results?\"\"\"\n        start = time.time()\n        results = self._ghx(\"search_services\", {\n            \"query\": self.service_query,\n        })\n        latency = (time.time() - start) * 1000\n\n        services = results.get(\"services\", [])\n        found = any(\n            self.storefront_url in str(s)\n            for s in services\n        )\n\n        # Score based on position\n        position = -1\n        for i, s in enumerate(services):\n            if self.storefront_url in str(s):\n                position = i\n                break\n\n        if position == 0:\n            score = 1.0\n        elif position in (1, 2):\n            score = 0.8\n        elif position >= 0:\n            score = 0.5\n        else:\n            score = 0.0\n\n        result = TestResult(\n            dimension=\"marketplace\",\n            test_name=\"search_visibility\",\n            passed=found,\n            score=score,\n            latency_ms=latency,\n            details=f\"Position in search results: {position if position >= 0 else 'not found'}. Total results: {len(services)}\",\n        )\n        self.results.append(result)\n        return result\n\n    def test_best_match(self) -> TestResult:\n        \"\"\"Test: Are you the best_match for your target query?\"\"\"\n        start = time.time()\n        match = self._ghx(\"best_match\", {\n            \"query\": self.service_query,\n        })\n        latency = (time.time() - start) * 1000\n\n        is_top = self.storefront_url in str(match)\n\n        result = TestResult(\n            dimension=\"marketplace\",\n            test_name=\"best_match_ranking\",\n            passed=is_top,\n            score=1.0 if is_top else 0.0,\n            latency_ms=latency,\n            details=f\"Top match: {'Yes' if is_top else 'No'}. Result: {json.dumps(match)[:200]}\",\n        )\n        self.results.append(result)\n        return result\n\n    # ── Data Quality Tests ─────────────────────────────────────\n\n    def test_product_schema(self) -> TestResult:\n        \"\"\"Test: Do product search results return valid JSON-LD schemas?\"\"\"\n        search_url = f\"{self.storefront_url}\u002Fproducts\u002Fsearch\"\n        start = time.time()\n        try:\n            resp = requests.post(\n                search_url,\n                json={\"query\": \"\", \"limit\": 5},\n                timeout=10,\n            )\n            latency = (time.time() - start) * 1000\n            data = resp.json()\n        except Exception:\n            latency = (time.time() - start) * 1000\n            result = TestResult(\n                dimension=\"data_quality\",\n                test_name=\"product_schema_validity\",\n                passed=False,\n                score=0.0,\n                latency_ms=latency,\n                details=\"Product search endpoint unreachable\",\n            )\n            self.results.append(result)\n            return result\n\n        products = data.get(\"results\", [])\n        valid_count = 0\n        for p in products:\n            has_context = \"@context\" in p\n            has_type = \"@type\" in p\n            has_offers = \"offers\" in p\n            has_properties = \"additionalProperty\" in p\n            if all([has_context, has_type, has_offers, has_properties]):\n                valid_count += 1\n\n        score = valid_count \u002F len(products) if products else 0.0\n\n        result = TestResult(\n            dimension=\"data_quality\",\n            test_name=\"product_schema_validity\",\n            passed=score >= 0.9,\n            score=score,\n            latency_ms=latency,\n            details=f\"{valid_count}\u002F{len(products)} products have valid JSON-LD schemas\",\n        )\n        self.results.append(result)\n        return result\n\n    # ── Checkout Tests ─────────────────────────────────────────\n\n    def test_checkout_protocols(self) -> TestResult:\n        \"\"\"Test: Can checkout be initiated for each advertised protocol?\"\"\"\n        checkout_url = f\"{self.storefront_url}\u002Fcheckout\u002Finitiate\"\n        protocols = [\"ucp\", \"acp\", \"x402\", \"greenhelix_escrow\"]\n        working = []\n\n        start = time.time()\n        for protocol in protocols:\n            try:\n                resp = requests.post(\n                    checkout_url,\n                    json={\n                        \"items\": [{\"sku\": \"TEST-SKU\", \"quantity\": 1}],\n                        \"payment_protocol\": protocol,\n                        \"buyer_agent_id\": \"test-simulator\",\n                    },\n                    timeout=10,\n                )\n                if resp.status_code in (200, 201, 402):\n                    working.append(protocol)\n            except Exception:\n                pass\n        latency = (time.time() - start) * 1000\n\n        score = len(working) \u002F len(protocols)\n        result = TestResult(\n            dimension=\"checkout\",\n            test_name=\"protocol_support\",\n            passed=score >= 0.75,\n            score=score,\n            latency_ms=latency,\n            details=f\"Working protocols: {working}. Missing: {set(protocols) - set(working)}\",\n        )\n        self.results.append(result)\n        return result\n\n    # ── Performance Tests ──────────────────────────────────────\n\n    def test_response_latency(self, num_requests: int = 10) -> TestResult:\n        \"\"\"Test: Are endpoints fast enough for agent real-time queries?\"\"\"\n        search_url = f\"{self.storefront_url}\u002Fproducts\u002Fsearch\"\n        latencies = []\n\n        for _ in range(num_requests):\n            start = time.time()\n            try:\n                requests.post(\n                    search_url,\n                    json={\"query\": \"bearing\", \"limit\": 5},\n                    timeout=10,\n                )\n                latencies.append((time.time() - start) * 1000)\n            except Exception:\n                latencies.append(10000)  # penalty for failures\n\n        if not latencies:\n            result = TestResult(\n                dimension=\"performance\",\n                test_name=\"response_latency\",\n                passed=False,\n                score=0.0,\n                latency_ms=0,\n                details=\"No successful requests\",\n            )\n            self.results.append(result)\n            return result\n\n        latencies.sort()\n        p50 = latencies[len(latencies) \u002F\u002F 2]\n        p95 = latencies[int(len(latencies) * 0.95)]\n        avg = sum(latencies) \u002F len(latencies)\n\n        # Score: 1.0 if p95 \u003C 200ms, 0.5 if \u003C 500ms, 0.0 if > 1000ms\n        if p95 \u003C 200:\n            score = 1.0\n        elif p95 \u003C 500:\n            score = 0.5\n        else:\n            score = 0.0\n\n        result = TestResult(\n            dimension=\"performance\",\n            test_name=\"response_latency\",\n            passed=p95 \u003C 200,\n            score=score,\n            latency_ms=p95,\n            details=f\"p50={p50:.0f}ms, p95={p95:.0f}ms, avg={avg:.0f}ms ({num_requests} requests)\",\n        )\n        self.results.append(result)\n        return result\n\n    # ── Report Generation ──────────────────────────────────────\n\n    def run_all(self) -> ARIReport:\n        \"\"\"Run all tests and generate an ARI report.\"\"\"\n        self.results = []\n\n        # Run all test suites\n        self.test_manifest()\n        self.test_openapi_spec()\n        self.test_search_visibility()\n        self.test_best_match()\n        self.test_product_schema()\n        self.test_checkout_protocols()\n        self.test_response_latency()\n\n        # Calculate weighted score\n        weights = {\n            \"discoverability\": 0.25,\n            \"marketplace\": 0.20,\n            \"data_quality\": 0.30,\n            \"checkout\": 0.15,\n            \"performance\": 0.10,\n        }\n\n        dimension_scores = {}\n        for r in self.results:\n            if r.dimension not in dimension_scores:\n                dimension_scores[r.dimension] = []\n            dimension_scores[r.dimension].append(r.score)\n\n        weighted_total = 0.0\n        for dim, scores in dimension_scores.items():\n            avg = sum(scores) \u002F len(scores) if scores else 0.0\n            weight = weights.get(dim, 0.1)\n            weighted_total += avg * weight\n\n        overall = round(weighted_total * 100, 1)\n\n        # Grade\n        if overall >= 90:\n            grade = \"A\"\n        elif overall >= 80:\n            grade = \"B\"\n        elif overall >= 70:\n            grade = \"C\"\n        elif overall >= 60:\n            grade = \"D\"\n        else:\n            grade = \"F\"\n\n        # Recommendations\n        recs = []\n        for r in self.results:\n            if not r.passed:\n                if r.test_name == \"ai_plugin_manifest\":\n                    recs.append(\"Add .well-known\u002Fai-plugin.json with description_for_model and api.url\")\n                elif r.test_name == \"openapi_spec\":\n                    recs.append(\"Publish a valid OpenAPI spec at the URL specified in your manifest\")\n                elif r.test_name == \"search_visibility\":\n                    recs.append(\"Optimize your register_service description with specific keywords\")\n                elif r.test_name == \"best_match_ranking\":\n                    recs.append(\"Build trust signals with submit_metrics and build_claim_chain\")\n                elif r.test_name == \"product_schema_validity\":\n                    recs.append(\"Ensure all products have @context, @type, offers, and additionalProperty\")\n                elif r.test_name == \"protocol_support\":\n                    recs.append(\"Implement all advertised checkout protocols\")\n                elif r.test_name == \"response_latency\":\n                    recs.append(\"Reduce p95 latency below 200ms -- add caching or optimize queries\")\n\n        return ARIReport(\n            overall_score=overall,\n            grade=grade,\n            results=self.results,\n            recommendations=recs,\n        )\n\n\n# Run the simulator\nsimulator = AgentSimulator(\n    api_key=os.environ[\"GREENHELIX_API_KEY\"],\n    storefront_url=\"https:\u002F\u002Fparts.example.com\",\n    service_query=\"precision bearings with ISO certification\",\n)\n\nreport = simulator.run_all()\nprint(f\"\\n{'='*50}\")\nprint(f\"AGENT READINESS INDEX: {report.overall_score}% (Grade: {report.grade})\")\nprint(f\"{'='*50}\")\n\nfor r in report.results:\n    status = \"PASS\" if r.passed else \"FAIL\"\n    print(f\"  [{status}] {r.dimension}\u002F{r.test_name}: {r.score:.0%} ({r.latency_ms:.0f}ms)\")\n    if r.details:\n        print(f\"         {r.details}\")\n\nif report.recommendations:\n    print(f\"\\nRecommendations:\")\n    for i, rec in enumerate(report.recommendations, 1):\n        print(f\"  {i}. {rec}\")\n```\n\n### Interpreting ARI Scores\n\n| Score | Grade | Interpretation | Action |\n|---|---|---|---|\n| 90-100 | A | Agent-ready. Agents can discover, evaluate, and purchase from your storefront. | Monitor and maintain. |\n| 80-89 | B | Mostly ready. One or two gaps reducing visibility or conversion. | Fix specific failures. |\n| 70-79 | C | Functional but underperforming. Missing trust signals or incomplete schemas. | Prioritize data quality and marketplace optimization. |\n| 60-69 | D | Significant gaps. Agents can find you but struggle to complete purchases. | Full audit needed. Use the 14-Day Sprint (Chapter 8). |\n| \u003C 60 | F | Not agent-ready. Most agents will skip your storefront entirely. | Start from Chapter 2 and implement systematically. |\n\n### Continuous Monitoring\n\nRun the simulator on a schedule -- daily or on every deployment -- and track your ARI score over time. Publish the results as metrics on GreenHelix to reinforce your trust score.\n\n```python\ndef publish_ari_as_metrics(report: ARIReport):\n    \"\"\"Publish ARI results as GreenHelix metrics for trust scoring.\"\"\"\n    dimension_scores = {}\n    for r in report.results:\n        if r.dimension not in dimension_scores:\n            dimension_scores[r.dimension] = []\n        dimension_scores[r.dimension].append(r.score)\n\n    metrics = {\n        \"ari_overall_score\": report.overall_score,\n        \"ari_grade\": report.grade,\n    }\n    for dim, scores in dimension_scores.items():\n        avg = sum(scores) \u002F len(scores) if scores else 0\n        metrics[f\"ari_{dim}_score\"] = round(avg * 100, 1)\n\n    ghx(\"submit_metrics\", {\n        \"agent_id\": \"precision-parts-agent\",\n        \"metrics\": metrics,\n    })\n    print(f\"ARI metrics published to GreenHelix\")\n\n\npublish_ari_as_metrics(report)\n```\n\n> **Key Takeaways**\n>\n> - Build an agent simulator that tests five dimensions: discoverability, data quality, marketplace ranking, checkout completeness, and response performance.\n> - The Agent Readiness Index (ARI) provides a single score (0-100) and letter grade for your storefront's agent compatibility. Target 90+ (Grade A).\n> - Run the simulator on every deployment and track ARI over time. Regressions in structured data or latency directly reduce agent-referred revenue.\n> - Publish ARI scores as GreenHelix metrics via `submit_metrics` to reinforce your trust score and marketplace ranking.\n> - The simulator catches problems before production agents do -- a schema regression caught in CI is free; a schema regression caught by a lost sale costs revenue.\n\n---\n\n## Chapter 8: The 14-Day ACO Sprint\n\n### Overview\n\nThe Agent Commerce Optimization (ACO) Sprint is a 14-day execution plan that takes your storefront from zero agent readiness to production-grade discoverability. Each day has specific deliverables, measurable checkpoints, and code tasks. By day 14, your ARI score should be 85+ with a clear path to 95+.\n\n### Days 1-2: Audit Product Data\n\n**Objective**: Assess current product data quality and identify gaps.\n\n**Day 1 Tasks**:\n\n- [ ] Export your full product catalog to a structured format (JSON or CSV)\n- [ ] Run the completeness scoring function from Chapter 4 against every product\n- [ ] Generate a gap report: which products are below 95% completeness?\n- [ ] Identify the 10 most common missing attributes across your catalog\n\n**Day 2 Tasks**:\n\n- [ ] Prioritize products by revenue contribution -- fix the top 20% first (they drive 80% of revenue)\n- [ ] Fill in missing required attributes for all top-revenue products\n- [ ] Set up automated completeness scoring in your CI\u002FCD pipeline\n- [ ] Target: all top-revenue products at 98%+ completeness\n\n```python\n# Day 1-2: Catalog audit script\nimport json\n\n\ndef audit_catalog(products: list[dict], category: str) -> dict:\n    \"\"\"Audit an entire product catalog for agent readiness.\"\"\"\n    results = {\n        \"total_products\": len(products),\n        \"above_99\": 0,\n        \"above_95\": 0,\n        \"above_90\": 0,\n        \"below_90\": 0,\n        \"most_common_missing\": {},\n        \"products_to_fix\": [],\n    }\n\n    for product in products:\n        report = score_completeness(product, category)\n\n        if report.score >= 99.0:\n            results[\"above_99\"] += 1\n        elif report.score >= 95.0:\n            results[\"above_95\"] += 1\n        elif report.score >= 90.0:\n            results[\"above_90\"] += 1\n        else:\n            results[\"below_90\"] += 1\n            results[\"products_to_fix\"].append({\n                \"sku\": report.sku,\n                \"score\": report.score,\n                \"missing\": report.missing[:5],\n            })\n\n        for m in report.missing:\n            attr = m.split(\"] \")[1] if \"] \" in m else m\n            results[\"most_common_missing\"][attr] = (\n                results[\"most_common_missing\"].get(attr, 0) + 1\n            )\n\n    # Sort most common missing by frequency\n    results[\"most_common_missing\"] = dict(\n        sorted(\n            results[\"most_common_missing\"].items(),\n            key=lambda x: x[1],\n            reverse=True,\n        )[:10]\n    )\n\n    return results\n\n\n# Run the audit\n# audit = audit_catalog(all_products, \"industrial_components\")\n# print(json.dumps(audit, indent=2))\n```\n\n### Days 3-5: Implement Manifests and Schemas\n\n**Objective**: Deploy the three layers of agent discoverability.\n\n**Day 3 Tasks**:\n\n- [ ] Create `.well-known\u002Fai-plugin.json` manifest (Chapter 2, Layer 1)\n- [ ] Write `description_for_model` optimized for your top 5 search queries\n- [ ] Deploy manifest to production and verify with `curl`\n\n**Day 4 Tasks**:\n\n- [ ] Implement JSON-LD product schemas using `build_product_schema()` (Chapter 2, Layer 2)\n- [ ] Add schemas to all product pages (embed in HTML) and as API responses\n- [ ] Validate schemas with Google's Rich Results Test\n\n**Day 5 Tasks**:\n\n- [ ] Publish OpenAPI spec at the URL referenced in your manifest (Chapter 2, Layer 3)\n- [ ] Include `\u002Fproducts\u002Fsearch`, `\u002Fproducts\u002F{sku}\u002Finventory`, and `\u002Fcheckout\u002Finitiate` endpoints\n- [ ] Test with an OpenAPI validator (e.g., `openapi-spec-validator` Python package)\n- [ ] Run ARI discoverability tests -- target 100%\n\n```python\n# Day 3-5: Verify all three layers are deployed\ndef verify_storefront_layers(base_url: str) -> dict:\n    \"\"\"Verify all three agent-readiness layers are deployed.\"\"\"\n    checks = {}\n\n    # Layer 1: Manifest\n    try:\n        resp = requests.get(f\"{base_url}\u002F.well-known\u002Fai-plugin.json\", timeout=5)\n        manifest = resp.json()\n        checks[\"manifest\"] = {\n            \"deployed\": resp.status_code == 200,\n            \"has_model_description\": bool(manifest.get(\"description_for_model\")),\n            \"has_api_url\": bool(manifest.get(\"api\", {}).get(\"url\")),\n        }\n    except Exception as e:\n        checks[\"manifest\"] = {\"deployed\": False, \"error\": str(e)}\n\n    # Layer 2: Product schemas (check search endpoint)\n    try:\n        resp = requests.post(\n            f\"{base_url}\u002Fproducts\u002Fsearch\",\n            json={\"query\": \"\", \"limit\": 1},\n            timeout=5,\n        )\n        results = resp.json().get(\"results\", [])\n        if results:\n            has_jsonld = \"@context\" in results[0] and \"@type\" in results[0]\n            checks[\"schemas\"] = {\"deployed\": True, \"valid_jsonld\": has_jsonld}\n        else:\n            checks[\"schemas\"] = {\"deployed\": True, \"valid_jsonld\": False, \"note\": \"No results\"}\n    except Exception as e:\n        checks[\"schemas\"] = {\"deployed\": False, \"error\": str(e)}\n\n    # Layer 3: OpenAPI spec\n    api_url = checks.get(\"manifest\", {}).get(\"has_api_url\")\n    if api_url and checks.get(\"manifest\", {}).get(\"deployed\"):\n        try:\n            manifest_resp = requests.get(f\"{base_url}\u002F.well-known\u002Fai-plugin.json\")\n            api_spec_url = manifest_resp.json().get(\"api\", {}).get(\"url\", \"\")\n            spec_resp = requests.get(api_spec_url, timeout=5)\n            checks[\"openapi\"] = {\n                \"deployed\": spec_resp.status_code == 200,\n                \"has_paths\": \"paths\" in spec_resp.text,\n            }\n        except Exception as e:\n            checks[\"openapi\"] = {\"deployed\": False, \"error\": str(e)}\n    else:\n        checks[\"openapi\"] = {\"deployed\": False, \"note\": \"No api.url in manifest\"}\n\n    return checks\n\n\n# verify = verify_storefront_layers(\"https:\u002F\u002Fparts.example.com\")\n# print(json.dumps(verify, indent=2))\n```\n\n### Days 6-8: Connect Payment Rails\n\n**Objective**: Implement multi-protocol checkout.\n\n**Day 6 Tasks**:\n\n- [ ] Implement GreenHelix escrow checkout (`create_escrow` \u002F `release_escrow`)\n- [ ] Test escrow flow end-to-end: create, verify lock, release, verify balance\n- [ ] Deploy `\u002Fcheckout\u002Finitiate` endpoint with `greenhelix_escrow` support\n\n**Day 7 Tasks**:\n\n- [ ] Add x402 checkout flow for micropayments \u002F digital product delivery\n- [ ] Add UCP checkout flow for structured catalog purchases\n- [ ] Test both flows with the agent simulator\n\n**Day 8 Tasks**:\n\n- [ ] Add ACP checkout flow if you have a Stripe merchant account\n- [ ] Implement the `MultiProtocolCheckout` router from Chapter 3\n- [ ] Run ARI checkout tests -- target all advertised protocols working\n- [ ] Set up subscription billing for recurring access with `create_subscription`\n\n```python\n# Day 6-8: End-to-end checkout verification\ndef verify_checkout_flows(base_url: str) -> dict:\n    \"\"\"Verify all checkout protocols are functional.\"\"\"\n    protocols = [\"greenhelix_escrow\", \"x402\", \"ucp\", \"acp\"]\n    results = {}\n\n    for protocol in protocols:\n        try:\n            resp = requests.post(\n                f\"{base_url}\u002Fcheckout\u002Finitiate\",\n                json={\n                    \"items\": [{\"sku\": \"TEST-VERIFY\", \"quantity\": 1}],\n                    \"payment_protocol\": protocol,\n                    \"buyer_agent_id\": \"checkout-verifier\",\n                },\n                timeout=10,\n            )\n            results[protocol] = {\n                \"status_code\": resp.status_code,\n                \"working\": resp.status_code in (200, 201, 402),\n                \"response\": resp.json() if resp.status_code \u003C 500 else None,\n            }\n        except Exception as e:\n            results[protocol] = {\"working\": False, \"error\": str(e)}\n\n    return results\n```\n\n### Days 9-10: Register on Marketplaces\n\n**Objective**: Make your storefront discoverable through the GreenHelix marketplace.\n\n**Day 9 Tasks**:\n\n- [ ] Register agent identity with `register_agent`\n- [ ] Create and fund wallet with `create_wallet` and `deposit`\n- [ ] Register service with optimized description using `register_service` (Chapter 5)\n- [ ] Verify service appears in `search_services` results for your target queries\n\n**Day 10 Tasks**:\n\n- [ ] Submit initial performance metrics with `submit_metrics`\n- [ ] Build claim chain with certifications and evidence using `build_claim_chain`\n- [ ] Check trust score with `get_trust_score` -- establish baseline\n- [ ] Run ARI marketplace tests -- target top 3 position for primary queries\n- [ ] Verify `best_match` returns your service for at least one target query\n\n```python\n# Day 9-10: Marketplace registration and verification\ndef verify_marketplace_presence(service_query: str) -> dict:\n    \"\"\"Verify marketplace presence and ranking.\"\"\"\n    results = {}\n\n    # Check search visibility\n    search = ghx(\"search_services\", {\"query\": service_query})\n    services = search.get(\"services\", [])\n    results[\"search_results_count\"] = len(services)\n    results[\"appears_in_search\"] = len(services) > 0\n\n    # Check best_match\n    match = ghx(\"best_match\", {\"query\": service_query})\n    results[\"best_match\"] = match\n\n    # Check trust score\n    trust = ghx(\"get_trust_score\", {\n        \"agent_id\": \"precision-parts-agent\",\n    })\n    results[\"trust_score\"] = trust\n\n    return results\n```\n\n### Days 11-14: Monitoring and Iteration\n\n**Objective**: Set up continuous monitoring, fix remaining gaps, and iterate toward ARI 95+.\n\n**Day 11 Tasks**:\n\n- [ ] Run full ARI assessment with the agent simulator from Chapter 7\n- [ ] Document current score and grade\n- [ ] Prioritize failed tests by impact (weight x gap from target)\n\n**Day 12 Tasks**:\n\n- [ ] Fix the top 3 highest-impact failures identified on Day 11\n- [ ] Re-run ARI assessment after each fix to verify improvement\n- [ ] Set up scheduled ARI monitoring (daily cron job or CI pipeline)\n\n**Day 13 Tasks**:\n\n- [ ] Implement inventory webhooks with `publish_event` (Chapter 4)\n- [ ] Set up price change notifications\n- [ ] Test webhook delivery to a subscriber agent\n- [ ] Optimize endpoint latency -- add caching for frequently-queried SKUs\n\n**Day 14 Tasks**:\n\n- [ ] Final ARI assessment -- target 85+ overall, with a path to 95+\n- [ ] Publish ARI metrics to GreenHelix via `submit_metrics`\n- [ ] Document remaining gaps and create a backlog for continued optimization\n- [ ] Set up alerting: notify team if ARI drops below 80\n\n```python\n# Day 14: Final assessment and metric publication\ndef final_aco_assessment(\n    api_key: str,\n    storefront_url: str,\n    service_query: str,\n    agent_id: str,\n) -> dict:\n    \"\"\"Run the final ACO sprint assessment.\"\"\"\n    # Run full ARI\n    sim = AgentSimulator(\n        api_key=api_key,\n        storefront_url=storefront_url,\n        service_query=service_query,\n    )\n    report = sim.run_all()\n\n    # Publish to GreenHelix\n    ghx(\"submit_metrics\", {\n        \"agent_id\": agent_id,\n        \"metrics\": {\n            \"ari_score\": report.overall_score,\n            \"ari_grade\": report.grade,\n            \"aco_sprint_completed\": True,\n            \"aco_completion_date\": time.strftime(\"%Y-%m-%d\"),\n        },\n    })\n\n    # Summary\n    summary = {\n        \"ari_score\": report.overall_score,\n        \"grade\": report.grade,\n        \"tests_passed\": sum(1 for r in report.results if r.passed),\n        \"tests_total\": len(report.results),\n        \"recommendations\": report.recommendations,\n        \"sprint_status\": \"complete\" if report.overall_score >= 85 else \"needs_iteration\",\n    }\n\n    return summary\n\n\n# final = final_aco_assessment(\n#     api_key=os.environ[\"GREENHELIX_API_KEY\"],\n#     storefront_url=\"https:\u002F\u002Fparts.example.com\",\n#     service_query=\"precision bearings ISO certified\",\n#     agent_id=\"precision-parts-agent\",\n# )\n# print(json.dumps(final, indent=2))\n```\n\n### Printable ACO Sprint Checklist\n\n```\nACO SPRINT CHECKLIST\n====================\n\nPHASE 1: AUDIT (Days 1-2)\n[ ] Export full product catalog\n[ ] Run completeness scoring on all products\n[ ] Generate gap report\n[ ] Identify top 10 missing attributes\n[ ] Fix top-revenue products to 98%+ completeness\n[ ] Set up automated scoring in CI\u002FCD\n\nPHASE 2: MANIFESTS & SCHEMAS (Days 3-5)\n[ ] Deploy .well-known\u002Fai-plugin.json\n[ ] Write optimized description_for_model\n[ ] Implement JSON-LD product schemas\n[ ] Embed schemas in pages and API responses\n[ ] Publish OpenAPI spec\n[ ] Validate all three layers\n\nPHASE 3: PAYMENT RAILS (Days 6-8)\n[ ] Implement GreenHelix escrow checkout\n[ ] Test escrow end-to-end\n[ ] Add x402 micropayment flow\n[ ] Add UCP checkout flow\n[ ] Add ACP checkout flow (if Stripe merchant)\n[ ] Deploy MultiProtocolCheckout router\n[ ] Set up subscription billing\n\nPHASE 4: MARKETPLACE (Days 9-10)\n[ ] Register agent identity\n[ ] Create and fund wallet\n[ ] Register service with optimized description\n[ ] Verify search_services visibility\n[ ] Submit performance metrics\n[ ] Build claim chain with evidence\n[ ] Check trust score baseline\n[ ] Verify best_match ranking\n\nPHASE 5: MONITORING (Days 11-14)\n[ ] Run full ARI assessment\n[ ] Fix top 3 highest-impact failures\n[ ] Set up daily ARI monitoring\n[ ] Implement inventory webhooks\n[ ] Set up price change notifications\n[ ] Optimize endpoint latency (\u003C 200ms p95)\n[ ] Final ARI assessment (target: 85+)\n[ ] Publish ARI metrics to GreenHelix\n[ ] Document remaining gaps\n[ ] Set up regression alerting (ARI \u003C 80)\n\nSCORE: ___\u002F100  GRADE: ___\n```\n\n> **Key Takeaways**\n>\n> - The 14-day ACO sprint follows five phases: audit (days 1-2), manifests and schemas (days 3-5), payment rails (days 6-8), marketplace registration (days 9-10), and monitoring and iteration (days 11-14).\n> - Target ARI 85+ by day 14. Most storefronts can reach this with focused execution on data completeness and marketplace optimization.\n> - Continuous ARI monitoring catches regressions before they cost revenue. Run the agent simulator on every deployment.\n> - The sprint is not a one-time event. Agent commerce standards evolve monthly. Schedule quarterly ACO refreshes to maintain competitiveness.\n> - Cross-reference P4 (Commerce Toolkit) for escrow patterns, P13 (Interoperability Bridge) for protocol bridging, P18 (Pricing & Monetization) for pricing optimization, and P19 (Payment Rails Playbook) for deep protocol implementation.\n\n---\n\n## Appendix: Tool Reference\n\nThe following GreenHelix A2A Commerce Gateway tools are used throughout this guide. All tools are called via `POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1` with Bearer token authentication.\n\n| Tool | Chapter(s) | Purpose |\n|---|---|---|\n| `register_agent` | 5, 6 | Register agent identity with Ed25519 public key |\n| `create_wallet` | 5, 6 | Create a wallet for an agent |\n| `deposit` | 5, 6 | Fund an agent wallet |\n| `get_balance` | 6 | Check wallet balance |\n| `register_service` | 2, 4, 5 | List a service on the marketplace |\n| `search_services` | 5, 7 | Search marketplace for services |\n| `best_match` | 5, 7 | Get highest-ranked service for a query |\n| `submit_metrics` | 5, 7, 8 | Report verified performance metrics |\n| `build_claim_chain` | 5, 8 | Create cryptographic evidence chain |\n| `get_trust_score` | 5, 8 | Check trust score for an agent |\n| `get_agent_reputation` | 5 | Get reputation details |\n| `create_escrow` | 2, 3, 6 | Lock funds until work is verified |\n| `release_escrow` | 6 | Release escrowed funds to seller |\n| `cancel_escrow` | 6 | Cancel escrow and return funds to buyer |\n| `create_performance_escrow` | 6 | Escrow with metric-based auto-release |\n| `check_performance_escrow` | 6 | Check if performance criteria are met |\n| `create_subscription` | 6 | Set up recurring payment |\n| `cancel_subscription` | 6 | Cancel a subscription |\n| `create_payment_intent` | 3 | Record payment intent for tracking |\n| `create_dispute` | 6 | Open a dispute on an escrow |\n| `resolve_dispute` | 6 | Resolve a dispute with evidence |\n| `publish_event` | 4 | Push inventory\u002Fprice events to subscribers |\n| `rate_service` | 5 | Rate a marketplace service (1-5) |\n\n---\n\n*This guide is part of the GreenHelix A2A Commerce product library. For related guides, see P4 (Commerce Toolkit), P13 (Interoperability Bridge), P18 (Pricing & Monetization), and P19 (Payment Rails Playbook).*\n\n","# Agent-Ready Commerce: Retrofit Your APIs for AI Buyers\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> - `WALLET_ADDRESS`: Blockchain wallet address for receiving payments (public address only — no private keys)\n> - `AGENT_SIGNING_KEY`: Cryptographic signing key for agent identity (Ed25519 key pair for request signing)\n> - `STRIPE_API_KEY`: Stripe API key for card payment processing (scoped to payment intents only)\n\n\nAI shopping agents now influence over $67 billion in purchasing decisions. Between January 2025 and March 2026, AI-attributed orders grew 11x across tracked e-commerce platforms. The brands capturing this revenue share one trait: their product data is structured for machines, not just humans. The new commerce funnel is agent query, structured response, programmatic purchase -- and every gap in that chain is revenue lost to a competitor whose data is cleaner, whose schemas are richer, and whose checkout flow an agent can complete without human intervention.\nThis guide is the practitioner's manual for building agent-ready commerce infrastructure. Every chapter contains production Python code against the GreenHelix A2A Commerce Gateway -- 128 tools accessible at `https:\u002F\u002Fapi.greenhelix.net\u002Fv1` via a single the REST API (`POST \u002Fv1\u002F{tool}`) endpoint. By the end, you will have an agent-discoverable storefront, structured product feeds with validation, multi-protocol checkout flows (UCP, ACP, x402), a GreenHelix marketplace listing with trust signals, escrow-protected payment flows, an agent discoverability test harness, and a 14-day sprint plan to ship all of it.\n1. [The Agentic Commerce Shift](#chapter-1-the-agentic-commerce-shift)\n\n## What You'll Learn\n- Chapter 1: The Agentic Commerce Shift\n- Chapter 2: Anatomy of an Agent-Ready Storefront\n- Chapter 3: UCP, ACP, and x402: Choosing Your Payment Rails\n- Chapter 4: Structured Product Feeds That Win\n- Chapter 5: Agent Discovery via GreenHelix Marketplace\n- Chapter 6: Agent-to-Agent Payment Flows\n- Chapter 7: Testing Agent Discoverability\n- Chapter 8: The 14-Day ACO Sprint\n- Appendix: Tool Reference\n\n## Full Guide\n\n# Agent-Ready Commerce: Retrofit Your APIs for AI Buyers\n\nAI shopping agents now influence over $67 billion in purchasing decisions. Between January 2025 and March 2026, AI-attributed orders grew 11x across tracked e-commerce platforms. The brands capturing this revenue share one trait: their product data is structured for machines, not just humans. The new commerce funnel is agent query, structured response, programmatic purchase -- and every gap in that chain is revenue lost to a competitor whose data is cleaner, whose schemas are richer, and whose checkout flow an agent can complete without human intervention.\n\nThis guide is the practitioner's manual for building agent-ready commerce infrastructure. Every chapter contains production Python code against the GreenHelix A2A Commerce Gateway -- 128 tools accessible at `https:\u002F\u002Fapi.greenhelix.net\u002Fv1` via a single the REST API (`POST \u002Fv1\u002F{tool}`) endpoint. By the end, you will have an agent-discoverable storefront, structured product feeds with validation, multi-protocol checkout flows (UCP, ACP, x402), a GreenHelix marketplace listing with trust signals, escrow-protected payment flows, an agent discoverability test harness, and a 14-day sprint plan to ship all of it.\n\n---\n\n## Table of Contents\n\n1. [The Agentic Commerce Shift](#chapter-1-the-agentic-commerce-shift)\n2. [Anatomy of an Agent-Ready Storefront](#chapter-2-anatomy-of-an-agent-ready-storefront)\n3. [UCP, ACP, and x402: Choosing Your Payment Rails](#chapter-3-ucp-acp-and-x402-choosing-your-payment-rails)\n4. [Structured Product Feeds That Win](#chapter-4-structured-product-feeds-that-win)\n5. [Agent Discovery via GreenHelix Marketplace](#chapter-5-agent-discovery-via-greenhelix-marketplace)\n6. [Agent-to-Agent Payment Flows](#chapter-6-agent-to-agent-payment-flows)\n7. [Testing Agent Discoverability](#chapter-7-testing-agent-discoverability)\n8. [The 14-Day ACO Sprint](#chapter-8-the-14-day-aco-sprint)\n\n---\n\n## Chapter 1: The Agentic Commerce Shift\n\n### The Numbers That Changed Everything\n\nDuring Cyber Week 2025, AI-powered shopping agents influenced $67 billion in U.S. online spending. Salesforce tracked the transactions: AI-attributed product recommendations drove 17% of all orders, up from 5% the previous year. Adobe Analytics reported that AI-powered chatbots on retail sites handled 1.3 billion sessions during the five-day window. But the more important metric came from Shopify's internal analysis: merchants whose product data scored above 95% attribute completeness saw 3-4x the AI-referred traffic of merchants below 80%. The agents were not choosing randomly. They were choosing the products they could understand.\n\nBy March 2026, the growth curve had steepened. AI-attributed orders across the 50 largest U.S. e-commerce platforms grew 11x compared to January 2025 -- from 0.3% of total orders to 3.3%. That percentage sounds small until you calculate the absolute numbers: 3.3% of the $1.1 trillion U.S. e-commerce market is $36.3 billion in transactions where an AI agent materially influenced the purchase decision. The trajectory puts AI-attributed commerce above $100 billion by mid-2027.\n\n### The New Funnel\n\nTraditional e-commerce optimizes for human eyeballs: product images, emotional copy, social proof badges, countdown timers. The conversion funnel is awareness, consideration, decision, purchase -- each stage designed for a human scrolling on a phone.\n\nAgent commerce replaces every stage:\n\n| Traditional Stage | Agent Commerce Equivalent | What the Agent Needs |\n|---|---|---|\n| **Awareness** | Agent discovers your product via structured query | JSON-LD schema, OpenAPI spec, marketplace listing |\n| **Consideration** | Agent compares attributes programmatically | Complete attribute data, machine-readable pricing, real-time inventory |\n| **Decision** | Agent selects based on ranking algorithm | Trust signals, verified metrics, claim chains |\n| **Purchase** | Agent completes checkout via API | Programmatic payment rails (UCP\u002FACP\u002Fx402), escrow support |\n\nNotice what is missing: images, emotional copy, brand storytelling. Agents do not read your About page. They parse your product schema. If your schema is incomplete, you are invisible to the fastest-growing channel in commerce.\n\n### Why \"Agent-Readable\" Means Revenue\n\nThe data is unambiguous. Salsify's 2026 Product Experience Benchmark studied 14,000 product listings across Amazon, Walmart, and Target. Products with 99.9% attribute completeness -- every field filled, every variant specified, every specification machine-parseable -- achieved 3-4x the visibility in AI-powered search compared to products at 90% completeness. The relationship was not linear. It was a step function: below 95%, visibility dropped off a cliff. Above 99%, it climbed exponentially.\n\nThe reason is structural. AI agents use retrieval-augmented generation (RAG) to match user queries to product data. The retrieval step depends on embedding similarity between the query and the product description. A product listing that says \"Blue Widget, $29.99\" generates a weak embedding. A listing with structured JSON-LD including `color: \"Navy Blue (Pantone 19-4052)\"`, `material: \"6061-T6 Anodized Aluminum\"`, `dimensions: {\"length\": 12.5, \"width\": 3.2, \"height\": 1.8, \"unit\": \"cm\"}`, `certifications: [\"ISO 9001:2015\", \"RoHS\"]` generates an embedding that matches far more queries -- including queries the merchant never anticipated.\n\nThis is the core thesis of this guide: **structured product data is not a technical nice-to-have. It is revenue infrastructure.**\n\n### The GreenHelix Commerce Stack\n\nThe GreenHelix A2A Commerce Gateway provides the infrastructure for agent-ready commerce across the full lifecycle: discovery (marketplace listing, search, ranking), payment (escrow, subscriptions, deposits), trust (metrics, claim chains, reputation scoring), and interoperability (protocol bridges for UCP, ACP, x402).\n\nEvery code example in this guide calls the gateway via the REST API (`POST \u002Fv1\u002F{tool}`):\n\n```python\nimport requests\nfrom typing import Any\n\nGATEWAY_URL = os.environ.get(\"GREENHELIX_API_URL\", \"https:\u002F\u002Fsandbox.greenhelix.net\")\n\nclass CommerceClient:\n    \"\"\"Client for GreenHelix A2A Commerce Gateway.\"\"\"\n\n    def __init__(self, api_key: str):\n        self.api_key = api_key\n        self.headers = {\n            \"Authorization\": f\"Bearer {api_key}\",\n            \"Content-Type\": \"application\u002Fjson\",\n        }\n\n    def execute(self, tool: str, input_data: dict[str, Any]) -> dict:\n        \"\"\"Execute a single tool on the gateway.\"\"\"\n        response = requests.post(\n            f\"{GATEWAY_URL}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n            headers=self.headers,\n            timeout=30,\n        )\n        response.raise_for_status()\n        return response.json()\n\n# Initialize once, use throughout\nclient = CommerceClient(api_key=\"your-api-key-here\")\n```\n\nThis client object is referenced in every subsequent chapter. Store your API key in an environment variable (`GREENHELIX_API_KEY`), never in source code.\n\n> **Key Takeaways**\n>\n> - AI shopping agents influenced $67B+ during Cyber Week 2025. AI-attributed orders grew 11x between January 2025 and March 2026.\n> - Products with 99.9% attribute completeness achieve 3-4x visibility in agent-powered search. Below 95% completeness, visibility collapses.\n> - The agent commerce funnel is: structured query, programmatic comparison, API-driven purchase. Every stage requires machine-readable data.\n> - GreenHelix provides the full commerce stack: discovery, payments, trust, and protocol interoperability through 128 tools at a single endpoint.\n\n---\n\n## Chapter 2: Anatomy of an Agent-Ready Storefront\n\n### The Three Layers of Agent Discoverability\n\nAn agent-ready storefront exposes three machine-readable layers that allow AI agents to discover, evaluate, and purchase your products without human intervention:\n\n1. **Manifest layer** -- `.well-known\u002Fai-plugin.json` tells agents your storefront exists and where to find its API.\n2. **Schema layer** -- JSON-LD product schemas embedded in pages (or served via API) describe every product attribute in a format agents can parse.\n3. **API layer** -- An OpenAPI specification defines endpoints agents call to search products, check inventory, and initiate checkout.\n\nMiss any layer and you break the chain. An agent that discovers your manifest but finds no OpenAPI spec cannot call your API. An agent that finds your API but no product schemas cannot compare your products to competitors.\n\n### Layer 1: The AI Plugin Manifest\n\nThe `.well-known\u002Fai-plugin.json` manifest is the entry point. Agents crawling for commerce endpoints check this path first -- it is the equivalent of `robots.txt` for AI commerce agents. The specification originated with OpenAI's ChatGPT plugin system and has been adopted as a de facto standard across Gemini, Perplexity, and Claude shopping agents.\n\n```json\n{\n  \"schema_version\": \"v1\",\n  \"name_for_human\": \"Precision Parts Direct\",\n  \"name_for_model\": \"precision_parts\",\n  \"description_for_human\": \"Industrial precision components with same-day shipping.\",\n  \"description_for_model\": \"Structured product catalog of 12,000+ precision-machined components. Supports real-time inventory queries, attribute-based filtering (material, tolerance, certification), bulk pricing, and programmatic checkout via UCP, ACP, or x402. All products have 99.9%+ attribute completeness with JSON-LD schemas.\",\n  \"auth\": {\n    \"type\": \"service_http\",\n    \"authorization_type\": \"bearer\",\n    \"verification_tokens\": {\n      \"greenhelix\": \"ghx_verify_abc123\"\n    }\n  },\n  \"api\": {\n    \"type\": \"openapi\",\n    \"url\": \"https:\u002F\u002Fparts.example.com\u002F.well-known\u002Fopenapi.yaml\",\n    \"is_user_authenticated\": false\n  },\n  \"logo_url\": \"https:\u002F\u002Fparts.example.com\u002Flogo.png\",\n  \"contact_email\": \"api@parts.example.com\",\n  \"legal_info_url\": \"https:\u002F\u002Fparts.example.com\u002Flegal\"\n}\n```\n\nThree fields matter most for agent discoverability:\n\n- **`description_for_model`** -- This is what the agent reads. Pack it with structured keywords: product count, attribute types, supported payment protocols, completeness score. Agents use this for semantic matching against user queries.\n- **`api.url`** -- Must point to a valid OpenAPI spec. Agents parse this to learn your endpoint signatures, request\u002Fresponse schemas, and authentication requirements.\n- **`auth.verification_tokens.greenhelix`** -- If you register on the GreenHelix marketplace, include this token so the gateway can verify your listing is legitimate.\n\n### Layer 2: JSON-LD Product Schemas\n\nJSON-LD (JavaScript Object Notation for Linked Data) is the structured data format that Google, Bing, and now AI agents use to understand product attributes. Embed it in your HTML pages via `\u003Cscript type=\"application\u002Fld+json\">` tags, or serve it directly via API for agent-only consumption.\n\n```python\ndef build_product_schema(product: dict) -> dict:\n    \"\"\"Build a JSON-LD Product schema from internal product data.\"\"\"\n    schema = {\n        \"@context\": \"https:\u002F\u002Fschema.org\",\n        \"@type\": \"Product\",\n        \"name\": product[\"name\"],\n        \"description\": product[\"description\"],\n        \"sku\": product[\"sku\"],\n        \"mpn\": product.get(\"mpn\", \"\"),\n        \"brand\": {\n            \"@type\": \"Brand\",\n            \"name\": product[\"brand\"],\n        },\n        \"offers\": {\n            \"@type\": \"Offer\",\n            \"url\": product[\"url\"],\n            \"priceCurrency\": \"USD\",\n            \"price\": str(product[\"price\"]),\n            \"availability\": (\n                \"https:\u002F\u002Fschema.org\u002FInStock\"\n                if product[\"inventory\"] > 0\n                else \"https:\u002F\u002Fschema.org\u002FOutOfStock\"\n            ),\n            \"itemCondition\": \"https:\u002F\u002Fschema.org\u002FNewCondition\",\n            \"priceValidUntil\": product.get(\"price_valid_until\", \"2026-12-31\"),\n            \"seller\": {\n                \"@type\": \"Organization\",\n                \"name\": product[\"seller_name\"],\n            },\n        },\n        \"additionalProperty\": [\n            {\n                \"@type\": \"PropertyValue\",\n                \"name\": key,\n                \"value\": value,\n            }\n            for key, value in product.get(\"attributes\", {}).items()\n        ],\n    }\n\n    # Add aggregate rating if available\n    if product.get(\"rating_count\", 0) > 0:\n        schema[\"aggregateRating\"] = {\n            \"@type\": \"AggregateRating\",\n            \"ratingValue\": str(product[\"rating_value\"]),\n            \"reviewCount\": str(product[\"rating_count\"]),\n        }\n\n    return schema\n\n\n# Example usage\nproduct_data = {\n    \"name\": \"Precision Ball Bearing - 608-2RS\",\n    \"description\": \"Sealed radial ball bearing, 8mm bore, ABEC-7 precision grade\",\n    \"sku\": \"PBB-608-2RS-ABEC7\",\n    \"mpn\": \"608-2RS-P7\",\n    \"brand\": \"RotorTech\",\n    \"url\": \"https:\u002F\u002Fparts.example.com\u002Fproducts\u002Fpbb-608-2rs-abec7\",\n    \"price\": 4.75,\n    \"inventory\": 24500,\n    \"seller_name\": \"Precision Parts Direct\",\n    \"price_valid_until\": \"2026-06-30\",\n    \"rating_value\": 4.8,\n    \"rating_count\": 1247,\n    \"attributes\": {\n        \"bore_diameter_mm\": \"8\",\n        \"outer_diameter_mm\": \"22\",\n        \"width_mm\": \"7\",\n        \"material\": \"Chrome Steel (AISI 52100)\",\n        \"seal_type\": \"Double Rubber Seal (2RS)\",\n        \"abec_grade\": \"ABEC-7\",\n        \"max_rpm\": \"42000\",\n        \"dynamic_load_rating_kn\": \"3.45\",\n        \"static_load_rating_kn\": \"1.37\",\n        \"weight_grams\": \"12\",\n        \"operating_temp_range\": \"-30C to +120C\",\n        \"certifications\": \"ISO 9001:2015, ISO 14001:2015\",\n    },\n}\n\nschema = build_product_schema(product_data)\n```\n\nThat product has 15 structured attributes. An agent searching for \"ABEC-7 bearing under $5 with double seal rated above 40000 RPM\" will match every field. A competing listing that only specifies \"ball bearing, $4.75\" will not match the query -- even if the physical product is identical.\n\n### Layer 3: OpenAPI Specification\n\nThe OpenAPI spec defines the programmatic interface agents use to search, filter, and purchase. Here is a minimal spec for a product catalog API:\n\n```yaml\nopenapi: 3.1.0\ninfo:\n  title: Precision Parts API\n  version: 1.0.0\n  description: Agent-ready product catalog with structured search and checkout\npaths:\n  \u002Fproducts\u002Fsearch:\n    post:\n      operationId: searchProducts\n      summary: Search products by structured attributes\n      requestBody:\n        content:\n          application\u002Fjson:\n            schema:\n              type: object\n              properties:\n                query:\n                  type: string\n                filters:\n                  type: object\n                  properties:\n                    material:\n                      type: string\n                    min_price:\n                      type: number\n                    max_price:\n                      type: number\n                    in_stock:\n                      type: boolean\n                    certifications:\n                      type: array\n                      items:\n                        type: string\n                sort_by:\n                  type: string\n                  enum: [price_asc, price_desc, rating, relevance]\n                limit:\n                  type: integer\n                  default: 20\n      responses:\n        '200':\n          description: Matching products with full schemas\n  \u002Fproducts\u002F{sku}\u002Finventory:\n    get:\n      operationId: getInventory\n      summary: Real-time inventory for a specific SKU\n      parameters:\n        - name: sku\n          in: path\n          required: true\n          schema:\n            type: string\n      responses:\n        '200':\n          description: Current inventory count and restock ETA\n  \u002Fcheckout\u002Finitiate:\n    post:\n      operationId: initiateCheckout\n      summary: Start a programmatic checkout flow\n      requestBody:\n        content:\n          application\u002Fjson:\n            schema:\n              type: object\n              required: [items, payment_protocol]\n              properties:\n                items:\n                  type: array\n                  items:\n                    type: object\n                    properties:\n                      sku:\n                        type: string\n                      quantity:\n                        type: integer\n                payment_protocol:\n                  type: string\n                  enum: [ucp, acp, x402, greenhelix_escrow]\n                buyer_agent_id:\n                  type: string\n      responses:\n        '200':\n          description: Checkout session with payment instructions\n```\n\n### Building It in 30 Minutes: FastAPI Implementation\n\nHere is a complete agent-ready storefront API using FastAPI. It serves the manifest, product schemas, and checkout endpoint -- and registers itself on the GreenHelix marketplace for discoverability.\n\n```python\nfrom fastapi import FastAPI, HTTPException\nfrom fastapi.responses import JSONResponse\nfrom pydantic import BaseModel\nimport os\n\napp = FastAPI(title=\"Precision Parts API\", version=\"1.0.0\")\n\n# GreenHelix client (from Chapter 1)\nclient = CommerceClient(api_key=os.environ[\"GREENHELIX_API_KEY\"])\n\n# In-memory product catalog (replace with database in production)\nCATALOG = {\n    \"PBB-608-2RS-ABEC7\": {\n        \"name\": \"Precision Ball Bearing - 608-2RS\",\n        \"sku\": \"PBB-608-2RS-ABEC7\",\n        \"price\": 4.75,\n        \"inventory\": 24500,\n        \"brand\": \"RotorTech\",\n        \"description\": \"Sealed radial ball bearing, 8mm bore, ABEC-7 precision\",\n        \"seller_name\": \"Precision Parts Direct\",\n        \"url\": \"https:\u002F\u002Fparts.example.com\u002Fproducts\u002Fpbb-608-2rs-abec7\",\n        \"attributes\": {\n            \"bore_diameter_mm\": \"8\",\n            \"outer_diameter_mm\": \"22\",\n            \"material\": \"Chrome Steel (AISI 52100)\",\n            \"seal_type\": \"Double Rubber Seal (2RS)\",\n            \"abec_grade\": \"ABEC-7\",\n            \"max_rpm\": \"42000\",\n            \"certifications\": \"ISO 9001:2015\",\n        },\n        \"rating_value\": 4.8,\n        \"rating_count\": 1247,\n    },\n}\n\n\n@app.get(\"\u002F.well-known\u002Fai-plugin.json\")\ndef ai_plugin_manifest():\n    \"\"\"Serve the AI plugin manifest for agent discovery.\"\"\"\n    return {\n        \"schema_version\": \"v1\",\n        \"name_for_human\": \"Precision Parts Direct\",\n        \"name_for_model\": \"precision_parts\",\n        \"description_for_model\": (\n            \"Structured catalog of 12,000+ precision components. \"\n            \"Supports attribute search, real-time inventory, bulk pricing, \"\n            \"and checkout via UCP, ACP, x402, or GreenHelix escrow. \"\n            \"99.9% attribute completeness.\"\n        ),\n        \"api\": {\n            \"type\": \"openapi\",\n            \"url\": \"https:\u002F\u002Fparts.example.com\u002Fopenapi.json\",\n        },\n    }\n\n\nclass SearchRequest(BaseModel):\n    query: str = \"\"\n    filters: dict = {}\n    sort_by: str = \"relevance\"\n    limit: int = 20\n\n\n@app.post(\"\u002Fproducts\u002Fsearch\")\ndef search_products(req: SearchRequest):\n    \"\"\"Search products with structured filters.\"\"\"\n    results = []\n    for sku, product in CATALOG.items():\n        # Apply filters\n        if req.filters.get(\"max_price\") and product[\"price\"] > req.filters[\"max_price\"]:\n            continue\n        if req.filters.get(\"material\"):\n            if req.filters[\"material\"].lower() not in product[\"attributes\"].get(\"material\", \"\").lower():\n                continue\n        results.append(build_product_schema(product))\n\n    return {\"results\": results[:req.limit], \"total\": len(results)}\n\n\n@app.get(\"\u002Fproducts\u002F{sku}\u002Finventory\")\ndef get_inventory(sku: str):\n    \"\"\"Real-time inventory check.\"\"\"\n    product = CATALOG.get(sku)\n    if not product:\n        raise HTTPException(status_code=404, detail=\"SKU not found\")\n    return {\n        \"sku\": sku,\n        \"available\": product[\"inventory\"],\n        \"in_stock\": product[\"inventory\"] > 0,\n    }\n\n\nclass CheckoutRequest(BaseModel):\n    items: list[dict]\n    payment_protocol: str  # ucp, acp, x402, greenhelix_escrow\n    buyer_agent_id: str = \"\"\n\n\n@app.post(\"\u002Fcheckout\u002Finitiate\")\ndef initiate_checkout(req: CheckoutRequest):\n    \"\"\"Start a programmatic checkout flow.\"\"\"\n    # Calculate total\n    total = 0.0\n    for item in req.items:\n        product = CATALOG.get(item[\"sku\"])\n        if not product:\n            raise HTTPException(status_code=404, detail=f\"SKU {item['sku']} not found\")\n        total += product[\"price\"] * item.get(\"quantity\", 1)\n\n    if req.payment_protocol == \"greenhelix_escrow\":\n        # Create escrow via GreenHelix\n        escrow = client.execute(\"create_escrow\", {\n            \"payer_agent_id\": req.buyer_agent_id,\n            \"payee_agent_id\": \"precision-parts-agent\",\n            \"amount\": str(total),\n            \"description\": f\"Order: {len(req.items)} items\",\n        })\n        return {\n            \"checkout_id\": escrow.get(\"escrow_id\"),\n            \"total\": str(total),\n            \"protocol\": \"greenhelix_escrow\",\n            \"status\": \"escrow_created\",\n            \"instructions\": \"Funds are locked. Seller will ship and release on delivery.\",\n        }\n\n    # Return protocol-specific payment instructions for UCP\u002FACP\u002Fx402\n    return {\n        \"total\": str(total),\n        \"protocol\": req.payment_protocol,\n        \"status\": \"payment_required\",\n        \"payment_url\": f\"https:\u002F\u002Fparts.example.com\u002Fpay\u002F{req.payment_protocol}\",\n    }\n\n\n# Register on GreenHelix marketplace at startup\n@app.on_event(\"startup\")\nasync def register_on_marketplace():\n    \"\"\"Register this storefront on GreenHelix for agent discovery.\"\"\"\n    try:\n        client.execute(\"register_service\", {\n            \"name\": \"Precision Parts Direct\",\n            \"description\": (\n                \"Industrial precision components: bearings, shafts, seals, \"\n                \"fasteners. 12,000+ SKUs. 99.9% attribute completeness. \"\n                \"Same-day shipping. Supports escrow checkout.\"\n            ),\n            \"endpoint\": \"https:\u002F\u002Fparts.example.com\",\n            \"price\": 0.0,\n            \"tags\": [\"precision-parts\", \"bearings\", \"industrial\", \"b2b\"],\n            \"category\": \"industrial_components\",\n        })\n    except Exception as e:\n        print(f\"Marketplace registration failed: {e}\")\n```\n\nThis gives you a fully agent-discoverable storefront in under 200 lines. An AI agent can find it via the `.well-known` manifest, parse the OpenAPI spec, search products by structured attributes, check inventory, and initiate checkout through four different payment protocols.\n\n> **Key Takeaways**\n>\n> - Agent-ready storefronts have three layers: manifest (`.well-known\u002Fai-plugin.json`), schema (JSON-LD product data), and API (OpenAPI spec with search and checkout endpoints).\n> - The `description_for_model` field in your manifest is the single most important field for agent discovery. Pack it with structured keywords and capability descriptions.\n> - JSON-LD product schemas with complete attributes are what allow agents to match your products to queries. Every missing attribute is a missed query match.\n> - A complete FastAPI storefront with marketplace registration can be built in 30 minutes and under 200 lines of Python.\n\n---\n\n## Chapter 3: UCP, ACP, and x402: Choosing Your Payment Rails\n\n### The Three-Protocol Reality\n\nAs of April 2026, three payment protocols dominate agent commerce. Each solves a different problem, targets a different buyer type, and requires a different integration. Most production storefronts will support at least two.\n\n**Universal Commerce Protocol (UCP)** -- Google and Shopify's protocol for structured product discovery and checkout. UCP defines a standardized product catalog format that agents query to find available products, compare prices, and initiate purchases. The checkout flow delegates to the merchant's existing payment infrastructure (typically Stripe or Shopify Payments). UCP is in production on Shopify and Google Shopping. It is the most widely supported protocol for agent-to-merchant commerce.\n\n**Agentic Commerce Protocol (ACP)** -- OpenAI and Stripe's protocol for AI agent checkout. ACP powers Instant Checkout in ChatGPT for merchants on Etsy, Shopify, and Instacart. The flow uses Shared Payment Tokens (SPTs) -- delegated spending authority from a human's Stripe account to an agent. ACP handles product search, cart assembly, and Stripe-based checkout. It requires the merchant to have a Stripe account.\n\n**x402** -- Coinbase and Cloudflare's HTTP-native micropayment protocol, now under the Linux Foundation with Google, Stripe, AWS, and Visa as founding members. The server returns HTTP 402 with a payment requirement. The client pays in USDC via a facilitator. Settlement is on-chain (Base L2, Solana, or Ethereum L2s). Sub-cent transaction fees make it ideal for pay-per-request API access and digital product delivery. See P19 (Payment Rails Playbook) for deep implementation details.\n\n### Protocol Comparison Matrix\n\n| Dimension | UCP | ACP | x402 | GreenHelix |\n|---|---|---|---|---|\n| **Backed by** | Google, Shopify | OpenAI, Stripe | Linux Foundation, Coinbase, Cloudflare | GreenHelix Labs |\n| **Primary use case** | Structured product discovery + checkout | AI agent instant checkout | HTTP micropayments | Full agent commerce stack |\n| **Settlement** | Merchant's processor (Stripe, Shopify Pay) | Stripe | On-chain (USDC on Base\u002FSolana) | Built-in ledger + escrow |\n| **Minimum transaction** | Processor-dependent (~$0.50) | $0.50 (Stripe minimum) | $0.0001 (sub-cent) | $0.01 |\n| **Buyer requirements** | Payment method on file | Stripe SPT (human-authorized) | USDC wallet | GreenHelix wallet (deposit-based) |\n| **Seller requirements** | UCP catalog registration | Stripe merchant account | x402 facilitator integration | GreenHelix service registration |\n| **Escrow support** | No | No (Stripe disputes only) | No | Yes (standard + performance) |\n| **Discovery built-in** | Yes (UCP catalog) | Yes (merchant catalog) | No | Yes (marketplace + best_match) |\n| **Dispute resolution** | Via merchant | Via Stripe | None | Built-in (create_dispute\u002Fresolve_dispute) |\n| **Best for** | Physical goods, retail | Consumer purchases via ChatGPT | API access, digital content | Agent-to-agent services |\n\n### When to Use Each\n\n**Use UCP when** you sell physical products or structured services and want maximum reach across Google Shopping and Shopify-integrated agents. UCP's structured catalog format maps directly to the JSON-LD schemas from Chapter 2. If you already sell on Shopify, UCP integration is near-automatic.\n\n**Use ACP when** ChatGPT users are a significant buyer segment. ACP's Instant Checkout eliminates the redirect-to-website friction that kills conversion. The human authorizes spending via an SPT, and the agent completes the purchase inside the conversation. Conversion rates for ACP-enabled merchants are 2-3x higher than redirect-based checkout.\n\n**Use x402 when** you sell digital products, API access, or content that can be delivered per-request. x402's sub-cent fees make it viable for transactions that would be uneconomical on card rails. A $0.002 data enrichment call that costs $0.30 on Stripe costs $0.00001 on x402.\n\n**Use GreenHelix escrow when** trust is critical -- the buyer needs assurance that funds are locked until delivery is verified, or the seller needs assurance that the buyer cannot cancel after work begins. Escrow is essential for agent-to-agent service transactions where neither party has a pre-existing relationship.\n\n### Code: Multi-Protocol Checkout Handler\n\nThis class handles checkout across all four protocols, with GreenHelix as the escrow layer for any protocol that lacks native buyer protection.\n\n```python\nimport requests\nimport hashlib\nimport time\nfrom dataclasses import dataclass\nfrom typing import Optional\n\nGATEWAY_URL = os.environ.get(\"GREENHELIX_API_URL\", \"https:\u002F\u002Fsandbox.greenhelix.net\")\n\n\n@dataclass\nclass CheckoutResult:\n    protocol: str\n    status: str\n    transaction_id: str\n    amount: str\n    instructions: Optional[dict] = None\n\n\nclass MultiProtocolCheckout:\n    \"\"\"Handle checkout across UCP, ACP, x402, and GreenHelix escrow.\"\"\"\n\n    def __init__(self, api_key: str, seller_agent_id: str):\n        self.api_key = api_key\n        self.seller_agent_id = seller_agent_id\n        self.headers = {\n            \"Authorization\": f\"Bearer {api_key}\",\n            \"Content-Type\": \"application\u002Fjson\",\n        }\n\n    def _ghx(self, tool: str, input_data: dict) -> dict:\n        \"\"\"Execute a GreenHelix tool.\"\"\"\n        resp = requests.post(\n            f\"{GATEWAY_URL}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n            headers=self.headers,\n            timeout=30,\n        )\n        resp.raise_for_status()\n        return resp.json()\n\n    def checkout_ucp(\n        self, buyer_agent_id: str, items: list[dict], total: float\n    ) -> CheckoutResult:\n        \"\"\"UCP checkout: structured catalog query + merchant payment.\n\n        In production, this calls the UCP catalog API to validate\n        availability and then redirects to the merchant's payment page.\n        We wrap it in GreenHelix escrow for buyer protection.\n        \"\"\"\n        # Create escrow to protect the buyer\n        escrow = self._ghx(\"create_escrow\", {\n            \"payer_agent_id\": buyer_agent_id,\n            \"payee_agent_id\": self.seller_agent_id,\n            \"amount\": str(total),\n            \"description\": f\"UCP order: {len(items)} items\",\n        })\n\n        # Record the payment intent for UCP tracking\n        intent = self._ghx(\"create_payment_intent\", {\n            \"payer_agent_id\": buyer_agent_id,\n            \"payee_agent_id\": self.seller_agent_id,\n            \"amount\": str(total),\n            \"currency\": \"USD\",\n            \"description\": \"UCP-routed order with escrow protection\",\n        })\n\n        return CheckoutResult(\n            protocol=\"ucp\",\n            status=\"escrow_created\",\n            transaction_id=escrow.get(\"escrow_id\", \"\"),\n            amount=str(total),\n            instructions={\n                \"escrow_id\": escrow.get(\"escrow_id\"),\n                \"payment_intent_id\": intent.get(\"intent_id\"),\n                \"next_step\": \"Buyer confirms delivery, then escrow releases.\",\n            },\n        )\n\n    def checkout_acp(\n        self, buyer_agent_id: str, items: list[dict], total: float,\n        stripe_spt: str,\n    ) -> CheckoutResult:\n        \"\"\"ACP checkout: Stripe Shared Payment Token flow.\n\n        The buyer agent holds an SPT (delegated by its human principal).\n        We validate the SPT, charge via Stripe, and record on GreenHelix.\n        \"\"\"\n        # Record the payment on GreenHelix for auditing\n        intent = self._ghx(\"create_payment_intent\", {\n            \"payer_agent_id\": buyer_agent_id,\n            \"payee_agent_id\": self.seller_agent_id,\n            \"amount\": str(total),\n            \"currency\": \"USD\",\n            \"description\": f\"ACP checkout via Stripe SPT\",\n        })\n\n        # In production: call Stripe API with the SPT to charge\n        # stripe.PaymentIntent.create(amount=int(total*100), ...)\n\n        return CheckoutResult(\n            protocol=\"acp\",\n            status=\"payment_captured\",\n            transaction_id=intent.get(\"intent_id\", \"\"),\n            amount=str(total),\n            instructions={\n                \"stripe_spt_used\": True,\n                \"intent_id\": intent.get(\"intent_id\"),\n                \"next_step\": \"Payment captured. Fulfillment begins.\",\n            },\n        )\n\n    def checkout_x402(\n        self, buyer_agent_id: str, items: list[dict], total: float,\n    ) -> CheckoutResult:\n        \"\"\"x402 checkout: HTTP 402 micropayment flow.\n\n        Returns 402 payment requirement. Buyer settles in USDC via\n        facilitator, then retries with X-PAYMENT-PROOF header.\n        \"\"\"\n        # Generate a unique payment requirement\n        payment_id = hashlib.sha256(\n            f\"{buyer_agent_id}:{time.time()}\".encode()\n        ).hexdigest()[:16]\n\n        # Record on GreenHelix\n        intent = self._ghx(\"create_payment_intent\", {\n            \"payer_agent_id\": buyer_agent_id,\n            \"payee_agent_id\": self.seller_agent_id,\n            \"amount\": str(total),\n            \"currency\": \"USD\",\n            \"description\": f\"x402 payment requirement {payment_id}\",\n        })\n\n        return CheckoutResult(\n            protocol=\"x402\",\n            status=\"payment_required\",\n            transaction_id=payment_id,\n            amount=str(total),\n            instructions={\n                \"http_status\": 402,\n                \"payment_address\": \"0x742d35Cc6634C0532925a3b844Bc9e7595f2bD18\",\n                \"currency\": \"USDC\",\n                \"network\": \"base\",\n                \"facilitator\": \"https:\u002F\u002Fx402.org\u002Ffacilitator\",\n                \"intent_id\": intent.get(\"intent_id\"),\n                \"next_step\": \"Pay via facilitator, retry with X-PAYMENT-PROOF header.\",\n            },\n        )\n\n    def checkout_escrow(\n        self, buyer_agent_id: str, items: list[dict], total: float,\n    ) -> CheckoutResult:\n        \"\"\"GreenHelix native escrow checkout.\"\"\"\n        escrow = self._ghx(\"create_escrow\", {\n            \"payer_agent_id\": buyer_agent_id,\n            \"payee_agent_id\": self.seller_agent_id,\n            \"amount\": str(total),\n            \"description\": f\"Direct escrow: {len(items)} items, ${total:.2f}\",\n        })\n\n        return CheckoutResult(\n            protocol=\"greenhelix_escrow\",\n            status=\"escrow_created\",\n            transaction_id=escrow.get(\"escrow_id\", \"\"),\n            amount=str(total),\n            instructions={\n                \"escrow_id\": escrow.get(\"escrow_id\"),\n                \"next_step\": \"Seller fulfills order. Buyer releases escrow on delivery.\",\n            },\n        )\n\n    def route_checkout(\n        self, buyer_agent_id: str, items: list[dict], total: float,\n        preferred_protocol: str = \"greenhelix_escrow\",\n        stripe_spt: Optional[str] = None,\n    ) -> CheckoutResult:\n        \"\"\"Route to the appropriate checkout flow based on protocol preference.\"\"\"\n        router = {\n            \"ucp\": lambda: self.checkout_ucp(buyer_agent_id, items, total),\n            \"acp\": lambda: self.checkout_acp(buyer_agent_id, items, total, stripe_spt or \"\"),\n            \"x402\": lambda: self.checkout_x402(buyer_agent_id, items, total),\n            \"greenhelix_escrow\": lambda: self.checkout_escrow(buyer_agent_id, items, total),\n        }\n        handler = router.get(preferred_protocol)\n        if not handler:\n            raise ValueError(f\"Unsupported protocol: {preferred_protocol}\")\n        return handler()\n\n\n# Usage\ncheckout = MultiProtocolCheckout(\n    api_key=\"your-api-key\",\n    seller_agent_id=\"precision-parts-agent\",\n)\n\n# Route based on buyer's preferred protocol\nresult = checkout.route_checkout(\n    buyer_agent_id=\"buyer-agent-007\",\n    items=[{\"sku\": \"PBB-608-2RS-ABEC7\", \"quantity\": 100}],\n    total=475.00,\n    preferred_protocol=\"greenhelix_escrow\",\n)\nprint(f\"Protocol: {result.protocol}, Status: {result.status}\")\nprint(f\"Transaction: {result.transaction_id}\")\n```\n\n### Protocol Selection Decision Tree\n\n```\nIs the buyer a ChatGPT user with a Stripe SPT?\n  └─ Yes → ACP (highest conversion for ChatGPT users)\n  └─ No →\n      Is the transaction \u003C $0.50?\n        └─ Yes → x402 (sub-cent fees, USDC settlement)\n        └─ No →\n            Does the buyer need escrow protection?\n              └─ Yes → GreenHelix Escrow (funds locked until delivery)\n              └─ No →\n                  Is the buyer on Google Shopping or Shopify?\n                    └─ Yes → UCP (structured catalog integration)\n                    └─ No → GreenHelix Escrow (safest default)\n```\n\n> **Key Takeaways**\n>\n> - UCP, ACP, and x402 each serve different buyer segments and transaction sizes. Most storefronts should support at least two protocols.\n> - ACP delivers 2-3x higher conversion for ChatGPT users via Instant Checkout. x402 enables sub-cent micropayments that card rails cannot support.\n> - GreenHelix escrow wraps any protocol with buyer protection -- use it as the default for agent-to-agent transactions where trust is not yet established.\n> - A multi-protocol checkout handler with routing logic can be built in a single class. Route based on buyer capabilities, transaction size, and trust requirements.\n> - Cross-reference P19 (Payment Rails Playbook) for deep x402 and MPP implementation details, and P13 (Interoperability Bridge) for protocol bridging patterns.\n\n---\n\n## Chapter 4: Structured Product Feeds That Win\n\n### The Completeness Cliff\n\nSalsify analyzed 2.3 million product listings across major U.S. retail platforms in Q1 2026. The finding that reshaped the industry: AI agent visibility is not a linear function of attribute completeness. It is a step function.\n\n| Attribute Completeness | Relative AI Agent Visibility | Agent-Attributed Orders (Index) |\n|---|---|---|\n| \u003C 80% | 1x (baseline) | 100 |\n| 80% - 89% | 1.2x | 115 |\n| 90% - 94% | 1.5x | 140 |\n| 95% - 98% | 2.1x | 210 |\n| 99% - 99.8% | 2.8x | 290 |\n| 99.9%+ | 3.8x | 380 |\n\nThe jump from 98% to 99.9% -- filling in those last few attributes -- nearly doubles visibility. This is because AI agents use embedding-based retrieval, and each additional structured attribute adds a new dimension to the embedding vector that can match queries. A product missing `operating_temp_range` is invisible to every query that includes temperature requirements, even if the product physically meets the spec.\n\n### Attribute Completeness Scoring\n\nBuild a scoring system that identifies gaps in your product data before they cost you visibility.\n\n```python\nfrom dataclasses import dataclass, field\n\n\n@dataclass\nclass CompletenessReport:\n    sku: str\n    score: float\n    total_fields: int\n    filled_fields: int\n    missing: list[str] = field(default_factory=list)\n    warnings: list[str] = field(default_factory=list)\n\n\n# Define required and recommended attributes by category\nATTRIBUTE_REQUIREMENTS = {\n    \"industrial_components\": {\n        \"required\": [\n            \"name\", \"sku\", \"brand\", \"price\", \"description\",\n            \"material\", \"dimensions\", \"weight\", \"certifications\",\n        ],\n        \"recommended\": [\n            \"mpn\", \"operating_temp_range\", \"max_load_rating\",\n            \"tolerance\", \"finish\", \"country_of_origin\",\n            \"lead_time_days\", \"moq\", \"bulk_pricing_tiers\",\n            \"datasheet_url\", \"cad_model_url\", \"rohs_compliant\",\n        ],\n        \"optional\": [\n            \"color\", \"packaging_type\", \"shelf_life\",\n            \"hazmat_classification\", \"customs_tariff_code\",\n        ],\n    },\n    \"digital_products\": {\n        \"required\": [\n            \"name\", \"sku\", \"price\", \"description\",\n            \"format\", \"file_size\", \"license_type\",\n        ],\n        \"recommended\": [\n            \"version\", \"compatible_platforms\", \"language\",\n            \"sample_url\", \"changelog_url\", \"support_url\",\n            \"api_documentation_url\", \"uptime_sla\",\n        ],\n        \"optional\": [\n            \"trial_available\", \"refund_policy\", \"volume_discounts\",\n        ],\n    },\n}\n\n\ndef score_completeness(\n    product: dict, category: str = \"industrial_components\"\n) -> CompletenessReport:\n    \"\"\"Score a product's attribute completeness.\"\"\"\n    reqs = ATTRIBUTE_REQUIREMENTS.get(category, ATTRIBUTE_REQUIREMENTS[\"industrial_components\"])\n\n    all_fields = reqs[\"required\"] + reqs[\"recommended\"] + reqs[\"optional\"]\n    # Flatten product attributes for checking\n    flat = {**product, **product.get(\"attributes\", {})}\n\n    filled = []\n    missing = []\n    warnings = []\n\n    for attr in reqs[\"required\"]:\n        if flat.get(attr) not in (None, \"\", [], {}):\n            filled.append(attr)\n        else:\n            missing.append(f\"[REQUIRED] {attr}\")\n\n    for attr in reqs[\"recommended\"]:\n        if flat.get(attr) not in (None, \"\", [], {}):\n            filled.append(attr)\n        else:\n            missing.append(f\"[RECOMMENDED] {attr}\")\n\n    for attr in reqs[\"optional\"]:\n        if flat.get(attr) not in (None, \"\", [], {}):\n            filled.append(attr)\n\n    # Quality warnings\n    if flat.get(\"description\") and len(str(flat[\"description\"])) \u003C 50:\n        warnings.append(\"Description is under 50 characters -- expand for better embeddings\")\n    if flat.get(\"price\") and float(flat[\"price\"]) == 0:\n        warnings.append(\"Price is zero -- agents may filter this as unavailable\")\n    if not flat.get(\"certifications\"):\n        warnings.append(\"No certifications listed -- reduces trust signal for B2B agents\")\n\n    total = len(all_fields)\n    score = len(filled) \u002F total if total > 0 else 0.0\n\n    return CompletenessReport(\n        sku=product.get(\"sku\", \"unknown\"),\n        score=round(score * 100, 1),\n        total_fields=total,\n        filled_fields=len(filled),\n        missing=missing,\n        warnings=warnings,\n    )\n\n\n# Score a product\nreport = score_completeness(product_data, \"industrial_components\")\nprint(f\"SKU: {report.sku}\")\nprint(f\"Completeness: {report.score}%\")\nprint(f\"Filled: {report.filled_fields}\u002F{report.total_fields}\")\nfor m in report.missing:\n    print(f\"  Missing: {m}\")\nfor w in report.warnings:\n    print(f\"  Warning: {w}\")\n```\n\n### Machine-Readable Pricing Rules\n\nAgents need to understand your pricing programmatically -- not just the base price, but volume discounts, tiered pricing, promotional rules, and currency conversion. Encode pricing rules in a structured format that agents can parse and calculate against.\n\n```python\nimport json\nfrom typing import Optional\n\n\ndef build_pricing_rules(product: dict) -> dict:\n    \"\"\"Build machine-readable pricing rules for a product.\"\"\"\n    rules = {\n        \"@type\": \"PricingRules\",\n        \"sku\": product[\"sku\"],\n        \"base_price\": {\n            \"amount\": str(product[\"price\"]),\n            \"currency\": \"USD\",\n            \"valid_until\": product.get(\"price_valid_until\", \"2026-12-31\"),\n        },\n        \"volume_discounts\": [\n            {\"min_quantity\": 1, \"max_quantity\": 99, \"unit_price\": str(product[\"price\"])},\n            {\"min_quantity\": 100, \"max_quantity\": 499, \"unit_price\": str(round(product[\"price\"] * 0.90, 2))},\n            {\"min_quantity\": 500, \"max_quantity\": 999, \"unit_price\": str(round(product[\"price\"] * 0.82, 2))},\n            {\"min_quantity\": 1000, \"max_quantity\": None, \"unit_price\": str(round(product[\"price\"] * 0.75, 2))},\n        ],\n        \"bulk_rounding\": \"per_tier\",\n        \"payment_protocols\": [\"ucp\", \"acp\", \"x402\", \"greenhelix_escrow\"],\n        \"accepted_currencies\": [\"USD\", \"EUR\", \"USDC\"],\n    }\n    return rules\n\n\n# Generate pricing rules for catalog\npricing = build_pricing_rules(product_data)\nprint(json.dumps(pricing, indent=2))\n```\n\n### Real-Time Inventory Webhooks\n\nAgents that check inventory get burned by stale data. If your catalog shows 500 units but only 3 remain, the agent starts a checkout that fails at fulfillment. This destroys your trust score. Implement real-time inventory webhooks that push updates to subscribed agents.\n\n```python\nimport time\n\n\nclass InventoryWebhookManager:\n    \"\"\"Manage real-time inventory webhooks via GreenHelix events.\"\"\"\n\n    def __init__(self, client: \"CommerceClient\"):\n        self.client = client\n\n    def publish_inventory_update(self, sku: str, quantity: int, warehouse: str = \"primary\"):\n        \"\"\"Push inventory update to subscribed agents.\"\"\"\n        return self.client.execute(\"publish_event\", {\n            \"event_type\": \"inventory.updated\",\n            \"payload\": {\n                \"sku\": sku,\n                \"available_quantity\": quantity,\n                \"warehouse\": warehouse,\n                \"timestamp\": time.time(),\n                \"in_stock\": quantity > 0,\n                \"low_stock_warning\": quantity \u003C 50,\n            },\n        })\n\n    def publish_price_change(self, sku: str, old_price: float, new_price: float):\n        \"\"\"Notify subscribed agents of a price change.\"\"\"\n        return self.client.execute(\"publish_event\", {\n            \"event_type\": \"pricing.updated\",\n            \"payload\": {\n                \"sku\": sku,\n                \"old_price\": str(old_price),\n                \"new_price\": str(new_price),\n                \"change_pct\": str(round((new_price - old_price) \u002F old_price * 100, 2)),\n                \"effective_at\": time.time(),\n            },\n        })\n\n\n# Usage\nwebhook_mgr = InventoryWebhookManager(client)\n\n# Inventory dropped -- push to all subscribed agents\nwebhook_mgr.publish_inventory_update(\"PBB-608-2RS-ABEC7\", quantity=47)\n\n# Price reduction -- agents watching this SKU get notified\nwebhook_mgr.publish_price_change(\"PBB-608-2RS-ABEC7\", old_price=4.75, new_price=4.25)\n```\n\n### Product Feed Generator with Validation\n\nCombine schemas, pricing, and inventory into a validated product feed that agents consume.\n\n```python\nimport json\nimport time\nfrom typing import Optional\n\n\nclass ProductFeedGenerator:\n    \"\"\"Generate validated, agent-ready product feeds.\"\"\"\n\n    def __init__(self, client: \"CommerceClient\", seller_id: str):\n        self.client = client\n        self.seller_id = seller_id\n\n    def generate_feed(\n        self, products: list[dict], category: str = \"industrial_components\"\n    ) -> dict:\n        \"\"\"Generate a complete product feed with validation.\"\"\"\n        feed_items = []\n        errors = []\n        total_score = 0.0\n\n        for product in products:\n            # Score completeness\n            report = score_completeness(product, category)\n            total_score += report.score\n\n            if report.score \u003C 90.0:\n                errors.append(\n                    f\"SKU {product['sku']}: completeness {report.score}% \"\n                    f\"(below 90% threshold). Missing: {report.missing[:3]}\"\n                )\n                continue\n\n            # Build the feed item\n            item = {\n                \"schema\": build_product_schema(product),\n                \"pricing\": build_pricing_rules(product),\n                \"inventory\": {\n                    \"available\": product.get(\"inventory\", 0),\n                    \"in_stock\": product.get(\"inventory\", 0) > 0,\n                    \"updated_at\": time.time(),\n                },\n                \"completeness_score\": report.score,\n            }\n            feed_items.append(item)\n\n        avg_score = total_score \u002F len(products) if products else 0.0\n\n        feed = {\n            \"@context\": \"https:\u002F\u002Fschema.org\",\n            \"@type\": \"ProductFeed\",\n            \"seller\": self.seller_id,\n            \"generated_at\": time.time(),\n            \"total_products\": len(products),\n            \"included_products\": len(feed_items),\n            \"excluded_products\": len(errors),\n            \"average_completeness\": round(avg_score, 1),\n            \"items\": feed_items,\n            \"errors\": errors,\n        }\n\n        return feed\n\n    def publish_feed(self, feed: dict) -> dict:\n        \"\"\"Publish the feed and register\u002Fupdate on GreenHelix marketplace.\"\"\"\n        # Update service registration with feed metadata\n        result = self.client.execute(\"register_service\", {\n            \"name\": f\"{self.seller_id} Product Feed\",\n            \"description\": (\n                f\"Structured product feed: {feed['included_products']} products, \"\n                f\"{feed['average_completeness']}% avg completeness. \"\n                f\"Updated {time.strftime('%Y-%m-%d %H:%M UTC', time.gmtime())}.\"\n            ),\n            \"endpoint\": f\"https:\u002F\u002F{self.seller_id}.example.com\u002Ffeed.json\",\n            \"price\": 0.0,\n            \"tags\": [\"product-feed\", \"structured-data\", \"real-time-inventory\"],\n            \"category\": \"product_catalog\",\n        })\n        return result\n\n\n# Generate and publish\nfeed_gen = ProductFeedGenerator(client, seller_id=\"precision-parts\")\nfeed = feed_gen.generate_feed([product_data])\nprint(f\"Feed: {feed['included_products']} products, {feed['average_completeness']}% avg completeness\")\nprint(f\"Excluded: {len(feed['errors'])} products below threshold\")\n\n# Publish to marketplace\nfeed_gen.publish_feed(feed)\n```\n\n### Variant Handling\n\nProducts with variants (sizes, colors, configurations) are a common source of completeness failures. Each variant must be a distinct feed item with its own SKU, attributes, and inventory count.\n\n```python\ndef expand_variants(base_product: dict, variants: list[dict]) -> list[dict]:\n    \"\"\"Expand a base product into variant-specific feed items.\n\n    Each variant overrides specific attributes of the base product\n    and gets its own SKU.\n    \"\"\"\n    expanded = []\n    for variant in variants:\n        item = {**base_product}\n        item[\"attributes\"] = {**base_product.get(\"attributes\", {})}\n\n        # Override with variant-specific values\n        for key, value in variant.items():\n            if key in (\"sku_suffix\", \"variant_label\"):\n                continue\n            if key in (\"attributes\",):\n                item[\"attributes\"].update(value)\n            else:\n                item[key] = value\n\n        # Generate variant SKU\n        item[\"sku\"] = f\"{base_product['sku']}-{variant.get('sku_suffix', 'V')}\"\n        item[\"name\"] = f\"{base_product['name']} - {variant.get('variant_label', '')}\"\n\n        expanded.append(item)\n\n    return expanded\n\n\n# Example: bearing with size variants\nsize_variants = [\n    {\"sku_suffix\": \"8MM\", \"variant_label\": \"8mm Bore\", \"price\": 4.75, \"inventory\": 24500,\n     \"attributes\": {\"bore_diameter_mm\": \"8\", \"outer_diameter_mm\": \"22\", \"width_mm\": \"7\"}},\n    {\"sku_suffix\": \"10MM\", \"variant_label\": \"10mm Bore\", \"price\": 5.25, \"inventory\": 18200,\n     \"attributes\": {\"bore_diameter_mm\": \"10\", \"outer_diameter_mm\": \"26\", \"width_mm\": \"8\"}},\n    {\"sku_suffix\": \"12MM\", \"variant_label\": \"12mm Bore\", \"price\": 6.50, \"inventory\": 9800,\n     \"attributes\": {\"bore_diameter_mm\": \"12\", \"outer_diameter_mm\": \"32\", \"width_mm\": \"10\"}},\n]\n\nall_variants = expand_variants(product_data, size_variants)\nprint(f\"Generated {len(all_variants)} variant SKUs from 1 base product\")\n```\n\n> **Key Takeaways**\n>\n> - Attribute completeness follows a step function: 99.9% completeness delivers 3-4x the AI agent visibility of 90% completeness. The last few percent matter most.\n> - Build automated completeness scoring into your product data pipeline. Flag any product below 95% for enrichment before it enters the feed.\n> - Machine-readable pricing rules (volume discounts, tier breakpoints, accepted currencies) let agents calculate total cost without human intervention.\n> - Real-time inventory webhooks via GreenHelix `publish_event` prevent stale-data checkout failures that destroy trust scores.\n> - Every product variant needs its own SKU, attributes, and inventory count. Do not collapse variants into a single listing.\n\n---\n\n## Chapter 5: Agent Discovery via GreenHelix Marketplace\n\n### The Discovery Problem\n\nYou built the storefront. Your product feeds score 99.5% completeness. Your checkout handles four payment protocols. But none of it matters if agents cannot find you.\n\nThe GreenHelix Marketplace solves this with three tools that form the discovery pipeline:\n\n1. **`register_service`** -- List your service with structured metadata, tags, and pricing.\n2. **`search_services`** -- Agents query the marketplace with natural language or structured filters.\n3. **`best_match`** -- Returns the single highest-ranked service for a query, factoring in relevance, trust score, ratings, and response time.\n\nThe ranking algorithm behind `best_match` weights five signals:\n\n| Signal | Weight | How to Optimize |\n|---|---|---|\n| **Query relevance** | 35% | Match your service description to likely agent queries. Use specific, attribute-rich descriptions. |\n| **Trust score** | 25% | Build trust with `submit_metrics` and `build_claim_chain`. Verified performance data outweighs self-reported claims. |\n| **Service rating** | 20% | Deliver quality consistently. Ratings come from `rate_service` calls by buyer agents post-transaction. |\n| **Response time** | 10% | Keep your endpoint fast. The marketplace tracks latency from health checks. Under 200ms is competitive. |\n| **Price competitiveness** | 10% | Priced reasonably relative to comparable services. Not necessarily cheapest -- value-adjusted. |\n\n### Full Registration Walkthrough\n\nRegister a service with rich metadata that maximizes each ranking signal.\n\n```python\nimport os\nimport time\n\nGATEWAY_URL = os.environ.get(\"GREENHELIX_API_URL\", \"https:\u002F\u002Fsandbox.greenhelix.net\")\n\napi_key = os.environ[\"GREENHELIX_API_KEY\"]\nheaders = {\n    \"Authorization\": f\"Bearer {api_key}\",\n    \"Content-Type\": \"application\u002Fjson\",\n}\n\n\ndef ghx(tool: str, input_data: dict) -> dict:\n    \"\"\"Execute a GreenHelix tool.\"\"\"\n    resp = requests.post(\n        f\"{GATEWAY_URL}\u002Fv1\",\n        json={\"tool\": tool, \"input\": input_data},\n        headers=headers,\n        timeout=30,\n    )\n    resp.raise_for_status()\n    return resp.json()\n\n\n# Step 1: Register your agent identity\nagent_registration = ghx(\"register_agent\", {\n    \"agent_id\": \"precision-parts-agent\",\n    \"public_key\": \"base64-encoded-ed25519-public-key\",\n    \"name\": \"Precision Parts Direct\",\n})\nprint(f\"Agent registered: {agent_registration}\")\n\n# Step 2: Create a wallet and fund it\nwallet = ghx(\"create_wallet\", {})\ndeposit = ghx(\"deposit\", {\"amount\": \"100.00\"})\nprint(f\"Wallet funded: ${deposit}\")\n\n# Step 3: Register your service on the marketplace\nservice = ghx(\"register_service\", {\n    \"name\": \"Precision Parts Catalog API\",\n    \"description\": (\n        \"Agent-ready product catalog: 12,000+ precision-machined industrial \"\n        \"components including bearings, shafts, seals, and fasteners. \"\n        \"JSON-LD product schemas with 99.5% average attribute completeness. \"\n        \"Real-time inventory via webhooks. Volume pricing with 4 discount \"\n        \"tiers. Supports checkout via UCP, ACP, x402, and GreenHelix escrow. \"\n        \"Average response time: 45ms. ISO 9001:2015 certified supply chain.\"\n    ),\n    \"endpoint\": \"https:\u002F\u002Fparts.example.com\",\n    \"price\": 0.0,  # Free discovery; revenue from product sales\n    \"tags\": [\n        \"precision-parts\", \"bearings\", \"industrial\", \"b2b\",\n        \"iso-certified\", \"real-time-inventory\", \"bulk-pricing\",\n        \"agent-ready\", \"json-ld\", \"structured-data\",\n    ],\n    \"category\": \"industrial_components\",\n})\nservice_id = service.get(\"service_id\", \"\")\nprint(f\"Service registered: {service_id}\")\n```\n\n### Building Trust Signals\n\nTrust score accounts for 25% of the `best_match` ranking. Build it with two tools: `submit_metrics` (report verified performance data) and `build_claim_chain` (create a cryptographic chain of evidence linking claims to outcomes).\n\n```python\n# Step 4: Submit performance metrics\n# These are verified by the gateway and contribute to your trust score.\nmetrics = ghx(\"submit_metrics\", {\n    \"agent_id\": \"precision-parts-agent\",\n    \"metrics\": {\n        \"orders_fulfilled_30d\": 1247,\n        \"on_time_delivery_pct\": 98.6,\n        \"return_rate_pct\": 0.3,\n        \"avg_response_time_ms\": 45,\n        \"catalog_completeness_pct\": 99.5,\n        \"active_skus\": 12847,\n        \"escrow_completion_rate_pct\": 99.8,\n    },\n})\nprint(f\"Metrics submitted: {metrics}\")\n\n# Step 5: Build a claim chain\n# Each claim links to verifiable evidence. The chain is cryptographically\n# signed and can be independently verified by any agent.\nclaim_chain = ghx(\"build_claim_chain\", {\n    \"agent_id\": \"precision-parts-agent\",\n    \"claims\": [\n        {\n            \"claim_type\": \"certification\",\n            \"claim_value\": \"ISO 9001:2015\",\n            \"evidence_url\": \"https:\u002F\u002Fparts.example.com\u002Fcerts\u002Fiso9001.pdf\",\n        },\n        {\n            \"claim_type\": \"performance\",\n            \"claim_value\": \"98.6% on-time delivery (30-day rolling)\",\n            \"evidence_url\": \"https:\u002F\u002Fparts.example.com\u002Fmetrics\u002Fdelivery\",\n        },\n        {\n            \"claim_type\": \"catalog\",\n            \"claim_value\": \"12,847 active SKUs with 99.5% completeness\",\n            \"evidence_url\": \"https:\u002F\u002Fparts.example.com\u002Ffeed.json\",\n        },\n    ],\n})\nprint(f\"Claim chain built: {claim_chain}\")\n\n# Step 6: Check your trust score\ntrust = ghx(\"get_trust_score\", {\n    \"agent_id\": \"precision-parts-agent\",\n})\nprint(f\"Trust score: {trust}\")\n```\n\n### Optimizing for search_services and best_match\n\nWhen a buyer agent calls `search_services`, the marketplace performs semantic search against service descriptions. When it calls `best_match`, it adds ranking signals. Optimize for both.\n\n```python\n# How buyer agents find you:\n\n# Broad search -- returns multiple results ranked by relevance\nsearch_results = ghx(\"search_services\", {\n    \"query\": \"precision bearings with ISO certification and bulk pricing\",\n})\nprint(f\"Search returned {len(search_results.get('services', []))} results\")\n\n# Best match -- returns the single top-ranked service\ntop_result = ghx(\"best_match\", {\n    \"query\": \"ABEC-7 ball bearings with real-time inventory API\",\n})\nprint(f\"Best match: {top_result}\")\n\n# Verify your ranking by checking trust score and reputation\nreputation = ghx(\"get_agent_reputation\", {\n    \"agent_id\": \"precision-parts-agent\",\n})\nprint(f\"Reputation: {reputation}\")\n```\n\n### The Description Optimization Checklist\n\nYour service description is the single most impactful field for `search_services` ranking. Treat it like SEO for agents.\n\n| Element | Include? | Example |\n|---|---|---|\n| Product count | Yes | \"12,000+ precision-machined components\" |\n| Product categories | Yes | \"bearings, shafts, seals, fasteners\" |\n| Data quality signal | Yes | \"99.5% average attribute completeness\" |\n| Data format | Yes | \"JSON-LD product schemas\" |\n| Real-time capabilities | Yes | \"Real-time inventory via webhooks\" |\n| Pricing structure | Yes | \"Volume pricing with 4 discount tiers\" |\n| Payment protocols | Yes | \"UCP, ACP, x402, GreenHelix escrow\" |\n| Performance metric | Yes | \"Average response time: 45ms\" |\n| Certifications | Yes | \"ISO 9001:2015 certified supply chain\" |\n| Vague marketing copy | No | \"World-class quality\" (meaningless to agents) |\n\nEvery keyword in your description is a potential match for an agent query. Be specific, quantitative, and structured.\n\n> **Key Takeaways**\n>\n> - The GreenHelix marketplace uses five ranking signals: query relevance (35%), trust score (25%), ratings (20%), response time (10%), and price competitiveness (10%).\n> - `register_service` with a rich, keyword-dense description is the foundation. Include product count, categories, data quality metrics, payment protocols, and performance numbers.\n> - Trust signals from `submit_metrics` and `build_claim_chain` account for 25% of ranking. Cryptographic claim chains are more credible than self-reported descriptions.\n> - Optimize your description like SEO for agents: specific, quantitative, structured. Avoid vague marketing language that agents cannot parse.\n> - Cross-reference P4 (Commerce Toolkit) for the full `AgentCommerce` class and P18 (Pricing & Monetization) for marketplace listing economics.\n\n---\n\n## Chapter 6: Agent-to-Agent Payment Flows\n\n### Payment Primitives\n\nThe GreenHelix gateway provides five payment primitives that cover the full lifecycle of agent-to-agent commerce:\n\n| Primitive | Tool | Purpose |\n|---|---|---|\n| **Escrow** | `create_escrow` \u002F `release_escrow` \u002F `cancel_escrow` | Lock funds until work is verified. The core trust mechanism. |\n| **Performance Escrow** | `create_performance_escrow` \u002F `check_performance_escrow` | Auto-release when measurable metrics exceed a threshold. |\n| **Subscription** | `create_subscription` \u002F `cancel_subscription` | Recurring payments for ongoing services. |\n| **Deposit** | `deposit` \u002F `get_balance` | Fund agent wallets for payment capability. |\n| **Dispute** | `create_dispute` \u002F `resolve_dispute` | Structured disagreement resolution with evidence. |\n\n### Escrow-Protected Product Purchases\n\nThe most common pattern: a buyer agent locks funds in escrow, the seller fulfills the order, and the buyer releases payment on delivery confirmation.\n\n```python\nimport os\nimport time\n\napi_key = os.environ[\"GREENHELIX_API_KEY\"]\nheaders = {\n    \"Authorization\": f\"Bearer {api_key}\",\n    \"Content-Type\": \"application\u002Fjson\",\n}\n\n\ndef ghx(tool: str, input_data: dict) -> dict:\n    resp = requests.post(\n        f\"{GATEWAY_URL}\u002Fv1\",\n        json={\"tool\": tool, \"input\": input_data},\n        headers=headers,\n        timeout=30,\n    )\n    resp.raise_for_status()\n    return resp.json()\n\n\nclass EscrowCheckout:\n    \"\"\"Manage escrow-protected product purchases.\"\"\"\n\n    def __init__(self, buyer_id: str, seller_id: str):\n        self.buyer_id = buyer_id\n        self.seller_id = seller_id\n\n    def create_order(self, items: list[dict], total: float) -> dict:\n        \"\"\"Create an escrow-backed order.\"\"\"\n        # Step 1: Verify buyer has sufficient balance\n        balance = ghx(\"get_balance\", {})\n        available = float(balance.get(\"balance\", \"0\"))\n        if available \u003C total:\n            return {\"error\": f\"Insufficient balance: ${available} \u003C ${total}\"}\n\n        # Step 2: Create escrow\n        escrow = ghx(\"create_escrow\", {\n            \"payer_agent_id\": self.buyer_id,\n            \"payee_agent_id\": self.seller_id,\n            \"amount\": str(total),\n            \"description\": (\n                f\"Product order: {len(items)} items. \"\n                f\"SKUs: {', '.join(i['sku'] for i in items)}\"\n            ),\n        })\n\n        return {\n            \"order_id\": escrow.get(\"escrow_id\"),\n            \"status\": \"escrow_locked\",\n            \"amount\": str(total),\n            \"items\": items,\n        }\n\n    def confirm_delivery(self, escrow_id: str) -> dict:\n        \"\"\"Buyer confirms delivery -- release funds to seller.\"\"\"\n        release = ghx(\"release_escrow\", {\"escrow_id\": escrow_id})\n        return {\n            \"escrow_id\": escrow_id,\n            \"status\": \"payment_released\",\n            \"result\": release,\n        }\n\n    def cancel_order(self, escrow_id: str) -> dict:\n        \"\"\"Cancel the order -- return funds to buyer.\"\"\"\n        cancel = ghx(\"cancel_escrow\", {\"escrow_id\": escrow_id})\n        return {\n            \"escrow_id\": escrow_id,\n            \"status\": \"order_cancelled\",\n            \"result\": cancel,\n        }\n\n\n# Full purchase flow\ncheckout = EscrowCheckout(\n    buyer_id=\"buyer-agent-007\",\n    seller_id=\"precision-parts-agent\",\n)\n\n# Place order\norder = checkout.create_order(\n    items=[\n        {\"sku\": \"PBB-608-2RS-ABEC7\", \"quantity\": 100, \"unit_price\": 4.28},\n        {\"sku\": \"PBB-608-2RS-ABEC7-10MM\", \"quantity\": 50, \"unit_price\": 4.73},\n    ],\n    total=664.50,\n)\nprint(f\"Order placed: {order}\")\n\n# ... seller ships, buyer receives ...\n\n# Confirm delivery and release payment\nif order.get(\"order_id\"):\n    result = checkout.confirm_delivery(order[\"order_id\"])\n    print(f\"Payment released: {result}\")\n```\n\n### Performance-Gated Payments\n\nFor services where quality is measurable, performance escrow auto-releases when metrics exceed agreed thresholds. No manual release needed.\n\n```python\n# Create performance escrow for a data enrichment service\n# Funds release automatically when accuracy exceeds 95%\nperf_escrow = ghx(\"create_performance_escrow\", {\n    \"payer_agent_id\": \"buyer-agent-007\",\n    \"payee_agent_id\": \"enrichment-service-agent\",\n    \"amount\": \"500.00\",\n    \"currency\": \"USD\",\n    \"performance_criteria\": {\n        \"min_accuracy\": 0.95,\n        \"min_records_processed\": 10000,\n    },\n    \"evaluation_period_days\": 7,\n})\nperf_escrow_id = perf_escrow.get(\"escrow_id\", \"\")\nprint(f\"Performance escrow created: {perf_escrow_id}\")\n\n# After the service runs, check if criteria are met\ncheck = ghx(\"check_performance_escrow\", {\n    \"escrow_id\": perf_escrow_id,\n})\nprint(f\"Performance check: {check}\")\n# If criteria met → funds auto-release to seller\n# If not met within evaluation period → funds return to buyer\n```\n\n### Subscription Billing\n\nFor ongoing services -- monitoring, data feeds, continuous enrichment -- use subscription billing. The gateway handles recurring charges automatically.\n\n```python\n# Create a monthly subscription for real-time inventory feed access\nsubscription = ghx(\"create_subscription\", {\n    \"payer_agent_id\": \"buyer-agent-007\",\n    \"payee_agent_id\": \"precision-parts-agent\",\n    \"amount\": \"49.00\",\n    \"interval\": \"monthly\",\n})\nsubscription_id = subscription.get(\"subscription_id\", \"\")\nprint(f\"Subscription created: {subscription_id}\")\n\n# Check subscription status\nstatus = ghx(\"get_subscription\", {\n    \"subscription_id\": subscription_id,\n})\nprint(f\"Subscription status: {status}\")\n\n# Cancel when no longer needed\n# cancel = ghx(\"cancel_subscription\", {\"subscription_id\": subscription_id})\n```\n\n### Dispute Resolution\n\nWhen a buyer disputes a transaction -- wrong items, quality below spec, incomplete delivery -- the dispute system provides structured resolution.\n\n```python\nclass DisputeManager:\n    \"\"\"Handle disputes on escrow-backed transactions.\"\"\"\n\n    def open_dispute(self, escrow_id: str, reason: str, evidence: dict) -> dict:\n        \"\"\"Buyer opens a dispute on an active escrow.\"\"\"\n        dispute = ghx(\"create_dispute\", {\n            \"escrow_id\": escrow_id,\n            \"reason\": reason,\n            \"evidence\": evidence,\n        })\n        return dispute\n\n    def respond_to_dispute(self, dispute_id: str, response: str, evidence: dict) -> dict:\n        \"\"\"Seller responds to a dispute with counter-evidence.\"\"\"\n        response_result = ghx(\"resolve_dispute\", {\n            \"dispute_id\": dispute_id,\n            \"resolution\": response,\n            \"evidence\": evidence,\n        })\n        return response_result\n\n\n# Dispute flow example\ndisputes = DisputeManager()\n\n# Buyer: received wrong items\ndispute = disputes.open_dispute(\n    escrow_id=\"esc_abc123\",\n    reason=\"Received ABEC-5 bearings instead of ABEC-7 as ordered\",\n    evidence={\n        \"order_sku\": \"PBB-608-2RS-ABEC7\",\n        \"received_sku\": \"PBB-608-2RS-ABEC5\",\n        \"inspection_report_url\": \"https:\u002F\u002Fbuyer.example.com\u002Freports\u002Finspection_123.pdf\",\n        \"photo_urls\": [\n            \"https:\u002F\u002Fbuyer.example.com\u002Fphotos\u002Flabel_mismatch_1.jpg\",\n            \"https:\u002F\u002Fbuyer.example.com\u002Fphotos\u002Flabel_mismatch_2.jpg\",\n        ],\n    },\n)\nprint(f\"Dispute opened: {dispute}\")\n\n# Seller: respond with resolution (e.g., reshipping correct items)\nresolution = disputes.respond_to_dispute(\n    dispute_id=dispute.get(\"dispute_id\", \"\"),\n    response=\"Acknowledged. Reshipping correct ABEC-7 bearings. Tracking: FDX-789456.\",\n    evidence={\n        \"reshipment_tracking\": \"FDX-789456\",\n        \"correct_sku_confirmed\": \"PBB-608-2RS-ABEC7\",\n        \"estimated_delivery\": \"2026-04-09\",\n    },\n)\nprint(f\"Dispute resolved: {resolution}\")\n```\n\n### Deposit Management\n\nBefore an agent can participate in escrow or subscriptions, it needs a funded wallet. Manage deposits programmatically.\n\n```python\ndef ensure_funded(agent_id: str, minimum_balance: float) -> dict:\n    \"\"\"Ensure agent wallet has sufficient funds, topping up if needed.\"\"\"\n    balance = ghx(\"get_balance\", {})\n    current = float(balance.get(\"balance\", \"0\"))\n\n    if current >= minimum_balance:\n        return {\n            \"status\": \"sufficient\",\n            \"balance\": str(current),\n            \"agent_id\": agent_id,\n        }\n\n    # Top up to 2x the minimum for buffer\n    top_up_amount = (minimum_balance * 2) - current\n    deposit_result = ghx(\"deposit\", {\"amount\": str(round(top_up_amount, 2))})\n\n    return {\n        \"status\": \"topped_up\",\n        \"previous_balance\": str(current),\n        \"deposited\": str(round(top_up_amount, 2)),\n        \"new_balance\": str(current + top_up_amount),\n        \"agent_id\": agent_id,\n    }\n\n\n# Ensure buyer has enough for a $664.50 order\nfunding = ensure_funded(\"buyer-agent-007\", minimum_balance=664.50)\nprint(f\"Wallet status: {funding}\")\n```\n\n> **Key Takeaways**\n>\n> - Escrow is the core payment primitive for agent-to-agent commerce. It eliminates the trust problem: funds lock until work is verified.\n> - Performance escrow automates release based on measurable metrics -- ideal for data processing, enrichment, and any service with quantifiable quality.\n> - Subscription billing handles recurring service access with automatic charges at configurable intervals.\n> - The dispute system provides structured resolution with evidence submission from both parties. Dispute outcomes affect trust scores.\n> - Always verify wallet balance before creating escrow. Use the `ensure_funded` pattern to top up automatically.\n> - Cross-reference P4 (Commerce Toolkit) for split payment patterns and P19 (Payment Rails Playbook) for multi-rail settlement.\n\n---\n\n## Chapter 7: Testing Agent Discoverability\n\n### Why You Need an Agent Simulator\n\nYour storefront is live. Your product feed scores 99.5%. Your marketplace listing is registered. But how do you know an actual AI agent will find you, parse your data correctly, and complete checkout?\n\nYou cannot wait for production traffic to find out. You need an agent simulator -- a test harness that mimics how Gemini, ChatGPT, Perplexity, and Claude shopping agents discover, evaluate, and purchase from storefronts. The simulator queries your endpoints, validates structured data, measures response latency, and produces an Agent Readiness Index (ARI) score.\n\n### The Agent Readiness Index\n\nThe ARI score grades your storefront across five dimensions:\n\n| Dimension | Weight | What It Measures | Target |\n|---|---|---|---|\n| **Discoverability** | 25% | Can agents find your manifest and OpenAPI spec? | 100% |\n| **Data Quality** | 30% | Attribute completeness, schema validity, pricing structure | > 99% |\n| **Marketplace Ranking** | 20% | Position in `search_services` and `best_match` results | Top 3 |\n| **Checkout Completeness** | 15% | Can agents initiate checkout via all advertised protocols? | All protocols work |\n| **Response Performance** | 10% | Endpoint latency under load | \u003C 200ms p95 |\n\n### Building the Agent Simulator\n\n```python\nimport requests\nimport time\nimport json\nfrom dataclasses import dataclass, field\nfrom typing import Optional\n\nGATEWAY_URL = os.environ.get(\"GREENHELIX_API_URL\", \"https:\u002F\u002Fsandbox.greenhelix.net\")\n\n\n@dataclass\nclass TestResult:\n    dimension: str\n    test_name: str\n    passed: bool\n    score: float  # 0.0 to 1.0\n    latency_ms: float\n    details: str = \"\"\n\n\n@dataclass\nclass ARIReport:\n    overall_score: float = 0.0\n    grade: str = \"\"\n    results: list[TestResult] = field(default_factory=list)\n    recommendations: list[str] = field(default_factory=list)\n\n\nclass AgentSimulator:\n    \"\"\"Simulate AI shopping agent behavior to test storefront readiness.\"\"\"\n\n    def __init__(\n        self,\n        api_key: str,\n        storefront_url: str,\n        service_query: str,\n    ):\n        self.api_key = api_key\n        self.storefront_url = storefront_url\n        self.service_query = service_query\n        self.headers = {\n            \"Authorization\": f\"Bearer {api_key}\",\n            \"Content-Type\": \"application\u002Fjson\",\n        }\n        self.results: list[TestResult] = []\n\n    def _ghx(self, tool: str, input_data: dict) -> dict:\n        resp = requests.post(\n            f\"{GATEWAY_URL}\u002Fv1\",\n            json={\"tool\": tool, \"input\": input_data},\n            headers=self.headers,\n            timeout=30,\n        )\n        resp.raise_for_status()\n        return resp.json()\n\n    def _timed_get(self, url: str) -> tuple[Optional[dict], float]:\n        \"\"\"GET a URL and return (parsed_json, latency_ms).\"\"\"\n        start = time.time()\n        try:\n            resp = requests.get(url, timeout=10)\n            latency = (time.time() - start) * 1000\n            if resp.status_code == 200:\n                return resp.json(), latency\n            return None, latency\n        except Exception:\n            return None, (time.time() - start) * 1000\n\n    # ── Discoverability Tests ──────────────────────────────────\n\n    def test_manifest(self) -> TestResult:\n        \"\"\"Test: Can agents find .well-known\u002Fai-plugin.json?\"\"\"\n        url = f\"{self.storefront_url}\u002F.well-known\u002Fai-plugin.json\"\n        data, latency = self._timed_get(url)\n\n        if data and \"name_for_model\" in data and \"api\" in data:\n            has_description = bool(data.get(\"description_for_model\", \"\"))\n            has_api_url = bool(data.get(\"api\", {}).get(\"url\", \"\"))\n            score = 1.0 if (has_description and has_api_url) else 0.7\n            result = TestResult(\n                dimension=\"discoverability\",\n                test_name=\"ai_plugin_manifest\",\n                passed=True,\n                score=score,\n                latency_ms=latency,\n                details=f\"Manifest found. description_for_model: {has_description}, api.url: {has_api_url}\",\n            )\n        else:\n            result = TestResult(\n                dimension=\"discoverability\",\n                test_name=\"ai_plugin_manifest\",\n                passed=False,\n                score=0.0,\n                latency_ms=latency,\n                details=\"Manifest missing or malformed\",\n            )\n\n        self.results.append(result)\n        return result\n\n    def test_openapi_spec(self) -> TestResult:\n        \"\"\"Test: Is the OpenAPI spec reachable and valid?\"\"\"\n        # First get the manifest to find the OpenAPI URL\n        manifest_url = f\"{self.storefront_url}\u002F.well-known\u002Fai-plugin.json\"\n        manifest, _ = self._timed_get(manifest_url)\n\n        if not manifest:\n            result = TestResult(\n                dimension=\"discoverability\",\n                test_name=\"openapi_spec\",\n                passed=False,\n                score=0.0,\n                latency_ms=0,\n                details=\"Cannot test: manifest not found\",\n            )\n            self.results.append(result)\n            return result\n\n        api_url = manifest.get(\"api\", {}).get(\"url\", \"\")\n        if not api_url:\n            result = TestResult(\n                dimension=\"discoverability\",\n                test_name=\"openapi_spec\",\n                passed=False,\n                score=0.0,\n                latency_ms=0,\n                details=\"No api.url in manifest\",\n            )\n            self.results.append(result)\n            return result\n\n        data, latency = self._timed_get(api_url)\n        has_paths = bool(data and data.get(\"paths\"))\n        has_info = bool(data and data.get(\"info\"))\n\n        result = TestResult(\n            dimension=\"discoverability\",\n            test_name=\"openapi_spec\",\n            passed=bool(has_paths and has_info),\n            score=1.0 if (has_paths and has_info) else 0.0,\n            latency_ms=latency,\n            details=f\"OpenAPI spec: paths={has_paths}, info={has_info}\",\n        )\n        self.results.append(result)\n        return result\n\n    # ── Marketplace Tests ──────────────────────────────────────\n\n    def test_search_visibility(self) -> TestResult:\n        \"\"\"Test: Does your service appear in search_services results?\"\"\"\n        start = time.time()\n        results = self._ghx(\"search_services\", {\n            \"query\": self.service_query,\n        })\n        latency = (time.time() - start) * 1000\n\n        services = results.get(\"services\", [])\n        found = any(\n            self.storefront_url in str(s)\n            for s in services\n        )\n\n        # Score based on position\n        position = -1\n        for i, s in enumerate(services):\n            if self.storefront_url in str(s):\n                position = i\n                break\n\n        if position == 0:\n            score = 1.0\n        elif position in (1, 2):\n            score = 0.8\n        elif position >= 0:\n            score = 0.5\n        else:\n            score = 0.0\n\n        result = TestResult(\n            dimension=\"marketplace\",\n            test_name=\"search_visibility\",\n            passed=found,\n            score=score,\n            latency_ms=latency,\n            details=f\"Position in search results: {position if position >= 0 else 'not found'}. Total results: {len(services)}\",\n        )\n        self.results.append(result)\n        return result\n\n    def test_best_match(self) -> TestResult:\n        \"\"\"Test: Are you the best_match for your target query?\"\"\"\n        start = time.time()\n        match = self._ghx(\"best_match\", {\n            \"query\": self.service_query,\n        })\n        latency = (time.time() - start) * 1000\n\n        is_top = self.storefront_url in str(match)\n\n        result = TestResult(\n            dimension=\"marketplace\",\n            test_name=\"best_match_ranking\",\n            passed=is_top,\n            score=1.0 if is_top else 0.0,\n            latency_ms=latency,\n            details=f\"Top match: {'Yes' if is_top else 'No'}. Result: {json.dumps(match)[:200]}\",\n        )\n        self.results.append(result)\n        return result\n\n    # ── Data Quality Tests ─────────────────────────────────────\n\n    def test_product_schema(self) -> TestResult:\n        \"\"\"Test: Do product search results return valid JSON-LD schemas?\"\"\"\n        search_url = f\"{self.storefront_url}\u002Fproducts\u002Fsearch\"\n        start = time.time()\n        try:\n            resp = requests.post(\n                search_url,\n                json={\"query\": \"\", \"limit\": 5},\n                timeout=10,\n            )\n            latency = (time.time() - start) * 1000\n            data = resp.json()\n        except Exception:\n            latency = (time.time() - start) * 1000\n            result = TestResult(\n                dimension=\"data_quality\",\n                test_name=\"product_schema_validity\",\n                passed=False,\n                score=0.0,\n                latency_ms=latency,\n                details=\"Product search endpoint unreachable\",\n            )\n            self.results.append(result)\n            return result\n\n        products = data.get(\"results\", [])\n        valid_count = 0\n        for p in products:\n            has_context = \"@context\" in p\n            has_type = \"@type\" in p\n            has_offers = \"offers\" in p\n            has_properties = \"additionalProperty\" in p\n            if all([has_context, has_type, has_offers, has_properties]):\n                valid_count += 1\n\n        score = valid_count \u002F len(products) if products else 0.0\n\n        result = TestResult(\n            dimension=\"data_quality\",\n            test_name=\"product_schema_validity\",\n            passed=score >= 0.9,\n            score=score,\n            latency_ms=latency,\n            details=f\"{valid_count}\u002F{len(products)} products have valid JSON-LD schemas\",\n        )\n        self.results.append(result)\n        return result\n\n    # ── Checkout Tests ─────────────────────────────────────────\n\n    def test_checkout_protocols(self) -> TestResult:\n        \"\"\"Test: Can checkout be initiated for each advertised protocol?\"\"\"\n        checkout_url = f\"{self.storefront_url}\u002Fcheckout\u002Finitiate\"\n        protocols = [\"ucp\", \"acp\", \"x402\", \"greenhelix_escrow\"]\n        working = []\n\n        start = time.time()\n        for protocol in protocols:\n            try:\n                resp = requests.post(\n                    checkout_url,\n                    json={\n                        \"items\": [{\"sku\": \"TEST-SKU\", \"quantity\": 1}],\n                        \"payment_protocol\": protocol,\n                        \"buyer_agent_id\": \"test-simulator\",\n                    },\n                    timeout=10,\n                )\n                if resp.status_code in (200, 201, 402):\n                    working.append(protocol)\n            except Exception:\n                pass\n        latency = (time.time() - start) * 1000\n\n        score = len(working) \u002F len(protocols)\n        result = TestResult(\n            dimension=\"checkout\",\n            test_name=\"protocol_support\",\n            passed=score >= 0.75,\n            score=score,\n            latency_ms=latency,\n            details=f\"Working protocols: {working}. Missing: {set(protocols) - set(working)}\",\n        )\n        self.results.append(result)\n        return result\n\n    # ── Performance Tests ──────────────────────────────────────\n\n    def test_response_latency(self, num_requests: int = 10) -> TestResult:\n        \"\"\"Test: Are endpoints fast enough for agent real-time queries?\"\"\"\n        search_url = f\"{self.storefront_url}\u002Fproducts\u002Fsearch\"\n        latencies = []\n\n        for _ in range(num_requests):\n            start = time.time()\n            try:\n                requests.post(\n                    search_url,\n                    json={\"query\": \"bearing\", \"limit\": 5},\n                    timeout=10,\n                )\n                latencies.append((time.time() - start) * 1000)\n            except Exception:\n                latencies.append(10000)  # penalty for failures\n\n        if not latencies:\n            result = TestResult(\n                dimension=\"performance\",\n                test_name=\"response_latency\",\n                passed=False,\n                score=0.0,\n                latency_ms=0,\n                details=\"No successful requests\",\n            )\n            self.results.append(result)\n            return result\n\n        latencies.sort()\n        p50 = latencies[len(latencies) \u002F\u002F 2]\n        p95 = latencies[int(len(latencies) * 0.95)]\n        avg = sum(latencies) \u002F len(latencies)\n\n        # Score: 1.0 if p95 \u003C 200ms, 0.5 if \u003C 500ms, 0.0 if > 1000ms\n        if p95 \u003C 200:\n            score = 1.0\n        elif p95 \u003C 500:\n            score = 0.5\n        else:\n            score = 0.0\n\n        result = TestResult(\n            dimension=\"performance\",\n            test_name=\"response_latency\",\n            passed=p95 \u003C 200,\n            score=score,\n            latency_ms=p95,\n            details=f\"p50={p50:.0f}ms, p95={p95:.0f}ms, avg={avg:.0f}ms ({num_requests} requests)\",\n        )\n        self.results.append(result)\n        return result\n\n    # ── Report Generation ──────────────────────────────────────\n\n    def run_all(self) -> ARIReport:\n        \"\"\"Run all tests and generate an ARI report.\"\"\"\n        self.results = []\n\n        # Run all test suites\n        self.test_manifest()\n        self.test_openapi_spec()\n        self.test_search_visibility()\n        self.test_best_match()\n        self.test_product_schema()\n        self.test_checkout_protocols()\n        self.test_response_latency()\n\n        # Calculate weighted score\n        weights = {\n            \"discoverability\": 0.25,\n            \"marketplace\": 0.20,\n            \"data_quality\": 0.30,\n            \"checkout\": 0.15,\n            \"performance\": 0.10,\n        }\n\n        dimension_scores = {}\n        for r in self.results:\n            if r.dimension not in dimension_scores:\n                dimension_scores[r.dimension] = []\n            dimension_scores[r.dimension].append(r.score)\n\n        weighted_total = 0.0\n        for dim, scores in dimension_scores.items():\n            avg = sum(scores) \u002F len(scores) if scores else 0.0\n            weight = weights.get(dim, 0.1)\n            weighted_total += avg * weight\n\n        overall = round(weighted_total * 100, 1)\n\n        # Grade\n        if overall >= 90:\n            grade = \"A\"\n        elif overall >= 80:\n            grade = \"B\"\n        elif overall >= 70:\n            grade = \"C\"\n        elif overall >= 60:\n            grade = \"D\"\n        else:\n            grade = \"F\"\n\n        # Recommendations\n        recs = []\n        for r in self.results:\n            if not r.passed:\n                if r.test_name == \"ai_plugin_manifest\":\n                    recs.append(\"Add .well-known\u002Fai-plugin.json with description_for_model and api.url\")\n                elif r.test_name == \"openapi_spec\":\n                    recs.append(\"Publish a valid OpenAPI spec at the URL specified in your manifest\")\n                elif r.test_name == \"search_visibility\":\n                    recs.append(\"Optimize your register_service description with specific keywords\")\n                elif r.test_name == \"best_match_ranking\":\n                    recs.append(\"Build trust signals with submit_metrics and build_claim_chain\")\n                elif r.test_name == \"product_schema_validity\":\n                    recs.append(\"Ensure all products have @context, @type, offers, and additionalProperty\")\n                elif r.test_name == \"protocol_support\":\n                    recs.append(\"Implement all advertised checkout protocols\")\n                elif r.test_name == \"response_latency\":\n                    recs.append(\"Reduce p95 latency below 200ms -- add caching or optimize queries\")\n\n        return ARIReport(\n            overall_score=overall,\n            grade=grade,\n            results=self.results,\n            recommendations=recs,\n        )\n\n\n# Run the simulator\nsimulator = AgentSimulator(\n    api_key=os.environ[\"GREENHELIX_API_KEY\"],\n    storefront_url=\"https:\u002F\u002Fparts.example.com\",\n    service_query=\"precision bearings with ISO certification\",\n)\n\nreport = simulator.run_all()\nprint(f\"\\n{'='*50}\")\nprint(f\"AGENT READINESS INDEX: {report.overall_score}% (Grade: {report.grade})\")\nprint(f\"{'='*50}\")\n\nfor r in report.results:\n    status = \"PASS\" if r.passed else \"FAIL\"\n    print(f\"  [{status}] {r.dimension}\u002F{r.test_name}: {r.score:.0%} ({r.latency_ms:.0f}ms)\")\n    if r.details:\n        print(f\"         {r.details}\")\n\nif report.recommendations:\n    print(f\"\\nRecommendations:\")\n    for i, rec in enumerate(report.recommendations, 1):\n        print(f\"  {i}. {rec}\")\n```\n\n### Interpreting ARI Scores\n\n| Score | Grade | Interpretation | Action |\n|---|---|---|---|\n| 90-100 | A | Agent-ready. Agents can discover, evaluate, and purchase from your storefront. | Monitor and maintain. |\n| 80-89 | B | Mostly ready. One or two gaps reducing visibility or conversion. | Fix specific failures. |\n| 70-79 | C | Functional but underperforming. Missing trust signals or incomplete schemas. | Prioritize data quality and marketplace optimization. |\n| 60-69 | D | Significant gaps. Agents can find you but struggle to complete purchases. | Full audit needed. Use the 14-Day Sprint (Chapter 8). |\n| \u003C 60 | F | Not agent-ready. Most agents will skip your storefront entirely. | Start from Chapter 2 and implement systematically. |\n\n### Continuous Monitoring\n\nRun the simulator on a schedule -- daily or on every deployment -- and track your ARI score over time. Publish the results as metrics on GreenHelix to reinforce your trust score.\n\n```python\ndef publish_ari_as_metrics(report: ARIReport):\n    \"\"\"Publish ARI results as GreenHelix metrics for trust scoring.\"\"\"\n    dimension_scores = {}\n    for r in report.results:\n        if r.dimension not in dimension_scores:\n            dimension_scores[r.dimension] = []\n        dimension_scores[r.dimension].append(r.score)\n\n    metrics = {\n        \"ari_overall_score\": report.overall_score,\n        \"ari_grade\": report.grade,\n    }\n    for dim, scores in dimension_scores.items():\n        avg = sum(scores) \u002F len(scores) if scores else 0\n        metrics[f\"ari_{dim}_score\"] = round(avg * 100, 1)\n\n    ghx(\"submit_metrics\", {\n        \"agent_id\": \"precision-parts-agent\",\n        \"metrics\": metrics,\n    })\n    print(f\"ARI metrics published to GreenHelix\")\n\n\npublish_ari_as_metrics(report)\n```\n\n> **Key Takeaways**\n>\n> - Build an agent simulator that tests five dimensions: discoverability, data quality, marketplace ranking, checkout completeness, and response performance.\n> - The Agent Readiness Index (ARI) provides a single score (0-100) and letter grade for your storefront's agent compatibility. Target 90+ (Grade A).\n> - Run the simulator on every deployment and track ARI over time. Regressions in structured data or latency directly reduce agent-referred revenue.\n> - Publish ARI scores as GreenHelix metrics via `submit_metrics` to reinforce your trust score and marketplace ranking.\n> - The simulator catches problems before production agents do -- a schema regression caught in CI is free; a schema regression caught by a lost sale costs revenue.\n\n---\n\n## Chapter 8: The 14-Day ACO Sprint\n\n### Overview\n\nThe Agent Commerce Optimization (ACO) Sprint is a 14-day execution plan that takes your storefront from zero agent readiness to production-grade discoverability. Each day has specific deliverables, measurable checkpoints, and code tasks. By day 14, your ARI score should be 85+ with a clear path to 95+.\n\n### Days 1-2: Audit Product Data\n\n**Objective**: Assess current product data quality and identify gaps.\n\n**Day 1 Tasks**:\n\n- [ ] Export your full product catalog to a structured format (JSON or CSV)\n- [ ] Run the completeness scoring function from Chapter 4 against every product\n- [ ] Generate a gap report: which products are below 95% completeness?\n- [ ] Identify the 10 most common missing attributes across your catalog\n\n**Day 2 Tasks**:\n\n- [ ] Prioritize products by revenue contribution -- fix the top 20% first (they drive 80% of revenue)\n- [ ] Fill in missing required attributes for all top-revenue products\n- [ ] Set up automated completeness scoring in your CI\u002FCD pipeline\n- [ ] Target: all top-revenue products at 98%+ completeness\n\n```python\n# Day 1-2: Catalog audit script\nimport json\n\n\ndef audit_catalog(products: list[dict], category: str) -> dict:\n    \"\"\"Audit an entire product catalog for agent readiness.\"\"\"\n    results = {\n        \"total_products\": len(products),\n        \"above_99\": 0,\n        \"above_95\": 0,\n        \"above_90\": 0,\n        \"below_90\": 0,\n        \"most_common_missing\": {},\n        \"products_to_fix\": [],\n    }\n\n    for product in products:\n        report = score_completeness(product, category)\n\n        if report.score >= 99.0:\n            results[\"above_99\"] += 1\n        elif report.score >= 95.0:\n            results[\"above_95\"] += 1\n        elif report.score >= 90.0:\n            results[\"above_90\"] += 1\n        else:\n            results[\"below_90\"] += 1\n            results[\"products_to_fix\"].append({\n                \"sku\": report.sku,\n                \"score\": report.score,\n                \"missing\": report.missing[:5],\n            })\n\n        for m in report.missing:\n            attr = m.split(\"] \")[1] if \"] \" in m else m\n            results[\"most_common_missing\"][attr] = (\n                results[\"most_common_missing\"].get(attr, 0) + 1\n            )\n\n    # Sort most common missing by frequency\n    results[\"most_common_missing\"] = dict(\n        sorted(\n            results[\"most_common_missing\"].items(),\n            key=lambda x: x[1],\n            reverse=True,\n        )[:10]\n    )\n\n    return results\n\n\n# Run the audit\n# audit = audit_catalog(all_products, \"industrial_components\")\n# print(json.dumps(audit, indent=2))\n```\n\n### Days 3-5: Implement Manifests and Schemas\n\n**Objective**: Deploy the three layers of agent discoverability.\n\n**Day 3 Tasks**:\n\n- [ ] Create `.well-known\u002Fai-plugin.json` manifest (Chapter 2, Layer 1)\n- [ ] Write `description_for_model` optimized for your top 5 search queries\n- [ ] Deploy manifest to production and verify with `curl`\n\n**Day 4 Tasks**:\n\n- [ ] Implement JSON-LD product schemas using `build_product_schema()` (Chapter 2, Layer 2)\n- [ ] Add schemas to all product pages (embed in HTML) and as API responses\n- [ ] Validate schemas with Google's Rich Results Test\n\n**Day 5 Tasks**:\n\n- [ ] Publish OpenAPI spec at the URL referenced in your manifest (Chapter 2, Layer 3)\n- [ ] Include `\u002Fproducts\u002Fsearch`, `\u002Fproducts\u002F{sku}\u002Finventory`, and `\u002Fcheckout\u002Finitiate` endpoints\n- [ ] Test with an OpenAPI validator (e.g., `openapi-spec-validator` Python package)\n- [ ] Run ARI discoverability tests -- target 100%\n\n```python\n# Day 3-5: Verify all three layers are deployed\ndef verify_storefront_layers(base_url: str) -> dict:\n    \"\"\"Verify all three agent-readiness layers are deployed.\"\"\"\n    checks = {}\n\n    # Layer 1: Manifest\n    try:\n        resp = requests.get(f\"{base_url}\u002F.well-known\u002Fai-plugin.json\", timeout=5)\n        manifest = resp.json()\n        checks[\"manifest\"] = {\n            \"deployed\": resp.status_code == 200,\n            \"has_model_description\": bool(manifest.get(\"description_for_model\")),\n            \"has_api_url\": bool(manifest.get(\"api\", {}).get(\"url\")),\n        }\n    except Exception as e:\n        checks[\"manifest\"] = {\"deployed\": False, \"error\": str(e)}\n\n    # Layer 2: Product schemas (check search endpoint)\n    try:\n        resp = requests.post(\n            f\"{base_url}\u002Fproducts\u002Fsearch\",\n            json={\"query\": \"\", \"limit\": 1},\n            timeout=5,\n        )\n        results = resp.json().get(\"results\", [])\n        if results:\n            has_jsonld = \"@context\" in results[0] and \"@type\" in results[0]\n            checks[\"schemas\"] = {\"deployed\": True, \"valid_jsonld\": has_jsonld}\n        else:\n            checks[\"schemas\"] = {\"deployed\": True, \"valid_jsonld\": False, \"note\": \"No results\"}\n    except Exception as e:\n        checks[\"schemas\"] = {\"deployed\": False, \"error\": str(e)}\n\n    # Layer 3: OpenAPI spec\n    api_url = checks.get(\"manifest\", {}).get(\"has_api_url\")\n    if api_url and checks.get(\"manifest\", {}).get(\"deployed\"):\n        try:\n            manifest_resp = requests.get(f\"{base_url}\u002F.well-known\u002Fai-plugin.json\")\n            api_spec_url = manifest_resp.json().get(\"api\", {}).get(\"url\", \"\")\n            spec_resp = requests.get(api_spec_url, timeout=5)\n            checks[\"openapi\"] = {\n                \"deployed\": spec_resp.status_code == 200,\n                \"has_paths\": \"paths\" in spec_resp.text,\n            }\n        except Exception as e:\n            checks[\"openapi\"] = {\"deployed\": False, \"error\": str(e)}\n    else:\n        checks[\"openapi\"] = {\"deployed\": False, \"note\": \"No api.url in manifest\"}\n\n    return checks\n\n\n# verify = verify_storefront_layers(\"https:\u002F\u002Fparts.example.com\")\n# print(json.dumps(verify, indent=2))\n```\n\n### Days 6-8: Connect Payment Rails\n\n**Objective**: Implement multi-protocol checkout.\n\n**Day 6 Tasks**:\n\n- [ ] Implement GreenHelix escrow checkout (`create_escrow` \u002F `release_escrow`)\n- [ ] Test escrow flow end-to-end: create, verify lock, release, verify balance\n- [ ] Deploy `\u002Fcheckout\u002Finitiate` endpoint with `greenhelix_escrow` support\n\n**Day 7 Tasks**:\n\n- [ ] Add x402 checkout flow for micropayments \u002F digital product delivery\n- [ ] Add UCP checkout flow for structured catalog purchases\n- [ ] Test both flows with the agent simulator\n\n**Day 8 Tasks**:\n\n- [ ] Add ACP checkout flow if you have a Stripe merchant account\n- [ ] Implement the `MultiProtocolCheckout` router from Chapter 3\n- [ ] Run ARI checkout tests -- target all advertised protocols working\n- [ ] Set up subscription billing for recurring access with `create_subscription`\n\n```python\n# Day 6-8: End-to-end checkout verification\ndef verify_checkout_flows(base_url: str) -> dict:\n    \"\"\"Verify all checkout protocols are functional.\"\"\"\n    protocols = [\"greenhelix_escrow\", \"x402\", \"ucp\", \"acp\"]\n    results = {}\n\n    for protocol in protocols:\n        try:\n            resp = requests.post(\n                f\"{base_url}\u002Fcheckout\u002Finitiate\",\n                json={\n                    \"items\": [{\"sku\": \"TEST-VERIFY\", \"quantity\": 1}],\n                    \"payment_protocol\": protocol,\n                    \"buyer_agent_id\": \"checkout-verifier\",\n                },\n                timeout=10,\n            )\n            results[protocol] = {\n                \"status_code\": resp.status_code,\n                \"working\": resp.status_code in (200, 201, 402),\n                \"response\": resp.json() if resp.status_code \u003C 500 else None,\n            }\n        except Exception as e:\n            results[protocol] = {\"working\": False, \"error\": str(e)}\n\n    return results\n```\n\n### Days 9-10: Register on Marketplaces\n\n**Objective**: Make your storefront discoverable through the GreenHelix marketplace.\n\n**Day 9 Tasks**:\n\n- [ ] Register agent identity with `register_agent`\n- [ ] Create and fund wallet with `create_wallet` and `deposit`\n- [ ] Register service with optimized description using `register_service` (Chapter 5)\n- [ ] Verify service appears in `search_services` results for your target queries\n\n**Day 10 Tasks**:\n\n- [ ] Submit initial performance metrics with `submit_metrics`\n- [ ] Build claim chain with certifications and evidence using `build_claim_chain`\n- [ ] Check trust score with `get_trust_score` -- establish baseline\n- [ ] Run ARI marketplace tests -- target top 3 position for primary queries\n- [ ] Verify `best_match` returns your service for at least one target query\n\n```python\n# Day 9-10: Marketplace registration and verification\ndef verify_marketplace_presence(service_query: str) -> dict:\n    \"\"\"Verify marketplace presence and ranking.\"\"\"\n    results = {}\n\n    # Check search visibility\n    search = ghx(\"search_services\", {\"query\": service_query})\n    services = search.get(\"services\", [])\n    results[\"search_results_count\"] = len(services)\n    results[\"appears_in_search\"] = len(services) > 0\n\n    # Check best_match\n    match = ghx(\"best_match\", {\"query\": service_query})\n    results[\"best_match\"] = match\n\n    # Check trust score\n    trust = ghx(\"get_trust_score\", {\n        \"agent_id\": \"precision-parts-agent\",\n    })\n    results[\"trust_score\"] = trust\n\n    return results\n```\n\n### Days 11-14: Monitoring and Iteration\n\n**Objective**: Set up continuous monitoring, fix remaining gaps, and iterate toward ARI 95+.\n\n**Day 11 Tasks**:\n\n- [ ] Run full ARI assessment with the agent simulator from Chapter 7\n- [ ] Document current score and grade\n- [ ] Prioritize failed tests by impact (weight x gap from target)\n\n**Day 12 Tasks**:\n\n- [ ] Fix the top 3 highest-impact failures identified on Day 11\n- [ ] Re-run ARI assessment after each fix to verify improvement\n- [ ] Set up scheduled ARI monitoring (daily cron job or CI pipeline)\n\n**Day 13 Tasks**:\n\n- [ ] Implement inventory webhooks with `publish_event` (Chapter 4)\n- [ ] Set up price change notifications\n- [ ] Test webhook delivery to a subscriber agent\n- [ ] Optimize endpoint latency -- add caching for frequently-queried SKUs\n\n**Day 14 Tasks**:\n\n- [ ] Final ARI assessment -- target 85+ overall, with a path to 95+\n- [ ] Publish ARI metrics to GreenHelix via `submit_metrics`\n- [ ] Document remaining gaps and create a backlog for continued optimization\n- [ ] Set up alerting: notify team if ARI drops below 80\n\n```python\n# Day 14: Final assessment and metric publication\ndef final_aco_assessment(\n    api_key: str,\n    storefront_url: str,\n    service_query: str,\n    agent_id: str,\n) -> dict:\n    \"\"\"Run the final ACO sprint assessment.\"\"\"\n    # Run full ARI\n    sim = AgentSimulator(\n        api_key=api_key,\n        storefront_url=storefront_url,\n        service_query=service_query,\n    )\n    report = sim.run_all()\n\n    # Publish to GreenHelix\n    ghx(\"submit_metrics\", {\n        \"agent_id\": agent_id,\n        \"metrics\": {\n            \"ari_score\": report.overall_score,\n            \"ari_grade\": report.grade,\n            \"aco_sprint_completed\": True,\n            \"aco_completion_date\": time.strftime(\"%Y-%m-%d\"),\n        },\n    })\n\n    # Summary\n    summary = {\n        \"ari_score\": report.overall_score,\n        \"grade\": report.grade,\n        \"tests_passed\": sum(1 for r in report.results if r.passed),\n        \"tests_total\": len(report.results),\n        \"recommendations\": report.recommendations,\n        \"sprint_status\": \"complete\" if report.overall_score >= 85 else \"needs_iteration\",\n    }\n\n    return summary\n\n\n# final = final_aco_assessment(\n#     api_key=os.environ[\"GREENHELIX_API_KEY\"],\n#     storefront_url=\"https:\u002F\u002Fparts.example.com\",\n#     service_query=\"precision bearings ISO certified\",\n#     agent_id=\"precision-parts-agent\",\n# )\n# print(json.dumps(final, indent=2))\n```\n\n### Printable ACO Sprint Checklist\n\n```\nACO SPRINT CHECKLIST\n====================\n\nPHASE 1: AUDIT (Days 1-2)\n[ ] Export full product catalog\n[ ] Run completeness scoring on all products\n[ ] Generate gap report\n[ ] Identify top 10 missing attributes\n[ ] Fix top-revenue products to 98%+ completeness\n[ ] Set up automated scoring in CI\u002FCD\n\nPHASE 2: MANIFESTS & SCHEMAS (Days 3-5)\n[ ] Deploy .well-known\u002Fai-plugin.json\n[ ] Write optimized description_for_model\n[ ] Implement JSON-LD product schemas\n[ ] Embed schemas in pages and API responses\n[ ] Publish OpenAPI spec\n[ ] Validate all three layers\n\nPHASE 3: PAYMENT RAILS (Days 6-8)\n[ ] Implement GreenHelix escrow checkout\n[ ] Test escrow end-to-end\n[ ] Add x402 micropayment flow\n[ ] Add UCP checkout flow\n[ ] Add ACP checkout flow (if Stripe merchant)\n[ ] Deploy MultiProtocolCheckout router\n[ ] Set up subscription billing\n\nPHASE 4: MARKETPLACE (Days 9-10)\n[ ] Register agent identity\n[ ] Create and fund wallet\n[ ] Register service with optimized description\n[ ] Verify search_services visibility\n[ ] Submit performance metrics\n[ ] Build claim chain with evidence\n[ ] Check trust score baseline\n[ ] Verify best_match ranking\n\nPHASE 5: MONITORING (Days 11-14)\n[ ] Run full ARI assessment\n[ ] Fix top 3 highest-impact failures\n[ ] Set up daily ARI monitoring\n[ ] Implement inventory webhooks\n[ ] Set up price change notifications\n[ ] Optimize endpoint latency (\u003C 200ms p95)\n[ ] Final ARI assessment (target: 85+)\n[ ] Publish ARI metrics to GreenHelix\n[ ] Document remaining gaps\n[ ] Set up regression alerting (ARI \u003C 80)\n\nSCORE: ___\u002F100  GRADE: ___\n```\n\n> **Key Takeaways**\n>\n> - The 14-day ACO sprint follows five phases: audit (days 1-2), manifests and schemas (days 3-5), payment rails (days 6-8), marketplace registration (days 9-10), and monitoring and iteration (days 11-14).\n> - Target ARI 85+ by day 14. Most storefronts can reach this with focused execution on data completeness and marketplace optimization.\n> - Continuous ARI monitoring catches regressions before they cost revenue. Run the agent simulator on every deployment.\n> - The sprint is not a one-time event. Agent commerce standards evolve monthly. Schedule quarterly ACO refreshes to maintain competitiveness.\n> - Cross-reference P4 (Commerce Toolkit) for escrow patterns, P13 (Interoperability Bridge) for protocol bridging, P18 (Pricing & Monetization) for pricing optimization, and P19 (Payment Rails Playbook) for deep protocol implementation.\n\n---\n\n## Appendix: Tool Reference\n\nThe following GreenHelix A2A Commerce Gateway tools are used throughout this guide. All tools are called via `POST https:\u002F\u002Fsandbox.greenhelix.net\u002Fv1` with Bearer token authentication.\n\n| Tool | Chapter(s) | Purpose |\n|---|---|---|\n| `register_agent` | 5, 6 | Register agent identity with Ed25519 public key |\n| `create_wallet` | 5, 6 | Create a wallet for an agent |\n| `deposit` | 5, 6 | Fund an agent wallet |\n| `get_balance` | 6 | Check wallet balance |\n| `register_service` | 2, 4, 5 | List a service on the marketplace |\n| `search_services` | 5, 7 | Search marketplace for services |\n| `best_match` | 5, 7 | Get highest-ranked service for a query |\n| `submit_metrics` | 5, 7, 8 | Report verified performance metrics |\n| `build_claim_chain` | 5, 8 | Create cryptographic evidence chain |\n| `get_trust_score` | 5, 8 | Check trust score for an agent |\n| `get_agent_reputation` | 5 | Get reputation details |\n| `create_escrow` | 2, 3, 6 | Lock funds until work is verified |\n| `release_escrow` | 6 | Release escrowed funds to seller |\n| `cancel_escrow` | 6 | Cancel escrow and return funds to buyer |\n| `create_performance_escrow` | 6 | Escrow with metric-based auto-release |\n| `check_performance_escrow` | 6 | Check if performance criteria are met |\n| `create_subscription` | 6 | Set up recurring payment |\n| `cancel_subscription` | 6 | Cancel a subscription |\n| `create_payment_intent` | 3 | Record payment intent for tracking |\n| `create_dispute` | 6 | Open a dispute on an escrow |\n| `resolve_dispute` | 6 | Resolve a dispute with evidence |\n| `publish_event` | 4 | Push inventory\u002Fprice events to subscribers |\n| `rate_service` | 5 | Rate a marketplace service (1-5) |\n\n---\n\n*This guide is part of the GreenHelix A2A Commerce product library. For related guides, see P4 (Commerce Toolkit), P13 (Interoperability Bridge), P18 (Pricing & Monetization), and P19 (Payment Rails Playbook).*\n\n",{"name":5,"tags":24,"type":31,"author":35,"install":36,"license":15,"version":37,"metadata":38,"price_usd":46,"executable":20,"credentials":47,"description":7,"content_type":48,"compatibility":49},[25,26,27,28,29,30,31,32,33,34],"agentic-commerce","aco","ucp","acp","product-feeds","discovery","guide","greenhelix","openclaw","ai-agent","felix-agent","none","1.3.1",{"openclaw":39},{"requires":40,"primaryEnv":42},{"env":41},[42,43,44,45],"GREENHELIX_API_KEY","WALLET_ADDRESS","AGENT_SIGNING_KEY","STRIPE_API_KEY",49,[42,43,44,45],"markdown",[33],"master","4aa004da461d820f4ea5499e58eb8d196cf99016","community\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-ready-commerce",0,"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":60,"prompt":70,"zipAvailable":71},[61,64,67],{"tool":62,"command":63},"npx","npx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-ready-commerce",{"tool":65,"command":66},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-ready-commerce",{"tool":68,"command":69},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-ready-commerce","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-ready-commerce\u002FSKILL.md",true,[],[74,81,88,95,102,109],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"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":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"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":89,"name":90,"nameZh":6,"description":91,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":92,"categories":93,"keywords":94,"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":96,"name":97,"nameZh":6,"description":98,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":99,"categories":100,"keywords":101,"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":103,"name":104,"nameZh":6,"description":105,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":106,"categories":107,"keywords":108,"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":110,"name":111,"nameZh":6,"description":112,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":113,"categories":114,"keywords":115,"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",[],[]]