Repository navigation
feat(runtime): events/command-completed — every dispatch emits a bus event (RTOS doctrine restored) - #1503
Merged
Conversation
…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]>
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
Closes Priority 3 from PERSONA-AS-DEVELOPER-GAP.md: restores the RTOS-brain doctrine at the dispatch layer. Every
CommandExecutor::execute()now emits acommand:completedevent 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)ts-rs exported, camelCase wire, optional
errorelided on success. Topic constantCOMMAND_COMPLETED_TOPIC = "command:completed"centralized.CommandExecutorextensionsbus: Option<Arc<MessageBus>>field +with_message_bus()builderexecute()wrapsexecute_inner()with timing + event emissioninit_executor_with_bus_and_interceptors(...)for production startupinit_executorpaths still work — no bus = silent no-op telemetryMessageBuschangeAdded
command:to the realtime passthrough list (joiningchat:,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)
command:joins realtime passthrough. Test then confirms 32 distinct events arriveCommandResultdoesn't impl Clone, blocking simple test fixtureCannedModulestoresResult<Value, String>(cloneable) + wraps inJsonon each callemit_command_completeduses fire-and-forgetpublish_async_only; logs serialize failures silentlyTest plan (17/17 pass)
What this PR does NOT do
init_executor_with_bus_and_interceptors. Safe — no bus wired = silent no-op. Follow-up PR threads the runtime's bus throughipc::start_servercommand:queued/command:dispatchinglifecycle events. Stream cell shape (gap report priority 4) is the right home for in-flight progressbus.receiver()orbus.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/buildcompleting on their machine emitscommand:completedto your local bus; your persona learns who built what, when. That's the cooperation economy made operational.Stacks on
canarydirectly. Independent of any open chain.Gap report priorities — all 3 large items shipped this session
code/exists+code/list+code/globcargo/build+cargo/testevents/command-completedPriorities 4 (
code/shell/stream— needs Stream cell shape) and 5 (code/delete+code/move) are clean follow-ups.References
three-primitives-commands-events-persona,alignment-via-substrate-economics,rtos-brain-no-region-on-hot-path