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: preserve uncommitted lockfile-only changes in dependency-updates worktrees (#12863)
Adam Eivyad04e4f56cc2
diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.jsindex 753961dd39..4c362bbbfe 100644--- a/server/services/agentFinalization.js+++ b/server/services/agentFinalization.js@@ -539,6 +539,13 @@ async function verifyLandedChangeRequest(refs, forge, workspacePath) {* every existing caller, persisted payload and test sees exactly what it saw* before this indirection existed.*/+async function hasUncommittedLockfileDeliverable(task, workspacePath) {+ if (resolveTaskHookType(task) !== 'dependency-updates') return false;+ const { readWorktreeStatus, classifyWorktreeDirt } = await import('./worktreeManager.js');+ const status = await readWorktreeStatus(workspacePath).catch(() => null);+ return status !== null && classifyWorktreeDirt(status, { preserveLockfiles: true }).hasRealChanges;+}+function prVerdictFromObservation(observation) {const policy = PR_OBSERVATION_POLICY[observation.outcome];const verdict = { ok: policy.completionOk };@@ -646,6 +653,11 @@ async function observePrClaim({ task, workspacePath, success, prExpected, agentS// Deliberately gated on an EXPLICIT 0: an unreadable count is not evidence// of an empty branch, so it leaves the miss standing.const ahead = await countCommitsAhead(workspacePath).catch(() => null);+ // A dependency-updates run can leave its deliverable (a lockfile-only change)+ // uncommitted; cleanup preserves it, so the empty branch is not "already current".+ if (ahead === 0 && await hasUncommittedLockfileDeliverable(task, workspacePath)) {+ return prObservation(PR_OBSERVATION.MISSING_PR, { branch, commitsAhead: 0, inconclusive: false });+ }if (ahead === 0) return prObservation(PR_OBSERVATION.EMPTY_BRANCH, { branch });// The stand-down a parallel claim produces: the branch holds this run's// (now redundant) commits, the forge holds no change request for it, anddiff --git a/server/services/agentWorkspacePrep.js b/server/services/agentWorkspacePrep.jsindex 664c29205f..9db532fc00 100644--- a/server/services/agentWorkspacePrep.js+++ b/server/services/agentWorkspacePrep.js@@ -111,7 +111,7 @@ export { resolveTaskTargetBranch as resolveTaskExistingBranch } from '../lib/tas** @returns {Promise<{ worktreeInfo: object, adoptedFrom: string }|{ refused: string }|null>}*/-async function adoptWorktreeHoldingBranch({ agentId, workspacePath, branchName, preferredPath = null, taskId, allowLiveClaim = false, deepResume = false, adopt = true, reviewTarget = null }) {+async function adoptWorktreeHoldingBranch({ agentId, workspacePath, branchName, preferredPath = null, taskId, allowLiveClaim = false, deepResume = false, adopt = true, reviewTarget = null, preserveLockfiles = false }) {// Fail CLOSED on an unreadable agent list: an empty protected set would read as// "nothing is running", which is the one wrong answer here — it would move a// live run's directory. The caller's timed pause is the safe outcome instead.@@ -155,7 +155,7 @@ async function adoptWorktreeHoldingBranch({ agentId, workspacePath, branchName,const refused = await validateCleanupReviewTarget({ target: reviewTarget, workspacePath: holder.path, requireCheckout: true, launchTaskId: taskId });if (refused) return { refused };}- const worktreeInfo = await adoptWorktree(agentId, workspacePath, holder.path, branchName, ...(deepResume ? [{ deepResume: true }] : [])).catch(err => {+ const worktreeInfo = await adoptWorktree(agentId, workspacePath, holder.path, branchName, ...(deepResume || preserveLockfiles ? [{ ...(deepResume && { deepResume }), ...(preserveLockfiles && { preserveLockfiles }) }] : [])).catch(err => {if (err.code === 'DEEP_RESUME_PRESERVED') return { refused: err.message };emitLog('warn', `🌳 Could not adopt ${holder.path} holding ${branchName} for task ${taskId}: ${err.message}`, { taskId });return null;@@ -270,6 +270,7 @@ async function prepareRequestedWorktree({// can prove both. Releasing an idle sibling holder in place stays allowed.adopt: !pinnedHead,reviewTarget,+ preserveLockfiles: isolateDependencies,}): Promise.resolve(null);diff --git a/server/services/agentWorkspacePrep.test.js b/server/services/agentWorkspacePrep.test.jsindex 4a947faeac..fa7cd6a542 100644--- a/server/services/agentWorkspacePrep.test.js+++ b/server/services/agentWorkspacePrep.test.js@@ -480,7 +480,7 @@ describe('prepareAgentWorkspace — resuming an interrupted run', () => {agentId: 'agent-new', task: resumeTask({ analysisType: 'dependency-updates' }),});- expect(adoptWorktree).toHaveBeenCalledWith('agent-new', expect.any(String), DEAD_TREE, 'cos/t-resume/agent-dead');+ expect(adoptWorktree).toHaveBeenCalledWith('agent-new', expect.any(String), DEAD_TREE, 'cos/t-resume/agent-dead', { preserveLockfiles: true });expect(unlinkWorktreeDependencies).toHaveBeenCalledWith(expect.any(String), '/mock/worktrees/agent-new');expect(createWorktree).not.toHaveBeenCalled();expect(r.outcome).toBe('ready');diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.jsindex 4c9ef38065..e42ff3b4ba 100644--- a/server/services/agentWorktreeCleanup.js+++ b/server/services/agentWorktreeCleanup.js@@ -18,6 +18,7 @@ import { join } from 'path';import { emitLog } from './cosEvents.js';import { addTask, forceSpawnTask, getAgents, updateTask } from './cos.js';import * as git from './git.js';+import { resolveTaskHookType } from './taskTypeHooks.js';import { removeWorktree, classifyWorktreeDirt, listWorktrees } from './worktreeManager.js';import { claimContinuationPointer } from '../lib/claimContinuation.js';import { isTruthyMeta } from './agentState.js';@@ -295,6 +296,9 @@ function cleanupOptions({ prCreation = PR_CREATION.NEVER, prCompletion = null, rreviewerModels, reviewerEfforts, skipMerge, description, agentOutput, originalTask };}+// A lockfile-only diff is a legitimate deliverable for dependency-updates only.+export const lockfileDeliverable = (task) => ({ preserveLockfiles: resolveTaskHookType(task) === 'dependency-updates' });+async function discardAgentWorktree({ agentId, sourceWorkspace, worktreeBranch }) {emitLog('info', `🌳 Discarding worktree for reasoning agent ${agentId} (no merge, no PR)`, { agentId, branchName: worktreeBranch });// `discardDirt`: the discard prompt explicitly invites scratch edits ("only@@ -378,7 +382,7 @@ async function openWorktreePullRequest(context) {return completeOpenedPullRequest(context, prResult);}-async function handlePrCreationFailure({ agentId, sourceWorkspace, worktreeBranch, warnings }, prResult, targetBranch) {+async function handlePrCreationFailure({ agentId, sourceWorkspace, worktreeBranch, warnings, originalTask }, prResult, targetBranch) {const reason = prResult?.error || 'unknown error (createPR returned null or threw)';// "No commits between X and Y" means the agent made no code changes.@@ -390,7 +394,7 @@ async function handlePrCreationFailure({ agentId, sourceWorkspace, worktreeBrancemitLog('warn', `🌳 Remote branch delete failed for ${worktreeBranch}: ${err.message}`, { agentId });warnings.push(`Remote branch delete failed for ${worktreeBranch}: ${err.message}`);});- const result = await removeWorktree(agentId, sourceWorkspace, worktreeBranch, { merge: false }).catch(err => {+ const result = await removeWorktree(agentId, sourceWorkspace, worktreeBranch, { merge: false, ...lockfileDeliverable(originalTask) }).catch(err => {emitLog('warn', `🌳 Worktree cleanup failed for ${agentId}: ${err.message}`, { agentId });return { warnings: [`Worktree cleanup failed for ${agentId}: ${err.message}`] };});@@ -447,7 +451,7 @@ async function completeOpenedPullRequest(context, prResult) {// at …", the task was blocked, and the pull request it existed to land was// orphaned. Nothing below this point reads the worktree — the Copilot// pre-request above is the last user of that checkout.- const result = await removeWorktree(agentId, sourceWorkspace, worktreeBranch, { merge: false }).catch(err => {+ const result = await removeWorktree(agentId, sourceWorkspace, worktreeBranch, { merge: false, ...lockfileDeliverable(originalTask) }).catch(err => {emitLog('warn', `🌳 Worktree cleanup failed for ${agentId}: ${err.message}`, { agentId });return { cleanupIncomplete: true, warnings: [`Worktree cleanup failed: ${err.message}`] };});@@ -591,6 +595,7 @@ async function mergeOrPreserveWorktree({ agentId, sourceWorkspace, worktreeBranc// from the preserved work through resolveResumeBranch below.const result = await removeWorktree(agentId, sourceWorkspace, worktreeBranch, {merge: shouldMerge,+ ...lockfileDeliverable(originalTask),}).catch(err => {emitLog('warn', `🌳 Worktree cleanup failed for ${agentId}: ${err.message}`, { agentId });return { cleanupIncomplete: true, warnings: [`Worktree cleanup failed: ${err.message}`] };@@ -714,7 +719,7 @@ async function deleteMergedRemoteCopy(agentId, sourceWorkspace, branchName) {* adoption candidate. Omit to consider only the branch-attach shape.* @returns {Promise<{branchName: string, worktreePath: string|null}|null>}*/-export async function resolveResumePointer(sourceWorkspace, branchName, worktreePath = null) {+export async function resolveResumePointer(sourceWorkspace, branchName, worktreePath = null, { preserveLockfiles = false } = {}) {if (!sourceWorkspace || !branchName) return null;const survivingTree = !!(worktreePath && existsSync(worktreePath));@@ -755,7 +760,7 @@ export async function resolveResumePointer(sourceWorkspace, branchName, worktree// resuming" can't disagree: lockfile churn an agent never meant to commit is// not work, and a tree holding only that should start clean.const porcelain = await git.getStatusPorcelain(worktreePath).catch(() => '');- if (!classifyWorktreeDirt(porcelain).hasRealChanges) return null;+ if (!classifyWorktreeDirt(porcelain, { preserveLockfiles }).hasRealChanges) return null;emitLog('info', `🌳 Worktree ${worktreePath} survived on ${branchName} — a retry can adopt it and keep its uncommitted work`, { branchName, worktreePath });return { branchName, worktreePath };}@@ -845,7 +850,7 @@ export async function resolveTaskResumePatch({ task, agentId, agentMetadata }) {// convention is the fallback for a record written before it was stamped (same// idiom cleanupAgentWorktree uses for the PR push).const worktreePath = agentMetadata.workspacePath || join(PATHS.worktrees, agentId);- const pointer = await resolveResumePointer(agentMetadata.sourceWorkspace, agentMetadata.worktreeBranch, worktreePath)+ const pointer = await resolveResumePointer(agentMetadata.sourceWorkspace, agentMetadata.worktreeBranch, worktreePath, lockfileDeliverable(task)).catch(err => {emitLog('warn', `Failed to resolve resume pointer for ${agentId}: ${err.message}`, { agentId });return null;diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.jsindex 9c0db7695f..ad124b498f 100644--- a/server/services/worktreeManager.js+++ b/server/services/worktreeManager.js@@ -552,6 +552,7 @@ 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.+ * @param {{ ignoredPaths?: string[], preserveLockfiles?: boolean }} [opts] - `preserveLockfiles` classifies lockfiles as real changes* @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)@@ -563,7 +564,7 @@ async function enforceUpstreamOrUndoAdd(sourceWorkspace, branchName, worktreePat* superseded while it sat uncommitted.* - hasRealChanges: at least one non-lockfile change (worktree must be preserved)*/-export function classifyWorktreeDirt(porcelain, { ignoredPaths = [] } = {}) {+export function classifyWorktreeDirt(porcelain, { ignoredPaths = [], preserveLockfiles = false } = {}) {const ignored = [...AGENT_SCRATCH_PATHS, ...ignoredPaths];// Git's porcelain v1 output C-quotes paths with spaces and several other// characters. Decode those paths before comparing them with scratch roots or@@ -619,7 +620,9 @@ export function classifyWorktreeDirt(porcelain, { ignoredPaths = [] } = {}) {if (lines.length === 0) {return { clean: true, lockfileOnly: false, lockfilePaths: [], untrackedLockfilePaths: [], realChangePaths: [], hasRealChanges: false };}- const isLockfile = (line) => AUTO_GENERATED_LOCKFILES.some(f => toPath(line).endsWith(f));+ // `dependency-updates` can legitimately deliver a lockfile-only diff (`npm audit+ // fix`, a transitive bump), so there a lockfile is work, never churn.+ const isLockfile = (line) => !preserveLockfiles && AUTO_GENERATED_LOCKFILES.some(f => toPath(line).endsWith(f));// `R old -> new` (rename) names two paths; the post-rename path is the one// that exists on disk and the one a diff against the default branch reports.const lockfileLines = lines.filter(isLockfile);@@ -1390,7 +1393,7 @@ async function adoptWorktreeUnlocked(agentId, sourceWorkspace, existingWorktreePconst porcelain = await execGit(['status', '--porcelain'], targetPath).then(r => r.stdout.trim()).catch(() => '');- const dirt = classifyWorktreeDirt(porcelain);+ const dirt = classifyWorktreeDirt(porcelain, { preserveLockfiles: options.preserveLockfiles === true });if (dirt.lockfileOnly) {console.log(`🧹 Discarding ${dirt.lockfilePaths.length} auto-generated lockfile change(s) in adopted worktree ${agentId}`);await discardLockfileChanges(targetPath, dirt).catch(err => {@@ -1503,6 +1506,8 @@ async function cleanupWorktreeBranch(sourceWorkspace, branchName, {* @param {string} branchName - The worktree branch to clean up* @param {object} options* @param {boolean} [options.merge] - attempt to merge the branch back first+ * @param {boolean} [options.preserveLockfiles] - keep a lockfile-only change (a+ * `dependency-updates` deliverable) instead of discarding it as install churn* @param {boolean} [options.discardDirt] - remove even when the tree is dirty.* The dirty-abort exists to protect work that might still be wanted; the* throwaway-worktree posture has already declared this tree's contents@@ -1672,7 +1677,8 @@ async function removeWorktreeNow(agentId, sourceWorkspace, branchName, options,// name, plus the legacy shared one a pre-upgrade run may have left — and no// other agent's.const dirt = classifyWorktreeDirt(dirtyFiles, {- ignoredPaths: [DONE_SENTINEL_NAME, ...doneSentinelCandidateNames(agentId)]+ ignoredPaths: [DONE_SENTINEL_NAME, ...doneSentinelCandidateNames(agentId)],+ preserveLockfiles: options.preserveLockfiles === true});if (!dirt.clean && options.discardDirt) {// Throwaway posture: the caller has already established that nothing in thisdiff --git a/server/services/worktreeManager.test.js b/server/services/worktreeManager.test.jsindex 403b717778..632a91bd9c 100644--- a/server/services/worktreeManager.test.js+++ b/server/services/worktreeManager.test.js@@ -253,6 +253,11 @@ describe('classifyWorktreeDirt (real exported helper)', () => {expect(r.lockfileOnly).toBe(false);});+ it('preserveLockfiles reports lockfiles as real changes', () => {+ const r = classifyWorktreeDirt(' M package-lock.json\n', { preserveLockfiles: true });+ expect(r).toMatchObject({ lockfileOnly: false, hasRealChanges: true, realChangePaths: ['package-lock.json'], lockfilePaths: [] });+ });+it('recognizes a lockfile-only working tree and extracts paths', () => {const r = classifyWorktreeDirt(' M package-lock.json\n M client/package-lock.json');expect(r.lockfileOnly).toBe(true);@@ -880,6 +885,17 @@ describe('removeWorktree identity, dirt and branch preservation', () => {expect(calledWith(['checkout', '--', 'package-lock.json'])).toBe(false);});+ it('dependency-updates lockfile-only dirt is preserved, not discarded', async () => {+ scriptGit({ porcelain: ' M package-lock.json' });++ const result = await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x', { merge: false, preserveLockfiles: true });++ expect(result).toMatchObject({ removed: false, merged: false });+ expect(result.warnings.join(' ')).toMatch(/uncommitted changes detected.*package-lock\.json/);+ expect(calledWith(['checkout', '--', 'package-lock.json'])).toBe(false);+ expect(calledWith(['worktree', 'remove', join(PATHS.worktrees, 'agent-x'), '--force'])).toBe(false);+ });+it('restores a modified tracked lockfile with checkout before removal', async () => {scriptGit({ porcelain: ' M pnpm-lock.yaml' });