Skip to content

fix(bindings): land ts-rs output for cell shapes + refresh stale barrels - #1488

Merged
joelteply merged 1 commit into
canaryfrom
fix/cell-shapes-ts-bindings
May 31, 2026
Merged

joelteply merged 1 commit into
canaryfrom
fix/cell-shapes-ts-bindings

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Summary

PR #1485 merged the Rust cell shapes (HandleRef / StreamPlaceholder / LambdaPlaceholder) but the ts-rs-generated .ts files weren't part of the diff — they only existed in my local working tree. Consumers on canary cannot import { HandleRef } from '@shared/generated/runtime' until those files land.

This PR drops the three files in + reruns the binding generator to refresh every stale barrel in the tree in one pass.

Diff scope

Change Files
New cell-shape bindings (the fix proper) shared/generated/runtime/{HandleRef,StreamPlaceholder,LambdaPlaceholder}.ts
Runtime barrel refresh — re-export the 3 new + 12 brain-region types already on canary as files but absent from index.ts shared/generated/runtime/index.ts
Persona barrel refresh — re-export EdgeKind + EngramEdge already on canary as files shared/generated/persona/index.ts
Master barrel — runtime + system switched from export * to explicit lists. PressureLevel exists in both; dedup rule = first-seen wins (runtime). Callers needing the system variant import it directly from @shared/generated/system. shared/generated/index.ts

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 writes regenerated files to the working tree without auto-committing. If a Rust author lands a PR without first running the generator + committing the TS output, the bindings drift.

Future hardening (not in this PR): a precommit check that fails loud when ts-rs output is dirty after build. Same pattern other generators use.

Verification

npx tsx generator/generate-rust-bindings.ts
✅ Generated 535 TypeScript types from Rust via ts-rs

Runs in under 10s on a warm cargo cache. No errors. Only warnings are the 8 known cross-domain duplicate type names that the explicit-export strategy used here handles.

Test plan

  • CI build:ts passes
  • TS consumers can import HandleRef, StreamPlaceholder, LambdaPlaceholder from @shared/generated/runtime
  • TS consumers can import EdgeKind, EngramEdge from @shared/generated/persona
  • No regressions in existing imports (e.g., PressureLevel from runtime keeps working)

References

