Skip to content

feat(positron): slice 2D-2 — Substrate coordinator + Connection state machine - #1604

Merged
joelteply merged 4 commits into
canaryfrom
feat/continuum-positron-session-2d-task
Jun 10, 2026
Merged

joelteply merged 4 commits into
canaryfrom
feat/continuum-positron-session-2d-task

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Summary

Composes the snapshot-then-live primitives into substrate-side state that one positron client session can occupy.

Stacked on #1603 (slice 2D-1 broadcast primitive). Stack: #1600 → #1601 → #1602 → #1603 → #1604.

What ships

  • Substrate — coordinator wrapping cache + broadcast. store(env) hits BOTH seams via the SAME Arc<StateEnvelope> allocation per [[shared-decode-per-persona-perspective]]. Substrate code can no longer accidentally hit one seam and not the other.

  • SubstrateStateCache::store_arc — added to support the shared-allocation path. Old cache.store stays as a one-line wrapper for callers that build StateEnvelope directly.

  • Connection — one client session's substrate-recorded state: subscription: Subscription + observers: HashMap<String, ObserverRegistration>. Single dispatch point: Connection::handle(msg, substrate, dispatcher) -> Vec<ServerMessage> matches every variant exhaustively and delegates to the existing apply_* primitives.

Three load-bearing pins at the connection layer

The wrapper layer is exactly the surface where doctrine drift sneaks in. Each pin is one test:

  • resubscribe_replaces_not_merges — the §"Subscribe is declarative (replace, not merge)" doctrine carried up from Subscription::replace to the connection's subscription field.
  • reobserve_under_same_id_replaces_not_adds — same doctrine for observers, scoped per observer_id so distinct observers coexist while same-id re-Observe replaces.
  • command_success_emits_no_protocol_frame_in_connection_too + command_failure_emits_command_failed_at_connection_layer — the §"loud failures + no success-ack" asymmetry must survive the wrapping.

What this slice does NOT ship (slice 2D-3)

  • Async session task — long-running future that reads ClientMessage from the transport's inbound stream, drives Connection::handle, attaches watch::Receivers for the new Subscription's kinds, fans live envelopes through ServerMessage::State to the transport's outbound sink, and quantizes per-observer budget_hz.

The Connection state machine is the building block that the async task composes. Keeping it sync + pure-mutation makes the async loop's logic narrow (just plumbing) and lets every state transition be unit-tested without spawning tasks.

Doctrines

  • [[no-fallbacks-ever]] — every variant in Connection::handle is explicit; no _ => … arm.
  • [[shared-decode-per-persona-perspective]] — Substrate::store shares one Arc allocation between cache and broadcast.
  • [[strong-typing-across-boundaries]] — CommandDispatch is a trait; subscription / observer state are typed values.

Test plan

  • cargo test -p continuum-positron — 54/54 green (49 lib + 5 integration). +12 new tests this slice (3 substrate + 9 connection).
  • cargo check -p continuum-positron — clean.
  • CI workspace build when stack lands on canary.

@joelteply

Copy link
Copy Markdown
Contributor Author

SENTINEL VERDICT: APPROVE — delta conforms to v0.1.1; two notes, one inherited and one latent, neither a regression introduced by this diff.

Verified (49 unit + 5 integration green against v0.1.1):

  • Substrate::store hits cache + broadcast with ONE shared Arc — the can't-drift coordinator the two primitives needed; pinned by store_hits_both_cache_and_broadcast and cache_and_broadcast_see_identical_revisions_after_many_stores.
  • Connection owns subscription state, declarative replace — Subscribe replaces wholesale (resubscribe_replaces_not_merges); Observe replaces per observer_id while distinct ids coexist (reobserve_under_same_id_replaces_not_adds, multiple_observer_ids_coexist).
  • Watermark scoping (the round-2 catch): the drop watermark is a consumer-side concept and nothing here violates it — Connection keeps NO per-kind rendered-revision state that could survive a Subscribe/Observe; the subscription is replaced wholesale, and cross-reconnect knowledge travels only in last_seen, exactly as the spec requires. The skip rule propagates through the connection layer intact (subscribe_with_matching_last_seen_skips_through_connection_layer).
  • CommandFailed asymmetry preserved at the connection layer — success empty, failure one frame, sender-only delivery documented as the 2D-3 task's obligation.

Notes (required before/at 2D-3, not blockers for this delta):

  1. Inherits feat(positron): slice 2D-1 — per-kind watch::Sender broadcast primitive #1603's cold-start hole — Connection never attaches watch receivers (deferred to 2D-3), so the hole isn't exploited here, but this PR will need a rebase when feat(positron): slice 2D-1 — per-kind watch::Sender broadcast primitive #1603's fix lands. When 2D-3 splices snapshot→live, attach the receiver BEFORE emitting snapshot frames (and treat the receiver's current value as a floor) so the per-kind non-decreasing revision order holds across the splice.

  2. Substrate::store is racy under concurrent same-kind producers — cache and broadcast lock independently, so two interleaved store() calls can leave the cache at rev N−1 while watch emitted N, and emit decreasing revisions on the watch stream (spec: substrate MUST emit non-decreasing per kind; the consumer drop-rule makes it harmless but the cache staleness persists until the next mutation). If the event bridge is single-task, say so in the store doc as a contract; otherwise add an only-if-newer revision guard in store_arc + do the send under the same critical section.

  3. Observer registrations are per-connection only; the same observer_id on two live connections double-perceives. Fine for now — flag when budget enforcement lands, since budget should be per-observer, not per-connection.

