Fuente: ddx-documentation/osprey-engine.md
`ddx-osprey-engine/` is the adaptive agentic engine behind the Osprey playground: a turn router, five lanes, plans compiled to Mastra workflows, durable runs, Tool-RAG and capture plus eval. Mastra 1.82 (`@mastra/core` 1.82.0) on the Dudoxx router (`llm-router.dudoxx.com`). It listens on `127.0.0.1:9630` and has one caller: ddx-api. Contract: `ddx-osprey-engine/CLAUDE.md`. Realtime delivery: [realtime.md](/es/docs/realtime). Ports: [ports.md](/es/docs/ports). Rules the engine keeps (plan `_invariants.md`): `ddx-mastra/` is copied from, never edited or imported; wire types come only from `@ddx/contracts/osprey-*`; no mock model or provider (a dead router, Postgres, Qdrant or Centrifugo fails loudly, exit 3); demo tools use synthetic fixtures. ## Request path Browser, then ddx-web BFF `/api/v1`, then ddx-api `/osprey/*`, then the engine gateway. ddx-api checks session and tenant ownership before every engine call and sends identity and permissions as headers. A session row missing in ddx-api is backfilled once: ddx-api asks the engine `GET /sessions/:id` with the caller's own tenant and user headers (the engine answers only for the owner); 200 writes the row with the caller's org and user (engine-created sessions such as `osprey session seed`), 404 stays one 403. A run id never grants access. Routes (engine gateway; ddx-api mirrors them under `/osprey`): | Route | Purpose | |---|---| | `POST /sessions` | Create (201); the engine mints `ses_<uuid>` | | `GET /sessions?q&limit&cursor&groupId&projectId&archived&temporary` | The caller's rail: pinned first, then newest update; search over title OR any `turn.received` text; keyset cursor; only `origin='user'` and not deleted; archived and temporary sessions only with their flag | | `GET /sessions/:id` | Session view (title, active run, node statuses, plan) | | `PATCH /sessions/:id` | Rename, pin, move (own group / project), archive and / or share (`UpdateSession`, at least one key); a rename appends `session.titled` with source `user`. Session-row columns only, never an event row | | `DELETE /sessions/:id` | Soft delete (204); the session is a 404 afterwards | | `POST /sessions/:id/turns` | Submit a turn (202) | | `GET /sessions/:id/snapshot` | Resnapshot with `afterRevision`, `tailTurns`, `beforeRevision` ([realtime.md](/es/docs/realtime)) | | `POST /sessions/:id/ui-action` | Acknowledge a client action (204) | | `POST /runs/:runId/resume` | Resume with `decision` or `data` (202; 409 on a duplicate in-flight resume) | | `POST /runs/:runId/cancel` | Stop a run (202; 409 when it already ended) | | `POST /sessions/:id/fork` | Fork at `uptoTurnId` into a new session (201) | | `POST /sessions/:id/turns/:turnId/regenerate`, `.../edit` | Re-answer or edit a turn on a new branch (202, `sessionId` = the branch) | | `GET\|POST /projects`, `GET\|PATCH\|DELETE /projects/:id`, `POST /projects/:id/files`, `DELETE /projects/:id/files/:mediaId` | Assistant projects and their linked files | | `GET\|POST /session-groups`, `PATCH\|DELETE /session-groups/:id` | Session folders | | `GET /models` | Registry chat models (id, label, provider, default) | | `GET /personas[/:id]`, `POST /personas/org\|user`, `PATCH\|DELETE /personas/org\|user/:id`, `GET /memories`, `POST /memories`, `DELETE /memories/:id` | Personae and saved memories | | `GET /files/:mediaId`, `POST /files/ingest` | File-RAG status and raw-byte ingest | | `GET /sessions/:id/attachments` | Turn attachments of one session (`{attachments}`, newest first; foreign or unknown 404) | | `GET /usage/sessions/:id`, `GET /usage/me?range=` | Token, cost and latency rollups of `turn.completed` (GET only) | | `GET /usage/calls?after=<seq>&limit=` | Metered-call ledger page (`UsageCallPage`, limit at most 500); needs `usage:org`, else 403 | | `DELETE /files/:mediaId[?sessionId]` | Purge one ingested file (204; foreign or unknown 404; ingest in flight 409) | | `GET /voice/voices?provider=`, `GET /voice/stt-status` | TTS voice catalog; STT provider decision readout | | `GET /blobs/:blobId` | Owner-scoped bytes of a tool-made image or Word file | | `GET /mcp-servers[/:id[/tools]]`, `POST /mcp-servers/org\|user`, `PATCH\|DELETE .../org\|user/:id`, `POST .../org\|user/:id/test` | MCP server registry | | `/skills`, `/agents`, `/plugins` (same list, get, `org\|user` create, patch, delete shape) | Skills, user agents, plugin bundles | | `ws://127.0.0.1:9631/voice` | Voice gateway (ADR 0020), see §Voice | HTTP shapes: [api/osprey-api.openapi.yaml](./api/osprey-api.openapi.yaml) (ddx-api) and [api/osprey-engine.openapi.yaml](./api/osprey-engine.openapi.yaml) (engine gateway). ## Router and lanes Each turn passes one router (`src/router/`): zero-LLM rules first (an approval or form answer resumes, a `/plan` `/chat` `/react` slash command forces a lane, the `assistant.llm.mode` setting (`chat`, `react`, `plan`) pins a lane (`auto` routes as before), a pure UI command goes to react, a verb plus an image/PDF/Word noun goes to react (`image-intent` / `document-intent`), a vague imperative clarifies), then one decision-model call. The decision call also answers the background `workflow` (`none` | `deep-content` | `diagnosis`; criteria in `route-prompt.md` `## workflow:*`); there is no keyword rule for deep content (owner 2026-11-12). Turns that need live or external data (current conditions, news, date and time, web or video) are react, never chat. The router is bounded by a 400 ms p95 target. | Lane | What it does | |---|---| | `chat` | Plain answer, no tools | | `react` | Tool loop on a Mastra DurableAgent; every open (start and resume) goes through `driveReact()` with `maxSteps` and `prepareStep`. One tool call per step (`parallel_tool_calls: false`); the turn's thinking fields are re-sent on every step | | `plan` | Drafts a plan, compiles it to a workflow, runs it with approvals and a failure ladder | | `clarify` | Asks one question when the request has no referent | | `resume` | Continues a suspended run from an explicit approve, deny or form answer; never automatic | A lane writes only through `ctx.append`, and owns its terminal run event. Terminal run events are `run.finished`, `run.failed`, `run.stalled` and `run.cancelled`; the event log drops any draft of a run that is already terminal. The CLI (`osprey chat`, `session`, `turn`, `plan`, `run`, `tools`, `eval`) runs the same facade in-process and reads events back from `osprey.event`. ## Tool-RAG At most 4 searched plus 3 pinned tools reach one model call; always-include tools count inside the cap. Mutating tools carry idempotency keys (`<runId>:<nodeId>`), recorded in an effects ledger (`sql/002`). The measured maximum was 7 tools per call. The searchable catalogue has 11 live capability tools: `web_search`, `search_news`, `get_weather`, `generate_image`, `deep_research`, `current_datetime`, `youtube_search`, `summarize_thread`, `search_documents`, `generate_pdf` and `generate_docx`. `generate_docx` builds a Word file server-side with the `docx` dependency (^9.15.0) from `OSPREY_DOCUMENT_PRESET` (`@ddx/contracts/osprey-document-preset`), stores it in `osprey.blob` (at most 10 MiB) and emits a `docx` UI block (`blobId`, `filename`, `bytes`, `title`, `preset`); a run without an owner returns an error envelope. `generate_pdf` and `generate_docx` accept a DocumentSpec object or markdown text. Zero-LLM router rules also send a generate-intent request (a verb plus an image, PDF or Word noun, en/de/fr/es, at most 30 words, no patient or appointment words) to react (`image-intent`, `document-intent`); a turn with inline images goes to chat first. `generate_image` and `generate_docx` write blobs; the other tools write nothing. `youtube_search` and `search_documents` count as untrusted-content sources (approval-gated copies of mutating tools, plan approval before every mutating node). ## Plan compiler `src/plan/`: `planner` (structured-output draft), `binder` (per-node Tool-RAG), `validate` (typed `PlanValidationError`), `compiler`, `store` (`osprey.plan`, `osprey.plan_run`), `runtime`, `failure-policy` and `mutator` (Plan v+1 patches and diff). A plan version compiles to a registered dynamic workflow `plan-<sessionId>-<planId>-v<version>` using registered keys only; agent nodes are registered at boot (`src/boot/plan-workers.ts`) so stored plans resume after a reboot. A node with no tool above the score floor clarifies and never runs with zero tools. Foreach items run as child workflow runs. Known limits: a root step cannot read a parallel child's output (depend on the parallel block and read a later step). The binder rejects a `${key}` that names no upstream output. A plan mutation can finish a run without reaching the goal; success criteria are not checked at run end (open, reported by task 036). ### Build events (plan osprey-run-graph, G11/G12) One attempt writes a fixed sequence, so the run graph can show the plan being built instead of only the plan being run: 1. `plan.drafted` with `phase: 'drafting'` — one row per newly COMPLETE node as the planner streams, each carrying the plan built so far (a drafting partial REPLACES the previous drafting node set, it never accumulates). `attempt` is the 1-based planner attempt. 2. One `plan.bound {planId, version, ok, bindings[{nodeId, status: bound | unbound | gate | pinned, toolIds[], score, source}], clarify?}` — the per-node result of the Tool-RAG bind. `status` is `gate` when the node is approval-gated and `pinned` when it binds a pinned UI tool (`ui_control`, `render_card`); `clarify` names the node that found no tool and why. 3. On a failed attempt only, `plan.rejected {planId, version, attempt, stage: bind | validate, issues[{nodeId?, code, message}]}` — written BEFORE the retry, so the browser can mark the issue node `rejected` with its reason. 4. `plan.drafted` with `phase: 'final'` — the bound plan of that version; this fixes the node set. `phase` and `attempt` are optional and every row written before this change still parses. A row without `phase` (G14) replaces the drafting set per row, nodes show `pending`, binding falls back to the plan node's `toolId` / `allowedTools`, and the build strip shows "not recorded". `plan.mutated` keeps its own shape (`plan`, `diff`) and marks the graph's added / removed / rewired / changed nodes for the new version. ### Tool-call parent (`stepId`) `tool.call` and `tool.result` carry an optional `stepId` — the plan node id that made the call (`packages/ddx-contracts/src/osprey-events.ts`). The plan runtime knows the node id when it invokes the tool (`src/plan/runtime.ts`, set only when the tool input really carries a node field; a `"node"` fallback would be a guess and never reaches the log). React rows never set it: a react call's parent is the LAST `llm.step.started` of its run, and an old plan row without `stepId` attaches only when exactly one running node of that run is bound to that `toolId`, else to the run's `unattributed` group. This is what lets two tool nodes of one `parallel` container keep their own calls apart. ### Run graph projection (web) `ddx-web/src/lib/osprey/run-graph.ts` folds the same `osprey.event` rows into `SessionView.runGraphs`, ONE graph per RUN (never per session: `view.plan` / `view.steps` are keyed by a bare node id and would bleed across turns). The fold is pure, reads no text or reasoning event, and returns the same object when an event changes nothing, so a live row and a compacted snapshot fold deep-equal (FM3). Layout (`run-graph-layout.ts`, own layered layout — no dagre, no elkjs) is keyed by a topology signature of node and edge keys, so a status change re-renders the node only. The canvas is `@xyflow/react`, loaded through `next/dynamic` when the Run tab opens. No new event type, no new realtime path: the graph is the same log the panel already receives. ## Failure ladder (AC9) One retry owner per class: step retries (at most 2) then REWIRE (failed tools excluded, same mutating class and category, at most 2 per run, `step.rewired`) then MUTATE (planner re-plan to Plan v+1, at most 3 per run, `plan.mutated` with a diff) then `run.stalled` with a readable reason in under 60 s. A denied or permission error is `run.failed`. Every new plan version runs in the same run id, so a done mutating step is replayed and has no second effect. ## Approval binding An approval authorises one call, not a step. `run.suspended` carries `toolCallId` and a `binding` `{toolCallId?, nodeId?, toolId, fingerprint, summary, expiresAt?}`; the fingerprint is sha256 of the canonical `{toolName, args}` (keys sorted, `idempotencyKey` and Osprey bookkeeping fields dropped). - **Plan lane.** The compiler hoists the argument entries of the first mutating tool node that depends on an approval node in front of the gate, so the human sees the final arguments. On approve the runtime compares the fingerprint of the call with the binding that was shown; a changed call appends `approval.invalidated` and suspends again. The gated tool wrapper re-hashes before `tool.call` and throws `ApprovalMismatchError` with zero effects. A mismatch re-issues the plan as v+1 (`plan.mutated`, diff `re-ask approval`). A gate binds ONE call (the first mutating dependent). Bindings are read back from the `run.suspended` / `run.resumed` rows, so they survive a restart (`readApprovalBindings`, `readApprovedToolCall`). - **React lane.** Mastra's `requireApproval` stays the gate; a `beforeToolCall` hook (`buildReactApprovalHooks`) refuses a gated call whose fingerprint differs from the approved binding. - **Reject with feedback.** In the plan lane a deny with `data.feedback` cancels the suspended version, re-drafts Plan v+1 with the feedback, appends one `plan.mutated` and asks again in the same run. A deny without feedback ends the run with `run.failed`. - The browser shows the states open, responded, denied, invalidated and expired on one inline card. Judge: engine suite `approval-binding`. ## UI from every lane `ui.block`, `ui.action` and `ui.action.acked` work in every lane. A UI-only request (every clause names a UI verb and object, no data word, no digit) routes to react with reason `ui-intent`; `request_plan` refuses UI-only goals. The binder keeps a planner-chosen `ui_control` or `render_card` node when the pinned tools are passed to it (`plan/runtime.ts` passes them), so a UI-only plan step binds and the run graph shows that binding (`plan.bound` row `status: 'pinned'`; engine suite `run-graph-edges` case `ui-binding`). The plan lane appends one summary text part (`text.start/delta/end`, partId `plan-summary:<runId>:<n>`) in front of every terminal run event. ## Cancel `POST /runs/:runId/cancel` stops a run. The turn runner keeps one `AbortController` per run (turn and resume). Cancel writes one guarded batch: `tool.denied {reason: cancelled}` for an open approval or form, `text.end` for every open part, then `run.cancelled`; it then aborts the live stream or the plan workflow. A run that already ended answers 409 and writes no event. Known limit: cancelling a SUSPENDED react approval leaves the Mastra durable snapshot suspended in `osprey_mastra`; the log says `run.cancelled` and every later resume is 409. The CLI `osprey run cancel` is unchanged and works on a suspended run only (it appends `run.failed`). ## Session titles and meta `sql/006_session_meta.sql` adds `pinned`, `updated_at`, `title_source` (`first-turn`, `model`, `user`), `origin` (`user`, `suite`, `seed`, `subrun`), `deleted_at` and a partial rail index. Suites, seeds and sub-runs have an `origin` other than `user`, so they stay off the rail. Turn 1 writes `session.titled {first-turn}` (the user text clamped to 60 characters at a word boundary) in the same append as `turn.received`. After the turn one structured-output call to the wrapped Dudoxx model (own request, thinking off, temperature 0, 1500 ms timeout) refines it to `session.titled {model}`; a failure is logged loudly and the first-turn title stays. A machine title never replaces a user title. ## Durability and recovery Postgres schema `osprey` (`sql/000`-`032`; table below covers `000`-`015`): base, event log, tool effects, plan, turn records, run claims, session meta, then the assistant platform files. The migrator applies every unapplied file in name order, and each file is idempotent. `osprey.event` is the only authority. - Every plan, react and deep-content run runs under a lease in `osprey.run_claim` (kinds `plan`, `react`, `deep`; 5 s heartbeat, 15 s lease). - The recovery sweep (`src/boot/recovery.ts`) runs at boot and every 5 s. It adopts a stale lease, appends `run.recovered`, restarts a plan from the Postgres snapshot, recovers a react run or restarts a deep run (`getDeepContentRuntime().restart`), then closes the orphaned turn lock. A reboot alone never fails a run. After 3 failed attempts the run gets `run.failed` with `recovery-exhausted`. A deep run that exhausts recovery moves to `failed` with the deep `failed` progress phase and no `run.failed`; the deep runtime owns its lease release and its single terminal. - Side effects re-run only through the idempotency ledger. - Capture: one `osprey.turn_record` per turn, derived from `osprey.event` (`src/capture/turn-recorder.ts`). ## Deep content (plan osprey-deep-content) A long-report ask starts a background run: the react lane calls `start_deep_content`, which returns a handle and a `deep-content` card; the run id is `dcr_<id>`. The run is the workflow `osprey-deep-content` under a lease of kind `deep` (`src/deep-content/runtime.ts`). Source: `ddx-osprey-engine/src/deep-content/`. - Stages: scope (brief) → plan → research (parallel sub-agents, source registry, gap rounds) → outline (claim-once) → write (sequential, one section per iteration) → edit → cite → publish. Research is parallel, writing is sequential. - Store: `sql/015_deep_content.sql` (`store.ts`): runs, artifacts, source registry, claim ledger. Reads are scoped to tenant and user. - Budgets (`DEEP_CONTENT_DEFAULTS`): 6 sub-agents, 6 searches each, 2 gap rounds, 30 min wall clock stay hard caps. `maxTokens` defaults to no cap (`null`); a request may set it. Tokens are counted per run. - Researcher history digest (`research/history-compact.ts`): every tool result but the newest is cut to a short url/title digest before each provider call, so a multi-step researcher does not re-send all earlier pages. - Judges (`judges/`): repetition (embedding cosine), claim ledger, LLM coherence; the result is stored in `deep_run.judge`. - Progress: `progress.data.deep` through `DeepEmitter` (see `realtime.md`); no new event type. - Read routes: `GET /deep-runs/:id` (status, counters, judge) and `GET /deep-runs/:id/document` (markdown; 409 before the run has succeeded); a foreign or unknown run is 404. `POST /runs/:id/cancel` also stops a `dcr_` run. - Not implemented: persona `tool_ids` run-time enforcement. ## Diagnosis engine (plan diagnosis-engine) Per-specialty diagnosis: a doctor submits one patient or a cohort, the engine scores, asks questions and returns outputs. Decision record: [ADR 0021](/es/docs/adr/0021-diagnosis-engine). It adds no lane and no event type. | Part | Where | What it does | |---|---|---| | Deterministic core | `packages/ddx-diagnosis-core` (`@ddx/diagnosis-core`) | Log-odds Bayes scoring with a seeded Monte Carlo interval, expected-information-gain questions, red flags, must-not-miss, fail-closed safety, deterministic outputs. Imports no model, Mastra, pg or network module. Same evidence gives the same `resultHash`. | | Knowledge store | `ddx-osprey-engine/src/diagnosis/knowledge-store.ts`, `sql/017` | Shared, no tenant or patient column: specialties, concepts, labels (`pg_trgm`), cards, immutable revisions, evidence sources, installed packs. | | Seed packs | `ddx-osprey-engine/datasets/diagnosis/*.pack.json` | Dermatology, gastroenterology, cardiology (`osprey-dx-pack/1`, 0.1.0, 12 cards each) plus a 20-case gold set per specialty. Installed by `osprey dx pack install-all`. | | Hybrid retrieval | `src/diagnosis/retrieval.ts`, `index-knowledge.ts` | Normalisation cascade (code, label, trigram, vector, unmapped), then reciprocal-rank fusion over pack findings, Qdrant `osprey_dx_knowledge` chunks and finding overlap. Rebuilt with `osprey dx index rebuild`. | | Casework | `src/diagnosis/case-store.ts`, `sql/018` | `dx_run`, `dx_question`, `dx_output`, `dx_feedback`; owner-scoped (tenant + user from gateway headers; foreign or unknown = 404). | | Workflow | `src/diagnosis/workflow.ts`, `steps-assess.ts`, `steps-output.ts` | Workflow `osprey-diagnosis`: `dx-load` → `dx-intake` → `dx-retrieve` → bounded `dx-assess-round` loop → `dx-safety` → `dx-reason` → `dx-outputs`. | | Questions | workflow step suspend | When questions remain the run suspends and emits `run.suspended` kind `form`; the doctor answers and the run resumes, up to `maxRounds`. A cohort run never suspends. | | Runtime | `src/diagnosis/runtime.ts` | `DiagnosisRuntime` under an `osprey.run_claim` lease of kind `diagnosis`. A suspended run holds no lease; `resume()` re-claims it. Recovery restarts an adopted run from its snapshot (`continueDiagnosis`). One terminal progress phase per run. | | Progress | `src/diagnosis/emit.ts`, `events/snapshot.ts` | `progress.data.dx` (`DxProgressData`); snapshot compaction keeps these rows. | | Gateway | `src/diagnosis/gateway.ts` | `/diagnosis/*`: runs (start, status, answers, outputs, feedback), knowledge reads, proposals, decision, curator tick. Decision and tick need the `diagnosis:curate` or `diagnosis:system` permission. | | Curation | `src/diagnosis/curation/` | `feedback-signals.ts` (past `feedbackMinSupport` creates a pending proposal), `proposals.ts` (`decide()`), `promotion-gate.ts`, `curator.ts` + `extract.ts` (unattended research). `sql/019`: `dx_proposal`, `dx_curator_job`. | **Safety.** A red flag pins must-not-miss cards and raises urgency. A check that cannot run is `blocked_unknown`. Guidance is withheld on `blocked` and `blocked_unknown`. Report sentences without a resolvable evidence id are stripped. Every output carries citations and the disclaimer. **Promotion gate.** `decide()` publishes a revision only with a real reviewer id and a passing gate. The gate replays the specialty gold set: must-not-miss recall below the published baseline is `gate_failed` (no override); top-5 recall may drop by at most `gateTop5Tolerance`. Seed baselines (`datasets/diagnosis/baseline.json`): must-not-miss recall 1.0 on all three; top-5 recall 0.78 cardiology, 0.83 dermatology, 0.77 gastroenterology. **Curator.** A tick claims a window (unique `window_key`), picks the stalest cards, builds the research brief from card fields only (no casework import, so no patient data), starts a deep-content run on a dedicated system session, and turns the finished run into pending, cited proposals. It never publishes. Failed or cancelled runs create no proposal. The ddx-api scheduler fires the tick on every node; the engine dedups by window. **Settings.** `module.diagnosis.*` (19 core keys plus later additions, [settings.md](/es/docs/settings) §Diagnosis keys) travels in the run-start or tick body as `DxSettings`, never in `x-osprey-settings`. **Card author** (plan dx-card-kb, `src/diagnosis/card-author/`). The workflow `osprey-dx-card-author` writes one card folder (`osprey-dx-card/1`) per run: a new card from a free-text brief, or an upgrade of an installed card (mode `new` | `upgrade`). Steps: target, search, fetch, draft (one part per item), merge, translate, verify, assemble. Sources are generic per-part web searches capped at `sourcesPerCard`; every cited URL must have been fetched and alive (dead URLs are reported, never cited). Verify checks the folder schema, the refs-frozen guard (an upgrade keeps the base card's code, specialty, refs, relations, rule keys and option keys), 4-locale completeness, citation quotes against the fetched pages, URL liveness, expert revert and an authorship scan. A value with no source keeps the installed value with derivation `expert`. A run is one row in `osprey.dx_card_author_run` (`sql/025`) with a stage checkpoint (`sql/026`) written after each stage: a run read shows interim `progress` (sources, finished parts, the partial folder, `resumable`), and a failed run resumes from its checkpoint with the same id. The boot module `src/boot/card-author.ts` fails runs orphaned by an engine restart at start. Routes: `POST /diagnosis/card-author/runs`, `GET /diagnosis/card-author/runs[/:id]`, `POST …/runs/:id/resume`, `POST …/runs/:id/submit`; owner-scoped, see [api/osprey-engine.openapi.yaml](./api/osprey-engine.openapi.yaml). The run never installs or publishes: submit files one PENDING proposal of `kind: folder` (`curation/proposals.ts`, proposer = the run's owner), and a different reviewer decides it. Settings: `module.diagnosis.cardAuthorModel`, `cardAuthorSourcesPerCard`, `cardAuthorConcurrency` ([settings.md](/es/docs/settings)). Wire types: `@ddx/contracts/osprey-diagnosis-card-author`. **Case Studio** (plan osprey-case-studio, all under `ddx-osprey-engine/src/diagnosis/`). A case carries patient context (medications by ATC code, allergy classes, conditions, kidney and liver bands, pregnancy, breastfeeding) in its intake, and a cohort carries it per patient. New engine routes, all owner-scoped (tenant + user from the gateway headers; a foreign or unknown run is 404): - `GET /diagnosis/allergen-classes?q=` lists allergy classes for the picker (`gateway-knowledge.ts`). - `GET /diagnosis/runs/:id/questions` returns the question history: every stored question of every round with its answer, note and source (`question-history.ts`). `POST` on the same path is the ask-more call. - `GET /diagnosis/runs/:id/case-report?sections&caseNumber` returns `{ report, markdown, document, judge }`. A run with no completed result is 409. `caseNumber` is optional and must match `^DX-\d{4}-\d{5}$` (400 otherwise); without it the report has no case number and no run number, nothing is invented. Files: `case-report.ts` assembles the report from stored results (it never recomputes a number); `case-report-render.ts` builds ONE typed section list that feeds both the Markdown and the PDF document spec, so the two carry the same values; `case-report-judge.ts` is the numbers judge (every probability, odds and interval in the Markdown and in the PDF spec must equal the stored run); `draft-intake.ts` maps a confirmed chat draft to the single-patient run intake and keeps the safety context whole; `answer-labels.ts` writes the label lines of an approval card. Report text comes from `prompts/case-report.md` (the section order, placeholders only) and `prompts/case-report.labels.json` (4 locales). The report prints no run id, case id, hash or rule key; those stay in the JSON `generatedFrom`. Numbering and file names: [naming-constitution.md](/es/docs/naming-constitution) §6.5. Assistant tools of the case chat: `dx_case_facts` (the case as stored), `dx_question_candidates` (read-only; the finding ids the assistant may propose, from the round's own ranking), `dx_question_propose`, `dx_ask_more` and `dx_case_patch`. The last three need approval and the card shows names, never ids. Ask-more rule: an approved assistant pick always keeps the last slot of the round, so the cap never drops it; red-flag rule-outs come first. A cohort run refuses ask-more. Migrations: `030` adds the answer note and the question source (`engine` or `assistant`) to `dx_question`; `031` is the Dx persona text v3 (case facts first, one more question round, case change by proposal; it updates only persona rows still equal to the `029` text). Run `pnpm osprey db migrate`. When the report is too large for the PDF bounds, the response has `pdfError` and no `document`; the Markdown stays whole and a cut PDF is never sent. **CLI.** `osprey dx pack install|install-all`, `dx cards list --specialty`, `dx corpus ingest`, `dx index rebuild`, `dx cards author (--queue <file.json> | --card <CODE>) --out <dir> [--model] [--limit] [--concurrency] [--sources] [--dry-run] [--json]` (writes `<CODE>/card.json` folders to `--out`, never installs), `dx learn check --before <run> --after <run> --proposal <id>`, `dx learn import-stage <signals.json>`. **Suites** (all PASS at close-out): `dx-core-determinism` and `dx-eval-golden` (zero model calls), `dx-run-live`, `dx-curator-live`. **Case drafts: async fill, mapping and alternatives** (plan osprey-dx-accuracy, under `ddx-osprey-engine/src/diagnosis/` unless noted). `POST /diagnosis/cases/:id/drafts` answers 201 at once with `fill: pending`. `draft-fill.ts` (`startDraftFill`) claims the row in `draft-store.ts` (`claimDraftFill`: one transaction plus an advisory lock; dedupe on case + text hash, so a repeat call returns the live row; a failed or stale row is retried on the same id with `fillAttempt` + 1) and runs the extraction in the background. The fill ends `ready` (`completeDraftFill`) or `failed` (`failDraftFill`, a fixed error text, never model output). A pending row past `draftStaleMinutes` reads `failed` / `stale`. Every draft answer carries `fill`, `fillError` and `fillAttempt`; confirm and edit answer 409 while `fill` is not `ready`. `sql/032` adds the columns `fill_status`, `fill_error`, `fill_attempt`, `text_hash`, `fill_deadline` and the dedupe index `dx_case_draft_fill_dedupe_idx`. Boot module `src/boot/draft-fill.ts` fails pending fills past their deadline at server start; a second engine on the same database keeps its live fills. The chat-tool path stays synchronous. Mapping: concept-match judges the top `conceptMatchTopK` vector hits with the scrubbed case note (`conceptMatchNoteChars`) and offers `conceptMatchCandidates` candidates; a vector-mapped item is always held; each item carries up to `draftAlternatives` `alternatives` the doctor can switch to; a measure without value and unit becomes a text-only sign. The gateway method loop (`src/gateway/routes.ts`) registers PUT, which `PUT /diagnosis/drafts/:id` needs. Keys: [settings.md](/es/docs/settings) §Draft and mapping keys. **Mastra spine** (plan osprey-mastra-native, `ddx-osprey-engine/src/diagnosis/spine/`). A second run engine beside the workflow `osprey-diagnosis`. The registry key `module.diagnosis.engine` picks it per run: `legacy` (the seed, today's pipeline) or `mastra` (the spine). The STORED run settings decide start, resume, ask-more, restart, cancel and reads, so a run never changes engine mid-life (`runtime.ts` `isSpine`). The spine is built and switchable; it is not the default, and its parity, accuracy, time and token runs (tasks 053-057, 062) have not run yet. The legacy path stays until the parity gate passes. | Part | Where | What it does | |---|---|---| | Workflow | `spine/workflow.ts` | Workflow `osprey-dx-spine`: `dx-spine-load` → `dx-spine-intake` → `dx-spine-match` → `dx-spine-retrieve` → bounded `.dountil` round (`dx-spine-score` → `dx-spine-rank` → `dx-spine-questions`, suspend for the doctor, resume on answers) → `dx-spine-safety` → `dx-spine-differential` → `dx-spine-deep-reason` → `dx-spine-report` → `dx-spine-outputs` → `dx-spine-case-library`. Each step is a `createStep` with zod in/out and emits a progress row with `data.dx.spineStep`. | | Deterministic steps | `spine/steps-score.ts`, `spine/tools/score-tools.ts` | Score, rank and questions wrap the legacy assess helpers; `packages/ddx-diagnosis-core` and the match cascade (code → label → trigram → vector) are unchanged, so a spine round computes the same `resultHash` as the legacy round. | | Registered agents | `spine/agents.ts` | One Mastra agent per role, built once per process (`buildSpineAgents`) and registered on the instance: `osprey-dx-spine-intake`, `-concept-match`, `-differential`, `-challenger`, `-pattern-seeker`, `-pharmacology`, `-auditor`, `-report`. Model, instructions, tools and step bound resolve from the run's request context (`spine/run-context.ts`); every call uses the wrapped `dudoxxMastraModel`. | | Agent tools + guard | `spine/tools/{search,case,score}-tools.ts`, `spine/tool-guard.ts` | `search_cards`, `graph_walk`, `explain`, `similar_cases`, `score_case`, `rank`. `guardTool` parses input (one repair), accepts only run-scoped concept and card ids, caps calls per agent call at `agentToolCallCap` and refuses a third identical call; a refusal is a typed result, never a throw. The core recomputes every number from Postgres evidence; an agent number or id is never truth. | | Capped inputs | `spine/agent-inputs.ts` | Differential, deep-reason and report agents see only the top `agentHypothesisTopN` hypotheses (`deepReasonTopN` for deep reasoning) and `agentEvidencePerHypothesis` evidence items each. Prompts get the shared tool-use block `prompts/spine-tools.md`. | | Typed card chunks (v3) | `rag/card-chunks.ts`, `index-knowledge.ts` | Mastra `MDocument` chunks per card revision: header-aware section chunks, one chunk per finding row with its likelihood ratios, concept-label chunks; optional one-time keyword and question extract (`prompts/card-chunk-{keywords,questions}.md`) kept in chunk metadata, outside the content hash. Collection `osprey_dx_knowledge_v3` (dense 2560 + sparse) sits beside v2. Point ids are content-addressed: an unchanged card writes 0 points. `dx cards install` re-ingests a changed card into v3 after commit, and a publish (`indexRevision`) re-ingests that card only; a v3 failure keeps the publish and adds a warning. v2 stays on `dx index reconcile`. | | Vector query + rerank + GraphRAG | `rag/vector-query.ts`, `rag/graph-tools.ts` | Mastra vector query tool over v3 (Qdrant dense + sparse prefetch fused by RRF, published revisions only), reranked by `rerankMode` (`mastra` = `rerankWithScorer`). `dx-card-relations` walks the curated `dx_concept_relation` rows; `dx-graph-walk` is a `createGraphRAGTool` chunk walk at `graphRagThreshold`. GraphRAG output never enters scoring or the `resultHash`. | | Case library | `case-library/{ingest,search,recall}.ts`, `sql/033`, `repositories/case-library.ts` | The `dx-spine-case-library` step ingests every completed spine run before the run end: an identifier-scrubbed summary (concept ids + labels, item kinds, ranked hypotheses, stop reason, case number), chunked with `MDocument`, embedded, upserted owner-scoped into Qdrant `osprey_dx_cases`, with a row in `osprey.dx_case_library`. A run without a case number skips (`no_case_number`). Search returns past cases of the same tenant AND the same doctor only, labelled "similar past case <case number>", scrubbed; a past case is never a case fact or scoring evidence. Doctor feedback notes live in `osprey.dx_feedback_note`. | | Case number | `sql/035`, `runtime.ts` | ddx-api resolves the kernel case number and sends optional `caseNumber` on run start and draft confirm; the run row stores it (`dx_run.case_number`). | | Cross-case recall | `case-library/recall.ts`, `mastra/instance.ts`, `lanes/react/index.ts` | A `[case:<id>]` assistant turn with memory on gets Mastra Memory options with resource `tenant:doctor` (`crossCaseRecall`, `crossCaseRecallTopK`, `recallLastMessages`, read from the case's newest owned run, else registry seeds). The react agent's input processors are a dynamic argument: the recall label processor marks recalled items "similar past case <case number>", scrubs them and marks them non-factual; an item without a case number is dropped. | | Budget + scorers | `src/lib/run-budget.ts`, `spine/scorers.ts` | Per-step input and output tokens and model-call ms, run totals and `overBudget` against `runInputTokenBudget`, one `[budget]` stderr line at finish; stored as `result.budget` and exposed on run status (`DxRunBudget`). Code scorers `dx-budget`, `dx-other-share`, `dx-agent-refusals` run on the case-library step and persist through Mastra live scoring; they never change the run. | | SQL | `repositories/` | Every diagnosis SQL statement lives in `src/diagnosis/repositories/` (one module per aggregate, zod-parsed rows). The AC10 regex counts 0 `query(` call sites elsewhere under `src/diagnosis/`. One read crosses into Mastra storage: `runs.ts` `listWorkflowSnapshotTexts` reads `osprey_mastra.mastra_workflow_snapshot` for the replay. | **Learning loop** (plan osprey-mastra-native). Every signal is ids and counts, never patient text; every card change is a PENDING proposal that a reviewer other than the proposer decides. - Board acts (`curation/board-signals.ts`, `sql/034`): an alternative switch, an item tick or untick and a confirmed final diagnosis are recorded as id-and-count signals after the gateway write succeeds. A final-diagnosis signal at `boardSignalMinSupport` files a PENDING feedback proposal. - Notes and case-library outcomes feed the curator signals as PENDING count-only proposals (`feedback-signals.ts`). - Pre-review gate (D3): `createProposal` / `createFolderProposal` attach the promotion gate result on the TUNE split (holdout rows dropped) to the pending row in the background. `decide()` judges the gate now and the stored gate: a must-not-miss drop always fails; a top-5 failure publishes only with an `overrideReason` (≤ 1000 characters, logged to stderr); without one a failure now is `gate_failed` and a stored-only failure is refused (`override_required`, 400). - Closed loop (D4, `curation/closed-loop.ts`): `osprey dx learn check --before <run> --after <run> --proposal <id>` compares the gold-card rank per case of two usage runs around a publish; a case worse than `closedLoopRankTolerance` files a PENDING rollback proposal (never a rollback). - Stage signals: `osprey dx learn import-stage <signals.json>` adds the stage misses of a usage run (counts only, written by `osprey-usage signals <runDir>`) to the gap signals; a HOLDOUT run and a run already imported are refused. - Mixed intake (D5, `draft-fill.ts`): a form value wins over the text fill; each field records its origin and conflicts. **Assistant tools** (plan osprey-mastra-native, registered in the chat catalogue and reached through tool search). `dx_analyze_case` starts or attaches to an owned run, relays each step as an interim data event and answers with one speech sentence; `dx_score_case`, `dx_rank`, `dx_search_cards`, `dx_graph_walk` wrap the spine tools with owner checks (`tools/catalogue/diagnosis-spine.ts`). Card CRUD (`diagnosis-cards.ts`): `dx_card_get` / `dx_card_search` read without approval and answer WITHHELD for a safety-blocked on-screen run (shared check `diagnosis-safety.ts`); `dx_card_insert` / `dx_card_update` / `dx_card_update_attribute` need `diagnosis:propose` and only file a PENDING `dx_proposal`. Case library (`diagnosis-library.ts`): `dx_similar_cases` and `dx_feedback_note` (approval required). The Dx persona text is v4 (`sql/036`). **Observability note** (security review 052, accepted). "No PHI in a Mastra snapshot" holds for workflow snapshots. Spine agent spans go through `MastraStorageExporter`, and `SensitiveDataFilter` redacts secrets, not free text, so agent span input (case free text) is stored in `osprey_mastra` spans, in the same Postgres as `dx_run.intake`. No retention or purge ties those spans to case deletion. **API surface.** ddx-api serves 8 case routes (`/osprey/diagnosis/{specialties,cards,cards/:cardId,cases/:caseId/runs,runs/:runId,runs/:runId/answers,runs/:runId/outputs,runs/:runId/feedback}`) and 4 platform-admin routes (`proposals`, `proposals/:proposalId`, `proposals/:proposalId/decision`, `curator/tick`); later plans added more diagnosis routes, among them 5 card-author routes (`POST|GET /osprey/diagnosis/card-author/runs`, `GET …/runs/:runId`, `POST …/runs/:runId/resume`, `POST …/runs/:runId/submit`); see `ddx-api/src/osprey/CLAUDE.md`. The generated OpenAPI files (`api/openapi.json`, `api/osprey-api.openapi.yaml`, `api/osprey-engine.openapi.yaml`) did not list `/osprey/diagnosis` at close-out (the two hand-written YAML files now list the card-author routes): they are produced by `./ddx-manage.sh docs` (lead). ## Assistant platform (plan ai-assistant-platform) Settings, per-turn model and effort, forks, projects, personae, files, MCP, customization and voice. The contract is `ddx-osprey-engine/CLAUDE.md`; module shapes are in `packages/ddx-contracts/README.md` §Osprey engine. ### SQL migrations | File | Adds | |---|---| | `007_assistant_projects.sql` | projects, project files, session groups, session archive / temporary / share columns, fork lineage columns | | `008_personas.sql` | org and user personae (org scope = `user_id` NULL), `session.persona_id` | | `009_files.sql` | ingested-file metadata (`osprey.file`, `project_file`); chunks live in Qdrant collection `osprey_files` | | `010_customize.sql` | MCP servers (header names and secret-box ciphertext only), skills, plugins, user agents, `plugin_id` bundle ownership | | `011_file_claim.sql` | `osprey.file.claimed_at` (ingest claim; applied before 010 on a fresh database, order-safe) | | `012_blobs.sql` | `osprey.blob`: owner-scoped bytes of tool-made media, at most 10 MiB per row | | `013_mcp_tool_pins.sql` | `mcp_server.tool_allow_pins`: fingerprints of allow-listed MCP tools | | `014_usage_call.sql` | `osprey.usage_call`: metered-call ledger (ids and counts only, never content), one `text` row per turn (partial unique index), cursor `seq` | | `015_deep_content.sql` | deep-content store: `osprey.deep_run`, `deep_artifact`, `deep_claim` (artifacts upsert on `(run_id, kind, key)`), and `run_claim` kind `deep` | | `025_diagnosis_card_author.sql` | `osprey.dx_card_author_run` (one card-author run: mode, folder, report, proposal); `dx_proposal` gains `kind` diff or folder, `folder`, `card_code`, `specialty`, `card_author_run_id`, and a NULL-able `card_id` | | `026_diagnosis_card_author_checkpoint.sql` | `dx_card_author_run.checkpoint` (last good stage state, drives resume) | ### Settings header and per-turn model The gateway reads `x-osprey-settings` (base64url JSON of the 23 `assistant.*` keys ddx-api resolved; keys: [settings.md](/es/docs/settings) §Assistant keys). `src/gateway/assistant-settings.ts` validates each key; a bad key, value or encoding is 400 `bad_settings`. Lanes receive it as `ctx.assistant`. Model and effort: body over settings; unknown model is 400 `unknown_model` before the turn lock; effort becomes a thinking budget, never `reasoning_effort`. ### Forks, projects, personae, files - Fork, regenerate and edit copy the event prefix into a new session in one transaction and clone the Mastra memory thread. The source session never changes. An open run in the prefix is 409. - Projects carry instructions (a 600-token layer in chat and react) and linked files. Groups are folders. Every store query filters tenant and user; foreign is 404. - The assistant identity in the core prompt is one neutral line ("You are Osprey, Dudoxx's clinical-workflow assistant."); the detailed identity comes from the seeded "Osprey" default persona, a `## Persona` layer folded into the one system message (the provider merges every system message into one). `ddx-seeder` provisions the seed personae, skills, agents and projects over ddx-api HTTP: `./ddx-manage.sh seed osprey [--dry-run]` (refused in production; [ddx-seeder/README.md](../ddx-seeder/README.md)). Seed texts are `NEEDS_REVIEW`. - Turn persona = body, then the session's persona, then `assistant.persona.defaultId`. Instructions (`assistant.instructions`, `assistant.style.tone`) and persona text are budgeted layers; `assistant.memory.enabled=false` drops working memory and semantic recall for the call. - Add a memory: `POST /memories` `{text}` writes one line into the caller's working memory (201 `SavedMemory`). Bounds are the settings `assistant.memory.maxLines` (seed 8) and `assistant.memory.maxLineChars` (seed 160), both org tier, edit by `org-admin`. 400 `invalid_body` (too long, empty, or patient-shaped: `patient_data`); 409 `memory_full` or `memory_disabled`. A server-side guard keeps working memory to the template keys and drops patient-shaped values. The model may also write it through `updateWorkingMemory` in the chat and react lanes. - File-RAG: ingest parses PDF (unpdf), text, markdown and csv, chunks, embeds and writes Qdrant `osprey_files`. Images are sent to the model for that call only (`TurnImagesProcessor`); the log and `osprey_mastra` store no image bytes. A vision request on a model without the image capability is 400 `vision_unsupported`. ### Providers, MCP, customization - Capability tools (`web_search`, `search_news`, `deep_research`, `get_weather`, `generate_image`) are live and read-only. Search goes through an ordered `SearchChain` (exa, brave, tavily) with fallback to the next keyed provider. Image generation uses the router only (`/images/generations`, alias `OSPREY_IMAGE_MODEL`, `b64_json`); the bytes are stored in `osprey.blob` and served as `/api/v1/osprey/blobs/:id`. A blank alias or a router without that alias answers `tool_unavailable` with an error that names `OSPREY_IMAGE_MODEL` (expected alias `dudoxx-image`) and says to register it in LiteLLM; nothing is faked. Each stored image writes one `usage_call` row (kind `image`, 1 unit, provider `router`); a ledger failure is logged and never hides the image. Query text reaches the chosen vendor (operator-accepted, flagged in review 039). - MCP servers: header values are sealed with AES-256-GCM (`src/lib/secret-box.ts`); reads show header names only. URLs pass an SSRF guard at save and at every connect (DNS vetted, socket pinned, no redirects); allow-listed tools are pinned to a fingerprint; a run that can read untrusted content gets approval-gated copies of mutating tools. - Skills, user agents and plugins: plugin install is one transaction; agent runs use the wrapped Dudoxx model only. - Tool-call cap: more than 8 tool calls in one model step, or the same call 3 times in a row, ends the stream as `run.failed {kind: policy}`. Within one step a repeated read-only call (same tool, same exact arguments) runs once and the model gets that one answer (step memo); a read-only repeat gives its start back to the cap, a mutating call never does. - Models: the router alias table is `packages/ddx-contracts/src/llm-router-models.ts` (12 router aliases, 7 legacy ids, capabilities, limits, USD-per-million prices). There is no direct OpenRouter provider; `or-*` aliases go through the router. The default model is `dudoxx-prod` (`DUDOXX_MODEL_NAME`); it accepts one leading system message only, so the wrapped model merges every system message into one. Title and decision models stay on `dudoxx-gemma`. - Per-turn params: `assistant.llm.temperature|topP|topK|maxOutputTokens|thinkingBudget` are sent only when they differ from the platform default (`maxOutputTokens` clamped to the alias cap, `thinkingBudget` only with effort `off`) and are recorded on `run.started.requestMeta`; a react resume re-applies them. - File-RAG also reads docx, xlsx and pptx (zip text via `node:zlib`). Audio and video are accepted but not indexed: the file row settles `failed` with a `skipped:` reason. ### Telemetry and usage Every turn records `turn.completed.usage.{model, ttftMs, durationMs, outputTokensPerSecond, costUsd, turnNumber}` next to the token counts (clock origin = lane dispatch; fields in [observability.md](/es/docs/observability) §9). `tool.result` carries `durationMs` and `startedAt`. The usage routes sum these rows per session and per user; they never recompute a price. The metered-call ledger `osprey.usage_call` (sql/014) records every metered call: one `text` row per turn (written by the turn recorder before the turn record), one `image` row per stored image, and STT and TTS rows from the voice session. `GET /usage/calls` pages it by `seq` for ddx-api, which calls with the system permission `usage:org`. ddx-api copies the rows into its own `ai` schema (`OspreyUsageEvent`, append-only, price snapshot frozen at ingest, cost NULL when unpriced) every 60 s per active org, priced from `ModelPrice` (platform-wide per alias; every edit adds a `ModelPriceRevision`). The routes `GET /usage/summary|series|users|orgs` and `GET|PATCH /usage/prices` live in `ddx-api/src/usage/` (see `ddx-api/src/usage/CLAUDE.md`). Known limit: `dudoxx-image` has no price row, so image calls show as unpriced. ### Voice The engine voice gateway listens on `127.0.0.1:9631` path `/voice` (loopback only, fixed port). The browser never connects to it. Path: browser, ddx-web BFF route class `stream-voice`, ddx-api `/osprey/voice` relay (single-use ticket from `POST /osprey/sessions/:id/voice-ticket`), engine socket. Decision record: [ADR 0020](/es/docs/adr/0020-voice-audio-transport). - Up: PCM16 16 kHz 100 ms frames plus control JSON. Down: PCM16 24 kHz audio plus control JSON. - Browser down-leg frames (length-prefixed): kind 1 PCM audio, kind 2 control JSON, kind 3 `open` (empty; ddx-api writes it first so the Next BFF flushes the response headers). - A voice turn is a normal turn (`voice: true`): same lock, lanes and tool-call cap; the reply is read from `osprey.event`. Turn end combines the STT hint, a semantic end-of-turn call and silence limits. Barge-in aborts the reply audio. - STT providers: `ddx-omni`, `deepgram`, `deepgram-onprem` (live when both `DEEPGRAM_ONPREMISE_*` keys are set; with the platform-default fallback order it is tried right before `deepgram`). `GET /voice/stt-status` lists them with `enabled`, `configured`, `healthy?`, `source`. TTS providers: `ddx-omni`, `deepgram`, `inworld`, `murf`, `openrouter`, `elevenlabs`, `kyutai` (`openrouter` speaks through the router alias `OSPREY_ROUTER_TTS_MODEL`). `GET /voice/voices` lists the voices per provider. A provider with a blank key is `unconfigured` (doctor shows N/A) and is skipped in the fallback order. Since review 050 M1, `assistant.voice.stt.provider`, `assistant.voice.tts.provider` and `assistant.voice.fallbackOrder` are org-tier only; the engine ignores a `start` override of them. - Voice frame fields: `start.language` (en, de, fr, es) pins STT and reply language for the stream; `OSPREY_VOICE_LANGUAGE` is the fallback and a provider-detected language of a turn's finals sets that turn's reply language (echoed as `finalTranscript.language`). `caption` frames carry optional `words` (timed from `offsetMs`, the reply audio position of the chunk), `wordsSource` (`provider` or `estimate`) and `offsetMs`; captions leave when the chunk's audio starts. STT and TTS usage is written to the `usage_call` ledger. - Speech budget (`src/voice/speech-budget.ts`, enforced in code by the budgeted `SentenceChunker`, never only in the prompt). The model opens a voice reply with `<speak length="short|normal|long">`; the budget caps what is spoken: | Length tag | Max sentences | Max display chars | Min extension from screen text | |---|---|---|---| | `short` (absent or unknown tag) | 1 | 220 | 0 | | `normal` (prompt default) | 5 | 700 | 3 | | `long` | 14 | 1800 | 6 | | no tag (fallback: the screen text is spoken) | 3 | 700 | n/a | The first sentence is always admitted; once capped, the chunker stays capped. The rest of the answer stays on screen. - Caption text vs TTS text: each chunk carries `display` (markdown-stripped sentence) and `text` (`toSpeakable`, e.g. "one hundred fifteen/ninety-five mmHg"). TTS gets `text`; caption frames send `text` = display and `spoken` = TTS text, with word timings over the display words. Display text is never TTS-normalised. - Voice prompt (`voicePromptLayer`, tagged system message, merged after the Summary layer and before working memory): speak block first, never read the screen aloud, a card/table/chart gets at most 3 spoken key facts, an action that waits for approval is announced with "please approve it on screen", numbers as digits. A closing format reminder ends the layer. - Suspend: a `run.suspended` row for the turn ends the spoken reply. When nothing was admitted yet, the session speaks ONE cue (`SUSPEND_CUES`: en/fr/de/es x approval|form|clarify) that points at the on-screen card. A spoken "approve" is a new turn and never resumes a run; only an on-screen decision does. - `voice.reply`: the session writes exactly one per voice turn (normal end, suspend, barge-in, close or error) through `EngineApi.recordVoiceReply` (schema `VoiceReplySchema` in `@ddx/contracts`; turn scope, owner-checked, no `runId`). Fields: `mode` (`tagged`|`fallback`), `length?`, `speakable` (admitted display sentences), `readable` (screen markdown), `sentences`, `chars`, `capped`. A write failure is logged and never fails the turn. Event catalog row: [realtime.md](/es/docs/realtime). - Web surface: voice starts in the thread (animated orb beside the composer input; dictation mic disabled while voice runs). "Full screen" opens the dialog, which shows the thread's own `OspreyTurn` (cards, HITL card) beside the orb; leaving the dialog keeps the voice stream running. The browser shows `voice.reply.speakable` in a "spoken" disclosure on the turn. - Measured first audio after end of speech: p50 2915 to 3422 ms (`findings/assistant-job/voice-latency.md`). The 800 ms stretch and 1200 ms job targets are NOT met. ### Environment key names Names only. Template: `ddx-osprey-engine/.env.example`; read by `src/lib/env.ts` (DUDOXX_*) and `src/lib/osprey-env.ts` (OSPREY_*). | Group | Keys | |---|---| | Core | `OSPREY_DATABASE_URL`, `OSPREY_QDRANT_URL`, `OSPREY_QDRANT_API_KEY`, `OSPREY_HTTP_PORT`, `CENTRIFUGO_API_URL`, `CENTRIFUGO_HTTP_API_KEY`, `OSPREY_MINIO_*` | | Search | `OSPREY_SEARCH_PROVIDERS` (ordered, for example exa,brave), `OSPREY_EXA_API_KEY`, `OSPREY_BRAVE_API_KEY`, `OSPREY_TAVILY_API_KEY` | | Images | `OSPREY_IMAGE_PROVIDER` (router only), `OSPREY_IMAGE_MODEL` (router image alias; blank = tool unavailable; the live value is `dudoxx-image`, which must be registered in the LiteLLM router that `DUDOXX_BASE_URL` points at) | | Secret box and MCP | `OSPREY_SECRET_KEY` (base64, 32 bytes), `OSPREY_SECRET_KEY_VERSION`, `OSPREY_SECRET_KEY_PREVIOUS`, `OSPREY_SECRET_KEY_PREVIOUS_VERSION`, `OSPREY_MCP_ALLOW_PRIVATE_HOSTS` (false in every shared deployment) | | Voice | `OSPREY_VOICE_LANGUAGE` (en, de, fr, es; default de), `DUDOXX_STT_URL`, `DUDOXX_STT_API_KEY` (blank falls back to `DUDOXX_TTS_API_KEY`), `DUDOXX_TTS_URL`, `DUDOXX_TTS_API_KEY` | | Deepgram | `OSPREY_DEEPGRAM_DUDOXX_URL`, `OSPREY_DEEPGRAM_DUDOXX_API_KEY` (self-hosted, wins), `OSPREY_DEEPGRAM_API_KEY` (cloud), `OSPREY_DEEPGRAM_STT_MODEL`, `DEEPGRAM_ONPREMISE_BASE_URL`, `DEEPGRAM_ONPREMISE_API_KEY` (on-prem) | | Other TTS | `OSPREY_ROUTER_TTS_MODEL` (router speech alias for the `openrouter` TTS id), `OSPREY_INWORLD_API_KEY`, `OSPREY_INWORLD_TTS_MODEL`, `OSPREY_MURF_API_KEY`, `OSPREY_MURF_REGION`, `OSPREY_ELEVENLABS_API_KEY`, `OSPREY_ELEVENLABS_TTS_MODEL`, `OSPREY_KYUTAI_TTS_URL` | Web-side renames of the same plan: `SITE_URL` became `DDX_WEB_SITE_URL`; new `DDX_WEB_GOOGLE_SITE_VERIFICATION` (server) and `NEXT_PUBLIC_GA4_MEASUREMENT_ID` (client), all in `ddx-web/.env.example`. Known limits: a crash-recovered react run continues on the lane default model; blob retention on session purge is open (accepted limit, review 040 L3); regenerate or edit of the first turn gives an empty branch without lineage columns; plan lanes carry no MCP tools. ## Permissions header and role map The engine reads `x-osprey-permissions` (comma-separated) only from the header, never the body. It keeps ids that some catalogue tool declares; unknown ids are dropped and logged. No header means no mutating tool. ddx-api derives the value from the caller's verified org roles (`OspreyPermissionMapper`): | Org role | Permissions | |---|---| | `org-admin` | `chart:write`, `letters:send`, `schedule:write`, `tasks:write`, `tools:read`, `mcp:user`, `plugins:user`, `mcp:org`, `plugins:org` | | `staff` | the four tool ids, `tools:read`, `mcp:user`, `plugins:user` | | `member` | `schedule:write`, `tasks:write`, `tools:read`, `mcp:user`, `plugins:user` | | `client`, unknown | none | **Needs owner review.** The 037-api worker chose this map from the catalogue vocabulary. It needs owner sign-off before any non-dev use (lead notes, OWNER REVIEW authz). ## Measured results (task 035, held-out, honest) Source: `findings/osprey-engine/eval/2026-10-28-report.md`. Re-run: `sh findings/osprey-engine/eval/rerun.sh`. | Gate | Value | Limit | Result | |---|---|---|---| | AC4 router accuracy (n=180) | 0.778 | 0.90 or more | FAIL | | AC4 router p95 | 289 to 396 ms | 400 ms or less | PASS | | AC8 tool recall@4 (n=124) | 0.817 | 0.90 or more | FAIL | | AC8 tools per call | 7 at most | 7 or less | PASS | | AC11 turn-record coverage | 1.0 | 1.0 | PASS | The plan lane is the weak spot (accuracy 0.361; 23 of 40 misses are plan routed to react). Six of 15 hand-read misses looked mislabelled in the silver labels. The held-out split is spent after one bounded tuning pass. Owner decision needed: a human-reviewed relabel with a new split, or a scope change. ### Run-graph judges (plan osprey-run-graph, task 009) Source: `findings/osprey-run-graph/judge/verdict.md` (2026-11-16). 9 of 15 AC pass, 3 fail, 3 are unproven because no spec was authored (tests are opt-in). The two engine suites this plan added are `run-graph-edges` (`parallel`, `ui-binding`, `react-order` — all PASS) and `plan-build-events` (`sequence` PASS, `reject-feedback` PASS, `bind-failure` FLAKY 2 of 3 runs). The `bind-failure` fixture sends an off-domain goal and expects the binder to refuse; when the planner binds a domain tool instead, no rejection is written and the case fails. A model-dependent fixture is not a deterministic judge, so the fix lane must build the refusing plan in the suite. ## Open defects and follow-ups - Playground v2 judge verdict (`findings/osprey-playground-v2/judge/verdict.md`) is FAIL on a strict reading: engine suites 7 of 7, vitest 31 of 31, BFF probes 6 of 6, browser 7 of 9 rows pass; AC26 (streamed tool input painted in the browser) fails; the approval mutation path was not triggered by the model; AC5, AC8, AC12 (browser), AC17, AC18 and AC19 were not run. The suite `lanes-chat-react` failed twice on model behaviour in task 007 (no baseline) and is not attributed. - A dead run does not show as expired: a suspended run stays resumable after an engine restart (claim released, plans re-registered). - `./ddx-manage.sh` state for the engine pid was fixed to name the 9630 listener (the `tsx watch` child). - The binder bound a "create a follow-up task" step to `list_tasks` in the browser run; the lead added a planner rule that agent steps never change data. - Engine-down (503) path of ddx-api was not probed live. `./ddx-manage.sh docs` (OpenAPI export) was not run after the new routes; the hand-written OpenAPI files cover them until the owner regenerates. - Mastra spine (plan osprey-mastra-native): the measured tasks 053-057 and 062 (parity, accuracy, time, tokens) and Plan A 018-019 are deferred to the owner validation session. The spine resume / time-travel path and the request-context restore from a snapshot are not proven live. Legacy deletion (058-061) waits for a passing parity gate. --- Last reconciled: 2026-11-17 · plan osprey-mastra-native task 064 (Mastra spine, case library, learning loop, sql/033-036)
ddx-osprey-engine/ is the adaptive agentic engine behind the Osprey playground: a turn router,
five lanes, plans compiled to Mastra workflows, durable runs, Tool-RAG and capture plus eval. Mastra 1.82
(@mastra/core 1.82.0) on the Dudoxx router (llm-router.dudoxx.com). It listens on 127.0.0.1:9630 and has one caller:
ddx-api. Contract: ddx-osprey-engine/CLAUDE.md. Realtime delivery: .
Ports: .
Rules the engine keeps (plan _invariants.md): ddx-mastra/ is copied from, never edited or imported;
wire types come only from @ddx/contracts/osprey-*; no mock model or provider (a dead router,
Postgres, Qdrant or Centrifugo fails loudly, exit 3); demo tools use synthetic fixtures.
Browser, then ddx-web BFF /api/v1, then ddx-api /osprey/*, then the engine gateway. ddx-api checks
session and tenant ownership before every engine call and sends identity and permissions as headers.
A session row missing in ddx-api is backfilled once: ddx-api asks the engine GET /sessions/:id with the caller's
own tenant and user headers (the engine answers only for the owner); 200 writes the row with the caller's org and
user (engine-created sessions such as osprey session seed), 404 stays one 403. A run id never grants access.
Routes (engine gateway; ddx-api mirrors them under /osprey):
HTTP shapes: (ddx-api) and (engine gateway).
Each turn passes one router (src/router/): zero-LLM rules first (an approval or form answer resumes,
a /plan /chat /react slash command forces a lane, the assistant.llm.mode setting (chat, react, plan) pins a lane (auto routes as before), a pure UI command goes to react, a verb plus an image/PDF/Word noun goes to react (image-intent / document-intent), a vague
imperative clarifies), then one decision-model call. The decision call also answers the background workflow (none | deep-content | diagnosis; criteria in route-prompt.md ## workflow:*); there is no keyword rule for deep content (owner 2026-11-12). Turns that need live or external data (current conditions, news, date and time, web or video) are react, never chat. The router is bounded by a 400 ms p95 target.
A lane writes only through ctx.append, and owns its terminal run event. Terminal run events are run.finished,
run.failed, run.stalled and run.cancelled; the event log drops any draft of a run that is already terminal. The CLI (osprey chat,
session, turn, plan, run, tools, eval) runs the same facade in-process and reads events back
from osprey.event.
At most 4 searched plus 3 pinned tools reach one model call; always-include tools count inside the cap.
Mutating tools carry idempotency keys (<runId>:<nodeId>), recorded in an effects ledger (sql/002).
The measured maximum was 7 tools per call.
The searchable catalogue has 11 live capability tools: web_search, search_news, get_weather, generate_image, deep_research,
current_datetime, youtube_search, summarize_thread, search_documents, generate_pdf and generate_docx. generate_docx builds a Word file server-side with the docx dependency (^9.15.0) from OSPREY_DOCUMENT_PRESET (@ddx/contracts/osprey-document-preset), stores it in osprey.blob (at most 10 MiB) and emits a docx UI block (blobId, filename, bytes, title, preset); a run without an owner returns an error envelope. generate_pdf and generate_docx accept a DocumentSpec object or markdown text. Zero-LLM router rules also send a generate-intent request (a verb plus an image, PDF or Word noun, en/de/fr/es, at most 30 words, no patient or appointment words) to react (image-intent, document-intent); a turn with inline images goes to chat first. generate_image and generate_docx write blobs; the other tools write nothing. youtube_search and
search_documents count as untrusted-content sources (approval-gated copies of mutating tools, plan approval before every mutating node).
src/plan/: planner (structured-output draft), binder (per-node Tool-RAG), validate (typed
PlanValidationError), compiler, store (osprey.plan, osprey.plan_run), runtime, failure-policy
and mutator (Plan v+1 patches and diff). A plan version compiles to a registered dynamic workflow
plan-<sessionId>-<planId>-v<version> using registered keys only; agent nodes are registered at boot
(src/boot/plan-workers.ts) so stored plans resume after a reboot. A node with no tool above the score
floor clarifies and never runs with zero tools. Foreach items run as child workflow runs.
Known limits: a root step cannot read a parallel child's output (depend on the parallel block and read a
later step). The binder rejects a ${key} that names no upstream output. A plan mutation can finish a run
without reaching the goal; success criteria are not checked at run end (open, reported by task 036).
One attempt writes a fixed sequence, so the run graph can show the plan being built instead of only the plan being run:
plan.drafted with phase: 'drafting' — one row per newly COMPLETE node as the planner streams,
each carrying the plan built so far (a drafting partial REPLACES the previous drafting node set, it
never accumulates). attempt is the 1-based planner attempt.plan.bound {planId, version, ok, bindings[{nodeId, status: bound | unbound | gate | pinned, toolIds[], score, source}], clarify?} — the per-node result of the Tool-RAG bind. status is gate
when the node is approval-gated and pinned when it binds a pinned UI tool (ui_control,
render_card); clarify names the node that found no tool and why.plan.rejected {planId, version, attempt, stage: bind | validate, issues[{nodeId?, code, message}]} — written BEFORE the retry, so the browser can mark the issue node
rejected with its reason.plan.drafted with phase: 'final' — the bound plan of that version; this fixes the node set.phase and attempt are optional and every row written before this change still parses. A row without
phase (G14) replaces the drafting set per row, nodes show pending, binding falls back to the plan node's
toolId / allowedTools, and the build strip shows "not recorded". plan.mutated keeps its own shape
(plan, diff) and marks the graph's added / removed / rewired / changed nodes for the new version.
stepId)tool.call and tool.result carry an optional stepId — the plan node id that made the call
(packages/ddx-contracts/src/osprey-events.ts). The plan runtime knows the node id when it invokes the
tool (src/plan/runtime.ts, set only when the tool input really carries a node field; a "node" fallback
would be a guess and never reaches the log). React rows never set it: a react call's parent is the LAST
llm.step.started of its run, and an old plan row without stepId attaches only when exactly one running
node of that run is bound to that toolId, else to the run's unattributed group. This is what lets two
tool nodes of one parallel container keep their own calls apart.
ddx-web/src/lib/osprey/run-graph.ts folds the same osprey.event rows into SessionView.runGraphs,
ONE graph per RUN (never per session: view.plan / view.steps are keyed by a bare node id and would bleed
across turns). The fold is pure, reads no text or reasoning event, and returns the same object when an event
changes nothing, so a live row and a compacted snapshot fold deep-equal (FM3). Layout
(run-graph-layout.ts, own layered layout — no dagre, no elkjs) is keyed by a topology signature of node and
edge keys, so a status change re-renders the node only. The canvas is @xyflow/react, loaded through
next/dynamic when the Run tab opens. No new event type, no new realtime path: the graph is the same log the
panel already receives.
One retry owner per class: step retries (at most 2) then REWIRE (failed tools excluded, same mutating
class and category, at most 2 per run, step.rewired) then MUTATE (planner re-plan to Plan v+1, at most 3
per run, plan.mutated with a diff) then run.stalled with a readable reason in under 60 s. A denied or
permission error is run.failed. Every new plan version runs in the same run id, so a done mutating step
is replayed and has no second effect.
An approval authorises one call, not a step. run.suspended carries toolCallId and a binding
{toolCallId?, nodeId?, toolId, fingerprint, summary, expiresAt?}; the fingerprint is sha256 of the canonical
{toolName, args} (keys sorted, idempotencyKey and Osprey bookkeeping fields dropped).
approval.invalidated and suspends again. The gated tool wrapper re-hashes before
tool.call and throws ApprovalMismatchError with zero effects. A mismatch re-issues the plan as v+1 (plan.mutated,
diff re-ask approval). A gate binds ONE call (the first mutating dependent). Bindings are read back from the run.suspended /
run.resumed rows, so they survive a restart (readApprovalBindings, readApprovedToolCall).requireApproval stays the gate; a beforeToolCall hook (buildReactApprovalHooks) refuses a gated call
whose fingerprint differs from the approved binding.data.feedback cancels the suspended version, re-drafts Plan v+1 with the
feedback, appends one plan.mutated and asks again in the same run. A deny without feedback ends the run with run.failed.Judge: engine suite approval-binding.
ui.block, ui.action and ui.action.acked work in every lane. A UI-only request (every clause names a UI verb and object, no data
word, no digit) routes to react with reason ui-intent; request_plan refuses UI-only goals. The binder keeps a planner-chosen
ui_control or render_card node when the pinned tools are passed to it (plan/runtime.ts passes them), so a UI-only plan step binds
and the run graph shows that binding (plan.bound row status: 'pinned'; engine suite run-graph-edges case ui-binding). The plan lane appends one summary text part
(text.start/delta/end, partId plan-summary:<runId>:<n>) in front of every terminal run event.
POST /runs/:runId/cancel stops a run. The turn runner keeps one AbortController per run (turn and resume). Cancel writes one guarded
batch: tool.denied {reason: cancelled} for an open approval or form, text.end for every open part, then run.cancelled; it then aborts
the live stream or the plan workflow. A run that already ended answers 409 and writes no event. Known limit: cancelling a SUSPENDED react
approval leaves the Mastra durable snapshot suspended in osprey_mastra; the log says run.cancelled and every later resume is 409. The CLI
osprey run cancel is unchanged and works on a suspended run only (it appends run.failed).
sql/006_session_meta.sql adds pinned, updated_at, title_source (first-turn, model, user), origin (user, suite, seed,
subrun), deleted_at and a partial rail index. Suites, seeds and sub-runs have an origin other than user, so they stay off the rail.
Turn 1 writes session.titled {first-turn} (the user text clamped to 60 characters at a word boundary) in the same append as
turn.received. After the turn one structured-output call to the wrapped Dudoxx model (own request, thinking off, temperature 0, 1500 ms
timeout) refines it to session.titled {model}; a failure is logged loudly and the first-turn title stays. A machine title never replaces a
user title.
Postgres schema osprey (sql/000-032; table below covers 000-015): base, event log, tool effects, plan, turn records, run claims, session meta, then the assistant platform files. The migrator applies every unapplied file in name order, and each file is idempotent.
osprey.event is the only authority.
osprey.run_claim (kinds plan, react, deep; 5 s heartbeat, 15 s lease).src/boot/recovery.ts) runs at boot and every 5 s. It adopts a stale lease, appends
run.recovered, restarts a plan from the Postgres snapshot, recovers a react run or restarts a deep run (getDeepContentRuntime().restart), then closes the
orphaned turn lock. A reboot alone never fails a run. After 3 failed attempts the run gets run.failed
with recovery-exhausted. A deep run that exhausts recovery moves to failed with the deep failed progress phase and
no run.failed; the deep runtime owns its lease release and its single terminal.osprey.turn_record per turn, derived from osprey.event (src/capture/turn-recorder.ts).A long-report ask starts a background run: the react lane calls start_deep_content, which returns a handle and a
deep-content card; the run id is dcr_<id>. The run is the workflow osprey-deep-content under a lease of kind deep
(src/deep-content/runtime.ts). Source: ddx-osprey-engine/src/deep-content/.
sql/015_deep_content.sql (store.ts): runs, artifacts, source registry, claim ledger. Reads are scoped to tenant and user.DEEP_CONTENT_DEFAULTS): 6 sub-agents, 6 searches each, 2 gap rounds, 30 min wall clock stay hard caps.
maxTokens defaults to no cap (null); a request may set it. Tokens are counted per run.research/history-compact.ts): every tool result but the newest is cut to a short url/title digest
before each provider call, so a multi-step researcher does not re-send all earlier pages.judges/): repetition (embedding cosine), claim ledger, LLM coherence; the result is stored in deep_run.judge.progress.data.deep through DeepEmitter (see realtime.md); no new event type.GET /deep-runs/:id (status, counters, judge) and GET /deep-runs/:id/document (markdown; 409 before the run
has succeeded); a foreign or unknown run is 404. POST /runs/:id/cancel also stops a dcr_ run.tool_ids run-time enforcement.Per-specialty diagnosis: a doctor submits one patient or a cohort, the engine scores, asks questions and returns outputs. Decision record: . It adds no lane and no event type.
Safety. A red flag pins must-not-miss cards and raises urgency. A check that cannot run is blocked_unknown.
Guidance is withheld on blocked and blocked_unknown. Report sentences without a resolvable evidence id are
stripped. Every output carries citations and the disclaimer.
Promotion gate. decide() publishes a revision only with a real reviewer id and a passing gate. The gate
replays the specialty gold set: must-not-miss recall below the published baseline is gate_failed (no override);
top-5 recall may drop by at most gateTop5Tolerance. Seed baselines (datasets/diagnosis/baseline.json):
must-not-miss recall 1.0 on all three; top-5 recall 0.78 cardiology, 0.83 dermatology, 0.77 gastroenterology.
Curator. A tick claims a window (unique window_key), picks the stalest cards, builds the research brief from
card fields only (no casework import, so no patient data), starts a deep-content run on a dedicated system
session, and turns the finished run into pending, cited proposals. It never publishes. Failed or cancelled runs
create no proposal. The ddx-api scheduler fires the tick on every node; the engine dedups by window.
Settings. module.diagnosis.* (19 core keys plus later additions, §Diagnosis keys) travels in the run-start
or tick body as DxSettings, never in x-osprey-settings.
Card author (plan dx-card-kb, src/diagnosis/card-author/). The workflow osprey-dx-card-author writes one card
folder (osprey-dx-card/1) per run: a new card from a free-text brief, or an upgrade of an installed card (mode new |
upgrade). Steps: target, search, fetch, draft (one part per item), merge, translate, verify, assemble. Sources are
generic per-part web searches capped at sourcesPerCard; every cited URL must have been fetched and alive (dead URLs
are reported, never cited). Verify checks the folder schema, the refs-frozen guard (an upgrade keeps the base card's
code, specialty, refs, relations, rule keys and option keys), 4-locale completeness, citation quotes against the fetched
pages, URL liveness, expert revert and an authorship scan. A value with no source keeps the installed value with
derivation expert. A run is one row in osprey.dx_card_author_run (sql/025) with a stage checkpoint (sql/026)
written after each stage: a run read shows interim progress (sources, finished parts, the partial folder,
resumable), and a failed run resumes from its checkpoint with the same id. The boot module src/boot/card-author.ts
fails runs orphaned by an engine restart at start. Routes: POST /diagnosis/card-author/runs,
GET /diagnosis/card-author/runs[/:id], POST …/runs/:id/resume, POST …/runs/:id/submit; owner-scoped, see
. The run never installs or publishes: submit files
one PENDING proposal of kind: folder (curation/proposals.ts, proposer = the run's owner), and a different reviewer
decides it. Settings: module.diagnosis.cardAuthorModel, cardAuthorSourcesPerCard, cardAuthorConcurrency
(). Wire types: @ddx/contracts/osprey-diagnosis-card-author.
Case Studio (plan osprey-case-studio, all under ddx-osprey-engine/src/diagnosis/). A case carries patient context (medications by ATC code, allergy classes, conditions, kidney and liver bands, pregnancy, breastfeeding) in its intake, and a cohort carries it per patient. New engine routes, all owner-scoped (tenant + user from the gateway headers; a foreign or unknown run is 404):
GET /diagnosis/allergen-classes?q= lists allergy classes for the picker (gateway-knowledge.ts).GET /diagnosis/runs/:id/questions returns the question history: every stored question of every round with its answer, note and source (question-history.ts). POST on the same path is the ask-more call.GET /diagnosis/runs/:id/case-report?sections&caseNumber returns { report, markdown, document, judge }. A run with no completed result is 409. caseNumber is optional and must match ^DX-\d{4}-\d{5}$ (400 otherwise); without it the report has no case number and no run number, nothing is invented.Files: case-report.ts assembles the report from stored results (it never recomputes a number); case-report-render.ts builds ONE typed section list that feeds both the Markdown and the PDF document spec, so the two carry the same values; case-report-judge.ts is the numbers judge (every probability, odds and interval in the Markdown and in the PDF spec must equal the stored run); draft-intake.ts maps a confirmed chat draft to the single-patient run intake and keeps the safety context whole; answer-labels.ts writes the label lines of an approval card. Report text comes from prompts/case-report.md (the section order, placeholders only) and prompts/case-report.labels.json (4 locales). The report prints no run id, case id, hash or rule key; those stay in the JSON generatedFrom. Numbering and file names: §6.5.
Assistant tools of the case chat: dx_case_facts (the case as stored), dx_question_candidates (read-only; the finding ids the assistant may propose, from the round's own ranking), dx_question_propose, dx_ask_more and dx_case_patch. The last three need approval and the card shows names, never ids. Ask-more rule: an approved assistant pick always keeps the last slot of the round, so the cap never drops it; red-flag rule-outs come first. A cohort run refuses ask-more. Migrations: 030 adds the answer note and the question source (engine or assistant) to dx_question; 031 is the Dx persona text v3 (case facts first, one more question round, case change by proposal; it updates only persona rows still equal to the 029 text). Run pnpm osprey db migrate. When the report is too large for the PDF bounds, the response has pdfError and no document; the Markdown stays whole and a cut PDF is never sent.
CLI. osprey dx pack install|install-all, dx cards list --specialty, dx corpus ingest, dx index rebuild,
dx cards author (--queue <file.json> | --card <CODE>) --out <dir> [--model] [--limit] [--concurrency] [--sources] [--dry-run] [--json] (writes <CODE>/card.json folders to --out, never installs), dx learn check --before <run> --after <run> --proposal <id>, dx learn import-stage <signals.json>.
Suites (all PASS at close-out): dx-core-determinism and dx-eval-golden (zero model calls),
dx-run-live, dx-curator-live.
Case drafts: async fill, mapping and alternatives (plan osprey-dx-accuracy, under ddx-osprey-engine/src/diagnosis/ unless noted). POST /diagnosis/cases/:id/drafts answers 201 at once with fill: pending. draft-fill.ts (startDraftFill) claims the row in draft-store.ts (claimDraftFill: one transaction plus an advisory lock; dedupe on case + text hash, so a repeat call returns the live row; a failed or stale row is retried on the same id with fillAttempt + 1) and runs the extraction in the background. The fill ends ready (completeDraftFill) or failed (failDraftFill, a fixed error text, never model output). A pending row past draftStaleMinutes reads failed / stale. Every draft answer carries fill, fillError and fillAttempt; confirm and edit answer 409 while fill is not ready. sql/032 adds the columns fill_status, fill_error, fill_attempt, text_hash, fill_deadline and the dedupe index dx_case_draft_fill_dedupe_idx. Boot module src/boot/draft-fill.ts fails pending fills past their deadline at server start; a second engine on the same database keeps its live fills. The chat-tool path stays synchronous. Mapping: concept-match judges the top conceptMatchTopK vector hits with the scrubbed case note (conceptMatchNoteChars) and offers conceptMatchCandidates candidates; a vector-mapped item is always held; each item carries up to draftAlternatives alternatives the doctor can switch to; a measure without value and unit becomes a text-only sign. The gateway method loop (src/gateway/routes.ts) registers PUT, which PUT /diagnosis/drafts/:id needs. Keys: §Draft and mapping keys.
Mastra spine (plan osprey-mastra-native, ddx-osprey-engine/src/diagnosis/spine/). A second run engine beside the
workflow osprey-diagnosis. The registry key module.diagnosis.engine picks it per run: legacy (the seed, today's
pipeline) or mastra (the spine). The STORED run settings decide start, resume, ask-more, restart, cancel and reads,
so a run never changes engine mid-life (runtime.ts isSpine). The spine is built and switchable; it is not the
default, and its parity, accuracy, time and token runs (tasks 053-057, 062) have not run yet. The legacy path stays
until the parity gate passes.
Learning loop (plan osprey-mastra-native). Every signal is ids and counts, never patient text; every card change is a PENDING proposal that a reviewer other than the proposer decides.
curation/board-signals.ts, sql/034): an alternative switch, an item tick or untick and a confirmed
final diagnosis are recorded as id-and-count signals after the gateway write succeeds. A final-diagnosis signal at
boardSignalMinSupport files a PENDING feedback proposal.feedback-signals.ts).createProposal / createFolderProposal attach the promotion gate result on the TUNE split
(holdout rows dropped) to the pending row in the background. decide() judges the gate now and the stored gate: a
must-not-miss drop always fails; a top-5 failure publishes only with an overrideReason (≤ 1000 characters, logged
to stderr); without one a failure now is gate_failed and a stored-only failure is refused (override_required, 400).curation/closed-loop.ts): osprey dx learn check --before <run> --after <run> --proposal <id>
compares the gold-card rank per case of two usage runs around a publish; a case worse than
closedLoopRankTolerance files a PENDING rollback proposal (never a rollback).osprey dx learn import-stage <signals.json> adds the stage misses of a usage run (counts only,
written by osprey-usage signals <runDir>) to the gap signals; a HOLDOUT run and a run already imported are refused.draft-fill.ts): a form value wins over the text fill; each field records its origin and
conflicts.Assistant tools (plan osprey-mastra-native, registered in the chat catalogue and reached through tool search).
dx_analyze_case starts or attaches to an owned run, relays each step as an interim data event and answers with one
speech sentence; dx_score_case, dx_rank, dx_search_cards, dx_graph_walk wrap the spine tools with owner
checks (tools/catalogue/diagnosis-spine.ts). Card CRUD (diagnosis-cards.ts): dx_card_get / dx_card_search
read without approval and answer WITHHELD for a safety-blocked on-screen run (shared check
diagnosis-safety.ts); dx_card_insert / dx_card_update / dx_card_update_attribute need diagnosis:propose and
only file a PENDING dx_proposal. Case library (diagnosis-library.ts): dx_similar_cases and dx_feedback_note
(approval required). The Dx persona text is v4 (sql/036).
Observability note (security review 052, accepted). "No PHI in a Mastra snapshot" holds for workflow snapshots.
Spine agent spans go through MastraStorageExporter, and SensitiveDataFilter redacts secrets, not free text, so
agent span input (case free text) is stored in osprey_mastra spans, in the same Postgres as dx_run.intake. No
retention or purge ties those spans to case deletion.
API surface. ddx-api serves 8 case routes (/osprey/diagnosis/{specialties,cards,cards/:cardId,cases/:caseId/runs,runs/:runId,runs/:runId/answers,runs/:runId/outputs,runs/:runId/feedback})
and 4 platform-admin routes (proposals, proposals/:proposalId, proposals/:proposalId/decision,
curator/tick); later plans added more diagnosis routes, among them 5 card-author routes (POST|GET /osprey/diagnosis/card-author/runs, GET …/runs/:runId, POST …/runs/:runId/resume, POST …/runs/:runId/submit); see ddx-api/src/osprey/CLAUDE.md. The generated OpenAPI files (api/openapi.json,
api/osprey-api.openapi.yaml, api/osprey-engine.openapi.yaml) did not list /osprey/diagnosis at close-out (the two hand-written YAML files now list the card-author routes):
they are produced by ./ddx-manage.sh docs (lead).
Settings, per-turn model and effort, forks, projects, personae, files, MCP, customization and voice. The
contract is ddx-osprey-engine/CLAUDE.md; module shapes are in packages/ddx-contracts/README.md §Osprey engine.
The gateway reads x-osprey-settings (base64url JSON of the 23 assistant.* keys ddx-api resolved; keys:
§Assistant keys). src/gateway/assistant-settings.ts validates each key; a bad key, value or
encoding is 400 bad_settings. Lanes receive it as ctx.assistant. Model and effort: body over settings; unknown model is
400 unknown_model before the turn lock; effort becomes a thinking budget, never reasoning_effort.
## Persona layer folded into the one system message
(the provider merges every system message into one). ddx-seeder provisions the seed personae, skills, agents and projects over
ddx-api HTTP: ./ddx-manage.sh seed osprey [--dry-run] (refused in production; ).
Seed texts are NEEDS_REVIEW.assistant.persona.defaultId. Instructions (assistant.instructions,
assistant.style.tone) and persona text are budgeted layers; assistant.memory.enabled=false drops working memory and
semantic recall for the call.POST /memories {text} writes one line into the caller's working memory (201 SavedMemory). Bounds are the
settings assistant.memory.maxLines (seed 8) and assistant.memory.maxLineChars (seed 160), both org tier, edit by org-admin.
400 invalid_body (too long, empty, or patient-shaped: patient_data); 409 memory_full or memory_disabled. A server-side guard
keeps working memory to the template keys and drops patient-shaped values. The model may also write it through updateWorkingMemory
in the chat and react lanes.osprey_files. Images are
sent to the model for that call only (TurnImagesProcessor); the log and osprey_mastra store no image bytes. A vision
request on a model without the image capability is 400 vision_unsupported.web_search, search_news, deep_research, get_weather, generate_image) are live and read-only.
Search goes through an ordered SearchChain (exa, brave, tavily) with fallback to the next keyed provider. Image generation
uses the router only (/images/generations, alias OSPREY_IMAGE_MODEL, b64_json); the bytes are stored in osprey.blob and served as
/api/v1/osprey/blobs/:id. A blank alias or a router without that alias answers tool_unavailable with an error that names OSPREY_IMAGE_MODEL (expected alias dudoxx-image) and says to register it in LiteLLM; nothing is faked. Each stored image writes one usage_call row (kind image, 1 unit, provider router); a ledger failure is logged and never hides the image. Query text reaches the chosen vendor (operator-accepted, flagged in review 039).src/lib/secret-box.ts); reads show header names only. URLs pass an
SSRF guard at save and at every connect (DNS vetted, socket pinned, no redirects); allow-listed tools are pinned to a
fingerprint; a run that can read untrusted content gets approval-gated copies of mutating tools.run.failed {kind: policy}. Within one step a repeated read-only call (same tool, same exact arguments) runs once and the model
gets that one answer (step memo); a read-only repeat gives its start back to the cap, a mutating call never does.packages/ddx-contracts/src/llm-router-models.ts (12 router aliases, 7 legacy ids, capabilities, limits,
USD-per-million prices). There is no direct OpenRouter provider; or-* aliases go through the router. The default model is dudoxx-prod
(DUDOXX_MODEL_NAME); it accepts one leading system message only, so the wrapped model merges every system message into one. Title and
decision models stay on dudoxx-gemma.assistant.llm.temperature|topP|topK|maxOutputTokens|thinkingBudget are sent only when they differ from the platform
default (maxOutputTokens clamped to the alias cap, thinkingBudget only with effort off) and are recorded on
run.started.requestMeta; a react resume re-applies them.node:zlib). Audio and video are accepted but not indexed: the file row settles
failed with a skipped: reason.Every turn records turn.completed.usage.{model, ttftMs, durationMs, outputTokensPerSecond, costUsd, turnNumber} next to the token counts
(clock origin = lane dispatch; fields in §9). tool.result carries durationMs and startedAt. The
usage routes sum these rows per session and per user; they never recompute a price.
The metered-call ledger osprey.usage_call (sql/014) records every metered call: one text row per turn (written by the turn recorder before the turn record), one image row per stored image, and STT and TTS rows from the voice session. GET /usage/calls pages it by seq for ddx-api, which calls with the system permission usage:org. ddx-api copies the rows into its own ai schema (OspreyUsageEvent, append-only, price snapshot frozen at ingest, cost NULL when unpriced) every 60 s per active org, priced from ModelPrice (platform-wide per alias; every edit adds a ModelPriceRevision). The routes GET /usage/summary|series|users|orgs and GET|PATCH /usage/prices live in ddx-api/src/usage/ (see ddx-api/src/usage/CLAUDE.md). Known limit: dudoxx-image has no price row, so image calls show as unpriced.
The engine voice gateway listens on 127.0.0.1:9631 path /voice (loopback only, fixed port). The browser never connects
to it. Path: browser, ddx-web BFF route class stream-voice, ddx-api /osprey/voice relay (single-use ticket from
POST /osprey/sessions/:id/voice-ticket), engine socket. Decision record: .
open (empty; ddx-api writes it
first so the Next BFF flushes the response headers).voice: true): same lock, lanes and tool-call cap; the reply is read from osprey.event.
Turn end combines the STT hint, a semantic end-of-turn call and silence limits. Barge-in aborts the reply audio.ddx-omni, deepgram, deepgram-onprem (live when both DEEPGRAM_ONPREMISE_* keys are set; with the platform-default
fallback order it is tried right before deepgram). GET /voice/stt-status lists them with enabled, configured, healthy?, source.
TTS providers: ddx-omni, deepgram, inworld, murf, openrouter, elevenlabs,
kyutai (openrouter speaks through the router alias OSPREY_ROUTER_TTS_MODEL). GET /voice/voices lists the voices per provider. A provider with a blank key is unconfigured (doctor shows N/A) and is skipped in the fallback order. Since review
050 M1, assistant.voice.stt.provider, assistant.voice.tts.provider and assistant.voice.fallbackOrder are org-tier only;
the engine ignores a start override of them.start.language (en, de, fr, es) pins STT and reply language for the stream; OSPREY_VOICE_LANGUAGE is the fallback and a provider-detected language of a turn's finals sets that turn's reply language (echoed as finalTranscript.language). caption frames carry optional words (timed from offsetMs, the reply audio position of the chunk), wordsSource (provider or estimate) and offsetMs; captions leave when the chunk's audio starts. STT and TTS usage is written to the usage_call ledger.Speech budget (src/voice/speech-budget.ts, enforced in code by the budgeted SentenceChunker, never only in the prompt).
The model opens a voice reply with <speak length="short|normal|long">; the budget caps what is spoken:
The first sentence is always admitted; once capped, the chunker stays capped. The rest of the answer stays on screen.
display (markdown-stripped sentence) and text (toSpeakable, e.g.
"one hundred fifteen/ninety-five mmHg"). TTS gets text; caption frames send text = display and spoken = TTS text,
with word timings over the display words. Display text is never TTS-normalised.voicePromptLayer, tagged system message, merged after the Summary layer and before working memory): speak
block first, never read the screen aloud, a card/table/chart gets at most 3 spoken key facts, an action that waits for
approval is announced with "please approve it on screen", numbers as digits. A closing format reminder ends the layer.run.suspended row for the turn ends the spoken reply. When nothing was admitted yet, the session speaks ONE
cue (SUSPEND_CUES: en/fr/de/es x approval|form|clarify) that points at the on-screen card. A spoken "approve" is a new
turn and never resumes a run; only an on-screen decision does.voice.reply: the session writes exactly one per voice turn (normal end, suspend, barge-in, close or error) through
EngineApi.recordVoiceReply (schema VoiceReplySchema in @ddx/contracts; turn scope, owner-checked, no runId). Fields:
mode (tagged|fallback), length?, speakable (admitted display sentences), readable (screen markdown), sentences,
chars, capped. A write failure is logged and never fails the turn. Event catalog row: .OspreyTurn (cards, HITL card) beside the orb; leaving the
dialog keeps the voice stream running. The browser shows voice.reply.speakable in a "spoken" disclosure on the turn.findings/assistant-job/voice-latency.md). The 800 ms
stretch and 1200 ms job targets are NOT met.Names only. Template: ddx-osprey-engine/.env.example; read by src/lib/env.ts (DUDOXX_) and src/lib/osprey-env.ts (OSPREY_).
Web-side renames of the same plan: SITE_URL became DDX_WEB_SITE_URL; new DDX_WEB_GOOGLE_SITE_VERIFICATION (server) and
NEXT_PUBLIC_GA4_MEASUREMENT_ID (client), all in ddx-web/.env.example.
Known limits: a crash-recovered react run continues on the lane default model; blob retention on session purge is open (accepted limit, review 040 L3); regenerate or edit of the first turn gives an empty branch without lineage columns; plan lanes carry no MCP tools.
The engine reads x-osprey-permissions (comma-separated) only from the header, never the body. It keeps
ids that some catalogue tool declares; unknown ids are dropped and logged. No header means no mutating tool.
ddx-api derives the value from the caller's verified org roles (OspreyPermissionMapper):
Needs owner review. The 037-api worker chose this map from the catalogue vocabulary. It needs owner sign-off before any non-dev use (lead notes, OWNER REVIEW authz).
Source: findings/osprey-engine/eval/2026-10-28-report.md. Re-run: sh findings/osprey-engine/eval/rerun.sh.
The plan lane is the weak spot (accuracy 0.361; 23 of 40 misses are plan routed to react). Six of 15 hand-read misses looked mislabelled in the silver labels. The held-out split is spent after one bounded tuning pass. Owner decision needed: a human-reviewed relabel with a new split, or a scope change.
Source: findings/osprey-run-graph/judge/verdict.md (2026-11-16). 9 of 15 AC pass, 3 fail, 3 are
unproven because no spec was authored (tests are opt-in). The two engine suites this plan added are
run-graph-edges (parallel, ui-binding, react-order — all PASS) and plan-build-events
(sequence PASS, reject-feedback PASS, bind-failure FLAKY 2 of 3 runs). The bind-failure fixture
sends an off-domain goal and expects the binder to refuse; when the planner binds a domain tool instead,
no rejection is written and the case fails. A model-dependent fixture is not a deterministic judge, so
the fix lane must build the refusing plan in the suite.
findings/osprey-playground-v2/judge/verdict.md) is FAIL on a strict reading: engine suites 7 of 7,
vitest 31 of 31, BFF probes 6 of 6, browser 7 of 9 rows pass; AC26 (streamed tool input painted in the browser) fails; the
approval mutation path was not triggered by the model; AC5, AC8, AC12 (browser), AC17, AC18 and AC19 were not run. The suite
lanes-chat-react failed twice on model behaviour in task 007 (no baseline) and is not attributed../ddx-manage.sh state for the engine pid was fixed to name the 9630 listener (the tsx watch child).list_tasks in the browser run; the lead added a
planner rule that agent steps never change data../ddx-manage.sh docs (OpenAPI export) was not run
after the new routes; the hand-written OpenAPI files cover them until the owner regenerates.Last reconciled: 2026-11-17 · plan osprey-mastra-native task 064 (Mastra spine, case library, learning loop, sql/033-036)
adr/
deploy/
research/