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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix([issue-5862]): parse git's worktree porcelain as CRLF, unbreaking Windows CI
[._.]/ Adam Eivyeee21790fca8
diff --git a/scripts/ci-test-plan.js b/scripts/ci-test-plan.jsindex 484722a92f..a816ecae62 100644--- a/scripts/ci-test-plan.js+++ b/scripts/ci-test-plan.js@@ -39,6 +39,15 @@ const WINDOWS_RISK_RULES = [/^scripts\/fix-windows-console(?:\.test)?\.js$/,/^scripts\/ps1-bom\.test\.js$/,/^server\/lib\/(?:bufferedSpawn|detachedSpawn|childProcess|bashResolver|processEnv|platform|spawnCwd|cliProviderRun|grok)\b/,+ // Path SEMANTICS differ per platform in ways pinPlatform() cannot fake: NTFS+ // and APFS are case-insensitive while ext4 is not, and git reports paths its+ // own way (drive-letter case, 8.3 short names like C:\Users\RUNNER~1). A+ // case-sensitive containment check therefore passed on Linux while reporting a+ // managed worktree as unmanaged on Windows, and the reaper silently skipped it+ // — green everywhere CI looked. These modules decide containment and worktree+ // identity, so they need a real Windows run.+ /^server\/lib\/(?:pathSafety|worktreeOwnership)(?:\.test)?\.js$/,+ /^server\/services\/worktree(?:Manager|Reap)\b/,/^server\/lib\/shell(?:Cd|Exit|LivenessProbe|ReadinessProbe)(?:\.test)?\.js$/,/^server\/lib\/agentGuard\//,/^server\/cos-runner\//,diff --git a/server/lib/fileUtils.test.js b/server/lib/fileUtils.test.jsindex aa2e180f15..1be6573b1d 100644--- a/server/lib/fileUtils.test.js+++ b/server/lib/fileUtils.test.js@@ -814,6 +814,27 @@ describe('fileUtils', () => {expect(isPathInsideDir('/data/uploads', '/etc/passwd')).toBe(false);});+ // Windows and macOS filesystems are case-insensitive, so two spellings of+ // one directory are one directory. A case-SENSITIVE prefix compare reported+ // a managed worktree as `worktree-unmanaged-location` and the reaper+ // silently never reaped it — git reports paths its own way (drive-letter+ // case, 8.3 short names), which need not match how PortOS spelled the root.+ it('matches case-insensitively only where the filesystem is', () => {+ const insensitive = process.platform === 'win32' || process.platform === 'darwin';+ expect(isPathInsideDir('/data/Uploads', '/data/uploads/foo.png')).toBe(insensitive);+ expect(isPathInsideDir('/data/uploads', '/data/UPLOADS/sub/foo.png')).toBe(insensitive);+ });++ // Case-folding must only ever recognize the SAME directory — never widen+ // containment to a sibling or admit a traversal.+ it('still rejects escapes and prefix-sibling directories under case-folding', () => {+ expect(isPathInsideDir('/data/Uploads', '/data/uploads-evil/foo.png')).toBe(false);+ expect(isPathInsideDir('/data/Uploads', '/data/UPLOADS/../etc/passwd')).toBe(false);+ expect(isPathInsideDir('/data/Uploads', '/etc/passwd')).toBe(false);+ // The root itself is not "inside" itself, in either casing.+ expect(isPathInsideDir('/data/Uploads', '/data/uploads')).toBe(false);+ });+it('rejects a sibling dir whose name merely starts with the root (the trailing-sep bug)', () => {// The old `startsWith(DIR)` check without a trailing separator let// `/data/uploads-evil/x` slip through because the string prefix matched.diff --git a/server/lib/pathSafety.js b/server/lib/pathSafety.jsindex 6b17156690..f0221f04cd 100644--- a/server/lib/pathSafety.js+++ b/server/lib/pathSafety.js@@ -1,6 +1,7 @@/** Filename validation, containment checks, and approved asset resolution. */import { existsSync, statSync } from 'fs';import { basename, join, resolve as resolvePath, sep as PATH_SEP } from 'path';+import { platform } from 'os';import { ServerError } from './errorHandler.js';import { PATHS } from './paths.js';import { escapeRegExp } from './textUtils.js';@@ -122,16 +123,31 @@ export function isTopLevelEntryName(name) {* NOT reported as "inside" (there's no trailing separator on the bare root),* which is the desired behavior for file-containment checks.*+ * Comparison is case-INSENSITIVE on Windows and macOS, whose filesystems are.+ * A bare `startsWith` there reports `C:\\Users\\Foo\\wt` as outside+ * `C:\\Users\\foo`, even though both name the same directory — so a managed+ * worktree read as `worktree-unmanaged-location` and was silently never reaped.+ * Git is a live source of such spellings: `git worktree list` reports paths the+ * way git normalized them (drive-letter case, 8.3 short names like+ * `C:\\Users\\RUNNER~1`), which need not match how PortOS spelled the root.+ * Case-folding only ever makes containment recognize paths that ARE the same+ * file on that platform; it can never admit a path from outside the root, so+ * the security posture is unchanged. Linux stays case-sensitive, where two+ * spellings really are two different directories.+ ** @param {string} dir - the containing directory (absolute or relative)* @param {string} candidatePath - the path to test* @returns {boolean}*/+const CASE_INSENSITIVE_FS = platform() === 'win32' || platform() === 'darwin';+export function isPathInsideDir(dir, candidatePath) {if (typeof dir !== 'string' || typeof candidatePath !== 'string' || !dir || !candidatePath) {return false;}- const rootPrefix = resolvePath(dir) + PATH_SEP;- return resolvePath(candidatePath).startsWith(rootPrefix);+ const fold = (p) => (CASE_INSENSITIVE_FS ? p.toLowerCase() : p);+ const rootPrefix = fold(resolvePath(dir) + PATH_SEP);+ return fold(resolvePath(candidatePath)).startsWith(rootPrefix);}/**diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.jsindex a80da8b151..60c06dba6e 100644--- a/server/services/worktreeManager.js+++ b/server/services/worktreeManager.js@@ -958,14 +958,22 @@ export async function mergeBaseIntoFeatureWorktree(featureAgentId, baseBranch) {}/**- * List all active worktrees for the repository+ * List all active worktrees for the repository.+ *+ * Split on CRLF as well as LF. On Windows git's porcelain output is CRLF, and a+ * bare `split('\n')` leaves a trailing \r on every value: `path` and `branch`+ * silently carry it, so containment checks and path equality match nothing, and+ * the flag lines never compare equal (`'bare\r' !== 'bare'`) so `bare`,+ * `detached`, `locked` and `prunable` all read as false. That is what made the+ * reaper report a managed worktree as `worktree-unmanaged-location` on Windows+ * and skip it forever, while every Linux run stayed green.*/export async function listWorktrees(sourceWorkspace) {const { stdout } = await execGit(['worktree', 'list', '--porcelain'], sourceWorkspace);const worktrees = [];let current = {};- for (const line of stdout.split('\n')) {+ for (const line of stdout.split(/\r?\n/)) {if (line.startsWith('worktree ')) {if (current.path) worktrees.push(current);current = { path: line.slice(9) };diff --git a/server/services/worktreeManager.test.js b/server/services/worktreeManager.test.jsindex 150e971a73..b170c8068c 100644--- a/server/services/worktreeManager.test.js+++ b/server/services/worktreeManager.test.js@@ -42,6 +42,7 @@ const {findAdoptableWorktreeForBranch,createWorktree,createPersistentWorktree,+ listWorktrees,} = await import('./worktreeManager.js');const { isPathInsideDir } = await import('../lib/fileUtils.js');const { worktreeOwnershipReason } = await import('../lib/worktreeOwnership.js');@@ -581,6 +582,47 @@ describe('isGitLockError (worktree add lock detection, #2193)', () => {});});+// Windows git emits CRLF, and a bare split('\n') leaves a trailing \r on every+// parsed value. That is invisible on Linux and silently breaks the reaper on+// Windows: the path and branch carry the \r so containment and equality match+// nothing, and the flag lines stop comparing equal so bare/detached/locked/+// prunable all read false. It failed a real Windows CI job for hours while every+// Linux run stayed green, so the contract is pinned against BOTH line endings.+describe('listWorktrees line endings', () => {+ beforeEach(() => { execGitMock.mockReset(); });++ const PORCELAIN = [+ 'worktree /repo',+ 'HEAD abc123',+ 'branch refs/heads/main',+ '',+ 'worktree /repo/.claude/worktrees/wt',+ 'HEAD def456',+ 'branch refs/heads/feature',+ 'locked',+ 'prunable',+ '',+ ];++ it.each([['LF', '\n'], ['CRLF', '\r\n']])('parses %s porcelain identically', async (_label, eol) => {+ execGitMock.mockResolvedValueOnce({ stdout: PORCELAIN.join(eol), stderr: '', exitCode: 0 });++ const worktrees = await listWorktrees('/repo');++ expect(worktrees).toHaveLength(2);+ // No stray \r anywhere — these values are compared against filesystem paths+ // and branch names, where a trailing carriage return matches nothing.+ expect(worktrees[0]).toMatchObject({ path: '/repo', head: 'abc123', branch: 'refs/heads/main' });+ expect(worktrees[1]).toMatchObject({+ path: '/repo/.claude/worktrees/wt',+ head: 'def456',+ branch: 'refs/heads/feature',+ locked: true,+ prunable: true,+ });+ });+});+describe('addWorktreeWithRetry (lock-contention retry, #2193)', () => {beforeEach(() => {execGitMock.mockReset();