From 93b63a9ae2272d4fa04e4d0524dc5bf685b16d42 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:00:13 -0500 Subject: [PATCH 1/2] fix(cloister): reaper keeps unheld commits and precious files; GitLab merge proof (PAN-5990) The closed-issue reaper force-removes a merged workspace. It now also keeps the folder, branches and volumes when: - a checkout holds commits on neither the target nor the verified branch (detached HEAD, another branch, a .swarm worker branch), or a rebase/merge/cherry-pick/revert/bisect is in progress; the remote-less polyrepo wrapper may hold only .gitignore and pipeline-record commits - a known-precious gitignored file exists (.env*, *.sql/.dump/.sqlite/.db outside node_modules, anything under .tmp/); bounded listing with --directory, build/cache folders never inspected - an untracked .overdeck/ file is not one of the exact runtime names Overdeck's writers produce - a file in the synced .claude/skills|commands|agents folders was not written by the sync (manifest entries with matching hash, the agent template's copy_dirs and rendered templates, generated .env and .hume-config are recognised by exact path), even when .claude/ is gitignored The GitLab merged-MR path now refuses a fork MR, a different target or a merge/squash commit not on the target, as the GitHub path does. Closes #5990 Co-Authored-By: Claude Opus 5.5 Overdeck-Conversation: conv-20261204-38bc --- changelog.d/pan-5990.md | 5 + configuration/polyrepo.mdx | 2 + .../reap-issue-residue-forge-merged.test.ts | 16 +- .../__tests__/reap-issue-residue.test.ts | 2 +- src/lib/cloister/reap-issue-residue.ts | 5 +- src/lib/forge.ts | 48 ++- src/lib/lifecycle/verify-merged.ts | 34 +- .../__tests__/reap-work-checks.test.ts | 317 ++++++++++++++++++ .../__tests__/uncommitted-work.test.ts | 40 ++- src/lib/workspaces/ignored-work.ts | 109 ++++++ src/lib/workspaces/overdeck-runtime-files.ts | 74 ++++ src/lib/workspaces/overdeck-written-paths.ts | 149 ++++++++ src/lib/workspaces/uncommitted-work.ts | 100 +++++- src/lib/workspaces/unheld-commits.ts | 132 ++++++++ tests/unit/lib/forge-merged-artifact.test.ts | 65 ++++ .../lifecycle/verify-merged-gitlab-mr.test.ts | 145 ++++++++ 16 files changed, 1199 insertions(+), 44 deletions(-) create mode 100644 changelog.d/pan-5990.md create mode 100644 src/lib/workspaces/__tests__/reap-work-checks.test.ts create mode 100644 src/lib/workspaces/ignored-work.ts create mode 100644 src/lib/workspaces/overdeck-runtime-files.ts create mode 100644 src/lib/workspaces/overdeck-written-paths.ts create mode 100644 src/lib/workspaces/unheld-commits.ts create mode 100644 tests/unit/lib/lifecycle/verify-merged-gitlab-mr.test.ts diff --git a/changelog.d/pan-5990.md b/changelog.d/pan-5990.md new file mode 100644 index 00000000000..3c227f1245e --- /dev/null +++ b/changelog.d/pan-5990.md @@ -0,0 +1,5 @@ +#### Fixed + +- **Closed-issue cleanup keeps work that `git status` cannot see:** before it removes a merged issue's workspace, cleanup now also keeps the folder, both branches and the stack's volumes when a checkout holds a commit that neither the target branch nor the merged feature branch holds (on a detached HEAD, another branch, or a `.swarm/` worker branch), or has a rebase, merge, cherry-pick, revert or bisect in progress. It also keeps them when a gitignored `.env` or `.env.*` file (not `.env.example`), a `.sql`, `.dump`, `.sqlite` or `.db` file outside `node_modules/`, or anything under `.tmp/` is present. Build and cache output never blocks cleanup, and neither does an `.env` that Overdeck rendered from `workspace.env.template`. ([#5990](https://github.com/eltmon/overdeck/issues/5990)) +- **Cleanup recognises Overdeck's own files by exact path:** only the files Overdeck writes under `.overdeck/` (such as `continue.json`, `pipeline.jsonl` and `verification/`) count as runtime. Any other untracked file there, for example a new file under `.overdeck/context/`, keeps the workspace. Synced skills and agents that are unchanged since the sync, the project agent template's files, the rendered `.mcp.json` and an unchanged `.hume-config` no longer keep old polyrepo workspaces forever. A file you add to `.claude/skills/` yourself still keeps the workspace, even when `.claude/` is gitignored. ([#5990](https://github.com/eltmon/overdeck/issues/5990)) +- **GitLab merges are proven like GitHub ones:** a merged GitLab merge request now counts for cleanup only if it comes from the same project, merged into the target branch, and has its merge or squash commit on that branch. If GitLab does not report one of these facts, nothing is removed. ([#5990](https://github.com/eltmon/overdeck/issues/5990)) diff --git a/configuration/polyrepo.mdx b/configuration/polyrepo.mdx index ac646648835..a9a41a6824f 100644 --- a/configuration/polyrepo.mdx +++ b/configuration/polyrepo.mdx @@ -152,6 +152,8 @@ The workspace root becomes a small local repository (no remote) when planning co If a workspace was created before Overdeck started writing these entries, the next agent start from the dashboard repairs it automatically; no manual step is needed. Anything else left uncommitted at the workspace root still stops a start, exactly as before. +When a closed issue's workspace is cleaned up, the root repository's commits may touch only its `.gitignore` and Overdeck's pipeline records (such as `.pan/continues/` and `.pan/specs/`). A commit of anything else, such as a PRD draft under `.pan/drafts/`, keeps the workspace. Cleanup recognises the files Overdeck wrote at the root by exact path, even in a workspace created before the `.gitignore` entries: synced skills and agents that `.claude/.overdeck-manifest.json` lists and that are unchanged, the agent template's `copy_dirs` files and rendered templates such as `.mcp.json`, and an unchanged `.hume-config`. A file you add to `.claude/skills/` yourself keeps the workspace. + ## Template Placeholders | Placeholder | Example | Description | diff --git a/src/lib/cloister/__tests__/reap-issue-residue-forge-merged.test.ts b/src/lib/cloister/__tests__/reap-issue-residue-forge-merged.test.ts index 7d8b01d9225..d9426eb0355 100644 --- a/src/lib/cloister/__tests__/reap-issue-residue-forge-merged.test.ts +++ b/src/lib/cloister/__tests__/reap-issue-residue-forge-merged.test.ts @@ -216,7 +216,7 @@ describe('reapIssueResidue when the forge reports a merged PR (PAN-5959)', () => describe('uncommitted work in a merged workspace (PAN-5979)', () => { it('reaps nothing when a tracked file has an uncommitted change', async () => { writeFileSync(join(workspacePath, 'feature.txt'), 'edited, not committed\n'); - await expectNothingReaped('uncommitted work kept'); + await expectNothingReaped('work kept'); }); it('reaps nothing when a change is staged', async () => { @@ -264,6 +264,20 @@ describe('reapIssueResidue when the forge reports a merged PR (PAN-5959)', () => }); }); + describe('work git status cannot see (PAN-5990)', () => { + it('reaps nothing when a detached HEAD holds a commit on neither main nor the feature branch', async () => { + git(workspacePath, 'switch', '-q', '--detach'); + commitFile(workspacePath, 'detached.txt', 'detached work\n', 'detached work'); + await expectNothingReaped('detached HEAD'); + }); + + it('reaps nothing when the workspace holds a gitignored .env', async () => { + writeFileSync(join(projectPath, '.git', 'info', 'exclude'), '.env\n'); + writeFileSync(join(workspacePath, '.env'), 'SECRET=local\n'); + await expectNothingReaped('gitignored files the reap would delete'); + }); + }); + describe('the merged PR must have merged into the target (PAN-5979)', () => { it('reaps nothing when the PR merged into another base', async () => { mocks.mergedPr = { ...mocks.mergedPr!, baseRefName: 'release' }; diff --git a/src/lib/cloister/__tests__/reap-issue-residue.test.ts b/src/lib/cloister/__tests__/reap-issue-residue.test.ts index e0222c76c4d..f6b170d2dbe 100644 --- a/src/lib/cloister/__tests__/reap-issue-residue.test.ts +++ b/src/lib/cloister/__tests__/reap-issue-residue.test.ts @@ -258,7 +258,7 @@ describe('reapIssueResidue', () => { expect(mocks.reapWorkerWorktrees).not.toHaveBeenCalled(); expect(mocks.exec.mock.calls.some((call) => String(call[0]).startsWith('git branch -D'))).toBe(false); expect(mocks.exec.mock.calls.some((call) => String(call[0]).startsWith('git push origin --delete'))).toBe(false); - expect(actions.some((action) => action.includes('uncommitted work kept') && action.includes('src/wip.ts'))).toBe(true); + expect(actions.some((action) => action.includes('work kept') && action.includes('src/wip.ts'))).toBe(true); }); it('keeps everything when the uncommitted-work check itself throws (PAN-5979)', async () => { diff --git a/src/lib/cloister/reap-issue-residue.ts b/src/lib/cloister/reap-issue-residue.ts index 5675c8d9ace..6e840719cfc 100644 --- a/src/lib/cloister/reap-issue-residue.ts +++ b/src/lib/cloister/reap-issue-residue.ts @@ -86,6 +86,9 @@ export async function reapIssueResidue(projectPath: string, issueId: string): Pr // A merged branch proves nothing about the working trees: the folder (and // every `.swarm/worker-` worktree in it) is force-removed below, so any // uncommitted work keeps the folder, the branches and the volumes (PAN-5979). + // So do commits the merged branch does not hold, a rebase or merge in + // progress, precious gitignored files (`.env*`, dumps, `.tmp/`) and files in + // the synced `.claude/` folders that pan sync did not write (PAN-5990). // Decided before the teardown, which wipes volumes exactly when reapDisk. let dirtyReason: string | null = null; if (reapDisk) { @@ -115,7 +118,7 @@ export async function reapIssueResidue(projectPath: string, issueId: string): Pr if (!reapDisk) { actions.push(dirtyReason - ? `skipped disk reap for ${issueId} — uncommitted work kept (${dirtyReason})` + ? `skipped disk reap for ${issueId} — work kept (${dirtyReason})` : `skipped disk reap for ${issueId} — merge not proven (${mergeProof})`); return actions; } diff --git a/src/lib/forge.ts b/src/lib/forge.ts index 9b5b966ab3e..d36f76bc10e 100644 --- a/src/lib/forge.ts +++ b/src/lib/forge.ts @@ -84,10 +84,10 @@ export interface CreateReviewArtifactResult extends ReviewArtifactRef { /** Merged lookups: the artifact's head commit when the forge reports it. */ headSha?: string; /** - * GitHub merged lookups (PAN-5964): the PR's base branch, its merge commit, - * and whether it came from a fork, when the forge reports them. The - * closed-issue reaper refuses a merge it cannot prove with all three - * (`mergedIntoTargetRefusal`, PAN-5979). + * Merged lookups (GitHub PAN-5964, GitLab PAN-5990): the PR's or MR's base + * branch, its merge commit, and whether it came from a fork, when the forge + * reports them. The closed-issue reaper refuses a merge it cannot prove with + * all three (`mergedIntoTargetRefusal`, PAN-5979). */ baseRefName?: string; mergeCommitOid?: string; @@ -408,25 +408,41 @@ async function findMergedGitLabArtifact( encoding: 'utf-8', timeout: FORGE_OBSERVATION_TIMEOUT_MS, }); - const artifacts = target ? [JSON.parse(stdout.trim())] : JSON.parse(stdout.trim() || '[]') as Array<{ - iid?: number; web_url?: string; state?: string; source_branch?: string; - target_branch?: string; sha?: string; - }>; - const merged = artifacts.find((artifact: { - iid?: number; web_url?: string; state?: string; source_branch?: string; - target_branch?: string; sha?: string; - }) => artifact.state === 'merged' && matchesCurrentArtifact(input, { - sourceBranch: artifact.source_branch, - targetBranch: artifact.target_branch, - headSha: artifact.sha, - })); + const artifacts = (target ? [JSON.parse(stdout.trim())] : JSON.parse(stdout.trim() || '[]')) as GlabMergedMr[]; + // PAN-5990: a fork's MR can share the branch name, as with GitHub; a listed + // MR known to come from another project is dropped, as `gh pr list` rows are. + const merged = artifacts.find((artifact) => artifact.state === 'merged' + && (target !== undefined || glabIsCrossProject(artifact) !== true) + && matchesCurrentArtifact(input, { + sourceBranch: artifact.source_branch, + targetBranch: artifact.target_branch, + headSha: artifact.sha, + })); return merged ? { forge: 'gitlab', created: false, url: merged.web_url, id: merged.iid ? String(merged.iid) : input.artifactId, headSha: merged.sha, + baseRefName: merged.target_branch, + // A merge-commit MR records `merge_commit_sha`; a fast-forward squash + // records only `squash_commit_sha`. Either is the commit on the target. + mergeCommitOid: merged.merge_commit_sha || merged.squash_commit_sha || undefined, + isCrossRepository: glabIsCrossProject(merged), } : null; } +type GlabMergedMr = { + iid?: number; web_url?: string; state?: string; source_branch?: string; + target_branch?: string; sha?: string; + merge_commit_sha?: string | null; squash_commit_sha?: string | null; + source_project_id?: number | null; target_project_id?: number | null; +}; + +/** Whether the MR comes from another project (a fork), or undefined when GitLab does not say. */ +function glabIsCrossProject(mr: GlabMergedMr): boolean | undefined { + if (typeof mr.source_project_id !== 'number' || typeof mr.target_project_id !== 'number') return undefined; + return mr.source_project_id !== mr.target_project_id; +} + function delay(ms: number): Promise { return new Promise((resolve) => setTimeout(resolve, ms)); } diff --git a/src/lib/lifecycle/verify-merged.ts b/src/lib/lifecycle/verify-merged.ts index 2609b7c912b..fda3a0996b3 100644 --- a/src/lib/lifecycle/verify-merged.ts +++ b/src/lib/lifecycle/verify-merged.ts @@ -227,7 +227,10 @@ export async function verifyBranchMergedImpl( interface GitLabMergeLookupCache { attempted: boolean; - artifact?: { id?: string; url?: string; headSha?: string } | null; + artifact?: { + id?: string; url?: string; headSha?: string; + baseRefName?: string; mergeCommitOid?: string; isCrossRepository?: boolean; + } | null; } /** The PAN-2406 / FR-5 post-merge delta judgment, shared by the GitHub PR and GitLab MR paths. */ @@ -477,6 +480,24 @@ async function verifySquashMergedMrByBranch( const artifact = lookup.artifact; if (!artifact?.headSha) return null; + // PAN-5990: the same proof the GitHub path demands (PAN-5979), checked + // before the head match: same project, based on the target, merge commit + // on the target. A missing fact is a refusal. + if (root.requireBranchCovered) { + const refusal = await mergedIntoTargetRefusal(root, { + headRefOid: artifact.headSha, + baseRefName: artifact.baseRefName, + mergeCommitOid: artifact.mergeCommitOid, + isCrossRepository: artifact.isCrossRepository, + }, comparison.ref, artifact.id ? `MR !${artifact.id}` : 'the merged GitLab MR'); + if (refusal) { + return { + result: stepFailed('close-out:verify-merged', `Merge into ${root.targetBranch} not proven for ${branchRef}: ${refusal}`), + reused, + }; + } + } + if (tipSha === artifact.headSha) { const label = artifact.id ? `MR !${artifact.id}` : 'GitLab MR'; const url = artifact.url ? ` (${artifact.url})` : ''; @@ -503,10 +524,15 @@ async function verifySquashMergedMrByBranch( * or null when it does. The PR must come from this repository (a fork's PR * can share the branch name, and `gh pr list --head` does not filter by * owner), its base must be the target, and its merge commit must be on the - * target ref. A missing field is a refusal. + * target ref. A missing field is a refusal. PAN-5990: a merged GitLab MR is + * judged the same way, under its own `label`. */ -async function mergedIntoTargetRefusal(root: MergeVerificationRoot, pr: MergedPrFacts, targetRef: string): Promise { - const label = typeof pr.number === 'number' ? `PR #${pr.number}` : 'the merged GitHub PR'; +async function mergedIntoTargetRefusal( + root: MergeVerificationRoot, + pr: MergedPrFacts, + targetRef: string, + label = typeof pr.number === 'number' ? `PR #${pr.number}` : 'the merged GitHub PR', +): Promise { if (pr.isCrossRepository !== false) { return pr.isCrossRepository === true ? `${label} comes from another repository (a fork)` diff --git a/src/lib/workspaces/__tests__/reap-work-checks.test.ts b/src/lib/workspaces/__tests__/reap-work-checks.test.ts new file mode 100644 index 00000000000..7b698f5e713 --- /dev/null +++ b/src/lib/workspaces/__tests__/reap-work-checks.test.ts @@ -0,0 +1,317 @@ +/** + * PAN-5990: what `git status` cannot see, checked before the closed-issue + * reaper force-removes a merged workspace. Each case is real git in a temp + * directory: a project repo with a bare origin, the issue's worktree on + * `feature/pan-1`, and the project lookup mocked to a configurable project. + * + * 1. committed work the merged branch does not hold, and operations in progress; + * 2. known-precious gitignored files (keep, don't archive); + * 3. the exact `.overdeck/` runtime names; + * 4. pan-sync output by exact path, and the polyrepo wrapper's `.gitignore`. + */ +import { createHash } from 'node:crypto'; +import { execFileSync } from 'node:child_process'; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; + +const mocks = vi.hoisted(() => ({ + members: [] as string[], + project: null as null | { path: string; workspace: Record }, +})); + +vi.mock('../../project-repos.js', () => ({ + resolveWorkspaceRepoRoots: vi.fn((_issueId: string, ws: string) => (mocks.members.length === 0 + ? [{ repoKey: 'pan-1', dir: ws, sourceBranch: 'feature/pan-1', targetBranch: 'main', isPolyrepo: false }] + : mocks.members.map((key) => ({ repoKey: key, dir: join(ws, key), sourceBranch: 'feature/pan-1', targetBranch: 'main', isPolyrepo: true })))), +})); +vi.mock('../../projects.js', () => ({ + resolveProjectFromIssueSync: vi.fn(() => (mocks.project + ? { projectKey: 'zzq', projectName: 'zzq', projectPath: mocks.project.path } + : null)), + getProjectSync: vi.fn(() => (mocks.project ? { name: 'zzq', path: mocks.project.path, workspace: mocks.project.workspace } : null)), +})); + +import { checkWorkspaceUncommittedWork } from '../uncommitted-work.js'; +import { ensurePolyrepoWorkspaceGitignore } from '../../workspace-manager/polyrepo-gitignore.js'; + +const ISSUE = 'PAN-1'; +const BRANCH = 'feature/pan-1'; + +function git(cwd: string, args: string[], env: NodeJS.ProcessEnv = {}): string { + return execFileSync('git', ['-c', 'user.name=test', '-c', 'user.email=test@example.invalid', '-c', 'commit.gpgsign=false', ...args], { + cwd, + encoding: 'utf-8', + stdio: ['ignore', 'pipe', 'ignore'], + env: { ...process.env, ...env }, + }).trim(); +} + +function write(path: string, content: string): void { + mkdirSync(dirname(path), { recursive: true }); + writeFileSync(path, content); +} + +function commitFile(cwd: string, file: string, content: string, message: string): void { + write(join(cwd, file), content); + git(cwd, ['add', '-f', file]); + git(cwd, ['commit', '-q', '-m', message]); +} + +function sha256(path: string): string { + return `sha256:${createHash('sha256').update(readFileSync(path)).digest('hex')}`; +} + +async function verdict(ws: string): Promise<{ clean: boolean; reason?: string }> { + const result = await checkWorkspaceUncommittedWork(ws, ISSUE); + return result.clean ? { clean: true } : { clean: false, reason: result.reason }; +} + +describe('checkWorkspaceUncommittedWork beyond git status (PAN-5990)', () => { + let root: string; + let projectPath: string; + let ws: string; + + beforeEach(() => { + root = mkdtempSync(join(tmpdir(), 'pan-5990-reap-')); + mocks.members = []; + mocks.project = null; + const origin = join(root, 'origin.git'); + git(root, ['init', '-q', '--bare', '-b', 'main', origin]); + projectPath = join(root, 'project'); + mkdirSync(projectPath); + git(projectPath, ['init', '-q', '-b', 'main']); + write(join(projectPath, '.gitignore'), '.swarm/\n.env\n.env.*\n*.sql\n*.db\n*.dump\n*.sqlite\n.tmp/\nnode_modules/\ndist/\nbackups/\n'); + commitFile(projectPath, 'README.md', 'base\n', 'base'); + git(projectPath, ['add', '.gitignore']); + git(projectPath, ['commit', '-q', '-m', 'ignore']); + git(projectPath, ['remote', 'add', 'origin', origin]); + git(projectPath, ['push', '-q', 'origin', 'main']); + + // The issue's worktree; its own commit is on the branch the merge proved. + ws = join(root, 'ws'); + git(projectPath, ['worktree', 'add', '-q', '-b', BRANCH, ws]); + commitFile(ws, 'feature.ts', 'work\n', 'feature work'); + }); + + afterEach(() => { + rmSync(root, { recursive: true, force: true }); + }); + + it('is clean when every commit is on the target or the verified branch', async () => { + expect(await verdict(ws)).toEqual({ clean: true }); + }); + + describe('1. committed work the merged branch does not hold', () => { + it('keeps a detached HEAD with a commit on neither branch', async () => { + git(ws, ['switch', '-q', '--detach']); + commitFile(ws, 'lost.ts', 'detached work\n', 'detached work'); + + const result = await verdict(ws); + + expect(result.clean).toBe(false); + expect(result.reason).toContain('detached HEAD'); + expect(result.reason).toContain('on neither main nor feature/pan-1'); + }); + + it('keeps a commit on another branch checked out in the worktree', async () => { + git(ws, ['switch', '-q', '-c', 'side']); + commitFile(ws, 'side.ts', 'side work\n', 'side work'); + + expect((await verdict(ws)).reason).toContain('branch side'); + }); + + it('accepts a detached HEAD that sits on the verified branch', async () => { + git(ws, ['switch', '-q', '--detach']); + expect(await verdict(ws)).toEqual({ clean: true }); + }); + + it('keeps a rebase paused without conflicts (git status is clean)', async () => { + commitFile(ws, 'second.ts', 'second\n', 'second'); + git(ws, ['rebase', '-q', '-i', 'HEAD~1'], { GIT_SEQUENCE_EDITOR: 'sed -i -e 1s/^pick/edit/' }); + expect(git(ws, ['status', '--porcelain'])).toBe(''); + + expect((await verdict(ws)).reason).toContain('a rebase is in progress'); + }); + + it('keeps a .swarm worker worktree with a commit not on the feature branch', async () => { + const worker = join(ws, '.swarm', 'worker-1'); + git(projectPath, ['worktree', 'add', '-q', '-b', `${BRANCH}-worker-1`, worker, BRANCH]); + commitFile(worker, 'worker.ts', 'worker work\n', 'worker work'); + + const result = await verdict(ws); + + expect(result.reason).toContain(`branch ${BRANCH}-worker-1 in ${worker}`); + }); + + describe('the polyrepo wrapper', () => { + let wrapper: string; + + beforeEach(() => { + mocks.members = ['fe']; + wrapper = join(root, 'wrapper'); + mkdirSync(wrapper); + git(wrapper, ['init', '-q', '-b', 'master']); + commitFile(wrapper, '.gitignore', 'fe/\n', 'chore(plan): complete planning'); + // The member checkout, at the verified branch's tip (the branch itself is checked out in ws). + git(projectPath, ['worktree', 'add', '-q', '--detach', join(wrapper, 'fe'), BRANCH]); + }); + + it('accepts commits of its .gitignore and pipeline records', async () => { + commitFile(wrapper, '.pan/continues/PAN-1.xbrief.json', '{}\n', 'record status'); + expect(await verdict(wrapper)).toEqual({ clean: true }); + }); + + it('keeps a commit of anything else, such as a PRD draft', async () => { + commitFile(wrapper, '.pan/drafts/pan-1.md', '# PRD\n', 'draft'); + expect((await verdict(wrapper)).reason).toContain(`the workspace repo ${wrapper} holds 1 local commit(s)`); + }); + }); + }); + + describe('2. known-precious gitignored files', () => { + it.each([ + ['.env'], + ['config/.env.local'], + ['data/local.sqlite'], + ['seed/prod.sql'], + ['app.db'], + ['.tmp/mockup.html'], + ['backups/deep/prod.dump'], + ])('keeps %s', async (file) => { + write(join(ws, file), 'precious\n'); + + const result = await verdict(ws); + + expect(result.clean).toBe(false); + expect(result.reason).toContain('gitignored files the reap would delete'); + expect(result.reason).toContain(file.startsWith('.tmp/') ? '.tmp/' : file); + }); + + it.each([ + ['.env.example'], + ['node_modules/pkg/fixture.sql'], + ['packages/x/node_modules/pkg/data.db'], + ['dist/cache.db'], + ])('does not keep %s', async (file) => { + write(join(ws, file), 'regenerable\n'); + expect(await verdict(ws)).toEqual({ clean: true }); + }); + + it('does not keep an empty .tmp/ folder', async () => { + mkdirSync(join(ws, '.tmp', 'empty'), { recursive: true }); + expect(await verdict(ws)).toEqual({ clean: true }); + }); + + it('does not keep the .env Overdeck rendered from workspace.env.template', async () => { + mocks.project = { path: projectPath, workspace: { env: { template: 'PORT=1\n' } } }; + write(join(ws, '.env'), 'PORT=1\n'); + expect(await verdict(ws)).toEqual({ clean: true }); + }); + }); + + describe('3. the .overdeck/ runtime names', () => { + it('does not keep the runtime files Overdeck writes', async () => { + write(join(ws, '.overdeck', 'pipeline.jsonl'), '{}\n'); + write(join(ws, '.overdeck', 'continue.json'), '{}\n'); + write(join(ws, '.overdeck', 'verification', '2026-12-03T12-00-00-000Z-abcd1234.json'), '{}\n'); + write(join(ws, '.overdeck', 'feedback', '001-review-pass.md'), 'ok\n'); + expect(await verdict(ws)).toEqual({ clean: true }); + }); + + it.each([ + ['.overdeck/context/codebase/new.md'], + ['.overdeck/notes.md'], + ['.overdeck/feedback/scratch.txt'], + ])('keeps any other untracked file: %s', async (file) => { + write(join(ws, file), 'work\n'); + expect((await verdict(ws)).reason).toContain(file); + }); + }); + + describe('4. pan-sync output', () => { + function syncSkill(name: string): string { + const path = join(ws, '.claude', 'skills', name, 'SKILL.md'); + write(path, `# ${name}\n`); + const manifestPath = join(ws, '.claude', '.overdeck-manifest.json'); + let installed: Record = {}; + try { + installed = (JSON.parse(readFileSync(manifestPath, 'utf-8')) as { installed: Record }).installed; + } catch { /* first entry */ } + installed[`skills/${name}/SKILL.md`] = { hash: sha256(path), source: 'overdeck', installed_at: '2026-12-03T00:00:00Z' }; + write(manifestPath, JSON.stringify({ version: 1, managed_by: 'overdeck', installed })); + return path; + } + + it('does not keep synced skills, the manifest and the sync\'s .claude files', async () => { + syncSkill('pan-done'); + syncSkill('pan-start'); + write(join(ws, '.claude', 'settings.json'), '{}\n'); + write(join(ws, '.claude', '.caveman-variant'), 'x\n'); + expect(await verdict(ws)).toEqual({ clean: true }); + }); + + it('keeps a synced skill that was edited after the sync', async () => { + const path = syncSkill('pan-done'); + writeFileSync(path, '# edited by the operator\n'); + expect((await verdict(ws)).reason).toContain('.claude/skills/pan-done/SKILL.md'); + }); + + it('keeps an operator skill the sync did not write', async () => { + syncSkill('pan-done'); + write(join(ws, '.claude', 'skills', 'mine', 'SKILL.md'), '# mine\n'); + const result = await verdict(ws); + expect(result.reason).toContain('uncommitted changes'); + expect(result.reason).toContain('.claude/skills/mine/SKILL.md'); + }); + + it('keeps an operator skill even when .claude/ is gitignored', async () => { + // The wrapper's generated .gitignore ignores the whole folder (PAN-5199). + writeFileSync(join(projectPath, '.git', 'info', 'exclude'), '.claude/\n'); + syncSkill('pan-done'); + expect(await verdict(ws)).toEqual({ clean: true }); + + write(join(ws, '.claude', 'skills', 'mine', 'SKILL.md'), '# mine\n'); + expect((await verdict(ws)).reason).toContain('files pan sync did not write'); + }); + + it('does not keep files the project agent template wrote; keeps others beside them', async () => { + const templateDir = join(projectPath, 'infra', '.agent-template'); + write(join(templateDir, '.mcp.json.template'), '{"mcpServers":{}}\n'); + write(join(templateDir, '.claude', 'commands', 'work-issue.md'), '# work\n'); + write(join(templateDir, '.claude', 'commands', 'pan', 'up.md'), '# up\n'); + mocks.project = { + path: projectPath, + workspace: { agent: { template_dir: 'infra/.agent-template', copy_dirs: ['.claude/commands'] } }, + }; + write(join(ws, '.mcp.json'), '{"mcpServers":{}}\n'); + write(join(ws, '.claude', 'commands', 'work-issue.md'), '# work for {{FEATURE_FOLDER}}\n'); + write(join(ws, '.claude', 'commands', 'pan', 'up.md'), '# up\n'); + expect(await verdict(ws)).toEqual({ clean: true }); + + write(join(ws, '.claude', 'commands', 'mine.md'), '# mine\n'); + expect((await verdict(ws)).reason).toContain('.claude/commands/mine.md'); + }); + + it('does not keep a .hume-config as Overdeck writes it; keeps an edited one', async () => { + write(join(ws, '.hume-config'), 'HUME_CONFIG_ID=abc-123\nVITE_HUME_CONFIG_ID=abc-123\n'); + expect(await verdict(ws)).toEqual({ clean: true }); + + write(join(ws, '.hume-config'), 'HUME_CONFIG_ID=abc-123\nVITE_HUME_CONFIG_ID=abc-123\nHUME_SECRET=mine\n'); + expect((await verdict(ws)).reason).toContain('.hume-config'); + }); + + it('the generated polyrepo wrapper .gitignore ignores every pan-sync path', () => { + const wrapper = join(root, 'wrapper-ignore'); + mkdirSync(wrapper); + git(wrapper, ['init', '-q', '-b', 'master']); + ensurePolyrepoWorkspaceGitignore(wrapper, [{ name: 'fe' }]); + + const paths = ['.claude/skills/pan-done/SKILL.md', '.claude/commands/pan/up.md', '.claude/agents/pan-work-agent.md', '.mcp.json', '.hume-config']; + const ignored = git(wrapper, ['check-ignore', '--no-index', ...paths]).split('\n'); + + expect(ignored).toEqual(paths); + }); + }); +}); diff --git a/src/lib/workspaces/__tests__/uncommitted-work.test.ts b/src/lib/workspaces/__tests__/uncommitted-work.test.ts index 0ae3579cd61..6a786851291 100644 --- a/src/lib/workspaces/__tests__/uncommitted-work.test.ts +++ b/src/lib/workspaces/__tests__/uncommitted-work.test.ts @@ -1,7 +1,8 @@ /** * PAN-5979: the closed-issue reaper asks checkWorkspaceUncommittedWork before * it force-removes a workspace folder. Real git repos in a temp directory; the - * project-repo resolver is mocked to a monorepo (no configured members). + * project-repo resolver is mocked to a monorepo by default (one root at the + * workspace, `feature/pan-1` into `main`), and the project lookup to none. */ import { execFileSync } from 'node:child_process'; import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; @@ -9,7 +10,20 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -vi.mock('../../project-repos.js', () => ({ resolveWorkspaceRepoRoots: vi.fn(() => []) })); +const mocks = vi.hoisted(() => ({ + /** Member repo keys of a polyrepo workspace; empty means a monorepo. */ + members: [] as string[], +})); + +vi.mock('../../project-repos.js', () => ({ + resolveWorkspaceRepoRoots: vi.fn((_issueId: string, ws: string) => (mocks.members.length === 0 + ? [{ repoKey: 'pan-1', dir: ws, sourceBranch: 'feature/pan-1', targetBranch: 'main', isPolyrepo: false }] + : mocks.members.map((key) => ({ repoKey: key, dir: join(ws, key), sourceBranch: 'feature/pan-1', targetBranch: 'main', isPolyrepo: true })))), +})); +vi.mock('../../projects.js', () => ({ + resolveProjectFromIssueSync: vi.fn(() => null), + getProjectSync: vi.fn(() => null), +})); import { checkWorkspaceUncommittedWork, findWorkspaceCheckouts, uncommittedWorkPaths } from '../uncommitted-work.js'; @@ -29,13 +43,26 @@ function repo(dir: string): void { git(dir, 'commit', '-q', '-m', 'base'); } +/** A polyrepo wrapper as Overdeck makes it: no remote, one commit of its `.gitignore`. */ +function wrapperRepo(dir: string): void { + mkdirSync(dir, { recursive: true }); + git(dir, 'init', '-q', '-b', 'master'); + writeFileSync(join(dir, '.gitignore'), 'fe/\napi/\n.overdeck/\n'); + git(dir, 'add', '.gitignore'); + git(dir, 'commit', '-q', '-m', 'chore(plan): complete planning'); +} + describe('uncommittedWorkPaths', () => { - it('ignores only pipeline exhaust: the .pan state plane, .husky/_ and untracked .overdeck runtime', () => { + it('ignores only pipeline exhaust: the .pan state plane, .husky/_ and the .overdeck runtime files Overdeck writes', () => { const porcelain = [ ' M .pan/continues/PAN-1.xbrief.json', '?? .pan/test/run-1/result.json', ' M .pan/specs/2026-12-03-PAN-1.xbrief.json', '?? .overdeck/pipeline.jsonl', + '?? .overdeck/feedback/001-review-pass.md', + '?? .overdeck/verification/2026-12-03T12-00-00-000Z-abcd1234.json', + '?? .overdeck/context/codebase/new.md', + '?? .overdeck/surprise.txt', '?? .husky/_/pre-rebase', '?? .pan/drafts/pan-1.md', '?? .pan/notes/idea.md', @@ -49,6 +76,8 @@ describe('uncommittedWorkPaths', () => { ].join('\n'); expect(uncommittedWorkPaths(porcelain)).toEqual([ + '.overdeck/context/codebase/new.md', + '.overdeck/surprise.txt', '.pan/drafts/pan-1.md', '.pan/notes/idea.md', '.overdeck/context/codebase/concerns.md', @@ -68,6 +97,7 @@ describe('checkWorkspaceUncommittedWork', () => { beforeEach(() => { root = mkdtempSync(join(tmpdir(), 'pan-5979-uncommitted-')); + mocks.members = []; }); afterEach(() => { @@ -86,6 +116,7 @@ describe('checkWorkspaceUncommittedWork', () => { }); it('finds polyrepo members and .swarm worktrees, and reports dirt in a member', async () => { + mocks.members = ['fe', 'api']; const ws = join(root, 'ws'); mkdirSync(ws); repo(join(ws, 'fe')); @@ -106,8 +137,9 @@ describe('checkWorkspaceUncommittedWork', () => { }); it('judges each member of a git wrapper on its own, not as an untracked folder of the wrapper', async () => { + mocks.members = ['fe', 'api']; const ws = join(root, 'ws'); - repo(ws); + wrapperRepo(ws); repo(join(ws, 'fe')); repo(join(ws, 'api')); diff --git a/src/lib/workspaces/ignored-work.ts b/src/lib/workspaces/ignored-work.ts new file mode 100644 index 00000000000..eed4e10b974 --- /dev/null +++ b/src/lib/workspaces/ignored-work.ts @@ -0,0 +1,109 @@ +/** + * PAN-5990: gitignored files the closed-issue reaper must not delete. `git + * status` never shows them, but the forced removal of the folder does. + * + * Policy: keep, don't archive. A checkout that holds a known-precious ignored + * file keeps the whole workspace: + * - `.env` and `.env.*` (not `.env.example`); + * - `*.sql`, `*.dump`, `*.sqlite`, `*.db` outside `node_modules/`; + * - anything under a `.tmp/` folder (the mockup convention). + * Files Overdeck generated itself (a rendered `.env`) are passed in and skipped. + * Ordinary build and cache output never blocks. + * + * Bounds: `--directory` collapses each wholly ignored folder into one entry, + * so `node_modules/` is never walked. A collapsed folder that is not build, + * cache or Overdeck output (`backups/`, say) is listed once more on its own, + * without its `node_modules/`. Every git call has a timeout and a buffer cap, + * and too many such folders is itself a reason to keep the workspace. Git does + * not list ignored files inside an untracked folder; such a folder's untracked + * files keep the workspace through `git status` already. + */ +import { execFile } from 'node:child_process'; +import { promisify } from 'node:util'; + +const execFileAsync = promisify(execFile); +const GIT_TIMEOUT_MS = 30_000; +const GIT_MAX_BUFFER = 32 * 1024 * 1024; +/** Collapsed ignored folders listed one level further before the scan gives up. */ +const MAX_FOLDERS_TO_LIST = 50; + +/** Collapsed ignored folders that hold build, cache or Overdeck output, never kept. */ +const NOT_LISTED_FOLDERS = new Set([ + 'node_modules', 'dist', 'build', 'out', 'target', 'coverage', '.nyc_output', + '.vite', '.turbo', '.next', '.nuxt', '.svelte-kit', '.cache', '.parcel-cache', + '.gradle', '.venv', 'venv', '__pycache__', '.pytest_cache', '.mypy_cache', '.ruff_cache', + '.swarm', '.devcontainer', '.overdeck', '.pan', '.claude', +]); +/** The generated git-hooks folder (`isGeneratedGitHookPath`). */ +const HOOKS_FOLDER = '.husky/_/'; + +const PRECIOUS_EXTENSIONS = ['.sql', '.dump', '.sqlite', '.db']; + +/** The `.claude/` folders the workspace sync writes into. */ +export const SYNC_CLAUDE_FOLDERS = ['.claude/skills', '.claude/commands', '.claude/agents'] as const; + +async function listIgnored(dir: string, extra: string[]): Promise { + const { stdout } = await execFileAsync( + 'git', + ['--no-optional-locks', 'ls-files', '--others', '--ignored', '--exclude-standard', '-z', ...extra], + { cwd: dir, encoding: 'utf-8', timeout: GIT_TIMEOUT_MS, maxBuffer: GIT_MAX_BUFFER }, + ); + return stdout.split('\0').filter(Boolean); +} + +function segments(path: string): string[] { + return path.replace(/\\/g, '/').split('/').filter(Boolean); +} + +/** True when an ignored path (file, or folder ending in `/`) is a known-precious one. */ +export function isPreciousIgnoredPath(path: string): boolean { + const parts = segments(path); + if (parts.includes('node_modules')) return false; + const isFolder = path.endsWith('/'); + if (parts.slice(0, isFolder ? parts.length : -1).includes('.tmp')) return true; + if (isFolder) return false; + const name = parts[parts.length - 1] ?? ''; + if (name === '.env' || (name.startsWith('.env.') && name !== '.env.example')) return true; + const lower = name.toLowerCase(); + return PRECIOUS_EXTENSIONS.some((ext) => lower.endsWith(ext) && lower.length > ext.length); +} + +/** + * The known-precious gitignored files in the checkout at `dir` (relative + * paths; a `.tmp/` folder is reported as the folder). `generated` holds paths + * Overdeck wrote itself, which never count. Throws when a listing fails or + * exceeds its bounds. + */ +export async function findPreciousIgnoredFiles(dir: string, generated: ReadonlySet = new Set()): Promise { + const found: string[] = []; + const toList: string[] = []; + for (const entry of await listIgnored(dir, ['--directory', '--no-empty-directory'])) { + if (segments(entry).includes('node_modules')) continue; + if (!entry.endsWith('/')) { + if (isPreciousIgnoredPath(entry) && !generated.has(entry)) found.push(entry); + } else if (isPreciousIgnoredPath(entry)) { + found.push(entry); + } else if (entry !== HOOKS_FOLDER && !NOT_LISTED_FOLDERS.has(segments(entry).at(-1) ?? '')) { + toList.push(entry); + } + } + if (toList.length > MAX_FOLDERS_TO_LIST) { + throw new Error(`${toList.length} ignored folders to inspect, more than ${MAX_FOLDERS_TO_LIST}`); + } + for (const folder of toList) { + for (const path of await listIgnored(dir, ['--', folder, ':(exclude,glob)**/node_modules/**'])) { + if (isPreciousIgnoredPath(path) && !generated.has(path)) found.push(path); + } + } + return found; +} + +/** + * Ignored files in the workspace sync's `.claude/` folders that the sync did + * not write (`written`, from `loadOverdeckWrittenPaths`): an operator's own + * skill, command or agent. Throws when the listing fails. + */ +export async function findUnwrittenSyncFolderFiles(dir: string, written: ReadonlySet): Promise { + const paths = await listIgnored(dir, ['--', ...SYNC_CLAUDE_FOLDERS]); + return paths.filter((path) => !written.has(path)); +} diff --git a/src/lib/workspaces/overdeck-runtime-files.ts b/src/lib/workspaces/overdeck-runtime-files.ts new file mode 100644 index 00000000000..a76987dc0da --- /dev/null +++ b/src/lib/workspaces/overdeck-runtime-files.ts @@ -0,0 +1,74 @@ +/** + * PAN-5990: the exact files Overdeck writes under a workspace's `.overdeck/` + * runtime directory, for the closed-issue reaper. The reaper force-removes the + * folder, so only names a known writer produces count as runtime; any other + * untracked file under `.overdeck/` (a new file under the tracked + * `.overdeck/context/`, say) counts as work and keeps the workspace. + * + * The `pan done` and spawn gates keep the blanket `.overdeck/` prefix + * (`isOverdeckWorkspaceRuntimePath`): there the file stays on disk. + * + * Writers, as of PAN-5990: + * - continue.json, spec.vbrief.json: planning (`plan-finalize.ts`, `uat-fixtures/seed.ts`, the plan role) + * - pending-promotion.json: `plan-finalize.ts` + * - setup-incomplete: `workspace-manager/setup-marker.ts` + * - context.md, INFERENCE.md: `pan-dir/context.ts`, `planning/spawn-planning-session.ts` + * - pipeline.jsonl: `cloister/pipeline-journal.ts` + * - verification-latest.json, verification/: `cloister/verification-artifact.ts` + * - test-removal-waiver.json: `cloister/test-skip-waiver.ts` + * - sast-latest.json: `cloister/sast-run.ts` + * - stack-pin.json: `workspace/stack-idle-config.ts`; stack-reclaim.lock: `workspace/stack-restore.ts` + * - deft-install.json, deft-lift/, deft-run-summary.jsonl: `deft/` (the summary through `DEFT_RUN_SUMMARY_PATH`) + * - plan-artifact-backups/: `overdeck/plan-artifact-commit.ts` + * - config.yaml, projects.yaml, settings.json: `workspace-manager/migration.ts` (copies of `~/.overdeck`) + * - feedback/NNN--.md: `pan-dir/feedback.ts` + * Committed content (`context/`, `memory/`) is never listed here. + */ + +const RUNTIME_FILES = new Set([ + 'continue.json', + 'spec.vbrief.json', + 'pending-promotion.json', + 'setup-incomplete', + 'context.md', + 'INFERENCE.md', + 'pipeline.jsonl', + 'verification-latest.json', + 'test-removal-waiver.json', + 'sast-latest.json', + 'stack-pin.json', + 'stack-reclaim.lock', + 'deft-install.json', + 'deft-run-summary.jsonl', + 'config.yaml', + 'projects.yaml', + 'settings.json', +]); + +/** Temp files the atomic writers above leave behind when interrupted. */ +const RUNTIME_TEMP_FILES = [ + /^pending-promotion\.json\.tmp$/, + /^context\.md\.tmp$/, + /^test-removal-waiver\.json\.tmp$/, + /^deft-install\.json\.\d+\.tmp$/, +]; + +/** Runtime directories, each with the names its writer produces inside it. */ +const RUNTIME_DIR_ENTRIES: Record = { + feedback: /^\d{3}-[^/]+\.md$/, + verification: /^[^/]+\.json$/, + 'deft-lift': /^[0-9a-f]{16}\.(current|base|other)$/, + // Plan artifacts moved aside under a timestamp, plus the folder's own `*` ignore file. + 'plan-artifact-backups': /^(\.gitignore|[^/]+\/.+)$/, +}; + +/** True when `relativePath` (from the checkout root) is a file Overdeck writes under `.overdeck/`. */ +export function isOverdeckRuntimeFile(relativePath: string): boolean { + const normalized = relativePath.trim().replace(/\\/g, '/'); + if (!normalized.startsWith('.overdeck/')) return false; + const rest = normalized.slice('.overdeck/'.length); + const slash = rest.indexOf('/'); + if (slash === -1) return RUNTIME_FILES.has(rest) || RUNTIME_TEMP_FILES.some((pattern) => pattern.test(rest)); + const pattern = RUNTIME_DIR_ENTRIES[rest.slice(0, slash)]; + return pattern !== undefined && pattern.test(rest.slice(slash + 1)); +} diff --git a/src/lib/workspaces/overdeck-written-paths.ts b/src/lib/workspaces/overdeck-written-paths.ts new file mode 100644 index 00000000000..8408d286964 --- /dev/null +++ b/src/lib/workspaces/overdeck-written-paths.ts @@ -0,0 +1,149 @@ +/** + * PAN-5990: the exact files Overdeck wrote into a workspace root when it set + * the workspace up, for the closed-issue reaper. They are regenerable, so an + * untracked (or gitignored) copy is not work; every other file under the same + * folders is. An operator's own skill in `.claude/skills/` is therefore kept. + * + * The sources, each the list the writer itself uses: + * - `.claude/.overdeck-manifest.json`: every file `mergeSkillsIntoWorkspace` / + * `mergePanSkillsIntoWorkspace` / `applyProjectTemplateOverlay` placed + * (`skills-merge.ts`). A file whose hash no longer matches was edited, and + * counts as work. + * - `OVERDECK_WORKSPACE_SYNC_EXCLUDE_PATTERNS`: the exact `.claude/` files the + * sync writes (settings, `mcp.json`, the manifest, the caveman variant). + * - The project's `workspace.agent` template: the rendered `*.template` + * targets (`.mcp.json`, …) and every file under its `copy_dirs` + * (`create.ts`, `copyProjectTemplateDirs`). + * - `/.env` when `workspace.env.template` renders it (`create.ts`). + * - `.hume-config` when it holds exactly the two lines `create.ts` writes. The + * content, not the config, decides: a project may drop `hume` later. + */ +import { createHash } from 'node:crypto'; +import type { Dirent } from 'node:fs'; +import { existsSync } from 'node:fs'; +import { readdir, readFile } from 'node:fs/promises'; +import { join } from 'node:path'; + +import { isHarnessNativeTarget } from '../context-layers/native-instructions.js'; +import { getProjectSync, resolveProjectFromIssueSync } from '../projects.js'; +import { OVERDECK_WORKSPACE_SYNC_EXCLUDE_PATTERNS } from '../workspace-sync-paths.js'; + +const MANIFEST_PATH = '.claude/.overdeck-manifest.json'; +const HUME_CONFIG_PATH = '.hume-config'; +const GENERATED_HUME_CONFIG = /^HUME_CONFIG_ID=([^\s=]+)\nVITE_HUME_CONFIG_ID=\1\n$/; +/** Bound on the template walk; a project template is a handful of files. */ +const MAX_TEMPLATE_FILES = 5_000; +const MAX_TEMPLATE_DEPTH = 8; + +/** The sync's exact `.claude/` files: the exclude patterns that name one file. */ +const SYNC_FILES = OVERDECK_WORKSPACE_SYNC_EXCLUDE_PATTERNS + .filter((pattern) => !pattern.endsWith('/') && !pattern.includes('*')) + .map((pattern) => pattern.replace(/^\//, '')); + +async function sha256(path: string): Promise { + try { + return `sha256:${createHash('sha256').update(await readFile(path)).digest('hex')}`; + } catch { + return null; + } +} + +/** Manifest entries whose file on disk still has the hash the sync recorded. */ +async function unmodifiedManifestFiles(workspacePath: string): Promise { + let installed: Record; + try { + const raw = JSON.parse(await readFile(join(workspacePath, MANIFEST_PATH), 'utf-8')) as { + managed_by?: unknown; installed?: unknown; + }; + if (raw.managed_by !== 'overdeck' || !raw.installed || typeof raw.installed !== 'object') return []; + installed = raw.installed as Record; + } catch { + return []; + } + const files: string[] = []; + for (const [key, entry] of Object.entries(installed)) { + if (key.includes('..') || typeof entry?.hash !== 'string') continue; + const path = `.claude/${key}`; + if (await sha256(join(workspacePath, path)) === entry.hash) files.push(path); + } + return files; +} + +/** Every file under `dir`, relative to it; throws past the bounds. */ +async function listFiles(dir: string): Promise { + const files: string[] = []; + const walk = async (current: string, prefix: string, depth: number): Promise => { + if (depth > MAX_TEMPLATE_DEPTH) throw new Error(`template folder ${dir} is nested too deeply`); + let entries: Dirent[]; + try { + entries = await readdir(current, { withFileTypes: true }); + } catch { + return; + } + for (const entry of entries) { + const rel = prefix ? `${prefix}/${entry.name}` : entry.name; + if (entry.isDirectory()) await walk(join(current, entry.name), rel, depth + 1); + else if (entry.isFile()) files.push(rel); + if (files.length > MAX_TEMPLATE_FILES) throw new Error(`template folder ${dir} holds too many files`); + } + }; + await walk(dir, '', 0); + return files; +} + +/** What the project's agent template wrote into the workspace root. */ +async function projectTemplateFiles(issueId: string): Promise { + const project = resolveProjectFromIssueSync(issueId); + const config = project ? getProjectSync(project.projectKey) : null; + const workspace = config?.workspace; + if (!project || !workspace) return []; + + const files: string[] = []; + if (workspace.env?.template) files.push('.env'); + + const agent = workspace.agent; + if (!agent?.template_dir) return files; + const templateDir = join(project.projectPath, agent.template_dir); + if (!existsSync(templateDir)) return files; + + const templates = agent.templates + ?? (await readdir(templateDir).catch(() => [] as string[])) + .filter((source) => source.endsWith('.template')) + .map((source) => ({ source, target: source.slice(0, -'.template'.length) })); + for (const { target } of templates) { + if (!isHarnessNativeTarget(target)) files.push(target.replace(/^\.\//, '')); + } + for (const dir of agent.copy_dirs ?? agent.symlinks ?? []) { + if (isHarnessNativeTarget(dir)) continue; + const prefix = dir.replace(/^\.\//, '').replace(/\/+$/, ''); + for (const rel of await listFiles(join(templateDir, prefix))) { + const path = `${prefix}/${rel}`; + if (!isHarnessNativeTarget(path)) files.push(path); + } + } + return files; +} + +/** `.hume-config` as `create.ts` writes it, or nothing. */ +async function generatedHumeConfig(workspacePath: string): Promise { + try { + const content = await readFile(join(workspacePath, HUME_CONFIG_PATH), 'utf-8'); + return GENERATED_HUME_CONFIG.test(content) ? [HUME_CONFIG_PATH] : []; + } catch { + return []; + } +} + +/** + * The paths (relative to the workspace root, `/`-separated) Overdeck wrote + * there and that are still as written. Throws when a source cannot be read + * within its bounds; the caller then keeps the workspace. + */ +export async function loadOverdeckWrittenPaths(workspacePath: string, issueId: string): Promise> { + return new Set([ + ...SYNC_FILES, + ...await unmodifiedManifestFiles(workspacePath), + ...await projectTemplateFiles(issueId), + ...await generatedHumeConfig(workspacePath), + ]); +} diff --git a/src/lib/workspaces/uncommitted-work.ts b/src/lib/workspaces/uncommitted-work.ts index 977bc492806..5de5b595104 100644 --- a/src/lib/workspaces/uncommitted-work.ts +++ b/src/lib/workspaces/uncommitted-work.ts @@ -13,27 +13,43 @@ * - the `.pan/` state plane (`isStatePlanePath`: continues, specs, test, * review, feedback, `.tasks/`), the pipeline's own records; * - the generated `.husky/_/` hooks; - * - untracked files under `.overdeck/` (machine-local runtime). A change to a - * tracked `.overdeck/` file, such as `.overdeck/context/`, is work. + * - untracked files under `.overdeck/` with the exact names Overdeck writes + * there (`isOverdeckRuntimeFile`, PAN-5990). Any other file under + * `.overdeck/`, and a change to a tracked one such as `.overdeck/context/`, + * is work; + * - in the workspace root, untracked files Overdeck wrote there as they were + * written (`loadOverdeckWrittenPaths`: synced skills, agents and commands, + * the rendered `.mcp.json`, …, PAN-5990). * Everything else under `.pan/` (drafts, notes, …) is work, and so are the * bookkeeping folders agents read as instructions (`.pan/skills/`, * `.pan/skill-overrides/`, `.pan/context/`, `.overdeck/memory/`, PAN-5814). + * + * PAN-5990 adds what `git status` cannot see, each also a reason to keep: + * - committed work the merged branch does not hold, and a rebase, merge, + * cherry-pick, revert or bisect in progress (`unheld-commits.ts`); + * - known-precious gitignored files: `.env*`, database dumps, `.tmp/` + * (`ignored-work.ts`); + * - gitignored files in the root's synced `.claude/skills|commands|agents/` + * that the sync did not write. */ import { execFile } from 'node:child_process'; import type { Dirent } from 'node:fs'; import { existsSync, readdirSync } from 'node:fs'; -import { join } from 'node:path'; +import { join, sep } from 'node:path'; import { promisify } from 'node:util'; import { isReviewRequiredBookkeepingPath } from '../cloister/bookkeeping-paths.js'; -import { resolveWorkspaceRepoRoots } from '../project-repos.js'; +import { resolveWorkspaceRepoRoots, type WorkspaceRepoRoot } from '../project-repos.js'; import { isGeneratedGitHookPath, - isOverdeckWorkspaceRuntimePath, isStatePlanePath, parsePorcelainStatusEntries, type PorcelainStatusEntry, } from '../state-plane.js'; +import { findPreciousIgnoredFiles, findUnwrittenSyncFolderFiles } from './ignored-work.js'; +import { isOverdeckRuntimeFile } from './overdeck-runtime-files.js'; +import { loadOverdeckWrittenPaths } from './overdeck-written-paths.js'; +import { findUnheldCommitWork, type CheckoutRole } from './unheld-commits.js'; const execFileAsync = promisify(execFile); @@ -50,17 +66,26 @@ export function isPipelineExhaustEntry(entry: PorcelainStatusEntry): boolean { const { status, path } = entry; if (isReviewRequiredBookkeepingPath(path)) return false; if (isStatePlanePath(path) || isGeneratedGitHookPath(path)) return true; - const normalized = path.replace(/\\/g, '/'); - return status === '??' && normalized.startsWith('.overdeck/') && isOverdeckWorkspaceRuntimePath(normalized); + return status === '??' && isOverdeckRuntimeFile(path); } -/** The work paths in `git status --porcelain --untracked-files=all` output (empty when clean). */ -export function uncommittedWorkPaths(porcelain: string): string[] { +/** + * The work paths in `git status --porcelain --untracked-files=all` output + * (empty when clean). `written` holds untracked paths Overdeck wrote, as they + * were written; a tracked file is work whatever the set says. + */ +export function uncommittedWorkPaths(porcelain: string, written: ReadonlySet = new Set()): string[] { return parsePorcelainStatusEntries(porcelain) .filter((entry) => !isPipelineExhaustEntry(entry)) + .filter((entry) => !(entry.status === '??' && written.has(entry.path.replace(/\\/g, '/')))) .map((entry) => entry.path); } +function describePaths(paths: string[]): string { + const shown = paths.slice(0, 5).join(', '); + return paths.length > 5 ? `${shown} and ${paths.length - 5} more` : shown; +} + function hasGit(dir: string): boolean { return existsSync(join(dir, '.git')); } @@ -113,34 +138,75 @@ export async function checkWorkspaceUncommittedWork( if (!existsSync(workspacePath)) return { clean: true, checked: [] }; let checkouts: string[]; + let roots: WorkspaceRepoRoot[]; try { checkouts = findWorkspaceCheckouts(workspacePath); + roots = resolveWorkspaceRepoRoots(issueId, workspacePath); // Configured member repos laid out under a path name (PAN-3254) are found // by the resolver even when the scan above missed them. - for (const root of resolveWorkspaceRepoRoots(issueId, workspacePath)) { + for (const root of roots) { if (!root.degradedPolyrepo && hasGit(root.dir) && !checkouts.includes(root.dir)) checkouts.push(root.dir); } } catch (err) { - return { clean: false, reason: `cannot list the checkouts in ${workspacePath}: ${err instanceof Error ? err.message : String(err)}` }; + return { clean: false, reason: `cannot list the checkouts in ${workspacePath}: ${errorLine(err)}` }; + } + + let written: Set; + try { + written = await loadOverdeckWrittenPaths(workspacePath, issueId); + } catch (err) { + return { clean: false, reason: `cannot list the files Overdeck wrote in ${workspacePath}: ${errorLine(err)}` }; } for (const dir of checkouts) { + const isRoot = dir === workspacePath; let porcelain: string; try { porcelain = await readStatus(dir); } catch (err) { - const message = err instanceof Error ? err.message.split('\n')[0] : String(err); - return { clean: false, reason: `cannot read git status in ${dir}: ${message}` }; + return { clean: false, reason: `cannot read git status in ${dir}: ${errorLine(err)}` }; } // A wrapper repo that does not ignore its member folders lists them as // untracked (`?? fe/`); each member is checked on its own instead. - const paths = uncommittedWorkPaths(porcelain) + const paths = uncommittedWorkPaths(porcelain, isRoot ? written : undefined) .filter((path) => !checkouts.includes(join(dir, path.replace(/\/+$/, '')))); if (paths.length > 0) { - const shown = paths.slice(0, 5).join(', '); - const more = paths.length > 5 ? ` and ${paths.length - 5} more` : ''; - return { clean: false, reason: `uncommitted changes in ${dir}: ${shown}${more}` }; + return { clean: false, reason: `uncommitted changes in ${dir}: ${describePaths(paths)}` }; + } + + const unheld = await findUnheldCommitWork(dir, checkoutRole(dir, workspacePath, roots)); + if (unheld) return { clean: false, reason: unheld }; + + try { + const precious = await findPreciousIgnoredFiles(dir, isRoot ? written : undefined); + if (precious.length > 0) { + return { clean: false, reason: `gitignored files the reap would delete in ${dir}: ${describePaths(precious)}` }; + } + const unsynced = isRoot ? await findUnwrittenSyncFolderFiles(dir, written) : []; + if (unsynced.length > 0) { + return { clean: false, reason: `files pan sync did not write in ${dir}: ${describePaths(unsynced)}` }; + } + } catch (err) { + return { clean: false, reason: `cannot list the gitignored files in ${dir}: ${errorLine(err)}` }; } } return { clean: true, checked: checkouts }; } + +function errorLine(err: unknown): string { + return err instanceof Error ? err.message.split('\n')[0] : String(err); +} + +/** + * Which branches hold a checkout's commits: those of the member repo it is, + * or whose `.swarm/` worktree it is (the nearest configured root above it). + * The root of a polyrepo workspace is the wrapper repo. Null when unknown. + */ +function checkoutRole(dir: string, workspacePath: string, roots: WorkspaceRepoRoot[]): CheckoutRole | null { + const polyrepo = roots.some((root) => root.isPolyrepo || root.degradedPolyrepo); + if (dir === workspacePath && polyrepo) return { kind: 'wrapper' }; + const owner = roots + .filter((root) => !root.degradedPolyrepo && (dir === root.dir || dir.startsWith(`${root.dir}${sep}`))) + .sort((a, b) => b.dir.length - a.dir.length)[0]; + return owner ? { kind: 'member', branches: { targetBranch: owner.targetBranch, sourceBranch: owner.sourceBranch } } : null; +} diff --git a/src/lib/workspaces/unheld-commits.ts b/src/lib/workspaces/unheld-commits.ts new file mode 100644 index 00000000000..d91251cc83a --- /dev/null +++ b/src/lib/workspaces/unheld-commits.ts @@ -0,0 +1,132 @@ +/** + * PAN-5990: committed work the merged branch does not hold. `git status` is + * clean for a commit on a detached HEAD, on another branch, or in a rebase, + * cherry-pick or `git am` paused without conflicts, yet the reaper's forced + * worktree removal (and its `git branch -D`) loses it. Each check returns why + * the checkout must be kept, or null. + * + * - An operation in progress (`rebase-merge/`, `rebase-apply/`, `MERGE_HEAD`, + * `CHERRY_PICK_HEAD`, `REVERT_HEAD`, `BISECT_LOG` in the worktree's own git + * dir) always keeps it. + * - A member checkout keeps it when `git rev-list HEAD --not + * ` is non-empty: the merge proof covers the target and the + * feature branch tips (local and `origin/`), nothing else. + * - The polyrepo wrapper has no remote, target or feature branch: Overdeck + * commits its `.gitignore` and pipeline records there. Any of its commits + * that touches another path keeps it. + * + * Fail closed: a git call that fails or times out is a reason to keep. + */ +import { execFile } from 'node:child_process'; +import { existsSync } from 'node:fs'; +import { join } from 'node:path'; +import { promisify } from 'node:util'; + +import { isStatePlanePath } from '../state-plane.js'; + +const execFileAsync = promisify(execFile); +const GIT_TIMEOUT_MS = 30_000; +const GIT_MAX_BUFFER = 32 * 1024 * 1024; +/** How many unheld commits to name in a reason. */ +const SHOWN_COMMITS = 5; + +const IN_PROGRESS_MARKERS: Array<[string, string]> = [ + ['rebase-merge', 'a rebase'], + ['rebase-apply', 'a rebase or git am'], + ['MERGE_HEAD', 'a merge'], + ['CHERRY_PICK_HEAD', 'a cherry-pick'], + ['REVERT_HEAD', 'a revert'], + ['BISECT_LOG', 'a bisect'], +]; + +/** Which branches hold a checkout's commits once the reap has run. */ +export interface CheckoutBranches { + /** The branch the work merged into (`main`). */ + targetBranch: string; + /** The branch whose merge the reaper proved (`feature/`). */ + sourceBranch: string; +} + +export type CheckoutRole = + | { kind: 'member'; branches: CheckoutBranches } + | { kind: 'wrapper' }; + +async function git(dir: string, args: string[]): Promise { + const { stdout } = await execFileAsync('git', ['--no-optional-locks', ...args], { + cwd: dir, encoding: 'utf-8', timeout: GIT_TIMEOUT_MS, maxBuffer: GIT_MAX_BUFFER, + }); + return stdout; +} + +function lines(stdout: string): string[] { + return stdout.split('\n').map((line) => line.trim()).filter(Boolean); +} + +function firstLine(err: unknown): string { + return err instanceof Error ? err.message.split('\n')[0] : String(err); +} + +function listCommits(commits: string[]): string { + const shown = commits.slice(0, SHOWN_COMMITS).map((sha) => sha.slice(0, 12)).join(', '); + return commits.length > SHOWN_COMMITS ? `${shown} and ${commits.length - SHOWN_COMMITS} more` : shown; +} + +/** The refs that hold a member checkout's commits, of those that exist. */ +async function holdingRefs(dir: string, branches: CheckoutBranches): Promise<{ target: string[]; source: string[] }> { + const existing = new Set(lines(await git(dir, [ + 'for-each-ref', '--format=%(refname)', + `refs/remotes/origin/${branches.targetBranch}`, `refs/heads/${branches.targetBranch}`, + `refs/heads/${branches.sourceBranch}`, `refs/remotes/origin/${branches.sourceBranch}`, + ]))); + const pick = (branch: string) => [`refs/remotes/origin/${branch}`, `refs/heads/${branch}`].filter((ref) => existing.has(ref)); + return { target: pick(branches.targetBranch), source: pick(branches.sourceBranch) }; +} + +async function memberUnheldReason(dir: string, branches: CheckoutBranches): Promise { + const refs = await holdingRefs(dir, branches); + if (refs.target.length === 0) { + return `cannot tell which commits in ${dir} are kept: no ${branches.targetBranch} or origin/${branches.targetBranch} ref`; + } + const commits = lines(await git(dir, ['rev-list', 'HEAD', '--not', ...refs.target, ...refs.source])); + if (commits.length === 0) return null; + let head = 'HEAD'; + try { + head = `branch ${(await git(dir, ['symbolic-ref', '--short', '-q', 'HEAD'])).trim()}`; + } catch { + head = 'detached HEAD'; + } + return `${head} in ${dir} holds ${commits.length} commit(s) on neither ${branches.targetBranch} nor ${branches.sourceBranch}: ${listCommits(commits)}`; +} + +async function wrapperUnheldReason(dir: string): Promise { + // `--format=%x00%H` marks each commit; the paths it touches follow it. + const log = await git(dir, ['log', '--no-renames', '--format=%x00%H', '--name-only', 'HEAD', '--not', '--remotes']); + const commits: string[] = []; + for (const block of log.split('\0').filter((entry) => entry.trim())) { + const [sha, ...paths] = lines(block); + if (paths.some((path) => path !== '.gitignore' && !isStatePlanePath(path))) commits.push(sha); + } + if (commits.length === 0) return null; + return `the workspace repo ${dir} holds ${commits.length} local commit(s) beyond its .gitignore and pipeline records: ${listCommits(commits)}`; +} + +/** Why the checkout at `dir` holds committed work the reap would lose, or null. */ +export async function findUnheldCommitWork(dir: string, role: CheckoutRole | null): Promise { + try { + const gitDir = (await git(dir, ['rev-parse', '--absolute-git-dir'])).trim(); + for (const [marker, operation] of IN_PROGRESS_MARKERS) { + if (existsSync(join(gitDir, marker))) return `${operation} is in progress in ${dir} (${marker})`; + } + try { + await git(dir, ['rev-parse', '--verify', '--quiet', 'HEAD^{commit}']); + } catch (err) { + // Exit 1 without a timeout: HEAD has no commit yet, so nothing is lost. + if ((err as { code?: unknown; killed?: unknown }).code === 1 && !(err as { killed?: unknown }).killed) return null; + throw err; + } + if (!role) return `cannot tell which branch holds the commits in ${dir}`; + return role.kind === 'wrapper' ? await wrapperUnheldReason(dir) : await memberUnheldReason(dir, role.branches); + } catch (err) { + return `cannot check the commits in ${dir}: ${firstLine(err)}`; + } +} diff --git a/tests/unit/lib/forge-merged-artifact.test.ts b/tests/unit/lib/forge-merged-artifact.test.ts index fbde419987f..17f9326c4cc 100644 --- a/tests/unit/lib/forge-merged-artifact.test.ts +++ b/tests/unit/lib/forge-merged-artifact.test.ts @@ -272,7 +272,72 @@ describe('findMergedArtifact', () => { url: 'https://gitlab.com/org/repo/-/merge_requests/70', id: '70', headSha: currentHead, + baseRefName: 'main', + }); + }); + + it('reports the merged GitLab MR\'s base, merge commit and fork flag (PAN-5990)', async () => { + execMock.mockResolvedValueOnce({ + stdout: JSON.stringify([{ + iid: 70, web_url: 'https://gitlab.com/org/repo/-/merge_requests/70', state: 'merged', + source_branch: 'feature/min-857', target_branch: 'main', sha: currentHead, + merge_commit_sha: 'merge-sha', squash_commit_sha: 'squash-sha', + source_project_id: 7, target_project_id: 7, + }]), + stderr: '', + }); + + const result = await getForgeAdapter('gitlab').findMergedArtifact({ + sourceBranch: 'feature/min-857', targetBranch: 'main', repository: 'org/repo', cwd: '/tmp/repo', + }); + + expect(result).toMatchObject({ baseRefName: 'main', mergeCommitOid: 'merge-sha', isCrossRepository: false }); + }); + + it('takes the squash commit as the merge commit of a fast-forward squash MR (PAN-5990)', async () => { + execMock.mockResolvedValueOnce({ + stdout: JSON.stringify([{ + iid: 70, state: 'merged', source_branch: 'feature/min-857', target_branch: 'main', sha: currentHead, + merge_commit_sha: null, squash_commit_sha: 'squash-sha', source_project_id: 7, target_project_id: 7, + }]), + stderr: '', + }); + + const result = await getForgeAdapter('gitlab').findMergedArtifact({ sourceBranch: 'feature/min-857', cwd: '/tmp/repo' }); + + expect(result?.mergeCommitOid).toBe('squash-sha'); + }); + + it('skips a listed merged MR from a fork, as with GitHub PRs (PAN-5990)', async () => { + execMock.mockResolvedValueOnce({ + stdout: JSON.stringify([ + { + iid: 72, state: 'merged', source_branch: 'feature/min-857', target_branch: 'main', sha: 'fork-head', + merge_commit_sha: 'fork-merge', source_project_id: 99, target_project_id: 7, + }, + { + iid: 70, state: 'merged', source_branch: 'feature/min-857', target_branch: 'main', sha: currentHead, + merge_commit_sha: 'merge-sha', source_project_id: 7, target_project_id: 7, + }, + ]), + stderr: '', + }); + + const result = await getForgeAdapter('gitlab').findMergedArtifact({ sourceBranch: 'feature/min-857', cwd: '/tmp/repo' }); + + expect(result).toMatchObject({ id: '70', headSha: currentHead, isCrossRepository: false }); + }); + + it('reports an MR without project ids as not saying whether it is a fork (PAN-5990)', async () => { + execMock.mockResolvedValueOnce({ + stdout: JSON.stringify([{ iid: 70, state: 'merged', source_branch: 'feature/min-857', target_branch: 'main', sha: currentHead }]), + stderr: '', }); + + const result = await getForgeAdapter('gitlab').findMergedArtifact({ sourceBranch: 'feature/min-857', cwd: '/tmp/repo' }); + + expect(result?.isCrossRepository).toBeUndefined(); + expect(result?.mergeCommitOid).toBeUndefined(); }); it('does not accept an old merged GitLab MR when the current cycle is still open', async () => { diff --git a/tests/unit/lib/lifecycle/verify-merged-gitlab-mr.test.ts b/tests/unit/lib/lifecycle/verify-merged-gitlab-mr.test.ts new file mode 100644 index 00000000000..53c5babbbe3 --- /dev/null +++ b/tests/unit/lib/lifecycle/verify-merged-gitlab-mr.test.ts @@ -0,0 +1,145 @@ +/** + * PAN-5990: GitLab parity with PAN-5979. In the reaper's `requireBranchCovered` + * mode a merged GitLab MR proves the merge only when it comes from the same + * project, was merged into the target, and its merge commit is on the target. + * A missing fact is a refusal. Outside that mode the MR path is unchanged. + * + * The repo, its bare origin and the squash merge are real git in a temp + * directory. The forge adapter, the issue-level PR lookup and the repo + * resolver are mocked. + */ +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, beforeEach, describe, expect, it, vi } from 'vitest'; + +const mocks = vi.hoisted(() => ({ + repos: [] as unknown[], + gitlabArtifact: null as null | Record, +})); + +vi.mock('../../../../src/lib/forge.js', async (importOriginal) => ({ + ...(await importOriginal()), + getForgeAdapter: vi.fn((forge: string) => ({ + forge, + findMergedArtifact: async () => (forge === 'gitlab' ? mocks.gitlabArtifact : null), + })), +})); +// A Linear-tracked issue: no issue-level GitHub PR. +vi.mock('../../../../src/lib/overdeck/pull-requests.js', async (importOriginal) => ({ + ...(await importOriginal()), + fetchIssuePullRequest: vi.fn(async (issueId: string) => ({ issueId, pr: null })), +})); +vi.mock('../../../../src/lib/project-repos.js', async (importOriginal) => ({ + ...(await importOriginal()), + resolveProjectReposForIssue: vi.fn(() => mocks.repos), +})); + +import { verifyBranchMergedImpl } from '../../../../src/lib/lifecycle/verify-merged.js'; + +const ISSUE = 'ZZQ-90'; +const BRANCH = 'feature/zzq-90'; + +function git(cwd: string, ...args: string[]): string { + return execFileSync('git', ['-c', 'user.name=test', '-c', 'user.email=test@example.invalid', '-c', 'commit.gpgsign=false', ...args], { + cwd, + encoding: 'utf-8', + stdio: ['ignore', 'pipe', 'ignore'], + }).trim(); +} + +function commitFile(cwd: string, file: string, content: string, message: string): void { + writeFileSync(join(cwd, file), content); + git(cwd, 'add', file); + git(cwd, 'commit', '-q', '-m', message); +} + +describe('the GitLab merged-MR proof in requireBranchCovered mode (PAN-5990)', () => { + let root: string; + let apiPath: string; + let mrHead: string; + let squashCommit: string; + let strayCommit: string; + + beforeEach(() => { + vi.clearAllMocks(); + root = mkdtempSync(join(tmpdir(), 'pan-5990-gitlab-mr-')); + const origin = join(root, 'api-origin.git'); + git(root, 'init', '-q', '--bare', '-b', 'main', origin); + + apiPath = join(root, 'project', 'api'); + mkdirSync(apiPath, { recursive: true }); + git(apiPath, 'init', '-q', '-b', 'main'); + commitFile(apiPath, 'README.md', 'base\n', 'base'); + git(apiPath, 'remote', 'add', 'origin', origin); + git(apiPath, 'push', '-q', 'origin', 'main'); + + // The MR head pushed, then squash-merged into main. + git(apiPath, 'checkout', '-q', '-b', BRANCH); + commitFile(apiPath, 'api.ts', 'work\n', 'api work'); + mrHead = git(apiPath, 'rev-parse', 'HEAD'); + git(apiPath, 'push', '-q', 'origin', BRANCH); + git(apiPath, 'checkout', '-q', 'main'); + git(apiPath, 'merge', '-q', '--squash', BRANCH); + git(apiPath, 'commit', '-q', '-m', 'api work (!12)'); + git(apiPath, 'push', '-q', 'origin', 'main'); + squashCommit = git(apiPath, 'rev-parse', 'HEAD'); + // A commit that is not on the target, to stand in for a merge commit elsewhere. + git(apiPath, 'checkout', '-q', '-b', 'elsewhere'); + commitFile(apiPath, 'other.txt', 'other\n', 'merged elsewhere'); + strayCommit = git(apiPath, 'rev-parse', 'HEAD'); + git(apiPath, 'checkout', '-q', 'main'); + + mocks.repos = [ + { projectKey: 'zzq', projectPath: join(root, 'project'), repoKey: 'api', repoPath: apiPath, forge: 'gitlab', sourceBranch: BRANCH, targetBranch: 'main', mergeOrder: 0, required: true }, + ]; + mocks.gitlabArtifact = { + forge: 'gitlab', created: false, url: 'https://gitlab.com/acme/api/-/merge_requests/12', id: '12', + headSha: mrHead, baseRefName: 'main', mergeCommitOid: squashCommit, isCrossRepository: false, + }; + }); + + afterEach(() => { + rmSync(root, { recursive: true, force: true }); + }); + + it('accepts a same-project MR merged into the target whose merge commit is on the target', async () => { + const result = await verifyBranchMergedImpl({ issueId: ISSUE, projectPath: join(root, 'project') }, { requireBranchCovered: true }); + + expect(result.error).toBeUndefined(); + expect(result.success).toBe(true); + expect(result.details).toEqual(expect.arrayContaining([expect.stringContaining('MR !12 is merged')])); + }); + + it.each([ + ['comes from a fork', { isCrossRepository: true }, 'MR !12 comes from another repository (a fork)'], + ['does not say whether it is a fork', { isCrossRepository: undefined }, 'MR !12 does not say whether it comes from another repository'], + ['was merged into another branch', { baseRefName: 'develop' }, 'MR !12 was merged into develop, not main'], + ['has no merge commit', { mergeCommitOid: undefined }, 'MR !12 has no merge commit'], + ])('refuses when the merged MR %s', async (_label, patch, reason) => { + mocks.gitlabArtifact = { ...mocks.gitlabArtifact!, ...patch }; + + const result = await verifyBranchMergedImpl({ issueId: ISSUE, projectPath: join(root, 'project') }, { requireBranchCovered: true }); + + expect(result.success).toBe(false); + expect(result.error).toContain(reason); + }); + + it('refuses when the merged MR\'s merge commit is not on the target', async () => { + mocks.gitlabArtifact = { ...mocks.gitlabArtifact!, mergeCommitOid: strayCommit }; + + const result = await verifyBranchMergedImpl({ issueId: ISSUE, projectPath: join(root, 'project') }, { requireBranchCovered: true }); + + expect(result.success).toBe(false); + expect(result.error).toContain(`the merge commit ${strayCommit} of MR !12 is not on origin/main`); + }); + + it('keeps the close-out\'s head-match path when the reaper\'s mode is off', async () => { + mocks.gitlabArtifact = { ...mocks.gitlabArtifact!, isCrossRepository: undefined, mergeCommitOid: undefined }; + + const result = await verifyBranchMergedImpl({ issueId: ISSUE, projectPath: join(root, 'project') }); + + expect(result.success).toBe(true); + }); +}); From d69c5afd87857875b35fdc442fb0cfa8e24e9169 Mon Sep 17 00:00:00 2001 From: "overdeck-agent[bot]" <4205044+overdeck-agent[bot]@users.noreply.github.com> Date: Thu, 3 Dec 2026 22:11:25 -0500 Subject: [PATCH 2/2] fix(cloister): reaper judges nested clones, stash and workspace.md (PAN-5990) A checkout inherits a member's branches only when it shares that member's repository; local refs, other branches and stash entries count only when the repository lives outside the workspace folder. The wrapper check covers every branch and stash entry. context/workspace.md and the pan sync mirror of a checkout's own skills/ are recognised as written. Co-Authored-By: Claude Opus 5.5 Overdeck-Conversation: conv-20261204-38bc --- changelog.d/pan-5990.md | 2 +- .../__tests__/reap-work-checks.test.ts | 68 +++++++++++++++++++ .../__tests__/uncommitted-work.test.ts | 20 ++++-- src/lib/workspaces/overdeck-runtime-files.ts | 5 +- src/lib/workspaces/overdeck-written-paths.ts | 26 +++++-- src/lib/workspaces/uncommitted-work.ts | 11 +-- src/lib/workspaces/unheld-commits.ts | 61 ++++++++++++----- 7 files changed, 162 insertions(+), 31 deletions(-) diff --git a/changelog.d/pan-5990.md b/changelog.d/pan-5990.md index 3c227f1245e..848e2eb702e 100644 --- a/changelog.d/pan-5990.md +++ b/changelog.d/pan-5990.md @@ -1,5 +1,5 @@ #### Fixed -- **Closed-issue cleanup keeps work that `git status` cannot see:** before it removes a merged issue's workspace, cleanup now also keeps the folder, both branches and the stack's volumes when a checkout holds a commit that neither the target branch nor the merged feature branch holds (on a detached HEAD, another branch, or a `.swarm/` worker branch), or has a rebase, merge, cherry-pick, revert or bisect in progress. It also keeps them when a gitignored `.env` or `.env.*` file (not `.env.example`), a `.sql`, `.dump`, `.sqlite` or `.db` file outside `node_modules/`, or anything under `.tmp/` is present. Build and cache output never blocks cleanup, and neither does an `.env` that Overdeck rendered from `workspace.env.template`. ([#5990](https://github.com/eltmon/overdeck/issues/5990)) +- **Closed-issue cleanup keeps work that `git status` cannot see:** before it removes a merged issue's workspace, cleanup now also keeps the folder, both branches and the stack's volumes when a checkout holds a commit that neither the target branch nor the merged feature branch holds (on a detached HEAD, another branch or a `.swarm/` worker branch, or in the branches or stash of a repository that lives inside the workspace folder), or has a rebase, merge, cherry-pick, revert or bisect in progress. It also keeps them when a gitignored `.env` or `.env.*` file (not `.env.example`), a `.sql`, `.dump`, `.sqlite` or `.db` file outside `node_modules/`, or anything under `.tmp/` is present. Build and cache output never blocks cleanup, and neither does an `.env` that Overdeck rendered from `workspace.env.template`. ([#5990](https://github.com/eltmon/overdeck/issues/5990)) - **Cleanup recognises Overdeck's own files by exact path:** only the files Overdeck writes under `.overdeck/` (such as `continue.json`, `pipeline.jsonl` and `verification/`) count as runtime. Any other untracked file there, for example a new file under `.overdeck/context/`, keeps the workspace. Synced skills and agents that are unchanged since the sync, the project agent template's files, the rendered `.mcp.json` and an unchanged `.hume-config` no longer keep old polyrepo workspaces forever. A file you add to `.claude/skills/` yourself still keeps the workspace, even when `.claude/` is gitignored. ([#5990](https://github.com/eltmon/overdeck/issues/5990)) - **GitLab merges are proven like GitHub ones:** a merged GitLab merge request now counts for cleanup only if it comes from the same project, merged into the target branch, and has its merge or squash commit on that branch. If GitLab does not report one of these facts, nothing is removed. ([#5990](https://github.com/eltmon/overdeck/issues/5990)) diff --git a/src/lib/workspaces/__tests__/reap-work-checks.test.ts b/src/lib/workspaces/__tests__/reap-work-checks.test.ts index 7b698f5e713..c9b49247896 100644 --- a/src/lib/workspaces/__tests__/reap-work-checks.test.ts +++ b/src/lib/workspaces/__tests__/reap-work-checks.test.ts @@ -145,6 +145,57 @@ describe('checkWorkspaceUncommittedWork beyond git status (PAN-5990)', () => { expect(result.reason).toContain(`branch ${BRANCH}-worker-1 in ${worker}`); }); + it('keeps a separate clone inside the workspace whose own main holds an unpushed commit', async () => { + const clone = join(ws, 'refclone'); + git(root, ['clone', '-q', join(root, 'origin.git'), clone]); + commitFile(clone, 'unpushed.ts', 'unpushed\n', 'unpushed work'); + + expect((await verdict(ws)).reason).toContain(`cannot tell which branch holds the commits in ${clone}`); + }); + + describe('a member cloned into the workspace (its refs die with the folder)', () => { + let member: string; + + beforeEach(() => { + mocks.members = ['api']; + const wrapper = join(root, 'cloned-wrapper'); + mkdirSync(wrapper); + member = join(wrapper, 'api'); + git(root, ['clone', '-q', join(root, 'origin.git'), member]); + git(member, ['switch', '-q', '-c', BRANCH]); + commitFile(member, 'api.ts', 'api\n', 'api work'); + git(member, ['push', '-q', 'origin', BRANCH]); + ws = wrapper; + }); + + it('accepts it when every commit is on origin', async () => { + expect(await verdict(ws)).toEqual({ clean: true }); + }); + + it('keeps an unpushed commit on the local feature branch', async () => { + commitFile(member, 'more.ts', 'more\n', 'unpushed feature work'); + expect((await verdict(ws)).reason).toContain(`branch ${BRANCH} in ${member}`); + }); + + it('keeps an unpushed commit on another local branch that is not checked out', async () => { + git(member, ['switch', '-q', '-c', 'side']); + commitFile(member, 'side.ts', 'side\n', 'side work'); + git(member, ['switch', '-q', BRANCH]); + expect((await verdict(ws)).reason).toContain('1 commit(s) on neither main nor feature/pan-1'); + }); + + it('keeps a stash entry', async () => { + // What a stash records: a commit on HEAD under refs/stash, the tree clean. + const tree = git(member, ['rev-parse', 'HEAD^{tree}']); + const entry = git(member, ['commit-tree', tree, '-p', 'HEAD', '-m', 'WIP on feature/pan-1']); + git(member, ['update-ref', '--create-reflog', 'refs/stash', entry]); + // A newer entry on top that origin holds: the first now lives only in the reflog. + git(member, ['update-ref', '--create-reflog', 'refs/stash', git(member, ['rev-parse', 'HEAD'])]); + expect(git(member, ['status', '--porcelain'])).toBe(''); + expect((await verdict(ws)).reason).toContain('on neither main nor feature/pan-1'); + }); + }); + describe('the polyrepo wrapper', () => { let wrapper: string; @@ -167,6 +218,13 @@ describe('checkWorkspaceUncommittedWork beyond git status (PAN-5990)', () => { commitFile(wrapper, '.pan/drafts/pan-1.md', '# PRD\n', 'draft'); expect((await verdict(wrapper)).reason).toContain(`the workspace repo ${wrapper} holds 1 local commit(s)`); }); + + it('keeps such a commit on a branch that is not checked out', async () => { + git(wrapper, ['switch', '-q', '-c', 'notes']); + commitFile(wrapper, 'notes.md', 'notes\n', 'notes'); + git(wrapper, ['switch', '-q', 'master']); + expect((await verdict(wrapper)).reason).toContain('holds 1 local commit(s)'); + }); }); }); @@ -217,6 +275,7 @@ describe('checkWorkspaceUncommittedWork beyond git status (PAN-5990)', () => { write(join(ws, '.overdeck', 'continue.json'), '{}\n'); write(join(ws, '.overdeck', 'verification', '2026-12-03T12-00-00-000Z-abcd1234.json'), '{}\n'); write(join(ws, '.overdeck', 'feedback', '001-review-pass.md'), 'ok\n'); + write(join(ws, '.overdeck', 'context', 'workspace.md'), '# workspace layer\n'); expect(await verdict(ws)).toEqual({ clean: true }); }); @@ -294,6 +353,15 @@ describe('checkWorkspaceUncommittedWork beyond git status (PAN-5990)', () => { expect((await verdict(ws)).reason).toContain('.claude/commands/mine.md'); }); + it('does not keep the pan sync mirror of the checkout\'s own skills/; keeps a diverged copy', async () => { + commitFile(ws, 'skills/house/SKILL.md', '# house\n', 'house skill'); + write(join(ws, '.claude', 'skills', 'house', 'SKILL.md'), '# house\n'); + expect(await verdict(ws)).toEqual({ clean: true }); + + write(join(ws, '.claude', 'skills', 'house', 'SKILL.md'), '# house, edited here\n'); + expect((await verdict(ws)).reason).toContain('.claude/skills/house/SKILL.md'); + }); + it('does not keep a .hume-config as Overdeck writes it; keeps an edited one', async () => { write(join(ws, '.hume-config'), 'HUME_CONFIG_ID=abc-123\nVITE_HUME_CONFIG_ID=abc-123\n'); expect(await verdict(ws)).toEqual({ clean: true }); diff --git a/src/lib/workspaces/__tests__/uncommitted-work.test.ts b/src/lib/workspaces/__tests__/uncommitted-work.test.ts index 6a786851291..e53a93c6fb0 100644 --- a/src/lib/workspaces/__tests__/uncommitted-work.test.ts +++ b/src/lib/workspaces/__tests__/uncommitted-work.test.ts @@ -43,6 +43,16 @@ function repo(dir: string): void { git(dir, 'commit', '-q', '-m', 'base'); } +/** + * A checkout as Overdeck makes one: a worktree on `feature/pan-1` of a repo + * that lives outside the workspace folder, so its refs outlive the reap. + */ +function worktree(root: string, dir: string): void { + const source = join(root, 'repos', dir.slice(root.length).replace(/[\\/]/g, '_')); + repo(source); + git(source, 'worktree', 'add', '-q', '-b', 'feature/pan-1', dir); +} + /** A polyrepo wrapper as Overdeck makes it: no remote, one commit of its `.gitignore`. */ function wrapperRepo(dir: string): void { mkdirSync(dir, { recursive: true }); @@ -108,7 +118,7 @@ describe('checkWorkspaceUncommittedWork', () => { expect(await checkWorkspaceUncommittedWork(join(root, 'gone'), 'PAN-1')).toEqual({ clean: true, checked: [] }); const ws = join(root, 'ws'); - repo(ws); + worktree(root, ws); mkdirSync(join(ws, 'build')); writeFileSync(join(ws, 'build', 'out.js'), 'generated\n'); @@ -119,8 +129,8 @@ describe('checkWorkspaceUncommittedWork', () => { mocks.members = ['fe', 'api']; const ws = join(root, 'ws'); mkdirSync(ws); - repo(join(ws, 'fe')); - repo(join(ws, 'api')); + worktree(root, join(ws, 'fe')); + worktree(root, join(ws, 'api')); git(join(ws, 'fe'), 'worktree', 'add', '-q', '-b', 'w1', join(ws, 'fe', '.swarm', 'worker-1')); mkdirSync(join(ws, 'src')); @@ -140,8 +150,8 @@ describe('checkWorkspaceUncommittedWork', () => { mocks.members = ['fe', 'api']; const ws = join(root, 'ws'); wrapperRepo(ws); - repo(join(ws, 'fe')); - repo(join(ws, 'api')); + worktree(root, join(ws, 'fe')); + worktree(root, join(ws, 'api')); expect(await checkWorkspaceUncommittedWork(ws, 'PAN-1')).toMatchObject({ clean: true }); diff --git a/src/lib/workspaces/overdeck-runtime-files.ts b/src/lib/workspaces/overdeck-runtime-files.ts index a76987dc0da..97479cec99d 100644 --- a/src/lib/workspaces/overdeck-runtime-files.ts +++ b/src/lib/workspaces/overdeck-runtime-files.ts @@ -22,7 +22,9 @@ * - plan-artifact-backups/: `overdeck/plan-artifact-commit.ts` * - config.yaml, projects.yaml, settings.json: `workspace-manager/migration.ts` (copies of `~/.overdeck`) * - feedback/NNN--.md: `pan-dir/feedback.ts` - * Committed content (`context/`, `memory/`) is never listed here. + * - context/workspace.md: the workspace context layer, assembled per workspace + * and never committed (`context-layers/layers.ts`, `workspace-create.ts`) + * Committed content (the rest of `context/`, `memory/`) is never listed here. */ const RUNTIME_FILES = new Set([ @@ -56,6 +58,7 @@ const RUNTIME_TEMP_FILES = [ /** Runtime directories, each with the names its writer produces inside it. */ const RUNTIME_DIR_ENTRIES: Record = { feedback: /^\d{3}-[^/]+\.md$/, + context: /^workspace\.md$/, verification: /^[^/]+\.json$/, 'deft-lift': /^[0-9a-f]{16}\.(current|base|other)$/, // Plan artifacts moved aside under a timestamp, plus the folder's own `*` ignore file. diff --git a/src/lib/workspaces/overdeck-written-paths.ts b/src/lib/workspaces/overdeck-written-paths.ts index 8408d286964..25aba5a9a75 100644 --- a/src/lib/workspaces/overdeck-written-paths.ts +++ b/src/lib/workspaces/overdeck-written-paths.ts @@ -17,6 +17,9 @@ * - `/.env` when `workspace.env.template` renders it (`create.ts`). * - `.hume-config` when it holds exactly the two lines `create.ts` writes. The * content, not the config, decides: a project may drop `hume` later. + * - `.claude/skills/` identical to `skills/`: `pan sync` run in a + * checkout that keeps a top-level `skills/` mirrors it (`mirrorProjectSkills` + * in `sync.ts`, whose manifest lives outside the checkout). */ import { createHash } from 'node:crypto'; import type { Dirent } from 'node:fs'; @@ -31,7 +34,7 @@ import { OVERDECK_WORKSPACE_SYNC_EXCLUDE_PATTERNS } from '../workspace-sync-path const MANIFEST_PATH = '.claude/.overdeck-manifest.json'; const HUME_CONFIG_PATH = '.hume-config'; const GENERATED_HUME_CONFIG = /^HUME_CONFIG_ID=([^\s=]+)\nVITE_HUME_CONFIG_ID=\1\n$/; -/** Bound on the template walk; a project template is a handful of files. */ +/** Bound on the template and `skills/` walks; each is a handful of files. */ const MAX_TEMPLATE_FILES = 5_000; const MAX_TEMPLATE_DEPTH = 8; @@ -69,11 +72,11 @@ async function unmodifiedManifestFiles(workspacePath: string): Promise return files; } -/** Every file under `dir`, relative to it; throws past the bounds. */ +/** Every file under `dir`, relative to it (none when it is missing); throws past the bounds. */ async function listFiles(dir: string): Promise { const files: string[] = []; const walk = async (current: string, prefix: string, depth: number): Promise => { - if (depth > MAX_TEMPLATE_DEPTH) throw new Error(`template folder ${dir} is nested too deeply`); + if (depth > MAX_TEMPLATE_DEPTH) throw new Error(`${dir} is nested too deeply`); let entries: Dirent[]; try { entries = await readdir(current, { withFileTypes: true }); @@ -84,7 +87,7 @@ async function listFiles(dir: string): Promise { const rel = prefix ? `${prefix}/${entry.name}` : entry.name; if (entry.isDirectory()) await walk(join(current, entry.name), rel, depth + 1); else if (entry.isFile()) files.push(rel); - if (files.length > MAX_TEMPLATE_FILES) throw new Error(`template folder ${dir} holds too many files`); + if (files.length > MAX_TEMPLATE_FILES) throw new Error(`${dir} holds too many files`); } }; await walk(dir, '', 0); @@ -134,6 +137,20 @@ async function generatedHumeConfig(workspacePath: string): Promise { } } +/** `.claude/skills/` files identical to the checkout's own `skills/` source. */ +async function mirroredProjectSkills(workspacePath: string): Promise { + const sourceDir = join(workspacePath, 'skills'); + if (!existsSync(sourceDir)) return []; + const files: string[] = []; + for (const rel of await listFiles(sourceDir)) { + const source = await sha256(join(sourceDir, rel)); + if (source !== null && await sha256(join(workspacePath, '.claude', 'skills', rel)) === source) { + files.push(`.claude/skills/${rel}`); + } + } + return files; +} + /** * The paths (relative to the workspace root, `/`-separated) Overdeck wrote * there and that are still as written. Throws when a source cannot be read @@ -145,5 +162,6 @@ export async function loadOverdeckWrittenPaths(workspacePath: string, issueId: s ...await unmodifiedManifestFiles(workspacePath), ...await projectTemplateFiles(issueId), ...await generatedHumeConfig(workspacePath), + ...await mirroredProjectSkills(workspacePath), ]); } diff --git a/src/lib/workspaces/uncommitted-work.ts b/src/lib/workspaces/uncommitted-work.ts index 5de5b595104..315c33e945c 100644 --- a/src/lib/workspaces/uncommitted-work.ts +++ b/src/lib/workspaces/uncommitted-work.ts @@ -174,7 +174,7 @@ export async function checkWorkspaceUncommittedWork( return { clean: false, reason: `uncommitted changes in ${dir}: ${describePaths(paths)}` }; } - const unheld = await findUnheldCommitWork(dir, checkoutRole(dir, workspacePath, roots)); + const unheld = await findUnheldCommitWork(dir, checkoutRole(dir, workspacePath, roots), workspacePath); if (unheld) return { clean: false, reason: unheld }; try { @@ -199,8 +199,9 @@ function errorLine(err: unknown): string { /** * Which branches hold a checkout's commits: those of the member repo it is, - * or whose `.swarm/` worktree it is (the nearest configured root above it). - * The root of a polyrepo workspace is the wrapper repo. Null when unknown. + * or of the nearest configured root above it (`findUnheldCommitWork` checks + * that the two share a repository). The root of a polyrepo workspace is the + * wrapper repo. Null when no root covers it. */ function checkoutRole(dir: string, workspacePath: string, roots: WorkspaceRepoRoot[]): CheckoutRole | null { const polyrepo = roots.some((root) => root.isPolyrepo || root.degradedPolyrepo); @@ -208,5 +209,7 @@ function checkoutRole(dir: string, workspacePath: string, roots: WorkspaceRepoRo const owner = roots .filter((root) => !root.degradedPolyrepo && (dir === root.dir || dir.startsWith(`${root.dir}${sep}`))) .sort((a, b) => b.dir.length - a.dir.length)[0]; - return owner ? { kind: 'member', branches: { targetBranch: owner.targetBranch, sourceBranch: owner.sourceBranch } } : null; + return owner + ? { kind: 'member', rootDir: owner.dir, branches: { targetBranch: owner.targetBranch, sourceBranch: owner.sourceBranch } } + : null; } diff --git a/src/lib/workspaces/unheld-commits.ts b/src/lib/workspaces/unheld-commits.ts index d91251cc83a..d8f456374b7 100644 --- a/src/lib/workspaces/unheld-commits.ts +++ b/src/lib/workspaces/unheld-commits.ts @@ -10,16 +10,23 @@ * dir) always keeps it. * - A member checkout keeps it when `git rev-list HEAD --not * ` is non-empty: the merge proof covers the target and the - * feature branch tips (local and `origin/`), nothing else. + * feature branch tips (local and `origin/`), nothing else. A checkout below + * a member (a `.swarm/` worktree) is judged by that member's branches only + * when it shares the member's repository (`--git-common-dir`); a separate + * clone has unknown branches and is kept. + * - When the repository itself lives inside the workspace folder, its local + * refs, other branches and stash die with the folder: only `origin/` refs + * hold anything, and every local branch and the stash are judged too. * - The polyrepo wrapper has no remote, target or feature branch: Overdeck - * commits its `.gitignore` and pipeline records there. Any of its commits - * that touches another path keeps it. + * commits its `.gitignore` and pipeline records there. Any commit on any of + * its branches or in its stash that touches another path keeps it. * * Fail closed: a git call that fails or times out is a reason to keep. */ import { execFile } from 'node:child_process'; import { existsSync } from 'node:fs'; -import { join } from 'node:path'; +import { realpath } from 'node:fs/promises'; +import { join, sep } from 'node:path'; import { promisify } from 'node:util'; import { isStatePlanePath } from '../state-plane.js'; @@ -48,7 +55,8 @@ export interface CheckoutBranches { } export type CheckoutRole = - | { kind: 'member'; branches: CheckoutBranches } + /** `rootDir` is the member checkout whose branches apply (the checkout itself, or the one above it). */ + | { kind: 'member'; rootDir: string; branches: CheckoutBranches } | { kind: 'wrapper' }; async function git(dir: string, args: string[]): Promise { @@ -71,23 +79,43 @@ function listCommits(commits: string[]): string { return commits.length > SHOWN_COMMITS ? `${shown} and ${commits.length - SHOWN_COMMITS} more` : shown; } -/** The refs that hold a member checkout's commits, of those that exist. */ -async function holdingRefs(dir: string, branches: CheckoutBranches): Promise<{ target: string[]; source: string[] }> { +/** Every stash entry (the ref's tip and its reflog), which die with a repository inside the folder. */ +async function stashEntries(dir: string): Promise { + if (!(await git(dir, ['for-each-ref', '--format=%(refname)', 'refs/stash'])).trim()) return []; + return lines(await git(dir, ['log', '--walk-reflogs', '--format=%H', 'refs/stash'])); +} + +async function commonDir(dir: string): Promise { + return realpath((await git(dir, ['rev-parse', '--path-format=absolute', '--git-common-dir'])).trim()); +} + +/** The refs that hold a member checkout's commits, of those that exist (only `origin/` ones when local refs die). */ +async function holdingRefs(dir: string, branches: CheckoutBranches, localRefsSurvive: boolean): Promise<{ target: string[]; source: string[] }> { const existing = new Set(lines(await git(dir, [ 'for-each-ref', '--format=%(refname)', `refs/remotes/origin/${branches.targetBranch}`, `refs/heads/${branches.targetBranch}`, `refs/heads/${branches.sourceBranch}`, `refs/remotes/origin/${branches.sourceBranch}`, ]))); - const pick = (branch: string) => [`refs/remotes/origin/${branch}`, `refs/heads/${branch}`].filter((ref) => existing.has(ref)); + const pick = (branch: string) => [`refs/remotes/origin/${branch}`, ...(localRefsSurvive ? [`refs/heads/${branch}`] : [])] + .filter((ref) => existing.has(ref)); return { target: pick(branches.targetBranch), source: pick(branches.sourceBranch) }; } -async function memberUnheldReason(dir: string, branches: CheckoutBranches): Promise { - const refs = await holdingRefs(dir, branches); +async function memberUnheldReason(dir: string, role: Extract, workspacePath: string): Promise { + const { branches } = role; + const common = await commonDir(dir); + if (dir !== role.rootDir && common !== await commonDir(role.rootDir)) { + return `cannot tell which branch holds the commits in ${dir}: it is not a worktree of ${role.rootDir}'s repository`; + } + const workspace = await realpath(workspacePath); + const localRefsSurvive = common !== workspace && !common.startsWith(`${workspace}${sep}`); + const refs = await holdingRefs(dir, branches, localRefsSurvive); if (refs.target.length === 0) { - return `cannot tell which commits in ${dir} are kept: no ${branches.targetBranch} or origin/${branches.targetBranch} ref`; + return `cannot tell which commits in ${dir} are kept: no ${localRefsSurvive ? `${branches.targetBranch} or ` : ''}origin/${branches.targetBranch} ref`; } - const commits = lines(await git(dir, ['rev-list', 'HEAD', '--not', ...refs.target, ...refs.source])); + // A repository inside the folder loses every local branch and its stash too. + const tips = localRefsSurvive ? ['HEAD'] : ['HEAD', '--branches', ...await stashEntries(dir)]; + const commits = lines(await git(dir, ['rev-list', ...tips, '--not', ...refs.target, ...refs.source])); if (commits.length === 0) return null; let head = 'HEAD'; try { @@ -100,7 +128,8 @@ async function memberUnheldReason(dir: string, branches: CheckoutBranches): Prom async function wrapperUnheldReason(dir: string): Promise { // `--format=%x00%H` marks each commit; the paths it touches follow it. - const log = await git(dir, ['log', '--no-renames', '--format=%x00%H', '--name-only', 'HEAD', '--not', '--remotes']); + // `--all` covers every branch and the stash, which die with the folder. + const log = await git(dir, ['log', '--no-renames', '--format=%x00%H', '--name-only', '--all', ...await stashEntries(dir), '--not', '--remotes']); const commits: string[] = []; for (const block of log.split('\0').filter((entry) => entry.trim())) { const [sha, ...paths] = lines(block); @@ -110,8 +139,8 @@ async function wrapperUnheldReason(dir: string): Promise { return `the workspace repo ${dir} holds ${commits.length} local commit(s) beyond its .gitignore and pipeline records: ${listCommits(commits)}`; } -/** Why the checkout at `dir` holds committed work the reap would lose, or null. */ -export async function findUnheldCommitWork(dir: string, role: CheckoutRole | null): Promise { +/** Why the checkout at `dir`, inside `workspacePath`, holds committed work the reap would lose, or null. */ +export async function findUnheldCommitWork(dir: string, role: CheckoutRole | null, workspacePath: string): Promise { try { const gitDir = (await git(dir, ['rev-parse', '--absolute-git-dir'])).trim(); for (const [marker, operation] of IN_PROGRESS_MARKERS) { @@ -125,7 +154,7 @@ export async function findUnheldCommitWork(dir: string, role: CheckoutRole | nul throw err; } if (!role) return `cannot tell which branch holds the commits in ${dir}`; - return role.kind === 'wrapper' ? await wrapperUnheldReason(dir) : await memberUnheldReason(dir, role.branches); + return role.kind === 'wrapper' ? await wrapperUnheldReason(dir) : await memberUnheldReason(dir, role, workspacePath); } catch (err) { return `cannot check the commits in ${dir}: ${firstLine(err)}`; }