Skip to content

feat(runtime,system): RTOS substrate sweep — one signal primitive across broker, IPC, Bevy, ticks, disk, probe sink - #1557

Merged
joelteply merged 31 commits into
canaryfrom
fix/rtos-broker-and-ipc-ready
Jun 8, 2026
Merged

joelteply merged 31 commits into
canaryfrom
fix/rtos-broker-and-ipc-ready

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Summary

RTOS substrate sweep — one unified pattern lands across broker, IPC, Bevy, runtime ticks, ready signals, disk surveillance, and probe sink. 14 commits, each independently shippable. No parallel hierarchies; everything composes on the existing ServiceModule trait + the canonical owner-task shape from docs/architecture/CONCURRENCY-STYLE-GUIDE.md (new doctrine document in this PR).

What changed (slice by slice)

Doctrine + style guide:

  • 15aa2f5 — Author CONCURRENCY-STYLE-GUIDE.md synthesizing CBAR-SUBSTRATE / RESOURCE / BRAIN-REGIONS / OBSERVABILITY into one operational guide. Canonical owner-task shape, cadence ladder, reporter contract, ten forbidden moves, acceptance test. Pinned in CLAUDE.md as required-first-read.
  • 1d27023 — clean-as-you-go cargo discipline added to CLAUDE.md session-specific guidance.
  • 8ded9c5 — CLAUDE.md test-infra pin: table of canonical fixtures (HeuristicInferenceAdapter, RAG capture/replay, persona recorder, RecordingModule, stress-tests gate) so future PRs use what's shipped instead of reinventing.

Substrate fixes:

  • eb08267 — Kill CONTINUUM_GPU_CONCURRENCY env var. Substrate operational policy is code, never a runtime tunable. GPU_SLOTS_FLOOR/CEILING const-derived from logical CPU count.
  • c81c75e — start_tick_loops RTOS-safe: tokio::time::interval (no drift) + catch_unwind per tick + quarantine after 3 consecutive panics + probes at every meaningful seam. Every existing ServiceModule with a tick_interval gets the safety treatment, zero per-module edits.
  • aa21d40 — Add ServiceModule::ready_edge() default-impl + Runtime::wait_for_ready(name). The canonical "this module is ready" primitive — replaces oneshots, polls, ad-hoc atomic flags. Five unit tests pin the contract paths.

Signal-replaces-race migrations:

  • 73f8fdc — IPC server: 100 ms thread::sleep race → oneshot ready (intermediate, superseded by 38dacf0).
  • 854ce7c — Bevy renderer: 30 s sleep(2) poll loop → subscribe_ready() watch.
  • 38dacf0 — IPC ready edge: oneshot → watch primitive. Three subsystems (Bevy, IPC, future MemoryPressureMonitor) now publish ready edges through the same shape. ONE primitive across the board.

