Compare commits

..

8 Commits

Author SHA1 Message Date
vh 8ebe227ae4 feat(#17): dispatch-layer op-feed for the provider (slice 2 — Observe)
Slice 2 of issue #17 — the OBSERVE half. New ratatoskr.provider.opfeed:

- OpEvent{ts, plane, op, session_id, status, req_summary, resp_summary,
  turn_id=None} — scope-only summaries, never record bodies / PAD content
- OpSink Protocol + JsonlOpSink (continuous append-only JSONL, INV-007)
- instrument_provider_app(app, *, plane, sink): an ASGI middleware over the
  built bifrost provider app. Buffers+replays the request, captures the
  response, reads session_id off the dispatch JWT's "sub" claim (INV-005 —
  present for ALL verbs incl. search/get/delete, which bifrost withholds from
  the store method), emits exactly one OpEvent per inbound bifrost-call incl.
  handshake + errors. Read-only over dispatch; store scope semantics untouched
  (INV-004). A sink/summary failure is swallowed + logged, never breaks serve
  (POST-003).
- Per-verb summaries: search {scope_all,scope_any,top_k}->{hit_count,hits};
  upsert_many {record_count,scopes}->{upserted,replayed}; get/get_many/
  delete_many {ids}->{found_count|deleted}; emit (affect, opaque)->{stored};
  handshake {caps_requested}->{caps_granted,ok}; error->{error: code}
- serve_memory/serve wired: opt-in via RATATOSKR_OPFEED_PATH (maybe_instrument)

