Skip to content
Source
Sign inSign up
pingdotgg/t3code

feat(orchestrator): introduce new orchestrator #2829

Mergedjuliusmarmingemerged 250+ commits intomain fromrefs/pull/2829/headmerged by juliusmarminge View on GitHub

juliusmarmingecommented

Important

Revert before merging into main

V2-only stopgaps that must be undone or moved when this lands. Add to this list whenever a preview-only change goes in.

  • OpenCode 2 compatibility policy on preview builds. Preview builds keep their bundled OpenCode policy (OpenCode 2 supported, 1.x "limited support") instead of main's fetched manifest, which still marks OpenCode 2 broken (#14198). Before merging: remove the preview-only override in ModelManifest, and put the V2 OpenCode policy into main's apps/server/src/provider/model-manifest.json.

Summary

  • wire orchestration V2 provider adapter registry/factory flow for Codex and Claude provider instances
  • add Claude replay/query primitives, native fork/rollback fixtures, subagent fixture coverage, and provider replay harness updates
  • update debugger model/provider picker and improve user-facing orchestration errors

Validation

  • bun fmt
  • bun lint
  • bun typecheck
  • bun run test -- src/orchestration-v2/testkit/OrchestratorReplayFixtures.integration.test.ts -t claudeAgent
  • bun run test -- src/orchestration-v2/testkit/ClaudeReplayFixtures.integration.test.ts
  • bun run test -- src/orchestration-v2/testkit/ThreadFork.integration.test.ts -t Claude

Notes

  • Draft PR for review of current branch state. Codex all-provider replay still needs schema alignment with latest app-server behavior before it can be treated as a full-suite signal.

Closes

Verified against the branch with code/commit evidence. Issues listed under High confidence have a concrete V2 mechanism (named in the note). Medium confidence items belong to a V1 race or lifecycle class that V2 structurally removes; prune any you want to re-verify after merge.

High confidence

Closes #871 — V2 mints message identity itself in orchestration-v2/IdAllocator.ts (random id scoped by thread + ordinal) instead of keying projections on provider-supplied message… Closes #4673 — V2 owns queue state in the orchestrator with explicit queue controls and pending-question commands (fix(queue): preserve and hold queued messages after restart, fea… Closes #2778 — V2 tracks delegated children in projections and wakes the parent when they finish (fix(orchestrator): Stop treating a wait timeout as a dead child (#7427), fix(orch… Closes #4952 Closes #4873 Closes #4775 Closes #4795 Closes #4710 Closes #4668 Closes #4619 Closes #4584 Closes #4561 Closes #4713 Closes #4198 Closes #4452 Closes #3797 Closes #4232 Closes #3666 Closes #3580 Closes #2785 Closes #2789 Closes #3138 Closes #1404 Closes #231 Closes #216 Closes #12940 — CursorAdapterV2 passes enableAgentRetries: true to the Cursor SDK session (apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.ts:331) Closes #12928 — AcpAdapterV2 maps ACP tool kind search to file_search and only fetch to web_search, replacing main's canonicalItemTypeFromAcpToolKind which lumps search and… Closes #12915 — The buggy schedulePromptAdmissionRecovery path lives only in V1's OpenCodeAdapter.ts, which V2 removes in favour of OpenCodeAdapterV2 plus commits 'correlate OpenCode… Closes #12904 — V2 deletes the V1 provider adapter layer that raised ProviderAdapterSessionClosedError and replaces it with ProviderSessionManager plus ProviderRuntimeRecoveryService,… Closes #12679 — The branch carries 'fix(server): preserve provider history across repeated rollbacks (#12676)' and 'fix(pi): use native forks and preserve rollback session identity',… Closes #12285 — The settledDeliveryCount cohort cap no longer exists on the branch. Closes #12100 — V2 makes queuing server-owned with a queued_turn intent released as a separate turn after the active turn (fix(web): retain server-side queuing on v2, fix(orchestratio… Closes #11968 — V2's orchestrator MCP toolkit ships t3_thread_update with action='rename' that defaults to the calling thread (apps/server/src/mcp/ThreadMetadataMcpService.ts, toolkit… Closes #11889 — V2 deletes the reactor-based path (orchestration-v2/ThreadDeletion.ts runs through the serialized orchestrator and effect worker) and lands 'fix(server): cancel pendin… Closes #11799 — V2's ProviderSessionManager release path writes runtime-request.updated with a not_resumable capability for every pending approval_request and user_input_request bound… Closes #11730 — V2's server-owned settlement rejects threads with pendingBackgroundTasks/live activity (ThreadSettlementService.isAutoSettlementCandidate) and adds 'feat(orchestrator)… Closes #11711 — V2's isAutoSettlementCandidate in orchestration-v2/ThreadSettlementService.ts returns false when pinnedAt is set (covered by ThreadSettlementService.test.ts 'excludes… Closes #11428 — V2 commit "fix: stop retained background work after a turn settles" makes ProviderTurnControlService.interrupt accept a non-running run that still has pending backgrou… Closes #10928 — orchestration-v2/RestartContinuation.ts dispatches the automatic continuation with the source run's modelSelection, whose options carry reasoningEffort, so the restart… Closes #10786 — V2 records the reply on the user_input_request turn item itself as questionAnswer (answers plus questionTextById) in Orchestrator.ts rather than synthesizing a u… Closes #10545 — V2 adds a distinct Limited stop state with resume/snooze-at-reset ("feat(v2): show provider limit stops as Limited (#12677)", "#12686", "#12687"), documented in the V2… Closes #10480 — V2 runs Cursor through the official @cursor/sdk and explicitly does not use Cursor's ACP transport for V2 execution (user-cursor.md. Closes #10099 — V2 makes settlement server-owned in ThreadSettlementService. Closes #9107 — V2 models provider-owned background work as first-class turn items (background_task/background_command/monitor in orchestrationV2.ts) with normalized post-settlement W… Closes #9047 — apps/server/src/provider/Layers/CursorAdapter.ts does not exist on V2. Closes #9029 — ClaudeAdapterV2 projects TodoWrite todos into todo_list plan items rather than depending on Task tools, surfaced by "fix(web): surface v2 todo-list plans as task progr… Closes #8946 — V2's deriveTurnFolds pulls subagent items and background work entries into the run fold and drops main's agent-spawn never-fold exclusion. Closes #8594 — The V1 ClaudeAdapter is deleted on V2. Closes #8499 — V2 models native subagents and maps nested Codex subagent threads into thread lineage, rendered by "feat(web): show subagent models and running count in Lineage" after… Closes #8091 — Task steps are projected from the persisted event log, and "fix(orchestrator): preserve task-step elapsed time across restart (#10051)" restores the list after relaunch. Closes #7328 — V2 ports title regeneration to the orchestrator with tracked contract state: 'feat(contracts): track thread title regeneration', 'feat(orchestration): port thread titl… Closes #7281 — V2 carries per-subagent model through projections: 'fix(claude): retain requested subagent models', 'fix(server): preserve Claude subagent models', 'feat(web): show su… Closes #7244 — V2 runs Cursor on the official @cursor/sdk and treats CURSOR_API_KEY as the auth method (docs/user/cursor.md prerequisites. Closes #7155 — V2's provider session recovery plus '[orchestrator-v2] fix(orchestrator): Restore Claude session continuity for resume, wake, and idle release (#3860)' rebuilds the re… Closes #7075 — V2's CodexSessionRuntime sends thread/resume with excludeTurns: true on the main resume path (apps/server/src/provider/Layers/CodexSessionRuntime.ts:751 on the branch,… Closes #5953 — V2 models native Codex subagents as separate projected child threads (feat(orchestration-v2): model native subagents. Closes #5750 — ProviderRuntimeRecoveryService reconciles non-terminal runs against actual provider inventory at startup/shutdown and retires the outbox effects tied to the lost proce… Closes #5518 — V2 tracks delegated children in projections and settlement (fix(notifications): silence subagent threads. Closes #5476 — Server-owned ThreadSettlementService returns no settlement whenever any linked pull request snapshot is missing or still open, and the guarded thread.auto-settle comma… Closes #5454 — ProviderRuntimeRecoveryService reconciles on startup/shutdown and cancels every pending runtimeRequest with a user-facing 'server restarted before the provider work co… Closes #5436 — V2 makes the follow-up queue server-owned and durable (queued messages keep order and are held across a server restart. Closes #5110 — V2 adds ProviderTextDeltaCoalescer and ThreadLiveEventCoalescer, which buffer and flush provider text deltas before persistence/publication instead of writing one dura… Closes #4650 — ClaudeAdapterV2 handles the SDK compact_boundary message and publishes usedTokens: afterTokenCount from compact_metadata.post_tokens, replacing V1's monotonic… Closes #4495 — The failing call site (context.query.setPermissionMode wrapped as turn/setPermissionMode in apps/server/src/provider/Layers/ClaudeAdapter.ts) does not exist in V2. Closes #2477 — V2 models native subagents as distinct lineage nodes with their own projection rows rather than splicing their text into the parent stream — `feat(orchestration-v2): m…

Medium confidence (under review)

