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

fix: unbreak the Windows update, CoS worktree creation, and worktree reaping

[._.]/ Adam Eivy4b619a9846d8
diff --git a/.changelog/next/fixed-main.md b/.changelog/next/fixed-main.md
new file mode 100644
index 0000000000..8d31522e56
--- /dev/null
+++ b/.changelog/next/fixed-main.md
@@ -0,0 +1,3 @@
+- Windows: the update script aborted before building the client and restarting, because Node refuses to spawn npm.cmd without a shell (EINVAL) — leaving the UI permanently reporting a stale client build
+- Windows: git worktree add for CoS agents timed out at 30s on a full checkout, blocking tasks with worktree-failed while git actually completed the worktree
+- Windows: orphaned and merged CoS worktrees were never cleaned up, because git reports POSIX paths while PortOS built Windows ones
diff --git a/scripts/ensure-deps.js b/scripts/ensure-deps.js
index e48edd00ea..cdda3e453a 100644
--- a/scripts/ensure-deps.js
+++ b/scripts/ensure-deps.js
@@ -8,7 +8,16 @@ import { execFileSync } from 'child_process';
import { createHash } from 'crypto';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
-import { rebuildTrusted, NPM } from './trusted-rebuilds.js';
+import { rebuildTrusted } from './trusted-rebuilds.js';
+// Node refuses to spawn npm's `.cmd` shim under `shell:false` (CVE-2024-27980),
+// so every npm spawn goes through this wrap. Safe to import before `npm install`
+// has ever run — bufferedSpawn's whole import graph is Node builtins only.
+import { prepareCliSpawn } from '../server/lib/bufferedSpawn.js';
+
+const npmSpawn = (args, options) => {
+ const { command, args: spawnArgs } = prepareCliSpawn('npm', args);
+ return execFileSync(command, spawnArgs, options);
+};
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
@@ -108,7 +117,7 @@ function cleanWorkspaceDeps(dir) {
function install(dir, label) {
try {
- execFileSync(NPM, ['install'], { cwd: dir, stdio: 'inherit', windowsHide: true });
+ npmSpawn(['install'], { cwd: dir, stdio: 'inherit', windowsHide: true });
return rebuildTrusted(dir, label);
} catch (err) {
console.error(`⚠️ npm install failed for ${label}: ${err.message ?? err}`);
@@ -120,7 +129,7 @@ function install(dir, label) {
return false;
}
try {
- execFileSync(NPM, ['install'], { cwd: dir, stdio: 'inherit', windowsHide: true });
+ npmSpawn(['install'], { cwd: dir, stdio: 'inherit', windowsHide: true });
return rebuildTrusted(dir, label);
} catch (retryErr) {
console.error(`❌ npm install failed for ${label} after retry: ${retryErr.message ?? retryErr}`);
diff --git a/scripts/run-ci-tests.js b/scripts/run-ci-tests.js
index ea5c11fb25..e95fbd4224 100644
--- a/scripts/run-ci-tests.js
+++ b/scripts/run-ci-tests.js
@@ -1,6 +1,7 @@
#!/usr/bin/env node
import { spawnSync } from 'child_process';
+import { prepareCliSpawn } from '../server/lib/bufferedSpawn.js';
const scope = process.argv[2];
if (!['server', 'client'].includes(scope)) {
@@ -40,12 +41,15 @@ if (mode === 'files' && selectedFiles.length === 0) {
process.exit(0);
}
-const npmCommand = process.platform === 'win32' ? 'npm.cmd' : 'npm';
const run = (extraArgs, label) => {
const args = ['run', 'test:ci', '--prefix', scope];
if (extraArgs.length > 0) args.push('--', ...extraArgs);
console.log(`Running ${scope} ${label}${extraArgs.length ? ` (${extraArgs.length} selector argument(s))` : ''}.`);
- const result = spawnSync(npmCommand, args, {
+ // Wrapped, not a bare `npm.cmd`: Node refuses to spawn a `.cmd` under
+ // `shell:false` and throws EINVAL, so this script could never run on a
+ // Windows checkout. See server/lib/bufferedSpawn.js.
+ const { command, args: spawnArgs } = prepareCliSpawn('npm', args);
+ const result = spawnSync(command, spawnArgs, {
stdio: 'inherit',
env: process.env,
});
diff --git a/scripts/trusted-rebuilds.js b/scripts/trusted-rebuilds.js
index 4843b067d6..e17fcbfeff 100644
--- a/scripts/trusted-rebuilds.js
+++ b/scripts/trusted-rebuilds.js
@@ -21,12 +21,10 @@ import { execFileSync } from 'child_process';
import { existsSync, readdirSync } from 'fs';
import { join, dirname, resolve } from 'path';
import { fileURLToPath } from 'url';
+import { prepareCliSpawn } from '../server/lib/bufferedSpawn.js';
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
-/** npm's Windows shim. Shared so callers don't re-derive it. */
-export const NPM = process.platform === 'win32' ? 'npm.cmd' : 'npm';
-
/**
* Every directory npm can install into with that directory as the local prefix:
* the repo root plus each top-level directory carrying its own package.json.
@@ -96,7 +94,16 @@ export function rebuildTrusted(dir, label, { spawn = execFileSync } = {}) {
let ok = true;
for (const { pkgs, fatal } of groups) {
try {
- spawn(NPM, ['rebuild', ...pkgs], { cwd: dir, stdio: 'inherit', windowsHide: true });
+ // Through prepareCliSpawn: on Windows `npm` is a `.cmd` shim, and Node's
+ // CVE-2024-27980 patch REFUSES a `.cmd` target under `shell:false` with
+ // `spawnSync npm.cmd EINVAL`. Since the node-pty group is fatal, that
+ // throw exited this script 1, and `update.ps1` exits on a non-zero
+ // trusted-rebuilds — so every Windows update aborted before the client
+ // build and the pm2 restart, leaving the UI permanently reporting a stale
+ // client build. See server/lib/bufferedSpawn.js for why the fix is a
+ // `cmd.exe /c` wrap and not `shell:true` (which does not escape args).
+ const { command, args } = prepareCliSpawn('npm', ['rebuild', ...pkgs]);
+ spawn(command, args, { cwd: dir, stdio: 'inherit', windowsHide: true });
} catch (err) {
console.error(`⚠️ npm rebuild ${pkgs.join(' ')} failed for ${label}: ${err.message ?? err}`);
if (fatal) ok = false;
diff --git a/scripts/trusted-rebuilds.test.js b/scripts/trusted-rebuilds.test.js
index df0baa9873..67833cbacc 100644
--- a/scripts/trusted-rebuilds.test.js
+++ b/scripts/trusted-rebuilds.test.js
@@ -1,8 +1,10 @@
import { describe, it, expect } from 'vitest';
import { readFileSync, existsSync, readdirSync } from 'fs';
+import { execFileSync } from 'child_process';
import { join } from 'path';
import { TRUSTED_REBUILDS, discoverWorkspaces, workspaceDir, rebuildTrusted, runCli } from './trusted-rebuilds.js';
+import { prepareCliSpawn } from '../server/lib/bufferedSpawn.js';
// Discovered, not hand-listed: a hardcoded roster here would silently miss a
// workspace added later, leaving it with no `ignore-scripts` guard while this
@@ -225,8 +227,15 @@ describe('rebuildTrusted failure semantics', () => {
it('spawns one npm rebuild per group, with the group\'s packages', () => {
const calls = [];
- rebuildTrusted('/tmp', 'server', { spawn: (_bin, args) => calls.push(args) });
- expect(calls).toEqual(TRUSTED_REBUILDS.server.map((group) => ['rebuild', ...group.pkgs]));
+ rebuildTrusted('/tmp', 'server', { spawn: (bin, args) => calls.push([bin, args]) });
+ // Compared against prepareCliSpawn rather than a hardcoded `npm` + args pair:
+ // the launchable form is platform-dependent (on Windows npm is a `.cmd` shim
+ // that has to be wrapped), so pinning the POSIX shape would fail the suite on
+ // a Windows checkout.
+ expect(calls).toEqual(TRUSTED_REBUILDS.server.map((group) => {
+ const { command, args } = prepareCliSpawn('npm', ['rebuild', ...group.pkgs]);
+ return [command, args];
+ }));
});
it('fails when a fatal group fails', () => {
@@ -252,6 +261,26 @@ describe('rebuildTrusted failure semantics', () => {
});
});
+// Node ≥18.20.2 REFUSES to spawn a `.cmd`/`.bat` target under `shell:false` and
+// throws `spawnSync npm.cmd EINVAL`. Because the node-pty group is fatal, that
+// throw made `trusted-rebuilds.js server` exit 1, which made `update.ps1` exit
+// before the client build and the pm2 restart — so every Windows update left the
+// UI reporting "the served client build is older than the UI source", with no
+// way to clear it by updating again. bufferedSpawn owns the wrap; this asserts
+// the end-to-end property that regressed, on whatever platform CI runs.
+describe('npm spawn shape', () => {
+ it('never hands a bare .cmd/.bat to a shell-less spawn', () => {
+ const { command } = prepareCliSpawn('npm', ['rebuild', 'node-pty']);
+ expect(command, 'a .cmd target under shell:false throws EINVAL').not.toMatch(/\.(cmd|bat)$/i);
+ });
+
+ it('actually runs npm on this platform', () => {
+ const { command, args } = prepareCliSpawn('npm', ['--version']);
+ const out = execFileSync(command, args, { encoding: 'utf8', windowsHide: true });
+ expect(out.trim()).toMatch(/^\d+\.\d+\.\d+/);
+ });
+});
+
describe('runCli exit codes', () => {
const noop = () => {};
diff --git a/server/services/installState.test.js b/server/services/installState.test.js
index efc829d8c6..59212a61ab 100644
--- a/server/services/installState.test.js
+++ b/server/services/installState.test.js
@@ -39,10 +39,18 @@ const ROOT = '/repo';
// Build a statMtime mock from a { pathSuffix: mtimeMs } map. A path not present
// in the map resolves to null (absent), mirroring the real helper.
+//
+// The incoming path is separator-normalized because the real statMtime receives
+// paths built with `join` — on Windows those arrive as `\repo\client\dist\…` and
+// never match a `'client/dist/index.html'` suffix. Unnormalized, every
+// stale-build test saw "no bundle" and asserted against `null`, so the whole
+// staleBuild signal was untested on the platform whose false alarm prompted it.
+// Only the incoming path needs it; every key below is a POSIX literal.
function makeStat(map) {
return async (path) => {
+ const posixPath = String(path).replace(/\\/g, '/');
for (const [suffix, mtime] of Object.entries(map)) {
- if (path.endsWith(suffix)) return mtime;
+ if (posixPath.endsWith(suffix)) return mtime;
}
return null;
};
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.js
index 84d2d25ee7..1a54273712 100644
--- a/server/services/worktreeManager.js
+++ b/server/services/worktreeManager.js
@@ -11,14 +11,24 @@
import { existsSync, realpathSync } from 'fs';
import { readdir, rm, stat } from 'fs/promises';
-import { join } from 'path';
-import { ensureDir, PATHS, sleep, tryReadFile } from '../lib/fileUtils.js';
+import { join, win32 } from 'path';
+import { ensureDir, isPathInsideDir, PATHS, sleep, tryReadFile } from '../lib/fileUtils.js';
import { DONE_SENTINEL_NAME, doneSentinelName } from '../lib/agentSentinel.js';
import { execGit } from '../lib/execGit.js';
import { createKeyCachedQueue } from '../lib/createKeyCachedQueue.js';
import { ensureInstanceId } from './instances.js';
const WORKTREES_DIR = PATHS.worktrees;
+// `git worktree list --porcelain` reports POSIX separators on every platform —
+// `H:/repo/data/cos/worktrees/agent-x` — while WORKTREES_DIR is built with
+// `join` and is backslash-separated on Windows. So a git-reported path is never
+// compared with a bare `startsWith`/`split('/')`: `isPathInsideDir` resolves
+// both sides first (and rejects a sibling like `worktrees-old`), and
+// `win32.basename` treats either separator as one. Before this, every CoS
+// worktree failed the containment check on Windows — `cleanupOrphanedWorktrees`
+// skipped them all and `reapMergedWorktrees` filed them as `unmanaged-location`,
+// so the daily line read "reaped 0 merged + 0 orphaned" with orphans on disk.
+const worktreeAgentId = (worktreePath) => win32.basename(worktreePath || '');
// 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'];
// Cap the dirty paths named in a "worktree preserved" warning — the message ends
@@ -35,6 +45,17 @@ const DIRT_PATHS_IN_WARNING = 5;
const WORKTREE_ADD_MAX_ATTEMPTS = 4;
const WORKTREE_ADD_RETRY_DELAY_MS = 250;
+// `git worktree add` materializes a FULL checkout, so it is nothing like the
+// metadata reads execGit's 30s default was sized for: ~5.8k files here, and on
+// Windows every one of them is written through the AV filter driver, which puts
+// a cold add well past 30s. Worse, the timeout doesn't stop git — the checkout
+// keeps running and lands — so PortOS blocks the task with `worktree-failed`
+// while the worktree and branch it just gave up on exist on disk, which then
+// defeats the orphan-branch cleanup ("Cannot delete branch … checked out at …").
+// Ten minutes is far above any healthy add and still bounded. Applies to
+// `worktree move` too — it routes through this same wrapper.
+const WORKTREE_ADD_TIMEOUT_MS = 10 * 60 * 1000;
+
/**
* True when a git error message indicates lock/contention on the worktree or
* index lock (as opposed to a genuine, non-retryable failure like a bad ref,
@@ -45,9 +66,20 @@ const WORKTREE_ADD_RETRY_DELAY_MS = 250;
* (caught by `index.lock`), whereas `a branch named 'X' already exists` and
* `'<path>' already exists` are permanent. Exported for unit testing against
* real git lock-error wording.
+ *
+ * The "unable to create" alternative is anchored to a quoted `.lock` path on
+ * purpose. A bare `unable to create` also matches git's PER-FILE checkout
+ * failure, `error: unable to create file <path>: Permission denied` — exactly
+ * what a Windows AV filter driver produces mid-checkout. That is not lock
+ * contention and does not clear on retry, but it IS reached only after git has
+ * written most of the tree, so matching it spent the whole retry budget on
+ * repeated full checkouts: with WORKTREE_ADD_TIMEOUT_MS that is 4 × 10 min of
+ * head-of-line blocking on the per-repo queue for a permanent failure. The
+ * retry budget is sized for bookkeeping-lock failures, which fail in
+ * milliseconds.
*/
export function isGitLockError(message) {
- return /index\.lock|cannot lock|could not lock|unable to (?:create|write|lock)|already locked|another git process/i.test(message || '');
+ return /index\.lock|cannot lock|could not lock|unable to create '[^']*\.lock'|unable to (?:write|lock)|already locked|another git process/i.test(message || '');
}
/**
@@ -65,7 +97,7 @@ export function isGitLockError(message) {
* (#2193) — the branch is exactly the orphan it needs to delete.
*/
export function addWorktreeWithRetry(args, repo, attempt = 1, firstError = null) {
- return execGit(args, repo).catch((err) => {
+ return execGit(args, repo, { timeout: WORKTREE_ADD_TIMEOUT_MS }).catch((err) => {
const originalError = firstError || err;
if (attempt >= WORKTREE_ADD_MAX_ATTEMPTS || !isGitLockError(err.message)) {
err.firstAttemptError = originalError;
@@ -862,9 +894,9 @@ export async function cleanupOrphanedWorktrees(sourceWorkspace, activeAgentIds)
for (const wt of worktrees) {
// Only clean up worktrees under our managed directory
- if (!wt.path.startsWith(WORKTREES_DIR)) continue;
+ if (!isPathInsideDir(WORKTREES_DIR, wt.path)) continue;
- const agentId = wt.path.split('/').pop();
+ const agentId = worktreeAgentId(wt.path);
handledAgentIds.add(agentId);
// Never reap human-driven `/claim` worktrees (`claim-<slug>`) — they belong
// to the `/claim` command's own Phase 7 cleanup, not CoS. See isHumanClaimWorktree.
@@ -957,13 +989,13 @@ export async function reapMergedWorktrees(sourceWorkspace, {
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();
+ const agentId = worktreeAgentId(wt.path);
// 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);
+ const isCosTree = isPathInsideDir(WORKTREES_DIR, wt.path);
+ const isClaudeTree = isPathInsideDir(claudeTreesRoot, wt.path);
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; }
diff --git a/server/services/worktreeManager.test.js b/server/services/worktreeManager.test.js
index 3877df40e5..9e2d9abb89 100644
--- a/server/services/worktreeManager.test.js
+++ b/server/services/worktreeManager.test.js
@@ -39,6 +39,8 @@ const {
removeWorktree,
adoptWorktree,
} = await import('./worktreeManager.js');
+const { isPathInsideDir } = await import('../lib/fileUtils.js');
+const { win32 } = await import('path');
const { existsSync } = await import('fs');
const { PATHS } = await import('../lib/fileUtils.js');
@@ -391,11 +393,44 @@ describe('Broken Worktree Detection', () => {
});
});
+// Git reports POSIX separators on every platform, while PATHS.worktrees is
+// backslash-separated on Windows — so a bare `startsWith` matched nothing there:
+// `cleanupOrphanedWorktrees` skipped every CoS worktree and `reapMergedWorktrees`
+// filed them all as `unmanaged-location`, which is why the daily line read
+// "reaped 0 merged + 0 orphaned" on a Windows install with orphans on disk.
+// These pin the properties the module RELIES ON from the shared helpers, so a
+// change to either one surfaces here rather than as silent dead cleanup.
+describe('git-vs-PortOS path comparison', () => {
+ it('matches a git-reported POSIX path against a Windows worktrees dir', () => {
+ // win32-only: `resolvePath` folds `/` to `\` on Windows, which is what makes
+ // the mixed-separator comparison work. On POSIX a backslash is a legal
+ // filename character, so this case can't arise and isn't asserted.
+ if (process.platform !== 'win32') return;
+ expect(isPathInsideDir('H:\\repo\\data\\cos\\worktrees', 'H:/repo/data/cos/worktrees/agent-abc')).toBe(true);
+ });
+
+ it('does not match a sibling directory that merely shares a prefix', () => {
+ expect(isPathInsideDir('/repo/data/cos/worktrees', '/repo/data/cos/worktrees-old/agent-abc')).toBe(false);
+ });
+
+ it('does not treat the directory itself as being under itself', () => {
+ expect(isPathInsideDir('/repo/data/cos/worktrees', '/repo/data/cos/worktrees')).toBe(false);
+ });
+
+ it('reads the agent id off either separator', () => {
+ expect(win32.basename('H:/repo/data/cos/worktrees/agent-abc')).toBe('agent-abc');
+ expect(win32.basename('H:\\repo\\data\\cos\\worktrees\\agent-abc')).toBe('agent-abc');
+ });
+});
+
describe('Orphaned Worktree Detection', () => {
function findOrphanedWorktrees(worktrees, worktreesDir, activeAgentIds) {
return worktrees.filter(wt => {
- if (!wt.path.startsWith(worktreesDir)) return false;
- const agentId = wt.path.split('/').pop();
+ // The real helpers, not a local re-implementation: a mirrored copy here is
+ // exactly what let the Windows separator bug live in the shipped path
+ // while this suite stayed green.
+ if (!isPathInsideDir(worktreesDir, wt.path)) return false;
+ const agentId = win32.basename(wt.path);
// Mirror the real cleanup guard: human-driven `/claim` worktrees are
// never CoS orphans.
if (isHumanClaimWorktree(agentId)) return false;
@@ -528,6 +563,21 @@ describe('isGitLockError (worktree add lock detection, #2193)', () => {
expect(isGitLockError('')).toBe(false);
expect(isGitLockError(undefined)).toBe(false);
});
+
+ // A per-file checkout failure is NOT lock contention. It reads "unable to
+ // create", but it only happens after git has written most of the tree — so
+ // retrying it costs a full checkout per attempt. With the 10-minute add
+ // timeout that is 4 × 10 min of head-of-line blocking on the per-repo queue,
+ // for an error that never clears. This is the Windows AV-filter failure mode
+ // the long timeout exists to tolerate, so the two must not compound.
+ it('does NOT flag a per-file checkout failure as lock contention', () => {
+ expect(isGitLockError('error: unable to create file some/deep/path.js: Permission denied')).toBe(false);
+ expect(isGitLockError('error: unable to create symlink foo/bar: Operation not permitted')).toBe(false);
+ });
+
+ it('still flags a genuine lock-FILE creation failure', () => {
+ expect(isGitLockError("fatal: Unable to create '/repo/.git/config.lock': File exists")).toBe(true);
+ });
});
describe('addWorktreeWithRetry (lock-contention retry, #2193)', () => {
@@ -545,6 +595,21 @@ describe('addWorktreeWithRetry (lock-contention retry, #2193)', () => {
expect(execGitMock).toHaveBeenCalledTimes(1);
});
+ // See WORKTREE_ADD_TIMEOUT_MS for why 30s was not enough.
+ it('gives the add far more than execGit\'s 30s default, since it writes a full checkout', async () => {
+ execGitMock.mockResolvedValueOnce({ stdout: '', stderr: '', exitCode: 0 });
+ await addWorktreeWithRetry(['worktree', 'add', '/wt', 'main'], '/repo');
+ const [, , options] = execGitMock.mock.calls[0];
+ expect(options?.timeout).toBeGreaterThanOrEqual(5 * 60 * 1000);
+ });
+
+ it('does NOT retry a timeout — git is still running and would collide with itself', async () => {
+ execGitMock.mockRejectedValueOnce(new Error('git command timed out after 600s: git worktree add -b cos/t/a /wt origin/main'));
+ await expect(addWorktreeWithRetry(['worktree', 'add', '-b', 'cos/t/a', '/wt', 'origin/main'], '/repo'))
+ .rejects.toThrow(/timed out/);
+ expect(execGitMock).toHaveBeenCalledTimes(1);
+ });
+
it('retries a lock error then succeeds', async () => {
execGitMock
.mockRejectedValueOnce(new Error("Unable to create '/repo/.git/index.lock': File exists"))
@@ -774,7 +839,13 @@ describe('adoptWorktree — resuming an interrupted run in its own worktree', ()
it('moves the dead run’s tree to the retrying agent’s directory', async () => {
const result = await adoptWorktree('agent-new', '/repo', DEAD_TREE, 'cos/task-1/agent-dead');
- expect(execGitMock).toHaveBeenCalledWith(['worktree', 'move', DEAD_TREE, NEW_TREE], '/repo');
+ // Third arg is the long add/move timeout — a move relocates a whole checkout,
+ // so it needs the same headroom as the add it shares a wrapper with.
+ expect(execGitMock).toHaveBeenCalledWith(
+ ['worktree', 'move', DEAD_TREE, NEW_TREE],
+ '/repo',
+ expect.objectContaining({ timeout: expect.any(Number) })
+ );
expect(result).toMatchObject({
worktreePath: NEW_TREE, branchName: 'cos/task-1/agent-dead',
existingBranch: true, adopted: true
diff --git a/server/services/worktreeReap.test.js b/server/services/worktreeReap.test.js
index a9c52c98af..c431bf969b 100644
--- a/server/services/worktreeReap.test.js
+++ b/server/services/worktreeReap.test.js
@@ -16,6 +16,16 @@ import { execGit } from '../lib/execGit.js';
import { isBranchMergedInto } from './git.js';
import { reapMergedWorktrees } from './worktreeManager.js';
+/**
+ * Why `wantedPath` was skipped, matched separator-insensitively — `skipped[].path`
+ * is git's POSIX output while these tests build paths with `join()`. See the
+ * WORKTREES_DIR comment in worktreeManager.js for the full failure mode.
+ */
+function skipReason(result, wantedPath) {
+ const posix = (p) => (p || '').replace(/\\/g, '/');
+ return result.skipped.find((s) => posix(s.path) === posix(wantedPath))?.reason;
+}
+
async function commitFile(dir, name, content, message) {
await writeFile(join(dir, name), content);
await execGit(['add', '.'], dir);
@@ -126,7 +136,7 @@ describe('reapMergedWorktrees', () => {
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(skipReason(result, unmergedPath)).toBe('unmerged');
expect(existsSync(mergedPath)).toBe(false);
expect(existsSync(unmergedPath)).toBe(true);
@@ -145,7 +155,7 @@ describe('reapMergedWorktrees', () => {
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(skipReason(result, path)).toBe('uncommitted');
expect(existsSync(path)).toBe(true);
});
@@ -156,7 +166,7 @@ describe('reapMergedWorktrees', () => {
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(skipReason(result, path)).toBe('uncommitted');
expect(existsSync(path)).toBe(true);
});
@@ -168,7 +178,7 @@ describe('reapMergedWorktrees', () => {
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(skipReason(result, path)).toBe('uncommitted');
expect(existsSync(path)).toBe(true);
});
@@ -180,7 +190,7 @@ describe('reapMergedWorktrees', () => {
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(skipReason(result, path)).toBe('locked');
expect(existsSync(path)).toBe(true);
});
@@ -194,7 +204,7 @@ describe('reapMergedWorktrees', () => {
});
expect(result.reaped.map(r => r.branch)).not.toContain('active-br');
- expect(result.skipped.find(s => s.path === path)?.reason).toBe('active-agent');
+ expect(skipReason(result, path)).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();
@@ -220,7 +230,7 @@ describe('reapMergedWorktrees', () => {
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(skipReason(result, path)).toBe('claude-tree-excluded');
expect(existsSync(path)).toBe(true);
});
});