Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(orchestrator): session audit remediation — error fidelity, session resume, reconcile visibility #3677

Closedjuliusmarmingewants to merge 16 commits intot3code/codex-turn-mapping fromt3code/orchestration-v2-audit-fixesopened View on GitHub

juliusmarmingecommented

Stacked on #2829 (whose branch now carries the shared C0 continuation plumbing from #3578/#3860). Remediation work from the full v2 session audit — plan and adversarially-verified findings in .plans/22-orchestration-v2-audit-remediation.md / .plans/22-orchestration-v2-audit-findings.json.

Restructure note

This PR was reorganized to combine strengths with @mwolson's parallel stack:

  • C0 (ea57e97d58, shared continuation plumbing) was fast-forwarded onto the base branch.
  • Claude session-continuity fixes (is_error run status + idle-resume hardening, with replay fixtures claude_result_is_error, claude_idle_resume, and the new advance_clock fixture step) moved to #3860, rebased onto its continuation architecture.
  • Our previous turn.wakeup/ProviderWakeupService implementation was dropped in favor of the C0 continuation design.
  • Grok/ACP lifecycle work lives in #3578.

What remains here (orthogonal audit fixes)

  • Preserve real failure causes (plan #2): makeProviderFailure walks the wrapper-error cause chain; failed runs no longer persist only "Claude Agent SDK query failed." with the root cause recorded nowhere. App-verified with a broken Claude binary path.
  • Cursor failure correlation data (plan #3): failed cursor turns persist run id / requestId / duration (the SDK exposes no error text on results — raised with Cursor alongside the EPIPE report).
  • Native-log failure frames (plan #4): Claude and Cursor runners write runner.error frames (redacted cause chain) at every fallible SDK boundary, so a failed turn is explainable from the log. App-verified.
  • Surface reconcile cancellations (plan #5): startup/shutdown reconcile appends a visible "Run interrupted" item with the reason instead of silently eating the user's turn. App-verified via kill-mid-turn.
  • Codex shared-session log routing (plan #9): protocol frames route per native thread id to the owning app thread's log file; rotation of the opener's log no longer destroys other threads' ground truth. App-verified with a real codex subagent spawn.
  • ACP streaming-delta coalescing (plan #10): subagent per-token emits persisted ~2700 events for one 6KB result; now throttled to one snapshot per 100ms window with a guaranteed flush at task completion and at turn finalize. Fixture-asserted.
  • OpenCode file_search output/error (plan #12): tool outcomes preserved on the contract + adapter. App-verified with a real OpenCode agent.
  • claude_text_segments regression fixture (plan #11): locks per-uuid assistant text segmentation.

Each fix carries replay-fixture or unit coverage plus a real-agent verification round in an isolated dev instance, documented per item in the plan file.

🤖 Generated with Claude Code


Note

Medium Risk Touches core orchestration adapters, event persistence, and runtime recovery paths; mistakes could mis-route logs, drop streamed subagent text, or change how failures appear to users.

Overview Implements orthogonal fixes from the orchestration v2 session audit (tracked in .plans/22-orchestration-v2-audit-remediation.md and .plans/22-orchestration-v2-audit-findings.json), while Claude is_error/wakeup work stays in other PRs.

Failure fidelity: makeProviderFailure now walks nested causes (with deduped messages and propagated codes). Cursor failed turns persist correlation text (requestId, duration) when the SDK omits error bodies. Claude and Cursor runners log runner.error frames on SDK failures so native logs explain failed turns.

Runtime recovery: ProviderRuntimeRecoveryService emits a user-visible Run interrupted error turn item when reconcile cancels in-progress runs, instead of silent cancellation.

Codex logging: Shared app-server protocol frames route to the owning app thread’s log via a native-thread-id map, not only the opener’s file.

ACP / OpenCode: Grok subagent assistant streaming is coalesced (~100ms snapshots with flush on completion and turn finalize) to cut per-token event amplification. OpenCode file_search items now carry tool output/error on the adapter side.

Tests cover cause chains, codex log routing, and recovery reconcile events.

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

Note

Fix orchestrator session audit issues: error fidelity, session resume visibility, and subagent stream coalescing

  • Subagent stream coalescing: Throttles per-token ACP subagent assistant updates into periodic 100ms snapshots via streamSubagentAssistant/flushSubagentAssistant in AcpAdapterV2.ts, preventing excessive event emission while ensuring final text is always persisted at turn/task completion.
  • Reconciliation visibility: ProviderRuntimeRecoveryService.reconcileProjection now emits a synthesized 'Run interrupted' error turn item when cancelling in-progress runs, giving users a visible indication of runtime-initiated cancellations.
  • Error fidelity: makeProviderFailure in ProviderFailure.ts now walks up to 6 levels of nested error causes, deduplicates repeated messages, and propagates error codes from any level in the chain.
  • Protocol log routing: Codex adapter routes native protocol log frames to the correct app thread by maintaining a map of native thread IDs to app ThreadIds, instead of always logging under the opener thread.
  • Runner error logging: Claude and Cursor adapters now emit runner.error frames to native protocol logs on SDK failures for lifecycle operations.
  • file_search turn items: Now include optional output and error fields from the tool result in OpenCodeAdapterV2.ts and the contracts schema.
Macroscope summarized 269e5a8.
    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: 29545e92-bfbb-4173-abfd-4a6c6c012d5b

      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
      • Commit unit tests in branch `t3code/orchestration-v2-audit-fixes`

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

    3. apps/server/src/orchestration-v2/RunExecutionService.ts line 183OutdatedResolvedby juliusmarminge
      apps/server/src/orchestration-v2/ProviderWakeupService.ts line 162OutdatedResolvedby juliusmarminge
    4. macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      Approvability

      Verdict: Needs human review

      4 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).
    5. Cursor Bugbot has reviewed your changes using high effort and found 3 potential issues.

      There are 4 total unresolved issues (including 1 from previous review).

      Autofix Details

      Bugbot Autofix prepared fixes for all 3 issues found in the latest run.

      • ✅ Fixed: Scheduled flush flag not cleared
        • Added subagent.streamFlushScheduled = false in flushSubagentAssistant so that the schedule flag is properly reset on terminal/synchronous flushes, preventing subsequent chunks from hitting the early return.
      • ✅ Fixed: Turn end skips subagent flush
        • Added a loop in finalizeTurn that iterates over context.subagents and calls flushSubagentAssistant for any subagent with streamPendingText === true, ensuring coalesced text is persisted before the turn is marked finalized.
      • ✅ Resolved by another fix: Concurrent duplicate subagent snapshots
        • The Bug 1 fix (clearing streamFlushScheduled in flushSubagentAssistant) ensures the forked sleep callback sees streamPendingText === false after a synchronous flush, preventing the duplicate emit race.

      Create PR

      Or push these changes by commenting:

      @cursor push 59569dd592
      Preview (pingdotgg/t3code@59569dd592)
      diff --git a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts
      --- a/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts
      +++ b/apps/server/src/orchestration-v2/Adapters/AcpAdapterV2.ts
      @@ -915,6 +915,7 @@
                   subagent.assistantText += finalText;
                 }
                 subagent.streamPendingText = false;
      +          subagent.streamFlushScheduled = false;
                 yield* emitSubagentAssistantSnapshot(subagent);
               });
       
      @@ -2054,6 +2055,11 @@
                 if (context.finalized) return;
                 context.finalized = true;
                 yield* closeTextStreams(context);
      +          for (const subagent of context.subagents.values()) {
      +            if (subagent.streamPendingText) {
      +              yield* flushSubagentAssistant(subagent);
      +            }
      +          }
                 const now = yield* DateTime.now;
                 const turn = providerTurnPayload(context, status, now);
                 yield* Ref.update(providerTurns, (current) => {
      You can send follow-ups to the cloud agent here.
    6. Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

      Autofix Details

      Bugbot Autofix prepared a fix for the issue found in the latest run.

      • ✅ Fixed: Coalesced wakeup requests silently discarded
        • Added a per-thread pendingWakeups map that stores coalesced requests and re-offers them to the relay queue when the in-flight dispatch completes, ensuring no wakeup is permanently lost.

      Create PR

      Or push these changes by commenting:

      @cursor push f013d3849b
      Preview (pingdotgg/t3code@f013d3849b)
      diff --git a/apps/server/src/orchestration-v2/ProviderWakeupService.ts b/apps/server/src/orchestration-v2/ProviderWakeupService.ts
      --- a/apps/server/src/orchestration-v2/ProviderWakeupService.ts
      +++ b/apps/server/src/orchestration-v2/ProviderWakeupService.ts
      @@ -171,9 +171,11 @@
           // Wakeups dispatch concurrently, one in flight per thread: quiescence
           // waiting for one busy thread must not head-of-line-block every other
           // thread's wakeup (which could be superseded while it waits). A wakeup
      -    // arriving while its thread already has one in flight is coalesced away —
      -    // the adapter buffers all pending activity behind a single attach.
      +    // arriving while its thread already has one in flight is held pending;
      +    // when the in-flight dispatch finishes it re-offers the pending request
      +    // so a failed dispatch does not permanently lose the wakeup.
           const inFlightThreads = yield* Ref.make(new Set<ThreadId>());
      +    const pendingWakeups = yield* Ref.make(new Map<ThreadId, ProviderWakeupRequest>());
           return yield* relay.take.pipe(
             Effect.flatMap((input) =>
               Ref.modify(inFlightThreads, (current) => {
      @@ -192,16 +194,37 @@
                             const next = new Set(current);
                             next.delete(input.threadId);
                             return next;
      -                    }),
      +                    }).pipe(
      +                      Effect.andThen(
      +                        Ref.modify(pendingWakeups, (m) => {
      +                          const pending = m.get(input.threadId);
      +                          if (pending === undefined) return [undefined, m] as const;
      +                          const next = new Map(m);
      +                          next.delete(input.threadId);
      +                          return [pending, next] as const;
      +                        }),
      +                      ),
      +                      Effect.flatMap((pending) =>
      +                        pending !== undefined ? relay.offer(pending) : Effect.void,
      +                      ),
      +                    ),
                         ),
                         Effect.forkScoped,
                         Effect.asVoid,
                       )
      -              : Effect.logInfo("orchestration-v2.provider-wakeup.coalesced", {
      -                  threadId: input.threadId,
      -                  providerThreadId: input.providerThreadId,
      -                  origin: input.origin,
      -                }),
      +              : Ref.update(pendingWakeups, (m) => {
      +                  const next = new Map(m);
      +                  next.set(input.threadId, input);
      +                  return next;
      +                }).pipe(
      +                  Effect.andThen(
      +                    Effect.logInfo("orchestration-v2.provider-wakeup.coalesced", {
      +                      threadId: input.threadId,
      +                      providerThreadId: input.providerThreadId,
      +                      origin: input.origin,
      +                    }),
      +                  ),
      +                ),
                 ),
               ),
             ),
      You can send follow-ups to the cloud agent here.
    7. Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

      Autofix Details

      Bugbot Autofix prepared a fix for the issue found in the latest run.

      • ✅ Fixed: Wakeup drain lacks interrupt cleanup
        • Added Effect.onInterrupt handler to the forked drainThread that deletes the thread's entry from threadStates upon fiber interruption, allowing subsequent wakeups to claim and dispatch normally.

      Create PR

      Or push these changes by commenting:

      @cursor push 1e87251a89
      Preview (pingdotgg/t3code@1e87251a89)
      diff --git a/apps/server/src/orchestration-v2/ProviderWakeupService.ts b/apps/server/src/orchestration-v2/ProviderWakeupService.ts
      --- a/apps/server/src/orchestration-v2/ProviderWakeupService.ts
      +++ b/apps/server/src/orchestration-v2/ProviderWakeupService.ts
      @@ -213,7 +213,17 @@
               }).pipe(
                 Effect.flatMap((claimed) =>
                   claimed
      -              ? drainThread(input).pipe(Effect.forkScoped, Effect.asVoid)
      +              ? drainThread(input).pipe(
      +                  Effect.onInterrupt(() =>
      +                    Ref.update(threadStates, (current) => {
      +                      const next = new Map(current);
      +                      next.delete(input.threadId);
      +                      return next;
      +                    }),
      +                  ),
      +                  Effect.forkScoped,
      +                  Effect.asVoid,
      +                )
                     : Effect.logInfo("orchestration-v2.provider-wakeup.follow-up-parked", {
                         threadId: input.threadId,
                         providerThreadId: input.providerThreadId,
      You can send follow-ups to the cloud agent here.
      apps/server/src/orchestration-v2/ProviderWakeupService.ts line 217OutdatedResolvedby juliusmarminge
    8. @@ -89,0 +103,21 @@
      103+} {
      104+ const messages: Array<string> = [];
      105+ let code: string | undefined;
      106+ const seen = new Set<unknown>();
      107+ let current: unknown = value;
      108+ for (let depth = 0; depth < MAX_FAILURE_CAUSE_DEPTH; depth += 1) {
      109+ if (current === null || current === undefined || seen.has(current)) break;
      110+ seen.add(current);
      111+ if (typeof current === "string") {
      112+ if (current.length > 0 && messages.at(-1) !== current) messages.push(current);
      113+ break;
      114+ }
      115+ if (typeof current !== "object" && !(current instanceof Error)) break;
      116+ const message =
      117+ current instanceof Error ? current.message : stringField(current, "message");
      118+ if (typeof message === "string" && message.length > 0 && messages.at(-1) !== message) {
      119+ messages.push(message);
      120+ }
      121+ code ??= stringField(current, "code");
      122+ current = (current as { readonly cause?: unknown }).cause;
      123+ }
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium orchestration-v2/ProviderFailure.ts:122

      causeChain reads (current as { readonly cause?: unknown }).cause without exception protection. If a provider error or nested wrapper exposes cause through a throwing getter or Proxy, makeProviderFailure throws while processing the original failure, so no transport-safe failure is ever produced or persisted. The message and code accesses are already guarded via stringField and instanceof Error, but the .cause read on line 122 is not. Consider wrapping the .cause access in try/catch and stopping traversal when access fails.

      -    current = (current as { readonly cause?: unknown }).cause;
      +    try {
      +      current = (current as { readonly cause?: unknown }).cause;
      +    } catch {
      +      break;
      +    }
      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/server/src/orchestration-v2/ProviderFailure.ts around lines 122-123:
      
      `causeChain` reads `(current as { readonly cause?: unknown }).cause` without exception protection. If a provider error or nested wrapper exposes `cause` through a throwing getter or Proxy, `makeProviderFailure` throws while processing the original failure, so no transport-safe failure is ever produced or persisted. The `message` and `code` accesses are already guarded via `stringField` and `instanceof Error`, but the `.cause` read on line 122 is not. Consider wrapping the `.cause` access in `try`/`catch` and stopping traversal when access fails.
      @@ -1045,3 +1052,4 @@
      10451052 }),
      10461053 );
      10471054
      1055+const CODEX_RAW_THREAD_ID_PATTERN = /"threadId"\s*:\s*"([^"]+)"/;
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium Adapters/CodexAdapterV2.ts:1055

      CODEX_RAW_THREAD_ID_PATTERN regex-scans the raw frame string and matches the first "threadId" anywhere, including user-controlled text inside params.input. When a prompt contains JSON like {"threadId":"<other id>"}, the regex returns that embedded value instead of the protocol field params.threadId, so the frame is routed to the wrong thread log. Parsing the JSON payload and inspecting structured protocol fields would avoid matching arbitrary user content.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/server/src/orchestration-v2/Adapters/CodexAdapterV2.ts around line 1055:
      
      `CODEX_RAW_THREAD_ID_PATTERN` regex-scans the raw frame string and matches the first `"threadId"` anywhere, including user-controlled text inside `params.input`. When a prompt contains JSON like `{"threadId":"<other id>"}`, the regex returns that embedded value instead of the protocol field `params.threadId`, so the frame is routed to the wrong thread log. Parsing the JSON payload and inspecting structured protocol fields would avoid matching arbitrary user content.
    9. @@ -90,7 +114,21 @@
      114+ }
      115+ if (typeof current !== "object" && !(current instanceof Error)) break;
      116+ const message =
      117+ current instanceof Error ? current.message : stringField(current, "message");
      118+ if (typeof message === "string" && message.length > 0 && messages.at(-1) !== message) {
      119+ messages.push(message);
      120+ }
      121+ code ??= stringField(current, "code");
      122+ current = (current as { readonly cause?: unknown }).cause;
      123+ }
      124+ return { messages, code };
      125+}
      126+
      90127 export function makeProviderFailure(input: {
      91128 readonly cause?: unknown;
      92129 readonly message?: string | undefined;
      93130 readonly code?: string | null | undefined;
      94131 readonly class?: OrchestrationV2ProviderFailureClass;
      95132 readonly retryable?: boolean | null;
      96133 }): OrchestrationV2ProviderFailure {
      134+ const chain = causeChain(input.cause);
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium orchestration-v2/ProviderFailure.ts:134

      When makeProviderFailure is called with both input.message and a nested cause whose own message already contains the caller-supplied text, the cause chain messages are deduplicated only against each other, not against input.message. For example, a caller passing "Workspace preparation failed: inner" alongside a cause chain ["wrapper", "inner"] produces "Workspace preparation failed: inner ← wrapper ← inner" — the inner segment appears twice because causeChain deduplicates adjacent messages within the chain but makeProviderFailure never checks whether chainMessage segments are already embedded in input.message. Consider deduplicating chain messages against the caller-supplied message before concatenating.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/server/src/orchestration-v2/ProviderFailure.ts around line 134:
      
      When `makeProviderFailure` is called with both `input.message` and a nested `cause` whose own message already contains the caller-supplied text, the cause chain messages are deduplicated only against each other, not against `input.message`. For example, a caller passing `"Workspace preparation failed: inner"` alongside a cause chain `["wrapper", "inner"]` produces `"Workspace preparation failed: inner ← wrapper ← inner"` — the `inner` segment appears twice because `causeChain` deduplicates adjacent messages within the chain but `makeProviderFailure` never checks whether `chainMessage` segments are already embedded in `input.message`. Consider deduplicating chain messages against the caller-supplied message before concatenating.
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟡 Medium

      https://github.com/pingdotgg/t3code/blob/269e5a8f89300020052b2261809b5dd9b2b87d64/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts#L608

      The interrupt, close, and forkSession operations can fail but don't emit a runner.error log frame, so the native protocol log still ends without explaining lifecycle failures. logRunnerFailure is only applied to query.open, prompt.offer, and query.set_model, while interrupt, closeClaudeQuery, and forkClaudeSession errors go unlogged. Consider wrapping those operations with logRunnerFailure as well.

      🚀 Reply "fix it for me" or copy this AI Prompt for your agent:
      In file @apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts around line 608:
      
      The `interrupt`, `close`, and `forkSession` operations can fail but don't emit a `runner.error` log frame, so the native protocol log still ends without explaining lifecycle failures. `logRunnerFailure` is only applied to `query.open`, `prompt.offer`, and `query.set_model`, while `interrupt`, `closeClaudeQuery`, and `forkClaudeSession` errors go unlogged. Consider wrapping those operations with `logRunnerFailure` as well.
    10. Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

      Fix All in Cursor Bugbot Autofix is [ON](https://www.cursor.com/dashboard/bugbot), but a cloud agent failed to start. Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 269e5a8f89300020052b2261809b5dd9b2b87d64. Configure [here](https://www.cursor.com/dashboard/bugbot).
      @@ -1354,3 +1415,6 @@
      13541415 readonly startedAt: DateTime.Utc;
      13551416 }) =>
      13561417 Effect.gen(function* () {
      1418+ const nativeThreadId = input.turnInput.providerThread.nativeThreadRef?.nativeId;
      1419+ if (nativeThreadId !== undefined && nativeThreadId !== null) {
      1420+ logThreadRoutes.set(nativeThreadId, input.turnInput.threadId);

      Codex log routes register late

      Medium Severity

      Per-frame Codex protocol logging only learns nativeThreadId → app ThreadId when registerRootTurn runs at the end of startTurn or when a subagent child thread is registered. ensureThread and resumeThread already obtain the native thread id but never update logThreadRoutes, so multiplexed siblings keep writing to the opener’s log until their first turn completes, partially defeating audit plan #9.

      Additional Locations (2)
      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 269e5a8f89300020052b2261809b5dd9b2b87d64. Configure [here](https://www.cursor.com/dashboard/bugbot).
    11. juliusmarminge closed this

    12. Adding the evaluation rationale to this already-closed PR: the audit findings are valuable, but the branch is too broad and stale to land as one unit. A current-base restack produced 168 passing focused tests but one real ACP regression—the new subagent delta coalescer breaks the existing carryover projection assertion—and also required formatting cleanup. The useful error-fidelity, recovery visibility, logging, and coalescing changes should be split into focused current-base PRs with dedicated regressions.

Sign in to join this conversation.