Skip to content
Source
Sign inSign up
pingdotgg/t3code

fix(server): recover threads whose worktree was removed #6197

Closedmackinleysmith(GitHub profile, opens in a new tab)wants to merge 11 commits intomain fromrefs/pull/6197/headopened View on GitHub

Problem

A thread whose git worktree is removed becomes permanently unusable, even though nothing about the conversation was actually lost.

The failure needs two things to line up, and neither is rare:

  1. The provider session drops. Auto-update restarts call stopAll; the idle reaper stops sessions after 30 minutes. Both are meant to be survivable — that is what the persisted resume cursor is for.
  2. The thread's worktree is gone. recoverSessionForThread replays the persisted cwd verbatim, with no check that it still exists.

Alone, each is harmless. Together the resume fails, and because provider CLIs key their transcript store off the cwd, the failure surfaces as a generic session not found — which toSessionError then relabelled as ProviderAdapterSessionNotFoundError: Unknown claudeAgent adapter thread. That reads like the thread is gone. It isn't: the transcript is still on disk and the full message history is still in our own projection. Nothing clears the stale resume cursor either (ProviderSessionDirectory.upsert deliberately preserves it), so every later turn repeats the identical doomed resume.

Observed on a real host: a 17-minute-old thread, never deleted or archived, died on the next turn after an auto-update restart. Its worktree was gone; its transcript and all 12 of its messages were intact. Across that machine, 140 of 166 live threads pointed at a worktree that no longer existed — including threads with 167, 144, and 126 messages.

What this changes

Four commits, each independently reviewable:

CommitWhat
stop reporting non-session failures as unknown sessionstoSessionError matched a bare "not found" substring. The SDK uses that same wording for a missing CLI binary and for missing files under the resumed cwd, so install problems and dead directories were both reported as unknown threads. Now requires the message to be about a session.
add worktree prune to the git driverA directory removed without git worktree remove leaves an admin entry claiming the path, which makes git worktree add refuse it. git worktree prune only drops entries whose directory is already gone.
refuse to resume a session into a missing working directoryStat the persisted cwd before resuming; fail with a typed ProviderSessionWorkspaceMissingError instead of launching a doomed CLI. A failed stat is treated as present, so a transient error cannot strand a healthy thread.
recreate a thread's worktree before starting a turnTurn start prunes and recreates the worktree from the thread's branch before the session is resolved. Best-effort — on failure the turn proceeds so existing handling reports the real reason. Either outcome appends a thread activity, because a recreated worktree means uncommitted work in the old one is gone and that should be visible.

Testing

  • typecheck clean.
  • 260 tests pass across ProviderService, ProviderCommandReactor, GitVcsDriverCore, GitWorkflowService, and server.test.ts.
  • Both new tests were verified to fail without their fix — each production change was disabled in turn and the corresponding test went red, then restored.

Notes for reviewers

  • ProviderService now requires FileSystem. Production wiring already provided it; three test layers did not. Fixing that surfaced a latent issue where NodeServices.layer was passed as a sibling inside Layer.mergeAll, which builds in parallel and would not have satisfied the dependency — moved beneath via Layer.provideMerge.
  • appendWorkspaceActivity deliberately duplicates the shape of appendProviderFailureActivity rather than generalising it, because the latter hardcodes tone: "error" and a closed kind union that would have to widen across every existing call site.

What this does not fix

It does not stop worktrees from being deleted. I could not determine the cause — there is no cleanup timer, no script, and no automatic removal in the codebase (removeWorktree is only reachable from the thread-delete flow). This makes the symptom survivable rather than absent; the deletion itself deserves its own investigation.

Recovery is also limited to threads whose branch still exists. On the host above that was 136 of 140 — but a thread whose branch is also gone will still fail, now with a clear typed error instead of a misleading one.


Note

Medium Risk Touches turn-start orchestration, provider session resume, and git worktree operations on the critical path for every turn with a worktree; behavior is mostly best-effort repair plus explicit typed failures when repair cannot run.

Overview Threads could become stuck after a provider restart when the thread’s git worktree directory was gone: resume replayed the persisted cwd and provider CLIs reported misleading “session not found” errors.

Turn start now runs ensureThreadWorkspace before resolving the provider session: if the worktree path is missing or not a directory, it git worktree prunes stale entries, recreates the worktree from the thread branch (best-effort), and appends provider.workspace.restored thread activity on success or failure.

Provider resume paths (startSession with a resume cursor and recoverSessionForThread) stat the cwd and fail with ProviderSessionWorkspaceMissingError instead of launching the adapter when the workspace is unusable; the resume cursor is preserved.

