Skip to content

fix(worktrees): force-remove clean worktree with initialised submodule - #9096

Merged
nwparker merged 2 commits into
mainfrom
nwparker/fix-8670-wave2
Jul 17, 2026
Merged

nwparker merged 2 commits into
mainfrom
nwparker/fix-8670-wave2

Conversation

@nwparker

Copy link
Copy Markdown
Contributor

Summary

Fixes #8670

Deleting a clean Orca workspace failed when its linked worktree had an initialised submodule. Git refuses non-force git worktree remove for any worktree with initialised submodules (fatal: working trees containing submodules cannot be moved or removed), even when parent and submodule are fully clean. Orca's skip-confirm / non-force delete path always hit this and left the worktree registered on disk.

Credit: based on @xianjianlf2's fix in #8704 (kept as commit author). Rebased onto current main, adversarial review, and extra regression coverage.

Description

On that specific Git refusal (local + SSH relay):

  1. Re-prove cleanliness with git status --porcelain --untracked-files=all in the worktree (dirty submodule content shows as M <sub> / similar on the parent).
  2. If clean → retry git worktree remove --force.
  3. If dirty → throw the existing "Worktree has uncommitted or untracked changes." error (enables Force Delete recovery toast) — never auto-force-delete dirty trees.
  4. Callers that already passed force: true get no retry (first attempt already used --force).

Shared predicate: src/shared/worktree-submodule-removal.ts. Both runners pin English git output (UNTRANSLATED_GIT_OUTPUT_ENV), so the error-text match is stable. Git 2.17+ message/command — below the 2.25 baseline; no capability probe needed.

Evidence

Git fixture (this machine, Git 2.44): clean linked worktree + submodule update --init:

  • git worktree remove <wt> → exit 128, fatal submodule message
  • git worktree remove --force <wt> → exit 0, path removed
  • Dirty submodule (untracked / modified / new commit) surfaces non-empty parent porcelain → gate refuses auto-force

Vitest:

✓ src/shared/worktree-submodule-removal.test.ts (3)
✓ src/main/git/remove-worktree.test.ts (38)
✓ src/relay/git-handler-worktree-ops.test.ts (14)

ELI5

Git treats “worktree has a submodule checked out” as “you must say --force to delete this worktree,” even if nothing is dirty. Orca used to try a polite remove first and give up. Now, when Git says that exact thing, Orca double-checks that nothing is dirty; if the tree is clean it uses --force, and if something is dirty it stops and asks before destroying work.

User-regression-tradeoffs

Path Behavior
Clean worktree + initialised submodule, non-force (skip-confirm) Fixed: auto force-retry after clean recheck
Dirty worktree + submodule, non-force Still refuses; Force Delete toast path via existing dirty classification
Confirm dialog (force: true) Unchanged; already passed --force
Locked worktree Unchanged; lock check still blocks before remove
Unrelated remove failures Unchanged; no force retry

Tradeoff: a clean submodule worktree is removed with Git --force without a second prompt. That is safe because cleanliness is re-proven immediately before the force remove; it matches Git’s documented requirement for submodule worktrees, not a dirty-data bypass.

Screenshots

No visual change.

Testing

  • Targeted vitest (shared predicate + local remove + relay remove)
  • pnpm lint (not run full)
  • pnpm typecheck (not run full)
  • pnpm test (not run full suite)
  • pnpm build
  • Added/updated high-quality regression tests

AI Review Report

Adversarial review of #8704 approach (adopted):

  • Dirty force safety: only retries after re-proving clean status; dirty throws standard error. Added tests that dirty submodule and unrelated dirty-file fatals never force-retry.
  • Double force: callers with force: true do not enter retry (local + SSH tests).
  • Lock contract: lock assert still runs before remove; force path does not override locks.
  • Nested/other worktrees: Git force-remove is path-scoped; only the target worktree is removed.
  • Git 2.25 compat: worktree remove + refusal message since 2.17; retry uses no newer flags.
  • Cross-platform: path is passed as existing worktree path (no hardcoded separators); SSH relay path mirrored; no shortcuts/labels/UI.
  • Locale: relies on UNTRANSLATED_GIT_OUTPUT_ENV already used by local/relay runners.

Security Audit

  • No new IPC surface; uses existing remove + status git invocations.
  • Error matching is text-based on pinned English git fatals (not shell interpolation of user content into commands).
  • Force is only applied after an empty porcelain status for the worktree path already validated as a registered worktree; does not expand to recursive rm -rf outside git worktree remove --force.
  • No secrets, auth, or dependency changes.

Notes

xianjianlf2 and others added 2 commits July 16, 2026 17:29
…ed submodule

