Skip to content
Source
Sign inSign up
pingdotgg/t3code

feat(mobile): nested subagent threads behind a toggle #3871

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

Stacking

Warning

Stacked on #3870 (which itself requires #2829). Only the top two commits belong to this PR — refactor(client-runtime): share subagent thread tree projection and feat(mobile): show collapsible nested subagent threads. Everything below them is the #3870 stack.

Summary

Opt-in nested subagent threads for the mobile home screen and thread sidebar, kept separate from #3870 on purpose so it can be dropped or deferred independently if the feature isn't wanted:

  • a persisted "Show nested subagents" toggle in the thread-list filter menu, default off — with it off, nothing changes
  • when enabled, child subagent threads render indented and collapsible under their parent on phone, tablet, and the thread navigation sidebar; pagination keeps counting root threads so expanded branches don't consume the preview quota
  • the tree comes from a shared environment-scoped projection in client-runtime with cycle and orphan fallbacks, so clients cannot drift on which rows count as roots; the web sidebar adopts the same projection in #3861 — whichever lands first, the other's copy of the two threadRelationships files rebases away cleanly

Validation

  • vp check, vp run typecheck — green
  • focused suites (home list items, home thread list, preference storage, tree projection) — 32 tests passing
  • verified on the t3test AVD and a Pixel 7 Pro from the integration branch: toggle appears in the menu, nested Codex/Claude children expand and collapse, and the preference survives a cold restart

Note

Medium Risk Low-risk list UX when the toggle stays off; medium overall because the diff also touches mobile thread navigation, feed, and desktop userdata paths where regressions would affect daily use.

Overview Adds an opt-in Show nested subagents control on the mobile home thread list (persisted in device preferences, default off). When enabled, the list uses shared client-runtime helpers (getSubagentThreadTreeRoots, flattenSubagentThreadTree) to indent subagent child threads under parents with per-branch expand/collapse; Show more pagination still counts root threads so expanded nests do not eat preview slots. Recent-thread previews and grouping now derive from roots as well.

The same diff also carries broader mobile orchestration V2 work alongside that feature: home/archive fixtures move to V2 shell types, orchestration cache schema alignment, thread detail feed changes (latestRun, fork-from-response, expandable work log + ThreadActivityInspector), queue reorder UI, relationship banner, runtime-request IDs, and checkpoint summaries from projection. Desktop production state paths shift from userdata to userdata-v2 (and related branding/test expectations). Large .plans docs and a small marketing harness label update are documentation-only.

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

Note

Add nested subagent thread display behind a toggle in mobile home and sidebar

  • Adds a 'Show nested subagents' toggle to the mobile home header, sidebar filter menu, and navigation sidebar, persisted via a new useSubagentThreadListPreference hook.
  • Thread list rows now support hierarchical display with expandable/collapsible branches, depth-based indentation, and disclosure chevrons; root-thread-based pagination excludes subagent threads from recent slots.
  • Introduces a full Orchestration V2 runtime on both server and client: V2 projection store, event sink, effect outbox, provider adapters (Claude, Codex, Cursor, Grok, ACP Registry, OpenCode), session manager, run execution, checkpoint capture/rollback, thread fork/merge, and queue management.
  • Adds new UI surfaces including ThreadDetailsPanel, ThreadRelationshipsPanel, ThreadRelationshipsBanner, ThreadQueueControl, ThreadAutomationsPanel, V2ItemInspector, and V2LifecycleRow on web and mobile.
  • Migrates server shell/thread state and client atoms from V1 to V2 snapshot and projection types; all provider drivers now expose orchestrationAdapter instead of adapter.
  • Adds 8 database migrations (033–040) covering V2 event log, projection tables, effect outbox, provider session bindings, scheduled tasks, and application event source.
  • Exposes an Orchestrator MCP toolkit with handlers for thread lifecycle, task delegation, and scheduled task management.
  • Risk: default server state directory changes from userdata to userdata-v2 (and desktop from t3code to t3code-v2), and the SSH tunnel script targets userdata-v2; existing V1 persisted state will not be read by default.
📊 Macroscope summarized d03b0c3. 189 files reviewed, 0 issues evaluated, 0 issues filtered, 0 comments posted

🗂️ Filtered Issues

No issues evaluated.