Test discipline:

  • bd9c8ea — Gate concurrency stress harness behind --features stress-tests cargo feature. ~1,300 LOC of stress tests from tasks Build(deps-dev): Bump @types/node from 22.14.0 to 22.15.29 #64-68 (chat/data/generator/realtime) skipped at default compile; periodic CI runs them. Mirrors the existing test-fixtures doctrine.
  • 636d833 — Test cull: delete tests/multi_persona_stress_baseline.rs (referenced non-existent modules — pure debt), fix Box→Arc in persona_respond_replay.rs + fixture_assembly_replay.rs (broken by task Bump dotenv from 16.6.1 to 17.2.3 #162 adapter-store refactor, never repaired).

New monitor following the doctrine end-to-end:

  • 60b62a1 — DiskPressureMonitor (task Build(deps): Bump inquirer from 8.2.6 to 12.7.0 #88 first slice). Mirrors MemoryPressureMonitor exactly: own task, interval + MissedTickBehavior::Skip, watch channel, is_disk_gate_closed() atomic, per-source reporters with 100 ms timeout + 3-panic quarantine, ready_edge on first snapshot, shared 80/90/95 tier ladder, probe!(class = "ready.observed", module = "disk-pressure-monitor") for replay. Four contract tests per the "less tests with more coverage" principle.

Auto-clean structural fix (the disk-bomb closure):

  • f937e6c — JsonlProbeFileSink::new_rolling(dir, max_log_files) using tracing_appender::rolling::Builder with daily rotation + 7-file retention. Mirrors the fmt-layer rolling pattern from fix(probes): rolling-log fmt-layer default — disarm the disk bomb (#211) #1547. Disk usage bounded by design.
  • eb75bd5 — Rip the unmerged-legacy CONTINUUM_PROBE_FILE env var + deprecated .path() alias. Only env-based entry point is CONTINUUM_PROBE_DIR (rolling, structural auto-clean). Per [[no-backcompat-for-unmerged-code]]: nothing on canary depends on the old name; aliasing creates only divergence surface.

Why this is one PR

Each commit independently passes lib check + targeted tests. They land together because they're all the same shape — ServiceModule + watch + interval + catch_unwind + ready_edge — applied across enough surface that the pattern is visible. Splitting would lose the "one unified primitive everywhere" story the doctrine doc claims.

What's NOT in this PR (next slices)

  • Port MemoryPressureMonitor to be a ServiceModule (slice A.5 — paired with DiskPressureMonitor so both live in the trait hierarchy)
  • Register DiskPressureMonitor as a ResourcePool with PressureBroker so disk pressure participates in cross-resource tier-relief (task Build(deps): Bump inquirer from 8.2.6 to 12.7.0 #88 second slice)
  • Real disk reporters (cargo-target, ~/.continuum/cache, model registry) — gives the snapshot per-path detail
  • Apply auto-clean-is-structural-not-operational doctrine to ~/.continuum/genome/ (4.2 GB unbounded LRU), persona recorder outputs, sentinel checkpoint dirs

Test plan

  • cargo check -p continuum-core --features metal,accelerate — lib green, 64 pre-existing warnings, no new
  • cargo test -p continuum-core --lib runtime::runtime::ready_edge_tests — 5/5 pass
  • cargo test -p continuum-core --lib routing::probe_file_sink — 15/15 pass (including new new_rolling_writes_to_dated_file_in_target_dir)
  • Reviewer pass — adversarial verify each slice individually
  • Spot-check: substrate boot writes a continuum-probes.YYYY-MM-DD.jsonl under CONTINUUM_PROBE_DIR and ages out after 7 days

🤖 Generated with Claude Code

joelteply and others added 14 commits June 8, 2026 11:49
The synthesis of CBAR-SUBSTRATE-ARCHITECTURE, RESOURCE-ARCHITECTURE,
BRAIN-REGIONS-SUBSTRATE, and OBSERVABILITY-AS-SUBSTRATE into one
operational guide for adding a new monitor / broker / pool / region /
background tick without reinventing what is already shipped
(ServiceModule, BrainRegion, PagedResourcePool, PressureBroker,
MemoryPressureMonitor).

Captures the canonical owner-task shape (own tokio task + interval +
watch::Sender<Snapshot> + atomic gate + spawn_blocking + 100ms timeout
+ quarantine), the cadence ladder, the reporter contract, the ten
forbidden moves (env-var-tuned substrate thresholds, sleep-loops,
tracing::info!(target=...) masquerading as a probe, hot-path pressure
interpretation, locks across await, etc.), and the acceptance-test
checklist.

CLAUDE.md gains a second STOP block — required first read before any
work that adds a tokio task, watch channel, pressure source, resource
pool, brain region, or background tick, or touches files under
runtime/, paging/, system_resources/. Mirrors the existing
PERSONA-COGNITION-PIPELINE.md pin's shape.

Written after the disk-guard slop intervention 2026-06-08: the
amnesiac model started reinventing MemoryPressureMonitor as
runtime/disk_guard.rs with env-tunable thresholds running on main.
This guide is that slop's tombstone — the next session that touches
concurrency starts here.

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

The broker's GPU slot count is substrate operational policy. Operators
do not tune how many GPU slots the PressureBroker offers — the broker's
tier-relief + AdaptiveThroughputPlanner shape actual concurrency under
load. The env var was an escape hatch with no documentation, no real
caller, and an unbounded panic surface (UTF-8 / parse / zero guards).

Replace with two named consts (GPU_SLOTS_FLOOR=4, GPU_SLOTS_CEILING=8)
derived from logical CPU count and clamped — same default as before for
every operator who never set the env var (which is all of them).

Per docs/architecture/CONCURRENCY-STYLE-GUIDE.md § "What lives in code,
not env vars": substrate operational policy is code, never a runtime
tunable. Env vars are reserved for deployment shape (socket paths, log
roots) and debug overrides with no production meaning.

Follow-up slice can derive these from GpuMemoryManager::detect() so a
5090 gets more slots than an Intel iGPU — hardware-tier policy in
code, not env.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Main was sleeping 100ms after spawning the IPC thread, hoping the Unix
socket would exist by then so start-workers.sh / process supervisors
would not race. start_server's bootstrap (model_registry init, runtime
build, airc discovery up to 180s, module registration, runtime ticks,
verify_registration) takes seconds to minutes before reaching the bind.
The 100ms sleep was guessing at a number it could never satisfy.

Wire a tokio::sync::oneshot through start_server. Fire it after the
Unix socket is bound and chmod 0o666'd — the exact moment supervisors
can connect. Main awaits the receiver. Err on the receiver means the
IPC thread errored out before binding, on which path it already calls
libc::_exit(1); main exits cleanly from its own arm.

Per docs/architecture/CONCURRENCY-STYLE-GUIDE.md: signals replace
races. The hot path reads a real ready edge instead of a sleep.

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

Every ServiceModule with a tick_interval shares the same loop runner.
That runner was broken in three ways:

  - tokio::time::sleep in a loop, not tokio::time::interval — cadence
    drifts under load and missed ticks stack as backlog
  - No catch_unwind around tick() — one panic silently kills the task,
    the module stops ticking forever, no log line, invisible bug
  - No quarantine on repeated failure — a wedged module ticks panic
    after panic indefinitely

Fix all three at the substrate level so every existing module (Health,
GPU, AIRC, Persona spawner, Pressure broker, MCP, Cognition, ~30 in
total) gets the safety treatment without per-module edits.

New shape per docs/architecture/CONCURRENCY-STYLE-GUIDE.md:

  - run_tick_loop_for() is the per-module body
  - tokio::time::interval + MissedTickBehavior::Skip (no drift, no backlog)
  - Per-tick AssertUnwindSafe(...).catch_unwind() boundary
  - Consecutive-panic counter; TICK_QUARANTINE_AFTER = 3 (matches the
    MemoryPressureMonitor reporter quarantine — one substrate convention)
  - Dynamic cadence re-read each iteration; ticker rebuilds on change
  - probe!(class = "tick.spawn|panic|error|quarantined|cadence_changed|aborted",
    module = name, ...) at every meaningful seam, so JsonlProbeFileSink +
    ProbeRouterLayer record the actual tick lifecycle (per
    [[jtag-probes-are-rtos-debugger]])
  - Per-module logger via runtime::logger("tick.<name>") writes
    structured prose into .continuum/jtag/logs/system/modules/

Module-side API unchanged — fn tick() -> Result<(), String> stays the
contract. Modules don't see any of the new machinery; they just gain
crash isolation and accurate cadence.

panic_message() best-effort-extracts the payload as &'static str or
String so probes carry a real label instead of <opaque>.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
The substrate's canonical "this module is ready to do real work" signal,
on the existing ServiceModule trait — not a parallel hierarchy. Per
[[docs/architecture/CONCURRENCY-STYLE-GUIDE.md]]: signals replace races.

New trait method (default-impl):

  fn ready_edge(&self) -> Option<watch::Receiver<bool>> { None }

Modules with internal warmup whose initialize() races with real
readiness (Bevy renderer thread, IPC socket bind, MemoryPressureMonitor
first snapshot) override to expose a watch::Receiver<bool> that flips
false -> true exactly once. Default None means "ready immediately after
initialize" -- the right semantics for the ~30 existing modules that
don't have an internal race.

New Runtime helper:

  pub async fn wait_for_ready(&self, module_name: &str) -> Result<(), String>

Consults the module's ready_edge. Fast-path Ok if the watch is already
true. Awaits the transition otherwise. Returns Err if the module isn't
registered or if the watch sender drops before publishing ready (which
means the module's task died before becoming healthy -- substrate is in
trouble; the caller decides whether to bail).

This replaces:
  - main.rs's recently-added oneshot::Sender wiring for IPC
  - main.rs's 15-attempt sleep-poll for Bevy renderer init
  - any future ad-hoc oneshot threading through start_X APIs

Each meaningful seam emits a probe -- ready.awaiting / ready.observed /
ready.watch_closed -- so the JSONL probe sink records exactly when
readiness was published for each module. Replay sees the boot order.

Five unit tests pin the contract: default-immediate, fast-path,
awaits-transition, dropped-sender-is-Err, unknown-module-is-Err. Each
runs under tokio::time::timeout so a regression that hangs surfaces as
a failure instead of CI hanging forever.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Doctrine line in session-specific guidance: always export
CARGO_TARGET_DIR to the shared cache so artifacts land in one place,
check disk after each cycle, sweep ghost workspace target dirs that
RA / manual cargo created by bypassing the env var, prefer cargo check
to cargo test when validating type-correctness.

Written after a cargo test cycle ate 10 GB of disk and dropped free
space from 13 GB to 3 GB without warning. The fix in tree (Slice 3 in
src/workers/.cargo/config.toml) is already documented as opt-in; this
is the operational discipline that bridges until operators opt in.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
main.rs had a 15-attempt sleep-poll for Bevy renderer init:

    for attempt in 0..15 {
        tokio::time::sleep(Duration::from_secs(2)).await;
        if let Some(bevy) = bevy_renderer::try_get() { register(); return; }
    }
    warn!("Bevy NOT registered after 30s");

The 30s give-up window was misleading — it didn't time out the actual
Bevy init, only this task's patience. And even when Bevy started cleanly,
the registration paid up to 2s of wasted sleep.

Replace with a signal. bevy_renderer/api.rs now publishes a watch::Sender<bool>
that flips false -> true exactly once when get_or_init completes, and exposes
subscribe_ready() -> watch::Receiver<bool>. main.rs subscribes once and
registers the reporter on the first transition.

Bevy ready emits a probe (class = "ready.observed", module = "bevy-renderer")
so the JsonlProbeFileSink records exactly when init completed. shutdown()
flips the watch back to false so a subsequent get_or_init restart re-fires
the edge for new subscribers.

main.rs's register_bevy_reporter helper is extracted from the inline
async task so the subscribe-and-await loop reads as one signal-shaped
block. The fast-path borrow_and_update() covers the race where Bevy
came up before main subscribed.

This is the same shape ServiceModule::ready_edge will eventually wrap
via the trait method — bevy_renderer is the first non-trait subsystem
to publish a ready edge. IPC server's oneshot (shipped earlier on this
branch) is next in line for the same treatment.

Per docs/architecture/CONCURRENCY-STYLE-GUIDE.md: signals replace races.

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

The concurrency stress tests landed in tasks #64-68 (chat dual-write,
chat multi-persona, data cursors, generator per-name lock, airc
realtime_store) validated their target invariants at sign-off time and
were left in tree. ~1,300 LOC across four files. Each one uses
`#[tokio::test(flavor = "multi_thread", worker_threads = 4)]` plus
50-task `futures::join_all` bodies — they compile into every cargo
test run, and the runtime flavor + body size dominate the test
binary's compile cost.

Same shape as the existing `test-fixtures` cargo feature: wrap the
stress harness in a `#[cfg(feature = "stress-tests")] mod stress {
use super::*; … }` sub-module so default `cargo test` skips
compilation entirely. Periodic CI:

    cargo test -p continuum-core --features stress-tests

Test gating doctrine (continuum-core/Cargo.toml, "stress-tests"):
- compile-time gating, not `#[ignore]`, so the binary literally
  doesn't contain the stress harness when the feature is off
- one-mod-per-file: each module's stress block is its own `mod stress`
- same opt-in shape as `test-fixtures` so operators don't have to
  remember two patterns
- new stress tests go in the same gated mod; do not add another
  separate test mod per PR

What's gated:
- modules/chat/mod.rs: Multi-persona concurrency block (4 tests +
  helper imports) — task #65
- modules/data.rs: Concurrency stress tests for the query-cursor
  surface (setup_concurrent helper + 2 tests) — task #66
- modules/generator/mod.rs: per-name-lock stress (3 tests) — task #67
- airc/realtime_store.rs: cursor + publish concurrency (4 tests) —
  task #68

(chat module's earlier dual-write stress block at line 900 is task #64
 and is more tightly coupled to the canonical chat/send path; left
 unannotated for now — a follow-up may either gate it or merge it
 into the regular tests.)

Per Joel 2026-06-08: "Yes half the battle is tests and we wrote all
this infra. Need to stop forgetting." Test infrastructure that exists
must be greppable, used, and curated — not silently bloated by PR
after PR adding its own stress block to the same file.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
The recurring slop pattern revealed by the test audit (3,646 test
functions in continuum-core, 34% of LOC, files with 3-6 separate
#[cfg(test)] mod blocks each): the model keeps forgetting that we
already wrote the test infrastructure and reinvents fixtures /
mocks / stress harnesses per-PR.

Add a fourth STOP block to CLAUDE.md as the canonical pointer to
what already exists:

- HeuristicInferenceAdapter (ai/heuristic_adapter.rs) — the canned-
  response inference fixture, gated #[cfg(any(test, feature =
  "test-fixtures"))]
