[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M77HF5R5DP2J4EEMJKGNNKK9":3,"skill-same:01M77HF5R5DP2J4EEMJKGNNKK9":63},{"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":40,"commitSha":41,"skillDirectory":42,"forksCount":43,"repositoryHtmlUrl":44,"repositoryHomepageUrl":45,"ownerHtmlUrl":46,"ownerBlogUrl":6,"ownerDescription":47,"updatedAt":48,"install":49,"resources":62},"01M77HF5R5DP2J4EEMJKGNNKK9","greenhelix-agent-observability-stack",null,"Agent Observability Stack: Distributed Tracing, Metrics, and Alerting for Multi-Agent Systems. Build a complete observability stack for agent commerce: OpenTelemetry integration, distributed tracing across agent calls, custom metrics, anomaly detection, dashboard design, SLA monitoring, and cost attribution. Includes detailed Python code examples with full API integration.","Lord1Egypt\u002Fawesome-skill-forge","Lord1Egypt","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F99746359?v=4","01M7592YDNT0XK9WJ0T2MQVPDN","Mohamed Mounir Ali AL Keshita","01M75GRFNHC8VZNWEB8DKDE433",3,"MIT","https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-observability-stack\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: greenhelix-agent-observability-stack\nversion: \"1.3.1\"\ndescription: \"Agent Observability Stack: Distributed Tracing, Metrics, and Alerting for Multi-Agent Systems. Build a complete observability stack for agent commerce: OpenTelemetry integration, distributed tracing across agent calls, custom metrics, anomaly detection, dashboard design, SLA monitoring, and cost attribution. Includes detailed Python code examples with full API integration.\"\nlicense: MIT\ncompatibility: [openclaw]\nauthor: felix-agent\ntype: guide\ntags: [observability, monitoring, tracing, metrics, opentelemetry, guide, greenhelix, openclaw, ai-agent]\nprice_usd: 49.0\ncontent_type: markdown\nexecutable: false\ninstall: none\ncredentials: none\n---\n# Agent Observability Stack: Distributed Tracing, Metrics, and Alerting for Multi-Agent Systems\n\n> **Notice**: This is an educational guide with illustrative code examples.\n> It does not execute code, require credentials, 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\nWhen Agent A calls Agent B which calls Agent C, and the transaction takes 12 seconds instead of 200ms, where is the bottleneck? When your agent fleet processes 10,000 transactions per day and revenue drops 15%, which agent is underperforming? When an escrow settlement fails silently at 3am, how quickly do you find out? Traditional monitoring tools -- ping checks, CPU graphs, uptime dashboards -- cannot answer these questions for distributed agent systems. They were built for monoliths and simple request-response services. Agent commerce is fundamentally different: transactions span multiple autonomous agents, each with its own state, pricing, and failure modes. A single customer-facing operation might traverse five agents, two escrow contracts, and three separate billing events before completing. The failure surface is combinatorial, not linear.\nYou need observability, not just monitoring. Monitoring tells you something is broken. Observability tells you why, where, and how to fix it. For agent commerce, this means distributed tracing to follow transactions across agent boundaries, custom metrics to measure business outcomes (not just infrastructure health), and intelligent alerting to catch problems before your users do. The difference between a 15-minute outage and a 4-hour revenue leak is whether your observability stack understands agent-to-agent transaction flows.\nThis guide builds a complete observability stack from scratch. We use OpenTelemetry standards for interoperability, integrate directly with GreenHelix's metrics and event tools for agent-specific telemetry, and build anomaly detection that understands the patterns unique to agent commerce. Every component is production Python code you can deploy today. By the end, you will have distributed tracing across agent calls, custom business metrics, anomaly detection, dashboards, alerting with escalation policies, and SLA monitoring with cost attribution.\n\n## What You'll Learn\n- Chapter 1: The Three Pillars of Agent Observability\n- Chapter 2: AgentTracer Class\n- Chapter 3: Distributed Tracing Across Agent Calls\n- Chapter 4: MetricsCollector Class\n- Chapter 5: Anomaly Detection\n- Chapter 6: Dashboard Design\n- Chapter 7: AlertManager Class\n- Chapter 8: SLA Monitoring and Cost Attribution\n- What's Next\n\n## Full Guide\n\n# Agent Observability Stack: Distributed Tracing, Metrics, and Alerting for Multi-Agent Systems\n\nWhen Agent A calls Agent B which calls Agent C, and the transaction takes 12 seconds instead of 200ms, where is the bottleneck? When your agent fleet processes 10,000 transactions per day and revenue drops 15%, which agent is underperforming? When an escrow settlement fails silently at 3am, how quickly do you find out? Traditional monitoring tools -- ping checks, CPU graphs, uptime dashboards -- cannot answer these questions for distributed agent systems. They were built for monoliths and simple request-response services. Agent commerce is fundamentally different: transactions span multiple autonomous agents, each with its own state, pricing, and failure modes. A single customer-facing operation might traverse five agents, two escrow contracts, and three separate billing events before completing. The failure surface is combinatorial, not linear.\n\nYou need observability, not just monitoring. Monitoring tells you something is broken. Observability tells you why, where, and how to fix it. For agent commerce, this means distributed tracing to follow transactions across agent boundaries, custom metrics to measure business outcomes (not just infrastructure health), and intelligent alerting to catch problems before your users do. The difference between a 15-minute outage and a 4-hour revenue leak is whether your observability stack understands agent-to-agent transaction flows.\n\nThis guide builds a complete observability stack from scratch. We use OpenTelemetry standards for interoperability, integrate directly with GreenHelix's metrics and event tools for agent-specific telemetry, and build anomaly detection that understands the patterns unique to agent commerce. Every component is production Python code you can deploy today. By the end, you will have distributed tracing across agent calls, custom business metrics, anomaly detection, dashboards, alerting with escalation policies, and SLA monitoring with cost attribution.\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## Chapter 1: The Three Pillars of Agent Observability\n\nObservability for distributed systems rests on three pillars: traces, metrics, and logs. Each answers a different class of question, and none is sufficient alone. For agent commerce, each pillar has specific requirements that differ from traditional web service observability.\n\n### Traces: Following a Transaction Across Agent Boundaries\n\nA trace is the complete record of a single transaction as it flows through your system. In agent commerce, a trace might begin when a customer agent requests a service, pass through a gateway agent, invoke a specialist agent, trigger an escrow creation, wait for fulfillment, and end with settlement and payment distribution. Each step in that journey is a span, and the collection of spans forms a trace.\n\nThe critical difference from traditional distributed tracing is that agent boundaries are not just service boundaries -- they are trust boundaries. When Agent A calls Agent B, there is an economic transaction embedded in that call. The trace must capture not just latency and status codes, but also billing events, escrow state transitions, and the economic context of each span. A span that shows \"200 OK in 150ms\" is incomplete if it does not also show \"billed 0.003 credits, escrow ID esw_abc123 created.\"\n\nTraces answer questions like: Why did this specific transaction fail? Where did the latency come from? Which agent in the chain was the bottleneck? Did the billing event match the actual work performed?\n\n### Metrics: Measuring Agent Health, Performance, and Business Outcomes\n\nMetrics are aggregated numerical measurements over time. Where traces give you detail about individual transactions, metrics give you the big picture. For agent commerce, metrics fall into three categories.\n\nInfrastructure metrics measure the health of your agents as software systems: CPU usage, memory consumption, request queue depth, connection pool utilization. These are table stakes and most monitoring tools handle them well.\n\nPerformance metrics measure how your agents behave under load: request latency (p50, p95, p99), throughput (requests per second), error rates, and timeout rates. These require histograms and percentile calculations, not just averages.\n\nBusiness metrics are where agent commerce diverges from traditional services. You need to track revenue per agent, cost per transaction, escrow settlement rates, dispute rates, SLA compliance percentages, and customer satisfaction proxies. These metrics directly measure whether your agent fleet is making money or losing it.\n\nGreenHelix's `submit_metrics` tool accepts custom metric submissions, making it the natural sink for all three categories. The tool accepts metric name, value, dimensions, and timestamp, allowing you to build rich, queryable metric series.\n\n### Logs: Structured Event Logging for Debugging\n\nLogs are discrete events with context. In agent commerce, structured logs are essential because you need to correlate log events across agent boundaries. A plain text log line like \"Error processing request\" is useless when you have 50 agents each producing thousands of log lines per hour.\n\nStructured logs include the trace ID, span ID, agent ID, transaction ID, and any relevant business context as machine-parseable fields. When something goes wrong, you filter logs by trace ID and see every event from every agent involved in that transaction, in chronological order.\n\nGreenHelix's `get_events` tool retrieves event streams that serve as a structured log source. Events include agent interactions, billing events, escrow state changes, and webhook deliveries. By correlating your application logs with GreenHelix events, you get a complete picture of what happened and why.\n\n### Why All Three Matter\n\nMetrics tell you something is wrong: \"Error rate spiked to 5% at 14:32.\" Traces tell you where and why: \"Transaction txn_789 failed at Agent C because the escrow creation timed out after 30 seconds.\" Logs give you the details: \"Agent C's connection pool was exhausted because Agent D was not releasing connections after failed settlements.\"\n\nWithout metrics, you do not know there is a problem until users complain. Without traces, you cannot pinpoint which agent or which step is responsible. Without logs, you cannot understand the root cause well enough to fix it. Agent commerce multiplies this dependency because the interactions are more complex, the failure modes are more subtle, and the economic consequences of missed problems are direct and measurable.\n\n### GreenHelix Tools for Observability\n\nThree GreenHelix tools form the foundation of our observability stack:\n\n**submit_metrics** accepts custom metric data points with dimensions. We use this to push agent performance metrics, business metrics, and custom counters into GreenHelix's metric store.\n\n**get_events** retrieves event streams filtered by agent, time range, and event type. We use this to pull structured event data for trace correlation and log enrichment.\n\n**register_webhook** creates webhook subscriptions for specific event types. We use this to trigger real-time alerts when critical events occur, rather than polling for problems.\n\n```python\nfrom greenhelix import GreenHelixClient\n\nclient = GreenHelixClient(api_key=\"your-api-key\")\n\n# Submit a custom metric\nclient.execute_tool(\"submit_metrics\", {\n    \"agent_id\": \"agent-payment-processor\",\n    \"metrics\": [\n        {\n            \"name\": \"transaction.latency_ms\",\n            \"value\": 245.3,\n            \"dimensions\": {\n                \"agent\": \"agent-payment-processor\",\n                \"operation\": \"process_payment\",\n                \"status\": \"success\"\n            },\n            \"timestamp\": \"2026-04-07T14:30:00Z\"\n        }\n    ]\n})\n\n# Retrieve events for trace correlation\nevents = client.execute_tool(\"get_events\", {\n    \"agent_id\": \"agent-payment-processor\",\n    \"event_types\": [\"escrow.created\", \"escrow.settled\", \"billing.charged\"],\n    \"start_time\": \"2026-04-07T14:00:00Z\",\n    \"end_time\": \"2026-04-07T15:00:00Z\"\n})\n\n# Register a webhook for real-time alerting\nclient.execute_tool(\"register_webhook\", {\n    \"url\": \"https:\u002F\u002Falerts.myfleet.com\u002Fwebhook\",\n    \"event_types\": [\"escrow.failed\", \"billing.error\"],\n    \"agent_id\": \"agent-payment-processor\"\n})\n```\n\nThese three tools, combined with OpenTelemetry's tracing and metrics APIs, give us everything we need to build a production observability stack.\n\n---\n\n## Chapter 2: AgentTracer Class\n\nThe core of our observability stack is a tracer that understands agent commerce. Standard OpenTelemetry tracers create spans for HTTP requests and database calls. Our `AgentTracer` wraps OpenTelemetry to add agent-specific context: billing events, escrow state, economic metadata, and cross-agent trace propagation.\n\n### Design Principles\n\nThe tracer must be lightweight. Adding observability should not measurably increase transaction latency. We target less than 1ms overhead per span, which means in-memory buffering with asynchronous export.\n\nThe tracer must be OpenTelemetry-compatible. This means traces can be exported to Jaeger, Zipkin, Grafana Tempo, or any other OTel-compatible backend. We do not lock you into a proprietary format.\n\nThe tracer must understand agent commerce primitives. Spans should automatically capture billing amounts, escrow IDs, agent identities, and transaction types without requiring manual instrumentation at every call site.\n\n### The AgentTracer Implementation\n\n```python\nimport time\nimport uuid\nimport threading\nfrom dataclasses import dataclass, field\nfrom typing import Optional, Dict, Any, List\nfrom contextlib import contextmanager\nfrom opentelemetry import trace\nfrom opentelemetry.sdk.trace import TracerProvider\nfrom opentelemetry.sdk.trace.export import (\n    BatchSpanProcessor,\n    SpanExporter,\n    SpanExportResult,\n)\nfrom opentelemetry.trace import StatusCode, SpanKind\nfrom opentelemetry.context import attach, detach, set_value, get_value\n\n\n@dataclass\nclass AgentSpanAttributes:\n    \"\"\"Standard attributes for agent commerce spans.\"\"\"\n    AGENT_ID = \"agent.id\"\n    AGENT_ROLE = \"agent.role\"\n    TRANSACTION_ID = \"agent.transaction.id\"\n    ESCROW_ID = \"agent.escrow.id\"\n    BILLING_AMOUNT = \"agent.billing.amount\"\n    BILLING_CURRENCY = \"agent.billing.currency\"\n    OPERATION_TYPE = \"agent.operation.type\"\n    PEER_AGENT_ID = \"agent.peer.id\"\n    SLA_TIER = \"agent.sla.tier\"\n    COST_CENTER = \"agent.cost_center\"\n\n\nclass GreenHelixSpanExporter(SpanExporter):\n    \"\"\"Exports spans as metrics to GreenHelix submit_metrics.\"\"\"\n\n    def __init__(self, client, agent_id: str, batch_size: int = 50):\n        self._client = client\n        self._agent_id = agent_id\n        self._batch_size = batch_size\n\n    def export(self, spans) -> SpanExportResult:\n        metrics_batch = []\n        for span in spans:\n            duration_ms = (span.end_time - span.start_time) \u002F 1_000_000\n            attrs = dict(span.attributes) if span.attributes else {}\n\n            metrics_batch.append({\n                \"name\": \"agent.span.duration_ms\",\n                \"value\": duration_ms,\n                \"dimensions\": {\n                    \"agent\": self._agent_id,\n                    \"operation\": span.name,\n                    \"status\": \"ok\" if span.status.status_code == StatusCode.OK\n                             else \"error\",\n                    \"span_kind\": span.kind.name if span.kind else \"INTERNAL\",\n                    \"peer_agent\": attrs.get(AgentSpanAttributes.PEER_AGENT_ID, \"\"),\n                },\n                \"timestamp\": _ns_to_iso(span.end_time),\n            })\n\n            if AgentSpanAttributes.BILLING_AMOUNT in attrs:\n                metrics_batch.append({\n                    \"name\": \"agent.billing.amount\",\n                    \"value\": float(attrs[AgentSpanAttributes.BILLING_AMOUNT]),\n                    \"dimensions\": {\n                        \"agent\": self._agent_id,\n                        \"operation\": span.name,\n                        \"currency\": attrs.get(\n                            AgentSpanAttributes.BILLING_CURRENCY, \"credits\"\n                        ),\n                    },\n                    \"timestamp\": _ns_to_iso(span.end_time),\n                })\n\n            if len(metrics_batch) >= self._batch_size:\n                self._flush(metrics_batch)\n                metrics_batch = []\n\n        if metrics_batch:\n            self._flush(metrics_batch)\n\n        return SpanExportResult.SUCCESS\n\n    def _flush(self, metrics):\n        try:\n            self._client.execute_tool(\"submit_metrics\", {\n                \"agent_id\": self._agent_id,\n                \"metrics\": metrics,\n            })\n        except Exception:\n            return SpanExportResult.FAILURE\n\n    def shutdown(self):\n        pass\n\n\ndef _ns_to_iso(ns_timestamp: int) -> str:\n    \"\"\"Convert nanosecond timestamp to ISO 8601.\"\"\"\n    import datetime\n    dt = datetime.datetime.fromtimestamp(\n        ns_timestamp \u002F 1e9, tz=datetime.timezone.utc\n    )\n    return dt.isoformat()\n\n\nclass AgentTracer:\n    \"\"\"OpenTelemetry-compatible tracer for agent commerce.\"\"\"\n\n    def __init__(\n        self,\n        agent_id: str,\n        client=None,\n        service_name: str = None,\n        exporters: List[SpanExporter] = None,\n    ):\n        self.agent_id = agent_id\n        self._client = client\n        self._service_name = service_name or f\"agent-{agent_id}\"\n\n        provider = TracerProvider()\n\n        if client:\n            gh_exporter = GreenHelixSpanExporter(client, agent_id)\n            provider.add_span_processor(BatchSpanProcessor(gh_exporter))\n\n        if exporters:\n            for exporter in exporters:\n                provider.add_span_processor(BatchSpanProcessor(exporter))\n\n        self._provider = provider\n        self._tracer = provider.get_tracer(\n            self._service_name, schema_url=\"https:\u002F\u002Fgreenhelix.net\u002Fschemas\u002Fagent\u002F1.0\"\n        )\n\n    @contextmanager\n    def start_span(\n        self,\n        name: str,\n        kind: SpanKind = SpanKind.INTERNAL,\n        attributes: Dict[str, Any] = None,\n        peer_agent_id: str = None,\n    ):\n        \"\"\"Start a new span with agent commerce context.\"\"\"\n        attrs = {\n            AgentSpanAttributes.AGENT_ID: self.agent_id,\n        }\n        if peer_agent_id:\n            attrs[AgentSpanAttributes.PEER_AGENT_ID] = peer_agent_id\n        if attributes:\n            attrs.update(attributes)\n\n        with self._tracer.start_as_current_span(\n            name, kind=kind, attributes=attrs\n        ) as span:\n            yield span\n\n    @contextmanager\n    def trace_agent_call(\n        self,\n        target_agent_id: str,\n        operation: str,\n        transaction_id: str = None,\n    ):\n        \"\"\"Trace a call from this agent to another agent.\"\"\"\n        txn_id = transaction_id or str(uuid.uuid4())\n        attrs = {\n            AgentSpanAttributes.OPERATION_TYPE: operation,\n            AgentSpanAttributes.TRANSACTION_ID: txn_id,\n        }\n\n        with self.start_span(\n            f\"call.{target_agent_id}.{operation}\",\n            kind=SpanKind.CLIENT,\n            attributes=attrs,\n            peer_agent_id=target_agent_id,\n        ) as span:\n            yield span\n\n    @contextmanager\n    def trace_escrow(self, escrow_id: str, operation: str):\n        \"\"\"Trace an escrow lifecycle operation.\"\"\"\n        attrs = {\n            AgentSpanAttributes.ESCROW_ID: escrow_id,\n            AgentSpanAttributes.OPERATION_TYPE: f\"escrow.{operation}\",\n        }\n\n        with self.start_span(\n            f\"escrow.{operation}\",\n            kind=SpanKind.INTERNAL,\n            attributes=attrs,\n        ) as span:\n            yield span\n\n    @contextmanager\n    def trace_billing(self, amount: float, currency: str = \"credits\"):\n        \"\"\"Trace a billing event.\"\"\"\n        attrs = {\n            AgentSpanAttributes.BILLING_AMOUNT: amount,\n            AgentSpanAttributes.BILLING_CURRENCY: currency,\n            AgentSpanAttributes.OPERATION_TYPE: \"billing.charge\",\n        }\n\n        with self.start_span(\n            \"billing.charge\",\n            kind=SpanKind.INTERNAL,\n            attributes=attrs,\n        ) as span:\n            yield span\n\n    def get_trace_context(self) -> Dict[str, str]:\n        \"\"\"Extract current trace context for propagation to other agents.\"\"\"\n        span = trace.get_current_span()\n        ctx = span.get_span_context()\n        if not ctx or not ctx.is_valid:\n            return {}\n\n        return {\n            \"traceparent\": f\"00-{format(ctx.trace_id, '032x')}-\"\n                           f\"{format(ctx.span_id, '016x')}-\"\n                           f\"{'01' if ctx.trace_flags & 1 else '00'}\",\n            \"x-agent-id\": self.agent_id,\n        }\n\n    def inject_context(self, headers: Dict[str, str]) -> Dict[str, str]:\n        \"\"\"Inject trace context into outgoing request headers.\"\"\"\n        headers.update(self.get_trace_context())\n        return headers\n\n    def shutdown(self):\n        \"\"\"Flush pending spans and shut down the tracer.\"\"\"\n        self._provider.shutdown()\n```\n\n### Using the AgentTracer\n\nThe tracer integrates naturally with GreenHelix client calls. Each API interaction gets a span, and the spans automatically capture timing, status, and agent commerce attributes.\n\n```python\nfrom greenhelix import GreenHelixClient\n\nclient = GreenHelixClient(api_key=\"your-api-key\")\ntracer = AgentTracer(agent_id=\"agent-marketplace\", client=client)\n\n# Trace a multi-step transaction\nwith tracer.trace_agent_call(\"agent-data-provider\", \"fetch_dataset\") as span:\n    result = client.execute_tool(\"call_agent\", {\n        \"target\": \"agent-data-provider\",\n        \"operation\": \"fetch_dataset\",\n        \"params\": {\"dataset_id\": \"ds_12345\"},\n        \"headers\": tracer.get_trace_context(),\n    })\n    span.set_attribute(\"dataset.size_bytes\", result.get(\"size\", 0))\n\n    if result.get(\"status\") == \"error\":\n        span.set_status(StatusCode.ERROR, result.get(\"message\", \"\"))\n    else:\n        span.set_status(StatusCode.OK)\n\n# Trace an escrow lifecycle\nwith tracer.trace_escrow(\"esw_abc123\", \"create\") as span:\n    escrow = client.execute_tool(\"create_escrow\", {\n        \"amount\": 5.00,\n        \"payer\": \"agent-buyer\",\n        \"payee\": \"agent-seller\",\n    })\n    span.set_attribute(\"escrow.amount\", 5.00)\n    span.set_status(StatusCode.OK)\n```\n\nThe key design choice is that `AgentTracer` wraps OpenTelemetry rather than replacing it. You can add any standard OTel exporter (Jaeger, OTLP, console) alongside the GreenHelix exporter. This means your agent traces show up in your existing observability infrastructure without any migration.\n\nThe `GreenHelixSpanExporter` converts spans to metrics via `submit_metrics`. This dual-purpose export means every traced operation automatically generates latency and billing metrics, eliminating the need to instrument metrics separately for operations you are already tracing.\n\n---\n\n## Chapter 3: Distributed Tracing Across Agent Calls\n\nSingle-agent tracing is straightforward. The real challenge is tracing a transaction as it flows through multiple independent agents, each potentially running on different infrastructure, operated by different teams, and communicating through the GreenHelix gateway.\n\n### The Problem: Trace Context Propagation\n\nWhen Agent A calls Agent B, Agent B has no inherent knowledge of Agent A's trace. Without explicit context propagation, Agent B starts a new, disconnected trace. You end up with five isolated traces instead of one unified trace showing the complete transaction flow.\n\nThe W3C Trace Context standard solves this with two HTTP headers: `traceparent` (containing trace ID, span ID, and sampling flags) and `tracestate` (containing vendor-specific data). Our `AgentTracer` already generates these headers via `get_trace_context()`. The challenge is ensuring every agent in the chain extracts, uses, and propagates these headers.\n\n### Trace Context in Agent-to-Agent Calls\n\nHere is the pattern for traced agent-to-agent calls. The calling agent injects context into outgoing headers. The receiving agent extracts context and creates child spans.\n\n```python\n# === Calling Agent (Agent A) ===\n\nclass TracedAgentClient:\n    \"\"\"HTTP client that automatically propagates trace context.\"\"\"\n\n    def __init__(self, tracer: AgentTracer, client):\n        self._tracer = tracer\n        self._client = client\n\n    def call_agent(\n        self,\n        target_agent: str,\n        operation: str,\n        params: Dict[str, Any],\n        transaction_id: str = None,\n    ) -> Dict[str, Any]:\n        \"\"\"Call another agent with automatic trace propagation.\"\"\"\n        with self._tracer.trace_agent_call(\n            target_agent, operation, transaction_id\n        ) as span:\n            headers = self._tracer.get_trace_context()\n            headers[\"x-transaction-id\"] = transaction_id or \"\"\n\n            result = self._client.execute_tool(\"call_agent\", {\n                \"target\": target_agent,\n                \"operation\": operation,\n                \"params\": params,\n                \"headers\": headers,\n            })\n\n            span.set_attribute(\"response.status\", result.get(\"status\", \"unknown\"))\n\n            if result.get(\"error\"):\n                span.set_status(StatusCode.ERROR, result[\"error\"])\n            else:\n                span.set_status(StatusCode.OK)\n\n            return result\n\n\n# === Receiving Agent (Agent B) ===\n\nfrom opentelemetry.trace.propagation import TraceContextTextMapPropagator\nfrom opentelemetry.context import Context\n\nclass TracedAgentHandler:\n    \"\"\"Request handler that extracts and continues trace context.\"\"\"\n\n    def __init__(self, tracer: AgentTracer):\n        self._tracer = tracer\n        self._propagator = TraceContextTextMapPropagator()\n\n    def handle_request(\n        self,\n        operation: str,\n        params: Dict[str, Any],\n        headers: Dict[str, str],\n    ) -> Dict[str, Any]:\n        \"\"\"Handle an incoming agent request, continuing the trace.\"\"\"\n        # Extract trace context from incoming headers\n        ctx = self._propagator.extract(carrier=headers)\n\n        # Create a child span under the extracted context\n        token = attach(ctx)\n        try:\n            with self._tracer.start_span(\n                f\"handle.{operation}\",\n                kind=SpanKind.SERVER,\n                attributes={\n                    \"caller.agent_id\": headers.get(\"x-agent-id\", \"unknown\"),\n                    AgentSpanAttributes.OPERATION_TYPE: operation,\n                },\n            ) as span:\n                result = self._dispatch(operation, params, span)\n                return result\n        finally:\n            detach(token)\n\n    def _dispatch(\n        self, operation: str, params: Dict[str, Any], span\n    ) -> Dict[str, Any]:\n        \"\"\"Route to the appropriate operation handler.\"\"\"\n        handler = getattr(self, f\"op_{operation}\", None)\n        if not handler:\n            span.set_status(StatusCode.ERROR, f\"Unknown operation: {operation}\")\n            return {\"error\": f\"Unknown operation: {operation}\"}\n        return handler(params, span)\n```\n\n### Tracing a Complete Transaction Through Five Agents\n\nConsider an agent commerce transaction where a customer agent orders a data analysis report. The transaction flows through five agents:\n\n1. **Customer Agent** -- initiates the request\n2. **Marketplace Agent** -- matches request to provider\n3. **Data Provider Agent** -- supplies raw data\n4. **Analysis Agent** -- processes and analyzes data\n5. **Delivery Agent** -- formats and delivers the report\n\n```python\ndef traced_execute(\n    client: TracedAgentClient,\n    tracer: AgentTracer,\n    request: Dict[str, Any],\n) -> Dict[str, Any]:\n    \"\"\"Execute a full traced transaction across multiple agents.\"\"\"\n    transaction_id = str(uuid.uuid4())\n\n    with tracer.start_span(\n        \"transaction.data_analysis_report\",\n        kind=SpanKind.INTERNAL,\n        attributes={\n            AgentSpanAttributes.TRANSACTION_ID: transaction_id,\n            AgentSpanAttributes.OPERATION_TYPE: \"data_analysis_report\",\n        },\n    ) as root_span:\n\n        # Step 1: Find a provider through the marketplace\n        with tracer.start_span(\"step.find_provider\") as step_span:\n            match = client.call_agent(\n                \"agent-marketplace\",\n                \"find_provider\",\n                {\"capability\": \"data_analysis\", \"budget\": request[\"budget\"]},\n                transaction_id=transaction_id,\n            )\n            step_span.set_attribute(\"provider.matched\", match.get(\"provider_id\", \"\"))\n\n        provider_id = match[\"provider_id\"]\n\n        # Step 2: Create escrow for the transaction\n        with tracer.trace_escrow(f\"esw_{transaction_id[:8]}\", \"create\") as esc_span:\n            escrow = client.call_agent(\n                \"agent-marketplace\",\n                \"create_escrow\",\n                {\n                    \"amount\": match[\"price\"],\n                    \"payer\": request[\"customer_agent\"],\n                    \"payee\": provider_id,\n                },\n                transaction_id=transaction_id,\n            )\n            esc_span.set_attribute(\"escrow.id\", escrow.get(\"escrow_id\", \"\"))\n\n        # Step 3: Fetch raw data\n        with tracer.start_span(\"step.fetch_data\") as step_span:\n            data = client.call_agent(\n                match[\"data_source\"],\n                \"fetch_dataset\",\n                {\"dataset_id\": request[\"dataset_id\"]},\n                transaction_id=transaction_id,\n            )\n            step_span.set_attribute(\"data.records\", data.get(\"record_count\", 0))\n\n        # Step 4: Run analysis\n        with tracer.start_span(\"step.analyze\") as step_span:\n            analysis = client.call_agent(\n                provider_id,\n                \"analyze_data\",\n                {\"data\": data[\"data\"], \"analysis_type\": request[\"analysis_type\"]},\n                transaction_id=transaction_id,\n            )\n            step_span.set_attribute(\"analysis.confidence\", analysis.get(\"confidence\", 0))\n\n        # Step 5: Deliver report\n        with tracer.start_span(\"step.deliver\") as step_span:\n            delivery = client.call_agent(\n                \"agent-delivery\",\n                \"deliver_report\",\n                {\n                    \"report\": analysis[\"report\"],\n                    \"recipient\": request[\"customer_agent\"],\n                    \"format\": request.get(\"format\", \"pdf\"),\n                },\n                transaction_id=transaction_id,\n            )\n            step_span.set_attribute(\"delivery.channel\", delivery.get(\"channel\", \"\"))\n\n        # Step 6: Settle escrow\n        with tracer.trace_escrow(escrow[\"escrow_id\"], \"settle\") as esc_span:\n            settlement = client.call_agent(\n                \"agent-marketplace\",\n                \"settle_escrow\",\n                {\"escrow_id\": escrow[\"escrow_id\"]},\n                transaction_id=transaction_id,\n            )\n            esc_span.set_attribute(\"settlement.status\", settlement.get(\"status\", \"\"))\n\n        root_span.set_status(StatusCode.OK)\n        return {\n            \"transaction_id\": transaction_id,\n            \"report_url\": delivery.get(\"url\"),\n            \"total_cost\": match[\"price\"],\n        }\n```\n\n### Trace Correlation with GreenHelix Events\n\nGreenHelix events have their own event IDs. To get a complete picture, you need to correlate your OpenTelemetry trace IDs with GreenHelix event IDs. The approach is to embed the trace ID in your GreenHelix API calls and then join on it during analysis.\n\n```python\ndef trace_escrow_lifecycle(\n    tracer: AgentTracer,\n    client,\n    escrow_id: str,\n) -> Dict[str, Any]:\n    \"\"\"Trace and correlate an escrow's full lifecycle with GreenHelix events.\"\"\"\n    trace_ctx = tracer.get_trace_context()\n    trace_id = trace_ctx.get(\"traceparent\", \"\").split(\"-\")[1] if trace_ctx else \"\"\n\n    with tracer.trace_escrow(escrow_id, \"lifecycle\") as span:\n        # Fetch GreenHelix events for this escrow\n        events = client.execute_tool(\"get_events\", {\n            \"filters\": {\"escrow_id\": escrow_id},\n            \"start_time\": \"2026-04-07T00:00:00Z\",\n            \"end_time\": \"2026-04-07T23:59:59Z\",\n        })\n\n        lifecycle = {\n            \"escrow_id\": escrow_id,\n            \"trace_id\": trace_id,\n            \"events\": [],\n        }\n\n        for event in events.get(\"events\", []):\n            event_type = event.get(\"type\", \"\")\n            lifecycle[\"events\"].append({\n                \"type\": event_type,\n                \"timestamp\": event.get(\"timestamp\"),\n                \"greenhelix_event_id\": event.get(\"event_id\"),\n                \"trace_id\": trace_id,\n            })\n\n            # Create a child span for each GreenHelix event\n            with tracer.start_span(\n                f\"greenhelix.event.{event_type}\",\n                attributes={\n                    \"greenhelix.event_id\": event.get(\"event_id\", \"\"),\n                    \"greenhelix.event_type\": event_type,\n                    AgentSpanAttributes.ESCROW_ID: escrow_id,\n                },\n            ) as event_span:\n                event_span.set_status(StatusCode.OK)\n\n        span.set_attribute(\"lifecycle.event_count\", len(lifecycle[\"events\"]))\n        return lifecycle\n```\n\n### Parent-Child Span Relationships\n\nOpenTelemetry automatically manages parent-child relationships through Python context managers. When you nest `start_span` calls, each inner span becomes a child of the outer span. This creates the tree structure visible in trace visualization tools like Jaeger.\n\nFor agent commerce, the hierarchy typically looks like:\n\n```\ntransaction.data_analysis_report (root)\n  |-- step.find_provider\n  |     |-- call.agent-marketplace.find_provider (CLIENT)\n  |-- escrow.create\n  |     |-- call.agent-marketplace.create_escrow (CLIENT)\n  |-- step.fetch_data\n  |     |-- call.agent-data-source.fetch_dataset (CLIENT)\n  |-- step.analyze\n  |     |-- call.agent-analysis.analyze_data (CLIENT)\n  |-- step.deliver\n  |     |-- call.agent-delivery.deliver_report (CLIENT)\n  |-- escrow.settle\n        |-- call.agent-marketplace.settle_escrow (CLIENT)\n```\n\nEach CLIENT span on the calling side has a corresponding SERVER span on the receiving side. The trace ID is the same across all agents, so a trace visualization tool shows the entire transaction as a single, unified trace spanning all five agents.\n\n---\n\n## Chapter 4: MetricsCollector Class\n\nTracing gives you per-transaction detail. Metrics give you the aggregate view: how is the fleet performing right now, how does today compare to yesterday, and are we meeting our business targets? The `MetricsCollector` class provides a clean API for collecting, buffering, and exporting metrics from your agent fleet.\n\n### Metric Types\n\nThere are three fundamental metric types for agent commerce:\n\n**Counters** are monotonically increasing values. Use them for total requests, total errors, total revenue, and total transactions. Counters answer \"how many\" questions.\n\n**Gauges** are point-in-time values that can go up or down. Use them for active connections, queue depth, current balance, and active escrows. Gauges answer \"how much right now\" questions.\n\n**Histograms** track the distribution of values. Use them for latency, transaction amounts, and response sizes. Histograms answer \"what is the distribution\" questions, giving you percentiles (p50, p95, p99) rather than just averages.\n\n### The MetricsCollector Implementation\n\n```python\nimport time\nimport math\nimport threading\nfrom collections import defaultdict\nfrom dataclasses import dataclass, field\nfrom typing import Dict, List, Optional, Callable, Any\n\n\n@dataclass\nclass MetricPoint:\n    \"\"\"A single metric data point.\"\"\"\n    name: str\n    value: float\n    dimensions: Dict[str, str]\n    timestamp: float\n    metric_type: str  # \"counter\", \"gauge\", \"histogram\"\n\n\nclass HistogramBuckets:\n    \"\"\"Tracks value distribution for histogram metrics.\"\"\"\n\n    def __init__(self, boundaries: List[float] = None):\n        self.boundaries = boundaries or [\n            5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000\n        ]\n        self.buckets = [0] * (len(self.boundaries) + 1)\n        self.sum = 0.0\n        self.count = 0\n        self.min = float(\"inf\")\n        self.max = float(\"-inf\")\n        self._values: List[float] = []\n\n    def observe(self, value: float):\n        self.sum += value\n        self.count += 1\n        self.min = min(self.min, value)\n        self.max = max(self.max, value)\n        self._values.append(value)\n\n        for i, boundary in enumerate(self.boundaries):\n            if value \u003C= boundary:\n                self.buckets[i] += 1\n                return\n        self.buckets[-1] += 1\n\n    def percentile(self, p: float) -> float:\n        if not self._values:\n            return 0.0\n        sorted_vals = sorted(self._values)\n        idx = int(math.ceil(p \u002F 100.0 * len(sorted_vals))) - 1\n        return sorted_vals[max(0, idx)]\n\n    def reset(self):\n        self.buckets = [0] * (len(self.boundaries) + 1)\n        self.sum = 0.0\n        self.count = 0\n        self.min = float(\"inf\")\n        self.max = float(\"-inf\")\n        self._values = []\n\n\nclass MetricsCollector:\n    \"\"\"Collects, buffers, and exports agent commerce metrics.\"\"\"\n\n    def __init__(\n        self,\n        agent_id: str,\n        client=None,\n        flush_interval_seconds: float = 60.0,\n        buffer_size: int = 1000,\n    ):\n        self.agent_id = agent_id\n        self._client = client\n        self._flush_interval = flush_interval_seconds\n        self._buffer_size = buffer_size\n\n        self._counters: Dict[str, float] = defaultdict(float)\n        self._gauges: Dict[str, float] = {}\n        self._histograms: Dict[str, HistogramBuckets] = {}\n        self._buffer: List[MetricPoint] = []\n        self._lock = threading.Lock()\n\n        self._dimensions_registry: Dict[str, Dict[str, str]] = {}\n        self._flush_callbacks: List[Callable] = []\n\n        self._running = False\n        self._flush_thread: Optional[threading.Thread] = None\n\n    def start(self):\n        \"\"\"Start the background flush thread.\"\"\"\n        self._running = True\n        self._flush_thread = threading.Thread(\n            target=self._flush_loop, daemon=True\n        )\n        self._flush_thread.start()\n\n    def stop(self):\n        \"\"\"Stop the background flush thread and flush remaining metrics.\"\"\"\n        self._running = False\n        if self._flush_thread:\n            self._flush_thread.join(timeout=5.0)\n        self.flush()\n\n    # --- Counter Operations ---\n\n    def increment(\n        self,\n        name: str,\n        value: float = 1.0,\n        dimensions: Dict[str, str] = None,\n    ):\n        \"\"\"Increment a counter metric.\"\"\"\n        key = self._make_key(name, dimensions)\n        with self._lock:\n            self._counters[key] += value\n            self._dimensions_registry[key] = dimensions or {}\n            self._buffer_point(name, self._counters[key], dimensions, \"counter\")\n\n    # --- Gauge Operations ---\n\n    def gauge_set(\n        self,\n        name: str,\n        value: float,\n        dimensions: Dict[str, str] = None,\n    ):\n        \"\"\"Set a gauge metric to an absolute value.\"\"\"\n        key = self._make_key(name, dimensions)\n        with self._lock:\n            self._gauges[key] = value\n            self._dimensions_registry[key] = dimensions or {}\n            self._buffer_point(name, value, dimensions, \"gauge\")\n\n    def gauge_increment(\n        self,\n        name: str,\n        value: float = 1.0,\n        dimensions: Dict[str, str] = None,\n    ):\n        \"\"\"Increment a gauge metric.\"\"\"\n        key = self._make_key(name, dimensions)\n        with self._lock:\n            self._gauges[key] = self._gauges.get(key, 0.0) + value\n            self._dimensions_registry[key] = dimensions or {}\n            self._buffer_point(name, self._gauges[key], dimensions, \"gauge\")\n\n    # --- Histogram Operations ---\n\n    def observe(\n        self,\n        name: str,\n        value: float,\n        dimensions: Dict[str, str] = None,\n        boundaries: List[float] = None,\n    ):\n        \"\"\"Record an observation in a histogram metric.\"\"\"\n        key = self._make_key(name, dimensions)\n        with self._lock:\n            if key not in self._histograms:\n                self._histograms[key] = HistogramBuckets(boundaries)\n            self._histograms[key].observe(value)\n            self._dimensions_registry[key] = dimensions or {}\n            self._buffer_point(name, value, dimensions, \"histogram\")\n\n    # --- Business Metric Helpers ---\n\n    def record_transaction(\n        self,\n        operation: str,\n        duration_ms: float,\n        amount: float,\n        status: str,\n        peer_agent: str = \"\",\n    ):\n        \"\"\"Record a complete transaction with all standard metrics.\"\"\"\n        dims = {\n            \"operation\": operation,\n            \"status\": status,\n            \"peer_agent\": peer_agent,\n        }\n\n        self.increment(\"transactions.total\", 1.0, dims)\n        self.observe(\"transactions.duration_ms\", duration_ms, dims)\n        self.observe(\"transactions.amount\", amount, dims)\n\n        if status == \"error\":\n            self.increment(\"transactions.errors\", 1.0, dims)\n\n    def record_revenue(self, amount: float, source: str, currency: str = \"credits\"):\n        \"\"\"Record revenue from an agent operation.\"\"\"\n        dims = {\"source\": source, \"currency\": currency}\n        self.increment(\"revenue.total\", amount, dims)\n\n    def record_cost(self, amount: float, category: str, currency: str = \"credits\"):\n        \"\"\"Record a cost incurred by the agent.\"\"\"\n        dims = {\"category\": category, \"currency\": currency}\n        self.increment(\"costs.total\", amount, dims)\n\n    def record_escrow_event(self, event_type: str, amount: float, escrow_id: str):\n        \"\"\"Record an escrow lifecycle event.\"\"\"\n        dims = {\"event_type\": event_type}\n        self.increment(f\"escrow.{event_type}\", 1.0, dims)\n        self.observe(\"escrow.amount\", amount, dims)\n\n    # --- Export and Flush ---\n\n    def flush(self):\n        \"\"\"Flush buffered metrics to GreenHelix.\"\"\"\n        with self._lock:\n            if not self._buffer:\n                return\n            batch = self._buffer[:]\n            self._buffer.clear()\n\n        if self._client:\n            metrics_payload = [\n                {\n                    \"name\": point.name,\n                    \"value\": point.value,\n                    \"dimensions\": {\n                        \"agent\": self.agent_id,\n                        **point.dimensions,\n                    },\n                    \"timestamp\": _ts_to_iso(point.timestamp),\n                }\n                for point in batch\n            ]\n\n            try:\n                self._client.execute_tool(\"submit_metrics\", {\n                    \"agent_id\": self.agent_id,\n                    \"metrics\": metrics_payload,\n                })\n            except Exception as e:\n                # Re-buffer on failure for retry\n                with self._lock:\n                    self._buffer = batch + self._buffer\n                    # Prevent unbounded growth\n                    if len(self._buffer) > self._buffer_size * 2:\n                        self._buffer = self._buffer[-self._buffer_size:]\n\n        for callback in self._flush_callbacks:\n            try:\n                callback(batch)\n            except Exception:\n                pass\n\n    def get_histogram_summary(\n        self, name: str, dimensions: Dict[str, str] = None\n    ) -> Dict[str, float]:\n        \"\"\"Get summary statistics for a histogram metric.\"\"\"\n        key = self._make_key(name, dimensions)\n        with self._lock:\n            hist = self._histograms.get(key)\n            if not hist or hist.count == 0:\n                return {}\n            return {\n                \"count\": hist.count,\n                \"sum\": hist.sum,\n                \"min\": hist.min,\n                \"max\": hist.max,\n                \"avg\": hist.sum \u002F hist.count,\n                \"p50\": hist.percentile(50),\n                \"p95\": hist.percentile(95),\n                \"p99\": hist.percentile(99),\n            }\n\n    def on_flush(self, callback: Callable):\n        \"\"\"Register a callback to be called on each flush.\"\"\"\n        self._flush_callbacks.append(callback)\n\n    # --- Internal ---\n\n    def _buffer_point(\n        self,\n        name: str,\n        value: float,\n        dimensions: Dict[str, str],\n        metric_type: str,\n    ):\n        point = MetricPoint(\n            name=name,\n            value=value,\n            dimensions=dimensions or {},\n            timestamp=time.time(),\n            metric_type=metric_type,\n        )\n        self._buffer.append(point)\n\n        if len(self._buffer) >= self._buffer_size:\n            threading.Thread(target=self.flush, daemon=True).start()\n\n    def _flush_loop(self):\n        while self._running:\n            time.sleep(self._flush_interval)\n            self.flush()\n\n    @staticmethod\n    def _make_key(name: str, dimensions: Dict[str, str] = None) -> str:\n        if not dimensions:\n            return name\n        dim_str = \",\".join(f\"{k}={v}\" for k, v in sorted(dimensions.items()))\n        return f\"{name}{{{dim_str}}}\"\n\n\ndef _ts_to_iso(ts: float) -> str:\n    import datetime\n    dt = datetime.datetime.fromtimestamp(ts, tz=datetime.timezone.utc)\n    return dt.isoformat()\n```\n\n### Using the MetricsCollector\n\n```python\nclient = GreenHelixClient(api_key=\"your-api-key\")\nmetrics = MetricsCollector(agent_id=\"agent-marketplace\", client=client)\nmetrics.start()\n\n# Record a transaction\nstart = time.time()\nresult = process_order(order)\nduration_ms = (time.time() - start) * 1000\n\nmetrics.record_transaction(\n    operation=\"process_order\",\n    duration_ms=duration_ms,\n    amount=order[\"amount\"],\n    status=\"success\" if result[\"ok\"] else \"error\",\n    peer_agent=order[\"seller_agent\"],\n)\n\n# Record revenue and costs\nmetrics.record_revenue(order[\"commission\"], source=\"marketplace_fee\")\nmetrics.record_cost(order[\"gateway_fee\"], category=\"gateway\")\n\n# Record escrow events\nmetrics.record_escrow_event(\"created\", order[\"amount\"], result[\"escrow_id\"])\n\n# Get latency percentiles\nsummary = metrics.get_histogram_summary(\n    \"transactions.duration_ms\",\n    {\"operation\": \"process_order\", \"status\": \"success\"},\n)\nprint(f\"p50={summary['p50']:.0f}ms  p95={summary['p95']:.0f}ms  p99={summary['p99']:.0f}ms\")\n\n# Clean shutdown\nmetrics.stop()\n```\n\nThe `MetricsCollector` buffers metrics in memory and flushes them periodically (default 60 seconds) or when the buffer fills. This batching reduces API calls to GreenHelix while ensuring metrics are not lost. The retry logic on flush failure re-buffers metrics for the next flush cycle, with a cap to prevent unbounded memory growth.\n\n---\n\n## Chapter 5: Anomaly Detection\n\nRaw metrics are necessary but not sufficient. An agent operator managing a fleet of 50 agents cannot watch 200 dashboards for problems. You need automated anomaly detection that understands normal patterns and alerts on deviations.\n\n### Statistical Anomaly Detection for Agent Metrics\n\nAnomaly detection for agent commerce differs from traditional infrastructure monitoring in two ways. First, agent traffic patterns are often bursty and non-uniform: a marketplace agent might handle 100 requests per minute during business hours and 5 per minute overnight. Second, business metrics like revenue have seasonal patterns (daily, weekly, monthly) that must be accounted for.\n\nOur `AnomalyDetector` uses three complementary detection methods: Z-score for sudden spikes, percentage change for trend shifts, and seasonal decomposition for pattern violations.\n\n```python\nimport math\nimport time\nfrom collections import deque\nfrom dataclasses import dataclass, field\nfrom typing import Dict, List, Optional, Tuple\nfrom enum import Enum\n\n\nclass AnomalyType(Enum):\n    SPIKE = \"spike\"\n    DROP = \"drop\"\n    TREND_CHANGE = \"trend_change\"\n    SEASONAL_VIOLATION = \"seasonal_violation\"\n\n\nclass Severity(Enum):\n    LOW = \"low\"\n    MEDIUM = \"medium\"\n    HIGH = \"high\"\n    CRITICAL = \"critical\"\n\n\n@dataclass\nclass Anomaly:\n    \"\"\"A detected anomaly in a metric series.\"\"\"\n    metric_name: str\n    anomaly_type: AnomalyType\n    severity: Severity\n    current_value: float\n    expected_value: float\n    deviation: float\n    timestamp: float\n    dimensions: Dict[str, str] = field(default_factory=dict)\n    message: str = \"\"\n\n\nclass MetricWindow:\n    \"\"\"Sliding window of metric values for statistical analysis.\"\"\"\n\n    def __init__(self, window_size: int = 60):\n        self._values: deque = deque(maxlen=window_size)\n        self._timestamps: deque = deque(maxlen=window_size)\n\n    def add(self, value: float, timestamp: float = None):\n        self._values.append(value)\n        self._timestamps.append(timestamp or time.time())\n\n    @property\n    def count(self) -> int:\n        return len(self._values)\n\n    @property\n    def mean(self) -> float:\n        if not self._values:\n            return 0.0\n        return sum(self._values) \u002F len(self._values)\n\n    @property\n    def std(self) -> float:\n        if len(self._values) \u003C 2:\n            return 0.0\n        m = self.mean\n        variance = sum((v - m) ** 2 for v in self._values) \u002F (len(self._values) - 1)\n        return math.sqrt(variance)\n\n    @property\n    def values(self) -> List[float]:\n        return list(self._values)\n\n    @property\n    def latest(self) -> Optional[float]:\n        return self._values[-1] if self._values else None\n\n    def rate_of_change(self, periods: int = 5) -> Optional[float]:\n        \"\"\"Calculate rate of change over the last N periods.\"\"\"\n        if len(self._values) \u003C periods + 1:\n            return None\n        recent = list(self._values)[-periods:]\n        older = list(self._values)[-(periods + 1)]\n        if older == 0:\n            return None\n        return (recent[-1] - older) \u002F older\n\n\nclass SeasonalProfile:\n    \"\"\"Tracks seasonal patterns for a metric (hourly buckets).\"\"\"\n\n    def __init__(self, num_buckets: int = 24):\n        self._num_buckets = num_buckets\n        self._bucket_values: Dict[int, List[float]] = {\n            i: [] for i in range(num_buckets)\n        }\n\n    def add(self, value: float, timestamp: float):\n        import datetime\n        dt = datetime.datetime.fromtimestamp(timestamp, tz=datetime.timezone.utc)\n        bucket = dt.hour  # Hourly buckets\n        self._bucket_values[bucket].append(value)\n\n    def expected_value(self, timestamp: float) -> Optional[Tuple[float, float]]:\n        \"\"\"Return (mean, std) for the expected value at this time.\"\"\"\n        import datetime\n        dt = datetime.datetime.fromtimestamp(timestamp, tz=datetime.timezone.utc)\n        bucket = dt.hour\n        values = self._bucket_values.get(bucket, [])\n        if len(values) \u003C 7:  # Need at least a week of data\n            return None\n        m = sum(values) \u002F len(values)\n        variance = sum((v - m) ** 2 for v in values) \u002F (len(values) - 1)\n        return m, math.sqrt(variance)\n\n\nclass AnomalyDetector:\n    \"\"\"Detects anomalies in agent commerce metric streams.\"\"\"\n\n    def __init__(\n        self,\n        z_score_threshold: float = 3.0,\n        pct_change_threshold: float = 0.30,\n        seasonal_z_threshold: float = 2.5,\n        min_data_points: int = 20,\n    ):\n        self._z_threshold = z_score_threshold\n        self._pct_threshold = pct_change_threshold\n        self._seasonal_z_threshold = seasonal_z_threshold\n        self._min_data_points = min_data_points\n\n        self._windows: Dict[str, MetricWindow] = {}\n        self._seasonal: Dict[str, SeasonalProfile] = {}\n        self._anomaly_callbacks: List = []\n\n    def observe(\n        self,\n        metric_name: str,\n        value: float,\n        dimensions: Dict[str, str] = None,\n        timestamp: float = None,\n    ) -> List[Anomaly]:\n        \"\"\"Observe a metric value and check for anomalies.\"\"\"\n        ts = timestamp or time.time()\n        key = self._make_key(metric_name, dimensions)\n\n        if key not in self._windows:\n            self._windows[key] = MetricWindow(window_size=120)\n            self._seasonal[key] = SeasonalProfile()\n\n        window = self._windows[key]\n        seasonal = self._seasonal[key]\n\n        window.add(value, ts)\n        seasonal.add(value, ts)\n\n        anomalies = []\n\n        if window.count >= self._min_data_points:\n            # Z-score detection\n            z_anomaly = self._check_z_score(\n                metric_name, value, window, dimensions, ts\n            )\n            if z_anomaly:\n                anomalies.append(z_anomaly)\n\n            # Percentage change detection\n            pct_anomaly = self._check_pct_change(\n                metric_name, value, window, dimensions, ts\n            )\n            if pct_anomaly:\n                anomalies.append(pct_anomaly)\n\n        # Seasonal detection\n        seasonal_anomaly = self._check_seasonal(\n            metric_name, value, seasonal, dimensions, ts\n        )\n        if seasonal_anomaly:\n            anomalies.append(seasonal_anomaly)\n\n        for anomaly in anomalies:\n            for callback in self._anomaly_callbacks:\n                try:\n                    callback(anomaly)\n                except Exception:\n                    pass\n\n        return anomalies\n\n    def on_anomaly(self, callback):\n        \"\"\"Register a callback for detected anomalies.\"\"\"\n        self._anomaly_callbacks.append(callback)\n\n    def _check_z_score(\n        self,\n        metric_name: str,\n        value: float,\n        window: MetricWindow,\n        dimensions: Dict[str, str],\n        timestamp: float,\n    ) -> Optional[Anomaly]:\n        \"\"\"Detect anomalies using Z-score (standard deviations from mean).\"\"\"\n        std = window.std\n        if std == 0:\n            return None\n\n        z_score = abs(value - window.mean) \u002F std\n        if z_score \u003C self._z_threshold:\n            return None\n\n        anomaly_type = AnomalyType.SPIKE if value > window.mean else AnomalyType.DROP\n        severity = self._z_to_severity(z_score)\n\n        return Anomaly(\n            metric_name=metric_name,\n            anomaly_type=anomaly_type,\n            severity=severity,\n            current_value=value,\n            expected_value=window.mean,\n            deviation=z_score,\n            timestamp=timestamp,\n            dimensions=dimensions or {},\n            message=f\"{metric_name} is {z_score:.1f} standard deviations \"\n                    f\"{'above' if value > window.mean else 'below'} the mean \"\n                    f\"(current={value:.2f}, mean={window.mean:.2f}, std={std:.2f})\",\n        )\n\n    def _check_pct_change(\n        self,\n        metric_name: str,\n        value: float,\n        window: MetricWindow,\n        dimensions: Dict[str, str],\n        timestamp: float,\n    ) -> Optional[Anomaly]:\n        \"\"\"Detect anomalies using percentage change over recent periods.\"\"\"\n        roc = window.rate_of_change(periods=5)\n        if roc is None or abs(roc) \u003C self._pct_threshold:\n            return None\n\n        anomaly_type = (\n            AnomalyType.TREND_CHANGE\n        )\n        severity = Severity.MEDIUM if abs(roc) \u003C 0.5 else Severity.HIGH\n\n        return Anomaly(\n            metric_name=metric_name,\n            anomaly_type=anomaly_type,\n            severity=severity,\n            current_value=value,\n            expected_value=window.mean,\n            deviation=roc,\n            timestamp=timestamp,\n            dimensions=dimensions or {},\n            message=f\"{metric_name} changed by {roc*100:.1f}% over the last 5 periods \"\n                    f\"(current={value:.2f})\",\n        )\n\n    def _check_seasonal(\n        self,\n        metric_name: str,\n        value: float,\n        seasonal: SeasonalProfile,\n        dimensions: Dict[str, str],\n        timestamp: float,\n    ) -> Optional[Anomaly]:\n        \"\"\"Detect anomalies relative to seasonal patterns.\"\"\"\n        expected = seasonal.expected_value(timestamp)\n        if expected is None:\n            return None\n\n        mean, std = expected\n        if std == 0:\n            return None\n\n        z_score = abs(value - mean) \u002F std\n        if z_score \u003C self._seasonal_z_threshold:\n            return None\n\n        return Anomaly(\n            metric_name=metric_name,\n            anomaly_type=AnomalyType.SEASONAL_VIOLATION,\n            severity=self._z_to_severity(z_score),\n            current_value=value,\n            expected_value=mean,\n            deviation=z_score,\n            timestamp=timestamp,\n            dimensions=dimensions or {},\n            message=f\"{metric_name} deviates {z_score:.1f} std from seasonal expectation \"\n                    f\"(current={value:.2f}, expected={mean:.2f} +\u002F- {std:.2f})\",\n        )\n\n    @staticmethod\n    def _z_to_severity(z_score: float) -> Severity:\n        if z_score >= 5.0:\n            return Severity.CRITICAL\n        elif z_score >= 4.0:\n            return Severity.HIGH\n        elif z_score >= 3.0:\n            return Severity.MEDIUM\n        return Severity.LOW\n\n    @staticmethod\n    def _make_key(name: str, dimensions: Dict[str, str] = None) -> str:\n        if not dimensions:\n            return name\n        dim_str = \",\".join(f\"{k}={v}\" for k, v in sorted(dimensions.items()))\n        return f\"{name}{{{dim_str}}}\"\n```\n\n### Integrating Anomaly Detection with Metrics Collection\n\nThe `AnomalyDetector` works alongside the `MetricsCollector`. Feed every metric observation to both:\n\n```python\ndetector = AnomalyDetector(\n    z_score_threshold=3.0,\n    pct_change_threshold=0.30,\n    min_data_points=20,\n)\nmetrics = MetricsCollector(agent_id=\"agent-marketplace\", client=client)\n\ndef record_and_detect(\n    metric_name: str,\n    value: float,\n    dimensions: Dict[str, str] = None,\n):\n    \"\"\"Record a metric and check for anomalies in one call.\"\"\"\n    metrics.observe(metric_name, value, dimensions)\n    anomalies = detector.observe(metric_name, value, dimensions)\n\n    for anomaly in anomalies:\n        print(f\"ANOMALY: {anomaly.message}\")\n        # Feed anomaly back as a metric for meta-monitoring\n        metrics.increment(\n            \"anomalies.detected\",\n            1.0,\n            {\n                \"metric\": anomaly.metric_name,\n                \"type\": anomaly.anomaly_type.value,\n                \"severity\": anomaly.severity.value,\n            },\n        )\n\n    return anomalies\n\n# Example: detect latency spike\nrecord_and_detect(\n    \"transactions.duration_ms\",\n    12500.0,  # 12.5 seconds -- likely anomalous\n    {\"operation\": \"process_order\"},\n)\n```\n\nThe detector's sliding window approach means it adapts to changing baselines. If your agent's latency gradually increases from 200ms to 300ms over a week, the detector adjusts its baseline and does not fire false alerts. But if latency jumps from 300ms to 3000ms in one minute, the Z-score catches it immediately.\n\nThe seasonal profile prevents false alerts during known traffic patterns. If your agent processes fewer transactions overnight, a drop from 100 req\u002Fs to 10 req\u002Fs at midnight is not anomalous -- the seasonal profile knows that is normal for that hour.\n\n---\n\n## Chapter 6: Dashboard Design\n\nAnomaly detection catches problems automatically, but operators still need dashboards for situational awareness, capacity planning, and stakeholder reporting. This chapter describes the three essential dashboards for agent commerce operations, with the data sources and queries needed to populate them.\n\n### Dashboard 1: Fleet Health Overview\n\nThe fleet health dashboard is the first thing you look at when something might be wrong. It answers: \"Is everything healthy right now?\"\n\n**Key panels:**\n\n1. **Agent Status Grid** -- A grid showing every agent with color-coded health status (green\u002Fyellow\u002Fred). Data source: gauge metrics for each agent's last heartbeat timestamp and error rate. An agent is green if error rate is below 1% and last heartbeat was within 60 seconds, yellow if error rate is 1-5% or heartbeat is 60-120 seconds stale, and red otherwise.\n\n2. **Fleet Error Rate** -- A time series chart showing the aggregate error rate across all agents over the last 24 hours, with the anomaly detection threshold overlaid. Data source: counter metrics `transactions.errors` \u002F `transactions.total`, aggregated per minute.\n\n3. **Active Escrows** -- A gauge showing the current number of open (unsettled) escrows, with a trend line. A rising trend indicates settlement failures or slow processing. Data source: gauge metric `escrow.active_count`.\n\n4. **Latency Heatmap** -- A heatmap showing p95 latency for each agent over the last 6 hours. Columns are time buckets (15-minute intervals), rows are agents, and color intensity represents latency. This makes it easy to spot both fleet-wide issues (a hot column) and per-agent issues (a hot row). Data source: histogram metric `transactions.duration_ms`, p95 aggregation.\n\n5. **Alert Summary** -- A table of currently active alerts grouped by severity, with acknowledge\u002Fresolve buttons. Data source: the AlertManager's active alerts state (covered in Chapter 7).\n\n```python\ndef build_fleet_health_query(agent_ids: List[str]) -> Dict[str, Any]:\n    \"\"\"Build the query configuration for the fleet health dashboard.\"\"\"\n    return {\n        \"panels\": [\n            {\n                \"title\": \"Agent Status Grid\",\n                \"type\": \"status_grid\",\n                \"query\": {\n                    \"metrics\": [\"agent.heartbeat.age_seconds\", \"transactions.errors\"],\n                    \"group_by\": [\"agent\"],\n                    \"thresholds\": {\n                        \"green\": {\"error_rate\": 0.01, \"heartbeat_age\": 60},\n                        \"yellow\": {\"error_rate\": 0.05, \"heartbeat_age\": 120},\n                        \"red\": {\"error_rate\": 1.0, \"heartbeat_age\": float(\"inf\")},\n                    },\n                },\n            },\n            {\n                \"title\": \"Fleet Error Rate\",\n                \"type\": \"time_series\",\n                \"query\": {\n                    \"metric\": \"transactions.errors\",\n                    \"aggregation\": \"rate\",\n                    \"interval\": \"1m\",\n                    \"time_range\": \"24h\",\n                },\n            },\n            {\n                \"title\": \"Active Escrows\",\n                \"type\": \"gauge_with_trend\",\n                \"query\": {\n                    \"metric\": \"escrow.active_count\",\n                    \"aggregation\": \"latest\",\n                    \"trend_window\": \"6h\",\n                },\n            },\n            {\n                \"title\": \"Latency Heatmap\",\n                \"type\": \"heatmap\",\n                \"query\": {\n                    \"metric\": \"transactions.duration_ms\",\n                    \"aggregation\": \"p95\",\n                    \"group_by\": [\"agent\"],\n                    \"interval\": \"15m\",\n                    \"time_range\": \"6h\",\n                },\n            },\n        ],\n    }\n```\n\n### Dashboard 2: Transaction Flow\n\nThe transaction flow dashboard shows how transactions move through your agent fleet. It answers: \"What is happening to our transactions?\"\n\n**Key panels:**\n\n1. **Transaction Funnel** -- A funnel visualization showing transactions at each stage: initiated, matched, escrowed, fulfilled, settled, completed. Drop-off at each stage reveals where transactions are failing. Data source: counter metrics per transaction stage.\n\n2. **Agent-to-Agent Flow** -- A Sankey diagram or chord chart showing traffic volume between agent pairs. Thick lines indicate high-volume relationships. Clicking a flow line drills down to latency and error metrics for that specific agent pair. Data source: counter metric `transactions.total` with `peer_agent` dimension.\n\n3. **Escrow Lifecycle** -- A state diagram showing escrows in each state (pending, funded, fulfilled, settled, disputed, expired) with transition rates. Data source: counter metrics per escrow state transition.\n\n4. **Slow Transactions** -- A table of the 20 slowest transactions in the last hour, with trace IDs linked to the trace viewer. This gives operators one-click access to detailed trace analysis for the worst-performing transactions. Data source: histogram metric `transactions.duration_ms`, top-N query.\n\n5. **Transaction Volume** -- A stacked area chart showing transaction volume per operation type over the last 24 hours. Data source: counter metric `transactions.total` grouped by `operation` dimension.\n\n### Dashboard 3: Revenue and Cost\n\nThe revenue and cost dashboard is for business stakeholders and capacity planning. It answers: \"Are we making money, and where is it going?\"\n\n**Key panels:**\n\n1. **Net Revenue** -- A single large number showing today's net revenue (revenue minus costs), with comparison to same day last week. Data source: counter metrics `revenue.total` minus `costs.total`.\n\n2. **Revenue by Agent** -- A bar chart showing revenue contribution per agent. Identifies your most and least profitable agents. Data source: counter metric `revenue.total` grouped by `agent` dimension.\n\n3. **Cost Breakdown** -- A pie chart showing costs by category: gateway fees, escrow fees, infrastructure, third-party API calls. Data source: counter metric `costs.total` grouped by `category` dimension.\n\n4. **Revenue Trend** -- A time series comparing daily revenue over the last 30 days, with the anomaly detection band overlaid. Revenue drops outside the expected band trigger alerts. Data source: counter metric `revenue.total`, daily aggregation.\n\n5. **Per-Transaction Economics** -- A table showing average revenue, cost, and margin per operation type. Identifies operations that are losing money. Data source: derived from `revenue.total` and `costs.total` metrics divided by `transactions.total`, grouped by `operation`.\n\nEach dashboard should auto-refresh on a cadence appropriate to its purpose: fleet health every 30 seconds, transaction flow every minute, revenue and cost every 5 minutes. The underlying data all comes from the `MetricsCollector` metrics pushed to GreenHelix via `submit_metrics`, queried back for visualization.\n\n---\n\n## Chapter 7: AlertManager Class\n\nDashboards require someone to be watching them. Alerts push problems to the right people at the right time. The `AlertManager` evaluates alert rules against incoming metrics, deduplicates and groups related alerts, routes them through appropriate channels, and escalates when problems are not acknowledged.\n\n### Alert Rule Types\n\nThree types of alert rules cover the scenarios that matter for agent commerce:\n\n**Threshold alerts** fire when a metric crosses a static or dynamic boundary. Example: \"Error rate exceeds 5%.\" These are simple and reliable for known boundaries.\n\n**Rate-of-change alerts** fire when a metric changes too quickly. Example: \"Transaction volume dropped more than 30% in 10 minutes.\" These catch problems that threshold alerts miss because the absolute value might still be \"normal.\"\n\n**Anomaly-based alerts** fire when the `AnomalyDetector` identifies a statistical anomaly. These adapt to changing baselines and seasonal patterns, catching subtle issues that would require constantly adjusting threshold values.\n\n### The AlertManager Implementation\n\n```python\nimport time\nimport uuid\nimport threading\nimport json\nfrom dataclasses import dataclass, field\nfrom typing import Dict, List, Optional, Callable, Any\nfrom enum import Enum\nfrom collections import defaultdict\n\n\nclass AlertState(Enum):\n    FIRING = \"firing\"\n    ACKNOWLEDGED = \"acknowledged\"\n    RESOLVED = \"resolved\"\n\n\nclass AlertChannel(Enum):\n    WEBHOOK = \"webhook\"\n    EMAIL = \"email\"\n    SLACK = \"slack\"\n    PAGERDUTY = \"pagerduty\"\n\n\n@dataclass\nclass AlertRule:\n    \"\"\"Definition of an alert rule.\"\"\"\n    name: str\n    metric_name: str\n    condition: str  # \"threshold\", \"rate_of_change\", \"anomaly\"\n    threshold: Optional[float] = None\n    comparison: str = \"gt\"  # \"gt\", \"lt\", \"gte\", \"lte\"\n    window_minutes: int = 5\n    severity: str = \"medium\"\n    channels: List[AlertChannel] = field(default_factory=list)\n    dimensions_filter: Dict[str, str] = field(default_factory=dict)\n    cooldown_minutes: int = 15\n    escalation_minutes: int = 30\n    description: str = \"\"\n    runbook_url: str = \"\"\n\n\n@dataclass\nclass Alert:\n    \"\"\"An active alert instance.\"\"\"\n    id: str\n    rule: AlertRule\n    state: AlertState\n    fired_at: float\n    last_value: float\n    message: str\n    acknowledged_at: Optional[float] = None\n    acknowledged_by: Optional[str] = None\n    resolved_at: Optional[float] = None\n    escalated: bool = False\n    notification_count: int = 0\n    dimensions: Dict[str, str] = field(default_factory=dict)\n\n\nclass AlertManager:\n    \"\"\"Manages alert rules, routing, deduplication, and escalation.\"\"\"\n\n    def __init__(\n        self,\n        agent_id: str,\n        client=None,\n        anomaly_detector: \"AnomalyDetector\" = None,\n    ):\n        self.agent_id = agent_id\n        self._client = client\n        self._detector = anomaly_detector\n\n        self._rules: Dict[str, AlertRule] = {}\n        self._active_alerts: Dict[str, Alert] = {}\n        self._alert_history: List[Alert] = []\n        self._cooldowns: Dict[str, float] = {}\n        self._lock = threading.Lock()\n\n        # Channel handlers\n        self._channel_handlers: Dict[AlertChannel, Callable] = {}\n\n        # Escalation thread\n        self._running = False\n        self._escalation_thread: Optional[threading.Thread] = None\n\n    def start(self):\n        \"\"\"Start the escalation monitoring thread.\"\"\"\n        self._running = True\n        self._escalation_thread = threading.Thread(\n            target=self._escalation_loop, daemon=True\n        )\n        self._escalation_thread.start()\n\n    def stop(self):\n        self._running = False\n        if self._escalation_thread:\n            self._escalation_thread.join(timeout=5.0)\n\n    # --- Rule Management ---\n\n    def add_rule(self, rule: AlertRule):\n        \"\"\"Add an alert rule.\"\"\"\n        self._rules[rule.name] = rule\n\n    def remove_rule(self, name: str):\n        \"\"\"Remove an alert rule.\"\"\"\n        self._rules.pop(name, None)\n\n    # --- Channel Configuration ---\n\n    def register_channel(self, channel: AlertChannel, handler: Callable):\n        \"\"\"Register a notification handler for a channel.\"\"\"\n        self._channel_handlers[channel] = handler\n\n    def configure_webhook(self, url: str):\n        \"\"\"Configure webhook channel with a URL.\"\"\"\n        import urllib.request\n\n        def webhook_handler(alert: Alert, message: str):\n            payload = json.dumps({\n                \"alert_id\": alert.id,\n                \"rule\": alert.rule.name,\n                \"severity\": alert.rule.severity,\n                \"state\": alert.state.value,\n                \"message\": message,\n                \"value\": alert.last_value,\n                \"fired_at\": alert.fired_at,\n                \"agent_id\": self.agent_id,\n                \"dimensions\": alert.dimensions,\n            }).encode()\n\n            req = urllib.request.Request(\n                url,\n                data=payload,\n                headers={\"Content-Type\": \"application\u002Fjson\"},\n                method=\"POST\",\n            )\n            try:\n                urllib.request.urlopen(req, timeout=10)\n            except Exception:\n                pass\n\n        self._channel_handlers[AlertChannel.WEBHOOK] = webhook_handler\n\n    def configure_slack(self, webhook_url: str, default_channel: str = \"#alerts\"):\n        \"\"\"Configure Slack channel.\"\"\"\n        import urllib.request\n\n        def slack_handler(alert: Alert, message: str):\n            severity_emoji = {\n                \"critical\": \":red_circle:\",\n                \"high\": \":large_orange_circle:\",\n                \"medium\": \":large_yellow_circle:\",\n                \"low\": \":white_circle:\",\n            }\n            emoji = severity_emoji.get(alert.rule.severity, \":grey_question:\")\n\n            payload = json.dumps({\n                \"channel\": default_channel,\n                \"text\": f\"{emoji} *{alert.rule.name}*\\n{message}\",\n                \"attachments\": [\n                    {\n                        \"color\": {\n                            \"critical\": \"#ff0000\",\n                            \"high\": \"#ff8800\",\n                            \"medium\": \"#ffcc00\",\n                            \"low\": \"#cccccc\",\n                        }.get(alert.rule.severity, \"#cccccc\"),\n                        \"fields\": [\n                            {\"title\": \"Agent\", \"value\": self.agent_id, \"short\": True},\n                            {\"title\": \"Value\", \"value\": str(alert.last_value), \"short\": True},\n                            {\"title\": \"Severity\", \"value\": alert.rule.severity, \"short\": True},\n                            {\"title\": \"Alert ID\", \"value\": alert.id, \"short\": True},\n                        ],\n                    }\n                ],\n            }).encode()\n\n            req = urllib.request.Request(\n                webhook_url,\n                data=payload,\n                headers={\"Content-Type\": \"application\u002Fjson\"},\n                method=\"POST\",\n            )\n            try:\n                urllib.request.urlopen(req, timeout=10)\n            except Exception:\n                pass\n\n        self._channel_handlers[AlertChannel.SLACK] = slack_handler\n\n    # --- Alert Evaluation ---\n\n    def evaluate(\n        self,\n        metric_name: str,\n        value: float,\n        dimensions: Dict[str, str] = None,\n    ) -> List[Alert]:\n        \"\"\"Evaluate all rules against a metric value.\"\"\"\n        new_alerts = []\n        dims = dimensions or {}\n\n        for rule in self._rules.values():\n            if rule.metric_name != metric_name:\n                continue\n\n            # Check dimension filter\n            if rule.dimensions_filter:\n                if not all(\n                    dims.get(k) == v for k, v in rule.dimensions_filter.items()\n                ):\n                    continue\n\n            # Check cooldown\n            cooldown_key = f\"{rule.name}:{self._dim_key(dims)}\"\n            if cooldown_key in self._cooldowns:\n                if time.time() - self._cooldowns[cooldown_key] \u003C rule.cooldown_minutes * 60:\n                    continue\n\n            triggered = False\n\n            if rule.condition == \"threshold\":\n                triggered = self._check_threshold(rule, value)\n            elif rule.condition == \"rate_of_change\":\n                triggered = self._check_rate_of_change(rule, value, metric_name, dims)\n            elif rule.condition == \"anomaly\" and self._detector:\n                anomalies = self._detector.observe(metric_name, value, dims)\n                triggered = len(anomalies) > 0\n\n            if triggered:\n                alert = self._fire_alert(rule, value, dims)\n                if alert:\n                    new_alerts.append(alert)\n                    self._cooldowns[cooldown_key] = time.time()\n\n        # Check for auto-resolution\n        self._check_resolutions(metric_name, value, dims)\n\n        return new_alerts\n\n    def acknowledge(self, alert_id: str, acknowledged_by: str = \"operator\"):\n        \"\"\"Acknowledge an active alert.\"\"\"\n        with self._lock:\n            alert = self._active_alerts.get(alert_id)\n            if alert and alert.state == AlertState.FIRING:\n                alert.state = AlertState.ACKNOWLEDGED\n                alert.acknowledged_at = time.time()\n                alert.acknowledged_by = acknowledged_by\n\n    def resolve(self, alert_id: str):\n        \"\"\"Manually resolve an alert.\"\"\"\n        with self._lock:\n            alert = self._active_alerts.get(alert_id)\n            if alert:\n                alert.state = AlertState.RESOLVED\n                alert.resolved_at = time.time()\n                self._alert_history.append(alert)\n                del self._active_alerts[alert_id]\n                self._notify(alert, f\"RESOLVED: {alert.rule.name}\")\n\n    def get_active_alerts(\n        self, severity: str = None\n    ) -> List[Alert]:\n        \"\"\"Get all active (firing or acknowledged) alerts.\"\"\"\n        with self._lock:\n            alerts = list(self._active_alerts.values())\n            if severity:\n                alerts = [a for a in alerts if a.rule.severity == severity]\n            return sorted(alerts, key=lambda a: a.fired_at, reverse=True)\n\n    # --- Internal ---\n\n    def _check_threshold(self, rule: AlertRule, value: float) -> bool:\n        if rule.threshold is None:\n            return False\n        ops = {\n            \"gt\": lambda v, t: v > t,\n            \"lt\": lambda v, t: v \u003C t,\n            \"gte\": lambda v, t: v >= t,\n            \"lte\": lambda v, t: v \u003C= t,\n        }\n        op = ops.get(rule.comparison, ops[\"gt\"])\n        return op(value, rule.threshold)\n\n    def _check_rate_of_change(\n        self,\n        rule: AlertRule,\n        value: float,\n        metric_name: str,\n        dimensions: Dict[str, str],\n    ) -> bool:\n        if not self._detector:\n            return False\n        key = self._detector._make_key(metric_name, dimensions)\n        window = self._detector._windows.get(key)\n        if not window:\n            return False\n        roc = window.rate_of_change(periods=5)\n        if roc is None or rule.threshold is None:\n            return False\n        return abs(roc) > rule.threshold\n\n    def _fire_alert(\n        self,\n        rule: AlertRule,\n        value: float,\n        dimensions: Dict[str, str],\n    ) -> Optional[Alert]:\n        # Deduplicate: check if same rule + dimensions already firing\n        dedup_key = f\"{rule.name}:{self._dim_key(dimensions)}\"\n        with self._lock:\n            for alert in self._active_alerts.values():\n                existing_key = f\"{alert.rule.name}:{self._dim_key(alert.dimensions)}\"\n                if existing_key == dedup_key:\n                    # Update existing alert instead of creating new one\n                    alert.last_value = value\n                    alert.notification_count += 1\n                    return None\n\n            alert = Alert(\n                id=f\"alert_{uuid.uuid4().hex[:12]}\",\n                rule=rule,\n                state=AlertState.FIRING,\n                fired_at=time.time(),\n                last_value=value,\n                message=f\"{rule.name}: {rule.metric_name} = {value} \"\n                        f\"(threshold: {rule.comparison} {rule.threshold})\",\n                dimensions=dimensions,\n            )\n            self._active_alerts[alert.id] = alert\n\n        self._notify(alert, alert.message)\n        return alert\n\n    def _notify(self, alert: Alert, message: str):\n        for channel in alert.rule.channels:\n            handler = self._channel_handlers.get(channel)\n            if handler:\n                try:\n                    handler(alert, message)\n                except Exception:\n                    pass\n\n        # Also register webhook with GreenHelix for event-driven alerts\n        if self._client and alert.state == AlertState.FIRING:\n            try:\n                self._client.execute_tool(\"submit_metrics\", {\n                    \"agent_id\": self.agent_id,\n                    \"metrics\": [{\n                        \"name\": \"alerts.fired\",\n                        \"value\": 1,\n                        \"dimensions\": {\n                            \"rule\": alert.rule.name,\n                            \"severity\": alert.rule.severity,\n                            \"agent\": self.agent_id,\n                        },\n                    }],\n                })\n            except Exception:\n                pass\n\n    def _check_resolutions(\n        self,\n        metric_name: str,\n        value: float,\n        dimensions: Dict[str, str],\n    ):\n        \"\"\"Auto-resolve alerts when the condition clears.\"\"\"\n        with self._lock:\n            to_resolve = []\n            for alert_id, alert in self._active_alerts.items():\n                if alert.rule.metric_name != metric_name:\n                    continue\n                if alert.rule.condition == \"threshold\":\n                    if not self._check_threshold(alert.rule, value):\n                        to_resolve.append(alert_id)\n\n            for alert_id in to_resolve:\n                alert = self._active_alerts[alert_id]\n                alert.state = AlertState.RESOLVED\n                alert.resolved_at = time.time()\n                self._alert_history.append(alert)\n                del self._active_alerts[alert_id]\n                self._notify(alert, f\"RESOLVED: {alert.rule.name}\")\n\n    def _escalation_loop(self):\n        \"\"\"Periodically check for alerts needing escalation.\"\"\"\n        while self._running:\n            time.sleep(60)\n            now = time.time()\n            with self._lock:\n                for alert in self._active_alerts.values():\n                    if alert.state != AlertState.FIRING:\n                        continue\n                    if alert.escalated:\n                        continue\n                    age_minutes = (now - alert.fired_at) \u002F 60\n                    if age_minutes >= alert.rule.escalation_minutes:\n                        alert.escalated = True\n                        self._notify(\n                            alert,\n                            f\"ESCALATION: {alert.rule.name} has been firing for \"\n                            f\"{age_minutes:.0f} minutes without acknowledgment\",\n                        )\n\n    @staticmethod\n    def _dim_key(dimensions: Dict[str, str]) -> str:\n        if not dimensions:\n            return \"\"\n        return \",\".join(f\"{k}={v}\" for k, v in sorted(dimensions.items()))\n```\n\n### Configuring Alert Rules\n\nHere is a practical configuration for an agent commerce deployment:\n\n```python\nalert_manager = AlertManager(\n    agent_id=\"agent-marketplace\",\n    client=client,\n    anomaly_detector=detector,\n)\n\n# Configure notification channels\nalert_manager.configure_webhook(\"https:\u002F\u002Falerts.myfleet.com\u002Fwebhook\")\nalert_manager.configure_slack(\n    webhook_url=\"https:\u002F\u002Fhooks.slack.com\u002Fservices\u002FT00\u002FB00\u002Fxxx\",\n    default_channel=\"#agent-alerts\",\n)\n\n# Rule 1: High error rate\nalert_manager.add_rule(AlertRule(\n    name=\"high_error_rate\",\n    metric_name=\"transactions.errors\",\n    condition=\"threshold\",\n    threshold=0.05,\n    comparison=\"gt\",\n    severity=\"high\",\n    channels=[AlertChannel.SLACK, AlertChannel.WEBHOOK],\n    cooldown_minutes=15,\n    escalation_minutes=30,\n    description=\"Transaction error rate exceeds 5%\",\n    runbook_url=\"https:\u002F\u002Fwiki.myfleet.com\u002Frunbooks\u002Fhigh-error-rate\",\n))\n\n# Rule 2: Latency spike\nalert_manager.add_rule(AlertRule(\n    name=\"latency_spike\",\n    metric_name=\"transactions.duration_ms\",\n    condition=\"threshold\",\n    threshold=5000,\n    comparison=\"gt\",\n    severity=\"medium\",\n    channels=[AlertChannel.SLACK],\n    cooldown_minutes=10,\n    description=\"Transaction latency exceeds 5 seconds\",\n))\n\n# Rule 3: Revenue drop\nalert_manager.add_rule(AlertRule(\n    name=\"revenue_drop\",\n    metric_name=\"revenue.total\",\n    condition=\"rate_of_change\",\n    threshold=0.30,  # 30% drop\n    severity=\"critical\",\n    channels=[AlertChannel.SLACK, AlertChannel.PAGERDUTY, AlertChannel.WEBHOOK],\n    cooldown_minutes=60,\n    escalation_minutes=15,\n    description=\"Revenue dropped more than 30% in 5 periods\",\n))\n\n# Rule 4: Anomaly-based (uses AnomalyDetector)\nalert_manager.add_rule(AlertRule(\n    name=\"escrow_anomaly\",\n    metric_name=\"escrow.created\",\n    condition=\"anomaly\",\n    severity=\"medium\",\n    channels=[AlertChannel.SLACK],\n    cooldown_minutes=30,\n    description=\"Anomalous escrow creation pattern detected\",\n))\n\nalert_manager.start()\n\n# Evaluate metrics as they come in\nalert_manager.evaluate(\"transactions.errors\", 0.08, {\"operation\": \"process_order\"})\nalert_manager.evaluate(\"transactions.duration_ms\", 7500.0, {\"operation\": \"process_order\"})\n```\n\nThe deduplication logic prevents alert storms: if the same rule fires for the same dimensions, the existing alert is updated rather than creating a new notification. The cooldown period prevents re-firing too quickly after an alert resolves and re-triggers. The escalation thread ensures that un-acknowledged alerts get escalated to additional channels after the configured timeout.\n\n---\n\n## Chapter 8: SLA Monitoring and Cost Attribution\n\nThe final piece of the observability stack ties technical metrics to business commitments. SLA monitoring tracks whether your agents are meeting their published service level agreements. Cost attribution tracks where money is being spent and whether each agent is profitable.\n\n### SLA Definition and Tracking\n\nAn SLA for an agent commerce system typically includes:\n\n- **Availability**: the percentage of time the agent is accepting and processing requests (target: 99.9%)\n- **Latency**: the p95 or p99 response time for standard operations (target: under 500ms for p95)\n- **Error rate**: the percentage of transactions that fail (target: under 0.1%)\n- **Settlement time**: the time from escrow creation to settlement (target: under 24 hours)\n\n```python\nimport time\nfrom dataclasses import dataclass, field\nfrom typing import Dict, List, Optional, Any\n\n\n@dataclass\nclass SLADefinition:\n    \"\"\"An SLA definition with target and measurement parameters.\"\"\"\n    name: str\n    metric_name: str\n    target_value: float\n    comparison: str  # \"lte\" (latency), \"gte\" (availability), \"lte\" (error rate)\n    measurement_window: str  # \"1h\", \"24h\", \"7d\", \"30d\"\n    description: str = \"\"\n\n\n@dataclass\nclass SLAStatus:\n    \"\"\"Current status of an SLA.\"\"\"\n    definition: SLADefinition\n    current_value: float\n    compliant: bool\n    compliance_percentage: float  # % of measurement windows that met the SLA\n    last_violation: Optional[float] = None\n    violation_count: int = 0\n\n\nclass SLAMonitor:\n    \"\"\"Tracks SLA compliance for agent commerce operations.\"\"\"\n\n    def __init__(\n        self,\n        agent_id: str,\n        metrics_collector: \"MetricsCollector\",\n        client=None,\n    ):\n        self.agent_id = agent_id\n        self._metrics = metrics_collector\n        self._client = client\n        self._sla_definitions: Dict[str, SLADefinition] = {}\n        self._compliance_history: Dict[str, List[bool]] = defaultdict(list)\n        self._violation_callbacks: List = []\n\n    def define_sla(self, sla: SLADefinition):\n        \"\"\"Register an SLA definition.\"\"\"\n        self._sla_definitions[sla.name] = sla\n\n    def on_violation(self, callback):\n        \"\"\"Register a callback for SLA violations.\"\"\"\n        self._violation_callbacks.append(callback)\n\n    def check_sla(\n        self,\n        sla_name: str,\n        current_value: float,\n    ) -> SLAStatus:\n        \"\"\"Check if a metric value meets the SLA target.\"\"\"\n        sla = self._sla_definitions.get(sla_name)\n        if not sla:\n            raise ValueError(f\"Unknown SLA: {sla_name}\")\n\n        ops = {\n            \"lte\": lambda v, t: v \u003C= t,\n            \"gte\": lambda v, t: v >= t,\n            \"lt\": lambda v, t: v \u003C t,\n            \"gt\": lambda v, t: v > t,\n        }\n        op = ops.get(sla.comparison, ops[\"lte\"])\n        compliant = op(current_value, sla.target_value)\n\n        # Track compliance history\n        self._compliance_history[sla_name].append(compliant)\n\n        # Calculate compliance percentage (last 100 checks)\n        history = self._compliance_history[sla_name][-100:]\n        compliance_pct = sum(1 for c in history if c) \u002F len(history) * 100\n\n        status = SLAStatus(\n            definition=sla,\n            current_value=current_value,\n            compliant=compliant,\n            compliance_percentage=compliance_pct,\n            violation_count=sum(1 for c in history if not c),\n        )\n\n        if not compliant:\n            status.last_violation = time.time()\n\n            # Record violation metric\n            self._metrics.increment(\n                \"sla.violations\",\n                1.0,\n                {\"sla\": sla_name, \"agent\": self.agent_id},\n            )\n\n            for callback in self._violation_callbacks:\n                try:\n                    callback(status)\n                except Exception:\n                    pass\n\n        # Always record compliance percentage\n        self._metrics.gauge_set(\n            \"sla.compliance_pct\",\n            compliance_pct,\n            {\"sla\": sla_name, \"agent\": self.agent_id},\n        )\n\n        return status\n\n    def get_all_sla_status(self) -> Dict[str, SLAStatus]:\n        \"\"\"Get the last known status for all SLAs.\"\"\"\n        results = {}\n        for name in self._sla_definitions:\n            history = self._compliance_history.get(name, [])\n            if not history:\n                continue\n            last_100 = history[-100:]\n            compliance_pct = sum(1 for c in last_100 if c) \u002F len(last_100) * 100\n            results[name] = SLAStatus(\n                definition=self._sla_definitions[name],\n                current_value=0.0,  # Would need last observed value\n                compliant=last_100[-1] if last_100 else True,\n                compliance_percentage=compliance_pct,\n                violation_count=sum(1 for c in last_100 if not c),\n            )\n        return results\n```\n\n### Per-Agent Cost Attribution\n\nIn a multi-agent fleet, you need to know which agents are profitable and which are burning money. Cost attribution tracks every expense back to the agent that incurred it.\n\n```python\n@dataclass\nclass CostEntry:\n    \"\"\"A single cost entry attributed to an agent.\"\"\"\n    agent_id: str\n    category: str\n    amount: float\n    currency: str\n    timestamp: float\n    transaction_id: str = \"\"\n    description: str = \"\"\n\n\nclass CostAttributor:\n    \"\"\"Tracks and attributes costs across an agent fleet.\"\"\"\n\n    def __init__(self, metrics_collector: \"MetricsCollector\"):\n        self._metrics = metrics_collector\n        self._costs: Dict[str, List[CostEntry]] = defaultdict(list)\n        self._budgets: Dict[str, float] = {}\n        self._budget_callbacks: List = []\n\n    def record_cost(\n        self,\n        agent_id: str,\n        category: str,\n        amount: float,\n        currency: str = \"credits\",\n        transaction_id: str = \"\",\n        description: str = \"\",\n    ):\n        \"\"\"Record a cost attributed to an agent.\"\"\"\n        entry = CostEntry(\n            agent_id=agent_id,\n            category=category,\n            amount=amount,\n            currency=currency,\n            timestamp=time.time(),\n            transaction_id=transaction_id,\n            description=description,\n        )\n        self._costs[agent_id].append(entry)\n\n        self._metrics.record_cost(amount, category, currency)\n        self._metrics.increment(\n            \"cost_attribution.total\",\n            amount,\n            {\"agent\": agent_id, \"category\": category},\n        )\n\n        # Check budget\n        if agent_id in self._budgets:\n            total = self.get_agent_total(agent_id)\n            budget = self._budgets[agent_id]\n            utilization = total \u002F budget if budget > 0 else 0\n\n            self._metrics.gauge_set(\n                \"budget.utilization_pct\",\n                utilization * 100,\n                {\"agent\": agent_id},\n            )\n\n            if utilization >= 0.9:\n                for callback in self._budget_callbacks:\n                    try:\n                        callback(agent_id, total, budget, utilization)\n                    except Exception:\n                        pass\n\n    def set_budget(self, agent_id: str, budget: float):\n        \"\"\"Set a spending budget for an agent.\"\"\"\n        self._budgets[agent_id] = budget\n\n    def on_budget_warning(self, callback):\n        \"\"\"Register a callback for budget threshold warnings.\"\"\"\n        self._budget_callbacks.append(callback)\n\n    def get_agent_total(\n        self,\n        agent_id: str,\n        since: float = None,\n    ) -> float:\n        \"\"\"Get total costs for an agent since a given time.\"\"\"\n        costs = self._costs.get(agent_id, [])\n        if since:\n            costs = [c for c in costs if c.timestamp >= since]\n        return sum(c.amount for c in costs)\n\n    def get_agent_breakdown(\n        self,\n        agent_id: str,\n        since: float = None,\n    ) -> Dict[str, float]:\n        \"\"\"Get cost breakdown by category for an agent.\"\"\"\n        costs = self._costs.get(agent_id, [])\n        if since:\n            costs = [c for c in costs if c.timestamp >= since]\n        breakdown = defaultdict(float)\n        for cost in costs:\n            breakdown[cost.category] += cost.amount\n        return dict(breakdown)\n\n    def generate_monthly_report(\n        self,\n        month_start: float,\n        month_end: float,\n    ) -> Dict[str, Any]:\n        \"\"\"Generate a monthly cost attribution report.\"\"\"\n        report = {\n            \"period_start\": month_start,\n            \"period_end\": month_end,\n            \"agents\": {},\n            \"total_cost\": 0.0,\n            \"top_categories\": defaultdict(float),\n        }\n\n        for agent_id, costs in self._costs.items():\n            month_costs = [\n                c for c in costs\n                if month_start \u003C= c.timestamp \u003C= month_end\n            ]\n            if not month_costs:\n                continue\n\n            agent_total = sum(c.amount for c in month_costs)\n            breakdown = defaultdict(float)\n            for cost in month_costs:\n                breakdown[cost.category] += cost.amount\n                report[\"top_categories\"][cost.category] += cost.amount\n\n            budget = self._budgets.get(agent_id, 0)\n            report[\"agents\"][agent_id] = {\n                \"total_cost\": agent_total,\n                \"budget\": budget,\n                \"utilization_pct\": (agent_total \u002F budget * 100) if budget else 0,\n                \"transaction_count\": len(month_costs),\n                \"breakdown\": dict(breakdown),\n            }\n            report[\"total_cost\"] += agent_total\n\n        report[\"top_categories\"] = dict(\n            sorted(\n                report[\"top_categories\"].items(),\n                key=lambda x: x[1],\n                reverse=True,\n            )\n        )\n\n        return report\n```\n\n### Putting It All Together\n\nHere is how all the observability components integrate for a production agent deployment:\n\n```python\nfrom greenhelix import GreenHelixClient\n\n# Initialize core components\nclient = GreenHelixClient(api_key=\"your-api-key\")\ntracer = AgentTracer(agent_id=\"agent-marketplace\", client=client)\nmetrics = MetricsCollector(agent_id=\"agent-marketplace\", client=client)\ndetector = AnomalyDetector()\nalert_manager = AlertManager(\n    agent_id=\"agent-marketplace\", client=client, anomaly_detector=detector\n)\nsla_monitor = SLAMonitor(\n    agent_id=\"agent-marketplace\", metrics_collector=metrics, client=client\n)\ncost_tracker = CostAttributor(metrics_collector=metrics)\n\n# Define SLAs\nsla_monitor.define_sla(SLADefinition(\n    name=\"availability\",\n    metric_name=\"agent.availability_pct\",\n    target_value=99.9,\n    comparison=\"gte\",\n    measurement_window=\"24h\",\n))\n\nsla_monitor.define_sla(SLADefinition(\n    name=\"latency_p95\",\n    metric_name=\"transactions.duration_ms\",\n    target_value=500,\n    comparison=\"lte\",\n    measurement_window=\"1h\",\n))\n\n# Set budgets\ncost_tracker.set_budget(\"agent-marketplace\", budget=1000.0)\ncost_tracker.set_budget(\"agent-data-provider\", budget=500.0)\n\n# Wire SLA violations to alerts\nsla_monitor.on_violation(lambda status: alert_manager.evaluate(\n    status.definition.metric_name,\n    status.current_value,\n    {\"sla\": status.definition.name},\n))\n\n# Wire budget warnings to alerts\ncost_tracker.on_budget_warning(\n    lambda agent, total, budget, util: alert_manager.evaluate(\n        \"budget.utilization_pct\",\n        util * 100,\n        {\"agent\": agent},\n    )\n)\n\n# Start background threads\nmetrics.start()\nalert_manager.start()\n\n# Now every transaction is automatically traced, metered, checked,\n# and alerted on:\ndef handle_transaction(request):\n    with tracer.trace_agent_call(\n        request[\"target\"], request[\"operation\"]\n    ) as span:\n        start = time.time()\n        result = process(request)\n        duration_ms = (time.time() - start) * 1000\n\n        # Metrics\n        metrics.record_transaction(\n            operation=request[\"operation\"],\n            duration_ms=duration_ms,\n            amount=request.get(\"amount\", 0),\n            status=\"success\" if result[\"ok\"] else \"error\",\n            peer_agent=request[\"target\"],\n        )\n\n        # Anomaly detection + alerting\n        alert_manager.evaluate(\"transactions.duration_ms\", duration_ms)\n        alert_manager.evaluate(\n            \"transactions.errors\",\n            0 if result[\"ok\"] else 1,\n        )\n\n        # SLA check\n        sla_monitor.check_sla(\"latency_p95\", duration_ms)\n\n        # Cost attribution\n        cost_tracker.record_cost(\n            agent_id=\"agent-marketplace\",\n            category=\"gateway_fee\",\n            amount=result.get(\"fee\", 0),\n            transaction_id=result.get(\"transaction_id\", \"\"),\n        )\n\n        return result\n```\n\nThis integration means every transaction flowing through your agent automatically generates traces for debugging, metrics for dashboards, anomaly detection for automated problem finding, alerts for operator notification, SLA tracking for compliance reporting, and cost attribution for business analysis. The operational overhead is minimal -- a few milliseconds of in-process buffering per transaction -- and the visibility gain is transformative.\n\n---\n\n## What's Next\n\nThis guide built the observability stack from the bottom up: tracing, metrics, anomaly detection, dashboards, alerting, and SLA monitoring. Each component works independently but delivers maximum value when integrated.\n\nTo put this into production, start with the `AgentTracer` and `MetricsCollector`. These two components give you immediate visibility with minimal effort. Add the `AnomalyDetector` once you have a few days of baseline data. Configure the `AlertManager` with conservative thresholds and tighten them as you learn your system's normal patterns. Roll out `SLAMonitor` and `CostAttributor` when you have paying customers who need compliance reports.\n\nThe next guides in this series cover agent security hardening (protecting your fleet from adversarial agents), agent marketplace economics (pricing strategies and commission structures), and agent scaling patterns (handling 100x traffic growth without rewriting your stack). Each builds on the observability foundation established here because you cannot secure, price, or scale what you cannot see.\n\n","# Agent Observability Stack: Distributed Tracing, Metrics, and Alerting for Multi-Agent Systems\n\n> **Notice**: This is an educational guide with illustrative code examples.\n> It does not execute code, require credentials, 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\nWhen Agent A calls Agent B which calls Agent C, and the transaction takes 12 seconds instead of 200ms, where is the bottleneck? When your agent fleet processes 10,000 transactions per day and revenue drops 15%, which agent is underperforming? When an escrow settlement fails silently at 3am, how quickly do you find out? Traditional monitoring tools -- ping checks, CPU graphs, uptime dashboards -- cannot answer these questions for distributed agent systems. They were built for monoliths and simple request-response services. Agent commerce is fundamentally different: transactions span multiple autonomous agents, each with its own state, pricing, and failure modes. A single customer-facing operation might traverse five agents, two escrow contracts, and three separate billing events before completing. The failure surface is combinatorial, not linear.\nYou need observability, not just monitoring. Monitoring tells you something is broken. Observability tells you why, where, and how to fix it. For agent commerce, this means distributed tracing to follow transactions across agent boundaries, custom metrics to measure business outcomes (not just infrastructure health), and intelligent alerting to catch problems before your users do. The difference between a 15-minute outage and a 4-hour revenue leak is whether your observability stack understands agent-to-agent transaction flows.\nThis guide builds a complete observability stack from scratch. We use OpenTelemetry standards for interoperability, integrate directly with GreenHelix's metrics and event tools for agent-specific telemetry, and build anomaly detection that understands the patterns unique to agent commerce. Every component is production Python code you can deploy today. By the end, you will have distributed tracing across agent calls, custom business metrics, anomaly detection, dashboards, alerting with escalation policies, and SLA monitoring with cost attribution.\n\n## What You'll Learn\n- Chapter 1: The Three Pillars of Agent Observability\n- Chapter 2: AgentTracer Class\n- Chapter 3: Distributed Tracing Across Agent Calls\n- Chapter 4: MetricsCollector Class\n- Chapter 5: Anomaly Detection\n- Chapter 6: Dashboard Design\n- Chapter 7: AlertManager Class\n- Chapter 8: SLA Monitoring and Cost Attribution\n- What's Next\n\n## Full Guide\n\n# Agent Observability Stack: Distributed Tracing, Metrics, and Alerting for Multi-Agent Systems\n\nWhen Agent A calls Agent B which calls Agent C, and the transaction takes 12 seconds instead of 200ms, where is the bottleneck? When your agent fleet processes 10,000 transactions per day and revenue drops 15%, which agent is underperforming? When an escrow settlement fails silently at 3am, how quickly do you find out? Traditional monitoring tools -- ping checks, CPU graphs, uptime dashboards -- cannot answer these questions for distributed agent systems. They were built for monoliths and simple request-response services. Agent commerce is fundamentally different: transactions span multiple autonomous agents, each with its own state, pricing, and failure modes. A single customer-facing operation might traverse five agents, two escrow contracts, and three separate billing events before completing. The failure surface is combinatorial, not linear.\n\nYou need observability, not just monitoring. Monitoring tells you something is broken. Observability tells you why, where, and how to fix it. For agent commerce, this means distributed tracing to follow transactions across agent boundaries, custom metrics to measure business outcomes (not just infrastructure health), and intelligent alerting to catch problems before your users do. The difference between a 15-minute outage and a 4-hour revenue leak is whether your observability stack understands agent-to-agent transaction flows.\n\nThis guide builds a complete observability stack from scratch. We use OpenTelemetry standards for interoperability, integrate directly with GreenHelix's metrics and event tools for agent-specific telemetry, and build anomaly detection that understands the patterns unique to agent commerce. Every component is production Python code you can deploy today. By the end, you will have distributed tracing across agent calls, custom business metrics, anomaly detection, dashboards, alerting with escalation policies, and SLA monitoring with cost attribution.\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## Chapter 1: The Three Pillars of Agent Observability\n\nObservability for distributed systems rests on three pillars: traces, metrics, and logs. Each answers a different class of question, and none is sufficient alone. For agent commerce, each pillar has specific requirements that differ from traditional web service observability.\n\n### Traces: Following a Transaction Across Agent Boundaries\n\nA trace is the complete record of a single transaction as it flows through your system. In agent commerce, a trace might begin when a customer agent requests a service, pass through a gateway agent, invoke a specialist agent, trigger an escrow creation, wait for fulfillment, and end with settlement and payment distribution. Each step in that journey is a span, and the collection of spans forms a trace.\n\nThe critical difference from traditional distributed tracing is that agent boundaries are not just service boundaries -- they are trust boundaries. When Agent A calls Agent B, there is an economic transaction embedded in that call. The trace must capture not just latency and status codes, but also billing events, escrow state transitions, and the economic context of each span. A span that shows \"200 OK in 150ms\" is incomplete if it does not also show \"billed 0.003 credits, escrow ID esw_abc123 created.\"\n\nTraces answer questions like: Why did this specific transaction fail? Where did the latency come from? Which agent in the chain was the bottleneck? Did the billing event match the actual work performed?\n\n### Metrics: Measuring Agent Health, Performance, and Business Outcomes\n\nMetrics are aggregated numerical measurements over time. Where traces give you detail about individual transactions, metrics give you the big picture. For agent commerce, metrics fall into three categories.\n\nInfrastructure metrics measure the health of your agents as software systems: CPU usage, memory consumption, request queue depth, connection pool utilization. These are table stakes and most monitoring tools handle them well.\n\nPerformance metrics measure how your agents behave under load: request latency (p50, p95, p99), throughput (requests per second), error rates, and timeout rates. These require histograms and percentile calculations, not just averages.\n\nBusiness metrics are where agent commerce diverges from traditional services. You need to track revenue per agent, cost per transaction, escrow settlement rates, dispute rates, SLA compliance percentages, and customer satisfaction proxies. These metrics directly measure whether your agent fleet is making money or losing it.\n\nGreenHelix's `submit_metrics` tool accepts custom metric submissions, making it the natural sink for all three categories. The tool accepts metric name, value, dimensions, and timestamp, allowing you to build rich, queryable metric series.\n\n### Logs: Structured Event Logging for Debugging\n\nLogs are discrete events with context. In agent commerce, structured logs are essential because you need to correlate log events across agent boundaries. A plain text log line like \"Error processing request\" is useless when you have 50 agents each producing thousands of log lines per hour.\n\nStructured logs include the trace ID, span ID, agent ID, transaction ID, and any relevant business context as machine-parseable fields. When something goes wrong, you filter logs by trace ID and see every event from every agent involved in that transaction, in chronological order.\n\nGreenHelix's `get_events` tool retrieves event streams that serve as a structured log source. Events include agent interactions, billing events, escrow state changes, and webhook deliveries. By correlating your application logs with GreenHelix events, you get a complete picture of what happened and why.\n\n### Why All Three Matter\n\nMetrics tell you something is wrong: \"Error rate spiked to 5% at 14:32.\" Traces tell you where and why: \"Transaction txn_789 failed at Agent C because the escrow creation timed out after 30 seconds.\" Logs give you the details: \"Agent C's connection pool was exhausted because Agent D was not releasing connections after failed settlements.\"\n\nWithout metrics, you do not know there is a problem until users complain. Without traces, you cannot pinpoint which agent or which step is responsible. Without logs, you cannot understand the root cause well enough to fix it. Agent commerce multiplies this dependency because the interactions are more complex, the failure modes are more subtle, and the economic consequences of missed problems are direct and measurable.\n\n### GreenHelix Tools for Observability\n\nThree GreenHelix tools form the foundation of our observability stack:\n\n**submit_metrics** accepts custom metric data points with dimensions. We use this to push agent performance metrics, business metrics, and custom counters into GreenHelix's metric store.\n\n**get_events** retrieves event streams filtered by agent, time range, and event type. We use this to pull structured event data for trace correlation and log enrichment.\n\n**register_webhook** creates webhook subscriptions for specific event types. We use this to trigger real-time alerts when critical events occur, rather than polling for problems.\n\n```python\nfrom greenhelix import GreenHelixClient\n\nclient = GreenHelixClient(api_key=\"your-api-key\")\n\n# Submit a custom metric\nclient.execute_tool(\"submit_metrics\", {\n    \"agent_id\": \"agent-payment-processor\",\n    \"metrics\": [\n        {\n            \"name\": \"transaction.latency_ms\",\n            \"value\": 245.3,\n            \"dimensions\": {\n                \"agent\": \"agent-payment-processor\",\n                \"operation\": \"process_payment\",\n                \"status\": \"success\"\n            },\n            \"timestamp\": \"2026-04-07T14:30:00Z\"\n        }\n    ]\n})\n\n# Retrieve events for trace correlation\nevents = client.execute_tool(\"get_events\", {\n    \"agent_id\": \"agent-payment-processor\",\n    \"event_types\": [\"escrow.created\", \"escrow.settled\", \"billing.charged\"],\n    \"start_time\": \"2026-04-07T14:00:00Z\",\n    \"end_time\": \"2026-04-07T15:00:00Z\"\n})\n\n# Register a webhook for real-time alerting\nclient.execute_tool(\"register_webhook\", {\n    \"url\": \"https:\u002F\u002Falerts.myfleet.com\u002Fwebhook\",\n    \"event_types\": [\"escrow.failed\", \"billing.error\"],\n    \"agent_id\": \"agent-payment-processor\"\n})\n```\n\nThese three tools, combined with OpenTelemetry's tracing and metrics APIs, give us everything we need to build a production observability stack.\n\n---\n\n## Chapter 2: AgentTracer Class\n\nThe core of our observability stack is a tracer that understands agent commerce. Standard OpenTelemetry tracers create spans for HTTP requests and database calls. Our `AgentTracer` wraps OpenTelemetry to add agent-specific context: billing events, escrow state, economic metadata, and cross-agent trace propagation.\n\n### Design Principles\n\nThe tracer must be lightweight. Adding observability should not measurably increase transaction latency. We target less than 1ms overhead per span, which means in-memory buffering with asynchronous export.\n\nThe tracer must be OpenTelemetry-compatible. This means traces can be exported to Jaeger, Zipkin, Grafana Tempo, or any other OTel-compatible backend. We do not lock you into a proprietary format.\n\nThe tracer must understand agent commerce primitives. Spans should automatically capture billing amounts, escrow IDs, agent identities, and transaction types without requiring manual instrumentation at every call site.\n\n### The AgentTracer Implementation\n\n```python\nimport time\nimport uuid\nimport threading\nfrom dataclasses import dataclass, field\nfrom typing import Optional, Dict, Any, List\nfrom contextlib import contextmanager\nfrom opentelemetry import trace\nfrom opentelemetry.sdk.trace import TracerProvider\nfrom opentelemetry.sdk.trace.export import (\n    BatchSpanProcessor,\n    SpanExporter,\n    SpanExportResult,\n)\nfrom opentelemetry.trace import StatusCode, SpanKind\nfrom opentelemetry.context import attach, detach, set_value, get_value\n\n\n@dataclass\nclass AgentSpanAttributes:\n    \"\"\"Standard attributes for agent commerce spans.\"\"\"\n    AGENT_ID = \"agent.id\"\n    AGENT_ROLE = \"agent.role\"\n    TRANSACTION_ID = \"agent.transaction.id\"\n    ESCROW_ID = \"agent.escrow.id\"\n    BILLING_AMOUNT = \"agent.billing.amount\"\n    BILLING_CURRENCY = \"agent.billing.currency\"\n    OPERATION_TYPE = \"agent.operation.type\"\n    PEER_AGENT_ID = \"agent.peer.id\"\n    SLA_TIER = \"agent.sla.tier\"\n    COST_CENTER = \"agent.cost_center\"\n\n\nclass GreenHelixSpanExporter(SpanExporter):\n    \"\"\"Exports spans as metrics to GreenHelix submit_metrics.\"\"\"\n\n    def __init__(self, client, agent_id: str, batch_size: int = 50):\n        self._client = client\n        self._agent_id = agent_id\n        self._batch_size = batch_size\n\n    def export(self, spans) -> SpanExportResult:\n        metrics_batch = []\n        for span in spans:\n            duration_ms = (span.end_time - span.start_time) \u002F 1_000_000\n            attrs = dict(span.attributes) if span.attributes else {}\n\n            metrics_batch.append({\n                \"name\": \"agent.span.duration_ms\",\n                \"value\": duration_ms,\n                \"dimensions\": {\n                    \"agent\": self._agent_id,\n                    \"operation\": span.name,\n                    \"status\": \"ok\" if span.status.status_code == StatusCode.OK\n                             else \"error\",\n                    \"span_kind\": span.kind.name if span.kind else \"INTERNAL\",\n                    \"peer_agent\": attrs.get(AgentSpanAttributes.PEER_AGENT_ID, \"\"),\n                },\n                \"timestamp\": _ns_to_iso(span.end_time),\n            })\n\n            if AgentSpanAttributes.BILLING_AMOUNT in attrs:\n                metrics_batch.append({\n                    \"name\": \"agent.billing.amount\",\n                    \"value\": float(attrs[AgentSpanAttributes.BILLING_AMOUNT]),\n                    \"dimensions\": {\n                        \"agent\": self._agent_id,\n                        \"operation\": span.name,\n                        \"currency\": attrs.get(\n                            AgentSpanAttributes.BILLING_CURRENCY, \"credits\"\n                        ),\n                    },\n                    \"timestamp\": _ns_to_iso(span.end_time),\n                })\n\n            if len(metrics_batch) >= self._batch_size:\n                self._flush(metrics_batch)\n                metrics_batch = []\n\n        if metrics_batch:\n            self._flush(metrics_batch)\n\n        return SpanExportResult.SUCCESS\n\n    def _flush(self, metrics):\n        try:\n            self._client.execute_tool(\"submit_metrics\", {\n                \"agent_id\": self._agent_id,\n                \"metrics\": metrics,\n            })\n        except Exception:\n            return SpanExportResult.FAILURE\n\n    def shutdown(self):\n        pass\n\n\ndef _ns_to_iso(ns_timestamp: int) -> str:\n    \"\"\"Convert nanosecond timestamp to ISO 8601.\"\"\"\n    import datetime\n    dt = datetime.datetime.fromtimestamp(\n        ns_timestamp \u002F 1e9, tz=datetime.timezone.utc\n    )\n    return dt.isoformat()\n\n\nclass AgentTracer:\n    \"\"\"OpenTelemetry-compatible tracer for agent commerce.\"\"\"\n\n    def __init__(\n        self,\n        agent_id: str,\n        client=None,\n        service_name: str = None,\n        exporters: List[SpanExporter] = None,\n    ):\n        self.agent_id = agent_id\n        self._client = client\n        self._service_name = service_name or f\"agent-{agent_id}\"\n\n        provider = TracerProvider()\n\n        if client:\n            gh_exporter = GreenHelixSpanExporter(client, agent_id)\n            provider.add_span_processor(BatchSpanProcessor(gh_exporter))\n\n        if exporters:\n            for exporter in exporters:\n                provider.add_span_processor(BatchSpanProcessor(exporter))\n\n        self._provider = provider\n        self._tracer = provider.get_tracer(\n            self._service_name, schema_url=\"https:\u002F\u002Fgreenhelix.net\u002Fschemas\u002Fagent\u002F1.0\"\n        )\n\n    @contextmanager\n    def start_span(\n        self,\n        name: str,\n        kind: SpanKind = SpanKind.INTERNAL,\n        attributes: Dict[str, Any] = None,\n        peer_agent_id: str = None,\n    ):\n        \"\"\"Start a new span with agent commerce context.\"\"\"\n        attrs = {\n            AgentSpanAttributes.AGENT_ID: self.agent_id,\n        }\n        if peer_agent_id:\n            attrs[AgentSpanAttributes.PEER_AGENT_ID] = peer_agent_id\n        if attributes:\n            attrs.update(attributes)\n\n        with self._tracer.start_as_current_span(\n            name, kind=kind, attributes=attrs\n        ) as span:\n            yield span\n\n    @contextmanager\n    def trace_agent_call(\n        self,\n        target_agent_id: str,\n        operation: str,\n        transaction_id: str = None,\n    ):\n        \"\"\"Trace a call from this agent to another agent.\"\"\"\n        txn_id = transaction_id or str(uuid.uuid4())\n        attrs = {\n            AgentSpanAttributes.OPERATION_TYPE: operation,\n            AgentSpanAttributes.TRANSACTION_ID: txn_id,\n        }\n\n        with self.start_span(\n            f\"call.{target_agent_id}.{operation}\",\n            kind=SpanKind.CLIENT,\n            attributes=attrs,\n            peer_agent_id=target_agent_id,\n        ) as span:\n            yield span\n\n    @contextmanager\n    def trace_escrow(self, escrow_id: str, operation: str):\n        \"\"\"Trace an escrow lifecycle operation.\"\"\"\n        attrs = {\n            AgentSpanAttributes.ESCROW_ID: escrow_id,\n            AgentSpanAttributes.OPERATION_TYPE: f\"escrow.{operation}\",\n        }\n\n        with self.start_span(\n            f\"escrow.{operation}\",\n            kind=SpanKind.INTERNAL,\n            attributes=attrs,\n        ) as span:\n            yield span\n\n    @contextmanager\n    def trace_billing(self, amount: float, currency: str = \"credits\"):\n        \"\"\"Trace a billing event.\"\"\"\n        attrs = {\n            AgentSpanAttributes.BILLING_AMOUNT: amount,\n            AgentSpanAttributes.BILLING_CURRENCY: currency,\n            AgentSpanAttributes.OPERATION_TYPE: \"billing.charge\",\n        }\n\n        with self.start_span(\n            \"billing.charge\",\n            kind=SpanKind.INTERNAL,\n            attributes=attrs,\n        ) as span:\n            yield span\n\n    def get_trace_context(self) -> Dict[str, str]:\n        \"\"\"Extract current trace context for propagation to other agents.\"\"\"\n        span = trace.get_current_span()\n        ctx = span.get_span_context()\n        if not ctx or not ctx.is_valid:\n            return {}\n\n        return {\n            \"traceparent\": f\"00-{format(ctx.trace_id, '032x')}-\"\n                           f\"{format(ctx.span_id, '016x')}-\"\n                           f\"{'01' if ctx.trace_flags & 1 else '00'}\",\n            \"x-agent-id\": self.agent_id,\n        }\n\n    def inject_context(self, headers: Dict[str, str]) -> Dict[str, str]:\n        \"\"\"Inject trace context into outgoing request headers.\"\"\"\n        headers.update(self.get_trace_context())\n        return headers\n\n    def shutdown(self):\n        \"\"\"Flush pending spans and shut down the tracer.\"\"\"\n        self._provider.shutdown()\n```\n\n### Using the AgentTracer\n\nThe tracer integrates naturally with GreenHelix client calls. Each API interaction gets a span, and the spans automatically capture timing, status, and agent commerce attributes.\n\n```python\nfrom greenhelix import GreenHelixClient\n\nclient = GreenHelixClient(api_key=\"your-api-key\")\ntracer = AgentTracer(agent_id=\"agent-marketplace\", client=client)\n\n# Trace a multi-step transaction\nwith tracer.trace_agent_call(\"agent-data-provider\", \"fetch_dataset\") as span:\n    result = client.execute_tool(\"call_agent\", {\n        \"target\": \"agent-data-provider\",\n        \"operation\": \"fetch_dataset\",\n        \"params\": {\"dataset_id\": \"ds_12345\"},\n        \"headers\": tracer.get_trace_context(),\n    })\n    span.set_attribute(\"dataset.size_bytes\", result.get(\"size\", 0))\n\n    if result.get(\"status\") == \"error\":\n        span.set_status(StatusCode.ERROR, result.get(\"message\", \"\"))\n    else:\n        span.set_status(StatusCode.OK)\n\n# Trace an escrow lifecycle\nwith tracer.trace_escrow(\"esw_abc123\", \"create\") as span:\n    escrow = client.execute_tool(\"create_escrow\", {\n        \"amount\": 5.00,\n        \"payer\": \"agent-buyer\",\n        \"payee\": \"agent-seller\",\n    })\n    span.set_attribute(\"escrow.amount\", 5.00)\n    span.set_status(StatusCode.OK)\n```\n\nThe key design choice is that `AgentTracer` wraps OpenTelemetry rather than replacing it. You can add any standard OTel exporter (Jaeger, OTLP, console) alongside the GreenHelix exporter. This means your agent traces show up in your existing observability infrastructure without any migration.\n\nThe `GreenHelixSpanExporter` converts spans to metrics via `submit_metrics`. This dual-purpose export means every traced operation automatically generates latency and billing metrics, eliminating the need to instrument metrics separately for operations you are already tracing.\n\n---\n\n## Chapter 3: Distributed Tracing Across Agent Calls\n\nSingle-agent tracing is straightforward. The real challenge is tracing a transaction as it flows through multiple independent agents, each potentially running on different infrastructure, operated by different teams, and communicating through the GreenHelix gateway.\n\n### The Problem: Trace Context Propagation\n\nWhen Agent A calls Agent B, Agent B has no inherent knowledge of Agent A's trace. Without explicit context propagation, Agent B starts a new, disconnected trace. You end up with five isolated traces instead of one unified trace showing the complete transaction flow.\n\nThe W3C Trace Context standard solves this with two HTTP headers: `traceparent` (containing trace ID, span ID, and sampling flags) and `tracestate` (containing vendor-specific data). Our `AgentTracer` already generates these headers via `get_trace_context()`. The challenge is ensuring every agent in the chain extracts, uses, and propagates these headers.\n\n### Trace Context in Agent-to-Agent Calls\n\nHere is the pattern for traced agent-to-agent calls. The calling agent injects context into outgoing headers. The receiving agent extracts context and creates child spans.\n\n```python\n# === Calling Agent (Agent A) ===\n\nclass TracedAgentClient:\n    \"\"\"HTTP client that automatically propagates trace context.\"\"\"\n\n    def __init__(self, tracer: AgentTracer, client):\n        self._tracer = tracer\n        self._client = client\n\n    def call_agent(\n        self,\n        target_agent: str,\n        operation: str,\n        params: Dict[str, Any],\n        transaction_id: str = None,\n    ) -> Dict[str, Any]:\n        \"\"\"Call another agent with automatic trace propagation.\"\"\"\n        with self._tracer.trace_agent_call(\n            target_agent, operation, transaction_id\n        ) as span:\n            headers = self._tracer.get_trace_context()\n            headers[\"x-transaction-id\"] = transaction_id or \"\"\n\n            result = self._client.execute_tool(\"call_agent\", {\n                \"target\": target_agent,\n                \"operation\": operation,\n                \"params\": params,\n                \"headers\": headers,\n            })\n\n            span.set_attribute(\"response.status\", result.get(\"status\", \"unknown\"))\n\n            if result.get(\"error\"):\n                span.set_status(StatusCode.ERROR, result[\"error\"])\n            else:\n                span.set_status(StatusCode.OK)\n\n            return result\n\n\n# === Receiving Agent (Agent B) ===\n\nfrom opentelemetry.trace.propagation import TraceContextTextMapPropagator\nfrom opentelemetry.context import Context\n\nclass TracedAgentHandler:\n    \"\"\"Request handler that extracts and continues trace context.\"\"\"\n\n    def __init__(self, tracer: AgentTracer):\n        self._tracer = tracer\n        self._propagator = TraceContextTextMapPropagator()\n\n    def handle_request(\n        self,\n        operation: str,\n        params: Dict[str, Any],\n        headers: Dict[str, str],\n    ) -> Dict[str, Any]:\n        \"\"\"Handle an incoming agent request, continuing the trace.\"\"\"\n        # Extract trace context from incoming headers\n        ctx = self._propagator.extract(carrier=headers)\n\n        # Create a child span under the extracted context\n        token = attach(ctx)\n        try:\n            with self._tracer.start_span(\n                f\"handle.{operation}\",\n                kind=SpanKind.SERVER,\n                attributes={\n                    \"caller.agent_id\": headers.get(\"x-agent-id\", \"unknown\"),\n                    AgentSpanAttributes.OPERATION_TYPE: operation,\n                },\n            ) as span:\n                result = self._dispatch(operation, params, span)\n                return result\n        finally:\n            detach(token)\n\n    def _dispatch(\n        self, operation: str, params: Dict[str, Any], span\n    ) -> Dict[str, Any]:\n        \"\"\"Route to the appropriate operation handler.\"\"\"\n        handler = getattr(self, f\"op_{operation}\", None)\n        if not handler:\n            span.set_status(StatusCode.ERROR, f\"Unknown operation: {operation}\")\n            return {\"error\": f\"Unknown operation: {operation}\"}\n        return handler(params, span)\n```\n\n### Tracing a Complete Transaction Through Five Agents\n\nConsider an agent commerce transaction where a customer agent orders a data analysis report. The transaction flows through five agents:\n\n1. **Customer Agent** -- initiates the request\n2. **Marketplace Agent** -- matches request to provider\n3. **Data Provider Agent** -- supplies raw data\n4. **Analysis Agent** -- processes and analyzes data\n5. **Delivery Agent** -- formats and delivers the report\n\n```python\ndef traced_execute(\n    client: TracedAgentClient,\n    tracer: AgentTracer,\n    request: Dict[str, Any],\n) -> Dict[str, Any]:\n    \"\"\"Execute a full traced transaction across multiple agents.\"\"\"\n    transaction_id = str(uuid.uuid4())\n\n    with tracer.start_span(\n        \"transaction.data_analysis_report\",\n        kind=SpanKind.INTERNAL,\n        attributes={\n            AgentSpanAttributes.TRANSACTION_ID: transaction_id,\n            AgentSpanAttributes.OPERATION_TYPE: \"data_analysis_report\",\n        },\n    ) as root_span:\n\n        # Step 1: Find a provider through the marketplace\n        with tracer.start_span(\"step.find_provider\") as step_span:\n            match = client.call_agent(\n                \"agent-marketplace\",\n                \"find_provider\",\n                {\"capability\": \"data_analysis\", \"budget\": request[\"budget\"]},\n                transaction_id=transaction_id,\n            )\n            step_span.set_attribute(\"provider.matched\", match.get(\"provider_id\", \"\"))\n\n        provider_id = match[\"provider_id\"]\n\n        # Step 2: Create escrow for the transaction\n        with tracer.trace_escrow(f\"esw_{transaction_id[:8]}\", \"create\") as esc_span:\n            escrow = client.call_agent(\n                \"agent-marketplace\",\n                \"create_escrow\",\n                {\n                    \"amount\": match[\"price\"],\n                    \"payer\": request[\"customer_agent\"],\n                    \"payee\": provider_id,\n                },\n                transaction_id=transaction_id,\n            )\n            esc_span.set_attribute(\"escrow.id\", escrow.get(\"escrow_id\", \"\"))\n\n        # Step 3: Fetch raw data\n        with tracer.start_span(\"step.fetch_data\") as step_span:\n            data = client.call_agent(\n                match[\"data_source\"],\n                \"fetch_dataset\",\n                {\"dataset_id\": request[\"dataset_id\"]},\n                transaction_id=transaction_id,\n            )\n            step_span.set_attribute(\"data.records\", data.get(\"record_count\", 0))\n\n        # Step 4: Run analysis\n        with tracer.start_span(\"step.analyze\") as step_span:\n            analysis = client.call_agent(\n                provider_id,\n                \"analyze_data\",\n                {\"data\": data[\"data\"], \"analysis_type\": request[\"analysis_type\"]},\n                transaction_id=transaction_id,\n            )\n            step_span.set_attribute(\"analysis.confidence\", analysis.get(\"confidence\", 0))\n\n        # Step 5: Deliver report\n        with tracer.start_span(\"step.deliver\") as step_span:\n            delivery = client.call_agent(\n                \"agent-delivery\",\n                \"deliver_report\",\n                {\n                    \"report\": analysis[\"report\"],\n                    \"recipient\": request[\"customer_agent\"],\n                    \"format\": request.get(\"format\", \"pdf\"),\n                },\n                transaction_id=transaction_id,\n            )\n            step_span.set_attribute(\"delivery.channel\", delivery.get(\"channel\", \"\"))\n\n        # Step 6: Settle escrow\n        with tracer.trace_escrow(escrow[\"escrow_id\"], \"settle\") as esc_span:\n            settlement = client.call_agent(\n                \"agent-marketplace\",\n                \"settle_escrow\",\n                {\"escrow_id\": escrow[\"escrow_id\"]},\n                transaction_id=transaction_id,\n            )\n            esc_span.set_attribute(\"settlement.status\", settlement.get(\"status\", \"\"))\n\n        root_span.set_status(StatusCode.OK)\n        return {\n            \"transaction_id\": transaction_id,\n            \"report_url\": delivery.get(\"url\"),\n            \"total_cost\": match[\"price\"],\n        }\n```\n\n### Trace Correlation with GreenHelix Events\n\nGreenHelix events have their own event IDs. To get a complete picture, you need to correlate your OpenTelemetry trace IDs with GreenHelix event IDs. The approach is to embed the trace ID in your GreenHelix API calls and then join on it during analysis.\n\n```python\ndef trace_escrow_lifecycle(\n    tracer: AgentTracer,\n    client,\n    escrow_id: str,\n) -> Dict[str, Any]:\n    \"\"\"Trace and correlate an escrow's full lifecycle with GreenHelix events.\"\"\"\n    trace_ctx = tracer.get_trace_context()\n    trace_id = trace_ctx.get(\"traceparent\", \"\").split(\"-\")[1] if trace_ctx else \"\"\n\n    with tracer.trace_escrow(escrow_id, \"lifecycle\") as span:\n        # Fetch GreenHelix events for this escrow\n        events = client.execute_tool(\"get_events\", {\n            \"filters\": {\"escrow_id\": escrow_id},\n            \"start_time\": \"2026-04-07T00:00:00Z\",\n            \"end_time\": \"2026-04-07T23:59:59Z\",\n        })\n\n        lifecycle = {\n            \"escrow_id\": escrow_id,\n            \"trace_id\": trace_id,\n            \"events\": [],\n        }\n\n        for event in events.get(\"events\", []):\n            event_type = event.get(\"type\", \"\")\n            lifecycle[\"events\"].append({\n                \"type\": event_type,\n                \"timestamp\": event.get(\"timestamp\"),\n                \"greenhelix_event_id\": event.get(\"event_id\"),\n                \"trace_id\": trace_id,\n            })\n\n            # Create a child span for each GreenHelix event\n            with tracer.start_span(\n                f\"greenhelix.event.{event_type}\",\n                attributes={\n                    \"greenhelix.event_id\": event.get(\"event_id\", \"\"),\n                    \"greenhelix.event_type\": event_type,\n                    AgentSpanAttributes.ESCROW_ID: escrow_id,\n                },\n            ) as event_span:\n                event_span.set_status(StatusCode.OK)\n\n        span.set_attribute(\"lifecycle.event_count\", len(lifecycle[\"events\"]))\n        return lifecycle\n```\n\n### Parent-Child Span Relationships\n\nOpenTelemetry automatically manages parent-child relationships through Python context managers. When you nest `start_span` calls, each inner span becomes a child of the outer span. This creates the tree structure visible in trace visualization tools like Jaeger.\n\nFor agent commerce, the hierarchy typically looks like:\n\n```\ntransaction.data_analysis_report (root)\n  |-- step.find_provider\n  |     |-- call.agent-marketplace.find_provider (CLIENT)\n  |-- escrow.create\n  |     |-- call.agent-marketplace.create_escrow (CLIENT)\n  |-- step.fetch_data\n  |     |-- call.agent-data-source.fetch_dataset (CLIENT)\n  |-- step.analyze\n  |     |-- call.agent-analysis.analyze_data (CLIENT)\n  |-- step.deliver\n  |     |-- call.agent-delivery.deliver_report (CLIENT)\n  |-- escrow.settle\n        |-- call.agent-marketplace.settle_escrow (CLIENT)\n```\n\nEach CLIENT span on the calling side has a corresponding SERVER span on the receiving side. The trace ID is the same across all agents, so a trace visualization tool shows the entire transaction as a single, unified trace spanning all five agents.\n\n---\n\n## Chapter 4: MetricsCollector Class\n\nTracing gives you per-transaction detail. Metrics give you the aggregate view: how is the fleet performing right now, how does today compare to yesterday, and are we meeting our business targets? The `MetricsCollector` class provides a clean API for collecting, buffering, and exporting metrics from your agent fleet.\n\n### Metric Types\n\nThere are three fundamental metric types for agent commerce:\n\n**Counters** are monotonically increasing values. Use them for total requests, total errors, total revenue, and total transactions. Counters answer \"how many\" questions.\n\n**Gauges** are point-in-time values that can go up or down. Use them for active connections, queue depth, current balance, and active escrows. Gauges answer \"how much right now\" questions.\n\n**Histograms** track the distribution of values. Use them for latency, transaction amounts, and response sizes. Histograms answer \"what is the distribution\" questions, giving you percentiles (p50, p95, p99) rather than just averages.\n\n### The MetricsCollector Implementation\n\n```python\nimport time\nimport math\nimport threading\nfrom collections import defaultdict\nfrom dataclasses import dataclass, field\nfrom typing import Dict, List, Optional, Callable, Any\n\n\n@dataclass\nclass MetricPoint:\n    \"\"\"A single metric data point.\"\"\"\n    name: str\n    value: float\n    dimensions: Dict[str, str]\n    timestamp: float\n    metric_type: str  # \"counter\", \"gauge\", \"histogram\"\n\n\nclass HistogramBuckets:\n    \"\"\"Tracks value distribution for histogram metrics.\"\"\"\n\n    def __init__(self, boundaries: List[float] = None):\n        self.boundaries = boundaries or [\n            5, 10, 25, 50, 100, 250, 500, 1000, 2500, 5000, 10000\n        ]\n        self.buckets = [0] * (len(self.boundaries) + 1)\n        self.sum = 0.0\n        self.count = 0\n        self.min = float(\"inf\")\n        self.max = float(\"-inf\")\n        self._values: List[float] = []\n\n    def observe(self, value: float):\n        self.sum += value\n        self.count += 1\n        self.min = min(self.min, value)\n        self.max = max(self.max, value)\n        self._values.append(value)\n\n        for i, boundary in enumerate(self.boundaries):\n            if value \u003C= boundary:\n                self.buckets[i] += 1\n                return\n        self.buckets[-1] += 1\n\n    def percentile(self, p: float) -> float:\n        if not self._values:\n            return 0.0\n        sorted_vals = sorted(self._values)\n        idx = int(math.ceil(p \u002F 100.0 * len(sorted_vals))) - 1\n        return sorted_vals[max(0, idx)]\n\n    def reset(self):\n        self.buckets = [0] * (len(self.boundaries) + 1)\n        self.sum = 0.0\n        self.count = 0\n        self.min = float(\"inf\")\n        self.max = float(\"-inf\")\n        self._values = []\n\n\nclass MetricsCollector:\n    \"\"\"Collects, buffers, and exports agent commerce metrics.\"\"\"\n\n    def __init__(\n        self,\n        agent_id: str,\n        client=None,\n        flush_interval_seconds: float = 60.0,\n        buffer_size: int = 1000,\n    ):\n        self.agent_id = agent_id\n        self._client = client\n        self._flush_interval = flush_interval_seconds\n        self._buffer_size = buffer_size\n\n        self._counters: Dict[str, float] = defaultdict(float)\n        self._gauges: Dict[str, float] = {}\n        self._histograms: Dict[str, HistogramBuckets] = {}\n        self._buffer: List[MetricPoint] = []\n        self._lock = threading.Lock()\n\n        self._dimensions_registry: Dict[str, Dict[str, str]] = {}\n        self._flush_callbacks: List[Callable] = []\n\n        self._running = False\n        self._flush_thread: Optional[threading.Thread] = None\n\n    def start(self):\n        \"\"\"Start the background flush thread.\"\"\"\n        self._running = True\n        self._flush_thread = threading.Thread(\n            target=self._flush_loop, daemon=True\n        )\n        self._flush_thread.start()\n\n    def stop(self):\n        \"\"\"Stop the background flush thread and flush remaining metrics.\"\"\"\n        self._running = False\n        if self._flush_thread:\n            self._flush_thread.join(timeout=5.0)\n        self.flush()\n\n    # --- Counter Operations ---\n\n    def increment(\n        self,\n        name: str,\n        value: float = 1.0,\n        dimensions: Dict[str, str] = None,\n    ):\n        \"\"\"Increment a counter metric.\"\"\"\n        key = self._make_key(name, dimensions)\n        with self._lock:\n            self._counters[key] += value\n            self._dimensions_registry[key] = dimensions or {}\n            self._buffer_point(name, self._counters[key], dimensions, \"counter\")\n\n    # --- Gauge Operations ---\n\n    def gauge_set(\n        self,\n        name: str,\n        value: float,\n        dimensions: Dict[str, str] = None,\n    ):\n        \"\"\"Set a gauge metric to an absolute value.\"\"\"\n        key = self._make_key(name, dimensions)\n        with self._lock:\n            self._gauges[key] = value\n            self._dimensions_registry[key] = dimensions or {}\n            self._buffer_point(name, value, dimensions, \"gauge\")\n\n    def gauge_increment(\n        self,\n        name: str,\n        value: float = 1.0,\n        dimensions: Dict[str, str] = None,\n    ):\n        \"\"\"Increment a gauge metric.\"\"\"\n        key = self._make_key(name, dimensions)\n        with self._lock:\n            self._gauges[key] = self._gauges.get(key, 0.0) + value\n            self._dimensions_registry[key] = dimensions or {}\n            self._buffer_point(name, self._gauges[key], dimensions, \"gauge\")\n\n    # --- Histogram Operations ---\n\n    def observe(\n        self,\n        name: str,\n        value: float,\n        dimensions: Dict[str, str] = None,\n        boundaries: List[float] = None,\n    ):\n        \"\"\"Record an observation in a histogram metric.\"\"\"\n        key = self._make_key(name, dimensions)\n        with self._lock:\n            if key not in self._histograms:\n                self._histograms[key] = HistogramBuckets(boundaries)\n            self._histograms[key].observe(value)\n            self._dimensions_registry[key] = dimensions or {}\n            self._buffer_point(name, value, dimensions, \"histogram\")\n\n    # --- Business Metric Helpers ---\n\n    def record_transaction(\n        self,\n        operation: str,\n        duration_ms: float,\n        amount: float,\n        status: str,\n        peer_agent: str = \"\",\n    ):\n        \"\"\"Record a complete transaction with all standard metrics.\"\"\"\n        dims = {\n            \"operation\": operation,\n            \"status\": status,\n            \"peer_agent\": peer_agent,\n        }\n\n        self.increment(\"transactions.total\", 1.0, dims)\n        self.observe(\"transactions.duration_ms\", duration_ms, dims)\n        self.observe(\"transactions.amount\", amount, dims)\n\n        if status == \"error\":\n            self.increment(\"transactions.errors\", 1.0, dims)\n\n    def record_revenue(self, amount: float, source: str, currency: str = \"credits\"):\n        \"\"\"Record revenue from an agent operation.\"\"\"\n        dims = {\"source\": source, \"currency\": currency}\n        self.increment(\"revenue.total\", amount, dims)\n\n    def record_cost(self, amount: float, category: str, currency: str = \"credits\"):\n        \"\"\"Record a cost incurred by the agent.\"\"\"\n        dims = {\"category\": category, \"currency\": currency}\n        self.increment(\"costs.total\", amount, dims)\n\n    def record_escrow_event(self, event_type: str, amount: float, escrow_id: str):\n        \"\"\"Record an escrow lifecycle event.\"\"\"\n        dims = {\"event_type\": event_type}\n        self.increment(f\"escrow.{event_type}\", 1.0, dims)\n        self.observe(\"escrow.amount\", amount, dims)\n\n    # --- Export and Flush ---\n\n    def flush(self):\n        \"\"\"Flush buffered metrics to GreenHelix.\"\"\"\n        with self._lock:\n            if not self._buffer:\n                return\n            batch = self._buffer[:]\n            self._buffer.clear()\n\n        if self._client:\n            metrics_payload = [\n                {\n                    \"name\": point.name,\n                    \"value\": point.value,\n                    \"dimensions\": {\n                        \"agent\": self.agent_id,\n                        **point.dimensions,\n                    },\n                    \"timestamp\": _ts_to_iso(point.timestamp),\n                }\n                for point in batch\n            ]\n\n            try:\n                self._client.execute_tool(\"submit_metrics\", {\n                    \"agent_id\": self.agent_id,\n                    \"metrics\": metrics_payload,\n                })\n            except Exception as e:\n                # Re-buffer on failure for retry\n                with self._lock:\n                    self._buffer = batch + self._buffer\n                    # Prevent unbounded growth\n                    if len(self._buffer) > self._buffer_size * 2:\n                        self._buffer = self._buffer[-self._buffer_size:]\n\n        for callback in self._flush_callbacks:\n            try:\n                callback(batch)\n            except Exception:\n                pass\n\n    def get_histogram_summary(\n        self, name: str, dimensions: Dict[str, str] = None\n    ) -> Dict[str, float]:\n        \"\"\"Get summary statistics for a histogram metric.\"\"\"\n        key = self._make_key(name, dimensions)\n        with self._lock:\n            hist = self._histograms.get(key)\n            if not hist or hist.count == 0:\n                return {}\n            return {\n                \"count\": hist.count,\n                \"sum\": hist.sum,\n                \"min\": hist.min,\n                \"max\": hist.max,\n                \"avg\": hist.sum \u002F hist.count,\n                \"p50\": hist.percentile(50),\n                \"p95\": hist.percentile(95),\n                \"p99\": hist.percentile(99),\n            }\n\n    def on_flush(self, callback: Callable):\n        \"\"\"Register a callback to be called on each flush.\"\"\"\n        self._flush_callbacks.append(callback)\n\n    # --- Internal ---\n\n    def _buffer_point(\n        self,\n        name: str,\n        value: float,\n        dimensions: Dict[str, str],\n        metric_type: str,\n    ):\n        point = MetricPoint(\n            name=name,\n            value=value,\n            dimensions=dimensions or {},\n            timestamp=time.time(),\n            metric_type=metric_type,\n        )\n        self._buffer.append(point)\n\n        if len(self._buffer) >= self._buffer_size:\n            threading.Thread(target=self.flush, daemon=True).start()\n\n    def _flush_loop(self):\n        while self._running:\n            time.sleep(self._flush_interval)\n            self.flush()\n\n    @staticmethod\n    def _make_key(name: str, dimensions: Dict[str, str] = None) -> str:\n        if not dimensions:\n            return name\n        dim_str = \",\".join(f\"{k}={v}\" for k, v in sorted(dimensions.items()))\n        return f\"{name}{{{dim_str}}}\"\n\n\ndef _ts_to_iso(ts: float) -> str:\n    import datetime\n    dt = datetime.datetime.fromtimestamp(ts, tz=datetime.timezone.utc)\n    return dt.isoformat()\n```\n\n### Using the MetricsCollector\n\n```python\nclient = GreenHelixClient(api_key=\"your-api-key\")\nmetrics = MetricsCollector(agent_id=\"agent-marketplace\", client=client)\nmetrics.start()\n\n# Record a transaction\nstart = time.time()\nresult = process_order(order)\nduration_ms = (time.time() - start) * 1000\n\nmetrics.record_transaction(\n    operation=\"process_order\",\n    duration_ms=duration_ms,\n    amount=order[\"amount\"],\n    status=\"success\" if result[\"ok\"] else \"error\",\n    peer_agent=order[\"seller_agent\"],\n)\n\n# Record revenue and costs\nmetrics.record_revenue(order[\"commission\"], source=\"marketplace_fee\")\nmetrics.record_cost(order[\"gateway_fee\"], category=\"gateway\")\n\n# Record escrow events\nmetrics.record_escrow_event(\"created\", order[\"amount\"], result[\"escrow_id\"])\n\n# Get latency percentiles\nsummary = metrics.get_histogram_summary(\n    \"transactions.duration_ms\",\n    {\"operation\": \"process_order\", \"status\": \"success\"},\n)\nprint(f\"p50={summary['p50']:.0f}ms  p95={summary['p95']:.0f}ms  p99={summary['p99']:.0f}ms\")\n\n# Clean shutdown\nmetrics.stop()\n```\n\nThe `MetricsCollector` buffers metrics in memory and flushes them periodically (default 60 seconds) or when the buffer fills. This batching reduces API calls to GreenHelix while ensuring metrics are not lost. The retry logic on flush failure re-buffers metrics for the next flush cycle, with a cap to prevent unbounded memory growth.\n\n---\n\n## Chapter 5: Anomaly Detection\n\nRaw metrics are necessary but not sufficient. An agent operator managing a fleet of 50 agents cannot watch 200 dashboards for problems. You need automated anomaly detection that understands normal patterns and alerts on deviations.\n\n### Statistical Anomaly Detection for Agent Metrics\n\nAnomaly detection for agent commerce differs from traditional infrastructure monitoring in two ways. First, agent traffic patterns are often bursty and non-uniform: a marketplace agent might handle 100 requests per minute during business hours and 5 per minute overnight. Second, business metrics like revenue have seasonal patterns (daily, weekly, monthly) that must be accounted for.\n\nOur `AnomalyDetector` uses three complementary detection methods: Z-score for sudden spikes, percentage change for trend shifts, and seasonal decomposition for pattern violations.\n\n```python\nimport math\nimport time\nfrom collections import deque\nfrom dataclasses import dataclass, field\nfrom typing import Dict, List, Optional, Tuple\nfrom enum import Enum\n\n\nclass AnomalyType(Enum):\n    SPIKE = \"spike\"\n    DROP = \"drop\"\n    TREND_CHANGE = \"trend_change\"\n    SEASONAL_VIOLATION = \"seasonal_violation\"\n\n\nclass Severity(Enum):\n    LOW = \"low\"\n    MEDIUM = \"medium\"\n    HIGH = \"high\"\n    CRITICAL = \"critical\"\n\n\n@dataclass\nclass Anomaly:\n    \"\"\"A detected anomaly in a metric series.\"\"\"\n    metric_name: str\n    anomaly_type: AnomalyType\n    severity: Severity\n    current_value: float\n    expected_value: float\n    deviation: float\n    timestamp: float\n    dimensions: Dict[str, str] = field(default_factory=dict)\n    message: str = \"\"\n\n\nclass MetricWindow:\n    \"\"\"Sliding window of metric values for statistical analysis.\"\"\"\n\n    def __init__(self, window_size: int = 60):\n        self._values: deque = deque(maxlen=window_size)\n        self._timestamps: deque = deque(maxlen=window_size)\n\n    def add(self, value: float, timestamp: float = None):\n        self._values.append(value)\n        self._timestamps.append(timestamp or time.time())\n\n    @property\n    def count(self) -> int:\n        return len(self._values)\n\n    @property\n    def mean(self) -> float:\n        if not self._values:\n            return 0.0\n        return sum(self._values) \u002F len(self._values)\n\n    @property\n    def std(self) -> float:\n        if len(self._values) \u003C 2:\n            return 0.0\n        m = self.mean\n        variance = sum((v - m) ** 2 for v in self._values) \u002F (len(self._values) - 1)\n        return math.sqrt(variance)\n\n    @property\n    def values(self) -> List[float]:\n        return list(self._values)\n\n    @property\n    def latest(self) -> Optional[float]:\n        return self._values[-1] if self._values else None\n\n    def rate_of_change(self, periods: int = 5) -> Optional[float]:\n        \"\"\"Calculate rate of change over the last N periods.\"\"\"\n        if len(self._values) \u003C periods + 1:\n            return None\n        recent = list(self._values)[-periods:]\n        older = list(self._values)[-(periods + 1)]\n        if older == 0:\n            return None\n        return (recent[-1] - older) \u002F older\n\n\nclass SeasonalProfile:\n    \"\"\"Tracks seasonal patterns for a metric (hourly buckets).\"\"\"\n\n    def __init__(self, num_buckets: int = 24):\n        self._num_buckets = num_buckets\n        self._bucket_values: Dict[int, List[float]] = {\n            i: [] for i in range(num_buckets)\n        }\n\n    def add(self, value: float, timestamp: float):\n        import datetime\n        dt = datetime.datetime.fromtimestamp(timestamp, tz=datetime.timezone.utc)\n        bucket = dt.hour  # Hourly buckets\n        self._bucket_values[bucket].append(value)\n\n    def expected_value(self, timestamp: float) -> Optional[Tuple[float, float]]:\n        \"\"\"Return (mean, std) for the expected value at this time.\"\"\"\n        import datetime\n        dt = datetime.datetime.fromtimestamp(timestamp, tz=datetime.timezone.utc)\n        bucket = dt.hour\n        values = self._bucket_values.get(bucket, [])\n        if len(values) \u003C 7:  # Need at least a week of data\n            return None\n        m = sum(values) \u002F len(values)\n        variance = sum((v - m) ** 2 for v in values) \u002F (len(values) - 1)\n        return m, math.sqrt(variance)\n\n\nclass AnomalyDetector:\n    \"\"\"Detects anomalies in agent commerce metric streams.\"\"\"\n\n    def __init__(\n        self,\n        z_score_threshold: float = 3.0,\n        pct_change_threshold: float = 0.30,\n        seasonal_z_threshold: float = 2.5,\n        min_data_points: int = 20,\n    ):\n        self._z_threshold = z_score_threshold\n        self._pct_threshold = pct_change_threshold\n        self._seasonal_z_threshold = seasonal_z_threshold\n        self._min_data_points = min_data_points\n\n        self._windows: Dict[str, MetricWindow] = {}\n        self._seasonal: Dict[str, SeasonalProfile] = {}\n        self._anomaly_callbacks: List = []\n\n    def observe(\n        self,\n        metric_name: str,\n        value: float,\n        dimensions: Dict[str, str] = None,\n        timestamp: float = None,\n    ) -> List[Anomaly]:\n        \"\"\"Observe a metric value and check for anomalies.\"\"\"\n        ts = timestamp or time.time()\n        key = self._make_key(metric_name, dimensions)\n\n        if key not in self._windows:\n            self._windows[key] = MetricWindow(window_size=120)\n            self._seasonal[key] = SeasonalProfile()\n\n        window = self._windows[key]\n        seasonal = self._seasonal[key]\n\n        window.add(value, ts)\n        seasonal.add(value, ts)\n\n        anomalies = []\n\n        if window.count >= self._min_data_points:\n            # Z-score detection\n            z_anomaly = self._check_z_score(\n                metric_name, value, window, dimensions, ts\n            )\n            if z_anomaly:\n                anomalies.append(z_anomaly)\n\n            # Percentage change detection\n            pct_anomaly = self._check_pct_change(\n                metric_name, value, window, dimensions, ts\n            )\n            if pct_anomaly:\n                anomalies.append(pct_anomaly)\n\n        # Seasonal detection\n        seasonal_anomaly = self._check_seasonal(\n            metric_name, value, seasonal, dimensions, ts\n        )\n        if seasonal_anomaly:\n            anomalies.append(seasonal_anomaly)\n\n        for anomaly in anomalies:\n            for callback in self._anomaly_callbacks:\n                try:\n                    callback(anomaly)\n                except Exception:\n                    pass\n\n        return anomalies\n\n    def on_anomaly(self, callback):\n        \"\"\"Register a callback for detected anomalies.\"\"\"\n        self._anomaly_callbacks.append(callback)\n\n    def _check_z_score(\n        self,\n        metric_name: str,\n        value: float,\n        window: MetricWindow,\n        dimensions: Dict[str, str],\n        timestamp: float,\n    ) -> Optional[Anomaly]:\n        \"\"\"Detect anomalies using Z-score (standard deviations from mean).\"\"\"\n        std = window.std\n        if std == 0:\n            return None\n\n        z_score = abs(value - window.mean) \u002F std\n        if z_score \u003C self._z_threshold:\n            return None\n\n        anomaly_type = AnomalyType.SPIKE if value > window.mean else AnomalyType.DROP\n        severity = self._z_to_severity(z_score)\n\n        return Anomaly(\n            metric_name=metric_name,\n            anomaly_type=anomaly_type,\n            severity=severity,\n            current_value=value,\n            expected_value=window.mean,\n            deviation=z_score,\n            timestamp=timestamp,\n            dimensions=dimensions or {},\n            message=f\"{metric_name} is {z_score:.1f} standard deviations \"\n                    f\"{'above' if value > window.mean else 'below'} the mean \"\n                    f\"(current={value:.2f}, mean={window.mean:.2f}, std={std:.2f})\",\n        )\n\n    def _check_pct_change(\n        self,\n        metric_name: str,\n        value: float,\n        window: MetricWindow,\n        dimensions: Dict[str, str],\n        timestamp: float,\n    ) -> Optional[Anomaly]:\n        \"\"\"Detect anomalies using percentage change over recent periods.\"\"\"\n        roc = window.rate_of_change(periods=5)\n        if roc is None or abs(roc) \u003C self._pct_threshold:\n            return None\n\n        anomaly_type = (\n            AnomalyType.TREND_CHANGE\n        )\n        severity = Severity.MEDIUM if abs(roc) \u003C 0.5 else Severity.HIGH\n\n        return Anomaly(\n            metric_name=metric_name,\n            anomaly_type=anomaly_type,\n            severity=severity,\n            current_value=value,\n            expected_value=window.mean,\n            deviation=roc,\n            timestamp=timestamp,\n            dimensions=dimensions or {},\n            message=f\"{metric_name} changed by {roc*100:.1f}% over the last 5 periods \"\n                    f\"(current={value:.2f})\",\n        )\n\n    def _check_seasonal(\n        self,\n        metric_name: str,\n        value: float,\n        seasonal: SeasonalProfile,\n        dimensions: Dict[str, str],\n        timestamp: float,\n    ) -> Optional[Anomaly]:\n        \"\"\"Detect anomalies relative to seasonal patterns.\"\"\"\n        expected = seasonal.expected_value(timestamp)\n        if expected is None:\n            return None\n\n        mean, std = expected\n        if std == 0:\n            return None\n\n        z_score = abs(value - mean) \u002F std\n        if z_score \u003C self._seasonal_z_threshold:\n            return None\n\n        return Anomaly(\n            metric_name=metric_name,\n            anomaly_type=AnomalyType.SEASONAL_VIOLATION,\n            severity=self._z_to_severity(z_score),\n            current_value=value,\n            expected_value=mean,\n            deviation=z_score,\n            timestamp=timestamp,\n            dimensions=dimensions or {},\n            message=f\"{metric_name} deviates {z_score:.1f} std from seasonal expectation \"\n                    f\"(current={value:.2f}, expected={mean:.2f} +\u002F- {std:.2f})\",\n        )\n\n    @staticmethod\n    def _z_to_severity(z_score: float) -> Severity:\n        if z_score >= 5.0:\n            return Severity.CRITICAL\n        elif z_score >= 4.0:\n            return Severity.HIGH\n        elif z_score >= 3.0:\n            return Severity.MEDIUM\n        return Severity.LOW\n\n    @staticmethod\n    def _make_key(name: str, dimensions: Dict[str, str] = None) -> str:\n        if not dimensions:\n            return name\n        dim_str = \",\".join(f\"{k}={v}\" for k, v in sorted(dimensions.items()))\n        return f\"{name}{{{dim_str}}}\"\n```\n\n### Integrating Anomaly Detection with Metrics Collection\n\nThe `AnomalyDetector` works alongside the `MetricsCollector`. Feed every metric observation to both:\n\n```python\ndetector = AnomalyDetector(\n    z_score_threshold=3.0,\n    pct_change_threshold=0.30,\n    min_data_points=20,\n)\nmetrics = MetricsCollector(agent_id=\"agent-marketplace\", client=client)\n\ndef record_and_detect(\n    metric_name: str,\n    value: float,\n    dimensions: Dict[str, str] = None,\n):\n    \"\"\"Record a metric and check for anomalies in one call.\"\"\"\n    metrics.observe(metric_name, value, dimensions)\n    anomalies = detector.observe(metric_name, value, dimensions)\n\n    for anomaly in anomalies:\n        print(f\"ANOMALY: {anomaly.message}\")\n        # Feed anomaly back as a metric for meta-monitoring\n        metrics.increment(\n            \"anomalies.detected\",\n            1.0,\n            {\n                \"metric\": anomaly.metric_name,\n                \"type\": anomaly.anomaly_type.value,\n                \"severity\": anomaly.severity.value,\n            },\n        )\n\n    return anomalies\n\n# Example: detect latency spike\nrecord_and_detect(\n    \"transactions.duration_ms\",\n    12500.0,  # 12.5 seconds -- likely anomalous\n    {\"operation\": \"process_order\"},\n)\n```\n\nThe detector's sliding window approach means it adapts to changing baselines. If your agent's latency gradually increases from 200ms to 300ms over a week, the detector adjusts its baseline and does not fire false alerts. But if latency jumps from 300ms to 3000ms in one minute, the Z-score catches it immediately.\n\nThe seasonal profile prevents false alerts during known traffic patterns. If your agent processes fewer transactions overnight, a drop from 100 req\u002Fs to 10 req\u002Fs at midnight is not anomalous -- the seasonal profile knows that is normal for that hour.\n\n---\n\n## Chapter 6: Dashboard Design\n\nAnomaly detection catches problems automatically, but operators still need dashboards for situational awareness, capacity planning, and stakeholder reporting. This chapter describes the three essential dashboards for agent commerce operations, with the data sources and queries needed to populate them.\n\n### Dashboard 1: Fleet Health Overview\n\nThe fleet health dashboard is the first thing you look at when something might be wrong. It answers: \"Is everything healthy right now?\"\n\n**Key panels:**\n\n1. **Agent Status Grid** -- A grid showing every agent with color-coded health status (green\u002Fyellow\u002Fred). Data source: gauge metrics for each agent's last heartbeat timestamp and error rate. An agent is green if error rate is below 1% and last heartbeat was within 60 seconds, yellow if error rate is 1-5% or heartbeat is 60-120 seconds stale, and red otherwise.\n\n2. **Fleet Error Rate** -- A time series chart showing the aggregate error rate across all agents over the last 24 hours, with the anomaly detection threshold overlaid. Data source: counter metrics `transactions.errors` \u002F `transactions.total`, aggregated per minute.\n\n3. **Active Escrows** -- A gauge showing the current number of open (unsettled) escrows, with a trend line. A rising trend indicates settlement failures or slow processing. Data source: gauge metric `escrow.active_count`.\n\n4. **Latency Heatmap** -- A heatmap showing p95 latency for each agent over the last 6 hours. Columns are time buckets (15-minute intervals), rows are agents, and color intensity represents latency. This makes it easy to spot both fleet-wide issues (a hot column) and per-agent issues (a hot row). Data source: histogram metric `transactions.duration_ms`, p95 aggregation.\n\n5. **Alert Summary** -- A table of currently active alerts grouped by severity, with acknowledge\u002Fresolve buttons. Data source: the AlertManager's active alerts state (covered in Chapter 7).\n\n```python\ndef build_fleet_health_query(agent_ids: List[str]) -> Dict[str, Any]:\n    \"\"\"Build the query configuration for the fleet health dashboard.\"\"\"\n    return {\n        \"panels\": [\n            {\n                \"title\": \"Agent Status Grid\",\n                \"type\": \"status_grid\",\n                \"query\": {\n                    \"metrics\": [\"agent.heartbeat.age_seconds\", \"transactions.errors\"],\n                    \"group_by\": [\"agent\"],\n                    \"thresholds\": {\n                        \"green\": {\"error_rate\": 0.01, \"heartbeat_age\": 60},\n                        \"yellow\": {\"error_rate\": 0.05, \"heartbeat_age\": 120},\n                        \"red\": {\"error_rate\": 1.0, \"heartbeat_age\": float(\"inf\")},\n                    },\n                },\n            },\n            {\n                \"title\": \"Fleet Error Rate\",\n                \"type\": \"time_series\",\n                \"query\": {\n                    \"metric\": \"transactions.errors\",\n                    \"aggregation\": \"rate\",\n                    \"interval\": \"1m\",\n                    \"time_range\": \"24h\",\n                },\n            },\n            {\n                \"title\": \"Active Escrows\",\n                \"type\": \"gauge_with_trend\",\n                \"query\": {\n                    \"metric\": \"escrow.active_count\",\n                    \"aggregation\": \"latest\",\n                    \"trend_window\": \"6h\",\n                },\n            },\n            {\n                \"title\": \"Latency Heatmap\",\n                \"type\": \"heatmap\",\n                \"query\": {\n                    \"metric\": \"transactions.duration_ms\",\n                    \"aggregation\": \"p95\",\n                    \"group_by\": [\"agent\"],\n                    \"interval\": \"15m\",\n                    \"time_range\": \"6h\",\n                },\n            },\n        ],\n    }\n```\n\n### Dashboard 2: Transaction Flow\n\nThe transaction flow dashboard shows how transactions move through your agent fleet. It answers: \"What is happening to our transactions?\"\n\n**Key panels:**\n\n1. **Transaction Funnel** -- A funnel visualization showing transactions at each stage: initiated, matched, escrowed, fulfilled, settled, completed. Drop-off at each stage reveals where transactions are failing. Data source: counter metrics per transaction stage.\n\n2. **Agent-to-Agent Flow** -- A Sankey diagram or chord chart showing traffic volume between agent pairs. Thick lines indicate high-volume relationships. Clicking a flow line drills down to latency and error metrics for that specific agent pair. Data source: counter metric `transactions.total` with `peer_agent` dimension.\n\n3. **Escrow Lifecycle** -- A state diagram showing escrows in each state (pending, funded, fulfilled, settled, disputed, expired) with transition rates. Data source: counter metrics per escrow state transition.\n\n4. **Slow Transactions** -- A table of the 20 slowest transactions in the last hour, with trace IDs linked to the trace viewer. This gives operators one-click access to detailed trace analysis for the worst-performing transactions. Data source: histogram metric `transactions.duration_ms`, top-N query.\n\n5. **Transaction Volume** -- A stacked area chart showing transaction volume per operation type over the last 24 hours. Data source: counter metric `transactions.total` grouped by `operation` dimension.\n\n### Dashboard 3: Revenue and Cost\n\nThe revenue and cost dashboard is for business stakeholders and capacity planning. It answers: \"Are we making money, and where is it going?\"\n\n**Key panels:**\n\n1. **Net Revenue** -- A single large number showing today's net revenue (revenue minus costs), with comparison to same day last week. Data source: counter metrics `revenue.total` minus `costs.total`.\n\n2. **Revenue by Agent** -- A bar chart showing revenue contribution per agent. Identifies your most and least profitable agents. Data source: counter metric `revenue.total` grouped by `agent` dimension.\n\n3. **Cost Breakdown** -- A pie chart showing costs by category: gateway fees, escrow fees, infrastructure, third-party API calls. Data source: counter metric `costs.total` grouped by `category` dimension.\n\n4. **Revenue Trend** -- A time series comparing daily revenue over the last 30 days, with the anomaly detection band overlaid. Revenue drops outside the expected band trigger alerts. Data source: counter metric `revenue.total`, daily aggregation.\n\n5. **Per-Transaction Economics** -- A table showing average revenue, cost, and margin per operation type. Identifies operations that are losing money. Data source: derived from `revenue.total` and `costs.total` metrics divided by `transactions.total`, grouped by `operation`.\n\nEach dashboard should auto-refresh on a cadence appropriate to its purpose: fleet health every 30 seconds, transaction flow every minute, revenue and cost every 5 minutes. The underlying data all comes from the `MetricsCollector` metrics pushed to GreenHelix via `submit_metrics`, queried back for visualization.\n\n---\n\n## Chapter 7: AlertManager Class\n\nDashboards require someone to be watching them. Alerts push problems to the right people at the right time. The `AlertManager` evaluates alert rules against incoming metrics, deduplicates and groups related alerts, routes them through appropriate channels, and escalates when problems are not acknowledged.\n\n### Alert Rule Types\n\nThree types of alert rules cover the scenarios that matter for agent commerce:\n\n**Threshold alerts** fire when a metric crosses a static or dynamic boundary. Example: \"Error rate exceeds 5%.\" These are simple and reliable for known boundaries.\n\n**Rate-of-change alerts** fire when a metric changes too quickly. Example: \"Transaction volume dropped more than 30% in 10 minutes.\" These catch problems that threshold alerts miss because the absolute value might still be \"normal.\"\n\n**Anomaly-based alerts** fire when the `AnomalyDetector` identifies a statistical anomaly. These adapt to changing baselines and seasonal patterns, catching subtle issues that would require constantly adjusting threshold values.\n\n### The AlertManager Implementation\n\n```python\nimport time\nimport uuid\nimport threading\nimport json\nfrom dataclasses import dataclass, field\nfrom typing import Dict, List, Optional, Callable, Any\nfrom enum import Enum\nfrom collections import defaultdict\n\n\nclass AlertState(Enum):\n    FIRING = \"firing\"\n    ACKNOWLEDGED = \"acknowledged\"\n    RESOLVED = \"resolved\"\n\n\nclass AlertChannel(Enum):\n    WEBHOOK = \"webhook\"\n    EMAIL = \"email\"\n    SLACK = \"slack\"\n    PAGERDUTY = \"pagerduty\"\n\n\n@dataclass\nclass AlertRule:\n    \"\"\"Definition of an alert rule.\"\"\"\n    name: str\n    metric_name: str\n    condition: str  # \"threshold\", \"rate_of_change\", \"anomaly\"\n    threshold: Optional[float] = None\n    comparison: str = \"gt\"  # \"gt\", \"lt\", \"gte\", \"lte\"\n    window_minutes: int = 5\n    severity: str = \"medium\"\n    channels: List[AlertChannel] = field(default_factory=list)\n    dimensions_filter: Dict[str, str] = field(default_factory=dict)\n    cooldown_minutes: int = 15\n    escalation_minutes: int = 30\n    description: str = \"\"\n    runbook_url: str = \"\"\n\n\n@dataclass\nclass Alert:\n    \"\"\"An active alert instance.\"\"\"\n    id: str\n    rule: AlertRule\n    state: AlertState\n    fired_at: float\n    last_value: float\n    message: str\n    acknowledged_at: Optional[float] = None\n    acknowledged_by: Optional[str] = None\n    resolved_at: Optional[float] = None\n    escalated: bool = False\n    notification_count: int = 0\n    dimensions: Dict[str, str] = field(default_factory=dict)\n\n\nclass AlertManager:\n    \"\"\"Manages alert rules, routing, deduplication, and escalation.\"\"\"\n\n    def __init__(\n        self,\n        agent_id: str,\n        client=None,\n        anomaly_detector: \"AnomalyDetector\" = None,\n    ):\n        self.agent_id = agent_id\n        self._client = client\n        self._detector = anomaly_detector\n\n        self._rules: Dict[str, AlertRule] = {}\n        self._active_alerts: Dict[str, Alert] = {}\n        self._alert_history: List[Alert] = []\n        self._cooldowns: Dict[str, float] = {}\n        self._lock = threading.Lock()\n\n        # Channel handlers\n        self._channel_handlers: Dict[AlertChannel, Callable] = {}\n\n        # Escalation thread\n        self._running = False\n        self._escalation_thread: Optional[threading.Thread] = None\n\n    def start(self):\n        \"\"\"Start the escalation monitoring thread.\"\"\"\n        self._running = True\n        self._escalation_thread = threading.Thread(\n            target=self._escalation_loop, daemon=True\n        )\n        self._escalation_thread.start()\n\n    def stop(self):\n        self._running = False\n        if self._escalation_thread:\n            self._escalation_thread.join(timeout=5.0)\n\n    # --- Rule Management ---\n\n    def add_rule(self, rule: AlertRule):\n        \"\"\"Add an alert rule.\"\"\"\n        self._rules[rule.name] = rule\n\n    def remove_rule(self, name: str):\n        \"\"\"Remove an alert rule.\"\"\"\n        self._rules.pop(name, None)\n\n    # --- Channel Configuration ---\n\n    def register_channel(self, channel: AlertChannel, handler: Callable):\n        \"\"\"Register a notification handler for a channel.\"\"\"\n        self._channel_handlers[channel] = handler\n\n    def configure_webhook(self, url: str):\n        \"\"\"Configure webhook channel with a URL.\"\"\"\n        import urllib.request\n\n        def webhook_handler(alert: Alert, message: str):\n            payload = json.dumps({\n                \"alert_id\": alert.id,\n                \"rule\": alert.rule.name,\n                \"severity\": alert.rule.severity,\n                \"state\": alert.state.value,\n                \"message\": message,\n                \"value\": alert.last_value,\n                \"fired_at\": alert.fired_at,\n                \"agent_id\": self.agent_id,\n                \"dimensions\": alert.dimensions,\n            }).encode()\n\n            req = urllib.request.Request(\n                url,\n                data=payload,\n                headers={\"Content-Type\": \"application\u002Fjson\"},\n                method=\"POST\",\n            )\n            try:\n                urllib.request.urlopen(req, timeout=10)\n            except Exception:\n                pass\n\n        self._channel_handlers[AlertChannel.WEBHOOK] = webhook_handler\n\n    def configure_slack(self, webhook_url: str, default_channel: str = \"#alerts\"):\n        \"\"\"Configure Slack channel.\"\"\"\n        import urllib.request\n\n        def slack_handler(alert: Alert, message: str):\n            severity_emoji = {\n                \"critical\": \":red_circle:\",\n                \"high\": \":large_orange_circle:\",\n                \"medium\": \":large_yellow_circle:\",\n                \"low\": \":white_circle:\",\n            }\n            emoji = severity_emoji.get(alert.rule.severity, \":grey_question:\")\n\n            payload = json.dumps({\n                \"channel\": default_channel,\n                \"text\": f\"{emoji} *{alert.rule.name}*\\n{message}\",\n                \"attachments\": [\n                    {\n                        \"color\": {\n                            \"critical\": \"#ff0000\",\n                            \"high\": \"#ff8800\",\n                            \"medium\": \"#ffcc00\",\n                            \"low\": \"#cccccc\",\n                        }.get(alert.rule.severity, \"#cccccc\"),\n                        \"fields\": [\n                            {\"title\": \"Agent\", \"value\": self.agent_id, \"short\": True},\n                            {\"title\": \"Value\", \"value\": str(alert.last_value), \"short\": True},\n                            {\"title\": \"Severity\", \"value\": alert.rule.severity, \"short\": True},\n                            {\"title\": \"Alert ID\", \"value\": alert.id, \"short\": True},\n                        ],\n                    }\n                ],\n            }).encode()\n\n            req = urllib.request.Request(\n                webhook_url,\n                data=payload,\n                headers={\"Content-Type\": \"application\u002Fjson\"},\n                method=\"POST\",\n            )\n            try:\n                urllib.request.urlopen(req, timeout=10)\n            except Exception:\n                pass\n\n        self._channel_handlers[AlertChannel.SLACK] = slack_handler\n\n    # --- Alert Evaluation ---\n\n    def evaluate(\n        self,\n        metric_name: str,\n        value: float,\n        dimensions: Dict[str, str] = None,\n    ) -> List[Alert]:\n        \"\"\"Evaluate all rules against a metric value.\"\"\"\n        new_alerts = []\n        dims = dimensions or {}\n\n        for rule in self._rules.values():\n            if rule.metric_name != metric_name:\n                continue\n\n            # Check dimension filter\n            if rule.dimensions_filter:\n                if not all(\n                    dims.get(k) == v for k, v in rule.dimensions_filter.items()\n                ):\n                    continue\n\n            # Check cooldown\n            cooldown_key = f\"{rule.name}:{self._dim_key(dims)}\"\n            if cooldown_key in self._cooldowns:\n                if time.time() - self._cooldowns[cooldown_key] \u003C rule.cooldown_minutes * 60:\n                    continue\n\n            triggered = False\n\n            if rule.condition == \"threshold\":\n                triggered = self._check_threshold(rule, value)\n            elif rule.condition == \"rate_of_change\":\n                triggered = self._check_rate_of_change(rule, value, metric_name, dims)\n            elif rule.condition == \"anomaly\" and self._detector:\n                anomalies = self._detector.observe(metric_name, value, dims)\n                triggered = len(anomalies) > 0\n\n            if triggered:\n                alert = self._fire_alert(rule, value, dims)\n                if alert:\n                    new_alerts.append(alert)\n                    self._cooldowns[cooldown_key] = time.time()\n\n        # Check for auto-resolution\n        self._check_resolutions(metric_name, value, dims)\n\n        return new_alerts\n\n    def acknowledge(self, alert_id: str, acknowledged_by: str = \"operator\"):\n        \"\"\"Acknowledge an active alert.\"\"\"\n        with self._lock:\n            alert = self._active_alerts.get(alert_id)\n            if alert and alert.state == AlertState.FIRING:\n                alert.state = AlertState.ACKNOWLEDGED\n                alert.acknowledged_at = time.time()\n                alert.acknowledged_by = acknowledged_by\n\n    def resolve(self, alert_id: str):\n        \"\"\"Manually resolve an alert.\"\"\"\n        with self._lock:\n            alert = self._active_alerts.get(alert_id)\n            if alert:\n                alert.state = AlertState.RESOLVED\n                alert.resolved_at = time.time()\n                self._alert_history.append(alert)\n                del self._active_alerts[alert_id]\n                self._notify(alert, f\"RESOLVED: {alert.rule.name}\")\n\n    def get_active_alerts(\n        self, severity: str = None\n    ) -> List[Alert]:\n        \"\"\"Get all active (firing or acknowledged) alerts.\"\"\"\n        with self._lock:\n            alerts = list(self._active_alerts.values())\n            if severity:\n                alerts = [a for a in alerts if a.rule.severity == severity]\n            return sorted(alerts, key=lambda a: a.fired_at, reverse=True)\n\n    # --- Internal ---\n\n    def _check_threshold(self, rule: AlertRule, value: float) -> bool:\n        if rule.threshold is None:\n            return False\n        ops = {\n            \"gt\": lambda v, t: v > t,\n            \"lt\": lambda v, t: v \u003C t,\n            \"gte\": lambda v, t: v >= t,\n            \"lte\": lambda v, t: v \u003C= t,\n        }\n        op = ops.get(rule.comparison, ops[\"gt\"])\n        return op(value, rule.threshold)\n\n    def _check_rate_of_change(\n        self,\n        rule: AlertRule,\n        value: float,\n        metric_name: str,\n        dimensions: Dict[str, str],\n    ) -> bool:\n        if not self._detector:\n            return False\n        key = self._detector._make_key(metric_name, dimensions)\n        window = self._detector._windows.get(key)\n        if not window:\n            return False\n        roc = window.rate_of_change(periods=5)\n        if roc is None or rule.threshold is None:\n            return False\n        return abs(roc) > rule.threshold\n\n    def _fire_alert(\n        self,\n        rule: AlertRule,\n        value: float,\n        dimensions: Dict[str, str],\n    ) -> Optional[Alert]:\n        # Deduplicate: check if same rule + dimensions already firing\n        dedup_key = f\"{rule.name}:{self._dim_key(dimensions)}\"\n        with self._lock:\n            for alert in self._active_alerts.values():\n                existing_key = f\"{alert.rule.name}:{self._dim_key(alert.dimensions)}\"\n                if existing_key == dedup_key:\n                    # Update existing alert instead of creating new one\n                    alert.last_value = value\n                    alert.notification_count += 1\n                    return None\n\n            alert = Alert(\n                id=f\"alert_{uuid.uuid4().hex[:12]}\",\n                rule=rule,\n                state=AlertState.FIRING,\n                fired_at=time.time(),\n                last_value=value,\n                message=f\"{rule.name}: {rule.metric_name} = {value} \"\n                        f\"(threshold: {rule.comparison} {rule.threshold})\",\n                dimensions=dimensions,\n            )\n            self._active_alerts[alert.id] = alert\n\n        self._notify(alert, alert.message)\n        return alert\n\n    def _notify(self, alert: Alert, message: str):\n        for channel in alert.rule.channels:\n            handler = self._channel_handlers.get(channel)\n            if handler:\n                try:\n                    handler(alert, message)\n                except Exception:\n                    pass\n\n        # Also register webhook with GreenHelix for event-driven alerts\n        if self._client and alert.state == AlertState.FIRING:\n            try:\n                self._client.execute_tool(\"submit_metrics\", {\n                    \"agent_id\": self.agent_id,\n                    \"metrics\": [{\n                        \"name\": \"alerts.fired\",\n                        \"value\": 1,\n                        \"dimensions\": {\n                            \"rule\": alert.rule.name,\n                            \"severity\": alert.rule.severity,\n                            \"agent\": self.agent_id,\n                        },\n                    }],\n                })\n            except Exception:\n                pass\n\n    def _check_resolutions(\n        self,\n        metric_name: str,\n        value: float,\n        dimensions: Dict[str, str],\n    ):\n        \"\"\"Auto-resolve alerts when the condition clears.\"\"\"\n        with self._lock:\n            to_resolve = []\n            for alert_id, alert in self._active_alerts.items():\n                if alert.rule.metric_name != metric_name:\n                    continue\n                if alert.rule.condition == \"threshold\":\n                    if not self._check_threshold(alert.rule, value):\n                        to_resolve.append(alert_id)\n\n            for alert_id in to_resolve:\n                alert = self._active_alerts[alert_id]\n                alert.state = AlertState.RESOLVED\n                alert.resolved_at = time.time()\n                self._alert_history.append(alert)\n                del self._active_alerts[alert_id]\n                self._notify(alert, f\"RESOLVED: {alert.rule.name}\")\n\n    def _escalation_loop(self):\n        \"\"\"Periodically check for alerts needing escalation.\"\"\"\n        while self._running:\n            time.sleep(60)\n            now = time.time()\n            with self._lock:\n                for alert in self._active_alerts.values():\n                    if alert.state != AlertState.FIRING:\n                        continue\n                    if alert.escalated:\n                        continue\n                    age_minutes = (now - alert.fired_at) \u002F 60\n                    if age_minutes >= alert.rule.escalation_minutes:\n                        alert.escalated = True\n                        self._notify(\n                            alert,\n                            f\"ESCALATION: {alert.rule.name} has been firing for \"\n                            f\"{age_minutes:.0f} minutes without acknowledgment\",\n                        )\n\n    @staticmethod\n    def _dim_key(dimensions: Dict[str, str]) -> str:\n        if not dimensions:\n            return \"\"\n        return \",\".join(f\"{k}={v}\" for k, v in sorted(dimensions.items()))\n```\n\n### Configuring Alert Rules\n\nHere is a practical configuration for an agent commerce deployment:\n\n```python\nalert_manager = AlertManager(\n    agent_id=\"agent-marketplace\",\n    client=client,\n    anomaly_detector=detector,\n)\n\n# Configure notification channels\nalert_manager.configure_webhook(\"https:\u002F\u002Falerts.myfleet.com\u002Fwebhook\")\nalert_manager.configure_slack(\n    webhook_url=\"https:\u002F\u002Fhooks.slack.com\u002Fservices\u002FT00\u002FB00\u002Fxxx\",\n    default_channel=\"#agent-alerts\",\n)\n\n# Rule 1: High error rate\nalert_manager.add_rule(AlertRule(\n    name=\"high_error_rate\",\n    metric_name=\"transactions.errors\",\n    condition=\"threshold\",\n    threshold=0.05,\n    comparison=\"gt\",\n    severity=\"high\",\n    channels=[AlertChannel.SLACK, AlertChannel.WEBHOOK],\n    cooldown_minutes=15,\n    escalation_minutes=30,\n    description=\"Transaction error rate exceeds 5%\",\n    runbook_url=\"https:\u002F\u002Fwiki.myfleet.com\u002Frunbooks\u002Fhigh-error-rate\",\n))\n\n# Rule 2: Latency spike\nalert_manager.add_rule(AlertRule(\n    name=\"latency_spike\",\n    metric_name=\"transactions.duration_ms\",\n    condition=\"threshold\",\n    threshold=5000,\n    comparison=\"gt\",\n    severity=\"medium\",\n    channels=[AlertChannel.SLACK],\n    cooldown_minutes=10,\n    description=\"Transaction latency exceeds 5 seconds\",\n))\n\n# Rule 3: Revenue drop\nalert_manager.add_rule(AlertRule(\n    name=\"revenue_drop\",\n    metric_name=\"revenue.total\",\n    condition=\"rate_of_change\",\n    threshold=0.30,  # 30% drop\n    severity=\"critical\",\n    channels=[AlertChannel.SLACK, AlertChannel.PAGERDUTY, AlertChannel.WEBHOOK],\n    cooldown_minutes=60,\n    escalation_minutes=15,\n    description=\"Revenue dropped more than 30% in 5 periods\",\n))\n\n# Rule 4: Anomaly-based (uses AnomalyDetector)\nalert_manager.add_rule(AlertRule(\n    name=\"escrow_anomaly\",\n    metric_name=\"escrow.created\",\n    condition=\"anomaly\",\n    severity=\"medium\",\n    channels=[AlertChannel.SLACK],\n    cooldown_minutes=30,\n    description=\"Anomalous escrow creation pattern detected\",\n))\n\nalert_manager.start()\n\n# Evaluate metrics as they come in\nalert_manager.evaluate(\"transactions.errors\", 0.08, {\"operation\": \"process_order\"})\nalert_manager.evaluate(\"transactions.duration_ms\", 7500.0, {\"operation\": \"process_order\"})\n```\n\nThe deduplication logic prevents alert storms: if the same rule fires for the same dimensions, the existing alert is updated rather than creating a new notification. The cooldown period prevents re-firing too quickly after an alert resolves and re-triggers. The escalation thread ensures that un-acknowledged alerts get escalated to additional channels after the configured timeout.\n\n---\n\n## Chapter 8: SLA Monitoring and Cost Attribution\n\nThe final piece of the observability stack ties technical metrics to business commitments. SLA monitoring tracks whether your agents are meeting their published service level agreements. Cost attribution tracks where money is being spent and whether each agent is profitable.\n\n### SLA Definition and Tracking\n\nAn SLA for an agent commerce system typically includes:\n\n- **Availability**: the percentage of time the agent is accepting and processing requests (target: 99.9%)\n- **Latency**: the p95 or p99 response time for standard operations (target: under 500ms for p95)\n- **Error rate**: the percentage of transactions that fail (target: under 0.1%)\n- **Settlement time**: the time from escrow creation to settlement (target: under 24 hours)\n\n```python\nimport time\nfrom dataclasses import dataclass, field\nfrom typing import Dict, List, Optional, Any\n\n\n@dataclass\nclass SLADefinition:\n    \"\"\"An SLA definition with target and measurement parameters.\"\"\"\n    name: str\n    metric_name: str\n    target_value: float\n    comparison: str  # \"lte\" (latency), \"gte\" (availability), \"lte\" (error rate)\n    measurement_window: str  # \"1h\", \"24h\", \"7d\", \"30d\"\n    description: str = \"\"\n\n\n@dataclass\nclass SLAStatus:\n    \"\"\"Current status of an SLA.\"\"\"\n    definition: SLADefinition\n    current_value: float\n    compliant: bool\n    compliance_percentage: float  # % of measurement windows that met the SLA\n    last_violation: Optional[float] = None\n    violation_count: int = 0\n\n\nclass SLAMonitor:\n    \"\"\"Tracks SLA compliance for agent commerce operations.\"\"\"\n\n    def __init__(\n        self,\n        agent_id: str,\n        metrics_collector: \"MetricsCollector\",\n        client=None,\n    ):\n        self.agent_id = agent_id\n        self._metrics = metrics_collector\n        self._client = client\n        self._sla_definitions: Dict[str, SLADefinition] = {}\n        self._compliance_history: Dict[str, List[bool]] = defaultdict(list)\n        self._violation_callbacks: List = []\n\n    def define_sla(self, sla: SLADefinition):\n        \"\"\"Register an SLA definition.\"\"\"\n        self._sla_definitions[sla.name] = sla\n\n    def on_violation(self, callback):\n        \"\"\"Register a callback for SLA violations.\"\"\"\n        self._violation_callbacks.append(callback)\n\n    def check_sla(\n        self,\n        sla_name: str,\n        current_value: float,\n    ) -> SLAStatus:\n        \"\"\"Check if a metric value meets the SLA target.\"\"\"\n        sla = self._sla_definitions.get(sla_name)\n        if not sla:\n            raise ValueError(f\"Unknown SLA: {sla_name}\")\n\n        ops = {\n            \"lte\": lambda v, t: v \u003C= t,\n            \"gte\": lambda v, t: v >= t,\n            \"lt\": lambda v, t: v \u003C t,\n            \"gt\": lambda v, t: v > t,\n        }\n        op = ops.get(sla.comparison, ops[\"lte\"])\n        compliant = op(current_value, sla.target_value)\n\n        # Track compliance history\n        self._compliance_history[sla_name].append(compliant)\n\n        # Calculate compliance percentage (last 100 checks)\n        history = self._compliance_history[sla_name][-100:]\n        compliance_pct = sum(1 for c in history if c) \u002F len(history) * 100\n\n        status = SLAStatus(\n            definition=sla,\n            current_value=current_value,\n            compliant=compliant,\n            compliance_percentage=compliance_pct,\n            violation_count=sum(1 for c in history if not c),\n        )\n\n        if not compliant:\n            status.last_violation = time.time()\n\n            # Record violation metric\n            self._metrics.increment(\n                \"sla.violations\",\n                1.0,\n                {\"sla\": sla_name, \"agent\": self.agent_id},\n            )\n\n            for callback in self._violation_callbacks:\n                try:\n                    callback(status)\n                except Exception:\n                    pass\n\n        # Always record compliance percentage\n        self._metrics.gauge_set(\n            \"sla.compliance_pct\",\n            compliance_pct,\n            {\"sla\": sla_name, \"agent\": self.agent_id},\n        )\n\n        return status\n\n    def get_all_sla_status(self) -> Dict[str, SLAStatus]:\n        \"\"\"Get the last known status for all SLAs.\"\"\"\n        results = {}\n        for name in self._sla_definitions:\n            history = self._compliance_history.get(name, [])\n            if not history:\n                continue\n            last_100 = history[-100:]\n            compliance_pct = sum(1 for c in last_100 if c) \u002F len(last_100) * 100\n            results[name] = SLAStatus(\n                definition=self._sla_definitions[name],\n                current_value=0.0,  # Would need last observed value\n                compliant=last_100[-1] if last_100 else True,\n                compliance_percentage=compliance_pct,\n                violation_count=sum(1 for c in last_100 if not c),\n            )\n        return results\n```\n\n### Per-Agent Cost Attribution\n\nIn a multi-agent fleet, you need to know which agents are profitable and which are burning money. Cost attribution tracks every expense back to the agent that incurred it.\n\n```python\n@dataclass\nclass CostEntry:\n    \"\"\"A single cost entry attributed to an agent.\"\"\"\n    agent_id: str\n    category: str\n    amount: float\n    currency: str\n    timestamp: float\n    transaction_id: str = \"\"\n    description: str = \"\"\n\n\nclass CostAttributor:\n    \"\"\"Tracks and attributes costs across an agent fleet.\"\"\"\n\n    def __init__(self, metrics_collector: \"MetricsCollector\"):\n        self._metrics = metrics_collector\n        self._costs: Dict[str, List[CostEntry]] = defaultdict(list)\n        self._budgets: Dict[str, float] = {}\n        self._budget_callbacks: List = []\n\n    def record_cost(\n        self,\n        agent_id: str,\n        category: str,\n        amount: float,\n        currency: str = \"credits\",\n        transaction_id: str = \"\",\n        description: str = \"\",\n    ):\n        \"\"\"Record a cost attributed to an agent.\"\"\"\n        entry = CostEntry(\n            agent_id=agent_id,\n            category=category,\n            amount=amount,\n            currency=currency,\n            timestamp=time.time(),\n            transaction_id=transaction_id,\n            description=description,\n        )\n        self._costs[agent_id].append(entry)\n\n        self._metrics.record_cost(amount, category, currency)\n        self._metrics.increment(\n            \"cost_attribution.total\",\n            amount,\n            {\"agent\": agent_id, \"category\": category},\n        )\n\n        # Check budget\n        if agent_id in self._budgets:\n            total = self.get_agent_total(agent_id)\n            budget = self._budgets[agent_id]\n            utilization = total \u002F budget if budget > 0 else 0\n\n            self._metrics.gauge_set(\n                \"budget.utilization_pct\",\n                utilization * 100,\n                {\"agent\": agent_id},\n            )\n\n            if utilization >= 0.9:\n                for callback in self._budget_callbacks:\n                    try:\n                        callback(agent_id, total, budget, utilization)\n                    except Exception:\n                        pass\n\n    def set_budget(self, agent_id: str, budget: float):\n        \"\"\"Set a spending budget for an agent.\"\"\"\n        self._budgets[agent_id] = budget\n\n    def on_budget_warning(self, callback):\n        \"\"\"Register a callback for budget threshold warnings.\"\"\"\n        self._budget_callbacks.append(callback)\n\n    def get_agent_total(\n        self,\n        agent_id: str,\n        since: float = None,\n    ) -> float:\n        \"\"\"Get total costs for an agent since a given time.\"\"\"\n        costs = self._costs.get(agent_id, [])\n        if since:\n            costs = [c for c in costs if c.timestamp >= since]\n        return sum(c.amount for c in costs)\n\n    def get_agent_breakdown(\n        self,\n        agent_id: str,\n        since: float = None,\n    ) -> Dict[str, float]:\n        \"\"\"Get cost breakdown by category for an agent.\"\"\"\n        costs = self._costs.get(agent_id, [])\n        if since:\n            costs = [c for c in costs if c.timestamp >= since]\n        breakdown = defaultdict(float)\n        for cost in costs:\n            breakdown[cost.category] += cost.amount\n        return dict(breakdown)\n\n    def generate_monthly_report(\n        self,\n        month_start: float,\n        month_end: float,\n    ) -> Dict[str, Any]:\n        \"\"\"Generate a monthly cost attribution report.\"\"\"\n        report = {\n            \"period_start\": month_start,\n            \"period_end\": month_end,\n            \"agents\": {},\n            \"total_cost\": 0.0,\n            \"top_categories\": defaultdict(float),\n        }\n\n        for agent_id, costs in self._costs.items():\n            month_costs = [\n                c for c in costs\n                if month_start \u003C= c.timestamp \u003C= month_end\n            ]\n            if not month_costs:\n                continue\n\n            agent_total = sum(c.amount for c in month_costs)\n            breakdown = defaultdict(float)\n            for cost in month_costs:\n                breakdown[cost.category] += cost.amount\n                report[\"top_categories\"][cost.category] += cost.amount\n\n            budget = self._budgets.get(agent_id, 0)\n            report[\"agents\"][agent_id] = {\n                \"total_cost\": agent_total,\n                \"budget\": budget,\n                \"utilization_pct\": (agent_total \u002F budget * 100) if budget else 0,\n                \"transaction_count\": len(month_costs),\n                \"breakdown\": dict(breakdown),\n            }\n            report[\"total_cost\"] += agent_total\n\n        report[\"top_categories\"] = dict(\n            sorted(\n                report[\"top_categories\"].items(),\n                key=lambda x: x[1],\n                reverse=True,\n            )\n        )\n\n        return report\n```\n\n### Putting It All Together\n\nHere is how all the observability components integrate for a production agent deployment:\n\n```python\nfrom greenhelix import GreenHelixClient\n\n# Initialize core components\nclient = GreenHelixClient(api_key=\"your-api-key\")\ntracer = AgentTracer(agent_id=\"agent-marketplace\", client=client)\nmetrics = MetricsCollector(agent_id=\"agent-marketplace\", client=client)\ndetector = AnomalyDetector()\nalert_manager = AlertManager(\n    agent_id=\"agent-marketplace\", client=client, anomaly_detector=detector\n)\nsla_monitor = SLAMonitor(\n    agent_id=\"agent-marketplace\", metrics_collector=metrics, client=client\n)\ncost_tracker = CostAttributor(metrics_collector=metrics)\n\n# Define SLAs\nsla_monitor.define_sla(SLADefinition(\n    name=\"availability\",\n    metric_name=\"agent.availability_pct\",\n    target_value=99.9,\n    comparison=\"gte\",\n    measurement_window=\"24h\",\n))\n\nsla_monitor.define_sla(SLADefinition(\n    name=\"latency_p95\",\n    metric_name=\"transactions.duration_ms\",\n    target_value=500,\n    comparison=\"lte\",\n    measurement_window=\"1h\",\n))\n\n# Set budgets\ncost_tracker.set_budget(\"agent-marketplace\", budget=1000.0)\ncost_tracker.set_budget(\"agent-data-provider\", budget=500.0)\n\n# Wire SLA violations to alerts\nsla_monitor.on_violation(lambda status: alert_manager.evaluate(\n    status.definition.metric_name,\n    status.current_value,\n    {\"sla\": status.definition.name},\n))\n\n# Wire budget warnings to alerts\ncost_tracker.on_budget_warning(\n    lambda agent, total, budget, util: alert_manager.evaluate(\n        \"budget.utilization_pct\",\n        util * 100,\n        {\"agent\": agent},\n    )\n)\n\n# Start background threads\nmetrics.start()\nalert_manager.start()\n\n# Now every transaction is automatically traced, metered, checked,\n# and alerted on:\ndef handle_transaction(request):\n    with tracer.trace_agent_call(\n        request[\"target\"], request[\"operation\"]\n    ) as span:\n        start = time.time()\n        result = process(request)\n        duration_ms = (time.time() - start) * 1000\n\n        # Metrics\n        metrics.record_transaction(\n            operation=request[\"operation\"],\n            duration_ms=duration_ms,\n            amount=request.get(\"amount\", 0),\n            status=\"success\" if result[\"ok\"] else \"error\",\n            peer_agent=request[\"target\"],\n        )\n\n        # Anomaly detection + alerting\n        alert_manager.evaluate(\"transactions.duration_ms\", duration_ms)\n        alert_manager.evaluate(\n            \"transactions.errors\",\n            0 if result[\"ok\"] else 1,\n        )\n\n        # SLA check\n        sla_monitor.check_sla(\"latency_p95\", duration_ms)\n\n        # Cost attribution\n        cost_tracker.record_cost(\n            agent_id=\"agent-marketplace\",\n            category=\"gateway_fee\",\n            amount=result.get(\"fee\", 0),\n            transaction_id=result.get(\"transaction_id\", \"\"),\n        )\n\n        return result\n```\n\nThis integration means every transaction flowing through your agent automatically generates traces for debugging, metrics for dashboards, anomaly detection for automated problem finding, alerts for operator notification, SLA tracking for compliance reporting, and cost attribution for business analysis. The operational overhead is minimal -- a few milliseconds of in-process buffering per transaction -- and the visibility gain is transformative.\n\n---\n\n## What's Next\n\nThis guide built the observability stack from the bottom up: tracing, metrics, anomaly detection, dashboards, alerting, and SLA monitoring. Each component works independently but delivers maximum value when integrated.\n\nTo put this into production, start with the `AgentTracer` and `MetricsCollector`. These two components give you immediate visibility with minimal effort. Add the `AnomalyDetector` once you have a few days of baseline data. Configure the `AlertManager` with conservative thresholds and tighten them as you learn your system's normal patterns. Roll out `SLAMonitor` and `CostAttributor` when you have paying customers who need compliance reports.\n\nThe next guides in this series cover agent security hardening (protecting your fleet from adversarial agents), agent marketplace economics (pricing strategies and commission structures), and agent scaling patterns (handling 100x traffic growth without rewriting your stack). Each builds on the observability foundation established here because you cannot secure, price, or scale what you cannot see.\n\n",{"name":5,"tags":24,"type":30,"author":34,"install":35,"license":15,"version":36,"price_usd":37,"executable":20,"credentials":35,"description":7,"content_type":38,"compatibility":39},[25,26,27,28,29,30,31,32,33],"observability","monitoring","tracing","metrics","opentelemetry","guide","greenhelix","openclaw","ai-agent","felix-agent","none","1.3.1",49,"markdown",[32],"master","4aa004da461d820f4ea5499e58eb8d196cf99016","community\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-observability-stack",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":50,"prompt":60,"zipAvailable":61},[51,54,57],{"tool":52,"command":53},"npx","npx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-observability-stack",{"tool":55,"command":56},"bunx","bunx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-observability-stack",{"tool":58,"command":59},"pnpm","pnpm dlx skills add Lord1Egypt\u002Fawesome-skill-forge --skill greenhelix-agent-observability-stack","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FLord1Egypt\u002Fawesome-skill-forge\u002Fblob\u002Fmaster\u002Fcommunity\u002Fclawhub\u002Fg\u002Fgreenhelix-agent-observability-stack\u002FSKILL.md",true,[],[64,71,78,85,92,99],{"skillNo":65,"name":66,"nameZh":6,"description":67,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":68,"categories":69,"keywords":70,"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":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},"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":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},"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":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},"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":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},"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":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},"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",[],[]]