feat(#18): PAD read-endpoint — web pane renders live PAD/valence from our affect store (Deliverable 2)
The web persona pane now renders live PAD/valence for Tier-3 agents from our
:8390 affect store, closing the persona-telemetry gap (Worldtree persona_state
404s for Tier-3 per ADR-0009; Tier-3 emits no affect_update SSE).
- provider: non-bifrost GET /affect/state/{agent_id} on the affect-store-owning
app (add_route — keeps /bifrost/* top-level + op-feed-skipped); explicit
no_affect_snapshot 404 (never a zeroed PAD); busy_timeout + check_same_thread
on the connection.
- web: GET /api/affect/{agent_id} proxy — end_user_id server-supplied (never the
browser), colon-id round-trip, configured RATATOSKR_AFFECT_READ_URL.
- pane: honest affect render (pad + valence + emitted_at, labelled "affect", no
fabricated Tier-1 fields); explicit empty-state; polls 2s post-turn.
Contract-first (docs/contracts/issues/18.contract.md, Deliverable-2-scoped;
Deliverable 1 / composite endpoint deferred — bifrost-blocked on a public
build_combined_app, WT dispatch confirmed single-endpoint caps-routed).
Heid-code-review panel: 1 INV-001 drift (strip fabricated "neutral") + 4
test-gaps fixed. Live-smoke PROVEN: web->provider->affect.db chain returns real
sindra/vuong PAD; Playwright DOM check confirms the pane render + the fix.
Suite 482 green.
This commit is contained in:
@@ -0,0 +1,249 @@
|
||||
---
|
||||
contract_version: "2.1"
|
||||
target_module: "ratatoskr.provider.affect_store + ratatoskr.web (server + static/index.html)"
|
||||
scope: "Issue #18 DELIVERABLE 2 ONLY — the PAD read-endpoint so the web pane renders live PAD/valence for a Tier-3 agent from OUR :8390 affect store. Three pieces: (1) a NON-bifrost read route on the affect-store-owning app — GET /affect/state/{agent_id}?end_user_id=… → store.get(agent_id, end_user_id); (2) a web proxy GET /api/affect/{agent_id} that supplies end_user_id SERVER-SIDE (RATATOSKR_END_USER_ID), never from the browser, and proxies to a CONFIGURED affect-read base URL (RATATOSKR_AFFECT_READ_URL) so the pane is decoupled from the bind target; (3) a NEW pane render path for the affect-emit snapshot shape (pad + per-entity valence + emitted_at) — NOT a reuse of renderPersonaPane (the Tier-1 persona_state shape we never receive for Tier-3). DELIVERABLE 1 (composite :8392 endpoint) is DEFERRED — bifrost-blocked on a public bifrost.consumer.build_combined_app (bifrost-dev confirmed, ~v0.9.0, design locked) AND gated on the open FR-1 Worldtree-dispatch question (worldtree-dev consult in flight). When build_combined_app lands and FR-1 resolves, this contract is AMENDED to add Deliverable 1. Direct in-session TDD (the #17 pattern). The panel framing-consult (Heid, 3 arms) pressure-tested this design; its triaged findings are folded in as INV/POST clauses below."
|
||||
depends_on:
|
||||
- "httpx"
|
||||
- "starlette"
|
||||
- "ratatoskr.provider.affect_store"
|
||||
- "ratatoskr.web.server"
|
||||
used_by:
|
||||
- "ratatoskr.provider.serve"
|
||||
- "ratatoskr.web.entrypoint"
|
||||
language: "python"
|
||||
complexity: "medium"
|
||||
estimated_loc: 130
|
||||
confidence: 0.82
|
||||
assumptions:
|
||||
- "VERIFIED (live affect.db this session): the stored affect.emit snapshot shape is {agent_id, end_user_id, pad:{pleasure,arousal,dominance}, valence:[{entity_id,entity_type,familiarity,interaction_count,regard}], emitted_at}. It overlaps the Worldtree Tier-1 persona_state shape ONLY on agent_id + pad; it has NO dominant_emotion/baseline_pad/mood_drift/emotions_active/last_updated_at, and it HAS valence[] + emitted_at the persona shape lacks. So the pane CANNOT reuse renderPersonaPane — a new affect render path is required (Heid panel Q4: render honestly, do not fabricate Tier-1 fields)."
|
||||
- "VERIFIED (wire, prior session): a Tier-3 turn emits ZERO affect_update SSE and Worldtree persona_state 404s for every Tier-3 colon-id agent (ADR-0009 Tier-1-only). Both Worldtree-side persona sources are dead for consumer agents, so reading OUR store is the only path. The pane therefore POLLS the read endpoint (on session-start + after each turn-end); there is no SSE affect channel to subscribe to."
|
||||
- "The affect store already exposes get(agent_id, end_user_id) -> dict | None (affect_store.py:102). The read route is a thin wrapper over it; the store's conduit-opacity is unaffected (the route returns the stored blob verbatim)."
|
||||
- "RatatoskrAffectStore holds ONE sqlite3.Connection shared across emit + the new read in a single process; the event loop serializes the sync sqlite calls (no threadpool), so same-process read+write needs no extra locking. busy_timeout matters for the FUTURE cross-process case (composite :8392 + standalone :8390 opening the same affect.db); setting it now is correct prep, not a same-process fix."
|
||||
- "build_affect_provider_app currently returns build_affect_app(...) directly. It now adds the read route to that app via app.add_route('/affect/state/{agent_id}', ...) — keeping /bifrost/handshake + /bifrost/affect-call as TOP-LEVEL routes (so the existing route-introspection test stays green AND the op-feed's scope['path'] check in opfeed.py _BIFROST_PATHS still matches the bifrost calls and passes the read route through untouched, INV-004). add_route is preferred over an outer Mount precisely because Mount would push the bifrost paths under the mount and break top-level introspection — add_route is the surgical composition."
|
||||
- "The web affect-read hop is SERVER-TO-PROVIDER (same dev box), distinct from the Worldtree-visible host used for binding. So RATATOSKR_AFFECT_READ_URL is its own config (default http://127.0.0.1:8390), NOT derived from RATATOSKR_PROVIDER_VISIBLE_HOST (which is the WT-visible host for handshake)."
|
||||
- "Tests: respx mocks the provider read URL for the web-proxy unit tests; the provider read route is tested in-process against a seeded RatatoskrAffectStore (mirroring the existing affect_store tests). A colon-id (ratatoskr:sindra) round-trips browser->web->provider and is asserted end-to-end (Heid panel FM-7)."
|
||||
open_questions:
|
||||
- "DELIVERABLE 1 / FR-1 (does NOT block Deliverable 2): does Worldtree dispatch BOTH memory-call AND affect-call to ONE bound endpoint that advertised both caps, or is the binding effectively single-plane? Worldtree-dev consult in flight (msg 01KVDXQMJF…). If single-plane, Deliverable 1 needs a Worldtree-side change too. Resolution gates the Deliverable-1 amendment, not this contract."
|
||||
- "Valence display cap: the snapshot's valence[] is unbounded in principle. v1 caps the rendered list (scroll/limit) so the pane layout can't blow out (Heid panel Groa-FM4). Exact cap is a UI detail settled in implementation; the INVARIANT is 'bounded render', not a specific number."
|
||||
prd:
|
||||
issue: 18
|
||||
issue_url: "https://gitea.phasefinal.com/vh/ratatoskr/issues/18"
|
||||
body_sha256_16: "92be262865f38c0e"
|
||||
lock_in_comment_id: null
|
||||
lock_in_sha256_16: null
|
||||
lock_in_at: null
|
||||
pinned_at: "2026-06-18T18:00:00+00:00"
|
||||
dependencies:
|
||||
- issue: 17
|
||||
path: "src/ratatoskr/web/server.py"
|
||||
reason: "INV-006 of #17 — end_user_id is SERVER-configured (app.state.end_user_id from RATATOSKR_END_USER_ID), never read from the browser. The affect-read proxy follows the same posture: the browser names the agent (already in the picker); the server supplies end_user_id."
|
||||
- issue: 17
|
||||
path: "src/ratatoskr/provider/opfeed.py"
|
||||
reason: "The op-feed instruments only _BIFROST_PATHS; the new non-bifrost read route is outside that set and is passed through untouched. Deliverable 2 must NOT alter op-feed behavior (INV-004)."
|
||||
---
|
||||
|
||||
# Issue #18 (Deliverable 2) — PAD read-endpoint → persona pane renders OUR store
|
||||
|
||||
## Context
|
||||
|
||||
Ratatoskr binds a Tier-3 session to its own affect provider (:8390) and Worldtree
|
||||
persists the agent's PAD/valence there (live-proven: vuong session pleasure +0.146,
|
||||
familiarity 0.18→0.59 over 8 turns). But the web pane shows "telemetry isn't exposed":
|
||||
it reads Worldtree `persona_state` (`loadPersona`, index.html:707), which 404s for every
|
||||
Tier-3 colon-id agent (ADR-0009, Tier-1-only), AND a Tier-3 turn emits zero
|
||||
`affect_update` SSE. Both Worldtree-side persona sources are dead for consumer agents.
|
||||
The pane was never wired to render PAD from OUR store — Deliverable 2 closes that.
|
||||
|
||||
**Scope is the PAD-display half ONLY.** Deliverable 1 (the composite :8392 endpoint that
|
||||
lets one session bind both planes) is bifrost-blocked: bifrost-dev has confirmed a public
|
||||
`bifrost.consumer.build_combined_app` (clean additive minor, ~v0.9.0, design locked) and is
|
||||
standing by on the open Worldtree-dispatch question (FR-1). This contract is amended to add
|
||||
Deliverable 1 once that lands. Deliverable 2 has zero bifrost or Worldtree dependency — it
|
||||
reads our own `affect.db` — so it ships now, independently.
|
||||
|
||||
## Public surface
|
||||
|
||||
```python
|
||||
# Provider side (ratatoskr.provider.affect_store) — a NON-bifrost read route on the
|
||||
# affect-store-owning app, composed alongside the bifrost app.
|
||||
def build_affect_provider_app(
|
||||
store: RatatoskrAffectStore,
|
||||
heimdall_key: bytes,
|
||||
consumer_id: str = "ratatoskr",
|
||||
):
|
||||
"""Builds the bifrost affect app, then app.add_route('/affect/state/{agent_id}',
|
||||
…) to add the PAD read route (reading store.get) as a top-level sibling of the
|
||||
bifrost handshake + affect-call routes. The read route is non-bifrost (no JWT)
|
||||
under the internal-LAN trust model. See FN build_affect_provider_app."""
|
||||
|
||||
|
||||
def open_affect_store(db_path: str) -> RatatoskrAffectStore:
|
||||
"""Unchanged surface; additionally sets PRAGMA busy_timeout=5000 on the connection
|
||||
(INV-006) so a contended write waits rather than failing SQLITE_BUSY immediately —
|
||||
WAL alone does not serialize concurrent writers."""
|
||||
```
|
||||
|
||||
```python
|
||||
# Web side (ratatoskr.web.server) — a server-side proxy to the configured affect-read URL.
|
||||
async def _affect_state_endpoint(request: Request) -> JSONResponse:
|
||||
"""GET /api/affect/{agent_id}. Supplies end_user_id from app.state.end_user_id
|
||||
(NEVER the browser); proxies to app.state.affect_read_url, re-encoding agent_id into
|
||||
the provider path (colon-id safe). See FN affect_state_endpoint."""
|
||||
|
||||
|
||||
def create_app(
|
||||
client_factory,
|
||||
*,
|
||||
end_user_id: str | None = None,
|
||||
bifrost_consumer_key: str | None = None,
|
||||
bifrost_visible_host: str | None = None,
|
||||
affect_read_url: str | None = None, # NEW: provider affect-read base URL
|
||||
) -> Starlette: ...
|
||||
```
|
||||
|
||||
```javascript
|
||||
// Pane side (static/index.html) — a NEW render path for the affect-emit shape.
|
||||
function renderAffectPane(snap) { /* pad + per-entity valence + emitted_at; header "affect snapshot" */ }
|
||||
async function loadAffect(agentId) { /* GET /api/affect/{id}; honest render or explicit empty-state */ }
|
||||
// loadPersona dispatches: colon-id agent -> loadAffect; else -> existing persona_state path.
|
||||
```
|
||||
|
||||
## Exception classes / error codes
|
||||
|
||||
No new Python exception types. Error states are JSON `{error_code}` bodies:
|
||||
|
||||
| Surface | error_code | Status | Meaning |
|
||||
|---|---|---|---|
|
||||
| provider read route | `missing_end_user_id` | 400 | `?end_user_id` absent |
|
||||
| provider read route | `no_affect_snapshot` | 404 | `store.get` returned None — no emit yet for (agent, user) |
|
||||
| web proxy | `affect_not_configured` | 400 | `affect_read_url` or server `end_user_id` unset |
|
||||
| web proxy | `affect_provider_unreachable` | 502 | network error reaching the provider read route |
|
||||
| web proxy | (passthrough) | provider status | provider 404/400 surfaced to the browser verbatim |
|
||||
|
||||
## Invariants
|
||||
|
||||
- **INV-001 (honest shape, no fabrication).** The pane renders ONLY fields the
|
||||
affect.emit snapshot actually carries — `pad{pleasure,arousal,dominance}`, per-entity
|
||||
`valence[]` (familiarity/regard/interaction_count), `emitted_at`. It MUST NOT
|
||||
synthesize Tier-1 `persona_state` fields (`dominant_emotion`, `baseline_pad`,
|
||||
`mood_drift`, `emotions_active`) — those are platform concepts Tier-3 structurally
|
||||
lacks (ADR-0009); a fabricated empty `mood_drift` reads as a bug, not an absence.
|
||||
- **INV-002 (end_user_id is server-supplied, never browser).** The web proxy reads
|
||||
`end_user_id` from `app.state.end_user_id` (RATATOSKR_END_USER_ID); it MUST NOT accept
|
||||
one from the browser body/query. Mirrors #17 INV-006 — a client cannot read an
|
||||
arbitrary end-user's affect partition.
|
||||
- **INV-003 (empty/missing is fail-visible).** No emit yet for (agent, user) → an
|
||||
EXPLICIT no-data state (provider 404 `no_affect_snapshot`; pane shows "no affect
|
||||
emitted yet for this agent / user"). NEVER a zeroed `pad:{0,0,0}` that looks like real
|
||||
PAD. A missing/unset `RATATOSKR_END_USER_ID` is a visible config error, not a silent
|
||||
empty result.
|
||||
- **INV-004 (op-feed + scope semantics untouched).** The read route is non-bifrost and
|
||||
sits OUTSIDE `opfeed._BIFROST_PATHS`, so the op-feed passes it through and emits no
|
||||
OpEvent for it. Deliverable 2 changes neither op-feed behavior nor store scope/affect
|
||||
semantics; the store stays conduit-opaque (it returns the stored blob verbatim).
|
||||
- **INV-005 (label honesty).** When the pane renders affect-store data it is labelled
|
||||
"affect" (e.g. "affect snapshot"), NOT "persona" — the data is affect, not Worldtree
|
||||
persona_state, and the label must not imply otherwise.
|
||||
- **INV-006 (SQLite busy_timeout).** Every affect-store connection sets
|
||||
`busy_timeout >= 5000ms`. WAL permits one writer + many readers but the default
|
||||
busy_timeout is 0 (a contended write returns SQLITE_BUSY immediately). This is prep
|
||||
for the future composite/standalone two-process topology; harmless single-process.
|
||||
- **INV-007 (read route on the store owner; pane decoupled via configured URL).** The
|
||||
read route is mounted by whatever app owns the affect store; the pane proxies to
|
||||
`RATATOSKR_AFFECT_READ_URL`, so it renders regardless of which endpoint a session is
|
||||
bound to. The deferred composite (Deliverable 1) will mount the SAME read route over
|
||||
the SAME `affect.db` — one shared helper, not a composite-only feature.
|
||||
- **INV-008 (colon-id round-trip).** A Tier-3 `agent_id` containing `:`
|
||||
(`ratatoskr:sindra`) round-trips browser → web (`encodeURIComponent`) → provider (web
|
||||
re-encodes via `quote(agent_id, safe='')` into the provider path) → `store.get`. Both
|
||||
hops are asserted end-to-end with a colon-id (Heid panel FM-7).
|
||||
|
||||
## Data flow
|
||||
|
||||
PANE LOAD (poll, no SSE): on session-start and after each turn-end, the pane calls
|
||||
`loadPersona(agentId)`. For a colon-id (Tier-3) agent it dispatches to `loadAffect` →
|
||||
`GET /api/affect/{agent_id}` → the web server supplies `end_user_id` server-side →
|
||||
proxies to `GET {affect_read_url}/affect/state/{quote(agent_id)}?end_user_id=…` → the
|
||||
provider reads `store.get(agent_id, end_user_id)` → snapshot JSON (200) or
|
||||
`no_affect_snapshot` (404) → `renderAffectPane` or the explicit empty-state. For a
|
||||
non-colon (Tier-1) agent, the existing `persona_state` path is unchanged.
|
||||
|
||||
## Function contracts
|
||||
|
||||
```contract
|
||||
FN build_affect_provider_app(store: RatatoskrAffectStore, heimdall_key: bytes, consumer_id: str = "ratatoskr") -> ASGIApp
|
||||
BRIEF: Compose the PAD read route + the bifrost affect app into one Starlette app, so the affect provider also serves the non-bifrost read.
|
||||
|
||||
PRE: [PRE-001 hard] store.affect_supported is True -- else ValueError (unchanged)
|
||||
PRE: [PRE-002 hard] heimdall_key is non-empty bytes -- else ValueError (unchanged)
|
||||
POST: [POST-001 return_value] returns the bifrost affect app with an added top-level GET /affect/state/{agent_id} route -- assert
|
||||
POST: [POST-002 return_value] /bifrost/handshake + /bifrost/affect-call remain top-level routes so the op-feed still matches them (INV-004) -- assert
|
||||
STEPS:
|
||||
1. app = build_affect_app(store, verifier, registration) as today (after the existing PRE guards)
|
||||
2. define _affect_state_route closing over store (see FN affect_state_route)
|
||||
3. app.add_route('/affect/state/{agent_id}', _affect_state_route, methods=['GET']); return app
|
||||
```
|
||||
|
||||
```contract
|
||||
FN affect_state_route(request) -> JSONResponse # provider-side, closes over store
|
||||
BRIEF: Read store.get(agent_id, end_user_id) and return the snapshot or an explicit no-data 404.
|
||||
|
||||
PRE: [PRE-001 hard] end_user_id query param present and non-empty -- else 400 missing_end_user_id (INV-003)
|
||||
POST: [POST-001 return_value] store.get returns a snapshot → 200 with the snapshot JSON verbatim (conduit-opaque) -- assert
|
||||
POST: [POST-002 return_value] store.get returns None → 404 {error_code:"no_affect_snapshot", agent_id, end_user_id} (INV-003) -- assert
|
||||
STEPS:
|
||||
1. agent_id = path_params['agent_id']; end_user_id = query_params.get('end_user_id')
|
||||
2. guard end_user_id (PRE-001); snap = store.get(agent_id, end_user_id)
|
||||
3. snap is None → 404 no_affect_snapshot; else 200 snap
|
||||
```
|
||||
|
||||
```contract
|
||||
FN affect_state_endpoint(request) -> JSONResponse # web-side proxy
|
||||
BRIEF: Proxy GET /api/affect/{agent_id} to the configured provider read URL, supplying end_user_id server-side, colon-id safe.
|
||||
|
||||
PRE: [PRE-001 hard] app.state.affect_read_url and app.state.end_user_id are set -- else 400 affect_not_configured (INV-002/003)
|
||||
POST: [POST-001 state_change] the upstream request carries end_user_id from app.state, NEVER from the browser (INV-002) -- assert
|
||||
POST: [POST-002 return_value] provider 200 → 200 with the snapshot; provider 404/400 → same status passthrough -- assert
|
||||
POST: [POST-003 exception] httpx.RequestError reaching the provider → 502 affect_provider_unreachable -- assert
|
||||
POST: [POST-004 side_effect] agent_id is quote()'d into the provider path so a colon-id round-trips (INV-008) -- assert
|
||||
STEPS:
|
||||
1. agent_id = path_params['agent_id']; read affect_read_url + end_user_id from app.state; guard (PRE-001)
|
||||
2. url = f"{affect_read_url}/affect/state/{quote(agent_id, safe='')}"
|
||||
3. GET url with params {end_user_id}; on RequestError → 502; else passthrough (status, json)
|
||||
```
|
||||
|
||||
## ERROR_ROUTING
|
||||
|
||||
| Wire (provider) | Web proxy → browser | Pane render |
|
||||
|---|---|---|
|
||||
| 200 snapshot | 200 snapshot | `renderAffectPane` (pad + valence + emitted_at) |
|
||||
| 404 `no_affect_snapshot` | 404 `no_affect_snapshot` | "no affect emitted yet for this agent / user" (INV-003) |
|
||||
| 400 `missing_end_user_id` | (server always supplies it) | n/a — config bug surfaced as `affect_not_configured` |
|
||||
| (provider unreachable) | 502 `affect_provider_unreachable` | "affect provider unavailable" |
|
||||
| (server misconfig) | 400 `affect_not_configured` | "affect telemetry not configured" |
|
||||
|
||||
## Acceptance
|
||||
|
||||
Unit (respx + in-process store):
|
||||
1. provider read route: seeded store → 200 with the exact snapshot; unseeded (agent,user) → 404 `no_affect_snapshot`; missing `end_user_id` → 400.
|
||||
2. provider app: `/bifrost/handshake` + `/bifrost/affect-call` still reachable after the read route is composed in (INV-004 / POST-002).
|
||||
3. web proxy: supplies server `end_user_id` (browser-supplied one is ignored); colon-id `ratatoskr:sindra` round-trips into the provider path (INV-008); provider-unreachable → 502; unconfigured → 400.
|
||||
4. op-feed: a request to `/affect/state/...` produces NO OpEvent (INV-004).
|
||||
5. busy_timeout: `open_affect_store` connection reports `busy_timeout == 5000` (INV-006).
|
||||
|
||||
Live-smoke (load-bearing, manual — the repo's posture): with the affect provider up and a
|
||||
prior emit for `ratatoskr:sindra` / the configured end_user, open the web pane on that agent
|
||||
→ the pane renders live PAD + valence + `emitted_at` from OUR store (no "telemetry isn't
|
||||
exposed"); on a fresh (agent,user) with no emit → the explicit empty-state, not a zeroed PAD.
|
||||
|
||||
## Out of scope / DEFERRED (anti-creep)
|
||||
|
||||
- **Deliverable 1 — composite :8392 endpoint** — bifrost-blocked (public `build_combined_app`,
|
||||
~v0.9.0, design locked) + FR-1 (Worldtree dual-plane dispatch, worldtree-dev consult in
|
||||
flight). Added by amendment when both resolve. This is the SAME issue, not a new one.
|
||||
- WT #289 mediated affect-read (`affect.fetch` over bifrost) — we own the store, read it
|
||||
directly; no Worldtree dependency.
|
||||
- Production hardening (TLS/RS256 on the read route; auth on /affect/state) — internal-LAN
|
||||
trust model, consistent with the rest of ratatoskr.web.
|
||||
- Real-time push of PAD into the pane — Tier-3 emits no affect SSE; v1 polls. A push channel
|
||||
would need a Worldtree-side affect SSE, out of scope.
|
||||
+1
-1
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
|
||||
|
||||
[project]
|
||||
name = "ratatoskr"
|
||||
version = "0.17.13"
|
||||
version = "0.17.14"
|
||||
description = "Worldtree Conversation API debug TUI — multi-pane observability dashboard"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.12"
|
||||
|
||||
@@ -20,6 +20,8 @@ from typing import Any
|
||||
from bifrost.affect import AffectIdempotencyConflict, AffectInvalidArguments
|
||||
from bifrost.consumer import ConsumerRegistration, build_affect_app
|
||||
from bifrost.reference_server import JwtVerifier
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import JSONResponse
|
||||
|
||||
_SHORT_RETRY_TTL_SECONDS = 300
|
||||
|
||||
@@ -110,7 +112,14 @@ class RatatoskrAffectStore:
|
||||
|
||||
def open_affect_store(db_path: str) -> RatatoskrAffectStore:
|
||||
"""Open the SQLite-backed affect store, creating the schema on first use."""
|
||||
conn = sqlite3.connect(db_path)
|
||||
# check_same_thread=False: the affect provider is an ASGI app; Starlette/uvicorn
|
||||
# may run a handler off the connection's creating thread (and TestClient always
|
||||
# does). Access stays serialized by the event loop, so this is safe.
|
||||
conn = sqlite3.connect(db_path, check_same_thread=False)
|
||||
# INV-006: state busy_timeout explicitly rather than lean on sqlite3's timeout=5.0
|
||||
# default — a contended write WAITS up to 5s instead of failing SQLITE_BUSY at once
|
||||
# (prep for the composite/standalone two-process topology).
|
||||
conn.execute("PRAGMA busy_timeout=5000")
|
||||
if db_path != ":memory:":
|
||||
conn.execute("PRAGMA journal_mode=WAL")
|
||||
conn.execute(
|
||||
@@ -143,4 +152,30 @@ def build_affect_provider_app(
|
||||
raise ValueError("heimdall_key must be non-empty bytes")
|
||||
verifier = JwtVerifier(algorithm="HS256", key_bytes=heimdall_key)
|
||||
registration = ConsumerRegistration(consumer_id=consumer_id)
|
||||
return build_affect_app(store=store, verifier=verifier, registration=registration)
|
||||
app = build_affect_app(store=store, verifier=verifier, registration=registration)
|
||||
|
||||
# Issue #18 (Deliverable 2): a NON-bifrost PAD read route added as a top-level
|
||||
# sibling of the bifrost routes (add_route, not Mount — keeps /bifrost/* top-level
|
||||
# so the op-feed's path check still matches them and skips this one). Internal-LAN
|
||||
# trust model: no JWT on the read.
|
||||
async def _affect_state_route(request: Request) -> JSONResponse:
|
||||
agent_id = request.path_params["agent_id"]
|
||||
end_user_id = request.query_params.get("end_user_id")
|
||||
if not end_user_id: # PRE-001: never look up against a None/empty partition
|
||||
return JSONResponse(
|
||||
{"error_code": "missing_end_user_id"}, status_code=400
|
||||
)
|
||||
snap = store.get(agent_id, end_user_id)
|
||||
if snap is None: # INV-003: explicit no-data, never a fabricated zeroed PAD
|
||||
return JSONResponse(
|
||||
{
|
||||
"error_code": "no_affect_snapshot",
|
||||
"agent_id": agent_id,
|
||||
"end_user_id": end_user_id,
|
||||
},
|
||||
status_code=404,
|
||||
)
|
||||
return JSONResponse(snap)
|
||||
|
||||
app.add_route("/affect/state/{agent_id}", _affect_state_route, methods=["GET"])
|
||||
return app
|
||||
|
||||
@@ -63,6 +63,11 @@ def main(argv: list[str] | None = None) -> int:
|
||||
# selects the plane; the consumer key + visible host live server-side only.
|
||||
bifrost_consumer_key = os.environ.get("RATATOSKR_BIFROST_CONSUMER_KEY")
|
||||
bifrost_visible_host = os.environ.get("RATATOSKR_PROVIDER_VISIBLE_HOST")
|
||||
# Issue #18 (Deliverable 2): the affect provider's read base URL (server→provider
|
||||
# hop on the same dev box) so the persona pane can render PAD/valence from OUR store.
|
||||
affect_read_url = os.environ.get(
|
||||
"RATATOSKR_AFFECT_READ_URL", "http://127.0.0.1:8390"
|
||||
)
|
||||
|
||||
# INV-001: lazy import. Users without [web] extras get a clean hint
|
||||
# instead of a raw ImportError. Scoped narrowly to the OPTIONAL
|
||||
@@ -102,6 +107,7 @@ def main(argv: list[str] | None = None) -> int:
|
||||
end_user_id=end_user_id,
|
||||
bifrost_consumer_key=bifrost_consumer_key,
|
||||
bifrost_visible_host=bifrost_visible_host,
|
||||
affect_read_url=affect_read_url,
|
||||
)
|
||||
|
||||
# Boot banner to stderr (so stdout stays clean for piping).
|
||||
|
||||
@@ -393,12 +393,36 @@ async def _persona_state_endpoint(request: Request) -> JSONResponse:
|
||||
return JSONResponse(snap, status_code=200)
|
||||
|
||||
|
||||
async def _affect_state_endpoint(request: Request) -> JSONResponse:
|
||||
"""GET /api/affect/{agent_id} → proxy the provider PAD read route. Supplies
|
||||
end_user_id SERVER-SIDE (never the browser, INV-002); proxies to the configured
|
||||
affect-read URL, re-encoding agent_id into the path (colon-id safe, INV-008).
|
||||
Per FN affect_state_endpoint (#18 Deliverable 2)."""
|
||||
from urllib.parse import quote
|
||||
|
||||
agent_id = request.path_params["agent_id"]
|
||||
affect_read_url = request.app.state.affect_read_url
|
||||
end_user_id = request.app.state.end_user_id
|
||||
if not (affect_read_url and end_user_id): # PRE-001: fail-visible, never silent
|
||||
return JSONResponse({"error_code": "affect_not_configured"}, status_code=400)
|
||||
url = f"{affect_read_url}/affect/state/{quote(agent_id, safe='')}"
|
||||
try:
|
||||
async with httpx.AsyncClient() as client:
|
||||
r = await client.get(url, params={"end_user_id": end_user_id})
|
||||
except httpx.RequestError:
|
||||
return JSONResponse(
|
||||
{"error_code": "affect_provider_unreachable"}, status_code=502
|
||||
)
|
||||
return JSONResponse(r.json(), status_code=r.status_code)
|
||||
|
||||
|
||||
def create_app(
|
||||
client_factory: Callable[[], httpx.AsyncClient],
|
||||
*,
|
||||
end_user_id: str | None = None,
|
||||
bifrost_consumer_key: str | None = None,
|
||||
bifrost_visible_host: str | None = None,
|
||||
affect_read_url: str | None = None,
|
||||
) -> Starlette:
|
||||
"""Construct the Starlette app — wire routes + state per FN create_app.
|
||||
|
||||
@@ -458,6 +482,7 @@ def create_app(
|
||||
Route("/api/agents", _agents_endpoint),
|
||||
Route("/api/sessions", _create_session_endpoint, methods=["POST"]),
|
||||
Route("/api/agents/{agent_id}/persona_state", _persona_state_endpoint),
|
||||
Route("/api/affect/{agent_id}", _affect_state_endpoint),
|
||||
Route("/api/turns/{session_id}", _submit_turn_endpoint, methods=["POST"]),
|
||||
Route("/api/turns/{session_id}/stream", _stream_turn_endpoint),
|
||||
Route("/api/turns/{session_id}/cancel", _cancel_turn_endpoint, methods=["POST"]),
|
||||
@@ -470,6 +495,9 @@ def create_app(
|
||||
# selects only the PLANE; the server constructs the bound session (INV-008).
|
||||
app.state.bifrost_consumer_key = bifrost_consumer_key
|
||||
app.state.bifrost_visible_host = bifrost_visible_host
|
||||
# Issue #18 (Deliverable 2): the provider affect-read base URL (server→provider hop,
|
||||
# same dev box) — distinct from the WT-visible host used for binding.
|
||||
app.state.affect_read_url = affect_read_url
|
||||
# INV-002: turn registry is in-process memory, keyed (session_id, turn_id)
|
||||
app.state.turn_registry = {}
|
||||
return app
|
||||
|
||||
@@ -679,8 +679,12 @@ function setPersonaStrip(snap) {
|
||||
bars += `<div class="pad"><span class="k">${k}</span>`
|
||||
+ `<span class="track"><span class="fill" style="left:${left}%;width:${width}%"></span></span></div>`;
|
||||
}
|
||||
// INV-001 (honest shape): only show a dominant_emotion when one is actually present
|
||||
// (Tier-1 persona_state). Affect snapshots have none — show agent + PAD bars, never a
|
||||
// fabricated "neutral" label.
|
||||
const emo = snap.dominant_emotion ? ` · <b>${esc(snap.dominant_emotion)}</b>` : "";
|
||||
strip.innerHTML =
|
||||
`<span class="emo">${esc(snap.agent_id || "?")} · <b>${esc(snap.dominant_emotion || "neutral")}</b></span>`
|
||||
`<span class="emo">${esc(snap.agent_id || "?")}${emo}</span>`
|
||||
+ `<span class="pad-bars">${bars}</span>`;
|
||||
strip.classList.add("show");
|
||||
}
|
||||
@@ -705,6 +709,10 @@ function renderPersonaPane(snap) {
|
||||
}
|
||||
|
||||
async function loadPersona(agentId) {
|
||||
// Tier-3 (colon-id) agents have no Worldtree persona_state (ADR-0009, Tier-1-only)
|
||||
// and emit no affect SSE — render live PAD/valence from OUR affect store instead
|
||||
// (issue #18 Deliverable 2).
|
||||
if (agentId.includes(":")) { return loadAffect(agentId); }
|
||||
try {
|
||||
const r = await fetch("/api/agents/" + encodeURIComponent(agentId) + "/persona_state");
|
||||
if (r.status === 200) {
|
||||
@@ -732,6 +740,59 @@ async function loadPersona(agentId) {
|
||||
}
|
||||
}
|
||||
|
||||
// Issue #18 (Deliverable 2): render the affect-emit snapshot from OUR store. HONEST
|
||||
// shape only — pad + per-entity valence + emitted_at; NO fabricated Tier-1 persona
|
||||
// fields (dominant_emotion / mood_drift), which Tier-3 structurally lacks (INV-001).
|
||||
// Labelled "affect", not "persona" (INV-005).
|
||||
function renderAffectPane(snap) {
|
||||
const row = (k, v) => `<div><span class="pk">${esc(k)}</span> <span class="pv">${esc(v)}</span></div>`;
|
||||
const head = (t) => `<div class="ph">${esc(t)}</div>`;
|
||||
const all = snap.valence || [];
|
||||
const shown = all.slice(0, 8); // bounded render — valence[] is unbounded in principle
|
||||
const valRows = shown.map((v) =>
|
||||
row(v.entity_id || "?",
|
||||
`familiarity ${JSON.stringify(v.familiarity)} · regard ${JSON.stringify(v.regard)}`
|
||||
+ ` · n=${JSON.stringify(v.interaction_count)}`)
|
||||
).join("");
|
||||
$("pane-persona").innerHTML =
|
||||
head("affect snapshot · " + (snap.agent_id || "?")) +
|
||||
`<div> </div>` + head("pad") +
|
||||
row("pleasure", JSON.stringify(snap.pad?.pleasure)) +
|
||||
row("arousal", JSON.stringify(snap.pad?.arousal)) +
|
||||
row("dominance", JSON.stringify(snap.pad?.dominance)) +
|
||||
`<div> </div>` + head("valence (" + all.length + ")") +
|
||||
(valRows || `<div class="empty">none</div>`) +
|
||||
`<div> </div>` + row("emitted_at", snap.emitted_at || "?");
|
||||
}
|
||||
|
||||
async function loadAffect(agentId) {
|
||||
try {
|
||||
const r = await fetch("/api/affect/" + encodeURIComponent(agentId));
|
||||
if (r.status === 200) {
|
||||
const snap = await r.json();
|
||||
renderAffectPane(snap);
|
||||
setPersonaStrip(snap); // pad bars are the live signal
|
||||
} else {
|
||||
let code = "";
|
||||
try { code = (await r.json()).error_code || ""; } catch (_) {}
|
||||
let msg;
|
||||
if (r.status === 404 && code === "no_affect_snapshot") {
|
||||
msg = "no affect emitted yet for this agent / user — take a turn; Tier-3 affect " +
|
||||
"lands in our store a few seconds after the turn ends.";
|
||||
} else if (code === "affect_not_configured") {
|
||||
msg = "affect telemetry not configured (RATATOSKR_AFFECT_READ_URL + RATATOSKR_END_USER_ID).";
|
||||
} else if (r.status === 502 && code === "affect_provider_unreachable") {
|
||||
msg = "affect provider unreachable (is the :8390 provider up?).";
|
||||
} else {
|
||||
msg = `affect unavailable (HTTP ${esc(r.status)}${code ? " · " + esc(code) : ""}).`;
|
||||
}
|
||||
$("pane-persona").innerHTML = `<div class="empty">${msg}</div>`;
|
||||
}
|
||||
} catch (e) {
|
||||
$("pane-persona").innerHTML = `<div class="empty">affect fetch failed</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- session lifecycle ----
|
||||
async function startSession() {
|
||||
const agentId = $("agent-picker").value;
|
||||
@@ -943,6 +1004,11 @@ async function submitPrompt() {
|
||||
state.eventSource = null; state.turnId = null;
|
||||
$("composer").classList.remove("streaming");
|
||||
setConn(cls === "error" ? "error" : "idle", cls === "error" ? "error" : "connected");
|
||||
if (cls === "done" && state.agentId) {
|
||||
// Tier-3 affect.emit is POST-TURN ASYNC — it lands in our store a couple seconds
|
||||
// after [done]. Refresh the pane on a short delay to catch the new PAD (issue #18).
|
||||
setTimeout(() => loadPersona(state.agentId), 2000);
|
||||
}
|
||||
$("prompt-input").focus();
|
||||
}
|
||||
es.addEventListener("done", (e) => terminal("done", "done", e));
|
||||
|
||||
@@ -46,6 +46,14 @@ def test_open_advertises_capability_and_schema():
|
||||
store._conn.execute("SELECT * FROM affect_idempotency")
|
||||
|
||||
|
||||
def test_open_sets_busy_timeout(tmp_path):
|
||||
"""INV-006: every connection sets busy_timeout>=5000ms (WAL's default is 0, so a
|
||||
contended write would fail SQLITE_BUSY immediately) — prep for the two-process
|
||||
composite/standalone topology."""
|
||||
store = open_affect_store(str(tmp_path / "affect.db"))
|
||||
assert store._conn.execute("PRAGMA busy_timeout").fetchone()[0] == 5000
|
||||
|
||||
|
||||
def test_reopen_existing_file_is_idempotent(tmp_path):
|
||||
db = str(tmp_path / "affect.db")
|
||||
open_affect_store(db) # first open creates schema
|
||||
@@ -163,6 +171,11 @@ def test_build_app_exposes_handshake_and_affect_routes():
|
||||
assert "/bifrost/handshake" in routes
|
||||
assert "/bifrost/affect-call" in routes
|
||||
assert "POST" in routes["/bifrost/affect-call"].methods # POST-001: the verb, not just the path
|
||||
# POST-002: bifrost routes remain REACHABLE (not merely registered) after the read
|
||||
# route is composed in via add_route — drive one without a JWT → routed (auth-
|
||||
# rejected), never 404.
|
||||
r = TestClient(app).post("/bifrost/affect-call", json={"operation": "affect.emit"})
|
||||
assert r.status_code != 404
|
||||
|
||||
|
||||
def test_build_app_rejects_non_advertising_store():
|
||||
@@ -228,3 +241,75 @@ async def test_parity_vs_reference_store_through_dispatch():
|
||||
assert await dispatch_affect_call(_env(other), ctx, ref) == await dispatch_affect_call(
|
||||
_env(other), ctx, mine
|
||||
)
|
||||
|
||||
|
||||
# --- PAD read route (issue #18 Deliverable 2) ---
|
||||
# Non-bifrost GET /affect/state/{agent_id}?end_user_id=… → store.get snapshot.
|
||||
|
||||
import json as _json
|
||||
|
||||
from starlette.testclient import TestClient
|
||||
|
||||
|
||||
def _affect_snapshot(agent: str = "ratatoskr:sindra", user: str = "vuong") -> dict:
|
||||
# The real affect.emit shape (verified live): pad + per-entity valence + emitted_at.
|
||||
return {
|
||||
"agent_id": agent,
|
||||
"end_user_id": user,
|
||||
"pad": {"pleasure": 0.1459, "arousal": 0.0796, "dominance": -0.0071},
|
||||
"valence": [
|
||||
{
|
||||
"entity_id": "ratatoskr",
|
||||
"entity_type": "human",
|
||||
"familiarity": 0.5886,
|
||||
"interaction_count": 8,
|
||||
"regard": 0.15,
|
||||
}
|
||||
],
|
||||
"emitted_at": "2026-06-18T15:58:12+00:00",
|
||||
}
|
||||
|
||||
|
||||
def _seed(store, snap: dict) -> None:
|
||||
blob = _json.dumps(snap, sort_keys=True, separators=(",", ":"))
|
||||
store._conn.execute(
|
||||
"INSERT INTO affect_snapshots (agent_id, end_user_id, snapshot_json, arrived_at) "
|
||||
"VALUES (?, ?, ?, ?)",
|
||||
(snap["agent_id"], snap["end_user_id"], blob, "0"),
|
||||
)
|
||||
store._conn.commit()
|
||||
|
||||
|
||||
def test_affect_state_route_returns_seeded_snapshot():
|
||||
"""tracer: seeded (agent, user) → 200 with the snapshot verbatim. Colon-id in the
|
||||
path exercises INV-008 at the provider hop."""
|
||||
store = open_affect_store(":memory:")
|
||||
snap = _affect_snapshot()
|
||||
_seed(store, snap)
|
||||
client = TestClient(build_affect_provider_app(store, heimdall_key=b"k"))
|
||||
r = client.get("/affect/state/ratatoskr:sindra", params={"end_user_id": "vuong"})
|
||||
assert r.status_code == 200
|
||||
assert r.json() == snap
|
||||
|
||||
|
||||
def test_affect_state_route_absent_returns_404_no_snapshot():
|
||||
"""INV-003: no emit yet for (agent, user) → explicit 404 no_affect_snapshot,
|
||||
NEVER a zeroed pad that reads as real data."""
|
||||
store = open_affect_store(":memory:")
|
||||
client = TestClient(build_affect_provider_app(store, heimdall_key=b"k"))
|
||||
r = client.get("/affect/state/ratatoskr:ghost", params={"end_user_id": "nobody"})
|
||||
assert r.status_code == 404
|
||||
body = r.json()
|
||||
assert body["error_code"] == "no_affect_snapshot"
|
||||
assert "pad" not in body # no fabricated PAD
|
||||
|
||||
|
||||
def test_affect_state_route_missing_end_user_id_returns_400():
|
||||
"""PRE-001: absent end_user_id query → 400 missing_end_user_id (not a silent
|
||||
no-snapshot lookup against a None partition)."""
|
||||
store = open_affect_store(":memory:")
|
||||
_seed(store, _affect_snapshot())
|
||||
client = TestClient(build_affect_provider_app(store, heimdall_key=b"k"))
|
||||
r = client.get("/affect/state/ratatoskr:sindra") # no end_user_id
|
||||
assert r.status_code == 400
|
||||
assert r.json()["error_code"] == "missing_end_user_id"
|
||||
|
||||
@@ -277,6 +277,41 @@ class TestOpFeedAffect:
|
||||
assert ev.req_summary == {} # conduit-opaque
|
||||
assert ev.resp_summary == {"stored": True}
|
||||
|
||||
async def test_pad_read_route_emits_no_opevent(self) -> None:
|
||||
"""INV-004 (#18 D2): the non-bifrost PAD read route is OUTSIDE _BIFROST_PATHS,
|
||||
so the op-feed passes it through and records NO OpEvent — observe is bifrost-
|
||||
only and the read path adds no plane attribution."""
|
||||
import json as _json
|
||||
|
||||
sink = _RecordingSink()
|
||||
app, store = _wrapped_affect_app(sink)
|
||||
blob = _json.dumps(
|
||||
{
|
||||
"agent_id": "ratatoskr:sindra",
|
||||
"end_user_id": "vuong",
|
||||
"pad": {"pleasure": 0.1, "arousal": 0.0, "dominance": 0.0},
|
||||
"valence": [],
|
||||
"emitted_at": "2026-06-18T00:00:00+00:00",
|
||||
},
|
||||
sort_keys=True,
|
||||
separators=(",", ":"),
|
||||
)
|
||||
store._conn.execute(
|
||||
"INSERT INTO affect_snapshots (agent_id, end_user_id, snapshot_json, arrived_at) "
|
||||
"VALUES (?, ?, ?, ?)",
|
||||
("ratatoskr:sindra", "vuong", blob, "0"),
|
||||
)
|
||||
store._conn.commit()
|
||||
transport = httpx.ASGITransport(app=app)
|
||||
async with httpx.AsyncClient(
|
||||
transport=transport, base_url="http://provider"
|
||||
) as client:
|
||||
resp = await client.get(
|
||||
"/affect/state/ratatoskr:sindra", params={"end_user_id": "vuong"}
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
assert sink.events == [] # op-feed recorded nothing for the non-bifrost route
|
||||
|
||||
|
||||
class TestInstrumentGuards:
|
||||
def test_unknown_plane_raises(self) -> None:
|
||||
|
||||
+117
-1
@@ -616,13 +616,15 @@ class TestCreateAppShape:
|
||||
"""create_app FN — route registration + state wiring (contract TESTS)."""
|
||||
|
||||
def test_routes_registered(self) -> None:
|
||||
"""routes_registered [tracer]: app.routes contains all 9 path patterns."""
|
||||
"""routes_registered [tracer]: app.routes contains all path patterns,
|
||||
including the #18 affect-read proxy."""
|
||||
from ratatoskr.web.server import create_app
|
||||
app = create_app(_mock_client_factory())
|
||||
paths = {getattr(r, "path", None) for r in app.routes}
|
||||
for expected in (
|
||||
"/", "/version", "/api/agents", "/api/sessions",
|
||||
"/api/agents/{agent_id}/persona_state",
|
||||
"/api/affect/{agent_id}",
|
||||
"/api/turns/{session_id}", "/api/turns/{session_id}/stream",
|
||||
"/api/turns/{session_id}/cancel",
|
||||
):
|
||||
@@ -902,3 +904,117 @@ class TestWebBifrostBind:
|
||||
resp = TestClient(app).post("/api/sessions", json={"agent_id": "mimir"})
|
||||
assert resp.status_code == 201
|
||||
assert "bifrost" not in resp.json()
|
||||
|
||||
|
||||
class TestAffectStateEndpoint:
|
||||
"""affect_state_endpoint FN — #18 Deliverable 2: web proxy to the provider PAD read."""
|
||||
|
||||
@respx.mock
|
||||
def test_happy_proxies_and_supplies_server_end_user_id(self) -> None:
|
||||
"""tracer: GET /api/affect/{id} → proxies to the configured provider read URL,
|
||||
supplying end_user_id SERVER-SIDE (INV-002); colon-id round-trips (INV-008)."""
|
||||
from ratatoskr.web.server import create_app
|
||||
|
||||
snap = {
|
||||
"agent_id": "ratatoskr:sindra",
|
||||
"pad": {"pleasure": 0.15, "arousal": 0.08, "dominance": -0.01},
|
||||
"valence": [{"entity_id": "ratatoskr", "familiarity": 0.59, "regard": 0.15}],
|
||||
"emitted_at": "2026-06-18T15:58:12+00:00",
|
||||
}
|
||||
route = respx.get(url__regex=r"http://prov:8390/affect/state/.+").mock(
|
||||
return_value=httpx.Response(200, json=snap)
|
||||
)
|
||||
app = create_app(
|
||||
_mock_client_factory(),
|
||||
end_user_id="vuong",
|
||||
affect_read_url="http://prov:8390",
|
||||
)
|
||||
resp = TestClient(app).get("/api/affect/ratatoskr:sindra")
|
||||
assert resp.status_code == 200
|
||||
assert resp.json() == snap
|
||||
assert route.calls.last.request.url.params["end_user_id"] == "vuong"
|
||||
# INV-008: the colon-id round-trips into the provider path — whether the wire
|
||||
# keeps %3A or normalizes it, it must unquote back to the exact agent_id.
|
||||
from urllib.parse import unquote
|
||||
seg = str(route.calls.last.request.url).split("/affect/state/")[1].split("?")[0]
|
||||
assert unquote(seg) == "ratatoskr:sindra"
|
||||
|
||||
@respx.mock
|
||||
def test_browser_supplied_end_user_id_is_ignored(self) -> None:
|
||||
"""INV-002: a browser-supplied end_user_id query is IGNORED; the server's
|
||||
configured partition is used."""
|
||||
from ratatoskr.web.server import create_app
|
||||
|
||||
route = respx.get(url__regex=r"http://prov:8390/affect/state/.+").mock(
|
||||
return_value=httpx.Response(200, json={"agent_id": "ratatoskr:sindra"})
|
||||
)
|
||||
app = create_app(
|
||||
_mock_client_factory(), end_user_id="vuong", affect_read_url="http://prov:8390"
|
||||
)
|
||||
TestClient(app).get("/api/affect/ratatoskr:sindra?end_user_id=attacker")
|
||||
assert route.calls.last.request.url.params["end_user_id"] == "vuong"
|
||||
|
||||
def test_unconfigured_returns_400(self) -> None:
|
||||
"""PRE-001: no affect_read_url → 400 affect_not_configured (no silent attempt)."""
|
||||
from ratatoskr.web.server import create_app
|
||||
|
||||
app = create_app(_mock_client_factory(), end_user_id="vuong") # no affect_read_url
|
||||
resp = TestClient(app).get("/api/affect/ratatoskr:sindra")
|
||||
assert resp.status_code == 400
|
||||
assert resp.json()["error_code"] == "affect_not_configured"
|
||||
|
||||
def test_no_end_user_configured_returns_400(self) -> None:
|
||||
"""PRE-001: affect_read_url set but server end_user_id unset → 400 (INV-003
|
||||
fail-visible, never a silent empty)."""
|
||||
from ratatoskr.web.server import create_app
|
||||
|
||||
app = create_app(_mock_client_factory(), affect_read_url="http://prov:8390")
|
||||
resp = TestClient(app).get("/api/affect/ratatoskr:sindra")
|
||||
assert resp.status_code == 400
|
||||
assert resp.json()["error_code"] == "affect_not_configured"
|
||||
|
||||
@respx.mock
|
||||
def test_provider_unreachable_returns_502(self) -> None:
|
||||
"""POST-003: a network error reaching the provider → 502 affect_provider_unreachable."""
|
||||
from ratatoskr.web.server import create_app
|
||||
|
||||
respx.get(url__regex=r"http://prov:8390/affect/state/.+").mock(
|
||||
side_effect=httpx.ConnectError("refused")
|
||||
)
|
||||
app = create_app(
|
||||
_mock_client_factory(), end_user_id="vuong", affect_read_url="http://prov:8390"
|
||||
)
|
||||
resp = TestClient(app).get("/api/affect/ratatoskr:sindra")
|
||||
assert resp.status_code == 502
|
||||
assert resp.json()["error_code"] == "affect_provider_unreachable"
|
||||
|
||||
@respx.mock
|
||||
def test_provider_404_passes_through(self) -> None:
|
||||
"""POST-002: provider no_affect_snapshot 404 surfaces to the browser verbatim."""
|
||||
from ratatoskr.web.server import create_app
|
||||
|
||||
respx.get(url__regex=r"http://prov:8390/affect/state/.+").mock(
|
||||
return_value=httpx.Response(404, json={"error_code": "no_affect_snapshot"})
|
||||
)
|
||||
app = create_app(
|
||||
_mock_client_factory(), end_user_id="vuong", affect_read_url="http://prov:8390"
|
||||
)
|
||||
resp = TestClient(app).get("/api/affect/ratatoskr:sindra")
|
||||
assert resp.status_code == 404
|
||||
assert resp.json()["error_code"] == "no_affect_snapshot"
|
||||
|
||||
@respx.mock
|
||||
def test_provider_400_passes_through(self) -> None:
|
||||
"""POST-002: a provider 400 (e.g. missing_end_user_id — unreachable in normal
|
||||
flow since the proxy always supplies it) still passes through verbatim."""
|
||||
from ratatoskr.web.server import create_app
|
||||
|
||||
respx.get(url__regex=r"http://prov:8390/affect/state/.+").mock(
|
||||
return_value=httpx.Response(400, json={"error_code": "missing_end_user_id"})
|
||||
)
|
||||
app = create_app(
|
||||
_mock_client_factory(), end_user_id="vuong", affect_read_url="http://prov:8390"
|
||||
)
|
||||
resp = TestClient(app).get("/api/affect/ratatoskr:sindra")
|
||||
assert resp.status_code == 400
|
||||
assert resp.json()["error_code"] == "missing_end_user_id"
|
||||
|
||||
Reference in New Issue
Block a user