Skip to content

test(arch): engine-OS layering ratchet (task #240 — second proof) - #1589

Merged
joelteply merged 1 commit into
canaryfrom
feat/arch-test-engine-os-layering
Jun 9, 2026
Merged

joelteply merged 1 commit into
canaryfrom
feat/arch-test-engine-os-layering

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Summary

Second proof in the architecture-test matrix: a Shape 5 build-graph constraint that pins the engine-OS layering doctrine clause via a ratchet pattern.

What ships

tests/architecture_engine_os_layering.rs with 2 tests:

  1. runtime_submodule_paths_outside_runtime_ratchet — walks every .rs file outside runtime/, counts use crate::runtime::<submodule>::* imports, asserts count ≤ grandfathered budget of 29. New violations BLOCK; ratchet only goes down.
  2. runtime_internal_submodule_use_is_allowed — sanity-pins the intentional scope (runtime/* internals can compose freely).

Why ratchet, not strict

29 existing violations. Some need item-by-item public-API decisions (e.g. should BusEvent be promoted to runtime root or is the consumer the wrong shape?). Strict would block the PR until all 29 are resolved — that's a separate cleanup PR campaign. The ratchet enforces 'no growth' now and 'monotonically decreasing' over time. When the count reaches 0, the constraint graduates to strict.

This matches the proof-discipline doc: ship abstract recipe (test) AND literal first state (grandfathered count) together.

Matrix update

PROVING-THE-DOCTRINE.md row 'Engine-OS layering' flips 🔴 → 🟡 (ratchet active; → ✅ when count = 0).

What this catches going forward

  • New use crate::runtime::<submodule>::X from cognition/persona/modules → BLOCK
  • Refactor of runtime submodules that breaks consumers → BLOCK at test time, not at downstream compile failure
  • Forgetting to add a re-export when promoting an item → BLOCK

Test plan

  • cargo test --test architecture_engine_os_layering --features metal,accelerate — 2/2 pass
  • Tag convention: // proves: engine-OS layering
  • Ratchet logic correct in both directions (grow + shrink)

🤖 Generated with Claude Code

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

Second proof in the architecture-test matrix: a Shape 5 (build-graph
constraint) test that pins the engine-OS layering doctrine clause.

## What ships

`core/continuum-core/tests/architecture_engine_os_layering.rs` — two
integration tests:

1. `runtime_submodule_paths_outside_runtime_ratchet` — walks every
   .rs file outside `core/continuum-core/src/runtime/`, counts
   imports that reach into specific runtime submodule paths (e.g.
   `use crate::runtime::message_bus::MessageBus`), and asserts the
   count doesn't grow beyond the current grandfathered budget of 29.
   New violations BLOCK the test; existing ones are tracked for
   follow-up cleanup PRs.

2. `runtime_internal_submodule_use_is_allowed` — sanity-pins the
   intentional scope: `runtime/*` files CAN reach into their own
   sibling submodules (that's normal internal composition). The
   constraint applies only to consumers OUTSIDE `runtime/*`.

## Why ratchet (not strict)

29 existing violations exist across the substrate; their fixes
require considered decisions:
- Some items (e.g. `BusEvent`) aren't currently re-exported at the
  runtime root; promoting them is a public-API decision per item.
- Some callers genuinely reach for internals that should be
  refactored, not promoted.

The ratchet pattern: existing count is the budget, new ones BLOCK,
the number only goes DOWN. When a follow-up PR fixes violations, it
updates `GRANDFATHERED_VIOLATIONS` to the new lower count. When the
count reaches 0, the constraint graduates to strict enforcement.

This matches the proof-discipline doc's discipline: ship the
abstract recipe (the test) AND the literal first state (the
grandfathered count) together. Every subsequent PR ratchets down.

## Matrix update

`PROVING-THE-DOCTRINE.md` row for "Engine-OS layering" flips from
🔴 (no proof) to 🟡 (ratchet active, target is full ✅ when count = 0).

## What this catches going forward

- A new module that does `use crate::runtime::message_bus::BusEvent`
  instead of `use crate::runtime::BusEvent` (after BusEvent gets
  promoted to root) will fail the test.
- A refactor that splits `command_executor` into two submodules
  won't silently break consumers — the test reminds the substrate
  to update root re-exports.
- A cognition module that reaches into `runtime::late_bound::*`
  internals will be caught at PR review.

## Doctrine alignment

- Substrate doctrine § "Engine-on-OS framing" — runtime is the
  engine block; consumers compose against the public surface
- [[adapter-pattern-is-the-pivot-insurance]] — the public re-export
  layer IS the pivot insurance for engine internals

## Test plan

- [x] `cargo test -p continuum-core --test
      architecture_engine_os_layering --features metal,accelerate`
      — 2/2 pass
- [x] `// proves: engine-OS layering` tag convention applied
- [x] Ratchet logic verified (both grow-detection and
      shrink-detection paths)

## Related

- Task #240 (this PR adds the second proof to the matrix)
- Builds on #1588 (first proof — no-fallbacks integration test)
- Follow-up: dedicated cleanup PRs ratchet the 29 → 0 over time

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@joelteply
joelteply merged commit 89c31ff into canary Jun 9, 2026
2 checks passed
@joelteply
joelteply deleted the feat/arch-test-engine-os-layering branch June 9, 2026 23:54
joelteply added a commit that referenced this pull request Jun 10, 2026
…ry) (#1590)

* test(arch): close two nits from #1589 review (pub-use prefix + symmetry)

Two adversarial-review nits from PR #1589's APPROVE-WITH-NITS verdict,
shipped as their own tiny ratchet PR per the test-fixtures doctrine.

## Nit 1 — `pub use` prefix bypass

The previous scanner matched `use crate::runtime::<sub>::*` but missed
`pub use crate::runtime::<sub>::*` (re-export from an intermediate
module). That shape leaks the same engine-internal path through the
consumer's public surface — same hazard, different prefix.

Fix: strip a leading `pub ` after the existing `trim_start()` so the
ratchet catches both shapes.

## Nit 3 — symmetric closure: every submodule is tracked

Reviewer flagged the silent-gap class: a future PR could add
`pub mod new_thing;` to `runtime/mod.rs` without extending
`FORBIDDEN_RUNTIME_SUBMODULES`, opening a path the ratchet wouldn't
catch.

Fix: a third test (`every_runtime_submodule_is_tracked`) parses every
`pub mod X;` line out of `runtime/mod.rs` and asserts each name appears
in the forbidden list. New submodule → test fails until the list is
extended (and the ratchet count rebaselined if any callers already
reached in).

## Why these were nits, not blocks

Both are defense-in-depth on a ratchet that was already correct for
today's tree (no `pub use` reaches exist; submodule list matches
declarations). The grandfathered count stays at 29 — these patches
don't fix existing violations, they close future-PR-shaped holes.

## Nit 2 (deferred — separate cleanup PR)

Inline `crate::runtime::<sub>::Item` references (not at the top of
a `use` block) aren't matched by the current line-prefix scan. That's
a ~10-violation cleanup that wants its own ratchet field (`inline`
vs `import`) — not in scope here. Tracked as follow-up under #240.

## Test plan

- [x] `cargo test -p continuum-core --test
      architecture_engine_os_layering --features metal,accelerate`
      — 3/3 pass (was 2/2; +`every_runtime_submodule_is_tracked`)
- [x] Manual sanity: `grep -n "^pub mod" runtime/mod.rs` produces
      exactly the 22 names in FORBIDDEN_RUNTIME_SUBMODULES (the 23rd,
      `"runtime"`, covers the inner lifecycle module per the existing
      sanity test's skip)

## Doctrine alignment

- [[no-fallbacks-ever]] — the ratchet IS the engine-OS layering's
  no-fallback equivalent at the build-graph layer
- [[abstract-into-literal-design-principle]] — shipping the recipe
  (test) AND the literal first state (29 grandfathered) together;
  every PR ratchets down

## Related

- Closes nit 1 + nit 3 from PR #1589's adversarial review
- Task #240 (architecture-test matrix — second proof rolling forward)
- Nit 2 (inline references) deferred to a follow-up ratchet PR

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

* test(arch): harden two scanners per reviewer nits (close visibility + inline-body holes)

Reviewer on PR #1590 returned APPROVE-WITH-NITS with two trivial
surface-hardening notes. Folding them in here keeps the ratchet PR
self-complete instead of trailing a no-op-today follow-up.

## Hardening 1 — visibility-modifier coverage

`trim_start_matches("pub ")` requires a literal space, so neither
`pub(crate) use crate::runtime::<sub>::*` nor `pub(super) use ...`
were caught. Both shapes leak the same engine-internal path through
the consumer's re-export surface (the public-vs-pub(crate) distinction
is about *who* sees the leak, not whether it exists).

Fix: chain three `trim_start_matches` calls — longer forms first so
they don't fall through to the shorter `pub ` matcher leaving a
leftover `(crate) ` / `(super) ` prefix.

```rust
let trimmed = trimmed
    .trim_start_matches("pub(crate) ")
    .trim_start_matches("pub(super) ")
    .trim_start_matches("pub ");
```

Zero hits in the tree today — this is pure forward-defense.

## Hardening 2 — `pub mod X { ... }` inline-body shape

The symmetry parser used `rest.split(';').next()` to extract the
module name. For the (rare) inline `pub mod X { ... }` shape, that
yields `X { ... }` instead of `X`, which would then fail the
`FORBIDDEN_RUNTIME_SUBMODULES.contains()` check spuriously OR (worse)
silently grandfather a name that doesn't match anything real.

Fix: `rest.split_whitespace().next()` + `trim_end_matches(';')`.
Handles all three shapes uniformly:

| Input                          | Extracted name |
|--------------------------------|----------------|
| `pub mod X;`                   | `X`            |
| `pub mod X; // comment`        | `X`            |
| `pub mod X { ... }`            | `X`            |

`runtime/mod.rs` is 100% file-declarations today, so no behavior
change — same forward-defense pattern.

## Deferred to a separate follow-up — nit 3

Reviewer's third nit: if a `pub mod X;` is later demoted to
`pub(crate) mod X;` while still in `FORBIDDEN_RUNTIME_SUBMODULES`,
the ratchet would silently stop watching that name. Closing this
needs a small design choice (warn-vs-fail? auto-remove from list?)
that doesn't belong on this PR — tracked under #240.

## Test plan

- [x] `cargo test -p continuum-core --test
      architecture_engine_os_layering --features metal,accelerate`
      — 3/3 pass
- [x] Manually verified: zero `pub(crate) use crate::runtime::*` or
      `pub mod X { ... }` patterns in tree today, so no behavior
      change from these hardenings
- [x] Ratchet count stays at 29 — these tighten the matcher; they
      don't fix existing violations

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 Jun 10, 2026
…t (task #240) (#1591)

* test(arch): ban static `OnceLock<Arc<T>>` singletons via shape-5 ratchet (task #240 — third proof shape)

Third proof in the architecture-test matrix. Pins the
"localized state per citizen" doctrine clause — the substrate is
multi-citizen by design; module-scope `static OnceLock<Arc<T>>` is
the doctrine violation because it pretends substrate state is
process-global when in practice each peer / persona / citizen needs
its own runtime.

## What ships

`core/continuum-core/tests/architecture_no_singleton_state.rs` —
two integration tests:

1. `static_singleton_state_ratchet` — scans every `.rs` file under
   `core/continuum-core/src/`, finds lines matching
   `static NAME: <forbidden-type-shape>`, asserts the count doesn't
   grow beyond the current grandfathered budget of **12**. NEW
   singletons BLOCK; existing ones are tracked for follow-up
   migrations to `LateBound<T>` per PR #1583's pattern.

   Forbidden type shapes: `OnceLock<Arc<T>>`, `OnceCell<Arc<T>>`,
   `std::sync::OnceLock<Arc<T>>`, `once_cell::sync::OnceCell<Arc<T>>`.
   `OnceLock<T>` without `Arc` is a value primitive (allowed);
   per-instance struct fields are install-once DI (allowed —
   migrate to `LateBound<T>` for ergonomics over time).

   Test mods (`#[cfg(test)] mod tests { ... }`) are exempted via a
   simple brace-depth counter so fixture statics in tests don't
   trip the ratchet. Today's count is zero in test mods, but the
   exemption keeps the rule future-proof.

2. `late_bound_remains_the_canonical_primitive` — positive pin:
   `runtime/late_bound.rs` exists, declares `pub struct LateBound`,
   and wraps `OnceLock<Arc<...>>` internally. If the canonical
   primitive ever moves or its underlying type changes, the test
   is loud, not silent.

## The 12 grandfathered violations

All in `live/*` or `modules/*` — they predate `LateBound<T>` and
need per-module migration:

- `live/video/capture.rs::instance()` — VideoFrameCapture singleton
- `live/video/bevy_renderer/api.rs::RENDERER_GPU_MANAGER`
- `live/audio/tts/mod.rs::{TTS_GPU_MANAGER, TTS_REGISTRY}`
- `live/audio/vad/silero.rs::SILERO_SESSION` (+ raw variant in
  `silero_raw.rs`)
- `live/audio/stt/mod.rs::STT_REGISTRY`
- `live/avatar/registry.rs::AVATAR_REGISTRY`
- `modules/embedding.rs::{MODEL_CACHE, EMBEDDING_GPU_MANAGER, EMBEDDING_POOL}`
- `modules/sentinel/mod.rs::GLOBAL_SENTINEL` (read by signal
  handlers — needs different shutdown plumbing; trickiest one)

## Why ratchet (not strict)

Same reason as the engine-OS layering ratchet (PR #1589): the
existing violations require considered per-module migration
decisions, not a blanket sed sweep. The ratchet pattern: NEW ones
BLOCK, the count only goes DOWN, each cleanup PR rebaselines.
When 0 is reached, the clause graduates to strict enforcement.

This matches the proof-discipline doc's discipline: ship the
abstract recipe (the test) AND the literal first state (the
grandfathered count) together. Every subsequent PR ratchets down.

## Matrix update

`PROVING-THE-DOCTRINE.md` row for "Localized state per citizen"
flips from 🟡 (TODO placeholder) to 🟡 (ratchet active, target is
full ✅ when count = 0).

## What this catches going forward

- A new module that does `static GLOBAL_X: OnceLock<Arc<X>> = ...`
  instead of installing X on a per-instance `LateBound<X>` field
  will fail the test.
- A regression that reintroduces a `static GLOBAL_EXECUTOR` shape
  (the exact pattern PR #1583 closed for `CommandExecutor`) will
  fail the test BEFORE it reaches review.
- Forgotten `once_cell::sync::OnceCell<Arc<T>>` patterns (older
  spelling) are caught by the same scanner — qualified-path
  variants are in the forbidden list.

## Doctrine alignment

- Substrate doctrine § "Localized state per citizen" — each peer's
  runtime is its own state; no process-global Arc'd cells
- [[late-bound-primitive]] — the canonical install-once primitive
  for per-instance install-once DI

## Test plan

- [x] `cargo test -p continuum-core --test
      architecture_no_singleton_state --features metal,accelerate`
      — 2/2 pass; grandfathered count = 12 (exact match)
- [x] All 3 architecture-test integration files pass together:
      no-fallbacks (3) + engine-OS layering (3) + singleton ban (2)
      = 8/8
- [x] `// proves: localized state per citizen` tag convention
      applied
- [x] Ratchet logic verified (both grow-detection and
      shrink-detection paths via inspection of the panic branches)

## Related

- Task #240 (this PR adds the third proof to the matrix)
- Builds on PR #1583 (LateBound<T> primitive — the migration target)
- Builds on PR #1589 (ratchet pattern established)
- Follow-up: dedicated per-module cleanup PRs migrate the 12
  singletons to `LateBound<T>` or `ModuleContext`-threaded deps

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

* test(arch): harden singleton scanner per #1591 review nits (pub-prefix + inline cfg-test + tokio OnceCell)

Reviewer on PR #1591 returned APPROVE-WITH-NITS with three trivial
forward-defense holes. Folding them in keeps the ratchet PR
self-complete instead of trailing a no-op-today follow-up.

## Hardening 1 — `pub static` / `pub(crate) static` / `pub(super) static`

The previous scanner required `trimmed.starts_with("static ")` — it
would silently skip `pub static FOO: OnceLock<Arc<X>>`. Verified zero
such patterns exist in tree today (the few `pub static`s all wrap
non-Arc types and would have been excluded by the type-pattern check
anyway), but a future contributor adding a visibility prefix to a
singleton declaration shouldn't slip past the ratchet.

Fix: strip the visibility modifier before the `starts_with("static ")`
check, same chained `trim_start_matches` order as the engine-OS
layering scanner.

## Hardening 2 — inline `#[cfg(test)] mod tests { ... }`

The previous test-mod-exemption parser handled the two-line form
(attribute on one line, `mod NAME {` on the next) but missed the
single-line collapsed form. Verified zero occurrences in `src/`
today (the inline shape appears only in docstrings inside
`generator/templates.rs`), but the parser should match the patterns
the compiler accepts.

Fix: detect the inline shape on the same line as `#[cfg(test)]` and
open the brace-depth scope immediately; also handle the
single-line balanced case (`#[cfg(test)] mod x {}`) by checking
test_mod_depth after the line's `{`/`}` count.

## Hardening 3 — `tokio::sync::OnceCell<Arc<T>>`

The previous forbidden-type list covered `std::sync::OnceLock`,
`OnceCell` (from `once_cell::sync`), but not the qualified
`tokio::sync::OnceCell` spelling. Currently used as a struct field
in `runtime/shared_compute.rs` (legitimate per-instance install-once)
but not as a static — adding the pattern closes the qualified-path
hole proactively.

## What this doesn't fix (deferred to follow-up)

- Reviewer nit 4 (raw brace counter could miscount on `{`/`}` inside
  string literals or block comments within a test mod). Realistic
  exposure near-zero — tests don't usually embed `{` in raw strings
  around statics. A real fix needs a tiny tokenizer; not worth the
  complexity until it bites. Tracked under #240.
- Reviewer nit 5 (tighten `late_bound_remains_the_canonical_primitive`
  to assert presence of `name:` / `slot:` fields). Optional polish;
  current assertions on the type and the underlying `OnceLock<Arc<`
  are sufficient for catching rename/deletion.

## Test plan

- [x] `cargo test -p continuum-core --test
      architecture_no_singleton_state --features metal,accelerate`
      — 2/2 pass (ratchet count still 12, unchanged behavior on
      today's tree)
- [x] Manually verified: no `pub static.*: OnceLock<Arc<` or
      inline `#[cfg(test)] mod tests {` patterns in tree today, so
      "no behavior change from these hardenings" claim is honest

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 Jun 10, 2026
…ratchet (task #240 — fourth proof shape) (#1592)

Fourth proof in the architecture-test matrix. Pins the "module
compose-by-event" doctrine clause — substrate-internal modules
compose via the event substrate (MessageBus subscribe/emit) or via
pre-bound handles, not by imperative `CommandExecutor::execute_*`
round-trips through the outer command interface inside the
cognition hot path.

## What ships

`core/continuum-core/tests/architecture_compose_by_event.rs` — two
integration tests:

1. `cognition_command_executor_calls_ratchet` — scans every `.rs`
   file under `core/continuum-core/src/cognition/`, finds lines
   matching `.execute_json(`, `.execute_with_caller(`,
   `.execute_ts(`, `.execute_ts_json(`, asserts the count doesn't
   grow beyond the current grandfathered budget of **1**. NEW
   calls BLOCK; the existing one is tracked under #112-#114
   (route persona response / should_respond / validate through
   inference handle).

   Bare `.execute(` is intentionally NOT in the forbidden list —
   it would generate false positives across futures, queues, and
   other APIs. If a typed `executor.execute(typed_args)` pattern
   appears inside cognition in a future refactor, extend the list.

   Test mods (`#[cfg(test)] mod ... { ... }`) are exempted via
   the same brace-depth parser as the singleton-ban test, with
   inline `#[cfg(test)] mod tests {` handling.

   Line comments (`//` lines) are skipped so doc comments quoting
   the very pattern being banned don't trip the scanner — this
   matters for cognition module top-of-file docs that reference
   `Commands.execute('cognition/...')` as the TS-side caller
   contract.

2. `command_executor_remains_the_outer_boundary` — positive pin:
   `runtime/command_executor.rs` exists, declares
   `pub struct CommandExecutor`, exposes `pub async fn execute_json`.
   If the type is renamed or `execute_json` moves, the test is
   loud, not silent — and the FORBIDDEN list in this test file
   needs updating to match.

## The 1 grandfathered violation

`cognition/vision_describe.rs::describe_image_via_ai_generate` calls
`executor.execute_json("ai/generate", ...)`. The clean fix is a
pre-bound `InferenceHandle` (cf. tasks #107-#108), called directly
the same way `airc_chat_demo` already does. Migration tracked under
#112-#114 (the inference-command-routing campaign) and #106
(ai/* namespace consolidation).

## Why ratchet (not strict)

Same reason as engine-OS layering and singleton-ban: the single
existing violation needs a considered migration (which `InferenceHandle`
to pre-bind, where to wire the lifecycle), not a sed sweep. NEW
violations BLOCK at PR time; the ratchet count graduates to ✅ when
#112-#114 land.

## Matrix update

`PROVING-THE-DOCTRINE.md` row for "Module compose-by-event" flips
from 🔴 (no proof) to 🟡 (ratchet active, target ✅ when count = 0).

## Test plan

- [x] `cargo test -p continuum-core --test
      architecture_compose_by_event --features metal,accelerate`
      — 2/2 pass; grandfathered count = 1 (exact match)
- [x] `// proves: module compose-by-event` tag applied
- [x] Ratchet logic verified (both grow-detection and
      shrink-detection paths via inspection)
- [x] Line-comment skip verified — the two pre-existing
      `Commands.execute(...)` doc references in
      `vision_describe.rs` and `rate_proposals/mod.rs` do NOT
      trip the scanner

## Doctrine alignment

- Substrate doctrine § "Module compose-by-event" — cognition
  composes via event substrate or pre-bound handles, not
  imperative request-response round-trips
- [[no-fallbacks-ever]] — the ratchet IS the no-fallback
  equivalent for the cognition→command-executor coupling at
  build-graph layer

## Related

- Task #240 — architecture-test matrix, fourth proof
- Builds on PR #1589 (ratchet pattern) and PR #1591 (singleton ban —
  same scanner shape)
- Migration follow-up: tasks #112-#114 (#113 is currently
  in_progress) → ratchet count goes 1 → 0 → strict

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