Skip to content

feat(runtime): events/command-completed — every dispatch emits a bus event (RTOS doctrine restored) - #1503

Merged
joelteply merged 1 commit into
canaryfrom
feat/events-command-completed
May 31, 2026
Merged

joelteply merged 1 commit into
canaryfrom
feat/events-command-completed

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Summary

Closes Priority 3 from PERSONA-AS-DEVELOPER-GAP.md: restores the RTOS-brain doctrine at the dispatch layer. Every CommandExecutor::execute() now emits a command:completed event on the wired bus after dispatch settles. Subscribers consume completion events instead of polling result surfaces.

This is the largest of the three gap-report priorities and the most architecturally pivotal — touches the dispatch hot path and adds a substrate-level signal personas can use to stay reactive.

What lands

CommandCompletedEvent (new type)

pub struct CommandCompletedEvent {
    pub command_name: String,
    pub duration_ms: u64,
    pub success: bool,
    pub error: Option<String>,
}

ts-rs exported, camelCase wire, optional error elided on success. Topic constant COMMAND_COMPLETED_TOPIC = "command:completed" centralized.

CommandExecutor extensions

  • New bus: Option<Arc<MessageBus>> field + with_message_bus() builder
  • execute() wraps execute_inner() with timing + event emission
  • New init function init_executor_with_bus_and_interceptors(...) for production startup
  • Back-compat: existing init_executor paths still work — no bus = silent no-op telemetry

MessageBus change

Added command: to the realtime passthrough list (joining chat:, sentinel:, presence:, tool:). Coalescing was dropping 31/32 events under multi-persona load — caught by the concurrency stress test pre-merge.

Sharp design decisions (kinks the tests caught)

Kink Fix
Bus coalesces same-prefix events in 50ms windows → 32 concurrent dispatches → 1 event delivered command: joins realtime passthrough. Test then confirms 32 distinct events arrive
CommandResult doesn't impl Clone, blocking simple test fixture CannedModule stores Result<Value, String> (cloneable) + wraps in Json on each call
Event emission must be infallible — telemetry can't break dispatch emit_command_completed uses fire-and-forget publish_async_only; logs serialize failures silently

Test plan (17/17 pass)

runtime::command_events::tests:: (5)
  event_round_trips_through_wire_with_camel_case ... ok
  event_with_error_includes_error_on_wire ... ok
  event_parses_from_wire_shape_subscribers_will_see ... ok
  topic_constant_is_namespaced_action_format ... ok
  export_bindings_commandcompletedevent ... ok

runtime::command_executor::tests:: (12, 5 new + 7 pre-existing)
  dispatch_emits_completed_event_on_success ... ok        ← new
  dispatch_emits_completed_event_on_handler_error ... ok  ← new
  dispatch_without_wired_bus_is_no_op_telemetry ... ok    ← new (back-compat)
  ts_bridge_failure_still_emits_completed_event ... ok    ← new (third tier)
  concurrent_dispatches_each_emit_their_own_event ... ok  ← new (multi-thread)
  (pre-existing 7 still pass)

test result: ok. 17 passed; 0 failed

What this PR does NOT do

  • Does NOT wire production startup to use init_executor_with_bus_and_interceptors. Safe — no bus wired = silent no-op. Follow-up PR threads the runtime's bus through ipc::start_server
  • Does NOT emit per-tier events (interceptor vs Rust vs TS). One event per dispatch — outermost outcome
  • Does NOT emit command:queued / command:dispatching lifecycle events. Stream cell shape (gap report priority 4) is the right home for in-flight progress
  • Does NOT add a default subscriber. Substrate ships the publisher; consumers wire via bus.receiver() or bus.subscribe()

Substrate doctrine reinforced

Per [[three-primitives-commands-events-persona]] + [[alignment-via-substrate-economics]] + [[rtos-brain-no-region-on-hot-path]]: this PR composes Commands (dispatch) with Events (completion notifications) at the kernel layer. Personas now have a substrate-level signal for "command X just finished with outcome Y."

Once peer dispatches over airc grid also echo these events to local buses (transparent via GridInterceptor → grid event echo, future PR), attribution becomes substrate-observable across the grid. A peer's cargo/build completing on their machine emits command:completed to your local bus; your persona learns who built what, when. That's the cooperation economy made operational.

Stacks on

canary directly. Independent of any open chain.

Gap report priorities — all 3 large items shipped this session

Priority What PR
1 (Small) code/exists + code/list + code/glob #1501
2 (Medium) cargo/build + cargo/test #1502
3 (Large) events/command-completed this PR

Priorities 4 (code/shell/stream — needs Stream cell shape) and 5 (code/delete + code/move) are clean follow-ups.

References

…event

