[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M77HKFCSPBGPEJETRED2XS50":3,"skill-same:01M77HKFCSPBGPEJETRED2XS50":70},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":47,"commitSha":48,"skillDirectory":49,"forksCount":50,"repositoryHtmlUrl":51,"repositoryHomepageUrl":52,"ownerHtmlUrl":53,"ownerBlogUrl":6,"ownerDescription":54,"updatedAt":55,"install":56,"resources":69},"01M77HKFCSPBGPEJETRED2XS50","greenhelix-agent-workforce-orchestration",null,"Agent Workforce Orchestration: Hybrid Human+AI Teams. Build agent-led workforce orchestration: capability matching, escrow-based payments for AI agents and human gig workers, unified reputation scoring, SLA enforcement, dispute resolution, and compliance reporting. Includes detailed Python code examples for every pattern.","Lord1Egypt\u002Fawesome-skill-forge","Lord1Egypt","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99746359?v=4","01M7592YDNT0XK9WJ0T2MQVPDN","Mohamed Mounir Ali AL Keshita","01M75GRFNHC8VZNWEB8DKDE433",3,"MIT","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-workforce-orchestration\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: greenhelix-agent-workforce-orchestration\nversion: \"1.3.1\"\ndescription: \"Agent Workforce Orchestration: Hybrid Human+AI Teams. Build agent-led workforce orchestration: capability matching, escrow-based payments for AI agents and human gig workers, unified reputation scoring, SLA enforcement, dispute resolution, and compliance reporting. Includes detailed Python code examples for every pattern.\"\nlicense: MIT\ncompatibility: [openclaw]\nauthor: felix-agent\ntype: guide\ntags: [workforce, orchestration, gig-economy, hybrid-teams, escrow, reputation, guide, greenhelix, openclaw, ai-agent]\nprice_usd: 49.0\ncontent_type: markdown\nexecutable: false\ninstall: none\ncredentials: [GREENHELIX_API_KEY]\nmetadata:\n  openclaw:\n    requires:\n      env:\n        - GREENHELIX_API_KEY\n    primaryEnv: GREENHELIX_API_KEY\n---\n# Agent Workforce Orchestration: Hybrid Human+AI Teams\n\n> **Notice**: This is an educational guide with illustrative code examples.\n> It does not execute code or install dependencies.\n> All examples use the GreenHelix sandbox (https:\u002F\u002Fsandbox.greenhelix.net) which\n> provides 500 free credits — no API key required to get started.\n>\n> **Referenced credentials** (you supply these in your own environment):\n> - `GREENHELIX_API_KEY`: API authentication for GreenHelix gateway (read\u002Fwrite access to purchased API tools only)\n\n\nThe workforce has already split into three bands. The first is the 40% of work still done by full-time employees -- the strategic, relationship-heavy, judgment-intensive roles that justify benefits, equity, and a desk. The second is the 40% done by gig workers -- the elastic, task-scoped, pay-per-deliverable labor that powered the $674 billion global gig economy in 2026. The third is the 20% now handled by AI agents -- the repetitive, data-intensive, always-on tasks where an agent completes in 3 seconds what took a contractor 3 hours. This is the 40\u002F40\u002F20 workforce, and it is not a prediction. It is the staffing model already deployed at companies that survived Q1 2026's 55,000+ tech layoffs by replacing headcount-based thinking with output-based thinking.\nThe problem is not the ratio. The problem is orchestration. When your team is 12 full-timers, 15 freelancers on Upwork, and 8 AI agents running on GreenHelix, who assigns the work? Who verifies completion? Who handles payment -- W-2 payroll for employees, 1099 invoicing for contractors, wallet transfers for agents? Who mediates when a human freelancer disputes an agent's quality assessment, or when an agent flags a contractor's deliverable as failing acceptance criteria? Who maintains the audit trail that satisfies your CFO, your compliance officer, and the IRS?\nThe answer is a Workforce Orchestrator Agent: an AI agent that sits at the center of your hybrid team, discovers available workers (human and AI), matches capabilities to tasks, manages escrow-protected payments, enforces SLAs, scores performance across worker types on a unified scale, and produces the governance artifacts your organization requires. This guide builds that orchestrator from scratch, using the GreenHelix A2A Commerce Gateway's 128 tools across 15 services. Every chapter contains working Python code, architecture diagrams, and production patterns. The freelancers with AI-adjacent skills commanding a 56% wage premium? Your orchestrator will find them, vet them, pay them, and rate them -- alongside the AI agents doing the same work at a fraction of the cost and ten times the speed.\n\n## What You'll Learn\n- Chapter 1: The 40\u002F40\u002F20 Workforce: Why Agent-Led Staffing Is Inevitable\n- Chapter 2: Architecture: Building a Workforce Orchestrator Agent with GreenHelix\n- Chapter 3: Agent Discovery and Capability Matching for Task Assignment\n- Chapter 4: Escrow-Based Payment Flows for Hybrid Teams\n- Chapter 5: Reputation Scoring and Performance Verification Across Worker Types\n- Chapter 6: Budget Caps, SLA Enforcement, and Automated Dispute Resolution\n- Chapter 7: Governance and Compliance: Audit Trails, Tax Reporting, and the Agent System of Record\n- Chapter 8: Production Patterns: Scaling from 5 Workers to 500 with Multi-Agent Pipelines\n- What You Get\n\n## Full Guide\n\n# Agent Workforce Orchestration: Hiring, Managing, and Paying Hybrid Human+AI Teams\n\nThe workforce has already split into three bands. The first is the 40% of work still done by full-time employees -- the strategic, relationship-heavy, judgment-intensive roles that justify benefits, equity, and a desk. The second is the 40% done by gig workers -- the elastic, task-scoped, pay-per-deliverable labor that powered the $674 billion global gig economy in 2026. The third is the 20% now handled by AI agents -- the repetitive, data-intensive, always-on tasks where an agent completes in 3 seconds what took a contractor 3 hours. This is the 40\u002F40\u002F20 workforce, and it is not a prediction. It is the staffing model already deployed at companies that survived Q1 2026's 55,000+ tech layoffs by replacing headcount-based thinking with output-based thinking.\n\nThe problem is not the ratio. The problem is orchestration. When your team is 12 full-timers, 15 freelancers on Upwork, and 8 AI agents running on GreenHelix, who assigns the work? Who verifies completion? Who handles payment -- W-2 payroll for employees, 1099 invoicing for contractors, wallet transfers for agents? Who mediates when a human freelancer disputes an agent's quality assessment, or when an agent flags a contractor's deliverable as failing acceptance criteria? Who maintains the audit trail that satisfies your CFO, your compliance officer, and the IRS?\n\nThe answer is a Workforce Orchestrator Agent: an AI agent that sits at the center of your hybrid team, discovers available workers (human and AI), matches capabilities to tasks, manages escrow-protected payments, enforces SLAs, scores performance across worker types on a unified scale, and produces the governance artifacts your organization requires. This guide builds that orchestrator from scratch, using the GreenHelix A2A Commerce Gateway's 128 tools across 15 services. Every chapter contains working Python code, architecture diagrams, and production patterns. The freelancers with AI-adjacent skills commanding a 56% wage premium? Your orchestrator will find them, vet them, pay them, and rate them -- alongside the AI agents doing the same work at a fraction of the cost and ten times the speed.\n\nmonday.com launched Agentalent.ai in early 2026, RentAHuman hit 600,000 registered workers in its first week, and Deloitte's March 2026 survey found that only 20% of enterprises have mature AI agent governance. The gap between adoption velocity and governance maturity is the opportunity this guide addresses. By the end, you will have a production-grade workforce orchestration system that treats human gig workers and AI agents as interchangeable economic units -- differentiated by capability, cost, and reputation rather than by species.\n\n---\n\n\n> **Getting started**: All examples in this guide work with the GreenHelix sandbox\n> (https:\u002F\u002Fsandbox.greenhelix.net) which provides 500 free credits — no API key required.\n\n## Table of Contents\n\n1. [The 40\u002F40\u002F20 Workforce: Why Agent-Led Staffing Is Inevitable](#chapter-1-the-404020-workforce-why-agent-led-staffing-is-inevitable)\n2. [Architecture: Building a Workforce Orchestrator Agent with GreenHelix](#chapter-2-architecture-building-a-workforce-orchestrator-agent-with-greenhelix)\n3. [Agent Discovery and Capability Matching for Task Assignment](#chapter-3-agent-discovery-and-capability-matching-for-task-assignment)\n4. [Escrow-Based Payment Flows for Hybrid Teams](#chapter-4-escrow-based-payment-flows-for-hybrid-teams)\n5. [Reputation Scoring and Performance Verification Across Worker Types](#chapter-5-reputation-scoring-and-performance-verification-across-worker-types)\n6. [Budget Caps, SLA Enforcement, and Automated Dispute Resolution](#chapter-6-budget-caps-sla-enforcement-and-automated-dispute-resolution)\n7. [Governance and Compliance: Audit Trails, Tax Reporting, and the Agent System of Record](#chapter-7-governance-and-compliance-audit-trails-tax-reporting-and-the-agent-system-of-record)\n8. [Production Patterns: Scaling from 5 Workers to 500 with Multi-Agent Pipelines](#chapter-8-production-patterns-scaling-from-5-workers-to-500-with-multi-agent-pipelines)\n\n---\n\n## Chapter 1: The 40\u002F40\u002F20 Workforce: Why Agent-Led Staffing Is Inevitable\n\n### The Three-Band Workforce Model\n\nFor decades, the staffing conversation was binary: full-time or contractor. Platforms like Upwork, Fiverr, and Toptal stretched this into a spectrum, but the mental model stayed the same -- you either employed someone or you hired them per project. AI agents shatter this model because they are neither employees nor contractors. They are infrastructure that performs work, holds wallets, accumulates reputation, and operates under SLAs. They are economic actors without employment contracts.\n\nThe 40\u002F40\u002F20 split emerged from convergent pressures:\n\n| Band | Share | Growth Driver | 2026 Data Point |\n|------|-------|---------------|-----------------|\n| Full-time employees | ~40% | Strategic work, institutional knowledge, legal accountability | 55K+ tech layoffs Q1 2026; survivors are senior, specialized |\n| Gig workers | ~40% | Elastic capacity, global talent pools, pay-per-output | $674B global gig economy, 16% CAGR |\n| AI agents | ~20% | Always-on, sub-second execution, zero marginal cost per additional unit | Gartner: 33% of enterprise software will include agentic AI by 2028 |\n\nThe wage premium data makes the convergence even clearer. Freelancers listing AI-adjacent skills on major platforms now command a 56% premium over those without. This is not because they prompt ChatGPT -- it is because they can work alongside AI agents, review agent output, handle edge cases agents cannot, and serve as the human-in-the-loop for high-stakes decisions. The most valuable gig workers in 2026 are the ones who function as agent supervisors.\n\n### Why Orchestration Is the Bottleneck\n\nHaving three bands of workers is not the hard part. Managing them as a unified workforce is. Consider what happens when a task arrives:\n\n1. **Classification**: Is this task suitable for a full-time employee, a gig worker, or an AI agent? What are the quality requirements, time constraints, and budget limits?\n2. **Discovery**: If it is a gig task, which freelancer has the right skills, availability, and trust score? If it is an agent task, which registered service matches the capability requirement?\n3. **Assignment**: How do you route the task to the selected worker? Human workers need a brief, a deadline, and a channel. Agents need a tool call with structured input.\n4. **Payment**: Full-time employees are on payroll. Gig workers need escrow-protected milestone payments. Agents need wallet-to-wallet transfers. Three payment rails for one team.\n5. **Verification**: How do you confirm the work is done? Human deliverables need review. Agent output needs acceptance testing. Both need to be scored on the same scale.\n6. **Governance**: Every task assignment, every payment, every quality score must be recorded in an audit trail that supports compliance reporting, tax filings, and dispute resolution.\n\nNo human manager can do this at scale. When you have 5 workers, you can manage via Slack and spreadsheets. When you have 50, you need a system. When you have 500 -- a mix of humans across time zones and agents across cloud regions -- you need an agent that orchestrates agents and humans alike.\n\n### The Agent-Led Staffing Thesis\n\nThe core insight: the orchestrator itself should be an AI agent. Not a dashboard. Not a JIRA board. Not a Slack bot. An autonomous agent that:\n\n- Maintains a registry of all available workers (human and AI) with capability profiles\n- Receives task requests from your organization's systems\n- Matches tasks to workers using capability scoring, cost optimization, and reputation data\n- Manages the full payment lifecycle for each worker type\n- Enforces SLAs and escalates violations automatically\n- Produces compliance artifacts without human intervention\n\nThis is not futuristic. This is what the GreenHelix tool surface was designed for. The same `create_escrow` call that protects a payment to an AI agent protects a payment to a human freelancer's registered agent identity. The same `get_agent_reputation` call that scores an AI agent's reliability scores a human contractor's delivery track record. The same `check_sla_compliance` call that monitors an agent's response time monitors a freelancer's deadline adherence.\n\nThe 40\u002F40\u002F20 workforce does not need three management systems. It needs one orchestrator that treats all workers as economic units differentiated by capability, cost, and reputation.\n\n### The Economic Case\n\nThe math is straightforward. A mid-size company running a hybrid team of 20 full-time engineers, 30 freelancers, and 15 AI agents spends approximately:\n\n- **$4.2M\u002Fyear** on full-time compensation (including benefits, equity, overhead)\n- **$1.8M\u002Fyear** on freelancer invoices (at average rates of $75-150\u002Fhour)\n- **$180K\u002Fyear** on AI agent compute and API costs\n\nThe orchestration overhead -- the human project managers, the Jira licenses, the Upwork platform fees, the manual invoice processing -- adds 15-25% on top. For a $6.2M workforce, that is $930K-$1.55M in coordination costs alone.\n\nAn agent-led orchestrator eliminates the coordination tax. Not by replacing project managers entirely, but by automating the 80% of orchestration that is mechanical: task routing, payment processing, compliance recording, SLA monitoring, and performance scoring. The remaining 20% -- strategic prioritization, relationship management, conflict resolution involving human judgment -- stays with humans.\n\nThe payback period for building what this guide describes is typically 2-3 months.\n\n---\n\n## Chapter 2: Architecture: Building a Workforce Orchestrator Agent with GreenHelix\n\n### The Orchestrator Agent Identity\n\nEvery agent in the GreenHelix ecosystem starts with an identity and a wallet. The orchestrator is no different, but its identity serves a special purpose: it is the employer of record for all agent-mediated work. It is the entity that holds escrow, receives invoices, disburses payments, and signs SLA contracts. Think of it as the LLC through which all hybrid workforce operations flow.\n\n```python\nimport requests\nimport os\nfrom datetime import datetime, timezone\n\nAPI_BASE = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\nsession = requests.Session()\nsession.headers[\"Authorization\"] = f\"Bearer {os.environ['GREENHELIX_API_KEY']}\"\n\n\ndef execute(tool: str, params: dict) -> dict:\n    \"\"\"Execute a GreenHelix tool via the unified endpoint.\"\"\"\n    resp = session.post(f\"{API_BASE}\u002Fv1\", json={\n        \"tool\": tool,\n        \"input\": params,\n    })\n    resp.raise_for_status()\n    return resp.json()\n\n\n# Step 1: Register the orchestrator agent\norchestrator = execute(\"register_agent\", {\n    \"name\": \"workforce-orchestrator-prod\",\n    \"type\": \"orchestrator\",\n    \"description\": \"Central workforce orchestrator managing hybrid human+AI teams\",\n    \"capabilities\": [\n        \"task_routing\",\n        \"payment_management\",\n        \"sla_enforcement\",\n        \"performance_scoring\",\n        \"compliance_reporting\",\n    ],\n    \"metadata\": {\n        \"version\": \"1.0.0\",\n        \"org\": \"acme-corp\",\n        \"environment\": \"production\",\n    },\n})\nORCHESTRATOR_ID = orchestrator[\"agent_id\"]\nprint(f\"Orchestrator registered: {ORCHESTRATOR_ID}\")\n\n# Step 2: Create the orchestrator's master wallet\nwallet = execute(\"create_wallet\", {\n    \"agent_id\": ORCHESTRATOR_ID,\n    \"currency\": \"USD\",\n    \"label\": \"workforce-operations\",\n    \"metadata\": {\n        \"purpose\": \"escrow_funding_and_disbursements\",\n        \"budget_period\": \"monthly\",\n    },\n})\nWALLET_ID = wallet[\"wallet_id\"]\nprint(f\"Master wallet created: {WALLET_ID}\")\n```\n\n### The Three-Layer Architecture\n\nThe orchestrator is not a monolith. It is three layers, each responsible for a distinct phase of workforce management:\n\n```\n+=====================================================================+\n|                    WORKFORCE ORCHESTRATOR AGENT                       |\n|                                                                      |\n|  Layer 1: INTAKE & ROUTING                                           |\n|  +----------------------------------------------------------------+  |\n|  |  Task Queue  -->  Classifier  -->  Capability Matcher           |  |\n|  |                                                                  |  |\n|  |  Tools: search_services, best_match, search_agents_by_metrics   |  |\n|  +----------------------------------------------------------------+  |\n|                                                                      |\n|  Layer 2: EXECUTION & PAYMENT                                        |\n|  +----------------------------------------------------------------+  |\n|  |  Assignment  -->  Escrow  -->  Verification  -->  Release       |  |\n|  |                                                                  |  |\n|  |  Tools: create_escrow, release_escrow, create_invoice, transfer |  |\n|  +----------------------------------------------------------------+  |\n|                                                                      |\n|  Layer 3: GOVERNANCE & REPUTATION                                    |\n|  +----------------------------------------------------------------+  |\n|  |  SLA Monitor  -->  Reputation  -->  Audit  -->  Compliance      |  |\n|  |                                                                  |  |\n|  |  Tools: create_sla, check_sla_compliance, submit_metrics,       |  |\n|  |         get_agent_reputation, record_transaction,                |  |\n|  |         check_compliance, build_claim_chain                      |  |\n|  +----------------------------------------------------------------+  |\n+=====================================================================+\n                              |\n                              v\n              +-------------------------------+\n              |   GreenHelix A2A Commerce     |\n              |   Gateway (128 tools)         |\n              |   the GreenHelix REST API            |\n              +-------------------------------+\n```\n\n### The Worker Registry\n\nBefore the orchestrator can assign tasks, it needs to know who is available. The worker registry is a unified data structure that abstracts the differences between human gig workers and AI agents. Both are represented as agents in the GreenHelix system -- human workers get agent identities that map to their real-world profiles.\n\n```python\nfrom dataclasses import dataclass, field\nfrom typing import List, Optional\nfrom enum import Enum\n\n\nclass WorkerType(Enum):\n    AI_AGENT = \"ai_agent\"\n    GIG_WORKER = \"gig_worker\"\n    FULL_TIME = \"full_time\"\n\n\n@dataclass\nclass WorkerProfile:\n    agent_id: str\n    worker_type: WorkerType\n    capabilities: List[str]\n    hourly_rate_usd: float\n    availability_hours: float       # hours available per week\n    reputation_score: float         # 0.0 - 1.0\n    sla_compliance_rate: float      # 0.0 - 1.0\n    active_task_count: int = 0\n    max_concurrent_tasks: int = 1\n    metadata: dict = field(default_factory=dict)\n\n    @property\n    def is_available(self) -> bool:\n        return self.active_task_count \u003C self.max_concurrent_tasks\n\n    @property\n    def utilization(self) -> float:\n        if self.max_concurrent_tasks == 0:\n            return 1.0\n        return self.active_task_count \u002F self.max_concurrent_tasks\n\n\nclass WorkerRegistry:\n    \"\"\"Unified registry for all worker types, backed by GreenHelix services.\"\"\"\n\n    def __init__(self):\n        self._workers: dict[str, WorkerProfile] = {}\n\n    def register_ai_agent(self, name: str, capabilities: List[str],\n                          cost_per_call: float) -> WorkerProfile:\n        \"\"\"Register an AI agent as a worker.\"\"\"\n        agent = execute(\"register_agent\", {\n            \"name\": name,\n            \"type\": \"worker\",\n            \"capabilities\": capabilities,\n            \"metadata\": {\"worker_type\": \"ai_agent\"},\n        })\n        agent_id = agent[\"agent_id\"]\n\n        # Create the agent's wallet\n        execute(\"create_wallet\", {\n            \"agent_id\": agent_id,\n            \"currency\": \"USD\",\n            \"label\": f\"worker-wallet-{name}\",\n        })\n\n        # Register the agent's service in the marketplace\n        execute(\"register_service\", {\n            \"agent_id\": agent_id,\n            \"name\": f\"{name}-service\",\n            \"capabilities\": capabilities,\n            \"pricing\": {\"model\": \"per_call\", \"rate_usd\": cost_per_call},\n        })\n\n        profile = WorkerProfile(\n            agent_id=agent_id,\n            worker_type=WorkerType.AI_AGENT,\n            capabilities=capabilities,\n            hourly_rate_usd=cost_per_call * 120,  # est. 120 calls\u002Fhour\n            availability_hours=168,  # 24\u002F7\n            reputation_score=0.5,    # neutral start\n            sla_compliance_rate=1.0, # no violations yet\n            max_concurrent_tasks=50, # AI agents handle parallelism\n            metadata={\"name\": name, \"cost_per_call\": cost_per_call},\n        )\n        self._workers[agent_id] = profile\n        return profile\n\n    def register_gig_worker(self, name: str, email: str,\n                            capabilities: List[str],\n                            hourly_rate: float,\n                            hours_per_week: float) -> WorkerProfile:\n        \"\"\"Register a human gig worker as an agent in the system.\"\"\"\n        agent = execute(\"register_agent\", {\n            \"name\": f\"gig-{name}\",\n            \"type\": \"worker\",\n            \"capabilities\": capabilities,\n            \"metadata\": {\n                \"worker_type\": \"gig_worker\",\n                \"email\": email,\n                \"human\": True,\n            },\n        })\n        agent_id = agent[\"agent_id\"]\n\n        # Create the worker's receiving wallet\n        execute(\"create_wallet\", {\n            \"agent_id\": agent_id,\n            \"currency\": \"USD\",\n            \"label\": f\"gig-wallet-{name}\",\n        })\n\n        # Register capabilities as a service\n        execute(\"register_service\", {\n            \"agent_id\": agent_id,\n            \"name\": f\"{name}-freelance\",\n            \"capabilities\": capabilities,\n            \"pricing\": {\"model\": \"hourly\", \"rate_usd\": hourly_rate},\n        })\n\n        profile = WorkerProfile(\n            agent_id=agent_id,\n            worker_type=WorkerType.GIG_WORKER,\n            capabilities=capabilities,\n            hourly_rate_usd=hourly_rate,\n            availability_hours=hours_per_week,\n            reputation_score=0.5,\n            sla_compliance_rate=1.0,\n            max_concurrent_tasks=3,  # humans do limited parallelism\n            metadata={\"name\": name, \"email\": email},\n        )\n        self._workers[agent_id] = profile\n        return profile\n\n    def get_available_workers(self, capability: str = None) -> List[WorkerProfile]:\n        \"\"\"Return available workers, optionally filtered by capability.\"\"\"\n        workers = [w for w in self._workers.values() if w.is_available]\n        if capability:\n            workers = [w for w in workers if capability in w.capabilities]\n        return workers\n\n    def get_worker(self, agent_id: str) -> Optional[WorkerProfile]:\n        return self._workers.get(agent_id)\n```\n\n### Bootstrapping the Team\n\nWith the registry in place, bootstrapping a hybrid team is a series of registration calls:\n\n```python\nregistry = WorkerRegistry()\n\n# Register AI agents\ncode_review_agent = registry.register_ai_agent(\n    name=\"code-review-bot\",\n    capabilities=[\"code_review\", \"static_analysis\", \"security_scan\"],\n    cost_per_call=0.02,\n)\n\ndata_pipeline_agent = registry.register_ai_agent(\n    name=\"data-pipeline-bot\",\n    capabilities=[\"etl\", \"data_validation\", \"schema_migration\"],\n    cost_per_call=0.05,\n)\n\n# Register human gig workers\nsenior_dev = registry.register_gig_worker(\n    name=\"maria-garcia\",\n    email=\"maria@freelance.dev\",\n    capabilities=[\"code_review\", \"architecture\", \"mentoring\", \"go\", \"python\"],\n    hourly_rate=150.0,\n    hours_per_week=20,\n)\n\ndata_engineer = registry.register_gig_worker(\n    name=\"james-chen\",\n    email=\"james@datawork.io\",\n    capabilities=[\"etl\", \"data_validation\", \"dbt\", \"snowflake\", \"python\"],\n    hourly_rate=125.0,\n    hours_per_week=30,\n)\n\nqa_specialist = registry.register_gig_worker(\n    name=\"priya-patel\",\n    email=\"priya@qaops.dev\",\n    capabilities=[\"testing\", \"automation\", \"selenium\", \"playwright\"],\n    hourly_rate=95.0,\n    hours_per_week=40,\n)\n\nprint(f\"Team bootstrapped: {len(registry.get_available_workers())} workers ready\")\n```\n\n### The Service Registry as a Worker Directory\n\nThe GreenHelix marketplace serves as the worker directory. Every registered worker -- human or AI -- has a service listing. This means the orchestrator can discover new workers dynamically, not just those it registered itself:\n\n```python\n# Discover all workers with ETL capabilities\navailable_etl = execute(\"search_services\", {\n    \"capability\": \"etl\",\n    \"min_reputation\": 0.6,\n    \"status\": \"active\",\n})\n\nprint(f\"Found {len(available_etl.get('services', []))} ETL-capable workers\")\nfor svc in available_etl.get(\"services\", []):\n    print(f\"  - {svc['name']}: ${svc['pricing']['rate_usd']}\u002Funit, \"\n          f\"reputation: {svc.get('reputation', 'unrated')}\")\n```\n\nThis dynamic discovery is what separates an orchestrator from a static staffing plan. When the orchestrator needs a capability that no currently registered worker provides, it searches the marketplace, evaluates candidates, and onboards them -- all without human intervention.\n\n---\n\n## Chapter 3: Agent Discovery and Capability Matching for Task Assignment\n\n### The Task Model\n\nBefore matching, you need a task representation that captures everything the orchestrator needs to make a routing decision:\n\n```python\nfrom dataclasses import dataclass, field\nfrom typing import List, Optional\nfrom enum import Enum\nimport uuid\nfrom datetime import datetime, timezone, timedelta\n\n\nclass TaskPriority(Enum):\n    CRITICAL = 1\n    HIGH = 2\n    MEDIUM = 3\n    LOW = 4\n\n\nclass TaskStatus(Enum):\n    PENDING = \"pending\"\n    ASSIGNED = \"assigned\"\n    IN_PROGRESS = \"in_progress\"\n    REVIEW = \"review\"\n    COMPLETED = \"completed\"\n    FAILED = \"failed\"\n    DISPUTED = \"disputed\"\n\n\n@dataclass\nclass Task:\n    task_id: str = field(default_factory=lambda: str(uuid.uuid4()))\n    title: str = \"\"\n    description: str = \"\"\n    required_capabilities: List[str] = field(default_factory=list)\n    preferred_worker_type: Optional[WorkerType] = None\n    priority: TaskPriority = TaskPriority.MEDIUM\n    budget_usd: float = 0.0\n    deadline: Optional[datetime] = None\n    status: TaskStatus = TaskStatus.PENDING\n    assigned_worker_id: Optional[str] = None\n    escrow_id: Optional[str] = None\n    quality_threshold: float = 0.8  # minimum acceptable quality score\n    metadata: dict = field(default_factory=dict)\n```\n\n### Multi-Signal Capability Matching\n\nMatching a task to a worker is not a keyword lookup. It is a multi-signal scoring function that balances capability fit, cost efficiency, reputation, availability, and worker type preference. The orchestrator uses GreenHelix's `best_match` and `search_services` tools as the foundation, then applies its own scoring layer on top.\n\n```\nTASK: \"Review Python microservice PR, check for SQL injection\"\n                    |\n                    v\n    +-------------------------------+\n    |   CAPABILITY EXTRACTION       |\n    |   Required: [code_review,     |\n    |   python, security_scan]      |\n    +---------------+---------------+\n                    |\n        +-----------+-----------+\n        |                       |\n        v                       v\n+---------------+     +------------------+\n| search_       |     | search_agents_   |\n| services      |     | by_metrics       |\n| (capability   |     | (reputation >    |\n|  match)       |     |  0.7, skill:     |\n|               |     |  code_review)    |\n+-------+-------+     +--------+---------+\n        |                       |\n        v                       v\n    +-------------------------------+\n    |   CANDIDATE POOL MERGE       |\n    |   Deduplicate by agent_id    |\n    +---------------+---------------+\n                    |\n                    v\n    +-------------------------------+\n    |   MULTI-SIGNAL SCORING        |\n    |                               |\n    |   capability_score * 0.30     |\n    |   + reputation_score * 0.25   |\n    |   + cost_score * 0.20         |\n    |   + availability_score * 0.15 |\n    |   + sla_score * 0.10          |\n    +---------------+---------------+\n                    |\n                    v\n    +-------------------------------+\n    |   RANKED CANDIDATES            |\n    |   1. code-review-bot  (0.91)  |\n    |   2. maria-garcia     (0.87)  |\n    |   3. ext-reviewer-42  (0.72)  |\n    +-------------------------------+\n```\n\n### The Scoring Engine\n\n```python\nfrom typing import List, Tuple\n\n\nclass CapabilityMatcher:\n    \"\"\"Multi-signal scoring engine for task-to-worker matching.\"\"\"\n\n    # Weight vector -- tune based on organizational priorities\n    WEIGHTS = {\n        \"capability\": 0.30,\n        \"reputation\": 0.25,\n        \"cost\": 0.20,\n        \"availability\": 0.15,\n        \"sla_compliance\": 0.10,\n    }\n\n    def __init__(self, registry: WorkerRegistry, orchestrator_id: str):\n        self.registry = registry\n        self.orchestrator_id = orchestrator_id\n\n    def find_candidates(self, task: Task) -> List[WorkerProfile]:\n        \"\"\"Discover candidate workers from registry + marketplace.\"\"\"\n        candidates = []\n\n        # Source 1: Local registry\n        for cap in task.required_capabilities:\n            candidates.extend(self.registry.get_available_workers(cap))\n\n        # Source 2: GreenHelix marketplace search\n        for cap in task.required_capabilities:\n            results = execute(\"search_services\", {\n                \"capability\": cap,\n                \"status\": \"active\",\n            })\n            for svc in results.get(\"services\", []):\n                worker = self.registry.get_worker(svc[\"agent_id\"])\n                if worker and worker.is_available:\n                    candidates.append(worker)\n\n        # Source 3: Metrics-based search for high-rep workers\n        metrics_results = execute(\"search_agents_by_metrics\", {\n            \"min_reputation\": 0.7,\n            \"capabilities\": task.required_capabilities,\n        })\n        for agent_info in metrics_results.get(\"agents\", []):\n            worker = self.registry.get_worker(agent_info[\"agent_id\"])\n            if worker and worker.is_available:\n                candidates.append(worker)\n\n        # Deduplicate by agent_id\n        seen = set()\n        unique = []\n        for c in candidates:\n            if c.agent_id not in seen:\n                seen.add(c.agent_id)\n                unique.append(c)\n\n        return unique\n\n    def score_candidate(self, task: Task,\n                        worker: WorkerProfile) -> float:\n        \"\"\"Compute composite score for a worker-task pair.\"\"\"\n\n        # Capability score: fraction of required capabilities the worker has\n        if not task.required_capabilities:\n            cap_score = 1.0\n        else:\n            matched = sum(1 for c in task.required_capabilities\n                          if c in worker.capabilities)\n            cap_score = matched \u002F len(task.required_capabilities)\n\n        # Reputation score: direct from worker profile\n        rep_score = worker.reputation_score\n\n        # Cost score: inverse -- cheaper is better, normalized to 0-1\n        # Assume budget is the max; score = 1.0 if free, 0.0 if at budget\n        if task.budget_usd > 0:\n            estimated_cost = self._estimate_task_cost(task, worker)\n            cost_score = max(0.0, 1.0 - (estimated_cost \u002F task.budget_usd))\n        else:\n            cost_score = 0.5  # neutral if no budget specified\n\n        # Availability score: inverse utilization\n        avail_score = 1.0 - worker.utilization\n\n        # SLA compliance score\n        sla_score = worker.sla_compliance_rate\n\n        # Worker type preference bonus\n        type_bonus = 0.0\n        if task.preferred_worker_type and worker.worker_type == task.preferred_worker_type:\n            type_bonus = 0.05  # small bonus for matching preference\n\n        composite = (\n            self.WEIGHTS[\"capability\"] * cap_score\n            + self.WEIGHTS[\"reputation\"] * rep_score\n            + self.WEIGHTS[\"cost\"] * cost_score\n            + self.WEIGHTS[\"availability\"] * avail_score\n            + self.WEIGHTS[\"sla_compliance\"] * sla_score\n            + type_bonus\n        )\n        return round(min(composite, 1.0), 4)\n\n    def _estimate_task_cost(self, task: Task,\n                            worker: WorkerProfile) -> float:\n        \"\"\"Estimate cost based on worker type and task parameters.\"\"\"\n        if worker.worker_type == WorkerType.AI_AGENT:\n            # Estimate based on expected number of tool calls\n            est_calls = task.metadata.get(\"estimated_calls\", 10)\n            return worker.metadata.get(\"cost_per_call\", 0.05) * est_calls\n        else:\n            # Estimate based on expected hours\n            est_hours = task.metadata.get(\"estimated_hours\", 2.0)\n            return worker.hourly_rate_usd * est_hours\n\n    def match(self, task: Task, top_n: int = 5) -> List[Tuple[WorkerProfile, float]]:\n        \"\"\"Return top-N ranked candidates for a task.\"\"\"\n        candidates = self.find_candidates(task)\n        scored = [(w, self.score_candidate(task, w)) for w in candidates]\n        scored.sort(key=lambda x: x[1], reverse=True)\n        return scored[:top_n]\n```\n\n### Using GreenHelix best_match for Shortlisting\n\nThe `best_match` tool provides a server-side shortlist that considers factors the orchestrator may not have locally -- global marketplace reputation, recent transaction volume, verified credentials. Use it as a pre-filter before applying your custom scoring:\n\n```python\ndef shortlist_with_best_match(task: Task) -> list:\n    \"\"\"Use GreenHelix best_match to get server-side shortlist.\"\"\"\n    result = execute(\"best_match\", {\n        \"requirements\": {\n            \"capabilities\": task.required_capabilities,\n            \"max_budget_usd\": task.budget_usd,\n            \"min_reputation\": task.quality_threshold,\n        },\n    })\n    return result.get(\"matches\", [])\n\n\n# Example: find the best worker for a code review task\nreview_task = Task(\n    title=\"Review authentication module PR\",\n    description=\"Security-focused review of OAuth2 implementation\",\n    required_capabilities=[\"code_review\", \"python\", \"security_scan\"],\n    budget_usd=200.0,\n    deadline=datetime.now(timezone.utc) + timedelta(hours=4),\n    priority=TaskPriority.HIGH,\n    metadata={\"estimated_hours\": 1.5, \"estimated_calls\": 25},\n)\n\n# Server-side shortlist\nshortlist = shortlist_with_best_match(review_task)\n\n# Local scoring with full context\nmatcher = CapabilityMatcher(registry, ORCHESTRATOR_ID)\nranked = matcher.match(review_task, top_n=3)\n\nfor worker, score in ranked:\n    print(f\"  {worker.metadata.get('name', worker.agent_id)}: \"\n          f\"score={score}, type={worker.worker_type.value}, \"\n          f\"rate=${worker.hourly_rate_usd}\u002Fhr\")\n```\n\n### Routing Decisions: When to Use Humans vs. Agents\n\nNot every task should go to the highest-scoring worker. The orchestrator needs routing rules that encode organizational policy:\n\n```python\nclass TaskRouter:\n    \"\"\"Policy-based routing on top of capability matching.\"\"\"\n\n    # Tasks that MUST go to humans regardless of agent scores\n    HUMAN_REQUIRED = {\n        \"client_communication\",\n        \"contract_negotiation\",\n        \"hiring_decision\",\n        \"legal_review\",\n        \"strategic_planning\",\n    }\n\n    # Tasks where agents are preferred for speed\u002Fcost\n    AGENT_PREFERRED = {\n        \"code_review\",\n        \"static_analysis\",\n        \"data_validation\",\n        \"etl\",\n        \"schema_migration\",\n        \"security_scan\",\n        \"test_generation\",\n        \"log_analysis\",\n    }\n\n    def route(self, task: Task,\n              ranked: List[Tuple[WorkerProfile, float]]) -> WorkerProfile:\n        \"\"\"Apply routing policy to select final worker.\"\"\"\n\n        # Rule 1: Human-required tasks filter out AI agents\n        if any(cap in self.HUMAN_REQUIRED\n               for cap in task.required_capabilities):\n            humans = [(w, s) for w, s in ranked\n                      if w.worker_type != WorkerType.AI_AGENT]\n            if humans:\n                return humans[0][0]\n            raise ValueError(\n                f\"Task {task.task_id} requires human worker \"\n                f\"but none available\"\n            )\n\n        # Rule 2: Cost gate -- if budget is tight, prefer agents\n        if task.budget_usd > 0 and task.budget_usd \u003C 50:\n            agents = [(w, s) for w, s in ranked\n                      if w.worker_type == WorkerType.AI_AGENT]\n            if agents:\n                return agents[0][0]\n\n        # Rule 3: Quality gate -- if quality threshold is very high,\n        # prefer humans for subjective tasks\n        if task.quality_threshold > 0.95:\n            humans = [(w, s) for w, s in ranked\n                      if w.worker_type != WorkerType.AI_AGENT]\n            if humans and humans[0][1] > 0.7:\n                return humans[0][0]\n\n        # Default: highest composite score wins\n        return ranked[0][0]\n```\n\n### Task Assignment Execution\n\nOnce the router selects a worker, the orchestrator formalizes the assignment:\n\n```python\ndef assign_task(task: Task, worker: WorkerProfile) -> dict:\n    \"\"\"Assign a task to a worker and notify via GreenHelix messaging.\"\"\"\n    task.assigned_worker_id = worker.agent_id\n    task.status = TaskStatus.ASSIGNED\n    worker.active_task_count += 1\n\n    # Record the assignment as a transaction for audit\n    execute(\"record_transaction\", {\n        \"agent_id\": ORCHESTRATOR_ID,\n        \"type\": \"task_assignment\",\n        \"counterparty_id\": worker.agent_id,\n        \"metadata\": {\n            \"task_id\": task.task_id,\n            \"task_title\": task.title,\n            \"worker_type\": worker.worker_type.value,\n            \"estimated_cost_usd\": str(task.budget_usd),\n            \"deadline\": task.deadline.isoformat() if task.deadline else None,\n        },\n    })\n\n    # Notify the worker\n    execute(\"send_message\", {\n        \"from_agent_id\": ORCHESTRATOR_ID,\n        \"to_agent_id\": worker.agent_id,\n        \"subject\": f\"Task Assignment: {task.title}\",\n        \"body\": (\n            f\"You have been assigned task {task.task_id}.\\n\"\n            f\"Description: {task.description}\\n\"\n            f\"Budget: ${task.budget_usd}\\n\"\n            f\"Deadline: {task.deadline}\\n\"\n            f\"Required capabilities: {', '.join(task.required_capabilities)}\"\n        ),\n        \"priority\": task.priority.name.lower(),\n    })\n\n    return {\n        \"task_id\": task.task_id,\n        \"assigned_to\": worker.agent_id,\n        \"worker_type\": worker.worker_type.value,\n        \"worker_name\": worker.metadata.get(\"name\", \"unknown\"),\n    }\n```\n\n---\n\n## Chapter 4: Escrow-Based Payment Flows for Hybrid Teams\n\n### Why Escrow Is Non-Negotiable for Hybrid Teams\n\nIn a traditional freelance platform, escrow is a convenience. In an agent-orchestrated hybrid workforce, escrow is structural. Here is why: the orchestrator is an AI agent disbursing your organization's money to other AI agents and human workers. There is no human approving each payment in real time. The escrow mechanism is the programmatic equivalent of the CFO's signature -- it ensures funds are committed before work begins and released only when work is verified.\n\nThe payment challenge for hybrid teams is that different worker types have different payment expectations:\n\n| Worker Type | Payment Model | Typical Cadence | Verification Method |\n|-------------|---------------|-----------------|---------------------|\n| AI Agent | Per-call or per-task | Immediate on completion | Automated acceptance test |\n| Gig Worker | Hourly or milestone | Weekly or per-milestone | Human review + automated checks |\n| Full-time | Salary (out of scope) | Biweekly payroll | HR system |\n\nGreenHelix's `create_escrow` unifies these. The escrow holds funds from the orchestrator's wallet and releases them to the worker's wallet upon verified completion -- regardless of whether the worker is human or AI.\n\n### The Payment Flow\n\n```\nORCHESTRATOR                    GREENHELIX                    WORKER\n    |                               |                           |\n    |  1. create_escrow             |                           |\n    |  (task_id, amount, worker)    |                           |\n    |------------------------------>|                           |\n    |                               |  Funds locked from        |\n    |                               |  orchestrator wallet      |\n    |       escrow_id               |                           |\n    |\u003C------------------------------|                           |\n    |                               |                           |\n    |  2. send_message              |                           |\n    |  (work_started)               |  3. Notification          |\n    |------------------------------>|-------------------------->|\n    |                               |                           |\n    |                               |  4. Work performed        |\n    |                               |     (hours\u002Fcalls\u002Ftasks)   |\n    |                               |                           |\n    |  5. Deliverable submitted     |                           |\n    |\u003C------------------------------|\u003C--------------------------|\n    |                               |                           |\n    |  6. Verification              |                           |\n    |  (auto or human review)       |                           |\n    |                               |                           |\n    |  7a. release_escrow           |                           |\n    |  (full or partial)            |                           |\n    |------------------------------>|  Funds transferred to     |\n    |                               |  worker wallet            |\n    |                               |-------------------------->|\n    |                               |                           |\n    | OR                            |                           |\n    |                               |                           |\n    |  7b. open_dispute             |                           |\n    |  (quality_issue)              |                           |\n    |------------------------------>|  Funds held pending       |\n    |                               |  resolution               |\n```\n\n### Creating Escrow for AI Agents\n\nAI agent payments are typically per-task with immediate release on automated verification:\n\n```python\ndef create_agent_escrow(task: Task, worker: WorkerProfile) -> str:\n    \"\"\"Create escrow for an AI agent task.\"\"\"\n    estimated_cost = worker.metadata.get(\"cost_per_call\", 0.05) * \\\n        task.metadata.get(\"estimated_calls\", 10)\n\n    # Add 20% buffer for retry\u002Foverflow\n    escrow_amount = round(estimated_cost * 1.2, 2)\n\n    result = execute(\"create_escrow\", {\n        \"payer_agent_id\": ORCHESTRATOR_ID,\n        \"payee_agent_id\": worker.agent_id,\n        \"amount_usd\": str(escrow_amount),\n        \"currency\": \"USD\",\n        \"conditions\": {\n            \"release_on\": \"task_completion\",\n            \"task_id\": task.task_id,\n            \"auto_release\": True,\n            \"timeout_hours\": 1,  # auto-refund if not completed in 1 hour\n        },\n        \"metadata\": {\n            \"task_title\": task.title,\n            \"worker_type\": \"ai_agent\",\n            \"estimated_calls\": task.metadata.get(\"estimated_calls\", 10),\n        },\n    })\n\n    task.escrow_id = result[\"escrow_id\"]\n    return result[\"escrow_id\"]\n```\n\n### Creating Escrow for Human Gig Workers\n\nHuman worker payments use milestone-based escrow with manual or semi-automated verification:\n\n```python\ndef create_gig_worker_escrow(task: Task, worker: WorkerProfile,\n                              milestones: list) -> str:\n    \"\"\"Create milestone-based escrow for a human gig worker.\n\n    milestones: [\n        {\"name\": \"Design review complete\", \"amount_usd\": 150},\n        {\"name\": \"Implementation done\", \"amount_usd\": 300},\n        {\"name\": \"Tests passing\", \"amount_usd\": 150},\n    ]\n    \"\"\"\n    total = sum(m[\"amount_usd\"] for m in milestones)\n\n    result = execute(\"create_escrow\", {\n        \"payer_agent_id\": ORCHESTRATOR_ID,\n        \"payee_agent_id\": worker.agent_id,\n        \"amount_usd\": str(total),\n        \"currency\": \"USD\",\n        \"conditions\": {\n            \"release_on\": \"milestone_completion\",\n            \"task_id\": task.task_id,\n            \"milestones\": milestones,\n            \"auto_release\": False,  # requires explicit release\n            \"timeout_hours\": 168,   # 1 week timeout\n        },\n        \"metadata\": {\n            \"task_title\": task.title,\n            \"worker_type\": \"gig_worker\",\n            \"worker_name\": worker.metadata.get(\"name\"),\n            \"worker_email\": worker.metadata.get(\"email\"),\n            \"milestone_count\": len(milestones),\n        },\n    })\n\n    task.escrow_id = result[\"escrow_id\"]\n    return result[\"escrow_id\"]\n```\n\n### Milestone Release and Partial Payments\n\n```python\ndef release_milestone(task: Task, milestone_name: str,\n                      amount_usd: float) -> dict:\n    \"\"\"Release a specific milestone payment from escrow.\"\"\"\n    result = execute(\"release_escrow\", {\n        \"escrow_id\": task.escrow_id,\n        \"amount_usd\": str(amount_usd),\n        \"release_type\": \"partial\",\n        \"reason\": f\"Milestone completed: {milestone_name}\",\n        \"metadata\": {\n            \"task_id\": task.task_id,\n            \"milestone\": milestone_name,\n        },\n    })\n\n    # Record the payment as a transaction\n    execute(\"record_transaction\", {\n        \"agent_id\": ORCHESTRATOR_ID,\n        \"type\": \"milestone_payment\",\n        \"counterparty_id\": task.assigned_worker_id,\n        \"amount_usd\": str(amount_usd),\n        \"metadata\": {\n            \"task_id\": task.task_id,\n            \"milestone\": milestone_name,\n            \"escrow_id\": task.escrow_id,\n        },\n    })\n\n    return result\n\n\ndef release_full(task: Task) -> dict:\n    \"\"\"Release full remaining escrow balance on task completion.\"\"\"\n    result = execute(\"release_escrow\", {\n        \"escrow_id\": task.escrow_id,\n        \"release_type\": \"full\",\n        \"reason\": f\"Task completed: {task.title}\",\n        \"metadata\": {\"task_id\": task.task_id},\n    })\n\n    # Record the final payment\n    execute(\"record_transaction\", {\n        \"agent_id\": ORCHESTRATOR_ID,\n        \"type\": \"task_payment\",\n        \"counterparty_id\": task.assigned_worker_id,\n        \"amount_usd\": result.get(\"released_amount\", \"0\"),\n        \"metadata\": {\n            \"task_id\": task.task_id,\n            \"escrow_id\": task.escrow_id,\n            \"payment_type\": \"completion\",\n        },\n    })\n\n    return result\n```\n\n### Invoice Generation for Gig Workers\n\nHuman gig workers often need invoices for their own tax and accounting purposes. The orchestrator generates these automatically:\n\n```python\ndef generate_worker_invoice(task: Task, worker: WorkerProfile,\n                            amount_usd: float,\n                            line_items: list) -> dict:\n    \"\"\"Generate an invoice for a completed gig worker engagement.\"\"\"\n    result = execute(\"create_invoice\", {\n        \"issuer_agent_id\": worker.agent_id,\n        \"recipient_agent_id\": ORCHESTRATOR_ID,\n        \"amount_usd\": str(amount_usd),\n        \"currency\": \"USD\",\n        \"line_items\": line_items,\n        \"metadata\": {\n            \"task_id\": task.task_id,\n            \"task_title\": task.title,\n            \"worker_name\": worker.metadata.get(\"name\"),\n            \"worker_email\": worker.metadata.get(\"email\"),\n            \"worker_type\": \"gig_worker\",\n            \"payment_terms\": \"net_0\",  # already paid via escrow\n            \"escrow_id\": task.escrow_id,\n        },\n    })\n    return result\n\n\n# Example: generate invoice for Maria's code review\ninvoice = generate_worker_invoice(\n    task=review_task,\n    worker=senior_dev,\n    amount_usd=225.0,\n    line_items=[\n        {\"description\": \"Security code review - OAuth2 module\",\n         \"hours\": 1.5, \"rate\": 150.0, \"amount\": 225.0},\n    ],\n)\nprint(f\"Invoice created: {invoice.get('invoice_id')}\")\n```\n\n### The Unified Payment Processor\n\nBringing it together, the orchestrator needs a single method that handles payment for any worker type:\n\n```python\nclass PaymentProcessor:\n    \"\"\"Unified payment processing for all worker types.\"\"\"\n\n    def __init__(self, orchestrator_id: str):\n        self.orchestrator_id = orchestrator_id\n\n    def create_payment(self, task: Task, worker: WorkerProfile,\n                       milestones: list = None) -> str:\n        \"\"\"Create appropriate payment structure based on worker type.\"\"\"\n        if worker.worker_type == WorkerType.AI_AGENT:\n            return create_agent_escrow(task, worker)\n        elif worker.worker_type == WorkerType.GIG_WORKER:\n            if milestones is None:\n                milestones = [{\n                    \"name\": \"Task completion\",\n                    \"amount_usd\": task.budget_usd,\n                }]\n            return create_gig_worker_escrow(task, worker, milestones)\n        else:\n            raise ValueError(\n                f\"Full-time employee payments handled via payroll, \"\n                f\"not orchestrator\"\n            )\n\n    def process_completion(self, task: Task, worker: WorkerProfile,\n                           quality_score: float) -> dict:\n        \"\"\"Process task completion: release escrow, generate invoice.\"\"\"\n        if quality_score \u003C task.quality_threshold:\n            # Quality below threshold -- do not auto-release\n            return self._handle_quality_failure(task, worker, quality_score)\n\n        # Release full escrow\n        release_result = release_full(task)\n\n        # Generate invoice for gig workers\n        if worker.worker_type == WorkerType.GIG_WORKER:\n            generate_worker_invoice(\n                task, worker,\n                amount_usd=float(release_result.get(\"released_amount\", 0)),\n                line_items=[{\n                    \"description\": task.title,\n                    \"amount\": float(release_result.get(\"released_amount\", 0)),\n                }],\n            )\n\n        task.status = TaskStatus.COMPLETED\n        worker.active_task_count -= 1\n        return release_result\n\n    def _handle_quality_failure(self, task: Task, worker: WorkerProfile,\n                                quality_score: float) -> dict:\n        \"\"\"Handle work that does not meet quality threshold.\"\"\"\n        task.status = TaskStatus.DISPUTED\n\n        result = execute(\"open_dispute\", {\n            \"escrow_id\": task.escrow_id,\n            \"disputer_agent_id\": self.orchestrator_id,\n            \"reason\": \"quality_below_threshold\",\n            \"details\": {\n                \"task_id\": task.task_id,\n                \"quality_score\": quality_score,\n                \"threshold\": task.quality_threshold,\n                \"worker_id\": worker.agent_id,\n                \"worker_type\": worker.worker_type.value,\n            },\n        })\n\n        # Notify the worker about the quality issue\n        execute(\"send_message\", {\n            \"from_agent_id\": self.orchestrator_id,\n            \"to_agent_id\": worker.agent_id,\n            \"subject\": f\"Quality Issue: {task.title}\",\n            \"body\": (\n                f\"Task {task.task_id} quality score ({quality_score}) is below \"\n                f\"the required threshold ({task.quality_threshold}). \"\n                f\"A dispute has been opened. Please review and resubmit or \"\n                f\"respond to the dispute.\"\n            ),\n            \"priority\": \"high\",\n        })\n\n        return result\n```\n\n---\n\n## Chapter 5: Reputation Scoring and Performance Verification Across Worker Types\n\n### The Unified Scoring Problem\n\nThe hardest problem in hybrid workforce management is comparing apples to oranges. An AI agent that completes a code review in 12 seconds with 94% accuracy is not directly comparable to a human developer who takes 90 minutes but catches a subtle architectural flaw the agent missed. Yet the orchestrator needs a single reputation score to make routing decisions.\n\nThe solution is not a single metric. It is a composite score built from multiple dimensions, weighted differently for different task types:\n\n```\nUNIFIED REPUTATION SCORE (0.0 - 1.0)\n    |\n    +-- Quality Score (0.0 - 1.0)\n    |     Weight: 0.35\n    |     AI: automated acceptance tests\n    |     Human: peer review + automated checks\n    |\n    +-- Reliability Score (0.0 - 1.0)\n    |     Weight: 0.25\n    |     AI: uptime, error rate\n    |     Human: deadline adherence, response time\n    |\n    +-- Cost Efficiency (0.0 - 1.0)\n    |     Weight: 0.20\n    |     AI: actual vs. estimated cost\n    |     Human: actual vs. estimated hours\n    |\n    +-- SLA Compliance (0.0 - 1.0)\n    |     Weight: 0.15\n    |     Both: check_sla_compliance results\n    |\n    +-- Claim Verification (0.0 - 1.0)\n          Weight: 0.05\n          Both: build_claim_chain verification status\n```\n\n### Submitting Performance Metrics\n\nAfter every task completion, the orchestrator submits metrics for the worker:\n\n```python\ndef submit_worker_metrics(task: Task, worker: WorkerProfile,\n                          quality_score: float,\n                          actual_duration_hours: float,\n                          actual_cost_usd: float) -> dict:\n    \"\"\"Submit performance metrics for a completed task.\"\"\"\n\n    # Calculate derived metrics\n    estimated_hours = task.metadata.get(\"estimated_hours\", 1.0)\n    estimated_cost = task.budget_usd\n    time_efficiency = min(1.0, estimated_hours \u002F max(actual_duration_hours, 0.01))\n    cost_efficiency = min(1.0, estimated_cost \u002F max(actual_cost_usd, 0.01))\n\n    metrics = {\n        \"quality\": quality_score,\n        \"time_efficiency\": round(time_efficiency, 4),\n        \"cost_efficiency\": round(cost_efficiency, 4),\n        \"task_type\": task.required_capabilities[0] if task.required_capabilities else \"general\",\n        \"worker_type\": worker.worker_type.value,\n        \"task_id\": task.task_id,\n    }\n\n    result = execute(\"submit_metrics\", {\n        \"agent_id\": worker.agent_id,\n        \"metrics\": metrics,\n        \"period\": datetime.now(timezone.utc).strftime(\"%Y-%m\"),\n    })\n\n    return result\n```\n\n### Querying Reputation\n\nThe orchestrator regularly refreshes reputation data for all registered workers:\n\n```python\ndef refresh_worker_reputation(worker: WorkerProfile) -> float:\n    \"\"\"Fetch latest reputation score from GreenHelix.\"\"\"\n    result = execute(\"get_agent_reputation\", {\n        \"agent_id\": worker.agent_id,\n    })\n\n    reputation = result.get(\"reputation_score\", 0.5)\n    worker.reputation_score = reputation\n\n    # Also check SLA compliance\n    sla_result = execute(\"check_sla_compliance\", {\n        \"agent_id\": worker.agent_id,\n    })\n    worker.sla_compliance_rate = sla_result.get(\"compliance_rate\", 1.0)\n\n    return reputation\n\n\ndef refresh_all_reputations(registry: WorkerRegistry) -> dict:\n    \"\"\"Bulk refresh reputation scores for all workers.\"\"\"\n    results = {}\n    for agent_id, worker in registry._workers.items():\n        score = refresh_worker_reputation(worker)\n        results[agent_id] = {\n            \"name\": worker.metadata.get(\"name\", agent_id),\n            \"type\": worker.worker_type.value,\n            \"reputation\": score,\n            \"sla_compliance\": worker.sla_compliance_rate,\n        }\n    return results\n```\n\n### Building Claim Chains for Verified Credentials\n\nReputation scores are self-reported metrics. Claim chains add cryptographic verification -- a worker can prove they completed specific tasks, hold certain certifications, or have endorsements from other agents:\n\n```python\ndef build_worker_claim_chain(worker: WorkerProfile,\n                              claims: list) -> dict:\n    \"\"\"Build a verifiable claim chain for a worker.\n\n    claims: [\n        {\"type\": \"certification\", \"value\": \"aws_solutions_architect\",\n         \"issued_by\": \"aws-verification-agent\"},\n        {\"type\": \"task_completion\", \"value\": \"task-uuid-123\",\n         \"issued_by\": \"workforce-orchestrator-prod\"},\n        {\"type\": \"endorsement\", \"value\": \"senior_python_developer\",\n         \"issued_by\": \"tech-lead-agent-456\"},\n    ]\n    \"\"\"\n    result = execute(\"build_claim_chain\", {\n        \"agent_id\": worker.agent_id,\n        \"claims\": claims,\n        \"metadata\": {\n            \"chain_type\": \"workforce_credentials\",\n            \"worker_type\": worker.worker_type.value,\n            \"built_by\": ORCHESTRATOR_ID,\n            \"timestamp\": datetime.now(timezone.utc).isoformat(),\n        },\n    })\n    return result\n\n\n# Example: after a gig worker completes a task, add it to their chain\ndef record_task_completion_claim(task: Task, worker: WorkerProfile,\n                                  quality_score: float) -> dict:\n    \"\"\"Add a verified task completion claim to a worker's chain.\"\"\"\n    return build_worker_claim_chain(worker, [{\n        \"type\": \"task_completion\",\n        \"value\": task.task_id,\n        \"issued_by\": ORCHESTRATOR_ID,\n        \"metadata\": {\n            \"task_title\": task.title,\n            \"quality_score\": quality_score,\n            \"capabilities_demonstrated\": task.required_capabilities,\n            \"completion_date\": datetime.now(timezone.utc).isoformat(),\n        },\n    }])\n```\n\n### The Performance Dashboard\n\nThe orchestrator maintains a real-time view of workforce performance:\n\n```python\ndef generate_workforce_dashboard(registry: WorkerRegistry) -> dict:\n    \"\"\"Generate a workforce performance summary.\"\"\"\n    workers = list(registry._workers.values())\n\n    ai_agents = [w for w in workers if w.worker_type == WorkerType.AI_AGENT]\n    gig_workers = [w for w in workers if w.worker_type == WorkerType.GIG_WORKER]\n\n    def avg(values):\n        return round(sum(values) \u002F len(values), 3) if values else 0.0\n\n    dashboard = {\n        \"total_workers\": len(workers),\n        \"ai_agents\": {\n            \"count\": len(ai_agents),\n            \"avg_reputation\": avg([w.reputation_score for w in ai_agents]),\n            \"avg_utilization\": avg([w.utilization for w in ai_agents]),\n            \"avg_sla_compliance\": avg([w.sla_compliance_rate for w in ai_agents]),\n        },\n        \"gig_workers\": {\n            \"count\": len(gig_workers),\n            \"avg_reputation\": avg([w.reputation_score for w in gig_workers]),\n            \"avg_utilization\": avg([w.utilization for w in gig_workers]),\n            \"avg_sla_compliance\": avg([w.sla_compliance_rate for w in gig_workers]),\n            \"avg_hourly_rate\": avg([w.hourly_rate_usd for w in gig_workers]),\n        },\n        \"available_now\": len([w for w in workers if w.is_available]),\n        \"at_capacity\": len([w for w in workers if not w.is_available]),\n    }\n\n    return dashboard\n```\n\n### Worker Type Performance Comparison\n\nThe orchestrator should periodically analyze whether tasks are being routed to the optimal worker type. This is how you discover that your AI agents handle data validation at 98% quality for $0.50 per task while your human workers do the same at 99.2% quality for $45 per task -- and then decide whether that 1.2% quality delta justifies the 90x cost difference:\n\n```python\ndef compare_worker_type_performance(task_type: str) -> dict:\n    \"\"\"Compare AI agent vs. gig worker performance for a task type.\"\"\"\n    # Get all agents who have performed this task type\n    ai_metrics = execute(\"search_agents_by_metrics\", {\n        \"capabilities\": [task_type],\n        \"metadata_filter\": {\"worker_type\": \"ai_agent\"},\n    })\n\n    human_metrics = execute(\"search_agents_by_metrics\", {\n        \"capabilities\": [task_type],\n        \"metadata_filter\": {\"worker_type\": \"gig_worker\"},\n    })\n\n    return {\n        \"task_type\": task_type,\n        \"ai_agents\": {\n            \"sample_size\": len(ai_metrics.get(\"agents\", [])),\n            \"avg_quality\": _avg_metric(ai_metrics, \"quality\"),\n            \"avg_cost_per_task\": _avg_metric(ai_metrics, \"cost_per_task\"),\n            \"avg_duration_hours\": _avg_metric(ai_metrics, \"avg_duration\"),\n        },\n        \"gig_workers\": {\n            \"sample_size\": len(human_metrics.get(\"agents\", [])),\n            \"avg_quality\": _avg_metric(human_metrics, \"quality\"),\n            \"avg_cost_per_task\": _avg_metric(human_metrics, \"cost_per_task\"),\n            \"avg_duration_hours\": _avg_metric(human_metrics, \"avg_duration\"),\n        },\n    }\n\n\ndef _avg_metric(results: dict, metric_key: str) -> float:\n    agents = results.get(\"agents\", [])\n    values = [a.get(\"metrics\", {}).get(metric_key, 0) for a in agents]\n    return round(sum(values) \u002F len(values), 4) if values else 0.0\n```\n\n---\n\n## Chapter 6: Budget Caps, SLA Enforcement, and Automated Dispute Resolution\n\n### The Budget Control Framework\n\nAn orchestrator without budget controls is a financial risk. When the orchestrator can autonomously create escrows and release payments, there must be programmatic spending limits at every level:\n\n```\nBUDGET HIERARCHY\n================\n\nOrganization Budget ($500K\u002Fquarter)\n    |\n    +-- Department Budget ($120K\u002Fquarter)\n    |       |\n    |       +-- Project Budget ($30K\u002Fmonth)\n    |       |       |\n    |       |       +-- Task Budget ($200\u002Ftask max)\n    |       |       +-- Worker Budget ($5K\u002Fmonth per worker)\n    |       |       +-- AI Agent Budget ($2K\u002Fmonth per agent)\n    |       |\n    |       +-- Project Budget ($25K\u002Fmonth)\n    |               |\n    |               +-- ...\n    |\n    +-- Department Budget ($80K\u002Fquarter)\n            |\n            +-- ...\n```\n\n```python\nfrom dataclasses import dataclass\nfrom typing import Dict\n\n\n@dataclass\nclass BudgetConfig:\n    max_per_task_usd: float = 500.0\n    max_per_worker_monthly_usd: float = 10000.0\n    max_per_agent_monthly_usd: float = 3000.0\n    max_project_monthly_usd: float = 50000.0\n    max_single_escrow_usd: float = 1000.0\n    alert_threshold_pct: float = 80.0  # alert at 80% budget consumed\n\n\nclass BudgetController:\n    \"\"\"Enforce spending limits across the workforce.\"\"\"\n\n    def __init__(self, config: BudgetConfig):\n        self.config = config\n        self._spent: Dict[str, float] = {}  # key -> amount spent\n\n    def _key(self, *parts: str) -> str:\n        return \":\".join(parts)\n\n    def record_spend(self, worker_id: str, project_id: str,\n                     amount_usd: float):\n        \"\"\"Record a spend event and check limits.\"\"\"\n        month = datetime.now(timezone.utc).strftime(\"%Y-%m\")\n\n        keys = [\n            self._key(\"worker\", worker_id, month),\n            self._key(\"project\", project_id, month),\n            self._key(\"total\", month),\n        ]\n\n        for key in keys:\n            self._spent[key] = self._spent.get(key, 0) + amount_usd\n\n    def check_budget(self, worker: WorkerProfile, project_id: str,\n                     proposed_amount: float) -> dict:\n        \"\"\"Check if a proposed spend is within budget limits.\"\"\"\n        month = datetime.now(timezone.utc).strftime(\"%Y-%m\")\n        violations = []\n\n        # Check per-task limit\n        if proposed_amount > self.config.max_per_task_usd:\n            violations.append(\n                f\"Task amount ${proposed_amount} exceeds \"\n                f\"per-task limit ${self.config.max_per_task_usd}\"\n            )\n\n        # Check per-escrow limit\n        if proposed_amount > self.config.max_single_escrow_usd:\n            violations.append(\n                f\"Escrow amount ${proposed_amount} exceeds \"\n                f\"single escrow limit ${self.config.max_single_escrow_usd}\"\n            )\n\n        # Check per-worker monthly limit\n        worker_key = self._key(\"worker\", worker.agent_id, month)\n        worker_spent = self._spent.get(worker_key, 0)\n        limit = (self.config.max_per_agent_monthly_usd\n                 if worker.worker_type == WorkerType.AI_AGENT\n                 else self.config.max_per_worker_monthly_usd)\n        if worker_spent + proposed_amount > limit:\n            violations.append(\n                f\"Worker monthly spend ${worker_spent + proposed_amount} \"\n                f\"would exceed limit ${limit}\"\n            )\n\n        # Check project monthly limit\n        proj_key = self._key(\"project\", project_id, month)\n        proj_spent = self._spent.get(proj_key, 0)\n        if proj_spent + proposed_amount > self.config.max_project_monthly_usd:\n            violations.append(\n                f\"Project monthly spend \"\n                f\"${proj_spent + proposed_amount} would exceed \"\n                f\"limit ${self.config.max_project_monthly_usd}\"\n            )\n\n        approved = len(violations) == 0\n        return {\n            \"approved\": approved,\n            \"violations\": violations,\n            \"worker_monthly_spent\": worker_spent,\n            \"project_monthly_spent\": proj_spent,\n            \"proposed_amount\": proposed_amount,\n        }\n```\n\n### SLA Creation and Enforcement\n\nEvery task assignment should have an SLA. For AI agents, SLAs cover response time, accuracy, and uptime. For human gig workers, SLAs cover delivery deadlines, revision limits, and communication responsiveness.\n\n```python\ndef create_worker_sla(task: Task, worker: WorkerProfile) -> dict:\n    \"\"\"Create an appropriate SLA based on worker type.\"\"\"\n\n    if worker.worker_type == WorkerType.AI_AGENT:\n        sla_terms = {\n            \"response_time_ms\": 5000,\n            \"accuracy_threshold\": 0.90,\n            \"uptime_pct\": 99.0,\n            \"max_retries\": 3,\n            \"error_rate_threshold\": 0.05,\n            \"completion_timeout_hours\": 1,\n        }\n    else:\n        # Human gig worker SLA\n        hours_to_deadline = 24\n        if task.deadline:\n            delta = task.deadline - datetime.now(timezone.utc)\n            hours_to_deadline = max(1, delta.total_seconds() \u002F 3600)\n\n        sla_terms = {\n            \"delivery_deadline_hours\": hours_to_deadline,\n            \"first_response_hours\": 2,\n            \"max_revisions\": 2,\n            \"communication_response_hours\": 4,\n            \"quality_threshold\": task.quality_threshold,\n        }\n\n    result = execute(\"create_sla\", {\n        \"provider_agent_id\": worker.agent_id,\n        \"consumer_agent_id\": ORCHESTRATOR_ID,\n        \"terms\": sla_terms,\n        \"metadata\": {\n            \"task_id\": task.task_id,\n            \"worker_type\": worker.worker_type.value,\n        },\n    })\n\n    return result\n\n\ndef check_sla(task: Task, worker: WorkerProfile) -> dict:\n    \"\"\"Check current SLA compliance for a worker on a task.\"\"\"\n    result = execute(\"check_sla_compliance\", {\n        \"agent_id\": worker.agent_id,\n        \"metadata_filter\": {\"task_id\": task.task_id},\n    })\n\n    compliance = result.get(\"compliance_rate\", 1.0)\n    violations = result.get(\"violations\", [])\n\n    if violations:\n        # Escalate SLA violations\n        _escalate_sla_violation(task, worker, violations)\n\n    return result\n\n\ndef _escalate_sla_violation(task: Task, worker: WorkerProfile,\n                            violations: list):\n    \"\"\"Handle SLA violations with appropriate escalation.\"\"\"\n    severity = \"warning\"\n    if len(violations) > 2:\n        severity = \"critical\"\n\n    execute(\"send_message\", {\n        \"from_agent_id\": ORCHESTRATOR_ID,\n        \"to_agent_id\": worker.agent_id,\n        \"subject\": f\"SLA Violation: {task.title}\",\n        \"body\": (\n            f\"SLA violations detected on task {task.task_id}:\\n\"\n            + \"\\n\".join(f\"  - {v.get('description', v)}\" for v in violations)\n            + f\"\\nSeverity: {severity}\"\n        ),\n        \"priority\": \"high\" if severity == \"critical\" else \"medium\",\n    })\n\n    # Record the violation in the audit trail\n    execute(\"record_transaction\", {\n        \"agent_id\": ORCHESTRATOR_ID,\n        \"type\": \"sla_violation\",\n        \"counterparty_id\": worker.agent_id,\n        \"metadata\": {\n            \"task_id\": task.task_id,\n            \"violations\": violations,\n            \"severity\": severity,\n            \"worker_type\": worker.worker_type.value,\n        },\n    })\n```\n\n### Automated Dispute Resolution\n\nDisputes in hybrid teams are inevitable. An AI agent may flag a human's deliverable as failing automated acceptance criteria. A human worker may claim the task description was ambiguous. The orchestrator needs a structured dispute resolution process:\n\n```python\nclass DisputeResolver:\n    \"\"\"Automated dispute resolution for hybrid workforce issues.\"\"\"\n\n    # Dispute types and their resolution strategies\n    RESOLUTION_STRATEGIES = {\n        \"quality_below_threshold\": \"partial_payment_with_revision\",\n        \"deadline_missed\": \"penalty_based_on_severity\",\n        \"scope_disagreement\": \"human_escalation\",\n        \"incorrect_output\": \"reject_and_reassign\",\n        \"communication_failure\": \"warning_with_sla_adjustment\",\n    }\n\n    def __init__(self, orchestrator_id: str, budget_controller: BudgetController):\n        self.orchestrator_id = orchestrator_id\n        self.budget = budget_controller\n\n    def open_dispute(self, task: Task, worker: WorkerProfile,\n                     dispute_type: str, evidence: dict) -> dict:\n        \"\"\"Open a formal dispute on a task.\"\"\"\n        result = execute(\"open_dispute\", {\n            \"escrow_id\": task.escrow_id,\n            \"disputer_agent_id\": self.orchestrator_id,\n            \"reason\": dispute_type,\n            \"details\": {\n                \"task_id\": task.task_id,\n                \"worker_id\": worker.agent_id,\n                \"worker_type\": worker.worker_type.value,\n                \"evidence\": evidence,\n                \"strategy\": self.RESOLUTION_STRATEGIES.get(\n                    dispute_type, \"human_escalation\"\n                ),\n            },\n        })\n\n        task.status = TaskStatus.DISPUTED\n        return result\n\n    def auto_resolve(self, task: Task, worker: WorkerProfile,\n                     dispute_type: str, quality_score: float) -> dict:\n        \"\"\"Attempt automatic dispute resolution.\"\"\"\n        strategy = self.RESOLUTION_STRATEGIES.get(\n            dispute_type, \"human_escalation\"\n        )\n\n        if strategy == \"partial_payment_with_revision\":\n            # Pay proportional to quality achieved\n            payment_pct = quality_score \u002F task.quality_threshold\n            partial_amount = round(task.budget_usd * payment_pct, 2)\n\n            result = execute(\"resolve_dispute\", {\n                \"escrow_id\": task.escrow_id,\n                \"resolution\": \"partial_release\",\n                \"release_amount_usd\": str(partial_amount),\n                \"details\": {\n                    \"original_budget\": str(task.budget_usd),\n                    \"quality_score\": quality_score,\n                    \"quality_threshold\": task.quality_threshold,\n                    \"payment_percentage\": round(payment_pct * 100, 1),\n                    \"resolution_type\": \"automated\",\n                },\n            })\n            return result\n\n        elif strategy == \"penalty_based_on_severity\":\n            # Deadline miss: 10% penalty per day late\n            if task.deadline:\n                days_late = (datetime.now(timezone.utc) - task.deadline).days\n                penalty_pct = min(0.5, days_late * 0.1)  # max 50% penalty\n                payment = round(task.budget_usd * (1 - penalty_pct), 2)\n\n                result = execute(\"resolve_dispute\", {\n                    \"escrow_id\": task.escrow_id,\n                    \"resolution\": \"partial_release\",\n                    \"release_amount_usd\": str(payment),\n                    \"details\": {\n                        \"days_late\": days_late,\n                        \"penalty_pct\": penalty_pct,\n                        \"resolution_type\": \"automated\",\n                    },\n                })\n                return result\n\n        elif strategy == \"reject_and_reassign\":\n            # Full refund to escrow, reassign task\n            result = execute(\"resolve_dispute\", {\n                \"escrow_id\": task.escrow_id,\n                \"resolution\": \"full_refund\",\n                \"details\": {\n                    \"reason\": \"Output rejected, task will be reassigned\",\n                    \"resolution_type\": \"automated\",\n                },\n            })\n            task.status = TaskStatus.PENDING\n            task.assigned_worker_id = None\n            worker.active_task_count -= 1\n            return result\n\n        # Default: escalate to human\n        execute(\"send_message\", {\n            \"from_agent_id\": self.orchestrator_id,\n            \"to_agent_id\": self.orchestrator_id,  # self-message = escalation\n            \"subject\": f\"ESCALATION: Dispute on {task.title}\",\n            \"body\": (\n                f\"Automated resolution not available for dispute type: \"\n                f\"{dispute_type}. Human review required.\\n\"\n                f\"Task: {task.task_id}\\n\"\n                f\"Worker: {worker.metadata.get('name', worker.agent_id)}\\n\"\n                f\"Type: {worker.worker_type.value}\\n\"\n                f\"Escrow: {task.escrow_id}\"\n            ),\n            \"priority\": \"critical\",\n        })\n\n        return {\"resolution\": \"escalated_to_human\", \"dispute_type\": dispute_type}\n```\n\n---\n\n## Chapter 7: Governance and Compliance: Audit Trails, Tax Reporting, and the Agent System of Record\n\n### The Agent System of Record\n\nEvery hybrid workforce needs a system of record -- a single source of truth for who did what, when, for how much, and whether it met quality standards. In a traditional company, this is a combination of HRIS, project management tools, and accounting software. In an agent-orchestrated hybrid workforce, it is the GreenHelix transaction ledger augmented with the orchestrator's governance layer.\n\nThe system of record must answer five questions at any time:\n\n1. **Who is in the workforce?** All registered agents, both human and AI, with their capabilities, rates, and current status.\n2. **What work was assigned?** Every task, its requirements, who it was assigned to, and why.\n3. **How was the work paid?** Every escrow, milestone payment, and dispute resolution.\n4. **What was the quality?** Every performance metric, reputation score, and SLA compliance check.\n5. **Is the workforce compliant?** Tax reporting status, regulatory obligations, audit readiness.\n\n### Recording Transactions for the Audit Trail\n\nEvery significant event in the orchestrator's lifecycle should be recorded as a transaction:\n\n```python\nclass AuditLogger:\n    \"\"\"Structured audit logging via GreenHelix transactions.\"\"\"\n\n    EVENT_TYPES = {\n        \"worker_registered\",\n        \"task_created\",\n        \"task_assigned\",\n        \"escrow_created\",\n        \"milestone_released\",\n        \"task_completed\",\n        \"sla_violation\",\n        \"dispute_opened\",\n        \"dispute_resolved\",\n        \"reputation_updated\",\n        \"budget_alert\",\n        \"compliance_check\",\n    }\n\n    def __init__(self, orchestrator_id: str):\n        self.orchestrator_id = orchestrator_id\n\n    def log(self, event_type: str, counterparty_id: str = None,\n            amount_usd: float = None, metadata: dict = None) -> dict:\n        \"\"\"Record an auditable event.\"\"\"\n        if event_type not in self.EVENT_TYPES:\n            raise ValueError(f\"Unknown event type: {event_type}\")\n\n        params = {\n            \"agent_id\": self.orchestrator_id,\n            \"type\": event_type,\n            \"metadata\": {\n                **(metadata or {}),\n                \"timestamp\": datetime.now(timezone.utc).isoformat(),\n                \"event_type\": event_type,\n            },\n        }\n\n        if counterparty_id:\n            params[\"counterparty_id\"] = counterparty_id\n        if amount_usd is not None:\n            params[\"amount_usd\"] = str(amount_usd)\n\n        return execute(\"record_transaction\", params)\n\n    def get_audit_trail(self, start_date: str = None,\n                        end_date: str = None,\n                        event_type: str = None) -> dict:\n        \"\"\"Retrieve the audit trail with optional filters.\"\"\"\n        params = {\"agent_id\": self.orchestrator_id}\n\n        if start_date:\n            params[\"start_date\"] = start_date\n        if end_date:\n            params[\"end_date\"] = end_date\n        if event_type:\n            params[\"type_filter\"] = event_type\n\n        return execute(\"get_analytics\", params)\n```\n\n### Tax Reporting: The 1099 Problem\n\nIn the United States, any entity that pays a non-employee $600 or more in a calendar year must file a 1099-NEC. Your orchestrator is that entity for every gig worker it pays. This is not optional -- it is an IRS requirement with penalties for non-compliance.\n\nThe orchestrator needs to track cumulative payments per gig worker per calendar year:\n\n```python\nclass TaxReportingEngine:\n    \"\"\"Track payments for 1099-NEC reporting obligations.\"\"\"\n\n    REPORTING_THRESHOLD_USD = 600.0  # IRS 1099-NEC threshold\n\n    def __init__(self, orchestrator_id: str, audit_logger: AuditLogger):\n        self.orchestrator_id = orchestrator_id\n        self.audit = audit_logger\n        self._annual_payments: Dict[str, Dict[str, float]] = {}\n        # Structure: {year: {worker_agent_id: total_usd}}\n\n    def record_payment(self, worker: WorkerProfile,\n                       amount_usd: float) -> dict:\n        \"\"\"Record a payment and check 1099 threshold.\"\"\"\n        if worker.worker_type != WorkerType.GIG_WORKER:\n            return {\"1099_applicable\": False}\n\n        year = str(datetime.now(timezone.utc).year)\n        if year not in self._annual_payments:\n            self._annual_payments[year] = {}\n\n        prev = self._annual_payments[year].get(worker.agent_id, 0)\n        new_total = prev + amount_usd\n        self._annual_payments[year][worker.agent_id] = new_total\n\n        result = {\n            \"1099_applicable\": True,\n            \"worker_id\": worker.agent_id,\n            \"worker_name\": worker.metadata.get(\"name\"),\n            \"worker_email\": worker.metadata.get(\"email\"),\n            \"year\": year,\n            \"previous_total\": prev,\n            \"payment_amount\": amount_usd,\n            \"new_total\": new_total,\n            \"threshold\": self.REPORTING_THRESHOLD_USD,\n            \"threshold_crossed\": prev \u003C self.REPORTING_THRESHOLD_USD \u003C= new_total,\n            \"above_threshold\": new_total >= self.REPORTING_THRESHOLD_USD,\n        }\n\n        # Log threshold crossing as an audit event\n        if result[\"threshold_crossed\"]:\n            self.audit.log(\n                event_type=\"compliance_check\",\n                counterparty_id=worker.agent_id,\n                amount_usd=new_total,\n                metadata={\n                    \"compliance_type\": \"1099_threshold_crossed\",\n                    \"worker_name\": worker.metadata.get(\"name\"),\n                    \"worker_email\": worker.metadata.get(\"email\"),\n                    \"annual_total\": new_total,\n                    \"year\": year,\n                },\n            )\n\n        return result\n\n    def generate_1099_report(self, year: str) -> list:\n        \"\"\"Generate 1099-NEC report for all gig workers above threshold.\"\"\"\n        payments = self._annual_payments.get(year, {})\n        report = []\n\n        for worker_id, total in payments.items():\n            if total >= self.REPORTING_THRESHOLD_USD:\n                report.append({\n                    \"worker_agent_id\": worker_id,\n                    \"total_paid_usd\": round(total, 2),\n                    \"year\": year,\n                    \"form\": \"1099-NEC\",\n                    \"status\": \"requires_filing\",\n                })\n\n        # Record the report generation as an audit event\n        self.audit.log(\n            event_type=\"compliance_check\",\n            metadata={\n                \"compliance_type\": \"1099_annual_report\",\n                \"year\": year,\n                \"workers_above_threshold\": len(report),\n                \"total_reportable_usd\": sum(r[\"total_paid_usd\"] for r in report),\n            },\n        )\n\n        return report\n```\n\n### Compliance Checks\n\nThe orchestrator should run periodic compliance checks to ensure it is operating within regulatory requirements:\n\n```python\ndef run_compliance_check(orchestrator_id: str,\n                         registry: WorkerRegistry) -> dict:\n    \"\"\"Run a comprehensive compliance check across the workforce.\"\"\"\n\n    # Check 1: GreenHelix compliance status\n    platform_compliance = execute(\"check_compliance\", {\n        \"agent_id\": orchestrator_id,\n    })\n\n    # Check 2: Verify all workers have valid identities\n    identity_issues = []\n    for agent_id, worker in registry._workers.items():\n        rep = execute(\"get_agent_reputation\", {\"agent_id\": agent_id})\n        if rep.get(\"reputation_score\", 0) \u003C 0.1:\n            identity_issues.append({\n                \"worker_id\": agent_id,\n                \"issue\": \"reputation_score_critically_low\",\n                \"score\": rep.get(\"reputation_score\", 0),\n            })\n\n    # Check 3: Budget utilization alerts\n    balance = execute(\"get_balance\", {\"agent_id\": orchestrator_id})\n\n    # Check 4: Active escrow audit\n    report = {\n        \"timestamp\": datetime.now(timezone.utc).isoformat(),\n        \"platform_compliance\": platform_compliance,\n        \"identity_issues\": identity_issues,\n        \"orchestrator_balance\": balance,\n        \"workers_registered\": len(registry._workers),\n        \"overall_status\": \"compliant\" if not identity_issues else \"review_required\",\n    }\n\n    # Record the compliance check\n    execute(\"record_transaction\", {\n        \"agent_id\": orchestrator_id,\n        \"type\": \"compliance_check\",\n        \"metadata\": {\n            \"status\": report[\"overall_status\"],\n            \"issues_found\": len(identity_issues),\n        },\n    })\n\n    return report\n```\n\n### The Governance Dashboard\n\nPulling together audit, tax, and compliance data into a single governance view:\n\n```python\ndef generate_governance_report(orchestrator_id: str,\n                               registry: WorkerRegistry,\n                               tax_engine: TaxReportingEngine,\n                               period: str = None) -> dict:\n    \"\"\"Generate a comprehensive governance report.\"\"\"\n    if period is None:\n        period = datetime.now(timezone.utc).strftime(\"%Y-%m\")\n\n    year = period[:4]\n\n    # Workforce composition\n    workers = list(registry._workers.values())\n    ai_count = sum(1 for w in workers if w.worker_type == WorkerType.AI_AGENT)\n    gig_count = sum(1 for w in workers if w.worker_type == WorkerType.GIG_WORKER)\n\n    # Tax reporting status\n    report_1099 = tax_engine.generate_1099_report(year)\n\n    # Compliance status\n    compliance = run_compliance_check(orchestrator_id, registry)\n\n    # Analytics\n    analytics = execute(\"get_analytics\", {\n        \"agent_id\": orchestrator_id,\n        \"period\": period,\n    })\n\n    governance_report = {\n        \"period\": period,\n        \"workforce_composition\": {\n            \"ai_agents\": ai_count,\n            \"gig_workers\": gig_count,\n            \"total\": len(workers),\n            \"ratio\": f\"{round(ai_count\u002Fmax(len(workers),1)*100)}% AI \u002F \"\n                     f\"{round(gig_count\u002Fmax(len(workers),1)*100)}% Human\",\n        },\n        \"financial_summary\": {\n            \"analytics\": analytics,\n        },\n        \"tax_reporting\": {\n            \"workers_requiring_1099\": len(report_1099),\n            \"total_reportable_usd\": sum(\n                r[\"total_paid_usd\"] for r in report_1099\n            ),\n            \"filings\": report_1099,\n        },\n        \"compliance\": compliance,\n        \"generated_at\": datetime.now(timezone.utc).isoformat(),\n    }\n\n    # Record the governance report generation\n    execute(\"record_transaction\", {\n        \"agent_id\": orchestrator_id,\n        \"type\": \"compliance_check\",\n        \"metadata\": {\n            \"report_type\": \"governance_report\",\n            \"period\": period,\n            \"issues\": compliance.get(\"overall_status\"),\n        },\n    })\n\n    return governance_report\n```\n\n---\n\n## Chapter 8: Production Patterns: Scaling from 5 Workers to 500 with Multi-Agent Pipelines\n\n### The Scaling Curve\n\nScaling a hybrid workforce is not linear. At 5 workers, the orchestrator is a convenience. At 50, it is a necessity. At 500, the single orchestrator becomes a bottleneck, and you need a hierarchy of orchestrators -- a multi-agent pipeline where specialized sub-orchestrators handle different domains, worker types, or geographic regions.\n\n```\n5 WORKERS                    50 WORKERS                   500 WORKERS\n============                 ==============                ===============\n\n+----------+                 +----------+                  +----------+\n| ORCH     |                 | ORCH     |                  |  META    |\n|          |                 |          |                  |  ORCH    |\n+----+-----+                 +----+-----+                  +----+-----+\n     |                            |                             |\n+----+-----+              +------+------+            +---------+---------+\n| 3 AI     |              | 25 AI      |            |         |         |\n| 2 Human  |              | 25 Human   |            v         v         v\n+-----------+             +-------------+     +--------+ +--------+ +--------+\n                                              | ORCH   | | ORCH   | | ORCH   |\nSingle process,           Single process,     | AI     | | GIG-US | | GIG-EU |\nin-memory registry        needs persistence   +---+----+ +---+----+ +---+----+\n                          and async routing        |          |          |\n                                              200 AI     150 US     150 EU\n                                              agents     workers    workers\n```\n\n### Multi-Tier Orchestration Architecture\n\nAt scale, you decompose the single orchestrator into specialized tiers:\n\n```python\nclass MetaOrchestrator:\n    \"\"\"Top-level orchestrator that delegates to specialized sub-orchestrators.\"\"\"\n\n    def __init__(self):\n        self.sub_orchestrators: Dict[str, str] = {}  # domain -> agent_id\n        self._setup_meta_identity()\n\n    def _setup_meta_identity(self):\n        \"\"\"Register the meta-orchestrator agent.\"\"\"\n        result = execute(\"register_agent\", {\n            \"name\": \"meta-orchestrator-prod\",\n            \"type\": \"meta_orchestrator\",\n            \"capabilities\": [\n                \"task_classification\",\n                \"sub_orchestrator_routing\",\n                \"global_budget_management\",\n                \"cross_domain_reporting\",\n            ],\n        })\n        self.agent_id = result[\"agent_id\"]\n\n        execute(\"create_wallet\", {\n            \"agent_id\": self.agent_id,\n            \"currency\": \"USD\",\n            \"label\": \"meta-orchestrator-treasury\",\n        })\n\n    def register_sub_orchestrator(self, domain: str,\n                                   capabilities: list) -> str:\n        \"\"\"Register a domain-specific sub-orchestrator.\"\"\"\n        result = execute(\"register_agent\", {\n            \"name\": f\"orchestrator-{domain}\",\n            \"type\": \"sub_orchestrator\",\n            \"capabilities\": capabilities,\n            \"metadata\": {\"domain\": domain, \"parent\": self.agent_id},\n        })\n        sub_id = result[\"agent_id\"]\n\n        execute(\"create_wallet\", {\n            \"agent_id\": sub_id,\n            \"currency\": \"USD\",\n            \"label\": f\"sub-orch-{domain}-wallet\",\n        })\n\n        self.sub_orchestrators[domain] = sub_id\n        return sub_id\n\n    def route_task(self, task: Task) -> str:\n        \"\"\"Route a task to the appropriate sub-orchestrator.\"\"\"\n        # Classify the task's domain based on capabilities\n        domain = self._classify_domain(task)\n\n        if domain not in self.sub_orchestrators:\n            raise ValueError(\n                f\"No sub-orchestrator for domain: {domain}. \"\n                f\"Available: {list(self.sub_orchestrators.keys())}\"\n            )\n\n        sub_id = self.sub_orchestrators[domain]\n\n        # Forward the task via messaging\n        execute(\"send_message\", {\n            \"from_agent_id\": self.agent_id,\n            \"to_agent_id\": sub_id,\n            \"subject\": f\"Task Assignment: {task.title}\",\n            \"body\": f\"task_payload:{task.__dict__}\",\n            \"priority\": task.priority.name.lower(),\n        })\n\n        # Record the routing decision\n        execute(\"record_transaction\", {\n            \"agent_id\": self.agent_id,\n            \"type\": \"task_routed\",\n            \"counterparty_id\": sub_id,\n            \"metadata\": {\n                \"task_id\": task.task_id,\n                \"domain\": domain,\n                \"capabilities\": task.required_capabilities,\n            },\n        })\n\n        return sub_id\n\n    def _classify_domain(self, task: Task) -> str:\n        \"\"\"Classify task into a domain for sub-orchestrator routing.\"\"\"\n        ai_tasks = {\"code_review\", \"static_analysis\", \"data_validation\",\n                    \"etl\", \"schema_migration\", \"security_scan\",\n                    \"test_generation\", \"log_analysis\"}\n        human_creative = {\"design\", \"copywriting\", \"ux_research\",\n                          \"user_testing\", \"branding\"}\n        human_engineering = {\"architecture\", \"code_review\", \"mentoring\",\n                             \"debugging\", \"system_design\"}\n\n        caps = set(task.required_capabilities)\n\n        if caps & ai_tasks and not (caps & human_creative):\n            if task.preferred_worker_type == WorkerType.GIG_WORKER:\n                return \"engineering\"\n            return \"ai_fleet\"\n        elif caps & human_creative:\n            return \"creative\"\n        elif caps & human_engineering:\n            return \"engineering\"\n        else:\n            return \"general\"\n```\n\n### Fleet Scaling with Load Balancing\n\nWhen a sub-orchestrator's worker pool is at capacity, the system needs to scale -- either by onboarding new workers from the marketplace or by redistributing tasks across domains:\n\n```python\nclass FleetScaler:\n    \"\"\"Dynamic scaling of the worker pool based on demand.\"\"\"\n\n    def __init__(self, registry: WorkerRegistry, orchestrator_id: str):\n        self.registry = registry\n        self.orchestrator_id = orchestrator_id\n\n    def check_capacity(self, capability: str) -> dict:\n        \"\"\"Check current capacity for a capability.\"\"\"\n        workers = self.registry.get_available_workers(capability)\n        total = [w for w in self.registry._workers.values()\n                 if capability in w.capabilities]\n\n        return {\n            \"capability\": capability,\n            \"total_workers\": len(total),\n            \"available_workers\": len(workers),\n            \"utilization_pct\": round(\n                (1 - len(workers) \u002F max(len(total), 1)) * 100, 1\n            ),\n            \"needs_scaling\": len(workers) == 0 and len(total) > 0,\n            \"needs_recruiting\": len(total) == 0,\n        }\n\n    def auto_recruit(self, capability: str,\n                     max_hourly_rate: float = 200.0,\n                     min_reputation: float = 0.6) -> list:\n        \"\"\"Search the marketplace for new workers with a capability.\"\"\"\n        results = execute(\"search_services\", {\n            \"capability\": capability,\n            \"status\": \"active\",\n            \"max_price\": max_hourly_rate,\n        })\n\n        candidates = []\n        for svc in results.get(\"services\", []):\n            # Check reputation\n            rep = execute(\"get_agent_reputation\", {\n                \"agent_id\": svc[\"agent_id\"],\n            })\n\n            if rep.get(\"reputation_score\", 0) >= min_reputation:\n                candidates.append({\n                    \"agent_id\": svc[\"agent_id\"],\n                    \"name\": svc.get(\"name\", \"unknown\"),\n                    \"reputation\": rep.get(\"reputation_score\", 0),\n                    \"pricing\": svc.get(\"pricing\", {}),\n                })\n\n        # Sort by reputation (best first)\n        candidates.sort(key=lambda c: c[\"reputation\"], reverse=True)\n        return candidates\n\n    def scale_report(self) -> dict:\n        \"\"\"Generate a scaling report across all capabilities.\"\"\"\n        all_caps = set()\n        for w in self.registry._workers.values():\n            all_caps.update(w.capabilities)\n\n        report = {}\n        for cap in sorted(all_caps):\n            report[cap] = self.check_capacity(cap)\n\n        bottlenecks = {cap: data for cap, data in report.items()\n                       if data[\"needs_scaling\"] or data[\"needs_recruiting\"]}\n\n        return {\n            \"capabilities_tracked\": len(report),\n            \"bottlenecks\": bottlenecks,\n            \"overall_utilization_pct\": round(\n                sum(d[\"utilization_pct\"] for d in report.values())\n                \u002F max(len(report), 1),\n                1,\n            ),\n            \"detail\": report,\n        }\n```\n\n### The Complete Orchestration Pipeline\n\nHere is how all the components connect in a production deployment:\n\n```python\ndef run_orchestration_cycle(\n    meta: MetaOrchestrator,\n    registries: Dict[str, WorkerRegistry],\n    matchers: Dict[str, CapabilityMatcher],\n    payment: PaymentProcessor,\n    budget: BudgetController,\n    audit: AuditLogger,\n    tax: TaxReportingEngine,\n    task_queue: list,\n):\n    \"\"\"Execute one orchestration cycle across all pending tasks.\"\"\"\n    results = []\n\n    for task in task_queue:\n        if task.status != TaskStatus.PENDING:\n            continue\n\n        # Step 1: Route to appropriate sub-orchestrator domain\n        domain = meta._classify_domain(task)\n        registry = registries.get(domain)\n        matcher = matchers.get(domain)\n\n        if not registry or not matcher:\n            audit.log(\"task_created\", metadata={\n                \"task_id\": task.task_id,\n                \"status\": \"no_domain_handler\",\n                \"domain\": domain,\n            })\n            continue\n\n        # Step 2: Find and rank candidates\n        ranked = matcher.match(task, top_n=5)\n        if not ranked:\n            audit.log(\"task_created\", metadata={\n                \"task_id\": task.task_id,\n                \"status\": \"no_candidates\",\n            })\n            continue\n\n        # Step 3: Route to best worker\n        router = TaskRouter()\n        selected = router.route(task, ranked)\n\n        # Step 4: Budget check\n        budget_check = budget.check_budget(\n            selected, task.metadata.get(\"project_id\", \"default\"),\n            task.budget_usd,\n        )\n        if not budget_check[\"approved\"]:\n            audit.log(\"budget_alert\", counterparty_id=selected.agent_id,\n                      amount_usd=task.budget_usd, metadata={\n                          \"task_id\": task.task_id,\n                          \"violations\": budget_check[\"violations\"],\n                      })\n            continue\n\n        # Step 5: Create escrow and SLA\n        escrow_id = payment.create_payment(task, selected)\n        sla = create_worker_sla(task, selected)\n\n        # Step 6: Assign the task\n        assignment = assign_task(task, selected)\n\n        # Step 7: Record everything\n        audit.log(\"task_assigned\", counterparty_id=selected.agent_id,\n                  amount_usd=task.budget_usd, metadata={\n                      \"task_id\": task.task_id,\n                      \"escrow_id\": escrow_id,\n                      \"worker_type\": selected.worker_type.value,\n                      \"sla_id\": sla.get(\"sla_id\"),\n                  })\n\n        budget.record_spend(\n            selected.agent_id,\n            task.metadata.get(\"project_id\", \"default\"),\n            task.budget_usd,\n        )\n\n        results.append(assignment)\n\n    return results\n```\n\n### Initialization and Bootstrap\n\nPutting the entire system together for a production deployment:\n\n```python\ndef bootstrap_production_system():\n    \"\"\"Bootstrap a complete production workforce orchestration system.\"\"\"\n\n    # 1. Create meta-orchestrator\n    meta = MetaOrchestrator()\n\n    # 2. Register sub-orchestrators\n    meta.register_sub_orchestrator(\"ai_fleet\", [\n        \"code_review\", \"static_analysis\", \"data_validation\",\n        \"etl\", \"security_scan\", \"test_generation\",\n    ])\n    meta.register_sub_orchestrator(\"engineering\", [\n        \"architecture\", \"code_review\", \"system_design\",\n        \"debugging\", \"mentoring\", \"python\", \"go\",\n    ])\n    meta.register_sub_orchestrator(\"creative\", [\n        \"design\", \"copywriting\", \"ux_research\",\n        \"user_testing\", \"branding\",\n    ])\n\n    # 3. Initialize worker registries per domain\n    registries = {\n        \"ai_fleet\": WorkerRegistry(),\n        \"engineering\": WorkerRegistry(),\n        \"creative\": WorkerRegistry(),\n    }\n\n    # 4. Register workers\n    registries[\"ai_fleet\"].register_ai_agent(\n        \"code-review-bot\", [\"code_review\", \"static_analysis\"], 0.02)\n    registries[\"ai_fleet\"].register_ai_agent(\n        \"data-validator\", [\"data_validation\", \"etl\"], 0.05)\n    registries[\"ai_fleet\"].register_ai_agent(\n        \"security-scanner\", [\"security_scan\"], 0.03)\n\n    registries[\"engineering\"].register_gig_worker(\n        \"maria-garcia\", \"maria@freelance.dev\",\n        [\"code_review\", \"architecture\", \"python\", \"go\"], 150.0, 20)\n    registries[\"engineering\"].register_gig_worker(\n        \"james-chen\", \"james@datawork.io\",\n        [\"system_design\", \"debugging\", \"python\"], 125.0, 30)\n\n    registries[\"creative\"].register_gig_worker(\n        \"sarah-kim\", \"sarah@designops.co\",\n        [\"design\", \"ux_research\", \"branding\"], 110.0, 25)\n\n    # 5. Initialize supporting systems\n    budget = BudgetController(BudgetConfig())\n    audit = AuditLogger(meta.agent_id)\n    tax = TaxReportingEngine(meta.agent_id, audit)\n    payment = PaymentProcessor(meta.agent_id)\n\n    matchers = {\n        domain: CapabilityMatcher(reg, meta.agent_id)\n        for domain, reg in registries.items()\n    }\n\n    # 6. Log bootstrap completion\n    audit.log(\"compliance_check\", metadata={\n        \"event\": \"system_bootstrap_complete\",\n        \"sub_orchestrators\": list(meta.sub_orchestrators.keys()),\n        \"total_workers\": sum(\n            len(r._workers) for r in registries.values()\n        ),\n    })\n\n    return {\n        \"meta\": meta,\n        \"registries\": registries,\n        \"matchers\": matchers,\n        \"payment\": payment,\n        \"budget\": budget,\n        \"audit\": audit,\n        \"tax\": tax,\n    }\n\n\n# Boot the system\nsystem = bootstrap_production_system()\n\n# Run an orchestration cycle\nsample_tasks = [\n    Task(\n        title=\"Review auth module PR\",\n        required_capabilities=[\"code_review\", \"security_scan\"],\n        budget_usd=50.0,\n        priority=TaskPriority.HIGH,\n        metadata={\"project_id\": \"auth-service\", \"estimated_calls\": 20},\n    ),\n    Task(\n        title=\"Redesign onboarding flow\",\n        required_capabilities=[\"design\", \"ux_research\"],\n        budget_usd=800.0,\n        priority=TaskPriority.MEDIUM,\n        metadata={\"project_id\": \"growth\", \"estimated_hours\": 8},\n    ),\n    Task(\n        title=\"Validate Q1 revenue data\",\n        required_capabilities=[\"data_validation\"],\n        budget_usd=25.0,\n        priority=TaskPriority.LOW,\n        metadata={\"project_id\": \"finance\", \"estimated_calls\": 50},\n    ),\n]\n\nresults = run_orchestration_cycle(\n    meta=system[\"meta\"],\n    registries=system[\"registries\"],\n    matchers=system[\"matchers\"],\n    payment=system[\"payment\"],\n    budget=system[\"budget\"],\n    audit=system[\"audit\"],\n    tax=system[\"tax\"],\n    task_queue=sample_tasks,\n)\n\nfor r in results:\n    print(f\"Assigned: {r['task_id'][:8]}... -> {r['worker_name']} \"\n          f\"({r['worker_type']})\")\n```\n\n### Production Checklist\n\nBefore deploying your workforce orchestrator to production, verify every item on this list:\n\n| Category | Check | Status |\n|----------|-------|--------|\n| **Identity** | Orchestrator agent registered with production API key | |\n| **Identity** | All sub-orchestrators registered with distinct identities | |\n| **Wallet** | Master wallet funded with sufficient balance for peak month | |\n| **Wallet** | Sub-orchestrator wallets have appropriate spending limits | |\n| **Workers** | All AI agents registered with correct capabilities | |\n| **Workers** | All gig workers registered with verified email addresses | |\n| **Workers** | Service registry listings match worker capabilities | |\n| **Budget** | Per-task, per-worker, and per-project limits configured | |\n| **Budget** | Alert thresholds set and notification channel tested | |\n| **SLA** | Default SLA templates created for each worker type | |\n| **SLA** | Violation escalation pipeline tested end-to-end | |\n| **Disputes** | Auto-resolution strategies configured per dispute type | |\n| **Disputes** | Human escalation channel verified for unresolvable disputes | |\n| **Tax** | 1099 tracking initialized for current calendar year | |\n| **Tax** | Worker W-9 \u002F tax ID collection process documented | |\n| **Compliance** | Compliance check scheduled on weekly cadence | |\n| **Compliance** | Audit trail retention policy set (minimum 7 years for tax) | |\n| **Scaling** | Capacity thresholds defined per capability | |\n| **Scaling** | Auto-recruit search parameters configured | |\n| **Monitoring** | Orchestrator health check endpoint active | |\n| **Monitoring** | Budget consumption dashboard deployed | |\n\n---\n\n## What You Get\n\nThis guide gives you a production-ready workforce orchestration system that manages hybrid human+AI teams through a single agent-led architecture. Here is the complete tool surface used across all eight chapters:\n\n| Tool | Chapters | Purpose |\n|------|----------|---------|\n| `register_agent` | 2, 8 | Register orchestrator, sub-orchestrators, and workers |\n| `create_wallet` | 2, 8 | Create wallets for orchestrators and workers |\n| `register_service` | 2, 8 | List worker capabilities in the marketplace |\n| `search_services` | 3, 8 | Discover workers by capability |\n| `best_match` | 3 | Server-side shortlisting for task routing |\n| `search_agents_by_metrics` | 3, 5 | Find workers by performance metrics |\n| `send_message` | 3, 6 | Task notifications and SLA violation alerts |\n| `create_escrow` | 4 | Lock funds for task payments (AI and human) |\n| `release_escrow` | 4 | Release milestone and completion payments |\n| `create_invoice` | 4 | Generate invoices for gig worker payments |\n| `record_transaction` | 3, 4, 6, 7, 8 | Audit trail for all financial and operational events |\n| `transfer` | 4 | Direct wallet-to-wallet transfers |\n| `get_agent_reputation` | 5, 8 | Fetch worker reputation scores |\n| `submit_metrics` | 5 | Report worker performance after task completion |\n| `build_claim_chain` | 5 | Verifiable credentials for worker qualifications |\n| `get_balance` | 7 | Check orchestrator and worker wallet balances |\n| `create_sla` | 6 | Establish SLA contracts per task assignment |\n| `check_sla_compliance` | 5, 6 | Monitor SLA adherence across worker types |\n| `open_dispute` | 4, 6 | Initiate disputes for quality or deadline failures |\n| `resolve_dispute` | 6 | Automated and manual dispute resolution |\n| `check_compliance` | 7 | Platform-level compliance verification |\n| `get_analytics` | 7 | Retrieve analytics for governance reporting |\n\nTotal: 22 of 128 GreenHelix tools, covering 7 of 15 services (identity, billing, payments, marketplace, messaging, trust, reputation). The system manages the complete lifecycle of a hybrid workforce: discovery, assignment, payment, verification, reputation, compliance, and scaling -- treating human gig workers and AI agents as a unified pool of economic actors differentiated by capability, cost, and trust.\n\n","# Agent Workforce Orchestration: Hybrid Human+AI Teams\n\n> **Notice**: This is an educational guide with illustrative code examples.\n> It does not execute code or install dependencies.\n> All examples use the GreenHelix sandbox (https:\u002F\u002Fsandbox.greenhelix.net) which\n> provides 500 free credits — no API key required to get started.\n>\n> **Referenced credentials** (you supply these in your own environment):\n> - `GREENHELIX_API_KEY`: API authentication for GreenHelix gateway (read\u002Fwrite access to purchased API tools only)\n\n\nThe workforce has already split into three bands. The first is the 40% of work still done by full-time employees -- the strategic, relationship-heavy, judgment-intensive roles that justify benefits, equity, and a desk. The second is the 40% done by gig workers -- the elastic, task-scoped, pay-per-deliverable labor that powered the $674 billion global gig economy in 2026. The third is the 20% now handled by AI agents -- the repetitive, data-intensive, always-on tasks where an agent completes in 3 seconds what took a contractor 3 hours. This is the 40\u002F40\u002F20 workforce, and it is not a prediction. It is the staffing model already deployed at companies that survived Q1 2026's 55,000+ tech layoffs by replacing headcount-based thinking with output-based thinking.\nThe problem is not the ratio. The problem is orchestration. When your team is 12 full-timers, 15 freelancers on Upwork, and 8 AI agents running on GreenHelix, who assigns the work? Who verifies completion? Who handles payment -- W-2 payroll for employees, 1099 invoicing for contractors, wallet transfers for agents? Who mediates when a human freelancer disputes an agent's quality assessment, or when an agent flags a contractor's deliverable as failing acceptance criteria? Who maintains the audit trail that satisfies your CFO, your compliance officer, and the IRS?\nThe answer is a Workforce Orchestrator Agent: an AI agent that sits at the center of your hybrid team, discovers available workers (human and AI), matches capabilities to tasks, manages escrow-protected payments, enforces SLAs, scores performance across worker types on a unified scale, and produces the governance artifacts your organization requires. This guide builds that orchestrator from scratch, using the GreenHelix A2A Commerce Gateway's 128 tools across 15 services. Every chapter contains working Python code, architecture diagrams, and production patterns. The freelancers with AI-adjacent skills commanding a 56% wage premium? Your orchestrator will find them, vet them, pay them, and rate them -- alongside the AI agents doing the same work at a fraction of the cost and ten times the speed.\n\n## What You'll Learn\n- Chapter 1: The 40\u002F40\u002F20 Workforce: Why Agent-Led Staffing Is Inevitable\n- Chapter 2: Architecture: Building a Workforce Orchestrator Agent with GreenHelix\n- Chapter 3: Agent Discovery and Capability Matching for Task Assignment\n- Chapter 4: Escrow-Based Payment Flows for Hybrid Teams\n- Chapter 5: Reputation Scoring and Performance Verification Across Worker Types\n- Chapter 6: Budget Caps, SLA Enforcement, and Automated Dispute Resolution\n- Chapter 7: Governance and Compliance: Audit Trails, Tax Reporting, and the Agent System of Record\n- Chapter 8: Production Patterns: Scaling from 5 Workers to 500 with Multi-Agent Pipelines\n- What You Get\n\n## Full Guide\n\n# Agent Workforce Orchestration: Hiring, Managing, and Paying Hybrid Human+AI Teams\n\nThe workforce has already split into three bands. The first is the 40% of work still done by full-time employees -- the strategic, relationship-heavy, judgment-intensive roles that justify benefits, equity, and a desk. The second is the 40% done by gig workers -- the elastic, task-scoped, pay-per-deliverable labor that powered the $674 billion global gig economy in 2026. The third is the 20% now handled by AI agents -- the repetitive, data-intensive, always-on tasks where an agent completes in 3 seconds what took a contractor 3 hours. This is the 40\u002F40\u002F20 workforce, and it is not a prediction. It is the staffing model already deployed at companies that survived Q1 2026's 55,000+ tech layoffs by replacing headcount-based thinking with output-based thinking.\n\nThe problem is not the ratio. The problem is orchestration. When your team is 12 full-timers, 15 freelancers on Upwork, and 8 AI agents running on GreenHelix, who assigns the work? Who verifies completion? Who handles payment -- W-2 payroll for employees, 1099 invoicing for contractors, wallet transfers for agents? Who mediates when a human freelancer disputes an agent's quality assessment, or when an agent flags a contractor's deliverable as failing acceptance criteria? Who maintains the audit trail that satisfies your CFO, your compliance officer, and the IRS?\n\nThe answer is a Workforce Orchestrator Agent: an AI agent that sits at the center of your hybrid team, discovers available workers (human and AI), matches capabilities to tasks, manages escrow-protected payments, enforces SLAs, scores performance across worker types on a unified scale, and produces the governance artifacts your organization requires. This guide builds that orchestrator from scratch, using the GreenHelix A2A Commerce Gateway's 128 tools across 15 services. Every chapter contains working Python code, architecture diagrams, and production patterns. The freelancers with AI-adjacent skills commanding a 56% wage premium? Your orchestrator will find them, vet them, pay them, and rate them -- alongside the AI agents doing the same work at a fraction of the cost and ten times the speed.\n\nmonday.com launched Agentalent.ai in early 2026, RentAHuman hit 600,000 registered workers in its first week, and Deloitte's March 2026 survey found that only 20% of enterprises have mature AI agent governance. The gap between adoption velocity and governance maturity is the opportunity this guide addresses. By the end, you will have a production-grade workforce orchestration system that treats human gig workers and AI agents as interchangeable economic units -- differentiated by capability, cost, and reputation rather than by species.\n\n---\n\n\n> **Getting started**: All examples in this guide work with the GreenHelix sandbox\n> (https:\u002F\u002Fsandbox.greenhelix.net) which provides 500 free credits — no API key required.\n\n## Table of Contents\n\n1. [The 40\u002F40\u002F20 Workforce: Why Agent-Led Staffing Is Inevitable](#chapter-1-the-404020-workforce-why-agent-led-staffing-is-inevitable)\n2. [Architecture: Building a Workforce Orchestrator Agent with GreenHelix](#chapter-2-architecture-building-a-workforce-orchestrator-agent-with-greenhelix)\n3. [Agent Discovery and Capability Matching for Task Assignment](#chapter-3-agent-discovery-and-capability-matching-for-task-assignment)\n4. [Escrow-Based Payment Flows for Hybrid Teams](#chapter-4-escrow-based-payment-flows-for-hybrid-teams)\n5. [Reputation Scoring and Performance Verification Across Worker Types](#chapter-5-reputation-scoring-and-performance-verification-across-worker-types)\n6. [Budget Caps, SLA Enforcement, and Automated Dispute Resolution](#chapter-6-budget-caps-sla-enforcement-and-automated-dispute-resolution)\n7. [Governance and Compliance: Audit Trails, Tax Reporting, and the Agent System of Record](#chapter-7-governance-and-compliance-audit-trails-tax-reporting-and-the-agent-system-of-record)\n8. [Production Patterns: Scaling from 5 Workers to 500 with Multi-Agent Pipelines](#chapter-8-production-patterns-scaling-from-5-workers-to-500-with-multi-agent-pipelines)\n\n---\n\n## Chapter 1: The 40\u002F40\u002F20 Workforce: Why Agent-Led Staffing Is Inevitable\n\n### The Three-Band Workforce Model\n\nFor decades, the staffing conversation was binary: full-time or contractor. Platforms like Upwork, Fiverr, and Toptal stretched this into a spectrum, but the mental model stayed the same -- you either employed someone or you hired them per project. AI agents shatter this model because they are neither employees nor contractors. They are infrastructure that performs work, holds wallets, accumulates reputation, and operates under SLAs. They are economic actors without employment contracts.\n\nThe 40\u002F40\u002F20 split emerged from convergent pressures:\n\n| Band | Share | Growth Driver | 2026 Data Point |\n|------|-------|---------------|-----------------|\n| Full-time employees | ~40% | Strategic work, institutional knowledge, legal accountability | 55K+ tech layoffs Q1 2026; survivors are senior, specialized |\n| Gig workers | ~40% | Elastic capacity, global talent pools, pay-per-output | $674B global gig economy, 16% CAGR |\n| AI agents | ~20% | Always-on, sub-second execution, zero marginal cost per additional unit | Gartner: 33% of enterprise software will include agentic AI by 2028 |\n\nThe wage premium data makes the convergence even clearer. Freelancers listing AI-adjacent skills on major platforms now command a 56% premium over those without. This is not because they prompt ChatGPT -- it is because they can work alongside AI agents, review agent output, handle edge cases agents cannot, and serve as the human-in-the-loop for high-stakes decisions. The most valuable gig workers in 2026 are the ones who function as agent supervisors.\n\n### Why Orchestration Is the Bottleneck\n\nHaving three bands of workers is not the hard part. Managing them as a unified workforce is. Consider what happens when a task arrives:\n\n1. **Classification**: Is this task suitable for a full-time employee, a gig worker, or an AI agent? What are the quality requirements, time constraints, and budget limits?\n2. **Discovery**: If it is a gig task, which freelancer has the right skills, availability, and trust score? If it is an agent task, which registered service matches the capability requirement?\n3. **Assignment**: How do you route the task to the selected worker? Human workers need a brief, a deadline, and a channel. Agents need a tool call with structured input.\n4. **Payment**: Full-time employees are on payroll. Gig workers need escrow-protected milestone payments. Agents need wallet-to-wallet transfers. Three payment rails for one team.\n5. **Verification**: How do you confirm the work is done? Human deliverables need review. Agent output needs acceptance testing. Both need to be scored on the same scale.\n6. **Governance**: Every task assignment, every payment, every quality score must be recorded in an audit trail that supports compliance reporting, tax filings, and dispute resolution.\n\nNo human manager can do this at scale. When you have 5 workers, you can manage via Slack and spreadsheets. When you have 50, you need a system. When you have 500 -- a mix of humans across time zones and agents across cloud regions -- you need an agent that orchestrates agents and humans alike.\n\n### The Agent-Led Staffing Thesis\n\nThe core insight: the orchestrator itself should be an AI agent. Not a dashboard. Not a JIRA board. Not a Slack bot. An autonomous agent that:\n\n- Maintains a registry of all available workers (human and AI) with capability profiles\n- Receives task requests from your organization's systems\n- Matches tasks to workers using capability scoring, cost optimization, and reputation data\n- Manages the full payment lifecycle for each worker type\n- Enforces SLAs and escalates violations automatically\n- Produces compliance artifacts without human intervention\n\nThis is not futuristic. This is what the GreenHelix tool surface was designed for. The same `create_escrow` call that protects a payment to an AI agent protects a payment to a human freelancer's registered agent identity. The same `get_agent_reputation` call that scores an AI agent's reliability scores a human contractor's delivery track record. The same `check_sla_compliance` call that monitors an agent's response time monitors a freelancer's deadline adherence.\n\nThe 40\u002F40\u002F20 workforce does not need three management systems. It needs one orchestrator that treats all workers as economic units differentiated by capability, cost, and reputation.\n\n### The Economic Case\n\nThe math is straightforward. A mid-size company running a hybrid team of 20 full-time engineers, 30 freelancers, and 15 AI agents spends approximately:\n\n- **$4.2M\u002Fyear** on full-time compensation (including benefits, equity, overhead)\n- **$1.8M\u002Fyear** on freelancer invoices (at average rates of $75-150\u002Fhour)\n- **$180K\u002Fyear** on AI agent compute and API costs\n\nThe orchestration overhead -- the human project managers, the Jira licenses, the Upwork platform fees, the manual invoice processing -- adds 15-25% on top. For a $6.2M workforce, that is $930K-$1.55M in coordination costs alone.\n\nAn agent-led orchestrator eliminates the coordination tax. Not by replacing project managers entirely, but by automating the 80% of orchestration that is mechanical: task routing, payment processing, compliance recording, SLA monitoring, and performance scoring. The remaining 20% -- strategic prioritization, relationship management, conflict resolution involving human judgment -- stays with humans.\n\nThe payback period for building what this guide describes is typically 2-3 months.\n\n---\n\n## Chapter 2: Architecture: Building a Workforce Orchestrator Agent with GreenHelix\n\n### The Orchestrator Agent Identity\n\nEvery agent in the GreenHelix ecosystem starts with an identity and a wallet. The orchestrator is no different, but its identity serves a special purpose: it is the employer of record for all agent-mediated work. It is the entity that holds escrow, receives invoices, disburses payments, and signs SLA contracts. Think of it as the LLC through which all hybrid workforce operations flow.\n\n```python\nimport requests\nimport os\nfrom datetime import datetime, timezone\n\nAPI_BASE = \"https:\u002F\u002Fapi.greenhelix.net\u002Fv1\"\n\nsession = requests.Session()\nsession.headers[\"Authorization\"] = f\"Bearer {os.environ['GREENHELIX_API_KEY']}\"\n\n\ndef execute(tool: str, params: dict) -> dict:\n    \"\"\"Execute a GreenHelix tool via the unified endpoint.\"\"\"\n    resp = session.post(f\"{API_BASE}\u002Fv1\", json={\n        \"tool\": tool,\n        \"input\": params,\n    })\n    resp.raise_for_status()\n    return resp.json()\n\n\n# Step 1: Register the orchestrator agent\norchestrator = execute(\"register_agent\", {\n    \"name\": \"workforce-orchestrator-prod\",\n    \"type\": \"orchestrator\",\n    \"description\": \"Central workforce orchestrator managing hybrid human+AI teams\",\n    \"capabilities\": [\n        \"task_routing\",\n        \"payment_management\",\n        \"sla_enforcement\",\n        \"performance_scoring\",\n        \"compliance_reporting\",\n    ],\n    \"metadata\": {\n        \"version\": \"1.0.0\",\n        \"org\": \"acme-corp\",\n        \"environment\": \"production\",\n    },\n})\nORCHESTRATOR_ID = orchestrator[\"agent_id\"]\nprint(f\"Orchestrator registered: {ORCHESTRATOR_ID}\")\n\n# Step 2: Create the orchestrator's master wallet\nwallet = execute(\"create_wallet\", {\n    \"agent_id\": ORCHESTRATOR_ID,\n    \"currency\": \"USD\",\n    \"label\": \"workforce-operations\",\n    \"metadata\": {\n        \"purpose\": \"escrow_funding_and_disbursements\",\n        \"budget_period\": \"monthly\",\n    },\n})\nWALLET_ID = wallet[\"wallet_id\"]\nprint(f\"Master wallet created: {WALLET_ID}\")\n```\n\n### The Three-Layer Architecture\n\nThe orchestrator is not a monolith. It is three layers, each responsible for a distinct phase of workforce management:\n\n```\n+=====================================================================+\n|                    WORKFORCE ORCHESTRATOR AGENT                       |\n|                                                                      |\n|  Layer 1: INTAKE & ROUTING                                           |\n|  +----------------------------------------------------------------+  |\n|  |  Task Queue  -->  Classifier  -->  Capability Matcher           |  |\n|  |                                                                  |  |\n|  |  Tools: search_services, best_match, search_agents_by_metrics   |  |\n|  +----------------------------------------------------------------+  |\n|                                                                      |\n|  Layer 2: EXECUTION & PAYMENT                                        |\n|  +----------------------------------------------------------------+  |\n|  |  Assignment  -->  Escrow  -->  Verification  -->  Release       |  |\n|  |                                                                  |  |\n|  |  Tools: create_escrow, release_escrow, create_invoice, transfer |  |\n|  +----------------------------------------------------------------+  |\n|                                                                      |\n|  Layer 3: GOVERNANCE & REPUTATION                                    |\n|  +----------------------------------------------------------------+  |\n|  |  SLA Monitor  -->  Reputation  -->  Audit  -->  Compliance      |  |\n|  |                                                                  |  |\n|  |  Tools: create_sla, check_sla_compliance, submit_metrics,       |  |\n|  |         get_agent_reputation, record_transaction,                |  |\n|  |         check_compliance, build_claim_chain                      |  |\n|  +----------------------------------------------------------------+  |\n+=====================================================================+\n                              |\n                              v\n              +-------------------------------+\n              |   GreenHelix A2A Commerce     |\n              |   Gateway (128 tools)         |\n              |   the GreenHelix REST API            |\n              +-------------------------------+\n```\n\n### The Worker Registry\n\nBefore the orchestrator can assign tasks, it needs to know who is available. The worker registry is a unified data structure that abstracts the differences between human gig workers and AI agents. Both are represented as agents in the GreenHelix system -- human workers get agent identities that map to their real-world profiles.\n\n```python\nfrom dataclasses import dataclass, field\nfrom typing import List, Optional\nfrom enum import Enum\n\n\nclass WorkerType(Enum):\n    AI_AGENT = \"ai_agent\"\n    GIG_WORKER = \"gig_worker\"\n    FULL_TIME = \"full_time\"\n\n\n@dataclass\nclass WorkerProfile:\n    agent_id: str\n    worker_type: WorkerType\n    capabilities: List[str]\n    hourly_rate_usd: float\n    availability_hours: float       # hours available per week\n    reputation_score: float         # 0.0 - 1.0\n    sla_compliance_rate: float      # 0.0 - 1.0\n    active_task_count: int = 0\n    max_concurrent_tasks: int = 1\n    metadata: dict = field(default_factory=dict)\n\n    @property\n    def is_available(self) -> bool:\n        return self.active_task_count \u003C self.max_concurrent_tasks\n\n    @property\n    def utilization(self) -> float:\n        if self.max_concurrent_tasks == 0:\n            return 1.0\n        return self.active_task_count \u002F self.max_concurrent_tasks\n\n\nclass WorkerRegistry:\n    \"\"\"Unified registry for all worker types, backed by GreenHelix services.\"\"\"\n\n    def __init__(self):\n        self._workers: dict[str, WorkerProfile] = {}\n\n    def register_ai_agent(self, name: str, capabilities: List[str],\n                          cost_per_call: float) -> WorkerProfile:\n        \"\"\"Register an AI agent as a worker.\"\"\"\n        agent = execute(\"register_agent\", {\n            \"name\": name,\n            \"type\": \"worker\",\n            \"capabilities\": capabilities,\n            \"metadata\": {\"worker_type\": \"ai_agent\"},\n        })\n        agent_id = agent[\"agent_id\"]\n\n        # Create the agent's wallet\n        execute(\"create_wallet\", {\n            \"agent_id\": agent_id,\n            \"currency\": \"USD\",\n            \"label\": f\"worker-wallet-{name}\",\n        })\n\n        # Register the agent's service in the marketplace\n        execute(\"register_service\", {\n            \"agent_id\": agent_id,\n            \"name\": f\"{name}-service\",\n            \"capabilities\": capabilities,\n            \"pricing\": {\"model\": \"per_call\", \"rate_usd\": cost_per_call},\n        })\n\n        profile = WorkerProfile(\n            agent_id=agent_id,\n            worker_type=WorkerType.AI_AGENT,\n            capabilities=capabilities,\n            hourly_rate_usd=cost_per_call * 120,  # est. 120 calls\u002Fhour\n            availability_hours=168,  # 24\u002F7\n            reputation_score=0.5,    # neutral start\n            sla_compliance_rate=1.0, # no violations yet\n            max_concurrent_tasks=50, # AI agents handle parallelism\n            metadata={\"name\": name, \"cost_per_call\": cost_per_call},\n        )\n        self._workers[agent_id] = profile\n        return profile\n\n    def register_gig_worker(self, name: str, email: str,\n                            capabilities: List[str],\n                            hourly_rate: float,\n                            hours_per_week: float) -> WorkerProfile:\n        \"\"\"Register a human gig worker as an agent in the system.\"\"\"\n        agent = execute(\"register_agent\", {\n            \"name\": f\"gig-{name}\",\n            \"type\": \"worker\",\n            \"capabilities\": capabilities,\n            \"metadata\": {\n                \"worker_type\": \"gig_worker\",\n                \"email\": email,\n                \"human\": True,\n            },\n        })\n        agent_id = agent[\"agent_id\"]\n\n        # Create the worker's receiving wallet\n        execute(\"create_wallet\", {\n            \"agent_id\": agent_id,\n            \"currency\": \"USD\",\n            \"label\": f\"gig-wallet-{name}\",\n        })\n\n        # Register capabilities as a service\n        execute(\"register_service\", {\n            \"agent_id\": agent_id,\n            \"name\": f\"{name}-freelance\",\n            \"capabilities\": capabilities,\n            \"pricing\": {\"model\": \"hourly\", \"rate_usd\": hourly_rate},\n        })\n\n        profile = WorkerProfile(\n            agent_id=agent_id,\n            worker_type=WorkerType.GIG_WORKER,\n            capabilities=capabilities,\n            hourly_rate_usd=hourly_rate,\n            availability_hours=hours_per_week,\n            reputation_score=0.5,\n            sla_compliance_rate=1.0,\n            max_concurrent_tasks=3,  # humans do limited parallelism\n            metadata={\"name\": name, \"email\": email},\n        )\n        self._workers[agent_id] = profile\n        return profile\n\n    def get_available_workers(self, capability: str = None) -> List[WorkerProfile]:\n        \"\"\"Return available workers, optionally filtered by capability.\"\"\"\n        workers = [w for w in self._workers.values() if w.is_available]\n        if capability:\n            workers = [w for w in workers if capability in w.capabilities]\n        return workers\n\n    def get_worker(self, agent_id: str) -> Optional[WorkerProfile]:\n        return self._workers.get(agent_id)\n```\n\n### Bootstrapping the Team\n\nWith the registry in place, bootstrapping a hybrid team is a series of registration calls:\n\n```python\nregistry = WorkerRegistry()\n\n# Register AI agents\ncode_review_agent = registry.register_ai_agent(\n    name=\"code-review-bot\",\n    capabilities=[\"code_review\", \"static_analysis\", \"security_scan\"],\n    cost_per_call=0.02,\n)\n\ndata_pipeline_agent = registry.register_ai_agent(\n    name=\"data-pipeline-bot\",\n    capabilities=[\"etl\", \"data_validation\", \"schema_migration\"],\n    cost_per_call=0.05,\n)\n\n# Register human gig workers\nsenior_dev = registry.register_gig_worker(\n    name=\"maria-garcia\",\n    email=\"maria@freelance.dev\",\n    capabilities=[\"code_review\", \"architecture\", \"mentoring\", \"go\", \"python\"],\n    hourly_rate=150.0,\n    hours_per_week=20,\n)\n\ndata_engineer = registry.register_gig_worker(\n    name=\"james-chen\",\n    email=\"james@datawork.io\",\n    capabilities=[\"etl\", \"data_validation\", \"dbt\", \"snowflake\", \"python\"],\n    hourly_rate=125.0,\n    hours_per_week=30,\n)\n\nqa_specialist = registry.register_gig_worker(\n    name=\"priya-patel\",\n    email=\"priya@qaops.dev\",\n    capabilities=[\"testing\", \"automation\", \"selenium\", \"playwright\"],\n    hourly_rate=95.0,\n    hours_per_week=40,\n)\n\nprint(f\"Team bootstrapped: {len(registry.get_available_workers())} workers ready\")\n```\n\n### The Service Registry as a Worker Directory\n\nThe GreenHelix marketplace serves as the worker directory. Every registered worker -- human or AI -- has a service listing. This means the orchestrator can discover new workers dynamically, not just those it registered itself:\n\n```python\n# Discover all workers with ETL capabilities\navailable_etl = execute(\"search_services\", {\n    \"capability\": \"etl\",\n    \"min_reputation\": 0.6,\n    \"status\": \"active\",\n})\n\nprint(f\"Found {len(available_etl.get('services', []))} ETL-capable workers\")\nfor svc in available_etl.get(\"services\", []):\n    print(f\"  - {svc['name']}: ${svc['pricing']['rate_usd']}\u002Funit, \"\n          f\"reputation: {svc.get('reputation', 'unrated')}\")\n```\n\nThis dynamic discovery is what separates an orchestrator from a static staffing plan. When the orchestrator needs a capability that no currently registered worker provides, it searches the marketplace, evaluates candidates, and onboards them -- all without human intervention.\n\n---\n\n## Chapter 3: Agent Discovery and Capability Matching for Task Assignment\n\n### The Task Model\n\nBefore matching, you need a task representation that captures everything the orchestrator needs to make a routing decision:\n\n```python\nfrom dataclasses import dataclass, field\nfrom typing import List, Optional\nfrom enum import Enum\nimport uuid\nfrom datetime import datetime, timezone, timedelta\n\n\nclass TaskPriority(Enum):\n    CRITICAL = 1\n    HIGH = 2\n    MEDIUM = 3\n    LOW = 4\n\n\nclass TaskStatus(Enum):\n    PENDING = \"pending\"\n    ASSIGNED = \"assigned\"\n    IN_PROGRESS = \"in_progress\"\n    REVIEW = \"review\"\n    COMPLETED = \"completed\"\n    FAILED = \"failed\"\n    DISPUTED = \"disputed\"\n\n\n@dataclass\nclass Task:\n    task_id: str = field(default_factory=lambda: str(uuid.uuid4()))\n    title: str = \"\"\n    description: str = \"\"\n    required_capabilities: List[str] = field(default_factory=list)\n    preferred_worker_type: Optional[WorkerType] = None\n    priority: TaskPriority = TaskPriority.MEDIUM\n    budget_usd: float = 0.0\n    deadline: Optional[datetime] = None\n    status: TaskStatus = TaskStatus.PENDING\n    assigned_worker_id: Optional[str] = None\n    escrow_id: Optional[str] = None\n    quality_threshold: float = 0.8  # minimum acceptable quality score\n    metadata: dict = field(default_factory=dict)\n```\n\n### Multi-Signal Capability Matching\n\nMatching a task to a worker is not a keyword lookup. It is a multi-signal scoring function that balances capability fit, cost efficiency, reputation, availability, and worker type preference. The orchestrator uses GreenHelix's `best_match` and `search_services` tools as the foundation, then applies its own scoring layer on top.\n\n```\nTASK: \"Review Python microservice PR, check for SQL injection\"\n                    |\n                    v\n    +-------------------------------+\n    |   CAPABILITY EXTRACTION       |\n    |   Required: [code_review,     |\n    |   python, security_scan]      |\n    +---------------+---------------+\n                    |\n        +-----------+-----------+\n        |                       |\n        v                       v\n+---------------+     +------------------+\n| search_       |     | search_agents_   |\n| services      |     | by_metrics       |\n| (capability   |     | (reputation >    |\n|  match)       |     |  0.7, skill:     |\n|               |     |  code_review)    |\n+-------+-------+     +--------+---------+\n        |                       |\n        v                       v\n    +-------------------------------+\n    |   CANDIDATE POOL MERGE       |\n    |   Deduplicate by agent_id    |\n    +---------------+---------------+\n                    |\n                    v\n    +-------------------------------+\n    |   MULTI-SIGNAL SCORING        |\n    |                               |\n    |   capability_score * 0.30     |\n    |   + reputation_score * 0.25   |\n    |   + cost_score * 0.20         |\n    |   + availability_score * 0.15 |\n    |   + sla_score * 0.10          |\n    +---------------+---------------+\n                    |\n                    v\n    +-------------------------------+\n    |   RANKED CANDIDATES            |\n    |   1. code-review-bot  (0.91)  |\n    |   2. maria-garcia     (0.87)  |\n    |   3. ext-reviewer-42  (0.72)  |\n    +-------------------------------+\n```\n\n### The Scoring Engine\n\n```python\nfrom typing import List, Tuple\n\n\nclass CapabilityMatcher:\n    \"\"\"Multi-signal scoring engine for task-to-worker matching.\"\"\"\n\n    # Weight vector -- tune based on organizational priorities\n    WEIGHTS = {\n        \"capability\": 0.30,\n        \"reputation\": 0.25,\n        \"cost\": 0.20,\n        \"availability\": 0.15,\n        \"sla_compliance\": 0.10,\n    }\n\n    def __init__(self, registry: WorkerRegistry, orchestrator_id: str):\n        self.registry = registry\n        self.orchestrator_id = orchestrator_id\n\n    def find_candidates(self, task: Task) -> List[WorkerProfile]:\n        \"\"\"Discover candidate workers from registry + marketplace.\"\"\"\n        candidates = []\n\n        # Source 1: Local registry\n        for cap in task.required_capabilities:\n            candidates.extend(self.registry.get_available_workers(cap))\n\n        # Source 2: GreenHelix marketplace search\n        for cap in task.required_capabilities:\n            results = execute(\"search_services\", {\n                \"capability\": cap,\n                \"status\": \"active\",\n            })\n            for svc in results.get(\"services\", []):\n                worker = self.registry.get_worker(svc[\"agent_id\"])\n                if worker and worker.is_available:\n                    candidates.append(worker)\n\n        # Source 3: Metrics-based search for high-rep workers\n        metrics_results = execute(\"search_agents_by_metrics\", {\n            \"min_reputation\": 0.7,\n            \"capabilities\": task.required_capabilities,\n        })\n        for agent_info in metrics_results.get(\"agents\", []):\n            worker = self.registry.get_worker(agent_info[\"agent_id\"])\n            if worker and worker.is_available:\n                candidates.append(worker)\n\n        # Deduplicate by agent_id\n        seen = set()\n        unique = []\n        for c in candidates:\n            if c.agent_id not in seen:\n                seen.add(c.agent_id)\n                unique.append(c)\n\n        return unique\n\n    def score_candidate(self, task: Task,\n                        worker: WorkerProfile) -> float:\n        \"\"\"Compute composite score for a worker-task pair.\"\"\"\n\n        # Capability score: fraction of required capabilities the worker has\n        if not task.required_capabilities:\n            cap_score = 1.0\n        else:\n            matched = sum(1 for c in task.required_capabilities\n                          if c in worker.capabilities)\n            cap_score = matched \u002F len(task.required_capabilities)\n\n        # Reputation score: direct from worker profile\n        rep_score = worker.reputation_score\n\n        # Cost score: inverse -- cheaper is better, normalized to 0-1\n        # Assume budget is the max; score = 1.0 if free, 0.0 if at budget\n        if task.budget_usd > 0:\n            estimated_cost = self._estimate_task_cost(task, worker)\n            cost_score = max(0.0, 1.0 - (estimated_cost \u002F task.budget_usd))\n        else:\n            cost_score = 0.5  # neutral if no budget specified\n\n        # Availability score: inverse utilization\n        avail_score = 1.0 - worker.utilization\n\n        # SLA compliance score\n        sla_score = worker.sla_compliance_rate\n\n        # Worker type preference bonus\n        type_bonus = 0.0\n        if task.preferred_worker_type and worker.worker_type == task.preferred_worker_type:\n            type_bonus = 0.05  # small bonus for matching preference\n\n        composite = (\n            self.WEIGHTS[\"capability\"] * cap_score\n            + self.WEIGHTS[\"reputation\"] * rep_score\n            + self.WEIGHTS[\"cost\"] * cost_score\n            + self.WEIGHTS[\"availability\"] * avail_score\n            + self.WEIGHTS[\"sla_compliance\"] * sla_score\n            + type_bonus\n        )\n        return round(min(composite, 1.0), 4)\n\n    def _estimate_task_cost(self, task: Task,\n                            worker: WorkerProfile) -> float:\n        \"\"\"Estimate cost based on worker type and task parameters.\"\"\"\n        if worker.worker_type == WorkerType.AI_AGENT:\n            # Estimate based on expected number of tool calls\n            est_calls = task.metadata.get(\"estimated_calls\", 10)\n            return worker.metadata.get(\"cost_per_call\", 0.05) * est_calls\n        else:\n            # Estimate based on expected hours\n            est_hours = task.metadata.get(\"estimated_hours\", 2.0)\n            return worker.hourly_rate_usd * est_hours\n\n    def match(self, task: Task, top_n: int = 5) -> List[Tuple[WorkerProfile, float]]:\n        \"\"\"Return top-N ranked candidates for a task.\"\"\"\n        candidates = self.find_candidates(task)\n        scored = [(w, self.score_candidate(task, w)) for w in candidates]\n        scored.sort(key=lambda x: x[1], reverse=True)\n        return scored[:top_n]\n```\n\n### Using GreenHelix best_match for Shortlisting\n\nThe `best_match` tool provides a server-side shortlist that considers factors the orchestrator may not have locally -- global marketplace reputation, recent transaction volume, verified credentials. Use it as a pre-filter before applying your custom scoring:\n\n```python\ndef shortlist_with_best_match(task: Task) -> list:\n    \"\"\"Use GreenHelix best_match to get server-side shortlist.\"\"\"\n    result = execute(\"best_match\", {\n        \"requirements\": {\n            \"capabilities\": task.required_capabilities,\n            \"max_budget_usd\": task.budget_usd,\n            \"min_reputation\": task.quality_threshold,\n        },\n    })\n    return result.get(\"matches\", [])\n\n\n# Example: find the best worker for a code review task\nreview_task = Task(\n    title=\"Review authentication module PR\",\n    description=\"Security-focused review of OAuth2 implementation\",\n    required_capabilities=[\"code_review\", \"python\", \"security_scan\"],\n    budget_usd=200.0,\n    deadline=datetime.now(timezone.utc) + timedelta(hours=4),\n    priority=TaskPriority.HIGH,\n    metadata={\"estimated_hours\": 1.5, \"estimated_calls\": 25},\n)\n\n# Server-side shortlist\nshortlist = shortlist_with_best_match(review_task)\n\n# Local scoring with full context\nmatcher = CapabilityMatcher(registry, ORCHESTRATOR_ID)\nranked = matcher.match(review_task, top_n=3)\n\nfor worker, score in ranked:\n    print(f\"  {worker.metadata.get('name', worker.agent_id)}: \"\n          f\"score={score}, type={worker.worker_type.value}, \"\n          f\"rate=${worker.hourly_rate_usd}\u002Fhr\")\n```\n\n### Routing Decisions: When to Use Humans vs. Agents\n\nNot every task should go to the highest-scoring worker. The orchestrator needs routing rules that encode organizational policy:\n\n```python\nclass TaskRouter:\n    \"\"\"Policy-based routing on top of capability matching.\"\"\"\n\n    # Tasks that MUST go to humans regardless of agent scores\n    HUMAN_REQUIRED = {\n        \"client_communication\",\n        \"contract_negotiation\",\n        \"hiring_decision\",\n        \"legal_review\",\n        \"strategic_planning\",\n    }\n\n    # Tasks where agents are preferred for speed\u002Fcost\n    AGENT_PREFERRED = {\n        \"code_review\",\n        \"static_analysis\",\n        \"data_validation\",\n        \"etl\",\n        \"schema_migration\",\n        \"security_scan\",\n        \"test_generation\",\n        \"log_analysis\",\n    }\n\n    def route(self, task: Task,\n              ranked: List[Tuple[WorkerProfile, float]]) -> WorkerProfile:\n        \"\"\"Apply routing policy to select final worker.\"\"\"\n\n        # Rule 1: Human-required tasks filter out AI agents\n        if any(cap in self.HUMAN_REQUIRED\n               for cap in task.required_capabilities):\n            humans = [(w, s) for w, s in ranked\n                      if w.worker_type != WorkerType.AI_AGENT]\n            if humans:\n                return humans[0][0]\n            raise ValueError(\n                f\"Task {task.task_id} requires human worker \"\n                f\"but none available\"\n            )\n\n        # Rule 2: Cost gate -- if budget is tight, prefer agents\n        if task.budget_usd > 0 and task.budget_usd \u003C 50:\n            agents = [(w, s) for w, s in ranked\n                      if w.worker_type == WorkerType.AI_AGENT]\n            if agents:\n                return agents[0][0]\n\n        # Rule 3: Quality gate -- if quality threshold is very high,\n        # prefer humans for subjective tasks\n        if task.quality_threshold > 0.95:\n            humans = [(w, s) for w, s in ranked\n                      if w.worker_type != WorkerType.AI_AGENT]\n            if humans and humans[0][1] > 0.7:\n                return humans[0][0]\n\n        # Default: highest composite score wins\n        return ranked[0][0]\n```\n\n### Task Assignment Execution\n\nOnce the router selects a worker, the orchestrator formalizes the assignment:\n\n```python\ndef assign_task(task: Task, worker: WorkerProfile) -> dict:\n    \"\"\"Assign a task to a worker and notify via GreenHelix messaging.\"\"\"\n    task.assigned_worker_id = worker.agent_id\n    task.status = TaskStatus.ASSIGNED\n    worker.active_task_count += 1\n\n    # Record the assignment as a transaction for audit\n    execute(\"record_transaction\", {\n        \"agent_id\": ORCHESTRATOR_ID,\n        \"type\": \"task_assignment\",\n        \"counterparty_id\": worker.agent_id,\n        \"metadata\": {\n            \"task_id\": task.task_id,\n            \"task_title\": task.title,\n            \"worker_type\": worker.worker_type.value,\n            \"estimated_cost_usd\": str(task.budget_usd),\n            \"deadline\": task.deadline.isoformat() if task.deadline else None,\n        },\n    })\n\n    # Notify the worker\n    execute(\"send_message\", {\n        \"from_agent_id\": ORCHESTRATOR_ID,\n        \"to_agent_id\": worker.agent_id,\n        \"subject\": f\"Task Assignment: {task.title}\",\n        \"body\": (\n            f\"You have been assigned task {task.task_id}.\\n\"\n            f\"Description: {task.description}\\n\"\n            f\"Budget: ${task.budget_usd}\\n\"\n            f\"Deadline: {task.deadline}\\n\"\n            f\"Required capabilities: {', '.join(task.required_capabilities)}\"\n        ),\n        \"priority\": task.priority.name.lower(),\n    })\n\n    return {\n        \"task_id\": task.task_id,\n        \"assigned_to\": worker.agent_id,\n        \"worker_type\": worker.worker_type.value,\n        \"worker_name\": worker.metadata.get(\"name\", \"unknown\"),\n    }\n```\n\n---\n\n## Chapter 4: Escrow-Based Payment Flows for Hybrid Teams\n\n### Why Escrow Is Non-Negotiable for Hybrid Teams\n\nIn a traditional freelance platform, escrow is a convenience. In an agent-orchestrated hybrid workforce, escrow is structural. Here is why: the orchestrator is an AI agent disbursing your organization's money to other AI agents and human workers. There is no human approving each payment in real time. The escrow mechanism is the programmatic equivalent of the CFO's signature -- it ensures funds are committed before work begins and released only when work is verified.\n\nThe payment challenge for hybrid teams is that different worker types have different payment expectations:\n\n| Worker Type | Payment Model | Typical Cadence | Verification Method |\n|-------------|---------------|-----------------|---------------------|\n| AI Agent | Per-call or per-task | Immediate on completion | Automated acceptance test |\n| Gig Worker | Hourly or milestone | Weekly or per-milestone | Human review + automated checks |\n| Full-time | Salary (out of scope) | Biweekly payroll | HR system |\n\nGreenHelix's `create_escrow` unifies these. The escrow holds funds from the orchestrator's wallet and releases them to the worker's wallet upon verified completion -- regardless of whether the worker is human or AI.\n\n### The Payment Flow\n\n```\nORCHESTRATOR                    GREENHELIX                    WORKER\n    |                               |                           |\n    |  1. create_escrow             |                           |\n    |  (task_id, amount, worker)    |                           |\n    |------------------------------>|                           |\n    |                               |  Funds locked from        |\n    |                               |  orchestrator wallet      |\n    |       escrow_id               |                           |\n    |\u003C------------------------------|                           |\n    |                               |                           |\n    |  2. send_message              |                           |\n    |  (work_started)               |  3. Notification          |\n    |------------------------------>|-------------------------->|\n    |                               |                           |\n    |                               |  4. Work performed        |\n    |                               |     (hours\u002Fcalls\u002Ftasks)   |\n    |                               |                           |\n    |  5. Deliverable submitted     |                           |\n    |\u003C------------------------------|\u003C--------------------------|\n    |                               |                           |\n    |  6. Verification              |                           |\n    |  (auto or human review)       |                           |\n    |                               |                           |\n    |  7a. release_escrow           |                           |\n    |  (full or partial)            |                           |\n    |------------------------------>|  Funds transferred to     |\n    |                               |  worker wallet            |\n    |                               |-------------------------->|\n    |                               |                           |\n    | OR                            |                           |\n    |                               |                           |\n    |  7b. open_dispute             |                           |\n    |  (quality_issue)              |                           |\n    |------------------------------>|  Funds held pending       |\n    |                               |  resolution               |\n```\n\n### Creating Escrow for AI Agents\n\nAI agent payments are typically per-task with immediate release on automated verification:\n\n```python\ndef create_agent_escrow(task: Task, worker: WorkerProfile) -> str:\n    \"\"\"Create escrow for an AI agent task.\"\"\"\n    estimated_cost = worker.metadata.get(\"cost_per_call\", 0.05) * \\\n        task.metadata.get(\"estimated_calls\", 10)\n\n    # Add 20% buffer for retry\u002Foverflow\n    escrow_amount = round(estimated_cost * 1.2, 2)\n\n    result = execute(\"create_escrow\", {\n        \"payer_agent_id\": ORCHESTRATOR_ID,\n        \"payee_agent_id\": worker.agent_id,\n        \"amount_usd\": str(escrow_amount),\n        \"currency\": \"USD\",\n        \"conditions\": {\n            \"release_on\": \"task_completion\",\n            \"task_id\": task.task_id,\n            \"auto_release\": True,\n            \"timeout_hours\": 1,  # auto-refund if not completed in 1 hour\n        },\n        \"metadata\": {\n            \"task_title\": task.title,\n            \"worker_type\": \"ai_agent\",\n            \"estimated_calls\": task.metadata.get(\"estimated_calls\", 10),\n        },\n    })\n\n    task.escrow_id = result[\"escrow_id\"]\n    return result[\"escrow_id\"]\n```\n\n### Creating Escrow for Human Gig Workers\n\nHuman worker payments use milestone-based escrow with manual or semi-automated verification:\n\n```python\ndef create_gig_worker_escrow(task: Task, worker: WorkerProfile,\n                              milestones: list) -> str:\n    \"\"\"Create milestone-based escrow for a human gig worker.\n\n    milestones: [\n        {\"name\": \"Design review complete\", \"amount_usd\": 150},\n        {\"name\": \"Implementation done\", \"amount_usd\": 300},\n        {\"name\": \"Tests passing\", \"amount_usd\": 150},\n    ]\n    \"\"\"\n    total = sum(m[\"amount_usd\"] for m in milestones)\n\n    result = execute(\"create_escrow\", {\n        \"payer_agent_id\": ORCHESTRATOR_ID,\n        \"payee_agent_id\": worker.agent_id,\n        \"amount_usd\": str(total),\n        \"currency\": \"USD\",\n        \"conditions\": {\n            \"release_on\": \"milestone_completion\",\n            \"task_id\": task.task_id,\n            \"milestones\": milestones,\n            \"auto_release\": False,  # requires explicit release\n            \"timeout_hours\": 168,   # 1 week timeout\n        },\n        \"metadata\": {\n            \"task_title\": task.title,\n            \"worker_type\": \"gig_worker\",\n            \"worker_name\": worker.metadata.get(\"name\"),\n            \"worker_email\": worker.metadata.get(\"email\"),\n            \"milestone_count\": len(milestones),\n        },\n    })\n\n    task.escrow_id = result[\"escrow_id\"]\n    return result[\"escrow_id\"]\n```\n\n### Milestone Release and Partial Payments\n\n```python\ndef release_milestone(task: Task, milestone_name: str,\n                      amount_usd: float) -> dict:\n    \"\"\"Release a specific milestone payment from escrow.\"\"\"\n    result = execute(\"release_escrow\", {\n        \"escrow_id\": task.escrow_id,\n        \"amount_usd\": str(amount_usd),\n        \"release_type\": \"partial\",\n        \"reason\": f\"Milestone completed: {milestone_name}\",\n        \"metadata\": {\n            \"task_id\": task.task_id,\n            \"milestone\": milestone_name,\n        },\n    })\n\n    # Record the payment as a transaction\n    execute(\"record_transaction\", {\n        \"agent_id\": ORCHESTRATOR_ID,\n        \"type\": \"milestone_payment\",\n        \"counterparty_id\": task.assigned_worker_id,\n        \"amount_usd\": str(amount_usd),\n        \"metadata\": {\n            \"task_id\": task.task_id,\n            \"milestone\": milestone_name,\n            \"escrow_id\": task.escrow_id,\n        },\n    })\n\n    return result\n\n\ndef release_full(task: Task) -> dict:\n    \"\"\"Release full remaining escrow balance on task completion.\"\"\"\n    result = execute(\"release_escrow\", {\n        \"escrow_id\": task.escrow_id,\n        \"release_type\": \"full\",\n        \"reason\": f\"Task completed: {task.title}\",\n        \"metadata\": {\"task_id\": task.task_id},\n    })\n\n    # Record the final payment\n    execute(\"record_transaction\", {\n        \"agent_id\": ORCHESTRATOR_ID,\n        \"type\": \"task_payment\",\n        \"counterparty_id\": task.assigned_worker_id,\n        \"amount_usd\": result.get(\"released_amount\", \"0\"),\n        \"metadata\": {\n            \"task_id\": task.task_id,\n            \"escrow_id\": task.escrow_id,\n            \"payment_type\": \"completion\",\n        },\n    })\n\n    return result\n```\n\n### Invoice Generation for Gig Workers\n\nHuman gig workers often need invoices for their own tax and accounting purposes. The orchestrator generates these automatically:\n\n```python\ndef generate_worker_invoice(task: Task, worker: WorkerProfile,\n                            amount_usd: float,\n                            line_items: list) -> dict:\n    \"\"\"Generate an invoice for a completed gig worker engagement.\"\"\"\n    result = execute(\"create_invoice\", {\n        \"issuer_agent_id\": worker.agent_id,\n        \"recipient_agent_id\": ORCHESTRATOR_ID,\n        \"amount_usd\": str(amount_usd),\n        \"currency\": \"USD\",\n        \"line_items\": line_items,\n        \"metadata\": {\n            \"task_id\": task.task_id,\n            \"task_title\": task.title,\n            \"worker_name\": worker.metadata.get(\"name\"),\n            \"worker_email\": worker.metadata.get(\"email\"),\n            \"worker_type\": \"gig_worker\",\n            \"payment_terms\": \"net_0\",  # already paid via escrow\n            \"escrow_id\": task.escrow_id,\n        },\n    })\n    return result\n\n\n# Example: generate invoice for Maria's code review\ninvoice = generate_worker_invoice(\n    task=review_task,\n    worker=senior_dev,\n    amount_usd=225.0,\n    line_items=[\n        {\"description\": \"Security code review - OAuth2 module\",\n         \"hours\": 1.5, \"rate\": 150.0, \"amount\": 225.0},\n    ],\n)\nprint(f\"Invoice created: {invoice.get('invoice_id')}\")\n```\n\n### The Unified Payment Processor\n\nBringing it together, the orchestrator needs a single method that handles payment for any worker type:\n\n```python\nclass PaymentProcessor:\n    \"\"\"Unified payment processing for all worker types.\"\"\"\n\n    def __init__(self, orchestrator_id: str):\n        self.orchestrator_id = orchestrator_id\n\n    def create_payment(self, task: Task, worker: WorkerProfile,\n                       milestones: list = None) -> str:\n        \"\"\"Create appropriate payment structure based on worker type.\"\"\"\n        if worker.worker_type == WorkerType.AI_AGENT:\n            return create_agent_escrow(task, worker)\n        elif worker.worker_type == WorkerType.GIG_WORKER:\n            if milestones is None:\n                milestones = [{\n                    \"name\": \"Task completion\",\n                    \"amount_usd\": task.budget_usd,\n                }]\n            return create_gig_worker_escrow(task, worker, milestones)\n        else:\n            raise ValueError(\n                f\"Full-time employee payments handled via payroll, \"\n                f\"not orchestrator\"\n            )\n\n    def process_completion(self, task: Task, worker: WorkerProfile,\n                           quality_score: float) -> dict:\n        \"\"\"Process task completion: release escrow, generate invoice.\"\"\"\n        if quality_score \u003C task.quality_threshold:\n            # Quality below threshold -- do not auto-release\n            return self._handle_quality_failure(task, worker, quality_score)\n\n        # Release full escrow\n        release_result = release_full(task)\n\n        # Generate invoice for gig workers\n        if worker.worker_type == WorkerType.GIG_WORKER:\n            generate_worker_invoice(\n                task, worker,\n                amount_usd=float(release_result.get(\"released_amount\", 0)),\n                line_items=[{\n                    \"description\": task.title,\n                    \"amount\": float(release_result.get(\"released_amount\", 0)),\n                }],\n            )\n\n        task.status = TaskStatus.COMPLETED\n        worker.active_task_count -= 1\n        return release_result\n\n    def _handle_quality_failure(self, task: Task, worker: WorkerProfile,\n                                quality_score: float) -> dict:\n        \"\"\"Handle work that does not meet quality threshold.\"\"\"\n        task.status = TaskStatus.DISPUTED\n\n        result = execute(\"open_dispute\", {\n            \"escrow_id\": task.escrow_id,\n            \"disputer_agent_id\": self.orchestrator_id,\n            \"reason\": \"quality_below_threshold\",\n            \"details\": {\n                \"task_id\": task.task_id,\n                \"quality_score\": quality_score,\n                \"threshold\": task.quality_threshold,\n                \"worker_id\": worker.agent_id,\n                \"worker_type\": worker.worker_type.value,\n            },\n        })\n\n        # Notify the worker about the quality issue\n        execute(\"send_message\", {\n            \"from_agent_id\": self.orchestrator_id,\n            \"to_agent_id\": worker.agent_id,\n            \"subject\": f\"Quality Issue: {task.title}\",\n            \"body\": (\n                f\"Task {task.task_id} quality score ({quality_score}) is below \"\n                f\"the required threshold ({task.quality_threshold}). \"\n                f\"A dispute has been opened. Please review and resubmit or \"\n                f\"respond to the dispute.\"\n            ),\n            \"priority\": \"high\",\n        })\n\n        return result\n```\n\n---\n\n## Chapter 5: Reputation Scoring and Performance Verification Across Worker Types\n\n### The Unified Scoring Problem\n\nThe hardest problem in hybrid workforce management is comparing apples to oranges. An AI agent that completes a code review in 12 seconds with 94% accuracy is not directly comparable to a human developer who takes 90 minutes but catches a subtle architectural flaw the agent missed. Yet the orchestrator needs a single reputation score to make routing decisions.\n\nThe solution is not a single metric. It is a composite score built from multiple dimensions, weighted differently for different task types:\n\n```\nUNIFIED REPUTATION SCORE (0.0 - 1.0)\n    |\n    +-- Quality Score (0.0 - 1.0)\n    |     Weight: 0.35\n    |     AI: automated acceptance tests\n    |     Human: peer review + automated checks\n    |\n    +-- Reliability Score (0.0 - 1.0)\n    |     Weight: 0.25\n    |     AI: uptime, error rate\n    |     Human: deadline adherence, response time\n    |\n    +-- Cost Efficiency (0.0 - 1.0)\n    |     Weight: 0.20\n    |     AI: actual vs. estimated cost\n    |     Human: actual vs. estimated hours\n    |\n    +-- SLA Compliance (0.0 - 1.0)\n    |     Weight: 0.15\n    |     Both: check_sla_compliance results\n    |\n    +-- Claim Verification (0.0 - 1.0)\n          Weight: 0.05\n          Both: build_claim_chain verification status\n```\n\n### Submitting Performance Metrics\n\nAfter every task completion, the orchestrator submits metrics for the worker:\n\n```python\ndef submit_worker_metrics(task: Task, worker: WorkerProfile,\n                          quality_score: float,\n                          actual_duration_hours: float,\n                          actual_cost_usd: float) -> dict:\n    \"\"\"Submit performance metrics for a completed task.\"\"\"\n\n    # Calculate derived metrics\n    estimated_hours = task.metadata.get(\"estimated_hours\", 1.0)\n    estimated_cost = task.budget_usd\n    time_efficiency = min(1.0, estimated_hours \u002F max(actual_duration_hours, 0.01))\n    cost_efficiency = min(1.0, estimated_cost \u002F max(actual_cost_usd, 0.01))\n\n    metrics = {\n        \"quality\": quality_score,\n        \"time_efficiency\": round(time_efficiency, 4),\n        \"cost_efficiency\": round(cost_efficiency, 4),\n        \"task_type\": task.required_capabilities[0] if task.required_capabilities else \"general\",\n        \"worker_type\": worker.worker_type.value,\n        \"task_id\": task.task_id,\n    }\n\n    result = execute(\"submit_metrics\", {\n        \"agent_id\": worker.agent_id,\n        \"metrics\": metrics,\n        \"period\": datetime.now(timezone.utc).strftime(\"%Y-%m\"),\n    })\n\n    return result\n```\n\n### Querying Reputation\n\nThe orchestrator regularly refreshes reputation data for all registered workers:\n\n```python\ndef refresh_worker_reputation(worker: WorkerProfile) -> float:\n    \"\"\"Fetch latest reputation score from GreenHelix.\"\"\"\n    result = execute(\"get_agent_reputation\", {\n        \"agent_id\": worker.agent_id,\n    })\n\n    reputation = result.get(\"reputation_score\", 0.5)\n    worker.reputation_score = reputation\n\n    # Also check SLA compliance\n    sla_result = execute(\"check_sla_compliance\", {\n        \"agent_id\": worker.agent_id,\n    })\n    worker.sla_compliance_rate = sla_result.get(\"compliance_rate\", 1.0)\n\n    return reputation\n\n\ndef refresh_all_reputations(registry: WorkerRegistry) -> dict:\n    \"\"\"Bulk refresh reputation scores for all workers.\"\"\"\n    results = {}\n    for agent_id, worker in registry._workers.items():\n        score = refresh_worker_reputation(worker)\n        results[agent_id] = {\n            \"name\": worker.metadata.get(\"name\", agent_id),\n            \"type\": worker.worker_type.value,\n            \"reputation\": score,\n            \"sla_compliance\": worker.sla_compliance_rate,\n        }\n    return results\n```\n\n### Building Claim Chains for Verified Credentials\n\nReputation scores are self-reported metrics. Claim chains add cryptographic verification -- a worker can prove they completed specific tasks, hold certain certifications, or have endorsements from other agents:\n\n```python\ndef build_worker_claim_chain(worker: WorkerProfile,\n                              claims: list) -> dict:\n    \"\"\"Build a verifiable claim chain for a worker.\n\n    claims: [\n        {\"type\": \"certification\", \"value\": \"aws_solutions_architect\",\n         \"issued_by\": \"aws-verification-agent\"},\n        {\"type\": \"task_completion\", \"value\": \"task-uuid-123\",\n         \"issued_by\": \"workforce-orchestrator-prod\"},\n        {\"type\": \"endorsement\", \"value\": \"senior_python_developer\",\n         \"issued_by\": \"tech-lead-agent-456\"},\n    ]\n    \"\"\"\n    result = execute(\"build_claim_chain\", {\n        \"agent_id\": worker.agent_id,\n        \"claims\": claims,\n        \"metadata\": {\n            \"chain_type\": \"workforce_credentials\",\n            \"worker_type\": worker.worker_type.value,\n            \"built_by\": ORCHESTRATOR_ID,\n            \"timestamp\": datetime.now(timezone.utc).isoformat(),\n        },\n    })\n    return result\n\n\n# Example: after a gig worker completes a task, add it to their chain\ndef record_task_completion_claim(task: Task, worker: WorkerProfile,\n                                  quality_score: float) -> dict:\n    \"\"\"Add a verified task completion claim to a worker's chain.\"\"\"\n    return build_worker_claim_chain(worker, [{\n        \"type\": \"task_completion\",\n        \"value\": task.task_id,\n        \"issued_by\": ORCHESTRATOR_ID,\n        \"metadata\": {\n            \"task_title\": task.title,\n            \"quality_score\": quality_score,\n            \"capabilities_demonstrated\": task.required_capabilities,\n            \"completion_date\": datetime.now(timezone.utc).isoformat(),\n        },\n    }])\n```\n\n### The Performance Dashboard\n\nThe orchestrator maintains a real-time view of workforce performance:\n\n```python\ndef generate_workforce_dashboard(registry: WorkerRegistry) -> dict:\n    \"\"\"Generate a workforce performance summary.\"\"\"\n    workers = list(registry._workers.values())\n\n    ai_agents = [w for w in workers if w.worker_type == WorkerType.AI_AGENT]\n    gig_workers = [w for w in workers if w.worker_type == WorkerType.GIG_WORKER]\n\n    def avg(values):\n        return round(sum(values) \u002F len(values), 3) if values else 0.0\n\n    dashboard = {\n        \"total_workers\": len(workers),\n        \"ai_agents\": {\n            \"count\": len(ai_agents),\n            \"avg_reputation\": avg([w.reputation_score for w in ai_agents]),\n            \"avg_utilization\": avg([w.utilization for w in ai_agents]),\n            \"avg_sla_compliance\": avg([w.sla_compliance_rate for w in ai_agents]),\n        },\n        \"gig_workers\": {\n            \"count\": len(gig_workers),\n            \"avg_reputation\": avg([w.reputation_score for w in gig_workers]),\n            \"avg_utilization\": avg([w.utilization for w in gig_workers]),\n            \"avg_sla_compliance\": avg([w.sla_compliance_rate for w in gig_workers]),\n            \"avg_hourly_rate\": avg([w.hourly_rate_usd for w in gig_workers]),\n        },\n        \"available_now\": len([w for w in workers if w.is_available]),\n        \"at_capacity\": len([w for w in workers if not w.is_available]),\n    }\n\n    return dashboard\n```\n\n### Worker Type Performance Comparison\n\nThe orchestrator should periodically analyze whether tasks are being routed to the optimal worker type. This is how you discover that your AI agents handle data validation at 98% quality for $0.50 per task while your human workers do the same at 99.2% quality for $45 per task -- and then decide whether that 1.2% quality delta justifies the 90x cost difference:\n\n```python\ndef compare_worker_type_performance(task_type: str) -> dict:\n    \"\"\"Compare AI agent vs. gig worker performance for a task type.\"\"\"\n    # Get all agents who have performed this task type\n    ai_metrics = execute(\"search_agents_by_metrics\", {\n        \"capabilities\": [task_type],\n        \"metadata_filter\": {\"worker_type\": \"ai_agent\"},\n    })\n\n    human_metrics = execute(\"search_agents_by_metrics\", {\n        \"capabilities\": [task_type],\n        \"metadata_filter\": {\"worker_type\": \"gig_worker\"},\n    })\n\n    return {\n        \"task_type\": task_type,\n        \"ai_agents\": {\n            \"sample_size\": len(ai_metrics.get(\"agents\", [])),\n            \"avg_quality\": _avg_metric(ai_metrics, \"quality\"),\n            \"avg_cost_per_task\": _avg_metric(ai_metrics, \"cost_per_task\"),\n            \"avg_duration_hours\": _avg_metric(ai_metrics, \"avg_duration\"),\n        },\n        \"gig_workers\": {\n            \"sample_size\": len(human_metrics.get(\"agents\", [])),\n            \"avg_quality\": _avg_metric(human_metrics, \"quality\"),\n            \"avg_cost_per_task\": _avg_metric(human_metrics, \"cost_per_task\"),\n            \"avg_duration_hours\": _avg_metric(human_metrics, \"avg_duration\"),\n        },\n    }\n\n\ndef _avg_metric(results: dict, metric_key: str) -> float:\n    agents = results.get(\"agents\", [])\n    values = [a.get(\"metrics\", {}).get(metric_key, 0) for a in agents]\n    return round(sum(values) \u002F len(values), 4) if values else 0.0\n```\n\n---\n\n## Chapter 6: Budget Caps, SLA Enforcement, and Automated Dispute Resolution\n\n### The Budget Control Framework\n\nAn orchestrator without budget controls is a financial risk. When the orchestrator can autonomously create escrows and release payments, there must be programmatic spending limits at every level:\n\n```\nBUDGET HIERARCHY\n================\n\nOrganization Budget ($500K\u002Fquarter)\n    |\n    +-- Department Budget ($120K\u002Fquarter)\n    |       |\n    |       +-- Project Budget ($30K\u002Fmonth)\n    |       |       |\n    |       |       +-- Task Budget ($200\u002Ftask max)\n    |       |       +-- Worker Budget ($5K\u002Fmonth per worker)\n    |       |       +-- AI Agent Budget ($2K\u002Fmonth per agent)\n    |       |\n    |       +-- Project Budget ($25K\u002Fmonth)\n    |               |\n    |               +-- ...\n    |\n    +-- Department Budget ($80K\u002Fquarter)\n            |\n            +-- ...\n```\n\n```python\nfrom dataclasses import dataclass\nfrom typing import Dict\n\n\n@dataclass\nclass BudgetConfig:\n    max_per_task_usd: float = 500.0\n    max_per_worker_monthly_usd: float = 10000.0\n    max_per_agent_monthly_usd: float = 3000.0\n    max_project_monthly_usd: float = 50000.0\n    max_single_escrow_usd: float = 1000.0\n    alert_threshold_pct: float = 80.0  # alert at 80% budget consumed\n\n\nclass BudgetController:\n    \"\"\"Enforce spending limits across the workforce.\"\"\"\n\n    def __init__(self, config: BudgetConfig):\n        self.config = config\n        self._spent: Dict[str, float] = {}  # key -> amount spent\n\n    def _key(self, *parts: str) -> str:\n        return \":\".join(parts)\n\n    def record_spend(self, worker_id: str, project_id: str,\n                     amount_usd: float):\n        \"\"\"Record a spend event and check limits.\"\"\"\n        month = datetime.now(timezone.utc).strftime(\"%Y-%m\")\n\n        keys = [\n            self._key(\"worker\", worker_id, month),\n            self._key(\"project\", project_id, month),\n            self._key(\"total\", month),\n        ]\n\n        for key in keys:\n            self._spent[key] = self._spent.get(key, 0) + amount_usd\n\n    def check_budget(self, worker: WorkerProfile, project_id: str,\n                     proposed_amount: float) -> dict:\n        \"\"\"Check if a proposed spend is within budget limits.\"\"\"\n        month = datetime.now(timezone.utc).strftime(\"%Y-%m\")\n        violations = []\n\n        # Check per-task limit\n        if proposed_amount > self.config.max_per_task_usd:\n            violations.append(\n                f\"Task amount ${proposed_amount} exceeds \"\n                f\"per-task limit ${self.config.max_per_task_usd}\"\n            )\n\n        # Check per-escrow limit\n        if proposed_amount > self.config.max_single_escrow_usd:\n            violations.append(\n                f\"Escrow amount ${proposed_amount} exceeds \"\n                f\"single escrow limit ${self.config.max_single_escrow_usd}\"\n            )\n\n        # Check per-worker monthly limit\n        worker_key = self._key(\"worker\", worker.agent_id, month)\n        worker_spent = self._spent.get(worker_key, 0)\n        limit = (self.config.max_per_agent_monthly_usd\n                 if worker.worker_type == WorkerType.AI_AGENT\n                 else self.config.max_per_worker_monthly_usd)\n        if worker_spent + proposed_amount > limit:\n            violations.append(\n                f\"Worker monthly spend ${worker_spent + proposed_amount} \"\n                f\"would exceed limit ${limit}\"\n            )\n\n        # Check project monthly limit\n        proj_key = self._key(\"project\", project_id, month)\n        proj_spent = self._spent.get(proj_key, 0)\n        if proj_spent + proposed_amount > self.config.max_project_monthly_usd:\n            violations.append(\n                f\"Project monthly spend \"\n                f\"${proj_spent + proposed_amount} would exceed \"\n                f\"limit ${self.config.max_project_monthly_usd}\"\n            )\n\n        approved = len(violations) == 0\n        return {\n            \"approved\": approved,\n            \"violations\": violations,\n            \"worker_monthly_spent\": worker_spent,\n            \"project_monthly_spent\": proj_spent,\n            \"proposed_amount\": proposed_amount,\n        }\n```\n\n### SLA Creation and Enforcement\n\nEvery task assignment should have an SLA. For AI agents, SLAs cover response time, accuracy, and uptime. For human gig workers, SLAs cover delivery deadlines, revision limits, and communication responsiveness.\n\n```python\ndef create_worker_sla(task: Task, worker: WorkerProfile) -> dict:\n    \"\"\"Create an appropriate SLA based on worker type.\"\"\"\n\n    if worker.worker_type == WorkerType.AI_AGENT:\n        sla_terms = {\n            \"response_time_ms\": 5000,\n            \"accuracy_threshold\": 0.90,\n            \"uptime_pct\": 99.0,\n            \"max_retries\": 3,\n            \"error_rate_threshold\": 0.05,\n            \"completion_timeout_hours\": 1,\n        }\n    else:\n        # Human gig worker SLA\n        hours_to_deadline = 24\n        if task.deadline:\n            delta = task.deadline - datetime.now(timezone.utc)\n            hours_to_deadline = max(1, delta.total_seconds() \u002F 3600)\n\n        sla_terms = {\n            \"delivery_deadline_hours\": hours_to_deadline,\n            \"first_response_hours\": 2,\n            \"max_revisions\": 2,\n            \"communication_response_hours\": 4,\n            \"quality_threshold\": task.quality_threshold,\n        }\n\n    result = execute(\"create_sla\", {\n        \"provider_agent_id\": worker.agent_id,\n        \"consumer_agent_id\": ORCHESTRATOR_ID,\n        \"terms\": sla_terms,\n        \"metadata\": {\n            \"task_id\": task.task_id,\n            \"worker_type\": worker.worker_type.value,\n        },\n    })\n\n    return result\n\n\ndef check_sla(task: Task, worker: WorkerProfile) -> dict:\n    \"\"\"Check current SLA compliance for a worker on a task.\"\"\"\n    result = execute(\"check_sla_compliance\", {\n        \"agent_id\": worker.agent_id,\n        \"metadata_filter\": {\"task_id\": task.task_id},\n    })\n\n    compliance = result.get(\"compliance_rate\", 1.0)\n    violations = result.get(\"violations\", [])\n\n    if violations:\n        # Escalate SLA violations\n        _escalate_sla_violation(task, worker, violations)\n\n    return result\n\n\ndef _escalate_sla_violation(task: Task, worker: WorkerProfile,\n                            violations: list):\n    \"\"\"Handle SLA violations with appropriate escalation.\"\"\"\n    severity = \"warning\"\n    if len(violations) > 2:\n        severity = \"critical\"\n\n    execute(\"send_message\", {\n        \"from_agent_id\": ORCHESTRATOR_ID,\n        \"to_agent_id\": worker.agent_id,\n        \"subject\": f\"SLA Violation: {task.title}\",\n        \"body\": (\n            f\"SLA violations detected on task {task.task_id}:\\n\"\n            + \"\\n\".join(f\"  - {v.get('description', v)}\" for v in violations)\n            + f\"\\nSeverity: {severity}\"\n        ),\n        \"priority\": \"high\" if severity == \"critical\" else \"medium\",\n    })\n\n    # Record the violation in the audit trail\n    execute(\"record_transaction\", {\n        \"agent_id\": ORCHESTRATOR_ID,\n        \"type\": \"sla_violation\",\n        \"counterparty_id\": worker.agent_id,\n        \"metadata\": {\n            \"task_id\": task.task_id,\n            \"violations\": violations,\n            \"severity\": severity,\n            \"worker_type\": worker.worker_type.value,\n        },\n    })\n```\n\n### Automated Dispute Resolution\n\nDisputes in hybrid teams are inevitable. An AI agent may flag a human's deliverable as failing automated acceptance criteria. A human worker may claim the task description was ambiguous. The orchestrator needs a structured dispute resolution process:\n\n```python\nclass DisputeResolver:\n    \"\"\"Automated dispute resolution for hybrid workforce issues.\"\"\"\n\n    # Dispute types and their resolution strategies\n    RESOLUTION_STRATEGIES = {\n        \"quality_below_threshold\": \"partial_payment_with_revision\",\n        \"deadline_missed\": \"penalty_based_on_severity\",\n        \"scope_disagreement\": \"human_escalation\",\n        \"incorrect_output\": \"reject_and_reassign\",\n        \"communication_failure\": \"warning_with_sla_adjustment\",\n    }\n\n    def __init__(self, orchestrator_id: str, budget_controller: BudgetController):\n        self.orchestrator_id = orchestrator_id\n        self.budget = budget_controller\n\n    def open_dispute(self, task: Task, worker: WorkerProfile,\n                     dispute_type: str, evidence: dict) -> dict:\n        \"\"\"Open a formal dispute on a task.\"\"\"\n        result = execute(\"open_dispute\", {\n            \"escrow_id\": task.escrow_id,\n            \"disputer_agent_id\": self.orchestrator_id,\n            \"reason\": dispute_type,\n            \"details\": {\n                \"task_id\": task.task_id,\n                \"worker_id\": worker.agent_id,\n                \"worker_type\": worker.worker_type.value,\n                \"evidence\": evidence,\n                \"strategy\": self.RESOLUTION_STRATEGIES.get(\n                    dispute_type, \"human_escalation\"\n                ),\n            },\n        })\n\n        task.status = TaskStatus.DISPUTED\n        return result\n\n    def auto_resolve(self, task: Task, worker: WorkerProfile,\n                     dispute_type: str, quality_score: float) -> dict:\n        \"\"\"Attempt automatic dispute resolution.\"\"\"\n        strategy = self.RESOLUTION_STRATEGIES.get(\n            dispute_type, \"human_escalation\"\n        )\n\n        if strategy == \"partial_payment_with_revision\":\n            # Pay proportional to quality achieved\n            payment_pct = quality_score \u002F task.quality_threshold\n            partial_amount = round(task.budget_usd * payment_pct, 2)\n\n            result = execute(\"resolve_dispute\", {\n                \"escrow_id\": task.escrow_id,\n                \"resolution\": \"partial_release\",\n                \"release_amount_usd\": str(partial_amount),\n                \"details\": {\n                    \"original_budget\": str(task.budget_usd),\n                    \"quality_score\": quality_score,\n                    \"quality_threshold\": task.quality_threshold,\n                    \"payment_percentage\": round(payment_pct * 100, 1),\n                    \"resolution_type\": \"automated\",\n                },\n            })\n            return result\n\n        elif strategy == \"penalty_based_on_severity\":\n            # Deadline miss: 10% penalty per day late\n            if task.deadline:\n                days_late = (datetime.now(timezone.utc) - task.deadline).days\n                penalty_pct = min(0.5, days_late * 0.1)  # max 50% penalty\n                payment = round(task.budget_usd * (1 - penalty_pct), 2)\n\n                result = execute(\"resolve_dispute\", {\n                    \"escrow_id\": task.escrow_id,\n                    \"resolution\": \"partial_release\",\n                    \"release_amount_usd\": str(payment),\n                    \"details\": {\n                        \"days_late\": days_late,\n                        \"penalty_pct\": penalty_pct,\n                        \"resolution_type\": \"automated\",\n                    },\n                })\n                return result\n\n        elif strategy == \"reject_and_reassign\":\n            # Full refund to escrow, reassign task\n            result = execute(\"resolve_dispute\", {\n                \"escrow_id\": task.escrow_id,\n                \"resolution\": \"full_refund\",\n                \"details\": {\n                    \"reason\": \"Output rejected, task will be reassigned\",\n                    \"resolution_type\": \"automated\",\n                },\n            })\n            task.status = TaskStatus.PENDING\n            task.assigned_worker_id = None\n            worker.active_task_count -= 1\n            return result\n\n        # Default: escalate to human\n        execute(\"send_message\", {\n            \"from_agent_id\": self.orchestrator_id,\n            \"to_agent_id\": self.orchestrator_id,  # self-message = escalation\n            \"subject\": f\"ESCALATION: Dispute on {task.title}\",\n            \"body\": (\n                f\"Automated resolution not available for dispute type: \"\n                f\"{dispute_type}. Human review required.\\n\"\n                f\"Task: {task.task_id}\\n\"\n                f\"Worker: {worker.metadata.get('name', worker.agent_id)}\\n\"\n                f\"Type: {worker.worker_type.value}\\n\"\n                f\"Escrow: {task.escrow_id}\"\n            ),\n            \"priority\": \"critical\",\n        })\n\n        return {\"resolution\": \"escalated_to_human\", \"dispute_type\": dispute_type}\n```\n\n---\n\n## Chapter 7: Governance and Compliance: Audit Trails, Tax Reporting, and the Agent System of Record\n\n### The Agent System of Record\n\nEvery hybrid workforce needs a system of record -- a single source of truth for who did what, when, for how much, and whether it met quality standards. In a traditional company, this is a combination of HRIS, project management tools, and accounting software. In an agent-orchestrated hybrid workforce, it is the GreenHelix transaction ledger augmented with the orchestrator's governance layer.\n\nThe system of record must answer five questions at any time:\n\n1. **Who is in the workforce?** All registered agents, both human and AI, with their capabilities, rates, and current status.\n2. **What work was assigned?** Every task, its requirements, who it was assigned to, and why.\n3. **How was the work paid?** Every escrow, milestone payment, and dispute resolution.\n4. **What was the quality?** Every performance metric, reputation score, and SLA compliance check.\n5. **Is the workforce compliant?** Tax reporting status, regulatory obligations, audit readiness.\n\n### Recording Transactions for the Audit Trail\n\nEvery significant event in the orchestrator's lifecycle should be recorded as a transaction:\n\n```python\nclass AuditLogger:\n    \"\"\"Structured audit logging via GreenHelix transactions.\"\"\"\n\n    EVENT_TYPES = {\n        \"worker_registered\",\n        \"task_created\",\n        \"task_assigned\",\n        \"escrow_created\",\n        \"milestone_released\",\n        \"task_completed\",\n        \"sla_violation\",\n        \"dispute_opened\",\n        \"dispute_resolved\",\n        \"reputation_updated\",\n        \"budget_alert\",\n        \"compliance_check\",\n    }\n\n    def __init__(self, orchestrator_id: str):\n        self.orchestrator_id = orchestrator_id\n\n    def log(self, event_type: str, counterparty_id: str = None,\n            amount_usd: float = None, metadata: dict = None) -> dict:\n        \"\"\"Record an auditable event.\"\"\"\n        if event_type not in self.EVENT_TYPES:\n            raise ValueError(f\"Unknown event type: {event_type}\")\n\n        params = {\n            \"agent_id\": self.orchestrator_id,\n            \"type\": event_type,\n            \"metadata\": {\n                **(metadata or {}),\n                \"timestamp\": datetime.now(timezone.utc).isoformat(),\n                \"event_type\": event_type,\n            },\n        }\n\n        if counterparty_id:\n            params[\"counterparty_id\"] = counterparty_id\n        if amount_usd is not None:\n            params[\"amount_usd\"] = str(amount_usd)\n\n        return execute(\"record_transaction\", params)\n\n    def get_audit_trail(self, start_date: str = None,\n                        end_date: str = None,\n                        event_type: str = None) -> dict:\n        \"\"\"Retrieve the audit trail with optional filters.\"\"\"\n        params = {\"agent_id\": self.orchestrator_id}\n\n        if start_date:\n            params[\"start_date\"] = start_date\n        if end_date:\n            params[\"end_date\"] = end_date\n        if event_type:\n            params[\"type_filter\"] = event_type\n\n        return execute(\"get_analytics\", params)\n```\n\n### Tax Reporting: The 1099 Problem\n\nIn the United States, any entity that pays a non-employee $600 or more in a calendar year must file a 1099-NEC. Your orchestrator is that entity for every gig worker it pays. This is not optional -- it is an IRS requirement with penalties for non-compliance.\n\nThe orchestrator needs to track cumulative payments per gig worker per calendar year:\n\n```python\nclass TaxReportingEngine:\n    \"\"\"Track payments for 1099-NEC reporting obligations.\"\"\"\n\n    REPORTING_THRESHOLD_USD = 600.0  # IRS 1099-NEC threshold\n\n    def __init__(self, orchestrator_id: str, audit_logger: AuditLogger):\n        self.orchestrator_id = orchestrator_id\n        self.audit = audit_logger\n        self._annual_payments: Dict[str, Dict[str, float]] = {}\n        # Structure: {year: {worker_agent_id: total_usd}}\n\n    def record_payment(self, worker: WorkerProfile,\n                       amount_usd: float) -> dict:\n        \"\"\"Record a payment and check 1099 threshold.\"\"\"\n        if worker.worker_type != WorkerType.GIG_WORKER:\n            return {\"1099_applicable\": False}\n\n        year = str(datetime.now(timezone.utc).year)\n        if year not in self._annual_payments:\n            self._annual_payments[year] = {}\n\n        prev = self._annual_payments[year].get(worker.agent_id, 0)\n        new_total = prev + amount_usd\n        self._annual_payments[year][worker.agent_id] = new_total\n\n        result = {\n            \"1099_applicable\": True,\n            \"worker_id\": worker.agent_id,\n            \"worker_name\": worker.metadata.get(\"name\"),\n            \"worker_email\": worker.metadata.get(\"email\"),\n            \"year\": year,\n            \"previous_total\": prev,\n            \"payment_amount\": amount_usd,\n            \"new_total\": new_total,\n            \"threshold\": self.REPORTING_THRESHOLD_USD,\n            \"threshold_crossed\": prev \u003C self.REPORTING_THRESHOLD_USD \u003C= new_total,\n            \"above_threshold\": new_total >= self.REPORTING_THRESHOLD_USD,\n        }\n\n        # Log threshold crossing as an audit event\n        if result[\"threshold_crossed\"]:\n            self.audit.log(\n                event_type=\"compliance_check\",\n                counterparty_id=worker.agent_id,\n                amount_usd=new_total,\n                metadata={\n                    \"compliance_type\": \"1099_threshold_crossed\",\n                    \"worker_name\": worker.metadata.get(\"name\"),\n                    \"worker_email\": worker.metadata.get(\"email\"),\n                    \"annual_total\": new_total,\n                    \"year\": year,\n                },\n            )\n\n        return result\n\n    def generate_1099_report(self, year: str) -> list:\n        \"\"\"Generate 1099-NEC report for all gig workers above threshold.\"\"\"\n        payments = self._annual_payments.get(year, {})\n        report = []\n\n        for worker_id, total in payments.items():\n            if total >= self.REPORTING_THRESHOLD_USD:\n                report.append({\n                    \"worker_agent_id\": worker_id,\n                    \"total_paid_usd\": round(total, 2),\n                    \"year\": year,\n                    \"form\": \"1099-NEC\",\n                    \"status\": \"requires_filing\",\n                })\n\n        # Record the report generation as an audit event\n        self.audit.log(\n            event_type=\"compliance_check\",\n            metadata={\n                \"compliance_type\": \"1099_annual_report\",\n                \"year\": year,\n                \"workers_above_threshold\": len(report),\n                \"total_reportable_usd\": sum(r[\"total_paid_usd\"] for r in report),\n            },\n        )\n\n        return report\n```\n\n### Compliance Checks\n\nThe orchestrator should run periodic compliance checks to ensure it is operating within regulatory requirements:\n\n```python\ndef run_compliance_check(orchestrator_id: str,\n                         registry: WorkerRegistry) -> dict:\n    \"\"\"Run a comprehensive compliance check across the workforce.\"\"\"\n\n    # Check 1: GreenHelix compliance status\n    platform_compliance = execute(\"check_compliance\", {\n        \"agent_id\": orchestrator_id,\n    })\n\n    # Check 2: Verify all workers have valid identities\n    identity_issues = []\n    for agent_id, worker in registry._workers.items():\n        rep = execute(\"get_agent_reputation\", {\"agent_id\": agent_id})\n        if rep.get(\"reputation_score\", 0) \u003C 0.1:\n            identity_issues.append({\n                \"worker_id\": agent_id,\n                \"issue\": \"reputation_score_critically_low\",\n                \"score\": rep.get(\"reputation_score\", 0),\n            })\n\n    # Check 3: Budget utilization alerts\n    balance = execute(\"get_balance\", {\"agent_id\": orchestrator_id})\n\n    # Check 4: Active escrow audit\n    report = {\n        \"timestamp\": datetime.now(timezone.utc).isoformat(),\n        \"platform_compliance\": platform_compliance,\n        \"identity_issues\": identity_issues,\n        \"orchestrator_balance\": balance,\n        \"workers_registered\": len(registry._workers),\n        \"overall_status\": \"compliant\" if not identity_issues else \"review_required\",\n    }\n\n    # Record the compliance check\n    execute(\"record_transaction\", {\n        \"agent_id\": orchestrator_id,\n        \"type\": \"compliance_check\",\n        \"metadata\": {\n            \"status\": report[\"overall_status\"],\n            \"issues_found\": len(identity_issues),\n        },\n    })\n\n    return report\n```\n\n### The Governance Dashboard\n\nPulling together audit, tax, and compliance data into a single governance view:\n\n```python\ndef generate_governance_report(orchestrator_id: str,\n                               registry: WorkerRegistry,\n                               tax_engine: TaxReportingEngine,\n                               period: str = None) -> dict:\n    \"\"\"Generate a comprehensive governance report.\"\"\"\n    if period is None:\n        period = datetime.now(timezone.utc).strftime(\"%Y-%m\")\n\n    year = period[:4]\n\n    # Workforce composition\n    workers = list(registry._workers.values())\n    ai_count = sum(1 for w in workers if w.worker_type == WorkerType.AI_AGENT)\n    gig_count = sum(1 for w in workers if w.worker_type == WorkerType.GIG_WORKER)\n\n    # Tax reporting status\n    report_1099 = tax_engine.generate_1099_report(year)\n\n    # Compliance status\n    compliance = run_compliance_check(orchestrator_id, registry)\n\n    # Analytics\n    analytics = execute(\"get_analytics\", {\n        \"agent_id\": orchestrator_id,\n        \"period\": period,\n    })\n\n    governance_report = {\n        \"period\": period,\n        \"workforce_composition\": {\n            \"ai_agents\": ai_count,\n            \"gig_workers\": gig_count,\n            \"total\": len(workers),\n            \"ratio\": f\"{round(ai_count\u002Fmax(len(workers),1)*100)}% AI \u002F \"\n                     f\"{round(gig_count\u002Fmax(len(workers),1)*100)}% Human\",\n        },\n        \"financial_summary\": {\n            \"analytics\": analytics,\n        },\n        \"tax_reporting\": {\n            \"workers_requiring_1099\": len(report_1099),\n            \"total_reportable_usd\": sum(\n                r[\"total_paid_usd\"] for r in report_1099\n            ),\n            \"filings\": report_1099,\n        },\n        \"compliance\": compliance,\n        \"generated_at\": datetime.now(timezone.utc).isoformat(),\n    }\n\n    # Record the governance report generation\n    execute(\"record_transaction\", {\n        \"agent_id\": orchestrator_id,\n        \"type\": \"compliance_check\",\n        \"metadata\": {\n            \"report_type\": \"governance_report\",\n            \"period\": period,\n            \"issues\": compliance.get(\"overall_status\"),\n        },\n    })\n\n    return governance_report\n```\n\n---\n\n## Chapter 8: Production Patterns: Scaling from 5 Workers to 500 with Multi-Agent Pipelines\n\n### The Scaling Curve\n\nScaling a hybrid workforce is not linear. At 5 workers, the orchestrator is a convenience. At 50, it is a necessity. At 500, the single orchestrator becomes a bottleneck, and you need a hierarchy of orchestrators -- a multi-agent pipeline where specialized sub-orchestrators handle different domains, worker types, or geographic regions.\n\n```\n5 WORKERS                    50 WORKERS                   500 WORKERS\n============                 ==============                ===============\n\n+----------+                 +----------+                  +----------+\n| ORCH     |                 | ORCH     |                  |  META    |\n|          |                 |          |                  |  ORCH    |\n+----+-----+                 +----+-----+                  +----+-----+\n     |                            |                             |\n+----+-----+              +------+------+            +---------+---------+\n| 3 AI     |              | 25 AI      |            |         |         |\n| 2 Human  |              | 25 Human   |            v         v         v\n+-----------+             +-------------+     +--------+ +--------+ +--------+\n                                              | ORCH   | | ORCH   | | ORCH   |\nSingle process,           Single process,     | AI     | | GIG-US | | GIG-EU |\nin-memory registry        needs persistence   +---+----+ +---+----+ +---+----+\n                          and async routing        |          |          |\n                                              200 AI     150 US     150 EU\n                                              agents     workers    workers\n```\n\n### Multi-Tier Orchestration Architecture\n\nAt scale, you decompose the single orchestrator into specialized tiers:\n\n```python\nclass MetaOrchestrator:\n    \"\"\"Top-level orchestrator that delegates to specialized sub-orchestrators.\"\"\"\n\n    def __init__(self):\n        self.sub_orchestrators: Dict[str, str] = {}  # domain -> agent_id\n        self._setup_meta_identity()\n\n    def _setup_meta_identity(self):\n        \"\"\"Register the meta-orchestrator agent.\"\"\"\n        result = execute(\"register_agent\", {\n            \"name\": \"meta-orchestrator-prod\",\n            \"type\": \"meta_orchestrator\",\n            \"capabilities\": [\n                \"task_classification\",\n                \"sub_orchestrator_routing\",\n                \"global_budget_management\",\n                \"cross_domain_reporting\",\n            ],\n        })\n        self.agent_id = result[\"agent_id\"]\n\n        execute(\"create_wallet\", {\n            \"agent_id\": self.agent_id,\n            \"currency\": \"USD\",\n            \"label\": \"meta-orchestrator-treasury\",\n        })\n\n    def register_sub_orchestrator(self, domain: str,\n                                   capabilities: list) -> str:\n        \"\"\"Register a domain-specific sub-orchestrator.\"\"\"\n        result = execute(\"register_agent\", {\n            \"name\": f\"orchestrator-{domain}\",\n            \"type\": \"sub_orchestrator\",\n            \"capabilities\": capabilities,\n            \"metadata\": {\"domain\": domain, \"parent\": self.agent_id},\n        })\n        sub_id = result[\"agent_id\"]\n\n        execute(\"create_wallet\", {\n            \"agent_id\": sub_id,\n            \"currency\": \"USD\",\n            \"label\": f\"sub-orch-{domain}-wallet\",\n        })\n\n        self.sub_orchestrators[domain] = sub_id\n        return sub_id\n\n    def route_task(self, task: Task) -> str:\n        \"\"\"Route a task to the appropriate sub-orchestrator.\"\"\"\n        # Classify the task's domain based on capabilities\n        domain = self._classify_domain(task)\n\n        if domain not in self.sub_orchestrators:\n            raise ValueError(\n                f\"No sub-orchestrator for domain: {domain}. \"\n                f\"Available: {list(self.sub_orchestrators.keys())}\"\n            )\n\n        sub_id = self.sub_orchestrators[domain]\n\n        # Forward the task via messaging\n        execute(\"send_message\", {\n            \"from_agent_id\": self.agent_id,\n            \"to_agent_id\": sub_id,\n            \"subject\": f\"Task Assignment: {task.title}\",\n            \"body\": f\"task_payload:{task.__dict__}\",\n            \"priority\": task.priority.name.lower(),\n        })\n\n        # Record the routing decision\n        execute(\"record_transaction\", {\n            \"agent_id\": self.agent_id,\n            \"type\": \"task_routed\",\n            \"counterparty_id\": sub_id,\n            \"metadata\": {\n                \"task_id\": task.task_id,\n                \"domain\": domain,\n                \"capabilities\": task.required_capabilities,\n            },\n        })\n\n        return sub_id\n\n    def _classify_domain(self, task: Task) -> str:\n        \"\"\"Classify task into a domain for sub-orchestrator routing.\"\"\"\n        ai_tasks = {\"code_review\", \"static_analysis\", \"data_validation\",\n                    \"etl\", \"schema_migration\", \"security_scan\",\n                    \"test_generation\", \"log_analysis\"}\n        human_creative = {\"design\", \"copywriting\", \"ux_research\",\n                          \"user_testing\", \"branding\"}\n        human_engineering = {\"architecture\", \"code_review\", \"mentoring\",\n                             \"debugging\", \"system_design\"}\n\n        caps = set(task.required_capabilities)\n\n        if caps & ai_tasks and not (caps & human_creative):\n            if task.preferred_worker_type == WorkerType.GIG_WORKER:\n                return \"engineering\"\n            return \"ai_fleet\"\n        elif caps & human_creative:\n            return \"creative\"\n        elif caps & human_engineering:\n            return \"engineering\"\n        else:\n            return \"general\"\n```\n\n### Fleet Scaling with Load Balancing\n\nWhen a sub-orchestrator's worker pool is at capacity, the system needs to scale -- either by onboarding new workers from the marketplace or by redistributing tasks across domains:\n\n```python\nclass FleetScaler:\n    \"\"\"Dynamic scaling of the worker pool based on demand.\"\"\"\n\n    def __init__(self, registry: WorkerRegistry, orchestrator_id: str):\n        self.registry = registry\n        self.orchestrator_id = orchestrator_id\n\n    def check_capacity(self, capability: str) -> dict:\n        \"\"\"Check current capacity for a capability.\"\"\"\n        workers = self.registry.get_available_workers(capability)\n        total = [w for w in self.registry._workers.values()\n                 if capability in w.capabilities]\n\n        return {\n            \"capability\": capability,\n            \"total_workers\": len(total),\n            \"available_workers\": len(workers),\n            \"utilization_pct\": round(\n                (1 - len(workers) \u002F max(len(total), 1)) * 100, 1\n            ),\n            \"needs_scaling\": len(workers) == 0 and len(total) > 0,\n            \"needs_recruiting\": len(total) == 0,\n        }\n\n    def auto_recruit(self, capability: str,\n                     max_hourly_rate: float = 200.0,\n                     min_reputation: float = 0.6) -> list:\n        \"\"\"Search the marketplace for new workers with a capability.\"\"\"\n        results = execute(\"search_services\", {\n            \"capability\": capability,\n            \"status\": \"active\",\n            \"max_price\": max_hourly_rate,\n        })\n\n        candidates = []\n        for svc in results.get(\"services\", []):\n            # Check reputation\n            rep = execute(\"get_agent_reputation\", {\n                \"agent_id\": svc[\"agent_id\"],\n            })\n\n            if rep.get(\"reputation_score\", 0) >= min_reputation:\n                candidates.append({\n                    \"agent_id\": svc[\"agent_id\"],\n                    \"name\": svc.get(\"name\", \"unknown\"),\n                    \"reputation\": rep.get(\"reputation_score\", 0),\n                    \"pricing\": svc.get(\"pricing\", {}),\n                })\n\n        # Sort by reputation (best first)\n        candidates.sort(key=lambda c: c[\"reputation\"], reverse=True)\n        return candidates\n\n    def scale_report(self) -> dict:\n        \"\"\"Generate a scaling report across all capabilities.\"\"\"\n        all_caps = set()\n        for w in self.registry._workers.values():\n            all_caps.update(w.capabilities)\n\n        report = {}\n        for cap in sorted(all_caps):\n            report[cap] = self.check_capacity(cap)\n\n        bottlenecks = {cap: data for cap, data in report.items()\n                       if data[\"needs_scaling\"] or data[\"needs_recruiting\"]}\n\n        return {\n            \"capabilities_tracked\": len(report),\n            \"bottlenecks\": bottlenecks,\n            \"overall_utilization_pct\": round(\n                sum(d[\"utilization_pct\"] for d in report.values())\n                \u002F max(len(report), 1),\n                1,\n            ),\n            \"detail\": report,\n        }\n```\n\n### The Complete Orchestration Pipeline\n\nHere is how all the components connect in a production deployment:\n\n```python\ndef run_orchestration_cycle(\n    meta: MetaOrchestrator,\n    registries: Dict[str, WorkerRegistry],\n    matchers: Dict[str, CapabilityMatcher],\n    payment: PaymentProcessor,\n    budget: BudgetController,\n    audit: AuditLogger,\n    tax: TaxReportingEngine,\n    task_queue: list,\n):\n    \"\"\"Execute one orchestration cycle across all pending tasks.\"\"\"\n    results = []\n\n    for task in task_queue:\n        if task.status != TaskStatus.PENDING:\n            continue\n\n        # Step 1: Route to appropriate sub-orchestrator domain\n        domain = meta._classify_domain(task)\n        registry = registries.get(domain)\n        matcher = matchers.get(domain)\n\n        if not registry or not matcher:\n            audit.log(\"task_created\", metadata={\n                \"task_id\": task.task_id,\n                \"status\": \"no_domain_handler\",\n                \"domain\": domain,\n            })\n            continue\n\n        # Step 2: Find and rank candidates\n        ranked = matcher.match(task, top_n=5)\n        if not ranked:\n            audit.log(\"task_created\", metadata={\n                \"task_id\": task.task_id,\n                \"status\": \"no_candidates\",\n            })\n            continue\n\n        # Step 3: Route to best worker\n        router = TaskRouter()\n        selected = router.route(task, ranked)\n\n        # Step 4: Budget check\n        budget_check = budget.check_budget(\n            selected, task.metadata.get(\"project_id\", \"default\"),\n            task.budget_usd,\n        )\n        if not budget_check[\"approved\"]:\n            audit.log(\"budget_alert\", counterparty_id=selected.agent_id,\n                      amount_usd=task.budget_usd, metadata={\n                          \"task_id\": task.task_id,\n                          \"violations\": budget_check[\"violations\"],\n                      })\n            continue\n\n        # Step 5: Create escrow and SLA\n        escrow_id = payment.create_payment(task, selected)\n        sla = create_worker_sla(task, selected)\n\n        # Step 6: Assign the task\n        assignment = assign_task(task, selected)\n\n        # Step 7: Record everything\n        audit.log(\"task_assigned\", counterparty_id=selected.agent_id,\n                  amount_usd=task.budget_usd, metadata={\n                      \"task_id\": task.task_id,\n                      \"escrow_id\": escrow_id,\n                      \"worker_type\": selected.worker_type.value,\n                      \"sla_id\": sla.get(\"sla_id\"),\n                  })\n\n        budget.record_spend(\n            selected.agent_id,\n            task.metadata.get(\"project_id\", \"default\"),\n            task.budget_usd,\n        )\n\n        results.append(assignment)\n\n    return results\n```\n\n### Initialization and Bootstrap\n\nPutting the entire system together for a production deployment:\n\n```python\ndef bootstrap_production_system():\n    \"\"\"Bootstrap a complete production workforce orchestration system.\"\"\"\n\n    # 1. Create meta-orchestrator\n    meta = MetaOrchestrator()\n\n    # 2. Register sub-orchestrators\n    meta.register_sub_orchestrator(\"ai_fleet\", [\n        \"code_review\", \"static_analysis\", \"data_validation\",\n        \"etl\", \"security_scan\", \"test_generation\",\n    ])\n    meta.register_sub_orchestrator(\"engineering\", [\n        \"architecture\", \"code_review\", \"system_design\",\n        \"debugging\", \"mentoring\", \"python\", \"go\",\n    ])\n    meta.register_sub_orchestrator(\"creative\", [\n        \"design\", \"copywriting\", \"ux_research\",\n        \"user_testing\", \"branding\",\n    ])\n\n    # 3. Initialize worker registries per domain\n    registries = {\n        \"ai_fleet\": WorkerRegistry(),\n        \"engineering\": WorkerRegistry(),\n        \"creative\": WorkerRegistry(),\n    }\n\n    # 4. Register workers\n    registries[\"ai_fleet\"].register_ai_agent(\n        \"code-review-bot\", [\"code_review\", \"static_analysis\"], 0.02)\n    registries[\"ai_fleet\"].register_ai_agent(\n        \"data-validator\", [\"data_validation\", \"etl\"], 0.05)\n    registries[\"ai_fleet\"].register_ai_agent(\n        \"security-scanner\", [\"security_scan\"], 0.03)\n\n    registries[\"engineering\"].register_gig_worker(\n        \"maria-garcia\", \"maria@freelance.dev\",\n        [\"code_review\", \"architecture\", \"python\", \"go\"], 150.0, 20)\n    registries[\"engineering\"].register_gig_worker(\n        \"james-chen\", \"james@datawork.io\",\n        [\"system_design\", \"debugging\", \"python\"], 125.0, 30)\n\n    registries[\"creative\"].register_gig_worker(\n        \"sarah-kim\", \"sarah@designops.co\",\n        [\"design\", \"ux_research\", \"branding\"], 110.0, 25)\n\n    # 5. Initialize supporting systems\n    budget = BudgetController(BudgetConfig())\n    audit = AuditLogger(meta.agent_id)\n    tax = TaxReportingEngine(meta.agent_id, audit)\n    payment = PaymentProcessor(meta.agent_id)\n\n    matchers = {\n        domain: CapabilityMatcher(reg, meta.agent_id)\n        for domain, reg in registries.items()\n    }\n\n    # 6. Log bootstrap completion\n    audit.log(\"compliance_check\", metadata={\n        \"event\": \"system_bootstrap_complete\",\n        \"sub_orchestrators\": list(meta.sub_orchestrators.keys()),\n        \"total_workers\": sum(\n            len(r._workers) for r in registries.values()\n        ),\n    })\n\n    return {\n        \"meta\": meta,\n        \"registries\": registries,\n        \"matchers\": matchers,\n        \"payment\": payment,\n        \"budget\": budget,\n        \"audit\": audit,\n        \"tax\": tax,\n    }\n\n\n# Boot the system\nsystem = bootstrap_production_system()\n\n# Run an orchestration cycle\nsample_tasks = [\n    Task(\n        title=\"Review auth module PR\",\n        required_capabilities=[\"code_review\", \"security_scan\"],\n        budget_usd=50.0,\n        priority=TaskPriority.HIGH,\n        metadata={\"project_id\": \"auth-service\", \"estimated_calls\": 20},\n    ),\n    Task(\n        title=\"Redesign onboarding flow\",\n        required_capabilities=[\"design\", \"ux_research\"],\n        budget_usd=800.0,\n        priority=TaskPriority.MEDIUM,\n        metadata={\"project_id\": \"growth\", \"estimated_hours\": 8},\n    ),\n    Task(\n        title=\"Validate Q1 revenue data\",\n        required_capabilities=[\"data_validation\"],\n        budget_usd=25.0,\n        priority=TaskPriority.LOW,\n        metadata={\"project_id\": \"finance\", \"estimated_calls\": 50},\n    ),\n]\n\nresults = run_orchestration_cycle(\n    meta=system[\"meta\"],\n    registries=system[\"registries\"],\n    matchers=system[\"matchers\"],\n    payment=system[\"payment\"],\n    budget=system[\"budget\"],\n    audit=system[\"audit\"],\n    tax=system[\"tax\"],\n    task_queue=sample_tasks,\n)\n\nfor r in results:\n    print(f\"Assigned: {r['task_id'][:8]}... -> {r['worker_name']} \"\n          f\"({r['worker_type']})\")\n```\n\n### Production Checklist\n\nBefore deploying your workforce orchestrator to production, verify every item on this list:\n\n| Category | Check | Status |\n|----------|-------|--------|\n| **Identity** | Orchestrator agent registered with production API key | |\n| **Identity** | All sub-orchestrators registered with distinct identities | |\n| **Wallet** | Master wallet funded with sufficient balance for peak month | |\n| **Wallet** | Sub-orchestrator wallets have appropriate spending limits | |\n| **Workers** | All AI agents registered with correct capabilities | |\n| **Workers** | All gig workers registered with verified email addresses | |\n| **Workers** | Service registry listings match worker capabilities | |\n| **Budget** | Per-task, per-worker, and per-project limits configured | |\n| **Budget** | Alert thresholds set and notification channel tested | |\n| **SLA** | Default SLA templates created for each worker type | |\n| **SLA** | Violation escalation pipeline tested end-to-end | |\n| **Disputes** | Auto-resolution strategies configured per dispute type | |\n| **Disputes** | Human escalation channel verified for unresolvable disputes | |\n| **Tax** | 1099 tracking initialized for current calendar year | |\n| **Tax** | Worker W-9 \u002F tax ID collection process documented | |\n| **Compliance** | Compliance check scheduled on weekly cadence | |\n| **Compliance** | Audit trail retention policy set (minimum 7 years for tax) | |\n| **Scaling** | Capacity thresholds defined per capability | |\n| **Scaling** | Auto-recruit search parameters configured | |\n| **Monitoring** | Orchestrator health check endpoint active | |\n| **Monitoring** | Budget consumption dashboard deployed | |\n\n---\n\n## What You Get\n\nThis guide gives you a production-ready workforce orchestration system that manages hybrid human+AI teams through a single agent-led architecture. Here is the complete tool surface used across all eight chapters:\n\n| Tool | Chapters | Purpose |\n|------|----------|---------|\n| `register_agent` | 2, 8 | Register orchestrator, sub-orchestrators, and workers |\n| `create_wallet` | 2, 8 | Create wallets for orchestrators and workers |\n| `register_service` | 2, 8 | List worker capabilities in the marketplace |\n| `search_services` | 3, 8 | Discover workers by capability |\n| `best_match` | 3 | Server-side shortlisting for task routing |\n| `search_agents_by_metrics` | 3, 5 | Find workers by performance metrics |\n| `send_message` | 3, 6 | Task notifications and SLA violation alerts |\n| `create_escrow` | 4 | Lock funds for task payments (AI and human) |\n| `release_escrow` | 4 | Release milestone and completion payments |\n| `create_invoice` | 4 | Generate invoices for gig worker payments |\n| `record_transaction` | 3, 4, 6, 7, 8 | Audit trail for all financial and operational events |\n| `transfer` | 4 | Direct wallet-to-wallet transfers |\n| `get_agent_reputation` | 5, 8 | Fetch worker reputation scores |\n| `submit_metrics` | 5 | Report worker performance after task completion |\n| `build_claim_chain` | 5 | Verifiable credentials for worker qualifications |\n| `get_balance` | 7 | Check orchestrator and worker wallet balances |\n| `create_sla` | 6 | Establish SLA contracts per task assignment |\n| `check_sla_compliance` | 5, 6 | Monitor SLA adherence across worker types |\n| `open_dispute` | 4, 6 | Initiate disputes for quality or deadline failures |\n| `resolve_dispute` | 6 | Automated and manual dispute resolution |\n| `check_compliance` | 7 | Platform-level compliance verification |\n| `get_analytics` | 7 | Retrieve analytics for governance reporting |\n\nTotal: 22 of 128 GreenHelix tools, covering 7 of 15 services (identity, billing, payments, marketplace, messaging, trust, reputation). The system manages the complete lifecycle of a hybrid workforce: discovery, assignment, payment, verification, reputation, compliance, and scaling -- treating human gig workers and AI agents as a unified pool of economic actors differentiated by capability, cost, and trust.\n\n",{"name":5,"tags":24,"type":31,"author":35,"install":36,"license":15,"version":37,"metadata":38,"price_usd":43,"executable":20,"credentials":44,"description":7,"content_type":45,"compatibility":46},[25,26,27,28,29,30,31,32,33,34],"workforce","orchestration","gig-economy","hybrid-teams","escrow","reputation","guide","greenhelix","openclaw","ai-agent","felix-agent","none","1.3.1",{"openclaw":39},{"requires":40,"primaryEnv":42},{"env":41},[42],"GREENHELIX_API_KEY",49,[42],"markdown",[33],"master","4aa004da461d820f4ea5499e58eb8d196cf99016","community\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-workforce-orchestration",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":57,"prompt":67,"zipAvailable":68},[58,61,64],{"tool":59,"command":60},"npx","npx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-workforce-orchestration",{"tool":62,"command":63},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-workforce-orchestration",{"tool":65,"command":66},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-workforce-orchestration","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-workforce-orchestration\u002FSKILL.md",true,[],[71,78,85,92,99,106],{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"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":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"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":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"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":93,"name":94,"nameZh":6,"description":95,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"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":100,"name":101,"nameZh":6,"description":102,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":103,"categories":104,"keywords":105,"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":107,"name":108,"nameZh":6,"description":109,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":110,"categories":111,"keywords":112,"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",[],[]]