Compare commits

...

470 Commits

Author SHA1 Message Date
Patrick Buckley a16e6d66d8 chore: bump version to 1.8.0a3 2026-07-20 07:38:27 -07:00
Patrick Buckley 984a10307e feat(coordinator): MCP tool surface for coordinator sessions (#725)
Coordinator-kind workstreams get the same MCP surface as interactive
sessions — tools, resources, and prompts (read_resource/use_prompt go
dual-kind) — gated per-persona exactly like interactive, with no
separate feature flag.

The console hosts its manager with node parity end to end: boot calls
create_mcp_client inline (same catalog resolution: DB rows, then
mcp.config_path, then this host's config.toml), the admin reload
fan-out lazily constructs and reconciles it under a lock (the node's
unlocked equivalent is #873), per-server refresh/reconnect and the
admin MCP status view cover it under the collector's console
pseudo-node id, and shutdown follows LIFO teardown. Sessions read the
live manager through a per-construction getter — the console
counterpart of the node factory's mcp_ref[0] read; client presence is
the session-level contract, and the kind-aware tool assembly runs the
same listener/prime/rebind skeleton as interactive. bind_acting_user
re-scopes listeners and per-user pools, which is security-critical for
multi-sender coordinators.

The wire-safety status projections move verbatim to core/mcp_utils so
both hosts present one schema (node endpoint bodies byte-identical);
the console's per-server action classification is a pinned COPY of the
node endpoints', with a parity test driving both sides across the
outcome matrix that fails if either drifts.

The shared MCP error card (consent / re-consent / forbidden / operator)
moves to mcp_error.js + mcp_error.css, linked by all three card hosts
and pinned by className→rule and host→link parity tests; the module
joins the whole-file sink-scan and var-ratchet lists. Reload reporting
is honest about the console entry: excluded from the unreached-node
warning's list and denominator, and the toast claims "+ console" only
for a real reconcile, with an explicit note on failure.

The pending-consent badge (#874's console half) ships too: the console
defines the same onConsentDetected seam the node dashboard exposes —
lighting up the shared pane host's existing bridge for hosted
interactive panes — and the coordinator pane threads its card's
detections through the single MCP-error helper. The badge rides the
Admin > MCP Servers rail row, hydrates at boot from the Phase 9
pending-consent endpoint the console already serves, re-syncs to DB
truth when the operator views the MCP panel, and the rail-less
standalone page carries a status-bar chip instead. A coordinator that
hits a consent wall unattended now has a persistent, glanceable signal.

Pre-existing bugs fixed along the way: create_mcp_client returned None
on pool-only installs, leaving any host managerless after restart until
the next admin MCP write; admin_import_mcp_config never scheduled the
reload fan-out (stale catalogs after import); the admin settings UI
rendered the coordinator settings section unordered and unlabeled.
Follow-ups: #873 (node reload double-construct race); #874 narrows to
the admin-MCP-view per-server indicator.
2026-07-20 07:25:56 -07:00
renovate[bot] 5ae963cb49 chore(deps): lock file maintenance 2026-07-20 07:21:40 -07:00
github-actions[bot] e4604c278e chore: download vendored JS files 2026-07-20 07:21:23 -07:00
renovate[bot] c3306be442 chore(deps): update dependency katex to v0.18.1 2026-07-20 07:21:23 -07:00
renovate[bot] 686ddf2414 chore(deps): update actions/setup-python action to v7 2026-07-20 02:39:57 -07:00
renovate[bot] b89fe0fba2 chore(deps): update pypa/gh-action-pypi-publish digest to ba38be9 2026-07-20 02:39:40 -07:00
Patrick Buckley c4d180aa04 refactor(session): single assignment path for interactive tool lanes
Apply review round-2 finding: the wrap-both-lanes-through-_apply_cwd_notes
pattern was hand-copied at three sites (construction, MCP list_changed,
MCP disconnect), leaving the notes invariant convention-enforced. Route
all five interactive build sites through one _set_interactive_tools(
mcp_tools) helper — merge_mcp_tools with [] is a fresh copy of the
builtin base, so the no-MCP sites pass [] and the invariant becomes
structural. Coordinator branch keeps its direct build (no cwd-dependent
tools) and gains the explicit _task_tools annotation mypy now needs.
2026-07-19 19:09:58 -07:00
Patrick Buckley 8d1190d17a docs(tools): apply review round-1 findings (cwd notes)
- docs/tools.md: sync the tool-JSON metadata-keys table to _META_KEYS —
  it had drifted to 3 of 8 keys (coordinator, interactive, kind_variants
  were already missing; cwd_note/workspace_note are new).
- tests: cover the third note-rebuild trigger (_drop_mcp_surface) with a
  count==1 assertion on both lanes, and pin the deliberately uniform
  workspace_note wording across the fs tools so a one-file reword cannot
  drift the copies apart.
2026-07-19 19:09:58 -07:00
Patrick Buckley 460308241d fix(tools): lower working directory and workspace into fs tool descriptions
The process cwd was nowhere in the model's context: shells start in the
inherited process cwd (spawn_group_leader passes no cwd), relative file
paths resolve against it, but nothing told the model where it was
standing — in stock Docker every shell ran in /data while user files sat
in the /workspace mount, and the model's only recourse was to probe with
pwd (#857, #833).

Lower both facts into the tool schemas, where they gate intrinsically on
tool availability (a persona without fs tools carries no note, and
coordinator envelopes are untouched):

- tools/*.json: cwd_note/workspace_note metadata templates on bash,
  read_file, write_file, edit_file, search, diff_file; bash also states
  the fresh-shell-per-call semantics (cd does not persist) and drops a
  stale reference to the removed man tool.
- tools.apply_cwd_context(): renders the notes into descriptions;
  deep-copies noted tools (the fs dicts are shared across
  TOOLS/INTERACTIVE_TOOLS/TASK_AGENT_TOOLS and aliased through
  merge_mcp_tools), passes note-less tools through by reference.
- ChatSession._apply_cwd_notes(): wraps every fresh interactive build of
  _tools AND _task_tools (construction, MCP catalog change, MCP
  disconnect) — assignment-time, so the wire tools block stays
  byte-stable for provider prompt caches. os.getcwd() is OSError-guarded
  (MCP rebuilds run on a background thread; eval tears down its
  workdir); the workspace hint drops when the dir is missing or equals
  the cwd. Task-agent sub-agents carry their own notes via _task_tools,
  independent of parent persona visibility.
- config.get_workspace_dir(): [tools] workspace_dir with
  TURNSTONE_WORKSPACE env fallback (searxng pattern), informational
  only — no chdir, no path confinement (per-workstream working-dir
  grants are a separate planned feature).
- Dockerfile: ENV TURNSTONE_WORKSPACE=/workspace so stock deployments
  surface the mount with zero operator config.
- docs/docker.md: document the /data working directory, the
  working_dir: /workspace compose override as the operator-level fix,
  and the SQLite-fallback-DB-in-cwd caveat.

Closes #857
2026-07-19 19:09:58 -07:00
Patrick Buckley 83277a4d17 fix(console): validate project pick against rebuilt choices
The launcher project picker restored `previous` unconditionally after a
choices rebuild: a since-deleted project landed the select on a blank
selectedIndex=-1 instead of the "No project" placeholder (submit was
safe — getOptionValue returned "" — but the select looked broken).
Route it through _restorePick like the other three pickers; the
"+ New project…" sentinel stays excluded (it is a command, not a state,
and it IS in choices so validity alone would not exclude it).
2026-07-19 02:39:38 -07:00
Patrick Buckley 1d144c331b fix(ui): apply round-3 review findings (composer caches)
- ui: _paintFromCache returns its async-repaint promise;
  _paintProjectPicker routes through it (fork/hint stay bespoke) and the
  dashboard chains an Options-chip recompute on EVERY paint — an async
  repaint can drop a server-removed pick (or revert persona to its kind
  default) without firing 'change', and the chip must always name what
  submit will send
- ui/console: the false "never worse than the pre-cache behavior" claim
  replaced with the accepted-tradeoff ruling for module-load failure
  (no per-picker retry — cache-busted re-imports split-brain the cache;
  no inline-fetch fallback — that resurrects the deleted dual path)
- console: _paintHomeFromCache collapses the four verbatim
  _refreshAndPopulate* wrapper bodies; _restorePick collapses the four
  preserve-pick blocks (persona keeps its kind-default revert, now
  pinned by a test)
- models/skills: drop the consumer-less loaded/error readers from the
  modules + bridges (same omitted-not-exposed doctrine as onChange;
  projects/personas keep theirs as pre-existing public surface)
- tests: boot-order guard pins ALL FOUR data-layer module tags before
  shell.js (the boot anchor) in both index.html; wrapper/project-picker
  guards redirected to the chokepoints; chip-recompute chains asserted
2026-07-19 02:39:38 -07:00
Patrick Buckley 0d8be572c7 fix(ui): apply PR #869 review findings (turnstone + copilot)
- list_cache: null-prototype _byKey — a row keyed "__proto__" swapped the
  map's prototype via the inherited setter, and getByKey of inherited
  members ("toString", "constructor") resolved them as rows; + guard test
- list_cache: document why _pending clears BEFORE the trailing refresh
  (a .finally clear would coalesce a late force onto a stale fetch —
  declines the reviewer's .finally suggestion with the ruling in-code)
- list_cache: extra() accessor doc reflects the conditional reset;
  resetExtraOnError @param notes it is moot without extraDefaults
  (declines per-module knobs in personas/skills, which have no extra)
- ui: extract _paintFromCache — sync-mirrors-freshOnOpen /
  async-always-fresh:false now encoded once for the model/skill/persona
  wrappers and asserted at the chokepoint
- ui: replaceChildren() for the model/judge/skill picker clears
  (consistency with the persona/project populates)
- console: reword the skills fail-open comment to unambiguous past tense;
  drop the orphaned _resolveModelLabel docstring
- tests: fork-gate asserts require each paint to open its own
  `if (!_forkFromWsId)` block (the rfind+50 window false-passed a closed
  gate; the model first-gate check was vacuous; the persona gate was
  unasserted); drop one redundant `0 <=` (kept where it guards find()==-1)
2026-07-19 02:39:38 -07:00
Patrick Buckley c3beb202eb fix(ui): apply round-2 review + fix-sanity findings (composer caches)
An unprimed convergence re-review found a real login-recovery seam gap plus
cleanups (round 1's fix round manufactured one of them); fix-sanity vetted the plan.

- console onLoginSuccess recovery seam [0]+[2]: it re-warmed only skills+models
  after an in-place login; projects+personas (same pre-auth-401 gap) stayed empty
  (rail group-by-project flat, saved-coordinator raw slugs). Now force-refreshes
  ALL FOUR caches on login — force so a still-in-flight failing pre-auth fetch
  yields a trailing AUTHENTICATED refetch rather than coalescing onto the 401
  (skills/personas have no *_changed event to recover). Threads an optional
  callOpts through the four cache modules + console wrappers (backward-compatible;
  every non-console caller passes nothing).

- fork skill paint [4]: the round-1 wrapper extraction left the modal skill paint
  unconditional on a fork (wasted GET /v1/api/skills + hidden-select rebuild);
  fork-gate it like model/persona/project.

- persona wrapper [5]: extract _paintPersonaSelect so all four composer pickers
  share the sync-then-refresh wrapper instead of persona being inline-duplicated.

- dead machinery [6]: remove the zero-subscriber onModelsChange/onSkillsChange and
  the models fpExtra fingerprint fold (and the now-orphaned core fpExtra branch).
  The console repaints models via its direct models_changed handler, not a
  subscription; the fold only fed the subscriber-only fingerprint.

- O(1) modelLabel [7]: index the models cache by alias (keyField) so modelLabel is
  a getByKey, not a per-paint scan.

Declines documented in-code: forks-inherit-model [1] (deliberate) and the
fail-open cache [3] (intended, same policy as projects/personas). Deferral comment
at the ui onLoginSuccess twin (recovers on dashboard re-focus; follow-up).

Tests: rewrote the 7 guards the code changes moved (persona relocation, callOpts
threading, force, fpExtra removal) preserving their ordering intent, and added
fork-skill-gate, persona-wrapper, all-four-force, keyField, and
onModelsChange-removed coverage. 106 pass; ruff + mypy green.
2026-07-19 02:39:38 -07:00
Patrick Buckley 8d57697b2a fix(ui): apply max-effort review + fix-sanity findings (composer caches)
A max-effort review of the composer-cache branch found 3 correctness + 2 cleanup
issues; fix-sanity refined the plan before implementing.

- Modal select stickiness [0]: the reused new-ws <dialog> kept the last open's
  model/judge/skill pick and silently applied it to the next chat (sharp for a
  fork — model/judge were sent unguarded). The composer selects now render fresh
  each open (a fresh open has no `previous` selection to preserve) across ALL
  five selects, while a within-open async repaint still preserves a mid-window
  pick. The modal now shows the resolved default ("Default — gpt-5"). A fork
  INHERITS its source's model + judge (hidden + submit-gated on !_forkFromWsId,
  matching skill/persona/project).

- models default-alias reset [1]: the shared core's extra-reset-on-failure is
  now opt-in (resetExtraOnError). projects keeps it (require_project gates the
  picker, must fail open); models opts out, so a transient failure keeps the
  last-known resolved-default annotation instead of blanking it.

- models_changed coalescing race [2]: an opt-in trailing refresh in the core —
  a force caller (models_changed) awaits a refetch chained after the in-flight
  one and converges to the latest state instead of a response predating the
  change; startup/open callers stay coalesced.

- cleanups: the 4x paint-then-refresh block collapses into _paintModelSelects /
  _paintSkillSelect [6]; the "alias (model)" label centralizes into models.js
  modelLabel (registered on the window bridge) [7], deleting both local copies.

Tests: rewrote the 5 guards that pinned pre-fix literals + added fresh-matrix,
fork-inherit, bridge-registration, both-error-branch reset, and trailing-refresh
guards. 106 pass; ruff + mypy green.
2026-07-19 02:39:38 -07:00
Patrick Buckley 71b1365e7b refactor(ui): shared list-cache core + models/skills caches (no composer FOUC)
The model and skill composer pickers had no client cache: the new-ws modal, the
dashboard quick-create, and the console launcher each re-fetched /v1/api/models
and /v1/api/skills inline on every open, flashing an empty dropdown for the
round-trip even though the data was usually already in memory. Add shared caches
(models.js, skills.js) the composers read SYNCHRONOUSLY, then refresh-and-repaint
— the pattern the project/persona pickers already use.

The coalescing / fail-open refresh / change-detection / window-bridge machinery
was ~70% duplicated between projects.js and personas.js. Extract it once into
list_cache.js (makeListCache) and retrofit projects.js + personas.js onto it,
preserving their full public surface byte-for-byte (rail.js + project_creator.js
import them by name; the classic bundles read the window bridges). The
require_project advisory rides projects.js as fail-open `extra` state; personas
keep their kind-filtered choices and name->label map.

models.js carries BOTH server schemas (the node sends default_alias, the console
sends coordinator_default_alias; both send judge_default_alias) so each app reads
its own, and folds them into the fingerprint so a role-alias change still fires
onChange. skills.js returns raw rows (the ui pickers add a " [MCP]" suffix the
console omits). Selection is preserved across the sync->async repaint on every
select, including model + judge independently.

Also: the dashboard model/skill fetch-once guard is dropped (refresh-on-open now,
matching project/persona); the console re-warms models on login too (the boot
pass runs pre-auth, so the dropdown used to stay empty until a reload); and
models_changed repaints via the single refresh wrapper (no double path).
2026-07-19 02:39:38 -07:00
Patrick Buckley a23cc2c25e ci: remove claude workflows
The @claude mention responder (claude.yml) and the automatic PR review
(claude-code-review.yml) have been unreliable and are a frequent source
of CI breakage. Drop both; core CI (ci.yml, docker-publish, publish,
understone-example, vendor-js) is untouched and nothing else in the
tree references them.
2026-07-19 01:23:12 -07:00
Patrick Buckley 079257967d refactor(ui): extract _paintProjectPicker (dedupe modal/dashboard)
Review of #868 flagged the sync-paint + refresh + required/optional hint block as copy-pasted between showNewWsModal and _loadDashboardOptionsLists, already diverging structurally, so a future tweak could drift and silently re-introduce the FOUC on the missed surface. Collapse both into a shared _paintProjectPicker(sel, hint, {fork}) -- the modal passes the fork flag, the dashboard never forks. Guards re-pointed at the helper + a new one pins its sync-before-async pattern.
2026-07-18 17:36:02 -07:00
Patrick Buckley 4079542447 fix(ui): paint composer project/persona pickers from warm cache (no FOUC)
The new-workstream modal, the dashboard composer, and the console launcher
painted their project and persona <select>s only inside the async
refresh().then(...) callback, so each open flashed an empty/stale dropdown for a
network round-trip even though the client caches are already warmed at startup.
Paint synchronously from the warm cache first, then refresh-and-repaint (still
catches items created elsewhere). On a cold cache the sync paint is a no-op the
async fills, so it is never worse than before.

Both project paints reuse the same _populateProjectSelect + reconcile, so the
require_project strict-picker invariant (never auto-select a real project into a
possibly-shared one) is unchanged; persona reuses _populatePersonaSelect, which
preserves a mid-window pick and only applies the kind default when nothing valid
is selected.

Also folds in two deferred require_project polish items in the same code: the
dashboard Project label now shows the "required"/"optional" hint (parity with the
modal), and _reconcileRequiredProjectSelection reuses the projectChoices() list
its caller already built instead of recomputing it.

Models/skills selectors are a separate follow-up (no client cache today).
2026-07-18 17:36:02 -07:00
Patrick Buckley 8ce94360ae docs(projects): requireProject() advisory is safe to read synchronously 2026-07-18 16:12:59 -07:00
Patrick Buckley c019ab41d7 feat(server): opt-in server.require_project gate
Add an opt-in, default-off `server.require_project` setting. When an admin
enables it, creating an interactive chat is refused unless it is filed under a
project. The feature is inert and byte-identical when off, and can only ever
fail toward "off" (a missing config store or unset key reads as disabled).

- settings_registry: server.require_project (bool, default False, live read).
- auth: require_project_enabled + require_project_denies_create predicates
  (service scope / coordinator token_source exempt; NOT admin.coordinator),
  plus REQUIRE_PROJECT_ERROR / REQUIRE_PROJECT_CODE.
- node create gate via a declarative cfg.create_gate_require_project (wired True
  on the interactive mount only; coordinator spawns stay ungated).
- fork/resume: a fork's project is structurally its source's. Any explicit
  project_id is discarded, so a fork can never be re-filed under an unrelated
  project (which would move its copied history across a tenancy boundary).
  Inaccessible / projectless / nonexistent sources are uniform on body and
  status, so there is no cross-tenant oracle.
- console cluster-create proxy surfaces only the coded require_project 400 and
  masks every other node outcome (401/429/3xx/5xx, un-coded 400) to a sanitized
  502, guarding both body reads.
- list_projects advisory field + projects.js requireProject() (fail-open).
- fresh-create project picker requires an explicit project choice under the flag
  (no silent auto-select); forks hide the picker (inheritance is server-enforced)
  and get an accurate refusal message.
- tests: predicate matrix, resume-inheritance oracle discriminators, console
  masking, and end-to-end node-gate mount wiring.
2026-07-18 16:12:59 -07:00
Patrick Buckley cdc360bd98 fix(server): sanitize the retry closure's error display
The retry (_run) closure emitted the raw str(exc) to ui.on_error, so a
credential-bearing base-URL in a backend ConnectError
(https://user:pass@host) crossed into the dashboard SSE — the
confidentiality floor _record_fatal_error enforces, bypassed here.
Sanitize the display inline with the same sanitize_error_text redactor.

This is separable from the reused-session stale-flag hazard that keeps
_run off ensure_error_recorded: that hazard is about recording /
idempotency (deferred to #865); this is only the display string. The
double state emit and the pre-try no-persist remain in #865.

Adds a focused test that a retry-error's on_error is redacted.
Flagged by review on #866.
2026-07-17 20:08:56 -07:00
Patrick Buckley 3af80907c7 fix(server): init-message worker exits to error, not idle, on first-turn failure
The initial-message worker (_run_initial) collapsed both cancel and
backend-error exits into one `except (Exception, GenerationCancelled)`
arm that always stamped state=idle, clobbering the state=error that
session.send's _record_fatal_error had persisted+emitted. A spawned
child's first-turn backend failure (unreachable model server, exhausted
quota, auth error) therefore read as an empty, successful turn — the
coordinator's wait/inspect surface reads last_error only for
state=='error' — and the real error surfaced only after a manual nudge
re-ran the turn synchronously.

Split the arm: cancel -> idle, exception -> error. The failed child now
settles at state=error and the first wait_for_workstream returns the
enriched backend error inline. Also fixes the same latent bug for
scheduled tasks, which dispatch through the same endpoint and closure.

A failed first turn is deliberately terminal for automated wakes: it
settles to a non-ready error terminal, not the idle ready-set that
timer/watch wakes recur to, so explicit user/coordinator action
reactivates it rather than a silent auto-retry (a self-healing
wake-from-error would be a separate wake-gate change).

The exception arm routes through a new ChatSession.ensure_error_recorded:
a no-op when send already recorded the error in-line (the common
backend-boundary path — no duplicate state emit), and the recorder when a
pre-try exception (model-registry refresh, user-turn append,
system-message recompose) bypassed send's own handler, so state=error
always carries a meaningful last_error. Its idempotency guard
(_has_persisted_error) is session-lifetime, so ensure_error_recorded is
scoped to _run_initial's FRESH first-turn session only; the docstring
spells out why a session-reuse caller (retry, /send, coord send, wake)
must not route through it until the per-turn error-recorded signal of
#865 lands.

The other half of making an errored workstream cheap for a model to
handle is a stable identifier: the enriched backend error now leads with
the model ALIAS the coordinator references everywhere (list_nodes, spawn)
and annotates the backend id for the operator —
"model=DeepSeek-V4-Flash (id=deepseek-v4-flash)" — so a model routing
around a failed model correlates it against those surfaces without a
lookup, instead of burning reasoning tokens reconciling the alias against
a backend id it never sees anywhere else. Collapses to one token when the
alias and id coincide.

Tests (TestInitialWorkerFailureState) assert the coordinator-visible
manager state and the persisted last_error across the matrix — common-
backend and pre-try errors both settle error with a readable last_error;
cancel-to-idle settles idle with no error recorded. De-forks the
create-app fixture and uses the shared monotonic wait_until helper.

The completion-notification honesty surface and the error-recording
hygiene of the other send-worker closures (retry / main send / coord send
/ wake) are deferred to #865.
2026-07-17 20:08:56 -07:00
Patrick Buckley 9dea2c89f1 chore(sdk): regenerate openapi-console.json
The console OpenAPI spec had drifted from build_console_spec(): the committed
file was last generated at 1.7.0rc1 and was missing the persona and project_id
workstream-creation fields (Personas and Projects, both 1.7) plus the version
bump to 1.8.0a2. Regenerate via sdk/typescript/scripts/generate-types.py to
resync. Spec-only; no console API behavior change (openapi-server.json was
already current).
2026-07-17 11:55:47 -07:00
Patrick Buckley 515d372a14 fix(compaction): validate retry_in backoff before rendering the retry note
updateCompactionProgress coerced evt.retry_in with Number() and rendered it
unguarded, while the sibling part/total path two lines below is finiteness-
validated — a malformed backoff would render "retrying in NaNs". Validate
retry_in the same way (finite, non-negative), and keep the error text
regardless: the error is the load-bearing half of the note, so an unparseable
duration drops to "retrying (error)…" rather than suppressing the whole arm.

Addresses PR review feedback on the compaction reducer.
2026-07-17 11:28:44 -07:00
Patrick Buckley abe053f507 fix(compaction): review round 11 — settle-helper null-guard to the chokepoint
The settleSendResponse extraction left the two panes' call sites diverging on
the null-guard: interactive passed bare `data`, the coordinator passed
`data || {}` — reintroducing the copy-paste variation the shared helper existed
to erase. If a /send 2xx body were ever non-object JSON, the unknown/"ok"
fall-through would deref `data.attached_ids` and paint an already-delivered
message as a connection error; the endpoint always returns an object, so this
is a latent divergence, not a live bug.

Normalize the body once at the helper entry (`data = data || {}`) so both call
sites pass bare `data` and stay byte-identical, and every internal deref plus
any future caller is covered by the single chokepoint. The node settle-harness
gains a null-body case — red without the fix, since the call-arg evaluation
throws before the stub runs.
2026-07-17 11:28:44 -07:00
Patrick Buckley 1e86f068cd chore(compaction): review round 10 — cleanups from the first correctness-clean round
- INTERJECTION_CAP_CHARS joins PENDING_SENDS_MAX in workstream.py: the
  2000-char interjection cap was triplicated (queue_message's truncation,
  the defer-fidelity refusal, the test fake) and already drifting in
  measurement — the defer check deliberately measures RAW text (raw >=
  cleaned since parse_priority only strips, so it can only over-refuse
  into a full-fidelity fresh spawn, never admit a truncation), now
  stated in a comment. The four unrelated 2000s (notify tool, recall
  preview, summary formatting, agent step cap) stay deliberately
  unlinked — they are different contracts.
- The changelog's ~110-line compaction bullet is split into six per-seam
  bullets matching house style, and the Breaking (1.8) compaction-event
  notice moved under "### Changed" where integrators scanning bullet
  heads will actually see it (cross-referenced both ways with the
  pre-1.8 embedder compat bullet).
- SpawnMetricsHook takes (ui) only: the request parameter was threaded
  through the whole dispatch-attempt path solely to be ignored by both
  installed impls; the stale "coord wires None" claims in the rewritten
  comment blocks are corrected too.
- The attachments tests' Mock-hardening block lives once in
  _harden_ws_mock() — deliberately excluding _worker_running, which each
  fixture chooses per scenario (one relies on the truthy auto-Mock).
- Two hand-rolled poll loops become wait_until (file convention,
  diagnostic timeout) and the orphaned time import goes with them.
2026-07-17 11:28:44 -07:00
Patrick Buckley d280db514e fix(compaction): review round 9 — drain-exit ownership, missed-edge settle, pre-turn hook guard
Three point-guards from the ceiling round (no primitive took a hit;
correctness yield halved at identical review sensitivity):

- The drain's clean-exit wake moved OUT of the function-level try: it
  runs after the drain has already retired its slot, so a raise out of
  the wake (the dispatcher re-raises Thread.start failures) could reach
  the last-resort handler and clear a slot this thread no longer owned —
  nulling a successor drain's live registration and letting two drains
  service one list. The wake now runs post-try under its own guard
  (mirroring _retry_pending_wake), only on the clean-exit path, and the
  last-resort slot-clear is identity-guarded like every sibling exit
  seam. The except arm needed a function-local threading import: the
  module-top import is TYPE_CHECKING-only, so the guard would have
  NameErrored inside the handler with strict mypy fully green.
- The shared settle helper promotes a non-deferred chip that binds onto
  an already-idle pane: its only sweep fired mid-POST (unbound then) and
  no message_dispatched ever comes for non-deferred sends, so the chip
  stayed a permanently retractable "queued" bubble for a delivered
  message. Keyed on post-bind chip state (also catching a raced folded
  settle bind just reconciled) and skipping dismiss-in-flight chips —
  the sweep's own aria-busy discipline. Pinned behaviorally: the helper
  now executes under node (a 4-row missed-edge matrix), possible since
  the consumer-less window bridge is gone.
- _claim_generation's on_generation_claimed emission is call-guarded:
  it sits on send()'s pre-turn path, before the user turn is appended
  and before the fatal handler's coverage, so a raising override
  degrades to a lost latch-break instead of silently dropping every
  user message on that session.

Cleanups: /command's transport catch and status-less non-2xx bodies are
loud now (threading {ok, status} through the parse — deliberately no
throw-on-!ok pre-gate, since the busy and error arms ride 409/503);
PENDING_SENDS_MAX lives in workstream.py and ChatSession._QUEUE_MAX
aliases it (one backpressure bound, structurally incapable of
diverging); the send handler's not-ok arm uses _queue_full_response();
the dead window.createQueueController bridge is deleted and the file
header's consumer map corrected.
2026-07-17 11:28:44 -07:00
Patrick Buckley 1224b02d03 fix(compaction): review round 8 — seam obligations become primitives
Eight rounds of findings against the defer-and-drain seam shared one
generator: N sites each hand-copying M obligations (spawn discipline,
the order-barrier pair, backpressure, best-effort emission, the client
settle matrix), with every review finding an empty (site x obligation)
cell. This round makes each obligation a single primitive:

- The order barrier is Workstream.send_barrier_active() — one
  definition of the two-term pair (pending entries OR drain alive),
  consulted by the /send route, the coordinator adapter, and the
  queued-nudge wake gate, which previously carried only the list term
  and let a synthetic wake jump an acknowledged send during the
  claimed-entry window. _PendingSend moved to workstream.py beside the
  invariant that justifies the drain-alive term; the pending fields got
  precise types and worker_kind became a Literal, so a typo'd
  "command" comparison is now a type error instead of a silently
  never-firing defer guard.
- _defer_send probes the barrier before constructing anything, bounds
  acceptance at 10 pending (the interjection queue's own backpressure
  contract — unbounded acceptance pinned message + attachment bytes
  per entry for a whole command window and then ran one unattended
  turn each), and spawns the drain with rollback: a Thread.start
  failure pops the just-accepted entry and answers the retryable
  queue_full instead of 500ing after registration (a phantom the
  client could neither see nor retract, dispatched later as duplicate
  turns). start() deliberately stays inside the lock, unlike
  session_worker's outside-lock discipline: this slot is
  is_alive()-gated, false for a constructed-but-unstarted thread, so
  an outside-lock start would open a double-drain window.
- A /command whose worker never spawned answers 503
  {"status": "error"} (spec + docs + a pane error arm) instead of the
  generic 200 ok that told SDK callers their /clear ran.
- The compaction lifecycle emitter is raise-proof at its single
  dispatch tail: a raising duck-typed hook degrades to a lost render,
  never a lost end event — previously a raising on_error or a raising
  failed-end emit left every pane a frozen progress bar, and a raising
  SUCCESS end after the committed swap fabricated a failed end.
- The client settle matrix lives once: composer_queue's
  settleSendResponse owns every /send response arm for both panes
  (the near-verbatim twins were already drifting), parsePriority is
  shared, and the busy stamp is centralized in setBusy(b, source) with
  "server" as the fail-safe default. Deferred sends release the
  composer (no worker exists for them; retracting the chip no longer
  strands the pane in Stop mode), queue_full on an idle-looking pane
  removes the optimistic bubble and restores busy (the refusal can now
  fire with no worker and no drain to ever emit a state event), and
  the pre-bind settle buffer is TTL-based — a burst of deferred
  dispatches parked this tab's own raced settle first, where the old
  size cap evicted exactly it.
- The command backstop / console proxy timeout inequality is enforced
  by a test importing both named constants (both proxy_client
  constructions, startup and the mTLS re-create); the compaction card
  wears blue (magenta is reserved for the MCP surface); the redundant
  TerminalUI.on_compaction override is gone (the inherited protocol
  default is the policy site).
2026-07-17 11:28:44 -07:00
Patrick Buckley 5511ab9a35 fix(session-worker): release the slot claim when Thread.start itself fails
If thread creation raised (thread exhaustion, MemoryError), the
dispatcher had already claimed the worker slot under ws._lock — but the
flag's only clearer is _runner's finally, on a thread that never
started. The workstream then looked idle forever (no state change ever
fired) while every subsequent dispatch took the reuse path into a queue
no worker would drain, until an operator force-cancel.

Roll the claim back under the lock (identity-guarded, like _runner's
own clear, so a concurrent force-cancel's successor is never clobbered)
and re-raise. Re-raise rather than return False: callers' crash paths —
the deferred-send drain's per-iteration handler with its backoff — are
shaped for exceptions, and a False would masquerade as queue-full
backpressure and mislabel the wake gate's refusal log. worker_kind is
left stale, as documented (every reader conjoins _worker_running).

Affected every dispatch path: sends, wakes, retries, the deferred-send
drain, and workstream init.
2026-07-17 11:28:44 -07:00
Patrick Buckley fd5d3efb43 fix(compaction): review round 7 — drain crash/order/settle rows, protocol-default fallback, bool event-id guard
Completes the defer-and-drain seam against the matrix rows round 6 never
enumerated (the defer contract itself took no hits):

- Crash row: a claimed entry survives a dispatch crash — the
  per-iteration handler re-inserts it at head (claim-flagged so a
  claim-section failure can't duplicate it), backs off ~1s, retries.
  The last-resort handler spawns no successor (Thread.start fails under
  the exact exhaustion that reaches it): the route's ensure-drain stays
  the single spawn site, so single-flight is structural and a dead
  drain revives on the next defer.
- Order row: the pending list is the order authority. The /send route
  pre-checks pending/drain-alive under the same lock acquisition that
  appends (one _defer_send helper serves the barrier and command-window
  triggers); the coordinator adapter refuses via its return value; the
  queued-nudge wake gate yields to pending sends and is re-armed by the
  drain's clean exit — which covers lists emptied by pure retraction —
  as well as every deferred turn's exit; retry-after-rewind is a
  documented accepted overtake; init/create is fresh-ws-by-construction.
- Client settle row: queued responses carry "deferred": true
  (SendResponse + regenerated openapi-server.json, status enumeration
  completed); bind(el, msgId, {deferred, attachedCount}) replaces the
  _deferredAttachments expando; the idle sweep skips deferred and
  unbound chips; the shared dispatch attempt emits pane-tier
  message_dispatched (folded: true for interjection fold-ins — the chip
  clears only its deferred flag and keeps a live x while DELETE still
  genuinely retracts); settles that beat bind() park in a bounded
  buffer; an idle-thinking pane retro-converts its optimistic bubble
  into a real queued chip instead of presenting a parked message as
  sent. Rejection polling waits on the slot flags — one dispatch
  attempt per slot-state change, not 4 Hz.
- SessionUI.on_compaction's protocol stub became a real default body
  (the classic on_info rendering): explicit subclasses inherit protocol
  members as real methods, which defeated _compaction_event's getattr
  fallback for exactly the pre-1.8 embedders it serves.
- _coerce_event_id() rejects bools (isinstance(True, int) is True) at
  all three duck-typed event-id coercions: the compaction marker stamp,
  on_system_turn's persisted return, and _ui_event_id.
- Quick-command backstop 60s -> 25s, under the console proxy's 30s so
  the degraded "running" answer can traverse a proxied pane (which now
  surfaces it); /resume docs drop the fictional history SSE event
  (clear_ui + REST re-fetch is the contract); /send response docs match
  the wire.
2026-07-17 11:28:44 -07:00
Patrick Buckley e99673eb0c fix(compaction): review round 6 — defer-and-drain send windows, workstream-scoped notify, ERROR badge survives /compact
Replace park-and-abandon /send semantics with defer-and-drain: a send
landing in a command window is answered {status: queued, msg_id}
immediately and dispatched full-fidelity by a per-workstream drain
thread when the window closes. Parking encoded client disconnect as
message retraction — true only for the composer's ✕-abort; every
bounded caller (coordinator client and console proxy at timeout=30,
SDKs, stock proxies) timed out and lost its message for the whole
window, and the compensating client machinery was racy (one-shot
sendAbortMs sample) and over-broad (_sendAbort fired on the
interjection path, dispatching dismissed messages while showing a
connection error). Dismissal is now uniformly bind() → DELETE, with a
fall-through that retracts pending entries; retracting an
attachment-bearing deferred send surfaces the discarded-attachments
consequence. The drain claims entries under ws._lock immediately
before dispatch (DELETE can never remove an in-flight message),
refuses the truncating interjection fallback for oversized or
attachment entries atomically inside the enqueue callback, and never
gives up while the workstream lives; durability is documented as
node-local at-most-once. sendAbortMs, _sendAbort, the 600s bound and
the park loop are deleted; route and drain share one dispatch
implementation (spawn metrics included).

Also: the initial-send completion notify is un-gated from slot
ownership (_fire_notify_targets has exactly one call site — successor
turns never notify, so the round-5 guard prevented a duplicate that
cannot exist while converting force-cancel into permanent notification
loss for scheduled workstreams); /compact on an ERROR workstream
restores the badge instead of stamping idle over it; duck-typed
SessionUIs without on_compaction get the classic on_info lines back
via a shared renderer (superseded OK ends included — a committed swap
must never be silent; pre-1.8 SSE clients are deliberately not
dual-emitted, documented as a 1.8 breaking change); failed-end notice
suppression is computed once by the emitter as a notice bool on the
end event (SDK py+ts), replacing the hand-synced cli/JS policy while
the panes keep their pane-local card-ownership clause.
2026-07-17 11:28:44 -07:00
Patrick Buckley 1dbf7f410c feat(compaction): lifecycle events, web progress card, history re-render
Compaction becomes visible: a first-class 'compaction' SSE lifecycle
(start/progress/end, compaction_id-correlated, superseded-flagged ends)
replaces the loose info lines; both web panes render a progress-bar card
that settles into a persistent result card, re-rendered after reload via
the /history projection of the compaction marker row. Slash commands echo
as command chips instead of fake user turns.

The enabling rework: /command dispatches onto the workstream worker slot
(the old inline path blocked the node's event loop for whole compactions
and let /clear interleave with live turns). Busy refusals answer 409;
quick commands are awaited loop-natively with a 60s backstop; /compact is
fire-and-forget. Sends during a command window park in the /send route
and dispatch full-fidelity afterwards — the interjection queue (length
cap, cross-user guard, identity-swap hazards) is unreachable there — with
a compaction-aware client abort bound shared by both panes. compact_now()
carries send()'s full generation discipline; Stop aborts the in-flight
summary HTTP stream via a generation-scoped cancel ref; force-abandoned
compactions retire at their next checkpoint and their stragglers are
fenced off every surface (panes, pill latch, CLI). Every session retry
backoff is cancel-aware via one shared helper. Docs, OpenAPI spec, and
both SDKs updated.

Verified: 9457-test non-live suite, JS pin suites, headless-Chrome
reducer harness; five unprimed multi-agent review rounds (correctness
trend 15/6/6/4/4) with plan-level design passes on every fix round.
2026-07-17 11:28:44 -07:00
Sanjay Santhanam 82676080a4 fix(session): describe skill selections accurately
Use neutral "set" wording for operator skill markers so re-selecting the
current skill does not falsely claim a change. Update the regression
expectation for the persisted marker.
2026-07-17 00:58:37 -07:00
Sanjay Santhanam a64cd25807 fix(session): record operator skill changes
Operator-driven /skill changes were only shown in the UI, leaving no trajectory marker for the model. Persist a system turn for named skill changes and clears, with regression coverage for both paths.
2026-07-17 00:58:37 -07:00
renovate[bot] 8240d2c00d chore(deps): update helm release postgresql to ~18.8.0 2026-07-16 10:51:18 -07:00
renovate[bot] 8f8c2f4ca3 chore(deps): update github actions 2026-07-16 07:06:06 -07:00
renovate[bot] 7b1f77dda7 chore(deps): lock file maintenance 2026-07-15 21:07:39 -07:00
renovate[bot] 72229cac26 chore(deps): update ghcr.io/astral-sh/uv docker tag to v0.11.29 2026-07-15 21:07:15 -07:00
renovate[bot] 09c5475b0e chore(deps): update actions/setup-node action to v7 2026-07-15 21:06:48 -07:00
Patrick Buckley 0e6a99e0f1 chore: bump version to 1.8.0a2 2026-07-14 11:43:44 -07:00
Patrick Buckley 84577ee530 fix(mcp): PR #844 review — correct success docstring, back out the dead admin pill
Copilot review feedback (all three valid):

- _record_refresh_success docstring still claimed the push-driven
  single-kind refresh calls it — round 8 deliberately stopped that (a
  single kind can't declare a server-scoped 'ok'). Docstring now states
  the full-pass-only contract and points at the push path's _record
  closure for why.

- The admin refresh pill's skipped-tint logic (admin.js) and its
  .mcp-refresh-pill-skip CSS were dead code: /v1/api/_internal/mcp-status
  strips last_refresh_at/last_refresh_outcome via the read-scope
  projection, so admin.js never sets newestRefreshAt and the pill block
  never runs. Backed both out; the whole pill fix (whitelist the fields
  with a read-scope-coarsened outcome, THEN the color logic + CSS) now
  lives in #843. The CHANGELOG's false 'the admin console's refresh pill
  paints…' claim is dropped — the /mcp refresh CLI and the 202-skipped
  endpoint (which read last_refresh_outcome directly, not via the strip)
  still work and remain documented.

The 5 github-code-quality 'statement has no effect' comments are the
known PR #840 false-positive class (the scanner reads 'await <name>' as
a valueless expression); each flagged await is load-bearing (drains a
parked runner so the next assertion is non-vacuous, delivers a
cancellation, or awaits a _noop to fabricate a done owner_task) — no
code change.

Refs #839, #843
2026-07-14 11:39:25 -07:00
Patrick Buckley 80e7b9e9ca fix(mcp): review round 8 — push-success can't declare health, first-notify never debounced
- A single-kind push SUCCESS no longer clears the server error pill or
  stamps 'ok': _last_error / _last_refresh are server-scoped but a push
  refreshes only ONE kind, so a tools-failing server must not go green
  because its prompts push succeeded (a wrong-healthy window, bounded by
  the health tick — but a real 200-OK lie). Only a full pass declares
  'ok'; the failure's armed health-tick retry runs it. This reverts the
  over-reach of round 7's push-success outcome write (a self-inflicted
  regression) — net simpler.
- The (server, kind) debounce uses a None sentinel, not a 0.0 default:
  time.monotonic() counts from boot, so on a node whose process started
  < _NOTIFICATION_DEBOUNCE (5s) after boot, the 0.0 compare would debounce
  the VERY FIRST push — dropped with no recovery on the pool path. Absent
  stamp = never refreshed = always admit.
- _record_refresh_skipped completes the outcome-helper set: the three
  inline 'skipped' stamps now share one config-gated helper (with
  _record_refresh_success / _record_refresh_failure), and the
  reconnect-success branch routes through _record_refresh_success — no
  more hand-copied gates to drift.
- The per-message refreshers dict + on_debounce_drop closure are built
  ONCE per handler (both static and pool), not on every server->client
  message before the isinstance/debounce/coalesce early-returns.

Accepted (documented): an operator /mcp refresh that finds the connect
lock busy skips + arms the retry rather than waiting (waiting
re-introduces the refresh-budget exhaustion busy-skip exists to prevent).
4 findings refuted. Suite 9408 green.

Refs #839
2026-07-14 11:39:25 -07:00
Patrick Buckley 52dcb6a47b fix(mcp): review round 7 — consolidate the refresh-outcome write path
All three round-7 findings shared one root cause: last_refresh_outcome
(the single source of truth for the CLI / endpoint / admin pill) was
written inconsistently — ungated writes scattered across _refresh_server
and _refresh_all, never written by the push path, never popped on
removal. Consolidate every static outcome write through two config-gated
helpers so the invariant holds: _last_refresh[name] exists IFF the
server is configured and has a real outcome.

- _record_refresh_failure now stamps the (config-gated) error:<Class>
  outcome; _record_refresh_success is its twin (gated ok stamp + pill
  clear). The ungated writes inside _refresh_server (both the internal
  error write and the success write) and _refresh_all's except are
  removed — routed through the helpers. A failure observed for a
  just-removed server no longer leaves a permanent stale error: row.
- The push-driven refresh path (_run_static_notification_refresh._record)
  now records the outcome on BOTH success and failure, not just the
  error pill — a green 'ok' outcome no longer persists under a red error
  row after a push fails, and a successful push clears a prior error.
- remove_server_sync pops _last_refresh (via _clear_static_push_state
  markers=True); a session drop KEEPS it (the outcome persists across a
  reconnect — only removal clears it). The removed-mid-pass branch drops
  any stale row too, so last_refresh_outcome doesn't report a departed
  server's prior 'ok'.

_reap_bounded's pending-task concern was reviewed and REFUTED (a
pending child on external cancel during shutdown is correctly left to
loop teardown). Declined the per-notification refreshers-dict
allocation cleanup: trivial (a 3-entry dict on a rare debounced path),
and the late binding is deliberate for test overrides + mypy attribute
checks.

Tests: push-refresh success/failure write the outcome, removal pops it,
session drop keeps it, failure for a removed server leaves no stale
row; the 3 TestLastRefreshTracking tests updated to the split contract
(_refresh_server propagates, the caller records). Suite 9407 green.

Refs #839
2026-07-14 11:39:25 -07:00
Patrick Buckley 86aeb43120 fix(mcp): review round 6 — close the refresh-outcome reporting residuals
Three residual gaps in the round-5 skip-outcome threading, all in
_refresh_all's other reconnect branches plus the endpoint ordering:

- The disconnected-server reconnect DEFERRAL (_ensure_static_connected
  returns None: a sibling call in flight on the old stack, lock not
  held) returned None without stamping 'skipped', so the endpoint and
  pill read the STALE prior 'ok' and reported a never-run refresh as
  current. Now stamps 'skipped' like every other skip branch.
- A server removed from config between the top-of-loop session check
  and the cfg lookup fell through to  with results[name]
  UNSET, omitting it from the returned dict — an operator refreshing
  that one server saw a bare 'refresh complete' with no line. Now
  reports None so it renders.
- internal_mcp_refresh_one checked 'skipped' BEFORE the error pill, so
  a skip on a server carrying a live error returned a benign 202
  instead of 500 — a status-code-keyed caller would treat an erroring
  server as healthy-but-busy. Error is now checked first.
- _reap_bounded swallowed an external CancelledError (shutdown / an
  operator cancel of the refresh runner) — it now re-raises after a
  best-effort exception retrieval, honouring the cancel. Dropped the
  unneeded asyncio.shield in the process.

Tests: deferral stamps skipped, removed-mid-pass reported not omitted,
endpoint error-beats-skip → 500, reap re-raises external cancel. Suite
9403 green.

Refs #839
2026-07-14 11:39:25 -07:00
Patrick Buckley 748f670fe8 fix(mcp): review round 5 — thread the refresh outcome to every operator surface
The 'skipped'/None refresh sentinel added in round 4 was only half
threaded: consumers still misreported it. Unify all operator surfaces
on ONE source of truth — the per-server last_refresh_outcome ('ok' /
'skipped' / 'error:<Class>') — exposed via a new last_refresh_outcome()
accessor:

- _refresh_all returns None (not ([], [])) for a FAILURE too, so a
  failed refresh is never rendered as 'no changes' (the pre-#839 lie
  the sentinel exists to close); None is disambiguated skipped-vs-failed
  by the outcome. ([], []) now strictly means 'ran, no changes'.
- /mcp refresh renders skip ('skipped — retry scheduled') and failure
  ('refresh failed (error:X)') distinctly from 'no changes'.
- The node-internal refresh endpoint returns 202 'skipped' instead of a
  misleading 200 'ok' for a refresh that never ran (the busy-lock skip);
  it reads the outcome from the manager accessor because the public
  status projection deliberately whitelists last_refresh_outcome out.
- admin.js paints 'skipped' with a neutral info pill
  (.mcp-refresh-pill-skip), not the error-red any-non-'ok' used to get.
- _admit_list_changed rolls back BOTH the coalesce marker and the
  debounce stamp when scheduling raises, so a same-kind push in the
  window afterward isn't debounced against a refresh that never spawned
  (the pool path has no on_debounce_drop recovery).

Tests: endpoint 202-skip, CLI skip/failure render, _refresh_all
failure→None + outcome, spawn-failure stamp+marker rollback. Suite
9399 green.

NOTE filed #843: the admin refresh pill's data (last_refresh_at/outcome)
is stripped by BOTH status projections and never reaches admin.js — a
pre-existing latent bug (the pill has never rendered); the admin.js
color fix here is correct-when-reachable. Out of #839 scope (the read
projection strips it for a privacy reason that needs its own coarsening
decision).

Refs #839
2026-07-14 11:39:25 -07:00
Patrick Buckley 1a80466369 fix(mcp): review round 4 — removal/reconcile lifecycle, honest skip reporting, same-kind debounce recovery
reconcile_sync no longer abandons a DB-driven removal that timed out:
both the removal loop and the config-update loop keep the name in
_db_managed (and skip the follow-on add) when remove_server_sync
returns its mutated-nothing False, so the next pass retries instead of
the deleted/reconfigured server serving stale tools until restart.

remove_server_sync is now cancel-safe end to end: it FORCE-drops the
session before queueing (parked push runners bail at their session
gate instead of serializing ≤30s list calls ahead of the removal —
the noisy #839 server was exactly the one whose runners could starve
its own removal), and wraps the post-lock cleanup in try/finally so a
caller-timeout cancel landing mid-teardown still completes the state
pop, catalog rebuild, and lock retirement rather than stranding a
config-gone ghost catalog. Config survives a park-cancel, so the
health loop recovers it.

_refresh_all reports None (not a fake ([], [])) for a busy-skip or
supersede, stamps a 'skipped' status row, and /mcp refresh renders it
distinctly — the operator is no longer told a never-refreshed server
is current. A same-kind push lost to the debounce window (the prior
runner already finished; the server won't re-announce) arms the
health-tick retry, closing the one staleness hole the per-kind
debounce still had; a push covered by a queued runner does not arm
(no lost change). Static resource/prompt catalogs are capped at
connect discovery and every refresh. _list_resource_pair's reap is
bounded so a future SDK cancel-regression can't wedge the lock.

Cleanups: _arm_refresh_retry (retry-arm gate, ×3), _spawn_full_refresh
(discard+spawn, ×3), _popen_mcp_server (live-server spawn, ×2), the
tautological stamp-arithmetic TestNotificationDebounce deleted. Suite
9395 green.

Refs #839
2026-07-14 11:39:25 -07:00
Patrick Buckley 53f11454ad fix(mcp): review round 3 — cap static catalogs, atomic removal, unify the list_changed protocol twins
- Static resource/prompt catalogs are now size-capped at connect
  discovery AND on every refresh (mirrors the pool twins and the static
  tools path): a misbehaving server's push ran uncapped through the new
  spawned refresh path and could balloon the shared node's merged
  catalogs on every notification.
- remove_server_sync mutates NOTHING outside the per-name lock: the
  up-front config pop meant a removal cancelled while parked (behind
  the push-refresh runners that now share this lock) left a
  half-removed server — config gone, session and published catalogs
  alive, no driver able to reconnect or cleanly re-remove. A timed-out
  removal is now honestly retryable.
- _refresh_all's DISCONNECTED branch busy-skips too (parking inside
  _ensure_static_connected burned the pass's 30s budget on one
  mid-reconnect server), and a busy-skip on either branch ARMS the
  health-tick retry — an operator-requested refresh can no longer be
  silently dropped with output indistinguishable from 'no changes'.
- reconnect_sync drops the session before queueing on the lock (FORCE
  semantics already rebuilt live sessions): parked push runners bail
  at their session gate instead of serializing up to one 30s list call
  per kind ahead of the operator's recovery action. Residual: one
  mid-list holder can still precede the 45s attempt; a timed-out
  reconnect is honest and retryable.
- _refresh_server's supersede check gains the session arm: a spawned
  retry/post-reconnect pass racing an eviction skipped instead of
  manufacturing a false 'not connected' error pill (and a re-arm loop)
  for a self-healing condition.
- The list_changed protocol twins are UNIFIED (Closes #842): the
  admission half (_admit_list_changed) and the runner half
  (_run_list_changed_refresh) each exist once as plain parametrized
  methods — values and small closures, no factory layer (mcp v2 drops
  the factory pattern; the two thin message_handler closures remain
  only as SDK-v1 bindings). The one true asymmetry — coalesce-marker
  ownership on the superseded path — is a documented boolean: pool
  markers are only ever cleared by their runner; static markers are
  cleared by remove_server_sync, so a present marker belongs to the
  re-added generation. Both runners keep their names and signatures;
  the notification suites pass unchanged.
- Cleanups: per-kind staleness rechecks stripped from the static
  refreshers (unreachable under the lock discipline — the MUST-hold-
  lock contract is documented instead); _run_hl (5th run-on-loop copy)
  replaced at 44 call sites; _poll_until centralizes the live-test
  wait loops; docs no longer describe the periodic refresh tier
  removed in eb2a119d.

Refs #839
2026-07-14 11:39:25 -07:00
Patrick Buckley f8f191686f fix(mcp): review round 2 — busy-skip the refresh pass, fail-fast list pairs, health-tick refresh retry
- _refresh_server never parks on a held connect lock: the holder is
  itself a catalog publisher whose publish supersedes the pass, and
  parking burned refresh_sync's whole 30s budget on ONE busy server (a
  reconnect attempt holds the lock up to 45s), failing the operator
  pass for every healthy server queued behind it. Busy → skip (None),
  no publish, no status writes; the identity/state recheck stays as
  belt-and-braces for the one-tick check→acquire race.
- _list_resource_pair: the ONE copy of the paired resources/templates
  list protocol (both twins). Fail-fast — a fast real error (auth /
  method rejection) surfaces as ITSELF instead of being masked behind
  a hung sibling's eventual 30s TimeoutError — with the survivor
  CANCELLED and REAPED inside the timeout scope, never left detached
  on the shared session.
- Health-tick refresh retry: there is NO periodic refresh pass
  (removed in eb2a119d; the docs still claimed the 4h tier — fixed),
  so a push refresh that failed while the transport stayed up had no
  automatic recovery and the shared catalog stayed stale for every
  user until an operator intervened. Failures and busy-skips arm
  _static_refresh_retry via the shared recorder; the health tick
  drains it with one bounded, lock-serialized full pass per tick;
  success, session drops, removal, and the post-reconnect spawns
  clear it. This also un-latches the error pill: the retry's
  completion clears it within a tick.
- _record_refresh_failure: the bearer-redaction policy (type +
  message, never exc_info) lives exactly once; all three
  refresh-failure sites route through it.
- Static runner discards its coalesce marker only AFTER the
  lock-identity check: on the superseded path a marker present in the
  set belongs to the re-added generation's parked runner, and
  discarding it would mint duplicates past the one-parked-runner
  bound (the pool runner deliberately differs — nothing else clears
  pool markers, so its marker is its own to release).
- _clear_static_push_state: the ONE (server, kind) keyspace walk for
  stamps + retry flag (+ markers on removal).
- Tests: busy-skip, superseded-no-status, fail-fast + reap (<5s
  bound), retry arm/drain/re-arm/clear quartet, logged-wrapper
  contract updated to the shared recorder's arg shape; vacuous
  stamp-math test deleted (behavioral per-kind coverage retained);
  _free_port/_wait_tcp_ready/_wait_session_live hoisted to conftest
  for both live tests.

Refs #839
2026-07-14 11:39:25 -07:00
Patrick Buckley aefcf53405 fix(mcp): review round 1 — supersede retired-lock refreshes, per-kind debounce, complete gather pairs
- _refresh_server: post-acquire lock-identity + state-existence recheck;
  a pass superseded by remove (or remove + re-add) returns None and
  writes NO status — it must not run its list calls as a second,
  unserialized publisher against the re-add's discovery wiring,
  resurrect status rows for a removed server, or stamp a false "ok"
  over a generation it never refreshed. _refresh_all treats None as a
  deliberate skip (no breaker success record).
- Debounce stamps are per (server, kind) on BOTH paths: refreshes are
  kind-scoped, so a server-scoped stamp dropped a different-kind
  notification inside the window outright — a tools push swallowed the
  prompts push 100ms behind it, and nothing observed the prompt change
  until the server pushed that kind again. Teardown pops loop the
  kinds; remove_server_sync also discards the server's coalesce
  markers so a parked old-generation runner's marker cannot coalesce
  away a re-added server's first push.
- Resource refreshers (static + pool) gather with
  return_exceptions=True: fail-fast gather left the surviving list
  call running detached — outside the timeout scope and the lock
  serialization — as an unbounded in-flight request on the shared
  session.
- Spawned post-reconnect refreshes route through _refresh_server_logged:
  the re-raise escaped into _spawn_background's done-callback, whose
  exc_info log serializes the chained httpx.Request carrying the
  configured bearer for auth_type=static servers; _refresh_all's
  except drops exc_info for the same reason. Failure diagnostics widen
  to "Type: message" in logs and the error pill — the message text is
  header-free; only the serialized chain leaks.
- Accepted + documented: connect-lock contention on dispatch
  reconnects is bounded to one in-flight list call (parked runners
  bail instantly post-eviction); the error pill persists until the
  next COMPLETED refresh (a notification's arrival proves nothing
  about whether the failure resolved).
- Tests: per-kind debounce independence, superseded-pass writes
  nothing, gather-sibling completion, logged-wrapper swallow with the
  exc_info channel asserted SILENT, remove clears markers;
  _run_on_loop/_drain_background hoisted to conftest (4 drifted
  copies); proc.kill() portability in the live push test.

Runner-twin dedup (static/pool protocol duplication) deferred to #842.

Refs #839
2026-07-14 11:39:25 -07:00
Patrick Buckley 37144991c9 fix(mcp): spawn static list_changed refreshes off the receive loop
The static-path notification handler awaited its catalog refresh inline
in the SDK's receive loop, but the refresh issues a request on the same
session — a request whose response only that (now parked) loop could
route. The refresh never completed, and every user's calls on the
shared per-node session stalled behind it, unbounded, until the health
loop's ping timeout tore the transport down — which was also the only
way a pushed catalog change ever landed. Port of the pool-path protocol
(#836) onto the static primitives:

- Refreshes are debounce-gated, coalesced per (server, kind), and
  spawned as tracked tasks; the runner serializes on the per-name
  connect lock so a refresh, a connect's discovery wiring, and the
  manual/periodic _refresh_server pass can never publish out of order
  (the remove -> re-add race is closed by lock identity, the static
  twin of the pool's entry-identity check).
- The coalesce marker is cleared at lock-acquire so a change the
  in-flight list missed spawns exactly one successor; the finally
  discard is gated on non-acquisition so it never clobbers that
  successor's marker.
- The debounce stamp survives a failed refresh (throttle over lost
  window) and every teardown/eviction path now pops it via the paired
  _drop_static_session_and_stamp, so a reconnected transport's first
  notification refreshes immediately.
- All three static list calls are bounded by _CONNECT_TIMEOUT and
  discard their result if the state entry was replaced mid-flight;
  the resource pair rides one gather (mirrors the pool sibling).
- Failure logging is (Exception, BaseExceptionGroup) type-name-only:
  an escaping group reaches _spawn_background's exc_info log, which
  serializes the chained httpx request carrying the configured bearer
  for auth_type=static servers; the recorded operator error string is
  type-name-only for the same reason. Non-list-changed notifications
  no longer clear the server's error pill (that pop was accidental —
  only a completed refresh proves anything).

Includes a live end-to-end repro (FastMCP subprocess pushing
tools/list_changed through a real receive loop): pre-fix the triggering
call itself deadlocks (verified against main), post-fix it completes
with the catalog landing on the original session, no teardown.

Closes #839
2026-07-14 11:39:25 -07:00
Patrick Buckley b2f53d329b chore(ci): drop review-event triggers from claude.yml
Bot PR reviews (Copilot, code-quality) fired pull_request_review and
pull_request_review_comment runs that always gate out but pile up as
awaiting-approval clutter. @claude stays invocable via issue and PR
conversation comments, the only path actually used.
2026-07-13 23:35:15 -07:00
Patrick Buckley 6f991d6aff chore: bump version to 1.8.0a1 2026-07-13 22:41:36 -07:00
Patrick Buckley 7d4d76e097 fix(providers): PR review — orphan deltas arm the finish shim, test style
- Orphan argument deltas count as delivered output for the
  finish_reason_optional shim, exactly as they count as a streamed
  signal for the terminal harvest: a lax Responses server that never
  announces items AND never sends a terminal event still delivered its
  tool call — with the tolerance declared that is a completion, not an
  IncompleteStreamError. (Review caught the shim/harvest inconsistency
  the round-9 fix introduced.)
- Test style: single import style for the model_turn module, assert on
  a local instead of a call expression, drop a pass-through lambda.
2026-07-13 22:39:19 -07:00
Patrick Buckley 747177a76c fix(providers): review round 9 — orphan/harvest collision, shared shim gate, retired-id rationale
Correctness:
- Responses: orphan argument deltas (streamed without any
  output_item.added) now count as a streamed tool-call signal, so the
  terminal harvest stands down instead of re-emitting the same call
  onto the same slot — the reproduced collision concatenated the
  arguments JSON into an unparseable double copy.

Cleanup / documentation:
- finish_shim_due in _protocol is THE gate for the lax-server finish
  shim — one predicate (and one definition of 'delivered output') for
  all three adapter families, so the same capability flag cannot
  acquire per-family completion semantics.
- The Responses error/response.failed branches share one failure tail
  (only code/message extraction differs) — the same server failure can
  never become retryable through one event type and fatal through the
  other, pre- or post-terminal.
- _format_refusal pins the refusal rendering the streamed event and
  the terminal harvest both use.
- The capability-table floor comment and CHANGELOG Removed entry now
  state the real rationale: OpenAI has RETIRED the pruned ids from the
  API — the rows described unreachable contracts, not unpopular ones.
- CHANGELOG names the stream-entitlement break class (verified-org
  streaming, pre-stream_options gateway api-versions) with its
  serving-side remediation; deliberately no non-streaming fallback.
- docs/architecture.md retry section describes the collapsed
  transport: the two stacked retry ladders, IncompleteStreamError /
  ResponsesStreamFailedError retryability, finish_reason_optional
  remediation; stale non-streaming mentions updated (+ puml).
- Anthropic whole-block emission carries its residual hybrid-gateway
  bet as an explicit comment.

Held on standing rulings: post-finish usage forfeiture (keep result +
warn, rounds 4/8), session merge_usage twin and StreamAbortRef twin
(#832), stream_options wire delta (round 2, caveat now names Azure).
2026-07-13 22:39:19 -07:00
Patrick Buckley 49d33d8594 fix(providers): review round 8 — under-streaming gateway parity, abort-race close, usage-blip visibility
Correctness:
- Responses: output that exists ONLY in the terminal payload (buffering
  gateways that never fire output_text.delta / output_item.added) now
  reaches CompletionResult.content and tool_calls — the retired
  non-streaming _parse_response read this same payload, so the drain
  must too instead of returning a clean-looking empty success (blank
  compaction summary, silently-skipped tool call). Gated on nothing of
  that kind having streamed; refusal parts render as the streaming
  branch does.
- Anthropic: content pre-populated inside content_block_start (whole-
  block lax-gateway emission — the real API sends start blocks empty)
  is emitted for text, thinking, and tool_use input, type-guarded like
  _reasoning_text so duck-typed blocks can't leak non-strings.
- Responses: a response.completed payload that OMITS status maps to
  "stop" via the event type, matching the payload-less branch — the
  empty-string status read as 'length' and fired truncation policies
  on complete output.
- model_turn: the drain-retry loop re-checks cancel_ref.aborted after
  the backoff sleep — an abort landing mid-sleep now kills the
  abandoned worker with the original failure instead of issuing one
  more full request behind the deadline's back.
- drain_stream: the post-finish transport-blip tolerance logs a
  warning naming whether usage was captured — the kept result may
  report usage=None (chat-lane usage trails the finish reason) and
  that spend was vanishing from usage accounting with no signal.

Cleanup:
- ChatSession's inline tool-call fold adopts accumulate_tool_call_delta
  (drop-in — same ToolCallDelta semantics), so THE merge rule now has
  one implementation across the chat loop, drain_stream, and the
  Google capture; the helper's mirror-mandate docstring is retired.
- The task-agent _api_call contract comment reconciles the two retry
  layers (sub-harness owns request-level policy; model_turn owns
  drain-time re-issue) instead of claiming model_turn is policy-free.
- Anthropic's three terminal-emission sites share one
  _attach_terminal_blocks helper — replay fidelity can't depend on
  which terminal path a stream took.
- Responses create_streaming resolves capabilities once.

Held on standing rulings: o-series capability-row removal (4th report;
deliberate break, release-noted), StreamAbortRef/_CancelRef unification
(#832; docstring mirror-mandate).
2026-07-13 22:39:19 -07:00
Patrick Buckley 8fa0e7a29e fix(providers): review round 7 — id-disciplined slots, all-lane finish tolerance, retry backoff
Correctness:
- ToolCallSlotter: a slot whose id is KNOWN never splits on an id-less
  delta — on an id-disciplined server new calls arrive with ids, so an
  id-less fragment (the call's FIRST name announcement included) is
  always a continuation. Round-6 regression: {id} → {name} → {args}
  emission split into an unnamed id-bearing call plus a nameless twin.
  Also: a name arriving for a slot with no name yet never splits
  (args-first emission), and a bare same-name delta after complete
  arguments merges as a redundant footer instead of minting a phantom
  zero-argument call that would re-run a side-effecting tool.
- finish_reason_optional is honored on every drained lane, not just
  Chat Completions: Anthropic shims a missing message_delta
  stop_reason + message_stop pair, Responses a missing terminal event
  (both with collected blocks riding the shimmed finish) — the
  documented capabilities-JSON remediation now works on the
  anthropic-compatible/responses-compat gateways it was written for,
  matching the retired non-streaming paths' tolerance.
- Responses: an in-band error/response.failed frame arriving AFTER the
  terminal event is teardown noise — log and end the stream instead of
  raising away a generation already in hand (the in-band twin of
  drain_stream's post-finish transport-blip tolerance).
- model_turn drain retries pace like the SDK request retry they
  replace: 0.5s base, doubling, ±50% jitter — instant re-issues
  re-hit the still-active rate limit/overload and synchronize into
  fleet-scale retry bursts.
- Responses slot bookkeeping survives lax servers: slots minted by a
  counter (len(dict) collided calls after a duplicate/empty item-id
  overwrite), orphan argument deltas route to the most recently
  announced call instead of hardwired slot 0.

Cleanup:
- on_tool_call_delta now receives the normalized ToolCallDelta plus the
  raw SDK delta — Google's capture accumulates the exact bytes the
  mirror sees (the byte-identical extraction no longer exists twice).
- _ArgsScanner feeds only fully id-less slots (its verdict is never
  consulted for id'd slots — dominant-case hot path).
- Anthropic retryable set hoisted to a class constant (per-access
  frozenset allocation, same pattern already fixed on Responses).
- GoogleProvider class docstring names the hook-based capture instead
  of the deleted _extract_tool_calls override.
2026-07-13 22:39:19 -07:00
Patrick Buckley 16647db1b0 fix(providers): review round 6 — strict-by-default finish gate, slotter v3, drain retry
Correctness:
- The chat-lane finish shim is now armed only by an operator-declared
  finish_reason_optional capability (model-definition capabilities JSON).
  Default lanes treat a clean finish-less end as died-mid-generation
  (retryable) — SSE cannot distinguish lax-server completion from a
  worker dying behind a clean-closing proxy, and the default must catch
  truncation rather than bless it. When armed, reasoning-only output
  counts as a completed generation (parity with the retired
  non-streaming path's finish_reason-or-stop default).
- ToolCallSlotter v3: id-less call-boundary decisions now consult
  argument JSON completeness (incremental scanner) and name identity
  instead of a boolean has-args gate. Fixes both residual id-less
  ambiguities: two zero-argument whole-delta parallel calls no longer
  fuse (silently dropping an action), and redundant per-fragment name
  headers no longer split one call into malformed half-JSON calls.
- model_turn re-issues transient mid-stream deaths (provider's
  retryable_error_names, raised while draining) up to twice — the new
  home of the SDK request-level retry the non-streaming transport gave
  every single-shot lane (judge, title, perception, compaction).
  Request-time failures keep the SDK's own policy; an aborted
  cancel_ref suppresses re-issue (StreamAbortRef gains .aborted).

Cleanup:
- One slotter drives both the normalized mirror and Google's raw
  fidelity capture via an on_tool_call_delta hook — raw/mirror slot
  parity is structural now, not a maintained invariant.
- accumulate_tool_call_delta in _protocol.py is THE tool-call merge
  rule; drain_stream and the Google capture use it (session's copy is
  #832's tracked adoption).
- Responses terminal rebuild only runs when the terminal payload can
  disagree with the .done-collected items (truncation or count
  mismatch); on rebuild, annotations are replaced, not re-extended.
- Responses retryable set precomputed at class creation.

Held on standing rulings: o-series capability-row removal (deliberate,
release-noted with remediation), StreamAbortRef/_CancelRef unification
(#832; docstrings mandate mirroring until then).
2026-07-13 22:39:19 -07:00
Patrick Buckley 91c46051d9 feat(providers): drop o-series and pre-5.4 GPT-5 capability rows
The OpenAI commercial capability table floor is now gpt-5.4: o1,
o1-mini, o3, o3-mini, o3-pro, o4-mini, gpt-5, gpt-5-mini, gpt-5-nano,
gpt-5-pro, gpt-5.1, gpt-5.1-codex-max, gpt-5.2, gpt-5.2-pro, and
gpt-5.3 are effectively unused in the field. The gpt-5-search-api row
(different product surface) and the audio/STT/TTS rows stay.

A legacy id now resolves to OPENAI_DEFAULT (temperature sent, no
declared effort vocabulary, 200K window) — which those models may
reject; the remediation is the model definition's capabilities JSON or
a current model, release-noted under Unreleased → Removed.

This also retires the transport-collapse review's thrice-reported
"stream-rejecting o1-era models are stranded" finding by removing its
subject: no row in the table describes a non-streaming model anymore.

Tests migrate to 5.4-era equivalents that pin the same behaviors:
always-reasoning temperature suppression and off-list effort snap
(gpt-5.4-pro for gpt-5-pro/o3), explicit-none forwarding (gpt-5.4 for
gpt-5.1), empty-effort-vocabulary knob drop (gpt-5-search-api for
o1-mini), and the longest-prefix shadow hazard (gpt-5.4-pro vs gpt-5.4
for codex-max vs gpt-5.1).
2026-07-13 22:39:19 -07:00
Patrick Buckley 3a28dc2f16 fix(providers): review round 5 — same-id fragment merge, post-finish blip tolerance, chat finish shim
Correctness:

- ToolCallSlotter's reannounce split is gated to ID-LESS deltas: id
  equality proves the same call, so compat servers that repeat the
  id+name header on every argument fragment merge back into one call
  with valid JSON (round 4's ungated heuristic split them into
  duplicate half-JSON calls — execution-confirmed by the review).  The
  residual id-less repeat-name-per-fragment shape is documented as
  inherently ambiguous; ids are the only disambiguator.
- drain_stream keeps a completed result when the transport blips AFTER
  the finish reason (trailing usage chunk / citation footer window):
  the generation is in hand, so forfeit the trailing metadata instead
  of discarding a fully-delivered verdict or re-paying a compaction.
- The chat iterator shims finish_reason="stop" when a stream ends
  CLEANLY after delivering content or tool calls — the deleted
  non-streaming `or "stop"` default for lax finish-reason-less servers,
  now safe to restore because abrupt deaths surface as
  httpx.TransportError (round 4) rather than clean exhaustion.  This
  supersedes the round-3 keep-the-gate ruling: the httpx catch changed
  the calculus, and the Anthropic/Responses lanes already got their
  marker-based shims.  Empty/reasoning-only streams still fail the
  complete-or-error gate.  Two streaming tests gained the shim chunk.

Dispositions held: o1-era stream-rejecting models (third re-report)
stay a release-note remediation per the earlier ruling.

Cleanup: the two Responses terminal branches collapse into one path
(status derived from the event type when the payload is missing —
also fixes the end-of-stream debug log reporting finish_reason=None
for completed lax streams); the annotations walk is one shared helper
(the two copies had already diverged on None-content guarding);
_raise_responses_failure is annotated NoReturn; scripts/livepass.py
drops the phantom supports_streaming key; test_model_registry's
capture helpers ride scripted_chat_client; _openai_stream_chunk points
at its fake_chat_stream shape-twin for future consolidation.
2026-07-13 22:39:19 -07:00
Patrick Buckley cf7cfe8932 fix(providers): review round 4 — wire-error retryability, tap/mirror slot parity, terminal completeness
Correctness:

- drain_stream chains raw httpx.TransportError from stream iteration
  into retryable IncompleteStreamError (original type+message preserved
  via __cause__): streaming moved the body read out of the SDK's
  APIConnectionError-wrapped request, so mid-body connection drops and
  read timeouts — retried transparently on 1.7 — were escaping every
  single-shot retry loop as instantly-fatal raw httpx names.
- The index remap is extracted as ToolCallSlotter and GoogleProvider's
  raw tap slots THROUGH IT over the same delta sequence as the base
  iterator: round 3's mirror-side de-fusion had left the tap keying by
  wire index, so a degenerate stream produced 2 mirror calls vs 1 fused
  raw dict — _prepare_messages' length gate then silently dropped the
  thought_signature lane (400 on signature-strict Gemini models).
- The slotter also splits ID-LESS degenerate parallel calls: a delta
  announcing a name for a slot that already accumulated arguments is a
  second whole call, not a fragment (fragmented single calls pinned
  unaffected).
- A payload-less Responses terminal event keeps the provider_blocks
  already collected from output_item.done events (they came from the
  stream, not the missing payload); only usage is genuinely lost.
- The truncation-rebuild path walks the terminal output's message
  annotations, so truncated web-search turns keep their Sources footer
  (the in-flight item never received output_item.done).

Cleanup: one _raise_responses_failure ladder serves both in-band
failure shapes (error events + response.failed); IncompleteStreamError
joins the public providers export (docstrings tell callers to catch
it); the de-fusion tests ride the file's existing _openai_stream_chunk
helpers instead of a third hand-rolled SSE fake; the dead if-response
guard in the terminal branch is gone.

Deferred with note: classifying IncompleteStreamError once at the
retry-predicate consultation site instead of per-provider strings is
#832 territory (the predicate lives in ChatSession); the six-lane
parametrized test guards the listing until then.
2026-07-13 22:39:19 -07:00
Patrick Buckley 56b7674dfa fix(providers): review round 3 — in-band error events, terminal-marker tolerance, adapter-owned de-fusion
Correctness:

- Responses _iter_stream handles the SDK's in-band `error` SSE event
  (ResponseErrorEvent is YIELDED, not raised, and no response.failed
  need follow): the real API code/message now surfaces — code-gated for
  retryability like response.failed — instead of the stream exhausting
  finish-less and hiding the cause behind a retried
  IncompleteStreamError.
- Anthropic message_stop supplies a missing stop_reason: it is a genuine
  terminal marker, so a compat /v1/messages shim whose message_delta
  omits stop_reason completes (blocks intact) rather than failing a
  generation that arrived — tolerance the retired non-streaming default
  provided, restored without weakening the died-mid-response gate.
- A Responses terminal event without its response payload still emits
  the finish reason its type implies (lax compat servers), losing only
  usage/blocks rather than the whole result.

Dispositions held (documented, not re-coded): the complete-or-error
gate stays for finish-less Chat Completions streams — indistinguishable
in-band from a died generation, and silent partial-storage is the worse
failure; CHANGELOG now names the shape and each provider's accepted
terminal markers. supports_streaming deletion and the stream_options
wire delta were ruled earlier and keep their release-note remediations.

Cleanup: index-degenerate de-fusion MOVED from drain_stream into the
chat adapter's iterator (mirroring the Anthropic iterator's index
assignment) so the interactive loop is fixed too and the drain returns
to a plain mirror of the main-loop accumulator; a parametrized test
locks "IncompleteStreamError is retryable" across all six provider
lanes instead of trusting per-adapter memory; scripted_anthropic_client
joins scripted_chat_client (shared _ScriptedClient class, no function
attrs) and the two remaining hand-rolled anthropic closures convert.
2026-07-13 22:39:19 -07:00
Patrick Buckley 3ffa8b9057 fix(providers): review round 2 — complete-or-error drain, code-gated retries, truncation-safe blocks
Correctness (3 confirmed + 2 plausible, all fixed):

- drain_stream now raises typed, retryable IncompleteStreamError when a
  stream exhausts without any finish reason — every adapter emits one on
  a healthy stream, so its absence means the generation died
  mid-response behind a cleanly-closing proxy.  This restores the
  retired transport's complete-or-error contract (a half-generated
  compaction summary was previously returned as finish=stop and stored,
  silently replacing real history) and DELETES round 1's suffix-info
  fold: with no finish-less success path there is nothing to classify,
  so a trailing status ping can never be stored as content either.
- Index-degenerate parallel tool calls get distinct slots: a delta whose
  id differs from its slot's opens a new call (id-less fragments still
  follow their index's current call), so historical compat servers that
  emit every parallel call at index 0 no longer fuse distinct calls
  into concatenated garbage arguments.  Result order stays index-sorted
  (stable) like the retired array parse.
- response.failed retryability is code-gated: only transient codes
  (server_error, rate_limit_exceeded) raise the retryable typed error;
  deterministic rejections (invalid prompt, image fetch, policy) raise
  plain RuntimeError and stop retry loops on attempt zero instead of
  running the full backoff ladder against a doomed request.
- Terminal Responses events rebuild provider_blocks from
  response.output when present: the item being generated at
  max_output_tokens truncation never receives output_item.done, and
  storing a reasoning item without its required following item made the
  next turn's replay a 400.
- merge_usage's base case uses dataclasses.replace so a future UsageInfo
  field can't be silently zeroed on drained lanes.

Cleanup: run_abortable_with_deadline bundles the three-point abort
wiring (ref + cancel_ref + on_abandon) so it cannot be half-wired —
both judges converted; scripted_chat_client hoists the 14 chat-lane
fake_create closures (call scripts + .calls recording replace per-test
counter cells); fake_chat_stream gains reasoning=, collapsing the
reasoning-capture suite's hand-rolled chunk shape; FakeAnthropicBlock
hoists the duplicated _Block test class; the class and judge PlantUML
diagrams drop the retired create_completion flow.

Also converts test_model_registry's agent-model fakes, which returned
legacy response objects that iterated as EMPTY streams — they only
passed through the old drain's silent finish=stop default, exactly the
hazard the new gate exists to catch.
2026-07-13 22:39:19 -07:00
Patrick Buckley 08580f25f9 fix(providers): review round 1 — streaming parity gaps the collapse exposed
Correctness (4 confirmed + 1 plausible fixed, 2 accepted+documented):

- Anthropic _iter_anthropic_stream handles citations_delta: text-block
  citations now ride the raw block into provider_blocks, as replay
  requires (the retired non-streaming lane preserved them via
  model_dump; the streaming lane dropped them — a pre-existing main-loop
  gap the collapse would have extended to single-shot lanes).
- Anthropic text blocks separate with "\n" at each subsequent block
  start, restoring the retired lane's "\n".join rendering on drained
  lanes AND un-fusing streamed web-search responses in the chat loop.
- response.failed raises typed ResponsesStreamFailedError, listed in the
  provider's retryable_error_names — retry loops treat an in-band
  failure like the wire errors it stands in for instead of
  hard-stopping on a bare RuntimeError (judges keep their heuristic
  fallback after retries).
- drain_stream folds a finish-less stream's terminal citations footer
  (suffix rule: pre-finish info invalidated by any later payload), so
  lax compat servers that never send finish_reason keep their Sources.
- usage max-merge extracted as merge_usage() in _protocol.py — the one
  definition drain uses now and the session's inline consumer adopts on
  #832.

Accepted + release-noted instead of coded around: strict pre-2024
compat servers that 400 on stream_options (such a server already cannot
serve the chat loop; CHANGELOG caveat extended), and repeated-index
parallel tool-call merging on legacy compat servers (identical to the
main loop's accumulator semantics; a shared guard belongs in the #832
unification).

Cleanup: run_with_deadline grows on_abandon (best-effort, cannot mask
the deadline error) and both judges drop the copy-pasted abort
choreography; StreamAbortRef documents the _CancelRef adoption plan;
test_model_turn's fake replays through the shared as_stream adapter;
docs/architecture.md drops the retired Protocol row.

Tests: refusal handler pinned (was advertised, untested); typed-failed
retryability; citations capture; text-block separator (plus the mixed
text+search expectation updated for the separator chunk); finish-less
citation fold; on_abandon firing matrix; StreamAbortRef arrival race.
2026-07-13 22:39:19 -07:00
Patrick Buckley 1e7ad7bcb6 feat(providers): one transport — drain create_streaming, retire create_completion (#831)
Every single-shot lane (model_turn: judges, titles, compaction, web-fetch
extraction, perception, eval, optimizer) now samples through the provider's
streaming entry and accumulates via a shared drain_stream(), deleting
create_completion from the Protocol and all three adapters (xai/google
inherit). Request shaping can no longer drift between the two consumption
styles, and callers keep the exact CompletionResult contract.

The drain mirrors the main loop's proven chunk semantics: per-field
max-merge for usage (Anthropic splits prompt/completion across
message_start/message_delta), tool-call assembly by delta index,
provider_blocks from the terminal emission, trailing citation info folded
back into content (byte-matching the old format_citations append),
mid-stream status pings dropped.

Also in this change:

- model_turn grows cancel_ref; both judges wire their run_with_deadline
  abandon paths to a new StreamAbortRef (deadline.py) that closes the SDK
  stream — a timed-out judge call now aborts its HTTP read instead of
  pinning a daemon thread until the next upstream chunk. The append hook
  covers the arrival race, mirroring ChatSession._CancelRef.
- Responses streaming gains the response.incomplete terminal handler
  (truncated runs were mislabeled finish=stop and lost final usage AND
  collected provider_blocks) and a refusal handler ([Refused: …] content,
  matching the retired non-streaming rendering). Both also fix the main
  chat loop, which shared the gaps.
- supports_streaming capability flag deleted (zero readers) along with
  its admin capability tile; o1-era models that reject streaming need a
  model alias pointing at a current model (release-noted).
- Helpers that existed only for the deleted transport go with it:
  Responses._parse_response, chat/google._extract_tool_calls.

Known behavioral deltas (release-noted): OpenAI-compatible servers that
ignore stream_options.include_usage stop producing usage rows on these
lanes; multiple Anthropic text blocks concatenate without the old "\n"
joint (matching the main loop); model_turn lanes no longer risk client
read-timeouts on long generations — the reason the Anthropic adapter
already drained a stream internally.

Tests: new test_drain_stream.py pins the accumulator rules; shared fakes
(as_stream, fake_chat_stream, fake_anthropic_stream) migrate 11 suites to
the streaming transport, with the task-agent and adapter suites now
exercising the real _iter_stream + drain path end to end.
2026-07-13 22:39:19 -07:00
Patrick Buckley a66e9d456d fix(mcp): gate the marker release on non-acquisition; structure the paired protocols
Close the round-8 review findings:

- The refresh runner's finally-discard releases the coalesce marker
  ONLY when the lock was never acquired (cancelled while parked).
  After the at-acquire discard, a marker present at exit belongs to
  the successor spawned during the in-flight list call — discarding
  it unconditionally let the handler mint one extra runner per
  debounce window while the lock was congested, reopening the
  unbounded runner FIFO the marker exists to bound.

- The observe-before-lookup preamble lives once in
  _pool_lookup_checked (snapshot taken synchronously before the
  lookup await, render paired with the convergence drop) instead of
  verbatim in all three dispatchers — the ordering contract is now
  structural rather than comment discipline.

- drop_session is paired with its debounce-stamp pop in
  _drop_session_and_stamp, shared by the eviction, teardown, and
  owner-death paths; the shutdown sweep clears the pool notification
  stamp dict and the coalesce marker set alongside the other pool
  state.

- _mcp_tools_change_seq is initialized unconditionally for every
  session kind, so the attribute's existence no longer encodes
  whether an MCP client was wired at construction.
2026-07-13 21:13:42 -07:00
Patrick Buckley e9ecf91c07 fix(mcp): observe before the lookup; coalesce queued refreshes; pop stamps on every teardown
Close the round-7 review findings:

- The dead-grant observation is now snapshotted BEFORE the classified
  lookup's first await, by the callers (the three dispatchers via
  _pool_lookup_failure, _prime_one, and the obo credential gate), and
  _schedule_dead_grant_drop requires it as a parameter: snapshotting
  after the lookup returned could capture a session the
  consent-completion prime connected mid-lookup — its awaits can park
  on executor hops — and the drop then evicted the just-restored
  catalog it exists to spare, with no remaining re-prime path.

- Spawned list_changed refreshes coalesce on a per-(key, kind) marker:
  set at spawn, cleared the moment the runner acquires open_lock
  (before its list call, so a change the in-flight list missed spawns
  exactly one successor). Admission was one per 5s debounce window
  while each runner can hold the lock up to the 30s refresh timeout,
  so a notifying-but-slow server accreted lock waiters without bound —
  FIFO dispatch waits past the 120s budget, idle eviction starved by
  the contested lock, and background tasks growing for as long as the
  server kept notifying. The runner also returns quietly for an
  evicted session instead of failing through the log. The residual
  duty-cycle case (a wedged-but-notifying server defers idle eviction
  of its own entry until the first dispatch, recovery, or silence) is
  documented at the runner.

- Every teardown path now pops the notification debounce stamp:
  _teardown_pool_entry and _on_pool_owner_death left it in place, so
  the keep-stamp design's documented reconnect backstop did not exist
  on the idle-collapse and connect-failure paths — a change announced
  in a failed window could be debounced against a pre-collapse stamp
  after reconnect and never land. The idle-close path's own pop is
  now owned by _teardown_pool_entry.

- Cleanups: the notification table maps type to kind label only, with
  the kind-to-refresher map bound at dispatch time (mypy-checked
  attribute references, instance overrides keep working) instead of
  getattr on a name string; _schedule_dead_grant_drop skips when there
  is provably nothing to converge (no entry, or a session-less
  catalog-less stub), sparing a tracked no-op task per unconsented
  server per prime at scale; the fire-and-forget prime idiom's three
  hand-synced copies collapse into try_prime_user_pools (session
  construction, acting-user change, OIDC capture); the stale
  lock-contract docstrings on the resources/prompts refreshers now
  state the held-lock requirement; has_live_session_listener is the
  sole listener-liveness predicate (the private alias is gone); the
  construction-scoped tools-seq read is a constructor local instead of
  a persistent ChatSession attribute.
2026-07-13 21:13:42 -07:00
Patrick Buckley 7186e1e709 fix(mcp): observe sessions at dead-grant discovery; serialize spawned refreshes
Close the round-6 review findings, all in the round-5 surface:

- Dead-grant drops snapshot the entry's session when the failed lookup
  is observed and skip only when the session CHANGED since: a warm
  transport that predates the revocation is evicted with the catalog
  (failed lookups short-circuit dispatch before any 401 could evict it,
  so nothing else converges a warm entry until the idle TTL), while a
  session a re-consent prime created after the observation still parks
  the drop. The obo credential gate inherits the same semantics for
  warm obo entries.

- The spawned notification refresh serializes on open_lock with a
  same-entry recheck: unserialized it raced the connect wiring block
  (older discovery snapshot republished over the refresh's newer
  catalog, permanently hiding the change behind the consumed debounce
  stamp) and sibling same-key refreshes (the slower list call
  publishing the older catalog last).

- The refresh failure path keeps the debounce stamp instead of popping
  it: pop-on-failure re-armed the handler on every notification, so a
  fast-failing server spawned refresh tasks unthrottled at its
  notification rate. Changes announced in a failed window converge on
  the next list_changed or reconnect (teardown pops the stamp).

- The refresh runner catches BaseExceptionGroup alongside Exception: a
  wedged anyio transport surfaces session-op failures as groups, which
  escaped to the background-task failure log whose exc_info serializes
  the chained httpx request carrying the user's bearer.

- Cleanups: the three list_changed handler branches collapse into one
  table-driven path; _reprime_active_users reuses _live_listener_uids;
  the obo gate's synthesized kind="missing" verdict is contract-pinned
  to get_obo_access_token_classified's missing-credential return.
2026-07-13 21:13:42 -07:00
Patrick Buckley 2ce6638761 fix(mcp): spawn list_changed refreshes off the receive loop; close round-5 findings
The headline finding is pre-existing and structural, surfaced by this
branch's timeout: the SDK awaits notification handlers INLINE in its
receive loop, so a handler that awaits a request on the same session
can never receive its response — push-driven catalog refreshes have
never completed against a healthy server, and with the new timeout
they also stalled every in-flight call on the session for its
duration. Refreshes are now spawned as tracked background tasks, and
a FAILED refresh returns the debounce stamp so the server's next
list_changed retries instead of being dropped inside the window.

Also from the round:
- The obo credential-presence gate skipped exactly the per-server
  lookup whose kind='missing' would have dropped retained catalogs, so
  unlinked users' ghosts survived every new-session prime. The gate
  now schedules the same dead-grant drop for catalog-bearing obo
  entries before skipping the servers.
- Dead-grant drops re-validate under open_lock via skip_if_connected:
  a drop parked behind a re-consent prime's connect must not clear the
  freshly restored catalog (a live session proves a connect succeeded
  after the failed lookup that scheduled the drop). The explicit
  revocation path still clears warm entries unconditionally.
- The constructor's convergence re-check moved to the end of tool
  setup, where every _on_mcp_tools_changed dependency exists — the
  while-loop re-read could still be clobbered by the tool-search
  construction reading mixed state, and a mid-construction callback
  crash (pre-existing, swallowed by the fan-out) loses its update.
- _drop_catalog_locked's docstring told the truth about its wait bound
  (a same-key dispatch holds open_lock across its entire SDK call).
- The OIDC capture-site liveness gate call moved inside its try —
  nothing on that best-effort path may fail a login.
- One _pool_lookup_failure helper pairs render+drop for all three
  dispatchers; fake pool-tool seeds deduped to one module helper; the
  sleep-based test syncs replaced with a deterministic
  _background_tasks drain.
2026-07-13 21:13:42 -07:00
Patrick Buckley 1c4761971c fix(mcp): strip the revocation-generation protocol; keep the stable core
Round 4 confirmed six correctness bugs, all inside round 3's
catalog_gen machinery (a ChatSession.__init__ crash from the mirror-
race re-run, an orphaned-lock race created by the ensure-before-lookup
reorder, no generation memory across entry re-creation, gen reset on
re-ensure, a raw internal error surfacing to the session layer). Four
rounds of evidence: hardening this event-driven subsystem with new
concurrency machinery breeds interaction bugs about as fast as it
closes cosmetic races. Decision: remove the protocol, keep the core.

Stripped: PoolEntryState.catalog_gen, the expected_gen threading
through dispatch/prime/connect, the dispatcher ensure-before-lookup
reorders, _PoolGrantRevokedError, and the refresh gen-guards (the
entry-identity check stays — it protects against entry replacement
with no protocol). The publisher-suspended-across-a-drop races those
closed are now ACCEPTED RESIDUALS, documented at
_evict_session_drop_catalog: the ghost self-heals at next use via the
dead-grant drop (dispatch AND priming), and a reconnected stale bearer
dies at access-token expiry — the same bound every warm session
already rides at revocation time.

Kept from round 3 (stable, orthogonal): staged discovery publication,
prime-side dead-grant drops, the obo re-login prime, the single
_pool_lookup_verdict classification, drop_session() pairing, and the
tracked revocation drop task.

Fixed from round 4's orthogonal findings:
- ChatSession construction converges its tool lists with a bounded
  re-read loop instead of calling _on_mcp_tools_changed, which
  dereferences tool-search state initialized later in construction.
- _refresh_pool_server_tools gets the asyncio.timeout its resource and
  prompt siblings already had — a wedged server no longer hangs the
  notification-handler task.
- The OIDC capture-site prime is gated on the user having a live
  session listener (new public has_live_session_listener): routine SSO
  re-logins with nothing open no longer fan out mints and connects.
- _pool_lookup_verdict returns a Literal so a typo'd verdict
  comparison fails mypy instead of silently never matching.
- The triplicated double-401 comment blocks shrink to two-liners
  pointing at the single rationale in _evict_session's docstring.
2026-07-13 21:13:42 -07:00
Patrick Buckley 1e84f62619 fix(mcp): round-3 review fixes — revocation generation for catalog publishers
Round 3 identified the class behind the remaining bugs: catalog
PUBLISHERS never re-validate revocation state, so anything that read a
token or suspended before a drop could republish (resurrect) a revoked
catalog that retention then keeps forever. One primitive closes the
class:

- PoolEntryState.catalog_gen, bumped by _evict_session_drop_catalog.
  The three list_changed refreshes snapshot it before their awaits and
  discard results if it moved; dispatch and priming snapshot it before
  their token reads, and _connect_one_pool refuses to connect (raising
  _PoolGrantRevokedError, a non-breaker failure) when the generation
  moved past the caller's snapshot — the bearer in hand predates a
  disconnect.
- _connect_one_pool stages all three discovery results locally and
  publishes them together in the final wiring block: a mid-discovery
  failure now leaves the retained catalog exactly as it was instead of
  a torn half-update diverging from the per-user maps.
- Priming converges dead grants too: _prime_one schedules the same
  catalog drop the dispatchers use, so a NEW session's prime clears
  ghosts left by a disconnect made on another node.
- obo re-login is the obo restore moment: a successful credential
  capture at the OIDC callback now schedules prime_user_pools, so a
  previously dropped obo catalog returns to LIVE sessions (obo has no
  consent flow to heal through).
- ChatSession construction re-runs its tool rebuild when the change
  marker advanced during its authoritative read — the mirror race
  where a fresher listener update was clobbered by the constructor's
  staler snapshot.
- evict_user_session's drop task is now tracked (_spawn_background) so
  shutdown cancels it instead of abandoning a parked task.

Dedup/altitude from the round: _schedule_dead_grant_drop is the single
drop block (was three byte-identical copies); _pool_lookup_verdict is
the single lookup classification — rendering and _lookup_grant_dead
both derive from it, with literal code strings kept so the consent-url
sibling audit still sees the sites (expected count 7 -> 5 after the
collapse); PoolEntryState.drop_session() pairs session/bound_token
clearing structurally (owner-death was missing the bearer clear).
2026-07-13 21:13:42 -07:00
Patrick Buckley 49a30c1547 fix(mcp): round-2 review fixes for the catalog-retention branch
Five confirmed correctness findings, all in the round-1 fix code:

- The dead-grant catalog drop at the token-lookup error sites is now
  SCHEDULED instead of awaited: the drop waits on open_lock, which a
  same-key dispatch holds across its entire SDK call, so awaiting let
  a token-side error stall past the sync timeout and charge the
  breaker it is documented to bypass.
- The double-401 drop is removed entirely: a second 401 after a
  SUCCESSFUL forced refresh proves the grant is alive at the AS — it
  is the resource server rejecting a fresh bearer (JWKS lag, audience
  misconfig, clock skew), and dropping the catalog made RS recovery
  unhealable for live sessions. A genuinely revoked grant converges
  via the token-lookup drop (its row is gone by then).
- The drop decision has one source of truth (_lookup_grant_dead),
  gated on the token store + storage actually being wired: the obo
  lookup returns kind='missing' for boot-window infrastructure
  absences too, which must not clear catalogs. The empty-token
  fallback now classifies with its consent_required siblings.
- The LRU pass re-checks the LIVE warm count per iteration again —
  the one-shot over-count never saw concurrent warm-set changes
  (revocation evictions, owner deaths, connects) and closed healthy
  transports below the cap.
- _on_pool_owner_death clears bound_token: the third session-drop
  site the bearer-clearing sweep missed, and the one that cools an
  entry indefinitely.

Also from the round: reconcile stores both pool-name registries as
adjacent assignments and _retain_cooled documents the residual
single-bytecode flip-tear window (restored by the same reconcile's
re-prime); catalog-less drops skip the zero-delta rebuild+notify
fan-out; session construction does one authoritative post-registration
read instead of read-twice; evict_user_session schedules the locked
drop directly.
2026-07-13 21:13:42 -07:00
Patrick Buckley 4d89efa7b8 fix(mcp): registry-liveness for cooled entries, dead-grant convergence, revoke interlock
Fix round for the review of the #836 catalog-retention change
(14 findings: 9 correctness, 5 cleanup):

- Cooled retention now requires the server to still exist in the pool
  registries (_retain_cooled — ONE policy shared by the TTL skip and
  the close path): an admin delete/disable/rename/auth-flip drops the
  ghost catalog within one eviction tick. Pre-#836 the idle TTL
  bounded such ghosts to ~10 minutes; retention made them immortal,
  including a disabled server that stayed dispatchable and duplicate
  tool names after a flip to static.
- A dispatch that learns the grant is durably GONE (token row missing
  or refresh permanently rejected — the mcp_consent_required class)
  drops that (user, server) catalog, so a disconnect made on another
  node converges here at first touch instead of re-offering revoked
  tools behind a consent card. Re-consent restores the tools through
  the existing consent-completion single-server prime.
- Revocation drops serialize against an in-flight connect via the
  entry's open_lock (_drop_catalog_locked): an unserialized drop was
  republished (resurrected) by the connect's completing discovery,
  with nothing left to ever clear it.
- The LRU pass counts closes incrementally and the TTL pass checks a
  once-per-tick listener snapshot instead of scanning the listener
  registry per entry under its lock.
- bound_token (a plaintext bearer) is cleared whenever the session is
  dropped — it is dead on a session-less entry, and cooling otherwise
  retained it for the life of the user's sessions.
- Per-user status falls back to the cooled catalog for its counts and
  reports the idle pool separately (user_pools_idle): cooled is the
  steady state now, and the warm-only view said '0 tools' for a
  catalog the same user's chat was actively offered.
- Session construction re-reads the merged tool lists after listener
  registration, closing the read-then-register window that missed a
  concurrent drop's only notification.
- Dedup: one retention policy, one warm predicate, one rebuild+notify
  sequence (was three copies), and the drop-catalog path now layers
  on _evict_session instead of copying its prologue.

Known limits, deliberately deferred: shared-workstream participants
who are not the acting user still lose their catalogs at TTL (not a
regression — the next send re-primes), and the pre-existing
orphaned-lock race on full-drop is unchanged.
2026-07-13 21:13:42 -07:00
Patrick Buckley cb94ea349f fix(mcp): retain per-user catalogs when pool sessions close under live sessions
Idle-TTL eviction tore down a per-user pool entry, rebuilt the user's
tool/resource/prompt catalogs (now empty), and notified listeners — so
every live ChatSession for that user silently lost the server's tools
after 10 idle minutes, with no way back: prime_user_pools only runs at
session construction, acting-user change, and reconcile, and the
emptied catalog closes the session-side is_mcp_tool gate, so even a
history-motivated call can't reach the lazy-reconnect dispatch path.
The dispatch-failure paths (_evict_session on 401/403/transport)
cleared catalogs the same way, so a transport blip during a tool call
caused the same permanent loss with no TTL involved — and made the
breaker's half-open recovery and the consent/step-up cards unreachable.

Both now follow _on_pool_owner_death's evict-session-keep-entry shape:

- _evict_session drops only the session. The catalog stays; the next
  dispatch connect-or-reuses and re-runs discovery, so drift
  self-corrects and the refresh notification fans out then.
- TTL eviction COOLS entries of users with a live session (a
  registered user-scoped tool listener): transport closed, entry and
  catalog retained, no fan-out. Users without one keep the full drop,
  so departed users' entries don't outlive their sessions.
- The LRU cap now bounds WARM entries — the connection resources it
  exists to limit. Over the cap, live-listener users' entries are
  cooled rather than dropped; cooled catalog-only entries are bounded
  by live users x pool servers and reaped one tick after the user's
  last listener goes away.
- Explicit disconnect keeps its semantics: evict_user_session routes
  to the new _evict_session_drop_catalog (clear + rebuild + notify) —
  the user asked for the tools to leave. Clearing the catalog also
  marks the entry droppable, so it can't linger cooled.

Never-discovered stubs (no catalog) are always dropped, already-cooled
entries are skipped by later ticks, and a cooled entry keeps its
open_lock object for in-flight dispatchers.

Applies to oauth_user and oauth_obo alike: the pool and its eviction
are auth-type-agnostic, and for obo priming is the only path tools
enter a catalog at all.

Fixes #836
2026-07-13 21:13:42 -07:00
Patrick Buckley 3742e9660a docs(changelog): #827 turn-interface unification + sampling-knob assignment scheme with upgrade notes 2026-07-13 08:48:27 -07:00
Patrick Buckley e8a17921bf fix(model-turn): round-3 review — complete the scheme rollout to the main loop, coordinator role, admin save path, and CLI switch
- The main streaming loop now applies the in-code model-definition rung
  (caps.default_reasoning_effort) exactly like model_turn does, so the
  same alias samples identically between chat and every auxiliary lane
  (resolve_lane's stated contract). This also unblocks operator
  temperature on gpt-5.x aliases whose declared default is "none" — the
  main loop previously sent neither knob while aux lanes sent both.
- coordinator.reasoning_effort default "medium" -> "" (the missed unset
  sentinel): coordinators inherit like every other lane; the role rung
  fires only when the operator stored a value.
- admin webux: _onSettingChange no longer hides the save button for a
  blanked nullable number input, so the blank-means-inherit save path is
  actually reachable from the field it decorates.
- /model switch on STORE-LESS sessions (the CLI) keeps the user's
  explicit --temperature//reason knobs when the target alias declares no
  override — the current knobs are the only authority there (mirrors
  the max_tokens fallback). Store-backed sessions still re-resolve.
- ModelLane docstring no longer documents the removed caller-default
  effort rung; CLI status line shows any resolved effort ("medium" is no
  longer a hidden code default); dead `u = usage` alias dropped; three
  test docstrings re-pointed from the deleted
  ChatSession._maybe_synth_reasoning_block to
  model_turn.synth_reasoning_block.
2026-07-13 08:48:27 -07:00
Patrick Buckley 257a8c12ec fix(model-turn): no caller-default effort rung — local vocabularies make any code effort token unsafe
Follow-up ruling on the round-2 batch: default_reasoning_effort is
removed entirely. On local lanes effort_passthrough forwards the value
VERBATIM with the template as the sole authority on validity, and we
explicitly do not define effort vocabularies (or floors) for local
models — so a code-chosen "low" is an unvetted token, and on
manual-thinking boxes it flips enable_thinking on for lanes the
operator never configured, diverging from the main loop's unset. The
effort scheme is now exactly the temperature scheme: explicit relay >
alias > stored config > model definition > omit.

Utility/guard consequences handled the honest way instead:
- title gen: _TITLE_MAX_TOKENS 2048 -> 8192 (the budget must fit a full
  thinking pass at the MODEL'S OWN default now that code never bounds
  it) and the prompt enforces a hard 3-word maximum so the visible
  answer is trivially cheap regardless of what thinking spent.
- output guard: keeps its 512 cap; an unbounded thinking model that
  overruns it parses to a labelled llm_error verdict (heuristic tier
  stands) and the documented remediation is an effort value on the
  guard's model alias.
2026-07-13 08:48:27 -07:00
Patrick Buckley b6391d1f90 fix(model-turn): one sampling-knob assignment scheme — alias > config > model definition > omit
Round-2 review fixes. The round-1 de-pinning collided with
ConfigStore.get's default-on-miss semantics: the registry defaults
(temperature 1.0, effort "medium") were manufactured onto every
store-backed lane's wire, making the documented "unset -> omit"
terminal unreachable. Unset is now representable end to end, and one
scheme governs every lane: per-model alias value > operator-stored
global setting > in-code model definition (effort only: caps
declaration) > field omitted, inference engine's default rules.

- settings_registry: model.temperature default None, model.reasoning_effort
  default "" — the registered defaults ARE the unset sentinels, so the
  admin UI and the wire agree. Admin webux renders nullable floats blank
  ("(inherit model default)") and maps blank-save to reset; the "" effort
  choice reads "(inherit)".
- model_turn: resolve_temperature_setting/resolve_effort_setting are the
  ONE pair of operator-rung resolvers, shared by resolve_lane, both
  session factories, and the /model switch (the 4th-copy mirror is gone;
  the switch no longer leaks the previous model's override on store-less
  sessions). The caps rung moved out of the lane into model_turn's
  effective computation, below a new request-shaped default_reasoning_effort
  parameter (utility + output guard pass "low": budget coherence with
  their small token caps, not sampling policy — any operator or
  model-definition value beats it). The hidden "medium" terminal is gone.
- providers: Protocol + all adapters take reasoning_effort: str | None =
  None (the Protocol-signature "medium" was the same manufactured pin one
  layer down); ModelCapabilities.default_reasoning_effort defaults "" —
  commercial rows all declare theirs explicitly, so only local lanes and
  Anthropic change, both to match their real serving defaults (Anthropic
  manual-thinking models no longer get implicit thinking-on-medium).
  reasoning_template_kwargs distinguishes unset (inject nothing; template
  default rules) from the explicit "none" off-switch. apply_temperature
  skips temperature unless reasoning is EXPLICITLY off on none-declaring
  models (unset leaves the server default in charge, possibly reasoning-on).
- session: ctor takes temperature: float | None / reasoning_effort:
  str | None = None; _save_config/resume round-trip unset as "" (the
  str(None) era guarded); _run_agent relays session temperature AND
  effort on the same-alias fall-through only (a task alias's configured
  knobs stay reachable in both directions).
- optimizer: the five meta lanes are decoupled from --temperature/
  --reasoning-effort (test-model knobs, per their documented meaning);
  registry-less meta lanes omit both fields.
- cli: --temperature/--reasoning-effort default unset and fall through
  the model config instead of pinning 0.5/"medium" for every CLI session.
- cleanup from the review's below-cap findings: dead resolve_server_type
  deleted (tests re-pointed at _server_type_of), stale ChatSession
  comments in _openai_responses fixed, _store_get_or_none extracted,
  eval system-turn conversion hoisted out of the per-turn loop, dead
  _provider_extra_params patch removed, test_perception uses the shared
  mock_completion_result, effort_ladder uses apply_capability_overrides
  instead of a SimpleNamespace fake config.

Wire goldens regenerated: the only drift is the manufactured "medium"
effort vanishing from unset-effort requests (Responses reasoning.effort,
Chat/Google reasoning_effort, Anthropic output_config.effort) — pure
removals, no additions. Ladder tests now fake ConfigStore with the REAL
get() semantics (registry default on miss) so a forgiving fake can't
mask this class of bug again.
2026-07-13 08:48:27 -07:00
Patrick Buckley 09fd17f2da fix(model-turn): reasoning effort rides the ladder too; round-1 review fixes
Patrick's rulings applied from the round-1 high review:

- reasoning_effort loses every code pin, same as temperature: ModelLane
  resolves the ladder (ModelConfig.reasoning_effort → global
  model.reasoning_effort setting → the lane capabilities'
  default_reasoning_effort), model_turn takes str | None, and the pins
  in both judges, all five optimizer lanes, _utility_completion's
  signature default, and model_turn's own "medium" default are gone.
  Explicit relays of user/operator knobs (session effort on the agent
  seam and web-fetch, harness knobs in eval) stay relays.  Effort's
  terminal is the caps default, not wire omission — it gates thinking
  modes, so unset ≠ the explicit "none" value.
- model.temperature setting default 0.5 → 1.0 (safer for modern models;
  several providers no longer accept temperature at all — those drop it
  via capabilities regardless).  No judge-specific knob: a judge alias
  with a per-model override is the remediation path.
- The agent seam keeps the alias ladder (configured → inherited global
  → none), per ruling; the ModelLane docstring no longer documents the
  removed session-relay convention.
- Optimizer lanes get real operator knobs: the existing --temperature /
  --reasoning-effort CLI flags now relay into all five internal LLM
  steps (previously they reached only the eval sessions, leaving the
  deleted pins with no replacement mechanism).

Round-1 cleanups: create_streaming widened to float | None (the
Protocol's two entry points agree; all callers pass explicitly);
model_turn's provider invocation is a direct keyword call again (strict
mypy re-checks it); perception threads the caller's already-resolved
capabilities (one config generation across gate and wire); redundant
extra_params pre-resolution dropped at utility/agent/eval; the synth
source-tag joins the one-fetch-per-call cfg chain; effort_ladder
delegates its capability merge to resolve_capabilities; stale
_maybe_synth_reasoning_block pointers fixed in the providers package.

Wire goldens regenerated: the only drift is the hidden
"temperature": 0.5 pin vanishing from unset-temperature requests.
2026-07-13 08:48:27 -07:00
Patrick Buckley 3eb789dfff fix(model-turn): temperature truly inherits — None never reaches the wire
The second xhigh review caught the fix-round design error one layer
down: omitting the temperature kwarg did not yield the server default —
every adapter's create_completion signature defaulted it to 0.5 and
apply_temperature wrote it to the wire, so the deleted lane pins had
silently become a hidden universal 0.5 pin.

The house rule is now implemented end to end:

- Protocol + adapters take temperature: float | None = None, and None
  is OMITTED from the wire (apply_temperature None-gate; Anthropic's
  builder keeps its API-required thinking=1.0 forcing but never writes
  an unresolved value; Responses/xAI builders widened).
- resolve_lane climbs the documented ladder: ModelConfig.temperature →
  ConfigStore global model.temperature (new config_store param,
  threaded from ChatSession into both judges and perception) → None.
- perception.describe/describe_cached take alias/registry/config_store
  so operator settings on the perception alias actually reach the wire
  (previously structurally unreachable — no remediation path for a
  degraded memoized description).
- The agent seam stops relaying the SESSION model's temperature: the
  task/agent alias's own ladder governs, per the inherit-from-the-model
  contract.

Generation-coherence and audit fixes from the same review:

- ChatSession._resolve_capabilities fetches its config UNCAUGHT again —
  a registry failure on the session's own alias raises loudly instead
  of silently caching degraded static-table caps for the session
  lifetime (the never-crash fetch is a judge-constructor property).
- Judge constructors pass cfg=model_cfg (zero independent get_config
  fetches; pinned by test); the per-evaluation lane's constructor-
  frozen capabilities are documented as deliberate (window-coupled,
  refreshed on judge swap).
- OutputGuardJudge splits _lane_alias from _judge_model_alias so the
  audit label keeps its pre-#827 fallback semantics ("" → raw model id)
  while lane resolution inherits the session alias.
- model_turn fetches the alias config ONCE per call and threads it into
  both live flags (cfg sentinel standardized across the resolvers:
  ... = fetch for me, None = fetched-and-missed — also removes
  resolve_lane's latent double-fetch on a miss).
- cap_tool_calls shared by the eval and optimizer loops; hand-built
  ModelLane sites converted to resolve_lane; hand-rolled test result
  namespaces consolidated onto mock_completion_result; stale synth-test
  module docstring re-pointed.
2026-07-13 08:48:27 -07:00
Patrick Buckley 7e07f2ea93 feat(core): phase 2 — every single-shot lane speaks Turn IR (#827)
create_completion now has exactly one caller: model_turn. The π-side
lanes migrate off hand-built OpenAI dicts:

- _utility_completion (title gen, compaction, web-fetch extraction)
  takes list[Turn] and runs the session's primary lane through
  model_turn; its three call sites build Turn.system/Turn.user.
- perception.describe builds a by-reference trajectory (AttachmentRef +
  the prebuilt parts via resolve_attachments, reintroduced on
  model_turn with its first caller and pinned by tests) — Turn IR never
  carries inline media bytes, matching the main loop's wire path. Its
  temperature=0.2 pin is gone (house rule).
- eval HeadlessSession's loop lowers system prompts through the
  turns_from_dicts bridge and appends result.turn; the parallel-call
  cap now also drops the native lane on a capped turn (a capped mirror
  with a full native lane would replay orphan tool blocks).
- optimizer: all five sites (diversifier, observer, analyst loop,
  tool optimizer, prompt optimizer) build Turn IR through per-function
  lanes; every temperature pin (0.8/0.3/0.3/0.3/0.6) removed per house
  rule — sampling behavior belongs in the model's configuration.

Test mocks move to the shared full-shape helper where the model_turn
re-ingest now runs; perception/attachment tests assert the
by-reference placeholder + resolver contract instead of inline parts.
2026-07-13 08:48:27 -07:00
Patrick Buckley b0937683ae fix(model-turn): apply the #827 phase-1 review round
Behavior fixes, per review + house rules:

- Judges no longer pin temperature=0.0 — the lane inherits the model's
  configured temperature (ModelConfig.temperature via resolve_lane), and
  model_turn omits the kwarg entirely when nothing resolves. House rule:
  code never pins a temperature; modern models often misbehave below
  1.0, so the model's configuration is the source of truth. This also
  dissolves the extra_body-overrides-judge-pins collision: operator pins
  reaching the judge lane is the doctrine working.
- Session-fallback judges inherit the session's registry alias
  (session_model_alias threaded from ChatSession), so the registry-
  resolved extra_params / replay flag / vLLM attach apply on the default
  judge.model-unset configuration instead of only on explicit aliases.
- Blank-id native lanes are repaired, not dropped: model_turn backfills
  the manufactured mirror ids into blank-id native client tool blocks
  pairwise (the #825 1:1 ordering invariant), so thought_signature
  survives Google's blank-id compat responses and thinking blocks keep
  their continuity on blank-id locals. Only blank ids are ever written —
  a provider-assigned id (possibly signature-covered) is never touched —
  and any pairing mismatch falls back to the #825-converged total drop.
- model_turn(mint=...) without wire_id_map now raises: minted ids are
  unrestorable without the recovery map, and the two parameters were
  independently optional by accident.
- Lane resolution reads ONE defensively-fetched ModelConfig
  (_get_config_or_none): a registry hot-reload mid-resolution can't mix
  config generations, and an alias that raced away degrades each facet
  to its miss behavior instead of aborting a judge constructor into the
  silent session-model downgrade.

Extraction hygiene, per review:

- Dead session wrappers deleted (_resolve_server_type,
  _maybe_synth_reasoning_block, _get_server_compat) and their tests
  re-pointed at the module functions; the stranded reasoning-types
  comment and two stale doc pointers cleaned up.
- Speculative extra_headers / resolve_attachments pass-throughs dropped
  from model_turn until a caller lands (phase 2/4 reintroduces them
  with their lane).
- _server_type_of(cfg) is the one reader of server_compat.server_type;
  the vLLM-attach gate and resolve_server_type both use it, retiring
  the change-both-readers discipline comment.
- dataclasses import hoisted; module docstring restated as the durable
  contract (grep callers for coverage) instead of a rotting snapshot.
- mock_completion_result shared in tests/_session_helpers.py — one
  definition of "every field the re-ingest reads".
2026-07-13 08:48:27 -07:00
Patrick Buckley 54dd4ed50a feat(judge): both judges speak Turn IR through model_turn (#827)
The intent judge's evidence loop and the output-guard's single shot now
build list[Turn] and call model_turn — the hand-built OpenAI-dict
message construction is gone, and with it the judges' private
interlingua. The assistant turns they append carry the provider-native
lane, so the loop keeps reasoning continuity across its own turns.

That is what unblocks Gemini: thought_signature rides provider_blocks
and is reconstructed by the Google adapter's fidelity swap, so the
provider_name == "google" tool-skip is deleted — the Gemini judge runs
the same evidence-tool loop as every other provider instead of
degrading to a single-shot, tool-blind verdict.

judge.py's _resolve_model_capabilities mirror (#826) is deleted; both
judges resolve capabilities through the shared lane resolver, and each
evaluation builds a ModelLane (fresh client, constructor caps,
registry-resolved extra_params + live flags). The shared resolver
inherits the mirror's defensive non-dict capabilities check — without
it a malformed registry row would silently downgrade a judge to the
session model instead of just skipping the overrides.

Judge calls now resolve extra_params and replay_reasoning_to_model
from the registry like every other lane (previously: never sent, and
the protocol's back-compat default respectively).

Test mocks grow the CompletionResult fields the model_turn re-ingest
reads (provider_blocks, reasoning); alias-registry mocks wire
get_config, which the unified resolver uses.
2026-07-13 08:48:27 -07:00
Patrick Buckley ab35eb4215 refactor(core): extract model_turn, the shared plant-call primitive (#827)
Lower-and-sample is now one surface: core/model_turn.py owns the
Turn-IR lowering seam (dicts_from_turns -> sanitize_tool_call_arguments
-> restore_provider_tool_ids -> Phase 5 vLLM attach), the provider call,
and the re-ingest to an assistant Turn carrying the native lane.
ModelLane binds a resolved lane (provider, client, model, capabilities,
extra_params) and carries the registry so live operator toggles
(replay-reasoning, vLLM attach) keep re-resolving per call.

The task-agent seam is the first client: _run_agent builds a ModelLane
and calls model_turn with a mint closure; the inline mint/back-fill/
finalize block collapses to appending result.turn. Session capability/
extra-params/replay/finalize helpers become delegates to the module
functions, so lane resolution has exactly one logic path.

model_turn is policy-free by contract: retry, deadlines, tool
execution, and usage recording stay with each caller.

Two agent-path tests move their replay-flag pin to the module seam
(one had gone vacuous against the session wrapper); _record_aux_usage
now takes UsageInfo rather than a CompletionResult.
2026-07-13 08:48:27 -07:00
renovate[bot] 9b01d8e569 chore(deps): update dependency typescript to v7 2026-07-13 04:57:36 -07:00
renovate[bot] 4878f16475 chore(deps): update github actions 2026-07-13 04:57:21 -07:00
Patrick Buckley b2b8b6f65e fix(mcp): schedule node reload after admin write instead of blocking on it
The auto-notify added in the prior commit awaited _notify_nodes_mcp_reload
inline in create/update/delete, coupling each admin write's latency — and
success — to cluster reachability: on a large cluster with slow/unreachable
nodes the write could hang up to ceil(nodes/fan_out_limit)*30s behind the
fan-out, and a post-commit fan-out error would 500 a write that already landed.

Schedule the fan-out as a BackgroundTask that runs AFTER the 200 instead — the
"trigger, not drain" contract already used by _cascade_cancel_to_children — so
the write's response is never blocked on, nor failed by, the fan-out. The
pre-existing registry-install path is converted the same way for consistency.

There is no periodic node->DB reconcile, so a node that misses the reload serves
a stale MCP catalog until the next POST /reload. The background _run therefore
logs any unreached node (or a systemic fan-out fault) at WARNING — visible at
the default INFO level — rather than swallowing it; the per-node status view
also surfaces the divergence. A non-2xx reply from a node's reload/action
endpoint now counts as a failure (raise_for_status) rather than a reached node,
so neither the WARNING nor the operator /reload results miss a 5xx node.

Revert the getattr None-guard on _notify_nodes_mcp_reload: it turned the
operator-triggered POST /reload into a silent success ({} with 200) when the
fan-out infra was absent — a fail-loudly violation — and diverged from the
unguarded sibling _notify_nodes_mcp_action. The helper is drain-style again,
awaited only by /reload (which must surface fan-out failures); writes go through
the best-effort scheduler.

Tests: assert the reload is NOT scheduled on a delete/update 404 or a create
secret-store 503; that an unreached-node, raising, or non-2xx fan-out is logged
at WARNING / recorded as an error; and that operator POST /reload fails loudly
(500) without fan-out infra.
2026-07-12 19:03:35 -07:00
Patrick Buckley d6ccc5ed17 fix(console): show 'per-user' for idle pool MCP servers, not 'connecting'
oauth_user/oauth_obo servers hold no cluster-level session — they connect per-user on demand — so the admin status pill rendered 'connecting'/'idle', which reads as broken, when zero warm users is the normal resting state. Render 'per-user' for pool-backed servers instead.
2026-07-12 19:03:35 -07:00
Patrick Buckley b3cd91f1a0 fix(mcp): auto-notify nodes on admin create/update/delete
admin_create/update/delete_mcp_server wrote to the DB but never told nodes to reconcile — only the registry-install path and the explicit /reload did — so a programmatic create/edit/delete was inert on nodes until a manual reload (and the mid-session re-prime self-heal never fired). Call _notify_nodes_mcp_reload after each write, mirroring registry-install; also make that helper best-effort (skip when the cluster fan-out infra is absent) so a write can't 500 on it.
2026-07-12 19:03:35 -07:00
Patrick Buckley 9391509e85 fix(oidc): trust Entra's graph.microsoft.com userinfo out of the box
Microsoft Entra's discovery document advertises userinfo_endpoint on graph.microsoft.com — a host distinct from the login.microsoftonline.com issuer — so discover_oidc's cross-host guard rejected it and disabled OIDC unless the operator set trusted_endpoint_hosts. Add login.microsoftonline.com to the built-in KNOWN_TRUSTED_OAUTH_ENDPOINT_HOSTS allow-list (mirroring the Google entry) so Azure AD OIDC works with no extra configuration. Surfaced by the live obo integration test.
2026-07-12 19:03:35 -07:00
Patrick Buckley 49f2266e20 fix(mcp): address review of the re-prime self-heal
- detect an in-place oauth_user<->oauth_obo flip by diffing the pool servers' (name -> auth_type) view instead of names only, so a migrated server re-primes active sessions (a name-only diff saw the same name on both sides and missed it);
- guard prime_user_pools per-user so one scheduling failure can't propagate out of reconcile_sync (500 the reload) or skip the remaining users;
- log what was SCHEDULED (prime is fire-and-forget and no-ops for credential-less users / a down loop), not 're-primed', and take an int changed-count instead of a set whose name falsely implied per-server scoping.
2026-07-12 19:03:35 -07:00
Patrick Buckley d1de602b78 docs(mcp): align token-encryption + mint docstrings with oauth_obo
Startup key-enforcement counts ALL user-scoped auth types (oauth_user and oauth_obo, per is_user_scoped_auth), and the entra mint leg always carries scope=<audience>/.default (per-server oauth_scopes is ignored on that leg). The docstrings named only oauth_user / left the scope behavior ambiguous. Comment-only; no behavior change.
2026-07-12 19:03:35 -07:00
Patrick Buckley 86253a3b07 fix(mcp): re-prime active sessions when a pool server appears mid-reconcile
prime_user_pools runs once at ChatSession start, so an oauth_user/oauth_obo server registered while a session is already open never reached it — and for oauth_obo (no consent flow) priming is the ONLY path tools take into the catalog, so a mid-session registration stayed invisible until the session restarted. reconcile_sync now diffs the pool-server name set and re-primes every active session's user when a new server appears; idempotent (skips already-warm pools) and a no-op for users without a captured credential.
2026-07-12 19:03:35 -07:00
Patrick Buckley 530aaa6632 refactor(mcp): drop dead grant-profile recompute after runtime rediscovery
Round-12 review follow-up (no correctness findings). obo_grant_profile is
a static config field that OIDC runtime rediscovery never changes, so
recomputing profile/mint after maybe_rediscover_oidc was dead work that
implied the grant profile could change across a heal (it cannot). Re-read
only the discovery-derived state (enabled / token_endpoint).

The remaining review findings are accepted by design: the credential-
rotation CAS's sub-millisecond read->write window (self-heals on next
login; a full fix needs SELECT FOR UPDATE or a version column) and the
per-server delete loop on identity deletion (the per-server try/except
buys partial-failure resilience a single bulk delete would not).
2026-07-12 19:03:35 -07:00
Patrick Buckley 8a1efaf55e perf(mcp): skip redundant priming credential read; dedup sweep clear bookkeeping
Round-11 review follow-up — no correctness findings; efficiency/DRY cleanups.

- Session-start priming already confirms the captured credential exists
  once for all of a user's obo servers, but each per-server
  get_obo_access_token_classified re-read it pre-lock (N+1 reads). The
  priming path now passes credential_present=True so the per-server
  existence read is skipped; other callers keep their own read.

- _clear_pending_consent_best_effort (the sweep clear path) now routes
  through _mark_pending_consent_cleared instead of inlining the
  prune-then-stamp step, matching the helper's documented contract so the
  two DB-confirmed clear sites can't drift.

The per-dispatch pending-consent clear's DELETE volume and the removed
interactive.js no-consent-URL fallback are left as-is: the former is the
deliberate, TTL-bounded cost of cross-node badge self-heal, and the
latter is unreachable for oauth_user (which always carries a consent_url)
and intended for oauth_obo (which has no per-server consent flow).
2026-07-12 19:03:35 -07:00
Patrick Buckley 08d765a74a fix(mcp): record effective obo scope so entra .default isn't cached as narrow
Round-10 review follow-up.

- A server scoped under obo_grant_profile=rfc8693 that survives a switch
  to the entra profile mints <audience>/.default (the entra leg cannot
  honor per-server oauth_scopes), but the cache row recorded the
  configured narrow scope — so _is_fresh_obo_cache_row kept serving the
  broad .default bearer believing it was narrow, and a scope change that
  can't apply under entra looked like it had. The freshness gate and the
  cache row now record the EFFECTIVE scope the leg actually mints ('' for
  entra, the configured scope for rfc8693); the raw scope is still passed
  to the mint so the entra leg's "oauth_scopes ignored" warning still
  surfaces the misconfigured leftover.

Cleanup: the R9-5 single-per-mint client made every token-POST caller pass
a non-None client, so the transient-client fallback in _hardened_token_post
was dead and two doc/comment blocks described the opposite of the real
behavior. Removed the dead branch, tightened the http_client typing across
the mint chain, and corrected the docs.
2026-07-12 19:03:35 -07:00
Patrick Buckley 903cf5f72d fix(oidc/mcp): login-path self-heal, guard mint persist, CAS credential rotation
Round-9 review follow-up.

- Runtime OIDC rediscovery was triggered only from the obo mint path,
  which needs an already-signed-in user — so a single-node install (or
  one where every node booted during a transient IdP outage) kept OIDC
  LOGIN dark until an operator restart. The authorize and callback
  handlers now trigger maybe_rediscover_oidc before their enabled gate,
  so login self-heals too.

- A transient storage error on the obo mint-cache write (delete+create)
  raised out of get_obo_access_token_classified, discarding a valid
  just-minted token and breaking the classified-result contract. The
  cache write is now best-effort — the working bearer is returned and the
  next dispatch re-mints. Likewise the runtime rediscovery's discover_oidc
  call is wrapped in except Exception (like the boot path) so an
  unexpected discovery error can't escape the mint's contract.

- Login-time credential capture could race an in-flight mint on a
  strict-rotation IdP: the mint's rotation write-back would clobber the
  fresh login refresh token with a stale rotated one. The rotation
  write-back is now a value compare-and-swap against the token the mint
  read, so a credential a concurrent login just refreshed is not
  overwritten.

Cleanup: the rfc8693 mint now opens one transient httpx client for the
whole mint so the token-exchange leg reuses the refresh leg's connection
instead of a second TLS handshake.
2026-07-12 19:03:35 -07:00
Patrick Buckley ec079f0df3 fix(oidc/console): unblock obo edits when OIDC off; latch config-invalid rediscovery
Round-8 review follow-up — two correctness follow-ons from the round-7
rediscovery/console-gate fixes, plus two cleanups.

- The console obo write gate ran the OIDC-deployment checks on EVERY
  update, so once OIDC was operator-disabled any edit of an existing
  oauth_obo server — including the natural remedy of setting
  enabled=false — was rejected 400, leaving DELETE as the only way out.
  The deployment-level checks (encryption key, OIDC enabled/configured,
  capture opt-in, valid grant profile) now run only when a write is a NEW
  obo enablement (create or flip INTO obo); a same-type edit keeps only
  the per-server validity checks (audience required, entra-scope reject),
  so an operator can always disable or edit an existing obo server.

- Probing rediscovery with enabled forced True carried the retryable boot
  flag into discover_oidc, whose config-error branches returned enabled=
  False without clearing it, so a config-invalid IdP (an endpoint failing
  SSRF/same-origin validation) re-probed every 60s forever. The config-
  error branches now latch discovery_retryable=False (terminal), and
  maybe_rediscover installs that terminal config so the node stops
  probing; the transient fetch/degraded branches keep retrying.

Cleanups: fold the obo missing-expires_in fallback into
_expires_at_from_response via a default_ttl_seconds param (one owner of
the stored-expiry format), and drop the redundant audience-change
inequality already guaranteed by the no-op normalization (matching the
sibling scopes_changing).
2026-07-12 19:03:35 -07:00
Patrick Buckley af56170be6 fix(oidc/mcp): make runtime OIDC rediscovery actually work; preserve oauth_user paths
Round-7 review follow-up.

- The runtime OIDC re-discovery feature was dead code: discover_oidc
  PRESERVES the input config's `enabled` flag on success (only
  load_oidc_config ever sets it True), and maybe_rediscover_oidc always
  probed from the disabled boot config, so a successful rediscovery still
  returned enabled=False and the config swap was unreachable — the whole
  boot-outage auto-heal never worked. It now probes with enabled forced on
  so the flag is a reliable success signal. The unit test that "covered"
  this was mocking discover_oidc to return enabled=True, masking the bug;
  it now drives the real discover_oidc through a mocked HTTP discovery GET.

- The console never runs runtime rediscovery, so a transient discovery
  failure at console boot made every oauth_obo server un-editable and
  un-disable-able. The write gate now accepts a discovery_retryable config
  (OIDC configured, discovery transiently down) and rejects only a
  genuinely absent OIDC.

- The first rediscovery probe was suppressed for ~60s after host boot
  because the "last probe" timestamp defaulted to 0.0; it now uses a None
  sentinel for "never probed".

- Two behavior-preservation fixes for the pre-existing oauth_user path:
  the shared hardened token-POST no longer escalates oauth_user oversized
  error bodies (that status-based classification is opt-in for the obo
  legs only), and the token_revoked audit fires unconditionally for
  oauth_user again (a refresh failure means a real grant died) while
  staying delete-gated for obo to avoid revocation rows for tokens that
  never existed.

Cleanups: drop a throwaway set allocation in the pool-emptiness check,
compute the create handler's cleaned OAuth text once, remove a dead
no-op pop with a false comment, and simplify the cleared-map prune to two
non-overlapping passes.
2026-07-12 19:03:35 -07:00
Patrick Buckley 50d0ac9833 fix(mcp): classify oversized token error by status; dedup transition/obo-scan
Round-6 review follow-up — no CONFIRMED correctness bugs; one plausible
edge case and four DRY/drift cleanups.

- The shared hardened token-POST raised its 64KB body-size guard with the
  default TRANSIENT class before the non-200 was classified, so a permanent
  dead-grant whose error body exceeded the cap looped "please retry"
  forever and never escalated. An over-sized client-error response is now
  classified AMBIGUOUS by status (without reading the over-sized body), so
  it still escalates to the honest re-login/admin remedy after the streak.

- The admin update handler re-derived the is_flip predicate inline in the
  three token-purge guards (and computed target_auth / auth_type_now as two
  names for the same effective auth type). Both now reuse the single
  is_flip / target_auth derivations, so the purge guards and the column
  scrub can't desync on what counts as a flip.

- The oauth_obo server-name scan was hand-rolled in two places (the
  connections-list filter and the identity-delete cache purge) with
  divergent null handling. Extracted obo_server_names(storage) so a change
  to how sign-in-passthrough is recognised can't leave one path silently
  missing servers.

- Inlined the two single-use _*_detail wrappers into direct
  _pool_error_detail calls, keeping named wrappers only for the
  multi-caller situations.
2026-07-12 19:03:35 -07:00
Patrick Buckley 09aa50b7a1 fix(mcp): close obo auth-column leak, capture gate, and cooldown classification
Round-5 review follow-up — three CONFIRMED (one security) plus two
correctness issues, all traceable to earlier fixes in this branch.

SECURITY: the round-2 redesign gated the "scrub OAuth columns this
auth_type doesn't use" on is_flip, replacing the old unconditional
scrub. A same-type static/none/obo edit could then inject an
oauth_authorization_server_url that survived a later flip to oauth_user
(which uses that column) and redirected every consenting user's OAuth
traffic to an attacker AS. The scrub is now applied on EVERY write, and a
flip into oauth_user recomputes the oauth_user-only columns from the
request so a stale value can't carry in — the persisted OAuth columns
are once again a pure function of the target auth_type.

- The oauth_obo write gate now also requires capture_user_credential to
  be enabled: without it, login persists no credential and every dispatch
  returns "missing" with a remedy that can never succeed — the permanent
  misconfig the gate exists to reject.

- A permanent obo mint failure arms the cooldown (its shared credential
  survives the per-server revoke), but the in-cooldown short-circuit
  reported it as a retryable transient for the whole window, flapping
  against the honest re-login/admin affordance. The backoff state now
  records whether the arming failure was permanent, and the short-circuit
  surfaces the matching classification.

- The ambiguous-escalation revoke cleared the cooldown without re-arming;
  for obo (surviving credential) that let the next dispatch immediately
  re-mint against the still-failing IdP. It now re-arms the same terminal
  backstop the permanent branch has.

- The force-refresh reuse gate keyed on the cache row's 1-second `created`
  time, which couldn't tell a concurrent peer's fresh mint from the
  caller's own just-rejected token minted in the same second — so a retry
  could re-serve the rejected bearer. It now decides by token identity
  (the under-lock row differs from the pre-lock one), preserving the
  single-flight reuse while never re-serving a rejected token.

Also: guard _pool_error_detail's str.format so placeholder-free copy
can't raise inside the error renderer, and note why the connections-list
classifies obo rows by authoritative auth_type on that cold path.
2026-07-12 19:03:35 -07:00
Patrick Buckley c53bd464d0 refactor(mcp): dedup obo credential decrypt, cooldown arming, pool set, error copy
Round-4 review follow-up — no correctness findings; these are the four
cleanups it surfaced.

- The obo mint path decrypted the captured IdP refresh token twice per
  mint: once pre-lock only to test presence, then again under the lock.
  The pre-lock presence check now uses the raw existence read (no
  decrypt), mirroring the priming path; the single authoritative decrypt
  happens under the lock. Removes N throwaway decrypts per user at
  session-start priming across N obo servers.

- The "arm the per-(user,server) cooldown" idiom was written inline at
  four failure sites. Extracted _arm_cooldown (returns the backoff state
  so the streak-mutating callers reuse it), so a change to how backoff
  works is one edit.

- The oauth_user|obo pool-membership union was rebuilt inline at three
  iteration sites. Added a _pool_server_names property, the set-level
  counterpart to _is_pool_server, so a future third pool-backed auth type
  is registered in one place.

- The four per-situation remediation-copy helpers each repeated the
  oauth_user-vs-obo branch. Consolidated the copy into one
  (auth_model, situation) table behind _pool_error_detail — the single
  place the auth-model decision is made — so a dispatch site can't pair a
  situation with the wrong auth model's copy (the wrong-remediation bug
  class this review caught repeatedly). The named helpers remain as thin,
  tested wrappers.
2026-07-12 19:03:35 -07:00
Patrick Buckley 6d80051925 fix(mcp): decouple capture key guard from OIDC discovery; bound obo token TTL
Round-3 review follow-up.

- The startup guard that refuses to boot without a token-encryption key
  when capture_user_credential is enabled was gated on oidc_config.enabled.
  Enabled reflects whether OIDC *discovery* succeeded, which is transient:
  a node that boots while the IdP is unreachable comes up enabled=False,
  so the guard was silently skipped exactly when it was needed, and runtime
  rediscovery would later re-enable OIDC with the first login persisting a
  refresh token and no key. Gate on the operator's capture opt-in alone
  (a static config value), independent of discovery state.

- An obo mint response omitting the RFC 8693-optional expires_in cached
  expires_at=NULL, which the freshness gate reads as never-expiring — fine
  for opaque oauth_user tokens, wrong for a short-lived minted token, which
  would then be served indefinitely and defeat audience/scope narrowing
  that relies on TTL turnover. Fall back to a bounded default expiry.

- The empty-token fallback in the shared pool-lookup error mapping now uses
  the auth-model-aware consent detail like its sibling missing branch, so an
  obo row never shows per-server-consent copy with a null consent URL.

- Documented the _build_consent_url invariant at the chat error-card render
  gate: oauth_user rows always carry a consent URL, so gating the Connect
  button on its presence never hides a needed button for them; the button's
  absence for sign-in passthrough is intended (the detail text is the
  affordance).
2026-07-12 19:03:35 -07:00
Patrick Buckley d2e69ca527 fix(mcp): coherent obo auth-type carry-over + honest error affordances
Round-2 review follow-up. The headline is a redesign of the OAuth
column carry-over so scopes/audience can no longer leak or vanish across
an auth-type flip:

- oauth_audience and oauth_scopes keep their meaning only WITHIN an auth
  type (a resource indicator vs. an IdP app id; AS-consent scopes vs. an
  rfc8693 exchange scope). On any oauth_user<->oauth_obo flip they are
  now recomputed from the request (present -> value, absent -> NULL) and
  never carried from the old row. A shared _oauth_columns_to_clear policy
  drives both the create and update handlers. No-op normalization of a
  re-sent equal value applies only to same-type edits.
- The console form clears both semantic fields when the auth type
  changes and always submits the visible values; the previous
  "omit unchanged scopes" logic collided with the backend's flip
  handling and could silently drop or carry scopes.

Write-time validation now rejects oauth_obo rows that can never mint —
OIDC disabled/unconfigured, or an invalid obo_grant_profile — instead of
letting them surface per-dispatch as a retryable transient that never
heals.

Honest failure affordances for sign-in passthrough (no per-server
consent flow exists):

- the token_revoked audit fires only when a row was actually deleted, so
  a permanent mint rejection against a surviving credential no longer
  appends a bogus revocation on every post-cooldown dispatch/prime;
- the 403 insufficient-scope detail and the chat error card's action
  button are now auth-model-aware — obo errors point at the
  administrator rather than a dead-end re-consent, and the Connect button
  renders only when a real consent URL is present;
- the read-side freshness gate now enforces scopes as well as audience,
  so an rfc8693 scope narrowing takes effect on the next dispatch even if
  the best-effort admin cache purge failed.

Cleanups: the five decrypt-failure result constructions collapse into
_decrypt_failure_result; the cleared-pairs TTL bookkeeping into
_mark_pending_consent_cleared; drop the dead USER_SCOPED_AUTH_TYPES
re-export from mcp_oauth; correct the now-bidirectional oidc<->mcp_oauth
lazy-import note. Docs updated for the flip semantics and the OIDC
prerequisite.
2026-07-12 19:03:35 -07:00
Patrick Buckley 32c76499fa fix(mcp): harden obo mint path and admin lifecycle after review
Mint engine: guard the credential-rotation persist so a storage blip
cannot escape the classified-result contract mid-mint (and cannot brick
the user's other obo servers on strict-rotation IdPs); stop borrowing
the login flow's httpx client across event loops — mints use a transient
per-request client (obo_http_client remains as a test seam); retry OIDC
discovery at runtime (cooldown-gated, single-flight) so a node that
booted during an IdP outage can mint again without a restart; key the
under-lock force-refresh reuse gate on created, which delete+create
makes the mint time (obo rows never set last_refreshed, so the copied
oauth_user gate never fired and serialized waiters each re-redeemed).

Cross-node consent badges: the cleared-pairs set becomes a TTL map with
bounded growth, so a badge written by another node after this node's
last clear self-heals within one TTL window instead of surviving until
a restart.

Admin lifecycle: purge the mint cache when oauth_scopes changes on an
obo row (an rfc8693 privilege reduction now applies immediately, like
audience changes); normalize no-op scope/audience re-sends out of
updates — the admin form re-submits pre-filled fields on every save,
which both re-triggered purges and made entra-profile rows with legacy
scopes un-editable; make flip-into-obo scope handling grant-profile
aware (entra clears the carry-over, rfc8693 honors the request); clear
obo-era audience/scopes when flipping back to oauth_user (the IdP-side
app identifier is not a resource indicator); mirror the same column
policy in the create handler.

Revocation honesty: hide obo mint-cache rows from the user connections
list and refuse the per-server disconnect with 409 — deleting the row
returned 204, audited token_revoked, and then session-start priming
silently re-minted from the surviving captured credential.

Console form: keep the audience-from-URL autofill off for sign-in
passthrough (the audience there is an IdP application identifier, and
the prefilled URL passed every validation layer then failed every
mint); clear the autofill artifact when switching modes; omit unchanged
scopes from submissions.

Dispatchers: route tool/resource/prompt through one shared lookup-error
mapping and an auth-model-aware 401-exhausted detail (obo users are no
longer pointed at a consent flow that does not exist). The consent-url
audit count drops 13 → 7: the three per-dispatcher mapping copies
collapsed into _pool_lookup_error.

Priming: skip all obo servers for users with no captured credential via
one existence SELECT (previously three reads per server per session).

Also: USER_SCOPED_AUTH_TYPES now lives in storage._protocol so the
backend SQL predicates share the application layer's set; docs describe
the actual purge-on-transition behavior (the orphan-and-reactivate
claims were wrong); the entra e2e setup script no longer aborts
silently under set -e with suppressed stderr.
2026-07-12 19:03:35 -07:00
Patrick Buckley 44e9d46e40 fix(mcp): address pre-push review — obo scope/audience/priming defects
Frontend↔backend interaction bugs the backend-only rounds couldn't see:
- flip oauth_user->oauth_obo: the admin form re-submits the pre-filled
  oauth_user scopes, so the flip-clear (gated on 'oauth_scopes' not in
  body) was skipped -> rfc8693 mints broke permanently. Clear now
  compares to the existing value, robust to the re-send.
- entra edit-lockout: update validated the MERGED scopes, so a
  pre-existing scoped obo row under the entra profile became un-editable
  (every PUT 400'd). Reject only when the request actually SETS scopes.
- flush-cache button never rendered: consented_users_count is now
  populated for oauth_obo rows too, not just oauth_user.

Mint engine + priming:
- audience guard: a cached token minted for a since-narrowed audience is
  no longer served (extracted _is_fresh_obo_cache_row, used pre/post-lock,
  checks refresh-less + audience-match + fresh). _persist_obo_cache_row
  now delete+creates so the row's audience column tracks the mint (a
  plain update kept the stale audience -> re-mint loop).
- obo session priming passes revoke_ambiguous_escalation=False (new param
  threaded through get_obo_...), so an IdP wobble during a bulk prime
  can't escalate-revoke obo cache rows cluster-wide.

Cross-node + lifecycle:
- pending-consent success-clear now clears once-per-failure-cycle via a
  _pending_consent_cleared set (was gated on 'we wrote it' -> never fired
  cross-node/after-restart -> stale badge). Still no per-call SQL.
- identity-unlink cache purge: per-server try/except so one failure
  doesn't leave other servers' bearers un-purged.
- entra ignored-scopes: warn once per audience (was per-mint flood ->
  downgraded to debug -> no signal on a profile switch).
- entra_setup.sh writes single-quoted .env values (secret may contain $).

+6 regression tests. 1892 mcp/oidc/console tests green; mypy clean.

Refs #551.
2026-07-12 19:03:35 -07:00
Patrick Buckley 3e88c54751 test(mcp): check in oauth_obo e2e harnesses under scripts/obo-e2e
Manual (non-CI) harnesses that exercise the real oauth_obo mint path
against a live IdP, kept for future validation of the feature:

- entra_e2e.py: real Entra tenant, one interactive sign-in, drives
  get_obo_access_token_classified -> _obo_mint_entra (E1-E7)
- keycloak_e2e.py + .sh: ephemeral Keycloak, fully headless, drives the
  rfc8693 leg (refresh grant -> token exchange)
- entra_spike.py: raw-OAuth wire probe (pre-implementation reference)
- entra_setup.sh: creates the Entra spike app registrations
- .env.example template; real creds stay in a gitignored .env

Both legs pass E1-E7 (mint + aud, cache hit, single-credential->multi-
audience, rotation write-back, force_refresh, unconsented->credential
survives, flush->re-mint). Not wired into CI.

Refs #551.
2026-07-12 19:03:35 -07:00
Patrick Buckley 891c8b1785 docs(mcp): operator guide for oauth_obo single-credential sign-in passthrough (slice 5)
Adds the oauth_obo section to docs/mcp-oauth.md:
- when to use it vs oauth_user (mode table row)
- deployment config ([oidc] capture_user_credential + obo_grant_profile,
  encryption-key requirement)
- per-IdP setup: Entra (delegated permissions + admin consent, plus the
  verified admin-consent-propagation AADSTS65001 gotcha) and Keycloak
  RFC 8693 (standard token exchange + audience client scopes)
- revocation & custody model: identity-unlink cuts a user off (credential
  + cache purge); flush-cache is an honest re-mint, not a revoke; per-server
  revocation is IdP-governed
- auth-type-transition + troubleshooting table rows for obo
- interim #682 note (Entra pre-authorized-clients removes the second
  consent for plain oauth_user, tenant-config only)

Refs #551.
2026-07-12 19:03:35 -07:00
Patrick Buckley 202c39e634 feat(console): oauth_obo option in the admin MCP server form (slice 4 frontend)
Operators can now select sign-in passthrough (oauth_obo) in the console,
not just via the API:

- new 'Sign-in passthrough' auth-type radio with plain-language copy
  ('uses your org login - no separate connect')
- the shared OAuth fields block hides the oauth_user-only inputs
  (AS URL / registration / client id / secret) for obo and shows just
  the audience (marked required) plus scopes (hinted rfc8693-only), with
  an explanatory note
- client-side audience-required validation (inline error, not a 400)
- edit-populate + reset handle the new radio
- server list: obo servers get an honest 'flush cache (N)' action
  (drops minted tokens -> re-mint) instead of connect/bulk-revoke, with
  a confirm dialog that states it does NOT cut off access (that is
  IdP-governed / identity-unlink)

Refs #551.
2026-07-12 19:03:35 -07:00
Patrick Buckley e5f8453e1a fix(mcp): complete oauth_obo revocation lifecycle + fix hot-path regression (follow-up review)
Addresses the high follow-up review of the first fix round:

Revocation lifecycle (the review's dominant theme):
- identity-unlink now purges the user's minted obo cache rows in addition
  to revoking the credential, and the response/audit report the actual
  effect (credential + N cache rows) instead of a blanket revoked=true;
  warmed-session residual (bounded by token TTL) documented
- bulk-revoke on obo is now an honest cache-FLUSH: distinct audit event
  (obo_cache_flushed) + response effect=cache_flush_remints, since the
  shared credential survives and the next dispatch re-mints (oauth_user
  keeps its durable revoke semantics)
- changing oauth_audience on a pool-backed row now purges cached tokens
  (audience is the token binding), like URL/name/auth_type changes
- flipping oauth_user->oauth_obo now clears the stale AS-consent scopes
  (else rfc8693 sends them -> invalid_scope loop); write path rejects
  oauth_scopes under the entra profile (it mints <audience>/.default)
- a cache row bearing a refresh token is never served as an obo token
  (guards the cross-node purge-vs-refresh race)

Self-inflicted regression:
- _clear_pending_consent_sync is now gated on an in-memory
  _pending_consent_written hint, so the common successful-dispatch path
  issues ZERO SQL (was an unconditional per-dispatch DELETE)

Observability + cleanups:
- restore the obo_mint_rejected log carrying the IdP error text (the
  shared-helper unification dropped it); event names passed as whole
  literals so alerting can grep them
- persist_rotation typed Callable[[str], Awaitable[None]] (was Any)
- _prime_one branches on _obo_server_names (no pre-lookup SQL for
  oauth_user)
- removed now-dead any_oauth_user_mcp_servers (3 impls + tests)

+13 regression tests. Full mcp/oidc/console suite 1888 green; mypy clean.

Refs #551.
2026-07-12 19:03:35 -07:00
Patrick Buckley d02b9c0cf0 fix(mcp): oauth_obo credential lifecycle + pending-badge coverage (P1 per review)
- credential revocation (440): admin OIDC identity-unlink now deletes the
  captured IdP credential too (via delete_oidc_credential, previously
  zero callers), so a deprovisioned user stops minting — audited with
  obo_credential_revoked
- pending-consent badge gate (3539): new any_user_scoped_mcp_servers
  (oauth_user OR oauth_obo) replaces the oauth_user-only gate, so an
  obo-only install no longer short-circuits the badge to {pending: 0}
- pending-consent clear (5966): dispatch SUCCESS now clears the pending
  row (auth-blind _clear_pending_consent_sync) — the only clear path that
  covers obo, whose rows the token sweep (skips obo) and consent callback
  (obo never runs) would otherwise never clear
- test:50: strengthened the created-preservation assertion to plant a
  distinctly-past created via SQL so a reset is actually detectable

+4 tests (obo/user-scoped gate). NOTE: finding 1992 (orphan cache row on
concurrent delete-during-mint) accepted as bounded residual — the orphan
is a short-lived access-token cache row with NO refresh token, useless
without the deleted credential and self-expiring; a full fix needs FKs or
a delete-spanning lock. Tracked for follow-up.

Refs #551.
2026-07-12 19:03:35 -07:00
Patrick Buckley 429a7fd13c fix(mcp): prime oauth_obo pools at session start (fixes inert feature)
The review's most severe finding: nothing warmed oauth_obo pools, so
their tools never entered any per-user catalog and the documented 'mint
on first dispatch' was unreachable (the model can't dispatch a tool it
can't see) — the whole feature was dead in chat.

prime_user_pools now iterates both pool-backed registries. _prime_one
fetches server_row first, then routes oauth_obo through
get_obo_access_token_classified (mints from the captured credential;
missing credential → skipped, the re-login rail handles it) and
oauth_user through its own path unchanged. _rebuild_user_tool_map is
already auth-type-blind, so a warmed obo entry surfaces its tools.

+2 regression tests (obo routed through mint + warmed; skipped cleanly
when the user has no credential).

Refs #551.
2026-07-12 19:03:35 -07:00
Patrick Buckley d84393c25c fix(console): widen admin MCP surface for oauth_obo (P0/P1 per review)
- write-time validation (_enforce_oauth_obo_requirements): reject an
  oauth_obo row with no oauth_audience (400) or no encryption key (503,
  else it SystemExits the cluster at next boot) — at the save choke
  point, not per-dispatch (findings 10137/10163)
- update handler no longer nulls oauth_audience/oauth_scopes for
  oauth_obo (it needs them); clears only the oauth_user-only columns
  (10344)
- auth_type-transition purge now covers every pool-backed transition,
  including oauth_user->oauth_obo (was skipped: old per-server-AS refresh
  tokens leaked into the mint cache + left a live grant at the old AS
  unrevoked) and oauth_obo->static/none (10326)
- URL-change purge + https enforcement + client-secret clear now apply to
  oauth_obo, not just oauth_user (10339)
- bulk-revoke accepts oauth_obo — the documented remediation for the
  stale rows a flip leaves behind (10705)

+6 console tests (obo audience/key required, happy path, flip-purge, obo
bulk-revoke).

Refs #551.
2026-07-12 19:03:35 -07:00
Patrick Buckley 17c44305d6 fix(mcp): harden oauth_obo mint engine per max review (P0 security core)
Addresses the review's B/D/F classes + single-sourcing:

- B (credential corruption): the rfc8693 refresh-leg rotation is now
  persisted the instant it is obtained, BEFORE the exchange leg, via a
  persist_rotation callback under the held credential lock. A rotated RT
  survives an exchange-leg failure (no more cascade lockout), and the
  exchange response's own audience-scoped RT is never written to the
  shared credential.
- D (wrong-audience bearer): the entra leg ALWAYS pins scope=<audience>/
  .default (scope is Entra's only audience carrier); per-server
  oauth_scopes no longer replaces it (that dropped the audience and
  leaked a Graph-audience token to the MCP server). oauth_scopes stays a
  rfc8693-only knob.
- F (state-machine divergence): extracted _handle_refresh_failure, called
  by BOTH oauth_user and oauth_obo — oauth_user behaviour byte-identical
  (1304 tests green). Fixes: obo cooldown now gated on needs-mint so a
  force_refresh 401-retry falls through (2063); credential decrypt errors
  classified not raised (2099); permanent-rejection arms the cooldown as
  a terminal backstop so it stops re-minting + re-auditing every dispatch
  (2156); malformed-200 resets the ambiguous streak (2196); misconfig
  arms the cooldown to dampen the log/SQL flood (2089); server_row
  threaded from the dispatch caller to drop a hot-path SQL round-trip (2069).
- messaging (5993): obo refresh_failed now points at re-login/admin, not a
  nonexistent per-server consent flow.
- single-source (580/9732/217/1830): USER_SCOPED_AUTH_TYPES +
  is_user_scoped_auth live in mcp_crypto (leaf), re-exported; OBO_GRANT_
  PROFILES derives from _OBO_MINT_LEGS and drives oidc validation (was
  dead-exported).

+5 obo regression tests (rotation-survives-exchange-fail, exchange-RT-
ignored, terminal cooldown, cooldown fall-through, decrypt classified).

Refs #551.
2026-07-12 19:03:35 -07:00
Patrick Buckley e38e573f7c feat(mcp): route oauth_obo servers through the per-user pool
Gate sweep of the pool-backed class: oauth_obo joins oauth_user at
every pool-keying site, judged individually -

- _obo_server_names sibling registry (reconcile + boot); priming,
  keep-alive sweep, and consent-flow sites deliberately keep iterating
  _oauth_user_server_names only (obo has no per-server consent; its
  keep-alive lands with the credential lifecycle work)
- pool routing/status/static-health/tool-resolve gates use the shared
  is_user_scoped_auth predicate; status reports the real auth_type
- dispatch: _pool_token_lookup routes oauth_obo to the mint engine;
  'missing' detail becomes a re-login message (no per-server Connect
  URL is advertised - _build_consent_url already returns None)
- _db_servers_to_config skips obo rows from static auto-connect (would
  handshake-fail with empty headers and trip the breaker)
- web_search backend refusal covers both per-user auth types
- console: oauth_obo in _MCP_AUTH_TYPES, https enforcement extended;
  startup key requirement counts obo rows (encrypted mint cache)

Refs #551.
2026-07-12 19:03:35 -07:00
Patrick Buckley fd60450700 test(mcp): pin oauth_obo mint engine wire shapes and custody semantics
14 cases with exact request-body assertions per the spike-verified
shapes: entra default-scope + per-server override, rfc8693 two-call
chain with subject-token threading and rotation write-back, cache-hit
zero-call fast path, permanent-rejection cache-drop-credential-kept
(with the token_revoked audit row), transient cooldown short-circuit,
and loud-but-retryable misconfiguration.

Refs #551.
2026-07-12 19:03:35 -07:00
Patrick Buckley 012ad2a9b3 feat(mcp): oauth_obo mint engine - single-credential per-server token minting
get_obo_access_token_classified: sibling of the oauth_user classified
lookup sharing its result vocabulary, cache table, locks, and backoff,
but 'refresh' = mint from the user's captured credential via the
deployment grant leg ([oidc] obo_grant_profile):

- entra: one refresh-token redemption, scope=<audience>/.default
- rfc8693: refresh grant -> standard token exchange (audience=)

Both wire shapes are spike-verified (docs/design/obo-spike). Key
semantics: a missing cache row mints (no consent prerequisite); a
PERMANENT rejection drops only the per-server cache row - the shared
credential is never auto-deleted, so one mis-granted server cannot
lock a user out of the rest; rotation write-back persists the newest
credential BEFORE the cache write; mints single-flight cluster-wide on
a per-(user, issuer) advisory lock.

is_user_scoped_auth/USER_SCOPED_AUTH_TYPES define the pool-keyed auth
class once for the upcoming client-side gate sweep.

Refs #551.
2026-07-12 19:03:35 -07:00
Patrick Buckley 0732f9a7d2 feat(mcp): capture the IdP refresh token at OIDC login (opt-in)
[oidc] capture_user_credential (default off; env
TURNSTONE_OIDC_CAPTURE_USER_CREDENTIAL) persists the user's IdP refresh
token - encrypted with the MCP token envelope - as the single
credential oauth_obo servers will redeem on demand.

- enabling the knob appends offline_access to the login scopes
  (idempotent when the operator already lists it)
- capture runs after user provisioning and is best-effort: a capture
  failure logs loudly but never blocks login; the mint path surfaces a
  missing credential on the reconnect rail
- startup hard-fails (SystemExit) when capture is enabled without a
  [security] token encryption key, same as the oauth_user enforcement

Refs #551.
2026-07-12 19:03:35 -07:00
Patrick Buckley be22eb2fee feat(mcp): add oidc_user_credentials storage for single-credential minting
One captured IdP refresh token per (user, issuer), Fernet-encrypted with
the same envelope as mcp_user_tokens - the credential that
auth_type='oauth_obo' servers will redeem on demand for per-server
access tokens instead of holding per-(user, server) refresh tokens.

- migration 067 + mirrored create_all schema (parity-tested)
- storage protocol + both backends: upsert (replace-on-conflict),
  get, rotation write-back, delete, delete_user cascade
- MCPTokenStore encrypt/decrypt wrappers

Refs #551.
2026-07-12 19:03:35 -07:00
Patrick Buckley f4e54ce814 fix(install): gate get.docker.com by $ID instead of trapping all failures
Deciding the installer up front — get.docker.com for the IDs it recognizes,
Docker's repo directly for unrecognized derivatives — avoids treating a
transient get.docker.com failure (network, apt lock, EOL sleep) on a supported
distro as an "unsupported distro" and silently routing it into the repo path.

Recognized IDs now surface the real failure via die instead of masking it;
unrecognized derivatives (Nobara, Mint, …) skip the doomed call and its
"Unsupported distribution" output entirely rather than running it to fail.

Addresses review feedback on #829.
2026-07-11 18:41:05 -07:00
Patrick Buckley 4d423913b1 fix(install): install Docker on distros get.docker.com rejects
run.sh delegates Docker installation to get.docker.com, which detects the
distro from $ID alone and aborts with "Unsupported distribution '<id>'" on
any derivative it doesn't hardcode — Nobara (the reported case), Linux Mint,
Pop!_OS, AlmaLinux, Oracle Linux, and so on. run.sh's own detection already
resolves these via ID_LIKE/fallback, so the family is known; only the
delegated install fails.

When get.docker.com exits non-zero, fall back to adding Docker's official CE
repo for the upstream the family maps to and installing the same packages
(including the compose plugin the rest of run.sh depends on). Upstream is
chosen from PLATFORM_ID for the dnf family — Fedora is platform:fNN, Enterprise
Linux platform:elN, which ID_LIKE cannot distinguish (Nobara's is
"rhel centos fedora" yet it is pure Fedora) — and from UBUNTU_CODENAME for the
apt family, which is present only on Ubuntu lineage and is the exact codename
Docker's repo expects (Mint's VERSION_CODENAME is not).

Fixes #822.
2026-07-11 18:41:05 -07:00
Patrick Buckley a4876c00e2 fix(admin): add create-admin CLI; stop run.sh onboarding into a role-less user
The installer's "Finish setup" told users to run `turnstone-admin create-user`,
which creates a user with no role. Web login derives scopes solely from assigned
roles (empty perms -> read only), so that account logs in read-only and every
admin action fails with "Forbidden: token lacks 'approve' scope". Creating any
user also flips setup_required to false, so the browser first-run wizard -- the
only path that assigns the builtin-admin role -- never appears.

- run.sh: point "Finish setup" at the web setup wizard; use create-admin as the
  headless fallback instead of create-user
- admin.py: add `create-admin` -- creates a user + assigns builtin-admin, or
  promotes an existing role-less user (idempotent); guards on the seeded admin
  role and enforces the wizard's 8-char password floor for fresh accounts
- tests: cover fresh-grant (approve reaches the derived login scope), the
  promote/recovery path, idempotency, and both validation exits

Fixes #824
2026-07-11 18:15:48 -07:00
Patrick Buckley 6a94dc1d57 fix(judge): thread model-definition capabilities into judge completions
The intent judge and output-guard judge were the only create_completion
callers that never passed model-definition capabilities, so operator-declared
capabilities (effort passthrough, tool support, temperature, verbosity) were
silently ignored on judge calls. Every in-ChatSession lane threads them via
_resolve_capabilities; the judges live outside the session and never reached
it.

Add a shared _resolve_model_capabilities() helper mirroring
ChatSession._resolve_capabilities, and have both judges resolve
self._capabilities — from the judge alias's model definition, or the injected
session capabilities on the session-model fallback — and pass capabilities=
into create_completion. Replace each judge's context_window int arg with
session_capabilities: the fallback window now derives from the resolved caps
(identical to what the session passed before), while the alias path keeps
reading ModelConfig.context_window, a separate field the capability merge must
not touch.

Refresh the stale docs/judge.md note claiming sub-agents are exempt from intent
validation — task agents have been judge-gated since #773.

Refs #823
2026-07-11 17:53:24 -07:00
Patrick Buckley 8e2657248d docs(task-agent): record the decided durable-sub-turn id strategy at the mint site
If sub-turns ever persist: Turn-IR verbatim, re-mint at load (run_seq is
session-scoped), rebuild the wire map from the native lane's structural
1:1 pairing with the mirror; turns without native client tool blocks
need no entries. The map itself is never persisted — it is derivable,
and a second durable source of truth would have to be kept in lockstep
with the turns. Also documents why the mint must never be string-split
(not injective: parent and original may contain the delimiter).
2026-07-11 16:37:13 -07:00
Patrick Buckley 660aff6f1e fix(task-agent): guard the Google swap against partial lanes; fix a stale comment
The fidelity swap now requires the raw lane to be a faithful counterpart
of the mirror — same length, every id present — before replacing
tool_calls; a partially-corrupted lane (filtered non-dict elements)
would otherwise swap a shorter list over the mirror and orphan a
mirrored call whose tool result remains in history. The _run_agent
call-site comment now matches the builder's reasoning_text-only
blank-id rule.
2026-07-11 16:37:13 -07:00
Patrick Buckley dc52bc2b96 fix(task-agent): simplify the blank-id rule to reasoning_text-only and heal historical rows
The blank-id gate's strip-then-filter semantics left two residual
hazards (surviving Responses reasoning items whose pairing contract
needs their original sibling items; an asymmetric Messages-shaped lane
surviving when no client block was actually stripped). The rule is now
total and simpler: on a blank-id turn only the loose-text
reasoning_text synth block survives — it carries no id and is
shape-invalid on the Messages translator by design, and real-world
blank-id servers are Chat-Completions locals whose reasoning IS that
loose text. This also removes the builder's per-call provider import.

The Google fidelity swap now skips raw rows carrying a blank id
(historical captures that predate the gate would otherwise resurrect
the blank id on every replay — the sanitized mirror stays), guards
against non-dict lane elements, and legalizes via the new shared
lowering.legalize_tool_call_entry — the ONE per-entry legalizer the
sanitize pass also uses, so the two seats cannot drift on semantics or
the wire.tool_args_legalized breadcrumb.
2026-07-11 16:37:13 -07:00
Patrick Buckley 98cefc3660 fix(task-agent): move the blank-id gate into the shared native-lane builder
The blank-provider-id gate lived only at the _run_agent call site while
the main-loop stream accumulator has the identical back-fill-then-carry
seam — and it over-dropped, discarding the reasoning lane for exactly
the servers that emit blank ids. The gate now lives in
_finalize_provider_blocks as a had_blank_ids parameter both harnesses
thread: client tool blocks (which keep the blank id the mirror back-fill
never reached) are stripped, and when any were present the remaining
Messages-shaped blocks go with them (a surviving native lane REPLACES
the rebuilt content on the Anthropic translator, so a lane missing its
tool_use would orphan every mirrored call) — while shape-invalid
reasoning residuals (reasoning_text, Responses reasoning items) are
kept. This also closes the pre-existing main-loop case: a Gemini
openai-compat turn with a blank tool id no longer persists a raw
fidelity dict whose blank id the swap would resurrect on every replay.

The Google fidelity-swap legalization now reuses the canonical
lowering.legalized_arguments (made public) instead of a hand-rolled
narrower copy: dict-shaped arguments are serialized rather than
collapsed to {}, the standard wire.tool_args_legalized breadcrumb is
logged, and a degenerate non-dict function entry passes through
untouched instead of raising.
2026-07-11 16:37:13 -07:00
Patrick Buckley 646bceed52 fix(task-agent): review fixes for the native-lane carry
- Skip the native lane on a turn whose provider left a tool-call id
  blank: the uuid back-fill reaches only the tool_calls mirror, so a
  carried native tool_use block would replay the blank id and desync
  from the restored tool_result (Anthropic orphans the result; Google
  re-fills a fresh uuid). The rebuild path keeps every representation
  on the back-filled id — the pre-native behaviour, for exactly the
  degenerate case.
- Extract _reasoning_text as the ONE Chat-Completions reasoning
  extractor shared by the streaming and non-streaming paths: first
  non-empty STRING of reasoning/reasoning_content wins, so a server
  putting a structured object in reasoning can neither shadow valid
  text in reasoning_content nor leak a non-str into the session's
  reasoning accumulator.
- Legalize arguments when GoogleProvider's fidelity swap replaces the
  sanitized tool_calls mirror with the raw provider dicts — the swap
  could resurrect a malformed arguments string the upstream sanitize
  pass had fixed (pre-existing on the main loop; ids and
  thought_signature untouched).
- Drop the redundant emptiness guard on the agent seam's
  reasoning_parts (the shared finalize helper already guards) and
  document the wire_id_map lifetime invariant for future
  resumable/background agents.
2026-07-11 16:37:13 -07:00
Patrick Buckley d660819142 feat(task-agent): carry the provider-native reasoning lane in the sub-harness
A task agent's replayed turns now carry the native reasoning lane the
model produced (Anthropic thinking blocks + signatures, OpenAI Responses
reasoning items, Gemini thought_signature blocks, vLLM/llama.cpp parsed
reasoning text) instead of being rebuilt from content + tool_calls with
the reasoning dropped — restoring reasoning continuity across the
agent's own multi-turn tool loop on every provider lane.

The prerequisite is the id half: replace legalize_tool_call_ids with
restore_provider_tool_ids, a lowering pass that maps the session-minted
sub-tool ids back to the provider's own ids on the transient wire copy
(from the per-run mint map, never by string-splitting). The native
tool_use block is replayed verbatim — its id and signature untouched —
and the top-level mirror and tool_result agree with it on every request.
The minted id stays the sole internal key (registry, DOM, recall,
cancel ledger), #820 unchanged.

Chat-Completions lane: non-streaming create_completion now surfaces
reasoning/reasoning_content as CompletionResult.reasoning (the twin of
the streaming reasoning_delta extraction), and the agent seam runs the
Phase 5 vLLM reasoning-field replay against the agent's own provider
and alias. The native lane is finalized by a shared helper
(_finalize_provider_blocks) so the main loop and the sub-harness cannot
drift; replay honors the per-model replay_reasoning_to_model flag on
every lane, and llama.cpp stays capture-only, matching the main loop.
2026-07-11 16:37:13 -07:00
Patrick Buckley a5c3dc00fc fix(task-agent): address Copilot review on the id projection
- wire_safe_tool_call_id: SHA-256 not SHA-1 for the deterministic token —
  matches the codebase convention for fingerprints (attachments, auth,
  session) and drops the SHA-1 scanner flag. Non-crypto use, ids unchanged
  in shape (tid_ + 32 hex); no test pins the literal value.
- interactive.js: the two sub-agent child-id example comments now show the
  real minted shape (<parent>::r{run}s{step}::<id>), not a stale <seq> form.
2026-07-11 13:12:27 -07:00
Patrick Buckley 110d6b4fc0 fix(task-agent): mint session-unique sub-tool ids
Sub-agent tool ids were namespaced {parent}::{provider_id} — unique
across concurrent agents but not across turns within one agent. A local
provider reissuing "call_0" every response minted the same id twice, so
the live card's DOM row lookup collapsed distinct calls onto one row
while FIFO recall kept them apart: two views of one trajectory disagreed
on identical input (the bug-3 id-consistency defect). When the provider
also reuses the PARENT call id, sequential runs repeated the collision
one level up.

Mint {parent}::r{run}s{step}::{provider_id} at the single rewrite point:
a session-monotonic run tag (lock-allocated; runs start concurrently on
the 4-wide task pool) plus a per-run step tag make each id unique within
the session, and every consumer — nesting registry, error flags, DOM
data-call-id, recall projection, cancel ledger — keys on that one id.
The FIFO pairing helper stays as honest pairing for un-minted input
(unparented runs, direct construction), with its rationale rewritten.

The agent wire seam (_run_agent's _api_call) also runs the same two
validity passes the main loop already ran — sanitize_tool_call_arguments
(a documented vLLM deepseek_v4 renders malformed args and 400s; agents
hit the same backends) and legalize_tool_call_ids (projects the long,
::-containing ids to plain tokens, call/result pairing preserved). The
id projection is DEFENSIVE hardening, not a fix for an observed break:
the ids replay fine on the lenient anthropic-compatible deployment (the
prior ::-containing format ran reliably), it just keeps an agent's
self-built history valid on a hypothetically stricter backend. Applied
at the agent seam only — main-loop assistant turns carry a provider-
native block lane whose id must stay byte-identical to the mirrored
tool_calls, so the projection cannot run there without desyncing them.

Follow-ups: parent-level card aliasing under a reused parent id; the same
id hygiene for the main conversation loop / native lane.
2026-07-11 13:12:27 -07:00
Patrick Buckley 062a260c88 fix(console): scope response-control dirty flag to the identity that set it
A dirty flag set by touching a verbosity/reasoning-mode select survives a
model/provider/surface change, so the merge-side delete could destroy a key
hand-typed into the Advanced JSON for the renamed row. Honor the dirty
override only while the identity still matches the row that made it dirty.

Also document the captured-value fallback contract at both sites (the
baseline is deliberately not consulted: it arrives async or never on the
compat lane, capture has already lifted the value out of the row JSON, and
emission is gated server-side on the merged supports_* flag) and pin the
fallback plus the scoped dirty-delete in test_app_js.
2026-07-10 15:59:40 -07:00
Patrick Buckley 03861e0cf5 feat(console): verbosity and reasoning-mode controls in the model shelf
- capability-gated "Response controls" on the Models create/edit
  shelf: Output verbosity (low/medium/high) and Reasoning mode
  (Standard/Pro), shown only for Responses-surface models; the empty
  selection means provider default and omits the capability key
- values lift out of the capabilities JSON into the selects on edit
  and merge back on save with identity tracking, so changing the
  provider/model/surface resets them instead of carrying a value
  across models; the Advanced JSON textarea wins unless the select
  was touched last
- known GPT-5.6 models inherit support from the static table without
  persisting redundant support flags; OpenAI-compatible models pinned
  to the Responses surface opt in via the supports_verbosity /
  supports_pro_mode tiles
- invalidate in-flight capability lookups on any identity field
  change and on modal open so a stale response cannot clobber a fresh
  shelf; API-surface changes now run the full field-change path
- model list rows surface verbosity= / mode= override chips
2026-07-10 15:59:40 -07:00
Patrick Buckley b450b9ad20 fix(providers): align GPT-5.6 with the GA API surface
- every 5.6 tier accepts effort "max" and reasoning.mode
  "standard"/"pro" (GA docs: pro is a request mode on any GPT-5.6
  model) -- drop the Sol-only gating
- GPT-5.6 deprecates prompt_cache_retention; send
  prompt_cache_options={"ttl": "30m"} (its only supported lifetime)
  and keep the 24h retention policy for pre-5.6 models
- never inject commercial cache params into local lanes: dropped from
  the Chat Completions lane (which serves only openai-compatible and
  google) and gated off the compat-pinned Responses lane -- a gpt-5*
  served-model name is not an OpenAI account
- account cache writes: usage *_tokens_details.cache_write_tokens
  flows into cache_creation_tokens (5.6 bills writes at 1.25x the
  uncached input rate)
- drop non-string verbosity/reasoning_mode overrides with a warning
  instead of raising on unhashable capability-JSON values
- keep ModelCapabilities' public positional prefix stable by appending
  the verbosity/pro fields at the tail; pin it with a constructor test
- openai floor 2.44 -> 2.45, the first release with the typed
  prompt_cache_options kwarg
2026-07-10 15:59:40 -07:00
Patrick Buckley dc647f4d63 fix(bash): report exit code for killed shells; single import style in registry tests
Copilot: bash_output's schema promises the exit code once the shell has
exited, but the formatting attached it only to 'completed' — a killed
shell has one too (the negated signal number). Attach it to any exited
state.

Code-quality: the registry test file mixed a top-level from-import with
function-local 'import ... as bg_mod' for monkeypatching module
attributes; one from-style module alias at the top now serves all of
them.
2026-07-10 15:42:33 -07:00
Patrick Buckley ab7d56e0ba feat(bash): opt-in background shells with delta output reader and kill tool (#817)
Restore 'start a dev server, use it in a later call' as an explicit opt-in
after #816 made bash reap its whole process group on return. The surface
mirrors the dominant coding-agent convention: bash(run_in_background=true)
returns a bash_N handle immediately; bash_output(id, filter?) returns only
output produced since the previous read plus status and exit code;
kill_shell(id) terminates the shell's whole process group.

- Per-session BackgroundShellRegistry: capped rolling line buffer with
  drop-oldest gap accounting, exit-order record pruning, owner scoping for
  task_agents (shells reaped when the agent finishes), liveness-guarded
  group kills (a stale pgid is never signalled), budgeted teardown joins.
- Exit notices ride a shared external-event rail (sanitize, soft cap,
  channel 'any', idle wake) now common to watch fires; a new 'quiet'
  NudgeQueue channel lets a user cancel defer pending notices without
  letting them re-wake the stopped workstream, and failed wake delivery
  re-queues external notices seq- and predicate-intact without re-arming
  the wake gate.
- The bash_output filter runs in a killable subprocess: sre holds the GIL
  for an entire search, so no in-process timeout can bound a hostile
  pattern. Scrubbed child env, pinned UTF-8 pipes, honest timeout-vs-
  helper-failure error taxonomy, per-line match window with explicit
  clipping notes; a failed filter never consumes the delta.
- run_in_background rides the bash intent-judge projection; bash_output is
  exempt from the repeat warning but still recorded so interleaved polls
  keep breaking other tools' streaks; all bash boolean args share one
  lenient coercion dialect.
- Shells survive generation cancel and die with the workstream: every
  teardown path funnels through ChatSession.close(); CLI exit and the
  server lifespan now close every loaded session, signal-first and
  Ctrl-C-safe, so nothing detached outlives a graceful shutdown.
2026-07-10 15:42:33 -07:00
Patrick Buckley bec757a96b test(bash): use tmp_path fixture instead of tempfile.mktemp
CodeQL flagged tempfile.mktemp as an insecure temporary file and Copilot flagged the same call as race-prone (the path is not reserved). Use the pytest tmp_path fixture, which reserves a unique per-test directory and is cleaned up automatically.
2026-07-10 00:04:40 -07:00
Patrick Buckley c1cfb668b9 docs(changelog): sync 1.7.x release notes from stable/1.7; note bash fix
main was missing the 1.7.1 through 1.7.3 sections and the two-track preamble that shipped on stable/1.7; bring them in and add an Unreleased entry for the bash background-hang fix.
2026-07-10 00:04:40 -07:00
Patrick Buckley f1f488aa55 fix(bash): do not hang when a command backgrounds a long-lived process
A bash command that leaves a process running in the background (server &, a daemon) could wedge the whole workstream forever: the tool read stdout/stderr to EOF, which never arrives because the child inherits the pipe, and the timeout watchdog bailed the moment the tracked bash exited.

Wait on the tracked process bounded by the tool timeout (keyed on process exit, not pipe EOF) and terminate its whole session group on every exit path, reaping any backgrounded survivor, forcing the drain threads to EOF, and leaving nothing to leak. Decode with errors=replace so undecodable output is preserved instead of dropped, and pre-bind proc so a Popen failure surfaces the real error.

Behavior change: a process the command backgrounds no longer survives the call. First-class opt-in backgrounding is left as a separate change.
2026-07-10 00:04:40 -07:00
Patrick Buckley 9668862a7f fix(personas): engineer prompt wording from PR feedback
Name the task_agent tool literally so the model connects the guidance
to the tool the persona grants, and restore "asking for permission".
2026-07-09 19:19:02 -07:00
Patrick Buckley a0d7e2266e feat(personas): harden engineer base prompt with process discipline
engineer.md is the default BASE module for non-coordinator sessions.
Rework it from posture-level guidance to explicit process discipline:
phased work (understand, design, plan, edit, verify) with ceremony
scaled to the size of the change, red-green as the default for
testable work, minimal-diff scoping, a thrash-stop after repeated
failed attempts, and reporting only observed results. Exploration
delegates to task agents; push-back happens once, then defers with
the disagreement stated for the record.
2026-07-09 19:19:02 -07:00
Patrick Buckley 2ca4113ce5 docs(hypothesis): carry the factored Q_E reading into the glossary; primer wording
Review follow-ups: the s-shorthand convention and its glossary echo now
cover Q_E's own state argument (s -> w where Q_E reads it), and the Q_E
glossary row carries the factored (w, a) ~> (w', o) reading so the
symbol table no longer reintroduces the environment-reads-all-of-s
interpretation the outer-kernel note warns against. PRIMER: the
top-alone-widens bullet keeps owner language anchored to the
simple-case top; success is defined as an accepted end, consistent
with the declared-vs-actually-right distinction two sentences later.
2026-07-09 19:14:32 -07:00
Patrick Buckley 31301ba2a6 docs(hypothesis): harden the normal form; sync PRIMER
HYPOTHESIS.md:
- carry the initial law mu_0 in the tuple (and its displayed signature);
  split the rejection symbol into parse failure vs authorization
  refusal, with gamma(s, bot_Y) = bot_A as an axiom and a positional
  convention for the remaining bare bots
- factor the state s = (q, w) and retype Q_E to (w, a) ~> (w', o) so the
  latent world has a generator and the displayed T is its stated
  projection; quantify fail-closed over a rejection-invariant safe set K
- read H_ok as operational acceptance (H_acc) against analysis-only
  success G, with a convention for which claims read which side; score
  C6's ceiling against G and pin C5's slack to the correct-halting
  drift, resolving the tension with its own falsifier
- state ledger integrity relative to an attestation assumption (reported
  vs actual effects); split cancellation into safe vs unresolved and
  count unresolved as possibly-bad; add the realizability clause to
  C1/C3; admit multi-principal trust tops as deployment choices
- reversibility is declared in the tool contract the gate reads at
  authorization; the returned record's mark is confirmation, not source

PRIMER.md: mirror the same corrections in plain language -- ceiling not
cliff for the desk wall, contract-first reversibility, the multi-party
trust top (including the summary line), declared-vs-actual success on
dashboards, reported-vs-actual ledger honesty, cancel is not
automatically safe.
2026-07-09 19:14:32 -07:00
Patrick Buckley f5f721a979 fix(providers): include allowed reasoning modes in the unknown-mode warning
Mirror the verbosity warning so an operator typo in reasoning_mode logs the allowed values, not just the offending one.
2026-07-09 18:48:51 -07:00
Patrick Buckley 47f908c9e0 feat(providers): add OpenAI GPT-5.6 (Sol/Terra/Luna) support
Onboard the GPT-5.6 family (GA 2026-07-09) to the OpenAI Responses lane.

- Capability rows for gpt-5.6 (= Sol alias/catch-all), gpt-5.6-terra, and
  gpt-5.6-luna: 1.05M context, 128K output, tool_search/vision/pdf/reasoning
  replay, default effort medium, temperature only at effort=none.
- "max" reasoning effort, Sol-only; Terra/Luna cap at xhigh (the knob's "max"
  snaps to the xhigh ceiling). First commercial OpenAI use of "max" — the
  ordinal knob already ranked it, so no effort-ladder change was needed.
- Verbosity and pro mode as operator-declared capability fields
  (supports_verbosity/verbosity, supports_pro_mode/reasoning_mode), merged
  from the model-definition capabilities JSON and emitted on the Responses
  wire as text.verbosity and reasoning.mode. Both are gated by a supports
  flag plus an enum guard that drops unknown values with a warning. Pro mode
  is Sol-only. There is no gpt-5.6-pro model — "pro" is the reasoning.mode
  param, not a separate model id.
- Raise the openai floor to >=2.44 for the 5.6 Responses params.

Unit and wire-golden tests cover the rows, max->xhigh snapping, the two
levers, and the enum guards. Validated live against the OpenAI API: gpt-5.6
accepts the model id, effort "max", text.verbosity, and reasoning.mode="pro".
2026-07-09 18:48:51 -07:00
Patrick Buckley 2a32211e4a feat(webui): port SSE overflow-recovery companions to the coordinator pane
The #805 server-side fixes (emit-time batching, _ListenerQueue poison,
out-of-band closing) already cover every SSE stream, but the client-side
companions lived only in the interactive pane. Port them to coordinator.js
and extract the drift-prone pure core into a shared module (closes #806).

- shared_static/sse_overflow.js (new): storm-guard constants +
  overflowWindowTripped + degradedCooldownStep, imported by both panes so the
  trip threshold and cooldown ladder have one source of truth. interactive.js
  imports these instead of holding local copies; the two node runtime probes
  move to tests/test_sse_overflow_js.py.
- coordinator.js: handle the stream_overflow frame (storm guard -> degraded
  catch-up with a doubling cooldown; the reconnect replays from the ring, or
  falls to the replay_truncated -> /history floor); add the close-on-hide /
  replay-on-show visibilitychange handler plus a document.hidden guard at the
  connectSSE chokepoint; add drop-vs-render-wedge counters (onmessage now wraps
  the dispatch in try/catch -- the coordinator previously had no wedge guard,
  so a handler throw silently poisoned every later turn).
- After a stream gap the children/tasks sidebar re-syncs only when the ring
  replay cannot cover it: no resume cursor, a replay_truncated envelope, a gap
  beyond the cursor-trust window, or a live event id below the saved cursor (a
  process restart reset the counter, which the replay path reports as a false
  replay_ok). child_ws_*/task events are ordinary ring entries, so an ordinary
  short reconnect heals the sidebar through the live handlers with no REST
  rebuild -- a momentary blur/focus under close-on-hide rebuilds nothing.
- Close-session teardown detaches the visibility handler before the close POST
  so a hide/show mid-close can't resurrect a dying stream. A replay_truncated
  seen mid-stream is deferred (not dropped) and re-synced from /history on the
  next idle -- repairing both a ring-evicted gap and a turn stranded by
  close-on-hide (stream_end evicted while hidden), matching interactive.js's
  _pendingTruncatedResync.

The extraction stops at the pure core: interactive.js's stateful glue is
hard-pinned by its source-assertion suite, so its class-method shape stays put
and the coordinator reimplements the equivalent glue as closure functions.

Tests: new test_sse_overflow_js.py (module exports + the two runtime probes);
coordinator parity + lifecycle pins in test_app_js.py (replay-aware sidebar
refresh, restart detection, truncated-resync deferral, close-session
visibility detach); interactive's moved probes replaced by an extraction pin.
All JS-source suites green.
2026-07-08 16:58:23 -07:00
Patrick Buckley d115111756 docs(hypothesis): daemons + the outer loop; plain-language PRIMER
HYPOTHESIS.md:
- New appendix entry "Daemons (the recurrent harness)": a daemon as the
  regenerative process of concatenated runs — ready-set recurrence,
  renewal-reward lifting exactly at regeneration points, accumulation as
  what breaks regeneration (cross-cycle provenance meet, renewal events
  that reset accumulated risk), and authority under intermittence
  (owner contact as a renewal point for authority; TOCTOU at cycle
  scale).
- New body section "The loop": the task-dispatching outer loop as the
  harness construction applied one level out — the composition
  correspondence read at the top level, the daemon as its single-agent
  special case, the bare while-loop as the trivial-group harness one
  level up. Flagged as a sketch; outer fail-closed/reach-avoid
  treatment deferred to later rounds.
- Veto caveat threaded to match: judge-as-veto safety scoped to the
  authority lattice, and the nonblocking escape degrades to an
  always-enabled safe halt when the principal is unreachable.
- Consistency: Grounding's Asserted tier now covers "The loop";
  "always-enabled escalation" -> "escape" (the appendix's own term, now
  that the escape has an unattended form); brace the one unbraced \bot
  subscript (linter section-B HIT).

PRIMER.md: new plain-language companion — same object, no symbols, the
formal doc wins every disagreement. README's entry link now points at
the primer, which links onward to HYPOTHESIS.md.
2026-07-08 02:49:46 -07:00
Patrick Buckley 5dcf66c284 fix(webui): share renderer-output CSS so the console + coordinator highlight code
highlight.js, KaTeX and Mermaid all run on every surface via the shared
renderer (renderer.js), but their theme/wrapper CSS lived only in
ui/static/style.css. The console and coordinator load /static/style.css from
console/static/ — a different file on a different server — so hljs token spans
fell back to --fg (flat monospace for several releases), and the KaTeX/Mermaid
wrappers lacked their overflow containers, letting wide equations/diagrams
overflow the pane.

Move the hljs theme, .katex-display/.katex-error and the .mermaid-* wrappers
into shared_static/chat.css, which every surface loads via /shared/chat.css.
Restate the mermaid width-clamp for the preview pane (.preview-markdown) too,
since its content isn't a .msg.assistant message.

Drop the redundant background on .msg.assistant pre code.hljs so the <pre>
carries the code surface on every surface — otherwise the console/coordinator
(where the pre is --panel, not --code-bg) showed a darker box inside a lighter
padding band.
2026-07-08 01:37:46 -07:00
Patrick Buckley c328bebecd feat(schedules): add persona and project settings to scheduled tasks
A scheduled task could pin the model and skill of the workstream each
firing creates; it can now also pin its persona and project, so a
schedule can run under, e.g., the researcher persona attached to a
specific project's memory bucket.

The two values live on scheduled_tasks (migration 066, Text NOT NULL
default '') and are passed verbatim to create_workstream at dispatch,
where the node resolves the persona for the workstream kind and gates
the project attach. Empty means "kind-default persona / no project",
resolved late at each firing (mirrors how empty model/skill already
behave) -- existing schedules keep byte-identical dispatch behaviour,
so there is no backfill.

Also fixes a latent bug this feature depends on: admin_create_schedule
read created_by from request.state.user_id, which AuthMiddleware never
sets, so every scheduled task stored created_by=''. It now reads
auth_result.user_id like every other console endpoint. This is now
load-bearing -- the scheduler dispatches under created_by and the node
gates the project attach against it. admin_update_schedule adopts the
editing admin as owner when a project is assigned to a pre-fix orphaned
('') schedule, and re-validates persona/project only when they change
so a since-disabled persona or lost membership does not block unrelated
edits (the node re-checks at dispatch either way).

Wired through: schema + migration (up/down + parity tested), both
storage backends, API schemas, SDK create_workstream and console
create_schedule/update_schedule, scheduler dispatch, and the admin
schedule shelf (persona + project pickers, current value preserved so
an edit cannot silently clear a filtered-out selection).
2026-07-08 00:59:14 -07:00
Patrick Buckley d5ddc95e9f fix(web_fetch): inherit model settings for the extraction completion
The URL-extraction call hard-coded max_tokens=8192 and rode the "low"
reasoning default, which broke local-inference models whose registry entry
advertises a tighter output limit or a different reasoning config. Inherit
the session/registry max_tokens and reasoning_effort instead (temperature
already was) — the same knobs the main turn uses.

max_tokens is capped to context_window // 4, the ~25% output slice Phase 2
already reserves, matching the main turn's response reserve
(_remaining_token_budget), so a large operator budget can't push
prompt + output past a small context window on strict runtimes.
2026-07-08 00:30:44 -07:00
Patrick Buckley 026c646116 test(sse): normalize session_ui_base imports to a single style
github-code-quality flagged 8 spots where tests imported
turnstone.core.session_ui_base both as `from ... import` and `import ... as
suib` (the alias was only there to monkeypatch the module-level batch
constants). Drop the alias and patch via string target
(`monkeypatch.setattr("turnstone.core.session_ui_base._TOKEN_BATCH_WINDOW_SECS", ...)`),
which resolves to the same module global — behavior-identical. The one test
that READS the constant imports the symbol directly. Test-only, no
production change.
2026-07-07 23:32:20 -07:00
Patrick Buckley dfe09d029b fix(sse): guard connectSSE against opening into a hidden tab; fix stale closing comment
PR #805 review (Copilot + the round-3 finding it corroborates):

- connectSSE opened a new EventSource even when the tab was already hidden
  (e.g. a first load in a background tab), where the close-on-hide handler
  never fires because there is no open stream to close — so a throttled
  hidden tab could still become the slow consumer this PR prevents. Add the
  document.hidden guard at the single connect chokepoint, after the wsId
  assignment + visibilitychange-handler install (so the show edge reconnects)
  and before new EventSource (so nothing opens). The timer callbacks keep
  their own pre-checks (the recover beat's also gates failCount); this closes
  the fresh-connect path they never covered.

- Fix the stale _ListenerQueue.closing docstring: it claimed the drain loop
  checks closing BEFORE poisoned, but the round-2 fix moved that check INSIDE
  the poison branch (poisoned+closing -> clean close; a healthy closing queue
  drains its tail to the ws_closed sentinel). Wording now matches the code.
2026-07-07 23:32:20 -07:00
Patrick Buckley 5083f67e96 fix(sse): batch fast-stream tokens and recover overflowed listeners
A long live session driven by a fast local model (500-2000 tok/s) showed
corrupted / missing spans of assistant text while the backend stayed
healthy. Root cause: on_content_token/on_reasoning_token enqueued one SSE
event per model delta, so the per-listener queue (cap 500) overflowed
against any slow consumer; put_nowait on a full queue silently dropped the
newest event. Once saturated, drops scatter (the consumer keeps freeing
single slots), so the client's lastEventId sails past the holes and
reconnect-replay (eid > last_event_id) can never heal them. A dropped
fence-closer reshapes all downstream markdown -> reads as heavy corruption.

Fix B (primary) - emit-time micro-batching:
Coalesce content/reasoning fragments over a ~25 ms window (or 4 KB) into
one _enqueue, cutting the wire event rate ~10-20x at local-inference
speeds. A batch is assembled before it gets an _event_id, so it is one
ordinary ring entry no cursor can fall inside (unlike the forbidden
in-ring coalesce). Two conditions are load-bearing and pinned:
  1. The inflight-buffer append and the enqueue are one _ws_lock section,
     so a snapshot's snap_seq stays a true high-water mark for its text.
     Splitting them lets a straddling snapshot double-render (the client
     content path is a blind +=, no dedup).
  2. Every non-token emit flushes the pending batch first, enforced at the
     single _enqueue choke point, so stream_end/tool_*/state_change can't
     overtake trailing content and repaint it into a new bubble.

Fix A (recovery net) - poison-at-first-overflow:
_ListenerQueue latches `poisoned` atomically at the FIRST rejected put and
refuses every later put, freezing its contents as a contiguous prefix; the
drain loop closes the stream after an id-less stream_overflow frame and the
native EventSource reconnect replays the whole gap from the ring buffer.
Poisoning at the first full (not after N) is required: any deliver-while-
dropping window advances lastEventId past interior holes that reconnect
can't replay. A ws teardown that races the overflow sets an out-of-band
`closing` flag (mark_closing), checked inside the drain loop's poison
branch: a poisoned+closing queue returns clean (no false overflow frame),
while a healthy closing queue still drains its full tail FIFO to the in-band
ws_closed sentinel -- so a slow-but-unpoisoned client never loses the turn's
final content batch + stream_end at teardown.

Client (interactive.js):
- Reconnect storm guard: after 3 overflow closes in 60 s the pane drops to
  a degraded catch-up (stop live streaming, "connection is slow" state,
  reconnect after a doubling 15->120 s cooldown that resyncs from the ring
  or the uncapped /history floor). The cooldown ladder is keyed off a
  last-trip timestamp, not the overflow-window array (which the trip
  clears), so the escalation survives its own backoff.
- Close-on-hide / replay-on-show: a visibilitychange handler closes the
  EventSource on tab-hide (a throttled hidden tab is the likeliest slow
  consumer) and reconnects with the saved Last-Event-ID on show. The
  factory recovery beat defers when hidden, and giveUp() detaches the
  handler, so a dead or backgrounded controller can't reopen a stream.
- Drop-vs-render-wedge counters distinguish this bug (server overflow
  closes) from the handler-wedge class (render/finalize throws) in the
  field. No global gap-detector: live ids are not strictly monotonic
  across concurrent tool+content emit, so a naive id!=last+1 check would
  false-positive; recovery is server-signalled instead.

Corrects the stale _resolve_event_buffer_max comment that justified the
50k ring on a "PR-G closes connections on hide" mitigation that never
existed (the close-on-hide handler above is the real one).

Negative-tested (revert the guarantee, confirm the pin fails, restore):
per-token inflight append -> snapshot straddle double-render; removed
choke-point flush -> stream_end split; no poison latch -> silent drops;
top-of-loop closing check -> healthy-close tail loss; missing mark_closing
wiring / drain closing check -> clean close mis-reported as overflow;
_noteStreamOverflow cooldown reset -> ladder never escalates; removed
hidden-tab recovery guard / giveUp handler removal -> hidden-tab reconnect.
2026-07-07 23:32:20 -07:00
Patrick Buckley e5e48a788a fix(renderer): drop the indent an indented fence close drags into code content
Copilot review on PR #804:
- An indented closing fence line ("  ```") left its leading spaces as a
  trailing whitespace-only line inside the rendered code block: the content
  capture runs up to the backtick run and the close-line indent precedes it, so
  it was captured as content. Strip a trailing newline PLUS any trailing indent
  (/\n[ \t]*$/ instead of /\n$/); a column-0 close is unaffected. Red-green
  pinned (content is exactly "  x = 1", no trailing whitespace line).
- Correct a stale test docstring claiming the fence open anchor allows "up to 3
  spaces" of indent — it allows arbitrary indent (the 4-space case is pinned
  separately).
2026-07-07 23:03:47 -07:00
Patrick Buckley a164d61552 fix(renderer): contain markdown sentinel-forgery and recursive-frame content loss
The markdown renderer protects structural blocks with in-band NUL-framed
sentinels (chr(0)+tag+index+chr(0)). escapeHtml preserves U+0000, so
model/tool text could forge sentinels, and recursively-rendered <details>
bodies re-rendered against fresh block arrays and lost their content. This
lands the ordered containment fixes from the render-containment brief.

Fixes (each pinned in tests/test_renderer_js.py; all NUL-sensitive cases also
confirmed in real headless Chrome, which drops a U+0000 token the node harness
preserves):

- B1/B2/B3 — forged sentinels: strip U+0000 at the TOP-LEVEL render entry only
  (_fnDepth === 0). renderer.js is the sole NUL producer and every restore
  regex is NUL-framed, so removing NUL closes every forgery path (block
  duplication/relocation, out-of-range "undefined", cross-container injection)
  while generated sentinels in recursive frames survive. Only NUL is stripped,
  so a code fence still shows pasted control bytes (ESC/FF/VT/DEL) verbatim.
- B4 — blockquote-in-fence (the common one): the code-fence pass now runs
  before the line-based blockquote pass. Its open matches at line start after
  optional indent and an optional list marker (`- `, `1. `), and re-emits that
  indent+marker before the sentinel so the fence keeps its document position
  (a nested-list item stays nested; a fence continuing a footnote definition
  keeps the indent its continuation scan needs). A blockquoted fence (`> ```)
  is not matched (`>` is neither indent nor a list marker), so the blockquote
  pass extracts that `> ` run and its recursion renders the fence. A `> ` line
  inside a plain fence stays literal.
- B5 — <details> open anchored to line start (^[ \t]*), so a `<details>`
  mentioned mid-line inside inline code no longer starts a block.
- NEW-1 — recursive-frame content loss: <details> extraction runs AFTER fence
  protection and restores a fenced body from a saved raw-source array
  (codeBlockRaw) back to raw markdown before the recursive render, so
  code-in-details renders in-frame instead of restoring to "undefined". Running
  after fence also means a </details> shown as example code inside a fence
  can't close the block early, and a <details> shown inside a fence stays
  literal — no offset-based fence-awareness needed. Inline-code/math in footnote
  definitions render via the restore round-trip the undefined-guard enables
  (documented at the append site).
- NEW-3 — code blocks gained the <p>SENTINEL</p> unwrap variant DT/BQ/MB/TB
  already had, removing a stray empty <p> before a standalone <pre>. The CB
  unwrap is whitespace-tolerant so an indented own-line fence (whose indent the
  fence pass re-emits) also doesn't leave a stray <p>.
- Defense-in-depth: every restore callback returns the matched sentinel
  (inert; the browser drops the NUL) instead of the array's `undefined`.

Non-obvious decisions:
- Control chars are authored as literal \xNN hex escapes (byte-verified: only
  \uXXXX decodes to raw bytes in this toolchain; \xNN matches the file's
  existing \x00 sentinel convention).
- Open anchors allow arbitrary leading indent (the fence open also allows a
  list marker), not CommonMark's ^ {0,3}: the renderer has no indented-code
  fallback, so preserving the prior behaviour of matching indented/list-nested
  fences beats CommonMark strictness, while still excluding `> ``` and mid-line
  forms.
- codeBlockRaw (the <details> raw-fence array) and the restore callbacks are
  factored through a _restorer(arr) helper; codeBlockRaw is only populated when
  the text contains a <details> tag (its sole reader).
- The entry strip is depth-0-only on purpose: an unconditional strip would
  shred the generated sentinels recursive frames carry, foreclosing NEW-1.

Negative-tested (reverted the production line, confirmed the pin fails):
- fence anchor: unanchored swallows a blockquoted fence.
- NEW-1 codeBlockRaw restore: without it, code inside <details> is lost.

Deferred (called out per the brief):
- B6/NEW-4 bidi controls (U+202A–202E, U+2066–2069, U+200E/F) still pass
  through unescaped; they are not C0 so the entry strip misses them. Left to a
  follow-up — stripping risks corrupting legitimate RTL text and <bdi>
  isolation is involved for a string renderer.
2026-07-07 23:03:47 -07:00
Patrick Buckley 2c5adb7aca fix(web): sanitize the latin1_safe_filename fallback too
Review follow-up: the helper returned `fallback` verbatim when the name
sanitized to empty, so a future caller passing an unsafe fallback (non-latin-1,
control chars, quote, backslash) could reintroduce the header crash/corruption
the helper exists to prevent. Not reachable today — all call sites pass safe
ASCII literals — but the helper is a shared safety primitive whose contract is
wire-safe output.

Run the fallback through the same cleaning, backed by a safe constant if even
that is empty, so the return is always wire-safe and never filename="". Adds a
test.
2026-07-07 22:47:15 -07:00
Patrick Buckley fd3aed1eca fix(web): make Content-Disposition filenames safe on the wire
Attachment `/content`, preview, and workstream-export downloads built the
Content-Disposition `filename="..."` value straight from a user-supplied
name, stripping only quotes and CR/LF. Three input classes still broke the
header:

- Non-latin-1 names (CJK, em dash): Starlette encodes header values as
  latin-1 and raised, 500-ing the serving route. (The original get_content
  bug.)
- ASCII control bytes (NUL, form-feed, VT, DEL): latin-1-encodable, so they
  passed Starlette, but the HTTP server layer rejects control characters in a
  header value and 500s one layer later.
- Backslash: the RFC 6266 quoted-pair escape. A trailing backslash escaped
  the closing quote and corrupted the download filename (not a 500, but wrong
  output; Windows-origin uploads carry it legitimately).

Extract one `latin1_safe_filename()` helper in web_helpers that drops every
non-printable character plus the double-quote and backslash quoted-string
metacharacters, folds any surviving non-latin-1 codepoint to '?', and falls
back to a non-empty name so the header never emits an empty filename. Route
get_content, preview_response_headers, and the export handler through it,
replacing three near-duplicate inline strips.

Adds unit tests for the helper (non-latin-1 fold, control-char and backslash
stripping, per-site fallback) and an endpoint regression test.
2026-07-07 22:47:15 -07:00
Patrick Buckley f56fa55929 fix(ui): unsplit skips redundant refresh after closing an ephemeral pane
unsplit() closed each doomed (ephemeral) pane via close() — which already
renders/persists/notifies — then repeated that trio, firing intermediate
persist/notify passes mid-operation. A 2-cell split fully collapses inside
close(), so bail there; only a 3+-cell split (or an empty doom list) still
needs the trailing exit + refresh. The all-conversation path is unchanged.

Also reword the cell-chip CSS comment so it names the reversible hide vs
destructive close glyphs, now that an ephemeral pane can show the close glyph
in split mode.
2026-07-07 22:07:20 -07:00
Patrick Buckley ace9e034f9 fix(ui): ephemeral panes close on split-dismiss instead of orphaning a tab
The preview pane opens beside the conversation as a split cell. Dismissing
that cell — the per-cell chip, or Unsplit from the other pane — ran
closeCell(), which hides the pane but keeps it in _panes/_order, leaving an
orphan tab with no meaningful reopen (the reopen affordance is the transcript
chip, not the tab bar).

Add an `ephemeral` flag on ShellPane. For an ephemeral pane the cell chip and
Unsplit route to close() — destroying the pane and its tab — and the chip's
glyph/label read as a destructive close rather than a reversible hide. Unsplit
still spares the focused survivor even when it is ephemeral ("keep the focused
pane"). The preview pane sets the flag; conversational panes do not, so an
all-conversation split is unchanged (Unsplit reduces to the prior
_exitLayout(_activeId)).
2026-07-07 22:07:20 -07:00
Patrick Buckley cb59afe443 fix(nudge): log refused wakes; correct the already-dispatched hold-clear comment
The wake gate documented exactly one info line per call past its
gates, but a send() refusal (the authoritative under-lock _closed
re-check catching a teardown the gate's lockless peek missed) emitted
nothing — a dropped wake should stay traceable to its trigger, so the
refusal now logs nudge_wake.refused.

The already-dispatched branch's comment claimed a held reminder can
coexist with the terminal mark via a redelivery whose commit raised —
impossible with the current control flow (_redeliver_pending clears
the hold before committing).  Reworded to what the clear actually is:
the last line of defense against any coexisting hold leaking forever
once this branch deactivates the row, since inactive rows never
re-list.  Test comment updated to match.
2026-07-07 16:42:36 -07:00
Patrick Buckley 7886d3b763 fix(nudge): wake gate requires a real NudgeQueue
A session whose _nudge_queue answers has_pending truthily while its
deliver_wake_nudge_from_queue consumes nothing turns the worker-exit
backstop into an infinite respawn loop: the gate passes, the wake
worker no-ops, the exit backstop re-runs the gate, forever.
Mock-backed test sessions riding real Workstreams are exactly that
shape, and one worker on such a pairing is enough to ignite a
wake-thread storm that trips the leaked-thread guard in every
subsequent test.  The wake contract requires real drain semantics —
the spawned worker must CONSUME what the gate saw — so the gate now
refuses on type, not just presence.
2026-07-07 16:42:36 -07:00
Patrick Buckley fa1ba2cc01 fix(api): type initial_message_status as a Literal enum
str | None under-specified the field: the implementation and the TS SDK
union both constrain it to queue_full / refused_closed, and the Literal
projects a proper enum into the generated OpenAPI spec so clients
reject unexpected values. Specs regenerated.
2026-07-07 16:42:36 -07:00
Patrick Buckley e60c19befd fix(watch): harden nudge/wake delivery across eviction, cancel, and identity rebinds
Wake path:
- Denial metacog nudge moves to the tool channel so it drains with the
  denied tool batch instead of the next user-message seam.
- wake_workstream_if_pending: shared wake gate for watch fires on
  already-idle workstreams (no IDLE transition for the watcher to
  observe), wired as wake_fn at every set_watch_runner site via the
  shared _watch_fire_wake_fn helper (closes over the Workstream OBJECT
  — after eviction+restore an id-keyed manager lookup would miss).
- session_worker exit backstop re-runs the wake gate the moment worker
  ownership clears: IDLE fans out on the worker thread, so
  transition-time wakes always landed on the reuse path and no-op'd
  (the coordinator idle_children strand).
- deliver_wake_nudge_from_queue contains GenerationCancelled — it is
  the wake worker's run() closure and only Exception is caught
  downstream.

Watch delivery:
- Terminal fires that cannot reach their workstream are HELD and
  redelivered on min(interval, 60s) without re-running the command,
  bounded by MAX_DELIVERY_ATTEMPTS per cycle and the watch's own
  max_polls across cycles; the poll charge commits durably at hold
  time so restarts stay budget-bounded.
- Restore admission control: per-ws dedup + MAX_CONCURRENT_RESTORES
  cap, presence-only re-check under the lock, detection-only stall
  alerts (reclaiming a wedged admission would trade capped degradation
  for total poll-pool collapse).
- Permanent-vs-transient restore taxonomy: corrupt persona stamp and
  genuinely-missing history (confirmed by a raising storage probe —
  the resume loader swallows read blips into []) deactivate the watch
  immediately; everything else holds and retries.
- Cancel-race defense: delivery paths re-check is_watch_active before
  stashing/dispatching, cancel paths write the row BEFORE
  forget_terminal_dispatched, the HTTP cancel endpoint clears runner
  state, and a per-tick sweep bounds the residual stash-after-clear
  interleaving to one check_interval.
- Abandon/exhaustion commits are write-then-clear so storage that can
  read but not write retries the row write instead of re-running the
  command every cycle; the fresh-fire unrestorable path stashes before
  its deactivation write for the same reason.

Registry follows identity:
- The dispatch registry is keyed by _ws_id at registration time; every
  rebind now moves it: non-fork resume() and /new go through
  _follow_watch_registration (new key live before the old is removed,
  never stealing a registration another live session holds), removals
  are owner-checked so tearing down a watch-restore shell or a
  resumed-away session cannot unregister a live pane, the restore
  shell yields to a registration that appears mid-restore, CLI
  --resume registers after the successful resume, and both the open
  path and the detail-GET lazy rehydrate wire the registration.

Teardown gating and backpressure honesty:
- cleanup_session_ui marks ws._closed FIRST under ws._lock — every
  teardown path (close, close_idle, evict, delete, discard) funnels
  through it — and session_worker.send re-checks under the same lock,
  so a wake can never spawn a worker on a torn-down workstream.
- Create responses carry initial_message_status when the initial
  message could not be delivered (queue_full / refused_closed) instead
  of reading as success; staged attachments survive for the retry;
  /send surfaces a closed workstream as 404 rather than queue_full.

Docs/spec: OpenAPI artifacts regenerated; api-reference documents the
new create-response field; TS SDK type extended.

Tests: ~30 new pins (cancel races, budget durability across restarts,
owner-checked registry moves, teardown gating, stall alerts,
backpressure surfaces, wait_until final re-check); wide subsystem
sweep green (2353 passed).
2026-07-07 16:42:36 -07:00
Patrick Buckley bbe92faca1 fix(preview): fetch ceiling tracks the widest kind cap, not a flat 10 MB
Review feedback (PR #800): the URL lane hard-capped fetched bodies at
10 MB before kind resolution, making the 32 MiB pdf cap unreachable for
URL targets while path targets honored it. The flat pre-check is gone;
the guarded fetch's max_bytes now tracks max(PREVIEW_SIZE_CAPS.values())
- mirroring the path lane's stat pre-check - and the per-kind caps after
resolution stay authoritative.

Also drops a redundant function-local asyncio import in test_console.py.
2026-07-07 08:20:57 -07:00
Patrick Buckley 29a4bbf876 fix(preview,web): stream guarded fetches under a byte budget; salt preview blob ids
fetch_with_ssrf_guard now streams the response under a max_bytes budget
(default 32 MiB, counted on decoded bytes so gzip cannot expand past it)
instead of buffering blind - an unbounded body previously filled memory
before any caller-side size cap could run. Redirect-hop bodies are no
longer read at all, and the realized response drops stale wire-framing
headers (content-encoding/content-length/transfer-encoding) that no
longer describe the decoded content it carries.

Preview blob ids are salted out of the model-visible attachment
namespace (sha256("preview:" + body)): uploads use bare sha256(body)
and save_attachment freezes kind at first insert, so a byte-identical
preview/upload pair would otherwise share a row - whichever landed
second inherited the other's kind, silently hiding an upload from model
context or materializing preview bytes into a tool turn.
2026-07-07 08:20:57 -07:00
Patrick Buckley 09abc9d199 feat(tools): allow_private_network opt-in for private-address fetch/preview
turnstone's primary audience self-hosts it beside other lab services —
a web_fetch or open_preview aimed at Grafana, Home Assistant, or a dev
node on the local network is the operator using their own network, not
an attack. The hard SSRF refusal made those targets unreachable.

New runtime setting tools.allow_private_network (settings registry,
default off, rendered in console Settings → Tools; hot — read per tool
call, no restart). When enabled, a call NAMING a private address
becomes approvable: the approval prompt tags it "(private network)" so
the operator approves it as what it is, and the human gate stays.

The redirect side-door stays closed either way: a PUBLIC target that
302s into private address space is refused regardless of the opt-in —
that address never appeared on the approval card, so it is never
fetched. Only a chain whose approved origin was itself private skips
hop screening (its redirects are the operator's own network).

Refusals now teach the knob (mirrors the oidc opt-in hint): the error
names tools.allow_private_network and where to enable it. Surfaces
without a ConfigStore (bare CLI, eval) stay strict — there is no admin
surface to have opted in on.
2026-07-07 08:20:57 -07:00
Patrick Buckley 1e2ab91ec2 feat(preview): probe preflight, legacy charsets, remote-assets opt-in, md vendor parity
Four follow-ups to the preview pane:

- Probe-mode preflight: the pane preflights src-loaded kinds with
  GET ?probe=1 (204, real hardening headers, no body) instead of HEAD —
  the console reverse proxy forwards HEAD as a full GET, so the old
  preflight dragged the whole blob across the node→console hop twice.
  Ownership gate + renderable-type check still run on probes.
- Legacy-charset text: table/text/markdown now transcode to UTF-8 at
  store time (declared charset → UTF-8 → cp1252-replace ladder), same
  model the web kind already used. The ladder applies only when the
  text kind was DECLARED (MIME/extension/override); the bare no-hint
  fallback stays strict UTF-8 and NUL bytes still hard-reject, so
  binary rejection is unchanged.
- Remote assets default OFF: previewed pages are now served under
  "sandbox; default-src 'none'; style-src 'unsafe-inline'; img-src
  data:; font-src data:" — they render with inline styling but cannot
  contact their origin site (no viewer IP/traffic disclosure). A
  per-pane "Load remote images & styles" checkbox (web previews only,
  sticky, not persisted) reloads with ?assets=1 for the permissive
  bare-sandbox mode.
- Markdown vendor parity: preview markdown now runs renderer.js's
  postRenderMarkdown (hljs token coloring + lazy mermaid diagrams)
  like the conversation pane, with preview-scoped code-block/KaTeX
  chrome (the conversation theme is .msg.assistant-scoped).

Tests: probe/assets HTTP + policy coverage, charset ladder units +
stored-bytes round-trip, JS static guards for the probe form, the
default-off toggle, and the post-pass; headless-chrome harness grew to
41 assertions (probe-not-HEAD, toggle visibility/default, fenced-code
render). Full suite green.
2026-07-07 08:20:57 -07:00
Patrick Buckley e010124008 feat(preview): rich preview pane + open_preview tool
Tool results only ever rendered as plain text in the transcript. This
adds the model-driven rich-preview lane every comparable surface has,
in turnstone's developer-tool idiom: a preview pane that opens BESIDE
the conversation, keyboard-operable, sandboxed, never replacing the
transcript that spawned it.

Backend
- New built-in open_preview(target, kind?, title?): resolves an http(s)
  URL, a file path, or attachment:<id> to bytes; classifies into
  web/pdf/image/table/text/markdown (magic bytes > MIME hint >
  extension > UTF-8 fallback, legacy-charset pages transcoded); caps
  size per kind; persists content-addressed with kind="preview" —
  refcounted and GC'd with the workstream, skipped by trajectory
  reconstruction so preview bytes can never materialize onto the wire.
  URL targets gate like web_fetch (network egress); paths/attachments
  run unprompted like read_file.
- New core.web.fetch_with_ssrf_guard: manual redirect walk that
  SSRF-screens every hop BEFORE requesting it (follow_redirects=True
  checked nothing between hops); adopted by both open_preview and
  web_fetch. URL userinfo is stripped before the descriptor or the
  stored bytes see it; <base href> is injected doctype-safely so
  relative assets resolve without quirks mode.
- The preview descriptor rides the tool turn's meta side channel with
  ONE shape on every boundary: the live tool_result SSE event, the
  conversations.meta column, and the /history projection. Cancelled
  batches commit an already-announced preview (blob + meta) instead of
  stranding the open pane on a permanent 404.
- New GET {ws}/attachments/{id}/preview (read scope, same ownership
  gate as /content) serves the STORED type with per-MIME hardening:
  bare CSP sandbox for text/html (renderable, scriptless, opaque
  origin), no CSP for application/pdf (Chromium's viewer refuses
  sandboxed contexts), full default-src 'none' otherwise; filenames
  fold to latin-1-safe ASCII. The console /node proxy now forwards
  CSP/nosniff/disposition/cache-control instead of dropping them.
- History loads exclude preview blobs from the bulk content fetch at
  the query (they were read and discarded on every load).

Frontend
- New "preview" pane type registered in the shared shell (server +
  console): openPaneBeside placement, per-kind renderers — fully
  sandboxed iframe for pages, browser PDF viewer, sortable tables
  (CSV/TSV/JSON, ragged-file safe, 5k-row cap), rendered markdown,
  text — plus back/forward history with arrow keys, reload persistence
  via pane meta, and backoff auto-retry (0.9s..7.2s) bridging the gap
  between the live descriptor and the batch fold that commits its blob.
- Tool results carrying a descriptor render a credential-redacted
  preview chip (the reopen + replay affordance); live results auto-open
  the pane only while the originating pane holds focus.

Docs: docs/tools.md + prompts/tools.md. Tests: policy unit tests, tool
prepare/exec (mocked fetch), serving route + proxy header pass-through,
storage exclusion on both backends, cancel-path commit, JS static
guards; a headless-Chrome harness drives the real module graph (32 DOM
assertions).
2026-07-07 08:20:57 -07:00
Patrick Buckley 4350248d8f fix(oidc): carry the opt-in hint on discovered-endpoint rejections
The discovered-endpoint wrapper converted every OAuthSSRFError to a
bare OIDCError, so a private-resolving endpoint or trusted host got the
non-public message without the allow_private_network remediation even
though the same knob fixes it. Hoist the hint into a module constant
and append it in both wrappers.

Also name "unspecified" in the refused-even-with-opt-in message so
0.0.0.0/:: rejections read unambiguously.
2026-07-06 21:52:42 -07:00
Patrick Buckley 9c74673fd4 feat(oidc): allow_private_network opt-in for self-hosted IdPs
The SSRF guard on OIDC endpoint URLs hard-refused any hostname
resolving to a non-public address, which made it impossible to use a
self-hosted IdP (Keycloak, Authentik, Dex) on an internal network —
even though the login-flow issuer is operator-configured, i.e. trusted
input.

Add [oidc] allow_private_network in config.toml (or
TURNSTONE_OIDC_ALLOW_PRIVATE_NETWORK), default off. When set, the
issuer and its discovered endpoints may resolve to private-range,
unique-local, CGNAT, and loopback addresses. Link-local, multicast,
unspecified, and reserved ranges stay refused regardless — cloud
metadata services live on link-local and no legitimate IdP does. The
HTTPS requirement and same-origin endpoint checks are unchanged.

The private-address refusal now raises OAuthSSRFPrivateAddressError,
and the OIDC wrapper appends the remediation hint to the error message
so the failure is self-service. mcp_oauth call sites — where endpoint
URLs come from untrusted remote-server metadata — do not get the knob
and keep the strict public-address rule.
2026-07-06 21:52:42 -07:00
Patrick Buckley 19b1a04f17 fix(redaction): match connection-string schemes case-insensitively
RFC 3986 schemes are case-insensitive, so POSTGRESQL+PSYCOPG2:// or
HTTPS://user:pass@host in tool output leaked the password past the
case-sensitive scheme alternation. Compile with IGNORECASE on both
sides of the FE/backend mirror; the structural userinfo requirement
is unchanged. Uppercase-scheme cases added to both test suites.
2026-07-06 21:42:51 -07:00
Patrick Buckley ed2623ff44 fix(redaction): match SQLAlchemy driver schemes; add FE prefilter bailout
Connection-string redaction (the output_guard pattern and its frontend
mirror) only enumerated bare dialects plus +psycopg, so SQLAlchemy
dialect+driver URLs — postgresql+psycopg2://, postgresql+asyncpg://,
mysql+pymysql:// — leaked the password through every redaction surface.
The scheme now takes an optional +suffix instead of enumerating drivers.

redactCredentials() also gains a single early-exit prefilter scan ahead
of its sixteen replace passes, for plain-log tool output on card render.
The prefilter is documented and pinned as a superset of the pattern
set's required substrings, so a miss is provably a no-op: new smoke
cases assert bare sk-/AKIA/Bearer credentials with no '=', quote or '@'
anywhere in the text still redact, alongside the fast-path no-op and
the driver-scheme URLs on both sides of the mirror.
2026-07-06 21:42:51 -07:00
Patrick Buckley 625218b7b5 docs: price the learned veto's influence channels in HYPOTHESIS.md
- Proven: name supervisory control's controllability and nonblocking
  conditions as the ancestors of gate-early-on-irreversibles and the
  always-enabled escalation required behind a learned veto; cite TCSEC
  covert-channel analysis (NCSC-TG-030) for the verdict channel.
- Asserted: add the narrow-only rule's influence-side twin (verdict
  payloads to the plant selected, never generated).
- New caveat paragraph: a denial is free only in the authority lattice;
  in the dynamics it is an input (selection + targeted-liveness
  channels), so a learned veto needs a nonblocking escape it cannot
  disable, verdict payloads are selected rather than generated with the
  symbols/tokens/language thresholds bounding the alphabet, and the
  strongest form dissolves the verdict into scheduling over
  deterministic checks.
2026-07-06 21:15:04 -07:00
Patrick Buckley a029849724 fix(models): keep raw exception text out of client-construction 503s
Review: the wrapped ValueError is echoed in 503 bodies, and arbitrary
SDK exception text can embed filesystem paths. Echo the exception type
only; log the full exception with traceback at the raise site.
2026-07-06 21:10:27 -07:00
Patrick Buckley 9c2e809b26 fix(models): surface client-construction failures as factory misconfig
SDK client construction can fail on environment problems the config
never sees (e.g. httpx resolving a certifi CA path deleted by a venv
rebuild). Those escaped as bare exceptions and turned every workstream
open/create into an opaque 500; re-type them as ValueError in
ModelRegistry.get_client so routes answer 503 with the message and the
alias.
2026-07-06 21:10:27 -07:00
Patrick Buckley 51ed336989 fix(storage): survive oversized rows in postgres history search
to_tsvector was computed inline over full row content, so one row
whose tsvector exceeds PostgreSQL's 1MB limit aborted every
search_history scan. Cap the FTS input at 250K chars (worst-case
tsvector expansion stays under the limit; giant rows remain findable
by their head). The ILIKE fallback also never ran on postgres: the
failed statement leaves the autobegun transaction aborted, so roll it
back before falling back.
2026-07-06 21:10:27 -07:00
Patrick Buckley 90663ce695 fix(core): defer tool deepcopy until a description actually changes
Address review on #794. The prior gate deepcopied every agent tool, then compared, then discarded the copy on a no-op render; and its comment framed the equality case as 'no personas' when it also covers an idempotent re-render of unchanged aliases/personas. Compute the target model/persona descriptions from the current (read-only) schema first and only deepcopy when one differs — so a no-op render is genuinely allocation-free, not just fork-free. Behaviour is unchanged: identity preserved when nothing differs, stale text still cleared on reload.
2026-07-06 21:00:21 -07:00
Patrick Buckley bd37bcd1ec fix(core): keep agent-tool render idempotent so no-persona sessions share the tool constant
_render_agent_tool_descriptions rebuilt self._tools and reassigned it on every session init, deep-copying task_agent even with no model aliases and no personas to inject — the single-model CLI case the docstring says is skipped. This regressed after the persona-discoverability change removed the early 'if self._registry is None: return' guard, breaking the session._tools is INTERACTIVE_TOOLS invariant (test_session_without_mcp).

Gate the reassignment on whether a description actually changed: keep the original tool object when the render is a no-op, fork self._tools only when something was injected. Restores the shared-constant invariant, makes repeated renders idempotent, and preserves clear-stale-on-reload (an emptied registry still takes the changed path).
2026-07-06 21:00:21 -07:00
Patrick Buckley a61d454df5 docs: add funding button (GitHub Sponsors + PayPal)
Add .github/FUNDING.yml to enable the native GitHub Sponsor button, plus a Sponsor badge and a Support section in the README. Primary CTA is GitHub Sponsors (eous); PayPal (paypal.me/eousphoros) is offered as a one-off fallback.
2026-07-06 20:28:52 -07:00
Patrick Buckley 647939fe4d fix(personas): repr the input in the not-found resolver error
Review feedback on #792: the "not found or disabled" branch
interpolated the raw input unquoted, so the whitespace-only and
trailing-space inputs the forgiving lookup explicitly handles rendered
invisibly in CLI output and logs. Use {name!r} like the other two
resolver errors already do.
2026-07-06 19:58:36 -07:00
Patrick Buckley 457b01737a feat(personas): agent discoverability + forgiving name resolution
Coordinators and interactive agents had no way to enumerate valid
persona names: task_agent / spawn_workstream / spawn_batch described
`persona=` but nothing listed what it accepts, and resolution was an
exact case-sensitive slug match - users reaching for the display name
or a case variant got an unexplained failure.

- Inject the live persona catalog (enabled, interactive-kind; children
  and sub-agents are always interactive) into the `persona` parameter
  description of task_agent / spawn_workstream / spawn_batch, riding
  the same render path as the model-alias injection. Rebuilt from the
  pristine TOOLS base every render, so repeated renders are idempotent
  and archived personas drop out instead of lingering. Entries carry
  name + default marker + <=96-char description; names-only past 25
  personas. spawn_batch's persona property is nested per-child under
  children.items.properties (located via _persona_property, null-safe
  against name-colliding MCP tools). Storage-less sessions keep the
  base text: the render runs at session construction, so it gates on
  is_storage_initialized() rather than get_storage(), which would
  auto-init SQLite as a side effect.

- resolve_persona_for_kind - the ONE shared rule behind the HTTP
  create handler, CLI --persona, the coordinator spawn precheck, and
  task_agent prep - is now forgiving: exact slug, then the lowercased
  input (created names are regex-enforced lowercase slugs), then a
  case-insensitive display-name match accepted only when unique among
  the kind's enabled personas. Duplicates refuse loudly naming the
  candidate slugs; a same-label persona of another kind neither blocks
  nor wins (the label the caller saw came from a kind-filtered
  surface); whitespace-only input never matches blank display names
  (display_name defaults to ""). Every failure now enumerates the
  kind's valid names, so a stale injected list or a typo self-corrects
  on the next attempt.

- The canonical slug is stamped everywhere: task_agent prep rewrites
  its arg from the resolved snapshot, _validate_child_persona returns
  (canonical, error) and both spawn call sites adopt it - approval
  chrome, the wire, and workstream_config never carry a forgiven
  variant.

- Create-persona shelf: label hint under Name explaining agents and
  the CLI launch the persona by this name (case-insensitive) and the
  display name is only a list label. docs/personas.md gains a "How
  agents discover personas" section and drops the stale claim that
  task_agent has no persona parameter.

Tests: resolver unit suite (case/display/ambiguity/cross-kind/
whitespace/disabled/storage-failure) + guards for injection content
and ordering, idempotent re-render, archive drop, the 25-persona
prose cutoff, coordinator-kind exclusion, and canonical stamping
through spawn_workstream / spawn_batch / task_agent.
2026-07-06 19:58:36 -07:00
Patrick Buckley a40ff249ec fix: address review — request-scoped storage in coord tenancy checks
- _coordinator_tenant_check and _coord_attachment_owner resolved storage from
  the global registry (get_workstream_row / for_request without a storage arg),
  which can evaluate the project-tenancy decision against a different or
  auto-initialised backend and fail OPEN on a missing project row. Use
  request.app.state.auth_storage explicitly, matching cluster_ws_detail and
  _resolve_coordinator_or_404; fail closed (404) when it is unset.
- reject_unassignable_scopes now derives its allowed-scope error message from
  ASSIGNABLE_SCOPES so validation and the message can't drift.
2026-07-06 19:16:09 -07:00
Patrick Buckley 36419a9809 fix: scope private-project workstream visibility to members, not admins
Workstreams attached to a private project were visible -- including their
conversation content -- to holders of admin.cluster.inspect / admin.coordinator
(both default builtin-admin permissions), defeating the project's confidentiality
boundary. Enforce that a private project's resources are visible only to people
IN the project (owner, workstream creator, or an explicit member), even for admins.

Surfaces closed:

- WorkstreamProjectVisibility bypass narrowed to service scope only (node->console
  machine plumbing, re-filtered per-user at the console edge). No human principal
  bypasses; admin.cluster.inspect gates the inspect surfaces, not tenancy. This
  flows to /dashboard, session listings, the attachment row-gate, cluster_workstreams,
  cluster_node_detail, and cluster_snapshot/SSE.
- cluster_ws_detail 404-masks a workstream in a private project the caller can't
  see; cluster_ws_live_bulk routes such ids to the denied list (no private-project
  oracle).
- Coordinator operator verbs (history/export/detail/send/approve/set_title/open/
  children/tasks/attachments) now enforce project tenancy: _coordinator_tenant_check
  on coord_endpoint_config, the gate in _resolve_coordinator_or_404 (children/tasks),
  the tenant_check now run in make_open_handler before rehydrate, and a
  project-visibility check in _coord_attachment_owner. admin.coordinator gates the
  surface cluster-wide, but a non-member is 404-masked. The tenant-check mirrors the
  manager-first + coordinator-kind ladder so kind-isolation is preserved.
- service scope is no longer user-assignable: admin_create_token and both
  turnstone-admin CLI mint paths reject it via reject_unassignable_scopes, so an
  admin.users holder cannot self-mint a service token and restore the bypass. Service
  scope is minted only by ServiceTokenManager / the JWT secret.
- The events/global node proxy (service-elevated cross-tenant firehose) is gated on
  admin.cluster.inspect so a plain authenticated user cannot reach it through the
  console proxy.

Updates the OpenAPI description, the row-gate/tenancy-filter docstrings, and adds
tests for every surface (visibility predicate + cluster detail/bulk + coordinator
history/export/children/open/attachments + events/global proxy + scope-mint
rejection); inverts the tests that pinned the old admin-bypass contract.
2026-07-06 19:16:09 -07:00
Patrick Buckley 0c2c534c86 fix(mcp): route pool transport lifecycles through per-entry owner tasks (#788)
* fix(mcp): route static transport lifecycles through per-server owner tasks

A crash-looping MCP server drove the mcp-loop thread to a sustained,
climbing 100%+ CPU spin. Root cause: anyio cancel scopes are
host-task-bound, and the static path entered the SDK's transport /
ClientSession task-group scopes from short-lived connect tasks (every
health tick is a new task since #768). Once such a scope was cancelled
after its host task had finished - by anyio's task_done when a
transport child died with the server, or by ClientSession.__aexit__
during a cross-task teardown - CancelScope._deliver_cancellation could
never make progress (task.cancel() on a done task is a no-op) and
re-armed itself via call_soon every loop iteration, forever: ~900k
callbacks/s per zombie scope, one more per flap cycle (verified against
anyio 4.14.1; no upstream fix exists as of that release).

Fix: each static server's transport + session cms are now entered,
parked, and exited by ONE long-lived owner task
(_static_transport_owner), so scopes always have a live host and always
exit in the task that entered them. Teardown follows a one-cancel close
protocol (signal the close event before the first await, graceful
grace, then at most ONE cancel - never a second, which would abandon a
scope exit mid-flight). Connect timeouts now cancel only the waiting
caller; connect failures are delivered through a readiness future;
unrequested owner death (server died under a live session) evicts the
session immediately via a done-callback instead of waiting for the next
liveness ping. A rate-limited, mcp-loop-scoped gc-walk backstop
(_maybe_disarm_orphaned_scopes) disarms any zombie minted by paths not
yet migrated (the oauth_user pool keeps the old cross-task-close shape;
follow-up).

Also fixed: BaseExceptionGroup (BaseException-derived, as raised by
anyio task groups wrapping a stray CancelledError, e.g. an
accept-then-RST server) escaped `except Exception` in _connect_all and
killed it before the health/sweep loops were created - silently
disabling all autonomous recovery. Handled there and in the
health/sweep/eviction loops and the reconnect/refresh callers.

Verified: a live SIGKILL-flap repro went from 130%+ CPU (climbing, one
armed scope per cycle) to 0.3% flat with zero armed scopes; the RST
repro now leaves both background loops alive (previously both silently
dead). New tests: owner-lifecycle + close-protocol units (incl. an
exactly-one-cancel pin), a _connect_all BaseExceptionGroup regression,
a discriminating disarm-sweep test, and a ~10s live SIGKILL-flap smoke
test (real FastMCP subprocess, skips on environment gaps) asserting
zero armed scopes, exactly one live owner, and a post-recovery tool
call. Full 8470-test suite green; ruff+mypy clean.

* fix(mcp): route pool transport lifecycles through per-entry owner tasks

Completes the owner-task migration started for the static path: the
oauth_user pool path had the same latent anyio cancel-scope exposure
(host-task-bound scopes entered by short-lived connect tasks; a scope
cancelled after its host finished re-delivers cancellation via
call_soon forever - the 100%-CPU zombie), previously covered only by
the disarm backstop.

Each (user, server) pool entry's transport + ClientSession cms are now
entered, parked, and exited by ONE long-lived owner task
(_pool_transport_owner). The caller keeps building client_kwargs (the
per-user bearer and, when an auth-capture carrier is active, the
httpx_client_factory response hook) so 401/WWW-Authenticate capture
semantics are unchanged. Teardown is the shared one-cancel close
protocol (_teardown_pool_entry: signal before first await, graceful
grace, at most ONE cancel), used by the connect stale-guard, idle/LRU
eviction, and shutdown (parallel signal-then-reap). Unrequested owner
death evicts the session but keeps the entry and its discovered
catalog, matching the existing evict-session-keep-entry semantics the
auth_401 retry relies on.

Discovery still runs in the connecting caller while the transport is
hosted by the owner, so a transport collapse mid-discovery (e.g. the
SDK tearing its task group down on an upstream 401) cancels the OWNER,
not the caller - a bare await on the response stream would hang until
the 30s phase timeout. _await_pool_discovery races each discovery
await against owner completion and converts owner death into a prompt
ConnectionError (the owner is never cancelled there; teardown owns its
lifecycle). Carrier-first failure classification preserves auth_401
semantics for captured 401s.

With no cross-task stack closes left, _safe_close_stack and
_safe_teardown_on_connect_failure are deleted (zero callers).

Tests: new tests/test_mcp_pool_owner.py pins the pool close protocol
(graceful event-before-await close, exactly-one-cancel escalation,
owner-death eviction retaining entry+catalog, caller-cancel-mid-connect
cm-exit guarantee, factory-present-iff-capture, and the
owner-death-during-discovery fast-fail). 1010 mcp tests and the full
8471-test suite green, including the historical cross-task-anyio
sentinel test_integration_pool_reuse_401_refresh_and_retry_succeeds;
ruff+mypy clean; zero destroyed-task warnings.

* fix(mcp): harden disarm-sweep loop guard and owner BaseException arm

Review follow-ups on the owner-task migration:

- _maybe_disarm_orphaned_scopes now enforces its mcp-loop requirement
  instead of trusting callers: it returns without walking (and without
  advancing the rate-limit clock) unless the currently running loop IS
  self._loop. A suppressed close can fire before start() or after
  shutdown(), where the walk would be wasted at best and a cross-thread
  reach at worst.

- The transport owner's BaseException arm now re-raises non-Exception,
  non-group escapees (KeyboardInterrupt, SystemExit) after delivering
  them to the readiness future - failure delivery is the arm's job;
  swallowing an interpreter-level exit was not.

* fix(mcp): extend owner-death discovery fast-fail to the static path

The static connect path had the same exposure the pool's discovery race
closed: discovery runs in the connecting caller while the transport is
hosted by the owner task, so a transport collapse mid-discovery cancels
the OWNER and the caller's bare await on the response stream hung until
the caller-side attempt timeout (~45s) instead of failing promptly.

_await_pool_discovery is renamed to _await_owner_discovery (it is now
path-neutral) and wired into _connect_one_locked's four discovery
awaits. The helper also converts a discovery future that completes
CANCELLED without the race's own reap (an SDK-internal cancellation
shape) into the same ConnectionError, instead of leaking a bare
CancelledError the caller would misread as its own cancellation.

The pool transport owner's BaseException arm gains the same refinement
the static owner received in review: interpreter-level exits
(KeyboardInterrupt, SystemExit) re-raise after delivery to the
readiness future instead of being swallowed.

Tests: static owner-death-during-discovery fast-fail (<1s vs the ~45s
hang), and a direct pin on the cancelled-discovery-future conversion.

* fix(mcp): replace owner BaseException arm with targeted catch + finally delivery

The owner's failure arm now catches only (BaseExceptionGroup, Exception);
waiter delivery for everything else moves to a finally that resolves the
readiness future with a clean transport-failure ConnectionError before
the task unwinds. Interpreter exits and BaseException-derived library
control-flow escapes propagate from the owner exactly once, uncaught -
and the waiter can never be left hanging on an unresolved future (the
initial _connect_all connect has no outer bound). For SystemExit /
KeyboardInterrupt asyncio additionally stops the loop right after, so
the delivery is load-bearing for the non-exit BaseException shapes and
free for the exits.

Pinned by a test driving a BaseException-derived escape through the
owner: the waiter resolves promptly with ConnectionError while the
escape propagates unswallowed.

* fix(mcp): mirror targeted-catch + finally delivery in the pool owner

Same shape the static owner received in review: the failure arm catches
only (BaseExceptionGroup, Exception), and waiter delivery for anything
else moves to a finally that resolves the readiness future with a clean
ConnectionError before the task unwinds - interpreter exits and
BaseException-derived library escapes propagate exactly once, uncaught,
and the waiter can never be left hanging.

* test(mcp): narrow the escape test's waiter catch to explicit types

* test(mcp): narrow discovery-race waiter catches to explicit types

* refactor(mcp): make reap/synchronization awaits explicit to analyzers

Full-absorb reaps (cancel-then-drain of a future whose outcome is
deliberately consumed) become `await asyncio.gather(x,
return_exceptions=True)` - one line, self-describing, and in the
owner-died discovery reap it is also a small semantic improvement: a
caller cancellation arriving during the reap now propagates instead of
being masked by the ConnectionError. Bare synchronization awaits and
selective suppress blocks in tests keep their raise-through semantics
via throwaway assignment. Applied uniformly across the owner-task
test files, including sites introduced by the static-path PR.
2026-07-06 18:46:28 -07:00
renovate[bot] 5fded65b82 chore(deps): lock file maintenance 2026-07-06 18:20:14 -07:00
Patrick Buckley 7da731cbe1 test(mcp): narrow the escape test's waiter catch to explicit types 2026-07-06 18:19:17 -07:00
Patrick Buckley 8ed86ae7ab fix(mcp): replace owner BaseException arm with targeted catch + finally delivery
The owner's failure arm now catches only (BaseExceptionGroup, Exception);
waiter delivery for everything else moves to a finally that resolves the
readiness future with a clean transport-failure ConnectionError before
the task unwinds. Interpreter exits and BaseException-derived library
control-flow escapes propagate from the owner exactly once, uncaught -
and the waiter can never be left hanging on an unresolved future (the
initial _connect_all connect has no outer bound). For SystemExit /
KeyboardInterrupt asyncio additionally stops the loop right after, so
the delivery is load-bearing for the non-exit BaseException shapes and
free for the exits.

Pinned by a test driving a BaseException-derived escape through the
owner: the waiter resolves promptly with ConnectionError while the
escape propagates unswallowed.
2026-07-06 18:19:17 -07:00
Patrick Buckley ed30e4f0bf fix(mcp): harden disarm-sweep loop guard and owner BaseException arm
Review follow-ups on the owner-task migration:

- _maybe_disarm_orphaned_scopes now enforces its mcp-loop requirement
  instead of trusting callers: it returns without walking (and without
  advancing the rate-limit clock) unless the currently running loop IS
  self._loop. A suppressed close can fire before start() or after
  shutdown(), where the walk would be wasted at best and a cross-thread
  reach at worst.

- The transport owner's BaseException arm now re-raises non-Exception,
  non-group escapees (KeyboardInterrupt, SystemExit) after delivering
  them to the readiness future - failure delivery is the arm's job;
  swallowing an interpreter-level exit was not.
2026-07-06 18:19:17 -07:00
Patrick Buckley 62f62ae624 fix(mcp): route static transport lifecycles through per-server owner tasks
A crash-looping MCP server drove the mcp-loop thread to a sustained,
climbing 100%+ CPU spin. Root cause: anyio cancel scopes are
host-task-bound, and the static path entered the SDK's transport /
ClientSession task-group scopes from short-lived connect tasks (every
health tick is a new task since #768). Once such a scope was cancelled
after its host task had finished - by anyio's task_done when a
transport child died with the server, or by ClientSession.__aexit__
during a cross-task teardown - CancelScope._deliver_cancellation could
never make progress (task.cancel() on a done task is a no-op) and
re-armed itself via call_soon every loop iteration, forever: ~900k
callbacks/s per zombie scope, one more per flap cycle (verified against
anyio 4.14.1; no upstream fix exists as of that release).

Fix: each static server's transport + session cms are now entered,
parked, and exited by ONE long-lived owner task
(_static_transport_owner), so scopes always have a live host and always
exit in the task that entered them. Teardown follows a one-cancel close
protocol (signal the close event before the first await, graceful
grace, then at most ONE cancel - never a second, which would abandon a
scope exit mid-flight). Connect timeouts now cancel only the waiting
caller; connect failures are delivered through a readiness future;
unrequested owner death (server died under a live session) evicts the
session immediately via a done-callback instead of waiting for the next
liveness ping. A rate-limited, mcp-loop-scoped gc-walk backstop
(_maybe_disarm_orphaned_scopes) disarms any zombie minted by paths not
yet migrated (the oauth_user pool keeps the old cross-task-close shape;
follow-up).

Also fixed: BaseExceptionGroup (BaseException-derived, as raised by
anyio task groups wrapping a stray CancelledError, e.g. an
accept-then-RST server) escaped `except Exception` in _connect_all and
killed it before the health/sweep loops were created - silently
disabling all autonomous recovery. Handled there and in the
health/sweep/eviction loops and the reconnect/refresh callers.

Verified: a live SIGKILL-flap repro went from 130%+ CPU (climbing, one
armed scope per cycle) to 0.3% flat with zero armed scopes; the RST
repro now leaves both background loops alive (previously both silently
dead). New tests: owner-lifecycle + close-protocol units (incl. an
exactly-one-cancel pin), a _connect_all BaseExceptionGroup regression,
a discriminating disarm-sweep test, and a ~10s live SIGKILL-flap smoke
test (real FastMCP subprocess, skips on environment gaps) asserting
zero armed scopes, exactly one live owner, and a post-recovery tool
call. Full 8470-test suite green; ruff+mypy clean.
2026-07-06 18:19:17 -07:00
renovate[bot] 5ae6c2316f chore(deps): update ghcr.io/astral-sh/uv docker tag to v0.11.27 2026-07-06 18:03:22 -07:00
renovate[bot] d793adb24c chore(deps): update anthropics/claude-code-action digest to f87768c 2026-07-06 18:02:58 -07:00
renovate[bot] 3cf94dd80f chore(deps): lock file maintenance 2026-07-06 03:09:51 -07:00
renovate[bot] 0422f9214a chore(deps): update github actions 2026-07-06 03:09:35 -07:00
Patrick Buckley 4428e185e5 switch qwen to nvidia/Qwen3.6-27B-NVFP4 with MTP 2-token spec-decode
- Model: nvidia/Qwen3.6-27B-NVFP4 (FP4 4-bit, ~13.5 GiB weights)
- MTP speculative decoding: method=mtp, num_speculative_tokens=2
- runai_streamer for ~26x faster weight loading
- max-num-seqs bumped from 2 to 8 for throughput under concurrent load
- Added compile cache volume mounts (triton, torch inductor, flashinfer)
- Updated ROCm guidance to recommend Qwen/Qwen3.6-27B-FP8
- Removed --kv-cache-dtype fp8 (default fp16 is fine at 0.50 util)
2026-07-05 17:13:08 -07:00
Patrick Buckley c5ff3147ce fix: cover secret_access_key/aws_secret_access_key multi-segment key patterns
The bounded key prefix pattern (api_key=/secret_key= etc.) avoids
monkey/turkey false positives, but compound keys like secret_access_key
and aws_secret_access_key only matched on the access_key= suffix, leaking
the secret_ / aws_secret_ prefix. Added these as explicit alternations.

Also added bearer_token and secret_token to the token prefix list.
2026-07-05 16:09:07 -07:00
Patrick Buckley bfcfb0c791 fix: restore bare token=/key= matching with negative lookbehind to avoid monkey FP
Bare alternatives (|token, |key) for standalone token= and key= assignments
were re-added.  A negative lookbehind (?<![a-zA-Z0-9_]) prevents matching
word-suffixed identifiers like monkey=, turkey=, mytoken=, over_tokenized=.
Also applied the same protection to _RE_QUERY_CRED which had a bare |token
alternative without boundary protection.
2026-07-05 16:09:07 -07:00
Patrick Buckley cbf5c5f3b6 Fix false positives and perf issue in credential redaction
- Replace unbounded [a-zA-Z0-9_]*key= prefix with specific credential
  key suffix alternation to avoid false matches on monkey=, turkey=, etc.
  Same for *token= (access_token=/auth_token= but not over_tokenized=).
- Hoist redactCredentials() out of per-line diff render loop in
  buildConvCmd - 1 call on full text instead of N calls per line,
  eliminating ~2800 regex passes worst-case.
- Remove bare 'key' from _RE_QUERY_CRED alternation (too aggressive).
- Add x-api-key / x_api_key to JSON secret key lists in both Python
  and JS.
- Add re.IGNORECASE to configurable-mode credential_bearer pattern.
- Fix annotation dedup guard in _check_credentials (was checking flag
  name against annotation prose list, always-true dead code).
2026-07-05 16:09:07 -07:00
Patrick Buckley 31a1d5c3ee fix(redact): harden credential redaction and restore JS/backend parity
Address review findings on the client-side credential redactor and mirror
each fix into the backend output guard so both surfaces censor identically:

- Detect and redact single-quoted JSON secrets such as
  {'Authorization': 'Bearer ...'} (Python dict reprs / JS object literals),
  which the double-quote-only pattern silently bypassed on both sides.
- Cover mongodb+srv://, rediss:// and amqps:// connection strings.
- Match the Bearer auth scheme case-insensitively (RFC 7235).
- Redact prefixed key/token assignments (api_key=, secret_key=,
  access_token=) as a whole rather than chewing the tail into a garbled
  "api_[REDACTED:api_key]", while still covering bare key=/token=. A word
  boundary was rejected because it would drop coverage for <prefix>_key=.
- Remove the redundant |Authorization alternative (covered by /i) and swap
  the manual value-slicing helper for a capture-group substitution.

The backend edits touch both detection sites and both redaction pipelines,
so single-quoted secrets are flagged (and therefore sanitized), not merely
rewritten. Adds JS runtime-smoke and backend unit coverage for every case.
2026-07-05 13:26:32 -07:00
Patrick Buckley 93a7486cc2 Add client-side credential redaction for tool call cards
New shared ES6+ module (redact_credentials.js) provides comprehensive
visual credential censorship matching the backend output guard patterns:

  - PEM private key blocks, connection strings, Bearer tokens
  - OpenAI / GitHub / AWS / Google API key formats
  - Query-string and JSON-style credential values
  - JSON secret keys (api_key, password, token, authorization, etc.)
  - ENV secret lines (SECRET_KEY=, DATABASE_URL=, etc.)

Integrated into both frontend surfaces:
  - interactive.js: replaces legacy minimal _redactApiKeys function
  - conversation.js::buildConvResult (shared substrate, used by coordinator)
  - coordinator.js::renderToolOutput fallback paths

Backend parity: added 'authorization' to the JSON secret regex in
output_guard.py so the output guard flags and redacts Authorization
headers in JSON tool output.

Tests: ported the runtime smoke test from the removed _redactApiKeys
to import the new module directly; added redact_credentials.js to the
var-free and const-reassign guard bundles.
2026-07-05 13:26:32 -07:00
Patrick Buckley 56624f9597 fix(core): scrub credentials and control chars from tool-args log preview
`tool_args_preview` feeds `stream.tool_args_malformed` (WARNING) and
`wire.tool_args_legalized` (DEBUG), and tool arguments are model/user
controlled — they can carry secrets (a token in a bash command, a password in a
connection string) or raw CR/LF that break log lines. Route the preview through
`output_guard.redact_credentials` over the full value first (before the 120-char
cap, so a secret straddling the cut isn't half-shown past the pattern's reach),
then collapse every control char to a space, mirroring `audit._scrub_string`.

Addresses the PR review comments.
2026-07-05 11:59:52 -07:00
Patrick Buckley 16a68ae6d6 fix(core): legalize malformed tool-call arguments before the wire
A tool call whose `arguments` is not a JSON-object string (an unterminated
string from a non-`length` truncation, or an empty `""` from a no-arg call)
was committed verbatim and replayed on every subsequent send. Strict renderers
that re-parse arguments at render time (vLLM's `deepseek_v4`
`_postprocess_messages` runs `json.loads` on them) reject the whole request
with HTTP 400, wedging the conversation. The only prior guard dropped partial
tool calls on `finish_reason == "length"`; a `stop`/`tool_calls` finish reason
carrying invalid JSON slipped through, and its synthetic "retry" result kept it
from being an orphan, so the orphan-repair pass never touched it.

Add `sanitize_tool_call_arguments`, a wire-neutral legalize pass in lowering
(fold, legalize, repair), normalizing any non-JSON-object `arguments` to `{}`
on the transient wire copy only. The canonical trajectory keeps the raw model
output, so a wedged session self-recovers on its next send. A
`wire_valid_arguments` predicate is shared with a non-destructive
`stream.tool_args_malformed` warning at the stream accumulator, which surfaces
the model-quality problem at production time.

Convert `lowering.py` to structlog so the new pass emits structured events.
2026-07-05 11:59:52 -07:00
Patrick Buckley 2d4cb6fea9 fix(ui): make pane hotkeys work off macOS and match across surfaces
The pane/workstream accelerators only worked on macOS. They were bound to
Ctrl, which on Windows/Linux IS the browser's own accelerator: Ctrl+T,
Ctrl+W and Ctrl+1-9 were swallowed by the browser (new tab / close tab /
switch tab) and never reached the page. macOS browsers own Cmd instead, so
Ctrl was free there and everything appeared to work.

On top of that the shortcuts were declared in three places that had drifted
apart — the "?" overlay, each app.js keydown handler, and the tab-menu
badges in shell.js. The console fell to convTabMenu's node-proxy fallback
lane, which dropped every shortcut badge (and Fork), so its tab menu showed
no accelerators and Ctrl+W there just closed the browser tab.

Choose the modifier per platform (Ctrl on macOS, Alt on Windows/Linux) and
make shell.js the single source of truth for the per-pane accelerators: a
stable accel registry drives both the platform-aware badge and one shared
keydown handler that invokes the ACTIVE pane's own menu item, so a badge
can't advertise a chord the handler ignores and each surface contributes
only what it supports (the console omits Fork; it has no fork surface yet).

Each surface's app.js keeps only its global accels (new / switch /
dashboard); the console regains switch + dashboard to match. Mod+W now
uniformly means Close pane (drop the tab, session keeps running), matching
its badge and the universal Ctrl+W convention — previously the standalone's
Ctrl+W stopped the session. The previously-dead "Refresh title / Ctrl+Shift+R"
is wired, and Ctrl+T / Ctrl+D yield to text editing while a field is focused
(macOS transpose / delete-forward).
2026-07-05 09:09:34 -07:00
Patrick Buckley 357d00400e docs(changelog): document the 1.7.0 stable release 2026-07-05 06:37:44 -07:00
Patrick Buckley 3615f98c19 Fix send button stuck disabled by pruning orphaned approval cycles (#775)
* Fix send button stuck disabled by pruning orphaned approval cycles

When a DOM wipe (clear_ui / replay_truncated / replaceChildren)
detaches approval card elements while an approve_request event is
processed between the wipe and refetch-restore, the matching
approval_resolved may never arrive. The orphaned cycle entry in
approvalCycles keeps pendingApproval=true and the send button
disabled forever.

The fix adds a pruning pass at the top of _syncApprovalState():
cycles whose blockEls are all .isConnected === false are deleted
from the Map. This runs on every register/resolve/rebuild so
orphans are cleaned up promptly.

Also fixes an ordering bug in showInlineToolBlock discovered
during review: the block element was appended to the DOM after
_registerApprovalCycle, so the new isConnected prune would kill
the just-registered cycle before it took effect.

* Fix comment inaccuracy in showInlineToolBlock append-before-register guard

The comment said 'blockEls.every(el => el.isConnected)' but the
actual prune check is '!blockEls.some(el => el.isConnected)' -
no block elements are connected, not every element.
2026-07-05 06:03:40 -07:00
Patrick Buckley 801d5dfb59 chore: bump version to 1.7.0rc1 2026-07-05 02:03:18 -07:00
Patrick Buckley a352b20786 chore: bump version to 1.7.0a7 2026-07-05 02:02:16 -07:00
Patrick Buckley 6f8efaa44e test(golden): freeze the anthropic-compatible reasoning-effort wire
The wire-payload golden matrix had no anthropic-compatible coverage —
both AnthropicProvider rows are the native lane (compat=False), so the
distinct compat wire shape (reasoning control in
extra_body.chat_template_kwargs, never the native thinking param) was
unfrozen. Add the compat lane across all eight representative fixtures
with a manual-mode capability (the lane has no static table, so caps
ride in as a model definition would supply them) and reasoning_effort=
high: every golden now pins {enable_thinking: true, reasoning_effort:
high} in chat_template_kwargs, asserts the native thinking param is
absent, and preserves temperature (no forced 1.0). _capture gains an
optional caps override to support the no-static-table lane.
2026-07-05 01:59:38 -07:00
Patrick Buckley 9c90fe2722 fix(console): distinct effort label for native-adaptive none vs local toggle
Copilot review caught the native Anthropic adaptive ladders (sonnet-5,
fable-5, opus-4.8/4.7/4.6) labeling the none position 'None — sends
adaptive' — raw mode vocabulary the plain-language rule exists to
prevent. But treating the 'adaptive' token identically to the local
lane's 'on' would still misframe it: on these models thinking is always
on and an effort level rides output_config on every graded position
(verified on the wire), so 'thinking stays on' is true everywhere and
not what distinguishes none. The none position uniquely means no effort
is pinned — the model self-regulates it — so it now reads 'None — model
sets effort'. The local adaptive lane's bare toggle keeps 'thinking
stays on' (no effort lever exists there).
2026-07-05 01:59:38 -07:00
Patrick Buckley 1035fe05eb fix(console): effort annotations say in plain words what the request carries
Aliased knob positions were labeled after the lowest sibling sharing
their wire token — a toggle-only model rendered 'Max (= minimal)',
implying a minimal-effort downgrade the wire doesn't contain, and with
declared values 'High (= minimal)' while the wire carries high. Each
position now states its delivered level: exact matches stay plain
('Max'), snapped positions say 'Low — sends high', the adaptive none
position warns 'thinking stays on', budget detail stays in the
tooltip. Effort-param placeholder corrected to the real graded keys
(reasoning_effort / reasoning).
2026-07-05 01:59:38 -07:00
Patrick Buckley 530958e06b fix(providers): the session effort level always reaches the local-lane wire
Local lanes dropped the knob's graded value unless the operator declared
reasoning_effort_values (and, on the template channel, an effort key) —
picking Max sent a bare thinking toggle and the effort select
degenerated into seven positions that all meant 'on'. The user's
setting now always rides:

- openai-compatible: the flat reasoning_effort param carries the knob
  verbatim (effort_passthrough on the lane default); declared values
  still snap ordinally, and a declared effort_param still claims the
  template channel and suppresses the flat param.
- anthropic-compatible: the graded value rides chat_template_kwargs
  alongside the toggle whenever reasoning control is engaged — under
  the operator's effort_param, else the conventional fallback key
  (reasoning_effort); templates that don't reference the kwarg ignore
  it. thinking_mode=none still injects nothing.
- Commercial lanes untouched: empty declared values still mean 'no
  effort control' (o1-mini) and the ordinal snap is unchanged.

Golden writer now pins ensure_ascii=False: the baselines' literal em
dashes came from a hand edit (03f82521) the default-escaping writer
could never reproduce — regens no longer churn unrelated lines.
2026-07-05 01:59:38 -07:00
Patrick Buckley e136237b63 fix(providers): openai-compatible never consults the commercial table
Local-lane model ids are operator-chosen strings (vLLM
--served-model-name), so a prefix collision with a cloud model id
inherited that model's sampling and effort contract: a box named
o3-distill silently lost temperature support, and one named
gpt-5.5-my-finetune was sent gpt-5.5's snapped reasoning_effort values
it never declared. Both surfaces of the lane now return plain defaults
(OPENAI_COMPAT_DEFAULT in _openai_common): the chat class directly, and
the responses pin via a compat-mode OpenAIResponsesProvider mirroring
AnthropicProvider(compat=True). Everything beyond the defaults is
declared by the operator on the model definition, matching the
anthropic-compatible lane and lookup_model_capabilities' documented
'no static table for local models' contract. The commercial openai
lane (Responses-only) is untouched.

Pre-split tests that reached commercial rows through the chat-class
OpenAIProvider alias now source them from lookup_openai_capabilities;
their subject (registry rows + shared gating helpers) is unchanged.
2026-07-05 01:59:38 -07:00
Patrick Buckley 41e9907803 fix(console): available-models rows always carry effort_ladder
The except path for a malformed capabilities column appended the row
without the key, so clients had to null-check a field the happy path
guarantees. Initialize each entry with an empty ladder and let the try
block overwrite it — the response schema is stable per row.
2026-07-05 01:59:38 -07:00
Patrick Buckley 7c34d859b4 test(sdk): update stale send() vitest expectations to the path-keyed contract
Three server.test.ts / server-attachments.test.ts cases still asserted
the pre-verb-lift send shape (POST /v1/api/send with ws_id in the body).
The server route has been POST /v1/api/workstreams/{ws_id}/send (ws_id
in the path, {message} body) since that lift, and the SDK send() was
updated with it — only these expectations rotted. They fail on main
too; unrelated to approvals, folded in here to leave the TS SDK suite
green. Test-only, no SDK source change.
2026-07-05 01:57:54 -07:00
Patrick Buckley 16ee4e12ef fix(sdk): mark 1.7-added approval-cycle fields optional in the TS SDK
ApproveRequestEvent.cycle_id and ApprovalResolvedEvent.cycle_id /
call_ids were typed required, but they are 1.7 additions: a pre-1.7
server omits them on the wire, so a current SDK talking to an older
node sees undefined. The UI and channel adapters already keep the
legacy no-selector fallback for exactly that case. Mark them optional
so consumer code can't assume a string that may be absent — matching
the Python SDK, whose dataclasses default all three.
2026-07-05 01:57:54 -07:00
Patrick Buckley 976c07d047 fix(ui): make the App the sole owner of sendBtn.disabled
The interactive composer had two uncoordinated writers of
sendBtn.disabled: _syncApprovalState wrote `pendingApproval || busy`
directly, while Composer.setBusy wrote it too via _reconcileDisabled.
In queueWhileBusy mode the composer's write re-enables send, so a
state_change to "attention" (exactly the pending-approval state)
firing after an approve_request card rendered raced the approval
disable back off. The `|| busy` term also defeated the "Queue
message…" affordance whenever _syncApprovalState ran mid-turn.

Opt the composer into externalDisable (it keeps rotating the
Send/Queue label + placeholder + stop button, but no longer writes
the flag) and route every axis — live approval cycle, cross-user send
gate, busy — through one App reconciler, _reconcileSendDisabled. Busy
is intentionally not a disable axis here: queueWhileBusy keeps Send
clickable as "Queue" while the agent runs.

Pre-existing on main (the old scattered direct writes had the same
collision); surfaced by the concurrent-cycle review.
2026-07-05 01:57:54 -07:00
Patrick Buckley 8da5dc3f5a docs(api): regenerate OpenAPI specs for the details-list contract
The checked-in openapi-server.json / openapi-console.json still
described the removed singular pending_approval_detail field; re-run
generate-types.py so the reference specs carry the
pending_approval_details list + cycle_id. Retire two docstring
references to the deleted singular serializer and one stale comment.
2026-07-05 01:57:54 -07:00
Patrick Buckley 7f0e0406b3 test(approvals): concurrency matrix + suite migration to the cycle model
New regression matrix for the release blockers: cross-approval
independence, lost-wakeup at gate entry, FIFO selector-less
resolution, resolve-all sweep, double-resolution no-op, cards/legacy
view tracking, and the generation-exactness set — stale delivery
rejection, Smart-Approvals origin check, purge keep_origin, the
purge-to-register window eviction, late cross-generation "superseded"
stamping, concurrent smart+human gates, and the pre-delivered-verdict
fast path. Plus sub-agent judge wiring (agent_gate off the main
slot, close() firing all generations) and endpoint tests for cycle
pinning and the Approve+Always race guard.

Gate threads run under one shared mock-patch harness — mock.patch
start/stop of the same target from concurrent threads corrupts the
patcher's restore stack — with a sweep-until-dead teardown so the
conftest leak guard can't trip. Existing suites migrate off the
singleton fields to cycle assertions and the
pending_approval_details wire shape.
2026-07-05 01:57:54 -07:00
Patrick Buckley 6c94514106 feat(ui): concurrent approval cards in the interactive and coordinator frontends
interactive.js tracks live cycles in a Map: per-cycle action buttons
and feedback, per-cycle optimistic clears and resolved-status pills,
keyboard routed to the oldest (or the focused) cycle, announce-shell
dedupe, and a composer that stays disabled while ANY cycle is live.
Verdict glow is scored per batch — a sibling's verdict neither
recolors the oldest card nor leaves its own card stale.

coordinator.js renders one approval block per pending_approval_details
entry, posts child approve/deny with the block's cycle_id, clears
exactly the resolved cycle on approval_resolved (legacy events without
one clear all), and replays every entry from snapshots.
2026-07-05 01:57:54 -07:00
Patrick Buckley 0d0fe8dd71 feat(channels): cycle-keyed approval tracking in Slack and Discord
Track posted approval prompts by (ws_id, cycle_id) — one message per
concurrent cycle — so parallel task agents' prompts resolve
independently. Buttons carry the cycle in their value (Slack) /
footer (Discord); intent verdicts route onto the owning cycle's
message by call_id membership.

The exact-key-then-legacy-fallback lookup (an empty cycle_id from a
pre-multi-cycle server resolves the workstream's single tracked
entry) and the all-cycles sweep are centralised as shared _routing
helpers so the fallback semantics can't drift between adapters.
2026-07-05 01:57:54 -07:00
Patrick Buckley 18c3301428 feat(api): cycle-routed approval resolution across server, console, schemas, SDKs
POST /approve accepts cycle_id / call_id selectors and 409s on stale
selectors with the current cycle's ids so clients re-render instead of
silently resolving an unrelated batch. Selector-less bodies pin the
resolve to the cycle the lookup returned (not "whichever is oldest by
the time the resolve runs"), and Approve+Always names apply only after
the pinned cycle actually resolved — the auto-approve whitelist can no
longer describe a different batch than the one that resolved.

approve_request carries cycle_id; approval_resolved carries cycle_id +
call_ids; SSE reconnect replays every live cycle's card. The console
collector, coordinator UI fan-out, and both SDKs (Python + TS) thread
the cycle correlation through.

BREAKING (1.7): the singular pending_approval_detail field is removed
from dashboard rows, workstream detail, and node snapshots — replaced
by the pending_approval_details list (one entry per live cycle, each
carrying its cycle_id). stable/1.6 keeps the old shape.
2026-07-05 01:57:54 -07:00
Patrick Buckley 185dcc2960 feat(judge): sub-agent gates run the intent pipeline as their own generation
task_agent tool calls reached the approval gate judge-blind: no
heuristic verdict on the card, no LLM verdict, no audit row, and Smart
Approvals could never clear them. Run _evaluate_intent on the
sub-agent gate with the sub-agent's own trajectory as judge context —
its task prompt is the delegation contract the operator approved, so
"does this call serve the task" is the right local alignment question.

Sub-agent spawns are agent_gate generations: they never touch the main
loop's supersede slot (parallel siblings would make each other's
verdicts look stale), staleness is enforced per-cycle by the UI's
generation checks instead. Every generation registers in
_judge_cancel_events — kept exact by the judge's new done_callback —
so close() aborts all in-flight daemons; judge.cancel_on_approval
fires per-gate exactly like the main loop. CLI and eval UIs accept
the judge_event delivery kwarg.
2026-07-05 01:57:54 -07:00
Patrick Buckley 0fe8e4106f feat(approvals): concurrent approval-cycle registry in SessionUIBase
The approval pipeline was a per-UI singleton (one card, one Event, one
result slot) multiplexed by N concurrent gates. With parallel task
agents that meant one click could resolve every parked batch with the
same verdict, a sibling's gate entry could eat a just-fired resolution
(3600s "stuck dialog" hang), and Approve+Always could whitelist a
different batch than the one on screen.

Replace the singleton with a registry of ApprovalCycle objects keyed
by cycle_id: per-cycle events/results/decisions/verdict parking,
oldest-first selector-less resolution, guarded double-resolution, a
resolve_all_approvals sweep for cancel/close/worker-recovery, and a
maintained oldest-cycle view in the legacy _pending_approval slot for
boolean-ish consumers.

Verdict bookkeeping is generation-exact end to end: the entry purge
spares verdicts the entering batch's own judge spawn already delivered
(a fast judge no longer stalls the Smart-Approvals wait to its full
budget), registration evicts stale-generation arrivals that land in
the purge-to-register window, recent decisions are generation-tagged
so a stale generation's late verdict stamps "superseded" instead of
stealing a reused call_id's decision, and Smart-Approvals
qualification identity-checks the delivering generation.
2026-07-05 01:57:54 -07:00
Patrick Buckley fd65a490dc chore: keep design docs local-only 2026-07-05 01:57:54 -07:00
Patrick Buckley 3607517814 fix(providers): registry effort truth — o-series/gpt-5.5/codex-max/sonnet-5; forward declared none
Capability-registry corrections verified against the official OpenAI
reasoning guide, the Azure reasoning-models matrix (2026-06 revision),
and the Anthropic models-overview/effort/migration pages (2026-07):

OpenAI (vocabulary confirmed none/minimal/low/medium/high/xhigh — no
"max" level exists; knob max rides the xhigh ceiling via the ordinal
snap):
- o1/o3/o3-mini/o3-pro/o4-mini declare low/medium/high (every o-series
  model except o1-mini) — without declared values the session knob was
  silently dropped for these models. o1-mini stays effort-free.
- gpt-5.5 default corrected none -> medium (5.5 reasons by default,
  unlike 5.1-5.4).
- gpt-5.1-codex-max gets an explicit row: it prefix-matched the
  gpt-5.1 row (no xhigh), capping the knob's xhigh at high on the one
  model xhigh was introduced for.

Anthropic (effort-page matrix):
- claude-sonnet-5 row added — it previously fell through to
  _ANTHROPIC_DEFAULT (manual budgets, 200k ctx, no effort), all wrong:
  adaptive-by-default thinking (manual budgets are a 400), sampling
  params rejected, 1M ctx / 128k out, effort low..max incl. xhigh.
- claude-sonnet-4-6 gains its documented "max" effort level (knob
  xhigh now rides max, not high) and the stale 64k max_output becomes
  the documented 128k.
- fable-5 / opus-4-8 / opus-4-7 / opus-4-6 / opus-4-5 rows verified
  correct as declared.

Knob semantics completed: resolve_reasoning_effort now forwards the
knob's "none" position verbatim when the model DECLARES an explicit
none level (gpt-5.1+, grok-4.3) — omitting the param there leaves a
reasoning-on server default (gpt-5.5: medium) in charge of a knob
that promises off. Models without a declared none still omit, and
none is never a snap target. Parity harness swaps its synthetic
openai shape for the real gpt-5.5 registry row.
2026-07-04 20:54:20 -07:00
Patrick Buckley a0e04a8588 fix(providers): effort snapping is ordinal — round up, cap at the ceiling
The knob domain grew xhigh/max after the snapping fallbacks were
written, which silently inverted their semantics: off-list meant
"unrecognized string" then, but now usually means "above the model's
ceiling", where falling back to the default tier is directionally
wrong (grok-4.3 at knob max got low; values low/medium/high at knob
xhigh got medium; Anthropic manual mode gave xhigh/max a 4096 budget
while high got 16384).

One rule everywhere now, via snap_reasoning_effort in _protocol:
exact match wins; otherwise the smallest declared level ranking at or
above the knob; above the ceiling, the ceiling. "none" is never a
snap target, and default_reasoning_effort only catches values the
ordinal snap cannot rank.

- resolve_reasoning_effort (flat chat / responses / validated
  effort_param lanes) snaps ordinally: xhigh over (low, medium, high)
  now sends high; xhigh over DeepSeek-style (high, max) sends max —
  matching DeepSeek's official xhigh-to-max aliasing, so a declared
  values list now reproduces that contract instead of defeating it.
- _map_reasoning_to_effort (native output_config) rounds up too:
  knob xhigh on Opus 4.6 (low, medium, high, max) rides max instead
  of silently dropping output_config.
- EFFORT_BUDGET_MAP is monotone across the whole knob domain:
  minimal/low 1024 (API floor), medium 4096, high 16384, xhigh 32768,
  max 65536. Unknown strings still fall to the 4096 default.

Google defaults are unaffected (ceiling and default coincide at
high); wire goldens unchanged. Parity harness caught the budget
clamp interacting with its own max_tokens during development —
capture budget raised above the largest manual budget.
2026-07-04 20:54:20 -07:00
Patrick Buckley ffe8214cfe test(providers): ladder-to-wire effort parity harness across all lanes
Proves the effort-ladder projection against the real request path
instead of against the mapping helpers it shares with it. For 22
(provider lane x capability shape) points — both Anthropic lanes,
openai-compatible on both API surfaces, openai, google (default and
template-override hybrid), xai (default and inert-override), and the
DeepSeek/qwen template contracts — every knob position is driven
through the actual provider create_streaming against a recording fake
client, and two invariants are asserted per shape:

1. each ladder token decodes to an expected effort wire subset
   (toggle / template effort / flat param / thinking budget /
   output_config) that must equal the captured kwargs exactly;
2. two knob positions carry equal tokens iff they produce identical
   effort-relevant wire payloads — the grouping promise the UI
   annotations lean on.

The RecordingClient SDK-seam stub moves from the wire-payload golden
harness into tests/_wire_capture.py so both suites capture at the same
seam. Verified the harness catches the bug class it was built for:
re-adding xai to _CHAT_LANES fails xai-template-override-inert.
2026-07-04 20:54:20 -07:00
Patrick Buckley 1f63f622c9 fix(providers): xai effort ladder is flat-only; share the suppression rule
Second external audit round on the ladder. Verified and fixed:

- xai was in _CHAT_LANES on the false premise that XAIProvider
  subclasses the chat provider. It subclasses OpenAIResponsesProvider,
  whose surface ignores extra_body entirely, so a thinking_mode /
  effort_param override never changes an xai request — but the ladder
  claimed a template toggle ("on+low") that does not exist on the
  wire. xai now projects through the flat channel only, like openai.
- The flat-param suppression rule (a declared effort_param claims the
  template channel) was encoded independently in
  apply_temperature_and_effort and the ladder. Extracted into
  flat_effort_suppressed() in _protocol so the request path and the
  projection cannot drift.
- admin_effort_ladder logs the swallowed resolver exception before
  returning 400 (a genuine bug would otherwise hide as a silent 400).
- list_available_models reads server_compat with .get() instead of
  destructively popping it out of the parsed capabilities dict.
- models_changed SSE now re-annotates the skill launch-config effort
  select after invalidating the models cache instead of leaving a
  stale ladder until the next keystroke.
- Capabilities JSON textarea placeholder hints the two effort fields
  that have no structured control (reasoning_effort_values,
  default_reasoning_effort).
2026-07-04 20:54:20 -07:00
Patrick Buckley f4701bf0f9 test(golden): re-baseline Google wire payloads for the effort knob
The Gemini effort fix (ee9e9c1f) adds a flat reasoning_effort to every
Google chat-completions request at the session default knob — the
golden fixtures now carry it. Only the eight google__* goldens change
(one added key each); other providers' goldens are untouched — the
UPDATE_WIRE_GOLDENS pass also wanted to rewrite twelve passing goldens
with escape-format-only churn (raw em-dash vs \u2014), reverted to
keep the diff semantic.
2026-07-04 20:54:20 -07:00
Patrick Buckley 06cc184227 fix(console): address verified external-audit findings on the effort ladder
The one that mattered: /v1/api/models passed the capabilities column —
a JSON STRING (sa.Text) — straight into effort_ladder_for_model, whose
field filter calls .items() on it; the per-row guard swallowed the
AttributeError, so effort_ladder was silently absent from every row and
the sklc annotation could never fire. The endpoint now parses the JSON
and splits the namespaced server_compat exactly like the model_registry
loader, and a regression test seeds a string-capabilities row.

Projection fidelity: effort_ladder_for_model threads api_surface (the
responses surface ignores extra_body — flat-param-only ladder, matching
create_provider's request-time divergence); google/xai route through
the chat-lane projection they actually inherit (_finalize_extra_body +
flat param); the native-Anthropic branch reflects that output_config
gates on supports_effort alone, independent of thinking_mode; budget
clamping to per-request max_tokens is documented as out of scope.

Hardening and symmetry: admin endpoint 400s (not 500s) on non-dict JSON
bodies and gained HTTP tests; the admin edit-load strips effort_param
from the raw JSON only for the lanes whose save path re-adds it, so
non-compat rows can't silently lose a stored key; the empty-model early
return bumps the ladder sequence so stale in-flight responses can't
re-annotate; alias labels only reference positions the target select
actually offers (the skill shelf omits none/minimal); the sklc models
cache no longer pins a rejected promise and is invalidated on the
models_changed event; debounces unified at 500ms;
merge_reasoning_template_kwargs now always returns a fresh dict for
non-empty input; the shared budget constants are public.
2026-07-04 20:54:20 -07:00
Patrick Buckley 59a527f2f2 feat(console): surface each model's effective effort ladder
Seven knob positions render as seven behaviors in the UI, but the real
ladder depends on the lane and the model: qwen3.6 has two (off/on),
DeepSeek-V4 three, Claude 4.6 five. Operators had no way to see which
positions alias — the confusion class behind silently-equal effort
levels.

providers/effort_ladder.py projects the knob domain through the same
mapping functions the providers use at request time (resolve_reasoning_
effort, reasoning_template_kwargs, the manual budget map — hoisted to a
shared constant so the projection can't drift), yielding
{value, effective} rows where equal tokens promise identical requests.
/v1/api/models rows now carry the ladder (guarded per row), and
POST /v1/api/admin/models/effort-ladder computes it for the admin
modal's unsaved edits.

The admin per-model effort select and the skill launch-config effort
select annotate aliased positions ("Max (= high)", "None (model
default)") with a sends-tooltip; annotations refresh as thinking-mode /
effort-param / capabilities fields change. The ladder describes what
Turnstone sends — server-side templates may alias further (DeepSeek-V4
folds low/medium into its default high tier).
2026-07-04 20:54:20 -07:00
Patrick Buckley d7941c88be fix(providers): thread the session effort knob to Gemini
_GOOGLE_DEFAULT declared no reasoning_effort_values, so
resolve_reasoning_effort returned None and the session effort knob was
silently dropped for every Gemini model — the same bug class this
branch fixed on the local lanes. Gemini's OpenAI-compat surface
documents a flat reasoning_effort (2.5: thinking_budget mapping; 3.x:
thinking_level), so declaring values lights up the inherited
chat-completions path.

Values are the safe cross-model set (minimal/low/medium/high): "none"
is excluded because 2.5 Pro and the 3.x family reject disabling
thinking — and the resolver never forwards the knob's none anyway (the
param is omitted, server default applies). Off-list xhigh/max snap to
the declared default high. Encoded from the official compatibility
docs per the static-caps pattern; not live-verified.
2026-07-04 20:54:20 -07:00
Patrick Buckley c64dc16319 feat(console): Always-on thinking-mode option in the model form
Post effort-knob rework, "Enabled" (manual) means knob-controlled —
effort none turns thinking off. Operators who want the pre-#771
always-on behavior (knob never disables) previously had to hand-write
thinking_mode "adaptive" into the raw capabilities JSON. The dropdown
now offers all three representable modes — None / Effort-knob
controlled / Always on — and the edit-load lift captures adaptive
instead of relegating it to raw JSON.
2026-07-04 20:54:20 -07:00
Patrick Buckley d564cee43d docs(providers): ground the effort_param values caution in official template contracts
Cross-checked online: Qwen3.6's template documents enable_thinking +
preserve_thinking only — no effort parameter exists (vLLM's flat
reasoning_effort convenience boolean-maps to the same toggle).
DeepSeek-V4 officially accepts reasoning_effort high/max with Think
High as the default thinking tier and low/medium→high, xhigh→max
aliasing — so freeform effort_param passthrough matches the contract
exactly, and a declared values list omitting xhigh/max would make
Think Max unreachable. Live probes on both boxes agree with the
official contracts once the default-tier framing is applied.
2026-07-04 20:54:20 -07:00
Patrick Buckley 2cf23b6fe2 fix(providers): address high-effort review of the reasoning-knob branch
Verified findings applied:
- adaptive thinking_mode never knob-disables: the shared mapping now
  sends the toggle unconditionally true for adaptive (the native
  adaptive branch ignores the knob's none), while manual keeps the
  knob-driven contract. Restores the invariant the deleted chat-lane
  code upheld.
- a set effort_param suppresses the flat top-level reasoning_effort on
  the chat lane: the template channel replaces it — double-sending
  could 400 on schema-strict servers and disagree with operator pins.
- admin edit-save no longer drops a stored thinking_param when the
  thinking-mode dropdown is empty: the raw-JSON strip now only fires
  when a mode value actually round-trips through the dropdown.
- effort_param persistence gated on the local-server lanes so a value
  lingering across a provider switch never lands on commercial rows.
- three stale _compat_extra_params references renamed to
  merge_reasoning_template_kwargs.

Documented dispositions (no code change): the knob-none-disables flip
on upgrade is intentional and now carries an upgrade note; gateways
fronting real Claude belong on provider=anthropic with a custom
base_url (the compat lane is vLLM-schema-only); nonstandard
thinking_mode strings staying inert is the intended allowlist
contract. The real anthropic provider is unaffected throughout —
official Claude models keep native thinking/output_config.
2026-07-04 20:54:20 -07:00
Patrick Buckley 68b22adfa3 feat(providers): share the effort-knob→chat_template_kwargs mapping with the openai-compatible lane
Hoist the compat-lane injection into _protocol.merge_reasoning_template_kwargs
(next to ModelCapabilities — one implementation for both local-server lanes)
and retire OpenAIChatCompletionsProvider._apply_thinking_mode in its favor:
_finalize_extra_body now receives the session effort knob, so thinking_mode
manual/adaptive maps knob "none" to an explicit thinking_param false
(previously the toggle was unconditionally true) and caps.effort_param
carries the graded effort key on chat completions too. Operator
server_compat pins still win; the Responses surface is untouched (native
reasoning handles effort itself).

The admin Models form grows an "Effort param" field that round-trips like
thinking_param: lifted out of the raw capabilities JSON on edit-load,
re-added on save, cleared by emptying the field.

Verified live against qwen3.6-27b /v1/chat/completions: knob medium streams
reasoning_content, knob none suppresses it.
2026-07-04 20:54:20 -07:00
Patrick Buckley 9289693730 fix(providers): drive reasoning via chat_template_kwargs on the anthropic-compatible lane
The compat lane sent no reasoning control at all: vLLM's /v1/messages
has no thinking request field, thinking_mode stayed "none", and the
session effort knob was silently dropped. The reasoning levers live in
the chat template, so fold them into extra_body chat_template_kwargs
(_compat_extra_params): thinking_mode manual/adaptive maps the knob
onto caps.thinking_param (effort "none" = off, mirroring the native
manual-mode contract), and caps.effort_param (new ModelCapabilities
field) carries a graded effort value for gpt-oss-style templates,
validated against reasoning_effort_values when declared. Operator
server_compat entries win on key collision; native thinking params,
temperature forcing, and output_config never fire on compat.

resolve_reasoning_effort moves from _openai_common to _protocol next to
ModelCapabilities — importing it into _anthropic would otherwise cross
provider families.

The admin Models form now shows and round-trips the thinking-mode
dropdown for this lane; the #661 hide was premised on thinking_mode
being inert here, which this change inverts.

Verified live against qwen3.6-27b on vLLM /v1/messages: knob medium
streams a thinking block, knob none suppresses it, an operator pin
beats the knob.
2026-07-04 20:54:20 -07:00
metaclassing deff44bcea Addendum to Entra ID's... proclivities (#772)
* OIDC entra capture

* copilot being nitpicky

---------

Co-authored-by: pow3rtool <root@pow3rtools>
2026-07-04 16:48:52 -07:00
Patrick Buckley 217d3a3a9b feat(mcp): autonomous reconnect + liveness for static MCP servers (#768)
* feat(mcp): autonomous reconnect + liveness for static MCP servers

Static (non-oauth_user) MCP servers had no autonomous reconnect. Every reconnect
path was lazy — a tool dispatch (_cb_auto_reconnect), an operator refresh, or a
config edit — and the MCP SDK's own reconnect is a bounded 2-attempt burst on the
streamable-http GET stream only (verified: mcp 1.28.1), with no backoff and
nothing for the other transports. So a static server that went down and came back
while nobody was dispatching to it stayed disconnected until a dispatch or a
manual reconnect. Worse, a session whose transport dies while idle survives as a
non-None ClientSession with closed streams — nothing evicts it, so even a later
dispatch may not notice until it fails.

Add a static-server health loop on the mcp-loop (started in _connect_all; config
``static_health_check_seconds`` default 30, <= 0 disables):

- Reconnect: a disconnected server (session is None) is reconnected on a capped,
  jittered, FOREVER backoff (full jitter, base 1s, cap 60s, no attempt limit) —
  a server that returns after a long outage reconnects within ~a minute, and a
  permanently-misconfigured one costs at most one attempt per cap. The health
  loop owns this clock; the circuit breaker stays the DISPATCH fail-fast gate (a
  tool call to a down server errors immediately rather than blocking on the
  retry), and the loop keeps breaker state in sync so an open breaker closes on
  reconnect.
- Liveness: a connected server is pinged (send_ping) each cadence; a dead-but-
  idle one — which nothing else would notice — is evicted so the next tick
  reconnects it. This is the core of the "never reconnects" failure.

Serialize _connect_one per server behind a per-name lock (split into a thin
wrapper + _connect_one_locked): the health loop, a dispatch's _cb_auto_reconnect,
and an operator refresh could otherwise interleave teardown/rebuild on the shared
StaticServerState and corrupt it — a latent pre-existing race this also closes.
The body is unchanged (only relocated), so the delicate anyio / wait_for connect
logic is untouched.

Out of scope (follow-up): silent GET-stream / notification death — the SDK stops
the notification stream after 2 attempts while the request path stays alive, so
send_ping is blind to it; the fix is bounded session recycling, which needs a
static in-flight guard first (only PoolEntryState tracks in_flight today).

Tests: backoff bounds (capped / jittered / forever, no overflow), reconnect
success resets backoff + closes breaker, reconnect failure retries forever,
in-flight skip, per-name serialization (no overlap), ping keeps healthy / evicts
dead / evicts on timeout, tick skips oauth_user, connect_all start + disable
gating, clean cancel.

* fix(mcp): harden static-server health loop (review findings)

A max-effort review found 13 concurrency/correctness defects, all from the loop
mutating shared StaticServerState without the interlocks the pool path carries.
Fix all 13:

- In-flight interlock: add StaticServerState.in_flight (parity with
  PoolEntryState); _static_session_op increments/decrements around the static
  call_tool/read_resource/get_prompt session ops; the ping skips and never
  evicts a busy server, so a long tool call can't be torn down mid-flight.
- Dead-transport gating: the ping evicts + trips the breaker only on
  _is_dead_transport(exc); an McpError, httpx.PoolTimeout, or plain ping timeout
  is "slow, not dead" and only reschedules (matching the dispatch path).
- Session-identity: only evict the exact session that was pinged.
- asyncio.timeout (invariant-18) not wait_for for the ping; 5s->30s; the
  timeout-scoped cancel is distinguished from an external shutdown cancel
  (which still propagates) via .expired().
- Bounded reconnect: wrap _connect_one in asyncio.timeout so a server that
  handshakes then stalls list_tools can't wedge the loop or hold the per-name
  lock forever (connect internals untouched).
- Concurrent tick under asyncio.gather with a freshly-read clock for the sleep.
- Cross-path coordination: reconnect_sync/remove_server_sync take the per-name
  lock across teardown+rebuild (calling _connect_one_locked directly);
  _cb_auto_reconnect reuses a health-established session instead of racing a
  redundant reconnect and no longer trips the breaker on lock contention.
- Backoff hygiene on recovery; skip '__' names; on health reconnect clear only
  the open-circuit deadline (not the failure count) so a connect-ok/calls-fail
  server still escalates to a trip.

Adds 14 tests and adjusts those that assumed the old behavior; suite 195->209.

* fix(mcp): unify static-server reconnect coordination (round-3 review)

A third review round + live testing found 8 issues on the health loop, five
sharing one root: reconnect logic was fragmented across five drivers, each
handling the lock / session-reuse / in_flight / config-recheck / breaker / clock
differently and incompletely. Introduce one primitive and route every
lazy/autonomous driver through it.

_ensure_static_connected(name, cfg) — the single lazy (re)connect path, all under
the per-name lock: config re-check (+ lock-identity re-check, closing the
remove->re-add race) so a removed server is never resurrected; reuse-if-live so a
queued/concurrent driver never tears down and rebuilds a live session (the
observed reconnect storm); in_flight guard so a reconnect can't tear down a
session with a call still in flight on the evicted stack; bounded connect; and the
circuit breaker owned in one place (clear the open-circuit deadline on success per
finding-13, record one failure on real connect failure). Returns the session on
success/reuse, None on a deliberate skip, raises on real failure. Routed through
it: the health loop, a dispatch's _cb_auto_reconnect, and _refresh_all; operator
reconnect_sync stays a deliberate force-rebuild.

Also: fresh-clock deadlines (the stale tick-start clock was landing deadlines in
the past and collapsing the backoff into an every-tick retry storm); loop-death
fix (the tick no longer re-raises a CancelledError found in the gather results —
per-server fallout, not shutdown; the loop returns only when Task.cancelling()
marks a genuine shutdown); dispatch breaker records no failure on a sync-boundary
reconnect timeout (lock contention is not a server failure; real outcomes recorded
once, inside the primitive). Cleanups: extract _teardown_static_session (was
copy-pasted 3x); share _capped_exponential between the breaker cooldown and the
reconnect backoff. Adds 17 tests; test_mcp_client 204->226.

* fix(mcp): coherent timeout hierarchy + round-4 review fixes

A fourth review round on the unified reconnect coordination found 5 correctness
regressions + 1 cleanup, five sharing one root: the inner reconnect attempt bound
(45s) was LONGER than every caller wait (dispatch 30s, remove 15s, reconnect 30s),
so a caller cancelling mid-attempt delivered a bare CancelledError that slipped
past the primitive's `except Exception`.

- Coherent timeout hierarchy: add _STATIC_RECONNECT_CALLER_TIMEOUT_S (> the inner
  attempt bound) for the dispatch + operator waits, so the inner asyncio.timeout
  always fires first — a clean TimeoutError the primitive converts, cleans up, and
  records on the breaker — instead of a caller cancelling a live attempt. Fixes
  [0] (half-discovered session left installed, served with a stale catalog) and
  [1] (breaker never trips via dispatch).
- Primitive cancel-safe (belt-and-suspenders): its handler is now
  `except BaseException`, so even a bare CancelledError drops the partial session
  and records the failed attempt before re-raising.
- Operator waits: reconnect_sync / remove_server_sync default timeouts raised above
  the reconnect bound; remove_server_sync now CANCELS the pending _remove on
  timeout (so it can't later pop a re-added entry and corrupt state) and reports
  failure instead of a false 'removed' ([2], [4]).
- in_flight defer is gated on defer_if_busy: autonomous callers (health loop,
  _refresh_all) defer, but a DISPATCH reconnects rather than hard-fail a reachable
  server with an in-flight sibling ([3]).
- Cleanup: extract _schedule_next_ping (was a copy-pasted triplet in 3 branches) [5].

Adds 6 tests; the lock-contention test now shadows the caller-timeout constant so
it runs in ~1s instead of the full wait.

* fix(mcp): address PR review feedback on static reconnect

- _ensure_static_connected: skip breaker record on CancelledError
  (cancel proves nothing about the server; aligns docstring with impl)
- reconnect_sync: add asyncio.timeout wrapper so discovery-phase
  stalls get a clean TimeoutError inside the lock
- reconnect_sync: change except Exception to except BaseException
  so CancelledError from future.cancel() triggers catalog cleanup
- reconnect_sync: null state.session on failure so a tool-less
  session isn't mistaken for a live one
- _static_reconnect_one: use fresh monotonic clock for backoff
  gate instead of stale tick-start snapshot; remove dead now param
- _static_health_tick: correct docstring (0.5s clamp prevents
  busy-spin, not 'no sleep through short backoff')
- Test: new test for reconnect_sync timeout + catalog cleanup
- Test: update cancelled-attempt test for new CancelledError semantics
- Test: narrow except BaseException to except Exception + type hints
- Test: fix typo 'Understone' -> 'Turnstone'
- Test: remove unused stale_now variable; update mock signatures

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-07-04 07:40:48 -07:00
Stefano Maffeis bcf509a440 Drop dead last_ws_id/last_tool_call_id columns from mcp_pending_consent
Migration 054 added these columns but they were never populated (the sole
writer hardcodes None) and never read by any query, dashboard, or API.
Drop them so the schema matches reality.

Closes #769

Co-Authored-By: Paperclip <noreply@paperclip.ing>
2026-07-04 03:27:55 -07:00
Patrick Buckley 10f726f83d docs(mcp): correct _write_pending_consent last_ws_id/last_tool_call_id note
The docstring claimed the dispatch path plumbs a triggering ws / tool-call id
through a thin wrapper. It does not: _record_pending_consent_best_effort neither
receives nor forwards any id (the mcp dispatch layer never has one), the
proactive sweep has no dispatch, and nothing reads last_ws_id / last_tool_call_id
— they are unpopulated schema columns from migration 054. State that plainly so
the comment doesn't imply data is captured when it isn't (Copilot review nit).
2026-07-03 22:11:15 -07:00
Patrick Buckley acc262c405 feat(mcp): proactively keep consented OAuth (OBO) tokens fresh for unattended work
Per-user OAuth (auth_type=oauth_user) token refresh is entirely lazy: a token
is refreshed only when a tool is dispatched or a session binds the acting user,
and a dead refresh token is discovered only when a dispatch fails. That assumes
a human is driving the session, which breaks for autonomous / scheduled work
acting on behalf of an absent user — the token may be expired (latency), in a
transient-failure cooldown (unavailable), or the grant may be dead with nobody
present to re-consent. The only periodic MCP-loop task, idle eviction, actively
tears OBO connections down; nothing keeps tokens warm.

Add a background token-freshness sweep that keeps every consented oauth_user
grant hot WITHOUT keeping connections warm and WITHOUT mutating consent state on
a timer.

Sweep (_user_token_sweep_loop, default 240s):
- Enumerates consented (user, server) grants from the token store and runs the
  canonical refresh path for each. Strictly oauth_user-scoped: gates on
  _oauth_user_server_names and drives off mcp_user_tokens rows, so a static /
  no-auth server — which has neither — is structurally invisible (no DB scan, no
  authorization-server round-trip, no MCP-server call). Never connects to the
  MCP server; connections stay lazy.
- Observe-only: passes revoke_on_failure=False (new parameter on
  get_user_access_token_classified) so a timer NEVER deletes a token, emits
  token_revoked, or mutates the shared ambiguous-streak / cooldown. A dead grant
  is only surfaced (proactive dashboard pending-consent badge); the
  authoritative revoke stays on the lazy-dispatch path where a real user action
  justifies it. Because the row survives, a spurious server-wide invalid_grant
  (an AS maintenance window) self-heals — the badge is dropped on the tick the
  grant works again.
- Keepalive: force-refreshes a grant whose refresh token has sat un-exercised
  past user_token_refresh_keepalive_seconds (default 1800s) even while the
  access token is still fresh, so a provider that ages out idle refresh tokens
  can't expire one between a user's real sessions.
- Surfaces dead grants once per transition, pinning the pair only after a
  durable badge write so a failed persist retries rather than being lost. First
  sweep runs after a short startup grace so a restart surfaces a downed grant
  within seconds, not a full cadence later.

Cadence <= 0 disables the sweep; a positive value is floored (30s) so a
misconfigured tiny cadence can't turn the loop into a busy-loop. Reuses the
per-key refresh lock, so a keepalive force cannot double-refresh against a
concurrent dispatch.

Storage: add list_mcp_user_token_reconcile_targets() returning
(user_id, server_name, COALESCE(last_refreshed, created)) — expiry-unfiltered,
no ciphertext projected — on the protocol, sqlite, and postgres backends.

Tests: the sweep's no-auth invisibility (zero DB / AS calls with no oauth_user
server), observe-only non-destruction (token kept and shared streak untouched on
a background permanent / ambiguous failure), keepalive gating, badge
persist-then-pin retry, self-heal on recovery, cadence clamp / disable, and the
storage enumerator.
2026-07-03 22:11:15 -07:00
Patrick Buckley 62034378c6 fix(skills): address Copilot review — task_agent doc refs + gate fail-closed on missing storage
- task_agent.json referenced a non-existent `skill(action='search', query=...)`
  in two spots. The discovery tool is `skills` and the action is `find`
  (`search` is an activation value, not an action), so the guidance would
  mislead the model. Corrected both to `skills(action='find', query='...')`,
  matching the tool's own error strings.
- _high_risk_skill_denied returned "" (allow) when get_storage() is None — an
  asymmetry with the fail-closed lookup-exception path added earlier. A risk
  gate that can't verify the tier must DENY, not wave the skill through, so
  storage-unavailable (None) now denies too; both paths share one denial.
2026-07-03 19:16:36 -07:00
Patrick Buckley bcb8c5ab88 fix(skills): harden task_agent / persona / skill activation from whole-PR review
Two independent multi-agent reviews of the branch (high, then max effort) found
authority-confinement and robustness defects the per-step reviews could not
see. This commit addresses every confirmed finding. task_agent turned out to be
the surface that lagged its siblings on nearly every axis.

Risk gate (most severe):
- task_agent(skill=...) never enforced the high/critical-risk PRINCIPAL-load-
  only gate that skills(load) / spawn_workstream / spawn_batch enforce, so a
  model could route around it by delegating activation to a sub-agent. Enforce
  it inline in _prepare_task on the row already fetched (no re-query, no drift
  between get_skill_by_name and get_prompt_template_by_name).
- _high_risk_skill_denied now fails CLOSED on a storage fault: deny, never wave
  the skill through. Denying (not returning "") also keeps spawn_batch's per-row
  partial-success intact under a transient blip.
- (first round) extracted _high_risk_skill_denied onto spawn_workstream /
  spawn_batch, closing the coordinator-side bypass.

Persona confinement (Principle 7 attenuation on the task_agent edge):
- A restrictive persona now attenuates the sub-agent's TOOLS, not just its
  identity text — the tool lever is frozen into the item and filtered before
  _run_agent.
- Honor ALL FOUR persona levers on the sub-agent, not two: a child persona's
  mcp-off and memory-off levers now drop MCP tools (mcp__* + read_resource /
  use_prompt) and the memory tool, matching a main session under the persona.
- Cap the sub-agent by the PARENT session's own persona grant too, so a
  restricted principal cannot escalate authority by spawning.
- Add persona to the task_agent judge/audit func_args projection (policy +
  audit parity with spawn).
- Persona-resolution failures defer to a clean tool error (try/except mirroring
  _validate_child_persona) instead of an opaque "internal error".

Substitution / capability:
- substitute_args=False for capability contexts (defaults, task_agent) so a
  literal $ARGUMENTS / $N in a body is preserved, not blanked; env vars still
  resolve. The literal-$ARGUMENTS scan is deferred behind that guard (skipped on
  every capability render).
- Drop the CLAUDE_SKILL_DIR alias (canonical TURNSTONE_SKILL_DIR only). That
  name also lives in bash, where turnstone-as-a-node-inside-Claude-Code must not
  shadow the host's value; claiming it in the prompt but deferring in bash
  diverged the two surfaces (a review finding). turnstone now claims it in
  neither surface. The CLAUDE_SESSION_ID / CLAUDE_EFFORT prompt aliases stay
  (pure prompt values, no bash-namespace collision).

Skills-as-context:
- DEFAULT (always-on) skills stay in the identity system message — the standing
  baseline, never a mid-session cache-bust; only a NAMED applied skill moves to
  the user-role capability message. This shrinks the pending model-adherence
  eval surface to the named-skill move alone.

Cleanups: consolidate a duplicated rationale comment; correct the now-stale
"task agents are not persona-filtered" note.

PRE-MERGE GATE unchanged: the §7 Q1 model-adherence eval (named-skill move,
this branch vs main) is not runnable in-tree and must clear before merge.
2026-07-03 19:16:36 -07:00
Patrick Buckley fec5067fcd feat(skills): gate model-initiated load of high/critical-risk skills
A skill can auto-fire tools (auto_approve + allowed_tools) once loaded, so
letting the model activate a risky skill through skills(action='load') is an
injection-steerable lane that widens authority behind a rubber-stampable
approval. Deny it: high/critical-risk skills are now PRINCIPAL-load-only --
the model gets a clean error pointing the user at /skill, and the operator
loads such skills explicitly (handle_command /skill and cli --skill call
set_skill directly and bypass this gate).

The scanner-computed risk_level is the gate signal -- it already escalates for
the auto_approve + allowed_tools authority the create path warns about -- so no
new column or migration is needed. The check can only DENY, never widen, so it
is safe by construction (HYPOTHESIS.md Principle 7 / design section 5.5).

Remaining step-5 follow-ups, out of scope here: persisting the literal
disable-model-invocation frontmatter field for arbitrary author-marked skills
(needs a column) and deprecating the vestigial variables mechanism.
2026-07-03 19:16:36 -07:00
Patrick Buckley b0ed67aa60 refactor(skills): move applied-skill body out of the identity system message
Step 3 of the skill/persona split: an applied skill (including default skills)
is CAPABILITY context, so its body no longer sits in the identity system
message. It rides its own message (user role) after the identity block, with a
short intro naming the active skill. The <available-skills> discovery catalog
stays in the system message.

Two consequences:
- The cached identity prefix (persona BASE + ENV + POLICIES + catalogs) stays
  stable across skills(load): loading/clearing a skill changes only the
  trailing capability message, not the identity block.
- The task_agent base (_agent_system_messages) is snapshotted BEFORE the skill
  block, so a parent's applied skill no longer leaks into the sub-agent prefix
  (the sub-agent supplies its own persona identity and skill via _exec_task).

PRE-MERGE GATE: the design gates this on a model-adherence eval (this branch vs
main) verifying the model follows a skill as well from a context message as it
did from the system message (design section 7 Q1; ASSUMED-neutral, UNVERIFIED).
That eval is not runnable in-tree and MUST clear before this branch merges.
Mechanical structure is pinned by TestSkillContextPlacement.

Deferred follow-up: sub-agent (task_agent) skill-resource materialization, so
${TURNSTONE_SKILL_DIR} stays literal on that path (unchanged since step 1).

Test helpers (_sys_content) now read the full prompt prefix (identity + skill
context) so placement-agnostic assertions keep working.
2026-07-03 19:16:36 -07:00
Patrick Buckley c023272b16 refactor(skills): task_agent identity from persona, skill demoted to capability
Before, a task_agent's system identity WAS its skill (skill body concatenated
into the sub-agent's system message), and #683 deliberately gave task_agent no
persona. Now that personas are first-class on every creation/spawn path, make
task_agent consistent: identity comes from a persona, the skill is capability.

- task_agent gains persona= (validated at prep against the interactive kind,
  the general-purpose personas a worker can adopt). The resolved base prompt
  is frozen into the approval item; _exec_task never re-reads storage.
- Default identity (no persona=) stays _TASK_DEFAULT_IDENTITY. The one-shot,
  tool-over-narration operating guidance always layers on top.
- skill= is now CAPABILITY: rendered through the shared pipeline (step 1) and
  delivered as a distinct user-role context turn ahead of the task, never
  fused into the identity. Consecutive user turns coalesce at the provider
  boundary (Anthropic _merge_consecutive), so this is wire-safe.

Updates the task_agent tool schema (persona param; skill reframed as
capability) and flips the persona guard test (task_agent HAS a persona param
now). Sub-agent skill-resource materialization and the interactive
skills->context move remain follow-ups.
2026-07-03 19:16:36 -07:00
Patrick Buckley 3568a6db50 refactor(skills): unify skill-body substitution across invocation contexts
Skill-body placeholder substitution diverged by invocation context:
interactive load, default skills, and spawn-child ran the full
render + spec-substitute, while task_agent (_exec_task) ran
_render_template only -- so $ARGUMENTS and ${...} env placeholders
rendered literally on that one path.

Introduce _render_skill_body as the single render+substitute path and
route interactive load, defaults, and task_agent through it, so a skill
reading ${TURNSTONE_EFFORT} or $ARGUMENTS resolves identically wherever
it runs. A sub-agent has no invocation args, so bare $ARGUMENTS and the
positional $N / $ARGUMENTS[N] forms resolve to empty there -- matching
the defaults and spawn-child paths, not the old verbatim passthrough.

- Add ${TURNSTONE_*} as the canonical vendor-neutral spelling for the
  env placeholders (SESSION_ID, EFFORT, SKILL_DIR); keep ${CLAUDE_*} as
  a permanent back-compat alias so imported skills keep resolving.
- Bash env: export TURNSTONE_SKILL_DIR and SKILL_RESOURCES_DIR
  unconditionally, but add CLAUDE_SKILL_DIR only when the host has not
  set it, so turnstone does not shadow a real value when it runs as a
  node inside Claude Code.
- Materialize skill resources before substituting the body, so
  ${TURNSTONE_SKILL_DIR} resolves to the concrete bundle path on the
  interactive path.

Sub-agent resource materialization and moving identity to a first-class
persona are left to follow-ups; ${TURNSTONE_SKILL_DIR} stays literal on
the task_agent path for now (unchanged from prior behavior).
2026-07-03 19:16:36 -07:00
Patrick Buckley 9bf8d5699b fix(test): harden resolve_when_pending — cancellable worker (review)
Address Copilot review: cancel() now signals the worker to stop (a
cancellation Event) and joins only when started, so a test that errors
before the approval registers can't leak the worker or resolve late into a
finished test. The worker reads _pending_approval via getattr so a UI
without it can't crash the thread into a silent death (leaving approve_tools
blocked the full timeout), and only resolves when it actually observed the
registration.
2026-07-03 19:16:16 -07:00
Patrick Buckley c0ff00a1ff fix(test): eliminate lost-wakeup race in approval-prompt tests
The UI-approval tests drive a blocking approve_tools() by firing
resolve_approval() from a fixed 0.05s threading.Timer. approve_tools does
_approval_event.clear() -> register _pending_approval -> wait(3600s); on a
slow/loaded runner the timer can fire the event's .set() BEFORE that .clear(),
so the wakeup is wiped and approve_tools blocks the full _APPROVAL_WAIT_TIMEOUT
(one hour) -- surfacing as an intermittent CI hang (observed on the 3.12 runner
~15% into the suite; fast runners win the race, so 3.11/3.13 pass the same
commit).

Replace the fixed-delay timer with resolve_when_pending() (tests/conftest.py):
it waits until the approval is actually registered -- which happens AFTER the
clear -- before resolving, so the set can never be lost. The helper mirrors
threading.Timer's start()/cancel() so the surrounding scaffolding is unchanged.
10 sites across 3 files; the verdict-delivery timer (bounded to its own 5s
budget, not a hang) is left as-is.

Validated: the 3 files pass 20/20 under single-CPU stress (taskset -c 0) with
no hang or thread leak.
2026-07-03 19:16:16 -07:00
Patrick Buckley 45010f5890 fix(eval): address Copilot review — checkout-agnostic docs + skill validation
- Docstrings/help said the treatment skill 'composes into the system
  message'. This harness runs on both checkouts (system on main, a context
  turn on the placement-refactor branch), so the wording now describes the
  natural set_skill composition path without asserting a placement.
- Validate each skill-bearing case's 'skill' shape up front (driver +
  CLI) so a malformed dataset fails with a clear error, not a mid-run
  KeyError. Pinned by test_rejects_malformed_skill.
2026-07-03 17:30:33 -07:00
Patrick Buckley 845df69031 feat(eval): skill-adherence measurement mode
Add a two-arm skill-adherence mode to the eval measurement substrate that
measures whether a NAMED skill changes tool-use behaviour, so skill-in-system
(main) can be compared against skill-in-context.

- _run_single_test gains skill/skill_mode: skill_mode builds HeadlessSession
  under natural composition (no system_prompt_override) and, for the treatment
  arm, seeds the skill into the temp DB and activates it via the real
  set_skill path so the skill body folds into the system message under test.
  skill_mode defaults False, so the optimizer/measure paths are unchanged.
- Thread skill/skill_mode through _run_and_score_subprocess, _run_iteration
  and _run_iteration_parallel (serial + parallel).
- run_skill_adherence: per case, run treatment (skill) vs control (no skill)
  n_runs each, score against expected_actions, report per-case lift =
  pass_rate(treatment) - pass_rate(control) and the mean lift. The control
  isolates the skill's causal effect.
- turnstone-eval --skill-adherence <dataset>: loads a skill-scenario dataset
  and prints a treatment/control/lift table.
- eval_skill_adherence.json: authored search-first / test-after-edit /
  changelog-update scenarios, chosen so the base model does not do the action
  by default.
- tests: plumbing proof (skill folds into system_messages for treatment,
  absent for control) + lift-math aggregation.
2026-07-03 17:30:33 -07:00
renovate[bot] d47d528d9a chore(deps): update github actions 2026-07-03 17:20:15 -07:00
Patrick Buckley 50d0e6343f fix(eval): drop dead session rebind flagged in review
The success path already extracts message_count/total_usage before the
break, so the session = None rebind was unused dead code (code-quality
review). Remove it; exception/timeout cleanup paths are unchanged.
2026-07-03 16:39:31 -07:00
Patrick Buckley 7053439e84 refactor(eval): split measurement core from prompt optimizer
turnstone-eval was misnamed: it was a prompt optimizer, not a measurement
harness. Split the 3252-line turnstone/eval.py into a strictly one-way
dependency (optimizer -> eval-core; core never imports the optimizer):

- turnstone/eval/core.py  measurement substrate — everything up to and
  including _run_iteration: provider detection, NullUI, HeadlessSession,
  the test runner, score_run, aggregation, and neutral reporting.
- turnstone/eval/cli.py   new measure-only `turnstone-eval` — the old
  --no-optimize path promoted to the whole job (one _run_iteration call,
  then print the summary table).
- turnstone/optimizer.py  the UCB self-modify loop and its multi-agent
  pipeline (analyst/optimizer/observer/diversifier/tool optimizer), now
  `turnstone-optimizer`; imports from eval.core only.
- turnstone/eval/__init__.py re-exports the core public API for
  back-compat (score_run, _match_action, _run_iteration, HeadlessSession).

_apply_tool_overrides lives in core (HeadlessSession needs it) rather than
alongside the other tree helpers, so the dependency stays one-way.

Breaking change: `turnstone-eval` now measures; use `turnstone-optimizer`
to optimize. Both code paths are behaviour-preserving — the moved function
bodies are byte-identical.
2026-07-03 16:39:31 -07:00
Patrick Buckley cf05ffee7d fix(console): persona admin UX - grid columns, base-prompt copy, default row action
- Add the missing #admin-personas grid-template so the table lays out as
  columns; it was the only admin table without its own template, so every
  cell collapsed into one implicit stacked column.
- Base prompt: accurate per-mode placeholders (required on create; blank
  keeps a built-in's shipped prompt on edit) plus a client-side required
  check on create. The old "empty = the kind's stock base prompt" copy was
  wrong now that create rejects a missing base_prompt.
- Set the default persona from the row ("set default", with a scope-default
  badge) to match the models table; drop the shelf checkbox and its
  create/edit/submit wiring.
2026-07-03 00:29:26 -07:00
Patrick Buckley bed776a308 style: ruff format server_schemas and server
ruff format --check flagged two lines: a long persona-picker Field
description in server_schemas.py and a watch-restore create() call in
server.py that fits on one line after the persona-kwargs merge.
Formatting only, no behavior change.
2026-07-03 00:29:26 -07:00
Patrick Buckley dbf389783e refactor(personas): file-backed built-in prompts, explicit source column
Built-in persona base prompts move from inline DB text / base.md into
prompts/personas/<slug>.md — code-owned, PR-reviewable, drift-proof.
base.md / base_coordinator.md become personas/engineer.md / orchestrator.md.

Prompt source is now explicit in storage instead of inferred in app logic:
a new base_prompt_file column plus CHECK (base_prompt IS NOT NULL OR
base_prompt_file IS NOT NULL) — two nullable columns, never both empty.
Resolution is a coalesce (base_prompt else load(base_prompt_file)), frozen
into the workstream stamp at creation. base_prompt_file marks a persona as
built-in (code-only, un-archivable); an operator override on a built-in is
allowed and wins over the file. "Inherit the kind default" is a
workstream-creation act (is_default), not a persona-row state.

Migration 063:
- seeds reference their file (base_prompt NULL); no runtime file reads —
  the backfill's frozen prompt text is inlined as a point-in-time snapshot
  so migration history stays self-contained and reproducible.
- every existing workstream is stamped by kind (creative -> writer, else
  the kind default), set-based (INSERT..SELECT via temp tables) with the
  persona column added after the bulk writes to shorten its lock window.

Storage guards (both backends): operators must supply base_prompt;
built-ins can't be archived or have base_prompt_file set via the API;
clearing an operator persona's only source is rejected.

Follow-ups reviewed alongside (#756): soft-set visibility docstring scoped
to per-process; _apply_persona_snapshot / _current_persona_snapshot own the
stamp round-trip; spawn approval-header args (skill/name/target_node)
flattened+capped like persona; server-side tool injection generalized to
replace-only (client-def gated, incl. the xAI include forwarding). Seed
copy revised (researcher soft; de-costumed prose; engineer de-biased).
New test_schema_parity asserts create_all matches the alembic head.

Closes #683 groundwork; ruff + strict mypy clean, full suite green.
2026-07-03 00:29:26 -07:00
Patrick Buckley 75c2e6c364 fix(personas): apply PR review feedback
The roster persona merge distinguishes key-absence (pre-persona node in a
rolling upgrade — preserve) from present-but-empty (authoritative
unstamped — accept), so a stale in-memory value can never mask the
snapshot on an immutable field. The node create route caps the persona
slug at 64 like the console proxy, keeping oversized values out of the
storage lookup and the reflected 400 text. The four persona admin
handlers drop their redundant function-local asyncio imports, and the
DELETE-route test moves its request out of the assert statement.
2026-07-03 00:29:26 -07:00
Patrick Buckley d152c504e1 feat(personas): revise seed prompt copy
The scribe, researcher, and executive prompts drop the infrastructure-team
costume and the demo-theater close — those framings suit the stock BASE
modules (whose job is today's default engineer/orchestrator behavior) but
narrowed personas meant for general use: a scribe summarizing meeting
notes is not a teammate, and the executive's verdict language works
without corporate staging. The behavioral substance is unchanged —
fidelity discipline for scribe, evidence discipline for researcher,
interrogate/delegate/verdict for executive, with the approvals boundary
still stated plainly.

The writer prompt loses 'use the analysis channel', a harmony-format
holdover from the CLI's single-provider days — the reasoning cue is now
format-neutral. Migration docstrings ride along: the workstreams.persona
column is documented as a slug carrier, and downgrade() now states the
capability-widening consequence of stripping stamps.
2026-07-03 00:29:26 -07:00
Patrick Buckley b65e5cae0e docs(personas): accuracy sweep — spec models, protocol contracts, page corrections
Spec models now describe what the endpoints do: ListPersonasResponse
declares the tool_inventory the shelf depends on, both console create
models declare persona, CreatePersonaRequest declares org_id, and
UpdatePersonaRequest documents the null-vs-absent split (null clears
base_prompt/tool_allowlist, null on flags/kinds is ignored). Console
OpenAPI regenerated.

Protocol contracts match the implementations: update_persona's return
covers the no-op case, create_persona's raises-list is complete, and
both extended row-shape docstrings gain their tail columns plus the
append-only rule. The workstreams.persona comments say slug, not
display name.

Page corrections from the docs review: personas.md documents the
creative_mode-to-writer migration conversion, the mid-session /resume
MCP-lever behavior, visibility-based nudge gating, the soft-set
prompt-cache cost, and the executive tool list — and drops internal
jargon. The changelog entry moves under [Unreleased] with the house
breaking-marker style and the auto-conversion note. coordinator-skills
and the API tour stop using persona to mean framing; governance,
api-reference, sdk, console, tools, and memory pick up the new
permission family, endpoints, kwargs, picker, and lever caveats.
2026-07-03 00:29:26 -07:00
Patrick Buckley 09c05733c6 test(personas): harden the guard suite — real paths over scripted events
The rank guard now derives needs_approval through the real _prepare_tool
on a bash call under an allowlisting persona instead of scripting the
flag, and asserts the approval gate actually fires. The row-shape guard's
source-grep is replaced with behavioral collector tests driving both
ws_created lanes (poll-diff and SSE relay), plus a proxy-forward twin and
a saved-list value assertion that would catch positional column mix-ups.

Receiving-side stamping gets its first HTTP coverage: create with an
explicit persona under workstreams.create only (selection needs no
persona perm), kind-mismatch and unknown-name 400s, omitted-persona
default stamping, the 503 on a failed default lookup, and the clean-None
legacy lane. Resume adoption is pinned end to end: a corrupt target stamp
leaves the session fully intact, an MCP-on stamp is refused when the
client was persona-gated at construction, and an MCP-off stamp drops the
live surface (listeners deregistered, toolsets reset). Soft-set
tool_search expansion recomposes the prompt exactly once; legacy sessions
never recompose.

Compaction legs run real flows now: spill plus the recall-pointer variant
under memory-off with recall visible vs hidden, and a full stamp
surviving compaction-then-resume. Migration 063 gains the downgrade
config-cleanup case (stamps removed, creative_mode preserved) and the
conversion idempotency case (already-stamped creative rows don't crash
the upgrade).

RBAC coverage goes cross-perm: read-only and write-only principals hit
every verb (a wrong-perm-name regression in any handler is now visible),
archive and default-flip succeed through PATCH, persona.* strings
round-trip the role editors and the overrides overlay, and the production
route table is asserted directly (no DELETE registered). Endpoint/storage
fixtures move off migration-seed names; storage hardening tests cover the
size caps, corrupt-row reads, the TypeError-to-ValueError ordering, the
duplicate-name race mapping, and the single-default backstop. Shell
asserts pin the new picker surfaces and drop the last persona-as-kind
wording.
2026-07-03 00:29:26 -07:00
Patrick Buckley 5d1d34cd82 fix(personas): close review findings across the envelope, resume, and RBAC lanes
Provider search gating (replace-only): native web search now stands in for
a client web_search def that survived the persona visibility filter — on
both OpenAI surfaces and both injection lanes (web_search_options, the
server_side_tools loop, and _convert_tools' capability lane). A scribe or
any envelope hiding web_search stays search-free on search-capable models;
coordinators and tool-less utility calls stop receiving search too.

Resume stamp discipline: resume() loads config and parses the target's
stamp BEFORE touching session identity/history, so a corrupt stamp raises
with the session intact instead of half-adopting and then 'repairing' the
target's stamp on the next config save. The MCP lever now follows the
stamp on mid-session adoption: an MCP-off stamp drops the live surface in
place (listeners deregistered, toolsets reset); adopting an MCP-on stamp
into a session whose persona gated the client off is refused loudly (the
surface cannot be rebuilt post-construction). The REPL /resume handler
reports these errors instead of crashing the CLI.

Fail-closed default lane: a FAILED default-persona lookup at create is a
503 (routes) / clear exit (CLI) instead of silently degrading to the
unstamped stock envelope; a clean 'no default configured' still creates
legacy. resolve_persona_for_kind reports storage-unavailable distinctly
from unknown-persona.

Soft-set governance: tool_search expansion under a persona visibility set
recomposes the system prompt so tool-gated policy segments land with the
tool they gate. MCP resource/prompt catalogs gate on read_resource /
use_prompt visibility. Spawn judge/audit projections carry persona (the
human approval header already did). Active-list rows carry persona like
their project_id twin.

RBAC catalogs: persona.{create,read,write} join _VALID_PERMISSIONS and
the roles-editor sections, making the documented grant-outward path real.

Storage hardening: default-persona invariants move to a shared _utils
helper (validate + demote) with a pg advisory xact lock serializing
promotions and a post-promote single-default assertion; create maps the
unique-name race to the same ValueError as the pre-check; reads validate
JSON shape loudly (naming the persona); serialize enforces size caps;
field validation runs before invariant checks so malformed input is a 400,
never a TypeError-500. org_id guards explicit null and caps at 64.

Also: base_override='' means 'no override' at the compose boundary;
persona tag flattened/capped before the spawn approval header; /creative
redirect resolves the writer persona before advertising it; memory-nudge
gating unified through _nudges_enabled.

Provider/row-shape tests updated to the new contracts (the old ones
pinned the injection hole and the pre-persona row shape).
2026-07-03 00:29:26 -07:00
Patrick Buckley e2dcd2bd6b fix(personas): apply review findings — stamp adoption on fork/restore, PATCH semantics, gating
Review pass over the branch surfaced real defects, all fixed here with
regression guards:

- Fork-resume (resume_ws) adopts the SOURCE workstream's stamp,
  resolved pre-construction so all four levers (including the
  construction-time MCP gate) bind the fork; a corrupt source stamp is
  a loud 400, an unstamped legacy source forks unstamped — never the
  kind default. Watch-restore and CLI --resume thread the stamp the
  same way, closing an MCP leak where a restored MCP-off workstream
  re-merged the catalog.
- SessionManager.open parses the stamp inside the install guard so a
  corrupt stamp releases the reserved slot; a retry reproduces the
  loud error instead of 'already tracked'.
- Mid-session resume() adopting a stamp rebuilds the tool_search
  pathway to match (hard set drops it, soft set force-constructs it);
  soft persona sets survive the global tool-search setting being off.
- Memory nudges gate on actual memory-tool VISIBILITY, not just the
  memory lever, so an allowlist that hides the tool also silences the
  nudges that point at it; post-compaction resume gets a no-recall
  nudge variant when the pointer would dangle.
- Console PATCH: explicit null flags from UpdatePersonaRequest no
  longer archive the persona or flip levers on a rename; multi-kind
  personas survive a shelf edit; admin list ships the per-kind
  tool_inventory so the shelf checklist tracks the server inventory
  instead of a hardcoded JS list; admin CRUD moved off the event loop.
- Migration 063 converts legacy creative_mode workstreams to the full
  writer stamp (downgrade removes all persona keys).
- REPL: /new passes the persona; /workstreams unpacks the widened row.
- Shared resolve_persona_for_kind is the single eligibility rule for
  the HTTP handler, CLI, and spawn precheck; spawn_batch memoizes the
  persona lookup; ToolSearchManager.is_expanded gives the visibility
  tail an O(1) probe.
2026-07-03 00:29:26 -07:00
Patrick Buckley 0d6d7ebae1 docs(personas): concept doc, CHANGELOG 1.7 entry with /creative breaking note
docs/personas.md covers the four levers, the resolve-once/stamp-forever
snapshot semantics, the seed matrix, per-surface selection, authoring
rules, and RBAC; architecture.md's config-persistence paragraph swaps
the removed creative_mode for the persona stamp.
2026-07-03 00:29:26 -07:00
Patrick Buckley 9706fc5d9c test(personas): guard suite — rank guard, levers, spawn, RBAC, immutability
The 15 guards from the design brief: the approval path is untouched
under any persona (rank guard); empty-toolset personas compose no tools
block and put zero definitions on the wire; the tool_search escape hatch
is soft when included (discovered tools union with the allowlist) and
hard when omitted (pathway disabled, including native defer_loading);
memory-off suppresses recall injection, the memory tool, and
memory-directed nudges while behavioural nudges and task-agent tools
survive; MCP-off is session-wide and refresh-proof; spawn validates
persona at prep time and never inherits the parent's; task_agent's
schema stays persona-free; the stamp is immutable, survives
SessionManager.open threading, and corrupt stamps fail construction
loudly; mandatory prompt policies compose under every persona; CLI
resolution (extracted to resolve_cli_persona_kwargs for testability)
loads seeds, exits clearly on unknown names, and adopts the resume
target's stamp; persona edits/archives never touch stamped workstreams;
and the row-shape contract twins carry the persona field.

RBAC endpoint coverage: admin CRUD 403s without persona.* and succeeds
with it; the picker feed needs no persona permission and hides archived
personas; invariant violations surface as 400s; DELETE is 405.
2026-07-03 00:29:26 -07:00
Patrick Buckley 2329cb8ad5 feat(webui): persona picker, Service Hatch shelf, labels, row-emitter sweep, kind-id reclamation
Creation surfaces: the console launcher, the server webui new-workstream
dialog, and the dashboard composer all gain a Persona select fed by the
shared personas.js data layer (module cache + fingerprint + never-reject
fetch + window.TurnstonePersonas bridge, cloned from projects.js), kind-
filtered with the kind default preselected so a zero-touch launch is
byte-identical to today.

Authoring: a Personas tab in the console Manage surface (Governance
group, persona.read-gated) with a Service Hatch shelf exposing exactly
the four levers — base prompt, tool-visibility checklist (kind inventory
+ free-text row for MCP/dynamic names; tool_search membership decides
soft vs hard), MCP and memory toggles — plus kinds, default flip, and
archive.  No delete action anywhere (archive-only lifecycle).

The workstream wears it: SavedColumns.persona() on both saved tables,
hover/aria labels on the rail rows (raw slug fallback keeps archived
personas labelling their workstreams), and the full row-emitter sweep —
storage projections (list_workstreams tail, get_workstreams_batch,
list_workstreams_with_history) on both backends, the server dict
builders and ws_created events, both _coordinator_rows lanes, the
collector delta + pseudo-node paths, and the console cluster-create
proxy that rebuilds its body.

Naming reclamation: the launcher kind-toggle ids/classes that squatted
on 'persona' (launcher-personas, persona-coordinator/-interactive,
.persona-btn/.persona-led/.persona-tag) are renamed to kind-* before
'persona' becomes user-facing vocabulary, along with the prompts-module
and test wording that used persona to mean kind.
2026-07-03 00:29:26 -07:00
Patrick Buckley 54ebb24374 feat(personas): core stamping, four-lever application, create/spawn/SDK threading; remove /creative; add --persona
The persona resolved at creation is snapshotted into workstream_config
(five keys, all-or-none) and applied ONLY from the stamp — the personas
table is never read post-create, so edits/archives never touch existing
workstreams, and a corrupt stamp fails construction loudly instead of
silently reverting to a default envelope.  Legacy pre-063 workstreams
carry no keys and keep today's behavior byte-for-byte.

The four levers (turnstone/core/personas.py holds the codec):

1. Base override — compose_system_message(base_override=...) replaces
   exactly the BASE module; ENV/CONTEXT/TOOLS/POLICIES keep composing so
   mandatory prompt policies ride on top of every persona.  This also
   closes the old /creative hole where the fork bypassed composition
   (no CONTEXT, no DB policies).
2. Tool visibility — the allowlist intersects both the composition name
   set (TOOLS block self-suppresses, tool-gated policies drop, the
   memory advisory drops) and the END of _get_active_tools so the wire
   never advertises hidden tools.  tool_search in the set = soft
   (discovered tools union with the allowlist via the session's
   expanded-names set); absent = hard (the whole pathway is disabled,
   covering provider-native defer_loading, which has no synthetic name
   to filter).  Persona sets force client-side tool search.
3. MCP gate (session-wide) — an MCP-off persona drops the client
   reference at construction: no merge into _tools OR _task_tools, no
   listeners, refresh callbacks inert, resource/prompt catalogs gone.
4. Memory (own hands only) — no recall injection, memory-directed
   nudges suppressed (MEMORY_NUDGE_TYPES; behavioural nudges keep
   firing), memory tool hidden.  _task_tools is NOT filtered; compaction
   spill/markers are never persona-gated, and the post-compaction recall
   pointer is emitted only when the recall tool is actually visible.

Threading: the create handler resolves once (explicit name -> 400 on
unknown/disabled/kind-mismatch; empty -> the kind's default; pre-seed DB
-> unstamped legacy) and stamps via constructor kwargs + config keys +
the workstreams.persona column; SessionManager.open threads the stamp
pre-construction exactly like the saved model alias.  Non-fork resume
adopts the target's stamp so _save_config can't clobber it.  spawn /
spawn_batch gain a persona arg with prep-time validation (children are
interactive-kind; omitted = kind default, never the parent's).  Python +
TS SDKs, OpenAPI specs, the picker feed GET /v1/api/personas (authed, no
perm), and console admin CRUD /api/admin/personas (persona.* perms,
archive-only — no DELETE) round out the surface.

BREAKING: /creative is removed (the REPL command now points at the
writer persona); turnstone --persona <name> is the replacement.  Also
fixes the CLI session factory, which TypeErrored on the project_id
kwarg the shared InteractiveAdapter passes unconditionally.
2026-07-03 00:29:26 -07:00
Patrick Buckley cc48144a35 feat(storage): personas table, CRUD, seeds, perms (migration 063)
Adds the personas template shelf (#683): migration 063 creates the
personas table (tri-state tool_allowlist, per-kind is_default, archive
via enabled=0 — no hard delete) plus the workstreams.persona display
column, seeds the six launch personas (engineer/orchestrator as
zero-touch per-kind defaults; scribe/researcher/writer/executive as
curated envelopes), and grants persona.{create,read,write} to
builtin-admin following the 062 pattern.

Storage: list/get/get_by_name/get_default/create/update on both
backends, with the default-persona invariants (exactly one per kind,
single-kind, enabled, not archivable, demote-on-flip) enforced in the
storage layer and the JSON serialization shared via _utils so the
backends cannot drift.
2026-07-03 00:29:26 -07:00
Patrick Buckley 8f347da653 fix(registry): normalize config.toml context_window=0 to auto-detect
context_window=0 is the documented auto-detect sentinel -- "inherit the
CLI-detected window." The DB loader applies it (row.get(k, 0) or
context_window); the config.toml loader did not (entry.get(k, default)
only substitutes a MISSING key), so an explicit context_window = 0
leaked a literal 0 downstream, zeroing every budget that reads
ModelConfig.context_window -- judge lowering, session compaction. The DB
loader's comment even claimed config.toml shared "the same fallback
chain," which was false.

Match the DB loader at the source. The judge-side _positive_window
coercion stays as defense-in-depth, but its comments no longer misframe
0 as garbage -- it's a valid sentinel, now normalized at load.
2026-07-02 22:00:19 -07:00
Patrick Buckley 77de11a97d fix(judge): coerce non-positive judge windows + real output-guard fallback
Two window-sourcing edge cases the first pass missed:

- config.toml models can carry context_window=0 (that load path lacks
  the DB loader's 0-inherit normalization). The getattr guard caught a
  missing attribute but not a present 0, which would zero every budget
  and make honest_truncate drop everything. A shared _positive_window
  helper now coerces any non-positive / non-int window to the next sane
  candidate (the session window) then a floor, on every resolution path
  in both judges.

- The output-guard judge's session-model fallback keyed off
  provider.get_capabilities(), which reports 200k for local models --
  the fictitious-window bug the alias path already fixes. It now takes
  the session's real (config/registry-aware) window, like IntentJudge.

output_guard_judge shares _CHARS_PER_TOKEN from judge rather than
duplicating it, now that it imports the coercion helper anyway.
2026-07-02 22:00:19 -07:00
Patrick Buckley 587828c57e fix(judge): source the output-guard judge's real window + oversize backstop
The output-guard LLM judge fed the model the full tool output with no
window awareness, so on a small-window local judge a large output
overflowed into an opaque provider error and fell silently to
heuristic-only — the opted-in LLM tier vanished without a trace.

Resolve the judge's real context window from the registry's per-model
config (the static capability table reports 200k for every local
model), and add an up-front oversize guard: when the assembled prompt
would exceed the window, skip the doomed call and record a labelled
llm_error the operator can see instead of a silent no-op. The
heuristic tier runs first, so its verdict still stands.

Also drop the fixed 500-char cap on the tool_args framing field: like
the output under review it now lowers whole, bounded only by the same
window backstop, never by a default clip of a normal argument.
2026-07-02 22:00:19 -07:00
Patrick Buckley b0a5fa6856 fix(judge): give the intent judge the full tool arguments
The func_args projection in _evaluate_intent is the intent judge's
entire view of a pending call's arguments, yet it lowered only a
narrow field per tool: edit_file reached the judge as {path} with the
edits stripped, and skills mutations built their projection and never
assigned it, so the judge ruled on {}. A small local judge denied a
legitimate multi-edit edit_file at 95% confidence as "malformed,
missing old_string/new_string" on exactly this gap.

Project the full risk-relevant surface per tool — edits, file content,
timeouts, model overrides, skill risk fields, task status and
ordering, MCP resource URIs and prompt arguments — and add the
read_resource / use_prompt branches that previously fell through to an
empty {}.

Truncation is now a backstop, not a default. Arguments lower whole up
to the judge model's real context window, sourced from the registry's
per-model config rather than the static capability table (which
reports 200k for every local model and would over-budget a small local
judge into overflow). Only a genuine overflow truncates, with an
explicit dropped-character marker; the untruncated arguments always
remain in the trajectory. The verdict's persisted and streamed copy
carries a separate 16 KB backstop against pathological payloads.

A parametrized guard test asserts every gated tool projects a
non-empty argument view, so the silent-starvation failure mode fails
CI instead of shipping.
2026-07-02 22:00:19 -07:00
Patrick Buckley 73e7972fb8 fix(session): PR feedback + CI typecheck/test failures
- typecheck: dropping _acting_user_id from the SessionUI protocol (it made
  the attribute required, breaking NullUI's structural match and making
  TerminalUI abstract). _emit_state now narrows to SessionUIBase before
  assigning — the field belongs to the web-fanout UIs, not the protocol
  contract that CLI/eval UIs also satisfy.
- test: two mock queue_message stubs (attachments-endpoint fake,
  coordinator adapter double already fixed) needed the new
  interjector_user_id kwarg; the endpoint fake was raising TypeError ->
  queue_full. Added it and a negative test that a non-SessionUIBase UI is
  skipped by _emit_state.
- review (Copilot): _load_persisted_senders now latches _db_senders_loaded
  only if self._ws_id still matches the workstream it queried, so a
  concurrent resume() can't mark the read done for a workstream whose
  senders were never loaded.
- review (Copilot): corrected the acting-user-id comments in three places
  — it carries the owner id even single-user (the gate no-ops because it
  equals the viewer); it is empty only on unauthenticated lanes / before
  first state emit.

Note: the storage-protocol '...' stub flagged by the code-quality bot is
the file's universal convention (262 stubs, zero NotImplementedError);
left as-is for consistency.
2026-07-02 19:23:04 -07:00
Patrick Buckley 6424f73da4 feat(console): extend cross-user send gate to the coordinator surface
Coordinator workstreams will hit the same cross-user issue once MCP is
enabled there, so wire the same protection now.

- CoordinatorAdapter.send takes acting_user_id: binds it on a fresh turn
  (so MCP creds + the acting-user signal are correct) and passes it to
  queue_message on the interject path (CrossUserInterjectionError block).
  The create-time initial dispatch passes the creator's id.
- ConsoleCoordinatorUI.on_state_change includes acting_user_id (mirrors
  WebUI); the mid-turn-connect replay already carries it via the shared
  make_events_handler. The coordinator's user-facing /send route already
  reuses make_send_handler, so it inherited the interjector guard + 409.
- coordinator.js gains the same gate as the interactive pane: tracks the
  acting user from state_change, blocks send when busy AND acting !=
  viewer, and handles the 409 cleanly.

Drive-by hygiene (requested): the _verdictSig join used a raw U+001F
byte embedded in the source; replaced with String.fromCharCode(0x1f) —
identical runtime, ASCII-clean source (no invisible control char in the
file).
2026-07-02 19:23:04 -07:00
Patrick Buckley 9c1b76b632 feat(webui): disable send for non-acting participants while busy
The UX complement to the server-side cross-user interjection block: on a
shared workstream, while another participant's turn is in flight, this
viewer's send button is disabled so they don't click into a 409 (and
can't drive tools under the initiator's credentials).

Backend signal (the linchpin — the acting user was tracked but never
surfaced to clients):
- ChatSession._emit_state pushes the acting user (turn initiator, owner
  fallback) onto its UI (_acting_user_id on SessionUIBase).
- server.WebUI.on_state_change includes acting_user_id in the broadcast
  state_change event; the mid-turn-connect replay (session_routes) adds
  it too, so a client joining mid-turn learns who holds it. Id only (a
  uuid the client compares) — no name, no storage lookup on the hot path.

Frontend:
- auth.js retains the opaque user_id from /whoami (ts.user_id) — kept
  separate from the display username, used only for id comparison.
- composer.js gains an independent hard-block axis (setSendBlocked /
  _reconcileDisabled) so send can be disabled even in queueWhileBusy mode.
- interactive.js tracks the acting user from state_change, blocks send
  when busy AND acting_user_id !== the viewer's own id, and handles the
  409 as a clean message (reactive fallback for the click-beats-event
  race) instead of a generic connection error.

Degrades gracefully: single-user workstreams (acting user == viewer) and
older backends (no acting_user_id) never engage the gate.
2026-07-02 19:23:04 -07:00
Patrick Buckley 2ba54266c6 feat(session): block cross-user mid-turn interjections
A mid-turn interjection folds into the current turn under the
initiator's identity — bind_acting_user deliberately does not rebind
mid-turn — so on a shared workstream a second participant's queued text
would run any tools it triggers under the initiator's MCP (oauth_user)
credentials (confused deputy) and be stamped with the initiator's sender
label (misattribution). Rather than fold it in, reject: queue_message
now takes the authenticated interjector_user_id and raises
CrossUserInterjectionError when it differs from the current acting user.
The send route surfaces it as 409 cross_user_interjection. Only an
authenticated non-acting participant is blocked — self-interjection,
single-user workstreams, and unauthenticated internal lanes (empty id,
e.g. the coordinator adapter) are unaffected.
2026-07-02 19:23:04 -07:00
Patrick Buckley b9f95c357c fix(session): address ultrareview findings on shared-workstream branch
Cloud multi-agent review of the three follow-up commits surfaced 15
verified defects; this addresses them.

Security / correctness:
- output_guard was blind to the new sender-label trust marker: add
  fence.SENDER_LABEL_TAG to the forgery/leak detector and thread a
  second trusted nonce (trusted_sender_label_nonce) through
  evaluate_output/_check_marker_forgery so a forged or leaked
  sender-label block in tool output is flagged like an operator marker.
- Attachment-derived text (PDF extraction, audio transcript, perception
  output) bypassed sender-label neutralization because it materializes
  after _inject_sender_labels runs; neutralize it at each fallback site.
- _recompute_shared_state now runs on every compose (moved out of the
  non-creative branch) so a creative-mode resume can't leave shared
  state stale.
- /new and rewind/retry now reset shared state (were leaking the prior
  conversation's participant set / keeping a workstream latched 'shared'
  after its only second-participant evidence was deleted).
- Non-fork resume and /new remint both trust nonces; carrying a nonce
  across a workstream switch would let a token leaked in one forge a
  marker in another.
- _senders_dirty is only cleared once the persisted-sender read has
  actually landed, so a transient storage error retries within the turn.
- ws_id snapshot guard in _recompute_shared_state discards a result if
  resume() swapped workstreams mid-scan (MCP-callback race).
- recall/history search is scoped to the acting sender's visibility;
  the shared-workstream declaration now names that exception so the
  model doesn't read a filtered 'no results' as 'no record exists'.

Cleanup:
- fork skips the redundant persisted-sender read (its rows were just
  bulk-written); _maybe_note_new_participant goes through the single
  recompute entrypoint; senders_from_user_meta reuses _source_meta_from_json.
- fence.wrap docstring names the sender-label caller as a third
  untrusted-host boundary.

Tests: end-to-end compaction-narrowed resume recovery, hostile
display-name fence break-out, sender-label output-guard leak/forgery,
and the two-nonce independence.
2026-07-02 19:23:04 -07:00
Patrick Buckley c8f0c0cf90 chore(session): house-style polish on shared-workstream feature
- q-2: document the deliberate username-first display-name precedence in
  _resolve_display_name (diverges from auth.py's display_name-first
  because sender labels must match the owner-banner identity kind).
- q-3: drop change-lineage comments referencing the separate acting-user
  credential fix (tombstone noise once merged).
- q-4: tighten the plain-text attachment assertion from a tolerant
  subset check to exact shape + _sender value now that the stamp is
  deterministic.
- q-5: drop the contributor-local bare 'etc/' from .gitignore.
2026-07-02 19:23:04 -07:00
Patrick Buckley 21efeece32 fix(session): fence sender labels; move shared-ws behavior to a declaration
sec-1: the [message from <sender>] label was plain text, so a participant
could type a look-alike in their own message and impersonate another
sender to the model. Labels are now wrapped in a nonce-delimited
[start sender-label_<nonce>] ... [end sender-label_<nonce>] fence (new
fence.SENDER_LABEL_TAG, distinct value from the operator nonce) whose
token lives in the cached system prefix; participant content is
neutralized so typed look-alikes are defanged. A new
build_shared_workstream_declaration pins the token as the sole authentic
label.

sec-2 + q-1: the CONTEXT banner no longer embeds behavioral prose. It
carries a terse owner line + shared flag; the attribution rules, the
authenticity declaration, and the (now narrowed) tool-credential claim
move into the shared-workstream declaration. The credential claim is
corrected: per-participant credentials apply to MCP (OAuth) tools only;
built-in tools and skills run under the server/owner identity.

perf-3: _inject_sender_labels resolves each distinct sender's display
name once per call instead of once per turn, capping blocking storage
lookups at one per sender on the uncached error path.
2026-07-02 19:23:04 -07:00
Patrick Buckley 7f20b1bc84 fix(session): durable shared-workstream state + fork sender persistence
- _known_senders/_shared_workstream are now monotonic: union-only growth,
  latched shared flag, seeded once per workstream from a full-history
  distinct-sender read (new StorageBackend.list_message_senders) so
  compaction narrowing the resumable slice can no longer forget
  participants (duplicate join notes) or flip the banner back to
  single-user framing (prompt-prefix cache churn).
- Recompute is memoized per turn (invalidated on stamped user-turn
  append); system-prompt composition no longer pays an O(n) trajectory
  scan on every recompose.
- resume() resets the state: the monotonic guarantees are per
  workstream, not per session object.
- resume(fork=True) bulk-persist now carries the user-turn sender stamp
  into the fork's meta column (was: _source_meta only, which dropped
  attribution for every forked user turn on reopen).
2026-07-02 19:23:04 -07:00
metaclassing 212d1922e5 Multi-user chat context clarification and tool improvements (#750)
* multiuser chat fixes for identity clarity and obo oauth token selection during tool calls

* added some missing context to the session so that the llm would know what session/project to reference in tool calls

* updated to address copilots issues and excluded a local config folder

* I think this resolves the cicd failures

---------

Co-authored-by: pow3rtool <root@pow3rtools>
2026-07-02 16:12:47 -07:00
Patrick Buckley df573b7314 fix(webui): address review feedback on roster eviction and dead guards
- applyRosterSnapshot: null-prototype membership map (a ws id colliding
  with an Object.prototype property name would read as always-seen and
  dodge eviction) and a stable Object.keys snapshot for the eviction
  walk — current-key deletion during for...in is spec-safe, but the
  snapshot is self-evidently order-safe and skips inherited keys.
- _streamingRenderApply: drop the tautological typeof guards around the
  post-render decorators — both are module-local declarations, and the
  surrounding try/catch owns decoration fault tolerance.
2026-07-02 00:32:11 -07:00
Patrick Buckley 3c7a3c1375 fix(webui): wedge-proof the live-session pipeline and de-O(N) hot paths
Long sessions (5000+ messages, several compactions) degraded steadily
and could stop rendering entirely while the backend stayed healthy.
Four hard failure mechanisms, each sufficient on its own:

- Unguarded event pipeline: one throw escaping onmessage/handleEvent
  (e.g. renderMarkdown stack overflow on a few KB of nested "> ")
  stranded the streaming refs, so every later delta painted into the
  poisoned segment. stream_end now resets segment refs BEFORE the
  finalize render with a plain-text fallback (the coordinator pane's
  existing pattern); onmessage guards both parse and dispatch;
  renderMarkdown is depth-capped with throw-safe footnote-scope
  accounting; the streaming buffer is marked rendered only on success.

- Rebuild-vs-live races: clear_ui/replay_truncated re-renders wiped
  events painted in the snapshot->replaceChildren window (never
  redelivered) and left deltas writing into detached nodes. Rebuilds
  now quiesce the event stream behind a token-owned queue flushed
  after the render; streaming refs reset on every rebuild path
  including refetch FAILURE; a mid-stream replay_truncated defers its
  re-sync to the idle edge instead of dropping the repair.

- Ignored recovery floor: the global stream now handles node_snapshot
  and replay_truncated. Roster eviction (with a "Session ended" toast
  for open panes) happens only from the stream-ordered snapshot; the
  REST resync is merge-only and r.ok-gated so a mid-restart 503 body
  cannot read as an authoritative empty roster.

- Unbounded growth: _agentCards released on rebuild — deliberately NOT
  on transport-only reconnects, which must preserve the maps or the
  next child event builds a duplicate card; orphan grace timers
  cancelled on full reload/destroy; toast queue capped with duplicate
  coalescing; diff previews capped at 400 rendered lines (the
  spread-append could throw RangeError before the approval gate
  painted) with the omission notice below the scroll box; raw results
  clamped at 64KiB.

Per-event O(N) work removed from the hot paths: thinking-indicator
instance ref; near-bottom cached from a passive scroll listener and
re-checked at rAF pin time (a user scroll-up landing in the coalescing
window wins; ResizeObserver re-engages follow after layout changes);
rAF-coalesced outer and per-stream scroll pins; self-healing
call_id->row/stream lookup caches; verdict lookup scoped to the row's
batch; tracked retry holder; queue-controller Set replaces the
whole-transcript idle sweep; rail renders rAF-coalesced; coordinator
child_ws_state ticks routed to single-row updates (full render only on
terminal-boundary crossings) with observer unobserve on replace.

Also: the coordinator SSE-error 401 probe is un-deadened (raw fetch —
authFetch never resolves a 401 — with the body inspected so a
version_mismatch still takes auth.js's upgrade-reload path via the new
noteVersionMismatch export); the console cluster-SSE reconnect timer
is tracked across logout; the mermaid render chain is rejection-proof
per link and paints errors on the containers the failing link had
already claimed.

Measured with scripts/livepass.py --perf (n=3000 history + 20-turn
live storm): full replay 1060ms -> 238ms; re-render cycles 836-1071ms
-> ~94ms flat; chunk path now flat vs transcript size; worst longtask
1080ms -> ~500ms; agent-card retention across rebuilds 4 -> 0.

Known limit (needs a server-side event watermark on /history): a turn
completing inside the refetch window can paint twice after the quiesce
flush — rare, visible, and strictly better than the silent loss it
replaces.
2026-07-02 00:32:11 -07:00
Patrick Buckley 41e7d5b7d7 feat(livepass): add long-session perf harness (--perf)
New /perf/livepass.html mounts the real InteractivePane at production
scroll geometry and drives production-shaped SSE events through
handleEvent/replayHistory in real time (no virtual-time budget, no
forced reduced-motion — both corrupt the measurement), reporting:
replayHistory wall time at N messages, per-turn live-storm cost on top
of that transcript, tool_output_chunk throughput, busy/idle churn,
heap + node + agent-card counts across repeated replay cycles (the
detached-DOM leak probe), and longtask counts.

The --perf runner builds, serves, and launches headless Chrome with
--js-flags=--expose-gc and --enable-precise-memory-info so heap
numbers are real floors; the page POSTs its JSON report to
/perf/report. Reports carry a per-attempt run token the runner
validates, so a straggler POST from a killed prior attempt cannot be
misattributed to the next size, and the wait loop polls the Chrome
process so a sandbox startup failure bails to the --no-sandbox
fallback in seconds instead of burning the full timeout.
2026-07-02 00:32:11 -07:00
Patrick Buckley ca23f2876c fix(ci): refuse fork PRs in the vendor-js dispatch path
The workflow_dispatch input is an arbitrary PR number, and the job used
only headRefName to pick the checkout ref. For a fork PR that is a bare
branch name that can collide with a branch in this repo, so the job
(contents:write, ends in git push) would operate on that unrelated
branch. Resolve isCrossRepository alongside headRefName and fail loudly
unless the PR head lives in this repository.
2026-07-01 21:32:45 -07:00
Patrick Buckley a9898fdd6c fix(ci): gate workflow_run publishing to same-repo tag pushes
The publish and docker workflows trigger on workflow_run of CI, which
fires for every CI completion — including CI runs for pull requests
from forks — and always executes with this repo's secrets, tokens, and
the pypi environment. The only gate was CI success, so fork-PR CI runs
spawned publish jobs in the upstream context; actions/checkout v7's
fork-checkout refusal was the only thing that stopped one on 2026-06-30.
A fork PR whose head is an upstream-tagged commit would have passed the
tag check and reached the upload with valid OIDC.

Both workflows now require the triggering CI run to be a push event,
from this repository, with head_branch starting with 'v' — CI's push
trigger only matches main/stable/* branches and v* tags, so that is
necessarily a tag run (verified: tag-push runs report the tag name as
head_branch). Checkouts no longer persist the token while the tree's
build backend executes, and publishes are no longer cancellable
mid-upload (a half-uploaded release cannot be re-run cleanly because
PyPI rejects duplicate files).

vendor-js hardening in the same pass: gate on the immutable PR author
instead of github.actor, require a same-repo head before pushing to the
PR branch with contents:write, and pass github.head_ref through env
instead of interpolating it into the script body.
2026-07-01 21:32:45 -07:00
Patrick Buckley c71cc749d9 chore: bump version to 1.7.0a6 2026-07-01 21:07:52 -07:00
Patrick Buckley 2fb80cb88f fix(compaction): count fixed prompt overhead in the carry budget
Review finding on #751: the carry invariant omitted the system message
and tool definitions, which ride every request — at shipped defaults
reserve + 2 carries + margin lands exactly at the window, so any real
prompt overhead pushed the post-compaction send over it, and the
overflow backstop re-compacts WITHOUT the carries.

spare now subtracts system_tokens + tool_def_tokens (the same terms the
_estimated_prompt_tokens fallback counts), making
overhead + reserve + carries*budget + margin <= window hold by
construction. Invariant test pinned at shipped defaults with a 4k-token
synthetic prompt; a monotonicity test pins that the term is live; exact-
arithmetic tests isolate the overhead explicitly.
2026-07-01 21:06:31 -07:00
Patrick Buckley 2dd0688d45 fix(compaction): carry the plan and the ask across compaction verbatim
The definition review found the two control-relevant crossings paraphrased:
the model's wind-down spill (recorded on the cooperative advisory, then
handed to the summarizer with everything else) and the user's last message
(clipped to 400 chars in the continuation hint). Both now cross copied.

- carry_spill: when the model stopped because it was advised to wrap up,
  its final turn's text is shell-concatenated onto the summary under
  '## Wind-down (verbatim)', ahead of '## Continue'. The summarizer still
  reads the spill; its paraphrase is no longer the only survivor.
- _carry_budget_chars(carries): ~25% of the window per carry, sized so ALL
  concurrent carries fit the spare after the summary output reserve —
  spill + hint fire together at the end-of-turn site, and independent
  sizing stacked reserve + 2*(cw/4) + margin past the window at default
  config. Floored at 2000 chars; oversize content keeps head + tail.
- _truncate_block's marker reports the original size ('truncated — N chars
  total'), and a truncated carry adds one line telling the model the full
  text remains in history and recall can retrieve it.
- Summary turns carry source="compaction" (in-memory swap and checkpoint
  reconstruction); _find_turn_boundaries and _generate_title test the tag
  instead of the label string, so a user who literally types
  '[Conversation summary]' stays a real turn.
- The send-loop overflow backstop now passes my_generation, closing the
  compact-and-swap race every other compaction site already guards.

Tests: tests/test_compaction_crossing.py (tags on both paths, literal-label
boundary, budget arithmetic incl. the double-carry invariant at shipped
defaults, verbatim/truncated carries, spill semantics, forwarding); existing
suites updated for the tagged label turns and the new kwargs.
2026-07-01 21:06:31 -07:00
Patrick Buckley 848f123985 feat(recall): scope the recall tool to the compacted past
After a compaction, storage keeps the full transcript and the in-context
summary is a cache over it — recall is the model's re-derivation path back
into the originals. Un-scoped, its results duplicated the live context.

- search_history gains exclude_ws_id/exclude_after: the excluded ws's rows
  above the boundary (the live segment, already in context) are dropped in
  SQL via one shared fragment; rows at or below it — the summarized-away
  past — stay searchable. A never-compacted ws is excluded whole:
  everything is live. Other workstreams untouched.
- New get_compaction_checkpoint(ws_id) reads the latest marker's persisted
  watermark (distinct from get_compaction_watermark, which computes what a
  NEW compaction would use); the meta decoder is single-sourced with the
  resume slice (parse_checkpoint_watermark) so the two boundary consumers
  cannot drift.
- _exec_recall reads the boundary fresh at execution (a compaction that ran
  while the item was queued is respected) and labels own-conversation hits
  '(earlier in this conversation, compacted)'. Storage errors degrade to
  whole-ws exclusion — less information, never duplicates. Known limit
  (documented): a forked session excludes only its own ws, so inherited
  parent rows remain searchable — harmless duplication bounded by tenancy.
- NUDGE_COMPACTION_RESUME teaches the path: the summary is a digest, not
  the record, and recall can search the compacted portion.
- /history deliberately unchanged: a human browsing history has no context
  to duplicate.

Tests: tests/test_recall_compaction_scope.py — checkpoint reads (none /
marker / latest-wins / malformed-as-live), the exclusion matrix, the
composed tenancy+exclusion query with both filters dropping rows, exec
plumbing and labeling, the nudge line; cross-backend.
2026-07-01 21:05:57 -07:00
renovate[bot] 76241ab703 chore(deps): lock file maintenance 2026-07-01 19:47:04 -07:00
renovate[bot] 409875e296 chore(deps): update ghcr.io/astral-sh/uv docker tag to v0.11.26 2026-07-01 19:46:50 -07:00
Patrick Buckley 8e4f32c93a chore(ci): allow Renovate PRs through Claude Code review
Renovate opens PRs as a bot actor, which claude-code-action's default
human-actor check rejects — Renovate's dependency-bump PRs were never
getting reviewed.
2026-07-01 19:44:27 -07:00
Patrick Buckley 3e4c1931a1 fix(storage): scope conversation-history search by project tenancy
search_history / search_history_recent searched every workstream's rows
regardless of who asked. Pre-projects that matched the trusted-team
deployment shape; with private projects (062) it became a cross-tenant
read — the recall tool and /history returned private-project rows to
non-members.

Both methods take a keyword-only user_id (protocol, sqlite, postgresql)
scoped by one portable SQL predicate (HISTORY_VISIBILITY_SCOPE_SQL)
mirroring WorkstreamProjectVisibility: a row hides only when its
workstream links to an existing private project and the user is neither
the workstream creator, the project owner, nor a member. Applied in SQL
so limit/offset pagination stays honest; COALESCE guards the
NULL-creator row, which plain <> would leak.

The recall tool pins the scope identity at prepare time (the mcp_user_id
discipline) and fails loudly on an unpinned item; /history scopes to the
acting user; user_id=None (single-user CLI lanes) stays unscoped.

Tests: cross-backend visibility matrix, ws_visible parity pin,
marker-exclusion composition, LIKE-fallback path, prepare-pin plumbing.
2026-07-01 19:29:20 -07:00
renovate[bot] df7926215b chore(deps): update github actions 2026-07-01 19:26:18 -07:00
Patrick Buckley f583fb06db fix(projects): address PR review feedback — drop redundant asyncio import, precise failure-mode docs, format
The redundant function-local asyncio import in project_resources_endpoint
shadowed the module-level one. resolve_workstream_owner's docstring now
maps the failure modes precisely: a failed ROW lookup is fail-soft 404
(get_workstream_row degrades to None, pre-existing behaviour), while the
fail-closed 403 applies once a row is resolved and the project gate's
storage lookup fails — in-memory workstreams 403 on a gate blip,
not-loaded ones 404 at the row fetch first. Plus ruff-format on the
visibility test file (edited via script, so the local format hook never
saw it).
2026-07-01 18:01:50 -07:00
Patrick Buckley 4bca60c56c fix(projects): close review-found tenancy leaks + correctness regressions
Max-effort review findings on the visibility feature, worst first:

Leaks — the filter was sound where it ran, but several surfaces never
carried project_id to gate on:
- cluster_snapshot served the raw collector state with no filter at all;
  it now gets the same per-request tenancy treatment as its siblings
- console pseudo-node coordinator rows + emit_console_ws_created,
  the interactive-create ws_created event, and the poll-diff ws_created
  now carry project_id/user_id (parity with their filtered siblings —
  a missing field failed open, and a missing user_id over-hid the
  creator's own workstreams)
- the SSE snapshot's overview total/state histogram is re-derived from
  the filtered rows instead of leaking pre-filter counts

Correctness:
- saved list pages with OFFSET until it fills its 50-row window instead
  of filtering after the LIMIT (a caller's own rows at position 51+
  used to vanish behind other tenants' private rows); scan capped at 20
  pages, logged when hit
- an INHERITED project_id whose project was since deleted no longer
  400s coordinator child spawns — the dangling link is dropped; explicit
  unknown ids still 400, revoked membership still 403s
- the SSE filter keeps a per-connection unresolved map: a storage blip
  suppresses a row without pinning it hidden until reconnect (re-judged
  on later events, rate-limited); definitive verdicts settle as before
- bypass principals (service / admin.cluster.inspect) get payloads
  untouched — no row drops, no overview rewrite

Consistency and robustness:
- dashboard + saved-list visibility checks moved off the event loop
  (executor), matching every sibling site
- list_project_attachments chunks its IN() at 500 ids per statement
- ws_visible/ensure_project_attachable now share one _project_grants
  predicate so the tenancy rule can't diverge
- resolve_workstream_owner's docstring states the deliberate
  fail-closed trade for project-attached rows during DB outages
- the workstreams-for-project ordering test asserts strict order on a
  forced timestamp instead of a vacuous set fallback
2026-07-01 18:01:50 -07:00
Patrick Buckley 80b8997b88 fix(projects): full-suite findings — type-guard the visibility gate, bind acting user without breaking send stubs
ws_visible only treats real strings as project links (a test double or
corrupted value means no-project, not private-and-denied), the mgr-path
project_id is coerced likewise, and the HTTP send path binds the acting
user via a getattr-guarded bind_acting_user call inside the fresh-turn
closure instead of a send() kwarg — per-kind session stubs with explicit
send signatures keep working. Row-shape contract tests (interactive +
coordinator twins) grow the intentional project_id key.
2026-07-01 18:01:50 -07:00
Patrick Buckley bf9299de1a feat(projects): saved-list project column + per-project resources view
Dashboard saved-sessions lists now carry and render the workstream's
project: SavedWorkstreamInfo gains project_id (the saved projection was
extended in the visibility change), SavedColumns grows a PROJECT column
(name resolved through the shared projects data layer, searchable via
the filter haystack, re-rendered when the async project cache fills),
inserted on both the webui saved-workstreams and console saved-sessions
tables.

Manage → governance → Projects rows are now expandable (same
interaction contract as the Users tab's OIDC panel): a per-project
resources panel lists the project's workstreams (kind/state/updated),
referenced attachments (metadata + ws-scoped download link through the
console's node proxy), and the project-scoped memory count. Backed by
GET /v1/api/projects/{id}/resources (project.read + per-project ACL,
collection off the event loop) over two new storage queries —
list_workstreams_for_project (first consumer of idx_workstreams_project)
and list_project_attachments (conversation ref-list walk, metadata only,
first-referencing ws per blob, pruned blobs skipped).
2026-07-01 18:01:50 -07:00
Patrick Buckley fbfd170ca6 feat(projects): enforce private-project workstream visibility server-side
Workstreams attached to a private project were listed and reachable for
every authenticated user — only the scope tier was checked. Add a
tenancy predicate (WorkstreamProjectVisibility: private → project
owner/members, the workstream's own creator, service scope, or
admin.cluster.inspect; public/dangling/no project → unchanged
trusted-team visibility; membership itself is the grant — deliberately
NOT gated on the project.read capability, which guards the management
API) and apply it at every surface:

- listings: saved sessions (project_id + owner tail-appended to
  list_workstreams_with_history on both backends), active list, node
  dashboard, console cluster list (pre-pagination via a collector
  row_filter so totals stay honest), node detail
- console tier-1 SSE: per-connection snapshot filtering + a hidden-set
  for sparse follow-up events; ws_created project lookups run on the
  executor, membership changes take effect on reconnect
- row access: resolve_workstream_owner 403s private-project rows for
  non-members, covering every interactive ws-scoped verb via
  tenant_check (console coordinator lane stays on its privileged
  admin.coordinator gate)
- create: ensure_project_attachable gates explicit and parent-inherited
  project_id on both create validators (unknown project 400s instead of
  minting a dangling link)
2026-07-01 18:01:50 -07:00
Patrick Buckley 71c34839d9 fix(mcp): resolve oauth_user credentials for the acting user on shared workstreams
Per-user MCP credential resolution was bound once at session construction
to the persisted workstream owner, so on a shared workstream every sender
executed oauth_user tools under the creator's tokens (and saw the
creator's tool catalog). Bind the authenticated initiator of each turn
(send + retry paths) as the session's acting user: dispatch, catalog
merge, visibility gates, and consent flows now follow whoever is driving,
with the owner as fallback for CLI / eval / scheduled / internal turns.

Rebinding swaps the user-scoped tool/resource/prompt listeners (identity
is the (user_id, callback) pair), fire-and-forget primes the acting
user's pools, and rebuilds the merged tool list. Prepared tool items pin
the identity at prepare time so an item pending approval executes under
the user whose turn requested it, not whoever binds later. Queued
mid-turn interjections deliberately do not rebind (no mid-turn
credential switch).
2026-07-01 18:01:50 -07:00
Patrick Buckley f923351953 docs(hypothesis): harden the harness definition after peer review
Corrections: the middle-form re-separation names its true mechanism
(restarting specs or refusal-event predicates; within-run retries never
touch F), the standard-Borel aside admits belief-state coordinates, the
drift-slack display binds its variable, effect-record status gains a
`none` value (never launched) distinct from rolled_back and unknown,
and parsing is assigned to the inner readout R with the gate as pure
authorization.

Structure: the trusted principal as the provenance lattice's single
widening writer; two-rank control (authority vs plan) with a
rank-neutrality corollary; the narrow-only rule for learned checks;
pi's never-lower filter joins the deterministic core; gate TOCTOU and
cross-run serialization; a composition law for harness trees (four
correspondences) with delegation as monotone attenuation.

Appendix: new worked entries for resume (journal-before-dispatch),
parallel proposals (the batch gate), derived and durable state (the
provenance meet rule), and ambient authority (per-action capability).
Claims numbered C1-C8; two falsifiers added (certificate compression;
working-set probe anchored in streaming lower bounds).

Grounding: adds Ramadge-Wonham supervisory control, RL shielding, and
Dayan's successor representation; repairs the Positivity/Skolem gloss
and two citation characterizations. All 18 external citations verified
against their sources.
2026-07-01 18:01:07 -07:00
Patrick Buckley a7cab83dd1 fix(mcp): address pre-push review findings
A max-effort review of the branch before pushing surfaced six defects, several
introduced by this branch's own commits. All fixed:

[0]+[3] oauth priming (refined). Fully non-destructive priming never cleared a
genuinely-revoked grant — the dead token stayed "consented", its tools never
entered the catalog, and (bug) the PERMANENT branch returned before arming the
cooldown, so every session re-hit the AS with a dead refresh token. Root cause:
invalid_grant (PERMANENT) is a RELIABLE dead-grant signal (RFC 6749 §5.2), so
deferring its revoke was net-harmful. Renamed the flag revoke_on_dead_grant ->
revoke_ambiguous_escalation: priming now revokes genuinely-dead grants (permanent
/ expired-no-refresh) so the catalog isn't stranded cold behind a phantom token,
and defers ONLY the sustained-UNCLASSIFIABLE (ambiguous) escalation to lazy
dispatch — the case the "don't revoke an unused server's grant on a
misclassification" concern actually applies to. The cooldown is armed before the
ambiguous path, so the deferred case can't hammer the AS either.

[1] server.py. _public_server_status (operator refresh/reconnect endpoints)
didn't forward the new scope, so after per-user scoping every warm oauth_user
server rendered disconnected/empty there. Now passes aggregate=True (operator /
approve-scoped cluster view, matching the admin console).

[5] _is_dead_transport. The widened httpx.TimeoutException swept in
httpx.PoolTimeout — pool saturation, NOT a dead connection — so transient load
would evict a healthy session and trip the shared breaker for all users.
Narrowed to Connect/Read/WriteTimeout (kept NetworkError, RemoteProtocolError).

[8] _is_dead_transport. The exact-message "session terminated" fallback still
fired on a healthy session-owning server's protocol error with that message. The
SDK-synthesized code 32600 is the only deterministic signal (the message is
application-controlled), so match the code ALONE and drop the message fallback.

[11] cleanup. The dead-transport except block was triplicated across
call_tool_sync / read_resource_sync / get_prompt_sync — the exact drift this
branch had to repair. Extracted _record_and_evict_on_dead_transport.

Tests updated/added: prime revokes-permanent / defers-ambiguous (drives the real
resolver both ways); PoolTimeout-is-not-dead; exact-"Session terminated"-message
stays alive; _public_server_status aggregate. 836 test_mcp_* green, ruff + mypy
clean.
2026-06-30 19:30:20 -07:00
Patrick Buckley b28e8bac80 feat(mcp): admin-scoped aggregate view for oauth_user server status
Resolves the one regression the user-scoping in 0c28b0ce introduced: the admin
console reaches the read-scoped /mcp-status endpoint via the console proxy with
the ADMIN's forwarded identity, so per-user scoping made oauth_user servers show
as the admin's own (usually empty) pool instead of the cluster-health "in use by
anyone" aggregate.

Add an `aggregate` flag (default False) through get_all_server_status ->
get_server_status -> _oauth_user_server_status. When set, connected + a
representative catalog reflect ANY user's warm pool. internal_mcp_status gates it
on the admin.mcp permission: holders (who already see consent counts + server
config — the proxy forwards permissions via create_jwt, repopulated on validate)
get the aggregate; every other read-scoped caller stays strictly per-user, so the
cross-user catalog leak stays closed. Static-server status is unaffected.

Tests: manager-level aggregate-sees-any-user, and an endpoint-level gating test
asserting admin.mcp -> aggregate=True / read+approve-without-it -> aggregate=False.
2026-06-30 19:30:20 -07:00
Patrick Buckley 48f4c41442 fix(mcp): scope oauth_user server status to the requesting user
Follow-up to f585c47b (review finding #4). _oauth_user_server_status derived
connected + tools/resources/prompts counts from warm[0] — an arbitrary user's
pool entry — and get_all_server_status surfaced that to every read-scoped
caller of /v1/api/_internal/mcp-status, ignoring who was asking. So user B saw
user A's oauth_user server as connected with A's catalog size, over the wire
(connected + the three counts are in _READ_STATUS_PUBLIC_KEYS; user_pools /
auth_type are stripped). Before f585c47b these servers were absent from the
read map entirely.

Thread user_id through get_all_server_status -> get_server_status ->
_oauth_user_server_status; the warm-pool filter now matches uid == user_id, so
connected + counts reflect ONLY the requester's own pool. internal_mcp_status
passes _auth_user_id(request); an empty/absent principal (user_id falsy) sees
oauth_user servers as not-connected. Static-server status is unaffected (the
new param defaults to None and is ignored for them).

Note: the admin console (admin.mcp) reaches this same read endpoint via the
console proxy, which forwards the ADMIN's identity — so an admin now sees an
oauth_user server scoped to their OWN pool (typically not-connected) rather
than the prior any-user aggregate. Server-global health (circuit_open / error /
consecutive_failures) is unchanged, and the consented-users-count is a separate
aggregate. Restoring an aggregate in-use pill for admins (without re-leaking
per-user catalogs) would need a privilege-aware aggregate mode + admin.js
change — deferred.

Tests: updated TestOAuthUserServerStatus to the scoped signature, added the
cross-user isolation regression (user B sees neither A's connected flag nor A's
catalog size) and a no-user-context case.
2026-06-30 19:30:20 -07:00
Patrick Buckley 7f50fbefad fix(mcp/oauth): make session-start pool priming non-destructive
Follow-up to f585c47b (review finding #5/#6). f585c47b routed
_prime_user_pools through get_user_access_token_classified to refresh expired
tokens at session start (closing the chicken-and-egg where an expired token
stranded the pool). But that resolver also REVOKES a grant (delete_user_token
+ token_revoked audit) on a permanent-classified refresh failure — and priming
runs for EVERY consented server, so a single misclassified AS hiccup (e.g.
invalid_grant during a key-rotation window) could now delete a working grant
for a server the user isn't even using this session. The _prime_one comment
still claimed "priming can never revoke a live grant" — no longer true.

Add revoke_on_dead_grant: bool = True to get_user_access_token_classified. When
False, the four would-revoke sites return refresh_failed_transient with the
token left in place instead of deleting it. _prime_one passes False: priming
still refreshes+persists refreshable tokens (f585c47b's fix intact) but never
revokes — the authoritative revoke stays on the lazy-dispatch path, where the
user actually invokes the tool and a permanent failure means re-consent anyway.

Replaces the vacuous prime test (which fully stubbed the resolver, so its
"never revoke" assertion was meaningless) with a test that drives the REAL
resolver and pins both directions: same permanent failure, same code path,
revoke_on_dead_grant=False keeps the token / =True (lazy default) deletes it.
2026-06-30 19:30:20 -07:00
Patrick Buckley b8addd55c0 fix(mcp): complete dead-transport handling + harden oauth_user status
Follow-up to f585c47b. Three correctness gaps from a max-depth review of
that commit, all in the same dead-transport / session-corpse family it set
out to close.

1. read_resource_sync and get_prompt_sync were left on the old
   BrokenPipe/ConnectionReset/EOF-only eviction guard, so a dead
   streamable-http transport (McpError(CONNECTION_CLOSED), anyio
   ClosedResourceError, server-restarted session) reused the corpse session
   forever — the exact restart-hang call_tool_sync already fixes, just for
   resources and prompts. Both now route through _is_dead_transport and
   evict + trip the breaker like the tool-call path.

2. _is_dead_transport matched a bare "session terminated"/"session not
   found" substring, so a healthy session-owning MCP server (game/shell)
   rejecting a stale id with those words was misclassified as transport
   death — evicting the live session and opening the SHARED per-server
   breaker for every user after 3 such rejections. Now anchored on the
   SDK's deterministic synthesized code (32600, pinned as a named constant)
   with its exact message as a forward-compat fallback. The client never
   receives "session not found" for a real dead transport (the SDK discards
   the server's 404 body), so the tightening loses no coverage.

3. _is_dead_transport omitted httpx's read/write/close NetworkError leaves
   and the whole TimeoutException family (Read/Write/Pool timeouts are NOT
   builtin TimeoutError), so a stream that died on an idle read timeout —
   the dominant idle-death mode — fell through to "other" and the corpse
   was reused. Broadened to httpx.NetworkError | TimeoutException |
   RemoteProtocolError (LocalProtocolError, our own bug, stays excluded).

Also: _oauth_user_server_status iterated _user_pool_entries without a
list() snapshot, so a concurrent pool insert/evict on the mcp-loop thread
could raise "dictionary changed size during iteration" and 500 the status
endpoint. Snapshot like the sibling get_all_server_status does.

Adds TestIsDeadTransport (direct classifier unit tests, incl. the
healthy-"session not found"-is-not-dead and httpx-coverage regressions) and
resource/prompt eviction tests. All 8 behavior-change tests fail on the
pre-fix source and pass with the fix.
2026-06-30 19:30:20 -07:00
pow3rtool f585c47b7d mcp dead transport fix and token refresh 2026-06-30 15:22:23 -07:00
Patrick Buckley ee3a0297ea fix(compaction): don't classify a recognized rate-limit as context overflow
_stop_retrying calls _is_ctx_overflow with no exception-class gate of its own,
so a retryable 429 whose token-quota text contains an overflow phrase (e.g.
"... maximum number of tokens allowed per minute ...") was treated as a
deterministic overflow and made non-retryable.

Gate _is_ctx_overflow on "not a known backend class": an overflow is never a
recognized error (it arrives as BadRequestError/InternalServerError, neither in
_BACKEND_KNOWN_EXC_NAMES), so excluding known classes can't suppress a real
overflow while keeping a 429 retryable across every caller (the retry gates,
send-loop recovery, chunker, task_agent loop, formatter). _format_backend_error
drops its now-redundant inline class check.

Addresses Copilot review feedback on #740.
2026-06-30 03:47:12 -07:00
Patrick Buckley c6e5794125 fix(compaction): recover from context overflow on resume across providers
A session created under the openai-compatible provider and resumed under the
anthropic-compatible provider (same vLLM model) failed with an opaque
InternalError instead of recovering. Root cause: vLLM returns a context-window
overflow as HTTP 400 BadRequestError on /v1/chat/completions but HTTP 500
InternalServerError on /v1/messages, and the rehydrated resume payload overflowed
the window. The 500 was retried four times then surfaced as a bare class name.

- Detect overflow by message text, not exception class (_is_ctx_overflow),
  shared across the fatal-error formatter, both stream-retry gates, the send-loop
  recovery, the chunker, and the task_agent loop. Overflow is non-retryable
  (deterministic; no backoff). Phrasing is overflow-specific so a token-quota
  rate-limit isn't misclassified.
- Proactive pre-send compaction (Layer A): when already over the hard ceiling,
  compact once before the first stream so a resume that arrives over-window (or
  follows a switch to a smaller-context model, with no prior compaction) doesn't
  go out blind. Generation-guarded end to end so an orphaned or superseded send
  can never swap the live generation's history.
- Binary-subdivision chunker: an over-window summary batch is split in half and
  the partials merged (~log2(N) calls, not one per block); a lone over-window
  block is truncated progressively down to a floor before bailing irreducible.
- Cooperative cancellation honored through compaction; send() consumes its own
  generation's cancel signal on exit, so a stale cancel can't block a later
  idle /compact and a live cancel is never disarmed.
- _format_backend_error surfaces "Context window exceeded ..." instead of an
  opaque InternalServerError, and only for unrecognized classes.
- retry/rewind, the continuation hint, and title generation all exclude the
  synthetic [Conversation summary] turn so they can't target the label.
- task_agent salvages a sub-agent's partial work on any terminal error (not only
  overflow), re-raising only when there is nothing to salvage.
2026-06-30 03:47:12 -07:00
renovate[bot] 85b62860b2 chore(deps): update actions/checkout action to v7 2026-06-30 03:46:34 -07:00
renovate[bot] 74cf4e92aa chore(deps): pin dependencies 2026-06-30 01:38:15 -07:00
Patrick Buckley 6572b53c89 docs: refine HYPOTHESIS.md harness definition
- Add a plain-terms gloss of the claim (shell/plant split up front)
- Add a 'Converged-upon' grounding subsection: independent corroboration
  from capabilities, control theory, software architecture, and LM theory
- State provenance as a precondition of the reach-avoid certificate
  (CaMeL control/data-flow separation), not just an entry point to police
- Drop redundant 'none' from the effect-record status enum; normalize
  minor notation (A_bot, h->N)
- Fix stray backslash-escaped quotes that rendered literally
2026-06-28 21:59:44 -07:00
Patrick Buckley 7f1329d3b0 fix(memory): atomic single-statement upsert for memory save/update (#735)
* fix(memory): atomic single-statement upsert for memory save/update

save_structured_memory used "try INSERT -> catch IntegrityError ->
SELECT + UPDATE". On PostgreSQL a model saving the same key twice in a
turn logged a uq_smem_name_scope violation on the failing INSERT, and the
pattern threw + caught an exception on every update.

Replace it with one statement: a new StorageBackend.upsert_structured_memory
on both backends emitting INSERT ... ON CONFLICT (name, scope, scope_id)
DO UPDATE ... RETURNING.  It returns (row, was_update) -- the full saved
row and whether an existing row was updated -- like Django's
update_or_create; was_update is the supplied (fresh) memory_id differing
from the returned id.  save_structured_memory is a thin wrapper over it.

description / mem_type of None mean "leave unset": the column default
applies on insert and the stored value is kept on conflict; an explicit
value (including "" / "general") overwrites -- so clearing a description or
setting type back to "general" now persists, where the prior
"if mem_type != 'general'" / "if description" semantics silently dropped it.
The memory tool and the memories HTTP endpoint pass None for omitted fields
and read effective type/scope from the returned row; the HTTP endpoint
returns that row directly (one query, no follow-up SELECT).

Removes the now-unused update_structured_memory primitive and its dead
STRUCTURED_MEMORY_MUTABLE constant.  Adds cross-backend storage tests and a
session tool-path test (preserve-on-omit / overwrite-on-explicit), run on
PostgreSQL via --storage-backend -- the save-over-existing path was
previously SQLite-only.

* docs(memory): clarify upsert was_update precondition

Lead the upsert_structured_memory docstring with the behavioral contract
(callers MUST supply a fresh unique memory_id) rather than the internal
id-comparison mechanism, so a future caller can't reuse an existing id and
silently get was_update=False on a real update.
2026-06-28 20:24:20 -07:00
Patrick Buckley 5004858032 ci(claude): grant write permission so Claude reviews/replies can post
claude-code-review.yml granted pull-requests: read, so the Claude reviewer
ran green but its post step was permission-denied (permission_denials_count:
3) and posted no review on the PR. Bump to pull-requests: write so it can
post the review + inline comments.

claude.yml (the @claude responder) had the same read-only block and would
silently fail to post a reply; widen it to pull-requests + issues: write.

contents stays read -- no repo-push capability is granted. Both workflows
remain gated (the reviewer to same-repo PRs via head.repo.full_name ==
github.repository; the responder to @claude from OWNER/MEMBER/COLLABORATOR),
so write is scoped to already-trusted triggers.
2026-06-28 20:09:05 -07:00
Patrick Buckley de60127c45 fix(memory): don't recompose system prefix on memory write
Injected memories ride in the cached system block, so calling
_init_system_messages() on every memory save/update rebuilt the prompt
prefix and busted the provider prompt cache (a full system + history
re-write) -- for a memory the model already holds via the tool result.

memory(save) now only invalidates the per-turn search cache, so an
in-turn memory(search)/(list) still reflects the write; the new memory
folds into the prefix at the next natural recompose or the next session.

Also drop the redundant _init_system_messages() in the /reason handler:
reasoning effort rides in request kwargs (output_config / thinking), not
the composed prompt, so it recomposed to byte-identical output.

Add a chain-level test through the real _exec_memory -> no-recompose path
(asserts prefix unchanged, search cache invalidated, next recompose folds
the memory in). The prior memory tests either drove _init_system_messages
directly or patched it out, so this path was uncovered.
2026-06-28 18:31:11 -07:00
Patrick Buckley c7e0358aaf Add Claude Code GitHub Workflow (#733)
* "Claude PR Assistant workflow"

* "Claude Code Review workflow"

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-06-28 17:00:27 -07:00
Patrick Buckley bbadd00ac0 chore: bump version to 1.7.0a5 2026-06-28 04:12:06 -07:00
Patrick Buckley 8dd356b7e6 fix(task-agent): keep sub-tool steps nested + preserve denial reasons
Address the Copilot review on #732 plus a task-agent sub-tool nesting
race surfaced alongside it.

Nesting (web UI):
- A sub-tool step whose task_agent row hasn't painted yet (the 4-wide
  tool pool's ordering window) buffers and nests when the row lands,
  instead of escaping to a top-level row that looks main-harness-issued.
- A row that never paints (id-correlation mismatch / aborted agent)
  escapes its buffered steps back to a visible top-level paint after a
  grace window, so steps are never buffered invisibly or leaked.
- The nested card survives the parent row's pending->resolved rebuild; a
  call_id reused across turns builds a fresh card rather than stealing the
  prior agent's steps.
- tool_info routes through the same nesting path (no duplicate top-level
  row); a namespaced sub-tool result no longer grafts onto an unrelated
  top-level row.

Denial reasons (backend):
- Preserve the specific denial reason a gate already stamped (operator
  feedback, or the matched policy pattern; web and CLI contracts) instead
  of clobbering it with a flat "Denied by user" -- in both the sub-agent
  and the main tool loop.

Verified with the livepass task_agent harness (race + orphan-escape
scenarios, headless) and unit tests.
2026-06-28 04:09:30 -07:00
Patrick Buckley 77cb76c006 feat(task-agent): recall sub-trajectory + per-agent read isolation
Final chunk of the task_agent modernization: rebuild a finished task
agent's card from /history (reload / reopen while the workstream is in
memory) and isolate each sub-agent's file-read tracking.

Recall: _project_agent_steps projects a sub-agent's trajectory into step
items (FIFO-per-call_id pairing via _iter_agent_tool_results, shared with
_cancel_ledger; output/arguments/count capped); _stash_agent_trajectory
keeps them on the UI in an LRU-bounded store; make_history_handler
attaches them as agent_steps to each task_agent tool_call, and
replayHistory/_replayAgentCard rebuild the collapsed card. In-memory only
(durable persistence deferred); a cold/evicted entry renders the flat
parent row ("not retained"), never a fabricated 0-step card.

Read isolation: _read_files (the blind-overwrite guard's memory) is now
per-sub-agent via the _active_read_files contextvar -- _exec_task copies
the parent's set on spawn and merges the agent's reads back on
completion, so a sibling in the 4-wide pool can't suppress another
agent's guard.

Also: _exec_task now self-reports the task_agent tool_result on every
path (the parent loop only reports error/denied results centrally) --
without it the live card never completed and a failed task recorded
is_error=False in the canonical trajectory. is_error flows from
_tool_error_flags to the recalled step; on_info suppression is per-thread
so a parallel sibling tool's progress isn't dropped.
2026-06-28 04:09:30 -07:00
Patrick Buckley ca7958329a feat(task-agent): nest sub-tool steps in an expandable card
Route a task agent's sub-tool events (tool_pending / approve_request,
tagged with parent_call_id) into a collapsible card under the task_agent
row, replacing the blue on_info turn-legs.

- conversation.js / interactive.js: buildAgentCardBody +
  _routeAgentItems / _ensureAgentCard nest steps by parent_call_id.
  Collapsed by default (a task agent can run 100+ steps and the parent
  fans out many in parallel); the label carries the live count + state.
  Auto-expand when a nested approval is pending so the blocking prompt
  can't hide behind the toggle.
- session.py / session_ui_base.py: on_agent_step paints auto-tool step
  rows; namespace child call_ids by parent so the 4-wide task pool can't
  collide on local sequential ids (call_0); suppress sub-agent on_info on
  the web pane (no call_id to nest by — the card carries steps + result).
- cli.py: on_agent_step prints a dim step leg (no card on the CLI, which
  keeps its on_info).
- livepass.py: task-agent card harness driving the real InteractivePane.
2026-06-28 04:09:30 -07:00
Patrick Buckley 65eaacb341 feat(task-agent): Turn-IR sub-harness + parent-tagged step events
Rebuild the task_agent sub-harness on the canonical Turn trajectory (build list[Turn], lower via dicts_from_turns at the wire boundary) instead of hand-rolled OpenAI dicts; the cancel-ledger helpers read Turns.

Tag each sub-tool's events with parent_call_id via a lock-guarded child registry stamped centrally in SessionUIBase._enqueue, so a later UI can nest a task agent's steps under its card. Getattr-guarded on the session side so CLI/eval/test UIs are unaffected.

Behaviour-preserving (same wire shape, same cancellation semantics); the parent tag is wire-invisible and unconsumed until the frontend card lands.
2026-06-28 04:09:30 -07:00
Patrick Buckley 9837214414 fix(compaction): persist checkpoint markers to bound resume rehydration (#731)
Compaction swapped a session's in-memory history for a summary but left the full
transcript in storage, so resume() reloaded all of it -- on a long session, or
one switched to a smaller-context model, the rehydrated context overflowed the
model window and deadlocked the first post-resume send.

Persist a `_source="compaction"` marker (summary + watermark) on compaction;
resume rehydrates [summary] + [rows after the watermark] instead of the full
transcript. Full history stays in storage for /history, export, and audit;
markers are filtered from display, search, and export, and rewind/retry
truncation is floored at the marker so the summary's backing is never deleted.
The watermark and search filters count real transcript rows only. No migration.
2026-06-27 23:36:24 -07:00
Patrick Buckley 2b0b1cf73e chore: bump version to 1.7.0a4 2026-06-27 17:20:21 -07:00
Patrick Buckley 7263b31536 fix(compaction): cap summary input budget to true capacity (review)
Address PR #730 review. _summary_input_budget_chars now caps the _MIN_SUMMARY_BUDGET_CHARS floor at the true input capacity (input_tokens), so output reserve + budgeted input + prompt always fit context_window; on a window too small to summarize it returns a sub-floor budget and _pack_blocks bails as irreducible instead of overflowing the summary call. After the half-window output-reserve bound this only affected sub-~2048-token windows, but it was a real edge.

Clarify the _CompactionIrreducibleError docstring: chunked compaction never drops or fabricates whole turns, but a single oversized block is still head/tail-truncated as summary input via _truncate_block.

Add test_budget_never_exceeds_true_input_capacity.
2026-06-27 17:06:18 -07:00
Patrick Buckley 6b6c220986 fix(compaction): chunk the summary call so it can't overflow
The compaction summary ran as a single model call sized by the per-message
token estimate, which disagreed with the head+tail-capped formatted text, so a
long history could overflow the summary call itself; the old prefix-fit also
silently dropped the most-recent messages.

Summarize the whole selection via _summarize_blocks: greedily pack the
formatted blocks into batches that each fit the summary call's own input budget
(_summary_input_budget_chars), summarize each, and recursively merge the
partials until they collapse to one. The common case (it all fits) stays a
single call. Bail to the existing False path when the input is irreducible
rather than fabricate a summary; a mid-chunk failure leaves messages untouched
(atomic swap only on full success).

Bound the summary output reserve to half the context window
(_summary_output_tokens), used by BOTH the input-budget sizing and the actual
call. compact_max_tokens defaults to the full window (32768); clamped only by
max_output_tokens it reserved the entire context for output, flooring the input
budget so compaction overflowed (or bailed as irreducible) at the
default/small-window config that needs it most. Large windows are unaffected
(compact_max_tokens stays binding).

Guard an empty summary (keep history instead of swapping in nothing and
reporting success). Fold tool-def tokens into the _last_usage-less estimate AND
the post-compaction usage anchor, so the compact-before-truncate budget doesn't
over-state free space by the tool-def count. Single-source the shared
compactor/merge prompt section (_COMPACT_OUTPUT_FORMAT) and the tool-def sizing
(_tool_def_chars/_tool_def_tokens). A just-resumed session (no _last_usage) now
counts tool-def tokens so it doesn't undercount and skip proactive compaction
until its first reply re-anchors the estimate.

Prepush review follow-ups: generation-guard the end-of-turn auto-compaction and
its resume turn so a force-cancel during the slow summary call can't compact or
persist under a new generation (matching the mid-turn and end-of-loop guards);
single-source the soft-threshold predicate (_over_soft) shared by the mid-turn
policy, _compaction_owed, and the end-of-turn check; add tests for the
pre-attempted-compaction guard and the recursion depth ceiling.
2026-06-27 17:06:18 -07:00
Patrick Buckley 65d1552ffa fix(session): provider-anchored context budget + cooperative compaction
Unify truncation and compaction on one provider-anchored fullness measure
(_estimated_prompt_tokens), closing the 80-100% dead zone where tool output
was truncated but compaction never fired. Make compaction cooperative: advise
the model to wrap up and record its plan, compact if it continues, auto-resume
after a cooperative stop, and compact-before-truncate (preserving the in-flight
tool-call turn). Floor auto_compact_pct at 0.1 (invalid 0 -> default 0.8).
2026-06-27 17:06:18 -07:00
Patrick Buckley 9f54a97cc6 fix(understone): rebalance early game and add inn turn refresh
The opening hours were a gold/HP death spiral: a fresh hero spent more gold
healing a fight than the kill paid, mid-tier foes out-damaged a starting HP
bar, the map gave no read on where harder foes spawned, and a spent day left
the player idle until the UTC rollover. This eases the on-ramp across both
shipped worlds.

Economy
- Healer drops from 2 to 1 gold per HP, so topping up no longer outruns income.
- Starting purse 20 -> 37: enough to buy the cheapest armor and one potion up
  front, a one-point DEF bump plus a heal cushion the player chooses to spend.

Combat
- Tier 2-4 common foes lose 1 ATK each, trimming the burst that could halve or
  end a fresh hero in a single bout. Rares and the boss are untouched.

Wayfinding
- The road glyph changes from "=" to a shaded path that reads as one continuous
  road in every orientation; "=" only looked right horizontally and broke into
  stacked dashes on vertical runs. Cinder's basalt path gets the same treatment
  with a crosshatch glyph free in its palette.

Rest
- Sleeping at the inn now rolls a spent adventurer into a fresh day's turns (it
  already fully heals). The top-up fires only at zero turns, so it never banks
  past the daily cap.

Verified: full suite green (+2 rest tests, ruff/mypy clean); the greedy balance
bot still clears the world 11/12 seeds at an unchanged pace on both packs.
2026-06-27 09:40:03 -07:00
Patrick Buckley 0e1972e6aa chore: bump version to 1.7.0a3 2026-06-27 01:22:33 -07:00
Patrick Buckley b1542ad62d fix(title): reliable titles on thinking models; defer utility temperature
Auto-title generation and manual refresh stopped producing titles on
reasoning models (the cluster serves qwen3.6). The title call capped
max_tokens at 200, so the model's think pass consumed the whole budget and
content came back empty (finish_reason=length) -> the title was skipped.
Both paths share _generate_title, so both broke.

Title path:
- Raise the title completion to 2048 tokens so reasoning finishes and the
  title text actually lands.
- Recover the title from content (never reasoning): reuse the canonical
  _strip_reasoning (handles <think>/<reasoning>, paired or unclosed) plus a
  backstop for the opener-absent </think> shape some templates emit, take
  the first non-empty line, and peel a "Title:" label and wrapping
  markdown/quote decoration. Internal punctuation is preserved. Cap at 80 to
  match the manual-alias bound.

Temperature:
- _utility_completion no longer hard-codes a temperature; it defaults to the
  session/registry value the main turn uses. Title (was 0.7/0.3), web-fetch
  extraction (was 0.2), and compaction all defer. Hard-coding a constant
  fought thinking/no-temp models and silently overrode an explicit [models.*]
  temperature; the provider still gates temperature per model.

Tests: title sanitization across think/reasoning variants, truncation, and a
trailing-prose case; utility-completion temperature deferral + explicit
override.
2026-06-27 01:21:56 -07:00
Patrick Buckley b2c93ce15a fix(composer): show server error text on a rejected send
The send POST's `!r.ok` guard threw a bare `send_http_<status>`, which both
send `.catch` handlers render verbatim — so a rejected send surfaced as
"Connection error: send_http_400" instead of the server's reason. Read the
`{error}` body and throw that, falling back to the status code when a wedged
proxy answers non-JSON (502/504 HTML) so it can't become an "Unexpected
token <" error. Applied to interactive and coordinator.

Also correct the queue-controller comments: a dequeue releases no
"server-side reservation" (queued messages are text-only and dequeue_message
just pops the entry), and onAfterDequeue is wired by coordinator too — not
omitted.
2026-06-27 00:09:44 -07:00
Patrick Buckley 5f0b5bb173 fix(composer): node-proxy-correct, reliable queued-message dismiss
The queued-message dismiss DELETE hardcoded /v1/api/workstreams without
the node-proxy prefix, so cancelling a queued message on a proxied
(remote-node) interactive workstream hit the console root, 404'd, and
the message was delivered anyway -- the dismiss silently did nothing.

composer_queue:
- Prefix getBase() onto the dequeue DELETE; interactive passes getBase
  (mirrors the attachment controller). Coordinator stays at base "".
- Never remove the card before the server confirms the cancel: removed
  -> drop the card; not_found (already drained) -> promote to a sent
  bubble + "already sent" notice; 404 (reaped session) -> terminal drop;
  error/timeout -> re-enable + "couldn't remove" notice.
- Bound the DELETE with a 15s AbortController (Promise.race fallback when
  AbortController is absent) so a wedged node can't freeze the card.
- a11y: aria-disabled (not the real disabled attribute) keeps keyboard
  focus on the dismiss control; in-flight state shown via aria-busy + CSS.

consumers (interactive, coordinator):
- Bound the send POST with the same 15s timeout so a pre-bind dismiss
  can't strand the card when the POST hangs.
- r.ok guard so a rejected send (4xx/5xx error body) surfaces as an
  error instead of being promoted as "delivered".
- Coordinator wires onNotice -> appendText.
2026-06-27 00:09:44 -07:00
Patrick Buckley f2e48166f4 fix(lowering): warn when operator context would fold onto an assistant turn
Operator-context system turns must follow a user/tool input turn — producers
maintain this via the user/tool drain seams plus the synthetic wake turn, so an
assistant predecessor is unreachable today. Add a fail-loud guard so a future
producer that breaks the invariant surfaces in logs instead of silently splicing
operator markup into the model's own prior output.

Logged, not raised: it degrades to a fold, since the nonce still gates operator
trust regardless of the host turn, so the harm is out-of-distribution voice
rather than a trust breach — disproportionate to crash a turn over.
2026-06-26 19:37:01 -07:00
Patrick Buckley 2c1ec9c230 fix(fence): guard detection_pattern against an empty tag set
Address PR review feedback:

- detection_pattern(()) with an empty tag set compiled to an overly-broad regex
  (the empty alternation matches any [start ...]/[end ...] run), which would turn
  the forgery scanner into a false-positive generator. Reject an empty or
  all-empty tag set up front. Not reachable from the sole caller today, but it is
  a public, security-relevant helper.
- Clarify build_operator_instruction_declaration's docstring: the trusted region
  is delimited by both the start and end markers (each carrying the nonce), not
  just the opening marker.
2026-06-26 19:37:01 -07:00
Patrick Buckley a318265946 fix(fence): bracket trust-fence markers instead of angle-bracket XML
Swap the trust-fence marker shape from <tag_nonce>...</tag_nonce> to
[start tag_nonce]...[end tag_nonce] for both the operator fold (system-reminder)
and the output-guard judge (tool_output). Angle-bracket markup pushed some local
models out of distribution and toward emitting their own turn-structure tokens:
chat templates built around rigid <...>-style structural tokens derail once a
few folded reminders accumulate. The start/end keywords carry no slash (no </ or
[/ closing-tag shape) and read as ordinary text.

Single-source the shape in fence.py (_OPEN_KW/_CLOSE_KW + detection_pattern) so
wrap, neutralize, the forgery/leak detector, and both trust declarations track
one definition. The nonce still rides both boundaries (unforgeable close); the
leak-vs-forgery split and the forge-in / break-out defang are preserved. The
fold is wire-only, so there is no migration; the legacy persisted-envelope
readers keep the old shape.

Add regression tests pinning each trust declaration to fence.wrap's emission so
a future keyword change fails loudly instead of silently desyncing the anchors.
2026-06-26 19:37:01 -07:00
Patrick Buckley 2169559d6e feat(projects): governed project containers — memory scope, grouping, manage UI (#724)
* feat(projects): governed project containers — memory scope, grouping, manage UI

A workstream can attach to a project: a first-class, shareable resource
container that owns a `project` memory scope, groups conversations, and is
managed from the console.

Storage / migration 062: projects + project_members tables, workstreams.
project_id, and the memory type default project→general; grants
project.{create,read,write,delete} (admin-default).

Recall + writes: project memory is recalled iff the workstream is attached AND
the user has access (owner ∨ member ∨ public-for-read), resolved once at session
construction; coordinators recall it too. New saves default to the project when
attached + writable; the save and delete paths are write-gated; deleting a
project purges its scoped memory; archived projects aren't recalled.

Access = RBAC capability ∧ per-project ACL (auth.resolve_project_access, a
single-fetch resolver); visibility changes, member management, and delete are
owner-only.

API: project CRUD routes on both the server and console; project_id threaded
through workstream creation, spawn inheritance, the cluster-create proxy, the
dashboard / snapshot / coordinator row builders, and the collector deltas.

UI: a project picker with an inline "+ New project" creator in every creation
box (console launcher + standalone dialog + dashboard); group-by-project in the
rail; a project badge in the composer and on dashboard rows; a console manage
tab (list + create/edit + members shelves). The admin Memories view gains
coordinator/project scope filters and human scope labels (name, not hex). The
memory tool schema documents the project scope and the attach-aware default.

* fix(projects): client refresh hardening, creator race guard, SDK project_id

Addresses PR #724 review feedback plus two bugs found while validating it.

- projects.js refreshProjects: a non-OK status (e.g. 403 when the caller
  lacks project.read) or a network/parse error no longer blanks the cache
  or masquerades as "no projects" -- the prior cache is preserved, the
  failure is recorded (new projectsError()) and warned. Honors the
  long-standing "a transient error can't blank the rail" docstring.
- projects.js _fp: the fingerprint separators were raw control bytes,
  which made git treat the whole file as binary (no reviewable diff).
  Rewritten as escape sequences instead of raw bytes -- behavior is
  byte-identical at runtime.
- project_creator.js: createProject() could reject unhandled (authFetch
  throws on network/401; r.json() throws on a non-JSON body), leaving the
  widget stuck busy/disabled. Added a .catch, plus a generation guard so a
  create whose widget was cancelled/reopened mid-flight drops its result
  instead of selecting a project the user backed out of.
- types.ts: add project_id to CreateWorkstreamRequest / WorkstreamInfo /
  DashboardWorkstream to match the server schemas (was SDK-invisible).
- test_project_api.py: move side-effecting HTTP calls out of asserts so
  the requests run even under python -O.

* fix(projects): JSON.stringify the cache fingerprint, drop control-byte separators

_fp joined fields/rows on raw NUL/SOH bytes, which made projects.js read as binary to git. Replace with a collision-proof, escape-free JSON.stringify encoding -- same change-detection semantics, zero embedded control characters.
2026-06-26 17:24:06 -07:00
Patrick Buckley c7d8acb6a5 fix(effect-status): harden effect_status decode + fix tests for typed synth
- Turn.effect_status also catches TypeError: a corrupt non-string meta value
  (e.g. a dict that survived into the column) would otherwise crash a consumer
  on access, since EffectStatus(non-str) raises TypeError, not ValueError.
  Degrade to None, mirroring the meta decoders (Copilot review).
- test_lowering: the wire-repair synth now carries the _effect_status side
  channel (stripped before the provider wire) — assert it.
- test_session_mcp_dispatch_error: the _capture stub swallows the new status
  kwarg via **_ so it stays signature-compatible with _report_tool_result.
2026-06-26 08:38:31 -07:00
Patrick Buckley b74a5e116b feat(effect-status): type tool dispositions, not just prose
The unknown / none / committed distinction the cancel and timeout paths
carry lived only in the result's free text — a deterministic reader (a
re-issue guard, owner-side compensation) couldn't recover it without
parsing prose. Promote it to a typed EffectStatus on the canonical Turn.

- EffectStatus (committed/none/unknown/partial/rolled_back) rides
  TurnMeta.extra["effect_status"] — wire-invisible like the other meta
  side channels: the model still reads the body, deterministic code reads
  the type.
- Persisted in the role-exclusive conversations.meta column (source_meta
  rides SYSTEM turns, effect_status rides TOOL turns), routed by role in
  reconstruct_turns. No migration; survives reload for the audit trail.
- Producer seam: _report_tool_result(status=) + a _tool_status dict popped
  at the fold, mirroring _tool_error_flags.
- Populated where the disposition is already determined: UNKNOWN at the six
  unobserved sites (bash / MCP-tool timeout, bash SIGKILL-cancel, cancel
  synthesis, wire-repair) and a precise none/partial/unknown on a cancelled
  task agent (shared _cancel_ledger so the typed status and the prose
  disposition can't disagree). Ordinary results stay unset.

Only the unknown/none split is load-bearing (HYPOTHESIS.md effect-record
appendix: unknown, never none); the full per-effect reversibility list
stays deferred. Thread A of the effect-record work; Thread B (per-tool
Smart-Approval floor + reversibility surfacing) follows.
2026-06-26 08:38:31 -07:00
Patrick Buckley c1ca742b54 fix(tools): timed-out side-effecting tools read UNKNOWN, not a flat failure
A bash command SIGKILL'd at its deadline and a timed-out MCP tool call are
killed / abandoned mid-flight, so their side effects are as unobserved as a
cancelled call's. Both read as a definitive "timed out after Ns", which invites
a blind re-run (a double-send) exactly as a dropped record invites an orphan.

Route both through a shared TIMEOUT_OUTCOME_CLAUSE so they read "Outcome
UNKNOWN ... do not assume it did not run, reconcile before re-issuing" — the
same "unknown, never none" discipline cancellation already follows
(HYPOTHESIS.md effect-record appendix). bash also keeps any partial stdout
captured before the kill, mirroring the cancel path.

Read-only timeouts (search, MCP resource/prompt reads) stay a plain failure:
an idempotent read has nothing to reconcile, so the reconcile advice would be
misleading there.
2026-06-26 07:32:35 -07:00
Patrick Buckley 16ac3f19b5 docs(hypothesis): gate-placement & effect-record appendix; scope incompressibility; split the two walls (#721)
* docs(hypothesis): gate-placement & effect-record appendix; scope incompressibility; split the two walls

Refinement + expansion pass on the harness hypothesis.

Appendix (new subsections):
- Gate placement (fail-closed, in practice): γ as a pure, effect-free
  parse-and-authorize; syntactic / user-authorization / structural-intent
  validation; semantic intent as a recursive plant call (a mini-harness),
  not a predicate in γ; "before any invocation" sharpened to "before any
  effect" — reads aren't free, the parser must not act, the output is an
  action too.
- Effect records (what ρ folds back): pins down the
  e = (tool_id, action_id, status, effects, time) shape the body referenced
  twice but never defined; committed/none/unknown trichotomy + a reversibility
  bit, framed explicitly as an open interface, not a result.

Corrections:
- Scope the incompressibility conjecture: split per-step drift by coordinate
  (the shell term is a low-complexity designed descent), so the incompressible
  part is the plant's, not all of W; add the coarse-functional counter-
  possibility (V* is one scalar hitting time, sometimes cheap) and state the
  claim conditionally. Walks back the earlier "the dynamics it certifies are
  the weights" overclaim.
- Split the second wall: the tape / space-O(L) picture follows from the
  autoregressive structure alone; the per-pass TC^0 bound is separate and
  weaker; flag that chaining them is a non-sequitur.

Smaller:
- Concrete justification for the standard-Borel assumption.
- Reading-table rows for the C/Y/A/E spaces and for H_ok/B.
- Daemon note: per-cycle hazard compounds, (1-q)^h over the horizon.
- Minimax: well-posedness caveat for sup over the adversary class Π.
- Note that H_cancel refines the body's deliberately coarse H\H_ok.

Notation (consistency linter clean):
- Brace the subscript A_{⊥} in the new table row (was unbraced — GitHub
  render hazard the linter guards against).
- Daemon cycle-count N → h, freeing N for the fundamental matrix.

* docs(hypothesis): address Copilot review — plain quotes + 'none' status value

- Effect-record status enum: add `none`, which the prose already treats as a
  distinct value ("unknown ... never none"; the committed/none/unknown
  trichotomy). Resolves the enum/prose inconsistency — `none` (no effect) is
  distinct from `rolled_back` (ran, then undone).
- Drop the two backslash-escaped quotes (the incompressibility walk-back and
  the minimax well-posedness caveat) for plain quotes, matching the rest of
  the document. GFM strips the backslash, so they rendered fine; the escapes
  were just unnecessary and inconsistent.
2026-06-26 05:24:32 -07:00
Patrick Buckley c0be383f99 refactor(doctor): replace turnstone-bootstrap with turnstone-doctor (#718)
* refactor(doctor): replace turnstone-bootstrap with turnstone-doctor

turnstone-bootstrap was an LLM setup wizard for Day-0; run.sh now owns install.
Repurpose its LLM/conversation plumbing into turnstone-doctor — a diagnose-only
tool for a running cluster.

- Preflight detects the install kind (docker-compose/systemd/pip/source) from
  config.toml + TURNSTONE_* env, with secret redaction.
- Self-configuring brain resolves the cluster's own model from config/env/storage
  read-only (no migrations, no create_all), falling back to interactive
  selection; the attempt itself is the LLM-backend health check.
- Deterministic version check: installed version, cluster drift via the console's
  authoritative /health, and latest upstream stable/experimental (offline-safe).
- Read-only diagnostic tools (read_file, compose/systemd/journal, http_health,
  check_llm_backend, node_health, finish) behind one secret-scrubbing chokepoint;
  no generic shell, so read-only is structural.
- node_health reaches a node the right way for the detected install kind
  (exec-into-container for compose, direct HTTP otherwise), overridable per node
  for mixed clusters.
- mTLS-aware: forwards [database] SSL params and reports node-mesh mTLS instead of
  mislabelling healthy nodes "unreachable".

init_storage gains a backward-compatible create_tables override for read-only
opens. Entry point turnstone-bootstrap -> turnstone-doctor; README/QUICKSTART/
architecture/docker docs, the bundled compose header, run.sh, and the CI smoke
updated. CHANGELOG deferred.

* fix(doctor): address Copilot + CodeQL review findings on #718

Validated all seven review findings (none false positives) and fixed:

- check_llm_backend now applies the same scheme / metadata-host guard as
  http_health (extracted to _assert_safe_http_url), so a model-supplied
  base_url can't be steered at the cloud metadata endpoint or a file:// URL.
- node_health no longer double-appends the default port when the operator
  passes host:port (regression: 10.0.0.5:8081 -> http://10.0.0.5:8081:8080).
- node_health install_type enum uses "git-source" to match the label the
  rest of the module and the prompt/report show the model (a schema-strict
  provider would otherwise reject the value the model is told to use).
- _read_api_creds takes base_url + api_key as a unit from the first config
  source that defines either field, then env-fills, instead of splicing the
  two across different config files into a pair that exists in no real config.
- _mask_secrets masks assignment-shaped content inside comment lines, so a
  commented-out real secret can't leak through read_file / the report; prose
  comments (no KEY=value shape) still pass through untouched.
- drop the mixed import styles CodeQL flagged in doctor.py and test_doctor.py.

Adds 5 tests; ruff + mypy clean; full doctor suite passes (129).
2026-06-26 04:57:20 -07:00
Patrick Buckley 4baf6f81c3 docs(hypothesis): clarity pass, GitHub-render fixes, consistency linter (#720)
* docs(hypothesis): clarity pass, GitHub-render fixes, consistency linter

Document (HYPOTHESIS.md):
- split the dense "Formal" definition into labeled subsections
- define the load-bearing terms: certificate (proven witness vs measured
  surrogate) and the controller / plant (= M_W) / shell triad
- corrections: three-way drift split (+ r_env), scope the success/safety
  collapse to absorbing refusal, unify tau*->tau_H and drop the orphaned bare tau
- calibrations: pin the incompressibility conjecture (still conjectural),
  mark the interlingua=certificate identity as figure, soften the two-walls trade
- GitHub math rendering: brace command-subscripts (_\bot -> _{\bot}, etc.) so the
  markdown emphasis parser stops breaking inline math; replace R_\# with R_{\sharp}
  (\# unescapes to a raw # in GitHub math)

Linter (lint_hypothesis.py):
- deterministic consistency checks A-G; G adds an orphan/redundant-declaration
  scan that catches the bare-tau failure mode
- residue guards so tau^star, unbraced _\cmd subscripts, and \# cannot return

* fix(hypothesis): make lint_hypothesis.py pass ruff under py311

- precompute the inline-$ count so no backslash sits inside an f-string
  expression (backslashes in f-strings are 3.12+; the project targets 3.11)
- split the one-line import (E401/I001); open HYPOTHESIS.md via a context manager (SIM115)
2026-06-26 03:57:36 -07:00
Patrick Buckley 4aaf6feac4 chore(cancel): address Copilot review nits
- console/server.py: replace a stale hard-coded `session_routes.py:852-854`
  comment reference (already drifted to make_close_handler's signature) with
  a by-name reference to make_close_handler's not-found path.
- test_cancel.py: rename test_marks_most_recent_action_unknown ->
  test_marks_in_flight_action_unknown; the disposition marks the first
  unanswered (in-flight) call, not the most recent — they merely coincide in
  this two-call case.
2026-06-26 03:28:06 -07:00
Patrick Buckley bc93b1f748 fix(cancel): address code-review findings before PR
The multi-stage review of this branch surfaced four major + two minor issues,
three of them in the new cancellation code. All fixed here (bug-3, the stale
generated TS SDK spec, stays deferred — it regenerates out-of-band).

- sec-1: cancelling a coordinator now auto-cascades to its children, but the
  cancel route allows the service-scope bypass while the removed stop_cascade
  gated the same destructive subtree-cancel at no-bypass — a service token
  without admin.coordinator could trigger the cascade. Re-assert the
  no-service-bypass gate inside _cascade_cancel_to_children, so a plain cancel
  by an under-privileged service token still cancels the coordinator's own
  turn but no longer cascades.
- bug-1: _cancelled_agent_disposition took the LAST issued tool call as the
  in-flight one. _run_agent executes a turn's calls sequentially, so the
  in-flight call is the FIRST unanswered one — taking the last inverted
  unknown/none on a multi-call turn (a SIGKILL'd bash mislabelled "not
  started", the never-run tail mislabelled UNKNOWN, inviting a re-run of the
  destructive call). Fixed to first-unanswered.
- perf-1: the per-child cancel fan-out was awaited inline before the cancel's
  200, so a cancel could block for tens of seconds on slow/unreachable
  children. Return the fan-out as a response BackgroundTask so it runs after
  the 200 (trigger, not drain).
- bug-2: the initial-send worker (_run_initial) cleared _worker_running
  unconditionally — the same clobber the session_worker guard just fixed.
  Apply the identity guard there too.
- sec-2: restore the per-child cascade audit row (coordinator.cancel_cascaded)
  the removed stop_cascade wrote; it had become log-only.
- q-1: extract the shared UNKNOWN-outcome clause (UNOBSERVED_OUTCOME_CLAUSE)
  so the wire-repair fallback and the session-layer synthesis can't drift.
2026-06-26 03:28:06 -07:00
Patrick Buckley 03f82521d9 fix(cancel): close workstream self-cancel gaps from the completeness review
Follow-up to the cancellation review — harden how cancel interacts with a
workstream's OWN turn and tools, not just its children and agents.

- wait_for_workstream: the wait loop holds no cancel handle and blocks on the
  child-event bus, so a cancelled coordinator parked in a wait stayed pinned
  for up to WAIT_MAX_TIMEOUT (600s). Add a cooperative check to the ~2s
  progress heartbeat — it raises GenerationCancelled, which propagates out of
  the otherwise cancel-blind wait (~2s abort).
- spawn_batch: stop creating the rest of the children once cancel is observed;
  already-spawned children stay recorded (they are live, durably parent-linked
  workstreams), the remainder are marked not-spawned.
- session worker: only clear _worker_running if this thread is still the
  current worker, so a late-finishing abandoned worker (force-cancel) can't
  clobber a live successor's flag — which would let a third send spawn a
  duplicate worker on the same session.
- bash silent-cancel: a SIGKILL'd silent command now records outcome-UNKNOWN
  (is_error, partial output kept) instead of a clean "Cancelled by user." that
  read as a successful empty result on replay.
- wire-repair: the last-resort orphan disposition now reads outcome-UNKNOWN,
  matching the cooperative-cancel message (unknown, never none).

Deferred: MCP / web_fetch / web_search remain uninterruptible mid-call,
bounded by tool_timeout; only bash is truly preemptible.
2026-06-26 03:28:06 -07:00
Patrick Buckley 776430d860 feat(cancel): honest cancellation dispositions + coordinator subtree propagation
A cancelled agent previously discarded its own ledger and reported a bare
"(task interrupted by user)" — fabricating the *outcome* (read downstream
as "nothing happened"), which invites a double-send as readily as a
dropped record causes an orphan. Make the fold-back honest, and propagate
an owner's cancel down the coordinator subtree.

- task_agent (single + parallel): on cancel, fold back a deterministic
  disposition built from the agent's in-memory ledger — actions completed,
  the in-flight action flagged outcome-UNKNOWN, and not-started calls —
  instead of the opaque interrupted string.
- coordinator cancel now auto-propagates to its direct children via a
  post_cancel hook on the shared cancel handler (cooperative fan-out; no
  blocking drain).
- synthesized cancelled tool results now read outcome-UNKNOWN rather than
  implying the call never ran.
- remove the now-redundant stop_cascade operator endpoint (handler, route,
  OpenAPI spec + schema, tests, docs); a coordinator cancel supersedes it.
2026-06-26 03:28:06 -07:00
Patrick Buckley fafc2d5617 fix(mcp): prune the refresh lock alongside backoff on the missing/decrypt path
Review follow-up (#717). The bug-1 fix made the transient keep-path retain the
per-(user, server) refresh lock for serialization, so the lock entry now lingers
after a transient failure. When the token then vanishes (missing) or goes
undecryptable, _no_token_result pruned only the backoff entry and left the lock
entry stranded, so mcp_oauth_refresh_locks could grow on that path. Drop both
sibling dicts in _no_token_result (removing the now-redundant explicit
_drop_refresh_lock on the in-lock decrypt return); the regression test asserts
both are pruned on the missing-after-transient path.
2026-06-25 23:13:30 -07:00
Patrick Buckley 800b561f56 fix(mcp): classify OAuth refresh failures so neither a blip revokes consent nor a dead grant strands the user
Follow-up to #714 (Entra OBO, #682). A refresh failure deleted the user token +
emitted token_revoked regardless of cause, so a transient AS/network blip during
a forced refresh (the live 401-retry path) permanently revoked consent
cluster-wide. Fixing only that, though, opens the dual failure: a genuinely-dead
grant the AS reports in a non-standard shape would now be kept forever and the
user stranded on a retryable error with no re-consent path. This classifies the
failure three ways so each is handled correctly.

Classification (_classify_refresh_failure): MCPOAuthRefreshFailed carries a
_RefreshFailureClass instead of a bool —
- PERMANENT (revoke + re-consent): an explicit dead-grant / re-consent signal —
  invalid_grant at any 4xx (400/401/403), invalid_scope, or an OIDC
  interaction-required code (interaction_required / login_required /
  consent_required / account_selection_required) the AS surfaces.
- TRANSIENT (keep, retry, never escalate): infrastructure (network, 5xx, 429,
  malformed body) and operator-fixable codes (invalid_client, invalid_request,
  unauthorized_client, unsupported_grant_type, temporarily_unavailable) —
  re-consenting the user can't fix a bad client_secret, and an outage must not
  revoke consent however long it lasts.
- AMBIGUOUS (keep, but escalate after a run): a 400/401 we can't map to a
  standard code. A one-off can't revoke, but an uninterrupted streak past a
  threshold escalates to re-consent so a dead grant in a non-standard shape
  can't strand the user. Infra transients reset the streak, so an outage never
  escalates.

Concurrency: do NOT drop the per-(user,server) refresh lock on the keep-the-token
path. Evicting it while the token is still live let a second concurrent caller
mint a fresh lock and refresh the same token in parallel; with refresh-token
rotation the second send reuses the consumed token, gets invalid_grant, and
spuriously revokes — the exact bug this commit prevents. The async-with still
releases the lock on return; the registry entry is pruned only when the token is
actually refreshed or revoked. Bit SQLite single-node hardest, where the pg
advisory lock is a no-op.

perf: a per-(user,server) cooldown short-circuits the token-endpoint round-trip
for a brief window after a transient failure, so a down AS isn't hit once per
tool call; self-heals when the window expires. Plus the lock-free in-flight key
set that collapses concurrent session-start pool primes (single mcp-loop thread).

dispatch/FE: the transient kind maps to a retryable mcp_refresh_unavailable
structured error (not mcp_consent_required); the FE titles it "Temporarily
unavailable" under a new soft "transient" category (amber, not the red hard-error
styling) in both stylesheets, with no wrong re-consent button.

tests: invalid_client kept (pins the discriminator on the error code, not the 4xx
status), single ambiguous 400 kept, 403 invalid_grant revokes, interaction_required
revokes, ambiguous streak escalates at the threshold, sustained 5xx never escalates
(outage safety), and the cooldown skips the second AS round-trip — all through the
real AS HTTP boundary.
2026-06-25 23:13:30 -07:00
copilot-swe-agent[bot] de271dc2f9 docs: remove Ollama from run.sh local backend list 2026-06-25 21:59:54 -07:00
Patrick Buckley 090f31c5c4 docs: drop Ollama from local-model lists (README + bootstrap wizard) 2026-06-25 21:38:49 -07:00
Patrick Buckley b939919560 fix(mcp): harden Entra OBO OAuth review follow-ups for #706
Follow-up review of the #706 on-behalf-of / Entra ID MCP changes (#682).

security (PKCE downgrade): the AS-metadata "assume S256 when
code_challenge_methods_supported is absent" relaxation applied to BOTH the
RFC 8414 oauth-authorization-server document and the OIDC openid-configuration
document. Per RFC 8414 an omitted field on the oauth-authorization-server
document means the AS does NOT support PKCE, so this was fail-open. The client
always sends code_challenge_method=S256, making this discovery check the only
pre-flight that the AS enforces PKCE. Track which document won discovery and
assume S256 only for the OIDC document; the RFC 8414 document now fails closed.
Also log which discovery profile (rfc8414 vs oidc) answered, for operators
debugging an enterprise AS.

bug (consent loss): session-start pool priming called the refreshing token
lookup for every cold oauth_user server. A near-expiry token triggered a
refresh, and a transient refresh failure (network/5xx/429) deletes the token
and emits token_revoked — so a blip during a cold-pool warm (e.g. after a
reboot) silently revoked consent across servers the user wasn't even using.
Priming now reads the token directly and skips missing/near-expiry tokens;
a refresh that may fail stays on the lazy dispatch path.

perf/UX (blocking redirect): the OAuth callback awaited prime_user_server
(default 20s timeout), holding the consent redirect on a slow/unreachable MCP
server. Replaced with fire-and-forget schedule_prime_user_server that schedules
onto the mcp-loop (GC-safe, no unreferenced request-loop task) and returns at
once.

perf: prime a user's pools concurrently under a bound instead of serially, so
one slow upstream can't stall the rest.

hygiene: log (not silently swallow) prime scheduling failures at session start;
add exc_info to the prime-failure warning; guard run_coroutine_threadsafe
against a closed mcp-loop.

tests: per-document S256 + OIDC-fallback discovery cases; pool priming
(non-destructive on near-expiry, skips connected) and bound-token rotation
reconnect.
2026-06-25 20:42:22 -07:00
github-actions[bot] 0ed8d19db5 chore: download vendored JS files 2026-06-25 19:42:08 -07:00
renovate[bot] 8e362986cc chore(deps): update dependency mermaid to v11.16.0 2026-06-25 19:42:08 -07:00
metaclassing 76e9d0a4f1 Address remaining blockers to entra id on behalf of flow for user impersonation to mcp servers (#706)
* This is a collection of little snippits to resolve all the OBO flow problems required to get this talking to entra id for on behalf of user impersonating to protected mcp servers. we make sure turnstone checks these mcp servers on startup, and address some of microsofts opinionated implementations of oauth2/oidc and metadata provided by the identity provider.

* minor token timeout bugfix

---------

Co-authored-by: root <root@pow3rtools>
2026-06-25 19:26:47 -07:00
renovate[bot] 1c746af36f chore(deps): update actions/checkout action to v7 2026-06-25 19:21:07 -07:00
renovate[bot] c99d1d42ba chore(deps): update ghcr.io/astral-sh/uv docker tag to v0.11.24 2026-06-25 19:18:32 -07:00
Patrick Buckley ff5db73f97 chore(ui): refresh favicon to chevron mark across web entry points
Replace the amber gauge/needle favicon with a teal up-chevron and amber
dot on a dark-teal field. Applied identically to the console, coordinator,
and standalone UI entry points. Self-contained inline SVG data URI; no
network dependency.
2026-06-25 19:18:09 -07:00
renovate[bot] af98fe434a chore(deps): lock file maintenance 2026-06-25 19:17:12 -07:00
renovate[bot] c67b1ce9af chore(deps): update github actions 2026-06-25 19:16:47 -07:00
Claude e7e3135a37 docs(hypothesis): add "Appendix: model implementation" — cancellation as the worked pattern
Establishes the appendix pattern (locate a practical concern in the existing
formal objects; read off the discipline rather than inventing machinery) with
cancellation as the first and only worked example. Not the whole model.

Cancellation semantics, derived from objects already on the page:
- Cancel is a signal → lives in s (Markov). The gate closes on it: γ(s,y)=⊥ while
  live, which blocks pending actions and all future turns with no new machinery.
- In-flight (past γ) disposition is a trinary on the kind of Q_E: cancellable
  (propagate, true end-state), bounded (drain, real e), or opaque/unbounded
  (controller fabricates a synthetic "cancelled" e so the loop can halt).
- Load-bearing rule: ρ may fabricate the acknowledgment but not the outcome — an
  unobserved outcome is `unknown`, never `none` (double-send vs orphan, same bug
  opposite sign).
- New terminal H_cancel ⊆ H\H_ok: non-accepting but safe (outside B), postcondition
  "no action past γ after observed; in-flight drained or recorded unknown; ledger
  consistent."
- Cooperative not preemptive (observed at next γ check, not on send); recursive
  down the task-agent subtree (why task agents are the worst case).
- Compensation is the owner's job (saga, after H_cancel, reads child ledger) — the
  cancelled agent can't know if it's needed; it never observed the outcome.
- Design pressure: prefer bounded/instrumented Q_E over opaque, so cancellation and
  the ledger stay honest (a bash wrapper converts branch 3 -> branch 1).

Linter: balanced, no new collisions. Two ρ role-flags, both false positives
("authorized action" near ρ, correct usage).
2026-06-22 12:16:45 -07:00
Claude d1acded028 docs(hypothesis): round-sixteen (maxima re-run) — semantic-axis fixes the linter cannot see
The linter closed mechanical consistency; this review probes meaning, a separate
axis. Twelve findings, several real corrections, all folded.

Correctness:
- Stationarity overclaim: the supermartingale BOUND survives a nonstationary
  kernel under uniform conditional drift. Time-homogeneity is needed for V* as a
  fixed function, the resolvent/fundamental-matrix identities, and δ-calibration.
- Self-contradiction: "the certificate cannot be proven, only observed" contradicted
  the established "a proven inequality certifies" — reworded to "the architecture
  does not hand it to you; estimated unless separately certified."
- Citation: the TACL result is LOG-precision → logspace-uniform TC⁰ (verified);
  fixed/constant precision is a stronger restriction. Fixed in body and Grounding.

Modeling holes closed:
- Adversary class Π must respect rejection: γ(s,y)=⊥ ⇒ Q_E^α(s,⊥,·)=δ_e0, else the
  adversary resurrects refused side effects.
- R must be a syntactic/verified readout, not a semantic solver — otherwise the
  L-wall is void (compute could hide in R off the ≤L window).
- e must be an effect record (ledger outcome), not just API bytes, since only ρ
  writes external effects into s.
- The displayed M_W(c) freezes endpoint/version/sampler; config changes need a
  state-indexed M_{κ(s)} or K_C — the kernel can't silently depend on config in s.
- The final user-visible response/log is itself an effect: an authorized action
  through γ, or emitted only after an accepted halt.
- m_t must include a token counter and clock for the cap/timeout to be functions of it.

Residue (omissions a collision-linter can't catch):
- Another γ dropped from the K_C Dirac-special-case list.
- τ* mislabeled as "designed code" → the halt test (H) is the code; τ* is its
  emergent hitting time.
- H\H_ok relabeled "non-accepting" (safe refusals outside B; wrong/bad halts
  possibly in B), not uniformly "rejecting/fail-closed."
2026-06-22 12:16:45 -07:00
Claude d61baea8ae docs(hypothesis): round-fifteen — deterministic consistency lint; resolve G collision
Built and ran a static linter (no model): delimiter/emphasis balance, residue
regexes for everything prior rounds fixed, single-capital collision scan, a
definition check for recently-introduced symbols, and a γ/ρ role-neighborhood
scan. Result:
- All balance checks pass; all 10 residue regexes clean (no regression across
  14 rounds); all 12 introduced symbols defined; no display-only symbols.
- γ/ρ scan: one flag, a false positive (the symbol-table cell defines both).
- One real find: G was overloaded — the parser-stop update G(m_t,v) (added in
  round 14) collided with the Green/potential operator G. Renamed the stop-update
  to \mathsf{step}; the Green operator G is now unique.

This closes the consistency axis deterministically rather than by another review.
2026-06-22 12:16:45 -07:00
Claude 4ee148d9c0 docs(hypothesis): round-fourteen (maxima re-run) — round-13 residue, role/contradiction fixes, exact citation
Same prior-maxima full-tools review, re-run. Found mostly residue from round-13's
own edits plus longer-standing inconsistencies. Folded all; left the final
signature line alone (it is the author's call, and it is well-formed — see below).

Round-13 residue:
- 𝒴/𝒴_⊥ split half-committed: 𝒴 already includes ⊥, so R:𝒵→𝒴 and A_Y⊆𝒴 (drop _⊥).
- m_t was added to the inner triple with no dynamics: add m_{t+1}=G(m_t,v), define
  the stop set Stop and τ=inf{t:m_t∈Stop} in both display and prose.
- No-truncation special case had R=id, ill-typed on a triple: R(c,b,m)=c.
- Safety/success "exactly on safe refusals" overclaimed: they differ on any
  B-avoiding non-success run — also safe non-halting / endless safe retry, absent
  a.s. absorption into H∪B.

Role residue (γ does authorization/rejection; ρ does response/fold-back):
- "⊥ branch is what ρ rejects" → γ rejects it.
- "ρ validates response as well as the proposal" → ρ validates the response; γ
  gated the proposal.
- "fail-closed rejection at ρ" (falsification list) → at the gate γ.
- Symbol table still typed Q_E on authorized a → a∈𝒜_⊥ with the no-op; define e_0.

Longer-standing:
- Stochastic-controller contradiction: stochastic control falsifies the
  deterministic special case, not the broader K_C kernel model (round-9 K_C).
- Drift split r=r_shell+r_plant needs an additively separable V̂ or a declared
  attribution scheme.

Citation (verified via search, not the reviewer's say-so):
- TC⁰/log-precision → Merrill & Sabharwal, "The Parallelism Tradeoff", TACL 2023;
  caveat (added autoregressive steps escape it) → Merrill & Sabharwal, "The
  Expressive Power of Transformers with Chain of Thought", ICLR 2024.
2026-06-22 12:16:45 -07:00
Claude 7a403e5d91 docs(hypothesis): round-thirteen (prior-maxima full-tools audit) — consistency-debt cleanup
A cold reviewer given the complete prior-maxima changelog + full tools ran a
consistency audit of the file (it did not use tools for grounding — the gap was
internal). Found 15 real issues, all folded. No new design flaws; this is
accumulated editing debt from 12 rounds of surgical patches.

Half-applied fixes now propagated:
- Inner-kernel display still showed M_W(c)=Law(c_τ) and R:C→Y_⊥ despite the round-12
  triple; made z_t=(c_t,b_t,m_t) primary, R:Z→Y_⊥, M_W=Law(R(z_τ)).
- Append formula still used bare c·v; now suffix_{≤L}(c·v) in the display.
- Tuple still called B a "terminal set"; B is separate (τ_B fires mid-run).
- "halt/ready" survived at line 75 (fixed before only in tuple + table).

Collisions created by added notation:
- γ was both the authorization gate and the RL discount in (I-γP)^{-1}; discount → β.
- B was both the bad set and the dummy measurable set in the pushforward; dummy → A_Y.
- ρ over-credited as the disturbance-rejection margin; for side effects the margin
  is γ (consistent with round-12 irreversibility), ρ validates response/fold-back.

Real error in a prior round:
- The round-12 safety/success distinction collapses under absorbing refusal
  (Pr(τ_Hok<τ_B) requires reaching H_ok, so it is a success form). Split correctly:
  p_succ=Pr(τ_Hok<τ_F), F=B∪(H\Hok); p_safe=Pr(τ_B=∞); they differ on safe refusals.

Typing / hygiene:
- Q_E typed on S×A_⊥ (it is applied to ⊥); 𝒴 declared to include ⊥ (M_W, γ total).
- Controller list omitted γ and mis-listed the readout (specialization-only).
- Defined the previously-bare symbols D={s:E[τ_H]=∞}, μ, the drift r(s), and Π.
- Grounding "verify by measured drift" overstated; a proven inequality certifies,
  empirical drift only checks — reconciled with the body.
2026-06-22 12:16:45 -07:00
Claude afd66df4c0 docs(hypothesis): round-twelve (cold review, sandbox) — inner-state triple, authorization irreversibility, safety vs success
A cold no-priors review (given a local sandbox it did not use — the remaining
work is judgment, not computation). Mostly editorial/formal; its real catches
again concern round-10/11 additions. Folded the substantive ones, declined the
"extract a smaller core" restructure and the formalism padding.

Substantive:
- Inner kernel: replace round-11's awkward "read c_τ as the buffer" overload with
  a clean inner-state triple z_t=(c_t,b_t,m_t) — window, output buffer, parser/
  stop state — and M_W(c,·)=Law(R(z_τ)) from z_0=(c,∅,m_0). Strictly cleaner.
- Authorization is the irreversibility boundary: ρ can reject a bad tool RESPONSE
  but cannot undo an authorized action's side effects, so γ (not ρ) is the last
  line before irreversible effects. And the gate is bypassed if raw y reaches any
  sink (tool, logger, browser, remote) before γ.
- Safety ≠ success: p_ok=Pr(τ_Hok<τ_B) is the safety object (refusal permitted);
  the stricter success object races H_ok against all failure F=B∪(H\Hok). They
  differ exactly on safe refusals.

Precision:
- Foster–Lyapunov positive recurrence needs irreducibility/petite-set hypotheses;
  the absorbing-halt case needs only the weaker supermartingale hitting-time bound.
- Name an initial distribution s_0~μ_0. Fix residual "halt/ready" in the table
  (round 11 fixed only the tuple).
2026-06-22 12:16:45 -07:00
Claude 79cf8dae0b docs(hypothesis): round-eleven (confirmatory cold review) — fix B/terminal partition, fail-closed, output buffer
A JSON-constrained cold review largely validated round 10; its new catches
cluster in round-10's newly-added material.

Fixes (the real ones):
- Terminal-set partition was wrong (a round-10 error): B is NOT a terminal
  component — τ_B can fire mid-run. H now splits into accepting (H_ok) and
  rejecting/fail-closed (H\H_ok); B is a separate unsafe set for reach-avoid.
- Fail-closed generalized: rejection need not be terminal (reject-then-retry is
  valid) — define it as "no unauthorized side effect + land in a safe non-bad
  set," with terminal rejection one case. ρ must also validate the tool RESPONSE
  e (adversarial/malformed Q_E output), not only the model proposal at γ.
- Sliding-window truncation (round-10) loses transcript: the readout R reads a
  separate output buffer, not the truncated c_τ alone.

Precision:
- Deterministic maps are measurable transforms inside the pushforward, not
  literally "outside the integral."
- Absorbing halt H vs the separate (non-absorbing) daemon "ready" recurrence.
- "Syntactic soundness is free" qualified: relative to a formal schema and a
  correct validator.
- State-ablation falsifies Markovity but cannot establish it (necessary, not
  sufficient). Added a readout-typing diagnostic.
2026-06-22 12:16:45 -07:00
Claude 23a79a6c64 docs(hypothesis): round-ten (no-priors review) — authorization gate, minimax fix, raw-vs-correct halting
A cold no-tools external review (lower trust on world-facts, but its catches are
math-internal and correct) found two real bugs plus rigor gaps.

Bugs fixed:
- Verification-after-side-effect (the important one): the kernel ran e~Q_E(s,y)
  then ρ verified, so a tool call's side effect landed before authorization. Add
  a deterministic authorization gate γ:S×Y→A_⊥ between model and environment;
  Q_E now acts on the authorized action γ(s,y); ρ becomes ρ(s,y,a,e). Fail-closed
  is now a property (γ=⊥ ⇒ no-op env ⇒ fold to H\H_ok), not a name.
- Minimax drift display had a free y (introduced round 9): it integrated only
  over e while y~M_W(π(s)). Now integrates over both y and e, adversary as a
  policy α(s,y) over environment kernels, on the authorized action.

Reframing / rigor:
- Raw halting is cheap: a budget counter k gives V=k as a trivial halting
  certificate, so "no certificate by construction" overstated. The missing
  guarantee is correct/safe/successful halting (H_ok, B, p_ok).
- Standard Borel spaces (not merely measurable); define H, H_ok (⊆H), B (∩H_ok=∅)
  and hitting times τ_A up front; add 𝒜 to the tuple.
- Inner kernel: truncate c·v to suffix_{≤L} at the window edge; M_W is a
  probability kernel only via EOS/max-token/timeout/⊥ (else sub-probability +
  cemetery).
- Drift: weaker bound δ≤δ̄<ε gives E[τ]≤V̂/(ε-δ̄); distinguish δ_ν (distributional)
  from δ_sup (worst-case).
- Injection enters π's inputs (retrieval/pages/tool metadata), not only post-model
  Q_E; B needs a side-effect ledger in S. Architectural invariants stated
  (model sees only C; outputs are proposals; γ gates side effects; terminals
  partitioned). Complexity/LBA material marked heuristic, not definitional.
  An LLM-judge verifier is a learned kernel, not deterministic ρ.
2026-06-22 12:16:45 -07:00
Claude 2c943d2634 docs(hypothesis): round-nine (fresh review) — stochastic controller, minimax policy, reach-avoid
A cold external review (same priors, no path-dependence) surfaced three real gaps
the iterative chain missed, plus precision items. Folded in:

Substantive:
- Stochastic controller: the deterministic π,ρ,H are the Dirac special case of a
  controller kernel K_C(s,dc) (routing, sampled retries, ensembles, learned
  routers). Deterministic is the case worth wanting (localizes randomness); the
  split widens, not breaks, under stochastic control.
- Minimax type fix: the adversary chooses a POLICY/kernel, not the realized
  sample. Display is now sup over α of ∫ V(ρ(s,y,e)) Q_E^α(s,y,de), not sup over
  the post-probability e.
- Reach-avoid security: add a bad set B; injection steers toward B (wrong
  acceptance, exfiltration, unauthorized tool use, privilege escalation,
  irreversible effects), so security is reach-avoid p_ok=Pr(τ_{H_ok}<τ_B) with a
  barrier certificate for B, not liveness. B and H_ok added to the tuple.
- Unconditional V*_ok is infinite under any positive pre-acceptance failure
  probability ⇒ the workable object is p_ok (or the regenerative time on restart).

Precision / hygiene:
- Compiler claim scoped to a specific data-flow analysis (not a whole compiler);
  add integrability/optional-stopping conditions to the hitting-time bound.
- Formal hygiene: spaces measurable, τ/τ* stopping times, H absorbing.
- Mid-generation tool calls interleave the loops — clean nesting is an
  idealization needing a finer state machine.
- Soften SSM ("different", not "tighter"); demote "manifold" to informal
  shorthand in the formal section; gloss "all undefined behavior" as "no complete
  formal source-language semantics."

Not changed: V* incompressibility (already labeled conjectural in Grounding).
2026-06-22 12:16:45 -07:00
Claude 6c32b7e3cf docs(hypothesis): round-eight micro-edits — precise compiler claim, well-posedness wording
The review's verdict was "Merge." These are its two correct non-blocking nits;
its third nit (stop adding theorems/caveats) is heeded — nothing else changed.

- Grounding: "the compiler's V is free" → "a classical monotone data-flow
  analysis gets its V for free." A whole compiler does not get termination for
  free; the specific lattice-based analysis does (Kildall).
- Asserted: the Koopman/certificate co-determination "holds only under" →
  "is well-posed only under" the spectral assumptions — avoids asserting truth
  ("holds") for a claim explicitly labeled as not-a-theorem.

Deliberately NOT changed: D → D_H (prose already marks D harness-relative;
subscripting one formula while D stays bare elsewhere would add asymmetry, not
remove it), and no further theorem additions or caveats per the review's note
that more caveating now costs clarity without adding rigor.
2026-06-22 12:16:45 -07:00
Claude 480acd262b docs(hypothesis): round-seven micro-patch — harness-relative reachable, attribution, grounding
The review's verdict was "mergeable"; these are its three optional items plus the
delta-attribution nit.

- δ attribution: sampled-state coverage is an evaluation-protocol property, not a
  weights property. Attribute the noise floor / residual risk to the trained
  weights, the environment, AND the evaluation distribution.
- reachable(L) is harness-relative too (same reason U_H(L) is): rename to
  reachable_H(L) and note the divergent set D is likewise relative to H.
- Split the dense frontier paragraph in two: (1) the SR / fundamental-matrix /
  potential-operator identity with its caveats; (2) the speculative interlingua/
  certificate thesis. No content change.
- Grounding: add the absorbing-chain fundamental matrix (Kemeny & Snell 1960),
  the general-state potential/Green operator (Revuz 1984), and Koopman (Koopman
  1931; Lyapunov-from-eigenfunctions, Mauroy & Mezić 2016) to Proven; mark the
  Koopman/certificate co-determination (spectral-assumption-dependent) and the
  interlingua/certificate identification as Asserted.
2026-06-22 12:16:45 -07:00
Claude 08edb14588 docs(hypothesis): round-six fixes — harness-relative U_H(L), Neumann caveat, predicate split, Koopman hedge
- U(L) is harness-relative: tools and decompositions change membership, so rename
  to U_H(L) and note the shell's verified tools / decompositions determine what
  can be paged or outsourced.
- Countable fundamental matrix: lead with the Neumann series N=Σ Q_tr^n, scope
  countable to convergence, and write (I-Q_tr)^{-1} only when the inverse exists;
  general-state version is the same series read as the potential (Green) operator.
- Distinguish failure modes for V*_ok: infinite under a formal success predicate
  vs undefined if no predicate has been specified.
- Soften the delta "floors" line: mu(D), sampled-coverage, and Var[tau*] drive
  the empirical noise floor / residual risk, they are not literal floors of the
  drift slack.
- Hedge the Koopman bridge (the last frontier thread): the eigenbasis claim
  presumes a diagonalizable, point-spectrum operator — mixing dynamics carry
  continuous spectrum and admit no eigenbasis — and the linearizes/certificate-
  decomposes coincidence holds only for a V in the span of those eigenfunctions.
2026-06-22 12:16:45 -07:00
Claude 3f1be4f963 docs(hypothesis): round-five fixes — finite-mean hitting, potential operator, absorbing failure
Address the round-five review's three precision points (plus the adaptive-adversary
refinement).

- Absorption is finite expected hitting time, not positive recurrence: replace
  "positive-recurrent to H" with "reached in finite expected time," domain
  {s : E_s[τ_H] < ∞}. Positive recurrence stays reserved for the daemon/
  ready-state case (where it is used correctly).
- The fundamental matrix N=(I-Q_tr)^{-1}=Σ Q_tr^n is the finite/countable object;
  the formal model lives on general measurable spaces, so add the general-state
  potential (Green) operator G=Σ Q_tr^n with G·1=V* where the series converges.
  Q_tr now stated as the sub-stochastic kernel restricted to H^c.
- V*_ok is taken on the process where H\H_ok (halting wrong, refusing, failing
  closed) is absorbing failure — so a run that fails closed before acceptance
  has infinite accepting hitting time unless the spec restarts it. This is the
  mechanism by which a U(L) task sends V*_ok → ∞.
- Adaptive adversary: nonstationary Q_{E,n} → time-ordered product; an adaptive
  adversary → controlled / game-value operator (not merely time-indexed).
2026-06-22 12:16:45 -07:00
Claude 509f6e29a3 docs(hypothesis): pre-emptive round-four fixes — halting vs success, fundamental matrix
Fold in the two seams flagged after round three, before the next review pass.

- Limit section now states explicitly that its V*=E[τ*|s] certifies *halting*
  (reaching H at all), not correct halting; defers V*_ok (expected time to an
  accepting H_ok ⊆ H) to the second wall. Removes the latent inconsistency
  between the limit section (plain H) and the U(L) refinement (H_ok).
- Frontier section: the discounted successor-representation resolvent
  (I-γP)^{-1} presumes a discount γ and fixed P the stopped formulation lacks.
  Replace with the correct undiscounted/absorbing object — the fundamental
  matrix N=(I-Q_tr)^{-1}, Q_tr the sub-stochastic transient block — whose row
  sums N·1 are exactly V*. Converts analogy-dressed-as-identity into a true
  identity for the doc's own kernel.
- Mark the "one object seen twice" identity as holding only in the stationary
  regime: under the adversarial Q_{E,n} the resolvent/fundamental matrix become
  a time-ordered product, so identity in the stationary case, analogy beyond.
2026-06-22 12:16:45 -07:00
Claude 78f4b644b4 docs(hypothesis): round-three review fixes — V*_ok vs V*, pushforward readout, tool discharge
Address the round-three review. The substantive one is the V* correction.

- Successful halting vs raw halting (the real conceptual fix): a U(L) task does
  NOT make V*=E[τ_H|s] undefined — the chain can still hit H by failing closed,
  refusing, or returning a wrong answer. Split H from the accepting set H_ok and
  define V*_ok=E[τ_{H_ok}|s]; U(L) blows up V*_ok, not V*. Restate the domain as
  dom_{<∞}(V*_ok) ⊆ reachable(L)\D.
- Tools compute, not just store: the L-wall binds *model-mediated* work; work
  discharged to a verified external tool (solver, interpreter, compiler) runs
  off-context. U(L) now excludes tool-dischargeable work explicitly.
- Readout typing: use the pushforward M_W(c,·)=R_# Law(c_τ) (equivalently the
  conditional law); make R total, R: C → Y_⊥, with the ⊥ branch handled by the
  fail-closed ρ.
- Adversary/history: a history-conditioning adversary needs that history in s,
  else the object is a Markov game requiring further augmentation, not a chain.
- Hedge the LBA claim: "in the variable-L, fixed-precision idealization, the
  model-mediated inner computation behaves like a linear-bounded automaton."
2026-06-22 12:16:45 -07:00
Claude 7c84cc5353 docs(hypothesis): round-two review fixes — readout typing, S vs C, adversarial kernel
Address the three follow-up points on the first review patch.

- Reconcile the model kernel's two types: M_W(c,dy) maps into 𝒴, while the
  transformer line writes M_W(c)=Law(c_τ) over contexts. Add the readout R:
  𝒴 is either c_τ itself (𝒴=𝒞) or a deterministic readout R(c_τ), with
  M_W(c,dy)=Law(R(c_τ)∈dy).
- Separate harness state 𝒮 from model-visible context 𝒞: the L wall binds 𝒞
  (the L×d residual stream), not 𝒮. External stores (files, DBs, vector stores,
  durable memory) are shell-supplied memory that extends addressable storage but
  not the per-pass resident set — every read still routes through the ≤L window.
  Retype U(L) accordingly: not data exceeding L (pageable) but irreducible
  per-step working set exceeding L (not pageable).
- Make the time-homogeneity assumption explicit at the formal kernel: the
  displayed T is the fixed-kernel case; nonstationary/adversarial environments
  replace Q_E with a time-indexed kernel Q_{E,n} / admissible family, which the
  minimax certificate downstream quantifies over.
2026-06-22 12:16:45 -07:00
Claude 853bb27b3a docs(hypothesis): apply peer-review fixes — typing, Lyapunov status, δ as risk metric
Address the accepted points from an external peer review while preserving the
controller/plant thesis and the document's voice (layer, don't flatten).

- Claim: replace the ill-typed `T = ρ ∘ (M_W ∘ π, E)` with the integral
  transition kernel over (𝒴,ℰ); add explicit informal/formal split; demote the
  residual-stream implementation from definitional to a kept specialization
  (M_W as a general learned kernel); weaken "fixpoint searches" to hitting-time
  processes with fixpoint as one mode.
- Reading-it: note s is Markov only after state augmentation; mark controller
  determinism as conditional on versioned code/config/endpoint/interfaces.
- The limit: rephrase "carries no descent function by construction" to "supplies
  no certificate automatically" (a certificate is sufficient, not provided for
  free); label V* incompressibility as conjecture, not theorem.
- δ: "measure" → "estimate"; demote empirical δ from certificate to calibrated
  risk metric (confounds: bad V̂, coverage, sup not attained, nonstationarity,
  non-Markov); certificate only once statistically bounded.
- Cash-out: split "soundness is free" into syntactic soundness (free) vs
  semantic adequacy (empirical).
- Qualify the single-pass TC^0 claim (fixed-depth/fixed-precision; log-depth
  changes it) in both body and Grounding.
- Add an operational falsification program (state-ablation, determinism audit,
  drift calibration, adversarial-environment, boundary-control ablation).
2026-06-22 12:16:45 -07:00
Patrick Buckley a5f10b1c8c docs(readme): render the headline formula as a code block (PyPI-safe) 2026-06-22 01:10:20 -07:00
Patrick Buckley a7ab0a3a09 docs(hypothesis): add closing sign-off 2026-06-22 01:10:20 -07:00
Patrick Buckley 437c8bc7e2 docs(hypothesis): ground the doc + add the working-memory (L) bound and the interlingua frontier
Citations with a proven-vs-asserted split; the orthogonal context-length
tape bound (TC^0 single pass, the U(L) non-haltable region); and a flagged
frontier coda on V* and the semantic interlingua as one object.
2026-06-22 01:10:20 -07:00
Patrick Buckley 482a11c537 docs: add HYPOTHESIS.md — what is a harness?
A one-formula definition of a harness — a deterministic controller in
closed loop with a stochastic learned plant — and the certificate it
provably can't carry. The headline equation sits at the top of the
README and links through to the full doc.
2026-06-22 01:10:20 -07:00
Patrick Buckley e3af600a90 feat(deploy): vllm-litellm example — 3-model co-resident shape + HF loader (#688)
* feat(deploy): vllm-litellm example — 3-model co-resident shape + HF loader

Update the unified-memory inference example to the validated GB10 Spark shape:
qwen3.6-27B-FP8 (reasoning) + gemma-4-12B-it (perception) + Qwen3-Reranker-4B,
all co-resident on one GPU behind LiteLLM, loaded by HF id into a mounted
HF_HOME cache.

- qwen: MTP spec-decode + runai_streamer (weight load ~166s->1s) + full 256K at
  util 0.50 (default KV)
- gemma on the OpenAI lane (audio), reranker direct on :8002/rerank
- sequential startup + page-cache-drop guidance; runai_streamer kept on the big
  model only (its buffers break small models' KV budgets)
- README: HF-id loader, DGX Spark (validated) + AMD Strix Halo (ROCm) setup,
  tuning notes, troubleshooting
- wheel-check ALLOW entries for the example files (supersedes #687)

* docs(deploy): clarify AMD edits are compose literals (Copilot review)

In the Strix Halo guidance, --max-model-len and --load-format runai_streamer are
hard-coded in docker-compose.yml's vllm-qwen command, not .env vars — say where
to edit them.
2026-06-21 20:30:52 -07:00
Patrick Buckley f97c6351bb feat(deploy): add vLLM + LiteLLM unified-memory inference example (#686)
* feat(deploy): add vLLM + LiteLLM unified-memory inference example

A docker-compose stack co-residing a reasoning model (Qwen 3.6 27B) and a
perception model (Gemma 4 12B) on one unified-memory accelerator (NVIDIA DGX
Spark / AMD Strix Halo) behind a LiteLLM gateway serving both the Anthropic
/v1/messages and OpenAI /v1/chat/completions routes.

- qwen on the Anthropic lane (vLLM native /v1/messages), full 256K context
- gemma on the OpenAI lane (required for audio input_audio perception)
- sequential startup + page-cache drop for reliable KV provisioning on one card
- README: DGX Spark (validated) + AMD Strix Halo (ROCm) setup + troubleshooting

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-06-21 15:41:15 -07:00
Patrick Buckley 2b3b212971 Add altair + vl-convert-python viz stack (#685)
* feat(deps): add altair + vl-convert-python viz stack

The standard, ui://-ready visualization stack: one Vega-Lite spec renders to
static SVG via vl-convert (a bundled Rust renderer — no browser, GDAL, or
chromium) and drops into vega-embed for interactive ui:// panels. The first
consumer is the civic-records choropleth map; future ui:// surfaces build on
the same stack.

The dependency closure is fully permissive (BSD-3 + the OFL font + MIT/ISC JS) —
clean for Apache-2.0 and commercial use. Adds a mypy override for the untyped
vl_convert wheel.

* fix(deps): bump pydantic-settings to 2.14.2 (GHSA-4xgf-cpjx-pc3j)

Clears the pip-audit --strict advisory on the transitive pydantic-settings
2.14.1. Pinned as an explicit security floor in [project.dependencies]
(matching the starlette/cryptography CVE-floor convention) even though it is
transitive-only, so the floor is documented and survives re-resolution.

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* chore: regenerate uv.lock to pass lock check

---------

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
2026-06-21 15:39:41 -07:00
Patrick Buckley 73f4fb5933 test: address Copilot review on the leaked-thread guard
- The guard snapshotted live threads by `Thread.ident`, but idents are
  recycled after a thread exits — a new leaked thread reusing an exited
  thread's ident would be mistaken for pre-existing and missed (false
  negative). Snapshot the Thread OBJECTS and compare by identity instead.
- Fix the `serve` fixture docstring: the factory returns the ephemeral
  port, not the server.
2026-06-17 18:07:45 -07:00
Patrick Buckley a7d8895287 test: eliminate leaked-thread test pollution + guard against it
Background daemons, event loops, and test servers that outlived their test
bled into later tests' captured output — an intermittent "I/O operation on
closed file" heisenbug, and the same class behind a past multi-day CI-hang
investigation.

- conftest: a fail-on-leak autouse guard (`_no_leaked_threads`) snapshots
  threads at setup and fails any test that leaves one running past teardown,
  with an `allow_thread_leak` opt-out — so the next leak is caught in minutes,
  not days. Plus `logging.raiseExceptions = False` to mute the benign
  logging-vs-capture-teardown race, and shared loop/server teardown helpers
  (`stop_loop_thread`, `serve_until_exit`).

- collector (PRODUCT FIX): the node-discovery loop slept uninterruptibly, so
  `ClusterCollector.stop()` couldn't join the `console-discovery` thread until
  the full interval elapsed — a real shutdown hang in production (up to
  `discovery_interval`). It now sleeps on an interruptible Event that `stop()`
  sets and `start()` clears.

- test fixtures: docker_healthcheck's HTTP servers, the MCP background event
  loops (shutdown_default_executor + close), and the FastMCP uvicorn upstreams
  (timeout_graceful_shutdown=0 + force_exit) now tear down cleanly instead of
  leaking.

Full non-live suite: 7456 passed, 0 closed-file errors, 0 leaked threads, and
~1.5 min faster (the leaks were dragging it).
2026-06-17 18:07:45 -07:00
Patrick Buckley cc0fa53077 feat(coordinator): port Regenerate/Edit title to coordinators
Coordinators carry LLM/auto titles like interactive workstreams but had no
way to regenerate or rename them. Port the interactive "Refresh title" (LLM
regenerate) + "Edit title" (manual alias) dropdown actions by lifting the
two handlers — the last shared verbs that weren't yet lifted — and opting
coordinators in.

- session_routes.py: add make_refresh_title_handler / make_set_title_handler
  factories (cfg pattern, mirroring make_close_handler). set_title resolves
  the workstream BEFORE the alias write and 404s when the kind has no
  tenant_check storage gate and the in-memory manager doesn't own it:
  set_workstream_alias is a global, kind-unscoped UPDATE, so this prevents
  an operator renaming a workstream the coord manager doesn't own (e.g. an
  interactive ws via the coord route) and the silent-200 on a bogus id.
- server.py: re-point the interactive bundle to the lifted handlers; drop
  the standalone refresh_workstream_title / set_workstream_title.
- console/server.py: wire refresh_title / set_title into the coord bundle
  (gated by the existing admin.coordinator operator check).
- shell.js: enable titleVerbs on the coordinator pane's tab menu; the
  base-aware lane posts to the console-origin coord routes.

Tests: coord refresh/set-title (regenerate, operator-gate, 404 unknown,
alias store + broadcast, empty, conflict, cross-kind reject); interactive
title tests re-pointed to the lifted handlers for lift-parity; shell.js
coord-menu assertion.
2026-06-17 16:04:18 -07:00
Patrick Buckley d81f8abde5 fix(coordinator): address Copilot review on title persistence
Three points from the PR #676 Copilot review:

- _coord_display_name ran on a lifecycle-event path and called
  get_workstream_display_name → get_storage(), which auto-initializes a
  SQLite .turnstone.db in the CWD when storage isn't initialized yet —
  a stray-file footgun on early-startup / unit-test paths. Add
  is_storage_initialized() to the storage registry and skip the DB read
  (fall back to ws.name) when storage isn't up. (Copilot's "skip when
  ws.name is non-synthetic" suggestion would have broken alias > title >
  name, so guard on init state instead.)

- Document, on SessionUIBase, that on_aux_usage (storage/metrics, no
  _ws_lock state) and on_rename (queue/locked fan-out) are safe to call
  from a concurrent auxiliary thread — the title-gen thread now runs
  during streaming, and these are the only two UI hooks it touches. No
  behavior change: the methods were already thread-safe (the same path
  task_agent sub-agents use); the contract just didn't say so. Add a
  matching note at the title-trigger site.

- Note in _coordinator_rows that the secondary `title` field is
  best-effort for a live coord outside the limit=200 window (the
  user-visible `name` stays correct via the uncapped bulk lookup, and
  the window is unreachable in practice — live coords are max_active-
  bounded and sort to the top of updated DESC).
2026-06-17 16:03:59 -07:00
Patrick Buckley 1860d14a65 fix(coordinator): persist + eagerly generate workstream titles
Coordinator workstream LLM titles were written to workstreams.title but
never read back, and were rarely generated in the first place:

- Read path: the dashboard's `_coordinator_rows` builder hardcoded
  title="" and used the synthetic `ws.name`, so a generated title (or a
  user alias) reverted to `ws-xxxx` on every refresh. Interactive rows
  resolve via get_workstream_display_name, so the gap was coord-only.
- Write path: the auto-title trigger only fired on a tool-call-free
  assistant turn, which coordinators (near-constant tool use) seldom
  reach — so the title almost never generated.

Read path:
- Project `title` + `alias` in list_workstreams (appended after user_id so
  existing positional fallbacks stay valid). `_coordinator_rows` resolves
  the display name (alias > title > name) for both lanes — live names via
  the bulk get_workstream_display_names (exact ids, no row cap), persisted
  rows from their own _mapping.
- Seed the console pseudo-node fan-out with the resolved display name so a
  rehydrated coordinator shows its title in the live tree immediately
  (one bulk lookup instead of an N+1 over mgr.list_all()).

Write path:
- Fire auto-title right after the user turn is recorded in send(), gated on
  a real (non-wake, non-empty) user message, instead of waiting for the
  terminal tool-call-free turn. Applies to interactive + coordinator.
- Snapshot self.messages in _generate_title since it can now run
  concurrently with the streaming turn.
2026-06-17 16:03:59 -07:00
Patrick Buckley 381057e6ed fix(audio): omni STT transcode + thinking-off, with streaming
Speech-to-text against an omni chat model (e.g. Gemma-4 on vLLM) was
broken end to end:

- The browser records webm/opus, but the omni chat lane only decodes
  wav/mp3 (it sniffs the bytes), so every clip came back 400 "Invalid
  or unsupported audio file". Transcode the upload to 16 kHz mono WAV
  with ffmpeg first, hardened against the untrusted blob:
  -protocol_whitelist pipe (no file:/http: SSRF), -vn, and a duration cap.
- The chat STT path calls the raw client and so bypasses the provider's
  request shaping. It now forces enable_thinking=false (via the model's
  thinking_param): leaving reasoning on costs ~11x latency and returns
  empty content on some clips. The prompt precedes the audio part (the
  order Gemma documents for transcription) and max_tokens is capped.

Add a streaming variant: POST .../speech-to-text/stream returns the
transcript as plain-text deltas and the composer fills them in live
(~0.3s to first word). The blocking stream is driven from one worker
thread that owns and closes the upstream connection.

Drop the gemma skip_special_tokens server-compat workaround: the vLLM
bug it patched is fixed upstream, and a stale shim can corrupt output.

The node image now installs ffmpeg; rebuild to run this live.
2026-06-16 19:49:31 -07:00
Patrick Buckley 3e88d2395c fix(tls): stub backoff via a _sleep seam, not the global asyncio.sleep
The test-postgres failure on test_init_retries_exhausted_raises surfaced the
root cause: sleeps held 2275x 0.1 instead of [1.0, 2.0]. Those 0.1s came from
a concurrent background poller doing asyncio.sleep(0.1) on anyio's shared
(persistent) event loop — the tls retry tests patched the *global*
asyncio.sleep, which intercepted that poller too.

- Before: the stub didn't yield, so the poller busy-looped and monopolized
  the loop -> the test hung (the CI-only "after 92%" hang on 3.12+).
- The earlier "make the stub yield" change converted the hang into this
  flood (the poller spins instead of blocking), which is what exposed it.

Fix: route init()'s backoff through TLSClient._sleep so the tests stub that
method in isolation and never touch the global asyncio.sleep. Tasks sharing
the loop are no longer affected; schedule assertions are unchanged.

The deeper fragility this exploited — a leaked, un-cancelled background poller
surviving on the shared test loop — is left as a follow-up.
2026-06-16 17:10:12 -07:00
Patrick Buckley 8ba669cf57 fix(deadline): prefer a ready result over a same-window deadline/cancel
run_with_deadline checked the deadline/cancel before reading the result
queue, so a call that completed in the same scheduling window could be
reported as a spurious timeout. Drain the queue first.

Also from review:
- test_validate_regex_pattern stubs run_with_deadline, so the probe regex
  never runs — use a benign pattern instead of a real backtracking literal
  (the literal tripped a ReDoS scanner).
- output_guard_judge docstring: reference IntentJudge._parse_verdict instead
  of brittle judge.py line numbers.

The _runner BaseException catch is intentional and kept: it relays (not
swallows) whatever fn() raises to the caller via the queue; narrowing to
Exception would let a BaseException escape the worker so the caller never
gets a value, degrading the no-hang guarantee.
2026-06-16 17:10:12 -07:00
Patrick Buckley bde960f725 ci: cap the suite jobs at 20 minutes
A hung run otherwise rides GitHub's 6-hour default with -v streaming the
whole time (the source of the multi-GB job logs). Cap test and test-postgres
at 20 minutes so a flaky hang fails fast instead of bleeding hours.
2026-06-16 17:10:12 -07:00
Patrick Buckley 05fd08ed1f test(tls): yield in the asyncio.sleep stub (suspected CI-hang fix)
CI hung on test_init_retries_transient_failure (the new -v output named it:
its nodeid printed, no PASSED, the job rode to cancellation). It is the first
retry test that actually awaits the stubbed asyncio.sleep — the earlier tests
raise before sleeping — which points straight at the stub.

The stub returned without ever suspending, so the retry run completed in one
event-loop step with no checkpoint; that is fragile under the async test
runner and is the suspected cause (3.12/3.13/3.14 only — never reproduced on
3.11 or locally). Capture the real asyncio.sleep before patching and await
sleep(0) in the stub so it still yields, keeping the no-real-delay behavior
and the backoff-schedule assertions. Same fix in the discovery-failure test.
2026-06-16 17:10:12 -07:00
Patrick Buckley 0b4f77db33 fix(judge): daemon-thread call deadlines; raise local-model timeouts
The judges and the regex ReDoS probe ran a blocking call on a
ThreadPoolExecutor and abandoned the worker with shutdown(wait=False) on
timeout or cancel. concurrent.futures joins every executor worker from an
atexit hook regardless of wait=False, so a wedged call could pin
interpreter exit — and hang the test suite at shutdown.

Add turnstone/core/deadline.py::run_with_deadline: run a blocking callable
on a daemon thread bounded by a wall-clock timeout and an optional cancel
event. A daemon worker is never joined at exit, so abandoning one is safe.

Migrate three sites onto it:
- OutputGuardJudge.evaluate()
- IntentJudge._evaluate_single / _run_judge — this also removes
  _ExecutorPoisonedError and the executor-restart dance: per-call daemon
  threads can't poison a shared single-slot pool, so a timeout now returns
  None and the caller delivers one fallback verdict.
- console/server.py _validate_regex_pattern (regex ReDoS probe)

Also:
- Double the default judge LLM timeouts for slower local models:
  judge.timeout 60->120s and judge.output_guard_llm_timeout 30->60s
  (settings registry, JudgeConfig dataclass, --judge-timeout CLI default,
  class docstring, docs). Correct a stale doc that described the per-turn
  timeout as a total budget across turns.
- Raise the regex probe bound 0.5->3.0s so a legitimately complex pattern
  isn't false-flagged as catastrophic backtracking.
- CI: run pytest with -v instead of -q so a hang names the offending test
  instead of riding the job timeout.
- Tests: cover deadline.py and the regex validator; move test_judge.py off
  fixed sleeps onto the existing _wait_for helper.
2026-06-16 17:10:12 -07:00
Patrick Buckley fd5b710437 chore: bump version to 1.7.0a2 2026-06-16 04:39:26 -07:00
Patrick Buckley e562d04e8b fix(deps): enforce cryptography + starlette security floors
main's lockfile was already on the patched versions (cryptography 49.0.0,
starlette 1.3.1) via renovate, but the pyproject floors (>=42, >=1.0.1) still
permitted a regression to vulnerable versions. Raise the floors to match
stable/1.6's v1.6.7 security fix:
- cryptography >=48.0.1 (GHSA-537c-gmf6-5ccf — bundled OpenSSL vulnerable <48.0.1)
- starlette >=1.3.1 (CVE-2026-54282 host spoof + CVE-2026-54283 url-encoded form DoS)
2026-06-16 04:39:26 -07:00
Patrick Buckley f714e49e02 fix(voice): default blank provider to openai in the admin audio gate
Copilot review: _audioModelEligible gated stt/tts on md.provider, but a
blank/unset provider was treated as not-audio-capable and excluded — an
asymmetry with the backend, where _provider_carries_audio and
ModelConfig.provider both default to "openai". Default the provider to "openai"
before the check so a provider-less model isn't wrongly dropped from the
voice-role dropdowns.
2026-06-16 03:41:51 -07:00
Patrick Buckley f4bab9fe16 refactor(attachments): retire the vestigial reservation scaffolding
The by-ref change replaced the send_id reservation model with the per-node
upload buffer (peek-then-drain at write time), but the surrounding narration was
never swept and a no-op stub was retained to make the send handler "read like"
the old flow — which is what made a recent diagnosis assume reservations still
existed.

- Delete the no-op _release_reservation_on_fail() and its 5 call sites in the
  send handler (behaviour-preserving — it did nothing).
- Rename ordered_reserved / reserved_set -> ordered_taken / taken_set (the values
  are the "taken" subset from resolve_staged_attachments, not reservations).
- Sweep the stale "reserve/reservation" wording across the create/send
  docstrings, the API schemas/specs, and the SDK docstrings to the staged-buffer
  vocabulary (resolve / attach / drain). The canonical docs in attachment_buffer
  and attachments already stated the reservation token is gone.

No behaviour change; no tests exercised the removed scaffolding (the
migration-060 test correctly pins the reserved_at column removal and stays).
2026-06-16 03:41:51 -07:00
Patrick Buckley b8a8b04042 fix(attachments): drain create-time staged uploads synchronously
A create-time attachment is dispatched on the first turn, but the buffer drain
runs at write time inside the async dispatch worker (_append_user_turn). The
freshly-opened pane calls rehydrate() before the worker drains, so it painted
the image as a still-pending composer chip ("thumbnail in the text input box").

The inlined first-turn dispatch is the only consumer of those staged uploads and
always commits at create, so drain them from the buffer synchronously right
after resolving them — both the interactive and coordinator post-install paths.
The worker's own per-id discard then no-ops.
2026-06-16 03:41:51 -07:00
Patrick Buckley d6f9e6f7d3 fix(voice): gate audio roles to OpenAI-SDK providers
An omni model registered via the anthropic-compatible lane (vLLM Messages API)
was offered for the STT role because it carries supports_audio_input — but the
Anthropic SDK client has no .chat.completions and the Messages API has no audio
content block, so the mic failed with a cryptic
"'Anthropic' object has no attribute 'chat'".

Audio (input_audio) only rides the OpenAI-SDK surface, so gate all audio roles
to OpenAI-SDK providers (openai / openai-compatible / google / xai):
- model_supports_role returns False for anthropic(-compatible), so the mic
  won't draw and the STT/TTS dropdowns won't offer those models.
- transcribe() raises a clear AudioUnavailableError naming the provider instead
  of the opaque AttributeError (defence in depth).
- admin _audioModelEligible mirrors the gate — voice roles only; reranker hits a
  /rerank endpoint, not audio, so it stays un-gated.

To use an omni model's audio, register it as openai-compatible (the input_audio
path); the anthropic-compatible lane is text/vision only.
2026-06-16 03:41:51 -07:00
Patrick Buckley 531913ec03 refactor(attachments): address branch self-review
- DRY the launcher create body: the multipart (meta + file parts) vs JSON
  framing was duplicated in _createCoordinator and _createInteractive — extract
  _createWorkstreamFetchOpts so the create wire shape lives in one place.
- Correct the proxy comment: the forwarded owner uid comes from the
  authenticated ws_body (as on the JSON path), not the caller's meta; the proxy
  token source is console-proxy, not console.
2026-06-16 03:41:51 -07:00
Patrick Buckley 2568ea5691 feat(voice): let omni models serve speech-to-text via the chat path
The mic is an STT control — it records and transcribes to editable text in the
composer. STT eligibility required the dedicated /audio/transcriptions endpoint
(supports_transcription / a whisper-style name), so an omni chat model
(supports_audio_input, e.g. Gemma) couldn't back it: it has no transcription
endpoint, it ingests audio via chat.

- model_supports_role accepts supports_audio_input for the STT role, so an omni
  alias resolves as STT and the mic draws for it.
- transcribe() branches: a whisper-style alias keeps /audio/transcriptions; an
  omni alias transcribes via chat input_audio + an instruction prompt — the
  audio.stt_prompt override, else a default that emits only the transcript.
  Audio attachments on an omni-STT setup transcribe the same way.
- admin _audioModelEligible mirrors the eligibility so omni models show in the
  STT dropdown; the role description notes the two backends.
2026-06-16 03:41:51 -07:00
Patrick Buckley 0171a9dd18 fix(attachments): normalize EXIF orientation so thumbnails and models see upright images
Phone photos store landscape pixels plus an EXIF orientation tag. Browsers honour
the tag for <img>, but Pillow (our thumbnails) and many vision-model image
decoders do not — so the thumbnail rendered rotated AND the model literally
perceived the photo sideways (noticed earlier as model "hallucinations", before
thumbnails made the rotation visible).

Normalize on read, at both surfaces:
- new core/images.normalize_image_orientation: bakes the rotation into the pixels
  and re-encodes (preserving format); images with no / identity orientation pass
  through untouched (pristine original, no per-send cost).
- make_thumbnail applies exif_transpose — after the decompression-bomb pixel gate,
  which now also covers the transpose decode.
- attachment_to_content_part runs image bytes through the normalizer before
  base64, so the primary model and the perception model both get upright pixels.

Because normalization is on read (not at upload), it fixes already-stored uploads
too.
2026-06-16 03:41:51 -07:00
Patrick Buckley 793c5518cc fix(attachments): surface the perception role in admin (roles tab + settings filter)
The universal perception fallback (perception.model_alias) shipped backend-only
— session.py + perception.py + settings_registry.py — so its admin UI was never
wired. Operators had no way to assign it from the Models → Roles sub-tab, and the
raw setting leaked into the Settings tab.

- Add a Perception row to MODEL_ROLES (no capability filter — it spans
  image/PDF/audio; the description tells operators to enable supports_vision /
  supports_audio_input on the target model, which is what makes the audio
  fallback engage when no STT role is set).
- Derive the Settings role-key skip-set from MODEL_ROLES instead of a
  hand-maintained list, so perception is filtered out and no future role can
  drift back in (stt/tts/reranker had leaked the same way).
- Add an optional per-role disabledLabel so the blank dropdown option reads
  correctly for non-voice roles (perception, reranker) instead of "voice off".
- Refresh the stale STT description that claimed "no audio-capable session
  fallback" — audio attachments now fall back to perception.
2026-06-16 03:41:51 -07:00
Patrick Buckley 9c15bb035c fix(attachments): forward create-time attachments for console interactive sessions
The console creates interactive sessions by proxying to the owning node via
/v1/api/cluster/workstreams/new, which only forwarded JSON — so a file staged in
the launcher was blocked with "Attachments aren't supported for interactive
sessions yet". The node create endpoint already accepts multipart (meta JSON +
file parts) on interactive_endpoint_config; only the proxy lacked it.

Teach create_workstream to accept multipart: parse meta + files (same caps as
the node), pick the node exactly as before (auto / pool / pinned), and forward
the files instead of re-serialising JSON. _createInteractive sends multipart
when files are staged (mirroring _createCoordinator) and the launcher gate is
removed. The files-need-a-task guard already ensures an initial turn to
dispatch them on.
2026-06-16 03:41:51 -07:00
Patrick Buckley f7500261e2 fix(attachments): base-prefix interactive pane attachment requests
A console interactive pane is node-proxied — every request rides the pane's
transport base ("/node/{id}"). The attachment controller hardcoded bare
/v1/api/workstreams/... paths, so upload / list / delete / preview landed on
the console's OWN coord route, which resolves ws_id via coord_mgr.get() and
404s as "coordinator not found". The standalone server (base="") was
unaffected, which masked the bug.

Thread the pane base through: createAttachmentController and
buildAttachmentPreview take an optional getBase / base, and the interactive
pane wires this._base into both. Coordinator panes and the standalone server
pass "" and stay origin-mounted as before.
2026-06-16 03:41:51 -07:00
Patrick Buckley 8e05c10b78 fix(attachments): address PR review feedback (Copilot + code-quality)
- TextDecoder in the text-preview stream now flushes on completion/cancel, so a multibyte UTF-8 char split across a chunk boundary isn't dropped (Copilot).

- send() clears self._wire_part_cache in a finally so the per-send memo (which can hold large rasterized PDF page-images) is released at send end instead of retained on an idle session until the next send (Copilot + fix-review).

- Make the implicit byte-string concatenation in _minimal_pdf explicit (+) in test_pdf.py and test_thumbnails.py so it can't read as a missing comma (CodeQL / github-code-quality).
2026-06-16 00:48:14 -07:00
Patrick Buckley ed5c104a88 fix(attachments): address fix-review nits (ftyp scan, text-preview, cache doc)
A review of the fix commits surfaced three refinements:

- ftyp audio sniff: scan the whole ftyp box (its declared length) for an audio brand instead of a fixed 6-slot window, so a real .m4a with the brand listed late still passes — while a pure-video file (no audio brand) still rejects.

- text-preview: accumulate body chunks until >=240 chars before cancelling the stream, instead of assuming the first chunk is large (flush boundaries can split a large body into small early chunks).

- _resolve_attachments: correct the cache comment — the memo is refreshed per send and the wire resolver only runs during a send, so a stale value is never observed between sends.
2026-06-16 00:48:14 -07:00
Patrick Buckley dd80ca3655 chore(attachments): hygiene sweep — dead code, stale comments, SDK type, pdf nit
- Remove the unused PerceptionUnavailableError (never raised/caught/imported).

- Reword the now-shipped 'Phase 3' placeholder comments on the Anthropic + OpenAI-Responses audio paths to describe the live upstream STT/perception fallback (these placeholders are defensive, not pending work).

- Clarify the no-vision image fall-through comment (fires when perception is unconfigured OR can't see, not only the former).

- Type AttachmentInfo.kind as the image|text|pdf|audio union in the TS SDK.

- extract_pdf_text: append the truncation marker only when there's actual text, so a scanned PDF over the page cap returns '' (-> placeholder) instead of a content-free document part.
2026-06-16 00:48:14 -07:00
Patrick Buckley f7cba67c2c test(attachments): handler-level coverage for /thumbnail + the served-blob gate
The /thumbnail endpoint and the _resolve_served_blob ownership/404-leak gate it shares with /content had no handler-level test (only make_thumbnail as a unit + route mounting). Add cases through the real app: image -> 200 image/png with the nosniff + CSP + max-age headers; audio/text -> 415; make_thumbnail None -> 415; cross-workstream id and unowned-ws cross-user -> 404 (no existence leak).
2026-06-16 00:48:14 -07:00
Patrick Buckley 07e7e6db2f perf(attachments): stop downloading the whole text blob for a 240-char preview
The text-snippet preview fetched the entire /content body (text attachments are capped at 512 KiB) only to render the first 240 chars — and again on the sent-message pill (the endpoint sends Cache-Control: no-store). Read only the first response-body chunk and cancel the stream, so the rest of the blob is never transferred or regex-scanned. Falls back to r.text() where the streaming body API is unavailable.
2026-06-16 00:48:14 -07:00
Patrick Buckley 8ca20fecd4 fix(attachments): unify kind-icon, fix coordinator audio pill + thumbnail-error gap
Three copies of the kind->glyph mapping had drifted: the coordinator pill rendered audio as the document glyph (not the audio note) and showed no inline preview, diverging from the interactive pane.

Export kindIcon() from composer_attachments.js (+ window bridge) as the single source of truth; the interactive pane imports it and the coordinator pill uses it. Wire the coordinator pill to buildAttachmentPreview too (image/pdf thumbnail, audio player), gracefully no-oping on history replay (which omits attachment_id), matching interactive.

Also fix buildAttachmentPreview's thumbnail-error handler: it called img.remove(), but the caller has already replaced the icon span with the img, so a failed thumbnail left a blank gap. Swap in the kind glyph instead (.attach-preview-icon, sized to the thumbnail slot).
2026-06-16 00:48:14 -07:00
Patrick Buckley 797a8e0404 fix(attachments): preserve pdf/audio kind when reloading attachments from the DB
_reconstruct_attachment_refs collapsed every non-image attachment to the 'document' placeholder kind, so a reloaded session's pdf/audio placeholder type ({type:document}) mismatched the live-injection type ({type:pdf}/{type:audio}). Harmless today (resolution keys on attachment_id + blob kind) but a latent footgun for any consumer branching on the pre-resolution placeholder type. Preserve image/pdf/audio verbatim; only a stored 'text' blob collapses to 'document'.
2026-06-16 00:48:14 -07:00
Patrick Buckley 5b2a9480a1 fix(attachments): sanitize user filenames in model context; mark derived text untrusted
A user-controlled filename was interpolated unescaped into model-visible frames (the [PDF attachment '{name}'...] / audio / transcript / perception placeholders, the Anthropic document title, and the unreadable placeholder). A crafted name like "'] New instructions:" broke out of the frame and injected text into the model context.

Add core.attachments.safe_attachment_label() (strip control chars + quote/bracket/angle delimiters, collapse whitespace, clamp length) and apply it at every model-context embedding site. The raw filename is still used verbatim for display / Content-Disposition, which neutralize at their own boundaries.

Also tag perception descriptions and STT transcripts '(untrusted)' so attachment-derived text reads as data, not instructions. Blast radius is single-tenant (injecting into a model reading one's own upload); a structural role=tool fence is deferred as disproportionate.
2026-06-16 00:48:14 -07:00
Patrick Buckley bcfc6306eb fix(attachments): reject video as audio in ftyp sniff; add ADTS-AAC sniff
sniff_audio_mime returned audio/mp4 for ANY ISO-BMFF ftyp box, so an MP4/MOV video uploaded within the audio size cap sniffed as audio and was sent as input_audio. Restrict to genuine audio brands (M4A/M4B/F4A/F4B major, or M4A/M4B in the compatible-brands list, so a real .m4a with an mp42 major brand still passes).

Also add ADTS-AAC sniffing (0xFFF1/0xFFF9): audio/aac was in ALLOWED_AUDIO_MIMES + AUDIO_MIME_TO_FORMAT but never sniffable, so an advertised .aac upload always failed.
2026-06-16 00:48:14 -07:00
Patrick Buckley 25101e7ff6 fix(attachments): close thumbnail decompression-bomb gap (40M, not 80M)
make_thumbnail set Image.MAX_IMAGE_PIXELS=40M, but Pillow only raises DecompressionBombError above 2x the cap; a 40-80M px image merely warns and decodes fully (~480MB RGB), defeating the documented bound.

Gate on the header-declared size after open() and before convert(), so nothing past the cap is decoded. Explicit check rather than a warnings filter — make_thumbnail runs in a worker thread and global warnings state is not thread-safe. Adds tests for the (cap, 2*cap] warn-only window and the at-cap boundary.
2026-06-16 00:48:14 -07:00
Patrick Buckley 7da07e2350 perf(attachments): per-send wire-part memo to stop re-rasterizing every round-trip
_resolve_attachments re-runs on every agentic round-trip (and per fallback model), each time re-fetching every attachment across the full history and re-rasterizing / re-base64'ing it. A 10-page PDF in a 10-cycle tool turn was rendered dozens of times.

Add a per-send memo (self._wire_part_cache) keyed by (attachment_id, caps-signature): the materialized wire part is computed at most once per send. The cache is None outside a send (display/export paths unaffected) and reset per send to bound the heavy rasterized-page parts and pick up any mid-session capability change. Skip the DB fetch entirely when every id is already cached.

Also peek the perception (alias, content_hash) memo before building parts in _perception_fallback_part, so a cross-send describe hit no longer wastes a PDF rasterize. Leaves pdf.py's deliberate no-module-cache stance intact — the per-send scope addresses the round-trip amplification without the durable store it defers.

Adds describe_peek() + per-send-cache and peek tests.
2026-06-16 00:48:14 -07:00
Patrick Buckley d5d9db39d4 fix(attachments): repair dead OpenAI-Responses native PDF path
sanitize_messages ran inline_document_parts (which placeholders an application/pdf document part) before the Responses translator's native input_file branch could run, so every supports_pdf model silently degraded its PDF to an unsupported text placeholder.

Thread a skip_pdf_inline flag through sanitize_messages -> inline_document_parts; the Responses lane sets it so the PDF document survives to convert_content_parts. Chat / Google-compat keep the placeholder (they have no native PDF block).

The existing test exercised convert_content_parts in isolation, bypassing sanitize_messages and masking the bug. Add an end-to-end _convert_messages regression test (verified to fail without the fix) plus contrast tests pinning both lanes' behavior.
2026-06-16 00:48:14 -07:00
Patrick Buckley a3cb546030 docs(attachments): pin xAI Grok to the rasterize-PDF fallback
q-3 from the pre-push review, settled against docs.x.ai: Grok's document
support is an agentic attachment_search workflow over Files-API uploads
(file_id / file_url), not the inline base64 native ingestion that OpenAI
input_file / Anthropic document blocks use. Our native PDF path emits inline
base64, which xAI's Responses surface doesn't accept — so supports_pdf is
correctly left unset (Grok PDFs rasterize to images, which Grok can see).

Document the rationale on GROK_CAPABILITIES and pin every Grok row's
supports_pdf=False with a test so it isn't naively flipped without first
wiring a Files-API upload flow.
2026-06-16 00:48:14 -07:00
Patrick Buckley 558ddadc79 feat(attachments): universal perception fallback for non-native modalities
Add a `perception.model_alias` model role: when the primary model can't ingest
an attachment natively and can't be shown a degraded-but-native form, a
configured perception model perceives it and its output is carried as text.
Mirrors the STT role — a role alias plus a module-level memo so the extra LLM
round-trip runs once per attachment, not once per conversation turn. The call
goes through the provider abstraction's create_completion (the path the intent
judge uses), so any vision/omni provider works.

Bottom-tier, universal ladder — perception only fills the remaining gap:
- pdf  : native supports_pdf -> rasterize-to-vision-primary -> perception
         -> extracted text -> placeholder
- image: native vision -> perception (non-vision primary) -> native image_url
- audio: native supports_audio_input -> STT -> perception (omni) -> placeholder

Folds in two review findings the role subsumes:
- bug-1: thread the active attempt's capabilities into _resolve_attachments
  (bound in _try_stream) so a model fallback materializes attachments against
  the fallback model's caps, not the primary's.
- bug-2: charge a by-reference pdf/audio a bounded budget min(size_bytes, 16K)
  instead of zero, so a large-attachment turn isn't budgeted as ~empty (the
  exact materialized size isn't known until wire build).
2026-06-16 00:48:14 -07:00
Patrick Buckley 8af3e21dff fix(attachments): harden thumbnail/rasterize DoS + review nits
Pre-push review follow-ups that are independent of the perception-role work
(bug-1 caps threading, bug-2 budget, and the perf cluster fold into that):

- thumbnails: cap decoded pixels (Image.MAX_IMAGE_PIXELS=40M) so a small
  compressed image that decodes to huge dimensions can't OOM the node, and
  reject DecompressionBombError cleanly.
- pdf: clamp per-page render scale so the longest rendered side stays <= 2000px
  (a maximal MediaBox at scale 2.0 rendered to a ~28800px, multi-GB bitmap).
- session_routes: type classify_upload's rejection element as
  UploadRejection | None instead of Any.
- test_session_routes: assert the /thumbnail route mounts (it was untested) and
  fix the stale "quartet"/four wording to five.
2026-06-16 00:48:14 -07:00
Patrick Buckley 9ad447ca33 fix(attachments): design-review polish for preview chips/pills
Two-reviewer + sanity pass over the attachment previews:

- composer audio chip is icon+name+size only; the native <audio> player
  renders on the sent message, not the staging chip (too heavy at chip scale)
- cap sent-message pills (+ in-pill audio/snippet) so they no longer overflow
  the bubble at narrow widths; player and snippet drop to their own row
- clamp the chip filename in shared chat.css so long names ellipsize instead
  of wrapping (console main + coordinator previously left it unclamped)
- merge the duplicated .composer-chip rule; drop unused kind-modifier classes
  and inert vertical-align / inline-block declarations
- fix undefined var(--bg-base) -> var(--bg-surface) thumbnail backing
- label the <audio> control (aria-label) and drop the decorative snippet from
  the a11y tree

scripts/livepass.py: add an attachments harness that drives the real
createAttachmentController + Pane.addUserMessage so these surfaces render
headlessly for review.
2026-06-16 00:48:14 -07:00
Patrick Buckley c09ba6041f feat(attachments): inline chip previews (image/pdf thumbnail, audio player, text snippet)
- core/thumbnails.py + GET .../attachments/{id}/thumbnail: server-rendered PNG
  thumbnails (image downscale; pdf first page via pypdfium2). Extracted a shared
  ownership-gated blob resolver used by both get_content and the thumbnail route
- buildAttachmentPreview (composer_attachments.js): image/pdf -> thumbnail,
  audio -> <audio> player, text -> lazy snippet; reused by the composer chips and
  the sent-message pills (interactive.js). Cookie auth, so direct media src works
- chip kind icons now cover pdf/audio; the upload swap adopts the server's
  authoritative kind for styling + icon + preview
- chat.css preview styling; tests for make_thumbnail
2026-06-16 00:48:14 -07:00
Patrick Buckley 8ad6d3d2f3 feat(attachments): accept pdf/audio uploads in the UI + admin capability toggles
- composer: accept pdf/audio in the upload picker; client-side kind
  inference for the optimistic chip (server classify_upload stays
  authoritative)
- admin Models tab: supports_pdf + supports_audio_input toggles (flow
  through the field-aware capabilities merge into ModelCapabilities, so
  flipping supports_audio_input on an omni alias enables native input_audio)
- docs: AttachmentInfo.kind, AttachmentUpload, and the TS SDK note pdf/audio
2026-06-16 00:48:14 -07:00
Patrick Buckley 471d94b27f feat(attachments): rasterize PDF to page images for vision models without native PDF
A vision-capable model that can't ingest PDF natively now gets the PDF
rendered to one image per page instead of extracted text; falls back to
text extraction when rendering yields nothing.

- core/pdf.py: rasterize_pdf via pypdfium2 render + Pillow PNG (page-capped
  at 10, never raises)
- session._wire_content_part: pdf + !supports_pdf + supports_vision ->
  rasterized image parts; else text extraction
- trajectory.resolve_attachment_parts: a placeholder can now expand to a
  list of parts (1->N); the resolve_attachments callback return type widened
  to dict[str, Any] across the provider protocol + 4 providers
- pyproject: pillow dependency
- tests: rasterize_pdf, vision-rasterize gate path, 1->N materialization
2026-06-16 00:48:14 -07:00
Patrick Buckley addb8d0be8 feat(attachments): capability-gated client-side fallback (pdf->text, audio->transcript)
When the active model can't ingest a kind natively, the wire resolver
converts it client-side instead of sending a part the model can't read.
Per-kind ownership, no shared machinery: PDF text-extraction is a
pure-local PDF concern; audio transcription is an STT concern memoized
in the audio domain.

- core/pdf.py: extract_pdf_text via pypdfium2 (pure-local, no network, no
  cache — re-run per build; page-capped)
- core/audio.py: transcribe_cached — non-raising, memoized by
  (alias, content-hash); backend failures not cached
- session._wire_content_part: per-kind dispatch — native where the model
  supports the kind (supports_pdf / supports_audio_input), else fallback;
  display/export resolve natively so no conversion fires on a render
- image left ungated (pre-existing behavior unchanged)
- pyproject: pypdfium2 dependency + mypy untyped-import override
- tests: pdf extraction, transcript memoization, per-kind gate dispatch
2026-06-16 00:48:14 -07:00
Patrick Buckley 701ae46c72 feat(attachments): native PDF + audio translators, accept on upload
PDF and audio attachments now work end-to-end on the native provider
lanes; non-native lanes degrade to a placeholder (client-side fallback
lands next). Capability flags are populated but not yet consumed by a
wire-build gate.

- providers: Anthropic PDF -> base64 document; OpenAI Responses PDF ->
  input_file; compat/Google inline_document_parts PDF -> placeholder
  (fixes the base64-as-text mangle); audio = input_audio passthrough on
  the compat lane (omni), defensive text placeholders on Anthropic +
  Responses
- capabilities: supports_pdf on cloud Claude + OpenAI chat models;
  local/default/compat stay False (-> client-side fallback)
- upload: classifier accepts pdf (32 MiB) + audio (25 MiB); endpoint
  multipart read cap raised to PDF_SIZE_CAP
- hygiene: consolidate the duplicated upload classification into one
  attachments.classify_upload (+ UploadRejection); collapse
  AttachmentUploadHelpers to a single classify_upload callable
- tests: PDF/audio translator shapes, capability flags, classify_upload
2026-06-16 00:48:14 -07:00
Patrick Buckley 129560ee60 feat(attachments): pdf + audio attachment kinds (dormant spine)
Provider-neutral plumbing for PDF and audio attachments, with no
user-facing change yet: the upload classifier still rejects them and the
capability tables stay unpopulated (both land in the native-translator
phase). No migration — workstream_attachments.kind is free-text.

- attachments.py: PDF/audio byte caps, allowed-audio MIMEs + format map,
  magic-byte sniffers (sniff_pdf_mime / sniff_audio_mime),
  Attachment.is_pdf / is_audio
- providers/_protocol.py: supports_pdf / supports_audio_input capability
  fields (default False; orthogonal to the STT/TTS roles)
- storage/_utils.py: attachment_to_content_part emits the internal
  document(application/pdf, base64) and input_audio shapes
- session.py: by-reference placeholder branches for pdf / audio
- trajectory.py: AttachmentRef docstring (dict-bridge already kind-agnostic)
- tests: test_attachments_pdf_audio.py
2026-06-16 00:48:14 -07:00
Patrick Buckley 04b3a3abe4 feat(deploy): systemd units for a bare-metal turnstone-server node
Hardened service + slice + node-identity drop-in template + a README for
running a turnstone-server outside Docker that joins the compose cluster —
the production-shaped counterpart to the one-liner in docs/docker.md. Secrets
stay in config.toml; per-host identity + cluster URLs go in the drop-in. The
README notes the cross-host mTLS caveat (turnstonelabs/lacme#22).
2026-06-15 03:41:24 -07:00
Patrick Buckley 1f61350545 feat(compose): let bare-metal turnstone-servers join the cluster (incl. mTLS)
A turnstone-server running outside the compose network ("bare-metal", e.g. a
local-GPU box) couldn't fully join: it can't resolve the in-cluster console
(console:8090) to enroll its mTLS cert, and SearxNG was unreachable for
web_search. Only Postgres was published.

Publish the console's plain-HTTP ACME endpoint (:8090) and SearxNG (:8081)
alongside Postgres, all bound via one knob TURNSTONE_HOST_IP (default 127.0.0.1
-- nothing new on the LAN; set it to the host's LAN IP for a node on another
machine). Postgres keeps honoring the legacy POSTGRES_BIND as a fallback, so
existing .env files don't break.

The node's TLS client now honors TURNSTONE_CONSOLE_URL so a bare-metal node can
point at the published ACME endpoint instead of the unreachable in-cluster name
(empty = in-cluster service discovery, unchanged).

Docs (docker.md, tls.md), the run.sh-generated .env, and the bootstrap wizard
updated to match. The advertised host is the cert's primary SAN and the console
collector dials it back, so mTLS hostname verification holds both ways.
2026-06-15 03:41:24 -07:00
renovate[bot] 94e385e91f chore(deps): lock file maintenance 2026-06-15 02:49:32 -07:00
Patrick Buckley 108714a48d fix(auth): isolate server/console session cookies by name
The server (:8080) and console (:8090) both set a cookie named
`turnstone_auth`. Cookies ignore port (RFC 6265), so on a shared host
(localhost dev, the Electron build, single-box installs) logging into one
surface overwrote the other's cookie and 401'd the first session.

Give each surface its own cookie name -- `turnstone_auth_server` /
`turnstone_auth_console` -- threaded as a required `cookie_name` argument
through the cookie builders, `check_request`, `AuthMiddleware`, and the six
shared auth handlers (login/logout/setup/whoami/refresh/oidc_callback). Each
app passes its own constant; the parameter is required (no default) so a
forgotten caller fails loudly instead of silently reverting to the legacy name.

Names key on role, not node: the cluster shares one JWT identity and the
console->node proxy re-mints a bearer token (dropping Set-Cookie), so
per-instance names would break identity portability and aren't used.

Hard cutover: the legacy `turnstone_auth` cookie is no longer read and
self-expires within its 24h TTL (one forced re-login). JWT audience was
already enforced, so the shared cookie was a session clobber, not an auth
bypass.
2026-06-15 02:48:50 -07:00
Patrick Buckley a628e9f3b4 fix(ui): interactive pane keeps its scroll pin across tool calls
The interactive pane only auto-scrolled when isNearBottom() was true, but it measured that AFTER the new node was appended. A tool block is a tall one-shot append (batch shell, approval card, or result) that clears the 80px near-bottom threshold in a single step, so the post-append check read false and auto-follow silently disengaged at exactly tool-call time — the view froze at the top of the block and only snapped back at the next stream_end. Token streaming was unaffected because each append stays sub-threshold.

Capture the near-bottom state as the first statement of each tool-render method, before any DOM mutation, and thread it into scrollToBottom(stick). This re-pins when the user was already at the bottom and, unlike the coordinator pane's unconditional pin, leaves the view alone if they deliberately scrolled up while a result was rendering.

Methods fixed: announceToolBlock, showInlineToolBlock, resolveApproval, appendToolOutput (all three exit paths), appendToolOutputChunk.
2026-06-13 06:15:49 -07:00
Patrick Buckley 1468ca7972 fix(examples): accept remote Host headers when bound off localhost
The streamable-http server bound to 0.0.0.0/a LAN IP answered TCP and
/watch but returned 421 "Invalid Host header" on /mcp for every remote
node — which broke multi-node play entirely. FastMCP freezes DNS-rebinding
protection (a localhost-only Host allowlist) at CONSTRUCTION, and this
module builds its FastMCP at import time with the default 127.0.0.1 host;
flipping settings.host in _serve afterward never updated the frozen
allowlist, so the LAN Host was always rejected.

When UNDERSTONE_HOST is off localhost, drop the allowlist in _serve before
run() — matching the SDK's own default for a non-localhost bind. The /mcp
and /watch routes are unauthenticated by design, so serve only on a trusted
network (documented).

Regression test pins the mechanism: a default FastMCP 421s a foreign Host,
a protection-disabled one accepts it. Tests 420 -> 421.
2026-06-13 04:40:40 -07:00
Patrick Buckley efa8664e4d ci(examples): name the Understone job distinctly
The job was named "test", colliding with core CI's "test" matrix so the PR
checks list showed two "test (3.11)" rows. Rename it to "understone" so the
example's checks read unambiguously (understone (3.11) / (3.13)).
2026-06-13 04:40:40 -07:00
Patrick Buckley a0a097dfa8 fix(examples): address PR review feedback (CodeQL + Copilot)
- CodeQL (implicit string concatenation in a list): collapse the wrapped
  bullets in cli._render_validate_coverage to single literals. The rendered
  output is byte-identical (the example's ruff ignores E501); clears all
  six alerts and reads cleaner.
- Copilot: packs/README no longer claims the directory ships "effectively
  empty" — it ships the bundled Cinder Wastes alternate world.
- Copilot: the Cinder Wastes' ash_flats and caldera_deep zones overlapped
  on column x=60 (inclusive bounds + first-match zone_for silently shadowed
  the tier-3..5 band onto a 1x5 deep-edge strip). Move caldera_deep to
  x0=61 — no overlap, no dead tiles, deep zone still covers the dungeon.
  And harden the loader: overlapping zone rectangles are now a
  WorldLoadError, so no authored pack can ship that bug unseen (the
  cold-author dogfood loop — a generated pack exposed a validator gap).

Tests 419 -> 420 (zone-overlap rejection). Both worlds validate sound and
remain winnable by the sim bot.
2026-06-13 04:40:40 -07:00
Patrick Buckley 30c09aaf51 ci(examples): run the Understone example test suite
The door-game example is a standalone package (no turnstone-core
dependency) that the root suite does not collect — its
testpaths are scoped to ["tests"], so the example's 419 tests, ruff,
and mypy gates never ran in CI.

Add a path-filtered workflow that installs the example and runs its
full gate (pytest + ruff check + ruff format --check + mypy) whenever
examples/door-game (or this workflow) changes, across the example's
declared Python floor and ceiling (3.11, 3.13). Pinned action SHAs and
contents:read permissions match the existing CI workflows.
2026-06-13 04:40:40 -07:00
Patrick Buckley 393a6fc2b2 feat(examples): Understone v0.10 — the satchel, the ore-forge, and the vault
A game-loop mechanics patch: the satchel becomes a real stacking inventory,
forging now demands ore won in combat (not just gold), and a vault lets a
hero protect coin from ambush.

- Stacking satchel: the bag re-encodes from a flat id list to "id:qty"
  stacks, so potions stack (three Minor Potions fill one slot, not three)
  and materials ride alongside. satchel_max now caps distinct KINDS (3);
  per-kind quantity is unbounded. quaff/death-save still pull the strongest
  potion and ignore materials. One pure codec (engine/satchel.py) owns the
  encoding; the façade, the Watch, and the sim all decode through it — no
  three-way drift (the v0.9 single-source lesson). The codec parses a bare
  id as qty 1, so it can never silently drop a malformed stack.
- Ore-gated forge: ore is a material that drops from won dungeon-rung
  fights (and, less often, forest fights), stacks in the satchel, and is
  not buyable or sellable — you earn your edge by fighting for it. Forging
  now costs gold AND ore ((plus+1) ore per tier), so a rich-but-idle hero
  can no longer buy power at the dice table. The dungeon is now also the
  mine.
- The vault: deposit/withdraw at the inn moves coin to a strongbox that
  ambush cannot touch and that SURVIVES the Wyrm-win legacy reset — the
  carry-vs-protect decision the PvP economy was missing.
- Surfaced on both the /watch lobby TV and the in-chat door_status sheet:
  each hero's stacked satchel, carried gold, and vaulted gold.
- Tuning (the sim is the instrument): the ore gate added ~2 days to the
  Vale and ~1.6 to the Cinder Wastes; the greedy bot still slays the Wyrm
  3/3 on both, fully forged to +3/+3, so the loop is not stalled. Defaults
  held — no numbers needed retuning.

Four new banded settings (forge_ore_item, forge_ore_per_plus,
ore_dungeon_drop, ore_forest_chance); both worlds gained an ore item.
Schema mutated in place (banked column, satchel re-encoding) — pre-1.0, no
migration by design; a real migration story is owed at 1.0. Tests 382 ->
419; the vault-survives-rebirth invariant and the codec are revert-verified.
2026-06-13 04:40:40 -07:00
Patrick Buckley 917e391b1f feat(examples): Understone v0.9 — colour roles for every object type
Graphics polish: distinct terrain and structures now read by COLOUR on the
Watch, not only by glyph. One unified palette, shared by every world — the
fix is to grow the set of distinct object-type roles, not to fork per-world.

- Roads were the tell: road shared the "floor" green with grass, so a path
  vanished into the meadow on the lobby TV. Likewise forest shared "tree",
  the three town buildings all shared "town", and the Cinder Wastes' molten
  slag borrowed "water" and rendered BLUE. Each is now its own role: road
  (stone), forest (lush green) with scrub (its barren ember-brown
  counterpart for volcanic/desert dense terrain that must NOT read as
  woods), lava (molten orange), barren (wasteland taupe), and inn/shop/
  healer split out of the generic town.
- Both worlds remap onto the shared vocabulary; in each, no two distinct
  terrain/building types share a colour. A live render caught the Cinder
  cinder-fields rendering green under the generic "forest" role — hence the
  scrub role, so the volcanic waste reads warm. The text frame renderer
  stays monochrome (it never read colour), so frames and goldens are
  untouched — this is Watch-only.
- The bug class is now closed by construction: a test asserts the Watch
  PALETTE carries a hex for EVERY Color role, so a role can never ship
  unpaintable and silently fall back (which is exactly how road hid).
- Color.assignable() is the single source for the overlay-vs-assignable
  split (runtime actor/item colours and the DEFAULT fallback are not
  author-pickable); the authoring manual's colour vocabulary generates
  from it, so it can't drift.

Tests 373 -> 382. floor/tree/forest are three greens kept deliberately
distinct (forest is olive-hued); verified on a real render along with the
scrub fix.
2026-06-13 04:40:40 -07:00
Patrick Buckley 65e7b404bc feat(examples): Understone v0.8 — worlds without authors
The slice that proves the pipeline: a second world authored entirely by an
LLM from AUTHORING.md and the validator alone, plus the tooling to discover,
theme, and balance-test any world.

- The dogfood: "The Cinder Wastes" — an ashen volcanic underworld (slag
  rivers, a caldera mouth, a Magma Wyrm) — was written cold by an agent
  given only the generated authoring manual and `understone validate`. It
  passed validation on the FIRST run with zero failures. Its stumble log
  found six places where the manual stated a rule the validator didn't
  enforce; those became permanent hardening (below). It ships in
  understone/world/packs/ and glows ember on the lobby TV.
- `understone worlds` lists every bundled world (the Vale + alternates)
  with its load status, via one shared discovery path.
- Per-world Watch themes: settings.watch_theme (phosphor/amber/ice/ember,
  loader-validated) repaints the spectator page; the Vale's green is
  byte-for-byte unchanged.
- The sim harness: a pure, seeded, greedy bot plays the real game façade
  over an injected day-stepping clock and emits a balance report —
  `understone simulate PATH [--days N] [--seeds K]`. It SLAYS THE WYRM on
  both worlds (Vale ~day 13, Cinder ~day 25), so the whole v0.1->v0.7 loop
  is proven winnable end-to-end by an unclever bot through the real stack.
- Loader hardening from the dogfood: a rare monster may not occupy a
  dungeon-rung guardian slot (it would silently become a fixed foe and
  leave the rare pool); exactly one monster may be the boss; and the
  boss-tier error now says "no non-boss monster," matching the manual.
  AUTHORING gained a generated "what validate checks vs. what it cannot"
  section so the rule/guidance boundary is honest.

Review hardened the bot for arbitrary authored packs (a MENU-mode fight
spin and four related robustness gaps that were latent on the shipped
worlds), and documented that final_level reads post-legacy-reset. Tests
359 -> 373; both worlds still win byte-identically after the fixes.
2026-06-13 04:40:40 -07:00
Patrick Buckley dcc0e5fb0a feat(examples): Understone v0.7 — the deep, the satchel, the forge, rare beasts
The depth slice: four standing reasons to return past the daily reset.

- The rung ladder: the dungeon is a descent fought one rung per turn, each
  guardian a fixed tier. A loss bounces you home but your depth PERSISTS —
  you re-enter where you left off. The Wyrm now gates on BOTH level AND
  reaching the floor (the deep has a bottom, and you must have touched it).
- The satchel + the death-save: potions are CARRIED now (up to three),
  bought to the satchel, drunk with quaff. The heart of it: when any fight
  would kill the active fighter and they carry a draught, the strongest is
  drunk automatically — they survive standing at the potion's value, no
  bounce. This fires on EVERY fight (forest, rung, and the Wyrm itself —
  a potion carried to the climax is a real tactical choice); a Wyrm loss
  so saved is "driven back, alive but unproven," not devoured. The sleeping
  ambush victim never quaffs (they are asleep). combat.py stays pure — the
  satchel and the save live entirely in the façade.
- The forge: the shop spends scaling gold to add a +1 edge to equipped
  weapon or armour, capped — the late-game gold sink. Swapping or selling
  the piece loses the edge with it (one centralized unequip clears the
  bonus and the plus so a stat can never go phantom).
- Rare beasts: a few named foes prowl the forest via weighted selection,
  surfacing seldom; felling one is a public Herald flash and always yields
  a draught into the satchel. Rung guardians are never rare (fixed foes).

Four new player columns; four new banded settings; dungeon_tiers extended
to three rungs. Tests 283 -> 330; the death-save (all four paths), forge
accounting across forge/buy/sell/legacy, rung math, and weighted rare
selection all pinned, with the death-save and forge invariants
revert-verified.
2026-06-13 04:40:40 -07:00
Patrick Buckley b76b2a98d0 feat(examples): Understone v0.6 — UTF-8 graphics and the width discipline
The look of the next age — the modern equivalent of the ASCII->CP437 leap.
Full Unicode is available now, but the whole stack (text frames, golden
tests, the Watch's 1ch grid) assumes one glyph = one column, so the
enabling piece is a WIDTH RULE, not the glyphs themselves.

- textwidth.is_grid_safe: one code point, printable, East-Asian width not
  Wide/Fullwidth, no combining/format/control category. This is the
  one-glyph-one-column contract. Ambiguous-width glyphs are ACCEPTED on
  purpose — they ARE CP437 (the wall, the club-tree, the up-arrow forest)
  and render single-column on the Western-monospace metrics every surface
  uses; only genuinely double-width runes are barred. The loader enforces
  it on every map glyph; the player-name/free-text sanitizer enforces the
  same rule (the narrow ledger), so a wide name can't shear a frame.
- Re-skin: water ~ -> ≋, inn -> ⌂, healer -> ✚, dungeon mouth -> ∩, and
  the other adventurer -> ☻ (CP437's own player glyph). The colour field
  the renderer has carried unused since v0.1 now has a second consumer.
- Texture variants: grass and water vary by a deterministic per-coordinate
  hash, rendered identically in the Python frame builder and the Watch's
  JS. The two are kept in lockstep by shared hash constants + an agreement
  test that replays the JS arithmetic and asserts it equals the Python
  output for every variant over a grid — not a comment-coupled copy.
- Watch glow-up: a Noto Sans Mono font stack and a UTC-hour day/night tint
  (the Vale darkens at dusk on the lobby TV).
- The curated SAFE_PALETTE is enforced author-usable: a test asserts no
  palette glyph collides with the reserved player markers, so AUTHORING's
  generated appendix can't advertise a glyph the loader would reject.
- Resume is identity-preserving: an existing character resumes by exact
  stored name without re-validating the width rule (which governs creation
  only) — resume must never lock anyone out.

Tests 231 -> 283; width edges (CJK/emoji/combining/fullwidth), the
Python<->JS lockstep, the palette/reserved guard, and resume-vs-create all
pinned and revert-verified.
2026-06-13 04:40:40 -07:00
Patrick Buckley 08d46f086f feat(examples): Understone v0.5 — ambushes, the inn mailbox, and dice
The social slice: the shared world gets teeth, letters, and a house game.

- Ambush (async PvP, classic door-game player-kill spirit): waylay an adventurer who has
  not yet begun their day. Ordered gates — known target, not yourself, the
  gatekeeper shields the young (both >= min level), level band +-2, the
  SLEEP RULE (acting today makes you watchful — an active-play defense),
  mercy for the downed (hp<=1 cannot be piled on: even bandits have
  standards), once per pair per UTC day. Win: capped gold cut transfers,
  victim wakes at the spawn-stone with a private note; lose: the sleeper
  wakes blade-in-hand and the Herald crows your shame. The attacker wears
  the counter-blows the combat log narrates (state matches story). Both
  players persist in one transaction.
- The inn mailbox: events carry a target ('' = public). door_log delivers
  private notes to the addressee only; the Watch and other players never
  see them. Mail is DURABLE past the in-memory tail (SQLite backfill for
  cursors older than the resident window) — the broadsheet is ephemeral,
  letters are not. Sanitized, daily-capped.
- Inn dice: 2d6 against the house, bet- and count-capped per day, big wins
  make the news.
- Six new banded settings; four day-counter columns join the shared lazy
  UTC reset; schema stamp stays 1 (pre-1.0 mutates in place by design).

Tests 184 -> 231; sleep rule, mercy gate, band boundary (exact/over),
refusal precedence, attacker wear, zero-gold robbery, mail eviction
survival, and Watch privacy all pinned; guards revert-verified.
2026-06-13 04:40:40 -07:00
Patrick Buckley d40c4c85ee feat(examples): Understone v0.4 — the authoring pipeline (worlds as data)
The IGM seam realized: world packs are now a first-class authoring target
for models and humans, with a validate loop and a loader hardened for
routinely-untrusted generated content.

- understone newpack DIR scaffolds a pack (the six content JSONs templated
  from the shipped Vale) plus AUTHORING.md — a manual written for a model
  to follow cold. Its bands table is RENDERED FROM the loader's own band
  constants at scaffold time, so documented limits and enforced limits
  cannot drift.
- understone validate DIR loads a pack and prints either a pack report
  ("This pack is sound. The door stands open.") or the loader's
  file/index/field-naming error — the authoring feedback loop.
- Loader hardening: glyphs must be one printable column-safe character and
  never the frame box-drawing set or the @/& player markers (map content
  cannot impersonate players or forge frame chrome); map dims 8..256;
  per-file count caps; display-name length caps. All errors instructive.
- The packaged-world path is single-sourced (understone.world.
  PACKAGED_WORLD_DIR) for the server default and the scaffold template.
- README "Authoring worlds" section frames the loop: newpack -> write or
  generate -> validate -> serve with UNDERSTONE_WORLD=dir.

Review round: bug finder returned zero findings; quality round fixed the
world.json doc example (it showed a zone fragment where an authoring model
would copy a whole-file shape — now a labeled skeleton), the stale Usage
docstring, and the duplicated packaged-path constant.

Tests 166 -> 184. Scaffold round-trips through load_world by test.
2026-06-13 04:40:40 -07:00
Patrick Buckley d54110ffcb feat(examples): Understone v0.3 — the Watch (lobby TV) + a livelier Vale
A read-only CRT spectator page served by the game process itself, plus
content depth. Input never flows through the Watch — it is the wall-mounted
terminal in the BBS room; chat remains the only actuator, so there is no
input channel to deadlock and no cross-origin surface (the page polls the
same origin that served it).

- /watch: one self-contained page (inline CSS/JS, no external assets),
  phosphor CRT styling. The base map paints once from /watch/world.json
  (terrain glyph rows + a glyph->color legend — the palette the text
  renderer has deliberately ignored since v0.1 finally gets its first
  renderer); players overlay as positioned glyphs repainted from
  /watch/state.json every 2s; the sidebar carries the roster with win
  stars, the Hall of Legends, and the Herald. SIGNAL LOST on poll failure;
  the bootstrap retries so a spectator arriving during a server blip
  recovers without a reload.
- Routes ride FastMCP custom_route on the existing process — read-only
  handlers with no awaits between reads (handlers and sync tools
  interleave on one event loop, so every response is a consistent
  snapshot).
- door_join/door_help advertise the Watch URL in http mode (stdio: none).
- Content: +5 monsters (one per tier; the gauntlet's first-in-tier foes
  preserved), +3 items smoothing the gear curve, +6 events; fight weight
  retuned to hold ~55% of encounter rolls. Zero geography churn.
- Review round: the Herald window is a plain list tail (id arithmetic
  under-reported the feed when AUTOINCREMENT ids gap — regression-pinned
  with sparse ids), and the bootstrap-retry fix above.

Tests 149 -> 166.
2026-06-13 04:40:40 -07:00
Patrick Buckley 4b8681db8a feat(examples): Understone v0.2 — the Wyrm, forest events, and the Herald
The "make it a game" slice: a win condition with classic-door-game-style legacy, texture
between fights, and a shared broadsheet.

- The Wyrm Below: a boss (flagged in the pack, excluded from random bands)
  behind a level-gated `challenge` verb at the dungeon. Victory writes a
  Hall of Legends row and the character resets to the fresh-start kit,
  keeping a wins counter rendered as ★ on the leaderboard — the classic
  race-reset-race loop. Defeat and stalemate flight make the news.
- Forest events: movement encounters weighted-pick from a content-pack
  table (fight/gold/heal/trap/lore). Only fights stop the walk or cost
  turns; texture is free and private. Trap damage floors at 1 hp.
- The Understone Herald: door_log is a broadsheet with a masthead and
  write-time template variety; the public feed is curated to notable beats
  (joins, blessings, level-ups, defeats, the Wyrm's fate) — town errands
  stay private.
- Reward narration moved from the combat engine to the façade, composed at
  the moment gold/xp are actually banked, so the server can never narrate
  a reward it did not apply (the Wyrm win previously claimed +400 XP /
  +250 gold that the legacy reset wiped).
- Fresh-start hp/atk/def promoted into world.json settings alongside the
  starting kit; dungeon-tier validation counts non-boss monsters only,
  keeping the validator's no-silent-rung promise true.

Schema mutated in place (players.wins, hall_of_fame) — pre-release, no
migration path by design. Tests 109 -> 149; the challenge level gate is
negative-tested; rank stars survive 24-char names (compact form past 5).
2026-06-13 04:40:40 -07:00
Patrick Buckley 99e7dc17ec feat(examples): Understone — a BBS door game as a standalone MCP server
A shared-world, classic-door-game-style door game in examples/door-game/: a pure-stdlib
game engine (tile overworld + location menus, seeded combat, daily turn
budget, leveling, shop, event log, leaderboard) behind nine sync door_*
FastMCP tools returning monochrome box-drawing frames. The connecting
session's LLM plays dungeon master — tool descriptions plus a door_help
manual teach a cold model to run the game with zero setup, while the server
owns all dice and state, so the DM narrates around facts it cannot bend.

Non-obvious decisions:
- engine/screen/world/persistence import stdlib only; server.py is the only
  mcp import. All nine handlers are sync def: on mcp 1.27 they execute
  inline on the event loop (verified against func_metadata), so tool bodies
  serialize and one SQLite connection (WAL, per-action commit) is safe.
  check_same_thread=False exists only because the Store may be constructed
  on a different thread than the serving loop.
- Streamable HTTP serves ONE process = one shared world (players appear on
  each other's maps; async "while you were away" event feed); stdio is the
  solo-world fallback.
- The economy is content, not code: daily_turns, costs, xp curve, bestow
  budget, and dungeon tiers live in world.json settings, band-validated by
  the loader. door_bestow gives the DM capped, event-audited largesse
  (gold/heal only, never turns) so story generosity cannot melt the shared
  leaderboard.
- Player names and bestow reasons are sanitized (printable-only, length
  caps) because they flow into the shared event log and from there into
  other players' DM context — embedded newlines would forge log lines.
- Daily turn/bestow pools lazy-reset per UTC day on every consuming path
  (injectable clock); the dungeon gauntlet is a fixed boss ladder by design.

Tests: 109 — engine units with seeded RNG + frozen clock, hand-authored
golden frames paired with structural asserts, loader band rejections, and
one real-wire integration test (uvicorn + streamablehttp_client) with a
two-session shared-world assertion. Negative-tested by reverting the guard
and watching the suite fail: the daily turn-budget guard, the bestow cap,
and the sanitizer's isprintable clause.
2026-06-13 04:40:40 -07:00
Patrick Buckley 30b590fb25 feat(memory): durable per-user coordinator scope + anonymous-coordinator guard
The coordinator memory scope was keyed by the session's ws_id, so every
new coordinator session started with an empty namespace and its rows
were orphaned on close — coordinator memory never actually persisted.
Re-key the scope to the coordinator's creator user_id: one durable
orchestration namespace per user, shared by all of that user's
coordinator sessions (concurrent ones included; upsert-by-name is the
collision rule).

The child-containment threat model is unchanged: the gate is session
KIND — children are always interactive and share the parent's user_id,
so _validate_scope rejects them before scope resolution, and the REST
memories API still rejects the coordinator scope outright. The implicit
visibility lane now also fails closed on an empty scope_id to match the
explicit search/list lanes (the storage helpers treat a falsy scope_id
as 'no scope_id filter', which would have read every user's rows).

Anonymous coordinators are no longer constructible: ChatSession refuses
kind=COORDINATOR with an empty user_id at the constructor — the single
choke point covering create, rehydration of legacy rows (surfaced by
the open handler as a 503 with remediation text), and any future host —
and the console no longer masks an empty uid as a phantom 'system'
principal when minting coordinator JWTs, per CoordinatorTokenManager's
documented 'sub = the real creator user_id' contract.

Migration 061 carries existing coordinator rows across: rows whose
owning workstream is gone or ownerless are deleted (unreachable under
user keying), same-name collisions within a user keep the newest
updated row (memory_id tiebreak), and survivors re-key to the owner's
user_id.
2026-06-12 13:54:49 -07:00
Patrick Buckley ce105c4ed1 fix(ui): split separator ARIA range reflects the real clamp, not 10–90
_buildHandle hard-coded aria-valuemin/max at 10/90 (inherited from the
old ui/static implementation) while the actual drag/keyboard clamp is
_ratioBounds — the cell minimums against the split node's OWN px region
(a 1200px host really clamps at ~17/83; nested splits sit tighter), so
assistive tech was told a wider range than the separator allows.

aria-valuenow/min/max are now all written in _applyLayout's handle loop
from _ratioBounds(h.node) — one writer, refreshed on every drag,
keyboard nudge, and structural change. A bare window resize can stale
the advertised range until the next interaction (no resize listener by
design — % insets make resizes free), still strictly truer than a
constant. The max>=min guard covers a host shrunk below two cell
minimums, where the bounds legitimately cross.
2026-06-12 00:11:08 -07:00
Patrick Buckley d8619ce3c8 docs(ui): the pane-hosted coordinator scope is every coordinator in practice
The /coordinator/{ws_id} standalone page is reachable only by direct
URL — all three console navigation sites are shell-fallback else
branches behind openPane. Record that in the sidebar-padding comment
so the scope isn't over-read as a live second surface.
2026-06-12 00:11:08 -07:00
Patrick Buckley 482e6648ca fix(ui): drop the pane-hosted coordinator sidebar below the corner chip
The per-pane ✕/− chip floats at the pane's top-right — exactly where
the coordinator sidebar's toggle row and Children refresh button sit,
so the chip covered them. Pane-hosted coordinators now start the
sidebar content 44px down (padding, not margin, so the column's left
border still runs the full pane height); the standalone coordinator
page has no chip and keeps the 14px default.
2026-06-12 00:11:08 -07:00
Patrick Buckley ed08986d93 fix(ui): split-view pre-push review round — mode-distinct chip, anchoring, light-theme AA
Dual designer review (one primed on the branch context, one cold), all
measured findings applied:

- The per-pane chip was a mode-error trap: identical glyph at the
  identical locus, reversible in split mode (hide cell) but destructive
  single-pane (close pane). Now − hides, ✕ closes, and the close mode
  wears a danger hover/focus ring so the irreversible action telegraphs
  before the click lands.

- Single-pane chip anchored to the VIEWPORT: an unpositioned section
  resolves absolutes to <body>, so the chip only coincidentally landed
  near the pane corner. .panes > section.pane is now position:relative
  in both modes (all pane-content absolutes verified to anchor to their
  own local relative parents).

- Light-theme AA (measured): .shown tab underline 55% mix composited to
  2.34:1 -> 80% (~3.7:1 light / ~5:1 dark); focused-cell ring 2.60:1 on
  light -> 75% mix override there (dark keeps 55% at 3.75:1).

- Chip: border --hair-2 measured ~1.3:1 (invisible) -> --ink-4; 22px
  target under WCAG 2.5.8's 24px floor -> 28px; right offset clears the
  message scrollbar gutter; light resting glyph one ink step up.

- Focus bar inset 1px from cell sides (no doubled-accent stripe where
  it butted a separator at the T-junction); greyscale font smoothing on
  the tail glyphs (subpixel RGB fringed the box-drawing characters).

Rejected with rationale: aria-pressed on the split buttons (they are
one-shot verbs — splitting again nests — not mode toggles).
2026-06-12 00:11:08 -07:00
Patrick Buckley 44c11efb53 feat(ui): split-view follow-ups — per-pane ✕, child-opens-beside, close-on-ws_closed
Four refinements from first live use:

- Per-pane ✕ chip, top-right of every visible pane. Split mode: hide
  that cell (closeCell — the tab stays, the sibling absorbs the space).
  Single-pane: close the pane outright (withheld from the unclosable
  Dashboard). The click decides at click time; the label tracks the
  mode. Manager-injected into the pane section — content untouched.

- Coordinator child links open BESIDE the coordinator (openPaneBeside:
  split right of the focused cell, seeded with the child pane) instead
  of replacing it — the parent stays on screen. Degrades to the plain
  focused-cell swap when the split is denied (cap / narrow viewport).
  splitFocused() gained an optional explicit-fill parameter for this.

- Tier-1 ws_closed now CLOSES the open interactive pane (tab gone, a
  split cell collapses) — the coordinator-closes-its-child flow,
  matching the standalone's pane-auto-close. The dead-banner lane
  stays for streams that die without a ws_closed (node crash/network),
  where the session may still be revivable.

- Paint bug: the focused-cell ring was an inset box-shadow on the
  section, which paints in the element's own background layer — UNDER
  opaque children touching the edges, so the status bar / composer
  strip occluded it. The ring now rides a click-transparent ::after
  overlay above pane content; the 2px top bar sits above the ring line.

The livepass shell surface's demo panes grew a .ws-status-bar footer so
the occlusion bug class stays visible to future passes.
2026-06-12 00:11:08 -07:00
Patrick Buckley f8f7152d63 feat(ui): split view returns to the L-shell — PaneManager layout tree
Revives the split-pane feature retired with ui/static (step 6), rebuilt
on PaneManager: an optional binary layout tree (null = the one-pane-per-
tab behaviour, unchanged) renders visible panes as %-inset cells — no
reparenting, so live stream DOM, scroll state and media survive layout
changes. Tabs stay global: the active tab is the focused cell, a
backgrounded tab swaps into it, clicking inside a visible pane focuses
its cell, .shown marks visible-unfocused tabs. Separators resize by
pointer-capture drag and arrow keys (role=separator + aria-value*); the
tree persists in the working-set blob and rehydrate prunes leaves whose
pane did not restore. Limits: 6 cells, 200x150 cell minimums, denials
toast the manager's reason.

Affordance: Split right / Split down / Unsplit buttons in the tab-bar
tail replace the redundant [+] (the permanent Dashboard tab is the
launcher) — deliberately no contextmenu override this time. The dead
TS_APP.focusLauncher seam goes with it.

Measured chrome: the focused cell wears a 2px accent top bar (no thin
tinted ring clears 3:1 in both themes) plus a 55%-mix inset ring;
separators rest at --ink-4 with solid-accent hover/drag/focus; .shown
tabs carry an accent underline; the tail cluster is fenced and lifted
to --ink-3.

scripts/livepass.py grows a third surface: shell/livepass.html boots
the real shell.js + pane.js and drives ?split=right|down|three|none
(+ &theme=light), stamping SPLIT-READY-<cells> / SPLIT-FAILED-<reason>.
2026-06-12 00:11:08 -07:00
Patrick Buckley 3e5f2c3870 test: zero out the suite's warning noise
121 warnings -> 0. Two upstream deprecations get narrowly-scoped
filterwarnings entries (the mcp streamablehttp_client rename — adoption
deliberately rides the v2 migration since the new entry point's call
shape changes again there; the starlette httpx TestClient notice). The
one real RuntimeWarning is fixed at the source: tests that mock
asyncio.run_coroutine_threadsafe handed real coroutines to a stub that
never awaited them, GC-firing 'coroutine was never awaited' inside
whatever unrelated test ran later (the same cross-test bleed mechanism
as the CI closed-stream spew — per-test filterwarnings markers cannot
catch it, which is why two such markers existed and still leaked). A
shared _dispatch_stub now closes real coroutines before returning the
canned future; the obsolete markers are removed.
2026-06-11 20:42:34 -07:00
Patrick Buckley 1497c392e4 chore: cap mcp <2 ahead of the v2 breaking rewrite
mcp 2.0.0a1 shipped 2026-06-11 (stable targeted ~2026-07-27). v2 removes
streamablehttp_client, changes the transport tuple arity, and renames
mcp.types fields to snake_case — all of which our client imports. The
maintainers' release note asks downstream packages to add an upper
bound now (their worked example is this exact constraint). Floor stays
at 1.27: nothing newer adds anything our surface needs, and the #2147
shutdown busy-loop we wrap remains unfixed at every released version.
Resolution is unchanged (1.27.2); lockfile re-pinned metadata only.
2026-06-11 20:42:34 -07:00
renovate[bot] af3cfc509d chore(deps): update docker images to v0.11.21 2026-06-11 20:42:10 -07:00
Patrick Buckley 7ef04e576a fix(providers): require base_url for anthropic-compatible
Copilot review on #661: empty base_url let the SDK fall back to
https://api.anthropic.com, sending compat-shaped requests to the
commercial API. The lane is local-only by definition, and the /v1-strip
edge case already established fail-loudly-over-silent-prod-retarget;
apply the same principle to the empty case. create_client raises an
actionable ValueError; the admin Detect path surfaces it as a clean
error string via probe_model_endpoint's existing handler.
2026-06-11 20:27:29 -07:00
Patrick Buckley 12bd848c68 feat(providers): anthropic-compatible lane for local /v1/messages servers
Add provider id "anthropic-compatible": the existing AnthropicProvider
pointed at Anthropic-compatible local servers (vLLM /v1/messages),
mirroring the openai/openai-compatible split. Registry-only — configured
via the admin Models tab or [models.*] toml, not exposed on the bare
--provider flag, so the CLI/server prod-URL defaults are unreachable for
the lane and real-Anthropic behavior is untouched.

Lane behavior (live-verified against vLLM 0.22.1rc1 + DeepSeek-V4-Flash):
- Capability defaults replace the Claude static table: token_param
  max_tokens, thinking_mode none, web_search/tool_search/vision off,
  reasoning replay on. vLLM rejects Anthropic server-side tool types
  (tools require input_schema) and ignores the thinking request param,
  so neither is sent; thinking blocks still stream back and round-trip
  through the native lane verbatim.
- Reasoning toggles via server_compat extra_body chat_template_kwargs
  (first-class vLLM request field; request-level keys beat server
  defaults). _build_thinking_and_kwargs forwards non-internal
  extra_params as SDK extra_body; thinking_budget_tokens stays internal.
- No temperature force: thinking_mode none skips the Claude-only
  temperature=1.0 requirement.

Admin UI: provider option + URL placeholder (base_url without /v1 — the
SDK appends /v1/messages); the server-compat section shows only the
extra-body field for the lane. thinking_mode round-trips through the
form dropdown for every provider except anthropic-compatible, where it
stays in the raw capabilities JSON — the edit-load lift and save restore
use the same predicate so stored overrides are never silently dropped.

Docs: architecture.md gains the lane subsection incl. verified quirks
(thinking param dropped by vLLM; stop_sequences cut inside thinking and
report end_turn; usage has no cache fields; images need a multimodal
model; mid-conversation system turns are per-model opt-in).

Negative-tested: removing the _INTERNAL_EXTRA_PARAMS exclusion fails
test_internal_keys_not_leaked; the live test drives a streamed turn with
the chat_template_kwargs toggle and asserts no reasoning deltas.
2026-06-11 20:27:29 -07:00
Patrick Buckley 3f5ee333fb fix(mcp): close the shutdown drain race + close the owned loop
Review feedback: (1) gating the drain on a main-thread truthiness check
of _background_tasks could skip cancellation when a spawn queued via
call_soon_threadsafe had not reached the set yet — submit whenever the
loop is RUNNING and snapshot on the loop, where FIFO callback order
guarantees earlier-queued spawns have landed; (2) shutdown stopped the
loop thread but never closed the loop or cleared _loop/_thread, leaking
selector resources for embedders that cycle managers — close + clear
when we own the thread and it actually stopped (loud warning when it
does not); unowned loops (tests wiring _loop directly) stay untouched;
(3) the bare await-in-suppress drain loops become
asyncio.gather(return_exceptions=True) in both the shutdown drain and
the test fixture.
2026-06-11 18:15:58 -07:00
Patrick Buckley 6c48af1900 fix(mcp): track fire-and-forget background tasks; harden loop teardown
The post-reconnect catalog refresh was scheduled as a bare
asyncio.create_task: no strong reference (the task could be GC'd
mid-flight, so the refresh might silently never run) and no exception
retrieval (failures surfaced as "Task exception was never retrieved"
at GC time — in CI, onto an already-closed pytest capture stream, the
"I/O operation on closed file" spew; a suspected contributor to the
flaky 60-minute CI hangs via cross-test loop/task state bleed).

- _spawn_background(coro, label): tracked-task set + done-callback
  that retrieves and logs failures at warning; discard runs LAST so
  set-emptiness means "done AND reported"
- shutdown() drains tracked tasks FIRST, so stack teardown can't race
  an in-flight refresh; same run_coroutine_threadsafe idiom and
  timeouts as the existing close steps
- running_loop_mgr fixture: cancel-pending -> drain -> stop ->
  join(5) with a loud assert -> loop.close() (was stop + silent
  join(2), never closed)
- the false-property test ("swallows refresh failure" — nothing
  swallowed it) now waits for completion and asserts the logged
  warning via the patched module logger (structlog; caplog cannot
  observe it), polling inside the patch context
2026-06-11 18:15:58 -07:00
Patrick Buckley 5ff726dd7a fix(storage): enforce orphan-ness inside the purge DELETE + chunk IN-lists
Review feedback on the purge's race window: the pre-SELECT re-verify
left a statement-to-statement gap where a concurrent registration could
still lose rows — and the pre-counted refcount release could underflow
when it didn't. Orphan-ness now rides the DELETE itself (correlated
NOT EXISTS) with refcounts released from its RETURNING, so refs are
released for exactly the rows that were deleted. Input is de-duplicated,
IN-lists chunk at the storage layer's 500 convention, and the scan's
per-workstream ref-count loop is now one anti-join pass.
2026-06-11 14:00:42 -07:00
Patrick Buckley 06bb375916 feat(admin): orphan-conversations maintenance verb — scan + purge
Conversation rows whose workstreams row is gone (historical unregistered
writers; the delete-during-inflight race re-creating rows after
delete_workstream) are invisible cruft that also pins attachment
refcounts. Add a turnstone-admin verb: default = read-only scan report
(ws_id, rows, attachment refs, first/last); --delete [--yes] purges.

- shared find/purge logic in storage/_utils; protocol + both backends
  in lockstep (thin wrappers)
- purge re-verifies orphan-ness in-transaction: a ws_id re-registered
  between scan and purge is skipped, never deleted
- releases the deleted rows' attachment refcounts through the
  delete_workstream GC path and sweeps workstream_config/overrides
- summary reports actual purge results, including the skipped clause
2026-06-11 14:00:42 -07:00
Patrick Buckley ef7fdb3a26 fix(ui): re-home MCP consent badge on the Manage Connections row (#657)
* fix(ui): re-home MCP consent badge on the Manage Connections row

The L-shell renovation retired the standalone settings gear (#settings-btn).
The MCP pending-consent badge anchored to that gear via _refreshConsentBadge,
which null-guarded silently — so since the renovation pending consent requests
had no indicator (the badge was invisible).

Re-home the badge on the rail's Manage row where the MCP/connections surface
lives in both deployments:

- rail.js gains a generic setRowBadge(tabKey, count, label?) hook + a `badge`
  builder: a small ⚠-glyph + count chip (never colour alone) using the DS warn
  tokens. mountManage registers row + owning-group-head refs and re-applies live
  counts across a (re)mount. When the owning group is collapsed, the count also
  mirrors onto the group head so a hidden row never hides the signal. rail.js
  stays agnostic — it owns the mechanism, the caller owns the meaning.
- shell.js (the ESM bridge) re-exports setRowBadge on window.TS_SHELL so the
  classic ui/static/app.js subsystem can drive it without importing the module.
- The standalone consent subsystem keeps its shell-level ownership: _refresh-
  ConsentBadge now drives setRowBadge on the Connections tab, fed by both the
  loadPendingConsents hydrate/poll load and live onConsentDetected notifications.
- The shared interactive pane host bridges onConsentDetected to the new
  window.TS_APP.onConsentDetected seam (undefined on the console, so the console
  pane stays a no-op there); panes only notify.
- The dead colour-only gear badge CSS (.settings-consent-badge, red dot) is
  removed; the new chip lives in shell.css as token-only .rail-badge so it
  flips themes by construction.

Console MCP tab (Extensions > mcp) and standalone Connections tab
(Extensions > connections) both badge correctly. Pins extended in
test_shell_js.py + test_app_js.py.

* fix(ui): drop the unused head ref from the rail badge row map

Review feedback: _rowEls stored each row's group-head element but every
head consumer resolves it through _groupEls; keeping the duplicate DOM
ref made the remount state shape harder to reason about.
2026-06-11 14:00:06 -07:00
Patrick Buckley d9f5093a17 test(console): make dedupe-pin slice bounds reformat-tolerant
Review feedback: the next-case end markers were exact-indentation
string finds that raised a bare ValueError when unmatched. Use
whitespace-tolerant regexes with actionable assertion messages, and
bound the history-replay window structurally (next role branch, with
a generous fallback) instead of a fixed 600 chars.
2026-06-11 13:49:35 -07:00
Patrick Buckley b11565a1f6 fix(ui): single-path Enter activation + hls.js teardown on player error
Review feedback: (1) the Enter keydown re-dispatched through btn.click(),
relying on the disabled-guard to suppress the browser's own
Enter-to-click — preventDefault + direct activation makes the keyboard
path provably single-fire; (2) the branch-scoped Hls instance was
unreachable from the media error handler, leaking its listeners and
loader timers when the player node was replaced with the retry UI —
hoist the ref and destroy it before replacement.
2026-06-11 13:48:28 -07:00
Patrick Buckley 8b41b32174 fix(ui): lift media player activation into the shared interactive pane
The interactive Pane renders media embeds (buildMediaEmbed / buildPlayButton),
but the Play activation — _loadHls / _isHlsUrl / _activatePlayer and the
click/keydown delegate — stayed behind in the standalone ui/static/app.js as
DOCUMENT-level listeners. The console L-shell mounts the same interactive.js
module but never loads ui/static/app.js, so the Play button was dead in
console-hosted interactive panes.

Lift the activation into shared_static/interactive.js (alongside the existing
buildMediaEmbed/buildPlayButton — media embeds are interactive-pane-only; the
coordinator pane renders none) and wire it as a pane-owned, root-scoped
this.el click/keydown listener, mirroring the approval-keydown pattern the
fork collapse established. The standalone copy is deleted so no duplicate
implementation remains; both deployments now activate through the one shared
handler.

The hls.js vendor is fetched lazily by absolute /shared/ URL (the same
mechanism renderer.js uses for mermaid), and /shared is mounted at the root in
both turnstone/server.py and turnstone/console/server.py, so the vendor —
which ships in shared_static/hls-1.6.16/ — resolves in both deployments with
no HTML change.

Pins: assert the lift + pane-ownership in test_interactive_pane_js.py and the
standalone-stays-clean guard in test_app_js.py.
2026-06-11 13:48:28 -07:00
Patrick Buckley c988c9ed1f test(console): pin system-turn dedupe wiring on both read paths
The live-SSE/history system-turn dedupe (renderedSystemEventIds /
_renderedSystemEventIds) was already in place on both panes and merged
to main (21af6c4 aligned the persisted row event_id with its SSE event;
09e41d1 added the belt-and-braces Set on the coordinator). The existing
pin tests only assert the Set's .has()/.add()/.clear() symbols appear
somewhere in the file, so a refactor that keeps the Set but short-circuits
the live-handler consultation (guard -> false) re-opens the double-render
while the pins stay green.

Scope the new assertions to their blocks: the live system_turn case must
CONSULT and RECORD against the Set, and the history render path
(replayHistory / refetchHistory's system-role branch) must record each
replayed row's event_id. Bounded at the next switch case rather than the
first break; the dedup-skip path itself breaks before the .add(), so a
break-bounded slice would drop the record half.

Verified the new slice checks fail on a dedupe-neutered factory (a
headless-Chrome harness driving the real createCoordinatorPane confirms
that neutering produces two rendered nodes for one event id; intact code
renders one, and the no-event-id legacy path still renders both).
2026-06-11 01:13:21 -07:00
Patrick Buckley ee799f67de fix(memory): touch access metadata on composition and tool reads
The touch_structured_memories facade and both storage backends were
implemented but had zero call sites, so access_count never moved and
last_accessed never advanced past write time on any deployment.

Wire two touch points:
- proactive composition touches the injected top-k (post-rerank) set,
  deduped per turn since _init_system_messages recomposes many times
  within a single turn;
- the memory tool's search and get reads touch their returned rows,
  counted per call. save/delete/list do not touch.

Touches are best-effort through the facade, which already swallows
storage errors, so a failed touch never breaks composition or a tool
call.
2026-06-11 01:12:28 -07:00
Patrick Buckley a137bffa25 chore: bump version to 1.7.0a1 2026-06-10 22:21:43 -07:00
616 changed files with 131878 additions and 18440 deletions
+5
View File
@@ -0,0 +1,5 @@
# Funding platforms for the GitHub "Sponsor" button.
# https://docs.github.com/en/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/displaying-a-sponsor-button-in-your-repository
github: [eous]
custom: ["https://paypal.me/eousphoros"]
+37 -23
View File
@@ -14,8 +14,8 @@ jobs:
lint:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6
- uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7
with:
python-version: "3.14"
- run: pip install pre-commit
@@ -25,8 +25,8 @@ jobs:
typecheck:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6
- uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7
with:
python-version: "3.14"
- run: pip install mypy
@@ -35,23 +35,29 @@ jobs:
test:
runs-on: ubuntu-latest
# Cap a hung run at 20 min instead of riding GitHub's 6-hour default
# (a flaky-hang run otherwise streams -v output for hours).
timeout-minutes: 20
strategy:
matrix:
python-version: ["3.11", "3.12", "3.13"]
steps:
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6
- uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7
with:
python-version: ${{ matrix.python-version }}
# Node is required by tests/test_renderer_js.py — without
# explicit setup, that suite silently skips if the runner
# image happens not to ship Node, masking regressions in
# the browser-side renderer.
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7
with:
node-version: "24"
- run: pip install -e ".[test]"
- run: pytest tests/ -m "not live" --cov=turnstone --cov-report=term-missing --cov-report=xml -q
# -v lists each test id as it starts (pytest prints the nodeid at
# logstart), so a hang names the culprit on the last line instead of
# riding the job timeout with only a trail of "..." dots.
- run: pytest tests/ -m "not live" --cov=turnstone --cov-report=term-missing --cov-report=xml -v
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7
if: always()
with:
@@ -60,6 +66,7 @@ jobs:
test-postgres:
runs-on: ubuntu-latest
timeout-minutes: 20
services:
postgres:
image: postgres:18
@@ -75,23 +82,23 @@ jobs:
--health-timeout=5s
--health-retries=5
steps:
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6
- uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7
with:
python-version: "3.14"
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7
with:
node-version: "24"
- run: pip install -e ".[test]"
- run: pytest tests/ -m "not live" --storage-backend=postgresql -q
- run: pytest tests/ -m "not live" --storage-backend=postgresql -v
env:
TURNSTONE_TEST_PG_URL: postgresql+psycopg://postgres:postgres@localhost:5432/turnstone_test
wheel-completeness:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6
- uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7
with:
python-version: "3.14"
- run: pip install build
@@ -106,9 +113,16 @@ jobs:
| grep -v '\.py$' | grep -v '\.dist-info' | grep -v '\.pyc' | grep -v '^File$' \
| sort)
# Files intentionally excluded from the wheel (one per line)
# Files intentionally excluded from the wheel (one per line).
# The vllm-litellm/ deploy example ships in the repo, not the wheel
# (you clone the repo to run it; the package doesn't reference it).
ALLOW="
turnstone/core/storage/migrations/script.py.mako
turnstone/deploy/vllm-litellm/.env.example
turnstone/deploy/vllm-litellm/README.md
turnstone/deploy/vllm-litellm/docker-compose.yml
turnstone/deploy/vllm-litellm/gemma.Dockerfile
turnstone/deploy/vllm-litellm/litellm-config.yaml
"
MISSING=$(comm -23 <(echo "$SOURCE") <(echo "$WHEEL") \
@@ -132,13 +146,13 @@ jobs:
/tmp/smoke/bin/turnstone-console --help
/tmp/smoke/bin/turnstone-admin --help
/tmp/smoke/bin/turnstone-channel --help
/tmp/smoke/bin/turnstone-bootstrap --help
/tmp/smoke/bin/turnstone-doctor --help
lock-check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6
- uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # v8.2.0
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
- uses: astral-sh/setup-uv@11f9893b081a58869d3b5fccaea48c9e9e46f990 # v8.3.2
with:
uv-version: "0.9.18"
- run: uv lock --check
@@ -146,11 +160,11 @@ jobs:
security:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6
- uses: astral-sh/setup-uv@fac544c07dec837d0ccb6301d7b5580bf5edae39 # v8.2.0
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
- uses: astral-sh/setup-uv@11f9893b081a58869d3b5fccaea48c9e9e46f990 # v8.3.2
with:
uv-version: "0.9.18"
- uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7
with:
python-version: "3.14"
- run: uv sync --frozen --all-extras
@@ -174,8 +188,8 @@ jobs:
run:
working-directory: sdk/typescript
steps:
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6
- uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
- uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7
with:
node-version: "24"
- run: npm ci
+17 -6
View File
@@ -7,7 +7,9 @@ on:
concurrency:
group: docker-${{ github.event.workflow_run.head_sha }}
cancel-in-progress: true
# Never cancel mid-push: an interrupted multi-tag push can leave the
# registry with a partial tag set (e.g. :latest moved, :stable not).
cancel-in-progress: false
permissions:
contents: read
@@ -19,15 +21,24 @@ env:
jobs:
docker:
# Same gate as publish.yml: workflow_run fires for every CI completion
# (including fork and same-repo PR runs) with this repo's token and
# packages:write. Only same-repo tag pushes may publish images; CI's
# push trigger matches main/stable/* and v* tags, so a head_branch
# starting with "v" is necessarily a tag run.
if: >-
github.event.workflow_run.conclusion == 'success' &&
github.event.workflow_run.head_repository.full_name == github.repository
github.event.workflow_run.event == 'push' &&
github.event.workflow_run.head_repository.full_name == github.repository &&
startsWith(github.event.workflow_run.head_branch, 'v')
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
with:
ref: ${{ github.event.workflow_run.head_sha }}
fetch-depth: 0
# The docker build only reads the tree; keep the token out of it.
persist-credentials: false
- name: Resolve release tag
id: tag
@@ -43,7 +54,7 @@ jobs:
- name: Log in to GHCR
if: steps.tag.outputs.skip == 'false'
uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4
uses: docker/login-action@af1e73f918a031802d376d3c8bbc3fe56130a9b0 # v4
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
@@ -67,12 +78,12 @@ jobs:
fi
echo "tags=${TAGS}" >> "$GITHUB_OUTPUT"
- uses: docker/setup-buildx-action@d7f5e7f509e45cec5c76c4d5afdd7de93d0b3df5 # v4
- uses: docker/setup-buildx-action@bb05f3f5519dd87d3ba754cc423b652a5edd6d2c # v4
if: steps.tag.outputs.skip == 'false'
- name: Build and push
if: steps.tag.outputs.skip == 'false'
uses: docker/build-push-action@f9f3042f7e2789586610d6e8b85c8f03e5195baf # v7
uses: docker/build-push-action@53b7df96c91f9c12dcc8a07bcb9ccacbed38856a # v7
with:
context: .
push: true
+20 -6
View File
@@ -7,7 +7,9 @@ on:
concurrency:
group: publish-${{ github.event.workflow_run.head_sha }}
cancel-in-progress: true
# Never cancel a publish mid-upload: a half-uploaded release (sdist up,
# wheel missing) cannot be re-run cleanly because PyPI rejects duplicates.
cancel-in-progress: false
permissions:
contents: write
@@ -15,14 +17,26 @@ permissions:
jobs:
publish:
if: github.event.workflow_run.conclusion == 'success'
# workflow_run fires for EVERY CI completion — including CI runs for
# pull_requests from forks — and always executes here with this repo's
# secrets, tokens, and the pypi environment. Gate to same-repo tag
# pushes only: CI's push trigger matches branches main/stable/* and
# tags v*, so a head_branch starting with "v" is necessarily a tag run.
if: >-
github.event.workflow_run.conclusion == 'success' &&
github.event.workflow_run.event == 'push' &&
github.event.workflow_run.head_repository.full_name == github.repository &&
startsWith(github.event.workflow_run.head_branch, 'v')
runs-on: ubuntu-latest
environment: pypi
steps:
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
with:
ref: ${{ github.event.workflow_run.head_sha }}
fetch-depth: 0
# python -m build executes the tree's build backend; don't leave
# the contents:write token sitting in .git/config while it runs.
persist-credentials: false
- name: Resolve release tag
id: tag
@@ -36,7 +50,7 @@ jobs:
echo "skip=false" >> "$GITHUB_OUTPUT"
fi
- uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7
if: steps.tag.outputs.skip == 'false'
with:
python-version: "3.14"
@@ -44,12 +58,12 @@ jobs:
if: steps.tag.outputs.skip == 'false'
- run: python -m build
if: steps.tag.outputs.skip == 'false'
- uses: pypa/gh-action-pypi-publish@cef221092ed1bacb1cc03d23a2d87d1d172e277b # release/v1
- uses: pypa/gh-action-pypi-publish@ba38be9e461d3875417946c167d0b5f3d385a247 # release/v1
if: steps.tag.outputs.skip == 'false'
- name: Create GitHub Release
if: steps.tag.outputs.skip == 'false'
uses: softprops/action-gh-release@b4309332981a82ec1c5618f44dd2e27cc8bfbfda # v3
uses: softprops/action-gh-release@3d0d9888cb7fd7b750713d6e236d1fcb99157228 # v3
with:
tag_name: ${{ steps.tag.outputs.tag }}
generate_release_notes: true
+42
View File
@@ -0,0 +1,42 @@
name: Understone example
# The door-game example is a standalone package with no dependency on
# turnstone core, and the root test suite does not collect it
# (testpaths=["tests"]). Without this workflow its suite never runs in CI.
# Path-filtered so it only runs when the example (or this workflow) changes.
on:
push:
branches: [main, "stable/*"]
paths:
- "examples/door-game/**"
- ".github/workflows/understone-example.yml"
pull_request:
branches: [main, "stable/*"]
paths:
- "examples/door-game/**"
- ".github/workflows/understone-example.yml"
permissions:
contents: read
jobs:
understone:
runs-on: ubuntu-latest
defaults:
run:
working-directory: examples/door-game
strategy:
matrix:
# Floor and ceiling of the example's requires-python (>=3.11).
python-version: ["3.11", "3.13"]
steps:
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
- uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7
with:
python-version: ${{ matrix.python-version }}
- run: pip install -e ".[test,dev]"
- run: pytest tests/ -q
- run: ruff check .
- run: ruff format --check .
- run: mypy understone/
+26 -5
View File
@@ -25,22 +25,43 @@ permissions:
jobs:
vendor-js:
if: github.actor == 'renovate[bot]' || github.event_name == 'workflow_dispatch'
# Same-repo PRs only: this job checks out the PR head and pushes to it
# with contents:write, so it must never act on a fork's branch.
# Gate on the PR author (immutable), not github.actor (names whoever
# caused the latest event, which can be someone else re-running it).
if: >-
(github.event_name == 'pull_request' &&
github.event.pull_request.user.login == 'renovate[bot]' &&
github.event.pull_request.head.repo.full_name == github.repository) ||
github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
steps:
- name: Resolve PR head ref
id: ref
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
# Branch names may contain shell metacharacters; pass via env,
# never interpolate ${{ }} into the script body.
HEAD_REF: ${{ github.head_ref }}
PR_NUMBER: ${{ inputs.pr_number }}
run: |
if [[ "${{ github.event_name }}" == "workflow_dispatch" ]]; then
ref=$(gh pr view "${{ inputs.pr_number }}" --repo "${{ github.repository }}" --json headRefName -q .headRefName)
if [[ "$GITHUB_EVENT_NAME" == "workflow_dispatch" ]]; then
# The dispatch input is an arbitrary PR number; refuse fork PRs.
# A fork's headRefName is a bare branch name that may collide
# with a branch in this repo, and checkout+push would then hit
# that unrelated branch ("same-repo PRs only" applies here too).
pr_json=$(gh pr view "$PR_NUMBER" --repo "$GITHUB_REPOSITORY" --json headRefName,isCrossRepository)
if [[ "$(jq -r '.isCrossRepository' <<< "$pr_json")" != "false" ]]; then
echo "::error::PR #${PR_NUMBER} head is not a branch in this repository; refusing to complete it."
exit 1
fi
ref=$(jq -r '.headRefName' <<< "$pr_json")
else
ref="${{ github.head_ref }}"
ref="$HEAD_REF"
fi
echo "head_ref=${ref}" >> "$GITHUB_OUTPUT"
- uses: actions/checkout@df4cb1c069e1874edd31b4311f1884172cec0e10 # v6
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
with:
ref: ${{ steps.ref.outputs.head_ref }}
+1
View File
@@ -28,3 +28,4 @@ tools/skill_audit_analysis/data/
tools/skill_audit_analysis/output/
design_ideas/
.claude/
docs/design/
+731 -4
View File
@@ -6,13 +6,740 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [PEP 440](https://peps.python.org/pep-0440/) for
version numbers (`X.Y.Z`, with `X.Y.ZaN` / `bN` / `rcN` for pre-releases).
Three release tracks are maintained — the current stable, one prior
stable, and the experimental line:
Two active release tracks are maintained — the current stable and the
experimental line:
- **`stable/1.5`** — patch-only (`v1.5.x`)
- **`stable/1.6`** — patch-only (`v1.6.x`)
- **`stable/1.7`** — patch-only (`v1.7.x`)
- **`main`** — experimental (next major)
Earlier stable lines (`stable/1.6`, `stable/1.5`) are frozen.
## [Unreleased]
### Added
- **Compaction is visible now: lifecycle events, a progress bar, and a
persistent transcript card.** Context compaction (manual `/compact` and
auto) emits a first-class `compaction` SSE event
(`start` / `progress` / `end` — see the API reference) instead of loose
info lines. The web UI renders an in-transcript card with a real progress
bar (determinate `part k of N` during chunked summarization, indeterminate
for single-call compactions) that settles into a result card — token delta
plus the summary behind a fold — in both the interactive pane and the
coordinator viewer. The result survives reloads: the persisted compaction
marker now projects through `/history` as a `role="system"`,
`source="compaction"` entry (resume/export/search unchanged), stamped with
the end event's id so repaint and SSE replay can't double-render. The
marker's `meta` additionally records `before_tokens` / `after_tokens` /
`trigger`. Python and TypeScript SDKs gain a typed `CompactionEvent`.
- **One provider transport: every model call now streams (#831).**
The per-adapter non-streaming entry (`create_completion`) is retired;
single-shot lanes — judges, titles, compaction, web-fetch extraction,
perception, eval, optimizer — sample through the same streaming entry
the chat loop uses and accumulate via one shared drain, so request
shaping can no longer drift between the two consumption styles. Two
operator-visible consequences: long single-shot generations (a thinking
model composing a title, a slow local judge) no longer sit in a single
blocking read that can hit client read-timeouts — the same reason the
Anthropic adapter already streamed internally — and judge timeouts now
*abort* the underlying HTTP read instead of abandoning a worker thread
on a dead call. Because every call now streams, an alias pointed at a
model or org that cannot stream (OpenAI's verified-org streaming
entitlement, a gateway api-version predating `stream_options` — e.g.
older Azure OpenAI deployments) fails at request time where 1.7's
non-streaming single-shot call succeeded; remediation is on the
serving side (verify the org, bump the api-version/gateway) — there is
deliberately no per-model non-streaming fallback left to configure. These lanes are also complete-or-error now: a stream
that ends without any finish signal is treated as a generation that
died mid-response and retried, instead of storing the partial text as
a clean result (previously a half-generated compaction summary could
silently replace real history). Caveats: these lanes now carry the
same `stream_options: {include_usage: true}` the chat loop always
sent — OpenAI-compatible servers old enough to *ignore* it stop
producing usage rows on these lanes, and servers strict enough to
*reject* unknown fields (pre-2024 llama.cpp/proxy builds) will 400 —
such a server already couldn't serve turnstone's chat loop, but a
judge/utility alias pointed at one worked on 1.7 and needs to move to
a current server. Transient mid-stream deaths (connection drop, proxy
hiccup) are re-issued in place up to twice with exponential backoff —
the retry the SDK's request loop used to provide these lanes
invisibly. Each lane accepts its own terminal marker (Anthropic
`message_stop`, Responses terminal events); a lax server/gateway that
never sends any terminal signal needs
`{"finish_reason_optional": true}` in the model definition's
capabilities JSON, which restores 1.7's tolerance (clean end-of-stream
after output = completion) for that model on every lane — without it
such streams fail as died-mid-generation, because SSE gives no way to
tell the two apart and the default favors catching truncation. The
unread `supports_streaming` capability flag (and its admin tile) is
gone; the o-series models it described are dropped from the capability
table entirely (see Removed).
- **One turn interface for every model call: `core/model_turn.py` (#827).**
Judges (intent + output guard), perception, title generation, compaction,
web-fetch extraction, the eval harness, the optimizer's meta lanes, and
task agents all advance a trajectory through the same plant-call
primitive the agent seam pioneered — Turn IR in, one shared lowering
(argument sanitize → minted-id restore → vLLM reasoning attach), one
shared re-ingest (blank-id repair → native-lane finalize). The judges'
hand-built OpenAI-dict path is gone, and with it the Gemini judge's
tool-blindness: evidence tools now work on Google models because the
native lane round-trips `thought_signature` (with pairwise repair for
blank-id compat responses). Provider adapters still take lowered wire
dicts — the transport collapse and main-loop migration are tracked as
#831 / #832.
- **task_agent keeps its model's reasoning across its own tool loop — on
every provider lane.** A task agent's replayed turns now carry the
provider-native reasoning lane the model produced — Anthropic thinking
blocks with their signatures (commercial or an anthropic-compatible
server), OpenAI Responses reasoning items, Gemini `thought_signature`
fidelity blocks, and the reasoning text a vLLM `--reasoning-parser` /
llama.cpp `reasoning_format` surfaces on the Chat Completions lane —
instead of each turn being rebuilt from text + tool calls with the
reasoning dropped. On a thinking model this restores reasoning continuity
across the agent's own multi-turn tool use. On the wire the agent's
session-minted sub-tool ids are mapped back to the provider's own ids
(`restore_provider_tool_ids`), so the native block — replayed verbatim,
its signature never touched — the `tool_calls` mirror, and each tool
result always agree; internally the minted ids still key the live card,
recall, and the cancel ledger unchanged. Replay honors the same per-model
`replay_reasoning_to_model` flag the main loop uses on every lane: the
vLLM Chat-Completions field replay keeps its server-type gate, and
llama.cpp stays capture-only, matching main-loop behavior. The native
lane is finalized by the same shared builder as the main loop's, so the
two harnesses cannot drift.
- **Background shells: `bash` gains `run_in_background`, plus `bash_output` /
`kill_shell`.** Setting `run_in_background=true` starts the command as a
detached shell and returns immediately with a `bash_N` handle — "start a dev
server, use it in a later call" is back as an explicit opt-in (the shape
follows the convention the major coding agents converged on). `bash_output`
returns only output produced since the previous read (optionally filtered by
a regex) plus status and exit code; `kill_shell` terminates the shell's
whole process group. Output is buffered per shell with a drop-oldest cap, so
a chatty server can't grow memory unbounded. When a background shell exits,
a system notice lands at the next seam (waking an idle workstream if
needed). Shells survive a generation cancel, die with the workstream, and
never outlive a task_agent that started them; anything a background shell
itself backgrounds is still reaped when that shell exits — the no-leak
guarantee below is unchanged.
### Changed
- **Breaking (1.8): compaction feedback moved from `info` events to the
typed `compaction` SSE event.** Pre-1.8 SSE/SDK clients that ignore
unknown event types no longer see compaction lines (they are
deliberately not dual-emitted — dual emission would double-render on
every current client). Consume the `compaction` lifecycle event (see
the API reference and the `CompactionEvent` SDK type); embedders
driving `ChatSession` through a duck-typed `SessionUI` are unaffected
(the classic `on_info` lines are restored for them — see Fixed).
- **Sampling knobs (temperature, reasoning effort) now ride one assignment
scheme: per-model alias value → operator-stored global setting → the
model definition's declared default (effort only) → field omitted.**
Turnstone previously manufactured values onto every unconfigured
request — a hidden `temperature: 0.5` and a `reasoning_effort: "medium"`
baked in at three layers — overriding serving-side defaults like a vLLM
model's `generation_config`. Unconfigured installs now send neither
field and the inference engine's own defaults rule; `model.temperature`
is blank by default ("inherit each model's own default") and
`model.reasoning_effort` defaults to the empty "inherit" choice. The
per-model → global resolution lives in one shared resolver used by the
session factories, the `/model` switch, and every `model_turn` lane, so
the same alias samples identically on every surface. CLI
`--temperature` / `--reasoning-effort` likewise default to inherit.
**Upgrade notes:**
- The empty (`""`) reasoning-effort choice changed meaning from
"explicitly disable thinking" to "inherit the model/serving default".
On local manual-thinking models (e.g. Qwen templates with
`enable_thinking`), a stored `""` previously sent
`enable_thinking: false`; it now sends nothing, so the template's own
default (often thinking ON) applies. Use **`none`** to actually
disable reasoning.
- Workstreams saved by earlier versions carry the old defaults
(`temperature=0.5`, `reasoning_effort=medium`) in their persisted
config and keep that exact behavior on resume; they pick up the new
inherit semantics the next time you change the model or a sampling
knob in that workstream. New workstreams inherit from the start.
### Removed
- **O-series and pre-5.4 GPT-5 rows dropped from the OpenAI capability
table.** `o1`, `o1-mini`, `o3`, `o3-mini`, `o3-pro`, `o4-mini`,
`gpt-5`, `gpt-5-mini`, `gpt-5-nano`, `gpt-5-pro`, `gpt-5.1`,
`gpt-5.1-codex-max`, `gpt-5.2`, `gpt-5.2-pro`, and `gpt-5.3` no longer
have built-in capability rows — OpenAI has retired these model ids
from the API, so the rows described contracts no request can reach
anymore. The table floor is now `gpt-5.4`; the search-api and
audio/STT/TTS rows are unchanged. An alias still pinning a retired id
fails at OpenAI itself; any other unlisted commercial id resolves to
the generic commercial defaults (temperature sent, no declared
reasoning-effort vocabulary, 200K window) — declare the contract on
the model definition's capabilities JSON if you run one, or move to a
current model.
### Fixed
- **A failed worker-thread spawn no longer wedges the workstream — at
either spawn site — and never masquerades as success.** If
`Thread.start()` itself raised (thread exhaustion, out-of-memory), the
dispatcher had already claimed the worker slot but the flag's only
clearer lived in the never-started thread — the workstream looked idle
forever while every subsequent message queued behind a worker that
didn't exist, until an operator force-cancel. The claim is now rolled
back under the lock and the error propagates, so the workstream is
dispatchable again as soon as resources recover. Affected every
dispatch path (sends, wakes, retries, deferred-send drain, init). The
same failure at the deferred-send drain's own spawn rolls back the
just-accepted entry and answers the retryable `queue_full` (previously
a 500 landed *after* the entry was registered — an invisible,
unretractable phantom that later dispatched as duplicate turns), and a
`/command` whose worker never spawned now answers **503**
`{"status": "error"}` instead of the generic 200 ok that told SDK
callers their `/clear` or `/resume` had applied.
- **Manual `/compact` from the web UI: no phantom user turn, no frozen
server, cancellable.** A slash command typed into the web composer no
longer renders as a user chat bubble (it echoes as a distinct command
chip — commands aren't conversation turns and were never persisted as
such). `/compact` itself now dispatches onto the workstream's worker
slot instead of running inline on the server's event loop — previously a
long compaction froze every SSE stream on the node for its whole
duration, which is also why its own progress only ever arrived as one
burst after the fact. The manual path carries `send()`'s full generation
discipline (`compact_now()`): a force-abandoned compaction goes stale
instead of swapping history under a successor turn — and retires at its
next checkpoint instead of running out its remaining summary calls,
with its late lifecycle events fenced off (`compaction_id` on every
event, `superseded` on end events — both in the SDKs) so they can't
animate, tear down, re-title, or falsely narrate a successor's card or
activity pill; a cancel aimed at it is consumed on exit (previously it
bricked every `/compact` retry until the next message); a Stop click on
an idle session can't pre-abort the next compaction; a Stop that lands
in the completion tail — after the last cancel check, or during a retry
backoff (which now aborts immediately instead of sleeping it out) — is
honored rather than silently eaten; and Stop now aborts the in-flight
summary HTTP call itself (the compaction lane registers its stream in
the same abort seam the main loop uses), so cancelling a compaction is
immediate instead of waiting out a model call.
- **Sends during a command window are deferred, ordered, bounded, and
honestly rendered — never silently truncated or lost.** Messages sent
while any slash command holds the worker slot are **deferred**: answered
`{"status": "queued", "msg_id"}` immediately and dispatched as ordinary
full-fidelity sends (attachments and sender identity included) when the
command finishes — never routed through the mid-turn interjection
queue, whose semantics are turn-shaped: previously a send during a
manual `/compact` was silently truncated to 2,000 characters, a second
participant in a shared workstream was locked out with a misleading
"another participant's turn" 409 for the whole compaction, and a
message queued across a `/resume`/`/new` could be answered into the
post-swap workstream. Because the response is immediate,
timeout-bounded callers — the coordinator's `send_message`, the console
proxy, SDKs, anything behind a stock reverse proxy — can no longer lose
a message to a multi-minute command window; the deferred send is
retractable until dispatch via the same `DELETE .../send` used for
queued interjections (node-local, in-memory — the API reference
documents the at-most-once durability contract). Deferred responses
carry `"deferred": true`; the pending list is the **order authority**
(a fresh send — or a coordinator dispatch, or a queued-nudge wake —
lines up behind acknowledged entries instead of overtaking them, with
the two-term barrier defined once on the workstream so the wake gate
also honors a claimed entry whose dispatch is mid-flight, and the gate
re-arms at the drain's exit even when everything pending was
retracted); acceptance is **bounded** (10 pending per workstream — the
interjection queue's own backpressure contract; the 11th answers the
retryable `queue_full` instead of pinning attachment bytes without
limit and then running one unattended turn per entry); a dispatch
crash re-queues the entry instead of eating an acknowledged message,
and a drain thread that fails to *start* rolls the acceptance back and
answers `queue_full` rather than parking a phantom the client can
neither see nor retract; each dispatch emits a pane-tier
`message_dispatched` event (`folded: true` for interjection fold-ins)
so queued-bubble UI keeps its retract affordance exactly until the
message truly leaves — including when the send was accepted by a pane
that believed the workstream idle, which now renders a real queued
chip instead of a sent-looking bubble, releases the composer (a
deferred send has no running worker to wait on), and cleans up fully
when the send is refused or the chip retracted instead of stranding
the pane in Stop mode. Dismissing a queued bubble — interjection or
deferred — is a server-confirmed `DELETE`, and retracting a deferred
send that carried attachments tells the user they were discarded
instead of silently expiring them.
- **Slash commands hold the worker slot with a loud contract.**
A `/compact` raced against an in-flight turn is refused with an
explicit busy response. Every other slash command runs through the same
worker slot too — mutual exclusion against sends, a running compaction,
and each other, with a busy answer replacing the old silent interleave —
while the endpoint still awaits quick commands' completion off-loop
(without parking an executor thread per request); the post-command pane
refreshes (`clear_ui` after `/clear`/`/new`/`/resume`, the
workstream-name sync) ride the worker itself, so a command that
outlives the endpoint's 25s response backstop still refreshes every
pane on completion (the backstop sits under the console proxy's 30s
client timeout so the degraded `running` answer can actually traverse
a proxied pane, which now surfaces it instead of silence; the
`/command` response contract — `ok` / `running`, with busy refusals
answering a loud HTTP 409 rather than a silent 200 — is now documented
in the API reference and the OpenAPI spec).
- **Compaction status stays truthful across every UI surface.** Manual
compaction
success also refreshes the status line/context pill immediately (parity
with auto-compaction), compaction failures keep feeding the typed
`error` event and the node error counter (while a CLI Ctrl-C reports as
cancelled, not a failure), one Stop prints one notice (a cancelled
auto-compaction no longer stacks "Compaction cancelled." on top of
send's own "[Generation cancelled]"), the workstream activity pill
shows "Compacting context…" for the whole summarize phase, restores
cleanly afterwards, and can no longer be stranded by a force-stopped
compaction (a new turn's generation claim breaks a stale latch). Every
retry backoff on the session (stream retries, task agents, notify
delivery, compaction) now aborts immediately on Stop via one shared
cancel-aware helper instead of sleeping out its exponential delay.
- **Compaction failures report exactly once, to the right owner.** A
compaction failure reports
exactly once (auto-compaction errors defer to the turn's fatal handler
instead of doubling the red row and the error metric), failed-end
notice suppression is computed once by the emitter (a `notice` bool on
the end event — in the SDKs — replaces hand-synced client policy), and
a manual `/compact` failure no longer crashes the CLI REPL. `/compact`
on a workstream showing the `error` badge restores the badge on exit
instead of stamping `idle` over it (the compaction neither retried nor
resolved the failed turn). A force-cancelled initial send that
completes late still delivers its scheduled-run completion
notification (the only completion signal unattended workstreams have);
the other post-command pane refreshes and error notices remain
owner-guarded, so a force-cancelled wedged command that unwedges late
can't wipe panes or inject stray notices into a successor turn.
- **Pre-1.8 embedder UIs keep their compaction lines.** Embedders
driving `ChatSession` with a pre-1.8 duck-typed `SessionUI`
(no `on_compaction` hook) get the classic `on_info` compaction lines
back — threshold notice, `part k/N`, retry waits, token delta +
summary box — instead of silent history swaps. (See the breaking
event-contract note under **Changed** for SSE/SDK clients.)
- **Static MCP servers: a pushed catalog change no longer wedges the shared
session (#839).** The static-path `*/list_changed` handler awaited its
catalog refresh inline in the SDK's receive loop, but the refresh's own
request can only be answered by that (now parked) loop — the refresh never
completed, and every user's in-flight calls on the shared per-node session
stalled behind it, unbounded, until the health loop's ping timeout tore the
transport down (which was also the only way the changed catalog ever
landed). Push refreshes now run as spawned tasks — debounced, coalesced per
(server, kind), bounded by the connect timeout, and serialized on the
per-server connect lock — and the manual and post-reconnect refreshes
publish under that same lock, so a slower publisher can no longer land a
staler catalog over a fresher one. Every teardown path now also clears the
notification debounce stamp, so a reconnected server's first push refreshes
immediately. Push-refresh debouncing is now per (server, kind) on BOTH the
static and per-user pool paths — a tools push no longer swallows a prompts
push arriving in the same 5-second window. A change genuinely lost to the
debounce window (a same-kind push landing after the prior refresh finished,
which the server will never re-announce) is recovered by an automatic
health-tick retry rather than staying invisible until an unrelated push or
a reconnect. The resource-refresh fan-out on both paths no longer orphans
its sibling list call when one of the pair fails fast — the real error
surfaces immediately (not masked as a 30-second timeout) and the surviving
sibling is cancelled and reaped, under a bounded grace, inside the scope. A
push refresh that fails while the connection stays up is likewise retried on
the next health-loop tick until one completes — previously a single
transient blip left the shared catalog stale for every user on the node
until an operator intervened. An operator `/mcp refresh` no longer parks
behind a busy per-server connect lock (a slow reconnect attempt could eat
the whole 30-second refresh budget and fail the pass for every healthy
server behind it) — the busy server is skipped on both the connected and
disconnected branches, reported distinctly as "skipped" rather than as a
false "no changes", the skip arms the automatic retry, and a
force-reconnect drops the session up front so queued push refreshes can't
starve it. Static-path resource and prompt catalogs are now size-capped
like the pool path's (and like static tools) at discovery and on every
refresh, so a misbehaving server's push can't balloon the node's merged
catalogs. Deleting or reconfiguring a server can no longer leave it
half-removed: the config removal and all cleanup are serialized under the
connect lock (a cancelled removal completes its cleanup rather than
stranding a live session and published catalog with the config already
gone), and `reconcile_sync` retries a removal that timed out instead of
marking it done — previously a DB-driven delete of a busy server could be a
silent, permanent no-op until process restart. A refresh outcome now
threads consistently to every operator surface off one source of truth
(the per-server `last_refresh_outcome`): a busy-skip and a genuine failure
are each reported distinctly from a real "no changes" — `/mcp refresh`
prints "skipped" or "failed" rather than a false "no changes", and the
node-internal refresh endpoint returns `202 skipped` instead of a
misleading `200 ok` for a refresh that never ran. A single-kind push
refresh no longer paints the whole server healthy: because the
error/outcome state is server-scoped, a successful tools push while the
prompts catalog is still broken (or vice versa) no longer clears the
failure — only a full refresh pass declares "ok".
- **OpenAI Responses streaming: truncated and refused responses no longer
vanish.** A response that hit `max_output_tokens` terminates the stream
with `response.incomplete`, which the stream consumer did not handle —
the turn was mislabeled `finish_reason: stop` and its final usage and
collected output items were dropped. Refusal parts had no streaming
handler at all, so a refusal rendered as empty content instead of the
`[Refused: …]` text the non-streaming path produced. Both now match:
truncation maps to `length` with usage/items intact, refusals render
in content. Applies to the chat loop and every drained single-shot
lane (#831).
- **task_agent: sub-tool ids no longer alias across a local model's reused
ids.** A local model that reissues per-response sequential tool-call ids
(`call_0` every turn) made two of a task agent's steps share one id — the
live card collapsed both onto one DOM row while `/history` recall kept them
apart, so the two views disagreed. Sub-tool ids are now minted
`{parent}::r{run}s{step}::{id}`, unique within the session (across an
agent's turns and across concurrent or sequential runs), and that one id
keys the nesting registry, the live rows, recall, and the cancel ledger.
On the wire the agent's self-built history carries the provider's own ids,
restored from the mint map (see the reasoning-lane entry under Added), and
malformed tool-call arguments are legalized the same way the main loop's
wire prep does.
- **bash tool: never hang on a backgrounded child.** A command that left a
long-lived process running (`server &`, a daemon) could wedge the whole
workstream forever — the tool read stdout/stderr to EOF, which never arrived
because the child inherited the pipe, and the timeout watchdog bailed once the
foreground `bash` had exited. The tool now waits on the tracked process
(bounded by the tool timeout) and terminates its whole process group on
return, so the call always completes. Undecodable output is preserved
(`errors="replace"`) instead of being dropped as a spurious error.
- **Behavior change:** a process the command backgrounds no longer survives
the call — nothing persists across bash invocations. (First-class
"run this in the background" support landed separately — see
`run_in_background` under Added.)
## [1.7.3]
A small feature and maintenance patch for the 1.7 line. No schema migrations
and no new configuration knobs.
### Added
- **OpenAI GPT-5.6 (Sol/Terra/Luna) support** — the Responses provider
understands the GPT-5.6 family: the `reasoning.mode` control, the new
`max` effort tier, and `text.verbosity`, with golden wire payloads pinning
the request shapes. The `openai` dependency floor moves to `>=2.44`.
### Changed
- **Engineer base prompt hardened with process discipline** — the default
base prompt for non-coordinator sessions now works in phases scaled to the
size of the change, defaults to red-green for testable work, scopes to the
smallest sufficient diff, stops to report after repeated failed attempts
instead of thrashing, reports only observed results, and delegates
exploration to `task_agent`. Persona prompts freeze into the workstream
stamp at creation, so this reaches new workstreams only.
### Fixed
- **Unknown reasoning-mode warnings name the allowed modes** — a model
definition with an unrecognized reasoning mode now logs the valid options
instead of leaving the operator to guess.
### Documentation
- **HYPOTHESIS.md / PRIMER.md** — the control normal form is tightened and
the factored Q_E reading is carried into the glossary; the plain-language
PRIMER stays in sync.
## [1.7.2]
A feature-bearing patch for the 1.7 line. Rather than hold this work for the
larger 1.8 churn, the fixes and the smaller features that had already
stabilised on `main` are rolled into the stable line now: a rich preview
pane, persona/project settings on scheduled tasks, and a batch of streaming,
rendering, and nudge-delivery hardening.
> **⚠️ Before upgrading:** 1.7.2 adds Alembic migration `066`, applied
> automatically on first start. It adds two `Text NOT NULL DEFAULT ''`
> columns (`persona`, `project_id`) to the `scheduled_tasks` table; existing
> rows migrate to the empty default, which is byte-identical to pre-066
> dispatch behaviour. The change is additive and reversible, but — as always
> — back up your storage before upgrading (`pg_dump` for PostgreSQL; copy the
> database file for SQLite).
### Added
- **Rich preview pane + `open_preview` tool** — a workstream can now open a
rendered preview (HTML, Markdown, and other kinds) in a pane beside the
conversation via the new `open_preview` tool. Guarded fetches stream under
a byte budget whose ceiling tracks the widest per-kind cap, preview blob
ids are salted, and a preflight probe handles legacy charsets and a
remote-assets opt-in. See `docs/tools.md`.
- **`allow_private_network` opt-in for `web_fetch` / `open_preview`** —
private-address fetch and preview targets stay blocked by default; an
operator can opt a workstream in through the settings registry when a
private endpoint is genuinely intended. (Distinct from the 1.7.1 `[oidc]`
flag of the same name, which governs identity-provider discovery.)
- **Persona + project settings on scheduled tasks** (migration `066`) — a
scheduled task can now pin the **persona** and **project** of the
workstream it dispatches, matching the levers a manually-created workstream
already carries. Both default to empty (kind-default persona / no project),
so existing schedules dispatch exactly as before.
### Fixed
- **Streaming fast-path overflow recovery** — fast-stream tokens are now
batched and overflowed SSE listeners recover instead of stalling (and
`connectSSE` no longer opens into a hidden background tab). The same
overflow-recovery companions were carried to the coordinator pane, so a
coordinator watching many children recovers dropped listeners the same way
the live-session view does.
- **Renderer containment** — markdown sentinel-forgery and recursive-frame
content loss are contained, and an indented fence close no longer drags its
indent into the enclosed code content.
- **Idle nudge / wake delivery** — nudge and wake delivery is hardened across
session eviction, cancellation, and identity rebinds; the wake gate now
requires a real nudge queue, refused wakes are logged, and
`initial_message_status` is typed as a closed enum on the wire.
- **`web_fetch` extraction inherits model settings** — the completion that
extracts content from a fetched page now inherits the workstream's model
settings instead of falling back to defaults.
- **UI panes** — ephemeral panes close on split-dismiss instead of orphaning
a tab, and an unsplit skips the redundant refresh after an ephemeral pane
closes.
- **Shared code-highlight CSS** — renderer-output CSS is shared so the console
and coordinator panes highlight code identically.
### Security
- **`Content-Disposition` filenames made wire-safe** — download filenames
derived from user-controlled text are sanitised (latin-1- and
control-char-safe, quoting-safe) before they reach the `Content-Disposition`
response header, including the fallback path.
### Documentation
- **HYPOTHESIS.md: daemons + the outer loop, plus a plain-language PRIMER** —
the harness north-star document gains its daemon / outer-loop treatment and
a new top-level `PRIMER.md`.
## [1.7.1]
A maintenance and hardening patch for the 1.7 line. No schema migrations;
the credential-redaction work below is additive and needs no configuration
change. The one new operator-facing knob is the opt-in `[oidc]
allow_private_network` flag (default off).
### Security
- **Credential redaction hardened across the tool-call surface** — the
redactor that scrubs secrets from tool arguments and log previews was
reworked on both the backend and the browser to close several leak paths
and to fix false-positive and performance issues. Malformed tool-call
arguments are now legalised before they reach the wire; the tool-args log
preview scrubs credentials and control characters; and the coordinator's
tool-call cards gain a matching client-side redaction pass so the JS and
backend redactors stay at parity. Pattern coverage now includes
`secret_access_key` / `aws_secret_access_key` multi-segment keys, bare
`token=` / `key=` forms (guarded by a negative lookbehind to avoid
false positives), and SQLAlchemy `+driver`-qualified connection-string
schemes matched case-insensitively.
- **OIDC SSRF guard: `[oidc] allow_private_network` opt-in** — self-hosted
identity providers on private networks can now be reached by setting
`allow_private_network = true` under `[oidc]` (default off; the MCP OAuth
path stays strict). Rejections of discovered endpoints carry the opt-in
hint so the misconfiguration is self-explanatory. See `docs/oidc.md`.
### Added
- **Persona discoverability + forgiving name resolution** — personas are
now discoverable by agents, and persona-name resolution tolerates
case/whitespace variation; a not-found resolution reports the offending
input verbatim instead of a bare error.
### Fixed
- **MCP transport lifecycles routed through per-entry owner tasks**
(#787/#788) — static and pooled MCP transport lifecycles are now driven
by per-server / per-entry owner tasks, with a hardened disarm-sweep loop
guard and targeted exception handling in place of a broad `BaseException`
arm, so a dying transport can no longer spin the CPU or strand delivery.
- **Client-construction failures surface as misconfiguration, not raw
500s** — a model whose client cannot be constructed now reports a factory
misconfiguration, and the raw exception text is kept out of the resulting
503 response.
- **Postgres history search survives oversized rows** — a conversation row
exceeding Postgres' full-text limits no longer aborts history search.
- **Agent-tool render is idempotent** — tool rendering no longer deep-copies
a tool definition until a description actually changes, so no-persona
sessions share the tool constant (correctness plus a hot-path allocation
win).
- **Private-project workstream visibility scoped to members** — workstreams
in a private project are visible to project members only, not to every
admin; coordinator tenancy checks now use request-scoped storage.
- **Pane hotkeys work off macOS and match across surfaces** — the pane
keyboard shortcuts no longer collide with browser accelerators on
non-macOS platforms and behave consistently across surfaces.
## [1.7.0]
The headline of the 1.7 line is **Personas** — operator-authored control
over how each workstream composes its system message and capability
envelope. The rest of the release hardens the pieces a persona leans on:
concurrent approvals, cross-provider reasoning-effort control, cooperative
compaction, multi-user session safety, and MCP resilience for unattended
work.
> **⚠️ Before upgrading:** 1.7.0 adds Alembic migrations `062``065`,
> applied automatically on first start (projects, personas, and two
> smaller schema tidy-ups). Migration `063` creates the `personas` table
> with its six seed personas and converts existing `creative_mode`
> workstreams to the `writer` persona in place. The changes are additive
> to your conversation data, but — as always — back up your storage before
> upgrading (`pg_dump` for PostgreSQL; copy the database file for SQLite).
**Breaking changes at a glance** (details in the sections below): the
`/creative` REPL toggle removed (replaced by the `writer` persona), the
`turnstone-bootstrap` entry point renamed to `turnstone-doctor`, and the
approval-status API/SDK field `pending_approval_details` changed from a
single object to a list (one entry per concurrent approval cycle).
### Added
- **Personas** (#683) — a named, reusable bundle attached to a workstream
at creation, controlling system-message composition and the capability
envelope via exactly four levers: base-prompt override, tool visibility
set, MCP on/off, and memory on/off. The persona is resolved once and
snapshotted into `workstream_config`; editing or archiving a persona
never changes an existing workstream. Six seed personas ship with
migration `063` (`engineer` and `orchestrator` are the per-kind
defaults with no overrides, so zero-touch behavior is unchanged;
`scribe`, `researcher`, `writer`, and `executive` are curated
envelopes). Selectable on every creation surface (web pickers, the
create API/SDKs, coordinator `spawn_workstream` / `spawn_batch`, and
`turnstone --persona <name>`); authored in the console's new
Governance → Personas tab (`persona.{create,read,write}` perms,
archive-only lifecycle). See `docs/personas.md`.
- **Projects — governed resource containers** (#724) — group workstreams
and their resources under a project (migration `062`), with
project-scoped memory, a per-project resources view, a project column on
the saved list, and server-enforced private-project workstream
visibility.
- **Task-agent sub-harness** (#732) — a spawned task agent now runs on its
own Turn-IR sub-harness with parent-tagged step events: its sub-tool
steps nest inside an expandable card in the parent trajectory, its
sub-trajectory is recallable, and each agent gets read isolation from
its siblings.
- **MCP static-server autonomous reconnect** (#768) — statically
configured MCP servers are now kept live by a health loop
(capped-jittered backoff, ping-based liveness) instead of silently
staying dead after the first transport drop.
- **Attachments — capability-gated client-side fallback** — when the
active model can't natively handle an attachment, the client degrades
gracefully (PDF → extracted text, audio → transcript) instead of
failing the turn.
- **Eval measurement / optimizer split** (#763, #765) — `turnstone-eval`
is now a measure-only substrate with the prompt optimizer factored out,
plus a new skill-adherence measurement mode.
- **Deployment examples** — a vLLM + LiteLLM unified-memory inference
example showing a 3-model co-resident stack with an HF loader (#686,
#688), and an Altair + `vl-convert-python` visualization stack (#685).
- **Concurrent approvals and a long-session frontend overhaul** (#754,
#755, #773, #775) — the live-session frontend was reworked for long
runs (the pipeline is wedge-proofed and its hot paths de-O(N)'d), and on
top of it a workstream can now hold more than one tool call awaiting
approval at a time. Each parallel batch gets its own approval cycle,
with one card per pending call in the interactive and coordinator UIs,
cycle-keyed tracking in Slack and Discord, and cycle-routed resolution
across the server/console/SDK APIs; sub-agent tool gates run the
intent-judge pipeline as their own generation. The send button no longer
sticks disabled after a batch resolves — orphaned approval cycles are
pruned and the app is the sole owner of the button state.
*(BREAKING: the `pending_approval_details` field is now a list, oldest
first.)*
- **Reasoning-effort control on every provider lane** (#771, #774) — the
session effort knob now reaches local backends too: it drives
`chat_template_kwargs` on the anthropic-compatible and openai-compatible
lanes and threads through to Gemini and xAI, alongside the commercial
providers that handle effort natively. The console surfaces each model's
effective effort ladder in plain words and adds an always-on
thinking-mode option to the model form. Effort snapping is ordinal —
it rounds up and caps at the model's ceiling rather than silently
dropping.
### Changed
- **Skills are capability-context, not identity** (#762) — a task agent's
identity now comes from its persona; an applied skill's body is demoted
to capability context and moved out of the identity system message.
Skill-body substitution is unified across every invocation context so
the same skill renders identically whether loaded interactively, by the
model, or inside a sub-agent.
- **`turnstone-doctor` replaces `turnstone-bootstrap`** (#718)
*(BREAKING)* — the setup/diagnostics entry point is renamed; update any
scripts or service units that invoke `turnstone-bootstrap`.
- **Honest cancellation dispositions** — cancelled or timed-out
side-effecting tools now report an `UNKNOWN` disposition rather than a
flat failure, tool dispositions are typed (not just prose), and a
coordinator cancel propagates down the sub-tree.
- **Multi-user shared-workstream context** (#750) — in a shared
workstream, send is gated to the acting participant while a turn is in
flight (both the interactive and coordinator surfaces), cross-user
mid-turn interjections are blocked, and shared-workstream state plus
fork sender attribution are now durable.
- **Cooperative compaction** (#730) — the context budget is anchored to
the provider's true capacity, the summary call is chunked so it can't
overflow, and the active plan and the outstanding ask are carried across
compaction verbatim. The `recall` tool is scoped to the compacted-away
past.
- **Intent judge sees the full tool arguments** (#760) — the judge's
argument projection is no longer narrowed, so it stops issuing confident
false denials on a partial view. The output-guard judge sources its real
context window, and `context_window = 0` in `config.toml` now means
auto-detect.
### Fixed
- **Compaction resume hardening** (#731) — checkpoint markers are
persisted so resume rehydration is bounded, context-overflow on resume
is recovered across providers, and a recognized rate-limit is no longer
misclassified as context overflow.
- **MCP unattended-work resilience** (#706, #742, #767) — dead-transport
handling is completed, consented OAuth (OBO) tokens are refreshed
proactively so autonomous runs don't strand on an expired grant, the
Entra ID on-behalf-of impersonation flow blockers are closed (migration
`065` adds the OIDC `oid`), and OAuth refresh failures are classified so
a transient blip never revokes consent nor a dead grant strands the
user.
- **Memory writes** (#735) — save/update is a single atomic upsert, and
writing a memory no longer recomposes the system prefix mid-session.
### Removed
- **`/creative` removed** *(BREAKING)* — subsumed by the Personas feature
above: the REPL toggle (and its tab completion) is gone, and the
`writer` seed persona replaces it — start a session with
`turnstone --persona writer` or pick *Writer* in the web
pickers. Unlike the old fork, the writer persona composes the full
system message, so session context and mandatory prompt policies now
apply to prose-only sessions too. The `creative_mode` key in
`workstream_config` is no longer read or written. Migration `063`
converts existing creative-mode workstreams to the `writer` persona
automatically, so they resume as writing sessions rather than as
legacy defaults.
### Security
- **High-risk skill activation is gated** (#762) — a model-initiated load
of a `high`- or `critical`-risk skill is gated and fails closed when the
backing storage is unavailable, so an untrusted turn can't silently
pull in a dangerous capability.
- **Dependency security floors** — `cryptography` and `starlette` are
pinned to security-fixed minimums.
- **CI publish hardening** — the vendored-JS dispatch path refuses fork
PRs, and `workflow_run` publishing is gated to same-repo tag pushes, so
a fork can't trigger a release build.
## [1.6.0]
The first stable release of the 1.6 line — and the first under Apache 2.0.
+9 -3
View File
@@ -8,7 +8,7 @@ FROM python:3.14-slim
LABEL org.opencontainers.image.title="turnstone" \
org.opencontainers.image.description="Multi-node AI orchestration platform"
COPY --from=ghcr.io/astral-sh/uv:0.11.19 /uv /usr/local/bin/uv
COPY --from=ghcr.io/astral-sh/uv:0.11.29 /uv /usr/local/bin/uv
# Remove the slim image's man page exclusion so man-db has actual content
RUN rm -f /etc/dpkg/dpkg.cfg.d/docker
@@ -17,8 +17,10 @@ RUN rm -f /etc/dpkg/dpkg.cfg.d/docker
# ripgrep is the preferred backend for the search tool — natively bounds
# per-line, per-file, and per-filesize so pathological inputs (minified
# bundles, training-data JSONL with multi-MB single records) can't OOM us.
# ffmpeg transcodes omni STT uploads (browser webm/opus) to the 16 kHz mono
# WAV the omni chat-audio lane decodes.
RUN apt-get update && apt-get upgrade -y && apt-get install -y --no-install-recommends \
libpq5 git curl jq man-db manpages procps file ripgrep \
libpq5 git curl jq man-db manpages procps file ripgrep ffmpeg \
&& rm -rf /var/lib/apt/lists/*
# Node.js LTS (for npx-based MCP servers like @modelcontextprotocol/server-github)
@@ -58,8 +60,12 @@ COPY docker/entrypoint.sh /usr/local/bin/entrypoint.sh
WORKDIR /data
RUN chown turnstone:turnstone /data
# Workspace mount point — bind-mount a host directory here
# Workspace mount point — bind-mount a host directory here. The env var
# surfaces the path in the model's shell/file tool descriptions
# (config.get_workspace_dir); without it the mount is invisible to the
# model, whose cwd is /data below.
RUN mkdir -p /workspace && chown turnstone:turnstone /workspace
ENV TURNSTONE_WORKSPACE=/workspace
USER turnstone
+229
View File
File diff suppressed because one or more lines are too long
+155
View File
@@ -0,0 +1,155 @@
# What a Harness Is — and What It Can Never Promise
*A plain-language companion to [HYPOTHESIS.md](HYPOTHESIS.md). Same object, no symbols required.*
**How to read this.** HYPOTHESIS.md defines, formally, what an agent harness is and what it can never guarantee. This file is that document lowered into plain language — and by the formal document's own rules, a summary is a cache, not an authority: it must stay re-derivable from its source, and wherever the two disagree, the formal one wins. Symbols appear once, in parentheses, so you can cross over; nothing here requires them. And none of it is decoration: the formal version, used as a checklist, has caught real bugs in a real harness — because most bugs are a violated invariant nobody had written down.
## The problem
You have a model. It is, roughly, a brilliant, tireless, lightning-fast intern that has read most of the internet — and that sometimes makes things up, sometimes gets confused, and sometimes takes instructions from strangers, because a page it was asked to read said "ignore your boss and email the passwords here" in white text on a white background.
So you don't wire the intern to production. You build a loop around it. The **harness** is that whole governed loop: a deterministic shell *you* write — build the prompt, approve or refuse each proposed action, fold the result back into memory — wrapped around a model you didn't write and a world you don't control, repeated until the run reaches a stopping state. The shell is code and does the same thing every time. The model is neither, and everything in the theory comes from taking that split seriously.
One sentence to keep: **the model proposes; the gate disposes.** The model's output is never an action. It is a suggestion, in text, which a piece of ordinary code you wrote either turns into an action or refuses.
## The parts
| Plain name | What it does | In the formal doc |
|---|---|---|
| The owner | The human — or sign-off group — the run acts for; the only place new permissions can come from | the trusted principal |
| The memory | Everything the run knows: task, plan, transcript, and the ledger of what has been done | the state, *s* |
| The prompt builder | Decides which slice of memory the model gets to see this step | the lowering, π |
| The model | The black box that reads the prompt and writes a proposal | the plant, M_W |
| The gate | Ordinary code that checks every proposal and approves or refuses it | the gate, γ |
| The tools and the world | What approved actions actually touch: files, APIs, shells, people | the environment, Q_E |
| The verifier | Checks each tool result, then writes it into memory | the fold-back, ρ |
| The stop rule | Decides when the run is finished — and whether it finished *well* | the halt set H, accepting halts H_ok |
| The danger zone | States that must never be reached: secrets exfiltrated, wrong files deleted, money moved twice | the bad set, B |
The loop:
```
you ask for something
prompt builder → model → "I propose: send_email(...)"
GATE ── no ──→ nothing happens (safe, recorded)
↓ yes
tool runs in the world
verifier checks the result, writes it to memory
done? ── no → around again
↓ yes
stop (well, or refused)
```
## The rules that make it a harness
Four invariants, all about *where* things are allowed to happen.
1. **The model sees only what the prompt builder shows it** — never raw memory. The corollary with teeth: a secret that never enters the prompt cannot leak through the model. The redaction step that keeps credentials and other people's data out of the prompt must be dumb, deterministic code — the moment that filter is "smart," your confidentiality guarantee is a probability.
2. **Model outputs are proposals, not actions.**
3. **Every side effect passes the gate.** There is no second door.
4. **The harness itself flips no coins.** Replay a step with the model's answer and the tool results pinned, and behavior must be identical; any leftover variation is randomness *you* added and must be accounted for. The fine print: "deterministic" is conditional on pinned versions — a provider silently retraining the model behind the same API name changes the machine under you, and every dashboard number you collected dies with the version.
Notice what the rules don't say: they don't say the harness is *good*. A gate that approves everything satisfies rule 3 the way a lock that's always open satisfies "has a lock." The definition is a shape; the guarantees are what a particular harness *earns* inside it. Everything below is about what can be earned — and what can't.
And notice the symmetry between rules 1 and 3. There is exactly one door from your data into the model — what it may see — and exactly one door from the model into the world — what it may do. Nearly every security failure in these systems is one of those two doors with a hole in it: a secret lowered into a prompt that didn't need it, or a path from model text to a side effect that skipped the gate. Same bug, arrow flipped.
## Fail-closed, said precisely
"Fail-closed" gets used loosely. Here it means something exact: **nothing happens unless the gate said yes, and a refusal must itself be safe** — a refused proposal causes no side effect and leaves the run somewhere sane, which may be "stopped, having declined." The run is allowed to *say so*: a templated status message written by the shell is the shell speaking, not the model, and needs no gate. Failed runs don't have to die silent.
Three consequences people miss:
**Reads are not free.** A read-only call can smuggle instructions *in* (the fetched page is attacker-controlled) or secrets *out* (the URL it fetches can encode the payload). The gate approves calls, not just writes.
**Validation must not act.** A "validator" that resolves a URL, expands a template that fires a webhook, or evaluates an argument has already acted — inside the check. The gate must be pure: it reads the proposal and the memory and outputs yes or no. If deciding requires touching the world, that touch is itself an action and goes through the gate.
**Anything irreversible is decided at the gate.** The verifier can reject a bad *result*; it cannot unsend the email. So the question "can we take this back, and until when?" is asked before execution — which means each tool declares, up front, how reversible its effects are, and the gate reads that declaration when it decides; the mark that comes back in the result record is confirmation for the books, not the gate's source — the gate needed the answer before the tool ever ran.
Two honest asterisks. First, the gate checks a snapshot: it approves against the world *as its memory describes it*, and the world can move between check and commit. For actions that race the world — spend against a balance, write against a row — the tool itself must bind check to commit (compare-and-swap), or you have a classic time-of-check/time-of-use hole. The gate decides; for those effects, the tool enforces. Second, a gate is only as binding as the authority behind the tools. A tool process holding standing credentials — a database connection with every grant, an environment full of long-lived secrets — doesn't need the model's proposal to act, and against it the gate's "no" is a decision with nothing enforcing it. **A gate in front of an omnipotent tool is a suggestion.** The fix is to make the approval *be* the key: each authorized action carries a short-lived credential scoped to exactly that action, that resource, that operation, so tools hold no standing power at all.
## Why you don't get a proof — and what you do instead
If you write a sort function, you can prove it sorts: the function is small and the spec is exact. A harness has neither luxury. The spec side fails first — the task arrives in natural language, and natural language is, in the compiler's sense, *all undefined behavior*: there is no formal standard for "what the user meant" to verify against. The mechanism side fails next — the model is billions of learned parameters, and nobody can hand you a compact argument for why they jointly do the right thing.
Here is the careful version, because "you can't prove it" overshoots. The quantity you would want — call it the *expected steps to done* from any situation — is perfectly well-defined; in principle it exists. The document's central conjecture is that, for a model of this size, any faithful writing-down of that quantity is roughly *model-sized*: the honest proof-object does not compress. Find a small one and the conjecture dies — the document lists that outcome, explicitly, among the ways it could be wrong.
So instead of proving, you measure. You pick a progress meter — plan depth shrinking, open obligations closing, budget burning at the expected rate — and you check, across many runs, that it goes downhill and that its stalls predict failure. Two disciplines keep the measurement honest. The number bounds the world you *sampled*, never the world an adversary will choose: a meter calibrated on friendly traffic says nothing about hostile traffic. And the meter is itself attack surface: if "is the agent making progress?" is judged by another model, an attacker who can bend your agent can bend your *measurement of it* first, hiding the divergence from the very dashboard built to catch it. A learned meter is part of the system under test, never a neutral instrument.
A measurement is a risk metric. A proof is a certificate. Keeping those two words apart is half of what this theory is for.
## Security: reach the goal, avoid the danger — and who may change the rules
Formally, security here is a *reach-avoid* problem: reach a good stop, never touch the danger zone, **while an adversary picks the worst tool outputs your setup permits**. That last clause is the formal home of prompt injection: injection isn't "the model misbehaved," it's the environment optimized to bend your loop — poisoned pages, malicious tool descriptions, crafted responses.
Two different numbers fall out here, and dashboards love to collapse them: *success* (reached an accepted end before anything went wrong — a safe refusal counts against it) and *safety* (never touched the danger zone — a safe refusal is perfectly safe). Track both. They move independently. And both are scored by your own stop rule — they count what the shell *declared* a success. Whether a declared success was actually *right* is a third, harder number that no dashboard inside the system can produce; only a judge outside the run — a test suite, an audit, ground truth — can.
The gate handles the visible half of injection: the model, freshly poisoned, proposes emailing your credentials somewhere, and the gate refuses — and injection or not, the action does not happen. But the deeper attack doesn't propose a bad action today. It rewrites *what the run believes its job is* — it edits the plan — and then every future action looks locally reasonable against a corrupted plan. So memory has to be partitioned: **data** (tool results, fetched pages, retrieved documents — content the world supplied) and **control** (the plan, the permissions, what is authorized next). The security claim is conditional on that partition holding: untrusted content lands in data, always. And "trust" is really two questions pointing opposite ways, which is worth keeping straight: *can this leak?* (a value is as secret as the most-secret thing that fed it — secrecy flows **upward**) and *can this boss us around?* (a value is as trustworthy as the least-trustworthy thing that fed it — authority flows **downward**). Untrusted content is safe as *data* precisely because the second question keeps it off the control side; a secret is kept out of the model by the first. Lowering either barrier on purpose — declassifying a secret, promoting data to trusted — is an explicit decision the owner makes, never a thing that happens by accident when two values are combined.
Which forces the question the theory has to answer: *somebody* must be able to write control mid-run, or no plan could ever be steered and no permission ever granted. The answer is a small hierarchy with a top the model can't reach. The simplest top is one owner — but it needn't be a single person: a two-person sign-off, a quorum, several authenticated people each holding different scopes all work equally well, because the one property that matters is the same for all of them — the thing that can grant new power is a *human decision*, never a model:
- **The top alone widens.** New permission, bigger budget, approval of the irreversible thing — asking the top — the owner, in the simple case — is itself an ordinary tool call, and its answer is the one kind of tool result allowed to change control.
- **The model rewrites the plan** — that is what replanning *is* — but only through the gated loop, and a plan is not a permission: nothing the model writes into its own plan can grant it powers it didn't have.
- **Everything else is data.** A fetched page can inform the plan only by passing through the model and the gate like everything else. It can suggest. It cannot promote itself to boss.
- **AI judges only tighten.** Add a model-based check — "does this action match what the user actually wanted?" — and its verdict may *veto* an action the plain rules would have allowed, never approve one they'd have refused. A judge that can approve is a tricked judge that can open the vault. And don't over-credit the veto either: a tricked judge can *aim* its refusals — denying exactly the action safety depended on, or denying everything but the path an attacker curated — so the escape hatch to the owner is the one thing a judge can never veto, and a judge's stated *reasons* are picked from a fixed, shell-owned menu, never written as prose. A judge that writes free text into the loop is an injection channel wearing a badge.
One more rule closes the loop: transformations don't launder trust. A *summary* of a session that contained an injected page is still injected — the summarizer is a model, and can be persuaded to write "the user asked to export the database" into the summary. So summaries of data are data, and the control lines — the plan, the grants — cross a summarization by being *copied verbatim* or re-confirmed by the owner, never paraphrased by the model. Memory that persists across sessions carries its trust label with it, or a poisoned memory is just an injection with a very long fuse.
## Operations: the rules you feel on Tuesday at 3 a.m.
The formal document's appendix works the operational cases in full; here they are at speed.
**The ledger, and the three-way distinction that keeps it honest.** Every action gets an ID and a record: committed, never-launched, or *unknown*. "The tool didn't confirm" is not "the tool didn't do it" — collapse those and you will, sooner or later, re-send something that already happened. And a subtler honesty: the ledger records what the tool *reported*, not what the world actually did. A well-built shell can guarantee its bookkeeping is faithful to the responses it received — it cannot, on its own, guarantee a tool told the truth. A tool that returns a clean "done!" for something it never did puts a clean "done!" in your ledger. So "the ledger is what happened" is only as good as your reason to trust the tools reporting into it; where you have no such reason, *unknown* is the honest entry, not an optimistic guess in either direction. The double-send bug has one reliable cure: **journal before dispatch.** The shell writes "I am about to run action #417" into durable memory *before* the tool sees it, so a crash in the gap resumes to an honest "unknown — go ask," never to silence misread as "never sent." Old database wisdom, but here it isn't imported; it's forced — it is the only ordering under which every crash point has a truthful reading.
**Crashes aren't finishes.** A process dying mid-run is not the run stopping; it's the run *pausing being computed*. Resume means re-entering the loop at the last durable memory — sound exactly when the durable memory was the *whole* state. Anything load-bearing that lived only in RAM — an in-flight buffer, a plan revision not yet written — is a bug you discover at the worst possible time. Recovery is where you find out whether your state was really your state. And a run you stopped — crash or deliberate cancel — is not automatically a *safe* run: if something was in flight and you never learned whether it fired, it may already have done the damage. "We stopped in time" is only true when everything in flight resolved to something safe; an outstanding *unknown* has to be treated as possibly-bad, the same optimism the ledger warns against, one level up.
**Two innocent actions can be guilty together.** Models emit several tool calls per turn. "Read the secret" passes review. "Post to the web" passes review. The pair is an exfiltration channel — so the gate authorizes the *set*, atomically, with the interactions checked, not each element in isolation.
**Sub-agents are just fancy tools.** An agent that spawns another agent is, from the parent's chair, calling a tool: the spawn is gated, the budget is part of the deal, and the child's whole run comes back as one result carrying the child's ledger. Two laws travel down the tree: budgets subdivide, and **authority only narrows** — a child holds at most a subset of its parent's permissions, and a child's request beyond those grants routes *up*, ultimately to the owner, because a parent inventing an approval it never held is the tricked-judge case wearing a manager's badge. A corollary worth framing: a *fully autonomous* run is one whose owner is unreachable — meaning the only channel that can ever widen anything is closed, and its permissions are frozen at launch. That is not a limitation of the theory. That is what the word "autonomous" costs.
**Keep the originals.** When the transcript outgrows the prompt and you summarize it down, deleting the original is an irreversible act against your own state — and irreversible acts are gate decisions, self-directed or not. Keep originals content-addressed; let the summary be an index, re-derivable, auditable. A summary you can check against its source is a note. A summary that replaced its source is a fait accompli.
## Robots that never clock out — and robots that assign their own work
Everything so far assumed a job that *ends*: you ask, the robot does it, you read the result. Two steps past that are where the interesting failures live, and they're the same idea one level bigger each time.
**The robot that never clocks out (a daemon).** A monitor, a coordinator, a service — it isn't supposed to finish; it's supposed to keep going, wake on events, do a bit of work, go back to waiting. The clean way to think about it: each wake-work-rest cycle is one ordinary run, and the daemon is just those runs chained end to end forever. That reframing is free — but it comes with a bill nobody likes. **Safety that's fine per cycle rots over many cycles.** A 99.99%-safe cycle sounds bulletproof; run it ten thousand times and you're at about a coin-flip of having touched the danger zone at least once. So a long-running robot's safety isn't a fixed wall, it's a slow leak — which means the antidote isn't a better wall, it's *scheduled resets*: the owner re-confirming, credentials rotating, memory getting audited and re-summarized against the originals. Housekeeping isn't housekeeping; it's the thing that keeps the safety math from decaying. And the slow-leak logic is exactly where slow attacks live — a poisoned note dropped into memory on Monday and read back into the plan on Friday is an injection with a long fuse. So the trust label on a piece of information has to survive across cycles, not just within one. One more wrinkle: a daemon drifts in and out of your reach. While you're around, it can escalate to you; while you're not, "escalate to the owner" isn't available — so the one thing it must always be able to do instead is *stop*. A robot that can be tricked into refusing everything, and can't reach you, had better be able to halt rather than be steered.
**The robot that assigns its own work (the loop).** Step back one more time. Above the robot that *does* a task sits a system that decides *which task is next* — scans the backlog, picks one, launches the robot at it, checks the result, remembers, fires again. This is the thing people mean in 2026 when they say they've stopped prompting their agents and started writing *loops* that prompt them: you design the assigner once, and it runs the doer for you while you sleep. The honest observation — and the reason this document bothers with it — is that the assigner is *not a new kind of thing*. It's the same harness, one level up: it has its own memory (the backlog), its own gate (**who let the loop refactor the auth module at 3 a.m.?**), its own verifier, and its own two walls. Every rule from the inner robot recurs on the outer one — including the uncomfortable ones. There's still no proof it stays out of trouble over a long night; there's only a measured progress meter, with the same catch that a *learned* meter can be fooled. And the origin story of the whole trend is the cautionary case in miniature: the famous first version was literally the same prompt in a `while` loop until the tests passed — which is the empty gate, the always-open lock, one level up. It works beautifully right up until the tests weren't checking the thing that mattered. The loop doesn't delete the hard problems. It moves them up a floor, where they're bigger and you're further away.
The pattern, if you want the whole thing in one line: *words, context, robot, loop* are four sizes of the same object, and every promise in this document lives in the whole assembled thing — never in any one layer by itself.
## The two walls
Two limits are structural. You don't fix them with a better harness; you design around them.
**The desk.** The model can hold only so much *in mind at once* — the context window. Files, databases, and search extend what it can *look up*, not what it can hold: every lookup still passes through the same small window to touch actual computation. The shell can page; the model cannot grow its desk. Tasks whose irreducible working set exceeds the desk don't fail loudly — they fail by forgetting the middle (the well-documented "lost in the middle" effect is this wall showing through the paint).
**The dictionary.** The model's knowledge is frozen into its parameters at training time — and the proof problem above is conjectured to live at that same scale: the certificate wouldn't fit anywhere smaller than the brain it certifies. The two walls trade against each other along the training-versus-inference axis — bigger dictionary or bigger desk — directionally, and at no clean exchange rate.
## How this could be wrong
This is a hypothesis, and it says out loud what would kill it. The tests, in plain terms:
- **The replay test.** Rerun with model answers and tool results pinned. Any leftover variation — timestamps, wall-clocks, and cache expiries are the classic leaks — falsifies "the harness adds no randomness" until accounted for.
- **The drop-a-variable test.** Remove something from memory; if behavior statistics shift, the memory wasn't complete. The crash-resume version of the same test: if resuming from saved state breaks, the saved state wasn't the state.
- **Does the meter mean anything?** If no reasonable progress meter's drift predicts real failures — across the natural families, not just one bad candidate — the whole "measure what you can't prove" program is empty.
- **The red-team test.** Swap sampled tool outputs for worst-case ones: injected pages, poisoned metadata, malformed replies. The design must survive the worst permitted world, not the average one.
- **Gates versus begging.** The theory predicts deterministic gating beats prompt-level pleading. If "please be careful" alone matches real gates on security outcomes, the controller-versus-model story is wrong.
- **The compression hunt.** Exhibit a compact, provably sound progress certificate for a frontier-scale model on a nontrivial task family, and the central conjecture falls — constructively.
- **The desk probe.** Take a task family with a *proven* memory floor — so "it needed the whole picture at once" is someone else's theorem, not our excuse — scale it past the window, and watch: the wall predicts a *ceiling*, not a cliff — past the boundary, a success rate that stays capped no matter how many retries you buy. A family solved reliably out there, without new shell tricks for splitting the work, kills the wall.
## Who else landed here
The formal document keeps three honesty tiers. **Borrowed**: real theorems, cited — the drift and stopping-time mathematics is classical, and the very architecture of a deterministic supervisor gating a plant it didn't author is 1987 control theory; the shape is older than the web. **Ours**: the modeling choices and the conjectures — the walls, the incompressibility claim, the design rules — organizing principles, not results. **Corroborated**: pieces of the same object reached independently by people who never saw this framing — capability-security work isolating control flow from untrusted data (CaMeL), reinforcement-learning "shields" filtering a learned policy's actions through a deterministic checker, verification work that states the "learned safeguards can't certify" gap as its opening motivation, and architecture patterns converging on plan-then-execute. Even the field's live disagreement — provable-but-rigid deterministic layers versus flexible-but-uncertifiable learned checks — is, in this frame, not a fight but a placement: you need both, on their proper sides of the irreversibility line, with the learned one permitted only to tighten.
## What to remember
The model proposes; the gate disposes. No is the default, and a refusal must be safe. Only the top of the trust hierarchy widens permissions — a human decision, never the model, a tool result, a summary, or a judge. "Didn't confirm" is not "didn't happen." The desk is finite and the proof doesn't compress, so you measure — and you say *measurement* when you mean measurement. A robot that never stops leaks safety slowly, so it needs scheduled resets — and when it can't reach you, it must be able to stop. A loop that runs robots for you is just a bigger robot with the same rules and a further-away owner. And all of it is a hypothesis wearing its own kill-conditions on its sleeve.
The formal version — the objects, the certificates, the falsifiers, the citations — is [HYPOTHESIS.md](HYPOTHESIS.md). It wins every disagreement with this file, including this sentence.
*Same ramblings, fewer symbols.*
+81 -66
View File
@@ -1,92 +1,107 @@
# Bootstrap Wizard
# Quickstart
Interactive, AI-guided setup for Turnstone deployments. Instead of manually
editing `.env` files and reading deployment docs, the wizard walks you through
every decision conversationally and generates all the config files for you.
Install Turnstone, then diagnose it with `turnstone-doctor` if anything looks off.
## Quick Start
## Install
The one-line installer autodetects your distro (Ubuntu/Debian, Fedora/RHEL,
Arch, and WSL), installs git + Docker if missing, generates secrets, picks free
ports, and starts the stack:
```bash
turnstone-bootstrap
curl -fsSL https://raw.githubusercontent.com/turnstonelabs/turnstone/main/run.sh | bash
```
That's it — no flags, no arguments. The wizard prompts for everything.
Re-running is safe — it updates the checkout and keeps your existing `.env`.
When it finishes it prints the dashboard URL and how to create the first admin
user.
## How It Works
**Other ways to install**
1. **Pick a model** — Choose OpenAI, Anthropic, or a local/vLLM endpoint to
power the wizard. Local endpoints auto-detect available models.
2. **Answer questions** — The AI walks you through deployment mode, LLM
provider, database, authentication, ports, and optional features.
3. **Review generated files** — Each file is previewed before writing. You
confirm or reject every write.
4. **Start the stack** — The wizard prints the exact `docker compose` command
and a `setup.sh` script to create your first admin user, roles, and policies.
- **Already have Docker?** Clone the repo and `docker compose up` for the full
local cluster, or `docker compose -f turnstone/deploy/compose.yaml up` for the
released single-node stack. See [docs/docker.md](docs/docker.md).
- **Python package:** `pip install turnstone` (add `--pre` for the experimental
track), then run `turnstone-server` / `turnstone-console` directly. See the
[README](README.md#quickstart).
## What Gets Generated
## Diagnose: `turnstone-doctor`
| File | Purpose |
`turnstone-doctor` is an LLM-backed assistant that inspects a **running**
Turnstone install and helps you troubleshoot it. It is **read-only** — it
investigates and tells you the exact commands to fix things, but never changes
your system. (Installation is the installer's job, not the doctor's.)
```bash
# From a host that has the turnstone package installed:
turnstone-doctor
# For a Docker install from run.sh (no package on the host), run it with pipx:
pipx run --spec turnstone turnstone-doctor --dir ~/turnstone
```
### What it does
1. **Preflight** — detects how Turnstone is installed here (docker-compose,
systemd/bare-metal, pip, or a source checkout) by probing for `config.toml`
files, `TURNSTONE_*` environment variables, compose files, and systemd units.
2. **Self-configures its LLM** — it powers its own brain from your cluster's
*own* model configuration (env / `config.toml` / the database). Whether that
works is the first diagnostic: success means your LLM backend is healthy; if
it can't, that's surfaced as finding #1 and it falls back to asking you for a
provider and key so it can still help.
3. **Version check** — reports the installed version, version drift across your
cluster's nodes, and the latest upstream stable/experimental releases.
4. **Interactive diagnosis** — it reads logs, `/health`, `docker compose ps`,
`systemctl`, config, and ports to pin down problems like a node not joining
the console, an unreachable database, a down model backend, port conflicts,
or a JWT-secret mismatch — then hands you the precise remediation commands.
### Flags
| Flag | Purpose |
|------|---------|
| `.env` | All environment variables for `compose.yaml` |
| `setup.sh` | Post-start script: creates admin user, roles, tool policies, prompt templates via the API |
| `docker-compose.override.yaml` | Only if customizations beyond env vars are needed |
| `--dir PATH` | Install directory to inspect (default: current directory) |
| `--report` | Print the deterministic preflight report and exit — no LLM key needed |
| `--offline` | Skip the upstream GitHub version check |
## Requirements
`--report` is the fastest way to get a health snapshot (and to share one when
asking for help) — it never needs an API key:
- **Python 3.11+** with turnstone installed (`pip install turnstone`)
- **An LLM API key** — for the wizard itself (OpenAI, Anthropic, or a local
model). This can differ from the LLM your deployment will use.
- **Docker & Docker Compose** — needed to run the stack. The wizard detects
whether Docker is installed and gives platform-specific install instructions
if it's missing. You can still generate config files without Docker.
## Deployment Modes
- **Single-node production**`docker compose up` against the bundled
`turnstone/deploy/compose.yaml`: 1 server + console + channel + PostgreSQL,
pulled from ghcr.io. Good for most deployments.
- **Local multi-node cluster** — clone the repo and run `docker compose up` at
the root for a 10-node fleet + console + Caddy + channel, built locally.
See [docs/docker.md](docs/docker.md) for both.
## Example Session
```bash
turnstone-doctor --report --dir ~/turnstone
```
```
$ turnstone-bootstrap
## Install profile
- Detected kind(s): docker-compose (primary: docker-compose)
- Docker daemon reachable: yes
- Compose files:
/home/you/turnstone/compose.yaml
- Database: backend=postgresql, url=postgresql+psycopg://turnstone:****@postgres:5432/turnstone
- Candidate health URLs: http://localhost:8080/health, http://localhost:8090/health
Turnstone Bootstrap Wizard v1.5.0
────────────────────────────────────────────────
## Versions
- Installed (this tool): 1.7.0a2
- Cluster nodes: 10 reporting; versions ['1.7.0a2']
- Version drift across nodes: no
- Upstream: stable 1.6.9, experimental 1.7.0a2
Which provider for this wizard?
[1] OpenAI
[2] Anthropic
[3] OpenAI-compatible (local/vLLM)
> 3
Base URL [http://localhost:8000/v1]:
API key (press Enter for 'none'):
Querying http://localhost:8000/v1 for available models...
Found model: Qwen/Qwen3-32B
Connected to Qwen/Qwen3-32B. Handing off to AI assistant...
> (AI walks you through the rest interactively)
## LLM backend (ok)
- resolved Qwen/Qwen3-32B via openai-compatible @ http://host.docker.internal:8000/v1
```
Secrets (JWT secret, database password, API keys) are always redacted in the
report and in anything the doctor reads.
## Tips
- **Re-run safely** — running the wizard again detects your existing `.env`
and offers to update it rather than overwriting.
- **Duplicate writes are skipped** — if the LLM tries to write the same file
twice with identical content, it's silently ignored.
- **Type `quit` to exit** at any time during the conversation.
- **Ctrl+C** is handled gracefully — press once to interrupt, twice to exit.
- **Type `quit`** to exit the conversation; **Ctrl+C** interrupts (twice to quit).
- **Point it at the right install** with `--dir` when you run it from elsewhere.
- **(Re)installing or adding nodes?** Use the installer (`run.sh`), not the doctor.
## See Also
- [Docker Deployment](docs/docker.md) — manual compose setup and profiles
- [Docker Deployment](docs/docker.md) — compose stacks, ports, and bare-metal nodes
- [Security](docs/security.md) — auth architecture and token types
- [Governance](docs/governance.md) — roles, policies, and templates
+22 -4
View File
@@ -5,6 +5,7 @@
[![Python](https://img.shields.io/pypi/pyversions/turnstone)](https://pypi.org/project/turnstone/)
[![License](https://img.shields.io/badge/license-Apache--2.0-blue)](LICENSE)
[![Discord](https://img.shields.io/badge/Discord-join%20us-5865F2?logo=discord&logoColor=white)](https://discord.gg/Nh3bWMacaq)
[![Sponsor](https://img.shields.io/badge/Sponsor-%E2%9D%A4-db61a2?logo=githubsponsors&logoColor=white)](https://github.com/sponsors/eous)
Self-hosted, local-first orchestration for tool-using AI agents. Give LLMs real tools — shell, files, search, web — and run them across your own cluster with direct HTTP routing and interactive interfaces. Your code, your models, your data stay on hardware you control: no telemetry, no phone-home.
@@ -14,6 +15,14 @@ Self-hosted, local-first orchestration for tool-using AI agents. Give LLMs real
Named after the [Ruddy Turnstone](https://en.wikipedia.org/wiki/Ruddy_turnstone) (*Arenaria interpres*) — a shorebird that flips stones to discover what's hiding underneath.
**What is a harness?**
```
: s_{n+1} ~ T(s_n) for n < τ*, T = ρ ∘ (M_W ∘ π, E)
```
[**the primer →**](PRIMER.md)
### Release Tracks
| Track | Install | Docker | Description |
@@ -27,7 +36,7 @@ See [docs/releasing.md](docs/releasing.md) for the full release process.
Turnstone gives LLMs tools — shell, files, search, web, planning — and orchestrates multi-turn conversations where the model investigates, acts, and reports.
- **Local-first & private** — runs entirely on hardware you control, with no telemetry and no phone-home. Point it at local models (vLLM, llama.cpp, Ollama) or commercial APIs you hold the keys to — your prompts and data never transit a third party you didn't choose.
- **Local-first & private** — runs entirely on hardware you control, with no telemetry and no phone-home. Point it at local models (vLLM, llama.cpp) or commercial APIs you hold the keys to — your prompts and data never transit a third party you didn't choose.
- **Bring your own models** — OpenAI-compatible APIs (vLLM, llama.cpp, NIM), the Anthropic Messages API, and Google Gemini, mixed freely per role
- **Interactive sessions** — terminal CLI or browser UI with parallel workstreams
- **Cluster dashboard** — real-time view of every node and workstream, with a rendezvous routing proxy
@@ -86,7 +95,7 @@ LLM; add model backends from the console UI.
For production (released images from ghcr.io, real secrets required), use the
bundled stack: `docker compose -f turnstone/deploy/compose.yaml up`.
See [QUICKSTART.md](QUICKSTART.md) for the bootstrap wizard and [docs/docker.md](docs/docker.md) for Docker configuration.
See [QUICKSTART.md](QUICKSTART.md) for the install + troubleshooting walkthrough and [docs/docker.md](docs/docker.md) for Docker configuration.
### Programmatic (SDK)
@@ -116,8 +125,9 @@ Built-in tools for shell, files, search, web, memory, notifications, and autonom
| `turnstone-console` | Cluster dashboard + routing proxy + admin panel |
| `turnstone-channel` | Channel gateway (Discord and Slack adapters) |
| `turnstone-admin` | User/token management CLI |
| `turnstone-eval` | Eval harness for prompt/tool optimization |
| `turnstone-bootstrap` | LLM-guided setup wizard |
| `turnstone-eval` | Headless measurement — scores tool-use against expected actions |
| `turnstone-optimizer` | Prompt/tool optimizer (UCB self-modify loop over the eval substrate) |
| `turnstone-doctor` | LLM-backed cluster diagnostics |
### Diagrams
@@ -162,6 +172,14 @@ UML diagrams in [`docs/diagrams/`](docs/diagrams/):
- Optional: Discord / Slack channel integrations (`pip install turnstone[discord,slack]`)
- [Git LFS](https://git-lfs.com/) for cloning (diagram PNGs)
## Support
Turnstone is free, Apache-2.0, and self-hosted — no paid tier, no telemetry, no upsell. If it saves you time or you'd like to help keep development moving, you can sponsor the project:
**[❤ Sponsor Turnstone →](https://github.com/sponsors/eous)** · one-off via **[PayPal](https://paypal.me/eousphoros)**
Sponsorship is entirely optional and funds maintenance, new features, and infrastructure. Prefer to contribute in other ways? Filing issues, improving docs, and [pull requests](CONTRIBUTING.md) help just as much.
## Community
Questions, ideas, or want to show what you're building? Join us on Discord:
+44 -16
View File
@@ -29,10 +29,11 @@
# Fewer nodes (lighter machines):
# docker compose up postgres console caddy channel node-1 node-2 node-3
#
# Join a bare-metal host: Postgres is published on 127.0.0.1:5432, so a
# turnstone-server running directly on this machine (e.g. to use a local GPU)
# can join the same cluster. Keep the secret + connection settings in
# ~/.config/turnstone/config.toml (chmod 0600 — the loader warns otherwise):
# Join a bare-metal host: a turnstone-server running OUTSIDE compose (e.g. to use
# a local GPU) can join this cluster. Postgres, the console's ACME endpoint, and
# SearxNG are published on 127.0.0.1 so a node on THIS machine reaches them via
# localhost. Keep secrets in ~/.config/turnstone/config.toml (chmod 0600 — the
# loader warns otherwise):
# [auth]
# jwt_secret = "dev-only-insecure-jwt-secret-change-me-for-real-deployments"
# [database]
@@ -41,10 +42,19 @@
# [api]
# base_url = "http://localhost:8000/v1"
# api_key = "dummy"
# [tls] # only if the cluster runs mTLS
# enabled = true
# then run (node identity isn't a secret, so it stays on the command line):
# TURNSTONE_NODE_ID=host-1 TURNSTONE_ADVERTISE_URL=http://host.docker.internal:8080 \
# TURNSTONE_NODE_ID=host-1 \
# TURNSTONE_ADVERTISE_URL=http://host.docker.internal:8080 \
# TURNSTONE_CONSOLE_URL=http://localhost:8090 \
# TURNSTONE_SEARXNG_URL=http://localhost:8081 \
# turnstone-server --host 0.0.0.0 --port 8080
# It registers in Postgres and the console reaches it back via host.docker.internal.
# The node registers in Postgres, auto-enrolls its mTLS cert from the console's
# ACME endpoint (when the cluster runs mTLS), and the console collector reaches
# it back via host.docker.internal. To join from ANOTHER machine, set
# TURNSTONE_HOST_IP to this host's LAN IP and use it in the URLs above (and the
# node's TURNSTONE_ADVERTISE_URL = the NODE host's IP) — see docs/docker.md.
# =============================================================================
name: turnstone
@@ -93,13 +103,14 @@ services:
# INSECURE dev default — override POSTGRES_PASSWORD in .env for real use.
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-turnstone}
PGDATA: /var/lib/postgresql/data
# Published on localhost so a bare-metal turnstone-server running on THIS
# host can join the cluster (see "Join a bare-metal host" in the header).
# Bound to 127.0.0.1 by default; set POSTGRES_BIND=0.0.0.0 to let another
# machine connect — but set a real POSTGRES_PASSWORD first, or you'll expose
# a database with the insecure default password to your network.
# Published so a bare-metal turnstone-server can join the cluster (see "Join
# a bare-metal host" in the header). Bound to 127.0.0.1 by default (same-host
# nodes only); set TURNSTONE_HOST_IP to this host's LAN IP to let another
# machine connect — but set a real POSTGRES_PASSWORD first, or you'll expose a
# database with the insecure default password to your network. (The legacy
# POSTGRES_BIND is still honored as a fallback when TURNSTONE_HOST_IP is unset.)
ports:
- "${POSTGRES_BIND:-127.0.0.1}:${POSTGRES_PORT:-5432}:5432"
- "${TURNSTONE_HOST_IP:-${POSTGRES_BIND:-127.0.0.1}}:${POSTGRES_PORT:-5432}:5432"
volumes:
- postgres-data:/var/lib/postgresql/data
networks:
@@ -120,10 +131,12 @@ services:
# turnstone-console — cluster dashboard. Reach it ONLY through Caddy at
# https://localhost:8443 (see the caddy service below).
#
# The console port (8090) is deliberately NOT published to the host: a plain
# HTTP/1.1 origin caps the browser at 6 connections, which starves the
# dashboard's per-pane SSE streams. Caddy serves the browser over HTTP/2
# (multiplexed) and proxies to console:8090 internally, so the cap is gone.
# Browsers must reach the dashboard through Caddy (https://localhost:8443): a
# plain HTTP/1.1 origin caps the browser at 6 connections, which starves the
# dashboard's per-pane SSE streams, whereas Caddy serves HTTP/2 (multiplexed)
# and proxies to console:8090 internally. The console's :8090 is published
# below ONLY so bare-metal nodes can reach the plain-HTTP ACME enrollment
# endpoint — don't point a browser at it.
#
# The single `build:` here produces the turnstone:local image every other
# service reuses. extra_hosts lets the console reach a bare-metal server
@@ -138,6 +151,14 @@ services:
- turnstone-console
- --host=0.0.0.0
- --port=8090
# Publishes the console's plain-HTTP listener so a bare-metal node can reach
# the ACME endpoint, fetch the CA, and enroll its cert (the console serves
# HTTP here even under mTLS). Bound to 127.0.0.1 by default; setting
# TURNSTONE_HOST_IP exposes the WHOLE console HTTP API — including the
# cert-issuing ACME endpoint — on that interface, so the JWT secret's
# strength is the only gate. Browsers use Caddy :8443, never this port.
ports:
- "${TURNSTONE_HOST_IP:-127.0.0.1}:8090:8090"
environment:
TURNSTONE_JWT_SECRET: *jwt-secret
TURNSTONE_DB_BACKEND: *db-backend
@@ -219,6 +240,13 @@ services:
# -------------------------------------------------------------------
searxng:
image: searxng/searxng:${SEARXNG_IMAGE_TAG:-latest}
# Published so a bare-metal node's web_search can reach it. SearxNG has NO
# auth, so it is bound to 127.0.0.1 by default; setting TURNSTONE_HOST_IP
# exposes it on that interface — an open search proxy on your LAN, which also
# triggers the SearxNG AGPL-3.0 §13 source-offer obligation (see docs/docker.md).
# In-compose nodes always use the internal http://searxng:8080 and ignore this.
ports:
- "${TURNSTONE_HOST_IP:-127.0.0.1}:${SEARXNG_API_PORT:-8081}:8080"
volumes:
- ./turnstone/deploy/searxng:/etc/searxng:ro
- searxng-cache:/var/cache/searxng # favicon + internal SQLite cache (survives restarts)
+1 -1
View File
@@ -7,6 +7,6 @@ appVersion: "0.3.0"
dependencies:
- name: postgresql
version: ~18.7.0
version: ~18.8.0
repository: https://charts.bitnami.com/bitnami
condition: postgresql.enabled
+72
View File
@@ -0,0 +1,72 @@
# Running a bare-metal turnstone-server under systemd
These units run a `turnstone-server` **outside** Docker (e.g. on a box with a
local GPU) so it joins an existing cluster — typically the docker-compose stack
in [`compose.yaml`](../../compose.yaml). They are the hardened, production-shaped
counterpart to the quick `turnstone-server …` invocation in
[`docs/docker.md`](../../docs/docker.md) ("Join a bare-metal host").
| File | Purpose |
|------|---------|
| `turnstone-server.service` | The hardened server unit (sandboxed; secrets via `config.toml`). |
| `turnstone.slice` | Shared memory/process budget for colocated Turnstone units. |
| `turnstone-server.service.d/node.conf.example` | Per-host identity + cluster URLs drop-in (no secrets). |
## Cluster-side prerequisite
The compose stack must publish Postgres, the console's ACME endpoint, and SearxNG
on an address the bare-metal host can reach. Start it with `TURNSTONE_HOST_IP`
set to the compose host's LAN IP (default `127.0.0.1` keeps everything host-local):
```bash
TURNSTONE_HOST_IP=<compose-host-ip> docker compose up -d
```
## Install (run as root on the bare-metal host)
```bash
# 1. A dedicated, unprivileged user.
useradd --system --no-create-home --shell /usr/sbin/nologin turnstone
# 2. Install turnstone into a venv at /opt/turnstone-venv (lacme/mTLS is a core dep).
uv venv /opt/turnstone-venv --python 3.12
uv pip install --python /opt/turnstone-venv 'turnstone @ git+https://github.com/turnstonelabs/turnstone'
# …or from a local checkout: uv pip install --python /opt/turnstone-venv /path/to/turnstone
# 3. Secrets — match the cluster's JWT secret + DB credentials (kept out of env).
install -d -m 750 -o turnstone -g turnstone /etc/turnstone
cat > /etc/turnstone/config.toml <<'TOML'
[auth]
jwt_secret = "<same secret as the cluster>"
[database]
backend = "postgresql"
url = "postgresql+psycopg://turnstone:<password>@<compose-host-ip>:5432/turnstone"
[api]
base_url = "http://localhost:8000/v1" # a real model backend is configured in the console UI
api_key = "dummy"
TOML
chown turnstone:turnstone /etc/turnstone/config.toml
chmod 600 /etc/turnstone/config.toml
# 4. Units + per-host drop-in.
cp turnstone-server.service turnstone.slice /etc/systemd/system/
install -d /etc/systemd/system/turnstone-server.service.d
cp turnstone-server.service.d/node.conf.example \
/etc/systemd/system/turnstone-server.service.d/node.conf
$EDITOR /etc/systemd/system/turnstone-server.service.d/node.conf # set the addresses
# 5. Go.
systemctl daemon-reload
systemctl enable --now turnstone-server.service
journalctl -u turnstone-server -f # watch it register + (if the cluster runs mTLS) enroll
```
`tls.enabled` is **not** set here — a joining node inherits it from the cluster's
shared settings (the database). If the cluster runs mTLS, the node auto-enrolls a
cert from the console's ACME endpoint and re-advertises itself over `https://`.
> **mTLS + cross-host caveat:** a node on a *different* host than the console
> currently can't complete ACME enrollment — the console advertises an
> unroutable in-container address in its ACME directory
> ([turnstonelabs/lacme#22](https://github.com/turnstonelabs/lacme/issues/22)).
> Same-host bare-metal nodes, and any node in a non-mTLS cluster, are unaffected.
+85
View File
@@ -0,0 +1,85 @@
# Run a bare-metal turnstone-server as a systemd service so it joins a cluster
# (e.g. the docker-compose stack) from outside Docker — typically to use a local
# GPU. Install steps + the cluster-side prerequisites are in deploy/systemd/README.md
# and docs/docker.md ("Join a bare-metal host"). Per-host identity + the cluster
# URLs go in a drop-in (see node.conf.example); secrets go in config.toml.
[Unit]
Description=Turnstone server (chat workstreams + LLM gateway)
Documentation=https://github.com/turnstonelabs/turnstone
# Postgres is required. After= orders against a colocated postgresql.service
# when present and silently no-ops otherwise (the cluster DB is usually remote).
After=network.target postgresql.service
StartLimitIntervalSec=60
StartLimitBurst=5
[Service]
Type=exec
User=turnstone
Group=turnstone
# Secrets live in config.toml — JWT secret, Postgres URL+password, LLM API key —
# kept out of os.environ so a prompt-injected tool can't dump them via `env`.
Environment=TURNSTONE_CONFIG=/etc/turnstone/config.toml
Environment=TURNSTONE_LOG_LEVEL=info
Slice=turnstone.slice
# Per-host node identity + cluster wiring (TURNSTONE_NODE_ID / _ADVERTISE_URL /
# _CONSOLE_URL / _SEARXNG_URL) go in a drop-in, not here — see node.conf.example.
StateDirectory=turnstone
StateDirectoryMode=0750
LogsDirectory=turnstone
LogsDirectoryMode=0750
WorkingDirectory=/var/lib/turnstone
# --host 0.0.0.0 so the console collector + peer nodes can dial this node back
# at its advertised address. (A single-node, Caddy-fronted install can use
# 127.0.0.1 instead.) Rewrite --port if :8080 is already taken on the host.
ExecStart=/opt/turnstone-venv/bin/turnstone-server --host 0.0.0.0 --port 8080
Restart=on-failure
RestartSec=5s
TimeoutStartSec=120
TimeoutStopSec=30
KillSignal=SIGTERM
KillMode=mixed
# --- Resource limits ---
# SSE keeps an fd per active workstream + outbound LLM stream + MCP stdio pipe.
LimitNOFILE=65535
LimitNPROC=8192
TasksMax=8192
LimitCORE=0
# --- Hardening ---
NoNewPrivileges=true
CapabilityBoundingSet=
AmbientCapabilities=
UMask=0027
PrivateTmp=true
# PrivateDevices=true — disabled: GPU access via /sys/class/drm
ProtectSystem=strict
ProtectHome=true
ProtectKernelTunables=true
ProtectKernelModules=true
ProtectKernelLogs=true
ProtectControlGroups=true
ProtectClock=true
ProtectHostname=true
RestrictNamespaces=true
RestrictRealtime=true
RestrictSUIDSGID=true
RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
LockPersonality=true
MemoryDenyWriteExecute=true
SystemCallArchitectures=native
SystemCallFilter=@system-service
SystemCallFilter=~@privileged @mount
StandardOutput=journal
StandardError=journal
SyslogIdentifier=turnstone-server
[Install]
WantedBy=multi-user.target
@@ -0,0 +1,25 @@
# Per-host node identity + cluster wiring for a bare-metal turnstone-server.
# Copy to /etc/systemd/system/turnstone-server.service.d/node.conf and edit the
# addresses, then `systemctl daemon-reload`. Identity + URLs are NOT secrets, so
# they live here; the JWT secret + DB URL live in /etc/turnstone/config.toml.
#
# Addresses below use RFC 5737 documentation IPs — replace them:
# <this-host> = the bare-metal host's own LAN IP (what the console dials back)
# <compose-host> = the host running the cluster / docker-compose stack, started
# with TURNSTONE_HOST_IP=<compose-host> so :8090 and :8081 are
# published on its LAN interface (see docs/docker.md).
[Service]
# Unique node id (defaults to the hostname if unset).
Environment=TURNSTONE_NODE_ID=host-1
# The address peers + the console collector dial back. Auto-upgrades to https://
# once the node enrolls its mTLS cert.
Environment=TURNSTONE_ADVERTISE_URL=http://192.0.2.10:8080
# The cluster console's reachable plain-HTTP ACME/API endpoint. A bare-metal node
# can't resolve the in-cluster name (console:8090), so point it at the published
# port; turnstone-server honors this for cert enrollment.
Environment=TURNSTONE_CONSOLE_URL=http://192.0.2.1:8090
# The cluster's published SearxNG, for the web_search tool.
Environment=TURNSTONE_SEARXNG_URL=http://192.0.2.1:8081
+15
View File
@@ -0,0 +1,15 @@
# Shared resource budget for the colocated Turnstone units. Without a slice each
# unit's MemoryMax= is enforced independently — three units at 85% each can sum
# to 255% of host RAM before any throttles. Under a shared slice the cap is
# hierarchical: the slice ceiling is the real limit. (A bare-metal node that runs
# only turnstone-server still benefits — and keeps the unit's Slice= reference
# valid.) Adjust if the host runs other meaningful workloads alongside Turnstone.
[Unit]
Description=Turnstone services slice (server + console + channel)
Documentation=https://github.com/turnstonelabs/turnstone
Before=slices.target
[Slice]
MemoryHigh=70%
MemoryMax=85%
TasksMax=16384
+181 -33
View File
@@ -63,7 +63,10 @@ Auth is always enabled. All API endpoints except public paths require a valid to
Include a token in one of two ways:
- **Bearer header**: `Authorization: Bearer <token>`
- **Cookie**: `turnstone_auth=<token>` (set automatically by the login endpoint)
- **Cookie**: the surface-scoped auth cookie — `turnstone_auth_server` on
turnstone-server, `turnstone_auth_console` on turnstone-console (set
automatically by the login endpoint). The names differ so the two surfaces,
when co-hosted on one origin, don't overwrite each other's session.
The server accepts two token types:
@@ -102,7 +105,8 @@ Authenticate with credentials and receive a JWT. Accepts two credential formats:
}
```
The response also sets a `turnstone_auth` HttpOnly cookie containing the JWT.
The response also sets a surface-scoped HttpOnly cookie containing the JWT
(`turnstone_auth_server` on turnstone-server, `turnstone_auth_console` on turnstone-console).
**Response (failure):** `401`
@@ -114,7 +118,8 @@ The response also sets a `turnstone_auth` HttpOnly cookie containing the JWT.
### `POST /v1/api/auth/logout`
Clears the `turnstone_auth` cookie. No request body required.
Clears the surface-scoped auth cookie (`turnstone_auth_server` /
`turnstone_auth_console`). No request body required.
**Response:** `200`
@@ -199,7 +204,8 @@ this endpoint.
}
```
The response also sets a `turnstone_auth` HttpOnly cookie containing the JWT.
The response also sets a surface-scoped HttpOnly cookie containing the JWT
(`turnstone_auth_server` on turnstone-server, `turnstone_auth_console` on turnstone-console).
**Response (already set up):** `409`
@@ -452,7 +458,7 @@ Each item in `items` (shared by `tool_info` and `approve_request`):
| `context_window` | int | Total context window size in tokens |
| `pct` | float | Percentage of context window used |
| `effort` | string | Reasoning effort level (`low`/`medium`/`high`) |
| `cache_creation_tokens` | int | Tokens written to prompt cache (Anthropic) |
| `cache_creation_tokens` | int | Tokens written to prompt cache (Anthropic + OpenAI) |
| `cache_read_tokens` | int | Tokens served from prompt cache (Anthropic + OpenAI) |
**`info`** -- an informational message (e.g. command output).
@@ -461,6 +467,46 @@ Each item in `items` (shared by `tool_info` and `approve_request`):
{"type": "info", "message": "Session cleared."}
```
**`compaction`** -- context-compaction lifecycle (manual `/compact` and
auto-compaction). `phase: "start"` opens the operation (`trigger` is
`"manual"` or `"auto"`; auto adds `where` — e.g. `"mid-turn"` — and, when
the percentage threshold actually fired, `pct`; the context-overflow retry
path compacts without a `pct` since no threshold was evaluated).
`phase: "progress"` reports chunked summarization (`part`/`total`/`depth`,
where depth 0 summarizes transcript batches and deeper levels merge partial
summaries), a transient-error retry wait (`retry_in` seconds + `error`), or
`warning: "summary_truncated"`. `phase: "end"` settles it: `ok: true`
carries `before_tokens`/`after_tokens` and the produced `summary`;
`ok: false` carries a `reason`
(`"not_enough_messages"` / `"irreducible"` / `"empty_summary"` /
`"cancelled"` / `"error"`) and a human-readable `message` — for
`reason: "error"` the same message is also emitted as a paired typed
`error` event (that is the renderable error surface; the end event is
card-teardown). Failed ends also carry `notice`: the emitter-computed
display verdict — show `message` only when it is `true` (the server
suppresses error-reason, superseded, and cancelled-auto notices once,
centrally, so clients don't re-derive that policy). Every end (ok or
failed) carries `trigger`, and every event carries `compaction_id` — an
opaque integer correlating the start/progress/end of one compaction run (a
client that force-stopped one compaction can use it to ignore stragglers
from the abandoned run). End events also carry `superseded`: `true` marks
a force-abandoned compaction retiring after a successor generation took
over (an OK end's result card still stands: the history swap happened).
Superseded start/progress events are never emitted.
Exactly one `start` and one `end` are emitted per attempt,
so clients can key an in-progress affordance (progress bar) on the pair. A
successful end is also persisted: the summary replays from `/history` as a
`role: "system"`, `source: "compaction"` entry whose `meta` carries
`{watermark, before_tokens, after_tokens, trigger}` and whose `event_id`
matches the end event's id (dedup across repaint + replay).
```json
{"type": "compaction", "phase": "start", "compaction_id": 7, "trigger": "auto", "where": "mid-turn", "pct": 80}
{"type": "compaction", "phase": "progress", "compaction_id": 7, "part": 2, "total": 5, "depth": 0}
{"type": "compaction", "phase": "end", "ok": true, "compaction_id": 7, "trigger": "auto",
"before_tokens": 128400, "after_tokens": 9200, "summary": "## Decisions\n..."}
```
**`error`** -- an error message.
```json
@@ -692,6 +738,42 @@ Each skill summary:
---
### `GET /v1/api/personas`
Returns the enabled personas offered by the workstream-creation pickers.
Authenticated for any logged-in user and deliberately gated by **no**
`persona.*` permission — selecting a persona at creation is a user
action, while the `persona.*` perms gate authoring. Display fields only;
the levers (base prompt, tool set, MCP/memory toggles) stay server-side.
**Response:**
```json
{
"personas": [
{"name": "engineer", "display_name": "Engineer", "description": "The stock interactive workstream: full tools, MCP, and memory.", "applies_to_kinds": ["interactive"], "is_default": true},
{"name": "researcher", "display_name": "Researcher", "description": "Answers questions with evidence — reads and cites, loads tools to verify when needed.", "applies_to_kinds": ["interactive"], "is_default": false}
],
"total": 2
}
```
Each persona summary:
| Field | Type | Description |
|--------------------|--------|------------------------------------------------------------------|
| `name` | string | Persona slug (used in the `persona` field on workstream creation) |
| `display_name` | string | Human-readable label for pickers |
| `description` | string | Short description of the persona's intent |
| `applies_to_kinds` | array | Workstream kinds the persona applies to (`interactive` / `coordinator`) |
| `is_default` | bool | Whether this is the default persona for its kind |
> **Note:** For full persona management (create, edit, archive), use the
> admin endpoints at `/v1/api/admin/personas` (requires the
> `persona.{create,read,write}` permissions).
---
### `POST /v1/api/workstreams/{ws_id}/send`
Sends a user message to a workstream. Spawns a daemon worker thread that calls
@@ -706,32 +788,41 @@ Sends a user message to a workstream. Spawns a daemon worker thread that calls
**Request body:**
```json
{"message": "Explain how the server works"}
{"message": "Explain how the server works", "attachment_ids": ["a1"]}
```
| Field | Type | Required | Description |
|-----------|--------|----------|-------------------------|
| `message` | string | yes | The user's message text |
| Field | Type | Required | Description |
|------------------|------------|----------|------------------------------------------------------|
| `message` | string | yes | The user's message text |
| `attachment_ids` | string[] | no | Staged uploads to attach (omit = auto-consume; `[]` = none) |
**Response (success):**
**Response.** Every 200 body carries `attached_ids` and
`dropped_attachment_ids` (empty lists when no attachments are involved):
```json
{"status": "ok"}
```
**Response (busy):** Returned if the workstream's worker thread is still alive
from a previous request. Also pushes a `busy_error` event to the SSE stream.
```json
{"status": "busy"}
```
- `{"status": "ok", ...}` — a fresh turn was dispatched.
- `{"status": "queued", "priority", "msg_id", ...}` — folded into the live
turn's interjection queue; delivered at the next tool-result seam.
`DELETE .../send` with the `msg_id` retracts it before delivery.
- `{"status": "queued", "deferred": true, ...}` — parked on the deferred-send
list (a command window holds the slot, or earlier deferred sends are
pending) and dispatched as its own full-fidelity send afterwards; see the
defer contract under `POST /v1/api/command`.
- `{"status": "queue_full", ...}` — the send was refused with retry-shortly
semantics: the live worker's interjection queue is at capacity, the
deferred-send list hit its saturation bound (10 pending — the same
backpressure contract), or the deferred-send drain could not be started
under resource exhaustion (the message was **not** accepted; nothing is
parked).
- `{"status": "attachments_busy", ...}` — attachments can't ride a queued
turn; the staged uploads survive for a retry once the worker idles.
**Error responses:**
| Status | Body | Condition |
|--------|------------------------------------|------------------------|
| 400 | `{"error": "Empty message"}` | Message is empty |
| 404 | `{"error": "Unknown workstream"}` | `ws_id` not found |
| Status | Body | Condition |
|--------|-------------------------------------------------|----------------------------------------|
| 400 | `{"error": "message is required"}` | Message is empty |
| 404 | `{"error": "Unknown workstream"}` | `ws_id` not found (or closed mid-send) |
| 409 | `{"status": "cross_user_interjection", ...}` | Another participant's turn is in flight |
---
@@ -774,7 +865,56 @@ automatically approved without prompting.
### `POST /v1/api/command`
Executes a slash command in the given workstream.
Executes a slash command in the given workstream. Commands run on the
workstream's worker slot (mutual exclusion against sends, a running
compaction, and each other) — the endpoint is **not** unconditionally
synchronous:
- **Quick commands** (everything except `/compact`): the endpoint waits for
completion, so `{"status": "ok"}` means the command ran. A command still
running after 25 s answers `{"status": "running"}` — the worker keeps
going, its output reaches the pane via SSE, and the post-command pane
refreshes below still fire when it completes. (The bound sits under
common 30 s client/proxy timeouts — the console proxy's included — so
the degraded answer actually reaches bounded callers.)
- **`/compact`**: dispatched fire-and-forget — `{"status": "ok"}` means the
compaction *started*. A large context can legitimately compact for many
minutes; progress streams as `compaction` SSE events (see the event
reference) and the persisted marker row lands on completion. Do not read
`/history` expecting the compacted transcript immediately after the
response.
- **Busy refusal**: if a turn or another command holds the worker slot, the
command is refused with HTTP **409** `{"status": "busy", "error": ...}` and
did **not** run. Retry after the current turn finishes. (The old inline
endpoint executed commands unconditionally mid-turn; the 409 makes the
refusal loud for callers that only check the HTTP status.)
While a command holds the slot — and afterwards, while earlier deferred
sends are still waiting (the pending list is the order authority: a fresh
send never overtakes a message already acknowledged) — `POST .../send`
requests are **deferred**: the server answers `{"status": "queued",
"deferred": true, "msg_id": ...}` immediately and dispatches the message
as an ordinary full-fidelity send (attachments and sender identity
included) in arrival order once the slot frees — it is never routed
through the mid-turn interjection queue (no length cap, no cross-user
rejection). The response arrives within normal round-trip time, so
timeout-bounded clients (SDKs, proxies, the coordinator) need no special
handling. To retract a deferred send before it dispatches, issue the same
`DELETE .../send` with its `msg_id` used for queued interjections —
`{"status": "removed"}` confirms it will not dispatch; `"not_found"` means
it already dispatched (or is dispatching). Retracting a deferred send
discards any attachments it carried; re-attach to send them again. When a
deferred send dispatches, panes receive a `message_dispatched` event
(`msg_id`, plus `folded: true` when it folded into a live turn's
interjection queue rather than spawning its own turn) so queued-message
UI can settle the right way.
Durability: deferred sends are **node-local and in-memory** (the same
lifetime as the interjection queue). `"queued"` is at-most-once intake, not
durable acceptance — if the workstream is closed or the node restarts before
the window ends, the message is dropped. Anything that must survive a
restart should be re-sent after confirming dispatch (the turn appears on the
SSE stream / in `/history`).
**Request body:**
@@ -787,10 +927,12 @@ Executes a slash command in the given workstream.
| `command` | string | yes | The slash command (e.g. `/clear`) |
| `ws_id` | string | yes | Target workstream ID |
If the command is `/clear` or `/new`, the server pushes a `clear_ui` SSE event
to instruct the client to reset its message display. If the command is
`/resume`, the server pushes `clear_ui` followed by a `history` event
containing the resumed session's messages.
If the command is `/clear`, `/new`, or `/resume`, the server pushes a
`clear_ui` SSE event to instruct the client to reset its message display and
re-fetch the transcript via `GET .../history` (there is no SSE event that
carries the messages themselves). These follow-ups are emitted by the
command worker itself, so they fire even when the endpoint already answered
`{"status": "running"}`.
**Response:**
@@ -798,12 +940,16 @@ containing the resumed session's messages.
{"status": "ok"}
```
or `{"status": "running"}` as above.
**Error responses:**
| Status | Body | Condition |
|--------|------------------------------------|----------------------|
| 400 | `{"error": "Empty command"}` | Command is empty |
| 404 | `{"error": "Unknown workstream"}` | `ws_id` not found |
| Status | Body | Condition |
|--------|-------------------------------------|--------------------------------------------------|
| 400 | `{"error": "Empty command"}` | Command is empty |
| 404 | `{"error": "Unknown workstream"}` | `ws_id` not found |
| 409 | `{"status": "busy", "error": ...}` | A turn/command holds the worker |
| 503 | `{"status": "error", "error": ...}` | The command worker could not be started (resource exhaustion) — the command did **not** run; retry shortly |
---
@@ -889,6 +1035,7 @@ All fields are optional. The body can be empty or an empty JSON object.
| `auto_approve` | bool | false | Auto-approve all tool calls for this workstream |
| `resume_ws` | string | "" | Workstream ID to resume atomically during creation (empty = fresh)|
| `skill` | string | "" | Skill name. Applies content (system prompt), model, temperature, reasoning effort, max tokens, auto-approve policy, token budget, and other session config from the skill. Returns 400 if not found or disabled. Ignored when `resume_ws` is set (resumed sessions restore their own skill). |
| `persona` | string | "" | Persona slug. Resolved and snapshotted into the workstream at creation; empty selects the kind's default. |
| `judge_model` | string | "" | Optional model alias for the judge (overrides default judge model for this workstream) |
> **Skill behavior:** When `skill` is specified, the skill's content is injected as a system message and its session config fields (model, temperature, auto-approve, token budget, etc.) override system defaults for the new workstream.
@@ -905,6 +1052,7 @@ All fields are optional. The body can be empty or an empty JSON object.
| `name` | string | Auto-generated workstream name |
| `resumed` | bool | Whether a previous session was successfully resumed |
| `message_count` | int | Number of messages in the resumed session (0 if fresh) |
| `initial_message_status` | string | Present ONLY when the workstream was created but its `initial_message` could not be delivered: `"queue_full"` (a raced live worker's interjection queue was at capacity — resend via `/send`; any uploads stay staged) or `"refused_closed"` (the workstream was closed mid-create). Absent whenever the message was dispatched. |
**Error (limit reached):**
+202 -33
View File
@@ -19,10 +19,11 @@ plugs in.
| `turnstone` | `turnstone.cli` | `TerminalUI` | Interactive terminal REPL |
| `turnstone-server` | `turnstone.server` | `WebUI` | Browser-based chat (HTTP + SSE) |
| `turnstone-console` | `turnstone.console.server` | ClusterCollector | Cluster dashboard (aggregates all nodes) |
| `turnstone-eval` | `turnstone.eval` | `NullUI` | Headless evaluation and prompt optimization |
| `turnstone-eval` | `turnstone.eval.cli` | `NullUI` | Headless measurement (scores tool-use against expected actions) |
| `turnstone-optimizer` | `turnstone.optimizer` | `NullUI` | Prompt/tool optimization (UCB self-modify loop over the eval substrate) |
| `turnstone-channel` | `turnstone.channels.cli` | ChannelAdapter | Channel gateway (Discord, Slack, etc.) |
| `turnstone-admin` | `turnstone.admin` | — | Offline user and API token management |
| `turnstone-bootstrap` | `turnstone.bootstrap` | — | LLM-guided setup wizard |
| `turnstone-doctor` | `turnstone.doctor` | — | LLM-backed cluster diagnostics |
---
@@ -90,7 +91,7 @@ turnstone/
discord/ Discord adapter (bot, cog, views, streaming, config)
slack/ Slack adapter (Socket Mode bot, DM routing, approval buttons)
shared_static/ Shared design system (base.css, auth.js, theme.js, toast.js, utils.js, kb.js)
katex-0.17.0/ Vendored KaTeX math rendering library (MIT, woff2 fonts)
katex-0.18.1/ Vendored KaTeX math rendering library (MIT, woff2 fonts)
ui/
colors.py ANSI color constants with NO_COLOR support
markdown.py Streaming terminal markdown renderer (line-buffered)
@@ -267,7 +268,7 @@ the per-workstream events stream in
|-------|--------|-------|
| `TerminalUI` | `turnstone.cli` | ANSI colors, `MarkdownRenderer`, `Spinner`, readline-based `input()` for approval |
| `WebUI` | `turnstone.server` | SSE event queue per workstream + global broadcast, `threading.Event` for blocking on approval. `on_state_change` sends to both per-workstream and global SSE (the browser UI uses per-workstream `state_change` events to manage busy/idle transitions; `stream_end` only finalizes markdown rendering). |
| `NullUI` | `turnstone.eval` | Discards all output; `approve_tools` always returns `(True, None)` |
| `NullUI` | `turnstone.eval.core` | Discards all output; `approve_tools` always returns `(True, None)` |
### WorkstreamTerminalUI
@@ -608,8 +609,7 @@ LLMProvider (protocol)
| Method | Purpose |
|--------|---------|
| `create_streaming()` | Streaming request, yields normalized `StreamChunk` objects |
| `create_completion()` | Non-streaming request, returns `CompletionResult` |
| `create_streaming()` | The one transport: streaming request, yields normalized `StreamChunk` objects (single-shot callers accumulate via `drain_stream()` into a `CompletionResult`) |
| `get_capabilities()` | Per-model flags (`ModelCapabilities`) |
| `convert_tools()` | Translate OpenAI tool schemas to provider format |
| `retryable_error_names` | Exception class names that trigger retry |
@@ -621,20 +621,30 @@ LLMProvider (protocol)
|------|--------|
| `StreamChunk` | `content_delta`, `reasoning_delta`, `tool_call_deltas`, `info_delta`, `usage`, `finish_reason`, `provider_blocks` |
| `CompletionResult` | `content`, `tool_calls`, `finish_reason`, `usage`, `provider_blocks` |
| `ModelCapabilities` | `context_window`, `max_output_tokens`, `supports_temperature`, `token_param`, `thinking_mode`, `supports_effort`, `supports_web_search`, `supports_tool_search`, `supports_vision`, `supports_reasoning_replay` |
| `ModelCapabilities` | `context_window`, `max_output_tokens`, `supports_temperature`, `token_param`, `thinking_mode`, `supports_effort`, `supports_web_search`, `supports_tool_search`, `supports_vision`, `supports_reasoning_replay`, `supports_verbosity`, `verbosity`, `supports_pro_mode`, `reasoning_mode` |
| `UsageInfo` | `prompt_tokens`, `completion_tokens`, `total_tokens`, `cache_creation_tokens`, `cache_read_tokens` |
**OpenAIProvider** (`_openai.py`): passes messages through unchanged (they are
already in OpenAI format), including multi-part content blocks (text + images)
in tool results. Model capability lookup table covers GPT-5/5.1/5.2/5.3/5.4,
in tool results. Model capability lookup covers GPT-5 through GPT-5.6,
O-series, and search models (`gpt-5-search-api`) — all with `supports_vision`.
For search models, injects `web_search_options` and removes the `web_search`
function tool (the model always searches). Citations from `url_citation`
annotations are formatted as footnotes. Extended prompt cache retention
(`prompt_cache_retention: "24h"`) is enabled for GPT-5.x models at no
additional cost. Cached token counts are extracted from
`usage.prompt_tokens_details.cached_tokens`. Unknown models (local servers) get
permissive defaults with `supports_vision=False` and use SearxNG for web search.
annotations are formatted as footnotes. Pre-5.6 GPT-5 models request extended
prompt-cache retention (`prompt_cache_retention: "24h"`); GPT-5.6 uses
`prompt_cache_options.ttl: "30m"`. Cache reads and writes are extracted from
`cached_tokens` and `cache_write_tokens`. Unknown models get permissive
defaults with `supports_vision=False` and use SearxNG for web search. The
`openai-compatible` lane never consults this table at all — on either API
surface (the responses pin is served by a compat-mode
`OpenAIResponsesProvider`, mirroring `AnthropicProvider(compat=True)`): a
local server serves whatever the operator named it (vLLM
`--served-model-name` is a free string), so a prefix collision with a cloud
model id must not inherit that model's sampling/effort contract — every
local model gets the plain defaults, commercial prompt-cache controls are not
injected by model-name prefix, and anything beyond those defaults is declared
on the model definition (capabilities JSON + `server_compat`), matching the
`anthropic-compatible` lane.
**AnthropicProvider** (`_anthropic.py`): converts OpenAI-format messages to
Anthropic content blocks, maps `system`/`developer` roles to the `system`
@@ -652,7 +662,7 @@ display). Automatic prompt caching is enabled via top-level `cache_control:
cacheable block and advances it as conversations grow (90% input cost
reduction on cache hits, 1.25x write on first turn). Cache metrics
(`cache_creation_input_tokens`, `cache_read_input_tokens`) are extracted from
both streaming and non-streaming responses. The `anthropic` SDK is a core
the stream's usage events. The `anthropic` SDK is a core
dependency — the Anthropic provider is first-class alongside OpenAI.
**GoogleProvider** (`_google.py`): extends `OpenAIChatCompletionsProvider` for
@@ -702,7 +712,7 @@ agent_model = "claude"
Each `[models.*]` entry produces a `ModelConfig` with a `provider` field
(default: `"openai"`). Supported values: `"openai"`, `"anthropic"`, `"google"`,
and `"openai-compatible"`.
`"openai-compatible"`, and `"anthropic-compatible"`.
**Per-model sampling overrides:** Each model can specify `temperature`,
`max_tokens`, and `reasoning_effort` to override the global defaults from
@@ -765,6 +775,153 @@ model = "qwen-3.5-vl"
supports_vision = true
```
**Anthropic-compatible local servers (vLLM `/v1/messages`):** the
`"anthropic-compatible"` provider drives local servers that expose
Anthropic's Messages API for arbitrary checkpoints — vLLM's
`/v1/messages` endpoint, which requires a release with thinking-block
support in the Anthropic endpoint (post-2026-02-28; verified against
v0.22.1rc1). The lane reuses `AnthropicProvider` in compat mode: same
wire translation as the real Anthropic lane, but every model resolves to
the `_ANTHROPIC_COMPAT_DEFAULT` capabilities (200K context, 64K output,
`token_param=max_tokens`, `thinking_mode=none`, no native
web_search/tool_search, no vision) — the static Claude table never
applies to local checkpoints. `base_url` is required — the server root
WITHOUT `/v1` (the Anthropic SDK appends `/v1/messages`); a trailing
`/v1` pasted out of openai-compatible habit is stripped automatically,
and an empty value fails at client construction rather than falling
back to the commercial endpoint. Set a
placeholder `api_key` (e.g. `"dummy"`) for unauthenticated servers. Tool calling
needs the server started with `--enable-auto-tool-choice
--tool-call-parser <family>` plus the matching reasoning parser.
Per-model capability overrides opt in to what the checkpoint actually
supports:
```toml
[models.vllm-claude]
provider = "anthropic-compatible"
base_url = "http://localhost:8000" # no /v1 — the SDK appends /v1/messages
api_key = "dummy"
model = "deepseek-ai/DeepSeek-V4-Flash"
[models.vllm-claude.capabilities]
supports_vision = true # multimodal checkpoints only
supports_mid_conversation_system = true # template-dependent
context_window = 131072
thinking_mode = "manual" # session effort knob drives the template toggle
thinking_param = "enable_thinking" # Qwen/Gemma key; "thinking" for Granite/DeepSeek
```
Reasoning control does NOT use Anthropic's `thinking` request param —
the levers live in the chat template, reached through
`chat_template_kwargs` in the request body. Two channels, dynamic first:
* **Session effort knob (dynamic).** Set the model's thinking mode to
"Effort-knob controlled" in the admin Models form (or
`thinking_mode = "manual"` + `thinking_param` under
`[models.*.capabilities]`) and the provider maps the session's
reasoning-effort knob onto the template toggle per-request: effort
`none` sends `{<thinking_param>: false}`, any other level sends
`true` — the same contract as the real lane's manual mode. ("Always
on" / `thinking_mode = "adaptive"` instead always sends `true`: the
model self-regulates, so the knob never force-disables — mirroring
the native adaptive branch.) The graded effort value always rides
alongside the toggle: under `effort_param` when the operator names
the template's key, else under the conventional fallback key
(`reasoning_effort`) on the anthropic-compatible lane — the user's
effort setting always reaches the wire, and a template that doesn't
reference the kwarg ignores it. On the openai-compatible lane the
undeclared-key case rides the flat top-level `reasoning_effort`
param instead (the documented compat field), forwarded verbatim.
Optional `reasoning_effort_values` / `default_reasoning_effort`
validate the knob before it reaches the server; without declared
values the knob is forwarded as-is. The knob is ordinal, and validation
respects that: an off-list knob value rounds UP onto the declared
list and a value above the ceiling rides the ceiling
(`snap_reasoning_effort`) — asking for more effort than the model
declares never falls back to a lower default tier. The knob's
`none` position is forwarded verbatim when the model declares an
explicit `none` level (gpt-5.1+, grok-4.3) — omitting it there would
leave a reasoning-on server default (e.g. gpt-5.5's `medium`) in
charge of a knob that promises off — and omitted otherwise; `none`
is never a snap target for other positions.
`default_reasoning_effort` only catches values the ordinal snap
cannot rank (custom strings). Declare values that match the
template's documented vocabulary: for DeepSeek-V4, which officially
accepts `high`/`max` (Think High is the default thinking tier;
`low`/`medium` alias to `high`, `xhigh` to `max`), a
`("high", "max")` values list reproduces the official aliasing
exactly — `low`/`medium` round up to `high`, `xhigh` to `max`
and freeform passthrough matches it too. To map an undocumented
template, probe with per-request `chat_template_kwargs` and compare
`input_tokens`. Setting `effort_param` also suppresses the
flat top-level `reasoning_effort` request param on the
openai-compatible lane — the template channel replaces it, never
doubles it. With the default `thinking_mode = "none"` nothing is
injected and the server's template default decides.
Upgrade note: before 1.7.0a7 the openai-compatible lane sent the
toggle unconditionally `true` whenever thinking mode was enabled. A
stored per-model `reasoning_effort = "none"` now disables thinking
on such models — pick any real level (or clear the override) to keep
it on. Also since 1.7.0a7 the effort level itself always reaches the
wire on the local lanes (previously dropped unless
`reasoning_effort_values` was declared): flat `reasoning_effort` on
openai-compatible, the `effort_param`-or-fallback template key on
anthropic-compatible when reasoning control is engaged.
* **Operator pin (static).** Entries under `{"chat_template_kwargs":
...}` in the admin Models extra-body field ride the SDK's
`extra_body` unconditionally and win over the knob mapping on key
collision — e.g. pin `{"enable_thinking": true}` to keep thinking on
regardless of the session knob. (Server type and API surface remain
openai-compatible-only knobs and stay hidden for this provider.)
The same knob mapping drives the `openai-compatible` lane's Chat
Completions requests — `merge_reasoning_template_kwargs` is shared by
both local-server lanes, so `thinking_mode`/`thinking_param`/
`effort_param` mean the same thing whichever endpoint serves the model.
Only the Responses API surface (native reasoning) ignores it.
The console surfaces this projection as an *effective effort ladder*:
the admin model form's per-model effort select and the skill
launch-config effort select annotate each position with what the
request will carry, in plain words — a position whose delivered level
matches its name stays plain ("Max"), a snapped position says so
("Low — sends high"), the adaptive lanes' none position warns
"thinking stays on", and budget detail lives in the tooltip. A
position is never labeled after a sibling that shares its wire (that
rendered "Max (= minimal)", implying a downgrade the wire doesn't
contain). Computed server-side by `providers/effort_ladder.py` from
the same mapping functions the providers use at request time and
shipped on `/v1/api/models` rows (every row carries `effort_ladder`,
empty when the capabilities column fails to parse) and
`POST /v1/api/admin/models/effort-ladder`. The ladder describes what
Turnstone sends — a server-side template may alias further (DeepSeek-V4
folds `low`/`medium` into its default `high` tier).
The `anthropic-compatible` lane never sends Anthropic's native
`thinking`/`output_config` params — they are not in vLLM's request
schema. The real `anthropic` provider is unaffected: official Claude
models keep native thinking, budget mapping, and `output_config`
effort. A gateway fronting *real* Claude on a Messages-shaped URL
(e.g. a LiteLLM `anthropic/` route to the Claude API) should use
`provider = "anthropic"` with a custom `base_url`, which keeps the
native thinking params.
Verified quirks of vLLM's Anthropic endpoint:
* The `thinking` request param is silently dropped — use
`chat_template_kwargs` (above) to control reasoning.
* `stop_sequences` cut the raw stream wherever the text appears —
including inside thinking — and report `end_turn` with
`stop_sequence=None`. Turnstone does not send stop sequences from
this provider.
* No cache telemetry: `usage` carries input/output token counts only
(no `cache_creation_input_tokens` / `cache_read_input_tokens`).
* Images require a multimodal checkpoint — text-only models return a
500 on image blocks, so `supports_vision` stays opt-in per model.
* Mid-conversation `role: "system"` turns are template-dependent —
opt in per model via `supports_mid_conversation_system`.
**Database model definitions:** On server entry points, models can also be
defined in the `model_definitions` table (admin Models tab). DB models support
the same per-model sampling overrides. Config.toml models override DB models
@@ -960,9 +1117,10 @@ reconstructs the OpenAI message format from database rows:
in the same workstream
**Config persistence:** LLM-affecting parameters (`temperature`,
`reasoning_effort`, `max_tokens`, `instructions`, `creative_mode`) are
persisted to the `workstream_config` table on creation and whenever changed
via slash commands. `resume()` restores these values so resumed workstreams
`reasoning_effort`, `max_tokens`, `instructions`, and the persona
snapshot — see `docs/personas.md`) are persisted to the
`workstream_config` table on creation and whenever changed via slash
commands. `resume()` restores these values so resumed workstreams
behave identically to the original.
**`/clear` vs `/new`:** `/clear` wipes in-memory context but preserves
@@ -991,20 +1149,30 @@ Named (aliased) workstreams are never age-pruned. Configure with
### API Retry
`ChatSession._create_stream_with_retry()` (streaming path) and the agent
`_api_call()` (non-streaming) both use the same retry pattern:
Every model call streams (#831); retry lives at two stacked layers:
- **Retries**: 4 total attempts (1 initial + 3 retries, `_MAX_RETRIES = 3`)
- **Backoff**: exponential, base 1 second (`delay = 1s * 2^attempt`)
- **Retryable errors**: `RateLimitError`, `APITimeoutError`,
`APIConnectionError`, `InternalServerError`, `ServiceUnavailableError`,
`APIError` (matched by class name to avoid importing backend-specific
exception hierarchies)
- On retry: `ui.on_info()` notification
- On final failure: exception propagates
`_compact_messages()` also wraps its non-streaming API call in the same
retry loop.
- **Caller ladders**`ChatSession._create_stream_with_retry()` (chat
loop) and the agent `_api_call()` (drained via `model_turn`) use the
same pattern: 4 total attempts (1 initial + 3 retries,
`_MAX_RETRIES = 3`), exponential backoff base 1 second
(`delay = 1s * 2^attempt`), `ui.on_info()` on retry, exception
propagates on final failure. `_compact_messages()` wraps its drained
call in the same loop.
- **`model_turn`'s drain ladder** — inside every single-shot call,
mid-stream deaths (errors raised while draining, e.g.
`IncompleteStreamError`) are re-issued up to 2 more times with a
0.5s-base exponential backoff (±50% jitter); request-time failures
keep the SDK's own retry policy. The two ladders stack
multiplicatively on transient-shaped failures.
- **Retryable errors** are matched by class name against each
provider's `retryable_error_names` (avoids importing
backend-specific exception hierarchies): `RateLimitError`,
`APITimeoutError`, `APIConnectionError`, `InternalServerError`,
`ServiceUnavailableError`, `APIError`, plus the drained-transport
errors `IncompleteStreamError` (stream ended with no terminal
signal — for servers that never send one, declare
`finish_reason_optional` in the model's capabilities JSON) and
`ResponsesStreamFailedError` (transient in-band Responses failure).
### Finish Reason Handling
@@ -1017,7 +1185,7 @@ retry loop.
blocked.
Agent sub-sessions (`_run_agent()`) check `finish_reason` on each
non-streaming response and stop the agent early on `"length"` or
drained turn and stop the agent early on `"length"` or
`"content_filter"`.
`_compact_messages()` checks `finish_reason` on the compaction response and
@@ -1134,7 +1302,8 @@ Three hierarchical scopes control endpoint access:
`/metrics`, `/openapi.json`, `/docs`, `/api/auth/*`, and `/api/auth/setup`
are always allowed.
2. **Token extraction**`Authorization: Bearer <token>` header first, then
`turnstone_auth` cookie as fallback.
surface-scoped auth cookie (`turnstone_auth_server` on the node server,
`turnstone_auth_console` on the console) as fallback.
3. **Token type detection** — dots in the token indicate JWT; `ts_` prefix
indicates API token.
4. **Validation** — JWT signature check or API token hash lookup in storage.
+12 -25
View File
@@ -12,7 +12,6 @@ Existing bulk endpoints at time of writing:
|---------------------------------------------------------|--------------------------|------------------------------------------|
| `GET /v1/api/cluster/ws/live?ids=a,b,c` | bulk read | `{results, denied, truncated}` |
| model tool `spawn_batch` | bulk create (per-item) | `{results, denied}` |
| `POST /v1/api/workstreams/{ws_id}/stop_cascade` | cascade mutation | `{cancelled, failed, skipped}` |
| `POST /v1/api/workstreams/{ws_id}/close_all_children` | cascade mutation | `{closed, failed, skipped}` |
---
@@ -146,7 +145,7 @@ consistently-typed across the read and create cases.
```
Where `<bucket>` is the endpoint-specific name for "succeeded" —
`cancelled` for `stop_cascade`, `closed` for `close_all_children`.
`closed` for `close_all_children`.
The three buckets partition the input set exactly once:
| Bucket | Meaning |
@@ -161,20 +160,6 @@ be partial. `skipped` is pre-resolved — the target is already in
the terminal state the cascade was aiming at, so it's neither a
win to report nor a fault to fix.
### Example — `stop_cascade`
```json
{
"status": "ok",
"cancelled": ["child-1", "child-3"],
"failed": [],
"skipped": ["child-2"]
}
```
A subsequent retry would target only `failed` ids, not `skipped`
ones — the latter are already done.
### Example — `close_all_children`
```json
@@ -186,10 +171,12 @@ ones — the latter are already done.
}
```
Same partition, different success-bucket name. When `coord_client`
is unavailable (session loaded but no HTTP client attached — a
construction bug) every id goes to `failed` so the operator notices
rather than getting a silent all-skipped response.
Here the success bucket is `closed`. A subsequent retry would
target only `failed` ids, not `skipped` ones — the latter are
already done. When `coord_client` is unavailable (session loaded
but no HTTP client attached — a construction bug) every id goes to
`failed` so the operator notices rather than getting a silent
all-skipped response.
---
@@ -232,12 +219,12 @@ rather than getting a silent all-skipped response.
- **Phase 6** shipped `cluster/ws/live` as the first Shape A endpoint
(`{results, denied, truncated}`).
- **Phase 7** shipped `stop_cascade` as the first Shape B endpoint
(`{cancelled, failed, skipped}`).
- **Phase 7** introduced the Shape B cascade-mutation envelope
(`{<bucket>, failed, skipped}`) for the coordinator's
cancel-cascade path.
- **Phase 8 PR A** shipped `spawn_batch` (Shape A, keyed by idx) and
`close_all_children` (Shape B, twin of `stop_cascade`), which
crystallised the two-shape-per-semantic-category policy codified
here.
`close_all_children` (Shape B), which crystallised the
two-shape-per-semantic-category policy codified here.
Before adding a third shape, read this doc and argue for why the
new surface doesn't fit either A or B. Two idioms in the cluster
+4 -3
View File
@@ -379,6 +379,7 @@ Breadcrumb: `Cluster > Running` or `Cluster > db-west-04`. Server-side paginated
Triggered by the "+ new" header button. A modal dialog with:
- **Node selector** — dropdown with three targeting modes: "Auto (best available)" picks the node with the most headroom, "General pool (any node)" picks a node with available capacity using round-robin, or a specific node from the list (showing capacity).
- **Persona** — optional dropdown listing the enabled personas for the workstream kind. Sets the system-message composition and capability envelope at creation, snapshotted server-side; empty uses the kind's default. Picking one requires no `persona.*` permission.
- **Profile** — optional dropdown listing enabled skills. Applies the skill's model, auto-approve policy, token budget, and other behavioral settings at creation time.
- **Name** — optional text input. Auto-generated if left empty.
- **Model** — optional text input for a model alias from the target node's registry.
@@ -396,9 +397,9 @@ The browser maintains a local `clusterState` object that mirrors the cluster sna
Accessed via the "admin" button in the header (visible when authenticated
with `approve` scope). Provides user, API token, channel link, MCP server,
and skill management with 18 tabs (Users, API Tokens, Channels, Schedules,
Watches, Roles, Policies, Prompts, Judge, Skills, MCP Servers, Usage,
Audit, Memories, Models, Nodes, Settings, TLS). See also
and skill management with tabs that include Users, API Tokens, Channels,
Schedules, Watches, Personas, Roles, Policies, Prompts, Judge, Skills,
MCP Servers, Usage, Audit, Memories, Models, Nodes, Settings, and TLS. See also
[Governance](governance.md) for the Roles, Policies, Skills, Usage, and
Audit tabs, and [Settings](settings.md) for the database-backed
configuration editor.
+24 -43
View File
@@ -18,7 +18,7 @@ schema changes.
> auth and the `admin.coordinator` permission. A session-scoped JWT
> is minted per login (see [docs/oidc.md](oidc.md) / [docs/security.md](security.md));
> a service token may call the read paths but destructive governance
> paths (`/restrict`, `/stop_cascade`, `/close_all_children`) require
> paths (`/restrict`, `/close_all_children`) require
> the explicit `admin.coordinator` grant — a service-token owner
> match isn't enough.
@@ -44,7 +44,6 @@ schema changes.
| 6 | Wait for fan-out | model-side tool `wait_for_workstream` |
| 7 | Govern | `POST /v1/api/workstreams/{ws_id}/trust` |
| | | `POST /v1/api/workstreams/{ws_id}/restrict` |
| | | `POST /v1/api/workstreams/{ws_id}/stop_cascade` |
| | | `POST /v1/api/workstreams/{ws_id}/close_all_children` |
| 8 | Approve / cancel | `POST /v1/api/workstreams/{ws_id}/approve` |
| | | `POST /v1/api/workstreams/{ws_id}/cancel` |
@@ -53,7 +52,7 @@ schema changes.
Refer to `/openapi.json` (Swagger UI at `/docs`) on any
`turnstone-console` process for the authoritative operation ids and
schemas. Coordinator-only verbs (`/children`, `/trust`, `/restrict`,
`/stop_cascade`, `/close_all_children`) 404 against `kind=interactive`
`/close_all_children`) 404 against `kind=interactive`
rows; the shared verbs (`/send`, `/approve`, `/cancel`, `/events`,
`/history`, `/open`, `/close`, etc.) work on both kinds.
@@ -261,10 +260,10 @@ rounds to a 10× token-efficiency win.
---
## 7. Governance — trust, restrict, stop_cascade, close_all_children
## 7. Governance — trust, restrict, close_all_children
These four endpoints let an operator steer a live coordinator session
mid-flight. All four emit an audit event tagged
These three endpoints let an operator steer a live coordinator session
mid-flight. All three emit an audit event tagged
`coordinator.<action>` via the dedicated audit executor so a cascade
burst can't starve audit writes.
@@ -294,28 +293,6 @@ idempotent — calling twice with overlapping lists converges to the
union. Revocations don't survive a session close/reopen; operators
opt in per session. Cap 256 tool names per request, 128 chars each.
### `POST /stop_cascade` — cancel the subtree
```http
POST /v1/api/workstreams/{ws_id}/stop_cascade
{}
```
Cancels the coordinator's in-flight generation AND dispatches
`cancel_workstream` through the routing proxy for every direct
child in the in-memory registry. Returns:
```json
{"status": "ok", "cancelled": ["child-1", "child-3"], "failed": [], "skipped": ["child-2"]}
```
Response uses the [cascade-mutation bulk shape](bulk-endpoints.md):
`cancelled` = accepted, `failed` = dispatch error worth retrying,
`skipped` = upstream 404 (already gone — stale registry entry or
the row was deleted between snapshot and dispatch). Grandchildren
aren't touched directly; they sit behind their parent's cancel and
propagate via the child's SSE stream.
### `POST /close_all_children` — soft-close the direct fan-out
```http
@@ -329,16 +306,16 @@ Response:
{"status": "ok", "closed": ["c-1", "c-2"], "failed": [], "skipped": []}
```
Soft-close cascade bounded by the same semaphore as `stop_cascade`.
The `reason` (up to 512 chars) propagates into each closed child's
audit + `workstream_config` for postmortem. Unlike `stop_cascade`
this does NOT recurse into grandchildren — the model-facing tool
that pairs with this endpoint asks for a bounded teardown of the
coordinator's own fan-out. For a full-subtree teardown, use
`stop_cascade`.
Soft-close cascade bounded by a concurrency semaphore. The `reason`
(up to 512 chars) propagates into each closed child's audit +
`workstream_config` for postmortem. The model-facing tool that
pairs with this endpoint asks for a bounded teardown of the
coordinator's own fan-out. This *soft-closes*; to *cancel* the
fan-out instead, cancel the coordinator (§8) — a coordinator cancel
auto-cascades to its direct children.
See [bulk-endpoints.md](bulk-endpoints.md) for why both endpoints
share the cascade-mutation shape and how it differs from the
See [bulk-endpoints.md](bulk-endpoints.md) for why `close_all_children`
uses the cascade-mutation shape and how it differs from the
`spawn_batch` / `cluster/ws/live` shape.
---
@@ -356,7 +333,10 @@ POST /v1/api/workstreams/{ws_id}/approve
{"approved": true, "feedback": null, "always": true} // always-approve this tool name
```
`cancel` drops the in-flight generation but leaves the coordinator
`cancel` drops the coordinator's in-flight generation and, for a
coordinator, auto-cascades the cancel to its direct children:
`cancel_workstream` is dispatched through the routing proxy for
every direct child in the registry. The coordinator itself is left
idle and open for a fresh `send`:
```http
@@ -373,9 +353,10 @@ POST /v1/api/workstreams/{ws_id}/close
{}
```
Soft-closes the session — state persists, children keep running (use
`close_all_children` or `stop_cascade` first to wind them down), the
worker thread exits, SSE streams send a final `stream_end` and
Soft-closes the session — state persists, children keep running
(wind them down first with `close_all_children`, or by cancelling
the coordinator, which cascades the cancel to its direct children),
the worker thread exits, SSE streams send a final `stream_end` and
disconnect. The row is reopenable via
`POST /v1/api/workstreams/{ws_id}/open` so long as it hasn't been
deleted.
@@ -385,12 +366,12 @@ deleted.
## Further reading
- [coordinator-skills.md](coordinator-skills.md) — writing a skill
that runs on a coordinator session (orchestrator persona,
that runs on a coordinator session (orchestrator framing,
workflow patterns, `SkillKind` classifier).
- [bulk-endpoints.md](bulk-endpoints.md) — the two bulk-shape
idioms (`{results, denied, truncated}` vs
`{<bucket>, failed, skipped}`) used by `cluster/ws/live`,
`spawn_batch`, `stop_cascade`, and `close_all_children`.
`spawn_batch`, and `close_all_children`.
- [architecture.md](architecture.md) — cluster-wide architecture
including how coordinator sessions fit next to node-hosted
interactive workstreams.
+13 -13
View File
@@ -1,13 +1,13 @@
# Writing a coordinator-specific skill
Skills are prompt-level personas that steer a Turnstone session
A skill is prompt-level framing that steers a Turnstone session
toward a narrow task. Most skills target **interactive** sessions —
the single-workstream "do this thing" surface where the model wields
`bash`, `edit_file`, `web_fetch`, and the rest of the maker toolset.
A **coordinator skill** is different. It runs on a session whose job
is to orchestrate other sessions. The toolset is smaller and
narrower, the persona is an orchestrator instead of a maker, and the
narrower, the role is an orchestrator instead of a maker, and the
success metric is "did the plan resolve" instead of "did the code
compile". This doc covers the differences a skill author has to
care about.
@@ -22,8 +22,8 @@ migration 044 added the column). Three values:
| `SkillKind` enum | Stored as | Meaning |
|-------------------------|-----------------|----------------------------------------------------------------------------|
| `SkillKind.INTERACTIVE` | `"interactive"` | Authored for the interactive maker persona (single-workstream "do this"). |
| `SkillKind.COORDINATOR` | `"coordinator"` | Authored for the orchestrator persona (delegate, monitor, synthesise). |
| `SkillKind.INTERACTIVE` | `"interactive"` | Authored for the interactive maker role (single-workstream "do this"). |
| `SkillKind.COORDINATOR` | `"coordinator"` | Authored for the orchestrator role (delegate, monitor, synthesise). |
| `SkillKind.ANY` | `"any"` | Either surface (or audience-neutral). Default on create. |
The `kind` field is a `StrEnum` — drop-in `str` compatible — so DB
@@ -77,7 +77,7 @@ or MCP config can do adds to it. Current members:
| `delete_workstream` | wind-down | Hard-delete one child. Requires approval. |
| `list_nodes` | discover | Enumerate live cluster nodes + capabilities. |
| `skills` (action=find) | discover | Browse the skill catalog; opt-in `kind` filter narrows by audience. |
| `memory` | persist | Orchestration scratchpad keyed by the `coordinator` scope. |
| `memory` | persist | Durable orchestration memory (`coordinator` scope, per-user — survives across coordinator sessions). |
| `notify` | broadcast | Post a status update to a human channel at a narrative beat. |
| `tasks` | plan | Orchestrator-only scratchpad. Children don't see it. |
@@ -96,20 +96,20 @@ for the output. The coordinator stays the orchestrator.
---
## Persona differences
## Framing differences
Interactive skills compose on top of `base_interactive.md` — a
"maker" persona: get the work done, use the tools, edit the code,
"maker" framing: get the work done, use the tools, edit the code,
close the loop.
Coordinator skills compose on top of
[`base_coordinator.md`](../turnstone/prompts/base_coordinator.md) —
an "orchestrator" persona: decompose, delegate, monitor, synthesise.
[`personas/orchestrator.md`](../turnstone/prompts/personas/orchestrator.md) —
an "orchestrator" framing: decompose, delegate, monitor, synthesise.
The base text is short but sets the tone every coordinator skill
inherits:
> You are a coordinator on a small, focused infrastructure team.
> Your role is to orchestrate work across the cluster... You do
> You are a coordinator. Your role is to orchestrate work across
> the cluster... You do
> not edit files, run shell commands, browse the web, or manipulate
> the codebase directly. Children do that.
@@ -339,7 +339,7 @@ For a new coordinator skill:
A full end-to-end test isn't required for every skill; a
prepare-step unit test that asserts "given this initial message, the
first tool call is X with Y args" is usually sufficient to catch
persona drift without a real LLM in the loop.
framing drift without a real LLM in the loop.
---
@@ -351,7 +351,7 @@ persona drift without a real LLM in the loop.
`spawn_batch` and `close_all_children` use, so your skill can
parse results / denied arrays correctly.
- [governance.md](governance.md) — the broader governance surface
(`/trust`, `/restrict`, `/stop_cascade`, role-based permissions)
(`/trust`, `/restrict`, role-based permissions)
that wraps every coord session.
- [settings.md](settings.md) — `coordinator.model_alias` and
`coordinator.reasoning_effort` settings that gate which LLM runs
+2 -3
View File
@@ -66,8 +66,7 @@ class "NullUI" as NullUI {
interface "LLMProvider" as LLMProvider <<Protocol>> {
+ provider_name: str {property}
+ get_capabilities(model) → ModelCapabilities
+ create_streaming(client, model, messages, ..., replay_reasoning_to_model) → Iterator[StreamChunk]
+ create_completion(client, model, messages, ..., replay_reasoning_to_model) → CompletionResult
+ create_streaming(client, model, messages, ..., cancel_ref, replay_reasoning_to_model) → Iterator[StreamChunk]
+ convert_tools(tools) → list[dict]
+ extract_reasoning_text(provider_blocks) → str
+ retryable_error_names: frozenset[str] {property}
@@ -177,7 +176,7 @@ class "HeadlessSession" as HeadlessSession {
+ send_headless(input, max_turns, ...)
- _override_system_prompt(content)
--
eval.py: non-streaming,
eval.py: drained single-shot turns,
records all tool calls
}
+2 -2
View File
@@ -84,8 +84,8 @@ end note
loop up to 3 turns (timeout budget)
Judge -> LLM : create_completion(\nmodel, judge_messages,\ntools=[read_file, list_directory])
LLM --> Judge : CompletionResult
Judge -> LLM : model_turn(lane, judge_turns,\ntools=[read_file, list_directory])\nvia drained create_streaming
LLM --> Judge : ModelTurnResult
alt tool_calls present (turn < 3)
Judge -> Judge : _exec_read_only_tool()
+64 -16
View File
@@ -59,9 +59,11 @@ is gone. Everything goes through `https://localhost:8443`.
## Join a bare-metal host
PostgreSQL is published on `127.0.0.1:5432`, so a `turnstone-server` running
directly on the same machine — for example to use a local GPU — can join the
same cluster and show up in the console alongside the containerized nodes.
PostgreSQL, the console's ACME endpoint (`:8090`), and SearxNG (`:8081`) are
published on `127.0.0.1`, so a `turnstone-server` running directly on the same
machine — for example to use a local GPU — can join the same cluster (enrolling
its mTLS cert and running `web_search`) and show up in the console alongside the
containerized nodes.
Put the secret and connection settings in `~/.config/turnstone/config.toml`
(secrets belong in this file, not the process environment — keep it `0600`,
@@ -85,18 +87,31 @@ command line:
```bash
chmod 600 ~/.config/turnstone/config.toml
TURNSTONE_NODE_ID=host-1 TURNSTONE_ADVERTISE_URL=http://host.docker.internal:8080 \
TURNSTONE_NODE_ID=host-1 \
TURNSTONE_ADVERTISE_URL=http://host.docker.internal:8080 \
TURNSTONE_CONSOLE_URL=http://localhost:8090 \
TURNSTONE_SEARXNG_URL=http://localhost:8081 \
turnstone-server --host 0.0.0.0 --port 8080
```
The host server registers itself in PostgreSQL; the console reaches it back via
`host.docker.internal`. The `jwt_secret` and DB credentials above are the
dev-stack defaults — match whatever you set in `.env` if you changed them. To
let a **different** machine join, start the stack with `POSTGRES_BIND=0.0.0.0`
and use the host's routable IP in the `url` and `TURNSTONE_ADVERTISE_URL`
but **set a strong `POSTGRES_PASSWORD` first**, or you'll expose a database with
the insecure default password (and every user account + API-token hash in it) to
your network.
`host.docker.internal`. `TURNSTONE_CONSOLE_URL` points the node at the console's
published ACME endpoint so it can enroll its mTLS certificate (needed only when
the cluster runs mTLS; harmless otherwise), and `TURNSTONE_SEARXNG_URL` points
`web_search` at the published SearxNG. The `jwt_secret` and DB credentials above
are the dev-stack defaults — match whatever you set in `.env` if you changed them.
To let a server on a **different** machine join, start the stack with
`TURNSTONE_HOST_IP=<this host's LAN IP>` — that binds PostgreSQL, the console
ACME endpoint, and SearxNG to that interface. Then on the remote box set the
three URLs above to that IP, and set `TURNSTONE_ADVERTISE_URL` to the **remote**
box's own IP (the address the console dials back). **Set a strong
`POSTGRES_PASSWORD` first** — `TURNSTONE_HOST_IP` exposes the database (and every
user account + API-token hash in it), the console API, and the unauthenticated
SearxNG to your network.
To run the bare-metal node as a hardened, persistent service instead of by hand,
use the systemd units in [`deploy/systemd/`](../deploy/systemd/).
## Production stack
@@ -110,7 +125,7 @@ docker compose -f turnstone/deploy/compose.yaml up
It's the same shape as the dev stack — Caddy-fronted console, channel, and a
PostgreSQL all share one database so the console discovers the node — but it
pulls released images, runs a single server node, and has **no baked-in
secrets**. Set these in `.env` first (`turnstone-bootstrap` generates them):
secrets**. Set these in `.env` first (generate with `openssl rand -hex 32`):
```bash
TURNSTONE_JWT_SECRET=<python -c "import secrets; print(secrets.token_hex(32))">
@@ -174,15 +189,18 @@ overrides.
### Ports
Both stacks publish Caddy (dashboard) and PostgreSQL; the dev stack additionally
publishes the SearxNG UI on localhost. Everything else is reached through Caddy or
proxied by the console:
publishes the console's ACME endpoint and SearxNG on localhost so a bare-metal
node can enroll its cert and run `web_search`. Everything else is reached through
Caddy or proxied by the console:
| Variable | Default | Description |
|----------|---------|-------------|
| `CONSOLE_HTTPS_PORT` | `8443` | Host port for Caddy (dashboard HTTPS) |
| `SEARXNG_HTTPS_PORT` | `8444` | Host port for the SearxNG UI via Caddy (dev: localhost-only; prod: opt-in) |
| `POSTGRES_PORT` | `5432` | Host port for PostgreSQL (for bare-metal joins) |
| `POSTGRES_BIND` | `127.0.0.1` | Interface PostgreSQL binds on; set `0.0.0.0` for LAN access |
| `SEARXNG_API_PORT` | `8081` | Host port for the SearxNG API a bare-metal node's `web_search` dials (dev stack) |
| `TURNSTONE_HOST_IP` | `127.0.0.1` | Interface PostgreSQL, the console ACME endpoint, and SearxNG bind on (dev stack). Set to this host's LAN IP so a bare-metal node on **another machine** can reach them — set a strong `POSTGRES_PASSWORD` first (it also exposes the DB and the unauthenticated SearxNG to your network). |
| `POSTGRES_BIND` | `127.0.0.1` | Production stack (`turnstone/deploy/compose.yaml`) only: interface PostgreSQL binds on; set to the host's LAN IP for remote joins. |
### Channel gateway
@@ -234,6 +252,7 @@ interface, or anyone who can reach it can search through your instance.
| Variable | Default | Description |
|----------|---------|-------------|
| `WORKSPACE_MOUNT` | empty volume | Host directory bind-mounted at `/workspace` for the model to read/write |
| `TURNSTONE_WORKSPACE` | `/workspace` (image env) | Directory named as the user's workspace in the model's tool descriptions; informational only — see [Working directory](#working-directory) |
| `SKIP_PERMISSIONS` | — | Set to any value to auto-approve all tool calls (dev only) |
| `MCP_CONFIG` | — | Path to an MCP server config file |
| `TURNSTONE_IMAGE_TAG` | `latest` | ghcr.io image tag — production stack |
@@ -242,7 +261,7 @@ interface, or anyone who can reach it can search through your instance.
Both stacks install all entry points into a single image (`turnstone`,
`turnstone-server`, `turnstone-console`, `turnstone-channel`, `turnstone-admin`,
`turnstone-eval`, `turnstone-bootstrap`):
`turnstone-eval`, `turnstone-optimizer`, `turnstone-doctor`):
```bash
docker compose build # build the dev image
@@ -258,6 +277,35 @@ docker compose build --no-cache # rebuild from scratch
| `workspace` | `/workspace` (unless `WORKSPACE_MOUNT` is set) |
| `caddy-data` / `caddy-config` | Caddy's local CA and config (dev stack) |
## Working directory
Node processes run with `/data` as their working directory (the image's
`WORKDIR`), and that is where the model's shell commands execute and
relative file paths resolve — **not** `/workspace`. The shell and file
tool descriptions state both paths (the working directory, and the
workspace named by `TURNSTONE_WORKSPACE`), so the model knows to look in
`/workspace` for your files without being told each session.
To make tools start inside the mount instead, override the working
directory on the node services:
```yaml
services:
turnstone-node:
working_dir: /workspace
```
Two caveats before overriding:
- **SQLite fallback**: when a node runs without PostgreSQL, its fallback
database `.turnstone.db` is created in the process working directory.
Changing `working_dir` on an existing SQLite-fallback deployment makes
the node create a fresh database inside the mount and your prior state
appears lost (it is still in the `turnstone-data` volume under `/data`).
The stock compose stacks use PostgreSQL and are unaffected.
- Migrations (`entrypoint.sh`) run in the same working directory, so the
same SQLite caveat applies to them.
## Cleanup
```bash
+55 -24
View File
@@ -1,11 +1,19 @@
# Evaluation and Prompt Optimization (turnstone-eval)
# Evaluation and Prompt Optimization (turnstone-eval, turnstone-optimizer)
`turnstone-eval` is the evaluation and prompt optimization system for turnstone. It
runs test cases against the LLM, scores tool call sequences against expected
actions, and optionally uses a multi-agent pipeline to optimize the developer
prompt and tool descriptions.
Evaluation for turnstone is split into two commands:
Source: `turnstone/eval.py`
- **`turnstone-eval`** — the measurement substrate. Runs test cases against the LLM
and scores tool call sequences against expected actions. A single measurement pass,
no self-modification.
- **`turnstone-optimizer`** — the prompt/tool optimizer. Loops over the measurement
substrate, using a multi-agent pipeline (analyst, optimizer, observer, diversifier,
tool optimizer) to edit the developer prompt and tool descriptions so more tests pass.
The dependency is strictly one-way: the optimizer consumes the eval substrate; the
substrate never depends on the optimizer.
Source: `turnstone/eval/core.py` (measurement substrate), `turnstone/eval/cli.py`
(the `turnstone-eval` CLI), `turnstone/optimizer.py` (the `turnstone-optimizer` CLI).
---
@@ -27,8 +35,8 @@ This approach (inspired by [Learning to Self-Evolve](https://arxiv.org/abs/2603.
prevents irrecoverable collapse from bad edits — UCB naturally backtracks to
high-scoring ancestors instead of following a linear chain.
When optimization is disabled (`--no-optimize`), only steps 2-4 execute
(a single iteration evaluating the root node).
The `turnstone-eval` command (or `turnstone-optimizer --no-optimize`) executes only
steps 2-4: a single measurement pass over the root prompt, no optimization.
---
@@ -452,30 +460,46 @@ structure is:
## CLI Usage
The entry point is `turnstone-eval` (installed as a console script) or
`python -m turnstone.eval`.
Two console scripts (installed as entry points), or the equivalent `python -m`
invocations:
- `turnstone-eval` / `python -m turnstone.eval.cli` — measure only.
- `turnstone-optimizer` / `python -m turnstone.optimizer` — optimize.
### Measure (`turnstone-eval`)
```
turnstone-eval tests.json # evaluate + optimize
turnstone-eval tests.json --no-optimize # evaluate only (single iteration)
turnstone-eval tests.json --n-runs 5 --max-iter 10 # more thorough evaluation
turnstone-eval tests.json --prompt custom.txt # start from a custom prompt
turnstone-eval tests.json --optimize-tools # optimize tool descriptions only
turnstone-eval tests.json --diversify 10 # test with prompt variants
turnstone-eval tests.json -v # verbose per-turn logging
turnstone-eval tests.json # one measurement pass, print scores
turnstone-eval tests.json --prompt custom.txt # measure a custom prompt
turnstone-eval tests.json --n-runs 5 # more runs per case
turnstone-eval tests.json --parallel 4 # run cases across 4 workers
turnstone-eval tests.json -v # verbose per-turn logging
```
### Multi-model setup (local test model, cloud optimizer)
### Optimize (`turnstone-optimizer`)
```
turnstone-eval tests.json \
turnstone-optimizer tests.json # evaluate + optimize
turnstone-optimizer tests.json --no-optimize # single pass, no optimization
turnstone-optimizer tests.json --n-runs 5 --max-iter 10 # more thorough optimization
turnstone-optimizer tests.json --prompt custom.txt # start from a custom prompt
turnstone-optimizer tests.json --optimize-tools # optimize tool descriptions only
turnstone-optimizer tests.json --diversify 10 # test with prompt variants
```
#### Multi-model setup (local test model, cloud optimizer)
```
turnstone-optimizer tests.json \
--base-url http://localhost:8000/v1 \
--optimizer-base-url https://api.anthropic.com \
--optimizer-model claude-sonnet-4-6 \
--analyst-model claude-opus-4-6
```
### All Options
### Measurement Options
Accepted by **both** commands.
| Flag | Default | Description |
|-------------------------|----------------------------|-------------|
@@ -484,19 +508,26 @@ turnstone-eval tests.json \
| `--model` | auto-detect | Model name. Auto-detected from the API if not specified. |
| `--prompt` | turnstone built-in prompt | Path to initial prompt text file. |
| `--n-runs` | from tests.json or 3 | Number of runs per test case. |
| `--max-iter` | 5 | Maximum optimization iterations. |
| `--no-optimize` | false | Run evaluation only (sets max-iter to 1). |
| `--temperature` | 0.7 | Sampling temperature. |
| `--max-tokens` | 32768 | Max completion tokens. |
| `--reasoning-effort` | `medium` | Reasoning effort: `low`, `medium`, or `high`. |
| `--context-window` | 131072 | Context window size. |
| `--output` | `eval_results.json` | Output results file path. |
| `-v`, `--verbose` | false | Show detailed per-turn logging. |
| `--explore-constant` | 1.414 (sqrt(2)) | UCB exploration constant C. |
| `--test-timeout` | 300 | Per-test timeout in seconds. |
| `--suite-timeout` | 0 (unlimited) | Total suite timeout in seconds. |
| `--no-fast-fail` | false | Disable early termination on all-zero initial runs. |
| `--parallel` | 1 (serial) | Parallel workers (0=auto, N=use N workers). |
### Optimizer Options
Accepted by **`turnstone-optimizer`** only.
| Flag | Default | Description |
|-------------------------|----------------------------|-------------|
| `--max-iter` | 5 | Maximum optimization iterations. |
| `--no-optimize` | false | Run a single measurement pass (sets max-iter to 1). |
| `--explore-constant` | 1.414 (sqrt(2)) | UCB exploration constant C. |
| `--suite-timeout` | 0 (unlimited) | Total suite timeout in seconds. |
| `--optimizer-model` | same as `--model` | Model for prompt optimization. |
| `--optimizer-base-url` | same as `--base-url` | Base URL for optimizer model. |
| `--observer-model` | same as optimizer | Model for meta-optimization (observer). |
+14 -6
View File
@@ -13,7 +13,7 @@ The permission model has two layers:
1. **Scopes** (legacy) — `read`, `write`, `approve`. Checked by `AuthMiddleware`
on every request based on URL path classification.
2. **Permissions** (granular) — 15 permission strings checked per-endpoint by
2. **Permissions** (granular) — named permission strings checked per-endpoint by
`require_permission()`.
**Built-in roles** (seeded by migration 008):
@@ -24,7 +24,11 @@ The permission model has two layers:
| operator | read, write, workstreams.create, workstreams.close |
| viewer | read |
Custom roles can be created with any subset of the 15 valid permissions.
Custom roles can be created with any subset of the valid permissions.
The `persona.create` / `persona.read` / `persona.write` family gates
persona administration; migration `063` seeds all three onto
`builtin-admin`, and any role can be granted them through the standard
role and permission-override editors.
**Auth flow:**
1. User logs in (password or API token) → `_load_user_permissions()` aggregates
@@ -127,9 +131,12 @@ Per-LLM-request token and tool call metrics:
LLM response with prompt/completion tokens, cache tokens, tool call count,
model, ws_id
- **Prompt caching**: Anthropic automatic caching (`cache_control: ephemeral`)
and OpenAI extended retention (`prompt_cache_retention: 24h` for GPT-5.x)
are enabled by default. `cache_creation_tokens` and `cache_read_tokens` are
tracked per request in `usage_events` and surfaced in the Usage admin tab
and OpenAI caching are enabled by default. Pre-5.6 GPT-5 models request
`prompt_cache_retention: 24h`; GPT-5.6 uses
`prompt_cache_options: {"ttl": "30m"}`. GPT-5.6 cache writes use the
provider's 1.25× input-token rate. `cache_creation_tokens` and
`cache_read_tokens` are tracked per request in `usage_events` and surfaced
in the Usage admin tab
- **Querying**: `GET /v1/api/admin/usage` with `group_by` (day/hour/model/user)
and time range filtering — includes cache token aggregates
- **Prometheus**: `turnstone_tokens_total{type="cache_creation|cache_read"}`
@@ -177,6 +184,7 @@ All under `/v1/api/admin/` (requires `approve` scope + granular permission).
| Orgs | 3 (list, get, update) | `admin.orgs` |
| Tool Policies | 4 (CRUD) | `admin.policies` |
| Skills | 4 (CRUD) | `admin.skills` |
| Personas | 4 (list, create, get, edit/archive) | `persona.read` / `persona.create` / `persona.write` |
| Schedules | 6 (CRUD + runs) | `admin.schedules` |
| Watches | 3 (list, create, cancel) | `admin.watches` |
| Usage | 1 (aggregated query) | `admin.usage` |
@@ -222,7 +230,7 @@ Both Python and TypeScript console SDKs expose governance methods:
- **Privilege escalation prevented**: `admin_assign_role` blocks self-assignment
and requires caller to hold a superset of the target role's permissions
- **Permission validation**: Role create/update validates permissions against
a 15-item allowlist (`_VALID_PERMISSIONS`)
the permission allowlist (`_VALID_PERMISSIONS`)
- **Self-deletion blocked**: `admin_delete_user` rejects attempts to delete
your own account (matching the self-assignment guard on role endpoints)
- **Field allowlists**: Storage `update_*` methods filter fields against
+14 -7
View File
@@ -40,7 +40,7 @@ api_key = ""
smart_approvals = false # auto-approve high-confidence "approve" LLM verdicts (opt-in)
confidence_threshold = 0.95 # Smart Approvals auto-approve bar (LLM recommendation=approve)
max_context_ratio = 0.5 # max % of judge context window for history
timeout = 60.0 # seconds (generous for local models)
timeout = 120.0 # seconds (generous for local models)
read_only_tools = true # judge can use read_file/list_directory
cancel_on_approval = false # stop judging remaining tool calls once user decides
```
@@ -71,7 +71,7 @@ All fields are optional. The judge is enabled by default; use `enabled = false`
--judge / --no-judge Enable/disable (default: enabled)
--judge-model MODEL Model for judge
--judge-provider PROVIDER Provider for judge
--judge-timeout SECONDS LLM judge timeout (default: 60)
--judge-timeout SECONDS LLM judge timeout (default: 120)
--judge-confidence FLOAT Confidence threshold, 0-1 (default: 0.95)
```
@@ -193,9 +193,10 @@ Security hardening blocks access to sensitive paths:
### Timeout
The `timeout` setting (default 60 seconds) is a total budget across all judge
turns. Time is decremented after each LLM call. If the budget expires mid-turn,
the judge attempts to parse whatever partial response is available.
The `timeout` setting (default 120 seconds) applies **per turn**, not as a total
budget across turns — each of the up to 5 turns gets a fresh budget, so a slow
earlier turn doesn't starve later ones. If a turn's budget expires, the judge
attempts to parse whatever partial response is available.
---
@@ -248,8 +249,14 @@ are withheld from the live surfaces (a reused call_id must never ride a stale
`approve` into Smart Approvals) but still persist with
`user_decision = "superseded"` so the audit trail records the judge's answer.
Sub-agents (plan agent, task agent) are exempt from intent validation -- they
always get full tool visibility without judge evaluation.
Sub-agent (task agent) tool calls are judge-gated too. Each runs the same
intent pipeline as its own `agent_gate` generation, grounded in that sub-agent's
own trajectory -- its task prompt is the delegation contract the operator
approved, so "does this call serve the task" is the right local question.
Agent-gate generations never occupy the main loop's supersede slot (parallel
siblings would otherwise make each other's verdicts look stale); per-cycle
generation checks enforce staleness instead, and `judge.cancel_on_approval`
fires per gate exactly like the main loop.
---
+64 -4
View File
@@ -17,8 +17,9 @@ The MCP server admin form exposes three authorization modes ("Multitenant Author
| `none` | No headers attached. Open MCP server (or one gated by network policy only). | Internal MCP servers on a trusted network. |
| `static` | One static bearer token, configured per server, sent on every request from every user. | Service-to-service MCP servers where per-user attribution doesn't matter, or single-tenant deployments. |
| `oauth_user` *(recommended for user-data servers)* | Each user authorizes separately via OAuth 2.1 + PKCE; Turnstone stores per-user tokens encrypted at rest. | MCP servers that expose user-specific data or that want per-user audit attribution. |
| `oauth_obo` *(sign-in passthrough)* | Each user's Turnstone **org sign-in** (OIDC) mints a per-server access token on demand — no separate per-server consent. One captured credential per user covers every `oauth_obo` server. | Enterprise deployments where the identity provider governs access (Entra, Keycloak) and you want zero per-user connect clicks. See the dedicated section below. |
Switching `auth_type` away from `oauth_user` orphans existing per-user tokens. Use the admin **bulk-revoke** affordance on the server row (Phase 9) to clear them, or let them expire naturally — they're inert without the matching `auth_type` value.
Switching `auth_type` away from `oauth_user` / `oauth_obo` **deletes** that server's per-user rows (consents / minted cache) — see the transition table below. Switching back later starts clean: users re-consent (or re-mint) on next use. The admin **bulk-revoke** / **flush cache** affordance clears rows without an auth-type change.
---
@@ -65,6 +66,58 @@ Keep this in `config.toml` rather than environment variables. An in-process LLM
---
## `auth_type=oauth_obo` — single-credential sign-in passthrough
Where `oauth_user` makes each user complete a **separate** browser consent per MCP server, `oauth_obo` reuses the user's Turnstone **org sign-in** (OIDC). Turnstone captures one refresh credential per user at login and, on each tool call, mints a short-lived access token scoped to that server's audience. There is no per-server connect step, and one credential covers every `oauth_obo` server. This is the right shape when your identity provider already governs who may reach each backend (an Entra tenant with Entra-protected MCP servers; a Keycloak realm with token exchange).
Access is governed **downstream** by the IdP: a user can only mint a token for a server their delegated permissions allow. Removing that grant at the IdP cuts the user off regardless of their Turnstone state.
### Deployment configuration (`[oidc]` in `config.toml`)
`oauth_obo` requires OIDC SSO to be configured (it is the credential source), plus:
```toml
[oidc]
# ... your existing issuer / client_id / client_secret ...
capture_user_credential = true # persist the IdP refresh token at login
obo_grant_profile = "entra" # "entra" | "rfc8693" — how tokens are minted
```
- **`capture_user_credential`** (default `false`): when enabled, Turnstone appends `offline_access` to the login scopes and stores the returned refresh token, encrypted with the same `[security] mcp_token_encryption_key` as `oauth_user` tokens. **The encryption key is required** — Turnstone refuses to start with an `oauth_obo` row (or capture enabled) and no key.
- **`obo_grant_profile`** picks the mint mechanism (the IdP determines which one is valid; this is deployment-wide, not per-server):
- **`entra`** — redeems the user's refresh token directly for a token scoped to `<audience>/.default`. `oauth_scopes` on the server row is **not used** (the admin form rejects it under this profile).
- **`rfc8693`** — a refresh grant for a subject token, then an RFC 8693 token exchange for the server audience. Per-server `oauth_scopes` **are** sent on the exchange (some IdPs require the audience scope explicitly).
### Adding an `oauth_obo` server
In the admin MCP form, choose **Sign-in passthrough** and set **Audience** (required — the downstream resource the token is minted for, e.g. `api://<app-id>` on Entra or the client id on Keycloak). The client-id / secret / registration fields do not apply and are hidden.
`oauth_obo` servers are accepted only when **OIDC sign-in is configured and enabled** and `[oidc] obo_grant_profile` is a valid profile — the write is rejected otherwise, since a row that can never mint would surface to users as a permanent "please retry" that never heals.
### Identity-provider setup
**Entra (`obo_grant_profile = "entra"`):**
1. Turnstone's app registration must hold **delegated permissions** to each MCP server's exposed API, with **admin consent granted** (or the MCP app listed in Turnstone's `preAuthorizedApplications`).
2. Set the server row's Audience to the MCP app's Application ID URI (`api://<guid>`).
3. **Gotcha (verified):** admin-consent issued *immediately* after creating the app/service principal can silently skip a not-yet-propagated resource — the only symptom is `AADSTS65001` at mint time. Verify the delegated grant landed (`az ad app permission list-grants` / the portal's *API permissions* blade shows *Granted*), or grant it explicitly per resource. A missing grant surfaces in Turnstone as a re-login prompt on the affected server (same rail as a revoked credential), and the `mcp_server.oauth.obo_mint_rejected` log line carries the raw `AADSTS…` text.
**Keycloak / RFC 8693 (`obo_grant_profile = "rfc8693"`):**
1. Enable **standard token exchange** on Turnstone's client.
2. Grant the audience: add an audience client scope for each MCP client and attach it to Turnstone's client (optional scopes must be requested — set the server row's Scopes to that scope, or the exchange returns *"Requested audience not available"*).
3. Set the server row's Audience to the downstream client id.
### Revocation & custody
The captured credential is a single per-user secret that can mint for every `oauth_obo` server, so treat it like any long-lived credential:
- **Cut off one user:** unlink their OIDC identity in the admin console (**Users → OIDC identities → delete**). This revokes the captured credential **and** purges their minted cache rows, so future mints fail and cached tokens are dropped. (Warmed in-memory sessions on server nodes self-expire at the access-token TTL; there is no cross-node per-user session-kill.) Removing the user's access at the IdP is the authoritative cut-off.
- **Flush a server's minted tokens** (e.g. after narrowing its audience): the server row's **flush cache** action drops all users' cached tokens for that server. This is **not** a revocation — users re-mint on next use from their still-valid sign-in. It is surfaced honestly (audit `mcp_server.oauth.obo_cache_flushed`, response `effect: cache_flush_remints`) so it is never mistaken for cutting access.
- Per-server revocation in the `oauth_user` sense does not exist for `oauth_obo` — the credential is issuer-scoped and IdP-governed. Revoke at the IdP.
> **Interim for Entra without OBO:** if you don't want host-side minting, admin consent + `preAuthorizedApplications` on each MCP app registration removes the second consent prompt for the plain `oauth_user` flow too (a tenant-config change, no Turnstone code). Tracked in issue #682. It does not remove the per-server connect clicks or per-(user, server) token custody — that is what `oauth_obo` is for.
---
## Lifecycle
1. **First tool call** for a user against an `oauth_user` MCP server: pool dispatch finds no stored token, returns `mcp_consent_required` to the agent. Dashboard renders an inline "Connect" action card.
@@ -75,7 +128,7 @@ Keep this in `config.toml` rather than environment variables. An in-process LLM
4. **Step-up scope**: when a tool call hits `403` with `WWW-Authenticate: error="insufficient_scope"`, Turnstone emits `mcp_insufficient_scope` with the parsed scope set; the dashboard offers a "Connect with additional scopes" affordance that opens `/v1/api/mcp/oauth/start?server=<name>&scopes=<extra>` so the union of original + new scopes flows into the AS authorize request.
5. **User revoke** (settings modal): `DELETE /v1/api/mcp/oauth/connections/{server_name}` runs the authoritative local delete + best-effort RFC 7009 upstream revoke (fire-and-forget, capped at 256 concurrent in-flight tasks).
5. **User revoke** (settings modal): `DELETE /v1/api/mcp/oauth/connections/{server_name}` runs the authoritative local delete + best-effort RFC 7009 upstream revoke (fire-and-forget, capped at 256 concurrent in-flight tasks). `oauth_obo` servers are excluded: their rows are mint cache, not consents — deleting one only forces a re-mint — so the connections list hides them and the endpoint refuses them with `409` (revocation for sign-in passthrough happens at the identity layer: unlink the identity or revoke at the IdP).
6. **Admin bulk-revoke** (Phase 9): `POST /v1/api/admin/mcp-servers/{name}/bulk-revoke` drops every user's token for the server. Upstream RFC 7009 revoke is intentionally **not** attempted in bulk (avoids N upstream HTTP calls per admin click); tokens at the AS expire naturally. Use the per-user revoke endpoint if you need guaranteed upstream invalidation.
@@ -97,10 +150,13 @@ Additional indicators (circuit-breaker state, encryption-key mismatch) are expos
| From | To | What happens |
|---|---|---|
| `none` / `static``oauth_user` | — | New code path activates for this server. Existing static headers (if any) are no longer sent. Users must authorize on first use. |
| `oauth_user``none` / `static` | — | Existing `mcp_user_tokens` rows are **orphaned** — inert without a matching `auth_type`. Use admin bulk-revoke to drop them, or let them expire. Switching back to `oauth_user` later re-activates the orphaned rows if they haven't been deleted. |
| `oauth_user``none` / `static` | — | Existing `mcp_user_tokens` rows are **deleted**: the tokens are bound to the auth model + URL active at consent time, and rows left behind could silently rebind if a row with the old name/URL reappears. Switching back to `oauth_user` later starts clean — users re-consent on next use. This is **not reversible**; the AS-side grants are untouched (revoke upstream via the AS if needed). |
| OAuth `client_id` or `client_secret` rotated | — | Existing tokens may stop refreshing if the AS treats them as bound to the previous client. Bulk-revoke after rotation. |
| `oauth_user``oauth_obo` | — | The per-user rows are **deleted** on the flip (they mean different things: per-server AS refresh tokens vs. minted cache). `oauth_audience` and `oauth_scopes` mean different things in each model (a resource indicator vs. an IdP app identifier; AS-consent scopes vs. an rfc8693 exchange scope), so on a flip they **never carry** — each is taken from the request for the target model or set NULL. The admin console clears these fields when you change the auth type, so re-enter the correct values for the new mode; via the API, supply them explicitly (a flip into `oauth_obo` with no `oauth_audience` is rejected, and a non-empty `oauth_scopes` under the `entra` profile is rejected since that leg pins `<audience>/.default`). |
| `oauth_obo``none` / `static` | — | Minted cache rows are deleted. |
| `oauth_obo` **audience**, **URL**, or **`oauth_scopes`** changed | — | Minted cache rows are **deleted** (tokens are bound to the audience/URL/scopes at mint time), forcing a fresh mint — so an audience or scope narrowing takes effect immediately, not at token expiry. |
The orphan-by-default behavior is chosen so switching back to `oauth_user` is non-destructive. Bulk-revoke is the explicit cleanup path.
Every transition that changes what a stored row *means* deletes the rows outright — a stale consent or minted token must never be served under new semantics. There is no orphan-and-reactivate path.
---
@@ -113,5 +169,9 @@ The orphan-by-default behavior is chosen so switching back to `oauth_user` is no
| `mcp_oauth_url_insecure` | MCP server URL is `http://` (not `https://`) on a non-loopback host | Use `https://`. Per-user bearers must not transit cleartext. |
| Tools fail in scheduled / Discord / Slack runs | OAuth-MCP requires browser-based consent | Users must pre-consent via the web UI. Phase 9 dashboard badge surfaces deferred consents from these runs on next login. |
| Circuit breaker open repeatedly | Transport-level errors on the MCP server (DNS, TLS, 5xx) | Check the per-server error pill; auth errors do not trip the breaker. |
| **`oauth_obo`**: every tool call fails, log shows `obo_misconfigured` | Server row has no Audience, or `obo_grant_profile` is unset/unknown | Set the Audience on the server row; set `[oidc] obo_grant_profile` to `entra` or `rfc8693`. |
| **`oauth_obo`**: `obo_mint_rejected` with `AADSTS65001` | Turnstone's app lacks the (admin-consented) delegated grant to this MCP app — often admin consent that didn't propagate | Grant + admin-consent the delegated permission for this resource; verify it shows *Granted*. See the Entra gotcha above. |
| **`oauth_obo`**: "Sign in to Turnstone again" on one server | Captured credential missing/rejected, or a Conditional Access challenge | User re-logs into Turnstone (re-captures the credential). If it persists, check the IdP grant / CA policy. |
| **`oauth_obo`**: tools don't appear at all for a user | User has not signed in since `capture_user_credential` was enabled (no credential captured) | User logs out and back in via OIDC so the refresh credential is captured. |
See also: `docs/operations/mcp-oauth-headless.md` for the cron / channel-driven run caveat.
+35 -5
View File
@@ -26,15 +26,40 @@ Each memory has three dimensions:
### Memory scopes
| Scope | Visibility |
|--------------|-----------------------------------------------------------|
| `global` | Visible to all workstreams and users |
| `workstream` | Visible only within the originating workstream |
| `user` | Follows the authenticated user across workstreams |
| Scope | Visibility |
|---------------|-----------------------------------------------------------------|
| `global` | Visible to all workstreams and users |
| `workstream` | Visible only within the originating workstream |
| `user` | Follows the authenticated user across workstreams |
| `coordinator` | Coordinator sessions only; follows the user across coordinators |
A memory's identity is the tuple `(name, scope, scope_id)`. Saving a memory
with the same identity upserts -- updating content while preserving the ID.
### Coordinator scope
Coordinator sessions are isolated to a single scope: `coordinator`, keyed by
the coordinator's creator `user_id`. It is durable -- every coordinator
session the same user runs (including concurrent ones) shares one
orchestration namespace, so procedures and lessons survive close/reopen.
Isolation is bidirectional and enforced by session kind, not by secrecy of
the scope id:
- A coordinator session can read and write **only** `coordinator`-scope rows.
It never sees `global`/`workstream`/`user` memories, so content written by
interactive sessions (which routinely ingest untrusted MCP/attachment
output) cannot reach a coordinator's system message.
- Interactive sessions -- including a coordinator's own children, which share
its `user_id` -- are rejected from the `coordinator` scope on every memory
action. Children cannot plant rows the parent coordinator would read.
- The REST memory API (`/v1/api/memories`) does not accept the `coordinator`
scope at all; the scope is written exclusively through a coordinator
session's own memory tool.
Coordinator sessions require an authenticated user identity -- an anonymous
coordinator cannot be constructed, so the scope id is always a real user.
### BM25 relevance injection
On every conversation turn, the system:
@@ -50,6 +75,11 @@ This means the model always has its most relevant memories available without
explicit recall -- but can still use `memory(action='search')` for deeper
lookup.
The persona memory lever gates this pathway: a workstream whose persona
turns memory off receives no relevance injection at all -- the steps
above run only when memory is enabled for the session. See
[Personas](personas.md).
### Nudges
The metacognition layer can nudge the model to save memories at appropriate
+46 -9
View File
@@ -41,6 +41,7 @@ are set.
| `TURNSTONE_OIDC_PASSWORD_ENABLED` | No | `true` | Set to `false` to hide the password form and block all username/password logins (including admin). API tokens continue to work. |
| `TURNSTONE_OIDC_REDIRECT_BASE` | Yes | — | Externally-reachable origin for the OIDC redirect URI (e.g. `https://app.example.com`). Without this, OIDC will refuse to start. The previous Host-header fallback was unsafe under permissive reverse proxies. |
| `TURNSTONE_OIDC_TRUSTED_ENDPOINT_HOSTS` | No | — | Comma-separated list of additional hostnames whose endpoints the IdP discovery document is allowed to reference. See [Cross-host endpoints](#cross-host-endpoints). |
| `TURNSTONE_OIDC_ALLOW_PRIVATE_NETWORK` | No | `false` | Allow the issuer (and its discovered endpoints) to resolve to private/internal addresses — needed for a self-hosted IdP on an internal network. See [Self-hosted and internal IdPs](#self-hosted-and-internal-idps). |
All four required fields — issuer, client ID, client secret, and
`TURNSTONE_OIDC_REDIRECT_BASE` — must be set. If any are missing OIDC
@@ -76,17 +77,17 @@ IdP from redirecting the token-exchange POST (which carries
being aimed at internal services.
A few public IdPs legitimately split endpoints across hostnames. Google
is the canonical example:
and Microsoft Entra ID are the canonical examples:
| Field | Hostname |
|-------|----------|
| issuer | `accounts.google.com` |
| token_endpoint | `oauth2.googleapis.com` |
| jwks_uri | `www.googleapis.com` |
| userinfo_endpoint | `openidconnect.googleapis.com` |
| IdP | Issuer host | Cross-host endpoint(s) |
|-----|-------------|------------------------|
| Google | `accounts.google.com` | `oauth2.googleapis.com`, `www.googleapis.com`, `openidconnect.googleapis.com` |
| Microsoft Entra | `login.microsoftonline.com` | `graph.microsoft.com` (userinfo) |
Google's set is built in — operators using `https://accounts.google.com`
need no extra configuration.
Both sets are built in — operators using `https://accounts.google.com` or
`https://login.microsoftonline.com/<tenant>/v2.0` need no extra
configuration. (Entra's discovery document advertises `userinfo_endpoint`
on `graph.microsoft.com`, distinct from the issuer host.)
For other IdPs whose discovery document references a non-issuer host,
extend the allow-list explicitly:
@@ -99,6 +100,40 @@ The same scheme / no-userinfo / SSRF rules apply to allow-listed hosts —
this knob only relaxes the same-origin check, not the security gates.
Each entry is a hostname (no scheme, no path).
### Self-hosted and internal IdPs
By default Turnstone refuses an issuer whose hostname resolves to a
private or internal address:
```
OIDCError: endpoint URL resolves to non-public address (10.0.0.5): https://auth.example.site
```
This is SSRF hardening, not a licensing or product restriction: the OIDC
flow makes server-side HTTP requests (discovery, JWKS, token exchange),
and refusing non-public destinations keeps a mistyped or maliciously
steered issuer from aiming those fetches at internal services. For a
self-hosted IdP (Keycloak, Authentik, Dex, …) on a private network,
opt in explicitly in `config.toml`:
```toml
[oidc]
allow_private_network = true
```
or via `TURNSTONE_OIDC_ALLOW_PRIVATE_NETWORK=true` (the env var wins
when both are set).
The opt-in admits private-range (RFC 1918), unique-local, CGNAT
(100.64/10 — tailnets), and loopback addresses. Link-local, multicast,
and reserved ranges stay refused even with the opt-in — cloud metadata
services (169.254.169.254) live there, and no legitimate IdP does. The
HTTPS requirement and the same-origin endpoint checks are unaffected.
This knob only affects the login-flow IdP configured here. OAuth
endpoints advertised by remote MCP servers are untrusted input and are
always held to the strict public-address rule.
### config.toml alternative
```toml
@@ -111,6 +146,8 @@ provider_name = "Google"
role_claim = "groups"
password_enabled = true
redirect_base = "https://app.example.com"
# Self-hosted IdP on an internal network (see "Self-hosted and internal IdPs")
allow_private_network = false
[oidc.role_map]
admin = "builtin-admin"
+173
View File
@@ -0,0 +1,173 @@
# Personas
A **persona** is a named, reusable bundle attached to a workstream **at
creation** that controls how its system message is composed and what
capability envelope it runs with. Personas answer a recurring operational
complaint: the default composition primes every session for heavy tool use,
and there was no per-workstream dial to launch a "just write prose" or
"evidence-first research" session.
A persona is exactly four levers — no more:
| Lever | What it does |
|---|---|
| **Base prompt** | Replaces the BASE module of the composed system message. *Only* BASE: ENV, CONTEXT, TOOLS, and POLICIES keep composing, so mandatory [prompt policies](governance.md) ride on top of every persona. Built-in personas source their prose from a repo file; operator personas store it inline — see [Where persona prompts live](#where-persona-prompts-live). |
| **Tool visibility** | Which tools the session advertises. Tri-state: *unrestricted* (tracks tool growth and MCP catalogs), *no tools* (the TOOLS prompt block self-suppresses and zero definitions go on the wire), or an *exact set* of names. Including `tool_search` in a set makes it **soft** — tools the model discovers through search join the visible set; omitting it makes the set **hard** (the search pathway is disabled entirely). On commercial providers a soft set costs one prompt-cache re-prime per `tool_search` expansion, since each expansion rewrites the wire tool set and recomposes the prompt. |
| **MCP** | Whether the workstream talks to MCP at all. **Session-wide**: off means no MCP tools for the persona's own hands *or* for in-process task agents, no resource/prompt catalogs, and no listener registrations. This lever expresses infrastructure intent, not behavior shaping. |
| **Memory** | Whether the persona's **own hands** get memory: recalled-memory injection into the prompt, memory-directed metacognitive nudges, and the `memory` tool. Task agents keep their own envelope, and compaction spill/markers are session mechanics that are never persona-gated. An exact tool set that hides `memory` also mutes those nudges, and the compaction-resume pointer follows `recall`'s visibility. |
Visibility is behavior shaping, **not** a security boundary: any tool call
that does reach the wire still clears the same approval, judge, and policy
machinery as always. RBAC and tool policies remain the enforcement layers.
## Snapshot semantics — resolve once, stamp forever
The persona is resolved **once**, at workstream creation, and stamped into
`workstream_config` as five keys (`persona`, `persona_prompt`,
`persona_tools`, `persona_mcp`, `persona_memory`). From then on the session
reads only the stamp:
- **Editing or archiving a persona never changes an existing workstream.**
Rehydrate, resume, and post-compaction resume all run from the stamp.
A mid-session REPL `/resume` adopts the target workstream's stamp for
prompt, tools, and memory; for the MCP lever it can only narrow in
place — adopting an MCP-off stamp drops the live MCP surface, while
adopting an MCP-on stamp into a session whose persona dropped MCP at
construction is refused with an error telling you to reopen the
workstream fresh.
- A workstream outlives its persona — an archived persona keeps labelling
the workstreams stamped with it.
- A partial or unparseable stamp is treated as corruption: session
construction fails loudly rather than silently falling back to a default
envelope the operator never chose.
- Workstreams created before personas existed carry no stamp and keep
legacy behavior, byte-identical to the `engineer` / `orchestrator`
defaults below — with one exception: pre-1.7 workstreams that had
`creative_mode` set are converted by migration `063` into full
`writer` stamps, so they resume as writing sessions rather than as
legacy defaults.
- Forking (`resume_ws` on create) resumes the source's stamped persona; the
fork does not re-resolve.
## Seed personas
Migration `063` seeds six personas. The two per-kind **defaults** carry no
overrides at all, so a zero-touch launch behaves exactly as it did before
personas existed:
| Persona | Kind | Base prompt | Tools | MCP | Memory |
|---|---|---|---|---|---|
| `engineer` *(default)* | interactive | stock | unrestricted | on | on |
| `orchestrator` *(default)* | coordinator | stock | unrestricted | on | on |
| `scribe` | interactive | custom (faithful structuring of given material) | none | off | off |
| `researcher` | interactive | custom (evidence-first) | `read_file`, `search`, `web_fetch`, `web_search`, `recall`, `memory`, `tool_search` (soft) | off | on |
| `writer` | interactive | custom (creative writing partner — replaces the removed `/creative`) | none | off | on |
| `executive` | coordinator | custom (delegate, interrogate plans, judge outcomes) | spawn/inspect/lifecycle tools plus `memory`: `spawn_workstream`, `spawn_batch`, `send_to_workstream`, `wait_for_workstream`, `inspect_workstream`, `list_workstreams`, `list_nodes`, `close_workstream`, `cancel_workstream`, `memory` (hard) | off | on |
Notes:
- `scribe` turns memory off deliberately: recalled memories would
contaminate faithful summarization with unrelated context.
- `researcher`'s set is soft (includes `tool_search`): it starts with
read and evidence tools but can pull in others on demand — e.g. load
`bash` to run a snippet and verify a calculation. It is evidence-first,
not sandboxed; any escalated tool still hits the normal approval path.
- Coordinator sessions do not merge MCP today, so the MCP lever on
coordinator personas is forward-compatible bookkeeping; it bites on
interactive workstreams.
## Where persona prompts live
Prompt source is explicit in the persona row — two nullable columns, never both empty:
| `base_prompt_file` | `base_prompt` | Meaning |
|---|---|---|
| set (e.g. `scribe.md`) | — | **built-in**: prose lives in `prompts/personas/<file>`, code-owned and PR-reviewed |
| set | set | built-in with an **operator override** layered on top (the inline text wins) |
| — | set | **operator** persona, inline prose |
A `CHECK` forbids the both-empty row, so resolution is a plain coalesce —
`base_prompt ?? load(base_prompt_file)` — with no implicit "inherit the default"
branch in application logic. `base_prompt_file` is set only by the migration/code
(the admin API never exposes it): it marks a persona as built-in and blocks
archive, so `engineer` and `orchestrator` can't be removed. To customise a
built-in, set `base_prompt` on it (clear it to revert), or create your own persona.
The resolved prompt is **frozen into the workstream at creation** — later edits to
a built-in's file or an operator's row never change a running workstream; only new
ones pick up the change. "No persona" is not a state: every workstream is stamped,
and an empty `persona=` resolves to the kind's `is_default` (`engineer` /
`orchestrator`).
## Choosing a persona
Every creation surface takes an optional persona; empty always means the
kind's default (or plain legacy behavior on a database with no personas
seeded):
- **Web/console**: the persona select on the console launcher, the server
webui's new-workstream dialog, and the dashboard composer. Selecting a
persona requires **no** `persona.*` permission — the picker feed
(`GET /v1/api/personas`) is authenticated-only and returns display fields.
- **API/SDK**: `CreateWorkstreamRequest.persona` (Python:
`create_workstream(persona=...)`; TypeScript: `{ persona: ... }`).
- **CLI**: `turnstone --persona <name>`. Unknown or disabled names error at
startup. `--resume` ignores `--persona` and adopts the resumed
workstream's stamp.
- **Coordinator spawn**: `spawn_workstream` / `spawn_batch` take a
`persona` argument, validated when the coordinator prepares the spawn
and re-checked by the node that creates the child (children are always
interactive-kind). Omitted means the interactive **default** — a child
never inherits its parent coordinator's persona.
- **Sub-agents**: `task_agent` takes a `persona` argument setting the
sub-agent's identity and capability envelope (resolved against
interactive-kind personas, frozen into the task at prep). Omitted keeps
the default autonomous task-agent identity — never the parent's persona.
## How agents discover personas
Agents are told, not expected to guess: the live persona list (enabled,
interactive-kind — children and sub-agents are always interactive) is
injected into the `persona` parameter description of `task_agent`,
`spawn_workstream`, and `spawn_batch` whenever the session's tool surface
is rendered — session start, MCP catalog change, model-registry reload.
Each entry carries the name, the default marker, and the persona's
one-line description so the model can pick by purpose (descriptions drop
out past 25 personas; the name list always enumerates completely).
A persona created after that render is still reachable — pass its name.
Every resolve failure enumerates the names currently valid for the kind,
so a stale list (or a typo) self-corrects on the next attempt.
Resolution is forgiving on all surfaces (they share one rule):
- names match case-insensitively (`Writer` resolves `writer`);
- an input that uniquely matches a persona's **display name**
(case-insensitive, among the kind's enabled personas — display names are
not unique, and a same-label persona of another kind neither blocks nor
wins) resolves to that persona; an ambiguous match errors, listing the
candidate slugs;
- whatever variant matched, the stamped identity, approval chrome, and
wire always carry the canonical `name` slug.
## Authoring (console)
Personas are managed in the console's **Manage → Governance → Personas**
tab. The admin shelf exposes exactly the four levers plus the kind
list, the default marker, and archive. Rules:
- `name` is an immutable lowercase slug — and the identifier agents and
the CLI launch the persona by (`persona=` on the spawn tools,
`--persona` on the CLI); the create shelf says so under **Name**.
`display_name` is a list label, editable any time, and deliberately
not an identifier (a unique display name happens to resolve, as a
forgiveness fallback — don't design workflows around it).
- Exactly one default per kind, storage-enforced: flipping the flag on a
successor demotes the incumbent atomically, defaults are single-kind,
and a default cannot be archived.
- **Archive only** — there is no delete verb, so every stamped
workstream's provenance stays explicable.
RBAC: `persona.create` / `persona.read` / `persona.write` gate the admin
CRUD (`/v1/api/admin/personas`); all three are granted to `builtin-admin`
by migration `063`, and other roles opt in via role permission overrides.
+2 -2
View File
@@ -69,7 +69,7 @@ Both `TurnstoneServer` (sync) and `AsyncTurnstoneServer` (async) expose:
|----------|--------|---------|
| **Workstreams** | `list_workstreams()` | `ListWorkstreamsResponse` |
| | `dashboard()` | `DashboardResponse` |
| | `create_workstream(*, name, model, auto_approve, skill, initial_message, attachments)` | `CreateWorkstreamResponse` |
| | `create_workstream(*, name, model, auto_approve, skill, persona, initial_message, attachments)` | `CreateWorkstreamResponse` |
| | `close_workstream(ws_id)` | `StatusResponse` |
| **Attachments** | `upload_attachment(ws_id, filename, data, *, mime_type=...)` | `UploadAttachmentResponse` |
| | `list_attachments(ws_id)` | `ListAttachmentsResponse` |
@@ -100,7 +100,7 @@ Both `TurnstoneConsole` (sync) and `AsyncTurnstoneConsole` (async) expose:
| | `workstreams(*, state, node, search, sort, page, per_page)` | `ClusterWorkstreamsResponse` |
| | `node_detail(node_id)` | `NodeDetailResponse` |
| | `snapshot()` | `ClusterSnapshotResponse` |
| | `create_workstream(*, node_id, name, model, initial_message, skill)` | `ConsoleCreateWsResponse` |
| | `create_workstream(*, node_id, name, model, initial_message, skill, persona)` | `ConsoleCreateWsResponse` |
| **Schedules** | `list_schedules()` | `ListSchedulesResponse` |
| | `create_schedule(*, name, schedule_type, initial_message, ...)` | `ScheduleInfo` |
| | `get_schedule(task_id)` | `ScheduleInfo` |
+17
View File
@@ -54,6 +54,23 @@ When a per-model override is `NULL` (empty in the UI), the global default is
used. Switching models via `/model <alias>` re-resolves sampling parameters
from the new model's overrides or global defaults.
### Responses output controls (per-model)
Models whose capability table declares Responses output controls expose two
additional fields in the Models create/edit shelf:
| Field | Stored capability | Values | Effect |
|-------|-------------------|--------|--------|
| Output verbosity | `verbosity` | `low`, `medium`, `high` | Controls answer length independently of reasoning effort. |
| Reasoning mode | `reasoning_mode` | `standard`, `pro` | Selects standard or higher-compute Pro execution without changing the model ID. |
An empty selection means provider default and omits the capability key. Known
GPT-5.6 models inherit support from the built-in table without persisting
redundant support flags. An OpenAI-compatible model pinned to the Responses API
can opt in with the `supports_verbosity` and `supports_pro_mode` capability
tiles. Chat Completions and non-Responses providers do not surface or submit
these controls.
**Removed settings:** `model.name` and `model.context_window` have been removed
from ConfigStore. Model names and context windows are now configured per-model
in the Models tab. A startup warning is logged if these keys appear in
+6 -2
View File
@@ -244,7 +244,10 @@ const client = new TurnstoneServer({
### Node Bootstrap Flow
1. Node starts, connects to shared database (plain connection)
2. Discovers console URL from `services` table
2. Discovers the console URL from the `services` table — or honors an explicit
`TURNSTONE_CONSOLE_URL` (a bare-metal node outside the compose network can't
resolve the in-cluster `console` name, so it points this at the console's
published ACME endpoint)
3. Fetches CA root cert from `http://console/acme/ca.pem` (plain HTTP, TOFU)
4. Requests a service cert via ACME (plain HTTP, JWS-signed). The cert's
primary domain / SAN is the node's **advertised host** (the host of
@@ -291,7 +294,8 @@ cert's SANs don't include the dialed name.
The console registers itself in the `services` table on startup. If the console
hasn't started or the registration expired (1 hour TTL), nodes can't discover
it. Use `--console-url` explicitly.
it. Set `TURNSTONE_CONSOLE_URL` to a reachable console address (this is also how
a bare-metal node that can't resolve the in-cluster `console` name enrolls).
### Browser HTTPS to the console
+77 -18
View File
@@ -1,6 +1,6 @@
# Tools Reference
turnstone exposes 16 built-in tools plus any number of external MCP tools to the
turnstone exposes 17 built-in tools plus any number of external MCP tools to the
LLM via the OpenAI function-calling interface. Built-in tools are defined as JSON
files under `turnstone/tools/` and loaded at startup by `turnstone/core/tools.py`.
MCP tools are discovered from configured MCP servers at startup by
@@ -28,13 +28,19 @@ schema plus turnstone-specific metadata keys:
}
```
**Metadata keys** (stripped before sending the schema to the model):
**Metadata keys** (stripped before sending the schema to the model; the full
set lives in `_META_KEYS` in `turnstone/core/tools.py`):
| Key | Type | Meaning |
|----------------|------|---------|
| `task_agent` | bool | Tool is available to task sub-agents. |
| `auto_approve` | bool | Tool runs without user confirmation (read-only, safe operations). |
| `primary_key` | str | When the model sends a bare string instead of JSON args, map it to this parameter name. |
| Key | Type | Meaning |
|------------------|------|---------|
| `task_agent` | bool | Tool is available to task sub-agents. |
| `coordinator` | bool | Tool is available to coordinator sessions. Without `interactive: true` alongside it, this reads as coord-only and the tool is stripped from interactive sessions. |
| `interactive` | bool | Opt a `coordinator: true` tool back into interactive sessions (dual-kind tools like `memory`). |
| `auto_approve` | bool | Tool runs without user confirmation (read-only, safe operations). |
| `primary_key` | str | When the model sends a bare string instead of JSON args, map it to this parameter name. |
| `kind_variants` | dict | Per-kind description / parameter-schema overlays so each session kind sees only the surface it can use (see `memory.json`). |
| `cwd_note` | str | Sentence appended to the description at session build time with `{working_dir}` substituted — declare on tools whose semantics depend on the process working directory (see `bash.json`, `apply_cwd_context`). |
| `workspace_note` | str | Companion sentence naming the operator-configured workspace directory, `{workspace_dir}` substituted; dropped when no workspace is configured. |
---
@@ -44,10 +50,10 @@ schema plus turnstone-specific metadata keys:
| Name | Description |
|---------------------|-------------|
| `TOOLS` | All 28 loaded built-in tool definitions (interactive + coordinator union). Sessions send a kind-specific subset (`INTERACTIVE_TOOLS` or `COORDINATOR_TOOLS`). |
| `TOOLS` | All 29 loaded built-in tool definitions (interactive + coordinator union). Sessions send a kind-specific subset (`INTERACTIVE_TOOLS` or `COORDINATOR_TOOLS`). |
| `TASK_AGENT_TOOLS` | Tools with `task_agent: true` -- available to task sub-agents. Includes write operations. |
| `TASK_AUTO_TOOLS` | Set of all tool names with `auto_approve: true` -- used by task-agent sub-sessions to skip confirmation for matching available tools. |
| `BUILTIN_TOOL_NAMES`| Frozenset of all 28 built-in tool names (interactive + coordinator union). Used by tool search to distinguish always-on tools from deferrable MCP tools. |
| `BUILTIN_TOOL_NAMES`| Frozenset of all 29 built-in tool names (interactive + coordinator union). Used by tool search to distinguish always-on tools from deferrable MCP tools. |
| `PRIMARY_KEY_MAP` | Dict mapping tool name to its `primary_key` parameter name. |
---
@@ -65,7 +71,7 @@ Tool execution follows a three-phase pipeline inside `ChatSession._execute_tools
- Parses the JSON arguments (with fallback for malformed JSON).
- If JSON parsing fails entirely, uses `PRIMARY_KEY_MAP` to map a bare string
to the correct parameter.
- Dispatches to the matching `_prepare_{func_name}()` handler. There are 16
- Dispatches to the matching `_prepare_{func_name}()` handler. There are 17
built-in tools plus `tool_search` (synthetic, client-side BM25 fallback) and
the generic `_prepare_mcp_tool()` handler for MCP tools.
- Validates arguments and builds a preview dict containing:
@@ -125,6 +131,9 @@ Each item's `execute` callable is invoked:
- `web_fetch` -- fetches a URL (SSRF-protected, but makes network requests)
- `web_search` -- web search via self-hosted SearxNG (makes network requests)
- `task_agent` -- spawns an autonomous sub-agent
- `open_preview` -- **URL targets only** (network access, gated like `web_fetch`);
file-path and `attachment:` targets are local reads and run unprompted like
`read_file`
Note: The JSON schema metadata key `auto_approve` controls membership in
`TASK_AUTO_TOOLS` (used for task agent sub-sessions). The actual runtime
@@ -157,6 +166,7 @@ Every tool defines a `primary_key`. The mapping is:
| `search` | `query` |
| `web_fetch` | `url` |
| `web_search` | `query` |
| `open_preview` | `target` |
| `task_agent` | `prompt` |
| `memory` | `name` |
| `recall` | `query` |
@@ -285,7 +295,7 @@ Fetch a URL and extract specific information from it.
| `url` | string | yes | The URL to fetch (must start with `http://` or `https://`). |
| `question` | string | yes | What to extract or answer from the page content. |
- **What it does**: Fetches the URL, strips HTML to plain text, and uses the LLM to extract the answer to the question from the page content. Protected against SSRF (blocks private/internal IPs).
- **What it does**: Fetches the URL, strips HTML to plain text, and uses the LLM to extract the answer to the question from the page content. Every redirect hop is SSRF-screened before it is requested. Private/internal addresses are refused by default; enable `tools.allow_private_network` (console Settings → Tools) to make them approvable for self-hosted setups whose services live on the local network — the approval prompt marks such requests, and a public site redirecting into private space is refused regardless.
- **Auto-approve**: No -- requires user confirmation (makes network requests).
- **Agent availability**: `task_agent`.
@@ -345,6 +355,39 @@ It reports the score scale, whether the endpoint cleanly separates relevant from
---
### open_preview
Show the user rich content in a preview pane beside the conversation.
| Parameter | Type | Required | Description |
|-----------|--------|----------|-------------|
| `target` | string | yes | An http(s) URL, a file path, or `attachment:<id>` for a file attached to the conversation. |
| `kind` | string | no | Rendering override: `web`, `pdf`, `image`, `table`, `text`, or `markdown`. Detected from the content when omitted. |
| `title` | string | no | Pane header title. Defaults to the page title, filename, or URL. |
- **What it does**: Resolves the target to bytes (URLs fetch through the same
SSRF-guarded path as `web_fetch`, screened per redirect hop, honoring the
same `tools.allow_private_network` opt-in), classifies the
content, stores it content-addressed against the workstream, and opens the
frontend preview pane beside the conversation: web pages render in a fully
sandboxed iframe (no scripts, opaque origin), PDFs in the browser viewer,
images inline, CSV/TSV/JSON as a sortable table, text/markdown rendered. A
previewed web page loads none of its remote images or styles by default, so
opening it never reveals the viewer to the page's site; a toggle in the pane
header turns remote content back on for that preview. The
model receives only a one-line confirmation — to reason about content, use
`web_fetch` / `read_file` instead. Preview content is size-capped per kind
(pages 4 MB, PDFs 32 MB, images 4 MB, tables 2 MB, text 512 KB) and GC'd
with the workstream.
- **Auto-approve**: URL targets require confirmation (network access); file
paths and `attachment:` targets run unprompted (local reads).
- **Agent availability**: interactive sessions only (not `task_agent`, not
coordinators).
- **Surfaces**: the pane renders in the web UI (standalone and console). The
CLI prints the confirmation line only — there is no terminal pane.
---
## Agent
The tool name uses the `_agent` suffix — bare `task` collides with
@@ -545,6 +588,7 @@ pre-configure skills at workstream creation.
| `search` | File Ops | Yes | Yes | `query` |
| `web_fetch` | Info | No | Yes | `url` |
| `web_search` | Info | No | Yes | `query` |
| `open_preview`| Info | URL: no; path/attachment: yes | No | `target` |
| `task_agent` | Agent | No | No | `prompt` |
| `memory` | Memory | Yes | No | `name` |
| `recall` | Memory | Yes | No | `query` |
@@ -580,6 +624,11 @@ Tool search uses the best available mechanism for each provider:
`_exec_tool_search()` runs a pure-Python BM25 index over tool names and
descriptions, then expands the matched tools into the visible set.
A persona with a tool-visibility set overrides this selection: any exact
set forces tool search into the client-side BM25 mechanism (tier 3)
regardless of provider, and a **hard** set — one whose visible tools omit
`tool_search` — disables tool search entirely.
### Configuration
Tool search is configured in `config.toml` under the `[tools]` section:
@@ -649,7 +698,7 @@ MCP-compatible service.
3. **Schema conversion**: Each MCP tool's `inputSchema` is converted to OpenAI
function-calling format. The tool name is prefixed: `mcp__{server}__{tool}`.
4. **Merging**: MCP tools are appended after the 16 built-in tools via
4. **Merging**: MCP tools are appended after the 17 built-in tools via
`merge_mcp_tools()`. Built-in tools appear first, giving them natural LLM priority.
When dynamic tool search is active, MCP tools are deferred rather than directly
visible -- the model discovers them via search as needed (see
@@ -736,7 +785,10 @@ MCP tool lists stay up-to-date without restart through two mechanisms:
1. **Push notifications** -- MCP servers that declare `tools.listChanged: true` in
their capabilities send `notifications/tools/list_changed` when their tool list
changes. `MCPClientManager` registers a `message_handler` on each `ClientSession`
that triggers an immediate refresh for that server.
that triggers an immediate refresh for that server (debounced per server and
notification kind, and run off the receive loop). A refresh that fails while
the connection stays up is retried automatically on the next health-loop tick
until one completes.
2. **Manual** -- `/mcp refresh` re-fetches tools from all servers immediately.
`/mcp refresh <server>` targets a single server. If a server has disconnected,
@@ -744,6 +796,10 @@ MCP tool lists stay up-to-date without restart through two mechanisms:
same controls (refresh / reconnect buttons per server) for cluster-wide
fan-out.
Reconnects (health-loop, dispatch-driven, or operator-forced) always end in a
full catalog rediscovery, so a server that changed its tools while disconnected
comes back current.
When tools change, `MCPClientManager` rebuilds its merged tool list using copy-on-write
(new list/dict objects assigned atomically) and notifies all active `ChatSession`
instances via registered listener callbacks. Each session rebuilds its `_tools`,
@@ -814,13 +870,16 @@ catalog.
### Refresh
Resource lists stay current through the same three-tier mechanism as tool lists:
Resource lists stay current through the same mechanisms as tool lists:
1. **Push** -- Servers declaring `resources.listChanged: true` send
`notifications/resources/list_changed`, triggering an immediate refresh.
2. **Periodic** -- Servers without push are polled on the configured refresh
interval (default 4 hours, same timer as tools).
3. **Manual** -- `/mcp refresh` re-fetches resources alongside tools.
`notifications/resources/list_changed`, triggering an immediate refresh
(with the same failed-refresh retry on the health-loop tick).
2. **Manual** -- `/mcp refresh` re-fetches resources alongside tools.
Servers without push support are refreshed whenever they reconnect (every
reconnect ends in full rediscovery) or when an operator refreshes manually;
there is no periodic polling.
---
+56
View File
@@ -0,0 +1,56 @@
{
"defaults": {
"n_runs": 3
},
"cases": [
{
"id": "search-first",
"skill": {
"name": "search-first",
"content": "# Search First\n\nBefore answering ANY question about where something lives in the codebase, you MUST call the `search` tool first. Never answer from memory."
},
"user_prompt": "Where is JWT token validation implemented in this project?",
"expected_actions": [{ "tool": "search" }],
"match_mode": "ordered_subset",
"max_turns": 4
},
{
"id": "test-after-edit",
"skill": {
"name": "test-after-edit",
"content": "# Test After Edit\n\nAfter editing or writing ANY file, you MUST run the test suite with `python -m pytest` via bash before you finish. Do not report done until tests have run."
},
"user_prompt": "Add a function `clamp(x, lo, hi)` that clamps x to [lo, hi] in utils.py.",
"setup": {
"files": {
"utils.py": ""
}
},
"expected_actions": [
{ "tool": "write_file" },
{ "tool": "bash", "args_pattern": { "command": "pytest" } }
],
"match_mode": "ordered_subset",
"max_turns": 8
},
{
"id": "changelog-update",
"skill": {
"name": "changelog-update",
"content": "# Changelog Discipline\n\nWhenever you modify a file, you MUST also append a one-line entry to CHANGELOG.md describing the change in the same task."
},
"user_prompt": "Fix the off-by-one so pager.py shows the last page. Edit pager.py.",
"setup": {
"files": {
"pager.py": "def last_page(total_items, per_page):\n # off-by-one: drops the final partial page\n return total_items // per_page\n",
"CHANGELOG.md": "# Changelog\n"
}
},
"expected_actions": [
{ "tool": "edit_file", "args_pattern": { "path": "CHANGELOG.md" } }
],
"match_mode": "subset",
"max_turns": 8
}
]
}
+9
View File
@@ -0,0 +1,9 @@
__pycache__/
.venv/
*.db
*.db-wal
*.db-shm
.ruff_cache/
.pytest_cache/
.mypy_cache/
uv.lock
+282
View File
@@ -0,0 +1,282 @@
# Understone
A small, multiplayer, BBS-style **ANSI door game** served over the Model
Context Protocol (MCP). It is a text RPG in the spirit of *Legend of the Red
Dragon* — explore an overworld of box-drawing maps, fight wandering monsters,
shop and rest in town, and descend a dungeon — except the "door" is an MCP
server and the player drives it by talking to an AI assistant.
The server is the rules engine and the single source of truth. Players share
**one persistent world**: your assistant calls tools, the server returns
authoritative frames and facts, and the assistant narrates the story around
them.
This is a self-contained reference example. It depends only on `mcp` — there
is no dependency on Turnstone itself — so it runs against any MCP client.
## How to play
There is **no prompt to paste and no persona to configure**. The tool schema
is the whole interface. Once the server is registered with your assistant:
1. Tell your assistant you'd like to play an ANSI door game / text dungeon
RPG (it can discover the tools by name and description).
2. The assistant calls `door_help` to learn how to run the world, then
`door_join` with your adventurer's name.
3. Play unfolds as a conversation: "head east", "fight it", "rest at the inn".
Everything the assistant needs to run the game well is returned by
`door_help`.
## Gameplay
A run is a little RPG loop, played a bit each day:
- **Explore** the overworld of box-drawing maps. Walking is free, but the wild
country has texture — a step may turn up a wandering monster, a purse of
gold, a healing spring, a small trap (which can never kill you), or a scrap
of old Vale lore. Only one such find happens per move, and the non-combat
ones don't interrupt your walk.
- **Fight, shop, and heal** in and around town. Fighting and descending one
rung of the dungeon each spend one of your daily turns; resting, shopping and
moving do not.
- **Delve the deep, a rung at a time.** The dungeon is a ladder of guardians:
each `descend` faces the next one past your deepest and either advances your
depth or bounces you home (your depth persists either way). Carry a few
**potions in your satchel**`quaff` the strongest when you choose, and if a
fight would kill you the satchel saves you automatically, the elixir burning
down your throat at death's edge. Clearing a rung also yields **forge ore**,
which rides the satchel (a won forest fight sometimes turns up a little, too).
- **Forge an edge — with gold AND ore.** At the shop's **forge** you can add a
+1 edge to your equipped weapon or armour, up to a cap, each step dearer than
the last. A step costs gold *and* the ore you won in the deep — so the forge is
fed by descending, not just by a fat purse. Watch, too, for the **rare beasts**
that prowl the forest: felling one is Herald news and always drops a draught.
- **Win the game** by slaying **the Wyrm Below**. Once your hero is seasoned
enough AND has plumbed the deep to its floor, `challenge` it at the dungeon. A
victory frees the Vale, carves your run into the **Hall of Legends**, and — in
the tradition of the classic BBS door games — begins a new life: your
character resets to first-day gear and stats but keeps a permanent ★ for every
Wyrm slain, ready to do it all again.
- **Read the news.** `door_log` is the **Understone Herald**, a shared
broadsheet of notable deeds across the whole world — who joined, who rose a
level, who was dragged home by a goblin, and who freed the Vale.
- **Make it social.** It is a shared world, so you can touch other players.
`ambush` a rival who has not yet acted today — a classic
style player-kill that robs a sleeping foe of some gold, except the surest
defence is simply to take your own turn (an active player is awake and can't
be caught). Lose the ambush and *you* are the one who flees, shamed on the
feed. `post` a private note another player reads on their next visit (it
never reaches the public Herald). Or `gamble` a little gold at the inn's dice
against the house. Ambush spends a turn; mail and dice do not.
- **Bank your coin.** The inn keeps a strongbox: `deposit` gold into the
**vault** and `withdraw` it later (no turn either way). Banked gold is **safe
from ambush** — a sleeping-robber only ever lifts what you carry — and it is
the one thing that **survives a Wyrm-win reset**, carrying wealth across runs.
## Installation
This example uses [`uv`](https://docs.astral.sh/uv/). From the example
directory:
```bash
cd examples/door-game
uv venv
uv pip install -e .
```
That installs the `understone` entry point into the environment.
To run the tests and quality gates:
```bash
uv pip install -e ".[test,dev]"
uv run pytest
uv run ruff check .
uv run ruff format --check .
uv run mypy understone/
```
## Running the server
By default the server speaks the **stdio** transport, which is how MCP clients
launch a per-session subprocess:
```bash
understone
```
To host one shared world over HTTP for several clients, run the
**streamable-http** transport as a single long-lived process:
```bash
UNDERSTONE_TRANSPORT=streamable-http understone
```
### Environment variables
| Variable | Default | Description |
|----------|---------|-------------|
| `UNDERSTONE_DB` | `./understone.db` | SQLite database file for the world's state. |
| `UNDERSTONE_WORLD` | _(packaged pack)_ | Directory of a content pack to load instead of the bundled Vale of Understone. |
| `UNDERSTONE_TRANSPORT` | `stdio` | `stdio` or `streamable-http`. |
| `UNDERSTONE_HOST` | `127.0.0.1` | Bind host (streamable-http only). |
| `UNDERSTONE_PORT` | `8077` | Bind port (streamable-http only). |
| `UNDERSTONE_PATH` | `/mcp` | HTTP path for the MCP endpoint (streamable-http only). |
## The Watch — a live spectator view
When the server runs under the **streamable-http** transport, it also serves a
read-only **Watch** page: the lobby TV of the Vale. Point a browser at
```
http://127.0.0.1:8077/watch
```
(the host and port follow `UNDERSTONE_HOST` / `UNDERSTONE_PORT`). It is a
period **CRT spectator console** — a green-and-amber phosphor map of the whole
world with every adventurer's `☻` marker, a live **Understone Herald** feed, the
**Hall of Legends**, and a roster of who is currently abroad. It refreshes every
couple of seconds; if it loses contact it dims and reads `SIGNAL LOST` until the
server returns. The console's palette follows the pack: a world may pick its own
CRT colour with `settings.watch_theme` (`phosphor` green, `amber` gold, `ice`
blue, `ember` red), defaulting to the Vale's green if it says nothing.
The Watch is **strictly read-only**. Input never flows through it — there are no
controls, no forms, nothing that can change the world. It reads the same shared
state the tools do and paints it; that is all. There is no authentication, in
keeping with the rest of this easter-egg server (see the safety note below), so
treat the page as you would the MCP endpoint itself.
> _Screenshot: the Watch console — a phosphor-green overworld map with amber
> `☻` markers, the Herald feed and Hall of Legends down the right-hand rail.
> (Image placeholder; run the server and open the URL to see it live.)_
When the Watch is up, the `door_join` welcome and the `door_help` manual both
print its URL so players (and the assistant narrating for them) know it exists.
If you bind to `0.0.0.0` to share the world across a network, advertise a host
that browsers can actually reach (your machine's LAN address or hostname) rather
than `0.0.0.0` itself — the link is composed from `UNDERSTONE_HOST`.
## Authoring worlds
The Vale of Understone is just the *bundled* world. The whole game — its map,
monsters, economy, and endgame — is a **content pack**: a directory of six JSON
files the server loads at start. Nothing about the Vale is privileged; point
the server at another pack and it runs that world instead. This is the seam
where the game becomes its own authoring target: a pack is plain data, so a
person *or an LLM* can write one, and the same zero-setup philosophy that makes
the game playable with no prompt makes it **authorable with no code**.
The loop has these commands:
```bash
understone newpack mypack # scaffold a pack (copies the Vale as a template)
# ...edit or LLM-generate the JSON in mypack/ to describe your world...
understone validate mypack # check it; prints a report or names what's wrong
understone simulate mypack # play a greedy bot through it and measure the balance
UNDERSTONE_WORLD=mypack understone # serve your world
understone worlds # list the bundled worlds and whether each is sound
```
`newpack` writes a starting template plus an `AUTHORING.md` manual — the
file-by-file schema, the enforced limits, and design guidance — written to be
followed cold by a model. `validate` loads the pack through exactly the same
hardened loader the server uses and either prints a summary ending **"This pack
is sound. The door stands open."** or fails with one precise line naming the
file, the row, and the field at fault.
`simulate` is the **balance instrument**: it drives a deliberately simple,
greedy bot through the *real* game — the same `join`/`move`/`action` calls the
tools make — over a seeded RNG and an injected clock, then prints a report
(final level, gold earned, fights fought, rungs cleared, whether and when the
Wyrm fell). It is a tuning probe, not a player to admire: it answers "is this
world *shaped* right, and is it *winnable*?". Pass `--days N`, `--seed S`, or
`--seeds K` for a multi-seed sweep with means and spreads. `worlds` lists every
bundled world — the default Vale plus any alternate packs shipped under
`understone/world/packs/` — loading each so it can report it as sound or flawed.
**A second bundled world: The Cinder Wastes.** Understone ships a second world
alongside the Vale, in `understone/world/packs/cinder-wastes/` — a volcanic
ash-and-slag map whose Watch page glows ember-red instead of the Vale's green
phosphor. It is the pipeline's own dogfood: it was authored **by an LLM working
only from `AUTHORING.md` and the `validate` loop**, with no engine code touched,
then bundled verbatim. `understone worlds` lists it as sound, and
`understone simulate understone/world/packs/cinder-wastes --days 50 --seeds 3`
shows the greedy bot taking its Magma Wyrm — the end-to-end proof that a world
described purely as data, from the manual alone, is genuinely playable to
victory. Serve it with
`UNDERSTONE_WORLD=understone/world/packs/cinder-wastes understone`.
Packs are validated **hard** at load: every map glyph must render as exactly
one terminal column (no fullwidth runes, no emoji, no combining marks — the
frames are box-drawing rectangles) and may not collide with the frame's
box-drawing lines or the player markers, dimensions and counts are bounded,
display names are length-checked, and every cross-reference (a legend
character, a starting item, the boss monster, a dungeon tier) must resolve. The
loader also pins the rules that keep the endgame coherent: a world has exactly
one boss, and a dungeon tier's lead monster (its fixed rung guardian) may not be
a rare. Because packs are now routinely untrusted, generated output, those error
messages are not a nuisance — they are the **feedback loop**. Iterate against
them until the door stands open.
## Registering with Turnstone
Understone is an ordinary MCP server, so it plugs into Turnstone's MCP client
config two ways.
**Stdio (per-session subprocess).** Turnstone launches the `understone`
command for each session. Each session gets its own subprocess, so for a
truly shared world prefer the HTTP form below; stdio is simplest for solo
play.
```toml
[mcp.servers.understone]
command = "understone"
[mcp.servers.understone.env]
UNDERSTONE_DB = "/var/lib/understone/world.db"
```
**Streamable-HTTP (one shared world).** Run a single Understone process with
`UNDERSTONE_TRANSPORT=streamable-http` and point every client at its URL. This
is the right setup for multiplayer: one process, one database, one world that
all adventurers share.
```toml
[mcp.servers.understone]
url = "http://localhost:8077/mcp"
```
> **Operator note.** For multiplayer, start exactly one shared process —
> `UNDERSTONE_TRANSPORT=streamable-http understone` — and have all clients use
> the url form. The world lives in a single SQLite file written by that one
> process.
## The tools
| Tool | What it does |
|------|--------------|
| `door_help` | The game-master manual. Start here. |
| `door_join` | Create or resume an adventurer; returns the opening map. |
| `door_status` | The character sheet (read-only). |
| `door_look` | Redraw the current view — overworld map or location menu. |
| `door_move` | Walk the overworld (free; no daily turn spent). |
| `door_action` | Context verbs: fight, flee, ambush (a rival), rest, deposit/withdraw (the inn vault), buy, sell, forge (a +1 edge, gold + ore), heal, gamble (inn dice), descend (one rung), challenge (the Wyrm), post (mail another player), quaff (a carried potion), leave. |
| `door_log` | The Understone Herald — the shared feed of notable deeds. |
| `door_rank` | The leaderboard, plus the Hall of Legends (★ marks Wyrm kills). |
| `door_bestow` | Game-master grant of a little gold/healing for a story beat. |
## A note on identity and safety
This example is an **easter egg**, not a hardened service. Identity is
**self-asserted**: a "player" is just a name passed to the tools, and there is
**no authentication** — anyone who can reach the server can act as any name.
That is fine for a shared toy world among people who trust each other, and
deliberately out of scope for a game. Do not store anything sensitive in it,
and if you expose the HTTP transport beyond localhost, put it behind whatever
access control your environment already provides.
The game master's `door_bestow` channel can only grant small, capped amounts
of in-game gold and healing — never items, never turns — and every grant is
written to the public in-world log, so its reach is bounded by design.
+55
View File
@@ -0,0 +1,55 @@
[build-system]
requires = ["hatchling>=1.29"]
build-backend = "hatchling.build"
[project]
name = "understone"
version = "0.10.0"
description = "Understone — a BBS-style ANSI door game served over MCP."
requires-python = ">=3.11"
license = "Apache-2.0"
dependencies = [
"mcp>=1.27,<2",
]
[project.scripts]
understone = "understone.server:main"
[project.optional-dependencies]
test = ["pytest>=9.0"]
dev = ["ruff>=0.9", "mypy>=1.14"]
[tool.hatch.build.targets.wheel]
packages = ["understone"]
[tool.pytest.ini_options]
testpaths = ["tests"]
[tool.ruff]
target-version = "py311"
line-length = 100
[tool.ruff.lint]
select = ["E", "F", "W", "I", "N", "UP", "B", "A", "SIM", "TCH"]
ignore = ["E501"]
[tool.ruff.format]
quote-style = "double"
[tool.mypy]
python_version = "3.11"
strict = true
warn_return_any = true
warn_unused_configs = true
disallow_untyped_defs = true
disallow_incomplete_defs = true
check_untyped_defs = true
no_implicit_optional = true
[[tool.mypy.overrides]]
module = ["mcp", "mcp.*"]
ignore_missing_imports = true
[[tool.mypy.overrides]]
module = "tests.*"
disallow_untyped_defs = false
+256
View File
@@ -0,0 +1,256 @@
"""Shared test fixtures and builders.
These builders construct engine objects directly (no JSON loader) so the
engine tests stay independent of the content pack. Later chunks add
fixtures that load the shipped world and build the game façade.
"""
from __future__ import annotations
from collections import Counter
from datetime import UTC, datetime
from typing import TYPE_CHECKING
import pytest
from understone.engine.models import (
Item,
LocationDef,
Mode,
Monster,
Player,
Settings,
Slot,
TerrainDef,
WorldEvent,
Zone,
)
from understone.engine.world import World
if TYPE_CHECKING:
from collections.abc import Callable
from understone.game import Game
# ---------------------------------------------------------------------------
# Terrain kinds for synthetic test worlds
# ---------------------------------------------------------------------------
GRASS = TerrainDef(key="grass", glyph=".", walkable=True, encounter_rate=0.0, color="floor")
WALL = TerrainDef(key="wall", glyph="", walkable=False, encounter_rate=0.0, color="wall")
WATER = TerrainDef(key="water", glyph="~", walkable=False, encounter_rate=0.0, color="water")
FOREST = TerrainDef(key="forest", glyph="", walkable=True, encounter_rate=1.0, color="tree")
SAFE_FOREST = TerrainDef(key="forest", glyph="", walkable=True, encounter_rate=0.0, color="tree")
DEFAULT_SETTINGS = Settings(
daily_turns=10,
rest_cost=15,
heal_cost_per_hp=2,
starting_gold=20,
starting_weapon="rusty_dagger",
starting_armor="cloth_tunic",
start_hp=20,
start_atk=3,
start_def=0,
xp_base=100,
growth_max_hp=6,
growth_atk=2,
growth_def=1,
bestow_daily_budget=25,
dungeon_tiers=(4, 5),
boss_monster="wyrm_below",
wyrm_min_level=6,
ambush_min_level=3,
ambush_level_band=2,
ambush_gold_pct=25,
post_daily_cap=5,
gamble_max_bet=50,
gamble_daily_cap=5,
satchel_max=3,
forge_base_cost=60,
forge_max_plus=3,
rare_drop_item="minor_potion",
forge_ore_item="iron_ore",
forge_ore_per_plus=1,
ore_dungeon_drop=2,
ore_forest_chance=0.2,
watch_theme="phosphor",
)
def make_settings(**overrides: object) -> Settings:
"""Return DEFAULT_SETTINGS with field overrides for band testing."""
base = {
"daily_turns": DEFAULT_SETTINGS.daily_turns,
"rest_cost": DEFAULT_SETTINGS.rest_cost,
"heal_cost_per_hp": DEFAULT_SETTINGS.heal_cost_per_hp,
"starting_gold": DEFAULT_SETTINGS.starting_gold,
"starting_weapon": DEFAULT_SETTINGS.starting_weapon,
"starting_armor": DEFAULT_SETTINGS.starting_armor,
"start_hp": DEFAULT_SETTINGS.start_hp,
"start_atk": DEFAULT_SETTINGS.start_atk,
"start_def": DEFAULT_SETTINGS.start_def,
"xp_base": DEFAULT_SETTINGS.xp_base,
"growth_max_hp": DEFAULT_SETTINGS.growth_max_hp,
"growth_atk": DEFAULT_SETTINGS.growth_atk,
"growth_def": DEFAULT_SETTINGS.growth_def,
"bestow_daily_budget": DEFAULT_SETTINGS.bestow_daily_budget,
"dungeon_tiers": DEFAULT_SETTINGS.dungeon_tiers,
"boss_monster": DEFAULT_SETTINGS.boss_monster,
"wyrm_min_level": DEFAULT_SETTINGS.wyrm_min_level,
"ambush_min_level": DEFAULT_SETTINGS.ambush_min_level,
"ambush_level_band": DEFAULT_SETTINGS.ambush_level_band,
"ambush_gold_pct": DEFAULT_SETTINGS.ambush_gold_pct,
"post_daily_cap": DEFAULT_SETTINGS.post_daily_cap,
"gamble_max_bet": DEFAULT_SETTINGS.gamble_max_bet,
"gamble_daily_cap": DEFAULT_SETTINGS.gamble_daily_cap,
"satchel_max": DEFAULT_SETTINGS.satchel_max,
"forge_base_cost": DEFAULT_SETTINGS.forge_base_cost,
"forge_max_plus": DEFAULT_SETTINGS.forge_max_plus,
"rare_drop_item": DEFAULT_SETTINGS.rare_drop_item,
"forge_ore_item": DEFAULT_SETTINGS.forge_ore_item,
"forge_ore_per_plus": DEFAULT_SETTINGS.forge_ore_per_plus,
"ore_dungeon_drop": DEFAULT_SETTINGS.ore_dungeon_drop,
"ore_forest_chance": DEFAULT_SETTINGS.ore_forest_chance,
"watch_theme": DEFAULT_SETTINGS.watch_theme,
}
base.update(overrides)
return Settings(**base) # type: ignore[arg-type]
def make_player(**overrides: object) -> Player:
"""Build a Player at sane defaults; override any field by keyword."""
fields = {
"name": "Tester",
"x": 5,
"y": 5,
"hp": 20,
"max_hp": 20,
"level": 1,
"xp": 0,
"gold": 50,
"atk": 5,
"def_": 1,
"weapon_id": "rusty_dagger",
"armor_id": "cloth_tunic",
"turns_left": 10,
"turn_day": 0,
"mode": Mode.TILE,
"at_location": "",
"created_at": "2026-01-01T00:00:00+00:00",
"last_seen": "2026-01-01T00:00:00+00:00",
"log_cursor": 0,
"bestow_spent": 0,
"bestow_day": 0,
"wins": 0,
"posts_sent": 0,
"post_day": 0,
"gambles": 0,
"gamble_day": 0,
}
fields.update(overrides)
return Player(**fields) # type: ignore[arg-type]
def make_monster(**overrides: object) -> Monster:
"""Build a Monster at tier-1 defaults."""
fields = {
"tier": 1,
"name": "Field Rat",
"hp": 6,
"atk": 3,
"def_": 0,
"xp": 8,
"gold": 3,
"monster_id": "",
"boss": False,
}
fields.update(overrides)
return Monster(**fields) # type: ignore[arg-type]
def make_world(
*,
grid: list[list[TerrainDef]] | None = None,
width: int = 11,
height: int = 11,
spawn: tuple[int, int] = (5, 5),
locations: list[LocationDef] | None = None,
zones: list[Zone] | None = None,
monsters: list[Monster] | None = None,
items: list[Item] | None = None,
settings: Settings | None = None,
events: list[WorldEvent] | None = None,
) -> World:
"""Build a small synthetic World (all-grass by default)."""
if grid is None:
grid = [[GRASS for _ in range(width)] for _ in range(height)]
return World(
name="Test Vale",
width=width,
height=height,
spawn=spawn,
terrain=grid,
locations=locations or [],
zones=zones or [],
monsters=monsters or [make_monster()],
items=items or _default_items(),
settings=settings or DEFAULT_SETTINGS,
events=events,
)
def _default_items() -> list[Item]:
return [
Item("rusty_dagger", "Rusty Dagger", Slot.WEAPON, 2, 0, 0, 0),
Item("short_sword", "Short Sword", Slot.WEAPON, 5, 0, 0, 40),
Item("cloth_tunic", "Cloth Tunic", Slot.ARMOR, 0, 1, 0, 0),
Item("leather_armor", "Leather Armor", Slot.ARMOR, 0, 3, 0, 50),
Item("minor_potion", "Minor Potion", Slot.CONSUMABLE, 0, 0, 15, 12),
Item("iron_ore", "Iron Ore", Slot.MATERIAL, 0, 0, 0, 0),
]
def fixed_clock(moment: datetime) -> Callable[[], datetime]:
"""Return a clock callable that always reports *moment*."""
def _clock() -> datetime:
return moment
return _clock
def utc(year: int, month: int, day: int, hour: int = 0, minute: int = 0) -> datetime:
"""Construct a tz-aware UTC datetime."""
return datetime(year, month, day, hour, minute, tzinfo=UTC)
# ---------------------------------------------------------------------------
# Satchel test helpers (the v0.10 stack encoding)
# ---------------------------------------------------------------------------
# The satchel is stack-based ("id:qty"); these wrap the game façade's stack
# helpers so a test can seed/read a bag as a flat id list (duplicate ids
# collapse to one stack), keeping the assertions readable. Shared by the
# descend and Wyrm suites.
def set_satchel(game: Game, player: object, ids: list[str]) -> None:
"""Seed *player*'s satchel from a flat id list (duplicates -> one stack qty)."""
counts = Counter(ids)
stacks = [(item_id, counts[item_id]) for item_id in dict.fromkeys(ids)]
game._satchel_set_stacks(player, stacks) # type: ignore[arg-type]
def satchel_ids(game: Game, player: object) -> list[str]:
"""Return the satchel as a flat id list, each stack expanded by its qty."""
out: list[str] = []
for item_id, qty in game._satchel_stacks(player): # type: ignore[arg-type]
out.extend([item_id] * qty)
return out
@pytest.fixture
def small_world() -> World:
"""An 11x11 all-grass world with the default content tables."""
return make_world()
@@ -0,0 +1,7 @@
┌── The Sleeping Drake ───┐
│ A warm hearth crackles. │
│ A bed costs 15 gold. │
│ │
│ (R)est (L)eave │
└─────────────────────────┘
[ status ]
@@ -0,0 +1,8 @@
┌─ Vale ──┐
│@........│
│.........│
│.........│
│.........│
│.........│
└─────────┘
[ status ]
@@ -0,0 +1,8 @@
┌─ Vale ──┐
│.........│
│.........│
│....@....│
│.........│
│.........│
└─────────┘
[ status ]
+374
View File
@@ -0,0 +1,374 @@
"""Tests for the pack-authoring command surface.
Covers the validate/newpack functions directly (sound and broken packs, the
scaffold round-trip, AUTHORING.md generation from the live loader bands, and
the refuse-non-empty guard), the ``server.main`` argv dispatch (validate routes
through and bare invocation still reaches serve without binding a port), and
one end-to-end subprocess smoke of ``python -m understone validate``.
"""
from __future__ import annotations
import json
import shutil
import subprocess
import sys
from io import StringIO
from pathlib import Path
from typing import TYPE_CHECKING, Any
import pytest
from understone import cli, server
from understone.world import loader
if TYPE_CHECKING:
from collections.abc import Callable
EXAMPLE_DIR = Path(__file__).resolve().parents[1]
SHIPPED = EXAMPLE_DIR / "understone" / "world" / "data"
# The six content files a scaffolded pack must carry, plus the manual.
_PACK_JSONS = {
"terrain.json",
"monsters.json",
"items.json",
"locations.json",
"events.json",
"world.json",
}
# ---------------------------------------------------------------------------
# cli_validate
# ---------------------------------------------------------------------------
def test_cli_validate_sound_pack_reports_and_returns_zero() -> None:
out, err = StringIO(), StringIO()
rc = cli.cli_validate(SHIPPED, out=out, err=err)
assert rc == 0
report = out.getvalue()
assert "This pack is sound. The door stands open." in report
# The report surfaces the headline facts the brief calls for.
assert "The Vale of Understone" in report
assert "96x48" in report
assert "1 boss" in report
assert "% fight" in report
assert err.getvalue() == ""
def test_cli_validate_broken_pack_names_field_and_returns_two(tmp_path: Path) -> None:
# A pack whose daily_turns is out of band: the loader names the field.
pack = _clone_shipped(tmp_path)
_patch_world(pack, _break_daily_turns)
out, err = StringIO(), StringIO()
rc = cli.cli_validate(pack, out=out, err=err)
assert rc == 2
message = err.getvalue()
assert message.startswith("The pack is flawed:")
assert "daily_turns" in message # the offending field is named
assert out.getvalue() == ""
def test_cli_validate_missing_directory_returns_two(tmp_path: Path) -> None:
out, err = StringIO(), StringIO()
rc = cli.cli_validate(tmp_path / "nope", out=out, err=err)
assert rc == 2
assert "The pack is flawed:" in err.getvalue()
# ---------------------------------------------------------------------------
# cli_newpack
# ---------------------------------------------------------------------------
def test_cli_newpack_writes_template_and_manual(tmp_path: Path) -> None:
dest = tmp_path / "mypack"
out, err = StringIO(), StringIO()
rc = cli.cli_newpack(dest, out=out, err=err)
assert rc == 0
present = {p.name for p in dest.iterdir()}
assert present >= _PACK_JSONS # the six content files are all there
assert "AUTHORING.md" in present
# Next-steps guidance points the author at the validate verb.
assert "understone validate" in out.getvalue()
def test_cli_newpack_scaffold_validates(tmp_path: Path) -> None:
"""The load-bearing test: a freshly scaffolded pack loads cleanly.
newpack -> load_world round-trip. If the template the scaffolder copies
ever drifts out of the loader's bands, this fails immediately.
"""
dest = tmp_path / "mypack"
assert cli.cli_newpack(dest, out=StringIO(), err=StringIO()) == 0
world = loader.load_world(dest)
assert world.name == "The Vale of Understone"
assert world.width == 96
def test_cli_newpack_authoring_md_renders_live_band(tmp_path: Path) -> None:
"""AUTHORING.md's bands are generated from the loader, not hand-copied.
The daily_turns band is read straight from the live loader table and must
appear verbatim in the scaffolded manual proving generation from source.
"""
dest = tmp_path / "mypack"
cli.cli_newpack(dest, out=StringIO(), err=StringIO())
manual = (dest / "AUTHORING.md").read_text(encoding="utf-8")
lo, hi = loader.SETTINGS_BANDS["daily_turns"]
assert lo is not None and hi is not None
assert f"`{lo}..{hi}`" in manual
assert "daily_turns" in manual
def test_cli_newpack_authoring_md_has_width_rule_and_live_palette(tmp_path: Path) -> None:
"""AUTHORING.md documents the one-column rule and renders the live palette.
The width section states the Western-monospace assumption, and the safe
palette is generated from ``textwidth.SAFE_PALETTE`` (same can't-drift
pattern as the bands table) every glyph appears, in a backticked cell.
"""
from understone.engine.textwidth import SAFE_PALETTE
dest = tmp_path / "mypack"
cli.cli_newpack(dest, out=StringIO(), err=StringIO())
manual = (dest / "AUTHORING.md").read_text(encoding="utf-8")
assert "## Glyph width" in manual
assert "exactly one terminal column" in manual
assert "Western monospace" in manual # the stated assumption
assert "Safe glyph palette" in manual
for glyph in SAFE_PALETTE:
assert f"`{glyph}`" in manual, f"palette glyph {glyph!r} missing from manual"
def test_cli_newpack_authoring_md_documents_action_sets(tmp_path: Path) -> None:
"""AUTHORING.md documents each building's real verb menu.
The per-building menus are an explicit table: the inn's `gamble` (v0.8) and
the v0.10 vault verbs `deposit`/`withdraw`, the shop's `forge`, and so on.
This pins the table rows and the "quaff anywhere" note so a doc regression
trips.
"""
dest = tmp_path / "mypack"
cli.cli_newpack(dest, out=StringIO(), err=StringIO())
manual = (dest / "AUTHORING.md").read_text(encoding="utf-8")
assert "| `inn` | `rest`, `deposit`, `withdraw`, `gamble`, `leave` |" in manual
assert "| `shop` | `buy`, `sell`, `forge`, `leave` |" in manual
assert "| `healer` | `heal`, `leave` |" in manual
assert "| `dungeon` | `descend`, `challenge`, `leave` |" in manual
assert "`quaff`" in manual and "legal **anywhere**" in manual
# The vault is described where its verbs are listed.
assert "VAULT" in manual and "SAFE from ambush" in manual
def test_cli_newpack_authoring_md_documents_ore_forge(tmp_path: Path) -> None:
"""AUTHORING.md documents the v0.10 ore-gated forge: material slot + settings.
The forge ore is a `material` item earned in combat; the four ore settings
(item, per-plus, dungeon drop, forest chance) are documented, and the band
figures are generated from the live loader so they cannot drift.
"""
dest = tmp_path / "mypack"
cli.cli_newpack(dest, out=StringIO(), err=StringIO())
manual = (dest / "AUTHORING.md").read_text(encoding="utf-8")
assert "`material`" in manual # the new slot
assert "forge_ore_item" in manual
assert "ore_forest_chance" in manual # the float setting (prose, not the band table)
# The two banded ore settings carry their LIVE bands.
lo, hi = loader.SETTINGS_BANDS["ore_dungeon_drop"]
assert f"`{lo}..{hi}`" in manual
assert "earns in combat" in manual or "earned in combat" in manual
def test_cli_newpack_authoring_md_states_color_advisory_and_spawn_walkable(
tmp_path: Path,
) -> None:
"""AUTHORING.md states color is advisory (loader does not validate it) and
that spawn must be on walkable terrain both v0.8 honesty fixes."""
dest = tmp_path / "mypack"
cli.cli_newpack(dest, out=StringIO(), err=StringIO())
manual = (dest / "AUTHORING.md").read_text(encoding="utf-8")
# color is documented as advisory / not validated (it matches loader behaviour).
assert "advisory and not validated" in manual
# spawn's walkability requirement is now stated where spawn is introduced.
assert "must be on walkable terrain" in manual
def test_cli_newpack_authoring_md_color_roles_generated_from_enum(tmp_path: Path) -> None:
"""AUTHORING.md's colour-role vocabulary is generated from the Color enum.
The v0.9 fix: the assignable roles were hand-listed (and went stale road
and the per-building roles were missing). They are now generated from
``Color.assignable()`` the single source for the overlay-vs-assignable
split so the manual lists exactly what the Watch can paint and cannot
drift. This asserts the NEW roles appear, that every assignable enum role
appears, and that the non-assignable roles (overlays + DEFAULT) are NOT
offered as author-assignable.
"""
from understone.screen.palette import Color
dest = tmp_path / "mypack"
cli.cli_newpack(dest, out=StringIO(), err=StringIO())
manual = (dest / "AUTHORING.md").read_text(encoding="utf-8")
# A sampling of the new v0.9 roles is offered in the manual, backticked.
for role in ("road", "forest", "lava", "barren", "inn", "shop", "healer"):
assert f"`{role}`" in manual, f"new colour role {role!r} missing from manual"
# EVERY assignable enum role appears (generated, so the full set is present).
color_section = manual[manual.index("`color` — a palette role string") :].split("###", 1)[0]
for role in Color.assignable():
assert f"`{role.value}`" in manual, f"assignable role {role.value!r} missing from manual"
# The non-assignable roles (runtime overlays + the DEFAULT fallback) are NOT
# offered as terrain/location colours.
non_assignable = {c for c in Color} - set(Color.assignable())
assert Color.DEFAULT in non_assignable # the fallback is not author-pickable
for role in non_assignable:
assert f"`{role.value}`" not in color_section, (
f"non-assignable role {role.value!r} wrongly offered as author-assignable"
)
def test_cli_newpack_authoring_md_has_validate_coverage_split(tmp_path: Path) -> None:
"""AUTHORING.md honestly separates machine-enforced rules from eyeball-only.
The v0.8 subsection lists what `validate` DOES catch (including the two new
enforcements rare-as-guardian and single-boss) and what it does NOT (chief
among them: location menu `actions` contents are unvalidated).
"""
dest = tmp_path / "mypack"
cli.cli_newpack(dest, out=StringIO(), err=StringIO())
manual = (dest / "AUTHORING.md").read_text(encoding="utf-8")
assert "What `validate` checks, and what it cannot" in manual
# The newly-enforced rules are named in the DOES-catch list.
assert "Exactly one boss" in manual
assert "fixed rung guardian) must" in manual # rare-as-guardian enforcement
# The eyeball-only short list names the actions gap and the flavour caveat.
assert "Location menu `actions` contents" in manual
assert "Flavour and narration quality" in manual
def test_cli_newpack_refuses_non_empty_dir(tmp_path: Path) -> None:
dest = tmp_path / "occupied"
dest.mkdir()
(dest / "keep.txt").write_text("mine", encoding="utf-8")
out, err = StringIO(), StringIO()
rc = cli.cli_newpack(dest, out=out, err=err)
assert rc == 2
assert "non-empty" in err.getvalue()
# The pre-existing file is untouched (nothing was scaffolded over it).
assert (dest / "keep.txt").read_text(encoding="utf-8") == "mine"
assert not (dest / "AUTHORING.md").exists()
def test_cli_newpack_into_empty_existing_dir_succeeds(tmp_path: Path) -> None:
"""An existing but empty directory is a fine scaffold target."""
dest = tmp_path / "empty"
dest.mkdir()
assert cli.cli_newpack(dest, out=StringIO(), err=StringIO()) == 0
assert (dest / "AUTHORING.md").exists()
# ---------------------------------------------------------------------------
# server.main argv dispatch
# ---------------------------------------------------------------------------
def test_main_validate_dispatch_returns_status(
tmp_path: Path, capsys: pytest.CaptureFixture
) -> None:
# A broken pack routed through main exits 2; a sound one exits 0.
pack = _clone_shipped(tmp_path)
_patch_world(pack, _break_daily_turns)
with pytest.raises(SystemExit) as broken:
server.main(["validate", str(pack)])
assert broken.value.code == 2
with pytest.raises(SystemExit) as sound:
server.main(["validate", str(SHIPPED)])
assert sound.value.code == 0
assert "The door stands open." in capsys.readouterr().out
def test_main_newpack_dispatch(tmp_path: Path) -> None:
dest = tmp_path / "viamain"
with pytest.raises(SystemExit) as exc:
server.main(["newpack", str(dest)])
assert exc.value.code == 0
assert (dest / "AUTHORING.md").exists()
def test_main_worlds_dispatch(capsys: pytest.CaptureFixture) -> None:
"""`understone worlds` routes through main, exits 0, and lists the Vale."""
with pytest.raises(SystemExit) as exc:
server.main(["worlds"])
assert exc.value.code == 0
out = capsys.readouterr().out
assert "vale" in out
assert "The Vale of Understone" in out
assert "UNDERSTONE_WORLD=" in out
def test_bare_invocation_resolves_to_serve_without_side_effects() -> None:
"""Parsing no argv yields the serve path, and parsing has no side effects.
The transport launch (_serve) is reachable, but argument parsing neither
loads a world nor binds a port so this asserts the resolved command
without ever calling _serve.
"""
args = server._build_parser().parse_args([])
assert args.cmd is None # None => the serve branch in main()
assert callable(server._serve)
def test_subprocess_validate_packaged_world_exits_zero() -> None:
"""End-to-end smoke: `python -m understone validate <packaged dir>` exits 0."""
result = subprocess.run(
[sys.executable, "-m", "understone", "validate", str(SHIPPED)],
cwd=EXAMPLE_DIR,
capture_output=True,
text=True,
timeout=60,
)
assert result.returncode == 0, result.stderr
assert "The door stands open." in result.stdout
# ---------------------------------------------------------------------------
# helpers
# ---------------------------------------------------------------------------
def _clone_shipped(tmp_path: Path) -> Path:
dest = tmp_path / "pack"
shutil.copytree(SHIPPED, dest)
return dest
def _patch_world(pack: Path, mutate: Callable[[dict[str, Any]], None]) -> None:
path = pack / "world.json"
data = json.loads(path.read_text(encoding="utf-8"))
mutate(data)
path.write_text(json.dumps(data), encoding="utf-8")
def _break_daily_turns(data: dict[str, Any]) -> None:
"""Set daily_turns out of its 1..100 band so the pack fails to load."""
data["settings"]["daily_turns"] = 0
+123
View File
@@ -0,0 +1,123 @@
"""Combat resolution tests.
Pins determinism (a fixed seed yields identical results twice, log and
deltas), each outcome (win/lose/flee), xp/gold crediting on victory, and
the defeat contract: the result flags a spawn bounce with no xp/gold and a
zero hp delta (the façade applies hp=1 and the move).
"""
from __future__ import annotations
from tests.conftest import make_monster, make_player
from understone.engine.combat import Outcome, resolve_fight, resolve_flee
from understone.engine.rng import GameRNG
# A strong adventurer vs a Field Rat wins on every probed seed.
_WIN_SEED = 1
# A fragile adventurer vs a Stone Wyrm loses on every probed seed.
_LOSE_SEED = 0
# Flee outcomes (probed): seed 1 escapes clean, seed 0 is caught.
_FLEE_CLEAN_SEED = 1
_FLEE_CAUGHT_SEED = 0
def _strong_player() -> object:
return make_player(hp=20, max_hp=20, atk=5, def_=1, xp=0, gold=50)
def _wyrm() -> object:
return make_monster(tier=5, name="Stone Wyrm", hp=60, atk=18, def_=6, xp=140, gold=60)
def test_fight_is_deterministic_under_fixed_seed() -> None:
r1 = resolve_fight(GameRNG(seed=7), make_player(), make_monster())
r2 = resolve_fight(GameRNG(seed=7), make_player(), make_monster())
assert r1.log == r2.log
assert (r1.outcome, r1.xp_delta, r1.gold_delta, r1.hp_delta) == (
r2.outcome,
r2.xp_delta,
r2.gold_delta,
r2.hp_delta,
)
def test_win_credits_xp_and_gold() -> None:
player = make_player(hp=20, max_hp=20, atk=5, def_=1)
monster = make_monster(hp=6, atk=3, def_=0, xp=8, gold=3)
result = resolve_fight(GameRNG(seed=_WIN_SEED), player, monster)
assert result.outcome is Outcome.WIN
assert result.xp_delta == 8
assert result.gold_delta == 3
# hp_delta is non-positive (you may take a scratch) and never fatal here.
assert result.hp_delta <= 0
assert not result.bounce_to_spawn
def test_win_deltas_are_exact_for_pinned_seed() -> None:
player = make_player(hp=20, max_hp=20, atk=5, def_=1)
monster = make_monster(hp=6, atk=3, def_=0, xp=8, gold=3)
result = resolve_fight(GameRNG(seed=_WIN_SEED), player, monster)
# Pinned from a determinism probe; guards against silent damage drift.
assert result.hp_delta == -1
# The engine no longer emits a "falls + reward" line — that sentence is
# composed by the game façade where the xp/gold are actually banked — so
# the WIN log is one line shorter than before and ends on the kill blow.
assert len(result.log) == 4
assert result.log[-1] == "You strike for 6. (Field Rat: 0 HP)"
def test_win_log_does_not_claim_rewards() -> None:
"""The engine narrates the kill blow only; it never claims xp/gold itself.
Reward ownership lives in the façade (so the Wyrm-win legacy reset, which
keeps no xp/gold, narrates no reward). The deltas are still carried on the
result for the caller to apply.
"""
player = make_player(hp=20, max_hp=20, atk=5, def_=1)
monster = make_monster(hp=6, atk=3, def_=0, xp=8, gold=3)
result = resolve_fight(GameRNG(seed=_WIN_SEED), player, monster)
assert result.outcome is Outcome.WIN
assert result.xp_delta == 8 and result.gold_delta == 3 # deltas still set
joined = "\n".join(result.log)
assert "falls" not in joined # no kill/reward sentence in the engine log
assert "XP" not in joined and "gold" not in joined
def test_loss_flags_bounce_without_rewards() -> None:
result = resolve_fight(GameRNG(seed=_LOSE_SEED), _strong_player_loses(), _wyrm())
assert result.outcome is Outcome.LOSE
assert result.bounce_to_spawn is True
assert result.xp_delta == 0
assert result.gold_delta == 0
# Combat does not set hp to 1 itself — that is the façade's job.
assert result.hp_delta == 0
def _strong_player_loses() -> object:
return make_player(hp=12, max_hp=12, atk=4, def_=0)
def test_flee_can_escape_clean() -> None:
player = make_player(hp=20, max_hp=20, def_=1)
monster = make_monster(atk=8, def_=2)
result = resolve_flee(GameRNG(seed=_FLEE_CLEAN_SEED), player, monster)
assert result.outcome is Outcome.FLED
assert result.hp_delta == 0
def test_flee_caught_costs_hp_but_never_kills() -> None:
player = make_player(hp=20, max_hp=20, def_=1)
monster = make_monster(atk=8, def_=2)
result = resolve_flee(GameRNG(seed=_FLEE_CAUGHT_SEED), player, monster)
assert result.outcome is Outcome.FLED
assert result.hp_delta < 0
# A caught flight cannot drop the player to or below zero.
assert player.hp + result.hp_delta >= 1
def test_flee_caught_never_kills_at_low_hp() -> None:
player = make_player(hp=1, max_hp=20, def_=0)
monster = make_monster(atk=40, def_=0)
result = resolve_flee(GameRNG(seed=_FLEE_CAUGHT_SEED), player, monster)
# At 1 HP the most a failed flee can cost is 0 (cannot go below 1).
assert result.hp_delta == 0
File diff suppressed because it is too large Load Diff
+858
View File
@@ -0,0 +1,858 @@
"""Game façade integration tests over the shipped world.
Drives a full session against a temp store, a frozen clock, and a seeded
RNG: join -> status -> look -> move -> action(buy/rest/fight) -> log ->
rank -> bestow. Persistence is exercised by reopening the store.
Negative-test discipline (turn guard and bestow cap):
Two guards are pinned by assertions here. To confirm each assertion has
teeth, the implementer temporarily reverted the guard line and observed
the matching test FAIL, then restored it:
* Turn guard (engine/turns.py spend_turn): replacing
``if player.turns_left <= 0: return False`` with ``return True``
let fighting continue past the daily budget ``test_turn_budget_blocks``
then failed on the "spent for today" assertion. Restored.
* Bestow cap (game.py bestow): removing the ``if cost > remaining``
refusal let an over-budget bestowal through ``test_bestow_cap_refuses``
then failed on the unchanged-gold assertion. Restored.
* Sanitizer control-char guard (game.py _sanitize): disabling the
``not cleaned.isprintable()`` clause let a newline-injected name create a
player row and a public event ``test_join_rejects_control_char_name``
then failed. Restored. (See the comment block above the hygiene tests.)
"""
from __future__ import annotations
import unicodedata
from pathlib import Path
import pytest
from tests.conftest import fixed_clock, utc
from understone.engine.models import Mode
from understone.engine.rng import GameRNG
from understone.game import Game
from understone.persistence import Store
from understone.world.loader import load_world
PACK = Path(__file__).resolve().parents[1] / "understone" / "world" / "data"
@pytest.fixture
def clock() -> object:
return fixed_clock(utc(2026, 6, 12, 10, 0))
def _game(tmp_path: Path, clock: object, seed: int = 7) -> Game:
world = load_world(PACK)
store = Store(tmp_path / "game.db")
return Game(world, store, clock=clock, rng=GameRNG(seed=seed)) # type: ignore[arg-type]
# ---------------------------------------------------------------------------
# Join / status / look
# ---------------------------------------------------------------------------
def test_join_creates_player_at_spawn(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
out = game.join("Brandr")
player = game.players["Brandr"]
assert (player.x, player.y) == game.world.spawn
assert player.gold == game.world.settings.starting_gold
assert "@" in out
assert game.world.name in out
def test_join_resumes_existing(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
game.join("Brandr")
game.players["Brandr"].gold = 123
out = game.join("Brandr")
assert "Welcome back" in out
assert game.players["Brandr"].gold == 123
def test_status_unknown_player_is_friendly(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
out = game.status("Nobody")
assert "has signed the ledger" in out
assert "door_join" in out
def test_look_overworld_has_frame(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
game.join("Brandr")
out = game.look("Brandr")
assert "@" in out
assert "" in out and "" in out
assert len(out) < 2048
def test_overworld_frame_textured_borders_intact(tmp_path: Path, clock: object) -> None:
"""The textured overworld frame keeps square borders and a single player marker.
Structural discipline for the v0.6 texture: variants change the GLYPHS but
must never change the geometry. The box rows are uniform width, exactly one
'@' is painted, and the grass field shows more than one variant in a row
(the deterministic stipple, not a flat sheet of '.').
"""
game = _game(tmp_path, clock)
game.join("Brandr")
frame = game.look("Brandr")
lines = frame.split("\n")
# Box rows: top border + VIEW_H grid rows + bottom border, all equal width.
box = [ln for ln in lines if ln and ln[0] in "┌│└"]
widths = {len(ln) for ln in box}
assert len(widths) == 1, f"textured frame rows ragged: {widths}"
# Exactly one player marker, regardless of the surrounding texture.
assert frame.count("@") == 1
# The grass texture varies: a body row carries at least two of . , '
body = [ln for ln in lines if ln.startswith("")]
assert any(len({ch for ch in ln if ch in ".,'"}) >= 2 for ln in body)
def test_look_in_menu_shows_location(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
game.join("Brandr")
# Shop is two cells east of spawn along the road.
game.move("Brandr", "", "east", 2)
assert game.players["Brandr"].mode is Mode.MENU
out = game.look("Brandr")
assert "(B)uy" in out and "(L)eave" in out
# ---------------------------------------------------------------------------
# Move
# ---------------------------------------------------------------------------
def test_move_blocked_in_menu(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
game.join("Brandr")
game.move("Brandr", "", "east", 2) # into the shop menu
out = game.move("Brandr", "", "east", 2)
assert "inside" in out.lower()
def test_move_enters_location(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
game.join("Brandr")
out = game.move("Brandr", "", "west", 2) # inn is two cells west
assert game.players["Brandr"].at_location == "inn"
assert "step inside" in out.lower()
# ---------------------------------------------------------------------------
# Actions: rest, fight, turn budget
# ---------------------------------------------------------------------------
def test_rest_heals_and_charges(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
game.join("Brandr")
player = game.players["Brandr"]
player.hp = 5
game.move("Brandr", "", "west", 2) # inn
out = game.action("Brandr", "rest", "", "")
assert player.hp == player.max_hp
assert player.gold == game.world.settings.starting_gold - game.world.settings.rest_cost
assert "full health" in out.lower()
def test_rest_when_spent_restores_a_fresh_days_turns(tmp_path: Path, clock: object) -> None:
"""Sleeping at the inn with no turns left rolls into a fresh day's allowance."""
game = _game(tmp_path, clock)
game.join("Brandr")
player = game.players["Brandr"]
daily = game.world.settings.daily_turns
player.turns_left = 0 # spent for the day
player.hp = 5
game.move("Brandr", "", "west", 2) # step into the inn
out = game.action("Brandr", "rest", "", "")
assert player.turns_left == daily # a fresh day's turns restored
assert player.hp == player.max_hp # and fully mended
assert f"/{daily} ]" in out # footer reflects the refreshed budget
def test_rest_with_turns_in_hand_never_inflates_the_budget(tmp_path: Path, clock: object) -> None:
"""Resting mid-day mends but adds no turns — the top-up only fires at zero."""
game = _game(tmp_path, clock)
game.join("Brandr")
player = game.players["Brandr"]
daily = game.world.settings.daily_turns
player.turns_left = daily - 3 # turns still in hand
player.hp = 5
game.move("Brandr", "", "west", 2) # step into the inn
game.action("Brandr", "rest", "", "")
assert player.turns_left == daily - 3 # unchanged: no farming past the cap
assert player.hp == player.max_hp # but the heal still lands
def test_fight_spends_a_turn_and_credits(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
game.join("Brandr")
player = game.players["Brandr"]
# Drop into the forest_near zone so an encounter is available.
player.x, player.y = 35, 25
before_turns = player.turns_left
out = game.action("Brandr", "fight", "", "")
assert player.turns_left == before_turns - 1
assert player.xp > 0
assert "XP" in out
def test_turn_budget_blocks(tmp_path: Path, clock: object) -> None:
"""Pins the spend_turn guard: at 0 turns, fighting is refused.
See the module docstring for the revert-and-observe-failure check that
proves this assertion has teeth.
"""
game = _game(tmp_path, clock)
game.join("Brandr")
player = game.players["Brandr"]
player.x, player.y = 35, 25
player.turns_left = 0
out = game.action("Brandr", "fight", "", "")
assert "spent for today" in out.lower()
# No turn was consumed past zero, and no XP was gained.
assert player.turns_left == 0
assert player.xp == 0
# ---------------------------------------------------------------------------
# Log / rank
# ---------------------------------------------------------------------------
def test_log_reports_then_advances(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
game.join("Brandr")
# A second player acting creates a public event Brandr has not yet seen.
game.join("Sigrun")
first = game.log("Brandr")
assert "Sigrun" in first or "Brandr" in first
assert "The Understone Herald" in first # dressed as the broadsheet
# The cursor advanced; a second read with no new events is quiet.
second = game.log("Brandr")
assert "The Understone Herald" in second # the masthead still prints
assert "still" in second.lower() # the herald-flavoured "all quiet" line
def test_rank_marks_caller(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
game.join("Brandr")
game.join("Sigrun")
game.players["Sigrun"].level = 5
out = game.rank("Brandr")
assert "Brandr" in out and "Sigrun" in out
assert "*" in out # the caller's row is marked
assert "" in out # box-drawing table
# ---------------------------------------------------------------------------
# Rank ★ column: stars live in their own column, so a long name keeps them
# ---------------------------------------------------------------------------
def test_win_stars_column_formats() -> None:
"""Zero is blank, 1..5 render as ★ runs, and >5 collapses to ★xN."""
from understone.game import _win_stars
assert _win_stars(0) == ""
assert _win_stars(1) == ""
assert _win_stars(5) == "★★★★★"
assert _win_stars(7) == "★x7"
def test_long_name_with_one_win_keeps_its_star() -> None:
"""A full 24-char name no longer eats its own ★ (the v0.1 truncation bug).
The name occupied the whole 20-wide field before, clipping the star away;
with a separate stars column the survives beside a maximal name.
"""
from understone.engine.rank import RankEntry
from understone.game import _render_rank_table
name = "X" * 24
rows = _render_rank_table([RankEntry(name=name, level=5, xp=100, gold=50, wins=1)], caller="")
body = "\n".join(rows)
assert name in body # the full name is present
assert "" in body # and so is its star
def test_high_win_count_renders_compact_marker() -> None:
"""Seven wins render as the compact ``★x7`` rather than seven glyphs."""
from understone.engine.rank import RankEntry
from understone.game import _render_rank_table
rows = _render_rank_table([RankEntry(name="Champ", level=9, xp=9, gold=9, wins=7)], caller="")
body = "\n".join(rows)
assert "★x7" in body
assert "★★★★★★★" not in body # not seven literal stars
def test_shared_world_other_player_marker(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
game.join("Brandr")
game.join("Sigrun")
# Stand Sigrun one cell east of Brandr's spawn so she lands in the view.
sig = game.players["Sigrun"]
brandr = game.players["Brandr"]
sig.x, sig.y = brandr.x + 1, brandr.y
out = game.look("Brandr")
assert "" in out # the other player shows as '☻'
# ---------------------------------------------------------------------------
# Bestow (+ cap negative test)
# ---------------------------------------------------------------------------
def test_bestow_grants_gold(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
game.join("Brandr")
player = game.players["Brandr"]
before = player.gold
out = game.bestow("Brandr", "a daring rescue", 10, 0)
assert player.gold == before + 10
assert player.bestow_spent == 10
assert "bestowal" in out.lower()
def test_bestow_heal_charges_only_applied(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
game.join("Brandr")
player = game.players["Brandr"]
player.hp = player.max_hp - 3 # only 3 missing
game.bestow("Brandr", "mercy after a hard fight", 0, 10)
assert player.hp == player.max_hp
# Charged for 3 HP at heal_cost_per_hp, not the requested 10.
assert player.bestow_spent == 3 * game.world.settings.heal_cost_per_hp
def test_bestow_requires_reason(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
game.join("Brandr")
out = game.bestow("Brandr", " ", 10, 0)
assert "reason" in out.lower()
assert game.players["Brandr"].gold == game.world.settings.starting_gold
def test_bestow_requires_nonzero(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
game.join("Brandr")
out = game.bestow("Brandr", "nothing at all", 0, 0)
assert "at least" in out.lower()
def test_bestow_cap_refuses(tmp_path: Path, clock: object) -> None:
"""Pins the bestow cap: an over-budget grant is refused without mutation.
See the module docstring for the revert-and-observe-failure check that
proves this assertion has teeth.
"""
game = _game(tmp_path, clock)
game.join("Brandr")
player = game.players["Brandr"]
budget = game.world.settings.bestow_daily_budget
before_gold = player.gold
out = game.bestow("Brandr", "an absurd windfall", budget + 100, 0)
assert "the fates allow" in out.lower()
# Refused cleanly: no gold moved and no pool spent.
assert player.gold == before_gold
assert player.bestow_spent == 0
def test_bestow_pool_resets_next_day(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
game.join("Brandr")
player = game.players["Brandr"]
game.bestow("Brandr", "first blessing", 20, 0)
assert player.bestow_spent == 20
# Advance the clock past UTC midnight; the next bestow sees a fresh pool.
game.clock = fixed_clock(utc(2026, 6, 13, 0, 5)) # type: ignore[assignment]
game.bestow("Brandr", "a new day's fortune", 20, 0)
assert player.bestow_spent == 20 # reset to 0 then +20, not 40
# ---------------------------------------------------------------------------
# Persistence round-trip through the façade
# ---------------------------------------------------------------------------
def test_state_survives_store_reopen(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
game.join("Brandr")
game.players["Brandr"].x, game.players["Brandr"].y = 35, 25
game.action("Brandr", "fight", "", "")
xp_after = game.players["Brandr"].xp
gold_after = game.players["Brandr"].gold
game.store.close()
world = load_world(PACK)
reopened = Store(tmp_path / "game.db")
revived = Game(world, reopened, clock=clock) # type: ignore[arg-type]
assert revived.players["Brandr"].xp == xp_after
assert revived.players["Brandr"].gold == gold_after
# ---------------------------------------------------------------------------
# Day rollover applies to fight/descend, not just join/bestow
# ---------------------------------------------------------------------------
class _MutableClock:
"""A clock whose reported moment can be advanced between calls."""
def __init__(self, moment: object) -> None:
self.moment = moment
def __call__(self) -> object:
return self.moment
def test_fight_refreshes_budget_across_midnight(tmp_path: Path) -> None:
"""A fight on a new UTC day must reset the budget without re-joining.
Before the fix, _resolve_encounter spent a turn without calling
_ensure_day, so an exhausted player who returned the next day was still
blocked until they happened to re-join.
"""
clk = _MutableClock(utc(2026, 6, 12, 23, 0))
world = load_world(PACK)
store = Store(tmp_path / "game.db")
game = Game(world, store, clock=clk, rng=GameRNG(seed=7)) # type: ignore[arg-type]
game.join("Brandr")
player = game.players["Brandr"]
player.x, player.y = 35, 25 # forest_near zone: an encounter is available
player.turns_left = 0 # spent for the day
daily = game.world.settings.daily_turns
clk.moment = utc(2026, 6, 13, 0, 5) # cross UTC midnight, no re-join
out = game.action("Brandr", "fight", "", "")
assert "spent for today" not in out.lower() # the fresh day let the fight run
assert player.turns_left == daily - 1 # reset to full, then one spent
assert player.xp > 0
assert f"/{daily} ]" in out # footer shows the refreshed budget
def test_descend_refreshes_budget_across_midnight(tmp_path: Path) -> None:
"""Descending on a new UTC day resets the budget without re-joining."""
clk = _MutableClock(utc(2026, 6, 12, 23, 0))
world = load_world(PACK)
store = Store(tmp_path / "game.db")
game = Game(world, store, clock=clk, rng=GameRNG(seed=7)) # type: ignore[arg-type]
game.join("Hero")
player = game.players["Hero"]
# Overwhelming stats so the gauntlet itself never bounces the player.
player.level, player.atk, player.def_ = 20, 200, 100
player.hp = player.max_hp = 500
player.mode = Mode.MENU
player.at_location = "dungeon"
player.turns_left = 0
daily = game.world.settings.daily_turns
clk.moment = utc(2026, 6, 13, 0, 5)
out = game.action("Hero", "descend", "", "")
assert "too weary" not in out.lower()
assert player.turns_left == daily - 1
# ---------------------------------------------------------------------------
# Input hygiene chokepoint (the _sanitize helper)
# ---------------------------------------------------------------------------
#
# Negative-test discipline (security invariant): to prove the control-char
# rejection in Game._sanitize has teeth, the implementer temporarily replaced
# its ``not cleaned.isprintable()`` clause with ``False`` (disabling the
# check) and confirmed test_join_rejects_control_char_name FAILED — the
# injected name created a player row and a public event. The clause was then
# restored. The newline-injection test below is the standing regression for
# that invariant.
def test_join_rejects_control_char_name(tmp_path: Path, clock: object) -> None:
"""A bell/control character in a name is refused with the runes line."""
game = _game(tmp_path, clock)
out = game.join("Bra\x07ndr")
assert "strange runes" in out
assert game.players == {} # no row created
assert game.events == [] # nothing persisted
def test_join_rejects_newline_name_no_persist(tmp_path: Path, clock: object) -> None:
"""An embedded newline (log-injection vector) is refused, nothing written.
The name is kept short so it is the control-char clause not the length
clause that rejects it; this is the standing regression for the
isprintable security invariant documented in the module docstring.
"""
game = _game(tmp_path, clock)
out = game.join("Bra\nndr") # 7 chars: well under the 24 limit
assert "strange runes" in out # the runes (bad-character) refusal, not length
# The security invariant: no player row and no event row escaped the guard.
assert game.players == {}
assert game.events == []
def test_join_rejects_overlong_name(tmp_path: Path, clock: object) -> None:
"""A 25-character name is refused with the narrow-ledger line."""
game = _game(tmp_path, clock)
out = game.join("X" * 25)
assert "ledger is narrow" in out
assert game.players == {}
def test_join_accepts_max_length_name(tmp_path: Path, clock: object) -> None:
"""A 24-character name is exactly at the limit and accepted."""
game = _game(tmp_path, clock)
name = "X" * 24
game.join(name)
assert name in game.players
# ---------------------------------------------------------------------------
# Narrow-ledger width rule (the _sanitize one-column clause, v0.6)
#
# Names/reasons/mail render inside fixed-width frames and tables, so a glyph
# that does not fit a single column would shove a column out of true. The
# sanitizer rejects wide runes and combining marks; a printable-but-wide name
# gets the dedicated narrow-ledger refusal, not the control-char "runes" line.
# ---------------------------------------------------------------------------
def test_join_rejects_wide_cjk_name(tmp_path: Path, clock: object) -> None:
"""A CJK ideograph name is refused with the narrow-ledger line; nothing written."""
game = _game(tmp_path, clock)
out = game.join("")
assert "columns are narrow" in out
assert game.players == {}
assert game.events == []
def test_join_rejects_emoji_name(tmp_path: Path, clock: object) -> None:
"""An emoji in a name (🌲x) is wide and refused with the narrow-ledger line."""
game = _game(tmp_path, clock)
out = game.join("🌲x")
assert "columns are narrow" in out
assert game.players == {}
def test_join_rejects_fullwidth_name(tmp_path: Path, clock: object) -> None:
"""A fullwidth Latin letter () is two columns and refused."""
game = _game(tmp_path, clock)
out = game.join("")
assert "columns are narrow" in out
assert game.players == {}
def test_join_rejects_combining_mark_name(tmp_path: Path, clock: object) -> None:
"""A name with a combining mark (decomposed accent) is refused as wide.
The name is normalised to NFD so the 'o' carries a separate U+0308
combining diaeresis a zero-width code point that desynchronises the
column count. Built explicitly so the source encoding cannot mask it.
"""
game = _game(tmp_path, clock)
decomposed = unicodedata.normalize("NFD", "Bj\u00f6rn")
assert any(unicodedata.combining(ch) for ch in decomposed) # genuinely NFD
out = game.join(decomposed)
assert "columns are narrow" in out
assert game.players == {}
def test_join_accepts_composed_latin_name(tmp_path: Path, clock: object) -> None:
"""A precomposed Latin accent (NFC name) is all single-column and accepted."""
game = _game(tmp_path, clock)
composed = unicodedata.normalize("NFC", "Bj\u00f6rn")
game.join(composed)
assert composed in game.players
def _seed_wide_named_player(db: Path, clock: object, wide_name: str) -> None:
"""Write a stored adventurer whose name is a now-illegal wide rune.
Bypasses ``join`` (which would refuse a wide name at creation) by upserting
a Player row straight through the Store, so the fixture stands in for a save
that predates the narrow-ledger rule. Built by renaming a legitimately-
created hero so every other field stays valid.
"""
from dataclasses import replace
world = load_world(PACK)
seed = Store(db)
game = Game(world, seed, clock=clock, rng=GameRNG(seed=7)) # type: ignore[arg-type]
game.join("Brandr")
base = game.players["Brandr"]
seed.upsert_player(replace(base, name=wide_name))
seed.commit()
seed.close()
def test_join_resumes_stored_wide_name(tmp_path: Path, clock: object) -> None:
"""An existing adventurer with a wide-rune name resumes \u2014 identity is never re-gated.
Resume keys off the exact stored name BEFORE the sanitizer, so a character
whose name predates the narrow-ledger rule is welcomed back rather than
locked out. This is the resume-by-exact-name invariant.
"""
db = tmp_path / "game.db"
wide = "\u9f8d"
_seed_wide_named_player(db, clock, wide)
world = load_world(PACK)
game = Game(world, Store(db), clock=clock, rng=GameRNG(seed=7)) # type: ignore[arg-type]
out = game.join(wide)
assert "Welcome back" in out # resumed, not refused
assert "columns are narrow" not in out
assert wide in game.players
def test_join_still_refuses_new_wide_name(tmp_path: Path, clock: object) -> None:
"""Creation is still gated: a NEW wide name with no stored row is refused.
The resume bypass is exact-name only; a wide name that matches no stored
adventurer falls through to the creation gate and gets the narrow-ledger
refusal, with nothing written.
"""
db = tmp_path / "game.db"
# Seed one wide-named save, then try to CREATE a different wide name.
_seed_wide_named_player(db, clock, "\u9f8d")
world = load_world(PACK)
game = Game(world, Store(db), clock=clock, rng=GameRNG(seed=7)) # type: ignore[arg-type]
out = game.join("\u7363") # a different wide rune \u2014 no stored row for it
assert "columns are narrow" in out
assert "\u7363" not in game.players
def test_bestow_rejects_newline_reason_no_persist(tmp_path: Path, clock: object) -> None:
"""A newline-embedded bestow reason is refused; no event, pool unchanged."""
game = _game(tmp_path, clock)
game.join("Brandr")
player = game.players["Brandr"]
events_before = len(game.events)
out = game.bestow("Brandr", "heroics\nand a forged log line", 10, 0)
assert "plainly-spoken" in out
assert len(game.events) == events_before # no bestow event appended
assert player.bestow_spent == 0 # pool untouched
# ---------------------------------------------------------------------------
# Bestow: heal-only at full HP grants nothing (no empty grant persisted)
# ---------------------------------------------------------------------------
def test_bestow_heal_only_at_full_hp_refused(tmp_path: Path, clock: object) -> None:
"""A heal-only bestow at full HP applies nothing and must not persist."""
game = _game(tmp_path, clock)
game.join("Brandr")
player = game.players["Brandr"]
assert player.hp == player.max_hp # join starts at full health
events_before = len(game.events)
out = game.bestow("Brandr", "a quiet blessing", 0, 10)
assert "already hale" in out
assert len(game.events) == events_before # no "Fortune favours" line written
assert player.bestow_spent == 0 # nothing charged
# ---------------------------------------------------------------------------
# Descend the deep: one rung per descent (see test_descend.py for the ladder)
# ---------------------------------------------------------------------------
def test_descend_fights_one_rung_and_advances(tmp_path: Path, clock: object) -> None:
"""A strong player clears the next rung: one foe fought, rewards banked, depth +1."""
game = _game(tmp_path, clock)
game.join("Hero")
player = game.players["Hero"]
player.level, player.atk, player.def_ = 20, 200, 100
player.hp = player.max_hp = 500
player.mode = Mode.MENU
player.at_location = "dungeon"
before_turns, before_gold, before_xp = player.turns_left, player.gold, player.xp
out = game.action("Hero", "descend", "", "")
# The first rung is the tier-3 guardian (Forest Wolf); deeper rungs do NOT
# appear in one descent — the deep is fought a rung at a time now.
assert "Forest Wolf" in out
assert "Cave Troll" not in out
assert player.deepest_rung == 1
assert player.turns_left == before_turns - 1
assert player.gold > before_gold
assert player.xp > before_xp
def test_descend_bounces_weak_player_to_spawn(tmp_path: Path, clock: object) -> None:
"""A fresh weak player falls on the first rung and wakes at the spawn.
Depth is NOT advanced by a loss, but it persists at whatever it was (here 0).
"""
game = _game(tmp_path, clock)
game.join("Weakling")
player = game.players["Weakling"]
player.mode = Mode.MENU
player.at_location = "dungeon"
out = game.action("Weakling", "descend", "", "")
assert player.hp == 1
assert player.mode is Mode.TILE
assert player.at_location == ""
assert (player.x, player.y) == game.world.spawn
assert player.deepest_rung == 0 # a loss never advances the deep
# Felled by the first rung (the tier-3 Forest Wolf).
assert "Forest Wolf" in out
# ---------------------------------------------------------------------------
# Shop façade: buy / upgrade / sell / heal stat arithmetic
# ---------------------------------------------------------------------------
def test_shop_buy_upgrade_sell_heal_cycle(tmp_path: Path, clock: object) -> None:
"""Equip deltas apply once on buy/upgrade and unwind cleanly on sell."""
game = _game(tmp_path, clock)
game.join("Brandr")
player = game.players["Brandr"]
player.gold = 1000
player.mode = Mode.MENU
player.at_location = "shop"
short_sword = game.world.item_by_id("short_sword")
war_axe = game.world.item_by_id("war_axe")
starter = game.world.item_by_id(game.world.settings.starting_weapon)
assert short_sword is not None and war_axe is not None and starter is not None
starter_atk = player.atk # 3 base + rusty dagger bonus
# Buy the short sword: gold falls by its price, atk rises by the delta.
gold0 = player.gold
game.action("Brandr", "buy", "", "short_sword")
assert player.gold == gold0 - short_sword.price
assert player.atk == starter_atk + (short_sword.atk - starter.atk)
atk_with_sword = player.atk
# Upgrade to the war axe: atk reflects the difference, not a double-add.
gold1 = player.gold
game.action("Brandr", "buy", "", "war_axe")
assert player.gold == gold1 - war_axe.price
assert player.atk == atk_with_sword + (war_axe.atk - short_sword.atk)
# Sell the war axe: half-price refund, atk falls back to the starter bonus.
gold2 = player.gold
game.action("Brandr", "sell", "", "")
assert player.gold == gold2 + war_axe.price // 2
assert player.atk == starter_atk
# Heal at the shrine: HP restored, gold debited per missing point.
player.mode = Mode.MENU
player.at_location = "healer"
player.hp = player.max_hp - 5
per_hp = game.world.settings.heal_cost_per_hp
gold3 = player.gold
game.action("Brandr", "heal", "", "")
assert player.hp == player.max_hp
assert player.gold == gold3 - 5 * per_hp
def test_sell_starter_weapon_refused(tmp_path: Path, clock: object) -> None:
"""The starter blade is unsellable regardless of price (no free-gold loop)."""
game = _game(tmp_path, clock)
game.join("Brandr")
player = game.players["Brandr"]
assert player.weapon_id == game.world.settings.starting_weapon
player.mode = Mode.MENU
player.at_location = "shop"
gold_before = player.gold
out = game.action("Brandr", "sell", "", "")
assert "nothing worth selling" in out.lower()
assert player.gold == gold_before
# ---------------------------------------------------------------------------
# Bounded in-memory event tail (full history stays in SQLite)
# ---------------------------------------------------------------------------
def test_event_tail_is_capped_but_log_still_works(tmp_path: Path, clock: object) -> None:
"""Loading caps the resident tail; door_log still serves recent events."""
from understone.engine.log import since
from understone.game import EVENT_TAIL_KEEP
db = tmp_path / "game.db"
seed_store = Store(db)
last_id = 0
for i in range(EVENT_TAIL_KEEP + 50):
last_id = seed_store.insert_event("t", "sys", "note", f"event {i}")
seed_store.commit()
seed_store.close()
world = load_world(PACK)
game = Game(world, Store(db), clock=clock, rng=GameRNG(seed=7)) # type: ignore[arg-type]
# Only the most recent EVENT_TAIL_KEEP events are resident in memory.
assert len(game.events) == EVENT_TAIL_KEEP
assert game.events[-1].event_id == last_id
# door_log still reports events after a recent cursor.
recent_cursor = game.events[-3].event_id
game.join("Brandr")
game.players["Brandr"].log_cursor = recent_cursor
out = game.log("Brandr")
assert "The Understone Herald" in out # broadsheet masthead
assert "since your last visit" in out
fresh, new_cursor = since(game.events, recent_cursor)
assert fresh # there are events past the cursor
assert new_cursor == game.events[-1].event_id
def test_private_mail_survives_tail_eviction(tmp_path: Path, clock: object) -> None:
"""A private note older than the resident tail is still delivered (durable mail).
Public history that falls off the in-memory tail is gone by design (the
broadsheet does not keep), but mail must not be: a note left while the
recipient was away has to surface however many public events have since
pushed it out of the tail. A third player whose cursor also predates the
note must still never see it, because it was never theirs.
"""
from understone.persistence import EVENT_TAIL_KEEP
db = tmp_path / "game.db"
store = Store(db)
game = Game(load_world(PACK), store, clock=clock, rng=GameRNG(seed=7)) # type: ignore[arg-type]
game.join("Scribe")
game.join("Reader")
game.join("Bystander")
# Scribe leaves Reader a private note; neither Reader nor Bystander reads it.
secret = "the cellar key is under the third barrel"
game.action("Scribe", "post", "Reader", "", secret)
# Flood the feed past the tail bound so the note is evicted from memory.
for i in range(EVENT_TAIL_KEEP + 20):
store.insert_event("t", "sys", "note", f"broadsheet filler {i}")
store.commit()
store.close()
# Reopen: only the newest tail is resident, so the note now lives in the gap.
reopened = Store(db)
revived = Game(load_world(PACK), reopened, clock=clock, rng=GameRNG(seed=7)) # type: ignore[arg-type]
note_id = next(
e.event_id
for e in reopened.targeted_events_since("Reader", 0) # note: from SQLite, not the tail
if secret in e.text
)
assert note_id < revived.events[0].event_id # the note really is past the tail
# The recipient still sees the note, backfilled from SQLite...
reader_log = revived.log("Reader")
assert secret in reader_log
assert "While you were away" in reader_log
# ...but a third player never does, even though their cursor predates it too.
third_log = revived.log("Bystander")
assert secret not in third_log
reopened.close()
+118
View File
@@ -0,0 +1,118 @@
"""XP curve, level-up, and restorative-maths tests.
Pins the threshold edges (at / just below / just above), a multi-level
jump from a single award, the exact growth table, the inn's flat-rate
full heal with affordability gating, and the healer's per-HP cost maths.
"""
from __future__ import annotations
from tests.conftest import DEFAULT_SETTINGS, make_player, make_settings
from understone.engine.leveling import apply_xp, heal, rest, xp_for_level
# Default curve is 100 * (n-1)*n/2 cumulative:
# L2 = 100, L3 = 300, L4 = 600, L5 = 1000.
def test_xp_curve_thresholds() -> None:
assert xp_for_level(1, DEFAULT_SETTINGS) == 0
assert xp_for_level(2, DEFAULT_SETTINGS) == 100
assert xp_for_level(3, DEFAULT_SETTINGS) == 300
assert xp_for_level(4, DEFAULT_SETTINGS) == 600
assert xp_for_level(5, DEFAULT_SETTINGS) == 1000
def test_just_below_threshold_does_not_level() -> None:
player = make_player(level=1, xp=0, hp=20, max_hp=20)
gains = apply_xp(player, 99, DEFAULT_SETTINGS)
assert gains == []
assert player.level == 1
def test_exact_threshold_levels_once() -> None:
player = make_player(level=1, xp=0, hp=10, max_hp=20, atk=5, def_=1)
gains = apply_xp(player, 100, DEFAULT_SETTINGS)
assert len(gains) == 1
assert player.level == 2
# Growth table applied and a full heal granted on level-up.
assert player.max_hp == 26
assert player.atk == 7
assert player.def_ == 2
assert player.hp == player.max_hp
def test_just_above_threshold_levels_once() -> None:
player = make_player(level=1, xp=0)
gains = apply_xp(player, 101, DEFAULT_SETTINGS)
assert len(gains) == 1
assert player.level == 2
assert player.xp == 101
def test_single_award_can_jump_multiple_levels() -> None:
player = make_player(level=1, xp=0, max_hp=20, atk=5, def_=1)
gains = apply_xp(player, 600, DEFAULT_SETTINGS)
# 600 cumulative reaches level 4 (L2=100, L3=300, L4=600).
assert player.level == 4
assert [g.new_level for g in gains] == [2, 3, 4]
# Three levels of growth stacked.
assert player.max_hp == 20 + 3 * 6
assert player.atk == 5 + 3 * 2
assert player.def_ == 1 + 3 * 1
def test_growth_table_respects_settings() -> None:
settings = make_settings(growth_max_hp=10, growth_atk=3, growth_def=2, xp_base=50)
player = make_player(level=1, xp=0, max_hp=20, atk=5, def_=1)
apply_xp(player, 50, settings) # L2 at 50 with xp_base=50
assert player.level == 2
assert player.max_hp == 30
assert player.atk == 8
assert player.def_ == 3
# ---------------------------------------------------------------------------
# rest (inn) and heal (healer)
# ---------------------------------------------------------------------------
def test_rest_full_heals_and_charges() -> None:
player = make_player(hp=5, max_hp=20, gold=50)
assert rest(player, cost=15) is True
assert player.hp == 20
assert player.gold == 35
def test_rest_refused_when_unaffordable() -> None:
player = make_player(hp=5, max_hp=20, gold=10)
assert rest(player, cost=15) is False
assert player.hp == 5
assert player.gold == 10
def test_heal_charges_only_for_hp_restored() -> None:
player = make_player(hp=15, max_hp=20, gold=100)
result = heal(player, amount=10, cost_per_hp=2)
# Only 5 HP were missing.
assert result.healed == 5
assert result.cost == 10
assert player.hp == 20
assert player.gold == 90
def test_heal_bounded_by_affordability() -> None:
player = make_player(hp=2, max_hp=20, gold=7)
result = heal(player, amount=10, cost_per_hp=2)
# 7 gold buys 3 HP at 2/hp.
assert result.healed == 3
assert result.cost == 6
assert player.hp == 5
assert player.gold == 1
def test_heal_noop_when_full() -> None:
player = make_player(hp=20, max_hp=20, gold=100)
result = heal(player, amount=10, cost_per_hp=2)
assert result.healed == 0
assert result.cost == 0
assert player.gold == 100
@@ -0,0 +1,288 @@
"""End-to-end MCP integration test — the only test that touches the network.
Boots the real Understone FastMCP app (backed by a temp DB) in a uvicorn
thread, then drives it over the real streamable-HTTP wire with the real MCP
client: initialize, list_tools (all nine door_* names), join, look. A second
client session joins a second adventurer in the SAME process and world, and
the first player's view then shows the '&' other-player marker — proving the
shared-world, single-process contract over a real wire.
A second test drives the read-only Watch routes that ride inside the same app:
GET /watch (the HTML page), /watch/world.json (the static map), and
/watch/state.json (the live snapshot) confirming the spectator endpoints
serve real world data alongside a working /mcp without breaking either.
"""
from __future__ import annotations
import asyncio
import socket
import threading
import time
from typing import TYPE_CHECKING, Any
import httpx
import pytest
import uvicorn
from mcp import ClientSession
from mcp.client.streamable_http import streamable_http_client
from understone import server as understone_server
if TYPE_CHECKING:
from pathlib import Path
PACK = str(understone_server.PACKAGED_WORLD_DIR)
def _find_free_port() -> int:
s = socket.socket()
s.bind(("127.0.0.1", 0))
port = s.getsockname()[1]
s.close()
return int(port)
def _build_server(port: int, db_path: str) -> uvicorn.Server:
app = understone_server.create_app(db_path, PACK)
config = uvicorn.Config(app, host="127.0.0.1", port=port, log_level="warning", access_log=False)
return uvicorn.Server(config)
def _wait_ready(port: int, timeout: float = 5.0) -> None:
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
try:
with socket.create_connection(("127.0.0.1", port), timeout=0.5):
return
except OSError:
time.sleep(0.05)
raise TimeoutError(f"understone server at 127.0.0.1:{port} not ready after {timeout}s")
@pytest.fixture
def live_server(tmp_path: Path) -> Any:
"""Boot the real Understone app in a background uvicorn thread."""
port = _find_free_port()
db_path = str(tmp_path / "wire.db")
server = _build_server(port, db_path)
def _run() -> None:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(server.serve())
thread = threading.Thread(target=_run, daemon=True, name="understone-itest")
thread.start()
try:
_wait_ready(port)
yield f"http://127.0.0.1:{port}/mcp"
finally:
server.should_exit = True
thread.join(timeout=5)
# create_app installed a module-level game whose Store holds an open
# SQLite connection; close it and clear the singleton so the next test
# builds its own rather than inheriting this temp DB.
if understone_server._GAME is not None:
understone_server._GAME.store.close()
understone_server._GAME = None
# FastMCP caches a StreamableHTTPSessionManager on the module-level mcp
# singleton and refuses a second lifespan .run() on the same instance.
# Reset it so each fixture instance boots a fresh session manager (the
# production server only ever runs one). Without this, a second
# fixture-using test fails on "run() can only be called once".
understone_server.mcp._session_manager = None
async def _call_text(session: ClientSession, name: str, arguments: dict[str, Any]) -> str:
result = await session.call_tool(name, arguments)
chunks = [block.text for block in result.content if getattr(block, "type", None) == "text"]
return "\n".join(chunks)
async def _drive(url: str) -> dict[str, Any]:
"""Run the full client conversation and return observations."""
observations: dict[str, Any] = {}
async with (
streamable_http_client(url) as (read, write, _get_session_id),
ClientSession(read, write) as session,
):
await session.initialize()
tools = await session.list_tools()
observations["tool_names"] = sorted(t.name for t in tools.tools)
observations["join_one"] = await _call_text(session, "door_join", {"player": "Brandr"})
observations["look_one_before"] = await _call_text(
session, "door_look", {"player": "Brandr"}
)
# A SECOND, independent session joins a second adventurer in the same world.
async with (
streamable_http_client(url) as (read, write, _get_session_id),
ClientSession(read, write) as session,
):
await session.initialize()
# Place player two adjacent to player one so they share the view.
await _call_text(session, "door_join", {"player": "Sigrun"})
await _call_text(
session, "door_move", {"player": "Sigrun", "heading": "east", "distance": 1}
)
# Back as player one: the shared world now shows the other adventurer.
async with (
streamable_http_client(url) as (read, write, _get_session_id),
ClientSession(read, write) as session,
):
await session.initialize()
observations["look_one_after"] = await _call_text(
session, "door_look", {"player": "Brandr"}
)
observations["rank"] = await _call_text(session, "door_rank", {"player": "Brandr"})
return observations
def test_mcp_end_to_end(live_server: str) -> None:
obs = asyncio.run(_drive(live_server))
# All nine tools are advertised over the wire.
expected = {
"door_help",
"door_join",
"door_status",
"door_look",
"door_move",
"door_action",
"door_log",
"door_rank",
"door_bestow",
}
assert set(obs["tool_names"]) == expected
# The join + look frames are real ASCII map frames.
assert "@" in obs["join_one"]
look_before = obs["look_one_before"]
assert "@" in look_before
assert "" in look_before and "" in look_before
# Shared-world proof: after player two joins next door, player one sees '☻'.
assert "" in obs["look_one_after"]
# And the leaderboard lists both adventurers (one process, one world).
assert "Brandr" in obs["rank"]
assert "Sigrun" in obs["rank"]
def _watch_base(mcp_url: str) -> str:
"""Derive the app root (where /watch lives) from the /mcp endpoint URL."""
return mcp_url[: -len("/mcp")] if mcp_url.endswith("/mcp") else mcp_url
async def _join_over_mcp(mcp_url: str, name: str) -> None:
"""Sign one adventurer in over the real MCP wire (so state.json sees them)."""
async with (
streamable_http_client(mcp_url) as (read, write, _get_session_id),
ClientSession(read, write) as session,
):
await session.initialize()
await _call_text(session, "door_join", {"player": name})
def test_watch_routes_serve_world_state(live_server: str) -> None:
base = _watch_base(live_server)
# The MCP join writes the player into the shared world the routes read.
asyncio.run(_join_over_mcp(live_server, "Watcher"))
with httpx.Client(timeout=5.0) as client:
page = client.get(f"{base}/watch")
world = client.get(f"{base}/watch/world.json")
state = client.get(f"{base}/watch/state.json")
# The page is real HTML carrying the static masthead.
assert page.status_code == 200
assert page.headers["content-type"].startswith("text/html")
assert "Understone — Live Watch" in page.text
# The static world payload matches the loaded world.
assert world.status_code == 200
world_body = world.json()
assert world_body["width"] == 96
assert world_body["height"] == 48
assert len(world_body["glyph_rows"]) == world_body["height"]
assert all(len(row) == world_body["width"] for row in world_body["glyph_rows"])
# The live snapshot lists the adventurer who joined over MCP.
assert state.status_code == 200
state_body = state.json()
names = {p["name"] for p in state_body["players"]}
assert "Watcher" in names
def test_watch_routes_coexist_with_mcp(live_server: str) -> None:
"""The custom routes don't shadow /mcp: tool calls still work alongside them."""
base = _watch_base(live_server)
async def _drive_both() -> tuple[str, int]:
async with (
streamable_http_client(live_server) as (read, write, _get_session_id),
ClientSession(read, write) as session,
):
await session.initialize()
joined = await _call_text(session, "door_join", {"player": "Coexist"})
with httpx.Client(timeout=5.0) as client:
status = client.get(f"{base}/watch/state.json").status_code
return joined, status
joined, watch_status = asyncio.run(_drive_both())
assert "@" in joined # the MCP tool still returns a real frame
assert watch_status == 200 # and the watch route still answers
def test_streamable_http_host_gate_off_localhost() -> None:
"""A non-localhost bind must accept remote `Host` headers on /mcp.
REGRESSION: FastMCP freezes DNS-rebinding protection (a localhost-only Host
allowlist) at CONSTRUCTION, and ``server`` builds its FastMCP at import with
the default 127.0.0.1 host. A 0.0.0.0/LAN bind therefore answered TCP and
`/watch` but 421'd `/mcp` for every remote node ("Invalid Host header").
``_serve`` drops the allowlist when bound off localhost; this pins the
mechanism a default instance rejects a foreign Host, a protection-disabled
one accepts it (a 421 in the second case is the bug returning).
Uses fresh FastMCP instances (not the module singleton) so there is no
shared-state or app-cache coupling with the live-server tests above.
"""
from mcp.server.fastmcp import FastMCP
from mcp.server.transport_security import TransportSecuritySettings
from starlette.testclient import TestClient
foreign = {
"Host": "192.168.0.239:8077",
"Accept": "application/json, text/event-stream",
"Content-Type": "application/json",
}
init = {
"jsonrpc": "2.0",
"id": 1,
"method": "initialize",
"params": {
"protocolVersion": "2025-03-26",
"capabilities": {},
"clientInfo": {"name": "probe", "version": "0"},
},
}
# Default (localhost-baked allowlist) — a remote Host is refused.
locked = FastMCP("hostgate-locked")
with TestClient(locked.streamable_http_app()) as client:
assert client.post("/mcp", headers=foreign, json=init).status_code == 421
# Protection disabled (what _serve does off localhost) — remote Host accepted.
opened = FastMCP("hostgate-open")
opened.settings.transport_security = TransportSecuritySettings(
enable_dns_rebinding_protection=False
)
with TestClient(opened.streamable_http_app()) as client:
resp = client.post("/mcp", headers=foreign, json=init)
assert resp.status_code != 421, f"remote Host still rejected: {resp.status_code} {resp.text}"
+336
View File
@@ -0,0 +1,336 @@
"""Movement resolution tests.
Covers edge clipping on all four sides, blocking terrain, the two input
forms (``"NNEE"`` vs heading+distance) and their equivalence, location
entry flipping to MENU, the MAX_STEPS cap, and a stubbed always-encounter
RNG interrupting a walk with a pending fight.
"""
from __future__ import annotations
from tests.conftest import (
FOREST,
GRASS,
WALL,
WATER,
LocationDef,
Zone,
make_player,
make_world,
)
from understone.engine.models import Mode, WorldEvent
from understone.engine.movement import MAX_STEPS, parse_directions, resolve_move
from understone.engine.rng import GameRNG
class _NeverRNG(GameRNG):
"""An RNG whose chance() never fires (no wandering encounters)."""
def __init__(self) -> None:
super().__init__(seed=0)
def chance(self, probability: float) -> bool: # noqa: ARG002
return False
class _AlwaysRNG(GameRNG):
"""An RNG whose chance() always fires (forces an encounter).
The seed still drives ``weighted_index``/``randint``, so different seeds
select different event rows while every encounter roll fires.
"""
def __init__(self, seed: int = 0) -> None:
super().__init__(seed=seed)
def chance(self, probability: float) -> bool: # noqa: ARG002
return True
# ---------------------------------------------------------------------------
# parse_directions
# ---------------------------------------------------------------------------
def test_parse_steps_string() -> None:
assert parse_directions("NNEE", "", 1) == ["N", "N", "E", "E"]
def test_parse_heading_distance() -> None:
assert parse_directions("", "east", 3) == ["E", "E", "E"]
def test_parse_clamps_to_max_steps() -> None:
assert parse_directions("NNNNNNNNNNNN", "", 1) == ["N"] * MAX_STEPS
assert parse_directions("", "north", 99) == ["N"] * MAX_STEPS
def test_parse_rejects_unknown_direction() -> None:
try:
parse_directions("NQ", "", 1)
except ValueError as exc:
assert "Q" in str(exc)
else: # pragma: no cover - failure path
raise AssertionError("expected ValueError")
# ---------------------------------------------------------------------------
# Edge clipping (all four sides)
# ---------------------------------------------------------------------------
def test_clip_north_edge() -> None:
world = make_world()
player = make_player(x=5, y=0)
result = resolve_move(world, player, _NeverRNG(), heading="north", distance=3)
assert player.y == 0
assert result.steps_taken == 0
assert result.blocked
def test_clip_south_edge() -> None:
world = make_world()
player = make_player(x=5, y=10)
result = resolve_move(world, player, _NeverRNG(), heading="south", distance=3)
assert player.y == 10
assert result.blocked
def test_clip_west_edge() -> None:
world = make_world()
player = make_player(x=0, y=5)
result = resolve_move(world, player, _NeverRNG(), heading="west", distance=3)
assert player.x == 0
assert result.blocked
def test_clip_east_edge() -> None:
world = make_world()
player = make_player(x=10, y=5)
result = resolve_move(world, player, _NeverRNG(), heading="east", distance=3)
assert player.x == 10
assert result.blocked
def test_partial_move_then_clip() -> None:
world = make_world()
player = make_player(x=8, y=5)
result = resolve_move(world, player, _NeverRNG(), heading="east", distance=5)
# 8 -> 9 -> 10, then edge.
assert player.x == 10
assert result.steps_taken == 2
assert result.blocked
# ---------------------------------------------------------------------------
# Blocking terrain
# ---------------------------------------------------------------------------
def test_blocked_by_wall() -> None:
grid = [[GRASS for _ in range(11)] for _ in range(11)]
grid[5][6] = WALL
world = make_world(grid=grid)
player = make_player(x=5, y=5)
result = resolve_move(world, player, _NeverRNG(), heading="east", distance=2)
assert player.x == 5
assert result.blocked
assert "wall" in result.blocked_reason
def test_blocked_by_water() -> None:
grid = [[GRASS for _ in range(11)] for _ in range(11)]
grid[4][5] = WATER
world = make_world(grid=grid)
player = make_player(x=5, y=5)
result = resolve_move(world, player, _NeverRNG(), heading="north", distance=2)
assert player.y == 5
assert result.blocked
assert "water" in result.blocked_reason
# ---------------------------------------------------------------------------
# Input-form equivalence and direction correctness
# ---------------------------------------------------------------------------
def test_nnee_lands_at_expected_cell() -> None:
world = make_world()
player = make_player(x=5, y=5)
resolve_move(world, player, _NeverRNG(), steps="NNEE")
# Two north (y-2), two east (x+2).
assert (player.x, player.y) == (7, 3)
def test_heading_equivalent_to_steps() -> None:
world_a = make_world()
player_a = make_player(x=5, y=5)
resolve_move(world_a, player_a, _NeverRNG(), steps="EEE")
world_b = make_world()
player_b = make_player(x=5, y=5)
resolve_move(world_b, player_b, _NeverRNG(), heading="east", distance=3)
assert (player_a.x, player_a.y) == (player_b.x, player_b.y)
def test_max_steps_truncates_long_walk() -> None:
world = make_world(width=40, height=11)
player = make_player(x=0, y=5)
result = resolve_move(world, player, _NeverRNG(), heading="east", distance=99)
assert result.steps_taken == MAX_STEPS
assert player.x == MAX_STEPS
# ---------------------------------------------------------------------------
# Location entry flips to MENU
# ---------------------------------------------------------------------------
def test_entering_location_flips_menu_mode() -> None:
loc = LocationDef(
key="inn",
kind="inn",
name="The Sleeping Drake",
x=7,
y=5,
glyph="I",
color="town",
actions=("rest", "leave"),
)
world = make_world(locations=[loc])
player = make_player(x=5, y=5)
result = resolve_move(world, player, _NeverRNG(), heading="east", distance=4)
assert player.mode is Mode.MENU
assert player.at_location == "inn"
assert result.entered_location == "inn"
# Stopped on the door at x=7 even though distance asked for 4.
assert (player.x, player.y) == (7, 5)
# ---------------------------------------------------------------------------
# Encounter interrupt
# ---------------------------------------------------------------------------
def test_always_encounter_stops_with_pending_fight() -> None:
grid = [[FOREST for _ in range(11)] for _ in range(11)]
zone = Zone(key="wood", x0=0, y0=0, x1=10, y1=10, tier_lo=1, tier_hi=2)
world = make_world(grid=grid, zones=[zone])
player = make_player(x=5, y=5)
result = resolve_move(world, player, _AlwaysRNG(), heading="east", distance=5)
assert result.pending_fight == (1, 2)
# The encounter fires on the first entered cell.
assert result.steps_taken == 1
assert player.x == 6
def test_no_zone_means_no_encounter() -> None:
grid = [[FOREST for _ in range(11)] for _ in range(11)]
world = make_world(grid=grid, zones=[])
player = make_player(x=5, y=5)
result = resolve_move(world, player, _AlwaysRNG(), heading="east", distance=3)
assert result.pending_fight is None
assert result.steps_taken == 3
# ---------------------------------------------------------------------------
# Weighted non-combat overworld events (v0.2)
# ---------------------------------------------------------------------------
def _event_world(*events: WorldEvent) -> object:
"""An all-forest, fully-zoned world carrying a crafted event table."""
grid = [[FOREST for _ in range(11)] for _ in range(11)]
zone = Zone(key="wood", x0=0, y0=0, x1=10, y1=10, tier_lo=1, tier_hi=2)
return make_world(grid=grid, zones=[zone], events=list(events))
def test_event_fight_stops_the_walk() -> None:
"""A fight-kind event sets pending_fight and halts the walk like v0.1."""
world = _event_world(WorldEvent("fight", 1, "", 0, 0))
player = make_player(x=5, y=5)
result = resolve_move(world, player, _AlwaysRNG(), heading="east", distance=5)
assert result.pending_fight == (1, 2)
assert result.event is None
assert result.steps_taken == 1 # stopped on the first triggering cell
def test_event_gold_credits_and_continues() -> None:
"""A gold event credits the rolled amount and does NOT stop the walk."""
world = _event_world(WorldEvent("gold", 1, "a coin-purse", 5, 5))
player = make_player(x=5, y=5, gold=10)
result = resolve_move(world, player, _AlwaysRNG(), heading="east", distance=3)
assert result.event is not None
assert result.event.kind == "gold"
assert result.event.amount == 5 # min == max == 5, so deterministic
assert player.gold == 15
assert result.pending_fight is None
assert result.steps_taken == 3 # the walk ran to completion
def test_event_heal_caps_at_max_hp() -> None:
"""A heal event never overfills: hp is clamped to max_hp."""
world = _event_world(WorldEvent("heal", 1, "a spring", 50, 50))
player = make_player(x=5, y=5, hp=18, max_hp=20)
result = resolve_move(world, player, _AlwaysRNG(), heading="east", distance=1)
assert player.hp == 20 # +50 requested, capped at the 2 missing
assert result.event is not None and result.event.amount == 2
def test_event_trap_floors_hp_at_one_and_spares_gold() -> None:
"""A trap event never kills (floors at 1 HP) and never touches gold."""
world = _event_world(WorldEvent("trap", 1, "old briars", 500, 500))
player = make_player(x=5, y=5, hp=10, max_hp=20, gold=42)
result = resolve_move(world, player, _AlwaysRNG(), heading="east", distance=1)
assert player.hp == 1 # huge trap, but floored
assert player.gold == 42 # gold untouched
assert result.event is not None and result.event.amount == 9 # only 9 could be taken
def test_event_lore_mutates_nothing() -> None:
"""A lore event changes no state and reports a zero amount."""
world = _event_world(WorldEvent("lore", 1, "an old waystone", 0, 0))
player = make_player(x=5, y=5, hp=15, max_hp=20, gold=7)
before = (player.hp, player.gold)
result = resolve_move(world, player, _AlwaysRNG(), heading="east", distance=2)
assert (player.hp, player.gold) == before
assert result.event is not None and result.event.kind == "lore"
assert result.event.amount == 0
assert result.steps_taken == 2
def test_at_most_one_event_per_walk() -> None:
"""Once any event fires, no further cells roll for the rest of the walk.
Two distinct gold rolls would credit 2 gold (1 each); a single fired event
credits exactly 1, proving the walk stops rolling after the first trigger.
"""
world = _event_world(WorldEvent("gold", 1, "a coin", 1, 1))
player = make_player(x=5, y=5, gold=0)
resolve_move(world, player, _AlwaysRNG(), heading="east", distance=5)
assert player.gold == 1 # exactly one event, not five
def test_each_event_kind_reachable_with_crafted_table() -> None:
"""Equal weights make every kind in a crafted table reachable from movement."""
table = [
WorldEvent("fight", 1, "", 0, 0),
WorldEvent("gold", 1, "g", 1, 1),
WorldEvent("heal", 1, "h", 1, 1),
WorldEvent("trap", 1, "t", 1, 1),
WorldEvent("lore", 1, "l", 0, 0),
]
zone = Zone(key="wood", x0=0, y0=0, x1=0, y1=0, tier_lo=1, tier_hi=2)
grid = [[FOREST for _ in range(11)] for _ in range(11)]
world = make_world(grid=grid, zones=[zone], events=table)
seen: set[str] = set()
for seed in range(60):
player = make_player(x=0, y=1, hp=10, max_hp=20) # one step north into the zone cell
result = resolve_move(world, player, _AlwaysRNG(seed), steps="N")
if result.pending_fight is not None:
seen.add("fight")
elif result.event is not None:
seen.add(result.event.kind)
assert seen == {"fight", "gold", "heal", "trap", "lore"}
+9
View File
@@ -0,0 +1,9 @@
"""Smoke test for the packaging skeleton."""
from __future__ import annotations
import understone
def test_version_present() -> None:
assert understone.__version__ == "0.10.0"
@@ -0,0 +1,269 @@
"""SQLite persistence tests.
Covers idempotent schema init, a full player round-trip through every
column (including ``def_``, ``turn_day``, ``log_cursor`` and the bestow
fields), event append with cursor-based catch-up, leaderboard tie-breaks,
and that WAL journaling is active.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from tests.conftest import make_player
from understone.engine.log import since
from understone.engine.models import Mode
from understone.persistence import Store
if TYPE_CHECKING:
from pathlib import Path
def _store(tmp_path: Path) -> Store:
return Store(tmp_path / "understone.db")
def test_schema_init_is_idempotent(tmp_path: Path) -> None:
db = tmp_path / "understone.db"
Store(db).close()
# Re-opening the same file must not error or duplicate schema.
second = Store(db)
assert second.get_meta("schema_version") == "1"
second.close()
def test_wal_mode_active(tmp_path: Path) -> None:
store = _store(tmp_path)
assert store.journal_mode().lower() == "wal"
store.close()
def test_player_round_trip_all_columns(tmp_path: Path) -> None:
store = _store(tmp_path)
player = make_player(
name="Brandr",
x=12,
y=7,
hp=18,
max_hp=26,
level=3,
xp=305,
gold=88,
atk=9,
def_=4,
weapon_id="short_sword",
armor_id="leather_armor",
turns_left=6,
turn_day=739_400,
mode=Mode.MENU,
at_location="inn",
log_cursor=42,
bestow_spent=15,
bestow_day=739_400,
posts_sent=3,
post_day=739_400,
gambles=2,
gamble_day=739_400,
banked=420,
)
store.upsert_player(player)
store.commit()
store.close()
reopened = _store(tmp_path)
players, _ = reopened.load_all()
loaded = players["Brandr"]
assert loaded == player
assert loaded.banked == 420
# Spot-check the fields most prone to silent drop.
assert loaded.def_ == 4
assert loaded.turn_day == 739_400
assert loaded.log_cursor == 42
assert loaded.bestow_spent == 15
assert loaded.bestow_day == 739_400
assert loaded.mode is Mode.MENU
# The v0.5 social columns survive the round-trip too.
assert loaded.posts_sent == 3
assert loaded.post_day == 739_400
assert loaded.gambles == 2
assert loaded.gamble_day == 739_400
reopened.close()
def test_event_target_round_trips(tmp_path: Path) -> None:
"""A targeted (private) event keeps its target across a reopen; public is ''."""
store = _store(tmp_path)
pub = store.insert_event("t1", "Brandr", "join", "set out")
priv = store.insert_event("t2", "Sigrun", "ambushed", "robbed in your sleep", "Brandr")
store.commit()
store.close()
reopened = _store(tmp_path)
_, events = reopened.load_all()
by_id = {e.event_id: e for e in events}
assert by_id[pub].target == "" # public stays empty
assert by_id[priv].target == "Brandr" # private keeps its recipient
reopened.close()
def test_ambush_table_per_day_uniqueness(tmp_path: Path) -> None:
"""The ambushes PK is (attacker, target, day): one row per pair per day."""
store = _store(tmp_path)
day = 739_400
assert store.has_ambushed("Brandr", "Sigrun", day) is False
store.record_ambush("Brandr", "Sigrun", day)
store.commit()
assert store.has_ambushed("Brandr", "Sigrun", day) is True
# A second record for the same pair/day is a no-op (INSERT OR IGNORE):
# the duplicate must not raise and must not add a row.
store.record_ambush("Brandr", "Sigrun", day)
store.commit()
rows = store._conn.execute(
"SELECT COUNT(*) AS n FROM ambushes WHERE attacker=? AND target=? AND day=?",
("Brandr", "Sigrun", day),
).fetchone()
assert rows["n"] == 1
# A new day is a fresh attempt; the old day stays recorded.
assert store.has_ambushed("Brandr", "Sigrun", day + 1) is False
store.record_ambush("Brandr", "Sigrun", day + 1)
store.commit()
assert store.has_ambushed("Brandr", "Sigrun", day) is True
assert store.has_ambushed("Brandr", "Sigrun", day + 1) is True
store.close()
def test_upsert_updates_existing_row(tmp_path: Path) -> None:
store = _store(tmp_path)
player = make_player(name="Sigrun", gold=10)
store.upsert_player(player)
store.commit()
player.gold = 999
store.upsert_player(player)
store.commit()
store.close()
reopened = _store(tmp_path)
players, _ = reopened.load_all()
assert players["Sigrun"].gold == 999
assert len(players) == 1
reopened.close()
def test_event_append_and_since_cursor(tmp_path: Path) -> None:
store = _store(tmp_path)
id1 = store.insert_event("t1", "Brandr", "fight", "slew a rat")
id2 = store.insert_event("t2", "Sigrun", "bestow", "blessed with gold")
store.commit()
store.close()
reopened = _store(tmp_path)
_, events = reopened.load_all()
assert [e.event_id for e in events] == [id1, id2]
# Catch up from a cursor before both, then advance past the first.
fresh, cursor = since(events, 0)
assert len(fresh) == 2
assert cursor == id2
after_first, cursor2 = since(events, id1)
assert [e.event_id for e in after_first] == [id2]
assert cursor2 == id2
nothing, cursor3 = since(events, id2)
assert nothing == []
assert cursor3 == id2
reopened.close()
def test_top_ranks_tie_breaks(tmp_path: Path) -> None:
store = _store(tmp_path)
# Same level: higher XP ranks first; equal XP breaks by name ascending.
store.upsert_player(make_player(name="Carol", level=5, xp=1200, gold=10))
store.upsert_player(make_player(name="Alice", level=5, xp=1500, gold=10))
store.upsert_player(make_player(name="Bob", level=5, xp=1500, gold=10))
store.upsert_player(make_player(name="Dave", level=4, xp=9999, gold=10))
store.commit()
ranks = store.top_ranks(limit=10)
assert [r.name for r in ranks] == ["Alice", "Bob", "Carol", "Dave"]
store.close()
def test_top_ranks_honours_limit(tmp_path: Path) -> None:
store = _store(tmp_path)
for i in range(15):
store.upsert_player(make_player(name=f"P{i:02d}", level=i, xp=i * 10))
store.commit()
ranks = store.top_ranks(limit=10)
assert len(ranks) == 10
# Highest level first.
assert ranks[0].name == "P14"
store.close()
def test_meta_round_trip(tmp_path: Path) -> None:
store = _store(tmp_path)
store.set_meta("world_name", "The Vale of Understone")
assert store.get_meta("world_name") == "The Vale of Understone"
assert store.get_meta("missing") is None
store.close()
def test_retention_columns_round_trip(tmp_path: Path) -> None:
"""The retention columns survive a reopen: depth, the v0.10 stack-encoded
satchel, the two forged plusses, and the v0.10 banked vault gold."""
store = _store(tmp_path)
player = make_player(
name="Delver",
deepest_rung=2,
satchel="minor_potion:3,iron_ore:5", # v0.10 "id:qty" stack encoding
weapon_plus=2,
armor_plus=1,
banked=300,
)
store.upsert_player(player)
store.commit()
store.close()
reopened = _store(tmp_path)
players, _ = reopened.load_all()
loaded = players["Delver"]
assert loaded == player # full equality across every column
assert loaded.deepest_rung == 2
assert loaded.satchel == "minor_potion:3,iron_ore:5"
assert loaded.weapon_plus == 2
assert loaded.armor_plus == 1
assert loaded.banked == 300
reopened.close()
def test_v0_7_depth_columns_default_for_legacy_rows(tmp_path: Path) -> None:
"""A row written without the new columns loads them at their defaults.
The schema mutates in place (no migration, stamp stays 1), so the new
columns carry DB-side defaults: a pre-v0.7 player row (inserted with the
legacy column set) must read back deepest_rung 0, an empty satchel, and
zero plusses rather than erroring.
"""
store = _store(tmp_path)
store._conn.execute(
"INSERT INTO players "
"(name, x, y, hp, max_hp, level, xp, gold, atk, def_, weapon_id, armor_id, "
" turns_left, turn_day, mode, at_location, created_at, last_seen, log_cursor, "
" bestow_spent, bestow_day) "
"VALUES ('Old', 5, 5, 20, 20, 1, 0, 20, 5, 1, 'rusty_dagger', 'cloth_tunic', "
" 10, 0, 'tile', '', 't0', 't0', 0, 0, 0)",
)
store.commit()
store.close()
reopened = _store(tmp_path)
players, _ = reopened.load_all()
old = players["Old"]
assert old.deepest_rung == 0
assert old.satchel == ""
assert old.weapon_plus == 0
assert old.armor_plus == 0
assert old.banked == 0 # the v0.10 vault column defaults too
assert reopened.get_meta("schema_version") == "1" # stamp unchanged
reopened.close()
+47
View File
@@ -0,0 +1,47 @@
"""GameRNG tests — the deterministic randomness seam.
Covers the v0.2 ``weighted_index`` helper: that a fixed seed reproduces the
same stream, that the cumulative-sum mapping honours the weights' proportions,
and that every index of a crafted table is reachable.
"""
from __future__ import annotations
from collections import Counter
from understone.engine.rng import GameRNG
def test_weighted_index_is_deterministic_under_seed() -> None:
"""Two RNGs at the same seed yield the identical weighted-index stream."""
weights = [55, 8, 7, 5, 5, 5, 5, 3, 3, 4]
a = GameRNG(seed=2026)
b = GameRNG(seed=2026)
draws_a = [a.weighted_index(weights) for _ in range(50)]
draws_b = [b.weighted_index(weights) for _ in range(50)]
assert draws_a == draws_b
def test_weighted_index_every_index_reachable() -> None:
"""With equal weights, a crafted table sees every index appear."""
weights = [1, 1, 1, 1, 1]
rng = GameRNG(seed=7)
seen = {rng.weighted_index(weights) for _ in range(500)}
assert seen == set(range(len(weights)))
def test_weighted_index_single_entry_always_zero() -> None:
"""A one-row table can only ever pick index 0."""
rng = GameRNG(seed=1)
assert all(rng.weighted_index([9]) == 0 for _ in range(20))
def test_weighted_index_respects_proportions() -> None:
"""A heavily-weighted index dominates the empirical distribution."""
weights = [90, 5, 5]
rng = GameRNG(seed=99)
counts = Counter(rng.weighted_index(weights) for _ in range(4000))
# Index 0 carries 90% of the mass; it must be by far the most common.
assert counts[0] > counts[1] + counts[2]
# And the rare indices still occur (no off-by-one swallowing the tail).
assert counts[1] > 0 and counts[2] > 0
+63
View File
@@ -0,0 +1,63 @@
"""The satchel "id:qty" wire codec (understone.engine.satchel).
Pins the single-source codec the game façade, the Watch payload, and the
balance simulator all decode through. The format is comma-joined ``id:qty``
stacks; this proves a clean round-trip, the defensive bare-id => qty-1 rule, the
malformed/zero/empty fragments that are skipped, and that the encoder never
emits a zero-or-negative stack.
"""
from __future__ import annotations
import pytest
from understone.engine.satchel import decode_satchel, encode_satchel
def test_round_trips_id_qty_stacks() -> None:
"""The canonical "id:qty,id:qty" data decodes and re-encodes unchanged."""
encoded = "minor_potion:3,iron_ore:5"
stacks = decode_satchel(encoded)
assert stacks == [("minor_potion", 3), ("iron_ore", 5)]
assert encode_satchel(stacks) == encoded
def test_bare_id_decodes_as_qty_one() -> None:
"""A colonless chunk is a single item (defensive — never silently dropped)."""
assert decode_satchel("minor_potion") == [("minor_potion", 1)]
# Mixed with a normal stack, order preserved.
assert decode_satchel("minor_potion,iron_ore:5") == [
("minor_potion", 1),
("iron_ore", 5),
]
@pytest.mark.parametrize(
("encoded", "reason"),
[
("id:0", "zero quantity"),
("id:-1", "negative quantity"),
("id:abc", "non-integer quantity"),
(":5", "empty id"),
("", "empty string"),
("minor_potion:3,", "trailing comma yields an empty chunk"),
(",minor_potion:3", "leading comma yields an empty chunk"),
],
)
def test_skips_malformed_or_zero_fragments(encoded: str, reason: str) -> None:
"""A present-but-invalid or non-positive fragment is skipped; valid ones survive."""
stacks = decode_satchel(encoded)
assert all(item_id and qty > 0 for item_id, qty in stacks), reason
# The only valid stack in the trailing/leading-comma cases is the potion.
if "minor_potion:3" in encoded:
assert stacks == [("minor_potion", 3)]
else:
assert stacks == []
def test_encode_drops_non_positive_stacks() -> None:
"""The encoder never emits "id:0" or a negative quantity."""
assert encode_satchel([("minor_potion", 0)]) == ""
assert encode_satchel([("minor_potion", -2)]) == ""
assert encode_satchel([("minor_potion", 2), ("iron_ore", 0)]) == "minor_potion:2"
assert encode_satchel([]) == ""
+169
View File
@@ -0,0 +1,169 @@
"""Screen-layer tests: viewport maths, frame rendering, menu rendering.
Golden discipline: the golden files under ``tests/golden`` are authored by
hand (correct borders/centring, eyeballed) and are NOT machine-dumped
renderer output. Every golden comparison is paired with structural asserts
that hold independent of the exact golden bytes, so a renderer regression
that happens to match a stale golden still trips a structural check.
"""
from __future__ import annotations
from pathlib import Path
from understone.screen.grid import Cell, CellGrid
from understone.screen.menus import render_menu
from understone.screen.palette import Color
from understone.screen.text_renderer import render_frame
from understone.screen.viewport import compute_window
GOLDEN = Path(__file__).parent / "golden"
# ---------------------------------------------------------------------------
# viewport.compute_window
# ---------------------------------------------------------------------------
def test_window_centers_when_interior() -> None:
# 100x100 map, 48x16 view, focus at (50, 50): centred.
x0, y0 = compute_window(100, 100, 48, 16, 50, 50)
assert x0 == 50 - 48 // 2
assert y0 == 50 - 16 // 2
def test_window_clamps_nw_corner() -> None:
x0, y0 = compute_window(100, 100, 48, 16, 0, 0)
assert (x0, y0) == (0, 0)
def test_window_clamps_ne_corner() -> None:
x0, y0 = compute_window(100, 100, 48, 16, 99, 0)
assert x0 == 100 - 48
assert y0 == 0
def test_window_clamps_sw_corner() -> None:
x0, y0 = compute_window(100, 100, 48, 16, 0, 99)
assert x0 == 0
assert y0 == 100 - 16
def test_window_clamps_se_corner() -> None:
x0, y0 = compute_window(100, 100, 48, 16, 99, 99)
assert x0 == 100 - 48
assert y0 == 100 - 16
def test_window_view_larger_than_map_pins_origin() -> None:
x0, y0 = compute_window(10, 8, 48, 16, 5, 4)
assert (x0, y0) == (0, 0)
# ---------------------------------------------------------------------------
# Shared small-grid builders for the golden frames
# ---------------------------------------------------------------------------
_FLOOR = Cell(".", Color.FLOOR)
_PLAYER = Cell("@", Color.PLAYER)
def _floor_grid(rows: int, cols: int) -> CellGrid:
grid = CellGrid(rows, cols)
for r in range(rows):
for c in range(cols):
grid.set(r, c, _FLOOR)
return grid
def _spawn_grid() -> CellGrid:
"""9x5 floor with the player centred at (row 2, col 4)."""
grid = _floor_grid(5, 9)
grid.set(2, 4, _PLAYER)
return grid
def _edge_nw_grid() -> CellGrid:
"""9x5 floor with the player pinned to the NW corner (row 0, col 0)."""
grid = _floor_grid(5, 9)
grid.set(0, 0, _PLAYER)
return grid
# ---------------------------------------------------------------------------
# text_renderer.render_frame
# ---------------------------------------------------------------------------
def test_render_frame_matches_golden_spawn() -> None:
frame = render_frame(_spawn_grid(), title="Vale", status="[ status ]")
expected = (GOLDEN / "viewport_spawn.txt").read_text(encoding="utf-8")
assert frame == expected.rstrip("\n")
def test_render_frame_matches_golden_edge_nw() -> None:
frame = render_frame(_edge_nw_grid(), title="Vale", status="[ status ]")
expected = (GOLDEN / "viewport_edge_nw.txt").read_text(encoding="utf-8")
assert frame == expected.rstrip("\n")
def test_render_frame_structural_invariants() -> None:
frame = render_frame(_spawn_grid(), title="Vale", status="[ status ]")
lines = frame.split("\n")
# Top border, 5 grid rows, bottom border, status = 8 lines.
assert len(lines) == 8
# Title substring lives in the top border.
assert "Vale" in lines[0]
# Uniform width across the box (top border through bottom border).
box_lines = lines[:-1]
widths = {len(line) for line in box_lines}
assert len(widths) == 1, f"box rows ragged: {widths}"
# Exactly one '@' and it sits at the centre column of the interior.
body = lines[1:-2]
at_positions = [(r, line.index("@")) for r, line in enumerate(body) if "@" in line]
assert len(at_positions) == 1
_, col = at_positions[0]
# Interior centre: 1 (left border) + cols//2 = 1 + 4 = 5.
assert col == 1 + 9 // 2
# Status line is preserved verbatim as the last line.
assert lines[-1] == "[ status ]"
def test_render_frame_under_size_budget() -> None:
grid = _floor_grid(16, 48)
grid.set(8, 24, _PLAYER)
frame = render_frame(grid, title="The Vale of Understone", status="[ a long status line here ]")
assert len(frame) < 2048
# ---------------------------------------------------------------------------
# menus.render_menu
# ---------------------------------------------------------------------------
def test_render_menu_matches_golden_inn() -> None:
menu = render_menu(
"The Sleeping Drake",
["A warm hearth crackles.", "A bed costs 15 gold."],
["(R)est", "(L)eave"],
"[ status ]",
)
expected = (GOLDEN / "menu_inn.txt").read_text(encoding="utf-8")
assert menu == expected.rstrip("\n")
def test_render_menu_structural_invariants() -> None:
menu = render_menu(
"The Sleeping Drake",
["A warm hearth crackles.", "A bed costs 15 gold."],
["(R)est", "(L)eave"],
"[ status ]",
)
lines = menu.split("\n")
assert "The Sleeping Drake" in lines[0]
assert lines[-1] == "[ status ]"
box = lines[:-1]
widths = {len(line) for line in box}
assert len(widths) == 1, f"menu box ragged: {widths}"
# Option line is present inside the body.
assert any("(R)est" in line and "(L)eave" in line for line in lines)
+306
View File
@@ -0,0 +1,306 @@
"""Tests for the balance instrument (the greedy bot simulator).
These run the REAL game façade end-to-end, so they double as the fiercest
integration test in the suite: determinism (same inputs identical report),
that the greedy bot makes genuine progress over a Vale run, that its realized
fight share lands in a sane band, that a multi-seed sweep aggregates and the
report renders and the single best end-to-end assertion, that a short seed
sweep actually SLAYS THE WYRM, proving the whole v0.1v0.7 loop is winnable by
an unclever bot.
"""
from __future__ import annotations
from io import StringIO
from pathlib import Path
from typing import TYPE_CHECKING
from understone import sim
from understone.engine.models import LocationDef, Mode, Zone
from understone.engine.rng import GameRNG
from understone.game import Game
from understone.persistence import Store
from understone.sim import BalanceReport, simulate
from .conftest import make_monster, make_world
if TYPE_CHECKING:
import pytest
PACK = Path(__file__).resolve().parents[1] / "understone" / "world" / "data"
# ---------------------------------------------------------------------------
# determinism
# ---------------------------------------------------------------------------
def test_same_inputs_give_identical_report() -> None:
"""Same (pack, days, seed) → byte-identical BalanceReport (frozen + seeded)."""
a = simulate(PACK, 20, 5)
b = simulate(PACK, 20, 5)
assert a == b
assert isinstance(a, BalanceReport)
def test_different_seeds_diverge() -> None:
"""Different seeds produce different runs (the RNG actually threads through)."""
a = simulate(PACK, 20, 1)
b = simulate(PACK, 20, 2)
# The runs are not identical (some headline measure differs).
assert (a.fights_fought, a.total_gold_earned, a.day_of_first_wyrm_kill) != (
b.fights_fought,
b.total_gold_earned,
b.day_of_first_wyrm_kill,
)
# ---------------------------------------------------------------------------
# progress
# ---------------------------------------------------------------------------
def test_bot_makes_progress_over_thirty_days() -> None:
"""A 30-day Vale run climbs past level 1 and actually fights."""
r = simulate(PACK, 30, 1)
assert r.final_level > 1
assert r.fights_fought > 0
assert r.total_gold_earned > 0
# It also plumbs the deep — the rung ladder is reachable for a geared bot.
assert r.rungs_cleared > 0
def test_realized_fight_share_in_sane_band() -> None:
"""The bot's fight share is a real fraction and forest-fight dominant.
A greedy XP grinder spends most of its turns fighting the wood (the rest are
the handful of descents and the Wyrm bout), so the share is high but it is
a genuine fraction in (0, 1], never a degenerate 0 or a value out of range.
"""
r = simulate(PACK, 30, 3)
assert 0.0 < r.realized_fight_share <= 1.0
# Fights dominate the turn-spend, but descents/challenges exist too, so the
# share is below a hard 1.0 floor only loosely — assert the sane half-band.
assert r.realized_fight_share >= 0.5
# ---------------------------------------------------------------------------
# reporting & sweep
# ---------------------------------------------------------------------------
def test_report_renders_without_crashing() -> None:
r = simulate(PACK, 15, 1)
text = sim._render_report("The Vale of Understone", r)
assert "greedy bot" in text
assert "final level" in text
assert "Wyrm slain" in text
def test_cli_simulate_single_seed_renders(tmp_path: Path) -> None:
out = StringIO()
rc = sim.cli_simulate(PACK, 15, 1, out=out)
assert rc == 0
assert "The Vale of Understone" in out.getvalue()
assert "fight share" in out.getvalue()
def test_cli_simulate_sweep_aggregates() -> None:
"""A --seeds sweep prints per-seed lines plus an aggregate with spreads."""
out = StringIO()
rc = sim.cli_simulate(PACK, 20, 1, out=out, seeds=3)
assert rc == 0
text = out.getvalue()
assert "3 seeds" in text
assert "aggregate" in text
# Per-seed lines for each of the three seeds.
for seed in (1, 2, 3):
assert f"seed {seed:>3}" in text or f"seed {seed}" in text
# The aggregate carries a mean [min..max] spread.
assert "[" in text and "]" in text
def test_sweep_reports_are_each_deterministic() -> None:
"""Each seed in a sweep is independently reproducible by single simulate."""
seed = 4
swept = simulate(PACK, 20, seed)
again = simulate(PACK, 20, seed)
assert swept == again
# ---------------------------------------------------------------------------
# the load-bearing assertion: the world is winnable
# ---------------------------------------------------------------------------
def test_greedy_bot_slays_the_wyrm() -> None:
"""The single best end-to-end check: a short seed sweep KILLS THE WYRM.
If a greedy, unclever bot can take the Wyrm Below playing through the real
façade, then the whole authored loop movement, the zone-banded forest, the
economy, the rung ladder, the satchel death-save, the forge, and the endgame
gate composes into a *winnable* game. A run that ever stops winning trips
here. A small sweep (not one lucky seed) so the proof is robust.
"""
reports = [simulate(PACK, 40, seed) for seed in (1, 2, 3)]
kills = [r for r in reports if r.wyrm_killed]
assert kills, "the greedy bot never slew the Wyrm across the seed sweep"
# Every kill records the day it first happened, within the run window.
for r in kills:
assert r.day_of_first_wyrm_kill is not None
assert 1 <= r.day_of_first_wyrm_kill <= 40
# ---------------------------------------------------------------------------
# the bundled ALTERNATE world: The Cinder Wastes (LLM-authored from the manual)
#
# The Vale assertions above are the primary proof. These mirror them against the
# real bundled second world, so the dogfood pack — authored cold from AUTHORING.md
# — is held to the same bar: the bot must make genuine progress through it, and a
# short seed sweep must actually slay its Magma Wyrm. If the authored world ever
# stops being winnable, this trips.
# ---------------------------------------------------------------------------
CINDER = Path(__file__).resolve().parents[1] / "understone" / "world" / "packs" / "cinder-wastes"
def test_cinder_wastes_bot_makes_progress() -> None:
"""A short Cinder Wastes run climbs past level 1 and genuinely plays.
Fifteen days lands before the bot's first Wyrm kill (~day 24), so the level
is still climbing rather than reset post-win a stable "the world plays"
signal across the durable measures (level, fights, gold, the rung ladder).
"""
r = simulate(CINDER, 15, 1)
assert r.final_level > 1
assert r.fights_fought > 0
assert r.total_gold_earned > 0
assert r.rungs_cleared > 0 # the caldera rung ladder is reachable
def test_cinder_wastes_is_winnable() -> None:
"""The dogfood proof: a greedy bot SLAYS THE MAGMA WYRM in the authored world.
The Cinder Wastes was written by an LLM working only from AUTHORING.md and
the validator. This is the end-to-end demonstration that the manual plus the
loader produce not merely a *valid* pack but a *playable-to-victory* one a
short seed sweep takes the Magma Wyrm. (It is harder than the Vale: the kill
lands later, so the window is wider than the Vale's.)
"""
reports = [simulate(CINDER, 50, seed) for seed in (1, 2, 3)]
kills = [r for r in reports if r.wyrm_killed]
assert kills, "the greedy bot never slew the Magma Wyrm across the seed sweep"
for r in kills:
assert r.day_of_first_wyrm_kill is not None
assert 1 <= r.day_of_first_wyrm_kill <= 50
# ---------------------------------------------------------------------------
# robustness on non-shipped pack shapes: location doors inside hunt zones
#
# The bot runs arbitrary authored packs, not just the two bundled worlds, so a
# zone may overlap a location door. A door cell is "walkable" (you can step onto
# it) but standing on it flips the bot into that location's MENU — useless ground
# for a forest fight, and a "fight" issued from a MENU is rejected by the engine
# WITHOUT spending a turn. These pin the two guards that keep that from spinning
# the per-day loop or over-counting fights.
# ---------------------------------------------------------------------------
def _door(x: int, y: int) -> LocationDef:
"""A bare location door placed at ``(x, y)`` (an inn, for concreteness)."""
return LocationDef(
key="inn",
kind="inn",
name="Wayhouse",
x=x,
y=y,
glyph="",
color="town",
actions=("rest", "leave"),
)
def test_nearest_in_zone_skips_a_door_cell() -> None:
"""A door is never returned as a zone's hunt cell, even when it is nearest.
The zone here spans a column running away from the spawn; its closest-to-spawn
walkable cell IS a location door, with open ground one step further. The
helper must skip the door (it would only trap the bot in a menu) and return
the open cell beyond it the FIX-2 filter, mirroring ``_adjacent_open``.
"""
# 11x11 grass; spawn (5, 5). A door at (5, 6) is the nearest cell inside the
# zone (Manhattan 1); the nearest OPEN in-zone cell is (5, 7) (Manhattan 2).
world = make_world(
locations=[_door(5, 6)],
zones=[Zone(key="wood", x0=5, y0=6, x1=5, y1=9, tier_lo=1, tier_hi=1)],
)
walkable = sim._reachable(world)
assert (5, 6) in walkable # the door cell is walkable...
cell = sim._nearest_in_zone(world, walkable, world.zones[0])
assert cell is not None
assert cell != (5, 6) # ...but the helper does not pick it
assert world.location_at(*cell) is None # the returned cell is open ground
assert cell == (5, 7) # the nearest open in-zone cell beyond the door
def test_zone_hunt_spots_drops_a_zone_with_no_fightable_foe() -> None:
"""A zone whose tier band holds no foe is dropped, not appended with None.
FIX-4: the fallback in ``_best_hunt_spot`` (``ranked[-1]``) must never land on
a zone where no monster can roll. A zone banded to a tier with no monster is
simply not a hunting ground, so it never enters the spot list.
"""
# One zone banded to tier 9 (no monster lives there); the only monster is a
# tier-1 rat. The empty-band zone must be dropped entirely.
world = make_world(
monsters=[make_monster(tier=1)],
zones=[Zone(key="void", x0=4, y0=4, x1=6, y1=6, tier_lo=9, tier_hi=9)],
)
spots = sim._zone_hunt_spots(world, sim._reachable(world))
assert spots == [] # the foe-less zone is not a spot
def test_hunt_yields_the_turn_when_stuck_in_a_menu(
monkeypatch: pytest.MonkeyPatch, tmp_path: Path
) -> None:
"""A hunt that ends in a MENU yields the turn instead of over-counting.
The defence-in-depth for FIX-1: should the bot ever reach the fight moment
still inside a location MENU (a door swallowed the walk), the engine would
REJECT the "fight" without spending a turn and the old string-only check
misread that reject as a won bout, over-counting and spinning the loop. The
new mode pre-check must instead leave the menu and return False (yield), so no
phantom fight is recorded and the day loop makes honest progress.
"""
# A door at (5, 4) inside a tier-1 zone. We inject this door cell as the hunt
# spot directly — the pre-FIX-2 state where a door WAS the nearest in-zone
# cell — so the guard, not the spot-selection filter, is what is under test.
world = make_world(
locations=[_door(5, 4)],
zones=[Zone(key="wood", x0=4, y0=3, x1=6, y1=5, tier_lo=1, tier_hi=1)],
monsters=[make_monster(tier=1)],
)
clock = sim._Clock(sim._SIM_START)
game = Game(world, Store(tmp_path / "g.db"), clock=clock, rng=GameRNG(seed=1)) # type: ignore[arg-type]
bot = sim._Bot(game, world, clock)
game.join(bot.name)
bot._hunt_spots = [(1, (5, 4), make_monster(tier=1))]
player = game.players[bot.name]
# Model "a location door swallowed the walk": every navigation step ends with
# the bot back inside the door's menu, so the hunt reaches its fight decision
# still in MENU mode no matter how many times it tries to step clear — exactly
# the trap the guard exists for (a single un-menu + re-walk cannot escape it).
def _walk_into_door(_goal: tuple[int, int]) -> None:
player.mode = Mode.MENU
player.at_location = "inn"
monkeypatch.setattr(bot, "_goto_xy", _walk_into_door)
_walk_into_door((5, 4)) # start the hunt already inside the menu
fought = bot._hunt()
assert fought is False # the turn is yielded, not spent on a menu-reject
assert bot.fights_fought == 0 # no phantom fight recorded
assert game.players[bot.name].mode is Mode.TILE # and the menu was left behind
+862
View File
@@ -0,0 +1,862 @@
"""The v0.5 social slice — ambush (async PvP), inn mail, and inn dice.
Drives the game façade over the shipped world with a frozen clock and a seeded
RNG. Three feature areas:
* AMBUSH the full eligibility matrix (every refusal branch), the win path
(exact gold transfer, victim bounced to spawn at 1 HP, private mail visible
only to the victim, public news), the lose path (attacker bounced, no
transfer), the flee stalemate, per-day once-per-pair, and next-day retry.
* MAIL ``post`` delivers a private note to the target's log once, the sender
is confirmed, the daily cap refuses the overflow, the sanitizer rejects a
newline body, and the Watch state payload NEVER carries a targeted row.
* DICE win/lose/push under a seeded RNG, the bet band, affordability, the
daily cap (a push still counts), and the Herald firing only on a big win.
Negative-test discipline (the SLEEP RULE has teeth):
``test_sleep_rule_guard_has_teeth`` documents the revert-and-observe check.
Disabling the ``target.turn_day >= today`` clause in Game._ambush_refusal
let an ALREADY-AWAKE target be ambushed ``test_ambush_refused_target_awake``
then failed (the attempt resolved instead of being refused). The clause was
restored; that refusal test is the standing regression for the invariant.
"""
from __future__ import annotations
from pathlib import Path
import pytest
from tests.conftest import fixed_clock, utc
from understone.engine.models import Mode
from understone.engine.rng import GameRNG
from understone.game import Game
from understone.persistence import Store
from understone.watch import build_state_payload
from understone.world.loader import load_world
PACK = Path(__file__).resolve().parents[1] / "understone" / "world" / "data"
# The frozen "today" all these tests run on; the sleep rule keys off its ordinal.
_NOW = utc(2026, 6, 12, 10, 0)
_TODAY = _NOW.toordinal()
@pytest.fixture
def clock() -> object:
return fixed_clock(_NOW)
def _game(tmp_path: Path, clock: object, seed: int = 7) -> Game:
world = load_world(PACK)
store = Store(tmp_path / "social.db")
return Game(world, store, clock=clock, rng=GameRNG(seed=seed)) # type: ignore[arg-type]
def _arm_ambush(
game: Game,
*,
attacker_level: int = 5,
target_level: int = 5,
target_asleep: bool = True,
target_gold: int = 100,
) -> tuple[object, object]:
"""Join an attacker + target and tune their sheets for an ambush.
The attacker is overworld and seasoned; the target sits at *target_level*
with *target_gold*, and ``target_asleep`` controls the sleep rule (a
sleeping target has not acted today). Returns ``(attacker, target)``.
"""
game.join("Raider")
game.join("Sleeper")
attacker = game.players["Raider"]
target = game.players["Sleeper"]
attacker.level = attacker_level
target.level = target_level
target.gold = target_gold
target.turn_day = _TODAY - 1 if target_asleep else _TODAY
return attacker, target
# ---------------------------------------------------------------------------
# Ambush — eligibility matrix (each refusal is a distinct in-fiction line)
# ---------------------------------------------------------------------------
def test_ambush_refused_unknown_target(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
game.join("Raider")
game.players["Raider"].level = 5
out = game.action("Raider", "ambush", "Ghost", "")
assert "signed the ledger" in out # the unknown-player refusal
# No turn spent on an unresolvable target.
assert game.players["Raider"].turns_left == game.world.settings.daily_turns
def test_ambush_refused_self(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
game.join("Raider")
game.players["Raider"].level = 5
out = game.action("Raider", "ambush", "Raider", "")
assert "yourself" in out.lower()
def test_ambush_refused_young_attacker(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
floor = game.world.settings.ambush_min_level
_arm_ambush(game, attacker_level=floor - 1, target_level=floor + 1)
out = game.action("Raider", "ambush", "Sleeper", "")
assert "shields the young" in out
assert game.players["Raider"].turns_left == game.world.settings.daily_turns
def test_ambush_refused_young_target(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
floor = game.world.settings.ambush_min_level
# Attacker is seasoned but the target is below the floor: still shielded.
_arm_ambush(game, attacker_level=floor + 1, target_level=floor - 1)
out = game.action("Raider", "ambush", "Sleeper", "")
assert "shields the young" in out
def test_ambush_refused_out_of_band(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
band = game.world.settings.ambush_level_band
floor = game.world.settings.ambush_min_level
_arm_ambush(
game,
attacker_level=floor + band + 5,
target_level=floor,
)
out = game.action("Raider", "ambush", "Sleeper", "")
assert "far from your measure" in out
def test_ambush_band_beats_awake_in_refusal_order(tmp_path: Path, clock: object) -> None:
"""PRECEDENCE: the band gate is checked before the sleep rule.
A target who is BOTH out of band AND awake must report the band message,
not the watchful one pinning the documented order (level gates before the
live-play sleep defence).
"""
game = _game(tmp_path, clock)
band = game.world.settings.ambush_level_band
floor = game.world.settings.ambush_min_level
_arm_ambush(
game,
attacker_level=floor + band + 1, # one past the band...
target_level=floor,
target_asleep=False, # ...and also awake
)
out = game.action("Raider", "ambush", "Sleeper", "")
assert "far from your measure" in out # the band gate wins
assert "watchful today" not in out
def test_ambush_band_boundary_exact_is_allowed(tmp_path: Path, clock: object) -> None:
"""Exactly ``ambush_level_band`` apart clears the band gate (it is inclusive).
Armed awake so the very next gate the sleep rule is what speaks: a
'watchful today' refusal proves the band gate let this pair through.
"""
game = _game(tmp_path, clock)
band = game.world.settings.ambush_level_band
floor = game.world.settings.ambush_min_level
_arm_ambush(
game,
attacker_level=floor + band, # exactly band levels above the floor
target_level=floor,
target_asleep=False,
)
out = game.action("Raider", "ambush", "Sleeper", "")
assert "far from your measure" not in out # past the band gate
assert "watchful today" in out # stopped by the next gate instead
def test_ambush_band_boundary_one_over_is_refused(tmp_path: Path, clock: object) -> None:
"""One level past ``ambush_level_band`` is refused with the band message."""
game = _game(tmp_path, clock)
band = game.world.settings.ambush_level_band
floor = game.world.settings.ambush_min_level
_arm_ambush(
game,
attacker_level=floor + band + 1, # just over the band
target_level=floor,
)
out = game.action("Raider", "ambush", "Sleeper", "")
assert "far from your measure" in out
assert game.store.has_ambushed("Raider", "Sleeper", _TODAY) is False
def test_ambush_refused_target_awake(tmp_path: Path, clock: object) -> None:
"""The SLEEP RULE: a target who has already acted today is un-ambushable.
See the module docstring for the revert-and-observe check proving this
refusal has teeth.
"""
game = _game(tmp_path, clock)
_arm_ambush(game, target_asleep=False)
out = game.action("Raider", "ambush", "Sleeper", "")
assert "watchful today" in out
# Refused without resolving: no turn spent, no ambush recorded.
assert game.players["Raider"].turns_left == game.world.settings.daily_turns
assert game.store.has_ambushed("Raider", "Sleeper", _TODAY) is False
def test_ambush_refused_repeat_same_pair_same_day(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
attacker, target = _arm_ambush(game)
# First attempt resolves (attacker overwhelming -> a clean win).
attacker.atk = 200
target.hp = 5
game.action("Raider", "ambush", "Sleeper", "")
assert game.store.has_ambushed("Raider", "Sleeper", _TODAY) is True
# Re-arm the target as sleeping AND healed above 1 HP (so the mercy rule
# does not intercept first); the SAME pair is still barred for the day.
target.turn_day = _TODAY - 1
target.hp = 20
out = game.action("Raider", "ambush", "Sleeper", "")
assert "already lain in wait" in out
def test_ambush_refused_pile_on_downed_victim(tmp_path: Path, clock: object) -> None:
"""MERCY RULE: a second, DIFFERENT attacker cannot kick a just-bounced sleeper.
The first ambush leaves the victim at 1 HP (still asleep being robbed does
not start their day). A fresh raider then finds them battered in the ditch;
even bandits have standards, so the pile-on is refused outright no turn
spent, no pair-row written for the second attacker.
"""
game = _game(tmp_path, clock)
first, target = _arm_ambush(game, target_gold=100)
first.atk = 200 # one-shot: leaves the victim at 1 HP
target.hp = 5
game.action("Raider", "ambush", "Sleeper", "")
assert target.hp == 1 # downed and still asleep
# A second, seasoned raider tries to finish the job.
game.join("Marauder")
second = game.players["Marauder"]
second.level = 5
turns_before = second.turns_left
out = game.action("Marauder", "ambush", "Sleeper", "")
assert "battered in the ditch" in out
# No turn spent and no attempt recorded for the second attacker.
assert second.turns_left == turns_before
assert game.store.has_ambushed("Marauder", "Sleeper", _TODAY) is False
def test_ambush_healed_victim_is_ambushable_again(tmp_path: Path, clock: object) -> None:
"""The mercy rule lifts once the victim mends: healed above 1 HP (and still
asleep), a fresh attacker may strike."""
game = _game(tmp_path, clock)
first, target = _arm_ambush(game, target_gold=100)
first.atk = 200
target.hp = 5
game.action("Raider", "ambush", "Sleeper", "")
assert target.hp == 1
# The victim is tended back above the floor (still asleep this day).
target.hp = 18
game.join("Marauder")
second = game.players["Marauder"]
second.level = 5
second.atk = 200 # one-shot again
out = game.action("Marauder", "ambush", "Sleeper", "")
assert "battered in the ditch" not in out
# The fresh ambush resolved: recorded, and the victim is bounced anew.
assert game.store.has_ambushed("Marauder", "Sleeper", _TODAY) is True
assert target.hp == 1
def test_ambush_refused_zero_turns(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
attacker, _ = _arm_ambush(game)
attacker.turns_left = 0
out = game.action("Raider", "ambush", "Sleeper", "")
assert "spent for today" in out.lower()
# Eligible but exhausted: nothing recorded (the attempt never landed).
assert game.store.has_ambushed("Raider", "Sleeper", _TODAY) is False
# ---------------------------------------------------------------------------
# Ambush — outcomes (win / lose / flee) and the records they leave
# ---------------------------------------------------------------------------
def test_ambush_win_transfers_gold_and_bounces_victim(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
attacker, target = _arm_ambush(game, target_gold=100)
attacker.atk = 200 # one-shot the sleeper
target.hp = 5
pct = game.world.settings.ambush_gold_pct
steal = 100 * pct // 100 # 25 gold at the shipped 25%
raider_gold_before = attacker.gold
out = game.action("Raider", "ambush", "Sleeper", "")
# Exact transfer: attacker up by steal, victim down by the same.
assert attacker.gold == raider_gold_before + steal
assert target.gold == 100 - steal
# The victim wakes at the spawn at 1 HP, knocked out of any menu.
assert target.hp == 1
assert (target.x, target.y) == game.world.spawn
assert target.mode is Mode.TILE
assert target.at_location == ""
assert f"{steal} gold" in out
# The attempt is recorded.
assert game.store.has_ambushed("Raider", "Sleeper", _TODAY) is True
def test_ambush_steals_only_carried_gold_not_the_vault(tmp_path: Path, clock: object) -> None:
"""A winning ambush robs carried gold only — banked vault gold is untouched.
The steal is a slice of ``target.gold`` (gold in hand); the strongbox
(``banked``) is safe by design. This pins the vault's whole point: bank your
coin before you sleep and a sleeping-robber cannot lift it.
"""
game = _game(tmp_path, clock)
attacker, target = _arm_ambush(game, target_gold=40)
target.banked = 1000 # a fat vault the raider must not be able to touch
attacker.atk = 200 # one-shot the sleeper
target.hp = 5
pct = game.world.settings.ambush_gold_pct
steal = 40 * pct // 100 # a slice of the CARRIED 40, not the banked 1000
game.action("Raider", "ambush", "Sleeper", "")
assert target.gold == 40 - steal # carried gold robbed
assert target.banked == 1000 # the vault is wholly untouched
assert attacker.gold == game.world.settings.starting_gold + steal
def test_ambush_win_applies_attacker_wear(tmp_path: Path, clock: object) -> None:
"""A multi-round win banks the attacker's wear: the log narrates the
sleeper's counter-blows, so the sheet must show the HP they cost.
The one-shot win above leaves the attacker untouched, which would mask a
WIN branch that drops ``hp_delta`` on the floor. Here the sleeper is tanky
enough to trade blows before falling (and the attacker still wins), so the
attacker must end below full HP. Stats and seed are tuned so the win is
decisive but not instant.
"""
game = _game(tmp_path, clock)
attacker, target = _arm_ambush(game, target_gold=100)
attacker.atk, attacker.def_ = 8, 2
attacker.hp = attacker.max_hp = 30
target.atk, target.def_, target.hp = 5, 1, 25
out = game.action("Raider", "ambush", "Sleeper", "")
# The win lands (victim robbed and bounced to 1 HP)...
assert target.hp == 1
assert (
any(crow in out for crow in ("made off", "robbed the sleeping", "lifted")) or "rob" in out
)
# ...but the sleeper's counter-blows cost the attacker real HP this time.
assert attacker.hp < attacker.max_hp
assert attacker.hp >= 1 # never below the floor
def test_ambush_win_news_is_public_and_mail_is_private(tmp_path: Path, clock: object) -> None:
"""The victory crows on the public feed; the victim gets a PRIVATE note.
A THIRD player must see the public ambush line but never the private one.
"""
game = _game(tmp_path, clock)
attacker, target = _arm_ambush(game, target_gold=80)
attacker.atk = 200
target.hp = 5
game.join("Bystander") # a third player who must never see the private note
game.action("Raider", "ambush", "Sleeper", "")
# The victim reads the private "While you slept" note in their own log.
victim_log = game.log("Sleeper")
assert "While you slept" in victim_log
assert "ambushed you" in victim_log
# The bystander sees the public crow but NOT the private note.
third_log = game.log("Bystander")
assert (
"made off with" in third_log
or "robbed the sleeping" in third_log
or ("lifted" in third_log)
)
assert "While you slept" not in third_log
def test_ambush_win_on_pauper_steals_nothing_but_still_lands(tmp_path: Path, clock: object) -> None:
"""A win over a penniless sleeper: steal is 0, but the beat still plays.
The victim is bounced to the spawn at 1 HP all the same, the public herald
crows the robbery, and the private 'while you slept' note still reaches the
victim the gold transfer being empty changes none of that.
"""
game = _game(tmp_path, clock)
attacker, target = _arm_ambush(game, target_gold=0)
attacker.atk = 200 # one-shot the sleeper
target.hp = 5
game.join("Bystander")
raider_gold_before = attacker.gold
out = game.action("Raider", "ambush", "Sleeper", "")
# Nothing to steal: both purses are unchanged by the transfer.
assert attacker.gold == raider_gold_before
assert target.gold == 0
assert "0 gold" in out
# The victim is still bounced to the spawn at 1 HP.
assert target.hp == 1
assert (target.x, target.y) == game.world.spawn
assert target.mode is Mode.TILE
assert target.at_location == ""
# Public herald fires (a bystander reads the crow)...
third_log = game.log("Bystander")
assert any(crow in third_log for crow in ("made off", "robbed the sleeping", "lifted"))
# ...and the private mail still reaches the victim.
victim_log = game.log("Sleeper")
assert "While you slept" in victim_log
assert "ambushed you" in victim_log
def test_ambush_lose_bounces_attacker_no_transfer(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
attacker, target = _arm_ambush(game, target_gold=100)
# The sleeper is deadly: the ambush rebounds onto the attacker.
target.atk = 200
target.def_ = 100
target.hp = 200
attacker_gold_before = attacker.gold
out = game.action("Raider", "ambush", "Sleeper", "")
# No gold moved; the ATTACKER is the one bounced to spawn at 1 HP.
assert attacker.gold == attacker_gold_before
assert target.gold == 100
assert attacker.hp == 1
assert (attacker.x, attacker.y) == game.world.spawn
assert "flee" in out.lower() or "wakes" in out.lower()
# The attempt is still spent.
assert game.store.has_ambushed("Raider", "Sleeper", _TODAY) is True
def test_ambush_records_attempt_on_every_outcome(tmp_path: Path, clock: object) -> None:
"""Win, lose, or flee — the (attacker, target, day) row is always written."""
game = _game(tmp_path, clock)
attacker, target = _arm_ambush(game)
# Tune a flee: when neither side can meaningfully dent the other, the fight
# grinds to the 50-round stalemate guard, which resolves as FLED with no
# transfer. Both deal the 1-damage floor (atk << def), and both carry far
# more HP than 50 rounds can drain, so neither drops first.
attacker.atk, attacker.def_ = 1, 200
attacker.hp = attacker.max_hp = 500
target.atk, target.def_, target.hp = 1, 200, 500
gold_before = attacker.gold
out = game.action("Raider", "ambush", "Sleeper", "")
assert game.store.has_ambushed("Raider", "Sleeper", _TODAY) is True
assert attacker.gold == gold_before # a flee moves no gold
assert "slip away" in out.lower() or "nerve" in out.lower()
def test_ambush_next_day_retry_allowed(tmp_path: Path, clock: object) -> None:
"""A new UTC day clears the once-per-pair lock (advance the injected clock)."""
game = _game(tmp_path, clock)
attacker, target = _arm_ambush(game)
attacker.atk = 200
target.hp = 5
game.action("Raider", "ambush", "Sleeper", "")
assert game.store.has_ambushed("Raider", "Sleeper", _TODAY) is True
# Advance past UTC midnight; re-arm the sleeper for the new day.
tomorrow = utc(2026, 6, 13, 9, 0)
game.clock = fixed_clock(tomorrow) # type: ignore[assignment]
target.turn_day = tomorrow.toordinal() - 1 # asleep again
target.hp = 5
out = game.action("Raider", "ambush", "Sleeper", "")
assert "already lain in wait" not in out # the new day permits a fresh attempt
assert game.store.has_ambushed("Raider", "Sleeper", tomorrow.toordinal()) is True
def test_sleep_rule_guard_has_teeth(tmp_path: Path, clock: object) -> None:
"""Pin the sleep rule on a single-field divergence.
The un-ambushable case and the ambushable case differ ONLY in ``turn_day``:
with the target awake the action is refused, and flipping that one field to
asleep makes the very same attempt resolve and record.
"""
game = _game(tmp_path, clock)
attacker, target = _arm_ambush(game, target_asleep=False)
attacker.atk = 200
target.hp = 5
refused = game.action("Raider", "ambush", "Sleeper", "")
assert "watchful today" in refused
assert game.store.has_ambushed("Raider", "Sleeper", _TODAY) is False
# Flip ONLY the sleep field; now the very same attempt lands.
target.turn_day = _TODAY - 1
resolved = game.action("Raider", "ambush", "Sleeper", "")
assert "watchful today" not in resolved
assert game.store.has_ambushed("Raider", "Sleeper", _TODAY) is True
def test_ambush_both_rows_persist_in_one_transaction(tmp_path: Path, clock: object) -> None:
"""A win commits BOTH fighters' rows; a store reopen sees the transfer."""
game = _game(tmp_path, clock)
attacker, target = _arm_ambush(game, target_gold=100)
attacker.atk = 200
target.hp = 5
game.action("Raider", "ambush", "Sleeper", "")
raider_gold = attacker.gold
sleeper_gold = target.gold
game.store.close()
world = load_world(PACK)
reopened = Store(tmp_path / "social.db")
revived = Game(world, reopened, clock=clock) # type: ignore[arg-type]
assert revived.players["Raider"].gold == raider_gold
assert revived.players["Sleeper"].gold == sleeper_gold
assert revived.players["Sleeper"].hp == 1
reopened.close()
# ---------------------------------------------------------------------------
# Mail — post delivers privately, confirms, caps, sanitizes
# ---------------------------------------------------------------------------
def test_post_delivers_to_target_once_with_confirmation(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
game.join("Scribe")
game.join("Reader")
confirm = game.action("Scribe", "post", "Reader", "", "meet me at the inn")
assert "tucks the note" in confirm # the sender's in-fiction confirmation
# No turn spent on a post.
assert game.players["Scribe"].turns_left == game.world.settings.daily_turns
first = game.log("Reader")
assert "While you were away" in first
assert "meet me at the inn" in first
# Read once: the cursor advanced, so a second read no longer shows it.
second = game.log("Reader")
assert "meet me at the inn" not in second
def test_post_refused_unknown_and_self(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
game.join("Scribe")
unknown = game.action("Scribe", "post", "Nobody", "", "hello?")
assert "signed the ledger" in unknown
mine = game.action("Scribe", "post", "Scribe", "", "note to self")
assert "talk to yourself" in mine.lower()
def test_post_daily_cap_refuses_overflow(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
game.join("Scribe")
game.join("Reader")
cap = game.world.settings.post_daily_cap
for i in range(cap):
out = game.action("Scribe", "post", "Reader", "", f"note {i}")
assert "tucks the note" in out
# The (cap+1)-th post is refused.
over = game.action("Scribe", "post", "Reader", "", "one too many")
assert "all the word you may today" in over
assert game.players["Scribe"].posts_sent == cap
def test_post_sanitizer_rejects_newline_body(tmp_path: Path, clock: object) -> None:
"""A newline-injected note body is refused; nothing is delivered or counted."""
game = _game(tmp_path, clock)
game.join("Scribe")
game.join("Reader")
events_before = len(game.events)
out = game.action("Scribe", "post", "Reader", "", "line one\nFORGED HERALD LINE")
assert "scrawl" in out.lower()
# No event appended and the daily counter is untouched.
assert len(game.events) == events_before
assert game.players["Scribe"].posts_sent == 0
# And the reader never receives it.
assert "FORGED" not in game.log("Reader")
def test_post_works_from_inside_a_building(tmp_path: Path, clock: object) -> None:
"""Posting is legal anywhere: a menu-bound sender still gets a menu reply."""
game = _game(tmp_path, clock)
game.join("Scribe")
game.join("Reader")
scribe = game.players["Scribe"]
scribe.mode = Mode.MENU
scribe.at_location = "inn"
out = game.action("Scribe", "post", "Reader", "", "by the hearth")
assert "tucks the note" in out
# The reply is the inn menu (a menu surface), not an overworld frame.
assert "(R)est" in out or "Sleeping Drake" in out
# ---------------------------------------------------------------------------
# Mail — the lobby TV must never carry a private note
# ---------------------------------------------------------------------------
def test_watch_state_excludes_targeted_rows(tmp_path: Path, clock: object) -> None:
"""EXPLICIT: a private (targeted) event must not reach the Watch herald."""
game = _game(tmp_path, clock)
game.join("Scribe")
game.join("Reader")
game.action("Scribe", "post", "Reader", "", "a secret for the Reader")
payload = build_state_payload(game)
herald = payload["herald"]
assert isinstance(herald, list)
texts = [row["text"] for row in herald]
# The join lines are public and present; the private note is absent.
assert any("Scribe" in t or "Reader" in t for t in texts) # public joins show
assert all("a secret for the Reader" not in t for t in texts)
def test_watch_state_excludes_private_ambush_note(tmp_path: Path, clock: object) -> None:
"""The ambush victim's private alert is filtered from the lobby TV too."""
game = _game(tmp_path, clock)
attacker, target = _arm_ambush(game, target_gold=80)
attacker.atk = 200
target.hp = 5
game.action("Raider", "ambush", "Sleeper", "")
herald_texts = [row["text"] for row in build_state_payload(game)["herald"]] # type: ignore[union-attr]
# The PUBLIC ambush crow is on the feed...
assert any(
"Sleeper" in t and ("made off" in t or "robbed" in t or "lifted" in t) for t in herald_texts
)
# ...but the PRIVATE "While you slept" note never is.
assert all("While you slept" not in t for t in herald_texts)
# ---------------------------------------------------------------------------
# Dice — win / lose / push under a seeded RNG, bands, cap, herald gate
# ---------------------------------------------------------------------------
def _at_inn(game: Game, name: str) -> object:
"""Join *name* and seat them at the inn (MENU surface)."""
game.join(name)
player = game.players[name]
player.mode = Mode.MENU
player.at_location = "inn"
return player
def test_gamble_win_under_seeded_rng(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
player = _at_inn(game, "Gambler")
player.gold = 100
# Seed 2 makes the gamble child roll 11 (you) vs 9 (house) -> a win.
game.rng = GameRNG(seed=2)
out = game.action("Gambler", "gamble", "", "", "", 10)
assert player.gold == 110 # stake doubled back
assert "win" in out.lower()
# No turn spent; one game counted.
assert player.turns_left == game.world.settings.daily_turns
assert player.gambles == 1
def test_gamble_lose_under_seeded_rng(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
player = _at_inn(game, "Gambler")
player.gold = 100
# Seed 0 rolls 4 (you) vs 9 (house) -> a loss.
game.rng = GameRNG(seed=0)
out = game.action("Gambler", "gamble", "", "", "", 10)
assert player.gold == 90
assert "lose" in out.lower()
assert player.gambles == 1
def test_gamble_push_under_seeded_rng(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
player = _at_inn(game, "Gambler")
player.gold = 100
# Seed 1 rolls 6 vs 6 -> a push: no gold change, but it still counts.
game.rng = GameRNG(seed=1)
out = game.action("Gambler", "gamble", "", "", "", 10)
assert player.gold == 100
assert "push" in out.lower()
assert player.gambles == 1 # a push still consumes a daily game
def test_gamble_bet_band_refused(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
player = _at_inn(game, "Gambler")
player.gold = 100_000
max_bet = game.world.settings.gamble_max_bet
low = game.action("Gambler", "gamble", "", "", "", 0)
assert f"1 to {max_bet}" in low
high = game.action("Gambler", "gamble", "", "", "", max_bet + 1)
assert f"1 to {max_bet}" in high
# A rejected bet neither moves gold nor counts toward the cap.
assert player.gold == 100_000
assert player.gambles == 0
def test_gamble_unaffordable_refused(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
player = _at_inn(game, "Gambler")
player.gold = 5
out = game.action("Gambler", "gamble", "", "", "", 10) # within band, can't cover
assert "can't cover" in out.lower()
assert player.gold == 5
assert player.gambles == 0
def test_gamble_daily_cap_refused(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
player = _at_inn(game, "Gambler")
player.gold = 100_000
cap = game.world.settings.gamble_daily_cap
player.gambles = cap # already at the cap
out = game.action("Gambler", "gamble", "", "", "", 5)
assert "enough for one day" in out
assert player.gambles == cap # not incremented past the cap
def test_gamble_outside_inn_refused(tmp_path: Path, clock: object) -> None:
"""The dice live at the inn: the verb is illegal in another building."""
game = _game(tmp_path, clock)
player = _at_inn(game, "Gambler")
player.at_location = "shop" # the shop has no 'gamble' action
player.gold = 100
out = game.action("Gambler", "gamble", "", "", "", 10)
assert "can't 'gamble' here" in out.lower()
assert player.gold == 100
def test_gamble_big_win_heralds(tmp_path: Path, clock: object) -> None:
"""A win of >= 25 gold reaches the public Herald; a small one does not."""
game = _game(tmp_path, clock)
player = _at_inn(game, "Gambler")
player.gold = 1000
# A 50-gold win (>= the 25 threshold) writes a public dice line.
game.rng = GameRNG(seed=2) # a winning roll
events_before = len(game.events)
game.action("Gambler", "gamble", "", "", "", 50)
new = game.events[events_before:]
assert any(e.kind == "gamble" and e.target == "" for e in new)
assert player.gold == 1050
def test_gamble_small_win_is_quiet(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
player = _at_inn(game, "Gambler")
player.gold = 1000
# A 10-gold win is below the 25-gold Herald threshold: no public line.
game.rng = GameRNG(seed=2)
events_before = len(game.events)
game.action("Gambler", "gamble", "", "", "", 10)
new = game.events[events_before:]
assert all(e.kind != "gamble" for e in new)
assert player.gold == 1010
# ---------------------------------------------------------------------------
# The Vault — deposit/withdraw at the inn (no turn; banked gold is safe)
# ---------------------------------------------------------------------------
def test_deposit_moves_gold_to_the_vault_no_turn(tmp_path: Path, clock: object) -> None:
"""Deposit moves coin from hand to vault, costs no turn, and is friendly."""
game = _game(tmp_path, clock)
player = _at_inn(game, "Saver")
player.gold = 100
turns_before = player.turns_left
out = game.action("Saver", "deposit", "", "", "", 60)
assert player.gold == 40
assert player.banked == 60
assert player.turns_left == turns_before # banking spends no turn
assert "strongbox" in out.lower()
def test_withdraw_moves_gold_back_to_hand(tmp_path: Path, clock: object) -> None:
"""Withdraw moves coin from vault to hand."""
game = _game(tmp_path, clock)
player = _at_inn(game, "Saver")
player.gold = 10
player.banked = 90
game.action("Saver", "withdraw", "", "", "", 50)
assert player.gold == 60
assert player.banked == 40
def test_deposit_amount_exceeding_holdings_refused(tmp_path: Path, clock: object) -> None:
"""Depositing more than you carry is refused without mutation."""
game = _game(tmp_path, clock)
player = _at_inn(game, "Saver")
player.gold = 30
player.banked = 0
out = game.action("Saver", "deposit", "", "", "", 50)
assert player.gold == 30 # unchanged
assert player.banked == 0
assert "1 to 30" in out
def test_deposit_with_nothing_in_hand_refused(tmp_path: Path, clock: object) -> None:
"""Depositing with an empty hand is a friendly refusal."""
game = _game(tmp_path, clock)
player = _at_inn(game, "Saver")
player.gold = 0
out = game.action("Saver", "deposit", "", "", "", 10)
assert player.banked == 0
assert "no coin" in out.lower()
def test_withdraw_amount_exceeding_vault_refused(tmp_path: Path, clock: object) -> None:
"""Withdrawing more than is banked is refused without mutation."""
game = _game(tmp_path, clock)
player = _at_inn(game, "Saver")
player.gold = 0
player.banked = 20
out = game.action("Saver", "withdraw", "", "", "", 50)
assert player.gold == 0
assert player.banked == 20 # unchanged
assert "1 to 20" in out
def test_withdraw_empty_vault_refused(tmp_path: Path, clock: object) -> None:
"""Withdrawing from an empty vault is a friendly refusal."""
game = _game(tmp_path, clock)
player = _at_inn(game, "Saver")
player.banked = 0
out = game.action("Saver", "withdraw", "", "", "", 10)
assert player.gold == game.world.settings.starting_gold # unchanged
assert "empty" in out.lower()
def test_status_shows_carried_and_vault_gold(tmp_path: Path, clock: object) -> None:
"""door_status reports gold as carried-on-hand plus banked-in-the-vault."""
game = _game(tmp_path, clock)
game.join("Saver")
player = game.players["Saver"]
player.gold = 75
player.banked = 250
out = game.status("Saver")
assert "75 on hand" in out
assert "250 in the vault" in out
+60
View File
@@ -0,0 +1,60 @@
"""Deterministic terrain texturing (understone.screen.texture).
Pins the contract the Watch JS mirrors: a textured glyph is a pure function of
its cell coordinate (stable per cell), an un-listed glyph is returned
untouched, and the selection formula is ``(x * _HASH_X + y * _HASH_Y) % n``
derived from the module's hash constants. The formula is asserted against those
constants so a retune moves the test with it and a drift is caught.
"""
from __future__ import annotations
from understone.screen.texture import _HASH_X, _HASH_Y, VARIANTS, textured
def test_untextured_glyph_is_unchanged() -> None:
"""A glyph with no VARIANTS row passes through verbatim (actors, walls)."""
for ch in "█@☻⌂$":
assert textured(ch, 3, 7) == ch
def test_same_coord_same_variant() -> None:
"""Texturing is position-only and stable: one cell always picks one glyph."""
first = textured(".", 12, 5)
for _ in range(5):
assert textured(".", 12, 5) == first
def test_variant_is_always_in_the_row() -> None:
"""Every selected glyph is one of the declared variants for its base."""
choices = VARIANTS["."]
for x in range(20):
for y in range(20):
assert textured(".", x, y) in choices
def test_a_row_uses_more_than_one_variant() -> None:
"""Across a row the hash spreads — the texture is not a single repeated glyph."""
seen = {textured(".", x, 0) for x in range(len(VARIANTS["."]) * 4)}
assert len(seen) > 1
def test_formula_matches_the_hash_constants() -> None:
"""The selection index is (x * _HASH_X + y * _HASH_Y) % len — the JS twin's formula.
Derived from the live ``_HASH_X`` / ``_HASH_Y`` constants (not the literal
31/17) and checked against the live VARIANTS rows, so it stays a formula
test that tracks a retune rather than a snapshot a table or constant edit
could silently invalidate.
"""
for base, choices in VARIANTS.items():
n = len(choices)
for x, y in [(0, 0), (1, 0), (0, 1), (12, 5), (7, 13), (255, 255)]:
assert textured(base, x, y) == choices[(x * _HASH_X + y * _HASH_Y) % n]
def test_origin_cell_is_the_base_glyph() -> None:
"""Cell (0,0) hashes to index 0, which is the base glyph (variants[0])."""
for base, choices in VARIANTS.items():
assert textured(base, 0, 0) == choices[0]
assert choices[0] == base
@@ -0,0 +1,81 @@
"""The one-glyph-one-column grid contract (understone.engine.textwidth).
Pins the accept/reject boundary of :func:`is_grid_safe` and proves every
:data:`SAFE_PALETTE` entry clears it. The acceptances include the
East-Asian-Width *Ambiguous* CP437 glyphs the game leans on (`` ``),
which render single-column under the Western monospace our surfaces use; the
rejections are the genuinely double-width and zero-width classes that tear a
frame.
"""
from __future__ import annotations
import unicodedata
import pytest
from understone.engine.textwidth import SAFE_PALETTE, is_grid_safe
from understone.world.loader import RESERVED_GLYPHS
# Single-column glyphs that must be admitted: plain ASCII, a Latin accent that
# is one composed code point, and the Ambiguous-width CP437 set the re-skin uses.
_ACCEPTED = ["a", "Z", "ö", "", "", "", "", "", "", "", ".", "$", " "]
# Must be rejected, with the reason each one trips the gate.
_REJECTED = {
"": "wide CJK ideograph (EAW=W) — two columns",
"🌲": "emoji (EAW=W) — two columns",
"": "fullwidth Latin A (EAW=F) — two columns",
"": "decomposed e + combining acute — two code points",
"́": "a lone combining acute — zero width",
"👨‍👩": "ZWJ sequence — multiple code points",
"ab": "two characters",
"": "empty string",
"\t": "a control character",
}
@pytest.mark.parametrize("ch", _ACCEPTED)
def test_is_grid_safe_accepts(ch: str) -> None:
assert is_grid_safe(ch) is True
@pytest.mark.parametrize("text", list(_REJECTED), ids=list(_REJECTED.values()))
def test_is_grid_safe_rejects(text: str) -> None:
assert is_grid_safe(text) is False
def test_safe_palette_is_all_grid_safe() -> None:
"""Every curated palette glyph clears the gate — the appendix can't ship a dud."""
bad = [g for g in SAFE_PALETTE if not is_grid_safe(g)]
assert bad == [], f"palette has non-grid-safe glyphs: {bad}"
def test_safe_palette_has_no_reserved_glyphs() -> None:
"""No palette glyph is a loader-reserved marker — the 'author-usable' promise.
The appendix tells a pack author to pull any palette glyph for terrain,
structures, or actors, but the loader rejects the box-drawing frame lines
and the '@'/'' player markers (``loader.RESERVED_GLYPHS``). A palette entry
that is also reserved would hand the author a glyph that load-fails the
exact doc-vs-enforcement trap. Guarding the intersection keeps "all tested
safe AND author-usable" enforced, not merely asserted on width.
"""
collisions = set(SAFE_PALETTE) & RESERVED_GLYPHS
assert collisions == set(), f"palette offers loader-reserved glyphs: {sorted(collisions)}"
def test_safe_palette_has_no_duplicates() -> None:
"""The palette is a set in spirit; a dupe would be an authoring slip."""
assert len(SAFE_PALETTE) == len(set(SAFE_PALETTE))
def test_ambiguous_width_glyphs_are_accepted() -> None:
"""Document the load-bearing call: EAW=Ambiguous is admitted, not barred.
These are the CP437 glyphs the game depends on; if a future tightening
barred Ambiguous, the whole re-skin would vanish from the map.
"""
for ch in "█♣↑∩≈★":
assert unicodedata.east_asian_width(ch) == "A"
assert is_grid_safe(ch) is True
+94
View File
@@ -0,0 +1,94 @@
"""Daily-turn budget and UTC rollover tests.
Covers spend/refuse semantics, the lazy reset when the UTC day advances
(including a 23:59 -> 00:01 crossing on the same Player instance), and the
shared rollover of the bestow pool.
"""
from __future__ import annotations
from tests.conftest import fixed_clock, make_player, utc
from understone.engine.turns import ensure_day, spend_turn
def test_spend_decrements() -> None:
player = make_player(turns_left=3)
assert spend_turn(player) is True
assert player.turns_left == 2
def test_spend_refuses_at_zero_without_mutation() -> None:
player = make_player(turns_left=0)
before = player.turns_left
assert spend_turn(player) is False
assert player.turns_left == before
def test_ensure_day_resets_on_new_day() -> None:
day = utc(2026, 6, 12).toordinal()
player = make_player(turns_left=0, turn_day=day - 1, bestow_spent=20, bestow_day=day - 1)
reset = ensure_day(player, fixed_clock(utc(2026, 6, 12, 9, 0)), daily_turns=10)
assert reset is True
assert player.turns_left == 10
assert player.turn_day == day
assert player.bestow_spent == 0
assert player.bestow_day == day
def test_ensure_day_noop_within_same_day() -> None:
day = utc(2026, 6, 12).toordinal()
# Every day marker is already today, so no allowance (turns, bestow, posts,
# dice) is touched — the rollover is a pure no-op.
player = make_player(
turns_left=4,
turn_day=day,
bestow_spent=10,
bestow_day=day,
post_day=day,
gamble_day=day,
)
reset = ensure_day(player, fixed_clock(utc(2026, 6, 12, 23, 0)), daily_turns=10)
assert reset is False
assert player.turns_left == 4
assert player.bestow_spent == 10
def test_midnight_crossing_refreshes_on_same_instance() -> None:
# Evening of day one: spend down to a low budget.
player = make_player(turns_left=10, turn_day=0, bestow_spent=0, bestow_day=0)
evening = utc(2026, 6, 12, 23, 59)
ensure_day(player, fixed_clock(evening), daily_turns=10)
for _ in range(8):
spend_turn(player)
assert player.turns_left == 2
# Just past midnight (UTC) the next action refreshes the budget.
after_midnight = utc(2026, 6, 13, 0, 1)
reset = ensure_day(player, fixed_clock(after_midnight), daily_turns=10)
assert reset is True
assert player.turns_left == 10
assert player.turn_day == after_midnight.toordinal()
def test_bestow_pool_resets_on_the_same_boundary() -> None:
player = make_player(bestow_spent=25, bestow_day=utc(2026, 6, 12).toordinal())
ensure_day(player, fixed_clock(utc(2026, 6, 13, 0, 1)), daily_turns=10)
assert player.bestow_spent == 0
assert player.bestow_day == utc(2026, 6, 13).toordinal()
def test_social_caps_reset_on_the_same_boundary() -> None:
"""Posts and dice counts ride the same UTC rollover as turns and bestow."""
yesterday = utc(2026, 6, 12).toordinal()
player = make_player(
posts_sent=5,
post_day=yesterday,
gambles=5,
gamble_day=yesterday,
)
reset = ensure_day(player, fixed_clock(utc(2026, 6, 13, 0, 1)), daily_turns=10)
assert reset is True
assert player.posts_sent == 0
assert player.post_day == utc(2026, 6, 13).toordinal()
assert player.gambles == 0
assert player.gamble_day == utc(2026, 6, 13).toordinal()
+591
View File
@@ -0,0 +1,591 @@
"""Watch-page payload builders and the watch-URL advertisement.
These are pure-unit tests of :mod:`understone.watch` (no network): the static
world payload's shape and legend completeness, the dynamic state payload's
player/herald/hall content under a frozen clock, and the join/help "Watch the
Vale live" line that appears only when a Game carries a watch URL.
"""
from __future__ import annotations
import re
from pathlib import Path
from typing import TYPE_CHECKING
import pytest
from tests.conftest import fixed_clock, utc
from understone import server as understone_server
from understone import watch
from understone.engine.log import Event
from understone.engine.rng import GameRNG
from understone.game import Game
from understone.persistence import Store
from understone.screen.palette import Color
from understone.world.loader import load_world
if TYPE_CHECKING:
from understone.engine.world import World
PACK = Path(__file__).resolve().parents[1] / "understone" / "world" / "data"
@pytest.fixture
def world() -> World:
return load_world(PACK)
@pytest.fixture
def clock() -> object:
return fixed_clock(utc(2026, 6, 12, 10, 30))
def _game(tmp_path: Path, clock: object, watch_url: str | None = None) -> Game:
world = load_world(PACK)
store = Store(tmp_path / "watch.db")
return Game( # type: ignore[arg-type]
world, store, clock=clock, rng=GameRNG(seed=7), watch_url=watch_url
)
# ---------------------------------------------------------------------------
# World payload (static)
# ---------------------------------------------------------------------------
def test_world_payload_shape(world: World) -> None:
payload = watch.build_world_payload(world)
assert payload["name"] == world.name
assert payload["width"] == world.width
assert payload["height"] == world.height
rows = payload["glyph_rows"]
assert isinstance(rows, list)
assert len(rows) == world.height
assert all(isinstance(r, str) and len(r) == world.width for r in rows)
def test_world_payload_legend_is_complete(world: World) -> None:
payload = watch.build_world_payload(world)
rows = payload["glyph_rows"]
legend = payload["legend"]
assert isinstance(rows, list)
assert isinstance(legend, dict)
# Contract: every glyph that appears in the rows has a colour in the legend.
glyphs = {ch for row in rows for ch in row}
assert glyphs <= set(legend)
# And every legend colour is a real palette colour name (no stray roles).
valid = {c.value for c in Color}
assert set(legend.values()) <= valid
def test_world_payload_locations_present(world: World) -> None:
payload = watch.build_world_payload(world)
locations = payload["locations"]
assert isinstance(locations, list)
assert len(locations) == len(world.locations)
by_name = {loc["name"]: loc for loc in locations}
# The dungeon mouth rides in the locations overlay with its glyph + colour.
deep = by_name["The Understone Deep"]
assert deep["glyph"] == ""
assert deep["color"] == "dungeon"
assert (deep["x"], deep["y"]) == (70, 12)
def test_world_payload_carries_reskinned_glyphs(world: World) -> None:
"""The v0.6 re-skin reaches the Watch: ≋ water in the rows, ⌂/✚/∩ buildings.
Water rides the base terrain (glyph_rows + legend); the buildings ride the
locations overlay. If a glyph reverts, the live map drifts from the frames.
"""
payload = watch.build_world_payload(world)
rows = payload["glyph_rows"]
assert isinstance(rows, list)
glyphs = {ch for row in rows for ch in row}
assert "" in glyphs # water in the base map
assert "~" not in glyphs # the old water glyph is gone
legend = payload["legend"]
assert isinstance(legend, dict)
assert "" in legend
by_name = {loc["name"]: loc["glyph"] for loc in payload["locations"]} # type: ignore[index,union-attr]
assert by_name["The Sleeping Drake"] == ""
assert by_name["The Quiet Shrine"] == ""
assert by_name["The Understone Deep"] == ""
# ---------------------------------------------------------------------------
# v0.9 colour-role split — the payload now carries the EXPANDED vocabulary, so
# distinct terrain/building types read by hue on the Watch and not just by glyph.
# These pin the literal fixes: road no longer shares grass's colour, forest no
# longer shares tree's, the town buildings each carry their own role, and the
# Cinder slag is lava (orange), no longer water (blue).
# ---------------------------------------------------------------------------
CINDER = Path(__file__).resolve().parents[1] / "understone" / "world" / "packs" / "cinder-wastes"
def _terrain_kinds(world: World) -> dict[str, str]:
"""Return the distinct terrain kinds in *world* as ``{key: colour role}``.
``world.terrain`` is the painted 2-D grid (one ``TerrainDef`` per cell); the
distinct kinds are recovered by deduplicating it on ``key``. Every kind in a
shipped world appears on the map, so this sees all of them.
"""
kinds: dict[str, str] = {}
for row in world.terrain:
for cell in row:
kinds[cell.key] = cell.color
return kinds
def _legend_for_terrain_key(world: World, key: str) -> str:
"""Return the legend colour the payload carries for terrain ``key``.
Resolves the terrain key to its glyph, then reads that glyph's colour out of
the built payload's legend — so the assertion is on what the Watch receives,
not on the raw JSON.
"""
payload = watch.build_world_payload(world)
legend = payload["legend"]
assert isinstance(legend, dict)
glyph = next(cell.glyph for row in world.terrain for cell in row if cell.key == key)
return legend[glyph]
def test_vale_payload_road_is_not_floor(world: World) -> None:
"""REGRESSION (the literal bug the slice fixes): road has its OWN colour.
Before v0.9 the Vale road shared ``floor`` with grass, so a path was
indistinguishable from open ground on the Watch. The road now carries
``road``; grass keeps ``floor``; they must differ.
"""
road = _legend_for_terrain_key(world, "road")
grass = _legend_for_terrain_key(world, "grass")
assert road == "road"
assert grass == "floor"
assert road != grass
def test_vale_payload_forest_is_not_tree(world: World) -> None:
"""REGRESSION: forest has its OWN colour, no longer shared with tree.
Dense forest scrub used to share ``tree`` with the tree wall, so the two
read identically. Forest now carries ``forest``; tree keeps ``tree``.
"""
forest = _legend_for_terrain_key(world, "forest")
tree = _legend_for_terrain_key(world, "tree")
assert forest == "forest"
assert tree == "tree"
assert forest != tree
def test_vale_payload_buildings_carry_distinct_roles(world: World) -> None:
"""Each Vale town building rides its own role (inn/shop/healer), not ``town``."""
payload = watch.build_world_payload(world)
by_name = {loc["name"]: loc["color"] for loc in payload["locations"]} # type: ignore[index,union-attr]
assert by_name["The Sleeping Drake"] == "inn"
assert by_name["Gravel & Sons Outfitters"] == "shop"
assert by_name["The Quiet Shrine"] == "healer"
assert by_name["The Understone Deep"] == "dungeon"
# No two distinct buildings share a colour role.
roles = list(by_name.values())
assert len(set(roles)) == len(roles)
def test_cinder_payload_slag_is_lava_not_water() -> None:
"""The Cinder slag carries ``lava`` (orange), never ``water`` (blue) again.
This is the Cinder half of the bug: molten slag shared ``water``, so the
lava rendered BLUE on the Watch. After the remap the legend carries ``lava``
and ``water`` appears NOWHERE in the Cinder payload (no water in this world).
"""
cinder = load_world(CINDER)
payload = watch.build_world_payload(cinder)
legend = payload["legend"]
assert isinstance(legend, dict)
assert _legend_for_terrain_key(cinder, "slag") == "lava"
assert "water" not in legend.values()
def test_cinder_payload_carries_expanded_roles() -> None:
"""The Cinder terrain reads by hue: ash→barren, basalt→road, cinder→scrub.
Cinder-fields use ``scrub`` (dusky ember-brown), NOT ``forest`` (green)
a volcanic waste must not render as lush woods. ``forest`` is for green
worlds; ``scrub`` is its barren counterpart.
"""
cinder = load_world(CINDER)
assert _legend_for_terrain_key(cinder, "ash") == "barren"
assert _legend_for_terrain_key(cinder, "basalt") == "road"
assert _legend_for_terrain_key(cinder, "cinder") == "scrub"
legend = watch.build_world_payload(cinder)["legend"]
assert isinstance(legend, dict)
assert "forest" not in legend.values() # no green woods in a volcanic waste
# Obsidian spire reuses the wall role (a rock barrier), same as caldera.
assert _legend_for_terrain_key(cinder, "spire") == "wall"
assert _legend_for_terrain_key(cinder, "caldera") == "wall"
def test_both_worlds_terrain_roles_are_distinct_per_world() -> None:
"""No two DISTINCT terrain types share a colour role within a world.
The point of the slice: after the remap each terrain kind reads by its own
hue. (A role MAY be shared by two types that are deliberately the same
barrier spire/caldera both ``wall`` in Cinder so this checks distinct
KEYS that map to the same role are only the intended wall pair.)
"""
for world_dir, allowed_shared in (
(PACK, set()),
(CINDER, {("caldera", "spire")}),
):
w = load_world(world_dir)
by_role: dict[str, list[str]] = {}
for key, role in _terrain_kinds(w).items():
by_role.setdefault(role, []).append(key)
for role, keys in by_role.items():
if len(keys) > 1:
pair = tuple(sorted(keys))
assert pair in allowed_shared, f"unexpected shared role {role!r}: {keys}"
# ---------------------------------------------------------------------------
# State payload (dynamic)
# ---------------------------------------------------------------------------
def test_state_payload_includes_joined_player(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
game.join("Brandr")
payload = watch.build_state_payload(game)
players = payload["players"]
assert isinstance(players, list)
brandr = next(p for p in players if p["name"] == "Brandr")
assert brandr["level"] == 1
assert brandr["wins"] == 0
assert brandr["hp"] == brandr["max_hp"]
assert brandr["mode"] == "tile"
assert (brandr["x"], brandr["y"]) == game.world.spawn
# v0.10: a fresh hero shows their starting gold on hand, nothing banked, and
# an empty satchel.
assert brandr["gold"] == game.world.settings.starting_gold
assert brandr["banked"] == 0
assert brandr["satchel"] == []
def test_state_payload_surfaces_gold_banked_and_satchel(tmp_path: Path, clock: object) -> None:
"""A joined hero with a stocked satchel and banked gold shows the right values.
The lobby TV surfaces the whole shared world, so each player's purse (gold
on hand + vault) and satchel stacks (name + qty, resolved via the pack) ride
the state payload.
"""
game = _game(tmp_path, clock)
game.join("Brandr")
player = game.players["Brandr"]
player.gold = 120
player.banked = 300
game._satchel_set_stacks(player, [("iron_ore", 5), ("minor_potion", 2)])
payload = watch.build_state_payload(game)
brandr = next(p for p in payload["players"] if p["name"] == "Brandr") # type: ignore[union-attr]
assert brandr["gold"] == 120
assert brandr["banked"] == 300
# Stacks resolve their display name from the pack, preserving stow order.
assert brandr["satchel"] == [
{"name": "Iron Ore", "qty": 5},
{"name": "Minor Potion", "qty": 2},
]
def test_state_payload_satchel_unknown_id_falls_back_to_raw(tmp_path: Path, clock: object) -> None:
"""A satchel id no longer in the pack falls back to the raw id, never blank."""
game = _game(tmp_path, clock)
game.join("Brandr")
game.players["Brandr"].satchel = "ghost_item:2" # not in the pack
payload = watch.build_state_payload(game)
brandr = next(p for p in payload["players"] if p["name"] == "Brandr") # type: ignore[union-attr]
assert brandr["satchel"] == [{"name": "ghost_item", "qty": 2}]
def test_state_payload_reports_all_players_including_menu(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
game.join("Brandr")
game.join("Sigrun")
# Put Sigrun in a MENU surface; the Watch still shows her on the board.
sigrun = game.players["Sigrun"]
from understone.engine.models import Mode
sigrun.mode = Mode.MENU
sigrun.at_location = "inn"
payload = watch.build_state_payload(game)
names = {p["name"] for p in payload["players"]} # type: ignore[union-attr]
assert names == {"Brandr", "Sigrun"}
menu = next(p for p in payload["players"] if p["name"] == "Sigrun") # type: ignore[union-attr]
assert menu["mode"] == "menu"
def test_state_payload_ts_comes_from_clock(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
payload = watch.build_state_payload(game)
assert payload["ts"] == "2026-06-12T10:30:00+00:00"
def test_state_payload_herald_is_last_15_oldest_first(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
# Replace the resident feed with 20 synthetic events in ascending id order.
game.events = [
Event(
event_id=i,
ts=f"2026-06-12T10:{i:02d}:00+00:00",
kind="join",
actor=f"Hero{i}",
text=f"event {i}",
)
for i in range(1, 21)
]
payload = watch.build_state_payload(game)
herald = payload["herald"]
assert isinstance(herald, list)
assert len(herald) == 15
# Oldest-first: the window is events 6..20, in ascending order.
assert herald[0]["text"] == "event 6"
assert herald[-1]["text"] == "event 20"
def test_state_payload_herald_full_window_despite_sparse_ids(tmp_path: Path, clock: object) -> None:
"""Id gaps must not shrink the feed (regression: the window is a list
tail, not id arithmetic AUTOINCREMENT ids may be non-contiguous)."""
game = _game(tmp_path, clock)
game.events = [
Event(
event_id=i * 7, # sparse, non-contiguous ids
ts=f"2026-06-12T10:{i:02d}:00+00:00",
kind="join",
actor=f"Hero{i}",
text=f"event {i}",
)
for i in range(1, 21)
]
herald = watch.build_state_payload(game)["herald"]
assert len(herald) == 15
assert herald[0]["text"] == "event 6"
assert herald[-1]["text"] == "event 20"
def test_state_payload_herald_handles_short_feed(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
game.events = [
Event(
event_id=1,
ts="2026-06-12T10:00:00+00:00",
kind="join",
actor="Solo",
text="only one",
)
]
payload = watch.build_state_payload(game)
herald = payload["herald"]
assert isinstance(herald, list)
assert [e["text"] for e in herald] == ["only one"]
def test_state_payload_hall_capped_at_five(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
# Seven immortalised runs; the Watch shows only the five most recent.
for i in range(7):
game.store.insert_hall_row(f"Hero{i}", f"2026-06-{10 + i:02d}T12:00:00+00:00", i, 6 + i)
game.store.commit()
payload = watch.build_state_payload(game)
hall = payload["hall"]
assert isinstance(hall, list)
assert len(hall) == 5
# Newest first (store ordering): Hero6 leads.
assert hall[0]["name"] == "Hero6"
assert hall[0]["level_at_win"] == 12
# ---------------------------------------------------------------------------
# Watch-URL advertisement (join banner + help manual)
# ---------------------------------------------------------------------------
def test_join_advertises_watch_url_when_set(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock, watch_url="http://127.0.0.1:8077/watch")
out = game.join("Brandr")
assert "Watch the Vale live: http://127.0.0.1:8077/watch" in out
def test_join_omits_watch_line_when_unset(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock)
out = game.join("Brandr")
assert "Watch the Vale live" not in out
def test_resume_advertises_watch_url_when_set(tmp_path: Path, clock: object) -> None:
game = _game(tmp_path, clock, watch_url="http://127.0.0.1:8077/watch")
game.join("Brandr")
again = game.join("Brandr")
assert "Welcome back" in again
assert "Watch the Vale live: http://127.0.0.1:8077/watch" in again
def test_help_advertises_watch_url_when_set(tmp_path: Path) -> None:
# door_help reads the module game; install one carrying a watch URL.
world = load_world(PACK)
store = Store(tmp_path / "help.db")
understone_server._set_game(Game(world, store, watch_url="http://127.0.0.1:8077/watch"))
try:
manual = understone_server.door_help()
assert "Watch the Vale live: http://127.0.0.1:8077/watch" in manual
finally:
understone_server._GAME.store.close() # type: ignore[union-attr]
understone_server._GAME = None
def test_help_omits_watch_line_when_unset(tmp_path: Path) -> None:
world = load_world(PACK)
store = Store(tmp_path / "help.db")
understone_server._set_game(Game(world, store))
try:
manual = understone_server.door_help()
assert "Watch the Vale live" not in manual
finally:
understone_server._GAME.store.close() # type: ignore[union-attr]
understone_server._GAME = None
# ---------------------------------------------------------------------------
# WATCH_HTML lockstep guards (the JS twin of texture.py + the v0.6 glow-up)
#
# The inline page reproduces logic that lives in Python; these guard the two
# invariants most prone to silent drift — the texture selection formula and the
# other-player marker — plus the presence of the day-phase machinery.
# ---------------------------------------------------------------------------
def test_watch_html_derives_texture_formula_from_constants() -> None:
"""The page's JS index string is DERIVED from texture._HASH_X / _HASH_Y.
Not a hard-coded "x * 31 + y * 17" snapshot: the expected substring is built
from the live constants, so a Python-side retune that the watch builder
fails to track trips here instead of silently shipping a stale formula.
"""
from understone.screen import texture
expected = f"x * {texture._HASH_X} + y * {texture._HASH_Y}"
assert expected in watch.WATCH_HTML
def test_watch_html_js_selection_agrees_with_textured() -> None:
"""The JS selection arithmetic, replayed in Python, matches ``textured``.
The page computes ``variants[(x * _HASH_X + y * _HASH_Y) % len]``. Replaying
that exact formula here from the SAME constants and the SAME VARIANTS rows
and asserting it equals ``texture.textured`` over a full screen grid proves
both implementations select identically a stronger lockstep than a string
match, since it pins the result, not the source text.
"""
from understone.screen import texture
for base, choices in texture.VARIANTS.items():
for x in range(24):
for y in range(16):
js_pick = choices[(x * texture._HASH_X + y * texture._HASH_Y) % len(choices)]
assert texture.textured(base, x, y) == js_pick
def test_watch_html_variants_match_texture_table() -> None:
"""Every base->variants row in texture.VARIANTS appears in the JS VARIANTS map.
Glyphs ride into the inline JS as ``\\uXXXX`` escapes, so compare against the
escaped form. A new variant added to Python but not the page trips this.
"""
from understone.screen import texture
html = watch.WATCH_HTML
for base, choices in texture.VARIANTS.items():
for glyph in {base, *choices}:
token = glyph if glyph.isascii() else f"\\u{ord(glyph):04x}"
assert token in html, f"variant glyph {glyph!r} missing from WATCH_HTML"
def test_watch_html_uses_other_player_marker() -> None:
"""Players on the lobby TV wear the ☻ marker (escaped) — no bare '@' marker paint."""
assert "\\u263b" in watch.WATCH_HTML
def test_watch_html_renders_gold_banked_and_satchel() -> None:
"""The Adventurers panel JS references each player's gold, vault, and satchel."""
html = watch.WATCH_HTML
# The roster sub-lines read these state fields by name.
assert "p.gold" in html
assert "p.banked" in html
assert "p.satchel" in html
# The satchel line has a dedicated renderer with an empty-bag note.
assert "satchelText" in html
assert "satchel empty" in html
assert "vault" in html
def test_watch_html_has_day_phase_machinery() -> None:
"""The dusk/dawn glow-up is wired: the tint classes and the UTC-hour read."""
html = watch.WATCH_HTML
assert "applyDayPhase" in html
assert "getUTCHours" in html
assert ".map-frame.night" in html
assert ".map-frame.twilight" in html
assert "Noto Sans Mono" in html
# ---------------------------------------------------------------------------
# PALETTE completeness — the v0.9 invariant that kills the "silent fallback"
# bug class. The road bug existed because a Color role with no hex in the JS
# PALETTE map fell back to default; this pins that EVERY role has a hex.
# ---------------------------------------------------------------------------
def _watch_palette_keys() -> set[str]:
"""Parse the JS ``var PALETTE = { ... }`` map out of WATCH_HTML, return its keys.
The map uses bare (unquoted) JS identifier keys ``road: "#b89a6a",`` so
this slices the object literal and collects every ``key:`` token. Keeping the
parse here (not a hard-coded list) means the test reads whatever the page
actually ships, so a typo'd or dropped key surfaces as a missing role.
"""
html = watch.WATCH_HTML
start = html.index("var PALETTE = {")
body = html[start : html.index("};", start)]
# Each entry is `<ident>: "<hex>"`; capture the identifier before the colon.
return set(re.findall(r"(\w+)\s*:\s*\"#", body))
def test_watch_palette_covers_every_color_role() -> None:
"""EVERY Color enum value has an entry in the JS PALETTE map — no fallbacks.
This is the literal fix for the road bug: a shipped role with no hex paints
as ``default`` silently. Asserting ``{c.value} <= palette_keys`` means adding
a Color without a Watch hex trips here instead of shipping a grey/green road.
"""
palette_keys = _watch_palette_keys()
roles = {c.value for c in Color}
missing = roles - palette_keys
assert not missing, f"Color roles with no PALETTE hex (silent fallback): {sorted(missing)}"
def test_watch_palette_distinct_new_terrain_hexes() -> None:
"""The expanded terrain roles carry DISTINCT hexes (the point of the slice).
A guard that the seven new roles didn't accidentally collapse onto one hex
(which would re-introduce the very "two types, one colour" bug v0.9 fixes).
Parsed straight from the shipped map.
"""
html = watch.WATCH_HTML
start = html.index("var PALETTE = {")
body = html[start : html.index("};", start)]
pairs = dict(re.findall(r"(\w+)\s*:\s*\"(#[0-9a-fA-F]{6})\"", body))
new_roles = ["road", "forest", "lava", "barren", "inn", "shop", "healer"]
hexes = [pairs[r] for r in new_roles]
assert all(r in pairs for r in new_roles), "a new v0.9 role is missing its hex"
assert len(set(hexes)) == len(hexes), f"new roles share a hex: {hexes}"
# The molten role must NOT reuse water's blue (the Cinder slag bug).
assert pairs["lava"] != pairs["water"]
@@ -0,0 +1,143 @@
"""Tests for the per-pack Watch CRT theme (v0.8).
Covers the loader band (each of the four legal themes loads; an unknown theme
is rejected naming the legal set; an omitted theme defaults to phosphor), the
state-payload carrying the theme, and the WATCH_HTML page's JS THEME table —
including the load-bearing guard that the "phosphor" values byte-match the
original ``:root`` CSS, so the bundled Vale stays visually identical.
"""
from __future__ import annotations
import json
import shutil
from pathlib import Path
from typing import Any
import pytest
from understone import watch
from understone.errors import WorldLoadError
from understone.world.loader import (
DEFAULT_WATCH_THEME,
WATCH_THEMES,
load_world,
)
SHIPPED = Path(__file__).resolve().parents[1] / "understone" / "world" / "data"
# The original :root CRT custom-property values (pre-v0.8). The "phosphor" theme
# MUST reproduce these byte-for-byte so the default Vale is pixel-identical.
_ORIGINAL_ROOT = {
"--phosphor": "#7dffa0",
"--phosphor-dim": "#2f7a46",
"--amber": "#ffb44d",
"--bg": "#050a06",
"--panel": "#0a140d",
"--edge": "#163a22",
}
def _pack_with_theme(tmp_path: Path, theme: Any) -> Path:
"""Clone the Vale into a temp pack with ``settings.watch_theme`` set/removed.
``theme`` set to a string writes that value; set to the sentinel ``...``
DELETES the key entirely (to exercise the omitted-defaults path).
"""
dest = tmp_path / "themed"
shutil.copytree(SHIPPED, dest)
world_json = dest / "world.json"
data = json.loads(world_json.read_text(encoding="utf-8"))
if theme is ...:
data["settings"].pop("watch_theme", None)
else:
data["settings"]["watch_theme"] = theme
world_json.write_text(json.dumps(data), encoding="utf-8")
return dest
# ---------------------------------------------------------------------------
# loader band
# ---------------------------------------------------------------------------
@pytest.mark.parametrize("theme", sorted(WATCH_THEMES))
def test_each_legal_theme_loads(tmp_path: Path, theme: str) -> None:
pack = _pack_with_theme(tmp_path, theme)
world = load_world(pack)
assert world.settings.watch_theme == theme
def test_unknown_theme_rejected_naming_the_set(tmp_path: Path) -> None:
pack = _pack_with_theme(tmp_path, "ultraviolet")
with pytest.raises(WorldLoadError) as exc:
load_world(pack)
message = str(exc.value)
assert "watch_theme" in message
assert "ultraviolet" in message
# The friendly message lists every legal theme so the author can fix it.
for name in WATCH_THEMES:
assert name in message
def test_omitted_theme_defaults_to_phosphor(tmp_path: Path) -> None:
pack = _pack_with_theme(tmp_path, ...) # delete the key entirely
world = load_world(pack)
assert world.settings.watch_theme == DEFAULT_WATCH_THEME == "phosphor"
def test_shipped_vale_is_phosphor() -> None:
"""The bundled Vale ships the phosphor theme (its green is unchanged)."""
world = load_world(SHIPPED)
assert world.settings.watch_theme == "phosphor"
# ---------------------------------------------------------------------------
# payload + WATCH_HTML
# ---------------------------------------------------------------------------
def test_world_payload_carries_theme(tmp_path: Path) -> None:
pack = _pack_with_theme(tmp_path, "ice")
world = load_world(pack)
payload = watch.build_world_payload(world)
assert payload["theme"] == "ice"
def test_shipped_payload_theme_is_phosphor() -> None:
world = load_world(SHIPPED)
payload = watch.build_world_payload(world)
assert payload["theme"] == "phosphor"
def test_watch_html_has_theme_table_and_all_names() -> None:
"""The page carries a JS THEME table keyed by every legal theme name."""
html = watch.WATCH_HTML
assert "var THEMES" in html
assert "applyTheme" in html
for name in WATCH_THEMES:
# Each theme is a JS object key, e.g. ``phosphor: {``.
assert f"{name}: {{" in html, f"theme {name!r} missing from THEME table"
def test_watch_html_phosphor_values_byte_match_original_root() -> None:
"""The "phosphor" theme reproduces the original :root values exactly.
This is the load-bearing guard for "the Vale looks identical": every
original custom-property value still appears in the page (in the :root block
AND the THEME table), so swapping in the phosphor theme is a no-op repaint.
"""
html = watch.WATCH_HTML
for prop, value in _ORIGINAL_ROOT.items():
# The value lives both in the :root CSS and the phosphor theme entry.
assert html.count(value) >= 2, f"{prop} value {value} not byte-matched twice"
# And the phosphor theme maps the property to exactly that value.
assert f'"{prop}": "{value}"' in html, f"phosphor {prop} != {value}"
def test_watch_html_applies_theme_on_world_fetch() -> None:
"""The page applies the theme when world.json arrives (in paintMap)."""
html = watch.WATCH_HTML
assert "applyTheme(world.theme)" in html
# It swaps CSS custom properties on the document root.
assert "documentElement.style.setProperty" in html
@@ -0,0 +1,851 @@
"""Content-pack loader tests.
Asserts the shipped pack loads, and that representative malformed packs
each raise :class:`WorldLoadError` with a readable message: a bad legend
character, a location placed on non-walkable terrain, a row-width / height
mismatch, and an economy setting outside its sanity band.
"""
from __future__ import annotations
import json
import shutil
from pathlib import Path
from typing import Any
import pytest
from understone.errors import WorldLoadError
from understone.world.loader import load_world
SHIPPED = Path(__file__).resolve().parents[1] / "understone" / "world" / "data"
def test_shipped_pack_loads() -> None:
world = load_world(SHIPPED)
assert world.name == "The Vale of Understone"
assert world.width == 96
assert world.height == 48
assert world.is_walkable(*world.spawn)
assert len(world.locations) == 4
assert len(world.zones) == 2
# Tiers 1..5 are the random foes; tier 6 is the boss (the Wyrm Below).
assert {m.tier for m in world.monsters} == {1, 2, 3, 4, 5, 6}
boss = world.monster_by_id(world.settings.boss_monster)
assert boss is not None and boss.boss and boss.name == "the Wyrm Below"
def _clone_pack(tmp_path: Path) -> Path:
dest = tmp_path / "pack"
shutil.copytree(SHIPPED, dest)
return dest
def _rewrite(path: Path, mutate: Any) -> None:
data = json.loads(path.read_text(encoding="utf-8"))
mutate(data)
path.write_text(json.dumps(data), encoding="utf-8")
def test_bad_legend_char_rejected(tmp_path: Path) -> None:
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
# Splice an unknown glyph into the middle of a terrain row.
row = list(data["terrain_rows"][24])
row[40] = "Z"
data["terrain_rows"][24] = "".join(row)
_rewrite(pack / "world.json", mutate)
with pytest.raises(WorldLoadError, match="not in the legend"):
load_world(pack)
def test_location_on_non_walkable_rejected(tmp_path: Path) -> None:
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
# Move the inn onto a tree-border tile (col 0 is the tree frame).
for loc in data["locations"]:
if loc["key"] == "inn":
loc["x"] = 0
loc["y"] = 24
_rewrite(pack / "world.json", mutate)
with pytest.raises(WorldLoadError, match="non-walkable"):
load_world(pack)
def test_dimension_mismatch_rejected(tmp_path: Path) -> None:
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
# Truncate one row so its width no longer matches the declared width.
data["terrain_rows"][10] = data["terrain_rows"][10][:-5]
_rewrite(pack / "world.json", mutate)
with pytest.raises(WorldLoadError, match="wide but width is"):
load_world(pack)
def test_height_mismatch_rejected(tmp_path: Path) -> None:
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
data["terrain_rows"] = data["terrain_rows"][:-1]
_rewrite(pack / "world.json", mutate)
with pytest.raises(WorldLoadError, match="rows but height is"):
load_world(pack)
def test_settings_out_of_band_rejected(tmp_path: Path) -> None:
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
data["settings"]["daily_turns"] = 0 # band is 1..100
_rewrite(pack / "world.json", mutate)
with pytest.raises(WorldLoadError, match="daily_turns"):
load_world(pack)
def test_start_hp_zero_rejected(tmp_path: Path) -> None:
"""A starting HP of 0 is out of band (1..500): a hero must begin alive."""
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
data["settings"]["start_hp"] = 0 # band is 1..500
_rewrite(pack / "world.json", mutate)
with pytest.raises(WorldLoadError, match="start_hp"):
load_world(pack)
def test_unknown_starting_item_rejected(tmp_path: Path) -> None:
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
data["settings"]["starting_weapon"] = "no_such_blade"
_rewrite(pack / "world.json", mutate)
with pytest.raises(WorldLoadError, match="not a known item id"):
load_world(pack)
def test_missing_pack_file_rejected(tmp_path: Path) -> None:
pack = _clone_pack(tmp_path)
(pack / "monsters.json").unlink()
with pytest.raises(WorldLoadError, match="missing pack file"):
load_world(pack)
def test_monster_nonpositive_hp_rejected(tmp_path: Path) -> None:
pack = _clone_pack(tmp_path)
def mutate(data: list[dict[str, Any]]) -> None:
data[0]["hp"] = 0 # a monster with no hit points is unkillable nonsense
_rewrite(pack / "monsters.json", mutate)
with pytest.raises(WorldLoadError, match=r"monsters\.json\[0\] hp must be >= 1"):
load_world(pack)
def test_monster_negative_stat_rejected(tmp_path: Path) -> None:
pack = _clone_pack(tmp_path)
def mutate(data: list[dict[str, Any]]) -> None:
data[1]["gold"] = -5
_rewrite(pack / "monsters.json", mutate)
with pytest.raises(WorldLoadError, match=r"monsters\.json\[1\] gold must be >= 0"):
load_world(pack)
def test_item_negative_price_rejected(tmp_path: Path) -> None:
pack = _clone_pack(tmp_path)
def mutate(data: list[dict[str, Any]]) -> None:
data[1]["price"] = -10 # a negative price would pay the player to take it
_rewrite(pack / "items.json", mutate)
with pytest.raises(WorldLoadError, match=r"items\.json\[1\] price must be >= 0"):
load_world(pack)
def test_dungeon_tier_without_monster_rejected(tmp_path: Path) -> None:
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
# Tier 9 has no monster in the pack, so the gauntlet rung is unfillable.
data["settings"]["dungeon_tiers"] = [4, 9]
_rewrite(pack / "world.json", mutate)
with pytest.raises(WorldLoadError, match=r"dungeon_tiers\[1\] = 9 has no non-boss monster"):
load_world(pack)
def test_dungeon_tiers_empty_rejected(tmp_path: Path) -> None:
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
data["settings"]["dungeon_tiers"] = []
_rewrite(pack / "world.json", mutate)
with pytest.raises(WorldLoadError, match="dungeon_tiers must be a non-empty list"):
load_world(pack)
def test_dungeon_tier_backed_only_by_boss_rejected(tmp_path: Path) -> None:
"""A boss-only tier is unfillable: the gauntlet excludes boss monsters.
Tier 6 in the shipped pack holds only the Wyrm Below (a boss). A gauntlet
rung at tier 6 would draw from monsters_for_tier_band, which filters bosses
out, so the rung silently does nothing the loader must reject it instead.
The message says "no NON-boss monster" (not merely "no monster"): the boss
is present at that tier, it just cannot fill a rung, and the wording must
point the author at exactly that.
"""
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
data["settings"]["dungeon_tiers"] = [4, 6] # 6 is the boss-only tier
_rewrite(pack / "world.json", mutate)
with pytest.raises(WorldLoadError, match=r"dungeon_tiers\[1\] = 6 has no non-boss monster"):
load_world(pack)
# ---------------------------------------------------------------------------
# v0.2 loader rejections: the event table and the Wyrm settings
# ---------------------------------------------------------------------------
def test_events_without_fight_rejected(tmp_path: Path) -> None:
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
# Strip every fight row; a walk could then never spawn a monster.
data["events"] = [e for e in data["events"] if e["kind"] != "fight"]
_rewrite(pack / "events.json", mutate)
with pytest.raises(WorldLoadError, match="at least one 'fight' entry"):
load_world(pack)
def test_event_zero_weight_rejected(tmp_path: Path) -> None:
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
data["events"][0]["weight"] = 0
_rewrite(pack / "events.json", mutate)
with pytest.raises(WorldLoadError, match="weight must be > 0"):
load_world(pack)
def test_event_min_exceeds_max_rejected(tmp_path: Path) -> None:
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
# Find a value-bearing row and invert its band.
for event in data["events"]:
if event["kind"] == "gold":
event["min"], event["max"] = 9, 2
break
_rewrite(pack / "events.json", mutate)
with pytest.raises(WorldLoadError, match="min 9 exceeds max 2"):
load_world(pack)
def test_event_amount_out_of_band_rejected(tmp_path: Path) -> None:
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
for event in data["events"]:
if event["kind"] == "heal":
event["max"] = 500 # heal band is 1..100
break
_rewrite(pack / "events.json", mutate)
with pytest.raises(WorldLoadError, match=r"heal amount .* is out of band"):
load_world(pack)
def test_event_nonfight_blank_text_rejected(tmp_path: Path) -> None:
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
for event in data["events"]:
if event["kind"] == "lore":
event["text"] = " "
break
_rewrite(pack / "events.json", mutate)
with pytest.raises(WorldLoadError, match="requires non-empty 'text'"):
load_world(pack)
def test_boss_monster_unknown_rejected(tmp_path: Path) -> None:
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
data["settings"]["boss_monster"] = "no_such_wyrm"
_rewrite(pack / "world.json", mutate)
with pytest.raises(WorldLoadError, match="is not a known monster id"):
load_world(pack)
def test_boss_monster_not_flagged_boss_rejected(tmp_path: Path) -> None:
pack = _clone_pack(tmp_path)
def mutate(data: list[dict[str, Any]]) -> None:
# Give a plain monster an id and point boss_monster at it; it lacks the
# boss flag, so it must be rejected as the endgame foe.
data[0]["id"] = "field_rat"
_rewrite(pack / "monsters.json", mutate)
def point(data: dict[str, Any]) -> None:
data["settings"]["boss_monster"] = "field_rat"
_rewrite(pack / "world.json", point)
with pytest.raises(WorldLoadError, match='must be flagged "boss": true'):
load_world(pack)
def test_wyrm_min_level_out_of_band_rejected(tmp_path: Path) -> None:
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
data["settings"]["wyrm_min_level"] = 0 # band is 1..50
_rewrite(pack / "world.json", mutate)
with pytest.raises(WorldLoadError, match="wyrm_min_level"):
load_world(pack)
# ---------------------------------------------------------------------------
# v0.5 social settings: ambush / post / gamble economy bands
# ---------------------------------------------------------------------------
def test_ambush_gold_pct_out_of_band_rejected(tmp_path: Path) -> None:
"""The steal percentage is a 0..100 band; 101 is rejected by name."""
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
data["settings"]["ambush_gold_pct"] = 101 # band is 0..100
_rewrite(pack / "world.json", mutate)
with pytest.raises(WorldLoadError, match="ambush_gold_pct"):
load_world(pack)
def test_ambush_level_band_out_of_band_rejected(tmp_path: Path) -> None:
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
data["settings"]["ambush_level_band"] = 11 # band is 0..10
_rewrite(pack / "world.json", mutate)
with pytest.raises(WorldLoadError, match="ambush_level_band"):
load_world(pack)
def test_gamble_max_bet_out_of_band_rejected(tmp_path: Path) -> None:
"""A max bet of 0 is below the 1..10000 floor: the house needs a real stake."""
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
data["settings"]["gamble_max_bet"] = 0 # band is 1..10000
_rewrite(pack / "world.json", mutate)
with pytest.raises(WorldLoadError, match="gamble_max_bet"):
load_world(pack)
def test_post_daily_cap_out_of_band_rejected(tmp_path: Path) -> None:
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
data["settings"]["post_daily_cap"] = 51 # band is 0..50
_rewrite(pack / "world.json", mutate)
with pytest.raises(WorldLoadError, match="post_daily_cap"):
load_world(pack)
def test_missing_social_setting_rejected(tmp_path: Path) -> None:
"""A pack that predates the social settings fails loudly (no silent default)."""
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
del data["settings"]["ambush_min_level"]
_rewrite(pack / "world.json", mutate)
with pytest.raises(WorldLoadError, match="ambush_min_level"):
load_world(pack)
# ---------------------------------------------------------------------------
# v0.4 loader hardening: glyphs, map size, count caps, and name lengths
#
# Packs are now routinely untrusted LLM output, so the loader bands the shapes
# that could tear a frame, balloon memory, or impersonate a player. Each
# rejection still names the file and field at fault.
# ---------------------------------------------------------------------------
def test_box_drawing_terrain_glyph_rejected(tmp_path: Path) -> None:
"""A terrain glyph may not be a frame box-drawing line (it would tear borders)."""
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
data["."]["glyph"] = "" # the horizontal frame run
_rewrite(pack / "terrain.json", mutate)
with pytest.raises(WorldLoadError, match=r"terrain\.json.* box-drawing"):
load_world(pack)
def test_player_marker_terrain_glyph_rejected(tmp_path: Path) -> None:
"""A terrain glyph may not be '@' — that is the player's own marker."""
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
data["."]["glyph"] = "@"
_rewrite(pack / "terrain.json", mutate)
with pytest.raises(WorldLoadError, match=r"terrain\.json.* reserved for player markers"):
load_world(pack)
def test_other_player_marker_terrain_glyph_rejected(tmp_path: Path) -> None:
"""A terrain glyph may not be '' — the v0.6 other-player marker."""
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
data["."]["glyph"] = ""
_rewrite(pack / "terrain.json", mutate)
with pytest.raises(WorldLoadError, match=r"terrain\.json.* reserved for player markers"):
load_world(pack)
def test_ampersand_terrain_glyph_now_accepted(tmp_path: Path) -> None:
"""'&' is no longer an actor marker (☻ took that role), so it is pack-legal.
The load itself is the assertion it must not raise the actor-marker
rejection. A grass cell then carries the new glyph.
"""
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
data["."]["glyph"] = "&"
_rewrite(pack / "terrain.json", mutate)
world = load_world(pack) # no WorldLoadError: '&' is admitted
grass = next(
world.terrain_at(x, y)
for y in range(world.height)
for x in range(world.width)
if world.terrain_at(x, y).key == "grass"
)
assert grass.glyph == "&"
def test_wide_cjk_terrain_glyph_rejected(tmp_path: Path) -> None:
"""A Wide (EAW=W) ideograph would render two columns and tear the frame."""
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
data["."]["glyph"] = ""
_rewrite(pack / "terrain.json", mutate)
with pytest.raises(WorldLoadError, match=r"terrain\.json.* exactly one column"):
load_world(pack)
def test_fullwidth_terrain_glyph_rejected(tmp_path: Path) -> None:
"""A Fullwidth (EAW=F) Latin letter is two columns and is rejected."""
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
data["."]["glyph"] = "" # U+FF21 FULLWIDTH LATIN CAPITAL LETTER A
_rewrite(pack / "terrain.json", mutate)
with pytest.raises(WorldLoadError, match=r"terrain\.json.* exactly one column"):
load_world(pack)
def test_reskinned_shipped_pack_glyphs() -> None:
"""The shipped pack carries the v0.6 re-skin and still loads cleanly.
The load-bearing guard for the re-skin: water is and the three lettered
buildings became //. If a data edit reverts a glyph, this trips.
"""
world = load_world(SHIPPED)
waters = {
world.terrain_at(x, y).glyph
for y in range(world.height)
for x in range(world.width)
if world.terrain_at(x, y).key == "water"
}
assert waters == {""}
by_key = {loc.key: loc.glyph for loc in world.locations}
assert by_key["inn"] == ""
assert by_key["healer"] == ""
assert by_key["dungeon"] == ""
assert by_key["shop"] == "$" # the shop glyph is unchanged
def test_multichar_location_glyph_rejected(tmp_path: Path) -> None:
"""A location glyph must be exactly one character."""
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
data["inn"]["glyph"] = "In" # two characters
_rewrite(pack / "locations.json", mutate)
with pytest.raises(WorldLoadError, match=r"locations\.json.* single character"):
load_world(pack)
def test_oversized_map_rejected(tmp_path: Path) -> None:
"""A 300x300 map is past the dimension ceiling (8..256)."""
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
data["width"] = 300
data["height"] = 300
_rewrite(pack / "world.json", mutate)
with pytest.raises(WorldLoadError, match=r"world\.json width = 300 is out of band"):
load_world(pack)
def test_too_many_events_rejected(tmp_path: Path) -> None:
"""An event table over the 500-row cap is rejected before it is decoded."""
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
filler = {"kind": "lore", "weight": 1, "text": "filler"}
data["events"] = [filler.copy() for _ in range(501)]
_rewrite(pack / "events.json", mutate)
with pytest.raises(WorldLoadError, match=r"events\.json defines 501 events; the limit is 500"):
load_world(pack)
def test_overlong_monster_name_rejected(tmp_path: Path) -> None:
"""A 49-character monster name is one past the 48-char display limit."""
pack = _clone_pack(tmp_path)
def mutate(data: list[dict[str, Any]]) -> None:
data[0]["name"] = "x" * 49
_rewrite(pack / "monsters.json", mutate)
with pytest.raises(WorldLoadError, match=r"monsters\.json\[0\] name is 49 characters"):
load_world(pack)
# ---------------------------------------------------------------------------
# v0.7 loader rejections: the satchel/forge bands, rare_drop_item, monster weight
# ---------------------------------------------------------------------------
def test_rare_drop_item_unknown_rejected(tmp_path: Path) -> None:
"""A rare_drop_item that names no item is rejected with the item-id message."""
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
data["settings"]["rare_drop_item"] = "no_such_draught"
_rewrite(pack / "world.json", mutate)
with pytest.raises(WorldLoadError, match="rare_drop_item = 'no_such_draught' is not a known"):
load_world(pack)
def test_rare_drop_item_non_consumable_rejected(tmp_path: Path) -> None:
"""A rare_drop_item that names a weapon (not a consumable) is rejected.
The drop goes straight into the satchel to be quaffed, so a weapon or
armour id is incoherent the loader pins the slot.
"""
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
data["settings"]["rare_drop_item"] = "iron_sword" # a weapon, not a draught
_rewrite(pack / "world.json", mutate)
with pytest.raises(WorldLoadError, match="rare_drop_item = 'iron_sword' must be a consumable"):
load_world(pack)
def test_satchel_max_out_of_band_rejected(tmp_path: Path) -> None:
"""satchel_max above its 1..10 band is a load error."""
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
data["settings"]["satchel_max"] = 11
_rewrite(pack / "world.json", mutate)
with pytest.raises(WorldLoadError, match=r"satchel_max = 11 is out of band \(1\.\.10\)"):
load_world(pack)
def test_forge_max_plus_out_of_band_rejected(tmp_path: Path) -> None:
"""forge_max_plus above its 0..10 band is a load error."""
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
data["settings"]["forge_max_plus"] = 11
_rewrite(pack / "world.json", mutate)
with pytest.raises(WorldLoadError, match=r"forge_max_plus = 11 is out of band \(0\.\.10\)"):
load_world(pack)
def test_forge_base_cost_out_of_band_rejected(tmp_path: Path) -> None:
"""forge_base_cost below its floor of 1 is a load error."""
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
data["settings"]["forge_base_cost"] = 0
_rewrite(pack / "world.json", mutate)
with pytest.raises(WorldLoadError, match=r"forge_base_cost = 0 is out of band \(1\.\.10000\)"):
load_world(pack)
def test_forge_ore_item_unknown_rejected(tmp_path: Path) -> None:
"""A forge_ore_item that names no item is rejected with the item-id message."""
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
data["settings"]["forge_ore_item"] = "no_such_ore"
_rewrite(pack / "world.json", mutate)
with pytest.raises(WorldLoadError, match="forge_ore_item = 'no_such_ore' is not a known"):
load_world(pack)
def test_forge_ore_item_non_material_rejected(tmp_path: Path) -> None:
"""A forge_ore_item that names a non-material (a potion) is rejected.
Ore is carried in the satchel and spent at the forge, never equipped or
quaffed, so a consumable/weapon/armour id is incoherent the loader pins
the slot to ``material`` (mirroring the rare_drop_item consumable check).
"""
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
data["settings"]["forge_ore_item"] = "greater_potion" # a draught, not ore
_rewrite(pack / "world.json", mutate)
with pytest.raises(
WorldLoadError, match="forge_ore_item = 'greater_potion' must be a material"
):
load_world(pack)
def test_forge_ore_per_plus_out_of_band_rejected(tmp_path: Path) -> None:
"""forge_ore_per_plus above its 0..10 band is a load error."""
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
data["settings"]["forge_ore_per_plus"] = 11
_rewrite(pack / "world.json", mutate)
with pytest.raises(WorldLoadError, match=r"forge_ore_per_plus = 11 is out of band \(0\.\.10\)"):
load_world(pack)
def test_ore_dungeon_drop_out_of_band_rejected(tmp_path: Path) -> None:
"""ore_dungeon_drop above its 0..20 band is a load error."""
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
data["settings"]["ore_dungeon_drop"] = 21
_rewrite(pack / "world.json", mutate)
with pytest.raises(WorldLoadError, match=r"ore_dungeon_drop = 21 is out of band \(0\.\.20\)"):
load_world(pack)
def test_ore_forest_chance_out_of_band_rejected(tmp_path: Path) -> None:
"""ore_forest_chance outside 0.0..1.0 is a load error (it is a probability)."""
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
data["settings"]["ore_forest_chance"] = 1.5
_rewrite(pack / "world.json", mutate)
with pytest.raises(
WorldLoadError, match=r"ore_forest_chance = 1.5 is out of band \(0.0..1.0\)"
):
load_world(pack)
def test_monster_zero_weight_rejected(tmp_path: Path) -> None:
"""A monster weight of 0 is rejected (the weighted pick needs a positive total)."""
pack = _clone_pack(tmp_path)
def mutate(data: list[dict[str, Any]]) -> None:
data[0]["weight"] = 0
_rewrite(pack / "monsters.json", mutate)
with pytest.raises(WorldLoadError, match=r"monsters\.json\[0\] weight must be > 0"):
load_world(pack)
def test_shipped_pack_carries_rares_and_weights() -> None:
"""The shipped pack parses the v0.7 rare beasts with their low weights."""
world = load_world(SHIPPED)
rares = [m for m in world.monsters if m.rare]
names = {m.name for m in rares}
assert names == {"the Gilded Stag", "the Hollow Knight"}
assert all(m.weight == 1 for m in rares) # rares surface seldom
# The rare_drop_item resolves to a consumable.
drop = world.item_by_id(world.settings.rare_drop_item)
assert drop is not None and drop.slot.value == "consumable"
# The new economy settings land on their shipped values.
assert world.settings.satchel_max == 3
assert world.settings.forge_base_cost == 60
assert world.settings.forge_max_plus == 3
assert world.settings.dungeon_tiers == (3, 4, 5)
# v0.10 ore-forge settings resolve, and the forge ore is a material item.
assert world.settings.forge_ore_item == "iron_ore"
ore = world.item_by_id(world.settings.forge_ore_item)
assert ore is not None and ore.slot.value == "material"
assert world.settings.forge_ore_per_plus == 1
assert world.settings.ore_dungeon_drop == 2
assert world.settings.ore_forest_chance == 0.2
def test_monster_weight_and_rare_default_when_omitted(tmp_path: Path) -> None:
"""A monster spec without weight/rare loads as weight 10, rare False.
Both fields are optional with defaults, so an unannotated common monster
(the shipped Field Rat) parses to the default weight and the non-rare flag.
"""
world = load_world(SHIPPED)
rat = next(m for m in world.monsters if m.name == "Field Rat")
assert rat.weight == 10 # the default biasing weight
assert rat.rare is False
# ---------------------------------------------------------------------------
# v0.8 loader hardening: rare-as-rung-guardian and the single-boss invariant
#
# AUTHORING states both as rules; v0.8 makes them machine-checked. A rare in
# the lead slot of a dungeon tier would be silently promoted to a fixed rung
# guardian (and pulled from the rare pool); a stray second boss would validate
# clean yet make "the one endgame foe" a lie.
# ---------------------------------------------------------------------------
def test_rare_as_first_dungeon_tier_monster_rejected(tmp_path: Path) -> None:
"""A rare in the FIRST slot of a dungeon tier becomes a fixed guardian — rejected.
Tier 3 backs a ``dungeon_tiers`` rung and its first monster (the Forest
Wolf) is the rung guardian (``band[0]``). Flagging that lead monster rare
would quietly turn the rare into the fixed, repeatable guardian and remove
it from the weighted rare roll, so the loader rejects it by name.
"""
pack = _clone_pack(tmp_path)
def mutate(data: list[dict[str, Any]]) -> None:
wolf = next(m for m in data if m["name"] == "Forest Wolf") # first tier-3
wolf["rare"] = True
_rewrite(pack / "monsters.json", mutate)
with pytest.raises(
WorldLoadError,
match=r"'Forest Wolf' is rare but is the first tier-3 monster.*fixed guardian",
):
load_world(pack)
def test_rare_after_guardian_in_dungeon_tier_accepted(tmp_path: Path) -> None:
"""A rare placed AFTER the guardian in the same dungeon tier loads cleanly.
The shipped pack already does exactly this (the Hollow Knight is the third
tier-3 entry, behind the Forest Wolf guardian). Inserting another rare also
after the guardian must not trip the new check only the LEAD slot of a
dungeon tier is constrained.
"""
pack = _clone_pack(tmp_path)
def mutate(data: list[dict[str, Any]]) -> None:
# Splice a second tier-3 rare in just before the boss (well after the
# tier-3 guardian), so the tier's first non-boss monster is unchanged.
extra = {
"tier": 3,
"name": "the Ashen Stalker",
"hp": 26,
"atk": 10,
"def": 3,
"xp": 55,
"gold": 75,
"weight": 1,
"rare": True,
}
data.insert(len(data) - 1, extra)
_rewrite(pack / "monsters.json", mutate)
world = load_world(pack) # no WorldLoadError: the rare is not the lead foe
tier3 = world.monsters_for_tier_band(3, 3)
assert tier3[0].name == "Forest Wolf" # the guardian is still the non-rare lead
assert any(m.name == "the Ashen Stalker" and m.rare for m in tier3)
def test_two_bosses_rejected(tmp_path: Path) -> None:
"""Two ``boss``-flagged monsters are rejected: a world has exactly one boss."""
pack = _clone_pack(tmp_path)
def mutate(data: list[dict[str, Any]]) -> None:
# Give the Field Rat the boss flag too; now two monsters claim the role.
rat = next(m for m in data if m["name"] == "Field Rat")
rat["boss"] = True
rat["id"] = "field_rat"
_rewrite(pack / "monsters.json", mutate)
with pytest.raises(WorldLoadError, match=r"flags 2 monsters as .boss.* true"):
load_world(pack)
def test_single_boss_accepted() -> None:
"""The shipped pack carries exactly one boss and loads — the single-boss path.
The positive half of the invariant: the Wyrm Below is the only boss, so the
load succeeds and the boss count is exactly one.
"""
world = load_world(SHIPPED)
bosses = [m for m in world.monsters if m.boss]
assert len(bosses) == 1
assert bosses[0].name == "the Wyrm Below"
def test_overlapping_zones_rejected(tmp_path: Path) -> None:
"""Overlapping zone rectangles are a load error.
``zone_for`` returns the FIRST matching zone, so two zones sharing any cell
would silently shadow one tier band there exactly the bug a cold-authored
pack shipped (a 1-column caldera-edge strip dropped to the low band). Pull
the deep zone west so its rect overlaps the near zone and confirm the loader
refuses it rather than loading the ambiguity.
"""
pack = _clone_pack(tmp_path)
def mutate(data: dict[str, Any]) -> None:
for zone in data["zones"]:
if zone["key"] == "dungeon_deep":
zone["rect"][0] = 50 # now overlaps forest_near's x30..60 strip
_rewrite(pack / "world.json", mutate)
with pytest.raises(WorldLoadError, match="overlap"):
load_world(pack)
+206
View File
@@ -0,0 +1,206 @@
"""Tests for bundled-world discovery and the ``worlds`` listing.
Covers the discovery helper (the Vale leads, alternate packs follow
alphabetically, non-pack directories are skipped) and the ``cli_worlds``
listing it backs: a sound fixture pack reports "sound", a deliberately-flawed
fixture pack reports "flawed", and the Vale is always listed first. The
``packs/`` directory is monkeypatched to a temp fixture tree so these tests
never depend on the real (separately-authored) second world.
"""
from __future__ import annotations
import json
import shutil
from io import StringIO
from pathlib import Path
from typing import TYPE_CHECKING, Any
from understone import cli
from understone import world as world_pkg
from understone.world import VALE_SLUG, bundled_world_dirs
if TYPE_CHECKING:
import pytest
SHIPPED = Path(__file__).resolve().parents[1] / "understone" / "world" / "data"
def _make_packs(tmp_path: Path, *, sound: list[str], flawed: dict[str, Any]) -> Path:
"""Build a temp ``packs/`` tree: sound slugs plus flawed-world slugs.
Each sound slug is a verbatim copy of the shipped Vale; each flawed slug is
a copy whose ``world.json`` is patched with the given settings overrides so
it fails to load. Returns the packs root to monkeypatch ``PACKS_DIR`` onto.
"""
packs = tmp_path / "packs"
packs.mkdir()
for slug in sound:
shutil.copytree(SHIPPED, packs / slug)
for slug, overrides in flawed.items():
dest = packs / slug
shutil.copytree(SHIPPED, dest)
world_json = dest / "world.json"
data = json.loads(world_json.read_text(encoding="utf-8"))
data["settings"].update(overrides)
world_json.write_text(json.dumps(data), encoding="utf-8")
return packs
# ---------------------------------------------------------------------------
# bundled_world_dirs discovery
# ---------------------------------------------------------------------------
def test_bundled_world_dirs_vale_leads_then_alpha(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
packs = _make_packs(tmp_path, sound=["zephyr", "ashfall"], flawed={})
monkeypatch.setattr(world_pkg, "PACKS_DIR", packs)
found = bundled_world_dirs()
slugs = [slug for slug, _ in found]
# The Vale is always first; alternates follow alphabetically.
assert slugs == [VALE_SLUG, "ashfall", "zephyr"]
# The Vale entry points at the packaged data dir, not a packs subdir.
assert found[0][1] == world_pkg.PACKAGED_WORLD_DIR
def test_bundled_world_dirs_skips_non_pack_entries(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
packs = _make_packs(tmp_path, sound=["real"], flawed={})
# A README placeholder and a directory with no world.json are NOT worlds.
(packs / "README.md").write_text("placeholder", encoding="utf-8")
(packs / "empty_dir").mkdir()
monkeypatch.setattr(world_pkg, "PACKS_DIR", packs)
slugs = [slug for slug, _ in bundled_world_dirs()]
assert slugs == [VALE_SLUG, "real"]
def test_bundled_world_dirs_handles_absent_packs_dir(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""A missing packs/ directory yields just the Vale (never raises)."""
monkeypatch.setattr(world_pkg, "PACKS_DIR", tmp_path / "does_not_exist")
found = bundled_world_dirs()
assert [slug for slug, _ in found] == [VALE_SLUG]
# ---------------------------------------------------------------------------
# cli_worlds listing
# ---------------------------------------------------------------------------
def test_cli_worlds_lists_vale_sound_first(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(world_pkg, "PACKS_DIR", tmp_path / "empty")
out, err = StringIO(), StringIO()
rc = cli.cli_worlds(out=out, err=err)
assert rc == 0
text = out.getvalue()
lines = [ln for ln in text.splitlines() if ln.strip()]
# The very first listing line is the Vale, reported sound, with its size.
assert lines[0].split()[0] == VALE_SLUG
assert "The Vale of Understone" in lines[0]
assert "96x48" in lines[0]
assert "sound" in lines[0]
# The serve hint closes the listing.
assert "UNDERSTONE_WORLD=" in text
assert "the default Vale needs no setting" in text
def test_cli_worlds_reports_sound_alternate(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
packs = _make_packs(tmp_path, sound=["mirefen"], flawed={})
monkeypatch.setattr(world_pkg, "PACKS_DIR", packs)
out = StringIO()
cli.cli_worlds(out=out)
text = out.getvalue()
line = next(ln for ln in text.splitlines() if ln.strip().startswith("mirefen"))
assert "sound" in line
assert "flawed" not in line
def test_cli_worlds_flags_flawed_alternate(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
# daily_turns 0 is out of its 1..100 band: the pack fails to load.
packs = _make_packs(tmp_path, sound=["sound_one"], flawed={"broken": {"daily_turns": 0}})
monkeypatch.setattr(world_pkg, "PACKS_DIR", packs)
out = StringIO()
rc = cli.cli_worlds(out=out)
assert rc == 0 # a flawed pack is reported, never fatal
text = out.getvalue()
broken_line = next(ln for ln in text.splitlines() if ln.strip().startswith("broken"))
assert "flawed:" in broken_line
assert "daily_turns" in broken_line # the offending field surfaces
# The sound pack alongside it still reports sound — one bad pack doesn't
# poison the survey.
sound_line = next(ln for ln in text.splitlines() if ln.strip().startswith("sound_one"))
assert "sound" in sound_line
def test_cli_worlds_vale_sorts_before_flawed_alternate(
tmp_path: Path, monkeypatch: pytest.MonkeyPatch
) -> None:
"""Even with an alphabetically-earlier flawed pack, the Vale leads."""
packs = _make_packs(tmp_path, sound=[], flawed={"aaa_broken": {"start_hp": 0}})
monkeypatch.setattr(world_pkg, "PACKS_DIR", packs)
out = StringIO()
cli.cli_worlds(out=out)
lines = [ln for ln in out.getvalue().splitlines() if ln.strip()]
assert lines[0].split()[0] == VALE_SLUG
assert lines[1].strip().startswith("aaa_broken")
assert "flawed:" in lines[1]
# ---------------------------------------------------------------------------
# the REAL bundled alternate world (no monkeypatch): The Cinder Wastes
#
# The tests above stub PACKS_DIR to a fixture tree so they never depend on the
# separately-authored pack. These two exercise the actual shipped packs/ — the
# bundled Cinder Wastes must discover, load, validate, and appear in the listing
# as sound, so a broken or unbundled alternate trips here.
# ---------------------------------------------------------------------------
CINDER = Path(__file__).resolve().parents[1] / "understone" / "world" / "packs" / "cinder-wastes"
def test_bundled_cinder_wastes_loads_and_validates() -> None:
"""The bundled Cinder Wastes loads through the (strict v0.8) loader cleanly.
It is LLM-authored from AUTHORING.md alone, so this is the dogfood proof
that the manual + validator produce a pack the real loader accepts and,
after v0.8, one that passes the stricter rare-as-guardian and single-boss
checks (its rares sit after their guardians; it has exactly one boss).
"""
from understone.world.loader import load_world
world = load_world(CINDER)
assert world.name == "The Cinder Wastes"
assert world.settings.watch_theme == "ember" # the thematic ember CRT palette
bosses = [m for m in world.monsters if m.boss]
assert len(bosses) == 1 and bosses[0].name == "the Magma Wyrm"
# The boss id resolves and is the declared endgame foe.
assert world.settings.boss_monster == "magma_wyrm"
def test_cli_worlds_lists_bundled_cinder_wastes_sound() -> None:
"""`understone worlds` discovers the real bundled Cinder Wastes as sound.
No monkeypatch: this runs against the actual packs/ directory, so it asserts
the genuinely-shipped second world appears in the listing (alongside the
fixture-based listing tests above, which stay).
"""
out = StringIO()
rc = cli.cli_worlds(out=out)
assert rc == 0
line = next(ln for ln in out.getvalue().splitlines() if ln.strip().startswith("cinder-wastes"))
assert "The Cinder Wastes" in line
assert "sound" in line
assert "flawed" not in line
+600
View File
@@ -0,0 +1,600 @@
"""The Wyrm Below — the v0.2 endgame, legacy reset, and the Herald feed.
Drives the challenge verb against the shipped pack: the level gate, the win
path (Hall of Legends + reincarnation), defeat, and the stalemate flight, plus
the run-days bookkeeping. Also pins the boss exclusion from random selection
and proves the new level_up / defeat beats reach OTHER players' Herald.
Negative-test discipline (the level gate):
The challenge gate is pinned by ``test_challenge_under_level_refused``. To
confirm the assertion has teeth, the implementer temporarily removed the
``if player.level < min_level`` refusal in Game._challenge (letting an
under-level hero spend a turn and fight the Wyrm); the test then FAILED on
the unchanged-turns assertion (a turn was consumed and the refusal line was
absent). The guard was restored. This test is the standing regression.
"""
from __future__ import annotations
from pathlib import Path
import pytest
from tests.conftest import (
fixed_clock,
satchel_ids,
set_satchel,
utc,
)
from understone.engine.models import Mode
from understone.engine.rng import GameRNG
from understone.game import Game
from understone.persistence import Store
from understone.world.loader import load_world
PACK = Path(__file__).resolve().parents[1] / "understone" / "world" / "data"
# Module-local aliases for the shared satchel helpers, keeping the existing
# call sites (_set_satchel / _satchel_ids) unchanged.
_set_satchel = set_satchel
_satchel_ids = satchel_ids
@pytest.fixture
def clock() -> object:
return fixed_clock(utc(2026, 6, 12, 10, 0))
def _game(tmp_path: Path, clock: object, seed: int = 7) -> Game:
world = load_world(PACK)
store = Store(tmp_path / "game.db")
return Game(world, store, clock=clock, rng=GameRNG(seed=seed)) # type: ignore[arg-type]
# The flat-id-list satchel helpers (_set_satchel / _satchel_ids) live in
# tests/conftest.py now, shared with the descend suite; they are imported above.
def _at_dungeon(game: Game, name: str) -> object:
"""Place an already-joined player inside the dungeon menu, at the deep floor.
The challenge verb now gates on depth as well as level: the Wyrm will not
stir until the hero has plumbed the deep to its floor. These challenge
tests exercise the win/lose/flee paths, not the gate, so the helper puts
the hero at the bottom (deepest_rung == the rung count). The depth gate
itself is exercised by the dedicated tests in test_descend.py.
"""
player = game.players[name]
player.mode = Mode.MENU
player.at_location = "dungeon"
player.deepest_rung = len(game.world.settings.dungeon_tiers)
return player
# ---------------------------------------------------------------------------
# Boss exclusion from random selection
# ---------------------------------------------------------------------------
def test_boss_never_in_any_tier_band(tmp_path: Path, clock: object) -> None:
"""The Wyrm Below is never returned by monsters_for_tier_band, any band."""
game = _game(tmp_path, clock)
world = game.world
tiers = [m.tier for m in world.monsters]
lo, hi = min(tiers), max(tiers)
for band_lo in range(lo, hi + 2):
for band_hi in range(band_lo, hi + 2):
band = world.monsters_for_tier_band(band_lo, band_hi)
assert all(not m.boss for m in band)
assert all(m.monster_id != "wyrm_below" for m in band)
# ---------------------------------------------------------------------------
# The level gate (negative-tested; see module docstring)
# ---------------------------------------------------------------------------
def test_challenge_under_level_refused(tmp_path: Path, clock: object) -> None:
"""An under-level hero is turned away in-fiction, spending no turn.
See the module docstring for the revert-and-observe-failure check proving
the gate has teeth.
"""
game = _game(tmp_path, clock)
game.join("Brak")
player = _at_dungeon(game, "Brak")
assert player.level < game.world.settings.wyrm_min_level
before_turns = player.turns_left
before_events = len(game.events)
out = game.action("Brak", "challenge", "", "")
assert "sixth circle" in out.lower() # names the threshold in-fiction
assert player.turns_left == before_turns # no turn spent
assert player.level == 1 # nothing reset
assert len(game.events) == before_events # no public news
assert player.mode is Mode.MENU # still standing at the dungeon
def test_challenge_at_level_threshold_is_allowed(tmp_path: Path, clock: object) -> None:
"""Exactly at the threshold the challenge proceeds (spends a turn)."""
game = _game(tmp_path, clock)
game.join("Brak")
player = _at_dungeon(game, "Brak")
player.level = game.world.settings.wyrm_min_level
player.atk, player.def_, player.hp, player.max_hp = 500, 100, 500, 500
before_turns = player.turns_left
out = game.action("Brak", "challenge", "", "")
assert "sixth circle" not in out.lower() # not refused
assert player.turns_left == before_turns - 1 # a turn was spent
def test_challenge_at_zero_turns_refused_clean(tmp_path: Path) -> None:
"""At the level gate but out of turns, the challenge is refused with no effect.
A wyrm-eligible hero with an empty daily budget (and no day-roll to refill
it) is turned away in-fiction: no turn drops below zero, no Hall row is
cut, no public beat is written, wins are untouched and the no-op player
row is still committed (the refusal branch upserts + commits), so a store
reopen sees the unchanged hero.
"""
clk = _MutableClock(utc(2026, 6, 12, 10, 0))
world = load_world(PACK)
store = Store(tmp_path / "game.db")
game = Game(world, store, clock=clk, rng=GameRNG(seed=7)) # type: ignore[arg-type]
game.join("Brak")
player = _at_dungeon(game, "Brak")
player.level = game.world.settings.wyrm_min_level # eligible
player.turns_left = 0 # but spent for the day (same day: no refill)
events_before = len(game.events)
hall_before = len(game.store.top_hall(50))
out = game.action("Brak", "challenge", "", "")
assert "tomorrow" in out.lower() # the "too spent ... today" refusal
assert "sixth circle" not in out.lower() # not the level gate
assert player.turns_left == 0 # never spent below zero
assert player.wins == 0 # no win recorded
assert len(game.events) == events_before # no public feed beat
assert len(game.store.top_hall(50)) == hall_before # no Hall row
assert player.mode is Mode.MENU # still standing at the dungeon
# The refusal branch commits the (unchanged) row: a reopen sees the hero.
game.store.close()
reopened = Game(world, Store(tmp_path / "game.db"), clock=clk) # type: ignore[arg-type]
assert reopened.players["Brak"].turns_left == 0
assert reopened.players["Brak"].wins == 0
# ---------------------------------------------------------------------------
# Win path: Hall of Legends + legacy reset
# ---------------------------------------------------------------------------
def test_challenge_win_resets_with_legacy(tmp_path: Path, clock: object) -> None:
"""A win records the run, heralds it, and reincarnates the hero with a ★."""
game = _game(tmp_path, clock)
game.join("Brak")
player = _at_dungeon(game, "Brak")
# Mid-run state that must be wiped by the reset.
player.level, player.xp = 12, 5000
player.atk, player.def_, player.hp, player.max_hp = 500, 100, 500, 500
player.gold = 999
player.weapon_id, player.armor_id = "war_axe", "chainmail"
# State that must SURVIVE the reset.
player.turns_left = 4
player.log_cursor = 1
player.bestow_spent = 7
events_before = len(game.events)
settings = game.world.settings
out = game.action("Brak", "challenge", "", "")
# Win narration and the immortalised run.
assert "freed the vale" in out.lower()
assert "hall of legends" in out.lower()
# The legacy reset wipes xp/gold, so the Wyrm win must NOT narrate a reward
# the hero never keeps (the old engine appended "+400 XP, +250 gold." to the
# kill line, which _wyrm_won echoed verbatim). The boss's reward never lands.
boss = game.world.monster_by_id(game.world.settings.boss_monster)
assert boss is not None
assert f"+{boss.xp} XP" not in out # i.e. "+400 XP"
assert f"+{boss.gold} gold" not in out # i.e. "+250 gold"
assert "+400 XP" not in out and "+250 gold" not in out
hall = game.store.top_hall(5)
assert len(hall) == 1
assert hall[0].name == "Brak"
assert hall[0].level_at_win == 12 # the level at the moment of the kill
assert hall[0].run_days == 0 # same UTC day as the join under the frozen clock
# A public news beat was written (all-caps herald moment).
assert len(game.events) == events_before + 1
assert game.events[-1].kind == "wyrm_win"
assert "WYRM" in game.events[-1].text
# Reincarnation: stats/gold/gear/position back to first-day values.
assert player.wins == 1
assert player.level == 1
assert player.xp == 0
assert player.gold == settings.starting_gold
assert player.weapon_id == settings.starting_weapon
assert player.armor_id == settings.starting_armor
assert player.hp == player.max_hp
assert (player.x, player.y) == game.world.spawn
assert player.mode is Mode.TILE
assert player.at_location == ""
# The daily clock and the log cursor were deliberately left alone.
assert player.turns_left == 4 - 1 # only the one challenge turn was spent
assert player.log_cursor == 1
assert player.bestow_spent == 7
def test_challenge_win_legacy_reset_spares_the_vault(tmp_path: Path, clock: object) -> None:
"""The vault SURVIVES a Wyrm-win rebirth; carried gold resets to starting.
Banked gold is the one wealth (besides the ) a legacy reset does not clear:
the strongbox is the inn's, not the reborn hero's. This deposits gold into
the vault through the inn, drives a Wyrm WIN, and asserts ``banked`` is
UNCHANGED while ``gold`` drops back to ``starting_gold``.
Negative-check (the revert-and-observe-failure discipline of this module):
the implementer temporarily added ``player.banked = 0`` to
Game._reset_with_legacy; this test then FAILED on the unchanged-``banked``
assertion (the vault was wiped by the rebirth). The line was restored, so
this test is the standing regression that the vault outlives the reset.
"""
game = _game(tmp_path, clock)
game.join("Brak")
player = game.players["Brak"]
# Bank some gold through the real inn path, then stand at the dungeon floor.
player.gold = 200
player.mode = Mode.MENU
player.at_location = "inn"
game.action("Brak", "deposit", "", "", amount=120)
assert player.banked == 120 and player.gold == 80 # vault holds; hand drained
player = _at_dungeon(game, "Brak")
player.level = game.world.settings.wyrm_min_level
player.atk, player.def_, player.hp, player.max_hp = 500, 100, 500, 500
out = game.action("Brak", "challenge", "", "")
assert "freed the vale" in out.lower() # a genuine win drove the reset
assert player.wins == 1
assert player.banked == 120 # the vault is untouched by the rebirth
assert player.gold == game.world.settings.starting_gold # carried wealth resets
def test_challenge_win_star_in_rank_and_hall(tmp_path: Path, clock: object) -> None:
"""After a win, door_rank shows the ★ and renders the Hall of Legends."""
game = _game(tmp_path, clock)
game.join("Brak")
player = _at_dungeon(game, "Brak")
player.level = game.world.settings.wyrm_min_level
player.atk, player.def_, player.hp, player.max_hp = 500, 100, 500, 500
game.action("Brak", "challenge", "", "")
out = game.rank("Brak")
assert "" in out
assert "Hall of Legends" in out
assert "Brak" in out
def test_two_wins_render_two_stars(tmp_path: Path, clock: object) -> None:
"""A second Wyrm kill stacks a second ★ on the leaderboard name."""
game = _game(tmp_path, clock)
game.join("Brak")
for _ in range(2):
player = _at_dungeon(game, "Brak")
player.level = game.world.settings.wyrm_min_level
player.atk, player.def_, player.hp, player.max_hp = 500, 100, 500, 500
game.action("Brak", "challenge", "", "")
assert game.players["Brak"].wins == 2
assert "★★" in game.rank("Brak")
# ---------------------------------------------------------------------------
# Lose path and flight
# ---------------------------------------------------------------------------
def test_challenge_loss_bounces_and_heralds(tmp_path: Path, clock: object) -> None:
"""A defeat drops the hero to 1 HP at the spawn and heralds the devouring."""
game = _game(tmp_path, clock)
game.join("Brak")
player = _at_dungeon(game, "Brak")
player.level = game.world.settings.wyrm_min_level
player.atk, player.def_, player.hp, player.max_hp = 5, 1, 20, 20 # outmatched
events_before = len(game.events)
out = game.action("Brak", "challenge", "", "")
assert player.hp == 1
assert (player.x, player.y) == game.world.spawn
assert player.mode is Mode.TILE
assert player.at_location == ""
assert player.wins == 0 # a loss is not a win
assert len(game.events) == events_before + 1
devoured = game.events[-1]
assert devoured.kind == "wyrm_lose"
# Either phrasing of the devouring names the hero and the Wyrm.
assert "Brak" in devoured.text and "Wyrm" in devoured.text
assert "lays you low" in out.lower() or "wyrm" in out.lower()
def _doomed_wyrm_challenger(game: Game, name: str) -> object:
"""Stand *name* at the floor, wyrm-eligible, and doomed to a GRINDING loss.
The stats modest atk and def, hp 50 below max_hp 80, well off the spawn
make the Wyrm bout a genuine multi-round lethal loss (not a one-shot where
no blow lands before the save). hp 50 is none of the potion heal values
(15/40/70), so a death-save that sets hp to the potion's heal is unmistakable.
"""
player = _at_dungeon(game, name)
player.level = game.world.settings.wyrm_min_level
player.x, player.y = 35, 25 # away from the spawn (a save never moves them)
player.atk, player.def_, player.hp, player.max_hp = 6, 12, 50, 80
return player
def test_challenge_loss_with_potion_survives_no_legacy_reset(tmp_path: Path, clock: object) -> None:
"""A lethal Wyrm bout with a potion is SURVIVED — no bounce, no legacy reset.
The universal death-save reaches the Wyrm: a carried draught is drunk instead
of the devouring. A save is NOT a win, so NOTHING resets level, gold, and
``deepest_rung`` all stand and it is NOT the devouring either, so the hero
keeps their place at the dungeon. The PUBLIC beat is the survival one
(``wyrm_flee``, "driven back, alive but unproven"), NEVER "devoured". The
turn is still spent and the draught is consumed.
"""
game = _game(tmp_path, clock)
game.join("Brak")
player = _doomed_wyrm_challenger(game, "Brak")
potion = game.world.item_by_id("greater_potion")
assert potion is not None
_set_satchel(game, player, ["greater_potion"])
floor = len(game.world.settings.dungeon_tiers)
spawn = game.world.spawn
before_turns = player.turns_left
before_level, before_gold = player.level, player.gold
events_before = len(game.events)
out = game.action("Brak", "challenge", "", "")
# Survived standing: hp at the potion's value, no bounce, draught spent.
assert player.hp == min(player.max_hp, potion.heal)
assert (player.x, player.y) != spawn # NOT bounced to the spawn
assert player.mode is Mode.MENU # still standing at the dungeon
assert _satchel_ids(game, player) == [] # the draught was spent
assert "death's edge" in out.lower() # the spliced survival line
assert player.turns_left == before_turns - 1 # the challenge still cost a turn
# No win, so NO legacy reset: level, gold, and depth all stand.
assert player.wins == 0
assert player.level == before_level
assert player.gold == before_gold
assert player.deepest_rung == floor # depth untouched (no reset to 0)
# The PUBLIC beat is the survival one, NOT the devouring.
assert len(game.events) == events_before + 1
beat = game.events[-1]
assert beat.kind == "wyrm_flee"
assert beat.kind != "wyrm_lose"
assert "fled" in beat.text.lower() or "ran" in beat.text.lower()
def test_challenge_loss_potion_negative_without_save_devours(
tmp_path: Path, clock: object, monkeypatch: pytest.MonkeyPatch
) -> None:
"""NEGATIVE TEST: with the death-save disabled, the same potion-carrier is devoured.
The mechanical equivalent of reverting the added ``_death_save`` call in
``_wyrm_lost``: we stub ``_death_save`` to always decline, then run the exact
scenario of the survival test. The potion-carrier must now bounce to the
spawn at 1 HP with the draught UNSPENT and the PUBLIC beat back to
``wyrm_lose`` (devoured) proving the death-save (not some other path) is
what saves them at the Wyrm. Restoring the real method (automatic when the
patch lifts) restores the survival behaviour.
"""
game = _game(tmp_path, clock)
game.join("Brak")
player = _doomed_wyrm_challenger(game, "Brak")
_set_satchel(game, player, ["greater_potion"])
floor = len(game.world.settings.dungeon_tiers)
spawn = game.world.spawn
monkeypatch.setattr(Game, "_death_save", lambda self, pl, lines: False)
out = game.action("Brak", "challenge", "", "")
assert player.hp == 1 # devoured, not saved
assert (player.x, player.y) == spawn
assert player.mode is Mode.TILE
assert player.deepest_rung == floor # a defeat keeps depth (no reset, no advance)
assert _satchel_ids(game, player) == ["greater_potion"] # the draught is UNSPENT
assert "death's edge" not in out.lower() # no save, no dramatic line
assert game.events[-1].kind == "wyrm_lose" # the devouring beat, not the survival one
def test_challenge_stalemate_counts_as_flight(tmp_path: Path, clock: object) -> None:
"""A 50-round stalemate resolves as a flight: a wyrm_flee news beat.
With atk == boss def (no kill possible in the round cap) and enough HP to
outlast the boss's chip damage, resolve_fight returns FLED deterministically.
"""
game = _game(tmp_path, clock)
game.join("Brak")
player = _at_dungeon(game, "Brak")
player.level = game.world.settings.wyrm_min_level
player.atk, player.def_, player.hp, player.max_hp = 8, 24, 200, 200
events_before = len(game.events)
game.action("Brak", "challenge", "", "")
assert player.wins == 0
assert player.hp >= 1 # never killed by a flight
assert len(game.events) == events_before + 1
assert game.events[-1].kind == "wyrm_flee"
assert "fled" in game.events[-1].text.lower() or "ran" in game.events[-1].text.lower()
# ---------------------------------------------------------------------------
# run_days from a frozen, advanced clock
# ---------------------------------------------------------------------------
class _MutableClock:
"""A clock whose reported moment can be advanced between calls."""
def __init__(self, moment: object) -> None:
self.moment = moment
def __call__(self) -> object:
return self.moment
def test_run_days_counts_whole_days(tmp_path: Path) -> None:
"""Joining, advancing the clock three days, then winning records run_days==3."""
clk = _MutableClock(utc(2026, 6, 12, 10, 0))
world = load_world(PACK)
store = Store(tmp_path / "game.db")
game = Game(world, store, clock=clk, rng=GameRNG(seed=7)) # type: ignore[arg-type]
game.join("Brak")
player = _at_dungeon(game, "Brak")
player.level = game.world.settings.wyrm_min_level
player.atk, player.def_, player.hp, player.max_hp = 500, 100, 500, 500
clk.moment = utc(2026, 6, 15, 12, 0) # three days (and a couple hours) later
game.action("Brak", "challenge", "", "")
hall = game.store.top_hall(1)
assert hall[0].run_days == 3
def test_top_hall_orders_most_recent_first(tmp_path: Path) -> None:
"""Two heroes slay the Wyrm at advancing times; the latest tops the Hall.
Pins ``ORDER BY id DESC`` in ``Store.top_hall`` the most recently cut
run is at index 0, regardless of name or level-at-win order.
"""
clk = _MutableClock(utc(2026, 6, 12, 10, 0))
world = load_world(PACK)
store = Store(tmp_path / "game.db")
game = Game(world, store, clock=clk, rng=GameRNG(seed=7)) # type: ignore[arg-type]
def _win(name: str) -> None:
game.join(name)
hero = _at_dungeon(game, name)
hero.level = game.world.settings.wyrm_min_level
hero.atk, hero.def_, hero.hp, hero.max_hp = 500, 100, 500, 500
game.action(name, "challenge", "", "")
_win("Early")
clk.moment = utc(2026, 6, 13, 10, 0) # a day later
_win("Later")
hall = game.store.top_hall(5)
assert len(hall) == 2
assert hall[0].name == "Later" # most recent run is first
assert hall[1].name == "Early"
# ---------------------------------------------------------------------------
# Shared-feed proof: level_up and defeat reach ANOTHER player's Herald
# ---------------------------------------------------------------------------
def test_multi_level_jump_is_one_feed_beat_naming_final_level(
tmp_path: Path, clock: object
) -> None:
"""A single award crossing two thresholds posts ONE level_up beat, at the top.
With xp parked just under the level-3 line while still level 1, one forest
kill vaults the hero past both the level-2 and level-3 thresholds. The
public feed must carry exactly one level_up beat a multi-level jump is one
notable moment, not a flood and that beat must name the FINAL level (3),
not the intermediate one.
"""
game = _game(tmp_path, clock)
game.join("Climber")
climber = game.players["Climber"]
climber.x, climber.y = 35, 25 # forest_near zone
climber.atk, climber.def_, climber.hp, climber.max_hp = 100, 50, 100, 100
# Level 1 but xp just under L3 (300): the smallest forest reward (8) crosses
# both L2 (100) and L3 (300) in this one award.
climber.level, climber.xp = 1, 295
events_before = len(game.events)
game.action("Climber", "fight", "", "")
assert climber.level == 3 # vaulted two levels on the single kill
new_events = game.events[events_before:]
level_ups = [e for e in new_events if e.kind == "level_up"]
assert len(level_ups) == 1 # one beat, not one per level crossed
assert "level 3" in level_ups[0].text.lower() # names the final level
assert "level 2" not in level_ups[0].text.lower() # not the intermediate
def test_level_up_appears_in_other_players_herald(tmp_path: Path, clock: object) -> None:
"""A level-up by one hero is news in another hero's Herald."""
game = _game(tmp_path, clock)
game.join("Riser")
game.join("Watcher")
watcher = game.players["Watcher"]
watcher.log_cursor = game._latest_event_id() # start Watcher caught up
riser = game.players["Riser"]
riser.x, riser.y = 35, 25 # forest_near zone
riser.atk, riser.def_, riser.hp, riser.max_hp = 100, 50, 100, 100
riser.xp = 95 # one win (>= 8 xp) crosses the level-2 threshold of 100
game.action("Riser", "fight", "", "")
assert riser.level >= 2 # the fight pushed Riser over the line
out = game.log("Watcher")
assert "Riser" in out
assert "level 2" in out.lower()
def test_defeat_appears_in_other_players_herald(tmp_path: Path, clock: object) -> None:
"""A defeat by a regular monster is news in another hero's Herald."""
game = _game(tmp_path, clock)
game.join("Faller")
game.join("Watcher")
watcher = game.players["Watcher"]
watcher.log_cursor = game._latest_event_id()
faller = game.players["Faller"]
faller.x, faller.y = 35, 25 # forest_near zone
faller.atk, faller.def_, faller.hp, faller.max_hp = 1, 0, 2, 20 # certain to fall
game.action("Faller", "fight", "", "")
assert faller.hp == 1 # bounced
out = game.log("Watcher")
assert "Faller" in out
assert "dragged back" in out.lower() or "fell to" in out.lower() or "bested" in out.lower()
# ---------------------------------------------------------------------------
# Movement events at the façade: no turn, no public feed
# ---------------------------------------------------------------------------
def test_move_events_cost_no_turn_and_write_no_feed(tmp_path: Path, clock: object) -> None:
"""A walk that fires non-combat events spends no turn and posts no Herald news.
Walks Brak back and forth across the forest_near zone (encounter_rate 0.25)
enough that some non-fight event almost certainly fires; whatever happens,
no turn is consumed and no public event is appended.
"""
game = _game(tmp_path, clock)
game.join("Brak")
player = game.players["Brak"]
player.x, player.y = 35, 25 # inside forest_near
before_turns = player.turns_left
before_events = len(game.events)
for _ in range(12):
game.move("Brak", "", "east", 1)
game.move("Brak", "", "west", 1)
assert player.turns_left == before_turns # movement never costs a turn
assert len(game.events) == before_events # walk texture is private
@@ -0,0 +1,3 @@
"""Understone — a BBS-style ANSI door game served over MCP."""
__version__ = "0.10.0"
@@ -0,0 +1,4 @@
from understone.server import main
if __name__ == "__main__":
main()
+724
View File
@@ -0,0 +1,724 @@
"""The pack-authoring command surface — validate a pack and scaffold a new one.
This module is deliberately pure: it imports only the loader and the standard
library, takes no part in argument parsing (``server.main`` owns the argparse
front end), and writes to the streams it is handed. That keeps the authoring
loop ``newpack`` then ``validate`` testable as plain function calls.
Three entry points back the three verbs:
* :func:`cli_validate` loads a pack and, on success, prints a human-readable
report; on failure it prints the loader's author-facing message and returns
a non-zero code. This is the feedback half of the loop.
* :func:`cli_newpack` scaffolds a new pack: it copies the bundled world as a
starting template and writes an ``AUTHORING.md`` manual whose bands table is
generated from the loader's own band data, so the documented limits can
never drift from the enforced ones.
* :func:`cli_worlds` lists the bundled worlds the default Vale plus every
alternate pack shipped under ``world/packs/`` loading each so it can report
whether it is sound or flawed, the discovery seam for "worlds without authors".
"""
from __future__ import annotations
import shutil
import sys
from typing import TYPE_CHECKING, TextIO
from understone.engine.textwidth import SAFE_PALETTE
from understone.errors import WorldLoadError
from understone.world import PACKAGED_WORLD_DIR, bundled_world_dirs, loader
if TYPE_CHECKING:
from pathlib import Path
from understone.engine.world import World
# The six packaged content files copied verbatim as a new pack's template.
_PACK_FILES = (
"terrain.json",
"monsters.json",
"items.json",
"locations.json",
"events.json",
"world.json",
)
def cli_validate(pack_dir: Path, out: TextIO | None = None, err: TextIO | None = None) -> int:
"""Load *pack_dir* and report; return 0 if sound, 2 if it fails to load.
On success a pack report is written to *out* and the function returns 0.
On any :class:`WorldLoadError` the loader's message — which names the
file, index, and field at fault is written to *err* and the function
returns 2. The author iterates against that message until the pack loads.
*out*/*err* default to the live ``sys.stdout``/``sys.stderr`` resolved at
call time, so a caller (or pytest's capture) may redirect them.
"""
out = out if out is not None else sys.stdout
err = err if err is not None else sys.stderr
try:
world = loader.load_world(pack_dir)
except WorldLoadError as exc:
print(f"The pack is flawed: {exc}", file=err)
return 2
print(_pack_report(world), file=out)
return 0
def cli_newpack(dest: Path, out: TextIO | None = None, err: TextIO | None = None) -> int:
"""Scaffold a new content pack at *dest*; return 0, or 2 if *dest* is taken.
Refuses to write into an existing non-empty directory (so an author never
clobbers work in progress). Otherwise it creates *dest*, copies the six
packaged content files as a starting template, and writes an
``AUTHORING.md`` manual generated from the live loader bands. The author
then edits or regenerates the JSON and runs ``validate``.
*out*/*err* default to the live ``sys.stdout``/``sys.stderr`` resolved at
call time, so a caller (or pytest's capture) may redirect them.
"""
out = out if out is not None else sys.stdout
err = err if err is not None else sys.stderr
if dest.exists() and dest.is_dir() and any(dest.iterdir()):
print(f"refusing to scaffold into non-empty directory: {dest}", file=err)
return 2
if dest.exists() and not dest.is_dir():
print(f"refusing to scaffold over a file: {dest}", file=err)
return 2
dest.mkdir(parents=True, exist_ok=True)
for name in _PACK_FILES:
shutil.copyfile(PACKAGED_WORLD_DIR / name, dest / name)
(dest / "AUTHORING.md").write_text(build_authoring_md(), encoding="utf-8")
print(f"Scaffolded a new pack at {dest}.", file=out)
print("Six content files plus AUTHORING.md are in place; the template is the", file=out)
print("shipped Vale of Understone, ready to edit or regenerate.", file=out)
print(f"Next: edit or regenerate the JSON, then: understone validate {dest}", file=out)
return 0
def cli_worlds(out: TextIO | None = None, err: TextIO | None = None) -> int:
"""List every bundled world, reporting each as sound or flawed; return 0.
Discovers the worlds through :func:`~understone.world.bundled_world_dirs`
(the default Vale first, then the alternate packs alphabetically) and loads
each one. Each world is one line its slug, name, ``WxH``, and either
``sound`` or ``flawed: <short reason>`` so a shipped pack that has gone
out of band is visible at a glance rather than only failing at serve time.
A flawed world is reported, not fatal: the listing always returns 0 and
always ends with the hint for serving an alternate. *err* is accepted for a
uniform signature with the other verbs; the listing writes only to *out*.
"""
out = out if out is not None else sys.stdout
for slug, world_dir in bundled_world_dirs():
print(_world_line(slug, world_dir), file=out)
print("", file=out)
print(
"Serve one with UNDERSTONE_WORLD=<path> (or the default Vale needs no setting).",
file=out,
)
return 0
def _world_line(slug: str, world_dir: Path) -> str:
"""Render one ``worlds`` listing line for the world at *world_dir*.
Loads the world to report its real name, dimensions, and soundness. A pack
that fails to load is summarised as ``flawed: <reason>`` using the loader's
own author-facing message (truncated to keep the listing to one line per
world), never raised the listing surveys every bundled world even when one
is broken.
"""
try:
world = loader.load_world(world_dir)
except WorldLoadError as exc:
return f" {slug:<10} flawed: {_short_reason(str(exc))}"
return f" {slug:<10} {world.name}{world.width}x{world.height} — sound"
# How much of a loader error message the one-line ``worlds`` summary keeps.
_FLAW_REASON_MAX = 70
def _short_reason(message: str) -> str:
"""Trim a loader error to a single readable clause for the worlds listing."""
flattened = " ".join(message.split())
if len(flattened) <= _FLAW_REASON_MAX:
return flattened
return flattened[: _FLAW_REASON_MAX - 1].rstrip() + ""
def _pack_report(world: World) -> str:
"""Render the success report for a loaded *world*.
Counts and shares are computed from the runtime world so the figures match
what the engine will actually run, not what the JSON nominally declares.
"""
settings = world.settings
boss_count = sum(1 for m in world.monsters if m.boss)
fight_share = _fight_share_pct(world)
lines = [
f"{world.name}{world.width}x{world.height}",
f" monsters : {len(world.monsters)} ({boss_count} boss)",
f" items : {len(world.items)}",
f" zones : {len(world.zones)}",
f" events : {len(world.events)} ({fight_share}% fight by weight)",
(
" settings : "
f"{settings.daily_turns} turns/day, "
f"bestow budget {settings.bestow_daily_budget}, "
f"Wyrm gate level {settings.wyrm_min_level}"
),
"",
"This pack is sound. The door stands open.",
]
return "\n".join(lines)
def _fight_share_pct(world: World) -> int:
"""Return the share of overworld encounter weight that is a ``fight``.
Reported by weight, not row count, because weight is the draw probability
the engine actually rolls against it is the number an author tunes to hit
the ~55% fight feel.
"""
total = sum(e.weight for e in world.events)
if total == 0:
return 0
fight = sum(e.weight for e in world.events if e.kind == "fight")
return round(100 * fight / total)
def build_authoring_md() -> str:
"""Build the AUTHORING.md manual, bands table and glyph palette included.
Both the bands section and the safe-glyph palette are generated from live
source the loader's own band tables and ``textwidth.SAFE_PALETTE`` — so
the documented limits and the suggested glyphs are exactly what the loader
enforces and admits, and cannot silently drift from it.
"""
md = _AUTHORING_TEMPLATE.replace("{{BANDS}}", _render_bands())
md = md.replace("{{PALETTE}}", _render_palette())
md = md.replace("{{COLOR_ROLES}}", _render_color_roles())
return md.replace("{{VALIDATE_COVERAGE}}", _render_validate_coverage())
def _render_bands() -> str:
"""Render the bands reference straight from the loader's band data."""
parts: list[str] = []
parts.append("### Map and counts\n")
parts.append(
f"* Map width and height: each `{loader.MAP_DIM_MIN}`..`{loader.MAP_DIM_MAX}` cells."
)
# monsters/items/events are their own files; locations and zones are lists
# inside world.json, so name each cap's real source.
count_source = {
"monsters": "`monsters.json`",
"items": "`items.json`",
"events": "`events.json`",
"locations": "`world.json` → `locations`",
"zones": "`world.json` → `zones`",
}
for name, cap in loader.MAX_COUNTS.items():
parts.append(f"* {count_source[name]}: at most `{cap}` entries.")
parts.append(
f"* Display names (monster, item, location): at most "
f"`{loader.MAX_NAME_LEN}` printable characters."
)
parts.append(
"* Map glyphs (terrain, location, legend keys): exactly one terminal "
"column (one printable code point, no fullwidth runes, no combining "
"marks — see the width rule above), and never one of "
+ ", ".join(f"`{g}`" for g in _reserved_glyph_list())
+ " (the frame box-drawing lines and the `@`/`☻` player markers)."
)
parts.append("")
parts.append("### Economy and progression settings (`world.json` → `settings`)\n")
parts.append("| field | allowed range |")
parts.append("| --- | --- |")
for field_name, (lo, hi) in loader.SETTINGS_BANDS.items():
rng = f"{lo}..{hi}" if hi is not None else f"{lo} or more"
parts.append(f"| `{field_name}` | `{rng}` |")
parts.append("")
parts.append("### Overworld event amounts (`events.json`, per kind)\n")
parts.append("| kind | min..max amount |")
parts.append("| --- | --- |")
for kind, (lo, hi) in loader.EVENT_AMOUNT_BANDS.items():
parts.append(f"| `{kind}` | `{lo}..{hi}` |")
parts.append(
"\n(`fight` and `lore` carry no amount; `fight` draws its foe from the "
"zone tier band, `lore` is pure flavour text.)\n"
)
parts.append("### Watch theme (`world.json` → `settings.watch_theme`)\n")
legal = ", ".join(f"`{name}`" for name in sorted(loader.WATCH_THEMES))
parts.append(
f"OPTIONAL. The CRT palette the live Watch page paints your world in, "
f"one of: {legal}. It defaults to `{loader.DEFAULT_WATCH_THEME}` (the "
f"original green phosphor), so you may leave it out entirely — a pack "
f"that omits it looks exactly as the bundled Vale always has. Set it to "
f"give your world its own colour: `amber` is a warm gold monitor, `ice` "
f"a cold pale blue, `ember` a hot red/orange. An unknown name is a load "
f"error naming the legal set."
)
parts.append("\n### The ore-gated forge (`world.json` → `settings`)\n")
ore_per = loader.SETTINGS_BANDS["forge_ore_per_plus"]
dungeon = loader.SETTINGS_BANDS["ore_dungeon_drop"]
parts.append(
"Forging a +1 edge now costs both GOLD and ORE — a `material` item the "
"hero earns in combat, never buys. Four settings bind it:"
)
parts.append(
"* `forge_ore_item` — REQUIRED. The item id of your world's forge ore; "
"it must name an `items.json` entry whose `slot` is `material` (an "
"unknown id or a non-material slot is a load error). The Vale uses "
"`iron_ore`."
)
parts.append(
f"* `forge_ore_per_plus` — band `{ore_per[0]}..{ore_per[1]}`. Ore per +1 "
f"step: a +N forge costs `(current_plus + 1) * forge_ore_per_plus` ore. "
f"{_forge_ore_worked_example()}"
)
parts.append(
f"* `ore_dungeon_drop` — band `{dungeon[0]}..{dungeon[1]}`. Ore granted "
f"on every WON dungeon rung — the reliable source. The Vale drops 2."
)
parts.append(
"* `ore_forest_chance` — a `0.0`..`1.0` probability (a float, validated "
"outside the integer band table). The chance a WON forest fight yields "
"one ore — the occasional bonus source. The Vale uses `0.2`."
)
parts.append(
"\nOre rides the satchel as a stack, so it shares the `satchel_max` "
"DISTINCT-stack budget with potions (per-stack quantity is unbounded). "
"Tune the two sources so a hero who descends steadily earns enough ore "
"to forge without grinding — the `simulate` bot will tell you if the "
"gate stalls a winnable run."
)
return "\n".join(parts)
def _forge_ore_worked_example() -> str:
"""Render the per-step ore costs from the bundled Vale's live forge settings.
The starter template :func:`cli_newpack` copies IS the bundled Vale, so the
worked figures are computed from its actual ``forge_ore_per_plus`` and
``forge_max_plus`` rather than hardcoded a retune of the template moves
the manual with it. The steps are ``per_plus * (i + 1)`` for each ``i`` in
``range(forge_max_plus)``; the total is what it costs to max one slot.
"""
settings = loader.load_world(PACKAGED_WORLD_DIR).settings
per_plus = settings.forge_ore_per_plus
max_plus = settings.forge_max_plus
steps = [per_plus * (i + 1) for i in range(max_plus)]
if not steps:
return (
f"At the template's value of {per_plus}, slots cannot be forged (`forge_max_plus` 0)."
)
ladder = ", ".join(str(cost) for cost in steps)
total = sum(steps)
return (
f"At the template's value of {per_plus}, the steps cost {ladder} ore "
f"({total} ore to max a slot at `forge_max_plus` {max_plus})."
)
def _reserved_glyph_list() -> list[str]:
"""Return the reserved glyphs in a stable, readable order for the manual."""
box = [g for g in "┌┐└┘─│═" if g in loader.RESERVED_GLYPHS]
actors = [g for g in "@☻" if g in loader.RESERVED_GLYPHS]
return box + actors
def _render_palette() -> str:
"""Render the safe-glyph appendix straight from ``textwidth.SAFE_PALETTE``.
The glyphs are emitted in their declared order, wrapped in backticks so the
monospace renders them as discrete cells. Generated from the live constant,
so the suggested palette is exactly the set the loader's width gate admits.
"""
glyphs = " ".join(f"`{g}`" for g in SAFE_PALETTE)
return (
"Any single-column glyph the loader accepts is fair game, but these "
"carry the period BBS / CP437 flavour and are all guaranteed safe:\n\n"
f"{glyphs}"
)
def _render_color_roles() -> str:
"""Render the author-assignable colour roles, generated from the Color enum.
The Watch knows how to paint exactly the roles in ``screen.palette.Color``;
``Color.assignable()`` is the single source for which of those an author may
put on terrain or a location (the runtime overlay roles an actor/item wears,
and the DEFAULT fallback, are filtered out there). Generated from the enum,
so the documented vocabulary can never drift from what the Watch can
actually colour the same can't-drift discipline as the bands and the
safe-glyph palette. ``color`` itself stays advisory: the loader does not
validate it, so a typo is harmless and an unknown role just paints as the
default; these are simply the roles the Watch recognises.
"""
from understone.screen.palette import Color
return ", ".join(f"`{role.value}`" for role in Color.assignable())
def _render_validate_coverage() -> str:
"""Render the list of rules the loader actually enforces, generated from it.
The figures that can drift (the number of banded settings, the name-length
cap, the reserved glyphs) are read from the live loader so the list cannot
fall out of step with what `validate` does; the prose names each family of
check. This is the machine-enforced half of the honesty split in the manual
the eyeball-only half is hand-written below it, because "is the fiction
any good" is exactly what the loader can never see.
"""
settings_count = len(loader.SETTINGS_BANDS)
reserved = ", ".join(f"`{g}`" for g in _reserved_glyph_list())
bullets = [
f"* **Economy and progression bands** — every one of the {settings_count} `settings` fields must sit in its allowed range (the table above), and `growth` must be present and non-negative.",
f"* **Glyph safety** — every terrain, location, and legend glyph must render exactly one column and must not be a reserved marker ({reserved}).",
"* **Map integrity** — `width`/`height` in band, every `terrain_rows` row exactly `width` long with `height` rows, and every row character in the `legend`.",
"* **Walkability** — `spawn` and every placed location must sit on walkable terrain (and no two locations share a cell).",
f"* **Display-name length** — every monster, item, and location name within `{loader.MAX_NAME_LEN}` printable characters; content lists within their caps.",
"* **The fight row** — `events.json` must hold at least one `fight` entry, with weights `> 0`, `min <= max`, and amounts in their per-kind band.",
'* **Cross-references** — `legend` → terrain key, location placements → `locations.json` keys, `starting_weapon`/`starting_armor` → item ids, `boss_monster` → a monster flagged `"boss": true`, `rare_drop_item` → a consumable item id, and `forge_ore_item` → a `material` item id.',
"* **Zone tiers** — every zone's tier band must overlap at least one monster tier.",
"* **Dungeon ladder** — every `dungeon_tiers` tier must have a non-boss monster, and that tier's FIRST monster (its fixed rung guardian) must not be `rare`.",
'* **Exactly one boss** — at most one monster may carry `"boss": true`.',
]
return "\n".join(bullets)
_AUTHORING_TEMPLATE = """\
# Authoring a world pack for Understone
A *world pack* is a directory of six JSON files that the server loads at start
to become the entire game world its map, its monsters, its economy, its
endgame. There is no code to write: you describe a world as data, the loader
validates it hard, and the server runs it. This file is the manual; you can
follow it cold, by hand or with an LLM.
The loop is short:
1. `understone newpack mypack` scaffold this template (you are reading the
copy it wrote into `mypack/AUTHORING.md`).
2. Edit or regenerate the JSON files to describe your world.
3. `understone validate mypack` the loader checks the pack and either prints
a report ending **"This pack is sound. The door stands open."** or tells you
exactly which file, row, and field is wrong.
4. Repeat step 2 until it is sound, then serve it:
`UNDERSTONE_WORLD=mypack understone`.
The loader's error messages are written FOR you: every failure names the file,
the index, and the field, and says what was expected. Treat them as the
feedback loop iterate until the report says the door stands open.
---
## The six files and how they fit together
| file | shape | holds |
| --- | --- | --- |
| `terrain.json` | object keyed by legend char | terrain kinds: glyph, walkability, encounter rate |
| `monsters.json` | list | monster stat blocks, tiered; one flagged the boss |
| `items.json` | list | weapons, armour, consumables for the shop |
| `locations.json` | object keyed by location key | building kinds: name, glyph, menu actions, flavour |
| `events.json` | object with an `events` list | the weighted overworld encounter table |
| `world.json` | object | the map, placements, zones, and `settings` that bind it all |
The cross-references the loader enforces:
* every character in `world.json` `legend` must name a terrain `key` from
`terrain.json`; every character in `terrain_rows` must be in that legend;
* every placement in `world.json` `locations` must name a key defined in
`locations.json`, and must sit on walkable terrain;
* `settings.starting_weapon` / `starting_armor` must be ids from
`items.json`; `settings.boss_monster` must be an id from `monsters.json`
that is flagged `"boss": true`; `settings.rare_drop_item` must be an id from
`items.json` whose `slot` is `consumable`; `settings.forge_ore_item` must be
an id from `items.json` whose `slot` is `material`;
* every tier in `settings.dungeon_tiers` must be backed by a NON-boss monster;
* every zone's tier band must overlap at least one monster tier.
---
## File-by-file schema
### `terrain.json`
An object whose keys are the single-character legend symbols used in the map.
```json
{
".": {"key": "grass", "glyph": ".", "walkable": true, "encounter_rate": 0.1, "color": "floor"}
}
```
* `key` internal name the map legend resolves to.
* `glyph` the single character drawn on the map (see glyph rules below).
* `walkable` may a player stand here.
* `encounter_rate` `0.0`..`1.0`, the per-step chance a walk rolls the event
table on this terrain.
* `color` a palette role string. It is **advisory and not validated**: the
loader stores it but the text frame draws glyphs only (it is monochrome), so
any string loads and an unrecognised role simply maps to the default at render
time. Where colour DOES show is the live Watch page, which paints each role a
distinct hue. The roles the Watch knows how to paint pick the closest fit
are: {{COLOR_ROLES}}. A typo here is harmless, not a load error; it just
paints as the default. The four runtime overlay colours (the hero, rival
players, monsters, dropped items) are set by the engine, not assignable here.
### `monsters.json`
A list of stat blocks. `tier` groups foes by difficulty; zones and the dungeon
gauntlet draw from tiers. Exactly one monster should be the boss.
```json
{"tier": 2, "name": "Goblin", "hp": 12, "atk": 5, "def": 1, "xp": 18, "gold": 7}
```
The boss adds an `id` and `"boss": true`, and is referenced by
`settings.boss_monster`:
```json
{"tier": 6, "name": "the Wyrm Below", "hp": 120, "atk": 24, "def": 8,
"xp": 400, "gold": 250, "boss": true, "id": "wyrm_below"}
```
Two optional fields tune random forest encounters. `weight` (default `10`,
must be `> 0`) biases the weighted draw within a zone band a low weight
surfaces seldom and `rare` (default `false`) marks a named beast that, on
its kill, fires a public Herald flash and drops the pack's `rare_drop_item`
into the slayer's satchel. Rung guardians ignore both (a rung always takes the
FIRST monster of its tier, never a weighted roll), so a rare should not be the
first entry of a tier that backs a `dungeon_tiers` rung.
```json
{"tier": 2, "name": "the Gilded Stag", "hp": 16, "atk": 6, "def": 2,
"xp": 40, "gold": 60, "weight": 1, "rare": true}
```
### `items.json`
A list of equipment, consumables, and crafting materials. `slot` is `weapon`,
`armor`, `consumable`, or `material`. Weapons add `atk`, armour adds `def`,
consumables `heal`; a `material` carries none of these it is the forge ORE,
carried in the satchel and spent at the forge.
```json
{"id": "short_sword", "name": "Short Sword", "slot": "weapon", "atk": 5, "price": 40}
```
The forge ore is a `material` item the player EARNS in combat (not the shop):
price it `0` ore is never bought or sold and point `settings.forge_ore_item`
at its id. A won dungeon rung always drops `settings.ore_dungeon_drop` of it, and
a won forest fight has a `settings.ore_forest_chance` chance of one.
```json
{"id": "iron_ore", "name": "Iron Ore", "slot": "material", "price": 0}
```
### `locations.json`
An object keyed by location key. Each entry is a building kind with a menu of
`actions` the player may take inside it.
```json
{
"inn": {"kind": "inn", "name": "The Sleeping Drake", "glyph": "I",
"color": "town", "actions": ["rest", "gamble", "leave"],
"flavor": ["Lamplight pools on worn oak tables."]}
}
```
Give each building the menu that matches its role. The four building kinds and
the verbs the engine honours inside each are:
| `kind` | actions the engine understands |
| --- | --- |
| `inn` | `rest`, `deposit`, `withdraw`, `gamble`, `leave` |
| `shop` | `buy`, `sell`, `forge`, `leave` |
| `healer` | `heal`, `leave` |
| `dungeon` | `descend`, `challenge`, `leave` |
The inn's `deposit`/`withdraw` are the VAULT: a player banks gold into the inn
strongbox (`deposit amount=<gold>`) and draws it back (`withdraw amount=<gold>`).
Banked gold is SAFE from ambush a sleeping-robber only ever lifts gold in hand
and it SURVIVES the Wyrm-win legacy reset, so it is the one store of wealth
that carries across runs. Both cost no turn.
`quaff` (drink a satchel tonic) is legal **anywhere** and needs no menu entry.
The `actions` list is advisory it is the menu the narrator offers, NOT a
validated whitelist (see "What `validate` checks" below): a verb the engine does
not back simply confuses the narrator, so give each building only the verbs from
its row above.
### `events.json`
An object with an `events` list the weighted overworld encounter table the
server rolls as a player walks.
```json
{"events": [
{"kind": "fight", "weight": 82, "text": "Something snarls out of the brush."},
{"kind": "gold", "weight": 8, "text": "a rotted coin-purse", "min": 4, "max": 12}
]}
```
* `kind` `fight`, `gold`, `heal`, `trap`, or `lore`.
* `weight` relative draw weight (`> 0`).
* `text` required (non-empty) for every kind except `fight`.
* `min`/`max` required for the value-bearing kinds (`gold`, `heal`, `trap`).
There MUST be at least one `fight` row, or a walk could never find a monster.
### `world.json`
The binding file: `name`, `width`, `height`, `spawn` `[x, y]` (the hero's start
cell, which must be on walkable terrain), a `legend` mapping characters to
terrain keys, `terrain_rows` (one string per row, each exactly `width` long), a
`locations` list of `{"key", "x", "y"}` placements (each also on walkable
terrain), a `zones` list (rectangles that bias monster tiers), and a `settings`
object.
```json
{"key": "forest_near", "rect": [30, 18, 60, 36], "tier_lo": 1, "tier_hi": 2}
```
---
## The bands — the limits the loader enforces
These are generated from the loader's own tables, so they are exactly what
`validate` checks. A value outside its band is a load error.
{{BANDS}}
---
## Glyph width — the one-column rule
Every glyph drawn on the map must occupy **exactly one terminal column**. The
frames are box-drawing rectangles; a glyph that renders two columns (a CJK
ideograph like ``, an emoji like `🌲`, a fullwidth ``) shoves its row right
and tears the border, and a combining mark (a decomposed `é`, a lone accent)
stacks onto its neighbour and breaks the count the other way. The loader
rejects all of these at load.
What is admitted is judged for the **Western monospace** metrics every
Understone surface actually uses (the Watch's pinned font stack, a chat
client's code block): under those metrics the East-Asian "Ambiguous" width
class renders single-column, and that class is the CP437 heartland ``, ``,
``, ``, ``, `` all live there so the rule admits it and bars only the
genuinely double-width Wide and Fullwidth classes.
### Safe glyph palette
{{PALETTE}}
---
## Design guidance
**Turn economy.** `daily_turns` is the whole pacing lever: only fighting,
descending, and challenging the Wyrm spend a turn (moving, resting, shopping
are free). A small budget (the Vale uses 10) makes this a correspondence game
played a little each day. Set `rest_cost`, `heal_cost_per_hp`, and shop prices
so a day's gold roughly covers a day's recovery too cheap and there is no
tension, too dear and a hero stalls.
**Tier curve.** Lay monster tiers as a rising staircase: each tier should be a
real step up in `hp`/`atk` and a real step up in `xp`/`gold`, so the reward of
pushing into a harder zone pays for the risk. Keep two or three foes per tier
for variety. The boss should tower over the top random tier it is the climax.
**Encounter feel.** Aim for roughly 55% of overworld encounter WEIGHT on
`fight` rows; the rest is the texture of travel small gold finds, healing
springs, harmless traps, and lore that hints at the endgame. (The validate
report prints your actual fight share so you can tune it.)
**Glyphs.** Map glyphs must render as exactly one terminal column (see the
one-column rule above) and must never collide with the frame's box-drawing
lines or the `@`/`` player markers. Pick glyphs that read at a glance the
bundled Vale uses `.` open ground, `` water, `` tree, `` inn, `$` shop, ``
healer, `` dungeon and lean on the safe palette for period flavour.
**Boss rules.** Exactly one monster carries `"boss": true` and an `id`, and
`settings.boss_monster` points at it. The boss is the only win condition and is
faced only through the `challenge` verb, gated by `settings.wyrm_min_level`. A
boss tier must NOT appear in `settings.dungeon_tiers`: the gauntlet excludes
boss monsters, so a boss-only rung would be unfillable back every dungeon
tier with at least one ordinary monster.
**The deep, the satchel, and the forge.** `dungeon_tiers` is now a RUNG LADDER
fought one rung per `descend` list the tiers shallow-to-deep, and make it long
enough to feel like a journey (the Vale uses three). The Wyrm gates on reaching
the floor as well as on level. Size the satchel with `satchel_max` it caps the
DISTINCT stacks the bag holds (potions and ore each take a slot; per-stack
quantity is unbounded), and it is the death-save reserve, so keep it small (the
Vale carries 3). The forge is the late-game GOLD-AND-ORE sink: `forge_base_cost`
is the gold price of a +1 edge and scales up each tier (`base * (current_plus +
1)`), capped at `forge_max_plus`, and each step ALSO costs ore (see the ore-gated
forge above). Ore is won in the deep (and seldom in the forest), so the forge is
fed by descending price the gold so a fully-forged piece is a multi-day saving,
and set the ore sources so a steady delver can afford it without a grind.
**Rare beasts.** A rare monster is a small legend: give it a low `weight` so it
surfaces seldom, stats and rewards a clear notch above its tier, and remember it
always drops `rare_drop_item` (a consumable) into the satchel. Keep rares OFF
the first slot of any `dungeon_tiers` tier, or they would become a fixed rung
guardian instead of a rare roll `validate` now ENFORCES this, so a rare in a
dungeon tier's lead slot is a load error, not just bad form. Place the rare
anywhere after that tier's first ordinary monster.
**Location menus.** Give each building only the actions it can honour, drawn
from the per-kind table under `locations.json` above. An inn that offers `buy`
but no shop logic will confuse the narrator. This is the one major thing
`validate` does NOT check (see below): a wrong or invented verb loads fine and
only muddles the narration, so it is on you to match each menu to its building.
---
## The validate loop
Run `understone validate mypack` after every change. On success you get a
report name, size, monster/item/zone/event counts, fight share, and the key
settings ending in **"This pack is sound. The door stands open."** On
failure you get one precise line naming the file, the row, and the field.
The error messages are deliberately instructive: they are the authoring API.
Keep editing and re-validating until the door stands open, then point the
server at your pack with `UNDERSTONE_WORLD=mypack`.
### What `validate` checks, and what it cannot
`validate` runs your pack through the very loader the server uses, so a pack
that validates will load and serve. But the loader checks *structure and
references*, not *meaning* it cannot read your fiction. Keep the split honest:
**`validate` DOES catch (a load error if wrong):**
{{VALIDATE_COVERAGE}}
**`validate` does NOT catch (the eyeball-only short list):**
* **Location menu `actions` contents.** The list is the narrator's menu, not a
validated whitelist: a verb the engine does not back (a typo, or a fictional
`pray`) loads fine and only confuses the narration. Match each building's menu
to the per-kind table under `locations.json`.
* **Flavour and narration quality.** Names, `flavor` lines, event `text`, the
feel of the tier curve and the economy the loader checks they are present
and in band, never whether they are *good*. That judgement is yours; the
`simulate` bot can tell you a world is winnable and sanely paced, but only you
can tell whether it is worth playing.
"""
@@ -0,0 +1,6 @@
"""Game engine — pure stdlib mechanics with injectable clock and RNG.
This package has no knowledge of MCP, persistence, or rendering. Every
function takes its inputs explicitly (world, player, rng, clock) so the
mechanics are deterministic under test.
"""
@@ -0,0 +1,117 @@
"""Combat resolution — pure math over an injected RNG.
A fight runs deterministic rounds: both sides trade blows until one drops.
Damage is ``max(1, attacker_atk - defender_def)`` jittered by a small RNG
swing so identical stats still produce varied logs. The result is a value
object; turn accounting and the spawn-bounce on defeat are applied by the
caller (the game façade), keeping this module side-effect free.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from enum import StrEnum
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from understone.engine.models import Monster, Player
from understone.engine.rng import GameRNG
_MAX_ROUNDS = 50
class Outcome(StrEnum):
"""How a fight ended."""
WIN = "win"
LOSE = "lose"
FLED = "fled"
@dataclass(slots=True)
class FightResult:
"""The full outcome of a combat exchange.
Deltas are signed and meant to be applied to the player by the caller.
``bounce_to_spawn`` signals a defeat: the caller sets ``hp`` to 1 and
moves the player back to the spawn point.
"""
outcome: Outcome
log: list[str] = field(default_factory=list)
xp_delta: int = 0
gold_delta: int = 0
hp_delta: int = 0
bounce_to_spawn: bool = False
monster_name: str = ""
def _swing(rng: GameRNG, atk: int, def_: int) -> int:
"""Return one blow's damage: floor of 1, with a small RNG jitter."""
base = atk - def_
jitter = rng.randint(-1, 2)
return max(1, base + jitter)
def resolve_fight(rng: GameRNG, player: Player, monster: Monster) -> FightResult:
"""Run a full fight between *player* and *monster*.
The player strikes first each round. On victory the player banks the
monster's xp/gold and keeps any hp lost during the exchange. On defeat
the result flags a spawn bounce for the caller to apply.
"""
result = FightResult(outcome=Outcome.WIN, monster_name=monster.name)
player_hp = player.hp
monster_hp = monster.hp
result.log.append(f"You close with the {monster.name}.")
for _ in range(_MAX_ROUNDS):
dealt = _swing(rng, player.atk, monster.def_)
monster_hp -= dealt
result.log.append(f"You strike for {dealt}. ({monster.name}: {max(monster_hp, 0)} HP)")
if monster_hp <= 0:
result.outcome = Outcome.WIN
result.xp_delta = monster.xp
result.gold_delta = monster.gold
result.hp_delta = player_hp - player.hp
# The kill round (the strike line above) stays; the "falls + reward"
# sentence is composed by the caller at the moment it actually banks
# the xp/gold, so a reward is never narrated where none is applied
# (e.g. the Wyrm-win legacy reset, which keeps no xp/gold).
return result
taken = _swing(rng, monster.atk, player.def_)
player_hp -= taken
result.log.append(f"It hits back for {taken}. (You: {max(player_hp, 0)} HP)")
if player_hp <= 0:
result.outcome = Outcome.LOSE
result.bounce_to_spawn = True
result.log.append(
f"The {monster.name} lays you low. You wake at the spawn, barely alive."
)
return result
# Stalemate guard: treat an unresolved marathon as a flight to safety.
result.outcome = Outcome.FLED
result.hp_delta = player_hp - player.hp
result.log.append("The fight grinds on until you break away, winded.")
return result
def resolve_flee(rng: GameRNG, player: Player, monster: Monster) -> FightResult:
"""Attempt to flee a fight.
A successful flee escapes clean. A failed flee costs one free blow from
the monster but never drops the player below 1 HP (fleeing is a way out,
not a death trap).
"""
result = FightResult(outcome=Outcome.FLED, monster_name=monster.name)
if rng.chance(0.6):
result.log.append(f"You slip away from the {monster.name}.")
return result
taken = _swing(rng, monster.atk, player.def_)
taken = min(taken, max(player.hp - 1, 0))
result.hp_delta = -taken
result.log.append(f"You turn to run; the {monster.name} catches you for {taken} as you go.")
return result
@@ -0,0 +1,108 @@
"""Experience, level-ups, and the inn/healer restorative maths.
The XP curve and stat growth come from the content pack's settings, so no
progression constants live in this module. Level-ups loop (a single XP
award can cross several thresholds), grant flat stat growth, and fully
heal on each level gained.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from understone.engine.models import Player, Settings
@dataclass(slots=True)
class LevelUp:
"""A record of a single level gained, for narration."""
new_level: int
hp_gain: int
atk_gain: int
def_gain: int
def xp_for_level(level: int, settings: Settings) -> int:
"""Return cumulative XP required to *reach* ``level``.
Level 1 needs 0. The default curve is ``base * n*(n+1)/2`` over the
completed levels, i.e. a triangular ramp scaled by ``xp_base``.
"""
if level <= 1:
return 0
completed = level - 1
return settings.xp_base * completed * (completed + 1) // 2
def apply_xp(player: Player, amount: int, settings: Settings) -> list[LevelUp]:
"""Award ``amount`` XP to *player*, applying every level-up it unlocks.
Returns one :class:`LevelUp` per level gained (empty when none). Each
level grants flat growth from settings and fully heals the player.
"""
player.xp += max(0, amount)
gains: list[LevelUp] = []
while player.xp >= xp_for_level(player.level + 1, settings):
player.level += 1
player.max_hp += settings.growth_max_hp
player.atk += settings.growth_atk
player.def_ += settings.growth_def
player.hp = player.max_hp
gains.append(
LevelUp(
new_level=player.level,
hp_gain=settings.growth_max_hp,
atk_gain=settings.growth_atk,
def_gain=settings.growth_def,
)
)
return gains
def rest(player: Player, cost: int) -> bool:
"""Fully heal *player* at the inn for a flat ``cost``.
Returns ``False`` without mutation when the player cannot afford it.
Resting when already at full HP still succeeds (and still charges),
matching the inn's flat-rate fiction.
"""
if player.gold < cost:
return False
player.gold -= cost
player.hp = player.max_hp
return True
@dataclass(slots=True)
class HealResult:
"""Outcome of a healer purchase: HP actually restored and gold spent."""
healed: int
cost: int
def heal(player: Player, amount: int, cost_per_hp: int) -> HealResult:
"""Restore up to ``amount`` HP at ``cost_per_hp`` gold each.
Heals only the missing portion, charges only for HP actually restored,
and is further bounded by what the player can afford. Returns the amount
healed and the gold spent (both zero when nothing could be done).
"""
missing = player.max_hp - player.hp
want = max(0, min(amount, missing))
if want <= 0 or cost_per_hp < 0:
return HealResult(healed=0, cost=0)
if cost_per_hp == 0:
player.hp += want
return HealResult(healed=want, cost=0)
affordable = player.gold // cost_per_hp
apply = min(want, affordable)
if apply <= 0:
return HealResult(healed=0, cost=0)
spent = apply * cost_per_hp
player.hp += apply
player.gold -= spent
return HealResult(healed=apply, cost=spent)
@@ -0,0 +1,63 @@
"""The shared event log — a world-wide feed players catch up on.
Events are append-only and ordered by insertion. Each player tracks a
cursor (the id of the last event they have seen); ``since`` returns the
slice after a cursor and the new cursor to persist.
An event carries a ``target``: empty means PUBLIC (the broadsheet and the
lobby TV), a player name means a PRIVATE note that only that player reads in
their own catch-up. Targeted rows ride the same id order as public ones, so
the cursor advances identically whether or not a private note was shown.
"""
from __future__ import annotations
from dataclasses import dataclass
@dataclass(frozen=True, slots=True)
class Event:
"""A single logged happening in the shared world.
``target`` is the empty string for public events (heralded to everyone)
or a player's name for a private note delivered only to that player.
"""
event_id: int
ts: str
kind: str
actor: str
text: str
target: str = ""
def since(events: list[Event], cursor: int) -> tuple[list[Event], int]:
"""Return events newer than ``cursor`` and the cursor to store next.
Events are kept in ascending id order (the store hydrates the newest tail
and reverses it to ascending; appends are monotonic), so the last fresh
event carries the highest id; that becomes the new cursor.
When nothing is new the input cursor is returned, so advancing is
idempotent.
"""
fresh = [e for e in events if e.event_id > cursor]
if not fresh:
return [], cursor
return fresh, fresh[-1].event_id
def since_visible(events: list[Event], cursor: int, viewer: str) -> tuple[list[Event], int]:
"""Like :func:`since`, but hide private notes not addressed to *viewer*.
Returns the events newer than ``cursor`` that *viewer* may read every
public event (empty ``target``) plus the private notes addressed to them
and the new cursor. The cursor advances to the highest id PAST the old
cursor regardless of visibility, so a private note for someone else is
consumed (never re-scanned) without ever being shown here.
"""
fresh = [e for e in events if e.event_id > cursor]
if not fresh:
return [], cursor
new_cursor = fresh[-1].event_id
visible = [e for e in fresh if not e.target or e.target == viewer]
return visible, new_cursor
@@ -0,0 +1,232 @@
"""Core data models for the game engine.
All models are plain dataclasses. ``Player`` is mutable (the engine applies
deltas in place); the static content models (``Monster``, ``Item``,
``TerrainDef``, ``LocationDef``, ``Zone``) are frozen.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from enum import StrEnum
class Mode(StrEnum):
"""Which interaction surface the player is currently on."""
TILE = "tile"
MENU = "menu"
class Slot(StrEnum):
"""Equipment / item slot kinds."""
WEAPON = "weapon"
ARMOR = "armor"
CONSUMABLE = "consumable"
# v0.10 forge ore: a crafting MATERIAL carried in the satchel and spent at
# the forge. It is never equipped, never quaffed (no atk/def/heal), and
# never sold or bought — ore is earned in combat, not traded.
MATERIAL = "material"
@dataclass(slots=True)
class Player:
"""A single adventurer's durable state.
Coordinates are map cells; ``mode`` and ``at_location`` track whether
the player is on the overworld or inside a location menu. Turn fields
gate the daily action budget; bestow fields gate the daily fortune pool.
"""
name: str
x: int
y: int
hp: int
max_hp: int
level: int
xp: int
gold: int
atk: int
def_: int
weapon_id: str
armor_id: str
turns_left: int
turn_day: int
mode: Mode
at_location: str
created_at: str
last_seen: str
log_cursor: int
bestow_spent: int
bestow_day: int
wins: int = 0
posts_sent: int = 0
post_day: int = 0
gambles: int = 0
gamble_day: int = 0
# v0.7 "depth below" retention columns: how far the dungeon has been
# plumbed (0 = never descended; N = cleared rung N, 1-indexed), the
# carried satchel (see below), and the enhancement plus on whichever
# weapon/armour is CURRENTLY equipped in each slot.
deepest_rung: int = 0
# v0.10 STACK-BASED satchel: comma-joined "id:qty" stacks ('' = empty),
# e.g. "minor_potion:3,iron_ore:5". ``satchel_max`` caps DISTINCT stacks,
# not total items; per-stack qty is unbounded. Replaces the v0.7 flat id
# list. The "id:qty" wire format is owned by understone.engine.satchel
# (decode_satchel/encode_satchel); every reader goes through that codec.
satchel: str = ""
weapon_plus: int = 0
armor_plus: int = 0
# v0.10 the Vault: gold banked at the inn. SAFE from ambush (the steal only
# ever touches carried ``gold``) and SURVIVES the Wyrm-win legacy reset (a
# small persistent reward across runs, like a win ★).
banked: int = 0
@dataclass(frozen=True, slots=True)
class Monster:
"""A static monster definition from the content pack.
``boss`` monsters are the fixed endgame foe (the Wyrm Below): they are
excluded from random tier-band selection and only ever faced through the
deliberate ``challenge`` verb.
"""
tier: int
name: str
hp: int
atk: int
def_: int
xp: int
gold: int
monster_id: str = ""
boss: bool = False
# v0.7 weighted forest encounters: ``weight`` biases the random pick (a
# low weight surfaces seldom), ``rare`` marks a named beast that fires a
# public Herald flash and drops a guaranteed draught on the kill. Rung
# guardians ignore both (a rung is a fixed foe, never a weighted roll).
weight: int = 10
rare: bool = False
@dataclass(frozen=True, slots=True)
class Item:
"""A static item / equipment definition from the content pack."""
item_id: str
name: str
slot: Slot
atk: int
def_: int
heal: int
price: int
@dataclass(frozen=True, slots=True)
class TerrainDef:
"""A terrain kind: its glyph, walkability, encounter rate, colour role."""
key: str
glyph: str
walkable: bool
encounter_rate: float
color: str
@dataclass(frozen=True, slots=True)
class LocationDef:
"""A named location placed on the map (inn, shop, healer, dungeon)."""
key: str
kind: str
name: str
x: int
y: int
glyph: str
color: str
actions: tuple[str, ...]
flavor: tuple[str, ...] = field(default_factory=tuple)
@dataclass(frozen=True, slots=True)
class Zone:
"""A rectangular region that biases which monster tiers spawn."""
key: str
x0: int
y0: int
x1: int
y1: int
tier_lo: int
tier_hi: int
def contains(self, x: int, y: int) -> bool:
"""Return whether ``(x, y)`` falls inside this zone's rectangle."""
return self.x0 <= x <= self.x1 and self.y0 <= y <= self.y1
@dataclass(frozen=True, slots=True)
class WorldEvent:
"""One row of the weighted overworld encounter table.
``kind`` is one of ``fight``/``gold``/``heal``/``trap``/``lore``.
``weight`` biases random selection. ``lo``/``hi`` bound the rolled amount
for the value-bearing kinds (gold/heal/trap); they are unused for
``fight`` (the foe comes from the zone band) and ``lore`` (pure flavour).
"""
kind: str
weight: int
text: str
lo: int
hi: int
@dataclass(frozen=True, slots=True)
class Settings:
"""Economy and progression parameters sourced from the content pack."""
daily_turns: int
rest_cost: int
heal_cost_per_hp: int
starting_gold: int
starting_weapon: str
starting_armor: str
start_hp: int
start_atk: int
start_def: int
xp_base: int
growth_max_hp: int
growth_atk: int
growth_def: int
bestow_daily_budget: int
dungeon_tiers: tuple[int, ...]
boss_monster: str
wyrm_min_level: int
ambush_min_level: int
ambush_level_band: int
ambush_gold_pct: int
post_daily_cap: int
gamble_max_bet: int
gamble_daily_cap: int
# v0.7 "depth below": the carried-potion satchel size, the forge cost
# ladder (base * (current_plus + 1)) and its enhancement ceiling, and the
# consumable item a rare beast is guaranteed to drop on its kill.
satchel_max: int
forge_base_cost: int
forge_max_plus: int
rare_drop_item: str
# v0.10 the ore-gated forge: the world's forge MATERIAL item id (validated
# to slot=material), the ore each +1 step costs (need = (plus + 1) *
# per_plus), and the two ore sources — a guaranteed drop on a won dungeon
# rung and a chance of one ore on a won forest fight. Ore is combat-earned,
# never purchasable; the forge spends gold AND ore.
forge_ore_item: str
forge_ore_per_plus: int
ore_dungeon_drop: int
ore_forest_chance: float
# v0.8 "worlds without authors": the Watch's per-world CRT palette. One of
# the names in WATCH_THEMES; defaults to "phosphor" (the original green), so
# a pack that omits it looks exactly as the Vale always has.
watch_theme: str = "phosphor"
@@ -0,0 +1,223 @@
"""Overworld movement resolution.
Movement walks tile by tile so each intermediate cell is checked for
walls/edges and rolls an encounter. When a roll fires it weighted-picks one
row from the world's event table. A ``fight`` row STOPS the walk (a wandering
monster bars the path); the value-bearing rows (gold/heal/trap) and pure
``lore`` are applied immediately and the walk continues but only one event
fires per walk, so once any row has fired no further cells roll.
The walk stops early on the first of: running out of steps, hitting a blocked
cell, stepping onto a location door (flips to MENU), or a ``fight`` encounter.
Movement spends no daily turns only fighting does. Gold/heal/trap deltas are
applied straight to the player here (movement already mutates the player's
position), floored/capped so a trap never kills and a spring never overfills.
"""
from __future__ import annotations
from dataclasses import dataclass, field
from typing import TYPE_CHECKING
from understone.engine.models import Mode
if TYPE_CHECKING:
from understone.engine.models import Player, WorldEvent
from understone.engine.rng import GameRNG
from understone.engine.world import World
MAX_STEPS = 8
_DELTAS: dict[str, tuple[int, int]] = {
"N": (0, -1),
"S": (0, 1),
"E": (1, 0),
"W": (-1, 0),
}
_HEADINGS: dict[str, str] = {
"north": "N",
"south": "S",
"east": "E",
"west": "W",
"n": "N",
"s": "S",
"e": "E",
"w": "W",
}
@dataclass(slots=True)
class MoveEvent:
"""A non-fight overworld event already applied to the player.
``kind`` is ``gold``/``heal``/``trap``/``lore``; ``text`` is the pack's
flavour line; ``amount`` is the rolled magnitude (0 for ``lore``). The
player's hp/gold have already been mutated by ``resolve_move`` — this
record exists only so the façade can narrate what happened.
"""
kind: str
text: str
amount: int = 0
@dataclass(slots=True)
class MoveResult:
"""Outcome of a movement attempt.
``steps_taken`` counts cells actually entered. ``blocked`` is set when a
wall/edge stopped the walk. ``entered_location`` carries a location key
when the walk ended on a door. ``pending_fight`` carries an opponent
tier band when a ``fight`` encounter interrupted the walk. ``event``
carries a non-fight overworld event (already applied) when one fired.
"""
steps_taken: int
blocked: bool = False
blocked_reason: str = ""
entered_location: str | None = None
pending_fight: tuple[int, int] | None = None
event: MoveEvent | None = None
path_notes: list[str] = field(default_factory=list)
def parse_directions(steps: str, heading: str, distance: int) -> list[str]:
"""Translate either input form into a clamped list of cardinal steps.
The ``steps`` string (e.g. ``"NNEE"``) takes precedence when non-empty;
otherwise ``heading`` + ``distance`` is expanded. Either way the result
is clamped to ``MAX_STEPS``. Unknown direction characters are rejected.
"""
raw = steps.strip().upper()
if raw:
dirs: list[str] = []
for ch in raw:
if ch not in _DELTAS:
raise ValueError(f"unknown direction {ch!r} (use N/S/E/W)")
dirs.append(ch)
return dirs[:MAX_STEPS]
head = heading.strip().lower()
if not head:
return []
if head not in _HEADINGS:
raise ValueError(f"unknown heading {heading!r} (use north/south/east/west)")
count = max(0, min(distance, MAX_STEPS))
return [_HEADINGS[head]] * count
def resolve_move(
world: World,
player: Player,
rng: GameRNG,
*,
steps: str = "",
heading: str = "",
distance: int = 1,
max_steps: int = MAX_STEPS,
) -> MoveResult:
"""Walk *player* across *world* one cell at a time, mutating position.
Stops at the first blocking edge/wall, location door, or encounter.
Returns a :class:`MoveResult` describing where and why the walk ended.
"""
directions = parse_directions(steps, heading, distance)[:max_steps]
result = MoveResult(steps_taken=0)
fired = False # at most one overworld event per walk
for direction in directions:
dx, dy = _DELTAS[direction]
nx, ny = player.x + dx, player.y + dy
if not world.in_bounds(nx, ny):
result.blocked = True
result.blocked_reason = "the edge of the known world"
break
if not world.is_walkable(nx, ny):
terrain = world.terrain_at(nx, ny)
result.blocked = True
result.blocked_reason = _blocked_phrase(terrain.key)
break
player.x, player.y = nx, ny
result.steps_taken += 1
location = world.location_at(nx, ny)
if location is not None:
player.mode = Mode.MENU
player.at_location = location.key
result.entered_location = location.key
break
if fired:
continue
band = _encounter_band(world, nx, ny)
if band is None:
continue
terrain = world.terrain_at(nx, ny)
if not rng.chance(terrain.encounter_rate):
continue
fired = True
picked = _pick_event(world, rng)
if picked is None or picked.kind == "fight":
result.pending_fight = band
break
result.event = _apply_event(player, rng, picked)
return result
def _pick_event(world: World, rng: GameRNG) -> WorldEvent | None:
"""Weighted-pick one row from the world's event table, or ``None``.
Returns ``None`` only when the pack ships no event table at all, in which
case the caller falls back to the legacy always-a-fight behaviour.
"""
weights = world.event_weights()
if not weights:
return None
return world.events[rng.weighted_index(weights)]
def _apply_event(player: Player, rng: GameRNG, event: WorldEvent) -> MoveEvent:
"""Apply a non-fight event to *player* and return a record for narration.
``gold`` credits a rolled amount; ``heal`` adds hp capped at ``max_hp``;
``trap`` subtracts hp floored at 1 (a trap never kills, and never touches
gold); ``lore`` mutates nothing. Amounts roll over ``[lo, hi]``.
"""
if event.kind == "lore":
return MoveEvent(kind="lore", text=event.text)
amount = rng.randint(event.lo, event.hi)
if event.kind == "gold":
player.gold += amount
elif event.kind == "heal":
amount = min(amount, player.max_hp - player.hp)
player.hp += amount
elif event.kind == "trap":
amount = min(amount, max(player.hp - 1, 0))
player.hp -= amount
return MoveEvent(kind=event.kind, text=event.text, amount=amount)
def _encounter_band(world: World, x: int, y: int) -> tuple[int, int] | None:
"""Return the tier band for an encounter at ``(x, y)``, or ``None``.
Encounters only happen inside a zone; open terrain with no zone is safe.
"""
zone = world.zone_for(x, y)
if zone is None:
return None
return (zone.tier_lo, zone.tier_hi)
def _blocked_phrase(terrain_key: str) -> str:
"""Return an in-fiction phrase for being blocked by *terrain_key*."""
phrases = {
"water": "deep water",
"tree": "an impassable thicket",
"wall": "a sheer wall",
}
return phrases.get(terrain_key, "rough ground")
@@ -0,0 +1,42 @@
"""Leaderboard ordering.
Adventurers are ranked by level (desc), then XP (desc), then name (asc)
so ties break deterministically and alphabetically. The Hall of Legends is a
separate, append-only roll of completed runs (Wyrm kills), ordered newest
first by the store.
"""
from __future__ import annotations
from dataclasses import dataclass
@dataclass(frozen=True, slots=True)
class RankEntry:
"""One row of the leaderboard.
``wins`` is the number of times the adventurer has slain the Wyrm Below
(each shown as a beside the name); it does not affect ordering.
"""
name: str
level: int
xp: int
gold: int
wins: int = 0
@dataclass(frozen=True, slots=True)
class HallEntry:
"""One immortalised run in the Hall of Legends (a Wyrm slain)."""
name: str
win_ts: str
run_days: int
level_at_win: int
def leaderboard(entries: list[RankEntry], limit: int = 10) -> list[RankEntry]:
"""Return the top ``limit`` entries in leaderboard order."""
ordered = sorted(entries, key=lambda e: (-e.level, -e.xp, e.name))
return ordered[:limit]
@@ -0,0 +1,58 @@
"""Randomness with deterministic test injection.
A single master ``GameRNG`` is seeded once at startup (from ``os.urandom``
in production). Per-encounter child generators are derived from the master
so a fight's rolls are reproducible given the same child seed. No tool
argument ever carries a seed randomness is server-authoritative.
"""
from __future__ import annotations
import os
import random
class GameRNG:
"""A thin wrapper over ``random.Random`` with child-RNG derivation."""
def __init__(self, seed: int | None = None) -> None:
if seed is None:
seed = int.from_bytes(os.urandom(8), "big")
self._random = random.Random(seed)
def chance(self, probability: float) -> bool:
"""Return ``True`` with the given probability in ``[0.0, 1.0]``."""
if probability <= 0.0:
return False
if probability >= 1.0:
return True
return self._random.random() < probability
def randint(self, lo: int, hi: int) -> int:
"""Return a random integer in the inclusive range ``[lo, hi]``."""
return self._random.randint(lo, hi)
def choice_index(self, count: int) -> int:
"""Return a random index in ``[0, count)``."""
return self._random.randrange(count)
def weighted_index(self, weights: list[int]) -> int:
"""Return an index into ``weights`` chosen in proportion to them.
A single uniform draw is mapped through the cumulative sum, so the
result is deterministic under a fixed seed. ``weights`` must be
non-empty with a positive total (the loader guarantees this for the
content pack's event table).
"""
total = sum(weights)
roll = self._random.randrange(total)
cumulative = 0
for index, weight in enumerate(weights):
cumulative += weight
if roll < cumulative:
return index
return len(weights) - 1
def child(self) -> GameRNG:
"""Derive an independent child RNG seeded from the master stream."""
return GameRNG(self._random.getrandbits(64))
@@ -0,0 +1,62 @@
"""The satchel wire codec — the one home for the ``"id:qty"`` stack encoding.
A player's satchel is stored as a single string: comma-joined ``id:qty`` stacks,
e.g. ``"minor_potion:3,iron_ore:5"``; an empty string is an empty bag. This
module is the SINGLE source of truth for that format. Three readers carried a
byte-identical decode loop (the game façade, the Watch payload builder, and the
balance simulator); they all delegate here so the format is described and
parsed in exactly one place.
The codec is pure and stdlib-only: it knows the wire shape and nothing else.
It does NOT collapse duplicate ids into one stack, resolve ids against a content
pack, or enforce the distinct-stack cap those are stack *semantics* the
callers own. The codec only encodes and decodes.
"""
from __future__ import annotations
def decode_satchel(s: str) -> list[tuple[str, int]]:
"""Decode the ``"id:qty"`` satchel string into ordered ``(item_id, qty)`` stacks.
Splits on ``","`` and skips empty chunks (so an empty string, a leading or
trailing comma, and a doubled comma all yield no spurious stack). Each chunk
is partitioned on ``":"``:
* a chunk with no colon (a bare id) parses as quantity ``1`` a colonless
fragment is treated as a single item, never silently dropped;
* a chunk whose quantity is present but not an integer, or is ``<= 0``, is
skipped;
* a chunk with an empty id is skipped.
Order is preserved (first-stowed first), which fixes which potion a heal tie
resolves to. The codec collapses nothing callers own stack semantics.
"""
stacks: list[tuple[str, int]] = []
for chunk in s.split(","):
if not chunk:
continue
item_id, sep, qty_str = chunk.partition(":")
if not item_id:
continue
if not sep:
# A bare id with no colon is a single item (defensive: never drop it).
stacks.append((item_id, 1))
continue
try:
qty = int(qty_str)
except ValueError:
continue
if qty > 0:
stacks.append((item_id, qty))
return stacks
def encode_satchel(stacks: list[tuple[str, int]]) -> str:
"""Encode ``(item_id, qty)`` stacks back into the comma-joined ``"id:qty"`` string.
Any stack at quantity ``<= 0`` is dropped, so the encoding never emits
``"id:0"``; this is the single home for the drop-at-empty rule, letting
callers decrement freely and rely on a spent-to-zero stack falling away.
"""
return ",".join(f"{item_id}:{qty}" for item_id, qty in stacks if qty > 0)
@@ -0,0 +1,99 @@
"""The one-glyph-one-column contract for everything drawn on the grid.
Every surface Understone paints the bordered text frames, the golden frames
the screen tests pin, and the Watch's CSS ``1ch``-per-cell map — assumes each
map glyph occupies *exactly one* terminal column. A glyph that renders two
columns (a CJK ideograph, an emoji) shoves the row right and tears the
box-drawing border; a zero-width combining mark stacks onto its neighbour and
desynchronises the column count the other way. :func:`is_grid_safe` is the
single predicate that admits a character to the grid, and :data:`SAFE_PALETTE`
is the curated set of glyphs known to satisfy it with period CP437 flavour.
THE WESTERN-MONOSPACE ASSUMPTION. Width here is judged for the Western
monospace metrics every Understone surface actually uses the pinned Watch
font stack and the monospace of a chat client's code block. Under those
metrics the East-Asian-Width *Ambiguous* class renders single-column, and
Ambiguous is the CP437 heartland: `` `` are all EAW=A. So the rule
bars only the genuinely double-width classes Wide (``W``) and Fullwidth
(``F``) and admits Ambiguous, Narrow, Neutral, and Halfwidth. The trade is
deliberate: on a CJK-width terminal an Ambiguous glyph would take two columns,
but Understone's surfaces are not those terminals.
"""
from __future__ import annotations
import unicodedata
# East-Asian-Width classes that render two columns under Western monospace and
# would therefore tear a frame; everything else (Na/N/H/A) renders one column.
_DOUBLE_WIDTH_EAW = frozenset({"W", "F"})
# Unicode general categories that carry no column of their own — combining
# marks (Mn/Mc/Me) stack onto a neighbour, format/control codes (Cf/Cc) are
# invisible — so a single such code point is not a paintable cell.
_ZERO_WIDTH_CATEGORIES = frozenset({"Mn", "Mc", "Me", "Cf", "Cc"})
def is_grid_safe(ch: str) -> bool:
"""Return whether *ch* may occupy a single grid cell.
A grid-safe character is exactly one code point, is printable, is not an
East-Asian Wide or Fullwidth glyph (the only classes that render two
columns under the Western monospace metrics our surfaces use see the
module docstring), and is not a combining mark or format/control code (a
zero-width code point that would desynchronise the column count).
"""
if len(ch) != 1:
return False
if not ch.isprintable():
return False
if unicodedata.east_asian_width(ch) in _DOUBLE_WIDTH_EAW:
return False
return unicodedata.category(ch) not in _ZERO_WIDTH_CATEGORIES
# A curated set of single-column glyphs with BBS / CP437 character, grouped by
# the role an author is likely to want them for. Every entry is grid-safe AND
# free of the loader's reserved markers (two tests assert both), so a pack
# author can pull any of these for terrain, structures, or actors without
# risking a torn frame or colliding with the '@'/'☻' player markers. The black
# smiling face (☻) is the other-player marker and so is NOT here; its white
# twin (☺) is a free being glyph. The grouping is documentation; the set is
# what callers iterate.
SAFE_PALETTE: tuple[str, ...] = (
# terrain
"",
"",
"",
"",
"",
"",
"",
"",
".",
",",
"'",
'"',
"=",
"~",
"§",
"ø",
"¤",
"Ω",
# structures
"",
"",
"",
"",
"",
"$",
"",
"",
# beings
"",
"",
# misc
"",
"",
"",
)
@@ -0,0 +1,65 @@
"""Daily action budget and the UTC-day rollover.
Turns refresh lazily: the first action on a new UTC day resets the
budget rather than relying on a scheduled job. The same rollover resets
the per-player bestow pool and the social daily caps (posts left, dice
played), so every daily allowance shares one boundary. The clock is
injected so tests can cross midnight deterministically.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from collections.abc import Callable
from datetime import datetime
from understone.engine.models import Player
def _utc_ordinal(clock: Callable[[], datetime]) -> int:
"""Return today's proleptic-Gregorian ordinal in UTC."""
return clock().toordinal()
def ensure_day(player: Player, clock: Callable[[], datetime], daily_turns: int) -> bool:
"""Refresh daily allowances if the UTC day has advanced.
Returns ``True`` when a reset occurred. On a new UTC day this resets the
turn budget (to *daily_turns*), the bestow pool, the daily post count, and
the daily dice count each back to its baseline stamping the current UTC
ordinal onto every day marker. Each counter is reset independently so a
stale stamp on one never suppresses the refresh of another.
"""
today = _utc_ordinal(clock)
reset = False
if player.turn_day != today:
player.turns_left = daily_turns
player.turn_day = today
reset = True
if player.bestow_day != today:
player.bestow_spent = 0
player.bestow_day = today
reset = True
if player.post_day != today:
player.posts_sent = 0
player.post_day = today
reset = True
if player.gamble_day != today:
player.gambles = 0
player.gamble_day = today
reset = True
return reset
def spend_turn(player: Player) -> bool:
"""Consume one daily turn.
Returns ``True`` and decrements when a turn is available; returns
``False`` and leaves state untouched when the budget is exhausted.
"""
if player.turns_left <= 0:
return False
player.turns_left -= 1
return True
@@ -0,0 +1,117 @@
"""Runtime world model — terrain, locations, zones, content tables, settings.
Built by ``world.loader`` from JSON. The engine queries this for
walkability, encounter rates, location lookups, and tier-banded monster
selection. It holds no mutable game state.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from understone.engine.models import (
Item,
LocationDef,
Monster,
Settings,
TerrainDef,
WorldEvent,
Zone,
)
class World:
"""An immutable-after-construction view of the game map and content."""
def __init__(
self,
*,
name: str,
width: int,
height: int,
spawn: tuple[int, int],
terrain: list[list[TerrainDef]],
locations: list[LocationDef],
zones: list[Zone],
monsters: list[Monster],
items: list[Item],
settings: Settings,
events: list[WorldEvent] | None = None,
) -> None:
self.name = name
self.width = width
self.height = height
self.spawn = spawn
self.terrain = terrain
self.locations = locations
self.zones = zones
self.monsters = monsters
self.items = items
self.settings = settings
self.events: list[WorldEvent] = events or []
self._event_weights: list[int] = [e.weight for e in self.events]
self._loc_by_xy: dict[tuple[int, int], LocationDef] = {
(loc.x, loc.y): loc for loc in locations
}
self._loc_by_key: dict[str, LocationDef] = {loc.key: loc for loc in locations}
self._item_by_id: dict[str, Item] = {it.item_id: it for it in items}
self._monster_by_id: dict[str, Monster] = {
m.monster_id: m for m in monsters if m.monster_id
}
def in_bounds(self, x: int, y: int) -> bool:
"""Return whether ``(x, y)`` is inside the map rectangle."""
return 0 <= x < self.width and 0 <= y < self.height
def terrain_at(self, x: int, y: int) -> TerrainDef:
"""Return the terrain definition at ``(x, y)`` (caller bounds-checks)."""
return self.terrain[y][x]
def location_at(self, x: int, y: int) -> LocationDef | None:
"""Return the location placed at ``(x, y)``, if any."""
return self._loc_by_xy.get((x, y))
def location_by_key(self, key: str) -> LocationDef | None:
"""Return the location with the given key, if any."""
return self._loc_by_key.get(key)
def item_by_id(self, item_id: str) -> Item | None:
"""Return the item with the given id, if any."""
return self._item_by_id.get(item_id)
def monster_by_id(self, monster_id: str) -> Monster | None:
"""Return the monster with the given id, if any (boss lookup)."""
return self._monster_by_id.get(monster_id)
def event_weights(self) -> list[int]:
"""Return the parallel weight list for the overworld event table."""
return self._event_weights
def is_walkable(self, x: int, y: int) -> bool:
"""Return whether a player may stand on ``(x, y)``.
Out-of-bounds is never walkable. A location tile is always walkable
regardless of its underlying terrain (you can step onto the door).
"""
if not self.in_bounds(x, y):
return False
if (x, y) in self._loc_by_xy:
return True
return self.terrain[y][x].walkable
def zone_for(self, x: int, y: int) -> Zone | None:
"""Return the first zone whose rectangle contains ``(x, y)``."""
for zone in self.zones:
if zone.contains(x, y):
return zone
return None
def monsters_for_tier_band(self, lo: int, hi: int) -> list[Monster]:
"""Return non-boss monsters whose tier falls within ``[lo, hi]``.
Boss monsters (the Wyrm Below) are never returned: they are the fixed
endgame foe, faced only through the deliberate ``challenge`` verb, and
must never surface as a random encounter or a dungeon-gauntlet rung.
"""
return [m for m in self.monsters if lo <= m.tier <= hi and not m.boss]
+24
View File
@@ -0,0 +1,24 @@
"""Shared exception types for Understone.
These never cross the MCP boundary the server layer catches everything
and renders an in-fiction line but they let internal layers fail with a
readable, specific message.
"""
from __future__ import annotations
class UnderstoneError(Exception):
"""Base class for all Understone errors."""
class WorldLoadError(UnderstoneError):
"""Raised when a content pack fails to parse or validate.
The message is written to be readable by a pack author: it names the
file, the offending field, and what was expected.
"""
class PersistenceError(UnderstoneError):
"""Raised when the save store cannot be opened or migrated."""
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,391 @@
"""SQLite persistence — the only storage layer, ``sqlite3`` only.
A single connection is held for the process lifetime. MCP tool handlers are
synchronous and run on one event-loop thread, so writes serialise naturally
and no connection pool or lock is needed [VERIFIED: handlers are sync def].
WAL journaling is enabled so reads never block the single writer.
The store loads all players and recent events into memory at construction
(a write-through cache). State-changing tools update the cache and the DB in
one transaction; the game façade owns the per-action commit policy.
The connection is opened with ``check_same_thread=False`` because the Store
may be CONSTRUCTED on a different thread than the event-loop thread that later
serves tools (both the test fixture and ``main`` do this). Post-construction
access is single-threaded: sync tools run inline on the loop [verified against
mcp 1.27 func_metadata], so writes still serialise without a lock.
"""
from __future__ import annotations
import sqlite3
from typing import TYPE_CHECKING
from understone.engine.log import Event
from understone.engine.models import Mode, Player
from understone.engine.rank import HallEntry, RankEntry
if TYPE_CHECKING:
from pathlib import Path
# Pre-1.0 the schema mutates in place and the stamp is not yet meaningful;
# version discipline (and migrations) begins at 1.0.
_SCHEMA_VERSION = 1
# How many of the newest events to hydrate at construction. Full history stays
# in SQLite; this bounds the in-memory tail. Single source of truth — game.py
# imports it for the runtime trim, so the load size and the trim size cannot
# diverge. An ops knob (memory ceiling), never an economy value.
EVENT_TAIL_KEEP = 500
_PLAYER_COLUMNS = (
"name",
"x",
"y",
"hp",
"max_hp",
"level",
"xp",
"gold",
"atk",
"def_",
"weapon_id",
"armor_id",
"turns_left",
"turn_day",
"mode",
"at_location",
"created_at",
"last_seen",
"log_cursor",
"bestow_spent",
"bestow_day",
"wins",
"posts_sent",
"post_day",
"gambles",
"gamble_day",
"deepest_rung",
"satchel",
"weapon_plus",
"armor_plus",
"banked",
)
class Store:
"""A write-through SQLite store for players and the shared event log."""
def __init__(self, db_path: str | Path) -> None:
self._conn = sqlite3.connect(str(db_path), check_same_thread=False)
self._conn.row_factory = sqlite3.Row
self._conn.execute("PRAGMA journal_mode=WAL")
self._conn.execute("PRAGMA foreign_keys=ON")
self._init_schema()
# -- schema ----------------------------------------------------------
def _init_schema(self) -> None:
self._conn.executescript(
"""
CREATE TABLE IF NOT EXISTS players (
name TEXT PRIMARY KEY,
x INTEGER NOT NULL,
y INTEGER NOT NULL,
hp INTEGER NOT NULL,
max_hp INTEGER NOT NULL,
level INTEGER NOT NULL,
xp INTEGER NOT NULL,
gold INTEGER NOT NULL,
atk INTEGER NOT NULL,
def_ INTEGER NOT NULL,
weapon_id TEXT NOT NULL,
armor_id TEXT NOT NULL,
turns_left INTEGER NOT NULL,
turn_day INTEGER NOT NULL,
mode TEXT NOT NULL,
at_location TEXT NOT NULL,
created_at TEXT NOT NULL,
last_seen TEXT NOT NULL,
log_cursor INTEGER NOT NULL,
bestow_spent INTEGER NOT NULL,
bestow_day INTEGER NOT NULL,
wins INTEGER NOT NULL DEFAULT 0,
posts_sent INTEGER NOT NULL DEFAULT 0,
post_day INTEGER NOT NULL DEFAULT 0,
gambles INTEGER NOT NULL DEFAULT 0,
gamble_day INTEGER NOT NULL DEFAULT 0,
deepest_rung INTEGER NOT NULL DEFAULT 0,
satchel TEXT NOT NULL DEFAULT '',
weapon_plus INTEGER NOT NULL DEFAULT 0,
armor_plus INTEGER NOT NULL DEFAULT 0,
banked INTEGER NOT NULL DEFAULT 0
);
CREATE TABLE IF NOT EXISTS events (
id INTEGER PRIMARY KEY AUTOINCREMENT,
ts TEXT NOT NULL,
actor TEXT NOT NULL,
kind TEXT NOT NULL,
text TEXT NOT NULL,
target TEXT NOT NULL DEFAULT ''
);
CREATE TABLE IF NOT EXISTS ambushes (
attacker TEXT NOT NULL,
target TEXT NOT NULL,
day INTEGER NOT NULL,
PRIMARY KEY (attacker, target, day)
);
CREATE TABLE IF NOT EXISTS hall_of_fame (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
win_ts TEXT NOT NULL,
run_days INTEGER NOT NULL,
level_at_win INTEGER NOT NULL
);
CREATE TABLE IF NOT EXISTS meta (
key TEXT PRIMARY KEY,
value TEXT NOT NULL
);
"""
)
self._conn.execute(
"INSERT OR IGNORE INTO meta(key, value) VALUES('schema_version', ?)",
(str(_SCHEMA_VERSION),),
)
self._conn.commit()
def set_meta(self, key: str, value: str) -> None:
"""Upsert a meta key (e.g. ``world_name``) and commit."""
self._conn.execute(
"INSERT INTO meta(key, value) VALUES(?, ?) "
"ON CONFLICT(key) DO UPDATE SET value=excluded.value",
(key, value),
)
self._conn.commit()
def get_meta(self, key: str) -> str | None:
"""Return a meta value, or ``None`` if unset."""
row = self._conn.execute("SELECT value FROM meta WHERE key=?", (key,)).fetchone()
return None if row is None else str(row["value"])
# -- load ------------------------------------------------------------
def load_all(self) -> tuple[dict[str, Player], list[Event]]:
"""Load every player and the most recent events into memory.
Only the newest ``EVENT_TAIL_KEEP`` events are resident; the full history
remains in SQLite. The tail is fetched newest-first then reversed so
the returned list stays ascending by id (the order ``since`` expects).
"""
players = {
row["name"]: _row_to_player(row) for row in self._conn.execute("SELECT * FROM players")
}
rows = self._conn.execute(
"SELECT * FROM events ORDER BY id DESC LIMIT ?", (EVENT_TAIL_KEEP,)
).fetchall()
events = [_row_to_event(row) for row in reversed(rows)]
return players, events
# -- writes (no commit here; the façade commits per action) ----------
def upsert_player(self, player: Player) -> None:
"""Insert or update a player row (no commit)."""
placeholders = ", ".join("?" for _ in _PLAYER_COLUMNS)
assignments = ", ".join(f"{col}=excluded.{col}" for col in _PLAYER_COLUMNS if col != "name")
self._conn.execute(
f"INSERT INTO players ({', '.join(_PLAYER_COLUMNS)}) VALUES ({placeholders}) "
f"ON CONFLICT(name) DO UPDATE SET {assignments}",
_player_to_row(player),
)
def insert_event(self, ts: str, actor: str, kind: str, text: str, target: str = "") -> int:
"""Append an event row (no commit) and return its new id.
``target`` is empty for a public event or a player name for a private
note that only that player reads in their own catch-up.
"""
cur = self._conn.execute(
"INSERT INTO events(ts, actor, kind, text, target) VALUES(?, ?, ?, ?, ?)",
(ts, actor, kind, text, target),
)
return int(cur.lastrowid or 0)
def insert_hall_row(self, name: str, win_ts: str, run_days: int, level_at_win: int) -> int:
"""Append a Hall of Legends row (no commit) and return its new id."""
cur = self._conn.execute(
"INSERT INTO hall_of_fame(name, win_ts, run_days, level_at_win) VALUES(?, ?, ?, ?)",
(name, win_ts, run_days, level_at_win),
)
return int(cur.lastrowid or 0)
def record_ambush(self, attacker: str, target: str, day: int) -> None:
"""Mark that *attacker* has spent their ambush on *target* for *day*.
Idempotent: the ``(attacker, target, day)`` primary key means a repeat
write is ignored, so re-recording the same attempt is harmless. No
commit the façade folds this into the per-action transaction.
"""
self._conn.execute(
"INSERT OR IGNORE INTO ambushes(attacker, target, day) VALUES(?, ?, ?)",
(attacker, target, day),
)
def has_ambushed(self, attacker: str, target: str, day: int) -> bool:
"""Return whether *attacker* already ambushed *target* on *day*."""
row = self._conn.execute(
"SELECT 1 FROM ambushes WHERE attacker=? AND target=? AND day=?",
(attacker, target, day),
).fetchone()
return row is not None
def commit(self) -> None:
"""Commit the current transaction."""
self._conn.commit()
# -- read-only queries ----------------------------------------------
def top_ranks(self, limit: int = 10) -> list[RankEntry]:
"""Return the leaderboard ordered by level, xp, then name."""
rows = self._conn.execute(
"SELECT name, level, xp, gold, wins FROM players "
"ORDER BY level DESC, xp DESC, name ASC LIMIT ?",
(limit,),
)
return [
RankEntry(
name=row["name"],
level=row["level"],
xp=row["xp"],
gold=row["gold"],
wins=row["wins"],
)
for row in rows
]
def top_hall(self, limit: int = 5) -> list[HallEntry]:
"""Return the most recent Hall of Legends rows, newest first."""
rows = self._conn.execute(
"SELECT name, win_ts, run_days, level_at_win FROM hall_of_fame "
"ORDER BY id DESC LIMIT ?",
(limit,),
)
return [
HallEntry(
name=row["name"],
win_ts=row["win_ts"],
run_days=row["run_days"],
level_at_win=row["level_at_win"],
)
for row in rows
]
def targeted_events_since(self, viewer: str, cursor: int) -> list[Event]:
"""Return *viewer*'s private notes past *cursor*, ascending by id.
Public history older than the resident tail is ephemeral by design (the
broadsheet does not keep), but private mail is durable: a note left while
the recipient was away must survive however many public events have since
pushed it out of the in-memory tail. The façade pulls the recipient's
targeted rows from SQLite to backfill that gap before rendering.
"""
rows = self._conn.execute(
"SELECT * FROM events WHERE target=? AND id>? ORDER BY id",
(viewer, cursor),
).fetchall()
return [_row_to_event(row) for row in rows]
def journal_mode(self) -> str:
"""Return the active journal mode (for diagnostics / tests)."""
row = self._conn.execute("PRAGMA journal_mode").fetchone()
return str(row[0])
def close(self) -> None:
"""Close the underlying connection."""
self._conn.close()
def _player_to_row(player: Player) -> tuple[object, ...]:
return (
player.name,
player.x,
player.y,
player.hp,
player.max_hp,
player.level,
player.xp,
player.gold,
player.atk,
player.def_,
player.weapon_id,
player.armor_id,
player.turns_left,
player.turn_day,
str(player.mode),
player.at_location,
player.created_at,
player.last_seen,
player.log_cursor,
player.bestow_spent,
player.bestow_day,
player.wins,
player.posts_sent,
player.post_day,
player.gambles,
player.gamble_day,
player.deepest_rung,
player.satchel,
player.weapon_plus,
player.armor_plus,
player.banked,
)
def _row_to_player(row: sqlite3.Row) -> Player:
return Player(
name=row["name"],
x=row["x"],
y=row["y"],
hp=row["hp"],
max_hp=row["max_hp"],
level=row["level"],
xp=row["xp"],
gold=row["gold"],
atk=row["atk"],
def_=row["def_"],
weapon_id=row["weapon_id"],
armor_id=row["armor_id"],
turns_left=row["turns_left"],
turn_day=row["turn_day"],
mode=Mode(row["mode"]),
at_location=row["at_location"],
created_at=row["created_at"],
last_seen=row["last_seen"],
log_cursor=row["log_cursor"],
bestow_spent=row["bestow_spent"],
bestow_day=row["bestow_day"],
wins=row["wins"],
posts_sent=row["posts_sent"],
post_day=row["post_day"],
gambles=row["gambles"],
gamble_day=row["gamble_day"],
deepest_rung=row["deepest_rung"],
satchel=row["satchel"],
weapon_plus=row["weapon_plus"],
armor_plus=row["armor_plus"],
banked=row["banked"],
)
def _row_to_event(row: sqlite3.Row) -> Event:
return Event(
event_id=row["id"],
ts=row["ts"],
kind=row["kind"],
actor=row["actor"],
text=row["text"],
target=row["target"],
)
@@ -0,0 +1,5 @@
"""Screen layer — pure rendering of game state into text frames.
No ANSI SGR escape sequences are emitted in v1; colour is carried as
metadata on cells for a future renderer but never written to output.
"""
@@ -0,0 +1,35 @@
"""Shared box-drawing glyphs and the title-in-border helper.
The frame renderer and the menu renderer both draw a single box with a
centred title in the top border. The glyph set and that border logic live
here so the two renderers cannot drift apart.
"""
from __future__ import annotations
TL = "" # top-left corner
TR = "" # top-right corner
BL = "" # bottom-left corner
BR = "" # bottom-right corner
H = "" # horizontal run
V = "" # vertical edge
def border_with_title(inner: int, title: str) -> str:
"""Build the top border ``┌──title──┐`` with the title centred in the run.
*inner* is the interior width (between the corners). The title is wrapped
in single spaces and centred; if it does not fit the run it is truncated.
An empty/blank title yields a plain horizontal run.
"""
label = title.strip()
if not label:
return TL + (H * inner) + TR
framed = f" {label} "
if len(framed) > inner:
framed = framed[:inner]
pad = inner - len(framed)
left = pad // 2
right = pad - left
middle = (H * left) + framed + (H * right)
return TL + middle + TR
@@ -0,0 +1,61 @@
"""A 2-D grid of single-glyph cells.
The grid is the renderer's input surface: callers paint terrain and actors
into cells, then hand the grid to ``text_renderer`` for framing.
"""
from __future__ import annotations
from dataclasses import dataclass
from understone.screen.palette import Color
@dataclass(frozen=True, slots=True)
class Cell:
"""A single rendered position: exactly one glyph plus a colour role."""
glyph: str
color: Color
def __post_init__(self) -> None:
if len(self.glyph) != 1:
raise ValueError(f"cell glyph must be exactly one character, got {self.glyph!r}")
_BLANK = Cell(" ", Color.DEFAULT)
class CellGrid:
"""A mutable ``rows`` x ``cols`` grid of cells."""
def __init__(self, rows: int, cols: int) -> None:
if rows <= 0 or cols <= 0:
raise ValueError(f"grid must be positive, got {rows}x{cols}")
self.rows = rows
self.cols = cols
self._cells: list[list[Cell]] = [[_BLANK for _ in range(cols)] for _ in range(rows)]
def blank(self) -> None:
"""Reset every cell to the blank cell."""
for r in range(self.rows):
for c in range(self.cols):
self._cells[r][c] = _BLANK
def set(self, r: int, c: int, cell: Cell) -> None:
"""Paint *cell* at row *r*, column *c* (bounds-checked)."""
if not (0 <= r < self.rows and 0 <= c < self.cols):
raise IndexError(f"cell ({r},{c}) out of bounds for {self.rows}x{self.cols}")
self._cells[r][c] = cell
def get(self, r: int, c: int) -> Cell:
"""Return the cell at row *r*, column *c* (bounds-checked)."""
if not (0 <= r < self.rows and 0 <= c < self.cols):
raise IndexError(f"cell ({r},{c}) out of bounds for {self.rows}x{self.cols}")
return self._cells[r][c]
def row_glyphs(self, r: int) -> str:
"""Return row *r* as a string of its glyphs."""
if not (0 <= r < self.rows):
raise IndexError(f"row {r} out of bounds for {self.rows} rows")
return "".join(cell.glyph for cell in self._cells[r])
@@ -0,0 +1,47 @@
"""Classic door-game menu rendering for location interiors.
A menu is a boxed title, a block of flavour/body lines, an option line of
the ``(B)uy (S)ell (L)eave`` form, and a footer status line.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from understone.screen.box import BL, BR, H, V, border_with_title
if TYPE_CHECKING:
from collections.abc import Sequence
def render_menu(
title: str,
lines: Sequence[str],
options: Sequence[str],
status: str,
) -> str:
"""Render a boxed location menu.
*title* is centred in the top border, *lines* form the body (each
left-padded inside the box), *options* are joined with two spaces into
an option line, and *status* prints under the box.
"""
body = list(lines)
option_line = " ".join(options)
if option_line:
body.append("")
body.append(option_line)
inner = _inner_width(title, body)
out = [border_with_title(inner, title)]
for line in body:
out.append(V + " " + line.ljust(inner - 1) + V)
out.append(BL + (H * inner) + BR)
out.append(status)
return "\n".join(out)
def _inner_width(title: str, body: Sequence[str]) -> int:
"""Choose an inner width that fits the title and the widest body line."""
title_need = len(title.strip()) + 4
body_need = max((len(line) + 2 for line in body), default=0)
return max(title_need, body_need, 24)
@@ -0,0 +1,65 @@
"""Colour vocabulary for cells.
Colours are *stored* on cells and rendered by the live Watch page, which maps
each role to a hue (see ``watch.PALETTE``). The text frame renderer stays
monochrome it emits glyphs only so a cell's colour rides the grid model
untouched until a colour-aware renderer (the Watch today, an ANSI terminal
later) reads it.
"""
from __future__ import annotations
from enum import Enum
class Color(Enum):
"""Semantic colour roles for grid cells.
One global vocabulary, shared by every world there are no per-world or
per-theme palettes. Roles are split into two families: the runtime overlay
colours an actor or item wears (``PLAYER``/``OTHER_PLAYER``/``MONSTER``/
``ITEM``) and the author-assignable terrain/location roles a pack paints its
map with (everything else). A future colour renderer maps each role to a
hue; the Watch already does (see ``watch.PALETTE``).
"""
DEFAULT = "default"
WALL = "wall"
FLOOR = "floor"
PLAYER = "player"
OTHER_PLAYER = "other_player"
MONSTER = "monster"
ITEM = "item"
WATER = "water"
TREE = "tree"
TOWN = "town"
DUNGEON = "dungeon"
# Expanded terrain/location roles (v0.9) — so distinct types read by hue and
# not only by glyph. ROAD splits paths off FLOOR; FOREST is lush dense
# vegetation; SCRUB is its barren counterpart — rough, non-lush dense terrain
# (volcanic cinder, desert scrub) that must NOT read as green woods; LAVA
# gives molten ground its own orange (no longer mis-sharing WATER's blue);
# BARREN gives open wasteland ground a taupe; INN/SHOP/HEALER give each town
# building its own hue (TOWN stays as a generic fallback).
ROAD = "road"
FOREST = "forest"
SCRUB = "scrub"
LAVA = "lava"
BARREN = "barren"
INN = "inn"
SHOP = "shop"
HEALER = "healer"
@classmethod
def assignable(cls) -> list[Color]:
"""The roles a pack may paint terrain or a location with.
One source of truth for the overlay-vs-assignable split. Excludes the
runtime overlay colours an actor/item wears (``PLAYER``/
``OTHER_PLAYER``/``MONSTER``/``ITEM``) and the ``DEFAULT`` fallback
none of which an author assigns. Consumers (the authoring manual and
its test) read this so the documented vocabulary can never drift from
the enum. Returned in definition order.
"""
overlay = {cls.DEFAULT, cls.PLAYER, cls.OTHER_PLAYER, cls.MONSTER, cls.ITEM}
return [role for role in cls if role not in overlay]
@@ -0,0 +1,32 @@
"""Frame rendering — wrap a grid in a single box border with a title and status.
Deterministic and glyph-only (no ANSI). The title is centred within the
top border run; the status line is printed under the closed box.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from understone.screen.box import BL, BR, H, V, border_with_title
if TYPE_CHECKING:
from understone.screen.grid import CellGrid
def render_frame(grid: CellGrid, *, title: str, status: str) -> str:
"""Render *grid* inside a box, with *title* in the top border and *status* below.
The inner width equals the grid's column count. The title is centred
in the horizontal run of the top border; if it does not fit it is
truncated to the available run.
"""
inner = grid.cols
top = border_with_title(inner, title)
bottom = BL + (H * inner) + BR
lines = [top]
for r in range(grid.rows):
lines.append(V + grid.row_glyphs(r) + V)
lines.append(bottom)
lines.append(status)
return "\n".join(lines)
@@ -0,0 +1,54 @@
"""Deterministic terrain texturing — vary a terrain glyph by map position.
A field of identical `.`s reads flat; swapping in an occasional `,` or `'`
gives the overworld a hand-stippled BBS texture without storing anything on the
map. The variation is a PURE FUNCTION OF THE CELL COORDINATE, so it is stable
across redraws (a cell always picks the same variant) and reproducible the
model never sees it, only the renderer.
Only *terrain* cells are textured. The player marker, the other-player marker,
and location glyphs are painted on top and are never varied, so the eye can
always find them.
LOCKSTEP CONTRACT. The Watch page (``understone.watch.WATCH_HTML``) paints its
own base map in JavaScript and reproduces the EXACT same selection the same
``VARIANTS`` rows and the same ``(x * _HASH_X + y * _HASH_Y) % n`` index. The
page builds that index string FROM the :data:`_HASH_X` / :data:`_HASH_Y`
constants here (``understone.watch`` imports them), so a retune of either
number moves the JS with it; only the ``VARIANTS`` table must still be mirrored
by hand, or the live map and the tool frames will drift apart.
"""
from __future__ import annotations
# The position hash multipliers. The variant index for a cell is
# ``(x * _HASH_X + y * _HASH_Y) % len`` — two odd, coprime constants chosen so
# neighbouring cells spread across the variant row rather than banding. The
# Watch JS builds its own copy of this formula FROM these same two numbers
# (``understone.watch`` imports them), so a retune here moves the page in
# lockstep; a guard test pins the agreement.
_HASH_X = 31
_HASH_Y = 17
# Base glyph -> the ordered string of glyphs it may render as. The base glyph
# is index 0, so a cell that hashes to 0 is unchanged. Glyphs not listed here
# are never varied. Keep in lockstep with the Watch JS VARIANTS map.
VARIANTS: dict[str, str] = {
".": ".,'",
"": "≋≈",
}
def textured(glyph: str, x: int, y: int) -> str:
"""Return the variant of *glyph* for cell ``(x, y)``, or *glyph* unchanged.
When *glyph* has a :data:`VARIANTS` row, the cell coordinate selects one of
its variants by ``(x * _HASH_X + y * _HASH_Y) % len`` a fixed,
position-only hash so the choice is stable per cell and identical to the
Watch's. Glyphs with no row (every actor and location glyph, and any
un-listed terrain) are returned as-is.
"""
choices = VARIANTS.get(glyph)
if choices is None:
return glyph
return choices[(x * _HASH_X + y * _HASH_Y) % len(choices)]
@@ -0,0 +1,40 @@
"""Viewport window maths — pure integer arithmetic, no state.
Computes the top-left corner of a view window over a larger map, centred
on a focus point but clamped to map edges so the window never wraps and
never runs off the map. At edges the focus point sits off-centre.
"""
from __future__ import annotations
def compute_window(
map_w: int,
map_h: int,
view_w: int,
view_h: int,
cx: int,
cy: int,
) -> tuple[int, int]:
"""Return ``(x0, y0)`` top-left map coords for a view centred on ``(cx, cy)``.
The window is clamped so ``[x0, x0 + view_w)`` stays within
``[0, map_w)`` (and likewise for the vertical axis). When the map is
smaller than the view the origin pins to ``0``.
"""
x0 = _clamp_axis(map_w, view_w, cx)
y0 = _clamp_axis(map_h, view_h, cy)
return x0, y0
def _clamp_axis(map_size: int, view_size: int, center: int) -> int:
"""Clamp one axis: centre on ``center`` then pull inside the map edges."""
if view_size >= map_size:
return 0
origin = center - view_size // 2
max_origin = map_size - view_size
if origin < 0:
return 0
if origin > max_origin:
return max_origin
return origin
+648
View File
@@ -0,0 +1,648 @@
"""MCP server for Understone — the only module that imports ``mcp`` (or ``starlette``).
Nine ``door_*`` tools form the entire player interface. Every handler is a
synchronous ``def`` that takes and returns ``str``; no exception is allowed
to cross the MCP boundary (each handler catches, logs server-side, and
returns an in-fiction line). The handlers are thin wrappers over a single
module-level :class:`~understone.game.Game`; all rules live behind that
façade.
Three extra HTTP routes (``/watch`` and its two JSON feeds) serve the
read-only spectator page from :mod:`understone.watch`. They are registered via
FastMCP's ``custom_route`` and ride inside the streamable-http app; the
``starlette`` request/response types appear ONLY here, mirroring the MCP SDK's
own ``custom_route`` examples. The routes are unauthenticated by design and
strictly read-only they never mutate or persist world state.
Usage::
understone # via entry point (stdio transport)
python -m understone # via module
understone validate PATH # check a content pack loads cleanly
understone newpack PATH # scaffold a new pack + authoring manual
understone worlds # list the bundled worlds and their soundness
Environment variables
---------------------
UNDERSTONE_DB SQLite path (default: ./understone.db)
UNDERSTONE_WORLD Content-pack directory (default: packaged world/data)
UNDERSTONE_TRANSPORT "stdio" (default) or "streamable-http"
UNDERSTONE_HOST Bind host for http transport (default: 127.0.0.1)
UNDERSTONE_PORT Bind port for http transport (default: 8077)
UNDERSTONE_PATH HTTP path for the MCP endpoint (default: /mcp)
"""
from __future__ import annotations
import argparse
import logging
import os
from pathlib import Path
from typing import TYPE_CHECKING
from mcp.server.fastmcp import FastMCP
from mcp.server.transport_security import TransportSecuritySettings
from starlette.responses import HTMLResponse, JSONResponse, Response
from understone import cli, sim, watch
from understone.errors import WorldLoadError
from understone.game import Game
from understone.persistence import Store
from understone.world import PACKAGED_WORLD_DIR
from understone.world.loader import load_world
if TYPE_CHECKING:
from starlette.applications import Starlette
from starlette.requests import Request
log = logging.getLogger(__name__)
_PREMISE = (
"Understone is a shared-world BBS door game played through these tools. "
"Call door_help first to learn how to narrate it."
)
# The DM manual returned by door_help — a module constant so it is stable and
# greppable. It teaches an assistant how to run the game responsibly.
_DM_MANUAL = """\
UNDERSTONE A GUIDE FOR THE GAME MASTER
WHAT THIS IS
Understone is a multiplayer, BBS-style ANSI door game a small text RPG in
the lineage of the classic BBS door games. Many players share ONE
persistent world hosted by this server. You are the storyteller at the
terminal; the server is the rules engine and the single source of truth.
THE GOLDEN RULE
The server is authoritative. Never invent dice rolls, loot, gold, hit
points, map tiles, or outcomes. Every number and event comes back from a
tool call. Narrate AROUND the facts the tools return never ahead of them.
If you want something to happen, call the tool and see what the world says.
THE TWO MODES OF PLAY
1. The overworld (TILE mode). Tools return an ASCII "keyframe": a bordered
map window centred on the player. '@' is the player, '' is another
adventurer, glyphs are buildings ( inn, $ shop, healer, dungeon).
Movement here is FREE it costs no daily turns.
2. Location interiors (MENU mode). Stepping onto a building opens a menu of
options like (R)est, (B)uy, (H)eal, (D)escend, (L)eave.
PRESENTING FRAMES
When a tool returns a map or a menu, show it to the player VERBATIM inside a
fenced code block so the box-drawing lines stay aligned. Then add your prose
underneath. Do not redraw or paraphrase the frame.
NARRATION
Be vivid and in-fiction. Turn the terse result lines ("You travel 3 steps.",
"+8 XP, +3 gold.") into atmosphere. Keep your additions consistent with the
returned facts and the high-fantasy tone of the Vale of Understone.
THE DAILY RHYTHM
Each adventurer has a small budget of turns per real-world UTC day. Only
fighting, descending, and challenging the Wyrm spend a turn; moving,
resting, shopping and looking do not. When the budget is gone, the day is
done encourage the player to return tomorrow. This is a correspondence
game: a little each day.
WANDERING THE FOREST (the texture of a walk)
A step through wild country may turn up more than a monster. The server
rolls a private encounter table as the player walks: most often a foe (which
stops the walk for a fight or flight), but sometimes a purse of gold, a
healing spring, a small trap (it can never kill it floors at 1 HP), or a
scrap of Vale lore. The non-combat finds are applied at once, narrated in
the move result, and do NOT stop the walk; at most one such event happens
per move. These finds are PRIVATE they are not Herald news so narrate
them as the quiet texture of travelling, and watch the lore: it whispers of
something coiled beneath the dungeon.
DELVING DEEP (the reasons to come back)
Beneath the daily reset are four standing draws that reward a returning hero.
* THE RUNG LADDER. The dungeon is a ladder of guardians fought one rung per
'descend' (each costs a daily turn). A descent faces the NEXT rung past your
deepest; a win advances your depth and you climb back out, a loss bounces
you home but your depth PERSISTS you re-enter where you left off. Reaching
the last rung opens the Wyrm's door (the depth gate above). Narrate the deep
as a slow, earned descent, a rung at a time.
* THE SATCHEL AND THE DEATH-SAVE. A small satchel carries a few potions
(buying one at the shop now STOWS it instead of drinking it). 'quaff'
(anywhere, no turn) drinks the strongest. The heart of it: if a fight would
KILL the active fighter and they carry a potion, the strongest is drunk
AUTOMATICALLY they survive standing at the potion's value, no bounce, no
spawn reset. Play that beat big: the elixir burning down their throat at the
edge of death. (A sleeping ambush victim never auto-quaffs they are
asleep.)
* THE FORGE GOLD AND ORE. The shop's forge adds a +1 edge to the equipped
weapon or armour ('forge' target="weapon"/"armour"), up to a cap, each tier
dearer than the last. A step costs gold AND forge ore a material the hero
EARNS in combat, never buys: every cleared dungeon rung drops some, and a won
forest fight sometimes turns up a little. So the forge is fed by descending,
not just by a fat purse; a hero short of ore is told so. Swapping or selling
a forged piece loses the edge with it.
* RARE BEASTS. A few named beasts prowl the forest, surfacing seldom. Felling
one is loud a public Herald flash and it always guards a draught that
drops into the satchel (if there is room). Treat a rare kill as a small
legend in itself.
THE WYRM BELOW (the endgame, and how to win)
Deep under the dungeon sleeps the Wyrm Below a fixed, fearsome boss and
the ONLY win condition. At the dungeon, a sufficiently seasoned hero may
'challenge' it (door_action action="challenge"). The Wyrm gates on BOTH
level AND depth: an under-level hero is turned away first, and even a high
hero who has not plumbed the deep to its floor (see DELVING DEEP) is told the
Wyrm will not stir. Once both are met, the challenge spends a daily turn and
resolves in one call, like a fight.
* On victory the hero FREES THE VALE. The triumph is heralded to everyone,
the run is carved into the Hall of Legends (shown by door_rank), and the
hero is reborn in a classic-door-game-style legacy reset: level, gold, gear and stats
return to first-day values and they stand again at the town but they
keep a permanent for the win, and may set out to do it all again. Their
remaining turns for the day and their place in the world carry over.
* On defeat the Wyrm devours them; they wake at the spawn, barely alive.
Play this beat big: it is the climax of a whole run. Narrate the reset as the
Vale renewing itself around an undying legend, not as a death.
BESTOWING FORTUNE (use sparingly)
door_bestow lets you, the storyteller, grant a little gold or healing to
mark a great story moment a heroic rescue, a clever solution, a poignant
death-defiance. It NEVER grants items (gear comes from the shop) and NEVER
grants turns (the clock does not bend). It is capped by a small daily pool
per player, and every bestowal is written to the public log for all to see.
Treat it as seasoning, not a salt-shaker: reserve it for the rare, earned
beat, and never promise a reward you cannot actually deliver within the cap.
THE SOCIAL LAYER (rivals, mail, and dice)
Understone is a SHARED world, and three verbs let players touch one another.
* AMBUSH (door_action action="ambush" target=<player>, on the overworld).
A classic-door-game-style player-kill: you fall upon a RIVAL WHO HAS NOT YET ACTED
TODAY and rob them. The SLEEP RULE is the heart of it a player who has
already taken their turn that day is awake and cannot be ambushed, so the
surest defence is simply to play. The gatekeeper shields the young (both of
you must clear a level floor) and only matches near-equals (a level band).
On a win you take a slice of their gold and they wake at the spawn at 1 HP;
a public Herald crows the deed and the victim gets a PRIVATE note. But the
sleeper may WAKE: lose, and YOU are the one who flees bleeding, shamed on
the feed and gaining nothing. You get one attempt per rival per day, win or
lose. Narrate ambush as a real betrayal and losing one as just deserts.
* POST (door_action action="post" target=<player> text=<message>, anywhere).
Leave a private note at the inn for another player; they read it on their
next door_log under "While you were away". It costs no turn, is capped per
day, and the note is PRIVATE it never reaches the public Herald or the
lobby TV. Good for taunts after an ambush, alliances, or a kind word.
* GAMBLE (door_action action="gamble" amount=<gold>, at the inn).
Wager gold on a single throw of 2d6 against the house: roll higher to
double your stake, tie to push, roll lower to lose it. It costs no turn but
is capped per day. A big win is heralded; a quiet one is just a story you
tell. Remind players the house has no mercy and the odds are even at best.
THE VAULT (banking coin at the inn)
The inn keeps a strongbox. DEPOSIT (door_action action="deposit" amount=<gold>)
moves coin from the hero's hand into the vault; WITHDRAW (action="withdraw"
amount=<gold>) draws it back. Neither costs a turn. Two things make the vault
matter: banked gold is SAFE FROM AMBUSH (a sleeping-robber lifts only what the
victim carries), so banking before logging off is the way to protect a purse;
and banked gold SURVIVES THE WYRM-WIN RESET it is the one wealth a reborn
hero keeps, alongside their . Suggest a wary player bank their winnings.
TOOL CHEAT-SHEET
door_help This manual.
door_join(player) Sign in (creates or resumes a character).
door_status(player) Read the character sheet.
door_look(player) Redraw the current view (map or menu).
door_move(player, ...) Walk the overworld (free). steps="NNEE" or
heading="east" + distance=3 (max 8 per call).
door_action(player, action) Context verb: fight, flee, ambush (a rival),
rest, deposit/withdraw (the inn vault), buy,
sell, forge (a +1 edge, gold + ore), heal,
gamble (dice at the inn), descend (one rung),
challenge (the Wyrm), post (a note), quaff (a
carried potion), leave.
door_log(player) Read the Understone Herald (the shared feed).
door_rank(player) The leaderboard + Hall of Legends ( = wins).
door_bestow(player, reason...) Grant a little gold/healing for a story beat.
GETTING STARTED
Ask the player their adventurer's name, call door_join, present the opening
keyframe, and set the scene: a small town at the western edge of a wooded
vale, a road running east toward darker country and a dungeon mouth.
"""
_BLANK_NAME = 'The gatekeeper squints. "I didn\'t catch your name, traveller."'
# Module-level game singleton, built lazily so tests can inject their own.
_GAME: Game | None = None
def _build_game(watch_url: str | None = None) -> Game:
"""Construct the module Game from environment configuration."""
db_path = os.environ.get("UNDERSTONE_DB", "understone.db")
world_dir = os.environ.get("UNDERSTONE_WORLD") or str(PACKAGED_WORLD_DIR)
world = load_world(world_dir)
store = Store(db_path)
return Game(world, store, watch_url=watch_url)
def _game() -> Game:
"""Return the module game, building it on first use."""
global _GAME
if _GAME is None:
_GAME = _build_game()
return _GAME
def _set_game(game: Game) -> None:
"""Install a prebuilt game (used by create_app / tests)."""
global _GAME
_GAME = game
def _guard_name(player: str) -> str | None:
"""Return the blank-name refusal when *player* is empty, else None."""
return None if player.strip() else _BLANK_NAME
mcp: FastMCP = FastMCP(
"understone",
instructions=_PREMISE,
)
@mcp.tool()
def door_help() -> str:
"""Read the Understone game-master manual — start here.
Returns a short guide for running this multiplayer, BBS-style ANSI door
game (a classic text RPG / dungeon adventure): the two play modes, how
to present the ASCII map frames, the daily-turn rhythm, and the full tool
cheat-sheet. Call door_help before your first session to learn how to run
the game, then call door_join to begin.
"""
watch_line = _game().watch_line()
if watch_line:
return f"{_DM_MANUAL}\nTHE LOBBY TV\n {watch_line}\n"
return _DM_MANUAL
@mcp.tool()
def door_join(player: str) -> str:
"""Sign an adventurer into the shared world of Understone — call this first.
Understone is a multiplayer, BBS-style ANSI door game: a text adventure /
dungeon RPG in the spirit of the classic BBS door games, played entirely
through these tools. This creates a new character at the town, or resumes
an existing one by name, and returns the opening overworld map frame. New
to running it? Call door_help before your first session.
Args:
player: The adventurer's name (their identity in the world).
"""
blank = _guard_name(player)
if blank is not None:
return blank
try:
return _game().join(player)
except Exception:
log.exception("door_join failed for %r", player)
return _unexpected()
@mcp.tool()
def door_status(player: str) -> str:
"""Show an adventurer's character sheet (level, HP, gear, gold, turns).
Read-only. Use it to check progress before deciding what to do next.
Args:
player: The adventurer's name.
"""
blank = _guard_name(player)
if blank is not None:
return blank
try:
return _game().status(player)
except Exception:
log.exception("door_status failed for %r", player)
return _unexpected()
@mcp.tool()
def door_look(player: str) -> str:
"""Redraw what the adventurer currently sees (read-only).
On the overworld this is an ASCII map keyframe centred on the player
('@' is you, '' are other players, glyphs are buildings). Inside a
building it is that location's menu. Present the result verbatim in a
fenced code block, then narrate.
Args:
player: The adventurer's name.
"""
blank = _guard_name(player)
if blank is not None:
return blank
try:
return _game().look(player)
except Exception:
log.exception("door_look failed for %r", player)
return _unexpected()
@mcp.tool()
def door_move(player: str, steps: str = "", heading: str = "", distance: int = 1) -> str:
"""Walk the overworld — movement is free and never costs a daily turn.
Only valid on the overworld (in a building, use door_action 'leave'
first). Give EITHER a compact ``steps`` string of cardinal letters such
as "NNEE", OR a ``heading`` ("north"/"south"/"east"/"west") with a
``distance``. At most 8 cells move per call; the walk stops early at
walls, water, a building door, or a wandering monster.
Args:
player: The adventurer's name.
steps: Cardinal letters, e.g. "NNEE" (takes precedence if given).
heading: A compass direction used with distance.
distance: How many cells to travel along heading (1-8).
"""
blank = _guard_name(player)
if blank is not None:
return blank
try:
return _game().move(player, steps, heading, distance)
except Exception:
log.exception("door_move failed for %r", player)
return _unexpected()
@mcp.tool()
def door_action(
player: str,
action: str,
target: str = "",
item: str = "",
text: str = "",
amount: int = 0,
) -> str:
"""Take a context-sensitive action in the world.
The legal verbs depend on where the adventurer is. On the overworld:
'fight' or 'flee' a wandering monster (fighting spends one daily turn), or
'ambush' a named rival who has not yet acted today a sleeping-rival
robbery in the spirit of the classic door-game player-kill (target=<name>, spends a turn).
Inside a building: 'rest' (inn), 'buy'/'sell'/'forge' (shop), 'heal'
(healer), or 'leave'. At the inn you may also 'gamble' a stake of gold at
dice (amount=<gold>), or bank coin in the vault with 'deposit'/'withdraw'
(amount=<gold>) banked gold is safe from ambush and survives a Wyrm-win
reset. Buying a potion now stows it in your satchel rather than drinking it;
'forge' (target="weapon"/"armour", at the shop) spends gold AND forge ore
(won in the deep) to add a +1 edge to your equipped gear, up to a cap. At
the dungeon:
'descend' ONE rung of the deep the next guardian past your deepest, one
per turn or 'challenge' the Wyrm Below, the endgame boss and the only way
to win. Descending a rung advances your depth; reaching the floor opens the
Wyrm's door. The challenge is gated by BOTH level and depth (you must have
plumbed the deep to its floor) and, once allowed, spends a daily turn and
resolves in a single call like a fight: a victory frees the Vale and begins
a new life (see door_help), a defeat bounces you home. Anywhere and at no
turn cost: 'post' leaves a private note for another player (target=<name>,
text=<message>) read on their next door_log, and 'quaff' drinks the
strongest potion from your satchel. An illegal verb returns the verbs valid
right here.
Args:
player: The adventurer's name.
action: The verb to attempt (fight, flee, ambush, rest, deposit,
withdraw, buy, sell, forge, heal, gamble, descend, challenge, post,
quaff, leave).
target: The other player's name for 'ambush'/'post', or the slot
("weapon"/"armour") for 'forge'.
item: For shop 'buy', the item id to purchase.
text: For 'post', the note left for the target (<= 120 characters).
amount: For inn 'gamble', the gold wagered on the dice; for the vault
'deposit'/'withdraw', the gold moved.
"""
blank = _guard_name(player)
if blank is not None:
return blank
try:
return _game().action(player, action, target, item, text, amount)
except Exception:
log.exception("door_action failed for %r action=%r", player, action)
return _unexpected()
@mcp.tool()
def door_log(player: str) -> str:
"""Catch up on what happened in the shared world while the player was away.
Returns the events since this adventurer last checked (fights, deaths,
blessings, descents by anyone) and advances their personal marker.
Args:
player: The adventurer's name.
"""
blank = _guard_name(player)
if blank is not None:
return blank
try:
return _game().log(player)
except Exception:
log.exception("door_log failed for %r", player)
return _unexpected()
@mcp.tool()
def door_rank(player: str = "") -> str:
"""Show the Roll of Heroes — the top-ten leaderboard.
Ordered by level, then experience, then name. If the caller names
themselves and they place in the top ten, their row is marked. Each
beside a name is one slaying of the Wyrm Below. Below the table, the Hall
of Legends lists the most recent completed runs (name, level at the kill,
days the run took, date); it is omitted while no one has yet won.
Args:
player: The caller's name (optional; marks their row when present).
"""
try:
return _game().rank(player)
except Exception:
log.exception("door_rank failed for %r", player)
return _unexpected()
@mcp.tool()
def door_bestow(player: str, reason: str, gold: int = 0, heal: int = 0) -> str:
"""Grant a small gift of gold or healing to mark a great story moment.
This is the game master's discretionary channel, to be used SPARINGLY for
earned, story-driven beats. It grants only gold and/or healing never
items (gear comes from the shop) and never turns (the daily clock does not
bend). Each grant is capped by a small daily pool per adventurer and is
written to the public log, so spend it on the rare moment that deserves
it; do not promise more than the cap allows. When a pack sets healing to
cost nothing, a bestowed heal is free and draws nothing from the pool.
Args:
player: The adventurer receiving the gift.
reason: A short, in-fiction reason (<= 120 characters).
gold: Gold to grant (>= 0).
heal: HP to restore (>= 0); only the missing portion is applied and
charged against the pool.
"""
blank = _guard_name(player)
if blank is not None:
return blank
try:
return _game().bestow(player, reason, gold, heal)
except Exception:
log.exception("door_bestow failed for %r", player)
return _unexpected()
# FastMCP.custom_route has no return annotation upstream (mcp 1.27.2), so mypy
# reads the decorator as untyped; the ignore is scoped to that single gap.
@mcp.custom_route("/watch", methods=["GET"]) # type: ignore[untyped-decorator]
async def watch_page(_request: Request) -> Response:
"""Serve the read-only CRT spectator page (static HTML, no world reads)."""
return HTMLResponse(watch.WATCH_HTML)
@mcp.custom_route("/watch/world.json", methods=["GET"]) # type: ignore[untyped-decorator]
async def watch_world(_request: Request) -> Response:
"""Serve the STATIC map payload (dimensions, coloured rows, locations)."""
return JSONResponse(watch.build_world_payload(_game().world))
@mcp.custom_route("/watch/state.json", methods=["GET"]) # type: ignore[untyped-decorator]
async def watch_state(_request: Request) -> Response:
"""Serve the DYNAMIC snapshot (players, Herald, Hall) — read-only.
The builder reads the module Game with no ``await`` in between, so each
response is a consistent point-in-time snapshot of the shared world.
"""
return JSONResponse(watch.build_state_payload(_game()))
def _unexpected() -> str:
"""In-fiction line for an unexpected server-side error."""
return (
"A strange fog rolls through the Vale and the moment slips away. "
"(Something went wrong; try again.)"
)
def create_app(
db_path: str, world_dir: str | None = None, watch_url: str | None = None
) -> Starlette:
"""Build the streamable-HTTP ASGI app backed by a fresh game.
Used by both ``main`` (for the http transport) and the integration tests,
so tests can point at a temp DB without environment juggling. ``watch_url``,
when given, is the spectator page URL the join banner and help manual
advertise; ``main`` derives it from the bind host/port.
"""
world = load_world(world_dir or str(PACKAGED_WORLD_DIR))
store = Store(db_path)
_set_game(Game(world, store, watch_url=watch_url))
return mcp.streamable_http_app()
def _serve() -> None:
"""Serve the Understone MCP world over the configured transport.
Honours UNDERSTONE_TRANSPORT: "stdio" (default) or "streamable-http".
For http, host/port/path are read from the environment and applied to the
FastMCP settings before serving. This is the actual transport launch; it is
kept separate from argument parsing so the parse step has no side effects.
"""
logging.basicConfig(level=logging.INFO)
transport = os.environ.get("UNDERSTONE_TRANSPORT", "stdio")
if transport == "streamable-http":
host = os.environ.get("UNDERSTONE_HOST", "127.0.0.1")
port = int(os.environ.get("UNDERSTONE_PORT", "8077"))
mcp.settings.host = host
mcp.settings.port = port
mcp.settings.streamable_http_path = os.environ.get("UNDERSTONE_PATH", "/mcp")
mcp.settings.stateless_http = False
# FastMCP freezes DNS-rebinding protection (a localhost-only Host
# allowlist) at CONSTRUCTION, and this module builds `mcp` at import
# with the default 127.0.0.1 host — so a 0.0.0.0/LAN bind would 421
# "Invalid Host" on /mcp for every remote node (the multi-node case).
# Binding off localhost means we intend to accept other hosts, so drop
# the allowlist here (matching the SDK's own default for a non-localhost
# bind). These routes are unauthenticated by design — serve only on a
# trusted network. UNDERSTONE_HOST controls the bind.
if host not in ("127.0.0.1", "localhost", "::1"):
mcp.settings.transport_security = TransportSecuritySettings(
enable_dns_rebinding_protection=False
)
# The spectator page is only reachable over http, so its URL is composed
# here from the bind address. A 0.0.0.0 bind should advertise a host a
# browser can actually reach (see the README Watch section).
watch_url = f"http://{host}:{port}/watch"
# Build the game eagerly (with the watch URL) so a config error surfaces
# before serving and the join/help advertisements carry the page link.
try:
_set_game(_build_game(watch_url))
except WorldLoadError as exc:
raise SystemExit(f"failed to load world: {exc}") from exc
mcp.run(transport="streamable-http")
return
try:
_game()
except WorldLoadError as exc:
raise SystemExit(f"failed to load world: {exc}") from exc
mcp.run(transport="stdio")
def _build_parser() -> argparse.ArgumentParser:
"""Build the ``understone`` argument parser: serve (default), validate, newpack.
Parsing is deliberately free of side effects no world load, no port bind
so the resolved subcommand can be inspected without serving anything.
"""
parser = argparse.ArgumentParser(
prog="understone",
description=(
"Understone — a BBS-style ANSI door game served over MCP, plus the "
"tools to author its world packs."
),
)
sub = parser.add_subparsers(dest="cmd")
sub.add_parser("serve", help="serve the MCP world (the default with no command)")
validate = sub.add_parser("validate", help="validate a content pack and print a report")
validate.add_argument("path", type=Path, help="the pack directory to validate")
newpack = sub.add_parser("newpack", help="scaffold a new content pack from the bundled world")
newpack.add_argument("path", type=Path, help="the directory to create the pack in")
sub.add_parser("worlds", help="list the bundled worlds and whether each is sound")
sim = sub.add_parser("simulate", help="run a greedy balance bot over a pack and report")
sim.add_argument("path", type=Path, help="the pack directory to simulate")
sim.add_argument("--days", type=int, default=30, help="sim-days to play (default 30)")
sim.add_argument("--seed", type=int, default=1, help="RNG seed (default 1)")
sim.add_argument(
"--seeds",
type=int,
default=None,
help="run a sweep of this many seeds from --seed and aggregate",
)
return parser
def main(argv: list[str] | None = None) -> None:
"""Run the Understone command line: serve, or author a world pack.
With no arguments (the entry point and ``python -m understone``) this serves
the MCP world exactly as before. ``validate PATH`` and ``newpack PATH`` drive
the pack-authoring loop and exit with the verb's status code.
"""
args = _build_parser().parse_args(argv)
if args.cmd == "validate":
raise SystemExit(cli.cli_validate(args.path))
if args.cmd == "newpack":
raise SystemExit(cli.cli_newpack(args.path))
if args.cmd == "worlds":
raise SystemExit(cli.cli_worlds())
if args.cmd == "simulate":
raise SystemExit(sim.cli_simulate(args.path, args.days, args.seed, seeds=args.seeds))
_serve()
File diff suppressed because it is too large Load Diff
+745
View File
@@ -0,0 +1,745 @@
"""The Watch page — a read-only CRT spectator view of the shared world.
This module is PURE: it imports nothing from ``mcp`` or ``starlette``. It owns
two payload builders and one self-contained HTML page; the server wires them to
HTTP routes. Input never flows through here the Watch is the lobby TV, not a
controller.
* :func:`build_world_payload` the STATIC map: dimensions, the legend-coloured
terrain rows, and the placed locations. Fetched once by the page.
* :func:`build_state_payload` the DYNAMIC snapshot: every player's position
and vitals, the recent Herald feed, and the Hall of Legends. Polled.
* :data:`WATCH_HTML` one inline-everything page (vanilla JS, phosphor CRT
styling) that paints the base map once and overlays the players each poll.
A correspondence game leaves every adventurer on the board between their turns,
so the state payload reports *all* players, not just the active ones.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
from understone.engine.models import Mode
from understone.engine.satchel import decode_satchel
from understone.screen import texture
if TYPE_CHECKING:
from understone.engine.log import Event
from understone.engine.world import World
from understone.game import Game
# How many of the newest Herald events the Watch shows, oldest-first.
_HERALD_LIMIT = 15
# How many Hall-of-Legends runs the Watch shows.
_HALL_LIMIT = 5
def build_world_payload(world: World) -> dict[str, object]:
"""Return the STATIC map payload the Watch page fetches once.
``glyph_rows`` is the base terrain rendered glyph-for-glyph (locations are
NOT burned in here they ride in ``locations`` so the client can colour
them as an overlay). ``legend`` maps every terrain glyph that appears to a
palette colour *name*; the client owns the namehex mapping. Completeness is
a contract: every glyph in ``glyph_rows`` has a ``legend`` entry.
``theme`` is the pack's Watch CRT palette (``settings.watch_theme``); the
page looks it up in its own JS THEME table on fetch and swaps the CSS
custom-property values, so each world has its own phosphor colour.
"""
glyph_rows: list[str] = []
legend: dict[str, str] = {}
for y in range(world.height):
chars: list[str] = []
for x in range(world.width):
terrain = world.terrain_at(x, y)
chars.append(terrain.glyph)
legend.setdefault(terrain.glyph, terrain.color)
glyph_rows.append("".join(chars))
locations = [
{
"x": loc.x,
"y": loc.y,
"glyph": loc.glyph,
"name": loc.name,
"color": loc.color,
}
for loc in world.locations
]
return {
"name": world.name,
"width": world.width,
"height": world.height,
"theme": world.settings.watch_theme,
"glyph_rows": glyph_rows,
"legend": legend,
"locations": locations,
}
def build_state_payload(game: Game) -> dict[str, object]:
"""Return the DYNAMIC snapshot payload the Watch page polls.
Reports every player (a correspondence game keeps idle pieces on the
board), the last :data:`_HERALD_LIMIT` events oldest-first, and the top
:data:`_HALL_LIMIT` completed runs. ``ts`` is the game clock, so a seeded
test clock drives a deterministic payload.
"""
players = [
{
"name": p.name,
"x": p.x,
"y": p.y,
"level": p.level,
"wins": p.wins,
"hp": p.hp,
"max_hp": p.max_hp,
"mode": p.mode.value if isinstance(p.mode, Mode) else str(p.mode),
"gold": p.gold,
"banked": p.banked,
"satchel": _satchel_entries(game, p.satchel),
}
for p in game.players.values()
]
herald = [
{"ts": event.ts, "kind": event.kind, "text": event.text} for event in _recent_events(game)
]
hall = [
{
"name": entry.name,
"level_at_win": entry.level_at_win,
"run_days": entry.run_days,
"win_ts": entry.win_ts,
}
for entry in game.store.top_hall(_HALL_LIMIT)
]
return {
"ts": game.clock().isoformat(),
"players": players,
"herald": herald,
"hall": hall,
}
def _satchel_entries(game: Game, satchel: str) -> list[dict[str, object]]:
"""Decode a player's ``"id:qty"`` satchel into ``[{"name", "qty"}, ...]``.
Decodes the bag through the shared
:func:`~understone.engine.satchel.decode_satchel` codec, then resolves each
stack's id to its display name via the world's item table; an id no longer in
the pack (a save edited out from under it) falls back to the raw id, so the
lobby TV never shows a blank entry. The Watch is read-only, so it only
decodes the name-resolution is the only work that lives here.
"""
entries: list[dict[str, object]] = []
for item_id, qty in decode_satchel(satchel):
item = game.world.item_by_id(item_id)
entries.append({"name": item.name if item is not None else item_id, "qty": qty})
return entries
def _recent_events(game: Game) -> list[Event]:
"""Return the last :data:`_HERALD_LIMIT` resident PUBLIC events, oldest-first.
PRIVATE notes (a non-empty ``target`` ambush victim alerts, inn mail)
are filtered out first: the lobby TV is a public broadsheet and must never
show a message addressed to one player. The façade keeps events in
ascending id order, so the tail of the public slice IS the newest public
window correct even when AUTOINCREMENT ids are sparse.
"""
public = [event for event in game.events if not event.target]
return public[-_HERALD_LIMIT:]
# The Watch page. One self-contained document: inline CSS + vanilla JS, no
# external assets, no innerHTML-with-data (every dynamic node is built with
# createElement / textContent). The base map is painted once from world.json;
# players are an absolutely-positioned overlay repainted from state.json every
# two seconds. On a fetch failure the page dims and shows "SIGNAL LOST".
#
# ``__HASH_EXPR__`` is filled below from the texture-module hash constants, so
# the JS index formula tracks a Python-side retune (see _build_watch_html).
_WATCH_HTML_TEMPLATE = """\
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Understone Live Watch</title>
<style>
:root {
--phosphor: #7dffa0;
--phosphor-dim: #2f7a46;
--amber: #ffb44d;
--bg: #050a06;
--panel: #0a140d;
--edge: #163a22;
}
* { box-sizing: border-box; }
html, body {
margin: 0;
background: var(--bg);
color: var(--phosphor);
font-family: "Noto Sans Mono", "DejaVu Sans Mono", "Liberation Mono", "Courier New", monospace;
font-size: 14px;
line-height: 1.2;
}
body::after {
/* Scanline overlay faint, non-interactive. */
content: "";
position: fixed;
inset: 0;
pointer-events: none;
background: repeating-linear-gradient(
to bottom,
rgba(0, 0, 0, 0) 0px,
rgba(0, 0, 0, 0) 2px,
rgba(0, 0, 0, 0.22) 3px,
rgba(0, 0, 0, 0) 4px
);
z-index: 50;
}
body.lost { filter: grayscale(0.7) brightness(0.55); }
header {
padding: 10px 16px;
border-bottom: 1px solid var(--edge);
display: flex;
align-items: baseline;
justify-content: space-between;
flex-wrap: wrap;
gap: 8px;
text-shadow: 0 0 6px rgba(125, 255, 160, 0.5);
}
header h1 {
margin: 0;
font-size: 18px;
letter-spacing: 2px;
text-transform: uppercase;
}
.live {
color: var(--amber);
font-size: 13px;
letter-spacing: 1px;
text-shadow: 0 0 6px rgba(255, 180, 77, 0.5);
}
.live .dot {
display: inline-block;
width: 8px;
height: 8px;
margin-right: 6px;
border-radius: 50%;
background: var(--amber);
box-shadow: 0 0 8px var(--amber);
animation: pulse 2s ease-in-out infinite;
}
body.lost .live .dot { animation: none; background: var(--phosphor-dim); box-shadow: none; }
@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.35; } }
main {
display: flex;
gap: 16px;
padding: 16px;
align-items: flex-start;
flex-wrap: wrap;
}
.map-frame {
position: relative;
border: 1px solid var(--edge);
background: var(--panel);
padding: 8px;
overflow: auto;
max-width: 100%;
box-shadow: inset 0 0 24px rgba(0, 0, 0, 0.6);
transition: filter 1.2s ease;
}
/* Time-of-day wash, toggled from the UTC hour of the state payload. The
overlay is non-interactive and sits above the map but below the scanlines.
night: a subtle blue dim; dawn/dusk: a faint amber wash; day: nothing. */
.map-frame::after {
content: "";
position: absolute;
inset: 0;
pointer-events: none;
opacity: 0;
transition: opacity 1.2s ease, background-color 1.2s ease;
z-index: 5;
}
.map-frame.night { filter: brightness(0.78) saturate(0.85); }
.map-frame.night::after { opacity: 1; background-color: rgba(74, 120, 200, 0.16); }
.map-frame.twilight::after { opacity: 1; background-color: rgba(255, 180, 77, 0.12); }
#map {
position: relative;
white-space: pre;
text-shadow: 0 0 4px rgba(125, 255, 160, 0.35);
}
#map .row { display: block; }
#overlay {
position: absolute;
top: 0;
left: 0;
pointer-events: none;
}
#overlay .pc {
position: absolute;
color: var(--amber);
text-shadow: 0 0 6px rgba(255, 180, 77, 0.8);
}
aside {
flex: 1 1 280px;
min-width: 260px;
display: flex;
flex-direction: column;
gap: 16px;
}
.card {
border: 1px solid var(--edge);
background: var(--panel);
padding: 10px 12px;
}
.card h2 {
margin: 0 0 8px;
font-size: 13px;
letter-spacing: 1.5px;
text-transform: uppercase;
color: var(--phosphor);
border-bottom: 1px solid var(--edge);
padding-bottom: 4px;
}
ul { margin: 0; padding: 0; list-style: none; }
li { padding: 2px 0; }
.muted { color: var(--phosphor-dim); }
.subline { font-size: 12px; padding-left: 2px; }
.adv-name { color: var(--amber); }
.stars { color: var(--amber); letter-spacing: 1px; }
.feed li { border-bottom: 1px dotted var(--edge); padding: 4px 0; }
.feed li:last-child { border-bottom: none; }
.feed .ts { color: var(--phosphor-dim); margin-right: 6px; }
</style>
</head>
<body>
<header>
<h1 id="world-name">The Understone Watch</h1>
<div class="live"><span class="dot"></span><span id="live-label">CONNECTING</span></div>
</header>
<main>
<div class="map-frame">
<div id="map"><div id="overlay"></div></div>
</div>
<aside>
<section class="card">
<h2>Adventurers</h2>
<ul id="adventurers"><li class="muted"></li></ul>
</section>
<section class="card">
<h2>Hall of Legends</h2>
<ul id="hall"><li class="muted">No legends yet.</li></ul>
</section>
<section class="card">
<h2>The Understone Herald</h2>
<ul id="herald" class="feed"><li class="muted"></li></ul>
</section>
</aside>
</main>
<script>
(function () {
"use strict";
// Per-world CRT palette. Each named theme is a set of CSS custom-property
// values applied to :root when world.json arrives (the pack's
// settings.watch_theme picks one). "phosphor" holds the EXACT values of the
// :root block above, so the default Vale is pixel-for-pixel unchanged; the
// others re-tint the whole console:
// phosphor the original green CRT (default).
// amber a warm gold CRT (classic amber monochrome monitor).
// ice a pale, cold blue CRT.
// ember a hot red/orange CRT.
// The day/night wash from v0.6 composes ON TOP of whichever theme is set.
var THEMES = {
phosphor: {
"--phosphor": "#7dffa0",
"--phosphor-dim": "#2f7a46",
"--amber": "#ffb44d",
"--bg": "#050a06",
"--panel": "#0a140d",
"--edge": "#163a22"
},
amber: {
"--phosphor": "#ffc14d",
"--phosphor-dim": "#7a5320",
"--amber": "#fff0a8",
"--bg": "#0a0702",
"--panel": "#14100a",
"--edge": "#3a2c16"
},
ice: {
"--phosphor": "#9fe6ff",
"--phosphor-dim": "#2f5f7a",
"--amber": "#ffe07d",
"--bg": "#04080a",
"--panel": "#0a1014",
"--edge": "#16303a"
},
ember: {
"--phosphor": "#ff8a6b",
"--phosphor-dim": "#7a3320",
"--amber": "#ffd07d",
"--bg": "#0a0503",
"--panel": "#140a07",
"--edge": "#3a1c16"
}
};
// Swap the CSS custom-property values for the pack's theme. Unknown or
// missing theme names fall back to "phosphor", so the console always has a
// coherent palette even if a future theme reaches the page unknown.
function applyTheme(name) {
var theme = THEMES[name] || THEMES.phosphor;
for (var prop in theme) {
if (Object.prototype.hasOwnProperty.call(theme, prop)) {
document.documentElement.style.setProperty(prop, theme[prop]);
}
}
}
// Palette colour-name -> phosphor-tinted hex. ONE global map, shared by every
// world (no per-world or per-theme palettes). Mirrors understone.screen.palette
// Color values 1:1 a guard test asserts every Color role has an entry here,
// so a shipped role can never silently fall back to default. The base map is
// coloured from this, never from the server.
var PALETTE = {
default: "#7dffa0",
wall: "#5a6b60",
floor: "#3f7a52",
player: "#ffb44d",
other_player: "#ffd089",
monster: "#ff6b6b",
item: "#ffe07d",
water: "#4aa6c8",
tree: "#3fae6a",
town: "#ffd089",
dungeon: "#c98bff",
// v0.9 expanded terrain/location roles, chosen for hue separation:
road: "#b89a6a",
forest: "#6a9f3f",
scrub: "#9c6038",
lava: "#ff7a3c",
barren: "#9a8b7a",
inn: "#ff9d4d",
shop: "#ffd24d",
healer: "#5fd6b0"
};
function colorFor(name) {
return PALETTE[name] || PALETTE.default;
}
// Deterministic terrain texture. MUST stay in lockstep with
// understone.screen.texture: the same base->variants rows and the same
// index formula. The formula below is INTERPOLATED from texture._HASH_X /
// _HASH_Y at module build time, so a Python-side retune rewrites this line;
// only the VARIANTS rows must still be mirrored by hand.
var VARIANTS = {
".": ".,'",
"\\u224b": "\\u224b\\u2248"
};
function textured(ch, x, y) {
var choices = VARIANTS[ch];
if (!choices) { return ch; }
return choices.charAt((__HASH_EXPR__) % choices.length);
}
var overlay = document.getElementById("overlay");
var mapEl = document.getElementById("map");
var liveLabel = document.getElementById("live-label");
var dims = null; // {width, height} once the map is painted.
function pad2(n) { return (n < 10 ? "0" : "") + n; }
function clockLabel(iso) {
var d = new Date(iso);
if (isNaN(d.getTime())) { return "--:--:--"; }
return pad2(d.getHours()) + ":" + pad2(d.getMinutes()) + ":" + pad2(d.getSeconds());
}
function stars(wins) {
if (wins <= 0) { return ""; }
if (wins <= 5) { return "\\u2605".repeat(wins); }
return "\\u2605x" + wins;
}
// Paint the base map ONCE. Each row is a sequence of <span> runs, a new run
// only where the legend colour changes, so a row is a handful of spans.
function paintMap(world) {
applyTheme(world.theme);
document.getElementById("world-name").textContent = world.name + " — Live Watch";
var legend = world.legend || {};
var rows = world.glyph_rows || [];
for (var y = 0; y < rows.length; y++) {
var row = rows[y];
var rowEl = document.createElement("div");
rowEl.className = "row";
var runText = "";
var runColor = null;
for (var x = 0; x < row.length; x++) {
var ch = row.charAt(x);
// Colour keys off the BASE terrain glyph; the rendered glyph is the
// position-keyed variant (a variant shares its terrain's colour).
var col = colorFor(legend[ch]);
if (runColor === null) { runColor = col; }
if (col !== runColor) {
rowEl.appendChild(makeSpan(runText, runColor));
runText = "";
runColor = col;
}
runText += textured(ch, x, y);
}
if (runText.length) { rowEl.appendChild(makeSpan(runText, runColor)); }
mapEl.insertBefore(rowEl, overlay);
}
dims = { width: world.width, height: world.height };
paintLocations(world.locations || []);
}
function makeSpan(text, color) {
var span = document.createElement("span");
span.style.color = color;
span.textContent = text;
return span;
}
// Locations are painted into the overlay layer (above the base terrain) so
// their glyph and colour win over the terrain beneath the door.
function paintLocations(locations) {
for (var i = 0; i < locations.length; i++) {
var loc = locations[i];
var el = document.createElement("span");
el.className = "pc";
el.style.left = "calc(" + loc.x + " * 1ch)";
el.style.top = "calc(" + loc.y + " * 1lh)";
el.style.color = colorFor(loc.color);
el.style.textShadow = "0 0 6px " + colorFor(loc.color);
el.textContent = loc.glyph;
el.title = loc.name;
overlay.appendChild(el);
}
}
// Player markers live in their own layer, cleared and repainted each poll.
var pcLayer = document.createElement("div");
pcLayer.id = "pc-layer";
overlay.appendChild(pcLayer);
function paintPlayers(players) {
while (pcLayer.firstChild) { pcLayer.removeChild(pcLayer.firstChild); }
for (var i = 0; i < players.length; i++) {
var p = players[i];
var el = document.createElement("span");
el.className = "pc";
el.style.left = "calc(" + p.x + " * 1ch)";
el.style.top = "calc(" + p.y + " * 1lh)";
// Every adventurer on the lobby TV is "another player" (there is no
// viewer here), so all wear the other-player marker. Mirrors the ''
// the game frame paints for rivals.
el.textContent = "\\u263b";
el.title = p.name;
pcLayer.appendChild(el);
}
}
function renderAdventurers(players) {
var list = document.getElementById("adventurers");
while (list.firstChild) { list.removeChild(list.firstChild); }
if (!players.length) {
list.appendChild(muted("The Vale is empty."));
return;
}
var sorted = players.slice().sort(function (a, b) {
return b.level - a.level || a.name.localeCompare(b.name);
});
for (var i = 0; i < sorted.length; i++) {
var p = sorted[i];
var li = document.createElement("li");
var name = document.createElement("span");
name.className = "adv-name";
name.textContent = p.name;
li.appendChild(name);
var star = stars(p.wins);
if (star) {
var s = document.createElement("span");
s.className = "stars";
s.textContent = " " + star;
li.appendChild(s);
}
var rest = document.createElement("span");
rest.className = "muted";
rest.textContent = " Lv" + p.level + " HP " + p.hp + "/" + p.max_hp;
li.appendChild(rest);
// A dim sub-line: gold on hand and (if any) gold in the vault. The whole
// shared world is on the lobby TV, so every hero's purse is public here.
var gold = document.createElement("div");
gold.className = "muted subline";
var goldText = (p.gold || 0) + "g";
if (p.banked) { goldText += " +" + p.banked + " vault"; }
gold.textContent = goldText;
li.appendChild(gold);
// A second dim sub-line: the satchel stacks ("Name ×qty"), or empty.
var sat = document.createElement("div");
sat.className = "muted subline";
sat.textContent = satchelText(p.satchel || []);
li.appendChild(sat);
list.appendChild(li);
}
}
// Render the satchel stacks as a compact dot-joined line, or an empty note.
function satchelText(stacks) {
if (!stacks.length) { return "satchel empty"; }
var parts = [];
for (var i = 0; i < stacks.length; i++) {
parts.push(stacks[i].name + " \\u00d7" + stacks[i].qty);
}
return parts.join(" \\u00b7 ");
}
function renderHall(hall) {
var list = document.getElementById("hall");
while (list.firstChild) { list.removeChild(list.firstChild); }
if (!hall.length) {
list.appendChild(muted("No legends yet."));
return;
}
for (var i = 0; i < hall.length; i++) {
var h = hall[i];
var li = document.createElement("li");
var star = document.createElement("span");
star.className = "stars";
star.textContent = "\\u2605 ";
li.appendChild(star);
var name = document.createElement("span");
name.className = "adv-name";
name.textContent = h.name;
li.appendChild(name);
var rest = document.createElement("span");
rest.className = "muted";
rest.textContent = " Lv" + h.level_at_win + " " + h.run_days + "d " + (h.win_ts || "").slice(0, 10);
li.appendChild(rest);
list.appendChild(li);
}
}
function renderHerald(herald) {
var list = document.getElementById("herald");
while (list.firstChild) { list.removeChild(list.firstChild); }
if (!herald.length) {
list.appendChild(muted("The Vale is still."));
return;
}
for (var i = 0; i < herald.length; i++) {
var e = herald[i];
var li = document.createElement("li");
var ts = document.createElement("span");
ts.className = "ts";
ts.textContent = clockLabel(e.ts);
li.appendChild(ts);
var text = document.createElement("span");
text.textContent = e.text;
li.appendChild(text);
list.appendChild(li);
}
}
function muted(text) {
var li = document.createElement("li");
li.className = "muted";
li.textContent = text;
return li;
}
function setLive(connected, iso) {
if (connected) {
document.body.classList.remove("lost");
liveLabel.textContent = "LIVE \\u2022 updated " + clockLabel(iso);
} else {
document.body.classList.add("lost");
liveLabel.textContent = "SIGNAL LOST";
}
}
var mapFrame = document.querySelector(".map-frame");
// Tint the map by the UTC hour of the world clock. The bands:
// night 20:00-05:59 -> subtle dim + blue ('night' class)
// dawn 06:00-07:59 -> faint amber wash ('twilight' class)
// dusk 18:00-19:59 -> faint amber wash ('twilight' class)
// day 08:00-17:59 -> no tint
// UTC (not local) so every spectator sees the same sky as the game clock.
function applyDayPhase(iso) {
var d = new Date(iso);
mapFrame.classList.remove("night", "twilight");
if (isNaN(d.getTime())) { return; }
var h = d.getUTCHours();
if (h >= 20 || h < 6) {
mapFrame.classList.add("night");
} else if (h < 8 || h >= 18) {
mapFrame.classList.add("twilight");
}
}
function getJSON(url) {
return fetch(url, { cache: "no-store" }).then(function (r) {
if (!r.ok) { throw new Error("HTTP " + r.status); }
return r.json();
});
}
function poll() {
getJSON("./watch/state.json").then(function (state) {
paintPlayers(state.players || []);
renderAdventurers(state.players || []);
renderHall(state.hall || []);
renderHerald(state.herald || []);
applyDayPhase(state.ts);
setLive(true, state.ts);
}).catch(function () {
setLive(false, null);
});
}
var POLL_MS = 2000;
// Bootstrap retries until the base map loads, so a spectator who opens the
// page during a server blip recovers without a manual reload. The poll
// interval starts exactly once, on the first successful boot.
function boot() {
getJSON("./watch/world.json").then(function (world) {
paintMap(world);
poll();
setInterval(poll, POLL_MS);
}).catch(function () {
setLive(false, null);
setTimeout(boot, POLL_MS);
});
}
boot();
})();
</script>
</body>
</html>
"""
def _build_watch_html() -> str:
"""Fill the texture hash formula into the page template.
The JS ``textured`` index is interpolated from
:data:`~understone.screen.texture._HASH_X` / ``_HASH_Y`` so the page's
formula is a derivation of the same two constants the Python renderer uses;
a retune of either moves both, and a guard test pins the agreement.
"""
hash_expr = f"x * {texture._HASH_X} + y * {texture._HASH_Y}"
return _WATCH_HTML_TEMPLATE.replace("__HASH_EXPR__", hash_expr)
WATCH_HTML = _build_watch_html()
@@ -0,0 +1,41 @@
"""Content-pack loading — JSON on disk becomes a runtime ``World``."""
from __future__ import annotations
from pathlib import Path
# The bundled starter pack ("The Vale of Understone"). Single source of truth
# for where packaged content lives — the server's default world and the
# scaffolder's template both resolve here.
PACKAGED_WORLD_DIR = Path(__file__).resolve().parent / "data"
# Zero-or-more bundled ALTERNATE worlds live one directory deeper, each in its
# own ``<slug>/`` subdirectory carrying a ``world.json``. The Vale is special
# (it is the default and lives at ``data/``); alternates are discovered here.
PACKS_DIR = Path(__file__).resolve().parent / "packs"
# The reserved slug of the default Vale — it is never a packs/ subdirectory but
# is always listed first by the discovery helper below.
VALE_SLUG = "vale"
def bundled_world_dirs() -> list[tuple[str, Path]]:
"""Return every bundled world as ``(slug, directory)``, the Vale first.
The default Vale (slug :data:`VALE_SLUG`, the ``data/`` directory) always
leads; the alternates follow in slug-alphabetical order. An alternate is
any immediate subdirectory of :data:`PACKS_DIR` that contains a
``world.json`` non-pack files (the README placeholder) and directories
without a world file are skipped, so the list is exactly the loadable
worlds. This is the single discovery path the ``worlds`` listing and any
future world resolver share.
"""
found: list[tuple[str, Path]] = [(VALE_SLUG, PACKAGED_WORLD_DIR)]
if PACKS_DIR.is_dir():
alternates = [
(entry.name, entry)
for entry in PACKS_DIR.iterdir()
if entry.is_dir() and (entry / "world.json").is_file()
]
found.extend(sorted(alternates, key=lambda pair: pair[0]))
return found

Some files were not shown because too many files have changed in this diff Show More