The git stack gains pruneWorktrees (git worktree prune). The Claude adapter only maps session-specific “not found” patterns to session errors. Tests and layers are updated so FileSystem / NodeServices satisfy session-recovery checks.

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

Note

Recover provider threads whose git worktree directory has been removed

  • Before starting a provider turn, ProviderCommandReactor now calls ensureThreadWorkspace, which checks if the thread's worktree path exists and is a directory, runs git worktree prune to drop stale admin entries, then recreates the worktree from the thread branch if missing. A workspace restoration activity is appended to the thread on success or failure.
  • ProviderService now guards session resume paths with assertResumeWorkspaceExists, failing with the new ProviderSessionWorkspaceMissingError when the persisted cwd is missing or not a directory. Fresh sessions without a resume cursor are unaffected.
  • GitWorkflowService and GitVcsDriver gain a pruneWorktrees(cwd) method that runs git worktree prune with a 15s timeout.
  • The Claude adapter's toSessionError now matches session-not-found errors against specific regex patterns instead of a substring check, preventing misclassification of unrelated 'not found' errors (e.g. missing CLI binary or files under the resumed cwd).
Macroscope summarized 9e0229a.
    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 Plus

      Run ID: 90ba6d09-4063-4ce8-8038-fabb89f33183

      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

      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. Confirmed and fixed in ec24a7fa — thanks, this was a real gap and more significant than medium.

      Turn start does not reach recoverSessionForThread at all in the scenario this PR targets. buildSendTurnRequestForThread calls ensureSessionForThread first; after a restart there is no live adapter session, so existingSessionThreadId is null and it goes straight to startProviderSession → providerService.startSession, which resumes from the persisted cursor. By the time sendTurn runs, hasSession is true, so the recovery path never fires. The guard was sitting on the less-travelled branch.

      It was masked because ensureThreadWorkspace recreates the worktree before the turn, so the guard is only needed when that repair fails — branch also deleted, which was 4 of 140 cases on the host I profiled. Real, just narrow.

      Fix extracts the check into assertResumeWorkspaceExists and applies it to startSession too, gated on effectiveResumeCursor !== undefined so a fresh session with a not-yet-provisioned workspace is unaffected. New test covers the start-session path specifically; verified it fails with the guard disabled.

      The doc-comment point was also correct — it claimed the reactor catches this error and retries. It does neither. Rewritten to describe what actually happens.

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

      Approvability

      Verdict: Needs human review

      1 blocking correctness issue found. This PR introduces new automatic worktree recovery capability, not just a simple bug fix. The changes add significant new runtime behavior including detecting missing workspaces, pruning stale git entries, and recreating worktrees. Additionally, there is an unresolved high-severity finding about the git worktree prune command missing the --expire now flag, which may prevent the recovery from working correctly.

      You can customize Macroscope's approvability policy. [Learn more](https://docs.macroscope.com/approvability#example-custom-eligibility-rules).
    5. @@ -2980,3 +2980,11 @@
      29802980 });
      29812981 });
      29822982
      2983+ const pruneWorktrees: GitVcsDriver.GitVcsDriver["Service"]["pruneWorktrees"] = Effect.fn(
      2984+ "pruneWorktrees",
      2985+ )(function* (input) {
      2986+ // Only drops administrative entries whose working directory is already
      2987+ // gone, so this is safe to run before re-adding a worktree at a path a
      2988+ // stale entry still claims. Without it `git worktree add` refuses the
      2989+ // path outright.
      2990+ yield* executeGit("GitVcsDriver.pruneWorktrees", input.cwd, ["worktree", "prune"], {
      macroscopeapp[bot](GitHub profile, opens in a new tab)commented

      🟠 High vcs/GitVcsDriverCore.ts:2990

      git worktree prune without --expire now applies Git's default expiry threshold (typically three months), so a worktree entry whose directory was just deleted is not removed. The subsequent git worktree add at the same path still fails because Git considers the path claimed. This defeats the stated purpose of this method ("safe to run before re-adding a worktree at a path a stale entry still claims"). Add --expire, now so entries for already-missing directories are pruned immediately.

      🤖 Copy this AI Prompt to have your agent fix this:
      In file @apps/server/src/vcs/GitVcsDriverCore.ts around line 2990:
      
      `git worktree prune` without `--expire now` applies Git's default expiry threshold (typically three months), so a worktree entry whose directory was just deleted is **not** removed. The subsequent `git worktree add` at the same path still fails because Git considers the path claimed. This defeats the stated purpose of this method ("safe to run before re-adding a worktree at a path a stale entry still claims"). Add `--expire`, `now` so entries for already-missing directories are pruned immediately.
    6. Worked through all four findings — three valid and fixed in 2f0e095d, one I believe is incorrect.

      Valid — resolveProject unguarded (High). Confirmed, and it was worse than described because I widened it. hasHandledTurnStartRecently caches the dedupe key before any work, and processDomainEventSafely only logs a warning — so a failure escaping this best-effort helper drops the turn with no failure activity for the full 30 minute TTL. A resolveProject call already existed in this handler, but only on the first-turn branch; putting one on every turn made a narrow failure mode general. Guarded as suggested.

      Valid — exists() accepts a non-directory (High). Correct. Now stats and requires type === "Directory". One refinement on the suggested fix: a naive stat + orElseSucceed(true) inverts the guard, because stat on a missing path fails and would be read as "fine" — which is the case the guard exists for. Only NotFound/BadArgument count as unusable; other failures still pass so a permissions or transient error cannot strand a healthy thread. Added a test with a plain file at the worktree path; verified it fails against the old exists() check.

      Valid — null resume cursor (Low, from Bugbot). A persisted cursor is null rather than undefined when there is no resume state, so !== undefined treated a non-resuming start as a resume. Now excludes both.

      Not valid — git worktree prune needs --expire now (High). Git prunes entries whose directory is already gone unconditionally; the expiry threshold applies to other kinds of stale entry, not this one. Tested directly on git 2.50.1:

      $ git worktree add /tmp/wtt/wt2 -b feat2 && rm -rf /tmp/wtt/wt2
      $ git worktree prune -v --dry-run
      Removing worktrees/wt2: gitdir file points to non-existent location

      and a plain prune followed by git worktree add at the same path succeeds. Adding --expire now would widen what gets pruned beyond this method's purpose, so I have left it as is — happy to revisit if you have a case where the plain form is insufficient.

    7. Valid — fixed in c2cec3ae.

      Confirmed by convention rather than just reasoning: this file re-raises interrupts in eight other places (processDomainEventSafely, the title-regeneration handlers, and others), and my three catchCause sites in ensureThreadWorkspace were the only ones that did not. Since the helper runs inline on the turn-start fiber, a shutdown or worker drain mid-restore was flattened into a warning (or false for createWorktree) and the fiber continued into session start — which for a PR about session lifecycle is a bad way to lose a shutdown.

      All three now re-raise via Effect.failCause when Cause.hasInterruptsOnly(cause).

      Scoped deliberately to the catchCause sites: the two orElseSucceed recoveries in the same helper (fileSystem.exists, resolveProject) recover from a typed failure only and never observe an interrupt, so they did not need changing. Same for the Effect.catch on stat in ProviderService.

      Also rebased onto the main merge that landed on the branch. Re-verified against it: typecheck clean, 262 tests passing across the six affected files.

    8. Cursor Bugbot has reviewed your changes using high effort and found 1 potential issue.

      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).

      Want fixes drafted automatically? Bugbot Autofix can create code changes for findings. A team admin can enable Autofix in the Cursor dashboard.

      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 9e0229a27068080d9e1f9c65b510c78becc6e6c1. Configure [here](https://www.cursor.com/dashboard/bugbot).
      @@ -368,0 +480,21 @@
      480+ workspaceRoot,
      481+ cause: Cause.pretty(cause),
      482+ }),
      483+ ),
      484+ );
      485+
      486+ const restored = yield* gitWorkflow
      487+ .createWorktree({ cwd: workspaceRoot, refName: branch, path: worktreePath })
      488+ .pipe(
      489+ Effect.as(true),
      490+ Effect.catchCause((cause) =>
      491+ Cause.hasInterruptsOnly(cause)
      492+ ? Effect.failCause(cause)
      493+ : Effect.logWarning("provider.workspace.restore.failed", {
      494+ threadId: input.thread.threadId,
      495+ worktreePath,
      496+ branch,
      497+ cause: Cause.pretty(cause),
      498+ }).pipe(Effect.as(false)),
      499+ ),
      500+ );

      Restore skips live session restart

      Medium Severity

      ensureThreadWorkspace can recreate a missing worktree at the same path string, but that success is never signaled to ensureSessionForThread. A still-live adapter session compares equal on cwd and is reused, so the provider process can keep a stale deleted inode as its working directory while the new directory sits unused on disk.

      Additional Locations (1)
      Fix in Cursor Fix in Web
      Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit 9e0229a27068080d9e1f9c65b510c78becc6e6c1. Configure [here](https://www.cursor.com/dashboard/bugbot).
    9. Note

      🤖 GPT-5.6 Sol responding on behalf of Theo

      Closing in favor of #7839. The missing-worktree recovery from this PR was extracted and merged there. Any remaining session-resume or error-classification changes can be proposed separately.

Sign in to join this conversation.