Skip to content
Source
Sign inSign up
pingdotgg/t3code

feat(mobile): support orchestration V2 on Android #3870

ClosedPixPMusic(GitHub profile, opens in a new tab)wants to merge 99 commits intoandroid-dev-pr-3514 fromrefs/pull/3870/headopened View on GitHub

Stacking

Warning

This PR is stacked on two branches: it targets #3579 (android-dev-pr-3514) and requires #2829. Because GitHub can only express one base, the branch carries a merge of t3code/codex-turn-mapping, so the diff below includes #2829's changes until #2829 lands. Review the four commits after Merge orchestration v2 (#2829).

Summary

Makes the Orchestration V2 experience work on the Android app:

  • resolve the Android/V2 merge seams: the V2 shell/thread cache rides the Android SQLite cache store, adapted to the V2 snapshot contracts
  • fix(mobile): render V2 controls on Android — Android icon mappings for every symbol used by the V2 lineage banner, activity inspector, queue controls, and work-log thread links (iOS keeps delegating to expo-symbols)
  • fix(mobile): keep stop and steer responsive — the composer send action reflects actual delivery semantics (offline/backlogged → Queue; connected active turn → Steer) and messages deliver to a busy run instead of failing; the shared control-lane and Codex acknowledgement fixes ship separately in #3865
  • test(mobile): pin subagent result rendering — locks provider parity for projected subagent results in the activity views (pairs with #3866)
  • fix(mobile): avoid unsupported Hermes array sorting — Hermes 250829098.0.10 lacks Array.prototype.toSorted; release builds crashed opening a thread (ThreadRelationshipsBanner), replaced with immutable sort() equivalents plus a regression test

Validation

  • vp check, vp run typecheck — green across all 15 packages
  • focused mobile suites (composer model, outbox, activity views, relationship rows) — 32 tests passing
  • the same changes were validated on-device from the integration branch: bundled Release APK on a Pixel 7 Pro and the t3test AVD, cold launch clean with no Hermes/Nitro errors

Note

Medium Risk Broad mobile orchestration UI and cache contract changes affect thread messaging, queueing, and reconnect behavior; risk is mitigated by focused tests but the stacked diff increases review blast radius.

Overview Brings the mobile app onto Orchestration V2 end-to-end: shell/thread caches use shared ORCHESTRATION_CACHE_SCHEMA_VERSION and V2 snapshot shapes (projection.thread.id), and thread screens consume V2 shell projections, visibleTurnItems, and RuntimeRequestId for approvals/input instead of V1 turn/session models.

New thread UX wired to V2 workflows includes a lineage banner (fork/subagent/transfer navigation, merge-back, session detach), queue reorder/promote-to-steer, an activity inspector with structured payloads and checkpoint rollback, fork-from-assistant actions, and updated pending approval/input cards that respect live vs stale provider response capability.

Android-specific fixes: Tabler icon mappings for every SF Symbol used by those surfaces, composer Send / Steer / Queue labeling via resolveThreadComposerSendLabel and stop driven by threadRuntimeIsActive, and a Hermes crash fix replacing Array.prototype.toSorted with immutable sort() in orderThreadRelationshipRows (with regression test).

The diff also carries stacked changes (desktop userdata-v2 paths, large .plans docs, marketing copy) from the integration branch; the mobile commits above are the intended product scope.

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

Note

Add Orchestration V2 support to the Android mobile app, replacing session/turn model with runtime/run model

  • The mobile app's thread state, composer, approval/input cards, and status indicators are migrated from the v1 session/turn model to the v2 runtime/run model; useSelectedThreadDetail is replaced by useSelectedThreadProjection and useSelectedThreadVisibleTurnItems throughout.
  • New mobile UI components are added: ThreadRelationshipsBanner (fork/transfer/subagent navigation and merge-back), ThreadQueueControl (reorder and promote queued runs), ThreadActivityInspector (structured item detail view), and PendingApprovalCard/PendingUserInputCard now disable actions when responseCapability !== 'live'.
  • The server ships a full Orchestration V2 stack: ProjectionStoreV2, EventSinkV2, EventStoreV2, ProviderSessionManagerV2, OrchestratorV2, RunExecutionService, provider adapters (Codex, Claude, Cursor, Grok, OpenCode, ACP Registry), and database migrations 033–040.
  • A new Scheduled Tasks feature is introduced end-to-end: contracts, server service, SQL persistence (migration 040), settings UI (ScheduledTasksSettings), and a per-thread automations panel.
  • The MCP server gains an orchestrator toolkit (OrchestratorMcpService) exposing thread lifecycle, task delegation, and scheduling over MCP.
  • Cursor now uses @cursor/sdk directly instead of spawning an ACP runtime; CURSOR_API_KEY is required from provider environment settings.
  • Risk: Server state directory renamed from userdata to userdata-v2 and desktop app directories updated to t3code-v2; existing installations will start with a fresh state directory.
📊 Macroscope summarized a706e39. 5 files reviewed, 0 issues evaluated, 0 issues filtered, 0 comments posted

🗂️ Filtered Issues

No issues evaluated.

    1. coderabbitai[bot](GitHub profile, opens in a new tab)commented

      Important

      Review skipped

      Auto reviews are disabled on this repository. Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

      ⚙️ Run configuration

      Configuration used: Repository UI

      Review profile: CHILL

      Plan: Pro

      Run ID: 28a012fa-6522-46d9-8e3c-3d1f38bb31c5

      You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

      Use the checkbox below for a quick retry:

      • 🔍 Trigger review
      ✨ Finishing Touches
      🧪 Generate unit tests (beta)
      • Create PR with unit tests

      Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

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

    3. Cursor Bugbot has reviewed your changes using high effort and found 2 potential issues.

      Fix All in Cursor ❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, enable autofix in the [Cursor dashboard](https://www.cursor.com/dashboard/bugbot). Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 14e18da8b892ab2a20a65c9b20c24a483d844344. Configure [here](https://www.cursor.com/dashboard/bugbot).
      @@ -0,0 +1,14 @@
      1+import type { RemoteClientConnectionState } from "../../lib/connection";
      2+
      3+export type ThreadComposerSendLabel = "Queue" | "Send" | "Steer";
      4+
      5+export function resolveThreadComposerSendLabel(input: {
      6+ readonly connectionState: RemoteClientConnectionState;
      7+ readonly activeThreadBusy: boolean;
      8+ readonly queueCount: number;
      9+}): ThreadComposerSendLabel {
      10+ if (input.connectionState !== "connected" || input.queueCount > 0) {
      11+ return "Queue";
      12+ }
      13+ return input.activeThreadBusy ? "Steer" : "Send";
      14+}

      Steer label mismatches queue dispatch

      Medium Severity

      The composer's primary action label (Send, Queue, Steer) can misrepresent how a message will be handled. The resolveThreadComposerSendLabel function determines this label, but it can show "Steer" when the server will queue the message, and it only considers local outbox messages for the "Queue" label, ignoring server-side queued runs.

      Additional Locations (1)
      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 14e18da8b892ab2a20a65c9b20c24a483d844344. Configure [here](https://www.cursor.com/dashboard/bugbot).
      @@ -0,0 +53,21 @@
      53+export function ThreadRelationshipsBanner(props: {
      54+ readonly environmentId: EnvironmentId;
      55+ readonly threadId: ThreadId;
      56+}) {
      57+ const scopedProjection = useThreadProjection(props);
      58+ const projection = scopedProjection?.projection ?? null;
      59+ const threadShells = useThreadShells();
      60+ const environmentIds = useMemo(() => [props.environmentId], [props.environmentId]);
      61+ const archived = useArchivedThreadSnapshots(environmentIds);
      62+ const archivedShells =
      63+ archived.snapshots.find((entry) => entry.environmentId === props.environmentId)?.snapshot
      64+ .threads ?? EMPTY_THREAD_SHELLS;
      65+ const shells = useMemo<ReadonlyArray<OrchestrationV2ThreadShell>>(() => {
      66+ const environmentShells: OrchestrationV2ThreadShell[] = [];
      67+ for (const thread of threadShells) {
      68+ if (thread.environmentId === props.environmentId) {
      69+ environmentShells.push(thread.source);
      70+ }
      71+ }
      72+ environmentShells.push(...archivedShells);
      73+ return environmentShells;

      Archived shells overwrite live threads

      Medium Severity

      Building the relationship graph appends archived shell snapshots after active environment shells. deriveThreadRelationshipGraph keeps one node per thread id, so a stale archived row for a still-active thread replaces the live shell and can mark navigation as Archived or show wrong titles.

      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 14e18da8b892ab2a20a65c9b20c24a483d844344. Configure [here](https://www.cursor.com/dashboard/bugbot).

      This graph construction (including appending archived snapshots after live shells) comes from the #2829 base via the stack merge — this PR's commits only touch the sorting calls below it. Keeping the fix out of this PR to avoid widening the diff beyond the mobile stack; it's worth raising on #2829 itself.

    4. @@ -460,8 +461,4 @@
      460461 void navigation.navigate("Connections");
      461462 }, [navigation]);
      462463 const handleStopThread = useCallback(() => {
      463- if (
      464- !selectedThread ||
      465- (selectedThread.session?.status !== "running" &&
      466- selectedThread.session?.status !== "starting")
      467- ) {
      464+ const runtime = selectedThread?.runtime;
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High threads/ThreadRouteScreen.tsx:464

      handleStopThread checks selectedThread.runtime from the thread shell snapshot to decide whether to interrupt, but the busy/send state shown in the composer is derived from the projection in useThreadComposerState(). When the projection has an active run but the shell snapshot is stale, the composer shows the thread as busy while handleStopThread returns early without calling threadEnvironment.interruptTurn, making the Stop control a no-op for active runs. Consider basing the interrupt guard on the same projection-derived runtime state the composer uses.

      Also found in 1 other location(s)

      apps/mobile/src/features/threads/ThreadComposer.tsx:316

      showStopAction now follows threadRuntimeIsActive(props.selectedThread.runtime), which treats queued as active. In a thread that only has server-queued runs, the collapsed composer switches its primary control from send/queue to the destructive stop pill, even though the expanded composer still labels the send action as Queue. This makes the collapsed composer show the wrong action and can cause users to cancel queued work instead of adding another queued message.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/mobile/src/features/threads/ThreadRouteScreen.tsx around line 464:
      
      `handleStopThread` checks `selectedThread.runtime` from the thread shell snapshot to decide whether to interrupt, but the busy/send state shown in the composer is derived from the projection in `useThreadComposerState()`. When the projection has an active run but the shell snapshot is stale, the composer shows the thread as busy while `handleStopThread` returns early without calling `threadEnvironment.interruptTurn`, making the Stop control a no-op for active runs. Consider basing the interrupt guard on the same projection-derived runtime state the composer uses.
      
      Also found in 1 other location(s):
      - apps/mobile/src/features/threads/ThreadComposer.tsx:316 -- `showStopAction` now follows `threadRuntimeIsActive(props.selectedThread.runtime)`, which treats `queued` as active. In a thread that only has server-queued runs, the collapsed composer switches its primary control from send/queue to the destructive stop pill, even though the expanded composer still labels the send action as `Queue`. This makes the collapsed composer show the wrong action and can cause users to cancel queued work instead of adding another queued message.
      

      handleStopThread and its shell-snapshot guard come from the #2829 base (git blame shows only base commits on these lines); this PR's commits don't touch the stop path. Out of scope for the mobile stack — worth raising on #2829, where the same guard/composer divergence exists.

      Sorry, I'm unable to act on this request because you do not have permissions within this repository.

      @@ -440,3 +450,4 @@
      440450 <WorkingDurationPill startedAt={props.activeWorkStartedAt} />
      441451 ) : null}
      442452
      453+ <ThreadQueueControl
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium threads/ThreadDetailScreen.tsx:453

      When a thread has queued runs, the ThreadQueueControl panel rendered inside the floating overlay can overlap the ThreadFeed empty/unavailable placeholder, partially obscuring it. estimatedOverlayHeight only accounts for the composer chrome and WorkingDurationPill, but ThreadQueueControl also contributes to the overlay height. ThreadFeed receives that estimate as contentBottomInset, so it does not reserve enough space for the queue panel.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/mobile/src/features/threads/ThreadDetailScreen.tsx around line 453:
      
      When a thread has queued runs, the `ThreadQueueControl` panel rendered inside the floating overlay can overlap the `ThreadFeed` empty/unavailable placeholder, partially obscuring it. `estimatedOverlayHeight` only accounts for the composer chrome and `WorkingDurationPill`, but `ThreadQueueControl` also contributes to the overlay height. `ThreadFeed` receives that estimate as `contentBottomInset`, so it does not reserve enough space for the queue panel.

      This wiring (queue-control overlay / relationships banner as topAccessory) is present verbatim in the #2829 base's ThreadDetailScreen — the diff shows it only because this stack merges t3code/codex-turn-mapping. Out of scope here; belongs on #2829.

      Sorry, I'm unable to act on this request because you do not have permissions within this repository.

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

      🟡 Medium

      https://github.com/pingdotgg/t3code/blob/a706e3993e1f30d7fed733a89bd88e390910bd43/apps/mobile/src/features/threads/ThreadDetailScreen.tsx#L1

      The ThreadRelationshipsBanner passed as topAccessory is silently dropped whenever contentPresentation.kind is "unavailable" — ThreadFeed returns the placeholder early and never mounts the ListHeaderComponent that renders topAccessory, so the lineage banner and its detach/merge actions disappear when a thread is loading, disconnected, or unavailable. Consider rendering topAccessory in the placeholder path as well, or hoisting it above the early return in ThreadFeed.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/mobile/src/features/threads/ThreadDetailScreen.tsx around line 1:
      
      The `ThreadRelationshipsBanner` passed as `topAccessory` is silently dropped whenever `contentPresentation.kind` is `"unavailable"` — `ThreadFeed` returns the placeholder early and never mounts the `ListHeaderComponent` that renders `topAccessory`, so the lineage banner and its detach/merge actions disappear when a thread is loading, disconnected, or unavailable. Consider rendering `topAccessory` in the placeholder path as well, or hoisting it above the early return in `ThreadFeed`.
    5. This wiring (queue-control overlay / relationships banner as topAccessory) is present verbatim in the #2829 base's ThreadDetailScreen — the diff shows it only because this stack merges t3code/codex-turn-mapping. Out of scope here; belongs on #2829.

    6. Sorry, I'm unable to act on this request because you do not have permissions within this repository.

    7. @@ -0,0 +155,21 @@
      155+ }),
      156+ );
      157+ }),
      158+ );
      159+}
      160+
      161+const scenario = (readArgValue("--scenario") ?? process.env.T3_CURSOR_REPLAY_SCENARIO) as
      162+ | RecordingName
      163+ | undefined;
      164+if (scenario === undefined || RECORDINGS[scenario] === undefined) {
      165+ throw new Error(`Pass --scenario with one of: ${Object.keys(RECORDINGS).join(", ")}`);
      166+}
      167+
      168+const apiKey = process.env.CURSOR_API_KEY?.trim();
      169+if (!apiKey) {
      170+ throw new Error("CURSOR_API_KEY is required to record Cursor SDK replay fixtures.");
      171+}
      172+
      173+const recording = RECORDINGS[scenario];
      174+const workspace = await prepareWorkspace(scenario);
      175+if (scenario === "subagent" || scenario === "tool_call_read_only" || scenario === "todo_list") {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium scripts/record-cursor-agent-sdk-replay-fixture.ts:175

      writeFixtureFiles unconditionally overwrites package.json and tsconfig.json in the supplied cwd. When T3_CURSOR_REPLAY_CWD is set, prepareWorkspace returns that path with remove: false, so the script for subagent, todo_list, or tool_call_read_only overwrites the user's real project files and never cleans them up. Consider skipping writeFixtureFiles when workspace.remove is false, or writing fixture files into a subdirectory that is always cleaned up.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/scripts/record-cursor-agent-sdk-replay-fixture.ts around line 175:
      
      `writeFixtureFiles` unconditionally overwrites `package.json` and `tsconfig.json` in the supplied `cwd`. When `T3_CURSOR_REPLAY_CWD` is set, `prepareWorkspace` returns that path with `remove: false`, so the script for `subagent`, `todo_list`, or `tool_call_read_only` overwrites the user's real project files and never cleans them up. Consider skipping `writeFixtureFiles` when `workspace.remove` is `false`, or writing fixture files into a subdirectory that is always cleaned up.
      @@ -0,0 +398,21 @@
      398+ readonly payload: SDKMessage;
      399+ };
      400+
      401+export type ClaudeAgentSdkProtocolLogger = (
      402+ event: ClaudeAgentSdkProtocolLogEvent,
      403+) => Effect.Effect<void>;
      404+
      405+export function loggedClaudeQueryOptions(
      406+ options: ClaudeAgentSdkQueryOptions,
      407+): ClaudeAgentSdkLoggedQueryOptions {
      408+ return {
      409+ model: options.model,
      410+ tools: options.tools,
      411+ permissionMode: options.permissionMode,
      412+ ...(options.sessionId === undefined ? {} : { sessionId: options.sessionId }),
      413+ ...(options.resume === undefined ? {} : { resume: options.resume }),
      414+ ...(options.resumeSessionAt === undefined ? {} : { resumeSessionAt: options.resumeSessionAt }),
      415+ ...(options.cwd === undefined ? {} : { cwd: options.cwd }),
      416+ ...(options.allowedTools === undefined ? {} : { allowedTools: options.allowedTools }),
      417+ ...(options.disallowedTools === undefined ? {} : { disallowedTools: options.disallowedTools }),
      418+ ...(options.settings === undefined ? {} : { settings: options.settings }),
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Adapters/ClaudeAdapterV2.ts:418

      loggedClaudeQueryOptions copies options.settings verbatim into the native protocol log, so credentials passed via launchArgs (e.g. --token=...) are written to the provider event log in cleartext every time a Claude query is opened. env, mcpServers, and callbacks are already reduced to presence-only indicators (hasEnvironment, hasMcpServers, hasCanUseTool) to avoid leaking secrets, but settings — which contains the free-form launchArgs string — is logged in full. Consider applying the same redaction strategy to settings as is done for env and mcpServers (e.g. logging only hasSettings: true).

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts around line 418:
      
      `loggedClaudeQueryOptions` copies `options.settings` verbatim into the native protocol log, so credentials passed via `launchArgs` (e.g. `--token=...`) are written to the provider event log in cleartext every time a Claude query is opened. `env`, `mcpServers`, and callbacks are already reduced to presence-only indicators (`hasEnvironment`, `hasMcpServers`, `hasCanUseTool`) to avoid leaking secrets, but `settings` — which contains the free-form `launchArgs` string — is logged in full. Consider applying the same redaction strategy to `settings` as is done for `env` and `mcpServers` (e.g. logging only `hasSettings: true`).
      @@ -0,0 +262,21 @@
      262+ supportsModelSwitchInSession: setup.models != null || hasModelConfig,
      263+ supportsRuntimeModeSwitchInSession: setup.modes != null || hasModeConfig,
      264+ },
      265+ threads: {
      266+ ...base.threads,
      267+ canReadThreadSnapshot: canLoad,
      268+ canForkThread: canFork,
      269+ canForkFromTurn: false,
      270+ },
      271+ tools: {
      272+ ...base.tools,
      273+ supportsMcpTools: supportsMcp,
      274+ },
      275+ checkpointing: {
      276+ ...base.checkpointing,
      277+ providerCanReadConversationSnapshot: canLoad,
      278+ },
      279+ };
      280+}
      281+
      282+function acpMcpServers(threadId: ThreadId): ReadonlyArray<EffectAcpSchema.McpServer> {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/AcpAdapterV2.ts:282

      acpMcpServers always emits type: "http" even for agents that advertise only sse MCP support, so SSE-only agents receive an incompatible server config and silently fail to connect to the MCP server — MCP tools stop working for that provider. The session's MCP endpoint transport should be derived from the agent's mcpCapabilities rather than hardcoded to http.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts around line 282:
      
      `acpMcpServers` always emits `type: "http"` even for agents that advertise only `sse` MCP support, so SSE-only agents receive an incompatible server config and silently fail to connect to the MCP server — MCP tools stop working for that provider. The session's MCP endpoint transport should be derived from the agent's `mcpCapabilities` rather than hardcoded to `http`.
      @@ -0,0 +1118,21 @@
      1118+export interface ClaudeRuntimeQueryPolicy {
      1119+ readonly permissionMode: PermissionMode;
      1120+ readonly tools?: ClaudeAgentSdkQueryTools;
      1121+ readonly allowedTools?: ReadonlyArray<string>;
      1122+ readonly allowDangerouslySkipPermissions?: true;
      1123+ readonly installPermissionCallback: boolean;
      1124+}
      1125+
      1126+export function claudeRuntimeQueryPolicyForRuntimePolicy(
      1127+ runtimePolicy: ProviderAdapterV2RuntimePolicy,
      1128+): ClaudeRuntimeQueryPolicy {
      1129+ const permissionMode = permissionModeForClaudeRuntimePolicy(runtimePolicy);
      1130+ const readOnlyTools =
      1131+ permissionMode === "dontAsk" &&
      1132+ sandboxPolicyKindForClaudeRuntimePolicy(runtimePolicy) === "readOnly"
      1133+ ? CLAUDE_READ_ONLY_ALLOWED_TOOLS
      1134+ : undefined;
      1135+ const allowedTools =
      1136+ readOnlyTools !== undefined && readOnlyPolicyAllowsGlobalReads(runtimePolicy)
      1137+ ? readOnlyTools
      1138+ : undefined;
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Adapters/ClaudeAdapterV2.ts:1135

      claudeRuntimeQueryPolicyForRuntimePolicy leaves allowedTools unset for restricted read-only policies, so the tools: ["Read", "Glob", "Grep"] restriction is bypassed downstream: openQuery passes the undefined whitelist into claudeMcpQueryOverrides, which adds MCP tools without restriction. A restricted read-only sandbox can therefore still invoke mcp__* tools and escape the intended read-only limitation.

      The condition on line 1136 gates allowedTools behind readOnlyPolicyAllowsGlobalReads(runtimePolicy), so only the fullAccess read-only variant gets a whitelist populated. Consider populating allowedTools for all read-only policies (or otherwise ensuring the tool restriction applies to MCP tools as well).

      -  const allowedTools =
      -    readOnlyTools !== undefined && readOnlyPolicyAllowsGlobalReads(runtimePolicy)
      -      ? readOnlyTools
      -      : undefined;
      +  const allowedTools = readOnlyTools !== undefined ? readOnlyTools : undefined;
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts around lines 1135-1138:
      
      `claudeRuntimeQueryPolicyForRuntimePolicy` leaves `allowedTools` unset for restricted read-only policies, so the `tools: ["Read", "Glob", "Grep"]` restriction is bypassed downstream: `openQuery` passes the undefined whitelist into `claudeMcpQueryOverrides`, which adds MCP tools without restriction. A restricted read-only sandbox can therefore still invoke `mcp__*` tools and escape the intended read-only limitation.
      
      The condition on line 1136 gates `allowedTools` behind `readOnlyPolicyAllowsGlobalReads(runtimePolicy)`, so only the `fullAccess` read-only variant gets a whitelist populated. Consider populating `allowedTools` for all read-only policies (or otherwise ensuring the tool restriction applies to MCP tools as well).
      @@ -0,0 +569,21 @@
      569+ },
      570+ ];
      571+ }),
      572+ );
      573+}
      574+
      575+function nestedToolCallFromEnvelope(
      576+ envelope: Record<string, unknown>,
      577+): { readonly callId: string; readonly toolCall: ToolCall } | undefined {
      578+ const callId = typeof envelope.toolCallId === "string" ? envelope.toolCallId : undefined;
      579+ const wrapperEntry = Object.entries(envelope).find(([key]) => key.endsWith("ToolCall"));
      580+ if (wrapperEntry === undefined) {
      581+ return undefined;
      582+ }
      583+ const [wrapperName, rawCall] = wrapperEntry;
      584+ const call = unknownRecord(rawCall);
      585+ if (call === undefined) {
      586+ return undefined;
      587+ }
      588+ const args = unknownRecord(call.args) ?? {};
      589+ const fallbackCallId = `nested-${wrapperName}`;
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/CursorAdapterV2.ts:589

      When two nested tool calls of the same type arrive without toolCallId, nestedToolCallFromEnvelope assigns both calls the identical fallback id nested-${wrapperName} (e.g. two readToolCalls both get nested-readToolCall). Because downstream ids are derived from callId, the second call overwrites the first, so only one tool artifact survives in the child thread timeline. Consider making the fallback id unique, e.g. by appending a counter or random suffix.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.ts around line 589:
      
      When two nested tool calls of the same type arrive without `toolCallId`, `nestedToolCallFromEnvelope` assigns both calls the identical fallback id `nested-${wrapperName}` (e.g. two `readToolCall`s both get `nested-readToolCall`). Because downstream ids are derived from `callId`, the second call overwrites the first, so only one tool artifact survives in the child thread timeline. Consider making the fallback id unique, e.g. by appending a counter or random suffix.
      @@ -0,0 +92,21 @@
      92+ const [busyAction, setBusyAction] = useState<"merge" | "detach" | null>(null);
      93+ const navigation = useNavigation();
      94+ const mergeBack = useAtomCommand(threadEnvironment.mergeBack, "merge thread back");
      95+ const stopSession = useAtomCommand(threadEnvironment.stopSession, "thread session stop");
      96+ const insets = useSafeAreaInsets();
      97+ const backdropColor = useThemeColor("--color-backdrop");
      98+ const sheetColor = useThemeColor("--color-sheet");
      99+ const iconColor = useThemeColor("--color-icon-subtle");
      100+
      101+ if (rows.length === 0 && !canDetach) return null;
      102+
      103+ const primaryParent = rows.find(({ edge }) => edge.targetThreadId === props.threadId) ?? rows[0];
      104+ const primaryNode = primaryParent ? graph.nodes.get(primaryParent.threadId) : null;
      105+ const summary = primaryParent
      106+ ? `${relationshipLabel(primaryParent.edge, props.threadId)}: ${primaryNode?.thread?.title ?? "related thread"}`
      107+ : "Agent session connected";
      108+
      109+ const openThread = (threadId: ThreadId, archivedThread: boolean) => {
      110+ setVisible(false);
      111+ void Haptics.selectionAsync();
      112+ if (archivedThread) {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium threads/ThreadRelationshipsBanner.tsx:112

      Tapping an archived relationship row navigates to the generic SettingsArchive screen instead of the specific thread, because openThread ignores the selected threadId when archivedThread is true. The archive screen receives no target-thread parameter, so the user lands in the archive list with no way to reach the related thread they tapped. Consider passing threadId to SettingsArchive (e.g., as a route param) so archived threads can be opened directly, or document why the fallback to the list is intentional.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/mobile/src/features/threads/ThreadRelationshipsBanner.tsx around line 112:
      
      Tapping an archived relationship row navigates to the generic `SettingsArchive` screen instead of the specific thread, because `openThread` ignores the selected `threadId` when `archivedThread` is true. The archive screen receives no target-thread parameter, so the user lands in the archive list with no way to reach the related thread they tapped. Consider passing `threadId` to `SettingsArchive` (e.g., as a route param) so archived threads can be opened directly, or document why the fallback to the list is intentional.
      @@ -0,0 +502,21 @@
      502+ direction: "outgoing",
      503+ stage: "decoded",
      504+ payload: {
      505+ type: "query.open",
      506+ options: loggedClaudeQueryOptions(input.options),
      507+ },
      508+ });
      509+
      510+ return {
      511+ messages: Stream.fromAsyncIterable(queryRuntime, (cause) =>
      512+ queryRunnerError(cause, "fromAsyncIterable"),
      513+ ).pipe(
      514+ Stream.tap((message) =>
      515+ logProtocolEvent({
      516+ direction: "incoming",
      517+ stage: "decoded",
      518+ payload: message,
      519+ }),
      520+ ),
      521+ ),
      522+ offer: (message) =>
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/ClaudeAdapterV2.ts:522

      The offer method discards the boolean result of Queue.offer(promptQueue, message). After close runs Queue.shutdown(promptQueue), subsequent Queue.offer calls return false instead of enqueuing the message, so late prompt offers are silently dropped — the method still returns success and logs prompt.offer, giving the caller no indication the input was lost. Consider checking the Queue.offer result and failing (or at least skipping the log) when it returns false.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts around line 522:
      
      The `offer` method discards the boolean result of `Queue.offer(promptQueue, message)`. After `close` runs `Queue.shutdown(promptQueue)`, subsequent `Queue.offer` calls return `false` instead of enqueuing the message, so late prompt offers are silently dropped — the method still returns success and logs `prompt.offer`, giving the caller no indication the input was lost. Consider checking the `Queue.offer` result and failing (or at least skipping the log) when it returns `false`.
      @@ -66,11 +65,13 @@
      66- const selectedThread = useSelectedThreadDetail();
      65+ const selectedThread = useSelectedThreadProjection();
      6766 const userInputDraftsByRequestKey = useAtomValue(userInputDraftsByRequestKeyAtom);
      68- const [respondingApprovalId, setRespondingApprovalId] = useState<ApprovalRequestId | null>(null);
      69- const [respondingUserInputId, setRespondingUserInputId] = useState<ApprovalRequestId | null>(
      70- null,
      71- );
      72-
      73- const activePendingApprovals = useMemo(
      74- () => (selectedThread ? derivePendingApprovals(selectedThread.activities) : []),
      67+ const [respondingApprovalId, setRespondingApprovalId] = useState<RuntimeRequestId | null>(null);
      68+ const [respondingUserInputId, setRespondingUserInputId] = useState<RuntimeRequestId | null>(null);
      69+
      70+ const pendingRequests = useMemo(
      71+ () =>
      72+ selectedThread === null
      73+ ? { approvals: [], userInputs: [] }
      74+ : derivePendingThreadRequests(selectedThread.projection),
      7575 [selectedThread],
      7676 );
      77+ const activePendingApprovals = pendingRequests.approvals;
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium state/use-selected-thread-requests.ts:77

      activePendingApproval and activePendingUserInput take pendingRequests.approvals[0] and pendingRequests.userInputs[0], but derivePendingThreadRequests preserves the insertion order of projection.runtimeRequests rather than sorting by createdAt. When a thread has multiple pending approvals or user-input requests, the UI surfaces whichever request happens to be first in that arbitrary order — potentially a newer one — while an older pending request stays hidden and can never be answered. If the insertion order is guaranteed to match createdAt order upstream, consider documenting that invariant; otherwise sort the pending requests by createdAt before picking index 0.

      Also found in 1 other location(s)

      apps/mobile/src/state/use-thread-selection.ts:71

      threadDetailToShell picks the first pending runtime request with projection.runtimeRequests.find(...), while the persisted shell logic (threadShellFromProjection) sorts pending requests by newest createdAt and uses the latest one. If multiple requests are pending, this optimistic shell can expose an older request kind, so presentThreadShell derives the wrong hasPendingApprovals / hasPendingUserInput flags and the thread shows the wrong pending-action state until the shell cache catches up.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/mobile/src/state/use-selected-thread-requests.ts around line 77:
      
      `activePendingApproval` and `activePendingUserInput` take `pendingRequests.approvals[0]` and `pendingRequests.userInputs[0]`, but `derivePendingThreadRequests` preserves the insertion order of `projection.runtimeRequests` rather than sorting by `createdAt`. When a thread has multiple pending approvals or user-input requests, the UI surfaces whichever request happens to be first in that arbitrary order — potentially a newer one — while an older pending request stays hidden and can never be answered. If the insertion order is guaranteed to match `createdAt` order upstream, consider documenting that invariant; otherwise sort the pending requests by `createdAt` before picking index 0.
      
      Also found in 1 other location(s):
      - apps/mobile/src/state/use-thread-selection.ts:71 -- `threadDetailToShell` picks the first pending runtime request with `projection.runtimeRequests.find(...)`, while the persisted shell logic (`threadShellFromProjection`) sorts pending requests by newest `createdAt` and uses the latest one. If multiple requests are pending, this optimistic shell can expose an older request kind, so `presentThreadShell` derives the wrong `hasPendingApprovals` / `hasPendingUserInput` flags and the thread shows the wrong pending-action state until the shell cache catches up.
      
      @@ -0,0 +444,21 @@
      444+ }
      445+ if (result.type === "count") {
      446+ return result.output.counts.map((entry) => ({
      447+ fileName: entry.file,
      448+ preview: `${entry.count} matches`,
      449+ }));
      450+ }
      451+ return result.output.matches.map((entry) => ({
      452+ fileName: entry.file,
      453+ ...(entry.lineNumber === undefined ? {} : { line: entry.lineNumber }),
      454+ preview: entry.line,
      455+ }));
      456+ });
      457+ case "semSearch":
      458+ return [
      459+ {
      460+ fileName: "semantic-search",
      461+ preview: toolCall.result.value.results,
      462+ },
      463+ ];
      464+ default:
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/CursorAdapterV2.ts:464

      cursorToolSearchResults returns [] for successful ls and readLints tool calls because the switch only handles read, glob, grep, and semSearch, falling through to default. Callers classify these tool types as file-search items, so the UI renders a blank file-search card with no files or lint output. Consider adding case "ls": and case "readLints": branches that map toolCall.result.value into the expected { fileName, ... } result shape.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.ts around line 464:
      
      `cursorToolSearchResults` returns `[]` for successful `ls` and `readLints` tool calls because the `switch` only handles `read`, `glob`, `grep`, and `semSearch`, falling through to `default`. Callers classify these tool types as file-search items, so the UI renders a blank file-search card with no files or lint output. Consider adding `case "ls":` and `case "readLints":` branches that map `toolCall.result.value` into the expected `{ fileName, ... }` result shape.
      @@ -0,0 +1196,21 @@
      1196+const CLAUDE_KNOWN_TOOL_CLASSIFICATIONS: Record<
      1197+ string,
      1198+ {
      1199+ readonly itemType: ClaudeToolItemType;
      1200+ readonly requestKind: ProviderRequestKind;
      1201+ }
      1202+> = {
      1203+ agent: { itemType: "dynamic_tool", requestKind: "command" },
      1204+ bash: { itemType: "command_execution", requestKind: "command" },
      1205+ edit: { itemType: "file_change", requestKind: "file-change" },
      1206+ glob: { itemType: "dynamic_tool", requestKind: "file-read" },
      1207+ grep: { itemType: "dynamic_tool", requestKind: "file-read" },
      1208+ ls: { itemType: "dynamic_tool", requestKind: "file-read" },
      1209+ multiedit: { itemType: "file_change", requestKind: "file-change" },
      1210+ notebookedit: { itemType: "file_change", requestKind: "file-change" },
      1211+ read: { itemType: "dynamic_tool", requestKind: "file-read" },
      1212+ task: { itemType: "dynamic_tool", requestKind: "command" },
      1213+ todowrite: { itemType: "dynamic_tool", requestKind: "command" },
      1214+ toolsearch: { itemType: "dynamic_tool", requestKind: "command" },
      1215+ webfetch: { itemType: "web_search", requestKind: "command" },
      1216+ websearch: { itemType: "web_search", requestKind: "command" },
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/ClaudeAdapterV2.ts:1215

      CLAUDE_KNOWN_TOOL_CLASSIFICATIONS is missing several normalized tool names (e.g., bashcodeexecution, webfetch, task, todowrite), so classifyClaudeNativeTool falls through to the unknown branch and emits dynamic_tool items instead of command_execution/file_change items. Those Claude tool results are silently misprojected in the transcript and UI. Add entries for the missing normalized names (for example bashcodeexecution, webfetch) to the classification map so fallback-path tool results are classified correctly.

        toolsearch: { itemType: "dynamic_tool", requestKind: "command" },
      + bashcodeexecution: { itemType: "command_execution", requestKind: "command" },
        webfetch: { itemType: "web_search", requestKind: "command" },
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts around lines 1215-1216:
      
      `CLAUDE_KNOWN_TOOL_CLASSIFICATIONS` is missing several normalized tool names (e.g., `bashcodeexecution`, `webfetch`, `task`, `todowrite`), so `classifyClaudeNativeTool` falls through to the unknown branch and emits `dynamic_tool` items instead of `command_execution`/`file_change` items. Those Claude tool results are silently misprojected in the transcript and UI. Add entries for the missing normalized names (for example `bashcodeexecution`, `webfetch`) to the classification map so fallback-path tool results are classified correctly.
      @@ -0,0 +1067,21 @@
      1067+ type: Schema.Literal("fullAccess"),
      1068+ }),
      1069+});
      1070+
      1071+function sandboxPolicyKindForClaudeRuntimePolicy(
      1072+ runtimePolicy: ProviderAdapterV2RuntimePolicy,
      1073+): ClaudeRuntimeSandboxPolicyKindName | undefined {
      1074+ return runtimePolicy.sandboxPolicy !== undefined &&
      1075+ Schema.is(ClaudeRuntimeSandboxPolicyKind)(runtimePolicy.sandboxPolicy)
      1076+ ? runtimePolicy.sandboxPolicy.type
      1077+ : undefined;
      1078+}
      1079+
      1080+function readOnlyPolicyAllowsGlobalReads(runtimePolicy: ProviderAdapterV2RuntimePolicy): boolean {
      1081+ return (
      1082+ runtimePolicy.sandboxPolicy !== undefined &&
      1083+ Schema.is(ClaudeRuntimeReadOnlyFullAccessSandboxPolicy)(runtimePolicy.sandboxPolicy)
      1084+ );
      1085+}
      1086+
      1087+function permissionModeForClaudeRuntimePolicy(
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Adapters/ClaudeAdapterV2.ts:1087

      permissionModeForClaudeRuntimePolicy silently widens an explicit workspaceWrite or externalSandbox sandbox policy to full access. For example, a policy with runtimeMode: "full-access", approvalPolicy: "never", and sandboxPolicy: { type: "workspaceWrite" } returns "bypassPermissions" instead of a mode that respects the sandbox restriction.

      The switch on sandboxPolicyKindForClaudeRuntimePolicy falls through the workspaceWrite and externalSandbox cases without returning, so execution continues to the runtimeMode switch, which derives "bypassPermissions" from "full-access". Since the adapter relies on this mapping for enforcement and never passes the sandbox policy to the SDK, the explicit restriction is lost. Consider returning a mode that preserves the sandbox boundary for those cases, or document why the fallthrough is intentional.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts around line 1087:
      
      `permissionModeForClaudeRuntimePolicy` silently widens an explicit `workspaceWrite` or `externalSandbox` sandbox policy to full access. For example, a policy with `runtimeMode: "full-access"`, `approvalPolicy: "never"`, and `sandboxPolicy: { type: "workspaceWrite" }` returns `"bypassPermissions"` instead of a mode that respects the sandbox restriction.
      
      The `switch` on `sandboxPolicyKindForClaudeRuntimePolicy` falls through the `workspaceWrite` and `externalSandbox` cases without returning, so execution continues to the `runtimeMode` switch, which derives `"bypassPermissions"` from `"full-access"`. Since the adapter relies on this mapping for enforcement and never passes the sandbox policy to the SDK, the explicit restriction is lost. Consider returning a mode that preserves the sandbox boundary for those cases, or document why the fallthrough is intentional.
      @@ -0,0 +673,21 @@
      673+ : {}),
      674+ ...(input.environment === undefined ? {} : { env: input.environment }),
      675+ ...(input.mcpServers === undefined ? {} : { mcpServers: input.mcpServers }),
      676+ ...(Object.keys(extraArgs).length === 0 ? {} : { extraArgs }),
      677+ };
      678+ return input.cwd === null ? options : { ...options, cwd: input.cwd };
      679+}
      680+
      681+export function claudeMcpQueryOverrides(input: {
      682+ readonly threadId: ThreadId;
      683+ readonly allowedTools?: ReadonlyArray<string>;
      684+}): {
      685+ readonly allowedTools?: ReadonlyArray<string>;
      686+ readonly mcpServers?: ClaudeQueryOptions["mcpServers"];
      687+} {
      688+ const session = McpProviderSession.readMcpProviderSession(input.threadId);
      689+ if (session === undefined) {
      690+ return input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools };
      691+ }
      692+ return {
      693+ allowedTools: Array.from(new Set([...(input.allowedTools ?? []), "mcp__t3-code__*"])),
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/ClaudeAdapterV2.ts:693

      claudeMcpQueryOverrides always adds "mcp__t3-code__*" to allowedTools when an MCP session is present, but the pinned Claude Agent SDK version does not resolve wildcard entries against MCP tool names. This means every t3-code MCP tool call gets denied at the permission layer instead of being permitted, so the MCP-backed flow cannot execute any tool calls. The wildcard pattern needs to be expanded to concrete tool names (or handled through a different allow-list mechanism that the SDK recognizes), otherwise the MCP integration is effectively non-functional.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts around line 693:
      
      `claudeMcpQueryOverrides` always adds `"mcp__t3-code__*"` to `allowedTools` when an MCP session is present, but the pinned Claude Agent SDK version does not resolve wildcard entries against MCP tool names. This means every `t3-code` MCP tool call gets denied at the permission layer instead of being permitted, so the MCP-backed flow cannot execute any tool calls. The wildcard pattern needs to be expanded to concrete tool names (or handled through a different allow-list mechanism that the SDK recognizes), otherwise the MCP integration is effectively non-functional.
      @@ -0,0 +119,21 @@
      119+ canCreateEmptyThread: true,
      120+ canReadThreadSnapshot: true,
      121+ canRollbackThread: true,
      122+ canForkThread: true,
      123+ canForkFromTurn: true,
      124+ canForkFromSubagentThread: true,
      125+ exposesNativeThreadId: true,
      126+ },
      127+ turns: {
      128+ exposesNativeTurnId: true,
      129+ emitsTurnStarted: true,
      130+ emitsTurnCompleted: true,
      131+ supportsInterrupt: true,
      132+ supportsActiveSteering: true,
      133+ supportsSteeringByInterruptRestart: true,
      134+ supportsQueuedMessages: true,
      135+ terminalStatusQuality: "strong",
      136+ },
      137+ streaming: {
      138+ streamsAssistantText: true,
      139+ streamsReasoning: true,
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/CodexAdapterV2.ts:139

      CodexProviderCapabilitiesV2.streaming.streamsReasoning is true, but the adapter never projects Codex reasoning items into any node, message, or turn_item events. The item/started and item/completed handlers cover userMessage, agentMessage, tools, plans, and web search, but not reasoning, so reasoning traces are silently dropped. Any caller that enables reasoning UI based on this capability will show empty or missing reasoning output for Codex sessions.

      If streaming reasoning is not yet implemented, set streamsReasoning to false until the adapter emits reasoning items, or add handler logic that projects reasoning items into the appropriate events.

      -    streamsReasoning: true,
      +    streamsReasoning: false,
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts around line 139:
      
      `CodexProviderCapabilitiesV2.streaming.streamsReasoning` is `true`, but the adapter never projects Codex `reasoning` items into any `node`, `message`, or `turn_item` events. The `item/started` and `item/completed` handlers cover `userMessage`, `agentMessage`, tools, plans, and web search, but not `reasoning`, so reasoning traces are silently dropped. Any caller that enables reasoning UI based on this capability will show empty or missing reasoning output for Codex sessions.
      
      If streaming reasoning is not yet implemented, set `streamsReasoning` to `false` until the adapter emits reasoning items, or add handler logic that projects `reasoning` items into the appropriate events.
      @@ -1043,13 +431,11 @@
      1043- const unsettledTurnId = deriveUnsettledTurnId(latestTurn);
      1044- const foldsByAnchorId = new Map<string, ThreadFeedTurnFold>();
      1045- for (const [turnId, group] of groupsByTurnId) {
      1046- const { entries } = group;
      1047- if (turnId === unsettledTurnId) {
      1048- continue;
      1049- }
      1050- if (entries.some((entry) => entry.type === "message" && entry.message.streaming)) {
      431+ const activeRunId = unsettledRunId(latestRun);
      432+ const foldsByAnchorId = new Map<string, ThreadFeedRunFold>();
      433+ for (const [runId, group] of groupsByRunId) {
      434+ if (
      435+ runId === activeRunId ||
      436+ group.entries.some((entry) => entry.type === "message" && entry.message.streaming)
      437+ ) {
      1051438 continue;
      1052439 }
      1053-
      1054- const terminalAssistantMessageId = terminalAssistantMessageIdByTurn.get(turnId);
      440+ const terminalAssistantId = terminalAssistantMessageIdByRun.get(runId);
      1055441 const hiddenEntryIds = new Set(
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium lib/threadActivity.ts:441

      deriveThreadFeedRunFolds collapses every entry in a completed run except the terminal assistant message, so earlier assistant messages in the same run are hidden when the run is folded. Because Orchestration V2 allows multiple assistant messages under one runId (e.g., commentary plus final reply), settled runs silently drop assistant-authored content unless the user manually expands the fold. The filter at hiddenEntryIds only preserves the entry whose id matches terminalAssistantId; it does not exclude other message entries. Consider excluding all message entries with role === "assistant" from hiddenEntryIds, not just the terminal one.

      Also found in 2 other location(s)

      apps/mobile/src/features/threads/ThreadFeed.tsx:1529

      terminalAssistantMessageIds at line 1529 is keyed only by RunId, so when a single run produces more than one assistant message, each later message overwrites the previous one. showAssistantMeta then becomes true for only the last assistant message in that run, which drops the timestamp / copy / fork controls from earlier assistant messages and, in collapsed run-fold mode, can hide earlier terminal replies from nested child threads that share the same runId.

      packages/client-runtime/src/state/threadCheckpoints.ts:35

      deriveThreadCheckpointSummaries derives assistantMessageId by taking projection.messages.findLast(...) for the whole run. Runs can contain multiple assistant messages, so a checkpoint from an earlier assistant turn in that run will be associated with the last assistant message instead of the message that existed when the checkpoint was captured. Review/diff UI keyed by assistantMessageId will attach the checkpoint to the wrong response.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/mobile/src/lib/threadActivity.ts around line 441:
      
      `deriveThreadFeedRunFolds` collapses every entry in a completed run except the terminal assistant message, so earlier assistant messages in the same run are hidden when the run is folded. Because Orchestration V2 allows multiple assistant messages under one `runId` (e.g., commentary plus final reply), settled runs silently drop assistant-authored content unless the user manually expands the fold. The filter at `hiddenEntryIds` only preserves the entry whose `id` matches `terminalAssistantId`; it does not exclude other message entries. Consider excluding all `message` entries with `role === "assistant"` from `hiddenEntryIds`, not just the terminal one.
      
      Also found in 2 other location(s):
      - apps/mobile/src/features/threads/ThreadFeed.tsx:1529 -- `terminalAssistantMessageIds` at line `1529` is keyed only by `RunId`, so when a single run produces more than one assistant message, each later message overwrites the previous one. `showAssistantMeta` then becomes true for only the last assistant message in that run, which drops the timestamp / copy / fork controls from earlier assistant messages and, in collapsed run-fold mode, can hide earlier terminal replies from nested child threads that share the same `runId`.
      - packages/client-runtime/src/state/threadCheckpoints.ts:35 -- `deriveThreadCheckpointSummaries` derives `assistantMessageId` by taking `projection.messages.findLast(...)` for the whole run. Runs can contain multiple assistant messages, so a checkpoint from an earlier assistant turn in that run will be associated with the last assistant message instead of the message that existed when the checkpoint was captured. Review/diff UI keyed by `assistantMessageId` will attach the checkpoint to the wrong response.
      
      @@ -1357,14 +559,7 @@
      1357- .filter((value, index, values): value is string => {
      1358- return Boolean(value) && values.indexOf(value) === index;
      1359- })
      1360- .join("\n"),
      1361- toolLike: workLogEntryIsToolLike(entry),
      1362- status: workEntryStatus(entry),
      1363- },
      1364- };
      1365- }),
      1366- ],
      1367- (s) => new Date(s.createdAt),
      1368- Order.Date,
      1369- );
      1370-
      559+ id: item.messageId,
      560+ createdAt,
      561+ message: {
      562+ id: item.messageId,
      563+ role: item.type === "user_message" ? "user" : "assistant",
      564+ text: item.text,
      565+ attachments: item.type === "user_message" ? item.attachments : [],
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium lib/threadActivity.ts:565

      buildThreadFeed hard-codes assistant message attachments to [], so assistant messages that carry attachments in the server projection are rendered without them in the mobile thread feed. The code only preserves attachments for user_message rows; the assistant_message branch should propagate item.attachments instead of discarding them.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/mobile/src/lib/threadActivity.ts around line 565:
      
      `buildThreadFeed` hard-codes assistant message `attachments` to `[]`, so assistant messages that carry attachments in the server projection are rendered without them in the mobile thread feed. The code only preserves attachments for `user_message` rows; the `assistant_message` branch should propagate `item.attachments` instead of discarding them.
    8. Scope note on the Macroscope sweep: because this stack merges t3code/codex-turn-mapping (see the warning at the top of the PR body), the diff — and therefore the bot review — includes all of #2829. The findings in apps/server/** and in mobile files this PR's commits don't touch (threadActivity.ts, use-selected-thread-requests.ts, the relationship-banner navigation) are #2829 base code; git blame on those lines shows only base commits. They belong on #2829, not here.

      One of them is already fixed upstream in this stack: the claudeMcpQueryOverrides read-only allowlist finding is addressed by #3862 (fix(orchestrator): scope Claude MCP tool pre-approval) on the #2829 branch.

      Review scope for this PR is the commits after Merge orchestration v2 (#2829).

    9. @@ -0,0 +427,21 @@
      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";
      447+ }
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/OpenCodeAdapterV2.ts:435

      openCodePermissionRequestKind returns "file-read" for any external_directory permission, but in OpenCode external_directory gates external writes, edits, patches, and bash workdir access — not just reads. When the tool name is unavailable (toolName is undefined) or doesn't match any read/edit heuristic, the request is misclassified as read-only, so a write-capable external-directory approval is presented and handled as a mere file-read request. Consider mapping external_directory to "file-change" (or "command") so the permission reflects its actual scope.

         if (
           normalized === "read" ||
           normalized === "glob" ||
           normalized === "grep" ||
           normalized === "lsp" ||
      -    normalized === "external_directory" ||
           normalizedTool === "read" ||
           normalizedTool.includes("glob") ||
           normalizedTool.includes("grep") ||
           normalizedTool.includes("search")
         ) {
           return "file-read";
         }
      +  if (normalized === "external_directory") {
      +    return "file-change";
      +  }
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts around lines 435-447:
      
      `openCodePermissionRequestKind` returns `"file-read"` for any `external_directory` permission, but in OpenCode `external_directory` gates external writes, edits, patches, and bash workdir access — not just reads. When the tool name is unavailable (`toolName` is `undefined`) or doesn't match any read/edit heuristic, the request is misclassified as read-only, so a write-capable external-directory approval is presented and handled as a mere file-read request. Consider mapping `external_directory` to `"file-change"` (or `"command"`) so the permission reflects its actual scope.
      @@ -0,0 +2366,21 @@
      2366+ const providerThread = makeProviderThread({
      2367+ idAllocator,
      2368+ providerInstanceId: options.instanceId,
      2369+ providerSessionId: input.providerSessionId,
      2370+ appThreadId: threadInput.threadId,
      2371+ nativeSession,
      2372+ now: createdAt,
      2373+ });
      2374+ registerThread(nativeSession, providerThread, null);
      2375+ return providerThread;
      2376+ }).pipe(
      2377+ Effect.mapError(
      2378+ (cause) =>
      2379+ new ProviderAdapterEnsureThreadError({
      2380+ driver: OPENCODE_PROVIDER,
      2381+ threadId: threadInput.threadId,
      2382+ cause,
      2383+ }),
      2384+ ),
      2385+ ),
      2386+ resumeThread: (threadInput) =>
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Adapters/OpenCodeAdapterV2.ts:2386

      resumeThread calls only session.get and never applies threadInput.runtimePolicy, so a resumed OpenCode session keeps the permission rules it was originally created with. Since openCodePermissionRules is applied only at session.create time, resuming a thread that was created under a looser policy leaves edit/network/command permissions enabled even after the app has switched to a stricter runtimePolicy. The next turn on the resumed thread runs with stale, overly broad permissions instead of the requested policy. Consider re-applying threadInput.runtimePolicy (or re-invoking the permission-rule setup used at create time) during resume so the session's permissions match the current policy.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts around line 2386:
      
      `resumeThread` calls only `session.get` and never applies `threadInput.runtimePolicy`, so a resumed OpenCode session keeps the permission rules it was originally created with. Since `openCodePermissionRules` is applied only at `session.create` time, resuming a thread that was created under a looser policy leaves edit/network/command permissions enabled even after the app has switched to a stricter `runtimePolicy`. The next turn on the resumed thread runs with stale, overly broad permissions instead of the requested policy. Consider re-applying `threadInput.runtimePolicy` (or re-invoking the permission-rule setup used at create time) during resume so the session's permissions match the current policy.
      @@ -0,0 +19,21 @@
      19+export class OrchestrationEffectExecutionError extends Schema.TaggedErrorClass<OrchestrationEffectExecutionError>()(
      20+ "OrchestrationEffectExecutionError",
      21+ {
      22+ effectId: Schema.String,
      23+ effectType: Schema.String,
      24+ cause: Schema.optional(Schema.Defect()),
      25+ },
      26+) {}
      27+
      28+export interface OrchestrationEffectExecutorV2Shape {
      29+ readonly execute: (
      30+ effect: OrchestrationEffectV2,
      31+ ) => Effect.Effect<void, OrchestrationEffectExecutionError>;
      32+}
      33+
      34+export class OrchestrationEffectExecutorV2 extends Context.Service<
      35+ OrchestrationEffectExecutorV2,
      36+ OrchestrationEffectExecutorV2Shape
      37+>()("t3/orchestration-v2/EffectWorker/OrchestrationEffectExecutorV2") {}
      38+
      39+export const executorLayer: Layer.Layer<
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium orchestration-v2/EffectWorker.ts:39

      executorLayer yields ResourceCleanupService during layer construction, but ResourceCleanupService is a Context.Reference with a no-op default. The layer's required environment doesn't list it, so when the layer is built without an explicit override it captures the no-op default permanently. This means terminal.cleanup and attachment.cleanup effects silently do nothing — terminals and attachments are never cleaned up. Add ResourceCleanupService to the layer's RIn type so a real implementation must be provided, or yield it per-execution instead of at construction time.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/EffectWorker.ts around line 39:
      
      `executorLayer` yields `ResourceCleanupService` during layer construction, but `ResourceCleanupService` is a `Context.Reference` with a no-op default. The layer's required environment doesn't list it, so when the layer is built without an explicit override it captures the no-op default permanently. This means `terminal.cleanup` and `attachment.cleanup` effects silently do nothing — terminals and attachments are never cleaned up. Add `ResourceCleanupService` to the layer's `RIn` type so a real implementation must be provided, or yield it per-execution instead of at construction time.
      @@ -0,0 +2374,21 @@
      2374+ registerThread(nativeSession, providerThread, null);
      2375+ return providerThread;
      2376+ }).pipe(
      2377+ Effect.mapError(
      2378+ (cause) =>
      2379+ new ProviderAdapterEnsureThreadError({
      2380+ driver: OPENCODE_PROVIDER,
      2381+ threadId: threadInput.threadId,
      2382+ cause,
      2383+ }),
      2384+ ),
      2385+ ),
      2386+ resumeThread: (threadInput) =>
      2387+ Effect.gen(function* () {
      2388+ const sessionId = nativeThreadId(threadInput.providerThread);
      2389+ const response = yield* sdkCall("session.get", { sessionID: sessionId }, () =>
      2390+ client.session.get({ sessionID: sessionId }),
      2391+ );
      2392+ const nativeSession = unwrapData("session.get", response);
      2393+ const resumedAt = yield* DateTime.now;
      2394+ const providerThread = {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/OpenCodeAdapterV2.ts:2394

      The returned providerThread keeps the stale providerInstanceId from threadInput.providerThread instead of the current adapter instance's id. Only providerSessionId is overwritten, so resuming a thread created under a different OpenCode instance yields a providerThread whose providerInstanceId no longer matches the active instance. Downstream code filters provider threads by providerInstanceId, so the resumed thread cannot be matched and later turns may create a new native thread instead of continuing the conversation. Add providerInstanceId: input.providerInstanceId to the rebuilt object.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts around line 2394:
      
      The returned `providerThread` keeps the stale `providerInstanceId` from `threadInput.providerThread` instead of the current adapter instance's id. Only `providerSessionId` is overwritten, so resuming a thread created under a different OpenCode instance yields a `providerThread` whose `providerInstanceId` no longer matches the active instance. Downstream code filters provider threads by `providerInstanceId`, so the resumed thread cannot be matched and later turns may create a new native thread instead of continuing the conversation. Add `providerInstanceId: input.providerInstanceId` to the rebuilt object.
      @@ -0,0 +311,21 @@
      311+ open: Effect.fn("CursorAgentSdkRunner.open")(function* (input) {
      312+ const protocolLogger = makeCursorAgentSdkProtocolLogger({
      313+ nativeEventLogger,
      314+ threadId: input.threadId,
      315+ providerSessionId: input.providerSessionId,
      316+ });
      317+ const log = (event: CursorAgentSdkProtocolLogEvent) =>
      318+ protocolLogger === undefined ? Effect.void : protocolLogger(event);
      319+
      320+ yield* log({
      321+ direction: "outgoing",
      322+ stage: "decoded",
      323+ payload: {
      324+ type: "agent.open",
      325+ operation: input.operation,
      326+ ...(input.agentId === undefined ? {} : { agentId: input.agentId }),
      327+ options: loggedCursorAgentOptions(input.options),
      328+ },
      329+ });
      330+
      331+ const agent = yield* Effect.tryPromise({
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/CursorAgentSdk.ts:331

      When open is called with operation: "resume" and no agentId, the code passes undefined into Agent.resume via input.agentId!, causing an opaque SDK failure instead of a clear validation error. The non-null assertion suppresses the optional agentId without checking it. Consider validating that agentId is present before calling Agent.resume and returning a CursorAgentSdkRunnerError when it is missing.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/CursorAgentSdk.ts around line 331:
      
      When `open` is called with `operation: "resume"` and no `agentId`, the code passes `undefined` into `Agent.resume` via `input.agentId!`, causing an opaque SDK failure instead of a clear validation error. The non-null assertion suppresses the optional `agentId` without checking it. Consider validating that `agentId` is present before calling `Agent.resume` and returning a `CursorAgentSdkRunnerError` when it is missing.
      @@ -0,0 +47,21 @@
      47+ messageId: MessageId,
      48+ }),
      49+ Schema.Struct({
      50+ type: Schema.Literal("provider-turn.restart"),
      51+ providerSessionId: ProviderSessionId,
      52+ providerThreadId: ProviderThreadId,
      53+ providerTurnId: ProviderTurnId,
      54+ interruptedAttemptId: RunAttemptId,
      55+ runId: RunId,
      56+ sessionTransition: Schema.optional(
      57+ Schema.Union([
      58+ Schema.Struct({
      59+ type: Schema.Literal("replace"),
      60+ replacementProviderSessionId: ProviderSessionId,
      61+ }),
      62+ Schema.Struct({ type: Schema.Literal("detach") }),
      63+ ]),
      64+ ),
      65+ }),
      66+ Schema.Struct({
      67+ type: Schema.Literal("runtime-request.respond"),
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High orchestration-v2/EffectOutbox.ts:67

      The runtime-request.respond effect can fail after the runtime request has already been marked as resolved, leaving the request permanently stuck in a resolved state even though the provider never received the user's approval or answers. The outbox worker retries the effect and then marks the row failed, but nothing reopens the runtime request — so the UI/projection continues to show status: "resolved" while the provider call never succeeded. Consider adding a compensating action on terminal failure (e.g., re-opening the runtime request to pending or failed) so the projection reflects the actual outcome.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/EffectOutbox.ts around line 67:
      
      The `runtime-request.respond` effect can fail after the runtime request has already been marked as resolved, leaving the request permanently stuck in a resolved state even though the provider never received the user's approval or answers. The outbox worker retries the effect and then marks the row `failed`, but nothing reopens the runtime request — so the UI/projection continues to show `status: "resolved"` while the provider call never succeeded. Consider adding a compensating action on terminal failure (e.g., re-opening the runtime request to `pending` or `failed`) so the projection reflects the actual outcome.
      @@ -0,0 +532,21 @@
      532+ pattern: "*",
      533+ action: "deny" as const,
      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") {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Adapters/OpenCodeAdapterV2.ts:552

      When sandboxPolicy.type is "workspaceWrite", openCodePermissionRules appends edit → allow unconditionally, so file edits are auto-approved even when requiresApproval is true. Because rule evaluation is last-match-wins, this allow rule overrides the earlier edit → ask rule, silently bypassing the approval prompt and weakening the requested approval boundary. The edit-allow branch at line 552 should be guarded with !requiresApproval, matching the other conditional allow rules below it.

      -  if (runtimePolicy.runtimeMode === "auto-accept-edits" || sandboxType === "workspaceWrite") {
      +  if (!requiresApproval && (runtimePolicy.runtimeMode === "auto-accept-edits" || sandboxType === "workspaceWrite")) {
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts around line 552:
      
      When `sandboxPolicy.type` is `"workspaceWrite"`, `openCodePermissionRules` appends `edit → allow` unconditionally, so file edits are auto-approved even when `requiresApproval` is true. Because rule evaluation is last-match-wins, this allow rule overrides the earlier `edit → ask` rule, silently bypassing the approval prompt and weakening the requested approval boundary. The edit-allow branch at line 552 should be guarded with `!requiresApproval`, matching the other conditional allow rules below it.
      @@ -0,0 +275,21 @@
      275+ randomId<ProviderSessionId, typeof input>({
      276+ kind: "provider_session",
      277+ prefix: "provider-session",
      278+ parts: ["provider-instance", input.providerInstanceId, "thread", input.threadId],
      279+ make: ProviderSessionId.make,
      280+ })(input),
      281+ runtimeRequest: (input) =>
      282+ randomId<RuntimeRequestId, typeof input>({
      283+ kind: "runtime_request",
      284+ prefix: "runtime-request",
      285+ parts: [
      286+ "provider",
      287+ input.driver,
      288+ ...(input.providerTurnId === undefined ? [] : ["provider-turn", input.providerTurnId]),
      289+ ...(input.nativeRequestId === undefined
      290+ ? []
      291+ : ["native-request", input.nativeRequestId]),
      292+ ],
      293+ make: RuntimeRequestId.make,
      294+ })(input),
      295+ checkpointScope: (input) =>
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🔴 Critical orchestration-v2/IdAllocator.ts:295

      allocate.checkpointScope returns a deterministic ID from only threadId and name, so when CheckpointService.makeRootRunScope calls it with the constant ROOT_CHECKPOINT_SCOPE_NAME for every run in the same thread, the second run reuses the first run's scope ID instead of getting a distinct scope. This merges logically separate checkpoint scopes, causing duplicate-key failures or cross-run checkpoint corruption whenever a thread has more than one run. Consider including a run-specific value (e.g. runId) in the scope ID, or using randomId like the other allocate functions.

      Also found in 1 other location(s)

      apps/server/src/orchestration-v2/CheckpointService.ts:195

      makeRootRunScope always allocates the root scope with the fixed name &#34;root&#34;. IdAllocatorV2.allocate.checkpointScope is deterministic on (threadId, name), so every run in the same thread reuses the same CheckpointScopeId. Once a second run is created, its checkpoint-scope.created event upserts and overwrites the stored scope&#39;s runId, nodeId, providerThreadId, and createdAt for earlier runs. A concrete failure follows in materializeBaselineCheckpoint: if run 1 and run 2 are queued on the same thread before the first baseline is materialized, the baseline checkpoint emitted for run 1 will take nodeId from run 2&#39;s overwritten scope and be attached to the wrong node.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/IdAllocator.ts around line 295:
      
      `allocate.checkpointScope` returns a deterministic ID from only `threadId` and `name`, so when `CheckpointService.makeRootRunScope` calls it with the constant `ROOT_CHECKPOINT_SCOPE_NAME` for every run in the same thread, the second run reuses the first run's scope ID instead of getting a distinct scope. This merges logically separate checkpoint scopes, causing duplicate-key failures or cross-run checkpoint corruption whenever a thread has more than one run. Consider including a run-specific value (e.g. `runId`) in the scope ID, or using `randomId` like the other allocate functions.
      
      Also found in 1 other location(s):
      - apps/server/src/orchestration-v2/CheckpointService.ts:195 -- `makeRootRunScope` always allocates the root scope with the fixed name `"root"`. `IdAllocatorV2.allocate.checkpointScope` is deterministic on `(threadId, name)`, so every run in the same thread reuses the same `CheckpointScopeId`. Once a second run is created, its `checkpoint-scope.created` event upserts and overwrites the stored scope's `runId`, `nodeId`, `providerThreadId`, and `createdAt` for earlier runs. A concrete failure follows in `materializeBaselineCheckpoint`: if run 1 and run 2 are queued on the same thread before the first baseline is materialized, the baseline checkpoint emitted for run 1 will take `nodeId` from run 2's overwritten scope and be attached to the wrong node.
      
      @@ -0,0 +153,21 @@
      153+ >;
      154+ readonly getThreadEventSequence: (
      155+ threadId: ThreadId,
      156+ ) => Effect.Effect<number, OrchestratorV2Error>;
      157+ readonly streamStoredEvents: Stream.Stream<OrchestrationV2StoredEvent, OrchestratorV2Error>;
      158+ readonly streamStoredEventsFrom: (input?: {
      159+ readonly threadId?: ThreadId;
      160+ readonly afterSequence?: number;
      161+ }) => Stream.Stream<OrchestrationV2StoredEvent, OrchestratorV2Error>;
      162+ readonly streamDomainEvents: Stream.Stream<OrchestrationV2DomainEvent, OrchestratorV2Error>;
      163+}
      164+
      165+export class OrchestratorV2 extends Context.Service<OrchestratorV2, OrchestratorV2Shape>()(
      166+ "t3/orchestration-v2/Orchestrator/OrchestratorV2",
      167+) {}
      168+
      169+function nextRunOrdinal(projection: OrchestrationV2ThreadProjection): number {
      170+ return projection.runs.length + 1;
      171+}
      172+
      173+function commandThreadId(command: OrchestrationV2Command): ThreadId {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High orchestration-v2/Orchestrator.ts:173

      commandThreadId() returns command.targetThreadId for thread.fork and thread.merge_back, so these commands are serialized under the target thread's lock rather than the source thread's lock. Both dispatch paths immediately read command.sourceThreadId's projection to select a source run and build the context transfer. A concurrent command on the source thread (e.g. message.dispatch or provider.switch) runs under a different lock, so it can mutate the source projection while the fork/merge-back is still being planned, producing a stale or incorrect context transfer. Consider returning command.sourceThreadId for these cases (or acquiring both locks) so the source projection cannot change mid-planning.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Orchestrator.ts around line 173:
      
      `commandThreadId()` returns `command.targetThreadId` for `thread.fork` and `thread.merge_back`, so these commands are serialized under the target thread's lock rather than the source thread's lock. Both dispatch paths immediately read `command.sourceThreadId`'s projection to select a source run and build the context transfer. A concurrent command on the source thread (e.g. `message.dispatch` or `provider.switch`) runs under a different lock, so it can mutate the source projection while the fork/merge-back is still being planned, producing a stale or incorrect context transfer. Consider returning `command.sourceThreadId` for these cases (or acquiring both locks) so the source projection cannot change mid-planning.
      @@ -0,0 +106,21 @@
      106+ readonly sourceThreadId: ThreadId;
      107+ readonly targetThreadId: ThreadId;
      108+ readonly coveredRunOrdinals: OrchestrationV2ContextHandoff["coveredRunOrdinals"];
      109+ readonly deltaItems: ReadonlyArray<OrchestrationV2TurnItem>;
      110+}): string {
      111+ const itemLines = input.deltaItems.flatMap((item) => {
      112+ const line = summarizeDeltaItem(item);
      113+ return line === null ? [] : [line];
      114+ });
      115+ return [
      116+ "Merge-back context from forked conversation.",
      117+ `Source thread: ${input.sourceThreadId}`,
      118+ `Target thread: ${input.targetThreadId}`,
      119+ `Covered fork runs: ${input.coveredRunOrdinals.from}-${input.coveredRunOrdinals.to}`,
      120+ "",
      121+ "Fork delta:",
      122+ ...(itemLines.length === 0 ? ["- No user-visible delta items."] : itemLines),
      123+ ].join("\n");
      124+}
      125+
      126+function makeProviderHandoffSummary(input: {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High orchestration-v2/ContextHandoffService.ts:126

      makeProviderHandoffSummary discards every prior handoff turn item (if (item.type === "handoff") return []). Because prior handoff summaries are the only persisted record of already-transferred portable context (earlier provider switches, merge-back deltas), the new handoff summary silently omits that context. On a second provider switch or resume, conversation state that existed only inside previous handoff summaries is lost. Consider including prior handoff items in the summary instead of skipping them.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/ContextHandoffService.ts around line 126:
      
      `makeProviderHandoffSummary` discards every prior `handoff` turn item (`if (item.type === "handoff") return []`). Because prior handoff summaries are the only persisted record of already-transferred portable context (earlier provider switches, merge-back deltas), the new handoff summary silently omits that context. On a second provider switch or resume, conversation state that existed only inside previous handoff summaries is lost. Consider including prior `handoff` items in the summary instead of skipping them.
      @@ -0,0 +626,21 @@
      626+ readonly environment?: NodeJS.ProcessEnv;
      627+ readonly mcpServers?: ClaudeQueryOptions["mcpServers"];
      628+ readonly tools?: ClaudeAgentSdkQueryTools;
      629+ readonly allowedTools?: ReadonlyArray<string>;
      630+ readonly disallowedTools?: ReadonlyArray<string>;
      631+ readonly permissionMode?: PermissionMode;
      632+ readonly canUseTool?: CanUseTool;
      633+ readonly allowDangerouslySkipPermissions?: boolean;
      634+}): ClaudeAgentSdkQueryOptions {
      635+ const compiledSelection = compileClaudeModelSelection(input.modelSelection);
      636+ const extraArgs =
      637+ input.settings === undefined ? {} : parseCliArgs(input.settings.launchArgs).flags;
      638+ const threadIdentity: ClaudeAgentSdkThreadIdentity = input.resume
      639+ ? { resume: input.nativeThreadId }
      640+ : { sessionId: input.nativeThreadId };
      641+ const selectedTools = input.tools ?? CLAUDE_CODE_PRESET_TOOLS;
      642+ const selectionSettings =
      643+ Object.keys(compiledSelection.settings).length === 0
      644+ ? undefined
      645+ : (compiledSelection.settings as ClaudeSdkSettings);
      646+ const querySettings =
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/ClaudeAdapterV2.ts:646

      When compiledSelection.settings is non-empty and the caller passes sdkSettings as a string, makeClaudeQueryOptions silently drops the caller's sdkSettings value. The merge branch handles the object case by spreading both together, but the string case replaces sdkSettings with only selectionSettings, losing the caller-supplied string. A caller that passes a string-based SDK settings source together with model options like thinking, fastMode, or ultracode will lose its custom settings without any error.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts around line 646:
      
      When `compiledSelection.settings` is non-empty and the caller passes `sdkSettings` as a string, `makeClaudeQueryOptions` silently drops the caller's `sdkSettings` value. The merge branch handles the object case by spreading both together, but the string case replaces `sdkSettings` with only `selectionSettings`, losing the caller-supplied string. A caller that passes a string-based SDK settings source together with model options like `thinking`, `fastMode`, or `ultracode` will lose its custom settings without any error.
      @@ -0,0 +562,21 @@
      562+ if (!requiresApproval && sandboxType === "readOnly") {
      563+ const access = recordValue(sandboxPolicy, "access");
      564+ if (recordString(access, "type") === "fullAccess") {
      565+ rules.push({ permission: "external_directory", pattern: "*", action: "allow" });
      566+ }
      567+ }
      568+
      569+ if (!requiresApproval && sandboxType === "workspaceWrite") {
      570+ const writableRoots = recordValue(sandboxPolicy, "writableRoots");
      571+ if (Array.isArray(writableRoots)) {
      572+ for (const root of writableRoots) {
      573+ if (typeof root === "string" && root.trim().length > 0) {
      574+ rules.push({
      575+ permission: "external_directory",
      576+ pattern: `${root.replace(/\/$/, "")}/*`,
      577+ action: "allow",
      578+ });
      579+ }
      580+ }
      581+ }
      582+ }
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/OpenCodeAdapterV2.ts:569

      When sandboxPolicy.type === "workspaceWrite" and requiresApproval is false, the code grants external_directory only for entries in writableRoots but never processes sandboxPolicy.readOnlyAccess. Canonical workspace-write policies carry readOnlyAccess: { type: "fullAccess" }, so OpenCode sessions created under that policy deny reads from external directories that other adapters allow. Consider adding a rule for external_directory based on readOnlyAccess (mirroring the readOnly branch) so read-only external access is granted under workspaceWrite as well.

         if (!requiresApproval && sandboxType === "workspaceWrite") {
      +    const readOnlyAccess = recordValue(sandboxPolicy, "readOnlyAccess");
      +    if (recordString(readOnlyAccess, "type") === "fullAccess") {
      +      rules.push({ permission: "external_directory", pattern: "*", action: "allow" });
      +    }
           const writableRoots = recordValue(sandboxPolicy, "writableRoots");
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts around lines 569-582:
      
      When `sandboxPolicy.type === "workspaceWrite"` and `requiresApproval` is false, the code grants `external_directory` only for entries in `writableRoots` but never processes `sandboxPolicy.readOnlyAccess`. Canonical workspace-write policies carry `readOnlyAccess: { type: "fullAccess" }`, so OpenCode sessions created under that policy deny reads from external directories that other adapters allow. Consider adding a rule for `external_directory` based on `readOnlyAccess` (mirroring the `readOnly` branch) so read-only external access is granted under `workspaceWrite` as well.
      @@ -0,0 +513,21 @@
      513+
      514+export function buildCodexTurnStartParams(input: {
      515+ readonly nativeThreadId: string;
      516+ readonly codexInput: ReadonlyArray<CodexSchema.V2TurnStartParams__UserInput>;
      517+ readonly runtimePolicy: ProviderAdapterV2RuntimePolicy;
      518+ readonly modelSelection: ModelSelection;
      519+}) {
      520+ return Effect.gen(function* () {
      521+ const runtimeModeDefaults = codexRuntimeModeTurnDefaults(input.runtimePolicy.runtimeMode);
      522+ const approvalPolicy =
      523+ input.runtimePolicy.approvalPolicy === undefined
      524+ ? runtimeModeDefaults.approvalPolicy
      525+ : yield* decodeTurnApprovalPolicy(input.runtimePolicy.approvalPolicy);
      526+ const sandboxPolicy =
      527+ input.runtimePolicy.sandboxPolicy === undefined
      528+ ? runtimeModeDefaults.sandboxPolicy
      529+ : yield* decodeTurnSandboxPolicy(input.runtimePolicy.sandboxPolicy);
      530+ const selectedEffort = getModelSelectionStringOptionValue(
      531+ input.modelSelection,
      532+ "reasoningEffort",
      533+ );
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/CodexAdapterV2.ts:530

      buildCodexTurnStartParams ignores input.runtimePolicy.reasoningEffort and always derives effort from input.modelSelection.options. A RuntimePolicyV2 override that sets reasoningEffort is silently dropped, so turns run with the model-selected or default effort instead of the requested override. This also affects plan mode, where collaborationMode.settings.reasoning_effort falls back to "medium" instead of honoring the runtime policy. Consider reading input.runtimePolicy.reasoningEffort first and falling back to the model-selection option only when it is absent.

      -    const selectedEffort = getModelSelectionStringOptionValue(
      -      input.modelSelection,
      -      "reasoningEffort",
      -    );
      +    const selectedEffort =
      +      input.runtimePolicy.reasoningEffort ??
      +      getModelSelectionStringOptionValue(input.modelSelection, "reasoningEffort");
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts around lines 530-533:
      
      `buildCodexTurnStartParams` ignores `input.runtimePolicy.reasoningEffort` and always derives `effort` from `input.modelSelection.options`. A `RuntimePolicyV2` override that sets `reasoningEffort` is silently dropped, so turns run with the model-selected or default effort instead of the requested override. This also affects plan mode, where `collaborationMode.settings.reasoning_effort` falls back to `"medium"` instead of honoring the runtime policy. Consider reading `input.runtimePolicy.reasoningEffort` first and falling back to the model-selection option only when it is absent.
      @@ -0,0 +309,21 @@
      309+ input.capabilities.threads.canForkThread &&
      310+ (!input.fromSpecificTurn || input.capabilities.threads.canForkFromTurn) &&
      311+ input.capabilities.identity.nativeThreadIds === "strong";
      312+
      313+ if (canForkNatively) {
      314+ return Effect.succeed("native_fork");
      315+ }
      316+
      317+ return ensureContextHandoff({
      318+ commandId: input.commandId,
      319+ threadId: input.threadId,
      320+ providerInstanceId: input.providerInstanceId,
      321+ capabilities: input.capabilities,
      322+ strategy: "full_thread_summary",
      323+ }).pipe(Effect.as("portable_context"));
      324+};
      325+
      326+const decideMessageDispatch: CommandPolicyV2Shape["decideMessageDispatch"] = (input) => {
      327+ const activeRun = input.projection.runs.find(
      328+ (run) =>
      329+ run.status === "preparing" ||
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High orchestration-v2/CommandPolicy.ts:329

      When a run has status waiting (e.g., paused for approval or user input), decideMessageDispatch selects it as activeRun and then enters the steer_active or restart_active branch. Both branches require a provider turn with status running, but a waiting run has no running turn, so the function returns a CommandPolicyMessageDispatchError ("No running providerInstanceId turn found") instead of dispatching the message. This means messages sent while a run is waiting for approval are dropped with an error rather than delivered. Consider excluding waiting from the activeRun filter, or handle waiting runs without requiring a running provider turn.

      Also found in 1 other location(s)

      apps/mobile/src/features/threads/ThreadQueueControl.tsx:98

      ThreadQueueControl enables the Steer action whenever workflow.canPromoteToSteer is true, but deriveThreadQueueWorkflowState treats a run in waiting status as active. On V2 threads that are waiting for approval/user input, pressing this new Android button calls promoteQueuedRun, and the server&#39;s dispatchSteerIntoRun rejects it because the target run is not running and has no running provider turn. The promoted queued message therefore fails instead of being steered.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/CommandPolicy.ts around line 329:
      
      When a run has status `waiting` (e.g., paused for approval or user input), `decideMessageDispatch` selects it as `activeRun` and then enters the `steer_active` or `restart_active` branch. Both branches require a provider turn with status `running`, but a `waiting` run has no running turn, so the function returns a `CommandPolicyMessageDispatchError` ("No running providerInstanceId turn found") instead of dispatching the message. This means messages sent while a run is waiting for approval are dropped with an error rather than delivered. Consider excluding `waiting` from the `activeRun` filter, or handle `waiting` runs without requiring a `running` provider turn.
      
      Also found in 1 other location(s):
      - apps/mobile/src/features/threads/ThreadQueueControl.tsx:98 -- `ThreadQueueControl` enables the `Steer` action whenever `workflow.canPromoteToSteer` is true, but `deriveThreadQueueWorkflowState` treats a run in `waiting` status as active. On V2 threads that are waiting for approval/user input, pressing this new Android button calls `promoteQueuedRun`, and the server's `dispatchSteerIntoRun` rejects it because the target run is not `running` and has no running provider turn. The promoted queued message therefore fails instead of being steered.
      
      @@ -0,0 +26,21 @@
      26+ providerThreadId: ProviderThreadId,
      27+ checkpointId: CheckpointId,
      28+ cause: Schema.optional(Schema.Defect()),
      29+ },
      30+) {}
      31+
      32+export interface CheckpointRollbackServiceV2Shape {
      33+ readonly execute: (input: {
      34+ readonly threadId: ThreadId;
      35+ readonly providerThreadId: ProviderThreadId;
      36+ readonly checkpointId: CheckpointId;
      37+ readonly scopeId: CheckpointScopeId;
      38+ }) => Effect.Effect<void, CheckpointRollbackExecutionError>;
      39+}
      40+
      41+export class CheckpointRollbackServiceV2 extends Context.Service<
      42+ CheckpointRollbackServiceV2,
      43+ CheckpointRollbackServiceV2Shape
      44+>()("t3/orchestration-v2/CheckpointRollbackService/CheckpointRollbackServiceV2") {}
      45+
      46+export const layer: Layer.Layer<
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium orchestration-v2/CheckpointRollbackService.ts:46

      execute is not idempotent, so retries after a partial success duplicate rollback side effects and append redundant events. If eventSink.write commits but the effect worker crashes before marking the effect complete, the at-least-once retry re-opens the provider session, calls checkpoints.restore and session.rollbackThread again, and writes another provider-thread.updated event with a fresh timestamp — even though the rollback already completed. Unlike checkpoint.capture, which guards against re-application, execute has no such check, so every retry-after-success path produces duplicate provider-thread mutations and extra domain events.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/CheckpointRollbackService.ts around line 46:
      
      `execute` is not idempotent, so retries after a partial success duplicate rollback side effects and append redundant events. If `eventSink.write` commits but the effect worker crashes before marking the effect complete, the at-least-once retry re-opens the provider session, calls `checkpoints.restore` and `session.rollbackThread` again, and writes another `provider-thread.updated` event with a fresh timestamp — even though the rollback already completed. Unlike `checkpoint.capture`, which guards against re-application, `execute` has no such check, so every retry-after-success path produces duplicate provider-thread mutations and extra domain events.
    10. @@ -0,0 +330,21 @@
      330+ .pipe(Effect.as("cancelled" as const));
      331+ const exit = yield* Effect.exit(Effect.raceFirst(execution, cancellation)).pipe(
      332+ Effect.ensuring(outbox.clearCancellation(effect.id)),
      333+ );
      334+ if (Exit.isSuccess(exit) && exit.value === "cancelled") {
      335+ return true;
      336+ }
      337+ if (Exit.isSuccess(exit)) {
      338+ const completed = yield* outbox.succeed({ effectId: effect.id, workerId });
      339+ if (!completed) {
      340+ if (yield* wasCancelled(effect.id)) return true;
      341+ return yield* new OrchestrationEffectWorkerError({
      342+ operation: "complete",
      343+ effectId: effect.id,
      344+ cause: "The worker no longer owns the effect lease.",
      345+ });
      346+ }
      347+ return true;
      348+ }
      349+
      350+ const error = Cause.pretty(exit.cause);
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium orchestration-v2/EffectWorker.ts:350

      When the daemon shuts down and interrupts a running effect, Effect.exit at line 331 captures the interruption as Exit.Failure. The code then treats any failure as an execution error — logging it and calling outbox.retry or outbox.fail — so a normal shutdown burns retry attempts and can permanently fail an outbox entry whose provider operation never actually failed. Consider checking Cause.isInterrupted(exit.cause) (or only routing non-interruption failures through the retry/fail path) so shutdown interruptions are handled separately from genuine execution errors.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/EffectWorker.ts around line 350:
      
      When the daemon shuts down and interrupts a running effect, `Effect.exit` at line 331 captures the interruption as `Exit.Failure`. The code then treats any failure as an execution error — logging it and calling `outbox.retry` or `outbox.fail` — so a normal shutdown burns retry attempts and can permanently fail an outbox entry whose provider operation never actually failed. Consider checking `Cause.isInterrupted(exit.cause)` (or only routing non-interruption failures through the retry/fail path) so shutdown interruptions are handled separately from genuine execution errors.
      @@ -0,0 +2268,21 @@
      2268+ return withLocalVisibleTurnItems(projection);
      2269+ }
      2270+ const sourceProjection = readProjection(
      2271+ forkedFrom.threadId,
      2272+ new Set([...seenThreadIds, targetThreadId]),
      2273+ );
      2274+ return {
      2275+ ...projection,
      2276+ visibleTurnItems: buildVisibleTurnItems({
      2277+ projection,
      2278+ sourceProjection,
      2279+ }),
      2280+ };
      2281+ };
      2282+ const projection = readProjection(threadId, new Set());
      2283+ if (!projection) {
      2284+ return yield* new ProjectionStoreThreadNotFoundError({ threadId });
      2285+ }
      2286+ return projection;
      2287+ }),
      2288+ getThreadSnapshot: (threadId) =>
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium orchestration-v2/ProjectionStore.ts:2288

      getThreadSnapshot reads the projection from replayState and snapshotSequence from sequence in separate Ref accesses. An apply that fires between those reads increments sequence without being reflected in the returned projection, so callers receive a snapshot whose snapshotSequence is ahead of the projection. Clients use snapshotSequence as the resume cursor for event streaming, so the event that landed between the two reads is skipped permanently — the client gets the older projection but starts streaming after the missing event. Consider reading both values atomically (e.g., in a single Ref.modify) so snapshotSequence and the projection always describe the same point in time.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/ProjectionStore.ts around line 2288:
      
      `getThreadSnapshot` reads the projection from `replayState` and `snapshotSequence` from `sequence` in separate `Ref` accesses. An `apply` that fires between those reads increments `sequence` without being reflected in the returned projection, so callers receive a snapshot whose `snapshotSequence` is ahead of the projection. Clients use `snapshotSequence` as the resume cursor for event streaming, so the event that landed between the two reads is skipped permanently — the client gets the older projection but starts streaming after the missing event. Consider reading both values atomically (e.g., in a single `Ref.modify`) so `snapshotSequence` and the projection always describe the same point in time.
      @@ -0,0 +258,21 @@
      258+ ...base,
      259+ plans: upsertById(base.plans, event.payload),
      260+ };
      261+ case "checkpoint-scope.created":
      262+ return {
      263+ ...base,
      264+ checkpointScopes: upsertById(base.checkpointScopes, event.payload),
      265+ };
      266+ case "checkpoint.captured":
      267+ return {
      268+ ...base,
      269+ checkpoints: upsertById(base.checkpoints, event.payload),
      270+ };
      271+ case "checkpoint.rollback-requested":
      272+ return base;
      273+ case "context-handoff.updated":
      274+ return {
      275+ ...base,
      276+ contextHandoffs: upsertById(base.contextHandoffs, event.payload),
      277+ };
      278+ case "context-transfer.created":
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium orchestration-v2/ProjectionStore.ts:278

      In the in-memory projection, context-transfer.created and context-transfer.updated only upsert the transfer into the projection for event.threadId. But the SQL-backed projection exposes each transfer on both the sourceThreadId and targetThreadId threads. So when payload.sourceThreadId !== payload.targetThreadId, getThreadProjection() returns incomplete contextTransfers for the other thread — the transfer is silently missing from one side. Consider also upserting the transfer into the projection for the other participant thread, or document the divergence from the SQL projection if it is intentional.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/ProjectionStore.ts around line 278:
      
      In the in-memory projection, `context-transfer.created` and `context-transfer.updated` only upsert the transfer into the projection for `event.threadId`. But the SQL-backed projection exposes each transfer on both the `sourceThreadId` and `targetThreadId` threads. So when `payload.sourceThreadId !== payload.targetThreadId`, `getThreadProjection()` returns incomplete `contextTransfers` for the other thread — the transfer is silently missing from one side. Consider also upserting the transfer into the projection for the other participant thread, or document the divergence from the SQL projection if it is intentional.
      @@ -0,0 +109,21 @@
      109+ readonly type: OrchestrationV2DomainEvent["type"];
      110+ readonly payload: OrchestrationV2DomainEvent["payload"];
      111+ readonly threadId?: ThreadId;
      112+ readonly runId?: RunId | null;
      113+ readonly nodeId?: NodeId | null;
      114+ },
      115+ ) =>
      116+ Effect.gen(function* () {
      117+ const threadId = payloadInput.threadId ?? input.threadId;
      118+ const eventId = yield* idAllocator.allocate.event({
      119+ threadId,
      120+ providerSessionId: input.providerSessionId,
      121+ });
      122+ const occurredAt = yield* DateTime.now;
      123+ return yield* decodeDomainEvent(
      124+ compactUndefined({
      125+ id: eventId,
      126+ type: payloadInput.type,
      127+ threadId,
      128+ runId: payloadInput.runId ?? input.runId,
      129+ nodeId: payloadInput.nodeId ?? input.nodeId,
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium orchestration-v2/ProviderEventIngestor.ts:128

      In makeDomainEvent, payloadInput.runId ?? input.runId and payloadInput.nodeId ?? input.nodeId (lines 128–129) use nullish coalescing, so an explicit null in payloadInput is replaced with the parent value from input. This mis-tags provider artifacts that intentionally live outside a run — such as child-thread messages with runId: null — as belonging to the current root run, and downstream projection code silently leaks those artifacts into the parent run. Consider using a check that only falls back when the field is undefined, so an explicit null is preserved.

      Suggested change
      128- runId: payloadInput.runId ?? input.runId,
      129- nodeId: payloadInput.nodeId ?? input.nodeId,
      128+ runId: payloadInput.runId !== undefined ? payloadInput.runId : input.runId,
      129+ nodeId: payloadInput.nodeId !== undefined ? payloadInput.nodeId : input.nodeId,
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/ProviderEventIngestor.ts around lines 128-129:
      
      In `makeDomainEvent`, `payloadInput.runId ?? input.runId` and `payloadInput.nodeId ?? input.nodeId` (lines 128–129) use nullish coalescing, so an explicit `null` in `payloadInput` is replaced with the parent value from `input`. This mis-tags provider artifacts that intentionally live outside a run — such as child-thread messages with `runId: null` — as belonging to the current root run, and downstream projection code silently leaks those artifacts into the parent run. Consider using a check that only falls back when the field is `undefined`, so an explicit `null` is preserved.
      @@ -0,0 +119,21 @@
      119+ lease_owner TEXT,
      120+ lease_expires_at TEXT,
      121+ created_at TEXT NOT NULL,
      122+ updated_at TEXT NOT NULL,
      123+ completed_at TEXT,
      124+ last_error TEXT
      125+ )
      126+ `;
      127+ yield* sql`CREATE INDEX orchestration_v2_effect_outbox_claim_idx ON orchestration_v2_effect_outbox(status, available_at, lease_expires_at, created_at)`;
      128+ yield* sql`CREATE INDEX orchestration_v2_effect_outbox_command_idx ON orchestration_v2_effect_outbox(command_id, effect_id)`;
      129+
      130+ yield* sql`
      131+ CREATE TABLE orchestration_v2_turn_item_positions (
      132+ thread_id TEXT NOT NULL,
      133+ turn_item_id TEXT NOT NULL,
      134+ ordinal INTEGER NOT NULL,
      135+ PRIMARY KEY (thread_id, turn_item_id),
      136+ UNIQUE (thread_id, ordinal)
      137+ )
      138+ `;
      139+ yield* sql`
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Migrations/035_OrchestrationV2Foundation.ts:139

      The backfill into orchestration_v2_turn_item_positions silently drops most pre-existing turn items when a thread has duplicate legacy ordinal values. The INSERT OR IGNORE on lines 140–148 inserts raw ordinals into a table with UNIQUE (thread_id, ordinal), so when orchestration_v2_projection_turn_items contains repeated ordinals for the same thread, only the first row per ordinal survives and every skipped item is left without a position row. When any skipped item is later updated, TurnItemPositionStoreV2.allocate assigns it a fresh max ordinal, causing historical items to jump to the end of the thread and breaking ordering after upgrade. Consider renumbering ordinals per thread during the backfill (e.g. with a window function) so every turn item gets a unique position.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/persistence/Migrations/035_OrchestrationV2Foundation.ts around line 139:
      
      The backfill into `orchestration_v2_turn_item_positions` silently drops most pre-existing turn items when a thread has duplicate legacy `ordinal` values. The `INSERT OR IGNORE` on lines 140–148 inserts raw ordinals into a table with `UNIQUE (thread_id, ordinal)`, so when `orchestration_v2_projection_turn_items` contains repeated ordinals for the same thread, only the first row per ordinal survives and every skipped item is left without a position row. When any skipped item is later updated, `TurnItemPositionStoreV2.allocate` assigns it a fresh max ordinal, causing historical items to jump to the end of the thread and breaking ordering after upgrade. Consider renumbering ordinals per thread during the backfill (e.g. with a window function) so every turn item gets a unique position.
      @@ -0,0 +439,21 @@
      439+ const { nativeEventLogger } = input;
      440+ if (nativeEventLogger === undefined) {
      441+ return undefined;
      442+ }
      443+
      444+ return (event) =>
      445+ nativeEventLogger
      446+ .write(
      447+ {
      448+ provider: CLAUDE_PROVIDER,
      449+ protocol: CLAUDE_AGENT_SDK_QUERY_PROTOCOL,
      450+ kind: "protocol",
      451+ providerSessionId: input.providerSessionId,
      452+ event,
      453+ },
      454+ input.threadId,
      455+ )
      456+ .pipe(Effect.ignore);
      457+}
      458+
      459+export const claudeAgentSdkQueryRunnerLiveLayer: Layer.Layer<
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/ClaudeAdapterV2.ts:459

      claudeAgentSdkQueryRunnerLiveLayer constructs its own EventNdjsonLogger via makeEventNdjsonLogger(providerEventLogPath, { stream: "native" }) at line 468, while codexAppServerClientFactoryFromSettingsLayer and the cursor runner create separate EventNdjsonLogger instances targeting the same providerEventLogPath directory within the same merged infrastructure layer (ProviderOrchestrationAdapterInfrastructureLive). Each EventNdjsonLogger opens per-thread RotatingFileSink instances that write to *.log files keyed by thread segment. When multiple adapter-local loggers run concurrently for the same thread, they independently open and rotate the same *.log file. RotatingFileSink is not designed for concurrent rotation by multiple uncoordinated writers, so overlapping rotations can rename or truncate the active file out from under another writer, causing interleaved writes or dropped lines. Consider sharing a single EventNdjsonLogger instance across all adapters in the merged infrastructure layer so only one set of sinks writes to each *.log file.

      Also found in 1 other location(s)

      apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts:1108

      codexAppServerClientFactoryFromSettingsLayer also constructs a fresh makeEventNdjsonLogger(...) at line 1108 instead of sharing a singleton native logger service. In ProviderOrchestrationAdapterInfrastructureLive this layer is merged alongside the Claude and Cursor layers, so several rotating writers target the same per-thread protocol log files concurrently, which can lose or scramble log records during writes/rotation.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts around line 459:
      
      `claudeAgentSdkQueryRunnerLiveLayer` constructs its own `EventNdjsonLogger` via `makeEventNdjsonLogger(providerEventLogPath, { stream: "native" })` at line 468, while `codexAppServerClientFactoryFromSettingsLayer` and the cursor runner create separate `EventNdjsonLogger` instances targeting the same `providerEventLogPath` directory within the same merged infrastructure layer (`ProviderOrchestrationAdapterInfrastructureLive`). Each `EventNdjsonLogger` opens per-thread `RotatingFileSink` instances that write to `*.log` files keyed by thread segment. When multiple adapter-local loggers run concurrently for the same thread, they independently open and rotate the same `*.log` file. `RotatingFileSink` is not designed for concurrent rotation by multiple uncoordinated writers, so overlapping rotations can rename or truncate the active file out from under another writer, causing interleaved writes or dropped lines. Consider sharing a single `EventNdjsonLogger` instance across all adapters in the merged infrastructure layer so only one set of sinks writes to each `*.log` file.
      
      Also found in 1 other location(s):
      - apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts:1108 -- `codexAppServerClientFactoryFromSettingsLayer` also constructs a fresh `makeEventNdjsonLogger(...)` at line `1108` instead of sharing a singleton native logger service. In `ProviderOrchestrationAdapterInfrastructureLive` this layer is merged alongside the Claude and Cursor layers, so several rotating writers target the same per-thread protocol log files concurrently, which can lose or scramble log records during writes/rotation.
      
      @@ -0,0 +63,21 @@
      63+ const instanceChanged = current.instanceId !== targetModelSelection.instanceId;
      64+ const modelChanged = current.model !== targetModelSelection.model;
      65+ const getMetadata = (instanceId: typeof current.instanceId) =>
      66+ adapters.getMetadata !== undefined
      67+ ? adapters.getMetadata(instanceId)
      68+ : adapters.get(instanceId).pipe(
      69+ Effect.flatMap((adapter) =>
      70+ adapter.getCapabilities().pipe(
      71+ Effect.map((capabilities) => ({
      72+ driver: adapter.driver,
      73+ continuationKey: `${adapter.driver}:instance:${instanceId}`,
      74+ enabled: true,
      75+ capabilities,
      76+ })),
      77+ ),
      78+ ),
      79+ );
      80+ const currentInstance = yield* Effect.option(getMetadata(current.instanceId));
      81+ const targetInstance = yield* Effect.option(getMetadata(targetModelSelection.instanceId));
      82+ const targetAdapter = yield* Effect.option(adapters.get(targetModelSelection.instanceId));
      83+ const currentSession = projection.providerSessions
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium orchestration-v2/ProviderSwitchService.ts:83

      currentSession is selected as the newest session for the current instance without excluding terminal sessions. If a newer stopped or error session exists alongside an older live session, the plan is computed from the dead session. In a restart_and_resume transition, releaseProviderSessionIds only matches that dead session's id, so the active live session is never released and remains attached to the incompatible model. Consider filtering out stopped/error sessions before picking the newest, so the live session is the one targeted for release.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/ProviderSwitchService.ts around line 83:
      
      `currentSession` is selected as the newest session for the current instance without excluding terminal sessions. If a newer `stopped` or `error` session exists alongside an older live session, the plan is computed from the dead session. In a `restart_and_resume` transition, `releaseProviderSessionIds` only matches that dead session's `id`, so the active live session is never released and remains attached to the incompatible model. Consider filtering out `stopped`/`error` sessions before picking the newest, so the live session is the one targeted for release.
      @@ -0,0 +288,21 @@
      288+ .write(
      289+ {
      290+ provider: CURSOR_PROVIDER,
      291+ protocol: CURSOR_AGENT_SDK_PROTOCOL,
      292+ kind: "protocol",
      293+ providerSessionId: input.providerSessionId,
      294+ event,
      295+ },
      296+ input.threadId,
      297+ )
      298+ .pipe(Effect.ignore);
      299+}
      300+
      301+export const cursorAgentSdkRunnerLiveLayer: Layer.Layer<CursorAgentSdkRunner, never, ServerConfig> =
      302+ Layer.effect(
      303+ CursorAgentSdkRunner,
      304+ Effect.gen(function* () {
      305+ const { providerEventLogPath } = yield* ServerConfig;
      306+ const nativeEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, {
      307+ stream: "native",
      308+ });
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/CursorAgentSdk.ts:306

      The cursorAgentSdkRunnerLiveLayer layer never calls nativeEventLogger.close() during teardown. Because EventNdjsonLogger batches writes for up to 200 ms and only flushes pending records on close, shutting down the layer silently drops the last protocol log entries and leaks the logger's scoped file handles. The close finalizer should be registered so the batch is flushed when the layer's scope is released.

             const nativeEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, {
               stream: "native",
             });
      +      yield* Effect.addFinalizer(() => nativeEventLogger.close());
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/CursorAgentSdk.ts around lines 306-308:
      
      The `cursorAgentSdkRunnerLiveLayer` layer never calls `nativeEventLogger.close()` during teardown. Because `EventNdjsonLogger` batches writes for up to 200 ms and only flushes pending records on `close`, shutting down the layer silently drops the last protocol log entries and leaks the logger's scoped file handles. The `close` finalizer should be registered so the batch is flushed when the layer's scope is released.
      @@ -0,0 +165,21 @@
      165+ const belongs = ownsRun(event.node.runId) || ownsChildThread(event.node.threadId);
      166+ if (!belongs || event.node.providerThreadId === null) {
      167+ return [belongs, state];
      168+ }
      169+ return [true, addProviderThread(event.node.providerThreadId)];
      170+ }
      171+ case "subagent.updated":
      172+ return [ownsRun(event.subagent.runId) || ownsChildThread(event.subagent.threadId), state];
      173+ case "message.updated":
      174+ return [ownsRun(event.message.runId) || ownsChildThread(event.message.threadId), state];
      175+ case "turn_item.updated":
      176+ return [ownsRun(event.turnItem.runId) || ownsChildThread(event.turnItem.threadId), state];
      177+ case "plan.updated":
      178+ return [ownsRun(event.plan.runId) || ownsChildThread(event.plan.threadId), state];
      179+ case "runtime_request.updated":
      180+ return [
      181+ (event.threadId !== undefined && ownsChildThread(event.threadId)) ||
      182+ (event.runtimeRequest.providerTurnId !== null &&
      183+ state.ownedProviderTurnIds.has(event.runtimeRequest.providerTurnId)),
      184+ state,
      185+ ];
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High orchestration-v2/RunExecutionService.ts:179

      routeProviderEvent silently discards root-run runtime_request.updated events when the request has providerTurnId: null and threadId equal to the root thread. This causes approval/runtime requests emitted by the root turn to never be ingested, so the run can wait on an approval the app never sees.

      The runtime_request.updated case only accepts events from owned child threads (ownsChildThread excludes the root thread) or requests whose providerTurnId is already in ownedProviderTurnIds. When attempt.providerTurnId is null, the routing state starts with an empty ownedProviderTurnIds set, so neither condition matches. Consider also accepting runtime requests whose threadId equals input.threadId (the root thread).

          case "runtime_request.updated":
            return [
      -        (event.threadId !== undefined && ownsChildThread(event.threadId)) ||
      +        (event.threadId !== undefined && ownsThread(event.threadId)) ||
                (event.runtimeRequest.providerTurnId !== null &&
                  state.ownedProviderTurnIds.has(event.runtimeRequest.providerTurnId)),
              state,
            ];
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/RunExecutionService.ts around lines 179-185:
      
      `routeProviderEvent` silently discards root-run `runtime_request.updated` events when the request has `providerTurnId: null` and `threadId` equal to the root thread. This causes approval/runtime requests emitted by the root turn to never be ingested, so the run can wait on an approval the app never sees.
      
      The `runtime_request.updated` case only accepts events from owned *child* threads (`ownsChildThread` excludes the root thread) or requests whose `providerTurnId` is already in `ownedProviderTurnIds`. When `attempt.providerTurnId` is `null`, the routing state starts with an empty `ownedProviderTurnIds` set, so neither condition matches. Consider also accepting runtime requests whose `threadId` equals `input.threadId` (the root thread).
      @@ -0,0 +661,21 @@
      661+ sourceThreadId: row.sourceThreadId,
      662+ sourceItemId: row.sourceItemId,
      663+ item: row.item,
      664+ }));
      665+ const localPrefix = inheritedVisibleTurnItemsFromLocalItems(
      666+ input.sourceProjection.turnItems.filter((item) => {
      667+ if (
      668+ isOrchestrationV2SupersededInterrupt({
      669+ item,
      670+ attempts: input.sourceProjection.attempts,
      671+ })
      672+ ) {
      673+ return false;
      674+ }
      675+ if (item.runId === null) {
      676+ return false;
      677+ }
      678+ const ordinal = runOrdinalById.get(item.runId);
      679+ return ordinal !== undefined && ordinal <= sourceRun.ordinal;
      680+ }),
      681+ );
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium orchestration-v2/ProjectionStore.ts:665

      visibleTurnItemsThroughRun includes local turn items from rolled-back runs in the child thread's inherited timeline because it filters sourceProjection.turnItems with only isOrchestrationV2SupersededInterrupt and the run-ordinal check, never applying isOrchestrationV2TurnItemVisible. Forking from a later run after an earlier run was rolled back therefore surfaces rolled-back messages and actions in the descendant thread's conversation history. Consider applying the same visibility predicate used for active local items so rolled-back runs are excluded.

         const localPrefix = inheritedVisibleTurnItemsFromLocalItems(
           input.sourceProjection.turnItems.filter((item) => {
             if (
               isOrchestrationV2SupersededInterrupt({
                 item,
                 attempts: input.sourceProjection.attempts,
               })
             ) {
               return false;
             }
      -      if (item.runId === null) {
      +      if (!isOrchestrationV2TurnItemVisible(item, input.sourceProjection)) {
               return false;
             }
             const ordinal = runOrdinalById.get(item.runId);
             return ordinal !== undefined && ordinal <= sourceRun.ordinal;
           }),
         );
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/ProjectionStore.ts around lines 665-681:
      
      `visibleTurnItemsThroughRun` includes local turn items from rolled-back runs in the child thread's inherited timeline because it filters `sourceProjection.turnItems` with only `isOrchestrationV2SupersededInterrupt` and the run-ordinal check, never applying `isOrchestrationV2TurnItemVisible`. Forking from a later run after an earlier run was rolled back therefore surfaces rolled-back messages and actions in the descendant thread's conversation history. Consider applying the same visibility predicate used for active local items so rolled-back runs are excluded.
      @@ -0,0 +110,21 @@
      110+ operation: input.operation,
      111+ providerTurnId: input.providerTurnId,
      112+ cause: "The recorded provider execution target is no longer valid.",
      113+ });
      114+ }
      115+ // A restart-session command commits the replacement binding before its
      116+ // process-bound effect runs. The old live runtime must still receive
      117+ // the interrupt, but only when the projection matches the exact
      118+ // replacement captured by that same durable effect.
      119+ const interruptProviderThread = targetsRecordedSession
      120+ ? providerThread
      121+ : { ...providerThread, providerSessionId: input.providerSessionId };
      122+ if (providerTurn.status !== "running") {
      123+ return {
      124+ projection,
      125+ providerThread: interruptProviderThread,
      126+ providerTurn,
      127+ session: Option.none(),
      128+ };
      129+ }
      130+ const session = yield* sessions.get(input.providerSessionId);
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium orchestration-v2/ProviderTurnControlService.ts:130

      load returns a ProviderTurnControlError when providerTurn.status is still "running" but the provider session runtime is already gone (sessions.get returns Option.none()). Because terminal provider events are projected asynchronously on a detached ingestion fiber, a turn can finish and have its runtime removed before the projection reflects the status change. In that window, interrupt and interruptAndAwaitTerminal fail spuriously for a turn that has already terminated, instead of treating the missing runtime as already-terminal and no-oping (or waiting for the projection to catch up). Consider returning a no-op result when the session is missing but the turn is still marked running, rather than failing immediately.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/ProviderTurnControlService.ts around line 130:
      
      `load` returns a `ProviderTurnControlError` when `providerTurn.status` is still `"running"` but the provider session runtime is already gone (`sessions.get` returns `Option.none()`). Because terminal provider events are projected asynchronously on a detached ingestion fiber, a turn can finish and have its runtime removed before the projection reflects the status change. In that window, `interrupt` and `interruptAndAwaitTerminal` fail spuriously for a turn that has already terminated, instead of treating the missing runtime as already-terminal and no-oping (or waiting for the projection to catch up). Consider returning a no-op result when the session is missing but the turn is still marked `running`, rather than failing immediately.
      @@ -0,0 +153,21 @@
      153+ isProviderTurnControlError(cause)
      154+ ? cause
      155+ : new ProviderTurnControlError({
      156+ threadId: input.threadId,
      157+ operation: "interrupt",
      158+ providerTurnId: input.providerTurnId,
      159+ cause,
      160+ }),
      161+ ),
      162+ ),
      163+ interruptAndAwaitTerminal: (input) =>
      164+ Effect.gen(function* () {
      165+ const loaded = yield* load({ ...input, operation: "restart" });
      166+ if (Option.isSome(loaded.session)) {
      167+ yield* loaded.session.value.interruptTurn({
      168+ providerThread: loaded.providerThread,
      169+ providerTurnId: loaded.providerTurn.id,
      170+ });
      171+ }
      172+
      173+ for (let remaining = 1_000; remaining > 0; remaining -= 1) {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium orchestration-v2/ProviderTurnControlService.ts:173

      interruptAndAwaitTerminal polls the projection up to 1,000 times with setImmediate yields, then throws ProviderTurnControlError ("did not terminalize before restart") when the loop is exhausted. This is iteration-bounded, not time-bounded, so on a lightly loaded event loop the 1,000 iterations elapse in milliseconds while the detached ingestion fiber that projects terminal events is still catching up — causing the method to error out even though the turn terminalizes moments later. Consider replacing the fixed iteration count with a real clock-based timeout (e.g. Effect.timeout) so the wait duration is deterministic regardless of event-loop load.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/ProviderTurnControlService.ts around line 173:
      
      `interruptAndAwaitTerminal` polls the projection up to 1,000 times with `setImmediate` yields, then throws `ProviderTurnControlError` ("did not terminalize before restart") when the loop is exhausted. This is iteration-bounded, not time-bounded, so on a lightly loaded event loop the 1,000 iterations elapse in milliseconds while the detached ingestion fiber that projects terminal events is still catching up — causing the method to error out even though the turn terminalizes moments later. Consider replacing the fixed iteration count with a real clock-based timeout (e.g. `Effect.timeout`) so the wait duration is deterministic regardless of event-loop load.
      @@ -0,0 +308,21 @@
      308+ onSome: (effect) => effect.status === "cancelled",
      309+ }),
      310+ ),
      311+ );
      312+
      313+ const runOnce = Effect.gen(function* () {
      314+ const claimed = yield* outbox.claimNext({ workerId, leaseDurationMs });
      315+ if (Option.isNone(claimed)) {
      316+ return false;
      317+ }
      318+ const effect = claimed.value;
      319+ // Cancellation can commit after the durable claim but before the
      320+ // process-local Deferred is registered. Re-read the authoritative row
      321+ // once before starting external work; later cancellations use the
      322+ // Deferred raced below.
      323+ if (yield* wasCancelled(effect.id)) {
      324+ yield* outbox.clearCancellation(effect.id);
      325+ return true;
      326+ }
      327+ const execution = executor.execute(effect).pipe(Effect.as("executed" as const));
      328+ const cancellation = outbox
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium orchestration-v2/EffectWorker.ts:328

      A cancellation that commits after the wasCancelled re-check at line 323 but before awaitCancellation(effect.id) registers its deferred is permanently lost, so the worker proceeds to execute executor.execute(effect) even though the outbox row is already cancelled. The outbox only delivers cancellation wakeups to a pre-registered deferred; there is no retry or re-check after the deferred is installed. For process-bound effects like provider-turn.start or runtime-request.respond, this means cancelled work can still be sent to the provider. Consider re-checking wasCancelled(effect.id) immediately after awaitCancellation registers its deferred, or registering the deferred before the initial wasCancelled check.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/EffectWorker.ts around line 328:
      
      A cancellation that commits after the `wasCancelled` re-check at line 323 but before `awaitCancellation(effect.id)` registers its deferred is permanently lost, so the worker proceeds to execute `executor.execute(effect)` even though the outbox row is already `cancelled`. The outbox only delivers cancellation wakeups to a pre-registered deferred; there is no retry or re-check after the deferred is installed. For process-bound effects like `provider-turn.start` or `runtime-request.respond`, this means cancelled work can still be sent to the provider. Consider re-checking `wasCancelled(effect.id)` immediately after `awaitCancellation` registers its deferred, or registering the deferred before the initial `wasCancelled` check.
      @@ -0,0 +39,21 @@
      39+
      40+ const allocate: TurnItemPositionStoreV2Shape["allocate"] = ({
      41+ threadId,
      42+ turnItemId,
      43+ runId,
      44+ runOrdinal: suppliedRunOrdinal,
      45+ }) =>
      46+ Effect.gen(function* () {
      47+ const runRows =
      48+ runId === null
      49+ ? []
      50+ : yield* sql<{ readonly ordinal: number }>`
      51+ SELECT ordinal
      52+ FROM orchestration_v2_projection_runs
      53+ WHERE thread_id = ${threadId} AND run_id = ${runId}
      54+ LIMIT 1
      55+ `;
      56+ const runOrdinal = suppliedRunOrdinal ?? runRows[0]?.ordinal ?? null;
      57+ const lowerBound = runOrdinal === null ? 0 : runOrdinal * 1_000_000;
      58+ const upperBound = runOrdinal === null ? 999_999 : lowerBound + 999_999;
      59+ yield* sql`
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High orchestration-v2/TurnItemPositionStore.ts:59

      The allocate insert uses ON CONFLICT(thread_id, turn_item_id) DO NOTHING, which only handles duplicate turn-item ids. When two concurrent calls for different turnItemIds in the same thread/run both compute the same MAX(ordinal) + 1, the second insert hits the (thread_id, ordinal) uniqueness constraint and the effect fails with TurnItemPositionStoreError instead of retrying. This causes intermittent failures during concurrent turn-item creation. Consider retrying the allocation on a (thread_id, ordinal) conflict — e.g. loop until the SELECT … INSERT … SELECT succeeds — so that ordinal collisions resolve transparently.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/TurnItemPositionStore.ts around line 59:
      
      The `allocate` insert uses `ON CONFLICT(thread_id, turn_item_id) DO NOTHING`, which only handles duplicate turn-item ids. When two concurrent calls for *different* `turnItemId`s in the same thread/run both compute the same `MAX(ordinal) + 1`, the second insert hits the `(thread_id, ordinal)` uniqueness constraint and the effect fails with `TurnItemPositionStoreError` instead of retrying. This causes intermittent failures during concurrent turn-item creation. Consider retrying the allocation on a `(thread_id, ordinal)` conflict — e.g. loop until the `SELECT … INSERT … SELECT` succeeds — so that ordinal collisions resolve transparently.
      @@ -0,0 +208,21 @@
      208+ ...base,
      209+ subagents: upsertById(base.subagents, event.payload),
      210+ };
      211+ case "provider-session.attached":
      212+ case "provider-session.updated":
      213+ return {
      214+ ...base,
      215+ providerSessions: upsertById(base.providerSessions, event.payload),
      216+ };
      217+ case "provider-session.detached":
      218+ return {
      219+ ...base,
      220+ providerSessions: base.providerSessions.filter(
      221+ (session) => session.id !== event.payload.providerSessionId,
      222+ ),
      223+ };
      224+ case "provider-thread.updated":
      225+ return {
      226+ ...base,
      227+ thread:
      228+ event.payload.appThreadId === base.thread.id
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium orchestration-v2/ProjectionStore.ts:228

      When a provider-thread.updated event arrives for thread A but event.payload.appThreadId refers to thread B, applyToProjection drops the activeProviderThreadId update because the appThreadId === base.thread.id check fails on thread A's projection. Thread B's projection never receives the update because applyToProjectionReplayState only applies the event to event.threadId. As a result, the owning thread's activeProviderThreadId stays stale in the in-memory replay state while the SQL store updates the correct thread row. Consider routing provider-thread.updated events to the projection identified by event.payload.appThreadId, or updating both the event's thread and the appThreadId thread's projection.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/ProjectionStore.ts around line 228:
      
      When a `provider-thread.updated` event arrives for thread A but `event.payload.appThreadId` refers to thread B, `applyToProjection` drops the `activeProviderThreadId` update because the `appThreadId === base.thread.id` check fails on thread A's projection. Thread B's projection never receives the update because `applyToProjectionReplayState` only applies the event to `event.threadId`. As a result, the owning thread's `activeProviderThreadId` stays stale in the in-memory replay state while the SQL store updates the correct thread row. Consider routing `provider-thread.updated` events to the projection identified by `event.payload.appThreadId`, or updating both the event's thread and the `appThreadId` thread's projection.
    11. @@ -52,14 +46,14 @@
      46+ }>,
      5247 ): ContextWindowSnapshot | null {
      53- for (let index = activities.length - 1; index >= 0; index -= 1) {
      54- const activity = activities[index];
      55- if (!activity || activity.kind !== "context-window.updated") {
      48+ for (let index = entries.length - 1; index >= 0; index -= 1) {
      49+ const entry = entries[index];
      50+ if (!entry || entry.item.type !== "compaction") {
      5651 continue;
      5752 }
      58-
      59- const payload = asRecord(activity.payload);
      60- const usedTokens = asFiniteNumber(payload?.usedTokens);
      53+ const payload = entry.item;
      54+ const usedTokens = asFiniteNumber(payload.afterTokenCount);
      6155 if (usedTokens === null || usedTokens < 0) {
      6256 continue;
      6357 }
      6458
      65- const maxTokens = asFiniteNumber(payload?.maxTokens);
      59+ const maxTokens = null;
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium lib/contextWindow.ts:59

      deriveLatestContextWindowSnapshot hard-codes maxTokens to null, which forces usedPercentage, remainingTokens, and remainingPercentage to all be null in every returned snapshot. ContextWindowMeter relies on these fields to render the capacity label and progress bar, so the context-window UI loses its percentage display whenever a compaction snapshot is found. Consider deriving maxTokens from the compaction payload instead of setting it to null.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/web/src/lib/contextWindow.ts around line 59:
      
      `deriveLatestContextWindowSnapshot` hard-codes `maxTokens` to `null`, which forces `usedPercentage`, `remainingTokens`, and `remainingPercentage` to all be `null` in every returned snapshot. `ContextWindowMeter` relies on these fields to render the capacity label and progress bar, so the context-window UI loses its percentage display whenever a compaction snapshot is found. Consider deriving `maxTokens` from the compaction payload instead of setting it to `null`.
      @@ -907,3 +960,4 @@
      907960 markdownCwd={ctx.markdownCwd}
      908961 />
      909962 </div>
      963+ {(row.message.inputIntent && row.message.inputIntent !== "turn_start") ||
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium chat/MessagesTimeline.tsx:963

      When a user message's projectedItem.item.status is running, the badge renders with border-destructive/25 bg-destructive/8 text-destructive and displays the text running, making an in-progress turn look like an error. The condition on lines 964-967 and 972-975 excludes only completed, pending, and waiting, so every other status — including healthy in-progress ones like running — falls into the destructive badge branch. Consider narrowing the condition to only genuine error statuses (or explicitly excluding running) so active turns aren't shown as failures.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/web/src/components/chat/MessagesTimeline.tsx around line 963:
      
      When a user message's `projectedItem.item.status` is `running`, the badge renders with `border-destructive/25 bg-destructive/8 text-destructive` and displays the text `running`, making an in-progress turn look like an error. The condition on lines 964-967 and 972-975 excludes only `completed`, `pending`, and `waiting`, so every other status — including healthy in-progress ones like `running` — falls into the destructive badge branch. Consider narrowing the condition to only genuine error statuses (or explicitly excluding `running`) so active turns aren't shown as failures.
      @@ -304,5 +379,5 @@
      304379 }
      305380
      306381 const foldsByAnchorEntryId = new Map<string, TurnFold>();
      307- for (const [turnId, group] of groupsByTurnId) {
      308- if (turnId === input.unsettledTurnId) {
      382+ for (const [runId, group] of groupsByRunId) {
      383+ if (runId === input.unsettledRunId || interruptedRunIds.has(runId)) {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium chat/MessagesTimeline.logic.ts:383

      deriveTurnFolds excludes any run from folding as soon as it finds a persisted run_interrupt_request or run_interrupt_result event for it. Because those events are stored in the timeline, an interrupted run never collapses behind a turn-fold row again — not just for the in-session interrupt, but permanently after reload or once later turns start. The result is that interrupted conversations stay fully expanded forever instead of collapsing behind the usual "You stopped after …" summary.

      The interrupt exclusion is keyed purely on persisted event presence, so it applies to every render. If only the currently active interrupt should stay expanded, gate the skip on the run being the latest unsettled one instead of on the persisted event set.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/web/src/components/chat/MessagesTimeline.logic.ts around line 383:
      
      `deriveTurnFolds` excludes any run from folding as soon as it finds a persisted `run_interrupt_request` or `run_interrupt_result` event for it. Because those events are stored in the timeline, an interrupted run never collapses behind a turn-fold row again — not just for the in-session interrupt, but permanently after reload or once later turns start. The result is that interrupted conversations stay fully expanded forever instead of collapsing behind the usual `"You stopped after …"` summary.
      
      The interrupt exclusion is keyed purely on persisted event presence, so it applies to every render. If only the currently active interrupt should stay expanded, gate the skip on the run being the latest unsettled one instead of on the persisted event set.
      @@ -0,0 +40,21 @@
      40+ Dialog,
      41+ DialogClose,
      42+ DialogDescription,
      43+ DialogFooter,
      44+ DialogHeader,
      45+ DialogPanel,
      46+ DialogPopup,
      47+ DialogTitle,
      48+} from "../ui/dialog";
      49+import { Input } from "../ui/input";
      50+import { Select, SelectItem, SelectPopup, SelectTrigger, SelectValue } from "../ui/select";
      51+import { Switch } from "../ui/switch";
      52+import { Textarea } from "../ui/textarea";
      53+import { stackedThreadToast, toastManager } from "../ui/toast";
      54+import { Tooltip, TooltipPopup, TooltipTrigger } from "../ui/tooltip";
      55+import { SettingsPageContainer, SettingsSection, useRelativeTimeTick } from "./settingsLayout";
      56+
      57+type ScheduleMode = "fixed" | "interval";
      58+type WorkspaceMode = "root" | "worktree" | "existing_worktree";
      59+
      60+interface DraftState {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium settings/ScheduledTasksSettings.tsx:60

      Editing a scheduled task that targets a non-default branch silently resets it to main. DraftState only stores baseRef for worktree workspaces, so when taskToDraft loads a task whose workspaceStrategy is root or existing_worktree, the branch is dropped. submit then rebuilds workspaceStrategy without it, and saving overwrites the task's branch with the default. Consider preserving the branch in DraftState for all workspace modes so round-tripping an edit does not change which code branch future runs execute against.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/web/src/components/settings/ScheduledTasksSettings.tsx around line 60:
      
      Editing a scheduled task that targets a non-default branch silently resets it to `main`. `DraftState` only stores `baseRef` for `worktree` workspaces, so when `taskToDraft` loads a task whose `workspaceStrategy` is `root` or `existing_worktree`, the branch is dropped. `submit` then rebuilds `workspaceStrategy` without it, and saving overwrites the task's branch with the default. Consider preserving the branch in `DraftState` for all workspace modes so round-tripping an edit does not change which code branch future runs execute against.
      @@ -0,0 +172,21 @@
      172+ causation_event_id,
      173+ correlation_id,
      174+ actor_kind,
      175+ payload_json,
      176+ metadata_json,
      177+ application_event_version
      178+ )
      179+ VALUES (
      180+ ${createdEventId},
      181+ 'project',
      182+ ${project.project_id},
      183+ COALESCE(
      184+ (
      185+ SELECT MAX(stream_version) + 1
      186+ FROM orchestration_events
      187+ WHERE aggregate_kind = 'project' AND stream_id = ${project.project_id}
      188+ ),
      189+ 0
      190+ ),
      191+ 'project.created',
      192+ ${project.updated_at},
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Migrations/038_ApplicationEventSource.ts:192

      The project.created baseline event uses ${project.updated_at} for occurred_at instead of ${project.created_at}, so any project that was edited after creation gets a creation event timestamp equal to its last update time rather than its actual creation time. Consumers of orchestration_events.occurred_at — event history, sequencing metadata, command receipt timing, rebuild diagnostics — will see incorrect project creation times after this migration runs. The payload correctly stores createdAt, but the event column does not. Use ${project.created_at} for the occurred_at value of the project.created event.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/persistence/Migrations/038_ApplicationEventSource.ts around line 192:
      
      The `project.created` baseline event uses `${project.updated_at}` for `occurred_at` instead of `${project.created_at}`, so any project that was edited after creation gets a creation event timestamp equal to its last update time rather than its actual creation time. Consumers of `orchestration_events.occurred_at` — event history, sequencing metadata, command receipt timing, rebuild diagnostics — will see incorrect project creation times after this migration runs. The payload correctly stores `createdAt`, but the event column does not. Use `${project.created_at}` for the `occurred_at` value of the `project.created` event.
      @@ -131,6 +133,15 @@
      131- typeof cause.message === "string"
      132- ) {
      133- return cause.message;
      134- }
      135- return String(cause);
      136-}
      133+const persistChatAttachments = Effect.fn("ws.assets.persistChatAttachments")(function* (input: {
      134+ readonly threadId: ThreadId;
      135+ readonly messageId: MessageId;
      136+ readonly attachments: ReadonlyArray<{
      137+ readonly type: "image";
      138+ readonly name: string;
      139+ readonly mimeType: string;
      140+ readonly sizeBytes: number;
      141+ readonly dataUrl: string;
      142+ }>;
      143+}) {
      144+ const config = yield* ServerConfig.ServerConfig;
      145+ const fileSystem = yield* FileSystem.FileSystem;
      146+ const path = yield* Path.Path;
      147+ return yield* Effect.forEach(
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium src/ws.ts:147

      persistChatAttachments writes each attachment file inside Effect.forEach as it processes them, so if a later attachment fails validation or writeFile, the effect fails after earlier attachments have already been written to disk. The RPC returns PersistChatAttachmentsError with no attachment metadata persisted, leaving orphaned files behind and making a multi-attachment upload only partially durable. Consider buffering all attachments in memory first (validating and decoding before any writes), then writing files only after every attachment has passed validation — or clean up already-written files on failure.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/ws.ts around line 147:
      
      `persistChatAttachments` writes each attachment file inside `Effect.forEach` as it processes them, so if a later attachment fails validation or `writeFile`, the effect fails after earlier attachments have already been written to disk. The RPC returns `PersistChatAttachmentsError` with no attachment metadata persisted, leaving orphaned files behind and making a multi-attachment upload only partially durable. Consider buffering all attachments in memory first (validating and decoding before any writes), then writing files only after every attachment has passed validation — or clean up already-written files on failure.
      @@ -0,0 +239,21 @@
      239+ );
      240+ yield* Effect.all(
      241+ [
      242+ hasRepositoryIdentity
      243+ ? Effect.void
      244+ : requestLane(repositoryIdentityLane, workspaceRoot, "repositoryIdentity"),
      245+ hasFaviconPath ? Effect.void : requestLane(faviconLane, workspaceRoot, "faviconPath"),
      246+ ],
      247+ { concurrency: "unbounded", discard: true },
      248+ );
      249+ });
      250+
      251+ const getAvailable: ProjectEnrichmentService["Service"]["getAvailable"] = Effect.fn(
      252+ "ProjectEnrichmentService.getAvailable",
      253+ )(function* (workspaceRoot) {
      254+ const available = yield* peek(workspaceRoot);
      255+ yield* request(workspaceRoot);
      256+ return available;
      257+ });
      258+
      259+ const invalidate: ProjectEnrichmentService["Service"]["invalidate"] = Effect.fn(
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium project/ProjectEnrichmentService.ts:259

      invalidate only clears the caches but does not remove the root from pendingRoots or cancel queued/in-flight workers. If a root is invalidated while a resolution is still pending, that stale worker repopulates both caches after invalidation, so callers read outdated metadata they explicitly invalidated. Additionally, a follow-up request will not enqueue a fresh lookup because the root is still marked pending. Consider removing the root from pendingRoots (and draining or canceling queued work) during invalidation.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/project/ProjectEnrichmentService.ts around line 259:
      
      `invalidate` only clears the caches but does not remove the root from `pendingRoots` or cancel queued/in-flight workers. If a root is invalidated while a resolution is still pending, that stale worker repopulates both caches after invalidation, so callers read outdated metadata they explicitly invalidated. Additionally, a follow-up `request` will not enqueue a fresh lookup because the root is still marked pending. Consider removing the root from `pendingRoots` (and draining or canceling queued work) during invalidation.
      @@ -0,0 +324,21 @@
      324+ projectId: input.projectId,
      325+ ...(input.title === undefined ? {} : { title: input.title }),
      326+ ...(workspaceRoot === existing.value.workspaceRoot ? {} : { workspaceRoot }),
      327+ ...(input.defaultModelSelection === undefined
      328+ ? {}
      329+ : { defaultModelSelection: input.defaultModelSelection }),
      330+ ...(input.scripts === undefined ? {} : { scripts: [...input.scripts] }),
      331+ },
      332+ (workspaceRoot === existing.value.workspaceRoot
      333+ ? Effect.void
      334+ : invalidateEnrichment(existing.value.workspaceRoot, workspaceRoot)
      335+ ).pipe(Effect.andThen(readCommitted(input.projectId))),
      336+ );
      337+ },
      338+ );
      339+
      340+ const bootstrap: ProjectService["Service"]["bootstrap"] = Effect.fn("ProjectService.bootstrap")(
      341+ function* (input) {
      342+ const existing = yield* getByWorkspaceRoot(input.workspaceRoot);
      343+ if (Option.isSome(existing)) return { project: existing.value, created: false };
      344+ return { project: yield* create(input), created: true };
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium project/ProjectService.ts:340

      bootstrap calls getByWorkspaceRoot(input.workspaceRoot) before creating, and getByWorkspaceRoot normalizes the workspace root without createIfMissing. So bootstrapping a new project with createWorkspaceRootIfMissing: true fails with ProjectOperationError('normalize-workspace') when the directory doesn't exist, instead of creating it and returning { created: true }. The pre-check should normalize with createIfMissing: input.createWorkspaceRootIfMissing (or otherwise account for the flag) before deciding whether the project already exists.

        )(function* (input) {
      -    const existing = yield* getByWorkspaceRoot(input.workspaceRoot);
      +    const existing = yield* getByWorkspaceRoot(input.workspaceRoot, input.createWorkspaceRootIfMissing ?? false);
          if (Option.isSome(existing)) return { project: existing.value, created: false };
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/project/ProjectService.ts around lines 340-344:
      
      `bootstrap` calls `getByWorkspaceRoot(input.workspaceRoot)` before creating, and `getByWorkspaceRoot` normalizes the workspace root without `createIfMissing`. So bootstrapping a new project with `createWorkspaceRootIfMissing: true` fails with `ProjectOperationError('normalize-workspace')` when the directory doesn't exist, instead of creating it and returning `{ created: true }`. The pre-check should normalize with `createIfMissing: input.createWorkspaceRootIfMissing` (or otherwise account for the flag) before deciding whether the project already exists.
      @@ -0,0 +1,4 @@
      1+import * as Effect from "effect/Effect";
      2+import * as SqlClient from "effect/unstable/sql/SqlClient";
      3+
      4+export default Effect.gen(function* () {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Migrations/036_OrchestrationV2ProviderSessionBindings.ts:4

      The backfill in 036_OrchestrationV2ProviderSessionBindings loses provider-session-to-thread associations for sessions shared across multiple threads. After upgrading, getThreadProjection() reads provider sessions through the new orchestration_v2_projection_provider_session_bindings table, so a pre-existing session that was attached to several threads appears only under its last thread and disappears from every other thread's projection.

      The INSERT OR IGNORE ... SELECT provider_session_id, thread_id FROM orchestration_v2_projection_provider_sessions backfill copies only the single current thread_id stored per provider session. Prior to this migration, ProjectionStore allowed a provider session to be attached to multiple threads, but each attach overwrote the row's thread_id instead of appending, so the source table only retained the last association. The new bindings table is now the source of truth, so the earlier associations are permanently dropped. Consider reconstructing the historical associations from the events/log before creating the bindings table, or document this data-loss tradeoff if the loss is acceptable.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/persistence/Migrations/036_OrchestrationV2ProviderSessionBindings.ts around line 4:
      
      The backfill in `036_OrchestrationV2ProviderSessionBindings` loses provider-session-to-thread associations for sessions shared across multiple threads. After upgrading, `getThreadProjection()` reads provider sessions through the new `orchestration_v2_projection_provider_session_bindings` table, so a pre-existing session that was attached to several threads appears only under its last thread and disappears from every other thread's projection.
      
      The `INSERT OR IGNORE ... SELECT provider_session_id, thread_id FROM orchestration_v2_projection_provider_sessions` backfill copies only the single current `thread_id` stored per provider session. Prior to this migration, `ProjectionStore` allowed a provider session to be attached to multiple threads, but each attach overwrote the row's `thread_id` instead of appending, so the source table only retained the last association. The new bindings table is now the source of truth, so the earlier associations are permanently dropped. Consider reconstructing the historical associations from the events/log before creating the bindings table, or document this data-loss tradeoff if the loss is acceptable.
      @@ -157,4 +166,4 @@
      157166 availableEditors,
      158167 openInCwd,
      159168 compact = false,
      160- enableShortcut = true,
      169+ displayMode = "toolbar",
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium chat/OpenInPicker.tsx:169

      Removing the useEffect keyboard handler for the editor.openFavorite shortcut breaks Ctrl/Cmd+O in OpenInPicker usages outside ChatView — most visibly the compact picker in FilePreviewPanel. Pressing the shortcut there no longer opens the previewed file in the preferred editor, because only ChatView installs useOpenFavoriteEditorShortcut now, and that hook targets the thread gitCwd rather than the previewed file's absolutePath. Consider keeping a local keydown handler in OpenInPicker (gated by displayMode or a similar flag) so the shortcut still works for non-ChatView callers.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/web/src/components/chat/OpenInPicker.tsx around line 169:
      
      Removing the `useEffect` keyboard handler for the `editor.openFavorite` shortcut breaks Ctrl/Cmd+O in `OpenInPicker` usages outside `ChatView` — most visibly the compact picker in `FilePreviewPanel`. Pressing the shortcut there no longer opens the previewed file in the preferred editor, because only `ChatView` installs `useOpenFavoriteEditorShortcut` now, and that hook targets the thread `gitCwd` rather than the previewed file's `absolutePath`. Consider keeping a local keydown handler in `OpenInPicker` (gated by `displayMode` or a similar flag) so the shortcut still works for non-`ChatView` callers.
      @@ -0,0 +95,21 @@
      95+ EffectAcpErrors.AcpError,
      96+ Scope.Scope
      97+ >;
      98+ readonly assertComplete?: Effect.Effect<void, EffectAcpErrors.AcpError>;
      99+}
      100+
      101+export const registerGrokAcpExtensions: NonNullable<AcpAdapterV2Flavor["registerExtensions"]> = ({
      102+ runtime,
      103+ requestUserInput,
      104+}) =>
      105+ Effect.forEach(
      106+ ["x.ai/ask_user_question", "_x.ai/ask_user_question"] as const,
      107+ (method) =>
      108+ runtime.handleExtRequest(method, XAiAskUserQuestionRequest, (params) => {
      109+ const identity = extractXAiAskUserQuestionIdentity(params);
      110+ const questions = extractXAiAskUserQuestions(params).map((question) => ({
      111+ id: question.id,
      112+ header: question.header,
      113+ question: question.question,
      114+ options: [...question.options],
      115+ }));
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/GrokAdapterV2.ts:110

      registerGrokAcpExtensions rebuilds each question object with only id, header, question, and options, dropping the multiSelect field that extractXAiAskUserQuestions sets. When Grok sends a multi-select question, the UI receives it as single-select and only one choice is returned, so Grok gets an incomplete answer array. The rebuilt object should preserve multiSelect.

      Suggested change
      110- const questions = extractXAiAskUserQuestions(params).map((question) => ({
      111- id: question.id,
      112- header: question.header,
      113- question: question.question,
      114- options: [...question.options],
      115- }));
      110+ questions: extractXAiAskUserQuestions(params).map((question) => ({
      111+ id: question.id,
      112+ header: question.header,
      113+ question: question.question,
      114+ multiSelect: question.multiSelect,
      115+ options: [...question.options],
      116+ }))
      Also found in 1 other location(s)

      packages/client-runtime/src/state/threadRequests.ts:58

      derivePendingThreadRequests overwrites every user_input_request question with multiSelect: false. The contracts allow UserInputQuestion.multiSelect to be true, so any pending request that legitimately accepts multiple answers will be presented as single-select only, causing the client to render the wrong UI and prevent users from submitting the intended response.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.ts around lines 110-115:
      
      `registerGrokAcpExtensions` rebuilds each question object with only `id`, `header`, `question`, and `options`, dropping the `multiSelect` field that `extractXAiAskUserQuestions` sets. When Grok sends a multi-select question, the UI receives it as single-select and only one choice is returned, so Grok gets an incomplete answer array. The rebuilt object should preserve `multiSelect`.
      
      Also found in 1 other location(s):
      - packages/client-runtime/src/state/threadRequests.ts:58 -- `derivePendingThreadRequests` overwrites every `user_input_request` question with `multiSelect: false`. The contracts allow `UserInputQuestion.multiSelect` to be `true`, so any pending request that legitimately accepts multiple answers will be presented as single-select only, causing the client to render the wrong UI and prevent users from submitting the intended response.
      
      @@ -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

      🟠 High src/serverRuntimeStartup.ts:438

      A failure in resolveAutoBootstrapWelcomeTargets (e.g., from projects.bootstrap or threadLaunch.launch) now aborts the entire startup effect at line 438, causing commandGate.failCommandReady to be called so the server never accepts commands. Previously this optional auto-bootstrap step was forked and its failures were caught and logged as a warning, so the server remained usable even when the workspace/project bootstrap failed. Consider wrapping the autoBootstrap phase in an error handler (or reverting to a forked-and-logged pattern) so bootstrap failures degrade gracefully without blocking server command readiness.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/serverRuntimeStartup.ts around line 438:
      
      A failure in `resolveAutoBootstrapWelcomeTargets` (e.g., from `projects.bootstrap` or `threadLaunch.launch`) now aborts the entire `startup` effect at line 438, causing `commandGate.failCommandReady` to be called so the server never accepts commands. Previously this optional auto-bootstrap step was forked and its failures were caught and logged as a warning, so the server remained usable even when the workspace/project bootstrap failed. Consider wrapping the `autoBootstrap` phase in an error handler (or reverting to a forked-and-logged pattern) so bootstrap failures degrade gracefully without blocking server command readiness.
      @@ -0,0 +158,21 @@
      158+ function* (workspaceRoot: string) {
      159+ const repositoryIdentity = yield* Cache.get(repositoryIdentityCache, workspaceRoot);
      160+ yield* logFailure(workspaceRoot, "repositoryIdentity", repositoryIdentity);
      161+ const faviconPath = yield* Cache.getSuccess(faviconCache, workspaceRoot);
      162+ yield* PubSub.publish(changes, {
      163+ workspaceRoot,
      164+ repositoryIdentityResolved: Exit.isSuccess(repositoryIdentity),
      165+ enrichment: {
      166+ repositoryIdentity: availableValue(Option.some(repositoryIdentity)),
      167+ faviconPath: availableValue(faviconPath),
      168+ },
      169+ });
      170+ },
      171+ );
      172+
      173+ const resolveFavicon = Effect.fn("ProjectEnrichmentService.resolveFavicon")(function* (
      174+ workspaceRoot: string,
      175+ ) {
      176+ const faviconPath = yield* Cache.get(faviconCache, workspaceRoot);
      177+ yield* logFailure(workspaceRoot, "faviconPath", faviconPath);
      178+ });
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium project/ProjectEnrichmentService.ts:173

      resolveFavicon never publishes to changes, so when a workspace's favicon resolves after its repository identity has already emitted, subscribers to subscribeChanges never receive the favicon update and remain stuck with faviconPath: null. The repository-identity lane publishes a change event that includes the current favicon value, but the favicon lane only logs failures without emitting its own event on completion. Consider publishing a ProjectEnrichmentChange from resolveFavicon after the cache resolves, mirroring what resolveRepositoryIdentity does.

        const resolveFavicon = Effect.fn("ProjectEnrichmentService.resolveFavicon")(function* (
          workspaceRoot: string,
        ) {
          const faviconPath = yield* Cache.get(faviconCache, workspaceRoot);
          yield* logFailure(workspaceRoot, "faviconPath", faviconPath);
      +    const repositoryIdentity = yield* Cache.getSuccess(repositoryIdentityCache, workspaceRoot);
      +    yield* PubSub.publish(changes, {
      +      workspaceRoot,
      +      repositoryIdentityResolved: Exit.isSuccess(repositoryIdentity),
      +      enrichment: {
      +        repositoryIdentity: availableValue(repositoryIdentity),
      +        faviconPath: availableValue(faviconPath),
      +      },
      +    });
        });
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/project/ProjectEnrichmentService.ts around lines 173-178:
      
      `resolveFavicon` never publishes to `changes`, so when a workspace's favicon resolves after its repository identity has already emitted, subscribers to `subscribeChanges` never receive the favicon update and remain stuck with `faviconPath: null`. The repository-identity lane publishes a change event that includes the current favicon value, but the favicon lane only logs failures without emitting its own event on completion. Consider publishing a `ProjectEnrichmentChange` from `resolveFavicon` after the cache resolves, mirroring what `resolveRepositoryIdentity` does.
      @@ -0,0 +138,21 @@
      138+ `;
      139+ yield* sql`
      140+ INSERT OR IGNORE INTO orchestration_v2_turn_item_positions (
      141+ thread_id,
      142+ turn_item_id,
      143+ ordinal
      144+ )
      145+ SELECT thread_id, turn_item_id, ordinal
      146+ FROM orchestration_v2_projection_turn_items
      147+ ORDER BY thread_id, ordinal, turn_item_id
      148+ `;
      149+
      150+ yield* sql`
      151+ CREATE TABLE orchestration_v2_projection_metadata (
      152+ projection_name TEXT PRIMARY KEY,
      153+ schema_version INTEGER NOT NULL,
      154+ last_sequence INTEGER NOT NULL,
      155+ updated_at TEXT NOT NULL
      156+ )
      157+ `;
      158+ yield* sql`
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Migrations/035_OrchestrationV2Foundation.ts:158

      The orchestration_v2_projection_metadata seed row is inserted with schema_version = 1, but the runtime's ProjectionMaintenanceV2.verify expects ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION = 2. Because verify compares the stored version to that constant, every freshly migrated database is flagged as invalid and forced through a full V2 projection rebuild on the next boot. Consider seeding with 2 so the version matches what the runtime expects.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/persistence/Migrations/035_OrchestrationV2Foundation.ts around line 158:
      
      The `orchestration_v2_projection_metadata` seed row is inserted with `schema_version = 1`, but the runtime's `ProjectionMaintenanceV2.verify` expects `ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION = 2`. Because `verify` compares the stored version to that constant, every freshly migrated database is flagged as invalid and forced through a full V2 projection rebuild on the next boot. Consider seeding with `2` so the version matches what the runtime expects.
      @@ -0,0 +140,21 @@
      140+ {item.output !== undefined ? <StructuredValue value={item.output} /> : null}
      141+ {item.exitCode !== undefined ? (
      142+ <p className={item.exitCode === 0 ? "text-emerald-600" : "text-destructive"}>
      143+ Process exited with code {item.exitCode}
      144+ </p>
      145+ ) : null}
      146+ </div>
      147+ ) : null}
      148+
      149+ {item.type === "file_change" ? (
      150+ <div className="flex flex-wrap items-center gap-2">
      151+ <span className="font-mono text-muted-foreground">
      152+ {formatWorkspaceRelativePath(item.fileName, props.workspaceRoot)}
      153+ </span>
      154+ {item.additions !== undefined || item.deletions !== undefined ? (
      155+ <span>
      156+ <span className="text-emerald-600">+{item.additions ?? 0}</span>{" "}
      157+ <span className="text-destructive">-{item.deletions ?? 0}</span>
      158+ </span>
      159+ ) : null}
      160+ {item.runId !== null ? (
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium chat/V2ItemInspector.tsx:160

      The "Open diff" button in the file_change inspector calls props.onOpenTurnDiff(item.runId!, item.fileName) using the active thread's context, so for inherited file-change rows it opens the wrong thread's diff (or no diff at all) instead of the source thread where the run actually happened. The onOpenTurnDiff implementation resolves the diff against the active thread, not the projectedItem.sourceThreadId where item.runId originates. Consider threading props.projectedItem.sourceThreadId through onOpenTurnDiff so it opens the correct run's diff.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/web/src/components/chat/V2ItemInspector.tsx around line 160:
      
      The "Open diff" button in the `file_change` inspector calls `props.onOpenTurnDiff(item.runId!, item.fileName)` using the active thread's context, so for inherited file-change rows it opens the wrong thread's diff (or no diff at all) instead of the source thread where the run actually happened. The `onOpenTurnDiff` implementation resolves the diff against the active thread, not the `projectedItem.sourceThreadId` where `item.runId` originates. Consider threading `props.projectedItem.sourceThreadId` through `onOpenTurnDiff` so it opens the correct run's diff.
    12. @@ -94,20 +90 @@
      94- if (thread.session?.status === "error" || thread.latestTurn?.state === "error") {
      95- return "failed";
      96- }
      97- if (thread.session?.status === "starting") {
      98- return "starting";
      99- }
      100- if (thread.session?.status === "running" || thread.latestTurn?.state === "running") {
      101- return "running";
      102- }
      103- if (thread.latestTurn?.state === "completed") {
      104- return "completed";
      105- }
      106- // A turn that finished can still read as "interrupted" here: session
      107- // teardown settles still-running turns by session status, and that write
      108- // can race the turn.completed one. completedAt survives the race — a turn
      109- // that has a completion timestamp finished, whatever the state column says.
      110- // Without this, quick finish-then-teardown threads resolve to null
      111- // persistently and get tombstoned instead of published as completed.
      112- if (thread.latestTurn?.state === "interrupted" && thread.latestTurn.completedAt !== null) {
      113- return "completed";
      90+ if (thread.pendingRuntimeRequest !== null) {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium src/agentAwareness.ts:90

      resolveThreadAwarenessPhaseV2 returns "waiting_for_approval" for any non-null pendingRuntimeRequest that isn't user_input, which includes auth_refresh. Threads waiting on an auth refresh are published as actionable approval-needed rows even though there is no approval for the user to give. Consider excluding auth_refresh from the waiting_for_approval branch, matching the rest of the client model.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @packages/shared/src/agentAwareness.ts around line 90:
      
      `resolveThreadAwarenessPhaseV2` returns `"waiting_for_approval"` for any non-null `pendingRuntimeRequest` that isn't `user_input`, which includes `auth_refresh`. Threads waiting on an auth refresh are published as actionable approval-needed rows even though there is no approval for the user to give. Consider excluding `auth_refresh` from the `waiting_for_approval` branch, matching the rest of the client model.
      @@ -29,8 +132,18 @@
      29132 return { ...project, environmentId };
      30133 }
      31134
      32-export function scopeThreadShell(
      135+export function presentThreadShell(
      33136 environmentId: EnvironmentId,
      34- thread: OrchestrationThreadShell,
      137+ thread: OrchestrationV2ThreadShell,
      35138 ): EnvironmentThreadShell {
      36- return { ...thread, environmentId };
      139+ const updatedAt = iso(thread.updatedAt);
      140+ const latestRun =
      141+ thread.latestRunId === null
      142+ ? null
      143+ : ({
      144+ runId: thread.latestRunId,
      145+ status: thread.status === "idle" ? "completed" : thread.status,
      146+ requestedAt: null,
      147+ startedAt: null,
      148+ completedAt:
      149+ thread.status === "idle" || terminalRunStatus(thread.status) ? updatedAt : null,
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium state/models.ts:146

      presentThreadShell always sets latestRun.startedAt to null for V2 shell threads that have a latestRunId, so downstream consumers that treat a run as settled only when both startedAt and completedAt are present never see it as settled. For example, the Android "Plan Ready" badge gates on isLatestRunSettled(thread), which requires startedAt, so plan-mode threads loaded from a shell snapshot never show Plan Ready even after the run finishes and hasActionableProposedPlan is true. Consider populating startedAt (e.g. from thread.updatedAt or another available timestamp) so shell-derived runs are recognized as settled by those consumers.

      Suggested change
      146- requestedAt: null,
      147- startedAt: null,
      148- completedAt:
      149- thread.status === "idle" || terminalRunStatus(thread.status) ? updatedAt : null,
      146+ requestedAt: null,
      147+ startedAt: updatedAt,
      148+ completedAt:
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @packages/client-runtime/src/state/models.ts around lines 146-149:
      
      `presentThreadShell` always sets `latestRun.startedAt` to `null` for V2 shell threads that have a `latestRunId`, so downstream consumers that treat a run as settled only when both `startedAt` and `completedAt` are present never see it as settled. For example, the Android "Plan Ready" badge gates on `isLatestRunSettled(thread)`, which requires `startedAt`, so plan-mode threads loaded from a shell snapshot never show `Plan Ready` even after the run finishes and `hasActionableProposedPlan` is `true`. Consider populating `startedAt` (e.g. from `thread.updatedAt` or another available timestamp) so shell-derived runs are recognized as settled by those consumers.
      @@ -0,0 +15,21 @@
      15+ readonly checkpointTurnCount: number;
      16+ readonly checkpointRef: CheckpointRef;
      17+ readonly status: "ready" | "missing" | "error" | "stale";
      18+ readonly files: ReadonlyArray<{
      19+ readonly path: string;
      20+ readonly kind: string;
      21+ readonly additions: number;
      22+ readonly deletions: number;
      23+ }>;
      24+ readonly assistantMessageId: MessageId | null;
      25+ readonly completedAt: string;
      26+}
      27+
      28+/** Derives the checkpoint/diff rows needed by review UIs from native V2 entities. */
      29+export function deriveThreadCheckpointSummaries(
      30+ projection: OrchestrationV2ThreadProjection,
      31+): ReadonlyArray<ThreadCheckpointSummary> {
      32+ return projection.checkpoints.flatMap((checkpoint) => {
      33+ if (checkpoint.appRunOrdinal === null || checkpoint.runId === null) return [];
      34+ const assistantMessageId =
      35+ projection.messages.findLast(
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium state/threadCheckpoints.ts:35

      deriveThreadCheckpointSummaries derives assistantMessageId by calling projection.messages.findLast across the entire run. When a run contains multiple assistant messages, every checkpoint in that run is associated with the last assistant message rather than the one that existed when the checkpoint was captured. Any review/diff UI keyed on assistantMessageId will attach checkpoints from earlier turns to the wrong response. Consider matching on a per-turn criterion (e.g. message ordinal relative to checkpoint.appRunOrdinal) instead of findLast over the whole run.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @packages/client-runtime/src/state/threadCheckpoints.ts around line 35:
      
      `deriveThreadCheckpointSummaries` derives `assistantMessageId` by calling `projection.messages.findLast` across the entire run. When a run contains multiple assistant messages, every checkpoint in that run is associated with the **last** assistant message rather than the one that existed when the checkpoint was captured. Any review/diff UI keyed on `assistantMessageId` will attach checkpoints from earlier turns to the wrong response. Consider matching on a per-turn criterion (e.g. message ordinal relative to `checkpoint.appRunOrdinal`) instead of `findLast` over the whole run.
      @@ -187,0 +428,21 @@
      428+ ...(bootstrap?.branch === null || bootstrap?.branch === undefined
      429+ ? {}
      430+ : { branch: bootstrap.branch }),
      431+ };
      432+ return yield* request(ORCHESTRATION_V2_WS_METHODS.launchThread, {
      433+ commandId,
      434+ creationSource: input.creationSource ?? "web",
      435+ threadId: input.threadId,
      436+ ...(bootstrap === undefined ? { reuseExistingThread: true } : {}),
      437+ projectId: thread.projectId,
      438+ title: thread.title,
      439+ modelSelection: input.modelSelection ?? thread.modelSelection,
      440+ runtimeMode: input.runtimeMode,
      441+ interactionMode: input.interactionMode,
      442+ workspaceStrategy,
      443+ initialMessage: {
      444+ messageId: input.message.messageId,
      445+ text: input.message.text,
      446+ attachments,
      447+ },
      448+ });
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High operations/commands.ts:447

      startThreadTurn drops input.bootstrap?.runSetupScript when launching via ORCHESTRATION_V2_WS_METHODS.launchThread, so setup scripts never run on the initial launch path even though callers set runSetupScript: true. The launch request object built on line 432 omits the field entirely, causing the newly launched thread/worktree to skip the expected project bootstrap. Consider including runSetupScript in the launch payload when input.bootstrap provides it.

            initialMessage: {
              messageId: input.message.messageId,
              text: input.message.text,
              attachments,
            },
      +      ...(input.bootstrap?.runSetupScript === undefined
      +        ? {}
      +        : { runSetupScript: input.bootstrap.runSetupScript }),
          });
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @packages/client-runtime/src/operations/commands.ts around lines 447-448:
      
      `startThreadTurn` drops `input.bootstrap?.runSetupScript` when launching via `ORCHESTRATION_V2_WS_METHODS.launchThread`, so setup scripts never run on the initial launch path even though callers set `runSetupScript: true`. The launch request object built on line 432 omits the field entirely, causing the newly launched thread/worktree to skip the expected project bootstrap. Consider including `runSetupScript` in the launch payload when `input.bootstrap` provides it.
      @@ -136,3 +149,11 @@
      136149 scheduler,
      137150 concurrency,
      138151 }),
      152+ forkFromRun: createEnvironmentCommand(runtime, {
      153+ label: "environment-data:commands:thread:fork-from-run",
      154+ execute: (input: ForkThreadFromRunInput) => forkThreadFromRun(input),
      155+ scheduler,
      156+ concurrency: {
      157+ mode: "serial",
      158+ key: ({ environmentId, input }) => JSON.stringify([environmentId, input.sourceThreadId]),
      159+ },
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium state/threadCommands.ts:156

      forkFromRun serializes only on [environmentId, input.sourceThreadId], so a command targeting the forked thread (e.g. startTurn on targetThreadId) is not serialized behind the fork. If the follow-up command reaches the server before the fork creates the target thread and its pending transfer, it starts a normal run without fork context or fails to load. The serial key should include targetThreadId (or the fork should share a lane with subsequent commands on that thread) so follow-up commands wait for the fork to complete.

      Suggested change
      156- concurrency: {
      157- mode: "serial",
      158- key: ({ environmentId, input }) => JSON.stringify([environmentId, input.sourceThreadId]),
      159- },
      156+ concurrency: {
      157+ mode: "serial",
      158+ key: ({ environmentId, input }) => JSON.stringify([environmentId, input.sourceThreadId, input.targetThreadId]),
      159+ }
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @packages/client-runtime/src/state/threadCommands.ts around lines 156-159:
      
      `forkFromRun` serializes only on `[environmentId, input.sourceThreadId]`, so a command targeting the forked thread (e.g. `startTurn` on `targetThreadId`) is **not** serialized behind the fork. If the follow-up command reaches the server before the fork creates the target thread and its pending transfer, it starts a normal run without fork context or fails to load. The serial key should include `targetThreadId` (or the fork should share a lane with subsequent commands on that thread) so follow-up commands wait for the fork to complete.
      @@ -0,0 +23,21 @@
      23+ readonly nodes: ReadonlyMap<ThreadId, ThreadRelationshipNode>;
      24+ readonly edges: ReadonlyArray<ThreadRelationshipEdge>;
      25+}
      26+
      27+export interface ThreadRelationshipWalkRow {
      28+ readonly threadId: ThreadId;
      29+ readonly fromThreadId: ThreadId;
      30+ readonly depth: number;
      31+ readonly edge: ThreadRelationshipEdge;
      32+}
      33+
      34+export function resolveMergeBackTargetThreadId(
      35+ projection: Pick<OrchestrationV2ThreadProjection, "thread"> | null,
      36+): ThreadId | null {
      37+ if (projection?.thread.lineage.relationshipToParent !== "fork") return null;
      38+ return projection.thread.forkedFrom?.type === "run"
      39+ ? projection.thread.forkedFrom.threadId
      40+ : projection.thread.lineage.parentThreadId;
      41+}
      42+
      43+function edgeKey(edge: ThreadRelationshipEdge): string {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium state/threadRelationships.ts:43

      deriveThreadRelationshipGraph deduplicates edges by sourceThreadId/targetThreadId/kind, so when multiple contextTransfers exist between the same two threads, all but the last are silently overwritten in edgesByKey and dropped from the returned edges array. Distinct transfers can legitimately coexist (each has its own id and statuses like superseded/consumed), so callers lose the ability to render or inspect those relationships. Consider including a discriminator (e.g., the transfer id) in edgeKey for transfer edges, or switching to an append-only structure for transfers.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @packages/client-runtime/src/state/threadRelationships.ts around line 43:
      
      `deriveThreadRelationshipGraph` deduplicates edges by `sourceThreadId`/`targetThreadId`/`kind`, so when multiple `contextTransfers` exist between the same two threads, all but the last are silently overwritten in `edgesByKey` and dropped from the returned `edges` array. Distinct transfers can legitimately coexist (each has its own `id` and statuses like `superseded`/`consumed`), so callers lose the ability to render or inspect those relationships. Consider including a discriminator (e.g., the transfer `id`) in `edgeKey` for transfer edges, or switching to an append-only structure for transfers.
    13. @@ -0,0 +114,21 @@
      114+ }) -
      115+ relationshipSortKey({
      116+ edge: right.edge,
      117+ threadId: right.threadId,
      118+ currentThreadId: props.threadId,
      119+ mergeTargetThreadId,
      120+ }),
      121+ );
      122+ const canMerge = mergeTargetThreadId !== null && latestCompletedRun !== null;
      123+ const canDetach = projection ? canDetachThreadProviderSession(projection) : false;
      124+
      125+ if (relationshipRows.length === 0) {
      126+ return null;
      127+ }
      128+
      129+ const openThread = (threadId: ThreadId) => {
      130+ void navigate({
      131+ to: "/$environmentId/$threadId",
      132+ params: buildThreadRouteParams(scopeThreadRef(props.environmentId, threadId)),
      133+ });
      134+ };
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium chat/ThreadRelationshipsControl.tsx:125

      ThreadRelationshipsPanel returns null when relationshipRows.length === 0, which hides the entire section — including the "Disconnect agent session" menu — even on detachable threads. canDetach depends only on an active provider session, not on relationship rows, so a thread with no lineage relationships but an active session silently loses access to the detach action. Consider rendering the section header (with the detach menu) whenever canDetach is true, not only when there are relationship rows.

      -  if (relationshipRows.length === 0) {
      -    return null;
      -  }
      -
      -  const openThread = (threadId: ThreadId) => {
      +  const openThread = (threadId: ThreadId) => {
      +  if (relationshipRows.length === 0 && !canDetach) {
      +    return null;
      +  }
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/web/src/components/chat/ThreadRelationshipsControl.tsx around lines 125-134:
      
      `ThreadRelationshipsPanel` returns `null` when `relationshipRows.length === 0`, which hides the entire section — including the "Disconnect agent session" menu — even on detachable threads. `canDetach` depends only on an active provider session, not on relationship rows, so a thread with no lineage relationships but an active session silently loses access to the detach action. Consider rendering the section header (with the detach menu) whenever `canDetach` is true, not only when there are relationship rows.
      @@ -1098,17 +328,7 @@
      1098- } else if (Option.isNone(discoveryExit.value)) {
      1099- discoveryWarning = `Cursor ACP model discovery timed out after ${CURSOR_ACP_MODEL_DISCOVERY_TIMEOUT_MS}ms.`;
      1100- } else if (discoveryExit.value.value.length === 0) {
      1101- discoveryWarning = "Cursor ACP model discovery returned no built-in models.";
      1102- } else {
      1103- discoveredModels = discoveryExit.value;
      1104- }
      1105- }
      328+
      329+ const snapshot = catalogResult.success.value;
      330+ const discoveredModels = buildCursorDiscoveredModelsFromSdk(snapshot.models);
      1106331 return buildCursorProviderSnapshot({
      1107332 checkedAt,
      1108333 cursorSettings,
      1109- parsed,
      1110- discoveredModels: Option.getOrElse(
      1111- Option.filter(discoveredModels, (models) => models.length > 0),
      1112- () => [] as const,
      1113- ),
      1114- ...(discoveryWarning ? { discoveryWarning } : {}),
      334+ parsed: {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Layers/CursorProvider.ts:334

      When the SDK catalog read succeeds, checkCursorProviderStatus hard-codes version: null in the parsed probe data, so every healthy Cursor snapshot loses its version and update-advisory information. buildServerProvider() only produces versionAdvisory metadata when a real version string is passed, so users will never see Cursor version/update status even on successful provider checks. Consider populating version from snapshot (or another available source) on the success path instead of hard-coding null.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Layers/CursorProvider.ts around line 334:
      
      When the SDK catalog read succeeds, `checkCursorProviderStatus` hard-codes `version: null` in the `parsed` probe data, so every healthy Cursor snapshot loses its version and update-advisory information. `buildServerProvider()` only produces `versionAdvisory` metadata when a real version string is passed, so users will never see Cursor version/update status even on successful provider checks. Consider populating `version` from `snapshot` (or another available source) on the success path instead of hard-coding `null`.
      @@ -0,0 +21,21 @@
      21+ readonly canReorder: boolean;
      22+ readonly canPromoteToSteer: boolean;
      23+}
      24+
      25+export function resolveActiveThreadRun(projection: Projection): Run | null {
      26+ return projection.runs.findLast((run) => ACTIVE_RUN_STATUSES.has(run.status)) ?? null;
      27+}
      28+
      29+export function resolveThreadProviderSession(projection: Projection): ProviderSession | null {
      30+ const activeRun = resolveActiveThreadRun(projection);
      31+ const providerThreadId = activeRun?.providerThreadId ?? projection.thread.activeProviderThreadId;
      32+ const activeProviderThread =
      33+ providerThreadId === null
      34+ ? null
      35+ : (projection.providerThreads.find((thread) => thread.id === providerThreadId) ?? null);
      36+ const attachedProviderThread =
      37+ activeProviderThread ??
      38+ projection.providerThreads.find(
      39+ (thread) => thread.appThreadId === projection.thread.id && thread.providerSessionId !== null,
      40+ ) ??
      41+ null;
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium state/threadWorkflows.ts:36

      resolveThreadProviderSession falls back to the first provider thread matching the app thread id, not the most recent one. When activeProviderThreadId is null, it can bind to an old, stopped/errored session instead of the latest attached session, causing canDetachThreadProviderSession to wrongly return false and hiding supported queue/steer actions. Consider using findLast (and sorting by recency) so the newest attached provider thread wins.

        const attachedProviderThread =
          activeProviderThread ??
      -    projection.providerThreads.find(
      -      (thread) => thread.appThreadId === projection.thread.id && thread.providerSessionId !== null,
      -    ) ??
      -    null;
      +    projection.providerThreads.findLast(
      +      (thread) => thread.appThreadId === projection.thread.id && thread.providerSessionId !== null,
      +    ) ??
      +    null;
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @packages/client-runtime/src/state/threadWorkflows.ts around lines 36-41:
      
      `resolveThreadProviderSession` falls back to the first provider thread matching the app thread id, not the most recent one. When `activeProviderThreadId` is null, it can bind to an old, stopped/errored session instead of the latest attached session, causing `canDetachThreadProviderSession` to wrongly return `false` and hiding supported queue/steer actions. Consider using `findLast` (and sorting by recency) so the newest attached provider thread wins.
    14. @@ -0,0 +99,21 @@
      99+ status: transfer.status,
      100+ });
      101+ }
      102+ }
      103+
      104+ return { nodes, edges: [...edgesByKey.values()] };
      105+}
      106+
      107+export function relatedThreadIds(
      108+ graph: ThreadRelationshipGraph,
      109+ threadId: ThreadId,
      110+): ReadonlyArray<ThreadId> {
      111+ const ids = new Set<ThreadId>();
      112+ for (const edge of graph.edges) {
      113+ if (edge.sourceThreadId === threadId) ids.add(edge.targetThreadId);
      114+ if (edge.targetThreadId === threadId) ids.add(edge.sourceThreadId);
      115+ }
      116+ return [...ids];
      117+}
      118+
      119+export function walkThreadRelationships(
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium state/threadRelationships.ts:119

      walkThreadRelationships skips every edge to a thread after the first one that reaches it, so multiple relationships between the same two threads are silently dropped. For example, if a child is connected by both a subagent edge and a transfer edge, only whichever edge appears first in graph.edges is emitted and the other disappears from the result. Since each ThreadRelationshipWalkRow carries a single edge, callers see only one relationship where two exist.

      The visited set is keyed by ThreadId alone, so once a thread is enqueued all remaining edges to it are skipped. Consider keying visited by edge (e.g. edgeKey) instead of by thread id, so the walk emits all distinct edges while still avoiding traversal cycles.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @packages/client-runtime/src/state/threadRelationships.ts around line 119:
      
      `walkThreadRelationships` skips every edge to a thread after the first one that reaches it, so multiple relationships between the same two threads are silently dropped. For example, if a child is connected by both a `subagent` edge and a `transfer` edge, only whichever edge appears first in `graph.edges` is emitted and the other disappears from the result. Since each `ThreadRelationshipWalkRow` carries a single `edge`, callers see only one relationship where two exist.
      
      The `visited` set is keyed by `ThreadId` alone, so once a thread is enqueued all remaining edges to it are skipped. Consider keying `visited` by edge (e.g. `edgeKey`) instead of by thread id, so the walk emits all distinct edges while still avoiding traversal cycles.
    15. @@ -0,0 +2374,21 @@
      2374+ registerThread(nativeSession, providerThread, null);
      2375+ return providerThread;
      2376+ }).pipe(
      2377+ Effect.mapError(
      2378+ (cause) =>
      2379+ new ProviderAdapterEnsureThreadError({
      2380+ driver: OPENCODE_PROVIDER,
      2381+ threadId: threadInput.threadId,
      2382+ cause,
      2383+ }),
      2384+ ),
      2385+ ),
      2386+ resumeThread: (threadInput) =>
      2387+ Effect.gen(function* () {
      2388+ const sessionId = nativeThreadId(threadInput.providerThread);
      2389+ const response = yield* sdkCall("session.get", { sessionID: sessionId }, () =>
      2390+ client.session.get({ sessionID: sessionId }),
      2391+ );
      2392+ const nativeSession = unwrapData("session.get", response);
      2393+ const resumedAt = yield* DateTime.now;
      2394+ const providerThread = {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Adapters/OpenCodeAdapterV2.ts:2394

      The returned providerThread keeps the stale providerInstanceId from threadInput.providerThread instead of the current adapter instance's id. Only providerSessionId is overwritten, so resuming a thread created under a different OpenCode instance yields a providerThread whose providerInstanceId no longer matches the active instance. Downstream code filters provider threads by providerInstanceId, so the resumed thread cannot be matched and later turns may create a new native thread instead of continuing the conversation. Add providerInstanceId: input.providerInstanceId to the rebuilt object.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts around line 2394:
      
      The returned `providerThread` keeps the stale `providerInstanceId` from `threadInput.providerThread` instead of the current adapter instance's id. Only `providerSessionId` is overwritten, so resuming a thread created under a different OpenCode instance yields a `providerThread` whose `providerInstanceId` no longer matches the active instance. Downstream code filters provider threads by `providerInstanceId`, so the resumed thread cannot be matched and later turns may create a new native thread instead of continuing the conversation. Add `providerInstanceId: input.providerInstanceId` to the rebuilt object.
      @@ -0,0 +2366,21 @@
      2366+ const providerThread = makeProviderThread({
      2367+ idAllocator,
      2368+ providerInstanceId: options.instanceId,
      2369+ providerSessionId: input.providerSessionId,
      2370+ appThreadId: threadInput.threadId,
      2371+ nativeSession,
      2372+ now: createdAt,
      2373+ });
      2374+ registerThread(nativeSession, providerThread, null);
      2375+ return providerThread;
      2376+ }).pipe(
      2377+ Effect.mapError(
      2378+ (cause) =>
      2379+ new ProviderAdapterEnsureThreadError({
      2380+ driver: OPENCODE_PROVIDER,
      2381+ threadId: threadInput.threadId,
      2382+ cause,
      2383+ }),
      2384+ ),
      2385+ ),
      2386+ resumeThread: (threadInput) =>
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Adapters/OpenCodeAdapterV2.ts:2386

      resumeThread calls only session.get and never applies threadInput.runtimePolicy, so a resumed OpenCode session keeps the permission rules it was originally created with. Since openCodePermissionRules is applied only at session.create time, resuming a thread that was created under a looser policy leaves edit/network/command permissions enabled even after the app has switched to a stricter runtimePolicy. The next turn on the resumed thread runs with stale, overly broad permissions instead of the requested policy. Consider re-applying threadInput.runtimePolicy (or re-invoking the permission-rule setup used at create time) during resume so the session's permissions match the current policy.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts around line 2386:
      
      `resumeThread` calls only `session.get` and never applies `threadInput.runtimePolicy`, so a resumed OpenCode session keeps the permission rules it was originally created with. Since `openCodePermissionRules` is applied only at `session.create` time, resuming a thread that was created under a looser policy leaves edit/network/command permissions enabled even after the app has switched to a stricter `runtimePolicy`. The next turn on the resumed thread runs with stale, overly broad permissions instead of the requested policy. Consider re-applying `threadInput.runtimePolicy` (or re-invoking the permission-rule setup used at create time) during resume so the session's permissions match the current policy.
    16. @@ -0,0 +44,21 @@
      44+ null;
      45+ if (item === null) return EMPTY_V2_ITEM_SUPPORT;
      46+
      47+ const run =
      48+ item.runId === null
      49+ ? null
      50+ : (projection.runs.find((candidate) => candidate.id === item.runId) ?? null);
      51+ const attempts =
      52+ item.runId === null
      53+ ? EMPTY_V2_ITEM_SUPPORT.attempts
      54+ : projection.attempts.filter((candidate) => candidate.runId === item.runId);
      55+ const node =
      56+ item.nodeId === null
      57+ ? null
      58+ : (projection.nodes.find((candidate) => candidate.id === item.nodeId) ?? null);
      59+ const providerThread =
      60+ item.providerThreadId === null || item.providerThreadId === undefined
      61+ ? null
      62+ : (projection.providerThreads.find((candidate) => candidate.id === item.providerThreadId) ??
      63+ null);
      64+ const providerSession =
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium state/itemSupport.ts:64

      resolveV2ItemSupport returns providerSession: null when providerThread.providerSessionId is null, even when the item has a runtimeRequest whose responseCapability.providerSessionId references a session present in projection.providerSessions. This silently drops the session link for request-backed items on detached provider threads. Consider falling back to runtimeRequest.responseCapability.providerSessionId (for live capabilities) when providerThread.providerSessionId is absent.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @packages/client-runtime/src/state/itemSupport.ts around line 64:
      
      `resolveV2ItemSupport` returns `providerSession: null` when `providerThread.providerSessionId` is null, even when the item has a `runtimeRequest` whose `responseCapability.providerSessionId` references a session present in `projection.providerSessions`. This silently drops the session link for request-backed items on detached provider threads. Consider falling back to `runtimeRequest.responseCapability.providerSessionId` (for `live` capabilities) when `providerThread.providerSessionId` is absent.

Sign in to join this conversation.