Closes #4568 Closes #4766 Closes #4456 Closes #4399 Closes #3744 Closes #2921 Closes #3624 Closes #3149 Closes #2336 Closes #538 Closes #2173 Closes #2065 Closes #12926 — The 'Provider session did not survive a server restart' path exists only on main (serverRuntimeStartup.ts:346) Closes #12885 — Cross-thread session eviction is a V1 session-lifecycle race. Closes #12762 — V2 never replays the V1 event log: LegacyV1ThreadImporter reads projection_thread_messages from a statev2.sqlite snapshot, so a legacy thread.message-sent row missing… Closes #12694 — V2 replaces ensureSessionForThread's restart branch with ProviderSessionTransitionPolicy plus recovery that checks providerThreadHasPendingBackgroundTasks before retir… Closes #12502 — Stuck-Working class that V2 addresses via run finalization separate from provider turn completion plus 'fix(grok): Prevent spurious wake run after in-turn monitors' an… Closes #12467 — The branch adds 'fix(server): recover Pi resumes without reusing native history (#12933)' and 'fix(pi): use native forks and preserve rollback session identity', which… Closes #12456 — The recovery path it skips (schedulePromptAdmissionRecovery in V1's OpenCodeAdapter) is deleted in V2, whose OpenCode admission and stream-EOF handling is rebuilt in O… Closes #12374 — Same Cursor ACP transport-drop class as #12940, which V2 addresses by enabling enableAgentRetries in CursorAdapterV2. Closes #12325 — Same never-terminating tool-row class. Closes #12206 — ProviderAdapterSessionClosedError is the ACP session-lifecycle class V2 rewrites ('feat(providers): standardize ACP providers', 'fix(antigravity): accept supported leg… Closes #12187 — V2's run interrupt explicitly handles runs in preparing/starting with no provider turn, emitting an interrupt result and marking attempt/node/run interrupted ('Handle… Closes #12155 — V2 carries reasoning as typed turn items across clients ('fix(providers): enable Codex and Claude reasoning summaries in V2', 'fix(timeline): align V2 reasoning disclo… Closes #12136 — Same OpenCode prompt-admission rework as #11889 ('guard OpenCode prompt admission races', 'abort external OpenCode sessions on release') plus V2's interrupt path that… Closes #12131 — V2 tracks subagents in server projections and replaces the ad-hoc agents panel with projection-backed lineage/workspace-card surfaces ('refactor(web): remove the agent… Closes #12094 — The V2 timeline rewrite re-lays out these exact rows ('fix(web): anchor turn duration below the initiating prompt', 'fix: keep working timers anchored to the active ru… Closes #12072 — V2's mobile timeline is rebuilt on paged V2 turn items with LegendList owning end-follow and anchoring ('fix(mobile): keep scroll bounds current after animations', 'pe… Closes #12037 — V2 keeps a failed turn as a settled transcript item instead of wedging the thread ('fix(v2): keep failed turns visible in the transcript', 'fix(server): preserve gener… Closes #11992 — V2 reworks the mobile running-turn UI so the pill is part of the composer hub and scroll bounds track animations ('feat(mobile): make the composer pill the hub for the… Closes #11907 — V2 commits intent, projection and command receipt in one transaction with idempotent receipts, and holds sends as server-side queued turns, removing the V1 admission r… Closes #11903 — Mobile timelines are rebuilt from V2 typed turn items ('Render mobile timelines from V2 turn items', 'Enrich mobile V2 execution items', 'fix(chat): present and summar… Closes #11796 — The V1 processTurnInterruptRequested path is gone. Closes #11777 — V2 projects native Codex subagents as durable child nodes with results ('Map nested Codex subagent threads correctly', 'feat(subagents): disclose projected results con… Closes #11670 — V2 standardizes ACP providers behind one adapter with session recovery and surfaces typed failures ('feat(providers): standardize ACP providers', 'fix(server): surface… Closes #11432 — V2 maps Codex background command completions to typed turn items (codexBackgroundCommandDetail, source kind background_command) and renders background completions as t… Closes #11353 — V2 persists each assistant text block as its own ordered assistant_message turn item with its own messageId, so a later item in the same turn cannot overwrite an earli… Closes #11182 — Branch-only "perf(server): stop decoding unrelated events during startup" (#12846) rewrites ProjectionPipeline bootstrap to read cursor metadata instead of full event… Closes #10973 — V2 commit "fix(server): recover OpenCode status reconciliation" ignores stale timers and duplicate evidence so an older prompt's idle event cannot finish newer steerin… Closes #10934 — The "Provider session did not survive a server restart" path exists only on main. Closes #10798 — V2 replaces the Codex adapter with scoped session runtimes plus a provider session recovery service, and run state is orchestrator-owned rather than derived from the a… Closes #10684 — Same mechanism as #10202: V2's durable thread.model-selection.set command and thread.model-selection-updated projection replace per-client sticky model state. Closes #10375 — ClaudeAdapterV2 classifies local_bash task types explicitly and never fabricates a subagent for them, and V2 rebuilt the worklog rows ("fix(timeline): unify worklog… Closes #10202 — V2 makes thread model selection durable server state via the thread.model-selection.set command and thread.model-selection-updated event, which every subscribed cl… Closes #10192 — V2 projects questions as turn items rendered identically across clients and makes settlement server-owned ("fix: align V2 question and checkpoint timelines across clie… Closes #10185 — V2 models native subagents in projections and surfaces their models in Lineage, replacing the Agents right panel ("feat(web): show subagent models and running count in… Closes #9892 — V2 tracks subagents in projections and maps Grok task envelopes to subagent lineage ("Map Grok task envelopes to subagent lineage", "feat(orchestration-v2): model nati… Closes #9772 — V2 orders the transcript from the append-only event log and pages history by keyset rather than by wall-clock timestamps ("perf(orchestration): bound history reads in… Closes #9698 — V2 separates run finalization from provider turn completion and retires background work after a turn settles ("fix: stop retained background work after a turn settles"… Closes #9672 — V2 models queued messages as first-class durable queued_turn intents promoted by the serialized orchestrator ("fix(queue): preserve and hold queued messages after re… Closes #9607 — V2's provider session recovery restarts live sessions after dead/stale records and reopens Claude queries on credential rotation ("fix(server): restart the live sessio… Closes #9586 — V2 makes liveness an orchestrator projection and the settlement service detaches idle provider sessions ("fix(orchestrator): Restore Claude session continuity for resu… Closes #9414 — V2 adds bounded per-thread history loading with true-end paging and bounded snapshots ("perf(orchestration): bound complete thread snapshots", "fix(orchestration): pag… Closes #9352 — V2 shows live context usage in the composer meter as a first-class V2 surface ("feat(orchestration-v2): show live context usage in the meter (#8144)", "fix(server): ke… Closes #9214 — Fold derivation now keys on server-owned runIds instead of provider turn ids, and "fix(server): recover OpenCode status reconciliation" makes OpenCode run state author… Closes #8945 — V2 folds group by server-owned runId and deliberately keep every provider turn since the initiating prompt in one visual response, so a mid-turn pause no longer starts… Closes #8896 — V2 isolates its migrations from the V1 database and flags divergent migration ids ("test(server): prove v1 to v2 cutover on a copied database and flag divergent migrat… Closes #8873 — V2 replaces the checkpoint reactor with effect-worker checkpointing that starts the provider turn when baseline capture fails (#12153) and finalizes runs when checkpoi… Closes #8648 — V2 bounds history reads in SQL, bounds complete thread snapshots and resume payloads, releases thread history after turn startup, and keeps tool payloads out of comple… Closes #8618 — Stop is a serialized V2 command whose intent commits with a durable receipt, and "fix(orchestrator): report terminal runs after wait timeout" ends the stuck Thinking s… Closes #8382 — V2 adds AcpRuntimeModel parsing of ACP usage_update/state_update usage into a per-session contextUsage snapshot that feeds "feat(orchestration-v2): show live context u… Closes #8320 — V2 records provider session lifecycle as persisted typed events with a session recovery service, plus "fix(server): surface actionable provider failure messages (#1256… Closes #8263 — ProviderTurnStartService prunes and recreates a missing worktree at the thread's branch before starting the provider turn ("fix(orchestration): recreate missing worktr… Closes #8259 — V2 shares Codex sessions across orchestration threads and maps turns to provider instances. Closes #8146 — V2 replaces the hand-written Codex wire with the generated effect-codex-app-server schemas and app-server integration, so initialize payload decoding is regenerated fr… Closes #8105 — V2 projects file-change and diff items per run and thread and narrows subscriptions to the viewed thread, so opening a second thread cannot capture another thread's li… Closes #8022 — V2 Cursor execution and provider checks no longer use the ACP transport or cursor/list_available_models — it goes through the official SDK ('Switch Cursor provider to… Closes #7781 — V2 replaces the inferred turn→checkpoint range with durable run identity and checkpoint coordination ('fix(orchestration): stabilize Codex turn mapping and settlement'… Closes #7722 — V2 models native Codex subagents as first-class threads with orchestrator-owned stop ('Map nested Codex subagent threads correctly', 'fix(server): wait for native Code… Closes #7589 — V2 records provider turn state independently from run finalization and settles threads server-side, and 'fix(server): restore Claude resume compaction' covers the comp… Closes #7314 — V2 models subagents in projections and re-derives status from events ('feat(orchestration-v2): model native subagents', 'refactor(mobile): share subagent status indica… Closes #6517 — V1's ProviderCommandReactor semaphore is replaced by the serialized orchestrator plus effect worker. Closes #6389 — The V2 Claude adapter emits into the orchestrator where events and projections commit in one transaction, removing the in-flight-tool map race at finalize. Closes #6368 — Thread settlement and snooze become server-owned in ThreadSettlementService ('fix(server): keep old failures from waking snoozed V2 threads (#9903)', 'fix: reconcile m… Closes #6358 — V2's server-owned settlement evaluates without a connected client and 'fix(orchestration): reanchor unsettled threads' removes the stuck-unsettled state that pins the… Closes #6128 — The V1 thread read model that caused the archived_at asymmetry is replaced by V2's projection store and ThreadLifecycleService, with archive handled as a domain comman… Closes #5958 — The reported 'Orchestration command invariant failed' comes from the V1 OrchestrationEngine command path, which V2 replaces with the serialized Orchestrator and EventS… Closes #5952 — V2 SubagentProjection plus OpenCodeAdapterV2 child-session mapping (fix(opencode): route child-session approvals through the v2 adapter) projects native child sessions… Closes #5754 — CodexAdapterV2 maps collab wait/spawn items and empty receiver sets explicitly (replay fixture subagent_v2 covers a wait with empty receiverThreadIds), and RunFinaliza… Closes #5685 — V2 CheckpointRollbackService coordinates workspace rollback with the provider conversation and the timeline (fix: align V2 question and checkpoint timelines across cli… Closes #5514 — V2 ThreadPullRequestService skips settled threads in ordinary discovery and only stamps a link. Closes #5447 — Commands are serialized through one orchestrator with idempotent receipts and sessions are owned by ProviderSessionManager, removing the duplicate-dispatch race that p… Closes #5395 — ClaudeAdapterV2 maps sidechain items onto V2's native subagent model (feat(orchestration-v2): model native subagents. Closes #5323 — Shutdown/startup runtime reconciliation records an explicit cancellation for work interrupted by the quit, replacing the stale 'stream failed' state a killed provider… Closes #5035 — V2 drops the V1 per-event runProjectorForEvent nesting: EventSink commits events, projections, receipt and outbox in a single sql.withTransaction, removing the nested-… Closes #4962 — V2 projects delegated-child progress server-side and shares it with mobile (refactor(mobile): share subagent status indicators. Closes #4944 — V2 owns provider switching through ProviderSwitchService/ProviderSessionTransitionPolicy/ProviderSessionManager (Allow provider switching via handoff in chat threads. Closes #4818 — V2 threads no longer write through the V1 receipt repository. Closes #4728 — V2 reprojects Claude assistant text blocks and buffers streaming output per block (fix(timeline): preview live reasoning and buffer complete paragraphs), so text emi… Closes #4723 — fix(orchestration): recreate missing worktrees before turns prunes stale registrations and recreates the saved branch/path in ProviderTurnStartService, and Provid… Closes #4560 — V2 binds each thread to its own provider session record (orchestration_v2_projection_provider_sessions, keyed by provider instance + thread) and serializes commands… Closes #4225 — V2 commits the user-message event before any provider work runs in the effect worker, so a provider auth failure leaves the prompt persisted and rendered instead of sw… Closes #4178 — V2 bounds the read model and subscription payloads: perf(orchestration): bound complete thread snapshots, feat(orchestration): bound thread history and resume paylo… Closes #2644 — V2 separates provider turn completion from run finalization and rewrites the OpenCode adapter's turn mapping, so a finished provider turn settles the thread rather tha… Closes #2519 — V2 projects proposed plans as first-class rows (fix(server): project Claude plans and todos, fix(server): preserve Claude planning lifecycle, inline-plans rework),… Closes #2343 — V2 provider session recovery plus budgeted context handoff rebuild a resumed thread's context from the persisted transcript when the native provider session is gone, r… Closes #881 — Run and turn state are derived from the committed event log and recovered at startup by the V2 recovery services, so a resumed thread shows real provider activity inst…

Supersedes

These pull requests target the V1 orchestration/provider layers this PR replaces, and V2 already delivers the same fix or feature by another route. They are linked here (not auto-closed) so their authors can find the replacement; most were closed pending V2, the rest stay open for maintainer review.