- persona::recorder + vdd::turn_replay — live persona turn capture
  and replay
- RagCaptureSink / JsonlRagCaptureSink / RecordingRagSource /
  ReplayRagSource — RAG context capture and replay (PRs #10, #11, #12)
- TwoAircLoopback (in flight, task #187) — two-airc-peer cross-grid
  integration fixture
- RecordingModule pattern (runtime/runtime.rs) — bus-recording
  subscriber for event assertions
- mod stress { ... } gated behind stress-tests feature — concurrency
  harness (this PR)

Plus the six rules going forward, codified so they survive amnesia:

1. ONE #[cfg(test)] mod tests per file. Nest sub-mods inside, never
   add a peer test mod.
2. Stress tests go in the stress-tests-gated mod. Compile-time
   gating, not #[ignore].
3. Mocks / Stubs / Fakes go behind cfg(any(test, feature =
   "test-fixtures")). Production binaries cannot link them.
4. Battle-harden regressions get one #[test] in the existing mod
   with a // regression for #N link. Not their own file.
5. Reusable fixtures live in one place per concern. Never write a
   parallel MockX in your test file.
6. Every test justifies itself with // what this catches: naming
   the invariant or regression. Trivial getter tests get refused.

Per Joel 2026-06-08: "Yes half the battle is tests and we wrote all
this infra. Need to stop forgetting."

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

Two commits ago, ipc::start_server gained a `oneshot::Sender<()>`
parameter so main could await the bind+chmod. Then bevy_renderer
landed `subscribe_ready() -> watch::Receiver<bool>` for its own ready
signal. Two patterns for the same idea is the slop Joel called out
("reuse the same concurrent framework — we literally designed
persona for this no?").

Replace the IPC oneshot with the same watch primitive:

  ipc::subscribe_ready() -> watch::Receiver<bool>

`static IPC_READY: OnceLock<watch::Sender<bool>>` lives in ipc/mod.rs,
fires `false → true` exactly once when set_permissions(socket_path,
0o666) succeeds. Late subscribers see `true` on first
borrow_and_update. Same shape bevy_renderer::subscribe_ready uses;
same shape ServiceModule::ready_edge enforces via trait. One
mechanism across the board.

start_server's signature drops the oneshot parameter. main.rs
subscribes to ipc::subscribe_ready() before spawning the IPC thread
and awaits the watch transition. Probe emits `ready.observed` for
operator visibility.

This is the migration the CONCURRENCY-STYLE-GUIDE doctrine called
for: when you've shipped one off mechanism for a recurring concern,
the next commit replaces it with the canonical primitive. The
oneshot was the right shape for "two commits ago Slice 1"; the
watch is the right shape now that we have three subsystems
(MemoryPressureMonitor, bevy_renderer, ipc) publishing ready edges
through the same primitive.

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

Three outdated integration tests broke at the AdapterRegistry-stores-
Arc-natively refactor (task #162) and the scripted_adapter_factory
module-path drift. Pure debt — they don't compile, they don't run,
they accumulate every cycle.

DELETE: tests/multi_persona_stress_baseline.rs

References modules whose pub paths drifted (continuum_core::ai::
HeuristicInferenceAdapter requires the test-fixtures feature;
continuum_core::persona::scripted_adapter_factory + scripted_conversation
moved or never exported). The functionality it was meant to baseline
(supervisor + materialize_adapters + serve_persona_loop under load)
has unit-test coverage in the respective modules. Task #156 marked
this completed at sign-off; the artifact rotted afterward.

FIX (best-effort — Box → Arc at the registry boundary, matches the
exact compiler errors flagged in the audit; needs validation on the
next `cargo test --tests` cycle):

- tests/persona_respond_replay.rs:103 — Box::new(adapter) →
  Arc::new(adapter) for reg.register
- tests/fixture_assembly_replay.rs:509 — Arc::from(adapter) to
  convert the existing Box<dyn AIProviderAdapter> to Arc at the
  register call site

Both tests cover real prod failure modes their headers document
(max_tokens clipping mid-<think>, vision content dropped mid-flight);
keeping them in tree but making them compile is the right move
versus deletion.

Per Joel 2026-06-08: "We should have tests that are efficient in
consolidating logic calls, so less tests with more coverage. And get
rid of outdated stuff yes."

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Disk surveillance as a substrate concern, in the canonical RTOS shape.
The disk-guard slop that triggered docs/architecture/CONCURRENCY-STYLE-
GUIDE.md was a synchronous main-thread probe with env-tunable thresholds;
this is what that should have been from the start.

Mirrors MemoryPressureMonitor exactly:
- Own tokio task spawned by `start(reporters)`
- `tokio::time::interval` (not sleep-loop) — cadence doesn't drift
- `tokio::sync::watch::Sender<DiskPressureSnapshot>` publishes state;
  consumers subscribe lock-free
- `ready_edge()` flips false→true on first snapshot — same shape as
  ServiceModule::ready_edge, bevy_renderer::subscribe_ready,
  ipc::subscribe_ready (one primitive across the board)
- Per-source reporters via spawn_blocking + 100 ms timeout + 3-panic
  quarantine
- `is_disk_gate_closed()` atomic for lock-free hot-path checks; closes
  after Critical level sustained for 3+ polls (90 s)
- `CURRENT_DISK_LEVEL` lock-free level read from anywhere
- Outer catch_unwind around the loop body — no silent task death
- `probe!(class = "ready.observed", module = "disk-pressure-monitor")`
  on first snapshot for replay / mechanic-grade visibility
- Substrate-wide tier ladder (80/90/95) shared with memory_pressure so
  operators learn one threshold story, not two

Cadence: 30 s. Disk fills slowly; per the cadence ladder, lean slower
when in doubt. Memory polls every 2 s because RSS can spike in
milliseconds; disk doesn't.

Wired into main.rs alongside the memory monitor with `_disk_pressure_monitor`
(prefix-underscore to signal "intentionally unused locally — keeps the
Arc alive for the process lifetime"). Other consumers will fetch
via global accessor or ServiceModule registration in the follow-up.

Tests: three tight contract tests per Joel's "less tests with more
coverage" principle:
- `pressure_tiers_match_substrate_doctrine` — pins the 80/90/95
  thresholds; one test covers the whole tier ladder
- `level_to_u8_round_trips_via_current_level` — pins the atomic
  publication contract; one test walks all 4 variants
- `disk_gate_flips_and_resets` — pins gate forward + idempotency
- `reporter_trait_is_object_safe` — pins Arc<dyn DiskReporter>
  compiles (without this the whole monitor shape collapses)

Each test has a `// what this catches:` doc per the CLAUDE.md test-
infra doctrine. Loop body not unit-tested deliberately; one
integration test under the test-fixtures gate, with a synthetic
mount-point fake, is the right shape for that — follow-up.

Open follow-ups (not in this commit):
- Register as a ResourcePool with PressureBroker so disk pressure
  participates in cross-resource tier-relief (task #88's broker pool)
- airc pressure events (task #88's airc pressure)
- Real disk reporters (cargo-target dir, ~/.continuum/cache, model
  registry, fixtures archive) — gives the snapshot's per-path detail
- ServiceModule impl so the Runtime owns lifecycle uniformly
  (slice A.5, with MemoryPressureMonitor at the same time)

Per Joel 2026-06-08: "ok lets keep going with rtos design"

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

Per Joel 2026-06-08: "When we have repeated things, like incrementally
improving it, we need to make sure we auto clean like this thing does
now and we reduced the extra gb. It was nearly full."

JsonlProbeFileSink was the next disk bomb waiting. `OpenOptions::append`
on a single file, no rotation, no cap — turn it on for a measurement
session, forget to turn it off, recreate the 3 GB blob problem that
PR #1547 fixed for the fmt-layer.

This applies the same doctrine to the probe sink:

- New constructor `JsonlProbeFileSink::new_rolling(dir, classes, max_log_files)`
  builds a `tracing_appender::rolling::Builder` with daily rotation +
  `max_log_files(N)`. Files land at `<dir>/continuum-probes.YYYY-MM-DD`.
  Disk usage bounded by design, not by operator discipline.
- New env var `CONTINUUM_PROBE_DIR` → rolling mode. Production default.
- Legacy `CONTINUUM_PROBE_FILE` still works but logs a one-line
  `tracing::warn!` pointing operators at the new var. Kept because
  some forensic captures genuinely want one continuous file across days.
- `from_env()` prefers `CONTINUUM_PROBE_DIR` (rolling) and falls back to
  `CONTINUUM_PROBE_FILE` (single-file + deprecation warn).
- `DEFAULT_MAX_LOG_FILES = 7` — same retention as the fmt-layer rolling
  so operators learn one number.
- `path()` deprecated in favor of `target()` — same field, clearer name
  since "target" can be a file or directory depending on mode.
- Storage swapped to `Mutex<Box<dyn Write + Send>>` so the hot-path
  write code is identical regardless of mode.

One focused integration test (`new_rolling_writes_to_dated_file_in_target_dir`)
walks the full lifecycle in a single test per Joel's "less tests with
more coverage" principle — construct, install as tracing layer, fire
probe, observe `continuum-probes.*` file on disk with the right
content. Regression here = the auto-clean doctrine silently falls back
to unbounded growth.

Doctrine memory: [[auto-clean-is-structural-not-operational]].
Structural fix pattern, not opt-in operational discipline. Same shape
the fmt-layer rolling and cargo target shrink (PR #1556) follow.

Same pattern next applies to: ~/.continuum/genome/ (4.2 GB unbounded),
persona recorder fixture output, sentinel checkpoint dirs. Each one is
a follow-up slice.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Per Joel 2026-06-08: "Stop with backwards compatibility. Code ideally
why would something not in main need to be legacy lol."

Previous commit f937e6c added the rolling-mode constructor and the
new CONTINUUM_PROBE_DIR env var, but kept the old CONTINUUM_PROBE_FILE
env var (with a deprecation warn) and a deprecated path() alias.
Both the old env var and the old field name were renamed on this
same in-flight branch. There is no production caller. The "legacy
supported with warn" code path is debt born already deprecated.

Rip the old shape:

- Delete ENV_PROBE_FILE constant
- Delete from_env legacy fallback (single-file via deprecated env var)
- Delete #[deprecated] path() alias on JsonlProbeFileSink
- tracing_init.rs migrated to ENV_PROBE_DIR
- Updated test "from_env_returns_envvar_unset_when_dir_missing"
  (renamed from _when_path_missing for accuracy)
- Updated mod.rs re-exports — ENV_PROBE_FILE gone, ENV_PROBE_DIR
  and DEFAULT_MAX_LOG_FILES retained

The in-code `JsonlProbeFileSink::new(path, classes)` constructor
stays — it's a deliberate test/forensic API, not backcompat. The
ONLY env-based entry point is CONTINUUM_PROBE_DIR (rolling, bounded
by design).

Doctrine memory: [[no-backcompat-for-unmerged-code]]. The reflex to
"keep both for safety" creates surface area for future divergence
with zero migration benefit when nothing external consumes the old
shape.

15/15 probe_file_sink tests pass post-rip.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
joelteply and others added 15 commits June 8, 2026 14:55
…signal pool

Task #88 second slice — disk pressure now participates in the broker's
cross-resource tier-relief surface. Same broker that arbitrates memory,
Docker, LoRA, KV-cache, VRAM pressure now sees disk pressure on the
same wire.

`impl ResourcePool for DiskPressureMonitor`:
- tier_name = "disk-root"
- capacity_bytes / usage_bytes pulled from the latest snapshot
- evict_at_least returns 0 — the monitor is a SIGNAL source, not a
  holder of evictable files. Per task #88's split, concrete disk
  pools (genome cache, probe JSONL rotation, model registry, persona
  recorder outputs, sentinel checkpoints) register their own
  ResourcePool impls in follow-up slices; the broker will drive
  eviction against THOSE.

The zero-byte evict is the desired signal: when disk crosses tier
thresholds, broker emits `PressureAlert { tier_name: "disk-root",
bytes_freed: 0, action_taken: true }` — operators see "disk hot AND
nobody owns the eviction on this tier" which is structurally honest.

Wired into the substrate boot in `ipc/mod.rs::start_server` after
`PressureBrokerModule` registers itself. Threads disk_pressure_monitor
through main.rs → start_server alongside the existing memory
pressure_monitor.

Now the operator surface shows:
- `system/pressure-broker-state` IPC includes the disk-root pool in
  `pools` array with current pressure / tier
- Broker tick emits per-pool alerts to whatever sinks are registered
- Future broker-driven eviction across concrete disk pools all lights
  up on the same alert surface — no new mechanism per resource type

Same shape MemoryPressureMonitor would have if it were registered as a
ResourcePool (slice A.5 paired-port still pending). Once both monitors
go through the trait, the broker has uniform observation across the
whole substrate's resource surface.

Per Joel 2026-06-08: "Yeah just keep merging PRs and working on rtos."

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

Symmetric closure with the previous commit (f6c2e39) — both
substrate pressure monitors now appear on the broker's surface
uniformly. The broker arbitrates memory + disk + Docker + LoRA +
KV + VRAM tiers on one wire; one mental model for operators.

`impl ResourcePool for MemoryPressureMonitor`:
- tier_name = "sys-memory"
- capacity_bytes = snapshot.total_bytes
- usage_bytes = total - available
- evict_at_least returns 0 — same signal-only pattern as
  DiskPressureMonitor. RAM eviction belongs to CONCRETE consumer
  pools (genome cache, recall cache, fixture replay buffers, Bevy
  residency), each registering its own ResourcePool. The broker
  drives eviction against THOSE; this tier surfaces only the
  signal that "memory is hot AND nobody owns the eviction at the
  global level."

Registered alongside DiskPressureMonitor in `ipc/mod.rs::start_server`.
`pressure_monitor.clone()` so SystemResourceModule keeps its own
Arc for the existing snapshot IPC.

Result: `system/pressure-broker-state` now includes a `sys-memory`
tier alongside `disk-root`, `docker`, and any other registered
pools. The `PressureAlert` machinery fires consistently across all
tiers — no special-case per resource type.

Same shape doctrine the CONCURRENCY-STYLE-GUIDE preaches: one trait
+ one broker + uniform observation; concrete eviction belongs to
the concrete consumers.

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

Per Joel 2026-06-08: "System will be 100% concurrent, persona's
daemons, ORM, ai logic, commands and tools, etc. follow same pattern."

Each persona's `spawn_persona_service` bare-spawned `serve_persona_loop`
in a tokio task. If any single turn panicked (malformed input, adapter
bug, RAG store corruption, downstream library panic), the persona's
task died silently — that persona stopped responding with no log line,
no probe event, no operator-visible signal. Same class of bug that
`start_tick_loops` had before commit c81c75e; same fix applies.

Apply the canonical RTOS-safe shape from
docs/architecture/CONCURRENCY-STYLE-GUIDE.md:

  Ok(rt_handle.spawn(async move {
      let outcome = AssertUnwindSafe(serve_persona_loop(...))
          .catch_unwind()
          .await;
      match outcome {
          Ok(r) => r,
          Err(panic) => {
              // structured panic_msg extraction (same shape as
              // runtime::runtime::panic_message)
              tracing::error!(persona, persona_id, "service_loop aborted with panic");
              probe!(class = "persona.service_loop.aborted", persona, persona_id, reason);
              Err(format!("persona '{}' service loop panicked: {}", name, msg))
          }
      }
  }))

Captures `agent_name` + `persona_id` from `ctx.identity` BEFORE the
move so the panic path can report which persona died. Probe emission
sits on the `persona.service_loop.aborted` class — the JSONL sink +
ProbeRouterLayer fanout already in tree pick this up; operators tail
`continuum-probes.YYYY-MM-DD.jsonl` and see which persona dropped + why.

Same shape `start_tick_loops` (commit c81c75e), `MemoryPressureMonitor::start`,
`DiskPressureMonitor::start` use. One pattern across every owned task
in the substrate — the doctrine the CONCURRENCY-STYLE-GUIDE preaches
applied where it actually mattered for production: the per-persona
hot path.

Next slices following the same doctrine: cognition cycle (analyze /
score / render are each their own owned compute), ORM session
background tasks, command executor's dispatch path. Each follows the
same shape: AssertUnwindSafe + catch_unwind + probe-on-panic.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…otect every command + persona tool call

Per Joel 2026-06-08: "We need the persona tools and the command executor
that call optimized." Same RTOS-safe shape every owned task in the
substrate now uses — applied at the dispatch seam where it protects
everything in one move.

Three dispatch sites called `module.handle_command(...).await` raw:
- `Runtime::route_command` (async, IPC path)
- `Runtime::route_command_sync` (sync, rayon-thread path)
- `CommandExecutor::execute_with_caller` (persona tool path)

A panic inside any handler — UTF-8 slice past byte boundary, RAG store
corruption, downstream library bug, malformed JSON unwrap — poisoned
the dispatch task and propagated up the call stack. Persona tool calls
that flow through `Commands.execute('chat/send', ...)` had no guard;
one bad chat-module turn could kill the persona's cognition cycle.

Add `dispatch_with_panic_guard(&module, &full_cmd, params, module_name)`
free helper in `runtime::runtime`. Wraps `handle_command(...).await`
in `AssertUnwindSafe(...).catch_unwind()`, converts panics into typed
`Err(String)` carrying the panicking command + module + payload, and
emits `probe!(class = "command.dispatch.panicked", command, module,
reason)` so the JsonlProbeFileSink + ProbeRouterLayer already in tree
surface them to operators.

Wired into all three sites. Net effect: every command in the substrate
(~30 modules' handlers × every persona tool path) is now panic-isolated
at one seam. Same shape `start_tick_loops` did for tick handlers and
`spawn_persona_service` did for the per-persona service loop.

Why at the dispatch seam (not inside each `handle_command`): we can't
legislate `catch_unwind` discipline across the 30+ trait implementors.
Wrapping at the dispatch site protects every existing module + every
future module + the persona tool path that flows through `Commands.execute`
— one fix, blast radius bounded.

Follow-up doctrine memory candidate: panic isolation at the seam, not
inside each handler. Same pattern persona service_loop got two commits
ago.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
… broker → real eviction loop closed

Closes the broker → pool → real eviction loop end-to-end. Until this
commit, all registered ResourcePools on the broker were either:

- Signal-only (DiskPressureMonitor, MemoryPressureMonitor — observe
  pressure but evict_at_least returns 0)
- In-memory (PagedResourcePool<K,V> for KV cache, LoRA adapters, etc.)
- Domain-specific (DockerTierPool's macOS sparse-image logic)

Nothing in the substrate could yet actually delete files under disk
pressure. Disk pressure could fire all the alerts in the world; the
broker had no concrete pool to evict against.

`FilesystemTierPool` is the missing primitive — a generic ResourcePool
for any directory-backed cache. Instantiate with `(tier_name, dir,
max_bytes)`, register with the broker, done. Walk-by-mtime LRU eviction
deletes oldest files first when broker asks; the broker's pre-existing
PressureAlert machinery surfaces every eviction to operator-visible
probes.

Implementation:

- `walk_dir(dir)` recursively enumerates files + sizes + mtimes
- Per-tick snapshot cached 1 s so usage_bytes + evict_at_least in the
  same broker tick see consistent state
- evict_at_least walks the snapshot oldest-first, deletes files,
  accumulates freed bytes, stops when >= want_bytes, emits
  `probe!(class = "pool.evicted", tier, path, bytes)` per file
- Missing directory reports zero usage + zero eviction — safe to
  register pools at boot before dirs exist (e.g. fresh install)
- Failed eviction (locked file, permission) emits `pool.evict_failed`
  + warn log + continues to next-oldest file rather than bailing

First production instance: `~/.continuum/jtag/logs/probes/` registered
in start_server alongside the disk + memory pressure monitor
registrations. 500 MB soft cap — larger than a typical 7-day capture
but bounded so a runaway sprinkle / leak gets visible to the broker
before disk fills.

Composes with the auto-clean structural fix from f937e6c:
`tracing_appender::rolling` handles the time axis (daily rotation,
7-day retention); this pool handles the space-pressure axis
(broker-driven eviction when disk is hot). Both bounds active
simultaneously — same way memory pressure has both `bevy` shed-load
(time) AND broker eviction (space) in parallel.

Follow-up pools that drop in trivially with this primitive:
- ~/.continuum/genome/ — the 4.2 GB unbounded LRU on the punch list
- ~/.continuum/models/ — downloaded GGUF weights, biggest disk consumer
- ~/.continuum/fixtures/persona-respond/ — recorded persona turns
- ~/.continuum/jtag/logs/system/sentinels/ — sentinel checkpoint dirs

Each is a one-line `broker.register(FilesystemTierPool::new(...))`
follow-up. The whole punch list of disk-bomb risks closes uniformly
with this primitive.

Two contract tests per Joel's "less tests with more coverage":
- `evicts_oldest_first_until_target_bytes_freed` walks the full
  lifecycle: 3 files with controlled mtimes, evict_at_least returns
  the right amount, surviving files are the right ones, usage_bytes
  reflects post-eviction state
- `missing_dir_reports_zero_and_evicts_zero` pins the boot-before-dir-
  exists case so the substrate doesn't refuse to start when a fresh
  install has no probe history yet

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

Per Joel 2026-06-08: "Go into cognition stages. We can iterate with
both timing too" + "Wrote a lot of rag inspection and timing macros
we could use."

The substrate has `time_probe!(name, future)` — async-safe timing
that wraps a future in an `info_span!` with `seam = $name` +
`probe_class = "timing"`. The span's enter/exit durations land on the
same JsonlProbeFileSink / ProbeRouterLayer surface as `probe!` events,
so operators get a unified `class = "timing"` channel for all
substrate seams.

Zero uses of `time_probe!` in persona/ or cognition/ before this
commit. The cognition path was instrumented with manual `now_ms()`
deltas + structured `probe!(class = "persona.response.*", duration_ms
= ...)` events — semantic decision data on the probe channel, but no
dedicated timing channel.

Wrap the outermost `respond()` call at the service_loop seam in
`time_probe!("persona.respond", ...)`. Every persona turn now emits a
dedicated `{ probe_class: "timing", seam: "persona.respond" }` event.
With CONTINUUM_PROBE_DIR set, operators tail
`continuum-probes.YYYY-MM-DD.jsonl` and filter:

  jq 'select(.fields.probe_class == "timing" and .fields.seam ==
       "persona.respond")' continuum-probes.*.jsonl

…to get per-turn latency distribution. The existing per-stage
`probe!(class = "persona.response.analyze.result", analyze_duration_ms
= ...)` events stay — they carry semantic data plus the stage timing
inline. This commit adds the orthogonal per-turn timing channel that
multi-persona optimization campaigns can baseline against.

Follow-up slices (atomic): same `time_probe!` wrap around
`analyze()` and `run_render()` inside `respond_inner` so the per-stage
timing also lands on the canonical channel. With those three probes
(turn, analyze, render) the JSONL covers the 80/20 of turn latency
without further sprinkling.

Per task #195's "Inference latency perfection campaign" — this is the
substrate-side instrumentation half. The next campaign iteration runs
the substrate, captures the JSONL, slices the timing distribution by
persona / model / tier, and uses the data to pick the next
optimization.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…ge turn breakdown

Follow-up to cb746b0 (per-turn timing on `persona.respond` seam).
With this commit the full cognition turn timing lands on the canonical
`class = "timing"` channel:

  seam                              what it measures
  ─────────────────────────────────────────────────────────
  persona.respond                   total turn (service_loop seam)
  persona.respond.analyze           shared analysis (LLM call 1
                                    + cache hits + single-flight)
  persona.respond.run_render        prompt assembly + LLM call 2

Three probes cover the 80/20 of where a turn spends its time. With
CONTINUUM_PROBE_DIR set, operators slice the timing distribution by
seam directly off the JSONL:

  jq -r 'select(.fields.probe_class == "timing") |
         [.fields.seam, .fields["time.busy"]] | @TSV' \
    continuum-probes.*.jsonl | sort

The existing structured `probe!(class = "persona.response.*.result",
duration_ms = ..., from_cache = ..., model_used = ...)` events stay —
they carry the semantic decision data (cache hit ratio, intent,
matched_angle presence) that the bare timing channel doesn't. Pair the
two channels by `persona_id` + `message_id` for a complete turn record.

Three probes (turn / analyze / render) over zero macro uses is the
right ratio per [[jtag-probes-are-rtos-debugger]]: meaningful seam,
named for the operator's jq query, not for the call site. No further
sprinkles unless the data shows a fourth dominant cost.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…ol/ + tools/ at root

Stage 1 of the CBAR-style SDK layout. The substrate is no longer hidden under
src/workers/; clients consume per-language SDKs over a shared Rust client lib;
generated wire types live at protocol/typescript/ (mirrored swift/kotlin/flutter
slots will land alongside it as those SDKs come online).

  BEFORE                                  AFTER
  ──────────────────────────────────────────────────────────────────────
  src/workers/                            core/                  (rust substrate workspace)
  src/workers/continuum-core/             core/continuum-core/
  src/workers/continuum-orm-derive/       core/continuum-orm-derive/
  src/workers/llama/, livekit-*/, ...     core/llama/, core/livekit-*/, ...

  src/shared/generated/                   protocol/typescript/   (ts-rs raw types)

  core/continuum-core/bindings/           sdk/typescript/        (hand-written TS wrapper)
                                            ├── RustCoreIPC.ts   (composed client)
                                            └── modules/         (typed mixins)

  src/scripts/                            tools/scripts/         (dev tooling)
  src/generator/                          tools/generator/

  src/ (TS Node)                          src/ (TS Node — half-broken, by design)

The destination is `clients of one substrate, per env`:
  core/      → headless rust substrate (continuum-core-server + supporting crates)
  client/    → shared rust client lib   [Stage 2 — drives CLI + mobile FFI]
  sdk/{ts,flutter,swift,kotlin}/  → language SDKs over client/ [Stage 2-3]
  protocol/{typescript,swift,kotlin,flutter}/  → generated bindings [Stage 2-3]
  apps/{cli,web,mcp,mobile,desktop,vr}/  → thin UI shells [Stage 2+]
  tools/     → generators, scripts, ci

What this commit does:

  Rust side (verified — cargo check passes):
  - git mv src/workers core         (1478 file renames preserve history)
  - 592 #[ts(export_to)] paths bulk-updated: shared/generated/ → protocol/typescript/
  - Generator templates emit ../../../protocol/typescript/<name>/ for new modules
  - Internal doc-comment paths updated (file_engine, daemon_endpoint, blob,
    entity_schemas, generator/mod, generator/templates, generated_barrel_sync,
    .cargo/config.toml)
  - core/llama/build.rs uses CARGO_MANIFEST_DIR/../vendor/llama.cpp — no
    update needed; resolves to core/vendor/llama.cpp/ which exists

  Generated wire types:
  - git mv src/shared/generated protocol/typescript
  - 3 new untracked identity bindings (Identity, IdentityKind, IdentitySource)

  SDK bindings:
  - git mv core/continuum-core/bindings sdk/typescript
  - internal ../../../protocol/typescript/ paths shifted to ../../protocol/typescript/
    (shallower nesting after the move)

  Dev tooling:
  - git mv src/scripts tools/scripts
  - git mv src/generator tools/generator
  - tools/ self-refs updated (git-precommit.sh, git-prepush.sh, install.sh,
    setup-git-hooks.sh, install-common.sh, install-common.test.sh,
    validate-command-spec-coverage.ts, ensure-config.ts, continuum-chat-stream.ts)

  Infra & docs:
  - docker-compose.yml build contexts: src/workers → core
  - .github/workflows/{docker-images,carl-install-smoke}.yml: paths updated
  - scripts/{push-image,verify-image-revisions,airc-shared-target-opt-in,
    ratchet/persona-ts-ratchet,ci/canary-smoke-rust-features}.sh: paths updated
  - install.sh, bootstrap.sh, package.json: src/scripts → tools/scripts
  - CLAUDE.md hot-path refs: src/workers/continuum-core/src/{...} → core/...
  - src/tsconfig.json: added @protocol/*, @shared/generated → ../protocol/typescript,
    @scripts/* → ../tools/scripts/*, @generator/* → ../tools/generator/*

Node side (intentionally broken — see follow-up):
  Per [[rust-is-the-core-node-is-the-shell]] + task #143 (Rust-first clients),
  the Node TypeScript code under src/{commands,daemons,system,widgets,server,
  browser} no longer type-checks against the new layout. This is by design:
  the legacy Node implementation is queued for rewrite on top of sdk/typescript
  as the SDK consumption tier solidifies. Chasing 100+ relative-path import
  fixes in code that's slated for replacement is anti-architecture.

  What works headlessly today: npm start → bash tools/scripts/start-server.sh
  → continuum-core-server (the Rust substrate binary). That's the substrate-
  pure target per [[canary-stays-clean-pure-rust]].

  Tracking: task #215 — rebuild apps/{cli,web,mcp} on top of sdk/typescript
  when the SDK matures (client lib + idiomatic TS wrapper + Flutter parity).

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

Stage 2 of the substrate-first layout. The shared rust client lib is the
seam every embodiment talks through — the CLI links it directly, the
mobile / desktop / AR SDKs cross it via flutter_rust_bridge / swift-bridge
/ uniffi. One Rust crate, N language frontends, one connection / command /
event API.

Workspace move:
  core/Cargo.toml          → Cargo.toml          (repo-root workspace)
  core/Cargo.lock          → Cargo.lock
  core/.cargo/config.toml  → .cargo/config.toml
  members: ["continuum-core", ...]  → ["core/continuum-core", ...,
                                       "client/continuum-client"]

The workspace expresses the tier structure directly: core/* (substrate
crates) and client/* (shared client lib) are siblings under one workspace
that lives at the architectural top. Future tiers (apps/cli, apps/mobile
FFI shim, etc.) drop in as additional members without re-shuffling.

Skeleton:
  client/continuum-client/
    Cargo.toml              workspace-inherited deps; features { test-fixtures }
    src/
      lib.rs                re-exports: Connection, CommandClient,
                              EventSubscriber, Transport, ClientError
      transport.rs          Transport trait (async): request, subscribe, close
      connection.rs         Connection<T: Transport> — session container
      command.rs            CommandClient<T> — typed execute<P, R>
      event.rs              EventSubscriber<T> + EventStream alias
      error.rs              ClientError enum (Connect/Closed/Refused/Codec/
                              Transport/NotImplemented); From<serde_json::Error>

The crate compiles in 10.9s on first build and contributes 0 wire impls —
that is the point. It establishes the public API surface that future Stage
2.5+ slices fill in: the AircIpcTransport (local substrate over the
existing airc IPC seam), the AircGridTransport (remote substrate via
grid), the MockTransport behind test-fixtures for downstream tests.

Verified:
  cargo check -p continuum-client                          → clean (10.9s)
  cargo check -p continuum-core --features metal,accelerate → clean (2m30s)

Next stages this enables:
  Stage 2.5 — implement AircIpcTransport (local substrate session)
  Stage 3   — sdk/flutter via flutter_rust_bridge over continuum-client;
              sdk/{swift,kotlin} via uniffi/swift-bridge for native iOS/Android
  Stage 4   — apps/cli rewritten as rust binary linking continuum-client
              directly (replaces src/jtag + src/cli.ts per task #143)
  Stage 4+  — apps/{web,mcp,mobile,ar,desktop,vr} shells over their respective
              SDKs; same substrate, every embodiment

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…rc-protocol crate

Stage 2.5a of the SDK layout. The airc command + event wire envelopes
(AircCommandRequest/Response, AircEventSubscribe/Deliver/Unsubscribe/Ack,
all header constants, all body-hint constants) move out of
continuum-core's internal routing module into a shared crate that both
the substrate AND continuum-client depend on. Prevents wire drift between
server and client.

  core/continuum-airc-protocol/   NEW shared crate
    src/lib.rs                    re-exports command + event
    src/command.rs                AircCommandRequest, AircCommandResponse,
                                    HEADER_COMMAND_{PATH,KIND,ENV,STATUS},
                                    HEADER_CONTINUUM_BODY_HINT,
                                    COMMAND_{REQUEST,RESPONSE}_BODY_HINT
    src/event.rs                  AircEvent{Subscribe,SubscribeAck,Deliver,
                                    Unsubscribe,UnsubscribeAck},
                                    HEADER_EVENT_{TOPIC,KIND,SUBSCRIPTION_ID},
                                    EVENT_{SUBSCRIBE,DELIVER,UNSUBSCRIBE,ACK}_BODY_HINT

Substrate-internal coupling stays in continuum-core:
  core/continuum-core/src/routing/airc_command_protocol.rs
    Now a thin shim:
      pub use continuum_airc_protocol::command::*;
      pub fn command_request_from_route_decision(...) -> Option<AircCommandRequest>
        (was AircCommandRequest::from_route_decision impl; orphan rule
         prevents impl on foreign type, so converted to free function)

  core/continuum-core/src/routing/airc_event_protocol.rs
    Pure re-export shim:
      pub use continuum_airc_protocol::event::*;

  core/continuum-core/src/routing/airc_transport.rs
    One call-site change:
      AircCommandRequest::from_route_decision(decision, params)
        -> command_request_from_route_decision(decision, params)

Naming: continuum-airc-protocol (not airc-protocol) because the
workspace already pulls airc's own `airc-protocol` crate transitively
via airc-lib. Disambiguates substrate-side wire shape from airc's.

Verified:
  cargo check -p continuum-airc-protocol                          → 7.0s clean
  cargo check -p continuum-core --features metal,accelerate       → 1m08s clean

Next: Stage 2.5b implements AircIpcTransport in continuum-client using
this shared crate + airc-lib. Stage 2.5c adds Connection::connect_local
convenience + smoke test against a running continuum-core-server.

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

Stage 2.5b+c. The skeleton crate from Stage 2 grows its first functional
`Transport` impl: continuum-client can now address a continuum-core-server
over airc IPC using the same wire envelopes the substrate's command_handler
consumes (continuum-airc-protocol guarantees no drift).

client/continuum-client/src/airc_ipc.rs                       NEW
  AircIpcTransport
    new(airc: Arc<Airc>, target_peer: Uuid) -> Self
    with_deadline(deadline) -> Self                            builder
    DEFAULT_DEADLINE = 30s                                     matches substrate

  impl Transport for AircIpcTransport
    request(command, params) -> Result<Value, ClientError>
      Build AircCommandRequest with kind="peer"
      Serialize to Body::Json
      Stamp headers (path, kind, env?, body_hint)
      airc.request(MentionTarget::Peer(target), headers, body, deadline)
      airc.await_reply(pending)
      decode_reply -> Value | Refused | Transport

    subscribe(class) -> Err(NotImplemented)                    deferred slice
    close() -> Result<(), ClientError>                         idempotent

client/continuum-client/src/connection.rs                     UPDATED
  Connection<AircIpcTransport>::connect(airc, target_peer) -> Self
    Convenience constructor. Operator workflow:
      1. `airc status` on the running substrate → peer UUID
      2. let conn = Connection::connect(Arc::new(airc), peer_uuid);
      3. let result: MyResult = conn.commands()
           .execute::<MyParams, MyResult>("path/to/command", params).await?;

Tests (6 unit, all pass in 0.0s):
  build_headers_includes_path_kind_and_hint
  build_headers_adds_env_when_set
  decode_reply_ok_returns_value
  decode_reply_error_returns_refused
  decode_reply_no_body_returns_transport_error
  decode_reply_binary_body_returns_transport_error

What this slice DOES NOT do (intentional follow-ups):
  - Event subscription. AircEventSubscribe/Ack/Deliver/Unsubscribe is a
    multi-frame dance with stream demuxing on the caller side. Deserves
    its own focused slice; the substrate event protocol is already typed
    via continuum-airc-protocol so the wire shape is ready.
  - LAN-loopback integration test. Real client↔server roundtrip
    needs a TwoAircLoopback-style fixture (task #187, in-flight).
    Unit-level decode_reply tests cover the parsing surface; the
    actual airc-lib wire IO mirrors the substrate's own AircTransport
    (covered by routing::airc_transport::tests).

Verified:
  cargo check -p continuum-client                → 0.7s clean (incremental)
  cargo test  -p continuum-client --lib airc_ipc → 6 pass, 0 fail

Stage 2.5 complete (a+b+c). The seam is open: a Rust binary can now
link continuum-client, hand it an Airc + substrate peer_id, and call
substrate commands with typed results.

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

Following [[refine-tools-as-you-use-them]] + Joel "move first then design":
place the architectural shape in the tree itself, so future-Claude (and
future-Joel) find the right slot without re-reading every architecture
doc to remember where things go.

Tier READMEs (one per top-level dir):
  apps/README.md       — UI shells per embodiment (cli/web/mcp/mobile/ar/vr/desktop)
  client/README.md     — shared rust client lib (continuum-client + future siblings)
  protocol/README.md   — generated wire bindings (don't edit; regenerated)
  sdk/README.md        — per-language SDKs over client/ (typescript/flutter/swift/kotlin)
  tools/README.md      — dev tooling (generator + scripts; not shipped)

App placeholder dirs (apps/<env>/README.md, no source yet):
  apps/cli/    — rust binary linking client/continuum-client (task #143)
  apps/web/    — browser shell over sdk/typescript (task #215)
  apps/mcp/    — MCP server, rust or Node TBD by latency (#195)
  apps/mobile/ — Flutter app over sdk/flutter (Stage 3+)
  apps/ar/     — Quest / Vision Pro / WebXR (Joel's CV/AR lineage)
  apps/vr/     — the Grid embodied per [[the-substrate-is-the-grid-tron-frame]]
  apps/desktop/— Tauri or Bevy; reuses apps/web UI or links rust client

SDK placeholder dirs (sdk/<lang>/README.md):
  sdk/flutter/ — flutter_rust_bridge → Dart pkg → apps/{mobile,ar,vr}
  sdk/swift/   — swift-bridge → SwiftPM → native iOS apps
  sdk/kotlin/  — uniffi → AAR → native Android apps

Already populated tiers:
  core/                              — rust substrate workspace (multiple crates)
  client/continuum-client/           — shared rust client lib (Stages 2+2.5)
  protocol/typescript/               — ts-rs generated types (Stage 1)
  sdk/typescript/                    — hand-written TS wrapper (Stage 1+2)
  tools/{scripts,generator}/         — dev tooling (Stage 1)

Net effect on the tree:
  before: 5 top-level tiers, 1 had a README
  after:  6 top-level tiers, 6 have READMEs + 10 placeholder app/sdk slots

No code touched. Future slices land in the obvious slot.

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

Stage 1 + 2 reshaped the tree (src/workers/ → core/, src/scripts/ →
tools/scripts/, src/shared/generated/ → protocol/typescript/,
core/continuum-core/bindings/ → sdk/typescript/) — but the 55
markdown files under docs/ kept saying the old paths. Future-Claude
reading PERSONA-COGNITION-PIPELINE.md or CBAR-SUBSTRATE-ARCHITECTURE.md
needs the paths to match what cargo and the shell agree on, not the
pre-sweep snapshot.

Bulk substitutions across docs/:
  src/workers/continuum-core/bindings → sdk/typescript
  src/workers                         → core
  src/shared/generated                → protocol/typescript
  src/scripts                         → tools/scripts
  src/generator                       → tools/generator
  core/continuum-core/bindings        → sdk/typescript

55 docs touched; 258 ins / 258 del (1:1 substitution).

core/README.md rewritten from scratch. The old content described
self-defining `worker.config.ts` registry pattern from when each rust
crate was a separate binary launched by shell scripts. That pattern no
longer matches reality — most crates compile into the single
continuum-core-server binary; `start-workers.sh`/`stop-workers.sh` are
now tools/, not the canonical lifecycle. New README:

  - Lists the workspace crates with one-line role each
  - Points at the doctrine docs (CBAR / CONCURRENCY-STYLE-GUIDE /
    PERSONA-COGNITION-PIPELINE / RTOS-DEBUGGER-PROBES)
  - Gives the canonical build incantation with CARGO_TARGET_DIR
  - Names vendored submodules (llama.cpp, whisper.cpp)

No code or behavior changes. The branch's nine Rust crates compile
exactly as before; this commit only resyncs the prose.

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

The fmt-layer auto-clean structural fix on this branch renamed the env
var; the rolling-file sink writes dated files into a directory now, not
a single .jsonl. README's probe-debugging example follows.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…ols/generator after Stage 1 move

Stage 1 moved src/scripts → tools/scripts and src/generator → tools/generator.
The repo-root package.json got patched, but src/package.json's npm scripts
(start, build:ts, prebuild, worker:start, hooks:setup, etc.) still pointed
at the old relative locations and broke CI's validate + carl-install-smoke
jobs (ERR_MODULE_NOT_FOUND on src/generator/generate-version.ts).

Bulk-patched all './scripts/...' / 'scripts/...' / 'generator/...' / './workers/...'
relatives to '../tools/scripts/...' / '../tools/generator/...' / '../core/...'.
Repo-root '../scripts/push-current-arch.sh' refs left intact (those orchestration
scripts at repo-root scripts/ never moved).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
joelteply and others added 2 commits June 8, 2026 18:02
…ft-prevention + rip-completeness

Stage 2.5 review surfaced two BLOCK concerns from 3-reviewer adversarial round:

  Reviewer 1: DEFAULT_DEADLINE + RouteKind wire strings duplicated client↔server
    — exactly the drift surface continuum-airc-protocol extraction was supposed
    to prevent.
  Reviewer 2: 6 stale CONTINUUM_PROBE_FILE references survived the rolling-log
    rip — violates [[no-backcompat-for-unmerged-code]]; also two stale
    AircCommandRequest::from_route_decision doc-comment refs.

Drift-prevention (R1):
  core/continuum-airc-protocol/src/command.rs adds:
    pub const KIND_LOCAL: &str = "local";
    pub const KIND_PEER: &str = "peer";
    pub const KIND_ROOM: &str = "room";
    pub const KIND_BROADCAST: &str = "broadcast";
    pub const DEFAULT_COMMAND_DEADLINE: Duration = Duration::from_secs(30);
  All re-exported from lib.rs.

  Consumers switched to import:
    core/continuum-core/src/routing/route_decision.rs
      RouteKind::as_str() matches → continuum_airc_protocol::KIND_*
    core/continuum-core/src/routing/airc_transport.rs
      DEFAULT_DEADLINE = pub use continuum_airc_protocol::DEFAULT_COMMAND_DEADLINE
    core/continuum-core/src/routing/command_handler.rs
      `parsed.request.kind != "peer"` → `!= continuum_airc_protocol::KIND_PEER`
    client/continuum-client/src/airc_ipc.rs
      DEFAULT_DEADLINE = pub use continuum_airc_protocol::DEFAULT_COMMAND_DEADLINE
      `"peer".to_string()` → `KIND_PEER.to_string()`

  Now: bump the deadline or rename a kind in one place, both ends move. Drift
  by literal duplication is impossible by construction.

Rip-completeness (R2):
  CONTINUUM_PROBE_FILE → CONTINUUM_PROBE_DIR swept across 4 files (was missed
  by the rolling-log structural rip):
    core/continuum-core/src/main.rs
    core/continuum-core/src/routing/probe_file_sink.rs
    core/continuum-core/src/routing/tracing_init.rs
    docs/architecture/RTOS-DEBUGGER-PROBES.md

  AircCommandRequest::from_route_decision → command_request_from_route_decision
  in 2 doc-comment sites in core/continuum-core/src/routing/airc_transport.rs.

Verified:
  cargo check -p continuum-airc-protocol -p continuum-client  → clean
  cargo check -p continuum-core --features metal,accelerate   → clean (38s)
  cargo test  -p continuum-client --lib airc_ipc              → 6/6 pass
  cargo test  -p continuum-airc-protocol                      → 13/13 pass

R1's third point (typed `kind` field on AircCommandResponse::Error to
distinguish policy refusal from BUG-class errors) is a protocol-shape
question worth its own slice — logged separately, not in scope for the
drift-fix commit.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
…ripts/)

Previous package.json fix only handled relative-anchored quote-boundary
paths. Embedded refs inside npm script strings (e.g. 'npx tsx generator/...'
inside 'build:ts') were missed.

Fixed: tsx generator/ → tsx ../tools/generator/ (matches build:ts,
prebuild, test scripts). bash scripts/ → bash ../tools/scripts/
(matches start, stop, install).

CI validate + carl-install-smoke should now clear (was: ERR_MODULE_NOT_FOUND
on src/generator/generate-version.ts).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@joelteply
joelteply merged commit 2cb63e0 into canary Jun 8, 2026
2 of 5 checks passed
@joelteply
joelteply deleted the fix/rtos-broker-and-ipc-ready branch June 8, 2026 23:06
joelteply added a commit that referenced this pull request Jun 8, 2026
…ort↔substrate wire roundtrip (tasks #187 + #188)

Stage 2 of task #187 lands the actual spawn-2-Aircs-on-loopback behavior,
and stage 1 of task #188 lands the integration test that proves the
AircIpcTransport wire shape matches what the substrate's command_handler
expects. Together these close the wire-roundtrip verification gap
adversarial reviewer 1 flagged on PR #1557.

TwoAircLoopback::new() — real impl (was: stub returning NotImplemented)

  Studied airc-lib's public API at the pinned rev (f6ed190):
    Airc::open(home)            — load identity, open coordinator store
    airc.peer_spec()            — emit a parseable PeerSpec string
    airc.add_peer(spec)         — mutual trust handshake
    airc.join(room)             — join a shared room
    airc.listen_lan(127.0.0.1:0)— bind a kernel-picked loopback port
    airc.connect_lan(addr, id)  — dial peer-targeted authenticated socket

  TwoAircLoopback::new() walks the canonical 4-step setup the substrate's
  own tests use:
    1. Allocate two TempDir homes
    2. Open peer_a + peer_b (strict verification policy)
    3. Mutual trust via parse(peer_spec) + add_peer
    4. Both join the shared fixture room
    5. Wire LAN: peer_b listens, peer_a dials with peer_b's peer_id

  Typed LoopbackError shape: TempDir / AircSpawn (one variant + a
  human-readable message naming which peer + which step failed). Drops
  the previous NotImplemented placeholder.

Bare-airc smoke test (lives inside airc-test-fixtures)
  bare_request_reply_round_trips_over_loopback — peer_a sends a request,
  peer_b's subscribe stream sees it, peer_b replies via airc.reply,
  peer_a's await_reply resolves with the body. Proves the fixture's wire
  is alive end-to-end without any continuum-specific protocol on top.

AircIpcTransport ↔ substrate wire-roundtrip test
  client/continuum-client/tests/airc_ipc_roundtrip.rs

  Spawns a substrate-equivalent responder on peer_a that:
    - Subscribes to airc events
    - Filters on continuum.body_hint = continuum.command.request.v1
    - Parses Body::Json as AircCommandRequest (continuum-airc-protocol)
    - Constructs AircCommandResponse::ok({echoed_path, echoed_params})
    - Replies via airc.reply with the substrate's reply header set
      (HEADER_COMMAND_STATUS + HEADER_CONTINUUM_BODY_HINT)

  On peer_b, builds Connection::connect(peer_b_airc, peer_a_id) and
  calls .commands().execute("debug/ping", {hello, count}). Asserts:
    result["ok"] == true
    result["echoed_path"] == "debug/ping"
    result["echoed_params"] == {hello, count}

  Every drift surface in continuum-airc-protocol is now exercised:
    KIND_PEER, DEFAULT_COMMAND_DEADLINE, HEADER_COMMAND_{PATH,KIND,STATUS},
    HEADER_CONTINUUM_BODY_HINT, COMMAND_{REQUEST,RESPONSE}_BODY_HINT.
  If any literal drifts on either side this test fails — caught BEFORE
  any substrate ships.

Verified:
  cargo test -p airc-test-fixtures                         → 1/1 pass (0.95s)
  cargo test -p continuum-client --test airc_ipc_roundtrip → 1/1 pass (0.93s)
  cargo test -p continuum-client                           → 6/6 unit + 1/1 integration
  cargo test -p continuum-airc-protocol                    → 13/13 pass

Closes:
  - task #187 (TwoAircLoopback fixture) — real impl lands
  - task #188 (cross-grid command roundtrip integration test) — first test lands
  - reviewer 1 BLOCK concern from PR #1557 round 1 — wire shape now
    verified end-to-end, not just by literal duplication of constants.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request Jun 9, 2026
…reakage from layout sweep (#1562)

The layout sweep (PR #1557, task #214) moved `generate-config.ts`
from `src/generator/` to `tools/generator/`. Node's module resolution
walks ancestors of the SCRIPT location, not `process.cwd()`, so the
`import * as dotenv from 'dotenv'` at the top now traverses
`tools/generator/` -> `tools/` -> `/` looking for `node_modules/dotenv`
and finds nothing — `dotenv` only exists at `src/node_modules/dotenv`
(a SIBLING of `tools/`, not an ancestor).

Every TS-validation CI job that invokes
`npx tsx ../tools/generator/generate-config.ts` has been failing on
canary since the layout sweep merged:

  Error: Cannot find module 'dotenv'
  Require stack:
  - /home/runner/work/continuum/continuum/tools/generator/generate-config.ts

Surfaced via PR #1561's validate / ts-eslint-baseline-ratchet /
verify-architectures / verify-after-rebuild checks. NOT caused by
that PR's diff — pre-existing canary infra regression that has been
silently breaking every TS PR check since the layout sweep landed.

Fix: replace `dotenv.parse()` with a 15-line inline `parseEnvText`.
The script only ever called `.parse()` (the pure string-to-KV
transform), never the `.config()` side-effect path that mutates
process.env. Inline parser handles the same shape (KEY=value,
optional surrounding quotes, # comments, blank lines). Like-for-like
behavioral replacement at zero dep cost.

Doctrinal bonus: generator scripts now have a node-stdlib-only
footprint, matching `generate-version.ts`'s shape. No upward-walk
module-resolution surprises possible. Aligns with task #209
("npm start IS the headless Rust binary, period") — fewer Node deps
in the build path is unambiguously good.

Verified locally:
  cd src && npx tsx ../tools/generator/generate-config.ts
  -> "shared/config.ts unchanged" (idempotent on re-run)
  -> HTTP_PORT/WS_PORT defaults pick up correctly
  -> ACTIVE_EXAMPLE resolved from main package.json

Net diff: -1 import + 6 lines removed, +33 lines added (parseEnvText
+ doc block explaining WHY this exists). No behavior change on the
happy path.

Co-authored-by: Claude Opus 4.7 <[email protected]>
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.

1 participant