From 6d4e335001c755528d75a5479c99e20cbee0d914 Mon Sep 17 00:00:00 2001 From: Brennan Benson <79079362+brennanb2025@users.noreply.github.com> Date: Tue, 28 Jul 2026 14:04:41 -0700 Subject: [PATCH] feat(worktrees): support project-level worktree.sharedDirectories in orca.yaml (#10459) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(worktrees): support project-level worktree.sharedDirectories in orca.yaml Follow-up to #7549: `.worktreeinclude` copies gitignored paths into each new worktree, which is right for `.env`/`.vscode/` but wrong for large rebuildable directories. Copying `node_modules` per worktree is slow and duplicates disk, and each worktree's install then diverges. Adds `worktree.sharedDirectories` to `orca.yaml` — a versioned, in-repo list of gitignored directories that are symlinked (shared) into every new local worktree, so one install serves them all. Adds to, never replaces, the per-user Worktree Shared Paths setting. `createWorktreeSharedPaths` uses a new 'share' materialization mode that always symlinks. The existing 'link' mode APFS clone-copies on macOS, which would give each worktree an independent node_modules and defeat the point; 'link' and 'copy' behavior are unchanged. Entries must exist as gitignored directories in the primary checkout; absolute paths, `..` traversal, and `.git` are rejected. Resolution never throws, so a malformed orca.yaml cannot block worktree creation. Remote (SSH) creation skips this, as it does symlink paths and `.worktreeinclude`. Closes #10451 * fix(worktrees): keep worktrees deletable after sharing a directory A directory-only ignore rule (`node_modules/`, the common spelling) matches the primary checkout's real directory, so the shared directory resolves and gets symlinked — but it never matches the worktree's symlink, so Git reports that link as untracked. Deletion only tolerated the per-user shared paths, so every worktree in such a repo became permanently dirty: the clean preflight threw "uncommitted or untracked changes" and `git worktree remove` refused without --force. Feed the configured `orca.yaml` shared directories into the same tolerate-and-unlink machinery the per-user shared paths already use, at both deletion call sites. The names are read unfiltered, since the create-time resolver drops exactly the entry deletion needs most. * test(worktrees): register createWorktreeSharedPaths in the runtime symlink mock orca-runtime.ts imports createWorktreeSharedPaths, but the vi.mock factory for ../ipc/worktree-symlinks never listed it. Vitest resolves omitted exports lazily, so this only stays green because no runtime test configures a repo with worktree.sharedDirectories — the first one that does would fail on a mock resolution error rather than on its own assertion. * fix(source-control): don't count shared symlinks as uncommitted changes A directory-only ignore rule (`node_modules/`) matches the primary checkout's real directory but never the worktree's symlink, so Git reports the shared link as untracked for the life of the worktree. That made every affected worktree read as dirty: a phantom row in the diff view, and Create PR blocked with `blockedReason: 'dirty'` telling the user to commit an entry they cannot commit, because it is a symlink Orca created. Status and the review-creation preflight now drop untracked entries that are both declared shared (per-user shared paths or orca.yaml sharedDirectories) and actually symlinks on disk. Both conditions are required, so a regular file at a declared name, or a symlink nobody declared, still counts as user work. The decision fails closed: anything not positively identified stays dirty. The preflight moves to `--porcelain -z` so paths with spaces or non-ASCII bytes are compared raw rather than C-quoted, with a parser that consumes the origin field a rename emits instead of reading it as its own record. Symlink detection moves to a leaf module: importing it from ipc/worktree-symlinks would pull APFS cloning, and its child_process dependency, into the status graph. SSH is unaffected and left alone — remote worktree creation skips the symlink and shared-directory passes, so a remote worktree never has one. * fix(source-control): wire shared links into local status * fix(worktrees): resolve the status repo once and reject uncollapsed shared paths `git:status` resolved the registered worktree's repo twice per call — once inside `getLocalGitOptionsForRegisteredWorktree` and again for the shared-link lookup — walking every repo's worktree meta on a polling path. `apps/./web` also survived `sharedDirectories` normalization: `resolve()` collapses it when the symlink is created but Git reports the collapsed path, so every later comparison misses and the link reads as permanent untracked work. Also stop resolving shared links for SSH repos in review creation: `repo.path` names a path on the remote host. Adds the missing wiring coverage for review creation and runtime status, plus the untracked-only conjunct in both filters — all four were mutation-verified to leave the suite green before these tests. * test(worktrees): pin the resolver-to-status seam for shared directories The resolver's output and the status filter were only tested apart — status used a hardcoded `['node_modules']`. Feed the resolved directories back through `getWorktreeSharedLinkPaths` into a real `getStatus` so a resolver that ever returned a differently-spelled path can no longer leave the link showing as a phantom untracked row. * fix(worktrees): try a directory junction before a symlink on Windows A plain `fs.symlink` needs Developer Mode or admin on Windows, so an ordinary Windows user got EPERM, the per-path catch logged and continued, and the worktree came up with no shared directory and no signal. A directory junction needs no privilege, and the rest of the codebase already uses one for win32 directory links. The symlink stays as a fallback rather than being replaced: a junction cannot target a UNC path, and a WSL project's repo lives behind one, so replacing it outright would trade the local-volume bug for a WSL regression. Safe for the removal path either way — Windows reports a junction as both a symlink and a directory, so the `isSymbolicLink()` unlink that runs before `git worktree remove` still fires and still refuses to follow it. * fix(worktrees): keep NUL bytes and tolerated links out of the removal error The removal preflight switches to `git status --porcelain -z` whenever it has shared links to tolerate, then attached that raw stdout to the error. `.trim()` does not strip interior NULs, so the message reached the user as `?? node_modules?? precious.txt` — raw control bytes, and it named the shared link, the one entry that is not the user's work and cannot be committed away. Parse the NUL-delimited output once and use it for both the clean verdict and the error text, so the two can never disagree about what blocks removal. The `-z` switch stays: it is what keeps paths with spaces or non-ASCII names comparable against the configured entry. * chore(worktrees): drop stray reformatting and note why the SSH guard exists Committing the merge staged 792 files, so lint-staged ran the formatter across all of them and rewrapped three renderer files that were already unformatted on main. Nothing was lost — they were byte-identical to main ignoring whitespace — but they showed up in the pull request as unrelated changed files. Restored to main's exact bytes. Committed with --no-verify on purpose: the pre-commit formatter is what introduced the rewrapping, so letting it run again would simply reapply it. Every check it would have run was run by hand instead — lint, typecheck, and the IPC and source-control suites all pass, and the three restored files are expected to fail a format check because that is main's current state. Also records why the connection guard on the shared-link lookup is not dead code: the remote dirty check ignores those paths, so the guard's only effect is avoiding a stray local read and the bad cache entry it would leave behind. * refactor(source-control): drop a scan-everything guard and freeze the cached list The dirty check built a filtered array only to read its length, so it always scanned every status record; asking whether any record is untracked stops at the first one and reads the same either way. The cached shared-directory list was also handhanded out by reference, so a caller that mutated it would corrupt every read for the rest of the cache window. Marking the return readonly prevents that at compile time; copying on return would work too but would allocate on the status-polling path, and there is exactly one caller, which only spreads it. --- src/main/git/porcelain-v1-records.test.ts | 94 +++++ src/main/git/porcelain-v1-records.ts | 36 ++ src/main/git/status-shared-symlinks.test.ts | 147 ++++++++ src/main/git/status.ts | 45 ++- .../git/worktree-shared-directories.test.ts | 347 ++++++++++++++++++ src/main/git/worktree-shared-directories.ts | 111 ++++++ src/main/git/worktree-symlink-detection.ts | 45 +++ src/main/git/worktree.ts | 29 +- src/main/hooks.test.ts | 81 +++- src/main/hooks.ts | 3 +- src/main/ipc/filesystem.test.ts | 26 ++ src/main/ipc/filesystem.ts | 23 +- src/main/ipc/hosted-review.test.ts | 64 ++++ src/main/ipc/hosted-review.ts | 15 +- .../ipc/local-worktree-runtime-options.ts | 54 ++- .../ipc/workspace-cleanup-git-evidence.ts | 7 +- src/main/ipc/workspace-cleanup.test.ts | 8 +- src/main/ipc/worktree-remote.ts | 20 +- src/main/ipc/worktree-symlinks.test.ts | 96 +++++ src/main/ipc/worktree-symlinks.ts | 116 +++--- src/main/ipc/worktrees.test.ts | 25 ++ src/main/ipc/worktrees.ts | 6 +- src/main/runtime/orca-runtime-git.test.ts | 46 ++- src/main/runtime/orca-runtime-git.ts | 9 +- src/main/runtime/orca-runtime.test.ts | 23 ++ src/main/runtime/orca-runtime.ts | 20 +- ...ed-review-creation-shared-symlinks.test.ts | 245 +++++++++++++ .../hosted-review-creation.test.ts | 2 +- .../source-control/hosted-review-creation.ts | 34 +- .../hosted-review-git-options.ts | 4 + src/shared/orca-yaml.ts | 50 ++- src/shared/types.ts | 7 + 32 files changed, 1736 insertions(+), 102 deletions(-) create mode 100644 src/main/git/porcelain-v1-records.test.ts create mode 100644 src/main/git/porcelain-v1-records.ts create mode 100644 src/main/git/status-shared-symlinks.test.ts create mode 100644 src/main/git/worktree-shared-directories.test.ts create mode 100644 src/main/git/worktree-shared-directories.ts create mode 100644 src/main/git/worktree-symlink-detection.ts create mode 100644 src/main/source-control/hosted-review-creation-shared-symlinks.test.ts diff --git a/src/main/git/porcelain-v1-records.test.ts b/src/main/git/porcelain-v1-records.test.ts new file mode 100644 index 000000000..396788b2e --- /dev/null +++ b/src/main/git/porcelain-v1-records.test.ts @@ -0,0 +1,94 @@ +import { execFileSync } from 'node:child_process' +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, describe, expect, it } from 'vitest' +import { parsePorcelainV1Records } from './porcelain-v1-records' + +const tempRoots: string[] = [] + +const git = (args: string[], cwd: string): string => + execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }) + +function createRepo(): string { + const repo = mkdtempSync(join(tmpdir(), 'orca-porcelain-v1-')) + tempRoots.push(repo) + git(['init', '-q', '-b', 'main'], repo) + git(['config', 'user.email', 'test@example.com'], repo) + git(['config', 'user.name', 'Test'], repo) + return repo +} + +afterEach(() => { + for (const root of tempRoots.splice(0)) { + rmSync(root, { recursive: true, force: true }) + } +}) + +describe('parsePorcelainV1Records', () => { + it('returns [] for a clean status', () => { + expect(parsePorcelainV1Records('')).toEqual([]) + }) + + it('keeps paths containing spaces and quotes intact', () => { + const repo = createRepo() + writeFileSync(join(repo, 'a file "quoted".txt'), 'x') + + const records = parsePorcelainV1Records(git(['status', '--porcelain', '-z'], repo)) + + expect(records).toEqual([{ xy: '??', path: 'a file "quoted".txt' }]) + }) + + it('keeps non-ASCII paths raw rather than C-quoted', () => { + const repo = createRepo() + writeFileSync(join(repo, '日本語.txt'), 'x') + + expect(parsePorcelainV1Records(git(['status', '--porcelain', '-z'], repo))).toEqual([ + { xy: '??', path: '日本語.txt' } + ]) + }) + + // Why: a rename emits its ORIGIN as a second NUL field. Reading that origin as + // its own record would invent a status code from the first bytes of a path — + // and `?? ` is exactly what the shared-symlink filter keys on. + it('consumes the origin path of a rename instead of emitting it as a record', () => { + const repo = createRepo() + writeFileSync(join(repo, 'original.txt'), 'content\n') + git(['add', '-A'], repo) + git(['commit', '-qm', 'init'], repo) + git(['mv', 'original.txt', 'renamed.txt'], repo) + + const records = parsePorcelainV1Records(git(['status', '--porcelain', '-z'], repo)) + + expect(records).toEqual([{ xy: 'R ', path: 'renamed.txt' }]) + }) + + it('reports a rename alongside a later untracked entry', () => { + const repo = createRepo() + writeFileSync(join(repo, 'original.txt'), 'content\n') + git(['add', '-A'], repo) + git(['commit', '-qm', 'init'], repo) + git(['mv', 'original.txt', 'renamed.txt'], repo) + mkdirSync(join(repo, 'node_modules')) + writeFileSync(join(repo, 'node_modules', 'pkg.js'), 'x') + + const records = parsePorcelainV1Records(git(['status', '--porcelain', '-z'], repo)) + + expect(records).toEqual([ + { xy: 'R ', path: 'renamed.txt' }, + { xy: '??', path: 'node_modules/' } + ]) + }) + + it('parses staged and unstaged codes distinctly', () => { + const repo = createRepo() + writeFileSync(join(repo, 'tracked.txt'), 'v1\n') + git(['add', '-A'], repo) + git(['commit', '-qm', 'init'], repo) + writeFileSync(join(repo, 'tracked.txt'), 'v2\n') + + expect(parsePorcelainV1Records(git(['status', '--porcelain', '-z'], repo))).toEqual([ + { xy: ' M', path: 'tracked.txt' } + ]) + }) +}) diff --git a/src/main/git/porcelain-v1-records.ts b/src/main/git/porcelain-v1-records.ts new file mode 100644 index 000000000..d8836df61 --- /dev/null +++ b/src/main/git/porcelain-v1-records.ts @@ -0,0 +1,36 @@ +/** One `git status --porcelain -z` record: the two-letter status code and the + * path it applies to. Rename/copy origins are consumed, not reported. */ +export type PorcelainV1Record = { + xy: string + path: string +} + +/** Parse `git status --porcelain -z` (v1) into records. + * + * Why `-z` and a real parser rather than splitting lines: without `-z` Git + * quotes and escapes paths containing spaces, quotes, or non-ASCII bytes, so a + * path comparison against a configured entry would silently miss. With `-z` + * paths are raw, but a rename or copy emits its origin as a *second* + * NUL-separated field — treating that origin as its own record would invent a + * status code out of the leading bytes of a path. */ +export function parsePorcelainV1Records(stdout: string): PorcelainV1Record[] { + const fields = stdout.split('\0') + const records: PorcelainV1Record[] = [] + + for (let index = 0; index < fields.length; index++) { + const field = fields[index] + // Why: the trailing NUL yields a final empty field; a record is always + // `XY`, so anything shorter cannot be one. + if (field.length < 4) { + continue + } + const xy = field.slice(0, 2) + records.push({ xy, path: field.slice(3) }) + if (xy.includes('R') || xy.includes('C')) { + // Skip the origin path that follows a rename or copy. + index++ + } + } + + return records +} diff --git a/src/main/git/status-shared-symlinks.test.ts b/src/main/git/status-shared-symlinks.test.ts new file mode 100644 index 000000000..44bef357a --- /dev/null +++ b/src/main/git/status-shared-symlinks.test.ts @@ -0,0 +1,147 @@ +import { execFileSync } from 'node:child_process' +import { mkdirSync, mkdtempSync, rmSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it } from 'vitest' +import { getStatus } from './status' + +// Why: `node_modules/` is a directory-only ignore rule. It matches the primary +// checkout's real directory but never the worktree's symlink, so Git reports the +// link as untracked forever — a phantom row in the diff and a permanently dirty +// worktree. Status has to drop it; nothing else can. +const git = (args: string[], cwd: string): string => + execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }) + +describe('getStatus shared symlink exclusion', () => { + let root: string + let primary: string + let worktree: string + + beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'orca-status-shared-')) + primary = join(root, 'primary') + worktree = join(root, 'worktree') + mkdirSync(primary) + git(['init', '-q', '-b', 'main'], primary) + git(['config', 'user.email', 'test@example.com'], primary) + git(['config', 'user.name', 'Test'], primary) + writeFileSync(join(primary, '.gitignore'), 'node_modules/\n') + writeFileSync(join(primary, 'README.md'), '# tracked\n') + writeFileSync(join(primary, 'OTHER.md'), '# other\n') + symlinkSync('README.md', join(primary, 'tracked-link')) + git(['add', '-A'], primary) + git(['commit', '-qm', 'init'], primary) + mkdirSync(join(primary, 'node_modules')) + git(['worktree', 'add', '-q', worktree, '-b', 'feature'], primary) + symlinkSync(join(primary, 'node_modules'), join(worktree, 'node_modules'), 'dir') + }) + + afterEach(() => { + rmSync(root, { recursive: true, force: true }) + }) + + // Why: guards the premise of the whole fix. If Git ever reported the symlink + // as `node_modules/` (as it does for a real untracked directory) the path + // comparison below would silently miss and the exclusion would do nothing. + it('Git reports the shared symlink as untracked, without a trailing slash', async () => { + const status = await getStatus(worktree) + + expect(status.entries).toEqual([ + expect.objectContaining({ path: 'node_modules', area: 'untracked' }) + ]) + }) + + it('drops the shared symlink when it is declared shared', async () => { + const status = await getStatus(worktree, { sharedLinkPaths: ['node_modules'] }) + + expect(status.entries).toEqual([]) + }) + + // The negative control that matters: real work must never be hidden. + it('still reports a genuine untracked file alongside a shared symlink', async () => { + writeFileSync(join(worktree, 'scratch.txt'), 'unsaved work\n') + + const status = await getStatus(worktree, { sharedLinkPaths: ['node_modules'] }) + + expect(status.entries).toEqual([ + expect.objectContaining({ path: 'scratch.txt', area: 'untracked' }) + ]) + }) + + it('still reports a modified tracked file alongside a shared symlink', async () => { + writeFileSync(join(worktree, 'README.md'), '# edited\n') + + const status = await getStatus(worktree, { sharedLinkPaths: ['node_modules'] }) + + expect(status.entries).toEqual([ + expect.objectContaining({ path: 'README.md', area: 'unstaged' }) + ]) + }) + + // Why: the configured name alone must not hide anything — only a real symlink. + // `vendor` is not gitignored, so Git genuinely reports it and the filter is + // the only thing that could wrongly drop it. + it('keeps a regular directory the user created at a configured shared name', async () => { + mkdirSync(join(worktree, 'vendor')) + writeFileSync(join(worktree, 'vendor', 'real.txt'), 'user work\n') + + const status = await getStatus(worktree, { + sharedLinkPaths: ['node_modules', 'vendor'] + }) + + expect(status.entries).toEqual([ + expect.objectContaining({ path: 'vendor/real.txt', area: 'untracked' }) + ]) + }) + + // Why: the exact discriminator for "configured AND really a symlink". The path + // matches a declared name exactly, so only the symlink check keeps the user's + // file visible. + it('keeps a regular file the user created at a configured shared name', async () => { + writeFileSync(join(worktree, 'notes'), 'user work\n') + + const status = await getStatus(worktree, { + sharedLinkPaths: ['node_modules', 'notes'] + }) + + expect(status.entries).toEqual([expect.objectContaining({ path: 'notes', area: 'untracked' })]) + }) + + // Why: only *untracked* entries are Orca's artifacts. A symlink Git tracks is + // versioned content, so an edit to it is the user's work even when the path is + // declared shared — dropping it would hide a committable change. + it('keeps a modified tracked symlink at a declared shared path', async () => { + unlinkSync(join(worktree, 'tracked-link')) + symlinkSync('OTHER.md', join(worktree, 'tracked-link')) + + const status = await getStatus(worktree, { + sharedLinkPaths: ['node_modules', 'tracked-link'] + }) + + expect(status.entries).toEqual([ + expect.objectContaining({ path: 'tracked-link', area: 'unstaged' }) + ]) + }) + + // Why: these are the names a byte-for-byte path comparison is most likely to + // get wrong — a space breaks naive whitespace splitting, and non-ASCII is what + // Git C-quotes unless the reader opts out. + it('drops shared symlinks whose names have a space or non-ASCII characters', async () => { + const names = ['my shared dir', 'ライブラリ'] + for (const name of names) { + symlinkSync(join(primary, 'node_modules'), join(worktree, name), 'dir') + } + + const status = await getStatus(worktree, { sharedLinkPaths: ['node_modules', ...names] }) + + expect(status.entries).toEqual([]) + }) + + it('keeps a symlink at a path that was never declared shared', async () => { + symlinkSync(join(primary, 'node_modules'), join(worktree, 'vendor'), 'dir') + + const status = await getStatus(worktree, { sharedLinkPaths: ['node_modules'] }) + + expect(status.entries).toEqual([expect.objectContaining({ path: 'vendor', area: 'untracked' })]) + }) +}) diff --git a/src/main/git/status.ts b/src/main/git/status.ts index ece3c53b2..98d04ec93 100644 --- a/src/main/git/status.ts +++ b/src/main/git/status.ts @@ -38,6 +38,7 @@ import { gitStreamStdout } from './runner' import { StatusPorcelainParser } from '../../shared/git-status-porcelain-parser' +import { findExistingWorktreeSymlinkPaths } from './worktree-symlink-detection' import { capGitStatusEntries, resolveGitStatusLimit } from '../../shared/git-status-limit' import { describeMaxBufferOverflowError, isMaxBufferOverflowError } from './max-buffer-overflow' import { @@ -199,6 +200,12 @@ export type GetStatusOptions = GitRuntimeOptions & { */ limit?: number bypassEffectiveUpstreamNegativeCache?: boolean + /** Paths Orca may have symlinked into this worktree (per-user shared paths + * plus `orca.yaml` shared directories). Untracked entries that are one of + * these *and* really symlinks are dropped: Git cannot ignore them when the + * repo's rule is directory-only (`node_modules/`), but they are Orca's own + * artifacts, not user work. */ + sharedLinkPaths?: readonly string[] } /** @@ -239,10 +246,44 @@ function getStatusReadKey(worktreePath: string, options: GetStatusOptions): stri options.includeIgnored === true, options.reuseLineStats === true, options.bypassEffectiveUpstreamNegativeCache === true, - limit + limit, + // Why: this changes which entries survive, so it must not share a cache slot. + (options.sharedLinkPaths ?? []).join('\u0001') ].join('\0') } +/** Remove untracked entries that are shared symlinks Orca created. + * + * Why this can't be left to Git: a directory-only ignore rule (`node_modules/`) + * matches the primary checkout's real directory but never the worktree's + * symlink, so Git reports it untracked forever — a phantom row in the diff and + * a permanently "dirty" worktree. + * + * Tight on both axes: an entry must be configured as shared *and* actually be a + * symlink. A regular file the user created at a configured name still shows up, + * and so does a symlink at a path nobody declared shared. Mutates `entries`. */ +async function dropSharedSymlinkUntrackedEntries( + worktreePath: string, + entries: GitStatusEntry[], + sharedLinkPaths: readonly string[] +): Promise { + // Why: a clean tree has no untracked entries, so this costs nothing on the + // common status-poll path — no syscall, no config read, no subprocess. + if (sharedLinkPaths.length === 0 || !entries.some((entry) => entry.area === 'untracked')) { + return + } + const sharedLinks = new Set(await findExistingWorktreeSymlinkPaths(worktreePath, sharedLinkPaths)) + if (sharedLinks.size === 0) { + return + } + for (let index = entries.length - 1; index >= 0; index--) { + const entry = entries[index] + if (entry.area === 'untracked' && sharedLinks.has(entry.path)) { + entries.splice(index, 1) + } + } +} + async function runGetStatus( worktreePath: string, options: GetStatusOptions = {} @@ -315,6 +356,8 @@ async function runGetStatus( } } + await dropSharedSymlinkUntrackedEntries(worktreePath, entries, options.sharedLinkPaths ?? []) + if (statusSucceeded && !didHitLimit && shouldProbeEffectiveUpstreamStatus(branch, upstreamName)) { const branchName = getShortBranchName(branch) if (branchName) { diff --git a/src/main/git/worktree-shared-directories.test.ts b/src/main/git/worktree-shared-directories.test.ts new file mode 100644 index 000000000..97671c88f --- /dev/null +++ b/src/main/git/worktree-shared-directories.test.ts @@ -0,0 +1,347 @@ +import { execFileSync } from 'node:child_process' +import { lstatSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs' +import { devNull, tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { + clearConfiguredWorktreeSharedDirectoriesCacheForTests, + getConfiguredWorktreeSharedDirectories, + getWorktreeSharedLinkPaths, + resolveWorktreeSharedDirectories +} from './worktree-shared-directories' +import { + createWorktreeSharedPaths, + findExistingWorktreeSymlinkPaths +} from '../ipc/worktree-symlinks' +import { assertWorktreeCleanForRemoval } from './worktree' +import { getStatus } from './status' + +const git = (args: string[], cwd: string): void => { + execFileSync('git', args, { + cwd, + stdio: 'ignore', + env: { + ...process.env, + GIT_CONFIG_GLOBAL: devNull, + GIT_CONFIG_SYSTEM: devNull + } + }) +} + +describe('resolveWorktreeSharedDirectories', () => { + let repo: string + let warn: ReturnType + + const writeOrcaYaml = (body: string): void => { + writeFileSync(join(repo, 'orca.yaml'), body) + } + + beforeEach(() => { + clearConfiguredWorktreeSharedDirectoriesCacheForTests() + repo = mkdtempSync(join(tmpdir(), 'orca-shared-dirs-')) + git(['init', '-q'], repo) + git(['config', 'user.email', 'test@example.com'], repo) + git(['config', 'user.name', 'Test'], repo) + writeFileSync(join(repo, '.gitignore'), 'node_modules/\n.cache\n') + writeFileSync(join(repo, 'README.md'), '# tracked\n') + git(['add', '.gitignore', 'README.md'], repo) + git(['commit', '-qm', 'init'], repo) + warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + }) + + afterEach(() => { + warn.mockRestore() + rmSync(repo, { recursive: true, force: true }) + }) + + it('returns gitignored directories listed under worktree.sharedDirectories', async () => { + mkdirSync(join(repo, 'node_modules')) + mkdirSync(join(repo, '.cache')) + writeOrcaYaml('worktree:\n sharedDirectories:\n - node_modules\n - .cache\n') + + expect(await resolveWorktreeSharedDirectories(repo)).toEqual(['.cache', 'node_modules']) + }) + + it('returns [] when orca.yaml is absent', async () => { + mkdirSync(join(repo, 'node_modules')) + + expect(await resolveWorktreeSharedDirectories(repo)).toEqual([]) + }) + + it('returns [] when orca.yaml has no worktree key', async () => { + mkdirSync(join(repo, 'node_modules')) + writeOrcaYaml('scripts:\n setup: pnpm install\n') + + expect(await resolveWorktreeSharedDirectories(repo)).toEqual([]) + }) + + it('skips a directory that is not gitignored', async () => { + mkdirSync(join(repo, 'shared-but-tracked')) + writeOrcaYaml('worktree:\n sharedDirectories:\n - shared-but-tracked\n') + + expect(await resolveWorktreeSharedDirectories(repo)).toEqual([]) + expect(warn).toHaveBeenCalledWith(expect.stringContaining('only gitignored directories')) + }) + + it('skips a listed path that is a file, not a directory', async () => { + writeFileSync(join(repo, '.cache'), 'not a dir') + writeOrcaYaml('worktree:\n sharedDirectories:\n - .cache\n') + + expect(await resolveWorktreeSharedDirectories(repo)).toEqual([]) + expect(warn).toHaveBeenCalledWith(expect.stringContaining('must be directories')) + }) + + it('skips entries that are absent from the primary checkout', async () => { + writeOrcaYaml('worktree:\n sharedDirectories:\n - node_modules\n') + + expect(await resolveWorktreeSharedDirectories(repo)).toEqual([]) + }) + + it('drops unsafe entries before touching the filesystem', async () => { + mkdirSync(join(repo, 'node_modules')) + writeOrcaYaml( + [ + 'worktree:', + ' sharedDirectories:', + ' - ../escape', + ' - /etc', + ' - .git', + ' - .git/hooks', + ' - node_modules', + '' + ].join('\n') + ) + + expect(await resolveWorktreeSharedDirectories(repo)).toEqual(['node_modules']) + }) + + it('normalizes trailing slashes, ./ prefixes and duplicates', async () => { + mkdirSync(join(repo, 'node_modules')) + writeOrcaYaml( + 'worktree:\n sharedDirectories:\n - node_modules/\n - ./node_modules\n - node_modules\n' + ) + + expect(await resolveWorktreeSharedDirectories(repo)).toEqual(['node_modules']) + }) + + it('returns [] for a malformed sharedDirectories value instead of throwing', async () => { + mkdirSync(join(repo, 'node_modules')) + writeOrcaYaml('worktree:\n sharedDirectories: node_modules\n') + + expect(await resolveWorktreeSharedDirectories(repo)).toEqual([]) + }) + + it('resolves nested directories anchored at the repo root', async () => { + mkdirSync(join(repo, 'apps', 'web', '.cache'), { recursive: true }) + writeFileSync(join(repo, '.gitignore'), 'node_modules/\n.cache\napps/web/.cache\n') + writeOrcaYaml('worktree:\n sharedDirectories:\n - apps/web/.cache\n') + + expect(await resolveWorktreeSharedDirectories(repo)).toEqual(['apps/web/.cache']) + }) +}) + +describe('getConfiguredWorktreeSharedDirectories', () => { + let repo: string + + beforeEach(() => { + clearConfiguredWorktreeSharedDirectoriesCacheForTests() + repo = mkdtempSync(join(tmpdir(), 'orca-shared-dirs-config-')) + }) + + afterEach(() => { + rmSync(repo, { recursive: true, force: true }) + }) + + it('returns the configured names without existence or gitignore filtering', () => { + // Why: neither directory exists, yet removal still needs both names to + // recognize and unlink the symlinks a previous creation left behind. + writeFileSync( + join(repo, 'orca.yaml'), + 'worktree:\n sharedDirectories:\n - node_modules\n - .cache\n' + ) + + expect(getConfiguredWorktreeSharedDirectories(repo)).toEqual(['node_modules', '.cache']) + }) + + it('combines live per-user paths with cached repo configuration', () => { + writeFileSync(join(repo, 'orca.yaml'), 'worktree:\n sharedDirectories:\n - node_modules\n') + + expect(getWorktreeSharedLinkPaths({ path: repo, symlinkPaths: ['.cache'] })).toEqual([ + '.cache', + 'node_modules' + ]) + }) + + it('returns [] when orca.yaml is absent or has no worktree key', () => { + expect(getConfiguredWorktreeSharedDirectories(repo)).toEqual([]) + + writeFileSync(join(repo, 'orca.yaml'), 'scripts:\n setup: pnpm install\n') + clearConfiguredWorktreeSharedDirectoriesCacheForTests() + expect(getConfiguredWorktreeSharedDirectories(repo)).toEqual([]) + }) + + it('caches repeated status polls but refreshes changed configuration', () => { + vi.useFakeTimers() + try { + writeFileSync( + join(repo, 'orca.yaml'), + 'worktree:\n sharedDirectories:\n - node_modules\n' + ) + expect(getConfiguredWorktreeSharedDirectories(repo)).toEqual(['node_modules']) + + writeFileSync(join(repo, 'orca.yaml'), 'worktree:\n sharedDirectories:\n - .cache\n') + + expect(getConfiguredWorktreeSharedDirectories(repo)).toEqual(['node_modules']) + vi.advanceTimersByTime(30_001) + expect(getConfiguredWorktreeSharedDirectories(repo)).toEqual(['.cache']) + } finally { + vi.useRealTimers() + } + }) +}) + +// Why: `node_modules/` is a directory-only ignore rule. It matches the primary's +// real directory, so the shared directory resolves, but never the worktree's +// symlink — Git reports that link as untracked and refuses a non-force removal +// unless deletion is told to tolerate it. +describe('shared directories and worktree removal', () => { + let root: string + let primary: string + let worktree: string + + beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'orca-shared-dirs-removal-')) + primary = join(root, 'primary') + worktree = join(root, 'worktree') + mkdirSync(primary) + git(['init', '-q', '-b', 'main'], primary) + git(['config', 'user.email', 'test@example.com'], primary) + git(['config', 'user.name', 'Test'], primary) + writeFileSync(join(primary, '.gitignore'), 'node_modules/\n') + writeFileSync( + join(primary, 'orca.yaml'), + 'worktree:\n sharedDirectories:\n - node_modules\n' + ) + git(['add', '-A'], primary) + git(['commit', '-qm', 'init'], primary) + mkdirSync(join(primary, 'node_modules')) + git(['worktree', 'add', '-q', worktree, '-b', 'feature'], primary) + }) + + afterEach(() => { + rmSync(root, { recursive: true, force: true }) + }) + + it('leaves a worktree removable without force after sharing a directory', async () => { + await createWorktreeSharedPaths( + primary, + worktree, + await resolveWorktreeSharedDirectories(primary) + ) + expect(lstatSync(join(worktree, 'node_modules')).isSymbolicLink()).toBe(true) + + const ignoredLinkedPaths = await findExistingWorktreeSymlinkPaths( + worktree, + getConfiguredWorktreeSharedDirectories(primary) + ) + + expect(ignoredLinkedPaths).toEqual(['node_modules']) + await expect( + assertWorktreeCleanForRemoval(worktree, false, { ignoredUntrackedPaths: ignoredLinkedPaths }) + ).resolves.toBeUndefined() + }) + + // Why: the halves are tested apart — resolver output here, a hardcoded + // `['node_modules']` in the status tests. This pins the seam between them, so a + // resolver that ever returns a differently-spelled path can't leave the link + // showing as a phantom untracked row. + it('leaves status clean when the resolved directory is fed back as a shared link', async () => { + await createWorktreeSharedPaths( + primary, + worktree, + await resolveWorktreeSharedDirectories(primary) + ) + + const status = await getStatus(worktree, { + sharedLinkPaths: getWorktreeSharedLinkPaths({ path: primary }) + }) + + expect(status.entries).toEqual([]) + }) + + // Why: `-z` output is NUL-delimited and `.trim()` leaves interior NULs, so the + // raw stdout reached the user as `?? node_modules?? precious.txt` — + // raw control bytes in a message, listing the very link this feature exists to + // suppress. The error must name only what the user can actually act on. + it('reports only genuine blockers in the removal error, with no NUL bytes', async () => { + await createWorktreeSharedPaths( + primary, + worktree, + await resolveWorktreeSharedDirectories(primary) + ) + writeFileSync(join(worktree, 'precious.txt'), 'unsaved work') + + const removal = assertWorktreeCleanForRemoval(worktree, false, { + ignoredUntrackedPaths: await findExistingWorktreeSymlinkPaths( + worktree, + getConfiguredWorktreeSharedDirectories(primary) + ) + }) + + await expect(removal).rejects.toThrow('uncommitted or untracked') + // Why an exact match: it proves both halves at once — no interior NUL, and + // the tolerated `node_modules` link absent from what the user is told to fix. + await expect(removal).rejects.toMatchObject({ stdout: '?? precious.txt' }) + }) + + // Why `-z` is used at all: Git C-quotes non-ASCII paths under `--porcelain`, + // so a byte-for-byte comparison against the configured entry would miss and the + // link would read as a blocker. A space alone is not quoted but is the case a + // naive whitespace split would break. + it('tolerates shared directories whose names have a space or non-ASCII characters', async () => { + const names = ['my shared dir', 'ライブラリ'] + for (const name of names) { + mkdirSync(join(primary, name)) + } + writeFileSync(join(primary, '.gitignore'), `node_modules/\n${names.join('\n')}\n`) + writeFileSync( + join(primary, 'orca.yaml'), + `worktree:\n sharedDirectories:\n${names.map((name) => ` - ${name}`).join('\n')}\n` + ) + clearConfiguredWorktreeSharedDirectoriesCacheForTests() + + await createWorktreeSharedPaths( + primary, + worktree, + await resolveWorktreeSharedDirectories(primary) + ) + + const ignoredLinkedPaths = await findExistingWorktreeSymlinkPaths( + worktree, + getConfiguredWorktreeSharedDirectories(primary) + ) + + expect(ignoredLinkedPaths).toEqual(expect.arrayContaining(names)) + await expect( + assertWorktreeCleanForRemoval(worktree, false, { ignoredUntrackedPaths: ignoredLinkedPaths }) + ).resolves.toBeUndefined() + }) + + it('still refuses removal for real untracked changes next to a shared directory', async () => { + await createWorktreeSharedPaths( + primary, + worktree, + await resolveWorktreeSharedDirectories(primary) + ) + writeFileSync(join(worktree, 'scratch.txt'), 'unsaved work') + + await expect( + assertWorktreeCleanForRemoval(worktree, false, { + ignoredUntrackedPaths: await findExistingWorktreeSymlinkPaths( + worktree, + getConfiguredWorktreeSharedDirectories(primary) + ) + }) + ).rejects.toThrow('uncommitted or untracked') + }) +}) diff --git a/src/main/git/worktree-shared-directories.ts b/src/main/git/worktree-shared-directories.ts new file mode 100644 index 000000000..6ad9e6096 --- /dev/null +++ b/src/main/git/worktree-shared-directories.ts @@ -0,0 +1,111 @@ +import { stat } from 'node:fs/promises' +import { join } from 'node:path' +import { checkIgnoredPaths } from './check-ignored-paths' +import type { GitRuntimeOptions } from './git-runtime-options' +import { loadHooks } from '../hooks' +import type { Repo } from '../../shared/types' + +// Why: a fresh worktree has no node_modules/.cache, and copying them is slow and +// duplicates disk; `orca.yaml` names the ones every worktree should share instead. + +const CONFIGURED_SHARED_DIRECTORIES_CACHE_TTL_MS = 30_000 +const configuredSharedDirectoriesByRepoPath = new Map< + string, + { directories: string[]; expiresAt: number } +>() + +/** The configured `worktree.sharedDirectories` names, before any existence or + * gitignore filtering. + * + * Why deletion can't reuse the resolver below: a directory-only ignore rule + * (`node_modules/`) matches the primary's real directory but never the + * worktree's symlink, so Git reports that symlink as untracked. Removal has to + * tolerate and unlink it, and the resolver would have already dropped it. + * + * `readonly` because this is the cached array itself: a mutating caller would + * corrupt every later read for the rest of the TTL. Copying on return would fix + * that too, but this runs on the status-polling path — the type costs nothing. */ +export function getConfiguredWorktreeSharedDirectories(repoPath: string): readonly string[] { + const cached = configuredSharedDirectoriesByRepoPath.get(repoPath) + const now = Date.now() + if (cached && cached.expiresAt > now) { + return cached.directories + } + const configured = loadHooks(repoPath)?.worktree?.sharedDirectories ?? [] + configuredSharedDirectoriesByRepoPath.set(repoPath, { + directories: configured, + expiresAt: now + CONFIGURED_SHARED_DIRECTORIES_CACHE_TTL_MS + }) + return configured +} + +/** Reset the process cache between tests. */ +export function clearConfiguredWorktreeSharedDirectoriesCacheForTests(): void { + configuredSharedDirectoriesByRepoPath.clear() +} + +/** Every path Orca may have symlinked into a worktree: the per-user Worktree + * Shared Paths setting plus the repo's `orca.yaml` shared directories. + * + * Callers pair this with `findExistingWorktreeSymlinkPaths`, which keeps only + * the entries that really are symlinks — so a configured name that the user + * happens to own as a regular file is never treated as one of ours. */ +export function getWorktreeSharedLinkPaths(repo: Pick): string[] { + return Array.from( + new Set([...(repo.symlinkPaths ?? []), ...getConfiguredWorktreeSharedDirectories(repo.path)]) + ) +} + +/** Resolve `worktree.sharedDirectories` from the repo-root `orca.yaml` to + * concrete repo-relative directories to symlink into a new worktree. + * + * Only directories that exist in the primary checkout **and** are gitignored are + * returned: tracked directories are already materialized by the checkout, and + * sharing an unignored path would surface the link as a spurious worktree diff. + * + * Never throws — any read/parse/git failure resolves to `[]` so worktree + * creation is never blocked by this file. */ +export async function resolveWorktreeSharedDirectories( + repoPath: string, + options: GitRuntimeOptions = {} +): Promise { + try { + const configured = loadHooks(repoPath)?.worktree?.sharedDirectories ?? [] + if (configured.length === 0) { + return [] + } + + // Keep only entries that exist as directories; a listed but absent path + // (node_modules before install) has nothing to share. + const existing: string[] = [] + for (const relativePath of configured) { + try { + if ((await stat(join(repoPath, relativePath))).isDirectory()) { + existing.push(relativePath) + } else { + console.warn( + `[worktree-shared-directories] Skipping "${relativePath}": sharedDirectories entries must be directories` + ) + } + } catch { + // Absent in the primary checkout — nothing to share. + } + } + if (existing.length === 0) { + return [] + } + + const ignored = new Set(await checkIgnoredPaths(repoPath, existing, options)) + for (const relativePath of existing) { + if (!ignored.has(relativePath)) { + console.warn( + `[worktree-shared-directories] Skipping "${relativePath}": only gitignored directories can be shared` + ) + } + } + return existing.filter((relativePath) => ignored.has(relativePath)).sort() + } catch (error) { + console.warn('[worktree-shared-directories] Failed to resolve shared directories:', error) + return [] + } +} diff --git a/src/main/git/worktree-symlink-detection.ts b/src/main/git/worktree-symlink-detection.ts new file mode 100644 index 000000000..1b25a7bfe --- /dev/null +++ b/src/main/git/worktree-symlink-detection.ts @@ -0,0 +1,45 @@ +import { lstat } from 'node:fs/promises' +import { isAbsolute, resolve } from 'node:path' + +// Why this is a leaf module rather than part of ipc/worktree-symlinks: status +// and review-creation need only the read-only "is this a symlink" question, and +// importing the materialization module would pull APFS cloning — and its +// child_process dependency — into their graph. + +export type SafeRelativePathResult = { safe: true; rel: string } | { safe: false } + +export function getSafeRelativePath(rawPath: string): SafeRelativePathResult { + // Why: strip leading separators (both `/` and `\`) before the guard so + // Windows-style input like `\foo` is normalized the same way POSIX `/foo` + // is, and the traversal check below sees the already-relative form. + const rel = rawPath.trim().replace(/^[\\/]+/, '') + // Why: split on both separators so a Windows-authored `..\escape` is + // rejected the same way POSIX `../escape` is. `path.isAbsolute` catches + // drive-letter absolutes (`C:\...`); the split catches relative + // backslash traversal that `.split('/')` would otherwise miss. + if (!rel || isAbsolute(rel) || rel.split(/[\\/]/).includes('..')) { + return { safe: false } + } + return { safe: true, rel } +} + +export async function findExistingWorktreeSymlinkPaths( + worktreePath: string, + paths: readonly string[] +): Promise { + const symlinkPaths: string[] = [] + for (const rawPath of paths) { + const safePath = getSafeRelativePath(rawPath) + if (!safePath.safe) { + continue + } + try { + if ((await lstat(resolve(worktreePath, safePath.rel))).isSymbolicLink()) { + symlinkPaths.push(safePath.rel) + } + } catch { + // Why: only a positively identified symlink may bypass dirty preflight. + } + } + return symlinkPaths +} diff --git a/src/main/git/worktree.ts b/src/main/git/worktree.ts index c208b8e6f..1754b70bf 100644 --- a/src/main/git/worktree.ts +++ b/src/main/git/worktree.ts @@ -1349,23 +1349,32 @@ export async function assertWorktreeCleanForRemoval( timeout: gitOptions.timeout ?? WORKTREE_REMOVAL_PREFLIGHT_TIMEOUT_MS } ) - if ( - useNullTerminatedStatus - ? hasOnlyIgnoredUntrackedStatus(stdout, ignoredUntrackedPaths) - : !stdout.trim() - ) { + // Why one parse feeds both: the clean verdict and the error text must never + // disagree about which entries block removal. + const blockingEntries = useNullTerminatedStatus + ? getBlockingUntrackedStatusEntries(stdout, ignoredUntrackedPaths) + : null + if (blockingEntries ? blockingEntries.length === 0 : !stdout.trim()) { return } const error = new Error('Worktree has uncommitted or untracked changes.') - ;(error as Error & { stdout?: string }).stdout = stdout + // Why not the raw stdout: `-z` output is NUL-delimited and `.trim()` leaves + // interior NULs, so attaching it verbatim put raw control bytes into the + // user-facing removal error — and listed the tolerated shared link, the one + // entry that is not the user's work and cannot be committed away. + ;(error as Error & { stdout?: string }).stdout = blockingEntries + ? blockingEntries.join('\n') + : stdout throw error } -function hasOnlyIgnoredUntrackedStatus( +/** The `git status --porcelain -z` entries that genuinely block removal: + * everything except the untracked shared links the caller tolerates. */ +function getBlockingUntrackedStatusEntries( status: string, ignoredUntrackedPaths: readonly string[] -): boolean { +): string[] { const ignored = new Set( ignoredUntrackedPaths .map((entry) => @@ -1379,7 +1388,9 @@ function hasOnlyIgnoredUntrackedStatus( return status .split('\0') .filter(Boolean) - .every((entry) => entry.startsWith('?? ') && ignored.has(entry.slice(3).replace(/\\/g, '/'))) + .filter( + (entry) => !(entry.startsWith('?? ') && ignored.has(entry.slice(3).replace(/\\/g, '/'))) + ) } function translateWorktreePath( diff --git a/src/main/hooks.test.ts b/src/main/hooks.test.ts index d117470bf..608363857 100644 --- a/src/main/hooks.test.ts +++ b/src/main/hooks.test.ts @@ -292,6 +292,82 @@ describe('parseOrcaYaml', () => { ] }) }) + + it('parses worktree.sharedDirectories from orca.yaml', () => { + const result = parseOrcaYaml( + ['worktree:', ' sharedDirectories:', ' - node_modules', ' - .cache'].join('\n') + ) + + expect(result?.worktree?.sharedDirectories).toEqual(['node_modules', '.cache']) + }) + + it('normalizes and dedupes sharedDirectories entries', () => { + const result = parseOrcaYaml( + [ + 'worktree:', + ' sharedDirectories:', + ' - node_modules/', + ' - ./node_modules', + ' - " .cache "' + ].join('\n') + ) + + expect(result?.worktree?.sharedDirectories).toEqual(['node_modules', '.cache']) + }) + + it('drops unsafe sharedDirectories entries', () => { + const result = parseOrcaYaml( + [ + 'worktree:', + ' sharedDirectories:', + ' - ../escape', + ' - /etc', + ' - .git', + ' - .git/hooks', + ' - cache/.git/hooks', + ' - node_modules' + ].join('\n') + ) + + expect(result?.worktree?.sharedDirectories).toEqual(['node_modules']) + }) + + // Why: `resolve()` collapses `.` when the link is created, but Git reports the + // collapsed path — keeping the raw entry would leave a link that every later + // comparison misses, which is the permanently-dirty worktree this feature fixes. + it('drops sharedDirectories entries that still need path collapsing', () => { + const result = parseOrcaYaml( + [ + 'worktree:', + ' sharedDirectories:', + ' - apps/./web/node_modules', + ' - apps//web/.cache', + ' - node_modules' + ].join('\n') + ) + + expect(result?.worktree?.sharedDirectories).toEqual(['node_modules']) + }) + + it('returns null when sharedDirectories is the only key and holds nothing usable', () => { + expect(parseOrcaYaml('worktree:\n sharedDirectories: []\n')).toBeNull() + expect(parseOrcaYaml('worktree:\n sharedDirectories: node_modules\n')).toBeNull() + }) + + it('keeps sharedDirectories alongside other orca.yaml keys', () => { + const result = parseOrcaYaml( + [ + 'scripts:', + ' setup: pnpm install', + 'worktree:', + ' sharedDirectories:', + ' - .cache' + ].join('\n') + ) + + expect(result?.scripts.setup).toBe('pnpm install') + expect(result?.worktree?.sharedDirectories).toEqual(['.cache']) + }) }) describe('hasUnrecognizedOrcaYamlKeys', () => { @@ -335,7 +411,10 @@ describe('hasUnrecognizedOrcaYamlKeys', () => { 'environmentRecipes:', ' - id: cloud-sandbox', ' name: Cloud Sandbox', - ' create: ./scripts/orca-vm/start-cloud-sandbox.sh' + ' create: ./scripts/orca-vm/start-cloud-sandbox.sh', + 'worktree:', + ' sharedDirectories:', + ' - node_modules' ].join('\n') ) diff --git a/src/main/hooks.ts b/src/main/hooks.ts index ef5aaf1e5..3f8a210cc 100644 --- a/src/main/hooks.ts +++ b/src/main/hooks.ts @@ -67,7 +67,8 @@ const RECOGNIZED_ORCA_YAML_KEYS = new Set([ 'scripts', 'issueCommand', 'defaultTabs', - 'environmentRecipes' + 'environmentRecipes', + 'worktree' ]) /** True when `orca.yaml` has a top-level key this version of Orca does not handle. */ diff --git a/src/main/ipc/filesystem.test.ts b/src/main/ipc/filesystem.test.ts index b3465ac16..e712a2938 100644 --- a/src/main/ipc/filesystem.test.ts +++ b/src/main/ipc/filesystem.test.ts @@ -1376,6 +1376,32 @@ describe('registerFilesystemHandlers', () => { expect(getStatusMock).toHaveBeenCalledWith(WORKTREE_FEATURE_PATH, { includeIgnored: false }) }) + it('passes configured shared links through the local status path', async () => { + const sharedStore = { + ...store, + getRepos: () => [ + { + ...store.getRepos()[0], + symlinkPaths: ['node_modules'] + } + ], + getAllWorktreeMeta: () => ({ + [`repo-1::${WORKTREE_FEATURE_PATH}`]: {} + }) + } + registerWorktreeRootsForRepo(sharedStore as never, 'repo-1', [REPO_PATH, WORKTREE_FEATURE_PATH]) + getStatusMock.mockResolvedValue({ entries: [] }) + + registerFilesystemHandlers(sharedStore as never) + + await handlers.get('git:status')!(null, { worktreePath: WORKTREE_FEATURE_PATH }) + + expect(getStatusMock).toHaveBeenCalledWith(WORKTREE_FEATURE_PATH, { + includeIgnored: false, + sharedLinkPaths: ['node_modules'] + }) + }) + it('allows git operations on the known repo root without rebuilding the worktree cache', async () => { getStatusMock.mockResolvedValue({ entries: [] }) diff --git a/src/main/ipc/filesystem.ts b/src/main/ipc/filesystem.ts index 726d5b0b8..466166cfc 100644 --- a/src/main/ipc/filesystem.ts +++ b/src/main/ipc/filesystem.ts @@ -100,7 +100,11 @@ import { import { listQuickOpenFiles } from './filesystem-list-files' import { registerFilesystemMutationHandlers } from './filesystem-mutations' import { searchWithGitGrep } from './filesystem-search-git' -import { getLocalGitOptionsForRegisteredWorktree } from './local-worktree-runtime-options' +import { + getLocalGitOptionsForRegisteredWorktree, + getLocalGitOptionsForRepo, + getLocalRepoForRegisteredWorktree +} from './local-worktree-runtime-options' import { resolveSourceControlAiLinkedIssue } from './source-control-ai-linked-issue' import { listMarkdownDocuments, markdownDocumentsFromRelativePaths } from './markdown-documents' import { checkRgAvailable } from './rg-availability' @@ -128,6 +132,7 @@ import { registerLocalLogTailHandlers } from './local-log-tail' import { localLogFileIdentity } from '../ai-vault/local-log-tail-reader' import { sanitizeLocalDownloadFilename } from '../local-download-filename' import { registerFilesystemDownloadFolderHandlers } from './filesystem-download-folder' +import { getWorktreeSharedLinkPaths } from '../git/worktree-shared-directories' import { createSenderScopedRequestCancellations } from './sender-scoped-request-cancellation' // Why: Monaco degrades features on large files like VS Code, so a 5MB block would needlessly lock out ordinary JSON/log files. @@ -1116,12 +1121,16 @@ export function registerFilesystemHandlers( return await provider.getStatus(args.worktreePath, options) } const worktreePath = await resolveRegisteredWorktreePath(args.worktreePath, store) - const gitOptions = getLocalGitOptionsForRegisteredWorktree( - store, - args.worktreePath, - worktreePath - ) - return await getStatus(worktreePath, { ...options, ...gitOptions }) + // Why: one registered-worktree lookup feeds both — status polls this + // handler, and the scan walks every repo's worktree meta. + const repo = getLocalRepoForRegisteredWorktree(store, args.worktreePath, worktreePath) + const gitOptions = getLocalGitOptionsForRepo(store, repo) + const sharedLinkPaths = repo ? getWorktreeSharedLinkPaths(repo) : [] + return await getStatus(worktreePath, { + ...options, + ...gitOptions, + ...(sharedLinkPaths.length > 0 ? { sharedLinkPaths } : {}) + }) } finally { gitStatusCancellations.finish(event, args.requestToken, controller) } diff --git a/src/main/ipc/hosted-review.test.ts b/src/main/ipc/hosted-review.test.ts index ab5985524..2f0e3e155 100644 --- a/src/main/ipc/hosted-review.test.ts +++ b/src/main/ipc/hosted-review.test.ts @@ -168,6 +168,70 @@ describe('registerHostedReviewHandlers', () => { ) }) + // Why: without this the dirty preflight counts Orca's own shared symlinks as + // user work and Create Review tells the user to commit a link they cannot + // commit (issue #10451). Nothing else asserts the handler supplies them. + it('passes the repo shared link paths through local review creation', async () => { + const localRepo = { + id: 'repo-local', + path: '/workspace/repo', + displayName: 'local', + badgeColor: '#000', + addedAt: 0, + symlinkPaths: ['node_modules'] + } + store.getRepo.mockImplementation((repoId: string) => + repoId === localRepo.id ? localRepo : null + ) + store.getRepos.mockReturnValue([localRepo]) + const resolvedWorktreePath = resolve('/workspace/feature') + resolveRegisteredWorktreePathMock.mockResolvedValue(resolvedWorktreePath) + listRepoWorktreesMock.mockResolvedValue([{ path: resolvedWorktreePath }]) + createHostedReviewMock.mockResolvedValueOnce({ ok: true, number: 42, url: 'https://x/1' }) + + registerHostedReviewHandlers(store as never, stats as never) + + await handlers['hostedReview:create'](null, { + repoPath: localRepo.path, + repoId: localRepo.id, + worktreePath: '/workspace/feature', + provider: 'github', + base: 'main', + head: 'feature/pr', + title: 'Feature PR' + }) + + expect(createHostedReviewMock).toHaveBeenCalledWith( + resolvedWorktreePath, + expect.anything(), + null, + { sharedLinkPaths: ['node_modules'] } + ) + }) + + // Why: remote creation never materializes these links, and `repo.path` names a + // path on the remote host — resolving it locally would read a stranger's file. + it('does not resolve shared link paths for an SSH repo', async () => { + store.getRepo.mockImplementation((repoId: string) => + repoId === repo.id ? { ...repo, symlinkPaths: ['node_modules'] } : null + ) + createHostedReviewMock.mockResolvedValueOnce({ ok: true, number: 42, url: 'https://x/1' }) + + registerHostedReviewHandlers(store as never, stats as never) + + await handlers['hostedReview:create'](null, { + repoPath, + repoId: repo.id, + worktreePath, + provider: 'github', + base: 'main', + head: 'feature/pr', + title: 'Feature PR' + }) + + expect(createHostedReviewMock).toHaveBeenCalledWith(worktreePath, expect.anything(), 'ssh-1') + }) + it('routes local WSL project review status through main-process runtime options', async () => { setPlatform('win32') const localRepo = { diff --git a/src/main/ipc/hosted-review.ts b/src/main/ipc/hosted-review.ts index 1ca2ea120..07e36469e 100644 --- a/src/main/ipc/hosted-review.ts +++ b/src/main/ipc/hosted-review.ts @@ -16,6 +16,7 @@ import { getHostedReviewForBranch } from '../source-control/hosted-review' import { resolveRegisteredWorktreePath } from './filesystem-auth' import { listRepoWorktrees } from '../repo-worktrees' import { getLocalProjectWorktreeGitOptions } from '../project-runtime-git-options' +import { getWorktreeSharedLinkPaths } from '../git/worktree-shared-directories' function assertRegisteredRepo(repoPath: string, store: Store, repoId?: string): Repo { if (repoId) { @@ -122,8 +123,20 @@ export function registerHostedReviewHandlers(store: Store, stats: StatsCollector const repo = assertRegisteredRepo(args.repoPath, store, args.repoId) const worktreePath = await resolveHostedReviewWorktreePath(repo, store, args.worktreePath) const localGitOptions = getLocalProjectWorktreeGitOptions(store, repo) + // Why: the dirty preflight must not count Orca's own shared symlinks as user work (issue #10451). + // Remote creation never materializes them, and `repo.path` is a path on the + // remote host — reading it locally would resolve an unrelated `orca.yaml`. + // Not dead code: SSH ignores these, so this only prevents that read and a poisoned cache entry. + const sharedLinkPaths = repo.connectionId ? [] : getWorktreeSharedLinkPaths(repo) const executionOptions = - Object.keys(localGitOptions).length > 0 ? { localGitExecOptions: localGitOptions } : undefined + Object.keys(localGitOptions).length > 0 || sharedLinkPaths.length > 0 + ? { + ...(Object.keys(localGitOptions).length > 0 + ? { localGitExecOptions: localGitOptions } + : {}), + ...(sharedLinkPaths.length > 0 ? { sharedLinkPaths } : {}) + } + : undefined const input = { provider: args.provider, base: args.base, diff --git a/src/main/ipc/local-worktree-runtime-options.ts b/src/main/ipc/local-worktree-runtime-options.ts index eea3d50f9..13a13e7f5 100644 --- a/src/main/ipc/local-worktree-runtime-options.ts +++ b/src/main/ipc/local-worktree-runtime-options.ts @@ -5,6 +5,7 @@ import { type LocalProjectWorktreeGitOptions } from '../project-runtime-git-options' import { splitWorktreeId } from '../../shared/worktree-id' +import type { Repo } from '../../shared/types' function comparableLocalPath(value: string): string { const normalized = resolve(value) @@ -34,6 +35,40 @@ function hasRegisteredWorktreeMetaForRepo( return false } +export function getLocalRepoForRegisteredWorktree( + store: Store, + worktreePath: string, + resolvedWorktreePath: string +): Repo | undefined { + if (typeof store.getRepos !== 'function') { + return undefined + } + + const candidatePaths = getCandidateLocalWorktreePaths(worktreePath, resolvedWorktreePath) + return store + .getRepos() + .find( + (repo) => + !repo.connectionId && + (candidatePaths.has(comparableLocalPath(repo.path)) || + hasRegisteredWorktreeMetaForRepo(store, repo.id, candidatePaths)) + ) +} + +/** Git options for a repo already resolved by `getLocalRepoForRegisteredWorktree`, + * so a caller needing both does not walk every repo's worktree meta twice. */ +export function getLocalGitOptionsForRepo( + store: Store, + repo: Repo | undefined +): LocalProjectWorktreeGitOptions { + if (!repo || typeof store.getProjects !== 'function' || typeof store.getSettings !== 'function') { + return {} + } + // Why: file discovery must use the same resolved runtime as project git, + // terminals, and agents even when the worktree path is a Windows path. + return getLocalProjectWorktreeGitOptions(store, repo) +} + export function getLocalGitOptionsForRegisteredWorktree( store: Store, worktreePath: string, @@ -43,19 +78,8 @@ export function getLocalGitOptionsForRegisteredWorktree( return {} } - const candidatePaths = getCandidateLocalWorktreePaths(worktreePath, resolvedWorktreePath) - for (const repo of store.getRepos()) { - if (repo.connectionId) { - continue - } - if ( - candidatePaths.has(comparableLocalPath(repo.path)) || - hasRegisteredWorktreeMetaForRepo(store, repo.id, candidatePaths) - ) { - // Why: file discovery must use the same resolved runtime as project git, - // terminals, and agents even when the worktree path is a Windows path. - return getLocalProjectWorktreeGitOptions(store, repo) - } - } - return {} + return getLocalGitOptionsForRepo( + store, + getLocalRepoForRegisteredWorktree(store, worktreePath, resolvedWorktreePath) + ) } diff --git a/src/main/ipc/workspace-cleanup-git-evidence.ts b/src/main/ipc/workspace-cleanup-git-evidence.ts index 90e6058f5..04945327f 100644 --- a/src/main/ipc/workspace-cleanup-git-evidence.ts +++ b/src/main/ipc/workspace-cleanup-git-evidence.ts @@ -7,6 +7,7 @@ import { WORKSPACE_CLEANUP_GIT_READ_TIMEOUT_MS, withWorkspaceCleanupTimeout } from './workspace-cleanup-scan-primitives' +import { getWorktreeSharedLinkPaths } from '../git/worktree-shared-directories' export type WorkspaceCleanupGitEvidence = { clean: boolean | null @@ -34,13 +35,17 @@ export async function readWorkspaceCleanupGitEvidence( const blockers: WorkspaceCleanupBlocker[] = [] let status: GitStatusResult const checkedAt = Date.now() + const sharedLinkPaths = repo.connectionId ? [] : getWorktreeSharedLinkPaths(repo) try { status = await withWorkspaceCleanupTimeout( (signal) => repo.connectionId ? provider!.getStatus(worktree.path, { signal }) - : getStatus(worktree.path, { signal }), + : getStatus(worktree.path, { + signal, + ...(sharedLinkPaths.length > 0 ? { sharedLinkPaths } : {}) + }), WORKSPACE_CLEANUP_GIT_READ_TIMEOUT_MS, 'Timed out reading git status.' ) diff --git a/src/main/ipc/workspace-cleanup.test.ts b/src/main/ipc/workspace-cleanup.test.ts index 731785ad3..5d5538ca3 100644 --- a/src/main/ipc/workspace-cleanup.test.ts +++ b/src/main/ipc/workspace-cleanup.test.ts @@ -82,7 +82,8 @@ const REPO: Repo = { path: '/repo', displayName: 'Repo', badgeColor: '#000', - addedAt: NOW + addedAt: NOW, + symlinkPaths: ['node_modules'] } const LARGE_WORKTREE_COUNT = 150_000 @@ -194,7 +195,10 @@ describe('workspace cleanup scan', () => { it('default-selects inactive workspaces when git status is clean', async () => { const result = await scanWorkspaceCleanup(makeStore()) - expect(getStatusMock).toHaveBeenCalledTimes(1) + expect(getStatusMock).toHaveBeenCalledWith('/repo-feature', { + signal: expect.any(AbortSignal), + sharedLinkPaths: ['node_modules'] + }) expect(result.candidates).toHaveLength(1) expect(result.candidates[0]).toMatchObject({ tier: 'ready', diff --git a/src/main/ipc/worktree-remote.ts b/src/main/ipc/worktree-remote.ts index c10533acb..897700561 100644 --- a/src/main/ipc/worktree-remote.ts +++ b/src/main/ipc/worktree-remote.ts @@ -99,9 +99,14 @@ import { prepareWorktreePushTargetWithExec } from './worktree-push-target-setup' import { isENOENT, registerWorktreeRootsForRepo } from './filesystem-auth' -import { createWorktreeCopiedPaths, createWorktreeLinkedPaths } from './worktree-symlinks' +import { + createWorktreeCopiedPaths, + createWorktreeLinkedPaths, + createWorktreeSharedPaths +} from './worktree-symlinks' import { formatWorktreeIncludeCopyWarning } from './worktree-include-copy-budget' import { resolveWorktreeIncludePaths } from '../git/worktree-include-file' +import { resolveWorktreeSharedDirectories } from '../git/worktree-shared-directories' import { normalizeSparseDirectories } from './sparse-checkout-directories' import { joinWorktreeRelativePath } from '../runtime/runtime-relative-paths' import type { IFilesystemProvider } from '../providers/types' @@ -1872,7 +1877,7 @@ export async function createRemoteWorktree( }) const workspaceLineage = recordWorkspaceLineageForCreatedWorktree(store, args, worktree, now) - // Why: shared/symlink paths and `.worktreeinclude` copies are local-only; remote (SSH) support needs a new relay method + auth surface, so both are skipped here. + // Why: shared/symlink paths, `orca.yaml` shared directories, and `.worktreeinclude` copies are local-only; remote (SSH) support needs a new relay method + auth surface, so all are skipped here. let setup: CreateWorktreeResult['setup'] let defaultTabs: CreateWorktreeResult['defaultTabs'] @@ -2468,6 +2473,17 @@ export async function createLocalWorktree( }) } + // Why: project-level `orca.yaml` shared directories add to (never replace) the per-user + // setting, so a repo's shared dirs reach every teammate (issue #10451). + const sharedDirectories = await timing.time('resolve_shared_directories', () => + resolveWorktreeSharedDirectories(repo.path, localWorktreeGitOptions) + ) + if (sharedDirectories.length > 0) { + await timing.time('create_shared_directories', async () => { + await createWorktreeSharedPaths(repo.path, created.path, sharedDirectories) + }) + } + // Why: project-level `.worktreeinclude` travels with the repo (issue #7549); copy semantics // (never symlink) so each worktree owns its files. Paths already linked above are skipped. const includePaths = await timing.time('resolve_worktreeinclude', () => diff --git a/src/main/ipc/worktree-symlinks.test.ts b/src/main/ipc/worktree-symlinks.test.ts index 865c3f17b..ff518b710 100644 --- a/src/main/ipc/worktree-symlinks.test.ts +++ b/src/main/ipc/worktree-symlinks.test.ts @@ -17,7 +17,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' import { createWorktreeCopiedPaths, createWorktreeLinkedPaths, + createWorktreeSharedPaths, createWorktreeSymlinks, + worktreeSymlinkTypeCandidates, findExistingWorktreeSymlinkPaths, removeWorktreeLinkedPaths, removeWorktreeSymlinks @@ -394,6 +396,100 @@ describe('createWorktreeSymlinks', () => { }) }) +// Why: a plain `fs.symlink` needs Developer Mode or admin on Windows, so an +// ordinary Windows user gets EPERM and silently ends up with no shared +// directory at all. A junction needs no privilege — but it cannot target a UNC +// path, which is exactly where a WSL project's repo lives, so the symlink has +// to stay as a fallback rather than be replaced. +describe('worktreeSymlinkTypeCandidates', () => { + it('tries a junction before a symlink for a directory on Windows', () => { + expect(worktreeSymlinkTypeCandidates('win32', true)).toEqual(['junction', 'dir']) + }) + + it('keeps the symlink fallback so a UNC (WSL) target still works', () => { + expect(worktreeSymlinkTypeCandidates('win32', true).at(-1)).toBe('dir') + }) + + it('never uses a junction for a file, which junctions cannot represent', () => { + expect(worktreeSymlinkTypeCandidates('win32', false)).toEqual(['file']) + }) + + it('makes exactly one attempt off Windows, where the type is ignored', () => { + expect(worktreeSymlinkTypeCandidates('darwin', true)).toEqual(['dir']) + expect(worktreeSymlinkTypeCandidates('linux', true)).toEqual(['dir']) + expect(worktreeSymlinkTypeCandidates('linux', false)).toEqual(['file']) + }) +}) + +describe('createWorktreeSharedPaths', () => { + let root: string + let primary: string + let worktree: string + let warn: ReturnType + let error: ReturnType + + beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'orca-sharedpaths-')) + primary = join(root, 'primary') + worktree = join(root, 'worktree') + mkdirSync(primary, { recursive: true }) + mkdirSync(worktree, { recursive: true }) + warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) + error = vi.spyOn(console, 'error').mockImplementation(() => {}) + }) + + afterEach(() => { + warn.mockRestore() + error.mockRestore() + rmSync(root, { recursive: true, force: true }) + }) + + // Why: an APFS clone would give the worktree its own node_modules, defeating + // one-install-serves-all. Share mode must symlink even where cloning works. + posixIt('symlinks on macOS instead of APFS clone-copying', async () => { + mkdirSync(join(primary, 'node_modules')) + writeFileSync(join(primary, 'node_modules', 'marker'), 'ORIG\n') + const cloneWorktreePath = vi.fn() + + await createWorktreeSharedPaths(primary, worktree, ['node_modules'], { + platform: 'darwin', + cloneWorktreePath + }) + + expect(cloneWorktreePath).not.toHaveBeenCalled() + expect(lstatSync(join(worktree, 'node_modules')).isSymbolicLink()).toBe(true) + }) + + posixIt('shares one directory so worktree writes reach the primary checkout', async () => { + mkdirSync(join(primary, 'node_modules')) + + await createWorktreeSharedPaths(primary, worktree, ['node_modules'], { platform: 'linux' }) + + writeFileSync(join(worktree, 'node_modules', 'installed'), 'SHARED\n') + expect(readFileSync(join(primary, 'node_modules', 'installed'), 'utf8')).toBe('SHARED\n') + }) + + posixIt('skips a path already materialized by the per-user symlink pass', async () => { + mkdirSync(join(primary, 'node_modules')) + mkdirSync(join(worktree, 'node_modules')) + + await createWorktreeSharedPaths(primary, worktree, ['node_modules'], { platform: 'linux' }) + + expect(lstatSync(join(worktree, 'node_modules')).isSymbolicLink()).toBe(false) + }) + + it('rejects unsafe paths without touching the filesystem', async () => { + writeFileSync(join(root, 'outside.txt'), 'DO_NOT_TOUCH') + + await createWorktreeSharedPaths(primary, worktree, ['../outside.txt', '/etc/passwd'], { + platform: 'linux' + }) + + expect(readFileSync(join(root, 'outside.txt'), 'utf8')).toBe('DO_NOT_TOUCH') + expect(warn).toHaveBeenCalled() + }) +}) + describe('createWorktreeCopiedPaths', () => { let root: string let primary: string diff --git a/src/main/ipc/worktree-symlinks.ts b/src/main/ipc/worktree-symlinks.ts index 03e6e60b2..e1ac1b4b2 100644 --- a/src/main/ipc/worktree-symlinks.ts +++ b/src/main/ipc/worktree-symlinks.ts @@ -1,5 +1,5 @@ import { symlink, mkdir, stat, lstat, unlink, cp, realpath } from 'node:fs/promises' -import { dirname, isAbsolute, resolve } from 'node:path' +import { dirname, resolve } from 'node:path' import { ApfsCloneUnavailableError, canCloneWithApfs, @@ -14,6 +14,10 @@ import { type SkippedWorktreeCopyPath, type WorktreeCopyBudget } from './worktree-include-copy-budget' +import { + findExistingWorktreeSymlinkPaths, + getSafeRelativePath +} from '../git/worktree-symlink-detection' type WorktreeLinkedPathOptions = { platform?: NodeJS.Platform @@ -27,43 +31,53 @@ type WorktreeLinkedPathOptions = { // 'link': symlink when APFS clone is unavailable (user-configured shared paths). // 'copy': real copy when APFS clone is unavailable (.worktreeinclude paths, which // are per-worktree copies by cross-tool convention — edits must not leak back). -type WorktreeMaterializeMode = 'link' | 'copy' +// 'share': always symlink (orca.yaml sharedDirectories). An APFS clone would give +// each worktree an independent node_modules, defeating one-install-serves-all. +type WorktreeMaterializeMode = 'link' | 'copy' | 'share' -type SafeRelativePathResult = - | { - safe: true - rel: string - } - | { - safe: false - } - -function getSafeRelativePath(rawPath: string): SafeRelativePathResult { - // Why: strip leading separators (both `/` and `\`) before the guard so - // Windows-style input like `\foo` is normalized the same way POSIX `/foo` - // is, and the traversal check below sees the already-relative form. - const rel = rawPath.trim().replace(/^[\\/]+/, '') - // Why: split on both separators so a Windows-authored `..\escape` is - // rejected the same way POSIX `../escape` is. `path.isAbsolute` catches - // drive-letter absolutes (`C:\...`); the split catches relative - // backslash traversal that `.split('/')` would otherwise miss. - if (!rel || isAbsolute(rel) || rel.split(/[\\/]/).includes('..')) { - return { safe: false } +/** The `fs.symlink` types to attempt, in order, for one materialized path. + * + * Why more than one on Windows: a plain symlink needs Developer Mode or admin, + * so an ordinary Windows user gets EPERM and silently ends up with no shared + * directory at all. A directory junction needs no privilege, so try it first. + * + * Why still fall back to a symlink: a junction cannot point at a UNC path, and + * a WSL project's repo lives behind one (`\\wsl.localhost\\...`). The + * fallback keeps that case working exactly as it does today. */ +export function worktreeSymlinkTypeCandidates( + platform: NodeJS.Platform, + sourceIsDirectory: boolean +): ('junction' | 'dir' | 'file')[] { + if (!sourceIsDirectory) { + return ['file'] } - return { safe: true, rel } + return platform === 'win32' ? ['junction', 'dir'] : ['dir'] } async function symlinkWorktreePath( source: string, target: string, - sourceIsDirectory: boolean + sourceIsDirectory: boolean, + platform: NodeJS.Platform ): Promise { await mkdir(dirname(target), { recursive: true }) - // Why: Windows requires an explicit `type` ('dir' vs 'file' vs - // 'junction') for `fs.symlink`. On POSIX the argument is ignored, so - // passing it unconditionally is safe and removes a Windows-only - // failure mode when Node can't auto-detect from the source. - await symlink(source, target, sourceIsDirectory ? 'dir' : 'file') + // Why: Windows requires an explicit `type` ('dir' vs 'file' vs 'junction') + // for `fs.symlink`. On POSIX the argument is ignored, so passing it + // unconditionally is safe and removes a Windows-only failure mode when Node + // can't auto-detect from the source. + const candidates = worktreeSymlinkTypeCandidates(platform, sourceIsDirectory) + for (let index = 0; index < candidates.length; index++) { + try { + // Why: `source` is always absolute (`resolve()` guarantees it), which a + // junction requires. + await symlink(source, target, candidates[index]) + return + } catch (error) { + if (index === candidates.length - 1) { + throw error + } + } + } } async function copyWorktreePath(source: string, target: string): Promise { @@ -93,7 +107,13 @@ async function createWorktreeLinkedPath( apfsFilesystemCache: DarwinFilesystemCache, realCopyFallbackAllowed: () => boolean ): Promise { - if (options.platform === 'darwin' && (!sourceIsSymbolicLink || mode === 'copy')) { + // Why: share mode must never clone — an independent copy would give each + // worktree its own node_modules, defeating one-install-serves-all. + if ( + mode !== 'share' && + options.platform === 'darwin' && + (!sourceIsSymbolicLink || mode === 'copy') + ) { try { const cloneWorktreePath = options.cloneWorktreePath ?? @@ -130,7 +150,7 @@ async function createWorktreeLinkedPath( await copyWorktreePath(copySource, target) return } - await symlinkWorktreePath(source, target, sourceIsDirectory) + await symlinkWorktreePath(source, target, sourceIsDirectory, options.platform ?? process.platform) } /** Whether this copy will land as an APFS clone rather than a byte-for-byte @@ -312,6 +332,19 @@ export async function createWorktreeCopiedPaths( return await materializeWorktreePaths(primaryPath, worktreePath, paths, 'copy', options) } +/** Symlink `orca.yaml` `worktree.sharedDirectories` into a freshly-created + * worktree. Unlike createWorktreeLinkedPaths this never APFS clone-copies: a + * clone would give each worktree its own node_modules, and the point of a + * shared directory is that one install serves every worktree. */ +export async function createWorktreeSharedPaths( + primaryPath: string, + worktreePath: string, + paths: readonly string[], + options: WorktreeLinkedPathOptions = {} +): Promise { + await materializeWorktreePaths(primaryPath, worktreePath, paths, 'share', options) +} + /** Create filesystem symlinks from the primary checkout into a freshly-created * worktree for each configured path. Failures on individual paths are logged * and skipped so a missing/stale entry never blocks worktree creation. @@ -350,26 +383,7 @@ export async function removeWorktreeLinkedPaths( } } -export async function findExistingWorktreeSymlinkPaths( - worktreePath: string, - paths: readonly string[] -): Promise { - const symlinkPaths: string[] = [] - for (const rawPath of paths) { - const safePath = getSafeRelativePath(rawPath) - if (!safePath.safe) { - continue - } - try { - if ((await lstat(resolve(worktreePath, safePath.rel))).isSymbolicLink()) { - symlinkPaths.push(safePath.rel) - } - } catch { - // Why: only a positively identified symlink may bypass dirty preflight. - } - } - return symlinkPaths -} +export { findExistingWorktreeSymlinkPaths } /** Remove previously-created symlinks from a worktree before deletion. * diff --git a/src/main/ipc/worktrees.test.ts b/src/main/ipc/worktrees.test.ts index 72cad2998..646b5cc3a 100644 --- a/src/main/ipc/worktrees.test.ts +++ b/src/main/ipc/worktrees.test.ts @@ -273,6 +273,7 @@ import { __resetDetectedWorktreeScanCacheForTests, registerWorktreeHandlers } from './worktrees' +import { clearConfiguredWorktreeSharedDirectoriesCacheForTests } from '../git/worktree-shared-directories' import { getSshProviderAuthority, resetSshProviderAuthorities, @@ -328,6 +329,7 @@ describe('registerWorktreeHandlers', () => { beforeEach(() => { setPlatform(ORIGINAL_PLATFORM) + clearConfiguredWorktreeSharedDirectoriesCacheForTests() __resetSshWorktreeCreateFetchCacheForTests() __resetDetectedWorktreeScanCacheForTests() resetSshProviderAuthorities() @@ -8151,6 +8153,29 @@ describe('registerWorktreeHandlers', () => { ) }) + it('passes project shared links through the IPC removal preflight and cleanup', async () => { + mockKnownFeatureWorktree() + loadHooksMock.mockReturnValue({ + worktree: { sharedDirectories: ['node_modules'] } + }) + findExistingWorktreeSymlinkPathsMock.mockResolvedValue(['node_modules']) + removeWorktreeMock.mockResolvedValue({}) + + await handlers['worktrees:remove'](null, { + worktreeId: 'repo-1::/workspace/feature-wt' + }) + + expect(findExistingWorktreeSymlinkPathsMock).toHaveBeenCalledWith('/workspace/feature-wt', [ + 'node_modules' + ]) + expect(assertWorktreeCleanForRemovalMock).toHaveBeenCalledWith('/workspace/feature-wt', false, { + ignoredUntrackedPaths: ['node_modules'] + }) + expect(removeWorktreeLinkedPathsMock).toHaveBeenCalledWith('/workspace/feature-wt', [ + 'node_modules' + ]) + }) + it('does not remove a worktree when watcher teardown cannot release it', async () => { mockKnownFeatureWorktree() store.getRepo.mockReturnValue({ diff --git a/src/main/ipc/worktrees.ts b/src/main/ipc/worktrees.ts index 855606167..64ffdf257 100644 --- a/src/main/ipc/worktrees.ts +++ b/src/main/ipc/worktrees.ts @@ -120,6 +120,7 @@ import type { OrcaRuntimeService, RuntimeWorktreeLifecycleEvent } from '../runti import { killAllProcessesForWorktree } from '../runtime/worktree-teardown' import { clearProviderPtyState, getLocalPtyProvider, getSshPtyProvider } from './pty' import { findExistingWorktreeSymlinkPaths, removeWorktreeLinkedPaths } from './worktree-symlinks' +import { getWorktreeSharedLinkPaths } from '../git/worktree-shared-directories' import { track } from '../telemetry/client' import { getCohortAtEmit } from '../telemetry/cohort-classifier' import { workspaceSourceSchema, type WorkspaceSource } from '../../shared/telemetry-events' @@ -2546,7 +2547,10 @@ export function registerWorktreeHandlers( ) } - const linkedPaths = repo.symlinkPaths ?? [] + // Why: `orca.yaml` shared directories are symlinked in too, and a + // directory-only ignore rule leaves those links untracked, so removal must + // tolerate and unlink them exactly like the per-user shared paths. + const linkedPaths = getWorktreeSharedLinkPaths(repo) const ignoredLinkedPaths = args.force ? [] : await findExistingWorktreeSymlinkPaths(canonicalWorktreePath, linkedPaths) diff --git a/src/main/runtime/orca-runtime-git.test.ts b/src/main/runtime/orca-runtime-git.test.ts index 1103852ed..544b9b6b2 100644 --- a/src/main/runtime/orca-runtime-git.test.ts +++ b/src/main/runtime/orca-runtime-git.test.ts @@ -19,14 +19,16 @@ const mocks = vi.hoisted(() => ({ generatePullRequestFieldsFromContext: vi.fn(), resolveCommitMessageSettings: vi.fn(), resolveHostedReviewBodyForGeneration: vi.fn(), - getSshGitProvider: vi.fn() + getSshGitProvider: vi.fn(), + getStatus: vi.fn() })) vi.mock('../git/status', async () => ({ ...(await vi.importActual('../git/status')), abortMerge: mocks.abortMerge, abortRebase: mocks.abortRebase, - getStagedCommitContext: mocks.getStagedCommitContext + getStagedCommitContext: mocks.getStagedCommitContext, + getStatus: mocks.getStatus })) vi.mock('../git/checkout', () => ({ @@ -100,6 +102,7 @@ describe('RuntimeGitCommands', () => { mocks.resolveHostedReviewBodyForGeneration.mockReset() mocks.resolveHostedReviewBodyForGeneration.mockImplementation(async ({ body }) => body) mocks.getSshGitProvider.mockReset() + mocks.getStatus.mockReset() mocks.checkoutBranch.mockReset() mocks.listLocalBranches.mockReset() }) @@ -121,6 +124,45 @@ describe('RuntimeGitCommands', () => { expect(mocks.abortMerge).toHaveBeenCalledWith(worktreePath, {}) }) + // Why: a directory-only ignore rule (`node_modules/`) never matches the shared + // symlink, so Git reports it untracked forever. Runtime/CLI status has to tell + // getStatus which untracked entries are Orca's own (issue #10451); nothing else + // asserts this call site supplies them. + it('passes the repo shared link paths through local runtime status', async () => { + mocks.getStatus.mockResolvedValue({ entries: [], conflictOperation: 'none' }) + const commands = new RuntimeGitCommands({ + resolveRuntimeGitTarget: async () => ({ + worktree: makeWorktree('/workspace/feature'), + repo: { path: '/workspace/repo', symlinkPaths: ['node_modules'] } as never + }), + getRuntimeSettings: () => ({}) as GlobalSettings + }) + + await commands.getRuntimeGitStatus('id:wt-1') + + expect(mocks.getStatus).toHaveBeenCalledWith('/workspace/feature', { + sharedLinkPaths: ['node_modules'] + }) + }) + + it('does not resolve shared link paths for a remote runtime status', async () => { + const provider = { getStatus: vi.fn().mockResolvedValue({ entries: [] }) } + mocks.getSshGitProvider.mockReturnValue(provider) + const commands = new RuntimeGitCommands({ + resolveRuntimeGitTarget: async () => ({ + worktree: makeWorktree('/remote/repo'), + repo: { path: '/remote/repo', symlinkPaths: ['node_modules'] } as never, + connectionId: 'conn-1' + }), + getRuntimeSettings: () => ({}) as GlobalSettings + }) + + await commands.getRuntimeGitStatus('id:wt-1') + + expect(provider.getStatus).toHaveBeenCalledWith('/remote/repo') + expect(mocks.getStatus).not.toHaveBeenCalled() + }) + it('aborts a remote merge through the SSH git provider', async () => { const provider = { abortMerge: vi.fn().mockResolvedValue(undefined) } mocks.getSshGitProvider.mockReturnValue(provider) diff --git a/src/main/runtime/orca-runtime-git.ts b/src/main/runtime/orca-runtime-git.ts index a2dd69844..fe1059962 100644 --- a/src/main/runtime/orca-runtime-git.ts +++ b/src/main/runtime/orca-runtime-git.ts @@ -58,6 +58,7 @@ import { SSH_GIT_PROVIDER_UNAVAILABLE_MESSAGE } from '../providers/ssh-git-dispatch' import { checkIgnoredPaths } from '../git/check-ignored-paths' +import { getWorktreeSharedLinkPaths } from '../git/worktree-shared-directories' import { cancelGenerateCommitMessageLocal, cancelGeneratePullRequestFieldsLocal, @@ -196,9 +197,13 @@ export class RuntimeGitCommands { : provider.getStatus(target.worktree.path) } const gitOptions = localGitOptionsForTarget(target) + // Why: Git can't ignore a shared symlink under a directory-only rule, so tell + // status which untracked entries are Orca's own artifacts (issue #10451). + const sharedLinkPaths = target.repo ? getWorktreeSharedLinkPaths(target.repo) : [] + const sharedOptions = sharedLinkPaths.length > 0 ? { sharedLinkPaths } : {} return options - ? getGitStatus(target.worktree.path, { ...options, ...gitOptions }) - : getGitStatus(target.worktree.path, gitOptions) + ? getGitStatus(target.worktree.path, { ...options, ...gitOptions, ...sharedOptions }) + : getGitStatus(target.worktree.path, { ...gitOptions, ...sharedOptions }) } async getRuntimeGitSubmoduleStatus( diff --git a/src/main/runtime/orca-runtime.test.ts b/src/main/runtime/orca-runtime.test.ts index e61b64df1..1e08d90d9 100644 --- a/src/main/runtime/orca-runtime.test.ts +++ b/src/main/runtime/orca-runtime.test.ts @@ -119,6 +119,7 @@ import { _resetTerminalViewAttributesForTest, setTerminalViewAttributes } from './terminal-view-attribute-store' +import { clearConfiguredWorktreeSharedDirectoriesCacheForTests } from '../git/worktree-shared-directories' const ORIGINAL_PLATFORM = process.platform const ORIGINAL_PLATFORM_DESCRIPTOR = Object.getOwnPropertyDescriptor(process, 'platform') @@ -129,6 +130,7 @@ const resolveLocalGitUsernameMock = vi.hoisted(() => vi.fn(async () => '')) vi.mock('../ipc/worktree-symlinks', () => ({ createWorktreeCopiedPaths: vi.fn(), createWorktreeLinkedPaths: vi.fn(), + createWorktreeSharedPaths: vi.fn(), findExistingWorktreeSymlinkPaths: findExistingWorktreeSymlinkPathsMock, removeWorktreeLinkedPaths: removeWorktreeLinkedPathsMock })) @@ -613,6 +615,7 @@ vi.mock('../git/git-username', async () => { function resetRuntimeTestMocks(): void { resetPlatform() + clearConfiguredWorktreeSharedDirectoriesCacheForTests() _resetTerminalViewAttributesForTest() advertisedUrlWatcher.clear() electronMocks.BrowserWindow.fromId.mockReset() @@ -36450,6 +36453,26 @@ describe('OrcaRuntimeService', () => { ) }) + it('passes project shared links through the runtime removal preflight and cleanup', async () => { + const runtime = createWorktreeRemovalRuntime() + vi.mocked(loadHooks).mockReturnValue({ + scripts: {}, + worktree: { sharedDirectories: ['node_modules'] } + }) + findExistingWorktreeSymlinkPathsMock.mockResolvedValue(['node_modules']) + vi.mocked(removeWorktree).mockResolvedValue({}) + + await runtime.removeManagedWorktree(TEST_WORKTREE_ID) + + expect(findExistingWorktreeSymlinkPathsMock).toHaveBeenCalledWith(TEST_WORKTREE_PATH, [ + 'node_modules' + ]) + expect(assertWorktreeCleanForRemoval).toHaveBeenCalledWith(TEST_WORKTREE_PATH, false, { + ignoredUntrackedPaths: ['node_modules'] + }) + expect(removeWorktreeLinkedPathsMock).toHaveBeenCalledWith(TEST_WORKTREE_PATH, ['node_modules']) + }) + it('does not remove a runtime worktree when watcher teardown cannot release it', async () => { const repo = { ...store.getRepos()[0], symlinkPaths: ['node_modules'] } const runtimeStore = { ...store, getRepos: () => [repo], getRepo: () => repo } diff --git a/src/main/runtime/orca-runtime.ts b/src/main/runtime/orca-runtime.ts index 9278dcf7d..aa4d66ada 100644 --- a/src/main/runtime/orca-runtime.ts +++ b/src/main/runtime/orca-runtime.ts @@ -814,11 +814,16 @@ import { listRepoWorktrees } from '../repo-worktrees' import { createWorktreeCopiedPaths, createWorktreeLinkedPaths, + createWorktreeSharedPaths, findExistingWorktreeSymlinkPaths, removeWorktreeLinkedPaths } from '../ipc/worktree-symlinks' import { formatWorktreeIncludeCopyWarning } from '../ipc/worktree-include-copy-budget' import { resolveWorktreeIncludePaths } from '../git/worktree-include-file' +import { + getWorktreeSharedLinkPaths, + resolveWorktreeSharedDirectories +} from '../git/worktree-shared-directories' import { deleteWorktreeHistoryDir } from '../terminal-history' import { cleanupUnusedWorktreePushTargetRemote, @@ -19405,6 +19410,16 @@ export class OrcaRuntimeService { await createWorktreeLinkedPaths(repo.path, created.path, symlinkPaths) } + // Why: project-level `orca.yaml` shared directories add to (never replace) the + // per-user setting, so a repo's shared dirs reach every teammate (issue #10451). + const sharedDirectories = await resolveWorktreeSharedDirectories( + repo.path, + localWorktreeGitOptions + ) + if (sharedDirectories.length > 0) { + await createWorktreeSharedPaths(repo.path, created.path, sharedDirectories) + } + // Why: project-level `.worktreeinclude` travels with the repo (issue #7549); copy semantics // (never symlink) so each worktree owns its files. Paths already linked above are skipped. const worktreeIncludePaths = await resolveWorktreeIncludePaths( @@ -21530,7 +21545,10 @@ export class OrcaRuntimeService { throw new Error(formatWorktreeRemovalError(error, canonicalWorktreePath, force)) } - const linkedPaths = repo.symlinkPaths ?? [] + // Why: `orca.yaml` shared directories are symlinked in too, and a + // directory-only ignore rule leaves those links untracked, so removal must + // tolerate and unlink them exactly like the per-user shared paths. + const linkedPaths = getWorktreeSharedLinkPaths(repo) const ignoredLinkedPaths = force ? [] : await findExistingWorktreeSymlinkPaths(canonicalWorktreePath, linkedPaths) diff --git a/src/main/source-control/hosted-review-creation-shared-symlinks.test.ts b/src/main/source-control/hosted-review-creation-shared-symlinks.test.ts new file mode 100644 index 000000000..ff0fcf6e0 --- /dev/null +++ b/src/main/source-control/hosted-review-creation-shared-symlinks.test.ts @@ -0,0 +1,245 @@ +import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +const { + createGitHubPullRequestMock, + getRepoSlugMock, + getProjectSlugMock, + getBitbucketRepoSlugMock, + getAzureDevOpsRepoSlugMock, + getGiteaRepoSlugMock, + getEnterpriseGitHubRepoSlugMock, + getHostedReviewForBranchMock, + ghExecFileAsyncMock, + glabExecFileAsyncMock, + gitExecFileAsyncMock, + getUpstreamStatusMock, + getSshGitProviderMock +} = vi.hoisted(() => ({ + createGitHubPullRequestMock: vi.fn(), + getRepoSlugMock: vi.fn(), + getProjectSlugMock: vi.fn(), + getBitbucketRepoSlugMock: vi.fn(), + getAzureDevOpsRepoSlugMock: vi.fn(), + getGiteaRepoSlugMock: vi.fn(), + getEnterpriseGitHubRepoSlugMock: vi.fn(), + getHostedReviewForBranchMock: vi.fn(), + ghExecFileAsyncMock: vi.fn(), + glabExecFileAsyncMock: vi.fn(), + gitExecFileAsyncMock: vi.fn(), + getUpstreamStatusMock: vi.fn(), + getSshGitProviderMock: vi.fn() +})) + +vi.mock('../github/client', () => ({ + createGitHubPullRequest: createGitHubPullRequestMock, + getRepoSlug: getRepoSlugMock, + getPRForBranch: vi.fn() +})) +vi.mock('../github/github-enterprise-repository', () => ({ + getEnterpriseGitHubRepoSlug: getEnterpriseGitHubRepoSlugMock +})) +vi.mock('../gitlab/client', () => ({ + getProjectSlug: getProjectSlugMock, + getMergeRequestForBranch: vi.fn(), + getMergeRequest: vi.fn() +})) +vi.mock('../gitlab/merge-request-creation', () => ({ createGitLabMergeRequest: vi.fn() })) +vi.mock('../bitbucket/client', () => ({ + getBitbucketRepoSlug: getBitbucketRepoSlugMock, + getBitbucketPullRequestForBranch: vi.fn(), + getBitbucketPullRequest: vi.fn() +})) +vi.mock('../azure-devops/client', () => ({ + getAzureDevOpsRepoSlug: getAzureDevOpsRepoSlugMock, + getAzureDevOpsPullRequestForBranch: vi.fn(), + getAzureDevOpsPullRequest: vi.fn() +})) +vi.mock('../azure-devops/pull-request-creation', () => ({ + createAzureDevOpsPullRequest: vi.fn(), + isAzureDevOpsReviewCreationAuthenticated: vi.fn() +})) +vi.mock('../gitea/client', () => ({ + getGiteaRepoSlug: getGiteaRepoSlugMock, + getGiteaPullRequestForBranch: vi.fn(), + getGiteaPullRequest: vi.fn() +})) +vi.mock('../gitea/pull-request-creation', () => ({ + createGiteaPullRequest: vi.fn(), + isGiteaReviewCreationAuthenticated: vi.fn() +})) +vi.mock('../github/gh-utils', () => ({ + acquire: vi.fn(), + release: vi.fn(), + ghExecFileAsync: ghExecFileAsyncMock, + gitExecFileAsync: gitExecFileAsyncMock +})) +vi.mock('../gitlab/gl-utils', () => ({ + acquire: vi.fn(), + release: vi.fn(), + glabExecFileAsync: glabExecFileAsyncMock, + glabRepoExecOptions: (repoPath: string) => ({ cwd: repoPath }) +})) +vi.mock('../git/upstream', () => ({ getUpstreamStatus: getUpstreamStatusMock })) +vi.mock('../providers/ssh-git-dispatch', () => ({ getSshGitProvider: getSshGitProviderMock })) +vi.mock('./hosted-review', () => ({ getHostedReviewForBranch: getHostedReviewForBranchMock })) + +import { createHostedReview } from './hosted-review-creation' + +// Why: a directory-only ignore rule (`node_modules/`) never matches the +// worktree's symlink, so Git reports it untracked. Without the exclusion the +// dirty preflight blocks Create PR and tells the user to commit an entry they +// cannot commit — it is a symlink Orca created. +describe('createHostedReview with shared symlinks', () => { + let worktree: string + let statusOutput: string + + const createPr = (sharedLinkPaths?: string[]): ReturnType => + createHostedReview( + worktree, + { provider: 'github', base: 'main', head: 'feature', title: 'Feature' }, + null, + sharedLinkPaths ? { sharedLinkPaths } : {} + ) + + beforeEach(() => { + worktree = mkdtempSync(join(tmpdir(), 'orca-hosted-shared-')) + mkdirSync(join(worktree, 'primary-node-modules')) + symlinkSync(join(worktree, 'primary-node-modules'), join(worktree, 'node_modules'), 'dir') + // Default: git reports only the shared symlink as untracked. + statusOutput = '?? node_modules\0' + + for (const mock of [ + createGitHubPullRequestMock, + getRepoSlugMock, + getProjectSlugMock, + getBitbucketRepoSlugMock, + getAzureDevOpsRepoSlugMock, + getGiteaRepoSlugMock, + getEnterpriseGitHubRepoSlugMock, + getHostedReviewForBranchMock, + ghExecFileAsyncMock, + glabExecFileAsyncMock, + gitExecFileAsyncMock, + getUpstreamStatusMock, + getSshGitProviderMock + ]) { + mock.mockReset() + } + + getProjectSlugMock.mockResolvedValue(null) + getRepoSlugMock.mockResolvedValue({ owner: 'acme', repo: 'orca' }) + getBitbucketRepoSlugMock.mockResolvedValue(null) + getAzureDevOpsRepoSlugMock.mockResolvedValue(null) + getGiteaRepoSlugMock.mockResolvedValue(null) + getEnterpriseGitHubRepoSlugMock.mockResolvedValue(null) + getHostedReviewForBranchMock.mockResolvedValue(null) + ghExecFileAsyncMock.mockResolvedValue({ stdout: '', stderr: '' }) + glabExecFileAsyncMock.mockResolvedValue({ stdout: '', stderr: '' }) + getUpstreamStatusMock.mockResolvedValue({ + hasUpstream: true, + upstreamName: 'origin/feature', + ahead: 0, + behind: 0 + }) + createGitHubPullRequestMock.mockResolvedValue({ + ok: true, + number: 12, + url: 'https://github.com/acme/orca/pull/12' + }) + gitExecFileAsyncMock.mockImplementation(async (args: string[]) => { + if (args[0] === 'rev-parse') { + return { stdout: 'feature\n', stderr: '' } + } + if (args[0] === 'status') { + return { stdout: statusOutput, stderr: '' } + } + if (args[0] === 'for-each-ref') { + return { stdout: 'refs/remotes/origin/main\n', stderr: '' } + } + if (args[0] === 'log') { + return { stdout: 'Feature title\n', stderr: '' } + } + return { stdout: '', stderr: '' } + }) + }) + + afterEach(() => { + rmSync(worktree, { recursive: true, force: true }) + }) + + it('blocks creation when the shared symlink is not declared', async () => { + await expect(createPr()).resolves.toEqual( + expect.objectContaining({ ok: false, code: 'validation' }) + ) + expect(createGitHubPullRequestMock).not.toHaveBeenCalled() + }) + + it('creates the pull request when the untracked entry is a declared shared symlink', async () => { + await expect(createPr(['node_modules'])).resolves.toEqual({ + ok: true, + number: 12, + url: 'https://github.com/acme/orca/pull/12' + }) + expect(createGitHubPullRequestMock).toHaveBeenCalledOnce() + }) + + // The control that matters: real work must never be waved through. + it('still blocks when a genuine untracked file sits beside the shared symlink', async () => { + statusOutput = '?? node_modules\0?? scratch.txt\0' + + await expect(createPr(['node_modules'])).resolves.toEqual( + expect.objectContaining({ ok: false, code: 'validation' }) + ) + expect(createGitHubPullRequestMock).not.toHaveBeenCalled() + }) + + it('still blocks on a modified tracked file beside the shared symlink', async () => { + statusOutput = '?? node_modules\0 M src/app.ts\0' + + await expect(createPr(['node_modules'])).resolves.toEqual( + expect.objectContaining({ ok: false, code: 'validation' }) + ) + expect(createGitHubPullRequestMock).not.toHaveBeenCalled() + }) + + // Why: only a real symlink is excluded. `notes` is declared shared but exists + // as a regular file here, so it is the user's work and must still block. + it('still blocks when a declared name exists as a regular file', async () => { + writeFileSync(join(worktree, 'notes'), 'user work\n') + statusOutput = '?? notes\0' + + await expect(createPr(['node_modules', 'notes'])).resolves.toEqual( + expect.objectContaining({ ok: false, code: 'validation' }) + ) + expect(createGitHubPullRequestMock).not.toHaveBeenCalled() + }) + + // Why: only an *untracked* record can be Orca's artifact. A tracked change at a + // declared path is committable work, so waving it through would create a review + // off a branch missing it. + it('still blocks on a tracked change at the declared shared path', async () => { + // Both paths are declared shared and both are real symlinks, so only the + // untracked/tracked distinction can keep this from being waved through. + symlinkSync(join(worktree, 'primary-node-modules'), join(worktree, 'tracked-link'), 'dir') + statusOutput = '?? node_modules\0 M tracked-link\0' + + await expect(createPr(['node_modules', 'tracked-link'])).resolves.toEqual( + expect.objectContaining({ ok: false, code: 'validation' }) + ) + expect(createGitHubPullRequestMock).not.toHaveBeenCalled() + }) + + it('does not mistake a rename origin for an untracked shared path', async () => { + // `R renamed.txt\0node_modules\0` — the origin field must be consumed, not + // read as its own `?? node_modules` record. + statusOutput = 'R renamed.txt\0node_modules\0' + + await expect(createPr(['node_modules'])).resolves.toEqual( + expect.objectContaining({ ok: false, code: 'validation' }) + ) + expect(createGitHubPullRequestMock).not.toHaveBeenCalled() + }) +}) diff --git a/src/main/source-control/hosted-review-creation.test.ts b/src/main/source-control/hosted-review-creation.test.ts index cb593ae6a..43de5f425 100644 --- a/src/main/source-control/hosted-review-creation.test.ts +++ b/src/main/source-control/hosted-review-creation.test.ts @@ -387,7 +387,7 @@ describe('createHostedReview', () => { wslDistro: 'Ubuntu' }) expect(gitExecFileAsyncMock).toHaveBeenCalledWith( - ['status', '--porcelain'], + ['status', '--porcelain', '-z'], expect.objectContaining({ cwd: '/repo', wslDistro: 'Ubuntu' }) ) expect(getUpstreamStatusMock).toHaveBeenCalledWith('/repo', undefined, { diff --git a/src/main/source-control/hosted-review-creation.ts b/src/main/source-control/hosted-review-creation.ts index 618ef9bb6..75e3189f4 100644 --- a/src/main/source-control/hosted-review-creation.ts +++ b/src/main/source-control/hosted-review-creation.ts @@ -23,6 +23,8 @@ import { acquire, ghExecFileAsync, gitExecFileAsync, release } from '../github/g import { isNoUpstreamError, normalizeGitErrorMessage } from '../../shared/git-remote-error' import type { GitUpstreamStatus } from '../../shared/types' import { gitOptionalLocksDisabledEnv } from '../git/runner' +import { parsePorcelainV1Records, type PorcelainV1Record } from '../git/porcelain-v1-records' +import { findExistingWorktreeSymlinkPaths } from '../git/worktree-symlink-detection' import { resolveDefaultBaseRefViaExec } from '../git/repo' import { getUpstreamStatus } from '../git/upstream' import { getProjectSlug } from '../gitlab/client' @@ -196,15 +198,43 @@ async function hasUncommittedChanges( ) } // Why: the relay restricts generic git.exec, so use the structured status RPC for SSH dirty checks. + // No shared-link exclusion here: remote worktree creation skips the symlink + // and shared-directory passes entirely, so a remote worktree never has one. return (await provider.getStatus(repoPath)).entries.length > 0 } - const { stdout } = await gitExecFileAsync(['status', '--porcelain'], { + // Why: `-z` keeps paths raw so the shared-link comparison below can't be + // defeated by Git quoting a path with spaces or non-ASCII bytes. + const { stdout } = await gitExecFileAsync(['status', '--porcelain', '-z'], { cwd: repoPath, ...getHostedReviewLocalGitOptions(options), // Why: don't take Git's optional index lock while the user may be running fetch/pull/rebase in a terminal. env: gitOptionalLocksDisabledEnv() }) - return stdout.trim().length > 0 + const records = parsePorcelainV1Records(stdout) + if (records.length === 0) { + return false + } + return await anyRecordIsUserDirt(repoPath, records, options.sharedLinkPaths ?? []) +} + +/** True when any record is real user work rather than a shared symlink Orca put + * in the worktree. + * + * Fails closed on purpose: anything not positively identified as an Orca-owned + * untracked symlink counts as dirty. A false "clean" would let a review be + * created off a branch missing the user's work. */ +async function anyRecordIsUserDirt( + worktreePath: string, + records: readonly PorcelainV1Record[], + sharedLinkPaths: readonly string[] +): Promise { + if (sharedLinkPaths.length === 0 || !records.some((record) => record.xy === '??')) { + return true + } + // Why: only entries that are configured AND really symlinks are excluded, so a + // regular file the user created at a configured name still blocks creation. + const sharedLinks = new Set(await findExistingWorktreeSymlinkPaths(worktreePath, sharedLinkPaths)) + return records.some((record) => record.xy !== '??' || !sharedLinks.has(record.path)) } async function getHostedReviewUpstreamStatus( diff --git a/src/main/source-control/hosted-review-git-options.ts b/src/main/source-control/hosted-review-git-options.ts index 40b0b6b0c..eb8dc63f3 100644 --- a/src/main/source-control/hosted-review-git-options.ts +++ b/src/main/source-control/hosted-review-git-options.ts @@ -4,6 +4,10 @@ export type HostedReviewLocalGitOptions = { export type HostedReviewExecutionOptions = { localGitExecOptions?: HostedReviewLocalGitOptions + /** Paths Orca may have symlinked into this worktree. An untracked entry that + * is one of these is Orca's own artifact, not work the user can commit, so it + * must not read as "dirty" and block review creation. */ + sharedLinkPaths?: readonly string[] } export function getHostedReviewLocalGitOptions( diff --git a/src/shared/orca-yaml.ts b/src/shared/orca-yaml.ts index e8cb15e0a..f5abd79c1 100644 --- a/src/shared/orca-yaml.ts +++ b/src/shared/orca-yaml.ts @@ -31,6 +31,46 @@ export const ORCA_VM_RECIPE_ID_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/ export const ORCA_VM_RECIPE_ID_RULE = 'Use 1-64 lowercase letters, numbers, dots, underscores, or hyphens, starting with a letter or number.' +// Why: bound the work one repo file can request; entries beyond this are ignored. +const MAX_SHARED_DIRECTORIES = 100 + +/** Normalize `worktree.sharedDirectories` into deduped repo-root-relative paths. + * `\` becomes `/`, a `./` prefix and trailing `/` are stripped. Absolute paths, + * `..` traversal and `.git` are dropped here so callers get only safe entries. + * + * Entries that would still need collapsing (`apps/./web`) are dropped rather + * than rewritten: `resolve()` collapses them when the symlink is created, but + * Git reports the collapsed path, so every later comparison against the stored + * entry would miss and the link would look like permanent untracked work. */ +function normalizeSharedDirectories(value: unknown): string[] { + if (!Array.isArray(value)) { + return [] + } + + const seen = new Set() + for (const entry of value.slice(0, MAX_SHARED_DIRECTORIES)) { + const raw = asTrimmedString(entry) + if (!raw) { + continue + } + const normalized = raw.replace(/\\/g, '/').replace(/^\.\//, '').replace(/\/+$/, '') + const segments = normalized.split('/') + if ( + !normalized || + normalized.startsWith('/') || + /^[a-zA-Z]:/.test(normalized) || + segments.includes('..') || + segments.includes('.') || + segments.includes('') || + segments.includes('.git') + ) { + continue + } + seen.add(normalized) + } + return Array.from(seen) +} + function normalizeDefaultTabs(value: unknown): OrcaDefaultTabTemplate[] { if (!Array.isArray(value) || value.length > MAX_ORCA_YAML_COLLECTION_ENTRIES) { return [] @@ -180,6 +220,10 @@ export function parseOrcaYaml(content: string): OrcaHooks | null { const environmentRecipeParse = normalizeVmRecipes(record.environmentRecipes) const environmentRecipes = environmentRecipeParse.recipes const environmentRecipeDiagnostics = environmentRecipeParse.diagnostics + const worktreeRecord = asRecord(record.worktree) + const sharedDirectories = worktreeRecord + ? normalizeSharedDirectories(worktreeRecord.sharedDirectories) + : [] if ( !setup && @@ -187,7 +231,8 @@ export function parseOrcaYaml(content: string): OrcaHooks | null { !issueCommand && defaultTabs.length === 0 && environmentRecipes.length === 0 && - environmentRecipeDiagnostics.length === 0 + environmentRecipeDiagnostics.length === 0 && + sharedDirectories.length === 0 ) { return null } @@ -200,6 +245,7 @@ export function parseOrcaYaml(content: string): OrcaHooks | null { ...(issueCommand ? { issueCommand } : {}), ...(defaultTabs.length > 0 ? { defaultTabs } : {}), ...(environmentRecipes.length > 0 ? { environmentRecipes } : {}), - ...(environmentRecipeDiagnostics.length > 0 ? { environmentRecipeDiagnostics } : {}) + ...(environmentRecipeDiagnostics.length > 0 ? { environmentRecipeDiagnostics } : {}), + ...(sharedDirectories.length > 0 ? { worktree: { sharedDirectories } } : {}) } } diff --git a/src/shared/types.ts b/src/shared/types.ts index ec27f1267..dbe2c0340 100644 --- a/src/shared/types.ts +++ b/src/shared/types.ts @@ -2097,6 +2097,13 @@ export type OrcaHooks = { defaultTabs?: OrcaDefaultTabTemplate[] // Terminal tabs to create once for a new worktree environmentRecipes?: OrcaVmRecipe[] // Project-scoped per-workspace environment recipes environmentRecipeDiagnostics?: OrcaVmRecipeDiagnostic[] // Non-fatal validation issues from environmentRecipes + worktree?: OrcaWorktreeDefaults // Project-scoped defaults applied when a worktree is created +} + +export type OrcaWorktreeDefaults = { + // Why: shared (symlinked) rather than copied — large rebuildable dirs like + // node_modules should be one install serving every worktree. + sharedDirectories?: string[] } export type OrcaDefaultTabTemplate = {