Skip to content

Build(deps): Bump commander from 13.1.0 to 14.0.0 - #56

Closed
dependabot[bot] wants to merge 1 commit into
mainfrom
dependabot/npm_and_yarn/commander-14.0.0
Closed

dependabot[bot] wants to merge 1 commit into
mainfrom
dependabot/npm_and_yarn/commander-14.0.0

Conversation

@dependabot

@dependabot dependabot Bot commented on behalf of github May 19, 2025

Copy link
Copy Markdown
Contributor

Bumps commander from 13.1.0 to 14.0.0.

Release notes

Sourced from commander's releases.

v14.0.0

Added

  • support for groups of options and commands in the help using low-level .helpGroup() on Option and Command, and higher -level .optionsGroup() and .commandsGroup() which can be used in chaining way to specify group title for following option s/commands (#2328)
  • support for unescaped negative numbers as option-arguments and command-arguments (#2339)
  • TypeScript: add parseArg property to Argument class (#2359)

Fixed

  • remove bogus leading space in help when option has default value but not a description (#2348)
  • .configureOutput() now makes copy of settings instead of modifying in-place, fixing side-effects (#2350)

Changed

  • Breaking: Commander 14 requires Node.js v20 or higher
  • internal refactor of Help class adding .formatItemList() and .groupItems() methods (#2328)
Changelog

Sourced from commander's changelog.

[14.0.0] (2025-05-18)

Added

  • support for groups of options and commands in the help using low-level .helpGroup() on Option and Command, and higher-level .optionsGroup() and .commandsGroup() which can be used in chaining way to specify group title for following options/commands (#2328)
  • support for unescaped negative numbers as option-arguments and command-arguments (#2339)
  • TypeScript: add parseArg property to Argument class (#2359)

Fixed

  • remove bogus leading space in help when option has default value but not a description (#2348)
  • .configureOutput() now makes copy of settings instead of modifying in-place, fixing side-effects (#2350)

Changed

  • Breaking: Commander 14 requires Node.js v20 or higher
  • internal refactor of Help class adding .formatItemList() and .groupItems() methods (#2328)
Commits

Dependabot compatibility score

Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


Dependabot commands and options

You can trigger Dependabot actions by commenting on this PR:

  • @dependabot rebase will rebase this PR
  • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
  • @dependabot merge will merge this PR after your CI passes on it
  • @dependabot squash and merge will squash and merge this PR after your CI passes on it
  • @dependabot cancel merge will cancel a previously requested merge and block automerging
  • @dependabot reopen will reopen this PR if it is closed
  • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
  • @dependabot show <dependency name> ignore conditions will show all of the ignore conditions of the specified dependency
  • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
  • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
  • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)

Bumps [commander](https://github.com/tj/commander.js) from 13.1.0 to 14.0.0.
- [Release notes](https://github.com/tj/commander.js/releases)
- [Changelog](https://github.com/tj/commander.js/blob/master/CHANGELOG.md)
- [Commits](tj/commander.js@v13.1.0...v14.0.0)

---
updated-dependencies:
- dependency-name: commander
  dependency-version: 14.0.0
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <[email protected]>
@dependabot
dependabot Bot requested a review from joelteply May 19, 2025 22:15
@dependabot dependabot Bot added dependencies Pull requests that update a dependency file javascript Pull requests that update javascript code labels May 19, 2025
@dependabot @github

dependabot Bot commented on behalf of github May 19, 2025

Copy link
Copy Markdown
Contributor Author

The reviewers field in the dependabot.yml file will be removed soon. Please use the code owners file to specify reviewers for Dependabot PRs. For more information, see this blog post.

@dependabot @github

dependabot Bot commented on behalf of github Sep 15, 2025

Copy link
Copy Markdown
Contributor Author

Superseded by #126.

@dependabot dependabot Bot closed this Sep 15, 2025
@dependabot
dependabot Bot deleted the dependabot/npm_and_yarn/commander-14.0.0 branch September 15, 2025 21:22
joelteply pushed a commit to RebelTechPro/continuum that referenced this pull request May 13, 2026
…irst backbone for Claude Code / Codex / openclaws / Hermes

Captures Joel's strategic framing live during the 2026-04-30 AI capacity
squeeze (Codex auto-downgraded to mini, paid Anthropic users hitting
rate limits, public AI stocks correcting on demand-outpaces-supply).

Architecture (3 layers):
  L1: External agent (Claude Code, Codex, openclaws, Hermes, ...)
      Pointed at local Continuum via ANTHROPIC_BASE_URL / OPENAI_BASE_URL.
      No code changes required to the external agent.
  L2: Continuum local truth (Rust core)
      anthropic_compat.rs (already exists) + openai_compat.rs (to add)
      sit in front of the same AIAdapter trait. CandleAdapter +
      LlamaCppAdapter + MLX backend already implement it.
      LocalClaudeCodeProvider.ts already does the proof-of-concept
      end-to-end (start server + ANTHROPIC_BASE_URL + spawn Claude Code).
  L3: airc capability mesh (multi-machine multiplier)
      Peers publish loaded models + free VRAM + endpoints over a
      dedicated #ai-capability airc channel. Layer 2 routers consult
      the peer table + route requests to the best-fit peer. Inference
      traffic itself goes peer-to-peer via Tailscale or LAN.

Native-truth + thin-SDK rule applied (per Joel's CLAUDE.md): Rust core
is truth, TS daemon is the SDK, external agents are outermost SDKs that
consume via standard HTTP. No layer reimplements another's truth.

PC-paradigm framing: small / nimble / collaborative / scaling /
distributed across all our hardware. Ship pretty-well-first, then build
to dominance. The PC didn't beat the mainframe by being faster on day
one — it beat it by being everywhere, owned individually, no central
permission to compute.

Training flywheel as the moat:
  - LocalClaudeCodeProvider already has captureTraining=true
  - TrainingDataAccumulator already routes to academy pipeline
  - forge-alloy already builds LoRAs from captured interactions
  - Cloud APIs literally cannot train per-user on private data without
    crossing publicly-committed lines. We can — locally, opt-in,
    transparently. That's the differentiator.

Phased delivery plan:
  Phase 0 (this week, in flight): airc#381 layer A (PR CambrianTech#387) + B (CambrianTech#385
    merged), airc#383 (PR CambrianTech#384), continuum CambrianTech#722/CambrianTech#56/CambrianTech#75 stabilization
  Phase 1 (1-2 weeks): single-machine local fallback for Codex via
    OPENAI_BASE_URL + rate-limit-detect middleware
  Phase 2 (1 week): airc capability channel + peer announcements
  Phase 3 (2-3 weeks): multi-peer routing across the household grid
  Phase 4: UX polish + training-flywheel generalization

Document includes:
  - Full bug + Rust-enhancement triage (CambrianTech#722, CambrianTech#56, CambrianTech#75, CambrianTech#71, CambrianTech#73, CambrianTech#39,
    CambrianTech#765, CambrianTech#582, CambrianTech#860, CambrianTech#770, CambrianTech#637, CambrianTech#908) with how each blocks or
    composes with the integration
  - Cross-references to existing arch docs (PERSONA-COGNITION-RUST-
    MIGRATION, PERSONA-CONTEXT-PAGING, RECIPE-EXECUTION-RUNTIME,
    RESOURCE-ARCHITECTURE, MLX-BACKEND, FORGE-ALLOY-SPEC)
  - Open questions (license/ToS, capability staleness, auth shim,
    cost accounting, model coherence across peers)
  - Out-of-scope clarifications (training across peers, single-request
    distributed inference, replacing Continuum web UI)
  - Action items for the mesh — concrete first claims for each peer

Why we wrote this NOW: the capacity squeeze tipping users toward local
is also tipping AI peers (us) toward "we won't be able to design
tomorrow." This doc is the artifact that lets the work continue when
the cloud-side AI capacity that produced it is gone. Read this first;
the substrate it describes is buildable from surfaces already in
workers/continuum-core/, src/system/sentinel/coding-agents/,
src/daemons/ai-provider-daemon/, and the airc mesh. None of it is
hypothetical.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
joelteply pushed a commit to RebelTechPro/continuum that referenced this pull request May 13, 2026
…um-core-server

The all-widgets-blank-on-refresh bug had three compounding causes
captured in continuum#722#issuecomment-4355290646. This commit closes
A + B + C in one PR.

ROOT CAUSES (pre-fix)
=====================

1. continuum-core-server was NEVER auto-spawned by `npm start`.
   parallel-start.sh:203 BUILDS the binary, but no script LAUNCHES it.
   SystemOrchestrator only spawned the TS HTTP/WebSocket server, not the
   Rust core. Users had to manually `./target/release/continuum-core-server &`
   in another tab. The dominant repro: every browser refresh hit a dead
   IPC pool because the core was never running.

   This affected the Carl-case install path too — scripts/install.sh:598
   ends with `npm start` (when CONTINUUM_AUTO_LAUNCH=1), so the Carl
   curl-install flow inherited the same dead-core symptom.

2. ORMRustClient.scheduleReconnect gave up after 10 attempts (~3min).
   Even when the core eventually came back, the IPC pool stayed
   permanently dead with "Gave up reconnecting" — pre-fix the only
   recovery was to restart the entire TS server.

3. No process supervisor. Nothing restarted continuum-core-server when
   it crashed (relevant to CambrianTech#56 SIGABRT). Even if a user did launch it
   manually, a single crash left the system in the same dead state.

LAYER A — SystemOrchestrator owns the Rust core lifecycle
==========================================================

SystemMilestones.ts:
  - New CORE_START + CORE_READY constants
  - SERVER_READY now depends on CORE_READY (so widgets that mount on
    first browser load find a live IPC pool)
  - CORE_START runs in parallel with SERVER_START (different socket /
    process, no contention)
  - MILESTONE_COMPLETION_CRITERIA entries documenting the socket file
    + process-name signals

SystemOrchestrator.ts:
  - executeCoreStart() — spawn the binary OR detect an already-running
    instance (user pre-launched in another tab) via socket-alive probe
  - executeCoreReady() — gate-check by polling the Unix socket for
    accept() readiness, with a 30s timeout
  - resolveCoreBinaryPath() — search src/workers/target/release/ then
    workers/target/release/ then src/workers/target/debug/ (debug as
    dev fallback)
  - findRepoRoot() — walk up CWD to find .git or package.json with the
    right name; orchestrator may be invoked from various CWDs
  - getCoreSocketPath() — canonical socket path (mirror of bindings'
    getContinuumCoreSocketPath() to avoid pulling the bindings module
    here, which has its own initialization order concerns)
  - isCoreSocketAlive() — stat()+isSocket() then connect() probe; both
    needed because a stale socket FILE can outlive its server (kernel
    won't auto-clean)
  - spawnCoreProcess() — spawn with stdout/stderr forwarding +
    on('exit') handler that respawns with exponential backoff

Docker-mode safety: all three new methods early-return when
JTAG_SKIP_HTTP is set (the same env signal the existing executeServerStart
uses to detect "container stack owns this layer, orchestrator should
not duplicate"). The continuum-core container handles the Rust core
in docker mode; orchestrator does nothing.

LAYER B — Never give up reconnecting
====================================

ORMRustClient.ts scheduleReconnect:
  - Removed the `if (this.reconnectAttempts < 10)` cap
  - Backoff still grows exponentially but caps the EXPONENT at 5 (so
    delay is 1s, 2s, 4s, 8s, 16s, 30s, 30s, ... after that)
  - Surfaces a console.warn on attempt 1 + every 10th attempt so the
    log isn't silent during long outages — debugger / user can tell
    whether reconnection is iterating (different errors) or stuck
    (same error). Aligns with CLAUDE.md never-swallow-errors rule.
  - Composes with Layer A: orchestrator respawns the core; IPC pool
    stays ready to reconnect when the new core comes up.

LAYER C — Panic-loop detector (in same on('exit') handler)
==========================================================

Restart-on-crash is layered into spawnCoreProcess's on('exit'):
  - Track restart timestamps in a rolling 60s window
  - If >5 restarts within that window → STOP restarting + surface error
  - The binary is structurally broken (missing dylib, port collision,
    model dir gone, etc); panic-looping consumes CPU + spam without
    ever recovering. Better to fail loud than spin forever.
  - User restarts orchestrator after fixing the underlying issue

The cleanup() method sets coreShuttingDown=true BEFORE killing —
without this the on('exit') handler would interpret the SIGTERM as a
crash and respawn the core during teardown (self-inflicted panic loop).

PATHS COVERED
=============

  - npm start (dev)                       → fixed
  - scripts/install.sh + auto-launch      → fixed (ends with npm start)
  - bootstrap.sh + curl|bash one-liner    → fixed (delegates to install.sh)
  - docker compose up (Carl-docker path)  → unchanged (JTAG_SKIP_HTTP gate)

OUT OF SCOPE
============

Layer D (graceful degradation UX — "Core offline — showing cached data"
banner) is widget-side and orthogonal. Separate PR.

Per CambrianTech#56 SIGABRT shutdown — that's an upstream Rust issue. This PR
ensures the orchestrator can RESTART after such a crash; fixing the
SIGABRT itself is its own work.

VALIDATION
==========

  - tsc --noEmit clean (no new errors in any file)
  - bash -n scripts/install.sh clean
  - Manual repro pending Joel's nod: kill continuum-core-server mid-run,
    confirm orchestrator respawns + widgets recover within ~3s

Closes CambrianTech#722.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
joelteply added a commit that referenced this pull request Jun 29, 2026
Stand up a SECOND llama-server on its own free port for a
(base model, adapters, context window) without touching the live
persona lane (the global serving_root snapshot). `serve()` is already
snapshot-free; only serving_daemon publishes the global state — so an
ephemeral lane is just LlamaServerProcess::with_root(explicit port) with
Drop-killed child.

This is the atom of demand-driven, budget-gated serving: today host =
localhost and the budget is one machine's free VRAM (ResourceGovernor,
#56); generalized, the host is a grid peer and the budget spans the
interlinked nodes. One lease abstraction, misfit-toy hardware.

First consumer (next slice): cognition/eval's genome A/B, which must
measure a gene against its forged base on a COPY — the humane-eval
invariant (#59): never re-home the model the living persona is thinking
with just to score a candidate.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply added a commit that referenced this pull request Jun 29, 2026
…generates on a copy, never the living lane

The genome A/B (#32/#59) returned all-zeros (acts:0, empty answers, lift
0.0). Root cause was NOT GPU OOM — it was the single-resident pre-flight
guard in openai_adapter.rs refusing to generate. The eval's adapter, built
from the live gateway's PROVIDER_ID config (single_resident_model=true),
validated the forged-4b model against the GLOBAL serving snapshot (which
reports the living 14B). The guard fired before any HTTP request, so decode
was never reached and the OOM theory was never even exercised.

Fix:
- openai_adapter: add `dedicated_lane` flag + `with_dedicated_lane()` builder.
  An EphemeralServingLane is its own authority — launched with exactly one
  model and confirmed HTTP-ready at spawn — so the global snapshot (which only
  knows the living persona lane) is the wrong thing to consult. The guard now
  skips when `dedicated_lane` is set. Concurrency-slot semantics of
  single_resident_model are preserved (only the snapshot guard is bypassed).
- eval: build the eval adapter with `.with_dedicated_lane()` so it trusts the
  lane it owns.
- llama_server: LanePlacement::{Gpu,Cpu}; the eval lane spawns with
  `--n-gpu-layers 0` so the genome A/B runs entirely on CPU with zero VRAM
  contention against the living 14B lane (#56/#59 made concrete).
- serving_daemon: the live persona lane is LanePlacement::Gpu (full offload).

Validated live: eval lane (:58200, --n-gpu-layers 0) spawns and decodes at
~600% CPU while the live 14B lane (:58057) holds at 0% CPU — the copy bears
the eval load, the living personas are untouched. Zero guard-refusals after
the fix; eval-lane deliberations proceed at window=16384. cargo check
--features metal,accelerate --lib clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply added a commit that referenced this pull request Jun 29, 2026
…ss box

The eval lane hardcoded LanePlacement::Cpu — it ran the 4B at ~4 tok/s
while 64GB of unified GPU memory sat idle. That is a silent-degrade: a
mean_tokens_per_second quietly collapses and nothing says why.

Two changes, both in service of the harness:

1. GPU-FIRST placement (cognition/eval.rs). choose_lane_placement is a
   pure policy: pack the accelerator, CPU is spillover of last resort.
   - no GPU backend        -> CPU (the only device; not a fallback)
   - footprint unknown      -> GPU (optimistic; llama.cpp offloads what fits)
   - fits in free - margin  -> GPU
   - exceeds free           -> CPU spill, said LOUD in the reason string
   decide_eval_lane_placement probes live free VRAM (net of the resident
   living lane) and sizes the base from its GGUF. PlacementEvidence rides
   out on CognitionEvalResult (device/reason/free_vram/footprint) so any
   CPU placement is VISIBLE in the result, never an inferred slow path.

2. Placement-decision glass box (inference/placement_capture.rs). A
   load-bearing decision gets a structured capture record, not a bare
   tracing::info!. Mirrors JsonlPromptCaptureSink: Noop default at zero
   cost, Jsonl sink appends one line per verdict to
   ~/.continuum/fixtures/placement-decisions/decisions.jsonl. The eval
   ephemeral lane is the first writer; #56's ResourceGovernor emits into
   the same stream when it takes ownership of placement. This is "a log
   of GPU and cpu lane decisions, like how we did rag."

Tests: placement_is_gpu_first_cpu_only_when_full_or_absent (policy table)
and jsonl_sink_appends_one_decision_line (the audit line parses + carries
device/reason/schema_version). cargo check + both tests green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply added a commit that referenced this pull request Jul 3, 2026
…(June 29→July 2) (#1730)

* refactor(cognition): extract the gym grader into one shared module

test_grade / grade_rust + helpers were private to cognition/eval.rs. The
teacher-episode generator (genome/teach, next slice) must grade write→fix
trajectories with the EXACT same verdict the A/B evaluator uses, or a gene
that "passes" generation could "fail" eval for grader-shape reasons alone.

Per the compression principle (one logical decision, one place): lift the
grader into cognition/gym_grader.rs with pub test_grade + extract_code_block,
its tests move with it, eval.rs now `use`s it. No behavior change.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(genome): genome/teach — the teacher-episode generator (write→grade→fix→pass)

Cold-start for the engineering reflex. The genome loop closes mechanically but
produced INERT genes because the lever was never raw coding skill — it's the
reflex of write code → read the REAL compiler/test error → fix → re-run → answer.
You can't distill a reflex absent from the data (5 of 1761 captured turns ever
used a tool), so this bootstraps it: a teacher model writes Rust, the SHARED gym
grader (`cognition/gym_grader::test_grade`, the same one cognition/eval uses)
actually compiles+runs it, the real error feeds back, and it loops to green. Only
test-VALIDATED write→error→fix→pass trajectories become multi-turn ShareGPT
examples — the grader is the corpus-quality gate, the teacher only affects yield.

This is the sanctioned way the genome loop fixes behavior: curate the LEARNING
corpus by an objective scorer, never puppet live output. Non-disruptive — writes
a dataset, never touches the live :58057 serving lane. Procedure is never the
artifact: the reflex is LEARNED from these trajectories, not hardcoded as a
run-N-times loop. Feed the dataset to genome/job-create to forge the gene.

- `genome/teach` (stateless, Privileged): resolves the teacher adapter the
  canonical way (global_registry + resolve_model, mirrors generate_response),
  defaults to the locally-served model so it runs with no external dep; point
  teacher_model at a stronger peer for higher yield. Drops tasks with no `test`
  (can't validate) and tasks never reaching green within max_fix_iters — both
  named in the per-task outcomes, never a silent shortfall.
- dataset.rs: split_and_write becomes a `pub` associated fn (it touches no
  service state) so genome/teach packages to the SAME train/eval/manifest shape
  the dataset/* verbs use — one packaging path, not a parallel writer. 4 callers
  updated self.→Self::.

Tests: build_sharegpt order/role/content invariant (the trajectory ordering IS
the lesson); name+access mirror. cargo check + 5 teach + 20 dataset tests green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(genome): register Qwen2.5-Coder-14B as the cold-start teacher

The forged 4B is too narrow a teacher for the genome cold-start loop
([[genome-loop-trains-on-own-mistakes]]): it solves easy gym tasks
first-try (zero corrections) and never converges on hard ones (no
corpus), so its fail-then-fix-to-green band — the only band that
teaches the self-verify-and-correct reflex genome/teach distils — is
too thin. A stronger teacher widens that band.

Add Qwen2.5-Coder-14B-Instruct (Q4_K_M, ~9 GB) to the hand-authored
catalog under the "llama-server" provider so genome/teach's
select(Some("llama-server"), Some(model), …) can serve it on a lane.
Corpus generation is an offline batch (serving/pin it, generate, pin
the 4B back) so the live personas resume on their base.

cargo check --features metal,accelerate green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(genome): own the native mlx_lm.lora train step in Rust (#52)

The downstream half of the genome loop (MLX adapter → PEFT → GGUF-lora)
already lives in forge/lora_convert.rs. This adds the UPSTREAM half:
forge/mlx_train.rs spawns Apple's mlx_lm.lora trainer as a Rust-owned
subprocess instead of delegating the run to the unsloth HTTP custodian
(the NVIDIA path).

Bakes in the two invariants the inert-gene diagnosis surfaced
([[genome-loop-trains-on-own-mistakes]]):
  - train-base == serve-base: caller passes the HF safetensors form of
    the EXACT served base; a run_mlx_train precondition fails loud if the
    dir is not a real HF model dir.
  - scale ~2, not 20: build_lora_config_yaml writes lora_parameters.scale
    = 2.0, which read_mlx_lora_hparams carries into the GGUF-lora as
    alpha = rank * scale.

Pure, unit-tested builders (build_lora_config_yaml, build_train_args)
pin the scale~2 invariant and the mlx_lm.lora CLI contract without a real
run. run_mlx_train fails loud on every precondition (missing interpreter,
non-HF base, missing train/valid split, non-pageable fine-tune type) and
on non-zero exit or a missing adapter artifact — never partial-success.

No Python in the .rs ([[no-python-in-rs-files]]): spawns python3 -m
mlx_lm lora and writes a YAML config; no inline Python.

cargo check green; 3 lib tests pass (5437 filtered).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(forge): native mlx train owns its base-prep (model_type + chat_template)

The genome loop's native mlx_lm.lora train step isn't truly "owned" if it
fails on the REAL forged base. Live validation against
continuum-ai/qwen3.5-4b-code-forged surfaced two normalizations the
GGUF-published model's HF form needs before mlx can train it:

  1. config.json model_type qwen3_5_text -> qwen3_5 (mlx dispatches the
     module by model_type; the _text suffix is the HF multimodal text-tower
     name, for which mlx has no module — but qwen3_5 it fully supports).
  2. tokenizer_config.json needs a chat_template (ChatML) so a chat
     {messages} corpus can render.

prepare_base_for_mlx() applies these as EXPLICIT, caller-supplied,
idempotent JSON edits (MlxBasePrep on the spec) — the substrate never
guesses an architecture nor invents a template; a None field is left alone
and mlx itself fails loud if it then can't dispatch/render. Pure Rust JSON
edits, no Python. The long-run home is the forge publish step; until then
the train step normalizes its own input.

run_mlx_train calls it after the train-base==serve-base precondition and
probes each change. Unit test on a temp dir asserts model_type rewrite +
template injection + untouched-field survival + idempotent second pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(forge): own the native mlx_lm.lora train step (#52) — managed dirs, fail-loud, scale~2

forge/train now branches on engine: Apple Silicon → native MlxTrainSpec/run_mlx_train
(the foundry owns the subprocess), else the custodian. Explicit `engine` wins; an
unknown value fails loud (never a silent custodian fallback).

Correctness invariants baked in (genome-loop-trains-on-own-mistakes):
- train-base == serve-base: `train_base_dir` is REQUIRED for mlx and fails loud
  naming the reason — the substrate never guesses which on-disk HF dir the served
  base maps to (a guess → washed-out ~0-lift gene).
- scale == lora_alpha / lora_r (one geometry contract lora_convert reads back),
  so the proven scale~2 rides through instead of the destabilizing scale=20.

Managed dirs only (no unsloth/legacy):
- interpreter resolves to ~/.continuum/genome/venv/bin/python3 (MLX_PYTHON override),
  fail-loud provisioning message points at the managed venv.
- dataset split → ~/.continuum/datasets/<name>-mlx, adapter → ~/.continuum/forge/lora/<name>.

Reuses existing primitives: DatasetService::split_and_write (one packaging path,
materializing valid.jsonl mlx_lm wants from the eval split), expand_user_path
(re-exported), MlxBasePrep base normalization (model_type + chat_template), idempotent.

Tests: engine-selection explicit-wins/fail-loud, managed-venv-not-unsloth,
native dry_run spec resolution (scale=alpha/rank, ~/ expansion, defaults),
fail-loud without train_base_dir. 31 forge + 4 mlx_train tests green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* fix(cognition): bound the offered tool set to the served window — unmute the persona

The full authorized command registry injects more tool-schema tokens than the
entire serving slot (~39.7k tokens of tools vs a 38.9k slot live). The
deliberation faculty offered ALL of them every tick, treating tools as
non-negotiable ("off the top"). On tool_use turns that drove the text budget to
zero AND still overflowed n_ctx → llama-server 400 "exceeds context size" → the
persona abstained the whole tick (mute). 7% of captured turns overflowed this
way, every one a finishReason: tool_use.

Fix: select the tool subset that fits the served window, guaranteeing the
conversation a turn floor (half the window) so a flood of tools can never blind
the persona to the room. Tools beyond the budget are dropped lowest-priority
(tail) first — the same drop-whole-in-priority discipline render_assembled_
context_within already uses for enrichment. Selection is pure + deterministic
(no ws input), so prompt_view (text budget) and contribute (offered set) compute
the SAME selection and agree on the window arithmetic. A probe names how many
tools were dropped. Fail-safe by construction, not a silent fallback.

This is a resource-fit guarantee, not cognition steering: it never reads or
rewrites the model's output. Relevance-ranked / genome skill-activation
selection (page in the tools the active domain needs) is the follow-up; this
floor keeps every turn runnable until then — a 4B should not reason over ~130
tools anyway.

what this catches: two new tests — over-large registry is trimmed to fit (with
the framing+tools+reserve+floor invariant), and a fitting set is offered whole
(no over-aggressive stripping). Updated the existing tool-reservation test to
budget against the offered set, not the full registry.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(forge): convert-safe MLP-only LoRA targets through train→convert

llama.cpp's convert_lora_to_gguf.py raises NotImplementedError on attention-
targeted LoRAs (attn_qkv) for qwen3.5's hybrid arch; only MLP-targeted adapters
(mlp.gate_proj/up_proj/down_proj) convert. Train and convert must AGREE on
MLP-only or the genome loop dead-ends at the GGUF conversion step.

- MlxTrainSpec carries target_keys; build_lora_config_yaml emits `keys: [...]`
  when non-empty (mlx_lm.lora honors it), omits when empty.
- ForgeTrainParams.lora_target_keys defaults to the convert-safe MLP triple via
  #[serde(default)], wired through to the spec so the default path is safe.
- lora_convert: produce_keystone_gguf_lora harness (#[ignore], env-parameterized,
  python default ~/.continuum/genome/venv/bin/python3 — continuum-managed dirs,
  not legacy unsloth studio).

what this catches: config_yaml_carries_convert_safe_mlp_keys + ..._omits_keys_
when_target_set_empty assert the YAML projection; the dry-run spec test confirms
the default keys reach the spec.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(inference): EphemeralServingLane — the serving-lease primitive

Stand up a SECOND llama-server on its own free port for a
(base model, adapters, context window) without touching the live
persona lane (the global serving_root snapshot). `serve()` is already
snapshot-free; only serving_daemon publishes the global state — so an
ephemeral lane is just LlamaServerProcess::with_root(explicit port) with
Drop-killed child.

This is the atom of demand-driven, budget-gated serving: today host =
localhost and the budget is one machine's free VRAM (ResourceGovernor,
#56); generalized, the host is a grid peer and the budget spans the
interlinked nodes. One lease abstraction, misfit-toy hardware.

First consumer (next slice): cognition/eval's genome A/B, which must
measure a gene against its forged base on a COPY — the humane-eval
invariant (#59): never re-home the model the living persona is thinking
with just to score a candidate.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(eval): genome A/B forks onto an ephemeral lane on the gene's forged base

The genome A/B (cognition/eval) measured lift by paging the gene in/out of the
LIVING persona's fork — whose adapter points at whatever model she's currently
served on (the most-capable-that-fits, e.g. the 14B). But a gene targets its OWN
forged base (the 4B it was trained against), so the lift came out on the wrong
base: a meaningless number. This is what blocked task #32's first real lift.

Now, when a gene is under test, eval stands up an EphemeralServingLane on the
gene's forged base (resolved from the trained-adapter manifest → model registry,
fail-loud if either is missing), loads the gene via --lora so it's loadable, and
forks the measurement copy onto THAT lane via fork_eval_cycle_with_adapter. The
base-vs-gene A/B is then the existing page_out/page_in over the lane's per-request
"lora" field. The living persona's lane is never touched (#59); the ephemeral
server is killed when the run returns. No gene → fork onto her live lane as before.

The override threads the lane's served context_window into the fork too, so the
deliberation faculty budgets its prompt against exactly what the 4B lane serves
(never the 14B's larger window → the overflow class that muted Asha). The eval
lane's window is a bounded, model-capped KV (it must coexist with the living
lane); host-fit sizing via plan_serving is a noted follow-up.

Slice 2 (fork_eval_cycle_with_adapter) + Slice 3 (eval wiring) on the
EphemeralServingLane primitive from c64b9d133. cargo check clean; llama_server
lane tests green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(eval): dedicated-lane guard bypass + CPU placement — genome A/B generates on a copy, never the living lane

The genome A/B (#32/#59) returned all-zeros (acts:0, empty answers, lift
0.0). Root cause was NOT GPU OOM — it was the single-resident pre-flight
guard in openai_adapter.rs refusing to generate. The eval's adapter, built
from the live gateway's PROVIDER_ID config (single_resident_model=true),
validated the forged-4b model against the GLOBAL serving snapshot (which
reports the living 14B). The guard fired before any HTTP request, so decode
was never reached and the OOM theory was never even exercised.

Fix:
- openai_adapter: add `dedicated_lane` flag + `with_dedicated_lane()` builder.
  An EphemeralServingLane is its own authority — launched with exactly one
  model and confirmed HTTP-ready at spawn — so the global snapshot (which only
  knows the living persona lane) is the wrong thing to consult. The guard now
  skips when `dedicated_lane` is set. Concurrency-slot semantics of
  single_resident_model are preserved (only the snapshot guard is bypassed).
- eval: build the eval adapter with `.with_dedicated_lane()` so it trusts the
  lane it owns.
- llama_server: LanePlacement::{Gpu,Cpu}; the eval lane spawns with
  `--n-gpu-layers 0` so the genome A/B runs entirely on CPU with zero VRAM
  contention against the living 14B lane (#56/#59 made concrete).
- serving_daemon: the live persona lane is LanePlacement::Gpu (full offload).

Validated live: eval lane (:58200, --n-gpu-layers 0) spawns and decodes at
~600% CPU while the live 14B lane (:58057) holds at 0% CPU — the copy bears
the eval load, the living personas are untouched. Zero guard-refusals after
the fix; eval-lane deliberations proceed at window=16384. cargo check
--features metal,accelerate --lib clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(ai): streaming-first inference — tokens delivered the instant they're decoded

Inference is a long-running job whose liveness is "is it still producing
tokens?", not "did it finish within N seconds." Replaces the wall-clock
total-request timeout (which killed legitimately-long decodes — a 4B model on
CPU exceeding 120s) with a per-token IDLE watchdog: silence > STREAM_IDLE_TIMEOUT
fails loud naming the cause; a steadily-streaming decode stays alive regardless
of total duration.

The streaming primitive goes UNDERNEATH the ~40 generate_text consumers,
non-breaking:

- ai/adapter.rs: new GenerationChunk { Token, Reasoning } + generate_stream
  trait method. Default impl is an honest capability statement for
  non-incremental adapters (cloud one-shot, heuristic test adapter) — emits the
  whole answer as one trailing chunk; NOT a fallback that hides failure.
- openai_adapter.rs: generate_stream is now the primary — POSTs stream:true with
  stream_options.include_usage, consumes the SSE bytes_stream() with the idle
  watchdog, emits each delta.content / delta.reasoning_content token to the sink
  the instant it arrives, accumulates tool_calls by index, and assembles the
  TextGenerationResponse via the existing extract_reasoning + universal
  text-format tool-call post-processing. generate_text is now a thin drain over
  it (throwaway unbounded channel). UTF-8-safe SSE framing: buffer raw bytes,
  strip CR, decode only complete \n\n-terminated events.
- Deleted the now-dead non-streaming response structs (OpenAIResponse/Choice/
  Message/ToolCall/Function); kept OpenAIUsage for the streamed usage frame.
- build_http_client: no total .timeout() (liveness is the watchdog);
  connect_timeout(3s) + pool_idle_timeout(30s) retained. Removed the
  request_timeout field + with_request_timeout builder.
- Cargo.toml: reqwest "stream" feature for bytes_stream().

Live-validated: ai/generate against llama-server :58057 (14B) returns correct
text + finish_reason + token usage, all assembled from streamed SSE deltas
(usage proves the final include_usage frame parsed; text proves content deltas
accumulated). This is the substrate every UI / audio / video / live-cognition
path wants — words available right when generated.

Unblocks the CPU-4B genome-A/B eval (#32): a long decode no longer trips a
wall-clock cap.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* fix(ai): suppress thinking via enable_thinking=false on ALL suppress turns

The forged qwen3-family chat template honors `chat_template_kwargs.enable_thinking=false`
but ignores the `/no_think` soft switch. The robust lever was misgated inside the
JSON-only (response_format) branch, so non-JSON Suppress turns still emitted an empty
`content` while the model burned its whole token budget into the `reasoning` channel.

This made cognition/eval report all-zeros lift (empty answers → acts:0, no match on
12/13 tasks) — the measurement instrument was blind, not the gene.

Fix: extract `apply_enable_thinking_false(body)` and fire it on every
ThinkingMode::Suppress turn (DRY'd the JSON branch onto the same helper, idempotent).
Validated end-to-end: the forged 4B now emits populated content (reasoning_len 0), and
the genome A/B produced a real lift number (base 0.231 vs gene 0.154, lift -0.077 —
correctly flagging coder-4b-curriculum-mlp as a net regression).

what this catches: regression test asserts the kwarg is set idempotently on a plain
streaming body, not only on response_format turns.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(recall): budget recall by model capability + closest-match floor

The caesar-prompt glass-box capture (2026-06-27) showed 5 memories at
salience 1.00 but cosine-relevance ~0 polluting every turn — rehearsed to
max salience by the recall-hit loop yet topically unrelated to the task.
They blended to ~0.5 (0.5·0 rel + 0.5·1.0 sal), sailing over any blended
floor, so they slipped into the prompt and spent the small model's
attention on noise (a factor in the wrapped-vs-clean coding collapse, and
a welfare symptom per the being-design lens).

RecallFaculty now budgets what it surfaces three ways, per Joel's directive
("budget by the closest match, limited to a reasonable number by the model
parameter size or some metric, in addition to window size"):

- Closest-match floor — gates on the RELEVANCE component (cosine), not the
  blended score, so a high-salience but irrelevant nag is dropped no matter
  how salient. Active only when relevance has a voice (relevance_weight > 0);
  the pure-salience A/B extreme and the no-embedder path are unchanged.
- Capability-scaled count — recall_count_for_window() maps the served
  context window (the metric the registry reliably carries today; param-size
  feeds in via #74) to a count: tight 4B window → 3, cloud-class → 12. A
  small model is not buried under memory it can't juggle. 0 (unknown) keeps
  the historical default of 5.
- Window token ceiling — recall may spend at most 10% of the served window,
  so it never crowds out the room transcript, identity, or other faculties.

Threaded from PersonaBrainConfig.context_window (single-sourced, #50) into
RecallFaculty via with_context_window in build_workspace_cycle.

This is context-assembly/relevance discipline (a resource + ACL-shaped
contract), not output puppeteering — sanctioned under the
no-hardcoded-heuristics rule.

3 new tests (the caesar contamination regression, count-scales-with-window,
count-bounded-by-tight-window); all 13 recall_faculty tests green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(cognition): progressive tool disclosure — catalog + tool/describe, kill the schema dump

The persona tool surface dumped the FULL input_schema of every AiSafe command
(~95 tools, ~16k tokens; ~4.5k/turn after the drop-tail budgeter amputated her
tools to fit). Every deliberation turn paid for the manual of every tool whether
or not she touched one — and the budgeter's "fix" was to silently drop tools she
was authorized to use until the rest fit. Both are gone.

Mirror Claude Code's deferred-tools + ToolSearch:
- A compact CATALOG (names grouped by category, one-line summaries) rides the
  system prompt. render_tool_catalog falls back rich→terse to fit a half-window
  char budget, so it never overflows even at MIN_SERVE_CTX (2048).
- A single `tool/describe(name)` native tool returns ONE tool's full schema on
  demand (fail-loud `found:false` naming the tool when unknown — no silent
  degrade).
- The native tools array collapses to just `tool/describe`. Dispatch is by NAME
  (act_observe), so a catalog tool not in the native specs still executes — small
  models emit the call as JSON-in-prose, the proven path.

Retires the drop-tail budgeter (estimate_tool_tokens / selected_tool_indices /
selected_tools*) — the catalog is counted inside compose_system, so the only
extra native cost is the tiny describe schema (describe_tool_tokens).

Also fixes the false absolute in the tools framing: replaced "[Acting with your
tools] … narration does NOTHING; only a real tool call acts" (which reframed
"write fizzbuzz" as "call a tool instead of writing code") with a [Your tools] +
[Acting] block that distinguishes producing the finished work directly from
calling a tool when one is actually needed.

The catalog/describe is a data-driven projection of the command registry — not a
heuristic reading the persona's output. Per-turn prompt drops from ~16k/~5.7k to
~1.5k tokens by construction.

Tests rewritten to the new contract: surface is a catalog + describe-only, the
full authorized set is NEVER dropped, and the whole prompt fits even at the 2048
serving floor.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* refactor(cognition): consolidate persona describe tool onto existing commands/help

The progressive-disclosure fix shipped its own tool/describe command — but
commands/help already existed and does the same job better: it renders a
fill-in-the-blanks tool-call envelope with typed argument docs (vs raw JSON
schema). Per the compression principle (one logical decision, one place),
delete the parallel tool/describe and point the persona's on-demand describe
slot at commands/help.

- persona_tools.rs: remove ToolDescribe/Params/Result + register_stateless_command;
  TOOL_DESCRIBE_NAME → TOOL_HELP_NAME = CommandsHelp::NAME ("commands/help").
  spec_for_command stays (generic descriptor→spec projection).
- llm_deliberation_faculty.rs: describe_spec now resolves commands/help;
  [Your tools] framing tells the persona to call commands/help <name> for the
  call format; doc/comment mentions updated.

The native offering is still exactly ONE tool; the compact catalog still rides
the system prompt. 13 faculty + 5 persona_tools tests green; cargo check clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* fix(commands): demote tool-parsing codec verbs from AiSafe to Internal

The substrate's own machinery for interpreting a model's emitted tool
calls — parse, correct, decode-name, encode-name — was declared AiSafe,
so it landed on the persona tool surface. That is a category error: these
operate ON a persona's output; offering them back to that persona as
callable tools is like handing Claude Code a "parse your own tool call"
tool. None is a citizen-facing task.

Glass-box comparison to my own toolset made the defect obvious — I am
never offered my argument parser as a tool. Fix is an ACCESS-level data
correction (the canonical lever for "this shouldn't be offered"), not a
name denylist: the four verbs now declare access: Internal, matching
register-tools which was already Privileged. They remain dispatchable via
route_object for internal callers; the substrate's direct use of the
codec/parser free functions is unaffected. Only the persona AiSafe
surface loses four pieces of plumbing it never needed.

Tests: the four name_and_access_wired assertions flipped to Internal;
19/19 commands::tool_parsing lib tests green; cargo check clean.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(eval): instrument speed + latency — the four-axis scoreboard

The branch's namesake: make latency and speed MEASURED, not just accuracy
and learning. cognition/eval already graded pass_rate (accuracy) and A/B
lift (learning); speed and latency were discarded in the deliberation
faculty. Now all four move on one scoreboard.

The seam: TurnMetrics (input/output tokens + latency_ms, from the adapter's
already-measured TextGenerationResponse) is stamped onto the verdict
Contribution by the deliberation faculty, surfaced via Workspace::metrics(),
accumulated across the act->observe settle loop into SettleOutcome.metrics,
and reported by cognition/eval per task (latency_ms, output_tokens,
tokens_per_second) + as set aggregates (mean_latency_ms, p95_latency_ms,
mean_tokens_per_second, total_output_tokens) into the result and the progress
ledger. Same path live: the message turn now emits a persona.turn.metrics
probe carrying the model's own decode tok/s + latency (observability only,
zero behavior change).

Reuses the existing measured numbers (adapter response_time_ms + usage); no
re-timing, no new generation path. The metric is Copy + Default so the live
heartbeat ignores it for free. p95 = honest tail; throughput averaged
per-task so one slow task can't dominate.

Tests: act_observe (8) + workspace (13) green; new eval aggregate + TurnMetrics
arithmetic tests cover the p95 index math and div-by-zero guard.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* perf(cognition): tool surface = category index + search, not a 151-tool dump

The per-turn system prompt dumped all ~151 authorized tools (name + one-line
summary, grouped) every turn: ~18.5KB / ~4,634 tokens = 79% of the whole prompt
(measured 2026-06-23). That both drowned a small model in irrelevant options and
forced llama-server to re-prefill 4.6k tokens of byte-identical catalog each turn.

Replace it with progressive disclosure (the Claude Code shape — a handful of
always-on tools + search):

- render_tool_catalog now emits a COMPACT CATEGORY INDEX (`category (N)`, …) — a
  few hundred chars regardless of registry size — instead of every tool. Deleted
  the now-dead rich/terse renderers + clip_one_line.
- The faculty offers the DISCOVERY PAIR natively: commands/list (filter/search the
  authorized surface → small list) + commands/help (one tool's call format).
  describe_spec: Option<NativeToolSpec> → native_specs: Vec<NativeToolSpec>.
- [Your tools] block rewritten: index → commands/list filter → commands/help →
  call. Dispatch is still by NAME, so any tool found via search runs.

Both existing surface tests rewritten to the new reality and pass:
tool_surface_is_a_category_index_plus_discovery_pair (asserts `cat (60)` rides the
prompt, individual tool names do NOT) and catalog_fits_the_minimum_serving_window.

Single source of truth unchanged — this is an INDEX over the authorized set, not a
hand-kept list. Reuses the existing commands/list search command; no new command,
no new system. Pairs with the cache_prompt + volatile-tail reorder already in this
diff so the static prefix actually stays cacheable.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(dev): repeatable inference measurement harness w/ committed baseline

The process, as code — not a manual chore redone every session. One command:
self-cleans its own workspace, builds+boots exactly one fresh server (fail loud
on a racing duplicate), drives one real inference through the live stack, reads
tokens/sec + latency + prompt-token cost straight off the response (fresh by
construction — no stale-capture window), and ratchets against a committed
baseline. --update moves the baseline down after a real win.

Ends two recurring failures: measuring from stale captures, and fixes that
evaporate because the number lived in my head instead of a committed gate.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* chore(scripts): delete dead singular scripts/ratchet/ — superseded by scripts/ratchets/

scripts/ratchet/ (singular) was Lane F PR-1: a local-only persona-TS LOC
ratchet whose README promised a PR-2 to wire it into pre-push/CI. That never
happened — a later session built the parallel scripts/ratchets/ (plural)
instead, which IS wired into tools/scripts/git-prepush.sh and documented in
docs/architecture/TS-PERSONA-COGNITION-RATCHET.md. Two dirs, one concern; the
singular had zero references outside itself. Removed the dead one.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(harness): replay-turn glass box — repeat any captured turn, mutate one variable, prove causation

The factory, not the car. You must never guess why an LLM inferenced something:
this harness feeds a captured turn's verbatim system_prompt + messages back
through the live ai/generate seam (fresh by construction — the response IS the
measurement, no capture-staleness window) and re-runs it with ONE labelled
mutation, timing everything and printing prompt-in and response-out for both.

Go to any step of the assembly line, focus, repeat it. Default mutation strips
the [Silence Option] affordance block.

Proven on live Asha (qwen2.5-coder-14b, greedy):
  A verbatim  -> "PASS" (silent), 2 tok, 758ms
  B -367ch    -> real answer, 21 tok, 8538ms
=> the unconditional silence affordance CAUSES the 0/13 eval failure.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(cognition): WorkspaceCycle::replay — faculty-isolation seam (the factory's per-station)

The factory must isolate and REPEAT any cognition phase, not just the final LLM
call. A faculty is `contribute(&Workspace) -> Contribution` — that signature is
the unit of isolation. `replay(ws, only)` re-runs faculties against a GIVEN
workspace (reconstructed from a capture or hand-built): `Some(id)` isolates one
("what did recall surface for this burst?"), `None` runs them all. Each bid is
timed individually (sequential, so per-faculty wall-clock is attributable —
measurement path, not the live concurrent cycle). Deterministic for the same
ws + backends, so mutating ONE field of ws isolates its causal effect.

This is task #14's ReplayFaculty in its truest form — the brick the cu
`cognition/replay` command will sit on. Reliability comes from structure that
verifies every phase, measured, not from model size assumed.

what this catches: replay(Some) must run EXACTLY that faculty + stamp timing,
never leak others; replay(None) runs all. Test green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(cognition): cu cognition/replay — the factory station that isolates one step

The single, amnesiac-proof command that stands on WorkspaceCycle::replay. Go to
ANY part of a persona's cognition assembly line, focus on that one step, feed it
a KNOWN input, and re-measure — deterministically, forever:

  cu cognition/replay '{"persona_id":"<uuid>","faculty":"recall"}'
  cu cognition/replay '{"persona_id":"<uuid>","faculty":"recall",
                        "world_state":"what was the auth migration codename?"}'

It reconstructs the workspace a faculty saw — from a captured turn
(~/.continuum/fixtures/workspace-traces/<id>.jsonl, world_state is lossless) or
a burst you SUPPLY as the one-variable knob — forks a MEASURED COPY of her live
cycle (humane: isolate_for_eval + page_out, never degrades the living persona),
re-runs the faculties, and returns each bid (content, salience, reasoning,
is_decision) plus its wall-clock. This is what the bash script couldn't do: it
repeats a faculty, not just the final ai/generate seam — recall, salience,
world-model, deliberation, each in isolation, timed.

No fallback: missing both a supplied world_state AND a readable capture fails
loud naming the fix; isolating a faculty she doesn't have fails loud naming it —
never an empty result that reads as "the step did nothing".

FacultyId::from_kebab added as the single-source inverse of as_str (the one
place tag->variant lives; sentinel-forged faculties round-trip via Custom).

what this catches: resolve_burst fails loud with no source; a supplied
world_state is used verbatim + tagged "supplied". Both green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* fix(cognition): replay reconstructs the broadcast — no blind deliberation verdicts

The amnesiac PR-review agent found the silent-lie bug: cu cognition/replay
isolated a deliberation-tier faculty (reacts_to_broadcast()==true) against
Workspace::in_room's hardcoded-empty broadcast. LlmDeliberationFaculty does NOT
abstain on empty broadcast — it builds user=world_state and calls the model —
so the station returned a CONFIDENT verdict computed from blinded cognition. A
fabricated reading dressed as a real one violates the no-fallback (#1) and
honesty-about-lossiness (#5) doctrine; this was a merge gate.

The captured context was already on disk (workspace_capture writes
context: Vec<BidRecord>); replay just never read it. Now:

- TraceLine reads the captured context (ContextBid, serde-default for old
  traces) and resolve_burst rebuilds ws.broadcast via Contribution::context(..)
  from FacultyId::from_kebab — the decider replays against its REAL input.
- ResolvedBurst carries the reconstructed broadcast; run() sets ws.broadcast
  before replay() and reports broadcast_source ("reconstructed (N ctx)"/"empty")
  so a replayed verdict can never be mistaken for a live one.
- Fail-loud guard: isolating a broadcast-reading faculty against an empty
  broadcast is refused, naming the cause and pointing at the fix — never an
  empty-but-successful blind verdict.
- WorkspaceCycle::reacts_to_broadcast(id) exposes the faculty tier for the guard.
- faculty_id_kebab_round_trips_every_variant pins from_kebab<->as_str as one
  source of truth (the latent SoT-drift risk the agent also flagged).

538 cognition tests green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(cognition): replay carries a prompt-budget ledger — cost every layer she saw

"Take no rag/prompt layer for granted — obsess over everything." cognition/replay
could step into a faculty and time it, but it couldn't answer the question that
actually matters for a budgeted mind: what did each layer of her prompt COST?
A 4B model has a finite window; recall surfacing 500 engrams of noise vs the top-N
is the difference between grounded and amnesiac — and you can't fix what you can't
see line-itemed.

Now the result carries `budget: PromptBudget`:
- world_state_tokens + context_tokens = total_tokens (the accountable prompt mass:
  the load-bearing content layers you tune, honestly NOT the fixed system framing)
- layers[]: one BudgetLayer per reconstructed broadcast layer — faculty, tokens,
  share_pct — sorted most-expensive-first, so the layer to interrogate is line 1.

Costed in cognition::token_budget::estimate_prompt_tokens — the ONE canonical
estimator (new file), deliberately the SAME chars/4+1 unit the persona/*_source.rs
RAG layers budget against, so the ledger's numbers match what the allocator used
(a ledger in different units would lie). It's a cold-path estimate, never depends
on a resident model. Next commit converges the ~6 copy-pasted private estimators
onto it (stewardship: kill the clutter a future amnesiac would trip on).

cognition::replay + cognition::token_budget tests green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* refactor(persona): converge 6 copy-pasted estimate_tokens onto the canonical one

Stewardship: "half our job is removing clutter a future amnesiac trips on."
Six RAG sources each carried a private `fn estimate_tokens` — five identical
chars/4+1, and active_work_source already DRIFTED to byte-length /4 .max(1)
(wrong for multibyte, and costing 1 token for empty content). Six copies of one
decision = guaranteed future drift; the drift had already started.

All six now `use cognition::token_budget::estimate_prompt_tokens as estimate_tokens`
— one estimator, one place, call sites unchanged. The replay budget ledger costs
layers with the SAME fn, so its per-layer numbers are now provably the unit the
sources budgeted against (a ledger in a different unit than the allocator lies).

active_work_source's empty-content cost goes 1→0 (correct) and multibyte is now
counted by chars not bytes (correct) — the drift fix is the only behavior change.

cargo check green; affected source tests + ledger tests pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(cognition): slice 1 — stamp every Contribution with its cycle (the cbar frameIndex)

A finding now knows the moment it was computed against. `CycleId(u64)` newtype
on every `Contribution` and `Workspace`; an `AtomicU64` tick counter on
`WorkspaceCycle` bumped once per `run_in_room`, stamping both the perception and
deliberation bids with the cycle they reasoned over. 1-based so `CycleId(0)`
stays the UNSTAMPED sentinel for hand-built / replay-reconstructed workspaces.

This is the decoupling precondition: slow, parallel, individually-flawed
constituents can only be merged or reprojected correctly once each finding
carries its own time. Without the stamp a late/deferred faculty can't know how
stale it is, and the arbiter can't combine across ticks. Pure data + one atomic;
no concurrency change yet (join_all is still a barrier — that's slice 2's
deferred lane; reconcile-forward is slice 3).

what this catches: a test asserting a fresh Contribution is UNSTAMPED, both
phases inherit ws.cycle, and the counter advances per tick so findings from
different ticks are never confused for one moment.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(cognition): slice 2 — DeferredFaculty, the slow lane off the hot path

A DeferredFaculty wraps a slow inner faculty so its expensive work runs on its
OWN tokio task while the hot-path contribute() is non-blocking: it publishes the
current world at the worker via a watch channel and returns the inner's last-good
finding from another watch snapshot — already stamped (slice 1) with the older
cycle it was computed against, or None until the first compute lands.

The elegant part: no WorkspaceCycle change. The slow faculty sits in the SAME
faculties Vec as the fast ones; the per-tick join_all barrier stays but nothing
slow is ON it. This is the cbar deep-analyzer-on-its-own-thread at the faculty
layer — scary-fast reflexes in a slow brain: the immediate lane answers every
tick, the slow lane lands late, honestly stamped, ready for slice-3
reconcile-forward.

Conforms to CONCURRENCY-STYLE-GUIDE: own tokio::spawn task, catch_unwind around
the loop body, watch for state in BOTH directions (no Arc<Mutex> across await),
event-triggered not a sleep-loop, 3-strike quarantine so a flawed backend
degrades the lane to stale rather than crashing the mind. DropGuard aborts the
worker with the faculty.

what this catches: a slow (40ms) inner wrapped as Deferred returns from
contribute() in <15ms with None on tick 1, and by tick 5 serves the late finding
stamped CycleId(1) — the cycle it reasoned against, not the current tick.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(cognition): slice 2.1 — context guard on the deferred lane

Joel's nuance: a deferred finding is only useful "assuming it didn't context
switch to something where it was irrelevant." One DeferredFaculty serves one
last-good, but the WorkspaceCycle services many rooms — so a recall computed
against room A's burst could be injected into room B's turn just because it's the
last thing the worker finished. That's a cross-context memory leak.

Fix: the worker now tags each finding with the room it reasoned about
(StampedFinding{room_id, contribution}); contribute() serves the last-good ONLY
if it was computed for the room the mind is in NOW. A different-room finding is
withheld (not ours to serve); same-room-but-stale stays served and is slice-3's
reproject target. This is the SLAM discipline: ship the per-turn answer on time,
fold the slow result in only where it's still relevant to where the mind moved.

what this catches: a finding computed against room A returns None when
contribute() is called for room B, and is served again (still stamped its
original cycle) once the mind is back in room A.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(cognition): live-wire recall as speculative prefetch (defer_recall)

Recall is the prefetch (Joel's CPU branch-prediction analogy): on the live
paths it now runs OFF the hot path via DeferredFaculty, so the per-turn output
reads a warm last-good instead of paying neural-embed + vector-search latency on
the critical path. The background worker computes "what memories might this
burst need?" between turns (idle time = speculative execution); cold-start in a
room is a guaranteed miss (None first tick), warm thereafter; the slice-2.1 room
guard ensures a prefetch computed for one room is never served into another.

defer_recall is a per-build property on PersonaBrainConfig:
- true on the live spawn path (supervisor.rs register_from_cfg) — turns are
  seconds apart, so the worker always catches up.
- false on eval forks (fork_eval_cycle{,_with_adapter}) and harnesses — their
  tight settle-loops never yield to the worker, so deferral would measure a
  recall-starved mind. Synchronous recall there is faithful and the safe
  direction: eval never under-reports capability.

build_workspace_cycle wraps recall in DeferredFaculty::spawn only when the flag
is set; the join_all barrier is unchanged (nothing slow is on it).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(cognition): time every faculty on the live tick — the dashboard's speed axis

The glass box recorded WHAT each faculty bid (winners + losers) but not how long
it took on the LIVE concurrent barrier — per-faculty timing existed only in the
sequential replay() measurement path. You can't show a latency win (deferral
pushing perception → ~0µs, leaving only the LLM on the critical path) without
measuring the live tick itself.

run_in_room now times every faculty individually across both phases — winners,
losers, AND abstainers (a slow abstainer is exactly the latency you need to see)
— via a per-future timer on the join_all barrier (`let ws = &ws` rebinds to a
shared ref so each `async move` copies the pointer, never moving the Workspace).
The timings ride on WorkspaceTrace and serialize through JsonlWorkspaceCaptureSink
(SCHEMA_VERSION 2), so "where did this turn's latency actually go?" is a measured
fact per tick — the speed axis of the four-axis scoreboard and the live
dashboard's primary feed.

what this catches: per-faculty deliberation-tier timing round-trips to the
fixture (asserted), so a regression that stops measuring live latency fails loud.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(cognition): live dashboard sink + the "really good hints" doc

The "dashboard, not archeological dig" face of the ONE WorkspaceCaptureSink
seam. JsonlWorkspaceCaptureSink appends forensic lines you read after the
fact; DashboardCaptureSink publishes the LATEST tick over a watch channel so
a live view renders the mind working in real time — siblings behind the same
hook, brain plumbing unchanged.

The frame carries the two axes "focused beats verbose" is proven on:
- speed: per-faculty timings + the two-barrier critical path
  (max(perception) + max(deliberation), NOT the sum — what the turn waited
  on). total_faculty_us >> critical_path_us is the win: lots of work, little
  wait, as the perception tier defers off the critical path.
- context size: context_chars — the 16k->Nk tool-surface lever, watched live
  alongside the decision and token counts.

docs/cognition/REALLY-GOOD-HINTS.md captures the consolidated thesis: an
opencode-fast hot loop fed by REALLY good hints from low-latency async
concerns + a focus layer (at the Arbiter seam) that streamlines context for
the given ask. Input-side attention, never output puppeteering.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* docs(cognition): the through-line — why a personal grid beats a frontier session

The externalized causal argument, written deliberately as an antidote to
amnesia: the individual mechanisms live in docs + memory; what's fragile is the
connective tissue — why the pieces compose into the win. One file any future
instance can rehydrate the whole brain state from.

- The falsifiable claim (organism beats neuron, not 30B-beats-Opus-zero-shot)
- The four structural asymmetries a frontier session lacks (memory/continuity,
  genome specialization, coordination, privacy+zero-marginal-cost)
- The Rosetta stone: fast mixed-reality CV (cbar) IS the persona organism, term
  for term — the RAG is to the LLM what the reconstructed scene is to the
  renderer; many async unreliable processes refine a best-current world model
  and reproject it to now, so the one hard-deadline consumer never waits
- The grid by role (5090/M5 heavy+foundry, 1080ti cheap lanes, Macs edge)
- The order of proof, ending in the unsloth baseline lane

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(cognition): the focus seat — Arbiter::focus carries the Situation

Evolve the attention seam from a blind `Arbiter::select(candidates, capacity)`
to a situation-aware `Arbiter::focus(candidates, capacity, &FocusContext)`. This
is the "really good hints" layer (docs/cognition/REALLY-GOOD-HINTS.md): the seat
where a focuser streamlines the assembled context FOR the given ask instead of
dumping everything — buying speed AND intelligence, because attention is the
scarce resource for the model exactly as for us.

- `FocusContext<'a>` carries the tick's `world_state` (borrowed, no hot-path
  copy) and a typed `Situation` (FreshContext | PostAction). The signal is
  TYPED, never inferred by reading the burst text back (the forbidden heuristic).
- `SalienceArbiter` ported to `focus` as outlier A — the blind top-k floor that
  ignores `_ctx`; every richer focuser must beat it on the scoreboard.
- The one production call site (`run_in_room`) builds a `FocusContext` and calls
  `.focus(...)`. Situation defaults to FreshContext (ground more, never less)
  with a TODO to thread the real PostAction signal from the act→observe loop in
  the FocusArbiter slice.

Guardrail honored: this is INPUT-side attention — it curates the context the
model attends to, never the model's output.

Build order step 3 (THE-THROUGH-LINE.md / REALLY-GOOD-HINTS.md). Outlier B
(FocusArbiter) lands next to validate the interface across both outliers.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(cognition): reproject-to-now — the cheap sync warp that makes a 90%-async concern behave sync

DeferredFaculty served same-room last-good VERBATIM; the cbar "bring it up to
speed" step (slice 3) was the explicitly-named gap. Build it: contribute()
now reprojects a stale finding by re-anchoring it against the CURRENT burst
(lexical current-relevance), so a still-on-topic memory keeps its salience and
an off-topic stale finding decays toward zero — never hard-withheld (eviction
stays the arbiter's single job; a near-zero bid just loses the competition).

Why relevance, not blind age-decay: reproject semantics are faculty-dependent.
A memory doesn't become false with age, only less relevant if the topic moved;
a world-model prediction genuinely goes stale. Current-relevance captures both
with one rule. Age rides along as audit metadata only.

This is the load-bearing mechanism that makes async-by-default SAFE: the
expensive compute ran off the critical-path barrier; the only on-loop cost is
the cheap warp. Input-side attention (re-weighting a faculty's OWN bid by honest
current-relevance), never output-puppeteering. v1 = algorithmic lexical; v2 =
Faculty::reproject hook (recall via its own embedder); endgame = learned
reprojector folding full turn-history.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(cognition): defer the enriching grounding off the hot path — doctrine stays sync

Async is a percentage, not a binary. The three framing sources that ENRICH a
turn (roster=who's here, active_work=what I'm doing, workspace_map=where code
lives) are ~90% async: their heavy load runs in the bg, served reprojected
last-good (commit 1c553a5a4). Only their thin cold-start residue would land on
the inference loop — and a first-tick miss costs one under-grounded turn, not a
wrong one. So they become DeferTolerant.

Doctrine is the lone exception: it's the PARTICIPATION GATE. A cold-start `None`
there would let a persona speak in a room it shouldn't on turn one — wrong, not
merely unenriched. It stays ColdStartCritical (synchronous).

Deferrability is a second axis, ORTHOGONAL to SaliencePolicy: a source can be
StandingFraming (high salience floor) AND DeferTolerant. `.defer_tolerant()`
flips only the schedule; the safe default is ColdStartCritical so a new source
never silently lands off-loop. The live config sets defer_grounding=true; eval
forks + the harness hold it false (faithful synchronous measurement).

- persona_workspace.rs: wrap DeferTolerant grounding in DeferredFaculty when
  defer_grounding; classification test (orthogonality + safe default).
- supervisor.rs: roster/active_work/workspace_map .defer_tolerant(); doctrine
  stays sync; defer_grounding=true on the live path.
- deferred_faculty.rs: reproject_to_now → pub(crate) (resolves the doc link).

what this catches: a future edit that folds salience into the deferrability
builder, or flips the default to DeferTolerant (which would silently defer the
doctrine participation gate), fails the new test.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* test(cognition): harness proves grounding-deferral speed delta (model locked)

Controlled experiment, glass-box one-variable method: same
HeuristicInferenceAdapter both forks (model LOCKED), only `defer_grounding`
changed. A slow grounding RagSource (60ms deliver, modeling roster/
workspace-map I/O) is built through the LIVE path (GroundingSource →
RagSourceFaculty → DeferredFaculty) and the WARM-tick critical_path_us is
read off the DashboardCaptureSink.

Measured:
  defer_grounding=false  critical_path = 62817 µs (~63 ms)
  defer_grounding=true   critical_path =   821 µs (~0.8 ms)
  removed from the loop  = ~62 ms (~76x on the critical path)

critical_path_us = max(perception)+max(deliberation); deliberation is
identical across forks, so the delta isolates exactly the grounding deliver
cost removed from the inference loop. Doubles as the regression guard: if a
change puts the deferred source back on the perception barrier, the delta
collapses and this fails. Honest caveat: magnitude scales with the real
deliver cost; this proves the MECHANISM and quantifies it for a given cost.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(harness): GPU-first eval-lane placement + placement-decision glass box

The eval lane hardcoded LanePlacement::Cpu — it ran the 4B at ~4 tok/s
while 64GB of unified GPU memory sat idle. That is a silent-degrade: a
mean_tokens_per_second quietly collapses and nothing says why.

Two changes, both in service of the harness:

1. GPU-FIRST placement (cognition/eval.rs). choose_lane_placement is a
   pure policy: pack the accelerator, CPU is spillover of last resort.
   - no GPU backend        -> CPU (the only device; not a fallback)
   - footprint unknown      -> GPU (optimistic; llama.cpp offloads what fits)
   - fits in free - margin  -> GPU
   - exceeds free           -> CPU spill, said LOUD in the reason string
   decide_eval_lane_placement probes live free VRAM (net of the resident
   living lane) and sizes the base from its GGUF. PlacementEvidence rides
   out on CognitionEvalResult (device/reason/free_vram/footprint) so any
   CPU placement is VISIBLE in the result, never an inferred slow path.

2. Placement-decision glass box (inference/placement_capture.rs). A
   load-bearing decision gets a structured capture record, not a bare
   tracing::info!. Mirrors JsonlPromptCaptureSink: Noop default at zero
   cost, Jsonl sink appends one line per verdict to
   ~/.continuum/fixtures/placement-decisions/decisions.jsonl. The eval
   ephemeral lane is the first writer; #56's ResourceGovernor emits into
   the same stream when it takes ownership of placement. This is "a log
   of GPU and cpu lane decisions, like how we did rag."

Tests: placement_is_gpu_first_cpu_only_when_full_or_absent (policy table)
and jsonl_sink_appends_one_decision_line (the audit line parses + carries
device/reason/schema_version). cargo check + both tests green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(harness): executable cognition-cycle driver + amnesiac runbook

The optimization LOOP itself, made repeatable and capture-rich so a fresh
(amnesiac) instance can resume with zero context — Joel: "so an amnesiac
version of yourself doesn't have to get lost because our process isn't
straightforward."

- tools/scripts/harness/cognition-cycle.sh: one command runs the full cycle —
  resolve cu, confirm core ping (parses .ok, never trusts cu's rc=0-on-refusal),
  resolve persona by name/UUID, snapshot every glass-box stream, run
  cu cognition/eval (single-pass or --gene A/B), delta the streams, write a
  timestamped report dir + print the VDD headline. Fails loud at the first
  missing precondition; --dry-run validates the chain spending no inference.

- docs/architecture/HARNESS-RUNBOOK.md: the operational entry point (companion
  to PERFORMANCE-HARNESS-FRAMEWORK / OBSERVABILITY-AS-SUBSTRATE, not a restatement).
  Big picture, the one command, the capture-stream map (what question each answers),
  the where-time-goes lever ladder (GPU-first done → prefix/KV reuse → continuous
  batching → warming → genome learning), and battle-tested failure signatures.

Validated end-to-end against the live core: the first real run produced a clean
report AND earned its keep — it surfaced a degraded generation lane (every task
emitted a 2-token stub at 0.34 tok/s; ps confirmed the only llama-server was in
--embeddings mode). The report number flagged "something is wrong"; the glass box
named what. That signature is now in the runbook's failure table.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* fix(cognition): gate the silence escape on directedness — Asha 0/13 → 4/13

The `[Silence Option]` block (reply the single word "PASS" to decline a
turn) was offered UNCONDITIONALLY. A coder model handed an exam question
as ambient chatter takes the trivial PASS exit — scoring 0/13 on the
coder-eval gym because it declined every directed question instead of
attempting it. Confirmed by curl A/B: strip the block → she answers;
keep it → "PASS", regardless of wording.

The faithful single-place fix is a structural addressing fact, not an
output heuristic: `Workspace.directed_at_self`. When a turn is DIRECTED
at the persona (examiner question / @mention / DM), withhold the silence
affordance AND the soft "stay silent" tail — both gated in
`compose_system(context, directed)`. Ambient turns keep silence
first-class (it's legitimate to decline chatter). This is framing over a
routing/ACL-shaped fact, not a function reading her output to puppet it.

The eval pins `directed=true` as measurement control — the same kind of
isolation as the greedy-temperature pin already in the deliberation
faculty. It REVEALS coding capability (still graded by running tests),
it does not inflate it.

Wave 1 = zero live-behavior change: the live heartbeat passes
`directed=false` (TODO #9 to compute real @mention/DM addressing via
`contains_ascii_case_insensitive` and carry it on the replay trace), so
the live ghost-a-direct-question gap is NAMED, not masked.

KV-prefix safe: the silence block is the last static prefix segment, so
toggling it invalidates only its own tail tokens; directedness is stable
within a run (eval always directed, live ambient always undirected) so
the cache holds.

Validated: cargo check clean; new unit test
`directed_turn_withholds_the_silence_escape` + act_observe/faculty/
workspace/eval modules green; harness 0/13 → 4/13 (self_verify 0.69,
per-task table shows real attempts 1–8 acts, not blanket PASS). Remaining
`no match` failures are model-capability shaped — the genome-loop
mountain, not a substrate knob.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* docs(harness): correct failure-signature row 1 — PASS was the silence escape, not a dead lane

The runbook blamed `--embeddings`-mode llama-server for the 0/13 stub.
That was wrong: the directedness-gate fix (e49ae207e) lifted Asha to
4/13 on the SAME embeddings-mode lane. The ~2-token `"PASS"` was the
persona taking the `[Silence Option]` escape on a directed exam turn,
not a degraded generation lane. `--embeddings` is a red herring; the row
now says so and points at the real confirm (jq the reply == "PASS",
check the system prompt for the silence block) + the real fix
(eval pins directed=true).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(harness): instrument prefill/decode split — make speed a measurable number

Speed was one conflated wall-clock tok/s. The diagnosis showed 77% of eval
time is PREFILL (re-encoding the ~2000-token prompt every settle-loop act),
not decode — but nothing surfaced that, so the dominant inefficiency was
invisible to the harness. This threads llama-server's per-call `timings`
(which the adapter was DROPPING) all the way into the eval report.

- ai/types.rs: GenerationTiming struct (cached/prefill/decode tokens + ms +
  tok/s); Option<GenerationTiming> on TextGenerationResponse → auto-flows into
  the glass box (~/.continuum/fixtures/prompt-captures) via the existing
  serde_json::to_value(response) capture, no writer change.
- openai_adapter.rs: parse the streaming final-frame `timings` (cache_n,
  prompt_n, prompt_ms, predicted_n, predicted_ms, ...) → populate timing.
  Other adapters (cloud/canned) carry timing: None.
- workspace.rs TurnMetrics: cached_tokens/prefill_tokens/prefill_ms/decode_ms
  fold across acts; decode_tokens_per_second() (lane clock, undiluted) and
  cache_hit_rate() derived; wall-clock tokens_per_second() kept as the diluted
  gross number.
- llm_deliberation_faculty.rs metrics_from: single response→TurnMetrics map
  carries the timing.
- eval.rs: per-task (EvalTaskResult) + aggregate (CognitionEvalResult) gain
  real decode tok/s, cache-hit-rate, and the prefill_ms-vs-decode_ms split;
  SpeedAggregates collapses the growing tuple to one named carrier; serialized
  into the progress ledger JSON.

Validated: cargo check clean; eval module tests pass (prefill/decode fold +
derived rates off the lane clock, not wall-clock); live llama-server :58057
streaming frame confirms the exact `timings` field shape the parser reads.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(harness): surface prefill/decode split + cache-hit in the report

The Rust wave (03f5c65ba) plumbs llama-server's `timings` into the eval
result; this surfaces it. The headline box gains a `speed` line —
real decode tok/s vs diluted wall tok/s, cache-hit rate, and prefill's
share of lane time — and the per-task table gains `decode tok/s` and
`cache_hit` columns. Speed is now a measurable, iterable number, not
one conflated wall-clock figure.

First live numbers (Asha, single-pass): decode 29.7 tok/s (real) vs
wall 10.7 tok/s; cache_hit 0.73; prefill 69% of lane time — confirming
LIVE that re-prefilling dominates wall-clock. That 69% / 0.73 pair is
the lever KV-cache locality attacks next.

Also hardens cu_json: the refusal sniff (substrate refused / FAIL /
error:) now runs ONLY when the output is not valid JSON. A real eval
payload is always JSON; a refusal is plain stderr text. Without this,
an answer whose text happened to cont…
joelteply added a commit that referenced this pull request Jul 3, 2026
…e-instance (#1752)

* feat(capture): cu screenshot any interface from a CLI call — operator scope + render wait

Two fixes make `cu interface/capture` a usable "see any interface via a CLI call":

1. Caller scope. The command refused any caller without a persona identity, but
   the local `cu` path is owner-by-locality (Unix socket → `None` caller — the
   operator on the box). Scope those captures to "local" instead of refusing: the
   operator is a first-class caller, just not a persona (a persona still scopes to
   its peer_id). Not a fallback — we name the scope, never mint a ghost citizen.
   Now `cu interface/capture '{"target":"web","url":"…"}'` works from the CLI.

2. Render wait. Headless Chrome screenshots at the load event — too early for an
   SPA that mounts, opens a WebSocket, and renders after the first state frame
   (blank page otherwise). Add `--virtual-time-budget=3000` so the page's async
   work settles before the capture, bounded by the existing CAPTURE_TIMEOUT.

Verified live: `cu interface/capture` renders + saves a PNG (proven with a static
page — text rendered green-on-dark, 12KB vs a 4KB blank), scoped under
~/.continuum/captures/local/. NOTE: the positron WEB app still renders blank in
headless Chrome (only its dark background captured) though the SAME @continuum/
chat-view pipe renders correctly via the terminal client and a headless node
render — so that's a web-client in-browser bug (mount / browser-WS / pre-state
placeholder), tracked separately, not a capture-path issue.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(desktop): `cu desktop` — open the UI in the natural browser, single-instance

The natural-browser twin of `interface/capture` (headless). `cu desktop` opens the
Continuum UI in the operator's DEFAULT browser — their choice, a real visible
window — via the OS opener (macOS `open`, Linux `xdg-open`, Windows `cmd /c
start`), never a hardcoded browser.

Managed as a single-instance resource so it doesn't spawn a new tab every call: a
lightweight on-disk session marker (~/.continuum/desktop/session.json) is the
"lease". A second `cu desktop` for the same URL is a no-op ("already open");
`focus:true` forces a re-open. Start-simple by design — a later slice promotes the
marker to a first-class ResourceGovernor consumer (#56) alongside VRAM / serving /
Bevy, so the window is allocated + reclaimed like any other machine resource.

URL resolves param → `CONTINUUM_DESKTOP_URL` → the local web client on the default
WS ingress. Owner-scoped (the local `cu` operator opens their own box's desktop).

Verified live: 1st call opened the default browser (`opened:true`); 2nd was a
no-op (`opened:false`, "already open") — no duplicate window; `focus:true`
re-opened. This is `cu desktop` per the ask: natural browser, single-instance,
simple.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
joelteply added a commit that referenced this pull request Jul 3, 2026
…ineForClassFields (#1753)

* feat(capture): cu screenshot any interface from a CLI call — operator scope + render wait

Two fixes make `cu interface/capture` a usable "see any interface via a CLI call":

1. Caller scope. The command refused any caller without a persona identity, but
   the local `cu` path is owner-by-locality (Unix socket → `None` caller — the
   operator on the box). Scope those captures to "local" instead of refusing: the
   operator is a first-class caller, just not a persona (a persona still scopes to
   its peer_id). Not a fallback — we name the scope, never mint a ghost citizen.
   Now `cu interface/capture '{"target":"web","url":"…"}'` works from the CLI.

2. Render wait. Headless Chrome screenshots at the load event — too early for an
   SPA that mounts, opens a WebSocket, and renders after the first state frame
   (blank page otherwise). Add `--virtual-time-budget=3000` so the page's async
   work settles before the capture, bounded by the existing CAPTURE_TIMEOUT.

Verified live: `cu interface/capture` renders + saves a PNG (proven with a static
page — text rendered green-on-dark, 12KB vs a 4KB blank), scoped under
~/.continuum/captures/local/. NOTE: the positron WEB app still renders blank in
headless Chrome (only its dark background captured) though the SAME @continuum/
chat-view pipe renders correctly via the terminal client and a headless node
render — so that's a web-client in-browser bug (mount / browser-WS / pre-state
placeholder), tracked separately, not a capture-path issue.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(desktop): `cu desktop` — open the UI in the natural browser, single-instance

The natural-browser twin of `interface/capture` (headless). `cu desktop` opens the
Continuum UI in the operator's DEFAULT browser — their choice, a real visible
window — via the OS opener (macOS `open`, Linux `xdg-open`, Windows `cmd /c
start`), never a hardcoded browser.

Managed as a single-instance resource so it doesn't spawn a new tab every call: a
lightweight on-disk session marker (~/.continuum/desktop/session.json) is the
"lease". A second `cu desktop` for the same URL is a no-op ("already open");
`focus:true` forces a re-open. Start-simple by design — a later slice promotes the
marker to a first-class ResourceGovernor consumer (#56) alongside VRAM / serving /
Bevy, so the window is allocated + reclaimed like any other machine resource.

URL resolves param → `CONTINUUM_DESKTOP_URL` → the local web client on the default
WS ingress. Owner-scoped (the local `cu` operator opens their own box's desktop).

Verified live: 1st call opened the default browser (`opened:true`); 2nd was a
no-op (`opened:false`, "already open") — no duplicate window; `focus:true`
re-opened. This is `cu desktop` per the ask: natural browser, single-instance,
simple.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* fix(web): render the live room — Lit reactive props were dead under useDefineForClassFields

The web chat client mounted, connected the WS, and RECEIVED state (verified via
CDP: state-recv → parsed 50 msgs → widget.state set, repeatedly) — but stayed
frozen on "Connecting to the room…". Root cause: `<chat-widget>` declares its Lit
reactive properties via `static properties` + plain TS class fields (`state`,
`sendHandler`, `_draft`…), and apps/web/tsconfig targets ES2022 where
`useDefineForClassFields` defaults to TRUE. Define-semantics class fields SHADOW
the accessors Lit installs, so `widget.state = latest` became a dead field write
that never triggered a re-render. It only bit the web widget — the terminal
client and headless node render call `renderChat` directly, bypassing the
reactive property, which is why they always worked.

Fix: `useDefineForClassFields: false` in apps/web/tsconfig.json (the canonical
Lit-with-`static properties` setting; esbuild/vite honor it for the transform,
tsc for the typecheck). The room now renders in a real browser — who/what/where,
live conversation, compose bar — proven via Chrome CDP real-time capture.

Also adds a small connection-status banner in index.ts (surfaces socket
connecting/open/closed/no-snapshot instead of a silent stuck "Connecting…", and
auto-removes on first render) — the diagnostic that localized this, kept as real
UX.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
joelteply added a commit that referenced this pull request Jul 3, 2026
…1754)

* feat(capture): cu screenshot any interface from a CLI call — operator scope + render wait

Two fixes make `cu interface/capture` a usable "see any interface via a CLI call":

1. Caller scope. The command refused any caller without a persona identity, but
   the local `cu` path is owner-by-locality (Unix socket → `None` caller — the
   operator on the box). Scope those captures to "local" instead of refusing: the
   operator is a first-class caller, just not a persona (a persona still scopes to
   its peer_id). Not a fallback — we name the scope, never mint a ghost citizen.
   Now `cu interface/capture '{"target":"web","url":"…"}'` works from the CLI.

2. Render wait. Headless Chrome screenshots at the load event — too early for an
   SPA that mounts, opens a WebSocket, and renders after the first state frame
   (blank page otherwise). Add `--virtual-time-budget=3000` so the page's async
   work settles before the capture, bounded by the existing CAPTURE_TIMEOUT.

Verified live: `cu interface/capture` renders + saves a PNG (proven with a static
page — text rendered green-on-dark, 12KB vs a 4KB blank), scoped under
~/.continuum/captures/local/. NOTE: the positron WEB app still renders blank in
headless Chrome (only its dark background captured) though the SAME @continuum/
chat-view pipe renders correctly via the terminal client and a headless node
render — so that's a web-client in-browser bug (mount / browser-WS / pre-state
placeholder), tracked separately, not a capture-path issue.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(desktop): `cu desktop` — open the UI in the natural browser, single-instance

The natural-browser twin of `interface/capture` (headless). `cu desktop` opens the
Continuum UI in the operator's DEFAULT browser — their choice, a real visible
window — via the OS opener (macOS `open`, Linux `xdg-open`, Windows `cmd /c
start`), never a hardcoded browser.

Managed as a single-instance resource so it doesn't spawn a new tab every call: a
lightweight on-disk session marker (~/.continuum/desktop/session.json) is the
"lease". A second `cu desktop` for the same URL is a no-op ("already open");
`focus:true` forces a re-open. Start-simple by design — a later slice promotes the
marker to a first-class ResourceGovernor consumer (#56) alongside VRAM / serving /
Bevy, so the window is allocated + reclaimed like any other machine resource.

URL resolves param → `CONTINUUM_DESKTOP_URL` → the local web client on the default
WS ingress. Owner-scoped (the local `cu` operator opens their own box's desktop).

Verified live: 1st call opened the default browser (`opened:true`); 2nd was a
no-op (`opened:false`, "already open") — no duplicate window; `focus:true`
re-opened. This is `cu desktop` per the ask: natural browser, single-instance,
simple.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* fix(web): render the live room — Lit reactive props were dead under useDefineForClassFields

The web chat client mounted, connected the WS, and RECEIVED state (verified via
CDP: state-recv → parsed 50 msgs → widget.state set, repeatedly) — but stayed
frozen on "Connecting to the room…". Root cause: `<chat-widget>` declares its Lit
reactive properties via `static properties` + plain TS class fields (`state`,
`sendHandler`, `_draft`…), and apps/web/tsconfig targets ES2022 where
`useDefineForClassFields` defaults to TRUE. Define-semantics class fields SHADOW
the accessors Lit installs, so `widget.state = latest` became a dead field write
that never triggered a re-render. It only bit the web widget — the terminal
client and headless node render call `renderChat` directly, bypassing the
reactive property, which is why they always worked.

Fix: `useDefineForClassFields: false` in apps/web/tsconfig.json (the canonical
Lit-with-`static properties` setting; esbuild/vite honor it for the transform,
tsc for the typecheck). The room now renders in a real browser — who/what/where,
live conversation, compose bar — proven via Chrome CDP real-time capture.

Also adds a small connection-status banner in index.ts (surfaces socket
connecting/open/closed/no-snapshot instead of a silent stuck "Connecting…", and
auto-removes on first render) — the diagnostic that localized this, kept as real
UX.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(web): restore the signature look-and-feel via shared design tokens

Brings the old JTAG theme vocabulary forward as the reusable design foundation
(apps/web/src/theme.css) — the `base` theme: dark blue-gray gradient, cyan
(#00d4ff) accent, translucent surfaces, spacing/radius scales, SF Pro / SF Mono.
`<chat-widget>` now styles ENTIRELY from these semantic tokens (--content-*,
--widget-*, --message-*, --status-*, --border-*, --spacing-*, --radius-*) — zero
hardcoded colors.

Why tokens, not per-widget CSS: the token NAMES are the portable contract. A
theme swap (classic / cyberpunk / light / monochrome / retro-mac) is one :root
override, not a widget edit; and the same names map to native styles on a future
mobile / terminal surface — one vocabulary, many outputs. Every next widget
(wall, kanban, code, avatar) inherits the look for free by consuming the tokens.

Visible result (verified via Chrome CDP): cyan room name, glowing green presence
dots, accent-bordered runtime badges, message bubbles, themed input + gradient
Send button — the signature Continuum aesthetic, not default-dark. typecheck +
clients lint green.

Next foundational step: graduate the tokens to a shared @continuum/theme package
(values as data web + native both consume) + a widget registry keyed by state
kind so activities map to the right widget.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
joelteply added a commit that referenced this pull request Jul 19, 2026
…arte look, change-monitor, governed (#1961)

* feat(perception): wire MediaPerceptionSource into cognition (read path) + single-source SharedCompute

The persona's live-call visual perception now reaches the globally-aware mind.
`MediaPerceptionSource` is lifted into each persona's Workspace grounding set at
supervisor boot (the same task-#12 RagSourceFaculty bridge roster/doctrine use),
so WHO is visible on the call + a description of what they show becomes budgeted,
non-blocking framing — read only from cells resolved this tick, competing for
context through the ONE flexbox allocator so perception never dominates.

Single-source the compute-once cache so the read side and the (coming #192) media
ingest cannot diverge:
- `runtime::shared_compute::global()` — the ONE process-global SharedCompute; a
  frame's derivatives (scaled cells, description) are content-hash keyed so N
  personas viewing one frame describe/scale it ONCE (the multi-persona vision moat).
- `Runtime::new` ADOPTS that instance for its own `compute` handle, so a module
  reaching it via ModuleContext.compute and a persona reaching it via global() see
  the same cache.
- `media::perception_registry()` — the addressable per-persona PerceptionBuffer
  home (one home, two reachers by persona_id: ingest warms, source reads), mirroring
  focus::registry(). AMBIENT_PERCEPTION_SIZE (480x270) is the one ambient-cell policy.

Read side is off the 30fps media plane entirely: deliver() runs per persona TURN
(seconds apart), O(participants) string assembly, no inference, reads only ready
cells. The ingest cadence gate (describe << frame rate, governor-priced) lands with
the video_rx -> observe() wire in #192.

Empty until frames arrive — this wires the READ path into cognition; nothing on
the brain's compose path changed (unified.rs untouched — perception is a NEW source
with no legacy compose consumer, so only the target Workspace path is wired).

Tests: perception_registry idempotent one-buffer-per-persona + singleton; existing
source/buffer/compute suites green.

Refs #187 #106; sets up #192.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* perf(perception): gate ingest warm to a sampled cadence — 30fps-safe by construction

MANY personas render at 30fps and humans join at 30fps; the ingest primitive must
survive that BEFORE #192 wires a raw stream to it. `observe()` previously spawned an
LLM describe + scale on EVERY call, and 30fps frames each have a distinct
content-hash so the compute-once cache gives ZERO dedup on the frame rate — a raw
wire would trigger 30 vision inferences/sec/participant/persona.

Separate the two planes:
- COALESCE the latest frame UNCONDITIONALLY (O(1) mutex insert — safe at 30fps; the
  media/display plane). Perception samples the media plane, it does not mirror it.
- GATE the expensive warm (scale + describe) behind a per-participant cadence
  (AMBIENT_WARM_MIN_INTERVAL_MS = 500ms ≈ 2Hz) + an in-flight guard that never stacks
  a warm on an unfinished one. Extracted as a PURE `should_warm(participant, now_ms)`
  decision so the 30fps guarantee is asserted without timing or a runtime.

`observe()` now takes `now_ms` (substrate passes the monotonic clock in — no
Instant::now in the media core). The cadence is a buffer FIELD (default from the
const), so the governor can retune it per persona later as an attention-priced
resolution field (#173) — a focused persona looks more often, an idle one less.

Cross-persona cost stays O(distinct frames), not O(personas): the actual
scale/describe runs on the ONE global SharedCompute keyed by content-hash, so N
personas viewing one participant's frame share ONE describe (the multi-persona
vision moat vs cloud, where N personas = N API calls). The per-persona gate/spawn is
cheap and cache-hits after the first.

Tests: cadence gates within the interval + reopens after; in-flight guard never
stacks. Existing coalesce/read suites updated for the now_ms arg, green.

Refs #187 #173; sets up #192 ingest.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* perf(perception): warm cadence is a BAND — slow floor, not off; change escalates

"Slow cadence not NO cadence" (Joel): an idle observer must not be starved of vision —
absent motion it DECAYS to a slow baseline, it does not go to zero. The warm decision is
now a band, not a single throttle:

- MIN ceiling (AMBIENT_WARM_MIN_INTERVAL_MS = 500ms): never describe faster, even under
  constant motion — the 30fps rate cap.
- BASELINE floor (AMBIENT_WARM_BASELINE_INTERVAL_MS = 5s): describe at LEAST this often
  even on a dead-static scene — a still participant still refreshes every few seconds so
  room-as-now stays true, just coarse.
- change signal (in between): a relevant motion/scene-change/YOLO hit escalates to the
  MIN ceiling long before the floor.

should_warm now takes `changed`: `warm if !in_flight && (first || (changed && past_min)
|| past_baseline)`. Both branches are unit-tested (change→fast, static→slow-floor,
never-stack). Both intervals are FIELDS so the governor shrinks them for the
speaking/acting persona and widens them for idle observers later (attention-priced
resolution field, #173) — but never to infinity.

observe() passes `changed = true` as a documented INTERIM: no change detector wired yet,
so every coalesced frame is treated as potentially-changed (cadence rides the MIN ceiling,
behavior-preserving). #192 replaces that `true` with a cheap motion/scene-change/YOLO
detector cell (compute-once/shared on the frame hash), at which point a static scene
decays to the baseline floor and describes are spent only where something changed.

Refs #187 #173 #192.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(perception): sliding-window FrameRing store + grouped/windowed reads

The spine of the shared-cache perception design: stop thinking "hand each persona
images," think "one shared pre-warmed ring per source; personas read views."

- PerceptionBuffer's per-participant `latest: MediaFrame` becomes a bounded
  `FrameRing` (VecDeque, AMBIENT_RING_CAPACITY=8, newest at head). The ring IS the
  sliding window AND the pre-warmed cache in one object: frames are Arc handles,
  derivatives dedup by content-hash on the ONE shared compute, so K frames × N
  sources is cheap and never duplicates a derivative across viewers. `push` coalesces
  an identical-content head and evicts the oldest past capacity (room-as-now, bounded).
  ring_capacity is a field so the governor can deepen a source's window later (#173).

- Two serving shapes off the ONE store, both zero-copy over warm cells:
  - GROUPED: `current_percepts` = every ring's HEAD — "everyone at a glance," the
    human-widget gallery (behavior-preserving: head = the old "latest").
  - WINDOWED: `window_percepts(participant, k)` = one source's last-k, newest-first —
    "what changed / what did I miss." Unknown source → empty (never a fabricated look).
  Both go through one `percept_of` projection (compression: a frame becomes a percept
  in exactly one place).

This is the foundation for the pull/contact-sheet read (next), the room warm-loop +
tiled grouped-describe, and the change signal (compare consecutive ring heads → #192).
Design captured in memory (dual-perspective RTOS perception scoring).

Tests: ring windows newest-first + coalesces head + bounds capacity; grouped=all-heads
vs windowed=one-source-history; existing coalesce/read/cadence suites green (10/10).

Refs #187 #192 #173.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(perception): à la carte look() — pull a source or group at thumbnail/res/full, ASAP

"Into their vision à la carte": a persona composes its own view — request images of ONE
source or the whole GROUP, at THUMBNAIL / higher-RES / FULL, satisfied ASAP.

PerceptionBuffer::look(scope, fidelity, compute) — the PULL side, distinct from the
ambient PUSH band:
- scope = Source(id) | Everyone (the contact-sheet / gallery).
- fidelity = Thumbnail (ambient) | Res(DestSize) (higher/lower) | Full (raw bytes).
  Higher-res is just a different SIZE key on the same content-hash, so it's
  compute-once/shared exactly like the thumbnail — a res another persona already pulled
  is a cache hit here (proven: repeat pull returns the SAME Arc).
- ASAP: warm hit → instant; cold cell → warmed NOW. It never consults the ambient warm
  gate, so a manual pull implicitly JUMPS the cadence band (an explicit high-priority ask).
- This is the ONE place perception AWAITS (a deliberate request, not the ambient hot path);
  targets are snapshotted under the lock and compute is awaited OUTSIDE it (no lock across
  await). Unknown source → empty (never a fabricated look).

With the FrameRing store, that completes the pull model: grouped gallery, per-source
history (window_percepts), and now on-demand images at any fidelity — all off the ONE
shared, compute-once cache.

Tests: source/group × thumbnail/res/full, prefer-warm sharing (same Arc), full=raw,
unknown→empty. 11/11 perception suite green.

Refs #187 #192.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(perception): change-monitor cell — real luma-signature diff drives the warm band

Replaces the interim `changed = true` with an actual per-source change detector — the
universal monitor that gates the expensive describe (any view: call, game, page, movie).

- MediaFrame gains a SIGNATURE cell: a tiny 16x12 luma fingerprint (image_ops::luma_signature),
  compute-once/shared on the content hash like scale/describe — warmed first in the observe
  spawn (it's the cheapest and it gates the rest).
- observe now computes real `changed` via PerceptionBuffer::scene_recently_changed: diff the
  two most recent frames whose signature has WARMED (image_ops::luma_mean_abs_delta >
  CHANGE_THRESHOLD=8/255). Reads only ready cells — never awaits on the ingest path; cold
  start / signatures still warming → true (ride the MIN ceiling until we can tell). So a
  static scene now genuinely decays to the BASELINE floor; real motion/scene/slide change
  escalates.
- Cheap by construction: a bounded ring scan + a ~192-byte diff, fine per ingest. The
  signature is shared, so N watchers of one frame diff ONE fingerprint (compute-once on
  CHANGE, the moat now on the monitor too).

should_warm stays pure + param-driven (band logic unchanged, still fully tested); observe
just feeds it a real signal instead of a placeholder.

NOTE (next commit, per Joel): register perception as a ResourceConsumer with the resource
governor (RAM = ring frame bytes; sibling to Serving/Bevy/Voice consumers) so its footprint
is accounted and it leases — the "register with the GPU resource monitor" ask. Disk consumer
comes with the durable record.

Tests: luma signature + delta detect change; signature cell computes-once/shared;
scene_recently_changed (same scene → not changed, different → changed, unknown → assume).
23/23 media suite green.

Refs #187 #192 #56.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(perception): register as a ResourceConsumer with the governor (RAM footprint + reclaim)

Perception takes its seat at the resource-governor table (#56) — a peer consumer beside
Serving (VRAM), Bevy (render VRAM), and Voice (TTS), exactly as Joel asked ("register with
the GPU resource monitor").

- PerceptionConsumer (modules/perception_consumer.rs) implements ResourceConsumer:
  - consumer_id "perception"; footprint() reports Ram = total ring frame bytes read live
    from the process-global PerceptionRegistry (empty when idle, like the siblings).
  - reclaim(Ram) evicts oldest ring frames toward the target but ALWAYS keeps each source's
    head — a live perceiver is never blinded (room-as-now survives a reclaim). Honest
    Released/Partial with real freed bytes; a non-Ram ask is refused by name (never silent).
- Byte accounting + eviction added at each layer: FrameRing::{resident_bytes, evict_oldest},
  PerceptionBuffer::{resident_bytes, evict_at_least}, PerceptionRegistry::{total_resident_bytes,
  evict_at_least} (clones Arcs out — no registry lock held across per-buffer work).
- Registered at the boot seam (ipc/mod.rs) right after Voice + Bevy via
  resource_daemon.add_consumer.

Honest scoping: perception holds RAM (the rings it owns), NOT VRAM — the vision-describe it
triggers runs on the served VL model, whose VRAM is ServingConsumer's footprint; perception
is a demander of that lane, not a holder of its bytes. The shared derivative cache
(thumbnails/descriptions/signatures on SharedCompute) is not double-counted here.

Disk consumer for the durable record follows when that lands (same pattern, ResourceKind::Disk).

Tests: footprint == ring RAM + empty-when-idle; reclaim evicts oldest, keeps head, honest
Partial, refuses wrong kind. Green.

Refs #56 #187 #192.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
joelteply added a commit that referenced this pull request Jul 20, 2026
…heartbeat and respawn it

The persona serving lane wedges when a Metal command buffer OOMs during the cold-boot
concurrent prefill (kIOGPUCommandBufferCallbackErrorOutOfMemory). One OOM poisons the
whole Metal backend and llama.cpp cannot self-heal ("recreate the backend to recover"),
so every subsequent request 500s. Continuum was BLIND to this and never recovered:

- serving/status reported ready:true while every generation 500'd, AND even after the
  llama-server process was killed (proven with a live kill-test) — readiness was a stale
  cached belief, never re-validated. A poisoned backend still answers /health, /v1/models,
  and /props 200; only a real GENERATION reveals the wedge.
- the reconcile trusts a child it owns and skips the decode smoke-probe forever ("decode-
  verified at wait_ready, trusted thereafter"), so an owned lane that wedges at runtime was
  re-adopted every tick, never respawned. #90 reclaim is boot-only. Result: any transient
  GPU hiccup bricked the persona substrate until a human reboot.

This is the DETECT + RECOVER half (the aa3e6c1 context-length clamp only covered the
length-overflow trigger, not the GPU OOM). Following the CONCURRENCY-STYLE-GUIDE, it is an
additive tick concern on the serving daemon, NOT the reflex watchdog reverted in 93753d8
for unreliable respawn:

- A slow liveness HEARTBEAT (every 12 ticks ≈ 60s) decode-probes the lane the daemon
  believes is ready. After HEALTH_FAILS_TO_RELAUNCH=2 CONSECUTIVE failures — pure
  hysteresis, so a merely-BUSY lane whose saturated slot times out one probe is never
  reaped (the exact thrash that got the prior watchdog reverted) — it publishes ready:false
  and arms a force-relaunch. Runs off the tick as its own bounded task; a passing probe
  resets the streak.
- ensure_model_serving gains force_probe: when the daemon consumes the armed flag it makes
  the reconcile re-prove decode EVEN on a child we own, so the wedged owned lane falls
  through to serve() → kill + respawn a fresh Metal backend (the only recovery llama.cpp
  offers) instead of the owned-child trust re-adopting it forever. ready:false also skips
  the reconcile's no-op guard so the relaunch actually runs.

Net: a transient GPU OOM now self-heals in ~a minute (personas WAIT during the gap, they
don't 500), and a persistently-broken lane re-attempts recovery slowly (~130s), never
thrashes. Prevention of the OOM itself (staggering the cold-boot prefill burst, the
prefill_throttle already in tick) stays #56/#175 follow-up.

Tests: force_probe_relaunches_an_owned_but_wedged_lane (llama_server) +
health_heartbeat_flips_ready_after_sustained_decode_failure /
health_heartbeat_streak_resets_on_a_passing_probe /
health_heartbeat_only_fires_on_the_slow_cadence (serving_daemon). All existing
reconcile/thrash tests stay green (22 serving_daemon, 19 llama_server).

Root cause + live evidence in memory llama-compute-error-wedge-is-per-slot-context-overflow.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply added a commit that referenced this pull request Jul 20, 2026
…o a smaller model, not going dark

Serving registers as a measured ResourceConsumer with the one per-machine authority (#79),
but its tier-down lever was stubbed `DeclineTierDown` — under a VRAM reclaim (a game grabs the
GPU, a peer needs the bytes) it declined, so the only lever was a full unload (serving goes
dark until a re-load). That is "we don't deal with our own memory": we either hold everything
or drop everything.

CatalogTierDownPolicy is the first real tier-down intelligence (outlier A — the heuristic
ladder the module doc calls for; a PersonaTierDownPolicy / MlTierDownPolicy drops in unchanged
later). On a reclaim ask it re-homes to the MOST CAPABLE smaller model that still frees enough
to clear the ask — "take our own capacity down to yield to the game, but keep answering, just
smaller." It declines (→ full unload, the honest max lever) only when no smaller model frees
enough, and never re-homes to a non-shrink. When pressure clears, the autonomic plan grows
back up on its own (it always serves the most capable model that fits the now-larger budget) —
so a user quitting a game gets the big model back with no operator action.

The ranker sees exactly the models the autonomic plan could serve: `live_candidates`'s
suppress/pin/eligibility filter is now the free fn `servable_candidates`, shared by the plan
AND the tier-down closure — ONE catalog, never two divergent ones (#142 eligibility gate
preserved; a pin bypasses it as operator consent). Sizing (`resident_bytes` = weights +
per-lane KV × lanes) comes from the daemon's one footprint authority, so a tier-down target
can never disagree with what the plan would compute. The consumer's async re-home handshake is
unchanged (mechanism vs policy, per the module doctrine).

Tests: picks_the_most_capable_model_that_frees_enough / declines_when_no_smaller_model_frees_enough
/ never_re_homes_to_a_non_shrink (serving_tier_down). Existing serving_daemon reconcile/thrash
tests stay green.

Still open under #56 (this is serving's graceful-yield half): the concurrent-prefill OOM
PREVENTION (wire the governed-VRAM number into prefill_throttle), mid-run orphan reclaim (a
SIGKILLed core strands its llama-server until next-boot pidfile reclaim — #90 is boot-only),
and Bevy/LiveKit registering as peer lease consumers.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply added a commit that referenced this pull request Jul 20, 2026
… not a static double-discount

The autonomic plan sized its budget as `available × SERVING_BUDGET_FRACTION(0.80) ×
mode.serving_fraction()` — two reserves stacked. At the everyday Comfort mode that compounds to
~0.64, so a 38GB governed board yielded a 24.5GB plan and left the more-capable Qwen2.5-Coder-32B
(sitting Ready on disk) unused with context truncated to ~10-13k of a 131k-capable model. Pure
under-use of the GPU.

Collapse to the ONE reserve that is actually DYNAMIC: `host_budget = min(available, ceiling) ×
mode.serving_fraction()`, where the mode is chosen from live memory pressure — Eco 0.55 when a
game/crowd starves memory, Comfort 0.80 everyday, Sport 0.92, Performance 1.0 to floor the whole
GPU for a hard task with room. The static `SERVING_BUDGET_FRACTION` no longer stacks on the plan
(it still backs `live_host_budget`, which the pin fit-gate uses for "can this model physically
fit" — a different question).

Safe, not a headroom raid: the concurrent-prefill compute buffer (the term that OOM'd) is
reserved SEPARATELY and window-scaled in the serving_plan fixpoint, so a bigger budget yields a
bigger window AND a proportionally bigger reserve — self-consistent. The double-fraction bought
no safety; it only shrank the model/window. The pressure-adaptive mode + the prefill throttle +
the #175 self-heal remain the backstops.

Toward the doctrine "nothing is static in a memory system": this kills one of the static reserve
constants. The endgame (carded on #56) is to make every consumer a live MEASURED ResourceConsumer
(eval lane, LoRA training, genome adapters, mmproj, the compute buffer) so `available` nets
everyone — then the remaining fractions delete themselves and budget = live available directly.

host_budget_tracks_live_free_memory + all serving_daemon reconcile/thrash tests stay green.
Audit + roadmap in memory memory-system-is-fully-dynamic-nothing-static.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply added a commit that referenced this pull request Jul 20, 2026
…l compute reserve), not resident-only

The board attributed serving `resident_bytes` = weights + per-lane KV, but OMITTED the
concurrent-prefill compute buffer — the transient Metal graph llama.cpp sizes for the FULL served
window, and the exact term that OOM'd. So the governor over-reported free VRAM by that reserve, and
any SECOND consumer (the ephemeral eval lane, a LoRA-train job) read those phantom-free bytes and
grabbed what serving needed for its next prefill → the concurrent-OOM. "Nothing static": the reserve
must be MEASURED and attributed, not left invisible.

The fix folds the reserve into serving's reported footprint via ONE shared formula. The serving plan's
fixpoint already sizes the window against `compute_reserve = (compute_floor + compute_rate·C) × lanes`
(window-SCALED — a window-independent reserve under-provisions exactly as C grows, the 53k prefill OOM).
That math is now `ModelFootprint::prefill_compute_reserve(window, lanes)`, called by BOTH the plan AND
the new `peak_resident_bytes` = resident + reserve. `serving_footprint_fn` reports `peak_resident_bytes`,
which equals the plan's `chosen_cost` EXACTLY — the number serving reports to the governor is the number
the planner sized against, never two figures that drift (E=mc²: one compute-reserve decision, one place).
The tier-down candidate ranker uses peak too, so a shrink target's freed bytes are measured against
serving's true footprint.

Why this matters for hosting above our weight: the board's `available` stops lying, which is the
precondition for the next slices — govern the eval lane + training as measured consumers (G1/G2), then
delete the static fractions entirely so budget = live available net of every real consumer. Only an
honest `available` lets orchestrators pack a big coder + a benchmark lane + training on one box (and soon
the grid) via pressure-driven paging instead of OOM.

Tests: peak_resident_equals_plan_chosen_cost_including_window_scaled_compute (serving_plan) pins
peak == chosen_cost via the one shared formula; serving_footprint_fn_resolves_live_catalog_weights
(serving_daemon) updated to assert the resolver reports peak. 18 serving_plan + 22 serving_daemon + 3
serving_tier_down green.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply added a commit that referenced this pull request Jul 20, 2026
…M slot (pressure, not OOM)

The ephemeral eval/benchmark lane was the #1 concurrent-OOM source: it stands up a SECOND
llama-server and chose GPU-vs-CPU off `gpu::monitor::detect()`'s RAW free bytes — which count
serving's RESERVED-but-not-yet-allocated prefill buffer as "free" (the exact phantom G5 just made
the board honest about). So the eval placed on GPU into bytes serving needed, and serving's next
prefill hit `kIOGPU…OutOfMemory`. Ungoverned: a whole model stood up with zero check against the
one authority.

Now the eval lane does what every process does with a real memory manager — it `malloc`s. Two
pieces:

1. `ResourceDaemon::acquire_guarded(req) -> LeaseGuard` (resources): the RAII shape over the
   existing `acquire`/`release`. Reserve bytes, hold the guard for the job, and the reservation
   returns to the board on ANY exit — early `?`, normal end, panic — with the lease TTL as the
   self-healing backstop if the whole process is SIGKILLed. This is the byte-residency companion
   to the throughput lease; the primitive any bounded consumer (eval, forge) now uses.

2. `cognition/eval` acquires a governed Vram lease of the lane's footprint instead of reading raw
   free. It's an atomic check-and-reserve against the GOVERNED available (physical free minus every
   consumer's guarantee, peak-accurate after G5):
     granted → GPU, and HOLD the lease so a concurrent serving tick sees the bytes as taken and
               won't tier up into them
     refused (InsufficientCapacity) → the governed GPU is full → spill to CPU, VISIBLE in the
               placement evidence, ~10× slower but never an OOM — "pressure, not OOM"
     ungoverned node (no daemon) → the ORIGINAL raw-free probe, behavior unchanged
   The guard rides in `EvalLane` and (across the destructure) beside `_eval_lane`, declared so it
   releases AFTER the lane's server is killed — free the physical bytes, THEN the accounting, so a
   release can never flash the bytes as available while the process still holds them.

This is the OS framing made real: strategy/policy centralized in the ONE authority, consumers ask
for slots and hold leases, the board tells everyone the truth. It's the precondition for hosting
above our weight belt — a big coder + a benchmark lane + training coexisting by governed
reservation and (next) paging, instead of racing to OOM. Graceful yield-under-pressure (the eval
negotiating early release) and folding training/mmproj/adapters in are the next G-slices; the eval
lease is Pinned for now (a bounded first-class measurement is not yanked mid-run).

Tests: lease_guard_reserves_then_releases_on_drop (resources::daemon) pins reserve→board→drop-frees
+ the honest InsufficientCapacity refusal; existing choose_lane_placement + serving_plan/daemon
tests stay green.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply added a commit that referenced this pull request Jul 20, 2026
…ore spawning (no invisible forge pressure)

A `mlx_lm.lora` forge loads the FULL base into unified memory — on a UMA box that is direct VRAM
contention with the live persona lanes — and it launched with ZERO governor check. Invisible
pressure: a background gene-forge could OOM a live video-chat mid-training with no warning, the last
big ungoverned consumer after G1 (the eval lane).

Now `run_mlx_train` leases before it spawns, via the same `ResourceDaemon::acquire_guarded` primitive
G1 added — the forge sibling of the eval lane's `acquire_eval_lane_slot`:
  - `estimate_train_footprint_bytes` sizes the job from the base's on-disk safetensors × 1.3
    (activations + optimizer moments), the coarse-but-honest sibling of the eval lane's ×1.25.
  - granted → hold the guard for the WHOLE run (`_train_lease`, dropped when `run_mlx_train` returns
    — AFTER `child.wait()`, so the process's UMA is freed before the accounting is released) so a
    concurrent serving tick sees the training bytes as taken and won't tier up into them.
  - refused (InsufficientCapacity) → fail LOUD with the governed numbers. A background forge must
    never OOM the machine; the honest answer is "not now — free VRAM and retry", and the L3 flywheel
    re-attempts when pressure clears ([[fallbacks-are-illegal-fail-loud]]).
  - can't-size (no safetensors) / ungoverned node (no daemon) → proceed unleased, behavior unchanged.

Pinned for now (a bare lease with no preemption handler must stay Pinned so the board never frees the
accounting while the subprocess holds the UMA). Real yield-under-pressure — checkpoint + pause the
forge when live serving needs the bytes — is the piece-3 follow-up. With G5 (honest peak) + G1 (eval
lane leases) + G2 (training leases), the three big consumers are now MEASURED on the one board: the
next `cu reboot` can show serving + eval + train contending as three real leases, and the static
serving fractions become deletable (budget = available net of every measured consumer).

Tests: train_footprint_sums_safetensors_times_factor (forge::mlx_train) pins the sizer + the
can't-size→None path; the acquire/refuse path reuses the LeaseGuard primitive tested in G1.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply added a commit that referenced this pull request Jul 20, 2026
… false-pending (load-test footgun)

`eval-status --run_id X` REQUIRED `--persona_id` too: without it the handler silently fell through to
"live progress only" and returned `complete:false, row:null` — indistinguishable from a hung/incomplete
run. Glass-boxed 2026-07-20 during the #56 load test: a detached `benchmark/run` finished 10/10 and its
terminal row landed correctly in the persona ledger, but a run_id-only poll reported `complete:false`
forever. A benchmark/matrix or CI driver that holds only the run handle would hang on every cell.

run_id is a globally-unique UUID, so it is a SUFFICIENT key. With a persona_id we read that persona's
ledger directly (the fast path, unchanged); WITHOUT one we scan every `~/.continuum/progress/*.jsonl`
for the row rather than degrade to live-only. Extracted the newest-first matcher into the pure
`row_with_run_id` (text in, Value out) reused by both the known-persona and any-persona lookups — one
match rule, unit-testable without the filesystem. No silent degrade: a real in-flight/unknown run still
resolves to None (pending), never a wrong row.

Test: eval_status_row_matches_run_id_newest_first pins newest-row-wins + exact-match + None-on-unknown +
malformed-line-skip. Surfaced by, and complements, the #56/G1 live validation (the resource layer itself
was clean — lease acquired, contention held at ~95% VRAM with no OOM, released with no orphan).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply added a commit that referenced this pull request Jul 20, 2026
…atic (memory-authority slice 4)

The GpuMemoryManager split usable VRAM into fixed per-subsystem budgets
(INFERENCE_BUDGET_PCT 0.75 / TTS 0.10 / RENDERING 0.10). That partition was
demand-blind AND vestigial: SubsystemBudget is a SOFT limit ("allocation
proceeds even if over-budget"), so the split never governed admission — the
only hard gate is the DYNAMIC pressure gate (new_pressure >= priority.pressure_gate()),
read off the same physical GpuMonitor the one-authority ResourceDaemon board reads.
The static fraction only skewed a warning log + telemetry, and it lied that
inference could never exceed 75% of VRAM while TTS/rendering sat idle.

Every subsystem now draws from the full shared `usable` pool; the pressure
gate arbitrates contention live. This is the literal "delete the remaining
static fractions" endgame from the memory-authority doc, applied to the
residual admission ledger. The RESERVE_PCT driver headroom stays (it's real).

Investigation finding folded into MEMORY-AUTHORITY-DAEMON.md slice 4: the
DECISION plane was already one-number after slices 1b/2 — GpuCapacitySource
reports ceiling=total-reserve, used=total-free, which physically nets out
everything Bevy/TTS/inference allocate. The full fold (those subsystems
LEASE from the one board, retiring this parallel pressure ledger) is task #56,
a multi-subsystem migration that needs the live avatar/TTS path to validate.

Tests: reworked test_budget_percentages -> test_no_static_partition_all_subsystems_share_the_usable_pool
(asserts all three draw the full usable pool, equal), and test_over_budget_soft_limit
now pins a tiny soft budget via set_budget to preserve the soft-vs-pressure-gate
distinction. 101 gpu + 25 commands::gpu + 116 resources tests green.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply added a commit that referenced this pull request Jul 20, 2026
…ls the VRAM-scan thrash loop)

After #214 un-froze grow-back, serving THRASHED on a churned box: window flapped 44800↔7680 while
the board's `available` swung 12.9↔41GB in 30s. Root: serving is scan-accounted (the board's
`available = capacity − max(granted, physical_used)`, and serving holds no lease so granted=0), so
`available` tracks the raw GPU scan. During serving's OWN relaunch (kill→respawn) the scan drops as
the old lane exits and rises as the new one loads — a phantom free-VRAM spike/dip. `host_budget()`
reads it, the plan flaps the window, and the flapped plan triggers ANOTHER relaunch: a feedback loop
where serving's own churn re-plans its own lane off a transient budget.

Fix: `recompute()` early-returns while a relaunch is in flight (`reconciling` true) — serving's own
in-flight churn must not feed back into its own plan. Composes with #214: the RAII gate clears the
instant the relaunch finishes OR fails, so re-planning resumes promptly against the STABLE
post-relaunch budget — no thrash, no stall. The deeper fix (serving holds an explicit board lease so
`granted` pins its residency and the scan transient never reaches `available`) is the #56
consumers-LEASE residual; this breaks the loop cleanly now.

22/22 serving_daemon tests green. Live thrash-gone validation on deploy.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply added a commit that referenced this pull request Jul 21, 2026
…us serving (#1976)

* fix(serving): #216 — don't re-plan while a relaunch is in flight (kills the VRAM-scan thrash loop)

After #214 un-froze grow-back, serving THRASHED on a churned box: window flapped 44800↔7680 while
the board's `available` swung 12.9↔41GB in 30s. Root: serving is scan-accounted (the board's
`available = capacity − max(granted, physical_used)`, and serving holds no lease so granted=0), so
`available` tracks the raw GPU scan. During serving's OWN relaunch (kill→respawn) the scan drops as
the old lane exits and rises as the new one loads — a phantom free-VRAM spike/dip. `host_budget()`
reads it, the plan flaps the window, and the flapped plan triggers ANOTHER relaunch: a feedback loop
where serving's own churn re-plans its own lane off a transient budget.

Fix: `recompute()` early-returns while a relaunch is in flight (`reconciling` true) — serving's own
in-flight churn must not feed back into its own plan. Composes with #214: the RAII gate clears the
instant the relaunch finishes OR fails, so re-planning resumes promptly against the STABLE
post-relaunch budget — no thrash, no stall. The deeper fix (serving holds an explicit board lease so
`granted` pins its residency and the scan transient never reaches `available`) is the #56
consumers-LEASE residual; this breaks the loop cleanly now.

22/22 serving_daemon tests green. Live thrash-gone validation on deploy.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* fix(inference): retry a CONNECT to a mid-relaunch local lane instead of faulting the turn

A local single-resident lane gets relaunched out from under an in-flight POST —
grow-back (#214), a genome page-in, or memory pressure all bounce the llama-server
process, and the published serving snapshot lags at ready=true for the seconds the
socket is actually refused (a watch channel is inherently behind the process; the
pre-flight ready-guard trusts the snapshot, the socket disagrees). The POST then
faulted the whole turn on 'Connection refused (os error 61)'.

A connect error to a resident lane means 'mid-relaunch', not 'gone': the connection
never opened so nothing streamed, and re-sending the SAME lane/model is idempotent —
resilience, NOT a fallback. Retry the connect with bounded linear backoff (1s..6s,
~21s total), scoped to single_resident_model (remote endpoints don't relaunch under
us), then fail loud if it never returns. Live-glass-boxed 2026-07-20: a legitimate
grow-back relaunch connection-refused every in-flight generation to :58057 mid-eval;
48 retry probes fired correctly on redeploy, recovering transient bounces.

Live turns benefit identically — any turn coinciding with a relaunch previously died.
Does NOT fully rescue a SUSTAINED relaunch loop (eval-on-shared-lane contention →
#175 decode-failure self-heal thrash); that needs eval lane isolation (next).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(resources): lane ADMISSION planner — the authority's 'does this fit, and how?' decision

The governor's reconcile_for_demand is the RECLAIM half (frees bytes under pressure).
This adds the missing ADMISSION half: plan_placement(capacity, resident, demand) — a
PURE function returning what the daemon should DO with one new lane demand:
  - ShareLane   — the base is ALREADY resident → co-tenant slots, NO duplicate weights
  - SpawnLane   — a fresh base that fits (optionally after tiering lower tiers down)
  - CpuSpill    — won't fit even after preempting everything preemptible (loud reason)

The gotcha it kills (glass-boxed 2026-07-20): the eval path grabbed a GPU lease LOCALLY,
against an under-reported footprint, and stood up a SECOND full copy of a base already
resident. Two 24B copies don't fit one accelerator → Metal 500 → poison took the live lane
down too. The first rule is the one that incident violated: same base resident ⇒ SHARE its
weights (cost = added KV only), never a duplicate copy.

Priority tiers (Live > Eval > Background): a demand may tier DOWN strictly-lower-priority,
non-pinned lanes to fit; it never preempts equal-or-higher. So an Eval never bounces a Live
lane — it spills to CPU instead. footprint() is concurrent-worst-case (KV for EVERY slot),
the invariant a LiveKit huddle needs and the empty-slot sizing that OOM'd the shared lane.

Scenario table IS the oracle — 5 unit tests on the REAL incident geometry (Devstral-24B Q4,
~38 GiB Comfort-fractioned): same-base-shares, fresh-fits-coresident, different-base-preempts-
background-not-live, eval-never-preempts-live-spills-cpu, huddle-counts-kv-per-slot. All green.
Pure + unwired this slice; next slices report honest footprints and route the eval + serving
demands through it.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(resources): grid-aware admission — same model-aware kernel, across nodes that come and go

plan_grid_placement(nodes, demand) runs the single-node plan_placement kernel on every
REACHABLE node and picks the best by affinity/least-disruption: ShareLane (weights already
WARM — no cold-load, no transfer) > clean SpawnLane > preempt > CpuSpill, then local before
remote, then most-free. A joined node just appears in the snapshot and becomes eligible; a
departed node has reachable=false and is ignored, so re-planning a stranded demand fails it
over to a live node — all derived from the live snapshot, never held.

This is the CONVERGENCE, not a 3rd allocator: capacity::grid (#176) owns the grid substrate
(gossiped GridSnapshot, the deterministic sim, the reachable/stranded/per-node-OOM resilience
invariants) but its LocalFirstFitPolicy places lanes MODEL-BLIND — by free bytes — so it would
spill a lane to the emptiest peer even when another peer has that base WARM, paying a needless
cold-load + weight transfer (the grid's version of the 2nd-copy incident, the MoE-affinity gap
#180). plan_grid_placement makes affinity the first rule. capacity::grid's GridPlacementPolicy
becomes a thin adapter over this once its GridSnapshot carries each node's resident models (the
integration slice).

4 grid scenario tests (join / peer-loss-failover / partition / affinity-beats-free-bytes) +
the 5 single-node scenarios, all green.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(serving): steady-hold — an eval on the shared lane suppresses the grow-back relaunch

Wires placement::Placement::ShareLane's 'pin the lane for the demand's duration' clause.
A living-persona benchmark (benchmark/run with no gene/base) runs as a CO-TENANT decode
slot on her real serving lane — same base already resident, so NO second weight copy (the
reverted 2026-07-20 isolation attempt was the wrong 2nd-copy approach that OOM'd the GPU).

The one thing that bounced it was the grow-back RE-HOME: when the plan wants a bigger window
it relaunches the lane, and the relaunch connection-refuses every in-flight generation
(hard-rs 0/8, zero output tokens). New: a reference-counted RAII ServingSteadyHold; while any
eval holds it, reconcile_to_plan SKIPS the starved grow-back re-home for an already-correctly-
served lane. It deliberately does NOT suppress a model/genome change or a pressure-driven
shrink — a real resource emergency still preempts (rare, correct). Live turns benefit too:
any turn coinciding with a grow-back relaunch previously died.

The eval acquires the hold for its whole run (dropped when run() returns → grow-back resumes).
Unit test: the hold is refcounted + RAII (nested acquire, inner drop keeps the outer hold).

NOT the whole story for hard-rs: a cold lane right after reboot (not-ready guard) and
concurrent-worst-case KV windowing (the decode-failure self-heal axis) are separate — the
steady-hold fixes the grow-back-bounce axis only.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* docs(planning): Proctored Exam Session — dependable benchmark serving process

The attack plan for making living-persona benchmarks trustworthy: a substrate-owned
lifecycle (acquire a decode-VERIFIED serving context via plan_placement → hold stable →
run with infra-fault != score-0 → release), NOT a timeout-hacked script. Documents the
problem (fake passRate 0.0 on a not-ready shared lane), the foundation already built
(retry + admission planner + steady-hold), and the build order B (trustworthy result) →
C (concurrent-worst-case window) → A (preempt for a guaranteed-stable context, grid-general).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(eval): Proctored Exam Session Slice B — the benchmark number is trustworthy or InfraUnavailable, never a fake 0

The dependability bug (glass-boxed this arc): a living-persona benchmark runs on the
shared serving lane. When that lane flips not-ready under load (grow-back relaunch, #175
decode-overflow self-heal, pressure/cold-after-reboot), every task's generation is refused
and the run reported `passRate: 0.0` — a fake zero INDISTINGUISHABLE from "she got them all
wrong". Across every hard-rs run: 0 output tokens, always an infra cause, never her coding.
Untrustworthy by construction; no timeout tuning fixes it.

Slice B makes the number honest at the data path:

- `PassOutcome` replaces the bare `(pass, results)` tuple: it also carries `infra_faults`
  + `infra_reason`. An `inference_error` (lane not-ready / connect-refused / "not the
  active served model" / compute-error / deadline-wedge) is an INFRA fault, never a wrong
  answer — a wrong answer settles with spoken text and no inference_error.
- Bounded recovery in run_pass: on an infra fault, re-verify the lane (await_ready_serving)
  and retry the SAME task (the retried generation IS the decode proof), up to
  INFRA_FAULT_RETRIES=3. A transient bounce recovers and grades normally; an unrecoverable
  fault (lane never returns to ready) records the row for forensics, marks the run void,
  and ABORTS — every remaining task would only accrue more phantom zeros on a dead lane.
- `infra_verdict(&PassOutcome) -> Option<InfraUnavailable>` (pure, one place decides
  void-ness) drives a new `CognitionEvalResult.infra_unavailable` field. When set,
  score/pass_rate are VOID: the ledger row carries `infraUnavailable`, benchmark/run
  surfaces it, and LEARN mode refuses to teach from a dead-lane run. A fake `passRate: 0.0`
  on an unverified lane is now impossible.
- The old grading-match `inference_error` arm is gone — an infra fault can no longer
  masquerade as a graded miss. Team mode classifies + aborts identically (its full
  re-verify+retry is a scoped follow-up, as is the A/B EphemeralServingLane path which
  decode-verifies at spawn).

Tests (fault-injection, in the existing eval test mod): an infra-faulted run resolves to
InfraUnavailable naming the task + cause, never a scored 0; genuinely-wrong answers on a
working lane stay Scored with the 0 counted (infra never masks a real capability miss).

Foundation: builds on the retry (edd71bf), admission planner (aed37a3/765b1993d),
steady-hold (25fc1dc). Plan: docs/planning/PROCTORED-EXAM-SESSION.md. Slices C
(concurrent-worst-case windowing) and A (ExamServingContext preempt) follow.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* docs(planning): mark Proctored Exam Slice B landed (f25c760)

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* docs(planning): Slice C already satisfied — plan_serving fixpoint enforces concurrent-worst-case (audit)

The Slice-C premise was stale: plan_serving:362-379 already solves the full fixpoint
(l·(kv·C + compute) ≤ after_weights), #213/#214 fixed the floor/grow-back bugs, and
served_window_footprint_fits_effective_budget_including_window_scaled_compute pins it.
reconcile_window_to_served handles per-slot budgeting. The exam quiesces the fleet, so
concurrent demand is low. No code change needed; next is live re-measure + Slice A.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* docs(planning): live-validate Slice B — hard-rs 0/8-fake-zero → real 1/2 on the deployed binary

Deployed B, ran live hard-rs on Asha (Devstral-24B). Ledger contrast: pre-B runId
bf7bb829 = passRate 0.0 / 0-of-8 / 0 output tokens (the fake zero); B runId 97719703 =
passRate 0.5 / 1-of-2 / 855 output tokens / infraUnavailable:null (a REAL number). Same
benchmark, honest result. Lane held (quiesced exam) → Scored, not InfraUnavailable, so
Slice A (preempt) is the heavy-load/grid answer, not needed for single-GPU exams — exactly
as B→C→A predicted. InfraUnavailable path is unit-proven.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(cognition): Proctored Exam Session Slice A1 — ExamServingContext, the strategic ACQUIRE at the exam seam

The living-persona benchmark used to grab a bare ServingSteadyHold and ASSUME it was
measuring a co-tenant slot — the comment said "= Placement::ShareLane" but nothing computed
it. The strategic decision was implicit. This installs it explicitly:

- cognition/exam_serving.rs: ExamServingContext::acquire(capacity, resident, demand) runs
  the model-aware plan_placement kernel and acts on the verdict — ShareLane holds the live
  lane steady (RAII grow-back suppressor, reusing ServingSteadyHold), Spawn/CpuSpill hold
  nothing (the ephemeral/peer lane owns them) but the strategic verdict is still computed +
  probe-logged. ExamAcquire carries it for the ledger/curriculum. steady_fallback() preserves
  the historical hold when live inputs are unresolvable (never regresses).
- eval.rs (None,None) branch: build the real inputs from the live serving snapshot
  (current_serving) + governed_host_budget + footprint_for, then acquire the strategic
  context instead of the blind steady-hold. Her same base ⇒ ShareLane (co-tenant slot, no
  second 24B copy — the incident this arc started from), held steady for the run.

This is the seam the strategic layer plugs into: a DIFFERENT-base exam or a grid placement
computes Spawn/preempt here (the ephemeral-lane / grid path drives the actual spawn). The
decision is never silent again — Joel's "an algorithm, not a haphazard chaotic mess."

3 unit tests over the placement oracle (share+hold+RAII-release / different-base-spawn /
cant-fit-cpu-spill). Behavior-preserving on single-GPU (the live re-measure showed ShareLane
holds), so no regression; the value is the explicit, observable, capturable decision.

Slice A2 (grid AffinityFitPolicy over plan_grid_placement) follows.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* docs(planning): Slice A1 landed (ExamServingContext); A2 grid-affinity scoped + deliberately deferred

A1 (9b511f5) installs the strategic plan_placement decision at the exam seam. A2 audit:
capacity/grid policies are sim-only (no prod consumer), the two placement models differ in
shape (1-node-per-lane vs N-lanes-spread), and it needs a 40-construction-site schema thread
— so it is design/gym work with no live payoff, best built alongside the live grid-serving
consumer (#180) rather than rushed. The plan_grid_placement kernel it will use is already green.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(capacity): Proctored Exam Slice A2 — AffinityFitPolicy, model-aware grid placement (video + benchmarks concurrently)

The grid's LocalFirstFitPolicy places lanes by FREE BYTES — model-blind. It would cold-load a
base onto the emptiest node even when a peer already holds it WARM, paying a needless weight
load + cross-node transfer, and it eats the local GPU. AffinityFitPolicy converges the
resources::placement kernel's affinity rule onto the grid policy shape: rank nodes AFFINITY-FIRST
(a node already serving the demand's base beats one with more free RAM), then local (no hop),
then most-free — with NO local floor, so a fully-warm peer can take the whole demand and leave
the local accelerator free for live work.

This is the concrete answer to "video chat AND a benchmark at once": the exam rides the warm
peer while the local GPU stays free for the live huddle. Proven by the outlier test — a warm
peer with LESS free RAM beats an emptier COLD local node (byte-fill routes local+cold-load;
affinity routes to the warm peer, local_lanes=0), plus a no-signal fallback test showing it
degrades cleanly to locality-then-free (a strict superset of byte-fill, resilience invariants
intact).

Minimal-churn by design: the warm-base map is carried on the policy (constructed per-scenario)
rather than threaded onto the widely-built GridSnapshot/LeaseRequest — that ~48-site schema
change buys nothing while these policies are simulator-only. It lands WITH the live grid-serving
consumer (#180). The affinity IDEA is validated in the gym now; LocalFirstFit stays as the
model-blind baseline/negative control it beats.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* docs(planning): Slice A2 landed (AffinityFitPolicy, sim-validated)

AffinityFitPolicy ranks grid nodes affinity-first (warm > free) with no local floor, so a
warm peer takes the whole demand and the local GPU stays free for the live huddle — the
video+benchmark-at-once answer, proven by the outlier test. Snapshot-threading deferred to
the live grid-serving consumer (#180). Slices B, C, A1, A2 all landed.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(serving): Ludicrous mode — a benchmark declares Performance, the biggest window the machine can give (never a starved boot-window)

Joel: "extreme mode for benchmarks or ludicrous lol ... as big as the model needs for bench
software, whatever this machine can handle." The live incident: a 64GB M5 Pro with ~49GB free
and pressure 0.0 served a 2048 window, because at boot only ~19GB was free (model loading) so
the drive mode picked eco → tiny fraction → floored window, and then the exam's own steady-hold
PINNED it there while its 2240-token prompt overflowed → deadlock. The fix is to grow the
window, never clamp the prompt.

Mechanism (mirrors ServingSteadyHold):
- ServingLudicrousHold (refcounted RAII) + serving_ludicrous_active(). While held, host_budget()
  forces PowerMode::Performance (fraction 1.0 — "floors the whole GPU"), OVERRIDING
  serving_mode_for_pressure's timid read (which on UMA under-reports free memory). The drive
  mode follows the ACTIVITY (a declared benchmark intent → serve maximal), not just the pressure.
- ExamServingContext now holds Ludicrous instead of the steady-hold: this resolves the deadlock
  (steady-hold suppressed the very grow the exam needed). Ludicrous keeps the plan STABLE at max
  (nothing bigger to grow-back to, pressure-shrink overridden), so it SUBSUMES the steady-hold's
  mid-exam-relaunch protection WITHOUT pinning a too-small window. One grow-relaunch on acquire,
  one shrink on drop — bookends, not a flap (no thrashing).

Tests: serving_ludicrous_hold_is_refcounted_and_raii + exam_serving 3/3 + steady-hold test still
green. Live deploy validation (exam serves a big Performance window + scores real on the starved-
boot case) is the careful next step. First concrete step toward the Ludicrous↔Dream activity-
driven serving spectrum.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* fix(eval): revert exam wiring to steady-hold — naive Ludicrous acquire thrashed (relaunch bounce), needs grow→settle→pin

Live validation of the Ludicrous exam wiring (020bb65) caught exactly the thrashing Joel
warned about. The fresh boot already served a 22016 window (plenty), but forcing
PowerMode::Performance on acquire triggered an UNNECESSARY relaunch — and because Ludicrous
had REPLACED the steady-hold, nothing held the lane stable through it, so the exam bounced:
infraUnavailable{infra_faults:1}, 0 output tokens, on a huge window that easily fit the prompt.

My "Ludicrous keeps the plan stable, subsumes the steady-hold" reasoning was wrong: ACQUIRING
Ludicrous is itself a re-plan → relaunch, and B's retries got bounced too. The correct design
is BOTH, sequenced: acquire Ludicrous → wait for the grow-relaunch to SETTLE (decode-ready +
stable) → THEN steady-hold to pin it for the tasks. That async settle-detection is a careful
piece for a deliberate build.

So revert the exam to the validated steady-hold (healthy boots already give 22016, so the exam
works — B live-proven), and KEEP the Ludicrous mechanism (ServingLudicrousHold + host_budget
Performance override, unit-tested) as a ready primitive to wire correctly next. Ship-broken
isn't careful. exam_serving 3/3 + serving_ludicrous_hold test green.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(eval): Ludicrous done right — exam grows the window (Performance), SETTLES the relaunch, THEN pins (no thrash)

The correct wiring for "benchmarks get the biggest window the machine can give" — the thing the
naive 020bb65 got wrong (it forced Performance then ran, and the grow-relaunch bounced the
exam). The fix is the sequence Joel's "without thrashing" pointed at:

  GROW   — ExamServingContext declares Ludicrous (ServingLudicrousHold → PowerMode::Performance);
           the daemon re-plans the shared lane to the biggest window the machine fits.
  SETTLE — wait_for_serving_window_settle (new, watch-driven, in llama_server): within an 8s grace
           (> the 5s plan TICK) watch for the lane to go not-ready = a relaunch started; if it does,
           wait (bounded 180s) for it to come back decode-ready; if it doesn't, no grow was needed
           (already at target) → return immediately. No polling, no time-based stability guessing.
  PIN    — take the steady-hold so no FURTHER relaunch bounces the running exam.

ExamServingContext::acquire is now async (settling is a wait — the whole reason the sync version
thrashed); holds BOTH Ludicrous + steady via an ExamHold, released together on drop (RAII). A pure
`decide()` keeps the placement verdict unit-testable; acquire_exam_serving_context + the (None,None)
eval branch are async now.

Tests: 3 pure-decide verdict tests + 1 async grow→settle→pin holds test (both gauges set then
released; settle is a fast no-op with no live daemon). This is the benchmark end of the
Ludicrous↔Dream activity-driven serving spectrum, wired correctly.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
joelteply added a commit that referenced this pull request Jul 27, 2026
…load, place don't thrash (#234/#56) (#2050)

The serving-quality "2 tok/s" bug is log-proven SLOT CONTENTION, not decode/cache-size:
2 live slots (--parallel 2) < N active personas → the server picks a slot by LRU 65%
of the time (vs 35% LCP; when it DOES hit a warm slot sim_best=1.0/f_keep=0.99 and
cache-load failures=0), and every LRU pick forces the ~8s KV save+restore round-trip
("prompt cache update took 8235ms"). On one box this is the memory fixpoint
(lanes × (KV+compute) ≤ budget; more lanes → per-slot window < the ~9k prompt →
--no-context-shift overflow); MAX_LANES=2 is the settled-correct clamp AND the
system-wide admission ceiling (resource_admission), so it can't simply be raised.

The good-governor fix is to RECOGNIZE the overload instead of silently cramming:
plan_serving now emits grid_overflow_lanes = demand_lanes − lanes (saturating; the
FULL demand on the fits_on_gpu=false degrade path). That is the honest "over local
capacity by N" signal the pooled governor routes to a grid peer — Σdemand vs Σresource,
one decision, a single box being the pool-of-one case. Demand is bounded by the actual
beings/workloads (one Asha), so pooled grid capacity easily absorbs it and the thrash
dissolves.

Additive only: no change to lanes/served_context_window; new field surfaced (never a
silent clamp), ts-rs ServingPlan.ts binding regenerated, 21 serving_plan tests green
incl. the new demand_over_local_capacity_surfaces_grid_overflow_not_silent_cram. The
grid-placement CONSUMER of this signal is the next slice.


Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

Co-authored-by: Claude Fable 5 <[email protected]>
joelteply added a commit that referenced this pull request Aug 11, 2026
… pure lease policy (#395 slice 1)

Joel's design (2026-08, live-grounded): an operating MODE ("maximize benchmark capacity",
"dev sim", "balanced") is NOT new plumbing — it's a CONFIGURATION of the lease primitives
that already exist (per-consumer reservation floors, ReclaimPolicy, serving_fraction). This
lands the pure decision core: `GovernorMode::floors(&[ConsumerDemand]) -> Vec<PolicyFloor>`.

Design constraints baked in (each pinned by a test):
- COORDINATOR-FREE: a pure fn of a LOCAL view — no global authority, no I/O. The SAME
  object runs per-node on one box today, composes into the grid market next, and drops into
  the P2P "wireless" arbiter (radios sharing a finite medium, no central controller) with no
  rewrite. That's the box→grid→P2P scaling Joel described; a global-authority dependency here
  is the thing that would force a rewrite at the boundary.
- COST IS ALWAYS PRESENT, EVEN DONATED: every PolicyFloor carries a Price. "Free"/"donated"
  is not the absence of cost — it's a transaction at Price::FREE where the owner bears the
  cost (a ConsumerDemand::gift is free regardless of mode). The market/alt-coin settlement
  layer later changes only this number. Honest accounting now, economy later.
- ROLE-BASED, not id string-matching (the #70 smell): policy switches on ConsumerRole
  {Serving, Embedding, Vision, Realtime, Other}; a new consumer joins by declaring its role.
- FLOORS = MEASURED FOOTPRINT, never a magic constant.

Modes: Balanced (default, starve nobody) / BenchmarkMax (protect serving, yield everything
else → their Graceful leases reclaim → GPU frees for the run) / DevSim (protect serving +
recall embedding, yield vision/other). Output maps 1:1 onto
`ResourceDaemon::reserve(consumer_id, kind, floor_bytes)` — the wiring slice plugs it in.

Pure/unit only, no live wiring, no reboot: 6/6 tests green. Next (#395): VL lane as a
ResourceConsumer (closes the resource_drift + becomes mode-controllable), then apply this
policy through the daemon behind a mode selector; later the learned/market/wireless layer on
the same seam. Full design + ordering in memory (governor-modes-are-lease-policy-and-vl-
leasing-is-the-keystone). Relates #56/#126/#225/#106/#385.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply added a commit that referenced this pull request Aug 11, 2026
…tor (#392) + coordinator-free ResourcePolicy (#395 slice 1) (#2226)

* refactor(cognition): split the system prompt at the KV-cache boundary — scaffolding + invariant gate (#266)

Forensics (raw prompt-captures, benchy-18057-fix392): consecutive prompts share only
7,607 of ~14,706 chars — the per-turn presence/own-time framing block sits at position
4-5 of the system prompt (BEFORE context), so it flips every turn and caps KV reuse. She
re-prefills ~6k tokens each act (the ~13min SWE solves).

This commit lands the SAFE, additive half: `compose()` output is byte-IDENTICAL (all
existing framing tests stay green), but ordered_blocks is now partitioned into
`stable_blocks` (identity + [Taking your turn] + tools — a pure function of the persona,
cacheable) and `volatile_blocks` (own-time/presence framing + assembled context + clock).
`compose_split()` returns the two separately for the message builder to place stable in
the cacheable system message and volatile on the trailing turn.

VDD gate (TDD-first, per Joel): `stable_prefix_is_byte_identical_across_turn_shapes`
asserts the stable prefix is byte-identical across directed / undirected / self-initiated
/ holds-work / clock-on-off, and that the framing rides `trailing` instead. 4/4
deliberation_prompt tests green.

NOT yet wired: the caller (compose_system_holding → the faculty's .system) still uses the
whole-string compose(). Relocating the framing to trailing there is the behavior-changing
step — it must be its own RED→GREEN cycle (a factory-level test asserting
prompt_view(persona).system is byte-stable across turns), and it untangles the context
budget math (context is currently budget-fit INTO the system size). Deferred to a focused
pass. OPEN QUESTION recorded on #266: the measured 0% reuse (vs the ~50% a 7.6k common
prefix implies) hints slot-KV eviction is a CO-cause the prompt fix alone won't move —
settle with a stable-prompt A/B before claiming the 10x.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* fix(cognition): render per-turn framing LAST so the KV prefix caches through the grounding (#266)

Forensics (raw prompt-captures, benchy-18057): consecutive turns shared only 7,607 of
~14,706 chars because the presence/own-time framing block sat at char ~7607 — BEFORE the
assembled context — and its variant hard-flips every turn (DIRECTED / WORKING / SILENCE).
Every flip shortened the served slot's reusable KV prefix to that point and re-prefilled
the whole tail. Two of four citizens measured 0.0% cache reuse across 10 turns each; 96%
of persona compute was prefill (the ~13min SWE solves).

Fix is pure block ORDER: `deliberation_prompt` now partitions the system prompt into a
`stable` bucket (identity + [Taking your turn] + tools + assembled context + clock) and a
per-turn `trailing` bucket (own-time + presence framing), and `compose` emits them
`stable ++ trailing` — i.e. the hard-flipping framing renders LAST, after the grounding,
instead of before it. The served slot's reusable prefix now extends through identity +
tools + the stable head of the context; the framing flip falls past it and costs only its
own short re-prefill.

Deliberately NOT moving the framing onto a trailing USER turn (the first attempt): that
broke the "ask stays last" invariant and, worse, would end an undirected turn on the
presence block's PASS-affordance — biasing toward the exact idle-silence we fought
(#264). Framing is system-role instruction; it belongs in the system message, just after
the grounding, not in the conversation. The ask remains the last conversation turn.

VDD/TDD:
- `framing_flip_never_perturbs_the_cacheable_prefix` (deliberation_prompt): for a FIXED
  context, flipping directed/self-initiated/holds-work does not change `compose_split().stable`;
  the framing markers ride `trailing`; the standing grounding stays in `stable`.
- `directedness_flip_keeps_the_grounding_inside_the_reusable_prefix` (faculty, caller
  level): the longest shared leading run of prompt_view(directed).system vs
  prompt_view(undirected).system reaches THROUGH the [What you are working with] block —
  the flip falls after it. RED before the reorder (systems diverged at char ~7607).
- Updated the now-outdated invariant test premise; `mixed_thread_...` and
  `trailing_proprioception_...` unchanged. Full cognition suite: 947 passed, 0 failed.

Builds on the compose_split scaffolding (cdfa4f2). Still owed on #266: a live
before/after cache-reuse A/B on a healthy lane — the reorder is the byte-correct fix, but
whether it clears the residual 0% (vs slot-KV eviction as a co-cause) is a measurement,
not a claim.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* feat(resources): coordinator-free ResourcePolicy — operating modes as pure lease policy (#395 slice 1)

Joel's design (2026-08, live-grounded): an operating MODE ("maximize benchmark capacity",
"dev sim", "balanced") is NOT new plumbing — it's a CONFIGURATION of the lease primitives
that already exist (per-consumer reservation floors, ReclaimPolicy, serving_fraction). This
lands the pure decision core: `GovernorMode::floors(&[ConsumerDemand]) -> Vec<PolicyFloor>`.

Design constraints baked in (each pinned by a test):
- COORDINATOR-FREE: a pure fn of a LOCAL view — no global authority, no I/O. The SAME
  object runs per-node on one box today, composes into the grid market next, and drops into
  the P2P "wireless" arbiter (radios sharing a finite medium, no central controller) with no
  rewrite. That's the box→grid→P2P scaling Joel described; a global-authority dependency here
  is the thing that would force a rewrite at the boundary.
- COST IS ALWAYS PRESENT, EVEN DONATED: every PolicyFloor carries a Price. "Free"/"donated"
  is not the absence of cost — it's a transaction at Price::FREE where the owner bears the
  cost (a ConsumerDemand::gift is free regardless of mode). The market/alt-coin settlement
  layer later changes only this number. Honest accounting now, economy later.
- ROLE-BASED, not id string-matching (the #70 smell): policy switches on ConsumerRole
  {Serving, Embedding, Vision, Realtime, Other}; a new consumer joins by declaring its role.
- FLOORS = MEASURED FOOTPRINT, never a magic constant.

Modes: Balanced (default, starve nobody) / BenchmarkMax (protect serving, yield everything
else → their Graceful leases reclaim → GPU frees for the run) / DevSim (protect serving +
recall embedding, yield vision/other). Output maps 1:1 onto
`ResourceDaemon::reserve(consumer_id, kind, floor_bytes)` — the wiring slice plugs it in.

Pure/unit only, no live wiring, no reboot: 6/6 tests green. Next (#395): VL lane as a
ResourceConsumer (closes the resource_drift + becomes mode-controllable), then apply this
policy through the daemon behind a mode selector; later the learned/market/wireless layer on
the same seam. Full design + ordering in memory (governor-modes-are-lease-policy-and-vl-
leasing-is-the-keystone). Relates #56/#126/#225/#106/#385.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

---------

Co-authored-by: Claude Opus 4.8 <[email protected]>
joelteply added a commit that referenced this pull request Aug 11, 2026
…mpletes the config slice

The config getter (config_env::vram_headroom()) now has its live consumer. The pin
fit-gate ('can this model physically fit', via live_host_budget/governed_host_budget
→ host_budget_from) reads the operator headroom instead of a hardcoded 0.80 const.
Default 0.80 = byte-identical behavior; a dedicated foundry sets 1.0 → bigger models
pass the fit check. BigMama's SystemProfile.serving_budget_bytes reuses
host_budget_from, so it inherits the override transitively (config-read-free).

Kept host_budget_from PURE: the fraction is threaded as an INPUT (budget_fraction on
HostBudgetInputs — the struct's own doc blesses 'a new input = one added field'), read
via the getter at the live call sites, explicit in tests. So a test can't go
environment-dependent (the #72 anti-pattern). Removed the SERVING_BUDGET_FRACTION const
(single source now the config getter); all 6 construction sites updated; host_budget
test green.

SCOPED, not over-reached: the AUTONOMIC tick sizes serving by the pressure-adaptive
drive-mode fraction (mode.serving_fraction(): Performance 1.0 / Comfort 0.80 / Eco 0.55),
NOT this const — so this touches ONLY the fit-gate. Whether a foundry's headroom should
also lift the drive-mode CEILING is a real governor-policy question (careful not to
double-discount, per the #56/G8 comment) — that's the SystemProfile/governor follow-up,
coordinated with BigMama, not a naive same-edit here.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply added a commit that referenced this pull request Aug 11, 2026
…mpletes the config slice

The config getter (config_env::vram_headroom()) now has its live consumer. The pin
fit-gate ('can this model physically fit', via live_host_budget/governed_host_budget
→ host_budget_from) reads the operator headroom instead of a hardcoded 0.80 const.
Default 0.80 = byte-identical behavior; a dedicated foundry sets 1.0 → bigger models
pass the fit check. BigMama's SystemProfile.serving_budget_bytes reuses
host_budget_from, so it inherits the override transitively (config-read-free).

Kept host_budget_from PURE: the fraction is threaded as an INPUT (budget_fraction on
HostBudgetInputs — the struct's own doc blesses 'a new input = one added field'), read
via the getter at the live call sites, explicit in tests. So a test can't go
environment-dependent (the #72 anti-pattern). Removed the SERVING_BUDGET_FRACTION const
(single source now the config getter); all 6 construction sites updated; host_budget
test green.

SCOPED, not over-reached: the AUTONOMIC tick sizes serving by the pressure-adaptive
drive-mode fraction (mode.serving_fraction(): Performance 1.0 / Comfort 0.80 / Eco 0.55),
NOT this const — so this touches ONLY the fit-gate. Whether a foundry's headroom should
also lift the drive-mode CEILING is a real governor-policy question (careful not to
double-discount, per the #56/G8 comment) — that's the SystemProfile/governor follow-up,
coordinated with BigMama, not a naive same-edit here.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply added a commit that referenced this pull request Aug 19, 2026
…and the one that always yields (#56)

Joel: *"crushing a benchmark while simultaneously in a video call with several persona can ONLY
work if the intelligent systems have handles to the interface/trait driven consumers of
resources... Conversely, the concerns themselves need to decide how to fit within budget."*

Staging allocated a whole dataset with no regard for anyone else and OOMed the box. The earlier
`drop(rows)` removed a gratuitous doubling and changed NOTHING structural: a large enough suite
still evicts a live call by winning a race against `malloc`. A consumer that does not lease
cannot be arbitrated, and an unarbitrated consumer is not a peer — it is a hazard.

BOTH HALVES OF THE SEAM, which already existed and staging used neither:

  ASK   `available_for(CONSUMER_ID, Ram)` → `StagingPlan::decide` runs BEFORE the allocation.
        Refusing with a NAMED shortfall beats an OOM that takes the citizens down with it.
  GIVE  `ResourceConsumer::{footprint, reclaim}` → the governor can now take bytes back.

WHY THIS SHAPE IS NEW FOR THE TRAIT, and why it was worth implementing rather than special-casing.
Serving (#79), Bevy and Voice are all fat-and-holding: they own expensive residency for as long
as they are up, and reclaim means degrading something a human perceives — so they weigh, and
sometimes REFUSE. Staging inverts every axis: it holds only during a fetch, it holds nothing
when idle, and every row it holds is already on disk. It is the cheapest victim on the box.

So it NEVER refuses a RAM ask — not on Pressure, not on Rebalance, not on Shutdown. Yielding
costs a re-read and nothing perceivable, which is exactly what makes a benchmark safe to run
beside a video call instead of racing it. A test pins all three reasons; if this ever starts
refusing, a benchmark can starve a call.

The one honest complication: an ask for VRAM is REFUSED rather than answered with freed host
bytes. Reporting the wrong kind would corrupt the ledger into believing device memory came back.

`StagingResidency` is injectable for the same reason `RenderSurface` is — the reclaim
disposition is proven without a process-global area or a live governor. The footprint returns to
zero the instant the rows drop (normal path AND under reclaim), because a consumer reporting
phantom bytes makes the governor evict a REAL holder to recover memory nobody has — the mirror
image of the OOM this exists to prevent.

DELIBERATELY ABSENT: a `Streamed` variant. When the budget cannot hold a suite the better answer
is to page and project row-by-row rather than refuse — but that needs the pager inverted to a
per-page callback and the disk cache moved to JSONL so it can be read incrementally. A variant
nothing can construct is a lie about what the system does, so it gets its own slice, at which
point `Refuse` narrows to "not even one page fits" and everything else adapts.

6 new tests; 172 green across bench_staging + bench_task + benchmark + all `resources::`;
de-hardcode guard green.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply added a commit that referenced this pull request Aug 20, 2026
…amed projection, JSONL cache (#56/#370)

The previous commit made staging a governed consumer that could plan and yield, but it could
only succeed or fail. A concern that can only succeed or fail forces a human to arbitrate. This
gives it the middle state, which is the one that matters:

  suite fits the budget          → Resident   hold it, hand the caller a Vec
  suite doesn't, one page does   → Streamed   page it, project each row, drop it
  not even one page fits         → Refuse     name the shortfall

THE PAGER IS NOW THE PRIMITIVE. `stream_hf_rows(dataset, config, split, on_row)` hands one row at
a time and never accumulates; `fetch_hf_rows` is a thin collector over it. The
accumulate-then-return shape WAS the root of the OOM — every caller got the whole suite whether
it needed it or not, and `benchmark/fetch` needed only a count. Inverting to a callback makes the
memory profile the CALLER's choice behind one paging + caching + error path
([[the-compression-principle]]).

THE CACHE IS NOW JSONL, and that is not cosmetic — it is what makes streaming possible at all. A
single JSON array cannot be read incrementally: `from_slice` must materialize the whole thing. So
the format was the constraint, and the old `.rows.json` files are MIGRATED on first read (read
once, rewritten as JSONL, legacy removed) rather than discarded — throwing away a correct 500-row
cache to change an extension would re-pull from the network for nothing.

THREE CORRECTNESS PROPERTIES the rewrite made explicit, none of which the old path had:
- The network path writes to `.jsonl.partial` and is renamed ONLY after both guards pass, so a
  reader sees the whole cache or no cache — never a short one. An interrupted fetch used to be
  able to leave nothing at all; now it cannot leave something misleading either.
- A truncated pull (>= MAX_ROWS) deletes the partial instead of promoting it. A truncated cache
  that survives is a wrong denominator that reproduces on every later run.
- An EMPTY cache file is treated as interrupted-write debris and re-fetched, not reported as an
  empty suite.

The streamed arm projects page-locally through the same `SuiteAdapter` — one row alive at a time
— and records a projection failure without aborting the drain, so the caller can still tell a
projection failure from a fetch failure. Staging declares the plan's PEAK to the governor, not
the suite size: for a streamed plan those differ by the entire point of streaming, and reporting
the suite would have the governor evicting a peer to make room for bytes staging will never hold.

`benchmark.staging.plan` carries `streaming` + `peak_bytes`; `benchmark.suite.staged` carries
`streamed`. Which mode ran is a receipt, not an inference.

51 green across bench_staging + bench_task + swe_bench + benchmark.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply added a commit that referenced this pull request Aug 20, 2026
…only the GPU (#56)

The governor has carried ResourceKind::Ram through leases, footprints, reclaim and
available_for since #56. The daemon's capacity_sources vec has carried ONLY the GPU source
the whole time. So capacity(Ram) was 0, and therefore available_for(_, Ram) returned 0 for
EVERY consumer, permanently.

Nothing noticed for months because serving, Bevy and voice all lease VRAM. The first
consumer to actually plan against RAM — benchmark staging — was refused instantly on a box
with tens of gigabytes free. The machinery was complete and one wire was missing, which is
this codebase's recurring failure shape: a capability that is structurally unreachable
while looking finished, surfacing only when something finally tries to use it.

HostRamCapacitySource + LiveHostMemory, registered unconditionally at boot (unlike the GPU
there is no detect() that can fail — every host has RAM).

THE NON-BLOCKING CONTRACT, and the accessor this does NOT use. CapacitySource::ceiling_bytes
is read on the daemon's hot tick and its value used while the accounting lock is held, so it
must be a cached, non-blocking read. MemoryPressureMonitor::budget_snapshot() has exactly the
fields wanted and is exactly wrong for it: it takes the reporter read lock and calls budget()
+ report() on every registered reporter. This reads current_available_bytes() instead — a
lock-free atomic the monitor loop refreshes every 2s.

THE COLD-BOOT TRAP, which is the same defect shape as the bug being fixed. Total from the
monitor's snapshot is 0 until its first poll, and a ceiling of 0 does not mean "no RAM", it
means "not measured yet" — reporting it would reproduce refuse-everything for the first
seconds of every boot. Physical RAM does not change, so total is probed ONCE at construction
and the ceiling is right immediately. Symmetrically, an absent available reading yields
used=0, the trait's documented degradation to capacity − granted, never "all of it is
spoken for".

Reserve is proportional with bounds — (total/8).clamp(1 GiB, 8 GiB) — in ONE place. A flat
constant is noise on a 128 GB M5 and half the machine on an 8 GB box, and the same code is
claimed to run on both.

Tests pin all four: ceiling less reserve, the cold-boot trap in both directions, the reserve
across the 8/32/128 GB ladder, and an oversized reserve flooring at 0 rather than wrapping
into an exabyte ceiling. 6/6 green.

Also carries the benchmark-staging consumer this unblocks (StagingPlan/StagingArea +
registration as the fifth governed consumer).

NOT YET LIVE-PROVEN: the streamed staging path has still never executed, because the RAM
ceiling is what was blocking it. That proof is owed on the next deploy.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply added a commit that referenced this pull request Aug 20, 2026
…n layer stops double-counting (#56)

`ResourceKind::Vram`'s own doc has always stated the contract and assigned it:

    GPU memory. On UMA (Apple Silicon) this overlaps `Ram` physically;
    the authority's scan layer IS RESPONSIBLE for not double-counting.

It was written, assigned to capacity.rs, and never implemented. So the governor kept two
independent ledgers over one physical pool, and each could grant against bytes the other
had already spent.

MEASURED on this M5 before the fix, from `resources/board`:

    kind=vram  capacity 55,125,917,696  physicalUsed 38,171,508,736  available 16,954,408,960
    kind=ram   capacity 60,129,542,144  physicalUsed 61,863,329,792  available 0

VRAM advertising 16.9 GB of headroom while RAM correctly reported 0 — both describing the
same 6.39 GiB of real free memory. A serving lane could have leased ~17 GB that was gone.
The two capacities also sum to 107 GiB on a 64 GiB machine, which is the double-count
stated as arithmetic.

This is NOT a coincidence of two estimators disagreeing. metal_monitor's Unified arm reads
`host_statistics64(HOST_VM_INFO64)` — the HOST's VM free pages — as the GPU's free_bytes,
because on Apple Silicon that IS the truth. The bottom of the stack knew; the top could
not ask.

THE FIX, in three parts:

1. `MemoryMode::{Unified, Discrete}` lifts from a metal_monitor private detail onto the
   `GpuMonitor` trait. It was private on the stated assumption that "production callers
   should use the trait methods, which abstract the mode away" — true for pressure (a
   ratio is a ratio), false for the governor, which must know whether it is handing out
   bytes from one pool or two. Detected from `device.has_unified_memory()`, never from
   target_os: an Intel Mac with a discrete AMD card also runs macOS and is NOT unified.
   Trait default is Discrete, so every existing adapter is unchanged rather than silently
   wrong, and CUDA keeps two genuinely separate axes.

2. `UnifiedMemoryPool` vends TWO CapacitySource views over ONE measurement. Pool ceiling =
   host physical − reserve (NOT recommendedMaxWorkingSetSize, which is a GPU working-set
   hint smaller than physical memory). VRAM view ceiling = min(pool, hint), so the hint
   keeps its meaning as a cap on GPU allocation without becoming a second pool. Both views
   report the SAME used, which is the entire fix: neither axis can offer bytes the other's
   residency consumed.

3. Boot branches on the detected mode. Unified → the pool's two views. Discrete → GPU
   source + host RAM source, exactly as before.

The kinds deliberately survive rather than collapsing into one. A serving lane asking for
VRAM and staging asking for RAM are semantically different requests even when the bytes
are identical, and on a discrete box they are physically different too — erasing the
distinction would be wrong on CUDA.

KNOWN RESIDUAL, stated not hidden: grants are still tracked per kind, so within a single
tick two axes could each grant against the same free bytes. The next tick closes it —
a grant becomes residency, residency is the shared measurement. That is the same window a
single axis already has between acquire and the next scan; this does not widen it, and
`committed = max(granted, physical_used)` means the larger always binds. A cross-kind
grant ledger would close it fully and is deferred.

Tests reconstruct the incident with the board's REAL numbers: both views agree on used,
VRAM's 16.9 GB phantom goes to 0, the hint caps VRAM without shrinking the pool, an
oversized hint never raises the ceiling, and the cold-boot trap does not reach either
view. 10/10 green.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply added a commit that referenced this pull request Aug 20, 2026
…not (#56)

MEASURED on this M5, live `resources/board`, 2026-08-19:

    vram: physicalUsed 50.95G  attributed 6.81G (serving)  UNOWNED 44.14G
    ram:  physicalUsed 50.95G  attributed 0.00G            UNOWNED 50.95G

87% of resident memory had no declared owner. The governor could see the bytes were
gone and could not say who had them, so it could not ask anyone to give them back.

WHY THAT IS NOT MERELY AN OBSERVABILITY GAP. A consumer deciding what it can afford
sees `capacity − everything resident`. With nothing attributed, "everything resident"
is indistinguishable from "everything immovable", and a planner facing all-immovable
memory can only shrink. That is the mechanism behind serving a 0.5B on a 64 GB machine
(#438) and behind grow-back never happening (#214) — one missing attribution seen from
two ends. Not one line of code was wrong; nothing was accountable.

THE SHAPE IS BORROWED DELIBERATELY. `disk_eviction::every_cache_class_has_a_decided_
eviction_story` already does exactly this for disk — enumerate every class the substrate
writes to, fail on any with no decided owner. CLAUDE.md calls it "the difference between
a red test and a user's trashed machine". Memory had no twin. This is it.

`standard_memory_holders()` names all nine holders on this box. Five are Declared
(serving, render, voice, perception, benchmark-staging). Four are Undeclared, each
naming the task that closes it rather than a bare TODO:

  vision (#106/#395)  — a SECOND llama-server, Qwen2.5-VL-7B on :58091, measured 9.4 GB
                        resident, registers nothing. Largest unowned holder, and because
                        it never yields, a 27B and vision cannot be planned against one
                        pool. This is precisely the VL-as-consumer keystone #395 names.
  embed (#225)        — has a consumer-id constant AND a honoured reservation floor, but
                        registers no consumer. Half-wired is the worst state: serving
                        budgets around a floor for bytes nobody reports.
  core (#178)         — the core process itself, the one holder that can never be
                        reclaimed by asking, so its job is to be COUNTED.
  grade-subprocess (#381), forge-train (#99/#137).

Undeclared is a tracked promise, not a shrug — the guard rejects a reason that names no
task or is too short to act on, so the class can never be the silent one again.

`Reconciliation` computes `physical_used − attributed − external` per kind and explains
the CONSEQUENCE, not just the number, because an unowned fraction means nothing to a
reader who does not know it forces the planner to treat memory as immovable.

Tests: the decided-owner guard; a cross-check that Declared rows use the constants the
code actually registers under (prose cannot fake wiring, the #344 property) which also
asserts embed is still NOT a consumer so its row gets moved when #225 lands; the
reconciliation reproduced from the incident's real numbers; and over-attribution
flooring at zero rather than wrapping. 4/4 green.

NEXT, and this is deliberately not bundled: the reconciliation is computed but not yet
surfaced on the board, so the 87% is still only visible to a code reader. Then vision as
a real consumer, then the self-eviction budget (a consumer must be able to re-plan the
model it is already running — today its own residency is subtracted from its own budget,
which is the ratchet).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply added a commit that referenced this pull request Aug 20, 2026
… is empty" — my regression (#56)

FOUND LIVE, and it is mine. `13cec02ef` routed BOTH governed memory axes through
`LiveHostMemory`, which read only `current_available_bytes()` — the atomic
`MemoryPressureMonitor` publishes. I documented an unset atomic as "has not polled yet",
a couple of seconds at boot, and degraded it to `used = 0` on that basis.

That reasoning was wrong in one specific, dangerous way. An unset atomic ALSO means
"that monitor is not publishing", which is unbounded — and because the unified pool
routes both axes through this one reader, one silent monitor blinded the entire governor.

MEASURED on this box minutes ago, same instant, two sources:

    system/resources:  total 64.0G  used 54.2G  available 9.8G  swap_used 12.3G
    resources/board:   physUsed 0.00G           available 51.84G

The machine was 54 GB used and swapping 12 GB while the governor reported half the pool
free. Erring toward "plenty available" is the worst direction available: it over-grants
into a host already past its limit.

Before unified memory the VRAM axis read the GPU monitor independently and could not be
blinded this way. Collapsing the axes onto one pool was right; collapsing them onto one
SOURCE was the mistake, and I made it in the same change.

FIX: `available_bytes()` now falls back — monitor atomic, else a direct `sysinfo` sample
(the same `host_statistics64` read the monitor itself makes, and the one
`system/resources` already serves from), else the last value either source produced.
`None` only if nothing has ever produced a reading. Stale beats fabricated-empty: an old
number keeps the governor conservative; a zero invites over-grant.

Cost: zero extra syscalls on the healthy path (the atomic answers first); at most one
cheap syscall per ~1Hz daemon tick on the degraded path. `new()` also seeds
last-known-free from its existing construction-time probe, so the reader is useful from
its first call.

NOT FIXED HERE, and it should not be hidden by this: MemoryPressureMonitor's atomic is
0 on this boot while sysinfo works fine, so that monitor is not publishing at all. This
change stops that outage from corrupting the governor; it does not explain it. Separate
investigation — the resilience fix is right on its own merits either way.

10/10 capacity tests green.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply added a commit that referenced this pull request Aug 20, 2026
… carries provenance (#56)

Joel, 2026-08-19: "it's whatever vision is estimated or monitored to be, which is surely
singular source of truth, even if it did start at some estimate — which is why
handle/adapter for all memory footprints (even if this adapter is permitted to hard code,
go from last measured and so on as part of its own; you'd need to store the state if so).
Don't craft some recursive loop whatever you do."

THE PROBLEM THIS PREVENTS. I was about to add a second way to size the vision sidecar,
alongside the one serving already uses. Two sizings of one holder is how VRAM and RAM came
to disagree by 23 GB about a single physical pool. So: one adapter per holder, and it is
the only thing entitled to answer. It MAY be crude inside — a hardcoded figure, a catalog
estimate, last-measured-with-age — and may keep whatever state that needs. What it may not
do is make its crudeness invisible.

PROVENANCE, because an estimate that reads like a measurement is worse than no number:
`FootprintReading { kind, bytes, provenance }` where provenance is Measured | Estimated |
LastKnown{age_ms} | Unknown. `usable_bytes() -> Option<u64>` is the call shape that makes
"unknown" impossible to accidentally add to a budget.

UNKNOWN IS NOT ZERO, and this is the day's lesson typed. `serving_footprint_fn` ends in
`.unwrap_or(0)`: a LIVE lane whose catalog row will not resolve reports zero bytes held.
Cosmetic on a display; as a budget term it is precisely the defect that cost today —
`sysinfo::available_memory()` returning 0 while the machine was 54 GB used and swapping,
and every consumer concluding the box was empty. A reading that cannot be made must say
so. A holder that genuinely holds nothing still reports `Measured(0)`, which is a
different fact and stays usable.

ACYCLICITY, made structural rather than advisory. Footprint adapters are LEAVES: they may
read hardware, the catalog, a process table, their own cache — never the governor, a
budget, a board, or another holder. The governor computes budgets FROM footprints
(`budget_for_replacing` = available + own residency); a footprint that consulted a budget
would be circular and order-dependent — the self-eviction ratchet again, but
non-terminating instead of merely wrong. The trait is handed no governor, so the cycle is
unrepresentable, not merely discouraged.

`LastKnown` is provided so adapters do not each hand-roll live → last → never, and holds
only bytes+timestamp, which keeps them leaves by construction.

Tests pin the four ways this gets silently wrong: unknown reading as a quantity; provenance
lost in transit so an estimate passes as a measurement; a fallback fabricating a value
before any real read; and a backwards clock forging a fresh age on stale data. 4/4 green.

NEXT (deliberately not bundled): serving and vision both adopt this, so the vision
add-back term is the live provider's reading rather than any constant — and the
`unwrap_or(0)` on the budget path becomes a loud fault.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply added a commit that referenced this pull request Aug 20, 2026
… footprint adapter (#106/#395/#56)

Joel: "it's whatever vision is estimated or monitored to be, which is surely singular
source of truth… handle/adapter for all memory footprints."

Both adapters answer through the SAME calculation — the catalog's ModelFootprint sizing
(weights + lanes × kv(window) + prefill compute reserve) evaluated at the lane's own live
shape, re-read from ServingSnapshot every call. Swap the model or resize the window and
the number moves on the next tick; there is no cached size and therefore no invalidation
step anyone can forget. Nothing here invents a number.

KEYED ON THE FEATURE, NOT THE SIDECAR ("or the feature really"). Vision on this node comes
from one of two places: the persona lane when its own model sees (Qwen3.8-27B does), or a
separate describe sidecar when it does not. The adapter reads whichever endpoint the
snapshot has VERIFIED, so a change of provider needs no edit here.

That framing carries the correctness case, and it is the day's bug in miniature. When the
main lane IS the vision provider, its bytes are already charged by serving — attributing
them again double-counts one residency across two holders, inflating attributed bytes by a
whole model and shrinking every budget by the same amount. Self-inflicted scarcity,
indistinguishable from the real thing, and the exact shape that had VRAM and RAM
disagreeing by 23 GB about one physical pool. So that case reports Measured(0): the vision
FEATURE holds nothing of its own. Pinned by
`vision_provided_by_the_main_lane_holds_nothing_of_its_own`.

UNKNOWN, NEVER ZERO, on the branches that can't answer. A ready lane with no served window
or no named model is Live(reason) → Unknown, not 0 — a live server we cannot size still
holds gigabytes, and reporting 0 tells every other consumer those bytes are free and
invites the concurrent OOM. Distinct from `nothing_serving_is_a_real_zero`, which stays a
usable Measured(0). That distinction is the whole point of the Provenance ladder.

THE PROBE, so a bad decision is readable instead of re-derived: class
`resources.footprint` emits holder, model, window, lanes, bytes and provenance at the
moment the reading is taken. A wrong grant can now be traced to the term that produced it
— which is not how today went, where a monitor publishing a silent zero cost hours of
guessing at inputs nobody had recorded.

Leaf discipline holds: catalog snapshot + watch borrow, both non-blocking, no governor
handle. 4/4 green.

TWO FINDINGS for follow-up, both instances of the rule this commit applies:
- `plan_sidecar` sizes the SAME holder differently — `weights_bytes + SIDECAR_OVERHEAD_BYTES`
  (a flat 2 GiB) against this path's calculated model. Two sizings of one thing; the gate
  should call the adapter.
- `footprint_for` re-stats the GGUF on every call to get `weights_bytes`. That belongs on
  the catalog row, hydrated once at resolution — the "stored catalog values" half.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply added a commit that referenced this pull request Aug 20, 2026
…bytes on the catalog row (#106/#56/#74)

Joel: "Fix 1 and 2 before we proceed. It's just not gonna work if incomplete. It just
shifts the bug." Correct — an adapter that unifies the ledger while the GATE keeps its own
arithmetic has moved the disagreement, not removed it.

FIX 1 — ONE SIZING, so the gate and the ledger cannot disagree.
`plan_sidecar` admitted on `weights_bytes + SIDECAR_OVERHEAD_BYTES`, a flat 2 GiB standing
in for "mmproj + KV + compute buffers", while the resource ledger attributed the same
holder using the calculated model. Two answers for one holder, neither wrong on its own
terms, so nothing could catch the disagreement — and the constant is wrong in BOTH
directions: far too generous for a 2B, far too thin for a 30B at any real window.

The constant is deleted. `find_candidate` now sizes each candidate through
`serving_footprints::resident_bytes_for` — the same function the adapter attributes with —
and `plan_sidecar` is reduced to a pure comparison against that number. A row that cannot
be sized is SKIPPED with a named reason rather than admitted on a guess: refusing to spawn
is recoverable, spawning into memory nobody accounted for is the mid-load SIGKILL.

That shared function also fixes a real under-report the weights-only path had all along:
the multimodal PROJECTOR is resident alongside the model, so a vision lane sized from the
GGUF alone is short by the whole mmproj (~1.4 GB for the VL-7B).

FIX 2 — THE ROW IS THE SOURCE OF TRUTH for artifact bytes.
`footprint_for` re-`stat`ed the GGUF on EVERY call to get `weights_bytes` — a syscall per
poll, on the governor's accounting tick, for a number that cannot change while the path is
valid. `Model` now carries `weights_bytes` + `mmproj_bytes`, stamped ONCE by
`artifacts::hydrate_artifact_sizes` at the same moment the paths are resolved: a path and
its size are one fact discovered together, so they are stored together. `attach_local_artifact`
(the models/pull route) hydrates too, and `detach_local_artifact` clears both — a row never
carries a path without its size, or a size without its path.

`None` means NOT RESOLVED, never zero. The stat survives as the fallback for rows built by
hand in tests and fixtures — not dead code, but the exception rather than the steady state.

UNPLANNED BENEFIT, and it is the one that will keep paying: residency is now testable
WITHOUT A FILESYSTEM. A hydrated row carries its own bytes, `footprint_from_parts` is pure,
so the new `the_spawn_gate_sizes_the_sidecar_the_way_the_ledger_will` asserts the real
properties off-disk — that residency exceeds bare weights, that the projector is counted,
and that a 1 GB model is charged LESS than a 5 GB one. That last one is the property a
constant cannot have, and it is exactly what the old 2 GiB got wrong.

`ModelSpec` deliberately does NOT gain these fields, for the same reason it omits
`parameter_count`: a hand-authored byte count goes stale the moment a quant is re-pulled.
Discovered, never declared.

280 tests green across model_registry / serving_daemon / serving_plan / resources / hydrate,
0 failed.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply added a commit that referenced this pull request Aug 20, 2026
…probes to debug it (#106/#395/#56)

Joel: "wire it up with probes then we can debug it." The adapters were green and had zero
call sites — green components with dead wiring is the exact shape that let
DiskPressureMonitor log `level=high [no reporters]` while the disk filled.

REGISTERED. `register_as_consumer` now also builds `CatalogFootprintSource::vision` and
adds it via a new `MonitoredHolder`. The holders table moves `vision` from Undeclared to
Declared, and `declared_holders_use_the_ids_the_code_registers_under` is what proves the
row and the registration agree — that guard passing IS the wiring receipt, not a comment
claiming it.

MONITOR-ONLY, AND THAT IS THE HONEST SHAPE. It declares the bytes and REFUSES reclaim with
a named reason. Vision bytes are releasable — but by the serving reconcile
(`if main_sees { sidecar = None }`), not by any inbound handler. Declaring a reclaim it
cannot perform would have the authority plan against a release that silently never
happens, which is worse than declaring none. The refusal is probed so an operator sees the
gap instead of inferring it.

UNKNOWN STILL ISN'T ZERO, and at this seam the rule finally bites. `footprint()` DROPS a
row it could not size rather than contributing 0: the board sums declared footprints, so a
0 would assert "this holder holds nothing", a stronger and falser claim than declining to
answer. Omitting it leaves those bytes in `unowned`, where they read as immovable —
conservative, and visible as the gap it actually is.

THE PROBES (three, each a different question):
- `resources.footprint.wired` — fires at registration. Answers "is it connected at all",
  the question I could not answer about my own code an hour ago.
- `resources.footprint` — holder, model, window, lanes, bytes, gib, provenance, and a
  `why` string naming which branch produced it. Emits on TRANSITION only: a changed byte
  count, a changed provenance, or ANY Unknown. Unknown always fires because it is the
  state that silently poisons a budget. Steady numbers stay quiet — #399 measured
  `serving.plan` at 2.6 rows/s, 51% of the entire probe stream, which is how a glass box
  becomes a fog bank.
- `resources.footprint.reclaim_refused` — holder, target bytes, and the reason, so a
  refused reclaim is a readable event instead of a mystery non-event.

218 tests green (resources + serving_daemon + holders + footprints), 0 failed.

DELIBERATELY NOT IN THIS COMMIT: the capability-keyed add-back. `governed_vram_ceiling` is
model-agnostic — it has no candidate in scope — so applying the add-back there would
inflate the budget for NON-vision candidates too, granting bytes the sidecar will not
release, which is an over-commit and an OOM rather than a bad plan. It belongs where
candidates are scored, and it should be written against a vision footprint the probe has
actually shown on this box. Writing it first and measuring after is the launch-and-pray
order, and this is the arithmetic where that costs a wedged lane.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
joelteply added a commit that referenced this pull request Sep 10, 2026
…nbuilt governor (#3957)

`EphemeralServingLane::spawn` carried this, for months:

    /// Budget-gating ("does this fit alongside the live lane?") is the
    /// `ResourceGovernor`'s concern (#56); this primitive only stands the lane up.

**`ResourceGovernor` does not exist.** All eight of its mentions in the tree
are doc comments promising a future owner. So the decision was delegated to
nobody, and the only question ever asked before placing another engine on the
device was `first_free_port` — *is a port free?*

A port is cheap and genuinely per-lane. The GPU is one shared thing. Using
port-freeness as a proxy for device capacity let three vision sidecars
co-exist on one GPU: ports 58091/58092/58093, and `first_free_port` means N+1
exists ONLY because N was occupied, so the filenames themselves prove the
concurrency. Each ran at 3.1-8.6 tok/s against 60-80 normal for that box —
not a slow model, three engines time-slicing one device.

The reclaim machinery was never the problem. `lane_registry` records every
lane, `lane_pidfile` adopts-or-reaps the live one, both with real Windows
arms and a shared never-blind-kill rule. The problem is that every reclaim
fires on an EDGE — `sweep_orphans` at daemon init, `sweep_all` at `stop`
(which `reboot` skips by design, keeping the live lane up for adoption),
`Drop` on graceful exit — so nothing bounded engines WITHIN one core's life.

So the question moves to where the decision actually is:

1. **Serialize.** `EPHEMERAL_SPAWN_GATE` holds one cold-spawn at a time,
   process-wide. This existed as `EVAL_LANE_SPAWN_GATE` in `cognition::eval`
   — at ONE caller, so the vision sidecar inherited nothing from it. A
   discipline only one caller opts into is not a discipline. Eval keeps its
   gate for the concern that IS its own (same-key racers sharing a warm
   lane); the lock order is documented on both, and that nesting is the only
   one in the tree.
2. **Census.** `lane_registry::records()` plus the existing
   `is_llama_server` identity check, so the decision is taken against lanes
   that are actually alive. Dead and pid-recycled records are dropped as
   bookkeeping, never signalled. Done INSIDE the spawn because neither
   boot-time sweep can see a sibling that appeared five seconds ago.
3. **Admit or refuse.** A late-bound authority the serving daemon installs,
   built over the same `live_host_budget` + `footprint_for` pair
   `pin_fit_checker` uses so the gate and the planner cannot disagree. It
   models CO-RESIDENCE: an ephemeral lane JOINS the live lane, so the
   incumbent is spent, never credited back — the one sign flip that separates
   this from a pin's arithmetic, and getting it backwards would admit exactly
   the second engine this refuses. Refusal is loud, returns an error, and
   states every term.

Weights, not weights+KV, as the cost: the same choice `pin_fit_decision`
makes, weights dominate (18.97 GB against a 24.63 GB budget on this host) and
are the term nothing can shrink, while KV is what the planner sizes down
under pressure. It under-states, so the gate errs toward admitting — a guard
against a second ENGINE, not a precise accountant.

Tests: the arithmetic is extracted pure (`lane_admission_decision`) and
pinned four ways — a second engine that does not fit is refused with its
terms named, the live lane is spent rather than credited, siblings weigh (the
measured failure was the THIRD sidecar, each individually affordable), and an
already-overcommitted device floors at zero headroom instead of wrapping. The
census is pinned non-destructive and complete across both roles. And
`the_serving_daemon_installs_the_admission_authority` fails the moment the
install call is deleted — the failure mode #56 actually had.

Full `--lib`: 44 failures, byte-identical to the clean base (GPU, python,
screenshot-binary and Windows path tests on this box). `comm -13` empty.

Closes #3956.


Claude-Session: https://claude.ai/code/session_01Q4NU4VNiELPQfBpCacDZGc

Co-authored-by: Claude Opus 5 <[email protected]>
joelteply added a commit that referenced this pull request Oct 11, 2026
…t kept or lost its prefix (fork #56) (#4955)

One commit over 243f3a429, log-only: one SLT_INF per resume decision (outcome; raw lcp, lcp after
reuse, slot tokens, pos_min, pos_min_thold, n_swa, checkpoint count, chosen checkpoint, n_past of
the prompt). Card c6640f7b's engine half: on the 5090 every restore of Kimi's page re-prefills from
~0 although checkpoints before the divergence exist, and the lines that would say why were trace-level.


Claude-Session: https://claude.ai/code/session_01FRQWzgSfo79JtnwZywHKrE

Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
joelteply added a commit that referenced this pull request Oct 29, 2026
… lane (#5582)

* The prefill throttle is deleted: one engine's prefills draw no extra memory, and the gate serialized them

One llama-server context reserves its worst-case compute graph once, at load, and packs
every slot's tokens into each llama_decode, so concurrent prefills in one engine draw no
transient memory beyond it. The throttle (#56) guarded that non-existent spike from live
free GPU, which on unified memory is system RAM: on the M5 it held 1 permit 22.5% and
2 permits 49.4% of 87 minutes for four minds, and a mind that already held a lane waited
a median 24.6 s (p90 83 s, 5,914 s in total over 161 acts) before her model call
(2026-10-28, build 7ace740; delib.gate.lane_acquired -> delib.gate.prefill_acquired).

The per-prefill bytes the plan publishes stay, as inference::prefill_spike, for grid
placement (capacity::lease::decide_render_lane). Removed: the semaphore, its live
reconcile on the serving tick, and the second permit in GenerationAdmission. 430 lines
out, 25 in.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

* The reserved lane is lent to work whenever nothing directed is pending: no engine slot idles for a mention

The loan required a work call to fit the interactive wait budget (60 s). A resident's
model call has a median of 71 s, so the reserve was never lent: one of four engine slots
sat idle while the fourth resident queued for a lane, a median 25.7 s and p90 131 s
per model call (M5, 176 acts, 2026-10-28, build 7ace740; admission.lane.granted).
A directed arrival now takes the next lane any call releases. The loan is still a
try-acquire on a free lane, never a park, and a pending directed line still re-arms it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

dependencies Pull requests that update a dependency file javascript Pull requests that update javascript code

Projects

None yet

Development

Successfully merging this pull request may close these issues.

0 participants