`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
joelteply merged commit 8171a2d into canary May 31, 2026
4 checks passed
@joelteply
joelteply deleted the fix/cell-shapes-ts-bindings branch May 31, 2026 00:21
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
…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
Auto-generated by `cargo test --release export_bindings` after the
preceding commit added the Rust types with `#[derive(TS)]`. Brings
the TS wire-shape surface into sync with the Rust dispatch shipped
in the parent PR (#1501).

# What this adds

- `DirEntry.ts` — `{ name, path, kind: FsEntryKind, sizeBytes? }`
- `ExistsResult.ts` — `{ success, exists, filePath, kind?, sizeBytes? }`
- `FsEntryKind.ts` — `"file" | "directory" | "symlink" | "other"`
- `GlobResult.ts` — `{ success, pattern, matches, totalMatches, truncated }`
- `ListResult.ts` — `{ success, directoryPath, entries: DirEntry[], totalCount }`
- Updates `src/shared/generated/code/index.ts` barrel to export the five
  new types

# Why split into its own commit

The Rust-side commit is the substantive change; the binding files
are deterministic outputs of the ts-rs derive macros. Keeping them in
a separate commit makes the diff easier to audit (Rust logic + tests
in one commit, generated wire shapes in another) and matches the
pattern from PR #1488 (the cell-shapes binding fixup).

Task #62 (CI guard for ts-rs binding drift) remains the right
long-term answer; until then, this kind of follow-up commit closes
the gap.

Co-Authored-By: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request May 31, 2026
…introspection cluster (#1501)

* feat(modules/code): code/exists + code/list + code/glob — filesystem introspection cluster

Closes the Priority 1 gap from
[PERSONA-AS-DEVELOPER-GAP.md](docs/planning/PERSONA-AS-DEVELOPER-GAP.md):
the filesystem-introspection seam that blocks a persona from safely
running `generate/module` (no way to check for collisions),
enumerating files before edits, or listing directories without
paying the full `code/tree` recursive cost.

# What this PR adds

Three new dispatch arms on the existing `code` ServiceModule (the
right home — sits alongside `code/read`, `code/write`, `code/edit`,
`code/tree`, `code/search`):

| Command | Signature | Purpose |
|---|---|---|
| `code/exists` | `{persona_id, file_path}` → `ExistsResult{exists, kind, size_bytes?}` | Probe before scaffolding — collision check + kind in one call |
| `code/list` | `{persona_id, path?, include_hidden?}` → `ListResult{entries: DirEntry[]}` | Flat readdir, directories first, alphabetical within each group |
| `code/glob` | `{persona_id, pattern, root?}` → `GlobResult{matches, truncated}` | Glob expansion (`**/*.rs` etc.), workspace-scoped, capped at 5000 matches |

Plus three FileEngine methods backing them (`exists`, `list_dir`,
`glob_match`) and a `validate_introspect_path` private helper that
handles non-existent paths cleanly (PathSecurity::validate_read
rejects them; introspection needs to answer "does this exist?"
without conflating absence with traversal).

# Doctrine followed

Per [COMMAND-INFRASTRUCTURE-FIELD-MANUAL.md](docs/architecture/COMMAND-INFRASTRUCTURE-FIELD-MANUAL.md):

- **Module Design Template §3** — typed `Params/Result` shapes
  with `#[derive(TS)]`, camelCase serde, optional fields with
  `#[ts(optional)]`
- **Concurrency doctrine §4** — multi-thread tokio stress test
  (`flavor = "multi_thread", worker_threads = 4`) pinning that
  concurrent introspection on a shared workspace returns
  consistent results
- **Three primitives** — all three are pure **Commands** (request/
  response queries against FileEngine, no state, no events)
- **Rethink-not-port** — these are designed Rust-first; there's
  no TS predecessor to port from. Wire shapes follow the existing
  `code/*` family's conventions for consistency.

# Sharp design decisions (the kinks the tests caught pre-merge)

1. **Non-existent paths report `exists=false`, not Err.** The
   substrate's `PathSecurity::validate_read` rejects missing
   paths because it canonicalizes — correct for read/write/edit,
   wrong for introspection. Added `validate_introspect_path`
   helper that does string-level safety (rejects `..` segments
   + absolute paths) without requiring existence.

2. **Glob filters explicitly via Override.matched().is_whitelist().**
   First implementation walked all files and emitted everything —
   gave 11 matches when 10 were expected. Fix: explicit
   per-entry whitelist check; files only (skip directories +
   scan root); standard_filters + hidden=true excludes dotfiles
   by default (matches Unix shell intuition).

3. **list_dir sorts directories first, then files, alphabetical
   within each group.** Predictable order matters for persona
   reproducibility — a generator that picks "first available
   name" must get the same answer every run.

4. **Glob result capped at GLOB_MAX_MATCHES (5000)** with
   `truncated: true` flag. A runaway `**/*` shouldn't OOM the
   caller; partial results are still useful and the cap is
   observable.

5. **Hidden file behavior diverges between list_dir and glob.**
   `code/list` includes hidden when `include_hidden=true` (explicit
   opt-in). `code/glob` always excludes hidden (matches Unix shell
   default — `**/*.rs` shouldn't surface `.git/*.rs`). Documented
   on each type.

# Tests (30/30 pass — 22 pre-existing + 8 new)

New tests in `src/workers/continuum-core/src/code/file_engine.rs::tests`:

**exists (4)**
- `exists_reports_file_with_size` — happy path with size
- `exists_reports_directory_without_size` — directory has no size
- `exists_reports_false_for_missing_with_no_error` — absence != error
- `exists_rejects_path_outside_workspace_via_path_security` — traversal blocked

**list_dir (5)**
- `list_dir_returns_flat_listing_directories_first` — ordering invariant
- `list_dir_excludes_hidden_by_default_includes_when_asked` — both modes
- `list_dir_reports_file_size_only_for_files` — per-kind size policy
- `list_dir_rejects_non_directory_path_loud` — clear error on misuse
- `list_dir_for_missing_path_returns_not_found` — missing != success
- `list_dir_handles_empty_directory_cleanly` — zero entries OK

**glob (5)**
- `glob_matches_files_by_extension_recursively` — `**/*.ts` works
- `glob_scoped_to_subdirectory_via_root_param` — root narrows scope
- `glob_with_no_matches_returns_empty_not_error` — 0 matches OK
- `glob_rejects_bad_pattern_loud` — malformed pattern fails clearly
- `glob_rejects_root_outside_workspace_via_path_security` — traversal blocked

**concurrency (1)**
- `introspection_under_concurrent_load_returns_consistent_results` —
  32 parallel exists+list+glob ops on a shared workspace, all return
  stable counts (10 files, 10 matches) regardless of concurrent
  siblings. Per field manual §4.2 — multi-thread tokio, not
  single-threaded.

All 22 pre-existing FileEngine tests still pass (no regression).

# ts-rs bindings

5 new types are annotated with `#[derive(TS)]` + `export_to`:
- `ExistsResult.ts`, `ListResult.ts`, `GlobResult.ts`
- `DirEntry.ts`, `FsEntryKind.ts`

These auto-generate next time `cargo test --release export_bindings`
runs (per the existing `generate-rust-bindings.ts` flow). The
pending CI guard for ts-rs drift (task #62) is the right place
to catch any future drift here.

# What this PR explicitly does NOT do

- **Does NOT add TS wrapper commands** in `src/commands/code/exists/`
  etc. The Rust ServiceModule + IPC bridge is the canonical surface
  per [[rust-is-the-core-node-is-the-shell]]. TS wrappers can be
  added in a follow-up if/when browser ergonomics need them.
- **Does NOT add `code/delete` or `code/move`.** Those are
  PERSONA-AS-DEVELOPER-GAP.md priority 5 (Small). FileEngine.delete
  already exists internally; the dispatch wiring is the only gap.
  Separate PR.
- **Does NOT add the `continuum-core/build` + `test` cluster** (gap
  report priority 2). That's the next sprint — needs cargo
  `--message-format=json` parsing into typed envelopes.
- **Does NOT add `events/command-completed`** (gap report priority 3).
  Largest scope item; needs its own design discussion.

# References

- [docs/planning/PERSONA-AS-DEVELOPER-GAP.md](docs/planning/PERSONA-AS-DEVELOPER-GAP.md)
  — Priority 1 cluster this PR ships
- [docs/architecture/COMMAND-INFRASTRUCTURE-FIELD-MANUAL.md](docs/architecture/COMMAND-INFRASTRUCTURE-FIELD-MANUAL.md)
  §3 (Module Design Template) + §4 (Concurrency doctrine)
- [docs/architecture/MODULE-CATALOG.md §0](docs/architecture/MODULE-CATALOG.md)
  — `code` module's row gains three commands when this PR + the gap
  report land
- Memory: [[three-primitives-commands-events-persona]],
  [[alignment-via-substrate-economics]] — these commands are
  routable + discoverable, composing naturally with future
  intra-grid sharing

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

* chore(bindings): land ts-rs output for the code/exists+list+glob types

Auto-generated by `cargo test --release export_bindings` after the
preceding commit added the Rust types with `#[derive(TS)]`. Brings
the TS wire-shape surface into sync with the Rust dispatch shipped
in the parent PR (#1501).

# What this adds

- `DirEntry.ts` — `{ name, path, kind: FsEntryKind, sizeBytes? }`
- `ExistsResult.ts` — `{ success, exists, filePath, kind?, sizeBytes? }`
- `FsEntryKind.ts` — `"file" | "directory" | "symlink" | "other"`
- `GlobResult.ts` — `{ success, pattern, matches, totalMatches, truncated }`
- `ListResult.ts` — `{ success, directoryPath, entries: DirEntry[], totalCount }`
- Updates `src/shared/generated/code/index.ts` barrel to export the five
  new types

# Why split into its own commit

The Rust-side commit is the substantive change; the binding files
are deterministic outputs of the ts-rs derive macros. Keeping them in
a separate commit makes the diff easier to audit (Rust logic + tests
in one commit, generated wire shapes in another) and matches the
pattern from PR #1488 (the cell-shapes binding fixup).

Task #62 (CI guard for ts-rs binding drift) remains the right
long-term answer; until then, this kind of follow-up commit closes
the gap.

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

* fix(modules/code): escape `*/` glyph in GlobResult docstring breaking TS build

Adversarial PR review caught: a literal `**/*` glyph in the Rust
docstring round-trips through ts-rs verbatim into a JSDoc block in
`shared/generated/code/GlobResult.ts`, where the `*/` substring at
column 57 prematurely closes the comment. `npm run build:ts` fails
with TS1131 + TS1160; that blocks the validate CI job + npm start
for the whole canary tree.

Fix: replace the glyph spellings with the words "double-star slash
star" in two places (one in the field doc, one in the const doc).
Regenerated `GlobResult.ts` no longer contains the hazard.

Per [[every-error-is-an-opportunity-to-battle-harden]]: the
docstring also flags task #62 ("ts-rs binding drift CI guard") as
the proper substrate-level fix — a regex check against `*/` in
generated `.ts` doc blocks would have caught this class of bug
mechanically.

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

---------

Co-authored-by: Claude Opus 4.7 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant