Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(server): attribute V2 turn diffs to the turn-start snapshot #11528

Closedsaphid(GitHub profile, opens in a new tab)wants to merge 4 commits intomain fromrefs/pull/11528/headopened View on GitHub

Summary

External changes made between V2 turns currently leak into the next turn's changed-files summary and diff, even when the agent edits nothing. For example, committing two new README lines while the thread is idle produces a misleading README.md +2 card on the next no-edit reply.

This captures a separate turn-start snapshot (<checkpoint-ref>-start) for each V2 run and diffs the completed checkpoint against it. Run-start baseline capture now also materializes the upcoming ordinal's start ref; single-turn diffs prefer the start ref when it exists and otherwise keep the previous checkpoint-to-checkpoint behavior, including when the previous turn left no checkpoint. Multi-turn comparisons continue to use their checkpoint endpoints. Changes made during a turn remain part of that turn's diff; this does not attribute changes by Git author.

A replay-safe checkpoint.baseline.cleanup outbox effect reclaims abandoned start refs after non-completed terminals, aborted provider starts, unsuccessful checkpoint capture, and restart recovery. Stopping a run before its provider turn starts queues cleanup in the same transaction as cancellation. Cleanup re-reads the projection, skips active runs and ready checkpoints owned by that run, and preserves a completed run's baseline while capture is still pending. A later turn's baseline at the same ordinal does not prevent cleanup of an abandoned start ref. Ref deletion runs under the per-workspace lock and is harmless when repeated or when the workspace has no Git repository. Rollback also deletes the start refs associated with discarded checkpoints.

Failed runs settle through the ownership-checked EventSink.writeIfRunCurrent. It now takes optional effects and queues them in the same transaction only when that write commits, so failed runs also reclaim their checkpoint baseline.

Port to the rewritten OV2 base

Restacked on 2026-09-27 onto t3code/codex-turn-mapping at 9fcc9a4bdb. Upstream now reads settings, captures the baseline and checks the start guard inside one preparation block whose failures write a failed terminal. The declined-start baseline cleanup is now queued inside that block. A follow-up test commit covers this: the start-guard scenario asserts the cleanup effect. It also passes the deletion planner's new attachmentIds input. Focused suites (15 files, 442 tests) and package typechecks in apps/server, apps/web, apps/mobile, and packages/client-runtime pass. SWE-2 Max reviewed the latest import-only restack resolution from supplied frozen evidence and found no actionable issues (process exit 0). The final same-size review-diff commit was dropped because the current base already contains the fix with stronger timestamp and split-index coverage.

Prior proposal

This is a campaign-owned adaptation of @emmsixx's #10197 (same defect, same approach), rebased onto the current t3code/codex-turn-mapping tip (9fcc9a4bdb, after the upstream force-push) with a small follow-up: getTurnDiff now consults an available turn-start ref before requiring the previous turn's checkpoint, so a single-turn diff still opens when the previous turn was interrupted and left no checkpoint. Credit for the design and most of the implementation belongs to the original PR.

Test plan

  • Rebased onto main 7812230572. Re-ran the tests, typecheck, vp lint and vp fmt --check below. Two looped tests now use it.effect.each for main's no-test-in-loop lint rule.
  • vp test run on the 14 test files this PR touches: 420 tests pass (idle commits and uncommitted idle edits excluded from no-edit turn diffs, turn edits retained, idempotent recapture, cancel/recovery/rollback ref reclaim, pending completed capture preserved, later same-ordinal baselines preserved, non-Git workspace no-ops, legacy fallback preserved)
  • Guarded-write cleanup: three failed-run tests in RunExecutionService.test.ts now assert the guarded write carries checkpoint.baseline.cleanup, and FoundationPersistence.test.ts "queues a guarded write's effects only when the run is still current" checks against the real SQLite sink that a stale attempt queues nothing. All four failed before the fix.
  • CI exposed a race in OrchestratorMcpToolkit.integration.test.ts (fan-out delivery): the test swapped the parent's delivery gate once a run was projected running, but the adapter reads the gate only when the turn starts, which this PR's turn-start snapshot delays. The race exists on main too, by 12–17 ms. Each gated delivery is now keyed by its own message id. That test passed 8 of 8 runs on this branch (5 of 8 before) and 3 of 3 on main.
  • Neighbouring ProviderTurnStartService.test.ts and ProviderEventIngestor.test.ts: 31 passed.
  • Typecheck in apps/server, apps/mobile, and packages/client-runtime: passed. apps/web reports only 2 errors in src/lib/embeddedScripts.ts (the unbash module was missing from the local install), which this PR does not change.
  • vp lint on the touched files: no errors. vp fmt --check: clean.
  • The 2026-09-27 import-only restack resolution reviewed by Devin SWE-2 Max using frozen evidence: no actionable findings, exit 0.

