Skip to content

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

Merged
joelteply merged 2 commits into
feat/continuum-positron-substratefrom
feat/continuum-positron-session-2a
Jun 10, 2026
Merged

joelteply merged 2 commits into
feat/continuum-positron-substratefrom
feat/continuum-positron-session-2a

Conversation

@joelteply

Copy link
Copy Markdown
Contributor

Summary

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

Stacked on #1600 (slice 1 substrate scaffold). Auto-rebases to canary when #1600 merges.

Joint workstream with Fable (@2a183194). Her v0.1.0 session protocol just merged as positron#2 (CambrianTech/positron). This PR is the continuum-side counterpart that consumes the typed session frames.

Slice 2A scope

  • 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; 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 snapshot-then-live 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. Function refuses non-Subscribe variants loudly per [[no-fallbacks-ever]].

The load-bearing skip rule

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. Renaming this test or changing its assertion is a regression.

Out of scope for 2A

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

Small follow-up for positron-core

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-core for downstream consumers who want HashSet-typed layer sets — non-blocking.

Doctrines

  • [[no-fallbacks-ever]] — apply_subscribe refuses non-Subscribe variants loudly; cache get() returns None not synthetic empty; Subscription::replace is the only constructor (no merge arm).
  • [[strong-typing-across-boundaries]] — Subscription is a typed value, not a HashMap-of-strings. Subscription::covers is the typed gate.
  • [[shared-decode-per-persona-perspective]] — cache stores Arc<StateEnvelope>; multiple subscribers' snapshots share the underlying allocation.

Test plan

Architecture docs

  • positron/positron-core/src/session.rs — the session protocol this PR implements the substrate side of
  • docs/planning/ALPHA-GAP-ANALYSIS.md §6 — the alpha blockers the positron contract closes structurally

… 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]>
@joelteply

Copy link
Copy Markdown
Contributor Author

SENTINEL VERDICT: BLOCK — does not compile against the normative contract (positron-core v0.1.1)

error[E0004]: non-exhaustive patterns: `&ServerMessage::CommandFailed { .. }` not covered
  --> core/continuum-positron/src/session.rs:242:15
  --> core/continuum-positron/src/session.rs:373:15

This head was written against positron-core 0.0.1 (pre-CommandFailed); the committed Cargo.lock says 0.0.1 but a path dep pins nothing — anyone with positron at v0.1.1 checked out gets a red cargo test on canary the moment this merges. #1602 currently smuggles the fix (the two other => panic!(...) arms added to these exact matches in its session.rs delta). Those arms belong in THIS PR — every merge point in a stack must be green on its own. Fold them in (and ideally pin the dep per my #1600 comment) and this flips to approve.

Protocol conformance of the delta itself is otherwise verified:

  • Skip rule is EXACT equality — should_skip uses ==, never >=; never-skip when cache revision is None or when last_seen has no entry for the kind. Pinned by higher_last_seen_does_NOT_skip_per_protocol_load_bearing_invariant (client@500 vs substrate@3 sends the snapshot — the counter-reset case the spec exists for).
  • Subscribe is declarative REPLACE — Subscription::replace is the only constructor from a frame; no merge method exists; layers deduped defensively.
  • Per-kind independence pinned (multiple_kinds_partition_snapshots_independently, unrelated_last_seen_does_not_match_chat).
  • Honest no-snapshot for kinds without cached state (no synthetic empty envelopes) — consistent with the spec's "the skip is purely an optimization; when in doubt, send" plus no-fabrication.

One non-blocking spec ambiguity worth a doc line: snapshot emission ignores layers entirely — a Subscribe { kinds: ["chat"], layers: [] } ("empty = none") still gets a chat snapshot. Defensible under when-in-doubt-send, but state which reading you intend.

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.
joelteply added a commit that referenced this pull request Jun 10, 2026
…h 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]>
@joelteply

Copy link
Copy Markdown
Contributor Author

SENTINEL VERDICT (round 2): APPROVE — head df717b33d compiles standalone and is green against positron-core v0.1.1 (23/23 unit tests, path dep resolved to a v0.1.1 worktree, workspace version 0.1.1).

The fix closes the round-1 BLOCK correctly:

  • The two formerly non-exhaustive ServerMessage matches (session.rs:242, :374) now carry other => panic!(...) arms — and both sit in mod tests, asserting on frames apply_subscribe just CONSTRUCTED. These are substrate-outbound frames; the substrate is the sender of ServerMessage, never the receiver, anywhere in this crate (verified: the only production-side ServerMessage expression is the construction at session.rs:176; no inbound match exists). A panic in a test assertion on the producer's own output is decisive-test hygiene, not a forward-compat violation — the skip-and-log rule binds consumers of inbound frames, and there are none here.
  • Drift check: the panic arms are byte-identical to the hunks removed from feat(positron): slices 2B+2C — Observe handler + Command dispatch (CommandFailed asymmetry) #1602's rebased feature commit — moved down the stack, not rewritten. No other content changed in this PR vs round 1.

Protocol conformance re-confirmed unchanged: exact-equality skip (higher_last_seen_does_NOT_skip_per_protocol_load_bearing_invariant green), declarative replace, per-kind partition, honest no-snapshot for uncached kinds.

Carried risk notes (non-blocking, unchanged from round 1): the dep is still an unpinned path dep ("both repos side-by-side"), so green-ness depends on the operator's positron checkout being v0.1.1 — the git-rev pin promised "on first cut" is now due since v0.1.1 is tagged. The layers-ignored-for-snapshots ambiguity also still wants its doc line.

@joelteply
joelteply merged commit d4424c0 into feat/continuum-positron-substrate Jun 10, 2026
2 checks passed
@joelteply
joelteply deleted the feat/continuum-positron-session-2a branch June 10, 2026 23:40
joelteply added a commit that referenced this pull request Jun 10, 2026
…h 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]>
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 added a commit that referenced this pull request Jun 10, 2026
Per @cambriantech/Fable's priority ruling on the positron-merge follow-ups:
the v0.1.1 pin protects the whole just-merged substrate stack from the next
positron-core change. Without it, the build silently follows whatever
positron checkout lives under the operator's side-by-side parent dir.

That ambiguity is exactly what produced #1601's compile break: slice 2A's
head compiled only against a stale local checkout, and the protocol drift
surfaced as a sentinel BLOCK at review time instead of as a `cargo check`
error at author time. With the tag pin, the build follows the upstream
v0.1.1 release commit explicitly, and any later positron-core change is a
deliberate dep bump.

Cargo.lock locks to the upstream v0.1.1 tag commit. 51 unit + 5 integration
tests on continuum-positron pass against the pinned dep.

Closes Joel's verdict follow-up on #1600.
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