Skip to content

fix(readme): Depersonalize recipe examples + Phase 4 daemon generator plan - #225

Merged
joelteply merged 2 commits into
mainfrom
feature/phase-4-daemon-generator
Dec 7, 2025
Merged

joelteply merged 2 commits into
mainfrom
feature/phase-4-daemon-generator

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Summary

This PR makes two quick fixes:

1. Depersonalize README Recipe Examples

Problem: README contained biographical/personal example ("Acme Corp") that made the project seem like a personal tool rather than a universal product.

Fix: Changed customer support recipe example from specific business name to generic "your business":

  • Before: customer-support-acme-corp
  • After: customer-support

This is a product for everyone - examples should be universal and applicable to any user.

2. Add Phase 4 Daemon Generator Implementation Plan

Added PHASE-4-DAEMON-GENERATOR.md with comprehensive task breakdown for implementing daemon generation (12-16 hours of work).

Why Daemons Matter: Critical path to LoRA infrastructure → cost-effective AI → alpha success.

Tasks:

  1. Study daemon patterns (2h)
  2. Create daemon templates (4h)
  3. Extend CommandGenerator (2h)
  4. Update audit system (2h)
  5. Dogfooding test with LoRA manager + training pipeline (2h)

See PHASE-4-DAEMON-GENERATOR.md for complete plan.


This PR just documents the plan. Implementation will follow in subsequent commits on this branch.

joelteply and others added 2 commits December 6, 2025 23:33
Changed customer support example from 'Acme Corp' (specific/biographical)
to generic 'your business' (universal).

Before: ./jtag recipe/load --activity="customer-support-acme-corp"
After: ./jtag recipe/load --activity="customer-support"

This is a product for everyone, not a biography. Examples should be universal and applicable to any user.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <[email protected]>
Copilot AI review requested due to automatic review settings December 7, 2025 05:33
@joelteply
joelteply merged commit e0168ed into main Dec 7, 2025
@joelteply
joelteply deleted the feature/phase-4-daemon-generator branch December 7, 2025 05:34

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR makes two targeted improvements to project documentation: depersonalizing README examples to make them universally applicable, and adding a comprehensive implementation plan for Phase 4's daemon generator feature.

  • Changed customer support recipe example from business-specific ("Acme Corp") to generic ("your business")
  • Added detailed Phase 4 daemon generator implementation plan with 12-16 hour task breakdown
  • Documented critical path to LoRA infrastructure for cost-effective AI

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 1 comment.

File Description
README.md Depersonalized customer support recipe example to use generic "your business" instead of "Acme Corp"
src/debug/jtag/docs/PHASE-4-DAEMON-GENERATOR.md Added comprehensive daemon generator implementation plan with 5 tasks, success criteria, and timeline estimates

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment on lines +164 to +167
After daemon generator is complete:
- ✅ Command generator (Phase 1 - shipped)
- ✅ Daemon generator (Phase 2 - this phase)
- 📋 Widget generator (Phase 3 - 17-20 hours)

Copilot AI Dec 7, 2025

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The phase numbering is inconsistent. The title says "Phase 4" but the "What's Next (Phase 5)" section lists:

  • "Command generator (Phase 1 - shipped)"
  • "Daemon generator (Phase 2 - this phase)"
  • "Widget generator (Phase 3 - 17-20 hours)"

According to this list, the daemon generator should be Phase 2, not Phase 4. Please align the phase numbering throughout the document.

