# Authentication Source: https://docs.moda.dev/administration/authentication Create API keys, use the right auth header for each API, and authenticate the CLI. Moda uses one credential for data access — the API key — plus a browser-based CLI session for CLI setup commands. This page covers creating and revoking keys, the header each API expects, and CLI authentication for interactive and headless use. ## API keys API keys (called ingestion keys in the dashboard) authenticate both the Ingestion API and the Data API. **1. Open Settings → Ingestion keys** Creating and revoking keys requires the admin or owner role. All members can view the key list. **2. Create a key** Click **New ingestion key** and name it. Keys never expire unless you set an optional expiry date. **3. Copy the key now** The full key is shown once, at creation. Afterwards the list shows only the key's name, prefix, creation date, age, last-used date, and expiry. Keys start with `moda_sk_` and are bound to the workspace they were created in. A key cannot be moved or re-pointed to another workspace — the server derives the workspace from the key on every request. ## Which header to use The two APIs read different headers. Sending the wrong one returns `401`. | API | Base URL | Auth header | | - | - | - | | Ingestion API | `https://moda-ingest.modas.workers.dev` | `Authorization: Bearer moda_sk_...` | | Data API | `https://moda.dev/api/v1/data` | `x-api-key: moda_sk_...` | > [!NOTE] > > The Ingestion API also accepts the bare key in the `Authorization` header, without the `Bearer ` prefix. Ingestion API example: ```bash theme={"dark"} curl -X POST https://moda-ingest.modas.workers.dev/v1/ingest \ -H "Authorization: Bearer YOUR_MODA_API_KEY" \ -H "Content-Type: application/json" \ -d '{"events":[{"conversation_id":"conv_123","role":"user","message":"Hello"}]}' ``` ```json theme={"dark"} { "success": true, "count": 1, "requestId": "7f9b2c9e-0a41-4c3e-9f1a-2d5c8e7b6a90" } ``` A missing header returns `401` with `{"success": false, "count": 0, "message": "Missing Authorization header", "requestId": "..."}`; a revoked, expired, or malformed key returns `401` with `"Invalid or expired API key"`. Data API example: ```bash theme={"dark"} curl "https://moda.dev/api/v1/data/tool-failures?days_back=7" \ -H "x-api-key: YOUR_MODA_API_KEY" ``` ```json theme={"dark"} { "summary": { "total": 42, "total_calls": 1875, "conversations": 31, "tools": 3, "failure_rate_pct": 2.2 }, "tools": [ { "tool_name": "search_flights", "failure_count": 28, "total_count": 640, "failure_rate_pct": 4.4, "conversation_count": 22, "top_error": "Upstream timeout after 10s", "last_seen": "2026-08-15T21:04:11Z" } ] } ``` In the SDKs, the Python SDK's `moda.init()` reads the `MODA_API_KEY` environment variable; the Node.js SDK's `Moda.init(apiKey, options)` requires the key as an explicit argument. See [Python](/ingestion/python) and [Node.js](/ingestion/node). ## Key expiry Keys do not expire by default. To limit a key's lifetime, set an expiry date when you create it; the key stops working at the end of that day, in your browser's time zone. An expiry cannot be changed later. Expired keys stay in the list, marked **Expired**, and are refused by both the Ingestion API and the Data API with the same `401` as a revoked key. Rotate a key before it expires so ingestion does not stop: create the new key and deploy it everywhere first. ## Revoking a key Revoke keys in **Settings → Ingestion keys** (admin or owner role). > [!WARNING] > > The Ingestion API caches key-validation results for up to 60 seconds, so a revoked key can continue to ingest for up to a minute after revocation. To rotate without data loss, create the new key, deploy it everywhere, then revoke the old one. ## CLI authentication The CLI uses two credentials: * **CLI session** — `moda auth login` opens the browser; signing in creates a CLI session used by setup and control commands such as `moda init` and `moda provision`. `moda auth status` shows the current session (exit code 4 when logged out); `moda auth logout` revokes it. * **API key** — Data API commands (`moda traces search`, `moda overview`, `moda detections list --family=emotion`, `moda problems get`, `moda tail`, ...) use an API key, not the session; this includes the write commands `moda problems feedback` and `moda problems link`. The CLI resolves the key in this order: the `MODA_API_KEY` environment variable, then the active profile, then `~/.moda/config.json`. ### Headless and CI: `moda provision` `moda provision` mints (or reuses) a workspace API key without any prompts and prints exactly one JSON document to stdout: ```json theme={"dark"} { "apiKey": "moda_sk_...", "tenantId": "…", "tenantName": "…", "tenantSlug": "…", "ingestUrl": "https://moda-ingest.modas.workers.dev", "baseUrl": "https://moda.dev", "reused": false } ``` It requires an existing CLI session and never opens a browser — run `moda auth login` on a machine with a browser first, then provision. Typical use for CI is provisioning locally and storing the key as a CI secret: ```bash theme={"dark"} moda auth login MODA_API_KEY="$(moda provision | jq -r .apiKey)" ``` Behavior: * Exit code 4 when no CLI session exists. * Exit code 5 when your account belongs to multiple workspaces and neither `--tenant-id` nor `MODA_TENANT_ID` selects one. * `--label` names the key (defaults to the hostname); `--save` persists the credentials to `~/.moda/config.json`; `reused: true` means an existing key was returned instead of a new one. ## Next steps * [Ingestion overview](/ingestion/overview) — where the Bearer header is used. * [Data API overview](/data-api/overview) — where the `x-api-key` header is used. * [Team](/administration/team) — the roles that gate key creation and revocation. * [Limits](/administration/limits) — request and query limits across both APIs. # Limits Source: https://docs.moda.dev/administration/limits Request size, batch, and query limits across the Ingestion API, Data API, dashboard, and CLI. This page consolidates every customer-visible limit and the exact behavior when you hit it. ## Ingestion API | Limit | Value | Behavior when exceeded | | - | - | - | | Request body (all endpoints) | 5 MB | `413` with `{"success": false, "count": 0, "message": "Request too large", "requestId": "..."}` | | Events per batch (`/v1/ingest`, `/v1/ingest/multi`) | 1,000 | `400` with `"Batch size exceeds limit of 1000"` | | Spans per OTLP request (`/v1/traces`) | No count limit — only the 5 MB body cap | `413` | There are currently no rate limits on the Ingestion API; it does not return `429`. Transient overload surfaces as `503` with `"retryable": true` — retry with backoff. See [Reliability](/ingestion/reliability). Error envelope on JSON endpoints: ```json theme={"dark"} { "success": false, "count": 0, "message": "...", "requestId": "...", "retryable": true } ``` | Status | Meaning | | - | - | | 200 | Accepted; `count` is the number of stored rows | | 400 | Invalid body, event validation failure, batch over 1,000, or invalid `environment` | | 401 | Missing, invalid, or revoked API key | | 413 | Body over 5 MB | | 500 | Internal error | | 503 | Temporary backpressure — safe to retry (`retryable: true`) | Unknown paths return a plain-text `404`. An optional `X-Request-ID` header (UUID) is echoed back as `requestId` for correlating requests with responses. ### Environments Accepted environment values: `development`, `staging`, `production`. * The request-level `environment` field on `/v1/ingest` and `/v1/ingest/multi` must be exactly one of the three values; anything else returns `400` listing the valid values. It defaults to `production`. * Environment values carried on OTLP attributes (`moda.environment` span attribute, `deployment.environment` resource attribute) normalize common aliases — `dev`/`develop` → `development`, `stg`/`stage` → `staging`, `prod` → `production` — and unknown values fall back to `production`. ## Data API Out-of-range numeric parameters are clamped to their maximum — they do not error. Invalid enum values and over-length strings return `400`. | Parameter | Cap | Behavior when exceeded | | - | - | - | | `days_back` | 90 | Clamped | | `offset` | 10,000 | Clamped | | `window` (context endpoints) | 5 | Clamped | | `q` (`/search` query) | 500 characters | `400` | | `note` (`POST /feedback`) | 4,000 characters | `400` | Per-endpoint `limit` caps: | Endpoint | Maximum `limit` | | - | - | | Most list endpoints | 100 | | `/frustrations`, `/emotions`, `/hallucinations` | 20 | | `/tool-failures/{toolName}` (examples) | 20 | | `/problems` | 25 | | `/tools` | 200 | | `/problems/{id}/reports`, `/problems/{id}/conversations`, `/problems/{id}/evidence` | 50 | ## Dashboard and CLI **CLI key limit.** Each workspace caps the number of active CLI-created keys (named `CLI - ...`). The default is 10; admins and owners can set it between 1 and 100 in **Settings → Ingestion keys**. ## Next steps * [Reliability](/ingestion/reliability) — retry guidance and error envelopes in depth. * [Data API overview](/data-api/overview) — endpoints these clamps apply to. * [Authentication](/administration/authentication) — key management and revocation timing. # Members and roles Source: https://docs.moda.dev/administration/team Invite teammates to your workspace and control what each role can do. Manage workspace access at **Settings → Members & roles**. Teammates join an existing workspace through invitations. Anyone can sign up at [moda.dev/signup](https://moda.dev/signup), but a new workspace is only created once the Moda team approves the request. ## Roles Every member has one of three roles: | Role | Summary | | - | - | | Viewer | Read-only access to the dashboard. The default role for invitations. | | Admin | Everything a viewer can do, plus workspace management: keys, members, integrations, and workspace settings. | | Owner | Everything an admin can do, plus promoting members to admin and transferring ownership. | What each action requires: | Action | Viewer | Admin | Owner | | - | - | - | - | | View traces, signals, problems, and other dashboard data | Yes | Yes | Yes | | View the ingestion-key list | Yes | Yes | Yes | | Create and revoke ingestion keys | — | Yes | Yes | | Invite members and cancel pending invitations | — | Yes | Yes | | Change a member's role to Viewer | — | Yes | Yes | | Promote a member to Admin | — | — | Yes | | Remove a member | — | Yes | Yes | | Rename the workspace | — | Yes | Yes | | Adjust the CLI key limit | — | Yes | Yes | | Transfer ownership | — | — | Yes | The owner's role cannot be changed and the owner cannot be removed; ownership moves only through a transfer. ## Inviting a member **1. Open the invite dialog** In **Settings → Members & roles**, click **Invite member**. Requires the admin or owner role. **2. Enter the email and role** Choose **Viewer** (read-only access, the default) or **Admin** (can manage settings and invite members). Invitations cannot grant the Owner role. **3. Send and track** The invitation appears under pending invitations, where it can be cancelled or resent. It expires after 7 days. If the email cannot be sent, Settings shows an error and keeps the invitation available under **Pending invitations**. Click **Resend email** to try again; there is no need to cancel and recreate it. **4. The invitee accepts** The invitee opens the invitation link, accepts, and lands in the workspace with the assigned role. > [!NOTE] > > Invitations work for both new and existing Moda accounts. The recipient must sign in with the invited email address. If they already belong to this workspace, the invite dialog tells you that they are already a member. ## Changing roles and removing members Admins and owners manage membership from the member list: * Change any non-owner member's role. Only the owner can promote a member to Admin; admins can set members to Viewer. * Remove any non-owner member. You cannot change your own role or remove yourself. ## Transferring ownership Only the owner can transfer ownership. In the member list, set another member's role to **Owner**; a confirmation dialog completes the transfer. After the transfer, the previous owner becomes an Admin and can no longer transfer ownership. ## Next steps * [Authentication](/administration/authentication) — the key management actions these roles gate. * [Limits](/administration/limits) — the CLI key limit admins can adjust. * [Quickstart](/quickstart) — get data flowing once your team has access. # Using the CLI from agents and CI Source: https://docs.moda.dev/cli/agents Drive the moda CLI from coding agents and CI pipelines: agent envelopes, exit-code handling, headless provisioning, and runnable examples. The `moda` CLI is built to be called by coding agents and CI jobs with zero configuration: when stdout is piped, `CI` is set, or an agent environment is detected (`CLAUDECODE`, `CURSOR`, `MODA_AGENT`), every command emits schema-versioned JSON and signals its state through exit codes. This page documents the machine protocol and gives complete, runnable recipes. ## Agent mode No flags are needed in automation — detection order is explicit flags → `MODA_FORMAT` → agent environment → TTY (see [Output formats](/cli/overview#output-formats)). To force it anywhere, set `MODA_AGENT=1` or pass `--agent`. Three output contracts matter to a machine caller: | Invocation | stdout | | - | - | | `moda --agent` (or auto-detected) | One `moda.agent.v1` envelope | | `moda --agent --stream` | NDJSON `moda.agent_event.v1` events | | `moda --json` | The raw payload only (no envelope); errors still print a structured error envelope | | `moda tail` | NDJSON: one JSON line per event in every output mode | These commands always bypass envelopes so their stdout can be captured directly: `moda provision` (one JSON credentials document), `moda auth token` / `moda auth api-key` (the bare credential), and `moda tail` (typed NDJSON records such as `{"type":"conversation",...}`; emotions polls also emit a `tail_coverage` metadata record `{complete, scanned, total, coverage_pct}` because the emotions endpoint is score-ranked with no cursor, and a one-time `tail_dedupe_evicted` record if dedupe memory rolls over. `--max-events` bounds every stdout record including metadata; a reserved slot keeps the coverage record in-stream, and if the bound leaves no room it is written to stderr rather than dropped). Discover the full protocol at runtime: ```bash theme={"dark"} moda manifest --json # commands, env vars, exit codes, stream events moda --json-schemas # JSON Schemas for the envelope and event contracts ``` ## The `moda.agent.v1` envelope **schema_version** `string` Always `"moda.agent.v1"`. **command** `string` The command that produced the envelope. **status** `string` `ok`, `degraded` (answer produced from a lower-trust fallback), or `error`. **generated_at** `string` ISO 8601 timestamp. **profile** `string` Active profile name, when one is set. **summary** `object` `{ text, confidence }` — one-line result summary; `confidence` is `high` | `medium` | `low` | `unknown`. **findings** `array` Ranked findings, each `{ id, title, status?, severity?, description?, evidence_ref_ids? }`. **evidence_refs** `array` Evidence behind the findings: `{ id, kind, label, path?, line?, href? }`. `href` is a root-relative dashboard link — prefix the Moda base URL to open it. **recommended_actions** `array` Suggested follow-ups: `{ id, title, rationale?, command?, mutability, requires_approval }`. **next_commands** `array` Commands the agent can run next: `{ command, purpose, mutability, requires_approval }`. `mutability` is `read` | `write` | `sync` | `unknown` — treat anything other than `read` as needing user approval when `requires_approval` is true. **artifacts** `array` Files the command created or verified: `{ kind, path, description? }`. **warnings** `array` Non-fatal warnings (strings). **errors** `array` Structured errors: `{ code, message, cause?, suggested_commands?, input_request?, auth?, blocking }`. Codes include `input_error`, `api_error`, `network_error`, `auth_required`, `input_required`, `cancelled`, `command_error`, `access_denied`, `cloud_unavailable`, `output_error`, `unknown_error`. **data** `object` The command payload — the same JSON `--json` would print, except that three commands trim it to fit agent context: `frustrations` and `emotions` leave out each row's embedded conversation window unless you pass `--include-window` (rows carry `anchor` and a `context_command` instead), and `problem ` returns a compact dossier (`view: "compact"`) unless you pass `--full`. **meta** `object` `run_id` plus a `tip` string on successful envelopes. **truncation** `object` Present when the envelope was bounded to fit `MODA_AGENT_MAX_OUTPUT_BYTES` (default 24,000 bytes for the whole envelope, under the 30,000-character limit at which agent harnesses such as Claude Code cut tool output). Text is never shortened: the complete output (the same JSON `--json` prints) is written to a local file at `truncation.data.full_output_path` (also listed in `artifacts` with kind `full_output`). Redundant fields go first: a message's `content_blocks` is removed when its `content` and tool calls already hold the same thing (counted in `truncation.data.shed_fields`). If that is not enough, whole trailing list items are dropped from `data`, counted in `truncation.data.dropped_items` and `omitted_rows`, with `complete: false`. The list's `pagination` is then rewritten to describe what was returned: `limit` and `returned` are the rows kept, `requested_limit` is what was asked for, `next_offset` starts at the first dropped row, and a server `next_cursor` that would skip the dropped rows is set to `null`. `next_commands` gets the exact command that fetches the dropped rows (for example `moda detections list --family=frustration --offset=3 --limit=7`), and a warning says how many rows were left out and where the full output file is. If even one item is over budget, `data` is a stub `{ truncated: true, original_bytes, max_bytes, full_output_path }`. Some commands size their own pages so nothing is cut behind a continuation: `moda traces get` keeps a window's anchor message and pages each trimmed side with `--all --from`, `--all` reads only about what fits, `moda traces spans` cuts an oversized page by spans and continues it with `--span-offset` before handing out `next_cursor`, and batch reads, `--include-window` and `--include-world-state` stop reading once the budget is spent. Files go to `MODA_AGENT_OUTPUT_DIR` (default `/moda-agent-output-`, a directory only your user can read; the CLI refuses it if another user owns it or it is a symlink). If that file cannot be written (unwritable directory, full disk), nothing is dropped or stubbed: the envelope keeps the whole result over the limit, `status` is `error` with an `output_error`, and the command exits `1`. Writing a new file prunes full-output files there older than `MODA_AGENT_OUTPUT_RETENTION_HOURS` (default 24), so copy any you need to keep. Secrets are redacted from every envelope and event before they are written. ## Streaming events (`moda.agent_event.v1`) `--agent --stream` (or `MODA_FORMAT=ndjson`) emits one JSON event per line for long-running commands such as `moda init`: | Event | Terminal | Meaning | | - | - | - | | `started` | no | First event of every stream. | | `progress` | no | Work continues; carries `phase` and `message`. | | `warning` | no | Non-fatal warning or skipped action. | | `artifact` | no | A file was produced. | | `heartbeat` | no | Liveness signal after `MODA_HEARTBEAT_MS` (default 10 s) without output. | | `completed` | yes | Success; carries the full envelope as `result`. | | `error` | yes | Failure; carries `error` and the error envelope. | | `needs_input` | yes | Exit-and-reinvoke input request (`input_request` payload). | | `auth_required` | yes | Authentication needed before retrying (`auth` payload). | | `cancelled` | yes | Interrupted. | Every stream shares one `run_id`, `seq` counts gaplessly from 1, and exactly one terminal event ends the stream. ## Exit-code handling | Code | State | What a caller should do | | - | - | - | | `0` | ok | Use the result. | | `1` | error | Read `errors[0].message`; retry only for `network_error`/`api_error` where sensible. | | `3` | degraded | `moda ask`: an answer exists but was synthesized locally (`data.degraded: true`) — treat as lower trust. | | `4` | auth required | Run `errors[0].auth.login_command`, then re-run `errors[0].auth.resume_command`. | | `5` | input required | Pick a choice from `errors[0].input_request.choices` and re-invoke with its `resume_flags`. | | `130` | cancelled | Stop; the run was interrupted or the pipe closed. | A complete handler: ```bash ask-moda.sh theme={"dark"} #!/usr/bin/env bash # Ask Moda a production question and branch on the exit code. set +e moda --agent ask "what should I fix first this week?" > ask.json status=$? set -e case "$status" in 0) jq -r '.summary.text' ask.json ;; 3) echo "Degraded answer (Moda Cloud unavailable; synthesized from local evidence):" jq -r '.summary.text' ask.json ;; 4) echo "Auth required. Run:" >&2 jq -r '.errors[0].auth.login_command | join(" ")' ask.json >&2 exit 4 ;; 5) echo "Input required. Choices:" >&2 jq -r '.errors[0].input_request.choices[] | "\(.label) -> \(.resume_flags | join(" "))"' ask.json >&2 exit 5 ;; 130) exit 130 ;; *) jq -r '.errors[0].message // "unknown error"' ask.json >&2 exit 1 ;; esac ``` ## `moda provision` in CI `moda provision` never opens a browser and never prompts, so the login happens once on a machine with a browser; CI then either stores the printed key as a secret (recommended) or reuses a copied session. Mint the key locally and store it as a repository secret in one line: ```bash theme={"dark"} moda auth login moda provision --tenant-id=1f7c9a2e-4b3d-4c8e-9a1b-2d3e4f5a6b7c --label=github-actions \ | jq -r .apiKey \ | gh secret set MODA_API_KEY ``` Provision prints exactly one JSON document (`{apiKey, tenantId, tenantName, tenantSlug, ingestUrl, baseUrl, reused}`) to stdout in every output mode, so `jq -r .apiKey` always works. Failure modes to script around: exit 4 = no stored session (log in first), exit 5 = multiple tenants and no `--tenant-id`/`MODA_TENANT_ID` (the error's `input_request.choices` lists each tenant with `resume_flags`). > [!WARNING] > > The provision output contains a live API key. Pipe it directly into your secret store — never into build logs. ## Example: fail CI on tool-failure regressions A scheduled job that reads the last 24 hours of tool failures and fails when any tool crosses a regression threshold. `--json` is passed explicitly: in CI the auto-detected mode would be `agent`, which wraps the payload in an envelope (you would then read `.data.tools` instead of `.tools`). ```yaml .github/workflows/moda-tool-failure-gate.yml theme={"dark"} name: Moda tool-failure gate on: schedule: - cron: "0 6 * * *" workflow_dispatch: jobs: gate: runs-on: ubuntu-latest env: MODA_API_KEY: ${{ secrets.MODA_API_KEY }} steps: - name: Fail on new tool-failure regressions run: | npx -y @moda-ai/cli tool-failures --json --days-back=1 > failures.json echo "Tools with failures in the last 24h:" jq -r '.tools[] | "\(.tool_name): \(.failure_count)/\(.total_count) calls failed (\(.failure_rate_pct)%)"' failures.json # Regression rule: any tool with >= 5 failures AND a failure rate above 10%. regressions=$(jq '[.tools[] | select(.failure_count >= 5 and .failure_rate_pct > 10)] | length' failures.json) if [ "$regressions" -gt 0 ]; then jq -r '.tools[] | select(.failure_count >= 5 and .failure_rate_pct > 10) | "::error::\(.tool_name): \(.failure_count) failures — \(.top_error)"' failures.json exit 1 fi ``` Adjust the thresholds to your traffic; `failure_rate_pct` alone spikes on low-volume tools, which is why the rule also requires an absolute failure count. The same pattern works for `moda detections list --family=emotion --json` (`.summary.negative_rate_pct`, the multi-family emotion model; `moda detections list --family=frustration` returns the frustration family of the same data in the legacy field names) and `moda problems list --view=book --json` (`.summary.open_problems`; without `--view=book` a dream-grouped tenant gets the dream view, whose `.summary.problems` counts its problems). > [!NOTE] > > The CLI's daily update check is automatically skipped in CI, and usage telemetry can be disabled with `MODA_CLI_TELEMETRY=0` or `DO_NOT_TRACK=1`. ## Example: letting a coding agent investigate A coding agent with `MODA_API_KEY` in its environment can investigate production behavior with read-only commands. Every command below auto-detects agent mode and returns envelopes; result rows carry `conversation_id` (the trace ID) + `message_index` anchors that chain into the next command: ```bash theme={"dark"} # 1. Find where users hit the problem (results carry conversation_id + message_index) moda traces search "refund failed" --mode=hybrid --time-range=7d --limit=5 # 2. Read the exact turns around a hit from step 1 moda traces get conv_5e1a9c2b7d3f4680 --msg-index=12 --window=2 # 3. Inspect what the agent knows about the trace now: its tasks and facts moda traces state conv_5e1a9c2b7d3f4680 # 4. Check whether a tool is behind it (anchors + optional context windows) moda detections tools refundPayment --include-window # 5. Open the ranked Problem behind the pattern, with its evidence # (the list the dashboard shows: the dream grouping when published, else the Book) moda problems list moda problems get 3f2a9c1e-8b4d-4e6f-9a2b-1c3d5e7f9a0b --evidence --limit=10 # 6. Ask for a cited synthesis (exit 3 = degraded local fallback) moda ask "why do refunds fail for enterprise users?" ``` Other read-only entry points: `moda detections list --family=emotion:confusion` and `moda detections list --family=hallucination --kind=contradicted` for signal triage, `moda clusters --search="refunds"` to resolve a use-case node by meaning, and `moda tail --once --signal=all` for a one-poll snapshot of live activity (new traces plus emotion detections). When a fix ships, close the loop with `moda problems feedback --action=mark_fixed`; to hand a Problem to your team, `moda problems link ` files it as a Linear issue (needs the Linear integration connected). These are the two writes in this family. Guidance worth encoding in your agent's instructions: * **Follow `next_commands`.** Envelopes suggest the next useful invocation, with `mutability` and `requires_approval` so the agent knows what is safe to run unprompted. (`moda agent next-action` is different: it suggests setup steps for the local repo, such as `moda init`.) * **Learn a command with `moda --help`**: it lists every flag with its type, range, and default. `moda manifest --json` is the full machine catalog (about 20k tokens), and `moda agent context` reports repo-local Moda state; both work offline. * **Branch on exit code 3 for `moda ask`.** A degraded answer is still an answer; the envelope's `status` is `degraded` and `data.degraded` is `true`. * **Respect search degradation.** `data.search_mode` is the mode that actually ran and `degrade_reason` says why; scores are not comparable across modes. * **Report bad data.** `moda feedback "" --conversation-id=...` flags wrong or missing results to the Moda team; envelopes remind agents via `meta.tip`. ## Next steps * [CLI reference](/cli/reference) — every command, flag, and output shape. * [CLI overview](/cli/overview) — install, auth, profiles, exit codes. * [Connect the MCP server](/mcp/overview) — the core read commands as MCP tools when your agent speaks MCP instead of shelling out. Some CLI commands (custom signal management, false-positive marks, users, registry) are CLI-only; see [parity](/mcp/parity). # Prompt, skill, and harness commands Source: https://docs.moda.dev/cli/hidden-features ## Prompt management Code-first prompt workflow — see [Prompt management](/prompt-management/overview) for concepts and [Workflow](/prompt-management/workflow) for the end-to-end guide. Running `moda prompts` with no subcommand is equivalent to `moda prompts status`. ### moda prompts init Creates `.moda/prompts.yml` if absent (never overwrites). The default manifest is version 2: `prompt_paths` discovers `prompts/**/*.prompt.{md,json,yaml,yml}` (exact globs from the repository root), and an empty `sources: []` list holds prompts mapped in code. See [Workflow](/prompt-management/workflow#map-prompts-defined-in-code). Paths are resolved against the current working directory, so run it from the project root. `created` distinguishes a fresh scaffold from an existing manifest, and `manifestPath` is the absolute path to verify — the agent envelope also lists it under `artifacts`. ```bash theme={"dark"} moda prompts init ``` ```json Output theme={"dark"} { "manifest": ".moda/prompts.yml", "manifestPath": "/home/you/project/.moda/prompts.yml", "lockfile": ".moda/prompts.lock.json", "lockPath": "/home/you/project/.moda/prompts.lock.json", "cwd": "/home/you/project", "created": true, "promptPaths": ["prompts/**/*.prompt.md", "prompts/**/*.prompt.json", "prompts/**/*.prompt.yaml", "prompts/**/*.prompt.yml"] } ``` If the manifest is not on disk after the run, the command exits non-zero with a `write_failed`-style error rather than reporting `status: "ok"`. ### moda prompts status / moda prompts diff Local-only comparison of discovered prompt files against `.moda/prompts.lock.json`. No network call. `status` lists every prompt; `diff` lists only the prompts that are `changed`, `new`, or `deleted` (plus an `unchanged` count). Neither is a textual diff: the lockfile stores content hashes only. Per-prompt `state` is `new`, `changed`, `unchanged`, or `deleted`. ```bash theme={"dark"} moda prompts status ``` ```json Output (trimmed) theme={"dark"} { "manifest": ".moda/prompts.yml", "lockfile": ".moda/prompts.lock.json", "manifestVersion": 2, "legacyManifest": false, "zeroMatchPatterns": [], "legacyOnlyFiles": [], "sources": 1, "total": 3, "changed": 1, "new": 0, "deleted": 0, "prompts": [ { "key": "support.triage", "sourcePath": "prompts/support/triage.prompt.md", "contentHash": "b41f0c…", "lockedHash": "a92c7e…", "versionId": "pver_1f2e3d4c5b6a79880911223344556677", "state": "changed" } ] } ``` `zeroMatchPatterns` lists `prompt_paths` patterns that match no file. `legacyOnlyFiles` lists `.prompt.*` files that older CLIs discovered anywhere in the repository but the current exact globs miss. When either is non-empty the command adds a warning, pointing at `moda prompts migrate` for legacy-only files. ### moda prompts migrate Rewrites `.moda/prompts.yml` to version 2. It keeps every pattern, `sources:` entry, and comment, adds an explicit `prompt_paths` entry for each legacy-only file (so its key and lockfile entry are unchanged), and ensures a `sources:` list. The write is atomic, and a manifest that is already version 2 with nothing to add is left alone. Local-only. ```bash theme={"dark"} moda prompts migrate --dry-run moda prompts migrate ``` | Flag | Default | Description | | - | - | - | | `--dry-run` | off | Return the migrated manifest (`content`) without writing it. | | `--discover` | off | Also scan for code-defined prompts (no agent calls). Adds only mappings that need no semantic verification; lists the rest under `pendingSources` with the command that verifies them. | The output lists `addedPaths`, `addedSources`, `zeroMatchPatterns` (kept, reported for you to fix), and `changed`. ### moda prompts sync Uploads all discovered prompts (unchanged ones are server-side no-ops — versions are content-addressed and immutable), moves each prompt's `current` pointer to the synced version, and writes `.moda/prompts.lock.json`. ```bash theme={"dark"} moda prompts sync ``` ```json Output (trimmed) theme={"dark"} { "synced": [ { "key": "support.triage", "promptId": "prompt_0a1b2c3d4e5f60718293a4b5", "versionId": "pver_1f2e3d4c5b6a79880911223344556677", "contentHash": "b41f0c…", "sourcePath": "prompts/support/triage.prompt.md" } ], "lockfile": ".moda/prompts.lock.json" } ``` | Flag | Default | Description | | - | - | - | | `--dry-run` | off | Compute IDs without writing anything (no lockfile update). | | `--from-harness[=]` | off | First register prompt mappings from a harness report (default `.moda/harness-report.json`). Older reports are normalized; prompts that do not resolve are listed in `harnessImport.skipped` with a reason. Fails only when none resolve. | | `--watch` | off | Poll local files and re-sync on change. | | `--interval` | 2500 | Poll interval in ms for `--watch` (min 1,000). | ### moda prompts promote Moves a release label (`dev`, `staging`, `prod`) to a specific version. Returns the updated prompt with all versions. ```bash theme={"dark"} moda prompts promote support.triage --label=prod --version=pver_1f2e3d4c5b6a79880911223344556677 ``` | Argument / flag | Description | | - | - | | `` | Prompt key (required). | | `--label` | `dev`, `staging`, or `prod` (required). | | `--version` | Target version ID from the lockfile (`--version-id` is an alias; required). | > [!NOTE] > > A `dev` promotion moves the same pointer that every sync overwrites, so it is replaced by the next `moda prompts sync`. Use `staging`/`prod` for stable release labels. ## Skills Skill commands manage the SKILL.md files your coding agents use. `moda skills push` talks to the control plane using your API key; `moda skills install` runs offline. ### moda skills install Copies the integration guides bundled with the CLI into `.claude/skills//` (and `.cursor/rules/.mdc` when the project uses Cursor), so your own coding agent can follow them. Runs offline and never overwrites files Moda does not manage. `--list` prints every bundled guide. `moda skills install moda-cli` installs or refreshes the CLI's own `moda-cli` skill for every detected coding agent, the same step `moda init` runs, without the rest of the wizard. Run it after upgrading the CLI so the guide matches the new version. A copy you edited locally is kept and reported as `kept`. ```bash theme={"dark"} npm install -g @moda-ai/cli@latest && moda skills install moda-cli moda skills install --list moda skills install integration-node-vercel-ai-sdk ``` ### moda skills push Pushes local `.claude/skills/**/SKILL.md` files up to Moda. Files Moda manages (bundled guides installed with `moda skills install`, and the `moda-cli` skill) are skipped. `--dry-run` shows what would be pushed. `moda skills sync` and `moda sync skills` are legacy names for this command. A real sync also maintains a managed `` block in the repo's `AGENTS.md` that tells coding agents to propose and make fixes themselves from Moda's evidence (`moda investigate`, `moda problems`, `moda problems get --evidence`, `moda traces get`); only the fenced block is Moda-owned — the rest of the file is never touched, and `--dry-run` skips the write. If the markers are damaged (a begin marker without an end marker, an end without a begin, duplicated markers, or markers in reverse order), the file is left unchanged, `agentsMd.status` is `skipped`, and a warning explains how to repair the markers. ```bash theme={"dark"} moda skills push --dry-run ``` ## Harness The harness commands produce and sync the cited map of your agent codebase. The supported path for analysis is the Moda GitHub App (see [Harness](/harness/overview)); the CLI analyze path is experimental. ### moda harness analyze Produces a cited harness report. Gated: without `--experimental` or `MODA_HARNESS_ANALYZE_CLI=1` it prints a pointer to the GitHub App and exits 1. ```bash theme={"dark"} moda harness analyze --json ``` ```json Output (gated) theme={"dark"} { "schema": "harness_analyze_disabled.v0.1", "status": "disabled", "reason": "cli_analyze_gated", "message": "Harness analysis now runs automatically via the Moda GitHub App — connect your repo in the Moda dashboard (Settings → Integrations). To run the experimental CLI analyze anyway, pass --experimental or set MODA_HARNESS_ANALYZE_CLI=1." } ``` | Flag | Description | | - | - | | `--experimental` | Opt in to CLI analysis (or set `MODA_HARNESS_ANALYZE_CLI=1`). | | `--remote` | Upload a safe source snapshot and analyze server-side (no local coding agent needed). | | `--github-actions` | GitHub Actions OIDC mode — no Moda API key on the runner. | | `--analyst=claude\|codex\|cursor\|local-scan` | Local analyst adapter. | | `--yes` | Skip the read-plan approval prompt. | ### moda harness pull Fetches a server-side analyze run (status while running, the report when done). `--sync` also syncs a passing report. `--run-id` targets a specific run; otherwise the run recorded in `.moda/harness-remote-run.json` is used. ```bash theme={"dark"} moda harness pull --sync ``` ### moda harness validate-report / approve / sync `validate-report` checks `.moda/harness-report.json` citations. `approve --yes` validates and writes a hash-bound approval file; `sync --from-report` uploads the approved report to Moda Cloud (it refuses unapproved reports) and writes `.moda/sync-state.json`. `moda sync` and `moda sync harness` are top-level aliases for harness sync; `moda sync prompts` aliases `moda prompts sync`. ```bash theme={"dark"} moda harness approve --yes moda harness sync --from-report .moda/harness-report.json ``` ### moda harness scan / candidates / agents / explain Local, no-LLM inspection commands: * `moda harness scan` — discover local runtime agents and write `.moda/harness.json` (`--json` for structured output). * `moda harness candidates` — static candidate pre-pass with file:line citations (`--out=PATH`). * `moda harness agents` — list detected runtime agents and families. * `moda harness explain [--agent=]` — explain the discovered harness graph. ```bash theme={"dark"} moda harness explain --agent=agent_support ``` ### moda harness delete Permanently deletes a synced harness from Moda Cloud. ```bash theme={"dark"} moda harness delete my-harness-key --yes ``` # CLI overview Source: https://docs.moda.dev/cli/overview Install the Moda CLI, authenticate, provision API keys headlessly, and understand profiles, output formats, and exit codes. The Moda CLI (`@moda-ai/cli`, installed as `moda`) queries your production trace data from the terminal, manages prompt versions, and syncs your harness. This page covers installation, authentication, profiles, output formats, and exit codes. The full command list is in the [CLI reference](/cli/reference), and agent/CI integration patterns are in [Using the CLI from agents and CI](/cli/agents). ## Install Requires Node.js 18 or later. ```bash Global install theme={"dark"} npm install -g @moda-ai/cli moda --version ``` ```bash Without installing theme={"dark"} npx -y @moda-ai/cli overview ``` ## Authentication The CLI uses two credentials for two different groups of commands: | Credential | Used by | How you get it | | - | - | - | | CLI session | `auth *` commands and `provision` | `moda auth login` (browser flow) | | API key (`moda_sk_...`) | Data commands (`search`, `overview`, `emotions`, `problem`, `tail`, `ask`, ...), `prompts`, `skills`, `harness sync` | `moda init`, `moda provision`, or the dashboard at Settings → Ingestion keys | API keys (called ingestion keys in the dashboard) are tenant-bound: a key always operates on the tenant it was created for, and `MODA_TENANT_ID` cannot re-point it. ### Log in (browser flow) ```bash theme={"dark"} moda auth login ``` The command opens your browser to moda.dev, where you sign in; the CLI completes a PKCE exchange against a localhost callback (ports 8432–8435, first free port). If the browser cannot reach the CLI — for example when you run the CLI over SSH — paste the callback URL or the one-time code shown in the browser back into the terminal. The resulting CLI session lasts 30 days on a sliding window and renews in the background. Related commands: * `moda auth status` — reports session state; exits 4 when logged out. `--online` also probes the API. * `moda auth whoami` — shows the authenticated user and available tenants. * `moda auth token` — prints the raw session token (for scripting control-plane calls). * `moda auth api-key` — prints the saved `moda_sk_` API key for `$(moda auth api-key)` and pipes. * `moda auth logout` — revokes the session server-side and clears local credentials, including the stored API key. > [!WARNING] > > The session token authenticates control-plane commands only. Data commands require a `moda_sk_` API key: set `MODA_API_KEY`, or mint one with `moda init` or `moda provision`. `moda auth token` output is not valid for the Data API. ### API key resolution order Data commands resolve the API key in this order: 1. `MODA_API_KEY` environment variable 2. The active profile's stored key 3. `~/.moda/config.json` (`api_key`) ## Headless provisioning: `moda provision` `moda provision` mints (or reuses) a tenant API key without any interactive prompts and prints exactly one JSON document to stdout — nothing else. It is built for CI bootstrap scripts and agents: ```bash theme={"dark"} MODA_API_KEY=$(moda provision --tenant-id=1f7c9a2e-4b3d-4c8e-9a1b-2d3e4f5a6b7c | jq -r .apiKey) ``` ```json Output theme={"dark"} { "apiKey": "moda_sk_...", "tenantId": "1f7c9a2e-4b3d-4c8e-9a1b-2d3e4f5a6b7c", "tenantName": "Acme Support", "tenantSlug": "acme-support", "ingestUrl": "https://moda-ingest.modas.workers.dev", "baseUrl": "https://moda.dev", "reused": false } ``` The field names are a stable contract. `reused` is `true` when an existing stored key passed a liveness check and no new key was created. Behavior to script around: * Provision requires an existing CLI session (`moda auth login` run previously on that machine) and **never opens a browser**. Without a session it fails with **exit code 4** and instructions to log in first. * With access to multiple tenants, `--tenant-id` (or the `MODA_TENANT_ID` env var; the flag wins) is required. Without it, provision fails with **exit code 5** and a machine-readable `input_request` that lists every tenant with its resume flags — it never prompts, even on an interactive terminal. * `--label=TEXT` names the key (default: machine hostname). `--save` also persists the key and tenant to `~/.moda/config.json`; by default provision only prints, so headless callers own storage. > [!WARNING] > > Provision's stdout contains a live API key. Capture it into a secret store or variable; do not pipe it to logs. ## Profiles and configuration CLI state lives in `~/.moda/`: `config.json` (API key, tenant ID, ingest URL), `profiles.json`, and per-profile secrets under `~/.moda/secrets/`. Three profiles exist by default: `prod` (`https://moda.dev`, the default), `staging`, and `local`. ```bash theme={"dark"} moda profiles list moda profiles use staging moda config show --profile=prod ``` Select a profile per invocation with `--profile=NAME` or the `MODA_PROFILE` env var. Two env vars override URLs directly: * `MODA_BASE_URL` — the moda.dev host used for the Data API and control-plane calls. * `MODA_INGEST_URL` — the Ingestion API host. A loopback `MODA_BASE_URL` (`localhost`, `127.0.0.1`, `::1`) is used only on a non-prod profile (`local`, `staging`, `dev`). On a prod profile the command fails with exit code 5 (`input_required`) before sending anything: the CLI never sends a prod profile's key to a loopback server, and it does not send the request to production in its place. Re-run with `--profile=local` (or `MODA_PROFILE=local`) to use the local stack, or unset `MODA_BASE_URL` to use production. `moda config show` reports such a URL as `refused`, and `moda auth status --online` reports `online.baseUrl`, the URL every request uses. ## Output formats The CLI picks an output mode automatically, in this priority order: 1. **Explicit flags**: `--human` (or `--prose`), `--json`, `--agent`, `--agent --stream` 2. **`MODA_FORMAT`** env var: `human` | `json` | `agent` | `agent-stream` | `ndjson` 3. **Agent environment detection**: a truthy `CLAUDECODE`, `CURSOR`, `CI`, or `MODA_AGENT` env var selects `agent` 4. **TTY detection**: piped or redirected stdout selects `agent`; an interactive terminal selects `human` The modes: | Mode | Output | | - | - | | `human` | Readable output for a terminal (data commands print pretty JSON; `overview`, `ask`, `doctor`, and others render prose) | | `json` | The raw payload as JSON: one compact line when piped, indented on a terminal or with `--pretty`; errors print a structured error envelope | | `agent` | One `moda.agent.v1` JSON envelope per invocation | | `agent-stream` | NDJSON `moda.agent_event.v1` events (`--agent --stream`) | This means a piped or CI invocation gets machine-parseable output with zero flags. These commands bypass envelopes in every mode because their stdout is meant to be captured directly: `moda provision` (one JSON credentials document), `moda auth token` / `moda auth api-key` (the bare credential), and `moda tail` (NDJSON — one JSON line per event, since a live tail is a stream rather than a single response). ### The `moda.agent.v1` envelope In `agent` mode every command emits a single JSON envelope: ```json theme={"dark"} { "schema_version": "moda.agent.v1", "command": "tool-failures", "status": "ok", "generated_at": "2026-08-16T09:14:02.318Z", "summary": { "text": "3 tools failed in the last 7 days.", "confidence": "high" }, "findings": [], "evidence_refs": [], "recommended_actions": [], "next_commands": [], "artifacts": [], "warnings": [], "errors": [], "data": { "summary": { "total": 41 }, "tools": [] }, "meta": { "run_id": "1c3f...", "tip": "If a result looks wrong or is missing data: moda feedback ..." } } ``` `status` is `ok`, `degraded`, or `error`; the command's payload is always under `data`. The full field reference, the streaming event schema, and exit-code recipes are on [Using the CLI from agents and CI](/cli/agents). `moda manifest --json` and `moda --json-schemas` describe the protocol machine-readably. ## Exit codes | Code | Meaning | | - | - | | `0` | Success. | | `1` | Error: command, input, unknown id (`not_found`), access denied, API, network, or unexpected failure. | | `3` | Degraded: an answer was produced from a local fallback instead of Moda Cloud (only `moda ask`). | | `4` | Authentication required: no API key, or the API rejected it (HTTP 401). Set `MODA_API_KEY` or run the login command in the error payload, then resume. | | `5` | Input required: a non-interactive caller must choose a value (for example `--tenant-id`, or `--profile=local` for a loopback `MODA_BASE_URL` on a prod profile) and re-invoke. | | `130` | Cancelled: interrupted (Ctrl+C) or the output consumer closed the pipe. | ## Update check and telemetry Both are on by default and both can be turned off: * **Update check.** At most once a day the CLI checks the npm registry for a newer `@moda-ai/cli` version and prints a notice to stderr on a terminal; agent envelopes carry it as `meta.update`. A failed check (offline, unreachable registry) also waits a day before the next try. In agent and JSON modes the check runs in a detached background process, so it never delays a command. Disable with `--no-update-check` (or `--no_update_check`) or `MODA_CLI_UPDATE_CHECK=0`. The check is automatically skipped in CI and when `DO_NOT_TRACK=1` is set. * **Usage telemetry.** The CLI reports command name, the *names* of flags the command accepts (never values or arguments; any other `--word` is only counted), exit status, and duration. It also reports `agent_host`, an environment-derived caller label (`claude-code`, `cursor`, `agent`, or `human`) independent of output mode, and `output_bytes`, the byte count written to stdout, including newlines and stream records. It never collects stdout content. Unrecognized agent environments are not identified by name. It is sent to the same base URL and with the same key the command uses, and not at all when `--profile` or `MODA_PROFILE` names a profile that does not exist. Events wait in a private local file (`~/.moda/telemetry/`, which never holds the API key) and are sent in batches by one background process once 20 have collected or the oldest is 30 seconds old (every run in CI). Disable with `--no-telemetry` (or `--no_telemetry`) for one run, or with `MODA_CLI_TELEMETRY=0` or `DO_NOT_TRACK=1`, which also delete events still waiting to be sent. * **Feedback tip.** Successful commands print a one-line `moda feedback` tip (stderr on a TTY, `meta.tip` in envelopes). Hide the stderr line with `MODA_CLI_TIPS=0`. ## Environment variables | Variable | Effect | | - | - | | `MODA_API_KEY` | API key for data commands (highest precedence). | | `MODA_TENANT_ID` | Tenant selection for `provision` and `init` (a flag wins over it). | | `MODA_PROFILE` | Active profile name. | | `MODA_BASE_URL` | Override the moda.dev host. A loopback URL needs a non-prod profile (`--profile=local`); on a prod profile the command exits 5. | | `MODA_INGEST_URL` | Override the Ingestion API host. | | `MODA_FORMAT` | Force an output mode: `human`, `json`, `agent`, `agent-stream`, `ndjson`. | | `MODA_AGENT` | Truthy value forces agent-environment detection. | | `MODA_AUTH_TIMEOUT_MS` | How long `moda auth login` waits for the browser (default 10 minutes, clamped 30 s – 30 min). | | `MODA_ASK_TIMEOUT_MS` | `moda ask` cloud timeout in milliseconds (default 250,000). | | `MODA_HEARTBEAT_MS` | Idle heartbeat interval in `agent-stream` mode (default 10,000). | | `MODA_AGENT_MAX_OUTPUT_BYTES` | Bound on agent envelope size (default 24,000 bytes, under the 30,000-character tool output limit of agent harnesses). Over it, redundant `content_blocks` are removed first, then whole list items are dropped (never cut text); `pagination` and `next_commands` say where the rest starts, and a `truncation` block points at the complete output file. | | `MODA_AGENT_OUTPUT_DIR` | Where over-budget agent output is written in full (default `/moda-agent-output-`, owner-only). | | `MODA_AGENT_OUTPUT_RETENTION_HOURS` | How long full-output files are kept (default 24). Each new file prunes older full-output files in that directory; other files are never touched. | | `MODA_CLI_TELEMETRY` | `0` (or `false`, `no`, `off`) disables usage telemetry. | | `MODA_CLI_UPDATE_CHECK` | `0` (or `false`, `no`, `off`) disables the daily update check. | | `MODA_CLI_TIPS` | `0` hides the feedback tip line. | | `DO_NOT_TRACK` | `1` (or any value except empty, `0`, `false`, `no`, `off`) disables telemetry and the update check. | ## Next steps * [CLI reference](/cli/reference) — every command with flags and example output. * [Using the CLI from agents and CI](/cli/agents) — envelopes, exit-code recipes, and CI examples. * [Data API overview](/data-api/overview) — the HTTP API behind the data commands. * [Connect the MCP server](/mcp/overview) — the core read commands as MCP tools for Claude Code, Cursor, and other MCP clients (some CLI commands are CLI-only; see [parity](/mcp/parity)). * [Authentication](/administration/authentication) — how API keys and sessions work across Moda. # CLI reference Source: https://docs.moda.dev/cli/reference Moda setup, data, and investigation commands with flags and example output. Reference for the documented `moda` CLI workflows. Install and authentication are covered in the [CLI overview](/cli/overview); this page lists each command by area. Conventions used below: * Flags accept `--flag=value` or `--flag value`. Boolean flags are `--flag`. * Data commands call the [Data API](/data-api/overview) (`https://moda.dev/api/v1/data`, `x-api-key` auth) and require an API key (`MODA_API_KEY`, profile, or `~/.moda/config.json`). Numeric ranges are validated before the request is sent. * Example outputs are shown as `--json` prints them (the raw payload, trimmed to representative fields). Piped and CI invocations get a `moda.agent.v1` envelope instead, with the same payload under `data` — see [Using the CLI from agents and CI](/cli/agents). * Requests time out after 30 seconds per attempt. Reads (GET) retry up to 3 times on 429/5xx and network errors. Writes never retry automatically, because a 5xx or dropped connection can arrive after the server already applied the write (exception: `ask` uses a 250-second timeout and retries at most once, on network errors only). * Commands follow `moda `: `traces list|search|get|state|spans`, `problems list|get|impact|feedback|reopen|linear|link`, `detections list|tools`, `review`, `reviews list`, `skills push`. The older names (`moda context`, `moda search`, `moda world-state`, `moda audit`, `moda problem`, `moda problem-feedback`, `moda emotions`, `moda frustrations`, `moda tool-failures`, `moda false-positive`, `moda skills sync`, ...) still work with the same flags and output, and print a deprecation notice (`meta.deprecated` in agent output); `moda --help` names the new form. * A trace is one full agent run, identified by its `conversation_id` (the trace ID). Data API paths and JSON fields keep the `conversation` / `conversation_id` names for backwards compatibility, and the legacy command and flag names noted below remain as aliases. ## Setup and diagnostics ### moda init Interactive project setup with browser login, tenant selection, API key provisioning, the moda-cli skill for your coding agents, and optional SDK integration through your coding agent. Init uploads nothing from your repository to Moda. Use `--yes` for non-interactive setup. ```bash theme={"dark"} moda init --yes --tenant-id=1f7c9a2e-4b3d-4c8e-9a1b-2d3e4f5a6b7c ``` | Flag | Description | | - | - | | `--yes` | Accept all defaults (non-interactive). | | `--tenant-id=ID` | Tenant to provision (required non-interactively with multiple tenants; `MODA_TENANT_ID` also honored). | | `--agent-skill` / `--no-agent-skill` | Install the moda-cli skill into detected coding agents (`.claude/skills/moda-cli`, `.cursor/rules`; the default), or skip it. | | `--sdk-integrate` / `--no-sdk-integrate` | Run your coding agent to install and wire the Moda SDK, or skip it. | | `--verification-id=ID` | Tag the SDK integration's test trace with this id instead of a generated one. The onboarding page passes its `onb_` id so its waiting room sees the trace. | | `--connect-code=CODE` | Sign in with the one-time `mcc_` code included in the command copied from the Moda onboarding page, instead of opening a browser. Codes last 10 minutes and work once; only a real member of the workspace can mint or redeem one. The code signs in even when the CLI already has a session (the new session replaces it, and init says whose it replaced), and init provisions the code's workspace unless `--tenant-id` names it. A rejected code falls back to the existing session or to browser sign-in. | | `--offline` | Skip the final online validation check. | ### moda provision Headless API key provisioning for CI and agents. Prints exactly one JSON credentials document to stdout; exits 4 without a stored session and 5 when a multi-tenant account omits `--tenant-id`. Flags: `--tenant-id`, `--label` (default: hostname), `--save`, `--profile`. Full behavior and output are documented in the [CLI overview](/cli/overview#headless-provisioning-moda-provision). ```bash theme={"dark"} moda provision --tenant-id=1f7c9a2e-4b3d-4c8e-9a1b-2d3e4f5a6b7c --label=ci-runner ``` ### moda status Concise local setup state (config, credentials, synced artifacts). ```bash theme={"dark"} moda status --json ``` ### moda doctor Diagnoses local setup and data flow: config, auth, prompt manifest, harness artifacts, and (unless `--offline`) an online connectivity check. Flags: `--json`, `--offline`, `--online`. ```bash theme={"dark"} moda doctor --json ``` ### moda manifest Machine-readable description of the CLI protocol: commands, global flags, env vars, exit codes, and stream events. `moda --json-schemas` prints the JSON Schemas for the agent output contract. ```bash theme={"dark"} moda manifest --json ``` ```json Output (trimmed) theme={"dark"} { "schema_version": "moda.manifest.v1", "cli_version": "1.26.0", "invocations": ["bunx @moda-ai/cli", "npx -y @moda-ai/cli", "moda"], "exit_codes": [ { "code": 0, "name": "ok", "meaning": "Command completed successfully." }, { "code": 4, "name": "auth_required", "meaning": "Run login_command, then resume." } ] } ``` ### moda profiles / moda config `moda profiles list|use |create |doctor [name]` manage local profiles (`prod`, `staging`, `local` by default). `moda config show [--profile=NAME]` prints the resolved configuration. ```bash theme={"dark"} moda profiles use staging moda config show ``` ## Sessions The CLI has two independent credentials, and the `auth` commands report both: | Credential | Obtained by | Used for | | - | - | - | | `moda_ct_` session token | `moda auth login` (browser PKCE) | Control plane: `provision`, `init`, `auth token` | | `moda_sk_` API key | `MODA_API_KEY`, `moda provision`, `moda init` | Every data command | An API key on its own is enough for all data commands. You only need a browser session to mint new keys or run the onboarding wizard. ### moda auth login Opens the browser PKCE login flow and stores a 30-day sliding CLI session. `--screen=signup` opens the signup screen instead. ```bash theme={"dark"} moda auth login ``` ```json Output theme={"dark"} { "status": "authenticated", "method": "browser", "profile": null } ``` **Non-interactive login.** `--api-key` authenticates with an API key and never opens a browser. The key is validated against the Data API before anything is written, then saved to `~/.moda/config.json`. Three ways to supply it, safest first: | Form | Key visible in argv? | | - | - | | `MODA_API_KEY` + `--api-key` or `--non-interactive` | No | | `--api-key-stdin` (piped) | No | | `--api-key=` | **Yes** — readable by local process monitors and recorded in shell history | ```bash theme={"dark"} MODA_API_KEY=moda_sk_... moda auth login --non-interactive printf %s "$KEY" | moda auth login --api-key-stdin moda auth login --api-key=moda_sk_... # warns: key is exposed in argv ``` ```json Output theme={"dark"} { "status": "authenticated", "method": "api_key", "profile": null, "apiKeyCredential": { "masked": "moda_sk_...p3RQ" }, "tenant_id": "43773cd2-7c6b-4087-887a-67f40266c765", "persisted": true } ``` A key the API rejects (401/403) and a key that cannot be validated (network failure) both fail without persisting anything. `--non-interactive` takes the same path but additionally guarantees no browser opens even when no key is found — it exits with the commands that would mint one. If `MODA_API_KEY` holds a **different** key than the one being saved, the environment still wins for every later command. Login reports this rather than a clean success: it warns on stderr, sets `"shadowed_by_env": true` and `"effective_credential": "env"`, and exits 3 (degraded). Unset `MODA_API_KEY` to use the saved credential. ### moda auth status Reports the state of both credentials without ever opening a browser. Exit code 0 = at least one usable credential, 4 = neither. `--online` adds 5-second probes and reports where requests go: `GET /api/v1/data/whoami` (served by the frontend proxy and the backend alike, so it also confirms a base URL pointed at the backend) and, when a browser session exists, `GET /api/cli/context` (frontend only). ```bash theme={"dark"} moda auth status --online --json ``` ```json Output theme={"dark"} { "loggedIn": true, "authenticated": true, "apiKeyCredential": { "present": true, "source": "env", "masked": "moda_sk_...p3RQ", "tenantId": "43773cd2-7c6b-4087-887a-67f40266c765" }, "profile": null, "expiresAt": "2026-09-15T09:14:02.000Z", "user": { "email": "dev@example.com" }, "online": { "baseUrl": "https://moda.dev", "reachable": true, "ok": true, "tenantCount": 1, "session": { "reachable": true, "status": 200, "ok": true }, "dataApi": { "reachable": true, "status": 200, "ok": true, "tenantId": "43773cd2-7c6b-4087-887a-67f40266c765", "tenantName": "Acme Support", "keyKind": "tenant", "scope": "full" } } } ``` `online.baseUrl` is the URL every request uses. `reachable` is true when either probe got an HTTP response; `ok` when every credential present was accepted. `dataApi` carries the key's tenant, kind and scope from `/whoami`; without a key it is an unauthenticated reachability check (a live Data API answers 401). `session` is present only with a browser session; a 404 there with a reachable `dataApi` means the base URL is the backend, and a warning says browser login needs the frontend URL. A 403 for an unknown or inaccessible tenant leaves the key counted and adds a warning naming the tenant fix. `loggedIn` covers the browser session only; `authenticated` is true when either credential is usable, and the exit code follows `authenticated`. `apiKeyCredential.source` is `env`, `profile`, or `config` — `env` tells you a `MODA_API_KEY` is shadowing anything stored on disk. The raw key is never emitted. Without `--online` this command does no network I/O, so `authenticated` reflects that a credential is **present**, not that it still works, and `apiKeyCredential.verified` is `null` (not checked). With `--online` the API key is probed too: a key the API rejects gets `verified: false`, stops counting toward `authenticated`, and exits 4. A key that cannot be reached stays `verified: false` but still counts, so a network blip never declares a good credential dead. Use `moda auth whoami` to verify a key on demand. ### moda auth token Prints the bare session token plus a newline to stdout in every output mode (built for `$(moda auth token)` composition). Exits 4 when logged out; with `--json` it prints `{"error":"not_authenticated"}` instead of prose. ```bash theme={"dark"} moda auth token ``` ### moda auth api-key Prints the saved `moda_sk_` API key (the one `moda init` stored, or `MODA_API_KEY` when set) plus a newline, in every output mode. Built for piping into one process or a secret store without echoing it. Exits 4 when no key is saved; with `--json` it prints `{"error":"no_api_key"}` instead of prose. ```bash theme={"dark"} MODA_API_KEY="$(moda auth api-key)" npm run dev moda auth api-key | wrangler secret put MODA_API_KEY ``` ### moda auth whoami Shows the authenticated user, session expiry, and available tenants. ```bash theme={"dark"} moda auth whoami ``` With no browser session but a usable API key, it reports the key credential instead of failing — this is the command to run to prove a non-interactive login worked. ```json Output theme={"dark"} { "profile": null, "credential": "api_key", "apiKeyCredential": { "source": "env", "masked": "moda_sk_...p3RQ", "verified": true }, "tenant_id": "43773cd2-7c6b-4087-887a-67f40266c765", "session": null, "context": null } ``` `verified: true` means the API accepted the key just now. If the API is unreachable the command exits 3 (degraded) with `verified: false` rather than claiming an identity it could not confirm. A rejected key is an error, not a logged-out state. ### moda auth logout Revokes the session server-side (best effort) and clears local credentials — including the stored API key. If `MODA_API_KEY` is set in the environment it still takes precedence afterwards; unset it to fully sign out. ```bash theme={"dark"} moda auth logout ``` ```json Output theme={"dark"} { "status": "logged_out", "profile": null, "api_key_cleared": true } ``` ## Production data These commands reject flags they don't take: a typo or an unsupported filter exits `1` with the valid flags and a "did you mean", instead of being silently ignored. A flag the chosen mode would not send, a value flag given no value (`--user-id` alone), a malformed number (`--limit=0x10`, `--limit=2.5`) and an extra argument after an id fail the same way. `--days-back` and `--days_back` are the same flag. `--dry-run` is refused on these reads before any request is sent, and an unknown `--profile`/`MODA_PROFILE` fails instead of falling back to another profile. `traces`, `search`, and `clusters` window with `--time-range`, and the signal commands (`emotions`, `frustrations`, `hallucinations`, `tool-failures`, and others) window with `--days-back`. The other spelling is rewritten when it names the same span (`--days-back=7` is `--time-range=7d`, `--time-range=30d` is `--days-back=30`); one with no exact match, or both at once, fails. ### moda overview Health briefing built from production data: data-flow status, local sync state (harness, prompts, skills), and the top finding. On a TTY it renders prose; `--raw` returns the raw Data API `/overview` payload instead. ```bash theme={"dark"} moda overview --days-back=30 --raw --json ``` ```json Output (trimmed) theme={"dark"} { "period": { "days": 30 }, "conversations": { "total": 1841, "trend_pct": 6.2 }, "frustrations": { "total_analyzed": 412, "frustrated": 9, "at_risk": 14, "rate_pct": 2.2 }, "tool_failures": { "total": 41, "conversations": 33, "tools": 3 }, "top_clusters": [], "recent_activity": [], "processing": { "detectors": [ { "family": "emotion", "enabled": false, "setting": "signals.frustration" }, { "family": "custom_signal", "enabled": true, "setting": "signals.custom_signals" }, { "family": "laziness", "enabled": true, "setting": null, "reason": "no_tenant_switch" } ] } } ``` `processing.detectors` (`detectors` in the briefing) says whether each detector runs for the tenant: `enabled: false` means it is switched off (`setting` names the switch, from Settings → Account → Signal processing), `null` means the state could not be read, and `setting: null` means the detector has no tenant switch. A detector that is off reports zero detections, which does not mean traces are clean, so the briefing warns about it. The emotion stage, frustration included, reads `signals.frustration`. | Flag | Default | Description | | - | - | - | | `--days-back` | 7 | Look-back window (1–90). | | `--raw` | off | Return the raw `/overview` payload instead of the briefing. Not combinable with the trend flags. | | `--compare` | off | Add `trends`: the dashboard KPIs for the window against the previous window of equal length (see below). | | `--series` | off | Add `trends.series`: `[bucket, value]` arrays per hour (windows up to 2 days) or per day. Implies `--compare`. | | `--since` | — | Trends window start (ISO date or datetime, UTC unless an offset is given). Not with `--days-back`. Implies `--compare`. | | `--until` | now | Trends window end, inclusive. Needs `--since`. | | `--agent-name` | — | Scope the trends `overview` section to one sub-agent (the Analytics agent selector). Names are in `trends.agent.options`. | | `--unit` | `conversation` | Denominator of `trends.rates`: `conversation`, `segment` or `turn`. | #### Did my change make it worse? ```bash theme={"dark"} moda overview --compare --since=2026-10-17T14:00:00Z moda overview --series --since=2026-10-17T14:00:00Z --agent-name=planner ``` `trends` comes from `GET /v1/data/trends`, which runs the dashboard's own loaders. Every one of them defines the previous window as the span of equal length just before the window, so `--since=` compares the time since the deploy with the same length of time before it. There is no separate `--compare-to` flag for that reason. Each figure is `{ current, previous, delta, delta_pct, spike? }`: `delta` is current minus previous (percentage points for a `_pct` rate) and `delta_pct` is the relative change. ```json Output (trends, trimmed) theme={"dark"} { "window": { "from": "2026-10-17T14:00:00.000Z", "to": "2026-10-18T14:00:00.000Z", "previous_from": "2026-10-16T14:00:00.000Z", "previous_to": "2026-10-17T14:00:00.000Z", "days": 1, "bucket": "hour" }, "agent": { "selected": "__all__", "label": "All agents", "options": [{ "agent": "planner", "label": "planner", "conversations": 812 }] }, "overview": { "conversations": { "current": 1104, "previous": 1180, "delta": -76, "delta_pct": -6.4 }, "negative_emotion_rate_pct": { "current": 31.2, "previous": 24.9, "delta": 6.3, "delta_pct": 25.3, "of": "analyzed traces", "n": { "current": [344, 1102], "previous": [292, 1173] } } }, "rates": { "unit": "conversation", "units": { "current": 1104, "previous": 1180, "delta": -76, "delta_pct": -6.4 }, "laziness_pct": { "current": 0.4, "previous": 0.2, "delta": 0.2, "delta_pct": 100, "flagged": 4 } }, "detectors": { "tool_failure": { "failures": { "current": 520, "previous": 310, "delta": 210, "delta_pct": 67.7, "spike": true } } }, "series": { "bucket": "hour", "negative_emotion_rate_pct": [["2026-10-17T14:00Z", 28.1], ["2026-10-17T15:00Z", 33.4]] } } ``` | Section | Dashboard source | | - | - | | `overview` | Analytics overview: traces, messages, negative emotion rate (per analyzed trace), failed tool calls (per call), hallucinations (a count). The only section `--agent-name` scopes. | | `problems` | Problems trend card: analysed traces, traces with a signal, signal rate. `--days-back` windows only. | | `rates` | Signals overview rate cards: each detector's share of units with a detection, per `--unit`. | | `detectors` | Detector tab KPI tiles for emotion, tool failures, laziness and hallucination. | Sections can disagree on a rate because each uses its own denominator; `rate_note` says which. With `--agent-name`, `problems`, `rates` and `detectors` are left out (their loaders have no sub-agent filter) and `trends.notes` says so. The `overview` section is the slowest read: a 30-day window on a large workspace can take about 40 seconds, and the CLI waits up to 90. A figure whose read failed is `null` with `unavailable: true`, never zero. ### moda clusters Browse the use-case cluster hierarchy from the latest completed cluster run. ```bash theme={"dark"} moda clusters --parent-id=node_12 ``` ```json Output (trimmed) theme={"dark"} { "cluster_run": { "id": "run_2031", "num_categories": 8, "num_clusters": 42, "num_segments": 1930, "completed_at": "2026-08-10T00:00:00Z" }, "breadcrumb": [{ "node_id": "node_12", "label": "Billing & refunds" }], "clusters": [ { "node_id": "node_44", "label": "Refund retries", "summary": "Users retry failed refunds", "keywords": ["refund", "retry"], "segment_count": 118, "has_children": false, "depth": 1 } ], "meta": { "total_clusters": 42, "total_segments": 1930 } } ``` | Flag | Default | Description | | - | - | - | | `--parent-id` | — | Drill into a category (omit for the root level). | | `--time-range` | `all` | `all`, `1h`, `24h`, `3d`, `7d`, `30d`, `90d`. | | `--cohort` | — | `builtin:` or a saved cohort id: only the clusters the cohort's users reach, with the cohort's `segment_count` (the dashboard Topics page's cohort counts). `meta.cohort_segments` sums the level; `total_clusters`/`total_segments` stay the whole run. Needs `--time-range` `all`, `3d`, `7d` or `30d`; also scopes `--search`. | Instead of walking the hierarchy, find a cluster by meaning with `--search`, or resolve a node deep link deterministically with `--node-id`: ```bash theme={"dark"} moda clusters --search="calendar scheduling conflicts" --limit=3 ``` ```json Output (trimmed) theme={"dark"} { "clusterRunId": "run_2031", "query": "calendar scheduling conflicts", "search_mode": "hybrid", "matches": [ { "node_id": "node_36", "parent_id": "node_3", "node_type": "cluster", "label": "Managing and rescheduling calendar appointments", "keywords": ["rescheduling", "calendar"], "segment_count": 24, "ancestor_path": [{ "nodeId": "node_3", "label": "Scheduling", "depth": 0 }], "similarity": 0.81 } ] } ``` | Flag | Default | Description | | - | - | - | | `--search` | — | Cluster search query (2–200 characters). Routes to task-cluster search instead of the hierarchy walk. | | `--node-id` | — | Resolve one node exactly (deep link); bypasses ranked search. | | `--mode` | `hybrid` | `fuzzy`, `semantic`, `hybrid` — cluster search mode. `search_mode` in the response is what actually ran. | | `--limit` | 30 | 1–50 (cluster search only). | ### moda cluster-traces List traces in one cluster node. Legacy alias: `moda cluster-conversations`. ```bash theme={"dark"} moda cluster-traces node_44 --limit=2 ``` ```json Output (trimmed) theme={"dark"} { "cluster": { "node_id": "node_44", "label": "Refund retries", "segment_count": 118 }, "conversations": [ { "conversation_id": "conv_5e1a9c2b7d3f4680", "summary": "User retries a failed refund three times", "message_count": 21 } ], "pagination": { "limit": 2, "offset": 0, "total": 118, "has_more": true } } ``` | Argument / flag | Default | Description | | - | - | - | | `` | required | Cluster node ID. | | `--limit` | 10 | 1–100. | | `--offset` | 0 | Pagination offset (≤ 10,000). | An unknown node ID returns `cluster: null` with an empty list, not an error. ### moda traces Search and filter traces by summary text, cluster, user, environment, world state, and outcome. Legacy alias: `moda conversations`. ```bash theme={"dark"} moda traces --world-state="refund,enterprise" --outcome=negative --limit=2 ``` ```json Output (trimmed) theme={"dark"} { "conversations": [ { "conversation_id": "conv_5e1a9c2b7d3f4680", "summary": "User retries a failed refund three times", "message_count": 21, "first_timestamp": "2026-08-14T18:02:10Z", "last_timestamp": "2026-08-14T18:41:55Z", "cluster_id": "node_44", "cluster_name": "Refund retries", "environment": "production" } ], "search_mode": "keyword", "pagination": { "limit": 2, "offset": 0, "total": 7, "has_more": true } } ``` | Flag | Default | Description | | - | - | - | | `--search` | — | Ranked trace search over tasks (stored summaries when task search is unavailable) and message bodies: hybrid when embeddings exist, else keyword. `total_kind` is `matches` for a keyword run and `candidate_pool` for a ranked run (results may not contain the words). | | `--cluster-id` | — | Filter by cluster node ID. | | `--user-id` | — | Filter to one user. | | `--time-range` | `all` | `all`, `1h`, `24h`, `3d`, `7d`, `30d`, `90d`. | | `--since` / `--until` | — | Absolute UTC bounds, ISO 8601 date or datetime, both inclusive (a date-only `--until` covers that day). Intersect `--time-range`; at most 366 days. | | `--environment` | `all` | `all`, `development`, `staging`, `production`. | | `--world-state` | — | Keyword match (case-insensitive substring) over each trace's world state: its task goals and summaries, and for a trace the task engine owns its facts and the user's profile; comma-separated terms are ANDed. Max 200 characters. | | `--outcome` | `any` | `negative` (a user frustration was detected in the trace) or `positive` (none was detected, including traces not yet analyzed). | | `--include-world-state` | off | Attach each result's world-state summary (`hasData`, fact counts per segment; one extra request per row). | | `--cohort` | — | `builtin:` or a saved cohort id: only traces of the cohort's current members, as the dashboard trace list scopes them. With `--search` the keyword path runs. | | `--limit` / `--offset` | 20 / 0 | Pagination (limit 1–100, offset ≤ 10,000). | Each row also carries the state the dashboard trace list shows, read through the same loader: `processing_status` (`pending` until the pipeline completes the trace, then `complete`), `error_message`, `indexed_at` (when the trace was indexed) and `membership_score` (use-case confidence for `cluster_id`, 0–1; null when the dashboard places the trace in another use case). A pending trace is not fully processed, so its detections may be incomplete and missing detections do not mean it is clean; the CLI warns when a page holds pending or errored traces. The fields are null for a trace not in the list index yet, and `"trace_state": "unavailable"` means the state could not be read. `moda traces get` returns the same values in `trace_state`. ### moda traces search Message-grain search across traces: keyword, semantic, or hybrid. ```bash theme={"dark"} moda traces search "refund failed" --mode=hybrid --time-range=7d --limit=1 ``` ```json Output theme={"dark"} { "query": "refund failed", "search_mode": "hybrid", "degrade_reason": "none", "results": [ { "conversation_id": "conv_5e1a9c2b7d3f4680", "message_index": 12, "role": "user", "timestamp": "2026-08-14T18:22:41Z", "snippet": "The refund failed again after I retried the payment.", "score": 0.0328, "cluster_id": "node_44", "cluster_name": "Refund retries", "conversation_summary": "User retries a failed refund three times" } ], "totals": { "matched_conversations": 18, "prior_window_matched_conversations": 25 }, "pagination": { "limit": 1, "returned": 1, "has_more": true } } ``` | Argument / flag | Default | Description | | - | - | - | | `""` | required | 1–500 characters. | | `--mode` | `hybrid` | `keyword`, `semantic`, or `hybrid`. | | `--user-id` | — | Filter to one user. | | `--time-range` | `all` | `all`, `1h`, `24h`, `3d`, `7d`, `30d`, `90d`. | | `--since` / `--until` | — | Absolute UTC bounds, ISO 8601 date or datetime, both inclusive (a date-only `--until` covers that day). Intersect `--time-range`; at most 366 days. | | `--limit` | 20 | 1–100. No offset — pagination is limit-only. | | `--include-tool-io` | off | Include tool input/output blocks in results. | `search_mode` in the response is the mode that actually ran: semantic and hybrid degrade to keyword when embeddings are unavailable (`degrade_reason: "semantic_unavailable"`, retry may fix) or no hit clears the relevance floor (`"below_relevance_floor"`, retry will not fix). Scores are not comparable across modes. Each result carries `conversation_id` + `message_index` — feed them to `moda traces get`. If message-level search returns nothing but whole traces match, the CLI returns those traces instead (the same search as `moda traces --search`). Each result then has `match_grain: "trace"` and no score or message index, and a `fallback` block (`source: "traces_search"`, `search_mode`, `total`, `total_kind`) plus a warning explain it. When `fallback.search_mode` is not `keyword`, the traces are relevance-ranked related traces that may not contain the exact words, and `total` is the candidate pool rather than a match count. `fallback.has_more` and a `moda traces --search ... --offset` next command cover paging. With `--mode=keyword` the trace-level search is not run, because it is relevance-ranked and could not be shown as literal matches: a warning says so and `next_commands` offers the `moda traces --search` command instead. If the fallback request fails, the response carries a warning rather than looking like a clean empty result. ### moda traces get Windowed context around one message in a trace. ```bash theme={"dark"} moda traces get conv_5e1a9c2b7d3f4680 --msg-index=12 --window=1 ``` ```json Output (trimmed) theme={"dark"} { "conversation_id": "conv_5e1a9c2b7d3f4680", "total_messages": 21, "summary": "User retries a failed refund three times", "context": { "center_index": 12, "from_index": 11, "to_index": 13, "messages": [ { "index": 12, "role": "user", "content": "The refund failed again after I retried the payment.", "tool_calls": [], "tool_results": [], "timestamp": "2026-08-14T18:22:41Z" } ] } } ``` | Argument / flag | Default | Description | | - | - | - | | `` | required | Trace ID to read (or `--conversation-id`). | | `--msg-index` | middle of the trace | Center message index. `null` or empty means no anchor (with a warning). | | `--window` | 2 | Turns of context per side (0–5). `0` returns only the anchor message plus `total_messages`; above 5 is clamped to 5 with a warning. | | `--metadata-only` | off | Returns only `summary` and `total_messages`, with `messages: []` and `metadata_only: true`. Can't be combined with `--window`. | | `--all` | off | Whole transcript in order; can't be combined with `--msg-index`, `--window` or `--metadata-only`. | | `--ids-from` | — | Batch: read targets one per line from `-` (stdin) or a file. | **Batch reads.** Pass up to 25 targets in one call, as several positionals or with `--ids-from`, instead of one `moda traces get` per trace. A target is `` or `@` (the anchor; ids may contain `:`); `--window`, `--metadata-only` and `--all` apply to every target. A line may also be JSON, `{"id": "...", "msg_index": N}`, which is the only spelling for an id ending in `@`. Targets are read 4 at a time. ```bash theme={"dark"} moda traces get telegram:8565459080@12 linq:c6f88988-aa@3 --window=1 printf '%s\n' conv_a@4 conv_b | moda traces get --ids-from=- ``` ```json Output (trimmed) theme={"dark"} { "results": [ { "target": "telegram:8565459080@12", "ok": true, "data": { "conversation_id": "telegram:8565459080", "total_messages": 40, "context": { "center_index": 12, "messages": [] } } }, { "target": "linq:c6f88988-aa@3", "ok": false, "error": { "code": "not_found", "message": "No trace found for id \"linq:c6f88988-aa\" in this tenant." } } ], "requested": 2, "returned": 2, "succeeded": 1, "failed": 1, "has_more": false, "remaining_targets": [] } ``` A failed target does not fail the call: the exit code is 1 only when every target failed. In `--agent` mode, if the combined envelope would go over the byte limit, the items that fit are returned, `has_more` is `true`, and `remaining_targets` plus a `next_commands` entry read the rest. One positional id keeps the single-trace output shown above. ### moda traces state A trace's [world state](/concepts/analysis#world-state) as it is now: its tasks (open and finished, each with a timeline; a subtask names its parent task), the facts recorded for it, and the user's durable profile. Tasks and facts come from the task engine for a trace it owns (`source: "task_engine"`), and from the task tracker otherwise. There is no history of state changes. ```bash theme={"dark"} moda traces state conv_5e1a9c2b7d3f4680 ``` ```json Output (trimmed) theme={"dark"} { "hasData": true, "userId": "user_1842", "userDurableProfile": { "slots": { "user.plan": { "value": "enterprise" } }, "updatedAt": "2026-08-14T18:30:02Z", "slotCount": 6 }, "conversationWarmstart": null, "segments": [ { "segmentIndex": 0, "startMsgIdx": 0, "endMsgIdx": 0, "slots": {}, "openThreads": [ { "id": "refund_retry", "status": "open", "summary": "Retry the failed refund", "timeline": [{ "text": "Refund failed", "msg_index": 9 }], "subgoals": [] } ], "slotCounts": { "durable": 0, "segmentLocal": 0, "total": 0 } } ], "summary": { "segmentCount": 1, "lastUpdatedAt": "2026-08-14T18:30:02Z" } } ``` `hasData: false` means no tasks or facts have been tracked for the trace (yet), or the trace does not exist; the CLI adds a warning, not an error. | Argument / flag | Default | Description | | - | - | - | | `` | required | Trace ID to read. | | `--summary-only` | off | Return `segmentSummaries` (fact counts and top facts per segment) instead of the segments. | **Retired flags.** World-state snapshots (`--snapshot`, with `--msg-index`, `--block-index`, `--segment-index`) and replay (`--replay`, with `--message-count`, `--format=frames|fold-inputs`) folded the world-state event log, which Moda no longer writes. The CLI rejects them with `retired_flag` (exit 1) and sends nothing; `errors[0].suggested_commands` names the replacements: `moda traces state ` for the current tasks and facts, and `moda traces get ` for the messages (`--msg-index=N` for a snapshot's turn, `--all` in place of a replay). `--event-limit` is still accepted and ignored, with a warning. ### moda traces spans Raw OpenTelemetry span read for one trace, looked up by its trace ID (`conversation_id`) or by an OTLP `trace_id`: hierarchy, orphans, duplicates. Useful for debugging ingestion. ```bash theme={"dark"} moda traces spans conv_5e1a9c2b7d3f4680 ``` ```json Output (trimmed) theme={"dark"} { "summary": { "total_spans": 18, "by_type": { "llm": 9, "tool": 8, "agent": 1 }, "trace_ids": ["4bf92f3577b34da6a3ce929d0e0e4736"], "orphan_count": 0, "duplicate_count": 0 }, "spans": [ { "span_id": "00f067aa0ba902b7", "parent_span_id": null, "trace_id": "4bf92f3577b34da6a3ce929d0e0e4736", "type": "llm" } ], "orphans": [], "duplicates": [] } ``` | Argument / flag | Default | Description | | - | - | - | | `` | required | ID to audit. | | `--kind` | `auto` | How to interpret the ID: `auto` (try it as an OTLP `trace_id`, then as a `conversation_id`), `trace`, `conversation`. | | `--include-raw` | off | Attach verbatim raw event bodies. | | `--limit` | 200 | Max spans (1–1,000). | | `--ids-from` | — | Batch: read ids one per line from `-` (stdin) or a file. | **Batch reads.** `moda traces spans ...` (or `--ids-from`) audits up to 25 ids in one call and returns the same `{ results: [{ target, ok, data | error }], ... }` shape as batch `moda traces get`. Ids are taken verbatim; `--cursor` cannot be combined with a batch, so follow each item's `next_commands` to page one trace. ### moda traces findings Everything Moda flagged on a trace in one read: emotion, laziness, hallucination, tool failure and custom signal detections, each anchored to its message (`msg_index`), plus the Problems the trace is evidence for. There is no time window, so a trace older than `--days-back` does not read clean the way `moda detections list --conversation-id` does. Backed by `GET /v1/data/conversations/:id/findings`, which reads each family through the loader the dashboard uses. ```bash theme={"dark"} moda traces findings conv_5e1a9c2b7d3f4680 moda traces findings conv_5e1a9c2b7d3f4680 conv_7a21 conv_9f03 # up to 25 ids (or --ids-from=-|) ``` ```json Output (agent, trimmed) theme={"dark"} { "conversation_id": "conv_5e1a9c2b7d3f4680", "window": "all", "summary": { "detections": 21, "by_family": { "emotion": 5, "laziness": 1, "hallucination": 0, "tool_failure": 15, "custom_signal": 0 }, "problems": 2 }, "families": { "emotion": { "state": "found", "count": 5, "enabled": true, "processed": true, "top": [{ "msg_index": 808, "family": "frustration", "polarity": "negative", "score": 0.95, "quote": "Why dont u write like me??" }], "more": 4 }, "hallucination": { "state": "none", "count": 0, "enabled": null, "processed": true, "verified_claims": 1, "top": [] }, "custom_signal": { "state": "not_run", "count": 0, "enabled": false, "processed": null, "top": [] } }, "problems": { "count": 2, "processed": true, "top": [{ "problem_id": "7c6172a2-e37a-55f5-bbd2-1e8d72baf78b", "title": "Drafts recycle published or recently delivered content", "attribution_count": 1, "lifecycle": "open", "in_book": true }] } } ``` Each family's `state` says what an empty result means: `found`; `none` (its detector ran on this trace and found nothing); `not_run` (the detector is off for the workspace, or has not processed this trace yet); `unknown` (nothing found, and the detector records nothing for a clean trace, as laziness does). Only `none` means clean. `enabled` is the workspace processing switch where one exists (`null` when there is none), and `processed` whether this trace has been through the detector (`null` when that is not recorded). `hallucination` lists contradicted claims and counts verified ones in `verified_claims`. A Problem's `in_book` says whether it is in the current Problems list; attributions older than the list's window are included. `next_commands` open each anchor with `moda traces get --msg-index= --window=2`. A missing trace is a `not_found` error (an item error in a batch). | Argument / flag | Default | Description | | - | - | - | | `` | required | One or more trace IDs (up to 25). | | `--limit` | 3 | Detections shown per family in agent and human output (1–50). Counts always cover every detection. | | `--ids-from` | — | Batch: read ids one per line from `-` (stdin) or a file. | `--json` prints the full response: up to 50 rows per family with all their fields, and `count` for the total. ### moda detections list, family frustration User frustration detections with evidence quotes. The CLI adds an `anchor` block per row (derived from `key_turns`/`user_quotes`) so agents can jump straight to `moda traces get`. `moda detections list --family=frustration` is the frustration family of [`moda detections list --family=emotion`](#moda-detections-list-family-emotion) in the legacy field names: it reads the same data as `moda detections list --family=emotion:frustration` and the dashboard's Signals page, so the numbers match. `total_analyzed` is `conversations_analyzed`, `frustrated_count` is `by_family.frustration`, and `at_risk_count` counts listed rows with `is_frustrated: false` and `risk_score` ≥ 0.5. Rows also carry the emotion fields (`detection_id`, `family`, `elicitor`, `detection_grade`, `downgrade_reason`), and the response says `"source": "emotion_detections"`. Earlier versions read a legacy table that held only part of the analyzed traces, so they could disagree with `emotions`. ```bash theme={"dark"} moda detections list --family=frustration --days-back=14 --limit=1 ``` ```json Output (trimmed) theme={"dark"} { "summary": { "total_analyzed": 412, "frustrated_count": 9, "at_risk_count": 14, "frustration_rate_pct": 2.2 }, "frustrations": [ { "conversation_id": "conv_5e1a9c2b7d3f4680", "is_frustrated": true, "frustration_score": 0.91, "risk_score": 0.88, "primary_cause": "Refund tool errored twice; the agent asked the user to retry.", "user_quotes": [{ "turn": 12, "quote": "This is the third time I am asking.", "signal": "exasperation" }], "key_turns": [12, 16], "message_count": 21, "detected_at": "2026-08-15T07:03:11Z", "anchor": { "kind": "frustration", "conversation_id": "conv_5e1a9c2b7d3f4680", "msg_index": 12, "signal": "exasperation", "quote_preview": "This is the third time I am asking.", "all_turns": [12, 16], "no_anchor": false } } ], "pagination": { "limit": 1, "offset": 0, "total": 9, "has_more": true } } ``` | Flag | Default | Description | | - | - | - | | `--days-back` | 7 | 1–90. | | `--limit` | 10 | 1–20. | | `--offset` | 0 | Pagination offset. | | `--user-id` | — | Scope every figure (summary, breakdown, list, total) to one end user. | | `--conversation-id` | — | Scope every figure to one trace. | | `--conversation-ids` | — | Scope every figure to several traces, comma-separated or a JSON array (up to 50). The server filters them in one request. Cannot be combined with `--conversation-id`. | | `--ids-from` | — | The `--conversation-ids` values one per line, from a file or `-` (stdin). | | `--include-window` | off | Attach a message window from the trace around each anchor. In agent output, rows leave out the embedded conversation window unless this is set; each row has `anchor` and `context_command` (`moda traces get --msg-index= --window=2`) instead. | | `--window` | 1 | Turns per side for `--include-window` (1–5). | | `--compare` | off | Add `summary.compare`: the family's dashboard KPI tiles and rate for this window against the previous window of equal length. Also on `--family=emotion`, `laziness`, `hallucination`, `tool_failure` and `moda detections tools`. Covers the whole family, so not with `--user-id` or `--conversation-id`. | ### moda detections list, family emotion Multi-family emotion detections: `frustration`, `sadness`, `confusion`, `anxiety`, `trust`, and `positive`. The summary always covers all families; `--family` filters the paginated detections list only. ```bash theme={"dark"} moda detections list --family=emotion:confusion --days-back=7 --limit=1 ``` ```json Output (trimmed) theme={"dark"} { "summary": { "conversations_analyzed": 11482, "by_family": { "frustration": 231, "sadness": 164, "confusion": 118, "anxiety": 51, "trust": 47, "positive": 1893 }, "negative_rate_pct": 4.6, "positive_rate_pct": 17.3, "repair_rate_pct": 23.2 }, "signal_breakdown": [{ "family": "confusion", "signal": "repeated_clarification", "count": 61 }], "detections": [ { "detection_id": "7404fcab-7141-4a04-9de9-e4b26659a755", "conversation_id": "conv_5e1a9c2b7d3f4680", "family": "confusion", "is_detected": true, "score": 0.84, "primary_cause": "Agent restated the plan three times without answering the pricing question.", "user_quotes": [{ "turn": 9, "quote": "I still don't understand what I'm being charged for.", "signal": "confusion" }], "key_turns": [9], "detected_at": "2026-08-15T11:02:44" } ], "pagination": { "limit": 1, "offset": 0, "total": 118, "detected": 97, "at_risk": 21, "has_more": true } } ``` `by_family` counts detected traces. The detections list also holds at-risk rows (`is_detected: false`, `risk_score` ≥ 0.5), so `pagination.total` is detected plus at-risk; `pagination.detected` and `pagination.at_risk` give the split. | Flag | Default | Description | | - | - | - | | `--family` | — | `frustration`, `disapproval`, `sadness`, `confusion`, `anxiety`, `trust`, `positive`. Filters detections only. | | `--user-id` | — | Scope every figure, summary included, to one end user. | | `--conversation-id` | — | Scope every figure to one trace. | | `--conversation-ids` | — | Scope every figure to several traces, comma-separated or a JSON array (up to 50). The server filters them in one request. Cannot be combined with `--conversation-id`. | | `--ids-from` | — | The `--conversation-ids` values one per line, from a file or `-` (stdin). | | `--days-back` | 7 | 1–90. Windows on analysis time, not `detected_at` (the anchor turn's timestamp, which can be much older on long-running traces). | | `--limit` | 10 | 1–20. | | `--offset` | 0 | 0–10,000. | | `--include-window` | off | Keep each detection's `conversation_context` in agent output (it is left out by default; rows carry `context_command`). `--json` always keeps it. | ### moda detections list, family hallucination Grounding detections: assistant claims that contradict or are verified against the trace's world state, with the rule that fired and the offending substring. ```bash theme={"dark"} moda detections list --family=hallucination --kind=contradicted --limit=1 ``` ```json Output (trimmed) theme={"dark"} { "summary": { "total_scored": 124, "contradicted_count": 29, "verified_count": 23, "ungrounded_count": 41, "ungrounded_rate": 0.331, "conversations_scored": 99, "rule_breakdown": [{ "source": "rule", "rule_id": "false_absence", "count": 17 }] }, "detections": [ { "conversation_id": "conv_5e1a9c2b7d3f4680", "message_index": 31, "kind": "contradicted", "label": "CONTRADICT", "confidence": 0.92, "rule_id": "false_absence", "violated_slot_key": "contact.email", "offending_substring": "I couldn't find a verified personal email for him.", "incident_id": null, "detected_at": "2026-08-15T09:41:07" } ], "pagination": { "limit": 1, "offset": 0, "total": 29 } } ``` Each hallucination names the Problems incident it comes from in `incident_id` (`null` for rows from before hallucinations came from validated incidents); `moda traces findings` shows it as `incident`. | Flag | Default | Description | | - | - | - | | `--kind` | — | `contradicted` or `verified`. Filters the detections list. | | `--conversation-id` | — | Scope to one trace (by trace ID). Note: this narrows the summary aggregates too, not just the list. | | `--conversation-ids` | — | Scope every figure to several traces, comma-separated or a JSON array (up to 50). The server filters them in one request. Cannot be combined with `--conversation-id`. | | `--ids-from` | — | The `--conversation-ids` values one per line, from a file or `-` (stdin). | | `--days-back` | 7 | 1–90. | | `--limit` | 10 | 1–20. | | `--offset` | 0 | 0–10,000. | The detections list contains only contradicted and verified rows; plain ungrounded rows appear in the summary counts but are not listed. `pagination` here has no `has_more` field — compute `offset + limit < total` client-side. ### moda detections list, per trace By default emotion and frustration rows are one per trace and family (`"counting": "per_detection"`), and hallucination rows one per scored message (`"counting": "per_message"`), so `pagination.total` is not the dashboard's trace count. `--group-by=trace` reads the dashboard Signals tab's own list (the same loader): one row per trace in `traces`, the dashboard's filters and sort, and `"counting": "per_trace"`, so the total matches the dashboard for the same window and filters. Each filter below implies `--group-by=trace`. Laziness rows are always one per trace. ```bash theme={"dark"} moda detections list --family=frustration --trajectory=building --sort=risk_score --limit=1 ``` ```json Output (trimmed) theme={"dark"} { "counting": "per_trace", "counting_note": "pagination.total counts traces with a matching detected family ...", "filters": { "family": "frustration", "trajectory": "building", "sort": "risk_score" }, "summary": { "conversations_analyzed": 2338, "negative_conversations": 212, "negative_rate_pct": 9.1 }, "traces": [ { "conversation_id": "conv_5e1a9c2b7d3f4680", "message_count": 21, "negative_detected": true, "families": [{ "family": "frustration", "score": 0.82, "trajectory": "building", "elicitor": "bot", "expressed_signals": ["exasperation"] }] } ], "pagination": { "limit": 1, "offset": 0, "total": 37, "has_more": true }, "processing": { "enabled": true, "setting": "signals.frustration" } } ``` | Flag | Families | Description | | - | - | - | | `--group-by` | emotion, frustration, hallucination, laziness | `trace` reads per trace. The defaults are `detection` (emotion, frustration) and `message` (hallucination). | | `--search` | all four | Substring of the trace ID (emotion and frustration also match the primary cause). | | `--status` | all four | Emotion: `all` (any detected family, default) or `detected` (a negative family). Hallucination: `contradicted` (default) or `all`. Laziness: `all` (default) or `strong`. | | `--elicitor` | emotion, frustration | `bot`, `external`, `self`, `ambiguous`. | | `--trajectory` | emotion, frustration | `none`, `building`, `peak`, `resolved`, `sustained`. | | `--signal` | emotion, frustration | Expressed signals, comma-separated (for example `sarcasm,anger`); a trace matches when any is expressed. | | `--rule` | hallucination | One `rule_id` from `summary.rule_breakdown`; it scopes the summary too. | | `--source` | hallucination | `rule`, `classifier`, `gpu`, `judge`, `human`. | | `--sort` | all four | Emotion: `score` (default), `risk_score`, `detected_at`, `message_count`. Hallucination: `contradicted_count` (default), `verified_count`, `last_detected_at`. Laziness: `detections_count` (default), `strong_count`, `last_detected_at`. | | `--order` | all four | `desc` (default) or `asc`. | | `--cohort` | all four | `builtin:` or a saved cohort id: only traces of the cohort's members, summary included. It implies `--group-by=trace` (laziness: list reads only, not with `--conversation-id`). The summary line names the cohort and the data carries `cohort`. | The per-trace list has no user scope and no single-trace read, so `--user-id`, `--conversation-id` and `--include-window` (and `--kind` for hallucinations) are rejected with it. Its `summary` covers the whole window and ignores the list filters, except hallucination `--rule`. ### moda detections tools Per-tool failure overview for the window. ```bash theme={"dark"} moda detections tools --days-back=7 ``` ```json Output (trimmed) theme={"dark"} { "summary": { "total": 41, "total_calls": 1876, "conversations": 33, "tools": 3, "failure_rate_pct": 2.2 }, "tools": [ { "tool_name": "lookupCustomer", "failure_count": 28, "total_count": 512, "failure_rate_pct": 5.5, "conversation_count": 22, "top_error": "TimeoutError: request to CRM timed out after 10000ms", "last_seen": "2026-08-15T22:41:09Z" } ] } ``` | Flag | Default | Description | | - | - | - | | `--days-back` | 7 | 1–90. | | `--cohort` | — | `builtin:` or a saved cohort id: the dashboard Tool Failures leaderboard for the cohort's traces (`source: "dashboard_tool_failures"`). It counts failures only, so there are no `total_calls` or failure rates under a cohort. | `moda detections list --family=custom_signal --signal-id=` also takes `--cohort`: only hits on traces of the cohort's members. ### moda detections tools, one tool Failure subtypes and concrete examples for one tool. Each example carries a CLI-added `anchor` (trace ID + message index). Example text (message bodies, tool results, error text) is returned whole. In `--agent` mode, if the envelope goes over its byte limit, whole trailing examples are dropped and `truncation.data.full_output_path` points at a file with every example. Each example's `context_command` (`moda traces get --msg-index=`) opens the surrounding trace. ```bash theme={"dark"} moda detections tools lookupCustomer --limit=1 ``` ```json Output (trimmed) theme={"dark"} { "tool_name": "lookupCustomer", "subtypes": [ { "subtype": "timeout.expired", "count": 21, "conversation_count": 17, "sample_error": "TimeoutError: request to CRM timed out after 10000ms", "last_seen": "2026-08-15T22:41:09Z" } ], "examples": [ { "conversation_id": "conv_5e1a9c2b7d3f4680", "error_message": "TimeoutError: request to CRM timed out after 10000ms", "error_subtype": "timeout.expired", "msg_index": 9, "detected_at": "2026-08-15T22:41:09Z", "anchor": { "kind": "tool_failure", "conversation_id": "conv_5e1a9c2b7d3f4680", "msg_index": 9, "tool_name": "lookupCustomer", "error_subtype": "timeout.expired", "no_anchor": false } } ], "pagination": { "limit": 1, "offset": 0, "total": 28, "has_more": true } } ``` | Argument / flag | Default | Description | | - | - | - | | `` | required | Tool to inspect. | | `--subtype` | — | Filter examples to one failure subtype, a value from the response's `subtypes` (e.g. `dependency.timeout`). An unknown subtype returns a warning listing valid ones. | | `--days-back` | 7 | 1–90. | | `--limit` | 5 | Examples per page, 1–20. | | `--offset` | 0 | Pagination offset. | | `--include-window` / `--window` | off / 1 | Attach message windows from the trace around each anchor. | Both forms suggest `moda tools get ` in `next_commands`: the tool's call count, success rate and schema. ### moda tools list Every tool called in the window, failing or not: the dashboard Tool catalog. `calls`, `failed_calls` and `success_rate_pct` count recorded tool receipts; `moda detections tools` counts classified failures, so the two can differ (`metric_note` says so in every response). ```bash theme={"dark"} moda tools list --sort=failure_rate --limit=2 ``` ```json Output (trimmed) theme={"dark"} { "window": { "days_back": 7 }, "filters": { "sort": "failure_rate" }, "summary": { "total_calls": 1876, "unique_tools": 14, "total_conversations": 402 }, "tools": [ { "tool_name": "lookupCustomer", "calls": 512, "failed_calls": 28, "success_rate_pct": 94.53, "failure_rate_pct": 5.47, "conversation_count": 210, "effect_direction": "read", "target_system": "crm", "last_seen": "2026-08-15T22:41:09" }, { "tool_name": "createTicket", "calls": 96, "failed_calls": 3, "success_rate_pct": 96.88, "failure_rate_pct": 3.13, "conversation_count": 80, "effect_direction": "write", "target_system": "zendesk", "last_seen": "2026-08-15T21:02:44" } ], "pagination": { "limit": 2, "offset": 0, "total": 14, "returned": 2, "has_more": true, "next_offset": 2 } } ``` When `has_more` is true, `next_commands` holds the next page (`moda tools list --sort=failure_rate --limit=2 --offset=2`). | Flag | Default | Description | | - | - | - | | `--days-back` | 7 | 1–90. | | `--sort` | `calls` | `calls`, `failure_rate`, `failures` (failed calls), `traces`, `last_seen`; all descending, ties by tool name. | | `--search` | — | Only tools whose name contains this text. | | `--direction` | — | Only tools with this effect direction: `read`, `write`, `send`, `spawn`, `compute`, `unknown`. | | `--limit` | 25 | Tools per page, 1–200. | | `--offset` | 0 | Pagination offset, 0–10,000. | ### moda tools get One tool: call stats, its registered definition (description and schema, or `null`) and the payload fields seen in recorded calls, usage per day (per hour under 7 days), its top failure categories with the newest failure of each, and recent calls. A tool with no calls in the window is `not_found`. ```bash theme={"dark"} moda tools get lookupCustomer ``` ```json Output (trimmed) theme={"dark"} { "tool_name": "lookupCustomer", "window": { "days_back": 7, "bucket": "day" }, "stats": { "calls": 512, "failed_calls": 28, "success_rate_pct": 94.53, "failure_detections": 31, "conversation_count": 210, "user_count": 188, "first_seen": "2026-08-09T00:12:40", "last_seen": "2026-08-15T22:41:09" }, "definition": { "registered": { "description": "Look up a customer by email or id", "schema": { "type": "object", "properties": { "email": { "type": "string" } } }, "source": "MANUAL", "is_active": true, "updated_at": "2026-08-01T10:00:00.000Z" }, "payloads_sampled": 512, "invalid_payloads": 0, "observed_fields": [{ "name": "email", "inferred_type": "string", "call_count": 498, "call_pct": 97.3, "common_values": [{ "value": "a@example.com", "count": 4, "pct": 0.8 }], "common_values_total": 10 }] }, "usage": [{ "timestamp": "2026-08-15 00:00:00", "calls": 80, "failed_calls": 6 }], "failure_categories": { "total_failures": 31, "categories_total": 2, "categories": [ { "category": "timeout.expired", "label": "Request timed out", "count": 21, "conversation_count": 17, "latest_failure": { "conversation_id": "conv_5e1a9c2b7d3f4680", "msg_index": 9, "tool_use_id": "toolu_01", "detected_at": "2026-08-15T22:41:09" }, "context_command": "moda traces get conv_5e1a9c2b7d3f4680 --msg-index=9 --window=2", "examples_command": "moda detections tools lookupCustomer --subtype=timeout.expired --days-back=7" } ] } } ``` `next_commands` start with `moda detections tools ` (the failure rows). Agent output keeps 20 observed fields with three common values each and 5 recent calls, and cuts inputs and sample errors at 200 characters (`*_total` fields give the full counts); `--full` keeps everything. The registered schema is never cut. | Argument / flag | Default | Description | | - | - | - | | `` | required | Tool to read (from `moda tools list`). | | `--days-back` | 7 | 1–90. | | `--full` | off | Keep observed values, tool class inputs and recent call inputs whole. | ### moda problems list The Problems the dashboard shows, ranked. By default (`--view=auto`) the CLI asks the same question the dashboard's Problems page asks: when the tenant has a dream grouping published, the list is that grouping (each problem with its definition, fix, incidents, users and severity, in the dashboard table's order); otherwise it is the Book's ranked list (`problems` and `untrusted`). `view` in the output says which one you got. `--view=book` or `--view=dream` picks one. Both read the dashboard's own loaders, so counts, ranking and the date range match the dashboard. The CLI appends `dashboard_url`. ```bash theme={"dark"} moda problems list moda problems list --sort=users --limit=20 moda problems list --view=book --days-back=7 moda problems list --view=book --offset=10 --list-version=3f476d219fc9f4ec ``` ```json Output (Book, trimmed) theme={"dark"} { "view": "book", "summary": { "days_back": 30, "window_hours": 72, "open_problems": 4, "reopened": 1, "total_problems": 11, "signals_attributed": 132, "explained_coverage_pct": 78.6 }, "problems": [ { "problem_id": "3f2a9c1e-8b4d-4e6f-9a2b-1c3d5e7f9a0b", "display_name": "CRM lookups time out during peak hours", "cause_statement": "lookupCustomer calls exceed the 10s timeout under load, so refund flows stall.", "lifecycle": "open", "rank_score": 42.5, "pressing_rank": 1, "rank_basis": "v4_impact", "affected_users": 19, "affected_conversations": 44 } ], "untrusted": [], "pagination": { "offset": 0, "limit": 10, "returned": 1, "untrusted_returned": 0, "has_more": true, "next_offset": 10, "list_version": "3f476d219fc9f4ec" }, "dashboard_url": "https://moda.dev/dashboard/problems" } ``` ```json Output (dream view, trimmed) theme={"dark"} { "available": true, "view": "dream", "run": { "run_id": "7c1e...", "window_hours": 2160, "incidents": 4574, "users": 1716 }, "summary": { "problems": 447, "incidents": 4574, "pinned_problem_ids": [] }, "problems": [ { "problem_id": "baa8f1bb-56f6-5bb9-a16c-cca9ca957c2d", "name": "Posts scheduled or published without explicit confirmation", "category": { "family_id": "agent_prompt", "name": "Agent prompt, skills and briefs" }, "incidents": 44, "users": 38, "silent_share_pct": 62, "severity": { "tier": "P0", "rank": 310.7, "alert": true, "worst": "Unapproved post auto-published publicly." } } ], "worst_incidents": [], "pagination": { "offset": 0, "limit": 10, "returned": 10, "total": 447, "has_more": true, "next_offset": 10, "list_version": "5031dd43ed702b8a" } } ``` | Flag | Default | Description | | - | - | - | | `--view` | `auto` | `auto` (what the dashboard shows), `book` or `dream`. | | `--days-back` | Book 30; dream view: its run window | 1–90. On a dream-grouped tenant the Book's counts are recounted for the range; `summary.window_hours` is the rollup's own window. | | `--limit` | 10 | 1–200 per page (per partition on the Book). The default keeps one page inside the agent byte budget. | | `--offset` | 0 | Row to start at: `pagination.next_offset` of the previous page. | | `--list-version` | — | `list_version` of the first page, passed with every later `--offset`. If a later page reports another version, the list changed: restart from the first page. | | `--sort` | `rank` | `rank` or `users`; dream view: `severity` (its rank), `silent`; Book: `signals`, `problems`, `signal:`. | | `--dir` | `desc` | `desc` or `asc`. | | `--cohort` | — | `builtin:` or a saved cohort id: only the Problems the cohort's users hit, with its counts. | `next_commands` carries the command for the next page. Dream problem ids are Book problem ids, so `moda problems get ` and its `--evidence`/`--traces` pages work for ids from either view. ### moda problems get Open one Problem: the dossier, or a paged sub-resource view. In agent output the dossier is compact by default (`view: "compact"`): the header, the dossier summary, verification counts, the top 5 evidence rows with `conversation_id`, `msg_index` and a `context_command`, one line per investigation report, counts of what was left out under `omitted`, and next commands for `--evidence`, `--reports`, `--traces` and `--full`. `--full` (and `--json`) return the whole dossier, which includes the rubric, rank trend, sub-problems, verification results, evidence, affected traces, investigation reports, hierarchy, and representative stories. ```bash theme={"dark"} moda problems get 3f2a9c1e-8b4d-4e6f-9a2b-1c3d5e7f9a0b moda problems get 3f2a9c1e-8b4d-4e6f-9a2b-1c3d5e7f9a0b --evidence --limit=10 moda problems get 3f2a9c1e-8b4d-4e6f-9a2b-1c3d5e7f9a0b --reports moda problems get 3f2a9c1e-8b4d-4e6f-9a2b-1c3d5e7f9a0b --traces --family=tool_failure moda problems get 3f2a9c1e-8b4d-4e6f-9a2b-1c3d5e7f9a0b --feedback moda problems get 3f2a9c1e-8b4d-4e6f-9a2b-1c3d5e7f9a0b --view=dream --limit=3 --offset=3 moda problems get 3f2a9c1e-8b4d-4e6f-9a2b-1c3d5e7f9a0b --trend --days-back=14 ``` ```json Output (dossier, trimmed) theme={"dark"} { "found": true, "problem_id": "3f2a9c1e-8b4d-4e6f-9a2b-1c3d5e7f9a0b", "alias_resolved": false, "header": { "display_name": "CRM lookups time out during peak hours", "lifecycle": "open", "rank_score": 42.5 }, "trend": [{ "run_ts": "2026-08-15T00:00:00", "rank_score": 42.5, "total_attributions": 132 }], "verification": { "audit_pass_rate": 0.86, "judge_audit": { "passed": 12, "total": 14 } }, "evidence": [{ "attribution_id": "a4b73e58-48de-4fb2-9c58-1c3d5e7f9a0b", "conversation_id": "conv_5e1a9c2b7d3f4680", "causal_rationale": "Timeout fired before the CRM responded.", "door": "rubric_match" }], "investigation_reports": { "items": [], "has_more": false, "next_cursor": null }, "stories": [] } ``` | Argument / flag | Default | Description | | - | - | - | | `` | required | Problem ID (UUIDs from `moda problems`; merged-away IDs resolve to the surviving problem with `alias_resolved: true`). | | `--full` | off | The whole dossier in agent output (the default there is the compact view). Dossier only; not combinable with the view flags. | | `--evidence` | off | Paged attribution evidence (rationales, anchors, replay verification). | | `--reports` | off | Paged investigation reports (mechanism, narrative, citations). | | `--traces` | off | Paged affected traces with deep-link anchors. Legacy alias: `--conversations`. | | `--feedback` | off | The problem's feedback queue and pending count. | | `--limit` | 25 (evidence/traces), 20 (reports) | 1–50. | | `--cursor` | — | Keyset cursor from the previous page's `next_cursor`. Opaque — pass it back verbatim. | | `--family` | — | `--traces` filter: `tool_failure`, `emotion`, `laziness`, `hallucination`, `custom_signal`, `conversation_reader`. | | `--door` | — | `--traces` filter: `rubric_match`, `local_causal_chain`. | | `--trend` | off | Incidents and users per UTC day as `[date, value]` arrays, and incidents and signals for the last `--days-back` days (default 30) against the same number of days before (`compare`; `null` above 45 days because the history keeps 90). Reads `GET /v1/data/problems/:id/history`, the dashboard's problem history loader. Only `--days-back` combines with it. | | `--view` | — | `dream`: the problem as the dashboard's dream page shows it (definition, fix, severity, and its incidents with the validator's verdicts, most serious first). Pages incidents with `--limit` (default 3) and `--offset`; `--days-back` sets the range (default the dream run's window). A problem outside the dream view is a not-found error that names the dossier command. | At most one view flag per invocation. The dossier endpoint never returns 404 — an unknown or retired ID comes back `found: false` and the CLI adds a not-found warning. Sub-resource views require a canonical UUID (the CLI rejects other ids before the network). Cursors are not portable across different `--family`/`--door` filters. ### moda problems feedback Close the loop on a Problem from the terminal: mark it fixed, dismiss it, rename it, or flag a bad attribution. Writes to the same reconcile queue as the dashboard. ```bash theme={"dark"} moda problems feedback 3f2a9c1e-8b4d-4e6f-9a2b-1c3d5e7f9a0b --action=mark_fixed moda problems feedback 3f2a9c1e-8b4d-4e6f-9a2b-1c3d5e7f9a0b --action=dismiss --reason="not actionable" moda problems feedback 3f2a9c1e-8b4d-4e6f-9a2b-1c3d5e7f9a0b --action=rename --new-name="CRM lookup timeouts" ``` ```json Output theme={"dark"} { "success": true, "feedback_id": "5b0c2f1e-8d43-4a6a-9c1d-7e2f3a4b5c6d", "problem_id": "3f2a9c1e-8b4d-4e6f-9a2b-1c3d5e7f9a0b", "action": "mark_fixed", "status": "pending", "duplicate": false } ``` | Argument / flag | Default | Description | | - | - | - | | `` | required | Canonical problem UUID. | | `--action` | required | `mark_fixed`, `dismiss`, `flag_attribution`, `rename`. | | `--reason` | — | Required for `dismiss` and `flag_attribution` (≤ 2,000 characters). | | `--attribution-id` | — | Required UUID for `flag_attribution`; find IDs with `moda problems get --evidence`. | | `--new-name` | — | Required for `rename` (≤ 255 characters). | | `--actor` | `moda-cli` | Recorded actor label. | The write is idempotent while the previous identical submission is still pending (`duplicate: true`, no new row). The CLI enforces the conditional requirements locally, so a bad invocation fails before the network. ### moda problems linear Show the Linear issue linked to a Problem. Requires the Linear integration to be connected (Integrations → Linear). In human mode the CLI also prints a one-line summary on stderr (`ENG-7 · In Progress · https://linear.app/...`), or a hint to run `moda problems link` when nothing is linked. ```bash theme={"dark"} moda problems linear 3f2a9c1e-8b4d-4e6f-9a2b-1c3d5e7f9a0b ``` ```json Output theme={"dark"} { "problem_id": "3f2a9c1e-8b4d-4e6f-9a2b-1c3d5e7f9a0b", "link": { "subjectKind": "problem", "subjectId": "3f2a9c1e-8b4d-4e6f-9a2b-1c3d5e7f9a0b", "origin": "mcp", "issue": { "id": "9d1c2b3a-4e5f-4a6b-8c7d-0e1f2a3b4c5d", "identifier": "ENG-7", "url": "https://linear.app/acme/issue/ENG-7/crm-lookups-time-out", "teamId": "5a6b7c8d-9e0f-4a1b-8c2d-3e4f5a6b7c8d", "stateName": "In Progress", "stateType": "started" }, "createdAt": "2026-08-16T09:14:02.000Z", "lastSyncedAt": "2026-08-16T10:02:11.000Z" } } ``` | Argument / flag | Default | Description | | - | - | - | | `` | required | Canonical problem UUID. | `link` is `null` when no issue is linked. ### moda problems link File a Problem as a Linear issue in your team's tracker, or link an existing issue with `--issue`. Requires the Linear integration to be connected (Integrations → Linear). ```bash theme={"dark"} moda problems link 3f2a9c1e-8b4d-4e6f-9a2b-1c3d5e7f9a0b --priority=2 moda problems link 3f2a9c1e-8b4d-4e6f-9a2b-1c3d5e7f9a0b --issue=ENG-123 ``` ```json Output theme={"dark"} { "problem_id": "3f2a9c1e-8b4d-4e6f-9a2b-1c3d5e7f9a0b", "created": true, "link": { "subjectKind": "problem", "origin": "mcp", "issue": { "identifier": "ENG-7", "url": "https://linear.app/acme/issue/ENG-7/crm-lookups-time-out", "stateName": "Todo", "stateType": "unstarted" } } } ``` | Argument / flag | Default | Description | | - | - | - | | `` | required | Canonical problem UUID. | | `--issue` | — | Link this existing issue (`ENG-123` or its `linear.app` URL) instead of filing a new one. Cannot be combined with `--team-id`, `--title`, or `--priority`. | | `--team-id` | integration default | Linear team to file into. Without it, the integration's default team is used; if none is set the command fails with a `--team-id` hint. | | `--title` | the Problem's name | Issue title (trimmed, truncated to 255 characters). | | `--priority` | — | 0–4: 0 none, 1 urgent, 2 high, 3 medium, 4 low. | Filing is idempotent per Problem: an already-linked Problem returns its existing link with `created: false`. Linking fails if the Problem is already linked to a different issue. ### moda feedback Flag wrong or missing data (or CLI quirks) to the Moda team. The note is required; IDs attach context. ```bash theme={"dark"} moda feedback "cluster label looks wrong" --category=bad_cluster_label --cluster-id=node_44 ``` ```json Output theme={"dark"} { "submitted": true, "category": "bad_cluster_label", "severity": "low", "feedback_id": "5b0c2f1e-8d43-4a6a-9c1d-7e2f3a4b5c6d", "submitted_at": "2026-08-16T09:14:02Z" } ``` | Argument / flag | Default | Description | | - | - | - | | `""` | required | Up to 4,000 characters. | | `--note` | — | The note, if not given as the argument. | | `--category` | `other` | `bad_cluster_label`, `mismatched_frustration`, `missing_data`, `noisy_data`, `wrong_tool_failure`, `incorrect_loop`, `api_quirk`, `false_positive_attribution`, `misrouted_fix`, `harness_bug`, `other`. An unknown value is sent as `other` with `refs.raw_category`, and a warning lists the valid ones. | | `--severity` | `low` | `info`, `low`, `medium`, `high`. | | `--conversation-id`, `--cluster-id`, `--tool-name`, `--run-id` | — | Attach references (`--conversation-id` takes a trace ID). | | `---id` | — | Any other id (`--problem-id`, `--fix-id`, `--attribution-id`, `--trace-id`, `--span-id`, `--message-index`) is attached to `refs`. | ### moda tail Live-tail production activity: poll the Data API and emit one JSON line per newly seen item (NDJSON on stdout in every output mode — a tail is a stream, so the single-envelope agent contract does not apply). `Ctrl-C` stops it. ```bash theme={"dark"} moda tail # new traces, every 15s moda tail --signal=all --interval=30 # traces + emotion detections moda tail --once --max-events=10 # one poll (baseline page), bounded ``` ```json Output (one line per item) theme={"dark"} {"type":"conversation","conversation_id":"conv_5e1a9c2b7d3f4680","timestamp":"2026-08-16T08:19:11","message_count":21,"environment":"production","cluster_name":"Refund retries","summary":"User retries a failed refund"} {"type":"emotion","detection_id":"7404fcab-7141-4a04-9de9-e4b26659a755","conversation_id":"conv_5e1a9c2b7d3f4680","family":"frustration","primary_cause":"Refund tool errored twice.","detected_at":"2026-08-15T11:02:44"} {"type":"tail_coverage","signal":"emotions","complete":false,"scanned":500,"total":3823,"coverage_pct":13.1,"pages_scanned":25,"detail":"..."} ``` | Flag | Default | Description | | - | - | - | | `--signal` | `traces` | `traces`, `emotions`, `all`. Legacy alias: `--signal=conversations` (same as `traces`). | | `--interval` | 15 | Seconds between polls (5–3,600). | | `--once` | off | One poll, then exit. | | `--limit` | 20 | Traces page size per poll (1–50). | | `--max-events` | — | Stop after N emitted stdout records, metadata included (enforced per record, so a large page never overshoots). | | `--full-scan` | off | Emotions: scan the whole one-day window instead of the top-scoring prefix (many more requests, bounded by the API's offset ceiling of 10,000). | Dedupe is in-memory per process: traces re-emit when they advance (`message_count` changes — long-running, single-trace-per-user tenants update in place); emotion detections emit once per `detection_id`. Trace records keep `"type":"conversation"` on the wire. **Emotions coverage.** The emotions endpoint is ranked by score with no time ordering or cursor, so a tail cannot ask for "detections since X" — by default it follows the highest-scoring detections and emits a `tail_coverage` record per poll stating exactly what it scanned (`scanned`, `total`, `coverage_pct`, `complete`). On high-volume tenants the default poll covers a fraction of the day; use `--full-scan` when completeness matters more than request count. `--max-events` bounds every record on stdout, metadata included. When it is set, one slot is reserved for the coverage record so a capped tail still reports what it saw; at `--max-events=1` the data row keeps the slot and the coverage record is written to stderr instead, where it cannot affect a consumer's record count. ### moda cohorts User cohorts, as the dashboard Users page defines them: six built-ins (`builtin:power_users`, `builtin:heavy_tool_users`, `builtin:frustrated`, `builtin:at_risk`, `builtin:new_this_week`, `builtin:silent_sufferers`) and the tenant's saved cohorts (a UUID). Each one's `ref` scopes a list with `--cohort=`: `problems list`, `traces list`, `detections list`, `detections tools` and `clusters`. A scoped list refreshes the cohort's membership snapshot first, as the dashboard does, and its summary names the cohort. ```bash theme={"dark"} moda cohorts list moda cohorts compare builtin:new_this_week builtin:power_users --days=30 moda problems list --sort=users --cohort=builtin:new_this_week ``` | Command | Description | | - | - | | `moda cohorts list [--include-archived]` | Built-ins first, then saved cohorts: `ref`, `name`, `definition`, `revision`. | | `moda cohorts get ` | One cohort. | | `moda cohorts fields` | The fields and operators a definition can use. | | `moda cohorts preview --file=` | Member count and a sample of user ids for an unsaved definition (`--definition=` inline). Writes nothing. | | `moda cohorts compare [--days=7\|30\|90]` | Two cohorts side by side: size, health bands, tokens, top topic categories and failure mix. | | `moda cohorts create --name=NAME --file=` | Write. Saves a cohort (`--description`, `--pinned`, `--color=neutral\|blue\|green\|amber\|red\|violet`). Takes `--dry-run`. | | `moda cohorts update ` | Write. Edits a saved cohort (same flags, plus `--note`). Built-in cohorts cannot be edited. Takes `--dry-run`. | A definition is `{"version":1,"window":"24h|7d|30d|90d","where":{...}}`, for example `{"version":1,"window":"30d","where":{"field":"tool_failure_count","op":"gte","value":3}}`. A `--file` may hold the definition alone or a body with a `definition` key. ## Production intelligence ### moda investigate Aggregates overview, tool failures, frustrations and the top 3 Problems into ranked findings with evidence references and next commands. `--tool=NAME` scopes to one tool; `--trace=ID` (legacy alias `--conversation=ID`) scopes only the frustration evidence to one trace. The Problems are the first rows of the list `moda problems list` shows (its default `--view=auto`): the dream grouping when the tenant's dashboard shows one, in the dashboard table's order, otherwise the Book's ranked list. `data.problemsView` says which list was used (`view`: `dream` or `book`), the window its counts cover, and the `moda problems list` command that lists the same Problems in the same order. Without `--days-back`, dream counts cover the dream run's window, the dashboard's default range; the Book uses the investigation window. Problem ids from either view work with `moda problems get `. If every source fails, the command fails with that error (a rejected key is `auth_required`, exit 4). If some fail, the result is `degraded` (exit 3), `data.failedSources` names them, and the summary starts with `Incomplete:`; it never reports "no strong production issue" from reads that failed. ```bash theme={"dark"} moda investigate --days-back=7 --tool=lookupCustomer ``` ```json Output (trimmed) theme={"dark"} { "schemaVersion": "production_investigation.v0.1", "daysBack": 7, "summary": { "text": "Top production finding: lookupCustomer is failing in production. lookupCustomer produced 28 failed call(s) in the last 7 day(s).", "confidence": "high" }, "findings": [ { "id": "finding_tool_failure_lookupCustomer", "kind": "tool_failure", "title": "lookupCustomer is failing in production", "severity": "critical", "confidence": "high", "impactScore": 115 } ], "nextCommands": ["moda detections tools lookupCustomer --days-back=7 --include-window", "moda problems list --view=dream --days-back=7"], "sourceStatus": { "overview": "ok", "tools": "ok", "frustrations": "ok", "problems": "ok" }, "problemsView": { "view": "dream", "window": "the last 7 day(s)", "command": "moda problems list --view=dream --days-back=7" } } ``` ### moda failures Same investigation, restricted to failure findings (frustration findings excluded). Flags: `--days-back`, `--tool`. ```bash theme={"dark"} moda failures --tool=lookupCustomer ``` ### moda ask Ask Moda a production question in natural language. On a TTY the answer streams live; add `--no-stream` for a buffered request. If the stream can't start, the CLI switches to the buffered request. If it drops after the run started, the CLI fails instead of asking again (a second run would cost a second analysis). The first run may still finish; retry with `--no-stream`. The cloud request times out after `MODA_ASK_TIMEOUT_MS` (default 250 s); if Moda Cloud is unavailable the CLI synthesizes an answer from local Data API evidence and **exits 3** with `source: "local_fallback"` and `degraded: true`. ```bash theme={"dark"} moda ask "what should I fix first?" --json ``` ```json Output (trimmed) theme={"dark"} { "schema_version": "moda.intelligence.v1", "source": "cloud", "degraded": false, "summary": { "text": "Fix lookupCustomer timeouts first.", "confidence": "high" }, "answer_markdown": "The strongest production signal this week is lookupCustomer timing out in 5.5% of calls, affecting 22 traces...", "answer_claims": [] } ``` | Argument / flag | Default | Description | | - | - | - | | `""` | required | The question. | | `--days-back` | 7 | Evidence window (1–90). | | `--no-stream` | off | Disable live streaming on a TTY. | ## Agent-native commands `moda agent context`, `moda agent next-action`, and `moda agent evidence ` emit local Moda context and readiness diagnostics, prioritized next commands, and expanded evidence for coding agents. For the ranked production investigation use `moda investigate`. They default to agent JSON output in every environment. See [Using the CLI from agents and CI](/cli/agents). ```bash theme={"dark"} moda agent next-action ``` ## Managing Moda from the CLI These commands do what the dashboard does. Each needs only an API key, and the tenant comes from the key. Writes take `--dry-run`: it validates the call, returns the exact request in `data.planned` (method, endpoint, body) and sends nothing, and its `next_commands` entry is the command that sends it (`requires_approval: true`). That includes `problems feedback`, `problems reopen`, `problems link`, `review`, `feedback`, `cohorts create|update` and the `signals` writes; `prompts promote` refuses `--dry-run` before any request. | Task | Command | | - | - | | Sort or page traces | `moda traces --sort=recent\|longest\|slowest --offset=N` | | Read a whole trace in order | `moda traces get --all` | | End users and one user's profile | `moda users [--window=30d --cohort=frustrated --sort=health_score --order=asc]`, `moda user ` (`--cohort` takes `builtin:`, a saved cohort id or a built-in key) | | User cohorts | `moda cohorts list [--include-archived]`, `get `, `fields`, `preview --file=`, `compare [--days=7\|30\|90]` | | Save or edit a cohort | `moda cohorts create --name=NAME --file= [--description --pinned --color] [--dry-run]`, `moda cohorts update [--name --file --note …] [--dry-run]` (archiving is dashboard-only) | | Reopen a problem marked fixed | `moda problems reopen [--reason=TEXT]` (resolved problems return only via re-detection) | | Draft and create a custom signal | `moda signals draft --note="…"`, `moda signals create --name --description --pass-criteria --fail-criteria [--polarity --locus --tool-names=a,b --file=body.json]` | | Edit a custom signal and change its status | `moda signals update …`, `moda signals activate\|pause\|delete ` (delete: drafts only) | | Review and tune a custom signal | `moda signals examples add\|update\|remove --conversation-id=…`, `refine`, `revise`, `proposals`, `accept`, `reject` | | Find matches for a custom signal | `moda signals search `, `search-status`, `search-stop`, `preview --file=detector.json` | | Prompt registry | `moda prompts list\|show\|proposals\|usage\|decide` | | Skills | `moda skills list\|show ` | | Synced harnesses | `moda harness list\|show\|versions\|diff` | API keys can't do these on purpose: manage members, invites and roles; mint API keys; manage billing, provider credentials or OAuth connections; create alert rules that message people; or archive an active custom signal. LLM-backed signal actions (draft, refine, revise, search, adding or updating a labeled example, and similar) are limited to 10 per minute per key. ## Next steps * [Using the CLI from agents and CI](/cli/agents) — envelope schema, exit-code recipes, CI examples. * [Data API overview](/data-api/overview) — the same data over HTTP. ## Problem impact by use case The `affected-use-cases` mode returns affected-trace counts by use case for a problem. The `trace-use-cases` mode resolves current use-case links for up to 25 trace IDs from problem-attributed segments across their history; it does not apply the `--days-back` window. Both derive results at read time. `moda problems impact` uses the same live, segment-scoped calculation as the dashboard. It returns counts, full analyzed-population denominators, the resolved classification run, time boundaries, and a dashboard link. It stores no counters. ```bash theme={"dark"} moda problems impact --mode=catalog moda problems impact --node-id=node_0 --days-back=7 moda problems impact --node-id=node_0 --days-back=all moda problems impact --problem-id= --days-back=30 moda problems impact --node-id=node_0 --problem-id= --mode=evidence moda problems impact --node-id=node_0 --mode=trend --days-back=30 moda problems impact --mode=overview --days-back=7 moda problems impact --problem-id= --mode=affected-use-cases moda problems impact --problem-id= --mode=trace-use-cases --conversation-ids='["trace_id"]' ``` `--days-back` accepts 1, 3, 7, 30, 90, or `all`. To continue evidence, pass the returned `nextCursor` as `--cursor`, `runId` as `--run-id`, and `window.to` as `--to`, retaining the same node, problem, and days. A classification change fails explicitly; fetch a fresh catalog instead of interpreting an old node ID in a new run. Use `--json` for plain JSON or `--agent` for the standard agent envelope. # Analysis Source: https://docs.moda.dev/concepts/analysis What Moda computes from ingested traces and where each result appears in the dashboard and Data API. After messages are ingested, Moda runs a set of analyses over each trace — the whole agent run, end to end, not any single API call — and across your whole workspace. This page describes each analysis at the product level: what it produces and where to find it. For the underlying objects, see the [data model](/concepts/data-model). ## Where each result appears | Result | Dashboard | Data API | | - | - | - | | Traces, messages, tool calls | [Traces](/dashboard/traces), [Tool Catalog](/dashboard/users-and-tools) | [`GET /conversations`](/data-api/traces) | | Trace summaries | [Trace detail](/dashboard/traces) | [`GET /overview`](/data-api/analytics) (recent activity) | | World state (tasks and facts) | [Trace detail → World State](/dashboard/traces) | [`GET /conversations/:id/world-state`](/data-api/traces) | | Emotion signals | [Signals → User Emotion](/dashboard/signals) | [`GET /emotions`](/data-api/signals) | | Tool-failure classification | [Signals → Tool Failures](/dashboard/signals) | [`GET /tool-failures`](/data-api/signals) | | Laziness signals | Alerts (built-in Laziness signal) | [`GET /trends`](/data-api/analytics) (rates and KPI tiles) | | Hallucination detection | [Problems](/dashboard/problems) | [`GET /hallucinations`](/data-api/signals) | | Problems | [Problems](/dashboard/problems) | [`GET /problems`](/data-api/problems) | | Use cases | [Clusters](/dashboard/use-cases) | [`GET /clusters`](/data-api/analytics) | ## Trace summaries Each trace with at least two messages gets a one-paragraph summary. Summaries are regenerated as the trace grows, feed the semantic search index, and appear on the trace detail page and in the recent-activity section of [`GET /overview`](/data-api/analytics). ## Use-case clusters Moda splits each trace into segments — contiguous stretches of one user goal — and groups segments into a hierarchical taxonomy of use cases: broad user areas at the top, specific user goals underneath, each with a label, description, keywords, and trace counts. * The first taxonomy for a workspace is built once 50 or more analyzed segments exist; before that, the Clusters page shows an empty state. * New segments are assigned to the existing taxonomy as they are analyzed, so cluster volumes stay current. * The hierarchy itself is rebuilt automatically as your traffic evolves — you never configure or trigger it. Segments that match no existing use case are held aside and grouped into new nodes at the next rebuild, so a genuinely new use case becomes visible once that rebuild has run. Use cases appear at [Observe → Clusters](/dashboard/use-cases), in the "What the agent handles" section of the [Home page](/dashboard/overview), and through [`GET /clusters`](/data-api/analytics), `GET /clusters/:nodeId/conversations`, and [`GET /task-clusters/search`](/data-api/analytics), which resolves a phrase like "refund requests" to a cluster `node_id` by name or meaning (CLI: `moda clusters --search`). ## Emotion signals Moda analyzes user messages for expressed emotion using a fixed taxonomy of 7 families and 17 signals: | Family | Signals | | - | - | | frustration | `exasperation`, `anger`, `profanity`, `insult`, `sarcasm`, `escalation_request` | | sadness | `disappointment`, `resignation`, `self_blame`, `personal_distress` | | confusion | `confusion` | | anxiety | `urgency` | | trust | `distrust` | | disapproval (shown as Redirection) | `disapprove` (shown as "redirect") | | positive | `gratitude`, `satisfaction`, `delight` | Five families are negative: frustration, sadness, confusion, anxiety and trust. `positive` is positive. `disapproval` is neither: it marks a calm rejection of something the agent produced, with no annoyance in it ("no, not that one"), never counts toward the negative rate, and carries no risk score. Each detection records a score, a risk score (negative families only), a trajectory (`none`, `building`, `peak`, `resolved`, `sustained`), an elicitor — whether the agent (`bot`), an external factor, the user themselves (`self`), or something `ambiguous` caused the emotion — a primary cause, and verbatim user quotes as evidence. The Signals → User Emotion tab reports the negative rate (per user turn by default, or per task or trace) and affected users. Emotion analysis runs once a trace has been quiet for about 30 minutes, and at least hourly on a trace that keeps going; traces escalated for deeper negative-emotion analysis can take longer to finish. Read them at [Signals → User Emotion](/dashboard/signals) or via [`GET /emotions`](/data-api/signals). ## Tool-failure classification Every tool call is recorded as it is ingested — name, success or failure, error text, and an effect classification (read, write, send, spawn, compute) — which powers the [Tool Catalog](/dashboard/users-and-tools) within seconds. Failed calls are then classified into failure categories. Every workspace draws on the same set of categories, and Signals → Tool Failures lists the ones your failed calls fall into. Each category carries: * a **label** — a short human-readable name for the failure * a **failure family** — the broader class the failure belongs to * a **likely cause** — what most plausibly produced the error * an **action hint** — what to try first when fixing it Failed calls are classified once the trace has been quiet for about an hour, and at least every four hours on a trace that keeps going. Classified failures appear at [Signals → Tool Failures](/dashboard/signals) (with per-tool drill-downs and time series) and via [`GET /tool-failures`](/data-api/signals) and `GET /tool-failures/:toolName`. ## Laziness signals Laziness detection flags agent effort shortfalls: replies that omit code they promised ("… rest of code …"), stubbed implementations, deflection to the user, promised actions with no tool call following, claimed inability to do things the tool catalog says the agent can do, and similar patterns. Each detection carries a pattern family and a confidence: * Detections at or above 0.5 confidence count as laziness on their own. * Weaker detections count only when two or more pattern families co-occur in the same trace. * Truncated-data patterns are treated as ingestion artifacts, not agent behavior, and are excluded from headline counts. Laziness detection runs once a trace has been quiet for about 30 minutes, and at least every two hours on a trace that keeps going. The Signals page has no Laziness tab: laziness reaches you through alerts (the built-in Laziness signal), laziness rates and KPI tiles in [`GET /trends`](/data-api/analytics), and the CLI's [`moda traces findings`](/cli/reference#moda-traces-findings) and `moda detections list --family=laziness`. ## Hallucination detection A hallucination is an agent message that told someone something the conversation shows is false: a reply, or a message the agent sent through a tool, such as a text, an email or a LinkedIn message. Hallucinations come from Problems: when the incident validator keeps an incident as a false statement (the agent's own words, shown false by a tool result, the user or other context in the conversation), each agent message it quotes becomes a hallucination, with the quoted claim, the evidence that shows it false, and the incident it comes from (`incident_id`). Hallucinations are counted, not given as a rate. Earlier detections, from a check that scored agent claims against the trace's tool results and task status, stay as history: their contradictions count as hallucinations, and their verified and unverified claims are kept as they were. Hallucinations are written when Problems reads the trace, about an hour after its last message. They appear with the [problem](/dashboard/problems) their incident belongs to, can drive alerts through the built-in Hallucinations signal, and are available via [`GET /hallucinations`](/data-api/signals). The Signals page has no Hallucinations tab. ## Problems Problems group negative signals across traces by root cause, so one underlying defect shows up as one ranked item instead of hundreds of scattered detections. * **Attribution** — as each trace is analyzed, its negative signals are attributed to an existing problem or held in the unexplained remainder. * **Discovery** — problem definitions are created and updated from the attributed evidence, and the list is re-ranked as evidence accumulates. * **Verification** — attributions are audited and stamped with a verification status, and each problem maintains a dossier: executive summary, impact, evidence, and investigation reports. * **Lifecycle** — problems move through Open, Reopened, Fixed, and Resolved. * **Feedback loop** — you can mark a problem fixed, dismiss it, flag a wrong attribution, or rename it. Feedback is incorporated automatically; marking a problem fixed arms automatic reopening if the same root cause recurs. Problems live at [Observe → Problems](/dashboard/problems) and in the [Data API problems endpoints](/data-api/problems), including `POST /problems/:id/feedback`. ## World state For each trace, Moda keeps a world state: the tasks the agent worked on and the facts established along the way. * **Tasks** — one per thing the user asked for, with a status (open, resolved, cancelled, idle) and a timeline of progress; a subtask names the task it belongs to. * **Facts** — key–value facts about the user and the work, where Moda's task tracking records them, plus the user's durable profile carried across traces. World state is the current state only: there is no per-message history of changes. View it in the World State view of the [trace detail page](/dashboard/traces) or via [`GET /conversations/:id/world-state`](/data-api/traces); the earlier `/replay` and `/snapshot` views are retired and answer `410 Gone`. ## Next steps * [Data model](/concepts/data-model) — the objects these analyses are computed over. * [Dashboard: Signals](/dashboard/signals) — browse emotion and tool-failure detections. * [Dashboard: Problems](/dashboard/problems) — work the ranked problem list and feedback loop. * [Data API overview](/data-api/overview) — read every analysis programmatically. # Data model Source: https://docs.moda.dev/concepts/data-model The objects Moda stores — traces, messages, users, environments — and the fields that control grouping and prompt attribution. Everything you send to Moda is stored as messages grouped into traces, optionally attached to a user and an environment. This page defines each object and the fields that control how data is grouped and attributed. For exact wire formats, see the [Ingestion API reference](/ingestion/http-api). ## Trace A trace is the full record of one agent run: every message, tool call, thinking block, and step that shares one `conversation_id` string (the trace ID). A trace does not require a human in the loop — a chat session is a trace, and so is a background agent run, a batch job, or one execution of a pipeline. It is the unit nearly every Moda analysis operates on: summaries, world state, signals, use cases, and problems are all computed per trace. Traces appear in the dashboard at Observe → Traces and through the Data API's [trace endpoints](/data-api/traces). A trace is the whole run end to end. It is not the same thing as an OpenTelemetry trace of one request: Moda accepts OpenTelemetry spans over `/v1/traces`, and groups them into a Moda trace by their `moda.conversation_id` attribute. ### Compatibility Traces were previously called conversations. Wire-level names keep the old name so existing integrations keep working: the `conversation_id` field and its SDK and OTLP equivalents, the `/conversations` Data API paths, and the `moda conversations` CLI alias. ### Setting the trace ID Any non-empty string works as a trace ID. Use an identifier your application already has — a session ID, thread ID, run ID, job ID, or ticket ID — and set it before the first model call. Set it in one of three ways: * **SDKs** — `moda.conversation_id = "..."` in [Python](/ingestion/python), `Moda.withConversationId(...)` in [Node.js](/ingestion/node). * **Ingestion API** — the required `conversation_id` field on every `/v1/ingest` event. * **OpenTelemetry** — the `moda.conversation_id` span attribute on `/v1/traces` (see [OpenTelemetry](/ingestion/opentelemetry)). ## Message A message is one event inside a trace: a user turn, an agent response, a system prompt, or a tool interaction. The SDKs create messages automatically from instrumented LLM calls. The field names below are as they appear on [`POST /v1/ingest`](/ingestion/http-api) events; each has an OTLP-attribute equivalent on `/v1/traces`. | Field | Description | | - | - | | `role` (required) | Typically `user`, `assistant`, or `system`. `assistant` messages are recorded as agent output; every other role is recorded as input to the agent. | | `content` / `message` / `content_blocks` | The message body: a plain string, or structured content blocks of type `text`, `thinking`, `tool_use`, `tool_result`, or `image`. The trace detail Timeline view renders these blocks and can filter the timeline by prompts, agent responses, thinking, tool calls, and images. | | `timestamp` | ISO 8601. Defaults to the time Moda received the event. | | `input_tokens`, `output_tokens`, `reasoning_tokens`, `cache_read_tokens`, `cache_creation_tokens` | Token usage for the model call, including provider cache buckets. | | `model`, `provider` | Which model produced the response and which provider served it — for example `gpt-4o` on `openai`. | | `finish_reason` | Why the model stopped: `stop`, `length`, `tool_calls`, and so on. | | `agent_name` | In multi-agent systems, which agent authored the message. The dashboard [Home page](/dashboard/overview) has an agent selector that scopes its metrics by this field; the OTLP equivalent is `gen_ai.agent.name`. | | `external_message_id` | Your own stable, unique ID for the message. | | `user_id` | The end user the message belongs to — see [User](#user). | | `environment` | Per-message override of the request-level environment — see [Environment](#environment). | | `prompt_id`, `prompt_name`, `prompt_version`, `prompt_version_id` | Link the message to a managed prompt version — see [Prompt attribution fields](#prompt-attribution-fields). | ## User A user is an end user of your agent, identified by an optional `user_id` string — an opaque identifier from your own system. Set it with `moda.user_id = "..."` (Python), `Moda.withUserId(...)` (Node.js), the `user_id` event field on `/v1/ingest`, or the `moda.user_id` OTLP attribute. Setting `user_id` powers: * **The Users page** ([Observe → Users](/dashboard/users-and-tools)): per-user health and activity, cohorts such as power users and at-risk users, and a per-user detail view with inferred traits, intent distribution, frustration trajectory, and an activity feed. * **User filtering**: the traces list in the dashboard and the `user_id` parameter on [`GET /conversations`](/data-api/traces). * **User-impact metrics**, such as the Affected users KPI on [Signals → User Emotion](/dashboard/signals) and the Affected users column on [Problems](/dashboard/problems). Traces ingested without a `user_id` are not attributed to any individual user: they are excluded from per-user rows and cohorts, and the Users page rolls them into a single aggregated anonymous row instead. ## Environment Every message belongs to one of three environments: `development`, `staging`, or `production`. Environments keep test traffic out of production analytics: the Traces page has an environment filter, and the Data API accepts an `environment` parameter on [`GET /conversations`](/data-api/traces). Set the environment with: * the `environment` field on the `/v1/ingest` request body, with an optional per-event override * the `environment` option of `Moda.init(...)` in Node.js * the `moda.environment` span attribute or `deployment.environment` resource attribute over OTLP; in Python, pass `resource_attributes={"deployment.environment": "staging"}` to `moda.init(...)` Common aliases are normalized: `dev` and `develop` become `development`; `stg` and `stage` become `staging`; `prod` becomes `production`. Any unrecognized or missing value is recorded as `production`. ## Prompt attribution fields Messages can carry `prompt_id`, `prompt_name`, `prompt_version`, and `prompt_version_id` to link a model call to a managed prompt version. The same link is available as `moda.prompt_key` / `moda.prompt_version` (and related) OTLP span attributes, and as telemetry metadata in the Vercel AI SDK integration. These optional fields identify the prompt and version that produced each call. ## Next steps * [Analysis](/concepts/analysis) — what Moda computes from this data and where each result appears. * [Ingestion overview](/ingestion/overview) — pick an ingestion path for your stack. * [Ingestion API reference](/ingestion/http-api) — exact request schemas, limits, and error envelopes. # Architecture Source: https://docs.moda.dev/cost/architecture # Cost attribution contracts and delivery lanes ## Decision summary Production still writes `cost_usage_event` metric rows. The old-ledger shutdown is done (#11640): its dispatch/consumer no longer publishes fresh days. Until the SQL ledger publishes, the published scoreboard is frozen at Nov 12; report progress from shadow builds, not as fresh published results. This PR changes no emitter, app import, database, flag or deployment. It defines the receipt, coverage, basis and ownership contracts for later work. SQL in `docs/cost/contracts/` is a proposal, **not a migration**. A migration requires explicit user approval and a successful dev dry run; only one may be in flight at a time. Do not copy these files into migrations without approval. Lane E first cuts over using the rows we have today. Only after several days of matching both formats does it switch to `cost_call`, deleting the old metric-matching code in the same stack. Five B lanes may write code in parallel; their deployments are staggered. Dates follow validation, not agent count. ### Rung ladder and current work 1. **Owner:** ≥95% of bill \$ have an owner+class (Nov 12: 43%). 2. **Tenant:** ≥90% of serving \$ have a tenant, which gives average cost per message per tenant. 3. **Run:** ≥90% of tenant \$ have run+stage (AI was 45% on Nov 14). 4. **Message:** every run records which messages it processed; per-call weights only where they change a decision. Lanes only take work for the current rung. The current rungs are **1–2**: shut down the old ledger (done, #11640) and switch to the SQL ledger; roll out keys (`credential_ref` 0% today); owner registry plus bill gaps; split Modal and ClickHouse by tenant. The B lanes' first job is tenant and key on every receipt. **Per-message (user re-plan):** a per-message v0 query ships now from the rows we have. v1 run membership in moda-problems (C2, `moda.cost_run_membership`) is unblocked and no longer waits on the run rung. `credential_ref` and run IDs in other apps are off the per-message critical path. Park the six coverage PRs' call-ID rework (#11314, #11318, #11324, #11325, \#11328, #11331), #11516, #11521, #11528, #11536 and lane D's per-run/per-conversation bases. Preserve approved work; do not rewrite it while it is parked. ## 1. Goals, accounting rules and outputs One AI call becomes one receipt with its usage, scope, timing and charge. A scope is set at the entry point, not guessed downstream. Close each provider/day to its bill, to the nanodollar: every bill dollar appears once. Keep charge credits, named idle costs and an explicit unexplained line; unexplained is never spread. Publication is the commit point: unpublished or failed builds are never read. Outputs stay `cost_ledger_daily`, `cost_interaction_daily` and `cost_ledger_publications`. They provide provider bill closure, shared-cost allocation with residuals, interaction costs, tenant margin and a scoreboard. Ledger kinds remain `exact`, `measured`, `allocated`, `internal`, `unexplained`. `allocated_estimate` describes an allocation method, not an exact receipt. Marginal cost is conversation-level AI cost assigned by coverage, plus serving compute allocated to that conversation. Fully loaded adds tenant work and serving idle in proportion to marginal cost, including fixed serving costs: storage and the serving share of Vercel/Cloudflare. Exclude R\&D, CI and retired resources from fully loaded serving cost; keep them internal and visible. Zero marginal cost cannot be a divisor: retain the unallocated pool explicitly until an approved fallback exists. Incomplete coverage remains run-level rather than artificially inflating covered messages' costs. No runtime integration, production benchmark, ledger rebuild, backfill or schema execution is part of this PR. A new coordinator or other mechanism requires a written reason, not an agent's preference. ## 2. Inputs and flow ``` A receipts + B scopes -> cost_call + cost_run_membership --+ C bills + prices + owner registry -----------------------+-> E SQL daily close -> F reports D measured shared-cost bases -> cost_basis_daily --------+ ``` * **Raw usage:** `moda.cost_usage_event` is unchanged as the current source of truth and Lane E's first input. Existing sibling suppression, exact-charge selection and fine-grain pricing remain until receipt parity is proven. * **Receipts:** future `moda.cost_call` has one latest row per billable call. It is written at `eventsFromLlmUsage` in `packages/pipeline-runtime/src/cost.ts` and the Python twin in `packages/moda-pipeline-runtime-python/src/moda_pipeline_runtime/cost.py`. Existing call sites keep their API; B lanes supply attribution and coverage. * **Coverage:** new **`moda.cost_run_membership`**, one row per run per day with the complete unit IDs it read; calls join on run_id. No `call_id` in v1. The legacy `moda.cost_usage_coverage` is left as it is (no ALTER/DROP). Do not create `cost_call_coverage`. See C2 below. * **Bills:** `provider_cost_fact` supplies vendor/account/SKU/day amounts and credits. C preserves restatements, collects missing AWS/Bedrock/Anthropic sources and normalizes `cf` to `cloudflare`. #11550's per-key OpenRouter split is checked against the SQL ledger, not blindly re-landed. An estimate is not an invoice; fixed Vercel cost is booked fixed. Source fingerprints include bill corrections and fetched data. * **Prices:** C owns `packages/database/src/cost/price-book.ts`, including cache and reasoning rates. Prices are versioned, applied at model/provider/key fine grain, and never override an available provider charge. * **Owner registry:** C supplies `infra/cost-owner-registry.yaml` and loads the proposed table. Resource types cover app, credential, Modal app, Cloudflare Worker and ClickHouse service. Owners have `serving`, `rnd`, `ci`, `retired` classes and non-overlapping effective windows. Missing ownership is visible; it is never silently treated as serving. * **Shared bases:** `cost_basis_daily` stores ClickHouse CPU-seconds, Modal container/busy-seconds, Cloudflare usage and explicitly versioned estimates. Quantity, unit and basis version travel with the attribution grain. Idle is `resource='idle'`, `tenant_id=''`, `method='idle'`. Measured usage comes first: tokens, busy seconds or exact cost. Message count is only an explicitly named fallback, with `method='allocated_estimate'` and a basis version. Nov 13 message shares (tenants 6d9f/2290/4bd5) were 81.5/12.1/6.4%; Modal embeddings hours were 91.3/4.3/4.4%; reported AI-dollar shares were 8.7/86.5/5.1%. The last series is a reported diagnostic, not normalized here. These differ too much for message count to be a primary cost basis. Untagged Modal time (about 200 hours that day) must remain separately labeled when estimated. * **Reports:** F reads only published ledger outputs, not another independent raw-usage pricing or allocation path. Existing approved report PRs are parked or adopted as listed in `pr-lane-map.md`. Approved future volume changes retain their meaning: hourly Cloudflare `queue_operations`/`bytes_written`, rollups of streams below \$1/day, no always-zero embeddings output-token row, duration rollups preserving totals/counts/latency distribution and tenant work bases. Hourly grains retain tenant, source, stage, metric, provider/account/resource and operation/class; preserve conversation/run dimensions where consumed, or a narrow identity mapping. No merge is allowed until reader/inventory/no-row tests show the chosen grain preserves those uses. ## 3. Contract C1: one receipt per billable call Types and validators live only in `packages/cost-contract`, not yet imported by apps. TS and Python share `fixtures/contracts.json` and a cross-language test. ### Identity and corrections `call_id` is lowercase SHA-256 hex of the UTF-8 canonical JSON array: ``` ["cost_call_v1", source, source_event_id, tenant_id, stage, entity_kind, entity_id, attempt_id] ``` After the version tag, these are **the canonical inputs of `makeCostIdempotencyKey`**, minus revision, metric, `usage_class`, `interval_id` and `seq` (including their aliases). Every array element is a string. Serialize with no insignificant whitespace: TS uses `JSON.stringify`; Python uses `json.dumps(..., ensure_ascii=False, separators=(',', ':'))`. Both hash the UTF-8 bytes, with JSON escaping for quotes, backslashes and control characters and no Unicode normalization or timestamp defaults. The literal `cost_call_v1` tag is independent of the correction revision. `tenant_id ?? tenant ?? ''` preserves the old alias/empty-string semantics. Other missing identity fields are empty. A missing source or source event ID returns an empty call ID; it must be counted and rejected, not randomly filled. JSON preserves field boundaries: `s`/`e1`/`t` and `s`/`e`/`1t` produce different IDs. Source event IDs must still be stable and unique per actual call. The legacy metric-level `makeCostIdempotencyKey` stays unchanged; its delimiter-free encoding is not used for call IDs. Another encoding requires a new version tag and an explicitly approved contract change, not a lane edit. Every metric row of the same call shares this identity. A billable retry is a new call and must have a distinct stable source event/attempt identity; a write retry is the same call and revision. `revision` is a positive safe integer and the SQL version column. Calls use `PARTITION BY toYYYYMM(day)` and `ORDER BY (day, tenant_id, call_id)`, with a 730-day TTL like raw usage. Deduplication works only within the sorting key and partition. Day and tenant are immutable for the life of a call; daily builds filter day rather than scanning all history. Day is derived from **ended_at in UTC**. A time correction crossing midnight requires a reversal on the old day plus a new call identity, like other identity changes, not moving a revision to a new key. Equal key/version retries have identical data. Readers select the latest revision explicitly; background merges are not a correctness mechanism. The shared whitespace rule is explicit: only ASCII space, tab, CR and LF count as blank; they are not trimmed from otherwise present IDs. BOM (U+FEFF) and unit separator (U+001F) are nonblank. Both languages reject malformed Unicode (lone surrogates) with validation errors, never a validator crash. Python also catches `UnicodeEncodeError`. Shared fixtures enforce the same hashes/validation results, including BOM, U+001F and lone surrogates. **Coverage keyed on `idempotency_key` is wrong:** that key identifies one metric row (input tokens, output tokens, charge, etc.), not the billable call. Joining it to coverage drops or duplicates parts of the same call. Do not hash that metric key to manufacture a call ID. ### Charge, usage, timing and required scope * Provider-reported `provider_cost_usd`, **including zero or a signed correction**, wins: `cost_source='exact'`, `cost_usd=provider_cost_usd`. Only null means no charge was supplied; then use the price book's `measured_cost_usd` and `cost_source='measured'`. `resolveCharge` and validation enforce this. * Input includes cached tokens; output includes reasoning tokens. Cache read and write are disjoint input subsets; reasoning is an output subset. Never add breakdowns to totals. Prices apply once to the relevant subdivisions, not once to totals and again to cached/reasoning tokens. `normalizeUsage` in TS/Python converts provider formats before validation: Anthropic and `bedrock-claude` report uncached input separately, so 10 input * 7 cache-read + 3 cache-write becomes 20 inclusive input. OpenRouter and `openai-style` already include cache: 100 prompt with 40 cached stays 100. Reasoning remains inside output. Shared fixtures exercise all four formats. * `started_at` and `ended_at` are UTC `DateTime64(3)`, represented on the wire as ISO UTC strings with exactly three decimal places. End must be at least start. `day` is the immutable UTC end date; requests is one. Counts are nonnegative safe integers shared by TS/Python, with UInt64 SQL storage. * `conversation` requires `tenant_id`, `conversation_id` and `run_id`. * `tenant` requires `tenant_id`, `run_kind`, `run_id`. * `company` requires `initiator_kind`, `initiator_id`, and **empty `tenant_id`**. The receipt level is `company`, while ledger classification is `internal`. * LLM calls require `credential_ref` (a name, never the key secret). The explicit `resource_kind='llm'` also catches newly added vendors. Known LLM provider names require it even if mislabeled `other`. * Validation rejects every missing required field. Missing IDs stay empty and appear in `missing_ids`, which Lane A must count. This package never inserts random IDs, placeholder tenants, inferred conversations or UUID defaults. ### Sub-nanodollar money All unit prices (USD per one token, not per million) and call costs are `Decimal(38,18)`, passed as decimal strings. Do not pass JavaScript floats. Price-book computations use decimal arithmetic; no call-level nanos conversion is allowed. **Round to integer nanos once at the ledger slice**, after summing its high-precision amounts. Apply truncation plus an explicit residual and deterministic largest remainder when distributing a slice; allocations plus their residual must equal the bill slice exactly. Persist the pricing/basis/method version used. No sub-nanodollar charge is lost merely because it is individually smaller than one nano. ## 4. Contract C2: run membership in stable message units `moda.cost_run_membership` holds **one row per run per charged day** (per extraction family, below): the complete list of message UNIT IDs the run actually read, scoped by day, tenant and conversation. IDs are recorded in full, never sampled or truncated. Calls join to it on `(day, tenant_id, conversation_id, run_id)`; per-call membership (`call_id`) is not part of v1. Source rows the run read that name no unit yet (mapped-source rows, units not materialized) go in `unresolved_keys`: recorded explicitly, never guessed. Never join metric-level idempotency keys. No message-index ranges: `apps/moda-conversation/src/message_units.py:932–944` rewrites indexes, and `worker.py:4408–4416` executes rewrites before inserting late batches. Unit IDs survive reordering. Record `extraction_version` and, for mapped IDs, `generation_digest`: mapped IDs are generation-scoped. `extraction_version` is one of the four values production writes to `moda.conversation_message_units`, grouped in families: | extraction_version | family | rank | | - | - | - | | `conversation_message_units_v1` | logs | 1 | | `conversation_message_units_v2` | logs | 2 | | `conversation_message_units_source_v1` | source | 1 | | `conversation_message_units_mapped_v1` (requires `generation_digest`) | mapped | 1 | Any other value is rejected; a new extraction version needs a contract change. Families cover different message sources, so their unit sets are disjoint and one run can read several: membership is the union of one row per family. In prod on Nov 15 (5% sample of run conversations, 322 conversations), 311 had units in more than one of v2/source_v1/mapped_v1 and no unit_id appeared under two of them; only 105 unit IDs appeared under both v1 and v2 (3 conversations). Within a family, for each `(run_id, day)` scoped by tenant/conversation, the close uses only the highest-ranked context (v2 supersedes v1); older contexts are ignored, never summed. A unit_id under two families fails closed. Within one version, ties choose the greatest generation_digest by unsigned UTF-8 byte order, not arrival time or revision. Deduplicate revisions within each full SQL key first, then `latestCoverage` selects the winning context; `validateCoverage` checks the selected rows. Conflicting equal-key revisions fail closed. Revision does not make an older extraction current. Recorded cost shares remain tied to the original charged membership snapshot: units absent from the latest version retain those shares at conversation level, counted as unresolved, even if they still exist elsewhere. Intersect the latest context's unit IDs with active units before `coverageAllocation`; never redistribute the absent shares or add costs from older contexts. Split evenly by default (`weight_basis='equal'`): one share per unit and per unresolved key; unresolved keys' shares stay at conversation level and are counted. Proportional `token_counts` (`tokens`) and explicit decimal weights are later refinements only where they change a decision, and require no unresolved keys. Fractions are in \[0,1] and sum to at most one per run. Never duplicate membership across contexts. Explicit weights are never normalized upward; the remainder stays run-level. Empty membership keeps all cost run-level. If a recorded unit is later merged away or deleted, retain its original share at conversation level and count it as unresolved; never drop it or redistribute it to surviving units. `coverageAllocation` and shared contract tests enforce this conservation rule. Membership is an observed snapshot, not today's set of active units. `validateCoverage` checks membership/context, fractions, one row per run/day/family and no unit under two families; `coverageAllocation` takes a run's selected rows together. The table has a day column, monthly partitioning, a sorting key of `(day, tenant_id, conversation_id, run_id, extraction_version, generation_digest)` and a 730-day TTL. All key fields are immutable. Day is the UTC end day of charged calls; a run spanning days repeats membership per charged day. Daily readers filter day; latest revisions are deduplicated within the full key. Volume (prod, Nov 15, read-only): about 13k moda-problems runs a day (reader 5.0k, task 5.2k, task review 2.5k, Dream about 0.2k), so about 13k rows a day (a little more where runs span families). The legacy prod table `moda.cost_usage_coverage` is unused (0 rows) and left in place. Creating the new table is a separate migration: dev dry run and user approval first. No backfill. ## 5. Contracts C3–C6: bases, registry, close and reports `CostBasisDaily` grain is day × provider × resource × tenant × conversation × run × app × stage × unit × basis_version × method, versioned by revision. Units are never mixed. Preserve measured bases separately from message estimates. Registry joins use effective windows at call/bill time; overlapping owners fail closed. The SQL files describe both tables without deploying them. E uses set-based SQL and staging keyed by deterministic build/step IDs. The Worker/DO sequences work, not giant in-memory aggregation. Use deterministic keys/insert tokens so an interrupted build resumes its failed step. Pin a source watermark and checksum fence, including bills, prices, registry, coverage and bases; re-verify before publishing and fail closed on change. Write the publication manifest last. Retain the previous publication on any failure. Close day D once by 08:00 UTC on D+1; rebuild only when its input fingerprint changes. Hourly rebuilding costs approximately 9 CPU-h/day, over the 2% budget. Vendor bills can arrive late or be restated: include fetched bill revisions and historical rule/price/registry changes in invalidation, not only raw usage or a two-day timer. Finality follows the vendor correction window; changes after freeze need explicit restatement, never silent loss. Do not add periodic no-change rebuilds. No new 1 GiB profile is approved here; that separate test/design decision remains on hold. ## 6. Exclusive lanes and existing PR ownership `infra/cost-lanes.json` is the executable path map. Specific exclusions separate shared Problems directories and Modal runtime files; the globs, not app names alone, decide ownership. Unowned paths require architect assignment, not a wildcard exception in a lane PR. | Lane | Owned work and real paths | Validation before production | | - | - | - | | A | Receipt writer/scope helpers in `packages/pipeline-runtime/**` and `packages/moda-pipeline-runtime-python/**`, excluding D's Modal interval/occupancy files; `cost.ts` writers in MCP, status and sentry-tail | Default-off per-app dual write; three full days matching dollars within ±0.1%; no insert loss | | B1 | PR tracker/GitHub, backend inference proxy and Anthropic data agent: `apps/moda-backend/src/{pr-tracker,inference,data-agent}/**`, `apps/moda-github/**`; backend `clickhouse/llm-cost-events.service.ts` and frontend `lib/llm-cost.ts` | Tenant, run ID, key and units read; inference/data-agent paths are not silent exceptions | | B2 | Task review/Problems, including `learning/opus.py`, plus detector/core callers; excludes reader/dream paths | ≥95% credentials, ≥90% conversation and coverage for applicable stages | | B3 | `apps/moda-problems/src/moda_problems/conversation_reader/**`, reader tests, conversation/ingest/world-facts callers | Same scope/key/coverage checks; preserve delivery/run identity | | B4 | Replay apps, `packages/replay-environments/**` (including sandbox proxy/gateway code), backend harness registration | Same checks, including sandbox model requests | | B5 | Problems dream directory, embeddings, thread-segments, analytics and clustering callers | Same checks; preserve measured tenant work bases | | C | Collector vendors/default collector infrastructure, Modal billing, price book, key and owner registries | Bills/credits complete, no unpriced tokens, owners complete | | D | ClickHouse/Modal/Cloudflare basis files, Modal runtime instrumentation, allocation SQL | Tenant split first; per-run/per-conversation bases parked; Problems timeout fix proven before intervals return | | E | Collector `ledger*`/`basis-refresh*`, `index.ts`, `types.ts`, `wrangler.toml`, `clickhouse.ts`, README and deploy workflow; database `sql-ledger*`, `rate*`, `financial-source*`, close/publication SQL | Bill closure, bounded compute, shadow parity and seven-day acceptance | | F | Backend `admin/costs*`, frontend admin cost routes/pages, scoreboard and existing billing interfaces | Published-only reads; monthly margin/bill reconciliation | | architect | This doc, contract modules/SQL, lane map/checker/CI, root package.json/bun.lock; database schema/src migrations, max_migration.txt and fresh-install.sql | No contract drift; one approved migration at a time | C owns collector and database `manual-bills.ts`; E owns database `rate.ts` and `financial-source.ts`. Database `schema/migrations/**` and the repository's actual `src/migrations/**` are architect-owned, not lane-specific DDL exceptions. These B groups are ordered by the observed spend priorities: PR tracker, task review, reader, replay, dream/embeddings. Five lanes write in parallel, **not** five simultaneous deploys. B2/B3/B5 coordinate shared Problems helper changes through their owner; they do not edit each other's paths. Every existing cost PR has exactly one owner in `pr-lane-map.md`. For a PR spanning lanes, choose the lane with the largest additions+deletions in owned files; note every other lane/shared path and split before applying strict lane markers. **Only the owning lane pushes to that PR. No other session pushes, including Replicas sessions that push review fixes.** Existing sessions are not automatically authorized by a historical footer. The architect assigns one active session within the owner lane; stop other sessions before resuming work. No lane rewrites work already in an approved PR. Adopt it and coordinate its merge. The six coverage PRs' call-ID rework is parked, preserving approved work. Close #11512 and #11545. #11532 was reverted by #11636: do not re-land it. \#11523, #11509 and #11550 belong to E for a check against the SQL ledger. \#11516/#11521/#11528/#11536 are parked rather than duplicated. No other PR is closed/edited by this contracts change. Historical cross-lane PRs must be split/coordinated before new marker enforcement; they are not blanket exemptions for future edits. CI recognizes `cost-lane:` labels and `cost//...` branches. Conflicting, unknown or malformed markers fail. Marked PRs may touch only their lane's paths; renames check both old/new names and overlapping ownership fails. Unmarked PRs fail only when they touch `unmarkedCostPaths`, the explicit short list in `infra/cost-lanes.json`: cost emitters/wrappers, database cost code, the whole dedicated cost-collector and Modal-billing apps, owner/key registries, cost emission scripts, cost/deploy workflows, Python cost-runtime/container-interval instrumentation, contracts/docs, filename-matched cost migrations, admin cost pages and the lane controls themselves. Whole app ownership otherwise applies **only to lane-marked PRs**: ordinary Problems or runtime changes need no cost marker. Root `package.json` and `bun.lock` remain outside this short list (19 merged PRs touched them in 14 days). Lane-marked PRs may touch them only as architect. Contract tests still run. Ownership is checked using the base commit's policy and checker before executing head code, so changing the PR's map cannot authorize its own edits. The first policy-creating PR necessarily bootstraps from its head; that initial policy needs explicit review. The workflow resolves queue origins and checks source diffs and queue paths with the base checker first. The head runner adds required-body and Graphite queue-origin checks; see [lane operating rules](lanes/README.md). CI checks paths, not human identity: the single-session pushing rule also needs operator enforcement. Making this check required in merge rules needs a repository admin. ## 7. Deployment radius and canaries Path-filter audit: a change to TS runtime `src/cost.ts` matches **13 deploy workflows**; the Python twin matches **18**. There are **25 unique filtered workflows** across the two. These are workflow counts, not a count of distinct apps/functions: the Problems workflow deploys both Problems and Dream, for example. An additional frontend workflow runs unfiltered on every main push. TS: analytics-scheduler, ingest, contract-compile, contract-validation, embeddings, github, harness-analyze, replay-runner, sentry-tail, thread-segments, tool-classification, topic-assignment, world-facts (`deploy-*.yml` names). Python: analytics-container, clustering, compliance-agent, conversation-drainer, conversation-worker, custom-signals-agent, design-registry, frustration-agent, laziness-agent, contract-compile, contract-validation, embeddings, problems, replay-runner, tool-classification, topic-assignment, user-refresh, replay. Lane A ships behind a **default-off per-app flag**. Package deployment may fan out as above, but enable receipt emission for one app at a time. Before each enable, record a baseline and rollback literal. Observe at least 30 minutes for insert loss/retries, inference/error rate, hook latency and volume. Any error rise means revert; keep the existing p99 >500 ms / interval volume >50k/hour rollback thresholds where that instrumentation is applicable. Confirmed inserts require `wait_for_async_insert=1`, bounded retries and surfaced shutdown loss. Run B deployments one at a time with the same canary rule. Do not re-enable Problems interval recording as a side effect of receipt adoption. The standalone contract module has no workspace manifest or app import and matches **no path-filtered app deploy**. But **zero deploy workflows on merge cannot be promised**: `deploy-frontend.yml` deliberately deploys main's latest tip without path filtering, including docs-only commits. The user accepts this existing exception: docs/contracts-only changes may harmlessly redeploy the unchanged frontend. This PR does not change that policy. Lane deployments still require the validation and canary gates above. ## 8. Validation-driven plan, rollback and deletion 1. **Contracts first:** review these types, fixtures, SQL and lane assignments. Land no database migration with them. Each future schema change needs the user approval + dev dry run rule, separately, one in flight at a time. 2. **E first cutover:** old-ledger shutdown is done (#11640). \#11633 is lane E's **next job after #11634 merges**, not parked; rung 1 depends on its SQL-ledger coordinator and publication work. Do not re-land #11532 (reverted by #11636); close #11512. Shadow Nov 11–12 using current narrow rows and compare against those old published days. Publish only once bill totals are equal and attribution differences are explained. Publications are provisional during the seven-day acceptance window. `buildLedger` is kept only as a frozen test comparison, never a runtime fallback. Until this publishes, progress comes from shadows; the published scoreboard stays frozen at Nov 12. Target ≤2% ClickHouse CPU; build D once at D+1 and rebuild only on input change, not hourly. The old-engine deletion PR lands within days in the same stack as the stop PR, independently of later receipt adoption. Keep only the frozen test comparison. Staging-table drops need explicit user approval and a dev dry run. 3. **A and C/D:** approved schemas precede writers. A canaries one app and then dual-writes confirmed receipts; compare receipt dollars/usage/identity to raw rows for at least three full days, including corrections/retries. C/D adopt approved bills/bases PRs; changes that need migrations wait for approval. 4. **B1–B5:** code may proceed in parallel against the contract. Enable in spend order, staggered, with stage-level credential/scope/coverage scoreboards. 5. **E receipt input:** only after several days of matching formats, switch to receipts + run membership + tenant bases + registry. Repeat shadows/row diffs and seven consecutive days of acceptance: exact bill totals, no lost calls, correct residuals, publication by 08:00, measured cost within budget. Delete obsolete format-matching code in the same receipt-adoption stack. This does not defer the old-engine deletion above. The seven-day gate is validation, not a promise that five agents finish in a week. 6. **F:** unpark reports only when publication/input contracts are accepted. Reconcile one month of tenant margins to bills before report cutover. There is **no rollback to the old ledger path**. Rollback means the last publication stays; failed or mismatched new builds never replace it. Preserve raw facts and recorded membership. Legacy rating (`rating.ts -> cost_rated_daily`) keeps running until its Cloudflare-estimate dependency is replaced; deleting the old ledger does not authorize stopping it. Every PR states its lane/step, scoreboard number/proof query and deleted code. Use Graphite (`gt modify -cam`, then `gt submit --no-stack --no-edit --publish --no-interactive`) only when authorized; require exact-head Greptile 5/5, Replicas approval and green CI before merge. ## 9. Open gates and risks * User approval and dev dry run for **each** proposed schema, especially the new `cost_run_membership` table; SQL syntax/Cloud shared-engine adaptation is not claimed production-tested by this contracts PR. * Stable producer source/attempt identities and legacy-to-call mapping must be demonstrated. Missing IDs are counted/rejected, never randomly repaired. * Equal-revision conflicting payloads, ownership-window overlap, changed source fences, invalid coverage and unknown prices must prevent publication. * Decimal precision must survive collector/JSON/driver boundaries; ledger-slice rounding and largest remainder need SQL integration tests in E's lane. * Actual close CPU/bytes/memory and vendor correction windows need validation; the held 1 GiB test is not implicitly resumed. * PR footers identify associated sessions, not a verified last GitHub pusher. Where no session is visible, stop/assign through the PR author before edits. # A Source: https://docs.moda.dev/cost/lanes/A # A — receipts and runtime ## Goal Every call emits a valid `cost_call` receipt under the [contract](../../../packages/cost-contract/README.md) and [architecture](../architecture.md). During the owner/tenant rungs, adopt emitter/key prerequisites, not per-call coverage redesign. The scoreboard holds current values. ## Metric Share of AI provider-charge dollars whose rows carry required attribution fields for their work level. This is an **interim readiness query**, not a full exit proof. It checks the existing slim financial projection's attribution fields over the last completed UTC hour, deduplicating metric identities. It does not claim that legacy metric rows are already valid `CostCall` objects. Legacy scope is conversation when `conversation_id` is present, tenant when only tenant is present, otherwise company; missing company initiators remain uncovered. The contract validator remains the authority for explicit work level, identity, Unicode, timestamps, usage and prices after adoption. Price-book-only/unbilled calls are outside this diagnostic's provider-charge denominator and need the bill reconciliation gate; do not report this as coverage of all invoiced spend. `occurrence_hash` is the projection's hash of the raw `idempotency_key`, and `has_call_identity` preserves whether `source_event_id` was nonempty. The window and provider-charge denominator are unchanged from the raw diagnostic. No raw payloads or event-ID strings need to be scanned. ## Proof query ```sql theme={"dark"} WITH charges AS ( SELECT occurrence_hash, argMax(tuple(quantity, source!='' AND has_call_identity=1 AND stage!='' AND caller_app!='' AND credential_ref!='' AND multiIf(conversation_id!='', tenant_id!='' AND run_id!='', tenant_id!='', run_kind!='' AND run_id!='', initiator_kind!='' AND initiator_id!='')), tuple(event_revision,_ingested_at)) AS v FROM moda.cost_usage_financial PREWHERE event_date>=toDate(toStartOfHour(now('UTC'))-INTERVAL 1 HOUR) AND event_date<=toDate(now('UTC')) AND metric='provider_cost' AND resource_kind='llm' AND unit='usd' AND event_time>=toStartOfHour(now('UTC'))-INTERVAL 1 HOUR AND event_time0 AND sum(abs(v.1))>0 AND countIf(NOT v.2)=0) AS field_readiness_pass FROM charges SETTINGS readonly=2,max_threads=1,max_bytes_to_read=1000000000,max_result_rows=1000, max_execution_time=30,read_overflow_mode='throw',result_overflow_mode='throw' ``` ## PRs to adopt now From the [merged map](../pr-lane-map.md): #11538 (runtime labels), #11515 (account resolution/legacy retirement; coordinate C/E), #11321 (emitter config). Adopt approved work rather than rewrite it. Coverage call-ID rework waits for the run/message rungs; B's six parked coverage PRs are not runtime prerequisites. ## Stop-and-ask conditions Ask before the `cost_call` migration, flipping any per-app flag, or any runtime package change. Also stop on ambiguous scope, missing invoice coverage or a proposal to substitute a random/default identity. Follow [standing rules](README.md). ## Exit check The query's `field_readiness_pass` must pass with a nonempty dollar denominator; unknown is fail. **Full lane exit is blocked until the `cost_call` table exists and has a contract-level proof query.** It additionally requires `validateCostCall` to accept the emitted receipts in both languages and approved per-app canary evidence. Do not label the SQL prerequisite alone as full contract compliance. # B Source: https://docs.moda.dev/cost/lanes/B # B — call sites (B1–B5) ## Goal Pass the tenant rung: attribute serving dollars to nonempty tenants at each app/caller site. Run ID and stage rollout wait for the run rung. The scoreboard holds current values; use the [architecture](../architecture.md) and existing B1–B5 ownership in `infra/cost-lanes.json`, not a new `B` marker. ## Metric Share of serving dollars with a nonempty tenant, by app and caller site. Published non-internal dollars, including unexplained dollars, are a conservative serving denominator until C classifies them; never improve the fraction by discarding an unknown app/site or an unexplained row. Absolute signed row amounts measure attribution exposure, not net bill reconciliation (E owns that gate). ## Proof query ```sql theme={"dark"} WITH publications AS ( SELECT day,argMax(ledger_run_id,tuple(ledger_version,published_at,ledger_run_id)) AS run FROM moda.cost_ledger_publications WHERE day>=toDate(now('UTC'))-7 AND day0 AND tenant_share>=0.90) AS exit_pass FROM moda.cost_ledger_daily FINAL PREWHERE day>=toDate(now('UTC'))-7 AND day=toDate(now('UTC'))-7 AND day=toDate(now('UTC'))-7 AND day0 AND owner_class_lower_bound>=0.95) AS attribution_prerequisite_pass FROM classified SETTINGS readonly=2,max_threads=1,max_bytes_to_read=1000000000,max_result_rows=1000, max_execution_time=30,read_overflow_mode='throw',result_overflow_mode='throw' ``` ## PRs to adopt now From the [merged map](../pr-lane-map.md): #11508 (manual PlanetScale invoices), \#11502 (bounded collector retries), #11326 (runtime key owners), #11269 (per-credential reconciliation), #11265 (per-app keys/deploy inventory). Coordinate #11515 with A/E; do not push to their PR. The collector's ledger wiring and database `rate.ts`/`financial-source.ts` belong to E, not C. E also owns the CI planner, ledger-load/schema-wait helpers, instrumentation and wiring/retirement tests needed by #11642; that PR waits for the architect's ownership correction in #11646 to land first. ## Stop-and-ask conditions Stop on missing invoices, an ambiguous owner/class, replacing provider charges with estimates, cross-lane edits or any migration/deploy/credential activation. Do not classify R\&D, CI or retired work as serving to improve tenant coverage. Follow [standing rules](README.md). ## Exit check `attribution_prerequisite_pass` must pass with a nonempty denominator. Full owner exit additionally reconciles this diagnostic to the approved owner registry and complete bill inventory at the same day/account grain. Until registry proof is available, **full lane exit is blocked until the approved owner registry exists and has a registry-backed proof query**, regardless of this lower-bound query. # D Source: https://docs.moda.dev/cost/lanes/D # D — shared-cost bases ## Goal Split shared ClickHouse, Modal, Cloudflare, Vercel and storage by a measured basis, leaving the residual explicit. Current work is owner/tenant splits, not run or conversation bases. The scoreboard holds current values; policy lives in the [architecture](../architecture.md). ## Metric Share of shared-dollar exposure allocated by a measured basis. A measured row must use the SQL executor's `allocation:` method, a versioned basis and a positive basis quantity. Estimated allocations and named idle/internal residuals remain in the denominator, not the measured numerator. E checks signed bill closure. ## Proof query ```sql theme={"dark"} WITH publications AS ( SELECT day,argMax(ledger_run_id,tuple(ledger_version,published_at,ledger_run_id)) AS run FROM moda.cost_ledger_publications WHERE day>=toDate(now('UTC'))-7 AND day0) AS measured_nanos, measured_nanos/nullIf(shared_exposure_nanos,0) AS measured_share, shared_exposure_nanos-measured_nanos AS explicit_residual_nanos, toUInt8(shared_exposure_nanos>0 AND measured_nanos=shared_exposure_nanos) AS exit_pass FROM moda.cost_ledger_daily FINAL PREWHERE day>=toDate(now('UTC'))-7 AND day0) GROUP BY provider ORDER BY provider SETTINGS readonly=2,max_threads=1,max_bytes_to_read=1000000000,max_result_rows=1000, max_execution_time=30,read_overflow_mode='throw',result_overflow_mode='throw' ``` ## PRs to adopt now From the [merged map](../pr-lane-map.md): #11519 (ClickHouse internal CPU buckets), \#11374 (explicit Modal internal classification), #11310 (Modal tenant allocation), \#11308 (occupancy/idle/untagged). Coordinate occupancy prerequisites in B2's \#11309 without pushing to it. Park D's per-run/per-conversation bases until the run/message rungs; adopt only owner/tenant slices now. The collector's `clickhouse-basis.clickhouse-local.test.ts` belongs to E for old-ledger retirement (#11642, after #11646's ownership correction lands). The production ClickHouse basis implementation remains D-owned. ## Stop-and-ask conditions Stop before a migration, deploy or flag flip; on estimated/fabricated bases, unexplained residual redistribution, or a proposed run/conversation expansion. Follow [standing rules](README.md). ## Exit check Every expected shared provider must appear with `exit_pass=1` for complete measured coverage; missing/empty providers fail. Otherwise report the query's explicit residual, not an invented split. A deliberate idle/fixed residual needs architect approval of its owner/class and does not become measured allocation. # E Source: https://docs.moda.dev/cost/lanes/E # E — SQL ledger ## Goal Next job is **#11633 rewired onto the SQL executor**, not the retired engine. Close the current owner/tenant rungs under the [architecture](../architecture.md). The scoreboard holds current values; shadow builds are progress evidence while published output is frozen. ## Metric Days closed to the bill **to the nanodollar**, published by D+1 08:00 UTC, with SQL-ledger CPU under **2% of sampled replica-host busy CPU**, using the user-approved cycle-1 denominator instead of the previous all-finished-query denominator. The closure diagnostic checks the latest seven completed UTC days, current SQL manifests and signed bill/ledger totals. Run [E-cpu.sql](E-cpu.sql) separately for the latest UTC hour whose end is at least two minutes old, allowing query-log rows to arrive before the check. Every replica's retained query log must cover both boundaries; otherwise the proof is unavailable. Its numerator reads terminal `QueryFinish`, `ExceptionBeforeStart` and `ExceptionWhileProcessing` rows whose `log_comment` contains `sql-ledger`, with `event_date` and tag filtering in `PREWHERE` before reading the CPU map. It sums `OSCPUVirtualTimeMicroseconds` per replica. It does not scan all query CPU to obtain a denominator. The denominator time-weights `OSUserTime + OSNiceTime + OSSystemTime` from `system.asynchronous_metric_log` across every current replica. Production metric descriptions define these unnormalized rates as busy CPU cores summed across the host's cores, including **all host processes**, not just query threads or ClickHouse. Multiplying by seconds gives CPU-seconds. This is a **sampled host CPU estimate**, including background work, not billed compute or query CPU. The estimate holds each rate over the preceding logged interval; boundary intervals are clipped to the hour, with at most two minutes of padding. Duplicate-second samples are averaged. Every host needs all three metrics covering the whole hour and no gap over ten seconds. Missing hosts/metrics, invalid samples, zero denominator, no tagged activity or missing CPU counters yield NULL and fail, never a passing zero. Host replacement during the hour requires review; this query is not a historical host-inventory audit. Both sources fit the unchanged 1 GB read guard in the bounded design. However, **tag completeness is not yet verified on the SQL executor deployment**: confirm that its reads, writes, retries and cleanup all carry the `sql-ledger` marker before treating a CPU result as exit evidence. The narrower tag scan is not proof that untagged work is absent. Until that review and the shadow checks pass, full E exit remains blocked. The closure query below deliberately keeps its CPU field NULL and overall exit blocked; it cannot certify the independent CPU gate. Equality of daily totals is a necessary diagnostic, not a replacement for the executor's per-bill conservation/content audits or explained-difference review. ## Proof query ```sql theme={"dark"} WITH publications AS ( SELECT day,argMax(tuple(ledger_run_id,published_at,builder_version,provisional), tuple(ledger_version,published_at,ledger_run_id)) AS p FROM moda.cost_ledger_publications WHERE day>=toDate(now('UTC'))-7 AND day=toDate(now('UTC'))-7 AND day=toDate(now('UTC'))-7 AND day0 AND l.rows>0 AND b.nanos=l.nanos AND p.p.2<=toDateTime(d.day+1,'UTC')+INTERVAL 8 HOUR) AS closed_on_time, toUInt8(0) AS exit_pass FROM (SELECT toDate(now('UTC'))-1-toInt32(number) AS day FROM numbers(7)) AS d LEFT JOIN publications AS p ON d.day=p.day LEFT JOIN bills AS b ON b.day=d.day AND b.ledger_run_id=p.p.1 LEFT JOIN ledger AS l ON l.day=d.day AND l.ledger_run_id=p.p.1 ORDER BY d.day SETTINGS readonly=2,max_threads=1,max_bytes_to_read=1000000000,max_result_rows=1000, max_execution_time=30,read_overflow_mode='throw',result_overflow_mode='throw' ``` ## PRs to adopt now From the [merged map](../pr-lane-map.md): #11633 is next. Check #11550, #11523 and \#11509 **against the SQL ledger**, preserving bill-key splits, invalidation and instrumentation checks without old-engine coupling. #11640 is merged. #11532 was reverted by #11636: do not re-land. #11512 and #11545 are designated for closure, not adoption. Keep legacy rating running until its Cloudflare-estimate dependency is replaced. Delete replaced execution code in the stop/deletion stack. \#11642's old-ledger retirement stays in E and depends on #11646 landing first. That architect correction moves the CI planner, ledger-load/schema-wait scripts, instrumentation and wiring/retirement tests from C/D to E. The CI planner reads ledger tables, so those helpers and tests follow E's existing `index.ts` and `clickhouse.ts` ownership. It does not transfer bill collectors or production ClickHouse basis allocation from C/D, or authorize drops/deploys. ## Stop-and-ask conditions Ask before **publishing, any table drop, or any deploy**. First compare Nov 11–12 shadow builds to old published days: equal bill totals and explained differences. Then use the seven-day provisional acceptance window before final acceptance. Keep `buildLedger` only as frozen test comparison. Rollback retains the last publication; it never restarts the old path. Follow [standing rules](README.md). ## Exit check Every generated day must have `closed_on_time=1`, the CPU companion must have `exit_pass=1` with verified tag completeness, and the combined exit remains blocked until all evidence is reviewed. Missing days cannot disappear from the result. Additionally require per-bill audits, approved shadow differences and the seven-day provisional acceptance evidence. A nonempty builder version alone does not certify the SQL executor: verify it against #11633's approved version. # F Source: https://docs.moda.dev/cost/lanes/F # F — reports and margins (parked) ## Goal **Parked until the tenant rung passes.** Later expose marginal and fully loaded cost per message from accepted publications, not a parallel ledger. The scoreboard holds current values; see the [architecture](../architecture.md). ## Metric Later: marginal serving cost per processed message, and fully loaded serving cost per processed message including storage and the measured serving share of Vercel/Cloudflare/fixed infrastructure, excluding R\&D/CI/retired work. Today's query is only an output-readiness diagnostic: it counts messages in each published snapshot and exposes marginal attributed cost. It deliberately does not manufacture fully loaded margins before C/D establish serving classification and fixed-cost splits. Message indexes here group an immutable publication's messages; they are never used as historical coverage identities. ## Proof query ```sql theme={"dark"} WITH publications AS ( SELECT day,argMax(ledger_run_id,tuple(ledger_version,published_at,ledger_run_id)) AS run FROM moda.cost_ledger_publications WHERE day>=toDate(now('UTC'))-7 AND day=toDate(now('UTC'))-7 AND day0 AND countIf(tenant_id='' OR conversation_id='' OR unit_id='')=0) AS output_readiness_pass FROM interactions GROUP BY day ORDER BY day SETTINGS readonly=2,max_threads=1,max_bytes_to_read=1000000000,max_result_rows=1000, max_execution_time=30,read_overflow_mode='throw',result_overflow_mode='throw' ``` ## PRs to adopt now None while parked. From the [merged map](../pr-lane-map.md), park #11516, #11521, \#11528 and #11536 until the tenant rung passes and SQL publications are accepted; fully loaded work also waits for measured serving bases. #11503's scoreboard work is an existing prerequisite, not authorization to start detailed reports. \#10907 is adjacent customer billing outside the provider-close cutover; parked here until that work is separately authorized after the tenant rung. ## Stop-and-ask conditions Stop before un-parking, changing a denominator, treating absent attribution as zero, estimating unexplained cost into messages, or any deploy/migration. Follow [standing rules](README.md). ## Exit check The query's `output_readiness_pass` must pass for every expected day; missing days/empty denominators fail. This is not permission to exit the parked state: the architect must first confirm the tenant rung and C/D/E gates, then approve a proof query for the fully loaded numerator. Neither a marginal output row nor a successful diagnostic is proof that fully loaded margins are available. # Pr lane map Source: https://docs.moda.dev/cost/pr-lane-map # Open cost PR map — approved ownership snapshot Original inventory snapshot: 2026-11-15; updated below for the approved rung-1–2 decisions. Historical changed-line splits and session evidence are retained; they are not a new inventory or a claim that every row is still open. Read-only inventory from `gh pr list --state open --limit 1000`; PR files and commit authors from the paginated GitHub API. Includes 39 current cost-program PRs (including newly opened #11633), reader credentials, and five adjacent billing/model-cost PRs: **45 total**. Dispositions are proposals, not GitHub actions. Nothing is closed, pushed, relabeled or merged here. Only the owning lane pushes to a PR, including fixes normally made by Replicas. The architect assigns one active session per owning lane; other sessions, including sessions that push fixes automatically, stop. An approved PR is adopted, not rewritten. The six coverage PRs’ call-ID rework is parked; preserve their membership/scope work. #11512/#11545 closure and the dispositions below are user-directed decisions. Park means preserve existing work, not duplicate it. Adoption is not a claim of completed review or permission to merge. Owner = lane with the largest additions+deletions in owned paths. The split column reports the actual lane totals; shared/unassigned paths require architect assignment or a separate coordinated PR before strict lane markers. Historical b1/b2 suffixes do not define ownership. Ties require architect resolution (none in this snapshot). Current session evidence comes from the PR footer or latest commit message; these identify associated sessions, not a verified GitHub pusher. Full workspace/session links are supplied so an operator can stop them. When absent, show the latest commit author and PR author; no session ID is invented. All current-program PRs have PR author arhamkhan04. Adjacent #10907/#10901/#8661/#7060/#4378 have PR author 876pol. Some footers name both an original Devin session and a later Replicas workspace; both are retained. | PR and existing work | Owner lane | Current session / author evidence | Disposition and reason | Cross-lane split (changed lines) | | - | - | - | - | - | | [#11633](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11633) feat(cost-ledger): stage daily close coordinator prototype | E | Devin AI; PR author arhamkhan04; session unknown | next job after #11634 merges — not parked; rung 1 depends on its SQL-ledger coordinator/publication work, with validation and compute gates | C: 21; E: 906; architect: 463 | | [#11550](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11550) fix(cost-collector): partition final OpenRouter bills by key activity | E | Replicas [886d20bb](https://app.replicas.dev/workspaces/886d20bb-b777-4711-b551-f92e79dd4818) | check vs SQL ledger — preserve approved per-key bill split; do not duplicate it | E: 204; C: 5 | | [#11545](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11545) revert(cost-collector): prepare rollback of #11504 attribution change | E | Devin AI; PR author arhamkhan04; session unknown | close — user-requested closure of contingency rollback; do not merge | single lane | | [#11538](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11538) pipeline-runtime: cost emitters send the JSON attribution label | A | Replicas [fd379797](https://app.replicas.dev/workspaces/fd379797-d3ca-4c9d-82e1-1e53b14fec71) | adopt — approved runtime attribution labels | single lane | | [#11536](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11536) feat(costs): tie change-log effects to distinct message cost deltas | F | Devin AI; PR author arhamkhan04; session unknown | park — detailed reports wait for current owner/tenant rungs and accepted SQL publications | single lane | | [#11535](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11535) fix(embeddings): label latency probe cost rows as internal | B5 | Devin [8b9d9c95](https://app.devin.ai/sessions/8b9d9c95f08d468cb50054067e4427a0); Replicas [c6560b7f](https://app.replicas.dev/workspaces/c6560b7f-555b-45b4-b388-47da9a1856f3) | adopt — approved internal embeddings probe classification | single lane | | [#11532](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11532) fix(cost-collector): re-land cadence with durable send-time coalescing | E | Replicas [9000127b](https://app.replicas.dev/workspaces/9000127b-7c43-43c0-b198-9131f1f14653) | reverted by #11636 — do not re-land | C: 124; E: 1389; shared/unassigned: 3 | | [#11528](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11528) feat(costs): add checked-in manual prices and margin scenarios | F | Replicas [289b9fac](https://app.replicas.dev/workspaces/289b9fac-cc1e-4df2-ba42-d9a1fe499764) | park — detailed reports wait for current owner/tenant rungs and accepted SQL publications | F: 703; shared/unassigned: 4 | | [#11523](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11523) fix(cost): invalidate published ledger days on Modal rule edits | E | Replicas [61291c0e](https://app.replicas.dev/workspaces/61291c0e-a7e7-4771-b28c-d4cfba462373) | check vs SQL ledger — preserve required Modal-rule invalidation without old-engine coupling | single lane | | [#11521](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11521) feat(costs): add fully loaded report allocation view | F | Replicas [623d2669](https://app.replicas.dev/workspaces/623d2669-7f3e-4627-b1a8-bba6f8c444f6) | park — detailed reports wait for current owner/tenant rungs and accepted SQL publications | F: 898; shared/unassigned: 4 | | [#11519](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11519) cost-collector: async_insert_flush and adhoc_script internal buckets in the ClickHouse basis | D | Replicas [a94f2a5d](https://app.replicas.dev/workspaces/a94f2a5d-b77d-46b4-902e-7dfd8b8345fd) | adopt — approved ClickHouse internal CPU buckets | single lane | | [#11516](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11516) feat(costs): add published marginal unit-cost report | F | Replicas [1fb07f68](https://app.replicas.dev/workspaces/1fb07f68-f9eb-4714-ba4d-bd59e7cb1624) | park — detailed reports wait for current owner/tenant rungs and accepted SQL publications | F: 741; shared/unassigned: 4 | | [#11515](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11515) fix(cost): resolve OpenRouter account identity and retire legacy billing | A | Replicas [cbc5ae6b](https://app.replicas.dev/workspaces/cbc5ae6b-0909-4439-99ff-954fead25f75) | adopt — approved account resolution and legacy retirement; coordinate C/E | B3: 3; E: 47; C: 71; A: 480; shared/unassigned: 48 | | [#11512](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11512) fix(cost-ledger): reread oversized provider bill days in dedup-key pages | E | Replicas [0b416b94](https://app.replicas.dev/workspaces/0b416b94-14df-43a1-afdc-1fc1703ac875) | close — superseded by the SQL-ledger path; do not re-land | single lane | | [#11509](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11509) feat(cost-collector): attribution blind spots in the instrumentation checks | E | Devin [8b9d9c95](https://app.devin.ai/sessions/8b9d9c95f08d468cb50054067e4427a0); Replicas [b9bd55b6](https://app.replicas.dev/workspaces/b9bd55b6-0255-481d-a62b-a774bd578918) | check vs SQL ledger — E owns matching/check integration; historical split below predates reassignment | C: 138; E: 47 | | [#11508](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11508) feat(cost): load PlanetScale's paid Jul-Oct invoices as manual bills | C | Replicas [327a0b8d](https://app.replicas.dev/workspaces/327a0b8d-84fa-451c-ba42-78ddc6b1f6ac) | adopt — approved historical manual invoices | C: 4; shared/unassigned: 2 | | [#11506](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11506) fix(conversation): retry fan-out cost row inserts and wait for the async flush so failed writes are seen | B3 | Devin [8b9d9c95](https://app.devin.ai/sessions/8b9d9c95f08d468cb50054067e4427a0); Replicas [41600d2c](https://app.replicas.dev/workspaces/41600d2c-9875-4643-ac7f-79dfe74a2f28) | adopt — approved confirmed inserts/retries | single lane | | [#11503](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11503) feat(costs): add published daily attribution scoreboard and raw event hygiene | F | Replicas [208c41cf](https://app.replicas.dev/workspaces/208c41cf-7113-4bb3-afbd-2a808a6c03b9) | adopt — approved published attribution scoreboard | single lane | | [#11502](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11502) feat(cost-collector): retry every collector's vendor reads with bounded backoff | C | Replicas [32de9135](https://app.replicas.dev/workspaces/32de9135-350c-4840-aede-0981ea4fb54d) | adopt — approved bounded vendor retries | single lane | | [#11374](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11374) feat(cost): classify internal Modal residuals using seeded app rules | D | Replicas [f30a327b](https://app.replicas.dev/workspaces/f30a327b-6539-43c2-8ed4-1f066495dfa4) | adopt — approved internal Modal residual classification; migration needs approval | D: 168; shared/unassigned: 12 | | [#11363](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11363) feat(cost): stage Problems and Dream credential deployment without call-site changes (b5) | B2 | Replicas [a0818a21](https://app.replicas.dev/workspaces/a0818a21-b549-4e4b-b5bf-5258dc857ff9) | adopt — approved Problems/Dream credentials, staged enablement | B5: 8; B2: 307; B1: 2; B4: 2; C: 108 | | [#11362](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11362) feat(cost): roll out fail-closed GitHub and replay credentials (b4) | B1 | Replicas [b8bc91c3](https://app.replicas.dev/workspaces/b8bc91c3-fa4a-4cad-afa6-f9fe79a7b8ef) | adopt — approved GitHub/replay credentials, split remaining lanes | B5: 8; B2: 6; B1: 78; B4: 17; shared/unassigned: 19; C: 28 | | [#11361](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11361) feat(cost): roll out fail-closed embedding and thread-segment credentials (b3) | B5 | Replicas [d11f669c](https://app.replicas.dev/workspaces/d11f669c-df1a-4e74-8387-44b42cf1e414) | adopt — approved embeddings/thread-segment credentials | B5: 266; B2: 6; B4: 2; C: 46 | | [#11360](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11360) feat(cost): roll out fail-closed custom-signals and laziness credentials (b2) | B2 | Replicas [7d21db84](https://app.replicas.dev/workspaces/7d21db84-be0b-4fbb-8ccd-6bd5cced2b30) | adopt — approved detector credentials, retain approved tests | B5: 4; B2: 625; B4: 2; C: 97; shared/unassigned: 192 | | [#11359](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11359) feat(cost): roll out fail-closed LLM credentials to analytics and core callers (b1) | B2 | Replicas [742a2b06](https://app.replicas.dev/workspaces/742a2b06-7e63-4056-b295-5f1fbc652146) | adopt — approved core credentials, split other callers | B5: 561; B2: 1758; B4: 93; C: 180; B1: 27 | | [#11331](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11331) feat(tool-classification): delivery run id and coverage of the gap receipts each delivery reads | B2 | Devin [8b9d9c95](https://app.devin.ai/sessions/8b9d9c95f08d468cb50054067e4427a0); Replicas [2d5f1563](https://app.replicas.dev/workspaces/2d5f1563-c968-4210-8020-416f41b4b866) | park — current rungs are 1–2; preserve existing work; call-ID rework deferred | E: 59; B2: 349; A: 1 | | [#11328](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11328) feat(thread-segments): delivery run id and coverage of each segment's member units | B5 | Devin [8b9d9c95](https://app.devin.ai/sessions/8b9d9c95f08d468cb50054067e4427a0); Replicas [3e6383d3](https://app.replicas.dev/workspaces/3e6383d3-80db-44fb-97ea-b9124e65791d) | park — current rungs are 1–2; preserve existing work; call-ID rework deferred | B3: 13; B5: 470 | | [#11326](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11326) feat(cost): resolve owners for runtime OpenRouter keys | C | Replicas [f057e5bf](https://app.replicas.dev/workspaces/f057e5bf-5e11-496e-99e1-410387af3a12) | adopt — approved runtime key ownership registry | single lane | | [#11325](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11325) feat(task-tracker): run id per tracker pass and coverage of the messages each call shows | B3 | Replicas [3834b51e](https://app.replicas.dev/workspaces/3834b51e-7ff0-4722-91db-708812d23d68) | park — current rungs are 1–2; preserve existing work; call-ID rework deferred | B3: 220; B2: 33 | | [#11324](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11324) feat(embeddings): attribute each delivery's cost and cover the units it embedded | B5 | Replicas [4a25b258](https://app.replicas.dev/workspaces/4a25b258-7a98-4d62-aed9-f236e021365b) | park — current rungs are 1–2; preserve existing work; call-ID rework deferred | E: 46; B5: 543; A: 151 | | [#11321](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11321) feat(pipeline-runtime): emitter config for caller_app, credential_ref and release | A | Replicas [c531ae35](https://app.replicas.dev/workspaces/c531ae35-9352-47e1-b2ad-3e63abbc2622) | adopt — approved emitter configuration | single lane | | [#11318](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11318) feat(problems): write per-unit cost coverage for task review windows | B3 | Replicas [f49f0f2f](https://app.replicas.dev/workspaces/f49f0f2f-3562-485b-97ce-12345c9bffd4) | park — current rungs are 1–2; preserve existing work; call-ID rework deferred | E: 24; B3: 116; B2: 23 | | [#11316](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11316) feat(cost): name the app and the exact key on every moda-problems cost row | B2 | Devin [8b9d9c95](https://app.devin.ai/sessions/8b9d9c95f08d468cb50054067e4427a0); Replicas [3b788ddd](https://app.replicas.dev/workspaces/3b788ddd-00a1-4184-b512-008e2ff4a7de) | adopt — reuse attribution work; normal review gates still apply | B2: 191; B3: 87; B5: 16; C: 17 | | [#11314](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11314) feat(problems): attribute reader cost rows to their run and write per-unit coverage | B2 | Devin [8b9d9c95](https://app.devin.ai/sessions/8b9d9c95f08d468cb50054067e4427a0); Replicas [32e37999](https://app.replicas.dev/workspaces/32e37999-8ee1-422f-94cb-c1281ab19364) | park — current rungs are 1–2; preserve existing work; call-ID rework deferred | E: 102; B3: 391; B2: 683 | | [#11310](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11310) feat(cost): daily Modal container-seconds basis and exact bill allocation views | D | Replicas [2925f2a9](https://app.replicas.dev/workspaces/2925f2a9-f171-491b-ae7b-c9115e4ae12e) | adopt — reuse Modal allocation work; separate migration approval/dev dry run required | architect: 297; D: 795; shared/unassigned: 9 | | [#11309](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11309) feat(cost): wire Modal occupancy into four apps | B2 | Replicas [bbb1e7fa](https://app.replicas.dev/workspaces/bbb1e7fa-1f9a-4ff6-8581-e39c34cae887) | adopt — reuse occupancy code; coordinate D and stagger app canaries | B5: 579; B3: 263; B2: 1753; A: 17; D: 1161 | | [#11308](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11308) feat(cost): account Modal container time by real run, idle and untagged | D | Replicas [a2a12629](https://app.replicas.dev/workspaces/a2a12629-66e6-428b-8a73-9039c7a77379) | adopt — reuse runtime occupancy; D owns most changes, coordinate A | B4: 3; A: 574; D: 1512 | | [#11269](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11269) feat(cost): daily per-credential OpenRouter/OpenRelay bill reconciliation alert | C | Replicas [f28e9548](https://app.replicas.dev/workspaces/f28e9548-cab8-4bb6-9406-afa83105f8ac) | adopt — approved per-key reconciliation alert | shared/unassigned: 58; C: 890; B1: 24 | | [#11265](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11265) feat(cost): give the remaining shared-key apps their own OpenRouter keys and name the credential on every deploy | C | Replicas [a38314e8](https://app.replicas.dev/workspaces/a38314e8-ea68-468e-a01e-4a7576fa9e5e) | adopt — approved per-app key inventory/deploy tooling | single lane | | [#11106](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11106) fix(problems): accept unlimited reader OpenRouter keys | B3 | Replicas [af61eadb](https://app.replicas.dev/workspaces/af61eadb-56cc-4c85-8cf3-d1ac4d4c5499) | adopt — approved reader key work; do not rewrite | B2: 10; B3: 80 | | [#10907](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/10907) feat(billing): unify organization usage balance and automatic reload | F | Replicas [bc1ff23b](https://app.replicas.dev/workspaces/bc1ff23b-7be3-4a76-9f08-bca397a0994f) | adopt, park — existing customer billing is outside provider-close cutover; coordinate B1 | C: 80; shared/unassigned: 1016; F: 1770; B1: 1158; E: 4; B3: 476 | | [#10901](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/10901) feat(inference): freeze customer pricing and charge settlement | B1 | Replicas [bc1ff23b](https://app.replicas.dev/workspaces/bc1ff23b-7be3-4a76-9f08-bca397a0994f) | adopt — preserve inference settlement; coordinate F, outside provider-close cutover | shared/unassigned: 55; F: 130; B4: 8; B1: 380 | | [#8661](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/8661) perf(ask): shared-brain model calls run on OpenRouter's priority tier | B1 | Replicas [2a420b32](https://app.replicas.dev/workspaces/2a420b32-ffa2-4172-84d4-82046d0c6ca4) | adopt — preserve existing priority-tier/cost tests; normal review gates | single lane | | [#7060](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/7060) test(ask): pass provider progress unwrapped through stage timer and cost wrapper | B1 | Replicas [801a6a0d](https://app.replicas.dev/workspaces/801a6a0d-a1e3-4af5-a348-f375fe03d388) | adopt — preserve the existing cost-wrapper test; normal review gates | single lane | | [#4378](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/4378) feat(problems): use Opus 5.5 for Book consolidation | B2 | Replicas [d8d95ac2](https://app.replicas.dev/workspaces/d8d95ac2-1b2b-495c-8549-8a4de4236914) | verify still relevant; rebase or close — very old PR, not automatic adoption | single lane | ## Search exclusions The broad title/branch search also returns non-cost work. These are explicitly excluded, not silently missed: #11049/#10104 are replay-state/screening ledgers or coverage, #7259/#7147 are product task/detection coverage, #6100/#6058/#3267/#3260/#3257/#3255/#3254/#3251/#2588/#2171/#2157/#1974 are pipeline-completion ledger/client cleanup (not financial close), and #4937/#4833 are problem-window/dashboard coverage rather than cost_usage_coverage. Keep their existing owners; this map does not authorize changing them. ## Before any lane resumes 1. The user approved this map and accepted the unchanged frontend deploy exception. Revalidate ownership if PR files change. 2. Assign one active session to each owner lane and stop other writers on the listed PRs. A footer alone is not authorization to push. 3. Adopt approved work rather than open competing replacements. For the six coverage PRs, the owner reworks only the contract mismatch, coordinating/splitting other lane paths before marking the PR. 4. User approval plus a dev dry run is required for every migration, one in flight at a time. Approval of an existing code PR is not blanket migration approval. 5. Refresh this point-in-time map before starting work if PRs/files changed. New cost PRs need an owner before work begins. ## Stop and deletion stack | PR | Owner lane | Current session / author evidence | Disposition and reason | | - | - | - | - | | [#11640](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11640) old-ledger shutdown | E | Merge commit 737d1e3eca author arhamkhan04; session unknown; no further pushes to merged PR | merged — old dispatch/consumer stopped; no rollback to the old path. Deletion follows within days in the same stack; staging drops need user approval and a dev dry run. | | [#11642](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11642) old-ledger retirement | E | Existing lane-E PR; session not refreshed in this ownership correction | depends on architect [#11646](https://app.graphite.com/github/pr/ModaLabs/ModaObservability/11646) landing first. CI planner/load/schema-wait scripts, instrumentation and wiring/retirement tests move from C/D to E because they read or exercise ledger tables. Bill collection and production measured-basis implementations retain C/D ownership. No table drop or deploy is authorized. | Lane D’s per-run/per-conversation bases are parked; tenant Modal/ClickHouse splits remain current work. Only the owning lane pushes, including Replicas fixes. Making cost-lanes required in merge rules needs a repo admin. # Analytics Source: https://docs.moda.dev/dashboard/overview The Analytics page summarizes one agent's health, activity, quality rates, and what needs review over a selected time window. The [Analytics page](https://moda.dev/dashboard/analytics) shows a snapshot of a single agent over a selected time window, with every rate compared against the previous window of the same length. Use it to decide, in one glance, whether anything needs your attention today. The dashboard's Home page contains the [ranked problems view](/dashboard/problems). ## Page controls * **Agent selector** — scopes the whole page to one agent, matched by the agent name in your telemetry. Traces without an agent name are grouped under **Unlabelled / default**. * **Date range** — last 24 hours, 7 days, 30 days, or 90 days, or a custom range. Each metric is compared to the window of equal length immediately before it. * **Refresh** — reloads the snapshot. The page also refreshes automatically every 5 minutes while the tab is visible. The selected agent and window are encoded in the URL, so a filtered view can be shared as a link. > [!NOTE] > > The sections on this page update automatically as new data is analyzed. See [How Moda analyzes traces](/concepts/analysis). ## Agent health A one-line assessment of the selected agent in the selected window, with a state badge: | State | Meaning | | - | - | | Healthy | No active problem or material quality regression in the window. | | Watching | No active problem, but one quality rate is worsening against the previous window. | | Needs attention | Open problems or material detector regressions are present. | | Insufficient data | Issue data or a quality detector could not load for this snapshot, or there are not enough processed traces to assess health. | The **Review issues** link opens [Problems](/dashboard/problems). ## Agent snapshot Three tiles summarize the window: | Tile | What it shows | | - | - | | Activity | Traces in the window (with message and tool-call counts) and the percentage change against the previous window. | | Negative emotion rate | Share of analyzed traces with at least one negative-emotion detection. | | Tool failure rate | Failed tool calls as a share of all tool calls (counted per call). | Hallucinations (agent messages the conversation shows were false, whether replies or messages sent through a tool such as a text or an email, each from a Problems incident the validator kept) are counted, not given as a rate, so they have no tile here: the Home page's **Quality rates** and **Quality rate** widgets show the count. Each quality tile links to the matching tab on the [Signals](/dashboard/signals) page, pre-filtered to the same agent and window. A **Health over time** chart beside Next actions plots each rate for the current window (solid line) and the previous window (dashed line). ## Next actions "What needs review, ranked by impact." A mixed queue of up to four rows: | Row type | What it is | Action link | | - | - | - | | Problem | An open or reopened problem, ranked by affected traces. | Open problem | | Tool regression | A tool failing in more traces than in the previous window. | Inspect signal | | Emotion regression | A negative emotion family detected in more traces than before. | Inspect signal | | Grounding regression | Ungrounded claims rising against the previous window. | Inspect signal | Each row shows the number of affected traces and links directly to the problem or signal view. ## Where the agent is breaking The top failing tools, ranked by affected traces rather than raw call volume. Each row shows the tool name, affected traces, failure rate, and failed-call count, and links to the [Tool Failures tab](/dashboard/signals) filtered to that tool. **View tool failures** opens the full list. ## What the agent handles The top use-case clusters, ranked by linked traces. A trace can belong to more than one use case, so rows may overlap. Each row links to the use-case detail; **View use cases** opens [Clusters](/dashboard/use-cases). This section is empty until the first use-case taxonomy has been built, which requires at least 50 analyzed trace segments. ## Data details A collapsible footer shows when the snapshot was generated, how fresh each data source is (the timestamp each source has data through), and any sources that were unavailable for this snapshot. Rates keep their source-specific denominators, so the tiles are not directly comparable to each other. ## Next steps * [Signals](/dashboard/signals) — drill into the detections behind each quality rate. * [Problems](/dashboard/problems) — work the ranked list of root causes. * [Traces](/dashboard/traces) — inspect individual traces end to end. * [How Moda analyzes traces](/concepts/analysis) — what Moda computes and where each result appears. # Problems Source: https://docs.moda.dev/dashboard/problems Root-cause groups of negative signals with an Open/Reopened/Fixed/Resolved lifecycle and a built-in feedback loop. A problem is a group of negative [signals](/dashboard/signals) — emotion, tool failures, laziness, hallucinations — that Moda attributes to a single root cause. New traces are attributed to existing problems within minutes, and new problems are discovered, ranked, and verified automatically as evidence accumulates. Open **Home** to see what is broken, review the evidence, and record what you fixed or dismissed. ## What the page shows * A **Signals** section with one card per family — tool failures, frustration, laziness, hallucinations — showing negative traces over traces for the window, a sparkline of the selected range against the window before it, and the move in percentage points. One legend names both lines; if the pipeline only has data for part of the previous window, it says where the dashed line starts (for example "30 days before (from Aug 1)"). The diagonal arrow on a card opens that family's tab on the [Signals](/dashboard/signals) page. To rank the problems table by a signal, use the sort control's "By signal" entries. * A ranked table grouped by parent. Each group lists the problems the latest rubric parented under it and starts closed, with a chevron to expand; the group row also says how many problems it holds. Leaves with no parent appear as ordinary rows — no Ungrouped folder. Pagination shows 10 groups or ungrouped leaves at a time. Rows show the problem, users impacted, and one signal number — total signals, or that family's count when the table is ranked by a signal. The sort control and an **Open** / **Fixed** state toggle sit above the table. The sort menu offers users impacted, problems per theme, total signals, and one entry per signal family; every entry has its own highest-to-lowest and lowest-to-highest arrows, and the direction is kept in the URL (`dir=asc`). The time window (1, 7, 30, or 90 days) in the page header applies to the cards and the table together. The cards count traces the Problems pipeline has finished analysing, so the cards, the coverage figures, and the ranked table all describe the same set. ## Lifecycle columns The Board view has four columns. Column position is computed by Moda — dragging records feedback rather than moving cards directly (see below). | Column | Meaning | | - | - | | **Open** | Active root causes. | | **Reopened** | A fix did not hold — set automatically when a problem you marked fixed recurs. | | **Fixed** | Marked fixed; Moda monitors it for recurrence. | | **Resolved** | Dismissed and retired. | ### Drag semantics Dragging a card on the Board submits a feedback action; it never changes the lifecycle immediately: * **Open or Reopened → Fixed** records a *mark fixed*. * **Open, Reopened, or Fixed → Resolved** records a *dismiss*. A reason is required before the drop submits. * **Open** and **Reopened** are not drop targets, and cards cannot be reordered within a column — rank is computed, not user-sorted. After a legal drop the card stays in its source column with a pending marker until the change is applied. Dropping the same action twice while one is pending is blocked. ## Problem detail (Dossier) Clicking a problem on the ranked list opens its full dossier. The full dossier shows the parent theme above the problem title (when the leaf has one), then **Overview** and **Traces** tabs. Overview has impact, a three-stage **causal chain** (Trigger → Faulty behavior → Observable signals), suggested investigation, and change history. Each stage is a compact card (flag, label, title) joined by a straight arrow. Related problems sit in a collapsed footer on Trigger ("Linked problems") and Faulty behavior ("Also observed in"); Observable signals has no footer. There is no separate linked-problems list. Stage cards do not open traces. The parent theme is not repeated on the chain. Every problem is referred to by its name (or its cause statement when it has no name yet) on every surface, including merge and split partners in change history; problem ids never appear in the UI. The **Traces** tab lists traces attributed to this problem. The same list is available through the Data API at [`GET /problems/:id/conversations`](/data-api/problems). Linked cards under a stage open that problem's preview. The Dossier header has an icon-only share control (copies the page link) and a menu to rename or dismiss the problem. ## Feedback actions Feedback is how you steer problem discovery. Every action is recorded immediately, shown as pending, and incorporated automatically — nothing edits the problem definition directly. | Action | Where | What it does | | - | - | - | | **Dismiss** | Dossier overflow menu, or drag to Resolved | Retires the problem. A reason is required and is used as input to the discovery loop. | | **Rename** | Dossier overflow menu | Changes the display name only; the problem's identity is unchanged. | | **Flag attribution** | An Evidence card in the Dossier | Records that a specific trace does not belong to this problem. A reason is required; it becomes a counter-example for discovery. | > [!NOTE] > > Feedback is applied asynchronously. Until it is applied, the dashboard shows a pending state on the affected problem, and duplicate submissions of the same action are collapsed onto the pending one. Feedback can also be submitted through the Data API: [`POST /problems/:id/feedback`](/data-api/problems). ## Next steps * [Signals](/dashboard/signals) — the per-trace detections that problems are built from. * [Problems in the Data API](/data-api/problems) — read problems, evidence, and reports, and submit feedback programmatically. * [Analysis](/concepts/analysis) — how problems relate to every other computed result. ## Investigate a problem by use case Open a [use case](/dashboard/use-cases) to see its **Surfaced problems**, with distinct affected traces and affected share of analyzed traffic. Select a problem to open its existing dossier and investigate or manage its lifecycle. Lifecycle and fix actions apply to the problem globally. Affected share measures attributed evidence, not task success or failure. Use cases may overlap, so their counts and percentages cannot be added. The recurrence view compares current evidence under the same classification; it is not a frozen record of what earlier dashboard views displayed. # Signals Source: https://docs.moda.dev/dashboard/signals Per-trace user emotion and tool-failure detections, with KPIs, taxonomies, and evidence links, and where to find laziness and hallucinations. A signal is an automatic per-trace detection: expressed user emotion, a failed tool call, an effort shortfall, or a false statement to the user. The Signals page (sidebar: Observe → Signals) is where you browse user emotion and tool failures. Laziness and hallucinations are not on this page; see [Laziness and hallucinations](#laziness-and-hallucinations) for where they appear. Detections run in the background after ingest: emotion analysis once a trace has been quiet for about 30 minutes, and tool-failure classification about an hour after it goes quiet. Tool calls themselves are recorded as they arrive. ## Page controls * **Date range** — Last 24 hours, 3, 7, 14, 30, or 90 days, or a custom range. * **Refresh** — reloads the active tab. * **Tabs** — User Emotion, Tool Failures. The active tab is addressable via the `type` URL parameter (`emotion`, `tool-failures`), and each tab supports its own deep-link parameter: `family` (User Emotion) and `tool` (Tool Failures). ## User Emotion Detects emotion expressed in the user's own messages, classified into 7 families and 17 signals: five negative families, one positive family, and Redirection, which is neither (see [Emotion taxonomy](#emotion-taxonomy)). Every analyzed trace counts toward the KPIs; the table lists traces with at least one detection or a negative-family risk score of 0.5 or higher. KPIs: | KPI | Meaning | | - | - | | Negative rate | Share of units with at least one negative-family detection (Frustration, Sadness, Confusion, Anxiety or Trust). Redirection and Positive detections never count. The unit is a user turn by default; you can switch it to task or trace. | | Affected users | Users with at least one negative reaction in the window. | Below the KPIs, a strip counts detections per emotion family, Redirection and Positive included; select a family to filter the list (`?family=`, which takes the stored key, so Redirection is `?family=disapproval`). Rows carry a status of **Detected** when the trace has a negative-family detection, and **Positive** otherwise, including traces whose only detection is Redirection; **Detected only** leaves those out. The **Confidence** column is the detector's 0 to 1 confidence for the strongest emotion in the row, judged from the user's own words; higher means a stronger detection of that emotion, not a happier user (a `distrust` row at 1.00 is strongly distrustful). Rows with nothing detected have no confidence and show their risk score instead, labelled `risk`. This is unrelated to the 0 to 100 health score on the [Users page](/dashboard/users-and-tools). Filter by status (All statuses / Detected only), family, elicitor, and trajectory; sort by confidence, risk, last seen, or message count, in either direction; search by trace ID or cause. Opening a row shows the cause, trajectory, elicitor, and verbatim user quotes — each quote links into the trace's [Timeline](/dashboard/traces) at the quoted turn. ### Emotion taxonomy | Family | Signals | Polarity | | - | - | - | | Frustration | `exasperation`, `anger`, `profanity`, `insult`, `sarcasm`, `escalation_request` | Negative | | Sadness | `disappointment`, `resignation`, `self_blame`, `personal_distress` | Negative | | Confusion | `confusion` | Negative | | Anxiety | `urgency` | Negative | | Trust | `distrust` | Negative | | Redirection | `disapprove`, shown as "redirect" | Neither: never counts toward the negative rate | | Positive | `gratitude`, `satisfaction`, `delight` | Positive | Redirection is a calm rejection of something the agent produced or proposed, with no annoyance in it ("no, not that one", "I don't like the ending"). A plain edit request such as "make it shorter" is not Redirection; a rejection with heat is Frustration. The stored keys are `disapproval` (family) and `disapprove` (signal), so filters, the Data API and the CLI use those names. Each detection also records: * **Elicitor** — what elicited the emotion: `bot`, `external`, `self`, or `ambiguous`. * **Trajectory** — how it evolved across the trace: `none`, `building`, `peak`, `resolved`, or `sustained`. * **Confidence** (0 to 1, from expressed evidence only) and **risk score** (0 to 1, likelihood from all signals including observed ones; negative families only, so Redirection and Positive carry none), a primary cause, and supporting quotes. ## Tool Failures "Tool invocations that returned errors or failed to execute." Tool calls are recorded at ingest and then classified into outcomes and named failure categories per tool. The failure list and `moda detections tools` count classified failures. The Signals failure-rate KPI is **classified failures / recorded tool receipts** (`side_effect_receipts`); `moda detections tools` divides classified failures by classified events. The Tools catalog and `moda tools` measure receipt success, so these rates can differ. KPIs: **Total Failures**, **Failure rate** (per tool call by default; you can switch it to per turn, task or trace), and **Tools Impacted**. A **Failures over time** chart plots failure events (stacked or grouped), and a per-tool drill-down is deep-linkable with `?tool=`. Each failure category carries: | Field | Meaning | | - | - | | Category label | Short name for this kind of failure. | | Family | The broader failure family the category belongs to. | | General error | A description of the underlying error. | | Likely cause | The probable cause of the failures in this category. | | Recommended action | A suggested fix. | Individual failure events link into the trace at the failed call. Tool-level success rates and usage live on the [Tool Catalog page](/dashboard/users-and-tools). ## Laziness and hallucinations Moda still detects laziness and hallucinations, but the Signals page has no tab for them. Laziness is checked on every trace. Hallucinations come from the Problems reader, so in a workspace set to analyze a sample of its traces, only the sampled traces are checked. Emotion analysis and tool-failure classification follow the same sample. You'll find them here: | Detection | What it flags | Where to find it | | - | - | - | | Laziness | Agent effort shortfalls: omitted or stubbed code, deflecting the work to the user, promised actions with no tool call, claimed inability to do what its tools allow, and stalling. Runs once a trace has been quiet for about 30 minutes. | Alerts (the built-in **Laziness** signal), laziness rates and KPI tiles in [`GET /trends`](/data-api/analytics), and the CLI's [`moda traces findings`](/cli/reference#moda-traces-findings) and `moda detections list --family=laziness`. | | Hallucinations | An agent message that told the user something the trace shows is false, kept by the Problems incident validator. Written about an hour after the trace's last message. | The [problem](/dashboard/problems) its incident belongs to, alerts (the built-in **Hallucinations** signal), [`GET /hallucinations`](/data-api/signals), and `moda detections list --family=hallucination`. | See [Analysis](/concepts/analysis) for how each detection works. ## Next steps * [Problems](/dashboard/problems) — signals grouped by root cause and ranked by impact. * [Home](/dashboard/overview) — the same quality rates as at-a-glance KPIs. * [Traces](/dashboard/traces) — where every signal's evidence links land. * [Data API: signals](/data-api/signals) — query emotions, tool failures, and hallucinations programmatically. * [Analysis](/concepts/analysis) — how each detection works, including laziness and hallucinations. # Traces Source: https://docs.moda.dev/dashboard/traces Browse every ingested trace, and inspect a single trace as a full message timeline or as its extracted world state. Traces (sidebar: Observe → Traces) lists every trace Moda has ingested and is the entry point for inspecting a single agent run turn by turn. A trace is the full record of one agent run — every message, tool call, thinking block, and step that shares one `conversation_id` (the trace ID) — whether or not a human was in the loop. New traces appear within seconds of sending data; analysis results attached to them (use case, world state, signals) fill in within minutes. ## Trace list The list supports: * **Search** — the "Search traces..." box filters the list. * **Filters** — environment (Production / Development / Staging) and use case. * **Time range** — All time, Last 24 hours, or Last 30 days. * **Sort** — Newest first, Oldest first, Most messages, Fewest messages. * **Pagination** — page sizes 10 / 25 / 50 / 100 with Previous / Next; the total count loads separately. The first page refetches automatically every 15 seconds while the tab is visible, so new traces stream in without a manual refresh. Filters, sort, and page size are reflected in the URL, so a filtered view can be shared as a link. Arriving from a user's detail page pre-filters the list to that user; a chip above the table clears the filter. ### Columns The **Columns** button shows or hides columns; column widths can be dragged. Preferences are saved in your browser. | Column | Shows | Visible by default | | - | - | - | | Trace | Preview of the first message text. | Yes | | Processed | Whether processing has completed (Processed / Unprocessed). | Yes | | Env | Environment badge (Prod / Dev / Staging). | Yes | | Messages | Message count. | Yes | | Use case | The assigned use-case cluster. | Yes | | Last active | Time of the most recent message. | Yes | | Trace ID | The full trace ID (the `conversation_id` value). | No | | Use case confidence | Membership score for the use-case assignment. | No | | First active | Time of the first message. | No | | Indexed | When Moda first indexed the trace. | No | | Processing | Processing status badge. | No | | World state | World-state build status: Ready when built, Stale when out of date, otherwise the in-progress status (Pending by default). | No | Clicking a row opens the trace detail in a new tab. ## Trace detail The header shows the trace ID, date, duration, and turn count, plus badges when they apply: a frustration score (shown when the score is 5 or higher), the tool-failure count, and the use case with its confidence. Previous / next links step through neighboring traces. A toggle switches between the two views: **Timeline** and **World State**. While a trace is still mostly unprocessed, a strip lists the pending pipeline stages (`segmentation`, `world-state`, `cluster`, `frustration`); it disappears once most stages have completed. ### Timeline Timeline is the raw record of the run: every message and content block in order. Each row shows content appropriate to its type: * **User messages** — the message content, rendered as markdown. * **Agent responses** — the model and provider above the response text. * **Thinking** — collapsed to a single expandable line. * **Tool calls** — expandable input and result; failed calls are highlighted. Every message has a copy button on hover. Messages that changed the tracked world state carry event chips; selecting a turn opens an inspector for that turn's state changes. A filter rail on the left toggles block categories — Prompts, Agent Responses, Thinking, Tool Calls (with per-tool sub-filters), Images, Email, Call Transcripts — each with a count, plus **Clear Filters**. When the trace carries signals, context banners appear above the timeline: * **Tool Call Failure** — the tool name and error, with **Jump to failure**. * **User Frustration Detected** — the score, trajectory, and primary cause, with clickable quotes that jump to the quoted turn. Evidence links from [Signals](/dashboard/signals) and [Problems](/dashboard/problems) open the Timeline scrolled to the relevant turn or failed tool call. ### World State World State shows what Moda extracted from the trace: the tasks the user pursued and the facts established along the way. It has two tabs. **Tasks** lists the trace's task threads with a resizable detail pane. Each thread has a status (Open / Resolved / Cancelled) and can contain subtasks (Open / Done / Blocked / Cancelled). The detail pane shows a progression timeline of actions — Message, Tool call, Correction, Subtask opened, Subtask completed, Failure, Retry — and each step can jump back to the matching turn in the Timeline. **Facts** lists the facts extracted from the trace; when the position is known, each fact is tagged with the turn where it was established. Both tabs are searchable ("Search threads" / "Search facts"); Tasks additionally supports filtering by thread status, subtask status, and action type, and sorting by Most recent turn, Status, or Title (A→Z). While the build is in progress, a "Still building world state" banner shows partial results and updates live. ## OpenTelemetry span viewer A standalone span viewer exists at `https://moda.dev/trace/`. It renders the OpenTelemetry span tree for one OTLP trace ingested over `/v1/traces`, with a span detail pane, and supports a `?span=` parameter to deep-link a specific span. It is auth-gated and not linked from the sidebar — open it by URL when you have an OpenTelemetry trace ID. This is the per-call span view; the Traces page above is the run-level view. ## Next steps * [Signals](/dashboard/signals) — the detections that produce the banners and badges on trace pages. * [Clusters](/dashboard/use-cases) — the clusters behind the Use case column. * [Data API: traces](/data-api/traces) — fetch traces and world state programmatically. # Clusters Source: https://docs.moda.dev/dashboard/use-cases A hierarchical taxonomy of what users ask your agent, kept current automatically and browsable down to individual traces. The Clusters page shows what your users actually ask the agent to do, organized as a hierarchy: broad **user areas** at the top, specific **user goals** as leaves. Open **Observe → Clusters** to see where trace volume concentrates, how each use case is trending, and which traces belong to each node. ## How the taxonomy is built Moda splits each trace into segments — contiguous stretches of one user goal — and clusters segments into the hierarchy. Each node carries a label, a description, keywords, and trace counts. * The first taxonomy for a workspace is built once at least **50 analyzed segments** exist. Before that, the page shows the empty state "No task clusters yet". * New segments are assigned to the existing taxonomy as they are analyzed, so counts stay current. * The hierarchy itself is rebuilt automatically as your traffic shifts — you never configure or trigger it. Segments that match no existing use case are held aside and grouped into new nodes at the next rebuild, so a genuinely new use case becomes visible once that rebuild has run. ## What the page shows Two view modes over the same hierarchy: * **Overview** — a ranked list of use cases with label, description, child-goal count (or "Leaf use case"), trace count, share of total, and trend. * **Browse** — the task tree side by side with an inspector pane for the selected node. A search box matches across the whole hierarchy, and a time range control scopes counts to All time, Last 3 days, Last 7 days, or Last 30 days. ## Drill into a use case Click a node to open its detail page. The header shows whether it is a **User area** (branch) or a **User goal** (leaf), plus a **Traces** metric and — when enough data exists — **Recent trend** and **Signals to review**. * **View traces** jumps to the **Representative traces** section: sampled real traces for this node, each opening in a new tab, with a load-more control. * **Goals within \** breaks a branch node down into its child goals. * **What to investigate next** lists health signals detected inside this use case, each with a link to the evidence. * **Related goals** and **Related terms** in the sidebar show nearby nodes and the vocabulary users employ for this use case. You can also filter the [Traces list](/dashboard/traces) by use case cluster, and the [Home page](/dashboard/overview) shows the top use cases in its "What the agent handles" section. ## Use cases in the API The same hierarchy is available through the Data API: [`GET /clusters`](/data-api/analytics) returns the taxonomy and `GET /clusters/:nodeId/conversations` returns a node's traces. ## Next steps * [Traces](/dashboard/traces) — filter the trace list by use case cluster. * [Analysis](/concepts/analysis) — how segmentation and clustering fit into the rest of the pipeline. ## Problems affecting a use case Open a use case to see its attributed problems, ranked by affected traces. Choose affected users or affected share to change the ranking, and switch between open/reopened problems and fixed/resolved problems. The inspector and focused Overview show a compact preview of the top three open problems, with a link to the full list on the use-case detail page. Affected share divides distinct affected traces by traces with problem analysis in this use case. Coverage counts show how much of the traffic and its matching segments have been analyzed. An unavailable rate means there is no analyzed population; it does not mean the use case is healthy. Embedded panels follow the page's time range, including **All time**. On the use-case detail page, **Traces** opens matching evidence at its exact turn and **Recurrence** shows daily affected share across the selected and preceding windows. All-time recurrence covers available history without a previous comparison window. These results use the current classification and can change when use cases are regenerated. Select a problem to open its existing dossier and manage it there. # Users and Tool Catalog Source: https://docs.moda.dev/dashboard/users-and-tools Per-user health and activity history, and an inventory of every tool your agent calls with effect classification and per-tool success rates. Two inventories are built entirely from ingested traces, with nothing to configure: **Users** (who is using your agent and how it is going for them) and the **Tool Catalog** (every tool the agent calls and how often its calls succeed). ## Users Open **Observe → Users**. Users are keyed by the user ID you attach to ingested events, so the page fills in once traces arrive with user IDs set (see [Ingestion overview](/ingestion/overview)). User aggregates refresh hourly. ### User list * KPIs: **Total Users**, **Active 7d**, **At Risk**, **Avg Health**, plus charts for active users over time and the health-score distribution. * Cohort pills filter the list: power users, heavy tool users, frustrated, at risk, new this week, and silent sufferers. Clicking an active cohort clears it. * Search matches user IDs; wrap a term in double quotes (`"user_123"`) for an exact match. * Time window presets: Last 24h, 7d, 30d, 90d. * Table columns: User, Traces, Health, Score, Top Intent, Signal, Last Seen. Page sizes 10/25/50/100 with numbered pagination. ### Health score Each user carries a health score from 0 to 100 for the selected window, shown in the **Score** column and in the detail page header. It reflects how many of the user's traces went wrong, weighted by how badly. Each trace takes a penalty, capped at 1, from what was detected in it: 0.6 for frustration, 0.3 for laziness, 0.2 for a problem found in the trace's context, 0.15 for confusion, disapproval, anxiety, sadness or distrust, and 0.1 per failed tool call, up to four. The score is 100 × (1 − total penalty ÷ (traces + 1)), kept between 0 and 100. The extra trace in the divisor acts as one clean trace, so a single bad trace scores 50, not 0. A hallucination counts when it surfaces as a [Problem](/dashboard/problems); a contradicted claim on the [Signals page](/dashboard/signals) does not lower the score on its own. The **Health** column is a band on that score: **Healthy** at 70 or above, **At Risk** from 40 to 69, and **Frustrated** below 40. This is a different number from the 0 to 1 **Confidence** on the Signals page, which measures how strongly the detector saw a given emotion, not how the user is doing. ### Per-user history Click a user to open their detail page (fixed 30-day window): * Header with identity and health status, and a stats row: **Traces**, **Turns**. * **Callouts** — notable findings for this user, such as behavior concentration and frustration trajectory. * **Intent distribution** and **Frustration trajectory** charts. * An **Activity feed** of the user's traces with a load-more control; each row opens the full trace. ## Tool Catalog Open **Harness → Tools**. Every tool call in ingested traces produces a record within seconds, so the catalog is close to real time. ### Tool inventory * Search by tool name, filter by effect or by outcome (has failed calls, or all calls succeeded), and pick a time range from Last 24 hours to Last 90 days. * Columns: Tool name, Calls, Success, Traces, Effect, System, Last seen. Sort by Calls, Success, Traces, or Last seen. ### Effect classification Each tool is classified by the kind of effect it has: | Effect | Meaning | | - | - | | **Read** | Retrieves data without changing anything (searches, fetches, lookups). | | **Write** | Creates, updates, or deletes state (files, records, database rows). | | **Send** | Delivers something outward (messages, emails, posts, remote transfers). | | **Spawn** | Starts another process or agent (launch, delegate, run). | | **Compute** | Runs computation without a lasting side effect (scripts, package commands). | Tools whose effect cannot be determined show `?`. ### Tool detail Clicking a tool opens its detail page: * **What the model reads** — the tool's registered description, when one is registered. * **Input parameters** — registered parameters merged with parameters observed in real calls, with types, call percentages, and common values. * **Common uses** — what the agent uses the tool for. ### Failure stats The **Success** column is each tool's share of recorded tool receipts that succeeded. Signals → Tool Failures counts classified failures and divides by recorded receipts for its KPI. `moda detections tools` divides classified failures by classified events. These rates can differ from the catalog. For failure *categories* — what kind of error, the likely cause, and a suggested action — use [Signals → Tool Failures](/dashboard/signals), or the Data API's [`GET /tool-failures`](/data-api/signals) and `GET /tool-failures/:toolName`. ### From the CLI or the Data API The same catalog is available over an API key: `moda tools list` and `moda tools get ` in the [CLI](/cli/reference#moda-tools-list), or [`GET /tools`](/data-api/signals#get-tools) and `GET /tools/:name`. Both read the same queries as this page, and `GET /tools/:name` also returns the top failure categories and the registered schema. ## Next steps * [Signals](/dashboard/signals) — tool-failure categories, emotion, laziness, and hallucination detections. * [Traces](/dashboard/traces) — the trace detail page and its World State view. * [Ingestion overview](/ingestion/overview) — how to attach user IDs so the Users page populates. # Analytics Source: https://docs.moda.dev/data-api/analytics GET /overview for headline KPIs, /clusters for the use-case hierarchy, and /task-clusters/search for finding cluster nodes. These endpoints read tenant-level aggregates: the headline KPIs shown on the dashboard home page and the hierarchical use-case clusters. New traces are assigned to existing clusters continuously; the hierarchy itself is rebuilt automatically as traffic evolves, and new cluster nodes appear once a rebuild has run. ## GET /overview Headline KPIs for a window, plus top clusters and recent activity. ### Query parameters **days_back** `integer` (default: 7) 1–90. Applies to the trace, frustration, and tool-failure KPIs, and to recent activity. ### Response fields **period** `object` `{days}` — the effective window. **conversations** `object` Trace counts: `total` in the window and `trend_pct` — percentage change versus the previous window of equal length (one decimal; `0` when the previous window was empty). **frustrations** `object` `total_analyzed`, `frustrated`, `at_risk` (risk score at least 0.5 but not frustrated), `rate_pct`. **tool_failures** `object` `total` (failed calls), `conversations` (traces with a failure), `tools`. **top_clusters** `array` Up to 10 clusters from the latest clustering run, largest first: `node_id`, `label`, `summary`, `keywords[]`, `segment_count`. **recent_activity** `array` Up to 10 most recent trace summaries updated within the last `days_back` days (7 by default): `conversation_id`, `summary`, `timestamp`. The window and `timestamp` use the rollup’s `updated_at` time. ### Example ```bash theme={"dark"} curl "https://moda.dev/api/v1/data/overview?days_back=30" \ -H "x-api-key: YOUR_MODA_API_KEY" ``` ```json theme={"dark"} { "period": { "days": 30 }, "conversations": { "total": 5417, "trend_pct": 8.2 }, "frustrations": { "total_analyzed": 4903, "frustrated": 171, "at_risk": 64, "rate_pct": 3.5 }, "tool_failures": { "total": 240, "conversations": 188, "tools": 9 }, "top_clusters": [ { "node_id": "node_3", "label": "Billing and refunds", "summary": "Users ask about invoices, plan changes, and refunds.", "keywords": ["refund", "invoice", "billing"], "segment_count": 812 }, { "node_id": "node_17", "label": "Integrations setup", "summary": "Users connect calendars, CRMs, and ticketing tools.", "keywords": ["oauth", "connect", "integration"], "segment_count": 655 } ], "recent_activity": [ { "conversation_id": "conv_9f2c41d08ab37e51", "summary": "User asks how to request a refund for an annual plan; agent explains the policy and opens a ticket.", "timestamp": "2026-08-14T09:42:11" } ] } ``` ## GET /trends The dashboard's KPIs for a window against the window of equal length just before it, from the same loaders as the Analytics overview, the Signals rate cards, the detector KPI tiles and the Problems trend card. With `since` set to a deploy time, the response compares the time since the deploy with the same length of time before it. `moda overview --compare` and `moda detections list --compare` read this endpoint. ### Query parameters | Parameter | Type | Default | Description | | - | - | - | - | | `days_back` | integer | 7 | Window ending now (1–90). Not with `since`/`until`. | | `since` | string | — | Window start: ISO 8601 date or datetime, UTC unless an offset is given. | | `until` | string | now | Window end, inclusive. Needs `since`. The window can span up to 90 days. | | `agent` | string | — | One sub-agent name (from `agent.options`). Scopes the `overview` section only; `problems`, `rates` and `detectors` are left out because their loaders have no agent filter. Cannot be combined with `family`. | | `unit` | string | `conversation` | Denominator of `rates`: `conversation`, `segment` or `turn`. | | `include` | string | all | Comma-separated sections: `overview`, `problems`, `rates`, `detectors`. `problems` needs `days_back`. | | `family` | string | — | One detector family (`emotion[:]`, `frustration`, `tool_failure`, `laziness[:]`, `hallucination`): only its detector KPIs and rate. `frustration` and sub-families return only that family's traces under `detectors` and leave out `rates`, whose cards count the whole detector. | | `series` | string | `0` | `1`: add `series`, `[bucket, value]` arrays per hour (windows up to 2 days) or per day. | ### Response fields Every figure is `{ current, previous, delta, delta_pct, spike? }`. `delta` is current minus previous (percentage points for a `_pct` rate), `delta_pct` the relative change in percent, and `spike` (present only when true) the dashboard's spike rule. | Field | Description | | - | - | | `window` | `from`, `to`, `previous_from`, `previous_to`, `days`, `bucket` (`hour` or `day`). | | `agent` | `selected` and `options` (`agent`, `label`, `conversations`), as the Analytics agent selector lists them. | | `overview` | `conversations`, `messages`, `negative_emotion_rate_pct` (per analyzed trace), `tool_failure_rate_pct` (failed tool calls per call), `hallucinations` (a count of hallucinations: agent replies the conversation shows were false, never a rate); rates carry `of` and `n` (numerator and denominator per window). | | `problems` | `window` (the loader's own bounds: its current window starts at a bucket boundary, so it can run longer than the previous one; a note gives both spans), `analysed_traces`, `traces_with_signal`, `signal_rate_pct` (the Problems trend card). | | `rates` | `unit`, `units`, `comparable`, and `_pct` with `flagged` for emotion, tool_failure, laziness, hallucination. When `comparable` is false (segment retention does not reach the previous window), `delta` and `delta_pct` are null. | | `detectors` | KPI tiles per family: `emotion` (conversations_analyzed, negative_rate_pct, negative_detections, affected_users, traces_by_family), `tool_failure` (failed_traces, failures, failure_rate_pct, tool_calls, users_impacted, tools_impacted), `laziness`, `hallucination`. | | `series` | With `series=1`: `bucket`, then one `[bucket, value]` array per figure. | | `notes` | Sections left out and why. | ### Example ```bash theme={"dark"} curl "https://moda.dev/api/v1/data/trends?since=2026-10-17T14:00:00Z&include=overview,rates" \ -H "x-api-key: $MODA_API_KEY" ``` ```json theme={"dark"} { "window": { "from": "2026-10-17T14:00:00.000Z", "to": "2026-10-18T14:00:00.000Z", "previous_from": "2026-10-16T14:00:00.000Z", "previous_to": "2026-10-17T14:00:00.000Z", "days": 1, "bucket": "hour" }, "overview": { "conversations": { "current": 1104, "previous": 1180, "delta": -76, "delta_pct": -6.4 }, "tool_failure_rate_pct": { "current": 1.31, "previous": 1.24, "delta": 0.07, "delta_pct": 5.4, "of": "tool receipts (one row per call)", "n": { "current": [173, 13243], "previous": [239, 19282] } } }, "rates": { "unit": "conversation", "units": { "current": 1104, "previous": 1180, "delta": -76, "delta_pct": -6.4 }, "comparable": true, "emotion_pct": { "current": 32.1, "previous": 31.4, "delta": 0.7, "delta_pct": 2.4, "flagged": 354 } } } ``` ## GET /clusters Browses the hierarchical use-case clusters from the latest completed clustering run. Call it without parameters for the root level; pass a node's `node_id` as `parent_id` to descend. ### Query parameters **parent_id** `string` Return the children of this node. Omit for root-level nodes. The response's `breadcrumb` traces the path from the root to this node. **time_range** `string` (default: all) One of `all`, `1h`, `24h`, `3d`, `7d`, `30d`, `90d`. The hierarchy always comes from the latest clustering run. With a window other than `all`, each node's `segment_count` counts only the run's segments whose trace was last active in the window, nodes with no such segments are left out, and `meta` counts the window. **cohort** `string` `builtin:` or a saved cohort id: only the nodes the cohort's users reach, each `segment_count` the cohort's segments over the Topics tree window (`time_range` must be `all`, `3d`, `7d` or `30d`), as the dashboard Topics page counts a cohort. `meta.cohort_clusters` and `meta.cohort_segments` describe this level; `total_clusters` and `total_segments` stay the whole run. The cohort's membership snapshot is refreshed first when it is missing or stale, as the dashboard does; an unknown saved cohort id returns `404`, and the response echoes `cohort`. ### Response fields **cluster_run** `object | null` The latest completed run: `id`, `num_categories`, `num_clusters`, `num_segments`, `completed_at`. `null` when no taxonomy exists yet — the first one is built once at least 50 analyzed segments exist. Always describes the whole run, whatever `time_range` is. **breadcrumb** `array` `{node_id, label}` path from the root to `parent_id`. Empty when `parent_id` is omitted. **clusters** `array` Child nodes ordered by size: `node_id`, `label`, `summary`, `keywords[]`, `node_type`, `segment_count`, `has_children`, `depth`. **meta** `object` `total_clusters` (nodes of type `cluster`; categories are not counted) and `total_segments` (each segment counted once), plus `time_range` and `windowed`. With `time_range=all` they match `cluster_run.num_clusters` and `cluster_run.num_segments`; with a window they count only clusters and segments in the window. ### Example ```bash theme={"dark"} curl "https://moda.dev/api/v1/data/clusters?parent_id=node_3" \ -H "x-api-key: YOUR_MODA_API_KEY" ``` ```json theme={"dark"} { "cluster_run": { "id": "v2_7f3d92e4-51b8-4c26-9a07-d1e5f2b8c634_20260809_020001_4e9a1c7b", "num_categories": 12, "num_clusters": 84, "num_segments": 10231, "completed_at": "2026-08-09T02:41:05" }, "breadcrumb": [ { "node_id": "node_3", "label": "Billing and refunds" } ], "clusters": [ { "node_id": "node_47", "label": "Refund requests", "summary": "Users ask for full or partial refunds.", "keywords": ["refund", "money back"], "node_type": "cluster", "segment_count": 388, "has_children": false, "depth": 1 }, { "node_id": "node_58", "label": "Invoice questions", "summary": "Users ask for invoices or billing history.", "keywords": ["invoice", "receipt"], "node_type": "cluster", "segment_count": 262, "has_children": false, "depth": 1 } ], "meta": { "total_clusters": 84, "total_segments": 10231, "time_range": "all", "windowed": false } } ``` ## GET /clusters/:nodeId/conversations Lists traces whose segments belong to one cluster node. > [!NOTE] > > An unknown `nodeId` returns `200` with `cluster: null` and an empty `conversations` array — not `404`. Check `cluster` before reading the list. ### Query parameters **limit** `integer` (default: 10) 1–100. **offset** `integer` (default: 0) 0–10,000. ### Response fields **cluster** `object | null` `node_id`, `label`, `summary`, `segment_count` — or `null` when the node does not exist in the latest run. **conversations** `array` One row per trace: `conversation_id`, `summary`, `message_count`. **pagination** `object` `limit`, `offset`, `total`, `has_more`. ### Example ```bash theme={"dark"} curl "https://moda.dev/api/v1/data/clusters/node_47/conversations?limit=2" \ -H "x-api-key: YOUR_MODA_API_KEY" ``` ```json theme={"dark"} { "cluster": { "node_id": "node_47", "label": "Refund requests", "summary": "Users ask for full or partial refunds.", "segment_count": 388 }, "conversations": [ { "conversation_id": "conv_9f2c41d08ab37e51", "summary": "User asks how to request a refund for an annual plan; agent explains the policy and opens a ticket.", "message_count": 18 }, { "conversation_id": "conv_77e0b3a94c12f8d6", "summary": "User requests a partial refund after downgrading mid-cycle.", "message_count": 9 } ], "pagination": { "limit": 2, "offset": 0, "total": 341, "has_more": true } } ``` ## GET /task-clusters/search Searches cluster nodes in the latest hierarchy by name or meaning. Use it to resolve a phrase like "refund requests" to a `node_id` you can pass to `/clusters/:nodeId/conversations` or the `cluster_id` filter on [`/conversations`](/data-api/traces). ### Query parameters **q** `string` Search text, 2–200 characters. Required unless `node_id` is given. **node_id** `string` Deterministic lookup of one node (returns that node with its ancestor path). Makes `q` optional. **mode** `string` (default: hybrid) `fuzzy`, `semantic`, or `hybrid`. **limit** `integer` (default: 30) 1–50. **cohort** `string` `builtin:` or a saved cohort id. Only nodes reached by the cohort's users are searched (before ranking and `limit`), and each match's `segment_count` counts the cohort's segments. With `node_id`, a node the cohort does not reach returns no match. The cohort's membership is refreshed first when it is missing or stale; an unknown saved cohort id returns `404`. **time_range** `string` (default: all) With `cohort`: the window the cohort's topics and counts cover, matching the Topics tree. One of `all`, `3d`, `7d`, `30d`. A topic the cohort reached only outside the window is not returned. ### Response fields **clusterRunId** `string | null` The run the matches came from. `null` (with empty `matches`) when no clustering run exists yet. **search_mode** `string` The mode that actually served the request. Falls back to `fuzzy` when semantic search is unavailable. **matches** `array` Each match has `node_id`, `parent_id`, `depth`, `node_type`, `label`, `description`, `keywords[]`, `segment_count`, `ancestor_path[]` (`{nodeId, label, depth}` from the root), `path_truncated`, and `similarity` (semantic/hybrid matches only). ### Example ```bash theme={"dark"} curl "https://moda.dev/api/v1/data/task-clusters/search?q=refunds&limit=1" \ -H "x-api-key: YOUR_MODA_API_KEY" ``` ```json theme={"dark"} { "clusterRunId": "v2_7f3d92e4-51b8-4c26-9a07-d1e5f2b8c634_20260809_020001_4e9a1c7b", "query": "refunds", "search_mode": "hybrid", "matches": [ { "node_id": "node_47", "parent_id": "node_3", "depth": 1, "node_type": "cluster", "label": "Refund requests", "description": "Users ask for full or partial refunds.", "keywords": ["refund", "money back"], "segment_count": 388, "ancestor_path": [ { "nodeId": "node_3", "label": "Billing and refunds", "depth": 0 } ], "path_truncated": false, "similarity": 0.83 } ] } ``` ## Next steps * [Traces](/data-api/traces) — filter the trace list by `cluster_id`. * [Dashboard: Clusters](/dashboard/use-cases) — the same hierarchy in the dashboard, including how the taxonomy is built. * [Problems](/data-api/problems) — ranked root-cause problems across signals. # Data API overview Source: https://docs.moda.dev/data-api/overview Read traces, signals, clusters, and problems over HTTP with an API key — the same data the dashboard shows. The Data API exposes the analytics Moda computes over your ingested traces as HTTP endpoints. A trace is one full agent run, identified by its `conversation_id` (the trace ID); endpoint paths and JSON fields keep the `conversation` / `conversation_id` names for backwards compatibility. It serves the same data as the dashboard, so you can use it from CI jobs, coding agents, and scripts. The [Moda CLI](/cli/overview) is built on this API. ## Base URL ``` https://moda.dev/api/v1/data ``` ## Authentication Every endpoint requires an API key (called an ingestion key in the dashboard) in the `x-api-key` header: ``` x-api-key: moda_sk_... ``` Keys are created at **Settings → Ingestion keys** and are shown once at creation. A key is bound to one tenant; every response is scoped to that tenant. See [Authentication](/administration/authentication) for key management. > [!WARNING] > > The Data API and the [Ingestion API](/ingestion/http-api) accept the same `moda_sk_` keys but read different headers. The Data API reads `x-api-key`; the Ingestion API reads `Authorization: Bearer`. A key sent in the wrong header returns `401`. CLI session tokens are not valid here. A missing key returns `401` with `"message": "API key is required"`; an invalid or revoked key returns: ```json theme={"dark"} { "message": "Invalid or revoked API key", "error": "Unauthorized", "statusCode": 401 } ``` To check a key without reading any analytics, call `GET /whoami`. It returns the tenant the key acts on and the key's kind and scope: ```json theme={"dark"} { "tenant_id": "6f1c2d9e-...", "tenant_name": "Acme", "tenant_slug": "acme", "api_key_id": "2b7e...", "key_kind": "tenant", "scope": "full", "read_only": false } ``` ## Make your first request ```bash theme={"dark"} curl "https://moda.dev/api/v1/data/overview?days_back=7" \ -H "x-api-key: YOUR_MODA_API_KEY" ``` ```json theme={"dark"} { "period": { "days": 7 }, "conversations": { "total": 1284, "trend_pct": 12.5 }, "frustrations": { "total_analyzed": 1102, "frustrated": 43, "at_risk": 18, "rate_pct": 3.9 }, "tool_failures": { "total": 67, "conversations": 51, "tools": 6 }, "top_clusters": [ { "node_id": "node_3", "label": "Billing and refunds", "summary": "Users ask about invoices, plan changes, and refunds.", "keywords": ["refund", "invoice", "billing"], "segment_count": 214 } ], "recent_activity": [ { "conversation_id": "conv_9f2c41d08ab37e51", "summary": "User asks how to request a refund for an annual plan; agent explains the policy and opens a ticket.", "timestamp": "2026-08-14T09:42:11" } ] } ``` The full `/overview` reference is on the [Analytics](/data-api/analytics) page. ## Common query parameters Most endpoints accept a subset of these parameters: | Parameter | Type | Values | Notes | | - | - | - | - | | `days_back` | integer | 1–90 | How far back to aggregate. Values above 90 are clamped to 90. | | `time_range` | string | `all`, `1h`, `24h`, `3d`, `7d`, `30d`, `90d` | Used by search and list endpoints instead of `days_back`. | | `environment` | string | `all`, `development`, `staging`, `production` | `/conversations` only. | | `limit` | integer | 1 up to a per-endpoint cap | See the limits table below. | | `offset` | integer | 0–10,000 | Values above 10,000 are clamped. | Two validation rules apply everywhere: * Numeric parameters must be non-negative integers; anything else (`limit=abc`, `offset=-1`) returns `400`. Values outside the allowed range are **clamped** to the nearest bound, not rejected. * Enum parameters (`mode`, `time_range`, `environment`, `outcome`, `kind`, `family`, ...) return `400` for values outside the documented set: ```json theme={"dark"} { "message": ["mode must be one of the following values: keyword, semantic, hybrid"], "error": "Bad Request", "statusCode": 400 } ``` ## Limits | Limit | Value | | - | - | | `days_back` maximum | 90 | | `limit` maximum (default) | 100 | | `limit` maximum on `/frustrations`, `/emotions`, `/hallucinations`, `/tool-failures/:toolName` | 20 | | `limit` maximum on `/problems` | 25 | | `limit` maximum on `/tools` | 200 | | `limit` maximum on `/problems/:id/reports`, `/problems/:id/conversations`, `/problems/:id/evidence` | 50 | | `offset` maximum | 10,000 | | Context `window` maximum | 5 messages each side | ## Pagination Three patterns are in use: 1. **`limit` + `offset`** — most list endpoints. Responses carry a `pagination` object; keep incrementing `offset` by `limit` while `has_more` is `true`: ```json theme={"dark"} { "pagination": { "limit": 20, "offset": 0, "total": 57, "has_more": true } } ``` 2. **`limit` only** — [`/search`](/data-api/search) has no `offset`. Its `pagination` object reports `limit`, `returned`, and `has_more`; narrow the query or time range instead of paging deeper. 3. **Keyset cursors** — the [problem sub-resources](/data-api/problems) (`/reports`, `/conversations`, `/evidence`) return `pagination.next_cursor`; pass it back as `cursor` to fetch the next page. ## Endpoints | Endpoint | Description | Reference | | - | - | - | | `GET /whoami` | The tenant, kind and scope of the calling key | [Authentication](#authentication) | | `GET /overview` | Headline KPIs, top clusters, recent activity | [Analytics](/data-api/analytics) | | `GET /trends` | Dashboard KPIs for a window against the previous window of equal length, with optional series | [Analytics](/data-api/analytics) | | `GET /clusters` | Use-case cluster hierarchy from the latest clustering run | [Analytics](/data-api/analytics) | | `GET /clusters/:nodeId/conversations` | Traces in one cluster | [Analytics](/data-api/analytics) | | `GET /task-clusters/search` | Search cluster nodes by name or meaning | [Analytics](/data-api/analytics) | | `GET /search` | Message-grain keyword / semantic / hybrid search | [Search](/data-api/search) | | `GET /conversations` | List and filter traces | [Traces](/data-api/traces) | | `GET /conversations/:id/context` | Windowed message context around one message | [Traces](/data-api/traces) | | `GET /conversations/:id/world-state` (`/replay` and `/snapshot` are retired: `410`) | World state: a trace's tasks and facts | [Traces](/data-api/traces) | | `GET /frustrations` | Frustration detections with evidence | [Signals](/data-api/signals) | | `GET /emotions` | Multi-family emotion detections | [Signals](/data-api/signals) | | `GET /tool-failures` (+ `/:toolName`) | Tool failure KPIs and per-tool examples | [Signals](/data-api/signals) | | `GET /tools` (+ `/:name`) | Tool catalog: every tool's calls and success rate; one tool's schema, usage, and failure categories | [Signals](/data-api/signals) | | `GET /hallucinations` | Grounding results: contradictions and verified claims | [Signals](/data-api/signals) | | `GET /problems` (+ `/:id`, `/:id/reports`, `/:id/conversations`, `/:id/evidence`) | Ranked root-cause problems and their evidence | [Problems](/data-api/problems) | | `GET`/`POST /problems/:id/feedback` | Problem feedback (mark fixed, dismiss, flag, rename) | [Problems](/data-api/problems) | | `GET /problems/:id/history` | One problem's incidents and users per day, with a comparison | [Problems](/data-api/problems) | | `POST /feedback` | General data-quality feedback | [Problems](/data-api/problems) | ## Errors | Status | Meaning | | - | - | | `400` | Validation failure: malformed numeric parameter, unknown enum value, missing required parameter or body field. | | `401` | Missing, invalid, or revoked API key. | | `404` | Referenced sub-resource does not exist (for example, an `attribution_id` that does not belong to the problem). | | `500` | Internal error. The body never contains internal details. | Error bodies follow one shape; `message` is a string or an array of validation messages: ```json theme={"dark"} { "statusCode": 500, "message": "An internal error occurred while processing your request.", "error": "Internal Server Error" } ``` > [!NOTE] > > Lookups of unknown IDs generally do not return `404`. `GET /clusters/:nodeId/conversations` returns `200` with `cluster: null`, and `GET /problems/:id` returns `200` with `found: false`. Check those fields instead of relying on the status code. ## Next steps * [Search](/data-api/search) — find the exact message where something happened, then jump to its context. * [Signals](/data-api/signals) — read frustration, emotion, tool-failure, and hallucination detections. * [Problems](/data-api/problems) — read the ranked problem list and send feedback. * [CLI overview](/cli/overview) — the same data from the terminal, with agent-friendly JSON output. * [Connect the MCP server](/mcp/overview) — the same data as MCP tools for Claude Code, Cursor, and other MCP clients. # Problems Source: https://docs.moda.dev/data-api/problems GET /problems for the ranked root-cause list, per-problem detail and evidence, and the feedback endpoints that steer discovery. Problems are recurring root causes that Moda discovers by grouping signals (frustrations, tool failures, and other detections) across traces. Signal attributions land within minutes, and the ranked list is updated automatically as evidence accumulates. These endpoints mirror the [Problems dashboard](/dashboard/problems) and add a feedback channel that steers discovery. Problem IDs are UUIDs. If a problem was merged into another, its old ID still resolves — responses report the surviving ID in `problem_id` and set `alias_resolved: true`. ## GET /problems The ranked problem list (the Book) with coverage and freshness metadata. It is read by the same loader as the dashboard's Problems list, so counts, ranking, trust and the date range are the dashboard's. For a tenant with a dream grouping published, the dashboard shows that grouping by default: read it with [GET /problems/dream](#get-problemsdream). ### Query parameters **days_back** `integer` (default: 30) 1–90. The range the counts cover. For a tenant whose Problems are dream-grouped (message-windowed), the counts are recounted live for the range and `summary.window_hours` reports the rollup's own window. **limit** `integer` (default: 25) 1–200 rows per page, applied to `problems` and `untrusted` separately. Also caps `emerging` and `hierarchy.macros`. The first page of the rank order may carry up to two extra rows: the open problems with the most affected users, when the rank cut dropped them (they appear again at their own rank on a later page; dedupe by `problem_id`). **offset** `integer` (default: 0) Row to start each partition at: `next_offset` of the previous page. **list_version** `string` `list_version` of the first page, passed with every later `offset`, so the page is cut from the same read. A later page whose `list_version` differs came from a newer list: restart from `offset=0`. **sort** `string` (default: rank) `rank` (the Book's order), `users`, `signals`, `problems` or `signal:`: the dashboard table's orders, applied to each partition before the page is cut. **dir** `string` (default: desc) `desc` or `asc`, for a `sort` other than `rank`. **cohort** `string` `builtin:` or a saved cohort id: only the problems the cohort's users hit, each with `cohort: {attributions, conversations}`. The cohort's membership snapshot is refreshed first, as the dashboard does. ### Response fields **summary** `object` `days_back`, `window_hours` (dream-grouped tenants only), `open_problems`, `reopened`, `total_problems`, `signals_attributed`, `explained_coverage_pct`. **remainder** `object` The tenant-wide coverage meter: `attributed_signals`, `unexplained_signals`, `unexplained_signals_scope`, `unexplained_signals_current`, `unexplained_signals_historical_only`, `coverage_pct`, `historically_attributed_signals`, `historical_coverage_pct`. Here `unexplained_signals` is everything the live problem list doesn't explain, and it splits into two parts: * `unexplained_signals_current`: signals in the window with no attribution at all. * `unexplained_signals_historical_only`: signals attributed only to problems that are no longer live (retired, resolved, or not in the latest ranking run). The two parts always add up to `unexplained_signals`. `unexplained_signals_scope` says which quantity `unexplained_signals` holds: `current_plus_historical` here and in the problem detail `remainder`. **problems** `array` The trusted ranked list — only rows whose `verification_status` is `current`, ordered by rank. Each row has `problem_id`, `display_name`, `cause_statement`, `lifecycle` (`open`, `fixed_monitoring`, `reopened`, `resolved`), `rank_score`, `rubric_version`, `total_attributions`, `family_weighted_count`, `affected_users`, `affected_conversations` (traces affected), `abandonment_rate`, `recency_score`, `trend_score`, `multi_family`, `family_counts`, `coverage_overall`, `coverage_by_family`, `audit_pass_rate` (or `null`), `verification_status`, `verified_causal_version`. When the Book keeps a curated shortlist, `pressing_rank` is the row's place on it (`null` when it is not on it); `rank_basis` is `v4_impact` when `rank_score` is the problems v4 impact score; `incidents` counts a dream-grouped tenant's incidents in the range. An empty name falls back to the cause, as the dashboard titles it. **untrusted** `array` Same row shape as `problems`, for rows whose verification is `failed`, `unverified`, or `stale`. They are still live problems and still visible, but never ranked. Treat `failed` and `unverified` rows as hypotheses; `stale` rows rank again after re-verification. **next_offset** `integer | null` Where the next page of `problems` and `untrusted` starts, or `null` on the last page. `offset`, `list_version`, `sort` (and `dir`, `cohort` when set) echo the page. **hierarchy** `object` `macros[]` — macro themes grouping leaf problems (`problem_id`, `display_name`, `display_description`, `tier`, `child_count`, `children[]`), at most `limit` of them — `macro_total` (all live macros), and `unparented_leaf_count`. **emerging** `array` Provisional problems not yet in the ranked list, at most `limit` of them, most supported first: `problem_id`, `display_name`, `display_description`, `family` (or `null`), `evidence_support` (`report_backed_members`, `attribution_count`), `verification_status`, `provisional: true`. **emerging_total** `integer` How many provisional problems there are in all; more than the length of `emerging` when `limit` cut it. **freshness** `object` When things were last computed: `book_computed_at`, `latest_assignment_at`, `lag_seconds`, `verification` (counts by status). **feedback_pending** `integer` Feedback rows submitted but not yet applied. **warnings** `string[]` Human-readable notes, empty when there are none. When `problems` is empty but `untrusted` or `emerging` has items, a warning says how many sit in each (with the `untrusted` verification breakdown). An empty `problems` list does not mean the tenant has no problems. ### Example ```bash theme={"dark"} curl "https://moda.dev/api/v1/data/problems?days_back=30&limit=1" \ -H "x-api-key: YOUR_MODA_API_KEY" ``` ```json theme={"dark"} { "summary": { "days_back": 30, "open_problems": 6, "reopened": 1, "total_problems": 8, "signals_attributed": 412, "explained_coverage_pct": 71.4 }, "remainder": { "attributed_signals": 412, "unexplained_signals": 165, "unexplained_signals_scope": "current_plus_historical", "unexplained_signals_current": 130, "unexplained_signals_historical_only": 35, "coverage_pct": 71.4, "historically_attributed_signals": 447, "historical_coverage_pct": 77.5 }, "problems": [ { "problem_id": "3f6b0a52-9d1c-4e7a-b2f8-6c0d5e4a3b21", "display_name": "Ticket creation fails on urgent priority", "cause_statement": "The create_ticket tool is called with priority values the ticketing API rejects, so refund escalations silently fail.", "lifecycle": "open", "rank_score": 0.92, "rubric_version": 4, "total_attributions": 61, "family_weighted_count": 48.5, "affected_users": 37, "affected_conversations": 44, "abandonment_rate": 0.27, "recency_score": 0.81, "trend_score": 0.34, "multi_family": true, "family_counts": { "tool_failure": 42, "emotion": 19 }, "coverage_overall": 0.71, "coverage_by_family": { "tool_failure": 0.84, "emotion": 0.52 }, "audit_pass_rate": 0.93, "verification_status": "current", "verified_causal_version": 3 } ], "untrusted": [], "hierarchy": { "macros": [ { "problem_id": "9a2e7c14-5b3f-4d80-a6e1-2f7b8c9d0e13", "display_name": "Ticketing integration reliability", "display_description": "Failures and workarounds in the ticketing tool chain.", "tier": "macro", "child_count": 2, "children": ["3f6b0a52-9d1c-4e7a-b2f8-6c0d5e4a3b21", "b4c8d1e6-0f2a-4357-9b8c-7d6e5f4a3b2c"] } ], "unparented_leaf_count": 3 }, "emerging": [], "freshness": { "book_computed_at": "2026-08-14T03:12:44", "latest_assignment_at": "2026-08-14T11:05:09", "lag_seconds": 28345, "verification": { "live_total": 8, "current": 6, "stale": 1, "failed": 0, "unverified": 1 } }, "feedback_pending": 1, "warnings": [] } ``` > [!NOTE] > > This example is trimmed for readability: with `limit=1` only the top-ranked row is shown, and the `untrusted` rows implied by the `verification` counts (`stale: 1`, `unverified: 1`) are omitted, as are `offset`, `next_offset` and `list_version`. ## GET /problems/dream The dream-grouped Problems list: what the dashboard's Problems page shows by default when the tenant has a dream grouping published. Read by the dashboard's own loader. A tenant without one gets `{"available": false, "view": "dream"}`, and its Problems are [GET /problems](#get-problems), as on the dashboard. ### Query parameters **days_back** `integer` 1–90 days ending now. Absent: the dream run's whole window, the dashboard's default. **limit** `integer` (default: 25) 1–200 problems per page. **offset** `integer` (default: 0) `next_offset` of the previous page. Pass `list_version` with it. **list_version** `string` `list_version` of the first page; a later page is cut from the same read while it is cached (5 minutes). **sort** `string` (default: severity) `severity` (the dream's rank), `users`, or `silent` (share of users who never noticed): the dashboard table's columns. **dir** `string` (default: desc) `desc` or `asc`. **cohort** `string` `builtin:` or a saved cohort id: every count comes from the cohort's users. ### Response fields **available** `boolean` `true` when the tenant has a dream grouping published (the dashboard then shows it). **run** `object` The dream run the list comes from: `run_id`, `window_end`, `window_hours`, `incidents`, `unsorted`, `users`, `users_grouped`. **summary** `object` `problems` (every problem the table shows), `incidents`, `unsorted_incidents`, `users`, `users_grouped`, `pinned_problem_ids`, and `previous` (the window before, with `comparable`). **problems** `array` One page, in the table's order. Each row has `problem_id` (a Book problem id: GET /problems/:id reads its dossier), `name`, `category`, `cause_statement`, `fix`, `owner`, `component`, `lifecycle`, `pinned`, `incidents`, `users`, `silent_users`, `silent_share_pct`, `noticed_counts`, `trend`, `previous_incidents` (when comparable), `severity` (`tier` P0–P3, `rank`, `alert`, `worst`), `dream_rank` and `first_incident_at`. **worst_incidents** `array` First page only: the most severe rated incidents of the shown problems. **next_offset** `integer | null` Where the next page starts, or `null`. `sort`, `dir`, `offset`, `limit` and `list_version` echo the page. ## GET /problems/dream/:id One dream problem as the dashboard's dream page shows it: its definition, scores, counts and severity, with a page of its incidents (the validator's verdict, quoted messages, assumptions and severity rating), most serious first. 404 when the problem is not in the dream grouping; `{"available": false}` when the tenant has none. **limit** `integer` (default: 5) 1–50 incidents per page. `incidents_total` counts them all; `next_offset` starts the next page. **offset** `integer` (default: 0) First incident to return. **days_back** `integer` 1–90. Absent: the dream run's whole window. ## GET /problems/:id Full detail for one problem. Returns `200` with `found: false` for an unknown or malformed ID — not `404`. ### Response fields **found** `boolean` `false` when the ID does not resolve to a problem; all other blocks are then empty or `null`. **problem_id / requested_problem_id / alias_resolved** `string / string / boolean` The surviving problem ID, the ID you requested, and whether a merged-away ID was folded to its survivor. **header** `object | null` The same row shape as the list on `GET /problems`. **rubric** `object | null` The latest problem definition: `version`, `cause_statement`, `display_name`, `display_description`, `lifecycle`, `parent_problem_id`, `change_reason`, `match_criteria`, `counter_examples`, `scope_hints`, `updated_at`, `tier` (`macro` or `leaf`), `provisional`, `affected_surface`, `causal_content_version`. **trend** `array` Rank history: `{run_ts, rank_score, total_attributions, rubric_version, coverage_overall}` per computation run, newest first. **sub_problems** `array` Child problems for macro problems: `{problem_id, display_name, cause_statement, lifecycle, version}`. **verification** `object` `audit_pass_rate`, `judge_audit` (`{passed, total}`), `counterfactual_replay` (`{passed, total}`), and `samples[]` — individual verification checks with `kind`, `passed`, `rubric_version`, `conversation_id`, `segment_id`, `rationale`, `verified_at`. **evidence** `array` A first page of evidence rows (see [`/problems/:id/evidence`](#get-problemsidevidence) for the full paginated set and field list). **affected_conversations** `array` Per-trace `{conversation_id, user_id, signal_count, family_counts, last_signal_at}` rollups. **remainder** `object` The same tenant-wide coverage meter as the list endpoint. **investigation_reports** `object` First page of investigation reports: `{items[], has_more, next_cursor}` (full set on [`/problems/:id/reports`](#get-problemsidreports)). **change_history** `array` Lineage events: `{problem_id, event_id, event_kind, related_problem_id, rubric_version, causal_content_version, reason, created_ts}`. **impact_identity** `object` `known_users`, `unknown_identity_conversations`, `total_conversations`, `identity_coverage_pct` — impact is split so traces without a known user are never reported as zero users. **hierarchy** `object` `tier`, `parent` (or `null`), `children[]`. **dossier** `object | null` Precomputed narrative blocks (`executive_summary`, `causal_chain`, `suggested_investigation`, `representative_story_keys`, `limitations`) plus computation metadata. `null` until a dossier has been generated. **stories** `array` Representative examples, each `{story_kind, evidence}` where `story_kind` is one of `top_confidence`, `replay_verified`, `newest`. ### Example ```bash theme={"dark"} curl "https://moda.dev/api/v1/data/problems/3f6b0a52-9d1c-4e7a-b2f8-6c0d5e4a3b21" \ -H "x-api-key: YOUR_MODA_API_KEY" ``` ```json theme={"dark"} { "found": true, "problem_id": "3f6b0a52-9d1c-4e7a-b2f8-6c0d5e4a3b21", "requested_problem_id": "3f6b0a52-9d1c-4e7a-b2f8-6c0d5e4a3b21", "alias_resolved": false, "header": { "problem_id": "3f6b0a52-9d1c-4e7a-b2f8-6c0d5e4a3b21", "display_name": "Ticket creation fails on urgent priority", "lifecycle": "open", "rank_score": 0.92, "verification_status": "current" }, "rubric": { "version": 4, "cause_statement": "The create_ticket tool is called with priority values the ticketing API rejects, so refund escalations silently fail.", "display_name": "Ticket creation fails on urgent priority", "display_description": "Escalations fail when the agent passes 'urgent' as a ticket priority.", "lifecycle": "open", "parent_problem_id": "9a2e7c14-5b3f-4d80-a6e1-2f7b8c9d0e13", "change_reason": "Narrowed match criteria after false positives on timeout errors.", "match_criteria": { "tool_name": "create_ticket", "error_pattern": "priority" }, "counter_examples": [], "scope_hints": [], "updated_at": "2026-08-14T03:11:57", "tier": "leaf", "provisional": false, "affected_surface": "ticketing integration", "causal_content_version": 3 }, "trend": [ { "run_ts": "2026-08-14T03:12:44", "rank_score": 0.92, "total_attributions": 61, "rubric_version": 4, "coverage_overall": 0.71 } ], "sub_problems": [], "verification": { "audit_pass_rate": 0.93, "judge_audit": { "passed": 14, "total": 15 }, "counterfactual_replay": { "passed": 4, "total": 4 }, "samples": [] }, "evidence": [ { "attribution_id": "e19c3d47-8a2b-4f60-95c1-3d2e1f0a9b87", "conversation_id": "conv_9f2c41d08ab37e51", "segment_id": "c7e5a1d2-4f6b-5a38-9c21-8b0e3d47f6a9", "anchor_signal_id": "8c1d2e3f-4a5b-6c7d-8e9f-0a1b2c3d4e5f", "anchor_msg_index": 7, "signal_family": "tool_failure", "signal_type": "validation_error", "confidence": 0.9, "causal_rationale": "The failure occurs on every escalation where the agent sets priority to 'urgent'.", "door": "rubric_match", "replay_verified": true, "evidence_snippet": "{\"excerpt\":\"create_ticket failed: 422 Unprocessable Entity\",\"families\":[\"tool_failure\"],\"line\":\"priority must be one of low, normal, high\",\"anchor\":{\"family\":\"tool_failure\",\"type\":\"validation_error\",\"msg_index\":7},\"door\":\"rubric_match\",\"mechanism\":\"invalid enum value\"}", "dedup_count": 1, "user_id": "user_4821", "assigned_at": "2026-08-14T09:52:30", "snippet_parsed": { "excerpt": "create_ticket failed: 422 Unprocessable Entity", "families": ["tool_failure"], "line": "priority must be one of low, normal, high", "anchor": { "family": "tool_failure", "type": "validation_error", "msg_index": 7 }, "door": "rubric_match", "mechanism": "invalid enum value" }, "snippet_legacy_raw_text": false, "report_id": "a7b6c5d4-e3f2-4109-8765-4321fedcba98" } ], "affected_conversations": [ { "conversation_id": "conv_9f2c41d08ab37e51", "user_id": "user_4821", "signal_count": 3, "family_counts": { "tool_failure": 2, "emotion": 1 }, "last_signal_at": "2026-08-14T09:52:30" } ], "remainder": { "attributed_signals": 412, "unexplained_signals": 165, "unexplained_signals_scope": "current_plus_historical", "unexplained_signals_current": 130, "unexplained_signals_historical_only": 35, "coverage_pct": 71.4, "historically_attributed_signals": 447, "historical_coverage_pct": 77.5 }, "investigation_reports": { "items": [], "has_more": true, "next_cursor": "eyJ0cyI6IjIwMjYtMDgtMTMifQ" }, "change_history": [], "impact_identity": { "known_users": 37, "unknown_identity_conversations": 5, "total_conversations": 44, "identity_coverage_pct": 88.6 }, "hierarchy": { "tier": "leaf", "parent": { "problem_id": "9a2e7c14-5b3f-4d80-a6e1-2f7b8c9d0e13", "display_name": "Ticketing integration reliability", "tier": "macro" }, "children": [] }, "dossier": null, "stories": [] } ``` > [!NOTE] > > The example trims `header` to a few fields for readability; the live response returns the complete list-row shape documented under `GET /problems`. ## GET /problems/:id/reports Investigation reports for one problem, keyset-paginated. ### Query parameters **limit** `integer` (default: 20) 1–50. **cursor** `string` The `next_cursor` from a previous page. Each report has `report_id`, `conversation_id`, `segment_id`, `status` (`investigated`, `no_problem`, or `rejected`), `problem_found`, `mechanism`, `narrative`, `citations[]` (`{path, ref, quote}`), `signals_explained`, `signals_total`, `signals_explained_ids[]`, `signals_unexplained_ids[]`, `suspected_surface`, `severity`, `confidence`, `primary_family`, `investigated_at`. ```bash theme={"dark"} curl "https://moda.dev/api/v1/data/problems/3f6b0a52-9d1c-4e7a-b2f8-6c0d5e4a3b21/reports?limit=1" \ -H "x-api-key: YOUR_MODA_API_KEY" ``` ```json theme={"dark"} { "problem_id": "3f6b0a52-9d1c-4e7a-b2f8-6c0d5e4a3b21", "requested_problem_id": "3f6b0a52-9d1c-4e7a-b2f8-6c0d5e4a3b21", "reports": [ { "report_id": "a7b6c5d4-e3f2-4109-8765-4321fedcba98", "conversation_id": "conv_9f2c41d08ab37e51", "segment_id": "c7e5a1d2-4f6b-5a38-9c21-8b0e3d47f6a9", "status": "investigated", "problem_found": true, "mechanism": "create_ticket rejects the 'urgent' priority enum; the agent never surfaces the error to the user.", "narrative": "The user asked for an escalation. The agent called create_ticket with priority 'urgent', which the ticketing API rejects with a 422. The agent then told the user the ticket was created.", "citations": [ { "path": "conversation", "ref": "msg 7", "quote": "422 Unprocessable Entity: field 'priority' must be one of low, normal, high" } ], "signals_explained": 2, "signals_total": 3, "signals_explained_ids": ["8c1d2e3f-4a5b-6c7d-8e9f-0a1b2c3d4e5f"], "signals_unexplained_ids": ["1f2e3d4c-5b6a-7980-1234-56789abcdef0"], "suspected_surface": "ticketing integration", "severity": "high", "confidence": 0.88, "primary_family": "tool_failure", "investigated_at": "2026-08-14T02:58:41" } ], "pagination": { "limit": 1, "has_more": true, "next_cursor": "eyJ0cyI6IjIwMjYtMDgtMTMifQ" } } ``` ## GET /problems/:id/conversations Traces attributed to one problem, keyset-paginated, with per-trace counts and an anchor for deep-linking. ### Query parameters **limit** `integer` (default: 25) 1–50. **cursor** `string` The `next_cursor` from a previous page. **family** `string` Filter to one signal family (for example `tool_failure`, `emotion`). **door** `string` How the trace joined the problem: `rubric_match` or `local_causal_chain`. ```bash theme={"dark"} curl "https://moda.dev/api/v1/data/problems/3f6b0a52-9d1c-4e7a-b2f8-6c0d5e4a3b21/conversations?limit=1" \ -H "x-api-key: YOUR_MODA_API_KEY" ``` ```json theme={"dark"} { "problem_id": "3f6b0a52-9d1c-4e7a-b2f8-6c0d5e4a3b21", "requested_problem_id": "3f6b0a52-9d1c-4e7a-b2f8-6c0d5e4a3b21", "family": null, "door": null, "conversations": [ { "conversation_id": "conv_9f2c41d08ab37e51", "user_id": "user_4821", "attribution_count": 3, "families": { "tool_failure": 2, "emotion": 1 }, "first_anchor_at": "2026-08-14T09:31:41", "last_anchor_at": "2026-08-14T09:52:30", "latest_anchor": { "segment_id": "c7e5a1d2-4f6b-5a38-9c21-8b0e3d47f6a9", "anchor_signal_id": "8c1d2e3f-4a5b-6c7d-8e9f-0a1b2c3d4e5f", "anchor_msg_index": 7 } } ], "pagination": { "limit": 1, "has_more": true, "next_cursor": "eyJ0cyI6IjIwMjYtMDgtMTQifQ" } } ``` Use `latest_anchor.anchor_msg_index` with [`/conversations/:id/context`](/data-api/traces#get-conversationsidcontext) to read the moment the signal fired. ## GET /problems/:id/evidence All evidence attributions for one problem, keyset-paginated. Rows have the same shape as the `evidence` block on `GET /problems/:id`: `attribution_id`, `conversation_id`, `segment_id`, `anchor_signal_id`, `anchor_msg_index`, `signal_family`, `signal_type`, `confidence`, `causal_rationale`, `door`, `replay_verified` (or `null`), `evidence_snippet`, `dedup_count`, `user_id`, `assigned_at`, `snippet_parsed` (structured parse of `evidence_snippet`, `null` for legacy raw-text rows), `snippet_legacy_raw_text`, `report_id` (or `null` for fast-lane rows). ### Query parameters **limit** `integer` (default: 25) 1–50. **cursor** `string` The `next_cursor` from a previous page. ```bash theme={"dark"} curl "https://moda.dev/api/v1/data/problems/3f6b0a52-9d1c-4e7a-b2f8-6c0d5e4a3b21/evidence?limit=25" \ -H "x-api-key: YOUR_MODA_API_KEY" ``` ## POST /problems/:id/feedback Records feedback on a problem. Feedback does not edit the problem directly — it is incorporated automatically. `mark_fixed` also arms automatic reopening if the problem recurs. This is the endpoint behind `moda problems feedback`. ### Body fields **action** `string` *required* One of `mark_fixed`, `dismiss`, `flag_attribution`, `rename`. **reason** `string` Up to 2,000 characters. **Required** for `dismiss` and `flag_attribution`. **attribution_id** `string` **Required** for `flag_attribution`. A non-UUID value returns `400`; a UUID that does not belong to this problem returns `404`. **new_display_name** `string` Up to 255 characters. **Required** for `rename`. **actor** `string` (default: data-api) Recorded as the acting identity, up to 255 characters. > [!NOTE] > > This endpoint is idempotent: `feedback_id` is derived deterministically from the payload, so resubmitting identical feedback while it is still pending returns the same `feedback_id` with `duplicate: true` and records nothing new. Safe to retry. ```bash theme={"dark"} curl -X POST "https://moda.dev/api/v1/data/problems/3f6b0a52-9d1c-4e7a-b2f8-6c0d5e4a3b21/feedback" \ -H "x-api-key: YOUR_MODA_API_KEY" \ -H "Content-Type: application/json" \ -d '{"action": "mark_fixed", "reason": "Priority enum fixed in ticketing client v2.4.1", "actor": "release-bot"}' ``` ```json theme={"dark"} { "success": true, "feedback_id": "c2d4e6f8-0a1b-4c3d-9e8f-7a6b5c4d3e2f", "problem_id": "3f6b0a52-9d1c-4e7a-b2f8-6c0d5e4a3b21", "action": "mark_fixed", "status": "pending", "duplicate": false } ``` A malformed (non-UUID) problem ID returns `400`. ## GET /problems/:id/history One problem's incidents and users per UTC day, from the dashboard's problem history loader, and the window against the window of equal length before it. A merged problem's history is its survivor's. `moda problems get --trend` reads this endpoint. | Parameter | Type | Default | Description | | - | - | - | - | | `days_back` | integer | 30 | Days of history (1–90). `compare` is `null` above 45 days because the history keeps 90 days. | | Field | Description | | - | - | | `problem_id`, `requested_problem_id` | The problem the history is for, and the id asked for. | | `first_seen`, `last_seen` | First and last day the problem held an incident, over all its history. | | `compare` | `incidents` and `signals`: `{ current, previous, delta, delta_pct }`. | | `series` | `incidents` and `users` as `[date, value]` arrays, oldest first. `users` are distinct per day; do not sum them. | ## GET /problems/:id/feedback Feedback history for one problem, with pending/consumed state. ```bash theme={"dark"} curl "https://moda.dev/api/v1/data/problems/3f6b0a52-9d1c-4e7a-b2f8-6c0d5e4a3b21/feedback" \ -H "x-api-key: YOUR_MODA_API_KEY" ``` ```json theme={"dark"} { "problem_id": "3f6b0a52-9d1c-4e7a-b2f8-6c0d5e4a3b21", "requested_problem_id": "3f6b0a52-9d1c-4e7a-b2f8-6c0d5e4a3b21", "feedback": [ { "feedback_id": "c2d4e6f8-0a1b-4c3d-9e8f-7a6b5c4d3e2f", "feedback_kind": "mark_fixed", "reason": "Priority enum fixed in ticketing client v2.4.1", "attribution_id": null, "new_display_name": "", "actor": "release-bot", "status": "pending", "consumed_by_run_id": null, "created_at": "2026-08-14T12:02:19.000Z" } ], "pending_count": 1 } ``` ## POST /feedback General feedback about data quality — a wrong cluster label, a mismatched frustration cause, missing data. This is separate from [problem feedback](#post-problemsidfeedback) (which `moda problems feedback` sends): it flags issues with what the Data API returned, and it is what `moda feedback` sends. Returns `202`. ### Body fields **category** `string` *required* One of `bad_cluster_label`, `mismatched_frustration`, `missing_data`, `noisy_data`, `wrong_tool_failure`, `incorrect_loop`, `api_quirk`, `false_positive_attribution`, `misrouted_fix`, `harness_bug`, `other`. Any other value is stored as `other`, with the submitted value in `refs.raw_category`. **severity** `string` (default: low) One of `info`, `low`, `medium`, `high`. **note** `string` Up to 4,000 characters describing what looked wrong. **source** `string` One of `cli`, `sdk`, `ui`. **agent** `string` The agent submitting the feedback, up to 64 characters. **cli_version** `string` Up to 32 characters. **refs** `object` Free-form references, for example `{"conversation_id": "...", "tool_name": "..."}`. **command_context** `object` Free-form context about the command or query that produced the suspect result. > [!WARNING] > > Unlike problem feedback, this endpoint is **not** idempotent — every request creates a new feedback record with a random `feedback_id`. Do not retry it automatically. ```bash theme={"dark"} curl -X POST "https://moda.dev/api/v1/data/feedback" \ -H "x-api-key: YOUR_MODA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "category": "bad_cluster_label", "severity": "low", "note": "Cluster node_47 is labeled Refund requests but contains mostly invoice questions.", "source": "sdk", "refs": { "cluster_id": "node_47" } }' ``` ```json theme={"dark"} { "feedback_id": "f0e1d2c3-b4a5-4968-8776-5544332211aa", "submitted_at": "2026-08-14 12:05:31.482" } ``` ## Next steps * [Dashboard: Problems](/dashboard/problems) — the same problem book as a kanban with dossiers. * [Signals](/data-api/signals) — the raw detections that problems are built from. * [Traces](/data-api/traces) — read the context around any evidence anchor. ## Problem impact within use cases `GET /api/v1/data/problem-impact` connects attributed problem evidence to the use-case segments in which it occurred. Authenticate with the same API key as other Data API endpoints; tenant scope comes from that key. | Parameter | Values | | - | - | | `nodeId` | A use-case node, including its descendants | | `problemId` | A problem UUID; merges resolve to the current problem | | `mode` | `metrics` (default), `trend`, `evidence`, `catalog`, `overview`, `affected-use-cases`, or `trace-use-cases` | | `days` | `1`, `3`, `7` (default), `30`, `90`, or `all` | | `to` | Optional UTC ISO timestamp with milliseconds; fixes the window end | | `runId` | Optional expected classification run; mismatch returns `409` | | `cursor` | Opaque continuation returned by `evidence`; retain the same scope | | `conversationIds` | JSON array of 1–25 trace IDs for `trace-use-cases`; requires `problemId` | Select a node, a problem, or both. `catalog` lists available use cases and problems. `overview` returns the distinct affected share for root use cases (or the selected node's children). A parent problem includes its current leaf problems. `affected-use-cases` returns affected counts without full population denominators. `trace-use-cases` resolves current use-case membership from a problem's attributed segments for the specified traces across their history; it does not apply the `days` window. The response includes `runId`, resolved `problemId`, `window`, `nodes`, `problems`, `rows`, `evidence`, `nextCursor`, and `computedAt`. Metric rows have `node_id`, `problem_id`, and `period` (`current` or `previous`). An empty `problem_id` identifies the full analyzed population; `*` identifies the distinct union of affected traces across selected problems. Use the empty-ID row's `analyzed` denominator for each problem's percentage. A problem-only metrics response includes only affected use cases, with each denominator covering that use case's full analyzed population. Never add problem counts to produce a distinct total. Trend rows include a UTC `bucket` date and span the current and preceding windows, or all available history for `days=all` without a preceding comparison window. A trend row's `period` is `previous` when its `bucket` date is before the first day of the window (`window.from`) and `current` otherwise, so each date is one row. Missing dates have no analyzed population and no rate. `affected / analyzed` is **affected share**, not task failure rate. `traces` counts distinct conversations with matching current segments. `analyzed` counts conversations containing at least one matching analyzed segment, including negative analysis outcomes. `segments` and `analyzed_segments` expose partial analysis coverage. `users` counts distinct nonempty identities on affected evidence; `identified_traces` provides identity coverage. Evidence returns up to 25 distinct conversations per page with the exact `segment_id` and zero-based `anchor_msg_index`. Continue using `nextCursor`, `runId`, `window.to`, and the original filters. A cursor from another scope is rejected. Unmapped evidence is excluded from scoped results. These are live reads of the current classification and attribution records, using segment occurrence timestamps. They are not stored historical snapshots: regeneration, merges, transfers, and retractions can change past results. Individual source reads can observe concurrent pipeline updates. `409` requests a classification refresh; query failures remain errors, never zero-count results. No materialized impact counters or refresh jobs are added. Like the dossier, every impact count excludes retracted reports and detections a review marked as false positives. Impact counts only attributions whose segment belongs to a use case in the current classification run and occurred inside the window, so a problem's `affected` count can be lower than the dossier's affected conversations, or zero. For `metrics`, `trend`, `evidence`, and `affected-use-cases` requests with a `problemId`, the response also includes `attributionCoverage`, which counts over all time, and a `warnings` list that explains the gap: * `attributedConversations`: the conversations attributed to the problem. This is the same population as the dossier's affected conversations: retracted reports and detections a review marked as false positives are excluded. * `inUseCaseConversations`: the attributed conversations with at least one attributed segment in a use case in scope. Only these can count as `affected`. * `outsideUseCaseConversations`: the attributed conversations that impact can't place in the selected scope. They split into the three counts below. * `otherUseCaseConversations`: conversations the run classified into a different use case. Only a request with a `nodeId` can have these. * `readerOnlyConversations`: conversations whose only evidence is conversation-level (reader) evidence, which has no thread segment. * `unclassifiedConversations`: conversations with attributed segments that the run didn't place in any use case, for example traces ingested after the run. * `uncountableInUseCase`: present only when some `inUseCaseConversations` can't count as `affected` in any window, split by reason. `stale` means the trace was re-segmented after the run, so the run's use-case membership points at a superseded segment. `ineligible` means the segment's current version was built by a different segment embedding version or source. `missing` means the segment no longer exists. These count again once a classification run includes the trace's current segments. The window uses the segment's effective occurrence time. That is the message time, or the conversation's first ingest time for replayed history whose message times are placeholders from before 2022. Window filters and displayed times such as `occurred_at` and trend buckets use the same value. # Search Source: https://docs.moda.dev/data-api/search GET /search — keyword, semantic, and hybrid search over individual messages, with anchors for jumping to trace context. `GET /search` searches individual messages across all your traces and returns snippet-level hits. Every result carries a `conversation_id` (the trace ID) + `message_index` anchor, so you can jump straight to the surrounding turns with [`GET /conversations/:id/context`](/data-api/traces#get-conversationsidcontext). ``` GET https://moda.dev/api/v1/data/search ``` ## Query parameters **q** `string` *required* The search query, 1–500 characters. Leading and trailing whitespace is trimmed; a whitespace-only query returns `400`. **mode** `string` (default: hybrid) `keyword`, `semantic`, or `hybrid`. Keyword matches literal substrings; semantic matches by meaning; hybrid fuses both. See [Search modes](#search-modes-and-degradation). **user_id** `string` Restrict results to traces from one end user. Maximum 200 characters. **time_range** `string` (default: all) One of `all`, `1h`, `24h`, `3d`, `7d`, `30d`, `90d`. Filters on each message's timestamp. Imported history that stores placeholder timestamps before 2022 is filtered on the time Moda received the message instead. **since** `string` Absolute start, inclusive: an ISO 8601 date (`2026-10-07`) or datetime (`2026-10-07T14:00:00Z`). UTC unless the value carries an offset. Uses the same message time as `time_range`, and the two combine as an intersection. Use it to single out one day or hour among many similar traces. **until** `string` Absolute end, inclusive. A date-only value covers that whole UTC day, so `since=2026-10-07&until=2026-10-07` is one day; a datetime includes that second. `since` must not be after `until`, and the range may span at most 366 days; otherwise the request fails with `400`. With `since` or `until` set, `prior_window_matched_conversations` is `null` (an absolute range has no prior window). **limit** `integer` (default: 20) Maximum results to return, 1–100. There is no `offset` — pagination is limit-only. **include_tool_io** `string` (default: false) `true` or `false`. When `true`, matches inside tool call inputs and tool results are included in the result list. ## Search modes and degradation The response always reports which mode **actually ran** (`search_mode`) and why, if it differs from what you requested (`degrade_reason`). A `semantic` or `hybrid` request degrades transparently to `keyword` rather than failing: | `degrade_reason` | Meaning | Retry? | | - | - | - | | `none` | The requested mode ran. | — | | `semantic_unavailable` | Semantic search was temporarily unavailable (for example, the query embedding timed out). Results were served by keyword search. | Retrying the same query may succeed. | | `below_relevance_floor` | Semantic search ran, but no hit cleared the relevance floor — the corpus has no conceptual matches for this query. Results were served by keyword search. | Retrying will not change the outcome. | > [!WARNING] > > Scores use a different scale per mode and are **not comparable across modes**: in `keyword` mode the score is an integer count of substring matches; in `semantic` mode it is a similarity value; in `hybrid` mode it is a small rank-fusion fraction. Branch on `search_mode` before applying any threshold, and use scores only to order results within a single response. Scores are rounded to 4 decimals. ## Response fields **query** `string` The query as searched (trimmed). **search_mode** `string` The mode that actually ran: `keyword`, `semantic`, or `hybrid`. May differ from the requested `mode`. **degrade_reason** `string` `none`, `semantic_unavailable`, or `below_relevance_floor`. **results** `array` Ranked hits. Each hit has `conversation_id`, `message_index`, `role` (`user` or `assistant`), `timestamp`, `snippet` (the matched text with surrounding context), `score`, `cluster_id` and `cluster_name` (the trace's use-case cluster, or `null`), and `conversation_summary` (a one-line description of the trace: its latest task's goal, else its stored summary from before summaries were retired, or `null`). Hits that resolve to a specific content block additionally carry `unit_id`, `content_block_index`, `block_type`, `tool_name`, and `chunk_index`. **totals** `object` Exact counts of distinct traces containing a literal (case-insensitive) match for the query — independent of the ranked page. `matched_conversations` covers the requested window; `prior_window_matched_conversations` covers the equal-length window immediately before it (`null` when `time_range=all`). Either can be `null` if the count query timed out — a missing number, never a fabricated zero. These two counts are literal-match counts in every mode, including `semantic` and `hybrid`, so they don't describe the size of a semantic or hybrid result set. The object also carries: * `mode`: the mode that ran (the same value as `search_mode`). * `matched_conversations_basis`: always `literal_substring`. * `candidate_conversations`: the number of distinct traces in the ranked candidate set of the mode that ran, before paging. It comes from a bounded pool, so it isn't a count over all your data. It is `null` when unknown. * `note`: a one-line explanation of the fields above. **pagination** `object` `limit` (requested page size), `returned` (hits in this response), and `has_more` (`true` when the ranked candidate pool held more hits than the page). There is no offset; to see different results, narrow `q`, `time_range`, or `user_id`. ## Example ```bash theme={"dark"} curl "https://moda.dev/api/v1/data/search?q=refund%20policy&mode=hybrid&time_range=7d&limit=2" \ -H "x-api-key: YOUR_MODA_API_KEY" ``` ```json theme={"dark"} { "query": "refund policy", "search_mode": "hybrid", "degrade_reason": "none", "results": [ { "conversation_id": "conv_9f2c41d08ab37e51", "message_index": 6, "role": "user", "timestamp": "2026-08-14T09:31:22", "snippet": "…I already asked about the refund policy twice and the bot keeps linking the same page…", "score": 0.0328, "cluster_id": "node_3", "cluster_name": "Billing and refunds", "conversation_summary": "User asks how to request a refund for an annual plan; agent explains the policy and opens a ticket." }, { "conversation_id": "conv_5d1a7be2c90f4438", "message_index": 12, "role": "assistant", "timestamp": "2026-08-13T18:04:57", "snippet": "Our refund policy allows cancellation within 14 days of purchase…", "score": 0.0312, "cluster_id": null, "cluster_name": null, "conversation_summary": null, "unit_id": "3e8b1c5d9f2a70648e0c3b7a1d5f2946c8a0e3d71f5b2c69a4e8d0b3f7c1a25e", "content_block_index": 0, "block_type": "text", "chunk_index": 0 } ], "totals": { "matched_conversations": 41, "prior_window_matched_conversations": 28, "mode": "hybrid", "matched_conversations_basis": "literal_substring", "candidate_conversations": 63, "note": "matched_conversations counts literal (substring) matches only, not the hybrid results; candidate_conversations is the number of distinct conversations in the hybrid ranked candidate set (a bounded pool, not a corpus count)." }, "pagination": { "limit": 2, "returned": 2, "has_more": true } } ``` To read the turns around the first hit: ```bash theme={"dark"} curl "https://moda.dev/api/v1/data/conversations/conv_9f2c41d08ab37e51/context?msg_index=6&window=2" \ -H "x-api-key: YOUR_MODA_API_KEY" ``` ## Next steps * [Traces](/data-api/traces) — fetch windowed context around any search hit. * [Signals](/data-api/signals) — if you are hunting failures, the frustration and tool-failure endpoints already embed context. * [CLI reference](/cli/reference) — `moda traces search` wraps this endpoint with the same modes. # Signals Source: https://docs.moda.dev/data-api/signals GET /frustrations, /emotions, /tool-failures, /tools, and /hallucinations — signal detections with evidence and embedded trace context. These endpoints read the per-trace signals Moda detects on ingested data: user frustration and other emotions, tool failures, and grounding (hallucination) results. Detections typically appear within minutes of ingest. The same data drives the [Signals dashboard](/dashboard/signals). ## GET /frustrations Frustration detections with evidence, verbatim user quotes, and an embedded context window. Reads the same emotion-engine data as [`/emotions`](#get-emotions) with `family=frustration` (windowed by analysis time), so counts match `/emotions` and the Signals dashboard. ### Query parameters **days_back** `integer` (default: 7) 1–90. **limit** `integer` (default: 10) 1–20. This endpoint's cap is 20, lower than the general 100. **offset** `integer` (default: 0) 0–10,000. **user_id** `string` Scope every figure in the response (summary, signal breakdown, list, and total) to one end user. A detection belongs to the first non-empty `user_id` seen in its trace. An empty value returns `400`. **conversation_id** `string` Scope every figure in the response to one trace. An empty value returns `400`. ### Response fields **summary** `object` `total_analyzed` (traces analyzed in the window), `frustrated_count`, `at_risk_count` (risk score at least 0.5 but not frustrated), `frustration_rate_pct`. **signal_breakdown** `object` Map of frustration signal to count, across frustrated traces only. **frustrations** `array` Frustrated and at-risk traces, ordered by `frustration_score` then `risk_score`. Each row has `conversation_id` (the trace ID), `is_frustrated`, `frustration_score`, `risk_score`, `trajectory`, `target`, `primary_cause`, `evidence`, `user_quotes[]` (`turn`, `quote`, `signal`), `expressed_signals[]`, `observed_signals[]`, `key_turns[]`, `message_count`, `detected_at`, and `conversation` — an embedded context window from the trace (same shape as [`/conversations/:id/context`](/data-api/traces#get-conversationsidcontext)) centered on the first key turn, or `null`. **pagination** `object` `limit`, `offset`, `total`, `has_more`. **processing** `object` `enabled` (`true`, `false`, or `null`), `setting` (`"signals.frustration"`), and optional `reason` (for example `"dogfood_tenant"`). This is the tenant processing switch that gates emotion and frustration analysis. When `enabled` is `false`, no new traces are analyzed, so zero counts mean "not analyzed", not "no frustration". `null` means the setting couldn't be read, so treat zeros as unconfirmed. Missing settings default to enabled. ### Example ```bash theme={"dark"} curl "https://moda.dev/api/v1/data/frustrations?days_back=7&limit=1" \ -H "x-api-key: YOUR_MODA_API_KEY" ``` ```json theme={"dark"} { "summary": { "total_analyzed": 1102, "frustrated_count": 43, "at_risk_count": 18, "frustration_rate_pct": 3.9 }, "signal_breakdown": { "exasperation": 21, "escalation_request": 12, "sarcasm": 7 }, "frustrations": [ { "conversation_id": "conv_9f2c41d08ab37e51", "is_frustrated": true, "frustration_score": 0.86, "risk_score": 0.91, "trajectory": "building", "target": "bot", "primary_cause": "Agent repeated the same help-page link instead of acting on the refund request.", "evidence": "User restated the request three times with escalating language before asking for a human.", "user_quotes": [ { "turn": 6, "quote": "I already asked about the refund policy twice and the bot keeps linking the same page.", "signal": "exasperation" } ], "expressed_signals": ["exasperation", "escalation_request"], "observed_signals": [], "key_turns": [6], "message_count": 18, "detected_at": "2026-08-14T09:44:03", "conversation": { "conversation_id": "conv_9f2c41d08ab37e51", "total_messages": 18, "summary": "", "context": { "center_index": 6, "from_index": 4, "to_index": 8, "messages": [ { "index": 6, "role": "user", "content": "I already asked about the refund policy twice and the bot keeps linking the same page.", "tool_calls": [], "tool_results": [], "timestamp": "2026-08-14T09:31:22" } ] } } } ], "pagination": { "limit": 1, "offset": 0, "total": 61, "has_more": true }, "processing": { "enabled": true, "setting": "signals.frustration" } } ``` ## GET /emotions Multi-family emotion detections. Moda scores seven families, `frustration`, `sadness`, `confusion`, `anxiety`, `trust`, `disapproval` (shown in the dashboard as Redirection) and `positive`, with one detection row per trace and family. The first five are negative; `disapproval` and `positive` never count toward `negative_rate_pct`. See [Signals in the dashboard](/dashboard/signals#emotion-taxonomy) for the full 17-signal taxonomy. ### Query parameters **days_back** `integer` (default: 7) 1–90. **limit** `integer` (default: 10) 1–20. **offset** `integer` (default: 0) 0–10,000. **family** `string` Filter the paginated `detections` list (and its `total`) to one family. The `summary` and `signal_breakdown` always cover all families. Unknown values return `400`. **user_id** `string` Scope every figure in the response (summary, signal breakdown, list, and total) to one end user. A detection belongs to the first non-empty `user_id` seen in its trace. An empty value returns `400`. **conversation_id** `string` Scope every figure in the response to one trace. An empty value returns `400`. **include_context** `string` (default: 1) `0` or `false` skips the embedded trace windows: every detection's `conversation_context` is `null` and the response is much smaller. Use it when paging the list and opening traces separately with `GET /conversations/:id/context`. **cohort** `string` `builtin:` or a saved cohort id; needs `group_by=trace`. The dashboard Signals list's cohort scope: only traces of the cohort's members, in the summary and the list. The cohort's membership snapshot is refreshed first when it is missing or stale, as the dashboard does; an unknown saved cohort id returns `404`, and the response echoes `cohort`. ### Response fields **summary** `object` `conversations_analyzed` (traces analyzed), `by_family` (detected count per family), `negative_rate_pct` (share of analyzed traces with any negative-family detection), `positive_rate_pct`, and `repair_rate_pct` (share of negative detections whose trajectory resolved). **signal_breakdown** `array` `{family, signal, count}` rows across detected traces. **detections** `array` Detected and at-risk rows, ordered by score. Each has `detection_id`, `conversation_id`, `user_id`, `family`, `is_detected`, `score`, `risk_score`, `trajectory`, `elicitor`, `primary_cause`, `evidence`, `user_quotes[]`, `expressed_signals[]`, `observed_signals[]`, `key_turns[]`, `downgrade_reason`, `detection_grade` (`rlm` for deep analyses, `light` for the positive-family fast path), `message_count`, `detected_at`, and `conversation_context` (embedded context window or `null`). **pagination** `object` `limit`, `offset`, `total`, `has_more`, `detected`, `at_risk`. `total` counts detected plus at-risk rows (`is_detected: false`); use `detected` for the detection count. **processing** `object` `enabled` (`true`, `false`, or `null`), `setting` (`"signals.frustration"`), and optional `reason` (for example `"dogfood_tenant"`). This is the tenant processing switch that gates emotion and frustration analysis. When `enabled` is `false`, no new traces are analyzed, so zero counts mean "not analyzed", not "no frustration". `null` means the setting couldn't be read, so treat zeros as unconfirmed. Missing settings default to enabled. ### Example ```bash theme={"dark"} curl "https://moda.dev/api/v1/data/emotions?days_back=7&family=confusion&limit=1" \ -H "x-api-key: YOUR_MODA_API_KEY" ``` ```json theme={"dark"} { "summary": { "conversations_analyzed": 1102, "by_family": { "frustration": 43, "sadness": 4, "confusion": 22, "anxiety": 9, "trust": 6, "positive": 131 }, "negative_rate_pct": 6.8, "positive_rate_pct": 11.9, "repair_rate_pct": 38.1 }, "signal_breakdown": [ { "family": "confusion", "signal": "confusion", "count": 22 }, { "family": "positive", "signal": "gratitude", "count": 87 } ], "detections": [ { "detection_id": "0a6f4c1e-2b7d-4e83-9c50-1f2a3b4c5d6e", "conversation_id": "conv_5d1a7be2c90f4438", "user_id": "user_4821", "family": "confusion", "is_detected": true, "score": 0.74, "risk_score": 0.55, "trajectory": "sustained", "elicitor": "bot", "primary_cause": "Agent used internal integration names the user did not recognize.", "evidence": "User asked what a 'connector token' is twice; the agent did not rephrase.", "user_quotes": [ { "turn": 9, "quote": "Sorry, what is a connector token? Where do I find that?", "signal": "confusion" } ], "expressed_signals": ["confusion"], "observed_signals": [], "key_turns": [9], "downgrade_reason": "", "detection_grade": "rlm", "message_count": 31, "detected_at": "2026-08-13T18:24:10", "conversation_context": null } ], "pagination": { "limit": 1, "offset": 0, "total": 22, "has_more": true }, "processing": { "enabled": true, "setting": "signals.frustration" } } ``` ## GET /tool-failures Per-tool failure KPIs for the window. Only tools with at least one failure are listed. This endpoint has no pagination; use [`/tool-failures/:toolName`](#get-tool-failurestoolname) for examples. ### Query parameters **days_back** `integer` (default: 7) 1–90. **cohort** `string` `builtin:` or a saved cohort id: the dashboard Tool Failures leaderboard for the cohort's traces, read through the page's own loader (`source: "dashboard_tool_failures"`). It counts failures only: `summary` is `total`, `conversations`, `tools`, and each tool carries `top_category` and `failure_family` instead of call totals and failure rates. The cohort's membership snapshot is refreshed first when it is missing or stale, as the dashboard does; an unknown saved cohort id returns `404`, and the response echoes `cohort`. ### Response fields **summary** `object` `total` (failed calls), `total_calls` (all calls), `conversations` (traces with a failure), `tools` (with a failure), `failure_rate_pct`. **tools** `array` Ordered by `failure_count` descending. Each has `tool_name`, `failure_count`, `total_count`, `failure_rate_pct`, `conversation_count` (traces affected), `top_error` (a sample error message, truncated to 80 characters), `last_seen`. ### Example ```bash theme={"dark"} curl "https://moda.dev/api/v1/data/tool-failures?days_back=7" \ -H "x-api-key: YOUR_MODA_API_KEY" ``` ```json theme={"dark"} { "summary": { "total": 67, "total_calls": 5204, "conversations": 51, "tools": 6, "failure_rate_pct": 1.3 }, "tools": [ { "tool_name": "create_ticket", "failure_count": 24, "total_count": 312, "failure_rate_pct": 7.7, "conversation_count": 19, "top_error": "422 Unprocessable Entity: field 'priority' must be one of low, normal, high", "last_seen": "2026-08-14T11:02:36" }, { "tool_name": "calendar_connect", "failure_count": 17, "total_count": 96, "failure_rate_pct": 17.7, "conversation_count": 14, "top_error": "OAuth exchange failed: invalid_grant", "last_seen": "2026-08-14T10:48:01" } ] } ``` ## GET /tool-failures/:toolName Failure detail for one tool: a breakdown by error subtype plus individual examples with embedded trace context. Subtype names come from your tenant's failure taxonomy — they are labels, not a fixed enum. ### Query parameters **subtype** `string` Filter `examples` (and the pagination `total`) to one error subtype. The `subtypes` breakdown is always unfiltered. **days_back** `integer` (default: 7) 1–90. **limit** `integer` (default: 5) 1–20. **offset** `integer` (default: 0) 0–10,000. **include_context** `string` (default: 1) `0` or `false` skips each example's embedded trace window: `conversation` is `null`. ### Response fields **tool_name** `string` **subtypes** `array` `{subtype, count, conversation_count, sample_error, last_seen}` per error subtype. **examples** `array` Newest first. Each has `failure_id`, `conversation_id`, `error_message`, `error_subtype`, `tool_input` (truncated), `msg_index`, `detected_at`, and `conversation` — an embedded context window from the trace centered on the failing call, or `null`. **pagination** `object` `limit`, `offset`, `total`, `has_more`. ### Example ```bash theme={"dark"} curl "https://moda.dev/api/v1/data/tool-failures/create_ticket?days_back=7&limit=1" \ -H "x-api-key: YOUR_MODA_API_KEY" ``` ```json theme={"dark"} { "tool_name": "create_ticket", "subtypes": [ { "subtype": "validation_error", "count": 18, "conversation_count": 14, "sample_error": "422 Unprocessable Entity: field 'priority' must be one of low, normal, high", "last_seen": "2026-08-14T11:02:36" }, { "subtype": "timeout", "count": 6, "conversation_count": 6, "sample_error": "Request timed out after 30000ms", "last_seen": "2026-08-13T22:14:52" } ], "examples": [ { "failure_id": "8c1d2e3f-4a5b-6c7d-8e9f-0a1b2c3d4e5f", "conversation_id": "conv_9f2c41d08ab37e51", "error_message": "422 Unprocessable Entity: field 'priority' must be one of low, normal, high", "error_subtype": "validation_error", "tool_input": "{\"topic\":\"refund\",\"plan\":\"annual\",\"priority\":\"urgent\"}", "msg_index": 7, "detected_at": "2026-08-14T09:31:41", "conversation": { "conversation_id": "conv_9f2c41d08ab37e51", "total_messages": 18, "summary": "", "context": { "center_index": 7, "from_index": 5, "to_index": 9, "messages": [ { "index": 7, "role": "assistant", "content": "", "tool_calls": [{ "id": "toolu_01Xk2m", "name": "create_ticket", "input": "{\"topic\":\"refund\",\"plan\":\"annual\",\"priority\":\"urgent\"}" }], "tool_results": [], "timestamp": "2026-08-14T09:31:40" } ] } } } ], "pagination": { "limit": 1, "offset": 0, "total": 24, "has_more": true } } ``` ## GET /tools The tool catalog: every tool called in the window, failing or not, with the figures of the dashboard Tool catalog (same query). `calls`, `failed_calls`, and `success_rate_pct` count recorded tool receipts. [`/tool-failures`](#get-tool-failures) counts classified tool failures instead, so the two can differ; `metric_note` says so in every response. ### Query parameters **days_back** `integer` (default: 7) 1–90. **sort** `string` (default: calls) `calls`, `failure_rate`, `failures` (failed calls), `traces`, or `last_seen`. All descending; `tool_name` breaks ties. **search** `string` Only tools whose name contains this text (case-insensitive). **direction** `string` Only tools with this effect direction: `read`, `write`, `send`, `spawn`, `compute`, or `unknown`. **limit** `integer` (default: 50) 1–200. **offset** `integer` (default: 0) 0–10,000. ### Response fields **summary** `object` `total_calls`, `unique_tools`, and `total_conversations` (traces with a call) for the window and filters. **tools** `array` Each has `tool_name`, `calls`, `failed_calls`, `success_rate_pct`, `failure_rate_pct`, `conversation_count`, `effect_direction` (the most common), `target_system` (the most common), and `last_seen`. **pagination** `object` `limit`, `offset`, `total` (tools matching), `returned`, `has_more`, and `next_offset` when `has_more` is true. ### Example ```bash theme={"dark"} curl "https://moda.dev/api/v1/data/tools?days_back=7&sort=failure_rate&limit=1" \ -H "x-api-key: YOUR_MODA_API_KEY" ``` ```json theme={"dark"} { "window": { "days_back": 7 }, "filters": { "sort": "failure_rate" }, "summary": { "total_calls": 5204, "unique_tools": 18, "total_conversations": 640 }, "tools": [ { "tool_name": "calendar_connect", "calls": 96, "failed_calls": 17, "success_rate_pct": 82.29, "failure_rate_pct": 17.71, "conversation_count": 61, "effect_direction": "write", "target_system": "calendar", "last_seen": "2026-08-14T10:48:01" } ], "pagination": { "limit": 1, "offset": 0, "total": 18, "returned": 1, "has_more": true, "next_offset": 1 }, "metric_note": "calls and failed_calls count recorded tool receipts, ..." } ``` ## GET /tools/:name One tool from the catalog: call stats, its registered definition and observed payload fields, usage over time, effect profile, top failure categories with the newest failure of each, and recent calls. Returns `404` when the tool has no calls in the window. ### Query parameters **days_back** `integer` (default: 7) 1–90. Under 7 days, `usage` is hourly; otherwise daily. ### Response fields **stats** `object` `calls`, `failed_calls`, `success_rate_pct`, `failure_detections` (classified failures, as in `/tool-failures/:toolName`), `conversation_count`, `user_count`, `first_seen`, `last_seen`, `primary_class_id`, `primary_class_description`. **definition** `object` `registered`: the tool definition registered for this name (`description`, `schema`, `source`, `is_active`, `updated_at`), or `null`. `observed_fields`: keys seen in recorded call inputs, each with `inferred_type`, `call_count`, `call_pct`, and up to 10 `common_values`. Also `payloads_sampled` and `invalid_payloads`. **usage** `array` `{timestamp, calls, failed_calls}` per bucket (see `window.bucket`). **failure_categories** `object` `total_failures`, `categories_total`, and the top 10 `categories`, each with `category` (the `subtype` value of `/tool-failures/:toolName`), `label`, `failure_family`, `likely_cause`, `action_hint`, `count`, `conversation_count`, `sample_error`, `last_seen`, and `latest_failure` (`conversation_id`, `msg_index`, `tool_use_id`, `detected_at`). **tool_classes** `array` Up to 10 recorded classes of use, each with `tool_class_id`, `description`, `effect_direction`, `target_system`, `target_resource`, `calls`, `sample_input`, and `example_inputs`. **recent_calls** `array` The 10 newest calls: `conversation_id`, `msg_index`, `success`, `inputs`, `conversation_timestamp`, and the call's class and target. ### Example ```bash theme={"dark"} curl "https://moda.dev/api/v1/data/tools/create_ticket?days_back=7" \ -H "x-api-key: YOUR_MODA_API_KEY" ``` ```json theme={"dark"} { "tool_name": "create_ticket", "window": { "days_back": 7, "bucket": "day" }, "stats": { "calls": 312, "failed_calls": 22, "success_rate_pct": 92.95, "failure_detections": 24, "conversation_count": 140, "user_count": 121, "first_seen": "2026-08-08T00:02:11", "last_seen": "2026-08-14T11:02:36" }, "definition": { "registered": { "description": "Open a support ticket", "schema": { "type": "object", "properties": { "priority": { "enum": ["low", "normal", "high"] } } }, "source": "MANUAL", "is_active": true, "updated_at": "2026-08-01T10:00:00.000Z" }, "payloads_sampled": 312, "invalid_payloads": 0, "observed_fields": [{ "name": "priority", "inferred_type": "string", "call_count": 312, "call_pct": 100, "common_values": [{ "value": "normal", "count": 190, "pct": 60.9 }, { "value": "urgent", "count": 18, "pct": 5.8 }] }] }, "usage": [{ "timestamp": "2026-08-14 00:00:00", "calls": 51, "failed_calls": 4 }], "failure_categories": { "total_failures": 24, "categories_total": 2, "categories": [ { "category": "validation_error", "label": "Invalid field value", "count": 18, "conversation_count": 14, "sample_error": "422 Unprocessable Entity: field 'priority' must be one of low, normal, high", "last_seen": "2026-08-14T11:02:36", "latest_failure": { "conversation_id": "conv_9f2c41d08ab37e51", "msg_index": 7, "tool_use_id": "toolu_01Xk2m", "detected_at": "2026-08-14T09:31:41" } } ] } } ``` ## GET /hallucinations Hallucinations: agent messages that told the user something the trace shows is false. Each comes from a Problems incident the validator kept as a false statement (`incident_id`); rows from before that change are the earlier grounding checks of agent claims against the trace's world state and tool results, kept as history. > [!NOTE] > > The per-message `detections` list contains only two kinds of rows: `contradicted` (a claim contradicted by evidence) and `verified` (a claim confirmed by evidence). Ungrounded claims — statements with no supporting or contradicting evidence — appear only in the `summary` aggregates and are never listed per message. ### Query parameters **days_back** `integer` (default: 7) 1–90. **limit** `integer` (default: 10) 1–20. **offset** `integer` (default: 0) 0–10,000. **conversation_id** `string` Scope the response — including the `summary` aggregates — to one trace. **kind** `string` `contradicted` or `verified`. Filters the `detections` list and its `total`. **cohort** `string` `builtin:` or a saved cohort id; needs `group_by=trace`. Only traces of the cohort's members, in the summary and the list. The cohort's membership snapshot is refreshed first when it is missing or stale, as the dashboard does; an unknown saved cohort id returns `404`, and the response echoes `cohort`. ### Response fields **summary** `object` Counts across all scored claims: `total_scored`, `contradicted_count`, `verified_count`, `ungrounded_count`, `ungrounded_rate` (0–1), `conversations_scored` (traces scored), `conversations_with_contradiction`, and `rule_breakdown[]` (`{source, rule_id, count}` for contradictions). **detections** `array` Contradicted rows first, then by confidence. Each has `conversation_id`, `message_index`, `unit_id`, `segment_id`, `kind` (`contradicted` or `verified`), `label`, `confidence`, `source`, `rule_id`, `model_id`, `violated_receipt_id` (or `null`), `violated_slot_key`, `violated_thread_id`, `offending_substring`, `evidence_quote`, `cws_high_water_msg_index`, `message_count`, `incident_id`, `detected_at`. `incident_id` names the Problems incident the hallucination comes from; it is `null` for rows from before hallucinations came from validated incidents. **pagination** `object` `limit`, `offset`, `total`. This endpoint does not return `has_more`; page until fewer than `limit` rows come back or `offset + limit >= total`. ### Example ```bash theme={"dark"} curl "https://moda.dev/api/v1/data/hallucinations?days_back=7&kind=contradicted&limit=1" \ -H "x-api-key: YOUR_MODA_API_KEY" ``` ```json theme={"dark"} { "summary": { "total_scored": 412, "contradicted_count": 9, "verified_count": 361, "ungrounded_count": 42, "ungrounded_rate": 0.102, "conversations_scored": 288, "conversations_with_contradiction": 8, "rule_breakdown": [ { "source": "rule", "rule_id": "success_vs_error_receipt", "count": 6 }, { "source": "judge", "rule_id": "", "count": 3 } ] }, "detections": [ { "conversation_id": "conv_9f2c41d08ab37e51", "message_index": 8, "unit_id": "f4a7c09d81e5b3628c1d5a9e0b7f43216d8e2a5c9b0f7e341a6d8c2b5e9f0a73", "segment_id": "c7e5a1d2-4f6b-5a38-9c21-8b0e3d47f6a9", "kind": "contradicted", "label": "CONTRADICT", "confidence": 0.97, "source": "rule", "rule_id": "success_vs_error_receipt", "model_id": "", "violated_receipt_id": "5b8d2f61-3c9a-4e07-b4d8-6f1a2c3e5d90", "violated_slot_key": "", "violated_thread_id": "refund_ticket", "offending_substring": "I've created the ticket for you", "evidence_quote": "create_ticket failed: 422 Unprocessable Entity", "cws_high_water_msg_index": 8, "message_count": 18, "incident_id": null, "detected_at": "2026-08-14T09:47:19" } ], "pagination": { "limit": 1, "offset": 0, "total": 9 } } ``` ## Next steps * [Traces](/data-api/traces) — pull a wider context window around any detection's key turn. * [Problems](/data-api/problems) — signals grouped into ranked root-cause problems. * [Dashboard: Signals](/dashboard/signals) — the same detections with the full emotion and failure taxonomies. # Traces Source: https://docs.moda.dev/data-api/traces GET /conversations for filtered lists of traces, /context for windowed messages, and /world-state for a trace's tasks and facts. These are the Traces endpoints. They read individual [traces](/concepts/data-model#trace): list and filter them, pull a window of messages around a specific turn, and inspect a trace's [world state](/concepts/analysis#world-state). Endpoint paths and field names keep `conversation` / `conversation_id` for backwards compatibility; a `conversation_id` value is the trace ID. ## GET /conversations Lists traces, newest first, with optional text search and structured filters. ### Query parameters **search** `string` Free-text search over trace summaries and message bodies. When `search` is the only filter, results may be relevance-ranked (see `search_mode` below). **cluster_id** `string` Restrict to traces assigned to one use-case cluster node (see [Analytics](/data-api/analytics)). **user_id** `string` Restrict to traces from one end user. **time_range** `string` (default: all) One of `all`, `1h`, `24h`, `3d`, `7d`, `30d`, `90d`. Filters on the trace's last activity. **since** `string` Absolute start, inclusive: an ISO 8601 date or datetime, UTC unless an offset is given. With `since` or `until` set, a trace is listed when it was active during the range: its first message is before the end and its last activity is at or after the start (intersected with `time_range`). With `search`, a trace is listed when a matching message falls inside the range. **until** `string` Absolute end, inclusive; a date-only value covers that whole UTC day. Must not precede `since`; at most 366 days apart. **environment** `string` (default: all) One of `all`, `development`, `staging`, `production`. **world_state** `string` Keyword(s) matched case-insensitively against the trace's world state: the goals and summaries of its tasks and, for a trace the task engine owns, its facts and the user's profile. Comma-separated terms are ANDed. Free text, not `key=value`. Maximum 200 characters. **outcome** `string` (default: any) `any`, `positive`, or `negative`, based on frustration detection. `negative` returns traces with a detected user frustration (detections whose every quote is marked a false positive are excluded); `positive` returns traces with none, including traces the frustration detector has not analyzed yet. **cohort** `string` `builtin:` or a saved cohort id: only traces of the cohort's current members, with the dashboard trace list's own cohort scope. With `search`, the keyword path runs (no hybrid ranking). The cohort's membership snapshot is refreshed first when it is missing or stale, as the dashboard does; an unknown saved cohort id returns `404`, and the response echoes `cohort`. **limit** `integer` (default: 20) 1–100. **offset** `integer` (default: 0) 0–10,000. ### Response fields **conversations** `array` One row per trace. Each row has `conversation_id` (the trace ID), `summary` (its latest task's goal, else its stored summary from before summaries were retired), `message_count`, `first_timestamp`, `last_timestamp`, `duration_ms`, `cluster_id` and `cluster_name` (or `null`), `environment`, `latest_task`, and `task_count`. `latest_task` is the trace's most recent open task, else its most recently updated task (or `null`): `thread_id`, `goal`, `status` (`active`, `resolved`, `cancelled`, or `stale` for idle), `latest_step`, `last_evidence_at`, `first_message_index`, and `last_message_index`. With `search_mode: hybrid`, rows the semantic leg ranked by a task also carry `matched_task` (`segment_id`, `thread_id`, `goal`, `status`, `similarity`). `duration_ms` is the time from the first to the last message. It is `null` when the first or last timestamp is unknown: some imported traces store `1970-01-01T00:00:00`, and replayed history stores placeholder timestamps before 2022 (such as `2020-01-01T00:00:00`). `sort_by=slowest` orders by `duration_ms` and puts rows with unknown durations last. **search_mode** `string` `keyword` or `hybrid`. `hybrid` runs only when `search` is set with no structured filters and semantic search is available; otherwise the deterministic keyword path serves the request. **pagination** `object` `limit`, `offset`, `total`, `has_more`. > [!NOTE] > > When `search_mode` is `hybrid`, `pagination.total` is the size of the relevance-ranked candidate pool, not an exact corpus count. Branch on `search_mode` before treating `total` as an exact figure — in `keyword` mode it is exact. ### Example ```bash theme={"dark"} curl "https://moda.dev/api/v1/data/conversations?time_range=7d&environment=production&outcome=negative&limit=2" \ -H "x-api-key: YOUR_MODA_API_KEY" ``` ```json theme={"dark"} { "conversations": [ { "conversation_id": "conv_9f2c41d08ab37e51", "summary": "User asks how to request a refund for an annual plan; agent explains the policy and opens a ticket.", "message_count": 18, "first_timestamp": "2026-08-14T09:12:03", "last_timestamp": "2026-08-14T09:41:47", "duration_ms": 1784000, "cluster_id": "node_3", "cluster_name": "Billing and refunds", "environment": "production" }, { "conversation_id": "conv_5d1a7be2c90f4438", "summary": "User cannot connect a calendar integration; agent retries the OAuth flow twice without success.", "message_count": 31, "first_timestamp": "2026-08-13T17:55:20", "last_timestamp": "2026-08-13T18:20:44", "duration_ms": 1524000, "cluster_id": "node_17", "cluster_name": "Integrations setup", "environment": "production" } ], "search_mode": "keyword", "pagination": { "limit": 2, "offset": 0, "total": 57, "has_more": true } } ``` ## GET /conversations/:id/context Returns a window of parsed messages centered on one message index. Use it to read the turns around a [search](/data-api/search) hit or a signal's key turn. ### Query parameters **msg_index** `integer` Zero-based index of the center message. Defaults to the middle of the trace. Out-of-range values are clamped to the last message. **window** `integer` (default: 2) Messages to include on each side of the center, 0–5 (larger values are clamped to 5). `0` returns only the center message, plus `summary` and `total_messages`. **metadata_only** `string` `1` (or `true`) returns only `summary` and `total_messages`, with an empty `context.messages` and `metadata_only: true`, without reading any message. ### Response fields **conversation_id** `string` **total_messages** `integer` Total messages stored for the trace. **summary** `string` One-line description of the trace: the goal of its latest task, else its stored summary from before conversation summaries were retired (they are no longer generated). Empty string when the trace has neither yet. **latest_task** `object | null` The trace's most recent open task, else its most recently updated task. Same shape as one entry of `tasks`. **task_count** `integer` How many tasks the trace has. **tasks** `array` The trace's tasks (world-state threads: one per thing the user asked for), open first, then most recently updated, up to 50. Each has `thread_id`, `goal`, `status` (`active`, `resolved`, `cancelled`, or `stale` for idle), `latest_step` (the newest timeline entry), `last_evidence_at`, `first_message_index`, and `last_message_index`. **context** `object` `center_index`, `from_index`, `to_index`, and `messages[]`. Each message has `index`, `role`, `content`, `tool_calls[]` (`id`, `name`, `input` — input is a truncated string), `tool_results[]` (`tool_use_id`, `content` — truncated, `is_error`), and `timestamp`. ### Example ```bash theme={"dark"} curl "https://moda.dev/api/v1/data/conversations/conv_9f2c41d08ab37e51/context?msg_index=6&window=1" \ -H "x-api-key: YOUR_MODA_API_KEY" ``` ```json theme={"dark"} { "conversation_id": "conv_9f2c41d08ab37e51", "total_messages": 18, "summary": "User asks how to request a refund for an annual plan; agent explains the policy and opens a ticket.", "context": { "center_index": 6, "from_index": 5, "to_index": 7, "messages": [ { "index": 5, "role": "assistant", "content": "You can request a refund from the billing page. Would you like me to open a ticket?", "tool_calls": [], "tool_results": [], "timestamp": "2026-08-14T09:28:10" }, { "index": 6, "role": "user", "content": "I already asked about the refund policy twice and the bot keeps linking the same page.", "tool_calls": [], "tool_results": [], "timestamp": "2026-08-14T09:31:22" }, { "index": 7, "role": "assistant", "content": "", "tool_calls": [ { "id": "toolu_01Xk2m", "name": "create_ticket", "input": "{\"topic\":\"refund\",\"plan\":\"annual\"}" } ], "tool_results": [], "timestamp": "2026-08-14T09:31:40" } ] } } ``` ## GET /conversations/:id/world-state Returns the trace's world state as it is now: its tasks (open and finished, each with a timeline; a subtask names its parent task), the facts recorded for it, and the end user's durable cross-trace profile. This is the same data as the World State view on the trace detail page. There is no history of state changes. Tasks and facts come from the task engine for a trace it owns (the response then carries `source: "task_engine"`), and from the task tracker otherwise. Task-tracker traces carry facts only where your workspace's task records state them. > [!NOTE] > > The world-state endpoints return camelCase field names (`hasData`, `segmentIndex`, ...), unlike the snake_case used by the rest of the Data API. ### Query parameters **summary_only** `string` Set to `1` to return `segments` as an empty array and add `segmentSummaries` — per-segment fact summaries (`segmentIndex`, `durableCount`, `topSlots`). Cheaper for a quick existence check. **event_limit** `integer` Retired with the world-state event log: still accepted, and ignored. ### Response fields **hasData** `boolean` `false` when no tasks or facts have been tracked for the trace yet. The response keeps its full shape (empty `segments`); an unknown trace ID answers the same way. **userId** `string | null` The end user the trace belongs to, when known. **userDurableProfile** `object | null` The user's current cross-trace profile: `slots` (map of slot key to `{value, source, ...}`), `updatedAt`, `slotCount`. **conversationWarmstart** `object | null` The durable facts the trace started with, for a trace the task engine owns; `null` otherwise. **source** `string` `task_engine` when the task engine owns the trace; absent otherwise. **segments** `array` The trace's tasks and facts: `segmentIndex`, `segmentId`, `startMsgIdx`, `endMsgIdx`, `slots` (facts), `carryIn`, `openThreads[]` (one per task, every status: `id`, `status` — `open` / `resolved` / `cancelled` / `stale` for idle, `summary`, `goal`, `timeline[]`, `subgoals[]`, and `parent_id` on a subtask), and `slotCounts` (`durable`, `segmentLocal`, `total`). **summary** `object` `segmentCount`, and `lastUpdatedAt`: the latest task-engine pass, or the latest task update. ### Example ```bash theme={"dark"} curl "https://moda.dev/api/v1/data/conversations/conv_9f2c41d08ab37e51/world-state" \ -H "x-api-key: YOUR_MODA_API_KEY" ``` ```json theme={"dark"} { "hasData": true, "userId": "user_4821", "userDurableProfile": { "slots": { "user.plan": { "value": "annual", "source": "user", "msg_index": 2 } }, "updatedAt": "2026-08-14T09:41:50", "slotCount": 1 }, "conversationWarmstart": null, "segments": [ { "segmentIndex": 0, "segmentId": "", "startMsgIdx": 0, "endMsgIdx": 11, "slots": {}, "carryIn": {}, "openThreads": [ { "id": "refund_ticket", "status": "resolved", "summary": "Open a refund ticket for the annual plan", "timeline": [ { "text": "Ticket created", "msg_index": 7, "tool_name": "create_ticket" } ], "subgoals": [] } ], "slotCounts": { "durable": 0, "segmentLocal": 0, "total": 0 } } ], "summary": { "segmentCount": 1, "lastUpdatedAt": "2026-08-14T09:41:50" } } ``` ### GET /conversations/:id/world-state/replay and /snapshot (retired) Both are retired: they folded the world-state event log, which Moda no longer writes. Every request answers `410 Gone` with a JSON body naming what replaces them: ```json theme={"dark"} { "statusCode": 410, "error": "Gone", "code": "world_state_snapshot_retired", "message": "World-state snapshots were retired with the world-state v1 event log they were folded from, which Moda no longer writes. Use GET /api/v1/data/conversations/:conversationId/world-state for the trace's current tasks and facts, and GET /api/v1/data/conversations/:conversationId/context?msg_index=N to read the messages at a turn." } ``` Replay answers the same with `code: "world_state_replay_retired"`. Read the trace's current tasks and facts with `GET /conversations/:id/world-state`, and what happened at a turn with [`GET /conversations/:id/context`](/data-api/traces#get-conversationsidcontext). ## Next steps * [Search](/data-api/search) — find the message index to center a context window on. * [Data model](/concepts/data-model) — what traces, segments, slots, and threads mean. * [Dashboard: Traces](/dashboard/traces) — the same data in the Timeline and World State views. # Harness analysis in CI Source: https://docs.moda.dev/harness/ci-rescan Run harness analysis from your own CI with GitHub Actions OIDC or an API key, instead of the hosted GitHub App path. The default way to keep a harness current is the [Moda GitHub App](/harness/overview): hosted analysis runs on every default-branch push with no CI configuration. Use this page when you want analysis to run inside your own CI instead — either with GitHub Actions OIDC (no long-lived secret) or with an API key (works in any CI system). > [!NOTE] > > `moda harness analyze` is opt-in. Without the `--experimental` flag or the environment variable `MODA_HARNESS_ANALYZE_CLI=1`, the command exits with code 1 and points you to the GitHub App. Every workflow on this page sets `MODA_HARNESS_ANALYZE_CLI: "1"`. ## Option A: GitHub Actions with OIDC `moda harness analyze --github-actions` authenticates with the workflow's GitHub Actions OIDC identity token, exchanged for a short-lived Moda token. No Moda API key is stored in the repository or used on the runner. The command builds a source snapshot on the runner, submits it for hosted analysis, polls for the result, and syncs the graph when permitted. Sync rules: * The harness graph syncs only when the workflow runs **on the default branch**, triggered by a **push** or a manual **`workflow_dispatch`**. * On any other ref or event, the run analyzes but does not sync. * The target workspace is resolved server-side from the repository identity in the OIDC token; the workflow cannot redirect it. Prerequisites: * The repository is connected through the Moda GitHub App (**Settings → Integrations**) with sync mode **GitHub Actions** or **Hosted analysis**. Otherwise the token exchange fails with 403. * The workflow grants `permissions: id-token: write`. * `@moda-ai/cli` 1.23.0 or later (`--github-actions` was added in 1.23.0). ```yaml .github/workflows/moda-sync.yml theme={"dark"} name: Moda Sync on: push: branches: [main] workflow_dispatch: permissions: contents: read # Required so the runner can request a GitHub Actions OIDC token. id-token: write concurrency: group: moda-sync-${{ github.ref }} cancel-in-progress: true jobs: sync: runs-on: ubuntu-latest env: # `moda harness analyze` is opt-in; this workflow drives it directly. MODA_HARNESS_ANALYZE_CLI: "1" steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 22 - name: Analyze and sync the harness (OIDC) run: npx -y --package=@moda-ai/cli@ moda harness analyze --github-actions --yes ``` Replace `` with the current `@moda-ai/cli` release. Pin an exact version rather than `@latest` so CI runs a release you have reviewed. After a successful default-branch run, the updated harness appears under **Harness** in the dashboard. ## Option B: API-key rescan workflow This variant authenticates with a Moda API key instead of OIDC. The commands run anywhere the CLI runs, so it also fits CI systems other than GitHub Actions. ### What the workflow runs Add the workflow file below to your repository. To only rescan when agent-relevant paths change, uncomment its `paths` filter. Each run executes three commands: 1. `moda harness analyze --remote --yes` — builds a safe source snapshot in CI, uploads it to Moda's hosted analysis over your API key, polls until the run completes, and writes the resulting report to `.moda/harness-report.json`. 2. `moda harness approve --yes` — validates the report and writes a non-interactive approval. 3. `moda harness sync --from-report` — uploads the approved graph to your workspace. Analysis itself runs on Moda's side under a Moda-held LLM key, so the workflow needs no LLM credentials — only your Moda API key. ### Repository secrets * `MODA_API_KEY` (required) — an API key (`moda_sk_...`) from **Settings → Ingestion keys**. See [Authentication](/administration/authentication). * `MODA_TENANT_ID` (optional) — keys are bound to a single workspace, so the key alone determines where the harness syncs. This secret only labels the CLI's local configuration and can be omitted. ### The workflow Replace `` with the current `@moda-ai/cli` release. Pin an exact version so CI runs a release you have reviewed. ```yaml .github/workflows/moda-harness-rescan.yml theme={"dark"} name: Moda Harness Rescan on: push: branches: [main] # Optional: scope rescans to agent-relevant paths, e.g. # paths: # - 'src/agents/**' workflow_dispatch: # Least privilege: this job reads the checked-out repo, uploads a safe # source snapshot to Moda over the API key, and syncs the refreshed harness # graph; it never writes back to the repository. permissions: contents: read # One in-flight rescan at a time; newer pushes supersede older runs. concurrency: group: moda-harness-rescan cancel-in-progress: true jobs: moda-harness-rescan: runs-on: ubuntu-latest env: MODA_API_KEY: ${{ secrets.MODA_API_KEY }} MODA_TENANT_ID: ${{ secrets.MODA_TENANT_ID }} # `moda harness analyze` is opt-in (the Moda GitHub App is the default # path); this workflow drives the CLI analyze directly, so it opts in. MODA_HARNESS_ANALYZE_CLI: "1" steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 22 - name: Re-analyze the harness on Moda run: npx -y --package=@moda-ai/cli@ moda harness analyze --remote --yes - name: Approve the refreshed harness report run: npx -y --package=@moda-ai/cli@ moda harness approve --yes - name: Sync the harness graph to Moda run: npx -y --package=@moda-ai/cli@ moda harness sync --from-report ``` ### Behavior notes * **Default branch only.** The workflow runs on pushes to `main` and on `workflow_dispatch`, never on `pull_request`, so unmerged agent changes are never synced. * **Path scoping.** Add `on.push.paths` globs so only pushes touching agent-relevant code trigger a rescan. * **Superseding runs.** The `concurrency` group cancels an in-flight rescan when a newer push lands. * **What leaves your CI.** `harness analyze --remote` uploads a bounded source snapshot: source, configuration, prompt, skill, eval, and deployment files, plus README and AGENTS files. Secret-like paths and symlinks are skipped, and secret-shaped strings are redacted before upload. The snapshot request is capped at 5 MB and the snapshot is deleted after the run. See [Limits](/administration/limits#harness). * **Read-only.** The job has `contents: read` permissions and never writes back to the repository. ## The approval gate Syncing with `moda harness sync --from-report` (option B) requires an explicit approval. The GitHub App hosted path and the OIDC path (option A) do not — in both, the server validates the report and syncs it directly. * `moda harness approve` validates the report first — it refuses to approve a report that fails validation — then writes `.moda/harness-report-approval.json`, bound to the report's hash. Without `--yes` it asks for interactive confirmation. * `moda harness sync --from-report` refuses reports that are not approved. Because the approval is hash-bound, any change to the report after approval requires approving again. * The serialized harness graph is capped at 2 MB on sync; the error message suggests narrowing the analysis root if you hit it. ## Resuming a detached run Remote analysis runs are recorded in `.moda/harness-remote-run.json`. If CI is interrupted mid-poll, `moda harness pull` fetches the finished report for the recorded run (`--run-id` selects a specific run), and `moda harness pull --sync` also syncs it. ## Local analysis Running the analysis on your own machine (`moda harness analyze --experimental`) is experimental. The hosted paths above are the supported way to produce and sync a harness. ## Troubleshooting | Symptom | Fix | | - | - | | `moda harness analyze is disabled: connect the Moda GitHub App...` (exit 1) | Set `MODA_HARNESS_ANALYZE_CLI: "1"` in the workflow env, or pass `--experimental`. | | `GitHub Actions OIDC is unavailable. Ensure the workflow sets permissions: id-token: write.` | Add `id-token: write` to the workflow's `permissions`. | | `Moda OIDC exchange failed (403).` | Connect the repository through the GitHub App in **Settings → Integrations** and set its sync mode to **GitHub Actions** or **Hosted analysis**. | | `Harness report validation failed; cannot approve.` | The report on disk is invalid or stale — re-run `moda harness analyze --remote --yes`. | | `413 Snapshot too large` | The snapshot exceeds 5 MB. Narrow the analysis with `moda harness analyze --path=`. | | `Harness graph is too large to sync` | The serialized graph exceeds 2 MB. Narrow the harness root or split agent roots into separate syncs. | ## Next steps * [Harness overview](/harness/overview) — the hosted GitHub App path and what the dashboard shows. * [Authentication](/administration/authentication) — creating and storing the API key for option B. * [CLI reference](/cli/reference) — flags for the `moda harness` command family. # Harness overview Source: https://docs.moda.dev/harness/overview A harness is a synced map of your agent codebase — agents, tools, prompts, and artifacts — kept current from your GitHub repository. A harness is a synced map of your agent codebase: the runtime agents Moda found in a repository, the artifacts they use (prompts, tools, skills, evals, model configurations), and the relationships between them, with citations back to source files. This page covers what the harness shows in the dashboard and the recommended setup with the Moda GitHub App. ## What you see in the dashboard Open **Harness** in the dashboard sidebar (under Improve). The list page shows every synced harness with its runtime agents, capabilities, open questions, and last sync time. Opening a harness shows five tabs: | Tab | Contents | | - | - | | Map | Interactive topology graph of agents, artifacts, and relationships, with a node inspector | | Inventory | The captured agents and artifacts as a list | | Analysis | The analysis behind the current harness version | | Captured source | The source files the analysis captured | | History | Previous harness versions — each sync creates a new version | Owners and admins can record a correction to a captured node (**Correct capture**); the correction is saved as a new harness version. ## Recommended setup: the Moda GitHub App With the GitHub App installed, the harness stays current without any CI configuration: every push to the repository's default branch triggers a hosted analysis, and the result syncs to your workspace automatically. **1. Connect GitHub** In the dashboard, open **Settings → Integrations** and connect GitHub. Install the Moda GitHub App on the repositories you want analyzed. Managing the integration requires the admin or owner role. **2. Configure the repository** Each connected repository has: * **Sync mode** — `Hosted analysis` (default), `GitHub Actions`, or `Off` (see [Sync modes](#sync-modes)). * **Path scope** (optional) — a path such as `services/agent` that limits analysis to part of the repository, useful in monorepos. * **Sync main branch** — on by default; turn it off to stop analyzing pushes without disconnecting the repository. **3. Push to the default branch** Any push to the default branch triggers an analysis. When it completes, the refreshed harness graph syncs to your workspace and a GitHub Check Run posts on the commit. **4. Verify** You should see: * A Check Run on the latest default-branch commit titled **"Harness mapped — N agents, M artifacts"**, with agent, artifact, and relationship counts, the number of files and bytes analyzed, and a "View the harness in Moda" link. * The repository row in **Settings → Integrations** showing status **Completed** with the analyzed commit SHA. * The harness listed under **Harness** in the dashboard. > [!NOTE] > > Hosted analysis covers only the default branch. Pull requests are not analyzed. ## Sync modes Set per repository in **Settings → Integrations**: | Mode | Behavior | | - | - | | Hosted analysis (default) | Moda analyzes the repository server-side on every default-branch push and syncs the result. No CI setup required. | | GitHub Actions | Analysis runs in your own CI with `moda harness analyze --github-actions`. See [Harness analysis in CI](/harness/ci-rescan). | | Off | No analysis runs for this repository, and re-analysis is disabled. | ## Re-running analysis For repositories in **Hosted analysis** mode: * **From the dashboard** — open **Settings → Integrations** and click **Analyze now** on the repository row. * **From GitHub** — the Check Run has a **Re-analyze** action button. Analysis run statuses shown in Settings → Integrations: **Queued**, **Running**, **Completed**, **Failed**, and **Superseded** (replaced by a newer analysis). ## What Moda reads Analysis works from a bounded snapshot of the repository: source, configuration, prompt, skill, eval, and deployment files, plus README and AGENTS files. Secret-like paths (`.env` files, private keys) and symlinks are skipped, dependency and build directories are excluded, and secret-shaped strings are redacted before analysis. If a repository exceeds the snapshot size limits, the analysis proceeds on the truncated snapshot and the Check Run notes the truncation. See [Limits](/administration/limits#harness) for the exact caps. ## Next steps * [Harness analysis in CI](/harness/ci-rescan) — run the analysis in your own GitHub Actions or other CI instead of the hosted path. * [Authentication](/administration/authentication) — create the API key used by the API-key CI variant. * [CLI reference](/cli/reference) — the `moda harness` command family. ## Workspace permissions | Action | Viewer | Admin | Owner | | - | - | - | - | | Manage the GitHub integration and re-run harness analysis | — | Yes | Yes | | Correct a harness capture | — | Yes | Yes | ## Harness | Limit | Value | Behavior | | - | - | - | | Source snapshot upload | 5 MB | Analysis request rejected with `413` — narrow with `moda harness analyze --path=` | | Serialized harness graph on sync | 2 MB | Sync refuses with an error suggesting a narrower analysis root | | Snapshot per-file size | 512 KB | Larger files are skipped | | Snapshot file count | 12,000 files | Analysis proceeds on a truncated snapshot; the GitHub Check Run notes the truncation | | Snapshot total text | 48 MB | Same truncation behavior | # Register a harness for Replay Environments Source: https://docs.moda.dev/harness/registration Bundle your agent repository with moda harness register so Moda can run your real harness in a sandbox with outbound network denied. A Replay Environment runs your real agent harness, not a reconstruction of it, in a sandbox where outbound network is denied. Databases and queues run as disposable local services, external APIs are answered by emulators or recorded fixtures, and model calls go to an approved inference lane. To build one, Moda needs your code. `moda harness register` collects it, shows you exactly what it collected, and uploads it. This is the runnable counterpart to [`moda registry`](/harness/registry), which describes your agents, prompts, and tools. Do both. A registration links to the registry harness version that was current when you registered. ## Preview the bundle ```bash theme={"dark"} moda harness register --dry-run ``` A dry run uploads nothing and needs no API key. It prints: * **Included**: file and byte counts by category (source, lockfiles, package manifests, deploy config, containers, migrations, tests, prompts, and so on). * **Excluded**: every path left out, with the reason. The contents of these paths never leave your machine. * **Git-ignored but present**: other ignored paths, by name only, in case a build needs them. * **Environment variables**: every name found in code and example files, with a proposed classification. Values are never read. * **Runtimes, dependencies, and migrations**: what the harness runs on, the services it calls with the adapter Moda proposes for each, and the migrations it would run. * **Gaps**, and **what Moda will still need from you**. The manifest and dependency map are written to a temporary directory named in the report, so you can read exactly what would be sent. ## What is collected The bundle is the whole git repository the harness lives in, including uncommitted and untracked files. The policy is to take more than a build needs: Moda can shrink a bundle later, but it can't recover files that were never sent. | Left out | Reason recorded | | - | - | | `.env`, `.env.*` (except `.env.example` and similar), `*.pem`, `*.key`, `id_rsa`, `.npmrc`, `.netrc`, service account files | `secret_path`: the file is never opened | | Files whose contents match a credential rule (cloud keys, private keys, provider API keys) | `secret_content`: the rule name is recorded, never the match | | `.git`, `.hg`, `.svn` | `vcs_internal` | | Git-ignored `node_modules`, `.venv`, and other installs a lockfile reproduces | `dependency_install` | | Git-ignored caches and build output (`dist`, `.next`, `__pycache__`, `.turbo`) | `regenerable_output` | | Files over the size budget | `size_limit` | | Symlinks that point outside the repository | `symlink_escape` | | Paths listed in `.modaignore` (gitignore-style patterns) | `user_exclude` (rule `modaignore`) | | Personal editor and agent config: `.vscode/`, `.idea/`, `.claude/settings.local.json`, `CLAUDE.local.md`, and uncommitted files under `.cursor/` or `.claude/` | `user_exclude` (rule `personal_config`) | | Files git ignores only through your global gitignore (`core.excludesFile`) or `.git/info/exclude` | `user_exclude` (rules `global_gitignore`, `info_exclude`) | ## Declare how it runs Tell Moda how the harness starts and which env vars route its model calls. Pass env var names, never values. ```bash theme={"dark"} moda harness register support-agent \ --model-base-url-env=OPENAI_BASE_URL \ --model-env=OPENAI_MODEL \ --model-api-key-env=OPENAI_API_KEY \ --entry -- node dist/server.js ``` `--entry` takes everything after `--` as the command, so put it last. `--entry="node dist/server.js"` also works. | Flag | Purpose | | - | - | | `[name]` | Harness name. Defaults to the `package.json` name, then the directory name. | | `--root=` | Directory of the harness inside the repository. Defaults to the current directory. | | `--mode=source\|sealed` | `source` (default) builds from the uploaded source. `sealed` runs an image you built; pass `--image=@sha256:`. | | `--entry -- ` | The command that starts the harness the way production does. | | `--model-base-url-env`, `--model-env`, `--model-api-key-env` | Env var names for the model base URL, model id, and API key. | | `--dry-run` | Collect and report only. | | `--json` | Machine-readable report. | ## Register Run the same command without `--dry-run`. The CLI uploads the bundle, manifest, and dependency map straight to Moda's object storage on short-lived presigned URLs (your API key is not sent with them). Moda then checks each upload's sha256 and size, analyzes it, and prints the registration id, status, and a dashboard link. ```bash theme={"dark"} moda harness registration status moda harness registration list ``` | Status | Meaning | | - | - | | `uploading` | Created; uploads not yet verified. | | `analyzing` | Uploads verified; Moda is computing the checklist. | | `needs_input` | The checklist has blocking items for you. | | `ready` | Nothing blocks building the environment. | | `compiling`, `validating` | Building the environment and smoke-booting it. | | `failed` | Analysis or the build failed; the reason is shown. | | `retired` | Deleted. The bundle bytes are removed and only a tombstone remains. | ## The checklist Open the registration in the dashboard to work through what Moda still needs: * **Env var classifications**: confirm or correct each proposed classification (`secret`, `config`, `dependency_endpoint`, `model_endpoint`, `model_credential`). Only names Moda could not classify block. * **Dependency adapters**: approve or reject the adapter proposed for each dependency (a real local engine, a provider emulator, a receipt-compiled simulator, a recorded fixture, or remote staging), or pick another. * **Migrations**: approve running them against a disposable database. * **Entrypoint and model routing**: when they were not declared and could not be detected. * **Gaps**: things the detector knows it could not resolve, and, after a smoke boot, files, env vars, or network calls the harness needed but did not have. Decisions are kept when Moda re-analyzes the same registration. ## Declare harnesses in `.moda/registration.json` Commit `.moda/registration.json` to tell Moda how each harness in the repository runs, without passing flags. The Moda GitHub App reads it on every registration. Each entry takes the same values as the CLI flags, and env var names only, never values. ```json .moda/registration.json theme={"dark"} { "schema": "moda_harness_registration.v1", "harnesses": [ { "name": "support-agent", "root": "apps/agent", "entrypoint": ["node", "dist/server.js"], "modelRouting": { "baseUrlEnv": "OPENAI_BASE_URL", "modelEnv": "OPENAI_MODEL", "apiKeyEnv": "OPENAI_API_KEY" } }, { "name": "billing-agent", "root": "apps/billing", "entrypoint": "python -m billing.server" } ] } ``` | Key | CLI equivalent | Notes | | - | - | - | | `name` | `[name]` | Required, and unique, when the file lists several harnesses. With one harness, optional: defaults to the root's `package.json` name, then the directory name (the repository name for `.`). 1-128 letters, digits, `.`, `_`, `-`. | | `root` | `--root` | Optional, default `.`. A path inside the repository; each root is one harness, so a monorepo can list several. | | `mode` | `--mode` | `source` (default) or `sealed`. | | `image` | `--image` | Sealed mode: `@sha256:`. | | `entrypoint` | `--entry` | The command, as an array of arguments or a string split on whitespace. | | `modelRouting.baseUrlEnv`, `.modelEnv`, `.apiKeyEnv` | `--model-base-url-env`, `--model-env`, `--model-api-key-env` | Env var names. | A file with a single harness can put its keys at the top level instead of under `harnesses`. Unknown keys are errors, so a typo is reported instead of ignored. Without the file, the App registers one harness at the repository root, and the checklist's entrypoint and model-routing items ask for what was not declared (detected entrypoints are proposed). ## Register from the GitHub App When the [Moda GitHub App](/harness/overview) is connected, Moda registers the repository the same way `moda harness register` does: the same bundle format, detector, checklist, and dashboard. The App downloads the commit's files from GitHub (only committed files, so local secrets such as `.env` or `.dev.vars` never exist there), collects them as committed content, and records the commit, branch, and remote from GitHub. Secret scanning and in-place redaction run exactly as in the CLI. On a clean clone of the same commit, the CLI and the App produce the same files and dependency map. It registers: * once when the App is installed, for each repository; * on every push to the default branch that changes files, for every harness: each registration bundles the whole repository, so a change anywhere (including code one harness imports from another's directory) can change any of them. A commit already registered with the same bundle bytes (a redelivered event, or an install and a push of the same head) is not registered twice; * when you choose **Re-register from GitHub** on the registrations page; * from GitHub Actions: exchange the workflow's OIDC token at `POST https://moda-github.modas.workers.dev/gha/exchange` (as `moda harness analyze --github-actions` does), then call `POST /gha/register` with the returned token from a default-branch push or `workflow_dispatch`. Registrations from the App show **GitHub App** and the commit in the list. A registration that could not be made (the download failed, `.moda/registration.json` is invalid, a root does not exist, the bundle is over the size limit) appears as `failed` with the reason. Each installation can start a limited number of registrations per hour. ## Have your coding agent do it `moda registry prompt` prints the brief for your coding agent. Its last part runs `moda harness register --dry-run`, reviews the exclusions and gaps with you, declares the entrypoint and model routing, and registers once you approve. # Register your harness Source: https://docs.moda.dev/harness/registry Have your coding agent describe your agents, prompt switching, tools, skills, and injected context with moda registry. `moda registry` lets your own coding agent (Claude Code, Codex, Cursor) describe how your agent runs from your codebase: which agents answer, with which prompt versions, models, sampling settings, tools, and skills, how control moves between agents, and what context your code injects into the prompt. You don't need the GitHub App or a repo upload. ## Hand it to your coding agent ```bash theme={"dark"} moda registry prompt | pbcopy # or: claude "$(moda registry prompt)" ``` The brief walks your agent through these steps: 1. Inventory every LLM call site. 2. Work out how the harness switches prompts. 3. List the context it injects. 4. Write `.moda/registry.json`, then validate and push it. 5. Make your traces name the agent and prompt version on each call. It shows you the diff first. 6. Check the result with `moda registry coverage`. ## What gets registered | Section | What it captures | | - | - | | `prompts` | Prompt text, templates, few-shot `messages`, `modelConfig` | | `tools` | OpenAI function schemas, verbatim | | `skills` | SKILL.md files | | `agents` | Prompt, model and params, tools, skills, handoffs, subagents, trace names | | `routing` | `single`, `handoff`, `router`, `rules`, or `trace_attribute`, plus a default agent | | `context` | Static values, the clock, and per-user, memory, retrieval, or tool context | | `runtime` | Framework, tool rounds per turn, history policy, skill loading | | `mcpServers` | Server names, transports, and tools (no credentials) | ## Name the agent on each call Each LLM call in your traces should say which agent and prompt made it. The agent name (`gen_ai.agent.name` or `moda.agent_name`) is matched against each registered agent's `key`, `name`, and `match.agentNames`, and the prompt key (`moda.prompt_key`) against each agent's `prompt` and `match.promptKeys`. Auto-instrumented OpenAI and Anthropic calls don't carry this, so add it where you build each agent or make each call: | What | OTel span attribute | Vercel AI SDK `experimental_telemetry.metadata` | `/v1/ingest` event field | | - | - | - | - | | Agent | `gen_ai.agent.name` or `moda.agent_name` | `moda.agent_name` | `agent_name` | | Prompt key | `moda.prompt_key` | `moda.prompt_key` | `prompt_name` | | Prompt version | `moda.prompt_version_id` | `moda.prompt_version_id` | `prompt_version_id` | See [Prompt attribution](/prompt-management/attribution) for full examples. ## History: every push is a commit Each successful `moda registry push` records a commit. A commit is a snapshot of everything registered, rendered as files: * `agents/.json` * `prompts/.md` * `tools/.json` * `skills//SKILL.md` * `harness/routing.json`, `harness/runtime.json`, `harness/context.json` and `harness/mcp-servers.json` Each commit also records your repo's git SHA, branch, and whether the checkout had uncommitted changes. Label a push with `--message`. ```bash theme={"dark"} moda registry push --message="Add billing agent" moda registry log # one commit per push moda registry show 3f9a2c1 # that commit's file diffs moda registry show working # changes since the last push ``` The dashboard **Registry** page shows the same history, git-style: * the commit log; * per-file diffs for any commit, or for a range (shift-click a second commit); * a file browser for any commit; * **uncommitted changes**: edits made outside a push, such as dashboard tool edits, MCP discovery, or `moda prompts sync`. Admins can commit them from the page. ## Check coverage ```bash theme={"dark"} moda registry status # registered harness and its version moda registry coverage --days=7 # recent production vs the registry ``` `coverage` reports: * the share of recent LLM calls that resolve to a registered agent; * agent names and prompt keys seen in traces that no agent claims; * tools used in production but not registered; * registered agents never seen. ## Run the real harness The registry describes your harness; it doesn't contain it. To have Moda run your actual code in a sandbox (Replay Environments), also register the repository with `moda harness register`. See [Register a harness for Replay Environments](/harness/registration). # Introduction Source: https://docs.moda.dev/index Infrastructure for catching AI agent mistakes in production and turning them into evals. Infrastructure for catching AI agent mistakes in production and turning them into evals. A trace is the full record of one agent run — every message, tool call, thinking block, and step — whether or not a human is in the loop. You send traces through the Python or Node.js SDK, OpenTelemetry, or the HTTP Ingestion API. Moda analyzes every trace automatically — grouping it into use-case clusters and detecting user emotion, tool failure, laziness, and hallucination signals, which are rolled up into problems — and you explore the results in the dashboard or query them with the Data API and CLI. ## The three surfaces ### Ingestion The Ingestion API accepts trace data from the Moda SDKs for Python and Node.js, which auto-instrument the OpenAI and Anthropic client libraries, and from any OpenTelemetry setup that exports OTLP over HTTP, or a direct HTTP call. Integrations also cover the [Vercel AI SDK](/ingestion/vercel-ai-sdk), the [Claude Agent SDK](/ingestion/claude-agent-sdk), and providers such as OpenRouter, Azure OpenAI, Bedrock, Vapi, and OpenClaw. Start with the [ingestion overview](/ingestion/overview) or the [quickstart](/quickstart). ### Dashboard The dashboard at [moda.dev/dashboard](https://moda.dev/dashboard) is where you read the analysis: browse [traces](/dashboard/traces) with a full timeline and world state, review [signals](/dashboard/signals) and [problems](/dashboard/problems), and explore [use cases](/dashboard/use-cases), users, and tools. The [dashboard overview](/dashboard/overview) describes each section. ### Data API & CLI Everything the dashboard shows is also queryable. The [Data API](/data-api/overview) is an HTTP API at `https://moda.dev/api/v1/data`, authenticated with your API key. The [CLI](/cli/overview) (`@moda-ai/cli`, binary `moda`) brings search, analytics, signal and Problem investigation (emotions, hallucinations, Problem dossiers, world state), live tailing, and fix workflows to your terminal and CI. The hosted [MCP server](/mcp/overview) exposes the same commands as MCP tools, so Claude Code, Cursor, or any MCP client can query your production data directly. ## How data flows 1. Your application sends traces to the Ingestion API — through an SDK, an OpenTelemetry exporter, or a direct HTTP request. 2. Moda processes new data within minutes; traces appear on the Traces page shortly after ingest. 3. Emotion, tool-failure, laziness, and hallucination signals appear within minutes, and problems and use-case clusters build automatically as evidence accumulates. ## Getting access Moda is invite-only. Sign up at [moda.dev/signup](https://moda.dev/signup) and request access. Once the Moda team approves your request, it creates your workspace with you as its owner, emails you, and onboarding starts at your next sign-in. Teammates join an existing workspace by invitation (**Settings → Members & roles**). To send data you need an API key (called an ingestion key in the dashboard): create one at **Settings → Ingestion keys**. The full key is shown once, at creation. ## Next steps * [Quickstart](/quickstart) — send your first trace and see it in the dashboard. * [Ingestion overview](/ingestion/overview) — choose the right way to send data for your stack. * [Data model](/concepts/data-model) — how traces, signals, problems, and use cases relate. * [Data API overview](/data-api/overview) — query your data programmatically. # Claude Agent SDK Source: https://docs.moda.dev/ingestion/claude-agent-sdk Install moda-claude-agent-sdk to capture Claude Agent SDK runs with prompts, responses, token usage, and tool-call counts. `moda-claude-agent-sdk` is a separate PyPI package that instruments the Claude Agent SDK (`claude-agent-sdk`) for Python. The Claude Agent SDK runs Claude Code as a subprocess rather than calling the Anthropic API from your process, so the Anthropic instrumentation in `moda-ai` never sees those calls — this package wraps `ClaudeSDKClient` directly instead. It is Python only; there is no Node.js equivalent. ## Prerequisites * Python 3.10 or later * The `moda-ai` and `claude-agent-sdk` packages * A Moda API key, created at **Settings → Ingestion keys** (see [Authentication](/administration/authentication)) ## Set up **1. Install all three packages** ```bash theme={"dark"} pip install moda-ai moda-claude-agent-sdk claude-agent-sdk ``` `moda-claude-agent-sdk` is not bundled with `moda-ai` — it must be installed explicitly. **2. Initialize Moda and run the agent** Call `moda.init()` before constructing `ClaudeSDKClient`. No other wiring is needed: `moda.init()` activates the instrumentation automatically when both packages are installed. ```python agent.py theme={"dark"} import asyncio import os import moda from claude_agent_sdk import ClaudeAgentOptions, ClaudeSDKClient moda.init(os.environ["MODA_API_KEY"]) moda.conversation_id = "session_8f2a" moda.user_id = "user_1042" async def main() -> None: options = ClaudeAgentOptions(model="claude-sonnet-4-20250514") async with ClaudeSDKClient(options=options) as client: await client.query("What is the capital of France?") # Consume the full stream — the final ResultMessage carries token usage async for message in client.receive_response(): print(message) asyncio.run(main()) moda.flush() ``` **3. Verify in the dashboard** Open **Traces** in the [dashboard](https://moda.dev/dashboard). Within minutes you should see a trace with ID `session_8f2a` containing your prompt as a user message and the agent's replies as assistant messages, with token counts attached. ## How it works The package wraps two methods on `ClaudeSDKClient`: * `query()` — captures the prompt. * `receive_response()` — wraps the returned async generator; messages pass through unchanged while token usage, completions, tool-call counts, and agent metadata accumulate. Each `query()` / `receive_response()` cycle produces one span (`claude_agent.chat`) carrying the prompt, the assistant completions from that run, token usage, and agent metadata. Prompt content is captured up to 4,000 characters and each assistant completion up to 8,000 characters. > [!WARNING] > > Token usage comes from the `ResultMessage` at the end of the stream. If your code breaks out of `receive_response()` early, the run is still recorded but token counts are missing. Always consume the generator to completion. With `ClaudeAgentOptions(include_partial_messages=True)`, usage is also accumulated from streaming events as a secondary source. ## Trace grouping Each agent run produces its own OpenTelemetry trace, so without an explicit trace ID — the `conversation_id` field — every run lands in its own Moda trace. Set `moda.conversation_id` (or use the `with moda.set_conversation_id(...)` context manager) before running the agent so that multi-turn sessions group into one trace: ```python multi_turn.py theme={"dark"} import asyncio import os import moda from claude_agent_sdk import ClaudeAgentOptions, ClaudeSDKClient moda.init(os.environ["MODA_API_KEY"]) async def main() -> None: options = ClaudeAgentOptions(model="claude-sonnet-4-20250514") # All queries in this block share one trace with moda.set_conversation_id("session_8f2a"), moda.set_user_id("user_1042"): async with ClaudeSDKClient(options=options) as client: await client.query("What is the capital of France?") async for message in client.receive_response(): print(message) await client.query("What is its population?") async for message in client.receive_response(): print(message) asyncio.run(main()) moda.flush() ``` The agent's own session ID is recorded as the `claude_agent.session_id` attribute, but it is not used for trace grouping — only `moda.conversation_id` is. ## What gets captured | Attribute | Contents | | - | - | | `gen_ai.request.model` | Model requested via `ClaudeAgentOptions` | | `gen_ai.response.model` | Model reported in the response | | `gen_ai.usage.input_tokens` | Input tokens, including cache-read and cache-creation tokens | | `gen_ai.usage.output_tokens` | Output tokens | | `llm.usage.total_tokens` | Input plus output tokens | | `claude_agent.num_turns` | Number of turns in the run | | `claude_agent.session_id` | The agent's session identifier | | `claude_agent.tool_call_count` | Tool-use blocks counted across the run | | `moda.conversation_id`, `moda.user_id` | Your trace ID and user context, when set | Streaming partial messages (`include_partial_messages=True`) and tool use are captured; assistant text streamed in deltas is assembled per turn. ## Troubleshooting | Symptom | Fix | | - | - | | No data appears | Install `moda-claude-agent-sdk` explicitly (it is not part of `moda-ai`), call `moda.init()` before constructing `ClaudeSDKClient`, and call `moda.flush()` before the process exits. | | Token counts are missing | The stream was not consumed to completion — iterate `receive_response()` until it is exhausted, or enable `include_partial_messages=True`. | | Every turn is a separate trace | No explicit trace ID was set. Set `moda.conversation_id` before running the agent. | ## Next steps * [Moda SDK for Python](/ingestion/python) — init options, environment variables, and context APIs. * [Anthropic](/ingestion/providers/anthropic) — auto-instrumentation for direct Anthropic API calls. * [Traces](/dashboard/traces) — how agent runs appear in the dashboard. * [Data model](/concepts/data-model) — how traces, messages, and signals relate. # Ingestion API Source: https://docs.moda.dev/ingestion/http-api HTTP reference for the Moda Ingestion API: authentication, POST /v1/ingest, POST /v1/ingest/multi, and POST /v1/traces. The Ingestion API accepts trace data over plain HTTP. A trace is one full agent run, identified by the `conversation_id` field (the trace ID); the field keeps its name for backwards compatibility. Use it when your language has no Moda SDK, when data originates outside your application process (backfills, message queues, webhook consumers), or when you need channel formats such as email and call transcripts. ## Base URL ``` https://moda-ingest.modas.workers.dev ``` All endpoints live under this host. There is no path-level versioning beyond the `/v1` prefix. ## Authentication Every endpoint except `GET /health` requires an API key (called an ingestion key in the dashboard) in the `Authorization` header: ``` Authorization: Bearer moda_sk_... ``` Keys are created at **Settings → Ingestion keys** and are shown once at creation. A key is bound to your tenant and cannot be re-pointed. See [Authentication](/administration/authentication) for key management and revocation. Requests with a missing or invalid key return `401`. The `message` field names the failure — `Missing Authorization header` when the header is absent, `Invalid or expired API key` otherwise: ```json theme={"dark"} { "success": false, "count": 0, "message": "Invalid or expired API key", "requestId": "550e8400-e29b-41d4-a716-446655440000" } ``` > [!NOTE] > > The `Bearer ` prefix is optional: a bare key in the `Authorization` header is also accepted. CLI session tokens are not valid here — only `moda_sk_` API keys. ## Request IDs You can send an optional `X-Request-ID` header on any request. If the value is a valid UUID, it is echoed back as `requestId` in the JSON response; otherwise the server generates a random UUID. Use it to correlate requests, responses, and retries in your own logs. ```bash theme={"dark"} curl https://moda-ingest.modas.workers.dev/v1/ingest \ -H "Authorization: Bearer YOUR_MODA_API_KEY" \ -H "X-Request-ID: 3f1c9a52-8f6e-4b0d-9c3a-2d7e5b1a4c88" \ -H "Content-Type: application/json" \ -d '{"events": []}' ``` ## GET /health Health check. No authentication. Returns `200` with the plain-text body `ok`. ```bash theme={"dark"} curl https://moda-ingest.modas.workers.dev/health ``` ``` ok ``` ## POST /v1/ingest Sends trace events as simple JSON. Each event is one message in a trace. Events with the same `conversation_id` are grouped into one trace. ### Request body **environment** `string` Environment for all events in the request. Must be exactly `development`, `staging`, or `production` (defaults to `production`); any other value is rejected with `400`. Individual events can override it with their own `environment` field. **events** `array` Up to 1,000 events per request. An empty or absent array returns `200` with `count: 0` and the message `No events provided`. ### Event fields **conversation_id** `string` *required* The trace ID this event belongs to. Events sharing a `conversation_id` form one trace. **role** `string` *required* Who produced the message — typically `user`, `assistant`, or `system`. Events with role `assistant` are recorded as model output; all other roles are recorded as input to the model. **message** `string` The message text. Used when `content` and `content_blocks` are absent. **content** `string | array` The message content, either as a string or as an array of content blocks (see below). If both `content` and `message` are present, `content` takes precedence. **content_blocks** `array` Structured content blocks for tool use, extended thinking, or images (see below). Used when `content` is absent. **timestamp** `string` ISO 8601 date-time of the event, for example `2026-08-16T10:30:00Z`. Defaults to the time the event is received. A `timestamp` that is present but unparseable is rejected with `400`. **trace_id** `string` Optional OpenTelemetry-style trace ID stored on the event. Defaults to `conversation_id`. Grouping into a Moda trace is by `conversation_id`, not this field. **user_id** `string` Identifier for the end user of the trace. **input_tokens** `number` Prompt (input) tokens used by the generation. Assistant events. **output_tokens** `number` Completion (output) tokens used by the generation. Assistant events. **reasoning_tokens** `number` Tokens used for extended thinking or reasoning output. **cache_read_tokens** `number` Prompt tokens served from the provider's cache. **cache_creation_tokens** `number` Prompt tokens written to the provider's cache. **model** `string` Model ID, for example `gpt-4o` or `claude-sonnet-4-20250514`. **provider** `string` Provider name, for example `openai` or `anthropic`. **finish_reason** `string` Why the model stopped generating, for example `stop`, `length`, or `tool_calls`. Assistant events. **prompt_id** `string` Optional prompt ID attached to the event. **prompt_name** `string` Name of the managed prompt used for this generation. **prompt_version** `string` Version of the managed prompt used for this generation. **prompt_version_id** `string` Moda prompt version ID, from `.moda/prompts.lock.json`. **agent_name** `string` In multi-agent systems, the agent that authored this event. **external_message_id** `string` Your own stable, unique ID for this message. **environment** `string` Per-event override of the request-level environment. Common aliases are normalized (`dev`/`develop` → `development`, `stg`/`stage` → `staging`, `prod` → `production`); unrecognized values fall back to `production`. > [!NOTE] > > Events carrying a `messageType` field are rejected with `400`. Channel-specific events (chat platforms, email, calls, tool invocations) belong on `POST /v1/ingest/multi`. ### Content blocks Use content blocks (in `content` or `content_blocks`) when a message contains more than plain text: | Block `type` | Fields | Description | | - | - | - | | `text` | `text` | Plain text | | `thinking` | `text` | Model reasoning (extended thinking) | | `tool_use` | `tool_name`, `tool_use_id`, `input` | Tool or function call issued by the model | | `tool_result` | `tool_use_id`, `content`, `is_error` | Result returned by a tool | | `image` | `source` (`{type, media_type?, data?, url?}`) | Image content (base64 or URL) | Every block accepts an optional numeric `index` (defaults to the block's position in the array). Anthropic API field names are also accepted: `name` is normalized to `tool_name`, `id` to `tool_use_id`, and a `thinking` field on thinking blocks to `text`. ```json theme={"dark"} { "conversation_id": "conv-abc123", "role": "assistant", "content_blocks": [ {"type": "text", "text": "Let me look that up."}, {"type": "tool_use", "tool_name": "web_search", "tool_use_id": "toolu_01", "input": {"query": "refund policy"}} ] } ``` ### Example ```bash theme={"dark"} curl https://moda-ingest.modas.workers.dev/v1/ingest \ -H "Authorization: Bearer YOUR_MODA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "environment": "production", "events": [ { "conversation_id": "conv-abc123", "role": "user", "message": "What is the capital of France?", "timestamp": "2026-08-16T10:30:00Z", "user_id": "user-789", "external_message_id": "msg-001" }, { "conversation_id": "conv-abc123", "role": "assistant", "message": "The capital of France is Paris.", "timestamp": "2026-08-16T10:30:01Z", "model": "gpt-4o", "provider": "openai", "input_tokens": 12, "output_tokens": 8, "cache_read_tokens": 0, "finish_reason": "stop", "agent_name": "support-bot", "external_message_id": "msg-002" } ] }' ``` Success response: ```json theme={"dark"} { "success": true, "count": 2, "requestId": "550e8400-e29b-41d4-a716-446655440000" } ``` Validation errors return `400` with a message naming the first failing event; nothing from the batch is stored: ```json theme={"dark"} { "success": false, "count": 0, "message": "Event 0: missing or invalid 'conversation_id'", "requestId": "550e8400-e29b-41d4-a716-446655440000" } ``` Temporary ingestion outages return `503` with `retryable: true`: ```json theme={"dark"} { "success": false, "count": 0, "message": "Queue temporarily unavailable", "requestId": "550e8400-e29b-41d4-a716-446655440000", "retryable": true } ``` The full status-code table and retry guidance are on the [Reliability](/ingestion/reliability) page. ## POST /v1/ingest/multi Ingests traces that span channels: chat platform messages, tool invocations, emails, and call transcripts. Each event declares its shape with `messageType`. ### Common event fields **id** `string` *required* Your stable, unique ID for the event (non-empty). It becomes the event's `external_message_id`. **messageType** `string` *required* One of `channel`, `tool_call`, `email`, or `call`. **conversationId** `string` *required* Trace ID (session or thread ID) that groups events into one trace, required for all four event types. **userId** `string` Identifier for the end user. **timestamp** `string` ISO 8601 date-time. Defaults to the time the event is received. **metadata** `object` Free-form object. Accepted, but its contents are not currently attached to the stored message. The request body has the same envelope as `/v1/ingest`: an optional request-level `environment` plus an `events` array of up to 1,000 events. ### Type-specific fields **`channel`** — a message in a chat or messaging platform: | Field | Type | Required | Description | | - | - | - | - | | `message` | string | Yes | Message content (may be an empty string) | | `role` | string | Yes | `user`, `assistant`, or `system` | **`tool_call`** — a tool or function invocation: | Field | Type | Required | Description | | - | - | - | - | | `name` | string | Yes | Tool or function name | | `toolCallRequest` | any | No | Request payload (any JSON, including `null`) | | `toolCallResponse` | any | No | Response payload (any JSON, including `null`) | **`email`** — one email in a thread: | Field | Type | Required | Description | | - | - | - | - | | `role` | string | Yes | `user` (inbound) or `assistant` (outbound) | | `body` | string | Yes | Email body | | `subject` | string | No | Subject line | | `inReplyTo` | string | No | Message-ID of the parent email | | `from` | string | No | Sender address | | `to` | array of strings | No | Recipient addresses | **`call`** — a phone, video, or voice call. Each call is stored as a single record containing the full transcript: | Field | Type | Required | Description | | - | - | - | - | | `transcript` | array | Yes | Non-empty array of `{role, content, timestamp?}` speaker turns; `role` and `content` are required on every turn | | `duration` | number | No | Call duration in seconds | | `callType` | string | No | `phone`, `video`, or `voice` | ### Example ```bash theme={"dark"} curl https://moda-ingest.modas.workers.dev/v1/ingest/multi \ -H "Authorization: Bearer YOUR_MODA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "events": [ { "messageType": "channel", "id": "msg-001", "conversationId": "support-thread-456", "message": "I need help with my subscription", "role": "user", "userId": "customer-789" }, { "messageType": "tool_call", "id": "tool-001", "conversationId": "support-thread-456", "name": "get_subscription", "toolCallRequest": {"user_id": "customer-789"}, "toolCallResponse": {"plan": "pro", "status": "active"} } ] }' ``` Success response — `details` breaks the accepted count down by event type: ```json theme={"dark"} { "success": true, "count": 2, "requestId": "550e8400-e29b-41d4-a716-446655440000", "details": { "channel": 1, "tool_call": 1, "email": 0, "call": 0, "call_transcript_messages": 0 } } ``` > [!NOTE] > > `details.call_transcript_messages` is always `0`; it is retained for backward compatibility. Calls are counted under `details.call`. Validation failures return `400` with a per-event message (for example `Event 0: Missing or invalid 'id' field`), and nothing from the batch is stored. ## POST /v1/traces The OpenTelemetry OTLP/HTTP trace endpoint. Both Moda SDKs export here by default, and any OTLP-capable exporter can target it directly. * Accepts OTLP/JSON, and OTLP/protobuf when the `Content-Type` header contains `protobuf`. * The body is a standard `ExportTraceServiceRequest` (`resourceSpans` → `scopeSpans` → `spans`). * Moda traces are extracted from GenAI span attributes: OTel GenAI semantic conventions (`gen_ai.*`), OpenLLMetry (`llm.prompts.*` / `llm.completions.*`), Vercel AI SDK (`ai.*`), and `moda.*` attributes for the trace ID (`moda.conversation_id`), user ID, environment, and prompt attribution. * Only the 5 MB body cap applies; there is no per-request span count limit. Responses: JSON requests get the standard envelope (`200` with `{"success": true, "count": N, "requestId": "..."}`, `400` with the message `Invalid OTLP format` on parse failure). Successful protobuf requests get an OTLP `ExportTraceServiceResponse` body instead; parse failures and `401` auth failures return the JSON envelope regardless of request format, while a `503` (including API-key validation being temporarily unavailable) returns an OTLP protobuf body. See [OpenTelemetry](/ingestion/opentelemetry) for the full list of supported span attributes and the trace ID precedence rules. ## Next steps * [Reliability](/ingestion/reliability) — status codes, retry guidance, and limits. * [OpenTelemetry](/ingestion/opentelemetry) — supported span attributes for `POST /v1/traces`. * [Authentication](/administration/authentication) — creating and revoking ingestion keys. # Media capture (Cloudflare R2) Source: https://docs.moda.dev/ingestion/media-capture Give Moda the photos, voice notes and renders your agent stores in R2 or fetches from the web, so traces and replays show the real files. Traces don't carry media bytes. They carry names for them: an R2 key such as `users//photos/.jpg`, a link, or a `[Media: image/png ]` marker in a tool result. With media capture, your Worker hands each file to Moda once, under its name. Moda then links every name it finds in your traces to the file, including files that arrive after the trace. Replays use the real bytes: * a replayed read of `env.R2_BUCKET.get(key)` returns the original object; * a replayed fetch of a captured URL returns the original response body; * any other name behaves as it did before. There is no separate Worker and no hook on each `put`. R2 event notifications feed a queue, and one branch in the `queue()` handler you already have consumes it. > [!WARNING] > > These files are your users' photos, voice notes and videos. Turn capture on only for prefixes your terms and user consent cover. Use `prefixes` and `parseKey` to leave out anything they don't cover. > [!NOTE] > > Ask Moda to enable media linking for your workspace before you start. Until it's enabled, files still upload, but traces and replays don't link to them. ## 1. Create the queue and the notification rules Create one rule for each prefix that holds media your agent reads or writes: ```bash theme={"dark"} wrangler queues create moda-media wrangler queues create moda-media-dlq wrangler r2 bucket notification create --event-type object-create --queue moda-media --prefix "users/" wrangler r2 bucket notification create --event-type object-create --queue moda-media --prefix "messages/" ``` ## 2. Consume the queue in your Worker Add the consumer to your Wrangler config: ```jsonc theme={"dark"} // wrangler.jsonc "queues": { "consumers": [ { "queue": "moda-media", "max_batch_size": 10, "max_batch_timeout": 5, "max_retries": 5, "dead_letter_queue": "moda-media-dlq" } ] } ``` Then add one branch to your existing `queue()` handler: ```ts theme={"dark"} import { r2MediaHandler } from 'moda-ai/media'; async queue(batch, env, ctx) { if (batch.queue === 'moda-media') { await r2MediaHandler(batch, env.R2_BUCKET, { apiKey: env.MODA_API_KEY, prefixes: ['users/', 'messages/'], parseKey: (key) => ({ endUserId: key.split('/')[1] }), }); return; } // ...your other queues } ``` | Option | Default | | | - | - | - | | `prefixes` | all keys | Keys outside these are acknowledged and skipped. | | `parseKey(key)` | none | Returns `{ endUserId }` for the user a key belongs to, or `null` to skip the object. | | `maxBytes` | 25 MB (at most 95 MB) | Larger objects are recorded by key only, without their bytes. | | `retryDelaySeconds` | 30 | First redelivery delay; doubles each attempt, up to 15 minutes. | | `onError(error)` | none | Called for each failure. The handler itself never throws. | The handler acknowledges each message when it's done. It asks for redelivery only when Moda or R2 is briefly unavailable (HTTP 408, 429, 5xx, or a network error). Under at-least-once delivery, a file is stored once: * uploads are keyed by the file's SHA-256; * redelivered notifications are skipped; * copies of one notification in the same batch share one upload. Deletes are ignored, and so is a notification for an object that was overwritten since. Objects over 8 MB are hashed while they stream (`crypto.DigestStream`), so memory stays flat. ## 3. Capture media fetched from outside URLs Media that never lands in R2, such as a CDN image your image tool fetches, goes through `captureFetchedMedia` right after the fetch: ```ts theme={"dark"} import { captureFetchedMedia } from 'moda-ai/media'; const response = await fetch(url); ctx.waitUntil(captureFetchedMedia(url, response.clone(), { apiKey: env.MODA_API_KEY, endUserId })); ``` Moda files the bytes under a hash of the URL's origin and path. The upload sends only that hash and the host, never the URL or its query string, because a signed link is a bearer token. A re-signed link to the same path still matches. > [!WARNING] > > This covers the upload only. If a signed URL also appears in a message or tool result, your trace sends it to Moda like any other text, and Moda stores it with the trace. Redact signed URLs from traces separately. ## What Moda stores | | Stored | Never stored | | - | - | - | | R2 objects | the bytes (by SHA-256), key, bucket, etag, size, content type, end user | other objects in the bucket | | Fetched URLs (upload) | the bytes (by SHA-256), the hash of origin and path, host, end user | the URL, its query string | | Traces | the trace as sent, including any URL in its text, plus an index of the names it mentions (keys, URL hashes) | | # Moda SDK for Node.js Source: https://docs.moda.dev/ingestion/node Install moda-ai to automatically capture openai and @anthropic-ai/sdk calls with trace and user context. The Moda SDK for Node.js (`moda-ai`) auto-instruments the `openai` and `@anthropic-ai/sdk` client libraries: after `await Moda.init(...)`, chat completions and messages — including streamed responses and tool calls — are captured and sent to Moda without changes to your provider code. This page covers installation, configuration, provider coverage, context APIs, manual capture, and running alongside an existing OpenTelemetry setup. ## Prerequisites * Node.js 18 or later (TypeScript 5.0 or later for type definitions) * A Moda API key, created at **Settings → Ingestion keys** (see [Authentication](/administration/authentication)) * The `openai` (4.0+) or `@anthropic-ai/sdk` (0.18+) package your app already uses ## Set up **1. Install the SDK** ```bash theme={"dark"} npm install moda-ai ``` **2. Initialize and make a call** Call `Moda.init(apiKey, options)` once at startup and await it. Create your provider clients after init. ```typescript app.ts theme={"dark"} import { Moda } from 'moda-ai'; import OpenAI from 'openai'; await Moda.init(process.env.MODA_API_KEY!, { environment: 'production', }); const client = new OpenAI(); Moda.conversationId = 'session_8f2a'; Moda.userId = 'user_1042'; const response = await client.chat.completions.create({ model: 'gpt-4o', messages: [{ role: 'user', content: 'Hello!' }], }); console.log(response.choices[0].message.content); await Moda.flush(); ``` **3. Verify in the dashboard** Open **Traces** in the [dashboard](https://moda.dev/dashboard). Within minutes you should see a trace with ID `session_8f2a` containing the user message and the assistant response, with the model name and token counts attached. > [!WARNING] > > `Moda.init()` is async and must be awaited, and it must run before you create provider clients. If init is not awaited, calls made before initialization completes are not captured. The API key argument is required — unlike the Python SDK, `Moda.init()` does not read `MODA_API_KEY` from the environment, and it throws `[Moda] API key is required` if the key is missing. ## Configuration ### `Moda.init()` options ```typescript theme={"dark"} await Moda.init(process.env.MODA_API_KEY!, { environment: 'staging', debug: false, batchSize: 100, flushInterval: 5000, }); ``` | Option | Type | Default | Description | | - | - | - | - | | `baseUrl` | `string` | `https://moda-ingest.modas.workers.dev/v1/traces` | Full URL of the ingestion traces endpoint. | | `environment` | `string` | `'production'` | Environment tag: `development`, `staging`, or `production`. | | `enabled` | `boolean` | `true` | Set `false` to disable the SDK entirely (no data is captured or sent). | | `debug` | `boolean` | `false` | Verbose logging; also switches to immediate (unbatched) span export. | | `batchSize` | `number` | `100` | Maximum spans per export batch. | | `flushInterval` | `number` | `5000` | Milliseconds between automatic exports of batched spans. | ### Lifecycle | Call | Behavior | | - | - | | `await Moda.flush()` | Force-export all pending spans. Call before the process exits or a serverless invocation returns. | | `await Moda.shutdown()` | Flush and release resources. You can call `Moda.init()` again afterward. | | `Moda.isInitialized()` | Returns whether the SDK is active. | Calling `Moda.init()` a second time while initialized is a no-op. `flush()` and `shutdown()` are safe no-ops before init. ## What gets instrumented The SDK instruments exactly two client libraries: * **`openai`** — `chat.completions.create`, including streaming and tool calls. * **`@anthropic-ai/sdk`** — `messages.create` and `messages.stream`, including tool use and extended thinking. | Provider | Support | | - | - | | OpenAI chat completions | Supported, including streaming | | OpenAI embeddings | Not supported — use the [Python SDK](/ingestion/python), [OpenTelemetry](/ingestion/opentelemetry), or the [HTTP API](/ingestion/http-api) | | Anthropic Messages | Supported, including streaming and extended thinking | | OpenRouter and other OpenAI-compatible gateways | Supported through the `openai` client with a custom `baseURL` — see below | | Amazon Bedrock | Not supported in Node.js — use [OpenTelemetry](/ingestion/opentelemetry) or the [HTTP API](/ingestion/http-api) | | Vercel AI SDK | Supported via `Moda.getVercelAITelemetry()` — see [Vercel AI SDK](/ingestion/vercel-ai-sdk) | | Vapi | Supported via `Moda.processVapiEndOfCallReport()` — see [Vapi](/ingestion/providers/vapi) | | OpenClaw | Supported via the OpenClaw helpers — see [OpenClaw](/ingestion/providers/openclaw) | | Anything else | Use [manual capture](#manual-capture-with-withllmcall) | ### Anthropic example ```typescript claude.ts theme={"dark"} import { Moda } from 'moda-ai'; import Anthropic from '@anthropic-ai/sdk'; await Moda.init(process.env.MODA_API_KEY!); const anthropic = new Anthropic(); Moda.conversationId = 'session_8f2a'; const response = await anthropic.messages.create({ model: 'claude-sonnet-4-20250514', max_tokens: 1024, system: 'You are a helpful assistant.', messages: [{ role: 'user', content: 'Hello!' }], }); await Moda.flush(); ``` ### OpenRouter and OpenAI-compatible endpoints Any endpoint reached through the `openai` client with a custom `baseURL` is captured — requests, responses, streaming, and token usage. The SDK records these calls with vendor `openai`. ```typescript openrouter.ts theme={"dark"} import { Moda } from 'moda-ai'; import OpenAI from 'openai'; await Moda.init(process.env.MODA_API_KEY!); const openrouter = new OpenAI({ baseURL: 'https://openrouter.ai/api/v1', apiKey: process.env.OPENROUTER_API_KEY, }); Moda.conversationId = 'session_8f2a'; const response = await openrouter.chat.completions.create({ model: 'anthropic/claude-3-haiku', messages: [{ role: 'user', content: 'Hello!' }], }); await Moda.flush(); ``` ## Trace and user context Set a trace ID — the `conversationId` property, which populates the `conversation_id` field — to group related calls into one trace, and a user ID to attribute them to a user. ### Global properties and setters ```typescript theme={"dark"} import { Moda } from 'moda-ai'; // Property style Moda.conversationId = 'support_ticket_123'; Moda.userId = 'user_1042'; // ... make LLM calls ... Moda.conversationId = null; // clear when done Moda.userId = null; // Method style (equivalent) Moda.setConversationId('support_ticket_123'); Moda.setUserId('user_1042'); Moda.clearConversationId(); Moda.clearUserId(); ``` Global context applies to every call in the process. In servers that handle concurrent requests, use the scoped functions instead. ### Scoped context `withConversationId`, `withUserId`, and `withContext` run a callback with context stored in `AsyncLocalStorage`: the scoped value overrides the global one, follows the callback across `await` boundaries, is isolated from parallel requests, restores the previous value on exit, and can be nested. ```typescript server.ts theme={"dark"} import { Moda, withContext } from 'moda-ai'; import OpenAI from 'openai'; await Moda.init(process.env.MODA_API_KEY!); const client = new OpenAI(); async function handleRequest(sessionId: string, userId: string, question: string) { return withContext(`session_${sessionId}`, userId, async () => { const response = await client.chat.completions.create({ model: 'gpt-4o', messages: [{ role: 'user', content: question }], }); return response.choices[0].message.content; }); } ``` ```typescript theme={"dark"} import { withConversationId, withUserId } from 'moda-ai'; // Scope only the trace ID await withConversationId('session_123', async () => { await client.chat.completions.create({ model: 'gpt-4o', messages: [{ role: 'user', content: 'Hello!' }], }); }); // Scope only the user ID await withUserId('user_456', async () => { await client.chat.completions.create({ model: 'gpt-4o', messages: [{ role: 'user', content: 'Hello!' }], }); }); ``` ### Reading context ```typescript theme={"dark"} import { getContext, getEffectiveContext, getGlobalContext } from 'moda-ai'; getContext(); // scoped (AsyncLocalStorage) context only getGlobalContext(); // global context only getEffectiveContext(); // combined; scoped values take precedence ``` > [!WARNING] > > Set the trace ID before the first model call of a session or run — from your session, thread, job, or run ID — so every call lands in one trace. Set `Moda.conversationId` or wrap the run in `withConversationId`. ## Manual capture with `withLLMCall` For providers that are not auto-instrumented (direct HTTP calls, custom gateways), wrap the call with `Moda.withLLMCall({ vendor, type }, callback)`. Call `span.reportRequest` before the call and `span.reportResponse` after it; errors thrown in the callback propagate normally. ```typescript manual.ts theme={"dark"} import { Moda } from 'moda-ai'; await Moda.init(process.env.MODA_API_KEY!); Moda.conversationId = 'session_8f2a'; const messages = [{ role: 'user' as const, content: 'Hello!' }]; const result = await Moda.withLLMCall( { vendor: 'custom', type: 'chat' }, async ({ span }) => { span.reportRequest({ model: 'my-model', messages }); const response = await fetch('https://llm.example.com/v1/chat/completions', { method: 'POST', headers: { Authorization: `Bearer ${process.env.PROVIDER_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'my-model', messages }), }); const data = await response.json(); span.reportResponse({ model: data.model, usage: data.usage, completions: data.choices, }); return data; }, ); await Moda.flush(); ``` | Helper | Description | | - | - | | `span.reportRequest({ model, messages, conversationId?, userId? })` | Record the request. Global or scoped context is used when `conversationId` and `userId` are omitted. | | `span.reportResponse({ model?, usage?, completions? })` | Record the response. `usage` accepts both `prompt_tokens`/`completion_tokens`/`total_tokens` and `input_tokens`/`output_tokens`. | | `span.rawSpan` | The underlying OpenTelemetry span for custom attributes. | ## Vercel AI SDK Pass `Moda.getVercelAITelemetry()` as `experimental_telemetry` on AI SDK calls: ```typescript theme={"dark"} import { Moda } from 'moda-ai'; import { generateText } from 'ai'; import { openai } from '@ai-sdk/openai'; await Moda.init(process.env.MODA_API_KEY!); Moda.conversationId = 'session_8f2a'; const result = await generateText({ model: openai('gpt-4o'), prompt: 'Write a haiku about the ocean.', experimental_telemetry: Moda.getVercelAITelemetry(), }); await Moda.flush(); ``` > [!NOTE] > > Trace and user context are snapshotted at the moment `getVercelAITelemetry()` is called. Set `Moda.conversationId` (or enter `withConversationId`) before calling it, not after. See [Vercel AI SDK](/ingestion/vercel-ai-sdk) for streaming, structured output, tools, and the full option list (`recordInputs`, `recordOutputs`, `functionId`, `metadata`). ## Using with an existing OpenTelemetry setup If another SDK has already registered a global `TracerProvider` — for example Sentry v8+ or dd-trace — `Moda.init()` detects it and adds Moda's span processor to that provider instead of creating its own. Both pipelines receive the same spans, and `Moda.shutdown()` removes only Moda's processor, leaving the other SDK untouched. Initialize the other SDK first, then Moda: ```typescript sentry.ts theme={"dark"} import * as Sentry from '@sentry/node'; import { Moda } from 'moda-ai'; import OpenAI from 'openai'; // 1. Initialize Sentry first Sentry.init({ dsn: process.env.SENTRY_DSN, tracesSampleRate: 1.0, }); // 2. Initialize Moda second — it attaches to Sentry's provider await Moda.init(process.env.MODA_API_KEY!, { debug: true }); // debug log: [Moda] Detected existing TracerProvider, adding Moda SpanProcessor to it const openai = new OpenAI(); const response = await openai.chat.completions.create({ model: 'gpt-4o', messages: [{ role: 'user', content: 'Hello!' }], }); await Moda.flush(); await Moda.shutdown(); // removes only Moda's span processor ``` ### Escape hatches If the external provider samples out or filters Moda's spans, create a standalone Moda provider that bypasses it: ```typescript theme={"dark"} import { Moda } from 'moda-ai'; Moda.createModaProvider({ apiKey: process.env.MODA_API_KEY! }); await Moda.registerInstrumentations(); ``` `createModaProvider` accepts `apiKey`, `baseUrl`, `debug`, `batchSize`, and `flushInterval`. For fully custom OpenTelemetry setups, `createModaSpanProcessor(options)` returns a span processor (same options) that you can add to your own `TracerProvider`. ## Flushing and serverless Spans are batched and exported every `flushInterval` milliseconds (default 5000). Unexported spans are lost when the process exits or a serverless runtime freezes, so: * **Serverless functions** — `await Moda.flush()` before each invocation returns: ```typescript handler.ts theme={"dark"} import { Moda, withConversationId } from 'moda-ai'; import OpenAI from 'openai'; await Moda.init(process.env.MODA_API_KEY!); const client = new OpenAI(); export async function handler(event: { sessionId: string; question: string }) { const result = await withConversationId(`session_${event.sessionId}`, () => client.chat.completions.create({ model: 'gpt-4o', messages: [{ role: 'user', content: event.question }], }), ); await Moda.flush(); // spans are batched — flush before the runtime freezes return result.choices[0].message.content; } ``` * **Long-running servers** — flush and shut down on termination: ```typescript theme={"dark"} process.on('SIGTERM', async () => { await Moda.flush(); await Moda.shutdown(); process.exit(0); }); ``` ## Troubleshooting | Symptom | Fix | | - | - | | `[Moda] API key is required` thrown at startup | Pass the key explicitly: `await Moda.init(process.env.MODA_API_KEY!)`. `Moda.init()` does not read `MODA_API_KEY` from the environment. | | Early calls are missing | `await Moda.init(...)` before creating provider clients and before the first LLM call. Calls made before initialization completes are not captured. | | Nothing appears in the dashboard | `await Moda.flush()` before the process exits or the serverless invocation returns. Enable `debug: true` to see export activity. | | Embedding calls are not captured | Expected: the Node.js SDK does not instrument OpenAI embeddings. Use the [Python SDK](/ingestion/python), [OpenTelemetry](/ingestion/opentelemetry), or the [HTTP API](/ingestion/http-api). | | One session shows up as many traces | Set `Moda.conversationId` or wrap the run in `withConversationId` before the first model call of the session. | | Spans missing in Moda while using Sentry or another OTel SDK | The external provider may sample out Moda's spans. Use `Moda.createModaProvider(...)` plus `Moda.registerInstrumentations()` to bypass it. | | Context set inside a request leaks or disappears | Use `withConversationId` / `withUserId` / `withContext` in concurrent handlers instead of the global setters; scoped context is isolated per async chain. | ## Next steps * [Vercel AI SDK](/ingestion/vercel-ai-sdk) — full guide for apps built on the `ai` package. * [OpenRouter](/ingestion/providers/openrouter) — provider-specific setup details. * [Reliability](/ingestion/reliability) — delivery guarantees, limits, and error handling. * [Data model](/concepts/data-model) — how captured messages become traces and signals. # OpenTelemetry Source: https://docs.moda.dev/ingestion/opentelemetry Point an existing OpenTelemetry exporter or collector at Moda's OTLP trace endpoint and control attribution with span attributes. Moda accepts standard OpenTelemetry traces over OTLP/HTTP. If your application is already instrumented — with the OpenTelemetry GenAI semantic conventions, OpenLLMetry, or the Vercel AI SDK's telemetry — point that exporter at Moda's trace endpoint and Moda traces are extracted without re-instrumentation. A Moda trace is one full agent run, keyed by the `moda.conversation_id` attribute (the trace ID); it can span many OpenTelemetry traces, and the OTLP `traceId` is only a fallback for grouping. The Moda SDKs use this same endpoint; you only need this page when integrating an existing OpenTelemetry pipeline directly. ## Endpoint and authentication ``` POST https://moda-ingest.modas.workers.dev/v1/traces Authorization: Bearer moda_sk_... ``` Both OTLP/HTTP encodings are accepted; OTLP/gRPC is not supported. | `Content-Type` | Body | | - | - | | `application/json` | OTLP/HTTP JSON (`ExportTraceServiceRequest`) | | `application/x-protobuf` | OTLP/HTTP protobuf | ## Point an exporter at Moda > [tab] Exporter environment variables > > Standard OTLP exporters read these variables: > > ```bash theme={"dark"} > export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT="https://moda-ingest.modas.workers.dev/v1/traces" > export OTEL_EXPORTER_OTLP_TRACES_HEADERS="Authorization=Bearer YOUR_MODA_API_KEY" > ``` > > Use the `_TRACES_`-scoped variables (rather than `OTEL_EXPORTER_OTLP_ENDPOINT`) so the exporter posts to the exact `/v1/traces` path and other signals in your pipeline are unaffected. > [tab] OpenTelemetry Collector > > Add an `otlphttp` exporter to your collector configuration and route the traces pipeline through it: > > ```yaml otel-collector-config.yaml theme={"dark"} > exporters: > otlphttp/moda: > traces_endpoint: https://moda-ingest.modas.workers.dev/v1/traces > headers: > Authorization: Bearer YOUR_MODA_API_KEY > > service: > pipelines: > traces: > receivers: [otlp] > processors: [batch] > exporters: [otlphttp/moda] > ``` > > Use `traces_endpoint` (not `endpoint`) so the collector sends to the exact path instead of appending its own. > [!NOTE] > > Already running OpenTelemetry inside a Node.js app? The Moda SDK for Node.js attaches its span processor to your existing TracerProvider instead of replacing it — see [Node.js SDK](/ingestion/node). ## Supported attribute conventions Moda recognizes GenAI spans in each of these conventions automatically, per span — mixed batches are fine: | Convention | Recognized attributes | | - | - | | OpenTelemetry GenAI semantic conventions | `gen_ai.input.messages` / `gen_ai.output.messages` (JSON-string message arrays; `parts` arrays supported), plus the older numbered `gen_ai.prompt.{n}.role` / `gen_ai.prompt.{n}.content` and `gen_ai.completion.{n}.*` flattening | | OpenLLMetry / Traceloop | `llm.prompts.{n}.role` / `llm.prompts.{n}.content` and `llm.completions.{n}.*` | | Vercel AI SDK telemetry | `ai.prompt.messages`, `ai.response.text`, `ai.response.object`, `ai.operationId` — see the [Vercel AI SDK guide](/ingestion/vercel-ai-sdk) for the SDK-level setup | | Single-string fallback | A bare `gen_ai.prompt` / `llm.prompt` and `gen_ai.completion` / `llm.completion` string, when the span also carries a model attribute | | Generic tool spans | Spans carrying `gen_ai.tool.name`, `db.system`, `rpc.system`, or `http.route` are captured as tool-call activity | When a span carries both `llm.*` and numbered `gen_ai.*` message attributes, the `llm.*` set is used — messages are never extracted twice from one span. ## Model, provider, usage, and finish reason For each field, the first attribute found wins: | Field | Attributes, in precedence order | | - | - | | Model | `llm.request.model`, `gen_ai.request.model`, `llm.response.model`, `gen_ai.response.model`, `ai.model.id` | | Provider | `gen_ai.provider.name`, `llm.system`, `gen_ai.system`, `ai.model.provider` | | Input tokens | `llm.usage.prompt_tokens` / `llm.usage.input_tokens`, `gen_ai.usage.input_tokens` / `gen_ai.usage.prompt_tokens`, `ai.usage.promptTokens` | | Output tokens | `llm.usage.completion_tokens` / `llm.usage.output_tokens`, `gen_ai.usage.output_tokens` / `gen_ai.usage.completion_tokens`, `ai.usage.completionTokens` | | Reasoning tokens | `gen_ai.usage.reasoning.output_tokens` | | Cache-read tokens | `gen_ai.usage.cache_read.input_tokens`, or the flat `gen_ai.usage.cache_read_input_tokens` | | Cache-creation tokens | `gen_ai.usage.cache_creation.input_tokens`, or the flat `gen_ai.usage.cache_creation_input_tokens` | | Finish reason | First entry of `gen_ai.response.finish_reasons`, then `gen_ai.response.finish_reason`, then `llm.response.finish_reason` | ## Moda attribution attributes Set these span attributes to control how spans map onto Moda traces, users, environments, and prompts. All are optional. | Attribute | Purpose | | - | - | | `moda.conversation_id` | The trace ID: groups spans into one Moda trace, across OpenTelemetry traces | | `moda.user_id` | End-user attribution for per-user analytics | | `moda.environment` | `development`, `staging`, or `production` for this span | | `moda.prompt_key`, `moda.prompt_id`, `moda.prompt_name`, `moda.prompt_version`, `moda.prompt_version_id` | Optional prompt attribution metadata | | `moda.external_message_id` | Your own stable, unique ID for the resulting message | | `gen_ai.agent.name` (or `agent.name`) | Agent identity recorded on the resulting messages | The trace ID, user, and prompt keys are also read from the Vercel AI SDK metadata form `ai.telemetry.metadata.moda.*`, which is how [`getVercelAITelemetry()`](/ingestion/vercel-ai-sdk) sets them. On the resource, `user.id` / `enduser.id` and `deployment.environment` are read as defaults for every span under that resource. ## Trace ID precedence For each span, the trace ID (`conversation_id`) is resolved in this order: 1. `moda.conversation_id` (including the `ai.telemetry.metadata.moda.conversation_id` form) 2. `gen_ai.conversation.id` — the legacy underscore form `gen_ai.conversation_id` and the Traceloop key `traceloop.association.properties.session_id` are also honored 3. The span's OpenTelemetry `traceId` A bare `session_id` attribute is deliberately ignored: it is too generic and could merge unrelated traces. Without an explicit `conversation_id`, spans group by OpenTelemetry trace — each OTLP trace becomes its own Moda trace — so set `moda.conversation_id` for anything multi-step. ## Environment normalization Environments are normalized to `development`, `staging`, or `production`. Common aliases map to their canonical forms (`dev` / `develop` → `development`, `stg` / `stage` → `staging`, `prod` → `production`); unrecognized values fall back to `production`. A span-level `moda.environment` overrides the resource-level `deployment.environment`. ## Example request A minimal OTLP/JSON request with one GenAI chat span: ```bash theme={"dark"} curl https://moda-ingest.modas.workers.dev/v1/traces \ -H "Authorization: Bearer YOUR_MODA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "resourceSpans": [{ "resource": {"attributes": [ {"key": "service.name", "value": {"stringValue": "my-app"}} ]}, "scopeSpans": [{ "spans": [{ "traceId": "5b8efff798038103d269b633813fc60c", "spanId": "eee19b7ec3c1b174", "name": "chat gpt-4o", "startTimeUnixNano": "1755338400000000000", "endTimeUnixNano": "1755338401500000000", "attributes": [ {"key": "gen_ai.operation.name", "value": {"stringValue": "chat"}}, {"key": "gen_ai.response.model", "value": {"stringValue": "gpt-4o"}}, {"key": "gen_ai.provider.name", "value": {"stringValue": "openai"}}, {"key": "gen_ai.usage.input_tokens", "value": {"intValue": "12"}}, {"key": "gen_ai.usage.output_tokens", "value": {"intValue": "8"}}, {"key": "moda.conversation_id", "value": {"stringValue": "conv-123"}}, {"key": "gen_ai.input.messages", "value": {"stringValue": "[{\"role\":\"user\",\"parts\":[{\"type\":\"text\",\"content\":\"What is the capital of France?\"}]}]"}}, {"key": "gen_ai.output.messages", "value": {"stringValue": "[{\"role\":\"assistant\",\"parts\":[{\"type\":\"text\",\"content\":\"Paris.\"}]}]"}} ] }] }] }] }' ``` JSON requests receive a JSON acknowledgment, where `count` is the number of trace messages extracted (the example yields two — one user message and one assistant message): ```json theme={"dark"} { "success": true, "count": 2, "requestId": "550e8400-e29b-41d4-a716-446655440000" } ``` Protobuf requests receive a standard OTLP `ExportTraceServiceResponse` (`Content-Type: application/x-protobuf`), so unmodified OTLP exporters work without changes. After sending, open **Traces** in the [dashboard](https://moda.dev/dashboard) — trace `conv-123` appears with the extracted user and assistant messages within minutes. ## Limits and errors * Request bodies are limited to 5 MB (`413` `Request too large`). There is no per-request span-count limit below that. * An optional `X-Request-ID` header (UUID) is echoed back as `requestId` for correlating requests with responses. | Status | Body | Meaning | | - | - | - | | `200` | `{"success": true, "count": n, "requestId": "..."}` | Accepted; `count: 0` means no trace data was extracted from the batch | | `400` | `{"success": false, "count": 0, "message": "Invalid OTLP format", "requestId": "..."}` | Unparseable body | | `401` | `{"success": false, "count": 0, "message": "...", "requestId": "..."}` | Missing or invalid API key | | `413` | `{"success": false, "count": 0, "message": "Request too large", "requestId": "..."}` | Body over 5 MB | | `503` | `{"success": false, "count": 0, "message": "Queue temporarily unavailable", "requestId": "...", "retryable": true}` | Backpressure — safe to retry | ## Next steps * [Ingestion overview](/ingestion/overview) — all ingestion endpoints, authentication, and shared limits. * [Vercel AI SDK](/ingestion/vercel-ai-sdk) — the AI SDK integration that emits `ai.*` telemetry to this endpoint. * [HTTP API](/ingestion/http-api) — the simple JSON alternative when you don't run OpenTelemetry. * [Reliability](/ingestion/reliability) — retries, limits, and error envelopes. # Ingestion overview Source: https://docs.moda.dev/ingestion/overview Choose how to send LLM and agent telemetry from your application to Moda. Ingestion is how trace data gets from your application into Moda: your app sends LLM requests, responses, and tool calls to the Ingestion API, and Moda groups them into traces — one per agent run, keyed by the `conversation_id` field (the trace ID) — for analysis. Use this page to pick the integration path that matches your stack. All paths authenticate with a Moda API key (called an ingestion key in the dashboard), created at **Settings → Ingestion keys**. See [Authentication](/administration/authentication) for key management. ## Choose an integration | Integration | When to use | Guide | | - | - | - | | Moda SDK for Python | Python 3.10+ apps that call OpenAI or Anthropic — including Azure OpenAI and OpenRouter through the OpenAI client, and Claude on Bedrock through the Anthropic client. One `moda.init()` call, no changes to provider code. | [Python SDK](/ingestion/python) | | Moda SDK for Node.js | Node.js 18+ apps that use the `openai` or `@anthropic-ai/sdk` packages, including OpenAI-compatible gateways such as OpenRouter via a custom `baseURL`. | [Node.js SDK](/ingestion/node) | | Vercel AI SDK | Apps built on the `ai` package. Pass Moda's telemetry config to `experimental_telemetry`; works with `generateText`, `streamText`, `generateObject`, and `streamObject` on any `@ai-sdk/*` provider. | [Vercel AI SDK](/ingestion/vercel-ai-sdk) | | Claude Agent SDK | Python agents built on `claude-agent-sdk`, which runs Claude Code as a subprocess. Requires the separate `moda-claude-agent-sdk` package. | [Claude Agent SDK](/ingestion/claude-agent-sdk) | | OpenTelemetry | You already emit OTLP traces (OTel GenAI semantic conventions, OpenLLMetry, or Vercel AI SDK attributes), or you use a language without a Moda SDK. | [OpenTelemetry](/ingestion/opentelemetry) | | HTTP API | Any other language or pipeline. Post JSON events directly; also the path for multi-channel data such as email and voice-call transcripts. | [HTTP API](/ingestion/http-api) | The SDKs and the OpenTelemetry path all deliver data to the same Ingestion API, so you can mix paths — for example, a Python backend on the SDK and a data pipeline on the HTTP API — and the data lands in the same traces. ## What gets captured | Data | Notes | | - | - | | Requests | Full message history sent to the model, including system prompts | | Responses | Assistant completions; streamed responses are assembled into the full completion once the stream ends | | Model and provider | Requested and responding model, plus the provider label recorded by the integration | | Token usage | Input, output, and reasoning tokens; cache read and cache write token counts when the integration reports them | | Tool calls | Tool names, arguments, and results, plus a per-message tool-use flag | | Finish reason | Why the model stopped (for example `stop`, `length`, `tool_calls`) | | Trace ID (`conversation_id`) | Groups related messages into one trace; set explicitly or derived automatically | | User ID | Optional identifier for per-user analytics | | Environment | `development`, `staging`, or `production` | | Agent name | Which agent produced the message, for multi-agent systems | | Prompt attribution | Optional prompt ID, name, and version metadata | | Timestamps | When each message was produced | > [!NOTE] > > Moda stores message content to power analysis. Make sure the traces you send align with your data-handling requirements. ## Environments Every event is tagged with one of three environments: `development`, `staging`, or `production`. Common aliases (`dev`, `stg`, `prod`) are normalized; unrecognized values are recorded as `production`. Each integration page shows how to set the environment for that path, and the dashboard lets you filter by it. ## What happens after ingest 1. Events are grouped into traces by `conversation_id` (the trace ID). New traces appear on the [Traces](/dashboard/traces) page within minutes. 2. Signal analyses — user emotion, tool failures, hallucinations, laziness — typically complete within minutes of ingest. 3. Problems and use-case clusters build automatically as evidence accumulates. See [Analysis](/concepts/analysis) for what each stage produces. Retrying a failed request is safe. Delivery semantics and limits are covered in [Reliability](/ingestion/reliability). ## Next steps * [Quickstart](/quickstart) — send your first trace end to end. * [Python SDK](/ingestion/python) or [Node.js SDK](/ingestion/node) — auto-instrumentation for OpenAI and Anthropic apps. * [Data model](/concepts/data-model) — how traces, messages, and signals relate. * [Reliability](/ingestion/reliability) — limits, retries, and error handling. # Anthropic Source: https://docs.moda.dev/ingestion/providers/anthropic Capture Anthropic Messages API calls automatically with the Moda SDK for Python or Node.js. This page shows how to capture Anthropic API traffic with Moda. Once the SDK is initialized, calls made with the official `anthropic` (Python) or `@anthropic-ai/sdk` (Node.js) client are captured automatically, including streaming, tool use, and extended thinking. ## Prerequisites * A Moda API key (created in the dashboard at **Settings → Ingestion keys**; shown once at creation) * An Anthropic API key * Python 3.10 or later, or Node.js 18 or later * Node.js only: `@anthropic-ai/sdk` version 0.18.0 or later ## Setup **1. Install the packages** ```bash pip theme={"dark"} pip install moda-ai anthropic ``` ```bash npm theme={"dark"} npm install moda-ai @anthropic-ai/sdk ``` **2. Initialize Moda before creating the client** Initialize the SDK first, then construct the Anthropic client. Flush before your process exits so buffered data is sent. ```python Python theme={"dark"} import moda from anthropic import Anthropic moda.init("YOUR_MODA_API_KEY") # Reads ANTHROPIC_API_KEY from the environment client = Anthropic() moda.conversation_id = "session_123" response = client.messages.create( model="claude-sonnet-4-20250514", max_tokens=1024, messages=[{"role": "user", "content": "Hello!"}], ) print(response.content[0].text) moda.flush() ``` ```typescript Node.js theme={"dark"} import { Moda } from 'moda-ai'; import Anthropic from '@anthropic-ai/sdk'; await Moda.init('YOUR_MODA_API_KEY'); // Reads ANTHROPIC_API_KEY from the environment const client = new Anthropic(); Moda.conversationId = 'session_123'; const response = await client.messages.create({ model: 'claude-sonnet-4-20250514', max_tokens: 1024, messages: [{ role: 'user', content: 'Hello!' }], }); console.log(response.content[0]); await Moda.flush(); ``` > [!WARNING] > > In Node.js, `Moda.init()` is async and the API key argument is required (it is not read from `MODA_API_KEY`). If `Moda.init()` is not awaited, calls made before initialization completes are not captured. In Python, `moda.init()` is synchronous and also reads the `MODA_API_KEY` environment variable, so `moda.init()` with no arguments works when that variable is set. **3. Verify in the dashboard** Run the script, then open [Traces](https://moda.dev/dashboard) in the dashboard. You should see a trace with ID `session_123` containing the user message and the assistant reply, with model `claude-sonnet-4-20250514` and token counts. Analysis signals typically appear within minutes of ingest. ## Trace grouping Set a trace ID — the `conversation_id` field — before the first call of a session or run, from your session, thread, job, or run ID, so every call lands in one trace. Use `moda.conversation_id` (Python) or `Moda.conversationId` / `Moda.withConversationId()` (Node.js). See [the Python SDK](/ingestion/python) and [the Node.js SDK](/ingestion/node) for the full context APIs. ## Streaming Both `messages.stream()` and `messages.create(..., stream=True)` are captured. The SDK records the complete response after the stream finishes, so consume the entire stream. ```python Python theme={"dark"} import moda from anthropic import Anthropic moda.init("YOUR_MODA_API_KEY") client = Anthropic() with client.messages.stream( model="claude-sonnet-4-20250514", max_tokens=1024, messages=[{"role": "user", "content": "Count to 5"}], ) as stream: for text in stream.text_stream: print(text, end="") moda.flush() ``` ```typescript Node.js theme={"dark"} import { Moda } from 'moda-ai'; import Anthropic from '@anthropic-ai/sdk'; await Moda.init('YOUR_MODA_API_KEY'); const client = new Anthropic(); const stream = await client.messages.stream({ model: 'claude-sonnet-4-20250514', max_tokens: 1024, messages: [{ role: 'user', content: 'Count to 5' }], }); for await (const event of stream) { if (event.type === 'content_block_delta' && event.delta.type === 'text_delta') { process.stdout.write(event.delta.text); } } await Moda.flush(); ``` ## Tool use Tool calls are captured automatically: `tool_use` blocks in assistant messages, and the `tool_result` blocks you send back in follow-up messages. ```python Python theme={"dark"} import moda from anthropic import Anthropic moda.init("YOUR_MODA_API_KEY") client = Anthropic() response = client.messages.create( model="claude-sonnet-4-20250514", max_tokens=1024, tools=[{ "name": "get_weather", "description": "Get the current weather for a location", "input_schema": { "type": "object", "properties": {"location": {"type": "string"}}, "required": ["location"], }, }], messages=[{"role": "user", "content": "What's the weather in London?"}], ) tool_use = next(block for block in response.content if block.type == "tool_use") print(tool_use.name, tool_use.input) moda.flush() ``` ```typescript Node.js theme={"dark"} import { Moda } from 'moda-ai'; import Anthropic from '@anthropic-ai/sdk'; await Moda.init('YOUR_MODA_API_KEY'); const client = new Anthropic(); const response = await client.messages.create({ model: 'claude-sonnet-4-20250514', max_tokens: 1024, tools: [{ name: 'get_weather', description: 'Get the current weather for a location', input_schema: { type: 'object', properties: { location: { type: 'string' } }, required: ['location'], }, }], messages: [{ role: 'user', content: "What's the weather in London?" }], }); const toolUse = response.content.find((block) => block.type === 'tool_use'); console.log(toolUse); await Moda.flush(); ``` ## Extended thinking When extended thinking is enabled, thinking content blocks are captured alongside the final text response, in both non-streaming and streaming calls. ```python Python theme={"dark"} import moda from anthropic import Anthropic moda.init("YOUR_MODA_API_KEY") client = Anthropic() response = client.messages.create( model="claude-sonnet-4-20250514", max_tokens=8000, thinking={"type": "enabled", "budget_tokens": 1024}, messages=[{"role": "user", "content": "What is 27 * 453?"}], ) thinking = next((b for b in response.content if b.type == "thinking"), None) print("Has thinking block:", thinking is not None) moda.flush() ``` ```typescript Node.js theme={"dark"} import { Moda } from 'moda-ai'; import Anthropic from '@anthropic-ai/sdk'; await Moda.init('YOUR_MODA_API_KEY'); const client = new Anthropic(); const response = await client.messages.create({ model: 'claude-sonnet-4-20250514', max_tokens: 8000, thinking: { type: 'enabled', budget_tokens: 1024 }, messages: [{ role: 'user', content: 'What is 27 * 453?' }], }); const thinking = response.content.find((b) => b.type === 'thinking'); console.log('Has thinking block:', Boolean(thinking)); await Moda.flush(); ``` ## Support matrix | Capability | Python | Node.js | | - | - | - | | Messages (`messages.create`) | Supported | Supported | | Streaming (`messages.stream`, `stream: true`) | Supported | Supported | | Tool use | Supported | Supported | | Extended thinking | Supported | Supported | | System prompts | Supported | Supported | | Token usage (input, output) | Supported | Supported | | Prompt cache token counts (cache read / creation) | Supported | Not captured | | Legacy Text Completions (`completions.create`) | Supported | Not supported | | Claude on Amazon Bedrock (`AnthropicBedrock` client) | Supported | Not supported — see [Amazon Bedrock](/ingestion/providers/bedrock) | ## Troubleshooting **No traces appear in the dashboard.** Initialize Moda before constructing the Anthropic client, and call `moda.flush()` (Python) or `await Moda.flush()` (Node.js) before the process exits. In Node.js, confirm `Moda.init()` is awaited and the API key starts with `moda_sk_`. **Streaming calls show no assistant message.** The response is recorded only after the stream ends. Consume the stream fully; a stream that is abandoned partway is not captured completely. **Thinking blocks are missing.** Extended thinking requires a model that supports it and the `thinking` parameter with `type: "enabled"` and a `budget_tokens` value. **Every request creates a new trace.** Set a trace ID before the first call of the session (see Trace grouping above). ## Next steps * [Python SDK](/ingestion/python) — init options, context managers, and instrument controls. * [Node.js SDK](/ingestion/node) — init options, scoped context, and manual tracing. * [Amazon Bedrock](/ingestion/providers/bedrock) — capturing Claude models served through Bedrock. * [Claude Agent SDK](/ingestion/claude-agent-sdk) — capturing agents built on the Claude Agent SDK (Python). # Azure OpenAI Source: https://docs.moda.dev/ingestion/providers/azure-openai Capture Azure OpenAI calls automatically with the Moda SDK for Python; from Node.js, use OpenTelemetry, the HTTP API, or manual tracing. This page shows how to capture Azure OpenAI Service traffic with Moda. The Python SDK captures calls made with the `AzureOpenAI` client automatically and records the provider as Azure, detected from the endpoint URL. The Node.js SDK does not auto-instrument Azure OpenAI — see [Node.js support](#nodejs-support) for alternatives. ## Prerequisites * A Moda API key (created in the dashboard at **Settings → Ingestion keys**; shown once at creation) * An Azure OpenAI resource with a model deployment, its API key, and its endpoint URL * Python 3.10 or later ## Setup (Python) **1. Install the packages** ```bash pip theme={"dark"} pip install moda-ai openai ``` **2. Initialize Moda before creating the client** Initialize the SDK first, then construct the `AzureOpenAI` client. Flush before your process exits so buffered data is sent. ```python app.py theme={"dark"} import os import moda from openai import AzureOpenAI moda.init("YOUR_MODA_API_KEY") client = AzureOpenAI( api_key=os.environ["AZURE_OPENAI_API_KEY"], api_version="2024-02-01", azure_endpoint="https://your-resource.openai.azure.com", ) moda.conversation_id = "session_123" response = client.chat.completions.create( model="gpt-4o", # your deployment name messages=[{"role": "user", "content": "Hello!"}], ) print(response.choices[0].message.content) moda.flush() ``` > [!NOTE] > > With Azure OpenAI, the `model` parameter is your deployment name, not the underlying model name. Moda records the value you pass as the model identifier. **3. Verify in the dashboard** Run the script, then open [Traces](https://moda.dev/dashboard) in the dashboard. You should see a trace with ID `session_123` containing the user message and the assistant reply. The recorded model is your deployment name, and the provider is recorded as Azure. ## Streaming and tool use (Python) The `AzureOpenAI` client uses the same chat completions and embeddings classes as the standard `OpenAI` client, so Azure calls go through the same instrumentation — streaming, tool use, and embeddings are captured through the same code paths, and only the client constructor differs. The SDK records streaming responses after the stream finishes, so consume the entire stream. See the [OpenAI streaming](/ingestion/providers/openai#streaming) and [tool use](/ingestion/providers/openai#tool-use) examples; replace the client with `AzureOpenAI` and the model with your deployment name. ## Node.js support The Moda SDK for Node.js does not auto-instrument the Azure OpenAI client. To capture Azure OpenAI traffic from a Node.js app, use one of: * [OpenTelemetry](/ingestion/opentelemetry) — export GenAI spans from your existing OTel setup to Moda's OTLP endpoint. * [HTTP API](/ingestion/http-api) — send trace events directly with a simple JSON payload. * `Moda.withLLMCall()` — wrap the Azure call manually and report the request and response yourself; see [the Node.js SDK](/ingestion/node). ## Support matrix | Capability | Python | Node.js | | - | - | - | | Chat completions (`AzureOpenAI` client) | Supported | Not supported — use [OpenTelemetry](/ingestion/opentelemetry) or the [HTTP API](/ingestion/http-api) | | Streaming | Supported | Not supported | | Tool use / function calling | Supported | Not supported | | Embeddings | Supported | Not supported | | Provider detection from endpoint URL | Supported | Not supported | ## Troubleshooting **The model field shows a deployment name instead of a model name.** Expected — Azure OpenAI addresses models by deployment name, and Moda records the identifier you pass. **No traces appear in the dashboard.** Initialize Moda before constructing the `AzureOpenAI` client, and call `moda.flush()` before the process exits. Confirm the Moda API key starts with `moda_sk_`. **Authentication errors from Azure.** Verify `api_key`, `api_version`, and `azure_endpoint`, and confirm the deployment exists in your Azure OpenAI resource. These errors come from Azure, not from Moda. ## Next steps * [OpenAI](/ingestion/providers/openai) — full coverage details for the shared OpenAI instrumentation. * [Python SDK](/ingestion/python) — init options, context managers, and instrument controls. * [OpenTelemetry](/ingestion/opentelemetry) — the recommended path for Azure OpenAI from Node.js. * [HTTP API](/ingestion/http-api) — send events directly from any language. # Amazon Bedrock Source: https://docs.moda.dev/ingestion/providers/bedrock Capture Anthropic models on Bedrock automatically with the Python SDK, or send other Bedrock traffic to Moda through manual capture or the HTTP API. Moda captures Anthropic models on Amazon Bedrock automatically in Python when you call them through the `AnthropicBedrock` client from the `anthropic` package. Calls made through `boto3` (`invoke_model`, `converse`) and all Bedrock calls from Node.js are not auto-instrumented — use manual capture, the HTTP API, or OpenTelemetry for those paths. ## Support matrix | Path | Support | | - | - | | Python — `AnthropicBedrock` client (`anthropic` package) | Supported: auto-instrumented by `moda-ai` | | Python — `boto3` (`invoke_model`, `converse`) | Not auto-instrumented: use the [HTTP API](/ingestion/http-api) or [OpenTelemetry](/ingestion/opentelemetry) | | Node.js — any Bedrock client | Not auto-instrumented: use `Moda.withLLMCall`, the [HTTP API](/ingestion/http-api), or [OpenTelemetry](/ingestion/opentelemetry) | ## Python: AnthropicBedrock client ### Prerequisites * Python 3.10 or later * The `moda-ai` and `anthropic` packages * AWS credentials with Bedrock model access (environment variables, shared credentials file, or an IAM role) * A Moda API key, created at **Settings → Ingestion keys** (see [Authentication](/administration/authentication)) **1. Install the packages** ```bash theme={"dark"} pip install moda-ai anthropic ``` **2. Initialize Moda before creating the client** `moda.init()` is synchronous. Call it before you construct the `AnthropicBedrock` client. ```python app.py theme={"dark"} import os import moda from anthropic import AnthropicBedrock moda.init(os.environ["MODA_API_KEY"]) client = AnthropicBedrock(aws_region="us-east-1") moda.conversation_id = "session_8f2a" moda.user_id = "user_1042" response = client.messages.create( model="us.anthropic.claude-sonnet-4-20250514-v1:0", max_tokens=1024, messages=[{"role": "user", "content": "Hello!"}], ) print(response.content[0].text) moda.flush() ``` The examples on this page use a US cross-region inference profile ID; substitute the model or inference-profile ID that is enabled for your AWS account and region. Streaming through `client.messages.stream(...)` and async clients are captured the same way. **3. Verify in the dashboard** Open **Traces** in the [dashboard](https://moda.dev/dashboard). Within minutes you should see a trace with ID `session_8f2a` containing the user message and the assistant response, with the model name and token counts attached. ## boto3 and Node.js The Moda SDKs do not auto-instrument `boto3` or any Node.js Bedrock client. Pick one of the following. ### Node.js: manual capture with `Moda.withLLMCall` If you already use the Moda SDK for Node.js, wrap the Bedrock call and report the request and response yourself: ```typescript app.ts theme={"dark"} import { Moda } from 'moda-ai'; import { BedrockRuntimeClient, ConverseCommand } from '@aws-sdk/client-bedrock-runtime'; await Moda.init(process.env.MODA_API_KEY!); const bedrock = new BedrockRuntimeClient({ region: 'us-east-1' }); const model = 'us.anthropic.claude-sonnet-4-20250514-v1:0'; const reply = await Moda.withLLMCall({ vendor: 'bedrock', type: 'chat' }, async ({ span }) => { span.reportRequest({ model, messages: [{ role: 'user', content: 'Hello!' }], conversationId: 'session_8f2a', userId: 'user_1042', }); const response = await bedrock.send(new ConverseCommand({ modelId: model, messages: [{ role: 'user', content: [{ text: 'Hello!' }] }], })); const text = response.output?.message?.content?.[0]?.text ?? ''; span.reportResponse({ usage: { input_tokens: response.usage?.inputTokens, output_tokens: response.usage?.outputTokens, }, completions: [{ role: 'assistant', content: text }], }); return text; }); console.log(reply); await Moda.flush(); ``` Errors thrown inside the callback propagate to your code after the span is recorded. See [the Node.js SDK page](/ingestion/node) for the full `withLLMCall` reference. ### Any language: HTTP API Make the Bedrock call as usual, then post the messages to `POST /v1/ingest`: ```python bedrock_ingest.py theme={"dark"} import os import boto3 import requests bedrock = boto3.client("bedrock-runtime", region_name="us-east-1") user_message = "Hello!" response = bedrock.converse( modelId="us.anthropic.claude-sonnet-4-20250514-v1:0", messages=[{"role": "user", "content": [{"text": user_message}]}], ) assistant_message = response["output"]["message"]["content"][0]["text"] usage = response.get("usage", {}) resp = requests.post( "https://moda-ingest.modas.workers.dev/v1/ingest", headers={ "Authorization": f"Bearer {os.environ['MODA_API_KEY']}", "Content-Type": "application/json", }, json={ "events": [ { "conversation_id": "session_8f2a", "user_id": "user_1042", "role": "user", "message": user_message, }, { "conversation_id": "session_8f2a", "user_id": "user_1042", "role": "assistant", "message": assistant_message, "model": "us.anthropic.claude-sonnet-4-20250514-v1:0", "provider": "bedrock", "input_tokens": usage.get("inputTokens"), "output_tokens": usage.get("outputTokens"), }, ] }, timeout=10, ) print(resp.json()) ``` ```typescript bedrock-ingest.ts theme={"dark"} import { BedrockRuntimeClient, ConverseCommand } from '@aws-sdk/client-bedrock-runtime'; const bedrock = new BedrockRuntimeClient({ region: 'us-east-1' }); const userMessage = 'Hello!'; const response = await bedrock.send(new ConverseCommand({ modelId: 'us.anthropic.claude-sonnet-4-20250514-v1:0', messages: [{ role: 'user', content: [{ text: userMessage }] }], })); const assistantMessage = response.output?.message?.content?.[0]?.text ?? ''; const res = await fetch('https://moda-ingest.modas.workers.dev/v1/ingest', { method: 'POST', headers: { Authorization: `Bearer ${process.env.MODA_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ events: [ { conversation_id: 'session_8f2a', user_id: 'user_1042', role: 'user', message: userMessage, }, { conversation_id: 'session_8f2a', user_id: 'user_1042', role: 'assistant', message: assistantMessage, model: 'us.anthropic.claude-sonnet-4-20250514-v1:0', provider: 'bedrock', input_tokens: response.usage?.inputTokens, output_tokens: response.usage?.outputTokens, }, ], }), }); console.log(await res.json()); ``` A successful request returns: ```json theme={"dark"} { "success": true, "count": 2, "requestId": "5b2f8a3e-1c9d-4e7a-9f0b-2d6c8e4a1b3f" } ``` The full event schema and limits are on the [HTTP API page](/ingestion/http-api). ### OpenTelemetry If your service already exports OpenTelemetry spans, point them at Moda's OTLP endpoint and add GenAI attributes to your Bedrock spans — see [OpenTelemetry](/ingestion/opentelemetry). > [!NOTE] > > In Python, `moda.init()` also activates the `opentelemetry-instrumentation-bedrock` package for `boto3` when both are installed. That package is third-party and is not bundled with `moda-ai`; install it separately if you want to try this path. ## Troubleshooting | Symptom | Fix | | - | - | | `boto3` calls do not appear | Expected — `boto3` is not auto-instrumented. Use manual capture, the HTTP API, or OpenTelemetry as shown above. | | Node.js Bedrock calls do not appear | Expected — the Node.js SDK has no Bedrock instrumentation. Use `Moda.withLLMCall` or the HTTP API. | | `AnthropicBedrock` calls do not appear (Python) | Call `moda.init()` before constructing the client, and `moda.flush()` before the process exits. | | Token counts missing on HTTP API events | `/v1/ingest` only stores tokens you send. Pass `input_tokens` and `output_tokens` from the Bedrock response `usage` object. | ## Next steps * [Moda SDK for Python](/ingestion/python) — init options, context APIs, and flush semantics. * [HTTP API](/ingestion/http-api) — full event schema, limits, and error envelope. * [OpenTelemetry](/ingestion/opentelemetry) — send OTLP spans from an existing tracing setup. * [Anthropic](/ingestion/providers/anthropic) — auto-instrumentation for the Anthropic API outside Bedrock. # OpenAI Source: https://docs.moda.dev/ingestion/providers/openai Capture OpenAI API calls automatically with the Moda SDK for Python or Node.js. This page shows how to capture OpenAI API traffic with Moda. Once the SDK is initialized, calls made with the official `openai` client are captured automatically — no changes to the calls themselves. ## Prerequisites * A Moda API key (created in the dashboard at **Settings → Ingestion keys**; shown once at creation) * An OpenAI API key * Python 3.10 or later, or Node.js 18 or later * Node.js only: `openai` package version 4.0.0 or later ## Setup **1. Install the packages** ```bash pip theme={"dark"} pip install moda-ai openai ``` ```bash npm theme={"dark"} npm install moda-ai openai ``` **2. Initialize Moda before creating the client** Initialize the SDK first, then construct the OpenAI client. Flush before your process exits so buffered data is sent. ```python Python theme={"dark"} import moda from openai import OpenAI moda.init("YOUR_MODA_API_KEY") # Reads OPENAI_API_KEY from the environment client = OpenAI() moda.conversation_id = "session_123" response = client.chat.completions.create( model="gpt-4o", messages=[{"role": "user", "content": "Hello!"}], ) print(response.choices[0].message.content) moda.flush() ``` ```typescript Node.js theme={"dark"} import { Moda } from 'moda-ai'; import OpenAI from 'openai'; await Moda.init('YOUR_MODA_API_KEY'); // Reads OPENAI_API_KEY from the environment const client = new OpenAI(); Moda.conversationId = 'session_123'; const response = await client.chat.completions.create({ model: 'gpt-4o', messages: [{ role: 'user', content: 'Hello!' }], }); console.log(response.choices[0].message.content); await Moda.flush(); ``` > [!WARNING] > > In Node.js, `Moda.init()` is async and the API key argument is required (it is not read from `MODA_API_KEY`). If `Moda.init()` is not awaited, calls made before initialization completes are not captured. In Python, `moda.init()` is synchronous and also reads the `MODA_API_KEY` environment variable, so `moda.init()` with no arguments works when that variable is set. **3. Verify in the dashboard** Run the script, then open [Traces](https://moda.dev/dashboard) in the dashboard. You should see a trace with ID `session_123` containing the user message and the assistant reply, with model `gpt-4o` and token counts. Analysis signals (emotion, tool failures) typically appear within minutes of ingest. ## Trace grouping Set a trace ID — the `conversation_id` field — before the first call of a session or run, from your session, thread, job, or run ID, so every call lands in one trace. Use `moda.conversation_id` (Python) or `Moda.conversationId` / `Moda.withConversationId()` (Node.js). See [the Python SDK](/ingestion/python) and [the Node.js SDK](/ingestion/node) for the full context APIs. ## Streaming Streaming chat completions are captured automatically. The SDK records the complete response after the stream finishes, so consume the entire stream. ```python Python theme={"dark"} import moda from openai import OpenAI moda.init("YOUR_MODA_API_KEY") client = OpenAI() stream = client.chat.completions.create( model="gpt-4o", messages=[{"role": "user", "content": "Count to 5"}], stream=True, ) for chunk in stream: print(chunk.choices[0].delta.content or "", end="") moda.flush() ``` ```typescript Node.js theme={"dark"} import { Moda } from 'moda-ai'; import OpenAI from 'openai'; await Moda.init('YOUR_MODA_API_KEY'); const client = new OpenAI(); const stream = await client.chat.completions.create({ model: 'gpt-4o', messages: [{ role: 'user', content: 'Count to 5' }], stream: true, }); for await (const chunk of stream) { process.stdout.write(chunk.choices[0]?.delta?.content || ''); } await Moda.flush(); ``` ## Tool use Function calling is captured automatically, including the tool call arguments in the assistant message and any `role: "tool"` result messages you send in follow-up calls. ```python Python theme={"dark"} import moda from openai import OpenAI moda.init("YOUR_MODA_API_KEY") client = OpenAI() response = client.chat.completions.create( model="gpt-4o", messages=[{"role": "user", "content": "What's the weather in London?"}], tools=[{ "type": "function", "function": { "name": "get_weather", "description": "Get the current weather for a location", "parameters": { "type": "object", "properties": {"location": {"type": "string"}}, "required": ["location"], }, }, }], ) tool_call = response.choices[0].message.tool_calls[0] print(tool_call.function.name, tool_call.function.arguments) moda.flush() ``` ```typescript Node.js theme={"dark"} import { Moda } from 'moda-ai'; import OpenAI from 'openai'; await Moda.init('YOUR_MODA_API_KEY'); const client = new OpenAI(); const response = await client.chat.completions.create({ model: 'gpt-4o', messages: [{ role: 'user', content: "What's the weather in London?" }], tools: [{ type: 'function', function: { name: 'get_weather', description: 'Get the current weather for a location', parameters: { type: 'object', properties: { location: { type: 'string' } }, required: ['location'], }, }, }], }); const toolCall = response.choices[0].message.tool_calls?.[0]; console.log(toolCall?.function.name, toolCall?.function.arguments); await Moda.flush(); ``` ## Embeddings (Python only) The Python SDK captures `client.embeddings.create()` calls. The Node.js SDK does not instrument embeddings — it captures chat completions only. ```python Python theme={"dark"} import moda from openai import OpenAI moda.init("YOUR_MODA_API_KEY") client = OpenAI() embedding = client.embeddings.create( model="text-embedding-3-small", input="The quick brown fox", ) moda.flush() ``` To capture embeddings from a Node.js app, send them yourself via [OpenTelemetry](/ingestion/opentelemetry) or the [HTTP API](/ingestion/http-api). ## Support matrix | Capability | Python | Node.js | | - | - | - | | Chat Completions (`chat.completions.create`) | Supported | Supported | | Streaming chat completions | Supported | Supported | | Tool use / function calling | Supported | Supported | | Token usage (input, output, total) | Supported | Supported | | Embeddings | Supported | Not supported — use [OpenTelemetry](/ingestion/opentelemetry) or the [HTTP API](/ingestion/http-api) | | Responses API (`responses.create`) | Supported | Not supported | | Assistants API | Supported | Not supported | | Image generation (`images.generate`) | Supported | Not supported | | Legacy completions (`completions.create`) | Supported | Not supported | OpenAI-compatible endpoints reached through the `openai` client with a custom base URL are also captured — see [Azure OpenAI](/ingestion/providers/azure-openai) and [OpenRouter](/ingestion/providers/openrouter). ## Troubleshooting **No traces appear in the dashboard.** Initialize Moda before constructing the OpenAI client, and call `moda.flush()` (Python) or `await Moda.flush()` (Node.js) before the process exits. In Node.js, confirm `Moda.init()` is awaited and the API key starts with `moda_sk_`. **Streaming calls show no assistant message.** The response is recorded only after the stream ends. Consume the stream fully; a stream that is abandoned partway is not captured completely. **Embeddings calls are missing in Node.js.** Expected — the Node.js SDK instruments chat completions only. Use the Python SDK, [OpenTelemetry](/ingestion/opentelemetry), or the [HTTP API](/ingestion/http-api). **Every request creates a new trace.** Set a trace ID before the first call of the session (see Trace grouping above). ## Next steps * [Python SDK](/ingestion/python) — init options, context managers, and instrument controls. * [Node.js SDK](/ingestion/node) — init options, scoped context, and manual tracing. * [OpenRouter](/ingestion/providers/openrouter) — capture other models through the same `openai` client. * [Traces](/dashboard/traces) — how captured traces appear in the dashboard. # OpenClaw Source: https://docs.moda.dev/ingestion/providers/openclaw Export OpenClaw's OTLP telemetry to Moda and generate the required configuration with the Node.js SDK helpers. Moda ingests OpenClaw telemetry natively: spans exported by OpenClaw's `diagnostics-otel` plugin are accepted on the ingestion API's `/v1/traces` endpoint and grouped into Moda traces by OpenClaw session. The Moda SDK for Node.js ships helpers that generate the plugin configuration and the OTLP environment variables. The OpenClaw helpers are Node.js only — the Python SDK does not include them. ## Prerequisites * Node.js 18 or later with `moda-ai` installed (`npm install moda-ai`) * An OpenClaw installation with the `diagnostics-otel` plugin available * A Moda API key, created at **Settings → Ingestion keys** (see [Authentication](/administration/authentication)) ## Set up **1. Generate the telemetry configuration** `Moda.getOpenClawTelemetryConfig()` returns the configuration object OpenClaw's `diagnostics-otel` plugin expects, pre-filled with Moda's OTLP endpoint and your API key: ```typescript generate-config.ts theme={"dark"} import { Moda } from 'moda-ai'; // Reads MODA_API_KEY from the environment; alternatively pass an // `apiKey` option or call `await Moda.init(...)` first. const config = Moda.getOpenClawTelemetryConfig({ serviceName: 'openclaw-gateway', enableMetrics: false, enableLogs: false, }); console.log(JSON.stringify(config, null, 2)); ``` ```json Output theme={"dark"} { "plugins": { "allow": ["diagnostics-otel"], "entries": { "diagnostics-otel": { "enabled": true } } }, "diagnostics": { "enabled": true, "otel": { "enabled": true, "endpoint": "https://moda-ingest.modas.workers.dev", "protocol": "http/protobuf", "serviceName": "openclaw-gateway", "traces": true, "metrics": false, "logs": false, "headers": { "Authorization": "Bearer moda_sk_..." } } } } ``` Merge this object into your OpenClaw configuration. **2. Or generate environment variables for spawned processes** If you launch OpenClaw as a subprocess, `Moda.getOpenClawEnvironment()` returns the equivalent `OTEL_*` environment variables: ```typescript launch.ts theme={"dark"} import { spawn } from 'node:child_process'; import { Moda } from 'moda-ai'; const env = Moda.getOpenClawEnvironment({ serviceName: 'openclaw-gateway', enableMetrics: false, enableLogs: false, extraEnv: { ANTHROPIC_API_KEY: process.env.ANTHROPIC_API_KEY }, }); // Launch OpenClaw with the generated variables const child = spawn('openclaw', process.argv.slice(2), { env: { ...process.env, ...env }, stdio: 'inherit', }); ``` The returned map contains: | Variable | Value | | - | - | | `OTEL_EXPORTER_OTLP_ENDPOINT` | `https://moda-ingest.modas.workers.dev` (or your `baseUrl`) | | `OTEL_EXPORTER_OTLP_PROTOCOL` | `http/protobuf` | | `OTEL_EXPORTER_OTLP_HEADERS` | `Authorization=Bearer%20moda_sk_...` (URL-encoded) | | `OTEL_SERVICE_NAME` | Your `serviceName` (default `openclaw`) | | `OTEL_TRACES_EXPORTER` | `otlp`, or `none` when `enableTraces: false` | | `OTEL_METRICS_EXPORTER` | `otlp`, or `none` when `enableMetrics: false` | | `OTEL_LOGS_EXPORTER` | `otlp`, or `none` when `enableLogs: false` | **3. Verify** Run an OpenClaw session, then open **Traces** in the [dashboard](https://moda.dev/dashboard). Within minutes you should see a trace per OpenClaw session containing model usage and processed-message entries. > [!NOTE] > > The ingestion API stores traces only — there are no `/v1/metrics` or `/v1/logs` endpoints. Set `enableMetrics: false` and `enableLogs: false` unless another OTLP backend consumes those signals. ### Helper options Both helpers accept the same options; `getOpenClawEnvironment` additionally accepts `extraEnv`. | Option | Default | Description | | - | - | - | | `apiKey` | Key passed to `Moda.init()`, then the `MODA_API_KEY` env var | Moda API key placed in the `Authorization` header | | `baseUrl` | `baseUrl` from `Moda.init()`, then `MODA_BASE_URL`, then `https://moda-ingest.modas.workers.dev/v1/traces` | OTLP endpoint base. A trailing `/v1/traces`, `/v1/metrics`, or `/v1/logs` is stripped because OTLP exporters append the signal path themselves | | `serviceName` | `openclaw` | OpenTelemetry service name | | `enableTraces` | `true` | Export traces | | `enableMetrics` | `true` | Export metrics (set to `false` — see the note above) | | `enableLogs` | `true` | Export logs (set to `false` — see the note above) | | `additionalHeaders` | — | Extra OTLP headers to attach | | `extraEnv` (`getOpenClawEnvironment` only) | — | Extra environment variables merged into the returned map | The helpers do not require `Moda.init()` to have run: they are the only part of the Node.js SDK that falls back to the `MODA_API_KEY` and `MODA_BASE_URL` environment variables. If no key can be resolved, they throw `[Moda] MODA_API_KEY is required for OpenClaw telemetry helpers`. ## What Moda extracts from OpenClaw spans Two OpenClaw span names are mapped into trace data; other `openclaw.*` spans are ignored. | Span name | Meaning | | - | - | | `openclaw.model.usage` | A model call, with provider, model, and token usage | | `openclaw.message.processed` | A processed message, with its outcome | Attributes read from those spans: | Attribute | Used for | | - | - | | `openclaw.sessionId` | Trace grouping (preferred) | | `openclaw.sessionKey` | Trace grouping (fallback) | | `openclaw.provider` | Provider | | `openclaw.model` | Model | | `openclaw.tokens.input`, `openclaw.tokens.output` | Token usage | | `openclaw.messageId` | External message ID for the resulting message | | `openclaw.outcome`, `openclaw.reason` | Outcome of `openclaw.message.processed` spans | When neither `openclaw.sessionId` nor `openclaw.sessionKey` is present, grouping falls back to the OTLP trace ID. ## Trace your own OpenClaw operations `Moda.withOpenClawOperation()` wraps gateway or CLI lifecycle work in a span named `openclaw.` with `llm.vendor: openclaw`. Trace and user IDs (`conversationId`, `userId`) come from the options, or from the ambient Moda context when omitted. Errors are recorded on the span and re-thrown. ```typescript operations.ts theme={"dark"} import { Moda } from 'moda-ai'; await Moda.init(process.env.MODA_API_KEY!); const result = await Moda.withOpenClawOperation( { operation: 'session.start', conversationId: 'oc-sess-1', userId: 'user_1042', attributes: { 'gateway.region': 'us-east-1' }, }, async ({ span }) => { // run the OpenClaw work you want traced, then return its result span.setAttribute('session.channel', 'gateway'); return 'session-started'; }, ); console.log(result); await Moda.flush(); ``` > [!NOTE] > > Operation spans record timing and errors but do not create trace messages. Message content comes from OpenClaw's own `openclaw.model.usage` and `openclaw.message.processed` spans. ## Troubleshooting | Symptom | Fix | | - | - | | `401` from `/v1/traces` | The key is missing, invalid, or revoked. The helpers set the `Authorization: Bearer moda_sk_...` header from your API key — check the key in the dashboard at **Settings → Ingestion keys**. | | Exports succeed but nothing appears in **Traces** | The spans reaching Moda are not named `openclaw.model.usage` / `openclaw.message.processed` and carry no GenAI attributes. Confirm the `diagnostics-otel` plugin is enabled and exporting traces (not only metrics or logs). | | Every message lands in its own Moda trace | Spans are missing `openclaw.sessionId` / `openclaw.sessionKey`, so grouping falls back to the OpenTelemetry trace ID. | | Exporter errors for metrics or logs | The ingestion API has no metrics or logs endpoints. Set `enableMetrics: false` and `enableLogs: false`. | ## Next steps * [OpenTelemetry](/ingestion/opentelemetry) — the full OTLP attribute contract on `/v1/traces`. * [Moda SDK for Node.js](/ingestion/node) — init, context APIs, and flush semantics. * [Traces](/dashboard/traces) — how ingested sessions appear in the dashboard. * [Reliability](/ingestion/reliability) — retry behavior and error envelopes. # OpenRouter Source: https://docs.moda.dev/ingestion/providers/openrouter Capture OpenRouter calls made through the OpenAI client with the Moda SDK for Python or Node.js. OpenRouter exposes many models behind an OpenAI-compatible API. Moda captures OpenRouter traffic through the standard `openai` client pointed at `https://openrouter.ai/api/v1` — there is no OpenRouter-specific setup beyond the base URL. ## Prerequisites * A Moda API key (created in the dashboard at **Settings → Ingestion keys**; shown once at creation) * An OpenRouter API key * Python 3.10 or later, or Node.js 18 or later * The `openai` package (version 4.0.0 or later in Node.js) ## Setup **1. Install the packages** ```bash pip theme={"dark"} pip install moda-ai openai ``` ```bash npm theme={"dark"} npm install moda-ai openai ``` **2. Point the OpenAI client at OpenRouter** Initialize Moda first, then construct the client with the OpenRouter base URL. Flush before your process exits so buffered data is sent. ```python Python theme={"dark"} import os import moda from openai import OpenAI moda.init("YOUR_MODA_API_KEY") openrouter = OpenAI( base_url="https://openrouter.ai/api/v1", api_key=os.environ["OPENROUTER_API_KEY"], ) moda.conversation_id = "session_123" response = openrouter.chat.completions.create( model="anthropic/claude-3-haiku", max_tokens=50, messages=[{"role": "user", "content": "Say hello in exactly 3 words."}], ) print(response.choices[0].message.content) moda.flush() ``` ```typescript Node.js theme={"dark"} import { Moda } from 'moda-ai'; import OpenAI from 'openai'; await Moda.init('YOUR_MODA_API_KEY'); const openrouter = new OpenAI({ baseURL: 'https://openrouter.ai/api/v1', apiKey: process.env.OPENROUTER_API_KEY, }); Moda.conversationId = 'session_123'; const response = await openrouter.chat.completions.create({ model: 'anthropic/claude-3-haiku', max_tokens: 50, messages: [{ role: 'user', content: 'Say hello in exactly 3 words.' }], }); console.log(response.choices[0].message.content); await Moda.flush(); ``` > [!WARNING] > > In Node.js, `Moda.init()` is async and the API key argument is required (it is not read from `MODA_API_KEY`). If `Moda.init()` is not awaited, calls made before initialization completes are not captured. **3. Verify in the dashboard** Run the script, then open [Traces](https://moda.dev/dashboard) in the dashboard. You should see a trace with ID `session_123` containing the user message and the assistant reply, with token counts when OpenRouter returns usage data. ## Model naming OpenRouter model IDs use the `provider/model` format, for example `anthropic/claude-3-haiku` or `google/gemini-2.0-flash-001`. How the model is recorded differs by SDK: * **Python**: the SDK detects OpenRouter from the base URL and records the model without the provider prefix (`anthropic/claude-3-haiku` is recorded as `claude-3-haiku`). * **Node.js**: the model is recorded as sent and returned, keeping the `provider/model` format. You can switch models between calls in the same session; calls stay grouped as long as the trace ID (`conversation_id`) is the same. ## Streaming Streaming works the same as with OpenAI. The SDK records the complete response after the stream finishes, so consume the entire stream. ```python Python theme={"dark"} import os import moda from openai import OpenAI moda.init("YOUR_MODA_API_KEY") openrouter = OpenAI( base_url="https://openrouter.ai/api/v1", api_key=os.environ["OPENROUTER_API_KEY"], ) stream = openrouter.chat.completions.create( model="google/gemini-2.0-flash-001", max_tokens=50, messages=[{"role": "user", "content": "Count to 5"}], stream=True, ) for chunk in stream: print(chunk.choices[0].delta.content or "", end="") moda.flush() ``` ```typescript Node.js theme={"dark"} import { Moda } from 'moda-ai'; import OpenAI from 'openai'; await Moda.init('YOUR_MODA_API_KEY'); const openrouter = new OpenAI({ baseURL: 'https://openrouter.ai/api/v1', apiKey: process.env.OPENROUTER_API_KEY, }); const stream = await openrouter.chat.completions.create({ model: 'google/gemini-2.0-flash-001', max_tokens: 50, messages: [{ role: 'user', content: 'Count to 5' }], stream: true, }); for await (const chunk of stream) { process.stdout.write(chunk.choices[0]?.delta?.content || ''); } await Moda.flush(); ``` ## Tool use Tool calls made through the `openai` client go through the same chat completions instrumentation as OpenAI and are captured the same way, when the underlying model supports tools. See the [OpenAI tool use example](/ingestion/providers/openai#tool-use) — only the `base_url` and model name change. ## Direct API calls with manual tracing (Node.js) If you call the OpenRouter HTTP API directly instead of using the `openai` client, wrap the call with `Moda.withLLMCall()` (Node.js only) to capture it: ```typescript Node.js theme={"dark"} import { Moda } from 'moda-ai'; await Moda.init('YOUR_MODA_API_KEY'); Moda.conversationId = 'session_123'; const messages = [{ role: 'user', content: 'Hello!' }]; const result = await Moda.withLLMCall( { vendor: 'openrouter', type: 'chat' }, async ({ span }) => { span.reportRequest({ model: 'anthropic/claude-3-haiku', messages }); const response = await fetch('https://openrouter.ai/api/v1/chat/completions', { method: 'POST', headers: { Authorization: `Bearer ${process.env.OPENROUTER_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'anthropic/claude-3-haiku', messages, max_tokens: 50 }), }); if (!response.ok) throw new Error(`API error: ${response.status}`); const data = await response.json(); span.reportResponse({ model: data.model, usage: data.usage, completions: data.choices, }); return data; } ); console.log(result.choices[0].message.content); await Moda.flush(); ``` There is no Python equivalent of `withLLMCall`; from Python, use the [HTTP API](/ingestion/http-api) or [OpenTelemetry](/ingestion/opentelemetry) for direct API calls. ## Support matrix | Capability | Python | Node.js | | - | - | - | | Chat completions via `openai` client with OpenRouter base URL | Supported | Supported | | Streaming | Supported | Supported | | Tool use (model-dependent) | Supported | Supported | | Token usage | Supported (when OpenRouter returns usage) | Supported (when OpenRouter returns usage) | | Model name normalization (`provider/model` prefix stripped) | Applied | Not applied — model keeps the `provider/model` format | | Manual tracing of direct HTTP calls (`withLLMCall`) | Not supported — use the [HTTP API](/ingestion/http-api) | Supported | ## Troubleshooting **No traces appear in the dashboard.** Initialize Moda before constructing the client, and call `moda.flush()` (Python) or `await Moda.flush()` (Node.js) before the process exits. In Node.js, confirm `Moda.init()` is awaited. **Token usage is missing.** Moda records token counts only when the OpenRouter response includes a `usage` object. Whether usage is returned depends on OpenRouter and the upstream provider, not on Moda. **Model names look different between Python and Node.js apps.** Expected — the Python SDK strips the `provider/` prefix, the Node.js SDK does not. See [Model naming](#model-naming). ## Next steps * [OpenAI](/ingestion/providers/openai) — the underlying client instrumentation, including tool use. * [Node.js SDK](/ingestion/node) — init options, scoped context, and `withLLMCall` reference. * [Python SDK](/ingestion/python) — init options and context managers. * [HTTP API](/ingestion/http-api) — send events directly when no SDK path fits. # Vapi Source: https://docs.moda.dev/ingestion/providers/vapi Forward Vapi end-of-call report webhooks to Moda to capture voice calls with their turns, tool calls, and transfers. Both Moda SDKs can turn a Vapi end-of-call report into trace data: you host a webhook endpoint, Vapi posts the report when a call ends, and you pass the payload to one helper function. Use this page to set up the webhook handler in Node.js or Python and to see exactly what gets captured. ## Prerequisites * `moda-ai` for Node.js (Node 18+) or Python (3.10+) * A webhook endpoint that Vapi can reach over HTTPS * A Moda API key, created at **Settings → Ingestion keys** (see [Authentication](/administration/authentication)) ## Set up **1. Install the SDK** ```bash npm theme={"dark"} npm install moda-ai ``` ```bash pip theme={"dark"} pip install moda-ai ``` **2. Create the webhook handler** Initialize Moda once, then pass each incoming payload to the end-of-call helper. Payloads that are not end-of-call reports are ignored without error, so it is safe to route all Vapi webhooks through the same handler — the `isEndOfCallReport` guard below is optional but makes the handler's intent explicit. ```typescript server.ts (Express) theme={"dark"} import express from 'express'; import { Moda } from 'moda-ai'; await Moda.init(process.env.MODA_API_KEY!); const app = express(); app.use(express.json()); app.post('/webhooks/vapi', (req, res) => { if (Moda.isEndOfCallReport(req.body)) { Moda.processVapiEndOfCallReport(req.body); } res.json({ status: 'ok' }); }); app.listen(3000); ``` ```typescript app/api/webhooks/vapi/route.ts (Next.js) theme={"dark"} import { Moda } from 'moda-ai'; export async function POST(request: Request) { if (!Moda.isInitialized()) { await Moda.init(process.env.MODA_API_KEY!); } const payload = await request.json(); if (Moda.isEndOfCallReport(payload)) { Moda.processVapiEndOfCallReport(payload); } // On serverless platforms, flush before returning or the data is lost await Moda.flush(); return Response.json({ status: 'ok' }); } ``` ```python app.py (FastAPI) theme={"dark"} import os import moda from fastapi import FastAPI, Request moda.init(os.environ["MODA_API_KEY"]) app = FastAPI() @app.post("/webhooks/vapi") async def vapi_webhook(request: Request): payload = await request.json() if moda.is_end_of_call_report(payload): moda.process_vapi_end_of_call_report(payload) return {"status": "ok"} ``` ```python app.py (Flask) theme={"dark"} import os import moda from flask import Flask, request moda.init(os.environ["MODA_API_KEY"]) app = Flask(__name__) @app.route("/webhooks/vapi", methods=["POST"]) def vapi_webhook(): payload = request.get_json() if moda.is_end_of_call_report(payload): moda.process_vapi_end_of_call_report(payload) return {"status": "ok"} ``` **3. Point Vapi at your endpoint** In Vapi, set your assistant's server URL to the webhook endpoint and enable the `end-of-call-report` server message so Vapi posts the report when a call ends. **4. Verify in the dashboard** Complete a test call, then open **Traces** in the [dashboard](https://moda.dev/dashboard). Within minutes of the call ending you should see a new trace containing the caller and assistant turns as messages, with any tool calls captured as tool-call entries. > [!WARNING] > > On serverless platforms (Vercel, Lambda, Cloudflare Workers), call `await Moda.flush()` (Node.js) or `moda.flush()` (Python) before returning the response. The runtime can freeze or terminate after the response is sent, and unflushed data is lost. Long-running servers flush automatically on the batch interval; flush once more on shutdown. ## Function reference Both functions are available on the `Moda` object and as top-level imports in Node.js, and at module level in Python. | Node.js | Python | Behavior | | - | - | - | | `Moda.processVapiEndOfCallReport(payload, options?)` | `moda.process_vapi_end_of_call_report(payload, options=None)` | Parses the report and records the call. Returns nothing. Returns early without recording anything if the payload is not an end-of-call report. | | `Moda.isEndOfCallReport(payload)` | `moda.is_end_of_call_report(payload)` | Returns `true` if the payload is an end-of-call report, in either the current `message`-wrapped format or the legacy flat format. | Options let you override the identifiers recorded on the call: ```typescript Node.js theme={"dark"} Moda.processVapiEndOfCallReport(payload, { conversationId: 'session_8f2a', userId: 'user_1042', }); ``` ```python Python theme={"dark"} moda.process_vapi_end_of_call_report(payload, { "conversation_id": "session_8f2a", "user_id": "user_1042", }) ``` | Option (Node.js / Python) | Default when omitted | | - | - | | `conversationId` / `conversation_id` (the trace ID) | `call.id` from the report | | `userId` / `user_id` | `call.customer.number` from the report | ## What gets captured Each processed report produces one OpenTelemetry trace with a parent span for the call and child spans for its parts, so a call and its turns appear together as one Moda trace. | Span | Contents | | - | - | | `vapi.call` (one per call) | Trace and user IDs, call duration, ended reason, status, assistant ID, start and end timestamps, total cost plus a per-component cost breakdown, and — when Vapi includes analysis — the call summary, structured data, and success evaluation. | | `vapi.turn.{index}` (one per assistant turn) | The caller's message and the assistant's response, plus model, voice, transcriber, and total latency in milliseconds when the report includes turn timing. | | `vapi.tool.{name}` (one per tool execution) | Tool name, tool call ID, parameters, and result. | | `vapi.transfer` (one per squad transfer) | The transfer event. | Turns are read from the report's `call.artifact.messages`; if the artifact has no messages, a `transcript` array of `{role, message}` entries on the report is converted instead. ## Troubleshooting | Symptom | Fix | | - | - | | Nothing appears after calls end | Ensure `Moda.init()` / `moda.init()` runs before the handler processes payloads, and confirm Vapi is actually sending `end-of-call-report` messages — log the result of `isEndOfCallReport(payload)` in your handler. | | Data appears locally but not from the deployed webhook | Serverless runtime terminated before export — flush before returning the response (see the warning above). | | A call appears with no turns | The report contained no `call.artifact.messages` and no `transcript` array. Check that your Vapi assistant produces transcript data in its reports. | ## Next steps * [Moda SDK for Node.js](/ingestion/node) — init options, flush semantics, and context APIs. * [Moda SDK for Python](/ingestion/python) — the same for Python services. * [Traces](/dashboard/traces) — how captured calls appear in the dashboard. * [Reliability](/ingestion/reliability) — retry behavior and error envelopes. # Moda SDK for Python Source: https://docs.moda.dev/ingestion/python Install moda-ai to automatically capture OpenAI and Anthropic calls with trace and user context. The Moda SDK for Python (`moda-ai`) auto-instruments the OpenAI and Anthropic client libraries: after one `moda.init()` call, every LLM request, response, streamed completion, and tool call is captured and sent to Moda without changes to your provider code. This page covers installation, configuration, provider coverage, and trace context. ## Prerequisites * Python 3.10 or later * A Moda API key, created at **Settings → Ingestion keys** (see [Authentication](/administration/authentication)) * The `openai` or `anthropic` package your app already uses ## Set up **1. Install the SDK** ```bash theme={"dark"} pip install moda-ai ``` The package installs as `moda-ai` but imports as `moda`. Instrumentation for OpenAI and Anthropic is bundled — no extra packages are needed for these two providers. **2. Initialize and make a call** Call `moda.init()` once at startup, before your app makes LLM calls. Initialization is synchronous. ```python app.py theme={"dark"} import os import moda from openai import OpenAI moda.init(api_key=os.environ["MODA_API_KEY"]) client = OpenAI() moda.conversation_id = "session_8f2a" moda.user_id = "user_1042" response = client.chat.completions.create( model="gpt-4o", messages=[{"role": "user", "content": "Hello!"}], ) print(response.choices[0].message.content) moda.flush() ``` **3. Verify in the dashboard** Open **Traces** in the [dashboard](https://moda.dev/dashboard). Within minutes you should see a trace with ID `session_8f2a` containing the user message and the assistant response, with the model name and token counts attached. ## Configuration ### `moda.init()` options ```python theme={"dark"} import moda moda.init( api_key="YOUR_MODA_API_KEY", app_name="support-bot", resource_attributes={"deployment.environment": "staging"}, ) ``` | Option | Type | Default | Description | | - | - | - | - | | `api_key` | `str` | `None` | Your Moda API key. Falls back to the `MODA_API_KEY` environment variable. | | `app_name` | `str` | script name | Application name attached to all telemetry (OTel `service.name`). | | `endpoint` | `str` | `https://moda-ingest.modas.workers.dev/v1/traces` | Ingestion endpoint URL. | | `debug` | `bool` | `False` | Verbose logging; also disables batching so spans are sent immediately. | | `enabled` | `bool` | `True` | Set `False` to disable instrumentation entirely (no data is captured or sent). | | `disable_batch` | `bool` | `False` | Send each span immediately instead of batching. Useful for short-lived scripts. | | `headers` | `dict` | `{}` | Custom exporter headers. When set, they replace the default `Authorization: Bearer` header. | | `resource_attributes` | `dict` | `{}` | Extra resource attributes. Set `deployment.environment` here to tag events as `development`, `staging`, or `production`. | | `instruments` | `set[Instruments]` | `None` (all) | Allowlist of instrumentations to enable. See [Selecting instrumentations](#selecting-instrumentations). | | `block_instruments` | `set[Instruments]` | `None` | Instrumentations to disable. | > [accordion] Advanced OpenTelemetry options > > For custom OpenTelemetry pipelines, `moda.init()` also accepts `exporter` (a custom `SpanExporter`), `processor` (a `SpanProcessor` or list of them), `propagator`, `sampler`, and `span_postprocess_callback`. When `exporter` or `processor` is set, spans are exported through your components instead of Moda's default OTLP exporter. ### Environment variables | Variable | Description | | - | - | | `MODA_API_KEY` | Your Moda API key. | | `MODA_BASE_URL` | Overrides the ingestion endpoint. | | `MODA_HEADERS` | Custom exporter headers; replaces the default `Authorization` header. | > [!WARNING] > > Environment variables take precedence over arguments passed to `moda.init()`. If `MODA_API_KEY` or `MODA_BASE_URL` is set in the process environment, it overrides the `api_key` and `endpoint` arguments. ## What gets instrumented `moda.init()` patches the provider client libraries. Anything your app does through them is captured, including streaming. **OpenAI** (`openai` package, sync and async clients): * Chat Completions — `create` and `parse`, including streaming and tool calls * Responses API — create, retrieve, cancel * Legacy Completions * Embeddings * Image generation * Assistants API (assistants, threads, runs) * Realtime API — sessions opened through `beta.realtime.connect()` **Anthropic** (`anthropic` package, sync and async clients): * Messages — `create` and `stream`, including tool use and extended thinking * Beta Messages * Legacy Completions * The `AnthropicBedrock` client, so Claude called through Amazon Bedrock is captured ### Provider detection for OpenAI-compatible endpoints When you point the OpenAI client at a different `base_url`, the SDK detects the vendor from the URL and records it as the provider: | `base_url` contains | Provider recorded | | - | - | | `openai.azure.com` | `Azure` | | `openrouter.ai` | `OpenRouter` (the `provider/` prefix is stripped from model names) | | `amazonaws.com` or `bedrock` | `AWS` (cross-region model IDs such as `us.anthropic...` are normalized to the base model name) | | `googleapis.com` or `vertex` | `Google` | | anything else | `openai` | Other OpenAI-compatible endpoints (for example Groq) are still fully captured — requests, responses, and token usage — but are recorded with provider `openai`. ```python openrouter.py theme={"dark"} import os import moda from openai import OpenAI moda.init(api_key=os.environ["MODA_API_KEY"]) openrouter = OpenAI( base_url="https://openrouter.ai/api/v1", api_key=os.environ["OPENROUTER_API_KEY"], ) moda.conversation_id = "session_8f2a" response = openrouter.chat.completions.create( model="anthropic/claude-3-haiku", messages=[{"role": "user", "content": "Hello!"}], ) moda.flush() ``` ### Supported providers | Provider | Support | | - | - | | OpenAI | Supported — instrumentation bundled with `moda-ai` | | Anthropic | Supported — instrumentation bundled with `moda-ai` | | Azure OpenAI | Supported through the OpenAI client with an Azure `base_url` | | OpenRouter | Supported through the OpenAI client with the OpenRouter `base_url` — see [OpenRouter](/ingestion/providers/openrouter) | | Claude on Amazon Bedrock | Supported through the `AnthropicBedrock` client — see [Bedrock](/ingestion/providers/bedrock) | | Bedrock via `boto3` | Requires installing `opentelemetry-instrumentation-bedrock` separately | | Claude Agent SDK | Supported through the separate `moda-claude-agent-sdk` package — see [Claude Agent SDK](/ingestion/claude-agent-sdk) | | Vapi | Supported via `moda.process_vapi_end_of_call_report` — see [Vapi](/ingestion/providers/vapi) | | Other frameworks (LangChain, LlamaIndex, and more) | The SDK activates them only if you install the matching `opentelemetry-instrumentation-` package; these packages are not bundled | ## Trace and user context Set a trace ID — the `conversation_id` field — to group related calls into one trace, and a user ID to attribute them to a user. Context is stored in `contextvars`, so it is safe in async code and threaded request handlers. ### Module properties ```python theme={"dark"} import moda moda.conversation_id = "support_ticket_123" moda.user_id = "user_1042" # ... make LLM calls ... moda.conversation_id = None # clear when done moda.user_id = None ``` ### Context managers `set_conversation_id` and `set_user_id` scope the context to a block and restore the previous value on exit — use them in concurrent request handlers: ```python handler.py theme={"dark"} import os import moda from openai import OpenAI moda.init(api_key=os.environ["MODA_API_KEY"]) client = OpenAI() def handle_request(session_id: str, user_id: str, question: str) -> str: with moda.set_conversation_id(f"session_{session_id}"): with moda.set_user_id(user_id): response = client.chat.completions.create( model="gpt-4o", messages=[{"role": "user", "content": question}], ) return response.choices[0].message.content ``` ### Setters and getters ```python theme={"dark"} from moda import ( set_conversation_id_value, set_user_id_value, get_conversation_id, get_user_id, ) set_conversation_id_value("session_123") # persists until cleared set_user_id_value("user_456") print(get_conversation_id()) # "session_123" print(get_user_id()) # "user_456" set_conversation_id_value(None) # clear set_user_id_value(None) ``` > [!WARNING] > > Set the trace ID before the first model call of a session or run — from your session, thread, job, or run ID — so every call lands in one trace. ## Selecting instrumentations By default all instrumentations are enabled, but each activates only when its target package is installed. Restrict them with `instruments` (allowlist) or `block_instruments` (blocklist): ```python theme={"dark"} import moda from moda import Instruments # Only instrument OpenAI moda.init(api_key="YOUR_MODA_API_KEY", instruments={Instruments.OPENAI}) ``` ```python theme={"dark"} import moda from moda import Instruments # Everything except the HTTP-library instrumentations moda.init( api_key="YOUR_MODA_API_KEY", block_instruments={Instruments.REQUESTS, Instruments.URLLIB3}, ) ``` Available `Instruments` values: | Category | Values | | - | - | | LLM providers | `OPENAI`, `ANTHROPIC`, `BEDROCK`, `COHERE`, `GOOGLE_GENERATIVEAI`, `GROQ`, `MISTRAL`, `OLLAMA`, `REPLICATE`, `SAGEMAKER`, `TOGETHER`, `VERTEXAI`, `WATSONX`, `WRITER`, `ALEPHALPHA`, `TRANSFORMERS` | | Agent frameworks | `AGNO`, `CLAUDE_AGENT_SDK`, `CREWAI`, `HAYSTACK`, `LANGCHAIN`, `LLAMA_INDEX`, `MCP`, `OPENAI_AGENTS` | | Vector stores | `CHROMA`, `LANCEDB`, `MARQO`, `MILVUS`, `PINECONE`, `QDRANT`, `WEAVIATE` | | Infrastructure | `PYMYSQL`, `REDIS`, `REQUESTS`, `URLLIB3` | Only the OpenAI and Anthropic instrumentation packages ship with `moda-ai`. All other values take effect only if you install the corresponding `opentelemetry-instrumentation-` package yourself. ## Flushing Spans are batched and exported in the background. Call `moda.flush()` to force-export pending spans: * Always flush before a script or worker exits — unexported spans are lost when the process ends. * In long-running servers, flushing on shutdown is enough; the batch exporter sends data continuously while the process runs. * For very short-lived processes, pass `disable_batch=True` to `moda.init()` so each span is sent immediately. There is no separate shutdown function in the Python SDK; `moda.flush()` is the only lifecycle call you need. ## Troubleshooting | Symptom | Fix | | - | - | | Nothing appears in the dashboard | Call `moda.flush()` before the process exits. Confirm `moda.init()` runs before your first LLM call and that the API key is valid. | | `Error: Missing Moda API key` printed at startup | Pass `api_key` to `moda.init()` or set `MODA_API_KEY`. The SDK prints this error and stays disabled rather than raising. | | An `api_key` or `endpoint` argument seems ignored | `MODA_API_KEY` and `MODA_BASE_URL` environment variables override init arguments. Unset the variable to use the argument. | | One session shows up as many traces | Set `moda.conversation_id` (or the `set_conversation_id` context manager) before the first model call of the session. | | A gateway provider shows as `openai` | Expected: URL-based detection covers Azure, OpenRouter, AWS, and Google. Other OpenAI-compatible endpoints (for example Groq) are recorded with provider `openai`. | | `ModuleNotFoundError: No module named 'moda'` | Install `moda-ai` (the import name is `moda`) and confirm Python 3.10 or later. | ## Next steps * [Claude Agent SDK](/ingestion/claude-agent-sdk) — instrument agents built on `claude-agent-sdk`. * [OpenAI](/ingestion/providers/openai) and [Anthropic](/ingestion/providers/anthropic) — provider-specific setup details. * [Data model](/concepts/data-model) — how captured messages become traces and signals. * [Reliability](/ingestion/reliability) — delivery guarantees and limits. # Reliability Source: https://docs.moda.dev/ingestion/reliability Error envelope, status codes, retry guidance, and limits for the Moda Ingestion API. This page describes how the Ingestion API behaves under failure: the error envelope, which status codes to retry, and the request limits. It applies to the `/v1/ingest`, `/v1/ingest/multi`, and `/v1/traces` endpoints. ## Response envelope JSON responses share one envelope: ```json theme={"dark"} { "success": false, "count": 0, "message": "Queue temporarily unavailable", "requestId": "550e8400-e29b-41d4-a716-446655440000", "retryable": true } ``` **success** `boolean` Whether the request was accepted. **count** `number` Number of events accepted. `0` on failure. **message** `string` Human-readable explanation. Present on failures and on some successes (for example `No events provided` on an empty batch). **requestId** `string` UUID identifying the request — your `X-Request-ID` header value if it was a valid UUID, otherwise server-generated. Include it when contacting support. **retryable** `boolean` Present and `true` on `503` responses. When set, resend the same request after a backoff. **details** `object` On `/v1/ingest/multi` successes only: accepted-event counts per `messageType`. > [!NOTE] > > Two exceptions to the JSON envelope: `404` returns the plain-text body `Not Found`, and protobuf requests to `/v1/traces` receive OTLP protobuf bodies on success and on `503`. ## Status codes | Status | Meaning | Common causes | Retry? | | - | - | - | - | | 200 | Accepted | Events stored, or an empty batch (`count: 0`) | — | | 400 | Invalid request | Malformed JSON; missing `conversation_id` or `role`; unparseable `timestamp`; request-level `environment` outside `development`/`staging`/`production`; more than 1,000 events in a batch; `messageType` events sent to `/v1/ingest`; invalid OTLP body on `/v1/traces` | No — fix the request first | | 401 | Authentication failed | Missing `Authorization` header; invalid, expired, or revoked API key | No — fix the key first | | 404 | Unknown route | Wrong path or HTTP method (plain-text `Not Found` body) | No | | 413 | Request too large | Body over 5 MB | No — split the batch | | 500 | Internal server error | Unhandled server-side error | Yes, with backoff | | 503 | Temporarily unavailable | Ingestion backpressure, or API-key validation temporarily unavailable; response carries `retryable: true` | Yes, with backoff | `400` validation errors name the first failing event by index (for example `Event 3: invalid 'timestamp' (must be an ISO 8601 date-time when provided)`), and nothing from the batch is stored — fix the event and resend the whole request. ## Retries * Retry `503` and `500` responses, and network errors or timeouts, with exponential backoff and jitter. * Honor the `retryable` field when present: `retryable: true` means resend the same request unchanged. * Do not retry `400`, `401`, `404`, or `413` without changing the request — they fail identically every time. * Resending an unchanged request to the endpoints on this page does not create duplicate data. Send the same `X-Request-ID` on retries to correlate attempts in your logs. ## Limits | Limit | Value | Exceeded response | | - | - | - | | Request body size (all ingestion endpoints) | 5 MB | `413` `Request too large` | | Events per batch (`/v1/ingest`, `/v1/ingest/multi`) | 1,000 | `400` `Batch size exceeds limit of 1000` | | Spans per request (`/v1/traces`) | No count limit; only the 5 MB body cap applies | — | | Request rate | No rate limits are enforced | — | Batching guidance: * Group events into batches instead of sending one request per event; a single request can carry up to 1,000 events within 5 MB. * A batch is validated as a whole: one invalid event rejects the entire request with `400` and nothing is stored. * If a batch approaches 5 MB, split it into smaller batches. ## Environments Events are tagged with an environment: `development`, `staging`, or `production` (the default). * The **request-level** `environment` field on `/v1/ingest` and `/v1/ingest/multi` must be exactly one of those three values; anything else returns `400`. * **Per-event** `environment` values on `/v1/ingest`, and `moda.environment` / `deployment.environment` attributes on `/v1/traces`, are normalized case-insensitively: `dev` and `develop` map to `development`, `stg` and `stage` to `staging`, `prod` to `production`. Unrecognized values fall back to `production`. ## Key revocation Revoking an ingestion key takes effect within 60 seconds: the server caches successful key validations for up to 60 seconds, so a just-revoked key may be accepted briefly before requests start returning `401`. Failed validations are never cached — an invalid key fails immediately. ## Next steps * [Ingestion API reference](/ingestion/http-api) — endpoints, event fields, and exact request/response shapes. * [Ingestion overview](/ingestion/overview) — choose between the SDKs, OpenTelemetry, and direct HTTP. * [Authentication](/administration/authentication) — creating and revoking ingestion keys. * [Limits](/administration/limits) — account-level limits beyond the Ingestion API. # State writes Source: https://docs.moda.dev/ingestion/state-writes Report writes to your agent's own state (memories, calendar, rules, files, config) so replays rebuild it exactly: recordStateWrite, POST /v1/state-writes, and the moda.state_write span event. A replay runs one past turn of your agent again. To do that faithfully it needs the state your agent read at the start of that turn: its memories, calendar, rules, prompt-visible files and configuration. Moda can infer that state from your traces (what the prompt rendered, what tool calls changed), but inference misses writes no prompt ever shows. When your agent reports its writes directly, the replay uses exactly what you reported. Reported writes take precedence over inferred state for the same row from the first report on. Rows you never report, and the time before you started reporting, still come from inference. > [!NOTE] > > State writes are enabled per workspace. Ask Moda to turn them on; until then `POST /v1/state-writes` answers `404` and span events are ignored. ## Node and Workers SDK `moda-ai/state` (moda-ai 1.19.0 or later) works on Node and Cloudflare Workers. Report each write at the storage helper every writer goes through, after the write has landed: ```typescript theme={"dark"} import { waitUntil } from 'cloudflare:workers'; // Workers only import { createStateWriter } from 'moda-ai/state'; const state = createStateWriter({ apiKey: env.MODA_API_KEY, waitUntil, // keeps the batch alive after the response stores: ['memories', 'calendar_posts', 'files', 'config'], }); state.recordStateWrite({ store: 'memories', op: 'upsert', key: memory.id, value: memory, userId }); state.recordStateWrite({ store: 'calendar_posts', op: 'update', key: post.id, fields: { status: 'scheduled' }, userId }); state.recordStateWrite({ store: 'memories', op: 'delete', key: memory.id, userId }); ``` `recordStateWrite` returns immediately and never throws. Outside a traced turn, writes are batched and sent to `POST /v1/state-writes`. Inside one (an active, recording OpenTelemetry span), the write becomes a `moda.state_write` event on that span and is exported with the trace, which links it to the turn. Fields named like credentials (`token`, `secret`, `password`, `api_key`, `cookie`, `authorization`, `credential`, and similar) are removed at any depth before anything is sent. Narrow further with `stores` (an allowlist) and `redact` (a hook that may change a write or drop it by returning `null`). ## Write fields | Field | Type | | | - | - | - | | `store` | string, required | The collection the row lives in: letters, digits, `_ . : / -`, at most 128 characters, starting with a letter or digit. A replay groups rows by store, so use the names your replay seed reads. | | `op` | string, required | `create` or `upsert` (send the whole row in `value`), `update` (send the changed `fields`), or `delete`. | | `key` | string, required | The row's id in the store, at most 512 characters. `*` is reserved. | | `value` | JSON | The row after the write. A value that is not an object (a file's text) is stored as `{ "value": ... }`. | | `fields` | object | The changed fields of an `update`. | | `before` | JSON | The row before an `update`, when you have it: a replay uses it to fill fields the update did not touch. | | `userId` | string | The end user the row belongs to, the same id your traces carry. Omit for state shared by every user. | | `conversationId`, `traceId` | string | Optional links to the conversation and turn. | | `at` | ISO 8601 string or epoch ms, required on the wire | When the write landed. The SDK fills in the current time. Must be within the last 730 days and at most 24 hours ahead. | | `writeId` | string | Idempotency id, `[A-Za-z0-9_.:-]`, at most 128 characters. The SDK generates one. A write sent again with the same `writeId` is stored once; without one, Moda derives it from the write's content. | | `sequence` | integer | The write's place among the writes your writer sent, `0` to `2147483647`. Writes with the same `at` apply in this order. The SDK fills it in with a per-writer counter. Resend it unchanged on a retry. | `value`, `fields` and `before` together may be at most 64 KiB of JSON per write. ## POST /v1/state-writes ```bash theme={"dark"} curl -X POST https://moda-ingest.modas.workers.dev/v1/state-writes \ -H "Authorization: Bearer $MODA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "schema": "moda_state_writes.v1", "writes": [ { "writeId": "w-7f3a", "store": "memories", "op": "create", "key": "m_123", "value": { "text": "Prefers short posts" }, "userId": "user_42", "at": "2026-11-13T10:00:00Z" } ] }' ``` Up to 500 writes and 512 KiB per request. Each write is validated on its own: ```json theme={"dark"} { "accepted": 1, "rejected": [], "writeIds": ["w-7f3a"] } ``` | Status | Meaning | | - | - | | `202` | Stored. `rejected` lists `{ index, reason }` for writes that failed validation (`missing_`, `invalid_`, `value_too_large`); fix those rather than retrying them. | | `400` | The body is not JSON, has no `"schema": "moda_state_writes.v1"`, or has no writes. | | `401` | Missing or invalid API key. | | `404` | State writes are not enabled for this workspace. | | `413` | More than 500 writes or 512 KiB. | | `503` | Storage or authentication is temporarily unavailable. Retry with the same body: writes keep their `writeId`, so a retry never stores a write twice. | ## Span event Inside a traced turn, attach the same write object (one per event) to the turn's span: * event name `moda.state_write` * string attribute `moda.state_write.json` holding the write as JSON The trace id comes from the span. When the write has no `conversationId` or `userId`, the span's `moda.conversation_id` and `moda.user_id` attributes are used. Invalid events are dropped without affecting the trace. ## How replays use reported writes For a replay of a turn, Moda builds the state from every reported write up to the turn's start, in time order: `create` and `upsert` replace the row, `update` patches it, `delete` removes it. Writes made during the turn itself or after it are never included. From a row's first reported write on, what Moda inferred about that row is ignored. # Vercel AI SDK Source: https://docs.moda.dev/ingestion/vercel-ai-sdk Capture generateText, streamText, generateObject, and streamObject calls by passing Moda's telemetry configuration to the AI SDK's experimental_telemetry option. The Vercel AI SDK has built-in OpenTelemetry support behind the per-call `experimental_telemetry` option. `Moda.getVercelAITelemetry()` returns a telemetry configuration that sends each call's telemetry to Moda. Use this page when your application calls the AI SDK (the `ai` package); if you call the `openai` or `@anthropic-ai/sdk` clients directly, see the [Node.js SDK](/ingestion/node) instead. ## Prerequisites * Node.js 18 or later * The `moda-ai`, `ai`, and at least one AI SDK provider package (for example `@ai-sdk/openai` or `@ai-sdk/anthropic`) * A Moda API key (created in the dashboard at **Settings → Ingestion keys**) Examples on this page use AI SDK 4.x, the major version Moda's integration tests run against. ## Set up **1. Install packages** ```bash theme={"dark"} npm install moda-ai ai @ai-sdk/openai ``` **2. Initialize Moda once at startup** ```typescript theme={"dark"} import { Moda } from 'moda-ai'; await Moda.init(process.env.MODA_API_KEY!); ``` > [!WARNING] > > `Moda.init()` is async and the API key argument is required — the Node.js SDK does not read `MODA_API_KEY` from the environment on its own. If `Moda.init()` is not awaited, calls made before initialization completes are not captured. **3. Pass the telemetry configuration on every call** Add `experimental_telemetry: Moda.getVercelAITelemetry()` to each `generateText`, `streamText`, `generateObject`, and `streamObject` call. Telemetry is opt-in per call: AI SDK calls without `experimental_telemetry` are not captured. **4. Flush before exit** Call `await Moda.flush()` before a short-lived process exits so buffered telemetry is delivered. ## generateText ```typescript app.ts theme={"dark"} import { Moda } from 'moda-ai'; import { generateText } from 'ai'; import { openai } from '@ai-sdk/openai'; await Moda.init(process.env.MODA_API_KEY!); Moda.conversationId = 'session_123'; Moda.userId = 'user_789'; const result = await generateText({ model: openai('gpt-4o'), system: 'You are a concise support assistant.', prompt: 'I need help with my order', experimental_telemetry: Moda.getVercelAITelemetry({ functionId: 'support-chat', }), }); console.log(result.text); await Moda.flush(); ``` After running this, open **Traces** in the [dashboard](https://moda.dev/dashboard). Within minutes you should see trace `session_123` containing your user message and the assistant reply, attributed to model `gpt-4o`. ## streamText Streaming works the same way. Telemetry is recorded when the stream completes: ```typescript stream.ts theme={"dark"} import { Moda } from 'moda-ai'; import { streamText } from 'ai'; import { openai } from '@ai-sdk/openai'; await Moda.init(process.env.MODA_API_KEY!); Moda.conversationId = 'session_123'; const result = streamText({ model: openai('gpt-4o'), prompt: 'Explain TypeScript generics in three sentences.', experimental_telemetry: Moda.getVercelAITelemetry({ functionId: 'explainer', }), }); for await (const chunk of result.textStream) { process.stdout.write(chunk); } await Moda.flush(); ``` A call is still recorded if you stop consuming the stream early, as long as the process flushes before exiting. ## generateObject and streamObject Structured output is captured as JSON on the assistant message: ```typescript classify.ts theme={"dark"} import { Moda } from 'moda-ai'; import { generateObject } from 'ai'; import { openai } from '@ai-sdk/openai'; import { z } from 'zod'; await Moda.init(process.env.MODA_API_KEY!); Moda.conversationId = 'session_123'; const result = await generateObject({ model: openai('gpt-4o'), schema: z.object({ sentiment: z.enum(['positive', 'negative', 'neutral']), confidence: z.number().min(0).max(1), }), prompt: 'Classify the sentiment of: "I love this product."', experimental_telemetry: Moda.getVercelAITelemetry({ functionId: 'sentiment', }), }); console.log(result.object); await Moda.flush(); ``` `streamObject` works the same way: pass the same telemetry configuration and consume `partialObjectStream`. ## Tool calls Tool calls and tool results are captured as structured content blocks on the assistant message, including multi-step runs with `maxSteps`: ```typescript weather.ts theme={"dark"} import { Moda } from 'moda-ai'; import { generateText, tool } from 'ai'; import { openai } from '@ai-sdk/openai'; import { z } from 'zod'; await Moda.init(process.env.MODA_API_KEY!); Moda.conversationId = 'session_123'; const result = await generateText({ model: openai('gpt-4o'), prompt: 'What is the weather in San Francisco?', tools: { getWeather: tool({ description: 'Get the current weather for a location', parameters: z.object({ location: z.string().describe('City name'), }), execute: async ({ location }) => ({ temperature: 18, condition: 'foggy', location, }), }), }, maxSteps: 2, experimental_telemetry: Moda.getVercelAITelemetry({ functionId: 'weather-agent', }), }); console.log(result.text); await Moda.flush(); ``` If a tool's `execute` function throws, the AI SDK call itself still completes and the call is still captured. ## Trace and user context `getVercelAITelemetry()` copies the active `Moda.conversationId` and `Moda.userId` into the telemetry metadata (as `moda.conversation_id` — the trace ID — and `moda.user_id`) **at the moment you call it**. Set context first, and create a fresh configuration for each call. > [!WARNING] > > If no trace ID is set, each AI SDK call is grouped by its OpenTelemetry trace ID and appears as a separate Moda trace. Set an explicit trace ID via `Moda.conversationId` for anything multi-step. For sequential code, use the global properties as in the examples above. For concurrent request handlers, use the scoped helper so overlapping requests do not leak context into each other: ```typescript handler.ts theme={"dark"} import { Moda, withContext } from 'moda-ai'; import { generateText } from 'ai'; import { openai } from '@ai-sdk/openai'; await Moda.init(process.env.MODA_API_KEY!); async function handleMessage(sessionId: string, userId: string, userMessage: string) { return withContext(`session_${sessionId}`, userId, async () => generateText({ model: openai('gpt-4o'), prompt: userMessage, experimental_telemetry: Moda.getVercelAITelemetry(), }), ); } const result = await handleMessage('42', 'user_789', 'Where is my order?'); console.log(result.text); await Moda.flush(); ``` ### Setting IDs through metadata directly You can also set `moda.conversation_id` and `moda.user_id` yourself in the `metadata` option instead of using the context APIs: ```typescript metadata.ts theme={"dark"} import { Moda } from 'moda-ai'; import { generateText } from 'ai'; import { openai } from '@ai-sdk/openai'; await Moda.init(process.env.MODA_API_KEY!); const result = await generateText({ model: openai('gpt-4o'), prompt: 'Hello', experimental_telemetry: Moda.getVercelAITelemetry({ metadata: { 'moda.conversation_id': 'session_123', 'moda.user_id': 'user_789', }, }), }); console.log(result.text); await Moda.flush(); ``` If a trace or user ID is active in Moda's context when you call `getVercelAITelemetry()`, the context value overwrites the same key in your `metadata`. ## Options `Moda.getVercelAITelemetry(options?)` accepts: **recordInputs** `boolean` (default: true) Whether to record input data (prompts, messages). Set to `false` to keep sensitive inputs out of telemetry; the call is still captured, without message content. **recordOutputs** `boolean` (default: true) Whether to record output data (completions, generated text). Set to `false` to keep sensitive outputs out of telemetry. **functionId** `string` Identifier for the operation, used to distinguish different AI operations in your app. **metadata** `object` Custom metadata attached to the call's telemetry spans. Values may be strings, numbers, booleans, or arrays of those types. Merged with the `moda.conversation_id` / `moda.user_id` keys Moda adds from the active context. The returned configuration is passed as-is to `experimental_telemetry` and includes Moda's tracer, so no other OpenTelemetry setup is required. ## Prompt attribution To attribute a call to a managed prompt version, pass the prompt identifiers from `.moda/prompts.lock.json` in `metadata`: ```typescript triage.ts theme={"dark"} import { Moda } from 'moda-ai'; import { generateText } from 'ai'; import { openai } from '@ai-sdk/openai'; await Moda.init(process.env.MODA_API_KEY!); Moda.conversationId = 'session_123'; const result = await generateText({ model: openai('gpt-4o'), system: 'You are a support triage assistant.', prompt: 'Customer reports a duplicate charge on their invoice.', experimental_telemetry: Moda.getVercelAITelemetry({ metadata: { 'moda.prompt_key': 'support.triage', 'moda.prompt_version': '3', 'moda.prompt_version_id': 'pv_abc123', }, }), }); console.log(result.text); await Moda.flush(); ``` These optional identifiers are attached to the captured call as prompt attribution metadata. ## Using the AI SDK alongside the `openai` package `Moda.init()` also auto-instruments the `openai` and `@anthropic-ai/sdk` packages when they are installed. This does not double-capture AI SDK calls: the AI SDK provider packages (`@ai-sdk/openai`, `@ai-sdk/anthropic`) make their own HTTP requests and do not call through the `openai` or `@anthropic-ai/sdk` clients, so an AI SDK call is recorded only through the telemetry configuration you pass. Both capture paths can run in the same process: * Calls made through the AI SDK are captured when you pass `experimental_telemetry`, and not otherwise. * Calls made directly with the `openai` or `@anthropic-ai/sdk` clients are captured automatically. > [!NOTE] > > The Node.js SDK has no option to disable auto-instrumentation for a single provider. `Moda.init(apiKey, { enabled: false })` disables the SDK entirely. The Python SDK's `instruments` / `block_instruments` options do not exist in Node.js. ## Troubleshooting | Symptom | Fix | | - | - | | No data appears in the dashboard | Confirm `Moda.init()` is awaited before the first AI SDK call, `experimental_telemetry` is passed on the call, and `await Moda.flush()` runs before the process exits. | | Calls appear as separate traces | Set `Moda.conversationId` (or use `withContext`) *before* calling `Moda.getVercelAITelemetry()` — the configuration snapshots context at call time. | | Messages captured without content | `recordInputs: false` / `recordOutputs: false` suppress message content by design. | | A streamed call is missing | The process exited before the stream settled and flushed; consume the stream (or keep the process alive) and call `await Moda.flush()`. | For deeper debugging, initialize with `debug: true`: `await Moda.init(apiKey, { debug: true })` logs exporter activity. ## Next steps * [Node.js SDK](/ingestion/node) — init options, context APIs, and auto-instrumentation of provider clients. * [OpenTelemetry](/ingestion/opentelemetry) — the trace endpoint and attribute conventions this integration emits. * [Traces](/dashboard/traces) — how captured traces appear in the dashboard. # Linear Source: https://docs.moda.dev/integrations/linear File Problems as Linear issues, keep their status in sync both ways, and ask @Moda about a Problem from inside Linear. The Linear integration turns a [Problem](/dashboard/problems) into a Linear issue that carries its cause, impact, and evidence, and keeps the two in step: completing the issue marks the Problem fixed, and if Moda sees the Problem come back, the issue reopens with the new evidence. It is in preview; ask Moda support to enable it for your workspace. ## Connect Linear 1. Open **Integrations** and select **Connect Linear**. Only workspace admins can connect. 2. Approve the Moda app in Linear. Moda is installed as an app, so issues and comments are authored by Moda and show "Your name (via Moda)" when you file them, and the integration keeps working if the person who connected it leaves. 3. Back on **Integrations**, choose the team Problems are filed in. Optionally pick a project and labels, and decide how Linear status flows back: | Setting | Default | What it does | | - | - | - | | **Issue completed in Linear** | Mark the Problem fixed | Moda records *mark fixed*; the Problem moves to **Fixed** at the next analysis run and Moda monitors it for recurrence. | | **Issue canceled in Linear** | Do nothing | Optionally dismiss the Problem. Dismissing can't be undone in Moda, so it is off by default. | | **Problem comes back** | Move to the team's first *Todo* state | When a fixed Problem recurs, Moda moves its closed issue back to this state and comments the new evidence. | **Disconnect** revokes Moda's access in Linear and deletes the stored credentials. Existing issues stay in Linear; their status stops syncing until you reconnect. ## File a Problem On a Problem, select **Create Linear issue**. Edit the title, team, and priority, then **Create issue**. The issue contains: * the cause statement and current impact (users, traces, rank, status), * the top five pieces of evidence, each linked to its trace, * a link back to the Problem, attached to the issue. Each Problem has at most one issue. Filing again, from another tab, the CLI, or an automation, returns the issue that already exists. To track a Problem with an issue your team already has, switch to **Existing issue** and paste its ID (`ENG-123`) or URL. The chip in the Problem header shows the issue's live Linear state; **Unlink issue** removes Moda's attachment and leaves the issue in Linear. ## How status syncs | When | Then | | - | - | | The issue moves to a *completed* state | The Problem is marked fixed (unless you turned this off). | | The issue is canceled | Nothing, or the Problem is dismissed if you opted in. | | The issue is deleted, or Moda's attachment is removed | The link is removed in Moda. | | Moda marks the Problem fixed | Moda comments that it is monitoring for recurrence. | | The Problem comes back | The issue moves back to an open state and Moda comments the new impact and evidence. | | The Problem is resolved | Moda comments on the issue. | | The Problem is merged into another | The issue follows the surviving Problem, or points to the surviving Problem's own issue. | Moda-to-Linear updates run every 15 minutes. Linear-to-Moda changes are recorded immediately and applied at the next analysis run. ## Ask @Moda in Linear Mention **@Moda** in a comment on an issue (or delegate the issue to Moda) to get the linked Problem's current status, impact, cause, and top evidence. Mention @Moda with a Problem's URL to link an issue your team filed by hand to that Problem. ## Automations With both Slack automations and Linear enabled, an automation can file in Linear instead of posting to Slack. Choose **Linear** as the destination and pick a team and priority: * Problem automations (**New problem**, **Problem gets worse**) use the Problem's one issue: the first alert files it, later alerts comment on it. * Other alerts file one issue each, and a recovery comments on the issue its alert filed. ## CLI and MCP * `moda problems linear ` (MCP `problem_linear`) shows the linked issue. * `moda problems link ` (MCP `problem_linear_file`) files the issue, or links one with `--issue=ENG-123`. Both use your API key and need the integration connected. See the [parity map](/mcp/parity). # Prompt, skill, and harness tools Source: https://docs.moda.dev/mcp/hidden-features ## Prompt management The prompt tools are the [code-first prompt workflow](/prompt-management/overview) with local file discovery replaced by inline content: prompt bodies travel as arguments, and the returned `key → {promptId, versionId}` mapping plus content hashes is the lockfile replacement — persist it client-side. `moda prompts init`, `status`, and `--watch` are local-file workflows and stay CLI-only. The prompt tools accept `tenant_id` (string, optional) where noted: the tenant to operate on, defaulting to the tenant embedded in the signed API key and required only for legacy unsigned keys. ### prompts_sync Pushes prompt definitions (content inline) to the Moda prompt registry, minting new versions for changed content, and returns the server's synced list plus each prompt's content hash computed with the CLI's exact canonicalization. The sync is a full push with no explicit delete list: keys absent from `prompts` are conveyed as implicitly removed, so send the complete set every time. ```json Arguments theme={"dark"} { "prompts": [ { "key": "support.triage", "name": "Support triage", "content": "You are a support triage agent. Classify the request, then...", "source_path": "prompts/support/triage.prompt.md" } ], "dry_run": false, "source_commit": "9f8e7d6c5b4a39281706f5e4d3c2b1a098765432" } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `prompts` | object\[] | required | The full set of prompts to push, content inline (the CLI discovers these from `.moda/prompts.yml` globs). At least one entry. | | `prompts[].key` | string | required | Registry key. The CLI derives it from the file path (`prompts/support/triage.prompt.md` → `support.triage`). | | `prompts[].content` | string | required | The prompt body text, inline. | | `prompts[].name` | string | — | Display name; defaults to the key when omitted (CLI parity). | | `prompts[].description` | string | — | Description frontmatter passthrough. | | `prompts[].category` | string | — | Category frontmatter passthrough. | | `prompts[].system_prompt` | string | — | System prompt (wire: `systemPrompt`). | | `prompts[].messages` | array | — | A JSON prompt file's `messages` array. | | `prompts[].variables` | array | — | A JSON prompt file's `variables` array. | | `prompts[].variables_schema` | object | — | Wire: `variablesSchema`. | | `prompts[].model_config` | object | — | A JSON prompt file's `modelConfig` (or `model:` frontmatter; wire: `modelConfig`). | | `prompts[].tool_refs` | array | — | Wire: `toolRefs`. | | `prompts[].response_schema` | object | — | Wire: `responseSchema`. | | `prompts[].source_path` | string | — | Discovered file path, informational only (wire: `sourcePath`). | | `dry_run` | boolean | false | Compute what would change without writing registry versions (wire: `dryRun`, always sent). | | `source_commit` | string | — | The commit the content came from — the CLI sends `git rev-parse HEAD` automatically (wire: `sourceCommit`; omitted entirely when not provided). | CLI: [moda prompts sync](/cli/hidden-features#moda-prompts-sync) ### prompts_diff Previews what a sync would change by running the same `POST /prompts/sync` with `dryRun` forced to true — the server-computed replacement for `moda prompts status`/`diff`, which compare local file hashes against a local lockfile. Never writes registry versions. ```json Arguments theme={"dark"} { "prompts": [ { "key": "support.triage", "content": "You are a support triage agent. Classify the request, then..." } ] } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `prompts` | object\[] | required | Same entry shape as `prompts_sync`: the full set of prompts to compare, content inline. | | `source_commit` | string | — | Wire: `sourceCommit`; omitted when not provided. | CLI: [moda prompts status / diff](/cli/hidden-features#moda-prompts-status-moda-prompts-diff) ### prompts_promote Points a registry label (`dev`, `staging`, or `prod`) at a specific prompt version — the final step after `prompts_sync` hands you a `versionId`. Promoting overwrites the label's current assignment, and a `prod` promotion redirects live traffic immediately, so confirm the version first. ```json Arguments theme={"dark"} { "prompt_key": "support.triage", "label": "prod", "version_id": "pver_1f2e3d4c5b6a79880911223344556677" } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `prompt_key` | string | required | The registry key whose label to move. | | `label` | enum | required | `dev`, `staging`, or `prod`. | | `version_id` | string | required | The prompt version id to promote (wire: `versionId`). | CLI: [moda prompts promote](/cli/hidden-features#moda-prompts-promote) ## Skills The MCP skill tool takes SKILL.md content inline as arguments: discovering skill files under `.claude/skills/` is the client's job. ### skills_push Pushes user-authored skills (SKILL.md content inline) to the Moda skill registry, minting new versions for changed content. This is `moda skills push` with local `.claude/skills/**/SKILL.md` discovery replaced by arguments; the CLI's managed `AGENTS.md` upsert is a local file write and stays CLI-only. Unchanged content is a server-side no-op. ```json Arguments theme={"dark"} { "skills": [ { "key": "handle-refund-retries", "name": "Handle refund retries", "skill_md": "---\nname: Handle refund retries\n---\nWhen a refund tool call fails, never retry with identical arguments...", "source_path": ".claude/skills/handle-refund-retries/SKILL.md" } ], "dry_run": true } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `skills` | object\[] | required | The user-authored skills to push (the CLI discovers these under `.claude/skills/`, excluding Moda-managed ones). At least one entry. | | `skills[].key` | string | required | The skill key (the CLI derives it from the `.claude/skills//` directory name). | | `skills[].name` | string | required | Display name (the CLI reads SKILL.md frontmatter, falling back to the key). | | `skills[].skill_md` | string | required | The full SKILL.md content, inline (wire: `skillMd`). | | `skills[].description` | string | — | SKILL.md description frontmatter. | | `skills[].source_path` | string | — | The discovered file path (wire: `sourcePath`). | | `skills[].content_hash` | string | — | Wire: `contentHash`. Computed as sha256 hex of `skill_md` when omitted (CLI-exact). | | `skills[].source_commit` | string | — | Per-skill `sourceCommit`; defaults to the top-level `source_commit`. | | `dry_run` | boolean | false | Compute what would change without writing registry versions (wire: `dryRun`, always sent). | | `source_commit` | string | — | Wire: `sourceCommit`; omitted entirely when not provided. | CLI: [moda skills push](/cli/hidden-features#moda-skills-push) ## Harness The harness tools cover the server-side halves of the [harness](/harness/overview) workflow: uploading, deleting, and reading hosted analysis runs. Producing the graph and report requires the local repo, so `moda harness scan`/`analyze`/`approve`/`validate-report` stay CLI-side. ### harness_sync Uploads a harness graph — and optionally an approved analysis report (the CLI's `--from-report` form) — to the tenant's harness registry. The backend's 2,000,000-byte graph limit is enforced client-side before the POST, and `dry_run` previews without writing. ```json Arguments theme={"dark"} { "graph": { "agents": [{ "id": "agent_support" }], "artifacts": [] }, "graph_hash": "b41f0c2a9e7d5f3186c4a2e0d8b6f4a2", "source_commit": "9f8e7d6c5b4a39281706f5e4d3c2b1a098765432", "dry_run": true } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `graph` | object | — | The harness graph from local `moda harness scan`/`analyze` (`.moda/harness.json`). Required unless `report` is given. | | `graph_hash` | string | — | The graph hash computed by the local scan (wire: `graphHash`). | | `source_commit` | string | — | Wire: `sourceCommit`; omitted when not provided. | | `dry_run` | boolean | false | Validate server-side without writing (wire: `dryRun`, always sent). | | `report` | object | — | The **approved** `.moda/harness-report.json` content (wire: `report`). The CLI refuses unapproved reports unless `--dry-run`. | | `report_hash` | string | — | Wire: `reportHash`. | | `report_validation_status` | string | — | The local `moda harness validate-report` outcome, for example `pass` (wire: `reportValidationStatus`). | | `report_approval` | object | — | The recorded approval object keyed to the report hash, from `moda harness approve` (wire: `reportApproval`). | CLI: [moda harness sync](/cli/hidden-features#moda-harness-validate-report-approve-sync) ### harness_delete Permanently deletes a harness from the tenant — including every synced version, agent, artifact, and relationship under it — and returns the server's deleted counts. There is no undo, which is why the CLI demands `--yes` and this tool demands `confirm: true`. ```json Arguments theme={"dark"} { "id_or_key": "my-harness-key", "confirm": true } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `id_or_key` | string | required | The harness to delete (the CLI's positional, also `--harness`). | | `confirm` | boolean | required | Must be `true` to delete. The deletion cannot be undone. | CLI: [moda harness delete](/cli/hidden-features#moda-harness-delete) ### harness_analyze_status Reads the status, progress, and (when completed) results of a hosted harness analysis run. Starting a remote analysis requires a source snapshot built from the local repo, so kicking one off is CLI-only (`moda harness analyze --remote` prints the run id this tool takes); this is the read half that `moda harness pull` uses. Server-controlled progress strings are sanitized of ANSI/control characters before being returned. ```json Arguments theme={"dark"} { "run_id": "8a4f2c6e-1b3d-4590-9e7f-a2c4e6081b3d" } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `run_id` | string | required | The hosted analysis run id (the CLI persists it in `.moda/harness-remote-run.json`). | CLI: [moda harness pull](/cli/hidden-features#moda-harness-pull) ## Additional CLI parity entries | MCP tool | CLI command | Toolset | Writes? | | - | - | - | - | | `prompts_sync` | `moda prompts sync` | prompts | Yes | | `prompts_diff` | `moda prompts diff` | prompts | No | | `prompts_promote` | `moda prompts promote` | prompts | Yes | | `skills_push` | `moda skills push` | skills | Yes | | `harness_sync` | `moda harness sync` | harness | Yes | | `harness_delete` | `moda harness delete` | harness | Yes | | `harness_analyze_status` | `moda harness pull` | harness | No | ### CLI-only commands | Command | Why it stays CLI-only | MCP alternative | | - | - | - | | `moda harness scan/analyze/approve/validate-report/candidates/agents/graph/explain/write-summary/status/register` | Scans or bundles the local repo and reads or writes `.moda/*` artifacts. | `harness_sync` uploads a locally produced graph; `harness_analyze_status` reads a hosted analysis run. | | `moda prompts init/status/migrate/diff --watch` | Local manifest/lockfile scaffolding. | `prompts_diff`, or `prompts_sync` with `dry_run: true`, for a server-computed diff. | | `moda skills install` | Copies guides bundled with the CLI into local coding-agent skill directories. | None. | # MCP server Source: https://docs.moda.dev/mcp/overview Connect any MCP client to Moda's hosted MCP server, which exposes every remote-capable moda CLI command as a tool authenticated per request with your API key. Moda's MCP server is a hosted, remote [Model Context Protocol](https://modelcontextprotocol.io) server that exposes `moda` CLI commands as MCP tools — 34 tools (29 registered by default; see [Toolsets](#toolsets)), each mirroring one CLI command and calling the same Data API, control-plane, and ingest endpoints the [CLI](/cli/overview) calls. Some remote-capable commands have no tool yet; [CLI parity](/mcp/parity#not-yet-exposed-over-mcp) lists them. It runs stateless on Cloudflare Workers: every request carries its own API key, and the server stores no credentials and keeps no session state. Each tool's manifest entry names the CLI command it mirrors (`dev.moda/cli_command`), so anything you know about a `moda` command transfers directly. > [!NOTE] > > This server lets your tools query Moda. The dashboard's **MCP servers** page is the reverse direction — it registers *your agents'* MCP servers so Moda can observe them. ## Endpoint ``` https://moda-mcp.modas.workers.dev/mcp ``` The transport is Streamable HTTP. One endpoint serves both the stateless MCP 2026-07-28 core and 2025-era legacy Streamable HTTP clients; there is no SSE-only transport and no session to establish or resume. A fresh server instance is built per request with your API key bound to it. An unauthenticated health check lives at `/health`: ```bash theme={"dark"} curl https://moda-mcp.modas.workers.dev/health ``` ```json Output theme={"dark"} { "service": "moda-mcp", "version": "0.1.0", "endpoint": "/mcp", "transport": "streamable-http (MCP 2026-07-28 + 2025 legacy compat)", "authentication": "Send your Moda API key on every request: Authorization: Bearer moda_sk_... (or x-api-key). Keys: https://moda.dev/settings or `moda provision`.", "docs": "https://docs.moda.dev/mcp/overview" } ``` ## Authentication Every request carries an API key (called an ingestion key in the dashboard) in a header — `Authorization: Bearer moda_sk_...` preferred, or `x-api-key`. Unlike the [Data API](/data-api/overview) and [Ingestion API](/ingestion/http-api), which each read only one of those headers, the MCP server accepts either. > [!WARNING] > > Keys travel in headers only — the server never accepts a key in the URL, so it cannot leak into logs, browser history, or MCP client config screenshots of the endpoint field. Authentication is per request: there is no login step, no session, and no server-side key storage. The tenant is embedded in the signed key, so every tool call is scoped to that key's tenant and nothing can re-point it. Get a key from the dashboard at **Settings → Ingestion keys** (shown once at creation), or mint one with the CLI: [`moda provision`](/cli/overview#headless-provisioning-moda-provision) for headless environments, or `moda init` during project setup. See [Authentication](/administration/authentication) for key management. A connection without a key still initializes and lists tools; calling any tool then returns an in-band error with setup instructions (where to get a key, how to configure the header) instead of a transport failure, so agents and client UIs surface exactly what to fix. An invalid or revoked key returns the same kind of in-band guidance on every call. ## Connect from clients ```bash Claude Code theme={"dark"} claude mcp add --transport http moda https://moda-mcp.modas.workers.dev/mcp \ --header "Authorization: Bearer $MODA_API_KEY" ``` ```json Cursor (~/.cursor/mcp.json) theme={"dark"} { "mcpServers": { "moda": { "url": "https://moda-mcp.modas.workers.dev/mcp", "headers": { "Authorization": "Bearer moda_sk_..." } } } } ``` ```json VS Code (.vscode/mcp.json) theme={"dark"} { "servers": { "moda": { "type": "http", "url": "https://moda-mcp.modas.workers.dev/mcp", "headers": { "Authorization": "Bearer moda_sk_..." } } } } ``` ```bash Claude Desktop / stdio-only clients theme={"dark"} npx mcp-remote https://moda-mcp.modas.workers.dev/mcp \ --header "Authorization: Bearer $MODA_API_KEY" ``` Clients that only speak stdio (Claude Desktop among them) connect through [`mcp-remote`](https://www.npmjs.com/package/mcp-remote), which proxies stdio to the remote endpoint. In every snippet, the endpoint URL also accepts a `?toolsets=` query parameter to shrink the tool surface — see below. ## Toolsets The toolsets covered in this documentation mirror the CLI's command areas: | Toolset | Tools | Covers | | - | - | - | | `data` | 23 | Production data and intelligence: `overview`, `search`, `conversations`, `context`, `world_state`, `audit`, `frustrations`, `emotions`, `hallucinations`, `tool_failures`, `problems`, `investigate`, `ask`, ... | | `meta` | 4 | Connection diagnostics: `whoami`, `doctor`, `status`, `manifest` | By default (no `?toolsets=`) the endpoint registers 29 tools: the `data` and `meta` toolsets plus `search_tools` and `execute_tool`, which reach the prompt, skill, and harness tools on demand (see [Lean mode](#lean-mode)). Append `?toolsets=` with a comma-separated list to register exactly those toolsets instead: ``` https://moda-mcp.modas.workers.dev/mcp?toolsets=data ``` `meta` is always included even when not requested — `whoami`, `doctor`, `status`, and `manifest` are the connection-diagnosis surface. Unknown toolset names are ignored; if nothing valid remains, the default surface is served. The `prompts`, `skills`, and `harness` toolsets are not registered by default but stay reachable through `search_tools` and `execute_tool`. Tools are registered in deterministic name order, so client prompt caches stay warm across requests. ### Lean mode `?toolsets=lean` serves 12 tools: the 10 core tools (`overview`, `search`, `conversations`, `context`, `ask`, `problems`, `problem`, `frustrations`, `tool_failures`, `whoami`) plus two catalog meta-tools: * `search_tools` — keyword-searches the tool catalog (every toolset) and returns matching names, descriptions, and input schemas. * `execute_tool` — runs any tool from that catalog by name with a JSON arguments object, validated against the target tool's schema before dispatch. This is progressive disclosure: agents keep a small prompt footprint for the common flows and reach the long tail on demand. Because `execute_tool` can reach write tools, it does not advertise a read-only annotation. ## Prompts, resources, and instructions On connect, the server publishes instructions that teach the Moda data model (traces, clusters, detections, problems) and the canonical investigation flows — `overview` → `problems` → `problem` → `context`, `search` → `context` — so agents chain tools correctly instead of guessing at entity relationships. ### Investigation prompts Five MCP prompts package Moda's investigation playbooks as slash-commands in clients that support them: | Prompt | Arguments | What it does | | - | - | - | | `triage-frustrations` | `days_back`, `topic` (optional) | Finds and ranks user-frustration hotspots, with transcript evidence and one concrete next action per hotspot. | | `hallucination-audit` | `days_back` (optional) | Audits contradicted agent outputs: rule breakdown, worst traces, and whether a prompt fix is warranted. | | `debug-tool-failures` | `tool_name` (optional) | Works a failing tool from overview to root cause: failure subtypes, representative transcripts, and the fix path. | | `investigate-conversation` | `conversation_id` (required) | Deep-dives one trace: transcript, world state, and signals. | | `weekly-agent-health` | — | Produces the weekly health report: KPIs, deltas, and top problems. | ### Trace transcripts as resources The resource template `moda://conversations/{conversation_id}` returns a windowed markdown transcript of one ingested trace (5 messages centered on the latest). Search-style tools return trace IDs (`conversation_id`); clients can attach or preview the transcript by id without spending a tool call. For a specific window, use the `context` tool with `msg_index` and `window`. ## Result shape * Tool results are JSON by default. Heavy read tools accept `response_format: "concise" | "detailed"`; `concise` returns a compact markdown rendering instead of the full payload. * Results are capped at roughly 25k tokens. Oversized results are truncated with an explicit hint to narrow the query (`limit`, `days_back`, `time_range`, an id) — never silently cut. * Unknown ids return an empty result plus a warning, not an error, matching the Data API's convention. * Every read tool carries a `readOnlyHint: true` annotation (plus `idempotentHint`); write tools declare themselves non-read-only, so clients can gate them behind approval. * Errors come back as recovery instructions — what failed, why, and what to do next — never a bare status code. * Transcript excerpts, user quotes, and world-state values inside results are end-user data from your production traffic. The server quarantines them under `untrusted_data` in structured results and fences them in resource markdown, so agents treat them as data, never as instructions. ## CLI-only commands Not every `moda` command is a tool. Commands that open a browser, manage local credentials, or read and write your repo (`moda init`, `moda provision`, `moda auth *`, ...) stay CLI-only. Some remote-capable commands (custom signals, detection reviews, users, and others) have no tool yet. The `manifest` tool returns the tool-to-command map, the reason each CLI-only command is excluded (`cli_only`), and the commands not yet exposed (`not_yet_exposed`); [CLI parity](/mcp/parity) lists both. > [!NOTE] > > On the roadmap: OAuth 2.1 resource-server authentication and a listing in the official MCP registry. Header-based API key authentication is the supported path today. ## Next steps * [MCP tool reference](/mcp/tools) — every tool with its parameters and example output. * [CLI parity](/mcp/parity) — the tool-to-command map, which commands stay CLI-only, and which have no tool yet. * [CLI overview](/cli/overview) — the same surface from the terminal, and how to mint API keys. * [Data API overview](/data-api/overview) — the HTTP API behind the data toolset. # CLI parity map Source: https://docs.moda.dev/mcp/parity How the documented MCP tools map onto moda CLI commands, where wire behavior is identical, where it deliberately deviates, and which commands stay CLI-only. Every MCP tool mirrors one [CLI](/cli/overview) command with the same name (kebab-case becomes snake_case, subcommand spaces become underscores) and the same wire behavior — same endpoints, same query parameters, same encodings, same warnings. The reverse is not complete: some remote-capable `moda` commands have no MCP tool yet, and they are listed under [Not yet exposed](#not-yet-exposed-over-mcp) below. The trace tools keep their original names (`conversations`, `cluster_conversations`) while the CLI's primary commands are now `moda traces` and `moda cluster-traces` — the legacy `moda conversations` / `moda cluster-conversations` aliases still match 1:1; the mapping below covers the documented tools. Each tool's registration carries the command it mirrors in `_meta["dev.moda/cli_command"]`, and the `manifest` tool returns this entire map machine-readably at runtime. ## Tool-to-command map The documented tools, grouped by toolset. **Writes?** reflects each tool's `readOnlyHint` annotation — what approval-gating clients see. | MCP tool | CLI command | Toolset | Writes? | | - | - | - | - | | `overview` | `moda overview` | data | No | | `investigate` | `moda investigate` | data | No | | `failures` | `moda failures` | data | No | | `ask` | `moda ask` | data | No | | `clusters` | `moda clusters` | data | No | | `cluster_conversations` | `moda cluster-traces` (legacy alias `moda cluster-conversations`) | data | No | | `conversations` | `moda traces` (legacy alias `moda conversations`) | data | No | | `search` | `moda traces search` | data | No | | `world_state` | `moda traces state` | data | No | | `context` | `moda traces get` | data | No | | `audit` | `moda traces spans` | data | No | | `frustrations` | `moda detections list --family=frustration` | data | No | | `tool_failures` | `moda detections tools` | data | No | | `tool_failure_detail` | `moda detections tools` | data | No | | `emotions` | `moda detections list --family=emotion` | data | No | | `hallucinations` | `moda detections list --family=hallucination` | data | No | | `problems` | `moda problems` | data | No | | `problem` | `moda problems get` | data | No | | `problem_feedback` | `moda problems feedback` | data | Yes | | `problem_linear` | `moda problems linear` | data | No | | `problem_linear_file` | `moda problems link` | data | Yes | | `feedback` | `moda feedback` | data | Yes | | `tail` | `moda tail --once` | data | No | | `whoami` | `moda auth whoami` | meta | No | | `doctor` | `moda doctor` | meta | No | | `status` | `moda status` | meta | No | | `manifest` | `moda manifest` | meta | No | ## Wire parity contract The server ports the CLI's request-building rules exactly; anything the backend sees is byte-for-byte what the CLI would have sent. The rules: | Rule | Behavior | | - | - | | Parameters travel only when provided | Absent parameters are omitted from the query string so backend defaults apply — the backend rejects unknown parameters, and the CLI never materializes defaults client-side. The handful of client-materialized defaults the CLI *does* send are copied exactly: `days_back` on `overview`/`investigate`/`failures` (default 7, floored and clamped to 90), `category`/`severity` in the `feedback` body, `signal`/`limit` in `tail`. The retired `world_state` snapshot and replay modes send nothing in either client. | | Numeric parameters are integers | Input schemas enforce integers, serialized as integer strings on the query string — never floats, never quoted numbers in JSON bodies. | | Boolean encodings copied per endpoint | Boolean wire encodings vary per endpoint by backend contract and are copied from the CLI verbatim: `include_tool_io=true` on `/search`, but `summary_only=1` on world-state and `include_raw=1` on audit. Booleans in JSON `POST` bodies are real JSON booleans. | | Empty-200 not-found convention | The Data API answers unknown ids with HTTP 200 and an empty payload, never a 404. Tools convert that to a warning — `No found for id "..." — it may not exist in this tenant` — using the CLI's template verbatim, never an error. | | UUID pre-validation on problem sub-resources | `problem` with a `view`, `problem_feedback`, `problem_linear`, and `problem_linear_file` require a canonical problem UUID and fail fast client-side before any network call, because the backend returns 400 for non-UUID ids on those routes. The `problem` dossier (no `view`) accepts any id and answers `found: false`. | | Zero transport retries on writes | Every non-idempotent `POST` passes `retries: 0` — a transport retry after a lost response could double-run a pipeline step or insert a duplicate row. Reads retry up to 3 times on 429/5xx with exponential backoff (500 ms initial). `ask` additionally retries exactly once on a network-level failure (the CLI's poisoned-connection guard); HTTP errors never consume that retry. | ### Timeout budgets Per-call timeouts mirror the CLI's budgets. Calls not listed use the 30-second default. | Call family | Budget | | - | - | | `ask` (`POST /cli/ask`) | 250 s | | Everything else | 30 s | ## Deliberate deviations The following behaviors intentionally differ from the CLI. Each is also called out in the affected tool's description. | Area | MCP server | CLI | | - | - | - | | Path-segment ids | Every path-segment id is URL-encoded before interpolation, so ids containing `/`, `?`, or `#` cannot break out of their path segment (hardening). Query-string behavior is untouched. | Encodes some path ids (`/audit/:id`) but not others (`/clusters/:node_id/conversations`, world-state, context) by design-accident. | | `tail` | The `--once` form only: one poll returning ordered events plus a coverage record stating how much of the score-ranked emotions window was scanned. Call repeatedly and dedupe by `conversation_id`/`detection_id` to follow along. | Continuous interval polling with cross-poll dedupe and NDJSON streaming. | ## CLI-only commands Commands that open a browser, manage local credentials, or read and write your repo have no MCP tool. The `manifest` tool returns this list under `cli_only` with the same reasons. | Command | Why it stays CLI-only | MCP alternative | | - | - | - | | `moda init` | Browser sign-in, local file writes, coding-agent subprocesses. | None — run it once in a terminal; it produces the API key this server authenticates with. | | `moda provision` | Requires a browser-minted CLI session token; it mints the API key this server uses. | None — provision the key headlessly, then configure it on the connection. | | `moda auth login/status/token/api-key/logout` | Manages local credentials; MCP auth is per-request headers. | `whoami` validates the connection's key and reports its tenant (`moda auth whoami`). | | `moda profiles` / `moda config` | Local credential/profile files; an MCP connection is one credential. | Add a separate MCP server entry per environment or tenant. | | `moda sync` | Shorthand for harness, prompts, and skills sync over files discovered on disk. | `prompts_sync`, `skills_push`, and `harness_sync` take the content as arguments. | | `moda harness scan/analyze/approve/validate-report/candidates/agents/graph/explain/write-summary/status/register` | Scans or bundles the local repo and reads or writes `.moda/*` artifacts. | `harness_sync` uploads a locally produced graph; `harness_analyze_status` reads a hosted analysis run. | | `moda registry template/validate/push/prompt` | Reads or writes a local registry manifest file. | None. | | `moda agent context/investigate/next-action/evidence` | Built from local doctor state plus `.moda` artifacts. | `overview`, `investigate`, and `doctor` cover the cloud halves. | | `moda tail` (continuous) | Long-running poller. | `tail` is the `--once` form; call it repeatedly and dedupe client-side. | | `moda prompts init/status/migrate/diff --watch` | Local manifest and lockfile scaffolding. | `prompts_diff`, or `prompts_sync` with `dry_run: true`, for a server-computed diff. | | `moda skills install` | Copies guides bundled with the CLI into local coding-agent skill directories. | None. | ## Not yet exposed over MCP These commands call Moda APIs and could be tools, but the MCP server has no tool for them today. Use the CLI or the dashboard for them. The `manifest` tool returns this list under `not_yet_exposed`. | Command | Closest MCP tool | | - | - | | `moda users`, `moda user` | None. | | `moda problems impact`, `moda problems reopen` | `problems`, `problem`, `problem_feedback`. | | `moda review`, `moda reviews list` | `feedback` reports wrong data to the Moda team; it does not record a review. | | `moda signals` (all subcommands), `moda signal`, `moda detections list --family=custom_signal` | None. | | `moda detections list --family=laziness` | None. | | `moda tools list`, `moda tools get` | `tool_failures` lists failing tools only. | | `moda prompts list/show/proposals/usage/decide` | None. | | `moda skills list/show` | None (`skills_push` covers `moda skills push`). | | `moda harness list/show/versions/diff/registration` | None. | | `moda registry status/log/show/coverage` | None. | ## Next steps * [MCP server](/mcp/overview) — endpoint, authentication, toolsets, and client setup. * [MCP tool reference](/mcp/tools) — every tool with its parameters and example output. * [CLI reference](/cli/reference) — the `moda` commands these tools mirror, with flags and trimmed outputs. # MCP tool reference Source: https://docs.moda.dev/mcp/tools Moda data, investigation, and connection tools with parameters and examples. Reference for the documented tools on the hosted Moda MCP server (`https://moda-mcp.modas.workers.dev/mcp`). Connection setup, authentication, and toolset filtering (`?toolsets=data`, `?toolsets=lean`) are covered in the [MCP server overview](/mcp/overview); the tool-to-command map, including which CLI commands stay CLI-only, is in [CLI parity](/mcp/parity). This page lists each tool by area, in the same areas as the [CLI reference](/cli/reference). Conventions used below: * Authentication is per request: every call uses the API key (called an ingestion key in the dashboard) sent in the connection's `Authorization: Bearer moda_sk_...` or `x-api-key` header, and every result is scoped to that key's tenant. Calls without a key return setup guidance in-band instead of a transport error. * Optional parameters you omit are left off the request entirely, so the backend default applies — the Default column shows `—` for these, and the description states the backend default where the server documents one. A concrete value in the Default column is materialized client-side and always sent, exactly like the CLI. * Unknown ids return empty results with a warning, not errors. * A trace is one full agent run, identified by its `conversation_id` (the trace ID). Tool names and parameters keep the `conversation` / `conversation_id` names for backwards compatibility; the CLI's `moda traces` and `moda cluster-traces` commands (legacy aliases `moda conversations`, `moda cluster-conversations`) are the same surface. * Heavy read tools (`conversations`, `search`, `context`, `frustrations`, `ask`) accept `response_format: "concise"` for a compact markdown rendering instead of the full JSON payload. * Every read tool advertises `readOnlyHint: true`. Write tools (POST) are sent exactly once and never retried. * All timestamps are UTC. Transcript excerpts, user quotes, and world-state values inside results are end-user production data — results quarantine them as untrusted content, never instructions. ## Production data ### overview Returns the tenant's production health briefing: status (`attention`/`healthy`/`quiet`), key metrics, severity-ranked findings, a next-command hint, and the untouched `/overview` payload under `raw_overview`. The first call of any "how is my agent doing?" question. ```json Arguments theme={"dark"} { "days_back": 30 } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `days_back` | integer | 7 | Window in days, 1–90. Unlike most parameters this is always sent on the wire — omitted it defaults to 7 client-side and is floored/clamped to 90, exactly like the CLI. | | `raw` | boolean | false | Return the untouched `/overview` payload instead of the synthesized briefing. Client-side switch only, never sent on the wire. | CLI: [moda overview](/cli/reference#moda-overview) ### clusters Lists the topic clusters Moda groups ingested traces into, or — when `search` or `node_id` is set — runs fuzzy/semantic/hybrid cluster search (including deterministic deep-link resolution by node id). Follow up with `cluster_conversations` on a node id. ```json Arguments theme={"dark"} { "search": "calendar scheduling conflicts", "mode": "hybrid", "limit": 3 } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `parent_id` | string | — | List children of this cluster node (list route only). | | `time_range` | enum | — | `all`, `1h`, `24h`, `3d`, `7d`, `30d`, `90d`. Backend default `all` (list route only). | | `search` | string | — | Free-text cluster search, 2–200 characters; switches to the search route. | | `node_id` | string | — | Deterministic deep-link resolution, 1–512 characters; switches to the search route. | | `mode` | enum | — | `fuzzy`, `semantic`, `hybrid`. Backend default `hybrid` (search route only). | | `limit` | integer | — | 1–50 (search route only). | CLI: [moda clusters](/cli/reference#moda-clusters) ### cluster_conversations Lists the traces grouped under one topic-cluster node, with pagination. An unknown node id yields an empty-200 payload plus a not-found warning. ```json Arguments theme={"dark"} { "node_id": "node_44", "limit": 10, "offset": 0 } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `node_id` | string | required | The cluster node to list traces for. | | `limit` | integer | — | 1–100; backend default 10. | | `offset` | integer | — | ≥ 0; backend default 0. | CLI: [moda cluster-traces](/cli/reference#moda-cluster-traces) ### conversations Lists ingested traces filtered by summary text, cluster, user, time range, environment, world-state keywords, and outcome, with pagination. The main browse/filter surface when you have filters rather than a semantic query — for message-level search use `search`. ```json Arguments theme={"dark"} { "world_state": "refund,enterprise", "outcome": "negative", "time_range": "7d", "limit": 20 } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `search` | string | — | Substring match on the trace summary. | | `cluster_id` | string | — | Only traces in this cluster. | | `user_id` | string | — | Only traces for this end user. | | `time_range` | enum | — | `all`, `1h`, `24h`, `3d`, `7d`, `30d`, `90d`. Backend default `all`. | | `since` / `until` | string | — | Absolute UTC bounds, ISO 8601 date or datetime, both inclusive (a date-only `until` covers that day). Intersect `time_range`; at most 366 days. | | `environment` | enum | — | `all`, `development`, `staging`, `production`. Backend default `all`. | | `world_state` | string | — | Comma-separated keywords (max 200 characters) ANDed against each trace's world state: its task goals and summaries, and for a trace the task engine owns its facts and the user's profile. | | `outcome` | enum | — | `any`, `positive`, `negative`. `negative` keeps traces with a detected user frustration, `positive` keeps traces with none. Default `any`; sent on the wire only when not `any`. | | `include_world_state` | boolean | false | Attach a world-state summary (`hasData`, fact counts per segment) to each row (one extra parallel request per row, best-effort). | | `limit` | integer | — | 1–100; backend default 20. | | `offset` | integer | — | ≥ 0; backend default 0. | | `response_format` | enum | — | `json` or `concise`. MCP-only: `concise` returns compact markdown. Omit for JSON. | CLI: [moda traces](/cli/reference#moda-traces) ### search Message-level keyword/semantic/hybrid search across every ingested trace, returning scored hits with `conversation_id`, `message_index`, role, and a snippet. Warnings report when the backend degraded to keyword mode or ran a different mode than requested. ```json Arguments theme={"dark"} { "query": "refund failed", "mode": "hybrid", "time_range": "7d", "limit": 20 } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `query` | string | required | The text to search for, 1–500 characters (wire param `q`). | | `mode` | enum | — | `keyword`, `semantic`, `hybrid`. Backend default `hybrid`. | | `user_id` | string | — | Restrict hits to this end user. | | `time_range` | enum | — | `all`, `1h`, `24h`, `3d`, `7d`, `30d`, `90d`. Backend default `all`. | | `since` / `until` | string | — | Absolute UTC bounds, ISO 8601 date or datetime, both inclusive (a date-only `until` covers that day). Intersect `time_range`; at most 366 days. | | `limit` | integer | — | 1–100; backend default 20. No offset — pagination is limit-only. | | `include_tool_io` | boolean | false | Also search tool call inputs/outputs (wire: `include_tool_io=true`). | | `response_format` | enum | — | `json` or `concise`. | CLI: [moda traces search](/cli/reference#moda-traces-search) ### context Returns a windowed transcript of one trace: up to `window` messages either side of `msg_index`, plus `total_messages`, the summary, and each message's role, content, and tool call/result counts. The standard follow-up after `search`, `frustrations`, or `tool_failure_detail` hands you an anchor. ```json Arguments theme={"dark"} { "conversation_id": "conv_5e1a9c2b7d3f4680", "msg_index": 12, "window": 3 } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `conversation_id` | string | required | The trace ID to read. | | `msg_index` | integer | — | Center the window on this message index (≥ 0); the backend picks the center when omitted. | | `window` | integer | — | Messages either side of the center, 1–5; backend default 2. | | `response_format` | enum | — | `json` or `concise`. | CLI: [moda traces get](/cli/reference#moda-traces-get) ### world_state Reads the world state Moda tracks for one trace, as it is now: its tasks (every status; a subtask names its parent) and facts, from the task engine or the task tracker, plus the user's durable profile. There is no history of state changes. An unknown id, or a trace with no tracked tasks yet, yields an empty-200 payload (`hasData: false`) plus a not-found warning. ```json Arguments theme={"dark"} { "conversation_id": "conv_5e1a9c2b7d3f4680" } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `conversation_id` | string | required | The trace ID whose world state to read. | | `summary_only` | boolean | false | Fact counts and top facts per segment instead of the full segments (wire: `summary_only=1`). | | `snapshot` | boolean | false | Retired: returns an error naming what replaces it, without a request. | | `replay` | boolean | false | Retired: returns an error naming what replaces it, without a request. | The snapshot and replay modes folded the world-state event log, which Moda no longer writes; their arguments (`msg_index`, `block_index`, `segment_index`, `format`, `message_count`) and `event_limit` are no longer accepted and are dropped if sent. Use `context` with `msg_index` to read what happened at a turn. CLI: [moda traces state](/cli/reference#moda-traces-state) ### audit Returns the ingestion audit for one trace, looked up by its trace ID (`conversation_id`) or by an OpenTelemetry `trace_id`: spans, hierarchy, orphans, and duplicates, optionally with raw records. Use it to debug instrumentation when a transcript from `context` looks wrong or incomplete. ```json Arguments theme={"dark"} { "id": "conv_5e1a9c2b7d3f4680", "include_raw": false } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `id` | string | required | The `conversation_id` (trace ID) or OpenTelemetry `trace_id` to audit. | | `kind` | enum | — | `auto`, `trace`, `conversation`. Default `auto` (try the id as an OpenTelemetry `trace_id`, then as a `conversation_id`); sent on the wire only when not `auto`. | | `include_raw` | boolean | false | Include raw ingested records (wire: `include_raw=1`). | | `limit` | integer | — | 1–1,000; backend default 200. | CLI: [moda traces spans](/cli/reference#moda-traces-spans) ### frustrations Lists user-frustration detections, each row carrying user quotes, key turns, and a computed `anchor` (`conversation_id` + `msg_index`) pointing at the frustrated moment. It reads the frustration family of `/emotions` (the same data as `emotions` with `family: "frustration"` and the dashboard) and keeps the legacy field names. When frustration analysis is off for the tenant, a warning says that zero rows do not mean users are not frustrated. ```json Arguments theme={"dark"} { "days_back": 14, "limit": 5, "include_window": true, "window": 2 } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `days_back` | integer | — | 1–90; backend default 7. | | `limit` | integer | — | 1–20 (backend clamp); backend default 10. | | `offset` | integer | — | ≥ 0; backend default 0. | | `user_id` | string | — | Scope every figure (summary, breakdown, list) to one end user. | | `conversation_id` | string | — | Scope every figure to one trace. | | `include_window` | boolean | false | Attach a transcript window around each row's anchor. | | `window` | integer | 1 | 1–5: messages either side of the anchor. Only used with `include_window`. | | `response_format` | enum | — | `json` or `concise`. | CLI: [moda detections list --family=frustration](/cli/reference#moda-detections-list-family-frustration) ### emotions Lists multi-family emotion detections (`frustration`, `sadness`, `confusion`, `anxiety`, `trust`, `positive`) ranked by score, with a summary and signal breakdown that always cover all families — `family` filters the detections list only. ```json Arguments theme={"dark"} { "family": "confusion", "days_back": 7, "limit": 10 } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `days_back` | integer | — | 1–90; backend default 7. | | `limit` | integer | — | 1–20 (backend clamp, not the global 100); backend default 10. | | `offset` | integer | — | 0–10,000 (the backend's inclusive ceiling). Results are score-ranked; there is no cursor. | | `family` | enum | — | `frustration`, `sadness`, `confusion`, `anxiety`, `trust`, `positive`. Filters the detections list; the summary stays all-family. | CLI: [moda detections list --family=emotion](/cli/reference#moda-detections-list-family-emotion) ### hallucinations Lists hallucination detections — agent claims checked against tracked world state — with `contradicted` and `verified` kinds. `conversation_id` scopes the summary too; `kind` narrows the detections list only. ```json Arguments theme={"dark"} { "kind": "contradicted", "days_back": 7, "limit": 10 } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `days_back` | integer | — | 1–90; backend default 7. | | `limit` | integer | — | 1–20; backend default 10. | | `offset` | integer | — | 0–10,000. | | `conversation_id` | string | — | Max 200 characters: scope the summary and list to one trace. | | `kind` | enum | — | `contradicted` or `verified`: narrow the detections list. | CLI: [moda detections list --family=hallucination](/cli/reference#moda-detections-list-family-hallucination) ### tool_failures Returns the tenant-wide tool-failure rollup for the window: which tools failed, how often, and across how many traces. Follow up with `tool_failure_detail` on a failing `tool_name`. ```json Arguments theme={"dark"} { "days_back": 7 } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `days_back` | integer | — | 1–90; backend default 7. The only parameter. | CLI: [moda detections tools](/cli/reference#moda-detections-tools) ### tool_failure_detail Drills into one tool's failures: error subtypes plus concrete failing examples, each carrying a computed `anchor` (`conversation_id`, `msg_index`, `tool_use_id`, `error_subtype`). Empty subtypes and examples yield a warning — an unknown tool name and a tool with no failures in the window are indistinguishable. ```json Arguments theme={"dark"} { "tool_name": "lookupCustomer", "subtype": "timeout.expired", "limit": 5, "include_window": true } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `tool_name` | string | required | The tool whose failures to inspect (names come from `tool_failures`). | | `subtype` | string | — | Narrow examples to one error subtype. | | `days_back` | integer | — | 1–90; backend default 7. | | `limit` | integer | — | 1–20 (backend clamp); backend default 5. | | `offset` | integer | — | ≥ 0; backend default 0. | | `include_window` | boolean | false | Attach a transcript window around each example's anchor. | | `window` | integer | 1 | 1–5: messages either side of the anchor. Only used with `include_window`. | CLI: [moda detections tools](/cli/reference#moda-detections-tools-one-tool) ### problems Returns Moda's ranked Problem list for the window — deduplicated cross-signal problem groups with scores and counts — plus a `dashboard_url` deep link. The starting point of "what should I fix first?". ```json Arguments theme={"dark"} { "days_back": 30, "limit": 10 } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `days_back` | integer | — | 1–90; backend default 30 — not 7, wider than the other tools. | | `limit` | integer | — | 1–25 (backend clamp); backend default 25. | CLI: [moda problems](/cli/reference#moda-problems) ### problem Fetches one Problem: the full dossier by default, or — with `view` — one paginated sub-resource page. `family`/`door` filter the `conversations` view (affected traces) only, and sub-resource views require the canonical problem UUID (the dossier accepts any id and answers `found: false` for unknown ones). ```json Arguments theme={"dark"} { "problem_id": "3f2a9c1e-8b4d-4e6f-9a2b-1c3d5e7f9a0b", "view": "evidence", "limit": 25 } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `problem_id` | string | required | The Problem to fetch (canonical UUID required for views). | | `view` | enum | — | `evidence`, `reports`, `conversations`, `feedback`: open one sub-resource page instead of the dossier. Mirrors the CLI's view flags (at most one). | | `limit` | integer | — | 1–50 (views only). | | `cursor` | string | — | Opaque keyset cursor from a prior page's `next_cursor`, passed back verbatim (views only). | | `family` | enum | — | `tool_failure`, `emotion`, `laziness`, `hallucination`: filter the `conversations` view (ignored on other views). | | `door` | enum | — | `rubric_match`, `local_causal_chain`: filter the `conversations` view (ignored on other views). | CLI: [moda problems get](/cli/reference#moda-problems-get) ### problem_feedback Submits feedback on a Problem: `mark_fixed`, `dismiss`, `flag_attribution`, or `rename`. This is a write (POST, never auto-retried); re-read with `problems` or `problem` to see the effect. ```json Arguments theme={"dark"} { "problem_id": "3f2a9c1e-8b4d-4e6f-9a2b-1c3d5e7f9a0b", "action": "dismiss", "reason": "not actionable" } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `problem_id` | string | required | Canonical problem UUID (from `problems`/`problem`). | | `action` | enum | required | `mark_fixed`, `dismiss`, `flag_attribution`, `rename`. | | `reason` | string | — | Max 2,000 characters. Required (non-blank) for `dismiss` and `flag_attribution`; trimmed before send. | | `attribution_id` | string | — | Attribution UUID, max 64 characters. Required for `flag_attribution`; list ids via `problem` with `view: "evidence"`. | | `new_name` | string | — | Max 255 characters. Required for `rename`; sent as `new_display_name`. | | `actor` | string | `moda-mcp` | Who is submitting, max 255 characters. | CLI: [moda problems feedback](/cli/reference#moda-problems-feedback) ### problem_linear Returns the Linear issue linked to a Problem — identifier, workflow state, URL, and team — or `link: null` when none is linked. Use it after `problems`/`problem` to check whether a Problem is already tracked before filing it. Requires the Linear integration to be connected (Integrations → Linear). ```json Arguments theme={"dark"} { "problem_id": "3f2a9c1e-8b4d-4e6f-9a2b-1c3d5e7f9a0b" } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `problem_id` | string | required | Canonical problem UUID (from `problems`/`problem`). | CLI: [moda problems linear](/cli/reference#moda-problems-linear) ### problem_linear_file Files a Problem as a new Linear issue in the team's tracker, or — with `issue` — links an existing Linear issue instead. Filing is idempotent per Problem: an already-linked Problem returns its link with `created: false`. Requires the Linear integration to be connected (Integrations → Linear). This is a write (POST, never auto-retried); re-read with `problem_linear`. ```json Arguments theme={"dark"} { "problem_id": "3f2a9c1e-8b4d-4e6f-9a2b-1c3d5e7f9a0b", "priority": 2 } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `problem_id` | string | required | Canonical problem UUID (from `problems`/`problem`). | | `issue` | string | — | Link this existing issue (`ENG-123` or its `linear.app` URL) instead of filing a new one. Cannot be combined with `team_id`, `title`, or `priority`. | | `team_id` | string | integration default | Linear team to file into. | | `title` | string | the Problem's name | Issue title; trimmed and truncated to 255 characters. | | `priority` | integer | — | 0–4: 0 none, 1 urgent, 2 high, 3 medium, 4 low. | CLI: [moda problems link](/cli/reference#moda-problems-link) ### feedback Sends product feedback about Moda itself to the Moda team: a free-text note with a category, severity, and optional references. This is a write (POST, never auto-retried); every call inserts a new feedback row. It does not analyze tenant data. ```json Arguments theme={"dark"} { "note": "cluster label looks wrong", "category": "bad_cluster_label", "cluster_id": "node_44" } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `note` | string | required | What looked wrong or could be better, 1–4,000 characters. | | `category` | enum | `other` | `bad_cluster_label`, `mismatched_frustration`, `missing_data`, `noisy_data`, `wrong_tool_failure`, `incorrect_loop`, `api_quirk`, `false_positive_attribution`, `misrouted_fix`, `harness_bug`, `other`. Materialized client-side into the request body. | | `severity` | enum | `low` | `info`, `low`, `medium`, `high`. Materialized client-side into the request body. | | `conversation_id` | string | — | 1–256 characters: the trace ID this feedback concerns. | | `cluster_id` | string | — | 1–256 characters: reference the cluster. | | `tool_name` | string | — | 1–256 characters: reference the tool. | | `run_id` | string | — | 1–256 characters: reference the run. | CLI: [moda feedback](/cli/reference#moda-feedback) ### tail One tail poll — the `--once` form of `moda tail`: a snapshot of recent activity as ordered events (the last hour's traces oldest-first, and/or the last day's emotion detections by `detected_at` ascending, with a coverage record stating how much of the score-ranked emotions window was scanned). Continuous tailing is CLI-only — call this tool repeatedly and dedupe by `conversation_id`/`detection_id` yourself. ```json Arguments theme={"dark"} { "signal": "all", "limit": 20 } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `signal` | enum | `conversations` | `conversations` (new traces), `emotions`, `all`: which streams to poll. Materialized client-side. | | `limit` | integer | 20 | 1–50: traces page size for the poll. Materialized client-side. | | `full_scan` | boolean | false | Emotions only: walk the whole last-day window (up to 501 pages, offset ceiling 10,000) instead of the default 25 pages. | CLI: [moda tail](/cli/reference#moda-tail) ## Production intelligence ### investigate Runs the ranked production investigation with the same sources and ranking as `moda investigate`: four parallel Data API reads (`/overview`, `/tool-failures`, the frustration family of `/emotions`, and the top 3 Problems of the list the `problems` tool shows by default: the dream grouping from `/problems/dream` when the tenant's dashboard shows one, otherwise the Book from `/problems`) synthesized into at most 8 severity-ranked findings with evidence refs and suggested next tools. Each fetched Problem and the top frustration finding keep a slot, so a burst of tool failures cannot push them out. Each source is best-effort, but failed reads never read as "no issue": a rejected API key, or every source failing, returns an error result; when only some sources fail, the result is degraded (`degraded: true`, `failed_sources` names them, and the summary starts with "Incomplete:"), and each failure is also a warning and a `source_status` entry. `problems_view` says which Problems list was used (`dream` or `book`), the window its counts cover (without `days_back`, the dream run's window, the dashboard's default), and the `problems` call that lists the same Problems in the same order. ```json Arguments theme={"dark"} { "days_back": 7, "tool": "lookupCustomer" } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `days_back` | integer | 7 | Window in days, 1–90; always sent on every fetch, clamped like the CLI. | | `tool` | string | — | Scope the failure lookup to one tool — switches the fetch to `/tool-failures/{tool}?days_back=N&limit=5` (URL-encoded). | | `conversation` | string | — | Trace ID (`--trace`). Scopes only the frustration evidence (sent as `conversation_id` on `/emotions`); overview, tool failures, and Problems stay tenant-wide, and a warning says so. | CLI: [moda investigate](/cli/reference#moda-investigate) ### failures The failure-only variant of `investigate`, matching `moda failures`: it reads only `/overview` and `/tool-failures` and ranks tool-failure (and insufficient-data) findings with the same severity rules. Frustrations and Problems are not fetched; use `investigate` or `problems` for those. Failed reads follow the `investigate` rules: a rejected key or both reads failing is an error, and one failed read gives a degraded result with `failed_sources`. ```json Arguments theme={"dark"} { "tool": "lookupCustomer", "days_back": 7 } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `days_back` | integer | 7 | Window in days, 1–90; always sent on both fetches. | | `tool` | string | — | Scope the failure lookup to one tool. | CLI: [moda failures](/cli/reference#moda-failures) ### ask Asks the Moda Cloud intelligence agent a free-form question about production behavior and returns a cited answer: the canonical `moda.intelligence.v1` payload as `structuredContent` plus the full ask result (answer, confidence, evidence refs, next commands). The slowest tool — up to \~4 minutes. If the cloud agent is unavailable or returns an empty answer, the result degrades to a locally synthesized answer built from the `investigate` evidence (`degraded: true`, with warnings). If those reads fail too (a rejected key, or every source down), `ask` returns an error instead of an answer. ```json Arguments theme={"dark"} { "question": "what should I fix first?", "days_back": 14, "response_format": "concise" } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `question` | string | required | The free-form question, non-empty. | | `days_back` | integer | 7 | Evidence window in days, 1–90. Sent to the cloud agent as `daysBack` in the POST body. | | `response_format` | enum | `detailed` | `detailed` or `concise`. `concise` returns a compact markdown rendering (answer + evidence + next commands). | CLI: [moda ask](/cli/reference#moda-ask) ## Connection & meta The meta tools reinterpret the CLI's local-machine diagnostics as their cloud-only halves. They take no parameters and stay registered in every toolset mode — they are the connection-diagnosis surface. ### whoami Validates the connection's Moda API key against the live API and reports the tenant it is scoped to. Call this first when any other tool returns an auth error, or to confirm which tenant this connection reads from. A key with no embedded tenant id (legacy unsigned key) yields a warning that tenant-scoped tools need an explicit `tenant_id` argument. ```json Arguments theme={"dark"} {} ``` CLI: [moda auth whoami](/cli/reference#moda-auth-whoami) ### doctor Runs the cloud half of `moda doctor`: validates the API key, probes the Data API and the ingest worker, and checks whether the tenant received data in the last day. Use it when tools return empty results or errors to distinguish auth, connectivity, and no-data cases. Local workspace checks remain CLI-only. ```json Arguments theme={"dark"} {} ``` CLI: [moda doctor](/cli/reference#moda-doctor) ### status The compact form of `doctor`: one call returning overall health plus last-day trace/failure/frustration counts. Use it for a quick liveness look before an investigation; use `doctor` for per-check detail. ```json Arguments theme={"dark"} {} ``` CLI: [moda status](/cli/reference#moda-status) ### manifest Describes this MCP server: version, toolsets, the full 1:1 map between MCP tools and moda CLI commands, and which CLI commands are CLI-only and why. Use it to discover capabilities outside the currently enabled toolsets. ```json Arguments theme={"dark"} {} ``` CLI: [moda manifest](/cli/reference#moda-manifest) ## Lean mode Connecting with `?toolsets=lean` registers 12 tools: ten core tools (`overview`, `search`, `conversations`, `context`, `ask`, `problems`, `problem`, `frustrations`, `tool_failures`, `whoami`) plus the two below, which give progressive access to the rest of the catalog without loading every schema into the client's context. The default connection (no `?toolsets=`) registers them too, next to the `data` and `meta` toolsets. They do not appear when `?toolsets=` lists toolsets, and have no CLI equivalent. ### search_tools Searches the catalog of Moda tools (every toolset) by keyword when the registered tools don't cover the need. Returns up to 10 matches with tool names, descriptions, and full input schemas — call a match with `execute_tool`. ```json Arguments theme={"dark"} { "query": "hallucination world state" } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `query` | string | required | Keywords to match against tool names, titles, descriptions, and CLI commands. | ### execute_tool Runs any tool from the `search_tools` catalog by name with a JSON arguments object; an unknown name returns an error. Arguments are validated against the target tool's schema before dispatch — invalid arguments return the expected schema in the error. Because it can reach write tools, it does not advertise `readOnlyHint`. ```json Arguments theme={"dark"} { "name": "hallucinations", "arguments": { "kind": "contradicted", "days_back": 7 } } ``` | Parameter | Type | Default | Description | | - | - | - | - | | `name` | string | required | Tool name from `search_tools`, for example `hallucinations`. | | `arguments` | object | — | Arguments object for the target tool; validated against that tool's schema. | ## Next steps * [MCP server overview](/mcp/overview) — endpoint, authentication, transport, and per-client connection setup. * [CLI parity](/mcp/parity) — the full tool-to-command map and which CLI commands stay CLI-only. * [Data API overview](/data-api/overview) — the HTTP surface these tools call, with the same auth key. # Prompt attribution Source: https://docs.moda.dev/prompt-management/attribution Stamp prompt identifiers on runtime LLM calls so Moda links traces to the prompt versions that produced them. Syncing gives every prompt an immutable version; attribution tells Moda which version served each production call. You attribute calls by stamping prompt identifiers on the data you already send: with the `prompt` option of the Cloudflare Think and AI SDK 7 helpers, as event fields on the HTTP Ingestion API, as span attributes over OpenTelemetry, or as telemetry metadata with the Vercel AI SDK. > [!NOTE] > > There is no SDK call that renders a prompt and attributes it automatically. The `moda-ai/think` and `moda-ai/ai7` helpers accept a `prompt` option (below). Auto-instrumented OpenAI and Anthropic calls made through the Moda SDKs carry no prompt attribution, because the SDKs expose no option to stamp these fields on auto-generated spans. For those, use one of the other mechanisms on this page. ## Where the identifiers come from `moda prompts sync` writes `.moda/prompts.lock.json` with the registry IDs for every prompt: ```json .moda/prompts.lock.json theme={"dark"} { "version": 1, "generatedAt": "2026-08-16T09:12:44.310Z", "prompts": { "support.triage": { "key": "support.triage", "sourcePath": "prompts/support/triage.prompt.md", "contentHash": "8c1f27ab…", "promptId": "prompt_7d1a9c0b3e5f24681357ace9", "versionId": "pver_0f31c2ab9d4e8877a1b2c3d4e5f60718" } } } ``` Read the lockfile at startup (or bake the values in at build time) and stamp `promptId` and `versionId` on the calls that use that prompt. ## Identifier fields | Purpose | `/v1/ingest` event field | OTLP span attribute | Vercel AI SDK metadata key | | - | - | - | - | | Prompt key | `prompt_name` (send the key) | `moda.prompt_key` | `moda.prompt_key` | | Registry prompt ID (`prompt_…`) | `prompt_id` | `moda.prompt_id` | `moda.prompt_id` | | Display name | `prompt_name` | `moda.prompt_name` | `moda.prompt_name` | | Version string (human-readable) | `prompt_version` | `moda.prompt_version` | `moda.prompt_version` | | Registry version ID (`pver_…`) | `prompt_version_id` | `moda.prompt_version_id` | `moda.prompt_version_id` | | Agent (registered agent key or trace name) | `agent_name` | `gen_ai.agent.name` or `moda.agent_name` | `moda.agent_name` | How much you send determines what you get: * **Linking to a prompt** requires `prompt_id` equal to the registry prompt ID, or `prompt_name` equal to the prompt key. On OTLP paths, `moda.prompt_key` alone is enough — the ID and name default to the key. * **Per-version usage** requires `prompt_version_id`. Without it, calls link to the prompt but not to a specific version. * **Registry coverage** matches the agent name against your [registered agents](/harness/registry), so `moda registry coverage` can show which calls resolve to one. * `prompt_version` is a free-form display string (for example a semver or git SHA of your choosing); it defaults to the version ID when omitted. Stamp the fields on the assistant events or LLM spans produced by the prompt. ## Cloudflare Think and AI SDK 7 `createThinkTelemetry` (from `moda-ai/think`, for Cloudflare Think agents) and `createAI7Telemetry` (from `moda-ai/ai7`, for direct AI SDK 7 `generateText` and `streamText` calls) take a `prompt` option. Pass the lockfile entry for the prompt the call uses. The helpers read its `key`, `promptId`, and `versionId` and stamp them on every model span they export, so you do not set the attribute names yourself. Both need `moda-ai` 1.16.0 or later. Import the lockfile at build time, so the version IDs ship with the deployed Worker: ```typescript src/agent.ts theme={"dark"} import { Think, type TurnContext } from '@cloudflare/think'; import { createThinkTelemetry } from 'moda-ai/think'; import lock from '../.moda/prompts.lock.json'; interface Env { MODA_API_KEY: string; AI: Ai } export class SupportAgent extends Think { async beforeTurn(_context: TurnContext) { const moda = createThinkTelemetry({ apiKey: this.env.MODA_API_KEY, prompt: lock.prompts['support.triage'], onExportError: error => console.error('Moda export failed', error.message), }); return { telemetry: moda.telemetry }; } } ``` Without Think, pass the same option to `createAI7Telemetry` and hand its `telemetry` to the call: ```typescript app.ts theme={"dark"} import { generateText } from 'ai'; import { createAI7Telemetry } from 'moda-ai/ai7'; import lock from './.moda/prompts.lock.json'; const moda = createAI7Telemetry({ apiKey: process.env.MODA_API_KEY!, conversationId: sessionId, prompt: lock.prompts['support.triage'], }); const result = await generateText({ ...existingOptions, telemetry: moda.telemetry }); await moda.flush(); ``` Keep rendering the prompt in your own code; the option only attributes the call. Re-run `moda prompts sync` and rebuild whenever a prompt changes, or new calls keep reporting the previous `versionId`. Create one helper per prompt-specific call (per turn for Think), so each call carries the version it actually used. ## HTTP Ingestion API Set the `prompt_*` fields directly on `/v1/ingest` events: ```bash theme={"dark"} curl -X POST https://moda-ingest.modas.workers.dev/v1/ingest \ -H "Authorization: Bearer YOUR_MODA_API_KEY" \ -H "Content-Type: application/json" \ -d '{ "events": [ { "conversation_id": "conv_support_1042", "role": "user", "message": "My invoice is wrong", "timestamp": "2026-08-16T09:30:00Z" }, { "conversation_id": "conv_support_1042", "role": "assistant", "message": "I can help with that. Let me pull up the invoice.", "model": "gpt-4o", "provider": "openai", "input_tokens": 412, "output_tokens": 58, "timestamp": "2026-08-16T09:30:02Z", "prompt_name": "support.triage", "prompt_id": "prompt_7d1a9c0b3e5f24681357ace9", "prompt_version_id": "pver_0f31c2ab9d4e8877a1b2c3d4e5f60718" } ] }' ``` ```json Response theme={"dark"} { "success": true, "count": 2, "requestId": "d4f7c2a1-9b3e-4c58-a1f2-3e8b90c47d15" } ``` See [HTTP API](/ingestion/http-api) for the full event schema, batch limits, and error envelope. ## OpenTelemetry span attributes If you export OTLP traces to Moda from your own OpenTelemetry setup, set the `moda.prompt_*` attributes on each LLM span (see [OpenTelemetry](/ingestion/opentelemetry) for exporter setup). Moda also reads `gen_ai.prompt.name` as a fallback for the prompt name. With the Moda SDK for Node.js, manual capture via `withLLMCall` exposes the underlying OTel span, so you can stamp the attributes there. Use this for calls the SDK does not auto-instrument: ```typescript app.ts theme={"dark"} import { Moda, type Message } from 'moda-ai'; import { readFileSync } from 'node:fs'; await Moda.init(process.env.MODA_API_KEY!); const lock = JSON.parse(readFileSync('.moda/prompts.lock.json', 'utf8')); const triage = lock.prompts['support.triage']; const messages: Message[] = [ { role: 'system', content: 'Route urgent account issues before answering.' }, { role: 'user', content: 'My invoice is wrong.' }, ]; Moda.conversationId = 'conv_support_1042'; const data = await Moda.withLLMCall({ vendor: 'openai', type: 'chat' }, async ({ span }) => { span.rawSpan.setAttribute('moda.prompt_key', 'support.triage'); span.rawSpan.setAttribute('moda.prompt_id', triage.promptId); span.rawSpan.setAttribute('moda.prompt_version_id', triage.versionId); span.reportRequest({ model: 'gpt-4o', messages }); const response = await fetch('https://api.openai.com/v1/chat/completions', { method: 'POST', headers: { Authorization: `Bearer ${process.env.OPENAI_API_KEY}`, 'Content-Type': 'application/json', }, body: JSON.stringify({ model: 'gpt-4o', messages }), }); const result = await response.json(); span.reportResponse({ model: result.model, usage: result.usage, completions: result.choices, }); return result; }); console.log(data.choices[0]?.message?.content); await Moda.flush(); ``` `withLLMCall` is Node.js only. The Moda SDK for Python has no manual-capture equivalent; from Python, send attributed events through the [HTTP API](/ingestion/http-api) or set the attributes in your own OpenTelemetry instrumentation. ## Vercel AI SDK Pass the identifiers in the `metadata` of `Moda.getVercelAITelemetry`. The AI SDK forwards metadata keys as span attributes that Moda reads: ```typescript app.ts theme={"dark"} import { Moda } from 'moda-ai'; import { generateText } from 'ai'; import { openai } from '@ai-sdk/openai'; import { readFileSync } from 'node:fs'; await Moda.init(process.env.MODA_API_KEY!); const lock = JSON.parse(readFileSync('.moda/prompts.lock.json', 'utf8')); const triage = lock.prompts['support.triage']; const userMessage = 'My invoice is wrong.'; Moda.conversationId = 'conv_support_1042'; const result = await generateText({ model: openai('gpt-4o'), system: 'Route urgent account issues before answering.', prompt: userMessage, experimental_telemetry: Moda.getVercelAITelemetry({ metadata: { 'moda.prompt_key': 'support.triage', 'moda.prompt_id': triage.promptId, 'moda.prompt_version_id': triage.versionId, }, }), }); console.log(result.text); await Moda.flush(); ``` > [!WARNING] > > `Moda.getVercelAITelemetry()` snapshots the trace and user context at the moment it is called. Set `Moda.conversationId` (or wrap the call in `withConversationId`) before creating the telemetry config, or the call is grouped without your trace ID. See [Vercel AI SDK](/ingestion/vercel-ai-sdk) for the full integration, including streaming and tool calls. ## What attribution unlocks * **Runtime usage per version.** The prompt detail page (Dashboard → Prompts → your prompt, Versions tab) shows calls, traces, and input/output tokens grouped by version. Rows appear within minutes of ingestion. * **Version-aware analysis.** Attributed traces let you compare how different versions behave in production. Calls without `prompt_version_id` still count toward the prompt's overall usage as long as they carry the prompt key or ID. ## Next steps * Cloudflare Think setup for coding agents: `moda skills install integration-cloudflare-think` installs the integration skill, which ends with this attribution step. * [Prompt workflow](/prompt-management/workflow) — where the lockfile and version IDs come from. * [HTTP API](/ingestion/http-api) — full `/v1/ingest` event schema and limits. * [OpenTelemetry](/ingestion/opentelemetry) — exporting OTLP traces to Moda from your own setup. # Prompt management overview Source: https://docs.moda.dev/prompt-management/overview Version prompts as files in your repository and track which version serves each production call. Moda prompt management is code-first: prompt files live in your repository, and the `moda` CLI syncs them to a versioned registry. Use it to keep an immutable history of every prompt change, mark which version is released where, and see how each version behaves in production. ## How it works 1. Prompt files (`.prompt.md` or `.prompt.json`) live in your repo. A manifest at `.moda/prompts.yml` declares where to find them. 2. `moda prompts sync` uploads them to the registry. Each unique content gets an immutable, content-addressed version. 3. Release labels (`dev`, `staging`, `prod`) point at versions. Promoting moves a label; it never changes content. 4. At runtime, your application stamps prompt identifiers on its LLM calls so Moda can attribute traces to versions. See [Prompt attribution](/prompt-management/attribution). > [!NOTE] > > The Moda SDKs do not include a prompt fetch, render, or templating API. Your application loads prompt content the same way it does today — from source files, constants, or your own loader. Moda versions the files and attributes runtime calls; it is not in the request path. ## Versions are content-addressed and immutable A version's identity is a hash of the prompt's key and content: the prompt text, system prompt, messages, variables, variables schema, model config, tool references, and response schema. This means: * Syncing unchanged content is a no-op that returns the same version ID. Retries and repeated CI runs never create duplicate versions. * Any content change creates a new version. Existing versions are never modified. * Changing only `name`, `description`, or `category` does not create a new version. * There is no delete or archive operation. Deleting a local file removes it from your lockfile on the next sync, but the prompt and its versions remain in the registry. Version IDs look like `pver_0f31c2ab9d4e8877a1b2c3d4e5f60718`; prompt IDs look like `prompt_7d1a9c0b3e5f24681357ace9`. Both are recorded in `.moda/prompts.lock.json` after a sync. ## Release labels A label points at exactly one version of a prompt. Promoting moves the label from whichever version held it to the target version. | Label | Behavior | | - | - | | `dev` | The current version. Every `moda prompts sync` moves `dev` to the version just synced. | | `staging` | Moves only when you promote: `moda prompts promote --label=staging --version=`. | | `prod` | Moves only when you promote: `moda prompts promote --label=prod --version=`. | > [!WARNING] > > Promoting a version to `dev` is overwritten by the next sync, because sync always moves the `dev` label to the version it just uploaded. Use `staging` or `prod` for pins that should survive syncs. > [!NOTE] > > Release labels are release pointers in the prompt registry. They are unrelated to the `environment` field (`development` / `staging` / `production`) on ingested traces. ## Prompts in the dashboard Open **Dashboard → Prompts** (in the Improve group). The library page lists repository-synced prompts with their versions, release labels, and call counts. Filter tabs narrow the list by label: All, Prod, Staging, Dev, Unlabeled. Each prompt's detail page shows the key, its labels, the source path, source commit, and manifest hash, plus its **Versions**: every synced version with its content, buttons to promote a version to `staging` or `prod`, a release-label panel showing which version each label points at, and a runtime usage table (calls, traces, input and output tokens per version). Usage rows appear only for calls that carry [prompt attribution](/prompt-management/attribution). ## Next steps * [Prompt workflow](/prompt-management/workflow) — set up the manifest, file formats, sync, and promote. * [Prompt attribution](/prompt-management/attribution) — link runtime LLM calls to prompt versions. * [CLI reference](/cli/reference) — full command and flag listing for the `moda` CLI. # Prompt workflow Source: https://docs.moda.dev/prompt-management/workflow Initialize the prompt manifest, write prompt files, sync versions, and promote release labels with the moda CLI. This page covers the day-to-day prompt management loop: create the manifest, write prompt files, check local state, sync versions, and promote release labels. All commands come from the `moda` CLI. ## Prerequisites * `@moda-ai/cli` installed: `npm install -g @moda-ai/cli` (Node.js >= 18). * An API key for `sync` and `promote`: set `MODA_API_KEY`, or run `moda init` once to provision and store one. `init`, `status`, `diff`, and `migrate` work offline. * If you already have a key and no browser (CI, a coding agent), `moda auth login --api-key` validates and stores it non-interactively; `moda auth whoami` confirms it worked. **1. Create the manifest** ```bash theme={"dark"} moda prompts init ``` Run this from your project root: the manifest path is resolved against the current working directory. The command reports the absolute `manifestPath` it wrote (and lists it under `artifacts` in agent mode), so you can verify the result without guessing where it landed. This writes `.moda/prompts.yml` if it does not exist (it never overwrites an existing manifest): ```yaml .moda/prompts.yml theme={"dark"} version: 2 prompt_paths: - "prompts/**/*.prompt.md" - "prompts/**/*.prompt.json" - "prompts/**/*.prompt.yaml" - "prompts/**/*.prompt.yml" sources: [] ``` A version 2 manifest has two fields: * **`prompt_paths`**: [fast-glob](https://github.com/mrmlnc/fast-glob) patterns, matched exactly and relative to the repository root. A pattern without glob characters is an exact file path, and the file must exist. Prefix a pattern with `!` to exclude matches. `node_modules`, `.git`, `dist`, `build`, `.env*`, `*.pem`, and `*.key` are never matched, and symlinks are rejected. * **`sources`**: prompts that live in code or config, mapped in place. See [Map prompts defined in code](#map-prompts-defined-in-code). `moda prompts sync` adds the mappings its discovery verifies, and you can also write them by hand. > [!NOTE] > > Manifests written by older CLIs say `version: 1`. They keep working, but those CLIs discovered prompts by `.prompt.*` suffix anywhere in the repository, while patterns are now exact globs. If prompt files outside `prompts/` stopped syncing, see [Migrate a version 1 manifest](#migrate-a-version-1-manifest). > [!NOTE] > > Although the default manifest lists `.prompt.yaml` and `.prompt.yml` patterns, the CLI parses those files with the same frontmatter parser as `.prompt.md`. Write prompts as `.prompt.md` or `.prompt.json`. **2. Write prompt files** **Markdown format** — optional frontmatter, then the prompt content as the body: ```md prompts/support/triage.prompt.md theme={"dark"} --- key: support.triage name: Support triage description: Classify incoming support requests category: support system_prompt: Route urgent account issues before answering. model: gpt-4o --- Classify the support request by urgency, account area, and next required tool. Return concise JSON with urgency, area, and rationale. ``` Recognized frontmatter keys: | Key | Effect | | - | - | | `key` | Registry key. Defaults to the path-derived key (below). | | `name` | Display name. Defaults to the key. | | `description` | Shown in the dashboard. | | `category` | Grouping metadata. | | `system_prompt` (or `systemPrompt`) | System prompt stored with the version. | | `model` | Stored as `modelConfig.model`. | Frontmatter is parsed line by line as flat `key: value` pairs — nested YAML structures and lists are not supported, and `.prompt.md` files cannot declare variables. Use `.prompt.json` for structured prompts. **JSON format** — supports the full schema, including messages, variables, and tool references: ```json prompts/support/answer.prompt.json theme={"dark"} { "key": "support.answer", "name": "Support answer", "description": "Draft grounded support replies after tool checks.", "content": "Write a concise answer that cites the tool result and names the next action.", "systemPrompt": "Prefer verified account state over assumptions.", "messages": [ { "role": "system", "content": "Prefer verified account state over assumptions." }, { "role": "user", "content": "{{customer_request}}" } ], "variables": [ { "name": "customer_request", "description": "The user's support request." } ], "variablesSchema": { "type": "object", "properties": { "customer_request": { "type": "string" } }, "required": ["customer_request"] }, "modelConfig": { "model": "gpt-4o", "temperature": 0.2 }, "toolRefs": [ { "name": "lookup_account_status" } ] } ``` Supported JSON fields: `key`, `name`, `description`, `category`, `content` (defaults to the pretty-printed `messages` array when omitted), `messages`, `systemPrompt`, `variables`, `variablesSchema`, `modelConfig`, `toolRefs`, `responseSchema`. `variables` and `variablesSchema` are stored as declared metadata with each version; the CLI and registry do not render or substitute variables. **Key derivation.** When no explicit `key` is set, the key comes from the file path: strip a leading `prompts/`, strip the `.prompt.` extension, and replace slashes with dots. `prompts/support/triage.prompt.md` becomes `support.triage`. **3. Check local state** ```bash theme={"dark"} moda prompts status ``` `status` is local-only — no network call. It compares discovered files against `.moda/prompts.lock.json`: ```json theme={"dark"} { "manifest": ".moda/prompts.yml", "lockfile": ".moda/prompts.lock.json", "manifestVersion": 2, "legacyManifest": false, "zeroMatchPatterns": ["prompts/**/*.prompt.yaml", "prompts/**/*.prompt.yml"], "legacyOnlyFiles": [], "sources": 0, "total": 2, "changed": 1, "new": 1, "deleted": 0, "prompts": [ { "key": "support.triage", "sourcePath": "prompts/support/triage.prompt.md", "contentHash": "8c1f27ab…", "lockedHash": "2f9e40cd…", "versionId": "pver_0f31c2ab9d4e8877a1b2c3d4e5f60718", "state": "changed" }, { "key": "support.answer", "sourcePath": "prompts/support/answer.prompt.json", "contentHash": "b47d19ce…", "lockedHash": null, "versionId": null, "state": "new" } ] } ``` Per-prompt `state` is one of `new` (not in the lockfile), `unchanged` (hash matches), `changed` (hash differs), or `deleted` (in the lockfile but no longer on disk). `status` also checks the manifest itself: * `zeroMatchPatterns` lists `prompt_paths` patterns that match no file. A manifest whose patterns all match nothing, and that has no `sources:`, syncs nothing without reporting an error. * `legacyOnlyFiles` lists `.prompt.*` files that older CLIs discovered but the current patterns miss. When it is non-empty, `status` warns and points at `moda prompts migrate`. `moda doctor` runs the same check as `prompts_discovered`. `moda prompts diff` runs the same comparison but lists only prompts that are `new`, `changed`, or `deleted`. It compares hashes; it is not a textual diff of prompt content. **4. Sync versions** ```bash theme={"dark"} moda prompts sync ``` Sync first scans for source definitions, then uses an installed coding-agent CLI (Claude Code, Codex, or Cursor) to follow unresolved relationships. New code mappings receive a separate semantic review, with deterministic checks of the selected source and cited SDK binding. Uncertain candidates stay in `discovery.pending` and are not uploaded. Existing configured mappings remain authoritative; no application modules are imported to extract prompt text. ```bash theme={"dark"} moda prompts sync --dry-run # deterministic preview moda prompts sync --dry-run --analyst=claude # assisted preview, no saved versions moda prompts sync --analyst=local-scan # no agent calls moda prompts sync --no-analyze # configured sources only ``` The default `auto` analyst uses an installed, authenticated CLI. Assistance uses that CLI's account and has no fixed wall-clock timeout; cancel the command to stop it. If assistance is unavailable, configured sources and dedicated prompt files still sync, while uncertain candidates remain pending. `--assist=none` also disables assistance. Agent-generated prompt text is never uploaded. Successful sync saves new accepted source mappings in `.moda/prompts.yml`. Runtime-composed prompts remain typed builder definitions with dependency fingerprints and partial coverage, not rendered runtime text. Finding one fragment does not mean every prompt in the repository has been found. Sync uploads **all** eligible prompts, not only changed ones. Because versions are content-addressed, unchanged prompts resolve to their existing version IDs and create nothing new. On success the CLI writes `.moda/prompts.lock.json`: ```json .moda/prompts.lock.json theme={"dark"} { "version": 1, "generatedAt": "2026-08-16T09:12:44.310Z", "prompts": { "support.triage": { "key": "support.triage", "sourcePath": "prompts/support/triage.prompt.md", "contentHash": "8c1f27ab…", "promptId": "prompt_7d1a9c0b3e5f24681357ace9", "versionId": "pver_0f31c2ab9d4e8877a1b2c3d4e5f60718" } } } ``` The lockfile holds the IDs you need for [runtime attribution](/prompt-management/attribution) and for `promote`. It is rewritten wholesale on each sync; commit it alongside your prompt files. Every sync also moves the `dev` label to the just-synced version of each prompt, so every synced prompt carries `dev`: `moda prompts list --label=dev` lists them all, and `--label=unlabeled` matches none. In API responses the label pointers are `devVersion` (the same value as `currentVersion`), `stagingVersion`, and `prodVersion`, and each version's `labels` lists every label pointing at it. A version's `releaseLabel` holds at most one stored label, so read `labels` for the full set. Options: * `--dry-run` — the server computes and returns the IDs without writing anything; the lockfile is not updated. * `--from-harness[=]` — first register the prompt mappings from a harness report (default `.moda/harness-report.json`). Reports from older CLIs are normalized, and prompts without a `promptSource` are mapped from their `sourcePath` when that is unambiguous. Prompts that still do not resolve against current source are listed in `harnessImport.skipped` with a reason. The command fails only when none resolve; regenerate the report with `moda harness analyze --experimental --concern=prompts`. * `--watch` — re-check local files on an interval and re-sync when hashes change. `--interval=` sets the poll interval (default 2500, minimum 1000). `moda sync prompts` is an alias for `moda prompts sync`. **5. Promote a release label** ```bash theme={"dark"} moda prompts promote support.triage --label=staging --version=pver_0f31c2ab9d4e8877a1b2c3d4e5f60718 ``` `--label` accepts `dev`, `staging`, or `prod`; `--version` (alias `--version-id`) takes the version ID from the lockfile or from `moda prompts status`. The label moves atomically from whichever version held it to the target version. Promote to `staging` before `prod` if you validate releases in a pre-production environment. You can also promote from the dashboard: each version on the prompt's Versions tab has staging and prod promote buttons. > [!WARNING] > > A `--label=dev` promotion is overwritten by the next `moda prompts sync`, because sync always moves `dev` to the version it just uploaded. ## Verify in the dashboard After the first sync, open **Dashboard → Prompts**. You should see each discovered prompt with one version, the `dev` label on that version, and the source path and commit you synced from. After a promote, the label badge moves to the target version on the prompt's Versions tab. ## Optional: sync automatically from CI Add this GitHub Actions workflow to run `moda prompts sync` (and `moda skills sync`) on every push to `main` — and only `main`, so unmerged versions are never published. It needs two repository secrets: `MODA_API_KEY` and `MODA_TENANT_ID`. ```yaml .github/workflows/moda-autosync.yml theme={"dark"} name: Moda Autosync on: push: branches: [main] permissions: contents: read concurrency: group: moda-autosync cancel-in-progress: true jobs: moda-sync: runs-on: ubuntu-latest env: MODA_API_KEY: ${{ secrets.MODA_API_KEY }} MODA_TENANT_ID: ${{ secrets.MODA_TENANT_ID }} steps: - uses: actions/checkout@v4 - uses: actions/setup-node@v4 with: node-version: 22 - name: Sync prompts to Moda run: npx -y --package=@moda-ai/cli@ moda prompts sync - name: Sync skills to Moda run: npx -y --package=@moda-ai/cli@ moda skills sync ``` Replace `` with an exact `@moda-ai/cli` release — the pin makes CLI upgrades explicit, reviewable diffs. ## Map prompts defined in code A prompt that lives in application code or config does not need its own file. Map it under `sources:` with a stable key, the file, and a selector: ```yaml .moda/prompts.yml theme={"dark"} version: 2 prompt_paths: - "prompts/**/*.prompt.md" sources: - key: support.system path: src/agent.ts selector: symbol: SYSTEM_PROMPT # a named TypeScript/JavaScript/Python definition - key: support.policy path: config/agents.yaml selector: pointer: /support/prompt # JSON Pointer into a JSON or YAML file - key: support.build path: src/prompt.py selector: symbol: build_prompt kind: builder # text | messages | template | builder dependencies: - path: config/policy.txt ``` | Field | Meaning | | - | - | | `key` | Registry key and lockfile key. Keep it stable: sync and `--from-harness` refuse to remap an existing key to a different `path` or `selector`, so change it by editing the manifest. | | `path` | File inside the repository. | | `selector.symbol` / `selector.pointer` | Which definition in the file. Omit it for a whole-file prompt. | | `kind` | Optional. Static strings resolve to `text` or `messages`, and strings with placeholders stay a `template`. Functions and runtime composition are `builder` definitions, versioned by source and dependency fingerprints rather than rendered text. | | `dependencies` | Files a builder reads. Editing one mints a new version. | Python selectors need `python3`. Modules are parsed, never imported. When a file is matched by both a glob and a `sources:` entry, the `sources:` entry owns it. Builders and templates are not plain prompt text: run the application's builder and attribute the resulting model call to its registry version. ## Migrate a version 1 manifest The default manifest has not changed, but discovery has. The first CLIs matched any file ending in `.prompt.md` or `.prompt.json` anywhere in the repository. Patterns are now exact globs from the repository root, so with the default `prompts/**` patterns, files such as `src/agents/support.prompt.md` silently stopped syncing. `moda prompts status` reports them as `legacyOnlyFiles`. ```bash theme={"dark"} moda prompts migrate --dry-run # print the rewritten manifest; writes nothing moda prompts migrate # apply it moda prompts migrate --discover # also scan for code-defined prompts ``` `migrate` rewrites `.moda/prompts.yml` to version 2: * Every existing pattern and `sources:` entry is kept, and comments are preserved. * Each legacy-only file is added to `prompt_paths` as an explicit path. Its path-derived key, lockfile entry, and version history stay the same. * A `sources:` list is added if missing. `--discover` scans for code-defined prompts without agent calls. A code mapping needs independent verification before it is registered, so the scan adds only mappings that need none. It lists the other candidates under `pendingSources`. To map them, run `moda harness analyze --experimental --concern=prompts` with an installed analyst, then `moda prompts sync --from-harness`, or add them under `sources:` yourself. The write is atomic. Running `migrate` on a version 2 manifest with nothing to add changes nothing. Patterns that still match nothing are kept and reported so you can fix or remove them. ## How the content hash is computed The lockfile `contentHash` decides whether a prompt is `changed` and which registry version it maps to. To check a lockfile from your own tooling, use the published helper instead of reimplementing it: ```typescript theme={"dark"} import { computePromptContentHash, PROMPT_HASH_VERSION } from '@moda-ai/cli/prompt-hash'; const hash = computePromptContentHash({ key: 'support.triage', content: 'Classify the support request by urgency, account area, and next required tool.', }); ``` `PROMPT_HASH_VERSION` is `1`. The algorithm is: ```text theme={"dark"} contentHash = sha256_hex(utf8(stableJson({ key, content, systemPrompt: systemPrompt ?? null, messages: messages ?? [], variables: variables ?? [], variablesSchema: variablesSchema ?? {}, modelConfig: modelConfig ?? {}, toolRefs: toolRefs ?? [], responseSchema: responseSchema ?? null, sourceDefinition: { kind, source, sourceHash, ... } // sources: entries only }))) ``` `stableJson` is `JSON.stringify` after sorting every object's keys, recursively, with `String.prototype.localeCompare`. Arrays keep their order. For `sources:` entries, `sourceDefinition` holds the mapping (`kind`, `source`) and the extracted `sourceHash`. Builders and templates also include `dependencies`, `coverage`, and `unresolved`, so editing a dependency or moving a selector mints a new version even when the text is identical. `name`, `description`, `category`, and `sourcePath` are not hashed. For `sources:` entries the registry recomputes the hash and rejects a mismatch. ## Deleting a prompt Delete the file from your repo. `moda prompts status` reports it as `deleted`, and the next sync drops it from the lockfile. The prompt and its versions remain in the registry — there is no delete or archive API — but they stop receiving new versions. ## Troubleshooting | Symptom | Fix | | - | - | | `sync` or `promote` fails asking for an API key (exit code 4) | Set `MODA_API_KEY` or run `moda init` to provision and store a key. | | `sync` fails with `prompts must contain at least one prompt`, or syncs nothing | No files matched the manifest patterns. Run `moda prompts status` and check `zeroMatchPatterns`. Patterns are exact globs from the repository root. | | Prompt files outside `prompts/` stopped syncing after a CLI upgrade | The manifest predates exact globs. `moda prompts status` lists the files under `legacyOnlyFiles`. Run `moda prompts migrate`. | | `sync --from-harness` fails with `has no prompt that maps to current source` | No prompt in the report resolves against current source, and the error lists each one with a reason. Regenerate the report with `moda harness analyze --experimental --concern=prompts`, or map prompts under `sources:`. | | `promote` returns 404 | The key or version ID does not exist in the registry. Copy `versionId` from `.moda/prompts.lock.json` or `moda prompts status`, and sync first if the version is new. | | A version promoted with `--label=dev` loses the label | The next sync moved `dev` to the newly synced version. Use `staging` or `prod` for durable pins. | | A changed name or description does not create a new version | Expected: `name`, `description`, and `category` are not part of the content hash. Only content changes version. | ## Next steps * [Prompt attribution](/prompt-management/attribution) — stamp the lockfile IDs on runtime calls so usage shows up per version. * [Prompt management overview](/prompt-management/overview) — the versioning and label model in one page. * [CLI reference](/cli/reference) — output modes, exit codes, and environment variables shared by all CLI commands. # Quickstart Source: https://docs.moda.dev/quickstart Install the Moda SDK, capture your first OpenAI or Anthropic call, and see the trace in the dashboard. This guide takes you from an empty project to a trace visible in the Moda dashboard. It uses the Moda SDK for Python or Node.js to auto-instrument the OpenAI client library; an [Anthropic variant](#anthropic-variant) follows at the end. ## Prerequisites * A Moda workspace. Moda is invite-only: sign up at [moda.dev/signup](https://moda.dev/signup) to request one, or join a teammate's workspace through their invitation. * A Moda API key. Create one in the dashboard at **Settings → Ingestion keys** — the full key is shown once, at creation. * An OpenAI API key (or an Anthropic API key for the variant below). * Python 3.10 or later, or Node.js 18 or later. **1. Install the SDK** Install `moda-ai` alongside the provider client you already use: ```bash pip theme={"dark"} pip install moda-ai openai ``` ```bash npm theme={"dark"} npm install moda-ai openai ``` > [!NOTE] > > The PyPI package is named `moda-ai`, but you import it as `moda`. **2. Initialize Moda and make a call** Initialize the SDK before you construct the provider client, make the call as usual, and flush before the process exits. ```python Python theme={"dark"} import moda from openai import OpenAI moda.init("YOUR_MODA_API_KEY") client = OpenAI() # reads OPENAI_API_KEY from the environment response = client.chat.completions.create( model="gpt-4o", messages=[{"role": "user", "content": "What can you help me with?"}], ) print(response.choices[0].message.content) moda.flush() ``` ```typescript Node.js theme={"dark"} import { Moda } from 'moda-ai'; import OpenAI from 'openai'; await Moda.init('YOUR_MODA_API_KEY'); const client = new OpenAI(); // reads OPENAI_API_KEY from the environment const response = await client.chat.completions.create({ model: 'gpt-4o', messages: [{ role: 'user', content: 'What can you help me with?' }], }); console.log(response.choices[0].message.content); await Moda.flush(); ``` > [!WARNING] > > In Node.js, `Moda.init()` is asynchronous and must be awaited. If it is not awaited, calls made before initialization completes are not captured. The Node.js SDK also requires the API key as an explicit argument — it does not read a `MODA_API_KEY` environment variable. Python's `moda.init()` is synchronous and falls back to `MODA_API_KEY` when no key is passed. > [!NOTE] > > The Node.js sample uses top-level `await`, which requires ES modules (`"type": "module"` in `package.json`). In a CommonJS project, wrap the code in an async function. **3. Add trace and user context** Set a trace ID — the `conversation_id` field (the trace ID) — and a user ID before the first model call of a session or run. Use an identifier your application already has, such as a session, thread, job, or run ID, so every call is attributed to the right trace and user: ```python Python theme={"dark"} moda.conversation_id = "session_abc123" # set to None to clear moda.user_id = "user_42" ``` ```typescript Node.js theme={"dark"} Moda.setConversationId('session_abc123'); Moda.setUserId('user_42'); ``` Calls made while these are set are attributed to that trace and user. Both SDKs also offer scoped forms that are safe in concurrent servers: `with moda.set_conversation_id(...)` in Python, and `withConversationId(...)` / `withContext(...)` (imported from `moda-ai`) in Node.js. See the [Python SDK](/ingestion/python) and [Node.js SDK](/ingestion/node) pages for details. **4. Verify in the dashboard** Open [https://moda.dev/dashboard](https://moda.dev/dashboard) and go to **Traces**. Your trace appears within minutes of the flush; click the row to open its **Timeline** view showing the prompt and the model's response. Emotion, tool-failure, laziness, and hallucination analyses appear on the **Signals** page within minutes. ## Anthropic variant The SDKs also auto-instrument the Anthropic client libraries. Install with `pip install moda-ai anthropic` or `npm install moda-ai @anthropic-ai/sdk`, then: ```python Python theme={"dark"} import moda from anthropic import Anthropic moda.init("YOUR_MODA_API_KEY") client = Anthropic() # reads ANTHROPIC_API_KEY from the environment response = client.messages.create( model="claude-sonnet-4-20250514", max_tokens=1024, messages=[{"role": "user", "content": "What can you help me with?"}], ) print(response.content[0].text) moda.flush() ``` ```typescript Node.js theme={"dark"} import { Moda } from 'moda-ai'; import Anthropic from '@anthropic-ai/sdk'; await Moda.init('YOUR_MODA_API_KEY'); const client = new Anthropic(); // reads ANTHROPIC_API_KEY from the environment const response = await client.messages.create({ model: 'claude-sonnet-4-20250514', max_tokens: 1024, messages: [{ role: 'user', content: 'What can you help me with?' }], }); console.log(response.content[0].text); await Moda.flush(); ``` ## Troubleshooting | Symptom | Fix | | - | - | | Nothing appears in Traces | Call `moda.init()` / `await Moda.init()` before constructing the provider client, and call `moda.flush()` / `await Moda.flush()` before the process exits. | | `401` with `Invalid or expired API key` | The key is wrong or has been revoked. Keys start with `moda_sk_` and are bound to one workspace. Create a new one at **Settings → Ingestion keys**. | | `[Moda] API key is required` (Node.js) | `Moda.init` takes the key as its first argument; the Node.js SDK does not read `MODA_API_KEY` from the environment. | | `ModuleNotFoundError: No module named 'moda'` | Run `pip install moda-ai`. The package installs the `moda` import. | | `Cannot find module 'moda-ai'` | Run `npm install moda-ai` in the project that makes the LLM calls. | | Related calls land in separate traces | Set `moda.conversation_id` / `Moda.setConversationId()` before the first call of the session (see step 3). | ## Next steps * [Moda SDK for Python](/ingestion/python) — init options, context managers, and supported instrumentations. * [Moda SDK for Node.js](/ingestion/node) — init options, scoped context, manual capture, and OpenTelemetry coexistence. * [Ingestion overview](/ingestion/overview) — other ways to send data, including OpenTelemetry and the HTTP API. * [Dashboard overview](/dashboard/overview) — what to look at once data is flowing.