High confidence

  • Supersedes #12478 — V2 decides commands without provider I/O and runs effects in the leased EffectWorker, serializing only per-identity via KeyedSerialExecutor rather than a process-wide…
  • Supersedes #12458 — V2 ships UsageLimitRecoveryWorker and the 'Resume at reset' / 'Auto-resume limited threads' feature (commits 'resume limited threads when usage resets (#12686)', 'snoo…
  • Supersedes #12114 — V2's thread metadata MCP tool supports action='rename' and 'regenerate_title' through the server-owned metadata workflow.
  • Supersedes #12018 — V2 has ThreadMetadataMcpService and the t3_thread_metadata update tool (commit 'feat(mcp): update thread metadata (#8690)').
  • Supersedes #11864 — V2's orchestrator MCP toolkit already exposes create_threads and t3_thread_list scoped to the calling project.
  • Supersedes #11795 — V2 ships OrchestratorMcpService with create_threads and t3_thread_launch (commits 'Add orchestration MCP toolkit', 'feat(mcp): expose project thread launch service').
  • Supersedes #11628 — V2 owns queueing in orchestration — follow-up messages become queued runs delivered in order (QueuedRunOrder/queued-run edit, reorder, promote-to-steer) instead of an…
  • Supersedes #11613 — OpenCodeAdapterV2 has a dedicated admission reconciliation generation and reconcile-idle action for delayed prompt admission (commits `correlate OpenCode prompt admi…
  • Supersedes #11560 — V2 ships t3_worktree_handoff, t3_worktree_status, and t3_worktree_list in the MCP worktree toolkit, including the queued continuation prompt.
  • Supersedes #11452 — OpenCodeAdapterV2 maps child sessions to subagent contexts and projects them as child threads via SubagentProjection.
  • Supersedes #11360 — V2's MCP toolkit provides t3_thread_launch (plus create_threads) for handing work to a new workspace-aware thread.
  • Supersedes #11356 — V2 ships Devin ACP support in the generic registry adapter (Adapters/DevinAcp.ts plus fix(acp): support Devin terminals, questions, and native subagents).
  • Supersedes #11303 — V2's MCP orchestrator toolkit already exposes persistent peer-thread coordination (t3_thread_launch, t3_thread_send, t3_thread_wait, t3_thread_read) with durab…
  • Supersedes #11262 — OpenCodeAdapterV2 models native subagents with lifecycle events and child-session mapping into projected subagent threads.
  • Supersedes #11225 — Cursor V2 no longer uses the ACP transport at all — execution goes through @cursor/sdk, and V2 additionally rejects partial output from failed Cursor runs.
  • Supersedes #11215 — V2 adds Limited run state plus snooze-until-reset and auto-resume-at-reset scheduling (commits #12677/#12686/#12687 and the Limited section of the user docs).
  • Supersedes #11214 — CursorAdapterV2 projects Cursor task subagents as read-only child app threads with their tool activity and final result (docs/user/cursor.md, SubagentProjection).
  • Supersedes #11202 — V2 thread settlement is server-owned: the guarded thread.auto-settle command rejects newer activity and live/blocked work and detaches idle provider sessions (`provi…
  • Supersedes #11170 — Cursor V2 runs on the official @cursor/sdk (CursorAcpExtension deleted) and CursorAdapterV2 maps updateTodos tool calls into task steps with emitsTodoList: true.
  • Supersedes #11096 — V2 delivers cross-provider forks and handoffs natively (t3_thread_fork, ContextHandoffServiceV2, commits fix(orchestration-v2): resolve cross-provider forks and `f…
  • Supersedes #10858 — OpenCodeAdapterV2 declares supportsSubagents/exposesSubagentThreadIds and maps child sessions through SubagentProjection into real child threads.
  • Supersedes #10793 — V2 persists Codex async questions as user_input_request items and runtime-request.respond commits the resolution plus the user message in one transaction against t…
  • Supersedes #10726 — OpenCodeAdapterV2 derives the real providerID/modelID from the native payload per assistant message and records it on the V2 turn (model field on the turn projecti…
  • Supersedes #10611 — V2 persists queued messages in the event log and restart recovery holds them with identity intact (queueHeld in orchestrationV2 contracts.
  • Supersedes #10608 — V2 serializes all commands for a thread through ThreadCommandExecutor and re-validates restore in CheckpointRestoreSafety "at command admission and again before pr…
  • Supersedes #10586 — V2 adds a first-class thread.user-input.dismiss command and ProviderEventIngestor.dismissNativeUserInputs, which clears native user inputs when the turn ends or th…
  • Supersedes #10550 — V2 commit "feat(v2): show provider limit stops as Limited (#12677)" plus usageLimitResetAt in orchestrationV2.ts.
  • Supersedes #10510 — V2 deletes CursorAcpSupport.ts and maps runtime modes onto the Cursor SDK directly: "full access disables its sandbox, while restricted modes and explicit non-full-a…
  • Supersedes #9852 — V2's ProviderTurnStartService recreates a missing worktree before starting a provider turn ("provider turn start recreating missing worktree"), matching commit "fix(…
  • Supersedes #9823 — V2's ThreadCommandExecutor is a KeyedSerialExecutor<ThreadId>, serializing per-thread work "without coupling unrelated identities to a process-wide mutex".
  • Supersedes #9437 — Same V2 fork model (ThreadForkService, thread.fork command, mobile fork/merge-back surfaces in commits "fix(mobile): wait for fork shell before navigation" and "pr…
  • Supersedes #9436 — V2 ships ThreadForkService with fork lineage, lazy context transfer and merge-back handoffs (commits "Add thread fork lineage and lazy context transfer", "feat(mcp):…
  • Supersedes #9247 — V2's CheckpointRestoreSafety resolves fileSystem.realPath on both the checkpoint scope cwd and the thread worktree before comparing, so symlinked paths compare equal.
  • Supersedes #9206 — V2 delivers this generically via commit "feat(orchestration-v2): show live context usage in the meter (#8144)" with usage normalized in GrokAdapterV2.
  • Supersedes #9124 — V2 persists read state server-side as thread.visit/thread.visited events with lastVisitedAt on the thread projection plus a thread.mark-unread command, so ever…
  • Supersedes #9051 — V2 deletes CursorAdapter.ts and runs Cursor through CursorAdapterV2/CursorAgentSdk on the official @cursor/sdk (docs/user/cursor.md: "does not use Cursor's ACP…
  • Supersedes #8453 — V2's normalizeClaudeTurnTokenUsage returns usageScope main_agent on every path, so subagent tokens cannot reach the parent context meter.
  • Supersedes #8412 — GrokAdapterV2 wires extractXAiAcpSubagentUpdate/extractXAiAcpSubagentEndNotice into V2 subagent lineage (Map Grok task envelopes to subagent lineage).
  • Supersedes #7393 — OpenCodeAdapterV2 declares supportsSubagents/exposesSubagentThreadIds/emitsSubagentLifecycle and maps child sessions through SubagentProjection into V2 lineage.
  • Supersedes #7308 — V2 delivers server-owned limit handling: show provider limit stops as Limited (#12677), resume limited threads when usage resets (#12686), snooze limited threads (#126…
  • Supersedes #7287 — V2 projects subagent identity through SubagentProjection and carries the requested model (fix(claude): retain requested subagent models.
  • Supersedes #7240 — V2 persists queued runs in the event log with queued-run.reorder/cancel/edit and queued-message.promote-to-steer commands (fix(queue): preserve and hold queued message…
  • Supersedes #7179 — Settlement and snooze are server-owned in V2 (ThreadSettlementService, thread.snoozed/unsnoozed projections) and the branch already carries fix(server): keep old failu…
  • Supersedes #7143 — ClaudeAdapterV2 derives every message and turn-item id from the native provider item id via IdAllocator.derive.messageFromProviderItem, so stream position is never the…
  • Supersedes #6148 — V2 routes every provider session by providerInstanceId and the orchestrator emits provider-session.detached plus a provider-session.detach effect for providerSwitchPla…

Partially / likely superseded

  • Supersedes #12221 — V2 queues additional runs instead of superseding a live one, and ProviderRuntimeRecoveryService/RunFinalizationService terminalize any nonterminal run whose provider w…
  • Supersedes #12189 — planThreadDeletion emits deletion events and cleanup effects in one EventSink transaction, with the effect worker performing the durable cleanup afterwards.
  • Supersedes #12135 — V2 keeps subagents in the thread projection (SubagentProjection) independent of the bounded message history window ('feat(orchestration): bound thread history and resu…
  • Supersedes #12073 — V2's generic ACP provider registry (AcpRegistryAdapterV2, 'feat(providers): standardize ACP providers') lets a DeepSeek ACP agent be registered without a bespoke drive…
  • Supersedes #12003 — OpenCodeAdapterV2's prompt-admission state machine plus 'cancel pending OpenCode prompts safely' cover the interrupt-before-submission window.
  • Supersedes #11908 — The transcript is the server-owned v2 event log, and ProviderSwitchServiceV2 plus ContextHandoffServiceV2 plan an instance change without the provider session owning t…
  • Supersedes #11839 — ProviderRuntimeRecoveryService cancels nonterminal runtime requests and background turn items whose provider process is gone before admitting new work.
  • Supersedes #11838 — V2 deletes ProviderSessionReaper entirely.
  • Supersedes #11640 — OpenCodeAdapterV2 reconciles prompt admission against the live session status (reconcileOpenCodePromptAdmissionStatus, commit 'recover OpenCode status reconciliation').
  • Supersedes #11471 — V1 CodexAdapter is deleted.
  • Supersedes #11423 — V2's ACP Registry lets any registry agent be added without a bespoke Copilot driver, so only the Copilot-specific quota/driver bits would remain.
  • Supersedes #11284 — GrokAdapterV2 is built on makeAcpAdapterV2, whose shared contextUsage tracking drives the V2 live context meter (commit `feat(orchestration-v2): show live context us…
  • Supersedes #11139 — V2 supports Devin through its ACP Registry path (Adapters/DevinAcp.ts, commit fix(acp): support Devin terminals, questions, and native subagents) rather than a bespo…
  • Supersedes #11090 — OpenCodeAdapterV2's admission state machine tracks idleDuringAdmission and emits reconcile-idle, replacing the V1 idle/turn-boundary handling.
  • Supersedes #10939 — V1 ProviderService is deleted.
  • Supersedes #10893 — V2 ships a generic ACP Registry adapter (AcpRegistryAdapterV2) that can register any registry agent, so a bespoke omp driver is at most partially needed.
  • Supersedes #10805 — OpenCodeAdapterV2 has an explicit prompt-admission state machine (admissionPending/idleDuringAdmission/reconcile-idle) so an idle signal during admission no long…
  • Supersedes #10799 — V1 CodexAdapter is deleted.
  • Supersedes #10607 — V2's ProviderRuntimeRecoveryService plus "harden Grok v2 runtime lifecycle" and "dedupe Grok continuation dispatch" handle crashed sessions centrally.
  • Supersedes #10575 — V2 projects native subagents as separate read-only child threads with their own tool activity (SubagentProjection), so per-subagent stream isolation is structural.
  • Supersedes #10295 — V2 replaces ActivityPayloadProjection.ts with ShellStream and the v2 activity log ("fold completed trailing background activity", "keep shell snapshots bounded and…
  • Supersedes #10132 — V2 ships UsageLimitRecoveryWorker with usageLimitContinuationOfRunId ("feat(v2): resume limited threads when usage resets (#12686)", "share scheduling for tasks an…
  • Supersedes #10087 — V2's diagnostics budget already keeps bounded detail: 64 KiB encoded payload budget with structural summaries that "retain routing identifiers, methods, status, and er…
  • Supersedes #9922 — Cursor V2 gets its model list from CursorSdkCatalog via @cursor/sdk instead of the CLI (CursorProvider.ts loses ~1060 lines of CLI probing), so CLI-version model f…
  • Supersedes #9612 — V2 deletes ProviderSessionReaper.ts.
  • Supersedes #9408 — V2's SubagentProjection plus "Codex background command completion and subagent resume" track subagent lifecycle in projections rather than in the deleted `ClaudeAdap…
  • Supersedes #9391 — V2 separates RunFinalizationService from provider turn completion and makes settlement server-owned in ThreadSettlementService ("stop retained background work afte…
  • Supersedes #9344 — V2 owns session lifecycle in ProviderSessionManager + ProviderRuntimeRecoveryService, which retires effects tied to lost provider processes before admitting new wo…
  • Supersedes #9319 — V2's RuntimeRequestService/runtime-request.respond reads the persisted request, validates required answers, and commits the resolution and user message in one tran…
  • Supersedes #9227 — CodexAdapterV2 persists Codex async notifications as user_input_request turn items and runtime requests that survive turn end, provider exit, and restart.
  • Supersedes #9158 — V2's generic ACP Registry (AcpRegistryAdapterV2, "feat(providers): standardize ACP providers") lets registry agents be added without a first-party driver, so the bes…
  • Supersedes #9130 — V2 replaces ProviderSessionDirectory/ProviderService with ProviderSessionManager and ProviderSessionTransitionPolicy, which decide resume versus fresh session from persisted session state.
  • Supersedes #8952 — V2 models native subagents in SubagentProjection ("feat(orchestration-v2): model native subagents", "show subagent details and history in workspace card")
  • Supersedes #8939 — V2 records run/turn state as committed events and handles OpenCode cancellation in OpenCodeAdapterV2 ("cancel pending OpenCode prompts safely", "abort external OpenC…
  • Supersedes #8857 — V2 replaces the usage-limit handover draft with ContextHandoffServiceV2 portable handoffs plus Limited status and resume-at-reset (feat(server): preserve budgeted hist…
  • Supersedes #8842 — ClaudeAdapterV2 derives deterministic ids from native item ids and V2 restores resume continuity explicitly (fix(server): restore Claude resume compaction.
  • Supersedes #8796 — ThreadDeletionReactor and ProviderSessionDirectory are deleted on V2.
  • Supersedes #8737 — V2 requires the MCP registry for provider sessions and rebuilds credentials per session (fix(claude): reopen queries after MCP credential rotation.
  • Supersedes #8659 — V2's live context meter (#8144) plus OpenCodeAdapterV2's own turn token accumulator already deliver OpenCode context and cost on the meter.
  • Supersedes #8619 — V2 commits stop intent plus its receipt in one transaction and acknowledges before provider work settles (fix(server): wait for native Codex start before Stop #10024.
  • Supersedes #8617 — V2 separates the thread-level contextUsage snapshot from per-turn TurnTokenUsage with explicit partial/complete status (fix(server): keep current provider context usage).
  • Supersedes #8425 — V2 rollback goes through CheckpointRollbackService with provider coordination and the orchestrator resolves runtime requests transactionally (fix(orchestration): exclu…
  • Supersedes #8097 — V2 persists queued/task state in the event log and restores it across restart (fix(queue): preserve and hold queued messages after restart.
  • Supersedes #7993 — Same ACP Registry path covers running Droid as a registry agent.
  • Supersedes #7865 — V2's generic ACP Registry (AcpRegistryAdapterV2 plus feat(providers): standardize ACP providers #6461) lets an ACP agent be registered without a bespoke first-party pr…
  • Supersedes #7854 — ProviderRuntimeIngestion.ts is deleted on V2.
  • Supersedes #7591 — V2 run state is server-owned and background work is modeled explicitly (fix: stop retained background work after a turn settles.
  • Supersedes #7520 — V2's normalizeClaudeTurnTokenUsage stamps usageScope main_agent with an explicit hasSubagents flag instead of folding subagent tokens into the parent turn.
  • Supersedes #7246 — ClaudeAdapterV2 derives the SDK permission mode from the runtime policy in permissionModeForClaudeRuntimePolicy (fix(claude): preserve approvals with full-access sandbox.
  • Supersedes #7238 — V2 adds a from-scratch CodexTurnTokenUsage.ts normalizer and maps nested Codex subagent threads to their own nodes, so parent turns no longer inherit child totals.
  • Supersedes #7192 — V2 separates provider turn end from run finalization (RunFinalizationService) and ClaudeAdapterV2 buffers late/idle notifications behind replay tombstones so post-fina…
  • Supersedes #7184 — ActivityPayloadProjection.ts is deleted on V2.
  • Supersedes #7072 — V2 ships a live context meter (feat(orchestration-v2): show live context usage in the meter #8144) fed by OpenCodeAdapterV2's own token accumulator (fix(server): retai…
  • Supersedes #6584 — V2 models native subagents as separate execution nodes whose completion does not block the root run (feat(orchestration-v2): model native subagents.
  • Supersedes #6162 — V2 adds a first-class provider-session.detach command with attached/updated/detached projections, so a thread's session can be released and rebuilt on the next turn wi…
  • Supersedes #6004 — CodexProgressCoalescer.ts is deleted on V2 and replaced by Adapters/ProviderTextDeltaCoalescer.ts feeding ProviderEventIngestor, with transport payloads bounded (perf(…
  • Supersedes #5711 — ProviderSessionReaper is deleted on V2.
  • Supersedes #5524 — V2 deletes ProviderSessionDirectory/ProviderService entirely and tracks session liveness as persisted provider-session.attached/updated/detached events plus ProviderRu…
  • Supersedes #5142 — ClaudeAdapter.ts is deleted on V2.

