源码快照 @ 2026-09-01 (source-only, 剔除非源码素材)
Publish Claude Code Binaries / Stage and publish binaries (push) Canceled after 0s
Publish Tutti App Runtime / Build darwin-arm64 (push) Canceled after 0s
Publish Tutti App Runtime / Build darwin-amd64 (push) Canceled after 0s
Publish Tutti App Runtime / Build linux-amd64 (push) Canceled after 0s
Publish Tutti App Runtime / Build windows-amd64 (push) Canceled after 0s
Sync Tutti Agent Skills / sync (push) Canceled after 0s
Windows Agent Adapters / Test Windows agent adapters (push) Canceled after 0s
Windows Daemon Adapters / Test Windows daemon adapters (push) Canceled after 0s
Publish Tutti App Runtime / Publish runtime catalog (push) Canceled after 0s
Publish Claude Code Binaries / Stage and publish binaries (push) Canceled after 0s
Publish Tutti App Runtime / Build darwin-arm64 (push) Canceled after 0s
Publish Tutti App Runtime / Build darwin-amd64 (push) Canceled after 0s
Publish Tutti App Runtime / Build linux-amd64 (push) Canceled after 0s
Publish Tutti App Runtime / Build windows-amd64 (push) Canceled after 0s
Sync Tutti Agent Skills / sync (push) Canceled after 0s
Windows Agent Adapters / Test Windows agent adapters (push) Canceled after 0s
Windows Daemon Adapters / Test Windows daemon adapters (push) Canceled after 0s
Publish Tutti App Runtime / Publish runtime catalog (push) Canceled after 0s
This commit is contained in:
commit
2ed3415fb7
8018 files changed
+1936476
No files matched your search
@@ -0,0 +1,47 @@
|
||||
# ADR 0001 — Codex app-server codegen: full generated surface, subset wiring
|
||||
|
||||
- Date: 2026-07-02
|
||||
- Status: Accepted (grilling session)
|
||||
- Context: protocol generation for the Codex app-server layer refactor.
|
||||
|
||||
## Decision
|
||||
|
||||
Port-and-slim codex-sdk-go's `internal/codegen` generator into tutti's
|
||||
`codexproto` package (design option **a**, not hand-written stubs and not
|
||||
vendoring the SDK's generated output).
|
||||
|
||||
- **Codegen surface = full.** Generate the complete protocol surface
|
||||
(~84 client methods / 8 server requests / 64 notifications) from the upstream
|
||||
`export`, plus the unavoidable hand-maintained type supplement
|
||||
(cf. SDK `protocol/manual_types.go`, 214 lines — go-jsonschema cannot express
|
||||
the whole schema).
|
||||
- **Wiring = subset.** This refactor's steps wire only the four-state-machine
|
||||
subset tutti actually uses today (~21 client / 4 server-req / 22 notif);
|
||||
the rest of the generated surface is additive and unwired (Step 1 is
|
||||
"purely additive").
|
||||
- **Full capability alignment is a direction, not this refactor's wiring scope.**
|
||||
Keeps the design's out-of-scope boundary (fork/compact/realtime/inject_items
|
||||
wiring) and the one-state-machine-per-step discipline intact, while laying the
|
||||
generator foundation so future alignment is "re-run + wire", not "write a
|
||||
generator".
|
||||
|
||||
## Why not
|
||||
|
||||
- **(b) hand-write stubs for the subset:** minimal now, but re-writing 156 stubs
|
||||
by hand for future full alignment and chasing every codex version bump is the
|
||||
exact cost a generator exists to remove.
|
||||
- **(c) vendor SDK's generated `protocol/`+`rpc/`:** pinned to an older codex
|
||||
commit (`e2b60462`) that lacks methods tutti already uses
|
||||
(`collaborationMode/list`), and inherits the SDK's facade opinions —
|
||||
contradicts D5 supply-chain stance for daemon core.
|
||||
|
||||
## Evidence
|
||||
|
||||
- SDK generator is `codex-sdk-go/internal/codegen/main.go` (1066 lines):
|
||||
runs Rust `export`, feeds JSON Schema → go-jsonschema → `protocol/types_gen.go`
|
||||
(3973 lines), and separately renders `rpc/*_requests_gen.go` from the
|
||||
`ClientRequest.json`/`ServerRequest.json` `oneOf` method-unions.
|
||||
- Generated files are stamped by codex git commit, not version string.
|
||||
- tutti uses ~25% of the client surface today; 3 used methods
|
||||
(`initialize`, `initialized`, `collaborationMode/list`) are NOT in the SDK's
|
||||
generated output — version/commit skew.
|
||||
@@ -0,0 +1,61 @@
|
||||
# ADR 0002 — codexproto: pinning, source acquisition, drift tolerance
|
||||
|
||||
- Date: 2026-07-02
|
||||
- Status: Accepted (grilling session)
|
||||
- Context: Step 1 codegen inputs. Corroborated by two independent real
|
||||
consumers: `codex-sdk-go` (Go) and `t3code/effect-codex-app-server` (TS).
|
||||
|
||||
## Decisions
|
||||
|
||||
### Pinning (Q3-A)
|
||||
|
||||
- codexproto is generated against an explicit **codex git commit SHA**, stamped
|
||||
into `metadata_gen.go` (cf. codex-sdk-go `Source codex commit:` and t3code
|
||||
`meta.gen.ts` `Upstream protocol ref:`).
|
||||
- The Step-0 runtime **binary** baseline (`codex-cli 0.142.5`) and this **source
|
||||
SHA** are recorded together in the bug-corpus/baseline doc. They are distinct
|
||||
axes: source SHA governs the typed surface; binary version is what the daemon
|
||||
actually spawns.
|
||||
|
||||
### Source acquisition (Q4 → option 1)
|
||||
|
||||
- **Vendor the upstream _already-committed_ `schema/json/*.json` at the pinned
|
||||
SHA. Do NOT run the Rust `export` bin.** The schema artifacts are tracked in
|
||||
the codex repo (`git ls-files codex-rs/app-server-protocol/schema/json`), so
|
||||
no Rust toolchain or local codex checkout is required.
|
||||
- **Eliminates design Risk #1** ("codegen toolchain depends on the Rust export
|
||||
bin"). Ops-2 becomes: vendor committed schema at pinned SHA + CI re-fetches the
|
||||
same ref and diffs.
|
||||
- Generator = adapted `codex-sdk-go/internal/codegen` (Go, go-jsonschema), with
|
||||
its `exportSchemas` (run-Rust) step **replaced** by "read vendored JSON".
|
||||
|
||||
### Drift tolerance (Q3-B)
|
||||
|
||||
- The runtime codex binary floats (auto-updates) relative to the pinned source.
|
||||
The CI drift check only catches codexproto-vs-pinned-source drift, NOT
|
||||
codexproto-vs-running-binary drift.
|
||||
- Therefore: generated types **allow unknown fields**, and notification/server-
|
||||
request dispatch keeps an explicit **unknown-method fallback** (cf. t3code
|
||||
`handleUnknownServerRequest` / `handleUnknownServerNotification`) that logs and
|
||||
degrades instead of crashing. This preserves the tolerance `map[string]any`
|
||||
has today. Extends the Step-4 "lossless tier / degradable events" principle
|
||||
down into the decode layer.
|
||||
|
||||
### Manual type supplement
|
||||
|
||||
- A hand-maintained supplement is unavoidable and universal across consumers
|
||||
(codex-sdk-go `manual_types.go` 214 lines; t3code `ManualSchemas`).
|
||||
- **`collaborationMode/list` is "used-but-unexported":** tutti calls it live
|
||||
(`codex_appserver_adapter.go:807`, feeding `turn/start`'s `collaborationMode`),
|
||||
but it is absent from upstream `ClientRequest.json` and from both reference
|
||||
consumers' generated output. It goes in tutti's manual supplement — NOT
|
||||
deleted, NOT expected from the generator.
|
||||
|
||||
## Evidence
|
||||
|
||||
- `git ls-files` lists `ClientRequest.json`, `codex_app_server_protocol.schemas.json`,
|
||||
`…v2.schemas.json` → schema is committed upstream.
|
||||
- t3code `generate.ts`: `UPSTREAM_REF` SHA + GitHub API `?ref=` fetch of committed
|
||||
JSON; `ManualSchemas`; `handleUnknown*` fallbacks.
|
||||
- collaborationMode exists upstream only as a ServerNotification/ThreadSettings
|
||||
field, never as a `collaborationMode/list` method.
|
||||
@@ -0,0 +1,108 @@
|
||||
# ADR 0003 — Step 3: thread registry + sub-agent event routing (identity-preserving)
|
||||
|
||||
- Date: 2026-07-02
|
||||
- Status: Accepted (grilling session)
|
||||
- Context: Step 3 (state machine B) replaces #602's foreign-thread drop-filter
|
||||
(`appServerNotificationThreadMismatch`). Decided by comparing three real
|
||||
consumers: t3code, and traycer's `subagent-nesting.ts` GUI protocol.
|
||||
|
||||
## Decision: identity-preserving routing (design "option 丙"), NOT suppression
|
||||
|
||||
The daemon routes sub-agent (child-thread) events **preserving child identity**,
|
||||
rather than dropping them (rejected option 1) or flat-re-tagging them into the
|
||||
parent turn (t3code's re-tag path, rejected — see Concurrency).
|
||||
|
||||
### Mechanism (daemon reducer, single-owner)
|
||||
|
||||
1. **Child→parent linkage from the parent item, not `parentThreadId`.** Seed a
|
||||
`map[childThreadID]parent` from the parent `collabAgentToolCall` item's
|
||||
**`receiverThreadIds`** (required, present already on `item/started`
|
||||
status=inProgress). Confirmed by t3code (`rememberCollabReceiverTurns`).
|
||||
`Thread.parentThreadId` exists in the schema but is NOT needed.
|
||||
2. **Suppress child lifecycle/turn noise** (thread/\*, turn/started, turn/completed,
|
||||
turn/plan, item/plan/delta, tokenUsage…) — cf. traycer `SUBAGENT_SUPPRESSED_EVENTS`
|
||||
and t3code `shouldSuppressChildConversationNotification`.
|
||||
3. **Re-home the remaining substantive child events** (item/started, item/completed,
|
||||
deltas, reasoning) onto the parent session stream, **stamped with a new
|
||||
`OwnerThreadID`** = the child thread id (cf. traycer `parentBlockId` /
|
||||
agent-runtime "owner of this event for nested rendering").
|
||||
4. **Summary card unchanged:** the parent `collabAgentToolCall` item still drives
|
||||
the collab card's final status/output (`appServerCollabAgentRawOutput`); Step 0
|
||||
`TestAppServerCollabAgentCompletedCarriesResultOutput` stays green untouched.
|
||||
5. **Unknown/foreign threads** (not in the child map, e.g. grandchildren — nested
|
||||
spawns are suppressed so we never learn their mapping) keep the ADR-0002
|
||||
unknown-fallback (log + drop) for ordinary progress. A bounded one-entry-per-
|
||||
thread terminal buffer retains `turn/completed` and non-retry `error` until
|
||||
`receiverThreadIds` registers the child, then replays the terminal with the
|
||||
child identity. Threads that never register still age out and are dropped.
|
||||
|
||||
### Data-model change (seam into Step 4)
|
||||
|
||||
- Add optional **`OwnerThreadID string`** to `activityshared.Event`
|
||||
(`packages/agent/daemon/activity/events/activity_types.go`). Empty = top-level
|
||||
main agent; non-empty = produced by that sub-agent child thread. Plain string —
|
||||
agent-agnostic, no codex-wire type (honors D7). `AgentSessionID`/`ProviderSessionID`
|
||||
stay = the PARENT session so the event belongs to the parent conversation.
|
||||
|
||||
### Wiring scope this refactor vs deferred
|
||||
|
||||
- **Wired now:** the summary collab card (as today). `OwnerThreadID`-tagged child
|
||||
events are emitted-but-unrendered (additive) — same philosophy as Step 1.
|
||||
- **Deferred (Step 9 / desktop):** traycer-style named, collapsible, per-sub-agent
|
||||
live-progress cards, fed by data ALREADY in the stream via `OwnerThreadID`.
|
||||
This is what makes D10's "nested visualization made cheap by the registry"
|
||||
actually true — suppression (option 1) would have destroyed the data and broken
|
||||
that promise.
|
||||
|
||||
## Why not the alternatives
|
||||
|
||||
- **Option 1 (drop all child events):** minimal, but destroys child identity at the
|
||||
daemon → the deferred nested view would NOT be cheap (contradicts D10) and the
|
||||
traycer-quality UX is foreclosed.
|
||||
- **t3code re-tag-to-parent-turn (flat):** concurrent sub-agents + parent all share
|
||||
one turnId; the UI appends by turnId with no collab-awareness → **garbled
|
||||
interleaved output**. Loses child identity.
|
||||
|
||||
## Corrections to the design
|
||||
|
||||
- **D8:** no per-thread reducer. A single reducer + `map[childThreadID]parent` +
|
||||
a suppress-set + an `OwnerThreadID` stamp. Lighter than "route each notification
|
||||
to its own per-thread reducer".
|
||||
- **D10:** linkage is `receiverThreadIds` (parent declares children), not
|
||||
`parentThreadId`; "made cheap by the registry" REQUIRES identity preservation
|
||||
(`OwnerThreadID`), which this ADR guarantees.
|
||||
|
||||
## Concurrency semantics (verified)
|
||||
|
||||
- **Multiple sub-agents:** N spawns → N distinct `collabAgentToolCall` items
|
||||
(distinct itemId) → N cards; or one spawn with `receiverThreadIds:[t1..tN]` +
|
||||
plural `agentsStates` → one card, N lanes. Each child thread is its own
|
||||
`OwnerThreadID` lane → future UI renders separate cards, no garble.
|
||||
- **Parent + child simultaneous:** parent deltas flow on the parent stream;
|
||||
child deltas carry `OwnerThreadID` → never corrupt the parent's text.
|
||||
- **Ordering:** mapping is normally known at child announce time
|
||||
(`receiverThreadIds` required on item/started). Early ordinary child progress
|
||||
before the announce → unknown-fallback (log+drop); early terminal evidence is
|
||||
retained in the bounded terminal buffer and replayed only after registration.
|
||||
Registry map and pending terminal buffer are mutex-guarded.
|
||||
|
||||
## Ordering verification (2026-07-02, Phase 0)
|
||||
|
||||
ADR question: can child-thread events arrive before the parent
|
||||
`collabAgentToolCall` announces `receiverThreadIds`?
|
||||
|
||||
- **Transport analysis:** notifications share one stdio NDJSON connection, so
|
||||
delivery is strictly serialized; the only theoretical gap is the app-server
|
||||
internally enqueueing child output between the spawn item's `started` (which
|
||||
already carries the required `receiverThreadIds`) and the registration being
|
||||
processed - a sub-millisecond window on the same pipe.
|
||||
- **Empirical:** across all four exported log bundles (2026-07-02 sessions with
|
||||
4-5 concurrent children each), every declared receiver had a complete row
|
||||
set; no early-drop evidence.
|
||||
- **Permanent telemetry:** the daemon tracks unknown-thread drops per session
|
||||
(bounded) and, when a child registers late, logs
|
||||
`child events arrived before registration` with the lost-event count and
|
||||
records it on the thread context (`droppedBeforeRegistration`, pinned by
|
||||
`TestCodexAppServerChildRegistrationReportsEarlyDrops`). Terminal evidence is
|
||||
separately replayed exactly once when available, pinned by
|
||||
`TestCodexAppServerChildTerminalBeforeRegistrationIsReplayed`.
|
||||
@@ -0,0 +1,81 @@
|
||||
# ADR 0004 — Step 4: hydration snapshot cursor (monotonic sequence, not timestamp)
|
||||
|
||||
- Date: 2026-07-02
|
||||
- Status: Accepted (grilling session)
|
||||
- Context: Step 4 (Cluster A, daemon-half). Corroborated by t3code (event-sourced
|
||||
`sequence`) and traycer (append-only chat event log + snapshot reconcile).
|
||||
|
||||
## Finding that reframes the design
|
||||
|
||||
The design says "the daemon correctly holds the user row **at version=1**; the
|
||||
defect is desktop-rooted." **Version is not 1,2,3 — it is a millisecond
|
||||
wall-clock timestamp**: `reporter.go:375,510` set `Seq: uint64(timestamp)` where
|
||||
`timestamp = event.OccurredAtUnixMS` (fallback `time.Now().UnixMilli()`), and the
|
||||
store maps `Version = update.Seq` (`service.go:2495`). Consequences:
|
||||
|
||||
- **Not gap-free** (design calls the contract "gap-free"; a timestamp cannot be).
|
||||
- **Same-millisecond collision:** the user-prompt row and the first turn/reply
|
||||
event can share one Version V. With the desktop cursor at V, the
|
||||
`Version <= afterVersion` filter (`service.go:234`) drops BOTH — a **daemon-side**
|
||||
path to "user message disappears", independent of the desktop reconcile bug.
|
||||
- **Non-monotonic across sources / no user-before-reply guarantee** (ms clock).
|
||||
|
||||
So the "gap-free, clientSubmitId-keyed, resyncable" contract the design assigns to
|
||||
Step 4 does NOT hold today; the "defect is purely desktop-rooted" claim is
|
||||
incomplete — timestamp-as-cursor is a co-conspirator.
|
||||
|
||||
## Decision: split delivery-cursor from display-order
|
||||
|
||||
Both reference implementations separate a monotonic sequence (ordering/cursor)
|
||||
from a wall-clock timestamp (display) — t3code `sequence` + `occurredAt`;
|
||||
traycer append-log order + `timestamp`. tutti's conflation is the anomaly. Adopt
|
||||
the split, minimally:
|
||||
|
||||
1. **`Version` becomes a store-assigned per-session monotonic, gap-free counter**
|
||||
— the delivery cursor. Assigned at store ingest (`upsertSessionMessagesLocked`,
|
||||
the single `entry.mu` lock point) on first insert of a `MessageID`, in commit
|
||||
order; **preserved on merge** (already done, `service.go:2605`) so it is stable
|
||||
within a load and the cursor never regresses. Stop deriving it from `Seq=timestamp`.
|
||||
2. **Display order sorts primarily by `OccurredAtUnixMS`** (existing field), with
|
||||
the counter as tiebreak — replacing "sort by Version(=timestamp) then ID".
|
||||
This stays robust to out-of-order replay (a pure ingest-order counter would
|
||||
mis-order history if replay is not chronological).
|
||||
3. **Identity stays `MessageID = f(clientSubmitId)`** (`prompt_content.go:155-161`)
|
||||
— cf. traycer `messageId` + `clientActionId`. Already correct in tutti.
|
||||
4. **Self-heal = full resync at `afterVersion=0`** (already returns the complete,
|
||||
deduped, ordered set; desktop already loads at 0 — `createDesktopAgentHostApi.test.ts:1627`).
|
||||
|
||||
## Blast radius (verified)
|
||||
|
||||
- **No daemon data migration.** No disk persistence (`repo.go` 20 lines; no
|
||||
sqlite/bolt/WriteFile in `packages/agent/daemon`); `sessionMessages` is an
|
||||
in-memory map rebuilt from provider replay each load. Nothing persisted a
|
||||
timestamp-Version to be incompatible with.
|
||||
- **Per-session only.** Version comparison/sort is already per-session
|
||||
(`latestVersionBySession[sessionID]`, single-session sort) — a per-session
|
||||
counter drops in; no cross-session global comparison exists.
|
||||
- **Version is load-relative & ordering-only** (counter restarts per load; values
|
||||
shift if the replay prefix differs). Identity is `MessageID`, never the counter.
|
||||
Any consumer treating Version as a stable/global key must be corrected; the
|
||||
daemon does not.
|
||||
- **Mixed fleet absorbed:** desktop starts each session view at `afterVersion=0`
|
||||
and re-keys by `MessageID`, so a new-daemon/old-desktop pair renders correctly;
|
||||
cursor advances in-memory, not persisted across reloads.
|
||||
- **"User chats based on history":** replay assigns 1..N to history in order, new
|
||||
user prompt = N+1, reply = N+2; desktop reconciles the optimistic echo by
|
||||
`MessageID` regardless of counter values. History cannot disappear (always
|
||||
re-fetched at 0, keyed by MessageID).
|
||||
|
||||
## Scope boundary (explicit)
|
||||
|
||||
- **NOT in scope:** durable append-only event log / event sourcing (both
|
||||
references have it; tutti does not). The ephemeral store + monotonic cursor +
|
||||
resync-at-0 is sufficient to close the bug. Durable log = **future direction**,
|
||||
a separate effort.
|
||||
|
||||
## Corrections to the design
|
||||
|
||||
- "daemon holds user row at version=1 / defect is desktop-rooted" → **version is a
|
||||
ms timestamp; same-ms collision is a daemon-side contributor** to Cluster A.
|
||||
- Step 4 "gap-free contract" is an ASPIRATION today; this ADR makes it real via the
|
||||
monotonic counter.
|
||||
@@ -0,0 +1,128 @@
|
||||
# ADR 0005 — Turn lifecycle: full optimal (reconciled projection + non-blocking command/observe), risk-controlled
|
||||
|
||||
> **Terminology (reconcile with ADR 0004):** "projection" here means an **in-memory,
|
||||
> snapshot-reconciled** projection (folded from live events, reconciled against the
|
||||
> Step-4 snapshot, replay-rebuilt per load). It is NOT a durable append-only event
|
||||
> log — that remains **out of scope / future direction** per ADR 0004. The t3code/
|
||||
> traycer "single event log" is the _shape_ we borrow (one reconciled state for
|
||||
> turns+messages+approvals), not a commitment to persist an event log.
|
||||
|
||||
- Date: 2026-07-02
|
||||
- Status: Accepted (grilling session) — **commit to the optimal target, no compromise; de-risked by sequencing + strangler shim + shadow-compare**
|
||||
- Context: Step 5 (Cluster C) and its interaction with Step 4 (A) and Step 7 (D).
|
||||
Both reference consumers (t3code, traycer) converge on this shape; tutti's
|
||||
blocking `Exec` + single `activeTurn` slot + implicit 7-field state is the anomaly.
|
||||
|
||||
## Optimal target (the no-compromise end state)
|
||||
|
||||
A single per-session **projection** that folds ALL provider lifecycle
|
||||
(turn state + messages + compaction + approvals) into explicit state, reconciled
|
||||
against the Step-4 authoritative snapshot, behind a **non-blocking command/observe**
|
||||
adapter API:
|
||||
|
||||
1. **Turn state = reducer output**, an explicit `turnPhase` state machine
|
||||
(`idle → running → compacting → interrupting → terminal{completed|failed|canceled}`),
|
||||
never a parked goroutine. Terminal transitions are ordinary events
|
||||
(`turn/completed` ∪ terminal `error` ∪ interrupted ∪ **snapshot-says-not-running**),
|
||||
NOT a status whitelist.
|
||||
2. **One projection for turns AND messages**, one `Version` cursor (ADR 0004),
|
||||
one `OwnerThreadID` lane model (ADR 0003) — matching t3code's single
|
||||
`sequence` event log and traycer's single chat event log. tutti today runs two
|
||||
parallel mechanisms (activity Store for messages; blocking `activeTurn` for
|
||||
turns); the optimum unifies them.
|
||||
3. **`Adapter.Exec` is non-blocking**: submit → return a turn handle; the
|
||||
controller observes progress + terminal outcome via the existing `EventSink`
|
||||
stream + the projected turn state, not a blocking return. No goroutine to
|
||||
wedge → the wedge (67009835), the stuck-spinner class, the liveness floor, and
|
||||
the single-turn constraint all disappear by construction.
|
||||
|
||||
## Sequencing (rides the EXISTING steps; no new steps; each shippable + green)
|
||||
|
||||
| Step | Sharpened to | Risk control |
|
||||
| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
|
||||
| **Step 4** | Reducer emits a **unified projection** (messages **+ turn state**) into one snapshot with one monotonic cursor (ADR 0004). Turn state becomes reconcilable. | Characterization corpus (Step 0) stays green; snapshot tested at the daemon boundary. Gap-free cursor is the prerequisite for making the projection a sole source of truth. |
|
||||
| **Step 5 (A+B)** | Explicit `turnPhase` enum + single `transition()` owned by the **reducer** (source of truth); `awaitTurnCompletion` rewritten as a **subscriber** ("block until phase==Terminal"). Compaction = first-class event in the machine. Terminal-error + snapshot-negative are transitions that deliver `done` + set phase. | **Shadow-compare**: run the projection's terminal classification alongside the old blocking model; assert equality against the Step-0 corpus + new golden turn tests BEFORE the projection becomes authoritative. Reducer is single-writer under `a.mu`; transitions turnID-guarded. |
|
||||
| **Step 7 (C+D)** | **Invert `Exec` via a strangler shim**: introduce the async submit/observe core; keep the blocking `Exec([]events, error)` signature as a thin wrapper over it (block until the projection reports terminal). Migrate controller/callers to the async API incrementally; remove the wrapper only when no caller needs it. Facade owns command/observe + session lifecycle (Cluster D). Projection unification (D) completes here. | **Strangler = reversible, no big-bang contract break.** Opens the controller↔adapter seam ONCE (with Cluster D). Gated on Step 4 snapshot being authoritative. |
|
||||
|
||||
## Risk controls (the "controlled" in "no compromise")
|
||||
|
||||
1. **Strangler shim for the Exec inversion** — the blocking signature never breaks;
|
||||
it becomes a wrapper over the async core; callers migrate one at a time; the
|
||||
wrapper is deleted last. Fully reversible per caller.
|
||||
2. **Projection-as-truth introduced behind the existing blocking await first**
|
||||
(Step 5) — during a shadow period the old `done`-channel path still dominates
|
||||
if the projection disagrees; flip only after shadow-compare passes.
|
||||
3. **Shadow-compare + characterization corpus** — new turn-state projection runs
|
||||
in parallel; its terminal classification must match the old model against the
|
||||
Step-0 corpus + golden turn tests before it becomes authoritative.
|
||||
4. **Hard gate: C depends on Step 4** — the projection cannot be the sole source of
|
||||
truth until the snapshot is gap-free/authoritative (ADR 0004).
|
||||
5. **One controller touch** — do C with Step 7 (Cluster D) so the seam opens once.
|
||||
6. **Per-step green + independently shippable** — the design's existing discipline;
|
||||
no step combines seams beyond its owner.
|
||||
|
||||
## Why no-compromise is safe here
|
||||
|
||||
- A+B (Step 5) are **strictly on the optimal path** — the enum machine as source of
|
||||
truth is step one of the projection, not a throwaway patch. Nothing built is discarded.
|
||||
- C (Exec inversion) is the only controller-touching leap, and the **strangler shim
|
||||
makes it incremental and reversible** — the blast radius is opened one caller at a
|
||||
time behind a stable signature, gated on Step 4, aligned with Step 7's existing seam.
|
||||
- D (unification) is the natural convergence of ADR 0003 (`OwnerThreadID`), ADR 0004
|
||||
(cursor), and the Step-4 reducer — one projection the other ADRs already feed.
|
||||
|
||||
## Supersedes / relates
|
||||
|
||||
- Supersedes the "minimal + explicit enum" vs "structural async" fork: **A+B = the
|
||||
enum beachhead, C+D = the structural completion; all committed, sequenced.**
|
||||
- Makes ADR 0004 (cursor) a hard prerequisite and ADR 0003 (`OwnerThreadID`) a
|
||||
feeder of the same unified projection.
|
||||
|
||||
## Implementation outcome (2026-07-02, Phase 1)
|
||||
|
||||
Step 7 (C+D) closed with three findings and two recorded deviations.
|
||||
|
||||
**Finding — caller migration was already complete.** The controller's
|
||||
`runAsyncExecTurn` is purely event-driven (it finishes on terminal/steer
|
||||
events from the sink, never on `Exec`'s return); the blocking `adapter.Exec`
|
||||
path serves only non-`AsyncExecAdapter` providers. The strangler shim's
|
||||
"migrate callers one at a time" phase had therefore already happened; the
|
||||
remaining inversion was adapter-internal.
|
||||
|
||||
**S1 — settle path owns terminal production (commit 2bb62315).** Turn outcome
|
||||
events (`EventTurnCompleted/Failed/Canceled` + finish classification) are now
|
||||
produced by the settle sequence itself, from all three exits: protocol settle
|
||||
(`settleActiveTurn`), force-cancel (`markTurnForceCanceled`), and an external
|
||||
death watcher (ctx cancel / client death become machine transitions). The
|
||||
blocking shell no longer classifies; it waits on the turn's `terminated`
|
||||
signal and snapshots. A dedupe-guarded shadow classification remains in the
|
||||
shell behind a 2s safety net, with `slog.Warn` telemetry on any shadow miss —
|
||||
this is the strangler's reversibility retained until Step 9 (Phase 2) proves
|
||||
the async path end-to-end, after which the shell can be deleted.
|
||||
|
||||
**S2 deviation — submit/wait split skipped.** With S1 landed, the parked
|
||||
Exec goroutine only idles; it produces nothing. Splitting `Exec` into
|
||||
submit/await APIs would have churned the adapter surface for no behavioral
|
||||
gain. The essence of C — terminal truth owned by the projection/settle path,
|
||||
not the blocking await — is achieved without it.
|
||||
|
||||
**S3 deviation — session-lifecycle ownership was already correct (doc-only).**
|
||||
The adapter owns live-session semantics and the busy veto
|
||||
(`ErrLiveSessionBusy`, test-covered); the controller owns scheduling and the
|
||||
idle-recycle policy over its own session timestamps
|
||||
(`ReleaseIdleLiveSessions`). No code change; the boundary matches this ADR's
|
||||
Cluster D intent.
|
||||
|
||||
**S4 — controller cancel band-aid retired (commit b3043e85).** `Controller.Cancel`
|
||||
no longer skips when its turn registry has no record ("cancel skipped because
|
||||
no active turn exists"). It reconciles with the adapter: always calls
|
||||
`adapter.Cancel`, publishes returned events (e.g. linked child agents
|
||||
outliving a completed parent turn), and answers `Canceled=true` iff work was
|
||||
actually stopped. The adapter's `ErrSessionNoActiveTurn` maps to a calm
|
||||
"nothing to stop" result.
|
||||
|
||||
Gates: Step-0 corpus (15) + Phase-0 expansion (18 runtime + 3 activity) green;
|
||||
full `packages/agent/daemon` module green; `-race` green for all app-server
|
||||
code (a pre-existing flaky race in `standard_acp_adapter.go`/
|
||||
`acp_turn_normalizer.go` — untouched by this refactor, inherited from main —
|
||||
was observed and is out of scope here).
|
||||
@@ -0,0 +1,103 @@
|
||||
# ADR 0006 — Step 6: approval / interactive resolver — full optimal (durable pending in the unified projection)
|
||||
|
||||
- Date: 2026-07-02
|
||||
- Status: Accepted (grilling session) — approval goes full optimal, the approval-side of ADR 0005.
|
||||
- Context: Step 6 (Cluster E). Verified against tutti code; compared to t3code
|
||||
(`pendingApprovals` + `approvalCorrelations` + `serverRequest/resolved`) and the
|
||||
openclaw-codex-app-server durable pending-input model.
|
||||
|
||||
## Finding
|
||||
|
||||
tutti's server-request handling (`item/{commandExecution,fileChange,permissions}/requestApproval`,
|
||||
`item/tool/requestUserInput`, MCP elicitation) is a **blocking RPC handler**: the
|
||||
JSON-RPC handler goroutine builds a `pendingInteractiveRequest{ response chan }`, registers it
|
||||
in an in-memory `pendingRequests` map, and **parks on `<-response`**; `SubmitInteractive`
|
||||
non-blocking-sends the decision (`default` → "already answered"). The RPC reply to codex
|
||||
IS the handler's return. Two structural gaps:
|
||||
|
||||
1. **No `serverRequest/resolved` handling.** When codex resolves a server-request
|
||||
out-of-band (auto-approve, codex cancel, timeout, another client), tutti never
|
||||
learns → the parked handler + the durable `waiting_input` event stall forever.
|
||||
This is the cua-driver stall class (1ec14c03).
|
||||
2. **Pending lifecycle is not durable/reconcilable.** On reconnect/recycle,
|
||||
`rejectPendingRequests` rejects all pending; nothing is restored/re-offered.
|
||||
|
||||
The approval **detail** IS already emitted durably (`EventCallStarted` + payload;
|
||||
`TurnPhaseWaitingApproval` already exists), so #418 was a narrower rendering gap —
|
||||
the deep gap is the pending STATE and its resolution.
|
||||
|
||||
## Decision: full optimal — the approval-side of ADR 0005
|
||||
|
||||
Cluster E is the same "blocking RPC handler → durable projection + command/observe
|
||||
responder" inversion as ADR 0005. Unify it into the SAME per-session projection:
|
||||
|
||||
1. **Approval = durable pending item in the unified projection.** Its state
|
||||
(`pending → resolved{decision} | interrupted`) is reconciled from authoritative
|
||||
events + snapshot — not held only in an in-memory map + a parked channel.
|
||||
2. **`serverRequest/resolved` is the authoritative terminal** for a pending approval
|
||||
(the approval-side analog of ADR 0005's "snapshot-says-not-running" terminal
|
||||
transition). Handling it fixes the stall class (1ec14c03) and is the immediate,
|
||||
low-risk win. Also cover the **unknown/unsupported server-request** path with an
|
||||
explicit reject/error surface (design's stated Step 6 requirement).
|
||||
3. **The responder holds codex's RPC request id and responds async** when the durable
|
||||
pending item is resolved — decoupled from a live handler goroutine (cf. t3code's
|
||||
`Deferred` + `approvalCorrelations`).
|
||||
4. **Reconnect policy — interrupted, not silent reject.** A pending approval that
|
||||
survives a reconnect is marked **interrupted** in the projection and **re-offered
|
||||
/ re-driven** (re-run the turn), NOT silently rejected.
|
||||
|
||||
## Protocol dependency to verify at implementation
|
||||
|
||||
Whether a pending approval can resolve the ORIGINAL RPC after reconnect depends on
|
||||
**whether codex re-issues the server-request on `thread/resume`** (tutti does not
|
||||
replay it; not yet confirmed codex re-issues). If codex does NOT re-issue, the
|
||||
original RPC is dead on reconnect → the durable model can only \*\*display interrupted
|
||||
|
||||
- re-drive\*\*, not resolve the dead RPC. So the reconnect policy (item 4) must not
|
||||
assume RPC revival. `serverRequest/resolved` is the reconcile signal that keeps the
|
||||
durable state honest regardless.
|
||||
|
||||
## Sequencing (gate + independence)
|
||||
|
||||
- **Gated on Step 4** (like ADR 0005 C): a durable pending approval reconcilable
|
||||
against the snapshot needs the Step-4 unified projection to exist first.
|
||||
- **Does NOT depend on Step 7's Exec inversion.** "Hold codex's RPC + respond async"
|
||||
is already what the current blocking-goroutine handler does (a goroutine is cheap
|
||||
and holds the JSON-RPC request open); Step 6 keeps that as the strangler shim while
|
||||
making the pending STATE durable and adding `serverRequest/resolved`. So Step 6
|
||||
(approval) legitimately precedes Step 7 (Exec inversion); it introduces the
|
||||
responder-over-durable-state pattern that Step 7 later generalizes to turns.
|
||||
|
||||
## Risk control
|
||||
|
||||
- **Strangler shim:** keep the current blocking handler as a thin shim OVER the
|
||||
durable pending item (park until the durable item resolves), migrate consumers to
|
||||
the durable-state + responder API incrementally, remove the shim last. Reversible.
|
||||
- **`serverRequest/resolved` first** — a small, isolated addition that fixes the
|
||||
stall class immediately, independent of the full inversion.
|
||||
- Per-step green: Cluster E regression tests (#418 detail, approve/deny mapping,
|
||||
requestUserInput, unknown-request reject) gate the step; Step-0 corpus stays green.
|
||||
|
||||
## Relations
|
||||
|
||||
- **Unifies with ADR 0005** — approvals become items in the same projection that
|
||||
carries turn state + messages; `SubmitInteractive` is a responder like the turn
|
||||
command; both reconcile against the Step-4 snapshot.
|
||||
- #418 detail is largely handled today; this ADR targets the pending STATE + resolution.
|
||||
|
||||
## Live verification (2026-07-02, Phase 0)
|
||||
|
||||
Ran against the real binary (`codex-cli 0.142.5`) via the env-gated test
|
||||
`TestLiveProtocolResumeServerRequestReissue`
|
||||
(`packages/agent/daemon/runtime/liveprotocol_verify_test.go`,
|
||||
`TUTTI_LIVE_PROTOCOL_VERIFY=1`): provoke `item/commandExecution/requestApproval`
|
||||
(read-only sandbox + untrusted policy), leave it unanswered, kill the client
|
||||
process, resume the thread from a fresh process.
|
||||
|
||||
**Verdict: codex does NOT re-issue the pending server-request after
|
||||
`thread/resume`.** Additionally: the interrupted-mid-approval turn does not
|
||||
resume (thread status returns `idle`), and the unanswered approval item is NOT
|
||||
replayed by resume — so a daemon restart leaves no zombie `waiting_input` row
|
||||
in the rebuilt store either. The conservative reconnect policy stands
|
||||
confirmed: no RPC revival is possible; pending approvals die with their turn
|
||||
and the user re-drives. No code change required.
|
||||
@@ -0,0 +1,30 @@
|
||||
# ADR 0007 — Sub-agent lane ownership
|
||||
|
||||
- Date: 2026-07-03
|
||||
- Status: Superseded
|
||||
- Superseded by:
|
||||
[Provider-Native Subagents](../specs/2026-07-15-provider-native-subagents.md)
|
||||
|
||||
## Former Problem
|
||||
|
||||
The earlier timeline-only model did not persist which delegation tool created a
|
||||
provider child thread. AgentGUI therefore guessed lane attachment from a
|
||||
partially loaded transcript, which could attach output to the wrong tool card.
|
||||
|
||||
## Current Decision
|
||||
|
||||
Provider-native agents are durable child `WorkspaceAgentSession` entities with
|
||||
their own turns, messages, and interactions. Each child stores one immutable
|
||||
creator relation:
|
||||
|
||||
- root session and root turn
|
||||
- direct parent session and parent turn
|
||||
- parent delegation tool-call id
|
||||
|
||||
AgentGUI attaches lanes only from those session relations and derives status
|
||||
only from the child's canonical turn. It does not read timeline ownership
|
||||
fields, infer relationships from message order, or reconstruct historical rows
|
||||
that lack a child session.
|
||||
|
||||
This ADR remains only as the record of why inferred timeline ownership was
|
||||
rejected. The linked specification is the implementation contract.
|
||||
@@ -0,0 +1,91 @@
|
||||
# ADR 0008 — Turn lifecycle snapshot authority: one source of truth for "is a turn running"
|
||||
|
||||
- Date: 2026-07-03
|
||||
- Status: Accepted (Phase A implemented for codex; Phase B implemented for the
|
||||
Claude SDK adapter, pending for the standard ACP adapters)
|
||||
- Extends: ADR 0005 (reducer as the codex turn-lifecycle source of truth) — this ADR
|
||||
promotes that principle from inside the codex adapter to the whole chain
|
||||
(controller → persisted store → service → GUI).
|
||||
|
||||
## Problem
|
||||
|
||||
"Is this conversation running a turn" had eight independent representations:
|
||||
the controller turn registry (`c.turns`), the codex turn machine, the
|
||||
`Session.{Status,TurnLifecycle,SubmitAvailability}` mirror (folded from
|
||||
discrete events and kept coherent by three patch mechanisms —
|
||||
`preserveActiveTurnStatus`, `reconcileSessionStatusLocked`, the sink's
|
||||
ready-guard), the discrete `turn.*` events on the wire, the persisted state
|
||||
patch (with a codex-only shaping path), an independent service-layer
|
||||
predicate, the GUI's four-level display-status fallback, and GUI/desktop local
|
||||
bookkeeping. Every recent lifecycle bug (stuck spinners, status flapping,
|
||||
stale-store overwrites, processing-row misfires) was drift between two of
|
||||
these.
|
||||
|
||||
## Decision
|
||||
|
||||
**The turn owner publishes idempotent `TurnLifecycle` snapshots; every other
|
||||
layer copies or purely derives. No layer recomputes lifecycle from discrete
|
||||
events, and no reconciliation patches exist for snapshot-authority sessions.**
|
||||
|
||||
1. **Snapshot contract** (`activityshared.TurnLifecycleSnapshot`, stamped into
|
||||
`Payload.Metadata["turnLifecycle"]` on the `turn.*` event emitted at each
|
||||
transition — no new event type; `turn.*` events already project to state
|
||||
patches only and never to message updates):
|
||||
`{v, origin: adapter|controller, seq, activeTurnId, phase, outcome?, settling?}`.
|
||||
- Full snapshot, consumers replace, never merge.
|
||||
- `seq` is monotonic per session; consumers drop lower-seq snapshots
|
||||
(snapshots reach the controller over two channels: the Exec emit closure
|
||||
and the session event sink).
|
||||
- Only `origin:"adapter"` snapshots flip a session into snapshot-authority
|
||||
mode; the controller authors exactly two snapshot kinds — the submit
|
||||
moment and the finishTurn settle fallback — which apply to any provider
|
||||
without flipping legacy sessions.
|
||||
2. **Codex adapter** stamps every emitted turn event at its emission choke
|
||||
points (`execBlocking`'s emit, adoption emitters), derived from the very
|
||||
transition the event states. The approval error path additionally emits a
|
||||
back-to-running event so the lifecycle cannot strand in `waiting_approval`.
|
||||
3. **Controller** (authority sessions): `Session.TurnLifecycle` = last valid
|
||||
snapshot; `Session.Status` = `statusForAuthoritySession(lifecycle,
|
||||
session-level signals)`; `SubmitAvailability` =
|
||||
`submitAvailabilityForAuthoritySession(lifecycle)`. The legacy folding path
|
||||
(`applySessionEvents` status fold, `applyTurnLifecycleFromEvents`,
|
||||
`preserveActiveTurnStatus`, `reconcileSessionStatusLocked`) survives only
|
||||
for non-authority sessions and is deleted in Phase B.
|
||||
4. **Persisted store**: `applyLifecycleSnapshotToPatch` copies the snapshot
|
||||
into the state patch provider-agnostically (replacing the codex-only
|
||||
`applyExplicitTurnLifecycleToPatch`, kept as legacy fallback). The resume
|
||||
stale-turn reconcile also repairs the persisted lifecycle to settled — the
|
||||
only lifecycle writer besides snapshot copies, and only when the runtime
|
||||
confirmed no live turn exists.
|
||||
5. **Live-phase vocabulary** lives in exactly one place:
|
||||
`activityshared.LiveTurnLifecyclePhases` / `TurnLifecyclePhaseIsLive`
|
||||
(accepting documented legacy tokens), mirrored in TypeScript as
|
||||
`LIVE_TURN_LIFECYCLE_PHASES` / `isLiveTurnLifecyclePhase`
|
||||
(activity-core selectors.ts). Parity is pinned by tests on both sides.
|
||||
6. **GUI**: a present lifecycle decides the display status entirely
|
||||
(status/currentPhase fallbacks apply only to lifecycle-less records); the
|
||||
processing indicator and the desktop queue-drain busy check gate on the
|
||||
lifecycle through the shared predicate.
|
||||
|
||||
## Phase B (Claude SDK adapter done; standard ACP pending)
|
||||
|
||||
Standard ACP and Claude SDK adapters stamp their existing turn-event call
|
||||
sites; the authority flag then flips automatically per session. Afterwards the
|
||||
legacy folding path, the patch-shaping fallback, the snapshot-enrichment
|
||||
overwrite, and the GUI lifecycle-less fallbacks are deleted.
|
||||
|
||||
The Claude SDK adapter stamps via the shared `stampAdapterTurnLifecycleEvents`
|
||||
helper (turn_lifecycle_stamp.go) at its three emission boundaries — the Exec
|
||||
submit events, the sidecar event dispatch choke point, and Cancel's returned
|
||||
events — and guards Cancel with a settled-turn check so a cancel racing the
|
||||
turn's own settle cannot fabricate a second terminal transition. The legacy
|
||||
folding deletion still waits on the standard ACP adapters.
|
||||
|
||||
## Invariant tests
|
||||
|
||||
`TestStatusForAuthoritySession` (derivation table),
|
||||
`TestControllerCodexStreamNeverIdlesMidTurn` (no available/settled patch
|
||||
between submit and settle), `TestApplyLifecycleSnapshotToPatchProviderAgnostic`,
|
||||
`TestCodexAppServerAdapterApprovalErrorPathResumesLifecycle`,
|
||||
`TestLiveTurnLifecyclePhasesCanonicalList` + the TS mirror test, plus the
|
||||
existing goal/cancel/adoption/steer behavior pins.
|
||||
@@ -0,0 +1,495 @@
|
||||
# ADR 0009 — Share a class-based Workbench host kernel across Tutti and TSH
|
||||
|
||||
- Date: 2026-07-11
|
||||
- Status: Accepted
|
||||
- Decision owners: Tutti desktop and Workbench maintainers
|
||||
- Related:
|
||||
- [Workbench](../conventions/workbench.md)
|
||||
- [Workbench Contributions](../architecture/workbench-contributions.md)
|
||||
- [Workbench Node Lifecycle](../architecture/workbench-node-lifecycle.md)
|
||||
- [Workbench Dock Model](../architecture/workbench-dock-model.md)
|
||||
|
||||
## Implementation status
|
||||
|
||||
Tutti completed the public package extraction in
|
||||
[#1194](https://github.com/tutti-os/tutti/pull/1194) and the direct desktop
|
||||
cutover in [#1196](https://github.com/tutti-os/tutti/pull/1196). The fixed npm
|
||||
release group published `@tutti-os/workbench-host@0.0.104` under
|
||||
`packages-v0.0.104` through
|
||||
[workflow run 29440844430](https://github.com/tutti-os/tutti/actions/runs/29440844430).
|
||||
|
||||
TSH adoption is intentionally separate downstream work. It should consume the
|
||||
stable npm package and its public conformance subpath; it does not keep a Tutti
|
||||
active spec open.
|
||||
|
||||
## Context
|
||||
|
||||
Tutti and TSH already share the canonical Workbench snapshot contract, Go
|
||||
validation service, surface mechanics, contribution contract, node identity
|
||||
helpers, and dock model. Their product hosts still own similar coordination in
|
||||
different forms:
|
||||
|
||||
- Tutti has a renderer DI singleton class that assembles and caches
|
||||
workspace-specific host input, but the class also contains Tutti product
|
||||
services and policies.
|
||||
- TSH has a contribution-first registry and durable room/user snapshot
|
||||
repository, but its host coordination is still implemented as React hooks.
|
||||
- `@tutti-os/workbench-surface` has a disposable shell session for layout,
|
||||
projection reconciliation, activation, and snapshot saves. It intentionally
|
||||
does not own product capability assembly or product business policy.
|
||||
|
||||
Class-based dependency injection alone does not solve this divergence. DI can
|
||||
construct and locate a long-lived service, but it does not define:
|
||||
|
||||
- how one renderer owns multiple sequential or concurrent Workbench scopes;
|
||||
- which inputs are renderer-singleton state and which are scope-local state;
|
||||
- when subscriptions, save queues, caches, and live projections are disposed;
|
||||
- how product-neutral contributions are ordered and validated;
|
||||
- how a user identity change prevents one user's cached snapshot from leaking
|
||||
into another user's room session;
|
||||
- which changes may update a live session and which require replacement.
|
||||
|
||||
Without a shared lifecycle owner, a DI service tends to become either a product
|
||||
mega-service or a thin wrapper around React lifecycle. Both products then have
|
||||
to rediscover the same session, disposal, cache, and conformance rules.
|
||||
|
||||
## Decision
|
||||
|
||||
Tutti and TSH will share a **class-based, DI-friendly Workbench host kernel**.
|
||||
The public package is `@tutti-os/workbench-host`.
|
||||
|
||||
The kernel has two explicit lifetime levels:
|
||||
|
||||
1. one `WorkbenchHostCoordinator` per renderer/window DI root; and
|
||||
2. one disposable `WorkbenchHostSession` per open Workbench scope partition.
|
||||
|
||||
The coordinator and session are ordinary classes with constructor-injected
|
||||
interfaces. The package does not require a particular DI container and does not
|
||||
use global service lookup. Both official renderers will use
|
||||
`@tutti-os/infra/di` to register their class service/coordinator. Each product
|
||||
still owns its service token, registration function, constructor adapters, and
|
||||
renderer composition root; none of that registration becomes a responsibility
|
||||
of the shared package. DI creates the coordinator, while the coordinator
|
||||
creates, indexes, replaces, and disposes scope sessions.
|
||||
|
||||
This host session is the product-host coordination layer above the existing
|
||||
`@tutti-os/workbench-surface` shell session. The surface remains the owner of
|
||||
window mechanics and shell persistence behavior. The host kernel must compose
|
||||
the surface contract rather than reimplement its reducer, contribution merge
|
||||
rules, snapshot sanitizer, node identity, or dock behavior.
|
||||
|
||||
## Dependency direction
|
||||
|
||||
The allowed package direction is:
|
||||
|
||||
```text
|
||||
Tutti renderer ─┬─> @tutti-os/workbench-host
|
||||
└─> @tutti-os/workbench-surface
|
||||
|
||||
TSH renderer ───┬─> @tutti-os/workbench-host
|
||||
└─> @tutti-os/workbench-surface
|
||||
|
||||
@tutti-os/workbench-host -- type-only/public-contract --> @tutti-os/workbench-surface
|
||||
@tutti-os/workbench-surface -X-> @tutti-os/workbench-host
|
||||
```
|
||||
|
||||
`@tutti-os/workbench-host` may use type-only or declaration-level dependencies
|
||||
on public surface contracts such as `WorkbenchContribution`,
|
||||
`WorkbenchHostHandle`, snapshot repository seams, and stable host-input types.
|
||||
Those declarations may transitively mention React types because the existing
|
||||
surface contribution contract contains render functions and React values.
|
||||
|
||||
This allowance does not give the host package React runtime ownership. Emitted
|
||||
host JavaScript must not import React, mount components, call hooks, own effect
|
||||
lifecycle, or implement `WorkbenchHost` rendering. It also must not import
|
||||
surface runtime helpers in a way that creates a runtime dependency cycle.
|
||||
Surface remains independently usable and must never import host.
|
||||
|
||||
If extraction produces a React runtime dependency, a `surface -> host` reverse
|
||||
dependency, or any host/surface cycle, the extraction must stop. Maintainers
|
||||
must re-review package ownership and move the disputed behavior back behind a
|
||||
product adapter or a lower-level neutral contract before continuing.
|
||||
|
||||
## Canonical model
|
||||
|
||||
### Shared kernel
|
||||
|
||||
The shared kernel owns only product-neutral coordination:
|
||||
|
||||
- coordinator/session lifecycle and idempotent disposal;
|
||||
- immutable scope and authenticated-principal snapshots captured at session
|
||||
creation;
|
||||
- deterministic capability-factory ordering and duplicate ownership checks;
|
||||
- stable contribution and host-input composition;
|
||||
- subscription and resource cleanup;
|
||||
- session replacement when an immutable partition changes;
|
||||
- forwarding dynamic projections and presentation-state updates without
|
||||
rebuilding the session;
|
||||
- diagnostics hooks for lifecycle and invariant violations;
|
||||
- a product-neutral conformance harness.
|
||||
|
||||
The shared kernel does not own Electron, React runtime lifecycle or components,
|
||||
daemon clients, authentication discovery, workspace or room business rules,
|
||||
cloud projection, terminal or agent lifecycle, user-visible product copy, or
|
||||
product-specific snapshot metadata. Type declarations may reference the public
|
||||
surface contracts described above.
|
||||
|
||||
### Product Profile
|
||||
|
||||
A `WorkbenchProductProfile` describes stable product-level choices. It is data
|
||||
and narrow callbacks, not a service bag. A profile includes:
|
||||
|
||||
- a stable product ID;
|
||||
- supported scope kind (`workspace` for Tutti, `room` for TSH);
|
||||
- deterministic capability factory descriptors;
|
||||
- host-level compatibility policy that cannot be expressed by a capability;
|
||||
- declared snapshot metadata ownership, if any;
|
||||
- optional feature flags that are stable for the lifetime of a session.
|
||||
|
||||
Profiles must not contain Tutti-or-TSH union fields, transport clients, mutable
|
||||
business stores, or optional properties for every product capability.
|
||||
|
||||
### Ports
|
||||
|
||||
Ports are small interfaces through which the kernel reaches an owner outside
|
||||
the kernel. The initial port families are:
|
||||
|
||||
- `WorkbenchSnapshotRepositoryPort`: load, cached read, save, and optional
|
||||
change subscription for an opaque snapshot partition;
|
||||
- `WorkbenchDiagnosticsPort`: structured lifecycle and invariant diagnostics;
|
||||
- `WorkbenchCapabilityRegistryPort`: supplies the factories allowed by the
|
||||
selected profile, if they are not passed directly at composition;
|
||||
- `WorkbenchSessionClockPort` only if deterministic time is proven necessary;
|
||||
- surface-session attachment/update seams needed to connect the headless host
|
||||
session to `@tutti-os/workbench-surface`.
|
||||
|
||||
Ports expose product-neutral values. A port must not grow into a renamed
|
||||
`window.tutti`, `window.tshApi`, `TuttidClient`, desktopd client, control-plane
|
||||
client, or product service container.
|
||||
|
||||
### Capability contributions
|
||||
|
||||
The existing `WorkbenchContribution` remains the canonical capability output.
|
||||
Feature-owned factories may contribute node definitions, dock entries, external
|
||||
state, launch handling, close handling, and close preparation under the current
|
||||
contract.
|
||||
|
||||
The kernel adds lifecycle and ownership around contribution factories; it does
|
||||
not replace `WorkbenchContribution` and does not change its merge semantics.
|
||||
Each factory receives:
|
||||
|
||||
- a minimal immutable session context (`productId`, scope, partition identity);
|
||||
- only the capability-specific ports supplied by the product adapter; and
|
||||
- stable presentation inputs that the capability genuinely owns.
|
||||
|
||||
A factory must not receive an entire product context and pick optional services
|
||||
from it.
|
||||
|
||||
### Product adapters
|
||||
|
||||
Tutti and TSH each own an adapter layer that:
|
||||
|
||||
- obtains the current workspace or room and authenticated user identity;
|
||||
- captures an immutable session partition;
|
||||
- maps the existing HTTP clients and snapshot repositories to shared ports;
|
||||
- supplies product capability factories and their narrow dependencies;
|
||||
- owns product copy, feature enablement, launch/reuse/close policy, and
|
||||
business-state projection;
|
||||
- registers a product-owned class service/coordinator with
|
||||
`@tutti-os/infra/di` in the product's renderer composition root; and
|
||||
- connects the resulting session to the React Workbench surface.
|
||||
|
||||
The long-term TSH target is therefore not only to consume the same kernel. Its
|
||||
renderer also adopts the same class-DI composition style as Tutti through
|
||||
`@tutti-os/infra/di`, replacing hook-owned host lifecycle. This is an official
|
||||
renderer integration decision, not a dependency from the host package to the DI
|
||||
framework.
|
||||
|
||||
The adapters are the only place where `workspaceId` can mean a Tutti workspace
|
||||
and where TSH's Workbench `workspaceId` compatibility field can carry a room
|
||||
ID. The shared kernel treats these as opaque scope IDs.
|
||||
|
||||
## Lifetime and partition rules
|
||||
|
||||
### Renderer singleton coordinator
|
||||
|
||||
There is exactly one coordinator in each renderer/window DI root. It may manage
|
||||
zero or more sessions, but it is not a process-global static and it does not own
|
||||
business entities. It owns only the index and lifecycle of sessions created in
|
||||
that renderer.
|
||||
|
||||
Coordinator isolation is also the window boundary. Two renderer/window roots
|
||||
that open the same immutable partition own independent coordinators and
|
||||
independent sessions; sessions are never shared across roots. Inside one root,
|
||||
opening the same immutable partition more than once returns leases to the same
|
||||
session, but that session has exactly one effective surface attachment. A
|
||||
renderer handoff may replace the attachment during React remount or shell
|
||||
transition, and a stale detach from the previous owner must not clear the
|
||||
current handle. The first public contract does not support two simultaneously
|
||||
effective Workbench surfaces for one session.
|
||||
|
||||
Opening the same immutable partition twice is idempotent or returns an explicit
|
||||
lease to the same session. Opening the same scope with a different immutable
|
||||
partition must dispose and replace the old session before the new session can
|
||||
publish host input.
|
||||
|
||||
### Disposable scope session
|
||||
|
||||
Each Tutti workspace or TSH room gets a disposable session. The session owns:
|
||||
|
||||
- the resolved contribution set and stable host-input projection;
|
||||
- scope-local subscriptions and adapter leases;
|
||||
- projection and dynamic-presentation bridges;
|
||||
- scope-local repository/cache coordination that is not owned by the daemon;
|
||||
- the attachment to the surface runtime handle; and
|
||||
- cleanup for all resources acquired during session construction.
|
||||
|
||||
Disposal is idempotent. The surface shell session may preserve its existing
|
||||
behavior of initiating one final, partition-bound snapshot flush during
|
||||
teardown. After teardown begins, the host session may not accept new updates,
|
||||
publish host input, notify subscribers, or call a detached surface handle. Late
|
||||
load/save completions must remain bound to the immutable snapshot partition;
|
||||
they may not publish into the disposed session, mutate another partition's
|
||||
cache, or overwrite a newer write for the same partition. Repository adapters
|
||||
must serialize or otherwise reject stale same-partition completions.
|
||||
|
||||
Renderer isolation does not authorize multiple durable writers for the same
|
||||
snapshot partition. A product that can open auxiliary renderer roots for the
|
||||
same logical scope must choose one durable owner or give auxiliary roots a
|
||||
different durable partition. Tutti's OS workspace renderer is the single
|
||||
durable writer for a workspace; standalone Agent renderer roots use a
|
||||
read-seeded, window-local repository and never issue workspace Workbench PUTs.
|
||||
Within the durable repository, loads and saves for one workspace are one
|
||||
invocation-ordered operation stream, while different workspaces remain
|
||||
independent. Product-owned snapshot metadata is merged from the latest cache at
|
||||
write execution time so a stale surface snapshot cannot undo a newer product
|
||||
metadata write.
|
||||
|
||||
Tutti enforces its single durable owner in the Electron main process. The
|
||||
workspace window registry is keyed by `workspaceId` for OS windows, concurrent
|
||||
open requests share one pending creation, and later requests restore/focus the
|
||||
registered window. Registration rejects a second OS owner as a backstop.
|
||||
Agent-only windows are intentionally excluded from that uniqueness rule because
|
||||
their repositories never issue durable Workbench writes.
|
||||
|
||||
### Scope and snapshot partitions
|
||||
|
||||
The kernel uses two related identities:
|
||||
|
||||
- `WorkbenchScope`: product-visible logical scope;
|
||||
- `WorkbenchSnapshotPartition`: immutable repository/cache key captured when a
|
||||
session starts.
|
||||
|
||||
Canonical mappings are:
|
||||
|
||||
| Product | Workbench scope | Snapshot partition |
|
||||
| ------- | ---------------------- | ---------------------------------------------------------------------- |
|
||||
| Tutti | `workspaceId` | `workspaceId` under the existing local authenticated desktop authority |
|
||||
| TSH | control-plane `roomId` | `roomId` plus an immutable authenticated-user snapshot |
|
||||
|
||||
The TSH authenticated-user snapshot contains only stable identity needed for
|
||||
partitioning, normally the authenticated user ID. It never contains a token or
|
||||
mutable auth client. The user ID continues to be derived by desktopd for the
|
||||
HTTP request; it is not accepted from a renderer request body. The renderer
|
||||
partition prevents cache reuse, while desktopd's `(room_id, user_id)` key
|
||||
remains the durable enforcement boundary.
|
||||
|
||||
If Tutti later supports switching durable user authorities within one local
|
||||
profile, it must introduce a versioned partition mapping through its product
|
||||
adapter. The shared kernel must not infer that policy.
|
||||
|
||||
## State ownership
|
||||
|
||||
| State | Authoritative owner | Kernel/session role | Forbidden owner |
|
||||
| ------------------------------------------------------------------------ | ------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------- |
|
||||
| Snapshot schema, migrations, normalization | `@tutti-os/workbench-snapshot` | Consume unchanged | Product adapter |
|
||||
| Frame, display mode, restore frame, minimized state, stack, active shell | Workbench surface session plus daemon snapshot repository | Coordinate attachment and persistence port | Capability business service |
|
||||
| Snapshot durability | `tuttid` for Tutti; desktopd SQLite keyed by `(room_id, user_id)` for TSH | Bind repository/cache access to the immutable partition; allow the surface's final teardown flush without cross-partition or stale same-partition publication | Renderer session |
|
||||
| Node type/instance identity and dock affinity | Existing Workbench surface contracts and identity helpers | Preserve and validate ownership | Product profile remapping |
|
||||
| Contribution ordering and duplicate capability ownership | Host kernel using declared factory `order` then `id` | Resolve deterministically | React render order |
|
||||
| Projected node presence | Owning product runtime/business service | Forward live projection into the attached surface session | Snapshot restore |
|
||||
| Terminal, agent, chat, app, file, transfer, and collaboration state | Product daemon/control plane/domain service | Read/project through capability adapter | Host kernel or snapshot |
|
||||
| Dynamic dock badges, availability, and attention | Owning capability service/store | Forward through stable state source | Static host-input rebuild |
|
||||
| Authenticated principal used for partitioning | Product authentication authority | Hold immutable identity snapshot for one session | Capability contribution |
|
||||
| React-only overlay/dialog/DOM state | Product presentation adapter | None, except commands/events across a narrow seam | Shared kernel |
|
||||
|
||||
## Invariants
|
||||
|
||||
1. A snapshot can restore shell presentation but can never create, delete, or
|
||||
become authoritative for a terminal, agent, chat, app, file, transfer, or
|
||||
collaboration business entity.
|
||||
2. At most one live host session exists per immutable snapshot partition in one
|
||||
renderer coordinator, and every session is disposed before its partition is
|
||||
replaced. Separate renderer/window coordinators never share sessions.
|
||||
3. TSH cache and persistence access for a room is partitioned by an immutable
|
||||
authenticated-user snapshot; credentials and user IDs are never supplied by
|
||||
capability contributions or persisted inside the Workbench snapshot.
|
||||
4. A capability owns each contribution ID, node `typeId`, and dock entry ID
|
||||
exactly once. Resolution is deterministic and independent of React render
|
||||
order.
|
||||
5. Dynamic business or dock state may update a stable session but may not
|
||||
recreate the coordinator, session, node definitions, or shell identities.
|
||||
6. A session has one effective surface attachment. A replacement attachment may
|
||||
take ownership during renderer handoff, while a stale detach cannot clear the
|
||||
replacement handle; simultaneous multi-surface ownership is not supported.
|
||||
7. Session disposal invalidates later host callbacks and publications. The
|
||||
surface may initiate its existing final partition-bound flush, but late
|
||||
completions cannot publish into a disposed session, cross partitions, or
|
||||
overwrite a newer same-partition write.
|
||||
8. Independent renderer coordinators do not imply independent durable writers:
|
||||
each product designates one writer per durable snapshot partition or assigns
|
||||
auxiliary roots a different or non-durable repository.
|
||||
9. Shared code depends on product-neutral ports. Tutti and TSH adapters may
|
||||
depend on the kernel, but the kernel never imports either product.
|
||||
10. Current `WorkbenchContribution`, snapshot schema, stable node identity,
|
||||
dock ordering/affinity, daemon API shapes, and business authority remain
|
||||
behaviorally compatible.
|
||||
11. Host may depend on surface public contracts at type/declaration level;
|
||||
surface never depends on host, and neither a React runtime dependency nor a
|
||||
host/surface cycle is allowed.
|
||||
|
||||
## Compatibility constraints
|
||||
|
||||
The extraction is a structural change, not a contract redesign:
|
||||
|
||||
- no change to `WorkbenchContribution` or the explicit `WorkbenchHost` props;
|
||||
- no snapshot schema or migration change;
|
||||
- no change to projected/launched node ID helpers or existing IDs;
|
||||
- no change to contribution merge precedence or product dock order;
|
||||
- no change to Tutti's `/v1/workspaces/{workspaceID}/workbench` API;
|
||||
- no change to TSH's `GET/PUT /v1/rooms/{roomId}/workbench` API;
|
||||
- no change to daemon-side reconciliation ownership; and
|
||||
- no movement of product business policy into a shared package.
|
||||
|
||||
Any implementation step that needs one of these changes must stop and propose a
|
||||
separate contract decision instead of hiding it inside the host extraction.
|
||||
|
||||
## Rejected designs
|
||||
|
||||
### Product inheritance
|
||||
|
||||
Rejected: a shared base host class with `TuttiWorkbenchHost` and
|
||||
`TSHWorkbenchHost` subclasses.
|
||||
|
||||
Inheritance would make product-specific lifecycle hooks part of the shared
|
||||
contract, encourage protected-state coupling, and make constructor/override
|
||||
order an implicit coordination protocol. The products are compositions of
|
||||
capabilities, not substitutable host subtypes. Use a final coordinator/session
|
||||
implementation with injected profiles and ports.
|
||||
|
||||
### Product-union mega-context
|
||||
|
||||
Rejected: one context such as `TuttiContext | TSHContext`, or an object with
|
||||
dozens of optional Tutti and TSH services.
|
||||
|
||||
That shape moves the fork into runtime conditionals, exposes unrelated business
|
||||
services to every factory, and makes absence ambiguous. Profiles declare stable
|
||||
choices; narrow ports provide shared needs; capability adapters receive only
|
||||
their own dependencies.
|
||||
|
||||
### Make `@tutti-os/workbench-surface` the product host
|
||||
|
||||
Rejected as the stable boundary. Surface owns shell mechanics and React
|
||||
presentation. Adding product host coordination there would couple a headless
|
||||
lifecycle concern to the UI package and make non-React testing and evolution
|
||||
harder.
|
||||
|
||||
### Keep two hosts and share only tests
|
||||
|
||||
Rejected as the long-term target. A conformance suite is required, but tests
|
||||
alone do not create one lifecycle owner. The current Tutti class and TSH hook
|
||||
would continue to drift in disposal, partition, cache, and update semantics.
|
||||
|
||||
## Public package evaluation
|
||||
|
||||
### Accepted: `@tutti-os/workbench-host`
|
||||
|
||||
Benefits:
|
||||
|
||||
- names the coordination domain explicitly;
|
||||
- can remain headless and class-based;
|
||||
- can expose a small public API and a conformance test subpath;
|
||||
- keeps `workbench-surface` focused on UI/shell mechanics; and
|
||||
- gives TSH a release-based dependency rather than copied host code while both
|
||||
official renderers use the same `@tutti-os/infra/di` class composition style.
|
||||
|
||||
Costs:
|
||||
|
||||
- adds a public compatibility surface and fixed-release-group member;
|
||||
- requires pack and release validation plus downstream adoption testing; and
|
||||
- requires strict export discipline to avoid publishing Tutti product types.
|
||||
|
||||
The extracted package contains only coordinator/session, profiles, ports,
|
||||
capability descriptors, and conformance helpers. Tutti's direct package cutover
|
||||
validated that boundary before stable publication.
|
||||
|
||||
### Alternative: `@tutti-os/workbench-surface/host`
|
||||
|
||||
This would avoid another package, but it couples headless host coordination to
|
||||
React/surface release and dependency shape. It remains rejected because the
|
||||
independent package has no React runtime dependency or circular dependency.
|
||||
|
||||
### Alternative: Tutti-private kernel plus copied TSH adapter
|
||||
|
||||
This had the lowest immediate release cost and was acceptable only for the
|
||||
Tutti-first proving step. It is not a completion state: TSH must consume the
|
||||
released package, never a filesystem link or copied source.
|
||||
|
||||
## Release decision
|
||||
|
||||
`@tutti-os/workbench-host` belongs to the existing fixed npm release group and
|
||||
uses its single shared version. It does not establish an independent version or
|
||||
release workflow.
|
||||
|
||||
- Local beta validation uses `pnpm release:beta`, publishes with the `beta`
|
||||
dist-tag, and creates no git tag or manifest commit.
|
||||
- Stable publication uses the repository's manual fixed-group workflow and the
|
||||
normal `packages-v<version>` tag.
|
||||
- Stable publication also creates the normal tags for every existing
|
||||
`packages/**/go.mod`, including `packages/workbench/service/v<version>`.
|
||||
- The TypeScript host package does not need its own `go.mod`; adding one only to
|
||||
obtain a tag is prohibited.
|
||||
- If no Go code or contract changes, TSH beta validation continues using the
|
||||
last stable Workbench Go module. A Go beta distribution mechanism is outside
|
||||
this decision.
|
||||
|
||||
The durable fixed-group roster and all release automation must be updated in
|
||||
one package-extraction PR. Before that edit, the implementation must audit and
|
||||
reconcile any existing roster drift between release documentation and config;
|
||||
it must not copy one stale list into another.
|
||||
|
||||
## Consequences
|
||||
|
||||
Positive consequences:
|
||||
|
||||
- both products share one lifecycle and partition model;
|
||||
- React becomes an adapter rather than the owner of host coordination;
|
||||
- product features stay independently contributable;
|
||||
- auth and scope isolation become explicit and testable;
|
||||
- the public Workbench surface and daemon contracts remain stable.
|
||||
|
||||
Costs and constraints:
|
||||
|
||||
- TSH must later replace hook-owned lifecycle with an adapter to the released
|
||||
coordinator/session;
|
||||
- the package's public API requires compatibility discipline and downstream
|
||||
adoption testing; and
|
||||
- a coordinator/session abstraction adds value only if its public surface stays
|
||||
smaller than either product host.
|
||||
|
||||
## Resolved extraction constraints
|
||||
|
||||
- Keep concurrent distinct partitions available internally, but do not promise
|
||||
multi-view UX or multiple effective surfaces for one session in the first
|
||||
public API.
|
||||
- Preserve the current public surface props and returned handle attachment for
|
||||
the public API. An externally created shell-session API requires a separate
|
||||
decision.
|
||||
|
||||
## Open questions
|
||||
|
||||
1. Which Tutti snapshot metadata (currently product-owned wallpaper and
|
||||
onboarding fields) should remain in the snapshot repository adapter versus a
|
||||
dedicated product metadata port? Default: keep compatibility in the Tutti
|
||||
adapter and extract only after conformance tests prove the
|
||||
ownership boundary.
|
||||
@@ -0,0 +1,135 @@
|
||||
# Agent Session Replay has a shared application core
|
||||
|
||||
**Accepted, amended 2026-07-29**
|
||||
|
||||
Tutti and TSH both record and replay Agent Sessions, so provider-neutral
|
||||
Recording and Cassette contracts live in `packages/agent/session-replay`. The
|
||||
package owns their identities, Recording status transitions and workflow,
|
||||
fixed-batch replay preparation, Cassette schema, semantic checkpoint model,
|
||||
allowlist, size policy, and integrity validation. Its ports cover metadata,
|
||||
semantic Replay State, artifact publication, and provider-tape recording.
|
||||
Product runtime adapters own
|
||||
ephemeral replay process identity, progress, cancellation, and settlement.
|
||||
|
||||
Recording is a mutable task that produces zero or one Cassette. Its replay
|
||||
payload is immutable, while its user-visible name may change.
|
||||
Cancelling a Recording discards its candidate artifact and metadata, so
|
||||
canceled Recordings do not appear in recording history.
|
||||
Cassette is a portable artifact whose local database row is only a rebuildable
|
||||
catalog entry. Cassette is the only persistent Replay artifact. A Replay Surface
|
||||
executes one Cassette inside a transient Replay Workspace; neither Surface
|
||||
playback state nor Workspace execution state is stored as product metadata.
|
||||
|
||||
The name lives in `cassette.json`, defaults to the Recording creation timestamp,
|
||||
and may be edited from Desktop. A rename rewrites that manifest, recalculates
|
||||
its SHA-256, and commits the new Recording and Cassette metadata together.
|
||||
|
||||
Each product supplies adapters. Tutti keeps SQLite migrations, semantic state
|
||||
capture/restore, HTTP, local state-root resolution, daemon composition, and
|
||||
Electron launch in `services/tuttid` and `apps/desktop`. TSH supplies equivalent
|
||||
adapters without importing Tutti product code. Tutti's filesystem artifact
|
||||
adapter lives under `services/tuttid/data/agentsessionreplay`; its service layer
|
||||
only maps Workspace DTOs and applies local target policy. Replay runtime state
|
||||
lives only in the isolated Desktop, daemon, and SQLite runtime and is discarded
|
||||
with that runtime. Cassette content never depends on a product database.
|
||||
|
||||
The shared package remains the workflow owner. Tutti's service and Desktop
|
||||
layers own only their adapters and composition decisions; they must not grow a
|
||||
second Recording/Cassette state machine.
|
||||
|
||||
Final replay verification compares typed Agent, Tutti Mode, Workflow, and Issue
|
||||
business state. It
|
||||
does not compare provider-discovered runtime context, capability catalogs, or
|
||||
usage counters because those values describe the current runtime environment,
|
||||
not the recorded scenario. Stable semantic identities are restored directly;
|
||||
comparison reports the first exact business-state path mismatch.
|
||||
|
||||
Recording candidates and published Cassettes also have separate physical
|
||||
locations. A completed candidate is published under its own Cassette id only
|
||||
after an allowlist audit. The portable artifact contains its sole top-level
|
||||
manifest, ordered Activity Events, optional semantic initial state, required
|
||||
semantic expected state, provider protocol tape, and explicitly referenced blobs. It
|
||||
must reject logs, screenshots, SQLite databases, workspace copies, credentials,
|
||||
and every other unrecognized file. Provider frames are limited to 8 MiB per
|
||||
decoded payload and 256 MiB on disk; the complete Cassette is limited to 384
|
||||
MiB. Manifests record per-file and per-provider-frame size evidence so anomalous
|
||||
growth is attributable instead of hidden by compression.
|
||||
|
||||
Provider protocol tape mechanics remain in `packages/agent/daemon/runtime`.
|
||||
Tutti Desktop asks the daemon to validate and resolve one fixed Cassette batch,
|
||||
then launches the separate Electron adapter with Cassette, root Session, and
|
||||
Cassette-directory bindings. This preparation creates no mutable execution
|
||||
metadata. The isolated daemon uses a fail-closed replay transport and does not
|
||||
install the real runtime preparer, provider command resolver, extension runtime
|
||||
resolver, or provider availability probe. Replay does not add a switch to
|
||||
`ProcessSpec`.
|
||||
|
||||
The JavaScript replay runner remains a temporary Tutti Electron adapter. It
|
||||
reads the shared `cassette-policy.json`; it does not define a second Cassette
|
||||
schema or size policy. Activity-engine intents are dispatched into the isolated
|
||||
renderer engine, their correlated command effects are verified there, and only
|
||||
operations without an engine entrypoint use direct daemon stimuli. A normal
|
||||
direct `session.send` waits for canonical Session idle; steer does not.
|
||||
|
||||
Desktop owns the recording toolbar, recording list, replay-window controls,
|
||||
feature gating, and product copy. Completed recording rows launch Replay
|
||||
directly. The primary workspace window does not own a selected Recording or
|
||||
render Replay pause/checkpoint controls. AgentGUI exposes only generic host
|
||||
render slots and contains no recording/replay contracts, state, provider
|
||||
policy, controls, or copy.
|
||||
|
||||
Replay playback is monotonic inside one Replay Surface. Pause and resume keep
|
||||
the same Surface. Moving to the next stable checkpoint temporarily fast-forwards
|
||||
recorded timing, but still consumes every provider frame and performs every
|
||||
outbound assertion. Moving backward or restarting must replace the transient
|
||||
Surface or Replay Workspace; it must not rewind an already-mutated daemon,
|
||||
database, or provider cursor in place.
|
||||
|
||||
Provider frames and activity events share the daemon playback state. Activity
|
||||
events advance by their recorded `occurredAtUnixMs` offset, freeze while Replay
|
||||
is paused, scale with Replay speed, and skip recorded waits during checkpoint
|
||||
fast-forward. Effect verification starts only when its recorded time is
|
||||
reached; a long-running Turn must not be shortened into a runner timeout.
|
||||
|
||||
Cassette schema v7 is the only accepted schema. It stores the ordered
|
||||
`activity-events.jsonl` stimulus stream and a required
|
||||
`checkpoint-plan.json`, plus portable composer defaults under
|
||||
`replayPrerequisites`; no older reader, migration, or fallback exists.
|
||||
Published artifacts contain no source Workspace ID. Replay creates a
|
||||
fresh transient Workspace and binds it only at daemon-restore and product-event
|
||||
boundaries; user payload strings are not recursively rewritten.
|
||||
Queue and steer are recorded as activity-engine intents plus correlated command
|
||||
effects, so replay rebuilds the same transient engine state instead of reducing
|
||||
those actions to HTTP calls.
|
||||
|
||||
Schema v7 serializes Replay Checkpoints. Each checkpoint owns a vector Replay
|
||||
Cursor, a bootstrap, Activity-boundary, or Provider-observation Trigger,
|
||||
portable Logical Subjects, and canonical Readiness Predicates. Recording
|
||||
observes but never pauses. Replay holds every lane at the selected cursor and
|
||||
reports a checkpoint reached only after its trigger, canonical commit, and
|
||||
readiness are confirmed. Renderer hydration adds the runtime-only Inspectable
|
||||
Checkpoint gate.
|
||||
|
||||
The replayable interaction contract has a single cross-language source:
|
||||
`activity-contract.json` in the shared core declares, per intent type, the
|
||||
allowed effect command types and whether an effect is required. The renderer
|
||||
keeps one registry module in sync with it for correlation, stable effect
|
||||
fields, readiness, and rebase rules; the Go core enforces it when an event is
|
||||
recorded, before a Recording completes, and when a Cassette is validated.
|
||||
Sealing is fail-closed: a replayable command without a resolvable causing
|
||||
intent, or still awaiting its result, fails recording completion instead of
|
||||
publishing a Cassette that can only fail later during replay. Replay bindings,
|
||||
drivers, and coordinators mount only inside the isolated replay runtime, and
|
||||
the renderer recorder exists only while a Recording is active; the normal
|
||||
Desktop path carries no replay machinery.
|
||||
|
||||
The default-off `agent.sessionRecording` preference gates process composition
|
||||
at startup. The renderer waits for initial persisted preference hydration
|
||||
before constructing the Workspace service container; Replay consumes that
|
||||
hydrated decision without owning preference loading or update propagation.
|
||||
Disabled Desktop composition creates no Replay manager, access
|
||||
adapter, IPC handler, renderer Replay service, recording binding, recorder map,
|
||||
observer map, or Engine observer. Enabling composition preserves live recorder
|
||||
attachment only for an active Recording. A preference change does not
|
||||
retroactively rebuild a running daemon or renderer; it takes effect on the next
|
||||
process composition.
|
||||
@@ -0,0 +1,20 @@
|
||||
# Architecture Decision Records
|
||||
|
||||
ADRs record consequential decisions and the tradeoffs behind them. They explain
|
||||
why a boundary exists; current architecture and code describe how it is
|
||||
implemented now.
|
||||
|
||||
- [ADR 0001: Codex app-server codegen approach](./0001-codex-appserver-codegen-approach.md)
|
||||
- [ADR 0002: Codexproto pinning and source drift](./0002-codexproto-pinning-source-drift.md)
|
||||
- [ADR 0003: Thread registry and sub-agent routing](./0003-step3-thread-registry-subagent-routing.md)
|
||||
- [ADR 0004: Hydration monotonic cursor](./0004-step4-hydration-monotonic-cursor.md)
|
||||
- [ADR 0005: Turn lifecycle projection](./0005-turn-lifecycle-optimal-projection.md)
|
||||
- [ADR 0006: Durable approval resolver projection](./0006-step6-approval-resolver-durable-projection.md)
|
||||
- [ADR 0007: Sub-agent lane ownership (superseded)](./0007-subagent-lane-owner-callid.md)
|
||||
- [ADR 0008: Turn lifecycle snapshot authority](./0008-turn-lifecycle-snapshot-authority.md)
|
||||
- [ADR 0009: Cross-product Workbench host kernel](./0009-cross-product-workbench-host-kernel.md)
|
||||
- [ADR 0010: Agent Session Replay boundary](./0010-agent-session-replay-boundary.md)
|
||||
- [Codex App-Server Refactor Glossary](./glossary.md)
|
||||
|
||||
New ADRs should state `Proposed`, `Accepted`, `Superseded`, or `Rejected` near
|
||||
the title and link any ADR they replace.
|
||||
@@ -0,0 +1,68 @@
|
||||
# Glossary — Codex app-server refactor
|
||||
|
||||
- **codexproto** — tutti's generated protocol package
|
||||
(`packages/agent/daemon/runtime/codexproto`); typed protocol boundary
|
||||
(enabling infra, per D6). Holds generated types + RPC stubs + hand-maintained
|
||||
type supplement.
|
||||
- **Generated surface** — the full set of protocol types / RPC method stubs /
|
||||
notification types emitted by the codegen pipeline from upstream `export`.
|
||||
- **Wired subset** — the methods/notifications a refactor step actually connects
|
||||
to tutti behavior. This refactor wires only the four-state-machine subset.
|
||||
- **export bin** — `codex-rs/app-server-protocol/src/bin/export.rs`; emits
|
||||
`codex_app_server_protocol.schemas.json` (+ `.v2`) and filtered TypeScript.
|
||||
- **Pinned commit** — the codex git commit codexproto is generated against and
|
||||
stamped with; distinct from the binary version baseline (`codex-cli 0.142.5`)
|
||||
captured in Step 0.
|
||||
- **Four state machines** — thread identity (B) / turn+compaction (C) /
|
||||
session-lifecycle (D) / hydration-snapshot (A); the real refactor target (D6).
|
||||
- **Used-but-unexported method** — a method tutti calls at runtime that is absent
|
||||
from the upstream exported schema (e.g. `collaborationMode/list`). Lives in the
|
||||
manual type supplement + relies on the runtime binary actually serving it.
|
||||
- **Unknown-method fallback** — dispatch path for a notification/server-request
|
||||
whose method is not in the generated surface; logs + degrades, never crashes.
|
||||
Preserves `map[string]any`'s tolerance of a floating runtime binary.
|
||||
- **Pinned source SHA vs binary baseline** — two distinct version axes: the codex
|
||||
git commit codexproto is generated from, vs the `codex-cli` version the daemon
|
||||
spawns (`0.142.5`, Step 0). CI drift only guards the former.
|
||||
- **OwnerThreadID** — new optional field on `activityshared.Event`. Empty =
|
||||
main/top-level agent; non-empty = the sub-agent child thread that produced the
|
||||
event. Preserves child identity so nested sub-agent cards are a cheap later UI
|
||||
addition. tutti's analogue of traycer's `parentBlockId`.
|
||||
- **Identity-preserving routing (option 丙)** — Step 3's chosen model: suppress
|
||||
child lifecycle noise, re-home substantive child events tagged with
|
||||
`OwnerThreadID`, keep the summary card parent-item-driven. Contrast: option 1
|
||||
(drop all) and t3code flat re-tag (garbles concurrent output).
|
||||
- **receiverThreadIds** — required array on the `collabAgentToolCall` item; the
|
||||
parent declaring which child threads it spawned. The linkage source for routing
|
||||
(not `Thread.parentThreadId`).
|
||||
- **Delivery cursor (Version)** — redefined (ADR 0004) as a store-assigned
|
||||
per-session monotonic, gap-free counter used only for incremental sync
|
||||
(`afterVersion`). NOT a timestamp, NOT a stable cross-load key. Display order
|
||||
uses `OccurredAtUnixMS`; identity uses `MessageID`.
|
||||
- **Same-ms collision** — the pre-fix daemon bug: user row + first reply event
|
||||
sharing one ms-timestamp Version, both skippable by an `afterVersion` cursor.
|
||||
- **Load-relative counter** — the Version counter restarts and re-assigns per
|
||||
session load (store is replay-rebuilt, not durable); safe because the desktop
|
||||
resyncs at 0 and keys by MessageID. Contrast t3code/traycer durable sequences.
|
||||
- **Unified projection** — the optimal end state (ADR 0005): one per-session reducer
|
||||
folds turn state + messages + compaction + approvals into explicit state,
|
||||
reconciled against the Step-4 snapshot; matches t3code's single `sequence` log /
|
||||
traycer's single chat event log. Replaces tutti's two parallel mechanisms.
|
||||
- **turnPhase** — explicit turn state enum (idle/running/compacting/interrupting/
|
||||
terminal{completed|failed|canceled}) owned by the reducer; terminal is a phase,
|
||||
not a status whitelist. Replaces the scattered 7-field implicit state.
|
||||
- **Command/observe split** — non-blocking `Exec` (submit → handle; observe via
|
||||
event stream + projected state), reached via a strangler shim over the blocking
|
||||
signature. Removes the wedge/floor/single-turn constraints by construction.
|
||||
- **Strangler shim (Exec inversion)** — the risk control for ADR 0005 Step 7: keep
|
||||
the blocking `Exec([]events,error)` as a thin wrapper over the async core; migrate
|
||||
callers incrementally; delete the wrapper last. Reversible, no big-bang.
|
||||
- **serverRequest/resolved** — codex notification that a server-request was resolved
|
||||
(possibly out-of-band). The authoritative terminal for a pending approval; tutti
|
||||
does not handle it today → the stall class (1ec14c03). ADR 0006 adds it.
|
||||
- **Durable pending approval** — an approval represented as a reconcilable item in the
|
||||
unified projection (pending/resolved/interrupted), not a parked goroutine on a
|
||||
channel. Responder holds codex's RPC and responds async. (ADR 0006)
|
||||
- **Interrupted-pending policy** — on reconnect, a surviving pending approval is marked
|
||||
interrupted + re-offered/re-driven, never silently rejected; RPC revival is not
|
||||
assumed (bounded by codex re-issue behavior on resume). (ADR 0006)
|
||||
Reference in new issue
Block a user