Resolves the contract's open question: the dispatch JWT DOES carry session_id
(= the "sub" claim). Tests drive the REAL bifrost dispatch end-to-end with
minted JWTs. 11 new tests; full suite 453 green; ruff + mypy clean (opfeed.py).
2026-06-18 00:36:33 -07:00
vh 7be162e84d feat(#17): create_session Bifrost-bind primitive (slice 1)
Slice 1 of issue #17 (Bifrost-binding the chat client) — the client-side
BIND primitive, TDD'd against docs/contracts/issues/17.contract.md.

- BifrostBinding{endpoint_url, scope=None} frozen dataclass (#160 shape)
- create_session(..., bifrost=, consumer_key=): carries the bifrost body
  field and OVERRIDES the bearer to the consumer key per-request (INV-001 —
  never falls back to the canary key)
- BifrostConsumerKeyMissing: raised BEFORE any HTTP when a binding lacks a
  non-empty key (PRE-001)
- BifrostHandshakeFailed: 502 on a BOUND create -> carries detail.bifrost_error
  (both-shape unwrap per the persona_state wire lesson); gated on bifrost!=None
  so an unbound 502 stays SessionApiFailed (INV-002)
- endpoint_for_plane: memory->:8391 / affect->:8390, invalid->ValueError

7 new tests; full suite 442 green; ruff clean.
2026-06-18 00:21:36 -07:00
vh f533464c54 memory: snapshot — persona-pane reframe (worldtree-dev): persona_state GET is Tier-1-only by ADR-0009 (colon-404 correct-by-design, not a stub); Tier-3 affect is CLIENT-persisted — we already hold PAD/valence @ :8390 from affect.emit, so the pane is an OUR-side render via #17 affect-binding (→ affect.emit → :8390 → render), NOT a WT endpoint wait. WT #289 affect.fetch = optional mediated-read; #300 = WT client-impl guide. Expands #17 payoff: memory AND the persona pane. 2026-06-18 00:04:30 -07:00
vh 37cdef511f fix(web): de-ugly the Tier-3 persona pane — clear message instead of bare HTTP 404
persona_state hard-404s every Tier-3 (colon-id) agent by design upstream
(WT api.py:1220, "Phase 2.0 has no Tier 3 persona") — so the Persona pane
showed "persona not available (HTTP 404)" for consumer-defined characters.
loadPersona now reads error_code + renders a clear Tier-3-aware message
(she still responds in character; only the affect/OCEAN readout is gated),
with distinct text for persona_not_configured / 403 / other.

Also (snapshot): sindra switched to thoughtful-character role
(mistral-small-4-reasoning); worldtree-dev pinged re Tier-3 persona_state
roadmap (thread 01KVCR6P); #17 (bifrost-binding the chat client) teed up as
the next-context target.

v0.17.7
2026-06-18 00:00:41 -07:00
vh 835375d22b memory: snapshot — FULL COVERAGE proven (verbose persona too): sindra-probe theatrical turn promoted the user fact cleanly under Stage 2/v0.36.0 + cold-recalled @0.694; :8081 confirmed on v0.36.0; closes the verbose-persona caveat end-to-end. Operator session: :8391 wiped, ratatoskr-web up :8765 (consumer key, sindra in picker) — persona+debug only, web client does NOT bind :8391 (#17 unbuilt = no memory persistence in web chat) 2026-06-17 23:45:08 -07:00
vh 7666203722 memory: snapshot — Tier-3 memory PROVEN end-to-end live (terse-probe cold recall @0.6994, fresh history-free session); #296 arc closed: Stage 1 (v0.35.19) recallability gate validated live + bisect localized residual to verbose-persona volume, Stage 2 (v0.36.0) MERGED at worldtree-codex (user-only per-turn extraction), live-validated eval fixture pair -> #305; root-cause chain v0.35.16 emit-2-meta -> v0.35.19 emit-then-reject -> v0.36.0 fix; foot-gun: :8391 store-wipe != WT promotion-dedup reset (clean promotion smoke needs a fresh agent+end_user) 2026-06-17 21:27:17 -07:00
vh 84d8c3f65f memory: snapshot — cold-recall arc PROVEN live e2e (#297/#298 union recall; WT v0.35.16 emits scope_any into our v0.17.6 store); #296 extraction quality the isolated upstream gap (triage→worldtree-dev, both symptoms localized in-code: empty _EXTRACTOR_SYSTEM + both-roles prefilter); sindra restored (DELETE+redefine, role:character→mistral-small-4, memory:{}); learnings: Tier-3 owner-scoped, define-takes-role, promotion 4-trigger hybrid, DELETE≠drain 2026-06-17 11:15:06 -07:00
vh 4eee7c89b2 pin: bump Worldtree spec to f1b59f8 (v0.35.16) — cold recall closes end-to-end
Worldtree shipped its half of the union-recall fix: #297 (client-side
per-scope-value union recall) + #298/#299 (adopt the bifrost v0.6
scope_any/scope_all wire, v0.35.16). It now emits scope_any on the recall
path, pairing with our v0.17.6 provider — cold cross-session recall is
closed end-to-end (pending a live re-smoke against a v0.35.16 instance).

Re-vendored conversation-api-spec.md + conversation_api.contract.md;
285-commit catch-up (v0.29.0 -> v0.35.16). Diff-reviewed: no client-facing
breaking changes for our consumer.

- #211 agent-slug rename (saga->echo, actor->mask) — slugs only, we pass --agent
- #245 end_user_id persistence + memory-scope resolver (additive)
- #187/#188/#219 Tier-3 define/PATCH policy (additive); error codes stable
- bifrost binding field + ephemeral_does_not_accept_bifrost 422 now documented (#17 surface)
- docs: SPEC-PIN.md pin table + history; bifrost-self-test recall status; persistent-memory

No package version bump (docs/pin-only, no ratatoskr code change).
2026-06-17 08:24:27 -07:00
16 changed files with 1422 additions and 60 deletions
+6 -6
View File
@@ -7,17 +7,17 @@ documents the pin, the vendored artifacts, and the bump procedure.
| Field | Value |
|---|---|
| Worldtree git SHA | `562001af28d752c3a60d449c7ddd09f44fa9dc9a` |
| Worldtree HEAD message | `feat(#201): v0.29.0 — awaiting_llm_first_token SSE heartbeat` |
| Pinned on | 2026-05-26 |
| Pinned by | ratatoskr-dev (bump for #201 awaiting_llm_first_token SSE) |
| Worldtree version at pin | `v0.29.0` |
| Worldtree git SHA | `f1b59f8cd6fe41e497d0be9dad9d3110451f0d9a` |
| Worldtree HEAD message | `Merge #299: adopt bifrost v0.6 memory scope wire (scope_any/scope_all)` |
| Pinned on | 2026-06-17 |
| Pinned by | ratatoskr-dev (bump for #297/#298 — cold recall closed end-to-end) |
| Worldtree version at pin | `v0.35.16` |
## Pin history
| Date | SHA | Version | Notable deltas consumed |
|---|---|---|---|
| 2026-05-26 | `562001a` | v0.29.0 | #201 — new SSE event `awaiting_llm_first_token` (heartbeat during BuildingPrompt → CallingLLM gap, default 5s interval) |
| 2026-06-17 | `f1b59f8` | v0.35.16 | **#297 + #298/#299 — Worldtree adopts the bifrost v0.6 scope wire (emits `scope_any`/`scope_all`) + client-side per-scope-value union recall. With our v0.17.6 provider this closes cold cross-session recall end-to-end.** Catch-up bump (v0.29.0→v0.35.16). Intervening client-facing deltas reviewed, none break our consumer: #211 agent rename (`saga``echo`, `actor``mask` — slugs only); #245 `end_user_id` persistence + memory-scope resolver; #187/#188/#219 Tier-3 define/PATCH policy (additive); `bifrost` binding field + `ephemeral_does_not_accept_bifrost` 422 now documented (the #17 surface). Error codes stable; no ratatoskr code change required. |
| 2026-05-25 | `da93ca7` | v0.28.0 | #204 — new SSE event `affect_update` (current/scheduled), new endpoint `GET /agents/{id}/persona_state`, auth-model doc edits |
| 2026-05-20 | `55101e9` | v0.19.0 | initial scaffold pin |
+4 -2
View File
@@ -155,8 +155,10 @@ Branch (a), scope asymmetry — fed to #297.
into `scope_all` (AND) + `scope_any` (OR/union). Worldtree can now send the visible
scopes as a `scope_any` union (e.g. `[{end_user: smoke-user}, {end_user: smoke-user,
agent_self: ...}]`), so the subset-scoped chunk recalls via the matching OR member.
Our store implements this at parity with the v0.6 reference; **end-to-end cold recall
now waits only on Worldtree emitting `scope_any`** on the recall path (#297).
Our store implements this at parity with the v0.6 reference; Worldtree **adopted the
v0.6 wire and now emits `scope_any`** on the recall path (#297 client-side union recall
+ #298/#299 bifrost-v0.6 adoption, v0.35.16), so cold cross-session recall is **closed
end-to-end** — pending a live re-smoke against a personal instance running v0.35.16.
## Notes / foot-guns
+142 -21
View File
@@ -61,7 +61,7 @@ When you call `POST /sessions` against an agent, the authorization check that fi
### Tier 1 — foundational agents (no `:` in agent_id)
Agents bundled with Worldtree: `mimir`, `lofn`, `soong`, `forseti`, `domari`, `vili`, `actor`, `saga`, `bragi`, `leif`, `troi`, `cara`, `glados`, and any future Asgardian. The agent_id is a simple slug like `mimir` — no colon.
Agents bundled with Worldtree: `mimir`, `lofn`, `forseti`, `domari`, `vili`, `mask`, `echo`, `muninn`, and any future Asgardian. The agent_id is a simple slug like `mimir` — no colon.
> **About tiers:** Your `tier` is set on the `users` table row your API key resolves to, assigned at key-mint time (see `POST /admin/keys`). Tiers are `anonymous` (dev-mode unauthenticated), `user` (default for newly-issued keys), `free`/`pro` (subscription-shaped, not actively differentiated), and `admin`. The tier you have is visible via `GET /me`'s `tier` field. Tier-derived scopes come from `config/policies.yaml > tiers.<tier>.scopes` — there is no per-key scope override.
@@ -989,7 +989,7 @@ Create a new conversation session with an agent.
**Bifrost field validation:**
- `endpoint_url`: required, must be an HTTPS URL.
- `scope`: optional, ≤ 256 chars, opaque string passed through to the JWT payload unchanged.
- Bifrost binding is **incompatible with ephemeral (Saga) sessions** — returns 422 `ephemeral_does_not_accept_bifrost`.
- Bifrost binding is **incompatible with ephemeral (Echo) sessions** — returns 422 `ephemeral_does_not_accept_bifrost`.
- Requires the `bifrost:invoke` scope (included in the `user` tier by default).
**Response:** `201 Created`
@@ -1535,7 +1535,7 @@ for (const tc of items) {
Ephemeral templates are a second tier of agent, distinct from foundational persistent agents (Mimir, Soong, etc.). They have no persona, no memory, no tools, and no motivational context. The consumer supplies the system prompt and (optionally) the model at session-create time; that config is frozen for the session's lifetime.
**Saga** is the first ephemeral template — Norse goddess of history and chronicle, a blank-slate actor that becomes whatever the consumer's system prompt instills.
**Echo** is the first ephemeral template — a blank-slate per-session host that becomes whatever the consumer's system prompt instills.
### Discovering available templates
@@ -1547,7 +1547,7 @@ Authorization: Bearer <any valid key>
```json
{
"ephemeral_templates": {
"saga": {
"echo": {
"allowed_models": ["glm5-turbo", "glm4.7", "glm4.5-air", "granite-structured", "qwen3.6-35-a3b"],
"default_model": "glm5-turbo",
"system_prompt_max_bytes": 32768
@@ -1556,14 +1556,14 @@ Authorization: Bearer <any valid key>
}
```
`GET /capabilities` does not require `instantiate:saga` scope — any authenticated caller can read what's available before deciding to instantiate.
`GET /capabilities` does not require `instantiate:echo` scope — any authenticated caller can read what's available before deciding to instantiate.
### Creating an ephemeral session
```json
POST /sessions
{
"agent_id": "saga",
"agent_id": "echo",
"config": {
"system_prompt": "You are a careful, skeptical frame-clarifier...",
"model": "glm5-turbo"
@@ -1580,16 +1580,16 @@ POST /sessions
| `system_prompt_required` | `config.system_prompt` missing or null |
| `system_prompt_empty` | `config.system_prompt` is whitespace-only |
| `system_prompt_too_large` | `config.system_prompt` > 32768 bytes UTF-8 |
| `model_not_allowed` | `config.model` present but not in `saga_allowed_models` |
| `model_not_allowed` | `config.model` present but not in `echo_allowed_models` |
**`config.model` resolution:** When `config.model` is omitted (or `null`), the server resolves it to `saga.default_model` from `config/defaults.yaml`. The resolved value is always populated in the session snapshot; `model` is never left absent or null in the stored config.
**`config.model` resolution:** When `config.model` is omitted (or `null`), the server resolves it to `echo.default_model` from `config/defaults.yaml`. The resolved value is always populated in the session snapshot; `model` is never left absent or null in the stored config.
**Response:** Same 201 shape as foundational sessions, with two new fields:
```json
{
"session_id": "...",
"agent_id": "saga",
"agent_id": "echo",
"kind": "ephemeral",
"config": {
"system_prompt": "You are a careful, skeptical frame-clarifier...",
@@ -1601,7 +1601,7 @@ POST /sessions
}
```
**`kind` field:** `"ephemeral"` for Saga sessions, `"foundational"` for all other sessions. Present on both `GET /sessions` list items and `GET /sessions/{id}`.
**`kind` field:** `"ephemeral"` for Echo sessions, `"foundational"` for all other sessions. Present on both `GET /sessions` list items and `GET /sessions/{id}`.
### Sending messages to an ephemeral session
@@ -1617,9 +1617,9 @@ SSE, cancel, `persist_partial`, rate limits, and error shapes are bit-identical
### Scope
Creating a Saga session requires the `instantiate:saga` scope. This scope is bundled in the `user` tier. Tier `admin` inherits it via the wildcard.
Creating an Echo session requires the `instantiate:echo` scope. This scope is bundled in the `user` tier. Tier `admin` inherits it via the wildcard.
### What Saga does NOT do
### What Echo does NOT do
- No persona injection (`PersonaRegistry.inject_context` not called)
- No post-turn appraisal (`PersonaRegistry.update_after_turn` not called)
@@ -2415,7 +2415,7 @@ The `POST /sessions/{session_id}/messages` endpoint also accepts an additive `mo
- Override is per-call only. Stored `CharacterSchema.model` is NOT mutated.
- Validated against the same `available_for_characters` allowlist that gates `CharacterSchema.model` at create time (#153 INV-091).
- Override displaces the character's bound model when both are set (per-call wins).
- Override is REJECTED on ephemeral (Saga) sessions — their config is frozen at session-create per INV-161-2.
- Override is REJECTED on ephemeral (Echo) sessions — their config is frozen at session-create per INV-161-2.
**Validation:**
1. Pydantic validates `model`: optional string, non-empty after stripping whitespace.
@@ -2672,7 +2672,7 @@ The override client has a fresh 25-call reentrancy budget, independent of the se
| Condition | HTTP | `error_code` | `bifrost_error` |
|-----------|------|-------------|----------------|
| `endpoint_url` is not HTTPS | 422 | `validation_failed` | — |
| Ephemeral (Saga) session | 422 | `validation_failed` | — |
| Ephemeral (Echo) session | 422 | `validation_failed` | — |
| Missing `bifrost:invoke` scope | 403 | `auth_scope_denied` | — |
| `consumer_id` not in Heimdall or not Bifrost-registered | 502 | `bifrost_consumer_not_found` | — |
| Handshake failed (network, auth, etc.) | 502 | `bifrost_handshake_failed` | spec error code |
@@ -2753,6 +2753,61 @@ Caller must:
`agent_name` is a strict slug `[a-z][a-z0-9-]{2,63}` and immutable
after definition.
The 201 response includes an advisory `warnings` array (#219) — see
"Model-assignment warnings" under `PATCH` below.
##### Motivational layer (Phase 2.2, #187)
`motivational` is **active** as of Phase 2.2 (persona + memory activated in
Phase 2.1; only `valence` still returns `layer_deferred`). It carries the
agent's goals + fears — the same substrate Tier 1 agents author in
`agents/<name>/motivation.yaml`:
```json
"motivational": {
"goals": [
{
"id": "successful_handoff",
"type": "achievement", // maintenance | achievement | avoidance
"salience": 0.85, // [0.0, 1.0]
"description": "You succeed when the user lands with the right specialist.",
"positive_signals": ["talk to mimir"], // optional
"negative_signals": ["stay with me"] // optional
}
],
"fears": [
{
"id": "specialist_displacement",
"salience": 0.90,
"description": "You fear being mistaken for the specialist the user needs.",
"trigger_signals": ["actually mimir would"] // optional (NB: fears use trigger_signals)
}
]
}
```
Semantics:
- **Per-agent, not per-(agent, end_user).** Goals/fears are an identity trait of
the agent — identical for every end-user and session.
- **Immutable post-define.** `PATCH` with `motivational` returns 422
`field_not_mutable`. To change motivations, define a new agent.
- **Rendered into the system prompt.** The config is captured on the session's
`AgentContext` at session-create and rendered into the prompt on each turn
(only goals/fears with `salience >= 0.5` surface). Tier 3 agents bypass the
persona registry; the render reuses the Tier 1 substrate so output is
identical to an equivalent Tier 1 `motivation.yaml`.
Validation rejects malformed payloads at define-time with these 422 codes:
`motivational_id_collision` (id duplicated across goals AND fears — case-sensitive),
`motivational_goal_invalid_type`, `motivational_salience_out_of_range`,
`motivational_description_too_short` (< 20 chars after strip),
`motivational_missing_required_field` (missing id / salience / description /
goal `type`). Unknown keys at the top level or inside a goal/fear object →
`validation_failed`. v0.1 exposes only the documented fields; advanced
`GoalConfig` knobs (`priority`, `resilient`, `completion_signal`, …) are not
consumer-settable yet.
#### `DELETE /agents/<user_id>:<agent_name>` — `204 No Content`
Owner-initiated hard-delete. Bypasses the 24h grace (distinct from the
@@ -2762,11 +2817,77 @@ session bound to this agent and revokes the owner's per-resource
#### `PATCH /agents/<user_id>:<agent_name>`
Phase 2.0 minimal: only `system_prompt` and/or `model` may be patched.
Any other key (including the immutable `agent_name`, `user_id`, or
layer fields — even `null`) returns 422 `field_not_mutable` BEFORE the
DB lookup. Active sessions continue using their cached `AgentContext`;
the new values take effect at the next session-create.
**Mutable surface (Phase 2.3, #188): `system_prompt` and/or `model` only.**
PATCH re-enforces the same validation as define — the `system_prompt`
byte-cap and the `model` allowlist. Any other key returns a 422 BEFORE
the DB lookup (so an immutable-field PATCH against a missing agent still
422s, not 404s), with the error code chosen by *why* the field can't be
set:
| Field(s) | Code | Reason |
|---|---|---|
| `agent_name`, `user_id`, `agent_id` | `field_not_mutable` | Identity — fixed at creation. |
| `persona`, `motivational` | `field_not_mutable` | Shipped traits; an agent *is* its personality/goals. Change → define a new agent. |
| `memory` | `field_not_mutable` | Rejected **wholesale** — see below. |
| `valence` | `layer_deferred` | Not a shipped layer yet (matches define-time); not a frozen trait. |
Every immutable/deferred field is rejected even when its value is `null` —
supplying the key at all is the trigger.
**`memory` is wholesale-immutable.** There is no sub-field carve-out:
`stm_capacity` / `stm_token_budget` are deprecated no-ops since the STM
tier was removed (#197), `allows_world_scope` is create-time-only (memory
scope policy must be fixed before any memory is written), and
`embedder_version` is library-pinned. Note the deliberate asymmetry with
define: `POST /agents/define` accept-and-ignores deprecated `stm_*`
(201 + deprecation warning), but `PATCH {"memory": {...}}` rejects the
whole field with `field_not_mutable`. When a real long-term-memory tuning
dial ships, its PATCH semantics will be specified at that time.
**Active sessions are unaffected.** A PATCH never mutates an in-flight
session's cached `AgentContext`; new `system_prompt` / `model` values take
effect only at the next session-create.
**Audit.** A successful PATCH emits one `agents.patch` event whose
`changes` detail records before/after per mutated field: `model` as literal
`{before, after}` values, and `system_prompt` as `{before_bytes,
after_bytes}` only — the raw prompt text is never written to the audit log
(potential PII).
**Model-assignment warnings (#219).** A `model` swap is **not blocked** for
capability or context-window compatibility, but PATCH (and `define`) attach an
advisory `warnings` array to the response — see the shared subsection below.
Correctness for over-budget prompts remains the runtime `context_overflow`
guard; the warnings are an early, best-effort heads-up.
##### Model-assignment warnings (`define` + PATCH)
Both `POST /agents/define` (201) and `PATCH /agents/<id>` (200) include a
`warnings` array in the response body (always present; `[]` when none). It is
**advisory and non-blocking** — never a rejection — and appears only on these
two mutation responses, not on `GET /agents/<id>`. Each entry is
`{code, severity, message, details}`. The closed code set:
| code | severity | when |
|---|---|---|
| `model_context_window_unknown` | `info` | The assigned model has no recorded context window (`0`/absent in the registry). |
| `model_context_window_smaller` | `warning` | Both prior and new model have known windows and the new one is smaller. `details: {before, after}`. |
| `model_capability_downgrade` | `warning` | The new model **explicitly** advertises fewer capabilities than the prior — drops `tools`, `vision`, or `audio`. `details: {dropped: [...]}`. |
Semantics:
- **`define`** has no prior model, so only `model_context_window_unknown` can
fire there. **PATCH** computes warnings only when the payload changes `model`
(a `system_prompt`-only PATCH returns `warnings: []`); the comparison is
against the resulting model.
- Capability warnings are **conditional by nature**: a Tier 3 agent row does
not record whether it uses tools/vision/audio (tools arrive per-session via
Bifrost), so the message is phrased "if your sessions rely on these…". A
downgrade is reported only when both models carry explicit registry metadata.
- Messages never claim a hard failure. The stored `system_prompt` cap is a
**byte** limit (32 KiB), independent of any model's token budget — it is not
a fit guarantee. A too-large prompt for the chosen model still surfaces at
runtime as `context_overflow`.
#### `POST /sessions` — Tier 3 routing
@@ -2860,8 +2981,8 @@ endpoint isn't reachable.
| `agent_name_invalid` | 422 | `agent_name` violates `[a-z][a-z0-9-]{2,63}`. |
| `system_prompt_too_large` | 422 | `system_prompt` > 32 KiB. |
| `model_not_available` | 422 | `model` not in `providers.yaml`. |
| `layer_deferred` | 422 | One of `persona` / `motivational` / `valence` / `memory` set. |
| `field_not_mutable` | 422 | PATCH carries an immutable key (any value, even `null`). |
| `layer_deferred` | 422 | `valence` set on define OR PATCH (the only still-deferred layer; persona/motivational/memory activated in Phase 2.1/2.2). |
| `field_not_mutable` | 422 | PATCH carries an immutable key — identity (`agent_name`/`user_id`), `persona`, `motivational`, or `memory` (any value, even `null`). `valence` → `layer_deferred` instead. |
| `end_user_id_required` | 422 | Tier 3 session-create without a non-empty `end_user_id`. |
| `tier3_user_id_unsupported` | 403 | Caller's `ctx.user_id` not slug-safe. |
| `auth_scope_denied` | 403 | Missing `agents.define` or wrong owner. |
+309 -13
View File
@@ -137,6 +137,68 @@ Sessions are persistent via SQLite. On server restart, existing sessions are
loadable from the store (lazy-loaded on first access). In-memory cache is
rebuilt on demand, not at startup.
## Memory-partition scope (#245 / ADR-0011)
`end_user_id` is the per-end-user memory partition key (distinct from `user_id`,
the API-key owner). It is REQUIRED at session-create for Lofn (Tier-1) and Tier-3
agents and must survive a store reload, because "remember me next session" is by
definition a reload. Memory partition resolution flows through ONE resolver that
cannot hand an authenticated session the shared `local_dev` partition.
- **INV-245-1 (end-user-id-durable)**: `end_user_id` is persisted as a `sessions`
table column at create and rehydrated onto the `ConversationSession` on every
cache-miss load (`get_session`). A session loaded from the store carries the
same `end_user_id` it was created with. Pre-migration rows read as `None`.
- **INV-245-2 (end-user-id-threaded-all-tiers)**: the `POST /sessions` handler
forwards `body.end_user_id` to `create_session` for EVERY agent, not only
Tier-3. (The pre-fix `if tier3_agent_context is not None else None` conditional
dropped it for Lofn despite the create gate requiring it.)
- **INV-245-3 (no-authenticated-local-dev)**: the two MEMORY partition sites —
auto-recall (read) and the ContextPromotion producer (write) — resolve via
`memory_scope_for_session`. An authenticated, memory-bearing session (one not
carrying the explicit `local_dev` sentinel) NEVER resolves to `local_dev`; a
missing `end_user_id` raises `MemoryScopeError`, and because both sites are
best-effort (recall is fire-and-forget; the producer is `_run_promotion_safe`),
the caller skips memory — it never silently writes to the shared partition.
- **INV-245-5 (persona-plane-corrected-by-persistence)**: the three PERSONA-plane
sites (`inject_context`, `get_state`, `update_after_turn` — ADR-0008 mood/PAD/
valence) keep their `session.end_user_id or "local_dev"` form but are on the
main turn path where a raise would break the turn. They are corrected by
INV-245-1/2: once `end_user_id` is persisted + threaded, the fallback yields a
real partition for authenticated sessions and `local_dev` only for the explicit
terminal path. Unifying the persona plane under the resolver (with main-path
error semantics) is follow-up, tracked with the #246-adjacent hardening.
- **INV-245-4 (terminal-explicit-local-dev)**: the internal terminal transport
creates its sessions with `end_user_id="local_dev"` explicitly. `local_dev` is
reached only by this positive assertion, never by omission. (External API
callers passing `local_dev` are still rejected per #216.)
```contract
FN memory_scope_for_session(session) -> MemoryScope
BRIEF: The single authority resolving a session to its memory partition scope.
Returns a typed MemoryScope(scope_type, scope_id); scope_type ∈
{local_dev, end_user, room, tenant} (only local_dev + end_user active in
v1; room/tenant reserved for ADR-0010). Cannot yield local_dev for an
authenticated session.
PRE: [PRE-001 soft] callers have already gated ephemeral / consumer_defined
sessions out (those skip memory before resolution)
POST: [POST-001 return_value] end_user_id == "local_dev" -> MemoryScope("local_dev", "local_dev")
POST: [POST-002 return_value] end_user_id truthy and != "local_dev" -> MemoryScope("end_user", end_user_id)
POST: [POST-003 exception] end_user_id is None/empty -> raise MemoryScopeError (NEVER local_dev)
ERRORS:
MemoryScopeError -> caller skips memory (best-effort) + emits an audit/log line; turn proceeds
STEPS:
1. [setup] read euid = session.end_user_id
2. [branch] euid == "local_dev" -> RETURN MemoryScope("local_dev", "local_dev") (terminal sentinel)
3. [branch] euid truthy -> RETURN MemoryScope("end_user", euid)
4. [error_handler] else (None/empty) -> RAISE MemoryScopeError (never silently local_dev)
TESTS:
end_user_partition [happy,tracer]: session end_user_id="alice" -> MemoryScope("end_user","alice")
terminal_local_dev [boundary]: session end_user_id="local_dev" -> MemoryScope("local_dev","local_dev")
authenticated_none_raises [boundary]: foundational session end_user_id=None -> raises MemoryScopeError, NOT local_dev
isolation_roundtrip [happy]: create_session(end_user_id="alice") write + clear cache + reload + recall isolates from a "bob" session; negative-assert no local_dev write
```
```contract
FN ConversationService.startup() -> None
BRIEF: Discover agents, build per-agent contexts, initialise shared infrastructure
@@ -1658,13 +1720,13 @@ Ephemeral templates are a new agent kind that bypass persona, memory, tools, and
**Invariants added by issue #161:**
- **INV-161-1 (ephemeral-template-bypass)**: For sessions where `session.ephemeral_config is not None`, `PersonaRegistry.inject_context` is NOT called pre-turn; `PersonaRegistry.update_after_turn` is NOT called post-turn; valence side-channel is NOT called; tool list passed to provider is `[]`.
- **INV-161-2 (frozen-session-config)**: Once a session is created with an `ephemeral_config` snapshot, subsequent mutations to `agents/saga/config.yaml`, `config/providers.yaml → saga_allowed_models`, or `config/defaults.yaml → saga.default_model` do NOT affect that session's per-turn `system_prompt` or `model`.
- **INV-161-2 (frozen-session-config)**: Once a session is created with an `ephemeral_config` snapshot, subsequent mutations to `agents/echo/config.yaml`, `config/providers.yaml → echo_allowed_models`, or `config/defaults.yaml → echo.default_model` do NOT affect that session's per-turn `system_prompt` or `model`.
- **INV-161-3 (no-tools-for-ephemeral)**: Tool list passed to the provider for an ephemeral session is `[]` regardless of any `tools:` block in the template's config.yaml.
- **INV-161-4 (foundational-flow-unchanged)**: For sessions where `session.ephemeral_config is None`, the per-turn path is bit-identical to pre-#161 — same system_prompt loading, same persona injection, same tool list, same audit-log shape.
- **INV-161-5 (config-required-for-ephemeral-create)**: `POST /sessions` against an ephemeral template MUST reject the request with 422 if `config` is missing or fails any validation step.
- **INV-161-6 (model-allowlist-enforcement)**: `config.model`, when supplied, MUST be in `saga_allowed_models` at session-create time. When omitted, server resolves to `saga.default_model` (startup-validated to be in the allowlist).
- **INV-161-6 (model-allowlist-enforcement)**: `config.model`, when supplied, MUST be in `echo_allowed_models` at session-create time. When omitted, server resolves to `echo.default_model` (startup-validated to be in the allowlist).
- **INV-161-7 (full-prompt-in-audit)**: Session-create audit entries for ephemeral sessions include `tier: 2` and `ephemeral_config` (full JSON).
- **INV-161-8 (cross-user-isolation)**: A Saga session created by user A is invisible to user B — `GET /sessions/{id}` returns 404.
- **INV-161-8 (cross-user-isolation)**: An Echo session created by user A is invisible to user B — `GET /sessions/{id}` returns 404.
- **INV-161-9 (foundational-rejects-config)**: `POST /sessions { agent_id: "<foundational>", config: {...} }` returns 422 with `error_code: "foundational_does_not_accept_config"`.
- **INV-161-10 (capabilities-public-shape)**: `GET /capabilities` is callable by any authenticated key. The response has `ephemeral_templates` at top-level.
- **INV-161-11 (template-kind-immutable-at-runtime)**: The `kind` field on a loaded `AgentContext` is set once at startup and never mutated.
@@ -1673,16 +1735,16 @@ Ephemeral templates are a new agent kind that bypass persona, memory, tools, and
| code | HTTP | trigger |
|---|---|---|
| `ephemeral_requires_config` | 422 | saga session without `config:` |
| `ephemeral_requires_config` | 422 | echo session without `config:` |
| `foundational_does_not_accept_config` | 422 | foundational agent with `config:` |
| `system_prompt_required` | 422 | `config.system_prompt` missing or null |
| `system_prompt_empty` | 422 | `config.system_prompt` whitespace-only |
| `system_prompt_too_large` | 422 | > 32768 bytes UTF-8 |
| `model_not_allowed` | 422 | model not in `saga_allowed_models` |
| `model_not_allowed` | 422 | model not in `echo_allowed_models` |
**New `AgentContext` fields:** `kind: str = "foundational"`, `saga_allowed_models: list | None`, `saga_default_model: str | None` — populated for ephemeral templates, `None` for foundational agents.
**New `AgentContext` fields:** `kind: str = "foundational"`, `echo_allowed_models: list | None`, `echo_default_model: str | None` — populated for ephemeral templates, `None` for foundational agents.
**Startup failfast:** server refuses to start if `agents/saga/config.yaml` is missing/malformed OR `saga.default_model` is not in `saga_allowed_models`. Raises `ConfigurationError` before binding any port.
**Startup failfast:** server refuses to start if `agents/echo/config.yaml` is missing/malformed OR `echo.default_model` is not in `echo_allowed_models`. Raises `ConfigurationError` before binding any port.
**Function-level contracts for issue #161** are documented in `docs/contracts/issues/161.contract.md`.
@@ -1704,7 +1766,7 @@ Bifrost allows consumers to expose tools to Worldtree agents. `POST /sessions` a
- **INV-160-1 (handshake-at-create)**: When `POST /sessions` carries `bifrost: {endpoint_url, ...}`, the handshake completes BEFORE the 201 response. No "create session, handshake later" path in v0.1. Verifiable via test: handshake-failing endpoint → 502; session not in store.
- **INV-160-2 (one-connection-per-session)**: Each Bifrost-bound session owns exactly one MCP connection. Two sessions binding to the same `endpoint_url` open two independent connections. No pooling, no sharing.
- **INV-160-3 (saga-incompatible)**: A session cannot be both ephemeral (Saga, `kind: "ephemeral"`) AND Bifrost-bound. Session-create rejects with 422 `ephemeral_does_not_accept_bifrost`. Verifiable: `POST /sessions { agent_id: "saga", config: {...}, bifrost: {...} }` → 422.
- **INV-160-3 (echo-incompatible)**: A session cannot be both ephemeral (Echo, `kind: "ephemeral"`) AND Bifrost-bound. Session-create rejects with 422 `ephemeral_does_not_accept_bifrost`. Verifiable: `POST /sessions { agent_id: "echo", config: {...}, bifrost: {...} }` → 422.
- **INV-160-4 (jwt-bound-to-session-expiry)**: JWT TTL is bound to session expiry — far-future `expires_at` for sessions without a fixed TTL. Re-mint happens only when a re-handshake fires (connection-loss recovery). No standalone JWT-staleness check.
- **INV-160-5 (reentrancy-25-per-turn)**: At most 25 successful Bifrost tool invocations per agent turn. The 26th returns `bifrost.reentrancy_cap_exceeded` without contacting the consumer. Counter resets per turn via `BifrostClient.reset_turn_counter()`. Enforced inside `BifrostClient.invoke_tool`.
- **INV-160-6 (tool-list-cached-per-session)**: Bifrost tools are fetched once at handshake and cached on `ConversationSession.bifrost_tools`. Per-turn dispatch reads from the cache; never re-fetches mid-session except on connection-loss recovery.
@@ -1751,7 +1813,7 @@ class BifrostEndpointOverride(BaseModel):
1. HTTPS URL check — Pydantic field validator; 422 on miss.
2. `bifrost:invoke` scope check — same as session-bound path; 403 on miss.
3. Ephemeral session rejection — 422 `ephemeral_does_not_accept_bifrost` when session is Saga (extends INV-160-3).
3. Ephemeral session rejection — 422 `ephemeral_does_not_accept_bifrost` when session is Echo (extends INV-160-3).
4. Heimdall consumer lookup — 502 `bifrost_consumer_not_found` on miss or unregistered.
5. Instantiate a new `BifrostClient` with the override consumer's algorithm + key; set `_jwt_ttl_seconds = 60`.
6. `await override_client.connect()` — 502 `bifrost_handshake_failed` on failure.
@@ -1789,7 +1851,7 @@ In the `finally` block, `await override_client.disconnect()` is called unconditi
The conversation API grows a three-tier agent model. Tier 1 is the
foundational set (Mimir, Bragi, Leif, ...) wired at startup. Tier 2 is
the ephemeral template surface (Saga). Tier 3 is the consumer-defined
the ephemeral template surface (Echo). Tier 3 is the consumer-defined
class addressed by `<user_id>:<agent_name>` and stored in Heimdall's
SQLite `consumer_agents` table.
@@ -1813,9 +1875,13 @@ SQLite `consumer_agents` table.
- **INV-181-5 (agent-name-immutable, Phase 2.0 scope)**: PATCH rejects
any payload that includes `agent_name`, returning 422
`field_not_mutable` BEFORE the DB lookup.
- **INV-181-6 (layer-immutable-in-patch, Phase 2.0 scope)**: PATCH
rejects payloads carrying any of `persona`, `motivational`,
`valence`, `memory` even when set to `null`.
- **INV-181-6 (layer-immutable-in-patch, Phase 2.0 scope; AMENDED #188)**:
PATCH rejects payloads carrying any of `persona`, `motivational`,
`memory` even when set to `null`, returning `field_not_mutable`.
**Amended by #188 (Phase 2.3):** `valence` was moved out of this
`field_not_mutable` set — it now returns `layer_deferred` (see
INV-188-1), because valence is a not-yet-shipped layer, not a frozen
trait. `memory` is rejected wholesale (see INV-188-2).
- **INV-181-7 (owner-delete-hard, Phase 2.0 scope)**: `DELETE
/agents/<id>` is a hard-delete; bypasses the 24h grace.
- **INV-181-8 (cascade-key-scoped, Phase 2.0 scope)**: Key revocation
@@ -1881,6 +1947,79 @@ SQLite `consumer_agents` table.
through `_publish`, so SSE resume / replay handles them with no
special case.
## Amendment — Suspended-tier license-state gate (issue #174, INV-174-1..9)
Adds a `suspended` tier with empty scope set to drive license-expiry
transitions without destroying user state. Endpoint
`POST /admin/users/{user_id}/tier` mutates the tier; the
`_http_exception_handler` rewrites `AUTH_SCOPE_DENIED` →
`USER_SUSPENDED` for any 403 raised against a non-anonymous caller with
an empty scope-set (the suspended-tier defining property). Ships in
v0.29.1.
- **INV-174-1 (closed tier vocabulary)**: `POST /admin/users/{user_id}/tier`
validates `body.tier` against the hard-coded set `{anonymous, user, free,
pro, admin, suspended}`. Out-of-set values return 422 `invalid_tier`.
Vocabulary is NOT derived from `policies.yaml` at runtime — a typo in
YAML must not silently expand the accepted set.
- **INV-174-2 (admin-only mutation)**: endpoint requires
`admin.users.write.tier_change` scope. Listed explicitly in admin
tier's scope set in `policies.yaml` for grep-discoverability (admin
also carries `*` umbrella).
- **INV-174-3 (tier mutation primitive)**:
`UserStore.update_user_tier(user_id, new_tier) -> User` is the storage
primitive. Raises `LookupError` for unknown user_id (endpoint converts
to 404 `user_not_found`).
- **INV-174-4 (suspended scope-set is exactly empty)**:
`policies.yaml.tiers["suspended"].scopes == []`. The empty set is what
makes the auth-denial work for free; the
`_http_exception_handler` rewrite uses
`ctx.user_id != "anonymous" and not ctx.scopes` as the
suspended-detection heuristic since `SecurityContext` deliberately
excludes `tier` (per `core/integration/types.py:64`).
- **INV-174-5 (uniform suspended error code via exception handler)**:
The `_http_exception_handler` (registered for `StarletteHTTPException`)
intercepts every 403 with `error_code: auth_scope_denied`; if the
request's stashed `SecurityContext` has an empty scope-set (and
non-anonymous user_id), it rewrites the detail to
`{error_code: "user_suspended", message: "Account is suspended."}`.
Single seam — covers every existing and future scope-deny site
without per-endpoint refactor. The ctx is stashed by
`get_security_context` on `request.state.security_context`.
- **INV-174-6 (/me carve-out)**: `/me` does NOT call `authorize()` and
therefore never raises `AUTH_SCOPE_DENIED`. Suspended users with
empty scopes reach the /me handler normally and see
`{user_id, tier: "suspended", scopes: [], ...}`. Adding a scope check
to /me without preserving the suspended-tier visibility would be a
contract violation — the carve-out is structural, not coded.
- **INV-174-7 (audit emission)**: every tier-change attempt emits
`conversation_api:admin:user:tier_changed` via `_audit_admin_action`
with `actor_user_id`, `target_user_id`, `outcome ∈
{success, denied}`, and `extra = {from_tier, to_tier, reason}` for
successes; `extra = {reason: <reason_code>}` for denials
(`invalid_tier`, `user_not_found`).
- **INV-174-8 (reversibility via audit replay)**: the user record does
NOT carry a `previous_tier` column. Restoration of a suspended user
requires reading the audit log to find the most recent
`tier_changed` event with `to_tier="suspended"` and replaying its
`from_tier` as the new target. Operational responsibility of SEA's
billing integration; Worldtree provides only the read (audit log) and
write (endpoint) surfaces.
- **INV-174-9 (no cross-tier session invalidation)**: a tier change for
a user with active SSE turns in flight does NOT cancel those turns.
The next request after the tier change picks up the new scope-set;
in-flight streams complete under the old tier. If SEA needs
immediate-cutoff semantics, that requires `disable_user`-style
hard-revoke, not a tier change.
## Amendment — AwaitingLLMFirstToken heartbeat (issue #201, INV-201-1..7)
Adds a periodic SSE heartbeat event during the gap between
@@ -2027,3 +2166,160 @@ Lofn introduces zero net-new persistence surface. No table, no
column, no Mimir KB collection. No new audit-event types. Existing
session-create / session-revoke audit covers Lofn the same way it
covers Mimir / Forseti.
## Amendment — Tier 3 motivational layer (issue #187, Phase 2.2)
Activates the `motivational` layer field on `POST /agents/define`, narrowing the
Phase 2.0 `layer_deferred` rejection (INV-181-3) to `valence` only. Full FN-level
spec at `docs/contracts/issues/187.contract.md`.
- **INV-187-1 (motivational-activated)**: `POST /agents/define` accepts a non-null
`motivational` object `{goals, fears}`; `_tier3_validate_layer_fields` rejects
only `valence` now. (Persona + memory were activated in Phase 2.1 / #189.)
- **INV-187-2 (define-validation)**: `validate_motivational_define_payload` enforces
the documented 422 codes — `motivational_id_collision` (case-sensitive, across
goals AND fears), `motivational_goal_invalid_type`,
`motivational_salience_out_of_range`, `motivational_description_too_short`
(< 20 chars after strip), `motivational_missing_required_field`. Unknown top-level
OR nested (per goal/fear) keys → `validation_failed` (sub-models extra-forbid).
Stricter than the Tier 1 `validate_motivation` (which only warns on short text).
- **INV-187-3 (per-agent-scope)**: motivational is per-agent, NOT
per-(agent, end_user) — stored once on the row, identical across all end-users.
- **INV-187-4 (immutable-in-patch)**: `PATCH` with `motivational` → 422
`field_not_mutable` (already covered by INV-181-6's `_IMMUTABLE_FIELDS` gate).
- **INV-187-5 (tier3-render-bridge)**: Tier 3 agents are NOT registered with the
`persona_registry`; the stored config rides on the per-session `AgentContext`
(`motivational_config`) and is rendered into the prompt per-turn in `stream_turn`
via `_append_motivational_context_section`, before the memory-context section.
- **INV-187-6 (fear-signal-shape)**: fears carry `trigger_signals`; goals carry
`positive_signals` + `negative_signals` (matches the `GoalConfig`/`FearConfig`
substrate).
- **INV-187-7 (tier-uniformity)**: the render reuses `core.persona.goals.load_goals`
+ `render_motivational_context`, so a Tier 3 motivational config produces a
byte-identical block to an equivalent Tier 1 `motivation.yaml`.
- **INV-187-8 (storage)**: persisted in `consumer_agents.tier3_layers_json` under
the `"motivational"` key; round-trips via `ConsumerAgent.motivational`; null/omitted
→ `None` (no fabricated defaults; no migration).
### Audit
`agents.define` audit `extra` gains `presence_motivational: bool` alongside
`presence_persona` / `presence_memory`.
## Amendment — Tier 3 PATCH mutability policy (issue #188, Phase 2.3)
Settles which Tier 3 agent fields are editable post-define. #197 deleted the
STM tier between this issue's filing (2026-05-19) and its implementation, so the
"mutable memory dials" the original issue envisioned no longer exist; the policy
collapses to: `system_prompt` + `model` mutable, everything else fixed, with
`valence` distinguished from the immutable traits by error code. No new
endpoint, no new storage, no new invariant philosophy — a clarification +
error-code alignment + audit enrichment over the Phase 2.0 PATCH baseline.
- **INV-188-1 (valence-deferred-in-patch)**: `PATCH /agents/<id>` carrying a
`valence` key (any value, including `null`) → 422 `layer_deferred` with
`field: "valence"`, matching define-time (INV-181-3). Rationale: valence is
a layer that does not exist yet, not a real-but-frozen trait; `layer_deferred`
is the truthful reason and gives consumers ONE code for "valence unavailable"
across both define and PATCH. The check precedes the DB lookup (INV-181-5/6
ordering), so a `valence` PATCH against a missing agent still 422s, not 404s.
- **INV-188-2 (memory-wholesale-immutable-in-patch)**: `PATCH` carrying a
`memory` key → 422 `field_not_mutable` with `field: "memory"`, rejected at the
WHOLE-field level. No sub-field carve-out exists: `stm_capacity` /
`stm_token_budget` are deprecated no-ops post-#197, `allows_world_scope` is
create-time-only (toggling it after memory is written breaks scope-visibility
invariants — memory scope policy must be fixed before any memory is written),
and `embedder_version` is library-pinned. A real LTM tuning dial would warrant
a deliberate per-sub-field PATCH contract at that time; pre-splitting for dead
fields is not done. NOTE the deliberate define/PATCH asymmetry: `define`
accept-and-ignores deprecated `stm_*` (201 + DeprecationWarning per
INV-197-19), but `PATCH memory:{...}` rejects wholesale (422). Acceptable
transitional artifact; disappears when the shims are removed.
- **INV-188-3 (patch-audit-before-after)**: a successful `agents.patch` audit
event's `extra.changes` records before/after for each mutated field —
`model: {before, after}` (literal values; allowlist enum, not PII) and
`system_prompt: {before_bytes, after_bytes}` (byte-length only; raw prompt
content is excluded as potential PII, consistent with `emit_consumer_agent_event`'s
exclusion rule). `changes` contains only keys for fields actually present in
the PATCH payload. `patched_fields` (the Phase 2.0 name list) is retained.
- **INV-188-4 (mutable-surface-unchanged)**: the mutable surface stays exactly
`system_prompt` + `model` (per INV-181 Phase 2.0). PATCH re-enforces the
define-time `system_prompt` byte-cap and `model` allowlist. #188 does NOT add
model-swap capability/context-window validation — that gap (a swap to a
smaller-context or non-tool model with no re-check of the existing prompt) is
tracked as a separate follow-up (#219), not folded here.
## Amendment — model-assignment advisory warnings (issue #219)
`POST /agents/define` and `PATCH /agents/<id>` attach a best-effort, **non-
blocking** `warnings` array to their 2xx response when the assigned `model`
carries metadata risk (smaller context window, unknown window, or an explicit
capability downgrade). This is advisory-only by deliberate design: hard
rejection was rejected (Heid panel + operator, 2026-05-29) because model
metadata coverage is partial (`context_window` is 0/unknown for several
allowlisted models; `supports_tools` defaults true), the stored `system_prompt`
cap is bytes not tokens, Tier 3 agent rows store no tool/modality usage (tools
arrive per-session via Bifrost, so any capability concern is inherently
conditional), and runtime already classifies the real failure as
`CONTEXT_OVERFLOW`. The warning is a receipt-note for the owner who just made a
deliberate change, not a correctness gate.
- **INV-219-1 (advisory-not-blocking)**: neither define nor PATCH ever rejects
on context-window or capability grounds. The allowlist check
(`model_not_available`) and `system_prompt` byte-cap are the only model-
related *rejections*; everything in #219 is a warning on an otherwise-2xx
response. Correctness for over-budget prompts remains the runtime
`CONTEXT_OVERFLOW` guard.
- **INV-219-2 (bounded-warning-codes)**: the closed code set is exactly —
`model_context_window_unknown` (severity `info`): the assigned model's
registry `context_window` is `0`/absent; `model_context_window_smaller`
(severity `warning`): prior and new model both have known windows and
new < prior (`details: {before, after}`); `model_capability_downgrade`
(severity `warning`): the new model EXPLICITLY drops a capability the prior
model advertised — `supports_tools`, `vision`, or `audio` (`details:
{dropped: [...]}`). No token-aware "prompt won't fit" code — deferred until
tokenizer-aware estimation exists; messages never claim a hard fit/failure.
- **INV-219-3 (when-evaluated, resulting-pair)**: warnings are computed
whenever a model is *assigned*. At define, always (prior = None → only
`model_context_window_unknown` can apply, since the comparative codes need a
prior). At PATCH, only when the payload carries a `model` key whose value
differs from the stored model (prior = stored model); a PATCH without `model`
(e.g. `system_prompt`-only) emits no model warnings. The comparison is always
against the *resulting* model.
- **INV-219-4 (capability-downgrade)**: a `model_capability_downgrade` fires
only when BOTH prior and new models resolve to registry `ModelInfo` AND the
new model's *effective* capability flags lack one the prior advertised
(`supports_tools`, `vision`, or `audio`). The "both resolve" guard is the
false-positive defense — an unresolvable model on either side yields no
downgrade claim. Beyond that, comparison uses the registry's **effective**
flags, which is asymmetric by capability because the data model collapses
absent-to-default and does not preserve a "was this declared?" bit:
- `supports_tools` defaults **true** (`ModelInfo` / `_build_model_info`), so
a tools-drop requires the new catalog entry to set `supports_tools: false`
*explicitly* — omission never triggers it.
- `vision` / `audio` default **false** (`ModelCapabilities`), so a drop is
detected whenever the prior advertised the capability and the new model does
not carry it — whether the new entry says `false` explicitly OR omits it.
This is the deliberate conservative reading: an undeclared modality is
treated as unsupported. (A vision-capable model with sloppy metadata that
omits its `vision` flag would thus be reported as a downgrade; the remedy is
to declare the flag in the catalog, not to suppress the advisory.)
Message phrasing is conditional ("if your sessions rely on these, e.g. Bifrost
tools, they may be rejected") — the agent row does not record whether tools or
modalities are actually used, so every capability warning is advisory by
nature.
- **INV-219-5 (inline-response-shape)**: the `warnings` array is added inline to
the define (201) and PATCH (200) response bodies — the existing flat
`ConsumerAgentResponse` dict gains a `warnings` key (always present, `[]` when
none). It is NOT added to the shared `ConsumerAgentResponse` pydantic model
nor to `GET /agents/<id>` — only the two mutation handlers merge it into their
returned dict, keeping persisted fields and the read path unchanged. Each
entry is `{code, severity, message, details}`.
- **INV-219-6 (single-helper)**: a single pure helper
`compute_model_swap_warnings(*, prior_model: str | None, new_model: str,
registry)` is the only source of warning logic; both define and PATCH call
it. It tolerates unresolvable specs / `None` `ModelInfo` / `context_window`
`0` by treating them as "unknown" (emitting the unknown-window info code where
applicable, never raising). Metadata improvements over time sharpen the
warnings with no API or signature change.
+70 -10
View File
@@ -41,9 +41,51 @@ model output is untrusted); upstream API key stays server-side (INV-003).
## Current state / in-flight
_As of 2026-06-16:_
_As of 2026-06-18:_
**LATEST (2026-06-16 PM) — BIFROST REPINNED 0.7.0→0.8.0 (wire v0.5→v0.6).** The
**LATEST (2026-06-18) — TIER-3 MEMORY PROVEN END-TO-END LIVE; #296 FIX SHIPPED (Stage 1 + Stage 2).**
The session's opening goal — "how far from Tier-3 agents we host with their own memories?" — is
ANSWERED: a hosted agent recalled a user fact across a COLD (history-free) session, live. Full chain:
seed → promotion → our v0.17.6 `:8391` store (upsert) → cold session → WT `scope_any` recall (1 hit @
cosine 0.6994) → model answered "Dark chocolate with sea salt." Proven with `ratatoskr:terse-probe`
(plain persona, end_user `terse-proof`) vs personal WT v0.35.19.
The whole #296 arc closed this session:
- **Stage 1** (v0.35.19, recallability admission gate + real `_EXTRACTOR_SYSTEM`) VALIDATED LIVE for
normal-volume turns — clean first-person distillate (`distiller_model_id="identity"`), recalls @0.70.
- **Bisect verdict:** residual = verbose-persona VOLUME crowd-out (symptom 1). terse-probe promotes the
fact cleanly; sindra's theatrical turn drowns it → v0.35.16 emits 2 meta-descriptions (a3466fab confirmed),
v0.35.19 gate catches + hard-rejects (emit-then-reject, fail-closed).
- **Stage 2** (v0.36.0, MERGED on demo) = user-only one-call-per-turn extraction, the STRUCTURAL fix for
the verbose drop; hard-linguistic layer at #305. Live-validated eval fixture pair handed to worldtree-dev
(terse-proof POSITIVE chunk + choc-v2/sindra NEGATIVE).
**FULL COVERAGE PROVEN (the OPEN item, now DONE):** re-smoked the VERBOSE persona — `ratatoskr:sindra-probe`
(sindra's actual theatrical prompt, end_user `verbose-v2`, FRESH agent to dodge the WT promotion-dedup) against
`:8081` **v0.36.0**: the high-volume theatrical turn promoted the USER FACT cleanly (not a meta-description) and a
COLD history-free session recalled it @ 0.694 — "Dark chocolate. With sea salt." So `:8081` is on v0.36.0 and
verbose characters remember too. All session commits + tags PUSHED to origin (v0.17.6, spec repin v0.35.16,
snapshots; tags v0.17.4/.5/.6).
**NOW (operator session):** `:8391` store WIPED clean; `ratatoskr-web` UP on `0.0.0.0:8765`
(LAN `http://10.100.10.50:8765`, consumer key — owner-matches sindra, end_user `vuong`, `ratatoskr:sindra` in the
picker). Sindra switched to the **`thoughtful-character` role → `mistral-small-4-reasoning`** (via DELETE+redefine;
she chats in full persona on it). **"No persona" 404 diagnosed = Worldtree limitation, NOT ours:** `persona_state`
hard-404s every Tier-3 (colon-id) agent by design (`api.py:1220` "Phase 2.0 has no Tier 3 persona", still on
v0.36.0) — a persona block in the define does NOT help (404 fires before the row read). Pinged worldtree-dev re:
the Tier-3 persona_state roadmap (thread `01KVCR6P…`). De-uglied our web persona pane (`index.html` `loadPersona`)
to render a clear Tier-3 message instead of a bare "HTTP 404". **CAVEAT still stands: the web client does NOT bind
to `:8391`/`:8390` (#17 unbuilt) → web chat = persona + debug only; no memory persistence, no affect telemetry.**
**NEXT (fresh context): #17 — bifrost-binding the chat client.** The single unblock for BOTH (a) memory persistence
in the web/TUI/CLI chat (Sindra remembering in a real session, not just scripts) AND (b) feeding the persona pane
from OUR `:8390` affect store — `affect.emit` PAD/valence, ours to render per ADR-0009 (NOT a WT persona_state to
wait for; see the reframe in Recent decisions). Contract `docs/contracts/issues/17.contract.md` is WRITTEN +
Heid-reviewed + drift-clean; **TDD is the next step** — slice 1 = the `create_session` bifrost-binding primitive
(consumer-key per-request bearer + missing-key precondition + 502→`BifrostHandshakeFailed`, respx-mocked), then
`endpoint_for_plane` → dispatch-layer op-feed → CLI/TUI/web triggers → live smoke. althing monitor armed.
**(2026-06-16 PM) — BIFROST REPINNED 0.7.0→0.8.0 (wire v0.5→v0.6).** The
memory `search` scope filter was split into `scope_all` (AND/intersection) +
`scope_any` (OR/union over a LIST of conjunctive scopes) — bifrost #11, the canonical
fix for the #295/#297 silent-zero AND foot-gun. Our store + contract (v1.2) + tests
@@ -52,12 +94,11 @@ reimplemented to parity with the v0.6 reference `_matches_scope`/`_validate_scop
test + the parity-vs-reference test through the real 0.8.0 `dispatch_memory_call`.
Memory provider BOUNCED onto 0.8.0 (`:8391`, fresh empty `memory.db` — the prior
5-chunk #296 corpus was WIPED, operator confirmed "nothing of value", SUPERSEDES the
"KEEP PINNED" note below). **End-to-end cold recall now waits only on Worldtree
EMITTING `scope_any` on its recall path (#297, upstream).** Affect plane untouched
(split is memory-only); affect provider still on its 0.7.0-loaded process (bounce
optional — affect wire unchanged at 0.8.0). NOT yet committed; patch bump v0.17.6
pending operator commit approval. **#17 contract carries stale `scope_filter` /
`_scope_matches`-AND references — fix when #17 TDD starts.**
"KEEP PINNED" note below). Shipped as v0.17.6 (`96d61a4`, tag v0.17.6); the #17
contract's stale `scope_filter`/`_scope_matches`-AND references were synced in the same
commit. Affect plane untouched (split is memory-only); affect provider still on its
0.7.0-loaded process (bounce optional — affect wire unchanged at 0.8.0). Cold-recall
status SUPERSEDED by the 2026-06-17 block above (now CLOSED end-to-end).
**Ratatoskr now has a SECOND identity: the v1 Bifrost Tier-3 consumer** — the
durable persistence provider Worldtree writes Tier-3 agent affect/persona +
@@ -140,8 +181,8 @@ HS256 = the API-key STRING utf-8-encoded; rotate via infra-ops.
operator's call. `graphify-out/GRAPH_REPORT.md` still runs dirty
(auto-regenerated artifact, not chased).
**Still standing from before:** Worldtree spec pin v0.29.0 (`562001a`) for the
conversation-API/TUI surface (untouched by the Bifrost work). Codex-first pilot
**Still standing from before:** Worldtree spec pin now v0.35.16 (`f1b59f8`) for the
conversation-API/TUI surface (bumped 2026-06-17 from v0.29.0/`562001a`). Codex-first pilot
still dormant (no codex session spun up — see the 2026-05-29 decision). Open
issues: #10 (subject migration, deferred), #11 (AdminEvents pane, deferred).
@@ -211,6 +252,22 @@ decision. Captures rationale that won't be obvious from code alone.
- `[2026-06-16]` **Repinned bifrost 0.7.0→0.8.0 + reimplemented memory `search` to the v0.6 scope split (operator-directed).** `scope_filter``scope_all` (AND) + `scope_any` (OR/union over a list of conjunctive scopes), bifrost #11 — the canonical resolution of the #295/#297 silent-zero. **SUPERSEDES the "Provider stores byte-faithful to AND reference / Do NOT flip `_scope_matches` to OR" entry above**: the reference itself now does OR via `scope_any` (a NEW field — `scope_all` keeps the old AND semantics; this is an additive split, not a flip of the AND predicate). Store / contract (v1.2) / tests at parity with the v0.6 reference; provider bounced onto 0.8.0 with a wiped DB (operator: "nothing of value"). Cold recall now gated only on Worldtree emitting `scope_any` (#297). **#17's contract has stale `scope_filter`/`_scope_matches`-AND references (its `assumptions`, INV-004, and the op-feed `search → req {scope_filter}` summary shape) — update those to `scope_all`/`scope_any` when #17 TDD starts; INV-004's intent (observe must not alter scope semantics) still holds.**
- `[2026-06-17]` **Worldtree spec pin bumped v0.29.0→v0.35.16 (`562001a`→`f1b59f8`); cold recall CLOSED end-to-end.** Worldtree shipped #297 (client-side per-scope-value union recall) + #298/#299 (adopt the bifrost v0.6 `scope_any`/`scope_all` wire) — it now emits `scope_any` on recall, the upstream half that pairs with our v0.17.6 provider. Re-vendored `conversation-api-spec.md` + `conversation_api.contract.md`; diff-reviewed the 285-commit catch-up — no client-breaking changes (#211 agent-slug rename saga→echo/actor→mask is slugs-only; #245 end_user_id+memory-scope; #187/#188/#219 Tier-3 define/PATCH additive; error codes stable). Shipped as a `pin:` commit, NO package bump (docs/pin-only, no ratatoskr code; per SemVer SKIP for docs-only). **Remaining proof: a live cold-recall re-smoke against a personal instance on v0.35.16** — the smoke target ran v0.35.2/.3, needs infra-ops to update it.
- `[2026-06-17]` **End-to-end cold-recall proof RAN — our stack proven, #296 isolated.** Against personal WT v0.35.16 with restored `ratatoskr:sindra`: #297/#298 union recall (WT emits `scope_any`), write path (promote→upsert→persist), and cold read (scope_any returns hits) ALL proven. Lone gap = upstream #296 extraction quality. Refines the spec-repin entry's "cold recall closes end-to-end": the WIRE closed; actual fact-recall is #296-blocked. (triage `01KVBBH0…`)
- `[2026-06-17]` **DELETE+redefine `ratatoskr:sindra` (operator-authorized; pre-v1 debug surface).** She SURVIVED the rebuild but was STALE (dead model `artemis-31b-v1i` + no memory block from Phase-2.0 tooling); memory is immutable post-define, so DELETE+redefine was the only path. v0.35.16 define takes **`role`** (capability), NOT `model`: `role:"character"` → first-healthy bind `mistral-small-4`; `memory:{}` trips the promotion gate (GET does NOT echo `memory_config`). Reasoning bind needs a `character`-role bind reorder (worldtree-dev flagged to operator). Our `tier3.py` define is Phase-2.0-stale (no role/memory/persona layers) — untracked modernization follow-up.
- `[2026-06-17]` **Promotion = 4-trigger hybrid (worldtree-dev, code-grounded):** salience (regex, 90s rate-limit) / `turn_count≥6` / context_pressure / **idle `≥10min` (unconditional on quality)**; per-turn `plan_promotion_run` for consumer_defined. **DELETE does NOT drain/promote** (delete-is-delete, #276) — idle `≥10min` is the deterministic flush. The seed promoted at ~4min (per-turn salience/turn-scan, before the idle floor).
- `[2026-06-17]` **#296 triage sent to worldtree-dev** (`01KVBBH0QRGT34GDJQEX5ACTT1`): extraction SUBJECT-INVERSION (promotes assistant prose, drops the user's fact) + META-DESCRIPTION-not-content; verbose-persona aggravator. The WAD-vs-bug cut resolved to BUG (extraction quality), not idle-gating.
- `[2026-06-18]` **Tier-3 memory PROVEN end-to-end live**`ratatoskr:terse-probe` recalled a seeded user fact in a COLD history-free session (scope_any → 1 hit @ cosine 0.6994 → "Dark chocolate with sea salt"). The session's headline; closes the opening "how far from Tier-3 memory" question for normal agents. (proof in this session's transcript)
- `[2026-06-18]` **#296 Stage 1 (v0.35.19) validated live + bisect localized the residual to VERBOSE-PERSONA VOLUME.** Stage 1's recallability admission gate works for normal turns (clean distillate, `distiller_model_id="identity"`); the terse-probe-promotes / sindra-drowns bisect pinned the remaining failure to symptom 1 (assistant-prose volume crowding out the user fact at extraction).
- `[2026-06-18]` **#296 Stage 2 (v0.36.0) MERGED at worldtree-codex** — user-only one-call-per-turn extraction, the STRUCTURAL fix for the subject-inversion drop sindra exposed. Staged per operator: core fix now (validated by our terse-probe PASS + WT test suite); hard-linguistic layer (larger-model escalation, marker-less-fact regex-demotion) tracked at Worldtree #305. We handed worldtree-dev a live-validated eval fixture PAIR for #305 (terse-proof POSITIVE chunk + choc-v2/sindra NEGATIVE-drop).
- `[2026-06-18]` **Full root-cause chain traced + confirmed** (a3466fab ledger pull via infra-ops): v0.35.16 verbose-sindra EMITS 2 meta-descriptions → v0.35.19 gate hard-rejects them (emit-then-reject) → v0.36.0 user-only pass emits the fact. The 2 v0.35.16 chunks ("Assistant's detailed flirtatious response…" / "…head tilt, eye locking, freckles…") are textbook subject-inversion; banked as #305 negative-fixture examples.
- `[2026-06-18]` **FULL-COVERAGE proof — verbose-persona memory works under Stage 2 (v0.36.0).** Re-smoked `ratatoskr:sindra-probe` (sindra's theatrical prompt; FRESH agent + end_user `verbose-v2` to dodge the WT promotion-dedup): the high-volume turn promoted the user fact CLEANLY (not a meta-description) and cold-recalled @ 0.694. Confirms `:8081` is on v0.36.0 and closes the verbose-persona caveat end-to-end. Then started `ratatoskr-web` (`:8765`, consumer key, `ratatoskr:sindra` in the picker) for the operator's Sindra session — **persona + debug only; the web client does NOT bind to `:8391` (#17 unbuilt), so no memory persistence in the web chat** (memory-enabled chat is the #17 build, or a manual bound session).
- `[2026-06-18]` **Tier-3 persona_state is a Worldtree limitation (not ours); sindra → thoughtful-character.** The web Persona-pane 404 ("persona not available") = `persona_state` hard-404s ALL Tier-3 (colon-id) agents by design (`api.py:1220`); a persona block in the define doesn't help (endpoint short-circuits before the row). Pinged worldtree-dev on the Tier-3 persona_state roadmap (thread `01KVCR6P…`) + de-uglied our web pane (`index.html loadPersona`) to render a clear message (v0.17.7). Separately switched `ratatoskr:sindra` to the `thoughtful-character` role (→ `mistral-small-4-reasoning`) via DELETE+redefine (kept her prompt; added an inert persona block). **REFRAME (worldtree-dev `01KVCRK9…`):** persona_state GET is **Tier-1-only by ADR-0009**, the colon-id 404 is correct-by-design (NOT a stub to wait for). Tier-3 affect is **CLIENT-persisted** — we ALREADY hold the PAD `{pleasure,arousal,dominance}` + valence at `:8390` from the `affect.emit` payload. So the Persona-pane fix is **OUR side**: #17 affect-binding → WT dispatches `affect.emit``:8390` → the web pane renders PAD/valence from our own store. WT #289 (`affect.fetch`/`affect:read`) = optional mediated-read (their intelligence over our raw store), NOT a prerequisite. WT #300 = their forthcoming v1 client-impl guide (who-owns-what), folding in this exact case.
_For per-issue TDD implementation notes, Volva findings, and contract amendments, see the git log — every per-issue commit carries a structured message capturing the trail._
## Tried and abandoned
@@ -250,3 +307,6 @@ defense against re-attempting the same cul-de-sac.
- `[2026-06-16]` **My #295 coupling hypothesis (the promoted question crowds out the fact at small top_k) was REFUTED** — worldtree-dev's recall over-fetches `top_k=128` (`injector.py:203`/`_store_helpers.py:101`), so the question can't crowd the fact out at search level. Reasonable cross-frontier hypothesis, correctly framed as a hypothesis not a conclusion; the real cause was the scope-axis asymmetry. Lesson: offer provider-side hypotheses, let the upstream owner check them against their code.
- `[2026-06-16]` **Contract drifted from its own design in two spots, caught only by `/heid-contract-review` (not same-author paraphrase):** the `OpEvent` dataclass omitted the `turn_id` that INV-005 promised; the `session_id` comment said "None for search/get/delete" contradicting the dispatch-layer design (the JWT carries session_id for all verbs at dispatch). Cross-model paraphrase is load-bearing for catching an author's own contract-vs-intent drift.
- `[2026-06-16]` **"No promotion" was checked TOO EARLY — Tier-3 promotion is ASYNC (lands AFTER the SSE turn-end).** The cold-recall probe's immediate post-turn fixture check showed 3 chunks (no promotion); a later check (during the v0.17.5 provider restart) found 5 — the probe HAD promoted 2 chunks (its question `acc3d49` + the model's non-answer `4773704`), just late. Don't trust an immediate post-turn fixture snapshot to judge promotion; it lands after the turn completes. (Same family as the "wire-200 ≠ recall, prove it in a cold session" lesson, extended to promotion timing — and the reason #17's contract pins a post-turn grace window + fixture before/after assertion.)
- `[2026-06-17]` **"sindra is GONE" (infra-ops, from `GET /agents` + admin token) was a FALSE NEGATIVE.** Consumer-defined Tier-3 agents are OWNER-SCOPED (separate `consumer_agents` table) — invisible to the foundational `GET /agents` roster even with an admin token. To check whether a Tier-3 agent exists, `GET /agents/<owner>:<name>` with the OWNER key. (Extends the 2026-06-15 "Sindra registration under-verified" lesson — even the roster query can't see consumer agents; only the owner-scoped point-GET does.)
- `[2026-06-17]` **"Promotion didn't fire → #296" was PREMATURE — twice over.** (1) Polled the op-feed only ~2min, but the upsert landed at ~4min — promotion is async + multi-trigger; watch a longer window. (2) It DID fire; the real bug is extraction QUALITY (assistant-prose promoted, user-fact dropped), not non-firing. "No upsert while a session is live and `<10min` idle" is WAD, not a miss. (Extends the 2026-06-16 "checked too early" entry with the multi-trigger timing + the fired-but-bad-content distinction.)
- `[2026-06-18]` **Wiping our `:8391` store does NOT reset Worldtree's promotion-side dedup** — the v0.35.19 sindra re-smoke (same agent + fresh end_user `choc-v2`) returned `reason_code=noop_duplicate` / `candidate_count=0`: the extractor NEVER RE-RAN, dedup short-circuited against the earlier `sindra-proof` promotion. So a "0 chunks / empty store" result can be a DEDUP artifact, not Stage 1 fail-closing — I mis-read it as fail-closed, worldtree-dev caught it from the ledger. **For a clean promotion smoke, use a BRAND-NEW agent + end_user (never-used names)** — exactly why terse-probe was valid. (Also: `llm_calls_used=0` is NOT the "did the extractor run" tell — `noop_duplicate` is; a3466fab promoted 2 candidates with `llm=0`.)
+2 -2
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "ratatoskr"
version = "0.17.6"
version = "0.17.9"
description = "Worldtree Conversation API debug TUI — multi-pane observability dashboard"
readme = "README.md"
requires-python = ">=3.12"
@@ -59,7 +59,7 @@ Repository = "https://gitea.phasefinal.com/vh/ratatoskr"
# Ratatoskr is built against Worldtree at this commit; the vendored
# spec snapshot in docs/ reflects that SHA.
[tool.ratatoskr.spec-pin]
worldtree-spec-rev = "562001af28d752c3a60d449c7ddd09f44fa9dc9a"
worldtree-spec-rev = "f1b59f8cd6fe41e497d0be9dad9d3110451f0d9a"
worldtree-version = "v0.29.0"
pinned-on = "2026-05-26"
+256
View File
@@ -0,0 +1,256 @@
"""Dispatch-layer observe feed for the Bifrost provider (issue #17, Observe half).
`instrument_provider_app` wraps a built provider ASGI app so every inbound
bifrost-call emits one structured `OpEvent` — correlated by `session_id` read off
the dispatch JWT — WITHOUT touching the store's scope semantics (INV-004). It is
the lens that lets ratatoskr, owning BOTH ends of the round-trip, see exactly
which memory/affect ops a given turn produced.
The store-method stdout shim in `memory_store.py` cannot see `session_id` for
search/get/delete (bifrost withholds `ctx` from those store methods); this feed
sits at the DISPATCH/ASGI layer where the JWT — and thus `session_id` (its `sub`
claim) — is always present (INV-005).
"""
from __future__ import annotations
import base64
import json
import sys
from dataclasses import asdict, dataclass
from datetime import UTC, datetime
from typing import Any, Protocol
@dataclass(frozen=True)
class OpEvent:
"""One observed bifrost-call at the dispatch layer (scope-only, never content)."""
ts: str # ISO 8601 UTC, capture time
plane: str # "memory" | "affect"
op: str # verb: search / upsert_many / get / get_many / delete_many / emit / handshake
session_id: str | None # JWT `sub` at the dispatch layer; None only if the JWT omits it
status: str # "ok" | "error"
req_summary: dict[str, Any] # per-verb, scope-only — no record bodies
resp_summary: dict[str, Any] # per-verb counts + ids/scores — never verbatim content
turn_id: str | None = None # INV-005 reservation, literal; unused in v1
class OpSink(Protocol):
"""Anything that accepts an OpEvent. v1 ships JsonlOpSink; tests pass fakes."""
def emit(self, event: OpEvent) -> None: ...
class JsonlOpSink:
"""Continuous append-only JSONL sink (INV-007: NOT per-session). One JSON line
per OpEvent to a text stream (default stdout)."""
def __init__(self, stream: Any = None) -> None:
self._stream = sys.stdout if stream is None else stream
def emit(self, event: OpEvent) -> None:
self._stream.write(json.dumps(asdict(event), separators=(",", ":")) + "\n")
self._stream.flush()
def maybe_instrument_from_env(app: Any, env: Any, *, plane: str) -> Any:
"""Opt-in serve wiring: when `RATATOSKR_OPFEED_PATH` is set, wrap `app` with
the dispatch-layer op-feed writing JSONL to that path; otherwise return `app`
unchanged. The append stream lives for the process (a long-running server)."""
path = env.get("RATATOSKR_OPFEED_PATH")
if not path:
return app
stream = open(path, "a", encoding="utf-8") # process-lifetime append stream
return instrument_provider_app(app, plane=plane, sink=JsonlOpSink(stream))
_BIFROST_PATHS = (
"/bifrost/handshake",
"/bifrost/memory-call",
"/bifrost/affect-call",
)
def _b64url_decode(seg: str) -> bytes:
return base64.urlsafe_b64decode(seg + "=" * (-len(seg) % 4))
def _session_id_from_auth(auth: bytes | None) -> str | None:
"""Read the `sub` claim (= session_id, per bifrost DispatchContext) off the
dispatch JWT WITHOUT verifying its signature — the inner app does real
verification; we only read a claim for correlation. None if absent/malformed."""
if not auth:
return None
try:
token = auth.decode("latin-1").strip()
if token.lower().startswith("bearer "):
token = token[7:].strip()
parts = token.split(".")
if len(parts) != 3:
return None
payload = json.loads(_b64url_decode(parts[1]))
sub = payload.get("sub")
return sub if isinstance(sub, str) else None
except Exception:
return None
def _op_from(path: str, req: dict[str, Any]) -> str:
"""The verb: 'handshake' for the handshake path; otherwise the body's
`operation`, with the affect-plane `affect.` prefix stripped (affect.emit ->
emit) so op vocabulary stays bare per the contract."""
if path == "/bifrost/handshake":
return "handshake"
operation = req.get("operation") or "unknown"
if path == "/bifrost/affect-call" and operation.startswith("affect."):
return operation.split(".", 1)[1]
return operation
def _ids_summary(args: dict[str, Any]) -> list[Any]:
"""Mirror bifrost `_ids_arg`: ids | chunk_ids | [chunk_id|id]."""
ids = args.get("ids") or args.get("chunk_ids")
if ids is None:
single = args.get("chunk_id") or args.get("id")
ids = [single] if single is not None else []
return ids
def _req_summary(plane: str, path: str, op: str, req: dict[str, Any]) -> dict[str, Any]:
"""Scope-only request summary — NEVER record bodies / PAD content."""
if path == "/bifrost/handshake":
return {"caps_requested": req.get("capabilities_requested")}
if plane == "affect":
return {} # affect stays conduit-opaque — no PAD content surfaced
args = req.get("args") or {}
if op == "search":
return {
"scope_all": args.get("scope_all") or {},
"scope_any": args.get("scope_any") or [],
"top_k": args.get("top_k"),
}
if op == "upsert_many":
records = args.get("records") or []
return {
"record_count": len(records),
"scopes": [r.get("scope") for r in records],
}
if op in ("get", "get_many", "delete_many"):
return {"ids": _ids_summary(args)}
return {}
def _resp_summary(
plane: str, path: str, op: str, resp: dict[str, Any], status: str
) -> dict[str, Any]:
"""Per-verb counts + ids/scores — never verbatim content. On error, the
bifrost error `code` (INV-007: failures recorded, not hidden)."""
if status == "error":
return {"error": resp.get("code")}
if path == "/bifrost/handshake":
return {"ok": True, "caps_granted": resp.get("capabilities_granted")}
if plane == "affect":
return {"stored": bool(resp.get("stored"))}
if op == "search":
results = resp.get("results") or []
return {
"hit_count": len(results),
"hits": [
{"chunk_id": r.get("chunk_id"), "score": r.get("score")}
for r in results
],
}
if op == "upsert_many":
return {"upserted": resp.get("upserted"), "replayed": resp.get("replayed")}
if op == "get":
return {"found_count": 1 if resp.get("record") else 0}
if op == "get_many":
return {"found_count": len(resp.get("records") or [])}
if op == "delete_many":
return {"deleted": resp.get("deleted")}
return {}
def _build_event(
plane: str, path: str, scope: dict[str, Any], req_body: bytes, captured: dict[str, Any]
) -> OpEvent:
headers = dict(scope.get("headers") or [])
session_id = _session_id_from_auth(headers.get(b"authorization"))
status = "ok" if 200 <= int(captured["status"]) < 300 else "error"
req = _safe_json(req_body)
resp = _safe_json(captured["body"])
op = _op_from(path, req)
return OpEvent(
ts=datetime.now(UTC).isoformat(),
plane=plane,
op=op,
session_id=session_id,
status=status,
req_summary=_req_summary(plane, path, op, req),
resp_summary=_resp_summary(plane, path, op, resp, status),
)
def _safe_json(raw: bytes) -> dict[str, Any]:
if not raw:
return {}
try:
value = json.loads(raw)
except (json.JSONDecodeError, ValueError):
return {}
return value if isinstance(value, dict) else {}
def instrument_provider_app(app: Any, *, plane: str, sink: OpSink) -> Any:
"""Wrap a built provider ASGI `app` so each inbound bifrost-call emits one
OpEvent to `sink`. Read-only over dispatch — store scope semantics untouched
(INV-004). A sink/summary failure never propagates into the dispatch path
(POST-003 / INV-007) — it is swallowed and logged to stderr.
"""
if plane not in ("memory", "affect"):
raise ValueError(f"plane must be 'memory' or 'affect', got {plane!r}")
async def wrapped(scope: dict[str, Any], receive: Any, send: Any) -> None:
if scope.get("type") != "http" or scope.get("path") not in _BIFROST_PATHS:
await app(scope, receive, send)
return
# Buffer the request body so we can BOTH summarise it AND replay it to the
# inner app (the inner app consumes `receive`; we must not steal the body).
req_body = b""
more = True
while more:
message = await receive()
if message["type"] == "http.request":
req_body += message.get("body", b"")
more = message.get("more_body", False)
else: # http.disconnect
more = False
replayed = False
async def replay_receive() -> dict[str, Any]:
nonlocal replayed
if not replayed:
replayed = True
return {"type": "http.request", "body": req_body, "more_body": False}
return {"type": "http.disconnect"}
captured: dict[str, Any] = {"status": 500, "body": b""}
async def capture_send(message: dict[str, Any]) -> None:
if message["type"] == "http.response.start":
captured["status"] = message["status"]
elif message["type"] == "http.response.body":
captured["body"] += message.get("body", b"")
await send(message)
await app(scope, replay_receive, capture_send)
try:
sink.emit(_build_event(plane, scope["path"], scope, req_body, captured))
except Exception as exc: # observe gap, never a serve break (POST-003)
sys.stderr.write(f"[opfeed] OpEvent emit failed (swallowed): {exc!r}\n")
return wrapped
+4 -1
View File
@@ -12,6 +12,7 @@ import os
from collections.abc import Mapping
from ratatoskr.provider.affect_store import build_affect_provider_app, open_affect_store
from ratatoskr.provider.opfeed import maybe_instrument_from_env
def build_app_from_env(env: Mapping[str, str] | None = None):
@@ -23,11 +24,13 @@ def build_app_from_env(env: Mapping[str, str] | None = None):
"RATATOSKR_HEIMDALL_KEY is required to serve the affect provider"
)
store = open_affect_store(env.get("RATATOSKR_AFFECT_DB", "affect.db"))
return build_affect_provider_app(
app = build_affect_provider_app(
store,
heimdall_key=key.encode(),
consumer_id=env.get("RATATOSKR_CONSUMER_ID", "ratatoskr"),
)
# Issue #17 (Observe): opt-in dispatch-layer op-feed when RATATOSKR_OPFEED_PATH set.
return maybe_instrument_from_env(app, env, plane="affect")
def main() -> None:
+4 -1
View File
@@ -17,6 +17,7 @@ import os
from collections.abc import Mapping
from ratatoskr.provider.memory_store import build_memory_provider_app, open_memory_store
from ratatoskr.provider.opfeed import maybe_instrument_from_env
def build_memory_app_from_env(env: Mapping[str, str] | None = None):
@@ -43,11 +44,13 @@ def build_memory_app_from_env(env: Mapping[str, str] | None = None):
store = open_memory_store(
env.get("RATATOSKR_MEMORY_DB", "memory.db"), embedding_dim=embedding_dim
)
return build_memory_provider_app(
app = build_memory_provider_app(
store,
heimdall_key=key.encode(),
consumer_id=env.get("RATATOSKR_CONSUMER_ID", "ratatoskr"),
)
# Issue #17 (Observe): opt-in dispatch-layer op-feed when RATATOSKR_OPFEED_PATH set.
return maybe_instrument_from_env(app, env, plane="memory")
def main() -> None:
+115 -2
View File
@@ -59,6 +59,20 @@ class AgentInfo:
ui_hints: dict[str, Any]
@dataclass(frozen=True)
class BifrostBinding:
"""Session-create Bifrost binding (Worldtree BifrostBindingRequest, #160).
Issue #17. `endpoint_url` is the WORLDTREE-VISIBLE base URL of ONE provider
plane (memory :8391 / affect :8390). `scope` is an opaque pass-through copied
into the handshake JWT unchanged (256 chars); ratatoskr does not interpret
it and v1 sends None.
"""
endpoint_url: str
scope: str | None = None
class AgentNotFound(Exception):
"""Raised on HTTP 404 from POST /sessions — unknown agent_id."""
@@ -89,6 +103,40 @@ class SessionApiFailed(Exception):
self.body = body
# Issue #17 — Bifrost-bind failure modes on POST /sessions.
class BifrostConsumerKeyMissing(Exception):
"""A bifrost binding was requested without a consumer_key.
Raised BEFORE any HTTP (INV-001): the bound create must never silently fall
back to the client's default canary key — the consumer key IS the handshake
identity Worldtree signs the Bifrost JWT with.
"""
def __init__(self) -> None:
super().__init__(
"bifrost binding requires a non-empty consumer_key; refusing to "
"fall back to the canary key (INV-001)"
)
class BifrostHandshakeFailed(Exception):
"""Raised on HTTP 502 `bifrost_handshake_failed` from a bound POST /sessions.
INV-002: the Bifrost handshake runs synchronously at session-create, so a
handshake failure (bad URL / down provider / wrong key / HTTPS rejection)
fails SESSION CREATION surfaced on the create path, never deferred to the
first turn. `bifrost_error` carries the spec-level code (e.g.
`bifrost.auth_rejected`); `body` is truncated to 1024 bytes, consistent with
`SessionApiFailed` (INV-004 precedent).
"""
def __init__(self, *, bifrost_error: str | None, body: bytes) -> None:
body = body[:1024]
super().__init__(f"bifrost handshake failed: bifrost_error={bifrost_error!r}")
self.bifrost_error = bifrost_error
self.body = body
# Worldtree #204 / v0.28.0 — persona_state endpoint failure modes.
class PersonaNotConfigured(Exception):
"""Raised on HTTP 404 `persona_not_configured` from GET persona_state.
@@ -176,11 +224,51 @@ async def list_sessions(
return SessionPage(items=items, next_cursor=body.get("next_cursor"))
def endpoint_for_plane(plane: str, base_host: str) -> str:
"""Map a provider plane name to its Worldtree-VISIBLE base URL.
Issue #17 dev helper: `memory` → :8391, `affect` → :8390. Returns the
Worldtree-visible base (e.g. `http://10.100.10.50:8391`), NOT the client's
loopback Worldtree must reach the provider over the network. `http://` is
deliberate: the HTTPS relaxation is allowlist-side (Worldtree's
BIFROST_CLIENT_ALLOWED_HOSTS), not a URL concern. A production HTTPS endpoint
is supplied directly, bypassing this helper.
"""
if plane not in ("memory", "affect"):
raise ValueError(
f"unknown plane: {plane!r} (expected 'memory' or 'affect')"
)
port = 8391 if plane == "memory" else 8390
return f"http://{base_host}:{port}"
def _bifrost_error_from(resp: httpx.Response) -> str | None:
"""Pull the spec-level `bifrost_error` from a 502 body.
Tolerates both the FastAPI-nested `{"detail": {"bifrost_error": }}` shape
(the spec's documented form, §"Optional Bifrost binding") and a flat
top-level `bifrost_error`, per the both-shape unwrap precedent established for
persona_state errors (the real wire returns the detail-nested form).
"""
try:
err = resp.json()
except ValueError:
return None
if not isinstance(err, dict):
return None
bifrost_error = err.get("bifrost_error")
if bifrost_error is None and isinstance(err.get("detail"), dict):
bifrost_error = err["detail"].get("bifrost_error")
return bifrost_error
async def create_session(
client: httpx.AsyncClient,
agent_id: str,
*,
end_user_id: str | None = None,
bifrost: BifrostBinding | None = None,
consumer_key: str | None = None,
) -> SessionInfo:
"""POST /sessions to create a new session. See contract FN create_session.
@@ -188,17 +276,42 @@ async def create_session(
When None (default), the body shape matches the pre-#5 baseline
`{"agent_id": agent_id}` so existing callers (mimir smoke) are unaffected.
Empty-string `end_user_id` is rejected before HTTP (PRE-003).
Per issue #17: when `bifrost` is set the request carries the binding and
authenticates with `consumer_key` (NOT the client's default canary bearer);
Worldtree handshakes synchronously to our provider before 201.
"""
assert client is not None
assert agent_id and isinstance(agent_id, str)
assert end_user_id is None or (isinstance(end_user_id, str) and end_user_id)
body: dict[str, str] = {"agent_id": agent_id}
# PRE-001 (INV-001): a bifrost binding REQUIRES a non-empty consumer key,
# enforced before any HTTP so a bound create never falls back to the canary.
if bifrost is not None and not (isinstance(consumer_key, str) and consumer_key):
raise BifrostConsumerKeyMissing()
body: dict[str, Any] = {"agent_id": agent_id}
if end_user_id is not None:
body["end_user_id"] = end_user_id
resp = await client.post("/sessions", json=body)
headers: dict[str, str] = {}
if bifrost is not None:
body["bifrost"] = {
"endpoint_url": bifrost.endpoint_url,
"scope": bifrost.scope,
}
# INV-001: the bound create authenticates with the consumer key,
# overriding the httpx client's default canary bearer per-request.
headers["Authorization"] = f"Bearer {consumer_key}"
resp = await client.post("/sessions", json=body, headers=headers)
if resp.status_code == 404:
raise AgentNotFound(agent_id=agent_id)
# POST-002 (INV-002): a 502 on a BOUND create is the synchronous Bifrost
# handshake failing. Gated on `bifrost is not None` — an unbound create's
# 502 is a generic upstream fault and stays SessionApiFailed.
if bifrost is not None and resp.status_code == 502:
raise BifrostHandshakeFailed(
bifrost_error=_bifrost_error_from(resp), body=resp.content
)
if resp.status_code != 201:
raise SessionApiFailed(status=resp.status_code, body=resp.content)
body = resp.json()
+14 -1
View File
@@ -704,7 +704,20 @@ async function loadPersona(agentId) {
renderPersonaPane(snap);
setPersonaStrip(snap);
} else {
$("pane-persona").innerHTML = `<div class="empty">persona not available (HTTP ${esc(r.status)})</div>`;
let code = "";
try { code = (await r.json()).error_code || ""; } catch (_) {}
let msg;
if (r.status === 404 && code === "persona_not_configured" && agentId.includes(":")) {
msg = "persona telemetry isn't exposed for Tier-3 (consumer-defined) agents on this Worldtree yet — " +
"the agent still responds in character; only this affect / OCEAN readout is gated.";
} else if (r.status === 404 && code === "persona_not_configured") {
msg = "this agent has no persona configured.";
} else if (r.status === 403) {
msg = "persona telemetry requires the persona.read scope.";
} else {
msg = `persona unavailable (HTTP ${esc(r.status)}${code ? " · " + esc(code) : ""}).`;
}
$("pane-persona").innerHTML = `<div class="empty">${msg}</div>`;
}
} catch (e) {
$("pane-persona").innerHTML = `<div class="empty">persona fetch failed</div>`;
+284
View File
@@ -0,0 +1,284 @@
"""Tests for the dispatch-layer observe feed (ratatoskr.provider.opfeed).
Issue #17 slice 2 (the Observe half). These drive the REAL bifrost provider ASGI
app end-to-end through `instrument_provider_app`, minting a valid dispatch JWT with
bifrost's own `mint_dispatch_jwt` — so the envelopes and the session_id claim are
the real wire shapes, not hand-mocked guesses (the repo's "test against the
shipped lib" posture).
"""
from __future__ import annotations
import httpx
import pytest
from bifrost.core.dispatch_jwt import mint_dispatch_jwt
from ratatoskr.provider.affect_store import (
build_affect_provider_app,
open_affect_store,
)
from ratatoskr.provider.memory_store import (
build_memory_provider_app,
open_memory_store,
)
from ratatoskr.provider.opfeed import instrument_provider_app
_KEY = "shared-secret"
_DIM = 8
_CONSUMER = "ratatoskr"
class _RecordingSink:
"""An OpSink that just records events (so a test can assert on them)."""
def __init__(self) -> None:
self.events: list = []
def emit(self, event) -> None:
self.events.append(event)
def _mint(session_id: str, scope: list[str]) -> str:
return mint_dispatch_jwt(
session_id=session_id,
consumer_id=_CONSUMER,
issuer="worldtree",
scope=scope,
secret_or_key=_KEY,
algorithm="HS256",
)
def _wrapped_memory_app(sink):
store = open_memory_store(":memory:", embedding_dim=_DIM)
app = build_memory_provider_app(
store, heimdall_key=_KEY.encode(), consumer_id=_CONSUMER
)
return instrument_provider_app(app, plane="memory", sink=sink), store
def _wrapped_affect_app(sink):
store = open_affect_store(":memory:")
app = build_affect_provider_app(
store, heimdall_key=_KEY.encode(), consumer_id=_CONSUMER
)
return instrument_provider_app(app, plane="affect", sink=sink), store
def _chunk(cid: str, scope: dict | None = None) -> dict:
return {
"id": cid,
"scope": scope or {"end_user": "u1"},
"embedding": [0.1] * _DIM,
"content": "x",
}
class _RaisingSink:
def emit(self, event) -> None:
raise RuntimeError("boom")
async def _post(app, path: str, body: dict, jwt: str | None) -> httpx.Response:
transport = httpx.ASGITransport(app=app)
headers = {"Authorization": f"Bearer {jwt}"} if jwt else {}
async with httpx.AsyncClient(
transport=transport, base_url="http://provider"
) as client:
return await client.post(path, json=body, headers=headers)
class TestOpFeedMemory:
async def test_search_emits_one_opevent(self) -> None:
"""search [tracer]: a memory search dispatched through the wrapped app
emits EXACTLY ONE OpEvent plane=memory, op=search, session_id from the
JWT sub, status=ok, scope-only req/resp summaries (POST-001/002, INV-005).
Empty store 0 hits."""
sink = _RecordingSink()
app, _store = _wrapped_memory_app(sink)
jwt = _mint("session-abc", ["memory:read"])
body = {
"operation": "search",
"args": {
"vector": [0.0] * _DIM,
"top_k": 5,
"scope_all": {"end_user": "u1"},
"scope_any": [],
},
}
resp = await _post(app, "/bifrost/memory-call", body, jwt)
assert resp.status_code == 200
assert len(sink.events) == 1
ev = sink.events[0]
assert ev.plane == "memory"
assert ev.op == "search"
assert ev.session_id == "session-abc"
assert ev.status == "ok"
assert ev.req_summary == {
"scope_all": {"end_user": "u1"},
"scope_any": [],
"top_k": 5,
}
assert ev.resp_summary["hit_count"] == 0
assert ev.turn_id is None
assert ev.ts # non-empty capture timestamp
async def test_upsert_many_summary(self) -> None:
"""upsert_many: req carries record_count + per-record scopes (no bodies);
resp carries upserted + replayed."""
sink = _RecordingSink()
app, _store = _wrapped_memory_app(sink)
jwt = _mint("session-up", ["memory:write"])
body = {
"operation": "upsert_many",
"args": {"records": [_chunk("c1"), _chunk("c2", {"end_user": "u2"})]},
"idempotency_key": "k1",
}
resp = await _post(app, "/bifrost/memory-call", body, jwt)
assert resp.status_code == 200
ev = sink.events[-1]
assert ev.op == "upsert_many"
assert ev.status == "ok"
assert ev.req_summary == {
"record_count": 2,
"scopes": [{"end_user": "u1"}, {"end_user": "u2"}],
}
assert ev.resp_summary == {"upserted": 2, "replayed": False}
async def test_get_and_delete_summaries(self) -> None:
"""get -> found_count; delete_many -> deleted; both req carry ids only."""
sink = _RecordingSink()
app, _store = _wrapped_memory_app(sink)
await _post(
app,
"/bifrost/memory-call",
{
"operation": "upsert_many",
"args": {"records": [_chunk("c1")]},
"idempotency_key": "k1",
},
_mint("s", ["memory:write"]),
)
await _post(
app,
"/bifrost/memory-call",
{"operation": "get", "args": {"chunk_id": "c1"}},
_mint("s", ["memory:read"]),
)
get_ev = sink.events[-1]
assert get_ev.op == "get"
assert get_ev.req_summary == {"ids": ["c1"]}
assert get_ev.resp_summary == {"found_count": 1}
await _post(
app,
"/bifrost/memory-call",
{"operation": "delete_many", "args": {"ids": ["c1"]}},
_mint("s", ["memory:write"]),
)
del_ev = sink.events[-1]
assert del_ev.op == "delete_many"
assert del_ev.req_summary == {"ids": ["c1"]}
assert del_ev.resp_summary == {"deleted": 1}
async def test_error_status_records_the_bifrost_code(self) -> None:
"""error [adversarial]: an unknown operation -> status=error and the
bifrost error `code` is recorded, never hidden (INV-007)."""
sink = _RecordingSink()
app, _store = _wrapped_memory_app(sink)
resp = await _post(
app,
"/bifrost/memory-call",
{"operation": "bogus", "args": {}},
_mint("s", ["memory:read"]),
)
assert resp.status_code != 200
assert len(sink.events) == 1
ev = sink.events[0]
assert ev.op == "bogus"
assert ev.status == "error"
assert ev.resp_summary == {"error": "memory.invalid_arguments"}
async def test_missing_jwt_session_id_none_still_emits(self) -> None:
"""no_jwt [boundary]: a call with NO Authorization still emits exactly one
OpEvent with session_id=None (INV-005) and status=error (auth rejected)."""
sink = _RecordingSink()
app, _store = _wrapped_memory_app(sink)
resp = await _post(
app,
"/bifrost/memory-call",
{"operation": "search", "args": {"vector": [0.0] * _DIM, "top_k": 1}},
None,
)
assert resp.status_code != 200
assert len(sink.events) == 1
assert sink.events[0].session_id is None
assert sink.events[0].status == "error"
async def test_handshake_op_from_path(self) -> None:
"""handshake: op is derived from the PATH (handshake bodies carry no
`operation` field); still exactly one OpEvent (POST-001 incl. handshake)."""
sink = _RecordingSink()
app, _store = _wrapped_memory_app(sink)
resp = await _post(
app,
"/bifrost/handshake",
{"bifrost_version": "99.0.0", "mcp_version": "0.4.0"},
None,
)
assert resp.status_code != 200 # version-major mismatch, cleanly rejected
assert len(sink.events) == 1
assert sink.events[0].op == "handshake"
async def test_sink_failure_never_breaks_dispatch(self) -> None:
"""sink_swallow [adversarial]: a raising sink must NOT break the dispatch
path the search still returns 200 (POST-003 / INV-007)."""
app, _store = _wrapped_memory_app(_RaisingSink())
resp = await _post(
app,
"/bifrost/memory-call",
{
"operation": "search",
"args": {"vector": [0.0] * _DIM, "top_k": 1, "scope_all": {}},
},
_mint("s", ["memory:read"]),
)
assert resp.status_code == 200
class TestOpFeedAffect:
async def test_emit_op_normalized_and_plane_affect(self) -> None:
"""affect emit: op is the bare verb (affect.emit -> emit), plane=affect,
session_id from the JWT; affect stays conduit-opaque (empty req_summary)."""
sink = _RecordingSink()
app, _store = _wrapped_affect_app(sink)
jwt = _mint("session-aff", ["affect:write"])
body = {
"operation": "affect.emit",
"args": {
"agent_id": "ratatoskr:sindra",
"end_user_id": "u1",
"pad": {"p": 0.1, "a": 0.2, "d": 0.3},
"valence": 0.5,
"emitted_at": "2026-06-18T00:00:00Z",
},
"idempotency_key": "k1",
}
resp = await _post(app, "/bifrost/affect-call", body, jwt)
assert resp.status_code == 200
assert len(sink.events) == 1
ev = sink.events[0]
assert ev.plane == "affect"
assert ev.op == "emit"
assert ev.session_id == "session-aff"
assert ev.status == "ok"
assert ev.req_summary == {} # conduit-opaque
assert ev.resp_summary == {"stored": True}
class TestInstrumentGuards:
def test_unknown_plane_raises(self) -> None:
with pytest.raises(ValueError):
instrument_provider_app(object(), plane="persona", sink=_RecordingSink())
+13
View File
@@ -21,3 +21,16 @@ def test_build_app_from_env_builds_app_with_routes():
paths = {getattr(r, "path", None) for r in app.routes}
assert "/bifrost/handshake" in paths
assert "/bifrost/affect-call" in paths
def test_opfeed_path_wraps_app(tmp_path):
# Issue #17 slice 2: RATATOSKR_OPFEED_PATH opts the dispatch op-feed in; the
# returned app is then the instrumented ASGI wrapper, not the raw Starlette.
app = build_app_from_env(
{
"RATATOSKR_HEIMDALL_KEY": "shared-secret",
"RATATOSKR_AFFECT_DB": ":memory:",
"RATATOSKR_OPFEED_PATH": str(tmp_path / "ops.jsonl"),
}
)
assert not hasattr(app, "routes") # wrapped: a bare ASGI callable
+14
View File
@@ -46,3 +46,17 @@ def test_build_memory_app_from_env_builds_app_with_routes():
paths = {getattr(r, "path", None) for r in app.routes}
assert "/bifrost/handshake" in paths
assert "/bifrost/memory-call" in paths
def test_opfeed_path_wraps_app(tmp_path):
# Issue #17 slice 2: RATATOSKR_OPFEED_PATH opts the dispatch op-feed in; the
# returned app is then the instrumented ASGI wrapper, not the raw Starlette.
app = build_memory_app_from_env(
{
"RATATOSKR_HEIMDALL_KEY": "shared-secret",
"RATATOSKR_MEMORY_DB": ":memory:",
"RATATOSKR_MEMORY_EMBEDDING_DIM": "8",
"RATATOSKR_OPFEED_PATH": str(tmp_path / "ops.jsonl"),
}
)
assert not hasattr(app, "routes") # wrapped: a bare ASGI callable
+184
View File
@@ -9,11 +9,15 @@ from ratatoskr.sessions import (
AgentNotAvailable,
AgentNotFound,
AuthScopeDenied,
BifrostBinding,
BifrostConsumerKeyMissing,
BifrostHandshakeFailed,
InvalidCursor,
PersonaNotConfigured,
SessionApiFailed,
SessionPage,
create_session,
endpoint_for_plane,
get_persona_state,
list_agents,
list_sessions,
@@ -206,6 +210,186 @@ class TestCreateSession:
assert route.call_count == 0
class TestCreateSessionBifrostBind:
"""Issue #17 slice 1 — the create_session Bifrost-bind primitive."""
@respx.mock
async def test_bind_happy_consumer_key_and_body(self) -> None:
"""bind_happy [tracer]: a bifrost binding makes the body carry the
`bifrost` field AND overrides the bearer to the consumer key (NOT the
client's canary default), 201 → SessionInfo. Proves the bind path
end-to-end (FN create_session STEPS 1-2, POST-001, INV-001)."""
import json as _json
route = respx.post("https://w.example/sessions").mock(
return_value=httpx.Response(
201,
json={
"session_id": "s-bound",
"agent_id": "ratatoskr:sindra",
"message_count": 0,
"created_at": "2026-06-18T12:00:00+00:00",
"last_active": "2026-06-18T12:00:00+00:00",
"metadata": {},
},
)
)
binding = BifrostBinding(endpoint_url="http://10.100.10.50:8391")
async with httpx.AsyncClient(
base_url="https://w.example",
headers={"Authorization": "Bearer canary-key"},
) as client:
info = await create_session(
client,
"ratatoskr:sindra",
end_user_id="smoke-user",
bifrost=binding,
consumer_key="consumer-key",
)
req = route.calls[0].request
body = _json.loads(req.content)
# body carries the bifrost field alongside agent_id/end_user_id
assert body == {
"agent_id": "ratatoskr:sindra",
"end_user_id": "smoke-user",
"bifrost": {
"endpoint_url": "http://10.100.10.50:8391",
"scope": None,
},
}
# bearer overridden to the consumer key (INV-001: never the canary default)
assert req.headers["Authorization"] == "Bearer consumer-key"
assert info.session_id == "s-bound"
assert info.agent_id == "ratatoskr:sindra"
@respx.mock
async def test_bind_without_consumer_key_raises_before_http(self) -> None:
"""missing_key [adversarial]: bifrost set but consumer_key None →
BifrostConsumerKeyMissing BEFORE any HTTP (PRE-001, INV-001: never fall
back to the canary key)."""
route = respx.post("https://w.example/sessions").mock(
return_value=httpx.Response(201, content=b"{}")
)
binding = BifrostBinding(endpoint_url="http://10.100.10.50:8391")
async with httpx.AsyncClient(base_url="https://w.example") as client:
with pytest.raises(BifrostConsumerKeyMissing):
await create_session(client, "ratatoskr:sindra", bifrost=binding)
assert route.call_count == 0
@respx.mock
async def test_bind_with_empty_consumer_key_raises_before_http(self) -> None:
"""empty_key [adversarial]: empty-string consumer_key is also rejected
before HTTP (PRE-001 requires a NON-EMPTY str)."""
route = respx.post("https://w.example/sessions").mock(
return_value=httpx.Response(201, content=b"{}")
)
binding = BifrostBinding(endpoint_url="http://10.100.10.50:8391")
async with httpx.AsyncClient(base_url="https://w.example") as client:
with pytest.raises(BifrostConsumerKeyMissing):
await create_session(
client, "ratatoskr:sindra", bifrost=binding, consumer_key=""
)
assert route.call_count == 0
@respx.mock
async def test_bind_handshake_failure_maps_to_502(self) -> None:
"""handshake_502 [adversarial]: a bound create that 502s with
detail.bifrost_error BifrostHandshakeFailed carrying the bifrost_error
+ raw body (POST-002, INV-002 bind-time failure). 'bifrost.auth_rejected'
is the canary-key-instead-of-consumer-key tell."""
respx.post("https://w.example/sessions").mock(
return_value=httpx.Response(
502,
json={
"error_code": "bifrost_handshake_failed",
"detail": {"bifrost_error": "bifrost.auth_rejected"},
},
)
)
binding = BifrostBinding(endpoint_url="http://10.100.10.50:8391")
async with httpx.AsyncClient(base_url="https://w.example") as client:
with pytest.raises(BifrostHandshakeFailed) as exc_info:
await create_session(
client, "ratatoskr:sindra", bifrost=binding, consumer_key="ck"
)
assert exc_info.value.bifrost_error == "bifrost.auth_rejected"
# the raw 502 body is carried for debugging
assert exc_info.value.body
@respx.mock
async def test_bind_ephemeral_rejection_is_session_api_failed(self) -> None:
"""ephemeral_422 [boundary]: 422 ephemeral_does_not_accept_bifrost is a
generic create failure SessionApiFailed, NOT a distinct exception
(POST-003 deliberate, an operator config error)."""
respx.post("https://w.example/sessions").mock(
return_value=httpx.Response(
422, json={"error_code": "ephemeral_does_not_accept_bifrost"}
)
)
binding = BifrostBinding(endpoint_url="http://10.100.10.50:8391")
async with httpx.AsyncClient(base_url="https://w.example") as client:
with pytest.raises(SessionApiFailed) as exc_info:
await create_session(
client, "echo", bifrost=binding, consumer_key="ck"
)
assert exc_info.value.status == 422
@respx.mock
async def test_unbound_create_unchanged_no_auth_override(self) -> None:
"""unbound_unchanged [regression]: with no bifrost, the body is the
pre-#17 shape AND create_session sends NO per-request Authorization
override the client's default canary bearer governs (INV-001: the two
call sites never cross)."""
import json as _json
route = respx.post("https://w.example/sessions").mock(
return_value=httpx.Response(
201,
json={
"session_id": "s1",
"agent_id": "mimir",
"message_count": 0,
"created_at": "2026-04-15T12:00:00+00:00",
"last_active": "2026-04-15T12:00:00+00:00",
"metadata": {},
},
)
)
async with httpx.AsyncClient(
base_url="https://w.example",
headers={"Authorization": "Bearer canary-key"},
) as client:
await create_session(client, "mimir")
req = route.calls[0].request
body = _json.loads(req.content)
assert body == {"agent_id": "mimir"}
# the client default bearer is used unchanged — no consumer-key override
assert req.headers["Authorization"] == "Bearer canary-key"
class TestEndpointForPlane:
"""Issue #17 — endpoint_for_plane: plane name → Worldtree-visible base URL."""
def test_memory_plane_maps_to_8391(self) -> None:
"""memory [tracer]: 'memory' → http://<host>:8391 (POST-001)."""
assert (
endpoint_for_plane("memory", "10.100.10.50")
== "http://10.100.10.50:8391"
)
def test_affect_plane_maps_to_8390(self) -> None:
"""affect: 'affect' → http://<host>:8390 (POST-001)."""
assert (
endpoint_for_plane("affect", "10.100.10.50")
== "http://10.100.10.50:8390"
)
def test_unknown_plane_raises_value_error(self) -> None:
"""unknown_plane [adversarial]: any other plane → ValueError (PRE-001)."""
with pytest.raises(ValueError):
endpoint_for_plane("persona", "10.100.10.50")
def _list_item(
*,
session_id: str = "s1",
Generated
+1 -1
View File
@@ -1052,7 +1052,7 @@ wheels = [
[[package]]
name = "ratatoskr"
version = "0.17.6"
version = "0.17.9"
source = { editable = "." }
dependencies = [
{ name = "httpx" },