Depends on #3861 for the server-side owned-subtree lifecycle cascade: mobile dispatches a single root command for archive/unarchive/delete and relies on the orchestrator to cascade the transition and cancel active runs across the owned subagent subtree.

    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: b0553413-3f04-4533-a286-02b3899e17a1

      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 d03b0c31981aee8397b7b7b82e5e984d04a6542d. Configure [here](https://www.cursor.com/dashboard/bugbot).
      @@ -163,4 +184,18 @@
      163184 : baselineCount,
      164185 totalCount,
      165186 );
      166- const visibleThreads = group.threads.slice(0, visibleCount);
      187+ const visibleRoots = roots.slice(0, visibleCount);
      188+ const visibleThreadRows: readonly SubagentThreadTreeRow<EnvironmentThreadShell>[] =
      189+ input.showSubagentThreads === true
      190+ ? flattenSubagentThreadTree({
      191+ threads: group.threads,
      192+ roots: visibleRoots,
      193+ expandedThreadKeys: input.expandedThreadKeys ?? new Set(),
      194+ threadSortOrder: input.threadSortOrder ?? "updated_at",
      195+ })
      196+ : visibleRoots.map((thread) => ({
      197+ thread,
      198+ depth: 0,
      199+ hasSubagentChildren: false,
      200+ isSubagentBranchExpanded: false,
      201+ }));

      Open subagent missing sidebar row

      High Severity

      When "Show nested subagents" is off, buildHomeListLayout incorrectly uses getSubagentThreadTreeRoots to determine total and visible thread counts. This causes child subagent threads to be excluded from the home list and navigation sidebar, even though they were previously displayed as flat rows. Consequently, these threads are not visible or selectable in the sidebar.

      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit d03b0c31981aee8397b7b7b82e5e984d04a6542d. Configure [here](https://www.cursor.com/dashboard/bugbot).
      @@ -163,4 +184,18 @@
      163184 : baselineCount,
      164185 totalCount,
      165186 );
      166- const visibleThreads = group.threads.slice(0, visibleCount);
      187+ const visibleRoots = roots.slice(0, visibleCount);
      188+ const visibleThreadRows: readonly SubagentThreadTreeRow<EnvironmentThreadShell>[] =
      189+ input.showSubagentThreads === true
      190+ ? flattenSubagentThreadTree({
      191+ threads: group.threads,
      192+ roots: visibleRoots,
      193+ expandedThreadKeys: input.expandedThreadKeys ?? new Set(),
      194+ threadSortOrder: input.threadSortOrder ?? "updated_at",
      195+ })
      196+ : visibleRoots.map((thread) => ({
      197+ thread,
      198+ depth: 0,
      199+ hasSubagentChildren: false,
      200+ isSubagentBranchExpanded: false,
      201+ }));

      Paginated roots hide selected subagent

      Medium Severity

      The new subagent display logic can inadvertently hide threads. When nested subagents are enabled, threads whose parent roots are paginated out, or subagent threads with collapsed parents during search, are not included in the visible list. This can cause selected or searched subagent threads to be missing from the home list.

      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit d03b0c31981aee8397b7b7b82e5e984d04a6542d. Configure [here](https://www.cursor.com/dashboard/bugbot).
    4. @@ -0,0 +42,21 @@
      42+ return yield* service.listScheduledTasks(scope);
      43+ }),
      44+ update_scheduled_task: (input) =>
      45+ Effect.gen(function* () {
      46+ const scope = yield* McpInvocationContext;
      47+ const service = yield* OrchestratorMcpService;
      48+ return yield* service.updateScheduledTask(scope, input);
      49+ }),
      50+ delete_scheduled_task: (input) =>
      51+ Effect.gen(function* () {
      52+ const scope = yield* McpInvocationContext;
      53+ const service = yield* OrchestratorMcpService;
      54+ return yield* service.deleteScheduledTask(scope, input);
      55+ }),
      56+ create_threads: (input) =>
      57+ Effect.gen(function* () {
      58+ const scope = yield* McpInvocationContext;
      59+ const service = yield* OrchestratorMcpService;
      60+ return yield* service.createThreads(scope, input);
      61+ }),
      62+ t3_thread_start: (input) =>
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium orchestrator/handlers.ts:62

      The t3_thread_start handler only calls service.createThreads and returns result.threads[0]!, so it creates an idle thread and never starts the first turn. The tool description says it "immediately start[s] its first turn," so callers invoking t3_thread_wait / t3_thread_read with the returned runId will observe an idle thread with no active run. The handler needs to also issue a start/send to the new thread after creation so the first turn is actually running.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/mcp/toolkits/orchestrator/handlers.ts around line 62:
      
      The `t3_thread_start` handler only calls `service.createThreads` and returns `result.threads[0]!`, so it creates an idle thread and never starts the first turn. The tool description says it "immediately start[s] its first turn," so callers invoking `t3_thread_wait` / `t3_thread_read` with the returned `runId` will observe an idle thread with no active run. The handler needs to also issue a start/send to the new thread after creation so the first turn is actually running.
      @@ -0,0 +242,21 @@
      242+ },
      243+} satisfies OrchestrationV2ProviderCapabilities;
      244+
      245+function negotiatedCapabilities(
      246+ base: OrchestrationV2ProviderCapabilities,
      247+ started: AcpSessionRuntimeStartResult,
      248+): OrchestrationV2ProviderCapabilities {
      249+ const agent = started.initializeResult.agentCapabilities ?? {};
      250+ const session = agent.sessionCapabilities;
      251+ const setup = started.sessionSetupResult;
      252+ const hasModelConfig =
      253+ setup.configOptions?.some((option) => option.category === "model") === true;
      254+ const hasModeConfig = setup.configOptions?.some((option) => option.category === "mode") === true;
      255+ const supportsMcp = agent.mcpCapabilities?.http === true || agent.mcpCapabilities?.sse === true;
      256+ const canLoad = agent.loadSession === true;
      257+ const canFork = session?.fork != null;
      258+ return {
      259+ ...base,
      260+ sessions: {
      261+ ...base.sessions,
      262+ supportsModelSwitchInSession: setup.models != null || hasModelConfig,
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/AcpAdapterV2.ts:262

      negotiatedCapabilities sets supportsModelSwitchInSession to true whenever sessionSetupResult.models is present, but ACP's models field reports current model state and does not imply session/set_model support. When an agent returns models without supporting model switching, the orchestrator treats in-session model changes as allowed, so configureSession calls runtime.setSessionModel(...) and the turn fails instead of forcing a restart. The hasModelConfig check (whether a "model" config option exists) is the reliable signal for switch support; setup.models != null should not also enable it.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts around line 262:
      
      `negotiatedCapabilities` sets `supportsModelSwitchInSession` to `true` whenever `sessionSetupResult.models` is present, but ACP's `models` field reports current model state and does not imply `session/set_model` support. When an agent returns `models` without supporting model switching, the orchestrator treats in-session model changes as allowed, so `configureSession` calls `runtime.setSessionModel(...)` and the turn fails instead of forcing a restart. The `hasModelConfig` check (whether a `"model"` config option exists) is the reliable signal for switch support; `setup.models != null` should not also enable it.
      @@ -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

      When cursorToolSearchResults receives an ls or readLints tool call that succeeded, it returns [] instead of the result entries. The default branch of the switch discards the successful result data, so the emitted file_search turn item loses all entries for those tool types. Consider adding case entries for ls and readLints to map their results into the expected { fileName, line?, preview? } shape.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.ts around line 464:
      
      When `cursorToolSearchResults` receives an `ls` or `readLints` tool call that succeeded, it returns `[]` instead of the result entries. The `default` branch of the `switch` discards the successful result data, so the emitted `file_search` turn item loses all entries for those tool types. Consider adding `case` entries for `ls` and `readLints` to map their results into the expected `{ fileName, line?, preview? }` shape.
      @@ -159,9 +157,19 @@
      157+ return firstScope === undefined
      158+ ? undefined
      159+ : checkpointRefForScopeOrdinal({
      160+ scopeId: firstScope.id,
      161+ ordinalWithinScope: 0,
      162+ });
      163+ })()
      164+ : readyCheckpoints.find((checkpoint) => checkpoint.appRunOrdinal === input.fromTurnCount)
      165+ ?.ref;
      166+ if (fromCheckpointRef === undefined) {
      159167 return yield* new CheckpointRefUnavailableError({
      160168 operation,
      161169 threadId: input.threadId,
      162- turnCount: input.toTurnCount,
      163- checkpoint: "to",
      170+ turnCount: input.fromTurnCount,
      171+ checkpoint: "from",
      164172 });
      165173 }
      166174
      167175 const diff = yield* checkpointStore
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium checkpointing/CheckpointDiffQuery.ts:175

      getTurnDiff always resolves both checkpoint refs inside toScope.cwd, but the from checkpoint may have been captured in a different scope's worktree. When a later run changed the runtime cwd, the from ref doesn't exist under toScope.cwd, so checkpointStore.diffCheckpoints fails with a "ref unavailable" error instead of returning the cross-run diff. Consider resolving the from ref in its own scope's cwd (or falling back to HEAD) when the scopes differ.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/checkpointing/CheckpointDiffQuery.ts around line 175:
      
      `getTurnDiff` always resolves both checkpoint refs inside `toScope.cwd`, but the `from` checkpoint may have been captured in a different scope's worktree. When a later run changed the runtime `cwd`, the `from` ref doesn't exist under `toScope.cwd`, so `checkpointStore.diffCheckpoints` fails with a "ref unavailable" error instead of returning the cross-run diff. Consider resolving the `from` ref in its own scope's `cwd` (or falling back to HEAD) when the scopes differ.
      @@ -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

      🟠 High Adapters/ClaudeAdapterV2.ts:522

      offer silently drops user prompts after the session is closed. Queue.shutdown(promptQueue) causes Queue.offer to return false, but Effect.asVoid discards that value, so callers see success while the message is never delivered to queryRuntime. The prompt.offer protocol log is also emitted, falsely claiming the message was sent.

      Check the Queue.offer result and fail when it returns false so callers are notified that the prompt was not enqueued.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts around line 522:
      
      `offer` silently drops user prompts after the session is closed. `Queue.shutdown(promptQueue)` causes `Queue.offer` to return `false`, but `Effect.asVoid` discards that value, so callers see success while the message is never delivered to `queryRuntime`. The `prompt.offer` protocol log is also emitted, falsely claiming the message was sent.
      
      Check the `Queue.offer` result and fail when it returns `false` so callers are notified that the prompt was not enqueued.
      @@ -0,0 +1577,21 @@
      1577+}
      1578+
      1579+function claudeToolResultBlocksFromUserMessage(
      1580+ message: SDKMessage,
      1581+): ReadonlyArray<ClaudeToolResultContentBlock> {
      1582+ if (message.type !== "user" || typeof message.message.content === "string") {
      1583+ return [];
      1584+ }
      1585+ return message.message.content.filter(isClaudeUserToolResultContentBlock);
      1586+}
      1587+
      1588+function claudeToolResultEntriesFromMessage(message: SDKMessage): ReadonlyArray<{
      1589+ readonly toolResult: ClaudeToolResultContentBlock;
      1590+ readonly output: ClaudeNativeToolOutput;
      1591+}> {
      1592+ const assistantResults = claudeToolResultBlocksFromAssistantMessage(message).map(
      1593+ (toolResult) => ({ toolResult, output: claudeNativeToolOutputFromToolResult(toolResult) }),
      1594+ );
      1595+ const userResults = claudeToolResultBlocksFromUserMessage(message);
      1596+ const structuredOutput =
      1597+ message.type === "user" && userResults.length === 1 ? message.tool_use_result : undefined;
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/ClaudeAdapterV2.ts:1597

      claudeToolResultEntriesFromMessage replaces the tool_result.content output with message.tool_use_result whenever a user message contains exactly one tool result. For built-in tools like Bash, tool_use_result is a structured object (e.g. { stdout, stderr, interrupted, ... }) while tool_result.content holds the human-readable output string. As a result, downstream artifacts serialize JSON blobs instead of the actual stdout/diff text whenever the message has a single tool result.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts around line 1597:
      
      `claudeToolResultEntriesFromMessage` replaces the `tool_result.content` output with `message.tool_use_result` whenever a `user` message contains exactly one tool result. For built-in tools like Bash, `tool_use_result` is a structured object (e.g. `{ stdout, stderr, interrupted, ... }`) while `tool_result.content` holds the human-readable output string. As a result, downstream artifacts serialize JSON blobs instead of the actual stdout/diff text whenever the message has a single tool result.
      @@ -1356,15 +559,6 @@
      1356- copyText: [summary, detail, fullDetail]
      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,
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium lib/threadActivity.ts:564

      buildThreadFeed forces attachments: [] for every assistant_message item, so any images or files included in an assistant reply are dropped from the mobile feed and never rendered. The conditionals on line 565 hardcode an empty array for assistant messages instead of reading item.attachments. Consider using item.attachments for both user_message and assistant_message rows.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/mobile/src/lib/threadActivity.ts around line 564:
      
      `buildThreadFeed` forces `attachments: []` for every `assistant_message` item, so any images or files included in an assistant reply are dropped from the mobile feed and never rendered. The conditionals on line 565 hardcode an empty array for assistant messages instead of reading `item.attachments`. Consider using `item.attachments` for both `user_message` and `assistant_message` rows.
      @@ -0,0 +1077,21 @@
      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(
      1088+ runtimePolicy: ProviderAdapterV2RuntimePolicy,
      1089+): PermissionMode {
      1090+ if (runtimePolicy.interactionMode === "plan") {
      1091+ return "plan";
      1092+ }
      1093+ if (runtimePolicy.approvalPolicy !== undefined && runtimePolicy.approvalPolicy !== "never") {
      1094+ return "default";
      1095+ }
      1096+
      1097+ switch (sandboxPolicyKindForClaudeRuntimePolicy(runtimePolicy)) {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Adapters/ClaudeAdapterV2.ts:1097

      permissionModeForClaudeRuntimePolicy returns "dontAsk" for a policy like { runtimeMode: "approval-required", sandboxPolicy: { type: "readOnly" } }, even though runtimeMode explicitly requires approvals. The sandboxPolicy check runs first and short-circuits to "dontAsk" before runtimeMode is consulted. Downstream, claudeRuntimeQueryPolicyForRuntimePolicy then installs no permission callback, so read-only tools execute automatically without any approval gating. Consider checking runtimeMode before sandboxPolicy so an approval-required runtime mode is never overridden by a read-only sandbox policy.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts around line 1097:
      
      `permissionModeForClaudeRuntimePolicy` returns `"dontAsk"` for a policy like `{ runtimeMode: "approval-required", sandboxPolicy: { type: "readOnly" } }`, even though `runtimeMode` explicitly requires approvals. The `sandboxPolicy` check runs first and short-circuits to `"dontAsk"` before `runtimeMode` is consulted. Downstream, `claudeRuntimeQueryPolicyForRuntimePolicy` then installs no permission callback, so read-only tools execute automatically without any approval gating. Consider checking `runtimeMode` before `sandboxPolicy` so an approval-required runtime mode is never overridden by a read-only sandbox policy.
      @@ -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

      🟠 High Adapters/ClaudeAdapterV2.ts:692

      claudeMcpQueryOverrides unconditionally adds "mcp__t3-code__*" to allowedTools whenever an MCP session exists, even when the caller's allowlist is a restrictive read-only set (e.g. Read, Glob, Grep). This causes read-only turns to gain access to mutating and orchestration tools exposed by the t3-code MCP server (such as preview_open and t3_thread_*), bypassing the sandbox restrictions the caller intended to enforce. Consider only adding the mcp__t3-code__* glob when the caller's allowedTools is undefined (i.e. unrestricted), or filtering the MCP tools to those that satisfy the caller's intended policy.

         if (session === undefined) {
           return input.allowedTools === undefined ? {} : { allowedTools: input.allowedTools };
         }
      +  if (input.allowedTools !== undefined) {
      +    return { allowedTools: input.allowedTools };
      +  }
         return {
           allowedTools: ["mcp__t3-code__*"],
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts around lines 692-693:
      
      `claudeMcpQueryOverrides` unconditionally adds `"mcp__t3-code__*"` to `allowedTools` whenever an MCP session exists, even when the caller's allowlist is a restrictive read-only set (e.g. `Read`, `Glob`, `Grep`). This causes read-only turns to gain access to mutating and orchestration tools exposed by the `t3-code` MCP server (such as `preview_open` and `t3_thread_*`), bypassing the sandbox restrictions the caller intended to enforce. Consider only adding the `mcp__t3-code__*` glob when the caller's `allowedTools` is undefined (i.e. unrestricted), or filtering the MCP tools to those that satisfy the caller's intended policy.
      @@ -0,0 +510,21 @@
      510+ };
      511+ }
      512+}
      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(
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/CodexAdapterV2.ts:530

      buildCodexTurnStartParams ignores input.runtimePolicy.reasoningEffort and only reads reasoningEffort from input.modelSelection. When a runtime policy sets reasoningEffort, that override is silently dropped and the Codex turn runs with the model default or user-selected effort instead of the enforced value. Consider preferring input.runtimePolicy.reasoningEffort (when present) before falling back to the model-selection option.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts around line 530:
      
      `buildCodexTurnStartParams` ignores `input.runtimePolicy.reasoningEffort` and only reads `reasoningEffort` from `input.modelSelection`. When a runtime policy sets `reasoningEffort`, that override is silently dropped and the Codex turn runs with the model default or user-selected effort instead of the enforced value. Consider preferring `input.runtimePolicy.reasoningEffort` (when present) before falling back to the model-selection option.
      @@ -63,12 +62,9 @@
      6362 "thread user input response",
      6463 );
      6564 const { selectedThread: selectedThreadShell } = useThreadSelection();
      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(
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

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

      useSelectedThreadRequests picks activePendingApprovals[0] and activePendingUserInputs[0] as the active request, but derivePendingThreadRequests returns requests in projection.runtimeRequests insertion order without sorting by createdAt. When requests arrive or are upserted out of chronological order, the hook surfaces and submits the wrong (not oldest) pending approval or user-input request. The previous code path sorted via derivePendingApprovals / derivePendingUserInputs; this regression is specific to the new mobile path. Consider sorting the derived approvals and user inputs by createdAt before selecting index 0.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/mobile/src/state/use-selected-thread-requests.ts around line 70:
      
      `useSelectedThreadRequests` picks `activePendingApprovals[0]` and `activePendingUserInputs[0]` as the active request, but `derivePendingThreadRequests` returns requests in `projection.runtimeRequests` insertion order without sorting by `createdAt`. When requests arrive or are upserted out of chronological order, the hook surfaces and submits the wrong (not oldest) pending approval or user-input request. The previous code path sorted via `derivePendingApprovals` / `derivePendingUserInputs`; this regression is specific to the new mobile path. Consider sorting the derived approvals and user inputs by `createdAt` before selecting index `0`.
      @@ -0,0 +157,21 @@
      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") {
      176+ await writeFixtureFiles(workspace.cwd);
      177+}
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

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

      When T3_CURSOR_REPLAY_CWD points at an existing project, running the subagent, todo_list, or tool_call_read_only scenarios silently overwrites the caller's package.json and tsconfig.json with hardcoded fixture content, destroying their real project configuration. prepareWorkspace returns remove: false for a user-supplied cwd, but writeFixtureFiles writes unconditionally. Consider skipping writeFixtureFiles when workspace.remove is false, or writing the fixture files into a dedicated subdirectory instead of the workspace root.

       if (scenario === "subagent" || scenario === "tool_call_read_only" || scenario === "todo_list") {
      -  await writeFixtureFiles(workspace.cwd);
      +  if (workspace.remove) {
      +    await writeFixtureFiles(workspace.cwd);
      +  }
       }
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/scripts/record-cursor-agent-sdk-replay-fixture.ts around lines 175-177:
      
      When `T3_CURSOR_REPLAY_CWD` points at an existing project, running the `subagent`, `todo_list`, or `tool_call_read_only` scenarios silently overwrites the caller's `package.json` and `tsconfig.json` with hardcoded fixture content, destroying their real project configuration. `prepareWorkspace` returns `remove: false` for a user-supplied `cwd`, but `writeFixtureFiles` writes unconditionally. Consider skipping `writeFixtureFiles` when `workspace.remove` is `false`, or writing the fixture files into a dedicated subdirectory instead of the workspace root.
      @@ -0,0 +504,21 @@
      504+ | { readonly status: "success"; readonly value: Value }
      505+ | { readonly status: "error"; readonly error: unknown }
      506+ | undefined {
      507+ const result = unknownRecord(rawResult);
      508+ if (result === undefined) {
      509+ return undefined;
      510+ }
      511+ const success = unknownRecord(result.success);
      512+ if (success !== undefined) {
      513+ return {
      514+ status: "success",
      515+ value: mapSuccess(success),
      516+ };
      517+ }
      518+ return {
      519+ status: "error",
      520+ error: result.error ?? result.permissionDenied ?? result,
      521+ };
      522+}
      523+
      524+function nestedGrepWorkspaceResults(success: Record<string, unknown>): Record<string, unknown> {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/CursorAdapterV2.ts:524

      nestedGrepWorkspaceResults always builds a { type: "content" } object and reads only content.matches, so nested grep calls made with outputMode set to "files" or "count" lose their actual results and return empty matches. The renderer handles files and count results separately, so subagent grep calls in those modes display incorrect or missing tool output. Consider branching on outputMode (or the presence of content.files / content.count) so each mode's data is preserved instead of being projected into the content shape.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.ts around line 524:
      
      `nestedGrepWorkspaceResults` always builds a `{ type: "content" }` object and reads only `content.matches`, so nested grep calls made with `outputMode` set to `"files"` or `"count"` lose their actual results and return empty matches. The renderer handles `files` and `count` results separately, so subagent grep calls in those modes display incorrect or missing tool output. Consider branching on `outputMode` (or the presence of `content.files` / `content.count`) so each mode's data is preserved instead of being projected into the content shape.
      @@ -0,0 +617,21 @@
      617+
      618+export function makeClaudeQueryOptions(input: {
      619+ readonly modelSelection: ModelSelection;
      620+ readonly nativeThreadId: string;
      621+ readonly resume: boolean;
      622+ readonly resumeSessionAt?: string;
      623+ readonly cwd: string | null;
      624+ readonly settings?: ClaudeSettings;
      625+ readonly sdkSettings?: string | ClaudeSdkSettings;
      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;
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/ClaudeAdapterV2.ts:637

      makeClaudeQueryOptions parses input.settings.launchArgs with parseCliArgs, which splits the string on raw whitespace without honoring shell quoting. A multi-word argument like --append-system-prompt "always think step by step" is broken into separate tokens — "always becomes the value for --append-system-prompt, and the remaining words are dropped as positionals. Users who set CLI arguments with spaces get silently truncated values at runtime. Consider using a shell-aware parser (e.g., parseArgsStringToArgs or shell-quote) so quoted values are preserved as a single token.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts around line 637:
      
      `makeClaudeQueryOptions` parses `input.settings.launchArgs` with `parseCliArgs`, which splits the string on raw whitespace without honoring shell quoting. A multi-word argument like `--append-system-prompt "always think step by step"` is broken into separate tokens — `"always` becomes the value for `--append-system-prompt`, and the remaining words are dropped as positionals. Users who set CLI arguments with spaces get silently truncated values at runtime. Consider using a shell-aware parser (e.g., `parseArgsStringToArgs` or `shell-quote`) so quoted values are preserved as a single token.
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High home/homeListItems.ts:165

      When showSubagentThreads is false (the default), buildHomeListLayout calls getSubagentThreadTreeRoots(group.threads) and renders only those roots. Non-root threads — including every thread whose lineage relationship is "subagent" — are dropped from the list entirely. The old code sliced group.threads directly, so subagent children appeared alongside their parents. With the new root-based pagination and no nested-tree toggle enabled, those child threads vanish from the home list and cannot be selected. Consider including non-root threads in the flat path (e.g., filter group.threads by the same root predicate used for pagination) so the default behavior still surfaces every thread.

      Also found in 2 other location(s)

      apps/mobile/src/features/threads/ThreadNavigationSidebar.tsx:255

      Passing showSubagentThreads into buildHomeListLayout at line 255 makes the default-off path hide every non-root subagent thread from the sidebar. buildHomeThreadGroups now reduces each group to rootThreads, and buildHomeListLayout&#39;s showSubagentThreads !== true branch only maps visibleRoots, so child threads are no longer rendered at all unless the new toggle is enabled. That changes existing behavior and can make previously visible/selected threads disappear from the list.

      apps/mobile/src/features/home/HomeScreen.tsx:272

      When showSubagentThreads is off, buildHomeListLayout still paginates over getSubagentThreadTreeRoots(group.threads) and renders visibleRoots only. That means every subagent child thread disappears from the home list instead of staying visible as a normal top-level row. Before this change the list used group.threads.slice(...), so turning the new feature off no longer preserves existing behavior and users can lose access to child threads entirely unless they enable nested mode.

      ✅ Resolved in ebef3b8f125724cb04bbb6677e2d3243008b0e41

    5. Approvability

      Verdict: Needs human review

      15 blocking correctness issues found. Diff is too large for automated approval analysis. A human reviewer should evaluate this PR.

      You can customize Macroscope's approvability policy. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    6. 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).

    7. @@ -0,0 +193,21 @@
      193+ identity: {
      194+ nativeThreadIds: "strong",
      195+ nativeTurnIds: "strong",
      196+ nativeItemIds: "strong",
      197+ nativeRequestIds: "strong",
      198+ },
      199+} satisfies OrchestrationV2ProviderCapabilities;
      200+
      201+function toProtocolError(detail: string, payload?: unknown): ProviderAdapterProtocolError {
      202+ return new ProviderAdapterProtocolError({
      203+ driver: CODEX_PROVIDER,
      204+ detail,
      205+ ...(payload === undefined ? {} : { payload }),
      206+ });
      207+}
      208+
      209+function normalizeCodexCause(error: unknown): unknown {
      210+ return error;
      211+}
      212+
      213+function codexTimestamp(seconds: number | null | undefined): DateTime.Utc {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Adapters/CodexAdapterV2.ts:213

      providerThreadFromCodexThread sets createdAt and updatedAt to NaN when the Codex thread response carries ISO 8601 strings for createdAt/updatedAt. codexTimestamp multiplies the value by 1000 and passes it to DateTime.makeUnsafe, so an ISO string like "2026-04-18T00:00:00.000Z" produces NaN, corrupting the timestamps on every provider thread. The function should parse ISO strings instead of assuming numeric Unix seconds.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts around line 213:
      
      `providerThreadFromCodexThread` sets `createdAt` and `updatedAt` to `NaN` when the Codex thread response carries ISO 8601 strings for `createdAt`/`updatedAt`. `codexTimestamp` multiplies the value by `1000` and passes it to `DateTime.makeUnsafe`, so an ISO string like `"2026-04-18T00:00:00.000Z"` produces `NaN`, corrupting the timestamps on every provider thread. The function should parse ISO strings instead of assuming numeric Unix seconds.
      @@ -0,0 +628,21 @@
      628+ lastRunOrdinal: null,
      629+ handoffIds: [],
      630+ forkedFrom: input.forkedFrom ?? null,
      631+ createdAt: codexTimestamp(input.thread.createdAt),
      632+ updatedAt: codexTimestamp(input.thread.updatedAt),
      633+ };
      634+}
      635+
      636+const isTerminalProviderTurn = (turn: OrchestrationV2ProviderTurn): boolean =>
      637+ turn.status === "completed" ||
      638+ turn.status === "interrupted" ||
      639+ turn.status === "failed" ||
      640+ turn.status === "cancelled";
      641+
      642+const providerTurnsForThread = (
      643+ providerTurns: ReadonlyArray<OrchestrationV2ProviderTurn>,
      644+ providerThread: OrchestrationV2ProviderThread,
      645+): ReadonlyArray<OrchestrationV2ProviderTurn> =>
      646+ providerTurns.filter((turn) => turn.providerThreadId === providerThread.id);
      647+
      648+const countTerminalTurnsAfterBoundary = (
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/CodexAdapterV2.ts:648

      resolveCodexForkRollbackTurnCount only counts terminal turns (completed/interrupted/failed/cancelled) after the fork boundary, so when later turns are still running or pending it returns 0. The forked Codex thread then skips native rollback and starts from the newest in-progress state instead of the requested historical turn. Consider counting all turns after the boundary, or at least all turns that have been initiated, so the rollback count reflects the actual conversation distance.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts around line 648:
      
      `resolveCodexForkRollbackTurnCount` only counts terminal turns (completed/interrupted/failed/cancelled) after the fork boundary, so when later turns are still `running` or `pending` it returns `0`. The forked Codex thread then skips native rollback and starts from the newest in-progress state instead of the requested historical turn. Consider counting all turns after the boundary, or at least all turns that have been initiated, so the rollback count reflects the actual conversation distance.
      @@ -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

      In openCodePermissionRules, the workspaceWrite branch only emits external_directory allow rules for entries in sandboxPolicy.writableRoots and never checks sandboxPolicy.readOnlyAccess. When a policy sets readOnlyAccess: { type: "fullAccess" } (e.g. WORKSPACE_NEVER_POLICY with type: "workspaceWrite" and approvalPolicy: "never"), reads from external directories outside the workspace remain denied, so OpenCode sessions that should have read-only access to external repos or files will fail or silently reject those reads. Consider adding an external_directory allow rule (pattern * or a scoped path) when readOnlyAccess.type === "fullAccess" in the workspaceWrite branch, mirroring the handling already present in the readOnly branch.

         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:
      
      In `openCodePermissionRules`, the `workspaceWrite` branch only emits `external_directory` allow rules for entries in `sandboxPolicy.writableRoots` and never checks `sandboxPolicy.readOnlyAccess`. When a policy sets `readOnlyAccess: { type: "fullAccess" }` (e.g. `WORKSPACE_NEVER_POLICY` with `type: "workspaceWrite"` and `approvalPolicy: "never"`), reads from external directories outside the workspace remain denied, so OpenCode sessions that should have read-only access to external repos or files will fail or silently reject those reads. Consider adding an `external_directory` allow rule (pattern `*` or a scoped path) when `readOnlyAccess.type === "fullAccess"` in the `workspaceWrite` branch, mirroring the handling already present in the `readOnly` branch.
      @@ -0,0 +81,21 @@
      81+ >
      82+ <Text
      83+ selectable
      84+ className="text-2xs leading-[17px] text-foreground-muted"
      85+ style={block.monospaced ? { fontFamily: "ui-monospace" } : undefined}
      86+ >
      87+ {block.value}
      88+ </Text>
      89+ </ScrollView>
      90+ </View>
      91+ ))}
      92+
      93+ {model.fileLinks.length > 0 ? (
      94+ <View className="gap-1">
      95+ <Text className="font-t3-medium text-3xs uppercase tracking-wide text-foreground-muted opacity-60">
      96+ Files
      97+ </Text>
      98+ {model.fileLinks.map((link) => {
      99+ const relativePath =
      100+ resolveWorkspaceRelativeFilePath(props.workspaceRoot, link.path) ??
      101+ (link.path.startsWith("/") ? null : link.path);
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium threads/ThreadActivityInspector.tsx:99

      File links with Windows absolute paths like C:\repo\file.ts or UNC paths like \\server\share\file are incorrectly treated as relative paths and remain tappable, navigating to ThreadFile with an invalid relative path instead of being disabled. The fallback on line 100 only rejects paths starting with /, so Windows-style absolute paths pass through because they don't begin with /. Consider using isAbsolutePath (which already handles Windows paths) instead of the link.path.startsWith("/") check.

      Suggested change
      99- const relativePath =
      100- resolveWorkspaceRelativeFilePath(props.workspaceRoot, link.path) ??
      101- (link.path.startsWith("/") ? null : link.path);
      99+ const relativePath =
      100+ resolveWorkspaceRelativeFilePath(props.workspaceRoot, link.path) ??
      101+ (isAbsolutePath(link.path) ? null : link.path);
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/mobile/src/features/threads/ThreadActivityInspector.tsx around lines 99-101:
      
      File links with Windows absolute paths like `C:\repo\file.ts` or UNC paths like `\\server\share\file` are incorrectly treated as relative paths and remain tappable, navigating to `ThreadFile` with an invalid relative path instead of being disabled. The fallback on line 100 only rejects paths starting with `/`, so Windows-style absolute paths pass through because they don't begin with `/`. Consider using `isAbsolutePath` (which already handles Windows paths) instead of the `link.path.startsWith("/")` check.
      @@ -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

      🟠 High orchestration-v2/CheckpointRollbackService.ts:46

      session.rollbackThread(...) is called before the rollback outcome is durably recorded via eventSink.write. If the process crashes after rollbackThread succeeds but before the events are written, a retry rebuilds runsToRollback from the stale projection and calls rollbackThread a second time, causing the provider conversation to be rewound too far or to fail against an already-rolled-back thread. Consider writing the rollback events before invoking session.rollbackThread, or guarding against re-entrant rollback with a persisted marker so a retry does not re-execute the provider-side rewind.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/CheckpointRollbackService.ts around line 46:
      
      `session.rollbackThread(...)` is called before the rollback outcome is durably recorded via `eventSink.write`. If the process crashes after `rollbackThread` succeeds but before the events are written, a retry rebuilds `runsToRollback` from the stale projection and calls `rollbackThread` a second time, causing the provider conversation to be rewound too far or to fail against an already-rolled-back thread. Consider writing the rollback events before invoking `session.rollbackThread`, or guarding against re-entrant rollback with a persisted marker so a retry does not re-execute the provider-side rewind.
      @@ -0,0 +148,21 @@
      148+ >
      149+ <SymbolView
      150+ name="arrow.up.right.square"
      151+ size={13}
      152+ tintColor={props.iconColor}
      153+ type="monochrome"
      154+ />
      155+ <Text className="min-w-0 flex-1 text-2xs leading-4 text-foreground">
      156+ {link.label}
      157+ </Text>
      158+ </Pressable>
      159+ ))}
      160+ </View>
      161+ ) : null}
      162+
      163+ {model.rollbackTarget ? (
      164+ <Pressable
      165+ accessibilityRole="button"
      166+ accessibilityLabel="Roll back to this checkpoint"
      167+ disabled={rollingBack}
      168+ onPress={() => {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High threads/ThreadActivityInspector.tsx:168

      Tapping the rollback button immediately invokes revertCheckpoint with no confirmation dialog. This is an irreversible data-loss action — the web UI explicitly warns it "will discard newer messages and turn diffs" and "cannot be undone." An accidental tap permanently rolls the thread back with no chance to cancel. Consider adding a confirmation step before invoking the command.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/mobile/src/features/threads/ThreadActivityInspector.tsx around line 168:
      
      Tapping the rollback button immediately invokes `revertCheckpoint` with no confirmation dialog. This is an irreversible data-loss action — the web UI explicitly warns it "will discard newer messages and turn diffs" and "cannot be undone." An accidental tap permanently rolls the thread back with no chance to cancel. Consider adding a confirmation step before invoking the command.
      @@ -0,0 +102,21 @@
      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) {
      113+ navigation.navigate("SettingsSheet", { screen: "SettingsArchive" });
      114+ return;
      115+ }
      116+ navigation.navigate("Thread", {
      117+ environmentId: props.environmentId,
      118+ threadId,
      119+ });
      120+ };
      121+
      122+ const merge = async () => {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium threads/ThreadRelationshipsBanner.tsx:122

      merge() and detach() don't guard against re-entry before busyAction is set, so a rapid double-tap fires the command twice. The serial scheduler queues both requests, leading to duplicate mergeBack/stopSession calls (e.g. merging the same fork twice). Consider adding an early return when busyAction !== null at the top of each handler.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/mobile/src/features/threads/ThreadRelationshipsBanner.tsx around line 122:
      
      `merge()` and `detach()` don't guard against re-entry before `busyAction` is set, so a rapid double-tap fires the command twice. The serial scheduler queues both requests, leading to duplicate `mergeBack`/`stopSession` calls (e.g. merging the same fork twice). Consider adding an early `return` when `busyAction !== null` at the top of each handler.
      @@ -0,0 +2192,21 @@
      2192+ (cause) =>
      2193+ new ProjectionStoreReadError({
      2194+ threadId: ThreadId.make("thread:shell"),
      2195+ cause,
      2196+ }),
      2197+ ),
      2198+ );
      2199+
      2200+ return {
      2201+ apply,
      2202+ getShellSnapshot,
      2203+ getThreadProjection,
      2204+ getThreadSnapshot,
      2205+ } satisfies ProjectionStoreV2Shape;
      2206+ }),
      2207+);
      2208+
      2209+export const layerMemory: Layer.Layer<ProjectionStoreV2> = Layer.effect(
      2210+ ProjectionStoreV2,
      2211+ Effect.gen(function* () {
      2212+ const replayState = yield* Ref.make(makeProjectionReplayState());
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium orchestration-v2/ProjectionStore.ts:2212

      getThreadSnapshot reads the projection from replayState and then separately reads sequence, but a concurrent apply can interleave between those two reads and produce a snapshot with an old projection paired with a newer snapshotSequence. Callers that stream from that newer sequence will skip the intervening event entirely, leaving the client permanently stale until a full reload.

      This happens because the projection state and the sequence counter are stored in two separate Refs and updated in two steps (Ref.modify(replayState, ...) then Ref.update(sequence, ...)), so readers can observe an inconsistent pair. Consider combining the projection state and sequence into a single Ref so updates and reads are atomic.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/ProjectionStore.ts around line 2212:
      
      `getThreadSnapshot` reads the projection from `replayState` and then separately reads `sequence`, but a concurrent `apply` can interleave between those two reads and produce a snapshot with an old projection paired with a newer `snapshotSequence`. Callers that stream from that newer sequence will skip the intervening event entirely, leaving the client permanently stale until a full reload.
      
      This happens because the projection state and the sequence counter are stored in two separate `Ref`s and updated in two steps (`Ref.modify(replayState, ...)` then `Ref.update(sequence, ...)`), so readers can observe an inconsistent pair. Consider combining the projection state and sequence into a single `Ref` so updates and reads are atomic.
      @@ -0,0 +1088,21 @@
      1088+function isSensitiveCodexProtocolKey(key: string): boolean {
      1089+ const normalized = key.replace(/[^a-z0-9]/gi, "").toLowerCase();
      1090+ return (
      1091+ normalized.endsWith("authorization") ||
      1092+ normalized.endsWith("apikey") ||
      1093+ normalized.endsWith("token") ||
      1094+ normalized.endsWith("password") ||
      1095+ normalized.endsWith("secret")
      1096+ );
      1097+}
      1098+
      1099+export const codexAppServerClientFactoryFromSettingsLayer: Layer.Layer<
      1100+ CodexAppServerClientFactory,
      1101+ never,
      1102+ ChildProcessSpawner.ChildProcessSpawner | ServerConfig
      1103+> = Layer.effect(
      1104+ CodexAppServerClientFactory,
      1105+ Effect.gen(function* () {
      1106+ const spawner = yield* ChildProcessSpawner.ChildProcessSpawner;
      1107+ const { providerEventLogPath } = yield* ServerConfig;
      1108+ const nativeEventLogger = yield* makeEventNdjsonLogger(providerEventLogPath, {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/CodexAdapterV2.ts:1108

      The codexAppServerClientFactoryFromSettingsLayer layer creates its own EventNdjsonLogger for the same providerEventLogPath native stream that other adapter infrastructure layers also create loggers for. Multiple independent RotatingFileSink instances own the same per-thread log files, so concurrent writes and rotations race across separate logger instances, dropping or corrupting protocol log entries.

      This happens because each merged layer calls makeEventNdjsonLogger with the same providerEventLogPath and stream: "native", producing separate RotatingFileSink objects for identical file paths. Consider sharing a single EventNdjsonLogger across all adapters via a common service or layer so only one sink owns each file path.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts around line 1108:
      
      The `codexAppServerClientFactoryFromSettingsLayer` layer creates its own `EventNdjsonLogger` for the same `providerEventLogPath` native stream that other adapter infrastructure layers also create loggers for. Multiple independent `RotatingFileSink` instances own the same per-thread log files, so concurrent writes and rotations race across separate logger instances, dropping or corrupting protocol log entries.
      
      This happens because each merged layer calls `makeEventNdjsonLogger` with the same `providerEventLogPath` and `stream: "native"`, producing separate `RotatingFileSink` objects for identical file paths. Consider sharing a single `EventNdjsonLogger` across all adapters via a common service or layer so only one sink owns each file path.
      @@ -0,0 +94,21 @@
      94+ ? Sources
      95+ : never
      96+ : never;
      97+ readonly sandboxEnabled?: boolean;
      98+ readonly enableAgentRetries?: boolean;
      99+ readonly hasCustomTools?: boolean;
      100+ };
      101+ readonly agents?: ReadonlyArray<string>;
      102+}
      103+
      104+export interface CursorAgentSdkLoggedSendOptions {
      105+ readonly model?: SendOptions["model"];
      106+ readonly mode?: SendOptions["mode"];
      107+ readonly local?: {
      108+ readonly force?: boolean;
      109+ readonly hasCustomTools?: boolean;
      110+ };
      111+ readonly idempotencyKey?: string;
      112+}
      113+
      114+export type CursorAgentSdkProtocolLogEvent =
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High Adapters/CursorAgentSdk.ts:114

      The CursorAgentSdkProtocolLogEvent type writes raw SDK payloads — including the user message, full InteractionUpdate, RunResult, and AgentMessage[] — verbatim into the native NDJSON log via makeCursorAgentSdkProtocolLogger. This persists prompts, assistant replies, tool output, and any secrets in provider traffic to disk, violating the native logging contract that forbids copying payload values into observability logs. The new event variants for run.start, interaction.update, run.completed, and agent.messages should log a redacted or summarized representation instead of the full payload, consistent with the existing native logging contract.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/CursorAgentSdk.ts around line 114:
      
      The `CursorAgentSdkProtocolLogEvent` type writes raw SDK payloads — including the user `message`, full `InteractionUpdate`, `RunResult`, and `AgentMessage[]` — verbatim into the native NDJSON log via `makeCursorAgentSdkProtocolLogger`. This persists prompts, assistant replies, tool output, and any secrets in provider traffic to disk, violating the native logging contract that forbids copying payload values into observability logs. The new event variants for `run.start`, `interaction.update`, `run.completed`, and `agent.messages` should log a redacted or summarized representation instead of the full payload, consistent with the existing native logging contract.
      @@ -0,0 +119,21 @@
      119+ `;
      120+ const expectedSequence = yield* eventStore.latestSequence();
      121+ const schemaVersion = metadata[0]?.schema_version ?? 0;
      122+ const projectionSequence = metadata[0]?.last_sequence ?? 0;
      123+ return {
      124+ valid:
      125+ schemaVersion === ORCHESTRATION_V2_PROJECTION_SCHEMA_VERSION &&
      126+ projectionSequence === expectedSequence &&
      127+ missingThreadIds.length === 0 &&
      128+ unexpectedThreadIds.length === 0 &&
      129+ unreadableThreadIds.length === 0,
      130+ schemaVersion,
      131+ expectedSequence,
      132+ projectionSequence,
      133+ unreadableThreadIds,
      134+ missingThreadIds,
      135+ unexpectedThreadIds,
      136+ } satisfies ProjectionVerificationV2;
      137+ });
      138+
      139+ const rebuild = Effect.gen(function* () {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium orchestration-v2/ProjectionMaintenance.ts:139

      rebuild reads all events into memory before opening its delete-and-replay transaction. If a new orchestration event is committed after that read completes but before/during the transaction, EventSink projects the newer event and then rebuild wipes it out by replaying only the stale prefix it already read. The method ends with projection tables missing the latest committed event and projection_metadata.last_sequence rolled back to an earlier value, leaving runtime data inconsistent until another repair runs. Consider moving readAllEvents inside sql.withTransaction (or otherwise acquiring the event-snapshot and projection-wipe under the same transaction/lock) so concurrent appends cannot interleave.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/ProjectionMaintenance.ts around line 139:
      
      `rebuild` reads all events into memory *before* opening its delete-and-replay transaction. If a new orchestration event is committed after that read completes but before/during the transaction, `EventSink` projects the newer event and then `rebuild` wipes it out by replaying only the stale prefix it already read. The method ends with projection tables missing the latest committed event and `projection_metadata.last_sequence` rolled back to an earlier value, leaving runtime data inconsistent until another repair runs. Consider moving `readAllEvents` inside `sql.withTransaction` (or otherwise acquiring the event-snapshot and projection-wipe under the same transaction/lock) so concurrent appends cannot interleave.
      @@ -0,0 +747,21 @@
      747+ (left, right) =>
      748+ DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt),
      749+ )[0] ?? null;
      750+ return {
      751+ createdBy: projection.thread.createdBy,
      752+ creationSource: projection.thread.creationSource,
      753+ id: projection.thread.id,
      754+ projectId: projection.thread.projectId,
      755+ title: projection.thread.title,
      756+ providerInstanceId: projection.thread.providerInstanceId,
      757+ modelSelection: projection.thread.modelSelection,
      758+ runtimeMode: projection.thread.runtimeMode,
      759+ interactionMode: projection.thread.interactionMode,
      760+ branch: projection.thread.branch,
      761+ worktreePath: projection.thread.worktreePath,
      762+ lineage: projection.thread.lineage,
      763+ forkedFrom: projection.thread.forkedFrom,
      764+ activeProviderThreadId: projection.thread.activeProviderThreadId,
      765+ latestRunId: latestRun?.id ?? null,
      766+ activeRunId: activeRun?.id ?? null,
      767+ status: latestRun?.status ?? "idle",
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium orchestration-v2/ProjectionStore.ts:767

      threadShellFromProjection sets status from latestRun?.status instead of activeRun?.status, so when an older run is still executing and a newer run is queued, the shell reports status: "queued" while activeRunId points at the running run. Consumers that gate UI or actions on status will treat an actively executing thread as merely queued and suppress running-only behavior. Consider deriving status from activeRun instead of latestRun.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/ProjectionStore.ts around line 767:
      
      `threadShellFromProjection` sets `status` from `latestRun?.status` instead of `activeRun?.status`, so when an older run is still executing and a newer run is queued, the shell reports `status: "queued"` while `activeRunId` points at the running run. Consumers that gate UI or actions on `status` will treat an actively executing thread as merely queued and suppress running-only behavior. Consider deriving `status` from `activeRun` instead of `latestRun`.
      @@ -0,0 +1852,21 @@
      1852+ startedAt,
      1853+ completedAt: null,
      1854+ };
      1855+ const turn: ActiveOpenCodeTurn = {
      1856+ isRoot: false,
      1857+ threadId: state.appThread.id,
      1858+ runId: null,
      1859+ rootNodeId,
      1860+ appThread: state.appThread,
      1861+ modelSelection: state.appThread.modelSelection,
      1862+ runtimePolicy: state.parentSubagent.parentTurn.runtimePolicy,
      1863+ providerTurnId,
      1864+ providerTurnOrdinal: providerTurn.ordinal,
      1865+ runOrdinal: state.parentSubagent.parentTurn.runOrdinal,
      1866+ runAttemptId: null,
      1867+ startedAt,
      1868+ itemOrdinals: new Map(),
      1869+ parts: new Map(),
      1870+ partIdsByMessage: new Map(),
      1871+ providerTurn,
      1872+ nextItemOrdinal: 1,
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/OpenCodeAdapterV2.ts:1872

      Every nested subagent turn initializes nextItemOrdinal to 1, so a second turn in the same child thread reuses ordinals 1, 2, etc. ProjectionStore.sortMessagesByTurnItemOrder orders thread messages by the smallest associated turnItem.ordinal, which means a later turn's messages sort ahead of an earlier turn's messages with the same ordinals. The child conversation appears out of order once a child thread has more than one turn.

      The ordinal should continue from where the previous turn in the same child thread left off, rather than resetting to 1 for each turn.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.ts around line 1872:
      
      Every nested subagent turn initializes `nextItemOrdinal` to `1`, so a second turn in the same child thread reuses ordinals `1`, `2`, etc. `ProjectionStore.sortMessagesByTurnItemOrder` orders thread messages by the smallest associated `turnItem.ordinal`, which means a later turn's messages sort ahead of an earlier turn's messages with the same ordinals. The child conversation appears out of order once a child thread has more than one turn.
      
      The ordinal should continue from where the previous turn in the same child thread left off, rather than resetting to `1` for each turn.
      @@ -801,0 +269,21 @@
      269+ case "compaction":
      270+ case "handoff":
      271+ return item.summary ?? null;
      272+ case "fork":
      273+ case "thread_created":
      274+ return item.targetThreadId;
      275+ case "subagent":
      276+ return item.result ?? item.progress ?? item.prompt;
      277+ case "dynamic_tool":
      278+ return null;
      279+ case "proposed_plan":
      280+ return item.markdown || null;
      281+ case "todo_list":
      282+ return `${item.steps.filter((step) => step.status === "completed").length}/${item.steps.length} completed`;
      283+ case "user_message":
      284+ case "assistant_message":
      285+ return item.text || null;
      286+ }
      287+}
      288+
      289+function toFeedActivity(row: OrchestrationV2ProjectedTurnItem): ThreadFeedActivity {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High lib/threadActivity.ts:289

      toFeedActivity eagerly calls JSON.stringify on the entire item for every visible activity row, embedding unbounded payloads (e.g. file_change.diffStr, command_execution.output, proposed_plan.markdown) into fullDetail as a string. A thread with large diffs or tool output allocates a massive serialized string for every row, which can freeze or OOM the mobile UI while building the feed. Consider deferring serialization until the user actually expands a row, or serializing only a bounded preview of item.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/mobile/src/lib/threadActivity.ts around line 289:
      
      `toFeedActivity` eagerly calls `JSON.stringify` on the entire `item` for every visible activity row, embedding unbounded payloads (e.g. `file_change.diffStr`, `command_execution.output`, `proposed_plan.markdown`) into `fullDetail` as a string. A thread with large diffs or tool output allocates a massive serialized string for every row, which can freeze or OOM the mobile UI while building the feed. Consider deferring serialization until the user actually expands a row, or serializing only a bounded preview of `item`.
    8. @@ -0,0 +239,21 @@
      239+
      240+function handleMessage(message: JsonRpcMessage): void {
      241+ if (stopped) return;
      242+ const actual = logicalIncoming(message);
      243+ if (actual === undefined) {
      244+ stopWithFailure("Could not identify outbound ACP frame", message);
      245+ return;
      246+ }
      247+ const entry = transcript.entries[cursor];
      248+ if (entry?.type !== "expect_outbound" || !matchesExpected(entry.frame, actual)) {
      249+ if (actual.kind === "request" && message.id !== undefined && message.id !== null) {
      250+ send({
      251+ jsonrpc: "2.0",
      252+ id: message.id,
      253+ error: { code: -32603, message: "ACP replay frame mismatch" },
      254+ });
      255+ }
      256+ stopWithFailure("Unexpected outbound ACP frame", actual);
      257+ return;
      258+ }
      259+ if (actual.kind === "request" && message.id !== undefined && message.id !== null) {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium scripts/acp-replay-agent.ts:259

      When the client sends two concurrent requests with the same ACP method, pendingClientRequestIds (keyed by actual.method) silently overwrites the first request id on line 260. When the recorded response is later emitted, it replies to the wrong request id, and the first request is never answered. Consider keying pending requests by id instead of method, or tracking multiple outstanding ids per method.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/scripts/acp-replay-agent.ts around line 259:
      
      When the client sends two concurrent requests with the same ACP method, `pendingClientRequestIds` (keyed by `actual.method`) silently overwrites the first request id on line 260. When the recorded response is later emitted, it replies to the wrong request id, and the first request is never answered. Consider keying pending requests by id instead of method, or tracking multiple outstanding ids per method.
      @@ -0,0 +326,21 @@
      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 };
      345+ },
      346+ );
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium project/ProjectService.ts:340

      bootstrap calls getByWorkspaceRoot(input.workspaceRoot) before create(input), and getByWorkspaceRoot normalizes the path via workspacePaths.normalizeWorkspaceRoot without passing createIfMissing. So when input.createWorkspaceRootIfMissing is true and the directory does not yet exist, bootstrap throws a ProjectOperationError instead of creating the workspace and bootstrapping the project — the createWorkspaceRootIfMissing option is never honored.

          function* (input) {
      -      const existing = yield* getByWorkspaceRoot(input.workspaceRoot);
      -      if (Option.isSome(existing)) return { project: existing.value, created: false };
      +      const existing = yield* getByWorkspaceRoot(input.workspaceRoot, {
      +        includeDeleted: true,
      +      }).pipe(
      +        Effect.catchTag("WorkspaceRootNotExistsError", () => Option.none()),
      +      );
      +      if (Option.isSome(existing)) {
      +        if (existing.value.deletedAt !== null) {
      +          return { project: yield* create(input), created: true };
      +        }
      +        return { project: existing.value, created: false };
      +      }
            return { project: yield* create(input), created: true };
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/project/ProjectService.ts around lines 340-346:
      
      `bootstrap` calls `getByWorkspaceRoot(input.workspaceRoot)` before `create(input)`, and `getByWorkspaceRoot` normalizes the path via `workspacePaths.normalizeWorkspaceRoot` without passing `createIfMissing`. So when `input.createWorkspaceRootIfMissing` is `true` and the directory does not yet exist, `bootstrap` throws a `ProjectOperationError` instead of creating the workspace and bootstrapping the project — the `createWorkspaceRootIfMissing` option is never honored.
      @@ -106,15 +99,4 @@
      10699 return emptyDiff;
      107100 }
      108101
      109- const threadContext = yield* projectionSnapshotQuery
      110- .getThreadCheckpointContext(input.threadId)
      111- .pipe(Effect.withSpan("checkpoint.turnDiff.lookupContext"));
      112- if (Option.isNone(threadContext)) {
      113- return yield* new CheckpointThreadNotFoundError({
      114- operation,
      115- threadId: input.threadId,
      116- });
      117- }
      118-
      119- const maxTurnCount = threadContext.value.checkpoints.reduce(
      120- (max, checkpoint) => Math.max(max, checkpoint.checkpointTurnCount),
      102+ const projection = yield* threads.getThreadProjection(input.threadId).pipe(
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium checkpointing/CheckpointDiffQuery.ts:102

      getTurnDiff catches every error from threads.getThreadProjection and replaces it with CheckpointThreadNotFoundError, so a persistence or decode failure is reported to callers as "thread not found" instead of the real error. This hides backend outages and makes diff requests return a misleading result during infrastructure faults. The Effect.mapError at line 103 discards the original error regardless of its type. Consider narrowing the mapping to only the thread-not-found case (or rethrowing non-not-found errors) so genuine failures propagate.

      Also found in 1 other location(s)

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

      getProjectThread maps every orchestrator.getThreadProjection failure to thread_not_found. OrchestratorV2.getThreadProjection wraps both missing-thread and projection-read/setup failures in OrchestratorProjectionError, so a database/read failure will now be reported as &#39;thread not found&#39; instead of surfacing an orchestration error. Calls such as sendToThread, waitForThread, and interruptThread will therefore return the wrong failure reason and can mislead callers into treating transient backend failures as a missing thread.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/checkpointing/CheckpointDiffQuery.ts around line 102:
      
      `getTurnDiff` catches every error from `threads.getThreadProjection` and replaces it with `CheckpointThreadNotFoundError`, so a persistence or decode failure is reported to callers as "thread not found" instead of the real error. This hides backend outages and makes diff requests return a misleading result during infrastructure faults. The `Effect.mapError` at line 103 discards the original error regardless of its type. Consider narrowing the mapping to only the thread-not-found case (or rethrowing non-not-found errors) so genuine failures propagate.
      
      Also found in 1 other location(s):
      - apps/server/src/orchestration-v2/ThreadManagementService.ts:241 -- `getProjectThread` maps every `orchestrator.getThreadProjection` failure to `thread_not_found`. `OrchestratorV2.getThreadProjection` wraps both missing-thread and projection-read/setup failures in `OrchestratorProjectionError`, so a database/read failure will now be reported as 'thread not found' instead of surfacing an orchestration error. Calls such as `sendToThread`, `waitForThread`, and `interruptThread` will therefore return the wrong failure reason and can mislead callers into treating transient backend failures as a missing thread.
      
      @@ -0,0 +15,21 @@
      15+) {}
      16+
      17+export interface TurnItemPositionStoreV2Shape {
      18+ readonly allocate: (input: {
      19+ readonly threadId: ThreadId;
      20+ readonly turnItemId: TurnItemId;
      21+ readonly runId: RunId | null;
      22+ readonly runOrdinal?: number;
      23+ }) => Effect.Effect<number, TurnItemPositionStoreError>;
      24+ readonly normalize: (
      25+ item: OrchestrationV2TurnItem,
      26+ runOrdinal?: number,
      27+ ) => Effect.Effect<OrchestrationV2TurnItem, TurnItemPositionStoreError>;
      28+}
      29+
      30+export class TurnItemPositionStoreV2 extends Context.Service<
      31+ TurnItemPositionStoreV2,
      32+ TurnItemPositionStoreV2Shape
      33+>()("t3/orchestration-v2/TurnItemPositionStore/TurnItemPositionStoreV2") {}
      34+
      35+export const layer: Layer.Layer<TurnItemPositionStoreV2, never, SqlClient.SqlClient> = Layer.effect(
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium orchestration-v2/TurnItemPositionStore.ts:35

      The allocate function can abort the entire event write with an unhandled unique-constraint error when two concurrent calls for different turnItemIds in the same thread compute the same next ordinal. The INSERT ... ON CONFLICT(thread_id, turn_item_id) DO NOTHING only handles conflicts on the (thread_id, turn_item_id) unique constraint, but the table also enforces UNIQUE (thread_id, ordinal). Both transactions read the same MAX(ordinal), both try to insert the same next value, and the second one hits the (thread_id, ordinal) constraint — which is not covered by the ON CONFLICT clause — causing a hard failure instead of retrying or returning an existing position. Consider retrying the allocation on a unique-violation error or using ON CONFLICT(thread_id, ordinal) with an update/do-nothing fallback that re-reads the existing row.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/TurnItemPositionStore.ts around line 35:
      
      The `allocate` function can abort the entire event write with an unhandled unique-constraint error when two concurrent calls for different `turnItemId`s in the same thread compute the same next `ordinal`. The `INSERT ... ON CONFLICT(thread_id, turn_item_id) DO NOTHING` only handles conflicts on the `(thread_id, turn_item_id)` unique constraint, but the table also enforces `UNIQUE (thread_id, ordinal)`. Both transactions read the same `MAX(ordinal)`, both try to insert the same next value, and the second one hits the `(thread_id, ordinal)` constraint — which is not covered by the `ON CONFLICT` clause — causing a hard failure instead of retrying or returning an existing position. Consider retrying the allocation on a unique-violation error or using `ON CONFLICT(thread_id, ordinal)` with an update/do-nothing fallback that re-reads the existing row.
      @@ -0,0 +6,21 @@
      6+ *
      7+ * The original V2 schema used a single `provider` column for both configured
      8+ * instance routing and driver identity. Keep those columns in place for
      9+ * migration compatibility. They remain write-through shadows where the old
      10+ * schema declared them NOT NULL; all V2 reads and indexes use the explicit
      11+ * columns added here.
      12+ */
      13+export default Effect.gen(function* () {
      14+ const sql = yield* SqlClient.SqlClient;
      15+
      16+ yield* sql`ALTER TABLE orchestration_v2_events ADD COLUMN driver TEXT`;
      17+ yield* sql`ALTER TABLE orchestration_v2_events ADD COLUMN provider_instance_id TEXT`;
      18+ yield* sql`
      19+ UPDATE orchestration_v2_events
      20+ SET
      21+ driver = provider,
      22+ provider_instance_id = COALESCE(
      23+ json_extract(payload_json, '$.providerInstanceId'),
      24+ provider
      25+ )
      26+ `;
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Migrations/035_OrchestrationV2Foundation.ts:18

      The migration backfills orchestration_v2_events.driver from the legacy provider column, but that column also held provider instance IDs (e.g. codex_personal) in the pre-split schema. When an upgraded database has custom instance IDs, driver ends up storing an instance ID instead of a valid ProviderDriverKind. Migration 038_ApplicationEventSource later copies this into application-event metadata, and the event decoder expects driver to be a valid ProviderDriverKind, so replaying or loading historical V2 events can fail after upgrade. Consider deriving driver from the JSON payload's driver field (falling back to a normalized default) instead of copying provider verbatim.

        yield* sql`
      -    UPDATE orchestration_v2_events
      -    SET
      -      driver = provider,
      -      provider_instance_id = COALESCE(
      -        json_extract(payload_json, '$.providerInstanceId'),
      -        provider
      -      )
      +    UPDATE orchestration_v2_events
      +    SET
      +      driver = COALESCE(json_extract(payload_json, '$.driver'), provider),
      +      provider_instance_id = COALESCE(
      +        json_extract(payload_json, '$.providerInstanceId'),
      +        provider
      +      )
        `;
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/persistence/Migrations/035_OrchestrationV2Foundation.ts around lines 18-26:
      
      The migration backfills `orchestration_v2_events.driver` from the legacy `provider` column, but that column also held provider instance IDs (e.g. `codex_personal`) in the pre-split schema. When an upgraded database has custom instance IDs, `driver` ends up storing an instance ID instead of a valid `ProviderDriverKind`. Migration `038_ApplicationEventSource` later copies this into application-event metadata, and the event decoder expects `driver` to be a valid `ProviderDriverKind`, so replaying or loading historical V2 events can fail after upgrade. Consider deriving `driver` from the JSON payload's `driver` field (falling back to a normalized default) instead of copying `provider` verbatim.
      @@ -0,0 +409,21 @@
      409+ Effect.gen(function* () {
      410+ const target = yield* getProjectThread(input);
      411+ const explicitRun =
      412+ input.runId === undefined
      413+ ? undefined
      414+ : target.runs.find((candidate) => candidate.id === input.runId);
      415+ if (input.runId !== undefined && explicitRun === undefined) {
      416+ return yield* managementError(
      417+ "run_not_found",
      418+ `Run ${input.runId} does not belong to thread ${input.threadId}.`,
      419+ );
      420+ }
      421+ if (explicitRun !== undefined && isTerminalRunStatus(explicitRun.status)) {
      422+ return {
      423+ type: "already_terminal",
      424+ run: explicitRun as OrchestrationV2Run & {
      425+ readonly status: ThreadManagementTerminalRunStatus;
      426+ },
      427+ } as const;
      428+ }
      429+ const interruptibleRun = latestActiveRun(target);
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium orchestration-v2/ThreadManagementService.ts:429

      interruptThread selects latestActiveRun(target) as the interrupt target, but latestActiveRun includes runs in the waiting status. When the only active run is waiting (e.g. for user approval), the code sends a run.interrupt command that the orchestrator rejects, producing an OrchestratorV2Error instead of a clean no_active_run or thread_not_interruptible result. Consider filtering to only statuses the orchestrator accepts for interruption (preparing, starting, running) instead of reusing latestActiveRun, which covers waiting.

      -      const interruptibleRun = latestActiveRun(target);
      +      const interruptibleRun = target.runs
      +        .filter((run) => run.status === "preparing" || run.status === "starting" || run.status === "running")
      +        .toSorted((left, right) => right.ordinal - left.ordinal)[0];
      Also found in 1 other location(s)

      packages/client-runtime/src/state/threadWorkflows.ts:76

      deriveThreadQueueWorkflowState sets canPromoteToSteer for any non-null activeRun, including &#34;preparing&#34;, &#34;starting&#34;, and &#34;waiting&#34; runs. The server only accepts steering when the active run is &#34;running&#34; and has a running provider turn (latestSteerableRun in ThreadManagementService.ts). On those other states the UI will enable the &#34;Promote to steer&#34; action, but pressing it fails with thread_not_sendable because there is no running turn to steer.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/ThreadManagementService.ts around line 429:
      
      `interruptThread` selects `latestActiveRun(target)` as the interrupt target, but `latestActiveRun` includes runs in the `waiting` status. When the only active run is `waiting` (e.g. for user approval), the code sends a `run.interrupt` command that the orchestrator rejects, producing an `OrchestratorV2Error` instead of a clean `no_active_run` or `thread_not_interruptible` result. Consider filtering to only statuses the orchestrator accepts for interruption (`preparing`, `starting`, `running`) instead of reusing `latestActiveRun`, which covers `waiting`.
      
      Also found in 1 other location(s):
      - packages/client-runtime/src/state/threadWorkflows.ts:76 -- `deriveThreadQueueWorkflowState` sets `canPromoteToSteer` for any non-null `activeRun`, including `"preparing"`, `"starting"`, and `"waiting"` runs. The server only accepts steering when the active run is `"running"` and has a running provider turn (`latestSteerableRun` in `ThreadManagementService.ts`). On those other states the UI will enable the "Promote to steer" action, but pressing it fails with `thread_not_sendable` because there is no running turn to steer.
      
      @@ -0,0 +68,21 @@
      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
      84+ .filter((session) => session.providerInstanceId === current.instanceId)
      85+ .toSorted(
      86+ (left, right) =>
      87+ DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt),
      88+ )[0];
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium orchestration-v2/ProviderSwitchService.ts:83

      When the newest session for the current provider instance is in a terminal stopped or error state, currentSession is set to that dead session. The transition decision then uses the dead session's cwd and capabilities, so the plan can return reuse or restart_and_resume based on a non-reusable session. Meanwhile releaseProviderSessionIds skips terminal sessions, so the actual older live session is never included for release and won't be detached. Filter out stopped and error sessions when selecting currentSession.

      +          const currentSession = projection.providerSessions
      +            .filter(
      +              (session) =>
      +                session.providerInstanceId === current.instanceId &&
      +                session.status !== "stopped" &&
      +                session.status !== "error",
      +            )
      +            .toSorted(
      +              (left, right) =>
      +                DateTime.toEpochMillis(right.updatedAt) - DateTime.toEpochMillis(left.updatedAt),
      +            )[0];
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/ProviderSwitchService.ts around lines 83-88:
      
      When the newest session for the current provider instance is in a terminal `stopped` or `error` state, `currentSession` is set to that dead session. The transition decision then uses the dead session's `cwd` and `capabilities`, so the plan can return `reuse` or `restart_and_resume` based on a non-reusable session. Meanwhile `releaseProviderSessionIds` skips terminal sessions, so the actual older live session is never included for release and won't be detached. Filter out `stopped` and `error` sessions when selecting `currentSession`.
      @@ -0,0 +145,21 @@
      145+ type: "thread.created",
      146+ threadId: input.event.appThread.id,
      147+ payload: input.event.appThread,
      148+ }),
      149+ ];
      150+ case "provider_session.updated":
      151+ return [
      152+ yield* makeDomainEvent(input, {
      153+ type: "provider-session.updated",
      154+ payload: input.event.providerSession,
      155+ }),
      156+ ];
      157+ case "provider_thread.updated":
      158+ return [
      159+ yield* makeDomainEvent(input, {
      160+ type: "provider-thread.updated",
      161+ threadId: input.event.providerThread.appThreadId ?? input.threadId,
      162+ payload: input.event.providerThread,
      163+ }),
      164+ ];
      165+ case "provider_turn.updated":
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium orchestration-v2/ProviderEventIngestor.ts:165

      When a provider_turn.updated event arrives without an explicit threadId, normalize falls back to input.threadId and assigns the provider-turn update to that thread. Since ingestNormalized is always called with the currently running parent thread as input.threadId, a provider-turn update for a child/subagent thread that omits event.threadId is appended to the parent thread's event stream instead of the child's. The child projection loses its provider-turn state and the parent thread is polluted with foreign turn data. Consider deriving the threadId from the provider turn itself rather than falling back to input.threadId.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/ProviderEventIngestor.ts around line 165:
      
      When a `provider_turn.updated` event arrives without an explicit `threadId`, `normalize` falls back to `input.threadId` and assigns the provider-turn update to that thread. Since `ingestNormalized` is always called with the currently running parent thread as `input.threadId`, a provider-turn update for a child/subagent thread that omits `event.threadId` is appended to the parent thread's event stream instead of the child's. The child projection loses its provider-turn state and the parent thread is polluted with foreign turn data. Consider deriving the `threadId` from the provider turn itself rather than falling back to `input.threadId`.
      @@ -0,0 +657,21 @@
      657+ (row) => row.item.threadId !== input.sourceProjection.thread.id || row.item.type === "fork",
      658+ )
      659+ .map((row) => ({
      660+ visibility: "inherited" as const,
      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+ }
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium orchestration-v2/ProjectionStore.ts:666

      visibleTurnItemsThroughRun omits the isOrchestrationV2TurnItemVisible check when building localPrefix, so turn items from rolled-back source runs are inherited into forked child threads as if they were visible. A thread forked after a rollback will show rolled-back history as valid inherited context, even though those items are hidden everywhere else. Add the isOrchestrationV2TurnItemVisible guard to the filter in localPrefix so rolled-back (and other hidden) items are excluded the same way they are when building visible turn items for the source thread itself.

        const localPrefix = inheritedVisibleTurnItemsFromLocalItems(
          input.sourceProjection.turnItems.filter((item) => {
            if (
              isOrchestrationV2SupersededInterrupt({
                item,
                attempts: input.sourceProjection.attempts,
              })
            ) {
              return false;
            }
      +      if (!isOrchestrationV2TurnItemVisible(item)) {
      +        return false;
      +      }
            if (item.runId === null) {
              return false;
            }
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/ProjectionStore.ts around lines 666-677:
      
      `visibleTurnItemsThroughRun` omits the `isOrchestrationV2TurnItemVisible` check when building `localPrefix`, so turn items from rolled-back source runs are inherited into forked child threads as if they were visible. A thread forked after a rollback will show rolled-back history as valid inherited context, even though those items are hidden everywhere else. Add the `isOrchestrationV2TurnItemVisible` guard to the filter in `localPrefix` so rolled-back (and other hidden) items are excluded the same way they are when building visible turn items for the source thread itself.
      @@ -0,0 +50,21 @@
      50+ : { defaultModelSelection: mutation.defaultModelSelection }),
      51+ ...(mutation.scripts === undefined ? {} : { scripts: mutation.scripts }),
      52+ })
      53+ : mutation.type === "project.update"
      54+ ? projects.update({
      55+ commandId: mutation.commandId,
      56+ projectId: mutation.projectId,
      57+ ...(mutation.title === undefined ? {} : { title: mutation.title }),
      58+ ...(mutation.workspaceRoot === undefined
      59+ ? {}
      60+ : { workspaceRoot: mutation.workspaceRoot }),
      61+ ...(mutation.defaultModelSelection === undefined
      62+ ? {}
      63+ : { defaultModelSelection: mutation.defaultModelSelection }),
      64+ ...(mutation.scripts === undefined ? {} : { scripts: mutation.scripts }),
      65+ })
      66+ : projects.delete({
      67+ commandId: mutation.commandId,
      68+ projectId: mutation.projectId,
      69+ });
      70+ return yield* startup
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium project/http.ts:70

      The mutate handler wraps every ProjectService failure in EnvironmentInternalError, so ordinary user errors like a conflict from creating a project on an already-owned workspace, or a not-found from updating/deleting an unknown project, are returned as internal_error instead of EnvironmentRequestInvalidError. HTTP clients cannot distinguish invalid input from a genuine server failure. Consider mapping expected ProjectService error cases to EnvironmentRequestInvalidError before falling back to failEnvironmentInternal.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/project/http.ts around line 70:
      
      The `mutate` handler wraps every `ProjectService` failure in `EnvironmentInternalError`, so ordinary user errors like a conflict from creating a project on an already-owned workspace, or a not-found from updating/deleting an unknown project, are returned as `internal_error` instead of `EnvironmentRequestInvalidError`. HTTP clients cannot distinguish invalid input from a genuine server failure. Consider mapping expected `ProjectService` error cases to `EnvironmentRequestInvalidError` before falling back to `failEnvironmentInternal`.
      @@ -0,0 +28,21 @@
      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<
      40+ OrchestrationEffectExecutorV2,
      41+ never,
      42+ | ProviderSessionManagerV2
      43+ | RunFinalizationService
      44+ | CheckpointRollbackServiceV2
      45+ | ProviderTurnControlServiceV2
      46+ | ProviderTurnStartServiceV2
      47+ | RuntimeRequestServiceV2
      48+> = Layer.effect(
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium orchestration-v2/EffectWorker.ts:39

      executorLayer declares its required environment without ResourceCleanupService, but the layer body does yield* ResourceCleanupService and uses it to handle terminal.cleanup and attachment.cleanup effects. Because ResourceCleanupService is a Context.Reference with a no-op default, the layer can build successfully without a real cleanup service, so terminal.cleanup and attachment.cleanup effects silently succeed without deleting anything. Add ResourceCleanupService to the Layer.Layer type parameter's union so the compiler enforces providing a real implementation.

      Suggested change
      39-export const executorLayer: Layer.Layer<
      40- OrchestrationEffectExecutorV2,
      41- never,
      42- | ProviderSessionManagerV2
      43- | RunFinalizationService
      44- | CheckpointRollbackServiceV2
      45- | ProviderTurnControlServiceV2
      46- | ProviderTurnStartServiceV2
      47- | RuntimeRequestServiceV2
      48-> = Layer.effect(
      39+export const executorLayer: Layer.Layer<
      40+ OrchestrationEffectExecutorV2,
      41+ never,
      42+ | ProviderSessionManagerV2
      43+ | RunFinalizationService
      44+ | CheckpointRollbackServiceV2
      45+ | ProviderTurnControlServiceV2
      46+ | ProviderTurnStartServiceV2
      47+ | RuntimeRequestServiceV2
      48+ | ResourceCleanupService
      49+> = Layer.effect(
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/EffectWorker.ts around lines 39-48:
      
      `executorLayer` declares its required environment without `ResourceCleanupService`, but the layer body does `yield* ResourceCleanupService` and uses it to handle `terminal.cleanup` and `attachment.cleanup` effects. Because `ResourceCleanupService` is a `Context.Reference` with a no-op default, the layer can build successfully without a real cleanup service, so `terminal.cleanup` and `attachment.cleanup` effects silently succeed without deleting anything. Add `ResourceCleanupService` to the `Layer.Layer` type parameter's union so the compiler enforces providing a real implementation.
      @@ -0,0 +442,21 @@
      442+ text: step.text,
      443+ ...(step.attachments === undefined ? {} : { attachments: step.attachments }),
      444+ }),
      445+ shouldRunInBackground ? { await: false, key } : undefined,
      446+ );
      447+ if (shouldRunInBackground) {
      448+ activeRunDispatchKeys.add(key);
      449+ } else if (
      450+ !(
      451+ nextStep !== undefined &&
      452+ (nextStep.type === "steer" || nextStep.type === "restart") &&
      453+ nextStep.targetRunIndex === messageIndex
      454+ )
      455+ ) {
      456+ steps.push({ type: "await_thread_idle", threadId: ids.threadId });
      457+ }
      458+ }
      459+ break;
      460+ case "queue_message":
      461+ messageIndex += 1;
      462+ pushDispatch(
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium fixtures/shared.ts:462

      The queue_message branch calls dispatchMessageCommand without setting dispatchMode, so it defaults to start_immediately instead of { type: "queue_after_active" }. A queue_message step that should produce a queued turn is dispatched as a normal immediate message, causing the wrong run.status and inputIntent and invalidating queued-turn replay coverage. Consider passing dispatchMode: { type: "queue_after_active" } in the queue_message branch.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/testkit/fixtures/shared.ts around line 462:
      
      The `queue_message` branch calls `dispatchMessageCommand` without setting `dispatchMode`, so it defaults to `start_immediately` instead of `{ type: "queue_after_active" }`. A `queue_message` step that should produce a queued turn is dispatched as a normal immediate message, causing the wrong `run.status` and `inputIntent` and invalidating queued-turn replay coverage. Consider passing `dispatchMode: { type: "queue_after_active" }` in the `queue_message` branch.
      @@ -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 waits for terminalization using a fixed 1000-iteration loop of setImmediate yields. setImmediate only advances the Node event loop by one tick — it is not a real-time delay — so the entire budget can elapse in milliseconds. If projection ingestion of the provider terminal event takes longer than 1000 event-loop turns, the method fails spuriously with Provider turn ... did not terminalize before restart even though the turn would settle shortly after. Consider replacing the fixed tick budget with a time-based timeout that sleeps between checks, so the wait duration reflects wall-clock time rather than event-loop turn count.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/ProviderTurnControlService.ts around line 173:
      
      `interruptAndAwaitTerminal` waits for terminalization using a fixed 1000-iteration loop of `setImmediate` yields. `setImmediate` only advances the Node event loop by one tick — it is not a real-time delay — so the entire budget can elapse in milliseconds. If projection ingestion of the provider terminal event takes longer than 1000 event-loop turns, the method fails spuriously with `Provider turn ... did not terminalize before restart` even though the turn would settle shortly after. Consider replacing the fixed tick budget with a time-based timeout that sleeps between checks, so the wait duration reflects wall-clock time rather than event-loop turn count.
      @@ -0,0 +38,21 @@
      38+ RuntimeRequestServiceV2Shape
      39+>()("t3/orchestration-v2/RuntimeRequestService/RuntimeRequestServiceV2") {}
      40+
      41+export const layer: Layer.Layer<
      42+ RuntimeRequestServiceV2,
      43+ never,
      44+ ProjectionStoreV2 | ProviderSessionManagerV2
      45+> = Layer.effect(
      46+ RuntimeRequestServiceV2,
      47+ Effect.gen(function* () {
      48+ const projections = yield* ProjectionStoreV2;
      49+ const sessions = yield* ProviderSessionManagerV2;
      50+
      51+ return RuntimeRequestServiceV2.of({
      52+ respond: (input) =>
      53+ Effect.gen(function* () {
      54+ const projection = yield* projections.getThreadProjection(input.threadId);
      55+ const request = projection.runtimeRequests.find(
      56+ (candidate) => candidate.id === input.requestId,
      57+ );
      58+ if (request === undefined) {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High orchestration-v2/RuntimeRequestService.ts:58

      The respond function allows duplicate responses for an already-resolved runtime request. projection.runtimeRequests retains resolved requests, so a second call with the same requestId passes the existence and session guards and forwards another respondToRuntimeRequest call to the provider, causing duplicate approvals or answers. The missing check is a request.status === "pending" (or equivalent) guard before calling session.value.respondToRuntimeRequest.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/RuntimeRequestService.ts around line 58:
      
      The `respond` function allows duplicate responses for an already-resolved runtime request. `projection.runtimeRequests` retains resolved requests, so a second call with the same `requestId` passes the existence and session guards and forwards another `respondToRuntimeRequest` call to the provider, causing duplicate approvals or answers. The missing check is a `request.status === "pending"` (or equivalent) guard before calling `session.value.respondToRuntimeRequest`.
      @@ -0,0 +168,21 @@
      168+ if (Option.isNone(row) || (row.value.deletedAt !== null && !options?.includeDeleted)) {
      169+ return Option.none();
      170+ }
      171+ return Option.some(yield* hydrateAvailable(row.value));
      172+ },
      173+ );
      174+
      175+ const getByWorkspaceRoot: ProjectService["Service"]["getByWorkspaceRoot"] = Effect.fn(
      176+ "ProjectService.getByWorkspaceRoot",
      177+ )(function* (workspaceRoot, options) {
      178+ const normalized = yield* workspacePaths.normalizeWorkspaceRoot(workspaceRoot).pipe(
      179+ Effect.mapError(
      180+ (cause) =>
      181+ new ProjectOperationError({
      182+ operation: "normalize-workspace",
      183+ workspaceRoot,
      184+ cause,
      185+ }),
      186+ ),
      187+ );
      188+ const row = (yield* readRows()).find(
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium project/ProjectService.ts:188

      getByWorkspaceRoot scans rows in oldest-first order and returns the first row whose workspaceRoot matches. When includeDeleted is true and a workspace was soft-deleted then reused by a newer active project, the method returns the older deleted project instead of the current active one. The .find() predicate does not prefer non-deleted rows, so callers get stale project data. Consider selecting the non-deleted row when one exists, or sorting by recency before the search.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/project/ProjectService.ts around line 188:
      
      `getByWorkspaceRoot` scans rows in oldest-first order and returns the first row whose `workspaceRoot` matches. When `includeDeleted` is `true` and a workspace was soft-deleted then reused by a newer active project, the method returns the older deleted project instead of the current active one. The `.find()` predicate does not prefer non-deleted rows, so callers get stale project data. Consider selecting the non-deleted row when one exists, or sorting by recency before the search.
    9. @@ -1099,16 +328,8 @@
      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: {
      335+ version: null,
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Layers/CursorProvider.ts:335

      checkCursorProviderStatus hard-codes version: null in the success path, so every healthy Cursor snapshot reports no installed version even when the SDK probe succeeds. Downstream consumers that read provider.version or versionAdvisory (e.g. settings UI and update/maintenance handling) can never surface a version or version-advisory state for Cursor providers. Consider populating version from the catalog or probe result instead of null.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Layers/CursorProvider.ts around line 335:
      
      `checkCursorProviderStatus` hard-codes `version: null` in the success path, so every healthy Cursor snapshot reports no installed version even when the SDK probe succeeds. Downstream consumers that read `provider.version` or `versionAdvisory` (e.g. settings UI and update/maintenance handling) can never surface a version or version-advisory state for Cursor providers. Consider populating `version` from the catalog or probe result instead of `null`.
      @@ -0,0 +93,21 @@
      93+ });
      94+ const checkedAt = DateTime.formatIso(yield* DateTime.now);
      95+ const orchestrationAdapter = yield* AcpRegistryAdapterV2Driver.create({
      96+ instanceId,
      97+ displayName,
      98+ accentColor,
      99+ environment,
      100+ enabled,
      101+ config,
      102+ }).pipe(
      103+ Effect.mapError(
      104+ (cause) =>
      105+ new ProviderDriverError({
      106+ driver: DRIVER_KIND,
      107+ instanceId,
      108+ detail: "Failed to build ACP Registry orchestration adapter.",
      109+ cause,
      110+ }),
      111+ ),
      112+ );
      113+ const currentSnapshot = () =>
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Drivers/AcpRegistryDriver.ts:113

      makeSnapshot copies the checkedAt timestamp captured at instance creation into every later snapshot.refresh() and snapshot.getSnapshot() call, so refreshes always report the original creation time instead of when the refresh actually ran. This makes the provider appear permanently stale — downstream cache/UI code cannot tell that a fresh check completed. Consider generating the timestamp inside currentSnapshot (e.g. via DateTime.formatIso(yield* DateTime.now)) so each refresh produces an up-to-date checkedAt.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Drivers/AcpRegistryDriver.ts around line 113:
      
      `makeSnapshot` copies the `checkedAt` timestamp captured at instance creation into every later `snapshot.refresh()` and `snapshot.getSnapshot()` call, so refreshes always report the original creation time instead of when the refresh actually ran. This makes the provider appear permanently stale — downstream cache/UI code cannot tell that a fresh check completed. Consider generating the timestamp inside `currentSnapshot` (e.g. via `DateTime.formatIso(yield* DateTime.now)`) so each refresh produces an up-to-date `checkedAt`.
      @@ -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

      A thread whose only pending runtime request is auth_refresh is incorrectly published with phase waiting_for_approval, because the fallback at line 90 treats every non-user_input pendingRuntimeRequest the same way. This marks the thread as interruptive in the relay with the headline "Approval needed" even though no user approval is actually pending. Consider checking for auth_refresh explicitly and excluding it from the waiting_for_approval branch, so such threads resolve via thread.status instead.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @packages/shared/src/agentAwareness.ts around line 90:
      
      A thread whose only pending runtime request is `auth_refresh` is incorrectly published with phase `waiting_for_approval`, because the fallback at line 90 treats every non-`user_input` `pendingRuntimeRequest` the same way. This marks the thread as interruptive in the relay with the headline "Approval needed" even though no user approval is actually pending. Consider checking for `auth_refresh` explicitly and excluding it from the `waiting_for_approval` branch, so such threads resolve via `thread.status` instead.
      @@ -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

      When serverConfig.autoBootstrapProjectFromCwd is enabled, a failure in resolveAutoBootstrapWelcomeTargets (e.g. projects.bootstrap(...), threads.getShellSnapshot(), or threadLaunch.launch(...)) now aborts the entire startup effect and calls commandGate.failCommandReady(...), preventing the server from ever reaching command readiness. Previously this bootstrap work was best-effort and failures were logged but did not block startup. Consider wrapping the autoBootstrap effect with Effect.catch so bootstrap failures degrade gracefully instead of failing the whole startup.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/serverRuntimeStartup.ts around line 438:
      
      When `serverConfig.autoBootstrapProjectFromCwd` is enabled, a failure in `resolveAutoBootstrapWelcomeTargets` (e.g. `projects.bootstrap(...)`, `threads.getShellSnapshot()`, or `threadLaunch.launch(...)`) now aborts the entire `startup` effect and calls `commandGate.failCommandReady(...)`, preventing the server from ever reaching command readiness. Previously this bootstrap work was best-effort and failures were logged but did not block startup. Consider wrapping the `autoBootstrap` effect with `Effect.catch` so bootstrap failures degrade gracefully instead of failing the whole startup.
      @@ -187,0 +427,21 @@
      427+ type: "root" as const,
      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+ },
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High operations/commands.ts:447

      startThreadTurn silently drops input.bootstrap.runSetupScript when launching via ORCHESTRATION_V2_WS_METHODS.launchThread. The launchThread request object built around line 432 never includes the runSetupScript flag, so the server never receives it and setup scripts stop running on first-message launches. Consider forwarding input.bootstrap.runSetupScript in the launchThread payload.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @packages/client-runtime/src/operations/commands.ts around line 447:
      
      `startThreadTurn` silently drops `input.bootstrap.runSetupScript` when launching via `ORCHESTRATION_V2_WS_METHODS.launchThread`. The `launchThread` request object built around line 432 never includes the `runSetupScript` flag, so the server never receives it and setup scripts stop running on first-message launches. Consider forwarding `input.bootstrap.runSetupScript` in the `launchThread` payload.
      @@ -0,0 +1,17 @@
      1+import { errorTag } from "@t3tools/shared/observability";
      2+
      3+export function structuralProtocolMethod(value: string): string {
      4+ return value.length <= 128 && /^[A-Za-z][A-Za-z0-9._:/-]*$/.test(value) ? value : "unknown";
      5+}
      6+
      7+/**
      8+ * Retain only bounded structural metadata for native protocol diagnostics.
      9+ * Provider payload values may contain prompts, credentials, or arbitrarily
      10+ * large tool output and must never be copied into the observability stream.
      11+ */
      12+export function summarizeNativeProtocolPayload(
      13+ payload: unknown,
      14+): Readonly<Record<string, unknown>> {
      15+ if (payload === null) return { valueType: "null" };
      16+ if (typeof payload === "string") {
      17+ return { valueType: "string", byteLength: new TextEncoder().encode(payload).byteLength };
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium provider/NativeProtocolLogging.ts:17

      summarizeNativeProtocolPayload calls new TextEncoder().encode(payload).byteLength on the full string. encode() allocates a Uint8Array containing the entire UTF-8 representation before .byteLength is read, so every large protocol string is fully duplicated in memory just to compute a length. Because the logger is fed arbitrary assistant/tool output, a sufficiently large string can spike memory and crash the Node process while producing the summary. Use Buffer.byteLength(payload) (which computes the UTF-8 byte length without allocating a full buffer) instead.

      Suggested change
      17- return { valueType: "string", byteLength: new TextEncoder().encode(payload).byteLength };
      17+ return { valueType: "string", byteLength: Buffer.byteLength(payload) };
      Also found in 1 other location(s)

      apps/mobile/src/lib/threadActivity.ts:293

      toFeedActivity now eagerly JSON.stringifys the entire item into fullDetail for every visible activity. Many OrchestrationV2TurnItem variants carry unbounded payloads such as file_change.diffStr/oldStr/newStr, command_execution.output, and proposed_plan.markdown, so opening a thread with large diffs or tool output will allocate huge duplicate strings for every row and can freeze or OOM the mobile UI while building the feed.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/NativeProtocolLogging.ts around line 17:
      
      `summarizeNativeProtocolPayload` calls `new TextEncoder().encode(payload).byteLength` on the full string. `encode()` allocates a `Uint8Array` containing the entire UTF-8 representation before `.byteLength` is read, so every large protocol string is fully duplicated in memory just to compute a length. Because the logger is fed arbitrary assistant/tool output, a sufficiently large string can spike memory and crash the Node process while producing the summary. Use `Buffer.byteLength(payload)` (which computes the UTF-8 byte length without allocating a full buffer) instead.
      
      Also found in 1 other location(s):
      - apps/mobile/src/lib/threadActivity.ts:293 -- `toFeedActivity` now eagerly `JSON.stringify`s the entire `item` into `fullDetail` for every visible activity. Many `OrchestrationV2TurnItem` variants carry unbounded payloads such as `file_change.diffStr`/`oldStr`/`newStr`, `command_execution.output`, and `proposed_plan.markdown`, so opening a thread with large diffs or tool output will allocate huge duplicate strings for every row and can freeze or OOM the mobile UI while building the feed.
      
      @@ -136,3 +149,17 @@
      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+ },
      160+ }),
      161+ mergeBack: createEnvironmentCommand(runtime, {
      162+ label: "environment-data:commands:thread:merge-back",
      163+ execute: (input: MergeThreadBackInput) => mergeThreadBack(input),
      164+ scheduler,
      165+ concurrency: {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium state/threadCommands.ts:165

      mergeBack serializes on [environmentId, input.sourceThreadId, input.targetThreadId], so it does not share a scheduler lane with the ordinary per-thread commands keyed by [environmentId, input.threadId]. A thread.merge_back can therefore run concurrently with delete, archive, updateMetadata, startTurn, and the rest on either the source or target thread. Since merge-back mutates both threads, running it alongside another command for either thread can interleave mutations and produce inconsistent merge results or failures against stale/deleted thread state. Consider keying mergeBack on the source thread id (and/or the target thread id) so it shares the lane with the other per-thread commands, or document why concurrent execution with those commands is safe.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @packages/client-runtime/src/state/threadCommands.ts around line 165:
      
      `mergeBack` serializes on `[environmentId, input.sourceThreadId, input.targetThreadId]`, so it does not share a scheduler lane with the ordinary per-thread commands keyed by `[environmentId, input.threadId]`. A `thread.merge_back` can therefore run concurrently with `delete`, `archive`, `updateMetadata`, `startTurn`, and the rest on either the source or target thread. Since merge-back mutates both threads, running it alongside another command for either thread can interleave mutations and produce inconsistent merge results or failures against stale/deleted thread state. Consider keying `mergeBack` on the source thread id (and/or the target thread id) so it shares the lane with the other per-thread commands, or document why concurrent execution with those commands is safe.
      @@ -0,0 +209,21 @@
      209+function taskToDraft(task: ScheduledTask): DraftState {
      210+ const schedule = task.schedule;
      211+ const weekdays =
      212+ schedule.type === "fixed_time" && schedule.weekdays && schedule.weekdays.length > 0
      213+ ? new Set(schedule.weekdays)
      214+ : new Set(ALL_WEEKDAYS);
      215+ return {
      216+ editingId: task.id,
      217+ title: task.title,
      218+ prompt: task.prompt,
      219+ enabled: task.enabled,
      220+ scheduleMode: schedule.type === "interval" ? "interval" : "fixed",
      221+ intervalMinutes:
      222+ schedule.type === "interval"
      223+ ? String(Math.max(1, Math.round(schedule.everyMs / 60_000)))
      224+ : "15",
      225+ timeOfDay: schedule.type === "fixed_time" ? schedule.timeOfDay : "09:00",
      226+ weekdays,
      227+ projectId: task.projectId,
      228+ threadId: task.threadId ?? "",
      229+ workspaceMode: task.workspaceStrategy.type,
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium settings/ScheduledTasksSettings.tsx:229

      Editing an existing worktree scheduled task silently overwrites a custom startFromOrigin: false setting. taskToDraft does not capture task.workspaceStrategy.startFromOrigin, and the submit path always hardcodes startFromOrigin: true when reconstructing the worktree strategy. A task intentionally based on the local checkout instead of origin/<baseRef> changes behavior after a no-op edit. Consider preserving startFromOrigin in DraftState and using it in the reconstructed strategy.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/web/src/components/settings/ScheduledTasksSettings.tsx around line 229:
      
      Editing an existing `worktree` scheduled task silently overwrites a custom `startFromOrigin: false` setting. `taskToDraft` does not capture `task.workspaceStrategy.startFromOrigin`, and the submit path always hardcodes `startFromOrigin: true` when reconstructing the worktree strategy. A task intentionally based on the local checkout instead of `origin/<baseRef>` changes behavior after a no-op edit. Consider preserving `startFromOrigin` in `DraftState` and using it in the reconstructed strategy.
      @@ -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 never creates a turn-fold for any run that has a run_interrupt_request or run_interrupt_result event. Lines 320–329 collect every interrupted runId, and line 383 skips all of them unconditionally — not just the latest one. As a result, old interrupted runs never collapse and stay permanently expanded in the timeline.

      The interrupt check should only suppress folding for the latest run (matching isLatestInterruptedTurn below), not for every run that was ever interrupted. Consider gating the skip on input.latestRun?.runId === runId.

      -    if (runId === input.unsettledRunId || interruptedRunIds.has(runId)) {
      +    if (runId === input.unsettledRunId || (input.latestRun?.runId === runId && interruptedRunIds.has(runId))) {
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/web/src/components/chat/MessagesTimeline.logic.ts around line 383:
      
      `deriveTurnFolds` never creates a turn-fold for any run that has a `run_interrupt_request` or `run_interrupt_result` event. Lines 320–329 collect every interrupted `runId`, and line 383 skips all of them unconditionally — not just the latest one. As a result, old interrupted runs never collapse and stay permanently expanded in the timeline.
      
      The interrupt check should only suppress folding for the *latest* run (matching `isLatestInterruptedTurn` below), not for every run that was ever interrupted. Consider gating the skip on `input.latestRun?.runId === runId`.
      @@ -0,0 +107,21 @@
      107+ const relationshipRows = immediateThreadRelationships(graph, props.threadId).toSorted(
      108+ (left, right) =>
      109+ relationshipSortKey({
      110+ edge: left.edge,
      111+ threadId: left.threadId,
      112+ currentThreadId: props.threadId,
      113+ mergeTargetThreadId,
      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+ }
      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 panel — including the "Disconnect agent session" menu — even when canDetach is true. A thread with an active provider session but no fork/subagent/transfer edges has zero relationship rows, so the user can never reach the disconnect action from the thread details UI. Consider rendering the panel whenever canDetach is true regardless of relationshipRows.length, instead of short-circuiting to null.

      -  if (relationshipRows.length === 0) {
      +  if (relationshipRows.length === 0 && !canDetach) {
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/web/src/components/chat/ThreadRelationshipsControl.tsx around lines 125-127:
      
      `ThreadRelationshipsPanel` returns `null` when `relationshipRows.length === 0`, which hides the entire panel — including the "Disconnect agent session" menu — even when `canDetach` is `true`. A thread with an active provider session but no fork/subagent/transfer edges has zero relationship rows, so the user can never reach the disconnect action from the thread details UI. Consider rendering the panel whenever `canDetach` is `true` regardless of `relationshipRows.length`, instead of short-circuiting to `null`.
      @@ -32,4 +35,4 @@
      3235 draftThread: DraftThreadState,
      3336 fallbackModelSelection: ModelSelection,
      3437 ): Thread {
      35- return {
      38+ const timestamp = DateTime.makeUnsafe(draftThread.createdAt);
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium components/ChatView.logic.ts:38

      buildLocalDraftThread parses draftThread.createdAt with DateTime.makeUnsafe, which throws on invalid date strings. Persisted draft sessions are rehydrated from composerDraftStore with any non-empty createdAt preserved as-is, so a malformed value in local storage will crash draft-thread rendering instead of falling back to a usable draft. Opening the affected draft becomes impossible until storage is cleared. Consider wrapping the parse in a try/catch (or validating the date) and falling back to the current time on failure.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/web/src/components/ChatView.logic.ts around line 38:
      
      `buildLocalDraftThread` parses `draftThread.createdAt` with `DateTime.makeUnsafe`, which throws on invalid date strings. Persisted draft sessions are rehydrated from `composerDraftStore` with any non-empty `createdAt` preserved as-is, so a malformed value in local storage will crash draft-thread rendering instead of falling back to a usable draft. Opening the affected draft becomes impossible until storage is cleared. Consider wrapping the parse in a try/catch (or validating the date) and falling back to the current time on failure.
      @@ -0,0 +38,21 @@
      38+
      39+/** Joins pending request entities to the request items that carry display data. */
      40+export function derivePendingThreadRequests(
      41+ projection: OrchestrationV2ThreadProjection,
      42+): PendingThreadRequests {
      43+ const approvals: ThreadPendingApproval[] = [];
      44+ const userInputs: ThreadPendingUserInput[] = [];
      45+
      46+ for (const request of projection.runtimeRequests) {
      47+ if (request.status !== "pending") continue;
      48+ const responseCapability = request.responseCapability.type;
      49+ if (request.kind === "user_input") {
      50+ const item = projection.turnItems.findLast(
      51+ (candidate) =>
      52+ candidate.type === "user_input_request" && candidate.requestId === request.id,
      53+ );
      54+ if (item === undefined || item.type !== "user_input_request") continue;
      55+ userInputs.push({
      56+ requestId: request.id,
      57+ createdAt: DateTime.formatIso(request.createdAt),
      58+ questions: item.questions.map((question) => ({ ...question, multiSelect: false })),
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium state/threadRequests.ts:58

      derivePendingThreadRequests overwrites every user_input_request question with multiSelect: false, so any pending prompt that actually allows multiple selections is presented to clients as single-select. The UI will only let the user choose one option and will submit the wrong answer shape for multi-select requests. Consider preserving question.multiSelect instead of hardcoding false.

      Suggested change
      58- questions: item.questions.map((question) => ({ ...question, multiSelect: false })),
      58+ questions: item.questions.map((question) => ({ ...question })),
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @packages/client-runtime/src/state/threadRequests.ts around line 58:
      
      `derivePendingThreadRequests` overwrites every `user_input_request` question with `multiSelect: false`, so any pending prompt that actually allows multiple selections is presented to clients as single-select. The UI will only let the user choose one option and will submit the wrong answer shape for multi-select requests. Consider preserving `question.multiSelect` instead of hardcoding `false`.
      @@ -495,9 +225,13 @@
      225+ return [...inputs].toSorted((left, right) => left.createdAt.localeCompare(right.createdAt));
      226+}
      495227
      496- if (
      497- activity.kind === "provider.user-input.respond.failed" &&
      498- requestId &&
      499- isStalePendingRequestFailureDetail(detail)
      500- ) {
      501- openByRequestId.delete(requestId);
      502- }
      503- }
      228+export function deriveActivePlanState(
      229+ projection: OrchestrationV2ThreadProjection | null,
      230+ latestRunId: RunId | undefined,
      231+): ActivePlanState | null {
      232+ if (projection === null) return null;
      233+ const plans = projection.plans.filter((plan) => plan.kind === "todo_list");
      234+ const plan =
      235+ [...plans].toReversed().find((candidate) => candidate.runId === latestRunId) ??
      236+ plans.at(-1) ??
      237+ null;
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium src/session-logic.ts:233

      deriveActivePlanState returns the last-inserted todo_list plan instead of the most recently updated one when no plan matches latestRunId. When an older plan is updated after a newer plan is created, plans.at(-1) still yields the newer (untouched) plan, so the Tasks panel can display stale steps/explanation for the wrong active plan. Consider sorting candidates by planItemTime(projection, plan.id) (descending) so the most recently updated plan is selected.

        const plans = projection.plans.filter((plan) => plan.kind === "todo_list");
      -  const plan =
      -    [...plans].toReversed().find((candidate) => candidate.runId === latestRunId) ??
      -    plans.at(-1) ??
      -    null;
      +  const byRecency = [...plans].toSorted(
      +    (left, right) =>
      +      planItemTime(projection, left.id).localeCompare(planItemTime(projection, right.id)) ||
      +      left.id.localeCompare(right.id),
      +  );
      +  const plan =
      +    [...byRecency].toReversed().find((candidate) => candidate.runId === latestRunId) ??
      +    byRecency.at(-1) ??
      +    null;
      Also found in 2 other location(s)

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

      threadDetailToShell selects pendingRuntimeRequest with projection.runtimeRequests.find(...), which returns the first pending request in array order instead of the newest one. If a thread has multiple pending requests, an older stale request can win over the current one, causing presentThreadShell to derive the wrong pending state (hasPendingApprovals vs hasPendingUserInput) and show the wrong thread status until the shell list materializes.

      apps/server/src/project/ProjectService.ts:188

      getByWorkspaceRoot scans readRows() in creation order and uses .find(...) even when options?.includeDeleted === true. If a project is soft-deleted and a new active project is later created for the same workspaceRoot, this method returns the older deleted row instead of the current active project, because listAll() is documented to return oldest-first. Callers asking for a workspace lookup with deleted rows included will get stale project data.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/web/src/session-logic.ts around lines 233-237:
      
      `deriveActivePlanState` returns the last-inserted `todo_list` plan instead of the most recently updated one when no plan matches `latestRunId`. When an older plan is updated after a newer plan is created, `plans.at(-1)` still yields the newer (untouched) plan, so the Tasks panel can display stale steps/explanation for the wrong active plan. Consider sorting candidates by `planItemTime(projection, plan.id)` (descending) so the most recently updated plan is selected.
      
      Also found in 2 other location(s):
      - apps/mobile/src/state/use-thread-selection.ts:71 -- `threadDetailToShell` selects `pendingRuntimeRequest` with `projection.runtimeRequests.find(...)`, which returns the first pending request in array order instead of the newest one. If a thread has multiple pending requests, an older stale request can win over the current one, causing `presentThreadShell` to derive the wrong pending state (`hasPendingApprovals` vs `hasPendingUserInput`) and show the wrong thread status until the shell list materializes.
      - apps/server/src/project/ProjectService.ts:188 -- `getByWorkspaceRoot` scans `readRows()` in creation order and uses `.find(...)` even when `options?.includeDeleted === true`. If a project is soft-deleted and a new active project is later created for the same `workspaceRoot`, this method returns the older deleted row instead of the current active project, because `listAll()` is documented to return oldest-first. Callers asking for a workspace lookup with deleted rows included will get stale project data.
      
      @@ -0,0 +77,21 @@
      77+ if (
      78+ previous.visibility === next.visibility &&
      79+ previous.sourceThreadId === next.sourceThreadId &&
      80+ previous.sourceItemId === next.sourceItemId &&
      81+ previous.item === item
      82+ ) {
      83+ return rows;
      84+ }
      85+ const updated = [...rows];
      86+ updated[index] = next;
      87+ return updated;
      88+}
      89+
      90+/** Applies one committed event to a matching thread projection. */
      91+export function applyOrchestrationV2ProjectionEvent(
      92+ projection: OrchestrationV2ThreadProjection | null,
      93+ event: OrchestrationV2DomainEvent,
      94+): OrchestrationV2ThreadProjection | null {
      95+ if (projection === null || event.threadId !== projection.thread.id) return projection;
      96+
      97+ const base = { ...projection, updatedAt: event.occurredAt };
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium state/orchestrationV2Projection.ts:97

      Every non-thread.* event updates projection.updatedAt but leaves projection.thread.updatedAt stale, so callers like use-thread-selection.ts that sort thread shells by thread.updatedAt show an old timestamp even after incremental run.*, turn-item.updated, etc. events have updated the projection. The case "thread.*" branch replaces thread wholesale with event.payload, but all other branches only update projection.updatedAt via base and never propagate event.occurredAt to thread.updatedAt. Consider updating thread.updatedAt in base (e.g. by spreading event.occurredAt into the thread) so the thread shell timestamp tracks projection activity.

      Suggested change
      97- const base = { ...projection, updatedAt: event.occurredAt };
      97+ const base = { ...projection, updatedAt: event.occurredAt, thread: { ...projection.thread, updatedAt: event.occurredAt } };
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @packages/client-runtime/src/state/orchestrationV2Projection.ts around line 97:
      
      Every non-`thread.*` event updates `projection.updatedAt` but leaves `projection.thread.updatedAt` stale, so callers like `use-thread-selection.ts` that sort thread shells by `thread.updatedAt` show an old timestamp even after incremental `run.*`, `turn-item.updated`, etc. events have updated the projection. The `case "thread.*"` branch replaces `thread` wholesale with `event.payload`, but all other branches only update `projection.updatedAt` via `base` and never propagate `event.occurredAt` to `thread.updatedAt`. Consider updating `thread.updatedAt` in `base` (e.g. by spreading `event.occurredAt` into the thread) so the thread shell timestamp tracks projection activity.
    10. @@ -0,0 +8,21 @@
      8+
      9+export function useOpenFavoriteEditorShortcut({
      10+ enabled,
      11+ environmentId,
      12+ keybindings,
      13+ availableEditors,
      14+ openInCwd,
      15+}: {
      16+ enabled: boolean;
      17+ environmentId: EnvironmentId;
      18+ keybindings: ResolvedKeybindingsConfig;
      19+ availableEditors: ReadonlyArray<EditorId>;
      20+ openInCwd: string | null;
      21+}) {
      22+ const openInEditorMutation = useAtomCommand(shellEnvironment.openInEditor, "open in editor");
      23+ const [preferredEditor] = usePreferredEditor(availableEditors);
      24+
      25+ useEffect(() => {
      26+ if (!enabled) return;
      27+ const handler = (event: globalThis.KeyboardEvent) => {
      28+ if (!isOpenFavoriteEditorShortcut(event, keybindings)) return;
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium chat/OpenInPickerShortcut.ts:28

      isOpenFavoriteEditorShortcut is called without passing the current shortcut context (e.g., terminalFocus, previewFocus), so when clauses on editor.openFavorite bindings are evaluated against stale defaults. A user keybinding like editor.openFavorite with when: "!terminalFocus" will still fire while the terminal is focused, because the live context state is never supplied to the matcher. Consider passing the current context into isOpenFavoriteEditorShortcut so when clauses resolve against the actual UI state.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/web/src/components/chat/OpenInPickerShortcut.ts around line 28:
      
      `isOpenFavoriteEditorShortcut` is called without passing the current shortcut context (e.g., `terminalFocus`, `previewFocus`), so `when` clauses on `editor.openFavorite` bindings are evaluated against stale defaults. A user keybinding like `editor.openFavorite` with `when: "!terminalFocus"` will still fire while the terminal is focused, because the live context state is never supplied to the matcher. Consider passing the current context into `isOpenFavoriteEditorShortcut` so `when` clauses resolve against the actual UI state.
      @@ -0,0 +89,21 @@
      89+ const canMerge = mergeTargetThreadId !== null && latestCompletedRun !== null;
      90+ const canDetach = projection ? canDetachThreadProviderSession(projection) : false;
      91+ const [visible, setVisible] = useState(false);
      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) => {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium threads/ThreadRelationshipsBanner.tsx:109

      When a user taps a row pointing at an archived thread, openThread() discards the threadId and navigates to the generic "SettingsArchive" screen, so the specific archived thread the user selected is never opened — they land on the full archive list with no way to distinguish which conversation they wanted. Consider passing threadId (or an environment + search filter) into the navigation params so the archive screen can preselect or deep-link to the tapped thread.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/mobile/src/features/threads/ThreadRelationshipsBanner.tsx around line 109:
      
      When a user taps a row pointing at an archived thread, `openThread()` discards the `threadId` and navigates to the generic `"SettingsArchive"` screen, so the specific archived thread the user selected is never opened — they land on the full archive list with no way to distinguish which conversation they wanted. Consider passing `threadId` (or an environment + search filter) into the navigation params so the archive screen can preselect or deep-link to the tapped thread.
      @@ -0,0 +246,21 @@
      246+ childrenByParentKey.set(parentKey, sortThreads(children, input.threadSortOrder));
      247+ }
      248+
      249+ const rows: SubagentThreadTreeRow<Thread>[] = [];
      250+ const visited = new Set<string>();
      251+ const visit = (thread: Thread, depth: number) => {
      252+ const key = subagentThreadKey(thread);
      253+ if (visited.has(key)) return;
      254+ visited.add(key);
      255+ const children = (childrenByParentKey.get(key) ?? []).filter(
      256+ (child) => !visited.has(subagentThreadKey(child)),
      257+ );
      258+ const hasSubagentChildren = children.length > 0;
      259+ const isSubagentBranchExpanded = hasSubagentChildren && input.expandedThreadKeys.has(key);
      260+ rows.push({ thread, depth, hasSubagentChildren, isSubagentBranchExpanded });
      261+ if (!isSubagentBranchExpanded) return;
      262+ for (const child of children) visit(child, depth + 1);
      263+ };
      264+
      265+ for (const root of input.roots) visit(root, 0);
      266+ return rows;
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium state/threadRelationships.ts:266

      walkThreadRelationships marks a thread as visited the first time it is reached, so when the same thread pair is connected by two different edge kinds (e.g. a lineage edge and a transfer edge), only the first edge is emitted and the second is silently dropped. The returned walk is missing valid relationship rows, hiding edges from callers. The visited check should be keyed on the (threadId, edge) pair (or edge key) rather than on relatedId alone, so distinct relationships to the same thread are all included.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @packages/client-runtime/src/state/threadRelationships.ts around line 266:
      
      `walkThreadRelationships` marks a thread as visited the first time it is reached, so when the same thread pair is connected by two different edge kinds (e.g. a lineage edge and a `transfer` edge), only the first edge is emitted and the second is silently dropped. The returned walk is missing valid relationship rows, hiding edges from callers. The `visited` check should be keyed on the `(threadId, edge)` pair (or edge key) rather than on `relatedId` alone, so distinct relationships to the same thread are all included.
      @@ -0,0 +55,21 @@
      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 =
      65+ providerThread?.providerSessionId == null
      66+ ? null
      67+ : (projection.providerSessions.find(
      68+ (candidate) => candidate.id === providerThread.providerSessionId,
      69+ ) ?? null);
      70+ const providerTurn =
      71+ item.providerTurnId === null
      72+ ? null
      73+ : (projection.providerTurns.find((candidate) => candidate.id === item.providerTurnId) ??
      74+ null);
      75+ const requestId =
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium state/itemSupport.ts:64

      resolveV2ItemSupport returns providerSession: null for items whose session is only reachable through runtimeRequest.responseCapability.providerSessionId when providerThread.providerSessionId is null (e.g., live runtime requests with an ad-hoc session). The test fixture models exactly this case (providerThread.providerSessionId: null, runtimeRequest.responseCapability.providerSessionId: session-1). Consumers lose session/model/cwd details for the item despite the projection containing the session record. Consider deriving providerSession from the runtime request's providerSessionId as a fallback before giving up.

        const providerSession =
          providerThread?.providerSessionId == null
            ? null
            : (projection.providerSessions.find(
                (candidate) => candidate.id === providerThread.providerSessionId,
              ) ?? null);
      +  const fallbackProviderSession =
      +    requestId != null
      +      ? (projection.runtimeRequests.find((candidate) => candidate.id === requestId) ?? null)
      +      : null;
        const providerTurn =
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @packages/client-runtime/src/state/itemSupport.ts around lines 64-75:
      
      `resolveV2ItemSupport` returns `providerSession: null` for items whose session is only reachable through `runtimeRequest.responseCapability.providerSessionId` when `providerThread.providerSessionId` is `null` (e.g., live runtime requests with an ad-hoc session). The test fixture models exactly this case (`providerThread.providerSessionId: null`, `runtimeRequest.responseCapability.providerSessionId: session-1`). Consumers lose session/model/cwd details for the item despite the projection containing the session record. Consider deriving `providerSession` from the runtime request's `providerSessionId` as a fallback before giving up.
      @@ -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 per-instance keyboard shortcut handler means editor.openFavorite always opens the thread root gitCwd instead of the file shown in a file preview. FilePreviewPanel renders a compact OpenInPicker with openInCwd={absolutePath}, so pressing the shortcut previously opened that specific file. After this change only ChatView's global handler remains, so the same shortcut always targets the thread root directory regardless of which file is being previewed. Consider restoring per-instance shortcut handling (or forwarding the preview path to the global handler) so the shortcut opens the correct file.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/web/src/components/chat/OpenInPicker.tsx around line 169:
      
      Removing the per-instance keyboard shortcut handler means `editor.openFavorite` always opens the thread root `gitCwd` instead of the file shown in a file preview. `FilePreviewPanel` renders a compact `OpenInPicker` with `openInCwd={absolutePath}`, so pressing the shortcut previously opened that specific file. After this change only `ChatView`'s global handler remains, so the same shortcut always targets the thread root directory regardless of which file is being previewed. Consider restoring per-instance shortcut handling (or forwarding the preview path to the global handler) so the shortcut opens the correct file.
      @@ -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 removes entries from the caches but does not cancel or deduplicate work already queued or in-flight for the same workspaceRoot. A resolver that started before the invalidation can write its old result back into the cache afterward, so the caller immediately sees stale metadata after requesting a refresh. Consider tracking in-flight or queued roots per lane and skipping or re-queueing stale completions, or canceling pending work for the invalidated roots.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/project/ProjectEnrichmentService.ts around line 259:
      
      `invalidate` removes entries from the caches but does not cancel or deduplicate work already queued or in-flight for the same `workspaceRoot`. A resolver that started before the invalidation can write its old result back into the cache afterward, so the caller immediately sees stale metadata after requesting a refresh. Consider tracking in-flight or queued roots per lane and skipping or re-queueing stale completions, or canceling pending work for the invalidated roots.
      @@ -0,0 +258,21 @@
      258+ return withLocalVisibleTurnItems({
      259+ ...base,
      260+ turnItems: upsertById(base.turnItems, event.payload),
      261+ });
      262+ case "plan.updated":
      263+ return {
      264+ ...base,
      265+ plans: upsertById(base.plans, event.payload),
      266+ };
      267+ case "checkpoint-scope.created":
      268+ return {
      269+ ...base,
      270+ checkpointScopes: upsertById(base.checkpointScopes, event.payload),
      271+ };
      272+ case "checkpoint.captured":
      273+ return {
      274+ ...base,
      275+ checkpoints: upsertById(base.checkpoints, event.payload),
      276+ };
      277+ case "checkpoint.rollback-requested":
      278+ return base;
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium orchestration-v2/ProjectionStore.ts:278

      When a context-transfer.created or context-transfer.updated event is applied, the transfer is only inserted into the projection for event.threadId. The SQL-backed store exposes a transfer on both sourceThreadId and targetThreadId, so a transfer event emitted for one side is missing from the other thread's memory projection. Callers reading the non-emitting thread miss transfers involving their thread.

      applyToProjection only knows about the single projection it receives, so the fix belongs in applyToProjectionReplayState (which has access to all projections) — it should upsert the transfer into both the sourceThreadId and targetThreadId projections, similar to how provider-session.attached/provider-session.updated already fan out across bound threads.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/ProjectionStore.ts around line 278:
      
      When a `context-transfer.created` or `context-transfer.updated` event is applied, the transfer is only inserted into the projection for `event.threadId`. The SQL-backed store exposes a transfer on **both** `sourceThreadId` and `targetThreadId`, so a transfer event emitted for one side is missing from the other thread's memory projection. Callers reading the non-emitting thread miss transfers involving their thread.
      
      `applyToProjection` only knows about the single projection it receives, so the fix belongs in `applyToProjectionReplayState` (which has access to all projections) — it should upsert the transfer into both the `sourceThreadId` and `targetThreadId` projections, similar to how `provider-session.attached`/`provider-session.updated` already fan out across bound threads.
    11. @@ -0,0 +27,21 @@
      27+>()("t3/orchestration-v2/CheckpointCleanupService/CheckpointCleanupServiceV2") {}
      28+
      29+export const layer: Layer.Layer<
      30+ CheckpointCleanupServiceV2,
      31+ never,
      32+ CheckpointServiceV2 | ProjectionStoreV2
      33+> = Layer.effect(
      34+ CheckpointCleanupServiceV2,
      35+ Effect.gen(function* () {
      36+ const checkpoints = yield* CheckpointServiceV2;
      37+ const projections = yield* ProjectionStoreV2;
      38+
      39+ const cleanup = Effect.fn("orchestrationV2.checkpointCleanup.cleanup")(function* (
      40+ threadId: ThreadId,
      41+ ) {
      42+ const projection = yield* projections.getThreadProjection(threadId);
      43+ const throughOrdinal = Math.max(
      44+ 0,
      45+ ...projection.runs.map((run) => run.ordinal),
      46+ ...projection.checkpoints.map((checkpoint) => checkpoint.ordinalWithinScope),
      47+ );
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High orchestration-v2/CheckpointCleanupService.ts:43

      When a thread accumulates many runs and checkpoints, Math.max(0, ...projection.runs.map(...), ...projection.checkpoints.map(...)) throws a RangeError: Maximum call stack size exceeded because it spreads every ordinal as a function argument. This aborts cleanup and leaves checkpoint refs undeleted. Consider computing the max with a reducer instead of spreading into Math.max.

      Suggested change
      43- const throughOrdinal = Math.max(
      44- 0,
      45- ...projection.runs.map((run) => run.ordinal),
      46- ...projection.checkpoints.map((checkpoint) => checkpoint.ordinalWithinScope),
      47- );
      43+ const throughOrdinal = [
      44+ ...projection.runs.map((run) => run.ordinal),
      45+ ...projection.checkpoints.map((checkpoint) => checkpoint.ordinalWithinScope),
      46+ ].reduce((max, n) => (n > max ? n : max), 0);
      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/CheckpointCleanupService.ts around lines 43-47:
      
      When a thread accumulates many runs and checkpoints, `Math.max(0, ...projection.runs.map(...), ...projection.checkpoints.map(...))` throws a `RangeError: Maximum call stack size exceeded` because it spreads every ordinal as a function argument. This aborts `cleanup` and leaves checkpoint refs undeleted. Consider computing the max with a reducer instead of spreading into `Math.max`.
      @@ -243,10 +249,20 @@
      243249 props.projectSortOrder,
      244250 props.searchQuery,
      245251 props.selectedEnvironmentId,
      252+ props.showSubagentThreads,
      246253 props.threadSortOrder,
      247254 props.threads,
      248255 ],
      249256 );
      250257
      251258 const hasSearchQuery = props.searchQuery.trim().length > 0;
      259+ const toggleSubagentBranch = useCallback((thread: EnvironmentThreadShell) => {
      260+ const key = subagentThreadKey(thread);
      261+ setExpandedSubagentThreadKeys((previous) => {
      262+ const next = new Set(previous);
      263+ if (next.has(key)) next.delete(key);
      264+ else next.add(key);
      265+ return next;
      266+ });
      267+ }, []);
      252268 const listLayout = useMemo(
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium home/HomeScreen.tsx:268

      In nested-subagent mode, a currently open subagent child thread disappears from the phone home list when its root falls past the initial page. HomeScreen calls buildHomeListLayout without pinnedThreadKey, and expandedSubagentThreadKeys starts empty, so if a deep-linked child lives under an older root the list renders only the first page of roots with no expanded ancestors — the open thread is unreachable until the user manually taps "Show more" and expands each ancestor. buildHomeListLayout already has pinnedThreadKey support for exactly this scenario; consider passing the currently selected thread's key so its branch root is kept visible.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/mobile/src/features/home/HomeScreen.tsx around line 268:
      
      In nested-subagent mode, a currently open subagent child thread disappears from the phone home list when its root falls past the initial page. `HomeScreen` calls `buildHomeListLayout` without `pinnedThreadKey`, and `expandedSubagentThreadKeys` starts empty, so if a deep-linked child lives under an older root the list renders only the first page of roots with no expanded ancestors — the open thread is unreachable until the user manually taps "Show more" and expands each ancestor. `buildHomeListLayout` already has `pinnedThreadKey` support for exactly this scenario; consider passing the currently selected thread's key so its branch root is kept visible.
      @@ -0,0 +280,21 @@
      280+/**
      281+ * IMPLEMENTATIONS
      282+ */
      283+export const layer: Layer.Layer<
      284+ RunExecutionServiceV2,
      285+ never,
      286+ | CheckpointServiceV2
      287+ | EventSinkV2
      288+ | IdAllocatorV2
      289+ | ProviderEventIngestorV2
      290+ | ServerSettingsService
      291+> = Layer.effect(
      292+ RunExecutionServiceV2,
      293+ Effect.gen(function* () {
      294+ const checkpointService = yield* CheckpointServiceV2;
      295+ const eventSink = yield* EventSinkV2;
      296+ const idAllocator = yield* IdAllocatorV2;
      297+ const providerEventIngestor = yield* ProviderEventIngestorV2;
      298+ const serverSettings = yield* ServerSettingsService;
      299+
      300+ const writeFinalRunEvents = (input: {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High orchestration-v2/RunExecutionService.ts:300

      writeFinalRunEvents writes terminal run.updated, node.updated, and provider-thread.updated events via eventSink.writeWithEffects without a transactional run-ownership guard. If a restart supersedes this attempt after shouldFinalizeRun() is checked but before the write commits, the superseded attempt overwrites the newer attempt's run state and enqueues a stale checkpoint capture. The shouldFinalizeRun() callback is a non-atomic precondition, so the window between the check and the unguarded write allows a superseded attempt to incorrectly persist terminal status for the current run. Consider routing the terminal events through eventSink.writeIfRunCurrent (with allowSupersededAttemptTerminalArtifacts where appropriate) so the write is rejected when the attempt no longer owns the run.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/RunExecutionService.ts around line 300:
      
      `writeFinalRunEvents` writes terminal `run.updated`, `node.updated`, and `provider-thread.updated` events via `eventSink.writeWithEffects` without a transactional run-ownership guard. If a restart supersedes this attempt after `shouldFinalizeRun()` is checked but before the write commits, the superseded attempt overwrites the newer attempt's run state and enqueues a stale checkpoint capture. The `shouldFinalizeRun()` callback is a non-atomic precondition, so the window between the check and the unguarded write allows a superseded attempt to incorrectly persist terminal status for the current run. Consider routing the terminal events through `eventSink.writeIfRunCurrent` (with `allowSupersededAttemptTerminalArtifacts` where appropriate) so the write is rejected when the attempt no longer owns the run.
      @@ -0,0 +129,21 @@
      129+ rootNode === undefined ||
      130+ attempt === undefined ||
      131+ providerThread === undefined ||
      132+ providerThread.providerSessionId === null ||
      133+ message === undefined ||
      134+ checkpointScope === undefined
      135+ ) {
      136+ return yield* new ProviderTurnStartError({
      137+ runId,
      138+ cause: `Run ${runId} is missing its execution projection state.`,
      139+ });
      140+ }
      141+ const providerSessionId = providerThread.providerSessionId;
      142+ type CurrentAttemptState = "current" | "run_stale" | "thread_inactive";
      143+ const getCurrentAttemptState = Effect.fn(
      144+ "orchestrationV2.providerTurnStart.getCurrentAttemptState",
      145+ )(
      146+ function* (
      147+ expectedStatus: OrchestrationV2Run["status"],
      148+ ): Effect.fn.Return<CurrentAttemptState, never> {
      149+ const currentOption = yield* Effect.option(
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High orchestration-v2/ProviderTurnStartService.ts:149

      Transient storage errors during projectionStore.getThreadProjection(...) are silently swallowed by getCurrentAttemptState, causing start() to exit successfully without advancing the run. The run stays stuck in starting with no retry or surfaced error, so provider-turn starts silently hang on ordinary database failures.

      getCurrentAttemptState wraps the projection read in Effect.option(...) and then Effect.catchCause(...), converting every failure — including transient store/DB errors — into "run_stale". continueIfCurrent then returns false and start() returns normally. Consider distinguishing transient errors (which should propagate) from a genuinely stale or missing run (which may warrant the current no-op behavior), so storage failures are not masked as stale-state exits.

      Also found in 1 other location(s)

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

      isGitCheckpointable at line 299 converts every CheckpointStore.isGitRepository failure into false. If VCS detection fails because of a real runtime problem (for example a transient VcsError, permission problem, or driver failure), captureBaseline, materializeBaselineCheckpoint, and capture all silently behave as though the workspace is not a Git repo and emit checkpoints with status &#34;missing&#34;/&#34;error&#34; instead of surfacing the failure. That leaves runs completing without a usable rollback checkpoint even though checkpointing was expected to work.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/ProviderTurnStartService.ts around line 149:
      
      Transient storage errors during `projectionStore.getThreadProjection(...)` are silently swallowed by `getCurrentAttemptState`, causing `start()` to exit successfully without advancing the run. The run stays stuck in `starting` with no retry or surfaced error, so provider-turn starts silently hang on ordinary database failures.
      
      `getCurrentAttemptState` wraps the projection read in `Effect.option(...)` and then `Effect.catchCause(...)`, converting every failure — including transient store/DB errors — into `"run_stale"`. `continueIfCurrent` then returns `false` and `start()` returns normally. Consider distinguishing transient errors (which should propagate) from a genuinely stale or missing run (which may warrant the current no-op behavior), so storage failures are not masked as stale-state exits.
      
      Also found in 1 other location(s):
      - apps/server/src/orchestration-v2/CheckpointService.ts:299 -- `isGitCheckpointable` at line `299` converts every `CheckpointStore.isGitRepository` failure into `false`. If VCS detection fails because of a real runtime problem (for example a transient `VcsError`, permission problem, or driver failure), `captureBaseline`, `materializeBaselineCheckpoint`, and `capture` all silently behave as though the workspace is not a Git repo and emit checkpoints with status `"missing"`/`"error"` instead of surfacing the failure. That leaves runs completing without a usable rollback checkpoint even though checkpointing was expected to work.
      
      @@ -31,3 +38,6 @@
      3138 return "Could not delete thread";
      3239 }
      3340
      41+function readThreadSubtree(thread: EnvironmentThreadShell): readonly EnvironmentThreadShell[] {
      42+ const snapshot = appAtomRegistry.get(environmentSnapshotAtom(thread.environmentId));
      43+ if (snapshot === null) return [thread];
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High home/useThreadListActions.ts:43

      readThreadSubtree returns only [thread] when the environment snapshot is null, so actionSubagentDescendants sees zero descendants. On the archived-threads screen, where appAtomRegistry.get(environmentSnapshotAtom(...)) is null, this causes useThreadAction to skip the confirmation dialog for a parent that still owns subagent children. Because the server applies thread.delete and thread.unarchive recursively, deleting or unarchiving a parent permanently removes or restores hidden child threads with no warning. Consider sourcing the subtree from the same archived-threads snapshot the screen already uses instead of returning [thread] when the live shell snapshot is null.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/mobile/src/features/home/useThreadListActions.ts around line 43:
      
      `readThreadSubtree` returns only `[thread]` when the environment snapshot is `null`, so `actionSubagentDescendants` sees zero descendants. On the archived-threads screen, where `appAtomRegistry.get(environmentSnapshotAtom(...))` is `null`, this causes `useThreadAction` to skip the confirmation dialog for a parent that still owns subagent children. Because the server applies `thread.delete` and `thread.unarchive` recursively, deleting or unarchiving a parent permanently removes or restores hidden child threads with no warning. Consider sourcing the subtree from the same archived-threads snapshot the screen already uses instead of returning `[thread]` when the live shell snapshot is `null`.
      @@ -0,0 +671,21 @@
      671+ yield* Ref.set(latestProviderThread, event.providerThread);
      672+ }
      673+ }
      674+ if (
      675+ event.type === "turn_item.updated" &&
      676+ event.turnItem.providerTurnId ===
      677+ (yield* Ref.get(eventRouting)).rootProviderTurnId
      678+ ) {
      679+ yield* Ref.update(latestTurnItemOrdinal, (current) =>
      680+ Math.max(current, event.turnItem.ordinal),
      681+ );
      682+ }
      683+ if (event.type === "turn.terminal") {
      684+ yield* Ref.set(terminalEvent, event);
      685+ yield* Ref.set(rootTerminalSeen, true);
      686+ yield* finalizeRootRun(event);
      687+ }
      688+ yield* trackChildLifecycle(event);
      689+ }),
      690+ ),
      691+ Stream.takeUntilEffect(() => shouldStopProviderEventIngestion),
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High orchestration-v2/RunExecutionService.ts:691

      Stream.takeUntilEffect(() => shouldStopProviderEventIngestion) stops the stream as soon as the root turn.terminal event arrives and activeChildProviderTurns and activeChildSubagents are both still empty. This drops owned child artifacts that arrive after the root terminal event — for example a late app_thread.created, provider_thread.updated, or message.updated for a nested subagent thread still in flight. The takeUntilEffect check runs immediately after the terminal event is processed (in the same Stream.tap callback), so if no child provider turns or subagents have been observed yet, the stream closes before the late child events can be ingested. Consider waiting for a grace period after the root terminal before stopping the stream, or deferring the stop check until at least one stream iteration after the terminal event.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/RunExecutionService.ts around line 691:
      
      `Stream.takeUntilEffect(() => shouldStopProviderEventIngestion)` stops the stream as soon as the root `turn.terminal` event arrives and `activeChildProviderTurns` and `activeChildSubagents` are both still empty. This drops owned child artifacts that arrive *after* the root terminal event — for example a late `app_thread.created`, `provider_thread.updated`, or `message.updated` for a nested subagent thread still in flight. The `takeUntilEffect` check runs immediately after the terminal event is processed (in the same `Stream.tap` callback), so if no child provider turns or subagents have been observed yet, the stream closes before the late child events can be ingested. Consider waiting for a grace period after the root terminal before stopping the stream, or deferring the stop check until at least one stream iteration after the terminal event.
      @@ -123,6 +142,17 @@
      123142 * When searching, pagination is suspended so every match stays visible.
      124143 */
      125144 readonly showAllThreads?: boolean;
      145+ /** Enables nested, collapsible subagent rows. Disabled by default. */
      146+ readonly showSubagentThreads?: boolean;
      147+ readonly expandedThreadKeys?: ReadonlySet<string>;
      148+ /**
      149+ * Key of an explicitly selected thread that must stay reachable. In nested
      150+ * mode, when its branch root falls past the pagination cut, that root is
      151+ * appended so the selection never disappears from the list.
      152+ */
      153+ readonly pinnedThreadKey?: string | null;
      154+ readonly threadSortOrder?: SidebarThreadSortOrder;
      126155 }): HomeListLayout {
      127156 const items: HomeListItem[] = [];
      128157 const stickyHeaderIndices: number[] = [];
      158+ const allThreads = input.groups.flatMap((group) => group.threads);
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium home/homeListItems.ts:158

      hasUnavailableSubagentParent is called with allThreads, which is built from group.threads — the threads that remain after search/filter grouping. When a subagent child is visible because its project matched, but its parent thread lives in a different project group that was filtered out, the function reports the parent as unavailable and the row renders a false Parent unavailable label. The parent thread still exists; it is just hidden by the current view filter. Consider passing the full, unfiltered thread list (e.g., all threads across all projects/environments before grouping) so the availability check reflects actual thread existence rather than current visibility.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/mobile/src/features/home/homeListItems.ts around line 158:
      
      `hasUnavailableSubagentParent` is called with `allThreads`, which is built from `group.threads` — the threads that remain after search/filter grouping. When a subagent child is visible because its project matched, but its parent thread lives in a different project group that was filtered out, the function reports the parent as unavailable and the row renders a false `Parent unavailable` label. The parent thread still exists; it is just hidden by the current view filter. Consider passing the full, unfiltered thread list (e.g., all threads across all projects/environments before grouping) so the availability check reflects actual thread existence rather than current visibility.
      @@ -0,0 +322,21 @@
      322+ },
      323+ },
      324+ ],
      325+ });
      326+ return replacement;
      327+ });
      328+ if (!(yield* continueIfCurrent("starting"))) {
      329+ return;
      330+ }
      331+ const now = yield* DateTime.now;
      332+ const runningProviderThread: OrchestrationV2ProviderThread = {
      333+ ...loadedProviderThread,
      334+ id: providerThread.id,
      335+ driver: session.driver,
      336+ providerInstanceId: run.providerInstanceId,
      337+ providerSessionId,
      338+ appThreadId: projection.thread.id,
      339+ ownerNodeId: providerThread.ownerNodeId,
      340+ firstRunOrdinal: providerThread.firstRunOrdinal ?? run.ordinal,
      341+ lastRunOrdinal: run.ordinal,
      342+ handoffIds: providerThread.handoffIds,
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium orchestration-v2/ProviderTurnStartService.ts:342

      When session.resumeThread(...) fails and a portable fallback handoff is created, the persisted provider-thread.updated event sets handoffIds to providerThread.handoffIds without appending the new handoff.id. This silently drops the linkage between the replacement provider thread and the fallback context handoff — any code that later reads providerThread.handoffIds will not find the handoff that was just written. Consider updating runningProviderThread.handoffIds to include the new handoff ID when effectiveHandoffs has been extended.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/ProviderTurnStartService.ts around line 342:
      
      When `session.resumeThread(...)` fails and a portable fallback handoff is created, the persisted `provider-thread.updated` event sets `handoffIds` to `providerThread.handoffIds` without appending the new `handoff.id`. This silently drops the linkage between the replacement provider thread and the fallback context handoff — any code that later reads `providerThread.handoffIds` will not find the handoff that was just written. Consider updating `runningProviderThread.handoffIds` to include the new handoff ID when `effectiveHandoffs` has been extended.
    12. @@ -0,0 +1283,21 @@
      1283+ firstStep.type === "fork" ||
      1284+ secondStep.type === "rollback" ||
      1285+ secondStep.type === "fork"
      1286+ ) {
      1287+ throw new Error("provider_thread_resume replay recording requires two turn steps.");
      1288+ }
      1289+
      1290+ const firstThread = yield* Effect.gen(function* () {
      1291+ const client = yield* initializeClient;
      1292+ const thread = yield* client.request("thread/start", {});
      1293+ yield* runTurnStep(client, thread.thread.id, firstStep);
      1294+ return thread;
      1295+ }).pipe(
      1296+ Effect.provide(
      1297+ makeCodexLayer({
      1298+ recorder,
      1299+ }),
      1300+ ),
      1301+ );
      1302+
      1303+ yield* recorder.writeRecord({
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium scripts/record-codex-app-server-replay-fixture.ts:1303

      The provider_thread_resume scenario writes a runtime_exit record between the first and second app-server sessions, but the replay driver treats runtime_exit as a permanent end-of-transcript marker. As a result, replaying the generated fixture stops after the first turn and never reaches thread/resume or the second turn. Consider removing the intermediate runtime_exit record so the second session's records remain reachable during replay.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/scripts/record-codex-app-server-replay-fixture.ts around line 1303:
      
      The `provider_thread_resume` scenario writes a `runtime_exit` record between the first and second app-server sessions, but the replay driver treats `runtime_exit` as a permanent end-of-transcript marker. As a result, replaying the generated fixture stops after the first turn and never reaches `thread/resume` or the second turn. Consider removing the intermediate `runtime_exit` record so the second session's records remain reachable during replay.
      @@ -0,0 +223,21 @@
      223+ cursor: this.cursor,
      224+ remaining: this.transcript.entries.length - this.cursor,
      225+ });
      226+ }
      227+ }
      228+
      229+ private advance(): void {
      230+ this.cursor += 1;
      231+ for (const waiter of this.waiters) waiter();
      232+ this.waiters.clear();
      233+ }
      234+
      235+ private fail(cause: unknown): void {
      236+ this.failure = cause;
      237+ for (const waiter of this.waiters) waiter();
      238+ this.waiters.clear();
      239+ }
      240+
      241+ private throwFailure(): void {
      242+ if (this.failure !== null) throw this.failure;
      243+ }
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/OpenCodeAdapterV2.testkit.ts:243

      response() can hang forever waiting for an entry that is already available. When response() sees an emit_inbound entry whose frame type is not sdk.response, it calls await this.changed() to wait for the cursor to advance. But advance() clears all current waiters before response() registers its own waiter — if another consumer (e.g. events()) consumes the entry and calls advance() in the window between response() reading this.cursor and registering the waiter, response() sleeps with no guaranteed future advance() to wake it. The same lost-wakeup race exists in events(). Consider re-checking the cursor after registering the waiter, or adding the waiter before reading the current entry so no advance() is missed.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/OpenCodeAdapterV2.testkit.ts around line 243:
      
      `response()` can hang forever waiting for an entry that is already available. When `response()` sees an `emit_inbound` entry whose frame type is not `sdk.response`, it calls `await this.changed()` to wait for the cursor to advance. But `advance()` clears all current waiters before `response()` registers its own waiter — if another consumer (e.g. `events()`) consumes the entry and calls `advance()` in the window between `response()` reading `this.cursor` and registering the waiter, `response()` sleeps with no guaranteed future `advance()` to wake it. The same lost-wakeup race exists in `events()`. Consider re-checking the cursor after registering the waiter, or adding the waiter before reading the current entry so no `advance()` is missed.
      @@ -0,0 +55,21 @@
      55+ const session = resolveThreadProviderSession(projection);
      56+ const capabilities = session?.capabilities.turns;
      57+ const queuedRuns = projection.runs
      58+ .filter((run) => run.status === "queued")
      59+ .sort(
      60+ (left, right) =>
      61+ (left.queuePosition ?? left.ordinal) - (right.queuePosition ?? right.ordinal) ||
      62+ left.ordinal - right.ordinal,
      63+ )
      64+ .map((run) => ({
      65+ run,
      66+ text:
      67+ projection.messages.find((message) => message.id === run.userMessageId)?.text ??
      68+ "Queued message",
      69+ }));
      70+
      71+ return {
      72+ activeRun,
      73+ queuedRuns,
      74+ canReorder: capabilities?.supportsQueuedMessages === true,
      75+ canPromoteToSteer:
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium state/threadWorkflows.ts:75

      canPromoteToSteer is true whenever activeRun is non-null, including runs with status "preparing", "starting", or "waiting". The server only allows steering when the run is "running" with an active provider turn, so promoting in those other states fails with thread_not_sendable. The check at line 76 should additionally require activeRun.status === "running".

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @packages/client-runtime/src/state/threadWorkflows.ts around line 75:
      
      `canPromoteToSteer` is `true` whenever `activeRun` is non-null, including runs with status `"preparing"`, `"starting"`, or `"waiting"`. The server only allows steering when the run is `"running"` with an active provider turn, so promoting in those other states fails with `thread_not_sendable`. The check at line 76 should additionally require `activeRun.status === "running"`.
      @@ -0,0 +1 @@
      1+import * as NodeRuntime from "@effect/platform-node/NodeRuntime";
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium scripts/record-codex-app-server-replay-fixture.ts:1

      The steered-turn flow deadlocks when the initial prompt triggers an approval request before turn/started fires. The approval handlers for item/commandExecution/requestApproval, item/fileChange/requestApproval, and item/permissions/requestApproval all call beforeApprovalResponse(), which awaits approvalGate. But approvalGate is only released after turn/steer is sent, and turn/steer is sent only after Deferred.await(started) completes — which requires the server to emit turn/started. If the server blocks on an approval request before emitting turn/started, both sides wait on each other indefinitely. Consider releasing the gate or restructuring the steer sequencing so approval requests are not blocked on turn/started.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/scripts/record-codex-app-server-replay-fixture.ts around line 1:
      
      The steered-turn flow deadlocks when the initial prompt triggers an approval request before `turn/started` fires. The approval handlers for `item/commandExecution/requestApproval`, `item/fileChange/requestApproval`, and `item/permissions/requestApproval` all call `beforeApprovalResponse()`, which awaits `approvalGate`. But `approvalGate` is only released after `turn/steer` is sent, and `turn/steer` is sent only after `Deferred.await(started)` completes — which requires the server to emit `turn/started`. If the server blocks on an approval request before emitting `turn/started`, both sides wait on each other indefinitely. Consider releasing the gate or restructuring the steer sequencing so approval requests are not blocked on `turn/started`.
      @@ -0,0 +204,21 @@
      204+ ...base,
      205+ attempts: upsertById(base.attempts, event.payload),
      206+ });
      207+ case "node.updated":
      208+ return {
      209+ ...base,
      210+ nodes: upsertById(base.nodes, event.payload),
      211+ };
      212+ case "subagent.updated":
      213+ return {
      214+ ...base,
      215+ subagents: upsertById(base.subagents, event.payload),
      216+ };
      217+ case "provider-session.attached":
      218+ case "provider-session.updated":
      219+ return {
      220+ ...base,
      221+ providerSessions: upsertById(base.providerSessions, event.payload),
      222+ };
      223+ case "provider-session.detached":
      224+ return {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium orchestration-v2/ProjectionStore.ts:224

      applyToProjection handles provider-thread.updated by upserting the payload only into the current thread's providerThreads array. When a provider thread belongs to a subagent node in a different thread, the parent-thread projection built by the memory-backed store never receives that provider thread, so its providerThreads list is missing entries that getThreadProjection on the SQL store returns. Any feature that inspects subagent provider threads sees different results depending on which projection store backs the thread. Consider mirroring the cross-thread fan-out already done for provider-session.* events (via providerSessionThreadIds) so provider-thread.updated events also upsert into every bound parent-thread projection, or document why the memory store intentionally omits this relationship.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/ProjectionStore.ts around line 224:
      
      `applyToProjection` handles `provider-thread.updated` by upserting the payload only into the current thread's `providerThreads` array. When a provider thread belongs to a subagent node in a different thread, the parent-thread projection built by the memory-backed store never receives that provider thread, so its `providerThreads` list is missing entries that `getThreadProjection` on the SQL store returns. Any feature that inspects subagent provider threads sees different results depending on which projection store backs the thread. Consider mirroring the cross-thread fan-out already done for `provider-session.*` events (via `providerSessionThreadIds`) so `provider-thread.updated` events also upsert into every bound parent-thread projection, or document why the memory store intentionally omits this relationship.
      @@ -520,17 +133,4 @@
      520- normalizeCursorConfigOptionToken(requestedContextWindow) ||
      521- normalizeCursorConfigOptionToken(option.name) ===
      522- normalizeCursorConfigOptionToken(requestedContextWindow),
      523- );
      524- if (value) {
      525- updates.push({ configId: contextOption.id, value });
      526- }
      527- }
      528-
      529- const fastOption = configOptions.find(
      530- (option) => option.category === "model_config" && isCursorFastConfigOption(option),
      531- );
      532- const requestedFastMode = getProviderOptionBooleanSelectionValue(selections, "fastMode");
      533- if (fastOption && typeof requestedFastMode === "boolean") {
      534- const value = findCursorBooleanConfigValue(fastOption, requestedFastMode);
      535- if (value !== undefined) {
      536- updates.push({ configId: fastOption.id, value });
      133+ const label = parameter.displayName?.trim() || toTitleCaseWords(id);
      134+ const defaultValue = cursorSdkDefaultParameterValue(model, nativeId);
      135+ const normalizedValues = new Set(values.map((entry) => entry.value.toLowerCase()));
      136+ if (values.length === 2 && normalizedValues.has("true") && normalizedValues.has("false")) {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Layers/CursorProvider.ts:136

      When a Cursor SDK parameter has exactly two values that normalize to true/false, it becomes a boolean toggle, but a parameter with three or more values that includes both true and false (e.g. ["true", "false", "default"]) is now always built as a select option instead of a boolean toggle. This changes the discovered capability shape for those models, breaking the expected UI control. The strict values.length === 2 guard rejects option sets the previous logic treated as boolean-like. Consider relaxing the guard to check whether the value set contains both true and false rather than requiring exactly two values.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/provider/Layers/CursorProvider.ts around line 136:
      
      When a Cursor SDK parameter has exactly two values that normalize to `true`/`false`, it becomes a boolean toggle, but a parameter with three or more values that includes both `true` and `false` (e.g. `["true", "false", "default"]`) is now always built as a `select` option instead of a boolean toggle. This changes the discovered capability shape for those models, breaking the expected UI control. The strict `values.length === 2` guard rejects option sets the previous logic treated as boolean-like. Consider relaxing the guard to check whether the value set contains both `true` and `false` rather than requiring exactly two values.
      @@ -0,0 +219,21 @@
      219+ ),
      220+ )
      221+ .toSorted((left, right) => right.ordinal - left.ordinal)[0];
      222+}
      223+
      224+function errorMessage(error: unknown): string {
      225+ return error instanceof Error ? error.message : String(error);
      226+}
      227+
      228+function managementError(
      229+ code: ThreadManagementError["code"],
      230+ message: string,
      231+ cause?: unknown,
      232+): ThreadManagementError {
      233+ return new ThreadManagementError({ code, message, ...(cause === undefined ? {} : { cause }) });
      234+}
      235+
      236+const make = Effect.gen(function* () {
      237+ const orchestrator = yield* OrchestratorV2;
      238+
      239+ const getProjectThread: ThreadManagementServiceShape["getProjectThread"] = (input) =>
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium orchestration-v2/ThreadManagementService.ts:239

      getProjectThread maps every orchestrator.getThreadProjection failure to thread_not_found, including projection-read failures. When the orchestrator fails due to a database or read error (wrapped in OrchestratorProjectionError), callers of sendToThread, waitForThread, and interruptThread receive a thread_not_found error code instead of an orchestration error, causing transient backend failures to be misreported as missing threads. Consider distinguishing projection-read failures from genuinely missing threads — e.g., by inspecting the OrchestratorProjectionError or mapping non-not-found causes to orchestration_error.

      Also found in 2 other location(s)

      apps/server/src/checkpointing/CheckpointDiffQuery.ts:103

      getTurnDiff now wraps every failure from threads.getThreadProjection in CheckpointThreadNotFoundError. If projection loading fails for any reason other than a missing thread (for example a persistence/decode error inside OrchestratorV2), callers will incorrectly receive a &#34;thread not found&#34; response instead of the real checkpoint/orchestration failure, which hides outages and makes diff requests behave incorrectly during backend faults.

      apps/server/src/project/http.ts:73

      The catch-all at lines 70-73 converts every ProjectService failure into EnvironmentInternalError. That means ordinary user mistakes such as ProjectConflictError (creating a project on an already-owned workspace) or ProjectNotFoundError (updating/deleting an unknown project) are returned from /api/projects/mutate as internal_error instead of the declared EnvironmentRequestInvalidError, so HTTP clients cannot distinguish invalid input from a server failure.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/ThreadManagementService.ts around line 239:
      
      `getProjectThread` maps every `orchestrator.getThreadProjection` failure to `thread_not_found`, including projection-read failures. When the orchestrator fails due to a database or read error (wrapped in `OrchestratorProjectionError`), callers of `sendToThread`, `waitForThread`, and `interruptThread` receive a `thread_not_found` error code instead of an orchestration error, causing transient backend failures to be misreported as missing threads. Consider distinguishing projection-read failures from genuinely missing threads — e.g., by inspecting the `OrchestratorProjectionError` or mapping non-not-found causes to `orchestration_error`.
      
      Also found in 2 other location(s):
      - apps/server/src/checkpointing/CheckpointDiffQuery.ts:103 -- `getTurnDiff` now wraps every failure from `threads.getThreadProjection` in `CheckpointThreadNotFoundError`. If projection loading fails for any reason other than a missing thread (for example a persistence/decode error inside `OrchestratorV2`), callers will incorrectly receive a "thread not found" response instead of the real checkpoint/orchestration failure, which hides outages and makes diff requests behave incorrectly during backend faults.
      - apps/server/src/project/http.ts:73 -- The catch-all at lines `70`-`73` converts every `ProjectService` failure into `EnvironmentInternalError`. That means ordinary user mistakes such as `ProjectConflictError` (creating a project on an already-owned workspace) or `ProjectNotFoundError` (updating/deleting an unknown project) are returned from `/api/projects/mutate` as `internal_error` instead of the declared `EnvironmentRequestInvalidError`, so HTTP clients cannot distinguish invalid input from a server failure.
      
      @@ -0,0 +540,21 @@
      540+ pushDispatch(
      541+ dispatchMessageCommand({
      542+ commandId: yield* idAllocator.allocate.command({
      543+ fixtureName: input.scenario,
      544+ commandName: `steer-${messageIndex}`,
      545+ }),
      546+ ids,
      547+ modelSelection: input.modelSelection,
      548+ messageId: yield* idAllocator.allocate.message({
      549+ threadId: ids.threadId,
      550+ ordinal: messageIndex,
      551+ }),
      552+ text: step.text,
      553+ ...(step.attachments === undefined ? {} : { attachments: step.attachments }),
      554+ dispatchMode: {
      555+ type: "steer_active",
      556+ targetRunId: runIdFor(step.targetRunIndex),
      557+ },
      558+ }),
      559+ );
      560+ if (input.fixtureInput.steps[stepIndex + 1]?.type !== "approve_next_runtime_request") {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium fixtures/shared.ts:560

      A steer or restart step followed by answer_next_user_input_request deadlocks the scenario. When the steered/restarted run pauses for user input, it enters waiting status, which await_thread_idle treats as active. Because await_thread_idle is inserted before the answer_next_user_input_request step runs, the scenario waits for a run that is blocked on the very answer that comes next.

      The guard at lines 560 and 594 only suppresses await_thread_idle when the next step is approve_next_runtime_request, but not for answer_next_user_input_request. Include answer_next_user_input_request in that condition so the answer step runs before waiting for idle.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/testkit/fixtures/shared.ts around line 560:
      
      A `steer` or `restart` step followed by `answer_next_user_input_request` deadlocks the scenario. When the steered/restarted run pauses for user input, it enters `waiting` status, which `await_thread_idle` treats as active. Because `await_thread_idle` is inserted before the `answer_next_user_input_request` step runs, the scenario waits for a run that is blocked on the very answer that comes next.
      
      The guard at lines 560 and 594 only suppresses `await_thread_idle` when the next step is `approve_next_runtime_request`, but not for `answer_next_user_input_request`. Include `answer_next_user_input_request` in that condition so the answer step runs before waiting for idle.
      @@ -0,0 +51,21 @@
      51+ return {
      52+ provider: transcript.provider,
      53+ protocol: transcript.protocol,
      54+ scenario: transcript.scenario,
      55+ };
      56+}
      57+
      58+function makeReplayServerConfig(
      59+ scenario: string,
      60+): Effect.Effect<
      61+ ServerConfig["Service"],
      62+ PlatformError.PlatformError,
      63+ FileSystem.FileSystem | Path.Path
      64+> {
      65+ return Effect.gen(function* () {
      66+ const fs = yield* FileSystem.FileSystem;
      67+ const path = yield* Path.Path;
      68+ const baseDir = yield* fs.makeTempDirectory({
      69+ prefix: `t3-orchestration-v2-codex-${scenario}-`,
      70+ });
      71+ const stateDir = path.join(baseDir, "userdata");
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/CodexAdapterV2.testkit.ts:69

      makeReplayServerConfig passes the raw scenario string into fs.makeTempDirectory as the temp directory prefix. Scenarios like provider_thread_resume/codex:first-runtime contain /, and Node's fs.mkdtemp appends random characters directly to the prefix, so the embedded path separator turns the prefix into a nested path whose parent does not exist. The result is an ENOENT error when building the Codex replay layer for those scenarios, instead of starting the replay harness. Consider sanitizing the scenario (e.g. replacing / and : with -) before using it in the prefix.

      Suggested change
      69- prefix: `t3-orchestration-v2-codex-${scenario}-`,
      70- });
      71- const stateDir = path.join(baseDir, "userdata");
      69+ const baseDir = yield* fs.makeTempDirectory({
      70+ prefix: `t3-orchestration-v2-codex-${scenario.replace(/[^a-zA-Z0-9]/g, "-")}-`,
      71+ });
      Also found in 1 other location(s)

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

      makeReplayServerConfig interpolates scenario directly into the fs.makeTempDirectory prefix. Unlike the shared replay helper, it never sanitizes path separators, so a transcript whose scenario contains / or \ makes the prefix point into a non-existent subdirectory and makeTempDirectory fails with ENOENT. The decoded transcript schema accepts any string here, so replay harness setup breaks for scenario names that include path separators.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.testkit.ts around lines 69-71:
      
      `makeReplayServerConfig` passes the raw `scenario` string into `fs.makeTempDirectory` as the temp directory prefix. Scenarios like `provider_thread_resume/codex:first-runtime` contain `/`, and Node's `fs.mkdtemp` appends random characters directly to the prefix, so the embedded path separator turns the prefix into a nested path whose parent does not exist. The result is an `ENOENT` error when building the Codex replay layer for those scenarios, instead of starting the replay harness. Consider sanitizing the scenario (e.g. replacing `/` and `:` with `-`) before using it in the prefix.
      
      Also found in 1 other location(s):
      - apps/server/src/orchestration-v2/Adapters/CursorAdapterV2.testkit.ts:519 -- `makeReplayServerConfig` interpolates `scenario` directly into the `fs.makeTempDirectory` prefix. Unlike the shared replay helper, it never sanitizes path separators, so a transcript whose `scenario` contains `/` or `\` makes the prefix point into a non-existent subdirectory and `makeTempDirectory` fails with `ENOENT`. The decoded transcript schema accepts any string here, so replay harness setup breaks for scenario names that include path separators.
      
      @@ -0,0 +51,21 @@
      51+import { layer as turnItemPositionStoreLayer } from "../TurnItemPositionStore.ts";
      52+import { layer as runtimeRequestServiceLayer } from "../RuntimeRequestService.ts";
      53+import { layer as threadForkServiceLayer } from "../ThreadForkService.ts";
      54+import {
      55+ runOrchestratorV2Scenario,
      56+ type OrchestratorV2ScenarioStepError,
      57+ type OrchestratorV2Scenario,
      58+ type OrchestratorV2ScenarioResult,
      59+} from "./OrchestratorScenario.ts";
      60+
      61+export function makeReplayServerConfig(
      62+ scenario: string,
      63+): Effect.Effect<
      64+ ServerConfig["Service"],
      65+ PlatformError.PlatformError,
      66+ FileSystem.FileSystem | Path.Path
      67+> {
      68+ const safeScenario = scenario.replace(/[^a-z0-9_-]+/gi, "-");
      69+ return Effect.gen(function* () {
      70+ const fs = yield* FileSystem.FileSystem;
      71+ const path = yield* Path.Path;
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium testkit/ProviderReplayHarness.ts:71

      makeReplayServerConfig creates a temp directory via fs.makeTempDirectory but never registers cleanup, so every call leaks the entire replay workspace (database, logs, worktrees, attachments) in the system temp directory. Repeated test runs will steadily consume disk and can fail when the temp volume fills. Consider scoping the temp directory so it is removed when the effect's scope closes.

      Also found in 2 other location(s)

      apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.testkit.ts:46

      makeAcpRegistryProviderAdapterRegistryReplayLayer allocates replayDir with fileSystem.makeTempDirectory at line 46 and never removes it. Each ACP Registry replay leaves its status.json directory behind after the layer is released, so repeated replay runs accumulate orphaned temp directories on disk.

      apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.testkit.ts:39

      makeGrokProviderAdapterRegistryReplayLayer creates replayDir with fileSystem.makeTempDirectory at line 39 without any finalizer or explicit removal. Every Grok replay run leaks that temporary directory and its status.json, causing unbounded temp-file growth across repeated test executions.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/orchestration-v2/testkit/ProviderReplayHarness.ts around line 71:
      
      `makeReplayServerConfig` creates a temp directory via `fs.makeTempDirectory` but never registers cleanup, so every call leaks the entire replay workspace (database, logs, worktrees, attachments) in the system temp directory. Repeated test runs will steadily consume disk and can fail when the temp volume fills. Consider scoping the temp directory so it is removed when the effect's scope closes.
      
      Also found in 2 other location(s):
      - apps/server/src/orchestration-v2/Adapters/AcpRegistryAdapterV2.testkit.ts:46 -- `makeAcpRegistryProviderAdapterRegistryReplayLayer` allocates `replayDir` with `fileSystem.makeTempDirectory` at line 46 and never removes it. Each ACP Registry replay leaves its `status.json` directory behind after the layer is released, so repeated replay runs accumulate orphaned temp directories on disk.
      - apps/server/src/orchestration-v2/Adapters/GrokAdapterV2.testkit.ts:39 -- `makeGrokProviderAdapterRegistryReplayLayer` creates `replayDir` with `fileSystem.makeTempDirectory` at line 39 without any finalizer or explicit removal. Every Grok replay run leaks that temporary directory and its `status.json`, causing unbounded temp-file growth across repeated test executions.
      

Sign in to join this conversation.