After the turn ends the run fiber that routes child-thread events may be
gone, so text left to the coalescer's timer flush could drop the tail of
a subagent stream (cursor bugbot review finding on the coalescer).
Co-Authored-By: Claude Fable 5 <[email protected]>
ACP streams a subagent's result per token, and emitSubagentAssistant
persisted a full-row message.updated + turn-item.updated event pair per
chunk — one 6KB grok subagent result amplified into ~2700 stored events,
14% of a whole session's event table (audit plan #10). Streamed chunks
now accumulate and emit at most once per 100ms window; the final text is
always flushed immediately on task completion, so the projection stays
exact. The grok_subagent_lineage fixture now asserts each child result
persists a single coalesced message.updated event (was one per chunk).
App-checked: a real streaming ACP result (4190 chars) persisted 4
message.updated events instead of thousands.
Co-Authored-By: Claude Fable 5 <[email protected]>
One codex app-server process multiplexes many app threads (the opener
plus every native subagent child), but the protocol logger froze the
opener's threadId at open time, so all traffic landed in the opener's
log file — and rotation of that busy file destroyed other threads'
native ground truth (audit plan #9, threads c878541b/de5f191a/68f7595b/
af66fc2c had no log file at all). The logger now resolves the target per
frame: it extracts the native thread id from each frame and looks it up
in a per-session route map seeded when a root turn or subagent thread
registers, falling back to the opener for unrouted frames.
App-verified with a real codex subagent spawn: the two subagent native
threads each got their own dedicated log file containing only their own
traffic (94 and 54 frames), where previously everything multiplexed into
the parent's file. Unit tests cover native-thread-id extraction across
decoded/raw frame shapes and the two-thread routing decision.
Co-Authored-By: Claude Fable 5 <[email protected]>
The native provider logs are the debugging ground truth, but SDK
rejections (query open, message stream, prompt offer, agent open,
run start/wait) raised errors without any log write — a failed turn
left the log ending mid-conversation with no explanation (audit plan
#4: neither of thread 721fc23c's failed turns was explainable from its
log). The Claude and Cursor runners now tap every fallible SDK boundary
and write a runner.error frame carrying the redacted cause chain.
App-verified: with a broken Claude binary the native log now records
`runner.error messages.stream | Claude Agent SDK query failed. ← Claude
Code native binary not found at ...` where it previously went silent.
Co-Authored-By: Claude Fable 5 <[email protected]>
A run cancelled by the startup/shutdown reconcile was indistinguishable
from a user cancel: the user's message simply never got an answer and no
explanation appeared anywhere (audit plan #5, threads 721fc23c and
48663fb7 — cursor crash and server restart both ate the turn silently).
The reconcile now appends a "Run interrupted" error item per terminalized
run carrying the reason ("Cancelled because the server restarted/shut
down before the provider work completed."), ordinal-appended after all
projected items to respect the thread-wide position uniqueness.
App-verified: killed the backend mid-turn; after restart the thread
shows "Run interrupted — Cancelled because the server restarted before
the provider work completed."
Co-Authored-By: Claude Fable 5 <[email protected]>
Locks in per-uuid assistant text segmentation (audit plan #11): the
6d618dc4 MCP session on build fc23be8184 merged 5 interleaved assistant
text segments into one separator-less end-of-turn item ordered after all
tool calls. The current emitAssistantTextArtifacts path already projects
one item per SDK message uuid; this fixture asserts text → command → text
ordering survives replay.
Co-Authored-By: Claude Fable 5 <[email protected]>
Failed read/grep/glob tools projected only {status: failed, pattern} —
the provider's error message was unrecoverable from projections, and
successful outputs were dropped too (audit plan #12, thread 3029dc85
item prt_f15692f3). The file_search contract gains optional output and
error fields; the OpenCode adapter maps part.state.output/error by
terminal status.
App-verified with a real OpenCode agent: a successful package.json read
projects the content in output, and a read of a nonexistent file
projects status failed with error "File not found: ...".
Co-Authored-By: Claude Fable 5 <[email protected]>
A failed cursor turn projected only the generic "Provider turn failed."
because the adapter read a nonexistent `error` field off RunResult
(@cursor/sdk 1.0.22 carries no error text on results; errorCode lives
only in the SDK's internal run store). Persist what the result does
carry — run id, requestId, and duration — so failures can be matched to
Cursor-side logs (audit plan #3, thread c9e72a05 run 2 lost requestId
beca30c7 + 440s duration). The speculative `error` read stays as a
makeProviderFailure cause for future SDK versions.
Co-Authored-By: Claude Fable 5 <[email protected]>
Adapter errors are tagged wrappers whose message getter is a fixed string
("Claude Agent SDK query failed.", "Failed to start run ...") while the
real defect lives in .cause — makeProviderFailure only read the wrapper,
so every failed run persisted a generic message with the root cause
recorded nowhere (audit plan #2: 8 undebuggable failures across 5
threads). makeProviderFailure now walks the cause chain (bounded depth,
deduped) and joins the messages, and picks up the deepest error code.
The run-execution failure log also prints the Cause pretty-formatted
instead of a depth-elided object.
App-verified: breaking the Claude binary path now projects
"Claude Agent SDK query failed. ← Claude Code native binary not found at
/tmp/nonexistent-claude-binary. ..." as the user-visible error item.
Co-Authored-By: Claude Fable 5 <[email protected]>
Introduce a provider-agnostic continuation request queue, worker, and optional
hasPendingBackgroundWork idle pin so adapters can surface post-settle native
wake traffic as first-class runs. No adapter offers continuations here; the
per-provider specialty commits wire attach mode.
Also fix shared run event ingestion dropping late background item
completions. The per-run provider event fiber stopped as soon as the root
turn terminalized and no child provider turns or subagent rows remained
active. Background-capable turn items (background commands, monitors,
subagent rows) that complete after root settlement then lost their trailing
turn_item.updated: the projection kept the item running forever even when
the underlying work (and any wake) succeeded.
Track non-terminal command_execution, dynamic_tool, and subagent turn items
owned by the run or an owned child thread, and keep ingesting until they
terminalize, gated on the root terminal status being completed so
interrupted and failed runs do not pin the stream open.
Repro evidence: Codex emits subagent.updated(completed) before the trailing
turn_item.updated(completed), so post-settle subagent items stuck at running
in the UI; background command items never completed in the
codex-background-exec-wake projection even though the wake run fired. The
same stuck-running signature appears on the Claude background Bash wake and
Grok monitor paths, which reuse this shared ingestion loop.
Ports main's features onto the V2 orchestrator and wire protocol:
- HTTP snapshot loading (#3719): new OrchestrationV2ThreadDetailSnapshot
contract, /api/orchestration/{shell,threads/:threadId} endpoints served
from the V2 engine (orchestration-v2/http.ts), afterSequence resume on
the V2 subscribeShell/subscribeThread WS methods, and V2-typed client
snapshot loaders wired into shell/thread sync with warm-cache resume.
- Thread cache now persists the snapshot sequence (cache schema v3) so
warm caches resume via afterSequence instead of refetching.
- Mobile: main's react-navigation architecture retained; branch's V2
surfaces (relationships banner, queue control, activity inspector,
work-log thread links, fork-from-run) ported off expo-router; thread
status presentation and awareness diagnostics mapped to V2 runtime
fields; pending-task start-turn helper gains creationSource "mobile".
- Retired v1-only additions from main (v1 RPC schemas, session/latestTurn
awareness heuristics, v1 engine test updates) where the branch already
replaced those systems with V2 equivalents.
Co-Authored-By: Claude Fable 5 <[email protected]>
- Let started threads switch providers when handoff is supported
- Keep model picker and block reasons aligned with thread capabilities
- Update logic tests for the new provider-switching rule
- remove ACP model discovery and mismatch probe code
- update provider, orchestration, and tests for SDK-based flows
- refresh marketing copy to match the SDK runtime
- Move desktop and server state paths to `userdata-v2`
- Handle Codex subagent activity events in orchestration v2
- Update related path and lifecycle tests
- Detect xAI Task tool calls as native subagents
- Project child session IDs and buffered chunks into the orchestration tree
- Add replay fixture coverage for Grok subagent lineage
Carry forward the reusable ACP replay, drain, and xAI extension work from #3156 while retaining V2-owned adapters, presentation, and provider-acknowledged cancellation semantics.
Co-authored-by: codex <[email protected]>
Share V2 item-to-entity linkage across clients and give mobile targeted execution, provider, request, checkpoint, search, subagent, and handoff inspection without reconstructing the timeline.
Co-authored-by: codex <[email protected]>
Use the authoritative visibleTurnItems projection directly so mobile preserves server ordering, inherited items, and synthetic items without rebuilding a parallel feed.
Co-authored-by: codex <[email protected]>
- Remove subagent prefixes from titles and timeline labels
- Hide subagent threads in the sidebar and add parent-thread navigation
- Align thread details, picker, and git/script controls with panel styling
- Move Open in editor shortcut handling into a shared hook
- Show Open in picker inside the thread details panel and restyle PR actions
- Tighten popover positioning for the panel layout
- Move the inline thread panel to an absolute overlay
- Add shared inset styling so the timeline and composer avoid overlap
- Rename composer glass styling to the shared floating surface class
- Add parent-thread records for spawned child threads
- Persist Claude subagent progress as reasoning items
- Tighten projection verification around readable thread projections
- Treat preparing as an active turn state in mobile and server flows
- Tighten ACP model option validation and selection reconfiguration
- Add coverage for turn mapping, raw protocol logging, and recovery paths
- Migrate web and mobile state, commands, and persistence to V2 projections
- Render conversations from authoritative visible turn items
- Harden runtime policy, launch handling, attachments, and cache invalidation
- Define Shape 4.0 for the client cutover and product parity
- Define Shape 4.5 for V2-native UI capabilities
- Defer existing V1 state migration to an out-of-scope Stage 5
Retain the existing event-sourced application data plane for projects and shell state while making orchestration v2 the sole agent runtime. Adapt v2 events and receipts to the shared infrastructure and remove the v1 provider reactors.
- Add scoped thread list, read, send, wait, and interrupt tools
- Track creation provenance and map provider turns across adapters
- Centralize thread lifecycle operations in a management service
- split streaming assistant and reasoning output into separate segments
- filter hidden interruption artifacts from projections and replay fixtures
- keep visible timeline positions stable when upserting streamed items
- Register orchestration tools on the MCP HTTP server
- Grant orchestration capability to MCP sessions
- Add service and integration coverage for delegated tasks and thread creation
- Add shared compact subheader styling for preview, file, and diff panels
- Open diff files in the thread file viewer when available
- Fix macOS cursor auto-hide and Option-modified shortcut matching
- Replace attachment and favicon routes with signed asset URLs
- Harden workspace and attachment asset resolution
- Update browser preview components and shared contracts
- Tie preview and debugger listeners to Effect scopes
- Factor shared automation helpers for snapshot and input handling
- Improve cleanup for browser preview sessions and port scanning
- derive preview partitions through `BrowserSession`
- serialize session state and async preview control flow
- update tests for screenshot, automation, and partition behavior
- Move preview session and IPC wiring into the new preview module
- Tighten IPC validation with schema-based handlers
- Update preview asset paths and tests for the browser preview port
- Move MCP session registry and preview broker out of `Layers/` and `Services/`
- Update imports, tests, and server wiring to use the new module layout
- Add IPC and runtime plumbing for preview annotation theming
- Generate and ship annotation CSS for the desktop overlay
- Add pointer and artifact handling for browser preview interactions
- Add structured annotation payload validation and tests
- Update preview preload to capture selected elements, regions, and strokes
- Wire new preview annotation UI into the web app
Co-authored-by: codex <[email protected]>
Adds an in-page element picker to the preview browser. Clicking the
crosshair button in the chrome row activates a blue-highlight picker
inside the guest webview; clicking an element captures its component
name (via react-grab), source location, html/css preview, and selector,
then attaches it to the chat composer as a chip that serializes into an
`<element_context>` block in the outgoing message.
Architecture:
- Per-`<webview>` preload bundle (`preview-pick-preload.cjs`) renders
the overlay, hosts the picker event loop, and bubbles the picked
payload back to main via the per-WebContents `wc.ipc` channel (not
`sendToHost`, which only fires on the host renderer's <webview>
element and never reaches main).
- Main coordinates via `PreviewViewManager.pickElement(tabId)`, which
cancels any in-flight session, force-focuses the guest (so the first
click on a remote page actually reaches the preload), then awaits the
payload. User-initiated cancels (Escape, beforeunload) echo `null`
back to main; main-initiated cancels and supersession tear down
silently to avoid the new-pick-resolves-with-stale-null race.
- Renderer fetches partition + webPreferences + preload URL in a single
`getPreviewConfig()` IPC call, snapshots the previously-focused host
element before triggering a pick, and restores focus when the pick
resolves so the user's textarea cursor isn't lost.
Security posture for the guest webview:
- `webpreferences="contextIsolation=false,sandbox=true,nodeIntegration=false"`
centralized in `preview-webview-preferences.ts`. contextIsolation off
is required so react-grab's `getElementContext` can reach the page's
React DevTools hook on `globalThis`. sandbox stays on so the page
cannot reach Node APIs even with shared globals (without it, the
preload's `require` would land on the page's `globalThis` and any
third-party site could send arbitrary IPC to main).
- Defense in depth: a `will-attach-webview` handler in main, gated on
the preview partition, force-pins `sandbox: true`, all
`nodeIntegration*: false`, and the absolute preload PATH (not URL —
that field rejects file:// URLs with "preload script must have
absolute path" and silently disables the picker).
Composer + transcript integration:
- New `elementContexts` slice in `composerDraftStore` (mirrors the
terminal-context slice: dedup by selector+tag+component+url, persist
via partializer, restore on send-failure retry).
- `ComposerPendingElementContexts` chip row above the editor.
- `deriveDisplayedUserMessageState` now strips both `<element_context>`
AND `<terminal_context>` blocks (element first, since it's appended
last) and exposes element entries to `MessagesTimeline`, which renders
them as compact chips beneath the message body.
- Pick button is disabled with explanatory tooltip when the page failed
to load (the React `<PreviewUnreachable>` overlay covers the webview,
so picks would silently dangle otherwise).
Tests added:
- `preview-webview-preferences.test.ts` locks down the security flags
(contextIsolation=false, sandbox=true, nodeIntegration=false, no
whitespace, only true/false literal values).
- `preview-pick-label-position.test.ts` covers the floating-label
clamp/flip math (no off-screen overflow, flip-below when no room
above, etc.).
- `picked-element-payload.test.ts` validator coverage.
- `elementContext.test.ts` for the serialization round-trip,
normalization, dedup, and label formatting.
- `composerDraftStore.test.ts` element-contexts slice (add, dedup,
remove, set, clear, persistence round-trip).
- `ChatView.logic.test.ts` sendable-content-with-element-only.
Build: new `tsdown` entry inlines react-grab + bippy into the picker
preload bundle (~59KB / 19KB gzipped).
Adds a desktop-only browser preview that lives in the right panel slot
alongside plan/diff. Lets the user point an Electron <webview> at any
URL — typed into a chrome-style URL bar, clicked from the empty-state
list of detected localhost dev servers, or auto-opened by a project
script with `previewUrl` set. Single-tab per thread.
Server (Effect/Layers):
- PreviewManager: per-(thread, tab) session metadata via SynchronizedRef
+ PubSub<PreviewEvent>; survives WS reconnect via `list`/replay.
- PreviewPortScanner: lsof on macOS/Linux, TCP probe fallback on
Windows; reference-counted polling so we only scan when subscribed.
- WS RPC + streams (`preview.open|navigate|refresh|close|list|reportStatus`,
`subscribePreviewEvents`, `subscribeDiscoveredLocalServers`).
Desktop:
- PreviewViewManager owns Chromium WebContents per tab, mediates
navigation/zoom/devtools/clear-storage. registerWebview gates by
webContents.getType() === "webview" and host-window match.
- IPC channels for create/close/register/navigate/back/forward/refresh/
zoom/hardReload/openDevTools/clearCookies/clearCache/getBrowserPartition.
- Forwards app-level shortcuts (mod+shift+J, mod+K, mod+,, mod+W) from
the webview back to the main window.
- Persisted browser session partition (cookies, cache).
Web:
- PreviewPanel/PreviewView/PreviewWebview render the surface; chrome row
with back/forward/refresh + URL input + Open-in-browser + 3-dot menu
(Hard reload, DevTools, Zoom −/+/reset, Clear cookies/cache).
- usePreviewSession subscribes to server events; usePreviewBridge
mirrors desktop state into the store and forwards Loading→Success/
LoadFailed back to the server.
- previewStateStore: per-thread snapshot + desktopOverlay + recently-
seen URLs (Zustand).
- rightPanelStore arbitrates plan vs. preview vs. diff; ChatView's
toggles strip the `?diff=1` URL hint when switching to preview and
vice versa so the panels are mutually exclusive.
- Top-nav Globe toggle in ChatHeader (desktop builds only) and a
`mod+shift+J` keybinding routed via a typed previewActionBus.
- PreviewEmptyState lists detected localhost servers (scanner +
configured project URLs + recently-seen) with live "listening" pulse.
- PreviewUnreachable: theme-aware port of Chromium's "site can't be
reached" page.
- Resizable inline panel (RightPanelResizeHandle + useResizableWidth);
width persists to localStorage on drag-end.
- Terminal link "Open in preview" context-menu integration for loopback
URLs.
Contracts:
- preview.ts schemas (PreviewSessionSnapshot, PreviewNavStatus,
PreviewEvent, RPC inputs/results, DiscoveredLocalServer).
- ProjectScript schema gains optional `previewUrl` + `autoOpenPreview`.
- New keybinding commands: preview.toggle/refresh/focusUrl/zoomIn/Out/
resetZoom; new `when:` contexts `previewFocus` / `previewOpen`.
Shared:
- @t3tools/shared/preview: normalizePreviewUrl, isPreviewableUrl,
isLoopbackHost, newPreviewTabId, LSOF_LOCAL_HOST_TOKENS.
Tests:
- contracts: schema decode tests for all preview events/snapshots/inputs.
- shared: URL normalization coverage.
- server: PreviewManager (open/navigate/reportStatus/refresh/close,
multi-subscriber isolation, idempotency); PortScanner (lsof parsing
including IPv6, TCP probe, reference-counted polling).
- web: previewStateStore (per-tab event application, dedupe,
reconnect recovery); rightPanelStore arbitration.
Send full canonical target-thread context when a provider switch consumes a merge-back, and cover returning to an existing provider thread after a cross-provider fork.
Co-authored-by: codex <[email protected]>
Allow a pending merge-back to be consumed while changing providers and deliver both the provider-switch history and fork delta to the selected provider.
Co-authored-by: codex <[email protected]>
Record provider fixtures for continued forks and sibling merge-backs, exercise context survival end to end, and stop completed run listeners from consuming later provider events.
Co-authored-by: codex <[email protected]>
- Restrict release workflow defaults to read-only access
- Grant `id-token` only to the publish job
- Document safe handling for `pull_request_target` in PR size checks
- add interrupt and mid-tool replay fixtures for Claude and Codex
- log Claude Agent SDK protocol frames to native event traces
- project Codex commandExecution start events into orchestration updates
- add active steering and interrupt-restart replay fixtures
- update Claude adapter/orchestrator turn handling for steering
- refresh replay and integration test coverage
- Record Claude SDK transcripts across multiple prompts and restart/query modes
- Add approval and tool-call replay coverage for new orchestration fixtures
- Update Claude adapter testkit to model open/prompt/permission frames
- Move Claude provider runtime logic into its own module
- Share the SDK query runner between live and replay paths
- Add replay driver error wrapping for unexpected failures
- Move Codex replay recording into `apps/server`
- Add Claude Agent SDK replay fixtures and test harness
- Update orchestration-v2 fixture scenarios and docs
- Map fork and merge-back turns into stored handoffs and transfer resolutions
- Add shell snapshot projection support plus coverage tests
- Update replay fixtures and web contracts for the new turn flow
OpenCode can leave the long-lived serve child in the spawned process group after the wrapper exits. Provider refresh owns only a scoped inventory probe, so cleanup targets that local process group when the refresh scope closes.
Constraint: Keep active OpenCode thread sessions scoped to their own session lifecycle.
Rejected: Disable provider refresh | would hide model and auth state changes.
Confidence: high
Scope-risk: narrow
Tested: bun run test src/provider/Layers/OpenCodeProvider.test.ts src/provider/Layers/OpenCodeAdapter.test.ts
Tested: bun fmt
Tested: bun lint
Tested: bun typecheck
Tested: bun run build:desktop
- Add context transfer IDs, schemas, and projections
- Support cheap fork creation and Codex native fork rollback
- Cover fork idempotency and replay behavior in tests
- Document the target orchestration graph, IDs, lifecycles, and capability model
- Add Codex app-server probe fixtures and update the probe test harness
- Use codex app-server snapshots for auth, models, and skills
- Remove legacy CLI/config discovery paths and related helpers
- Update tests for the new provider status flow
- Close the managed native event logger when the adapter layer tears down
- Make session runtime close idempotent with an atomic closed flag
- Add coverage for flushing thread native logs on shutdown
- Transfer session-owned scopes into adapter state
- Ensure runtime scopes close on stop and startup failure
- Add regression coverage for scoped lifecycle cleanup
- Use strict TurnId and ProviderItemId parsing in Codex session routing
- Decode in-memory stdio chunks in streaming mode to avoid split UTF-8 corruption
- ensure `chat.new` creates a fresh draft after a promoted draft thread
- enforce terminal cap per split group (4) while allowing additional terminal groups
- refine sidebar row selected/active styling via shared class-name logic and tests
* feat(web): add shift-click multi-select for sidebar threads
Add support for selecting multiple threads in the sidebar via
Cmd/Ctrl+Click (toggle) and Shift+Click (range select), with
bulk context menu actions for Delete and Mark Unread.
- New threadSelectionStore (Zustand) for ephemeral selection state
with anchor-based range selection and no-op guards
- Platform-aware modifier detection (Cmd on Mac, Ctrl elsewhere)
matching existing isMacPlatform pattern in terminal-links
- Extracted deleteThread helper from handleThreadContextMenu for
reuse by bulk delete, with deletedThreadIds set for correct
fallback navigation during batch operations
- Selected threads share the active thread highlight style
- Escape key clears selection; plain click clears and navigates
- Right-click on selected thread shows bulk menu; right-click on
unselected thread clears selection and shows single-thread menu
- 22 unit tests covering toggle, range select, clear, remove,
and edge cases (cross-project fallback, anchor stability)
* fix(web): filter deleted threads from worktree orphan check during bulk delete
When bulk-deleting threads that share a worktree, the stale threads
closure caused getOrphanedWorktreePathForThread to see the other
threads-being-deleted as still alive, suppressing the orphaned
worktree cleanup prompt. Filter out deletedThreadIds (keeping the
current thread) so the check correctly identifies worktrees that
will have no surviving references.
* fix(web): fix shift-click range selection, distinct selection styling, and deselect on click away
* Preserve thread multi-select on safe sidebar control clicks
- avoid clearing selection on mousedown for thread items and marked safe controls
- centralize the selection-safe selector and add logic tests for clear vs preserve behavior
- simplify thread selection store typing by merging state/actions interface
---------
Co-authored-by: Julius Marminge <[email protected]>
- Replace the inline composer PR menu with a dedicated `PullRequestThreadDialog`
- Remove `/checkout-pr` from composer slash-command parsing and tests
- Fix branch selector virtualization sizing for the checkout-PR row
- Change local PR worktree branch format from `pr/<number>-<head>` to `t3code/pr-<number>/<head>`
- Update GitManager tests to assert the new branch naming convention
- Treat remotes that only differ by trailing slash after `.git` as the same remote
- Add a GitCore regression test for trailing-slash remote reuse
- Refactor `GitHubCli` tests to `@effect/vitest` layer-based effect tests with reset cleanup
- create a unique local branch name for cross-repo PR worktrees (`pr/<number>-<head>`)
- fetch/set upstream against that local branch instead of overwriting local `main`
- add regression tests for fork PRs where head branch is `main`
- Restore/set upstream tracking when preparing local and reused PR worktrees
- Derive fork `owner/repo` from PR URL when GitHub omits `headRepositoryNameWithOwner`
- Expand GitManager tests to cover local mode, URL-derived fork identity, and reused worktree upstream recovery
- move branch filtering logic into `BranchToolbarBranchSelector`
- remove unused `filterBranchPickerItems` helper and related tests
- keep create-branch option pinned while filtering by query
- add GitCore helpers to ensure remotes, fetch remote branches, and set upstreams
- extend GitHub CLI parsing to include cross-repo PR metadata and repo clone URLs
- update GitManager flow and tests to materialize fork heads and keep tracking on fork remotes
- add `resolveBranchSelectionTarget` to unify checkout cwd/worktree decisions
- reuse existing worktrees when available, including switching back to main repo
- update branch selector to use shared logic and add targeted unit tests
- Add shared branch picker filtering logic and tests, including PR-reference-only results
- Improve branch selector UX/perf with deferred query filtering, conditional virtualization, and status-based current branch resolution
- Only expose and handle `/checkout-pr` for local draft threads in chat and toolbar UI
- Add git APIs to resolve PR refs and prepare PR thread workspaces
- Support fetching PR head refs into local branches and reusing existing worktrees
- Wire new websocket/contracts/web composer flows for PR-based thread creation
- Expand server/web/contracts tests for PR routing and branch/worktree behavior
- Replace manual UUID byte formatting fallback in `apps/web/src/lib/utils.ts`
- Use `Effect.runSync(Random.nextUUIDv4)` when `crypto.randomUUID` is unavailable
Replace direct crypto.randomUUID() calls with a randomUUID() helper in
utils.ts that falls back to crypto.getRandomValues() when the browser
is not in a secure context (e.g. plain HTTP on a non-localhost address).
Signed-off-by: Hiram Chirino <[email protected]>
Fixes: #769
* Updated wording for label from 'Commit, Create & Push PR' to 'Commit, Create & PR' to allow for it to fit within the current UI size constraints.
wording change
- Map Codex `error` notifications with `willRetry: true` to `runtime.warning`
- Keep active turns/sessions running during reconnect warnings
- Add adapter and ingestion tests for retry-warning behavior
- Keep long plan cards collapsed with lightweight preview text by default
- Render full plan markdown only after explicit expand to reduce thread open slowness
- Add tests for preview/strip helpers and browser coverage for expand behavior
- prevent accidental project toggles after drag operations
- switch project rows to Collapsible for stable expand/collapse animation
- add optional hidden scrollbar mode to ScrollArea and apply it in SidebarContent
- wire project list to dnd-kit sortable with vertical drag constraints
- prevent accidental expand/collapse clicks during drag gestures
- update store logic/tests and add dnd-kit dependencies
- Replace manual timeout debounce logic with `@tanstack/react-pacer`'s `Debouncer`
- Persist updates via `maybeExecute` to reduce localStorage write thrashing
- Flush pending persistence on `beforeunload` to avoid losing recent state
The ProviderHealth layer blocked server startup with two sequential CLI
spawns (codex --version + codex login status), each with a 4-second
timeout, delaying startup by up to 8 seconds.
Run health checks in the background via Effect.runPromise so the layer
resolves immediately with a placeholder status. Add an onReady callback
to ProviderHealthShape so wsServer can push the resolved statuses to
connected clients once checks complete, preventing early-connecting
clients from showing "Checking..." indefinitely.
During active sessions, every domain event triggered a full
syncSnapshot (IPC fetch + state rebuild + React re-render cascade) and
sometimes a provider query invalidation. Events fire in rapid bursts
during AI turns.
Replace per-event processing with a throttle-first pattern: schedule a
flush on the first event, absorb subsequent events within a 100ms
window, then sync once. Provider query invalidation is batched via a
flag. Since syncSnapshot fetches the complete snapshot, no events are
lost by skipping intermediate syncs.
The useStore subscriber called persistState on every state mutation,
triggering JSON.stringify + localStorage.setItem synchronously. It also
ran 8 localStorage.removeItem calls for legacy keys on every fire.
Wrap the subscriber with a 500ms debounce so rapid state changes batch
into a single write. Move legacy key cleanup behind a one-time flag so
it runs only once per page load. Add a beforeunload handler to flush
the final state.
Every keystroke triggered full JSON serialization of all composer drafts
(including base64 image attachments) and a synchronous localStorage
write. At normal typing speed this caused 5+ writes/sec, blocking the
main thread and creating noticeable input lag.
Wrap the Zustand persist storage with a 300ms debounce. In-memory state
updates remain immediate; only the serialization and storage write are
deferred. A beforeunload handler flushes pending writes to prevent data
loss. The removeItem method cancels any pending setItem to avoid
resurrecting cleared drafts.
Adds unit tests for the DebouncedStorage utility covering debounce
timing, rapid writes, removeItem cancellation, flush, and edge cases.
- Measure composer width from the form element in initial and resize paths
- Avoid relying on ResizeObserver contentRect width for compact footer layout decisions
- Replace `SIDEBAR_INSET_BASE_CLASSNAME` with an inline class string in `sidebar.tsx`
- Delete the now-unused `sidebar.logic.ts` helper and its focused unit test
- add shared footer layout breakpoint helper with tests
- switch chat composer footer to compact menu when width is constrained
- preserve plan sidebar toggle behavior while consolidating footer actions
- add `min-w-0` to chat/flex containers to prevent composer/sidebar overflow
- move `BranchToolbar` into the chat column so layout stays aligned with plan sidebar
- extract sidebar inset base classes to shared logic and add a regression test for `min-w-0`
- derive toast indices and Y offsets from the filtered visible toasts
- pass frontmost height and per-toast layout vars to the viewport/item styles
- add unit tests for visible toast layout calculations and height normalization
- delete `shouldShowFastTierIcon` and its test
- remove Zap icon badges from slash model commands and provider model picker
- simplify related ChatView props and memo dependencies
- Drop `serviceTier` from orchestration/provider contracts and server dispatch paths
- Remove service-tier app setting/UI and related resolver logic
- Keep fast badge behavior tied to explicit fast-mode boolean
- add "Plan Ready" sidebar status when a plan-mode turn is settled with a proposed plan
- update sidebar logic tests to cover the new status and expanded thread inputs
- add `Sidebar.logic.ts` to centralize thread status pill resolution
- show `Awaiting Input` when plan mode is blocked on user responses
- add unit tests for unseen completion and status-priority behavior
- prevent plan collapse/expand clicks from triggering chat scroll anchoring
- Use a toast error for add-project failures during immediate folder browse
- Keep inline add-project error state for non-immediate flows
- Include `shouldBrowseForProjectImmediately` in callback dependencies
- add `shouldOpenProjectFolderPickerImmediately` to centralize Sidebar behavior
- trigger folder browse directly when adding a project in desktop Electron
- keep manual path entry for mobile layouts and non-Electron, with tests for all cases
the rail's 16px hit area at z-20 sits right where the native os scrollbar
lives when the sidebar is in offcanvas mode and collapsed. this causes clicks
and drags on the scrollbar to toggle the sidebar instead on windows and linux.
scoping pointer-events-none to [data-collapsible=offcanvas][data-state=collapsed]
fixes the interception without affecting icon mode where the rail needs to stay
clickable.
Electron derives the userData path from productName in package.json,
which produces directories with spaces and parentheses on all platforms
(e.g. ~/.config/T3 Code (Alpha) on Linux). This is hostile to shell
usage and violates Linux XDG naming conventions.
Override the userData path via app.setPath() before the ready event to
use a clean lowercase name (t3code). If the legacy directory already
exists it is used as-is so existing users keep their Chromium profile
data (localStorage, cookies, sessions, cache).
This follows the same pattern VS Code uses — keeping productName for
display purposes while explicitly setting the data directory path.
Closes#578
`rawSearch` is already the output of `parseDiffRouteSearch` via the
`useSearch` select transform. The `useMemo` at line 760 re-parsed it
through the same function with an unsafe `as Record<string, unknown>`
cast, producing an identical result. Use `rawSearch` directly instead.
When the persisted state key was bumped from v7 to v8 in 689dda59,
the v7 key was not added to LEGACY_PERSISTED_STATE_KEYS. Users who
ran the app during the ~3-week v7 window retain a stale
`t3code:renderer-state:v7` entry in localStorage that is never
cleaned up.
The terminal RPC test used raw waitForMessage to receive the expected
terminal.event push, but a server.configUpdated push from the
keybindings file watcher can arrive first depending on OS timing.
Replace with the existing waitForPush helper that filters by channel.
* Add checkout and Node setup to release updater publish job
- Ensure the updater publish job checks out the target ref
- Initialize Node using the repository's package.json version file before downloading artifacts
* Fix release finalize lockfile refresh
- Ensure the updater publish job checks out the target ref
- Initialize Node using the repository's package.json version file before downloading artifacts
* fix(scripts): enable shell mode on Windows for .cmd shim resolution
On Windows, tools like `bun`, `npm`, `turbo`, and `bunx` are installed
as `.cmd` shims. Node's `child_process.spawn` cannot resolve these
without `shell: true`, causing `PlatformError: NotFound` on fresh
builds where there is no Turbo cache.
Add `shell: process.platform === "win32"` to all ChildProcess.make
calls in cli.ts, dev-runner.ts, and build-desktop-artifact.ts.
Closes#474
* docs: add comments explaining Windows shell spawn requirement
* docs: add shell spawn comments to remaining call sites
Adjust the Electron sidebar header to properly center the T3 wordmark
with the native window controls. The logo was sitting ~2px too low and
~8px too close to the traffic lights.
- Reduce wordmark container top margin from mt-2 (8px) to mt-1.5 (6px)
- Increase Electron header left padding from 82px to 90px for proper
traffic light clearance
- Match the desktop update button margin to stay aligned
Closes#564
Wire up Electron's context-menu event on webContents to surface
dictionary suggestions for misspelled words. Standard edit actions
(Cut, Copy, Paste, Select All) appear in all context menus.
Related to #473
The thread error banner had no way to be dismissed. Users hitting
unrecoverable errors (e.g. missing gh CLI during PR creation) were
stuck with a persistent error banner and no way to clear it.
Add a dismiss (X) button to ThreadErrorBanner using the existing
AlertAction component, wired to clear the thread error via
setThreadError(id, null).
Closes#496
* Add PR template with contribution notice and review checklist
- Add `.github/pull_request_template.md`
- Set expectations that external PRs may not be reviewed or merged
- Require clear change rationale plus UI before/after media when applicable
* Add contribution policy notice and link detailed guidelines
- add CONTRIBUTING.md with clear expectations for external PRs
- update README to direct would-be contributors to CONTRIBUTING.md first
When T3 Code web mode is accessed via HTTPS (e.g. through a reverse proxy
or Tailscale Serve), the WebSocket connection must use wss:// instead of
ws://. Browsers block mixed content — an insecure ws:// connection
initiated from an HTTPS page.
Fix: derive the WebSocket protocol from window.location.protocol.
Co-authored-by: PatrickBauer <[email protected]>
- Drop the redundant static bullet before the working status text in `MessagesTimeline`
- Keep the animated dots indicator as the sole working-state visual cue
* refactor(contracts): export ProviderStartOptions schema
* feat(contracts): add providerOptions to ThreadTurnStartCommand
* feat(web): send codex binary/home path settings to server
* feat(server): thread providerOptions through to session startup
* fix(contracts): define ProviderStartOptions inline to avoid circular dep
The import from provider.ts caused a ReferenceError at runtime because
of module initialization order in the bundled output.
* fix(server): preserve providerOptions across runtime mode changes and session recovery
Runtime mode toggles and server restarts silently dropped the custom
codex binary/home path, falling back to the default binary. Cache
providerOptions per thread in ProviderCommandReactor and persist it in
the session binding's runtimePayload so recovery can restore it.
Closes#486
Add a pre-flight version check that runs `codex --version` and blocks
session startup with a clear upgrade message when the installed CLI is
below v0.37.0. The check runs both synchronously at session start
(codexAppServerManager) and during provider health probes
(ProviderHealth), so users get fast feedback in the UI.
Introduces `codexCliVersion.ts` with semver parsing, comparison, and
formatting helpers shared by both call sites.
* Handle prerelease tags when publishing GitHub releases
- Derive `is_prerelease` and `make_latest` from the version format in preflight
- Mark suffixed versions (for example `1.2.3-alpha.1`) as prereleases
- Keep only plain `X.Y.Z` releases marked as latest
- Document prerelease/latest behavior in `docs/release.md`
* Force desktop auto-updates to stable latest channel
- set Electron updater channel to `latest`
- disable prerelease and downgrade updates regardless of app version
* fix: handle turbo shutdown in dev runner
* refactor: rely on effect child process shutdown
* refactor: inline turbo shutdown timeout
* add back sigint sigterm sighup handling
* refactor: tighten turbo signal forwarding
* refactor: inline dev runner errors
* fix: use detached false instead of manual signal forwarding
Effect defaults to detached: true on non-Windows, putting turbo in a
new process group where terminal signals (Ctrl+C) never reach it.
Setting detached: false keeps turbo in the same group, eliminating
the need for ~130 lines of manual signal forwarding.
* Update scripts/dev-runner.ts
Co-authored-by: Copilot <[email protected]>
---------
Co-authored-by: Copilot <[email protected]>
The app crashed when displaying code blocks with language identifiers
not bundled in Shiki (e.g. "env" from .env file edits). The language
string was cast to SupportedLanguages without validation, causing
resolveLanguage to throw an unhandled error that killed the thread.
Three layers of defense added:
- getHighlighterPromise falls back to "text" when Shiki rejects
- codeToHtml call wrapped in try/catch with "text" fallback
- CodeHighlightErrorBoundary prevents component tree crashes
Closes#266
Co-authored-by: Ahmed R <[email protected]>
* Guard non-git projects and improve send and diff UX
- Skip checkpoint capture/revert and turn diff ingestion for non-git workspaces
- Normalize project workspace roots and return clearer request/error messages
- Show "No Git" state in chat/diff UI and enrich work log with commands/files
- Track send start time so working status shows elapsed duration consistently
* Format active working timer in concise h/m/s units
- add `formatWorkingTimer` for human-friendly durations in ChatView
- show active "Working for" time as `0s`, `1m 5s`, or `2h 3m` instead of ms
* more cleanup
* Fix active work timing and use temp git workspaces in tests
- derive active work start from unsettled turn state instead of always latest turn
- update chat view to use shared deriveActiveWorkStartedAt helper
- make server/ws tests create temporary workspace roots with .git for project creation
- switch quickstart command from `npx t3@alpha` to `npx t3`
- fix wording in desktop app sentence
- replace "Discord link coming soon" with invite link
- add Shift+Tab keyboard handling in composer to switch chat/plan modes
- refactor mode toggle into shared callback used by hotkey and button
- add browser test to verify toggling only works when composer is focused
* marketing site
* redesign 1
* more
* Redesign marketing site: port to Astro, minimal dark homepage
Replace the React/Vite marketing site with a single static Astro page.
Dark theme matching the app aesthetic, featuring the production glossy
T3 icon, app screenshot, and a clean minimal layout.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
* Fix GitHub link to pingdotgg/t3code
Co-Authored-By: Claude Opus 4.6 <[email protected]>
---------
Co-authored-by: Claude Opus 4.6 <[email protected]>
* Stage production icons for desktop builds and publish
- add shared brand asset paths and a Windows .ico asset
- stage Linux/Windows icons in desktop artifact builds
- override and restore publish favicon during server CLI publish
* 'blip'
* Fix PR review issues for publish icon staging
* Refactor brand assets and harden Windows desktop build setup
* Apply remaining server orchestration updates
* Fix production mac icon asset
Co-authored-by: Theo Browne <[email protected]>
---------
Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: Theo Browne <[email protected]>
- Treat pending approvals as a dedicated composer state
- Disable prompt input and hide command menu/image chips while approval is active
- Move approval decision buttons into footer actions and simplify the header panel
- Pass resolved `openInCwd` from ChatView into OpenInPicker
- Fall back to project `cwd` when draft thread has no `worktreePath`
- Add browser test covering Open action for draft-only snapshot
- add `collectActiveTerminalThreadIds` to keep non-deleted server threads plus local draft threads
- use helper in root event router before orphan terminal state removal
- add unit tests for retained and deleted thread behavior
- Wrap test in `it.layer(NodeServices.layer)` for Node service provisioning
- Replace manual temp dir setup/cleanup with scoped `FileSystem.makeTempDirectoryScoped`
- Keep multi-batch flush assertions while simplifying test runtime wiring
- move `AnalyticsServiceLayerLive` from CLI runtime setup into `main` server layer
- persist telemetry `anonymous-id` under configured `stateDir` instead of home directory
- add `FetchHttpClient.layer` to `main.test.ts` test layer wiring
- introduce `AnalyticsService` with buffered PostHog batch flush
- add hashed telemetry identifier from Codex account id or anonymous local id
- record provider session/turn lifecycle events and flush on stop-all
- wire telemetry layer into server runtime and update tests with no-op analytics
- Send `collaborationMode` for both `default` and `plan` interactions
- Add default-mode developer instructions and preserve plan-mode behavior
- Update server/web tests for default collaboration mode and model constant usage
- Keep Claude Code and Cursor in provider list as disabled options
- Remove unused Claude agent SDK dependency from server
- Delete stale plan-mode deep-dive doc
- Replace ad-hoc `effort` handling with provider `modelOptions` across decider/reactor/adapters
- Map Codex `reasoningEffort` and `fastMode` to turn/session params (`effort`, `serviceTier`)
- Persist runtime/interaction/model selections from composer and sync them before sending turns
- Move model normalization/helpers into `@t3tools/shared/model` with updated contracts/tests
- Add `thread.proposed-plan-upserted` orchestration flow from ingestion through decider/projector
- Store proposed plans in a dedicated projection table and include them in snapshot queries
- Update provider runtime/web handling and tests to use proposed plans instead of assistant message wrappers
- Replace provider session-id centric plumbing with thread-id based runtime handling across server orchestration and provider layers
- Update persistence repositories/migrations and contracts for threadless runtime semantics
- Refresh integration/unit tests and web session/store types to match the new runtime model
- add structured lifecycle logs for Codex thread open/resume and provider session restarts
- introduce persistent server file logging layer and tighten WebSocket server startup/finalizer ordering
- preserve env-based boolean overrides in dev runner and stop forcing WS event logging in dev
- enrich provider session listing from persisted bindings and fix Claude rate-limit/task-id event mapping
- update orchestration and dev-runner tests for runtime-mode restart and env-flag behavior
- Add `thread.runtime-mode.set` -> `thread.runtime-mode-set` flow in decider/reactors/projectors
- Persist runtime mode on thread/session projections with new DB migrations
- Update provider and Codex integration tests to verify thread continuity across mode changes
Co-authored-by: codex <[email protected]>
- Define Cursor operating mode as binary `default | plan`
- Document mapping for `cursor/ask_question`, `cursor/create_plan`, and `cursor/update_todos`
- Update capability and fallback guidance based on docs plus probe evidence
- Reframe doc into a provider-agnostic implementation plan for Codex, Claude, and Cursor
- Define canonical mode, plan, and structured user-input models plus capability-driven UI behavior
- Add concrete orchestration, adapter, frontend, and test work items for rollout
- Map runtime session state transitions to orchestration session status
- Persist error reasons from `session.state.changed` error events
- Add coverage for waiting/error/stopped/ready transition handling
- add per-provider custom model settings/options in web settings and chat picker
- preserve Codex request type on `serverRequest/resolved` events
- validate empty Cursor prompts before turn start and keep tool-call item types consistent
- add tests for new adapter and model-settings behavior
- add PR event review checklist document
- map canonical approval request types to `requestKind` across ingestion and web pending approvals
- auto-approve Cursor permission requests when approval policy is `never`
- persist per-thread composer provider selection in draft store and use it in ChatView
- disable Cursor traits picker while model selection is locked
- Add provider capability plumbing for `sessionModelSwitch` and use it in session/turn routing
- Keep Cursor sessions stable when in-session model switching is unsupported
- Ingest canonical runtime events (`content.delta`, `item.*`, `request.*`) with legacy-shape compatibility
- Only include `effort` in start command when a value is selected
- Persist effort selection via composer draft state and hide picker when unavailable
- Add optional `provider` to `ClientThreadTurnStartCommand`
- Simplify thread model fallback selection in `ChatView`
- migrate Claude/Codex/registry adapters to canonical runtime event types and payload shapes
- add Cursor layer adapter plus tests and wire it through server layers
- update provider contracts/runtime schemas and related adapter tests
- Replace global reasoning constants with provider-scoped effort options/defaults
- Update ChatView to use Codex-specific reasoning effort types and default lookup
- Expand model contract tests for provider-specific reasoning effort behavior
- Restructure runtime events around a shared base plus typed payloads
- Add runtime-branded IDs and new event types (plan, item, request, user-input)
- Remove legacy canonical event names from docs and add schema decode/rejection tests
- Add Cursor ACP raw source types to `RuntimeEventRaw.source`
- Define canonical mappings for ACP lifecycle, updates, permissions, and errors
- Expand cross-provider equivalence table to include Cursor ACP and renumber sections
- Switch plan from `agent -p` stream-json to `agent acp` JSON-RPC transport
- Document ACP session, permission, event-mapping, and interrupt/recovery behavior
- Update implementation phases, tests, and delivery checklist for ACP-first design
- add `scripts/cursor-acp-probe.mjs` to run ACP protocol probing scenarios
- update `package.json` scripts for probe execution
- include generated probe summaries/transcripts under `.tmp/acp-probe/`
- Accept `cursor` as a first-class provider in orchestration, persistence, and session directory flows
- Update model/provider inference and normalization to handle Cursor model aliases
- Revamp chat provider/model picker with Cursor-specific trait controls and add coverage in tests
- add per-session `sessionSequence` on provider runtime events and persist activity `sequence`
- migrate `projection_thread_activities` with nullable `sequence` column + index
- sort server/web activity projections by sequence fallback to timestamp/id
- allow provider sessions/turns to start before a real threadId is emitted
- Default Claude sessions to bypass permissions when approval policy is `never`, while preserving explicit `permissionMode`
- Hide/send reasoning effort only for providers that support it in ChatView
- Add coverage for Claude permission-mode derivation and precedence, and update runtime event model docs
- Preserve active turn state when `session.started`/`thread.started` arrive mid-turn
- Emit `message.delta` from assistant text when stream deltas are missing, then complete the message
- Add Claude native SDK NDJSON observability logging and wire its log path in server layers
- Expand ingestion/adapter tests to cover mid-turn lifecycle and delta fallback behavior
- Do not pass `resumeCursor` when restarting a session after changing providers
- Treat synthetic Claude thread IDs (`claude-thread-*`) as unscoped during runtime ingestion
- Add tests covering provider-switch restart behavior and Claude turn lifecycle acceptance
- Stop synthesizing `resume` from generated thread IDs
- Persist resume session ID from query messages when available
- Validate resume/sessionId values as UUIDs before reuse
- Add tests for valid UUID resume passthrough and no synthesized resume
- Replace manual prompt async iterator with `Stream.fromQueue(...).toAsyncIterable`
- Use `Ref` for shared session context in tool approval callbacks
- Simplify timestamp/ID generation and close sessions via queue shutdown
- add `@anthropic-ai/claude-agent-sdk` dependency for `apps/server`
- replace placeholder Claude adapter with live session/query/event handling
- add comprehensive adapter tests for runtime events, approvals, resume, rollback, and model overrides
- introduce `ClaudeCodeAdapter` service and live layer wiring
- map runtime/session/request failures into provider adapter error types
- add coverage for validation, session-not-found mapping, lifecycle forwarding, and event passthrough
- Add per-provider model options, defaults, and slug aliases
- Add provider-aware model normalization/resolution helpers
- Preserve Codex-only constants/functions for backward compatibility
- Extend tests to cover Claude aliases and provider-specific fallback behavior
- Set `target_commitish` from preflight ref when creating GitHub releases
- Track whether package versions changed and expose it via step output
- Run format, lockfile refresh, and bump commit only when changes exist
Move the version bump commit and tag creation out of the preflight job
into a new finalize job that runs only after build, publish, and release
all succeed. This prevents orphaned version commits and tags on main
when downstream jobs fail.
- Preflight: validate version, lint/test only — no commit/tag/push
- Release: softprops/action-gh-release creates tag for workflow_dispatch
- Finalize: bump package.json versions, refresh lockfile, commit to main
Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Replace flat changed-files chips in ChatView with a nested, expandable tree
- Extract diff tree/stat logic into turnDiffTree utilities
- Add unit tests for stat aggregation, nesting, and Windows path normalization
- Move "New thread" action to each project header with hover icon + shortcut tooltip
- Limit thread lists to 6 items by default with per-project Show more/Show less controls
- Remove the global sidebar-level new thread button
- Use the larger of shared stack height and per-toast height to avoid clipping
- Make toast content columns flexible with `min-w-0` and `break-words`
- Keep action buttons from shrinking so long text wraps instead of overflowing
- Add a `Copy Thread ID` item to the thread context menu in the sidebar
- Copy the selected thread ID via Clipboard API
- Show success/error toasts based on copy result
- replace Lexical-node cursor adjacency check with text/cursor helper
- prevent `@query` typing from being treated as mention-pill adjacent
- add regression test for non-pill `@pac` input
- Only intercept left/right arrow keys when cursor is directly next to a mention
- Prevent default arrow behavior only for those mention-boundary moves
- Add `isCollapsedCursorAdjacentToMention` logic with coverage for left/right adjacency cases
- Route `system` messages through assistant height estimation
- Keep user attachment height logic scoped to user messages
- Add regression test for system-message sizing behavior
- Add viewport matrix coverage for long text and attachment row-height parity
- Reuse a mount/measure test harness to validate resize behavior in one session
- Ensure production CSS and viewport sizing are applied before measurements
- recompute timeline width from the root element on ResizeObserver updates
- rerun width effect when message/working state changes
- reduce minimum user chars per line for narrow layouts and add regression test
- Replace manual timeout polling loops with `vi.waitFor` in test helpers
- Improve reliability of locating and measuring virtualized user rows in attachment-height tests
- replace manual `createRoot` mounting with `render`/`unmount` from vitest-browser-react
- add `vitest-browser-react` to web devDependencies and lockfile
- Run ChatView browser tests through the real app router/store stack
- Add MSW worker setup and mocked WS/attachment responses for full-app rendering
- Extract shared `getRouter` setup and add a timeline root data hook for reliable measurement
- Replace mocked router hooks with a memory router + RouterProvider
- Render ChatView through a test route to exercise attachment height layout in realistic routing context
- Replace Playwright e2e timeline-height test setup with Vitest browser config
- Add `ChatView.browser.tsx` parity tests for text wrapping and attachment height estimation
- Add row data attributes in `ChatView` to support in-browser measurement targeting
- add browser E2E tests validating timeline height estimator against rendered DOM
- configure Playwright test runner and scripts in `apps/web`
- run browser tests in CI with Playwright browser caching and install step
The publish_cli job was checking out the default ref instead of the
preflight commit, so it published with the pre-bump version. Add the
correct ref to checkout and a --app-version flag as a safety override.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
- drop `electronmon` from desktop dependencies
- stop killing stale processes by matching electronmon hook paths
- keep cleanup scoped to `--t3code-dev-root` processes only
Use setFeedURL with private: true when a GitHub token is provided so
electron-updater queries the GitHub API instead of the public Atom feed
which rejects Bearer auth headers.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Extract desktop updater state transitions into `updateMachine` reducers with tests
- Extend update IPC/contracts to return `{accepted, completed, state}` for download/install actions
- Add web sidebar update-button logic for retryable download/install errors and clearer tooltips
- Add `updateState` helpers for auto-update eligibility reasons and progress throttling
- Show a user-facing dialog when manual update checks are unavailable
- Ensure manual update checks can open a window when none exist
- Add tests for disable-reason logic and 10% download progress bucketing
- track and clear startup + poll update timers through one cleanup path
- prevent update checks from starting while the app is quitting
- reset startup timer before scheduling to avoid duplicate checks
The guard for status === 'downloaded' logged 'skipping automatic install'
but the function only checks for updates, never installs. The guard was
also redundant since checkForUpdates() already returns early for
'downloaded', 'downloading', and 'available' statuses with correct
log messages.
Co-authored-by: Julius Marminge <[email protected]>
Applied via @cursor push command
- Prevent update install from running when shutdown is already in progress
- Ignore install IPC calls once `isQuitting` is set to avoid duplicate install attempts
- Skip redundant update checks while update is available/downloading/downloaded
- Wait for backend shutdown before `quitAndInstall` and improve updater error/progress handling
- Prevent sidebar update button clicks during download while preserving tooltip interactivity
- Skip desktop auto-update checks while an update is downloading or already downloaded
- Subscribe to update-state events before initial fetch in sidebar to avoid stale state races
- wire `electron-updater` into desktop main/preload IPC and shared contracts
- add sidebar update action for download/install state in Electron UI
- update release workflow/build script to include `latest*.yml` and `*.blockmap` assets
Add tree-kill via taskkill /T /F in processRunner and codexAppServerManager so timeout enforcement and session stop properly terminate the entire process tree instead of just the cmd.exe wrapper. Detect Windows command not found (exit 9009) in normalizeExitError. Pre-validate editor commands with isCommandAvailable in open.ts before spawning. Fix ProviderHealth test import and dev-runner test path assertion for Windows.
Made-with: Cursor
- Run Codex-related child processes with `shell` on Windows for reliable command execution
- Switch provider auth probe to `codex login status` and update health-check expectations
- Use Node PTY on Windows instead of Bun PTY in server runtime setup
- Parse nested/array JSON auth status output from `codex auth status --json`
- Return `unauthenticated` when JSON contains `authenticated: false`
- Return warning when JSON is parseable but lacks an auth marker
- add startup ProviderHealth service/layer to probe Codex install and auth state
- extend server contracts and WS payloads to include provider statuses
- show non-ready provider warnings in ChatView and cover with server/web tests
- add `vitest` to `apps/web` devDependencies and lockfile
- remove unused `envMode` prop from `BranchToolbar` usage and signature
- drop unused composer command input ref in `ChatView`
- Replace string-based env override plumbing with typed config/flag parsing
- Split server/web offset resolution from explicit port/dev-url overrides
- Refactor and expand dev-runner tests around offset/env behavior
- Add `vitest` as a contracts dev dependency for test execution
- Replace `scripts/dev-runner.mjs` with typed `scripts/dev-runner.ts` in a new `@t3tools/scripts` workspace
- Move networking helpers into `@t3tools/shared/Net` and reuse them in server and desktop
- Add shared NetService tests and align workspace deps to `catalog:` versions
- Pass command and args directly to `ChildProcess.make` in the publish CLI
- Remove fragile template-literal invocation to ensure command runs reliably
- Move branch combobox logic into `BranchToolbarBranchSelector` to simplify `BranchToolbar`
- Re-fetch git branches when opening the selector so options are current
- Preserve draft env mode correctly when switching between main and worktree branches
- Default new worktree branch selection to the current checked-out branch when unset
- Extract branch value resolution into shared logic with tests
- Stabilize virtualized branch list scroll/measurement to avoid loading glitches
- add `getSlashModelOptions` to centralize `/model` suggestion filtering
- include custom saved model slugs in slash-command suggestions
- update ChatView to consume shared helper and add focused tests
- Stop showing default-branch confirmation for `commit_push_pr`
- Keep confirmation only for direct `commit_push` actions
- Update logic test to match the new behavior
Deduplicate feature/ prefix logic in resolveAutoFeatureBranchName by
delegating to sanitizeFeatureBranchName. Skip the default-branch
confirmation dialog when there are no uncommitted changes (push-only),
since runFeatureBranchStep requires dirty worktree. Add merge-base
assertions to feature branch tests.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Consolidate the fragile 3-RPC flow (suggestCommitAndBranch → createBranch +
checkout → runStackedAction) into a single server-side operation triggered by
`runStackedAction({ featureBranch: true })`. The server now generates the
branch name via AI, deduplicates it, creates + checks out the branch, then
runs the normal commit/push/PR pipeline atomically.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Clarify that `packages/contracts` is schema-only with no runtime logic
- Add `packages/shared` as the home for shared runtime utilities and subpath exports
Create @t3tools/shared with explicit subpath exports (no barrel) for
shared utility logic. Move sanitizeBranchFragment and
sanitizeFeatureBranchName to @t3tools/shared/git, keeping contracts
focused on schemas.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Move sanitizeBranchFragment and sanitizeFeatureBranchName from three
duplicate definitions (CodexTextGeneration, GitManager, GitActionsControl)
into packages/contracts/src/git.ts. Remove the redundant double-sanitization
of branch names between the TextGeneration and GitManager layers —
CodexTextGeneration now owns sanitization of model output while GitManager
trusts the result and only sanitizes the custom commit message path.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Replace date-based auto feature branch names (feature/stacked-YYYYMMDD)
with semantically meaningful names derived from AI-generated commit
messages. The text generation prompt now returns a branch field alongside
subject and body, and a new suggestCommitAndBranch endpoint exposes this
to the web client for the default-branch checkout flow.
Co-Authored-By: Claude Opus 4.5 <[email protected]>
- Add virtualized rendering and filtered item handling in `BranchToolbar`
- Memoize branch-derived data and sync highlight scrolling for large branch sets
- Convert `ComboboxList` to `forwardRef` to support virtualizer scroll targeting
- tighten win32 command availability checks for PATHEXT and PATH delimiter handling
- add server tests for Windows executable resolution edge cases
- stop branch/create flows after checkout/create failures to avoid stale optimistic UI
- remove OpenInPicker side effect that persisted last editor on render
- Dispatch `thread.meta.update` with the renamed branch after `git.renameBranch`
- Remove pre-rename active-branch status check and related skip path
- Update reactor tests to assert branch metadata moves to generated branch
- Remove git command execution for commit hash retrieval
- Simplify commit hash resolution to use environment variable and embedded hash only
- Clean up unused code in IPC handler registration
- embed `t3codeCommitHash` into staged desktop package metadata during builds
- resolve commit hash from env/package/git and display it as About panel version
- replace React Query mutations with direct git API calls wrapped in `useTransition`
- show toast errors for branch create/checkout failures and keep optimistic branch updates
- disable branch controls during pending actions and refresh branches when opening menu
- add `zed` to shared editor contracts and Open In picker
- add Zed icon and wire launch resolution tests on macOS
- wrap branch optimistic updates in `startTransition` to avoid sync warnings
- Add server-side command detection and return `availableEditors` in server config
- Update Chat header Open In picker to show only installed editors and handle empty state
- Extend server/web tests and contracts for `availableEditors`; remove unused branch-sync logic
- use `useOptimistic` in `BranchToolbar` to update active branch immediately
- keep optimistic branch in sync on success and roll back on mutation errors
- Skip auto-rename when the active worktree branch no longer matches the temp branch
- Update reactor tests to cover branch-switch and first-turn rename behavior
- Show the actual current branch in the toolbar and use a VS Code icon in Open In picker
- add VS Code to editor contracts and picker UI
- use `code --goto` for line/column targets in open resolution
- refine chat scroll intent handling to avoid unwanted stick-to-bottom jumps
- run `gitCheckout` via `Effect.scoped` to satisfy new `Scope` requirement
- update `GitCore.checkoutBranch` service signature to include `Scope.Scope`
- upgrade Effect catalog refs and `@types/node` to latest pinned versions
Adds visual active-item highlighting to the command menu, suppresses
trigger detection when the cursor is adjacent to a mention pill, and
resets transient UI state on thread change.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Treat mention pills as atomic cursor units in Lexical selection math
- Add left/right arrow + selection normalization behavior around mention nodes
- Expand collapsed mention cursor before trigger detection so @path menu closes correctly
- Update mention pill rendering for non-editable, non-selectable chips and theme-aware icons
- Add tests for collapsed-to-expanded cursor mapping and trigger behavior
Introduce ComposerPromptEditor component using Lexical for rich text
editing with @-mention support for files. Includes mention detection
utilities and tests.
Co-Authored-By: Claude Opus 4.5 <[email protected]>
getDestructiveMenuIcon fell back to resolveIconPath("png") on
Windows/Linux which resolved to the T3 Code app icon, not a trash
icon. Restrict the icon to macOS where createFromNamedImage("trash")
provides the correct system icon.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
All exit paths in commitRename now use a thread-guarded finishRename
helper that only clears renamingThreadId when it still matches the
original threadId. Prevents a stale onBlur from cancelling a newly
started rename on a different thread.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Remove the duplicate DesktopContextMenuItem interface and use the
shared ContextMenuItem type from @t3tools/contracts instead.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
After the async dispatch, only clear renamingThreadId if it still
matches the thread being renamed, preventing a second rename's
input from being cleared by the first's completion.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Re-export ContextMenuItem and replace the inlined
{ id: T; label: string; destructive?: boolean } definitions in
wsNativeApi, contextMenuFallback, and the test file.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Only used internally within ipc.ts for DesktopBridge and NativeApi
type signatures, so no need to export it.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Prevents Space from triggering the parent SidebarMenuSubButton's
navigation handler while typing in the inline rename input.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
The inline rename replaces the prompt dialog entirely, so remove the
promptDialog.ts file, IPC channels, bridge methods, and related tests.
Context menu improvements (destructive, position) are kept.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Thread rename now uses an inline input directly in the sidebar row
instead of opening a separate Electron BrowserWindow or browser
window.prompt. Enter commits, Escape cancels, blur saves.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
Revert bare function calls / IIFEs back to useMemo for: modelOptions,
workLogEntries, latestTurnHasToolActivity, pendingApprovals, timelineEntries,
revertTurnCountByUserMessageId, completionSummary, and
completionDividerBeforeEntryId.
Add EMPTY_ACTIVITIES module-level constant so the ?? [] fallback doesn't
create a new array reference every render, which was defeating memoization.
Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Hoist removeOrphanedTerminalStates to a top-level selector in EventRouter
for consistency with other store selectors
- Convert timelineMessages IIFE to useMemo with proper deps
- Suppress no-map-spread in ChatView (spread is conditional, immutability required)
- Suppress exhaustive-deps for autoFocus in TerminalViewport (mount-time only)
Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Add setTerminalFocusRequestId call when terminal opens via toggle so the
terminal panel receives focus automatically
- Call clearTerminalState when deleting threads in the Sidebar and add
removeOrphanedTerminalStates to prune stale entries after read model sync
- Track optimisticUserMessages via ref and revoke their blob URLs in the
unmount cleanup effect to prevent memory leaks
Co-authored-by: Julius Marminge <[email protected]>
- Deep clone DEFAULT_THREAD_TERMINAL_STATE in createDefaultThreadTerminalState
- Remove imperative getTerminalState from terminal store; export
selectThreadTerminalState for reactive selectors instead
- Fix Sidebar terminal activity indicator not updating (was using
non-reactive getter)
- Add no-op bailouts to app store transitions (updateThread,
markThreadVisited, markThreadUnread, setError, setThreadBranch,
setProjectExpanded, setRuntimeMode) to prevent unnecessary re-renders
- Use createDefaultThreadTerminalState in clearTerminalState to avoid
storing frozen reference
Co-Authored-By: Claude Opus 4.6 <[email protected]>
- Mount `ChatView` with `key={threadId}` to fully reset UI state on thread switch
- Replace effect-driven local state with direct derived values and cleaner cleanup paths
- Simplify async command/script flows and minor context memo handling in sidebar/ui components
Remove duplicate selector declarations introduced during rebase and restore the streamlined AppStore shape so Zustand selector usage remains consistent.
Restore Sidebar cleanup semantics and pure store test assertions so lint/typecheck stay green after rebasing.
Made-with: Cursor
- Replace `getTerminalState` reads with `selectThreadTerminalState` in ChatView and Sidebar
- Split terminal reducer into pure thread terminal operations used by the Zustand store
- Drop persisted default thread entries and add tests for the new operation helpers
Drop the temporary selector overload from useStore and migrate the remaining selector call sites to the unified { state, dispatch } API so the store surface stays single-path.
Made-with: Cursor
- Main store: replace useReducer with Zustand; pure state transition
functions (syncServerReadModel, markThreadVisited, setError, etc.)
called via store methods. Persist via subscribe.
- Terminal store: single store keyed by threadId; replace
dispatchTerminalAction with direct methods (setTerminalOpen,
setTerminalHeight, splitTerminal, newTerminal, setActiveTerminal,
closeTerminal, setTerminalActivity). Pure reduceThreadTerminalState
used internally.
- Update all consumers to call dispatch.method(...) and terminal
store methods. Fix store tests to use markThreadUnread pure fn.
- Fix Fragment import in store.ts; fix unused get param for lint.
Made-with: Cursor
- Delete draftThreadTerminalState.ts (was only re-exporting shared module)
- Replace draftThreadTerminalState.test.ts with threadTerminalState.test.ts
using createDefaultThreadTerminalState and reduceThreadTerminalState
- Draft threads are first-class: same helpers and types as persisted threads
Made-with: Cursor
- Add shared threadTerminalState.ts: ThreadTerminalState type, default state,
normalize helpers, and single reduceThreadTerminalState() used by both flows
- Refactor store.ts to use shared terminal reducer and helpers; terminal
actions map to reduceThreadTerminalState(threadTerminalSlice(thread), action)
- Make draftThreadTerminalState.ts re-export shared module (same shape/actions)
- Add terminalState to composer draft store: getDraftThreadTerminalState,
setDraftThreadTerminalAction, clearDraftThreadTerminalState; draft thread
shape matches Thread terminal slice
- ChatView: move draft terminal from useState into composer draft store; use
same actions for draft and persisted; hydrate then clear draft terminal
when reconciling server state
Made-with: Cursor
Adds local terminal state management for draft threads before they're
promoted to server threads. Terminal operations (open, split, create,
close, activate, resize) now work on draft threads and hydrate into
the server thread state when the draft is promoted.
Co-Authored-By: Claude Opus 4.5 <[email protected]>
- Remove Action union/reducer dispatch path in `store.ts`
- Extract per-action state transition helpers and apply via `setAppState`
- Update `store.test.ts` to validate behavior through `useStore` actions
- Replace broad `useStore` state reads with targeted selector/action hooks across chat, diff, sidebar, and routing views
- Remove dispatch-style calls in favor of direct store actions to reduce unnecessary rerenders
- Improve chat UI interactions (composer menu navigation, image preview buttons, modal click targets)
- Add local `react-doctor` agent skill docs under `apps/web/.agents/react-doctor`
timelineEntries is derived from workLogEntries; the timelineEntries
effect already runs when work log changes. Dropped duplicate effect
and unused workLogCount variable.
Made-with: Cursor
collectUserMessageBlobPreviewUrls returns a compact array (image+blob only).
Consumer now indexes by image position, not full attachment index, so
blob URLs apply to the correct server attachments when some are skipped.
Made-with: Cursor
- Keep auto-scroll pinned to bottom during thread changes, composer resize, and streaming updates
- Improve virtualized timeline measurement/keying to prevent stale height reuse between threads
- Hand off blob image preview URLs from optimistic to server messages to avoid flicker/revocation races
- Stop `findFirstAvailableOffset` only when a required port exceeds `MAX_PORT`
- Add test covering offsets where only non-required ports are out of range
- Probe localhost ports and increment offsets when base ports are taken
- Resolve server/web offsets by mode while honoring explicit port/dev-url overrides
- Add tests for offset selection and per-mode fallback behavior
- replace `Effect.forkDetach` with `Effect.forkScoped` when refreshing checked-out branch upstream refs
- keep checkout responsive while ensuring the background task stays tied to scope lifecycle
- Track and persist `envMode` in composer draft thread state
- Keep worktree mode for local drafts even when `worktreePath` is null
- Update branch toolbar/chat/sidebar to use effective draft env mode
- Add tests for env mode persistence and undefined option merges
- allow `runProjectScript` for local draft threads when explicitly enabled
- move setup script execution to run after server thread creation
- gate setup script on worktree/base-branch availability and pass resolved worktree cwd
- Keep existing `branch` and `worktreePath` values when `setProjectDraftThreadId` receives `undefined`
- Add a regression test covering the undefined-update case
- Remove stale `draftsByThreadId` entries when project-thread mappings are replaced or cleared
- Preserve drafts when a thread is still mapped to another project
- Parse persisted image `dataUrl` payloads more defensively and use `Object.hasOwn` for draft-thread existence checks
- replace `read*` draft selectors with `getDraftThread`/`getDraftThreadByProjectId`
- centralize persisted localStorage parsing/caching in `composerDraftStore`
- make ChatView fallback read persisted attachments from in-memory store state
- Track draft thread metadata in composer draft store
- Reuse and update local draft threads from Sidebar/ChatView
- Create server thread only when sending first message, with rollback on failure
- Add/expand draft-thread store tests for mapping and context updates
- move project draft thread ID persistence/actions into `composerDraftStore`
- remove legacy `projectDraftThreads` module and update `ChatView`/`Sidebar` callers
- keep image dedupe stable across hydration and avoid revoking blob URLs on composer clear
- add store tests for project-thread mapping and composer clear behavior
- drop deprecated model slug aliases (`gpt-5`, `gpt-5-codex`, `gpt-5-codex-spark`)
- Reuse hidden draft threads while applying requested branch/worktree updates before navigation
- Export composer draft storage key and clone blob preview URLs when re-adding images after retry
- Deduplicate composer images by file signature (within and across calls) and add store tests for URL revoke behavior
- add a zustand-backed composer draft store with localStorage persistence for prompt, cursor, model/effort, and image attachments
- wire ChatView to draft state, restore/clear drafts correctly, and warn when an attachment cannot be persisted
- track per-project draft thread IDs so Sidebar reuses hidden draft threads and excludes empty drafts from thread lists
- Move install, lint, typecheck, and test steps ahead of release commit/tag in `release.yml`
- Add `buildVersion` to staged desktop `package.json` and set it to the app version
- Lowercase sanitized thread segments when creating attachment IDs
- Add coverage for mixed-case thread IDs in attachment store and projection pipeline tests
- Parse thread segments from attachment IDs using a UUID-aware pattern
- Prevent revert/delete cleanup from removing files belonging to similarly prefixed threads
- Add tests for prefix-collision cases in attachment store and projection pipeline
- Sanitize thread-derived attachment ID segments to safe, bounded tokens
- Resolve attachment IDs only when a matching file exists on disk
- Return 404 (not 400) for missing attachment IDs in the attachment route
- Add attachmentStore tests for ID sanitization and extension-based path lookup
- add attachment store helpers for IDs, route paths, and file resolution
- stop projection pipeline from mutating/storing data URLs; keep attachment metadata unchanged
- update Codex send/branch generation flows and tests to resolve images via attachment IDs
- add `ServerConfig.layerTest(cwd, stateDir)` to standardize test wiring
- require `ServerConfig` in `CodexTextGeneration` attachment path resolution
- update orchestration/projection tests and harness to use managed runtimes with explicit config
- accept `data:image/...;...;base64,...` headers while still rejecting invalid formats
- add `imageMime` tests for mime params, non-base64 URLs, and missing mime types
- fork branch-generation prompt effect at call site in `ProviderCommandReactor`
- Replace manual JSON schema constants and parse helpers with `Schema.Struct` definitions
- Generate JSON Schema from Effect Schema and decode output via `Schema.fromJsonString`
- Map `SchemaError` to `TextGenerationError` for invalid Codex responses
- Update `ProviderCommandReactor` test mock typing for `generateBranchName`
- Make branch-name generation return a required string instead of nullable output
- Propagate invalid Codex branch payloads as `TextGenerationError` instead of silently falling back
- Update provider command reactor to catch generation failures, log warnings, and skip rename safely
- add shared attachment path normalization and resolution helpers
- reuse persisted image files for turn start and branch name generation
- cover persisted attachment flow in text generation and reactor tests
- remove `git.renameBranch` from WS/contracts/native API surface and update server/web tests
- use `git branch -m -- ...` in GitCore to safely separate branch rename arguments
- Generate and rename temporary `t3code/*` worktree branches on first user turn in `ProviderCommandReactor`
- Remove websocket/client branch-generation RPCs and related contract/API surface
- Update Codex text-generation prompt to include attachment metadata only when attachments exist, with expanded tests
- Compute ahead count from base branch when upstream is missing
- Skip push/PR actions when no local commits are ahead
- Update server and UI tests for no-upstream push/PR behavior
- Change quick action to `Push` (not `Push & create PR`) when branch has no upstream and is not ahead
- Keep `Create PR` menu item disabled until the branch has commits ahead
- Add/adjust logic tests for both no-ahead and ahead scenarios
- Treat no-upstream branches as publishable: enable Push/Create PR and update quick actions
- Route Create PR menu action through commit+push+PR flow when appropriate
- Simplify Git action dialog to commit-only and add "Commit on new branch" option
- Prompt before commit/push actions on the default branch
- Allow one-click create+checkout of an auto-named feature branch and continue
- Add logic/tests for date-based unique auto feature branch naming
- add GitHub Actions release workflow for v*.*.* tags with preflight checks
- build and publish macOS, Linux, and Windows desktop artifacts in one release
- replace DMG-only script with cross-platform `dist:desktop:artifact` flow
- document release, signing setup, and new desktop dist commands
- fall back to plain checkout (detached HEAD) when `--track` would clash with an existing local branch
- add GitCore coverage for the conflict fallback path
- simplify branch-name derivation in BranchToolbar to consistently strip the first remote segment
- Fall back to empty remote branch and remote name data when git remote queries fail
- Log warnings instead of failing `listBranches`
- Add integration test covering remote lookup failure fallback
- add `remoteName` to git branch contract metadata
- resolve remote refs using full remote names (including slashes)
- avoid fallback to wrong local checkout when remote ref is missing
- update branch toolbar logic/tests to map and dedupe remote branches correctly
- Deduplicate branch list by removing remote refs that match an existing local branch
- Move remote-ref local-name derivation into shared BranchToolbar logic
- Add logic tests for remote-ref parsing and deduplication behavior
- Include remote refs in branch listings, ordered after local branches
- Auto-track remote branches on checkout when no local branch exists
- Update branch picker to label remote branches and store local branch name after checkout
- Add click handling on diff file headers (`data-title`) to open files via native `openInEditor`
- Resolve file paths against active thread/project cwd before launching editor
- Add header hover affordance and tighten diff panel spacing
- Show PR number/title in a tooltip on each thread PR icon
- Open PR links externally from the sidebar and show error toasts on failure
- Improve thread row keyboard handling after switching to a non-button render
Co-authored-by: codex <[email protected]>
- Wrap rendered markdown code blocks with a copy action button
- Show copy/check icons with transient "Copied" state and cleanup
- Style button to appear on hover/focus without shifting code layout
- Reuse in-flight highlight requests and allow later non-streaming renders to cache results
- Stabilize code block highlight state updates to avoid stale or redundant rerenders
- Export and reuse `fnv1a32` from `diffRendering` for shared cache key hashing
- Inject diff palette overrides via `unsafeCSS` in `DiffPanel`
- Add `diff-panel-viewport` background and keep file container border/background styling in `index.css`
- Switch panel root from `bg-card` to `bg-background` for consistent surface tone
- add diff-specific wrapper classes in `DiffPanel` for targeted theming
- override diff renderer color variables to match card/background palette
- soften chat markdown Shiki code-block background for consistency
- Replace `rehype-highlight`/`highlight.js` with `@pierre/diffs` highlighter in `ChatMarkdown`
- Add LRU caching and in-flight dedupe for highlighted code, with streaming-aware behavior
- Extract shared diff theme resolution utility and add unit tests for new LRU cache
- Write projected attachments under the thread directory using `messageSegment-fileName`
- Avoid nested per-message folders while preserving unique, deterministic file paths
- Update projection pipeline tests to match new attachment URLs and on-disk paths
- Make projection attachment writes use last-write-wins per file path
- Always write attachment files so updated message attachments replace stale bytes
- Add regression test covering same message/attachment index update behavior
- Treat `attachments: []` as an explicit update instead of dropping the field
- Add regression test covering attachment clearing for an existing thread message
- Open preview from the full image set instead of a single image
- Add previous/next controls with ArrowLeft/ArrowRight keyboard support
- Keep Escape-to-close behavior and show current image position
- Materialize only valid image data URLs and restrict inferred file extensions to a safe whitelist
- Preserve existing message attachments on upsert unless explicitly replaced or cleared
- Serve static `/` via `index.html` and block traversal attempts in static file requests
- Store message attachments in `projection_thread_messages.attachments_json`
- Materialize base64 image attachments to `stateDir/attachments` during projection
- Serve `/attachments/*` from the server and resolve preview URLs from WebSocket origin
- Add migration and tests for projection materialization and attachment serving
- Read and validate `cwd` from persisted runtime payload when restarting sessions
- Apply persisted `cwd` during stale-session recovery paths, including `sendTurn`
- Add tests to verify resumed sessions preserve the original working directory
- Ignore late write calls after a terminal session has already exited
- Add regression test for trailing writes after exit
- Close terminal drawer session once an exit event is handled
- Update favicon regex parsing to support rel/href in either order
- Add route tests for HTML link tags and object-style metadata with href-first ordering
- move `/api/project-favicon` handling into a dedicated server route with coverage for root and source-linked icons
- wire `wsServer` to use the new route helper
- treat any running session as unsettled in `isLatestTurnSettled` to prevent stale latest-turn banners, with test coverage
- Add `isLatestTurnSettled` to avoid treating an active running turn as complete
- Use the guard in `ChatView` for visited timestamps and completion summary/divider rendering
- Add unit tests covering running, ready, and incomplete-timestamp cases
- add `OrchestrationLatestTurn` schema and store full turn state/timestamps/message linkage
- update server projector/snapshot queries to populate `latestTurn` from session + projection_turns
- migrate web store/components to consume `latestTurn` and adjust related tests
- Use `ProviderTurnId` in `CheckpointReactor` tests instead of `TurnId`
- Guard `event.turnId` access in provider runtime ingestion when the field is absent
- Remove redundant runtime schema aliases for thread and turn IDs
- Use `ProviderThreadId` and `ProviderTurnId` directly across runtime event contracts
- Ignore auxiliary/non-active turn completions for session lifecycle and checkpoints
- Restrict runtime thread/turn IDs to provider IDs in contracts
- Add regression tests and ADR for lifecycle ownership rules
- Pass explicit Pierre light/dark theme into diff render options
- Re-key file diffs on resolved theme so views rerender on theme switch
- Stabilize `useTheme` snapshots to propagate system theme updates reliably
- Reorder restart flow to bind the new provider session before stopping the old one
- Log (and swallow) stop-session failures for superseded sessions
- Add regression test ensuring failed restart does not stop the active session
- Make `approvalPolicy` and `sandboxMode` required in orchestration contracts and turn-start flow
- Add defaults in provider reactors/ingestion to guarantee values are always set
- Store and hydrate both fields in projection persistence, snapshots, and related tests
Use conditional spreading for these properties to handle undefined
values correctly with exactOptionalPropertyTypes.
Co-Authored-By: Claude Opus 4.5 <[email protected]>
- add default `.t3/keybindings.json` for terminal/chat/editor/diff shortcuts
- include initial provider log files and SQLite state artifacts under `apps/server/.t3`
- Persist `approvalPolicy` and `sandboxMode` on orchestration sessions
- Reuse existing sessions when runtime mode is unchanged
- Stop and recreate provider sessions when runtime mode settings change
- Add reactor tests for reuse vs restart behavior
- Add `approvalPolicy` and `sandboxMode` to turn-start command and requested payload contracts
- Pass runtime mode-derived values from `ChatView` when dispatching `thread.turn.start`
- Thread provider options through decider/reactor into session startup, with tests updated
- Fetch orchestration snapshot when bootstrap project/thread IDs are absent
- Resolve project by current workspace and choose latest non-deleted thread
- Continue auto-navigation and expansion using resolved fallback IDs
- Server welcome now includes bootstrap project/thread IDs when cwd project/thread already exist
- Added regression test for reconnecting with persisted bootstrap state
- Root route ignores post-dispose welcome handling and marks thread as handled after navigate
- Track latest `pathname` in a ref for bootstrap event handling
- Prevent effect resubscriptions by removing `pathname` from deps
- Keep auto-navigation gated to root route using current path
- Create or reuse cwd project, create initial thread, and include bootstrap IDs in `server.welcome`
- Update web event routing to expand the project and auto-navigate from `/` to the bootstrapped thread
- Extend WebSocket welcome contract and add server/web tests for bootstrap payload handling
- Guard `onSend` with an in-flight ref to block double submits
- Set send phase before worktree prep and always clear in-flight state in `finally`
- Sync thread branch/worktree path immediately and await setup script execution
- Add `sendInFlightRef` guard in `ChatView` send handler
- Set sending state before async work and always clear it in `finally`
- Wrap early send flow in one `try/finally` to avoid double-submit races
- show an explicit error when New worktree mode has no base branch selected
- sync thread branch/worktree path immediately after creation
- run setup script in the new worktree terminal before continuing
Co-authored-by: codex <[email protected]>
- Drop optional `text` from `ThreadMessageAssistantCompleteCommand`
- Stop passing text on assistant-complete ingestion and decider paths
- Ensure completion events no longer overwrite message content
- Remove spilled-state cache tracking for buffered assistant messages
- Emit any remaining buffered text as a finalize delta on completion
- Keep assistant completion payload text empty in buffered mode
- Change provider runtime ingestion to flush the entire buffered assistant text once it crosses the max size
- Remove partial-retention logic and its keep-chars constant to simplify memory safety behavior
- cap buffered assistant text memory and spill older chunks as delta events
- finalize buffered messages by emitting retained remainder before completion when spilled
- add regression coverage for oversized buffered deltas and tighten type-safe test assertions
- Replace per-thread/turn/message delivery-mode caches with a single `Ref`
- Always complete assistant messages with buffered text from message state
- Remove obsolete delivery-mode cleanup and resolution paths
Use conditional spread for turnId to avoid passing undefined
explicitly when the target type expects an optional property.
Co-Authored-By: Claude Opus 4.5 <[email protected]>
- add `AssistantDeliveryMode` contracts and carry mode through turn-start events
- default assistant responses to buffered mode and preserve buffered text until completion
- support streaming mode end-to-end with ingestion/decider updates and test coverage
- add a Settings toggle to enable assistant streaming in the chat UI
- Append pending user messages to the timeline before server echo arrives
- Reuse message ID/timestamp for optimistic and sent payloads to avoid duplicates
- Remove optimistic entries on sync or send failure
- Replace boolean `isSending` with `sendPhase` state
- Show "Preparing worktree..." status before first-turn dispatch
- Keep composer editable while preventing duplicate sends and restore input on pre-send failures
- subscribe to terminal events in root route and dispatch terminal activity updates
- add reducer support to maintain `runningTerminalIds` per thread/terminal
- add unit tests for terminal event mapping and store activity state transitions
- Use generic type parameter for stream errors instead of unknown
- Type ServerShape errors as ServerLifecycleError instead of unknown
- Add error mapping for autoBootstrapProject and httpServerListen
- Type makeServerProviderLayer with ProviderUnsupportedError
- Use Effect.try with decodeUnknownSync in projector to avoid unknown requirements
- Fix test layer types from any/unknown to never
Co-Authored-By: Claude Opus 4.5 <[email protected]>
- Use domain errors directly in GitManager tests (`GitHubCliError`, `TextGenerationError`)
- Remove fixture-only GH error normalization in test scaffolding
- Introduce shared `PtyAdapterInitializationError` and use it in NodePTY adapter init
- Replace raw `Effect.promise`/generic errors with `Effect.tryPromise` and tagged schema errors
- Improve orchestration harness/test reliability with explicit timeout/runtime error types
- Tighten related tests and error assertions to match typed error flows
- add `gitMutationKeys` and attach mutation keys across git mutation options
- switch GitActionsControl loading state to `useIsMutating` with cwd-scoped keys
- add tests for cwd-scoped mutation keys and mutation option wiring
- Add `mark-unread` option to thread context menu and dispatch reducer action
- Implement `MARK_THREAD_UNREAD` to set `lastVisitedAt` just before latest completion
- Add reducer tests for unread behavior and no-op when no completed turn
- Update fallback context menu styling so only delete uses destructive color
- Bind `mod+d` to `diff.toggle` when terminal is not focused
- Wire ChatView to handle `diff.toggle` and show its shortcut in the diff button tooltip
- Limit sidebar `mod+b` listener to mobile to avoid desktop shortcut conflicts
- Extend web/contracts keybinding tests and command list for `diff.toggle`
- Prefer `T3CODE_STATE_DIR` from env when `--state-dir` is unset or blank
- Throw on invalid `T3CODE_PORT` overrides and always recompute `VITE_WS_URL`
- Add tests for env/state-dir precedence, blank overrides, and invalid ports
- make integration harness dispose path always remove temp root dirs via `Effect.ensuring`
- preserve shutdown failure by surfacing the first teardown error cause
- add integration test that forces `providerService.stopAll` failure and verifies temp dir cleanup
- default root dev commands to `T3CODE_STATE_DIR=~/.t3/dev`
- add `--` flag forwarding in `scripts/dev-runner.mjs` for server env flags
- resolve desktop state dir from `T3CODE_STATE_DIR` with new tests for desktop and dev runner
- pass a cache scope into `getRenderablePatch` and include resolved theme in DiffPanel cache keys
- add a test proving `buildPatchCacheKey` changes when cache scope changes
- detect `:line` and `:line:column` suffixes in open targets
- pass `--goto` when launching Cursor so it jumps to the cursor location
- add tests covering both line-only and line+column targets
- Wrap processDomainEvent in catchCause to prevent the reactor fiber from
terminating on handler errors, matching the pattern used by
ProviderRuntimeIngestion and CheckpointReactor.
- Replace duplicated resolveEffectiveThreadCwd with the shared
resolveThreadWorkspaceCwd from checkpointing/Utils.ts.
- Sync and persist missing default keybindings on server startup without overriding existing command mappings
- Return `keybindingsConfigPath` from `server.getConfig` and add Settings UI action to open `keybindings.json`
- Update server/keybindings tests to cover bootstrapping, conflict handling, and config responses
- Require `threadId` when starting provider sessions and route recovery via persisted bindings
- Persist and propagate provider `resumeCursor`/`providerThreadId` instead of synthesizing values
- Expose full session bindings in `ProviderSessionDirectory` and update tests/integration fixtures
- Rename sqlite state file from `orchestration.sqlite` to `state.sqlite`
- Decode `server.welcome`, terminal, and orchestration push events with Effect schemas
- Drop malformed payloads with warning logs instead of forwarding invalid data
- Add wsNativeApi tests for valid forwarding, caching, and malformed-payload handling
- Restructure Chat, DiffPanel, and Sidebar headers for cleaner Electron drag/no-drag behavior
- Keep turn-strip controls interactive while preserving draggable titlebar regions
- Lower inline diff panel minimum width from 28rem to 26rem for tighter layouts
- map `checkpoint/captured` to `thread.turnDiff.complete` and record turn status/id
- handle `thread.revert` to truncate messages and turn summaries in read model
- migrate event store from `better-sqlite3` to `node:sqlite` and add safe close/idempotent stop tests
Move state management from client to server using an event-sourced architecture:
- Add SQLite-backed event store with append-only event log
- Add orchestration engine with command queue, reducer, and read model
- Add Effect-based PubSub for real-time read model updates to clients
- Define orchestration schemas in contracts (commands, events, read model)
- Simplify client-side store by removing persistence layer
- Remove obsolete client-side persistence tests
Co-Authored-By: Claude Opus 4.5 <[email protected]>
Consolidate the repeated pattern of destructuring and removing diff/diffTurnId/diffFilePath
search params into a single stripDiffSearchParams() function in diffRouteSearch.ts.
Replaces 5 identical destructuring blocks across 3 files with calls to the shared helper.
Applied via @cursor push command
- Extract `DiffWorkerPoolProvider` into its own component and wrap `_chat` outlet with it
- Render/lazy-load `DiffPanel` from `/_chat/$threadId` so diff UI state and close behavior live with thread routing
- Keep responsive sheet vs inline diff presentation with route-level fallback loading UI
- Parse and validate `diff`, `diffTurnId`, and `diffFilePath` from chat route search
- Switch ChatView/DiffPanel diff open/target actions to router navigation instead of store actions
- Remove diff-specific state/actions from the app store and update reducer tests
- Prefer route thread id over stored diff thread when rendering diffs
- When visiting a different thread with diff open, retarget diff state and clear stale turn/file selection
- Add reducer test coverage for open-diff retargeting behavior
- Add left/right controls, edge fades, and wheel-to-horizontal scrolling for turn chips
- Auto-scroll selected turn chip into view and hide the chip strip scrollbar
- Simplify chip metadata to show compact per-turn time
- Add `optimizeDeps.include` entries for `@pierre/diffs` packages in web Vite config
- Improves dev startup/runtime stability for diff rendering modules
Scope invalidation to only the checkpoint diff query for the newly
captured turn instead of invalidating all provider queries. The
checkpoint/captured event carries a turnCount in its payload, so we
use a predicate to match only the query whose toTurnCount equals the
captured turn. This prevents N unnecessary refetches of immutable
diffs for already-completed turns on each new turn completion.
- Load per-turn checkpoint diffs in `ChatView` and show loading/error states in the timeline
- Drive changed-file chips/stats from checkpoint diff results instead of cached turn summary files
- Prevent reducer from rederiving completed turn summaries on late `turn/diff/updated` events; add regression test
- emit `checkpoint/captured` from `ProviderManager` after checkpoint init/capture
- add backend test coverage for the new checkpoint-captured notification flow
- refresh provider queries on `checkpoint/captured` and only re-derive diffs on `turn/completed`
- Remove persisted/stored patch bodies from turn diff summaries and keep metadata-only file stats
- Drop checkpoint diff hydration paths in chat/diff views; rely on selected checkpoint/conversation diffs only
- Sync checkpoint turn counts on session ensure and tune checkpoint diff query retry/backoff for not-ready errors
- Update tests for session logic, persistence, store reducer, and provider query retry behavior
- Dispatch `MARK_THREAD_VISITED` when `activeThreadId` changes in root route
- Add reducer handling to update a thread's `lastVisitedAt`
- Add reducer test coverage for selecting a thread updates visit time
- Add `@tanstack/react-virtual` to web dependencies
- Render chat timeline with virtualized rows for work logs, messages, and working indicator
- Replace end-of-list sentinel approach with scroll-container-based virtualization
- remove `activeThreadId` from web store state and persistence schema
- drive thread-scoped event handling and toast visibility from router params
- simplify chat index/route flow and add explicit `apps/web/vite.config.js`
- Switch web router setup to TanStack file routes and generated `routeTree.gen.ts`
- Move app bootstrap/event wiring into new root route component
- Enable TanStack router Vite plugin and ignore generated route tree in oxlint
- add route-based chat layout with index and `/$threadId` views
- navigate sidebar thread actions through router instead of store-only selection
- extract shared thread creation into `threadFactory` and wire new router deps
- wrap `git worktree remove` errors with command and cwd context
- add server test covering failed worktree removal messaging
- show an error toast and log details when orphaned worktree cleanup fails
- Restore null CWD in sessionOverrides for thread/start and thread/resume
so the Codex app server can distinguish 'no override' from an explicit
path (e.g., to reuse a resumed thread's original CWD).
- Use backreference in diff --git fallback regex to correctly parse paths
containing ' b/' (e.g., binary diffs without +++ b/ lines).
- Add test exercising the git header fallback for binary diffs with ' b/'
in the path.
Applied via @cursor push command
- upgrade `@pierre/diffs` to `^1.1.0-beta.16`
- switch file diff list to `Virtualizer` for smoother large patch rendering
- adjust diff panel container/layout handling and theme typing
- Keep the diff viewer alive when hidden to avoid remount churn
- Share diff worker pool setup via a dedicated provider
- Add `keepMounted` support to `SheetPopup` for sheet-mode persistence
- Wrap `DiffPanel` in `WorkerPoolContextProvider` and add a dedicated diffs worker
- Use content-based patch cache keys to stabilize `parsePatchFiles` caching
- Add tests for cache key stability, whitespace normalization, and content changes
- Include `cacheScope` in checkpoint diff query keys
- Pass turn/conversation-specific scopes from `ChatView` and `DiffPanel`
- Add tests for key separation and API argument forwarding
- update `useDebouncedValue` import to `@tanstack/react-pacer`
- add missing `diffThreadId`, `diffTurnId`, and `diffFilePath` in thread continuity test state
- add shared provider checkpoint diff query options and keys
- refactor `ChatView` and `DiffPanel` to fetch diffs via React Query
- persist selected-turn checkpoint diffs back into thread state for reuse
- Add a confirmation dialog before checkpoint revert
- Warn that newer messages and turn diffs will be discarded
- Cancel revert when the user does not confirm
- add reusable `ui/toggle` and `ui/toggle-group` components built on Base UI
- switch diff view mode controls and chat header diff toggle to use the new toggle primitives
- add server support to diff filesystem checkpoints, including root/HEAD fallbacks and lazy checkpoint initialization
- wire new `providers.getCheckpointDiff` WebSocket route through provider manager and contracts
- update web app to load per-turn diffs from checkpoints and improve diff panel behavior on narrow screens
- Replace placeholder diff sidebar with real turn/file patch rendering
- Link assistant messages to changed-file summaries and open targeted diffs
- Persist diff selection state in the store and cover parsing/reducer behavior with tests
- Lazy-load `DiffPanel` to reduce initial bundle cost
- add `FilesystemCheckpointStore` to capture, restore, and prune per-turn git refs
- wire checkpoint init/capture into `ProviderManager` with per-session locking and error events
- require checkpoint presence before rollback and restore workspace state after revert
- add tests for checkpoint store behavior and provider rollback integration
- add provider/WS contracts and server RPC handlers for listing/reverting checkpoints
- read and rollback Codex thread turns in the app server manager
- add ChatView checkpoint menu + store reducer support to revert local thread state
- expand backend, websocket, store, and contract tests for checkpoint flows
Move the duplicated script normalization logic (dedup-by-id + single
runOnWorktreeCreate enforcement) from apps/web/src/store.ts and
apps/server/src/projectRegistry.ts into packages/contracts/src/project.ts
so both consumers share one canonical implementation.
Applied via @cursor push command
Remove injectEnvIntoShellCommand, shellEscapePosix,
shellEscapeWindowsSetValue, ENV_KEY_PATTERN, and the now-unused
isWindowsPlatform import. These were leftover from an earlier approach
where env vars were injected into the shell command string, replaced
by passing env directly to terminal.open.
Applied via @cursor push command
- Remove autoFocus from the main terminal setup effect dependency array to
prevent full terminal teardown/recreation when switching tabs in split view.
Focus is already handled by a dedicated effect.
- Change threadTerminalRuntimeEnv memo dependency from activeProject to
activeProject?.cwd so unrelated project state changes (e.g. saving scripts)
don't trigger terminal re-initialization.
- Unexport injectEnvIntoShellCommand which is never imported by production
code (env injection is handled server-side), and remove its tests.
Applied via @cursor push command
- make `cols`/`rows` optional in terminal open contracts
- default new/restarted sessions to 120x30 when size hints are missing
- reuse existing terminal dimensions unless a new size is explicitly requested
- only send script terminal size hints when creating a new terminal
- Clear form fields only after the dialog close completes to avoid stale state during transitions
- Keep icon picker closed when the dialog closes
Co-authored-by: codex <[email protected]>
- add optional `env` to terminal open contract and validate env keys/limits
- propagate runtime env from web terminal/script launches to server PTY spawn
- start `zsh` with `-o nopromptsp` to avoid trailing `%` markers and add coverage
- add server `upsertKeybinding` flow to write `~/.t3/keybindings.json` and refresh cached config
- wire project script create/edit to save optional keybindings via the WS API
- improve script action UI with edit controls, icon picker, and preferred-script recall
- add coverage for keybinding upsert behavior in server and websocket tests
- add project-scoped script actions in the chat toolbar, including setup-on-worktree-create
- support dynamic `script.{id}.run` keybindings and command resolution
- persist and sync project scripts across web state, contracts, WebSocket API, and server registry
- add backend and frontend tests for script helpers, persistence, and registry behavior
- Switch composer menu arrow-key navigation to `Command`'s internal highlight handling
- Track highlighted item by id instead of manual index/keyboard state
- Remove custom hover/highlight plumbing and hidden-scroll sync logic
- Introduce a new test file to validate chunking behavior of git check-ignore to prevent oversized input strings.
- Adjust workspaceEntries.ts to implement chunking logic for git check-ignore, improving performance with large ignored path lists.
- Set a maximum byte limit for stdin in git check-ignore to enhance stability and prevent errors during processing.
- Reuse in-flight workspace index builds per cwd and cap `readdir` scan concurrency at 32
- Add server tests for build deduplication and directory read concurrency limits
- Track composer text in a ref so prompt replacements use current text after send/reset
- Replace slash-command menu glyph in ChatView with `BotIcon`
- Map `yml`/`yaml` to base YAML language id to avoid overly specific icons
- Add test coverage for GitHub workflow YAML icon selection
- Extract composer menu into memoized components for cleaner ChatView rendering
- Debounce path trigger queries and keep previous results while fetching
- Precompute searchable model fields to reduce repeated lowercase work
- render theme-aware VS Code icons for path suggestions in chat composer
- exclude `.convex` and gitignored paths more reliably in workspace indexing
- add tests plus a sync script and icon manifest/association data
- Build workspace index from `git ls-files` when in a Git repo, excluding ignored paths
- Skip configured ignored top-level directories during filesystem fallback indexing
- Update chat composer to insert `@path` directly in prompt and remove separate tagged-path chips
- Keep command menu navigation visible by scrolling the active/next item into view
- add `projects.searchEntries` API, contracts, and server-side indexed workspace search
- add composer trigger logic for `@` path suggestions and `/model` command completion
- include tagged paths in sent prompt/user-visible text and cover behavior with server/web tests
- Simplify the promise handling for opening PR links by directly using `void api.shell.openExternal(prUrl).catch(...)`
- Enhance error handling by adding a toast notification for failure cases, improving user feedback on PR link issues
- enforce max 4 terminals per thread in reducer and terminal normalization
- block split/new terminal actions in chat and drawer when limit is reached
- add reducer tests for split/new terminal cap behavior
- add `min-w-0` to ChatView container wrappers to allow proper flex shrinking
- make thread title truncatable with `truncate` and `title` tooltip
- keep action controls fixed-width with `shrink-0` to preserve header layout
- Introduce a new "clean" script to remove node_modules and build artifacts across apps and packages
- Enhances project maintenance by simplifying cleanup process
- Prevent `SET_THREAD_BRANCH` dispatch unless both `activeThreadId` and `syncedBranch` exist
- Avoids updating thread-branch state without an active thread context
- move branch-sync decision into `BranchToolbar.logic.ts`
- avoid auto-sync when env mode is `worktree` or thread has worktree path
- add unit tests for sync and no-sync cases
- Derive `activeSessionId` and `activeThreadId` before approval callbacks
- Avoid stale thread/session captures when submitting approval decisions
- Pass `hasMessages` to `MessagesTimeline` instead of the full thread
- Extract header, error, approvals, and timeline into memoized components
- Memoize `ChatMarkdown`, pickers, and handlers to reduce avoidable re-renders
- Reduce running-time ticker frequency from 250ms to 1000ms
- Replace `chat.newSameGitState` with `chat.newLocal` across contracts, server/web defaults, docs, and tests
- Make `chat.new` preserve branch/worktree state while `chat.newLocal` creates a local thread
- Show terminal close shortcut labels in drawer action tooltips and tab close controls
- Extend keybinding contracts/defaults with `terminal.close` and `chat.newSameGitState`
- Wire web handlers for `mod+w` to close focused terminal and `mod+shift+n` to open a thread preserving branch/worktree
- Update docs and keybinding tests across server, web, and contracts
- Replace `openPr`/`mergedPr` with `pr` in server and contracts
- Add PR `state` (`open`/`closed`/`merged`) to git status schema
- Resolve latest branch PR via `gh pr list --state all` sorted by `updatedAt`
- Add `dismissAfterVisibleMs` support to thread toasts
- Pause/resume countdown based on tab visibility and window focus
- Set Git action result toasts to dismiss after 10s when visible
- Show warning toast when attempting to delete a non-empty project
- Simplify confirmation copy to emphasize irreversible deletion
- Remove thread/worktree/session cleanup from project delete flow
- Prompt before deleting a project with thread and linked worktree counts
- Best-effort remove orphaned worktrees when project threads are deleted
- Show toast with error details if project deletion fails
- Add project right-click Delete action in `Sidebar` and clean up sessions/terminals before removal
- Add `DELETE_PROJECT` reducer action to remove the project, its threads, and reset active thread
- Add reducer test coverage for project deletion behavior
- Add a shared composer-focus scheduler in `ChatView`
- Refocus composer after runtime mode, model, effort, and env mode selections
- Let `BranchToolbar` request composer focus after branch/worktree actions
- set server config query `staleTime` to `Infinity` to avoid unnecessary refetches
- narrow `isWindowsPlatform` matching to Windows-prefixed identifiers
- add unit tests for Windows and non-Windows platform cases
- make resolved keybinding/shortcut schemas strict to reject unknown fields
- export server `DEFAULT_KEYBINDINGS` as source of truth and reuse it in ws tests
- simplify keybinding test fixtures and update docs to reference server defaults
- Move default keybindings, config parsing, validation, and merge logic out of `wsServer`
- Add `loadResolvedKeybindingsConfig(logger)` in `apps/server/src/keybindings.ts`
- Update server wiring docs to point to `server.getConfig` integration
- drop `key` and `when` from resolved keybinding rule schema/payload
- update server/web/contracts tests and keybindings docs for `whenAst`-only resolution
- delete unused web `LruCache` implementation and tests
- add server keybinding compiler for shortcuts and `when` AST parsing
- switch websocket/server config payload to resolved keybinding rules
- update web keybinding logic/types to consume resolved payload directly
- add/adjust contract, server, and web tests (including plus-key parsing) and docs
- Evaluate shortcut matches by resolving the last matching key+when rule, regardless of command
- Add cross-command precedence tests and switch assertions to `vitest` `assert`
- Clarify precedence behavior in `KEYBINDINGS.md`
- add `chat.new` and `editor.openFavorite` to keybinding contracts and server defaults
- use shared keybinding matching in sidebar/chat view instead of hardcoded Cmd/Ctrl combos
- document new commands/defaults and extend server/web keybinding tests
- add `serverConfigQueryOptions` in new `serverReactQuery` utility
- switch `ChatView` from manual `getConfig` effect/state to `useQuery`
- default to empty keybindings while config is unavailable
- Move default keybinding resolution/override merging into `server.getConfig`
- Return server-resolved keybindings to the web client instead of resolving in UI
- Update docs and tests to reflect server-side defaults, overrides, and truncation behavior
- Reuse `KeybindingRule` and `KeybindingsConfig` directly for resolved keybinding types
- Update normalization helper to accept `KeybindingRule` for consistent typing
- extend `server.getConfig` to return sanitized keybinding rules from `~/.t3/keybindings.json`
- apply resolved bindings in the web app for toggle/split/new terminal shortcuts and labels
- add contracts/docs and tests for config parsing, validation, and shortcut behavior
- server: only query open PRs when the current branch has an upstream; still fall back to merged PR lookup
- tests: cover status behavior for branches without upstream tracking
- web: fetch git status once per cwd, validate query data with schema parsing, and map merged PR badges by thread branch match
- extend `GitStatusResult` with nullable `mergedPr` metadata
- in server git status, query merged PR only when no open PR is found
- in sidebar, display a `Merged` status pill for threads on branches with merged PRs
- update server/web/contracts tests for the new status shape
- only auto-scroll when the user is already near the bottom
- centralize near-bottom detection in `chat-scroll.ts` with a 64px threshold
- add unit tests covering threshold and edge-case behavior
Co-authored-by: codex <[email protected]>
- Disable the quick sync action when local and upstream branches have diverged
- Treat mismatched branch/status data as out-of-sync and refresh before enabling actions
- Update GitActionsControl logic tests for diverged branch behavior
Co-authored-by: codex <[email protected]>
- derive upstream branch from `branch@{upstream}` and guard empty values
- fetch only `+refs/heads/<branch>:refs/remotes/<remote>/<branch>` instead of all remote refs
- add integration test asserting scoped fetch args during `checkoutBranch`
- treat post-checkout upstream fetch as best effort so checkout still succeeds
- route refresh fetch through `this.git(...)` for consistent behavior
- add regression test for fetch-timeout during branch checkout
- fetch tracked remote after checkout to update ahead/behind counts
- add integration test for behind count when remote branch advances
- invalidate git React Query data on `turn/completed` events in the web app
- Route worktree create/remove calls through shared git mutation options
- Invalidate git queries on mutation settle to keep branch/worktree data fresh
- Update chat and sidebar flows to use `mutateAsync` for worktree actions
- Add optional `onConfirmed` callback to `runGitActionWithToast`
- Use it from the Push CTA so the existing toast is closed only after user confirms push
- Move `buildGitActionProgressStages` into shared logic for reuse and tests
- Add `forcePushOnly` path so push actions show only `Pushing...`
- Cover push-only and commit+push stage behavior with new logic tests
- Only show open/create PR actions after push on non-default branches
- Fire git query invalidation without awaiting mutation success handlers
- Tweak disabled button classes to keep split-button borders/radii aligned
- Style disabled quick-action trigger with `aria-disabled` so hover tooltip still works
- Make git action menu popup/items use full-width layout for cleaner alignment
- let users create a new local branch directly from the branch combobox search
- remove separate "New branch" form/button flow in `BranchToolbar`
- add `inputClassName` support to `ComboboxInput` for native input styling control
- Dismiss the success toast before handling Push/Open PR/Create PR CTA clicks
- Prevent stale result toasts from lingering while starting the next git action
- Only include commit-related progress steps for stacked actions when there are working tree changes
- Prevents showing "Generating commit message"/"Committing" during pure push or PR flows
- Trigger `commit_push` directly from primary Push actions
- Simplify push confirmation copy and dialog descriptions
- Replace 6-file cap with a scrollable full changed-files list plus totals
- replace generic success text with action-specific toast titles/descriptions
- include short SHA/branch details for push and commit outcomes
- add tests for PR/commit/push summaries and description truncation
- Use the quick action button itself as the popover trigger
- Keep hover tooltips working on disabled controls via pointer-events override
- Remove focus/blur tab-stop handlers from disabled tooltip wrappers
- add working-tree file/line stats to git status contracts, server responses, and tests
- refactor web git queries/mutations into shared React Query helpers
- update git quick-action logic/UI to prefer commit/push/PR flows and clearer disabled states
- hide branch toolbar for non-repos and tighten related chat/toolbar behavior
- migrate web UI to shared Base UI primitives (alerts, buttons, combobox, toast, etc.)
- refactor chat and branch toolbars to use new components and cleaner interactions
- add cross-platform file-manager fallback in `openInEditor` server handling
- update model contracts/tests and web dependencies to support new UI flow
- build terminal spawn env from a filtered copy of process env
- exclude `PORT`, `T3CODE_*`, `VITE_*`, and Electron runtime vars
- add test coverage to verify filtered and preserved env keys
- Remove `ELECTRON_RUN_AS_NODE` before spawning `electronmon` in desktop dev script
- Replace detailed multi-step Git progress toast with a compact status message + optional Open PR action
- Keep the git action modal in selection mode while actions run in a dismissible progress toast
- Remove automatic `gh pr view --web` calls; only return PR metadata and open links on explicit user action
- Update server/web tests to assert no implicit PR browser open behavior
- move branch recency parsing into `readBranchRecency`
- fall back to an empty recency map if lookup fails
- add test to ensure branches still list when recency read times out
Co-authored-by: codex <[email protected]>
- Keep the current branch first
- Place the default branch second
- Sort remaining branches by most recent commit and update tests for this behavior
Co-authored-by: codex <[email protected]>
- Order `listGitBranches` by each branch's most recent commit date
- Keep current/default/name tiebreakers for stable ordering
- Add integration test coverage with dated commits to verify recency sort
- Format orphaned worktree paths to display only the final segment
- Apply formatting in Sidebar delete prompt for cleaner UX
- Add tests for Unix, Windows, trailing slash, and fallback cases
- add `dialogs.confirm` to native IPC/contracts and desktop preload/main bridge
- switch sidebar worktree deletion prompt from `window.confirm` to native API
- add `showDesktopConfirmDialog` helper with unit tests for dialog behavior
- Prompt to remove the worktree when a deleted thread is its only reference
- Best-effort cleanup via `api.git.removeWorktree` after thread deletion
- Add `getOrphanedWorktreePathForThread` helper with unit tests
- Replace terminal text badge with a right-aligned `TerminalIcon`
- Add accessible label/title: "Terminal process running"
- Keep pulse animation and terminal-active color styling
- Pass subprocess test options only when defined in `terminalManager` tests
- Narrow web store terminal event fixtures to `started`/`activity` event shapes
- Add cross-platform subprocess polling in `TerminalManager` and emit `activity` events when child-process state changes
- Update web store to derive `runningTerminalIds` from `activity.hasRunningSubprocess` instead of start/restart events
- Extend terminal contracts and tests to include the new `activity` event type
Co-authored-by: codex <[email protected]>
- Attempt `api.terminal.close` when toggling an open terminal off
- Fall back to sending `exit` if close is unavailable or fails
- Include `api` in callback dependencies to keep behavior current
- On open, read legacy transcript files and write them to the new terminal-scoped history path
- Remove legacy files after migration and warn if cleanup fails
- Update tests to assert migration, content preservation, and legacy file removal
- add `terminalRunning` to thread state and hydration defaults
- apply terminal events in reducer to sync running/open state (close drawer on exit)
- wire drawer running-state callbacks and show a Terminal status pill in sidebar
- extend store and persistence tests for terminal running/exited behavior
- Route `dev*` scripts through `scripts/dev-runner.mjs` to compute shared server/web port offsets
- Support `T3CODE_DEV_INSTANCE` (hashed or numeric) and explicit `T3CODE_PORT_OFFSET`
- Document multi-instance usage and allow server `VITE_DEV_SERVER_URL` override
- Pass `deleteHistory: true` when closing a terminal
- Fallback path now clears terminal before sending `exit`
- Use `gitCwd` as terminal cwd when available
- Call `api.terminal.close` when available when closing a terminal tab
- Fall back to writing `exit\n` to preserve compatibility with older/uninitialized terminals
- Replace `terminalLayout`/`splitTerminalIds` with `terminalGroups` and `activeTerminalGroupId`
- Update terminal drawer UI to render grouped splits with a terminal sidebar
- Bump persisted web state to v7 with legacy v6 migration coverage in tests
- Add terminal close controls in tab and split terminal views
- Send `exit` before closing and update active terminal/focus in chat state
- Add reducer support and tests for closing tabs, split fallback, and final-terminal drawer hide
- Support multiple terminal IDs per thread across contracts, server manager, and WS handling
- Persist terminal history per terminal ID and allow closing all terminals for a thread
- Update web thread state and terminal drawer to create, split, and switch active terminals
- Expand tests for multi-terminal behavior and terminal ID propagation
- Constrain pending approval cards to a centered max-width section with updated padding
- Improve light/dark theme contrast for approval detail text and action buttons
- Keep existing approval actions and behavior unchanged while updating visual hierarchy
- Moved pending-approval extraction to `session-logic` and reused it in `Sidebar` status rendering
- Added `lastVisitedAt` threading persistence through schema, types, hydrate/serialize paths, and tests
- Updated sidebar thread pills for completed/approval states and pulsing working status
- Marked active thread visits and completion visibility timestamps on selection and `turn/completed`
- Co-authored-by: codex <[email protected]>
2026-02-12 18:37:41 -08:00
6102 changed files with 1509980 additions and 16371 deletions
description:btca is a cli for getting information from other git repositories by querying them with natural language. Spawns an external subagent to explore external codebases (i.e. a github repo) and answer questions about them. Great when integrating complex libraries, frameworks, or tools.
---
btca is a cli for asking questions about various folders, primarily git repositories. It's built to give you the exact information you need without bloating your context window. btca uses agents under the hood to answer your question, so prompt it the way you would prompt a tool similar to yourself.
For example, assuming you have a resource named `codex`, you can ask questions like:
```bash
btca ask -r codex -q "What is the return format for Codex App Server responses? Are there any edge cases worth knowing?"
```
Your prompt may include specific names for resources to use, if they do then you should try those first. If you need to check available resources, you can use the `btca resources` command.
New resources can be created if the ones you need do not yet exist.
Review changed TypeScript and directly affected call sites for the conventions below. Apply them when a pull request creates, moves, refactors, or consumes an Effect service. Do not demand unrelated repository-wide cleanup. Treat these instructions as authoritative when older code differs.
## Imports and module namespaces
- Import Effect library modules from their subpaths as namespaces, for example `import * as Effect from "effect/Effect"` and `import * as Layer from "effect/Layer"`. Flag consolidated named imports from `"effect"` in touched Effect service code.
- At a service boundary, import the local service module as a namespace and use its public module shape: `WorkspacePaths.WorkspacePaths`, `WorkspacePaths.make`, and `WorkspacePaths.layer`. Flag aliases such as `import { layer as workspacePathsLayer }` that erase the module namespace.
- Namespace imports are not a blanket rule. Keep named imports for whole packages such as `@t3tools/contracts`, and for modules used only for a pure helper, error, schema, config value, or standalone type. Do not request `import type * as Contracts`.
- A package subpath that is itself a service module may use a namespace import when callers access its service/tag, `make`, or `layer` members.
- When a barrel exposes an entire service module, prefer `export * as TokenStore from "./tokenStore.ts"` so consumers can use `TokenStore.TokenStore` and `TokenStore.layer`. Do not individually rename `make` and `layer` exports to simulate a namespace.
## Service definition
- Use the canonical single-file order: imports, error/schema declarations, the `Context.Service` tag with its inline interface, `make`, then `layer`.
- Keep a service's schemas/errors, `Context.Service` tag, construction, and layer in one canonical module when they form one implementation.
- Define the service interface inline in the `Context.Service` declaration. Do not retain a standalone `FooShape` or `FooServiceShape` interface/type.
- Refer to the inferred service interface as `Foo["Service"]`, including in mechanically updated orchestration, MCP, tests, and integration harnesses.
- Export a real `make` when the module owns construction. Do not create `make = Effect.succeed(...)` solely to force `Layer.effect`.
- Export the canonical layer as `export const layer = Layer...`. `Layer.effect` is not required: use `Layer.succeed`, `Layer.scoped`, or another appropriate constructor when that matches the implementation.
- In a concrete implementation module already named for the implementation, use plain `make` and `layer` (for example `BunPtyAdapter.ts` and `NodePtyAdapter.ts`).
- Keep implementation-specific names when an abstract port module contains one of several possible implementations, for example `makeCloudflaredRelayClient` and `layerCloudflared` in `RelayClient.ts`.
-`infra/relay/src/db.ts` is an intentional exception: an inline `Layer.succeed(RelayDb, db)` is acceptable without generic `make`/`layer` exports.
## Errors and predicates
- Define service failures with `Schema.TaggedErrorClass` and structured attributes. Derive `message` from those attributes rather than storing an unstructured message as the only data.
-`Schema.Defect()` is not a substitute for modeling a generic error: its tag, fields, or both must identify the failure structurally, and its `message` must not merely stringify an opaque cause. A semantically precise error tag may preserve a real `cause` without inventing a redundant singleton field when no additional variable context exists; still retain any real path, resource, request, or entity context available at the wrapping site.
- Capture stable, serializable domain context such as the operation or stage, resource/path or entity identifier, and normalized category/status. Map failures where that context is known instead of wrapping an entire multi-step pipeline in one generic error. Do not add a `detail` field that merely copies `cause.message` and then use it to construct the wrapper message.
- Keep direct error attributes and log annotations safe and bounded. Do not copy raw wire payloads, command arguments or output, signed URLs, credentials, query strings, fragments, selectors, or arbitrary defect text into `detail`, `reason`, `message`, or a parallel log payload. Preserve the exact underlying value only as `cause`; expose normalized categories plus lengths/counts and safe URL protocol/hostname diagnostics where useful. Logging a sanitized error must not reintroduce a removed legacy `detail` or serialized `cause` field beside it.
- When translating or wrapping a real failure, preserve the immediate underlying error itself as `cause` alongside the structural fields so the complete error chain and stack remain available. If every construction wraps a failure, `cause` should be required; make it optional only when the same error can legitimately originate without an underlying failure.
- At a translation boundary, pass through an already structured domain error when it is part of the declared target error channel. Wrap only unknown or genuinely lower-level failures. A static factory or mapper may perform this classification when it is reused and keeps the policy next to the target error type.
- Derive the wrapper's `message` exclusively from its stable structural attributes, never from `cause`, `cause.message`, or a stringified defect. Do not replace the immediate error with only `error.cause`, erase a structured upstream error into a string, or manufacture an `Error` merely to populate `cause`. Pure validation/domain errors created without an underlying failure do not need a cause.
- Do not encode the same distinction twice with both a specific error tag and a single-value `operation`, `reason`, `kind`, or `phase` literal. Choose one coherent model: use distinct error classes and omit the redundant discriminator when callers or messages treat the failures as genuinely different, or use one service-level error with a multi-value operation discriminator and a generic message derived from that operation when the failures share the same semantics.
- Treat an error message exposed through an HTTP/RPC response, persisted state, UI, or another caller-visible boundary as behavior. Preserve those messages during a structural refactor. Existing distinct caller-visible messages are evidence that the failures should normally remain distinct error tags without redundant singleton discriminators, rather than being collapsed into a generic operation error.
- Split semantically distinct failures into separate error classes when a `reason`, `kind`, `phase`, or similar discriminator is used to choose the user-facing message or drive caller control flow. A discriminator used only for internal diagnostics may remain a field.
- Use `Schema.Union` of error classes when a shared schema, predicate, or helper type is useful.
- Export direct schema predicates such as `export const isFoo = Schema.is(Foo)`. Flag a private `Schema.is` constant wrapped by a redundant function with the same signature.
- Do not introduce a large `switch` or lookup table in an error's `message` getter to model failures that deserve separate error classes.
- Catch statically known tagged failures with `Effect.catchTags({ ... })`, including when handling only one tag. Do not use `catchIf` with a schema predicate merely to recover one or more known `_tag` variants, and do not use `catchTag`. `Effect.catch` is appropriate when the entire error channel is intentionally handled; `catchIf` remains appropriate for genuinely structural predicates such as inspecting an underlying platform error code.
- Do not add a helper whose only behavior is `(...args) => new SomeError({ ...args })`, including curried aliases used once with `mapError`. Construct the error at the failure boundary so its attributes and cause remain visible. Keep a mapper only when it performs real normalization, passes through existing domain errors, or adds reusable context/control flow.
- When a reusable error-to-error translation clearly belongs to the target error type, prefer a descriptive static factory on that error class over a detached production-side switch. Do not force a static method for one-off inline mappings.
## File layout and migrations
- When combining `domain/Services/Foo.ts` and `domain/Layers/Foo.ts`, hoist the result to `domain/Foo.ts`.
- Delete the old service/layer files. Do not leave compatibility re-export shims. Mechanically update every consumer, including orchestration, MCP, tests, and integration harnesses, to the canonical path.
- Do not flag genuinely separate implementation/adapter modules merely because they remain in an implementation-oriented directory.
- Avoid substantive orchestration or MCP redesign in service-cleanup PRs. Mechanical import, layer, and `Service["Service"]` updates are expected when required to remove obsolete paths or shapes.
## Change discipline
- Preserve useful comments, invariants, and specification documentation while moving code.
- Do not add large tests solely to prove a mechanical refactor. Update existing tests and imports as needed.
- If backend behavior changes, require focused tests. Use test implementations/layers for external services only; do not mock out core business logic.
- Do not require `Layer.effect`, universal namespace imports, generic `make`/`layer` names for abstract-port implementations, separate error classes for diagnostic-only fields, or new tests for import-only changes.
## Reporting
Report only concrete violations introduced or retained in the pull request's changed scope. Prefer precise inline comments on the smallest relevant line range and state the expected fix. A clear convention violation may fail the check. Do not fail for optional style preferences or unrelated legacy code.
This check defaults to failure. When there are no findings, stop immediately and make the entire final response exactly `All clear` on one line. Do not add a title, explanation, punctuation, Markdown, JSON, or trailing analysis, and do not continue reasoning after deciding the review is clean.
This is the working checklist for remediation execution.
Status values:
-`TODO`: Not started
-`IN_PROGRESS`: Currently being worked
-`BLOCKED`: Waiting on decision/dependency
-`DONE`: Implemented and verified
-`CLOSED_INVALID`: Stale/invalid review finding
Counts: active `51` (`valid=33`, `partially-valid=18`), closed-invalid `6`
## Active Checklist
### Phase 1
- [x]`C002` A dispatch error in `processEvent` will terminate the `Effect.forever` loop, permanently halting event ingestion. Consider adding error recovery (e.g., `Effect.catchAll` with logging) around `processEvent` so failures don't kill the fiber.
- Audit note: Ingestion worker loop can terminate on unhandled processEvent failure.
- [x]`C003` Consider attaching a no-op error listener before `socket.write` (e.g., `socket.on('error', () => {})`) to prevent an unhandled `EPIPE`/`ECONNRESET` from crashing the process if the client disconnects mid-handshake.
- Status: `DONE`
- Verdict: `valid`
- Severity: `High`
- Area: `WebSocket robustness`
- File: `apps/server/src/wsServer.ts:75`
- Threads: PRRT_kwDORLtfbc5v-cf4
- Audit note: Upgrade reject writes then destroys socket without defensive error listener.
- [x]`C012` Forked revert dispatch risks read model inconsistency
- Audit note: SessionId-only routing can misassociate events under races/rebinds.
- [x]`C020` On `message.completed`, the message ID is added to the set and `thread.message.assistant.complete` is dispatched. On `turn.completed`, the same set is iterated and `thread.message.assistant.complete` is dispatched again for each ID—including already-completed ones. Consider removing message IDs from the set after dispatching on `message.completed`, or filtering out already-completed IDs before the `turn.completed` loop.
- [x]`C026` Consider adding `.catch(() => {})` after `Effect.runPromise(handleMessage(ws, raw))` to prevent unhandled rejections from crashing the server if `encodeResponse` or setup logic fails.
- Status: `DONE`
- Verdict: `valid`
- Severity: `Medium`
- Area: `WebSocket robustness`
- File: `apps/server/src/wsServer.ts:545`
- Threads: PRRT_kwDORLtfbc5wj4cE
- Audit note: runPromise result still not caught; rejection can surface unhandled.
- [x]`C027` WS message handler can cause unhandled promise rejection
- Audit note: Errors are swallowed to empty diff with warning; not fully silent but still lossy.
- [x]`C045``truncateDetail` slices to `limit - 1` then appends `"..."` (3 chars), producing strings of length `limit + 2`. Consider slicing to `limit - 3` instead. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Audit note: truncateDetail still overshoots limit.
- [x]`C046``latestMessageIdByTurnKey` is written to but never read, and `clearAssistantMessageIdsForTurn` doesn't clear its entries—only `clearTurnStateForSession` does. Consider removing this map entirely if unused, or clearing it alongside `turnMessageIdsByTurnKey` in `clearAssistantMessageIdsForTurn`. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Audit note: latestMessageIdByTurnKey still unused/unpruned in per-turn clear path.
- [x]`C053` Consider using `socket.end(response)` instead of `socket.write(response)` + `socket.destroy()` to ensure the HTTP error response is fully flushed before closing the connection.
- Status: `DONE`
- Verdict: `valid`
- Severity: `Low`
- Area: `WebSocket robustness`
- File: `apps/server/src/wsServer.ts:83`
- Threads: PRRT_kwDORLtfbc5v-WPD
- Audit note: Still uses write+destroy rather than end() for rejection response.
- [ ]`C054` When array chunks contain a multi-byte UTF-8 character split across boundaries, decoding each chunk separately produces replacement characters. Consider using `Buffer.concat()` on all chunks before calling `.toString("utf8")`. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- [x]`C059` Suggestion: don’t spread `params` into `body`; it can override `_tag` and mishandle non-object values. Keep `_tag` separate and nest `params` under a single key (e.g., `data`), or validate `params` is a plain object.
- Status: `DONE`
- Verdict: `partially-valid`
- Severity: `Low`
- Area: `WebSocket robustness`
- File: `apps/web/src/wsTransport.ts:59`
- Threads: PRRT_kwDORLtfbc5whtrN
- Audit note: Transport \_tag override risk exists but current callsites are constrained.
### Phase 2
- [x]`C001` Non-atomic event appending can corrupt state on retry. If an error occurs mid-loop (lines 96-102) after some events are persisted but before the receipt is written, the command appears to fail. A retry generates new UUIDs via `crypto.randomUUID()` in the decider, appending duplicate events. Consider wrapping the loop in a transaction or using deterministic event IDs derived from `commandId`. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Audit note: Append/project/receipt are non-atomic; retry can duplicate events.
- [x]`C013` If `projectionPipeline.projectEvent` fails after `eventStore.append` succeeds, the event is persisted but `readModel` isn't updated, causing desync. Consider updating the in-memory `readModel` immediately after append (before the external projection), so local state stays consistent regardless of downstream failures.
- Audit note: Persisted event can outpace in-memory projection on mid-flight failure.
- [x]`C015` The gap-filling fallback logic can retain messages from turns that are about to be deleted, causing foreign key violations. Consider removing the fallback logic entirely, or filtering `fallbackUserMessages` and `fallbackAssistantMessages` to only include messages whose `turnId` is in `retainedTurnIds`. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Audit note: Message fallback retention issue is real, but prior FK-violation claim is overstated.
- [x]`C016` The in-memory `pendingTurnStartByThreadId` map isn't restored during bootstrap. If the service restarts after processing `thread.turn-start-requested` but before `thread.session-set`, the `userMessageId` and `startedAt` will be lost since bootstrap resumes _after_ the committed sequence. Consider persisting this pending state or processing these two events atomically. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Audit note: Edge schema strategy is in place across contracts/consumers (trim/normalize via schemas and decode at boundaries); CheckpointStore remains an internal repository boundary.
- [x]`C017``REQUIRED_SNAPSHOT_PROJECTORS` includes `pending-approvals` and `thread-turns`, but `getSnapshot` doesn't query their data. If these projectors lag behind, the returned `snapshotSequence` will be lower than what the included data actually reflects, causing clients to replay already-applied events. Consider filtering `REQUIRED_SNAPSHOT_PROJECTORS` to only include projectors whose data is actually fetched in the snapshot. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Audit note: handledTurnStartKeys still grows without pruning.
### Phase 5
- [ ]`C009` Git's braced rename syntax (e.g., `src/{old => new}/file.ts`) isn't handled correctly. The current slice after `=>` produces invalid paths like `new}/file.ts`. Consider expanding the braces to construct the full destination path. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Audit note: Braced rename parsing still breaks paths like src/{old => new}/file.ts.
- [ ]`C010``loadCustomKeybindingsConfig` fails when the config file doesn't exist, which is expected for new users. Consider catching `ENOENT` and returning an empty array instead. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Status: `TODO`
- Verdict: `valid`
- Severity: `Medium`
- Area: `Edge-case parsing/platform behavior`
- File: `apps/server/src/keybindings.ts:418`
- Threads: PRRT_kwDORLtfbc5wxvIJ
- Audit note: ENOENT for missing keybindings config still not handled as empty/default.
- [ ]`C022` Fish shell outputs `$PATH` as space-separated, not colon-separated. Consider checking if the shell is fish and using `string join : $PATH` instead, or validating the result contains colons before assigning.
- Status: `TODO`
- Verdict: `valid`
- Severity: `Medium`
- Area: `Edge-case parsing/platform behavior`
- File: `apps/server/src/os-jank.ts:10`
- Threads: PRRT_kwDORLtfbc5wkRZM
- Audit note: fish PATH formatting risk still exists in os-jank path recovery.
- [ ]`C023` Using `-il` flags causes the shell to source profile scripts that may print banners or other text, polluting the captured `PATH`. Consider using `-lc` (login only, non-interactive) to reduce unwanted output.
- [x]`C029``parseFileUrlHref` already decodes the path (line 46), but `safeDecode` is called again here, corrupting filenames containing `%` sequences. Consider skipping the decode when `fileUrlTarget` is non-null.
- Status: `DONE`
- Verdict: `valid`
- Severity: `Medium`
- Area: `Edge-case parsing/platform behavior`
- File: `apps/web/src/markdown-links.ts:105`
- Threads: PRRT_kwDORLtfbc5wnVsU
- Audit note: file URL decoding still double-decodes in one path.
- [x]`C030``EXTERNAL_SCHEME_PATTERN` matches `script.ts:10` as a scheme because `.ts:` looks like `scheme:`. Consider requiring `://` after the colon, or checking that what follows the colon is not just digits. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Status: `DONE`
- Verdict: `valid`
- Severity: `Medium`
- Area: `Edge-case parsing/platform behavior`
- File: `apps/web/src/markdown-links.ts:111`
- Threads: PRRT_kwDORLtfbc5wnVsK
- Audit note: Scheme regex still misclassifies script.ts:10 as external scheme.
- [ ]`C038` Multi-byte UTF-8 characters split across chunks will be corrupted when decoding each chunk separately. Consider accumulating all chunks first, then decoding once, or use `TextDecoder` with `stream: true`. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Audit note: Chunk-by-chunk UTF-8 decode can still corrupt split multibyte characters.
- [x]`C039` The `+` key can be parsed (via trailing `+` handling) but cannot be encoded because `shortcut.key.includes("+")` returns true for the literal `+` key. Consider checking `shortcut.key === "+"` separately and encoding it as `"space"` style (e.g., a special token), or adjusting the condition to allow the single `+` character. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Status: `DONE`
- Verdict: `partially-valid`
- Severity: `Low`
- Area: `Edge-case parsing/platform behavior`
- File: `apps/server/src/keybindings.ts:352`
- Threads: PRRT_kwDORLtfbc5wxvIB
- Audit note: Parser/encoder mismatch remains, but encoder path currently low-use.
- [x]`C040``upsertKeybindingRule` has a race condition: concurrent calls read the same file state, then the last write overwrites earlier changes. Consider wrapping the read-modify-write sequence with `Effect.Semaphore` to serialize access. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Audit note: Optimistic local+server dual update is intentional but can temporarily diverge.
- [x]`C037``Effect.callback` should return a cleanup function to close the server(s) on fiber interruption. Without it, the `Net.Server` handles keep the process alive and leak the port if the effect is cancelled. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Status: `DONE`
- Verdict: `partially-valid`
- Severity: `Low`
- Area: `Other`
- File: `apps/server/src/config.ts:41`
- Threads: PRRT_kwDORLtfbc5wj4cO
- Audit note: Callback cleanup missing, but practical exposure is low in one-shot startup path.
- [ ]`C047``SqlSchema.findOneOption` can produce both SQL errors and decode errors, but `mapError` wraps all as `PersistenceSqlError`. Consider distinguishing `ParseError` from SQL errors and mapping decode failures to `PersistenceDecodeError` instead. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Audit note: Decode and SQL errors still collapsed into one persistence error kind.
- [x]`C049``JSON.stringify(cause)` returns `undefined` for `undefined`, functions, or symbols, violating the `string` return type. Consider coercing the result to a string (e.g., `String(JSON.stringify(cause))`) or adding a fallback.
- Audit note: JSON.stringify(cause) may return undefined despite string expectations.
- [ ]`C050` The read-modify-write pattern (`getBySessionId` → merge → `upsert`) is susceptible to lost updates under concurrent writes. Consider wrapping in a transaction or adding optimistic concurrency control (e.g., version field) if concurrent session updates are expected. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Audit note: ProviderSessionDirectory upsert remains read-merge-write without concurrency control.
- [x]`C051` Using `??` for `providerThreadId` and `adapterKey` makes it impossible to clear these fields by passing `null`, since `null ?? existing` evaluates to `existing`. Consider using explicit `undefined` checks (like `resumeCursor` does) if clearing should be supported. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Audit note: Null-clearing issue is real for providerThreadId; adapterKey part overstated.
- [ ]`C052` Race condition: `processHandle` may be `null` when `data` callback fires, since it's assigned after `Bun.spawn` returns. Consider initializing `BunPtyProcess` first, then passing it to the callback to avoid losing initial output. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Audit note: Data callback may race before processHandle assignment.
- [ ]`C056` When `onOpenChange` is provided without `open`, the internal `_open` state never updates because `setOpenProp` takes precedence. Consider calling `_setOpen` when `openProp === undefined`, regardless of whether `setOpenProp` exists.
- Audit note: Bug pattern exists, but current callsites mostly avoid triggering it.
- [ ]`C057` The `resizable` object is recreated on every render, causing `SidebarRail`'s `useEffect` to repeatedly read localStorage and update the DOM. Consider memoizing the object with `useMemo`. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Audit note: Resizable object recreation still retriggers effect/storage reads.
- [ ]`C058` When `localStorage.getItem()` returns `null`, `Number(null)` evaluates to `0`, which passes `Number.isFinite(0)`. This causes the sidebar to clamp to `minWidth` on first load, overriding the `DIFF_INLINE_DEFAULT_WIDTH` CSS clamp. Consider checking for `null` or empty string before parsing, e.g. guard with `storedWidth === null || storedWidth === ''`. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Audit note: Number(null) -> 0 path still forces min width on initial load.
- [ ]`C060``defaultModel` should be `Schema.optional(Schema.NullOr(Schema.String))` to allow clearing the value. Currently there's no way to reset it to `null` since omitting means "no change" in patch semantics. <details> <summary>🚀 Reply "<strong>fix it for me</strong>" or copy this <strong>AI Prompt</strong> for your agent:</summary>
- Rationale: Broad catch is intentional for worker liveness; transactional dispatch path prevents the claimed non-invariant idempotency break in current design.
- [x]`C021` Shared mutable default metadata object causes stale eventId
# Plan: Claude Code Integration (Orchestration Architecture)
## Why this plan was rewritten
The previous plan targeted a pre-orchestration architecture (`ProviderManager`, provider-native WS event methods, and direct provider UI wiring). The current app now routes everything through:
2. Start input now uses typed `providerOptions` and generic `resumeCursor`; top-level provider-specific fields were removed.
3.`resumeCursor` is intentionally opaque outside adapters and must never be synthesized from `providerThreadId`.
4.`ProviderService` still requires adapter `startSession()` to return a `ProviderSession` with `threadId`.
5. Checkpoint revert currently calls `providerService.rollbackConversation()`, so Claude adapter needs a rollback strategy compatible with current reactor behavior.
6. Web currently marks Claude as unavailable (`"Claude Code (soon)"`) and model picker is Codex-only.
---
## Architecture target
Add Claude as a first-class provider adapter that emits canonical runtime events and works with existing orchestration reactors without adding new WS channels or bypass paths.
Key decisions:
1. Keep orchestration provider-agnostic; adapt Claude inside adapter/layer boundaries.
2. Use the existing canonical runtime stream (`ProviderRuntimeEvent`) as the only ingestion contract.
3. Keep provider session routing in `ProviderService` and `ProviderSessionDirectory`.
4. Add explicit provider selection to turn-start intent so first turn can start Claude session intentionally.
---
## Phase 1: Contracts and command shape updates
### 1.1 Provider-aware model contract
Update `packages/contracts/src/model.ts` so model resolution can be provider-aware instead of Codex-only.
Expected outcomes:
1. Introduce provider-scoped model lists (Codex + Claude).
2. Add helpers that resolve model by provider.
3. Preserve backwards compatibility for existing Codex defaults.
### 1.2 Turn-start provider intent
Update `packages/contracts/src/orchestration.ts`:
1. Add optional `provider: ProviderKind` to `ThreadTurnStartCommand`.
2. Carry provider through `ThreadTurnStartRequestedPayload`.
3. Keep existing command valid when provider is omitted.
This removes the implicit “Codex unless session already exists” behavior as the only path.
### 1.3 Provider session start input for Claude runtime knobs (completed)
Update `packages/contracts/src/provider.ts`:
1. Move provider-specific start fields into typed `providerOptions`:
-`providerOptions.codex`
-`providerOptions.claudeCode`
2. Keep `resumeCursor` as the single cross-provider resume input in `ProviderSessionStartInput`.
3. Deprecate/remove `resumeThreadId` from the generic start contract.
4. Treat `resumeCursor` as adapter-owned opaque state.
### 1.4 Contract tests (completed)
Update/add tests in `packages/contracts/src/*.test.ts` for:
1. New command payload shape.
2. Provider-aware model resolution behavior.
3. Breaking-change expectations for removed top-level provider fields.
Claude adapter must translate Agent SDK output into canonical `ProviderRuntimeEvent`.
Initial mapping target:
1. assistant text deltas -> `content.delta`
2. final assistant text -> `item.completed` and/or `turn.completed`
3. approval requests -> `request.opened`
4. approval results -> `request.resolved`
5. system lifecycle -> `session.*`, `thread.*`, `turn.*`
6. errors -> `runtime.error`
7. plan/proposed-plan content when derivable
Implementation note:
1. Keep raw Claude message on `raw` for debugging.
2. Prefer canonical item/request kinds over provider-native enums.
3. If Claude emits extra event kinds we do not model yet, map them to `tool.summary`, `runtime.warning`, or `unknown`-compatible payloads instead of dropping silently.
### 2.4 Resume cursor strategy
Define Claude-owned opaque resume state, e.g.:
```ts
interfaceClaudeResumeCursor{
readonlyversion: 1;
readonlythreadId?: string;
readonlysessionAt?: string;
}
```
Rules:
1. Serialize only adapter-owned state into `resumeCursor`.
2. Parse/validate only inside Claude adapter.
3. Store updated cursor when Claude runtime yields enough data to resume safely.
4. Never overload orchestration thread id as Claude thread id.
1. If a thread turn start requests `provider: "claudeCode"`, start Claude if no active session exists.
2. If a thread already has Claude session binding, reuse it.
3. If provider switches between Codex and Claude, explicitly stop/rebind before next send.
---
## Phase 4: Checkpoint and revert strategy
Claude does not necessarily expose the same conversation rewind primitive as Codex app-server. Current architecture expects `providerService.rollbackConversation()`.
Pick one explicit strategy:
### Option A: provider-native rewind
If SDK/runtime supports safe rewind:
1. implement in Claude adapter
2. keep `CheckpointReactor` unchanged
### Option B: session restart + state truncation shim
If no native rewind exists:
1. Claude adapter returns successful rollback by:
- stopping current Claude session
- clearing/rewriting stored Claude resume cursor to last safe resumable point
- forcing next turn to recreate session from persisted orchestration state
2. Document that rollback is “conversation reset to checkpoint boundary”, not provider-native turn deletion.
Whichever option is chosen:
1. behavior must be deterministic
2. checkpoint revert tests must pass under orchestration expectations
3. user-visible activity log should explain failures clearly when provider rollback is impossible
---
## Phase 5: Web integration
### 5.1 Provider picker and model picker
Update web state/UI:
1. allow choosing Claude as thread provider before first turn
2. show Claude model list from provider-aware model helpers
3. preserve existing Codex default behavior when provider omitted
Likely touch points:
1.`apps/web/src/store.ts`
2.`apps/web/src/components/ChatView.tsx`
3.`apps/web/src/types.ts`
4.`packages/shared/src/model.ts`
### 5.2 Settings for Claude executable/options
Add app settings if needed for:
1. Claude binary path
2. default permission mode
3. default max thinking tokens
Do not hardcode provider-specific config into generic session state if it belongs in app settings or typed `providerOptions`.
### 5.3 Session rendering
No new WS channel should be needed. Claude should appear through existing:
1. thread messages
2. activities/worklog
3. approvals
4. session state
5. checkpoints/diffs
---
## Phase 6: Testing strategy
### 6.1 Contract tests
Cover:
1. provider-aware model schemas
2. provider field on turn-start command
3. provider-specific start options schema
### 6.2 Adapter layer tests
Add `ClaudeAdapter.test.ts` covering:
1. session start
2. event mapping
3. approval bridge
4. resume cursor parse/serialize
5. interrupt behavior
6. rollback behavior or explicit unsupported error path
Use SDK-facing layer tests/mocks only at the boundary. Do not mock orchestration business logic in higher-level tests.
### 6.3 Provider service integration tests
Extend provider integration coverage so Claude is exercised through `ProviderService`:
1. start Claude session
2. send turn
3. receive canonical runtime events
4. restart/recover using persisted binding
### 6.4 Orchestration integration tests
Add/extend integration tests around:
1. first-turn provider selection
2. Claude approval requests routed through orchestration
3. Claude runtime ingestion -> messages/activities/session updates
4. checkpoint revert behavior under Claude
5. stopAll/restart recovery
These should validate real orchestration flows, not just adapter behavior.
# Plan: Provider-Neutral Runtime Determinism and Flake Elimination
## Summary
Replace timing-sensitive websocket and orchestration behavior with explicit typed runtime boundaries, ordered push delivery, and server-owned completion receipts. The cutover is broad and single-shot: no compatibility shim, no mixed old/new transport. The design must reduce flakes without baking Codex-specific lifecycle semantics into generic runtime code.
## Implementation Status
All 7 sections are implemented. CI passes (format, lint, typecheck, test, browser test, build). One deferred item remains: the shared `WsTestClient` helper from section 7 — tests use direct transport subscription and receipt-based waits instead.
### New files
| File | Purpose |
|------|---------|
| `packages/shared/src/DrainableWorker.ts` | Queue-based Effect worker with deterministic `drain` signal |
-`packages/contracts/src/ws.ts` now derives push messages from a `WsPushPayloadByChannel` channel-to-schema map. `WsPush` is a union schema replacing `channel: string` + `data: unknown`.
- Every server push carries `sequence: number`, auto-incremented in `ServerPushBus`.
-`packages/shared/src/schemaJson.ts` provides structured decode diagnostics via `formatSchemaError`.
-`packages/contracts/src/ws.test.ts` covers typed push envelope validation and channel/payload mismatch rejection.
### 3. Introduce explicit server readiness and a single push pipeline — DONE
-`apps/server/src/wsServer/pushBus.ts`: `ServerPushBus` with `publishAll` (broadcast) and `publishClient` (targeted) methods, backed by one ordered path. All pushes flow through it.
-`apps/server/src/wsServer/readiness.ts`: `ServerReadiness` with Deferred-based barriers for HTTP listening, push bus, keybindings, terminal subscriptions, and orchestration subscriptions.
-`server.welcome` is emitted only after connection-scoped and server-scoped readiness is complete.
-`wsServer.ts` no longer publishes directly from ad hoc background streams.
### 4. Turn background watchers into explicit runtimes — DONE
-`apps/server/src/keybindings.ts` refactored as explicit `KeybindingsShape` service with `start`, `ready`, `snapshot` semantics.
- Initial config load, cache warmup, and dual watcher attachment (`fs.watch` + `watchFileWithStatPolling`) complete before `ready` resolves.
-`watchFileWithStatPolling.ts` is the thin adapter for environments where `fs.watch` is unreliable.
### 5. Replace polling-based orchestration waiting with receipts — DONE
-`RuntimeReceiptBus` service defines three receipt types: `CheckpointBaselineCapturedReceipt`, `CheckpointDiffFinalizedReceipt` (with `status: "ready"|"missing"|"error"`), and `TurnProcessingQuiescedReceipt`.
-`CheckpointReactor`, `ProviderCommandReactor`, and `ProviderRuntimeIngestion` use `DrainableWorker` and publish receipts on completion.
- Integration harness and checkpoint tests await receipts instead of polling snapshots and git refs.
### 6. Centralize client transport state and decoding — DONE
-`apps/web/src/wsTransport.ts` implements an explicit connection state machine: `connecting`, `open`, `reconnecting`, `closed`, `disposed`.
- Two-phase decode (JSON parse → Schema validate) happens at the transport boundary. `wsNativeApi.ts` receives pre-validated messages.
- Cached latest welcome/config modeled as explicit `latestPushByChannel` state.
### 7. Replace ad hoc test helpers with semantic test clients — MOSTLY DONE
-`DrainableWorker` replaces timing-sensitive `Effect.sleep` with deterministic `drain()` across reactor tests.
- Orchestration harness waits on receipts/barriers instead of `waitForThread`, `waitForGitRef`, and retry loops.
- Behavioral assertions moved to deterministic unit-style harnesses; narrow integration tests kept for real filesystem/socket behavior.
- **Deferred:** Shared `WsTestClient` helper (connect, awaitSemanticWelcome, awaitTypedPush, trackSequence, matchRpcResponseById). Tests use direct transport subscription instead.
## Provider-Coupling Guardrails
- No generic runtime API may depend on Codex-native event names, thread IDs, or request payload shapes.
- No readiness barrier may be defined as "Codex has emitted X." Readiness is owned by the server runtime, not by provider event order.
- No websocket channel payload may contain raw provider-native payloads unless the channel is explicitly debug/internal.
- Any provider-specific divergence must be exposed through provider capabilities from `ProviderService.getCapabilities()`, not `if provider === "codex"` branches in shared runtime code.
- Generic tests must use canonical `ProviderRuntimeEvent` fixtures. Codex-specific ordering and translation tests stay in adapter/app-server suites only.
- Keep UI/provider-specific knobs such as Codex-only options scoped to provider UX code. Do not pull them into generic transport or orchestration state.
## Test Plan
- Contracts:
- schema tests for typed push envelopes and structured decode diagnostics
Define the long-term server auth architecture for T3 Code before first-class remote environments ship.
This plan is deliberately broader than the current WebSocket token check and narrower than a complete remote collaboration system. The goal is to make the server secure by default, keep local desktop UX frictionless, and leave clean integration points for future remote access methods.
This document is written in terms of Effect-native services and layers because auth needs to be a core runtime concern, not route-local glue code.
## Primary goals
- Make auth server-wide, not WebSocket-only.
- Make insecure exposure hard to do accidentally.
- Preserve zero-login local desktop UX for desktop-managed environments.
- Support browser-native pairing and session auth.
- Leave room for native/mobile credentials later without rewriting the server boundary.
- Keep auth separate from transport and launch method.
## Non-goals
- Full multi-user authorization and RBAC.
- OAuth / SSO / enterprise identity.
- Passkeys or biometric UX in v1.
- Syncing auth state across environments.
- Designing the full remote environment product in this document.
## Core decisions
### 1. Auth is a server concern
Every privileged surface of the T3 server must go through the same auth policy engine:
- HTTP routes
- WebSocket upgrades
- RPC methods reached through WebSocket
The current split where [`/ws`](../apps/server/src/ws.ts) checks `authToken` but routes in [`http.ts`](../apps/server/src/http.ts) do not is not sufficient for a remote-capable product.
### 2. Pairing and session are different things
The system should distinguish:
- bootstrap credentials
- session credentials
Bootstrap credentials are short-lived and high-trust. They allow a client to become authenticated.
Session credentials are the durable credentials used after pairing.
Bootstrap should never become the long-lived request credential.
### 3. Auth and transport are separate
Auth must not be defined by how the client reached the server.
Examples:
- local desktop-managed server
- LAN `ws://`
- public `wss://`
- tunneled `wss://`
- SSH-forwarded `ws://127.0.0.1:<port>`
All of these should feed into the same auth model.
### 4. Exposure level changes defaults
The more exposed an environment is, the narrower the safe default should be.
The server can emit a pairing URL where the token lives in the URL fragment so it is not automatically sent to the server before the client explicitly exchanges it.
## Sequence diagrams
These flows are meant to anchor the auth model in concrete user journeys.
The important invariant across all of them is:
- access method is not the auth method
- launch method is not the auth method
- bootstrap credential is not the session credential
### Normal desktop user
This is the default desktop-managed local flow.
The desktop shell is trusted to bootstrap the local renderer, but the renderer should still exchange that one-time bootstrap grant for a normal browser session cookie.
PhoneBrowser -> PrivateNet : GET /ws + authenticated cookie
PrivateNet -> T3Server : websocket upgrade
T3Server --> PhoneBrowser : websocket accepted
```
### Desktop user adding new SSH hosts
SSH should be treated as launch and reachability plumbing, not as the long-term auth model.
The desktop app uses SSH to start or reach the remote server, then the renderer pairs against that server using the same bootstrap/session split as every other environment.
```text
Participants:
DesktopUser = local desktop user
DesktopMain = desktop app
SSH = ssh transport/session
RemoteHost = remote machine
RemoteT3 = remote T3 server
Frontend = desktop renderer
DesktopUser -> DesktopMain : add SSH host
DesktopMain -> SSH : connect to remote host
SSH -> RemoteHost : probe environment / verify t3 availability
DesktopMain -> SSH : run remote launch command
SSH -> RemoteHost : t3 remote launch --json
RemoteHost -> RemoteT3 : start or reuse server
RemoteT3 --> RemoteHost : port + environment metadata
note over RemoteT3 : policy = RemoteReachablePolicy
note over DesktopMain,RemoteT3 : desktop may use a trusted bootstrap flow here
Frontend -> DesktopMain : request bootstrap for selected environment
DesktopMain --> Frontend : short-lived bootstrap grant
Frontend -> RemoteT3 : POST /api/auth/bootstrap via forwarded port
RemoteT3 -> RemoteT3 : validate bootstrap grant
RemoteT3 -> RemoteT3 : create browser session
RemoteT3 --> Frontend : Set-Cookie: session=...
Frontend -> RemoteT3 : GET /ws + authenticated cookie
RemoteT3 --> Frontend : websocket accepted
```
## Storage decisions
### Server secrets
Use a `ServerSecretStore` abstraction.
Preferred order (use a layer for each, resolve on startup):
1. OS secure storage if available
2. hardened filesystem fallback if not
The filesystem fallback should store only opaque signing material with strict file permissions. It should not store user passwords or reusable third-party credentials.
### Client credentials
Client-side credential persistence should prefer secure storage when available:
- desktop: OS keychain / secure store
- mobile: platform secure storage
- browser: cookie session for browser auth
This concern should stay in the client shell/runtime layer, not the server auth layer.
## What to build now
These are the parts worth building before remote environments ship:
1.`ServerAuth` service boundary.
2. route classification and route guards.
3.`ServerSecretStore` abstraction.
4. bootstrap vs session credential split.
5. browser session cookie codec as one session method.
6. explicit auth capabilities/config surfaced in contracts.
Even if only one pairing flow is used initially, these seams will keep future remote and mobile work contained.
## What to add as part of first remote-capable auth
1. Browser pairing flow using one-time bootstrap token and cookie session.
2. Desktop-managed auto-bootstrap for the local desktop-managed environment.
3. Auth-required defaults for any non-loopback or explicitly published server.
Make remote access feel first-class while keeping the free DIY path open.
The immediate product goal is:
- users can expose a backend through LAN, their own Tailscale, MagicDNS, a manual HTTPS endpoint, or later T3 Tunnel
- users can generate a hosted pairing link for `app.t3.codes`
- the hosted app can pair, persist, reconnect, and operate against saved environments without requiring a backend at the hosted app origin
- all transports reuse the same backend auth, WebSocket runtime, saved environment registry, and pairing UX
This plan intentionally leaves the paid T3 cloud tunnel fabric out of scope. It defines the OSS foundation that T3 Tunnel should later plug into.
## Current State
Already present or in progress:
- Server auth distinguishes bootstrap credentials from session credentials.
- One-time pairing credentials can be exchanged for browser sessions or bearer sessions.
- Saved remote environments store `httpBaseUrl`, `wsBaseUrl`, and a bearer token.
- Remote environment WebSocket connections use a short-lived WebSocket token.
- Pairing URLs can carry tokens in the URL fragment.
- Hosted `/pair?host=...#token=...` can add a saved environment.
- Hosted static startup can avoid assuming the page origin is the backend.
Main gaps:
- Reachability is represented ad hoc as `endpointUrl`, manual host input, or saved environment URLs.
- Desktop exposure, hosted pairing, manual remote environments, and future tunnels do not share one endpoint model.
- Tailscale/MagicDNS endpoints are not detected or surfaced.
- Hosted-static empty/offline states are still thin.
- Browser compatibility is not explicitly modeled, especially HTTPS hosted app to HTTP backend mixed-content failure.
## Core Decision: Add `AdvertisedEndpoint`
Add a new first-class contract instead of extending the environment descriptor.
### Why not extend `ExecutionEnvironmentDescriptor`
`ExecutionEnvironmentDescriptor` answers: "What environment is this?"
Examples:
- environment id
- label
- platform
- server version
- capabilities
`AdvertisedEndpoint` answers: "How can a client reach this environment right now?"
Examples:
- loopback URL
- LAN URL
- Tailscale IP URL
- MagicDNS/Serve URL
- manual URL
- future T3 Tunnel URL
- browser compatibility and exposure level
Those are different lifecycles. One environment can have many endpoints, endpoints can appear/disappear as network interfaces change, and the same descriptor is returned regardless of which endpoint the client used. Extending the descriptor would blur environment identity with transport reachability and make saved environments harder to reason about.
### Target Contract
Add a schema in `packages/contracts`, likely `remoteAccess.ts`:
5. Add WebSocket/API method or existing config field for endpoint snapshots.
6. Refactor settings connections UI:
- render endpoint rows
- endpoint picker for pairing link copy
- show compatibility warnings
7. Refactor hosted link builder to accept endpoint records.
8. Add tests for URL normalization and compatibility classification.
### Acceptance Criteria
- Existing LAN/network access UI still works.
- Pairing links are generated from endpoint records.
- Loopback endpoints never produce hosted pairing links silently.
- HTTP private-network endpoints are marked incompatible with `app.t3.codes`.
- No remote environment runtime changes are required for existing saved environments.
## Phase 2: BYO Tailscale/MagicDNS
### Goals
- Detect free DIY Tailscale reachability.
- Surface Tailscale endpoints as normal advertised endpoints.
- Keep users in control of their own tailnet.
### Tasks
1. Detect Tailscale IPs from network interfaces:
- IPv4 `100.64.0.0/10`
- mark as `provider: "tailscale-ip"`
2. Add optional desktop-side `tailscale status --json` discovery:
- MagicDNS hostname
- Tailscale Serve/Funnel HTTPS endpoint if discoverable
- graceful failure if CLI is missing
3. Add manual Tailscale endpoint override:
- hostname
- label
- preferred/default flag
4. Show Tailscale endpoint rows in settings:
- raw IP HTTP endpoint: desktop-compatible, hosted-app likely blocked
- HTTPS MagicDNS/Serve endpoint: hosted-compatible if URL is HTTPS
5. Generate pairing links using selected Tailscale endpoint.
6. Document DIY setup:
- local desktop-to-desktop over Tailscale
- hosted app requirements
- why HTTPS matters
### Acceptance Criteria
- A machine on Tailscale shows a Tailscale endpoint without paid features.
- Users can copy a Tailscale-hosted pairing link when the endpoint is HTTPS-compatible.
- Users can still copy token-only/manual values when endpoint compatibility is unknown.
- Tailscale is optional and never required for regular LAN/loopback use.
## Phase 3: Hosted Static App Completion
### Goals
-`app.t3.codes` works as a real client shell.
- It can pair, persist, reconnect, and clearly explain offline/incompatible states.
### Tasks
1. Finish hosted-static root behavior:
- no primary backend required
- saved environment hydration before initial routing decisions
- first saved environment selected as active
2. Add hosted empty state:
- no saved environments
- paste pairing URL
- add host + token
3. Add offline saved environment UI:
- last connected
- reconnect
- remove
- copy/add alternate endpoint
4. Audit primary-backend assumptions:
- command palette
- settings pages
- server config atom defaults
- keybindings
- provider/model lists
- update/desktop-only affordances
5. Add route tests for:
- hosted `/pair?host=...#token=...`
- hosted root with no saved environments
- hosted root with saved environment
- primary backend unavailable but saved environment present
6. Add deployment hardening:
- SPA fallback
- strict CSP
- no third-party scripts
- no query token logging
- disable or hide source maps in production if needed
7. Add browser error messages:
- mixed content
- unreachable backend
- CORS failure
- certificate failure
### Acceptance Criteria
-`app.t3.codes` can pair a reachable HTTPS backend and reconnect after reload.
- A saved environment can be used without any backend at `app.t3.codes`.
- Offline machines show a useful state instead of a generic boot error.
- HTTP endpoints are still supported in desktop/native/local contexts.
- Hosted HTTPS app only promises compatibility for HTTPS/WSS endpoints.
## Phase 4: Future T3 Tunnel Provider
Not part of the current implementation, but the endpoint abstraction should make it straightforward.
Future tunnel provider responsibilities:
- create endpoint with `provider: "t3-tunnel"`
- surface tunnel status
- provide stable HTTPS URL
- use existing backend pairing/session auth
- never bypass server auth
The tunnel fabric can later be Pipenet-derived, Tailscale-derived, or another reverse tunnel implementation. The rest of T3 Code should only see an `AdvertisedEndpoint`.
## Security Checklist
- Pairing tokens are short-lived and one-time.
- Generated hosted pairing links put tokens in the fragment.
- The backend remains the authorization boundary.
- Endpoint discovery never disables backend auth.
- Hosted app does not silently downgrade to HTTP.
- Tunnel/public endpoints require explicit user action.
- Client sessions remain revocable.
- Endpoint URLs and request logs must avoid recording pairing tokens.
- Future cloud tunnel must authenticate tunnel creation and tunnel data connections separately from backend pairing.
## Verification
Each implementation PR should run:
-`bun fmt`
-`bun lint`
-`bun typecheck`
- focused tests for changed backend/web behavior
- backend tests for any server-side endpoint discovery or auth changes using `bun run test`, never `bun test`
Implement the shared backend foundation for forking, provider handoff, merge-back, and future subagents without forcing provider selection at fork time. The first slice should create cheap app-level fork lineage and defer expensive context materialization until a run starts and the target provider is known.
1. No pending transfer targeting the thread/run: normal run start.
2. Pending fork transfer and same provider with native fork support: resolve native fork.
3. Pending transfer requiring portable context: return explicit unsupported/stub result in first slice, or build minimal portable context if cheap.
4. Failed resolution: fail command before provider side effects.
The resolver should be called before provider thread creation/startTurn so the adapter can decide whether to create, resume, or native-fork provider state.
## Codex Native Fork Path
Investigate the app-server native fork API in `effect-codex-app-server` and Codex docs/probes.
Implementation target:
- use native fork only when source provider is Codex and source native refs are strong;
- create or bind a new `ProviderThread` for the forked native thread;
- when the source point is an earlier completed Codex provider turn, fork the latest native thread first and then rollback the forked native thread by later terminal provider turns;
- mark `ContextTransfer.status = resolved_native` and then `consumed` when the first run starts;
If native API details are not clean, land the data model and resolver first with native fork marked unsupported, then add Codex native fork in a follow-up.
## Portable Context Fallback
The first slice should define the fallback boundary even if it does not fully implement high-quality summarization.
Minimum viable fallback:
- detect cross-provider fork/handoff need;
- create failed/unsupported transfer resolution with a clear command error, or
- generate a deterministic minimal context handoff from app projection if we want a usable MVP.
Do not silently concatenate hidden summaries into the user message without a `ContextTransfer`/`ContextHandoff` record.
## Merge-Back Preparation
Do not implement merge-back in the first slice, but keep model support:
-`ContextTransfer.type = "merge_back"`
-`basePoint` on transfer
- source thread may differ from target thread
The later merge-back command should create a transfer from fork latest stable point back to source thread and consume it with the next user message.
## Subagent Preparation
Do not implement subagents in this slice, but keep model support:
-`createdBy: "agent"`
-`type: "subagent_spawn"` and `"subagent_result"`
- source/target thread relationship fields
Native subagent ingestion can later map provider-native child refs into the same graph. Cross-provider app-owned subagents can later create child app threads using the same transfer primitive.
## Projection And Debugger
Backend projection first:
- expose thread lineage in thread projection;
- expose context transfers in debug projection;
- expose transfer status and resolution strategy.
Debugger after backend:
- fork button/control from stable source point;
- show thread lineage/source point;
- show pending/resolved/failed transfers;
- show native vs portable resolution.
Do not build debugger controls before the backend projection is authoritative.
## Tests
Use `bun run test`, not `bun test`.
Required backend tests:
-`thread.fork` from latest completed checkpoint creates target thread and pending transfer.
- fork command is idempotent through command receipts.
- fork does not create provider session/thread eagerly.
- first run on same-provider fork invokes native resolution path when capability exists.
- unsupported native fork falls back or fails according to explicit policy.
- active-run fork policy is deterministic.
- replay/recovery preserves target thread lineage and pending transfer.
Add test provider layers only at external service boundaries. Do not mock core orchestration policy.
## Implementation Order
1. Add contract schemas and ids for context transfers/source points.
2. Add migration/projection table for context transfers.
3. Add event store/projection handling for transfer events.
4. Add `thread.fork` command policy and orchestrator path.
5. Add tests for cheap idle fork creation and recovery.
6. Add start-context resolver interface.
7. Wire resolver into run startup with no-op behavior.
8. Add Codex native fork capability investigation and adapter path.
9. Add tests for same-provider native fork resolution.
10. Add debug projection surface after backend behavior is stable.
## Validation
Before considering the slice complete:
-`bun fmt`
-`bun lint`
-`bun typecheck`
- targeted backend tests with `bun run test`
If backend code changes are included, tests must cover the new orchestration behavior before the task is considered done.
## Implementation Status
Implemented in this slice:
- context transfer ids, schemas, JSON codecs, events, and projection storage
- app-thread lineage on thread creation and fork creation
-`thread.fork` command using `latest_stable`, explicit run, or explicit checkpoint source points
- cheap idle fork creation with no eager provider session/thread/run
- Codex same-provider native `thread/fork` resolution on first target dispatch
- Codex native fork-from-earlier-run resolution with `thread/fork` plus fork-local `thread/rollback`
- transfer status progression through `pending`, `resolved_native`, and `consumed`
- command receipt idempotency for duplicate fork commands
- replay-backed integration coverage for lazy fork creation and native Codex fork consumption
Explicitly deferred:
- portable `ContextHandoff` materialization for cross-provider forks/provider handoff
- merge-back command/runtime
- subagent spawn/result runtime
- debugger controls for creating/inspecting transfers
Introduce a provider-neutral VCS layer and rewrite the local Git implementation as an Effect-native driver. This phase should preserve user-visible behavior while replacing the Git-first service boundary with an abstraction that can support Git, Jujutsu, and later Sapling or another viable VCS.
The existing `GitCore` implementation is a behavior reference and source of regression tests, not the target architecture. New code should follow the newer package style used by `effect-acp` and `effect-codex-app-server`: typed service tags, schema-backed tagged errors, scoped process usage, explicit decode boundaries, and no Promise-based process helper as the core execution primitive.
## Scope
- Add VCS-domain contracts in `packages/contracts/src/vcs.ts`.
- Add shared runtime parsing helpers in `packages/shared/src/vcs/*` only when they are useful to both server and web.
- Add server services under `apps/server/src/vcs`:
-`Services/VcsDriver.ts`
-`Services/VcsRepositoryResolver.ts`
-`Services/VcsProcess.ts`
-`Layers/GitVcsDriver.ts`
-`errors.ts`
- Migrate server callers from Git-specific terms where the operation is actually VCS-generic.
- Update active consumers to the new VCS APIs in the same phase; do not add backwards-compatible export shims.
- Leave source-control hosting providers out of this phase except for remote metadata needed to describe repository status.
## Non-Goals
- No GitLab, Azure DevOps, or GitHub provider rewrite yet.
- No Jujutsu driver yet, but every interface must be designed so a Jujutsu driver does not have to pretend to be Git.
- No T3 Review implementation yet.
- No broad UI redesign.
## Driver Model
Use provider-neutral nouns in new APIs:
-`VcsDriver`: local repository mechanics.
-`RepositoryIdentity`: detected VCS kind, root path, common metadata path when available, remotes.
-`WorkingCopyStatus`: dirty state, changed files, aggregate insertions/deletions, current branch/bookmark/change name.
-`ChangeSet`: a committed or pending unit of change, not necessarily a Git commit.
-`RefName`: branch, bookmark, tag, or provider-specific ref.
The initial driver capabilities should be explicit:
```ts
exportinterfaceVcsDriverCapabilities{
readonlykind:"git"|"jj"|"sapling"|"unknown";
readonlysupportsWorktrees: boolean;
readonlysupportsBookmarks: boolean;
readonlysupportsAtomicSnapshot: boolean;
readonlysupportsPushDefaultRemote: boolean;
}
```
Do not model Jujutsu as `GitCoreShape extends ...`. The Git driver can expose Git-specific implementation details internally, but the public VCS layer should describe operations by intent:
-`detectRepository(cwd)`
-`status(cwd, options)`
-`listRefs(cwd, query/pagination)`
-`checkoutRef(cwd, ref)`
-`createRef(cwd, ref, from?)`
-`createWorkspace(cwd, ref, path?)`
-`removeWorkspace(path)`
-`prepareChangeContext(cwd, filePaths?)`
-`createChange(cwd, message, options)`
-`push(cwd, target?)`
-`rangeContext(cwd, base, head)`
-`listWorkspaceFiles(cwd, options)`
## Effect Process Layer
Create a small reusable `VcsProcess` service instead of using `runProcess`.
Requirements:
- Implement with `ChildProcess` and `ChildProcessSpawner` from `effect/unstable/process`.
- Support scoped acquisition/release for long-running commands and interruption.
- Support bounded stdout/stderr collection with truncation markers.
- DO not eagerly consume full stdout/stderr, return stream apis and expose helpers for consumers so we don't consume streams to memory unnecessarily...
- Support stdin.
- Support timeout through Effect scheduling/interruption, not ad-hoc timers.
- Stream output lines to progress callbacks as Effects.
- Return a typed `ProcessOutput` value for successful execution.
- Fail with typed errors, not generic thrown exceptions.
Errors should be schema-backed tagged classes, for example:
-`VcsProcessSpawnError`
-`VcsProcessExitError`
-`VcsProcessTimeoutError`
-`VcsOutputDecodeError`
-`VcsRepositoryDetectionError`
-`VcsUnsupportedOperationError`
Every error should carry operation name, command display string, cwd when applicable, exit code when applicable, stderr/stdout tails when useful, and original cause where available. Override `message` for user readable messages that provides meaning and hints where appropriate. Errors are schema backed so the full error details will be persisted and serialized properly when stored to DB/Logfiles.
## Git Driver Rewrite
Rewrite Git support against `VcsProcess`.
Carry forward current behavior from:
-`apps/server/src/git/Layers/GitCore.ts`
-`apps/server/src/git/Layers/GitCore.test.ts`
- current Git status/branch/worktree contracts
But split the implementation into smaller modules:
- command execution and hardening config
- repository detection
- status parsing
- branch/ref parsing
- worktree operations
- commit/range context generation
- push/pull operations
Keep parsing deterministic. Prefer Git porcelain formats, null-separated output, and schema decoding for JSON-like command output. Avoid regex parsing where Git gives a structured format.
## Freshness and Local Caching
Define freshness rules in the VCS layer before adding more providers. Local VCS status is cheap enough to refresh often; network-backed status is not.
Treat these as live/local:
- repository detection for the active cwd
- working copy dirty state
- staged/unstaged/untracked file summaries
- current branch/bookmark/change name
- local branch/bookmark lists
- local worktree/workspace lists
These may run on user-visible polling, but should still be debounced and coalesced per repository root. Prefer filesystem-triggered invalidation where available, with a short fallback poll interval. Concurrent requests for the same repository/status shape should share one in-flight Effect.
Treat these as cached or explicit-refresh only:
- remote tracking branch refreshes
- ahead/behind counts that require network fetches
- default branch discovery from a remote provider
- remote branch lists beyond locally known refs
The VCS driver should expose freshness metadata with status results:
Remote refreshes should be opt-in per operation, for example `refresh: "local-only" | "allow-cached-remote" | "force-remote"`. The default for background status should be `local-only`.
Use Effect `Cache` for repository identity and expensive local metadata:
- key by resolved repository root plus VCS kind
- invalidate on cwd/root changes and workspace mutation operations
- use short TTLs for local status caches when filesystem events are unavailable
- never hide command failures behind stale values unless the caller explicitly accepts stale data
## Cutover Policy
Prefer direct migration and deletion over compatibility wrappers.
Rules:
- Update consumers to call `VcsDriver`/`VcsRepositoryResolver` directly as soon as the new API exists.
- Delete migrated `GitCore` service methods and tests in the same PR that moves their consumers.
- Do not keep backwards-compatible export shims, barrel aliases, or old service names for convenience.
- Transitional modules are allowed only when a caller group is too complex or risky to migrate in the same PR.
- Every transitional module must have a narrow owner, a removal checklist, and a test proving it delegates to the new implementation.
- No new feature work may depend on transitional modules.
Expected transitional candidates:
- The highest-level `GitManager` orchestration can be migrated in slices if doing the full Commit + PR flow in one PR is too risky.
- WebSocket payload compatibility can remain only where changing it would require a coordinated UI/server protocol migration. Internal server code should still use the new VCS contracts.
## Tests
Add integration-style tests with real temporary Git repositories for the new Git driver:
- non-repository detection
- status for clean/dirty/untracked/staged states
- branch/ref list with pagination
- checkout/create branch
- worktree create/remove
- commit context generation with file filters
- commit creation with hook progress events
- push behavior against a local bare remote
- status polling does not perform remote network refresh by default
- concurrent duplicate status requests are coalesced
- bounded output/truncation
- timeout/interruption
- typed error shape for command failure and missing executable
Move or duplicate only the tests needed to prove behavior, then delete the old service tests in the same migration slice.
## Migration Steps
1. Add `vcs` contracts and tagged errors.
2. Add `VcsProcess` and unit tests around process execution semantics.
3. Add `VcsDriver` and `VcsRepositoryResolver` service contracts.
4. Implement `GitVcsDriver` with real Git command integration tests.
5. Move `GitStatusBroadcaster` and branch/worktree flows to the VCS service directly.
6. Move commit/range/push callers to the VCS service directly.
7. Delete migrated `GitCore` internals and tests as each caller group moves.
8. Add a transitional adapter only for any remaining `GitManager` path that is explicitly too complex to cut over safely in one PR.
9. Remove every transitional adapter before starting Phase 2 unless the adapter is documented as blocking on the provider cutover.
## Acceptance Criteria
- Current Git branch/status/worktree/commit behavior remains intact.
- New Git implementation does not depend on `processRunner.ts`.
- New errors are typed and inspectable by tests.
- VCS interfaces contain no GitHub/GitLab/Azure concepts.
- Active consumers use the new VCS APIs directly; any remaining transitional module has a written removal checklist and no compatibility export shim.
- Background status refresh is local-only by default and cannot hit provider rate limits.
- Jujutsu can be added by implementing a real driver instead of conforming to Git command semantics.
# Version Control Phase 2: Source Control Provider Foundation
## Goal
Introduce a pluggable source-control provider layer and rewrite GitHub support as an Effect-native provider. This phase should preserve the existing GitHub Commit + PR flow while making GitLab and Azure DevOps additive drivers rather than branches inside GitHub-oriented code.
The existing `GitHubCli` service and GitHub-specific `GitManager` paths are behavior references. The new provider layer should use detailed tagged errors, schema decode boundaries, `effect/unstable/process`, capability flags, and provider-neutral change-request types.
## Scope
- Add provider-domain contracts in `packages/contracts/src/sourceControl.ts`.
- Add provider URL/reference parsing helpers in `packages/shared/src/sourceControl/*`.
- Add server services under `apps/server/src/sourceControl`:
-`Services/SourceControlProvider.ts`
-`Services/SourceControlProviderRegistry.ts`
-`Services/SourceControlProcess.ts`
-`Layers/GitHubSourceControlProvider.ts`
-`errors.ts`
- Migrate PR creation, PR lookup, default-branch lookup, clone URL lookup, and PR checkout through the provider layer.
- Update active consumers to the provider APIs directly; do not add backwards-compatible `GitHubCli` export shims.
- Keep GitHub as the only production provider at the end of this phase, but make GitLab and Azure implementation paths obvious and bounded.
## Non-Goals
- No GitLab implementation in this phase, except fixtures/contracts that prove the abstraction can represent merge requests.
- No Azure DevOps implementation in this phase, except URL/reference parser test cases if cheap.
- No in-app review UI yet.
- No hard dependency on one CLI forever. The first GitHub driver may use `gh`, but the interface should support REST/GraphQL implementations later.
## Provider Model
Use provider-neutral names:
-`SourceControlProvider`: hosted repository and change-request mechanics.
Add a registry that resolves a provider from repository remotes and explicit user input.
Rules:
- Detection should be pure where possible and testable without spawning CLIs.
- Remote URL parsing belongs in `packages/shared`, not server-only provider layers.
- Unknown providers should return explicit unsupported-operation errors, not silently fall back to GitHub.
- Provider selection should be stable per operation and logged with enough context to debug bad remote detection.
The registry should support multiple provider implementations at runtime, not a single dispatcher file with inline provider branches.
## Rate Limits and Provider Caching
Design the provider layer around a strict freshness budget. Provider API and CLI calls must not be part of frequent background polling unless the operation is explicitly marked safe and cached.
Default behavior:
- Pure URL/remote parsing is always live because it is local.
- Provider detection from local remotes is live-local.
- Authentication checks are cached.
- Repository metadata is cached.
- Default branch metadata is cached.
- Change-request lists are cached and refreshed on explicit user actions or coarse intervals.
- Full review threads, comments, file diffs, and timeline data are fetched only when the user opens the relevant review surface or explicitly refreshes it.
- Create/update operations invalidate affected cache keys immediately after success.
Every read operation that can touch a provider should accept a refresh policy. Background UI reads should default to `cache-first` or `stale-while-revalidate`; direct user actions like pressing refresh can use `force-refresh`.
Use Effect `Cache` for provider data:
- auth status: key by provider kind, hostname, workspace identity, and account if known; TTL around minutes, not seconds
- repository metadata/default branch: key by provider repository stable ID or normalized remote URL; TTL around tens of minutes
- change-request summary lists: key by provider repository, state/filter, source ref, target ref; short TTL with stale-while-revalidate
- individual change-request summaries: key by provider repository and provider CR ID; short TTL, invalidated after create/update/comment operations
- review threads/comments/diffs: key by provider CR ID and head SHA/version when available; fetch on demand for T3 Review
Provider drivers should surface rate-limit signals when available:
- remaining quota
- reset time
- retry-after duration
- whether the limit is primary, secondary/abuse, or unknown
Rate-limit errors should be typed, retryable when the provider gives a reset/retry time, and visible enough for the UI to avoid repeatedly retrying a blocked operation.
Avoid rate-limit footguns:
- no provider calls from render loops or fast status polling
- no listing all PRs/MRs across all repos to infer one branch state
- no silent GitHub fallback for unknown providers
- no unbounded cache cardinality for branch names or free-form search queries
- no per-thread duplicate provider refresh when multiple views observe the same repository
## GitHub Provider Rewrite
Rewrite GitHub support as `GitHubSourceControlProvider`.
Carry forward behavior from:
-`apps/server/src/git/Layers/GitHubCli.ts`
-`apps/server/src/git/Layers/GitHubCli.test.ts`
-`apps/server/src/git/githubPullRequests.ts`
- GitHub-specific `GitManager` PR paths
Implementation requirements:
- Use `SourceControlProcess` built on `effect/unstable/process`, not `runProcess`.
- Decode `gh api` and `gh pr --json` responses with Effect Schema.
- Use typed errors for auth failure, missing CLI, command failure, output decode failure, unsupported reference, and provider mismatch.
- Keep stdout/stderr bounded.
- Avoid global mutable auth caches unless they are Effect `Cache` values with explicit keys, TTLs, and invalidation behavior.
- Parse provider rate-limit headers or CLI/API error payloads when available and map them to typed rate-limit errors.
- Keep GitHub nouns inside the GitHub driver; convert to `ChangeRequest` at the provider boundary.
## GitManager Cutover
Refactor `GitManager` so it coordinates three independent services:
-`VcsDriver` for local repository mechanics.
-`SourceControlProviderRegistry` for hosted provider selection.
-`TextGeneration` for message/body generation.
`GitManager` should stop depending directly on GitHub services. User-visible step labels should be provider-neutral unless the selected provider is known and the label is intentionally provider-specific.
The Commit + PR flow should become:
1. Resolve VCS repository and local status.
2. Resolve source-control provider from remotes.
3. Generate commit content through the existing text generation service.
4. Create local change through `VcsDriver`.
5. Push through `VcsDriver` or a narrow provider push helper only if the VCS requires provider-specific target syntax.
6. Generate change-request title/body.
7. Create the change request through `SourceControlProvider`.
## Cutover Policy
This phase should aggressively remove old GitHub-specific internals.
Rules:
- Move each active consumer directly to `SourceControlProviderRegistry` or a concrete provider test layer.
- Delete migrated `GitHubCli` methods, tests, and GitHub-specific helper exports in the same PR that moves their final consumer.
- Do not add compatibility export shims from `apps/server/src/git` to `apps/server/src/sourceControl`.
- Transitional modules are allowed only for a bounded `GitManager` slice that cannot move safely with the rest of the provider cutover.
- Every transitional module must have an owner comment, a removal checklist, and no public exports consumed by new code.
- Provider-neutral web parsing should replace GitHub-only parsing directly; do not keep parallel parser stacks unless a route still requires both during a single PR.
## GitLab and Azure Readiness
Use the triaged references as implementation inputs, not merge targets:
- GitLab PR #592 is useful for `glab mr` command mapping and JSON normalization.
- Azure issue #1138 defines a good first Azure slice: remote/URL detection and change-request thread setup for same-repo URLs.
The abstraction should let Phase 3 add:
-`GitLabSourceControlProvider` using `glab`.
-`AzureDevOpsSourceControlProvider` using `az repos pr` or REST APIs.
No provider should need to edit GitHub code to join the registry.
## T3 Review Design Constraint
Do not optimize only for creation/checkout. The provider layer must be able to support a future in-app review surface.
That means contracts should include stable IDs and enough metadata for:
- file-level diffs
- inline review threads
- resolved/unresolved state
- top-level discussion comments
- pending review submission
- provider URL back-links
Provider-specific fields can live in a metadata bag, but core review behavior should not require the UI to know whether the backing service is GitHub, GitLab, or Azure DevOps.
## Tests
Add tests at three levels:
- Pure parser tests for GitHub, GitLab, and Azure remote URLs and change-request references.
- Provider unit tests with fake `SourceControlProcess` output and schema decode failures.
- Integration-style GitHub CLI tests only where they can run hermetically or be skipped without hiding unit coverage.
Required cases:
- GitHub PR URL, number, and branch-ish references.
- missing CLI and auth failures produce distinct typed errors.
- invalid CLI JSON fails at decode boundary with useful context.
## Migration Steps
1. Add `sourceControl` contracts and provider-neutral schemas.
2. Add shared remote/reference parser helpers and tests.
3. Add `SourceControlProcess` and provider errors.
4. Add provider registry with GitHub-only registration.
5. Implement `GitHubSourceControlProvider` from scratch against the new process layer.
6. Cut GitHub PR operations in `GitManager` over to the provider registry.
7. Replace web PR-reference parsing with provider-neutral parser output while keeping current GitHub UX.
8. Add provider cache metrics and tests for cache hit, stale refresh, invalidation, and rate-limit error mapping.
9. Delete the migrated `GitHubCli` implementation, tests, and GitHub-specific helper exports unless an explicit transitional checklist remains.
## Acceptance Criteria
- Existing GitHub Commit + PR and PR checkout flows still work.
-`GitManager` no longer imports or depends on `GitHubCli`.
- Active consumers use source-control provider APIs directly; any remaining transitional module has a written removal checklist and no compatibility export shim.
- Source-control contracts can represent GitHub PRs, GitLab MRs, and Azure DevOps PRs.
- Unknown/unsupported providers fail explicitly and visibly.
- GitHub command execution does not depend on `processRunner.ts`.
- Background provider reads are cached/coalesced and do not consume provider API quota on every status refresh.
- Rate-limit responses become typed errors with retry/reset metadata where available.
- The provider API includes the review operations needed by future T3 Review work, even if they are capability-gated.
"summary":"Global cross-thread audit of the v2 orchestrator DB (43,378 events across 63 streams, 6,286 turn items, 60 threads, 206 runs). Core invariants are healthy: event streams have zero version gaps/duplicates and no occurred_at regressions >5s; turn-item ordinals have zero collisions and are 100% consistent with orchestration_v2_turn_item_positions; no nativeItemRef duplicates; outbox (463 rows) and command receipts (580) are fully succeeded/accepted; all 12 failed runs surfaced exactly one user-visible error item; no items/runs stuck beyond the one currently-live run (started 17:03Z, audit ran 17:07Z). Findings are edge-case lineage danglers, generic error strings that discard the underlying cause, sessions left 'ready' after detach, and 13 old local_bash tasks projected as empty-prompt subagents.",
"stats":"43,378 events / 63 streams (0 version gaps, 0 dupes, 0 time regressions >5s); 6,286 turn items (6,042 completed, 243 failed, 2 interrupted, 1 running=live); 206 runs (188 completed, 12 failed, 4 cancelled, 1 interrupted, 1 running=live); 212 provider_turns; 19 provider_sessions (3 ready, 16 stopped); 40 subagents (38 completed, 2 failed); outbox 463 rows all 'succeeded'; receipts 580 all 'accepted'; 12 error items total. Loss sample: 258 native tool_use ids in latest 71e29ba5 log \u2192 all accounted for (254 direct items, 3 Agent spawns as subagent items, 1 in-flight run)."
},
{
"sessionKey":"a5a643b2-codex-heya",
"summary":"Small 4-run codex smoke session (\"heya\") on 2026-06-28 04:52-05:22 UTC, plus one delegated Claude task child thread. Core pipeline is healthy: all 19 main-thread items + 3 child items are projected with verbatim text, ordinals match turn_item_positions exactly, lineage (run/node/provider_turn refs, subagent -> child thread -> context-transfer -> handoff) fully resolves, and all runs/turns/nodes/items are terminal. Two real problems: the codex-native collab subagent spawned in run 3 left zero trace in ingested events (its wait tool call, web search, and final \"Hello.\" message are lost), and the run-4 delegated Claude task that failed with a 401 auth error is recorded as status \"completed\" everywhere because the adapter ignores is_error on subtype \"success\" results.",
"summary":"Short two-turn Codex session (\"hey\" then \"spawn a subagent and say hello\") that spawned one provider-native subagent thread. Pipeline health is very good: every user-visible native item (2 user messages, 2 assistant messages, webSearch, subAgentActivity, child assistant message) is ingested and projected with exact untruncated text; lineage is fully consistent (subagent item childThreadId -> child thread, forkedFrom points back to parent provider-thread/turn, provider_turns map to run_attempts); all runs/turns/nodes/items terminal completed matching the native turn/completed events; ordinals match orchestration_v2_turn_item_positions with no collisions or duplicates and projection order matches native emission order. Only gaps: an (empty) reasoning item and token-usage/rate-limit notifications are dropped by the adapter, which has no handlers for them.",
"summary":"Short grok session (2026-06-29 21:46-21:48): user said \"yoo\", then \"spawn some subagents\"; grok ran 3 parallel Task subagents (git state, architecture docs, mobile connection changes) as child threads and summarized. Pipeline health is good: all runs/attempts/provider-turns completed, provider session stopped, lineage intact, no ordinal collisions, no duplicates, no truncation (subagent item result lengths 3721/6274/2647 exactly match child assistant_message lengths). The children's 1319-2711 events vs 2 projected items is EXPECTED: each child has exactly 2 distinct item ids (prompt + result) and the event volume is per-token streaming re-upserts of the result item, not lost items.",
"summary":"Short cursor (glm-5.2) session \"Hello therw!\" with 2 user turns and zero assistant output. The 7-line native log is genuine: the backend child process fatally crashed (Node error originating in @cursor/sdk/dist/esm/index.js) ~0.3s after run 1's run.started, killing the provider mid-turn; a startup reconcile then cancelled run 1. Run 2 (\"what did you just say\") resumed the agent but agent.send rejected 4ms after run.start and was projected as a failed run with only a generic error string; the process crashed again with the same @cursor/sdk fatal error 29s later. Projection internals (ordinals, positions, statuses, lineage forward-links) are consistent and all state is terminal \u2014 the problems are crash handling and error fidelity, not ingestion mechanics.",
"summary":"Thread 48663fb7 is a single \"hello\" message sent to the cursor provider (glm-5.2) at 2026-06-29T21:49:07Z. The provider session opened and acked run.started at 21:49:09.097Z, then the server restarted; a startup runtime-reconcile at 21:49:10.775Z cancelled the run/attempt/provider-turn, idled the provider thread, and stopped the session. Pipeline health is good: no native output was lost (the provider emitted nothing after run.started), lineage and ordinals are consistent, and nothing is stuck in a non-terminal state. The only gap is that the user got no assistant response and no explanation of why the run was cancelled.",
"summary":"Opencode chat session \"Hey!\" (2026-06-29 22:02-22:16, idle-reaped 22:46): 7 user turns spawning 5 native opencode subagent sessions, 2 cross-provider delegated claudeAgent tasks (results handed back via context-transfer/handoff), and 3 top-level threads (codex/grok/claude). Pipeline health is very good: all 9 runs/7 attempts/12 provider turns completed, every distinct item id in events has exactly one projection, ordinals match event arrival order with zero collisions or duplicates, lineage (run/node/provider-turn/subagent->child-thread) fully resolves, and the provider session was cleanly stopped after the 30-min idle window. Main issues found are debuggability gaps rather than data loss: the one failed tool call projected no error message (file_search items structurally cannot carry one), file_search outputs are never projected, a placeholder \"pending\" provider_thread row lingers, and the native log itself is payload-redacted so content-level verification is impossible.",
"stats":"Native log: 17,198 lines (15,542 part deltas, 723 part updates, 204 message updates, 7 promptAsync, 5 session.created, 12 session.idle; 0 error lines). Events: main 3,335 (1,047 turn-item.updated over 50 distinct items), opencode children 1051/1107/559/241/209, delegated-task children 94/34. Projected items: main 50, opencode children 185, delegated children 23 \u2014 every distinct event item id has exactly one projection (50/90/41/39/8/7 match 1:1). Runs: 7 main + 2 delegated, all completed; 7 attempts completed; 12 provider_turns completed; sessions stopped. 1 failed item (file_search), 0 stuck items, 0 ordinal collisions, 0 dangling run/node/turn/thread refs, 0 nativeItemRef dupes, positions table fully consistent."
},
{
"sessionKey":"9f8d616d-opencode",
"summary":"Single-turn opencode session ('hey' -> greeting reply) on 2026-06-29: 1 run, 1 provider turn, ~5s of activity, then 30min of heartbeats until the idle reaper stopped the session. The 100-events/5-items ratio is benign: 25 of the 33 turn-item.updated events are streaming updates of one reasoning part. No data loss, no duplicates, no ordering violations, no errors in the native log, and all runs/turns/items are terminal. Only minor findings: the pending-vs-resolved provider-thread dual-row pattern leaves run/attempt/turn pointing at a different provider_thread_id than the items, and the resolved provider-thread row lingered 'active' for ~20h after session stop before being marked idle.",
"summary":"MCP delegated task \"hello-opus-48\" sent one user prompt (\"Say hello briefly and stop.\") to claudeAgent (claude-opus-4-8). The API call never succeeded: the SDK logged two api_retry events with error_status 401 (authentication_failed) and then emitted a synthetic assistant message \"Failed to authenticate. API Error: 401 Invalid authentication credentials\" plus a result with subtype \"success\" but is_error:true / api_error_status:401. Ingestion and projection are structurally clean (all 3 items projected, ordinals consistent, lineage valid, nothing stuck), but the run/attempt/provider-turn were all recorded as \"completed\" with no failure info, so the delegated task looks successful despite executing zero tokens.",
"summary":"MCP-driven fan-out session: 2 claudeAgent delegated-task threads plus 3 parallel MCP threads (codex :0, grok :1, claudeAgent :2), all single-run. Pipeline health is good overall: all 122 items verified against native logs with exact tool-call counts (19/19 on :2, 1/1 and 16/16 on the delegated tasks), ordinals fully consistent with turn_item_positions, zero lineage orphans, no duplicates, and the codex 400 model error was ingested verbatim and surfaced as a user-visible failed error item. Main defects found: the claudeAgent adapter (as of the code that ran, fc23be8184) concatenates intra-turn assistant text segments without separators into one end-of-turn item, destroying segment boundaries and native interleaving; and the three claudeAgent provider sessions were never idle-reaped, staying 'ready' for ~21 hours until a simultaneous shutdown sweep.",
"summary":"Two-run grok session (\"spawn a subagent\"): run 1 asked the user clarifying questions (xai-question), spawned a background explore subagent; run 2 fetched its output via a blocking TaskOutput tool call and summarized it. Main-thread projections are complete and consistent (16 items, all completed, positions/ordinals match, no dupes, all terminal states correct, no backwards timestamps). The main problem is the subagent child thread: it froze at spawn time with a placeholder result, and the subagent's entire live transcript (116 tool calls over 74.9s) was never ingested \u2014 the real output survives only inside a parent-thread tool item.",
"summary":"Dev session on scheduled tasks: run 1 on codex, then a provider handoff to claudeAgent for runs 2-10 (8 completed, run 9 user-cancelled, run 10 failed 2s after query.open with no SDK response). Pipeline health is very good: zero lost native content in the claudeAgent portion, lineage fully intact, ordering matches native emission exactly, no duplicates, and nothing stuck non-terminal (session stopped, provider threads idle, 0 running items). The only real defect found is that run 10's failure was persisted with a hardcoded generic message, making it undebuggable from the DB.",
"stats":"Main thread: 1707 events, 363 items (169 codex run-1 + 194 claude), 69 messages, 10 runs, 10 provider turns (8 completed/1 cancelled/1 failed). 15 child threads: 2 Explore subagents (95+245 events, 20+50 items) + 13 bash-task threads (7-9 events, 2 items each); all child items completed. Native log 5336 lines (2 files, runs 2-10 only). Cross-checks: 156/156 main tool_use ids accounted for (154 toolu items + 2 Agent calls projected as task subagent items), 64/64 subagent tool_use ids, assistant text preserved exactly (27311 chars log = 27311 chars items), 94 thinking blocks all natively empty (SDK sends thinking_delta with empty text), 5/5 is_error tool_results projected as failed, 1 api_retry (recovered), 14 task_notifications + 1 task_updated-only completion (bqu8waxt3) all reconciled; 0 ordinal collisions, 0 position mismatches, 0 orphan lineage refs. All backgrounded-bash tasks completed within their runs, so cross-run/wakeup paths were not exercised in this session."
},
{
"sessionKey":"47763f5e-claude-fable",
"summary":"Long claudeAgent coding session (PR #3638 scheduled-tasks work, 20:56-23:43 UTC on 2026-07-01) with 16 runs, 2 Task subagents, and heavy post-turn wakeup activity via task notifications. The persisted portion of the pipeline is healthy \u2014 lineage, ordinals/positions, ordering vs native emission, terminal states, and text fidelity all check out \u2014 but roughly 40% of the provider's actual output (10 full post-turn wakeup turns: 16 assistant messages and ~84 tool calls, including real git pushes) was never ingested at all, this being one of the threads on which that gap was originally diagnosed. Two error-handling gaps stand out: a 401 auth failure projected as a completed run, and run 10's failure persisted only as 'Claude Agent SDK query failed.' with no root cause recorded anywhere.",
"stats":"Native log: 8088 lines (all protocol/decoded): 25 results, 594 assistant msgs (68 distinct main-thread text msgs, 122 with thinking), 371 unique tool_use (307 main / 64 child), 49 task_notification, 4 rate_limit (all 'allowed'), 3 query.open, 1 query.close. Ingested: 1546 events on main stream. Projected: 16 runs (15 completed, 1 failed), 16 provider_turns, 308 main items + 70 child items = 378 (positions table matches 378, no collisions/dupes), 68 messages, 2 subagents (both completed, child threads linked). Coverage gap: 84 tool calls + 16 assistant texts in log with no projection (all in wakeup windows); 0 items stuck running/streaming."
},
{
"sessionKey":"ea84f015-cursor-handoff",
"summary":"Long mixed-provider session (13 claudeAgent runs, then a clean claudeAgent\u2192cursor provider handoff at run 14, then 3 failed cursor runs) with two claudeAgent subagent child threads. Core pipeline health is good: ordering/positions are perfectly consistent, no duplicates, no stuck non-terminal items/nodes/messages, sampled long assistant text survives un-truncated, and handoff lineage (context-transfer consumed \u2192 handoff ready \u2192 run 14, thread.provider-switched) is fully intact. The big defect is the known 'invisible post-turn turns' problem: three post-run wakeup turns (10 and 17 native turns' worth of tool calls, including a GitHub comment being posted) produced zero events and zero projections. Secondary issues: 529-Overloaded turns (runs 11-13) projected as completed despite native is_error:true, and cursor run failures persisted with only a generic 'Provider turn failed.' string.",
"stats":"Events: 6482 (main) + 165 + 255 (two subagent child threads). Items: 695 main + 34 + 52 child; positions table matches 695/695 with zero ordinal collisions, zero duplicate nativeItemRefs. Runs: 17 total \u2014 13 claudeAgent completed, 1 cursor completed (14), 3 cursor failed (15/16/17; 15 had a superseded steering_restart attempt). 2 subagents, both completed and linked to child threads. Tool-call coverage: cursor run 15 window 51/51 projected; claudeAgent era 529 native tool_use ids, all projected except 42 post-turn-wakeup calls (lost) and 2 Agent spawns (correctly represented as subagent items). Nodes: 751, all terminal. Errors seen natively: 3 is_error results (529 Overloaded), 1 error_during_execution, 1 model_refusal_fallback, 29 api_retry, 3 cursor run status:error."
},
{
"sessionKey":"c9e72a05-cursor-failing-turns",
"summary":"Two-run cursor session (composer-2.5, fastMode) where the user asked why cursor turns fail; run 1 completed a full debugging pass, run 2 hung silently for 440s and failed \u2014 reproducing the very bug being investigated. The ingestion/projection pipeline itself is in excellent health: all 123 native tool calls plus reasoning/assistant text project 1:1 with exact character counts (3664/3664 assistant, 3382/3382 thinking), ordering matches native emission exactly, positions table is consistent (150/150, 0 ordinal mismatches or dupes), lineage refs all resolve, no stuck states (run/attempt/turn/node all 'failed' for run 2, session 'stopped' after agent.close), and timestamps are monotonic. The one substantive problem is error-handling fidelity: the run 2 failure is projected only as failure {message:\"Provider turn failed.\", code:null}, because CursorAdapterV2 reads a non-existent result.error and never surfaces the Cursor SDK's real error_code (an authentication error), dropping even the requestId/durationMs present in the decoded payload.",
"summary":"Single-run Cursor (composer-2.5, fastMode) session: user asked to remove extra spacing on the mobile Threads/Home screen; the agent searched, read files, made 3 edits to HomeScreen.tsx, and summarized. The pipeline is essentially clean: every native item (33 tool calls, 10 thinking segments, 3 assistant messages, 1 user message) maps 1:1 to projected turn_items with exact content fidelity, ordinals are contiguous and match native emission order, all statuses reached terminal states, and no errors occurred in the native log. Only minor gaps found: token usage from the native turn-ended/run.completed is not ingested anywhere, and run_attempt.provider_turn_id is never backfilled.",
"summary":"Four sibling codex threads multiplexed onto the shared codex app-server session ('provider-session:provider-instance:codex:shared'). The missing native logs are explained: the codex protocol logger is bound to the threadId that opened the shared session (71e29ba5, whose own codex native thread is 019f1b50), so all four threads' traffic went to 71e29ba5's log file and was mostly rotated away by that thread's heavy claude traffic. Events-to-projections consistency is excellent: all 11 runs and provider turns terminal (10 completed, 1 user-interrupted with proper interrupt request/result items), zero lineage violations, zero ordinal collisions or duplicates, projection order matches native start order (verified against the surviving log window for c878541b runs 4-6), and message text verified byte-exact (1733/1733 chars). Only gaps: codex reasoning items (empty-content in this session) and one contextCompaction item are not projected at all.",
"summary":"Largest session in the store: the wakeup/blur dev thread, started on codex (runs 1-55), provider-switched to claudeAgent via a ready context handoff (runs 56-122), spawning 7 claude subagent child threads; still live during the audit (run 122 completed mid-audit at 17:13:36Z). In-run ingestion is very healthy: ordinals/positions are perfectly consistent across main + child threads with zero collisions or dangling lineage refs, projection order exactly matches native emission (run 121 verified item-by-item), no duplicates, no stuck items/turns/streaming messages, and all failed runs and user-interrupted subagents are surfaced with error/failed items. The two significant problems are both loss-of-data outside run windows: 76 completed claudeAgent tool calls plus assistant text from post-turn task_notification wakeup turns were never ingested (the known invisible-post-turn-turns bug this thread was used to develop the fix for \u2014 no provider_wakeup runs exist here), and a 30-minute codex-era ingestion gap (16:10-16:40 Jul 1) lost 119 command/fileChange items with only assistant text later backfilled at a single flattened timestamp.",
"stats":"Main thread: 14259 events (seq 13799-43607, still live during audit), 3390 projected turn_items (922 assistant_message, 1658 command_execution, 345 file_change, 144 dynamic_tool, 26 web_search, 7 subagent, 4 error, 169 user_message, 117 checkpoint, 1 handoff), 1091 messages, 122 runs = 122 provider_turns (117 completed / 4 failed / 1 cancelled, statuses exactly aligned). 7 subagent child threads (not 9): 79-260 events and 17-53 items each, 214 child items total. Native logs cover only 2026-07-01T16:00:59Z onward (~50k lines, 11 files; earlier rotations deleted). Claude era: 1130 native toolu ids vs 1045 projected (76 lost in wakeup gaps, 7 Agent-remapped, 2 in-flight). Codex era (in-log): 450 native call ids, 119 unprojected. 4 native error_during_execution, 2 orchestrator transport failures, 1 user cancel, 2 user-interrupted subagents."
}
],
"confirmed":[
{
"title":"Codex-native collab subagent (run 3) entirely missing from events and projections",
"category":"lost-data",
"severity":"high",
"confidence":"high",
"knownIssue":false,
"evidence":"User prompt run 3 was 'spawn a subagent'. Native log a5a643b2-...log shows: item/completed subAgentActivity call_9wPxyaS7ueh1MXl7XJt6zysq (kind 'started', agentThreadId 019f0c93-d260-7740-a477-0c0d19e8b299, agentPath /root/hello_agent) at 2026-06-28T04:54:02.530Z; collabAgentToolCall call_DO2fwaX8dQlHoNipTbnPWxIX (tool 'wait', inProgress 04:54:04.013Z -> completed 04:54:14.015Z); and on child native thread 019f0c93-d260: webSearch ws_08e14d73aa33777f016a40a8f75cd0819ba433374351c23d4f (query 'Codex OpenAI latest docs'), reasoning rs_08e14..., agentMessage msg_08e14d73aa33777f016a40a8fd816c819bbd856f295f6ce730 (text 'Hello.', completed 04:54:23, child turn 019f0c93-d421 completed 04:54:23.777Z -- AFTER parent run 3 finalized 04:54:15.874Z). SQL: 0 rows in orchestration_events for LIKE '%call_DO2fwaX8dQlHoNipTbnPWxIX%', '%call_9wPxyaS7ueh1MXl7XJt6zysq%', '%ws_08e14d73%', '%msg_08e14d73%', '%019f0c93-d260%'; orchestration_v2_projection_subagents has only the run-4 delegate-task row. Run 3 projected only user_message + 2 assistant messages + checkpoint; the parent assistant text ('Subagent spawned as /root/hello_agent. It hasn't returned within the short wait window yet.') is the only user-visible trace. Note: current CodexAdapterV2.ts (registerSubagentActivity/registerSubagentThreads, lines ~2815/2986; commits 3b864044c6 2026-06-28 'Adopt userdata-v2 and subagent activity mapping' and 57aa76ac14 2026-06-29) now maps these item types, so the session likely ran a pre-fix build -- but the historical data is unrecoverable and the child agent's post-run-completion output (arrived 8s after parent turn completed) remains a late-arrival hazard.",
"repro":"sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT COUNT(*) FROM orchestration_events WHERE payload_json LIKE '%call_DO2fwaX8dQlHoNipTbnPWxIX%' OR payload_json LIKE '%019f0c93-d260%'\" # returns 0; vs grep -c 'subAgentActivity\\|collabAgentToolCall' ~/.t3/userdata-v2/logs/provider/a5a643b2-6ca8-4250-9c54-ddefe7d55565.log",
"sessionKey":"a5a643b2-codex-heya",
"verdict":{
"isReal":true,
"adjustedSeverity":"medium",
"reasoning":"Every evidence point reproduces: the native log contains subAgentActivity call_9wPxyaS7ueh1MXl7XJt6zysq, collabAgentToolCall call_DO2fwaX8dQlHoNipTbnPWxIX, and 29 child-thread (019f0c93-d260) lines including agentMessage msg_08e14d73 (\"Hello.\") at 04:54:23.755Z, while orchestration_events and all projections return 0 rows for every identifier; run 3 projected only user_message + 2 assistant messages + checkpoint, and the subagents table has only the run-4 delegate-task row. The child output also arrived 8s after run 3's projected completed_at (04:54:15.874Z), matching the late-arrival claim. So the data loss is real and unrecoverable. Severity adjusted to medium because the session predates fix commit 3b864044c6 (2026-06-28 17:58 PDT, ~20h after the session) and current CodexAdapterV2.ts (lines 2815/2986-2998) now maps both item types, so recurrence for these types is addressed; only the historical loss and an unverified late-arrival hazard remain."
}
},
{
"title":"Backend child process fatally crashed twice on @cursor/sdk, killing run 1 mid-turn with no user-visible error",
"category":"error-handling",
"severity":"high",
"confidence":"high",
"knownIssue":false,
"evidence":"server-child.log (~/.t3/userdata-v2/logs/server-child.log): stderr fatal-error dump referencing 'file:///Applications/T3 Code (Alpha).app/.../node_modules/@cursor/sdk/dist/esm/index.js:1' at 2026-06-29T21:48:20.166Z (0.33s after native run.started run-9d9ff525-e89c-41e3-90e6-1f7e841cc188 at 21:48:19.834Z) and again at 21:49:09.455Z (followed by 'Node.js v24.15.0' crash footer). Server restart at 21:48:21.35 logged 'V2 orchestration recovery completed { terminalizedRuns: 1, stoppedSessions: 2 }'. Reconcile events seq 6294-6299 (command:runtime-reconcile:startup...21:48:21.501Z) set run:thread:721fc23c...:ordinal:1, its attempt, and provider-turn run-9d9ff525 to 'cancelled'. Run 1 has no error/cancelled turn item \u2014 user asked 'Hello therw!' and got only the 'Workspace ready' item; the cancellation is silent (run status is the only signal). No assistant content was lost in the log sense (crash preceded any deltas), but the turn was killed by a server bug, not a user cancel, and is projected indistinguishably from a user cancellation.",
"repro":"grep -n 'cursor/sdk\\|terminalizedRuns' ~/.t3/userdata-v2/logs/server-child.log ; sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT event_type,occurred_at FROM orchestration_events WHERE stream_id='721fc23c-2cf3-42bf-9d84-edd94359dca9' AND event_id LIKE '%runtime-reconcile%'\"",
"sessionKey":"721fc23c-cursor",
"verdict":{
"isReal":true,
"adjustedSeverity":"medium",
"reasoning":"Every cited artifact reproduces: the @cursor/sdk fatal stderr dump at 21:48:20.166Z (0.33s after native run.started run-9d9ff525), a second fatal crash at 21:49:09.455Z with Node.js footer and child exit code=1, the recovery log 'terminalizedRuns: 1, stoppedSessions: 2', reconcile events seq 6294-6299 setting run 1/attempt/node/provider-turn to 'cancelled', and no error or cancelled turn item on run 1 (only user_message + workspace item). ProviderRuntimeRecoveryService.ts intentionally marks interrupted runs 'cancelled' and never persists its 'server restarted' detail string user-visibly, so the crash-induced kill is projected identically to a user cancel with zero debuggable trace \u2014 a real gap, though the terminalization itself is designed behavior. Downgraded to medium because recovery worked cleanly (nothing stuck, no assistant content lost since the crash preceded any deltas), and the finding slightly overstates impact: run 2's failure WAS surfaced with a visible provider_error item; only run 1 died silently."
}
},
{
"title":"401 authentication failure recorded as fully successful run \u2014 is_error on SDK result ignored",
"category":"error-handling",
"severity":"high",
"confidence":"high",
"knownIssue":false,
"evidence":"Native log 2026-06-28T05:22:33.360Z: result payload has subtype:\"success\" but is_error:true, api_error_status:401, result:\"Failed to authenticate. API Error: 401 Invalid authentication credentials\", usage all zeros; preceded by two api_retry events (05:22:31.612Z, 05:22:32.312Z, error_status 401 authentication_failed). Projections: run run:...ordinal:1 status=completed (event seq 146, run.updated stream_version 27), run_attempt ...attempt:1 status=completed (seq 139), provider_turn ...attempt%3A1 status=completed (seq 138), assistant turn-item turn-item:provider:claudeAgent:native-item:03e7bb1c-2ee8-46a9-8bf2-f2b66c7501dc status=completed. No failure/error field anywhere in any payload_json; the only trace of the error is the synthetic assistant message text (which did survive verbatim, so it is user-visible as ordinary assistant text, not as an error state). Root cause: terminalStatusFromResult in /Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts:1652 returns \"completed\" whenever message.subtype === \"success\" and the failure branch at ~line 3254 only fires for non-success subtypes; is_error/api_error_status are never checked (only tool-result is_error at lines 1498-1500). An MCP delegate_task caller polling run status sees success for a task that never executed.",
"repro":"grep 'api_error_status' ~/.t3/userdata-v2/logs/provider/thread-delegated-task-command-3amcp-3a1156181e-e188-4fe4-8cc5-a294003ebfed-3adel.log ; sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT status FROM orchestration_v2_projection_runs WHERE thread_id LIKE '%1156181e%';\"",
"sessionKey":"1156181e-delegated-task",
"verdict":{
"isReal":true,
"adjustedSeverity":"high",
"reasoning":"Every evidence point reproduces: the native log at 2026-06-28T05:22:33.360Z shows a result with subtype \"success\" but is_error:true, api_error_status:401, zero usage, preceded by two api_retry 401 authentication_failed events (05:22:31.612Z, 05:22:32.312Z); projections show run (seq 146), run_attempt (seq 139), provider_turn (seq 138) and assistant turn-item 03e7bb1c-2ee8-46a9-8bf2-f2b66c7501dc all status=completed with no failure field in any payload_json. The code claim is accurate: terminalStatusFromResult (ClaudeAdapterV2.ts:1658) returns \"completed\" for any subtype===\"success\" and the failure branch at ~3254 only fires for non-success subtypes, while the SDK's SDKResultSuccess type explicitly exposes is_error and api_error_status (sdk.d.ts:2739-2740) \u2014 so this is an ignored error signal, not an SDK ambiguity or intentional design. Severity high stands because this thread is a delegated MCP task whose caller consumes run status programmatically; an auth failure that executed zero turns is reported as a fully successful run, with the only trace being ordinary assistant text."
}
},
{
"title":"Subagent live transcript and final output never projected to its child thread",
"category":"lost-data",
"severity":"high",
"confidence":"high",
"knownIssue":false,
"evidence":"Child thread 'thread:provider:grok:native-thread:019f1b5f-efdb-7da0-acd7-1a31b3fe00bc%3Atask%3Acall-cdbbacb3-0c58-4992-86ce-7b549ffb16ce-1' has only 8 events (sequences 14437-14451, last stream_version 7 at 2026-07-01T01:52:10.705Z) and 2 turn_items, both timestamped at spawn (01:52:10). Its assistant_message item 'turn-item:provider:grok:native-item:call-cdbbacb3-...-1%3Aresult' contains only the bootstrap text 'Subagent started in background... Use get_command_or_subagent_output ... to wait for results.' Yet the task actually ran 01:52:10Z-01:53:25Z with tool_calls=116 (per TaskOutput result in parent item turn-item:provider:grok:native-item:019f1b5f...%3Atool%3Acall-5ca8a4be-6fc8-4924-909c-b198de7dcbc8-2). Native log shows 811 decoded incoming ACP messages between 01:52:14 and 01:52:59 (gap between run 1 Interrupt at 01:52:13.249 and run 2 start at 01:52:59.9) with ZERO orchestration_events ingested for any session stream in that window \u2014 the subagent's streamed activity was dropped, likely because AcpAdapterV2's subagent context (context.subagents / subagentsBySessionId / pendingSubagentNotifications in /Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts ~line 559) is per-active-turn and turn 1 had already finalized. The 15,053-char final output is preserved un-truncated ONLY inside the parent's turn-2 dynamic_tool item; a user opening the child thread 'Explore codebase structure and architecture' sees none of the subagent's work.",
"repro":"sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT COUNT(*) FROM orchestration_events WHERE occurred_at>'2026-07-01T01:52:13.4' AND occurred_at<'2026-07-01T01:52:59' AND (stream_id LIKE '%5dcea72d%' OR stream_id LIKE 'thread:provider:grok:native-thread:019f1b5f%');\" -- returns 0, vs grep of the log showing 811 decoded incoming messages in the same window",
"sessionKey":"5dcea72d-grok-subagent",
"verdict":{
"isReal":true,
"adjustedSeverity":"medium",
"reasoning":"All evidence reproduces: child thread has only 8 spawn-time events (seq 14437-14451, all 01:52:10Z) and its result item contains only bootstrap text; 0 orchestration_events exist in the 01:52:13.4-01:52:59 gap despite continuous decoded incoming traffic in the log; run 1 prompt failed with errorTag Interrupt at 01:52:13.249Z and the subagent ran to 01:53:25Z (116 tool_calls per parent TaskOutput item). Code intent confirms this is a bug, not design: AcpAdapterV2's emitSubagentAssistant/projectSubagentNotification/pendingSubagentNotifications (lines 845-882, 1447-1461) are built to stream subagent text into the child thread, but the per-turn context's finalized guard plus run 2's empty subagentsBySessionId map dropped everything; the subagent projection row is also frozen at spawn (completed_at 01:52:10.702Z, result=bootstrap text). Downgraded to medium because the full 15,053-char final output is preserved un-truncated and user-visible in the parent's turn-2 dynamic_tool item, and even happy-path design only projects assistant text chunks (not tool calls) to the child thread \u2014 the loss is the child-thread transcript and an accurate subagent row, not the final answer."
"evidence":"Native log has 25 result messages but only 16 runs exist. 10 results have no corresponding run/message/item: 21:19:42 ('CodeRabbit's final pass came back clean'), 22:14:37, 22:19:27, 22:25:18, 22:32:25, 22:38:55 (review-fix 'Rounds 3-7' incl. real git pushes 'a3c87931a2', 'cb28a0842f', 'c435bec111', '57ca73e655', 'd851eb7b9c'), 23:12:04, 23:17:19, 23:32:05 ('Round 11 pushed c19ceca8a5'), 23:41:55 ('Converged. PR #3638 is fully green'). Diff of tool_use ids in log vs nativeItemRef in projections: 86 missing (84 after excluding 2 Agent ids that are represented as task-id subagent items) \u2014 all timestamped inside wakeup windows (21:19, 22:13-22:38, 22:59:24-32, 23:11:24-34, 23:16-23:23, 23:29-23:31, 23:41). 16 native assistant text messages missing (uuids incl. 6299b5cf-7941-4355-8063-eb9d60d7216f @21:19:41, d226f500-43a0-489e-a1bd-888747c56495 @22:38:54, 093e91b9-0d5b-4ad9-a7a9-2ef06c4c2021 @23:41:52). Zero orchestration_events on the stream between 22:10:30 and 22:48:00 except one provider-session.updated (stopped) at 22:41:50.039Z. No run/message has inputIntent provider_wakeup; all 16 user messages have creationSource=web. This is the documented 'invisible post-turn turns' issue diagnosed on this exact thread (fix implemented later on branch t3code/codex-turn-mapping); this session's data predates the fix.",
"repro":"SELECT COUNT(*) FROM orchestration_events WHERE stream_id='47763f5e-76c1-4d67-8037-442a280f1514' AND occurred_at>'2026-07-01T22:10:30' AND occurred_at<'2026-07-01T22:48:00'; -- =1 (session stop only), while the native log shows 5 full result turns in that window: grep '\"type\":\"result\"' ~/.t3/userdata-v2/logs/provider/47763f5e-76c1-4d67-8037-442a280f1514.log.1 | grep 'T22:[123]'",
"sessionKey":"47763f5e-claude-fable",
"verdict":{
"isReal":true,
"adjustedSeverity":"high",
"reasoning":"Every evidence point reproduces: 25 decoded result messages in the native log vs 16 projected runs, with the exact 10 cited orphan results unmatched by any run completed_at; the repro SQL returns 1 (only a provider-session stop at 22:41:50.039Z) for a window where the log shows 5 full turns; 86 top-level tool_use ids (371 in log vs 285 projected across all threads) are missing, all timestamped in the orphan-turn windows; cited assistant texts/uuids exist in the log but in zero projection rows; and no run/message carries provider_wakeup intent. This is real, substantial user-facing data loss (whole review-fix rounds with real git pushes invisible), matching the documented pre-fix \"invisible post-turn turns\" issue on this exact thread \u2014 known issue, but the lost session data is not backfilled by the fix, so high severity stands."
}
},
{
"title":"Invisible post-turn wakeup turns: 42 native tool calls + final assistant messages never ingested or projected",
"category":"lost-data",
"severity":"high",
"confidence":"high",
"knownIssue":true,
"evidence":"Three windows where the claudeAgent SDK kept working after the orchestrator closed the run: 23:31:27-23:36:48 (16 calls: Bash/Read/Edit/TaskCreate/TaskUpdate, after run 5 completed 23:30:07), 00:16:13-00:17:13 (9 calls, after run 6 completed 00:16:09), 00:33:32-00:37:24 (16 calls incl. mcp__t3-code__preview_* tools, after run 7 completed 00:33:22). Native results confirm full turns: [2026-07-02T00:17:51.602Z] subtype success num_turns:10 and [00:37:39.534Z] num_turns:17. Zero rows in orchestration_events for e.g. toolu_012dzkuS4eoKeRiAaQ3icFpD (Bash 00:17:05.797Z); zero main-stream events between 00:16:10 and 00:21:50. The wakeup turn's final assistant text 'Done \u2014 comment posted: https://github.com/pingdotgg/t3code/pull/2829#issuecomment-4861082710' (log.2, 00:17:4x) has 0 events and 0 turn_items \u2014 the agent posted a GitHub comment with no user-visible record. This is the diagnosed 'invisible post-turn turns' issue; the fix (turn.wakeup / ProviderWakeupService / attach_wakeup) is on this branch but this session ran on the pre-fix build (this thread is itself the diagnosis session, title 'check in on this thread: 47763f5e...').",
"repro":"sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT count(*) FROM orchestration_events WHERE payload_json LIKE '%toolu_012dzkuS4eoKeRiAaQ3icFpD%'\" -- returns 0; grep toolu_012dzkuS4eoKeRiAaQ3icFpD ~/.t3/userdata-v2/logs/provider/ea84f015-*.log.2 shows the Bash tool_use",
"sessionKey":"ea84f015-cursor-handoff",
"verdict":{
"isReal":true,
"adjustedSeverity":"high",
"reasoning":"Re-ran the full evidence trail: run 5/6/7 completion timestamps match, all 9 window-2 tool ids (e.g. toolu_012dzkuS4eoKeRiAaQ3icFpD) and 33 window-1/3 ids have zero rows in orchestration_events, zero main-stream events exist in all three gap windows, and the final assistant text with the posted GitHub comment URL (issuecomment-4861082710) has 0 events and 0 turn_items despite 4 native log occurrences with a success result (num_turns:10 at 00:17:51.602Z). Minor correction: 5 ids the finding attributed to window 1 belong to run 6 and were ingested, but the total lost count is still exactly 42. The session ran on the pre-fix build (the fix lives uncommitted on this branch), so whole turns including a real-world side effect were permanently lost with no user-visible record \u2014 real lost-data, correctly flagged as a known issue, severity stays high."
}
},
{
"title":"Cursor turn failure projected with only generic 'Provider turn failed.' \u2014 real error detail (auth error) never captured",
"category":"error-handling",
"severity":"high",
"confidence":"high",
"knownIssue":false,
"evidence":"Run 2 (native run-f4d64e64-0af6-42bc-8813-5b6ce53a328d) failed: native log line [2026-07-02T02:35:28.424Z] run.completed result {status:\"error\", requestId:\"beca30c7-7e90-481b-abf7-fdab84b3c48d\", durationMs:440732} \u2014 no error field in the decoded payload, and zero interaction.updates for the entire 440s turn (only run.started at 02:28:07.973Z then silence). Projected error item turn-item:provider:cursor:native-item:terminal-failure%3Aprovider-turn%3A...run-f4d64e64... (event seq 38493, occurred_at 2026-07-02T02:35:28.524Z) carries failure {class:\"provider_error\", message:\"Provider turn failed.\", code:null, retryable:null} \u2014 requestId and durationMs from the native payload are dropped too. Cause: CursorAdapterV2.ts:2165-2168 maps `cause: (result as { readonly error?: unknown }).error` which is undefined on the SDK RunResult, falling back to DEFAULT_PROVIDER_FAILURE_MESSAGE. The session's own in-turn diagnosis (final assistant item ...assistant%3Arun-1cbebefe...%3A5) confirmed the real cause lives only in the Cursor SDK store runs.error_code (\"Authentication error If you are logged in, try logging out and back in.\") which T3 never reads. The failure IS surfaced user-visibly (error item status failed, run/attempt/provider-turn all 'failed'), but with zero debuggable detail \u2014 this exact gap forced the user to spawn this debugging thread, and then recurred on the thread itself (run ordinal 2).",
"repro":"sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT json_extract(payload_json,'$.failure') FROM orchestration_v2_projection_turn_items WHERE thread_id='c9e72a05-4c87-4dd5-b1b6-83834cc73afe' AND type='error';\" ; grep 'run.completed' ~/.t3/userdata-v2/logs/provider/c9e72a05-4c87-4dd5-b1b6-83834cc73afe.log | tail -1",
"sessionKey":"c9e72a05-cursor-failing-turns",
"verdict":{
"isReal":true,
"adjustedSeverity":"high",
"reasoning":"Fully reproduced: the projected error item for run-f4d64e64 carries only {\"message\":\"Provider turn failed.\",\"code\":null}, while the native log's run.completed (02:35:28.424Z, status \"error\", requestId beca30c7, durationMs 440732) confirms no detail was captured and requestId/durationMs were dropped. The cited code (CursorAdapterV2.ts:2165-2168) reads (result as {error?: unknown}).error, but @cursor/[email protected]'s RunResult type has no error field whatsoever \u2014 the fallback is guaranteed dead-code behavior for EVERY failed Cursor turn, and the SDK's public store API does expose RunRecord.errorCode (\"Authentication error...\") which T3 never reads. The failure is surfaced user-visibly with correct terminal states (so nothing is swallowed), but the projection retains zero debuggable detail for a systematic, provider-wide failure path, which matches the audit's explicit error-handling criterion; severity high stands."
}
},
{
"title":"Shared codex session native logs written to opener thread's file, not the active thread's \u2014 no log file ever created for these threads",
"category":"other",
"severity":"high",
"confidence":"high",
"knownIssue":false,
"evidence":"All four threads bind provider_session_id 'provider-session:provider-instance:codex:shared'. Their codex app-server protocol traffic appears in 71e29ba5-654b-4f67-b363-ad400e5bd016.log.6/.9/.10 (e.g. 019f1b62-f532 = c878541b's nativeThreadRef: 4768 hits in .log.10, 2828 in .log.9), interleaved with that thread's own claudeAgent and codex (019f1b50-4248) traffic. Cause: in /Users/julius/.t3/worktrees/codething-mvp/t3code-c1e5e1d1/apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts, codexAppServerClientFactoryFromSettingsLayer.open builds makeCodexAppServerProtocolLogger({ nativeEventLogger, threadId: input.threadId, ... }) once per app-server process; EventNdjsonLogger.write routes to `${threadSegment}.log` from that frozen threadId, so every thread multiplexed onto the shared session logs under the opener's file. No file named c878541b-*/de5f191a-*/68f7595b-*/af66fc2c-* was ever created.",
"repro":"grep -l '019f1b62-f532' ~/.t3/userdata-v2/logs/provider/*.log* # hits only 71e29ba5-654b-...log.{6,9,10}, never a file named after the audited threads",
"sessionKey":"codex-no-native-logs",
"verdict":{
"isReal":true,
"adjustedSeverity":"medium",
"reasoning":"Fully reproduced: all four threads bind provider-session:provider-instance:codex:shared; c878541b's nativeThreadRef 019f1b62-f532 appears exactly 4768x in 71e29ba5.log.10 and 2828x in .log.9 (interleaved with 71e29ba5's own codex ref 019f1b50-4248), and no log file named after any of the four threads exists. Code confirms the cause: CodexAdapterV2.ts line 1136 freezes input.threadId into makeCodexAppServerProtocolLogger at app-server open, so every multiplexed thread's protocol traffic routes to the opener's `${threadSegment}.log` \u2014 defeating EventNdjsonLogger's per-write threadId routing, so this is a misrouting bug, not intent. Downgraded to medium because ingestion/projections for these threads are intact (observability-only defect), though rotation under the busy opener file has permanently deleted 3 of 4 threads' protocol history."
}
},
{
"title":"Invisible post-turn wakeup turns (claudeAgent): 76 completed tool calls + assistant text never ingested or projected",
"category":"lost-data",
"severity":"high",
"confidence":"high",
"knownIssue":true,
"evidence":"1130 unique toolu_ ids in decoded native logs vs 1045 projected nativeItemRef ids. Of the 85 unmatched, 7 are Agent spawns (projected under task:<hash>:subagent ids, fine) and 2 are stream-only in-flight blocks; the remaining 76 (60 Bash, 7 Edit, 5 Read, 4 ScheduleWakeup) ALL fall in gaps between run windows \u2014 0 fall inside any run. Example: run 56 completed 2026-07-01T22:18:57.958Z (result subtype=success 22:18:57.333Z); at 22:20:52.374Z 'system task_notification bk7bmoyti' re-woke the session, assistant emitted text 'The build failed \u2014 let me see the actual error.' (22:20:58.275Z) then Bash toolu_011YH7oQm6yGVjWTfxwQ1QsH (22:20:59, tool_result 22:21:00) etc. \u2014 none exist in orchestration_events or turn_items (LIKE search for that text returns 0). This thread has ZERO wakeup runs/messages (0 messages with inputIntent provider_wakeup / creationSource other than agent|provider,user|web), while 367 provider_wakeup events exist elsewhere in the DB (first at 2026-07-01T22:47:41) \u2014 this is the thread on which the fix was being developed (memory: diagnosed 2026-07-01 on threads 47763f5e & 71e29ba5).",
"repro":"comm -23 /tmp/native_toolu.txt /tmp/proj_toolu.txt (native ids from grep -h '\"stage\":\"decoded\"' ~/.t3/userdata-v2/logs/provider/71e29ba5-654b-4f67-b363-ad400e5bd016.log* | grep -o 'toolu_[A-Za-z0-9]*' vs SELECT json_extract(payload_json,'$.nativeItemRef.nativeId') FROM orchestration_v2_projection_turn_items WHERE thread_id LIKE '%71e29ba5%')",
"sessionKey":"71e29ba5-claude-mega",
"verdict":{
"isReal":true,
"adjustedSeverity":"high",
"reasoning":"Re-ran the full evidence trail: 85 genuine claudeAgent tool_use ids in decoded native logs have no projection; after excluding 7 Agent spawns (verified projected as task:<hash> items) and 2 stream-only in-flight blocks, exactly 76 completed tool calls (60 Bash, 7 Edit, 5 Read, 4 ScheduleWakeup) all fall in gaps between run windows (0 inside any of the 127 runs). The cited example reproduces: assistant text 'The build failed...' at 2026-07-01T22:20:58.275Z between run 56 (ended 22:18:57.958Z) and run 57 (started 22:22:38.734Z), with 0 matching rows in orchestration_events; the thread has 0 provider_wakeup events/messages while 367 exist elsewhere. This is the documented known issue the branch fixes, but for this session the provider-emitted tool calls, results, and assistant text are unrecoverably absent from ingestion and projections, with losses continuing into 2026-07-02 \u2014 real high-severity lost data, correctly flagged knownIssue=true."
}
},
{
"title":"Provider failures persist only generic error strings; underlying cause is unrecoverable from the DB",
"category":"error-handling",
"severity":"medium",
"confidence":"high",
"knownIssue":false,
"evidence":"4 claudeAgent error items say only 'Claude Agent SDK query failed.' (class transport_error, code null) \u2014 e.g. run:thread:47763f5e-76c1-4d67-8037-442a280f1514:ordinal:10 failed 2026-07-01T22:48:38 with zero native-log traffic in that minute, so the real exception exists nowhere. Root cause: ClaudeAgentSdkQueryRunnerError.message getter in apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts:280 hardcodes the string and discards `cause`. Similarly 4 cursor items say 'Provider turn failed.' (code null) while the native run.completed carried status:'error' plus requestId d1cd7f44-91fb-45ce-bdd3-86e9b5cc8e3e and durationMs 2434335 that were dropped. Counter-example showing it can be done right: codex errors keep full detail ('stream disconnected before completion: error sending request for url (https://chatgpt.com/backend-api/codex/responses)' and the full 400 invalid_request_error body for gpt-5.3-codex).",
"repro":"sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT thread_id, json_extract(payload_json,'$.failure.message') FROM orchestration_v2_projection_turn_items WHERE type='error';\"",
"sessionKey":"GLOBAL",
"verdict":{
"isReal":true,
"adjustedSeverity":"medium",
"reasoning":"Reproduced the SQL: all 4 claudeAgent error items persist only 'Claude Agent SDK query failed.' (code/retryable null) and no richer detail exists in any orchestration_events row for those failures; the root cause is confirmed at ClaudeAdapterV2.ts:279-281 where the message getter hardcodes the string while the Schema.Defect cause field is discarded by makeProviderFailure (real exception goes only to Effect.logWarning). This is not intentional: ProviderFailure.ts has redaction/4096-char bounding built to persist real error text, and codex failures do persist full detail. Minor correction: the '47763f5e had zero native-log traffic at 22:48' claim is false (8 lines exist in .log.1, outgoing query.open/prompt.offer at 22:48:38.086), and the cursor generic message is partly upstream (native run.completed carried no error message, only requestId d1cd7f44/durationMs which were dropped) \u2014 but the core finding stands, so severity stays medium."
}
},
{
"title":"Delegated Claude task failed with 401 auth error but all statuses say 'completed' (is_error ignored on success-subtype result)",
"category":"error-handling",
"severity":"medium",
"confidence":"high",
"knownIssue":false,
"evidence":"Child native log thread-delegated-task-command-3amcp-3a1156181e-...log (2026-06-28T05:22:33Z) shows SDK result {\"type\":\"result\",\"subtype\":\"success\",\"is_error\":true,\"result\":\"Failed to authenticate. API Error: 401 Invalid authentication credentials\"}. Projections: child run run:thread:thread%3Adelegated-task%3Acommand%253Amcp%253A1156181e-...:ordinal:1 status=completed; provider_turn status=completed; subagent row node:delegated-task:command%3Amcp%3A1156181e-...%3Ahello-opus-48 status='completed' with result='Failed to authenticate...'; delegate_task tool item call_qV0wnlB5N6Osa6CPxTGN1Ajh output.status='completed'. Root cause in current code: ClaudeAdapterV2.ts terminalStatusFromResult (~line 1658) returns 'completed' whenever message.subtype==='success' without checking is_error, and the result handler (~line 3254) only attaches a ProviderFailure when subtype!=='success'. Mitigating: the error text IS preserved and user-visible (child assistant item 03e7bb1c-2ee8-46a9-8bf2-f2b66c7501dc text = the 401 message; parent's final assistant message msg_...9bb460 explains the failure), so nothing was swallowed -- but status semantics are wrong for anything filtering on failed tasks.",
"repro":"sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT status, json_extract(payload_json,'$.result') FROM orchestration_v2_projection_subagents WHERE subagent_id LIKE '%hello-opus-48%'\" # completed | Failed to authenticate. API Error: 401 ...",
"sessionKey":"a5a643b2-codex-heya",
"verdict":{
"isReal":true,
"adjustedSeverity":"medium",
"reasoning":"Re-ran every evidence step: the child native log shows SDK result subtype=\"success\" with is_error=true and api_error_status=401 (zero tokens, \"Failed to authenticate. API Error: 401...\"), yet the child run, provider_turn, subagent row, and the parent's delegate_task item (call_qV0wnlB5N6Osa6CPxTGN1Ajh, output.status=\"completed\") all report completed. Source confirms the cause: ClaudeAdapterV2.ts terminalStatusFromResult (line 1658) returns \"completed\" on subtype===\"success\" without checking is_error, and the result handler (lines 3250-3263) only attaches a ProviderFailure when subtype!==\"success\" \u2014 is_error is checked only for tool results, so this is an oversight, not intent. Medium stands: the error text is preserved and user-visible, but status semantics are wrong end-to-end for anything filtering on failed delegated tasks."
}
},
{
"title":"Streaming deltas persisted as full-row event pairs cause ~2800x event amplification on child result items",
"category":"other",
"severity":"medium",
"confidence":"high",
"knownIssue":false,
"evidence":"Child thread ...composer_call_kFjs8 accumulated 2711 events (1352 turn-item.updated + 1352 message.updated + overhead) to stream a single 6274-char result; the 3 children total 5702 turn-item/message events for ~12.6KB of final text. This one 2-minute session wrote 6017 rows to orchestration_events (43k total table), i.e. each streaming delta is persisted as a full-row upsert event for both the turn item and its message. Not a correctness bug (final projections are correct) but a storage/replay-cost anomaly.",
"repro":"sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT event_type, COUNT(*) FROM orchestration_events WHERE stream_id LIKE 'thread:provider:grok:native-thread:019f1558%' GROUP BY 1;\"",
"sessionKey":"20296b49-grok-tasks",
"verdict":{
"isReal":true,
"adjustedSeverity":"medium",
"reasoning":"Evidence reproduces exactly: 1352 turn-item.updated + 1352 message.updated events on the single kFjs8 result item with monotonically growing text (4 -> 6274 chars, sequences 2160-4862), and the session totals exactly 6017 event rows. Code confirms the mechanism: AcpAdapterV2.emitSubagentAssistant emits a full-row message+turn-item event pair per agent_message_chunk and ProviderEventIngestor persists each pair durably with no coalescing, throttling, or event-log pruning (ProjectionMaintenance only rebuilds projections by replaying the full log). Quantified: 18.0 MB of payload_json for ~12.6 KB of final subagent text (~1400x, quadratic in output length), 15.5% of the entire event table from one 2-minute session. Final projections are correct so severity stays medium, but the unbounded quadratic storage/replay cost is a real, unmitigated pipeline anomaly, not intended behavior or a misreading."
}
},
{
"title":"Run 2 failure projected with generic wrapper message; actual cause dropped from projection and depth-elided in server log",
"category":"error-handling",
"severity":"medium",
"confidence":"high",
"knownIssue":false,
"evidence":"Error turn item turn-item:provider:cursor:native-item:terminal-failure%3Aprovider-turn%3A...ordinal%25253A2... (ordinal 2000002, status failed, 21:48:40.703Z) persists failure = {class:'provider_error', message:'Failed to start run run:thread:721fc23c-2cf3-42bf-9d84-edd94359dca9:ordinal:2 on cursor provider thread provider-thread:provider:cursor:native-thread:pending%3A...', code:null, retryable:null}. That string is ProviderAdapterTurnStartError's message getter (apps/server/src/orchestration-v2/ProviderAdapter.ts:291); RunExecutionService.ts:830 builds the failure via makeProviderFailure({cause: Cause.squash(cause)}) so the tagged error's wrapped `cause` (the real agent.send rejection from CursorAgentSdk runnerError 'run.start') never reaches the projection. The only other record, server-child.log line 89 at 21:48:40.703Z, printed the cause as \"{ _id: 'Cause', failures: [ [Object] ] }\" \u2014 depth-elided. The underlying reason run 2 failed 4ms after run.start is now unrecoverable. Positive: the failure WAS surfaced user-visibly as an error item and run/attempt/node all show 'failed'.",
"repro":"sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT payload_json FROM orchestration_v2_projection_turn_items WHERE thread_id='721fc23c-2cf3-42bf-9d84-edd94359dca9' AND type='error'\" ; grep -n '721fc23c' ~/.t3/userdata-v2/logs/server-child.log",
"sessionKey":"721fc23c-cursor",
"verdict":{
"isReal":true,
"adjustedSeverity":"medium",
"reasoning":"All cited evidence reproduces: the projected error item and its source event (orchestration_events sequence 6314) both persist only ProviderAdapterTurnStartError's generic message getter (ProviderAdapter.ts:280-293); RunExecutionService.ts:~831 feeds Cause.squash(cause) into makeProviderFailure, which (ProviderFailure.ts:90-113) reads only .message/.code and never unwraps the nested cause defect that CursorAdapterV2.ts:2203 attaches. server-child.log line 89 depth-elides the cause as \"[ [Object] ]\" and the native provider log ends at the outgoing run.start (21:48:40.699Z) with no error event, so the real reason run 2 failed is unrecoverable from any persisted artifact. The failure was surfaced user-visibly with correct terminal statuses, so medium (not high) is the honest severity \u2014 this is a debuggability gap, not silent loss."
}
},
{
"title":"Native provider log never records failure frames \u2014 cursor SDK send errors and process death are invisible in the ground-truth log",
"category":"other",
"severity":"medium",
"confidence":"high",
"knownIssue":false,
"evidence":"Native log 721fc23c-2cf3-42bf-9d84-edd94359dca9.log ends at [2026-06-29T21:48:40.699Z] with outgoing run.start 'what did you just say' and no incoming frame, though the turn failed at 21:48:40.703Z. In Adapters/CursorAgentSdk.ts send(), the log writes cover outgoing run.start and incoming run.started/interaction.update/run.completed only; when agent.send rejects, Effect.tryPromise raises runnerError(cause,'run.start') with no protocol log write. Similarly run 1 shows run.started at 21:48:19.834Z and then nothing \u2014 no error, no lifecycle/exit record \u2014 because the process crash killed the logger too. Result: the 'ground truth' log cannot explain either failed turn, which is exactly why this session looked suspicious (7 lines vs 47 events).",
"reasoning":"Evidence reproduces fully: the native log ends at 21:48:40.699Z with the outgoing run.start and no failure frame while events 6313-6315 record the run failing at 21:48:40.703Z, and CursorAgentSdk.ts's error paths (runnerError catches at lines 408/440; run.completed logged via success-only Effect.tap) confirm no error-frame logging exists \u2014 indeed no adapter has an error/lifecycle log kind at all. However, the pipeline did not swallow anything: the failure was ingested and user-surfaced as turn-item 6314 (type error, status failed) with correct terminal statuses, and the raw cause is logged to the server application log (CursorAdapterV2.ts:2188 logWarning with cause), so this is an observability gap in the debug/protocol log (compounded by the generic projected message with code:null) rather than a data-loss or projection bug. Run 1's \"process crash\" explanation is unproven (DB shows cancelled, lastError null), so I downgrade to low: real, design-wide log-scope limitation worth fixing, but errors remain debuggable and user-visible through other channels."
}
},
{
"title":"Failed tool item drops the provider error message (file_search projection has no error/output field)",
"category":"error-handling",
"severity":"medium",
"confidence":"high",
"knownIssue":false,
"evidence":"Child thread ses_0ea978228: turn-item:provider:opencode:native-item:prt_f15692f30001qL66As1xsUCQXc (ordinal 87) went running->failed at 2026-06-29T22:04:02.915Z (events seq 8284 -> 8286 on stream thread:provider:opencode:native-thread:ses_0ea978228ffeVM6qpFUgGn62Vl). Final payload contains only {status:'failed', type:'file_search', pattern:'/Users/julius/Development/Work/codething-mvp/CLAUDE.md'} \u2014 no error text at all. Root cause in OpenCodeAdapterV2.ts: toolOutput() (line 659) returns part.state.error for status 'error', but the file_search branch (~line 1376) only maps 'pattern'; output/error is only attached for dynamic_tool. The contract (packages/contracts/src/orchestrationV2.ts line 841) also has no output/error field on file_search items, so the failure reason is unrecoverable from projections. Failure IS user-visible via status=failed, but not debuggable.",
"repro":"sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT payload_json FROM orchestration_v2_projection_turn_items WHERE turn_item_id='turn-item:provider:opencode:native-item:prt_f15692f30001qL66As1xsUCQXc';\"",
"sessionKey":"3029dc85-opencode",
"verdict":{
"isReal":true,
"adjustedSeverity":"medium",
"reasoning":"Reproduced the exact projection payload (failed file_search item prt_f15692f30001qL66As1xsUCQXc, ordinal 87, no error text) and the running->failed transition at events seq 8284->8286. Source confirms the mechanism: OpenCodeAdapterV2.ts toolOutput() (line 659) extracts part.state.error, but the file_search branch (lines 1376-1383) only maps pattern \u2014 output/error is attached only for command_execution/dynamic_tool \u2014 and the contract's file_search schema (orchestrationV2.ts line 841) has no field to hold it. The native log is additionally redacted (protocol payloads logged as fieldCount summaries only), so the error message is unrecoverable anywhere; failure is visible via status=failed but not debuggable, so medium stands."
}
},
{
"title":"Claude assistant text segments merged without separator into a single end-of-turn item, losing interleaving",
"category":"lost-data",
"severity":"medium",
"confidence":"high",
"knownIssue":false,
"evidence":"Thread :2 native log has 5 assistant text blocks with distinct SDK uuids (341420a1 len 95 @22:09:54, 78f308a1 len 37 @22:09:58, 26b0aa8d len 90 @22:10:11, 31c4bfa0 len 73 @22:11:40, bfa7a134 len 10347 @22:13:07), interleaved with 19 tool calls. Projection has ONE assistant_message item turn-item:provider:claudeAgent:native-item:bfa7a134-04d5-4434-bb14-66927497fb91, ordinal 1000021 (after all tools), text length 10642 = exact sum, joined with no whitespace: '...read all the files thoroughly.I'll read all files in the directory.Let me gather context...'. The 4 intermediate uuids have ZERO orchestration_events (only seq 11544-11546 reference bfa7a134, all at 22:13:07). Root cause in code that ran (git fc23be8184 ClaudeAdapterV2.ts:2815): `context.assistant.text += assistantText.text` with single emission at result time; current worktree code (emitAssistantTextArtifacts per message.uuid) already emits per-segment items, so this appears fixed for future runs.",
"repro":"sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT substr(json_extract(payload_json,'$.text'),80,150) FROM orchestration_v2_projection_turn_items WHERE thread_id LIKE '%126456a2%:2' AND type='assistant_message';\"",
"sessionKey":"6d618dc4-mcp-group",
"verdict":{
"isReal":true,
"adjustedSeverity":"low",
"reasoning":"Reproduced every claim: native log has 5 assistant text blocks (lens 95/37/90/73/10347 at 22:09:54\u201322:13:07) but the projection has one assistant_message item (native ref bfa7a134, ordinal 1000021 after all 19 tools) of length 10642 = exact sum, joined with no separator (\"thoroughly.I'll read all files in the directory.Let me gather context\"); the 4 intermediate uuids have zero orchestration_events while bfa7a134 has seq 11544\u201311547. Historical code (fc23be8184 ClaudeAdapterV2.ts:2815 `context.assistant.text +=`) caused it; current worktree emitAssistantTextArtifacts emits per-nativeItemId, so it is fixed going forward. Real for this session's data, but downgraded to low because no text content was lost (only interleaving/segmentation) and the fix already landed."
}
},
{
"title":"Subagent projection marked completed at spawn with placeholder result (lifecycle wrong by ~75s)",
"category":"other",
"severity":"medium",
"confidence":"high",
"knownIssue":false,
"evidence":"orchestration_v2_projection_subagents row 'node:provider:grok:native-item:call-cdbbacb3-0c58-4992-86ce-7b549ffb16ce-1' has status=completed, started_at=2026-07-01T01:52:10.677Z, completed_at=2026-07-01T01:52:10.702Z and result='Subagent started in background...\\nUse get_command_or_subagent_output...' \u2014 but the task's real lifetime was 01:52:10Z to 01:53:25Z (duration_secs 74.874 per the TaskOutput payload). The parent 'subagent' turn_item (ordinal 1000007) mirrors the same premature completedAt and placeholder result. Cause visible in AcpAdapterV2.emitSubagent (~lines 1047-1060): when the spawn tool returns 'started in background', taskStatus is non-running and update.result (the bootstrap text) is adopted as assistantText/result; nothing later updates it when the background task actually finishes.",
"repro":"sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT status, completed_at, substr(json_extract(payload_json,'$.result'),1,60) FROM orchestration_v2_projection_subagents WHERE thread_id='5dcea72d-15e1-4ded-922b-0b00c587de6c';\"",
"sessionKey":"5dcea72d-grok-subagent",
"verdict":{
"isReal":true,
"adjustedSeverity":"medium",
"reasoning":"Reproduced end-to-end: projection row 'node:provider:grok:native-item:call-cdbbacb3-...-1' has status=completed, completed_at=2026-07-01T01:52:10.702Z with result='Subagent started in background...' while the TaskOutput payload (event seq 14622, 01:53:28.477Z, item call-5ca8a4be-...) shows the task actually ran 01:52:10Z-01:53:25Z (duration_secs 74.874); only 3 subagent.updated events exist, all at spawn time, so nothing ever corrects it. Code confirms the cause: extractXAiAcpSubagentUpdate (XAiAcpExtension.ts:86-91) maps the spawn tool's completed status straight to subagent status with no background-spawn detection, and AcpAdapterV2.ts:1047-1053 adopts the bootstrap text as assistantText/result; the later TaskOutput tool call is projected as an unrelated dynamic_tool item and never routed back to the subagent, and the child thread's only assistant message is also the placeholder. Severity stays medium: the real 15.5KB output survives user-visibly in the separate dynamic_tool item, but the subagent card's lifecycle, result, and child-thread transcript are wrong, and this Grok/ACP path is not covered by the claudeAgent backgrounded-task known issue."
}
},
{
"title":"Run 10 terminal failure persisted with only a generic error message",
"category":"error-handling",
"severity":"medium",
"confidence":"high",
"knownIssue":false,
"evidence":"Run run:thread:7f1dfff1-...:ordinal:10 failed at 2026-07-01T20:47:58.607Z. The projected error item (turn-item:provider:claudeAgent:native-item:terminal-failure%3A...ordinal%25253A10..., event seq 25810) has failure {class:\"transport_error\", message:\"Claude Agent SDK query failed.\", code:null, retryable:null}. run-attempt payload (seq 25811) carries no error detail either. Native log ends at 20:47:58.429Z with outgoing query.open + prompt.offer (user text \".\") and zero incoming SDK messages, so the DB retains no clue what actually failed. Root cause in code: ClaudeAdapterV2.ts:279-280 \u2014 ClaudeAgentSdkQueryRunnerError.message hardcodes \"Claude Agent SDK query failed.\" and the underlying `cause` defect is never propagated into the projected failure. The failure IS user-visible (error item + run failed), but is undebuggable after the fact.",
"repro":"sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT json_extract(payload_json,'$.failure') FROM orchestration_v2_projection_turn_items WHERE thread_id='7f1dfff1-4cbb-450b-8514-764d11c903e1' AND type='error';\"",
"sessionKey":"7f1dfff1-claude-scheduled-tasks",
"verdict":{
"isReal":true,
"adjustedSeverity":"medium",
"reasoning":"Re-ran the repro: the error turn-item (event seq 25810) and run-attempt (seq 25811) for run ordinal 10 persist only {class:\"transport_error\", message:\"Claude Agent SDK query failed.\", code:null}, and the native log truly ends at 20:47:58.429Z with outgoing query.open/prompt.offer and no incoming SDK data, so no error detail exists anywhere in DB or provider log. Code confirms the mechanism: ClaudeAgentSdkQueryRunnerError.message is hardcoded at ClaudeAdapterV2.ts:279-280 and makeProviderFailure (ProviderFailure.ts:97-100) reads exactly that getter, dropping the Schema.Defect cause; the real cause only reaches an ephemeral Effect.logWarning. Other adapters (e.g. OpenCodeAdapterV2.ts:2202) propagate real detail, so this is an unintended gap, not design \u2014 finding stands at medium since the failure is user-visible but undebuggable after the fact."
}
},
{
"title":"401 authentication error result projected as successful run + plain assistant message",
"category":"error-handling",
"severity":"medium",
"confidence":"high",
"knownIssue":false,
"evidence":"Native result at 2026-07-01T20:56:54.878Z has is_error=true with result 'Failed to authenticate. API Error: 401 Invalid authentication credentials'. Run run:thread:47763f5e-...:ordinal:1 is projected status='completed' (completed_at 20:56:54.916Z) and its provider_turn completed. The error text is user-visible only as a normal assistant_message (turn-item:provider:claudeAgent:native-item:94ed662f-814a-43d7-aad3-92e479b9dfe8, status=completed, type=assistant_message) \u2014 no error item, no failed status, so the run reads as a success.",
"repro":"sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT status FROM orchestration_v2_projection_runs WHERE run_id='run:thread:47763f5e-76c1-4d67-8037-442a280f1514:ordinal:1';\" vs grep -m1 '\"type\":\"result\"' ~/.t3/userdata-v2/logs/provider/47763f5e-76c1-4d67-8037-442a280f1514.log.1 (is_error:true)",
"sessionKey":"47763f5e-claude-fable",
"verdict":{
"isReal":true,
"adjustedSeverity":"medium",
"reasoning":"Reproduced fully: native result at 20:56:54.878Z has subtype \"success\" with is_error:true and api_error_status:401, yet run ordinal:1 and its provider_turn are projected status=completed, and the error text survives only as a plain completed assistant_message item (94ed662f, itself the SDK's synthetic \"<synthetic>\"-model assistant message). Code confirms this is a gap, not intent: terminalStatusFromResult in ClaudeAdapterV2.ts only inspects message.subtype and the failure payload is attached only for non-\"success\" subtypes; is_error/api_error_status on result messages are never checked. The error text is user-visible via the SDK's synthetic message, but the run's structured status misreports failure as success and the 401 detail is not persisted, so medium severity stands."
}
},
{
"title":"Run 10 failure persisted with generic message only \u2014 no root cause anywhere",
"category":"error-handling",
"severity":"medium",
"confidence":"high",
"knownIssue":false,
"evidence":"Run ordinal:10 failed in 0.5s (requested 22:48:37.674Z, completed 22:48:38.293Z). The only error record is the error turn-item terminal-failure...ordinal%25253A10 with failure {class:'transport_error', message:'Claude Agent SDK query failed.', code:null, retryable:null}. The native log contains no error detail either \u2014 line 6324 (.log.1) shows the outgoing query.open at 22:48:38.086Z using create-style param sessionId:'b896a082-a480-416f-8ffd-c42845e71993' (after the session was closed at 22:41:50), then nothing incoming; the retry run 11 at 22:48:55.300Z used resume:'b896a082...' and succeeded. The actual SDK failure reason was never captured, and the failed open plausibly stems from reopening with sessionId instead of resume. Related: the query.close at 22:41:50 came ~31.8 min after run 9 completed (22:10:01) despite native wakeup activity through 22:38:55 \u2014 consistent with the known idle-session-reaper-vs-wakeup issue.",
"repro":"sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT json_extract(payload_json,'$.failure') FROM orchestration_v2_projection_turn_items WHERE thread_id='47763f5e-76c1-4d67-8037-442a280f1514' AND type='error';\" and sed -n '6323,6327p' ~/.t3/userdata-v2/logs/provider/47763f5e-76c1-4d67-8037-442a280f1514.log.1",
"sessionKey":"47763f5e-claude-fable",
"verdict":{
"isReal":true,
"adjustedSeverity":"medium",
"reasoning":"Fully reproduced: run ordinal:10 failed in ~0.6s and the only persisted failure anywhere (turn-item event seq 29464) is the generic {class:transport_error, message:'Claude Agent SDK query failed.'}; the native log (.log.1 lines 6324-6325) shows query.open at 22:48:38.086Z with create-style sessionId after the 22:41:50 query.close, no incoming lines, then a successful resume-based retry at 22:48:55. The genericness is by construction: ClaudeAgentSdkQueryRunnerError (ClaudeAdapterV2.ts:279-281) hardcodes its .message getter, defeating makeProviderFailure's cause.message extraction (ProviderFailure.ts), whose redaction/4096-char bounding shows real messages were intended to flow through. Even the fallback Effect.logWarning (server-child.log:457) collapsed the cause to '[Object]', so the root cause is unrecoverable from every persisted artifact \u2014 a real error-handling gap, though user-visibly surfaced and recovered by retry, so medium stands."
}
},
{
"title":"Runs 11-13 projected as 'completed' although native result had is_error:true (API 529 Overloaded)",
"category":"error-handling",
"severity":"medium",
"confidence":"high",
"knownIssue":false,
"evidence":"Native results in log.2: [2026-07-02T00:51:30.884Z], [00:55:19.085Z], [01:00:28.143Z] all 'subtype':'success','is_error':true,'num_turns':1 (preceded by 29 api_retry 'overloaded' events and one model_refusal_fallback at 00:51:30.857Z). Projections: runs ordinal 11/12/13 status 'completed', provider_turns 'completed'. The only user-visible signal is that the SDK emitted the error text as an assistant message (turn-item:provider:claudeAgent:native-item:9c0cead6-f253-44c8-8cc7-3c95b58a326e, run 13, text 'API Error: 529 Overloaded...'; run 11 item text 'API Error: Overloaded'). Run/attempt/turn statuses do not reflect the failure, so downstream logic treating these runs as successful is wrong.",
"repro":"sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT run_id,status FROM orchestration_v2_projection_runs WHERE run_id LIKE '%ea84f015%ordinal:1_' \" vs grep '\"is_error\":true' ~/.t3/userdata-v2/logs/provider/ea84f015-*.log.2",
"sessionKey":"ea84f015-cursor-handoff",
"verdict":{
"isReal":true,
"adjustedSeverity":"medium",
"reasoning":"Evidence fully reproduces: log.2 has three decoded results with subtype 'success' but is_error:true (00:51:30.884Z 'API Error: Overloaded', 00:55:19.085Z api_error_status:529, 01:00:28.143Z), while runs ordinal 11/12/13 and their provider_turns project as 'completed' with matching completed_at timestamps, and the only trace is the error text projected as a completed assistant_message (item 9c0cead6-... on run 13). Code confirms the gap: terminalStatusFromResult in ClaudeAdapterV2.ts returns 'completed' for any subtype==='success' and attaches a failure payload only for non-success subtypes, even though the SDK's SDKResultSuccess type explicitly carries is_error and api_error_status \u2014 the signal is typed and available but ignored, so this is a real mapping bug, not intended behavior. Severity stays medium: the error is user-visible as assistant text, but structured run/attempt/turn statuses misreport success and the 529 detail is not queryable, which misleads any downstream logic."
}
},
{
"title":"Native ground truth for most of the session destroyed by rotation of the opener thread's log",
"category":"lost-data",
"severity":"medium",
"confidence":"high",
"knownIssue":false,
"evidence":"Because codex traffic shares 71e29ba5's high-churn log (10 files x 10MB), the oldest surviving rotation (71e29ba5-...log.10) starts 2026-07-01T16:00:59.024Z. Everything earlier is deleted: c878541b runs 1-3 (01:54-15:58Z), all of de5f191a runs 1-3 (07:42-15:49Z), all of 68f7595b (05:53-05:56Z) and af66fc2c incl. its interrupted run (05:52-05:53Z). Only c878541b runs 4-6 (16:00-16:44Z) retain native logs. Consequence of the finding above; debuggability loss only \u2014 projections for the lost window exist and are internally consistent.",
"repro":"for f in ~/.t3/userdata-v2/logs/provider/71e29ba5-*.log*; do head -1 \"$f\" | cut -c2-25; done # earliest = 2026-07-01T16:00:59.024Z",
"sessionKey":"codex-no-native-logs",
"verdict":{
"isReal":true,
"adjustedSeverity":"low",
"reasoning":"Evidence fully reproduces: oldest surviving rotation (71e29ba5-...log.10) starts 2026-07-01T16:00:59.024Z; DB run windows confirm c878541b runs 1-3, all of de5f191a/68f7595b/af66fc2c predate it; native item ids from c878541b run 1 (msg_024da2f2..., call_z8cGFhrA...) appear in zero log files while run 4's msg_0e493c0caf68... appears 82x in .log.10, and no dedicated logs exist for the codex threads because CodexAdapterV2's protocol logger is keyed to the shared session's opener thread. Downgraded to low: the loss is a by-design consequence of intentional bounded rotation (10x10MB in EventNdjsonLogger.ts), the durable pipeline record (events + projections) for the lost window is intact and consistent, and the actual defect (codex traffic sharing a high-churn foreign thread's rotation budget) is the parent finding this one merely derives from."
}
},
{
"title":"Terminal-failure error items carry only generic message ('Claude Agent SDK query failed.'), underlying cause not preserved",
"category":"error-handling",
"severity":"medium",
"confidence":"high",
"knownIssue":false,
"evidence":"All 4 failed runs (37, 54 codex; 89, 119 claudeAgent) DO get a user-visible type='error' item (good surfacing), but payload is generic: run 119 item failure = {class:'transport_error', message:'Claude Agent SDK query failed.', code:null, retryable:null}, title 'Provider error'. The native log at both claude failure sites (2026-07-02T04:47:07.200Z and 16:45:25.921Z) shows only outgoing query.open/prompt.offer with no captured error line, so neither projection nor provider log retains the actual failure reason \u2014 undebuggable after the fact.",
"repro":"sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT json_extract(payload_json,'$.failure'), json_extract(payload_json,'$.title') FROM orchestration_v2_projection_turn_items WHERE thread_id='71e29ba5-654b-4f67-b363-ad400e5bd016' AND type='error'\"",
"sessionKey":"71e29ba5-claude-mega",
"verdict":{
"isReal":true,
"adjustedSeverity":"medium",
"reasoning":"Reproduced fully: claudeAgent failed runs 89/119 project only {class:'transport_error', message:'Claude Agent SDK query failed.', code:null} (event seq 43072), and the provider log at both failure sites (04:47:07.200Z log.2:790, 16:45:25.921Z log:3026) shows only outgoing query.open/prompt.offer with no error line. Source confirms the mechanism: ClaudeAgentSdkQueryRunnerError (ClaudeAdapterV2.ts:280) hardcodes its message getter while the real error lives in its cause Defect, which makeProviderFailure (ProviderFailure.ts:90) never unwraps \u2014 defeating the redaction/bounding machinery built to carry real messages (codex failures on this same thread DO carry specific messages, proving intent). The adapter's Effect.logWarning with the full cause was not found in any retained server trace log, so the failure reason is genuinely lost; medium severity stands since errors are surfaced but undebuggable."
}
}
],
"refuted":[
{
"title":"Orchestrator ingestion gap 16:10-16:40 Jul 1 (codex era): 119 native command/fileChange items lost; assistant messages backfilled with flattened timestamps",
"category":"lost-data",
"severity":"high",
"confidence":"high",
"knownIssue":true,
"evidence":"Zero orchestration_events for the stream between 2026-07-01T16:10:19 (run 50 completed) and 16:40:12 (run 51 requested), yet the native codex log shows substantive work in that window and around it: item/started fileChange items and commandExecutions incl. 'vp test .../OrchestratorReplayFixtures', 'vp check', 'git add apps/server/src/orchestration-v2/Adapters/Claude...' (call_0j3Wjk1K3an2l1CpCRgYBp8b 16:43:43) and 'git push origin t3code/codex-turn-mapping' (call_Hc9NQMOiQ9wo3by6RnzGbShQ 16:43:50), all with source 'unifiedExecStartup' on native thread 019f1b62-f532-79e2-9553-af817911965c. 119 of 450 native call_ ids have no projected turn_item (comm diff), all first seen 16:01-16:43 Jul 1. When run 51 started, 13 assistant messages (message:provider:codex:native-item:msg_*) were backfilled with IDENTICAL created_at 2026-07-01T16:40:14.821Z describing that missing work, but 0 turn_items have startedAt in 16:11-16:40. Text recovered, tool/file items and real timestamps lost. Mechanism (server down/restart vs codex turn-mapping bug) not fully determinable because logs older than 16:00:59Z were rotated away; loss itself is certain.",
"repro":"sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT count(*) FROM orchestration_events WHERE stream_id='71e29ba5-654b-4f67-b363-ad400e5bd016' AND occurred_at BETWEEN '2026-07-01T16:11' AND '2026-07-01T16:39'\" -> 0; SELECT count(*) FROM orchestration_v2_projection_messages WHERE thread_id='71e29ba5-654b-4f67-b363-ad400e5bd016' AND created_at='2026-07-01T16:40:14.821Z' -> 13",
"sessionKey":"71e29ba5-claude-mega",
"verdict":{
"isReal":false,
"reasoning":"The \"lost\" work belongs to a different session: the codex provider session is shared, so this thread's log contains other threads' traffic. All gap-window log lines (1322 decoded events, 16:11-16:39) carry threadId 019f1b62-f532-..., which per orchestration_v2_projection_provider_threads is owned by thread c878541b-a832-..., not 71e29ba5 (whose codex nativeThreadRef is 019f1b50-4248-...). Exactly 119 call_ ids in the log belong to 019f1b62 and ALL 119 (including the cited call_0j3Wjk1K3an2l1CpCRgYBp8b and call_Hc9NQMOiQ9wo3by6RnzGbShQ) are projected on thread c878541b; all 62 call_ ids on this thread's own native id are projected on 71e29ba5 (comm diff = 0 both ways). The zero-event window is genuine idle time between run 50 (completed 16:10:19) and run 51 (requested 16:40:12), and the 13 messages at created_at 16:40:14.821Z are run 51's live-streamed assistant messages (e.g. msg_00c4d1e6... streamed at 16:48:38 on threadId 019f1b50) \u2014 every one of the 55 codex runs shows the same pattern of assistant messages sharing created_at = run start, so this is systematic projection behavior, not backfill of lost work."
}
},
{
"title":"All thinking/reasoning blocks dropped for main thread (122 native thinking messages, 0 reasoning items)",
"category":"lost-data",
"severity":"medium",
"confidence":"medium",
"knownIssue":false,
"evidence":"Native log contains 122 distinct main-thread assistant messages with thinking content blocks plus 646 'thinking_tokens' system events, but the main thread has zero projected reasoning turn-items (the only 2 'reasoning' items in the session are subagent-progress placeholders on the child threads, e.g. turn-item:...task%3Aac08aa451ed54d3f6%3Aprogress). ClaudeAdapterV2.ts only extracts part.type==='text' blocks (line 730: content.flatMap((part) => (part.type === \"text\" ? [part.text] : []))). May be an intentional product choice for claudeAgent, but it means no reasoning is ever visible/persisted for this provider.",
"repro":"cat log.1 log | jq 'select(.event.payload.type==\"assistant\" and .event.payload.parent_tool_use_id==null) | select([.event.payload.message.content[]?|select(.type==\"thinking\")]|length>0) | .event.payload.uuid' | sort -u | wc -l # 122, vs SELECT COUNT(*) FROM orchestration_v2_projection_turn_items WHERE thread_id='47763f5e-76c1-4d67-8037-442a280f1514' AND type='reasoning'; -- 0",
"sessionKey":"47763f5e-claude-fable",
"verdict":{
"isReal":false,
"reasoning":"The counts reproduce (155 native thinking blocks, 0 projected reasoning items), but inspection of the actual block contents refutes the lost-data claim: every final thinking block in the native log is {\"thinking\":\"\",\"signature\":\"...\"} and all 593 thinking_delta stream events are {\"thinking\":\"\",\"estimated_tokens\":N} \u2014 the Claude Agent SDK redacted all thinking text at the source for claude-fable-5, so there was never any reasoning content to project. ClaudeAdapterV2.ts:730 extracting only text parts drops nothing user-visible here; projecting these blocks would produce 155 empty reasoning items. The 646 'thinking_tokens' system events are token telemetry, not content."
}
},
{
"title":"Failed cursor runs 15/16/17 keep only a generic 'Provider turn failed.' with code:null \u2014 no diagnostic detail persisted",
"category":"error-handling",
"severity":"medium",
"confidence":"high",
"knownIssue":false,
"evidence":"Error items exist and are user-visible (turn-item:provider:cursor:native-item:terminal-failure%3A...run-abf255cf / run-ceb09abc / run-f5fe7fcf, status failed, ordinals 15000098/16000002/17000002) but failure = {class:'provider_error', message:'Provider turn failed.', code:null, retryable:null}; run and run_attempt payloads contain no error field at all. Native run.completed results (log: 02:05:24.474Z, 02:16:37.138Z, 02:19:07.097Z) carry status:'error' with no message either \u2014 so cursor itself gave nothing \u2014 but available context (result.status, requestId d1cd7f44/55687657/6de8f367, durationMs 2434335/1223/657) was dropped. Run 15 did 40 min of work then errored; runs 16/17 ('continue') died in ~1s each with only 'Provider error' shown.",
"repro":"sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT payload_json FROM orchestration_v2_projection_turn_items WHERE thread_id='ea84f015-e597-4f79-9557-d39b5a895fba' AND type='error'\"",
"sessionKey":"ea84f015-cursor-handoff",
"verdict":{
"isReal":false,
"reasoning":"The evidence reproduces (three failed cursor runs projected with the generic 'Provider turn failed.' failure), but the native log shows cursor's run.completed results carried status:'error' with NO error/message/code field at all, so there was no provider diagnostic to persist. The code path is intentional: CursorAdapterV2 forwards result.error as cause, and makeProviderFailure (ProviderFailure.ts) extracts message/code when supplied, falling back to the tested DEFAULT_PROVIDER_FAILURE_MESSAGE \u2014 including an explicit test asserting arbitrary cause objects are deliberately not serialized. The 'dropped context' claim largely fails: result.status is persisted as failed on item/run/provider_turn, and durationMs is recoverable from the persisted provider_turn startedAt/completedAt (01:24:50.203Z\u219202:05:24.475Z \u2248 2434335ms); only cursor's requestId is unpersisted, which the ProviderFailure contract intentionally omits and which remains in the provider log. This is an upstream cursor SDK limitation plus a possible enhancement (persist requestId), not a pipeline discrepancy.",
"adjustedSeverity":"low"
}
}
],
"lowUnverified":[
{
"title":"Interrupt-result turn item references an interrupt-request parent that was never emitted",
"category":"lineage",
"severity":"low",
"confidence":"high",
"knownIssue":false,
"evidence":"turn_item 'turn-item:run:run%3Athread%3Aea84f015-e597-4f79-9557-d39b5a895fba%3Aordinal%3A15:signal:interrupt-result' (event seq 34176, 2026-07-02T01:24:49.393Z) has parent_item_id '...:signal:interrupt-request' with no matching row/event. Contrast thread af66fc2c-73cd-4c30-bea5-66932ecdba29 where both request (seq 20000) and result (seq 20003) were emitted. Code: makeInterruptResultTurnItem in apps/server/src/orchestration-v2/RunExecutionService.ts (line ~874) unconditionally derives parentItemId from the request id without ensuring that item was emitted; the request emission lives on a separate path in Orchestrator.ts:4422.",
"repro":"sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT turn_item_id, parent_item_id FROM orchestration_v2_projection_turn_items ti WHERE parent_item_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM orchestration_v2_projection_turn_items p WHERE p.turn_item_id=ti.parent_item_id);\"",
"sessionKey":"GLOBAL"
},
{
"title":"Synthesized terminal-failure error item references a provider_turn_id that was never projected",
"category":"lineage",
"severity":"low",
"confidence":"high",
"knownIssue":false,
"evidence":"turn_item 'turn-item:provider:cursor:native-item:terminal-failure%3A...' on thread 721fc23c-2cf3-42bf-9d84-edd94359dca9 (updated 2026-06-29T21:48:40.703Z) carries providerTurnId 'provider-turn:provider:cursor:native-turn:failed%3Arun-attempt%3A...ordinal%253A2%3Aattempt%3A1' which has no row in orchestration_v2_projection_provider_turns. The run failed 4ms after the outgoing run.start ('what did you just say', log 2026-06-29T21:48:40.699Z) with no incoming response; the synthetic 'failed' turn id was minted for the failure item but the turn itself never projected.",
"repro":"sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT turn_item_id FROM orchestration_v2_projection_turn_items ti WHERE ti.provider_turn_id IS NOT NULL AND NOT EXISTS (SELECT 1 FROM orchestration_v2_projection_provider_turns p WHERE p.provider_turn_id=ti.provider_turn_id);\"",
"sessionKey":"GLOBAL"
},
{
"title":"provider_sessions stay status='ready' after provider-session.detached (projection ignores detach)",
"category":"stuck-state",
"severity":"low",
"confidence":"medium",
"knownIssue":false,
"evidence":"Session provider-session:...claudeAgent:thread:47763f5e...:1c70abe8-4ecb-... got provider-session.detached event seq 31344 (2026-07-01T23:44:29.976Z, reason 'Thread archived.') and session ...ea84f015...:21ed85a2-... got detached seq 32566 (2026-07-02T01:03:00.273Z), yet both projection rows still show status='ready' with stale updated_at (22:48:37 / 22:12:31 \u2014 predating even later provider-session.updated events like seq 31274 at 23:42:43). The 16 'stopped' sessions were transitioned via updated events; detach alone leaves rows 'ready' indefinitely on archived threads.",
"repro":"sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT s.provider_session_id, s.status, s.updated_at FROM orchestration_v2_projection_provider_sessions s WHERE s.status='ready' AND EXISTS (SELECT 1 FROM orchestration_events e WHERE e.event_type='provider-session.detached' AND e.payload_json LIKE '%'||s.provider_session_id||'%');\"",
"sessionKey":"GLOBAL"
},
{
"title":"13 backgrounded local_bash tasks projected as subagents with empty prompts and synthetic child threads",
"category":"other",
"severity":"low",
"confidence":"high",
"knownIssue":true,
"evidence":"Thread 7f1dfff1-4cbb-450b-8514-764d11c903e1 run 2 (2026-07-01T15:51): tasks bw28jiyac, bzmkw8629, bnkw62tp7, etc. are task_type 'local_bash' in the native log (task_started has only a 'description' like 'vp run --filter @t3tools/web typecheck...', no prompt), yet each got a subagent row (prompt length 0), a child thread, and a user_message prompt item with text ''. Newer local_agent tasks (a-prefixed 16-hex ids) capture full prompts (1.9k-4.3k chars). Predates the backgrounded-Bash redesign on t3code/codex-turn-mapping where local_bash stays a running Bash item completed cross-run; these are stale artifacts of the old mapping, not current behavior.",
"repro":"sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT turn_item_id FROM orchestration_v2_projection_turn_items WHERE type='user_message' AND coalesce(json_extract(payload_json,'$.text'),'')='';\"",
"evidence":"Thread ea84f015 run 15: partial-tool-call toolu_01HgLigck78NC9MSVyjitDXe (edit) at log 2026-07-02T01:54:20.622Z never received tool-call-started/completed (stream stalled 6.5 min, cursor retried at 02:00:47 with new callId toolu_01NkWmCzHTn5ofjtYi4NkhsJ); the abandoned call's item 'turn-item:provider:cursor:native-item:toolu_01HgLigck78NC9MSVyjitDXe' (type file_change) was finalized status='completed' at run end (02:05:24.475Z) though the edit never executed. The retry also re-emitted identical assistant text ('Now the `WorkGroupSection` filter and the `SimpleWorkEntryRow` indicator.') producing items ...abf255cf...%3A6 (ordinal 15000077) and %3A7 (15000079) with duplicate visible text \u2014 faithful to two native text-delta emissions (log 01:54:19.813Z and 02:00:47.715Z), so provider-side, but rendered twice to the user.",
"repro":"grep -a 'SimpleWorkEntryRow\\` indicator' ~/.t3/userdata-v2/logs/provider/ea84f015-e597-4f79-9557-d39b5a895fba.log | cut -c1-30",
"sessionKey":"GLOBAL"
},
{
"title":"provider_turn status has no 'waiting' literal during ScheduleWakeup sleep loops",
"category":"stuck-state",
"severity":"low",
"confidence":"high",
"knownIssue":true,
"evidence":"Known issue per assignment; currently only 1 provider_turn 'running' (thread 71e29ba5, started 2026-07-02T17:03:04.470Z \u2014 genuinely live at audit time 17:07Z), so no stale instance observed in this pass, but the schema/status distribution confirms no 'waiting' state exists (statuses seen: cancelled/completed/failed/interrupted/running).",
"repro":"sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT status, count(*) FROM orchestration_v2_projection_provider_turns GROUP BY status;\"",
"sessionKey":"GLOBAL"
},
{
"title":"Codex reasoning items never ingested (no content lost in this session: all summaries empty)",
"category":"lost-data",
"severity":"low",
"confidence":"medium",
"knownIssue":false,
"evidence":"Native log contains 5 reasoning item/completed events (e.g. rs_0cfa4cea83165175016a40a8e17de08199a84ec646c88a40cd run 2, rs_0cfa4cea...8c48/9052/9329 run 4), all with summary: []. SQL: 0 orchestration_events on stream a5a643b2-... with payload LIKE '%native-item:rs_%', and 0 turn_items of reasoning type with a codex provider_thread anywhere in the DB (172 reasoning items exist for other providers). CodexAdapterV2.ts has no reasoning item mapping (grep hits only 'reasoningEffort' config). With empty summaries nothing user-visible was lost here, and dropping empty reasoning may be intentional, but non-empty reasoning summaries would be silently dropped.",
"title":"Codex reasoning items are silently dropped by CodexAdapterV2 (no handler for item type \"reasoning\")",
"category":"lost-data",
"severity":"low",
"confidence":"high",
"knownIssue":false,
"evidence":"Native log emits item/started + item/completed for reasoning item rs_056ea93bc8adc0f3016a42c0594d788194ad4afb537a0a0b16 at 2026-06-29T18:58:33.314Z/33.340Z (turn 019f14bf-4440-7bb0-9655-7194b384e690), but zero rows in orchestration_events reference it and no turn_item exists. Code confirms: CodexAdapterV2.ts item/started (line 2802) and item/completed (line 2875) handlers cover userMessage, subAgentActivity, commandExecution, mcpToolCall/dynamicToolCall, fileChange, webSearch, plan, collabAgentToolCall, agentMessage \u2014 no \"reasoning\" branch and no item/reasoning delta handler, despite capabilities declaring streamsReasoning: true (line 139). In THIS session the item had empty summary/content so no user-visible text was lost, hence severity low \u2014 but any non-empty reasoning summary would vanish.",
"repro":"grep 'rs_056ea93bc8adc0f3' ~/.t3/userdata-v2/logs/provider/a61e9269-0180-4f4c-988a-aca00b240469.log ; sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT count(*) FROM orchestration_events WHERE payload_json LIKE '%rs_056ea93bc8adc0f3%'\" -- returns 0",
"sessionKey":"a61e9269-codex"
},
{
"title":"thread/tokenUsage/updated and account/rateLimits/updated notifications never ingested; runs have no usage data",
"category":"lost-data",
"severity":"low",
"confidence":"medium",
"knownIssue":false,
"evidence":"Native log contains 5 thread/tokenUsage/updated and 5 account/rateLimits/updated decoded notifications; CodexAdapterV2.ts registers no handler for either (only item/agentMessage/delta, item/plan/delta, turn/plan/updated, turn/started, item/started, item/completed, turn/completed at lines 2693-3395). Runs projection payload has usage:null for both run:thread:a61e9269-0180-4f4c-988a-aca00b240469:ordinal:1 and :2, and no orchestration_events row carries token usage. May be intentional scope, but per-turn token accounting from the provider is discarded.",
"title":"Child task threads projecting only 2 items is intended, not data loss",
"category":"lost-data",
"severity":"low",
"confidence":"high",
"knownIssue":false,
"evidence":"Each child stream (e.g. ...composer_call_kFjs8) has exactly 2 distinct turn-item ids across its 2711 events: ...%3Aprompt (user_message, 1 event) and ...%3Aresult (assistant_message, 1352 events growing text 4->6274 chars). Grok's ACP Task envelope only exposes rawInput.prompt plus streamed output text (apps/server/src/provider/acp/XAiAcpExtension.ts extractXAiAcpSubagentUpdate / xAiTaskOutputText), and the child's intermediate narration is contained in the streamed result text ('I'll read the connection files...'). Parent subagent items' result lengths (3721/6274/2647) exactly equal child assistant_message text lengths \u2014 nothing truncated.",
"repro":"sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT json_extract(payload_json,'$.id'), COUNT(*), MAX(length(json_extract(payload_json,'$.text'))) FROM orchestration_events WHERE stream_id LIKE '%composer_call_kFjs8' AND event_type='turn-item.updated' GROUP BY 1;\"",
"sessionKey":"20296b49-grok-tasks"
},
{
"title":"Every successful grok turn logs session/prompt as failed with errorTag Interrupt",
"category":"error-handling",
"severity":"low",
"confidence":"high",
"knownIssue":false,
"evidence":"Native log events ec0b4762-8c1d-41c9-b4b3-2687da09d40b (2026-06-29T21:46:13.448Z) and 5a4a5b58-40ad-4f71-b2de-6e703e0c9173 (21:47:37.827Z): payload {method:'session/prompt',status:'failed',errorTag:'Interrupt'} \u2014 yet both runs completed successfully (run ordinal 1 completedAt 21:46:13.476Z, ordinal 2 completedAt 21:47:38.686Z). Cause: XAiAcpExtension races the direct prompt request against the private _x.ai/session/prompt_complete fallback; the losing fiber is interrupted and logged as a failed request. Correctly NOT surfaced as a user-visible error (nothing to surface), but the 'failed' log entries are misleading noise for future debugging.",
"title":"Grok native log redacts all payload content, limiting ground-truth audits",
"category":"other",
"severity":"low",
"confidence":"high",
"knownIssue":false,
"evidence":"All 3694 protocol lines in ~/.t3/userdata-v2/logs/provider/20296b49-edbf-420b-a862-d04238c10caf.log carry only shape summaries, e.g. payload {valueType:'string',byteLength:165} or {valueType:'array',itemCount:1} \u2014 no message text, tool names, or ids. Content-level loss/truncation verification against the provider is impossible from this log; verification here relied on internal consistency (event max text length == projection text length). If other providers' logs contain full JSON, grok's redaction is an inconsistency worth knowing about.",
"evidence":"All 6 child items have runId=null, providerThreadId=null, providerTurnId=null (e.g. turn-item ...composer_call_Olv1X%3Aprompt payload: runId:null, nodeId:'node:...%3Achild-root', creationSource:'provider'); child threads have zero run.created / provider-turn events. node_id resolves (child-root nodes exist) and the subagents projection links parent node -> child_thread_id, so navigation works via subagents rather than runs. Appears intentional for provider-native task children (no orchestrator run exists), but any consumer that groups items by run_id will see these as orphans.",
"repro":"sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT turn_item_id, run_id, provider_turn_id FROM orchestration_v2_projection_turn_items WHERE thread_id LIKE 'thread:provider:grok:native-thread:019f1558%';\"",
"sessionKey":"20296b49-grok-tasks"
},
{
"title":"run_attempts.provider_turn_id is never populated (null for all 207 attempts DB-wide) \u2014 back-link from attempt to provider turn missing",
"category":"lineage",
"severity":"low",
"confidence":"medium",
"knownIssue":false,
"evidence":"This session: run-attempt:run:run%3Athread%3A721fc23c...%3Aordinal%3A1:attempt:1 has providerTurnId:null although provider-turn:provider:cursor:native-turn:run-9d9ff525-e89c-41e3-90e6-1f7e841cc188 references that exact runAttemptId (forward link intact, nativeTurnRef strong). Global check: SELECT provider_turn_id IS NULL, count(*) FROM orchestration_v2_projection_run_attempts GROUP BY 1 shows every row (completed 188, failed 12, cancelled 4, interrupted 1, running 1, superseded 1) has NULL \u2014 the column/payload field exists but nothing ever writes it. Forward resolution via provider_turns.run_attempt_id works, so impact is limited to reverse-lookup ergonomics; may be intentional but the schema advertises the field.",
"repro":"sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT status, provider_turn_id IS NULL, count(*) FROM orchestration_v2_projection_run_attempts GROUP BY 1,2\"",
"sessionKey":"721fc23c-cursor"
},
{
"title":"Run orphaned by server restart is cancelled with no user-visible or persisted reason; user's message got no response",
"category":"error-handling",
"severity":"low",
"confidence":"high",
"knownIssue":false,
"evidence":"Native log ends at run.started 2026-06-29T21:49:09.097Z (runId run-f062e5d9-534a-48a8-8214-48fea97bc268) with zero assistant output. Events seq 6341-6346 (command:runtime-reconcile:startup:48663fb7-...:2026-06-29T21:49:10.775Z) set run:thread:48663fb7-...:ordinal:1, its attempt, and provider-turn:provider:cursor:native-turn:run-f062e5d9-... to status 'cancelled' with no reason field in any payload, indistinguishable from a user cancel. No error/system turn_item was emitted, so the timeline shows only the user 'hello' and 'Workspace ready' with nothing explaining the missing reply. Source: ProviderRuntimeRecoveryService.ts:107 builds detail 'Cancelled because the server restarted before the provider work completed.' but attaches it only to runtime-request payloads and outbox effect cancellations (lines 291/316), never to run/attempt/turn/item rows \u2014 intentional code path, but a debuggability/UX gap.",
"repro":"sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT sequence, event_type, payload_json FROM orchestration_events WHERE stream_id='48663fb7-fbd6-4be2-ad14-d8163282c069' AND command_id LIKE 'command:runtime-reconcile:%'\" \u2014 note status 'cancelled' payloads contain no reason; and grep -c NTIVE ~/.t3/userdata-v2/logs/provider/48663fb7-fbd6-4be2-ad14-d8163282c069.log shows only 4 lines with no assistant output.",
"evidence":"All 117 file_search items across the 5 opencode child threads have results=NULL (contract OrchestrationV2FileSearchResult array at orchestrationV2.ts:843 is never populated by OpenCodeAdapterV2 \u2014 its file_search branch emits only 'pattern'). Example: prt_f15688536002X4CTVKyjMIxGfL (ses_0ea978228, ordinal 3) has only pattern '/Users/julius/Development/Work/codething-mvp'. Tool outputs (file contents read, matches found) exist in opencode's part.state.output but are discarded for this item type. Likely intentional UI minimalism, but it is provider-emitted content with no projection.",
"repro":"sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT COUNT(*), SUM(json_extract(payload_json,'$.results') IS NOT NULL) FROM orchestration_v2_projection_turn_items WHERE thread_id LIKE 'thread:provider:opencode:native-thread:ses_%' AND type='file_search';\" -- returns 117|0",
"sessionKey":"3029dc85-opencode"
},
{
"title":"Placeholder 'pending' provider_thread row persists alongside the real one; orchestrator-synthesized items split across the two",
"category":"lineage",
"severity":"low",
"confidence":"medium",
"knownIssue":false,
"evidence":"Main thread has TWO provider_thread rows: provider-thread:provider:opencode:native-thread:pending%3Arun%3Athread%3A3029dc85...%3Aordinal%3A1 (status idle, first/last run ordinals 1-7) and the real provider-thread:provider:opencode:native-thread:ses_0ea983868ffens4ayJQLKgPE6J (idle, 1-7). 20 items (7 user_message, 7 checkpoint, 3 thread_created, 2 delegated subagent, 1 command_execution) still reference the pending placeholder while all native items reference ses_0ea983868 \u2014 e.g. thread_created item turn-item:created-thread:...126456a2...%3A0 has providerThreadId '...pending%3Arun%3A...ordinal%3A1' but providerTurnId pointing at the real session ses_0ea983868. Lineage is queryable but split; the placeholder was never collapsed after the native session id was learned.",
"repro":"sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT provider_thread_id, status, first_run_ordinal, last_run_ordinal FROM orchestration_v2_projection_provider_threads WHERE thread_id='3029dc85-93b7-43c5-8993-1beff41b1c98';\"",
"sessionKey":"3029dc85-opencode"
},
{
"title":"Single occurred_at inversion on main stream (checkpoint capture vs concurrent subagent-result handoff)",
"category":"ordering",
"severity":"low",
"confidence":"high",
"knownIssue":false,
"evidence":"Stream 3029dc85...: stream_version 1868 (sequence 10004, checkpoint.captured, occurred_at 2026-06-29T22:09:54.344Z, checkpoint root:name:5 for run 5) was appended AFTER stream_versions 1863-1867 (sequences 9881-9885, delegated subagent d43de13f completion + context-handoff/transfer, occurred_at 22:09:54.779Z) \u2014 occurred_at goes backwards by 435ms. Benign concurrency between run-5 completion checkpointing and the delegated claudeAgent subagent result handoff landing; projection ordinals unaffected (0 ordinal inversions vs first-seen event order across all 6 threads).",
"repro":"sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT stream_version, sequence, event_type, occurred_at FROM (SELECT stream_version, sequence, event_type, occurred_at, LAG(occurred_at) OVER (ORDER BY stream_version) prev FROM orchestration_events WHERE stream_id='3029dc85-93b7-43c5-8993-1beff41b1c98') WHERE occurred_at < prev;\"",
"sessionKey":"3029dc85-opencode"
},
{
"title":"Native provider log payloads are fully redacted (valueType/fieldCount only), preventing content-level loss auditing",
"category":"other",
"severity":"low",
"confidence":"high",
"knownIssue":false,
"evidence":"Every one of the 17,198 log lines in 3029dc85-93b7-43c5-8993-1beff41b1c98.log(.1) has kind='protocol' with inner payload reduced to {valueType:'object', fieldCount:N} \u2014 e.g. message.part.updated lines carry no part id, text, or error. Only method-level counts are auditable (15,542 message.part.delta, 723 message.part.updated, 204 message.updated, 7 session.promptAsync, 5 session.created, 12 session.idle). Method counts DO reconcile with projections (7 promptAsync = 7 runs; 5 session.created = 5 child threads; 12 session.idle = 7 main turns + 5 child turns), but text truncation and the actual error string of the failed file_search cannot be verified against the wire. If these logs are meant to be 'ground truth', the opencode SSE logger is not recording decoded payloads.",
"repro":"grep -h '\"message.part.updated\"' ~/.t3/userdata-v2/logs/provider/3029dc85-93b7-43c5-8993-1beff41b1c98.log.1 | head -1",
"sessionKey":"3029dc85-opencode"
},
{
"title":"Split provider-thread identity: run/attempt/provider_turn reference the pending-keyed provider-thread row while turn items and threads.active_provider_thread_id reference the ses_-keyed row",
"category":"lineage",
"severity":"low",
"confidence":"medium",
"knownIssue":false,
"evidence":"Two rows in orchestration_v2_projection_provider_threads for the same native session: 'provider-thread:provider:opencode:native-thread:pending%3Arun%3Athread%3A9f8d616d-...%3Aordinal%3A1' and 'provider-thread:provider:opencode:native-thread:ses_0ea7ea5deffe0eNd8RbfyTfgAw' (both idle, same provider_session_id, and the pending row's payload has nativeThreadRef.nativeId=ses_0ea7ea5deffe0eNd8RbfyTfgAw strength strong). projection_runs.provider_thread_id, run_attempts.provider_thread_id and provider_turns.provider_thread_id all point at the pending-keyed row, while the two provider-part turn_items (prt_f158168eb001r0Ubqqry5Z31Q1, prt_f158169d0002CgOsT8eNRkPGI3) and threads.active_provider_thread_id point at the ses_-keyed row. Notably provider_turns row provider-turn:...ses_0ea7ea5deffe0eNd8RbfyTfgAw%3Aattempt... encodes ses_ in its own id but its provider_thread_id column is the pending row. Pending id minted in Orchestrator.ts (`nativeThreadId: \\`pending:${runId}\\``, lines 2384/2772); the pending row is resolved via nativeThreadRef rather than rebinding downstream rows, so joins on provider_thread_id split the turn across two ids.",
"repro":"sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT provider_thread_id FROM orchestration_v2_projection_provider_turns WHERE thread_id='9f8d616d-86ee-4560-bd52-2387d6adb1c3'; SELECT DISTINCT provider_thread_id FROM orchestration_v2_projection_turn_items WHERE thread_id='9f8d616d-86ee-4560-bd52-2387d6adb1c3';\"",
"sessionKey":"9f8d616d-opencode"
},
{
"title":"Real provider-thread row stayed status 'active' for ~20h after the provider session stopped",
"category":"stuck-state",
"severity":"low",
"confidence":"high",
"knownIssue":false,
"evidence":"provider-session.updated seq 13792 marks session stopped at 2026-06-29T23:00:38.028Z (idle reaper ~30min after last activity 22:30:30; last native log line heartbeat 2026-06-29T23:00:27.024Z). The pending-keyed provider-thread went idle at turn completion (seq 13783, 22:30:30.877Z), but the ses_0ea7ea5deffe0eNd8RbfyTfgAw provider-thread's last status update before shutdown was 'active' (seq 13779, 22:30:30.876Z) and it was only flipped to idle by seq 13797 at 2026-06-30T18:59:15.308Z, ~20h later (presumably on next app start). During that window the projection showed an active provider-thread bound to a stopped session. Eventually reconciled; final state is consistent.",
"repro":"sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT sequence, occurred_at, json_extract(payload_json,'$.id'), json_extract(payload_json,'$.status') FROM orchestration_events WHERE stream_id='9f8d616d-86ee-4560-bd52-2387d6adb1c3' AND event_type IN ('provider-thread.updated','provider-session.updated') ORDER BY sequence\"",
"sessionKey":"9f8d616d-opencode"
},
{
"title":"OpenCode native log payloads are redacted to shape summaries, preventing content-level ground-truth verification",
"category":"other",
"severity":"low",
"confidence":"high",
"knownIssue":false,
"evidence":"Every one of the 273 lines in 9f8d616d-86ee-4560-bd52-2387d6adb1c3.log is kind 'protocol' (opencode-sdk.sse) with payload reduced to e.g. {\"payload\":{\"valueType\":\"object\",\"fieldCount\":3}} \u2014 no message text, part ids, or tool args (contrast with claude logs which carry full decoded JSON). Only method names/counts are auditable: 31 message.part.delta, 7 message.part.updated, 6 message.updated, 1 session.idle, 0 session.error. Projected content was spot-checked instead and looks sensible and un-truncated (user 'hey'; reasoning 'The user is just saying \"hey\" - a casual greeting...'; assistant 'Hey! What can I help you with?').",
"title":"run_attempt.provider_turn_id never populated (null on all 207 attempts DB-wide)",
"category":"lineage",
"severity":"low",
"confidence":"medium",
"knownIssue":false,
"evidence":"run-attempt row run-attempt:...ordinal%3A1:attempt:1 has providerTurnId:null in payload_json and empty provider_turn_id column, while the provider_turn row correctly back-references runAttemptId. DB-wide: SELECT count(*), sum(provider_turn_id IS NOT NULL AND provider_turn_id != '') FROM orchestration_v2_projection_run_attempts \u2192 207|0. Forward lineage attempt\u2192turn is only recoverable by scanning provider_turns; may be intentional (reverse-only linkage) but the column exists and is never filled.",
"repro":"sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT count(*), sum(provider_turn_id IS NOT NULL AND provider_turn_id != '') FROM orchestration_v2_projection_run_attempts;\"",
"sessionKey":"1156181e-delegated-task"
},
{
"title":"Provider session stayed 'running' ~25h after turn ended; only reconciled to 'stopped' at server shutdown",
"category":"stuck-state",
"severity":"low",
"confidence":"medium",
"knownIssue":true,
"evidence":"Turn completed 2026-06-28T05:22:33.360Z (last native log line); no further session events until sequence 168 provider-session.updated at 2026-06-29T06:33:36.481Z via command:runtime-reconcile:shutdown, which set status=stopped. No provider-session.detached was ever emitted for this thread. Related to the known idle-session-reaper/session-lifecycle area; state is correct now, so no data impact, but the projection reported a live session for a day for a one-shot delegated task.",
"repro":"sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT sequence, event_type, occurred_at FROM orchestration_events WHERE stream_id LIKE '%1156181e%' AND event_type LIKE 'provider-session%' ORDER BY sequence;\"",
"sessionKey":"1156181e-delegated-task"
},
{
"title":"claudeAgent provider sessions never idle-reaped; stayed 'ready' ~21 hours until simultaneous shutdown sweep",
"category":"stuck-state",
"severity":"low",
"confidence":"medium",
"knownIssue":false,
"evidence":"codex session stopped 2026-06-29T22:39:55 (seq 13789, 30 min after its 22:09:55 failure) and grok stopped 22:41:44 (seq 13790, 30 min after 22:11:44 completion) \u2014 idle reaper working. But all 3 claudeAgent sessions (last activity 22:08:48 / 22:09:50 / 22:13:07 on 6/29) only transitioned ready->stopped at 2026-06-30T18:59:15.286/.289/.291 (seq 13793-13795), simultaneously, ~21h later \u2014 a shutdown sweep, not the 30-min reaper. Native logs show no claude activity after 22:13, so either processes lingered or projections misreported 'ready' for a day. Inverse of the known 'reaper kills long sleeps' issue: reaper never fired for claudeAgent.",
"repro":"sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT sequence, occurred_at, json_extract(payload_json,'$.status') FROM orchestration_events WHERE event_type LIKE 'provider-session%' AND stream_id LIKE '%6d618dc4%' ORDER BY sequence;\"",
"sessionKey":"6d618dc4-mcp-group"
},
{
"title":"Codex model-rejection error fully preserved and user-visible (works as intended)",
"category":"error-handling",
"severity":"low",
"confidence":"high",
"knownIssue":false,
"evidence":"Native log 22:09:55.424 method 'error' / turn/completed status failed with message 'The gpt-5.3-codex model is not supported when using Codex with a ChatGPT account' (400 invalid_request_error). Projection: turn_item turn-item:provider:codex:native-item:terminal-failure%3A...019f156e-851a... type=error status=failed carries the verbatim JSON error in failure.message; run/run_attempt/provider_turn all 'failed'. No swallowing \u2014 this is a positive verification, listed for completeness.",
"repro":"sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT json_extract(payload_json,'$.failure.message') FROM orchestration_v2_projection_turn_items WHERE turn_item_id LIKE '%terminal-failure%019f156e-851a%';\"",
"sessionKey":"6d618dc4-mcp-group"
},
{
"title":"Grok session/prompt request ends with errorTag 'Interrupt' at the instant the turn completes",
"category":"other",
"severity":"low",
"confidence":"low",
"knownIssue":false,
"evidence":"Log 2026-06-29T22:11:44.909Z: {method:'session/prompt',status:'failed',errorTag:'Interrupt'} while provider_turn 019f156e-797f...:turn:1 completedAt 22:11:44.910 status=completed and the 6663-char assistant report is fully projected (item ordinal 1000074). Likely adapter-initiated interrupt cleanup after observing turn completion (grok capabilities: supportsSteeringByInterruptRestart=true); no data lost, but a native 'failed' prompt request maps to a 'completed' turn, which could confuse future debugging.",
"title":"Grok file_search/read items persist only pattern + fileName echo, no tool output; grok native log fully redacted",
"category":"lost-data",
"severity":"low",
"confidence":"low",
"knownIssue":false,
"evidence":"49 file_search items on thread :1 store e.g. pattern='pnpm-workspace.yaml', results=[{'fileName':'pnpm-workspace.yaml'}] (item turn-item:provider:grok:native-item:...call-e4489e09-...-1, ordinal 1000004) \u2014 the file content the tool returned is not kept, unlike claudeAgent command items which keep full stdout envelopes. Additionally the grok log redacts all decoded payloads to shape summaries ({'valueType':'array','itemCount':1}), so native-vs-projection content verification is impossible for grok; command_execution and reasoning items do carry real content, so this may be an intentional thin mapping for read-style tools.",
"repro":"sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT json_extract(payload_json,'$.pattern'), json_extract(payload_json,'$.results') FROM orchestration_v2_projection_turn_items WHERE thread_id LIKE '%126456a2%:1' AND type='file_search' LIMIT 5;\"",
"sessionKey":"6d618dc4-mcp-group"
},
{
"title":"Both session/prompt requests logged as failed with errorTag=Interrupt despite runs completing",
"category":"error-handling",
"severity":"low",
"confidence":"medium",
"knownIssue":false,
"evidence":"Native log request events: session/prompt started 01:51:45.517 -> failed errorTag=Interrupt at 01:52:13.249; session/prompt started 01:53:00.071 -> failed errorTag=Interrupt at 01:53:37.665. These timestamps exactly equal provider_turn completed_at values (turn 1: 01:52:13.249, turn 2: 01:53:37.665), and both runs/turns/items project as completed with full assistant content, so this appears to be intentional adapter teardown (interrupting the pending ACP prompt fiber once the turn result is reached; grok sets interruptPromptOnCancel:false in GrokAdapterV2.ts line 90/641). No content was lost and no spurious failure surfaced, but the log-level 'failed' status for successful turns will mislead debugging.",
"title":"run_attempts.provider_turn_id never populated (reverse link only)",
"category":"lineage",
"severity":"low",
"confidence":"medium",
"knownIssue":false,
"evidence":"Both attempts for this session (run-attempt:run:run%3Athread%3A5dcea72d...ordinal%3A1:attempt:1 and ...ordinal%3A2:attempt:1) have provider_turn_id NULL in both the column and payload_json; DB-wide, 0 of all rows in orchestration_v2_projection_run_attempts have a non-NULL provider_turn_id. Lineage is still resolvable via orchestration_v2_projection_provider_turns.run_attempt_id (both turns correctly reference their attempts), so this may be an intentionally unused column, but the forward link is dead.",
"repro":"sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT COUNT(*) FROM orchestration_v2_projection_run_attempts WHERE provider_turn_id IS NOT NULL;\"",
"sessionKey":"5dcea72d-grok-subagent"
},
{
"title":"Backgrounded-bash child threads have empty-text prompt user_message items",
"category":"other",
"severity":"low",
"confidence":"high",
"knownIssue":false,
"evidence":"All 13 backgrounded-bash child threads project a user_message item task%3A<id>%3Aprompt with text:\"\" (e.g. turn-item:provider:claudeAgent:native-item:task%3Abw28jiyac%3Aprompt, startedAt 2026-07-01T15:51:26.160Z), even though the native task_started event carried description \"vp run --filter @t3tools/web typecheck 2>&1 | tail...\". The command is still user-visible via the main-thread subagent item title, so impact is cosmetic (empty bubble if the child thread is opened).",
"repro":"sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT turn_item_id FROM orchestration_v2_projection_turn_items WHERE thread_id LIKE '%7f1dfff1%' AND type='user_message' AND json_extract(payload_json,'$.text')='';\"",
"sessionKey":"7f1dfff1-claude-scheduled-tasks"
},
{
"title":"Codex run 1 (169 items) has no surviving native log to verify against",
"category":"other",
"severity":"low",
"confidence":"high",
"knownIssue":false,
"evidence":"Run ordinal 1 (codex, 2026-07-01T01:45:03Z\u201302:01:10Z, 169 items incl. 10 failed command_executions) predates the oldest surviving log rotation: 7f1dfff1-...log.1 first line is 2026-07-01T15:48:00.224Z (run 2). The codex portion of the log was rotated away, so item-level loss/ordering for run 1 could not be ground-truthed; its events/projections are internally consistent (contiguous ordinals 1000001-1000169, all terminal).",
"title":"Provider session projection stuck at status 'ready' after detach/archive",
"category":"stuck-state",
"severity":"low",
"confidence":"medium",
"knownIssue":false,
"evidence":"provider-session.detached event at 2026-07-01T23:44:29.976Z (reason 'Thread archived.') for provider-session:...:1c70abe8-4ecb-43f8-8ee6-9ce19beddcfe, but the orchestration_v2_projection_provider_sessions row still shows status='ready' with updated_at=2026-07-01T22:48:37.724Z and thread_id still bound. The event stream also shows the session flip stopped\u2192ready correctly at 22:41:50/22:48:37, so the projection simply never reflects the final detached/terminated state.",
"repro":"sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT status, updated_at FROM orchestration_v2_projection_provider_sessions WHERE thread_id='47763f5e-76c1-4d67-8037-442a280f1514';\"",
"sessionKey":"47763f5e-claude-fable"
},
{
"title":"Detached claudeAgent provider session left in status 'ready' forever after handoff",
"category":"stuck-state",
"severity":"low",
"confidence":"medium",
"knownIssue":false,
"evidence":"Event seq 32566 provider-session.detached at 2026-07-02T01:03:00.273Z (reason 'Provider or model selection changed.') for provider-session:provider-instance:claudeAgent:thread:ea84f015-...:21ed85a2-2ed1-4bd8-94be-1e5affe1aa72, but the orchestration_v2_projection_provider_sessions row still shows status='ready' \u2014 no stopped update was ever emitted. The replacement cursor session was correctly moved to 'stopped' at 02:49:07 (seq 38639).",
"repro":"sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT provider_session_id,status FROM orchestration_v2_projection_provider_sessions WHERE provider_session_id LIKE '%ea84f015%'\"",
"sessionKey":"ea84f015-cursor-handoff"
},
{
"title":"Subagent child-thread items have null run_id / provider_thread_id / provider_turn_id",
"category":"lineage",
"severity":"low",
"confidence":"medium",
"knownIssue":false,
"evidence":"All 34 items of child thread ...a4bd1db1834cb086a and 52 items of ...ab96794f302d5fd03 have runId:null, providerThreadId:null, providerTurnId:null (e.g. turn-item:provider:claudeAgent:native-item:toolu_01L5SAT2nkGMce3gWf3qFFqJ). Lineage back to the parent exists only via orchestration_v2_projection_subagents (child_thread_id set, run_id = parent runs ordinal 2 and 5, both completed) and the two parent subagent turn items (task%3Aa4bd1db1834cb086a%3Asubagent / task%3Aab96794f302d5fd03%3Asubagent). Likely by design (child threads have no runs of their own), but items cannot be joined to any run/turn directly.",
"repro":"sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT count(*) FROM orchestration_v2_projection_turn_items WHERE thread_id LIKE 'thread:provider:claudeAgent%ea84f015%' AND run_id IS NULL\"",
"sessionKey":"ea84f015-cursor-handoff"
},
{
"title":"error_during_execution result during run 5 coincides with steering message \u2014 absorbed without any projected trace",
"category":"error-handling",
"severity":"low",
"confidence":"medium",
"knownIssue":false,
"evidence":"log.3 line 677 [2026-07-01T23:13:24.083Z] result subtype error_during_execution, is_error:true, duration_api_ms 2473149, session 44cbb4c7. A user steering message was ingested 50ms earlier (seq 30447 message.updated 23:13:24.031Z, message 513621d3-5a03-46e1-8fd7-cc4de4b417f1, run 5), so this looks like the intentional interrupt-for-steering path; run 5 continued and completed at 23:30:07 with items after 23:13. No event records the aborted query, which is acceptable if intentional but leaves no audit trail of the abort.",
"title":"5 tool calls that never returned natively were auto-marked 'completed' (with no results) at turn end",
"category":"lost-data",
"severity":"low",
"confidence":"high",
"knownIssue":false,
"evidence":"Native log has 123 distinct tool-call-started but only 118 tool-call-completed; the 5 without completion (tool_e1f3ce39... glob, tool_fd1ba594..., tool_e2f6262c..., tool_840aeaa9... grep, tool_671d1b53... read) are all projected as status 'completed' with completedAt forced to the turn-end timestamp 2026-07-02T02:25:57.991Z and no results payload (e.g. turn-item:provider:cursor:native-item:tool_e1f3ce39-4604-4ced-8039-bbd5e75946b ends with pattern:'**/*' and no results field). This is the intentional finalizeTurn flush (CursorAdapterV2.ts:1886-1889 emitToolArtifacts({completed:true})), but 'completed' misrepresents tools whose results never arrived; something like 'interrupted' or an explicit no-result marker would be more truthful. Minor: cursor itself abandoned these calls, so no user-visible content was lost.",
"repro":"sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT status, json_extract(payload_json,'$.completedAt') FROM orchestration_v2_projection_turn_items WHERE json_extract(payload_json,'$.nativeItemRef.nativeId')='tool_e1f3ce39-4604-4ced-8039-bbd5e75946b';\"",
"sessionKey":"c9e72a05-cursor-failing-turns"
},
{
"title":"Run 2 was a 7.3-minute silent hang before failing \u2014 nothing projected during the window (faithful to provider, but no progress/heartbeat signal exists)",
"category":"other",
"severity":"low",
"confidence":"high",
"knownIssue":false,
"evidence":"Native log: run.started for run-f4d64e64 at 02:28:07.973Z, next event is run.completed status 'error' at 02:35:28.424Z \u2014 zero interaction.updates in between. Ingested events for the stream in that window: 0 (SELECT COUNT(*) ... occurred_at BETWEEN '02:28:09' AND '02:35:28' returns 0). The pipeline mirrors the provider exactly (nothing lost), but the projection offers no signal distinguishing 'model working' from 'SDK dead due to auth error' during those 440s; the user just saw a running turn that eventually failed generically.",
"repro":"sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT COUNT(*) FROM orchestration_events WHERE stream_id='c9e72a05-4c87-4dd5-b1b6-83834cc73afe' AND occurred_at > '2026-07-02T02:28:09' AND occurred_at < '2026-07-02T02:35:28';\"",
"sessionKey":"c9e72a05-cursor-failing-turns"
},
{
"title":"Native 'read' tool calls are projected as type 'file_search'",
"category":"other",
"severity":"low",
"confidence":"medium",
"knownIssue":false,
"evidence":"18 native 'read' tool calls (e.g. tool_671d1b53-bb49-46ef-94de-8f682391c93 reading a file path) are projected as type 'file_search' with the file path as 'pattern'. Intentional per CursorAdapterV2.ts:1203-1219 (glob/grep/read/ls/readLints/semSearch all map to file_search), so the content is preserved, but the item type flattens semantically distinct operations (file reads rendered as searches). Cosmetic fidelity note only.",
"repro":"sqlite3 -readonly ~/.t3/userdata-v2/state.sqlite \"SELECT type FROM orchestration_v2_projection_turn_items WHERE json_extract(payload_json,'$.nativeItemRef.nativeId')='tool_671d1b53-bb49-46ef-94de-8f682391c93';\"",
"sessionKey":"c9e72a05-cursor-failing-turns"
},
{
"title":"Token usage from turn-ended/run.completed is dropped by the ingestion pipeline",
"category":"lost-data",
"severity":"low",
"confidence":"high",
"knownIssue":false,
"evidence":"Native log line 663 (2026-07-02T07:08:07.565Z) turn-ended carries usage {inputTokens:596379, outputTokens:6430, cacheReadTokens:522080}; line 664 run.completed repeats it with totalTokens:1124889. No event for stream_id=8ee00dcc-fa04-4fe7-9920-cd3432d45415 contains 'usage' or 'Tokens' (query returned 0 rows), and neither the run nor provider_turn projection payloads have a usage field. grep for 'usage' in apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.ts, ProviderEventIngestor.ts and ProviderAdapter.ts returns nothing \u2014 the v2 contract simply doesn't model usage, so this looks like a pipeline-wide design gap rather than a session bug, but users lose per-turn token/cost data.",
"repro":"sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT count(*) FROM orchestration_events WHERE stream_id='8ee00dcc-fa04-4fe7-9920-cd3432d45415' AND payload_json LIKE '%Tokens%';\" (returns 0) vs grep -c 'inputTokens' ~/.t3/userdata-v2/logs/provider/8ee00dcc-fa04-4fe7-9920-cd3432d45415.log (returns 2)",
"sessionKey":"8ee00dcc-cursor-spacing"
},
{
"title":"run_attempt.provider_turn_id never backfilled (forward link missing; reverse link intact)",
"category":"lineage",
"severity":"low",
"confidence":"medium",
"knownIssue":false,
"evidence":"orchestration_v2_projection_run_attempts row run-attempt:run:run%3Athread%3A8ee00dcc-fa04-4fe7-9920-cd3432d45415%3Aordinal%3A1:attempt:1 has provider_turn_id='' and payload providerTurnId:null even after completion, while orchestration_v2_projection_provider_turns row provider-turn:provider:cursor:native-turn:run-ee800ef2-cd0e-45bd-9481-65fd5cfdae67 correctly points back via run_attempt_id to that attempt. Lineage is resolvable only in one direction (turn->attempt).",
"repro":"sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT a.attempt_id, a.provider_turn_id, t.provider_turn_id FROM orchestration_v2_projection_run_attempts a JOIN orchestration_v2_projection_provider_turns t ON t.run_attempt_id=a.attempt_id WHERE a.thread_id='8ee00dcc-fa04-4fe7-9920-cd3432d45415';\"",
"sessionKey":"8ee00dcc-cursor-spacing"
},
{
"title":"file_change diffStr has malformed diff headers (a//abs/path, b//abs/path)",
"category":"other",
"severity":"low",
"confidence":"high",
"knownIssue":false,
"evidence":"turn-item:provider:cursor:native-item:tool_fee434e5-6388-483d-82f1-9e6c6ab418c (ordinal 1000042) payload diffStr begins '--- a//Users/julius/.t3/worktrees/codething-mvp/t3code-3cba2658/apps/mobile/src/features/home/HomeScreen.tsx' \u2014 absolute path concatenated after 'a/' yields double slash and a non-standard diff header; same for the other two file_change items (tool_361abe3b, tool_b586252d). Diff hunk content itself is intact (additions:2 deletions:1 recorded). Cosmetic, but breaks strict unified-diff parsers.",
"repro":"sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT substr(json_extract(payload_json,'$.diffStr'),1,80) FROM orchestration_v2_projection_turn_items WHERE thread_id='8ee00dcc-fa04-4fe7-9920-cd3432d45415' AND type='file_change';\"",
"sessionKey":"8ee00dcc-cursor-spacing"
},
{
"title":"Codex 'reasoning' items are silently dropped (no adapter handler, no projection)",
"category":"lost-data",
"severity":"low",
"confidence":"high",
"knownIssue":false,
"evidence":"Surviving log window shows 45 item/started + 45 item/completed reasoning items for native thread 019f1b62-f532 (c878541b runs 4-6), but the projection has 0 reasoning-type turn_items for any of the four threads (types present: assistant_message, command_execution, file_change, user_message, checkpoint, dynamic_tool, run_interrupt_*). CodexAdapterV2.ts item/started / item/completed handlers dispatch on userMessage/commandExecution/mcpToolCall/dynamicToolCall/fileChange/webSearch/plan/collabAgentToolCall/subAgentActivity and fall through for 'reasoning' despite capabilities streamsReasoning:true (line 139). Mitigating: every observed reasoning item had empty summary/content (e.g. rs_0e493c0caf681939016a4539c1c0988193b7174c9c067dfdb2, summary:[], content:[]), so no user-visible text was actually lost in this session.",
"repro":"cat ~/.t3/userdata-v2/logs/provider/71e29ba5-*.log.10 | grep '\"decoded\"' | grep '\"item/completed\"' | grep '019f1b62' | grep -c '\"reasoning\"' vs SELECT count(*) FROM orchestration_v2_projection_turn_items WHERE thread_id='c878541b-a832-4757-a254-5550e3f6c2d1' AND type LIKE '%reason%';",
"sessionKey":"codex-no-native-logs"
},
{
"title":"contextCompaction native item has no projection representation",
"category":"lost-data",
"severity":"low",
"confidence":"medium",
"knownIssue":false,
"evidence":"Native log shows item/completed contextCompaction id ad331e6d-f971-46a9-a04a-c70a1b86894f on turn 019f1e69-826e-7de2-9200-b6852ff53138 (c878541b run 4, ~16:00-16:05Z); no turn_item, node, or event for it exists (payload_json LIKE '%ompaction%' matches only incidental message text). Users cannot see that context was compacted mid-run. Native item carries only an id (no content), so the informational loss is small.",
"title":"Run 119 marked failed while its native query kept running; retry run 120 adopted the result, leaving a duplicated user message",
"category":"duplicate",
"severity":"low",
"confidence":"medium",
"knownIssue":false,
"evidence":"Run 119 failed at 2026-07-02T16:45:26.143Z (transport_error, ~1.5s after requested_at 16:45:24.618Z), but the native log shows query.open + prompt.offer at 16:45:25.921Z proceeding to SessionStart:resume (16:45:41) and a successful result at 16:47:00.764Z. Retry run 120 (requested 16:45:36.222Z) completed at 16:47:01.354Z with that assistant message (message:provider:claudeAgent:native-item:693d3576-4e56-4c10-9b0f-90ff9825f663, 3190 chars, intact). Two user messages with identical text exist: 9b135da3-dd1b-4a9a-90bc-ee4166bce48d (run 119) and 0f1b1078-74cb-4488-9626-e1ddbe933a9a (run 120) \u2014 timeline shows the prompt twice (plus the error item). Content preserved; cosmetic/duplication issue only.",
"repro":"sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT message_id, run_id, created_at FROM orchestration_v2_projection_messages WHERE thread_id='71e29ba5-654b-4f67-b363-ad400e5bd016' AND created_at BETWEEN '2026-07-02T16:45' AND '2026-07-02T16:46'\"",
"sessionKey":"71e29ba5-claude-mega"
},
{
"title":"4 native error_during_execution results silently recovered in-adapter with no projection trace",
"category":"error-handling",
"severity":"low",
"confidence":"medium",
"knownIssue":false,
"evidence":"Native results with subtype=error_during_execution/is_error=true at 2026-07-02T01:34:23.046Z, 02:29:30.034Z, 05:08:27.090Z, 17:03:10.206Z fall inside runs 73/80/95/122 \u2014 all completed with a single run attempt and no error item/event. At 01:34:23 the error coincides with an outgoing prompt.offer (mid-stream steering) followed immediately by system init and continued streaming, so the adapter's transparent re-query is likely intentional; but the transient error is invisible to projections (debug info only in provider log).",
"title":"Session has 7 subagent child threads, not 9 as briefed; all 7 fully linked and consistent",
"category":"lineage",
"severity":"low",
"confidence":"high",
"knownIssue":false,
"evidence":"Native log contains exactly 7 top-level Agent tool_use spawns (toolu_01CtiEb3..., 01CrTuja..., 01TiUmm..., 01W2SNA..., 01RjCn6..., 017H3QK..., 018VQWh...); projections have 7 type='subagent' items, 7 orchestration_v2_projection_subagents rows all with non-null child_thread_id resolving to existing thread rows, and 7 child-thread event streams (79-260 events each) with items on the correct thread ids (0 items with mismatched threadId). The 2 failed subagents (task%3Aafbafdde..., task%3Aa0e0b5f3..., completed_at 2026-07-02T08:34:33.868Z) match native '[Request interrupted by user for tool use]' is_error tool_results for toolu_017H3QKcEb9FrecsT4tyzg1M / toolu_018VQWhHKSAP1cFkZwZGRGe5 at 08:34:33.867Z \u2014 correct failure surfacing, not a bug.",
"repro":"sqlite3 ~/.t3/userdata-v2/state.sqlite \"SELECT count(*) FROM orchestration_v2_projection_subagents WHERE thread_id='71e29ba5-654b-4f67-b363-ad400e5bd016'\"",
- Use `effect/unstable/reactivity/AtomRpc` over the existing `WsRpcGroup`; stop wrapping RPC in promises via [wsRpcClient.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsRpcClient.ts) and [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts).
- Keep Zustand for orchestration read model and UI state.
- Keep a narrow `desktopBridge` adapter for dialogs, menus, external links, theme, and updater APIs.
- Do not introduce Suspense in this migration. Atom-backed hooks should keep returning `data`, `error`, `isLoading|isPending`, `refresh`, and `mutateAsync`-style surfaces so component churn stays low.
## Target Architecture
- Extract the websocket `RpcClient.Protocol` layer from [wsTransport.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsTransport.ts) into `rpc/protocol.ts`.
- Define one `AtomRpc.Service` for `WsRpcGroup` in `rpc/client.ts`.
- Add `platform/desktopBridge.ts` as the only browser/desktop facade.
- Remove from web by the end: [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts), [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts), [wsNativeApiState.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiState.ts), [wsNativeApiAtoms.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiAtoms.tsx), [wsRpcClient.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsRpcClient.ts), and all `*ReactQuery.ts` modules.
## Phase 1: Infrastructure First
1. Extract the shared websocket RPC protocol layer from [wsTransport.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsTransport.ts) without changing behavior.
2. Build the AtomRpc client on top of that layer.
3. Add one temporary `runRpc` helper for imperative handlers that still want `Promise` ergonomics; it must call the AtomRpc service directly and must not reintroduce a facade object.
4. Replace manual registry wiring with one app-level registry provider based on `@effect/atom-react`.
5. Land this as a no-behavior-change PR.
## Phase 2: Replace `wsNativeApi`-Owned Push State
1. Migrate welcome/config/provider/settings state first, because it is already atom-shaped and is the lowest-risk way to delete `wsNativeApi` responsibilities.
2. Replace [wsNativeApiState.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiState.ts) with `rpc/serverState.ts`, updated directly from `subscribeServerLifecycle` and `subscribeServerConfig`.
3. Keep the current hook names for one PR: `useServerConfig`, `useServerSettings`, `useServerProviders`, `useServerKeybindings`, `useServerWelcomeSubscription`, `useServerConfigUpdatedSubscription`.
4. Move bootstrap side effects out of [wsNativeApiAtoms.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApiAtoms.tsx) into a new root bootstrap component mounted from [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx).
5. Delete the `server.getConfig()` fallback logic from [wsNativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.ts); snapshot fetch now lives beside the stream atoms.
2. Add `rpc/gitAtoms.ts` and `rpc/useGit.ts` with `useGitStatus`, `useGitBranches`, `useResolvePullRequest`, and `useGitMutation`.
3. Mutation settlement must invalidate scoped keys, not a global cache. `checkout`, `pull`, `init`, `createWorktree`, `removeWorktree`, `preparePullRequestThread`, and stacked actions invalidate `git:${cwd}`. Worktree create/remove also invalidates `project:${cwd}`.
4. Replace [projectReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/projectReactQuery.ts) second. `useProjectSearchEntries` must preserve current “keep previous results while loading” behavior.
5. Replace [providerReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/providerReactQuery.ts) third. Preserve current checkpoint error normalization and retry/backoff semantics inside the atom effect. Invalidate by `checkpoint:${threadId}`.
6. Defer the desktop updater until the last phase.
## Phase 4: Move Root Invalidation Off `queryClient`
1. In [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx), remove `QueryClient` usage and replace the throttled `invalidateQueries` block with throttled invalidation helpers.
- config-affecting server events touch `server-config`
## Phase 5: Remove Imperative `NativeApi` Usage
1. Create narrow modules instead of a replacement mega-facade:
-`rpc/orchestrationActions.ts`
-`rpc/terminalActions.ts`
-`rpc/gitActions.ts`
-`rpc/projectActions.ts`
-`platform/desktopBridge.ts`
2. Migrate direct [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts) callers by domain, not file-by-file: git-heavy components first, then orchestration/thread actions, then shell/dialog helpers.
3. After the last caller is gone, delete [nativeApi.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/nativeApi.ts) and the `window.nativeApi` fallback entirely.
4. In the final cleanup PR, remove `NativeApi` from [ipc.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/packages/contracts/src/ipc.ts) if nothing outside web still needs it.
## Phase 6: Remove React Query Completely
1. Delete `@tanstack/react-query` from `apps/web/package.json`.
2. Remove `QueryClientProvider` and router context from [router.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/router.ts) and [__root.tsx](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/routes/__root.tsx).
3. Replace [desktopUpdateReactQuery.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/lib/desktopUpdateReactQuery.ts) with a writable atom plus `desktopBridge.onUpdateState`.
4. Delete the old query-option tests.
## Public Interfaces And Types
- Preserve the current server-state hook names during the transition.
- Do not expose raw AtomRpc clients to components.
- Do not add Suspense as part of this migration.
- Final boundary is direct RPC for server features plus `desktopBridge` for local desktop features.
## Test Plan
- Add unit tests for `rpc/serverState.ts`: snapshot bootstrapping, stream replay, provider/settings updates.
- Add unit tests for git/project/checkpoint hooks: loading, error mapping, retry behavior, invalidation, keep-previous-result behavior.
- Update the browser harness in [wsRpcHarness.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/test/wsRpcHarness.ts) to assert direct RPC + atom behavior instead of `__resetNativeApiForTests`.
- Replace [wsNativeApi.test.ts](/Users/julius/.t3/worktrees/codething-mvp/effect-http-router/apps/web/src/wsNativeApi.test.ts), `gitReactQuery.test.ts`, `providerReactQuery.test.ts`, and `desktopUpdateReactQuery.test.ts` with equivalent atom-backed coverage.
- Acceptance scenarios:
- welcome still bootstraps snapshot and navigation
- keybindings toast still responds to config stream updates
- git status/branches refresh after checkout/pull/worktree actions
- PR resolve dialog keeps cached result while typing
-`@` path search refreshes after file mutations and orchestration events
- diff panel refreshes when checkpoints arrive
- desktop updater still reflects push events and button actions
## Assumptions And Defaults
- Zustand stays in scope; only `react-query` is being removed.
-`desktopBridge` remains the only non-RPC boundary.
- The migration lands as 5-6 small PRs, each green independently.
- Invalidations are explicit and scoped; do not recreate a global cache client abstraction.
- Orchestration recovery/order logic stays as-is; only the data-fetching and mutation layer changes.
- Topic: `orchestration_events.stream_id` vs event runtime `aggregateId` naming.
- Decision: persist canonical DB column name `stream_id`; map to runtime `aggregateId` where needed in decider/projector code.
### A2
- Topic: JSON column typing in SQLite for `payload`, `metadata`, projection payload/files, runtime cursor/payload.
- Decision: store as `TEXT` JSON with strict encode/decode schemas at boundaries.
### A3
- Topic: `snapshotSequence` dependency set for min-sequence computation.
- Decision: include all projectors used to construct snapshot payload (`projects`, `threads`, `messages`, `activities`, `sessions`, `turns`, `checkpoints`, `pending_approvals`).
### A4
- Topic: no-gap handoff mechanism in `7.4.7`.
- Decision: implement explicit sequence fence semantics at snapshot time; replay starts from fence `fromSequenceExclusive`.
# Use `bun add <name>@<url>` instead of `bun add <url>`. Without an
# explicit name, bun's resolver hits a DependencyLoop bug when the
# consumer already has the same package name resolved from npm
# (oven-sh/bun#5789, oven-sh/bun#17946). The aliased form bypasses
# the buggy reconciliation path and works on fresh and existing
# projects alike.
BODY=$(printf '%s\n\nInstall the packages built from this commit:\n\n**alchemy**\n```sh\nbun add alchemy@https://pkg.ing/alchemy/%s\n```\n\n**@alchemy.run/better-auth**\n```sh\nbun add @alchemy.run/better-auth@https://pkg.ing/@alchemy.run/better-auth/%s\n```\n\n**@alchemy.run/pr-package**\n```sh\nbun add @alchemy.run/pr-package@https://pkg.ing/@alchemy.run/pr-package/%s\n```\n' "$MARKER" "$SHORT_SHA" "$SHORT_SHA" "$SHORT_SHA")
Alchemy Effect is an Infrastructure-as-Effects (IaE) framework that extends Infrastructure-as-Code (IaC) by combining business logic and infrastructure config into a single, type-safe program expressed as Effects.
It includes a core IaC engine built with Effect. Effect provides the foundation for type-safe, composable, and testable infrastructure programs. It brings errors into the type-system and provides declarative/composable retry logic that ensure proper and reliable handling of failures.
# Concepts
- **Cloud Provider** - a cloud provider that offers a set of Services, e.g. AWS, Azure, GCP, Cloudflare, Stripe, Planetscale, Neon, etc.
- **Service** - a collection of Resources, Functions, and Bindings offered by a Cloud Provider.
- **Resource** - a named entity that is configuted with "Input Properties" and produces "Output Attributes". May or may not have Binding Contract.
- **Input Properties** - the properties passed as input to configure a Resource. Otherwise known as the "desired state" of the Resource.
- **Output Attributes** - the attributes produced by a Resource. Otherwise known as the "current state" of the Resource.
- **Stable Properties** - properties that are not affected by an Update, e.g. the ID or ARN of a Resource.
- **Function** (aka. **Runtime**) - a special kind of Resource that includes a runtime implementation expressed as a Function producing an `Effect<A, Err, Req>`. The `Req` type captures runtime dependencies, from which Infrastructure Dependencies are inferred.
- **Resource Provider** (see [Provider](./packages/alchemy/src/Provider.ts))
A Resource Provider implements the following Lifecycle Operations:
- **Diff** - compares new props with old props and determines if the Resource needs to be updated or replaced. For updates, it can also specify a list of Stable Properties that will not be changed by the update.
- **Read** - reads the current state of a Resource and returns the current Output Attributes. May return `Unowned(attrs)` to signal an existing-but-foreign resource that the engine should refuse to take over unless `--adopt` is set.
- **Pre-Create** - an optional operation that creates a stub of a Resource before reconcile runs. Used to resolve circular dependencies — e.g. Function A and B depend on each other, so we create a stub of Function A first and then `reconcile` later wires up the real dependency.
- **Reconcile** - converges a Resource's actual cloud state to the desired state described by the new Input Properties. Called for both first-time provisioning and subsequent updates. The provider receives `output` (current Attributes) and `olds` (previous Props) which may both be `undefined` on a greenfield create, both defined on an update, or `output !== undefined && olds === undefined` on an adoption. See the **Reconciler doctrine** section below for the required shape.
- **Delete** - deletes an existing Resource. It must be designed as idempotent because it is always possible for state persistence to fail after the delete operation is called. If the resource doesn't exist during deletion, it should not be considered an error.
- **Capability** - a runtime requirement of a Function (e.g. require `SQS.SendMessage` on a `SQS.Queue`). Each Capability is split into two parts: a `Binding.Service` (runtime SDK wrapper) and a `Binding.Policy` (deploy-time IAM/binding attachment).
- **Binding.Service** - an Effect Service that wraps an SDK client and exposes a `.bind(resource)` method returning a typed callable for runtime use. Provided as a Layer on the **Function** Effect so it gets bundled into the Lambda/Worker. See [Binding](./packages/alchemy/src/Binding.ts).
- **Binding.Policy** - an Effect Service that runs only at deploy time to attach IAM policies (AWS) or bindings (Cloudflare) to a Function's role/config. At runtime, `Binding.Policy` uses `Effect.serviceOption` so it gracefully becomes a no-op when the layer is not provided. Policy layers are provided on the **Stack** via `AWS.providers()()`, not on the Function.
- **Binding** - data attached to a Resource via `resource.bind(data)`. A Binding is a `{ context: PolicyContext, data: BindingData }` tuple that is collected on the Stack during plan/deploy. Bindings enable circular references between Resources — the `Binding.Policy` calls `ctx.bind({ policyStatements: [...] })` on the target Function, which records the binding data on the Stack. The Resource Provider then receives the resolved binding data in its `reconcile` lifecycle operation via the `bindings` parameter.
- **Binding Contract** - the shape of data a Resource accepts from Bindings. For example, a Lambda Function accepts `{ env?: Record<string, any>, policyStatements?: PolicyStatement[] }` because it needs environment variables and IAM policies. A Cloudflare Worker accepts `{ bindings: Worker.Binding[] }` for its native binding system. The Binding Contract is declared as the fourth type parameter on the `Resource` interface. See [Lambda Function](./packages/alchemy/src/AWS/Lambda/Function.ts) and [Cloudflare Worker](./packages/alchemy/src/Cloudflare/Workers/Worker.ts).
- **Dependency** - Resources depend on other Resources through two mechanisms:
- Output Properties of one Resource passed as Input Properties to another Resource (non-circular, directed acyclic graph)
- Bindings that attach data (IAM policies, env vars, Cloudflare bindings) from one Resource to another, enabling circular references between Resources.
- **Output** - a reference to (or derived from) a Resource's "Output Attributes". E.g. Bucket.bucketArn
- **Stack** - a collection of Resources, Functions, and Bindings that are deployed together.
- **Stack Name** - the name of a Stack, e.g. `my-stack`
- **Stage** - the stage of a Stack, e.g. `dev`, `prod`, `dev-sam`
- **Stack Instance** - a deployed instance of a Stack+Stage
- **Resource Type** - the type of a Resource, e.g. `Bucket`, `Instance`
- **Physical Name** - a unique name for a Resource, e.g. `my-bucket-1234567890`. It is usually best to generate them using the built-in createPhysicalName utility function which generates
- **Logical ID** - the logical ID identifying a resource within a Stack, e.g. `my-bucket`. It is stable across creates, updates, deletes and replaces.
- **Instance ID** - a unique identifier for an instance of a Resource. It is stable across creates, updates and deletes. It changes when a resource is replaced. It is truncated and used as the suffix of the Physical Name.
- **Event Source** - a special kind of Binding between a Function and a Resource that produces events that invoke the Function, e.g. `SQS.QueueEventSource`. Event Sources are implemented as Binding.Service + Binding.Policy pairs, where the attach logic creates/updates the event source mapping via the cloud provider API.
- **Replacement** - the process of replacing a Resource with a new one. A new one is created, downstream dependencies are updated with the new reference, and then the old one is deleted. Or, the old one is deleted first and then the new one is created.
- **Dependency Violation** - an error that some APIs call when an operation cannot be performed because a dependency is not met. E.g. you cannot delete an EIP until the NAT Gateway it is attached to is deleted. Lifecycle operations typically retry Dependency Violations.
- **Eventual Consistency** - create/update/delete operations can be eventually consistent leading to a variety of failure modes. For example, a Resource may be created but not yet available for use, or a Resource may be deleted but still appear in the console. Errors caused by eventual consistency should be retried, and lifecycle operations/tests should be carefully designed to wait for consistency before proceeding.
- **Retryable Error** - an error that can be retried. E.g. a Dependency Violation, Eventual Consistency Error, Transient Failure, etc.
- **Non-Retryable Error** - an error that cannot be retried. E.g. a Validation Error, Authorization Error, etc.
- **Retry Policy** - a policy for retrying errors. E.g. a fixed delay, exponential backoff, max retries, while some condition is true, or until some condition is true/false, etc.
# File System Conventions
Each Service's Resources follow the same pattern. Resource contract and provider are co-located in the same file. Capabilities (Binding.Service + Binding.Policy) are in separate files named after the capability.
```sh
# source files
packages/alchemy/src/{Cloud}/{Service}/index.ts # re-exports all resources and capabilities
**Source of truth:** The source code is the single source of truth for all API documentation. JSDoc comments in `packages/alchemy/src/**/*.ts` are extracted and used to generate the public API reference markdown.
:::warning
**Never edit the generated markdown files** under `website/src/content/docs/providers/{Cloud}/`. They are overwritten on every regeneration.
To "update the docs", edit the JSDoc on the source `.ts` file (resource-level JSDoc on the exported `const`, plus field-level JSDoc on each prop/attribute) and re-run the generator. There is no separate doc file to update.
:::
**How to generate docs:**
```sh
bun generate:api-reference # -> website/src/content/docs/providers/{Cloud}/{Resource}.md
```
This is the only doc generator that produces user-facing output. ([scripts/generate-api-reference.ts](./scripts/generate-api-reference.ts)) does the following:
1. Discovers resource files in `packages/alchemy/src/{Cloud}/{Service}/`
2. Parses TypeScript with `ts-morph`
3. Extracts the resource-level summary plus `@section` / `@example` blocks from JSDoc
4. Writes one markdown file per resource at `website/src/content/docs/providers/{Cloud}/{Resource}.md`
After editing JSDoc on a resource, run `bun generate:api-reference` to refresh the website docs.
**Writing good documentation:** When adding or updating a resource, ensure all Props and Attrs have JSDoc comments:
```typescript
export interface BucketProps {
/**
* Name of the bucket. If omitted, a unique name will be generated.
* Must be lowercase and between 3-63 characters.
*/
bucketName?: string;
/**
* Whether to delete all objects when the bucket is destroyed.
* @default false
*/
forceDestroy?: boolean;
}
```
The `@default` tag is used to document default values and will appear in the generated documentation.
### Examples and Sections (IMPORTANT)
**Examples are critical for documentation.** Every resource should have examples demonstrating common use cases. Use `@section` and `@example` JSDoc tags on the main Resource export to organize examples into a navigable table of contents.
**Format:**
- `@section <Section Title>` - Creates a heading in the Examples section and adds an entry to the Quick Reference table of contents
- `@example <Example Title>` - Creates a subheading for a specific code example (must follow a `@section`)
- Code blocks inside examples use standard markdown fenced code blocks (` `)
1. A "Quick Reference" section with links to each `@section`
2. An "Examples" section with organized code examples under each section heading
**Best practices for examples:**
- Start with the simplest use case and progress to more complex ones
- Include examples for all major capabilities (GetObject, PutObject, etc.)
- Show real-world patterns like error handling, combining with other resources
- Use descriptive titles that explain what the example demonstrates
# Workflow
Development of Alchemy-Effect Resources is heavily pattern based. Each Service has many Resources that each have 0 oor more Capabilities and Event Sources. When working on a new Service, the following steps should be followed.
1. Research the AWS Service and identify its Resources, Identifier Types, Structs, Capabilities, and Event Sources. Refer to the corresponding Terraform Provider, Pulumi Provider, and CloudFormation docs for that service (use the provided tools specifically for searching these docs for services and resources).
- Output Attributes (for each attribute: Name, Type, Description)
3. Document each of the Capabilities and Bindings
Include the following information:
- Capability Name, e.g. `GetObject`, `PutObject` (it maps 1:1 with an AWS API)
- Constraints (e.g. `Key`)
- IAM Policies (how the capability maps to an IAM Policy, e.g. Effect: Allow, Action: s3:GetObject, Resource: `arn:aws:s3:::${bucketName}/${Key}`)
- Environment Variables (what environment variables should be added to a Lambda Function so that it can access the capability, e.g. `BUCKET_NAME`, `BUCKET_ARN`, `QUEUE_URL`, `QUEUE_ARN`, etc.)
4. Research and design each of the Lifecycle Operations
- **Diff** - identify which properties are always stable across any update, which properties change conditionally depending on new and old values, which properties trigger a replacement. This is usually just a distinct list, but can sometimes require if-this-then-that logic. Document it explicitly and exhaustively. Cross-reference with AWS CloudFormation, Terraform Provider and Pulumi Provider docs.
:::warning
You should almost never use `no-op` in the Diff. No-op should be explicitly designed as a way to say "i know this property changed, but i don't want it to trigger an update". This is an edge-case and not the norm. Usually you want diff to return `undefined` or `void` to let the engine apply the default update logic. Diff is usually just use as an optimization or to identify replacement instead of update.
:::
- **Read** - determine which API calls are required to read the Output Attributes of a Resource from the Cloud Provider state (otherwise known as refresh or synchronize resource state). This is usually a single Get{Resource} API call, but can be a complex set of calls depending on the Service. Read can also be called without the current Output Attributes because of past state persistence failures. These cases are handled by computing the deterministic Physical Name and looking it up or by searching for Resources using tags (if the Cloud Provider supports it). Read may return `Unowned(attrs)` when the resource exists but lacks our ownership tags, signalling the engine to gate adoption behind `--adopt` or `adopt(true)`.
- **Pre-Create** - determine if the Resource needs a pre-create operation. This is usually only the case for the special Function/Runtime Resources like AWS Lambda Functions. If it is required, then document which API call(s) should be called and what the empty (unit) input properties are. E.g. a Lambda Function takes a simple script that exports a no-op handler function.
- **Reconcile** - determine the API calls needed to converge the cloud's actual state to the desired state described by the new Input Properties. Reconcile must be a single flow that works whether the resource is missing (greenfield create), pre-existing under our ownership (update), or freshly adopted (`output` defined but `olds` absent). See the **Reconciler doctrine** section below.
- **Delete** - determine which APIs should be called and in what order to delete an existing Resource. Delete should be idempotent so that if the resource has already been deleted, it is not considered an error. It is common for deletions to fail because of Dependency Violations or Eventual Consistency Errors. These are not always called Dependency Violations in the API docs, so attention should be paid to investigating each API's possible error codes and how they should be handled by the Delete operation. Should we retry for a period of time, indefinitely, or fail immediately?
# Reconciler doctrine
The provider's `reconcile` function replaces the legacy `create` + `update` pair. It runs every time the engine wants to make the cloud match the desired state — whether that's the first time the resource is being provisioned, a routine update, or a takeover after `read` returned an existing cloud resource.
It receives `output: Attributes | undefined` and `olds: Props | undefined`:
| defined | defined | Routine update — engine-owned resource |
| defined | `undefined` | Adoption — engine adopted via `read` |
A reconciler MUST work correctly for all three combinations. It MUST NOT branch the body on `output === undefined` and run different code paths for "create" vs "update". That pattern is just rename-and-branch and re-introduces every assumption the old `create`/`update` split made. Instead, write one flow:
```
1. Observe — derive the physical identifier; read live cloud state via getX/describeX
2. Ensure — if the resource is missing, call createX. Catch AlreadyExists/ConflictException
as a race and continue. Wait for active state if applicable.
3. Sync — for each mutable aspect (settings, sub-resources, tags, policy):
- read OBSERVED cloud state (not olds)
- compute desired state from news + bindings
- diff observed against desired
- apply only the delta API call (skip the API entirely on no-op)
4. Return — re-read final state if needed; return the fresh Attributes shape
```
Key invariants:
- **Observation > assumption.** Cloud state is authoritative. `olds` is at most a hint to skip a no-op API call; it is never the source of truth for what's actually deployed.
- **Each sync step is independently idempotent.** Crash mid-reconcile, re-run, you converge.
- **`output` is treated as a cache** for stable identifiers (physical name, ARN, immutable id). It is NOT a guarantee that the resource still exists. If it doesn't, observation falls through to "missing" and ensure recreates.
- **`AlreadyExists`/`NotFoundException`/`ResourceInUseException`-style errors are caught**, not propagated — they're races or eventual-consistency, not failures.
- **Tags use observed cloud tags as the diff baseline**, not `olds.tags` or `output.tags`. Adoption may bring you a resource with foreign tags that need to be reconciled.
:::warning
**Do not write `if (output === undefined) { /* create body */ } else { /* update body */ }`.** That is rename-and-branch, not reconciliation. The reconciler's body is one observe-ensure-sync flow that produces correct cloud state regardless of starting point.
:::
The canonical reference reconcilers cover the common shapes:
- [S3 Bucket](./packages/alchemy/src/AWS/S3/Bucket.ts) — uses `ensureBucketExists` + `syncBucketTags` + `syncBucketPolicy` helpers; each helper is itself a tiny reconciler.
- [SQS Queue](./packages/alchemy/src/AWS/SQS/Queue.ts) — observe via `getQueueUrl`, ensure via `createQueue` (tolerates `QueueNameExists` race), sync attributes by diffing `getQueueAttributes` against desired, sync tags.
- [Kinesis Stream](./packages/alchemy/src/AWS/Kinesis/Stream.ts) — many mutable aspects (mode, shards, retention, encryption, metrics), each its own observed-vs-desired sync block.
- [EC2 Vpc](./packages/alchemy/src/AWS/EC2/Vpc.ts) — auto-assigned id, observe via `describeVpcs([output.vpcId])` with NotFound fallback to create, sync DNS attrs by reading `describeVpcAttribute`, sync tags from observed `vpc.Tags`.
- [Cloudflare Worker](./packages/alchemy/src/Cloudflare/Workers/Worker.ts) — non-AWS API; the underlying `putWorker` is a true upsert, so reconcile observes existing settings and delegates.
Existence-only resources (Lambda Permission, EC2 Route, EC2 RouteTableAssociation, IAM AccessKey, etc.) have nothing mutable beyond their identity. Their reconciler is just observe → if missing, create. There is no sync step.
5. Research and design the test cases for each resource. Test cases can be single or multi-step. Single-step test cases are just testing a single create success or failure mode. Multi-step cases are testing a sequence of operations, starting with create and then updating or replacing the resource multiple times. Test cases should be designed to be exhaustive and cover all possible success and failure modes, starting from simple happy paths to long, complicated aggregate (including other resources) smoke tests.
6. Implement the Resource contract and Provider in `packages/alchemy/src/{Cloud}/{Service}/{Resource}.ts`.
The Resource contract (Props, Attributes, Binding Contract) and the Resource Provider (lifecycle operations) are co-located in the same file.
Read through the established examples to understand the pattern:
For Resources that accept Bindings (like Lambda Function), include a fourth type parameter for the Binding Contract:
```ts
export interface Function extends Resource<
"AWS.Lambda.Function",
FunctionProps,
{
functionArn: string;
functionName: string;
functionUrl: string | undefined;
roleName: string;
roleArn: string;
},
{
env?: Record<string, any>;
policyStatements?: PolicyStatement[];
}
> {}
```
:::tip
Some Input Property types are wrapped in an `Input<T>`, but not all are. Only properties that may need to be references to another resource's Output Attribute. E.g. common use-cases are `Input<VpcId>`, `Input<QueueUrl>`, `Tags: Record<string, Input<string>>`.
:::
:::warning
For fields like `name: string`, `bucketName: string`, `bucketPrefix: string`, you should not use `Input<string>` because these properties need to be statically knowable in the `diff` function.
:::
7. Implement the Capabilities as `Binding.Service` + `Binding.Policy` pairs in `packages/alchemy/src/{Cloud}/{Service}/{Capability}.ts`.
Each capability has two parts:
- **`Binding.Service`** — runtime SDK wrapper, provided on the Function Effect (bundled into Lambda/Worker)
- **`Binding.Policy`** — deploy-time IAM policy attachment, provided on the Stack via `AWS.providers()()` (never bundled)
Read through the established capabilities to understand the pattern:
The `Binding.Policy` implementation calls `ctx.bind({ policyStatements: [...] })` on the target Function, which records binding data on the Stack. The `Binding.Service` implementation resolves the Policy via `yield* Policy(resource)`, then returns a typed callable that wraps the SDK client. At runtime, the Policy is not provided and becomes a no-op.
Each capability exports four things:
```ts
// 1. The Binding.Service class
export class PutRecord extends Binding.Service<...>()("AWS.Kinesis.PutRecord") {}
// 2. The Binding.Service Live layer (provided on Function Effect)
### Runtime-only methods: color with `Alchemy.RuntimeContext`
The runtime callable returned by a `Binding.Service` (the inner Effect inside `.bind(resource)`'s return) **must** declare `Alchemy.RuntimeContext` as a requirement. This is how Alchemy models "this code can only run inside a deployed Function/Worker" at the type level — analogous to a colored function.
```ts
import type { RuntimeContext } from "../../RuntimeContext.ts";
export class GetItem extends Binding.Service<
GetItem,
<T extends Table>(
table: T,
) => Effect.Effect<
(
request: GetItemRequest,
) => Effect.Effect<
DynamoDB.GetItemOutput,
DynamoDB.GetItemError,
RuntimeContext // ← runtime-only
>
>
>()("AWS.DynamoDB.GetItem") {}
```
Rules:
- **Outer Effect** (the `bind(resource)` setup) runs at the Function's init phase. It does NOT require `RuntimeContext`.
- **Inner Effect** (the actual SDK invocation) only makes sense inside a running Function. It MUST require `RuntimeContext`.
- Resolve cloud-environment services (`WorkerEnvironment`, AWS SDK clients, etc.) once during Layer construction and close over them. Do NOT leak `WorkerEnvironment` / `Lambda.FunctionEnvironment` onto the runtime callable — that couples downstream service code to a specific cloud and breaks Layer encapsulation. The Function/Worker runtime satisfies `RuntimeContext` automatically.
- The implementation can return `Effect.Effect<A, E>` without explicitly providing `RuntimeContext` (it's contravariant in `R`); just declare it on the interface.
Why this matters: consumers can build cloud-agnostic services on top of bindings using `Layer.effect(Tag, ...)` without polluting their service interface with `WorkerEnvironment`. See [Layers concept](./website/src/content/docs/concepts/layers.mdx).
After implementing, register the Policy in `AWS.providers()()`:
- Add the `*PolicyLive` layer to `bindings()` in [Providers.ts](./packages/alchemy/src/AWS/Providers.ts)
- Re-export from the service's `index.ts`
:::tip
If you need to know what AWS region or account ID the resource is being created/updated in, you can use this inside any of the lifecycle operations.
```ts
const region = yield * Region;
const account = yield * Account;
```
:::
:::warning
You should favor getting the region/account INSIDE the lifecycle operations instead of inside the Layer effect like this because then it's scoped to the resource isntead of the resource provider:
Do not use `Effect.orDie` in the lifecycle operations since this will crash the whole IaC engine.
:::
:::warning
**Never use `async`/`await`, raw `Promise`, `node:fs/promises`, `node:fs`, `node:os`, or `pathe` directly in resource code.** Always use the Effect platform services so that effects remain composable, traceable, retryable, and testable:
Sync, CPU-only Node APIs (e.g. `crypto.createHash().update().digest()`, `process.cwd()`, `Buffer`, `TextEncoder`) must still be wrapped in `Effect.sync(() => ...)` (or `Effect.try` if they can throw) so the call participates in the Effect runtime — tracing, interruption, and error channels. Don't call them as bare expressions inside `Effect.gen`.
This applies to **lifecycle operations, helpers, AND tests**. Tests must use `FileSystem.FileSystem`/`Path.Path` for any file/path access (see [Database.test.ts](./packages/alchemy/test/Cloudflare/D1/Database.test.ts) for the pattern).
:::
:::tip
If a Resource supports tags, you should always include the internal Alchemy tags to brand the resource with the app, stage and logical ID so that we can "know" that we created it and are responsible for it.
Do not roll your own tag diffing logic, always use `diffTags` from [Tags.ts](./packages/alchemy/src/Tags.ts), and diff against **observed cloud tags** (not `olds.tags` or `output.tags`). Adoption can hand you a resource whose tags don't match what we last persisted.
// Option 3. use `upsert` only if the API doesn't expect you to remove tags (only PUT/UPDATe)
const { upsert } = diffTags(oldTags, newTags);
```
:::
9. Implement the test cases in `packages/alchemy/test/{Cloud}/{Service}/{Resource}.test.ts`.
Read through the established test cases before continuing so that you understand the pattern and structure of the test cases.
- [S3 Bucket Test Cases](./test/AWS/S3/Bucket.test.ts)
- [SQS Queue Test Cases](./test/AWS/SQS/Queue.test.ts)
- [Lambda Function Test Cases](./test/AWS/Lambda/Function.test.ts)
- [Kinesis Stream Test Cases](./test/AWS/Kinesis/Stream.test.ts)
- [DynamoDB Table Test Cases](./test/AWS/DynamoDB/Table.test.ts)
- [VPC Test Cases](./test/AWS/EC2/Vpc.test.ts)
- [Subnet Test Cases](./test/AWS/EC2/Subnet.test.ts)
:::warning
Never use `Date.now()` when constructing the physical name of a resource. You should either:
1. Do not proide a name and rely on the resource provider to generate a unique name for you from the app, stage and logical ID.
2. Construct a deterministic one unique to each test case. But it should be the same on each subsequent run of the test case.
:::
3. Consider implementing an aggregate Smoke test that brings together multiple resources that are often used together.
See the [VPC Smoke Test](./test/AWS/EC2/Vpc.smoke.test.ts) for an example.
11. Add the resource-level JSDoc (`@section` + `@example` blocks) and field-level JSDoc on each prop/attribute on the source `.ts` file. Then run `bun generate:api-reference` to refresh `website/src/content/docs/providers/{Cloud}/{Resource}.md`. Do NOT manually edit the generated markdown.
# Test Fixtures for Effect-Native Workers / Functions
To test runtime behavior of an Effect-native Worker, Workflow, Lambda, etc., write a **fixture** that defines the Worker/Function with the bindings under test and exposes one HTTP route per behavior, then write a **test** that deploys the fixture once via `beforeAll` and drives it over HTTP.
## File system layout
Put fixtures in a `fixtures/` directory next to the test file. Each test suite owns its own fixtures — never reach across suites:
Compose a `Stack` that deploys the fixture, share one deploy across the file with `beforeAll`/`afterAll`, drive it via `HttpClient`, and retry the first request through edge propagation:
```ts
// Service.test.ts
import * as Alchemy from "@/index.ts";
import * as Cloudflare from "@/Cloudflare";
import * as Test from "@/Test/Vitest";
import { expect } from "@effect/vitest";
import * as Effect from "effect/Effect";
import * as Schedule from "effect/Schedule";
import * as HttpClient from "effect/unstable/http/HttpClient";
- `beforeAll(deploy(Stack))` returns a handle (`stack` above) that every `test` body can `yield*` to get the stack outputs.
- `afterAll.skipIf(!!process.env.NO_DESTROY)(destroy(Stack))` is the standard cleanup — set `NO_DESTROY=1` locally to keep the deployment around between runs while iterating.
- Always retry the first request (`Schedule.exponential("500 millis")`) — fresh workers.dev URLs and Lambda function URLs take a few seconds to start serving 200s.
- For POST: use `client.post(url)` for empty bodies, or `HttpClient.execute(HttpClientRequest.post(url).pipe(HttpClientRequest.bodyJsonUnsafe(body)))` for typed bodies.
- **Never use `while (Date.now() < deadline)` loops to poll** for an async side effect (a workflow status, a cron fire, a queue drain, eventual-consistency read, etc.). Use `Effect.repeat` with a `Schedule` and an `until` predicate so the polling participates in the Effect runtime — tracing, interruption, and error propagation work correctly, and the intent is declarative. Cap iterations with `times: N` (or a bounded schedule) so the test fails fast instead of running until the vitest timeout:
```ts
// good — declarative, bounded, interruption-safe
const value = yield* fetchValue.pipe(
Effect.repeat({
schedule: Schedule.spaced("5 seconds"),
until: (v) => v.ready,
times: 36,
}),
);
// bad — opaque loop, ignores interruption, leaks into vitest timeout
let value: Value | undefined;
const deadline = Date.now() + 180_000;
while (Date.now() < deadline) {
value = yield* fetchValue;
if (value.ready) break;
yield* Effect.sleep("5 seconds");
}
```
See [CronEventSource.test.ts](./packages/alchemy/test/Cloudflare/Workers/CronEventSource.test.ts) for a real-world example (polling a DO via the worker's `/times` route until the cron handler fires).
## Reference implementations
- Cloudflare AiGateway — [worker fixture](./packages/alchemy/test/Cloudflare/AiGateway/worker.ts) + [test](./packages/alchemy/test/Cloudflare/AiGateway/AiGateway.test.ts) (the deploy+fetch case lives at the bottom of the file)
- Cloudflare Cron Trigger — [worker + DO fixture](./packages/alchemy/test/Cloudflare/Workers/fixtures/cron-worker.ts) + [test](./packages/alchemy/test/Cloudflare/Workers/CronEventSource.test.ts) (cron handler writes to a DO; test polls a fetch route with `Effect.repeat` until the scheduled handler fires)
- AWS Lambda (DynamoDB bindings) — [Lambda fixture](./packages/alchemy/test/AWS/DynamoDB/handler.ts) + [test](./packages/alchemy/test/AWS/DynamoDB/Bindings.test.ts) (one `describe("<BindingName>")` per binding, all driving the same deployed Lambda)
# Spec-Driven Service Bring-Up
Use @processes/AWS.md as the source of truth for bringing a single AWS service from zero to full coverage.
That process covers:
- deriving resources, bindings, event sources, and helpers from distilled
- the audit-driven implementation loop
- deterministic checks for registration and binding test coverage
- Lambda fixture testing conventions
- learned conventions like no auto-marshalling and one `describe("<BindingName>")` block per binding
Keep `AGENTS.md` high-level and update @processes/AWS.md when the process evolves.
When a canonical resource needs mutable event-source configuration and there is any chance of circularity, prefer a resource binding contract over a plain input prop. DynamoDB Streams is the reference case: `Table` owns the actual stream state, while `streams(table)` injects that state via bindings and the runtime-specific layer handles the subscription mechanics. See @processes/AWS.md for the DynamoDB Streams case study.
# Build and Type Checking
Always run type checking before committing changes:
```bash
bun tsc -b
```
This runs the TypeScript compiler in build mode, which checks all projects in the workspace. This is critical because CI will fail if there are type errors.
Tutorials under `website/src/content/docs/tutorial/` are **step-by-step and granular**: every code snippet introduces exactly **one** new thing, followed by a short prose explanation of just that thing. Each step gets its own `##` heading.
**Anti-pattern** — one snippet that adds multiple distinct changes, followed by a numbered list or bullet list explaining each:
````md
## Bind the DO to the Worker
```diff lang="typescript"
+import Counter from "./counter.ts";
+import { HttpServerRequest } from "...";
Effect.gen(function* () {
+ const counters = yield* Counter;
return {
fetch: Effect.gen(function* () {
+ const request = yield* HttpServerRequest;
+ if (request.url.startsWith("/counter/") && ...) {
+ const next = yield* counters.getByName(name).increment();
+ return HttpServerResponse.text(String(next));
+ }
return HttpServerResponse.text("Hello!");
}),
};
})
```
Two things just happened:
1. `yield* Counter` registers the DO ...
2. `counters.getByName(name)` returns a typed stub ...
````
**Correct** — split into one heading per step, each with one snippet and one explanation:
````md
## Bind the DO to the Worker
```diff lang="typescript"
+import Counter from "./counter.ts";
Effect.gen(function* () {
+ const counters = yield* Counter;
...
})
```
`yield* Counter` registers the DO with the Worker (binding + class-migration metadata) and hands you the namespace.
## Call the DO from `fetch`
```diff lang="typescript"
+import { HttpServerRequest } from "...";
fetch: Effect.gen(function* () {
+ const request = yield* HttpServerRequest;
+ if (request.url.startsWith("/counter/") && ...) {
+ const next = yield* counters.getByName(name).increment();
+ return HttpServerResponse.text(String(next));
+ }
return HttpServerResponse.text("Hello!");
})
```
`counters.getByName(name)` returns a typed stub — `increment()` and `get()` round-trip through Cloudflare's RPC machinery.
````
Rules of thumb:
- If you find yourself writing "Two/three things just happened", "A few things are happening here", or a numbered/bulleted list explaining separate parts of a single snippet — **split the snippet**.
- One concept ⇒ one heading ⇒ one diff snippet ⇒ one explanation paragraph (no bullets).
- Bullet/numbered lists are fine when they describe a recap, prerequisites, or genuinely list-shaped content (e.g. "the Worker now handles two routes: PUT and GET" at the end). They are **not** fine as a substitute for splitting a compound snippet.
- A single API call that internally does several things (e.g. `Cloudflare.upgrade()`) doesn't need splitting — describe its behavior in prose.
- Use `diff lang="typescript"` blocks so each step shows what's added on top of the previous step.
# Pull Request Conventions
When you automatically open a PR, it MUST follow this structure:
- **Title**: Use conventional commit format (e.g. `fix(website): mobile theme metas`, `feat(aws/s3): add bucket lifecycle rules`).
- **Description heading levels**: NEVER use `#` or `##` in the PR description. The smallest heading allowed is `###`. The PR description must NOT begin with its own title heading — GitHub already renders the PR title above it.
- **Content**: Aim for the minimal content needed to convey the idea.
- Use simple sentences. If there are multiple discrete changes, use bullet points.
- **Prefer code snippets over prose.** A short ` ```ts ` or ` ```diff ` block showing the new/changed shape is worth more than a paragraph explaining it. Reach for code first; only add prose to fill in the "why" the snippet can't show on its own.
- Be direct and succinct. Cut adjectives, justifications, and anything that reads like marketing copy. If a sentence is restating what the diff already shows, delete it.
- **Never include a "Test plan", "Testing", or checklist of TODOs.** PR descriptions document the change, not the verification process. If something needs manual verification, follow the draft-PR rule below.
- Skip examples for trivial fixes, internal refactors, or doc-only changes.
Example PR description (good — code snippet does the talking):
````
Track which state-store backend each project uses by emitting a `state_store.init` span tagged with `alchemy.state_store.kind`.
```ts
// every Layer.effect(State, …) site now wraps construction:
Dashboard groups projects by kind from these spans (Axiom can't APL-query metric datasets).
````
- **Outstanding work / testing / review needed**: If there are outstanding steps, manual testing required, or review items, DO NOT leave a comment on the PR and DO NOT include them in the PR description. Instead:
1. Mark the PR as **draft**.
2. Tell the user (in the chat that initiated the PR creation) what is outstanding.
:::warning
**Markdown content must reach GitHub verbatim** — un-escaped backticks, fenced code blocks, etc. The reliable shape is to write the description to a file and pass `--body-file <path>` to `gh pr create` / `gh pr edit`:
```sh
# write the body to a temp file (use Write tool, not echo/cat heredoc)
gh pr edit 179 --body-file /tmp/pr-body.md
```
Do **not** inline the body via `--body "$(cat <<'EOF' ... EOF)"`. Even with a single-quoted heredoc some shells / `gh` versions still mangle backticks and backslashes; the resulting PR body ends up with literal `\`` sequences instead of inline code spans. `--body-file` sidesteps shell quoting entirely.
If you need to update an already-created PR's body, prefer `gh pr edit --body-file ...`. If that silently no-ops (older `gh` versions), fall back to `gh api -X PATCH repos/<owner>/<repo>/pulls/<n> -F body=@/tmp/pr-body.md`.
:::
The summary goes at the very top of the description as plain prose — NO heading above it, no `### Summary`, nothing. The PR title already serves as the title; do not repeat or re-title it. Only add `###` subheadings further down if the description genuinely has multiple sections worth separating.
Example PR description (good):
```
Persist the user's selected theme across reloads and fix a hero scroll glitch on mobile.
- Read theme from `localStorage` on mount before first paint
- Add `<meta name="theme-color">` per theme so mobile chrome matches
```
Example PR description (BAD — do not do this):
```
## Theme persistence fix ← no, the PR title already exists
accessSummary: Output.interpolate`Granted cluster-admin access on ${cluster.cluster.clusterName} to ${clusterAdmin.principalArn}.`,
workloadSummary: Output.interpolate`Demo workloads are declared in TypeScript and reconciled into namespace ${demoNamespace.name} on ${cluster.cluster.clusterName}.`,
Loaded 100 of 6102 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.