`git worktree remove` (non-force) categorically refuses any worktree with
an initialised submodule — `fatal: working trees containing submodules
cannot be moved or removed` — even when the parent and submodule are
completely clean. Orca's delete flow proves cleanliness first and then
runs a non-force remove, so deleting such a workspace always failed and
left the worktree registered and on disk.

On that specific refusal, re-prove cleanliness (parent `git status
--porcelain --untracked-files=all` reports dirty submodule content as
` M <sub>`) and retry with `--force`. A dirty worktree still surfaces
"Worktree has uncommitted or untracked changes." instead of force-deleting.
Applies to both the local path and the SSH relay path; both runners pin
English git output, so the error-text match is stable.

Fixes #8670

Co-Authored-By: Claude Fable 5 <[email protected]>
Add shared predicate unit tests plus local/SSH guards that unrelated
remove failures and already-forced callers never take the clean-submodule
--force retry path.

Co-authored-by: MarkXian <[email protected]>
@coderabbitai

coderabbitai Bot commented Jul 17, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Added shared detection for Git refusals involving initialized submodules. Main and relay worktree removal flows now check for uncommitted or untracked changes before retrying clean removals with --force, while preserving existing behavior for forced calls and unrelated errors. Tests cover successful retries, dirty worktrees, forced removals, unrelated failures, and error-shape handling.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 50.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly summarizes the main change: force-retrying clean worktree removal when an initialized submodule blocks non-force deletion.
Description check ✅ Passed The description follows the template and includes the required sections with clear summary, testing, review, security, screenshots, and notes.
Linked Issues check ✅ Passed The PR matches #8670 by retrying clean submodule worktree removals with --force, preserving dirty-worktree safety and leaving other paths unchanged.
Out of Scope Changes check ✅ Passed The changes stay focused on worktree removal, shared detection, and regression tests with no obvious unrelated edits.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch

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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
src/shared/worktree-submodule-removal.test.ts (1)

1-39: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a test case for the stdout field.

getErrorText inspects message, stderr, and stdout, but only message/stderr are exercised here. Add a case where the refusal text is only present on stdout.

✅ Suggested additional test
+  it('matches when the refusal is only on stdout', () => {
+    expect(
+      isSubmoduleWorktreeRemovalRefusal(
+        Object.assign(new Error('git worktree remove failed'), {
+          stdout: 'fatal: working trees containing submodules cannot be moved or removed'
+        })
+      )
+    ).toBe(true)
+  })
src/relay/git-handler-worktree-remove.ts (1)

168-174: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Extract the cleanliness-check-and-throw logic into the shared module.

The "run git status --porcelain --untracked-files=all, check if dirty, throw a standardized error with a stdout property" logic here duplicates the pattern used by assertWorktreeCleanForRemoval in src/main/git/worktree.ts. Since both files already import from src/shared/worktree-submodule-removal.ts, consider adding a small shared helper (e.g. assertCleanStatusOutputOrThrow(stdout)) there that both call after fetching their own git status output, keeping the error message/shape guaranteed consistent across the local and relay runners.

♻️ Sketch of a shared helper
+// in src/shared/worktree-submodule-removal.ts
+export function assertCleanStatusOutputOrThrow(stdout: string): void {
+  if (!stdout.trim()) {
+    return
+  }
+  const error = new Error('Worktree has uncommitted or untracked changes.')
+  ;(error as Error & { stdout?: string }).stdout = stdout
+  throw error
+}
-    const { stdout } = await git(['status', '--porcelain', '--untracked-files=all'], worktreePath)
-    if (stdout.trim()) {
-      const dirtyError = new Error('Worktree has uncommitted or untracked changes.')
-      ;(dirtyError as Error & { stdout?: string }).stdout = stdout
-      throw dirtyError
-    }
+    const { stdout } = await git(['status', '--porcelain', '--untracked-files=all'], worktreePath)
+    assertCleanStatusOutputOrThrow(stdout)

ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Pro

Run ID: 7440a771-e51c-4bef-8868-f7004e0ab1cc

📥 Commits

Reviewing files that changed from the base of the PR and between 1cdc8e8 and fb4fe74.

📒 Files selected for processing (6)
  • src/main/git/remove-worktree.test.ts
  • src/main/git/worktree.ts
  • src/relay/git-handler-worktree-ops.test.ts
  • src/relay/git-handler-worktree-remove.ts
  • src/shared/worktree-submodule-removal.test.ts
  • src/shared/worktree-submodule-removal.ts

@nwparker
nwparker merged commit d363c83 into main Jul 17, 2026
2 checks passed
@nwparker
nwparker deleted the nwparker/fix-8670-wave2 branch July 17, 2026 02:15
enrick-dev pushed a commit to enrick-dev/orca that referenced this pull request Oct 15, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Deleting a clean worktree fails when it contains an initialised submodule

2 participants