Copilot uses AI. Check for mistakes.
joelteply added a commit that referenced this pull request Jun 9, 2026
… round-trip (task #225, Stage B PR 1/3) (#1570)

First migration in the Stage B push Joel asked for: "port commands
next, as we clean them up with our idealism." `sentinel/escalate` was
the smallest, most self-contained call site that Stage A made
visible — pure substrate plumbing (no external integrations), two
call sites in one module, zero TS-side callers, easy to validate.

## What this kills

- `src/commands/sentinel/escalate/` (whole command dir — receiver
  that only Rust ever called)
- `src/system/sentinel/SentinelEscalationService.ts` (handler service)
- The re-export in `src/system/sentinel/index.ts`
- The `SENTINEL_ESCALATE` constant in `generated-command-constants.ts`
- The two entries in `src/server/generated.ts` + `src/browser/generated.ts`

After this, no TS source references the escalate command. The
substrate has one fewer round-trip on every sentinel completion.

## What replaces it

`core/continuum-core/src/modules/sentinel/escalation.rs` — a
substrate-pure dispatcher with the same three-stage pipeline the TS
service had, but compressed:

1. **Persist** the `SentinelExecutionResult` into the `sentinels`
   entity via `data/list` + `data/update`.
2. **Escalate** an `InboxTaskRecord` into the `tasks` collection
   via `data/create`. The TS version branched on
   `getPersonaInbox(...)` for online vs offline personas; the Rust
   version unifies on `data/create` because `ChannelModule::tick`
   already polls the `tasks` collection and routes pending tasks
   into the live `PersonaInbox`. **One path, not two.**
3. **Store** the terminal event as a `SentinelMemoryRecord` in
   the persona's `memories` collection.

Each downstream collection has its own private struct
(`SentinelExecutionResult`, `InboxTaskRecord`, `SentinelMemoryRecord`)
with `#[serde(rename_all = "camelCase")]`, so the field set is
enforced at the type level. Per Joel's mid-flight reminder on the
escalate work ("use good structs, well formulated"): no
`serde_json::json!` blobs at the call site, no `Value` pass-through.
Everything that crosses a serialization boundary is a typed record.

## Typed escalation primitives

Promoted the `SentinelEscalation.escalation_rules` field from
`Option<Value>` (TS pass-through) to `Option<Vec<EscalationRule>>`
now that Rust owns the schema. The wire enums
(`EscalationCondition` / `EscalationAction` / `EscalationPriority`)
get ts-rs exports so the TS side still has a typed view. New
helper `EscalationPriority::inbox_priority()` mirrors the TS
`PRIORITY_MAP` literal — covered by a unit test so a future
rename can't silently drift.

## New typed event surface

`SentinelEscalationEvent` bundles the terminal-status fields the
two completion paths already had locally (`handle`, status,
duration, error, escalation metadata). The two call sites in
`SentinelModule` now build the event from in-process Rust values
and call `escalation::dispatch(&executor, event).await` instead of
`executor.execute_ts_json("sentinel/escalate", json!(...))`.

`SentinelTerminalStatus` encodes the Completed / Failed / Cancelled
trichotomy with named helpers for the slug-to-string mappings
(inbox `taskType`, matched `EscalationCondition`, memory
importance) — so the slug taxonomy lives in one place instead of
duplicated TS ternaries.

## Substrate-pure unification

The TS service had two branches in `escalateToPersonaInbox`:
- Online persona -> in-memory `inbox.enqueue(task)`
- Offline persona -> `DataCreate.execute({collection: 'tasks', data: task})`

The Rust dispatcher does only the second. Why: `ChannelModule::tick`
already polls the `tasks` collection on every tick and routes pending
tasks through the per-persona `PersonaInbox`. The channel tick IS
the online/offline rendezvous. Two TS code paths become one Rust
code path — the channel routing layer was already doing the
work, the TS service was duplicating it.

## Verified

  cargo check -p continuum-core --lib --features metal,accelerate                 -> clean
  cargo test  -p continuum-core --lib --features metal,accelerate modules::sentinel:: -> 138/138
  cargo test  -p continuum-core --lib --features metal,accelerate escalation::    -> 5/5

The 5 new escalation unit tests pin the TS-contract surface:
- inbox priority scalars match the TS `PRIORITY_MAP` literal
- failed + cancelled both route through the `Error` condition
- task-type slugs match the TS literal set (`sentinel-complete` /
  `sentinel-failed` / `sentinel-escalation`)
- default escalation rules include `Complete=Notify+Low`
- `InboxTaskRecord` serializes to camelCase so
  `ChannelModule::data_to_task_queue_item` keeps parsing it

## Doctrinal alignment

- `[[no-fallbacks-ever]]` — escalation is no longer a TS-bridge
  fallthrough; failure surfaces as a typed `String` from each
  stage and is logged via `tracing::warn!`.
- `[[rust-is-the-core-node-is-the-shell]]` — every collection
  the dispatcher touches (`sentinels`, `tasks`, `memories`) is
  Rust-owned. The TS bridge for this command is dead.
- `[[rethink-dont-port-commands-to-rust]]` — the online/offline
  branch in the TS version was redundant with the channel tick;
  the Rust port removes it.

## What's next (Stage B PRs 2 + 3)

- Task #226: delete the feature-gated legacy `livekit_agent.rs`
  `execute_ts_json("collaboration/live/transcription")` call —
  pure deletion, dead surface (bridge_client is the active LiveKit
  path).
- Task #227: migrate `genome/job-create` — channel tick's LoRA
  training trigger. Bigger than escalate; genome is substantial
  Rust-side already.

Co-authored-by: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request Jun 9, 2026
…xecutor (task #219) (#1585)

* fix(runtime): no-fallbacks — refuse silent TS fallthrough in CommandExecutor (task #219)

Per the substrate's [[no-fallbacks-ever]] doctrine: when no Rust
module owns a command, the executor previously routed silently to
the TS bridge at `/tmp/jtag-command-router.sock`. In headless mode
this surfaced as a confusing "Failed to connect to
CommandRouterServer" error; in hybrid-host mode it silently
delegated to TS, breaking the mental model that "the substrate is
Rust." Both failure modes were visible after task #224 deleted
GLOBAL_EXECUTOR and the rest of the TS-migration campaign
(#225/#226/#227 etc.) shrunk what the bridge served.

This commit kills the implicit fallthrough. After this change:

1. Interceptor chain runs first (airc, grid, future transports) —
   unchanged.
2. Rust module registry tries next — unchanged.
3. If no interceptor handled and no module matched: typed Err
   naming the missing command + the explicit escape hatch.

Callers that EXPLICITLY want the TS bridge use
`CommandExecutor::execute_ts` or `execute_ts_json` directly — those
public methods stay live for the documented TS-only call sites
(sentinel steps for web_research/command/llm/coding_agent, grid
connection's unmigrated-command fallthrough, ai_provider's cloud-
adapter fallthrough pending task #229). The substrate just no
longer SILENTLY routes there.

## Files touched

- `runtime/command_executor.rs`:
  - Doctrine docstring updated: "TypeScript via Unix socket" item
    becomes "No silent TS fallthrough" with the explicit-API escape
    hatch named.
  - `execute_inner` step 3: silent `execute_ts_command(...)` call
    replaced with typed Err that names the command and points at
    the explicit API.
  - Updated existing test `airc_interceptor_declines_when_no_airc_target_params`
    to assert the new error shape (registry miss, NOT the airc
    interceptor short-circuiting).
  - Added regression test `unknown_command_returns_typed_no_fallback_error_not_ts_attempt`
    that pins the contract: error must NOT mention TS socket, MUST
    name the missing command, MUST point at the explicit API.
  - Renamed `ts_bridge_failure_still_emits_completed_event` →
    `no_rust_module_failure_still_emits_completed_event` to reflect
    the new terminal-state name. Telemetry coverage of the failure
    path preserved.

- `routing/command_handler.rs`:
  - Updated comment on the gate-recorded-caller test to reference
    [[no-fallbacks-ever]] task #219 instead of the now-dead TS-bridge
    fallthrough.

## Architecture-proof linkage

This PR adds a **shape-1 (unit-level invariant)** proof for the
"No silent TS fallthrough" clause in
`docs/architecture/SUBSTRATE-DOCTRINE-ORGANIC-FLOW.md`. The
matrix in `docs/architecture/PROVING-THE-DOCTRINE.md` flips this
clause from 🟡 to ✅.

The test is tagged with the comment `// what this catches:` per
the established convention; the future `// proves: no-fallback`
tag convention (introduced in the proof discipline doc) will be
backfilled in a sweep PR alongside the first architecture-tests
addition.

## Test plan

- [x] `cargo check -p continuum-core --lib --features metal,accelerate` clean
- [x] `cargo test runtime::command_executor` — 86/86 pass
- [x] `cargo test routing::command_handler modules::grid` — pass
- [x] Full lib suite: 4324/4325 pass; 1 unrelated flake
  (`routing::uri_layer::tests::no_subscriber_returns_empty_chain`,
  the known global tracing subscriber pollution from task #203).
  Confirmed passes in isolation: `cargo test no_subscriber_returns_empty_chain`
  green standalone.
- [ ] Adversarial reviewer on canary

## Doctrine alignment

- `[[no-fallbacks-ever]]` — implicit fallthrough was the textbook
  violation; this commit closes it.
- `[[rust-is-the-core-node-is-the-shell]]` — substrate dispatch
  ends at the Rust registry. TS is an explicit-API destination, not
  a silent dependency.
- `[[headless-rust-must-work-soon]]` — headless boot no longer
  appears broken just because no TS host is around.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

* docs(runtime,chat): no-fallbacks review nits — top-of-file doc + chat stub comment + test PR ref

Adversarial reviewer's three non-blocking nits on PR #1585:

1. command_executor.rs module-level doc comment (lines 1-21) still
   described "TypeScript commands: Routed via Unix socket to
   CommandRouterServer" as if the implicit chain crossed the bridge.
   After the no-fallbacks fix that's misleading; operators read
   top-down and would believe the wrong contract. Updated to
   describe the implicit chain as Rust-only and call out the
   explicit execute_ts* public API as the documented escape hatch.

2. chat/mod.rs:494-497 comment said the staged-migration stubs reach
   the back-compat TS impl "through the existing CommandRouterServer
   bridge". Post-PR the chat module owns its prefixes and emits a
   deterministic typed error; the bridge is no longer in this
   dispatch path. Updated to reflect: chat owns the prefix, callers
   who need the TS surface go through the explicit execute_ts_json
   API per [[no-fallbacks-ever]].

3. The regression test comment at command_executor.rs:835 referenced
   "Pre-PR #1584" as the predecessor — that's the docs PR, not this
   one. Changed to "Pre-PR #1585" to match.

All three are documentation tightenings. No behavior change. Build
clean; targeted tests pass.

Co-Authored-By: Claude Opus 4.7 <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request Aug 2, 2026
… model-load storm (BigMama's 102-context spin) (#2106)

Glass-boxed live on the Windows node: 102 llama_context creations x
~1200 MiB with ZERO IPC deltas, eating memory out from under the
ResourceGovernor. Root cause: resolve_recall_embedder runs per persona
REGISTRATION (and registration re-runs on every respawn), and every call
built a FRESH LlamaCppAdapter — a full ~1.2 GB embed-GGUF load into a
new context, a probe, and ~16 calibration passes. The call-site comment
claimed "already cached by the resolver"; only content vectors were
cached, never the resolution. Nine personas = nine resident embed
contexts; respawn churn = the storm.

Fix: rung 1 (the in-process embed model) resolves through ONE
process-global cell. Success memoizes permanently and resolution is
single-flight (concurrent spawns share one load). Failure is never
memoized permanently — the #71 lesson: a late-arriving embed model must
still be adoptable — but re-attempts are rate-limited by a 60s cooldown,
capping the worst case at ~1 load/minute instead of one per respawn.

Regression test pins the invariant: three back-to-back failed resolves
cost at most ONE load attempt.

Also repairs two test call sites of PersonaInstanceManagerModule::new
that PR #2105 missed (its signature change compiled clean under `cargo
check` but broke `cargo test` builds — check does not compile test code).

Governor accounting follow-up stays #225 (register embed weights as a
ResourceConsumer); this fix removes the drift MULTIPLICATION.


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 8, 2026
…roze every citizen's turns permanently (#2187)

Sampled live (2026-08-08): both SWE solvers AND the room citizens went
silent; `sample` showed their tasks 100%-parked in
RecallFaculty → CachingEmbeddingProvider::embed → DashMap::remove →
lock_exclusive_slow. The eviction branch read

    if let Some(victim) = self.cache.map.iter().next().map(|e| *e.key()) {
        self.cache.map.remove(&victim);
    }

The `iter()` temporary holds the shard's READ lock for the whole `if let`
block (scrutinee temporary lifetime), so `remove` waits forever on the
same shard's WRITE lock — dashmap's documented never-do. Reachable only
when the cache sits at EMBEDDING_CACHE_MAX (20,000), which is why it
slept until production filled the cache today: from then on every novel
embed permanently parked its task, and recall embeds inside every turn.

Fix: bind the victim key in its own `let` so the iterator guard drops at
that statement's end, then remove. Regression test fills a PRIVATE cache
(existing with_cache seam — never the process-global map) to the cap and
embeds one novel text under a 5s timeout.

Also found on the same trail, filed separately (#225): the embedder's
1792MiB VRAM lease is refused with 604MiB governed-available after the
serving window grew — embedding is fully dead on this box even without
the deadlock; recall degrades to no-relevance.

cognition::embedding 17/17.


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 8, 2026
…budgets around it — the parts figure it out (#225) (#2188)

Joel's ruling (2026-08-08): "At worst it ought to turn to paging, or the
budgeter just has all its parts figure it out." Measured the same day: the
serving window grew to fill the board, leaving 604 MiB governed-available
against the embedder's 1792 MiB per-call need — 113 refusals in 25 min,
embedding fully dead, every recall degraded to no-relevance. The refusal
message said "tier down serving and retry" but nothing ever told serving.

The negotiation was already BUILT and never wired: the ledger has
per-consumer reservation floors, `available_for` (global available minus
every OTHER consumer's unmet floor), and enforcement in `acquire` — with
zero production callers. Three wires close the loop:

1. RESOLVE → FLOOR: when the neural embedder resolves (this node embeds),
   it reserves EMBED_LANE_VRAM_BYTES on the board (`embed.vram.reserved`
   probe). A node with no embed model wastes nothing. The two constants
   move to module-level pub in llamacpp_adapter — ONE source for the
   per-call lease and the floor.
2. SERVING BUDGETS FROM ITS OWN VIEW: `governed_vram_ceiling` now returns
   `available_for("serving", Vram)` — the same math `acquire` enforces —
   instead of the reservation-blind global number, so the plan can no
   longer size the window into a slice it would then be refused. The
   None-when-no-Vram-row semantics ("governor hasn't reported" ≠ "zero
   free") are untouched. `available_for` exposed on governor + daemon.
3. ONE bounded retry (2s) on a per-call lease refusal — with the floor in
   place a refusal means transient over-commit, and relief lands within a
   governor tick. Second refusal stays the honest loud failure. One retry,
   never a loop.

Regression test: serving_budget_plans_around_other_consumers_floors —
floor shrinks serving's plannable view by exactly the slice; serving's own
floor never counts against itself; board-row None semantics preserved.

cargo check green; new test + resources 137/137.


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 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
…— end the ratchet (#438/#214)

The serving planner budgeted its NEXT model against `available_for(serving, Vram)`, and
`available_for` subtracts `max(granted, physical_used)` — which INCLUDES serving's own
resident weights. So the incumbent was counted against its own replacement.

MEASURED, live board, 2026-08-19:

    vram capacity              55,125,917,696
    serving's own residency    30,253,811,702   ← subtracted from serving
    available_for(serving)     16,954,408,960   ← what the planner was handed
    + own residency          = 47,208,220,662   ← what it could actually have

A 27B fits in 47.2 GB. It does not fit in 16.9 GB. **The planner refused to keep the
model it was already running**, stepped down to a 7B, and the next decision started from
a lower ceiling still — ending at a 0.5B at 4,608 context on a 64 GB machine. #438 and
#214 are not two bugs; they are this one, seen from each end.

It also explains the lane thrash Joel called out. The budget MOVES as the incumbent
loads (0 → 28 GB resident), so the planner re-decides mid-load and respawns. A budget
that does not subtract your own bytes from your own plan is also a STABLE budget.

FIX: `budget_for_replacing(consumer, kind)` = `available_for` + that consumer's OWN
measured residency. The rule lives in the ledger — one place knows it — rather than
every caller remembering to add back. `available_for` is already consumer-aware about
RESERVATIONS (#225); it was consumer-BLIND about RESIDENCY, and that asymmetry was the
whole defect.

SCOPE, deliberately narrow:
  - adds back ONLY the caller's own residency, never a peer's, so it can never plan into
    someone else's bytes;
  - other consumers' reservation floors stay excluded, exactly as before;
  - `acquire` still uses `available_for` — a lease must never be granted against bytes
    not yet released. This is a PLANNING number, not a grantable one, and a test pins
    that distinction.

THE INVARIANT, which is Joel's acceptance test stated as code: *a machine already
serving model X can always re-plan model X.* Anything else can only decay, and no
learned layer on top can recover — it would be training against a signal wrong by the
size of the resident model.

Tests use the incident's real numbers. The first asserts the PRECONDITION (the old
number is genuinely too small for the model already running) before asserting the fix,
so it cannot pass vacuously if the arithmetic changes.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01LoTjvf5j3Ez13g6k8mRkFo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants