Skip to content

feat(runtime): CommandInterceptor chain — kernel dispatch composes routing transports - #1483

Merged
joelteply merged 1 commit into
canaryfrom
feat/command-interceptor-chain
May 30, 2026
Merged

joelteply merged 1 commit into
canaryfrom
feat/command-interceptor-chain

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Summary

First execution of MODULE-ARCHITECTURE.md (PR #1482): the kernel composes routing decisions by walking a chain of interceptors before falling back to local Rust dispatch and then to TypeScript. No transport is special at the kernel level. Grid, airc, future mesh transports, future caching layers all sit behind the same trait and the same dispatch loop.

Zero behavior change for existing callers — the global executor is unchanged, no interceptors auto-installed, all existing commands work identically. New capability: any transport can plug into the dispatch chain via with_interceptor(...).

What broke before

The TS-side CommandDaemon grew a _gridInterceptor shim on the singleton specifically to hop work over to the grid before local dispatch. Same pressure now applies to airc, and any future transport (mesh, tower-relay) would re-bake the kernel each time. This PR generalizes: the kernel knows "walk a list, fall through when no one bites"; transports register themselves.

What this PR adds

runtime::command_interceptor::CommandInterceptor trait

#[async_trait]
pub trait CommandInterceptor: Send + Sync {
    async fn try_route(
        &self,
        command: &str,
        params: &Value,
    ) -> Result<InterceptorOutcome, String>;

    fn name(&self) -> &'static str;
}

pub enum InterceptorOutcome {
    Handled(CommandResult),  // Stop chain. Use this result.
    Decline,                 // Pass. Next interceptor (or local) tries.
}

Err aborts the chain immediately — no silent fallthrough on error. Per [[every-error-is-an-opportunity-to-battle-harden]]: silent fallthrough would hide exactly the routing bugs interceptors exist to surface.

runtime::airc_interceptor::AircInterceptor stub

  • Declines cleanly when no aircPeer/aircRoom param is present (back-compat guarantee for existing callers)
  • Fails loud with a concrete pointer to MODULE-ARCHITECTURE.md §7.1 when a caller actually requests airc routing
  • The fail-loud is the design: a caller writing aircPeer today learns immediately that the transport isn't ready, rather than getting silent local dispatch that masquerades as airc success
  • Replace the Err body with a call into @continuum-modules/airc's send-command primitive when the airc module ships

Extended CommandExecutor

let executor = CommandExecutor::new(registry)
    .with_interceptor(Arc::new(AircInterceptor::new()))
    .with_interceptor(Arc::new(GridInterceptor::new(...)));  // when wired

Dispatch order, single primitive:

  1. Interceptors (insertion order; first Handled wins; Err aborts)
  2. Local Rust ServiceModule via ModuleRegistry::route_command
  3. TypeScript via Unix socket (CommandRouterServer, unchanged)

Adding a transport = adding an interceptor. The trait is the seam.

Test plan

16 tests pin the contract:

Test Verifies
empty_chain_returns_none Empty chain falls through to local dispatch unchanged
all_decline_falls_through Walks every interceptor in insertion order
first_to_handle_wins_short_circuits_later Later interceptors not consulted (assertion on call count, not just result)
err_aborts_chain_no_silent_fallthrough Error propagates with interceptor name; later interceptors NOT consulted
name_propagates_through_dyn_trait name() survives the trait-object boundary for logs
airc::declines_when_no_airc_target Back-compat: existing callers see zero behavior change
airc::fails_loud_when_airc_peer_targeted Caller writing aircPeer today learns immediately
airc::fails_loud_when_airc_room_targeted Same for aircRoom
executor::empty_chain_by_default Fresh executor has zero interceptors
executor::with_interceptor_grows_chain_in_insertion_order with_interceptor appends, doesn't replace
executor::interceptors_walked_in_insertion_order_when_all_decline Order is observable
executor::first_handler_short_circuits_later_interceptors Stop happens, not just "result returned"
executor::airc_interceptor_declines_when_no_airc_target_params Composes with executor without false intercepts
executor::airc_interceptor_fails_loud_when_airc_peer_targeted Error reaches caller through executor + interceptor + chain
  • cargo check --lib --no-default-features --features metal,accelerate — clean
  • cargo test --lib runtime::command_interceptor runtime::airc_interceptor runtime::command_executor — 16/16

What this PR explicitly does NOT do

  • Does NOT modify init_executor — the global chain stays empty so this is purely additive. A follow-up PR can auto-install airc + grid interceptors once grid is wired.
  • Does NOT implement the GridInterceptor — that's a follow-up that bridges the existing modules/grid/router.rs::GridRouter into the new trait. The interceptor design supports it; the wiring is its own piece.
  • Does NOT add cell return shapes (Value/Handle/Stream/Lambda from MODULE-ARCHITECTURE §5.1). Today's CommandResult enum (Json + Binary) is preserved. Cells are a follow-up.
  • Does NOT migrate any existing command. The interceptor chain is the foundation; migrations build on top.

After merge

Follow-up PRs in priority order:

  1. GridInterceptor — bridges modules/grid/router.rs::GridRouter into the new trait. Wires Arc<GridRouter> + Arc<NodeRegistry> + Arc<dyn GridTransport> into the interceptor; auto-installs in init_executor.
  2. airc module + transport — @continuum-modules/airc ships with airc/send-command; AircInterceptor's Err body becomes a real call into it.
  3. Cell return shapes — extend CommandResult enum with Handle, Stream, Lambda per MODULE-ARCHITECTURE §5.1.
  4. First module migration — chat or generator module migrated under the full module-architecture pattern.

References

…uting transports

First execution of the architecture in PR #1482 (MODULE-ARCHITECTURE.md):
the kernel composes routing decisions by walking a chain of interceptors
before falling back to local Rust dispatch and then to TypeScript. No
transport is special at the kernel level — grid, airc, future mesh
transports, future caching layers all sit behind the same trait and the
same dispatch loop.

What broke before: the TS-side `CommandDaemon` grew a `_gridInterceptor`
shim on the singleton specifically to hop work over to the grid before
local dispatch. Same pressure now applies to airc, and any future
transport (mesh, tower-relay, etc.) would re-bake the kernel each time.
This commit generalizes: the kernel knows "walk a list, fall through
when no one bites"; transports register themselves.

Three pieces land together:

1. `runtime::command_interceptor::CommandInterceptor` trait with
   `InterceptorOutcome::{Handled, Decline}`. Implementations decide per
   call whether to take the command, pass, or fail. `Err` aborts the
   chain immediately — no silent fallthrough on error, per the standing
   `[[every-error-is-an-opportunity-to-battle-harden]]` rule, because
   silent fallthrough would hide exactly the routing bugs interceptors
   exist to surface.

2. `runtime::airc_interceptor::AircInterceptor` — stub form: declines
   cleanly when no `aircPeer`/`aircRoom` param is present (so existing
   callers see zero behavior change), fails loud with a concrete pointer
   to MODULE-ARCHITECTURE.md §7.1 when a caller actually requests airc
   routing. The fail-loud is the design: a caller who writes `aircPeer`
   today learns immediately that the transport isn't ready, rather than
   getting silent local dispatch that masquerades as airc success.
   Replace the `Err` body with a call into `@continuum-modules/airc`'s
   send-command primitive when the airc module ships.

3. `runtime::command_executor::CommandExecutor` extended with:
   - `interceptors: Vec<Arc<dyn CommandInterceptor>>` field
   - `with_interceptor(...)` builder for wiring at init
   - `interceptor_count()` diagnostic for kernel/health + tests
   - `execute()` rewritten to walk the chain BEFORE the existing
     ModuleRegistry → TS-bridge fallthrough

Dispatch order, top to bottom, single primitive:
  1. Interceptors (insertion order; first Handled wins; Err aborts)
  2. Local Rust ServiceModule via ModuleRegistry::route_command
  3. TypeScript via Unix socket (CommandRouterServer, unchanged)

Adding a transport is now adding an interceptor; no kernel changes
needed. The trait is the seam.

16 tests pin the contract:
- empty chain returns None (falls through to local dispatch unchanged)
- all-decline walks every interceptor in insertion order
- first Handled short-circuits later interceptors (assertions on the
  number of later calls, not just the result, to catch silent over-walks)
- Err aborts the chain with no silent fallthrough (interceptors after
  the error are NOT consulted; the error carries the interceptor name
  for diagnosis)
- name() survives the dyn trait boundary for logs + telemetry
- AircInterceptor declines without airc target params (back-compat
  guarantee that lets it be safely installed by default later)
- AircInterceptor fails loud with explicit aircPeer or aircRoom (the
  error names the target so callers can correlate logs and points at
  MODULE-ARCHITECTURE.md)
- CommandExecutor + AircInterceptor compose without breaking existing
  TS-bridge fallthrough on non-airc commands

The global `init_executor` is intentionally NOT changed in this PR — the
AircInterceptor is available, the wiring mechanism is in, but the global
chain stays empty so this PR is purely additive. A follow-up PR can
auto-install the airc + grid interceptors at init time once the grid
interceptor is wired.

This is the first execution of MODULE-ARCHITECTURE.md (PR #1482) and
the foundation everything else in the migration sits on. Per Joel
2026-05-30 "let's go" + "commands call commands, cross boundaries, even
towers and into the p2p mesh" — this is the seam where towers and the
p2p mesh plug in.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@joelteply
joelteply merged commit 9efe53b into canary May 30, 2026
3 checks passed
@joelteply
joelteply deleted the feat/command-interceptor-chain branch May 30, 2026 18:51
joelteply added a commit that referenced this pull request May 30, 2026
…he kernel chain (#1484)

Bridges the existing `modules/grid` routing into the
`CommandInterceptor` trait from PR #1483 and wires the chain
[AircInterceptor, GridInterceptor] into the production
`init_executor` at startup. Capability-based remote routing now
works for ANY command, not just explicit `grid/send` invocations.

# What lands

1. **Refactor: `handle_send` → `dispatch_to_node`.** Pulls the
   send-frame dance out of the explicit `grid/send` handler into a
   public `dispatch_to_node(state, node, command, params)` primitive.
   `handle_send` becomes a thin wrapper that parses params then
   delegates. Boy-scout move per Joel "do not half-ass it": one
   dispatch path, two callers (explicit `grid/send` + implicit
   interceptor), zero duplication.

2. **`GridState::try_route_remote`.** The new kernel-facing primitive.
   Applies `GridRouter::route` policy; if Local, returns `Ok(None)`
   so the interceptor declines; if Remote, dispatches via
   `dispatch_to_node` and returns `Ok(Some(result))`. Errors propagate
   per the `CommandInterceptor` contract (no silent fallthrough on
   Err, per `[[every-error-is-an-opportunity-to-battle-harden]]`).

3. **`GridModule::state()`** public getter. Lets the kernel build the
   `GridInterceptor` over the same `Arc<GridState>` the module itself
   runs on. No state duplication; no second router instance.

4. **`runtime::grid_interceptor::GridInterceptor`.** Wraps
   `try_route_remote`, implements `CommandInterceptor`. Lives in
   `runtime/` (not `modules/grid/`) because the interceptor TRAIT is a
   runtime concept — every transport interceptor sits behind it.
   GridInterceptor's *implementation* delegates to grid; that's just
   a dependency the runtime takes on the grid module, mediated by the
   public `state()` handle.

5. **`init_executor_with_interceptors`.** New entry point that takes
   a `Vec<Arc<dyn CommandInterceptor>>`. The back-compat
   `init_executor(registry)` shims to it with an empty chain so
   existing callers (tests, bin tools) keep working.

6. **Production wire-up in `ipc::start_server`.** Replaces
   `init_executor(registry)` with
   `init_executor_with_interceptors(registry, [AircInterceptor,
   GridInterceptor])`. Chain order is policy:
   - AircInterceptor first: explicit aircPeer/aircRoom targeting
     takes precedence over grid's capability-based remote routing
     (per MODULE-ARCHITECTURE.md §5).
   - GridInterceptor next: `routingHint` / `nodeId` /
     capability-based commands hop to a peer before the kernel tries
     local Rust dispatch.
   - Both decline cleanly when their routing decision is "local," so
     existing commands see zero behavior change.

# Test plan

20 tests pass (the original 16 from PR #1483 plus 4 new GridInterceptor
tests):

- `name_is_stable` — name() survives the dyn trait boundary
- `declines_when_router_picks_local` — no remote node + no hint →
  router picks Local → interceptor declines (chain falls through)
- `declines_for_local_only_hint` — routingHint:"local-only" forces
  Local regardless of capability
- `declines_when_target_node_not_in_registry` — explicit nodeId that
  doesn't resolve falls back to Local (existing GridRouter contract)

Remote-routing happy-path test (open transport, send frame, recv
response) lives behind a follow-up `tests/grid_interceptor_routes.rs`
integration test that stands up a mock GridTransport. Wiring this
unit-test surface against the real transport interface is non-trivial
(GridConnection trait + mock channel pair); deferred to keep this PR
focused.

# What this PR does NOT do

- Does NOT add cell return shapes (Value/Handle/Stream/Lambda from
  MODULE-ARCHITECTURE.md §5.1). Today's `CommandResult` enum (Json +
  Binary) is preserved. Cell shapes are a separate follow-up.
- Does NOT migrate any command to the per-module package architecture
  from MODULE-ARCHITECTURE.md §2. The interceptor chain is the kernel
  foundation; migrations build on top.
- Does NOT change the AircInterceptor's stub behavior — it still
  fails-loud on explicit aircPeer/aircRoom until the airc module ships
  its send-command primitive.

# After merge

Follow-up priorities:
1. `tests/grid_interceptor_routes.rs` — remote-routing integration
   test with a mock GridTransport.
2. Cell return shapes — extend `CommandResult` enum + thread through
   ServiceModule handlers + sketch the Handle protocol for hot-path
   cross-module state.
3. First module migration end-to-end (chat or the generator itself).

# References

- [docs/architecture/MODULE-ARCHITECTURE.md](docs/architecture/MODULE-ARCHITECTURE.md) §5 (composition) and §7.1 (airc as just another module)
- PR #1482 (architecture doc)
- PR #1483 (CommandInterceptor trait + AircInterceptor stub)

Co-authored-by: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request May 30, 2026
…work + reserved Stream/Lambda (#1485)

Lands the cell shapes from MODULE-ARCHITECTURE.md §5.1 as variants on
`CommandResult`. Handle is the headline shape — the answer to §13.1
(hot-path cross-module state) and the pattern Joel called out 2026-05-30:
"for long running commands like inference, hosting/inference/training/ORM
— a handle returned by the first call, passed in for subsequent work.
Always UUID for ids."

# What lands

1. **`runtime::cell_shapes::HandleRef`** — typed reference to state owned
   by a specific module. Fields: `owner: String` (the producing module),
   `id: Uuid` (UUID per Joel's directive; ts-rs binds it as `string` on
   the TS side), `type_tag: String` (`"<module>::<TypeName>"` convention),
   `created_at_ms: u64` (mint timestamp for TTL + ordering).

   Constructors:
   - `HandleRef::with_id(owner, id, type_tag)` — producer minted the
     UUID first and stored state under it; pass the same UUID here.
   - `HandleRef::mint(owner, type_tag)` — convenience that allocates
     a fresh UUID for producers that don't need to know it upfront.

2. **`runtime::cell_shapes::StreamPlaceholder` + `LambdaPlaceholder`** —
   reserved variants. Returning either is a RUNTIME ERROR per the
   contract; the in-process and wire protocols (streaming frame format
   + correlation/backpressure/cancellation, lambda dispatch+merge)
   aren't designed yet. The variants exist so the enum shape is fixed
   before handlers begin migrating, and so ts-rs binds the placeholders
   for TS-side anticipation. `#[non_exhaustive]` makes future field
   additions non-breaking for external code.

3. **Extended `CommandResult` enum** with `Handle(HandleRef)`,
   `Stream(StreamPlaceholder)`, `Lambda(LambdaPlaceholder)`. The
   existing `Json(Value)` and `Binary { metadata, data }` ARE the Value
   cell shape under the taxonomy — kept under their legacy names so
   the 300+ existing handlers don't have to change. `#[non_exhaustive]`
   on the enum signals downstream crates that more variants may come.

4. **`CommandResult::to_json_value`** — projects any cell shape to a
   plain `Value` for callers that just want the JSON payload regardless
   of variant. Json/Binary return their payload, Handle serializes the
   HandleRef as JSON (the TS-side caller holds it and passes back),
   Stream/Lambda return their canonical protocol errors via the new
   `stream_protocol_error` / `lambda_protocol_error` helpers.

5. **`CommandResult::handle(owner, id, type_tag)`** constructor — takes
   a Uuid directly to match the "producer mints UUID, stores state,
   returns handle" pattern from Joel's note.

6. **Five existing match sites updated** to handle the new variants:
   `runtime::command_executor::execute_json` (delegates to
   `to_json_value`), `modules::cognition` cross-module dispatcher
   (same), `modules::grid::connection` wire encoder (same), `ipc::mod`
   IPC response encoder (same), `modules::sentinel::steps::llm` (treats
   Handle/Stream/Lambda as contract violations with explicit step
   errors — ai/generate is a one-shot completion, not a long-running
   session, so handles belong elsewhere).

   Two test panic sites updated to use `other => panic!(...)` for
   forward-compat.

# Canonical use cases for Handle (per Joel)

- **inference** — `ai/inference/start { model, prompt }` returns a
  handle; `ai/inference/poll { handle }` + `ai/inference/cancel
  { handle }` operate on the running session.
- **training** — `training/run/start { recipe }` returns a handle;
  `training/run/progress { handle }` + `training/run/cancel { handle }`
  query and control.
- **hosting** — `live/room/join { roomId }` returns a handle;
  `live/audio/publish { handle, frame }` operates on the joined
  session.
- **ORM** — `data/transaction/begin` returns a handle;
  `data/transaction/exec { handle, query }` +
  `data/transaction/commit { handle }` thread the same transaction.

The pattern works the same whether the producer is in-process, in a
sibling module, or on a remote peer over grid/airc — Handle is a
typed reference that travels through the existing
`Commands.execute(name, { handle })` primitive. No kernel-level handle
registry needed; each producing module manages the lifetime of its own
handles internally.

# Test plan (23 tests pass)

cell_shapes::tests (7):
- `handle_ref_with_id_preserves_uuid` — UUID survives constructor
- `handle_ref_mint_generates_fresh_uuid` — successive mints distinct
- `handle_ref_roundtrips_through_json` — serde round-trip
- `handle_ref_id_serializes_as_string` — ts-rs/serde agree (`string`
  wire shape) so TS callers echo UUIDs cleanly
- `handle_ref_owns_distinct_state` — different UUIDs ≠ equal
- `stream_placeholder_roundtrips` — placeholder serde
- `lambda_placeholder_roundtrips` — placeholder serde

service_module::tests (8 new for CommandResult cell-shape integration):
- `json_to_json_value_returns_original`
- `binary_to_json_value_returns_metadata_drops_bytes` — bytes dropped;
  raw-byte consumers match on the variant directly
- `handle_to_json_value_serializes_handle_ref` — TS gets the handle as
  JSON they can echo back
- `stream_to_json_value_returns_protocol_error` — fail loud (named
  + points at doc), no silent degrade
- `lambda_to_json_value_returns_protocol_error` — same
- `command_result_handle_constructor_matches_handle_ref_with_id` —
  constructor produces the expected internal shape
- `command_result_protocol_errors_have_stable_wording` — error
  prefixes are stable for callers matching on them
- `handle_ref_round_trips_through_command_result_serialization` —
  end-to-end: handler → CommandResult → to_json_value → wire JSON →
  echo string → deserialize back → identical HandleRef

ts-rs export verification (3): HandleRef, StreamPlaceholder,
LambdaPlaceholder all generate clean TS bindings under
`shared/generated/runtime/`.

# What this PR does NOT do

- Does NOT change any existing handler's return shape. The 300+
  handlers still return Json/Binary; cell shapes are opt-in for new
  long-running commands.
- Does NOT design the Stream or Lambda wire protocols. Variants exist
  with `#[non_exhaustive]` placeholders so future fields land
  non-breaking; returning either today is a runtime error.
- Does NOT add a kernel-level handle registry — each producing module
  manages its own handle lifetimes internally per the design.
- Does NOT migrate any command to use Handle. Inference, training,
  hosting, ORM migrations are follow-up PRs that adopt the pattern.

# References

- [docs/architecture/MODULE-ARCHITECTURE.md](docs/architecture/MODULE-ARCHITECTURE.md)
  §5.1 (cell return shapes), §13.1 (hot-path cross-module state via
  cell handles)
- PR #1482 (architecture doc)
- PR #1483 (CommandInterceptor trait + AircInterceptor stub)
- PR #1484 (GridInterceptor wire-up — capability-based remote routing)

Co-authored-by: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request May 31, 2026
…trate work as authoring guide (#1493)

Per Joel 2026-05-30:
> "Let's make sure we have detailed designs for this command
>  infrastructure into modules and properly built from the ground
>  up by using our own generators."

Existing docs cover the **doctrine** (MODULE-ARCHITECTURE.md), the
**runtime contract** (CBAR-SUBSTRATE-ARCHITECTURE.md), and the
**concerns catalog** (MODULE-CATALOG.md). What was missing: the
**field manual** for a module author sitting down to write code
today.

This document codifies the substrate work from PRs #1483–#1492 into
reusable shape:

# What this manual covers

- **§1 The system in one sentence** — Commands + Events + Persona,
  in Rust, with airc handling grid. The doctrinal reduction Joel
  named on 2026-05-30.

- **§2 Substrate primitives quick reference** — ServiceModule trait,
  CommandRequest/Response envelopes, HandleRef + four cell shapes,
  HandleRef::expect_owned_by, CommandRequest::handle_id_or_legacy,
  interceptor chain, cross-module call pattern. Each with a code
  snippet pulled from the actual landed PRs.

- **§3 Module Design Template** — the canonical mod.rs + types.rs
  shape every ServiceModule follows. What the GeneratorModule
  scaffolds; what humans fill in. Rules for ts-rs annotations,
  serde camelCase, optional field handling, executor injection
  for tests.

- **§4 Concurrency doctrine** — per-resource locks (not module-wide),
  std::sync vs tokio::sync, the multi-thread test discipline
  (worker_threads=4), partial-failure semantics for dual-write
  composition. Pins the two real bugs caught this session
  (PR #1490 cursor race; PR #1487 generator same-name race) as
  doctrine, not anecdote.

- **§5 Migration playbook** — Joel's "rethink, don't port" rule
  with a pre-migration checklist + substrate checklist + a worked
  example for chat/analyze (the next chat migration).

- **§6 Generator usage** — how to scaffold a module via
  `./jtag generate/module`; v2 roadmap for the richer scaffold
  matching the Module Design Template.

- **§7 Acceptance criteria** — the 7-point bar for
  "concurrency-clean, wire-clean, ready for the headless integration
  test."

- **§8/§9 See also + PR references** — cross-refs to every
  substrate PR by surface, plus the existing architecture docs.

# Why a field manual now

The doctrinal docs answer the **why**. The catalog answers the
**which**. Neither answers the **how**: where do I find the
envelope API? what's the per-resource lock pattern? what shape
does the generator expect? what counts as a concurrency stress
test? The substrate is now coherent enough to be reduced to a
single reference an author can read once and start writing
clean modules from.

# What this does NOT do

- **Does NOT re-derive doctrine** — defers to MODULE-ARCHITECTURE.md
  for the architectural why.
- **Does NOT re-survey the module space** — defers to
  MODULE-CATALOG.md for what modules exist.
- **Does NOT change any code** — pure documentation, no Rust touched.
- **Does NOT propose v2 of the generator** in this PR — flagged in
  §6.1 as a separate follow-up. This PR establishes the template
  the v2 generator will emit.

# Follow-up PRs

- **Generator v2**: emit modules matching the Module Design Template
  (types.rs scaffold, tests skeleton with concurrency primer,
  DESIGN.md scaffold, per-resource lock scaffold when --stateful).
- **Per-module DESIGN.md pages** living next to mod.rs for each
  migrated module (chat, data, airc, generator). Each documents
  the module's role, command surface, state model, concurrency
  contract, kinks found.

# Length + scope

~440 lines. Tight by design — a manual the author reads in one
sitting before authoring, then references when stuck. The longer
the manual, the less anyone reads it.

Co-authored-by: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request May 31, 2026
…in Rust (step 4 of 4) (#1496)

Final step of the doc set Joel approved on 2026-05-30 ("Yeah let's do it. In order"):

1. ✅ Field manual codifying substrate (PR #1493)
2. ✅ Generator v2 emitting modules per the template (PR #1494)
3. ✅ Per-module design pages for what we've built (PR #1495)
4. **This PR**: MODULE-CATALOG.md update marking which modules are alive in Rust

# What this PR adds

A new `§0. Currently Live In Rust` section near the top of the
catalog with three sub-tables:

## Sub-table 1: Live modules

| Module | What ships | PR | Design doc | Concurrency proven |
|---|---|---|---|---|
| `chat` | chat/poll + chat/send | #1489 | CHAT-MODULE.md | 4 tests |
| `generator` | generate/module + v2 scaffold | #1487 + #1494 | GENERATOR-MODULE.md | 3 tests |
| `data` cursors | data/query-* with HandleRef | #1490 | DATA-CURSORS-MODULE.md | 7 tests |
| `airc/realtime-store` | in-process realtime store | (pre-session) + #1492 tests | AIRC-REALTIME-STORE-MODULE.md | 4 tests |

## Sub-table 2: Substrate primitives

The kernel-level work the four modules ride on — `ServiceModule`
trait, interceptor chain (PR #1483/#1484), HandleRef + cell shapes
(#1485), envelopes (#1486), expect_owned_by + handle_id_or_legacy
(#1491), field manual (#1493), generator v2 (#1494).

## Sub-table 3: Three-primitive map

Per Joel 2026-05-30, mapping the live modules to Commands / Events
/ Persona — showing chat + generator + data are Commands; airc/realtime
is Events; Persona is the next migration target.

# Why minimal restructure

The catalog is 1133 lines of design-proposal entries for every
Continuum concern. Restructuring individual entries to mark which
are live would scatter the live-vs-proposal signal across dozens
of sections. Putting it in one top-of-doc §0 section gives readers
the live-status at a glance without disturbing the rest of the
catalog's design-proposal framing.

# Doctrine the §0 establishes

Modules earn a row in §0 when they clear ALL THREE of the field
manual's acceptance criteria:

1. Rust implementation merged
2. Per-module design doc capturing role / surface / state /
   concurrency / migration / kinks
3. Multi-thread concurrency tests pinning per-resource invariants

This makes the catalog dual-purpose:
- **Design proposal repository** (§I–§IX, unchanged) — what we
  intend to build
- **Implementation status board** (§0, new) — what we've actually
  built + proven

Future migrations grow §0; the proposal sections shrink as their
entries get promoted.

# Updates to the header

- Cross-ref added to COMMAND-INFRASTRUCTURE-FIELD-MANUAL.md
  (joining CBAR / GENOME-FOUNDRY-SENTINEL / PERSONA-COGNITION-CONTRACT)
- Status line updated: "Most entries are design proposals … Some
  are now live in Rust — see §0 below"

# Net diff

+41 lines, -2 lines. Surgical addition that doesn't disturb the
existing catalog content.

# What this PR does NOT do

- **Does NOT migrate any module** — pure documentation
- **Does NOT restructure §I–§IX entries** — each concern stays in
  design-proposal form until it migrates to Rust + earns a §0 row
- **Does NOT add new module concerns to the catalog** — chat,
  generator, data cursors, and airc/realtime-store are already
  represented implicitly in the existing concerns sections; §0 is
  the live-status index, not a new concern listing

# References

- PR #1493 — Field manual (acceptance criteria the §0 table inherits)
- PR #1494 — Generator v2 (eats own dogfood)
- PR #1495 — Per-module design pages linked from §0
- PRs #1487, #1489, #1490, #1492 — the live modules
- Memory: `three-primitives-commands-events-persona`,
  `headless-rust-must-work-soon`

Co-authored-by: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request May 31, 2026
…dle as first-class field

Per Joel 2026-05-30: "Some things are used so much should just be part
of command result and params, handle for example. Find the patterns and
simplify. The better the pattern, the easier to use the command or to
reduce code size. I love OOP though."

Today's `ServiceModule::handle_command(command, params: Value) ->
Result<CommandResult, String>` shovels everything through raw JSON;
handlers re-parse the cross-cutting bits (handle, sessionId, userId,
success, error) themselves and rebuild the same envelope at every
return point. This commit gives the pattern names and a typed API so
new handlers stop hand-rolling the envelope every time.

# What lands

**`runtime::command_envelope::CommandRequest<P>`** — typed envelope
around an inbound command. Flattens the command-specific params `P`
with the cross-cutting fields every command can carry:
- `handle: Option<HandleRef>` — a handle from a previous call.
  Present when this command operates on existing state owned by
  another command (e.g., `inference/poll` carries the handle minted
  by `inference/start`).
- `session_id: Option<Uuid>` — calling session.
- `user_id: Option<Uuid>` — calling user.

Construction: `CommandRequest::<P>::from_value(value)?` at handler
entry. Test/programmatic construction via the builder methods
(`new(params)`, `.with_handle(...)`, `.with_session(...)`,
`.with_user(...)`). Wire shape stays flat — `#[serde(flatten)]` on
the params field — so existing TS-side callers don't see a shape
change.

**`runtime::command_envelope::CommandResponse<T>`** — typed envelope
around an outbound result. Same flatten pattern. Cross-cutting
fields:
- `success: bool` — operation-level success.
- `data: T` — command-specific payload, flattened into JSON.
- `handle: Option<HandleRef>` — a handle MINTED by this command for
  the caller's follow-up. The "first call returns a handle" pattern
  Joel called out for inference / training / hosting / ORM lives here.
- `error: Option<String>` — operation-level error, set when
  success == false.

Builder-style API: `CommandResponse::ok(data)` for happy path; chain
`.with_handle(owner, id, type_tag)` to mint a handle for follow-up;
`.with_handle_ref(handle)` to echo an existing handle. For failure,
`CommandResponse::<T>::err(message)` (requires `T: Default` so the
data field has a value; callers without a default just construct
directly).

Bridge into the existing `ServiceModule::handle_command` return: call
`.into_command_result()` — serializes the flattened envelope as
JSON, wraps as `CommandResult::Json`. One method to bridge typed
internal handler into the kernel surface.

# What this collapses (before/after)

Before — handler hand-rolls the envelope every time:
```ignore
async fn handle_inference_start(&self, params: Value) -> Result<CommandResult, String> {
    let p: InferenceStartParams = serde_json::from_value(params.clone())
        .map_err(|e| e.to_string())?;
    let session_id = params.get("sessionId").and_then(|v| v.as_str())
        .and_then(|s| Uuid::parse_str(s).ok());
    let id = Uuid::new_v4();
    self.sessions.insert(id, InferenceSession::new(p));
    Ok(CommandResult::Json(serde_json::json!({
        "success": true,
        "firstToken": first_token,
        "handle": HandleRef::with_id("ai/inference", id, "ai::InferenceSession"),
    })))
}
```

After — envelope handles the cross-cutting fields:
```ignore
async fn handle_inference_start(&self, params: Value) -> Result<CommandResult, String> {
    let req = CommandRequest::<InferenceStartParams>::from_value(params)?;
    let id = Uuid::new_v4();
    self.sessions.insert(id, InferenceSession::new(req.params));
    CommandResponse::ok(InferenceStartData { first_token })
        .with_handle("ai/inference", id, "ai::InferenceSession")
        .into_command_result()
}
```

Cross-cutting fields stop being something handlers know about. They
become free.

# Test plan (9/9 pass)

- `request_parses_flat_params_no_envelope_fields` — pure params,
  envelope fields default to None
- `request_parses_envelope_fields_flat` — handle/sessionId/userId all
  pulled from the same JSON object at top level
- `request_parse_error_carries_diagnostic` — type mismatch surfaces
  as Err with envelope identity (not panic)
- `request_builder_attaches_envelope_fields` — builder API works
- `response_ok_serializes_flat_with_success_true` — happy-path shape,
  handle/error omitted when None
- `response_with_handle_attaches_handle_at_top_level` — handle sits
  alongside flat data fields
- `response_err_serializes_with_success_false_and_message` — failure
  shape with default data preserved
- `response_into_command_result_yields_json_variant` — bridge to the
  ServiceModule return type works
- `round_trip_through_wire_preserves_envelope_fields` — end-to-end:
  handler returns response with handle → serialize → caller builds
  next request using the handle + own session/user → all envelope
  fields survive

# What this PR does NOT do

- Does NOT change `ServiceModule::handle_command` signature. The
  Value-based shape stays for the 300+ existing surface; new
  handlers opt into the typed envelope via `from_value` /
  `into_command_result`.
- Does NOT migrate any existing handler. The envelope is the
  primitive; migrations are individual follow-up PRs.
- Does NOT add a kernel-level handle registry. Each producer manages
  handle lifetimes internally per MODULE-ARCHITECTURE.md §13.1.

# References

- [docs/architecture/MODULE-ARCHITECTURE.md](docs/architecture/MODULE-ARCHITECTURE.md)
  §5.1 (cell return shapes), §13.1 (hot-path cross-module state)
- PR #1485 (cell return shapes — Handle variant + HandleRef)
- PR #1484 (GridInterceptor)
- PR #1483 (CommandInterceptor trait + AircInterceptor stub)
- PR #1482 (architecture doc)

Co-Authored-By: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request May 31, 2026
…dle as first-class field

Per Joel 2026-05-30: "Some things are used so much should just be part
of command result and params, handle for example. Find the patterns and
simplify. The better the pattern, the easier to use the command or to
reduce code size. I love OOP though."

Today's `ServiceModule::handle_command(command, params: Value) ->
Result<CommandResult, String>` shovels everything through raw JSON;
handlers re-parse the cross-cutting bits (handle, sessionId, userId,
success, error) themselves and rebuild the same envelope at every
return point. This commit gives the pattern names and a typed API so
new handlers stop hand-rolling the envelope every time.

# What lands

**`runtime::command_envelope::CommandRequest<P>`** — typed envelope
around an inbound command. Flattens the command-specific params `P`
with the cross-cutting fields every command can carry:
- `handle: Option<HandleRef>` — a handle from a previous call.
  Present when this command operates on existing state owned by
  another command (e.g., `inference/poll` carries the handle minted
  by `inference/start`).
- `session_id: Option<Uuid>` — calling session.
- `user_id: Option<Uuid>` — calling user.

Construction: `CommandRequest::<P>::from_value(value)?` at handler
entry. Test/programmatic construction via the builder methods
(`new(params)`, `.with_handle(...)`, `.with_session(...)`,
`.with_user(...)`). Wire shape stays flat — `#[serde(flatten)]` on
the params field — so existing TS-side callers don't see a shape
change.

**`runtime::command_envelope::CommandResponse<T>`** — typed envelope
around an outbound result. Same flatten pattern. Cross-cutting
fields:
- `success: bool` — operation-level success.
- `data: T` — command-specific payload, flattened into JSON.
- `handle: Option<HandleRef>` — a handle MINTED by this command for
  the caller's follow-up. The "first call returns a handle" pattern
  Joel called out for inference / training / hosting / ORM lives here.
- `error: Option<String>` — operation-level error, set when
  success == false.

Builder-style API: `CommandResponse::ok(data)` for happy path; chain
`.with_handle(owner, id, type_tag)` to mint a handle for follow-up;
`.with_handle_ref(handle)` to echo an existing handle. For failure,
`CommandResponse::<T>::err(message)` (requires `T: Default` so the
data field has a value; callers without a default just construct
directly).

Bridge into the existing `ServiceModule::handle_command` return: call
`.into_command_result()` — serializes the flattened envelope as
JSON, wraps as `CommandResult::Json`. One method to bridge typed
internal handler into the kernel surface.

# What this collapses (before/after)

Before — handler hand-rolls the envelope every time:
```ignore
async fn handle_inference_start(&self, params: Value) -> Result<CommandResult, String> {
    let p: InferenceStartParams = serde_json::from_value(params.clone())
        .map_err(|e| e.to_string())?;
    let session_id = params.get("sessionId").and_then(|v| v.as_str())
        .and_then(|s| Uuid::parse_str(s).ok());
    let id = Uuid::new_v4();
    self.sessions.insert(id, InferenceSession::new(p));
    Ok(CommandResult::Json(serde_json::json!({
        "success": true,
        "firstToken": first_token,
        "handle": HandleRef::with_id("ai/inference", id, "ai::InferenceSession"),
    })))
}
```

After — envelope handles the cross-cutting fields:
```ignore
async fn handle_inference_start(&self, params: Value) -> Result<CommandResult, String> {
    let req = CommandRequest::<InferenceStartParams>::from_value(params)?;
    let id = Uuid::new_v4();
    self.sessions.insert(id, InferenceSession::new(req.params));
    CommandResponse::ok(InferenceStartData { first_token })
        .with_handle("ai/inference", id, "ai::InferenceSession")
        .into_command_result()
}
```

Cross-cutting fields stop being something handlers know about. They
become free.

# Test plan (9/9 pass)

- `request_parses_flat_params_no_envelope_fields` — pure params,
  envelope fields default to None
- `request_parses_envelope_fields_flat` — handle/sessionId/userId all
  pulled from the same JSON object at top level
- `request_parse_error_carries_diagnostic` — type mismatch surfaces
  as Err with envelope identity (not panic)
- `request_builder_attaches_envelope_fields` — builder API works
- `response_ok_serializes_flat_with_success_true` — happy-path shape,
  handle/error omitted when None
- `response_with_handle_attaches_handle_at_top_level` — handle sits
  alongside flat data fields
- `response_err_serializes_with_success_false_and_message` — failure
  shape with default data preserved
- `response_into_command_result_yields_json_variant` — bridge to the
  ServiceModule return type works
- `round_trip_through_wire_preserves_envelope_fields` — end-to-end:
  handler returns response with handle → serialize → caller builds
  next request using the handle + own session/user → all envelope
  fields survive

# What this PR does NOT do

- Does NOT change `ServiceModule::handle_command` signature. The
  Value-based shape stays for the 300+ existing surface; new
  handlers opt into the typed envelope via `from_value` /
  `into_command_result`.
- Does NOT migrate any existing handler. The envelope is the
  primitive; migrations are individual follow-up PRs.
- Does NOT add a kernel-level handle registry. Each producer manages
  handle lifetimes internally per MODULE-ARCHITECTURE.md §13.1.

# References

- [docs/architecture/MODULE-ARCHITECTURE.md](docs/architecture/MODULE-ARCHITECTURE.md)
  §5.1 (cell return shapes), §13.1 (hot-path cross-module state)
- PR #1485 (cell return shapes — Handle variant + HandleRef)
- PR #1484 (GridInterceptor)
- PR #1483 (CommandInterceptor trait + AircInterceptor stub)
- PR #1482 (architecture doc)

Co-Authored-By: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request May 31, 2026
…w module scaffolds

Per Joel 2026-05-30: "we developed a generator so we could manufacture
these patterns for new commands modules etc, which itself was a
command. Meta."

The recursive bootstrap from MODULE-ARCHITECTURE.md §10 lands. The
generator IS a module. The things it creates are modules. Every
operation it performs is a command. The system describes itself in
its own terms.

# What this does

`Commands.execute("generate/module", { ... })` scaffolds a compilable
ServiceModule package under
`src/workers/continuum-core/src/modules/<name>/`:

- `mod.rs` — `pub struct <Name>Module {}` with `ServiceModule`
  implemented, the `ModuleConfig` declaring the spec's commands +
  events, and `handle_command` returning typed "not yet implemented"
  errors for each declared command (so the scaffold compiles + the
  author fills in real handlers afterwards).
- `README.md` — author-facing doc capturing the same contract +
  spelling out the manual wire-up step (add `pub mod <name>;` to
  the parent `modules/mod.rs`, register `Arc::new(<Name>Module::new())`
  at runtime startup).

The generated module follows every pattern this session codified:

- `ServiceModule` trait from PR #1471 (the substrate floor)
- `CommandResult` cell shapes from PR #1485
- `CommandRequest<P>` / `CommandResponse<T>` envelopes from PR #1486
  (the generator itself uses these — typed envelope in, typed
  envelope out)
- The architecture from MODULE-ARCHITECTURE.md (PR #1482)

# Why this is the meta move

Every architectural pattern we codified degrades fast if every new
module's author has to re-derive them from the docs. The generator
is the boy-scout amplifier: write the patterns once into the
templates, run `Commands.execute("generate/module", ...)`, get a
module skeleton that already follows them. Subsequent migrations
become "fill in the handler bodies" rather than "re-derive the
shape."

The generator can eventually generate itself (the recursion closes).
This PR ships the v1; future PRs add `generate/command` (add a new
command to an existing module) and `generate/refresh` (re-scan the
modules tree and refresh manifests).

# Implementation surface

Three files under `modules/generator/`:

- **`types.rs`** — `GenerateModuleParams` (name, description, commands,
  events_subscribed, events_published, priority, force) +
  `GenerateModuleResult` (module_path, files_created, next_step) +
  `PrioritySpec` wire enum + `validate_module_name`. All
  serde-friendly, no leak of internal types onto the wire.

- **`templates.rs`** — pure render functions: `mod_rs_template`,
  `readme_template`, and helpers. No I/O lives here; the caller does
  the writes. Keeps the templates testable in isolation and the I/O
  paths easy to swap (e.g., future dry-run mode).

- **`mod.rs`** — `GeneratorModule` (the `ServiceModule` impl) +
  `generate_module_inner` (the actual filesystem work). `handle_command`
  parses a `CommandRequest<GenerateModuleParams>` and materializes a
  `CommandResponse<GenerateModuleResult>` — uses the exact envelope
  pattern PR #1486 introduced, eating its own dogfood.

The module is wired into `modules/mod.rs` as `pub mod generator;` —
the same step the generator instructs callers to perform for the
modules IT scaffolds.

# Tests (21/21 pass)

types.rs (5):
- `validate_accepts_canonical_names` — chat, ai_provider,
  ai-provider, _internal, a1
- `validate_rejects_empty_or_invalid` — empty, capitalized,
  leading-digit, has-space, with-slash
- `priority_spec_round_trips_through_json` — all 4 variants
- `priority_spec_default_is_normal`
- `priority_spec_as_variant_str_matches_rust_enum`

templates.rs (7):
- `mod_rs_contains_struct_definition_and_trait_impl`
- `mod_rs_lists_each_declared_command_in_prefix_and_dispatch`
- `mod_rs_includes_module_name_prefix_in_command_prefixes`
- `mod_rs_subscribes_to_declared_events`
- `mod_rs_documents_published_events_in_module_docstring`
- `mod_rs_for_command_less_module_still_compiles_shape`
- `readme_lists_declared_contract`
- `readme_handles_empty_lists_gracefully`

mod.rs (8):
- `struct_name_handles_hyphens_underscores_and_simple_names`
- `config_advertises_generate_prefix`
- `generate_module_creates_dir_and_files` — full filesystem round-trip
  in a tempdir, asserts struct name + declared commands + ServiceModule
  appear in the generated mod.rs
- `generate_module_refuses_existing_dir_without_force` — fail-loud,
  error names the conflict AND the escape hatch
- `generate_module_overwrites_with_force` — and the second
  generation's description appears in the file
- `generate_module_rejects_invalid_names` — empty / space / slash /
  parent-escape / leading-digit
- `handle_command_returns_typed_envelope` — end-to-end through the
  ServiceModule trait + CommandRequest envelope + CommandResponse
  envelope + the JSON round-trip
- `handle_command_rejects_unknown_command_loud` — error names the bad
  command + what's supported

# What this PR explicitly does NOT do

- Does NOT auto-wire the generated module into the parent
  `modules/mod.rs`. The generator emits the exact line the caller
  needs to add — explicit human step keeps the registration audit
  obvious. A future `generate/refresh` command can do this
  automatically.
- Does NOT generate package.json / manifest.json. The architecture
  doc anticipates these, but the on-disk module structure in
  continuum-core today is "everything compiles into one binary," so
  per-module manifests are a future migration (WASM-component
  modules will need them per MODULE-ARCHITECTURE.md §9).
- Does NOT register `GeneratorModule` at runtime startup. The module
  is reachable via direct construction in tests; production wire-up
  happens in `ipc::start_server` once the typical "register Arc::new"
  pattern is followed (the generator's README spells this out for
  EVERY module it creates, including itself).
- Does NOT implement `generate/command` (add a command to an
  existing module) or `generate/refresh` (re-scan + refresh
  manifests). Both are natural follow-ups; this PR ships the v1.

# References

- [docs/architecture/MODULE-ARCHITECTURE.md](docs/architecture/MODULE-ARCHITECTURE.md)
  §10 (recursive bootstrap), §2 (what a module is)
- PR #1486 (CommandRequest/Response envelopes — used here)
- PR #1485 (cell shapes — used here)
- PR #1483 / #1484 (interceptor chain — orthogonal but composable)
- PR #1482 (architecture doc)

Co-Authored-By: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request May 31, 2026
…dle as first-class field

Per Joel 2026-05-30: "Some things are used so much should just be part
of command result and params, handle for example. Find the patterns and
simplify. The better the pattern, the easier to use the command or to
reduce code size. I love OOP though."

Today's `ServiceModule::handle_command(command, params: Value) ->
Result<CommandResult, String>` shovels everything through raw JSON;
handlers re-parse the cross-cutting bits (handle, sessionId, userId,
success, error) themselves and rebuild the same envelope at every
return point. This commit gives the pattern names and a typed API so
new handlers stop hand-rolling the envelope every time.

# What lands

**`runtime::command_envelope::CommandRequest<P>`** — typed envelope
around an inbound command. Flattens the command-specific params `P`
with the cross-cutting fields every command can carry:
- `handle: Option<HandleRef>` — a handle from a previous call.
  Present when this command operates on existing state owned by
  another command (e.g., `inference/poll` carries the handle minted
  by `inference/start`).
- `session_id: Option<Uuid>` — calling session.
- `user_id: Option<Uuid>` — calling user.

Construction: `CommandRequest::<P>::from_value(value)?` at handler
entry. Test/programmatic construction via the builder methods
(`new(params)`, `.with_handle(...)`, `.with_session(...)`,
`.with_user(...)`). Wire shape stays flat — `#[serde(flatten)]` on
the params field — so existing TS-side callers don't see a shape
change.

**`runtime::command_envelope::CommandResponse<T>`** — typed envelope
around an outbound result. Same flatten pattern. Cross-cutting
fields:
- `success: bool` — operation-level success.
- `data: T` — command-specific payload, flattened into JSON.
- `handle: Option<HandleRef>` — a handle MINTED by this command for
  the caller's follow-up. The "first call returns a handle" pattern
  Joel called out for inference / training / hosting / ORM lives here.
- `error: Option<String>` — operation-level error, set when
  success == false.

Builder-style API: `CommandResponse::ok(data)` for happy path; chain
`.with_handle(owner, id, type_tag)` to mint a handle for follow-up;
`.with_handle_ref(handle)` to echo an existing handle. For failure,
`CommandResponse::<T>::err(message)` (requires `T: Default` so the
data field has a value; callers without a default just construct
directly).

Bridge into the existing `ServiceModule::handle_command` return: call
`.into_command_result()` — serializes the flattened envelope as
JSON, wraps as `CommandResult::Json`. One method to bridge typed
internal handler into the kernel surface.

# What this collapses (before/after)

Before — handler hand-rolls the envelope every time:
```ignore
async fn handle_inference_start(&self, params: Value) -> Result<CommandResult, String> {
    let p: InferenceStartParams = serde_json::from_value(params.clone())
        .map_err(|e| e.to_string())?;
    let session_id = params.get("sessionId").and_then(|v| v.as_str())
        .and_then(|s| Uuid::parse_str(s).ok());
    let id = Uuid::new_v4();
    self.sessions.insert(id, InferenceSession::new(p));
    Ok(CommandResult::Json(serde_json::json!({
        "success": true,
        "firstToken": first_token,
        "handle": HandleRef::with_id("ai/inference", id, "ai::InferenceSession"),
    })))
}
```

After — envelope handles the cross-cutting fields:
```ignore
async fn handle_inference_start(&self, params: Value) -> Result<CommandResult, String> {
    let req = CommandRequest::<InferenceStartParams>::from_value(params)?;
    let id = Uuid::new_v4();
    self.sessions.insert(id, InferenceSession::new(req.params));
    CommandResponse::ok(InferenceStartData { first_token })
        .with_handle("ai/inference", id, "ai::InferenceSession")
        .into_command_result()
}
```

Cross-cutting fields stop being something handlers know about. They
become free.

# Test plan (9/9 pass)

- `request_parses_flat_params_no_envelope_fields` — pure params,
  envelope fields default to None
- `request_parses_envelope_fields_flat` — handle/sessionId/userId all
  pulled from the same JSON object at top level
- `request_parse_error_carries_diagnostic` — type mismatch surfaces
  as Err with envelope identity (not panic)
- `request_builder_attaches_envelope_fields` — builder API works
- `response_ok_serializes_flat_with_success_true` — happy-path shape,
  handle/error omitted when None
- `response_with_handle_attaches_handle_at_top_level` — handle sits
  alongside flat data fields
- `response_err_serializes_with_success_false_and_message` — failure
  shape with default data preserved
- `response_into_command_result_yields_json_variant` — bridge to the
  ServiceModule return type works
- `round_trip_through_wire_preserves_envelope_fields` — end-to-end:
  handler returns response with handle → serialize → caller builds
  next request using the handle + own session/user → all envelope
  fields survive

# What this PR does NOT do

- Does NOT change `ServiceModule::handle_command` signature. The
  Value-based shape stays for the 300+ existing surface; new
  handlers opt into the typed envelope via `from_value` /
  `into_command_result`.
- Does NOT migrate any existing handler. The envelope is the
  primitive; migrations are individual follow-up PRs.
- Does NOT add a kernel-level handle registry. Each producer manages
  handle lifetimes internally per MODULE-ARCHITECTURE.md §13.1.

# References

- [docs/architecture/MODULE-ARCHITECTURE.md](docs/architecture/MODULE-ARCHITECTURE.md)
  §5.1 (cell return shapes), §13.1 (hot-path cross-module state)
- PR #1485 (cell return shapes — Handle variant + HandleRef)
- PR #1484 (GridInterceptor)
- PR #1483 (CommandInterceptor trait + AircInterceptor stub)
- PR #1482 (architecture doc)

Co-Authored-By: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request May 31, 2026
…w module scaffolds

Per Joel 2026-05-30: "we developed a generator so we could manufacture
these patterns for new commands modules etc, which itself was a
command. Meta."

The recursive bootstrap from MODULE-ARCHITECTURE.md §10 lands. The
generator IS a module. The things it creates are modules. Every
operation it performs is a command. The system describes itself in
its own terms.

# What this does

`Commands.execute("generate/module", { ... })` scaffolds a compilable
ServiceModule package under
`src/workers/continuum-core/src/modules/<name>/`:

- `mod.rs` — `pub struct <Name>Module {}` with `ServiceModule`
  implemented, the `ModuleConfig` declaring the spec's commands +
  events, and `handle_command` returning typed "not yet implemented"
  errors for each declared command (so the scaffold compiles + the
  author fills in real handlers afterwards).
- `README.md` — author-facing doc capturing the same contract +
  spelling out the manual wire-up step (add `pub mod <name>;` to
  the parent `modules/mod.rs`, register `Arc::new(<Name>Module::new())`
  at runtime startup).

The generated module follows every pattern this session codified:

- `ServiceModule` trait from PR #1471 (the substrate floor)
- `CommandResult` cell shapes from PR #1485
- `CommandRequest<P>` / `CommandResponse<T>` envelopes from PR #1486
  (the generator itself uses these — typed envelope in, typed
  envelope out)
- The architecture from MODULE-ARCHITECTURE.md (PR #1482)

# Why this is the meta move

Every architectural pattern we codified degrades fast if every new
module's author has to re-derive them from the docs. The generator
is the boy-scout amplifier: write the patterns once into the
templates, run `Commands.execute("generate/module", ...)`, get a
module skeleton that already follows them. Subsequent migrations
become "fill in the handler bodies" rather than "re-derive the
shape."

The generator can eventually generate itself (the recursion closes).
This PR ships the v1; future PRs add `generate/command` (add a new
command to an existing module) and `generate/refresh` (re-scan the
modules tree and refresh manifests).

# Implementation surface

Three files under `modules/generator/`:

- **`types.rs`** — `GenerateModuleParams` (name, description, commands,
  events_subscribed, events_published, priority, force) +
  `GenerateModuleResult` (module_path, files_created, next_step) +
  `PrioritySpec` wire enum + `validate_module_name`. All
  serde-friendly, no leak of internal types onto the wire.

- **`templates.rs`** — pure render functions: `mod_rs_template`,
  `readme_template`, and helpers. No I/O lives here; the caller does
  the writes. Keeps the templates testable in isolation and the I/O
  paths easy to swap (e.g., future dry-run mode).

- **`mod.rs`** — `GeneratorModule` (the `ServiceModule` impl) +
  `generate_module_inner` (the actual filesystem work). `handle_command`
  parses a `CommandRequest<GenerateModuleParams>` and materializes a
  `CommandResponse<GenerateModuleResult>` — uses the exact envelope
  pattern PR #1486 introduced, eating its own dogfood.

The module is wired into `modules/mod.rs` as `pub mod generator;` —
the same step the generator instructs callers to perform for the
modules IT scaffolds.

# Tests (21/21 pass)

types.rs (5):
- `validate_accepts_canonical_names` — chat, ai_provider,
  ai-provider, _internal, a1
- `validate_rejects_empty_or_invalid` — empty, capitalized,
  leading-digit, has-space, with-slash
- `priority_spec_round_trips_through_json` — all 4 variants
- `priority_spec_default_is_normal`
- `priority_spec_as_variant_str_matches_rust_enum`

templates.rs (7):
- `mod_rs_contains_struct_definition_and_trait_impl`
- `mod_rs_lists_each_declared_command_in_prefix_and_dispatch`
- `mod_rs_includes_module_name_prefix_in_command_prefixes`
- `mod_rs_subscribes_to_declared_events`
- `mod_rs_documents_published_events_in_module_docstring`
- `mod_rs_for_command_less_module_still_compiles_shape`
- `readme_lists_declared_contract`
- `readme_handles_empty_lists_gracefully`

mod.rs (8):
- `struct_name_handles_hyphens_underscores_and_simple_names`
- `config_advertises_generate_prefix`
- `generate_module_creates_dir_and_files` — full filesystem round-trip
  in a tempdir, asserts struct name + declared commands + ServiceModule
  appear in the generated mod.rs
- `generate_module_refuses_existing_dir_without_force` — fail-loud,
  error names the conflict AND the escape hatch
- `generate_module_overwrites_with_force` — and the second
  generation's description appears in the file
- `generate_module_rejects_invalid_names` — empty / space / slash /
  parent-escape / leading-digit
- `handle_command_returns_typed_envelope` — end-to-end through the
  ServiceModule trait + CommandRequest envelope + CommandResponse
  envelope + the JSON round-trip
- `handle_command_rejects_unknown_command_loud` — error names the bad
  command + what's supported

# What this PR explicitly does NOT do

- Does NOT auto-wire the generated module into the parent
  `modules/mod.rs`. The generator emits the exact line the caller
  needs to add — explicit human step keeps the registration audit
  obvious. A future `generate/refresh` command can do this
  automatically.
- Does NOT generate package.json / manifest.json. The architecture
  doc anticipates these, but the on-disk module structure in
  continuum-core today is "everything compiles into one binary," so
  per-module manifests are a future migration (WASM-component
  modules will need them per MODULE-ARCHITECTURE.md §9).
- Does NOT register `GeneratorModule` at runtime startup. The module
  is reachable via direct construction in tests; production wire-up
  happens in `ipc::start_server` once the typical "register Arc::new"
  pattern is followed (the generator's README spells this out for
  EVERY module it creates, including itself).
- Does NOT implement `generate/command` (add a command to an
  existing module) or `generate/refresh` (re-scan + refresh
  manifests). Both are natural follow-ups; this PR ships the v1.

# References

- [docs/architecture/MODULE-ARCHITECTURE.md](docs/architecture/MODULE-ARCHITECTURE.md)
  §10 (recursive bootstrap), §2 (what a module is)
- PR #1486 (CommandRequest/Response envelopes — used here)
- PR #1485 (cell shapes — used here)
- PR #1483 / #1484 (interceptor chain — orthogonal but composable)
- PR #1482 (architecture doc)

Co-Authored-By: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request May 31, 2026
…dle as first-class field (#1486)

Per Joel 2026-05-30: "Some things are used so much should just be part
of command result and params, handle for example. Find the patterns and
simplify. The better the pattern, the easier to use the command or to
reduce code size. I love OOP though."

Today's `ServiceModule::handle_command(command, params: Value) ->
Result<CommandResult, String>` shovels everything through raw JSON;
handlers re-parse the cross-cutting bits (handle, sessionId, userId,
success, error) themselves and rebuild the same envelope at every
return point. This commit gives the pattern names and a typed API so
new handlers stop hand-rolling the envelope every time.

# What lands

**`runtime::command_envelope::CommandRequest<P>`** — typed envelope
around an inbound command. Flattens the command-specific params `P`
with the cross-cutting fields every command can carry:
- `handle: Option<HandleRef>` — a handle from a previous call.
  Present when this command operates on existing state owned by
  another command (e.g., `inference/poll` carries the handle minted
  by `inference/start`).
- `session_id: Option<Uuid>` — calling session.
- `user_id: Option<Uuid>` — calling user.

Construction: `CommandRequest::<P>::from_value(value)?` at handler
entry. Test/programmatic construction via the builder methods
(`new(params)`, `.with_handle(...)`, `.with_session(...)`,
`.with_user(...)`). Wire shape stays flat — `#[serde(flatten)]` on
the params field — so existing TS-side callers don't see a shape
change.

**`runtime::command_envelope::CommandResponse<T>`** — typed envelope
around an outbound result. Same flatten pattern. Cross-cutting
fields:
- `success: bool` — operation-level success.
- `data: T` — command-specific payload, flattened into JSON.
- `handle: Option<HandleRef>` — a handle MINTED by this command for
  the caller's follow-up. The "first call returns a handle" pattern
  Joel called out for inference / training / hosting / ORM lives here.
- `error: Option<String>` — operation-level error, set when
  success == false.

Builder-style API: `CommandResponse::ok(data)` for happy path; chain
`.with_handle(owner, id, type_tag)` to mint a handle for follow-up;
`.with_handle_ref(handle)` to echo an existing handle. For failure,
`CommandResponse::<T>::err(message)` (requires `T: Default` so the
data field has a value; callers without a default just construct
directly).

Bridge into the existing `ServiceModule::handle_command` return: call
`.into_command_result()` — serializes the flattened envelope as
JSON, wraps as `CommandResult::Json`. One method to bridge typed
internal handler into the kernel surface.

# What this collapses (before/after)

Before — handler hand-rolls the envelope every time:
```ignore
async fn handle_inference_start(&self, params: Value) -> Result<CommandResult, String> {
    let p: InferenceStartParams = serde_json::from_value(params.clone())
        .map_err(|e| e.to_string())?;
    let session_id = params.get("sessionId").and_then(|v| v.as_str())
        .and_then(|s| Uuid::parse_str(s).ok());
    let id = Uuid::new_v4();
    self.sessions.insert(id, InferenceSession::new(p));
    Ok(CommandResult::Json(serde_json::json!({
        "success": true,
        "firstToken": first_token,
        "handle": HandleRef::with_id("ai/inference", id, "ai::InferenceSession"),
    })))
}
```

After — envelope handles the cross-cutting fields:
```ignore
async fn handle_inference_start(&self, params: Value) -> Result<CommandResult, String> {
    let req = CommandRequest::<InferenceStartParams>::from_value(params)?;
    let id = Uuid::new_v4();
    self.sessions.insert(id, InferenceSession::new(req.params));
    CommandResponse::ok(InferenceStartData { first_token })
        .with_handle("ai/inference", id, "ai::InferenceSession")
        .into_command_result()
}
```

Cross-cutting fields stop being something handlers know about. They
become free.

# Test plan (9/9 pass)

- `request_parses_flat_params_no_envelope_fields` — pure params,
  envelope fields default to None
- `request_parses_envelope_fields_flat` — handle/sessionId/userId all
  pulled from the same JSON object at top level
- `request_parse_error_carries_diagnostic` — type mismatch surfaces
  as Err with envelope identity (not panic)
- `request_builder_attaches_envelope_fields` — builder API works
- `response_ok_serializes_flat_with_success_true` — happy-path shape,
  handle/error omitted when None
- `response_with_handle_attaches_handle_at_top_level` — handle sits
  alongside flat data fields
- `response_err_serializes_with_success_false_and_message` — failure
  shape with default data preserved
- `response_into_command_result_yields_json_variant` — bridge to the
  ServiceModule return type works
- `round_trip_through_wire_preserves_envelope_fields` — end-to-end:
  handler returns response with handle → serialize → caller builds
  next request using the handle + own session/user → all envelope
  fields survive

# What this PR does NOT do

- Does NOT change `ServiceModule::handle_command` signature. The
  Value-based shape stays for the 300+ existing surface; new
  handlers opt into the typed envelope via `from_value` /
  `into_command_result`.
- Does NOT migrate any existing handler. The envelope is the
  primitive; migrations are individual follow-up PRs.
- Does NOT add a kernel-level handle registry. Each producer manages
  handle lifetimes internally per MODULE-ARCHITECTURE.md §13.1.

# References

- [docs/architecture/MODULE-ARCHITECTURE.md](docs/architecture/MODULE-ARCHITECTURE.md)
  §5.1 (cell return shapes), §13.1 (hot-path cross-module state)
- PR #1485 (cell return shapes — Handle variant + HandleRef)
- PR #1484 (GridInterceptor)
- PR #1483 (CommandInterceptor trait + AircInterceptor stub)
- PR #1482 (architecture doc)

Co-authored-by: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request May 31, 2026
…w module scaffolds (#1487)

* feat(runtime): CommandRequest<P> / CommandResponse<T> envelopes — handle as first-class field

Per Joel 2026-05-30: "Some things are used so much should just be part
of command result and params, handle for example. Find the patterns and
simplify. The better the pattern, the easier to use the command or to
reduce code size. I love OOP though."

Today's `ServiceModule::handle_command(command, params: Value) ->
Result<CommandResult, String>` shovels everything through raw JSON;
handlers re-parse the cross-cutting bits (handle, sessionId, userId,
success, error) themselves and rebuild the same envelope at every
return point. This commit gives the pattern names and a typed API so
new handlers stop hand-rolling the envelope every time.

# What lands

**`runtime::command_envelope::CommandRequest<P>`** — typed envelope
around an inbound command. Flattens the command-specific params `P`
with the cross-cutting fields every command can carry:
- `handle: Option<HandleRef>` — a handle from a previous call.
  Present when this command operates on existing state owned by
  another command (e.g., `inference/poll` carries the handle minted
  by `inference/start`).
- `session_id: Option<Uuid>` — calling session.
- `user_id: Option<Uuid>` — calling user.

Construction: `CommandRequest::<P>::from_value(value)?` at handler
entry. Test/programmatic construction via the builder methods
(`new(params)`, `.with_handle(...)`, `.with_session(...)`,
`.with_user(...)`). Wire shape stays flat — `#[serde(flatten)]` on
the params field — so existing TS-side callers don't see a shape
change.

**`runtime::command_envelope::CommandResponse<T>`** — typed envelope
around an outbound result. Same flatten pattern. Cross-cutting
fields:
- `success: bool` — operation-level success.
- `data: T` — command-specific payload, flattened into JSON.
- `handle: Option<HandleRef>` — a handle MINTED by this command for
  the caller's follow-up. The "first call returns a handle" pattern
  Joel called out for inference / training / hosting / ORM lives here.
- `error: Option<String>` — operation-level error, set when
  success == false.

Builder-style API: `CommandResponse::ok(data)` for happy path; chain
`.with_handle(owner, id, type_tag)` to mint a handle for follow-up;
`.with_handle_ref(handle)` to echo an existing handle. For failure,
`CommandResponse::<T>::err(message)` (requires `T: Default` so the
data field has a value; callers without a default just construct
directly).

Bridge into the existing `ServiceModule::handle_command` return: call
`.into_command_result()` — serializes the flattened envelope as
JSON, wraps as `CommandResult::Json`. One method to bridge typed
internal handler into the kernel surface.

# What this collapses (before/after)

Before — handler hand-rolls the envelope every time:
```ignore
async fn handle_inference_start(&self, params: Value) -> Result<CommandResult, String> {
    let p: InferenceStartParams = serde_json::from_value(params.clone())
        .map_err(|e| e.to_string())?;
    let session_id = params.get("sessionId").and_then(|v| v.as_str())
        .and_then(|s| Uuid::parse_str(s).ok());
    let id = Uuid::new_v4();
    self.sessions.insert(id, InferenceSession::new(p));
    Ok(CommandResult::Json(serde_json::json!({
        "success": true,
        "firstToken": first_token,
        "handle": HandleRef::with_id("ai/inference", id, "ai::InferenceSession"),
    })))
}
```

After — envelope handles the cross-cutting fields:
```ignore
async fn handle_inference_start(&self, params: Value) -> Result<CommandResult, String> {
    let req = CommandRequest::<InferenceStartParams>::from_value(params)?;
    let id = Uuid::new_v4();
    self.sessions.insert(id, InferenceSession::new(req.params));
    CommandResponse::ok(InferenceStartData { first_token })
        .with_handle("ai/inference", id, "ai::InferenceSession")
        .into_command_result()
}
```

Cross-cutting fields stop being something handlers know about. They
become free.

# Test plan (9/9 pass)

- `request_parses_flat_params_no_envelope_fields` — pure params,
  envelope fields default to None
- `request_parses_envelope_fields_flat` — handle/sessionId/userId all
  pulled from the same JSON object at top level
- `request_parse_error_carries_diagnostic` — type mismatch surfaces
  as Err with envelope identity (not panic)
- `request_builder_attaches_envelope_fields` — builder API works
- `response_ok_serializes_flat_with_success_true` — happy-path shape,
  handle/error omitted when None
- `response_with_handle_attaches_handle_at_top_level` — handle sits
  alongside flat data fields
- `response_err_serializes_with_success_false_and_message` — failure
  shape with default data preserved
- `response_into_command_result_yields_json_variant` — bridge to the
  ServiceModule return type works
- `round_trip_through_wire_preserves_envelope_fields` — end-to-end:
  handler returns response with handle → serialize → caller builds
  next request using the handle + own session/user → all envelope
  fields survive

# What this PR does NOT do

- Does NOT change `ServiceModule::handle_command` signature. The
  Value-based shape stays for the 300+ existing surface; new
  handlers opt into the typed envelope via `from_value` /
  `into_command_result`.
- Does NOT migrate any existing handler. The envelope is the
  primitive; migrations are individual follow-up PRs.
- Does NOT add a kernel-level handle registry. Each producer manages
  handle lifetimes internally per MODULE-ARCHITECTURE.md §13.1.

# References

- [docs/architecture/MODULE-ARCHITECTURE.md](docs/architecture/MODULE-ARCHITECTURE.md)
  §5.1 (cell return shapes), §13.1 (hot-path cross-module state)
- PR #1485 (cell return shapes — Handle variant + HandleRef)
- PR #1484 (GridInterceptor)
- PR #1483 (CommandInterceptor trait + AircInterceptor stub)
- PR #1482 (architecture doc)

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

* feat(modules): GeneratorModule — recursive bootstrap, manufactures new module scaffolds

Per Joel 2026-05-30: "we developed a generator so we could manufacture
these patterns for new commands modules etc, which itself was a
command. Meta."

The recursive bootstrap from MODULE-ARCHITECTURE.md §10 lands. The
generator IS a module. The things it creates are modules. Every
operation it performs is a command. The system describes itself in
its own terms.

# What this does

`Commands.execute("generate/module", { ... })` scaffolds a compilable
ServiceModule package under
`src/workers/continuum-core/src/modules/<name>/`:

- `mod.rs` — `pub struct <Name>Module {}` with `ServiceModule`
  implemented, the `ModuleConfig` declaring the spec's commands +
  events, and `handle_command` returning typed "not yet implemented"
  errors for each declared command (so the scaffold compiles + the
  author fills in real handlers afterwards).
- `README.md` — author-facing doc capturing the same contract +
  spelling out the manual wire-up step (add `pub mod <name>;` to
  the parent `modules/mod.rs`, register `Arc::new(<Name>Module::new())`
  at runtime startup).

The generated module follows every pattern this session codified:

- `ServiceModule` trait from PR #1471 (the substrate floor)
- `CommandResult` cell shapes from PR #1485
- `CommandRequest<P>` / `CommandResponse<T>` envelopes from PR #1486
  (the generator itself uses these — typed envelope in, typed
  envelope out)
- The architecture from MODULE-ARCHITECTURE.md (PR #1482)

# Why this is the meta move

Every architectural pattern we codified degrades fast if every new
module's author has to re-derive them from the docs. The generator
is the boy-scout amplifier: write the patterns once into the
templates, run `Commands.execute("generate/module", ...)`, get a
module skeleton that already follows them. Subsequent migrations
become "fill in the handler bodies" rather than "re-derive the
shape."

The generator can eventually generate itself (the recursion closes).
This PR ships the v1; future PRs add `generate/command` (add a new
command to an existing module) and `generate/refresh` (re-scan the
modules tree and refresh manifests).

# Implementation surface

Three files under `modules/generator/`:

- **`types.rs`** — `GenerateModuleParams` (name, description, commands,
  events_subscribed, events_published, priority, force) +
  `GenerateModuleResult` (module_path, files_created, next_step) +
  `PrioritySpec` wire enum + `validate_module_name`. All
  serde-friendly, no leak of internal types onto the wire.

- **`templates.rs`** — pure render functions: `mod_rs_template`,
  `readme_template`, and helpers. No I/O lives here; the caller does
  the writes. Keeps the templates testable in isolation and the I/O
  paths easy to swap (e.g., future dry-run mode).

- **`mod.rs`** — `GeneratorModule` (the `ServiceModule` impl) +
  `generate_module_inner` (the actual filesystem work). `handle_command`
  parses a `CommandRequest<GenerateModuleParams>` and materializes a
  `CommandResponse<GenerateModuleResult>` — uses the exact envelope
  pattern PR #1486 introduced, eating its own dogfood.

The module is wired into `modules/mod.rs` as `pub mod generator;` —
the same step the generator instructs callers to perform for the
modules IT scaffolds.

# Tests (21/21 pass)

types.rs (5):
- `validate_accepts_canonical_names` — chat, ai_provider,
  ai-provider, _internal, a1
- `validate_rejects_empty_or_invalid` — empty, capitalized,
  leading-digit, has-space, with-slash
- `priority_spec_round_trips_through_json` — all 4 variants
- `priority_spec_default_is_normal`
- `priority_spec_as_variant_str_matches_rust_enum`

templates.rs (7):
- `mod_rs_contains_struct_definition_and_trait_impl`
- `mod_rs_lists_each_declared_command_in_prefix_and_dispatch`
- `mod_rs_includes_module_name_prefix_in_command_prefixes`
- `mod_rs_subscribes_to_declared_events`
- `mod_rs_documents_published_events_in_module_docstring`
- `mod_rs_for_command_less_module_still_compiles_shape`
- `readme_lists_declared_contract`
- `readme_handles_empty_lists_gracefully`

mod.rs (8):
- `struct_name_handles_hyphens_underscores_and_simple_names`
- `config_advertises_generate_prefix`
- `generate_module_creates_dir_and_files` — full filesystem round-trip
  in a tempdir, asserts struct name + declared commands + ServiceModule
  appear in the generated mod.rs
- `generate_module_refuses_existing_dir_without_force` — fail-loud,
  error names the conflict AND the escape hatch
- `generate_module_overwrites_with_force` — and the second
  generation's description appears in the file
- `generate_module_rejects_invalid_names` — empty / space / slash /
  parent-escape / leading-digit
- `handle_command_returns_typed_envelope` — end-to-end through the
  ServiceModule trait + CommandRequest envelope + CommandResponse
  envelope + the JSON round-trip
- `handle_command_rejects_unknown_command_loud` — error names the bad
  command + what's supported

# What this PR explicitly does NOT do

- Does NOT auto-wire the generated module into the parent
  `modules/mod.rs`. The generator emits the exact line the caller
  needs to add — explicit human step keeps the registration audit
  obvious. A future `generate/refresh` command can do this
  automatically.
- Does NOT generate package.json / manifest.json. The architecture
  doc anticipates these, but the on-disk module structure in
  continuum-core today is "everything compiles into one binary," so
  per-module manifests are a future migration (WASM-component
  modules will need them per MODULE-ARCHITECTURE.md §9).
- Does NOT register `GeneratorModule` at runtime startup. The module
  is reachable via direct construction in tests; production wire-up
  happens in `ipc::start_server` once the typical "register Arc::new"
  pattern is followed (the generator's README spells this out for
  EVERY module it creates, including itself).
- Does NOT implement `generate/command` (add a command to an
  existing module) or `generate/refresh` (re-scan + refresh
  manifests). Both are natural follow-ups; this PR ships the v1.

# References

- [docs/architecture/MODULE-ARCHITECTURE.md](docs/architecture/MODULE-ARCHITECTURE.md)
  §10 (recursive bootstrap), §2 (what a module is)
- PR #1486 (CommandRequest/Response envelopes — used here)
- PR #1485 (cell shapes — used here)
- PR #1483 / #1484 (interceptor chain — orthogonal but composable)
- PR #1482 (architecture doc)

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

* fix(modules/generator): per-name lock serializes concurrent same-name generation + concurrency tests

Per Joel 2026-05-30: "Each persona exists in its own threads."

# Race scenarios the test caught

Original `generate_module_inner`:
```rust
if target_dir.exists() && !params.force {
    return Err("already exists");
}
std::fs::create_dir_all(&target_dir)?;
write_file(mod.rs);
write_file(README.md);
```

Concurrent same-name `generate/module` calls:

1. **Both without force**: BOTH pass the exists() check, BOTH call
   create_dir_all (idempotent → both succeed), BOTH write — and the
   friendly "already exists" error is silenced. With DIFFERENT params,
   last write wins per file → **silent torn state** (mod.rs from
   caller A + README from caller B).

2. **Both with force**: same torn-state hazard — interleaved writes
   produce inconsistent final state.

3. **Different names**: no conflict, should stay fully parallel.

# The fix

`DashMap<String, Arc<std::sync::Mutex<()>>>` keyed by module name.
The per-name mutex is acquired before the exists() check and held
through the writes — same-name concurrent calls serialize; different
names stay parallel via DashMap's per-shard locking.

`std::sync::Mutex` (not `tokio::sync::Mutex`) because the protected
critical section is purely synchronous filesystem I/O — no `.await`
inside the lock. Blocking the tokio worker for the brief mkdir + 2
writes is correct and avoids cascading the API into async. The
critical section is short and generation is rare (humans/AI
scaffolding modules, not the hot path).

Lock entries are never evicted — module names are bounded (no
unbounded stream of unique names) and each entry is ~50 bytes. If
memory ever matters, a TTL scan can be added without changing the
protocol.

# Concurrency stress tests

Every test uses `flavor = "multi_thread", worker_threads = 4` so
spawned tasks actually preempt on distinct OS threads, not
cooperatively interleave on one.

## `same_name_concurrent_generation_without_force_yields_one_winner`

8 racers, same name, no force. Asserts EXACTLY 1 winner, 7 losers,
every loser's error names both the failure mode ("already exists")
AND the escape hatch ("force"). Without the per-name lock, this test
would have shown N winners (silent corruption).

## `same_name_concurrent_generation_with_force_produces_consistent_final_state`

8 racers, same name, force=true. Each caller embeds a unique
`MARKER-NN` in its `description` (which both templates write into
their output). Asserts both files end with the SAME marker — torn
state would show different markers in mod.rs vs README.

## `different_names_concurrent_generation_runs_fully_parallel`

12 racers, all distinct names. Asserts all 12 succeed, each module's
files exist with their own content. Verifies the per-name lock map
holds 12 distinct entries (different DashMap shards → no
contention).

# Tests (24/24 pass — 21 pre-existing + 3 new concurrency)

All pre-existing tests still pass — no regression from the locking
addition. The new tests pin all three cells of the
(same-name × force-flag) matrix plus the different-names parallel
path.

# Substrate doctrine reinforced

This is the SAME pattern that landed in PR #1490 (per-cursor mutex
for data/query-next). The pattern generalizes:

> Every ServiceModule that protects per-resource mutable state
> across an `.await` (tokio::sync::Mutex) OR holds per-resource
> filesystem invariants (std::sync::Mutex) must serialize per
> resource, not module-wide. `DashMap<Id, Arc<Mutex<State>>>` is the
> canonical pattern.

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

---------

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