joelteply added a commit that referenced this pull request Jun 10, 2026
…ance

Sentinel BLOCK on #1602: the trait signature
`dispatch(command: String, params: Value)` decomposed CommandEnvelope
at the substrate seam, silently erasing `source` (Human vs
Observer { observer_id }) and `kind` before the dispatcher ever saw
them. The positron wire doctrine says commands are "first-class but
never anonymous" precisely so substrate-side authorization + audit
can scope authority by who and what — that line was doing real work
and the seam was breaking it.

Change `CommandDispatch::dispatch(envelope: CommandEnvelope)` to
hand the full typed value across the seam, per
[[strong-typing-across-boundaries]]. `apply_command` no longer
destructures; tests record `Vec<CommandEnvelope>` instead of
`Vec<(String, Value)>`. New regression test
`dispatcher_receives_envelope_source_and_kind_intact` builds an
Observer-sourced command and asserts both `kind` and the
`observer_id` payload round-trip through the seam — locks the
provenance contract structurally.

The cascade through Connection::handle_command + the integration
roundtrip tests lands on #1604's branch when this rebases up.

Closes BLOCK on #1602.
@joelteply
joelteply force-pushed the feat/continuum-positron-session-2d-broadcast branch from 8f62eba to 69e10f0 Compare June 10, 2026 23:27
@joelteply
joelteply force-pushed the feat/continuum-positron-session-2d-task branch from 0c459f1 to 8f4ee6c Compare June 10, 2026 23:28
@joelteply

Copy link
Copy Markdown
Contributor Author

SENTINEL VERDICT (round 2): APPROVE — head 8f4ee6cc8 is the previously-approved delta plus a provably mechanical cascade. 51 unit + 5 integration green against positron-core v0.1.1.

Mechanical-only verified at the patch level, not by eyeball:

  • The rebased feature commit bfe5e530a is byte-identical (diff of git show patches) to the round-1-approved 0c459f1a7. Zero drift in the reviewed content.
  • The new cascade commit 8f4ee6cc8 touches ONLY test code: connection.rs's ScriptedDispatcher mock adopts the envelope-shaped dispatch (records Vec<CommandEnvelope>), and substrate.rs tests unwrap the new Option layer at borrow() — in every case immediately after a store() that guarantees Some, so no unwrap-on-None is reachable. No production line changed.

Conformance re-confirmed at the stack head:

  • Watermark scoping: Connection still keeps no per-kind rendered-revision state; Subscribe replaces self.subscription wholesale, Observe replaces per observer_id via HashMap::insert (resubscribe_replaces_not_merges, reobserve_under_same_id_replaces_not_adds, multiple_observer_ids_coexist, subscribe_with_matching_last_seen_skips_through_connection_layer all green).
  • Provenance composes through the connection layer: handle_command forwards the whole ClientMessage::Command(envelope) to apply_command — nothing re-erases source/kind.
  • Substrate::store still hits cache + broadcast with ONE shared Arc (store_hits_both_cache_and_broadcast, cache_and_broadcast_see_identical_revisions_after_many_stores).
  • Every ServerMessage match in the crate remains a test assertion over substrate-constructed outbound frames; no inbound handling exists to violate skip-and-log.

Carried round-1 notes, still open for 2D-3 (not blockers): (1) attach the watch receiver BEFORE emitting snapshot frames and treat its current value as a floor, so the per-kind non-decreasing order holds across the snapshot→live splice — note the receiver's initial value may now be None, which is below any floor; (2) Substrate::store is racy under concurrent same-kind producers (cache and broadcast lock independently) — document single-task bridging as a contract or guard with only-if-newer under one critical section; (3) observer registrations are per-connection, so one observer_id on two connections double-perceives — revisit when budget enforcement lands.

joelteply added a commit that referenced this pull request Jun 10, 2026
…ance

Sentinel BLOCK on #1602: the trait signature
`dispatch(command: String, params: Value)` decomposed CommandEnvelope
at the substrate seam, silently erasing `source` (Human vs
Observer { observer_id }) and `kind` before the dispatcher ever saw
them. The positron wire doctrine says commands are "first-class but
never anonymous" precisely so substrate-side authorization + audit
can scope authority by who and what — that line was doing real work
and the seam was breaking it.

