Compare commits

...

6 Commits

Author SHA1 Message Date
vh 12cd8642fa feat(#20): worldtree-sdk adapter foundation — ratatoskr.wt (slice-1)
Slice-1 of the SDK cutover (docs/contracts/worldtree_sdk_cutover.contract.md):
the adapter chokepoint onto worldtree-sdk 1.0.0, unit-tested but not yet wired
to any surface (that is slice-2).

- build_client(base_url, *, api_key, admin_key=None, transport) constructs the
  single WorldtreeClient over a ratatoskr-owned injected httpx.AsyncClient.
  INV-CUT-1: the SDK is given the transport (_owns_client=False) and never closes
  it — proven by a test asserting aclose() leaves ratatoskr's transport open.
- translate_error implements the § Error map DEFAULT: SDK ApiError → the adapter's
  SessionApiFailed (carrying the SDK's parsed status/error_code/body); every
  discriminated WorldtreeError subclass passes through by identity. Route-specific
  rows land at their call-sites in later slices (the route is the discriminator).
- SessionApiFailed gains error_code vs the retiring sessions.py copy (extends it
  per the contract error-map row); the two coexist transiently and reconcile in
  slice-2 (DEC-4 incremental cutover — nothing wires the adapter this slice, so
  they never meet at runtime).

Deletes no hand-rolled path, so DEC-4's live-smoke bar does not apply yet.
Suite 541 green (534 + 7 new); mypy + ruff clean. Patch (internal foundation;
the cutover's minor bump is DEC-6 at slice-7 ship).
2026-07-18 23:59:33 -07:00
vh b7f4bc5e7c memory: /snapshot — slice-1 dep integrated + DEC-5 verified (29c4fda), adapter next
Re-snapshot for fresh context. Cutover slice-1 half-landed: worldtree-sdk==1.0.0
integrated + DEC-5 install-verified + committed (29c4fda), suite 534 green; the
ratatoskr.wt adapter (auth/transport split, error-map default) is the next step.
Substrate: unpushed cutover chain (e45640c contract, snapshot, 29c4fda dep) noted;
origin still at b1fbadd. Handoff aimed at the adapter. Index ~19 over soft cap;
archival deferred (guard-protected recents leave little to move — next run.)
2026-07-18 23:27:40 -07:00
vh 29c4fda12e build(deps): integrate worldtree-sdk==1.0.0 (DEC-5 verified) — #20 slice-1
Add the worldtree-sdk (Python) 1.0.0 consumer client to core deps + the gitea uv
source (reuses the existing bifrost gitea-index auth). DEC-5 precondition met: uv
resolves + installs it from the registry; WorldtreeClient constructs with an
injected httpx.AsyncClient and _owns_client=False (INV-CUT-1 transport ownership
confirmed live). httpx-sse retained until slice-7 teardown. Full suite 534 green —
the dep is inert until ratatoskr.wt wires it (next).

No version bump (dependency add, no runtime code consumes it yet). Refs #20.
2026-07-18 23:22:24 -07:00
vh 57fdc48e20 memory: /snapshot — worldtree-sdk cutover decided (#20), slice-1 next
Captures the SDK cutover as the active migration: contract done + heid-reviewed,
DEC-5 registry gate cleared, slice-1 foundation the next step. Plus ephemeral-Echo
(v0.21.2 #19) + reference-consumer parity arc in Recent decisions; tier3 model→role
deferred to slice-4 / worldtree-dev deploy flag. Handoff written for slice-1.
2026-07-18 23:19:21 -07:00
vh e45640c4da docs(contract): worldtree-sdk cutover — SDK-adapter contract (refs #20)
Consumer-layer cutover to worldtree-sdk (Python) 1.0.0: retire the hand-rolled
httpx wrappers (sessions/sse_client/tier3) behind a thin ratatoskr.wt adapter over
the SDK. Carries the 6 locked DECs (vor-cross'd with worldtree-codex), the route
map (21 wrappers -> SDK methods), the Error map table (heid-panel find:
route-as-discriminator, default -> SessionApiFailed), INV-CUT-1..5, and the 7-slice
plan. Adapter design: caller-injected transport (never closed), thin semantic error
adapter, Bifrost provider planes untouched.

heid-contract-review clean after fixups (3/3 error-map convergence + 6
clarifications folded in). No version bump (.contract.md, no code).

Refs #20.
2026-07-18 23:15:17 -07:00
vh b1fbadde3c docs(coverage): track v1 coverage against worldtree-sdk's 41-op ratified surface
worldtree-sdk v1.0.0 (wtsdk-dev, althing 01KXVF24WQD2T5ZCS49KKFCCMH) ratifies the
same 41-op surface from the identical OpenAPI 2.3.0 (sha 36148179601453a0) this
ledger already tracks — record it as the external parity authority. Ratatoskr is
the parallel Python/httpx reference-consumer (no TS adoption); the forthcoming
worldtree-sdk Python spine is the future consumable, noted as a repin candidate.

Fold in v0.21.2: POST /sessions row now notes ephemeral-Echo config passthrough
(role not model, W-4 cross-validated by the SDK); GET /capabilities row notes the
--whoami allowed_roles/default_role fix + spec v1.1. REST count unchanged (19/41 —
ephemeral is a depth enhancement to an already-covered route).

No version bump (docs-only coverage-ledger update).
2026-07-18 13:44:04 -07:00
7 changed files with 470 additions and 9 deletions
@@ -0,0 +1,218 @@
---
contract_version: "2.1"
module: "ratatoskr.wt"
purpose: "SDK-adapter cutover — replace ratatoskr's hand-rolled httpx consumer wrappers (sessions/sse_client/tier3) with a thin adapter over worldtree-sdk (Python) 1.0.0, deleting the old wrappers; CLI/TUI/web surfaces and caller-semantic exceptions preserved."
touches:
- src/ratatoskr/wt.py
- src/ratatoskr/cli.py
- src/ratatoskr/tui.py
- src/ratatoskr/web/server.py
scope: "Cut ratatoskr's CONSUMER client layer over from its hand-rolled httpx wrappers (sessions.py / sse_client.py / tier3.py / first_message.py) to consume worldtree-sdk (Python) 1.0.0. Replace the wrappers with a thin ratatoskr-owned adapter over the SDK; delete the old wrappers; keep the CLI / TUI / Starlette web surfaces and ratatoskr's caller-semantic exception surface. The Bifrost PROVIDER planes (memory/affect — where Worldtree dispatches INTO ratatoskr, ADR-0009) are consumer-orthogonal and untouched. Cutover decided by operator ruling 2026-07-18; design locked via vor-cross with worldtree-codex (thread 01KXWCWV3VKNR0HP74D2RCY0DC)."
depends_on:
- "worldtree-sdk (Python) == 1.0.0 # git tag python-v1.0.0; pin to the internal Gitea registry once published (DEC-5)"
used_by:
- "ratatoskr.cli"
- "ratatoskr.tui"
- "ratatoskr.web"
language: "python"
complexity: "high"
estimated_loc: 400 # net, rough — deletes (old wrappers) offset adds (adapter + call-site edits); sized per slice, not up front
confidence: 0.8
assumptions:
- "worldtree-sdk 1.0.0 is the GA Python consumer SDK ratatoskr's parity pass shaped; its resource surface (WorldtreeClient.sessions/agents/characters/me/capabilities/models/admin) covers all 21 of ratatoskr's covered routes. Verified against ~/development/worldtree-sdk @ python-v1.0.0."
- "Caller-injected transport is a first-class tested path (PY-INV-012): WorldtreeClient(base_url, auth=..., transport=my_httpx_async_client) uses ratatoskr's AsyncClient and NEVER closes it. Ratatoskr keeps base_url / bearer / User-Agent / timeout / web-app lifecycle ownership."
- "The SDK REST floor is an undiscriminated ApiError(error_code, message, status, body) (B-ERR-1/B-OPEN-3); hide-existence 404s are NOT distinguished by the SDK (B-ERR-4). Ratatoskr's caller-semantic mapping lives one layer up (DEC-2)."
---
# worldtree-sdk cutover — consumer-layer adapter contract
Single SDK-adapter contract per operator DEC-1. This is a migration contract: its
spine is a route-family slice plan, not a dense FN-block spec — each slice's
adapter FN detail is filled in at that slice's TDD (incremental migration; the
per-route SDK signatures are already mapped below).
## Locked design (operator-accepted 2026-07-18, post vor-cross)
- **DEC-1 — retire, don't repurpose (two-phase).** Normative authority for the
consumer wire transfers to THIS contract immediately (as of this file, #2 sessions
and #15 tier3 are superseded — no longer the spec of record); the contract FILES
are DELETED at slice-7 teardown, only after the code they specified is gone
(avoids both orphaning live code and leaving obsolete norms active mid-migration).
`first_message` is NOT retired — it stays a ratatoskr-owned usage contract at the
spec level (its preset / best-effort-timeout / swallow policy is local, not
SDK-owned). Repurposing the wire contracts would risk a shadow-normative copy of
SDK-owned semantics — the exact thing the cutover eliminates.
- **DEC-2 — thin semantic error adapter.** CLI/web/TUI keep ratatoskr's typed
exceptions; the adapter maps the SDK's `ApiError` floor → ratatoskr's
caller-semantic types (the SDK stays undiscriminated; hide-existence maps here).
- **DEC-3 — no shims (house rule).** Delete the old wrapper modules and update all
call-sites to the new adapter. No compatibility facade preserving old
module/function APIs (pre-1.0 no-backwards-compat rule).
- **DEC-4 — incremental + live-smoke, no soak.** Migrate one route-family per
slice, TDD each slice, and run a targeted LIVE smoke of that family against the
personal endpoint before deleting the replaced hand-rolled path. (The SDK's
fixture corpus proves the WIRE; the live smoke proves ratatoskr's
presenter/adapter/env-wiring survived the dependency inversion.)
**Smoke acceptance bar (the minimum that lets an old path be deleted):** drive
each route in the family's primary flow END-TO-END through the ratatoskr surface
(CLI/web) — not the wrapper directly — against the personal endpoint under the
real consumer key, and OBSERVE the expected success (a created session, a streamed
turn that renders, a persona write that reads back), not merely a non-crash. A
smoke that only asserts "no exception" does NOT clear the bar. **Smoke vs. soak
boundary:** a smoke is a single pass of the family's flows at deletion time; a
(forbidden) soak is a sustained dual-path parallel-run — do the former, not the
latter.
- **DEC-5 — wait for the registry.** Pin `worldtree-sdk == 1.0.0` from the internal
Gitea registry once published (verify the uv install first); use the
`python-v1.0.0` git tag only if the registry lags. Contract-drafting is NOT
gated (SDK source is inspectable); IMPLEMENTATION pin is.
- **DEC-6 — minor bump at ship.** The cutover ships as a minor (architecture-cutover
milestone; pre-1.0 breaking-internal) — requires explicit operator approval at
ship time, not now.
## Adapter design
- **`ratatoskr.wt`** — a thin adapter module owning ONE `WorldtreeClient`, built
with ratatoskr's own `httpx.AsyncClient` injected (`transport=`), ratatoskr's
`auth`/`admin_auth` providers, and the ratatoskr User-Agent. It exposes
ratatoskr-semantic call surfaces the presenters already expect, and translates
SDK errors → ratatoskr exceptions (DEC-2).
- **Transport ownership (INV-CUT-1 [hard]):** the injected `AsyncClient` is
ratatoskr-owned; `WorldtreeClient.aclose()` / `async with` exit must NOT close
it (SDK `_owns_client=False` on injection). Ratatoskr owns the client lifecycle
exactly as today.
- **Error boundary (INV-CUT-2 [hard]):** ratatoskr's caller-semantic exceptions
are raised by the adapter, mapping from the SDK where the SDK already
discriminates (`AgentNotAvailable`, `TurnLaunchUnavailable`, `SessionRetired`,
`Cancel*`, `Resume*`, `Malformed*`) and from `ApiError(status=..., error_code)`
on a KNOWN route otherwise — including the hide-existence 404 →
`AuthoredHistoryUnavailable` (labeling a call we made, NOT capability-probing).
- **Provider boundary (INV-CUT-3 [hard]):** the Bifrost provider planes stay
hand-rolled and are never routed through the SDK. The Bifrost-BOUND
`sessions.create` (consumer-side, `bifrost=` + consumer-key auth) DOES go through
the SDK and stays consumer-layer.
- **Import boundary (INV-CUT-4 [hard]):** `tests/test_no_worldtree_imports.py`
stays; the boundary becomes "no Worldtree SOURCE imports", with `worldtree_sdk`
the allowed client dependency.
## Invariants
- **INV-CUT-1 [hard]** — Ratatoskr owns the injected `httpx.AsyncClient` lifecycle;
the SDK never closes it (`_owns_client=False` on transport injection).
- **INV-CUT-2 [hard]** — The adapter raises ratatoskr's caller-semantic exceptions
per the explicit **§ Error map** table below — mapping from the SDK's discriminated
errors (passthrough) and from `ApiError` by the ROUTE that raised it (the route is
the discriminator, never the body). Every `ApiError` is mapped; the default is
`SessionApiFailed`. No route invents semantics the table doesn't list.
- **INV-CUT-3 [hard]** — The Bifrost PROVIDER planes never route through the SDK;
the Bifrost-BOUND `sessions.create` does (consumer-side).
- **INV-CUT-4 [hard]** — The no-Worldtree-SOURCE-import boundary holds
(`worldtree_sdk` allowed); `tests/test_no_worldtree_imports.py` enforces it.
- **INV-CUT-5 [hard]** — Each slice runs a LIVE smoke of its route family before the
replaced hand-rolled path is deleted (DEC-4); no old path is removed unproven.
## Route map — ratatoskr wrapper → SDK method (grounded @ python-v1.0.0)
| Ratatoskr wrapper (retiring) | SDK method | SDK return |
|---|---|---|
| `create_session` | `sessions.create(...)` | `SessionInfo` |
| `list_sessions` | `sessions.list(limit, cursor)` | page |
| `stream_turn` | `sessions.stream_turn(...)` (resilient) / `stream_turn_raw` (single) | `AsyncIterator[Event]` |
| `reconnect_turn` | folded into `sessions.stream_turn` auto-resume | — |
| `cancel_turn` | `sessions.cancel_turn(...)` | `CancelResult` |
| `get_session_messages` | `sessions.messages(id)` | open-world |
| `get_session_tools` | `sessions.tools(id)` | `SessionTools` |
| `set_persona_state` | `sessions.set_persona_state(id, PadState)` | None |
| `write_authored_history` | `sessions.write_history(...)` | authored-turn |
| `get_persona_state` | `agents.persona_state(agent_id)` | `AgentPersonaState` |
| `list_agents` | `agents.list()` | `AgentList` |
| `define_agent` | `agents.define(...)` | `DefinedAgent` |
| `patch_agent` | `agents.patch(id, changes)` | `PatchedAgent` |
| `delete_agent` | `agents.delete(id)` | None |
| `get_me` | `me.get()` | `MeInfo` |
| `get_capabilities` | `capabilities.get()` | `Capabilities` |
| `list_character_models` | `models.available_for_characters()` | `ModelsAvailable` |
| `create_character` | `characters.create(...)` | `CreatedCharacter` |
| `get_character_state` | `characters.state(id)` | `CharacterState` |
| `delete_character` | `characters.delete(id)` | `CharacterDeleteResult` |
| `get_session_bifrost` | `admin.sessions.bifrost(id)` | `BifrostInspection` |
| `stream_admin_events` | `admin.stream_events(...)` | `AsyncIterator[AdminEvent]` |
Note: SDK returns are typed `shapes.*`; per the parity pass the freeform reads
(`SessionTools`, `BifrostInspection`, capabilities) are deliberately open-world in
the Python spine. The adapter PASSES THESE THROUGH unmodified (does not normalize);
presenters read them as mappings, tolerant of wire drift. If an open-world read is
malformed the presenter degrades (never crashes) — same posture as the existing
`_format_whoami` hardening.
## Error map (INV-CUT-2 — the explicit table)
**The ROUTE is the discriminator, not the error body** (labeling a call we made, NOT
capability-probing — B-ERR-4). A 404 is mapped by which method raised it; the adapter
NEVER sniffs the body to decide whether something exists. Authored-history is
currently the ONLY hide-existence route (per Worldtree B-ERR-4); if Worldtree adds
others, they get their own row here — the default is NOT a general "any 404 → hidden".
| SDK raises (from) | Adapter maps to |
|---|---|
| SDK `AgentNotAvailable` / `TurnLaunchUnavailable` / `SessionRetired` (stream-open) | ratatoskr `AgentNotAvailable` / `TurnLaunchUnavailable` / (retired → `SessionApiFailed`) — same names, passthrough |
| SDK `ConnectionDropped` (mid-stream) | `SseConnectionDropped` |
| SDK `ResumeError` subclasses (in resilient stream) | resilient `stream_turn` absorbs; terminal → `SseConnectFailed` |
| SDK `Cancel*` (cancel_turn) | folded into `CancelResult`; late-cancel race (B-CAN-3) returns `cancelled=False`, never raises |
| `ApiError(404)` on `sessions.create` | `AgentNotFound` |
| `ApiError(404)` on `sessions.write_history` | `AuthoredHistoryUnavailable` (hide-existence) |
| `ApiError(422 cursor_invalid)` on `sessions.list` | `InvalidCursor` |
| `ApiError(502 bifrost_handshake_failed)` on bound `sessions.create` | `BifrostHandshakeFailed` |
| **`ApiError` (any other status/route) — the default** | `SessionApiFailed(status, error_code, body)` |
The default row is load-bearing: any `ApiError` not matched above surfaces as the
generic `SessionApiFailed` carrying the raw `status`/`error_code`/`body` — the
adapter does NOT invent per-route semantics the contract doesn't list, and does NOT
leave an `ApiError` un-mapped. Each slice adds/confirms its route's rows here before
the old path is deleted.
## Slice plan (incremental, DEC-4)
Each slice: wire the family through `ratatoskr.wt` → update call-sites → TDD →
LIVE smoke against the personal endpoint → delete the replaced hand-rolled path →
re-anchor its coverage-map rows.
1. **Foundation**`ratatoskr.wt` module + injected `WorldtreeClient` + auth
providers + the error-adapter skeleton (the § Error map's default `ApiError`
`SessionApiFailed` rule + the discriminated-error passthrough). No USER-VISIBLE
behavior change (imports/construction change; the skeleton is unit-tested but
unexercised by any surface until slice 2). Done = `ratatoskr.wt` importable, the
client constructs with an injected transport, and the error-map default is unit-
covered.
2. **Sessions/turn** — create/list/messages/tools/cancel + the turn STREAM + the
Bifrost-bound create. The turn presenter wires the resilient `sessions.stream_turn`
(auto-resume — this ABSORBS the old `reconnect_turn`, which is deleted this slice
with its call-sites); `stream_turn_raw` is available for a single-attempt caller
but is NOT the presenter default. (Highest-traffic; the SSE presenter is the
riskiest wiring.)
3. **Persona + authored-history** — set_persona_state (PadState) + write_history
(hide-existence mapping) + first_message presets (stay ratatoskr-owned OVER the
SDK method).
4. **Agents (Tier-3)** — list/get/define/patch/delete/persona_state. (Folds in the
pending `model``role` cutover — see [[project-tier3-agents-model-to-role-pending]].)
5. **Characters + me/capabilities/models** — the remaining consumer reads.
6. **Admin** — admin.sessions.bifrost + admin.stream_events (admin_auth).
7. **Teardown** — delete residual hand-rolled modules; drop `httpx-sse` (SDK owns
SSE parsing); retire contracts #2/#15; final coverage-map re-anchor; minor bump
(DEC-6, operator approval).
## Out of scope
- Bifrost PROVIDER planes (memory/affect) — hand-rolled, ADR-0009, untouched.
- CLI / TUI / Starlette web surfaces — their EXTERNAL BEHAVIOR is preserved (their
call-sites DO change — they're updated to the new adapter per `touches:`; what's
invariant is the observable behavior, not the code).
- The four parked post-v1 SDK ergonomics items (replayed:bool, raw-dict persona
escape hatch, list_all iterator, split session types) — coordinated post-v1 lane
with wtsdk-dev, not this cutover.
## Coverage-map re-anchor
`docs/coverage-map.md` shifts from "hand-rolled route exists + live-proven" to
"SDK method wired and exercised by a ratatoskr surface"; excluded-by-design rows
stay explicit. Re-anchored per slice as each family lands.
+19 -2
View File
@@ -23,6 +23,23 @@ anchors against the frozen machine-readable artifacts, NOT the prose markdown:
| Conversation SSE events | `conversation-api-sse-events.schema.json` (sha `9deeebf4…`) — **11 discriminated event types** | **client** |
| Bifrost wire (consumer protocol) | wire **v0.6** STABLE/FROZEN (`bifrost==1.0.0`) — memory + affect planes | **provider** (Worldtree dispatches into us) |
> **External ratification — worldtree-sdk v1.0.0 (wtsdk-dev, 2026-07-18, althing
> thread `01KXVF24WQD2T5ZCS49KKFCCMH`).** The TypeScript v0 consumer SDK wires all
> **41 ops as typed methods** from the **same OpenAPI 2.3.0** (sha
> `36148179601453a0` — matches our vendored pin exactly), so it is the independent
> parity authority for the surface this ledger tracks. Ratatoskr does **not** adopt
> the SDK — we are the parallel **Python/httpx** reference-consumer of the identical
> surface (no TS/npm surface exists to pin it into). Cross-check corroboration: the
> SDK's **W-4** (send `config.role`, response echoes `model` unremapped) matches what
> ratatoskr shipped in **v0.21.2** for ephemeral-Echo create.
>
> **Future consumable — worldtree-sdk Python spine (wtsdk-dev, next milestone).** The
> TS v1 surface is our parity *checklist*; the forthcoming **Python spine** (same
> behavioral-spec + fixture corpus, TS decisions kept Python-portable per their
> surface-design §6) is what ratatoskr would actually *consume* when it lands.
> wtsdk-dev slots ratatoskr as **THE reference consumer** whose coverage column
> drives that spine — a future repin candidate, not yet available.
> **Pin drift (finding P-1) — REMEDIATED 2026-06-30.** Ratatoskr formerly
> vendored only the **prose markdown** (`docs/conversation-api-spec.md`), which
> is byte-identical to live Worldtree's but frozen at v0.35.16-era content (last
@@ -67,7 +84,7 @@ sub-gap).
| Endpoint | Status | Where consumed | Note |
|---|---|---|---|
| `POST /sessions` | ✅ | `sessions.py:307``cli.py:482`,`tui.py:1508`,`web/server.py:155` | + `end_user_id`, `bifrost` binding; 404→AgentNotFound, 502→BifrostHandshakeFailed |
| `POST /sessions` | ✅ | `sessions.py` `create_session``cli.py`,`tui.py`,`web/server.py` | + `end_user_id`, `bifrost` binding; 404→AgentNotFound, 502→BifrostHandshakeFailed. **v0.21.2 (#19): ephemeral-template (Echo) create**`config` passthrough (`--system-prompt`), `role` not `model` (W-4), `kind`/`config` captured; 422 ephemeral_requires_config now reachable-and-handled. Depth enhancement to an already-covered route — count unchanged |
| `POST /sessions/{id}/messages` (turn stream, SSE) | ✅ | `sse_client.py:484` `stream_turn` → cli/tui/web | the primary surface; 409→AgentNotAvailable, 503→TurnLaunchUnavailable (b2 #331) |
| `POST /sessions/{id}/history` (authored-history-write, #347) | ✅ | `sessions.py:583` `write_authored_history``cli.py:758` `--seed-first-message` | v1: author=assistant, effects=none, per-session idempotency; 404→AuthoredHistoryUnavailable (hide-existence: feature-absent, never probe); 409/422 mapped. **LIVE-PROVEN 2026-07-06** on personal :8081 (grant applied via a rule-based Heimdall allow, worldtree-dev): create mimir session → seed → **201** (seq=0, phase=seeded, turn_id=1798) → GET /messages reads it back as a plain role=assistant turn (model-invisible provenance confirmed). Hide-404 for ungranted is unit+probe covered |
| `GET /sessions/{id}/messages` (history) | ✅ | `sessions.py:635` `get_session_messages``cli.py:758` `--seed-first-message` read-back | un-deferred as the #347 seed read-back — confirms model-invisible provenance (a seed reads back as a normal `role=assistant` turn) |
@@ -78,7 +95,7 @@ sub-gap).
| `PATCH /agents/{id}` | ✅ | `tier3.py:219``_run_patch` | Tier-3 mutate (system_prompt/model) |
| `DELETE /agents/{id}` | ✅ | `tier3.py:242``_run_delete` | Tier-3 hard-delete |
| `GET /me` | ✅ | `sessions.py:411` `get_me``cli.py` `--whoami` | identity/whoami probe; 401→SessionApiFailed |
| `GET /capabilities` | ✅ | `sessions.py:428` `get_capabilities``cli.py` `--whoami` | Echo ephemeral-template discovery |
| `GET /capabilities` | ✅ | `sessions.py` `get_capabilities``cli.py` `--whoami` | Echo ephemeral-template discovery. **v0.21.2: `--whoami` renderer reads `allowed_roles`/`default_role`** (was the dead `allowed_models`/`default_model`) + tolerates malformed caps; matches conversation-api-spec **v1.1** (`b4a278c`) |
| `GET /sessions/{id}/tools` | ✅ | `sessions.py:411` `get_session_tools``tui.py` `_hydrate_session_tools` | owner-scoped tool inventory in the TUI Tools pane (#183) |
| `GET /admin/sessions/{id}/bifrost` | ✅ | `sessions.py:428` `get_session_bifrost``tui.py` `_hydrate_bifrost_state` | admin-scoped BifrostState pane (#176); admin key (`RATATOSKR_ADMIN_API_KEY`); live-auth-proven |
| `GET /admin/events` (SSE) | ✅ | `sse_client.py` `stream_admin_events``tui.py` `_stream_admin_events` | admin lifecycle SSE stream (#11), session-filtered AdminEvents pane; admin key; live-auth-proven |
+37 -4
View File
@@ -46,6 +46,33 @@ upstream API key stays server-side (INV-003).
_As of 2026-07-18 (evening):_
**🔨 ACTIVE MIGRATION — worldtree-sdk cutover (issue #20), starting slice-1.** Operator ruled ADOPT
(2026-07-18): ratatoskr cuts its CONSUMER client layer over to consume **worldtree-sdk (Python) 1.0.0**
retire the hand-rolled httpx wrappers (`sessions`/`sse_client`/`tier3`) behind a thin `ratatoskr.wt`
adapter over the SDK. Both TS + Python SDK 1.0.0 are GA (**Python live + pip-installable on the gitea
PyPI** — DEC-5 gate cleared). Ratatoskr's own **parity pass shaped the Python spine** (open-world reads,
caller-injected transport, per-wire role/model). Design locked (6 DECs, vor-cross'd with worldtree-codex,
heid-panel-reviewed → error-map table added); contract `docs/contracts/worldtree_sdk_cutover.contract.md`
(committed `e45640c`). **SLICE-1 IN PROGRESS:** ✅ dep integrated + DEC-5 verified + committed (`29c4fda`) — `worldtree-sdk==1.0.0`
installs from the gitea registry (reuses bifrost's index auth, NO new token; core dep + `[tool.uv.sources]`),
`WorldtreeClient` constructs with an injected transport (`_owns_client=False`, INV-CUT-1 confirmed live),
suite 534 green. **NEXT = the adapter** `src/ratatoskr/wt.py` (TDD): `build_client(base_url, *, api_key,
admin_key, transport)``WorldtreeClient(auth=, admin_auth=, transport=)` (DESIGN CARE: SDK does per-request
auth via the providers; our injected `httpx.AsyncClient` carries base_url/UA/timeout, NOT the Authorization
header — read the SDK `client.py` @ `~/development/worldtree-sdk` for the split, INV-CUT-1) + `translate_error`
DEFAULT (SDK `ApiError``SessionApiFailed`, discriminated `WorldtreeError` subclasses passthrough; route-specific
rows come in later slices). Unit-test; NO surface wiring (slice-2). Then slices 2-7 (route-family + deletions,
live-smoke per slice). Scope: consumer layer ONLY;
Bifrost provider planes untouched. Multi-session grind. Full design → auto-memory
`project_worldtree_sdk_cutover`. This SUPERSEDES the #371 "repin rides the later Python milestone" framing
below (that milestone shipped; we're adopting, not just repinning).
**⏸️ DEFERRED — tier3 agents `model``role` (scope B), on worldtree-dev's deploy flag.** WT renames the
agents-RESPONSE selector `model``role` (spec 1.2, commit `387c67b`, NOT yet deployed). `_parse_tier3_agent_info`
reads `body["model"]` → KeyErrors post-deploy. Operator chose scope B (full tier3 `model``role` incl.
contract #15 + CLI `--model``--role`). Implement ON the deploy flag, not before (breaks the current demo);
folds into cutover slice-4. Auto-memory `project_tier3_agents_model_to_role_pending`.
**✅ RESOLVED — the "app product" workstreams leave Rata entirely (operator 2026-07-18).**
**No arbo fork, no SillyTavern-on-Rata** — a NEW repo (template-dev standing up) takes over BOTH
app-product ideas. Rata does NOT fork into anything and is NOT the base for any chat / image-gen app.
@@ -88,10 +115,13 @@ Full record → `persistent-memory.d/2026-07-18-368-silo-test-passed.md`. Siblin
(2) R39 Phase-2 **matched-quartets rebuild** (confirmatory, "whenever"); (3) bifrost **snapshot-cursor
adoption** (ruled normative, not blocking → `persistent-memory.d/2026-07-16-bifrost-cursor-conformance.md`).
**Substrate / environment:** branch `main` at **v0.21.1**, **PUSHED to origin 2026-07-18** (incl.
tier3 b127-role adaptation `860e0d5`, #368 memory snapshots + silo work, the contract-drift fix
`4bd9abd`, and this snapshot); origin `git@gitea.phasefinal.com:vh/ratatoskr.git`. bifrost
**`==1.1.4`** / wire v0.7; WT openapi vendored 2.3.0; **suite 644 green**. Personal WT on **b127**
**Substrate / environment:** branch `main` at **v0.21.2**. **origin at `b1fbadd`** (pushed 2026-07-18:
canonical syncs `5d06a27`/`80c8d58`, ephemeral-Echo `c7016f2` #19, coverage-map→SDK-surface `b1fbadd`).
**UNPUSHED local commits** (cutover work — operator hasn't pushed): cutover contract `e45640c` #20, the
`memory:` snapshot, dep-integration `29c4fda` (worldtree-sdk==1.0.0), + this snapshot — **push is the
operator's call**. origin `git@gitea.phasefinal.com:vh/ratatoskr.git`. **NEW core dep: `worldtree-sdk==1.0.0`**
(gitea PyPI, `[tool.uv.sources]`). bifrost **`==1.1.4`** / wire v0.7; WT openapi vendored 2.3.0,
**conversation-api-spec re-synced to v1.1** (`b4a278c`); **suite 534 green**. Personal WT on **b127**
(`http://10.250.50.152:8081`; #368 silo + #364 promotion-hygiene live both instances). The combined
**:8392** provider (memory+affect) + **:8765** web are THE surfaces, dev-box BACKGROUND SHELLS —
restart via `scratchpad/relaunch_by_pid.py <pid>` (pid via `ss -ltnp | grep <port>`). `env.sh` sets
@@ -238,6 +268,9 @@ decision. Captures rationale that won't be obvious from code alone.
- `[2026-07-18]` **issue #1 contract drift fixed (`4bd9abd`) — SSE event vocab re-canonicalized: added `awaiting_llm_first_token` (#201) + `affect_update` (#204) to the Event union + TESTS (both were parsed by `_envelope_for_type` and tested in `test_sse_client.py`, but never in #1's contract; surfaced by the #371 parity pass). Contract-only, no bump.**
- `[2026-07-18]` **Both app products (arbo image-gen + SillyTavern chat) leave Rata to a NEW repo (template-dev standing up); Rata does NOT fork and is NOT the app base.** Reverts Rata to its core — Worldtree debug-observability surface + Bifrost reference impl + Conversation-API SDK seed/future-consumer. Supersedes the 2026-07-17 'fork Rata for arbo' NEXT-MAJOR plan.
- `[2026-07-18]` **ephemeral-template (Echo) create SHIPPED (`v0.21.2`, `c7016f2`, #19)**`config` passthrough + `--system-prompt` + `SessionInfo.kind/config` + `--whoami` roles fix. Diagnosed from the ignored `session_api_failed` startup line; role/model drift resolved w/ worldtree-dev (spec re-synced v1.1). TDD + heid contract-review + bug-hunt.
- `[2026-07-18]` **Rata = THE reference consumer of the worldtree-sdk Python spine** — parity pass (12 grounded findings) shaped its contract BEFORE build (open-world reads, caller-injected transport, per-wire role/model — adopted); coverage-map re-anchored to the SDK's 41-op ratified surface (`b1fbadd`); 4 ergonomics items parked post-v1 with wtsdk-dev.
- `[2026-07-18]` **worldtree-sdk cutover DECIDED — adopt the Python SDK for the consumer client layer** (operator, overriding "stay hand-rolled"). Issue #20; contract `docs/contracts/worldtree_sdk_cutover.contract.md` (`e45640c`, vor-cross'd + heid-reviewed); auto-memory `project_worldtree_sdk_cutover`. Consumer layer only, Bifrost provider untouched; slice-1 foundation next. See in-flight.
_65 older entries (2026-05-* debug-TUI/web era + the 2026-06-14 → 06-18 Bifrost-provider build / #17+#18 / #295-296 era) archived to archival-memory.md._
+4 -2
View File
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
[project]
name = "ratatoskr"
version = "0.21.2"
version = "0.21.3"
description = "Worldtree Conversation API debug console (web + headless CLI) — multi-pane observability"
readme = "README.md"
requires-python = ">=3.12"
@@ -16,7 +16,8 @@ keywords = ["worldtree", "debug", "sse", "web", "observability"]
# See docs/design-brief.md §3 (httpx-sse).
dependencies = [
"httpx>=0.27",
"httpx-sse>=0.4",
"httpx-sse>=0.4", # #20 slice-7 teardown drops this once the SDK owns SSE parsing
"worldtree-sdk==1.0.0", # #20 cutover: the consumer client layer (gitea PyPI); slices retire the hand-rolled wrappers behind ratatoskr.wt
]
[project.optional-dependencies]
@@ -70,6 +71,7 @@ url = "https://gitea.phasefinal.com/api/packages/vh/pypi/simple/"
[tool.uv.sources]
bifrost = { index = "gitea" }
worldtree-sdk = { index = "gitea" }
[tool.hatch.build.targets.wheel]
packages = ["src/ratatoskr"]
+92
View File
@@ -0,0 +1,92 @@
"""worldtree-sdk adapter — ratatoskr's single chokepoint onto the Conversation-API SDK.
Slice-1 foundation of the SDK cutover (issue #20;
`docs/contracts/worldtree_sdk_cutover.contract.md`). A thin adapter that owns ONE
`WorldtreeClient`, built over ratatoskr's own injected `httpx.AsyncClient`
transport, and translates the SDK's error floor into ratatoskr's caller-semantic
exceptions. Two hard invariants anchor it:
* **INV-CUT-1** — ratatoskr owns the injected transport's lifecycle; the SDK is
given it as `transport=` (so `_owns_client=False`) and MUST NOT close it.
* **INV-CUT-2** — the adapter raises ratatoskr's caller-semantic exceptions; the
ROUTE is the discriminator (never the error body).
This slice ships only the construction chokepoint (`build_client`) and the error
adapter's DEFAULT rule (`translate_error`: `ApiError` → `SessionApiFailed`, every
discriminated `WorldtreeError` subclass passing through unchanged). Route-specific
error rows (`AgentNotFound`, `InvalidCursor`, `AuthoredHistoryUnavailable`, ...)
and the CLI / web / TUI surface wiring land in later slices.
Transient-migration note (DEC-4, incremental cutover): a same-named
`SessionApiFailed` still lives in the retiring `ratatoskr.sessions` wrapper and
serves the old hand-rolled path until slice-2 deletes it. No surface wires the
adapter in this slice, so the two never meet at runtime; slice-2 reconciles them
(deletes the `sessions.py` copy, points presenters at this one, which additionally
carries the SDK's parsed `error_code`).
"""
from __future__ import annotations
import httpx
from worldtree_sdk import ApiError, AuthProvider, WorldtreeClient
class SessionApiFailed(Exception):
"""The adapter's DEFAULT caller-semantic error (INV-CUT-2 default row): any SDK
`ApiError` not mapped to a more specific ratatoskr exception surfaces here,
carrying the SDK's cleanly-parsed `status` / `error_code` / `body` verbatim.
The `body` is already UTF-8-byte-bounded and bearer-scrubbed by the SDK."""
def __init__(self, *, status: int, error_code: str, body: str | None = None) -> None:
super().__init__(
f"worldtree API failed: status={status}, error_code={error_code!r}"
)
self.status = status
self.error_code = error_code
self.body = body
def build_client(
base_url: str,
*,
api_key: AuthProvider,
admin_key: AuthProvider | None = None,
transport: httpx.AsyncClient,
) -> WorldtreeClient:
"""Construct the adapter's `WorldtreeClient` over a ratatoskr-owned transport.
`transport` is REQUIRED and ratatoskr-owned: injecting it sets the SDK's
`_owns_client=False`, so `WorldtreeClient.aclose()` never closes it — ratatoskr
owns the lifecycle exactly as today (INV-CUT-1). ratatoskr's `api_key` /
`admin_key` map to the SDK's per-request `auth` / `admin_auth` providers; the
injected transport carries ratatoskr's User-Agent / timeout (wired by the
caller in slice-2), NOT the Authorization header — the SDK adds auth per
request.
"""
return WorldtreeClient(
base_url,
auth=api_key,
admin_auth=admin_key,
transport=transport,
)
def translate_error(exc: BaseException) -> BaseException:
"""Map an SDK exception to ratatoskr's caller-semantic exception (INV-CUT-2).
Foundation scope — the § Error map DEFAULT plus discriminated passthrough:
* SDK `ApiError` (the undiscriminated REST floor) → `SessionApiFailed`
carrying `status` / `error_code` / `body`.
* Every other exception — the SDK's discriminated `WorldtreeError` subclasses
(`AgentNotAvailable`, `SessionRetired`, `ResumeError`, `Cancel*`, ...) and
any non-SDK error — passes through by IDENTITY, unchanged.
Route-specific rows (a 404 on `sessions.create` → `AgentNotFound`, a 404 on
`sessions.write_history` → `AuthoredHistoryUnavailable`, ...) are the ROUTE's
to add at its call-site in later slices, never inferred from the body here.
"""
if isinstance(exc, ApiError):
return SessionApiFailed(
status=exc.status, error_code=exc.error_code, body=exc.body
)
return exc
+85
View File
@@ -0,0 +1,85 @@
"""Unit tests for the worldtree-sdk adapter (`ratatoskr.wt`) — slice-1 foundation.
Covers the two foundation surfaces (issue #20 cutover contract, slice 1):
* `build_client` — construction wiring + injected-transport ownership (INV-CUT-1:
the SDK must never close ratatoskr's transport).
* `translate_error` — the § Error map DEFAULT (`ApiError` → `SessionApiFailed`)
plus discriminated-`WorldtreeError` passthrough (INV-CUT-2).
No ratatoskr surface (CLI / web / TUI) is exercised here — that wiring lands in
slice 2. These tests hit no network (WorldtreeClient does no I/O at construction).
"""
from __future__ import annotations
import httpx
from worldtree_sdk import AgentNotAvailable, ApiError, WorldtreeClient
from ratatoskr.wt import SessionApiFailed, build_client, translate_error
class TestBuildClient:
async def test_constructs_worldtree_client(self) -> None:
transport = httpx.AsyncClient()
try:
client = build_client(
"https://wt.example:8081", api_key="ck-test", transport=transport
)
assert isinstance(client, WorldtreeClient)
assert client.base_url == "https://wt.example:8081"
finally:
await transport.aclose()
async def test_injected_transport_is_ratatoskr_owned(self) -> None:
# INV-CUT-1 [hard]: aclose() on the SDK client must NOT close ratatoskr's
# transport — ratatoskr owns the lifecycle exactly as it does today.
transport = httpx.AsyncClient()
client = build_client("https://wt.example", api_key="ck", transport=transport)
await client.aclose()
assert client.closed is True
assert transport.is_closed is False
await transport.aclose()
async def test_admin_key_optional(self) -> None:
transport = httpx.AsyncClient()
try:
# Absent admin_key → admin_auth=None; still constructs.
without_admin = build_client(
"https://wt.example", api_key="ck", transport=transport
)
assert isinstance(without_admin, WorldtreeClient)
# Present admin_key → constructs (admin surface available in later slices).
with_admin = build_client(
"https://wt.example", api_key="ck", admin_key="ak", transport=transport
)
assert isinstance(with_admin, WorldtreeClient)
finally:
await transport.aclose()
class TestTranslateError:
def test_apierror_maps_to_session_api_failed_default(self) -> None:
exc = ApiError("some_code", "boom", status=500, body="raw-body")
mapped = translate_error(exc)
assert isinstance(mapped, SessionApiFailed)
assert mapped.status == 500
assert mapped.error_code == "some_code"
assert mapped.body == "raw-body"
def test_apierror_with_no_body_maps_cleanly(self) -> None:
exc = ApiError("nope", "no body", status=404)
mapped = translate_error(exc)
assert isinstance(mapped, SessionApiFailed)
assert mapped.status == 404
assert mapped.error_code == "nope"
assert mapped.body is None
def test_discriminated_subclass_passes_through_unchanged(self) -> None:
# Discriminated WorldtreeError subclasses are already the right semantic
# type — the adapter passes them through by identity (no re-wrap).
exc = AgentNotAvailable("agent_not_available", "gone", status=409)
assert translate_error(exc) is exc
def test_non_worldtree_error_passes_through_unchanged(self) -> None:
exc = ValueError("unrelated")
assert translate_error(exc) is exc
Generated
+15 -1
View File
@@ -472,11 +472,12 @@ wheels = [
[[package]]
name = "ratatoskr"
version = "0.21.2"
version = "0.21.3"
source = { editable = "." }
dependencies = [
{ name = "httpx" },
{ name = "httpx-sse" },
{ name = "worldtree-sdk" },
]
[package.optional-dependencies]
@@ -519,6 +520,7 @@ requires-dist = [
{ name = "sqlite-vec", marker = "extra == 'provider'", specifier = ">=0.1.6" },
{ name = "starlette", marker = "extra == 'web'", specifier = ">=0.40" },
{ name = "uvicorn", extras = ["standard"], marker = "extra == 'web'", specifier = ">=0.30" },
{ name = "worldtree-sdk", specifier = "==1.0.0", index = "https://gitea.phasefinal.com/api/packages/vh/pypi/simple/" },
]
provides-extras = ["web", "provider", "dev"]
@@ -903,3 +905,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/9f/3e/28135a24e384493fa804216b79a6a6759a38cc4ff59118787b9fb693df93/websockets-16.0-cp314-cp314t-win_amd64.whl", hash = "sha256:b14dc141ed6d2dde437cddb216004bcac6a1df0935d79656387bd41632ba0bbd", size = 178531 },
{ url = "https://files.pythonhosted.org/packages/6f/28/258ebab549c2bf3e64d2b0217b973467394a9cea8c42f70418ca2c5d0d2e/websockets-16.0-py3-none-any.whl", hash = "sha256:1637db62fad1dc833276dded54215f2c7fa46912301a24bd94d45d46a011ceec", size = 171598 },
]
[[package]]
name = "worldtree-sdk"
version = "1.0.0"
source = { registry = "https://gitea.phasefinal.com/api/packages/vh/pypi/simple/" }
dependencies = [
{ name = "httpx" },
]
sdist = { url = "https://gitea.phasefinal.com/api/packages/vh/pypi/files/worldtree-sdk/1.0.0/worldtree_sdk-1.0.0.tar.gz", hash = "sha256:0b87001fd90b304befe5e76d21a41dd093057a9d59f86a25189fab80defcd043" }
wheels = [
{ url = "https://gitea.phasefinal.com/api/packages/vh/pypi/files/worldtree-sdk/1.0.0/worldtree_sdk-1.0.0-py3-none-any.whl", hash = "sha256:ec9cb03ecdb4662bf1280a64316ee4545bb1330db42e3135f34f56e62c07f6c5" },
]