Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: delete untracked lockfiles instead of failing worktree removal (#11867)
Adam Eivyaaf861b959f4
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.jsindex 60f22155ce..4a5d9a64a5 100644--- a/server/services/worktreeManager.js+++ b/server/services/worktreeManager.js@@ -457,10 +457,11 @@ async function enforceUpstreamOrUndoAdd(sourceWorkspace, branchName, worktreePat* statically, notably one run's own `.agent-done-<agentId>` sentinel. Matched* as roots: a directory entry also covers everything under it. They are still* removed only when the rest of the tree is safe to remove.- * @returns {{ clean: boolean, lockfileOnly: boolean, lockfilePaths: string[], realChangePaths: string[], hasRealChanges: boolean }}+ * @returns {{ clean: boolean, lockfileOnly: boolean, lockfilePaths: string[], untrackedLockfilePaths: string[], realChangePaths: string[], hasRealChanges: boolean }}* - clean: no changes at all* - lockfileOnly: every change is an auto-generated lockfile (safe to discard)* - lockfilePaths: paths of those lockfiles (strip the porcelain `XY ` status prefix)+ * - untrackedLockfilePaths: the subset of lockfilePaths that is untracked (`??`)* - realChangePaths: paths of the NON-lockfile changes, same prefix stripping.* Branch reconciliation intersects these with what the default branch has* touched since the branch diverged, to spot work that may have been@@ -475,7 +476,7 @@ export function classifyWorktreeDirt(porcelain, { ignoredPaths = [] } = {}) {.filter(Boolean).filter(line => !matchesScratchRoot(toPath(line), ignored));if (lines.length === 0) {- return { clean: true, lockfileOnly: false, lockfilePaths: [], realChangePaths: [], hasRealChanges: false };+ return { clean: true, lockfileOnly: false, lockfilePaths: [], untrackedLockfilePaths: [], realChangePaths: [], hasRealChanges: false };}const isLockfile = (line) => AUTO_GENERATED_LOCKFILES.some(f => line.endsWith(f));// `R old -> new` (rename) names two paths; the post-rename path is the one@@ -486,11 +487,29 @@ export function classifyWorktreeDirt(porcelain, { ignoredPaths = [] } = {}) {clean: false,lockfileOnly,lockfilePaths: lockfileLines.map(toPath),+ // Untracked (`??`) lockfiles have no index entry, so `git checkout --` cannot+ // restore them; discardLockfileChanges deletes these instead.+ untrackedLockfilePaths: lockfileLines.filter(line => line.startsWith('??')).map(toPath),realChangePaths: lines.filter((line) => !isLockfile(line)).map(toPath),hasRealChanges: !lockfileOnly};}+/**+ * Discard the auto-generated lockfile churn that `classifyWorktreeDirt` reported.+ * Untracked lockfiles are deleted (git cannot restore what it does not track);+ * tracked ones are restored from the index. Rejects if either step fails, so the+ * caller decides whether the tree is still safe to remove.+ */+async function discardLockfileChanges(worktreePath, dirt) {+ const untracked = new Set(dirt.untrackedLockfilePaths);+ for (const path of untracked) {+ await rm(join(worktreePath, path), { force: true });+ }+ const tracked = dirt.lockfilePaths.filter(path => !untracked.has(path));+ if (tracked.length) await execGit(['checkout', '--', ...tracked], worktreePath);+}+/** A proven-absent directory is empty; an existing tree must identify itself.* Git can otherwise walk out of a broken linked checkout and report its parent* clean. null means unknown, including unreadable directories or status errors.@@ -1043,7 +1062,7 @@ async function adoptWorktreeUnlocked(agentId, sourceWorkspace, existingWorktreePconst dirt = classifyWorktreeDirt(porcelain);if (dirt.lockfileOnly) {console.log(`🧹 Discarding ${dirt.lockfilePaths.length} auto-generated lockfile change(s) in adopted worktree ${agentId}`);- await execGit(['checkout', '--', ...dirt.lockfilePaths], targetPath).catch(err => {+ await discardLockfileChanges(targetPath, dirt).catch(err => {console.log(`⚠️ Lockfile discard failed in adopted worktree ${agentId}: ${err.message}`);});}@@ -1211,7 +1230,13 @@ export async function removeWorktree(agentId, sourceWorkspace, branchName, optio// (e.g., npm install resolving ^version to exact version in package-lock.json)if (dirt.lockfileOnly) {console.log(`🧹 Discarding ${dirt.lockfilePaths.length} auto-generated lockfile change(s) in worktree ${agentId}`);- await execGit(['checkout', '--', ...dirt.lockfilePaths], worktreePath);+ // Never throws past removeWorktree: an undiscardable lockfile keeps the tree.+ const discarded = await discardLockfileChanges(worktreePath, dirt).then(() => true, err => {+ console.log(`⚠️ Lockfile discard failed in worktree ${agentId}, preserving to avoid data loss: ${err.message}`);+ warnings.push(`Worktree preserved — lockfile discard failed in ${worktreePath}: ${err.message}`);+ return false;+ });+ if (!discarded) return { merged: false, removed: false, uncommittedSaved: false, warnings };} else {// NAME the dirty paths. The bare message reads as "your work was left// behind" with no way to tell real uncommitted work from a transientdiff --git a/server/services/worktreeManager.test.js b/server/services/worktreeManager.test.jsindex 47a652ce41..9a45ca5019 100644--- a/server/services/worktreeManager.test.js+++ b/server/services/worktreeManager.test.js@@ -141,7 +141,7 @@ describe('Worktree dependency preparation', () => {describe('classifyWorktreeDirt (real exported helper)', () => {it('reports clean for empty / whitespace-only porcelain', () => {- expect(classifyWorktreeDirt('')).toEqual({ clean: true, lockfileOnly: false, lockfilePaths: [], realChangePaths: [], hasRealChanges: false });+ expect(classifyWorktreeDirt('')).toEqual({ clean: true, lockfileOnly: false, lockfilePaths: [], untrackedLockfilePaths: [], realChangePaths: [], hasRealChanges: false });expect(classifyWorktreeDirt(' \n ').clean).toBe(true);expect(classifyWorktreeDirt(null).clean).toBe(true);});@@ -741,6 +741,42 @@ describe('removeWorktree identity, dirt and branch preservation', () => {expect(calledWith(['merge', 'cos/task-1/agent-x', '--no-edit'])).toBe(false);});+ // An untracked lockfile has no index entry, so `git checkout --` cannot restore it+ // and used to reject the whole removal (#11867). It must be deleted instead.+ it('removes a worktree whose only dirt is an untracked lockfile', async () => {+ scriptGit({ porcelain: '?? package-lock.json' });++ const result = await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x', { merge: false });++ expect(result.removed).toBe(true);+ expect(rm).toHaveBeenCalledWith(join(PATHS.worktrees, 'agent-x', 'package-lock.json'), { force: true });+ expect(calledWith(['checkout', '--', 'package-lock.json'])).toBe(false);+ });++ it('restores a modified tracked lockfile with checkout before removal', async () => {+ scriptGit({ porcelain: ' M pnpm-lock.yaml' });++ const result = await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x', { merge: false });++ expect(result.removed).toBe(true);+ expect(calledWith(['checkout', '--', 'pnpm-lock.yaml'])).toBe(true);+ expect(rm).not.toHaveBeenCalledWith(expect.stringContaining('pnpm-lock.yaml'), expect.anything());+ });++ it('preserves the worktree instead of rejecting when the lockfile discard fails', async () => {+ scriptGit({ porcelain: ' M yarn.lock' });+ const scripted = execGitMock.getMockImplementation();+ execGitMock.mockImplementation((args, ...rest) => (args[0] === 'checkout'+ ? Promise.reject(new Error('index is locked'))+ : scripted(args, ...rest)));++ const result = await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x', { merge: false });++ expect(result).toMatchObject({ removed: false, merged: false, uncommittedSaved: false });+ expect(result.warnings.join(' ')).toMatch(/lockfile discard failed/);+ expect(calledWith(['worktree', 'remove', join(PATHS.worktrees, 'agent-x'), '--force'])).toBe(false);+ });+it('still removes an empty branch after a verified zero commit count', async () => {const result = await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x', { merge: true });@@ -1248,6 +1284,17 @@ describe('adoptWorktree — resuming an interrupted run in its own worktree', ()await expect(adoptWorktree('agent-new', '/repo', DEAD_TREE, 'cos/task-1/agent-dead')).resolves.toBeNull();});+ it('deletes an untracked lockfile rather than checking it out when adopting', async () => {+ execGitMock.mockImplementation((args) => Promise.resolve({+ stdout: args[0] === 'status' ? '?? package-lock.json' : '', stderr: '', exitCode: 0,+ }));++ await adoptWorktree('agent-new', '/repo', DEAD_TREE, 'cos/task-1/agent-dead');++ expect(rm).toHaveBeenCalledWith(join(NEW_TREE, 'package-lock.json'), { force: true });+ expect(execGitMock).not.toHaveBeenCalledWith(['checkout', '--', 'package-lock.json'], expect.anything());+ });+it('is a no-op when the tree already sits at the destination', async () => {scriptPaths({ source: true, target: true });