Repository navigation
feat(runtime): cell return shapes — Handle for long-running stateful work + reserved Stream/Lambda - #1485
Merged
Conversation
…work + reserved Stream/Lambda
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]>
This was referenced May 30, 2026
Merged
Merged
joelteply
added a commit
that referenced
this pull request
May 31, 2026
…els (#1488) `cargo test` regenerates the TS bindings ts-rs declares via `#[ts(export, export_to = ...)]`, but the resulting files only land on canary if the author commits them. PR #1485 merged the Rust cell shapes (`HandleRef`, `StreamPlaceholder`, `LambdaPlaceholder`) but the generated `.ts` files weren't part of the diff — they only existed in my local working tree. That left consumers on canary unable to import `HandleRef` from `@shared/generated/runtime`. This PR adds those three files + reruns `npx tsx generator/generate-rust-bindings.ts` to refresh every barrel in one pass. Runtime and persona barrels both had stale indices from earlier merges that landed `.ts` files but not the `index.ts` updates that re-export them. # Diff scope - `shared/generated/runtime/HandleRef.ts` — new (cell shapes PR #1485) - `shared/generated/runtime/StreamPlaceholder.ts` — new (reserved cell shape per PR #1485) - `shared/generated/runtime/LambdaPlaceholder.ts` — new (reserved cell shape per PR #1485) - `shared/generated/runtime/index.ts` — re-export the three new types + 10 brain_region types that were already on canary as files but absent from the barrel (CadenceHint, ComputeClass, MemoryClass, PersonaLifecycle, PressureLevel, PressureProfile, PressureSignalKind, RegionId, RegionSignal, RegionTelemetry, SleepPhase, TickOutcome) - `shared/generated/persona/index.ts` — re-export `EdgeKind` + `EngramEdge` (already on canary as files; barrel was stale) - `shared/generated/index.ts` — master barrel switched runtime and system from `export *` to explicit lists because `PressureLevel` exists in both. Dedup rule: first seen wins (runtime), callers needing the system variant import it directly from `@shared/generated/system`. Both module lists below verified to cover every `.ts` file currently in their directories. # Why a single fixup rather than per-PR follow-ups The generator's auto-dedup + barrel-refresh runs all-at-once. Doing it once per drifted module would re-trigger the dedup each time and produce noisy diffs that each touch the master barrel. One pass gets the entire `shared/generated/` tree coherent with current Rust state. # Why this gap exists at all `generate-rust-bindings.ts` runs as part of `npm start` prebuild, but the script writes regenerated files to the working tree — it doesn't auto-commit them. If a Rust author lands a PR without first running the generator + committing the TS output, the bindings drift. A future follow-up could add a precommit check that fails loud when `ts-rs` output is dirty after build (similar to other generators). # Verification `npx tsx generator/generate-rust-bindings.ts` produces 535 types, runs to completion in under 10s (cargo cache warm), and emits no errors. The only warnings are the 8 known cross-domain duplicate type names that the generator handles automatically via the explicit-export strategy used here. 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
…ll in Rust) Per Joel: > "Chat is gonna be airc man. So that's extracted period. Chat is of > course a bonafide command though. Do not cheapen it. So the > commands need to be or at least some to start, entirely rust." The split: - **Substrate** (delivery, pub/sub, peers, signing) → airc - **Commands** (chat/send, chat/poll, chat/analyze, chat/export) → Continuum kernel-level ServiceModule, this PR This is the FIRST real module migration from a TS command to a Rust `ServiceModule`. The chat module exercises every pattern the substrate floor PRs established: - `ServiceModule` trait - `CommandResult` cell shapes (PR #1485) - `CommandRequest<P>` / `CommandResponse<T>` envelopes (PR #1486) - Cross-module dispatch via the kernel executor (chat calls `data/query` — neither knows the other beyond the command surface) - Scaffold shape that GeneratorModule (PR #1487) produces - ts-rs typed wire boundary # Scope of THIS PR Only `chat/poll` ships in Rust. The other three commands (`chat/send`, `chat/analyze`, `chat/export`) are wired into the dispatch table as fail-loud stubs that name issue #57 as the migration tracker. Their TS implementations stay live on canary — consumers see no regression. Why staged: `chat/poll` is the cleanest outlier (pure read, no airc, no media side-effects) which lets us validate the cross-module call pattern (chat → data via the kernel executor) without dragging substrate + media into the first migration. Subsequent commands fold in real behavior incrementally. # Module structure ``` src/workers/continuum-core/src/modules/chat/ ├── mod.rs // ChatModule, ServiceModule impl, poll handler └── types.rs // ChatPollParams, ChatPollResult (ts-rs exports) ``` `mod.rs` follows the GeneratorModule template exactly — `pub struct ChatModule`, `impl ServiceModule`, `ModuleConfig` declaring both `chat/` and `collaboration/chat/` prefixes (legacy back-compat), the `handle_command` dispatch arms, the typed envelope pattern. `types.rs` carries `#[derive(TS)]` on both param + result types, exporting to `shared/generated/chat/`. Wire shape: camelCase, optional fields elided when absent. `CHAT_MESSAGES_COLLECTION` constant + `DEFAULT_POLL_LIMIT` constant centralized here. # Cross-module call pattern `chat/poll` doesn't open a database connection — it calls `data/query` via the kernel executor. Chat is blind to which adapter implements the storage; the data module routes per its own resolution rules. This is exactly MODULE-ARCHITECTURE.md §5: commands call commands; modules don't know about each other beyond the command surface. The chat module accepts an optional executor override at construction (`with_executor(...)`) — production uses the kernel-global, tests inject their own. That lets every test in this module spin up a fresh registry with a `StubDataModule` and exercise the full cross-module path without trampling the global `OnceLock`. # Tests (17/17 pass) types.rs (5): - `poll_params_defaults_to_all_none` - `poll_params_round_trip_through_json_with_camel_case` - `poll_params_accepts_missing_fields` - `poll_result_omits_after_message_id_when_none` - `poll_result_includes_after_message_id_when_set` mod.rs (10): - `config_advertises_both_command_prefixes` - `unknown_command_returns_loud_error_naming_supported_commands` - `unmigrated_commands_fail_loud_and_name_followup` (all 6 stub surfaces: chat/send, chat/analyze, chat/export, + collaboration/ prefixed versions) - `poll_returns_empty_result_when_data_module_returns_no_messages` - `poll_without_anchor_queries_data_desc_and_returns_chronological` - `poll_with_room_id_passes_filter_to_data_module` - `poll_with_anchor_looks_up_timestamp_then_filters_gt` - `poll_with_anchor_returns_err_when_anchor_missing` - `handle_command_routes_chat_poll_through_typed_envelope` - `handle_command_accepts_legacy_collaboration_prefix` ts-rs exports (2): - `export_bindings_chatpollparams` - `export_bindings_chatpollresult` # Wire output ``` shared/generated/chat/ ├── ChatPollParams.ts // { roomId?, afterMessageId?, limit? } ├── ChatPollResult.ts // { messages, count, afterMessageId? } └── index.ts // barrel ``` The master barrel (`shared/generated/index.ts`) gains `export * from './chat'`. Other barrel drift (runtime, persona) is PR #1488's territory — left untouched here so the two PRs don't fight over the same lines. # What this PR explicitly does NOT do - Does NOT migrate `chat/send`, `chat/analyze`, `chat/export`. Stubs name issue #57. Each is a future PR. - Does NOT register `ChatModule` at runtime startup. Adding `runtime.register(Arc::new(ChatModule::new()))` in `ipc::start_server` would route ALL `chat/*` traffic through this module — including the stubbed commands which would then break. Registration happens in the same PR that fills in the first real `chat/send` so consumers see one atomic change. Today: chat module exists, is tested, but the legacy TS path still owns every chat command at runtime. - Does NOT do room-name resolution. The kernel command takes an already-resolved `roomId`; name → id stays in TS browser/CLI callsites (or a future `channel/resolve` command). Keeps the kernel command compositional with the future channel module. - Does NOT auto-rebuild the master barrel from outside the chat directory — that drift was already on canary and is PR #1488's job. This PR only adds the `chat` entry. # References - [docs/architecture/MODULE-ARCHITECTURE.md](docs/architecture/MODULE-ARCHITECTURE.md) §5 (composition: commands call commands) - PR #1486 (CommandRequest/Response envelopes — used here) - PR #1487 (GeneratorModule — chat follows its template) - Issue #57 (migration tracker — stubs name it) 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
…ope shape
Per Joel:
> "You can work out the kinks and reinforce patterns by picking good
> example commands which push the envelope, npi"
The hand-rolled string `queryId` pattern in `data/query-open` /
`data/query-next` / `data/query-close` predates HandleRef + the typed
envelope. It's the perfect kink-finding migration target: a REAL
long-running stateful operation that currently passes a stringly-typed
session id around, with no kernel-level typing of the handle's owner,
type, or lifetime.
# What this PR does
1. `data/query-open` now MINTS a `HandleRef { owner: "data", id: Uuid,
type_tag: "data::QueryCursor", created_at_ms }` via
`CommandResponse::with_handle`. Wire shape gains a top-level
`handle` field alongside the legacy `data.queryId` (the SAME UUID
— identity invariant covered by test).
2. `data/query-next` and `data/query-close` accept BOTH shapes via the
typed envelope:
- **new canonical**: `{ handle: HandleRef }` on the
`CommandRequest` envelope
- **legacy back-compat**: `{ queryId: "<uuid-string>" }` flat in
the params body
A single resolver (`resolve_query_cursor_id`) walks the envelope
first, falls back to the legacy field, and fails loud when neither
is present — naming both supported shapes so the caller can
self-correct.
3. The resolver VALIDATES handles aggressively:
- **wrong owner** → typed error naming both the offending owner and
the expected (`data`). The grid interceptor is supposed to route
calls back to the actual owner before dispatch; arriving here
with the wrong owner means either the routing misfired or a
caller hand-crafted a bogus handle.
- **wrong type_tag** → typed error naming both the offending tag
and the expected (`data::QueryCursor`). Within-module
discriminator: a future `data::Migration` handle threaded through
the cursor surface would silently look up nonsense in the
paginated_queries map; we catch it here.
- **unknown handle** → typed error naming the cursor + likely
causes (closed via `query-close`, evicted by future TTL,
previous process instance).
# What this PR explicitly does NOT do
- Does NOT drop the legacy `queryId` field from the open response or
the next/close inputs. The migration is additive; consumers
migrate at their own pace. A follow-up drops `queryId` once every
TS consumer threads the handle.
- Does NOT change the DashMap key type from `String` to `Uuid`. The
HandleRef carries a `Uuid` on the wire; the data module
string-converts at the lookup boundary. Smaller surgery, same
identity semantics.
- Does NOT add envelope plumbing to OTHER data handlers (create,
read, update, delete, query, vector/*). Those are one-shot
operations; they don't need handles. Only long-running stateful
surfaces benefit from HandleRef.
# Kink-finding outcomes (real bugs the migration design caught)
- Empty-params query-next used to deserialize to `query_id: ""`
(required-string field). Now BOTH fields are optional and the empty
case is reachable — without a typed error it would silently
no-op-404. The resolver names both supported shapes in the error.
- Cross-module handle confusion (owner="chat" reaching the data
handler) was previously impossible because there was no handle —
only an opaque string. With typed handles, the validation surface
exists. The test forces it.
- Cross-resource handle confusion (owner="data" but
type_tag="data::Migration") same: the test forces a future failure
mode that the type_tag discriminator was DESIGNED for.
# Patterns reinforced
- **Typed envelope at every typed surface**: every new handler from
here on parses `CommandRequest::<P>::from_value(params)` at the
entry. The cross-cutting `handle` / `sessionId` / `userId` fields
are free.
- **CommandResponse::with_handle for any minted handle**: a single
fluent expression replaces hand-rolling the JSON. Wire shape stays
flat — handle lives at top level, data lives nested or flat
depending on the back-compat needs of the response.
- **Validate the owner AND the type_tag before lookup**: the type
system can't catch a hand-crafted bogus handle; the resolver must.
This pattern goes into every future module that consumes handles.
# Tests (10 new + 8 pre-existing, all 18 pass)
New (`modules::data::tests::`):
- `query_open_returns_handle_alongside_legacy_query_id` — additive
migration: both shapes present
- `query_next_accepts_handle_in_envelope` — new canonical path
- `query_next_still_accepts_legacy_query_id_field` — back-compat
preserved
- `query_next_rejects_handle_with_wrong_owner` — kink
- `query_next_rejects_handle_with_wrong_type_tag` — kink
- `query_next_rejects_when_neither_handle_nor_query_id_provided` —
empty-params surfaces typed error
- `query_next_with_unknown_handle_returns_handle_not_found` — stale
handle typed error
- `query_close_accepts_handle_in_envelope` + after-close stale check
- `query_close_still_accepts_legacy_query_id_field`
- `full_round_trip_open_next_close_via_handles_only` — end-to-end
through the new canonical shape, 12 rows / 3 pages
Pre-existing (untouched, all pass):
- `test_paginated_query` — legacy `queryId` round-trip via the same
path; no regression
- `test_paginated_query_count_exact` — same
# Stacks on
PR #1486 (CommandRequest/Response envelopes — used at every entry +
exit of the migrated handlers).
# References
- [docs/architecture/MODULE-ARCHITECTURE.md](docs/architecture/MODULE-ARCHITECTURE.md)
§10 (recursive bootstrap), §5 (composition)
- PR #1485 (cell shapes — HandleRef used here)
- PR #1486 (envelope pattern — used at every handler surface)
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]>
joelteply
added a commit
that referenced
this pull request
May 31, 2026
…ll in Rust) Per Joel: > "Chat is gonna be airc man. So that's extracted period. Chat is of > course a bonafide command though. Do not cheapen it. So the > commands need to be or at least some to start, entirely rust." The split: - **Substrate** (delivery, pub/sub, peers, signing) → airc - **Commands** (chat/send, chat/poll, chat/analyze, chat/export) → Continuum kernel-level ServiceModule, this PR This is the FIRST real module migration from a TS command to a Rust `ServiceModule`. The chat module exercises every pattern the substrate floor PRs established: - `ServiceModule` trait - `CommandResult` cell shapes (PR #1485) - `CommandRequest<P>` / `CommandResponse<T>` envelopes (PR #1486) - Cross-module dispatch via the kernel executor (chat calls `data/query` — neither knows the other beyond the command surface) - Scaffold shape that GeneratorModule (PR #1487) produces - ts-rs typed wire boundary # Scope of THIS PR Only `chat/poll` ships in Rust. The other three commands (`chat/send`, `chat/analyze`, `chat/export`) are wired into the dispatch table as fail-loud stubs that name issue #57 as the migration tracker. Their TS implementations stay live on canary — consumers see no regression. Why staged: `chat/poll` is the cleanest outlier (pure read, no airc, no media side-effects) which lets us validate the cross-module call pattern (chat → data via the kernel executor) without dragging substrate + media into the first migration. Subsequent commands fold in real behavior incrementally. # Module structure ``` src/workers/continuum-core/src/modules/chat/ ├── mod.rs // ChatModule, ServiceModule impl, poll handler └── types.rs // ChatPollParams, ChatPollResult (ts-rs exports) ``` `mod.rs` follows the GeneratorModule template exactly — `pub struct ChatModule`, `impl ServiceModule`, `ModuleConfig` declaring both `chat/` and `collaboration/chat/` prefixes (legacy back-compat), the `handle_command` dispatch arms, the typed envelope pattern. `types.rs` carries `#[derive(TS)]` on both param + result types, exporting to `shared/generated/chat/`. Wire shape: camelCase, optional fields elided when absent. `CHAT_MESSAGES_COLLECTION` constant + `DEFAULT_POLL_LIMIT` constant centralized here. # Cross-module call pattern `chat/poll` doesn't open a database connection — it calls `data/query` via the kernel executor. Chat is blind to which adapter implements the storage; the data module routes per its own resolution rules. This is exactly MODULE-ARCHITECTURE.md §5: commands call commands; modules don't know about each other beyond the command surface. The chat module accepts an optional executor override at construction (`with_executor(...)`) — production uses the kernel-global, tests inject their own. That lets every test in this module spin up a fresh registry with a `StubDataModule` and exercise the full cross-module path without trampling the global `OnceLock`. # Tests (17/17 pass) types.rs (5): - `poll_params_defaults_to_all_none` - `poll_params_round_trip_through_json_with_camel_case` - `poll_params_accepts_missing_fields` - `poll_result_omits_after_message_id_when_none` - `poll_result_includes_after_message_id_when_set` mod.rs (10): - `config_advertises_both_command_prefixes` - `unknown_command_returns_loud_error_naming_supported_commands` - `unmigrated_commands_fail_loud_and_name_followup` (all 6 stub surfaces: chat/send, chat/analyze, chat/export, + collaboration/ prefixed versions) - `poll_returns_empty_result_when_data_module_returns_no_messages` - `poll_without_anchor_queries_data_desc_and_returns_chronological` - `poll_with_room_id_passes_filter_to_data_module` - `poll_with_anchor_looks_up_timestamp_then_filters_gt` - `poll_with_anchor_returns_err_when_anchor_missing` - `handle_command_routes_chat_poll_through_typed_envelope` - `handle_command_accepts_legacy_collaboration_prefix` ts-rs exports (2): - `export_bindings_chatpollparams` - `export_bindings_chatpollresult` # Wire output ``` shared/generated/chat/ ├── ChatPollParams.ts // { roomId?, afterMessageId?, limit? } ├── ChatPollResult.ts // { messages, count, afterMessageId? } └── index.ts // barrel ``` The master barrel (`shared/generated/index.ts`) gains `export * from './chat'`. Other barrel drift (runtime, persona) is PR #1488's territory — left untouched here so the two PRs don't fight over the same lines. # What this PR explicitly does NOT do - Does NOT migrate `chat/send`, `chat/analyze`, `chat/export`. Stubs name issue #57. Each is a future PR. - Does NOT register `ChatModule` at runtime startup. Adding `runtime.register(Arc::new(ChatModule::new()))` in `ipc::start_server` would route ALL `chat/*` traffic through this module — including the stubbed commands which would then break. Registration happens in the same PR that fills in the first real `chat/send` so consumers see one atomic change. Today: chat module exists, is tested, but the legacy TS path still owns every chat command at runtime. - Does NOT do room-name resolution. The kernel command takes an already-resolved `roomId`; name → id stays in TS browser/CLI callsites (or a future `channel/resolve` command). Keeps the kernel command compositional with the future channel module. - Does NOT auto-rebuild the master barrel from outside the chat directory — that drift was already on canary and is PR #1488's job. This PR only adds the `chat` entry. # References - [docs/architecture/MODULE-ARCHITECTURE.md](docs/architecture/MODULE-ARCHITECTURE.md) §5 (composition: commands call commands) - PR #1486 (CommandRequest/Response envelopes — used here) - PR #1487 (GeneratorModule — chat follows its template) - Issue #57 (migration tracker — stubs name it) Co-Authored-By: Claude Opus 4.7 <[email protected]>
joelteply
added a commit
that referenced
this pull request
May 31, 2026
…t (first dual-write composition) (#1489) * feat(modules): ChatModule — first proof-of-pattern migration (chat/poll in Rust) Per Joel: > "Chat is gonna be airc man. So that's extracted period. Chat is of > course a bonafide command though. Do not cheapen it. So the > commands need to be or at least some to start, entirely rust." The split: - **Substrate** (delivery, pub/sub, peers, signing) → airc - **Commands** (chat/send, chat/poll, chat/analyze, chat/export) → Continuum kernel-level ServiceModule, this PR This is the FIRST real module migration from a TS command to a Rust `ServiceModule`. The chat module exercises every pattern the substrate floor PRs established: - `ServiceModule` trait - `CommandResult` cell shapes (PR #1485) - `CommandRequest<P>` / `CommandResponse<T>` envelopes (PR #1486) - Cross-module dispatch via the kernel executor (chat calls `data/query` — neither knows the other beyond the command surface) - Scaffold shape that GeneratorModule (PR #1487) produces - ts-rs typed wire boundary # Scope of THIS PR Only `chat/poll` ships in Rust. The other three commands (`chat/send`, `chat/analyze`, `chat/export`) are wired into the dispatch table as fail-loud stubs that name issue #57 as the migration tracker. Their TS implementations stay live on canary — consumers see no regression. Why staged: `chat/poll` is the cleanest outlier (pure read, no airc, no media side-effects) which lets us validate the cross-module call pattern (chat → data via the kernel executor) without dragging substrate + media into the first migration. Subsequent commands fold in real behavior incrementally. # Module structure ``` src/workers/continuum-core/src/modules/chat/ ├── mod.rs // ChatModule, ServiceModule impl, poll handler └── types.rs // ChatPollParams, ChatPollResult (ts-rs exports) ``` `mod.rs` follows the GeneratorModule template exactly — `pub struct ChatModule`, `impl ServiceModule`, `ModuleConfig` declaring both `chat/` and `collaboration/chat/` prefixes (legacy back-compat), the `handle_command` dispatch arms, the typed envelope pattern. `types.rs` carries `#[derive(TS)]` on both param + result types, exporting to `shared/generated/chat/`. Wire shape: camelCase, optional fields elided when absent. `CHAT_MESSAGES_COLLECTION` constant + `DEFAULT_POLL_LIMIT` constant centralized here. # Cross-module call pattern `chat/poll` doesn't open a database connection — it calls `data/query` via the kernel executor. Chat is blind to which adapter implements the storage; the data module routes per its own resolution rules. This is exactly MODULE-ARCHITECTURE.md §5: commands call commands; modules don't know about each other beyond the command surface. The chat module accepts an optional executor override at construction (`with_executor(...)`) — production uses the kernel-global, tests inject their own. That lets every test in this module spin up a fresh registry with a `StubDataModule` and exercise the full cross-module path without trampling the global `OnceLock`. # Tests (17/17 pass) types.rs (5): - `poll_params_defaults_to_all_none` - `poll_params_round_trip_through_json_with_camel_case` - `poll_params_accepts_missing_fields` - `poll_result_omits_after_message_id_when_none` - `poll_result_includes_after_message_id_when_set` mod.rs (10): - `config_advertises_both_command_prefixes` - `unknown_command_returns_loud_error_naming_supported_commands` - `unmigrated_commands_fail_loud_and_name_followup` (all 6 stub surfaces: chat/send, chat/analyze, chat/export, + collaboration/ prefixed versions) - `poll_returns_empty_result_when_data_module_returns_no_messages` - `poll_without_anchor_queries_data_desc_and_returns_chronological` - `poll_with_room_id_passes_filter_to_data_module` - `poll_with_anchor_looks_up_timestamp_then_filters_gt` - `poll_with_anchor_returns_err_when_anchor_missing` - `handle_command_routes_chat_poll_through_typed_envelope` - `handle_command_accepts_legacy_collaboration_prefix` ts-rs exports (2): - `export_bindings_chatpollparams` - `export_bindings_chatpollresult` # Wire output ``` shared/generated/chat/ ├── ChatPollParams.ts // { roomId?, afterMessageId?, limit? } ├── ChatPollResult.ts // { messages, count, afterMessageId? } └── index.ts // barrel ``` The master barrel (`shared/generated/index.ts`) gains `export * from './chat'`. Other barrel drift (runtime, persona) is PR #1488's territory — left untouched here so the two PRs don't fight over the same lines. # What this PR explicitly does NOT do - Does NOT migrate `chat/send`, `chat/analyze`, `chat/export`. Stubs name issue #57. Each is a future PR. - Does NOT register `ChatModule` at runtime startup. Adding `runtime.register(Arc::new(ChatModule::new()))` in `ipc::start_server` would route ALL `chat/*` traffic through this module — including the stubbed commands which would then break. Registration happens in the same PR that fills in the first real `chat/send` so consumers see one atomic change. Today: chat module exists, is tested, but the legacy TS path still owns every chat command at runtime. - Does NOT do room-name resolution. The kernel command takes an already-resolved `roomId`; name → id stays in TS browser/CLI callsites (or a future `channel/resolve` command). Keeps the kernel command compositional with the future channel module. - Does NOT auto-rebuild the master barrel from outside the chat directory — that drift was already on canary and is PR #1488's job. This PR only adds the `chat` entry. # References - [docs/architecture/MODULE-ARCHITECTURE.md](docs/architecture/MODULE-ARCHITECTURE.md) §5 (composition: commands call commands) - PR #1486 (CommandRequest/Response envelopes — used here) - PR #1487 (GeneratorModule — chat follows its template) - Issue #57 (migration tracker — stubs name it) Co-Authored-By: Claude Opus 4.7 <[email protected]> * feat(modules/chat): chat/send migrates to Rust — first dual-write composition handler Per Joel: > "Yes please do." (re: chat/send next, the dual-write composition > stress-test) chat/send is the chat module's first multi-cross-module-call handler: chat → data (persist) then chat → airc (publish). The migration forces the substrate to commit on partial-failure semantics that the single-call handlers (chat/poll, data/query cursors) never had to face. # Why this PR pushes the envelope Two effects across two modules with no kernel-level transaction: | data | airc | handler returns | |------|------|----------------------------------------------------------| | ok | ok | `Ok(result with message_id + event_id)` | | ok | fail | `Ok(result with message_id, event_id=None, warning=...)` | | fail | — | `Err(...)` — no airc publish attempted | The (ok, fail) cell is the substrate-shaped kink the design needed proof of. An airc-only failure is NOT command-level failure: the message IS in the local store, consumers see it via chat/poll, a future retry/sync mechanism heals the broadcast. Surfacing this as `Err` would tell the caller "your write didn't happen" — which is wrong; half of the write did. The `warning` field is the right shape: **degraded success**. # Design decisions this PR locks in ## Ordering: data first, airc second Local persistence is the ground truth. The reverse order would risk publishing a message to peers that this node doesn't know about — a peer reading back that message would find no local record. With data-first, the worst case is *we have the message but peers don't* — a degradation, not a divergence. A test (`send_calls_data_before_airc`) pins the order via a shared call-log Mutex. If the ordering ever flips, the bad-divergence case becomes reachable; the test catches it. ## airc-fail returns Ok+warning, not Err The `warning` field names the failing surface, surfaces the underlying error (so callers can diagnose), confirms the message wasn't lost ("stored locally"), and includes the message id (so callers can correlate logs). Tested: - `send_with_airc_failure_returns_warning_and_null_event_id` ## data-fail short-circuits — airc NEVER called A test tracks airc invocations via `AtomicUsize` and asserts ZERO calls when data failed. Same invariant for the subtle data-returns-success=false path: - `send_with_data_executor_failure_propagates_as_err_and_skips_airc` - `send_with_data_success_false_propagates_as_err_and_skips_airc` ## Wire contracts pinned by tests, not just docs Two tests pin the on-the-wire shape chat hands to data + airc. If either downstream module changes its parse expectations, these tests catch the drift even though chat doesn't import their typed structs (coupling lives at the command/wire surface, not at the Rust type level — the substrate's whole point): - `send_writes_chat_messages_collection_with_canonical_entity_shape` → pins ChatMessageEntity layout (id/roomId/senderId/timestamp/ content/replyToId/metadata.source/status, ISO-8601 UTC timestamps) - `send_envelope_matches_airc_publish_wire_shape` → pins AircRealtimeEnvelope layout (eventId/roomId/sourceId/ createdAtMs/delivery, tagged payload variant with schema=chat_transcript and inline message data) # What this PR explicitly does NOT do - **Does NOT migrate** chat/analyze or chat/export (still fail-loud stubs naming issue #57). - **Does NOT register `ChatModule` at runtime startup.** Same reasoning as #1489 — until ALL chat commands are migrated, registration would break the remaining stubs at runtime. - **Does NOT do sender/room name resolution.** Kernel command takes pre-resolved UUIDs; resolution stays in TS browser/CLI (or a future channel/resolve + user/resolve pair). Same compositional principle chat/poll established. - **Does NOT externalize media.** Text-only for this migration; media paths (base64 → blob storage via MediaBlobService) are their own kink-finder. - **Does NOT do vision pre-warming.** Fire-and-forget visual descriptor generation is deferred to vision-module migration. - **Does NOT thread reply-to into threading metadata fully.** The `replyToId` field flows through to the stored entity + the airc payload, but the richer thread { threadId, replyCount, lastReplyAt } shape is deferred until the thread-tracking design is its own scope. - **Does NOT solve idempotency.** A retried chat/send (network glitch on the caller side) currently produces two stored messages — matches today's TS behavior. Future PR can add a `client_dedup_id` param + TTL'd dedup map; the substrate is ready for it but the design is its own scope. # Substrate kinks this PR surfaced (For potential future refinement — none blocking, all annotated): 1. **No envelope construction helpers for cross-module calls.** Chat hand-rolls `json!({ "envelope": {...} })` for airc. If many modules call airc/realtime-publish from Rust, an `airc::realtime_publish_envelope(builder...) -> Value` helper in the airc-shared module would distill this. Out of scope here; flag for if a second consumer appears. 2. **No typed cross-module command call.** Chat calls `executor.execute_json("data/create", json!({...}))` with raw JSON and parses the response back via `.get("success")`. A typed `executor.execute_typed::<DataCreateParams, DataCreateResult>(...)` would catch wire-shape drift at compile time. Same kink the handle_id_or_legacy refinement (#1491) solved for a different surface — flag for potential future refinement after we see if it reappears with a second consumer. 3. **No transaction primitive across modules.** Today: chat hand-codes the data-first / airc-best-effort ordering inline. If many modules need similar dual-write composition, a substrate-level `dual_write!(primary => ..., best_effort => ...)` macro could centralize the partial-failure pattern (warning construction, ordering enforcement, etc.). Flag for if/when a second consumer appears. # Tests (28/28 pass) Pre-existing chat/poll (17, all unchanged behavior): - StubDataModule extended to dispatch by command — back-compat `query_only` constructor preserves chat/poll's existing tests verbatim - All 17 chat/poll tests still pass through the refactored stub New chat/send (11): - `send_happy_path_returns_message_id_and_event_id` - `send_with_airc_failure_returns_warning_and_null_event_id` ← partial-failure cell - `send_with_data_executor_failure_propagates_as_err_and_skips_airc` ← hard-failure + ordering invariant - `send_with_data_success_false_propagates_as_err_and_skips_airc` ← the subtle data-success-false path - `send_calls_data_before_airc` ← ordering invariant via call log - `send_writes_chat_messages_collection_with_canonical_entity_shape` ← wire contract to data - `send_envelope_matches_airc_publish_wire_shape` ← wire contract to airc - `handle_command_routes_chat_send_through_typed_envelope` ← typed envelope round-trip end-to-end - `handle_command_chat_send_accepts_legacy_collaboration_prefix` ← back-compat - `unmigrated_commands_fail_loud_and_name_followup` (updated to exclude chat/send now that it's migrated) ts-rs bindings (2): - `export_bindings_chatsendparams` - `export_bindings_chatsendresult` # Wire output ``` shared/generated/chat/ ├── ChatPollParams.ts ├── ChatPollResult.ts ├── ChatSendParams.ts // { roomId, senderId, text, replyToId? } ├── ChatSendResult.ts // { messageId, eventId?, warning? } └── index.ts ``` # References - [docs/architecture/MODULE-ARCHITECTURE.md](docs/architecture/MODULE-ARCHITECTURE.md) §5 (composition: commands call commands) - PR #1489 (ChatModule + chat/poll — the first migration) - PR #1490 (data/query cursors — single-call HandleRef stress test) - PR #1491 (substrate refinements distilled from #1490) - Issue #57 (migration tracker) - Issue #64 (this migration) Co-Authored-By: Claude Opus 4.7 <[email protected]> * test(modules/chat): concurrency stress tests — multi-persona invariants pinned Per Joel 2026-05-30: "Each persona exists in its own threads." The kernel registers ONE ChatModule instance; every persona's thread invokes its `&self` methods concurrently against the same executor. The substrate is designed to be safe under that load — but until now no test PROVED it. Single-threaded `#[tokio::test]` runs serialize even genuinely racy code and would pass a substrate with a data race. This commit adds 4 concurrency stress tests pinning the invariants the dual-write / single-call composition designs depend on. Every test uses `flavor = "multi_thread", worker_threads = 4` so tasks actually preempt each other on distinct OS threads rather than cooperatively interleaving on one. # What's pinned 1. **`send_under_concurrent_load_stores_all_messages_with_distinct_ids`** 50 concurrent personas all call `chat/send` through the same ChatModule. Asserts: every send completes, every send writes exactly once, every returned `message_id` is distinct (no UUID collision, no shared mutable state holding the id), and the SET of stored ids equals the SET of returned ids (no lost writes, no phantom writes). 2. **`send_preserves_per_call_ordering_under_concurrent_load`** 25 concurrent sends interleave globally — but per-call `data/create` MUST still precede per-call `airc/realtime-publish`. The dual-write design's bad-divergence safety net (peers don't see a message the node hasn't stored) depends on this invariant holding under load. Tagging each observation with its `message_id` lets the test reconstruct per-call timelines from the interleaved global log. 3. **`send_isolates_mixed_outcomes_under_concurrent_load`** 30 concurrent sends with half airc-failing (text flag tells the stub to fail). Each call's `warning` must reference THIS call's `message_id`, not a concurrent sibling's. Cross-contamination between concurrent results would mean shared mutable state in the handler — this catches it. 4. **`poll_isolates_results_under_concurrent_load`** 30 concurrent `chat/poll` calls each polling a DIFFERENT room. The stub echoes the requested `roomId` in the synthetic result; the test asserts every task receives ITS OWN room's result. Catches result-swap bugs that would never appear single-threaded. # Why this discipline matters Concurrency tests aren't exercising rare paths — they're the production scenario. A test suite full of single-threaded `#[tokio::test]`s can sign off on a substrate that silently miscomputes under multi-persona load. Pinning the invariants here means the next refactor (e.g., adding a `dual_write!` macro or typed cross-module command call) is held to the same bar. The pattern goes into every future module that consumes the kernel: when you add a new handler that touches shared state, add a matching concurrency stress test. # Tests (23/23 pass — 19 pre-existing + 4 new concurrency) All previously-passing tests still pass. The new ones use real multi-threaded tokio runtime + `Arc<Mutex>` + atomic tracking to observe interleavings the substrate must handle. 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
May 31, 2026
…utex (re-opens #1490) (#1497) * feat(modules/data): query cursors mint typed HandleRef + accept envelope shape Per Joel: > "You can work out the kinks and reinforce patterns by picking good > example commands which push the envelope, npi" The hand-rolled string `queryId` pattern in `data/query-open` / `data/query-next` / `data/query-close` predates HandleRef + the typed envelope. It's the perfect kink-finding migration target: a REAL long-running stateful operation that currently passes a stringly-typed session id around, with no kernel-level typing of the handle's owner, type, or lifetime. # What this PR does 1. `data/query-open` now MINTS a `HandleRef { owner: "data", id: Uuid, type_tag: "data::QueryCursor", created_at_ms }` via `CommandResponse::with_handle`. Wire shape gains a top-level `handle` field alongside the legacy `data.queryId` (the SAME UUID — identity invariant covered by test). 2. `data/query-next` and `data/query-close` accept BOTH shapes via the typed envelope: - **new canonical**: `{ handle: HandleRef }` on the `CommandRequest` envelope - **legacy back-compat**: `{ queryId: "<uuid-string>" }` flat in the params body A single resolver (`resolve_query_cursor_id`) walks the envelope first, falls back to the legacy field, and fails loud when neither is present — naming both supported shapes so the caller can self-correct. 3. The resolver VALIDATES handles aggressively: - **wrong owner** → typed error naming both the offending owner and the expected (`data`). The grid interceptor is supposed to route calls back to the actual owner before dispatch; arriving here with the wrong owner means either the routing misfired or a caller hand-crafted a bogus handle. - **wrong type_tag** → typed error naming both the offending tag and the expected (`data::QueryCursor`). Within-module discriminator: a future `data::Migration` handle threaded through the cursor surface would silently look up nonsense in the paginated_queries map; we catch it here. - **unknown handle** → typed error naming the cursor + likely causes (closed via `query-close`, evicted by future TTL, previous process instance). # What this PR explicitly does NOT do - Does NOT drop the legacy `queryId` field from the open response or the next/close inputs. The migration is additive; consumers migrate at their own pace. A follow-up drops `queryId` once every TS consumer threads the handle. - Does NOT change the DashMap key type from `String` to `Uuid`. The HandleRef carries a `Uuid` on the wire; the data module string-converts at the lookup boundary. Smaller surgery, same identity semantics. - Does NOT add envelope plumbing to OTHER data handlers (create, read, update, delete, query, vector/*). Those are one-shot operations; they don't need handles. Only long-running stateful surfaces benefit from HandleRef. # Kink-finding outcomes (real bugs the migration design caught) - Empty-params query-next used to deserialize to `query_id: ""` (required-string field). Now BOTH fields are optional and the empty case is reachable — without a typed error it would silently no-op-404. The resolver names both supported shapes in the error. - Cross-module handle confusion (owner="chat" reaching the data handler) was previously impossible because there was no handle — only an opaque string. With typed handles, the validation surface exists. The test forces it. - Cross-resource handle confusion (owner="data" but type_tag="data::Migration") same: the test forces a future failure mode that the type_tag discriminator was DESIGNED for. # Patterns reinforced - **Typed envelope at every typed surface**: every new handler from here on parses `CommandRequest::<P>::from_value(params)` at the entry. The cross-cutting `handle` / `sessionId` / `userId` fields are free. - **CommandResponse::with_handle for any minted handle**: a single fluent expression replaces hand-rolling the JSON. Wire shape stays flat — handle lives at top level, data lives nested or flat depending on the back-compat needs of the response. - **Validate the owner AND the type_tag before lookup**: the type system can't catch a hand-crafted bogus handle; the resolver must. This pattern goes into every future module that consumes handles. # Tests (10 new + 8 pre-existing, all 18 pass) New (`modules::data::tests::`): - `query_open_returns_handle_alongside_legacy_query_id` — additive migration: both shapes present - `query_next_accepts_handle_in_envelope` — new canonical path - `query_next_still_accepts_legacy_query_id_field` — back-compat preserved - `query_next_rejects_handle_with_wrong_owner` — kink - `query_next_rejects_handle_with_wrong_type_tag` — kink - `query_next_rejects_when_neither_handle_nor_query_id_provided` — empty-params surfaces typed error - `query_next_with_unknown_handle_returns_handle_not_found` — stale handle typed error - `query_close_accepts_handle_in_envelope` + after-close stale check - `query_close_still_accepts_legacy_query_id_field` - `full_round_trip_open_next_close_via_handles_only` — end-to-end through the new canonical shape, 12 rows / 3 pages Pre-existing (untouched, all pass): - `test_paginated_query` — legacy `queryId` round-trip via the same path; no regression - `test_paginated_query_count_exact` — same # Stacks on PR #1486 (CommandRequest/Response envelopes — used at every entry + exit of the migrated handlers). # References - [docs/architecture/MODULE-ARCHITECTURE.md](docs/architecture/MODULE-ARCHITECTURE.md) §10 (recursive bootstrap), §5 (composition) - PR #1485 (cell shapes — HandleRef used here) - PR #1486 (envelope pattern — used at every handler surface) Co-Authored-By: Claude Opus 4.7 <[email protected]> * fix(modules/data): per-cursor mutex serializes concurrent query-next + concurrency tests pin it Per Joel 2026-05-30: "Each persona exists in its own threads." # The bug the concurrency test caught Original `handle_query_next` pattern: ```rust let state_info = self.paginated_queries.get(&cursor_id).map(|s| (s.current_page, ...)); // ^ DashMap shard lock released HERE // ... async adapter.query() runs with NO lock ... self.paginated_queries.get_mut(&cursor_id).map(|mut s| s.current_page += 1); ``` Under N concurrent next-calls on the SAME cursor (canonical multi-persona scenario, or one persona retrying), every call reads `current_page=0`, every call computes the same offset, every call queries the same first page, every call writes `current_page=1`. Result: 8 concurrent calls all return pageNumber=1; the cursor's final state is current_page=1 instead of current_page=8. The new `same_cursor_concurrent_next_does_not_corrupt_state` test caught this with the assertion *"page 1 served 8 times — the cursor advanced through it MORE than once, indicating a lost serialization"*. The fix landed in the same commit. # The fix Wrap each cursor's state in a `tokio::sync::Mutex` held across the async query. Concurrent next-calls on the SAME cursor serialize (the substrate's promise: page numbering stays monotone). Concurrent next-calls on DIFFERENT cursors stay fully parallel because each cursor has its OWN mutex — DashMap's lock-free read path is preserved. ```rust paginated_queries: DashMap<String, Arc<tokio::sync::Mutex<PaginatedQueryState>>> ``` `handle_query_next`: 1. Clone the `Arc<Mutex>` OUT of the DashMap shard (brief read lock, no contention) 2. `lock().await` the per-cursor mutex 3. Snapshot the read-only fields needed for the query into locals 4. Run the adapter query (mutex held — only ONE caller advances at a time) 5. Update state on the still-held lock (atomic with the read) `handle_query_close` unchanged: `DashMap.remove()` is atomic; if a concurrent next is mid-flight, it holds an Arc keeping the Mutex alive — its mutation succeeds against an orphaned state map that's never read again. From the caller's view: close said success; in-flight next returns its now-meaningless page; the cursor is unreachable for subsequent calls. Benign and arguably the correct contract — callers shouldn't race close with next. # Substrate doctrine reinforced Joel's reminder is doctrine, not just a one-off bug fix. Every ServiceModule that holds per-resource mutable state across an `.await` MUST hold a per-resource lock for the read-then-async- then-write window. Module-wide locks are wrong (serialize all resources). Per-resource locks via `DashMap<Id, Arc<Mutex<State>>>` are the canonical pattern. # Concurrency stress tests Both run with `flavor = "multi_thread", worker_threads = 4` so tasks actually preempt each other on distinct OS threads. ## `cursors_are_isolated_under_concurrent_open_and_next` (20 personas) Phase 1: 20 concurrent `query-open` calls. Asserts all 20 cursors mint DISTINCT HandleRef.id UUIDs. Phase 2: 20 concurrent `query-next` calls, each against its own cursor. Asserts each cursor's first page returns pageSize items and pageNumber=1 (per-cursor state, not shared). Phase 3: close half the cursors in parallel; assert the OTHER half STILL serves page 2 correctly. Close MUST be per-cursor — sibling state untouched. ## `same_cursor_concurrent_next_does_not_corrupt_state` (8 callers, 1 cursor) 30 rows, pageSize 5 → 6 valid pages. Fire 8 concurrent `query-next` calls against the SAME cursor handle. Asserts each non-tail page (1..=5) is served AT MOST ONCE — the per-cursor mutex serialized the advance. Without the fix, page 1 was served 8 times. # Tests (20/20 pass; 1 ignored onnxruntime) All 10 pre-existing HandleRef migration tests still pass — no regression from the locking restructure. The 2 new concurrency tests pin the invariants going forward. 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
May 31, 2026
…id_or_legacy Per Joel: > "You get to refine the pattern with better knowledge, therefore > improving elegance and reliability" Distill two primitives from the kinks the first real HandleRef consumer (PR #1490) had to handle inline, so every future consumer reaches for the substrate rather than reimplementing them. # The primitives ## HandleRef::expect_owned_by(owner, type_tag) -> Result<Uuid, String> The canonical handle-validation entry point. Returns the inner UUID when both the owner and type_tag match expectations; otherwise emits typed errors that name BOTH the offending value AND the expected value. Owner-mismatch is checked first (owner determines routing) and the error explicitly hints at the grid-interceptor responsibility — the diagnostic turns "weird error" into "ah, the interceptor misfired" or "ah, this caller built a bogus handle." Replaces ~12 lines of validation boilerplate per handle-consuming handler. Standardizes the error format across every module that uses handles. ## CommandRequest::handle_id_or_legacy(...) The single primitive shared by every additive migration of a stringly-typed id to a typed HandleRef. Walks two shapes: 1. envelope `handle` (new canonical) — validated via expect_owned_by, error prefixed with the command name 2. legacy string field on the params (back-compat) 3. neither → typed error naming BOTH supported shapes so the caller knows what to add Returns the resolved id as a String — the historical wire format every consumer's state map is already keyed on. New modules that key state by Uuid natively can `Uuid::parse_str` the result; legacy-only strings parse-fail there, which is fine because handle-only consumers post-migration don't have a legacy field to fall back to. Replaces ~25 lines of bespoke resolver per migration. Standardizes the error format across every dual-shape migration. # The consumer-side win (data.rs) Before (35-line `resolve_query_cursor_id` static fn + two callsites that each invoked it): ```rust fn resolve_query_cursor_id(handle, legacy, command) -> Result<...> { if let Some(h) = handle { if h.owner != DATA_MODULE_OWNER { return Err(...); } // 6 lines if h.type_tag != QUERY_CURSOR_TYPE_TAG { return Err(...); } // 6 lines return Ok(h.id.to_string()); } if let Some(id) = legacy { return Ok(id.clone()); } Err(format!("...")) // 4 lines } // Plus the two callsites: Self::resolve_query_cursor_id(...) ``` After (the static fn is gone; callsites invoke the substrate primitive directly): ```rust let cursor_id = req.handle_id_or_legacy( DATA_MODULE_OWNER, QUERY_CURSOR_TYPE_TAG, "queryId", &req.params.query_id, "data/query-next", )?; ``` Net: -84 lines from data.rs. The 411-line substrate addition is all either documentation, tested primitives, or new substrate-level tests — every future handle consumer benefits from this shrink, not just data. # Tests (48 pass, 1 ignored — onnxruntime, unrelated) ## New (runtime::cell_shapes::tests, 5) - `expect_owned_by_returns_uuid_when_owner_and_type_match` — happy path - `expect_owned_by_rejects_wrong_owner_with_both_values_named` - `expect_owned_by_rejects_wrong_type_tag_with_both_values_named` - `expect_owned_by_checks_owner_first_then_type` — pins routing-first precedence (owner before type) - `expect_owned_by_error_includes_routing_hint` — pins the grid-interceptor diagnostic in the owner-mismatch error ## New (runtime::command_envelope::tests, 6) - `handle_id_or_legacy_prefers_envelope_handle_when_both_present` — precedence (envelope wins) so consumers mid-migration don't diverge from new consumers about which id the resolver sees - `handle_id_or_legacy_falls_back_to_legacy_string_when_no_handle` - `handle_id_or_legacy_errors_loud_when_neither_shape_provided` - `handle_id_or_legacy_prepends_command_name_to_handle_validation_errors` - `handle_id_or_legacy_propagates_type_mismatch_with_command_name` - `handle_id_or_legacy_uses_canonical_uuid_string_for_handle_path` — pins the bridge-format invariant: handle-path and legacy-path resolve to the SAME string representation ## Pre-existing (modules::data::tests, all 17 still pass) The 10 HandleRef migration tests + 7 pre-existing cursor tests exercise the SAME behavior they did before through the refactored callsites. No regression — net effect is the substrate now owns what data.rs used to own inline. # What this PR explicitly does NOT do - Does NOT add convenience constructors like `CommandResponse::with_handle_minted` (auto-generate UUID). That case is one line (`Uuid::new_v4()` then `with_handle(...)`); the primitive doesn't justify the API surface. - Does NOT add a `handle_type!(QueryCursor)` macro that derives the type_tag string from the module + struct name at compile time. Worth considering, but the doc-convention `const QUERY_CURSOR_TYPE_TAG = "data::QueryCursor"` pattern is already cheap and explicit. - Does NOT touch other handle-related types (Stream, Lambda placeholders). Those are reserved-but-unused; their kinks will surface when they get real consumers. # References - PR #1485 (cell shapes — HandleRef defined here, extended here) - PR #1486 (envelope pattern — CommandRequest defined here, extended here) - PR #1490 (first real HandleRef consumer — the inline boilerplate this PR distills lived there) Co-Authored-By: Claude Opus 4.7 <[email protected]>
joelteply
added a commit
that referenced
this pull request
May 31, 2026
…id_or_legacy (#1498) Per Joel: > "You get to refine the pattern with better knowledge, therefore > improving elegance and reliability" Distill two primitives from the kinks the first real HandleRef consumer (PR #1490) had to handle inline, so every future consumer reaches for the substrate rather than reimplementing them. # The primitives ## HandleRef::expect_owned_by(owner, type_tag) -> Result<Uuid, String> The canonical handle-validation entry point. Returns the inner UUID when both the owner and type_tag match expectations; otherwise emits typed errors that name BOTH the offending value AND the expected value. Owner-mismatch is checked first (owner determines routing) and the error explicitly hints at the grid-interceptor responsibility — the diagnostic turns "weird error" into "ah, the interceptor misfired" or "ah, this caller built a bogus handle." Replaces ~12 lines of validation boilerplate per handle-consuming handler. Standardizes the error format across every module that uses handles. ## CommandRequest::handle_id_or_legacy(...) The single primitive shared by every additive migration of a stringly-typed id to a typed HandleRef. Walks two shapes: 1. envelope `handle` (new canonical) — validated via expect_owned_by, error prefixed with the command name 2. legacy string field on the params (back-compat) 3. neither → typed error naming BOTH supported shapes so the caller knows what to add Returns the resolved id as a String — the historical wire format every consumer's state map is already keyed on. New modules that key state by Uuid natively can `Uuid::parse_str` the result; legacy-only strings parse-fail there, which is fine because handle-only consumers post-migration don't have a legacy field to fall back to. Replaces ~25 lines of bespoke resolver per migration. Standardizes the error format across every dual-shape migration. # The consumer-side win (data.rs) Before (35-line `resolve_query_cursor_id` static fn + two callsites that each invoked it): ```rust fn resolve_query_cursor_id(handle, legacy, command) -> Result<...> { if let Some(h) = handle { if h.owner != DATA_MODULE_OWNER { return Err(...); } // 6 lines if h.type_tag != QUERY_CURSOR_TYPE_TAG { return Err(...); } // 6 lines return Ok(h.id.to_string()); } if let Some(id) = legacy { return Ok(id.clone()); } Err(format!("...")) // 4 lines } // Plus the two callsites: Self::resolve_query_cursor_id(...) ``` After (the static fn is gone; callsites invoke the substrate primitive directly): ```rust let cursor_id = req.handle_id_or_legacy( DATA_MODULE_OWNER, QUERY_CURSOR_TYPE_TAG, "queryId", &req.params.query_id, "data/query-next", )?; ``` Net: -84 lines from data.rs. The 411-line substrate addition is all either documentation, tested primitives, or new substrate-level tests — every future handle consumer benefits from this shrink, not just data. # Tests (48 pass, 1 ignored — onnxruntime, unrelated) ## New (runtime::cell_shapes::tests, 5) - `expect_owned_by_returns_uuid_when_owner_and_type_match` — happy path - `expect_owned_by_rejects_wrong_owner_with_both_values_named` - `expect_owned_by_rejects_wrong_type_tag_with_both_values_named` - `expect_owned_by_checks_owner_first_then_type` — pins routing-first precedence (owner before type) - `expect_owned_by_error_includes_routing_hint` — pins the grid-interceptor diagnostic in the owner-mismatch error ## New (runtime::command_envelope::tests, 6) - `handle_id_or_legacy_prefers_envelope_handle_when_both_present` — precedence (envelope wins) so consumers mid-migration don't diverge from new consumers about which id the resolver sees - `handle_id_or_legacy_falls_back_to_legacy_string_when_no_handle` - `handle_id_or_legacy_errors_loud_when_neither_shape_provided` - `handle_id_or_legacy_prepends_command_name_to_handle_validation_errors` - `handle_id_or_legacy_propagates_type_mismatch_with_command_name` - `handle_id_or_legacy_uses_canonical_uuid_string_for_handle_path` — pins the bridge-format invariant: handle-path and legacy-path resolve to the SAME string representation ## Pre-existing (modules::data::tests, all 17 still pass) The 10 HandleRef migration tests + 7 pre-existing cursor tests exercise the SAME behavior they did before through the refactored callsites. No regression — net effect is the substrate now owns what data.rs used to own inline. # What this PR explicitly does NOT do - Does NOT add convenience constructors like `CommandResponse::with_handle_minted` (auto-generate UUID). That case is one line (`Uuid::new_v4()` then `with_handle(...)`); the primitive doesn't justify the API surface. - Does NOT add a `handle_type!(QueryCursor)` macro that derives the type_tag string from the module + struct name at compile time. Worth considering, but the doc-convention `const QUERY_CURSOR_TYPE_TAG = "data::QueryCursor"` pattern is already cheap and explicit. - Does NOT touch other handle-related types (Stream, Lambda placeholders). Those are reserved-but-unused; their kinks will surface when they get real consumers. # References - PR #1485 (cell shapes — HandleRef defined here, extended here) - PR #1486 (envelope pattern — CommandRequest defined here, extended here) - PR #1490 (first real HandleRef consumer — the inline boilerplate this PR distills lived there) Co-authored-by: Claude Opus 4.7 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Lands the cell return 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 stateful work.Canonical use cases for Handle
ai/inference/start { model, prompt }→ handle;ai/inference/poll { handle }+ai/inference/cancel { handle }operate on the sessiontraining/run/start { recipe }→ handle;training/run/progress { handle }+training/run/cancel { handle }live/room/join { roomId }→ handle;live/audio/publish { handle, frame }data/transaction/begin→ handle;data/transaction/exec { handle, query }+data/transaction/commit { handle }Same primitive whether the producer is in-process, in a sibling module, or on a remote peer over grid/airc.
What lands
runtime::cell_shapes::HandleRef— owner + UUID id + type_tag + created_at_ms.with_id(...)for producer-allocated UUIDs;mint(...)for fresh ones.StreamPlaceholder+LambdaPlaceholder— reserved variants. Returning either is a runtime error (the wire protocols aren't designed).#[non_exhaustive]makes future field additions non-breaking.CommandResultenum —Handle(HandleRef),Stream(StreamPlaceholder),Lambda(LambdaPlaceholder)added.Json+BinaryARE the Value cell shape under the legacy names — 300+ existing handlers stay unchanged.CommandResult::to_json_value— projects any cell shape to a plainValuefor callers that just want the payload. Handle serializes the HandleRef; Stream/Lambda return canonical protocol errors viastream_protocol_error/lambda_protocol_error.CommandResult::handle(owner, id, type_tag)— direct constructor.to_json_valueeverywhere the call site just wants JSON; explicit error arms only where the cell shape signals a contract violation (LLM step).other => panic!(...)for forward-compat.Test plan (23/23 pass)
shared/generated/runtime/)What this PR explicitly does NOT do
#[non_exhaustive]placeholders so future fields land non-breaking.Follow-up: pattern lifting (Joel 2026-05-30 directive)
Handle is foundational enough that it deserves to be a first-class field on every command's params + result, not just a variant in an enum. The next PR introduces:
CommandResponse<T>— typed wrapper that bundlesdata: T+handle: Option<HandleRef>+ standard envelope fields. Builder-style ergonomics for handlers that produce both data AND a handle for follow-up.CommandRequest<P>— typed wrapper for params withhandle: Option<HandleRef>+session_id+user_idas first-class fields.Value-based handler signature stays for back-compat; new handlers reach for the typed shape.Tracked as a separate PR so the cell shape foundation lands first and the pattern lifting builds on it.
References