Closes discussions

Discussions cannot be auto-closed; these are linked so they can be resolved by hand after merge.

Note

Introduce orchestration V2 runtime, services, provider adapters, and MCP toolkits

  • Adds a complete orchestration V2 server runtime: projection store, event store, effect outbox, command receipts, checkpoint capture/rollback, thread management, run execution, provider session management, context handoff, runtime policy, and legacy V1 thread importer, composed through runtimeLayer.ts
  • Adds V2 provider adapters for Codex, Claude, Cursor, Grok, OpenCode, and ACP Registry with a shared adapter contract, driver registry, and selection-transition policy
  • Adds MCP toolkit services and HTTP registration for orchestrator delegation, thread operations, worktree handoff, project lifecycle, attachments, environment preferences, and preview controls
  • Adds scheduled-task persistence, scheduling logic, server service, client runtime atoms, and a settings UI surface
  • Migrates client-runtime and web/mobile UI from legacy session/turn fields to V2 projection-based runtime/run state, including thread details panel, queue controls, relationship graph, history loading, and item inspector
  • Registers database migrations 050–061 for V2 foundation tables, subagents, provider-session bindings, launch workflows, application event sourcing, effect cancellation, scheduled tasks, legacy import state, and recovery/shell indexes
  • Risk: replaces the legacy EnvironmentApi orchestration interface with orchestrationV2; removes serverUpdateThreadContinuation capability; CursorSettings no longer exposes binaryPath or apiEndpoint; ProviderUsageLimitsIngestionLive no longer subscribes to runtime events; thread routing resolves existing non-deleted threads directly to ready instead of loading
Macroscope summarized 6102d00.

Note

Medium Risk Mobile thread persistence and list/archive/stop behavior change with V2 runtime semantics; removing the thread-transfer report workflow reduces PR visibility into transfer budget regressions.

Overview This slice of the orchestration V2 rollout retires the thread-transfer PR comment pipeline (trusted publisher script, tests, and workflow_run workflow) while CI can still emit transfer artifacts; it also installs build-essential in CI so ACP process-tree fixtures compile instead of soft-skipping.

Mobile moves onto shared V2 client-runtime pieces: SQLite cache uses ORCHESTRATION_CACHE_SCHEMA_VERSION and stored V2 shell/thread snapshots, runtime wiring swaps in bounded thread snapshot loading and history control, and thread detail/review/archive flows read projections (runtime, RuntimeRequestId, checkpoint summaries from runId) instead of V1 session/turn shapes. UX additions include activity inspector, queue control, relationships banner, progressive history controls, server visit watermarking, stricter archive rules via threadCanArchive, and approval/user-input cards that honor live vs dead provider responseCapability.