Targets main (originally the orchestration V2 branch from #2829), related to #4249, and addresses #10348 for orchestration V2.

SWE-2 (Devin) in T3 Code via Cursor harness. Coordination trace: T3 thread 85c6faf5-464b-48cb-a67b-9b352baff462, campaign issue saphid/t3code-personal#298.

The 2026-10-05 rebase and the guarded-write fix: Claude Opus 5.5 in T3 Code (Claude Code harness). Independent review: GPT-6.1 Sol (high reasoning) in T3 Code, no actionable findings.

    1. github-actions[bot](GitHub profile, opens in a new tab) added labelsvouch:trusted

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

      🟡 Medium

      https://github.com/pingdotgg/t3code/blob/cb75f5c6aef571f5e945a2bfa6ffeba7cbd369b0/apps/server/src/orchestration-v2/RunExecutionService.ts#L1334

      The second shouldStartProviderTurn early return interrupts the subscription fiber without queuing checkpoint.baseline.cleanup, so cancellation or supersession between the two checks leaves the baseline ref materialized by captureBaseline indefinitely. Queue the same cleanup effect in this branch before returning.

      No longer relevant as of e45fbdbd62093851fa5bbe4d5426874c3f11baba

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

      Approvability

      Verdict: Not approved

      Macroscope's review found this PR not approvable — This is a broad V2 orchestration behavior change that adds turn-start Git snapshots, automatic cleanup effects, lifecycle/recovery wiring, and wider repository-detection changes across production paths. The existing diff and checkpoint semantics change across 32 files, so the scope and side effects warrant human review.

      You can add or adjust custom eligibility rules. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    4. Addressed the RunExecutionService review finding (macroscopeapp, comment 3998769105) in e45fbdbd62.

      The second shouldStartProviderTurn early return now enqueues checkpoint.baseline.cleanup (effect id suffix before-turn) after interrupting the subscription fiber, sharing an enqueueBaselineCleanup helper with the first guard (before-start). Effect ids stay deterministic and per-attempt; outbox dedup plus the projection re-checks in the cleanup handler keep double-enqueue safe and preserve baselines still owned by an active/superseding run.

      Regression coverage: the existing "rechecks run ownership immediately before calling the provider" test now drives a true-then-false guard sequence and asserts exactly one checkpoint.baseline.cleanup effect is emitted while session.startTurn is never called. Focused suite: 9 files, 121 tests, all passing; typecheck/lint/format clean; independent re-review found no actionable findings.

    5. Head updated to c2144329b4 — the only delta vs 400e6569b0 is +230 lines of test coverage in CheckpointCaptureService.test.ts (asserts checkpoint.baseline.cleanup is enqueued when capture records error/missing). Production code is byte-identical.

      I prototyped a turn-start reuse optimization (alias the start ref to the prior checkpoint commit when the worktree is provably unchanged) to avoid a ~3s full snapshot on the prompt path, but successive review passes kept finding soundness gaps in the cheap proof (index flags, submodule gitlink config, subdirectory workspaces, attribute/filter changes). Removed it — captureBaseline always runs the authoritative temp-index capture.

    6. Bugbot is paused — on-demand spend limit reached

      Bugbot uses usage-based billing for this team and has hit its on-demand spend limit.

      A team admin can raise the spend limit in the Cursor dashboard, or wait for the next billing cycle to continue.

    7. Test Server 3 failure on 0f7305aafa is a replay-gate flake unrelated to this change: queued_cancelled_while_active/codex timed out at release_replay_gate:turn/completed (bounded yield polling under CI load). The scenario only dispatches queued-run.cancel — the diff touches planThreadDeletion (thread.delete / project removal), a disjoint path. The exact scenario passes 4/4 locally (~450ms each). A maintainer rerun should clear it; I can't re-trigger checks without admin rights.

    8. Test Server 3 flaked again on dc0398c7e8 — same queued_cancelled_while_active/codex replay gate. Verified this scenario allocates no checkpoint scope (only rollback steps do, in shared.ts), so the baseline code path in this diff never executes for it. Patch content is byte-identical to heads where it passed (142d3cba0d, 13fb96eb42, c76bf1a2da).

      Release Smoke fails on the base commit 84c9498919 itself — ERR_PNPM_UNUSED_PATCH expo-modules-core@57.0.14 during vp install --lockfile-only. Not introduced by this diff (no pnpm/patches files touched).

    9. emmsixx(GitHub profile, opens in a new tab) approved these changes

      Looked this over as the #10197 author. Same defect, same approach, rebased cleanly onto the OV2 tip.

      The turn-start (-start) baseline is the right cut: idle worktree drift stays out of the next no-edit turn, in-turn edits stay attributed, and multi-turn diffs still use checkpoint endpoints. Preferring the start ref in getTurnDiff when the prior turn left no checkpoint is a sensible follow-up.

      Cleanup looks thorough without inventing new machinery — checkpoint.baseline.cleanup is replay-safe, projection-gated (active/ready/pending-completed preserve), and wired through cancel-before-provider, non-completed terminals, capture failure, recovery, rollback, and deletion. The before-turn / before-start enqueue fix for the dual shouldStartProviderTurn guards is the right response to the earlier finding. Leaving captureBaseline as the authoritative full snapshot (no reuse alias) matches the soundness notes in the thread.

      Tests cover the behavior that matters. No redesign asks from me.

    10. Third queued_cancelled_while_active/codex replay-gate flake on a50cfdcd74 (3/6 runs on identical content; siblings on the same base pass). Since the diff wires checkpointCaptureService into the replay layer and captureBaseline runs synchronously on the run fiber at turn start, the change plausibly adds bounded latency before the transcript reaches turn/completed, while release_replay_gate burns its 10k yieldNow budget quickly when nothing else is scheduled. Re-running via a no-op amend; if it recurs, a slightly higher SCENARIO_WAIT_ATTEMPTS or a scheduled wait (not raw yields) in the gate would make the test robust to the added latency.

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

      All clear

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

      Macroscope has since reviewed this pull request. An earlier review was skipped by a cost limit; a review has now completed, so that notice no longer applies.

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

      Effect Service Conventions found 1 issue in apps/server/src/storageCleanup.ts: the service-owning module makes its canonical make constructor private.

      Posted via Macroscope — Effect Service Conventions
    14. Effect Service Conventions found 1 blocking issue. See the inline review comment on apps/server/src/storageCleanup.ts.

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

      Effect Service Conventions found 1 blocking issue in apps/server/src/storageCleanup.ts: the canonical Effect service tag was made private.

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

      Effect Service Conventions found 1 blocking issue. See the inline review comment on apps/server/src/storageCleanup.ts.

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

      Effect Service Conventions found 1 issue in apps/server/src/storageCleanup.ts: export the canonical StorageCleanup service tag so the module retains its public service shape.

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

      Effect Service Conventions found 1 blocking issue. See the inline review comment on apps/server/src/storageCleanup.ts.

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

      Effect Service Conventions found 1 blocking issue in apps/server/src/storageCleanup.ts; details and a suggested fix are in the inline review.

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

      Effect Service Conventions found 1 blocking issue. The inline review on apps/server/src/storageCleanup.ts includes the required fix.

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

      Effect Service Conventions found 1 blocking issue in apps/server/src/storageCleanup.ts. See the inline review for the suggested fix.

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

      Effect Service Conventions found 1 blocking issue; see the inline review on apps/server/src/storageCleanup.ts.

      Posted via Macroscope — Effect Service Conventions
    23. Effect Service Conventions found 1 blocking issue in apps/server/src/storageCleanup.ts; the inline review provides the fix.

      Posted via Macroscope — Effect Service Conventions
    24. Effect Service Conventions found 1 blocking issue in apps/server/src/orchestration-v2/CheckpointService.ts; the inline review includes the suggested fix.

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

      Effect Service Conventions found 1 blocking issue. See the inline review on apps/server/src/orchestration-v2/CheckpointService.ts.

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

      All clear

      Posted via Macroscope — Effect Service Conventions
    27. @juliusmarminge Please review and merge this OV2 fix when you are happy with it.

      Attribute turn diffs to the turn-start snapshot.

      Checked 18 September at 10:58 UTC: current head 3de8a8cb2a1d429fe5c624be80d1f73a0f4ce1a9 is mergeable, all checks are green or intentionally skipped, and there is no new review feedback since the owner's completed scan. Current diff: +1,200/−154.

      The latest-head independent agent review is still pending capacity; no fresh clean review is claimed. This request is for this contribution PR. The two scheduling PRs (#11592/#11635) are being held for a separate integration finding.

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

      Effect Service Conventions found 1 blocking issue in apps/server/src/vcs/GitVcsDriver.ts; the inline review includes the suggested fix.

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

      Effect Service Conventions found 1 blocking issue. See the inline review on apps/server/src/vcs/GitVcsDriver.ts.

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

      Effect Service Conventions found 2 blocking issues in apps/server/src/vcs/GitVcsDriver.ts; the inline review includes suggested fixes.

      Posted via Macroscope — Effect Service Conventions
    31. Effect Service Conventions found 3 blocking catchTag violations in apps/server/src/vcs/GitVcsDriver.ts. Two new inline comments include suggested fixes; the existing unresolved inline comment covers the third.

      Posted via Macroscope — Effect Service Conventions
    32. Effect Service Conventions found 1 new blocking issue in apps/server/src/vcs/GitVcsDriver.ts; the inline review includes the suggested fix. Two previously reported catchTag violations also remain unresolved.

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

      Effect Service Conventions found 1 new blocking issue. See the inline review on apps/server/src/vcs/GitVcsDriver.ts.

      Posted via Macroscope — Effect Service Conventions
    34. Heads-up: 0532c54 fixes a regression on the current base (t3code/codex-turn-mapping @ 37671bd3) that was blocking this PR's CI — reproduces on the base alone, so flagging it explicitly rather than smuggling it in.

      getTurnStartContext loads checkpoint scopes filtered by node_id = <run's root node>. But every root run allocates the same deterministic name:root scope id, so a queued run's checkpoint-scope.created upserts the shared row onto its root node. For the earlier (still starting) run, the scoped read then returns zero scopes → providerTurnStart throws "missing execution projection state" → outbox retries forever → run stuck at starting (observed: queued_turn/* replay fixtures and two ProviderSwitch handoff tests all timing out on base).

      The read now also resolves the scope referenced by the run root node's checkpointScopeId — the same join providerTurnStart and startNextQueuedRun use — plus a regression test that reproduces the upsert clobber. Verified: the 6 queued_* fixtures + 2 ProviderSwitch timeouts all pass with the fix on the unmodified base, and on this branch.

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

      All clear

      Posted via Macroscope — Effect Service Conventions
    36. Update on the note above: upstream's new base (61a3501b15) already fixes the same regression itself — getTurnStartContext now resolves checkpoint scopes via scope_id IN the run root nodes' checkpointScopeId references, and getTurnStartHistory uses sql.in(runIds) directly (dropping the raw JSON.stringify that broke preferSchemaOverJson). My two fix commits were dropped on rebase as superseded; upstream also added equivalent regression coverage in TurnStartReads.test.ts. Rebased head is 20fdfa1.

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

      All clear

      Posted via Macroscope — Effect Service Conventions
    38. Note

      This comment is posted by Julius' dot

      Can a maintainer clarify the approved scope and landing target for this between-turn snapshot fix? The direction on #4249 was to port after #2829 merges, and the later checkpoint update says attribution remains deferred. It is unclear whether that deferral includes this narrower approach, which excludes idle changes but deliberately retains changes made during a turn.

      At 0d9c082, this targets the V2 preview branch and introduces per-turn start refs and replay-safe lifecycle cleanup. The bug report, focused tests and historical before/after evidence are useful. Please link the maintainer decision approving this scope on the preview branch, or confirm the intended base/landing sequence under prior approval. Leaving this open pending that clarification; this is not a correctness approval.

    39. juliusmarminge closed this

    40. juliusmarminge added labelstriage:keep-open

Sign in to join this conversation.