Cart feature flag (default OFF) + Session JSONL streaming over MoQ | SageOx
Cart feature flag (default OFF) + Session JSONL streaming over MoQ
Context
Customer rollout is imminent. Two workstreams:
Cart must vanish for customers.ox carts / ox cart-analyze and their 4 Claude slash commands are fully visible today. Feature-flag them, default off, zero customer-facing surface — team keeps dogfooding via flag. Cart shipped in v0.10.1, so cleanup of already-installed machines matters.
Session streaming (design + build). In parallel to the existing stop-time git-commit upload, stream each coding session's redacted JSONL to the cloud live over MoQ (same transport family as speaker/ox-dot audio). Streaming failure must never block or error a session today; local buffering covers outages. Applies uniformly to every agent we shim (Claude Code, Codex, Gemini, Droid, Amp, …). Format follows sageox-mono conversation/turns conventions. Serious test harness.
Plan was adversarially reviewed by 4 principal-engineer panels (security, streaming correctness, daemon fit, simplicity/completeness — daemon reviewer died on API error; its surface was covered by the other three). All confirmed findings folded in below.
internal/flags/ is the layered flag system (defaults → daemon remote settings → FEATURE_* env). TUIEnabled: false + cmd/ox/dashboard.go (Hidden + runtime refuse) is the default-OFF template.
session.RawWriter.WriteEntry (internal/session/raw_writer.go:120) is the build-enforced single writer of raw.jsonl; 3-layer secret redaction runs inside it, synchronously, before encode. Correction (review): live-recorded entries have no seq/eid — the seq-injecting SessionWriter (internal/session/store.go:223) is NOT used by either live producer. Seq must be added.
Two live producers: daemon tail mode (internal/daemon/agentwork/session_watcher.go — hookless agents) and transient CLI hook process (cmd/ox/agent_hook.go — Claude Code, never touches the daemon).
Pause/resume is upload-time filtering, not write-time (internal/session/classify.go:52, ADR-020): raw.jsonl keeps receiving entries while paused; the suspended seq range is excluded only when assembling the upload. Any live streamer must implement its own pause exclusion.
A second, deferred redaction tier exists: pre-push auto-redact/quarantine (cmd/ox/prepush_autoredact.go), manual ox session redact (cmd/ox/session_redact_history.go), catalog-update re-scans. All amend the LOCAL copy after write time — live streaming forfeits this net unless compensated.
sageox-mono MoQ canon: vendored kixelated moq-lite relay (WS ingress TCP/443 + QUIC UDP/4443), HS256 JWT minted by api-go internal/moqtoken (access = put/get claims only; kid required; root must equal connect path), broadcast naming sage/{ctx}s/{ctxId}/{recId}/{usrId}[~nonce], coordinates handed out by API (mode:"moq" → {broadcast_name, relay_url, jwt}, JWT ~1 h expiry), three-plane model (ADR-067/071: data = publish-only; receipts = out-of-band SSE watermark (Option A, what mono actually shipped); control = separate subscribe track, "bidirectional via composition").
moq-lite-04 wire facts: qmux caps a STREAM frame at 16 KiB (larger objects need OFF+LEN fragmentation); a MoQ group is the resume/replay unit (mono producers refuse to resume mid-group); no object-level ack exists in the protocol — a successful send means bytes left the producer, nothing more (ADR-071's core point).
speaker repo has a stdlib-only Go twin MoQ relay (speaker/tools/twin-moq-relay/, decoder currently draft-09, moving to lite-04) — reference for our publisher codec and in-tree test twin. Not in this workspace; codec is written fresh against speaker/firmware/moq_embed/docs/moq-lite-04-wire-reference.md.
internal/flags/flags.go: add CartsEnabled bool to Flags + *bool to Patch; Defaults() sets false // off until remote settings or env enables it.
internal/flags/env.go: map FEATURE_CARTS via envBoolPtr; extend allNil.
internal/flags/remote.go: add Carts *bool to CLIFeatures + wire in RemoteSettingsToPatch (nil-safe for old servers).
internal/flags/resolve.go: extend applyPatch.
Command gating
cmd/ox/carts.go: Hidden: true on cartsCmd + PersistentPreRunE gate on the parent (inherited by all 11 subcommands; runs before any RunE, so no dolt subprocess ever spawns while gated): error ox carts is not yet enabled — set FEATURE_CARTS=true or contact your team admin (dashboard.go pattern).
cmd/ox/cart_analyze.go: same — Hidden: true + gate at top of RunE.
Hidden removes them from ox --help, completions, and regenerated reference docs. "Teams:" group keeps 3 visible members (glance, murmur, teams) so no empty header. (Note only, no action: brandedHelp at root.go:265 would print an empty group header if a whole group were hidden — latent trap.)
Accepted leaks (deliberate): the refusal message names FEATURE_CARTS (dogfood-friendly, matches dashboard.go); explicit ox carts --help still renders (Hidden ≠ unavailable); the 4 command bodies stay embedded in the binary (required by conformance tests + flag-on install).
Slash-command install gating (new minimal mechanism — none exists today)
Policy lives in ox, adapter stays mechanical: ox init / ox doctor compute an exclude set from flags.Get() and pass it through the existing install-commands adapter call (cmd/ox/init.go:1916, cmd/ox/doctor_commands.go:44); cmd/ox-adapter-claude-code/commands.gooxCommandFiles() filters excluded names — the right single chokepoint: both handleInstallCommands and handleCheckCommands route through it, so doctor never reports the excluded files as missing.
Mark the 4 cart rows in internal/prime/capability_table.go:134-137 with a gate field (e.g. GatedBy: "carts") so the exclude set derives from the table — one source of truth. Conformance tests keep passing in both flag states because rows and embedded files always exist.
Cleanup (mandatory, not optional): cart shipped in v0.10.1 and agentx never prunes orphans — every machine that ran ox init/ox doctor since 2026-06-15 has ox-cart*.md installed and would keep a slash command that errors forever. ox doctor removes installed ox-cart* files when the flag is off, gated on the ox-hash ownership stamp (reuse IsCommandStale-style check) so a user's hand-authored file is never touched.
De-trace docs & release notes
Set Hidden + regen via ox docs (regen is the source of truth — drops cart pages and index.mdx nav links deterministically); commit the regen result.
cmd/ox/release_notes.md:49: LEAVE UNTOUCHED (Ryan ruling 2026-07-16). Cart shipped in v0.10.1; rewriting a tagged release's changelog falsifies history. The one-word historical mention in ox release-notes is accepted.
No changes needed: MCP tools, telemetry, README, marketplace plugin, prime output (verified clean). ADRs/specs/test fixtures mentioning cart stay (internal/historical, not runtime surfaces).
Dogfood story
This repo's own .claude/commands/ox-cart*.md stay (repo-local, never shipped). Team sets FEATURE_CARTS=true (note in CLAUDE.md Misc section); later the server enables features.carts for the sageox account via /api/v1/cli/settings (mono-side, not this PR).
Tests (review-corrected)
One cobra-level gate test (the only test that exercises the change): rootCmd.SetArgs(["carts","ready"]) → refusal with flag off; t.Setenv("FEATURE_CARTS","true") + flags re-init → gate passes. Same for cart-analyze.
Existing cart tests (carts_test.go, store_test.go, ledger_twin/cart_analyze_test.go) need no changes — none routes through the cobra gate (they call the store/analyze/marshal layers directly).
Install-exclusion test: flag off ⇒ oxCommandFiles() set excludes ox-cart*; doctor removes a pre-seeded stamped ox-cart file but leaves an unstamped one.
Conformance tests green in both states.
Release-gate check: grep sageox/ox-test-harness for cart usage before release (external integration suite would break on flag-off if it drives ox carts).
Workstream 2 — Session JSONL streaming over MoQ (FEATURE_SESSION_STREAMING, split into PR 2a transport / PR 2b daemon)
Core architecture: tail raw.jsonl, don't tee the writer
The daemon streams by tailing the already-redacted raw.jsonl from a persisted cursor — no RawWriter tee, no second buffer:
Buffering is free:raw.jsonl in the recording cache IS the local buffer. Relay down ⇒ cursor lags; recovery ⇒ resume from cursor. Survives daemon restarts, covers offline-for-hours.
Failure isolation by construction: streaming code is read-only on the file, separate goroutines; cannot block or corrupt capture. Satisfies "never an error/blocker today."
Uniform across all agents: both live producers converge on raw.jsonl; one tailer covers every adapter. Batch-rewrite paths (regenerate/redact/import) excluded by only streaming active recordings.
Inline redaction inherited: streamed bytes come from the post-inline-redaction file. (Correction of scope — review:) this covers the inline tier only; the deferred tier (pre-push auto-redact, manual redact, catalog re-scans) fires after bytes may already have streamed. See "Retroactive redaction" decision below.
Matches specs' stated intent (docs/specs/adapter-protocol.md:464 — "the daemon decides the upload policy").
Loading diagram...
Mermaid diagram
Correctness requirements from review (all first-class spec items, not afterthoughts)
Pause-awareness (CRITICAL). The publisher consults RecordingState.SuspendedAt + lifecycle pause markers and refuses to publish any entry whose seq falls in an open or closed suspended range (read cursor still advances). Without this, live streaming ships exactly the content the user paused to keep out — irrecoverably (MoQ has no retraction).
Real seq (CRITICAL). Add Seq int64 + Eid string to session.SessionEntry; RawWriter.WriteEntry stamps them (running count since header, persisted). Fixes every consumer, matches the raw-jsonl spec's stated intent, gives the stream its ordering/dedup key. Touches the chokepoint file — additive, redaction path unchanged.
Honest ack semantics (CRITICAL). Cursor-advance = local WS send success only — NOT durability (moq-lite has no object ack; ADR-071). v1 is explicitly best-effort duplicate; git upload remains the durability authority. The future receipt plane mirrors mono's shipped Option A (out-of-band SSE archived watermark), not the rejected in-band variant.
Torn-line safety. New raw-jsonl ParseLineFunc (header/entry/footer dispatch — 3 JSON shapes) consumes only \n-terminated lines; on EOF with unterminated trailing bytes, do not advance — retry next tick. (Existing TailWatcher Scanner behavior would corrupt multi-MB tool_output entries.)
Fragmentation + rotation + caps. OFF+LEN multi-frame fragmentation from day one (16 KiB qmux frame cap); group rotation on small bound (N entries / M seconds) so reconnect never re-sends unbounded groups; cap oversized tool_output payloads before framing. Publisher read-ahead bounded by bytes (backpressure), not entry count.
Daemon lifecycle.sessionstream.Manager re-attaches to live sessions on daemon start (DetectAndRestart pattern); hook-mode session activity feeds the daemon inactivity timer (heartbeat) so a live Claude Code session can't let the daemon idle-exit mid-stream (1 h timeout, internal/daemon/config.go:148).
Rewrite guard.rewriteRawJSONL (cmd/ox/session_regenerate.go:747) refuses to rewrite a session with an active recording (today only protected by directory topology).
Cursor hygiene.stream-cursor.json 0600, atomic temp+rename, clamped to file size on load; declared safe-to-lose (restart from 0 is correct under at-least-once). sent_at is observational only; seq is the sole ordering/dedup authority.
Security requirements from review
Server-authoritative enable:FEATURE_SESSION_STREAMING=true alone cannot exfiltrate — streaming starts only after the authenticated coordinates call succeeds, so the cloud (account-level feature check in api-go) is the authoritative gate; env is a local opt-in only. ox status shows session streaming: active (visible indicator).
JWT lifecycle: coordinates re-fetched on reconnect/near-expiry (JWTs are ~1 h; sessions run longer); daemon uses OAuth refresh (EnsureValidToken) for that call; JWT held in memory only, never persisted beside the cursor.
Codec = untrusted-input surface: strict bounds checks + frame/object size caps on every decoded field; wss:// required for non-loopback; never InsecureSkipVerify; OX_ALLOW_PLAINTEXT_ENDPOINT does not loosen MoQ TLS except loopback (twin tests). Mirror lfs/client.go:139 fail-closed posture.
Retroactive redaction (DECISION for Ryan — recommended default below): live streaming forfeits the deferred redaction net. Recommendation: ship v1 live streaming dogfood-only with (a) the plan's safety claim corrected (inline tier only), (b) a cloud purge/re-redact API keyed (session_id, seq) specified in the mono contract and called by the retroactive-redact paths when streaming was active, and (c) customer enablement blocked until that purge path exists server-side. Alternative (rejected as default): stream only at stop-time post-prepush — kills the live value.
Mono-side contract requirements (documented, enforced there): session archiver holds the narrowest get (per-team, ideally per-broadcast JIT), separate service identity + prefix namespace from the audio archiver; recommend asymmetric signing (EdDSA/RS256) so the relay can verify but not mint.
Stream format (spec doc: new docs/specs/session-streaming.md)
KBTurnLine/turns.jsonl field-mapping table lives in the spec as "future" — documented so cloud ingestion can go conversation-native (cnv_ twin) without a format break, but NOT built until mono locks the consumer.
At-least-once, duplicates possible: server dedup on (session_id, seq) is an unbuilt cross-repo dependency — flagged as such; twin harness exercises dedup locally so the property is tested by something before mono ships.
Transport: moq-lite-04 over WebSocket, pure Go (PR 2a — standalone, provable in isolation)
New internal/moq/ package (layered like internal/lfs/): client.go (WS dial, SETUP/ANNOUNCE, JWT opaque bearer, fail-closed), codec.go (moq-lite-04 publisher-side wire per the wire reference, incl. OFF+LEN fragmentation), publish.go (broadcast announce, catalog.json track + conversation track, group rotation).
Why WS not QUIC: relay already exposes WS ingress on TCP/443 (firewall-friendly), the ESP32 firmware proves the path, no Go moq client exists so we write a thin one either way, avoids the quic-go dep. Only new dep: coder/websocket (MIT — allowed).
Coordinates from the cloud, never minted locally (secret sauce stays behind the API): daemon calls a new api-go endpoint — request {session_id, session_name} → {broadcast_name, relay_url, jwt} — the coding-session analog of recordings mode:"moq". ox treats all three as opaque.
In-tree twin: internal/moq/moqtest/ — stdlib WS server accepting SETUP/ANNOUNCE/OBJECT, records frames, minimal fault hooks (reject JWT, drop mid-group, stall). Round-trip goldens against it.
Daemon integration (PR 2b): new internal/daemon/sessionstream/
Manager: discovers active recordings (.recording.json scan, same as finalize Detect()), one publisher goroutine per session: raw-jsonl tailer → pause filter → envelope → fragment → publish → persist cursor. Cursor in the session cache dir (complies with .claude/rules/ledger-cache.md).
Resilience: resilience.CircuitBreaker + cenkalti/backoff; reconnect re-fetches coordinates and resumes from cursor at a group boundary; all failures log-only (single-line key=value), never surfaced to session flow.
Bi-directional: reserved, not built — spec documents ADR-071 composition (parallel Subscriber on a control track, idempotent commands); v1 publish-only.
Flag off ⇒ Manager never constructed: zero goroutines, zero files, zero network.
Test harness (trimmed to what proves the pipe — simplicity review; grow later)
One twin round-trip E2E (2b): scripted session via test adapter → daemon streams to twin → twin's received JSONL ≡ redacted raw.jsonl entries minus paused ranges (byte-level property) → session stop → git path also completes untouched.
Cursor crash-safety (2b): crash-at-every-step around publish/cursor-write; restart; no loss, dupes allowed; twin-side dedup on (session_id, seq) yields exact set.
Pause test (2b): pause mid-session, emit entries, resume — paused seq range never appears at twin.
Flag-off test: zero network, zero stream files.
Deferred until mono locks the consumer contract: 5-way relay fault matrix, full golden wire suite, slow-tagged staging-relay integration.
Cloud-side contract (sageox-mono — separate repo, documented not implemented here)
Coordinates endpoint (+ account feature check = the authoritative enable) minting via existing moqtoken (put on the session broadcast, 1 h, kid, root-matched).
Purge/re-redact API keyed (session_id, seq) — prerequisite for customer enablement (see decision).
JSONL archiver analog subscriber (narrow get, separate identity) into conversation-native storage; server dedup on (session_id, seq).
Until mono ships, the twin relay stands in; the ox side is fully testable.
Small addition — PR customer-value rule (you asked)
.claude/rules/releases.md:31 already mandates "Lead with customer value — always" for release notes only. Nothing says it for PR descriptions. Add one line to the CLAUDE.md Pull requests paragraph: PR summaries lead with customer/coworker value (what a coworker can now do or what pain is gone), mechanism second — mirroring releases.md. Folded into PR 1.
Decisions for Ryan (per Required Reviews)
ChangelogRESOLVED: release_notes.md untouched.
Retroactive-redaction policy: recommended = live streaming dogfood-only now; customer enable blocked on mono purge API. Confirm or choose stop-time-only streaming.
New env vars: FEATURE_CARTS, FEATURE_SESSION_STREAMING (established FEATURE_* pattern, both default off). New remote settings fields: features.carts, features.session_streaming.
New files under session cache dir only (stream-cursor.json) — no ledger/team-context path changes; stream coordinates sourced from cloud API (API-source-of-truth rule respected).
Execution order & tracking
Beads epics at execution start: cart-flag and session-streaming (tasks per section, each loaded with this plan's context).
Branch: current ryan/cart-flag-and-jsonl-streaming for PR 1; PR 2a/2b stacked after.
Verification
make lint && make test green with defaults (both flags off); make test-all for LFS/twin tiers.
Manual: ox --help shows no cart; ox carts refuses; FEATURE_CARTS=true ox carts ready works; ox docs regen has no cart pages; fresh ox init in scratch repo installs no ox-cart*; doctor removes stale stamped ones; grep ox-test-harness for cart.
Streaming: scripted session + twin relay + FEATURE_SESSION_STREAMING=true; kill/restore twin mid-session; pause mid-session; verify twin transcript ≡ redacted raw.jsonl minus paused ranges and git upload still completes. Flag off: no stream artifacts.