Smaller touches: shared brand mark module, new uniwind adaptive color tokens, desktop env test for user-data dir names, README link to appearance docs, and marketing copy for Cursor harness.

Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 9eeed8c17109be3752d2f8e1643583d1f579ea2d. Bugbot is set up for automated code reviews on this repo. Configure [here](https://www.cursor.com/dashboard/bugbot).

Devin Review
    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented
      Review in Change Stack →

      Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

      ✨ Finishing Touches
      📝 Generate docstrings
      • Create stacked PR
      • Commit on current branch
      🧪 Generate unit tests (beta)
      • Commit to this branch
      • Create a new PR
      • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

      Autopilot is currently an internal CodeRabbit preview.


      Comment `@coderabbitai help` to get the list of available commands.
    2. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted

    3. @@ -0,0 +100,21 @@
      100+ if (firstRecord.type !== "transcript_start") {
      101+ entries.push(firstRecord);
      102+ }
      103+
      104+ for (const { line, lineNumber } of lines.slice(1)) {
      105+ const record = yield* parseReplayRecord(line, lineNumber);
      106+ if (record.type === "transcript_start") {
      107+ return yield* new ProviderReplayNdjsonLineParseError({
      108+ lineNumber,
      109+ line,
      110+ cause: "transcript_start is only valid as the first replay record",
      111+ });
      112+ }
      113+ entries.push(record);
      114+ }
      115+
      116+ return decodeTranscript({
      117+ ...metadata,
      118+ entries,
      119+ });
      120+ });
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low testkit/ReplayTranscriptNdjson.ts:116

      The call to decodeTranscript at line 116 invokes Schema.decodeUnknownSync, which throws on validation failure. Since this isn't wrapped in Effect.try, any validation error becomes an uncaught exception (defect) instead of a typed ProviderReplayNdjsonParseError. This breaks the function's declared error contract. Consider wrapping the call in Effect.try to catch the exception and convert it to the declared error type.

      -    return decodeTranscript({
      -      ...metadata,
      -      entries,
      -    });
      +    return yield* Effect.try({
      +      try: () =>
      +        decodeTranscript({
      +          ...metadata,
      +          entries,
      +        }),
      +      catch: (cause) =>
      +        new ProviderReplayNdjsonLineParseError({
      +          lineNumber: lines.length,
      +          line: "<transcript validation>",
      +          cause,
      +        }),
      +    });
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file apps/server/src/orchestration-v2/testkit/ReplayTranscriptNdjson.ts around lines 116-120:
      
      The call to `decodeTranscript` at line 116 invokes `Schema.decodeUnknownSync`, which throws on validation failure. Since this isn't wrapped in `Effect.try`, any validation error becomes an uncaught exception (defect) instead of a typed `ProviderReplayNdjsonParseError`. This breaks the function's declared error contract. Consider wrapping the call in `Effect.try` to catch the exception and convert it to the declared error type.
      
      Evidence trail:
      apps/server/src/orchestration-v2/testkit/ReplayTranscriptNdjson.ts lines 50-53: `decodeTranscript = Schema.decodeUnknownSync(ProviderReplayTranscript)` — throws on failure.
      Line 116-118: `return decodeTranscript({...metadata, entries})` — called directly inside Effect.gen without Effect.try wrapper.
      Lines 55-68 (`parseReplayRecord`): same pattern but correctly wrapped in `Effect.try`.
      Line 80: function declares error type `ProviderReplayNdjsonParseError`.
      packages/contracts/src/orchestrationV2.ts lines 1561-1568: `ProviderReplayTranscript` schema with `TrimmedNonEmptyString` fields that can fail validation.
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High orchestration-v2/EventSink.ts:89

      Events published to liveEvents between when eventStore.read completes and when Stream.fromPubSub(liveEvents) subscribes are lost because the PubSub has no replay buffer. Stream.concat only subscribes to the second stream after the first finishes, creating a race window where published events are dropped before the subscription exists. Consider buffering events from liveEvents until the subscription is established, or using a PubSub with replay.

      No longer relevant as of 7fcc993eaea406ab847fad56684cc58eaddfaac9

    4. github-actions[bot](GitHub profile, opens in a new tab)commented

      🚀 Expo continuous deployment is ready!

      • Project → t3-code
      • Platforms → android, ios
      • Scheme → t3code-preview
      &nbsp;🤖 Android🍎 iOS
      Fingerprintfe5a51f2e189da69dfc4c2cd458e6cfb5fdff2eaae3bd597809dfd7771d0898f735d172973d4c1c8
      Build DetailsBuild Permalink
      DetailsDistribution: INTERNAL
      Build profile: preview:dev
      Runtime version: fe5a51f2e189da69dfc4c2cd458e6cfb5fdff2ea
      App version: 0.1.0
      Git commit: 1d5a64460414f9a2c6ff4a5e4f977932228b7f1b
      Build Permalink
      DetailsDistribution: INTERNAL
      Build profile: preview:dev
      Runtime version: ae3bd597809dfd7771d0898f735d172973d4c1c8
      App version: 0.1.0
      Git commit: eea0dcae4150df8341606520c074dc651ae7c00a
      Update DetailsUpdate Permalink
      DetailsBranch: pr-2829
      Runtime version: fe5a51f2e189da69dfc4c2cd458e6cfb5fdff2ea
      Git commit: 1d5a64460414f9a2c6ff4a5e4f977932228b7f1b
      Update Permalink
      DetailsBranch: pr-2829
      Runtime version: ae3bd597809dfd7771d0898f735d172973d4c1c8
      Git commit: 1d5a64460414f9a2c6ff4a5e4f977932228b7f1b
      Update QR
    5. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🔴 Critical

      https://github.com/pingdotgg/t3code/blob/0f644fafe635d59858159538af8a7156a26f95dc/apps/server/src/ws.ts#L189

      The new orchestration V2 RPC methods (ORCHESTRATION_V2_WS_METHODS.dispatchCommand, getThreadProjection, subscribeShell, subscribeThread) are missing from the RPC_REQUIRED_SCOPE map at lines 139-193. When these methods are called, requiredScopeForMethod throws a synchronous Error because the method lookup fails, causing the RPC handlers to crash with an uncaught exception instead of executing the authorization check.

      No longer relevant as of 11db7239d49c82325f998cd6d88f42532d0b71af

    6. juliusmarminge changed the title

    7. @@ -0,0 +108,21 @@
      108+ ) =>
      109+ Effect.gen(function* () {
      110+ const threadId = payloadInput.threadId ?? input.threadId;
      111+ const eventId = yield* idAllocator.allocate.event({
      112+ threadId,
      113+ providerSessionId: input.providerSessionId,
      114+ });
      115+ const occurredAt = yield* DateTime.now;
      116+ return yield* Schema.decodeUnknownEffect(OrchestrationV2DomainEvent)(
      117+ compactUndefined({
      118+ id: eventId,
      119+ type: payloadInput.type,
      120+ threadId,
      121+ runId: payloadInput.runId ?? input.runId,
      122+ nodeId: payloadInput.nodeId ?? input.nodeId,
      123+ provider: input.event.provider,
      124+ rawEventId: input.rawEventId,
      125+ occurredAt,
      126+ payload: payloadInput.payload,
      127+ }),
      128+ );
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium orchestration-v2/ProviderEventIngestor.ts:109

      In makeDomainEvent, the ?? operator on lines 121 and 123 treats explicit null as equivalent to undefined, causing payloadInput.runId ?? input.runId to fall back to input.runId when payloadInput.runId is explicitly null. Since the type is readonly runId?: RunId | null, this means explicit null values from the caller (e.g., input.event.node.runId being null on line 172) are incorrectly overwritten instead of preserved. Consider using === undefined checks like lines 161-162 and 210-211, or use payloadInput.runId === undefined ? input.runId : payloadInput.runId.

                const threadId = payloadInput.threadId ?? input.threadId;
      -          const runId = payloadInput.runId ?? input.runId;
      -          const nodeId = payloadInput.nodeId ?? input.nodeId;
      +          const runId = payloadInput.runId === undefined ? input.runId : payloadInput.runId;
      +          const nodeId = payloadInput.nodeId === undefined ? input.nodeId : payloadInput.nodeId;
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/server/src/orchestration-v2/ProviderEventIngestor.ts around lines 109-128:
      
      In `makeDomainEvent`, the `??` operator on lines 121 and 123 treats explicit `null` as equivalent to `undefined`, causing `payloadInput.runId ?? input.runId` to fall back to `input.runId` when `payloadInput.runId` is explicitly `null`. Since the type is `readonly runId?: RunId | null`, this means explicit `null` values from the caller (e.g., `input.event.node.runId` being `null` on line 172) are incorrectly overwritten instead of preserved. Consider using `=== undefined` checks like lines 161-162 and 210-211, or use `payloadInput.runId === undefined ? input.runId : payloadInput.runId`.
      
      Evidence trail:
      apps/server/src/orchestration-v2/ProviderEventIngestor.ts lines 105-106 (payloadInput type with `RunId | null`), line 121 (`runId: payloadInput.runId ?? input.runId`), line 122 (`nodeId: payloadInput.nodeId ?? input.nodeId`), lines 161-162 and 210-211 (codebase uses `=== undefined` pattern elsewhere). packages/contracts/src/orchestrationV2.ts line 358 (`runId: Schema.NullOr(RunId)` on ExecutionNode - confirms null is a valid value), line 857 (`runId: Schema.optional(RunId)` on EventBase - domain event uses optional/undefined, not null). apps/server/src/orchestration-v2/ProviderEventIngestor.ts lines 80-81 (compactUndefined only strips undefined, not null).
    8. @@ -0,0 +251,21 @@
      251+ return [];
      252+ }
      253+ return [
      254+ {
      255+ type: "http",
      256+ name: "t3-code",
      257+ url: session.endpoint,
      258+ headers: [
      259+ {
      260+ name: "Authorization",
      261+ value: session.authorizationHeader,
      262+ },
      263+ ],
      264+ },
      265+ ];
      266+}
      267+
      268+function nativeThreadId(provider: ProviderKind, thread: OrchestrationV2ProviderThread): string {
      269+ const id = thread.nativeThreadRef?.nativeId;
      270+ if (id === null || id === undefined || id.trim().length === 0) {
      271+ throw new ProviderAdapterProtocolError({
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/AcpAdapterV2.ts:271

      When nativeThreadId is called inside Effect.gen generators (e.g., lines 899, 1813), the thrown ProviderAdapterProtocolError becomes an untyped defect instead of a typed failure. This bypasses Effect.mapError and other typed error handlers, causing the error to propagate as an unexpected defect. Consider converting nativeThreadId to return Effect<string, ProviderAdapterProtocolError> and yielding it at each call site, or inlining the validation with yield* new ProviderAdapterProtocolError(...) so the failure is properly typed.

      Also found in 1 other location(s)

      apps/server/src/orchestration-v2/ThreadManagementService.ts:278

      The statement return yield* managementError(...) cannot work correctly because managementError() returns a ThreadManagementError instance, not an Effect. The yield* operator in Effect.gen expects an Effect value. This should be return yield* Effect.fail(managementError(...)). The correct pattern is demonstrated elsewhere in this file (lines 241-246) where Effect.fail(managementError(...)) is properly used. This same bug pattern repeats at lines 291, 333, 357, 374, 390, 406, and 427.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts around line 271:
      
      When `nativeThreadId` is called inside `Effect.gen` generators (e.g., lines 899, 1813), the thrown `ProviderAdapterProtocolError` becomes an untyped defect instead of a typed failure. This bypasses `Effect.mapError` and other typed error handlers, causing the error to propagate as an unexpected defect. Consider converting `nativeThreadId` to return `Effect<string, ProviderAdapterProtocolError>` and yielding it at each call site, or inlining the validation with `yield* new ProviderAdapterProtocolError(...)` so the failure is properly typed.
      
      Evidence trail:
      1. nativeThreadId function with throw: apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts lines 268-277
      2. Call site inside Effect.gen: apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts line 899
      3. Call site inside Effect.gen: apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts line 1813
      4. Correct yield* pattern for comparison: apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts line 1808
      5. ProviderAdapterProtocolError class definition: apps/server/src/orchestration-v2/ProviderAdapter.ts lines 316-327
      6. Effect.gen implementation delegating to fromIteratorUnsafe: https://github.com/Effect-TS/effect-smol packages/effect/src/internal/effect.ts lines 1104-1125
      7. fromIteratorUnsafe calling iter.next() without try/catch: https://github.com/Effect-TS/effect-smol packages/effect/src/internal/effect.ts lines 1285-1307
      8. FiberImpl.runLoop catch block converting thrown errors to exitDie: https://github.com/Effect-TS/effect-smol packages/effect/src/internal/effect.ts lines 646-650
      9. die = exitDie producing Effect<never> (untyped): https://github.com/Effect-TS/effect-smol packages/effect/src/internal/effect.ts line 947
      
      Also found in 1 other location(s):
      - apps/server/src/orchestration-v2/ThreadManagementService.ts:278 -- The statement `return yield* managementError(...)` cannot work correctly because `managementError()` returns a `ThreadManagementError` instance, not an `Effect`. The `yield*` operator in `Effect.gen` expects an Effect value. This should be `return yield* Effect.fail(managementError(...))`. The correct pattern is demonstrated elsewhere in this file (lines 241-246) where `Effect.fail(managementError(...))` is properly used. This same bug pattern repeats at lines 291, 333, 357, 374, 390, 406, and 427.
      
    9. @@ -0,0 +186,21 @@
      186+ unsupported(
      187+ input,
      188+ "queued_messages",
      189+ "providerInstanceId does not support app-owned queued turns",
      190+ ),
      191+ );
      192+
      193+const decideSteeringExecution: CommandPolicyV2Shape["decideSteeringExecution"] = (input) => {
      194+ if (!input.forceRestart && input.capabilities.turns.supportsActiveSteering) {
      195+ return Effect.succeed("active_steering");
      196+ }
      197+ if (
      198+ input.capabilities.turns.supportsInterrupt &&
      199+ input.capabilities.turns.supportsSteeringByInterruptRestart
      200+ ) {
      201+ return Effect.succeed("interrupt_restart");
      202+ }
      203+ return Effect.fail(
      204+ unsupported(
      205+ input,
      206+ input.capabilities.turns.supportsInterrupt ? "interrupt_restart_steering" : "active_steering",
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low orchestration-v2/CommandPolicy.ts:206

      When forceRestart is true and supportsInterrupt is false, the error reports "active_steering" as the missing capability. Since the caller explicitly requested a restart, the error should name "interrupt_restart_steering" instead. Consider updating the capability selection to account for forceRestart.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/server/src/orchestration-v2/CommandPolicy.ts around line 206:
      
      When `forceRestart` is `true` and `supportsInterrupt` is `false`, the error reports `"active_steering"` as the missing capability. Since the caller explicitly requested a restart, the error should name `"interrupt_restart_steering"` instead. Consider updating the capability selection to account for `forceRestart`.
      
      Evidence trail:
      apps/server/src/orchestration-v2/CommandPolicy.ts lines 193-210 at REVIEWED_COMMIT. The function `decideSteeringExecution`: line 194 skips active_steering when forceRestart=true; line 198-199 checks supportsInterrupt; line 206 ternary `supportsInterrupt ? "interrupt_restart_steering" : "active_steering"` does not consider forceRestart when choosing the error capability name.
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low Adapters/CodexAdapterV2.testkit.ts:28

      CodexReplayTranscriptDecodeError expects driver, but metadataFromTranscript returns provider. When the error is constructed with ...metadataFromTranscript(transcript), driver is always undefined and the transcript's provider value is discarded. Rename the schema field to provider to align with the metadata helper.

      Also found in 3 other location(s)

      apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.testkit.ts:75

      Field name mismatch: metadataFromTranscript returns { provider, protocol, scenario } but AcpReplayTranscriptDecodeError expects driver not provider. When spreading ...metadataFromTranscript(transcript) into the error constructor at lines 75 and 84, the provider property is ignored (extra property) and the driver field remains undefined. The error message includes driver: Schema.optional(Schema.String) but never receives the actual provider value.

      apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.testkit.ts:61

      The driver field in CursorReplayTranscriptDecodeError will always be undefined because metadataFromTranscript() returns an object with key provider, not driver. When spreading {...metadataFromTranscript(transcript), cause} into the constructor, the provider value is passed but ignored (no matching schema field), while driver remains unset.

      apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.testkit.ts:45

      The driver field in OpenCodeReplayTranscriptDecodeError will always be undefined because transcriptMetadata() returns an object with key provider, not driver. When spreading {...transcriptMetadata(transcript), cause} into the constructor, the provider value is passed but ignored (no matching schema field), while driver remains unset.

      No longer relevant as of d26dac9602f67a97f2ecfaa9dcfa7f6edeb28cd1

    10. One Effect error-convention issue: a wrapper message is being derived from cause.message. See inline comment.

      Posted via Macroscope — Effect Service Conventions
    11. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium acp/AcpSessionRuntime.ts:486

      The adoptSession function resets assistantSegmentRef to { nextSegmentIndex: 0 } without first calling closeActiveAssistantSegment, so any active assistant segment is silently discarded when switching sessions via loadSession, resumeSession, or forkSession. This leaves consumers with an orphaned AssistantItemStarted event that never gets a matching AssistantItemCompleted. Consider closing the active segment before resetting the ref.

      No longer relevant as of 706c819cf36dff6e5037e5940dff9dd43c504ea3

    12. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium components/ChatView.tsx:4889

      The onRollbackCheckpoint prop is passed as an inline lambda, so it receives a new function reference on every render. Because MessagesTimeline depends on it in the sharedState useMemo, every re-render of ChatViewContent recomputes the context value and re-renders all timeline rows. Pass the existing stable useCallback reference directly instead.

      No longer relevant as of 3b864044c6102cd3fde59aff499b83bfe3f07edb

      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/ClaudeAdapterV2.ts:2864

      The abort listener on callbackOptions.signal never fires when the signal is already aborted, so Deferred.await(decision) can hang indefinitely if the caller has already cancelled the request. Check callbackOptions.signal.aborted after registering the listener and resolve the Deferred with "cancel" immediately if the signal is already set.

      No longer relevant as of d26dac9602f67a97f2ecfaa9dcfa7f6edeb28cd1

      @@ -0,0 +2270,21 @@
      2270+ effect.pipe(
      2271+ Effect.mapError(
      2272+ (cause) =>
      2273+ new ProviderAdapterEnsureThreadError({
      2274+ driver: CURSOR_PROVIDER,
      2275+ threadId: threadInput.threadId,
      2276+ cause,
      2277+ }),
      2278+ ),
      2279+ ),
      2280+ ),
      2281+ resumeThread: Effect.fn("CursorAdapterV2.resumeThread")(
      2282+ function* (threadInput: { readonly providerThread: OrchestrationV2ProviderThread }) {
      2283+ const agentId = nativeThreadId(threadInput.providerThread);
      2284+ yield* openAgent({
      2285+ operation: "resume",
      2286+ agentId,
      2287+ threadId: threadInput.providerThread.appThreadId ?? input.threadId,
      2288+ modelSelection: input.modelSelection,
      2289+ runtimePolicy: input.runtimePolicy,
      2290+ });
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟢 Low Adapters/CursorAdapterV2.ts:2282

      resumeThread silently ignores the optional modelSelection and runtimePolicy parameters that callers may pass. The parameter type is narrowed to only { readonly providerThread }, and the body always falls back to the session-level input.modelSelection and input.runtimePolicy. This means a caller requesting a model switch via resumeThread will have that selection dropped. Compare with startTurn (line 2084–2086), which correctly uses the turn-level values. Widen the parameter type and prefer the caller-supplied values with a fallback to the session defaults.

      -            function* (threadInput: { readonly providerThread: OrchestrationV2ProviderThread }) {
      +            function* (threadInput: {
      +              readonly providerThread: OrchestrationV2ProviderThread;
      +              readonly threadId?: ThreadId;
      +              readonly modelSelection?: ModelSelection;
      +              readonly runtimePolicy?: ProviderAdapterV2RuntimePolicy;
      +            }) {
                     const agentId = nativeThreadId(threadInput.providerThread);
                     yield* openAgent({
                       operation: "resume",
                       agentId,
      -                threadId: threadInput.providerThread.appThreadId ?? input.threadId,
      -                modelSelection: input.modelSelection,
      -                runtimePolicy: input.runtimePolicy,
      +                threadId: threadInput.threadId ?? threadInput.providerThread.appThreadId ?? input.threadId,
      +                modelSelection: threadInput.modelSelection ?? input.modelSelection,
      +                runtimePolicy: threadInput.runtimePolicy ?? input.runtimePolicy,
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.ts around lines 2282-2290:
      
      `resumeThread` silently ignores the optional `modelSelection` and `runtimePolicy` parameters that callers may pass. The parameter type is narrowed to only `{ readonly providerThread }`, and the body always falls back to the session-level `input.modelSelection` and `input.runtimePolicy`. This means a caller requesting a model switch via `resumeThread` will have that selection dropped. Compare with `startTurn` (line 2084–2086), which correctly uses the turn-level values. Widen the parameter type and prefer the caller-supplied values with a fallback to the session defaults.
      
      Evidence trail:
      - Interface definition: apps/server/src/orchestration-v2/ProviderAdapter.ts lines 480-485 (resumeThread accepts modelSelection? and runtimePolicy?)
      - CursorAdapterV2 resumeThread: apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.ts lines 2281-2290 (narrowed type, uses session-level input.modelSelection/runtimePolicy)
      - CursorAdapterV2 startTurn: apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.ts lines 2084-2085 (correctly uses turnInput.modelSelection/runtimePolicy)
      - AcpAdapterV2 resumeThread: apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts lines 1967-1990 (correctly widens type and uses threadInput.modelSelection ?? input.modelSelection)
      - Caller: apps/server/src/orchestration-v2/ProviderSessionManager.ts lines 871-895 (passes full input including modelSelection/runtimePolicy)
    13. @@ -351,0 +418,21 @@
      418+ unexpectedThreadCount: verification.unexpectedThreadIds.length,
      419+ unreadableThreadCount: verification.unreadableThreadIds.length,
      420+ },
      421+ ),
      422+ ),
      423+ ),
      424+ ),
      425+ rebuild: runStartupPhase(
      426+ "orchestration-v2.projections.rebuild",
      427+ projectionMaintenance.rebuild,
      428+ ),
      429+ recover: runStartupPhase("orchestration-v2.recovery", providerRuntimeRecovery.recover),
      430+ startEffectWorker: runStartupPhase(
      431+ "orchestration-v2.effect-worker.start",
      432+ Effect.gen(function* () {
      433+ const workerFiber = yield* EffectWorker.runDaemon.pipe(Effect.forkScoped);
      434+ yield* Ref.set(effectWorkerFiber, workerFiber);
      435+ yield* agentAwarenessRelay.start();
      436+ }),
      437+ ),
      438+ autoBootstrap: (serverConfig.autoBootstrapProjectFromCwd
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium src/serverRuntimeStartup.ts:438

      The autoBootstrap phase now runs inside runOrderedV2StartupPhases without error recovery, so any failure in projects.bootstrap, threads.getShellSnapshot, or threadLaunch.launch causes the entire startup sequence to fail and triggers commandGate.failCommandReady, preventing the server from accepting commands. Previously this was forked separately with Effect.catch that logged a warning, allowing the server to start even when auto-bootstrap failed. Consider restoring the catch so auto-bootstrap failures are non-fatal.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/server/src/serverRuntimeStartup.ts around line 438:
      
      The `autoBootstrap` phase now runs inside `runOrderedV2StartupPhases` without error recovery, so any failure in `projects.bootstrap`, `threads.getShellSnapshot`, or `threadLaunch.launch` causes the entire startup sequence to fail and triggers `commandGate.failCommandReady`, preventing the server from accepting commands. Previously this was forked separately with `Effect.catch` that logged a warning, allowing the server to start even when auto-bootstrap failed. Consider restoring the catch so auto-bootstrap failures are non-fatal.
      
      Evidence trail:
      apps/server/src/serverRuntimeStartup.ts lines 288-324 (runOrderedV2StartupPhases - autoBootstrap yielded directly with no catch), lines 438-444 (autoBootstrap phase passed in), lines 448-449 (signalCommandReady after the phases), lines 479-493 (startup exit check that calls failCommandReady). The git diff (MERGE_BASE..REVIEWED_COMMIT) shows the old code at the removed lines: `Effect.forkScoped(...)` wrapping auto-bootstrap with `Effect.catch((cause) => Effect.logWarning("startup auto-bootstrap welcome failed", { cause }))`.
    14. @@ -150,0 +191,21 @@
      191+ * Applies a real right-panel mutation and its thread-panel transition atomically.
      192+ * This is the only path real panel actions use, so visibility never has to be
      193+ * reconciled after the fact in React.
      194+ */
      195+const updateThread = (
      196+ state: RightPanelStoreData,
      197+ ref: ScopedThreadRef,
      198+ updater: (current: ThreadRightPanelState) => ThreadRightPanelState,
      199+): RightPanelStoreData => {
      200+ const threadKey = scopedThreadKey(ref);
      201+ const current = state.byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
      202+ const byThreadKey = updateThreadStateMap(state.byThreadKey, threadKey, updater);
      203+ const next = byThreadKey[threadKey] ?? EMPTY_THREAD_STATE;
      204+ let threadPanelVisibilityByThreadKey = state.threadPanelVisibilityByThreadKey;
      205+
      206+ if (!current.isOpen && next.isOpen) {
      207+ threadPanelVisibilityByThreadKey = updateThreadPanelVisibilityMap(
      208+ threadPanelVisibilityByThreadKey,
      209+ threadKey,
      210+ (visibility) => (visibility.popoverOpen ? { ...visibility, popoverOpen: false } : visibility),
      211+ );
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium src/rightPanelStore.ts:206

      When the real right panel opens, updateThread only clears popoverOpen if it was true, but it never sets inlineOpen: true when it was false. If the thread panel was previously visible inline (inlineOpen: true, popoverOpen: false) and the layout later switches to popover mode (e.g., at narrower widths), selectThreadPanelOpen reads popoverOpen which is still false, causing the thread panel to disappear even though it should remain visible. Consider preserving inlineOpen: true when the right panel opens so the panel stays visible across layout transitions.

        if (!current.isOpen && next.isOpen) {
           threadPanelVisibilityByThreadKey = updateThreadPanelVisibilityMap(
             threadPanelVisibilityByThreadKey,
             threadKey,
      -      (visibility) => (visibility.popoverOpen ? { ...visibility, popoverOpen: false } : visibility),
      +      (visibility) => ({ ...visibility, inlineOpen: true, popoverOpen: false }),
           );
         } else if (current.isOpen && !next.isOpen) {
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/web/src/rightPanelStore.ts around lines 206-211:
      
      When the real right panel opens, `updateThread` only clears `popoverOpen` if it was true, but it never sets `inlineOpen: true` when it was false. If the thread panel was previously visible inline (`inlineOpen: true`, `popoverOpen: false`) and the layout later switches to popover mode (e.g., at narrower widths), `selectThreadPanelOpen` reads `popoverOpen` which is still `false`, causing the thread panel to disappear even though it should remain visible. Consider preserving `inlineOpen: true` when the right panel opens so the panel stays visible across layout transitions.
    15. @@ -849,5 +862,4 @@
      849862 // Context window
      850863 // ------------------------------------------------------------------
      851864 const activeContextWindow = useMemo(
      852- () => deriveLatestContextWindowSnapshot(activeThreadActivities ?? []),
      853- [activeThreadActivities],
      865+ () => deriveLatestContextWindowSnapshot(activeThreadWorkEntries ?? []),
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium chat/ChatComposer.tsx:865

      activeContextWindow is now only populated when a compaction event exists in activeThreadWorkEntries, so the context-window meter hides normal token-usage during the entire run until compaction occurs. Users lose visibility into live token consumption that was previously shown via context-window.updated activity snapshots.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/web/src/components/chat/ChatComposer.tsx around line 865:
      
      `activeContextWindow` is now only populated when a compaction event exists in `activeThreadWorkEntries`, so the context-window meter hides normal token-usage during the entire run until compaction occurs. Users lose visibility into live token consumption that was previously shown via `context-window.updated` activity snapshots.
    16. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Adapters/CursorAdapterV2.ts:120

      CursorProviderCapabilitiesV2.turns.supportsQueuedMessages: true signals that the orchestrator can queue messages behind an active turn, but startTurn throws ProviderAdapterProtocolError when activeTurn is non-null. This causes the orchestrator to accept queued messages at planning time, then the adapter rejects them at runtime with 'Cursor provider turn ... is still active'.

      -    supportsQueuedMessages: true,
      +    supportsQueuedMessages: false,
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.ts around line 120:
      
      `CursorProviderCapabilitiesV2.turns.supportsQueuedMessages: true` signals that the orchestrator can queue messages behind an active turn, but `startTurn` throws `ProviderAdapterProtocolError` when `activeTurn` is non-null. This causes the orchestrator to accept queued messages at planning time, then the adapter rejects them at runtime with 'Cursor provider turn ... is still active'.
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium mcp/McpSessionRegistry.testkit.ts:21

      resolve returns Effect.succeed(undefined) for every token, so tokens minted by issue are never recognized as valid. When McpHttpServer authorizes requests via registry.resolve(token), all requests receive 401 unauthorized errors. Consider returning the session that was issued for the token, or document if this testkit intentionally breaks MCP auth.

      -    resolve: () => Effect.succeed(undefined),
      +    resolve: (token) =>
      +      Effect.succeed({
      +        environmentId: EnvironmentId.make("environment:mcp-test"),
      +        threadId: token.replace("Bearer mcp-test:", ""),
      +        providerSessionId: token.replace("Bearer ", ""),
      +        providerInstanceId: "mcp-test",
      +        endpoint: "http://127.0.0.1/mcp",
      +        authorizationHeader: token,
      +      }),
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/server/src/mcp/McpSessionRegistry.testkit.ts around line 21:
      
      `resolve` returns `Effect.succeed(undefined)` for every token, so tokens minted by `issue` are never recognized as valid. When `McpHttpServer` authorizes requests via `registry.resolve(token)`, all requests receive 401 unauthorized errors. Consider returning the session that was issued for the token, or document if this testkit intentionally breaks MCP auth.
      @@ -0,0 +94,21 @@
      94+ ? Sources
      95+ : never
      96+ : never;
      97+ readonly sandboxEnabled?: boolean;
      98+ readonly enableAgentRetries?: boolean;
      99+ readonly hasCustomTools?: boolean;
      100+ };
      101+ readonly agents?: ReadonlyArray<string>;
      102+}
      103+
      104+export interface CursorAgentSdkLoggedSendOptions {
      105+ readonly model?: SendOptions["model"];
      106+ readonly mode?: SendOptions["mode"];
      107+ readonly local?: {
      108+ readonly force?: boolean;
      109+ readonly hasCustomTools?: boolean;
      110+ };
      111+ readonly idempotencyKey?: string;
      112+}
      113+
      114+export type CursorAgentSdkProtocolLogEvent =
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Adapters/CursorAgentSdk.ts:114

      CursorAgentSdkProtocolLogEvent stores raw Cursor SDK payloads including full prompts (message), InteractionUpdate, RunResult, and AgentMessage[], and makeCursorAgentSdkProtocolLogger writes these verbatim to the native provider log. This violates the native logging policy in NativeProtocolLogging.ts, which forbids copying provider payload values because they can contain secrets. Runs with secrets in prompts, tool arguments, or message history will persist them to logs/provider/*.log, weakening local secret isolation.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/server/src/orchestration-v2/Adapters/CursorAgentSdk.ts around line 114:
      
      `CursorAgentSdkProtocolLogEvent` stores raw Cursor SDK payloads including full prompts (`message`), `InteractionUpdate`, `RunResult`, and `AgentMessage[]`, and `makeCursorAgentSdkProtocolLogger` writes these verbatim to the native provider log. This violates the native logging policy in `NativeProtocolLogging.ts`, which forbids copying provider payload values because they can contain secrets. Runs with secrets in prompts, tool arguments, or message history will persist them to `logs/provider/*.log`, weakening local secret isolation.
      @@ -0,0 +92,21 @@
      92+ EffectAcpErrors.AcpError,
      93+ Scope.Scope
      94+ >;
      95+ readonly assertComplete?: Effect.Effect<void, EffectAcpErrors.AcpError>;
      96+}
      97+
      98+export const registerGrokAcpExtensions: NonNullable<AcpAdapterV2Flavor["registerExtensions"]> = ({
      99+ runtime,
      100+ requestUserInput,
      101+}) =>
      102+ Effect.forEach(
      103+ ["x.ai/ask_user_question", "_x.ai/ask_user_question"] as const,
      104+ (method) =>
      105+ runtime.handleExtRequest(method, XAiAskUserQuestionRequest, (params) => {
      106+ const identity = extractXAiAskUserQuestionIdentity(params);
      107+ const questions = extractXAiAskUserQuestions(params).map((question) => ({
      108+ id: question.id,
      109+ header: question.header,
      110+ question: question.question,
      111+ options: [...question.options],
      112+ }));
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/GrokAdapterV2.ts:107

      registerGrokAcpExtensions rebuilds question objects but drops the multiSelect flag when calling requestUserInput. extractXAiAskUserQuestions() returns multiSelect: true for Grok's multi-select prompts, but lines 107-112 only copy id, header, question, and options. This causes multi-select prompts to be presented as single-select, so users cannot select all requested choices and the provider receives incomplete answers. Consider preserving multiSelect in the mapped question object.

      -        const questions = extractXAiAskUserQuestions(params).map((question) => ({
      -          id: question.id,
      -          header: question.header,
      -          question: question.question,
      -          options: [...question.options],
      -        }));
      Also found in 1 other location(s)

      packages/client-runtime/src/state/models.ts:625

      presentPendingRequests overwrites every user_input_request question&#39;s multiSelect flag with false. Providers can emit multiSelect: true questions (for example XAI ACP questions), and the web composer uses this flag to decide whether to allow multiple selections. Those prompts will be rendered as single-select and the client will submit only one answer instead of the required array.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.ts around lines 107-112:
      
      `registerGrokAcpExtensions` rebuilds question objects but drops the `multiSelect` flag when calling `requestUserInput`. `extractXAiAskUserQuestions()` returns `multiSelect: true` for Grok's multi-select prompts, but lines 107-112 only copy `id`, `header`, `question`, and `options`. This causes multi-select prompts to be presented as single-select, so users cannot select all requested choices and the provider receives incomplete answers. Consider preserving `multiSelect` in the mapped question object.
      
      Also found in 1 other location(s):
      - packages/client-runtime/src/state/models.ts:625 -- `presentPendingRequests` overwrites every `user_input_request` question's `multiSelect` flag with `false`. Providers can emit `multiSelect: true` questions (for example XAI ACP questions), and the web composer uses this flag to decide whether to allow multiple selections. Those prompts will be rendered as single-select and the client will submit only one answer instead of the required array.
      
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Adapters/CodexAdapterV2.ts:111

      supportsMultipleProviderThreadsPerSession: true declares that multiple threads can share a runtime session, but providerSession() constructs a session with a single cwd and model. When Orchestrator.ts reuses a providerSessionId for a second thread and ProviderSessionManager.ts attaches it to the existing runtime, the new thread receives the stale session record from the first thread via provider-session.attached. This causes thread B to see thread A's model and cwd in its projection/UI.

      -    supportsMultipleProviderThreadsPerSession: true,
      +    supportsMultipleProviderThreadsPerSession: false,
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts around line 111:
      
      `supportsMultipleProviderThreadsPerSession: true` declares that multiple threads can share a runtime session, but `providerSession()` constructs a session with a single `cwd` and `model`. When `Orchestrator.ts` reuses a `providerSessionId` for a second thread and `ProviderSessionManager.ts` attaches it to the existing runtime, the new thread receives the stale session record from the first thread via `provider-session.attached`. This causes thread B to see thread A's `model` and `cwd` in its projection/UI.
      @@ -0,0 +460,21 @@
      460+ return result.output.counts.map((entry) => ({
      461+ fileName: entry.file,
      462+ preview: `${entry.count} matches`,
      463+ }));
      464+ }
      465+ return result.output.matches.map((entry) => ({
      466+ fileName: entry.file,
      467+ ...(entry.lineNumber === undefined ? {} : { line: entry.lineNumber }),
      468+ preview: entry.line,
      469+ }));
      470+ });
      471+ case "semSearch":
      472+ return [
      473+ {
      474+ fileName: "semantic-search",
      475+ preview: toolCall.result.value.results,
      476+ },
      477+ ];
      478+ default:
      479+ return [];
      480+ }
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/CursorAdapterV2.ts:444

      cursorToolSearchResults returns [] for ls and readLints tool calls, so successful directory listings and lint results are silently dropped from file_search artifacts. The switch statement needs cases for both types to capture their outputs.

           case "semSearch":
             return [
               {
                 fileName: "semantic-search",
                 preview: toolCall.result.value.results,
               },
             ];
      +    case "ls":
      +      return toolCall.result.value.files.map((fileName) => ({ fileName }));
      +    case "readLints":
      +      return toolCall.result.value.lints.map((lint) => ({
      +        fileName: lint.file,
      +        line: lint.line,
      +        preview: lint.message,
      +      }));
           default:
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.ts around lines 444-480:
      
      `cursorToolSearchResults` returns `[]` for `ls` and `readLints` tool calls, so successful directory listings and lint results are silently dropped from `file_search` artifacts. The switch statement needs cases for both types to capture their outputs.
      @@ -0,0 +514,21 @@
      514+ readonly nativeThreadId: string;
      515+ readonly codexInput: ReadonlyArray<CodexSchema.V2TurnStartParams__UserInput>;
      516+ readonly runtimePolicy: ProviderAdapterV2RuntimePolicy;
      517+ readonly modelSelection: ModelSelection;
      518+}) {
      519+ return Effect.gen(function* () {
      520+ const runtimeModeDefaults = codexRuntimeModeTurnDefaults(input.runtimePolicy.runtimeMode);
      521+ const approvalPolicy =
      522+ input.runtimePolicy.approvalPolicy === undefined
      523+ ? runtimeModeDefaults.approvalPolicy
      524+ : yield* decodeTurnApprovalPolicy(input.runtimePolicy.approvalPolicy);
      525+ const sandboxPolicy =
      526+ input.runtimePolicy.sandboxPolicy === undefined
      527+ ? runtimeModeDefaults.sandboxPolicy
      528+ : yield* decodeTurnSandboxPolicy(input.runtimePolicy.sandboxPolicy);
      529+ const selectedEffort = getModelSelectionStringOptionValue(
      530+ input.modelSelection,
      531+ "reasoningEffort",
      532+ );
      533+ const effort =
      534+ selectedEffort === undefined ? undefined : yield* decodeTurnReasoningEffort(selectedEffort);
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/CodexAdapterV2.ts:529

      buildCodexTurnStartParams ignores input.runtimePolicy.reasoningEffort and only reads reasoningEffort from modelSelection. A caller passing a per-turn override like { reasoningEffort: "low" } in the runtime policy silently loses that setting, causing the turn to run with no effort field or the wrong fallback in plan mode.

           const selectedEffort = getModelSelectionStringOptionValue(
             input.modelSelection,
             "reasoningEffort",
      -    );
      -    const effort =
      -      selectedEffort === undefined ? undefined : yield* decodeTurnReasoningEffort(selectedEffort);
      +    ) ?? input.runtimePolicy.reasoningEffort;
      +    const effort =
      +      selectedEffort === undefined ? undefined : yield* decodeTurnReasoningEffort(selectedEffort);
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts around lines 529-534:
      
      `buildCodexTurnStartParams` ignores `input.runtimePolicy.reasoningEffort` and only reads `reasoningEffort` from `modelSelection`. A caller passing a per-turn override like `{ reasoningEffort: "low" }` in the runtime policy silently loses that setting, causing the turn to run with no `effort` field or the wrong fallback in plan mode.
      @@ -0,0 +534,21 @@
      534+ })),
      535+ ];
      536+
      537+ if (requiresApproval) {
      538+ rules.push({ permission: "*", pattern: "*", action: "ask" });
      539+ for (const permission of OPENCODE_RESTRICTED_PERMISSIONS) {
      540+ rules.push({ permission, pattern: "*", action: "ask" });
      541+ }
      542+ }
      543+
      544+ rules.push(
      545+ ...OPENCODE_ALWAYS_ALLOWED_PERMISSIONS.map((permission) => ({
      546+ permission,
      547+ pattern: "*",
      548+ action: "allow" as const,
      549+ })),
      550+ );
      551+
      552+ if (runtimePolicy.runtimeMode === "auto-accept-edits" || sandboxType === "workspaceWrite") {
      553+ rules.push({ permission: "edit", pattern: "*", action: "allow" });
      554+ }
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Adapters/OpenCodeAdapterV2.ts:552

      When runtimePolicy.runtimeMode === "auto-accept-edits", line 552 unconditionally appends { permission: "edit", pattern: "*", action: "allow" } to the rules, even if sandboxPolicy.type is "readOnly". A caller can combine approvalPolicy: "never" with a read-only sandbox and receive silent write access, violating the sandbox boundary. Consider guarding the edit-allow rule with sandboxType !== "readOnly" to respect the requested sandbox policy.

      -  if (runtimePolicy.runtimeMode === "auto-accept-edits" || sandboxType === "workspaceWrite") {
      +  if (sandboxType === "workspaceWrite" || (runtimePolicy.runtimeMode === "auto-accept-edits" && sandboxType !== "readOnly")) {
           rules.push({ permission: "edit", pattern: "*", action: "allow" });
         }
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts around lines 552-554:
      
      When `runtimePolicy.runtimeMode === "auto-accept-edits"`, line 552 unconditionally appends `{ permission: "edit", pattern: "*", action: "allow" }` to the rules, even if `sandboxPolicy.type` is `"readOnly"`. A caller can combine `approvalPolicy: "never"` with a read-only sandbox and receive silent write access, violating the sandbox boundary. Consider guarding the edit-allow rule with `sandboxType !== "readOnly"` to respect the requested sandbox policy.
    17. @@ -106,15 +99,4 @@
      10699 return emptyDiff;
      107100 }
      108101
      109- const threadContext = yield* projectionSnapshotQuery
      110- .getThreadCheckpointContext(input.threadId)
      111- .pipe(Effect.withSpan("checkpoint.turnDiff.lookupContext"));
      112- if (Option.isNone(threadContext)) {
      113- return yield* new CheckpointThreadNotFoundError({
      114- operation,
      115- threadId: input.threadId,
      116- });
      117- }
      118-
      119- const maxTurnCount = threadContext.value.checkpoints.reduce(
      120- (max, checkpoint) => Math.max(max, checkpoint.checkpointTurnCount),
      102+ const projection = yield* threads.getThreadProjection(input.threadId).pipe(
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium checkpointing/CheckpointDiffQuery.ts:102

      threads.getThreadProjection errors are unconditionally mapped to CheckpointThreadNotFoundError, so storage failures (e.g., PersistenceSqlError, PersistenceDecodeError) are misreported as missing threads. This causes checkpoint diff requests to return 404-style errors instead of the actual operational failures, breaking the CheckpointServiceError contract and hiding recoverable problems. Consider preserving the original error for projection lookup failures while only mapping None (thread not found) to CheckpointThreadNotFoundError.

      Also found in 2 other location(s)

      apps/server/src/orchestration-v2/ProviderSwitchService.ts:80

      ProviderSwitchServiceV2.plan wraps adapters.getMetadata(...) and adapters.get(...) with Effect.option at lines 80-82. In Effect, Effect.option converts any expected failure into Option.none(), so registry errors such as ProviderAdapterRegistryMetadataError or driver creation failures are silently treated as &#34;provider unavailable&#34;. A temporary metadata/capabilities failure will therefore produce a misleading reject plan instead of surfacing the real error, and a broken current-instance lookup can incorrectly force create_with_handoff/null transition logic.

      apps/server/src/orchestration-v2/ThreadManagementService.ts:241

      getProjectThread maps every orchestrator.getThreadProjection failure to ThreadManagementError with code thread_not_found. OrchestratorV2.getThreadProjection wraps both missing-thread cases and storage/decoding failures as OrchestratorProjectionError, so a database/read failure will now be reported to callers as a 404-style missing thread instead of an orchestration failure. Any caller of getProjectThread, sendToThread, waitForThread, or interruptThread can therefore return the wrong error and mis-handle real backend outages as if the thread did not exist.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/server/src/checkpointing/CheckpointDiffQuery.ts around line 102:
      
      `threads.getThreadProjection` errors are unconditionally mapped to `CheckpointThreadNotFoundError`, so storage failures (e.g., `PersistenceSqlError`, `PersistenceDecodeError`) are misreported as missing threads. This causes checkpoint diff requests to return 404-style errors instead of the actual operational failures, breaking the `CheckpointServiceError` contract and hiding recoverable problems. Consider preserving the original error for projection lookup failures while only mapping `None` (thread not found) to `CheckpointThreadNotFoundError`.
      
      Also found in 2 other location(s):
      - apps/server/src/orchestration-v2/ProviderSwitchService.ts:80 -- `ProviderSwitchServiceV2.plan` wraps `adapters.getMetadata(...)` and `adapters.get(...)` with `Effect.option` at lines `80`-`82`. In Effect, `Effect.option` converts any expected failure into `Option.none()`, so registry errors such as `ProviderAdapterRegistryMetadataError` or driver creation failures are silently treated as "provider unavailable". A temporary metadata/capabilities failure will therefore produce a misleading reject plan instead of surfacing the real error, and a broken current-instance lookup can incorrectly force `create_with_handoff`/`null` transition logic.
      - apps/server/src/orchestration-v2/ThreadManagementService.ts:241 -- `getProjectThread` maps every `orchestrator.getThreadProjection` failure to `ThreadManagementError` with code `thread_not_found`. `OrchestratorV2.getThreadProjection` wraps both missing-thread cases and storage/decoding failures as `OrchestratorProjectionError`, so a database/read failure will now be reported to callers as a 404-style missing thread instead of an orchestration failure. Any caller of `getProjectThread`, `sendToThread`, `waitForThread`, or `interruptThread` can therefore return the wrong error and mis-handle real backend outages as if the thread did not exist.
      
      @@ -0,0 +367,21 @@
      367+ run: (input) => RunId.make(joinId("run", "thread", input.threadId, "ordinal", input.ordinal)),
      368+ runAttempt: (input) =>
      369+ RunAttemptId.make(
      370+ joinId("run-attempt", "run", input.runId, "attempt", input.attemptOrdinal),
      371+ ),
      372+ rootNode: (input) => NodeId.make(joinId("node", "run", input.runId, "root")),
      373+ rootNodeAttempt: (input) =>
      374+ NodeId.make(joinId("node", "run", input.runId, "attempt", input.attemptOrdinal, "root")),
      375+ userTurnItem: (input) => TurnItemId.make(joinId("turn-item", "message", input.messageId)),
      376+ runSignalTurnItem: (input) =>
      377+ TurnItemId.make(joinId("turn-item", "run", input.runId, "signal", input.signal)),
      378+ providerThread: (input) =>
      379+ ProviderThreadId.make(
      380+ joinId(
      381+ "provider-thread",
      382+ "provider",
      383+ input.driver,
      384+ "native-thread",
      385+ input.nativeThreadId,
      386+ ),
      387+ ),
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High orchestration-v2/IdAllocator.ts:378

      The derived ProviderThreadId and ProviderTurnId IDs in derive.providerThread (line 378) and derive.providerTurn (line 388) only include driver + nativeThreadId/nativeTurnId, omitting ProviderInstanceId. When two configured instances of the same driver reuse a native ID, they generate identical orchestration IDs, causing cross-instance state corruption (events and stored records collapse onto one object). Consider including providerInstanceId in the ID join to ensure uniqueness per instance.

      -      providerThread: (input) =>
      -        ProviderThreadId.make(
      -          joinId(
      -            "provider-thread",
      -            "provider",
      -            input.driver,
      -            "native-thread",
      -            input.nativeThreadId,
      -          ),
      -        ),
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/server/src/orchestration-v2/IdAllocator.ts around lines 378-387:
      
      The derived `ProviderThreadId` and `ProviderTurnId` IDs in `derive.providerThread` (line 378) and `derive.providerTurn` (line 388) only include `driver` + `nativeThreadId`/`nativeTurnId`, omitting `ProviderInstanceId`. When two configured instances of the same driver reuse a native ID, they generate identical orchestration IDs, causing cross-instance state corruption (events and stored records collapse onto one object). Consider including `providerInstanceId` in the ID join to ensure uniqueness per instance.
      @@ -0,0 +426,21 @@
      426+ normalized === "edit" ||
      427+ normalized.includes("write") ||
      428+ normalized.includes("patch") ||
      429+ normalizedTool.includes("edit") ||
      430+ normalizedTool.includes("write") ||
      431+ normalizedTool.includes("patch")
      432+ ) {
      433+ return "file-change";
      434+ }
      435+ if (
      436+ normalized === "read" ||
      437+ normalized === "glob" ||
      438+ normalized === "grep" ||
      439+ normalized === "lsp" ||
      440+ normalized === "external_directory" ||
      441+ normalizedTool === "read" ||
      442+ normalizedTool.includes("glob") ||
      443+ normalizedTool.includes("grep") ||
      444+ normalizedTool.includes("search")
      445+ ) {
      446+ return "file-read";
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/OpenCodeAdapterV2.ts:419

      openCodePermissionRequestKind misclassifies network/external access permissions as file-read. When toolName includes "search" (e.g., websearch, codesearch) or when permission is external_directory, the function returns file-read instead of command. This causes the UI to present network/external access requests as harmless file reads, misleading users into approving riskier actions.

      -  if (
      -    normalized === "read" ||
      -    normalized === "glob" ||
      -    normalized === "grep" ||
      -    normalized === "lsp" ||
      -    normalized === "external_directory" ||
      -    normalizedTool === "read" ||
      -    normalizedTool.includes("glob") ||
      -    normalizedTool.includes("grep") ||
      -    normalizedTool.includes("search")
      -  ) {
      +  if (
      +    normalized === "read" ||
      +    normalized === "glob" ||
      +    normalized === "grep" ||
      +    normalized === "lsp" ||
      +    normalizedTool === "read" ||
      +    normalizedTool.includes("glob") ||
      +    normalizedTool.includes("grep")
      +  ) {
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts around lines 419-446:
      
      `openCodePermissionRequestKind` misclassifies network/external access permissions as `file-read`. When `toolName` includes "search" (e.g., `websearch`, `codesearch`) or when `permission` is `external_directory`, the function returns `file-read` instead of `command`. This causes the UI to present network/external access requests as harmless file reads, misleading users into approving riskier actions.

Sign in to join this conversation.