Closes Priority 3 from
[PERSONA-AS-DEVELOPER-GAP.md](docs/planning/PERSONA-AS-DEVELOPER-GAP.md):
restores the RTOS-brain doctrine ("handlers read pre-staged
results, never block on recall/embedding/planning") at the
dispatch layer. Every `CommandExecutor::execute()` now emits a
`command:completed` event on the wired bus after the dispatch
settles — subscribers consume completion events instead of
polling result surfaces.

# What this adds

## `CommandCompletedEvent` (new type)

```rust
pub struct CommandCompletedEvent {
    pub command_name: String,
    pub duration_ms: u64,
    pub success: bool,
    pub error: Option<String>,
}
```

- ts-rs exported to `shared/generated/runtime/CommandCompletedEvent.ts`
- camelCase wire shape, optional `error` elided on success
- Topic constant `COMMAND_COMPLETED_TOPIC = "command:completed"`
  centralized for publishers + subscribers + tests to share

## `CommandExecutor` extensions

- New `bus: Option<Arc<MessageBus>>` field
- Builder `with_message_bus(bus: Arc<MessageBus>) -> Self`
- New init function `init_executor_with_bus_and_interceptors(...)`
  for production startup; existing `init_executor` paths still work
  without a bus (telemetry no-ops)
- `execute()` wraps `execute_inner()` with timing + event emission
  — single `OnceLock`-set path for both production and back-compat

## `MessageBus` change

Added `command:` to the realtime passthrough list. The bus
coalesces non-realtime events with the same prefix in 50ms windows
to prevent floods from bulk ops — but command-completion events
violate the RTOS doctrine if coalesced (a persona's loop would
miss 31 out of 32 events under multi-persona load). Now flows
through uncoalesced, same as `chat:`, `sentinel:`, `presence:`,
`tool:`.

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

1. **Coalescing dropped events under load.** Initial
   `concurrent_dispatches_each_emit_their_own_event` test asserted
   32 events from 32 concurrent dispatches — got 1. Root cause: the
   bus's 50ms coalescing window collapses same-prefix events. Fix:
   `command:` joins the realtime passthrough list. The test then
   confirms 32 distinct events arrive (with unique command_names,
   no event loss, no payload corruption).

2. **CommandResult doesn't impl Clone.** Test fixtures need to
   return the same canned result on repeated calls. Solution:
   `CannedModule` stores `Result<Value, String>` (cloneable) and
   wraps in `CommandResult::Json` on each handler call. No
   substrate change.

3. **Event emission is infallible telemetry, not contract.** The
   `emit_command_completed` helper publishes via `publish_async_only`
   (fire-and-forget) and silently logs serialize failures (which
   shouldn't happen for a struct of plain fields, but tolerated).
   Telemetry must never break the dispatch contract.

# Pinned invariants (multi-thread tests)

`runtime::command_executor::tests`:
- `dispatch_emits_completed_event_on_success` — happy path event with
  command_name + duration + success=true + no error
- `dispatch_emits_completed_event_on_handler_error` — failure path
  event with success=false + populated error mirroring the Err msg
- `dispatch_without_wired_bus_is_no_op_telemetry` — back-compat
  path (no bus) doesn't panic + dispatch still works
- `ts_bridge_failure_still_emits_completed_event` — third dispatch
  tier (TS bridge fallthrough) covered for both no-handler and
  failure paths; telemetry is exhaustive
- `concurrent_dispatches_each_emit_their_own_event` —
  `flavor = "multi_thread", worker_threads = 4`; 32 parallel
  dispatches each produce exactly one distinct event (no loss,
  no dupe, no payload interleave)

`runtime::command_events::tests`:
- `event_round_trips_through_wire_with_camel_case`
- `event_with_error_includes_error_on_wire`
- `event_parses_from_wire_shape_subscribers_will_see` — pin the
  exact JSON shape downstream consumers will see
- `topic_constant_is_namespaced_action_format`
- `export_bindings_commandcompletedevent` (ts-rs)

# What this PR does NOT do

- **Does NOT wire production startup to use the new init function.**
  `ipc::start_server` still calls `init_executor_with_interceptors`
  (no bus). A follow-up PR threads the runtime's bus through into
  startup. Safe: with no bus wired, the event emission is a silent
  no-op so production behavior is byte-identical until the wire
  lands.
- **Does NOT emit per-tier events** (interceptor handled vs local
  Rust vs TS bridge). One event per `execute()` call — the
  outermost outcome. Per-tier telemetry can be added later if a
  consumer needs it.
- **Does NOT emit `command:queued` / `command:dispatching`
  lifecycle events.** Just `command:completed`. The Stream cell
  shape (gap report priority 4) is the right home for in-flight
  progress events when it lands.
- **Does NOT add a default subscriber** (a persona loop that
  consumes these events). The substrate ships the publisher;
  consumers wire up per their use case via `bus.receiver()` or
  the existing `bus.subscribe()` path.

# Substrate doctrine reinforced

Per [[three-primitives-commands-events-persona]] +
[[alignment-via-substrate-economics]]: this PR composes the
Commands primitive (dispatch) with the Events primitive
(completion notifications) at the kernel layer. Personas now
have a substrate-level signal for "command X just finished with
outcome Y" — the foundation `code/shell/stream` (gap report
priority 4) extends with line-by-line streaming when the Stream
cell shape activates.

For the alignment economics: once peer dispatches over airc grid
also emit these events on the local bus (transparent via the
GridInterceptor → grid event echo), attribution becomes
substrate-observable across the grid. A peer's `cargo/build`
completing on their machine emits `command:completed` to your
local bus; your persona learns who built what, when.

# References

- [docs/planning/PERSONA-AS-DEVELOPER-GAP.md](docs/planning/PERSONA-AS-DEVELOPER-GAP.md)
  Priority 3 (this PR). Priority 1 was #1501, Priority 2 was #1502.
- [docs/architecture/COMMAND-INFRASTRUCTURE-FIELD-MANUAL.md](docs/architecture/COMMAND-INFRASTRUCTURE-FIELD-MANUAL.md)
  §2 (Substrate primitives) — adds the dispatch-level event hook
- [MODULE-CATALOG.md §0](docs/architecture/MODULE-CATALOG.md) —
  runtime substrate row to add when this lands
- Memories: [[three-primitives-commands-events-persona]],
  [[alignment-via-substrate-economics]],
  [[rtos-brain-no-region-on-hot-path]]

Co-Authored-By: Claude Opus 4.7 <[email protected]>
@joelteply
joelteply merged commit e1105ad into canary May 31, 2026
4 checks passed
@joelteply
joelteply deleted the feat/events-command-completed branch May 31, 2026 02:24
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