Change `CommandDispatch::dispatch(envelope: CommandEnvelope)` to
hand the full typed value across the seam, per
[[strong-typing-across-boundaries]]. `apply_command` no longer
destructures; tests record `Vec<CommandEnvelope>` instead of
`Vec<(String, Value)>`. New regression test
`dispatcher_receives_envelope_source_and_kind_intact` builds an
Observer-sourced command and asserts both `kind` and the
`observer_id` payload round-trip through the seam — locks the
provenance contract structurally.

The cascade through Connection::handle_command + the integration
roundtrip tests lands on #1604's branch when this rebases up.

Closes BLOCK on #1602.
@joelteply
joelteply force-pushed the feat/continuum-positron-session-2d-broadcast branch from 69e10f0 to 8767e2a Compare June 10, 2026 23:45
@joelteply
joelteply force-pushed the feat/continuum-positron-session-2d-task branch from 8f4ee6c to 0c42f8c Compare June 10, 2026 23:45
joelteply added a commit that referenced this pull request Jun 10, 2026
…-opens #1602) (#1605)

* feat(positron): slices 2B+2C — Observe handler + Command dispatch with CommandFailed asymmetry (task #252)

Substrate-side handlers for positron v0.1.1's session protocol —
the remaining ClientMessage variants now have substrate-side
counterparts.

Ships:

- `ObserverRegistration { observer_id, budget_hz, kinds, layers }`
  + `apply_observe(cache, msg) -> (ObserverRegistration,
  Vec<ServerMessage>)` — mirror of apply_subscribe for ObserverSpec.
  Same exact-equality skip rule via `session::should_skip` (made
  pub(crate) and shared with apply_observe, since positron protocol
  §"Observers resync identically" says one resync contract for
  humans AND AIs). Declarative replace per `observer_id`: re-observe
  REPLACES that observer's prior registration, no merge method
  exists. `budget_hz` is captured but not yet enforced — enforcement
  is a broadcast-time concern in slice 2D.

- `CommandDispatch` trait + `apply_command(dispatcher, msg) ->
  Vec<ServerMessage>` — bridge CommandEnvelope through continuum's
  command surface. Intentionally asymmetric per v0.1.1 protocol:
  - Success → empty Vec (state change carries the implicit ack;
    unidirectional model stands)
  - Failure → ONE ServerMessage::CommandFailed { correlation_id,
    error } targeting only the failing connection (transport-level
    per-connection routing is the session-task's job; this pure
    handler just emits the frame)

- `CommandDispatch` is a trait, not a function pointer, so the
  substrate-side seam to continuum-core's CommandExecutor stays
  typed and extensible. Tests inject ScriptedDispatcher mocks
  rather than half-implementing the real executor.

Architectural correctness:

- positron protocol §"loud failures" doctrine pinned by
  `failure_emits_command_failed_with_echoed_correlation_id` —
  silent failure is forbidden, the substrate ALWAYS emits a
  CommandFailed frame on Err with the client's echoed correlation_id.

- positron protocol §"no success-ack" pinned by
  `success_emits_no_protocol_frame` — adding a synthetic success
  frame here would create a second correlate-able event that breaks
  the unidirectional model.

- Single resync contract pinned by
  `higher_last_seen_does_NOT_skip_for_observers_either` — the
  observer skip rule MUST behave identically to the subscriber skip
  rule. A divergent observer rule would re-introduce Fable's round-2
  catch (stale-forever) on the AI-perception path.

What this slice does NOT ship (intentional follow-up, slice 2D):

- Live broadcast plumbing — Fable's design call (in airc): `watch`
  per kind, not `broadcast`. StateEnvelopes are complete snapshots
  → latest-wins coalescing IS the spec; broadcast would buffer
  needless copies + bolt on a Lagged error path watch structurally
  avoids. Slice 2D ships the per-kind `watch::Sender<Arc<
  StateEnvelope>>` fan-out + per-observer `budget_hz` quantization.

- Per-connection session task — the agent that owns one
  ClientMessage/ServerMessage stream, routes incoming variants
  through the three apply_* handlers, owns the new Subscription /
  ObserverRegistration values, and forwards CommandFailed to ONLY
  the failing connection per protocol §"Delivery scope". Slice 2D.

- Event-bridging from continuum's bus → cache.store. The
  StateBuilder seam is ready; the bus wire-up lands in slice 2E.

31/31 tests green (23 from prior slices + 4 observer + 4 dispatch).
Stacks on PR #1601 (slice 2A).

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

* test(positron): end-to-end session-protocol smoke — typed payload round-trip through the whole chain

Five integration tests in `core/continuum-positron/tests/session_roundtrip.rs` exercise the substrate → wire → consumer chain that unit tests can't catch on their own:

- `typed_payload_round_trips_through_subscribe_snapshot` — substrate builds ChatViewState → StateBuilder frames → cache stores → apply_subscribe retrieves → serde_json round-trip → renderer deserializes back as typed ChatViewState. Pins the "continuum-positron and positron-lit speak the same typed shape" contract.

- `skip_rule_works_end_to_end_on_resubscribe` — first subscribe gets snapshot, immediate resubscribe with last_seen=current gets no frame. §6 reconnect-tolerance in miniature.

- `substrate_restart_resync_works_end_to_end` — stale-renderer-vs-fresh-substrate (client@500 vs substrate@1) MUST get the snapshot, never silently skip. The load-bearing invariant Fable's round-2 review caught, now pinned end-to-end (not just at the unit-test apply_subscribe seam). The renderer also sees the current substrate truth in the snapshot payload — not just a "we sent something" guarantee.

- `two_subscribers_share_envelope_bytes_per_doctrine` — two renderers subscribing in the same tick get byte-identical snapshots. Pins `[[shared-decode-per-persona-perspective]]` — cache stores Arc, doesn't re-decode per subscriber.

- `three_kinds_independently_partitioned` — multi-kind subscribe with selective skip (one kind matched, two didn't). Pins independent per-kind partitioning.

No new substrate code; pure integration coverage. Catches the class of bug where two modules each pass their own unit tests but compose incorrectly.

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

* fix(positron): CommandDispatch takes whole envelope — preserve provenance

Sentinel BLOCK on #1602: the trait signature
`dispatch(command: String, params: Value)` decomposed CommandEnvelope
at the substrate seam, silently erasing `source` (Human vs
Observer { observer_id }) and `kind` before the dispatcher ever saw
them. The positron wire doctrine says commands are "first-class but
never anonymous" precisely so substrate-side authorization + audit
can scope authority by who and what — that line was doing real work
and the seam was breaking it.

Change `CommandDispatch::dispatch(envelope: CommandEnvelope)` to
hand the full typed value across the seam, per
[[strong-typing-across-boundaries]]. `apply_command` no longer
destructures; tests record `Vec<CommandEnvelope>` instead of
`Vec<(String, Value)>`. New regression test
`dispatcher_receives_envelope_source_and_kind_intact` builds an
Observer-sourced command and asserts both `kind` and the
`observer_id` payload round-trip through the seam — locks the
provenance contract structurally.

The cascade through Connection::handle_command + the integration
roundtrip tests lands on #1604's branch when this rebases up.

Closes BLOCK on #1602.

---------

Co-authored-by: Claude Opus 4.7 <[email protected]>
joelteply added a commit that referenced this pull request Jun 10, 2026
…wState + revisions + StateBuilder (§6 closes #793/#794/#773) (#1600)

* feat(positron): substrate-side scaffold — typed ChatViewState + monotonic revisions + StateBuilder (task #252)

Continuum's positron substrate, slice 1. Implements the substrate
side of the positron contract — produces typed StateEnvelopes that
positron-lit (Fable's lane) renders. Closes ALPHA-GAP §6 alpha
P0/P1 blockers (#793 core-restart reconnect, #794 AI msgs not
realtime, #773 WS reconnect) structurally via the positron contract:
state-down, event-up, no widget-local source-of-truth caches.

Slice 1 ships:

- `KnownKind` enum + `wire_name()` mapping. Typed widget kinds so the
  match is rustc-enforced exhaustive; a typo at the call site is a
  compile error, not a runtime mismatch.

- `Revisions` — monotonic per-kind counter, `Mutex<HashMap>` keyed by
  `KnownKind`. Revisions stay per-KIND (not per `(kind, layer)`) per
  Fable's session-protocol design call: ViewState::revision() in the
  trait layer is one counter per state instance; layer classifies an
  UPDATE's cadence, not state identity. Layer-aware partitioning
  would fragment state identity.

- `ChatViewState` typed payload + supporting types (ChatMessageView,
  PersonaSlotView, SenderKind). #[derive(TS)] exported so the widget
  side reads typed objects, not `unknown`. SenderKind is tagged so
  the widget keys avatar/styling off a discriminant, no
  string-sniffing per `[[strong-typing-across-boundaries]]`.

- `StateBuilder` — frames typed payloads into
  `positron_core::wire::StateEnvelope`s with the right kind tag,
  auto-allocated monotonic revision, and explicit layer (session /
  persistent / ephemeral / semantic). Centralizes the three things
  that must line up on every state delivery so substrate call sites
  can't drift.

- bindings/ gitignored (ts-rs generated per cargo test; substrate
  source of truth is src/*.rs).

What this slice does NOT ship (intentional follow-up):

- Wire transport binding. Lands once Fable's positron session
  protocol PR (`df3fb2ab`, currently in Review) merges. Session
  protocol is typed Client/Server unions with
  `Subscribe { last_seen: [{kind, revision}] }` replay-on-resync —
  the §6 reconnect-tolerance primitive.

- Substrate event source. Continuum's existing event bus emits
  room/chat/persona events; the event → StateEnvelope bridging
  layer goes on top of this slice's typed schema in the next
  commit.

- ContinuumHost / observer registration. Lands with the wire
  transport so the AI-observer perception path (the
  `Observer<ChatViewState>` impl persona cognition uses to perceive
  the same chat humans see) is one cohesive cut.

Architectural correctness:

- I am the SUBSTRATE per positron's DESIGN.md §3, not a `Host` impl.
  Continuum produces StateEnvelopes; positron-lit consumes them.
  Naming is `continuum-positron` (substrate-side crate), not
  ContinuumHost.

Dep posture: path dep on [email protected] for active dev (Joel +
Fable both have the sibling repo); switch to git rev pin once
positron tags v0.1.

Test plan:
- `cargo test -p continuum-positron`: 12 passed (8 hand-written +
  4 ts-rs export bindings tests). 0 failures.
- `cargo check -p continuum-positron --features metal,accelerate`:
  clean (no features used in this crate; sanity-check it doesn't
  break workspace resolution).

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

* feat(positron): slice 2A — Subscribe handler with exact-equality skip rule (#1601)

* feat(positron): slice 2A — Subscribe handler with exact-equality skip rule (task #252)

Substrate-side handlers for positron v0.1.0's session protocol.
Slice 2A scope: `ClientMessage::Subscribe` → `(Subscription,
Vec<ServerMessage>)` per the snapshot-then-live contract.

Ships:

- `SubstrateStateCache` — in-memory map of latest `StateEnvelope`
  per kind. Event-bridging layer (slice 2B) writes; the subscribe
  handler reads. No fallback when a kind has no cached state yet —
  silence is the honest answer (per [[no-fallbacks-ever]]); a
  synthetic empty snapshot would mis-render the UI as "empty chat"
  when reality is "no state produced yet."

- `Subscription { kinds: HashSet<String>, layers: Vec<StateLayer> }`
  — one connection's declared interest set. Declarative replace is
  enforced at the type level: `Subscription::replace(...)` is the
  only constructor; there is no `merge` method. `Subscription::
  covers(kind, layer)` is the per-envelope live-broadcast gate
  (slice 2B consumer).

- `apply_subscribe(cache, msg) -> Result<(Subscription,
  Vec<ServerMessage>), String>` — implements the snapshot-then-live
  contract with the exact-equality skip rule. For each subscribed
  kind: look up the cached envelope; check the client's `last_seen`
  for an EXACT-equality match against the current revision. Match
  → skip. Mismatch (including substrate-restart counter-reset
  cases) → send the current snapshot. The function refuses
  non-Subscribe variants loudly per [[no-fallbacks-ever]].

The skip rule is the load-bearing one Fable's round-2 review caught
on positron#2: a `>=` comparison would let a client holding
`last_seen: 500` from a pre-restart substrate keep stale state
forever against a freshly-restarted substrate at revision 3. Exact
equality makes counter resets safe by construction — any mismatch
in either direction sends the snapshot. Pinned by the test
`higher_last_seen_does_NOT_skip_per_protocol_load_bearing_invariant`.

Out of scope for 2A (slice 2B+):
- `Command(CommandEnvelope)` → `Commands.execute` dispatch
- `Observe` registration + observer perception budget enforcement
- Live broadcast wiring (a `watch::Sender` or analog) — the
  Subscription type's `covers()` is the gate; the fan-out plumbing
  is the next slice
- Event-bridging from continuum's bus → cache.store

Small follow-up on [email protected]: `StateLayer` doesn't derive
`Hash`. Quickest fix here is `Vec<StateLayer>` (4 variants, linear
scan free, defensive sort+dedup in `Subscription::replace`). Worth
PR-ing `derive(Hash)` into positron for downstream consumers who
want HashSet-typed layer sets.

23/23 tests green (12 from slice 1 + 8 new session tests + 3 cache
tests). Stacks on PR #1600 (slice 1 substrate scaffold).

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

* fix(positron): exhaustive match arms for ServerMessage in session tests

Sentinel BLOCK on #1601: test sites at session.rs:243 and :374 matched
only ServerMessage::State, which compiles against positron-core v0.1.0
but not v0.1.1 (which added CommandFailed). Add the explicit
"other => panic!" arm at both sites so the tests stay decisive — wrong
variant fails loudly, not silently.

The CommandFailed match arms living in #1602's diff were the right
shape, just landing in the wrong PR — moves down the stack here.

Closes BLOCK on #1601.

---------

Co-authored-by: Claude Opus 4.7 <[email protected]>

* feat(positron): slices 2B+2C — Observe handler + Command dispatch (re-opens #1602) (#1605)

* feat(positron): slices 2B+2C — Observe handler + Command dispatch with CommandFailed asymmetry (task #252)

Substrate-side handlers for positron v0.1.1's session protocol —
the remaining ClientMessage variants now have substrate-side
counterparts.

Ships:

- `ObserverRegistration { observer_id, budget_hz, kinds, layers }`
  + `apply_observe(cache, msg) -> (ObserverRegistration,
  Vec<ServerMessage>)` — mirror of apply_subscribe for ObserverSpec.
  Same exact-equality skip rule via `session::should_skip` (made
  pub(crate) and shared with apply_observe, since positron protocol
  §"Observers resync identically" says one resync contract for
  humans AND AIs). Declarative replace per `observer_id`: re-observe
  REPLACES that observer's prior registration, no merge method
  exists. `budget_hz` is captured but not yet enforced — enforcement
  is a broadcast-time concern in slice 2D.

- `CommandDispatch` trait + `apply_command(dispatcher, msg) ->
  Vec<ServerMessage>` — bridge CommandEnvelope through continuum's
  command surface. Intentionally asymmetric per v0.1.1 protocol:
  - Success → empty Vec (state change carries the implicit ack;
    unidirectional model stands)
  - Failure → ONE ServerMessage::CommandFailed { correlation_id,
    error } targeting only the failing connection (transport-level
    per-connection routing is the session-task's job; this pure
    handler just emits the frame)

- `CommandDispatch` is a trait, not a function pointer, so the
  substrate-side seam to continuum-core's CommandExecutor stays
  typed and extensible. Tests inject ScriptedDispatcher mocks
  rather than half-implementing the real executor.

Architectural correctness:

- positron protocol §"loud failures" doctrine pinned by
  `failure_emits_command_failed_with_echoed_correlation_id` —
  silent failure is forbidden, the substrate ALWAYS emits a
  CommandFailed frame on Err with the client's echoed correlation_id.

- positron protocol §"no success-ack" pinned by
  `success_emits_no_protocol_frame` — adding a synthetic success
  frame here would create a second correlate-able event that breaks
  the unidirectional model.

- Single resync contract pinned by
  `higher_last_seen_does_NOT_skip_for_observers_either` — the
  observer skip rule MUST behave identically to the subscriber skip
  rule. A divergent observer rule would re-introduce Fable's round-2
  catch (stale-forever) on the AI-perception path.

What this slice does NOT ship (intentional follow-up, slice 2D):

- Live broadcast plumbing — Fable's design call (in airc): `watch`
  per kind, not `broadcast`. StateEnvelopes are complete snapshots
  → latest-wins coalescing IS the spec; broadcast would buffer
  needless copies + bolt on a Lagged error path watch structurally
  avoids. Slice 2D ships the per-kind `watch::Sender<Arc<
  StateEnvelope>>` fan-out + per-observer `budget_hz` quantization.

- Per-connection session task — the agent that owns one
  ClientMessage/ServerMessage stream, routes incoming variants
  through the three apply_* handlers, owns the new Subscription /
  ObserverRegistration values, and forwards CommandFailed to ONLY
  the failing connection per protocol §"Delivery scope". Slice 2D.

- Event-bridging from continuum's bus → cache.store. The
  StateBuilder seam is ready; the bus wire-up lands in slice 2E.

31/31 tests green (23 from prior slices + 4 observer + 4 dispatch).
Stacks on PR #1601 (slice 2A).

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

* test(positron): end-to-end session-protocol smoke — typed payload round-trip through the whole chain

Five integration tests in `core/continuum-positron/tests/session_roundtrip.rs` exercise the substrate → wire → consumer chain that unit tests can't catch on their own:

- `typed_payload_round_trips_through_subscribe_snapshot` — substrate builds ChatViewState → StateBuilder frames → cache stores → apply_subscribe retrieves → serde_json round-trip → renderer deserializes back as typed ChatViewState. Pins the "continuum-positron and positron-lit speak the same typed shape" contract.

- `skip_rule_works_end_to_end_on_resubscribe` — first subscribe gets snapshot, immediate resubscribe with last_seen=current gets no frame. §6 reconnect-tolerance in miniature.

- `substrate_restart_resync_works_end_to_end` — stale-renderer-vs-fresh-substrate (client@500 vs substrate@1) MUST get the snapshot, never silently skip. The load-bearing invariant Fable's round-2 review caught, now pinned end-to-end (not just at the unit-test apply_subscribe seam). The renderer also sees the current substrate truth in the snapshot payload — not just a "we sent something" guarantee.

- `two_subscribers_share_envelope_bytes_per_doctrine` — two renderers subscribing in the same tick get byte-identical snapshots. Pins `[[shared-decode-per-persona-perspective]]` — cache stores Arc, doesn't re-decode per subscriber.

- `three_kinds_independently_partitioned` — multi-kind subscribe with selective skip (one kind matched, two didn't). Pins independent per-kind partitioning.

No new substrate code; pure integration coverage. Catches the class of bug where two modules each pass their own unit tests but compose incorrectly.

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

* fix(positron): CommandDispatch takes whole envelope — preserve provenance

Sentinel BLOCK on #1602: the trait signature
`dispatch(command: String, params: Value)` decomposed CommandEnvelope
at the substrate seam, silently erasing `source` (Human vs
Observer { observer_id }) and `kind` before the dispatcher ever saw
them. The positron wire doctrine says commands are "first-class but
never anonymous" precisely so substrate-side authorization + audit
can scope authority by who and what — that line was doing real work
and the seam was breaking it.

Change `CommandDispatch::dispatch(envelope: CommandEnvelope)` to
hand the full typed value across the seam, per
[[strong-typing-across-boundaries]]. `apply_command` no longer
destructures; tests record `Vec<CommandEnvelope>` instead of
`Vec<(String, Value)>`. New regression test
`dispatcher_receives_envelope_source_and_kind_intact` builds an
Observer-sourced command and asserts both `kind` and the
`observer_id` payload round-trip through the seam — locks the
provenance contract structurally.

The cascade through Connection::handle_command + the integration
roundtrip tests lands on #1604's branch when this rebases up.

Closes BLOCK on #1602.

---------

Co-authored-by: Claude Opus 4.7 <[email protected]>

---------

Co-authored-by: Claude Opus 4.7 <[email protected]>
@joelteply
joelteply force-pushed the feat/continuum-positron-session-2d-broadcast branch from 8767e2a to b6e892d Compare June 10, 2026 23:47
joelteply and others added 4 commits June 10, 2026 18:48
…ve (task #252)

The substrate-side live-broadcast primitive for positron's snapshot-
then-live contract. `Broadcast` holds one
`tokio::sync::watch::Sender<Arc<StateEnvelope>>` per kind, lazy-
initialized on first send.

Per Fable's design call on the airc grid: watch (not broadcast).
StateEnvelopes are complete snapshots → latest-wins coalescing IS
the protocol; an intermediate envelope a receiver never saw is dead
weight, not data loss. broadcast would buffer N intermediates nobody
should render + bolt on a Lagged error path watch structurally
avoids.

Implementation notes:

- `send_replace` (not `send`) so the latest value persists across
  no-receivers windows. This is the load-bearing fix for the
  substrate-start-before-first-session-attach case: if substrate
  produces state before any session subscribes, the next session
  that attaches must see the latest value, not the original
  initial. `send` would silently no-op when there are no receivers,
  losing that update. `send_replace` always updates the watched
  value. Pinned by `send_with_no_subscribers_is_not_an_error` and
  `dropped_receivers_dont_break_subsequent_sends`.

- Lazy per-kind init. `watch::channel(initial)` requires an initial
  value, so we don't pre-allocate senders for kinds that may never
  produce state. First `send()` for a kind creates that kind's
  sender. `subscribe()` returns `None` if no envelope has ever been
  sent — honest `[[no-fallbacks-ever]]` answer; callers pair with
  the snapshot-then-live flow.

- Sessions / kinds are independent streams. Pinned by
  `kinds_are_independent_streams` — a send on one kind MUST NOT
  wake another kind's receivers.

What this slice does NOT ship (slice 2D-2):

- Per-connection session task — the agent that owns one
  ClientMessage/ServerMessage stream, routes incoming variants
  through apply_subscribe / apply_observe / apply_command, attaches
  watch::Receivers per the new Subscription, forwards live frames
  to its outbound sink, and emits CommandFailed sender-only.

- `Substrate` coordinator wrapping cache + broadcast. Substrate
  code that produces state pushes to BOTH today (cache.store +
  broadcast.send). Slice 2D-2 wraps the pair.

- Per-observer `budget_hz` quantization — the observer broadcast
  side-channel that quantizes envelopes per observer's declared
  budget. Slice 2D-2 wires this into the per-connection task.

6 broadcast tests cover the contract surface; 5 integration tests
from the prior commit still green. 37/37 lib + 5/5 integration =
42/42 total.

Stacks on PR #1602 (slices 2B+2C).

Co-Authored-By: Claude Opus 4.7 <[email protected]>
Sentinel BLOCK on #1603: a renderer that called subscribe(kind)
BEFORE the substrate had ever produced state for that kind got
None back, with no path to ever wake up when state arrived. The
session-task layer above would either crash on the None or wait
forever — exactly the kind of timing-dependent silent stall the
snapshot-then-live contract exists to prevent.

Flip the watched type from Arc<StateEnvelope> to
Option<Arc<StateEnvelope>>, and lazy-init the per-kind watch::Sender
from EITHER side:

- First send(envelope) → channel(Some(envelope)) (same as before).
- First subscribe(kind) on an unknown kind → channel(None), return
  the receiver pinned to None.
- A subsequent send transitions None → Some(env), which IS a
  watch::changed() notification — the early subscriber wakes
  exactly when state finally arrives.

Session tasks consume the stream by filtering the cold-start
placeholder:

  while rx.changed().await.is_ok() {
      if let Some(env) = rx.borrow_and_update().clone() {
          // forward Some(env) as ServerMessage::State
      }
  }

The cache + broadcast stay independent — apply_subscribe still uses
the cache for snapshot frames; broadcast handles the live edge.

New regression tests:
  - subscribe_before_any_send_yields_none_then_wakes_on_first_send
    covers the exact cold-start path.
  - cold_start_subscribers_for_different_kinds_wake_independently
    proves lazy-init per kind doesn't coalesce streams.

Existing tests updated for the Option wrapper.

Closes BLOCK on #1603.
… machine (task #252)

Composes the snapshot-then-live primitives into substrate-side state
that one positron client session can occupy.

Ships:

- `Substrate` — coordinator wrapping cache + broadcast. `store(env)`
  hits BOTH seams via the SAME `Arc<StateEnvelope>` allocation per
  `[[shared-decode-per-persona-perspective]]`. Substrate code that
  produces state can no longer accidentally hit one seam and not
  the other (the silent-bug class where new state shows up at
  subscribe-time but never as a live update, or vice versa).

  `SubstrateStateCache::store_arc` added to support the shared-
  allocation path — cache.store_arc(arc) instead of cache.store(env)
  then cache wrapping it in another Arc. Old cache.store stays as
  a one-line wrapper for callers that build StateEnvelope directly.

- `Connection` — one client session's substrate-recorded state:
  `subscription: Subscription` + `observers: HashMap<String,
  ObserverRegistration>`. Mutated in place as ClientMessages
  arrive. Single dispatch point: `Connection::handle(msg, substrate,
  dispatcher) -> Vec<ServerMessage>` matches the variant
  exhaustively (no [[no-fallbacks-ever]] hole) and delegates to
  the existing apply_subscribe / apply_observe / apply_command
  primitives.

- Three doctrine pins at the connection layer:
  - `resubscribe_replaces_not_merges` — the §"Subscribe is
    declarative (replace, not merge)" doctrine carried up from
    Subscription::replace to the connection's subscription field.
  - `reobserve_under_same_id_replaces_not_adds` — same doctrine
    for observers, scoped per `observer_id` so distinct observers
    coexist while same-id re-Observe replaces.
  - `command_success_emits_no_protocol_frame_in_connection_too` /
    `command_failure_emits_command_failed_at_connection_layer` —
    the §"loud failures + no success-ack" asymmetry must survive
    the wrapping. Multi-layer wrappers are exactly the surface where
    "I'll just add a success ack here for convenience" sneaks in.

What this slice does NOT ship (slice 2D-3):

- Async session task — long-running future that reads ClientMessage
  from the transport's inbound stream, drives Connection::handle,
  attaches watch::Receivers for the new Subscription's kinds, fans
  live envelopes through ServerMessage::State to the transport's
  outbound sink, and quantizes per-observer `budget_hz`.

The Connection state machine in this slice is the building block
that the async task composes. Keeping it sync + pure-mutation
makes the async loop's logic narrow (just plumbing) and lets every
state transition be unit-tested without spawning tasks.

54/54 tests green (49 lib + 5 integration). +12 new tests for
this slice (3 substrate + 9 connection).

Stacks on PR #1603 (slice 2D-1: broadcast primitive).

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

Rebasing the Substrate coordinator + Connection state machine onto
the new #1602 (CommandDispatch takes whole envelope) and #1603
(Broadcast::subscribe always returns Receiver<Option<...>>) requires
two mechanical follow-throughs that this commit makes:

- connection.rs ScriptedDispatcher takes `envelope: CommandEnvelope`
  instead of `(command: String, params: Value)` and records
  `Vec<CommandEnvelope>`. The unused `Value` import goes too.
- substrate.rs tests unwrap the new Option layer at the borrow:
  `rx.borrow().clone().expect("broadcast populated")`. Direct
  Option-unwrap calls on the Receiver (`.expect()`, `.unwrap()`) no
  longer compile because subscribe() always returns a Receiver, not
  an Option<Receiver>.

No behavioral change beyond the trait/type cascade. The
provenance-preserving dispatch + cold-start-safe broadcast continue
to compose through the Connection state machine and Substrate
coordinator unchanged.
@joelteply
joelteply force-pushed the feat/continuum-positron-session-2d-task branch from 0c42f8c to 3331332 Compare June 10, 2026 23:49
@joelteply
joelteply changed the base branch from feat/continuum-positron-session-2d-broadcast to canary June 10, 2026 23:49
@joelteply

Copy link
Copy Markdown
Contributor Author

Audit (per @cambriantech/Fable ruling): rebased onto canary (which now has substrate #1600 + slice-2A/2BC squash via #1601/#1605). PR now bundles slice 2D-1 (broadcast primitive) + cold-start fix + slice 2D-2 (Substrate + Connection) + cascade fix — all 4 commits because #1603's replacement-PR path got blocked by the same trap (its base died). Content unchanged from your re-verify-approved #1603 + #1604 verdicts (comments 4675726039 + 4675724283); approval transfers; verified by rebase + 51 unit + 5 integration tests green on canary HEAD.

Fable's discipline (rebase + retarget WHILE OPEN) DID work here because #1604 was still open — but gh pr edit --base canary silently no-ops when GraphQL emits an unrelated project-classic warning. Had to use gh api -X PATCH .../pulls/1604 -f base=canary directly. Filing as a sibling to airc gap card 6967921d.

@joelteply
joelteply merged commit a0149e4 into canary Jun 10, 2026
2 checks passed
@joelteply
joelteply deleted the feat/continuum-positron-session-2d-task branch June 10, 2026 23:49
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