Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

Harden merged worktree cleanup

Adam Eivyccc3ede96e0d
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 84c7c65b16..8d3735e100 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -19,6 +19,8 @@ TBD
## Changed
+- **Merge-verified worktree cleanup — reaps merged branches/worktrees without ever risking in-progress work.** Periodic worktree cleanup was previously disabled because it could obliterate worktrees still in use by other agents or outside the CoS system. The cleanup now reaps a worktree **only** when both gates pass: the working tree is clean (auto-generated lockfile churn ignored) **and** the branch is fully merged into the default branch. Merge detection (`isBranchMergedInto`) covers both normal merges (ancestor check) and squash/rebase merges (synthesized-tree `git cherry` patch-id), so it can't be fooled by a squashed history. The daily `agent-data-cleanup` job now runs this safe reap across both CoS worktrees (`data/cos/worktrees/`) and the `/work` / `/claim` / superpowers trees under `.claude/worktrees/` — unlocking locked-but-merged trees before removal — then falls back to the existing orphan-integration pass for dead agents whose commits never landed. Because the two gates together mean "nothing pending and nothing to lose," the previous data-loss failure mode is structurally impossible. To make detection bulletproof going forward, the automated review-loop and `/do:pr` merge commands now prefer a true merge commit (`gh pr merge --merge`) over `--squash`, keeping each branch tip in the default branch's history.
+
- **Autofixer and Google Calendar sync now run through your configured AI provider.** Both previously hardcoded `claude -p`, ignoring whichever provider/model the rest of PortOS uses. They now resolve a configured CLI provider/model and route through a shared, dependency-light invocation path (`server/lib/cliProviderRun.js`) — the same per-CLI argv conventions (Codex `exec -`, Gemini stdin, Claude Code `-p -`) the main runner uses. New UI controls let you pick the provider/model per feature: a **Settings › Autofixer** tab, and a picker on the **Calendar › Config** tab (for Google MCP-sync accounts). Both default to Claude Code when unset, so existing installs are unchanged. The picker is restricted to enabled **CLI** providers — the autofixer must edit files and run pm2, and the calendar sync must call MCP tools, neither of which an API chat provider can do. *Migration note:* calendar MCP sync no longer honors the legacy `CLAUDE_PATH` env var — point the provider's command at your binary under **AI Providers** instead. The Claude-specific `--allowedTools` MCP flag is now passed only to Claude-family providers.
- **Importer source ceiling raised from 200K → 5M characters.** The Create › Importer page previously rejected pasted sources over 200,000 characters — far short of a real novel (a 250-page book runs ~400K chars; long novels reach several million). That cap was an over-conservative "v1" product limit, not a fundamental constraint: the schema layer already allowed 5MB, and modern large-context providers (Claude, Gemini) ingest a whole novel in a single call. The importer now matches the 5MB abuse-guard ceiling, so the only remaining limit is dynamic — the active provider's context window (the entire corpus still goes into one extraction call until chunked extraction lands). Sources that fit the ceiling but overflow the chosen model's window surface a provider error; pick a large-context provider or trim in the meantime. The pipeline's per-issue canon-extract truncation budget was decoupled (stays 200K) since a single issue's stage output is already hard-bounded at 400K and operates at a fundamentally smaller scale than whole-book ingest.
diff --git a/PLAN.md b/PLAN.md
index 3deeb2c349..8fe63ca2a2 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -141,6 +141,13 @@ Surfaced by a gemini review during PR #489 (sync-hygiene) that scoped beyond tha
- [ ] [setup-browser-config-loss] **`scripts/setup-browser.js` `loadConfig` swallows JSON parse errors silently, then `applyCanaryToConfig` → `saveConfig` can overwrite a corrupt config with a near-empty one (key loss).** Add an emoji-prefixed warning on parse failure and avoid calling `saveConfig` when the existing file was unreadable. Verified (gemini IMPROVEMENT).
- [ ] [setup-browser-canary-headless] **Fresh Canary opt-in may run headless-invisible — verify intent.** gemini flagged that `applyCanaryToConfig` (`scripts/setup-browser.js:81`) sets `chromePath`/`macAppBundle` but not `headless: false`, so a fresh install that opts into Canary could run it invisibly. UNVERIFIED — confirm whether `false` is already the effective default before changing. (gemini IMPROVEMENT.)
+### Worktree cleanup — deferred follow-ups (2026-05-25)
+
+Surfaced while adding merge-verified worktree reaping (`isBranchMergedInto` + `reapMergedWorktrees`, NEXT.md). These were intentionally left out of that change.
+
+- [ ] [worktree-remove-helper] **Extract the repeated "worktree remove --force → on-fail rm + prune" dance into one helper.** The pattern (`git worktree remove <path> --force`, catch → `rm -rf` + `git worktree prune`) is now inlined in 4 spots in `server/services/worktreeManager.js`: `removeWorktree`, `reapMergedWorktrees`, `cleanupExternalRepoWorktrees`, and `removePersistentWorktree`. Extract `forceRemoveWorktreeDir(repo, worktreePath, label)` and route all four through it. Deferred from the `/simplify` pass on the reaper change because two of the four call sites are outside that feature's diff and the logging context differs slightly per site.
+- [ ] [plan-task-prefer-merge] **Switch the `/claim` (`plan-task`) Phase-6 merge order to prefer `--merge` over `--squash`.** The live `plan-task` prompt in `server/services/taskSchedule.js` (~line 562) still tries `gh pr merge --auto || --squash || --merge || --rebase`, so `/claim` squash-merges by default — inconsistent with the new `--merge`-first default now used by the review-loop / `/do:pr` agent prompts (`agentPromptBuilder.js`) and the `pr-reviewer-review` stage prompt. Deferred because: (a) `plan-task` is a **version-migrated** prompt, so the change needs a `PROMPT_VERSIONS['plan-task']` bump (7→8) **and** the v7 default preserved in `PREVIOUS_DEFAULT_PROMPTS['plan-task']` (~190-line byte-exact copy — error-prone); (b) `/claim` self-cleans its worktree/branch in Phase 7 regardless of merge method, so it doesn't contribute to worktree accumulation; and (c) `reapMergedWorktrees` detects squash merges anyway, so cleanup is already correct. Low benefit, non-trivial migration cost — do it as a focused follow-up when touching `plan-task` prompt versioning next.
+
## Future Ideas
- **Identity Context Injection** — per-task-type digital twin preamble toggle.
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index 346cda0463..40c3c04075 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -284,11 +284,11 @@ ${extraNotes.length ? '\n' + extraNotes.join('\n') + '\n' : ''}
1. ${waitOrInvokeStep}
2. If there are unresolved review findings, fix them in this worktree, run the project's tests, commit (\`feat:\`/\`fix:\` prefix, no Co-Authored-By), push, and (for Copilot) resolve the addressed threads.
3. Re-review with the same reviewer until it reports clean, then advance to the next reviewer in the list.
-4. When the reviewer list is exhausted (or the stop mode triggers), merge the PR **immediately** with this exact command (flags: \`--squash --delete-branch\`, nothing else):
+4. When the reviewer list is exhausted (or the stop mode triggers), merge the PR **immediately** with this exact command (flags: \`--merge --delete-branch\`, nothing else — a true merge commit keeps the branch tip in main's history so automated worktree cleanup can prove the branch is merged):
\`\`\`bash
- gh pr merge "${prUrl}" --squash --delete-branch
+ gh pr merge "${prUrl}" --merge --delete-branch
\`\`\`
- ${prOwner && prRepo && prNumber ? `(Equivalent: \`gh pr merge ${prNumber} --repo ${prOwner}/${prRepo} --squash --delete-branch\`.)` : ''}
+ ${prOwner && prRepo && prNumber ? `(Equivalent: \`gh pr merge ${prNumber} --repo ${prOwner}/${prRepo} --merge --delete-branch\`.)` : ''}
You have already verified the review is clean, so force the immediate merge. Adding any merge-deferral flag would leave the PR open after you exit.
5. Confirm the PR is actually merged before exiting: \`gh pr view "${prUrl}" --json state -q .state\` must return \`MERGED\`. If it returns \`OPEN\` or \`CLOSED\`, investigate (a check is failing, a thread is still unresolved, or branch protection is blocking) — fix and retry the merge. Do NOT exit until state is \`MERGED\`.
6. Exit. Do **not** run \`/do:push\` or open a new PR — the merge handles everything. The system will clean up your worktree on exit.
@@ -318,11 +318,11 @@ ${rprBody ? `\n### /do:rpr Reference (full procedure)\n\nWhen following the proc
`1. ${waitOrInvokeStep}`,
'2. If unresolved findings: fix in this worktree, run tests, commit (`feat:`/`fix:` prefix, no Co-Authored-By), push' + (hasCopilot ? ', and (for Copilot) resolve the addressed threads.' : '.'),
'3. Re-review with the same reviewer until clean, then advance to the next reviewer in the list.',
- '4. When the list is exhausted (or the stop mode triggers), merge **immediately** with this exact command (flags: `--squash --delete-branch`, nothing else):',
+ '4. When the list is exhausted (or the stop mode triggers), merge **immediately** with this exact command (flags: `--merge --delete-branch`, nothing else — a true merge commit keeps the branch tip in main\'s history so automated worktree cleanup can prove the branch is merged):',
' ```bash',
- ` gh pr merge "${prUrl}" --squash --delete-branch`,
+ ` gh pr merge "${prUrl}" --merge --delete-branch`,
' ```',
- prOwner && prRepo && prNumber ? ` (Equivalent: \`gh pr merge ${prNumber} --repo ${prOwner}/${prRepo} --squash --delete-branch\`.)` : null,
+ prOwner && prRepo && prNumber ? ` (Equivalent: \`gh pr merge ${prNumber} --repo ${prOwner}/${prRepo} --merge --delete-branch\`.)` : null,
' You have already verified the review is clean, so force the immediate merge. Adding any merge-deferral flag would leave the PR open after you exit.',
`5. Confirm the merge happened before exiting: \`gh pr view "${prUrl}" --json state -q .state\` must return \`MERGED\`. If it returns \`OPEN\` or \`CLOSED\`, investigate (failing check, unresolved thread, branch protection) — fix and retry. Do NOT exit until state is \`MERGED\`.`,
'6. Exit — do NOT run `/do:push` or open a new PR.',
@@ -825,9 +825,9 @@ function buildPostPRMergeSteps(startStep, { reviewers = DEFAULT_REVIEWERS, revie
? '`clean`, `partial` (a stop-mode short-circuit you opted into), or `too-large`'
: '`clean` (or `too-large`)';
const lines = [
- `${startStep}. **Merge the PR immediately when the ${reviewerLabel}review loop reports ${mergeStatuses}** — \`/do:pr\` opens the PR and runs the review loop but does NOT merge. Capture the PR URL printed by \`/do:pr\` and run the exact command below (flags: \`--squash --delete-branch\`, nothing else — any merge-deferral flag leaves the PR open after you exit). Skip the merge if the loop ended \`timeout\`, \`error\`, \`inconclusive\`, or \`guardrail\`; leave the PR open for human follow-up.`,
+ `${startStep}. **Merge the PR immediately when the ${reviewerLabel}review loop reports ${mergeStatuses}** — \`/do:pr\` opens the PR and runs the review loop but does NOT merge. Capture the PR URL printed by \`/do:pr\` and run the exact command below (flags: \`--merge --delete-branch\`, nothing else — a true merge commit keeps the branch tip in main's history so automated worktree cleanup can prove the branch is merged; any merge-deferral flag leaves the PR open after you exit). Skip the merge if the loop ended \`timeout\`, \`error\`, \`inconclusive\`, or \`guardrail\`; leave the PR open for human follow-up.`,
' ```bash',
- ' gh pr merge "<PR_URL>" --squash --delete-branch',
+ ' gh pr merge "<PR_URL>" --merge --delete-branch',
' ```',
`${startStep + 1}. Confirm the merge before exiting: \`gh pr view "<PR_URL>" --json state -q .state\` must return \`MERGED\`. If it returns \`OPEN\` or \`CLOSED\`, investigate (failing check, unresolved thread, branch protection), fix, and retry. Do NOT exit until state is \`MERGED\` (or you have explicitly decided not to merge per the rule above).`
];
diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.js
index a065065b87..6b968a0e61 100644
--- a/server/services/agentPromptBuilder.test.js
+++ b/server/services/agentPromptBuilder.test.js
@@ -180,7 +180,7 @@ describe('buildLightContextPrompt', () => {
expect(prompt).toMatch(/NOT run `\/quit`/);
// After /do:pr drives the Copilot review loop clean, the agent must
// merge and verify — otherwise the PR sits open after the agent exits.
- expect(prompt).toMatch(/gh pr merge "<PR_URL>" --squash --delete-branch/);
+ expect(prompt).toMatch(/gh pr merge "<PR_URL>" --merge --delete-branch/);
expect(prompt).not.toMatch(/gh pr merge[^\n]*--auto/);
expect(prompt).toMatch(/gh pr view "<PR_URL>" --json state -q \.state/);
expect(prompt).toMatch(/MERGED/);
@@ -253,7 +253,7 @@ describe('buildLightContextPrompt', () => {
// After /do:pr drives the Copilot review loop clean, the agent must
// merge and verify — without these steps the PR sits open after the
// agent exits (the original "agent abandoned the PR" bug).
- expect(prompt).toMatch(/gh pr merge "<PR_URL>" --squash --delete-branch/);
+ expect(prompt).toMatch(/gh pr merge "<PR_URL>" --merge --delete-branch/);
expect(prompt).not.toMatch(/gh pr merge[^\n]*--auto/);
expect(prompt).toMatch(/gh pr view "<PR_URL>" --json state -q \.state/);
expect(prompt).toMatch(/MERGED/);
@@ -269,7 +269,7 @@ describe('buildLightContextPrompt', () => {
expect(prompt).toMatch(/`\/do:pr`/);
expect(prompt).not.toMatch(/`\/simplify`/);
// Merge guidance still applies when /simplify is skipped.
- expect(prompt).toMatch(/gh pr merge "<PR_URL>" --squash --delete-branch/);
+ expect(prompt).toMatch(/gh pr merge "<PR_URL>" --merge --delete-branch/);
});
it('uses /do:push (not /do:pr) for Claude Code CLI when openPR is false', () => {
@@ -309,7 +309,7 @@ describe('buildLightContextPrompt', () => {
isTruthyMeta);
expect(prompt).toMatch(/## Review-Loop Follow-up/);
expect(prompt).toMatch(/task-src-1/);
- expect(prompt).toMatch(/gh pr merge "https:\/\/github\.com\/o\/r\/pull\/9" --squash --delete-branch/);
+ expect(prompt).toMatch(/gh pr merge "https:\/\/github\.com\/o\/r\/pull\/9" --merge --delete-branch/);
// --auto must NOT appear inside any `gh pr merge` invocation — it defers
// the merge and the PR sits open after the agent exits.
expect(prompt).not.toMatch(/gh pr merge[^\n]*--auto/);
@@ -516,8 +516,8 @@ describe('buildAgentPrompt — provider type routing', () => {
isTruthyMeta,
{ providerType: 'api' });
expect(prompt).toMatch(/## Review-Loop Follow-up/);
- // Merge command must be present, exactly with --squash --delete-branch.
- expect(prompt).toMatch(/gh pr merge "https:\/\/github\.com\/o\/r\/pull\/9" --squash --delete-branch/);
+ // Merge command must be present, exactly with --merge --delete-branch.
+ expect(prompt).toMatch(/gh pr merge "https:\/\/github\.com\/o\/r\/pull\/9" --merge --delete-branch/);
// --auto must NOT appear inside any `gh pr merge` invocation — it defers
// the merge and the PR sits open after the agent exits.
expect(prompt).not.toMatch(/gh pr merge[^\n]*--auto/);
diff --git a/server/services/autonomousJobs.js b/server/services/autonomousJobs.js
index b0d8bd7d7b..3b73050e93 100644
--- a/server/services/autonomousJobs.js
+++ b/server/services/autonomousJobs.js
@@ -28,7 +28,7 @@ import { runGoalCheckIn } from './goalCheckIn.js'
import { validateCommand, redactOutput, ALLOWED_COMMANDS_SORTED } from '../lib/commandSecurity.js'
import { getUserTimezone, getLocalParts, nextLocalTime } from '../lib/timezone.js'
import { parseCronToNextRun } from './eventScheduler.js'
-import { cleanupOrphanedWorktrees } from './worktreeManager.js'
+import { cleanupOrphanedWorktrees, reapMergedWorktrees } from './worktreeManager.js'
import { getActiveAgentIds } from './agentState.js'
/**
@@ -112,16 +112,27 @@ async function agentDataCleanup() {
}
}
- // Reap orphaned agent worktrees not tracked by any live agent (moved off the
- // CoS hot path). The helper guards `claim-*` worktrees, so this can't touch a
- // human's in-flight claim.
+ // First pass — SAFE reap: remove any worktree (CoS or `.claude/worktrees/`) whose
+ // branch is fully merged into the default branch AND whose working tree is clean.
+ // This is the bulk of the cleanup and cannot lose work (merged+clean ⇒ nothing
+ // pending). It guards active agents and human `claim-*` worktrees.
+ const merged = await reapMergedWorktrees(PATHS.root, { activeAgentIds: activeIds }).catch((err) => {
+ console.warn(`⚠️ Merged-worktree reap failed: ${err.message}`)
+ return { reaped: [] }
+ })
+
+ // Second pass — orphan integration: for inactive CoS worktrees that were NOT
+ // merged (e.g. an agent died after committing but before its PR landed), attempt
+ // to merge their commits back so the work isn't stranded. The helper guards
+ // `claim-*` worktrees, so this can't touch a human's in-flight claim.
const worktreesReaped = await cleanupOrphanedWorktrees(PATHS.root, activeIds).catch((err) => {
console.warn(`⚠️ Orphaned worktree cleanup failed: ${err.message}`)
return 0
})
- console.log(`🧹 Agent data cleanup: removed ${cleaned} dir(s) older than 7 days, reaped ${worktreesReaped} orphaned worktree(s)`)
- return { cleaned, worktreesReaped }
+ const mergedCount = merged?.reaped?.length || 0
+ console.log(`🧹 Agent data cleanup: removed ${cleaned} dir(s) older than 7 days, reaped ${mergedCount} merged + ${worktreesReaped} orphaned worktree(s)`)
+ return { cleaned, mergedReaped: mergedCount, worktreesReaped }
}
const SCRIPT_HANDLERS = {
@@ -383,7 +394,7 @@ Phase 4 — Report:
{
id: 'job-agent-data-cleanup',
name: 'Agent Data Cleanup',
- description: 'Remove completed agent data older than 7 days and reap orphaned agent worktrees.',
+ description: 'Remove completed agent data older than 7 days, reap worktrees/branches fully merged into main (clean working tree only), and integrate orphaned agent worktrees.',
category: 'agent-data-cleanup',
interval: 'daily',
intervalMs: DAY,
diff --git a/server/services/git.js b/server/services/git.js
index 663b69b60d..2be65d9a0a 100644
--- a/server/services/git.js
+++ b/server/services/git.js
@@ -1077,6 +1077,87 @@ export async function mergeBranch(dir, branchName) {
return { success: true, output: (result.stdout + result.stderr).trim() };
}
+/**
+ * Determine whether a branch's work is fully present in `target` (e.g. main),
+ * covering BOTH a normal/fast-forward/no-ff merge AND a squash (or rebase) merge.
+ *
+ * - Normal / ff / no-ff merge: the branch tip becomes reachable from target, so
+ * `git merge-base --is-ancestor` settles it immediately.
+ * - Rebase-and-merge replays the branch commits as new SHAs; the original tip is
+ * not an ancestor, so we ask `git cherry` whether each branch commit has a
+ * patch-equivalent commit in target. `git cherry` prints "- <sha>" when an
+ * equivalent exists upstream and "+ <sha>" when it does not, so an all-"-"
+ * result means the branch was replayed.
+ * - Squash merge: the branch's commits are collapsed into a single NEW commit on
+ * target, so individual commits usually are not patch-equivalent. We synthesize
+ * a commit holding the branch's full tree on top of the merge-base and ask
+ * `git cherry` whether target already contains that combined patch.
+ *
+ * Fails CLOSED: any git error (or unresolvable ref) returns false, so a detection
+ * failure can never authorize a delete. This is the gate the merged-worktree
+ * reaper relies on — see reapMergedWorktrees in worktreeManager.js.
+ *
+ * @param {string} dir - Repo working directory
+ * @param {string} branch - Branch whose work we're checking (local name or ref)
+ * @param {string} target - Branch it should be merged into (e.g. 'main')
+ * @returns {Promise<boolean>}
+ */
+export async function isBranchMergedInto(dir, branch, target) {
+ if (!branch || !target || branch === target) return false;
+
+ const resolve = (ref) => execGit(['rev-parse', '--verify', `${ref}^{commit}`], dir, { ignoreExitCode: true })
+ .then(r => (r.exitCode === 0 ? r.stdout.trim() : null))
+ .catch(() => null);
+
+ const [branchSha, targetSha] = await Promise.all([resolve(branch), resolve(target)]);
+ if (!branchSha || !targetSha) return false;
+
+ // Fast path: branch tip already reachable from target (normal / ff / no-ff merge,
+ // or the branch carries no unique commits).
+ const ancestor = await execGit(['merge-base', '--is-ancestor', branchSha, targetSha], dir, { ignoreExitCode: true })
+ .then(r => r.exitCode === 0)
+ .catch(() => false);
+ if (ancestor) return true;
+
+ // Rebase/cherry-pick path: does target contain every branch commit as an
+ // individual patch-equivalent commit?
+ const individualCherry = await execGit(['cherry', targetSha, branchSha], dir, { ignoreExitCode: true })
+ .then(r => r.stdout.trim())
+ .catch(() => null);
+ if (individualCherry === null) return false;
+ if (individualCherry !== '' && individualCherry.split('\n').every(line => line.startsWith('-'))) {
+ return true;
+ }
+
+ // Squash path: does target already contain the branch's combined patch?
+ const mergeBase = await execGit(['merge-base', targetSha, branchSha], dir, { ignoreExitCode: true })
+ .then(r => (r.exitCode === 0 ? r.stdout.trim() : null))
+ .catch(() => null);
+ if (!mergeBase) return false;
+ // No unique work beyond the merge base → nothing would be lost.
+ if (mergeBase === branchSha) return true;
+
+ const branchTree = await execGit(['rev-parse', `${branchSha}^{tree}`], dir, { ignoreExitCode: true })
+ .then(r => (r.exitCode === 0 ? r.stdout.trim() : null))
+ .catch(() => null);
+ if (!branchTree) return false;
+
+ // Synthesize a single commit with the branch's full tree atop the merge base.
+ // commit-tree uses the repo's configured identity; if that's unset it fails and
+ // we fall through to "not merged" (safe — the worktree is just preserved).
+ const synthesized = await execGit(['commit-tree', branchTree, '-p', mergeBase, '-m', 'merged-check-probe'], dir, { ignoreExitCode: true })
+ .then(r => (r.exitCode === 0 ? r.stdout.trim() : null))
+ .catch(() => null);
+ if (!synthesized) return false;
+
+ const combinedCherry = await execGit(['cherry', targetSha, synthesized], dir, { ignoreExitCode: true })
+ .then(r => r.stdout.trim())
+ .catch(() => null);
+ if (combinedCherry === null) return false;
+ if (combinedCherry === '') return true; // empty patch (tree already matches) ⇒ merged
+ return combinedCherry.split('\n').every(line => line.startsWith('-'));
+}
+
/**
* Checkout a remote branch that doesn't exist locally.
* Creates a local tracking branch from the remote ref.
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index c9a3513bf5..e7a911ba96 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -1076,9 +1076,9 @@ Repository: {repoPath}
- GitHub: \`gh pr checks <number>\` — wait for all checks to complete (poll every 30s, up to 10 minutes)
- GitLab: \`glab mr view <iid> -F json\` — check pipeline status
- Run the project's test suite locally: check for a test script in package.json, Makefile, or similar and run it
- - If all CI checks pass AND local tests pass:
- - GitHub: \`gh pr merge <number> --squash --delete-branch\`
- - GitLab: \`glab mr merge <iid> --squash --remove-source-branch\`
+ - If all CI checks pass AND local tests pass (prefer a true merge commit so the branch tip stays in the default branch's history — if the repo disallows merge commits, fall back to \`--squash\`):
+ - GitHub: \`gh pr merge <number> --merge --delete-branch || gh pr merge <number> --squash --delete-branch\`
+ - GitLab: \`glab mr merge <iid> --remove-source-branch || glab mr merge <iid> --squash --remove-source-branch\`
- If CI fails or tests fail, post a comment noting the failures and do NOT merge
- After merge, switch back to the default branch: \`git checkout <default-branch> && git pull\`
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.js
index d25475a981..7009216d16 100644
--- a/server/services/worktreeManager.js
+++ b/server/services/worktreeManager.js
@@ -19,6 +19,43 @@ const WORKTREES_DIR = PATHS.worktrees;
// Lockfiles that npm/yarn/pnpm modify as a side-effect — safe to discard during worktree cleanup
const AUTO_GENERATED_LOCKFILES = ['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml'];
+/**
+ * Classify a `git status --porcelain` blob into real changes vs auto-generated
+ * lockfile churn. Pure (testable) — callers decide what to do with the result.
+ *
+ * @param {string} porcelain - raw `git status --porcelain` stdout
+ * @returns {{ clean: boolean, lockfileOnly: boolean, lockfilePaths: string[], hasRealChanges: boolean }}
+ * - clean: no changes at all
+ * - lockfileOnly: every change is an auto-generated lockfile (safe to discard)
+ * - lockfilePaths: paths of those lockfiles (strip the porcelain `XY ` status prefix)
+ * - hasRealChanges: at least one non-lockfile change (worktree must be preserved)
+ */
+export function classifyWorktreeDirt(porcelain) {
+ const lines = (porcelain || '').split('\n').map(l => l.trim()).filter(Boolean);
+ if (lines.length === 0) {
+ return { clean: true, lockfileOnly: false, lockfilePaths: [], hasRealChanges: false };
+ }
+ const lockfileLines = lines.filter(line => AUTO_GENERATED_LOCKFILES.some(f => line.endsWith(f)));
+ const lockfileOnly = lockfileLines.length === lines.length;
+ return {
+ clean: false,
+ lockfileOnly,
+ lockfilePaths: lockfileLines.map(line => line.replace(/^\s*\S+\s+/, '')),
+ hasRealChanges: !lockfileOnly
+ };
+}
+
+/**
+ * Compare two filesystem paths for equality, resolving symlinks (e.g. macOS
+ * /var → /private/var) so normalization differences don't false-negative.
+ */
+function pathsEqual(a, b) {
+ if (!a || !b) return false;
+ if (a === b) return true;
+ const resolved = (p) => { try { return realpathSync(p); } catch { return p; } };
+ return resolved(a) === resolved(b);
+}
+
/**
* True when a worktree directory belongs to a human-driven `/claim` TUI
* session, not a CoS agent.
@@ -182,14 +219,7 @@ export async function removeWorktree(agentId, sourceWorkspace, branchName, optio
.catch(() => null);
// Compare realpath-resolved forms so symlinks (e.g. macOS /var → /private/var)
// or normalization differences don't false-positive as a broken worktree.
- const sameTopLevel = (a, b) => {
- if (!a || !b) return false;
- if (a === b) return true;
- const ra = (() => { try { return realpathSync(a); } catch { return a; } })();
- const rb = (() => { try { return realpathSync(b); } catch { return b; } })();
- return ra === rb;
- };
- if (detectedToplevel && !sameTopLevel(detectedToplevel, worktreePath)) {
+ if (detectedToplevel && !pathsEqual(detectedToplevel, worktreePath)) {
console.log(`🌳 Worktree ${agentId} resolves to ${detectedToplevel} instead of ${worktreePath} — broken worktree, removing`);
await rm(worktreePath, { recursive: true, force: true }).catch(rmErr => {
console.log(`⚠️ Failed to remove broken worktree ${agentId}: ${rmErr.message}`);
@@ -211,15 +241,10 @@ export async function removeWorktree(agentId, sourceWorkspace, branchName, optio
if (dirtyFiles) {
// Discard auto-generated lockfile changes that agents don't intend to commit
// (e.g., npm install resolving ^version to exact version in package-lock.json)
- const dirtyList = dirtyFiles.split('\n').filter(l => l.trim());
- const lockfileChanges = dirtyList.filter(line =>
- AUTO_GENERATED_LOCKFILES.some(f => line.endsWith(f))
- );
- if (lockfileChanges.length > 0 && lockfileChanges.length === dirtyList.length) {
- // Extract filepath from porcelain output (XY<space>path), handling trimmed first-line
- const lockfilePaths = lockfileChanges.map(line => line.replace(/^\s*\S+\s+/, ''));
- console.log(`🧹 Discarding ${lockfileChanges.length} auto-generated lockfile change(s) in worktree ${agentId}`);
- await execGit(['checkout', '--', ...lockfilePaths], worktreePath);
+ const dirt = classifyWorktreeDirt(dirtyFiles);
+ if (dirt.lockfileOnly) {
+ console.log(`🧹 Discarding ${dirt.lockfilePaths.length} auto-generated lockfile change(s) in worktree ${agentId}`);
+ await execGit(['checkout', '--', ...dirt.lockfilePaths], worktreePath);
} else {
console.log(`⚠️ Preserving worktree for ${agentId} — uncommitted changes detected, aborting cleanup to avoid data loss`);
warnings.push(`Worktree preserved — uncommitted changes detected in ${worktreePath}`);
@@ -453,6 +478,9 @@ export async function listWorktrees(sourceWorkspace) {
current.bare = true;
} else if (line === 'detached') {
current.detached = true;
+ } else if (line === 'locked' || line.startsWith('locked ')) {
+ // `git worktree list --porcelain` emits a bare `locked` line, or `locked <reason>`.
+ current.locked = true;
}
}
if (current.path) worktrees.push(current);
@@ -508,6 +536,116 @@ export async function cleanupOrphanedWorktrees(sourceWorkspace, activeAgentIds)
return cleaned;
}
+/**
+ * Reap worktrees whose branch is fully merged into the default branch AND whose
+ * working tree is clean. This is the SAFE counterpart to cleanupOrphanedWorktrees:
+ * it never integrates unmerged work, never deletes anything with pending
+ * changes, and honors worktree locks. A worktree is reaped only when BOTH hold:
+ * 1. the working tree is completely clean, and
+ * 2. every commit on the branch is already in the default branch — detected via
+ * `isBranchMergedInto`, which covers normal AND squash/rebase merges.
+ *
+ * Because of gate (2) this works regardless of merge strategy, but a true merge
+ * commit (see the `--merge`-preferring agent prompts) makes detection bulletproof.
+ *
+ * Covers both PortOS-managed CoS worktrees (`data/cos/worktrees/`) and the
+ * `.claude/worktrees/` trees created by `/work`, `/claim`, and the superpowers
+ * git-worktree skill (these share the PortOS repo, so they appear in
+ * `git worktree list`). Active CoS agents and locked worktrees are never touched.
+ * Human `/claim` worktrees (`claim-*`) are skipped by default (they self-clean in
+ * the claim flow's Phase 7).
+ *
+ * @param {string} sourceWorkspace - repo root
+ * @param {object} [options]
+ * @param {Set<string>} [options.activeAgentIds] - CoS agents currently running (never reaped)
+ * @param {boolean} [options.includeClaudeTrees=true] - also reap `.claude/worktrees/`
+ * @param {boolean} [options.dryRun=false] - report candidates without deleting
+ * @returns {Promise<{reaped: Array<{path,branch,locked}>, skipped: Array<{path,reason}>, defaultBranch: string, target: string, dryRun: boolean}>}
+ */
+export async function reapMergedWorktrees(sourceWorkspace, {
+ activeAgentIds = new Set(),
+ includeClaudeTrees = true,
+ dryRun = false
+} = {}) {
+ const { getDefaultBranch, isBranchMergedInto } = await import('./git.js');
+
+ // Refresh remote refs so "merged into origin/main" reflects the canonical state
+ // after a `gh pr merge`. Best-effort — fall back to local refs on failure.
+ await execGit(['fetch', 'origin', '--prune'], sourceWorkspace, { ignoreExitCode: true }).catch(() => {});
+
+ const defaultBranch = await getDefaultBranch(sourceWorkspace).catch(() => null) || 'main';
+ // Prefer the remote-tracking ref (post-merge truth); fall back to the local branch.
+ const remoteTarget = await execGit(['rev-parse', '--verify', `origin/${defaultBranch}^{commit}`], sourceWorkspace, { ignoreExitCode: true })
+ .then(r => (r.exitCode === 0 ? `origin/${defaultBranch}` : null))
+ .catch(() => null);
+ const target = remoteTarget || defaultBranch;
+
+ const currentBranch = await execGit(['rev-parse', '--abbrev-ref', 'HEAD'], sourceWorkspace, { ignoreExitCode: true })
+ .then(r => r.stdout.trim())
+ .catch(() => '');
+
+ const protectedBranches = new Set(['main', 'master', 'dev', 'develop', 'release', defaultBranch]);
+ const claudeTreesRoot = join(sourceWorkspace, '.claude', 'worktrees');
+
+ const worktrees = await listWorktrees(sourceWorkspace).catch(() => []);
+ const reaped = [];
+ const skipped = [];
+
+ for (const wt of worktrees) {
+ // Never touch the primary worktree (the main repo checkout).
+ if (pathsEqual(wt.path, sourceWorkspace)) continue;
+ if (wt.bare || wt.detached || !wt.branch) { skipped.push({ path: wt.path, reason: 'no-branch' }); continue; }
+
+ const branchName = wt.branch.replace(/^refs\/heads\//, '');
+ if (!branchName) { skipped.push({ path: wt.path, reason: 'no-branch' }); continue; }
+ if (protectedBranches.has(branchName) || branchName === currentBranch) { skipped.push({ path: wt.path, reason: 'protected' }); continue; }
+
+ const agentId = wt.path.split('/').pop();
+ // Human `/claim` worktrees self-clean in the claim flow's Phase 7 — never reap them here.
+ if (isHumanClaimWorktree(agentId)) { skipped.push({ path: wt.path, reason: 'human-claim' }); continue; }
+ if (activeAgentIds.has(agentId)) { skipped.push({ path: wt.path, reason: 'active-agent' }); continue; }
+
+ const isCosTree = wt.path.startsWith(WORKTREES_DIR);
+ const isClaudeTree = wt.path.startsWith(claudeTreesRoot);
+ if (!isCosTree && !isClaudeTree) { skipped.push({ path: wt.path, reason: 'unmanaged-location' }); continue; }
+ if (isClaudeTree && !includeClaudeTrees) { skipped.push({ path: wt.path, reason: 'claude-tree-excluded' }); continue; }
+ if (wt.locked) { skipped.push({ path: wt.path, reason: 'locked' }); continue; }
+
+ // Gate 1: working tree must be completely clean. Unlike removeWorktree(),
+ // the background reaper does not discard even lockfile-only edits: an
+ // uncommitted fresh-from-main worktree may be an active agent that has not
+ // made its first commit yet.
+ const status = await execGit(['status', '--porcelain'], wt.path).then(r => r.stdout).catch(() => null);
+ if (status === null) { skipped.push({ path: wt.path, reason: 'status-failed' }); continue; }
+ if (!classifyWorktreeDirt(status).clean) { skipped.push({ path: wt.path, reason: 'uncommitted' }); continue; }
+
+ // Gate 2: branch fully merged into the default branch (regular, squash, or rebase).
+ const merged = await isBranchMergedInto(sourceWorkspace, branchName, target).catch(() => false);
+ if (!merged) { skipped.push({ path: wt.path, reason: 'unmerged' }); continue; }
+
+ if (dryRun) { reaped.push({ path: wt.path, branch: branchName, locked: !!wt.locked }); continue; }
+
+ // Remove the worktree, then force-delete the branch (-D because squash-merged
+ // branches aren't recognized by -d, and we've proven the work is in default).
+ await execGit(['worktree', 'remove', wt.path, '--force'], sourceWorkspace)
+ .catch(async (err) => {
+ console.log(`⚠️ worktree remove failed for ${wt.path}, manual cleanup: ${err.message}`);
+ await rm(wt.path, { recursive: true, force: true }).catch(() => {});
+ await execGit(['worktree', 'prune'], sourceWorkspace).catch(() => {});
+ });
+ await execGit(['branch', '-D', branchName], sourceWorkspace).catch(err => {
+ console.log(`⚠️ branch delete failed for ${branchName}: ${err.message}`);
+ });
+ reaped.push({ path: wt.path, branch: branchName, locked: !!wt.locked });
+ }
+
+ if (reaped.length > 0) {
+ console.log(`🌳 ${dryRun ? 'Would reap' : 'Reaped'} ${reaped.length} merged worktree(s): ${reaped.map(r => r.branch).join(', ')}`);
+ }
+
+ return { reaped, skipped, defaultBranch, target, dryRun };
+}
+
/**
* Clean up worktree directories that belong to external repos (managed apps).
* These are created when agents work on apps outside PortOS but use the shared
diff --git a/server/services/worktreeManager.test.js b/server/services/worktreeManager.test.js
index 518e52ebd6..48a1a37ab1 100644
--- a/server/services/worktreeManager.test.js
+++ b/server/services/worktreeManager.test.js
@@ -1,6 +1,6 @@
import { describe, it, expect } from 'vitest';
import { join } from 'path';
-import { shouldRefuseDefaultBranchMerge, isHumanClaimWorktree } from './worktreeManager.js';
+import { shouldRefuseDefaultBranchMerge, isHumanClaimWorktree, classifyWorktreeDirt } from './worktreeManager.js';
/**
* Tests for the worktree manager service.
@@ -244,6 +244,40 @@ describe('Auto-generated Lockfile Detection', () => {
});
});
+describe('classifyWorktreeDirt (real exported helper)', () => {
+ it('reports clean for empty / whitespace-only porcelain', () => {
+ expect(classifyWorktreeDirt('')).toEqual({ clean: true, lockfileOnly: false, lockfilePaths: [], hasRealChanges: false });
+ expect(classifyWorktreeDirt(' \n ').clean).toBe(true);
+ expect(classifyWorktreeDirt(null).clean).toBe(true);
+ });
+
+ it('flags real (non-lockfile) changes', () => {
+ const r = classifyWorktreeDirt(' M src/index.js');
+ expect(r.clean).toBe(false);
+ expect(r.hasRealChanges).toBe(true);
+ expect(r.lockfileOnly).toBe(false);
+ });
+
+ it('recognizes a lockfile-only working tree and extracts paths', () => {
+ const r = classifyWorktreeDirt(' M package-lock.json\n M client/package-lock.json');
+ expect(r.lockfileOnly).toBe(true);
+ expect(r.hasRealChanges).toBe(false);
+ expect(r.lockfilePaths).toEqual(['package-lock.json', 'client/package-lock.json']);
+ });
+
+ it('treats mixed lockfile + real changes as real changes', () => {
+ const r = classifyWorktreeDirt(' M package-lock.json\n M src/app.js');
+ expect(r.lockfileOnly).toBe(false);
+ expect(r.hasRealChanges).toBe(true);
+ });
+
+ it('handles a trimmed first line (no leading status space)', () => {
+ const r = classifyWorktreeDirt('M yarn.lock');
+ expect(r.lockfileOnly).toBe(true);
+ expect(r.lockfilePaths).toEqual(['yarn.lock']);
+ });
+});
+
describe('Broken Worktree Detection', () => {
// Mirrors the rev-parse validation logic in removeWorktree that prevents
// git status from resolving to a parent repo (e.g., PortOS) when the
diff --git a/server/services/worktreeReap.test.js b/server/services/worktreeReap.test.js
new file mode 100644
index 0000000000..a9c52c98af
--- /dev/null
+++ b/server/services/worktreeReap.test.js
@@ -0,0 +1,226 @@
+/**
+ * Integration tests for merge-verified worktree reaping.
+ *
+ * These exercise REAL git (in a throwaway temp repo) rather than mirroring the
+ * logic inline, because the squash-merge detection in isBranchMergedInto relies
+ * on git's own `commit-tree` + `cherry` patch-id behavior — a hand-mirrored copy
+ * wouldn't catch git-version quirks, and that detection is the safety gate the
+ * reaper trusts before deleting anything.
+ */
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtemp, rm, writeFile, mkdir } from 'fs/promises';
+import { existsSync, realpathSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+import { execGit } from '../lib/execGit.js';
+import { isBranchMergedInto } from './git.js';
+import { reapMergedWorktrees } from './worktreeManager.js';
+
+async function commitFile(dir, name, content, message) {
+ await writeFile(join(dir, name), content);
+ await execGit(['add', '.'], dir);
+ await execGit(['commit', '-m', message], dir);
+}
+
+async function initRepo() {
+ // realpath-resolve: on macOS mkdtemp returns a /var symlink while
+ // `git worktree list` records the canonical /private/var path, which would
+ // break the reaper's startsWith() location checks and our path assertions.
+ const dir = realpathSync(await mkdtemp(join(tmpdir(), 'portos-reap-')));
+ await execGit(['init', '-b', 'main'], dir);
+ await execGit(['config', 'user.email', '[email protected]'], dir);
+ await execGit(['config', 'user.name', 'Test'], dir);
+ await execGit(['config', 'commit.gpgsign', 'false'], dir);
+ await commitFile(dir, 'base.txt', 'base\n', 'base');
+ return dir;
+}
+
+describe('isBranchMergedInto', () => {
+ let dir;
+ beforeEach(async () => { dir = await initRepo(); });
+ afterEach(async () => { await rm(dir, { recursive: true, force: true }); });
+
+ it('detects a normal (--no-ff) merge', async () => {
+ await execGit(['checkout', '-b', 'feat'], dir);
+ await commitFile(dir, 'feat.txt', 'work\n', 'feat work');
+ await execGit(['checkout', 'main'], dir);
+ await execGit(['merge', '--no-ff', 'feat', '--no-edit'], dir);
+
+ expect(await isBranchMergedInto(dir, 'feat', 'main')).toBe(true);
+ });
+
+ it('detects a squash merge (branch tip is NOT an ancestor)', async () => {
+ await execGit(['checkout', '-b', 'squashed'], dir);
+ await commitFile(dir, 's1.txt', 'one\n', 'commit one');
+ await commitFile(dir, 's2.txt', 'two\n', 'commit two');
+ await execGit(['checkout', 'main'], dir);
+ await execGit(['merge', '--squash', 'squashed'], dir);
+ await execGit(['commit', '-m', 'squashed work'], dir);
+
+ // Sanity: the original tip is genuinely not reachable from main.
+ const ancestor = await execGit(['merge-base', '--is-ancestor', 'squashed', 'main'], dir, { ignoreExitCode: true });
+ expect(ancestor.exitCode).not.toBe(0);
+
+ expect(await isBranchMergedInto(dir, 'squashed', 'main')).toBe(true);
+ });
+
+ it('detects a multi-commit rebase merge after the target branch advanced', async () => {
+ await execGit(['checkout', '-b', 'rebased'], dir);
+ await commitFile(dir, 'r1.txt', 'one\n', 'rebase commit one');
+ await commitFile(dir, 'r2.txt', 'two\n', 'rebase commit two');
+
+ const firstCommit = (await execGit(['rev-parse', 'rebased~1'], dir)).stdout.trim();
+ const secondCommit = (await execGit(['rev-parse', 'rebased'], dir)).stdout.trim();
+
+ await execGit(['checkout', 'main'], dir);
+ await commitFile(dir, 'target-advanced.txt', 'advanced\n', 'target advanced');
+ await execGit(['cherry-pick', firstCommit], dir);
+ await execGit(['cherry-pick', secondCommit], dir);
+
+ const ancestor = await execGit(['merge-base', '--is-ancestor', 'rebased', 'main'], dir, { ignoreExitCode: true });
+ expect(ancestor.exitCode).not.toBe(0);
+
+ expect(await isBranchMergedInto(dir, 'rebased', 'main')).toBe(true);
+ });
+
+ it('returns false for an unmerged branch with unique work', async () => {
+ await execGit(['checkout', '-b', 'pending'], dir);
+ await commitFile(dir, 'pending.txt', 'wip\n', 'wip');
+ await execGit(['checkout', 'main'], dir);
+
+ expect(await isBranchMergedInto(dir, 'pending', 'main')).toBe(false);
+ });
+
+ it('returns false for missing refs and self-comparison', async () => {
+ expect(await isBranchMergedInto(dir, 'nope', 'main')).toBe(false);
+ expect(await isBranchMergedInto(dir, 'main', 'nope')).toBe(false);
+ expect(await isBranchMergedInto(dir, 'main', 'main')).toBe(false);
+ });
+});
+
+describe('reapMergedWorktrees', () => {
+ let dir;
+ beforeEach(async () => { dir = await initRepo(); });
+ afterEach(async () => { await rm(dir, { recursive: true, force: true }); });
+
+ // The reaper only considers trees under WORKTREES_DIR (the real CoS data dir)
+ // or <repo>/.claude/worktrees — so the test trees live under .claude/worktrees.
+ const claudeRoot = (d) => join(d, '.claude', 'worktrees');
+
+ async function addWorktree(d, name, branch, { commit = true, base = 'main' } = {}) {
+ const path = join(claudeRoot(d), name);
+ await mkdir(claudeRoot(d), { recursive: true });
+ await execGit(['worktree', 'add', '-b', branch, path, base], d);
+ if (commit) await commitFile(path, `${name}.txt`, `${name}\n`, `${name} work`);
+ return path;
+ }
+
+ it('reaps a merged + clean worktree (and its branch) but preserves an unmerged one', async () => {
+ const mergedPath = await addWorktree(dir, 'merged', 'merged-br');
+ const unmergedPath = await addWorktree(dir, 'pending', 'pending-br');
+
+ // Merge only the first branch into main.
+ await execGit(['merge', '--no-ff', 'merged-br', '--no-edit'], dir);
+
+ const result = await reapMergedWorktrees(dir, { includeClaudeTrees: true });
+
+ expect(result.reaped.map(r => r.branch)).toContain('merged-br');
+ expect(result.reaped.map(r => r.branch)).not.toContain('pending-br');
+ expect(result.skipped.find(s => s.path === unmergedPath)?.reason).toBe('unmerged');
+
+ expect(existsSync(mergedPath)).toBe(false);
+ expect(existsSync(unmergedPath)).toBe(true);
+
+ const branches = (await execGit(['branch', '--format=%(refname:short)'], dir)).stdout.trim().split('\n');
+ expect(branches).not.toContain('merged-br');
+ expect(branches).toContain('pending-br');
+ });
+
+ it('preserves a merged worktree that has uncommitted changes', async () => {
+ const path = await addWorktree(dir, 'dirty', 'dirty-br');
+ await execGit(['merge', '--no-ff', 'dirty-br', '--no-edit'], dir);
+ // Introduce a real (non-lockfile) uncommitted change in the worktree.
+ await writeFile(join(path, 'scratch.txt'), 'unsaved\n');
+
+ const result = await reapMergedWorktrees(dir, { includeClaudeTrees: true });
+
+ expect(result.reaped.map(r => r.branch)).not.toContain('dirty-br');
+ expect(result.skipped.find(s => s.path === path)?.reason).toBe('uncommitted');
+ expect(existsSync(path)).toBe(true);
+ });
+
+ it('preserves a fresh-from-main worktree with uncommitted changes', async () => {
+ const path = await addWorktree(dir, 'not-started', 'not-started-br', { commit: false });
+ await writeFile(join(path, 'scratch.txt'), 'unsaved\n');
+
+ const result = await reapMergedWorktrees(dir, { includeClaudeTrees: true });
+
+ expect(result.reaped.map(r => r.branch)).not.toContain('not-started-br');
+ expect(result.skipped.find(s => s.path === path)?.reason).toBe('uncommitted');
+ expect(existsSync(path)).toBe(true);
+ });
+
+ it('preserves a merged worktree with lockfile-only uncommitted changes', async () => {
+ const path = await addWorktree(dir, 'lockfile-dirty', 'lockfile-dirty-br');
+ await execGit(['merge', '--no-ff', 'lockfile-dirty-br', '--no-edit'], dir);
+ await writeFile(join(path, 'package-lock.json'), '{}\n');
+
+ const result = await reapMergedWorktrees(dir, { includeClaudeTrees: true });
+
+ expect(result.reaped.map(r => r.branch)).not.toContain('lockfile-dirty-br');
+ expect(result.skipped.find(s => s.path === path)?.reason).toBe('uncommitted');
+ expect(existsSync(path)).toBe(true);
+ });
+
+ it('preserves a locked merged worktree', async () => {
+ const path = await addWorktree(dir, 'locked', 'locked-br');
+ await execGit(['merge', '--no-ff', 'locked-br', '--no-edit'], dir);
+ await execGit(['worktree', 'lock', path], dir);
+
+ const result = await reapMergedWorktrees(dir, { includeClaudeTrees: true });
+
+ expect(result.reaped.map(r => r.branch)).not.toContain('locked-br');
+ expect(result.skipped.find(s => s.path === path)?.reason).toBe('locked');
+ expect(existsSync(path)).toBe(true);
+ });
+
+ it('skips active agents and never touches the primary worktree', async () => {
+ const path = await addWorktree(dir, 'agent-active', 'active-br');
+ await execGit(['merge', '--no-ff', 'active-br', '--no-edit'], dir);
+
+ const result = await reapMergedWorktrees(dir, {
+ includeClaudeTrees: true,
+ activeAgentIds: new Set(['agent-active'])
+ });
+
+ expect(result.reaped.map(r => r.branch)).not.toContain('active-br');
+ expect(result.skipped.find(s => s.path === path)?.reason).toBe('active-agent');
+ expect(existsSync(path)).toBe(true);
+ // The main repo checkout is never reported as reaped or skipped-with-branch.
+ expect(result.reaped.find(r => r.branch === 'main')).toBeUndefined();
+ });
+
+ it('does not delete in dryRun mode', async () => {
+ const path = await addWorktree(dir, 'dry', 'dry-br');
+ await execGit(['merge', '--no-ff', 'dry-br', '--no-edit'], dir);
+
+ const result = await reapMergedWorktrees(dir, { includeClaudeTrees: true, dryRun: true });
+
+ expect(result.dryRun).toBe(true);
+ expect(result.reaped.map(r => r.branch)).toContain('dry-br');
+ expect(existsSync(path)).toBe(true);
+ const branches = (await execGit(['branch', '--format=%(refname:short)'], dir)).stdout.trim().split('\n');
+ expect(branches).toContain('dry-br');
+ });
+
+ it('excludes .claude trees when includeClaudeTrees is false', async () => {
+ const path = await addWorktree(dir, 'excluded', 'excluded-br');
+ await execGit(['merge', '--no-ff', 'excluded-br', '--no-edit'], dir);
+
+ const result = await reapMergedWorktrees(dir, { includeClaudeTrees: false });
+
+ expect(result.reaped.map(r => r.branch)).not.toContain('excluded-br');
+ expect(result.skipped.find(s => s.path === path)?.reason).toBe('claude-tree-excluded');
+ expect(existsSync(path)).toBe(true);
+ });
+});