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: stop duplicate agent cleanups from reporting a false "worktree preserved" warning
[._.]/ Adam Eivy08a1d20a31e0
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.mdindex caa2855cf7..c137756bb3 100644--- a/.changelog/NEXT.md+++ b/.changelog/NEXT.md@@ -154,6 +154,7 @@## Internal+- **A CoS agent whose worktree was removed cleanly no longer reports "Worktree preserved — uncommitted changes detected".** A completing agent reaches worktree cleanup twice by design: once through the runner path (`handleAgentCompletion` → `runAgentCompletionCleanup`) and once through the spawner's unconditional `finally` safety net, which exists so a throw from `finalizeAgent` can never strand a tree. Neither knows about the other and both are driven by independent events, so they overlapped — and the loser ran `git status --porcelain` while the winner was mid-`git worktree remove --force`, read the in-progress deletions as uncommitted work, and raised a warning plus a user notification for a worktree that removed cleanly ~200ms later. Observed on an agent whose PR had already merged, whose card then claimed its work was preserved. Cleanup is now re-entrant per agent id: a duplicate call joins the pass already running and returns its verdict instead of racing it, so the push, the PR, and the removal each happen once. The preserved-worktree warning also names the dirty paths now (capped at five) — the bare message gave no way to tell real abandoned work from a transient read, and the worktree is usually gone by the time anyone looks.- **[issue-3313] The URL search-param patch helper is now one hook instead of three copies.** `updateParams(patch, { replace })` — merge a patch into the query string, dropping keys set to empty so a cleared filter leaves the URL clean — had been re-typed into Catalog, Media Collections, and (in a narrower single-key form) the 3D page. It now lives in `useUrlParams`, which reads the live params off a ref because react-router's functional updater hands the callback the params captured at the render that memoized it — a debounced `?q=` write armed before a sort change would otherwise navigate with the pre-change snapshot and silently drop the sort the user just picked. The hook is also referentially stable, so the debounce effects on those pages stop re-arming every time an unrelated param changes.- **[issue-3335] Deleting a prompt stage now checks the source, not a hand-written list of ten.** `DELETE /api/prompts/:stage` force-guarded exactly the ten curated CoS/Brain/Memory stages, so removing `pipeline-series-concept-judge` (or roughly a hundred others PortOS resolves by literal key) succeeded with no warning and left the feature naming it throwing `Stage <key> not found` on its next run. Adding them all to the curated table was the wrong fix — the same table drives the Prompt Manager's `SYSTEM` badge and its "System only" filter, and badging ~100 of 127 rows makes both meaningless. Deletion protection is now a second, generated set: a checked-in manifest indexes every stage key a `server/` source names, including the ones reached only through an interpolated prefix like `pipeline-panel-${personaId}`, and a drift test fails until a new call site is regenerated into it. The badge and the filter still show the same ten stages; the delete dialog now names the files that reference the one you're about to remove.- **[issue-3288] Video render submission is no longer a 717-line route handler — and a failed lookup mid-request stops orphaning your upload.** `POST /api/video-gen` did request validation, backend-pin resolution, model checks, durable staging for four upload kinds with rollback bookkeeping, IC-LoRA/keyframe/a2v validation, render-history lookups, LoRA normalization and chunk resolution inline, with twenty-plus throw sites sharing mutable cleanup state — so every new video-gen parameter meant editing the monolith and risking an unrelated validation branch. That whole region now lives in `services/videoGen/prepareParams.js`, mirroring what `imageGen` already did, and the route is a thin parse → prepare → enqueue → respond shell. Validation order and the exact cleanup-on-throw unwind are preserved verbatim, pinned by the existing route suite plus a new service suite. The extraction also closed a real leak (#3326): every *explicit* throw released the staged uploads, but a plain rejected `await` — a music-video project or track lookup, a render-history read, or the enqueue itself — bubbled straight past them, orphaning up to 100MB per request under `data/uploads` with no job to ever clean it up. One rollback guard now covers every rejection point at once and stays correct as new awaits are added, rethrowing the original error untouched.diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.jsindex b4585e7a64..9a86f545d8 100644--- a/server/services/agentWorktreeCleanup.js+++ b/server/services/agentWorktreeCleanup.js@@ -27,6 +27,23 @@ import { detectForgeCli } from '../lib/gitForge.js';import { PR_COMPLETIONS, PR_COMPLETION_VALUES, leavesPrForHuman } from '../lib/prDisposition.js';import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, MODEL_SELECTABLE_REVIEWERS, normalizeReviewers, normalizeReviewUsernames, normalizeOptionalReviewers, normalizeReviewerMaxRounds } from '../lib/validation.js';+// In-flight cleanup per agentId, so two completion paths racing to clean the+// SAME agent coalesce onto one run instead of tripping over each other.+//+// A completing agent reaches cleanup twice by design: the runner path+// (`handleAgentCompletion` → `runAgentCompletionCleanup`) AND the spawner's+// `finally` safety net (agentTuiSpawning.js / agentCliSpawning.js), which fires+// unconditionally so a throw from `finalizeAgent` can never strand a worktree.+// Neither knows about the other, and they are driven by independent events, so+// they overlap. The loser then ran `git status --porcelain` while the winner was+// mid-`git worktree remove --force`, saw the in-progress deletions as ` D <path>`+// dirt, and reported "Worktree preserved — uncommitted changes detected" for a+// worktree that removed cleanly milliseconds later — a false warning AND a false+// user notification on a successful run (observed on agent-ce67bb09, whose PR had+// already merged). Sanctioned by the Security Model's re-entrancy-guard carve-out:+// this is one actor's duplicate in-flight operation, not two competing humans.+const inFlightCleanups = new Map();+/*** Clean up a worktree for a completed agent.* Reads worktree metadata from the agent's registered state and removes the worktree.@@ -43,8 +60,25 @@ import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, MODEL_SE* When skipMerge is true (review-loop follow-up agents), the cleanup never auto-merges* the worktree branch into the source workspace because `gh pr merge` already handled it.* Otherwise, merges the worktree branch back to the source branch on success.+ *+ * Re-entrant per `agentId`: a second call that arrives while the first is still+ * running joins it and resolves with the SAME warnings rather than starting a+ * competing pass (see `inFlightCleanups`). The joiner's `options` are therefore+ * ignored — one completing agent gets one cleanup, and the two duplicate callers+ * this guards against derive their options from the same task metadata anyway.*/-export async function cleanupAgentWorktree(agentId, success, { openPR = false, prCompletion = null, requestCopilotReview: legacyRequestCopilotReview = false, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewerMaxRounds = {}, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false, reviewerModels = null, skipMerge = false, description = null, agentOutput = null, originalTask = null } = {}) {+export async function cleanupAgentWorktree(agentId, success, options = {}) {+ const existing = inFlightCleanups.get(agentId);+ // Join the pass already underway. Its warnings are the run's warnings — the+ // duplicate caller must not re-derive them from a half-removed worktree.+ if (existing) return existing;+ const run = runCleanupAgentWorktree(agentId, success, options)+ .finally(() => { inFlightCleanups.delete(agentId); });+ inFlightCleanups.set(agentId, run);+ return run;+}++async function runCleanupAgentWorktree(agentId, success, { openPR = false, prCompletion = null, requestCopilotReview: legacyRequestCopilotReview = false, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewerMaxRounds = {}, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false, reviewerModels = null, skipMerge = false, description = null, agentOutput = null, originalTask = null } = {}) {const { getAgent: getAgentState } = await import('./cos.js');const agentState = await getAgentState(agentId).catch(() => null);if (!agentState?.metadata?.isWorktree) return [];diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.jsindex 19ae7377fb..6e4bd70f9a 100644--- a/server/services/cleanupAgentWorktree.test.js+++ b/server/services/cleanupAgentWorktree.test.js@@ -1484,3 +1484,116 @@ describe('cleanupAgentWorktree - discardWorktree (throwaway reasoning worktree)'expect(git.createPR).toHaveBeenCalled();});});++// A completing agent reaches cleanup TWICE by design — the runner path+// (`handleAgentCompletion` → `runAgentCompletionCleanup`) and the spawner's+// unconditional `finally` safety net. Driven by independent events, the two+// overlapped: the loser read `git status --porcelain` while the winner was+// mid-`git worktree remove --force`, saw the in-progress deletions as dirt, and+// reported "Worktree preserved — uncommitted changes detected" for a worktree+// that removed cleanly (observed on agent-ce67bb09, whose PR had already merged).+describe('cleanupAgentWorktree — re-entrancy (duplicate completion paths)', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ queuePendingMergeMock.mockResolvedValue(false);+ getAgent.mockResolvedValue(mockWorktreeAgent());+ git.getRepoBranches.mockResolvedValue({ baseBranch: 'main', devBranch: null });+ git.push.mockResolvedValue(undefined);+ git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/1' });+ git.generatePRDescription.mockResolvedValue('body');+ git.suggestPRTitle.mockResolvedValue('title');+ });++ it('coalesces two overlapping cleanups of the SAME agent into one pass', async () => {+ // Park the first pass INSIDE removeWorktree so the second call provably+ // lands mid-flight — the exact interleaving that produced the false warning.+ // `removeCalled` is what makes it provable: releasing on a bare microtask+ // tick would fire before the pass had even reached removeWorktree.+ let releaseRemove;+ const removeCalled = new Promise((signalCalled) => {+ removeWorktree.mockImplementation(() => new Promise((res) => {+ releaseRemove = () => res({ merged: false, removed: true, warnings: [] });+ signalCalled();+ }));+ });++ const first = cleanupAgentWorktree('agent-1', true, { openPR: true });+ await removeCalled;+ const second = cleanupAgentWorktree('agent-1', true, { openPR: true });++ releaseRemove();+ const [firstWarnings, secondWarnings] = await Promise.all([first, second]);++ // ONE removal, ONE push, ONE PR — the duplicate caller joined the pass.+ expect(removeWorktree).toHaveBeenCalledTimes(1);+ expect(git.push).toHaveBeenCalledTimes(1);+ expect(git.createPR).toHaveBeenCalledTimes(1);+ // ...and both callers observe the same verdict, so neither can report a+ // "preserved" warning the other's run never produced.+ expect(secondWarnings).toEqual(firstWarnings);+ });++ // The guard is keyed per agent — two agents finishing together must NOT be+ // collapsed into one cleanup. `openPR: false` keeps this on the plain merge+ // path so it asserts the keying and nothing else.+ it('does NOT coalesce across different agents', async () => {+ // Park each pass inside removeWorktree so both are in flight at once, and+ // parking keeps the post-removal follow-up machinery out of the test.+ const reached = [];+ const arrivals = [];+ removeWorktree.mockImplementation((agentId) => new Promise(() => {+ reached.push(agentId);+ arrivals.shift()?.();+ }));+ const nextArrival = () => new Promise((res) => { arrivals.push(res); });++ // B starts only once A is parked. A is still in flight, so this is the+ // overlap the guard has to distinguish — started sequentially so the two+ // passes don't race the lazy module graph and make the test flaky.+ const aParked = nextArrival();+ cleanupAgentWorktree('agent-A', true, { openPR: false });+ await aParked;+ const bParked = nextArrival();+ cleanupAgentWorktree('agent-B', true, { openPR: false });+ await bParked;++ expect(reached).toEqual(['agent-A', 'agent-B']);+ });++ it('releases the guard so a LATER cleanup of the same agent still runs', async () => {+ removeWorktree.mockResolvedValue({ merged: false, removed: true, warnings: [] });++ await cleanupAgentWorktree('agent-1', true, { openPR: true });+ await cleanupAgentWorktree('agent-1', true, { openPR: true });++ expect(removeWorktree).toHaveBeenCalledTimes(2);+ });++ // A failing removal is reported as a warning, not a throw — so the joiner must+ // receive that SAME warning rather than re-deriving its own verdict from a+ // worktree the failed pass may have left half-removed.+ it('gives the joiner the same warnings when the pass FAILS, and still releases the guard', async () => {+ let releaseRemove;+ const removeCalled = new Promise((signalCalled) => {+ removeWorktree.mockImplementation(() => new Promise((_res, rej) => {+ releaseRemove = () => rej(new Error('git exploded'));+ signalCalled();+ }));+ });++ const first = cleanupAgentWorktree('agent-1', true, { openPR: false });+ await removeCalled;+ const second = cleanupAgentWorktree('agent-1', true, { openPR: false });+ releaseRemove();++ const [firstWarnings, secondWarnings] = await Promise.all([first, second]);+ expect(firstWarnings.join(' ')).toContain('git exploded');+ expect(secondWarnings).toEqual(firstWarnings);+ expect(removeWorktree).toHaveBeenCalledTimes(1);++ // Guard cleared → a later cleanup is not wedged on the failed pass.+ removeWorktree.mockResolvedValue({ merged: false, removed: true, warnings: [] });+ await cleanupAgentWorktree('agent-1', true, { openPR: false });+ expect(removeWorktree).toHaveBeenCalledTimes(2);+ });+});diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.jsindex acbe7c7ff9..e95bfb46c7 100644--- a/server/services/worktreeManager.js+++ b/server/services/worktreeManager.js@@ -20,6 +20,10 @@ import { ensureInstanceId } from './instances.js';const WORKTREES_DIR = PATHS.worktrees;// Lockfiles that npm/yarn/pnpm modify as a side-effect — safe to discard during worktree cleanupconst AUTO_GENERATED_LOCKFILES = ['package-lock.json', 'yarn.lock', 'pnpm-lock.yaml'];+// Cap the dirty paths named in a "worktree preserved" warning — the message ends+// up in a notification and on the agent card, and a broad sweep can dirty+// hundreds of files. Enough to identify the work, short enough to read.+const DIRT_PATHS_IN_WARNING = 5;// `git worktree add` lock-contention retry (#2193). Git guards a repo's// worktree bookkeeping (`.git/worktrees`, `.git/index.lock`) with a per-repo@@ -532,8 +536,16 @@ export async function removeWorktree(agentId, sourceWorkspace, branchName, optioconsole.log(`🧹 Discarding ${dirt.lockfilePaths.length} auto-generated lockfile change(s) in worktree ${agentId}`);await execGit(['checkout', '--', ...dirt.lockfilePaths], worktreePath);} else {- console.log(`⚠️ Preserving worktree for ${agentId} — uncommitted changes detected, aborting cleanup to avoid data loss`);- warnings.push(`Worktree preserved — uncommitted changes detected in ${worktreePath}`);+ // NAME the dirty paths. The bare message reads as "your work was left+ // behind" with no way to tell real uncommitted work from a transient+ // observation, and the worktree is usually gone by the time anyone looks —+ // which is exactly what made the duplicate-cleanup race in+ // `agentWorktreeCleanup.js` undiagnosable from the card alone.+ const shown = dirt.realChangePaths.slice(0, DIRT_PATHS_IN_WARNING);+ const more = dirt.realChangePaths.length - shown.length;+ const detail = `${shown.join(', ')}${more > 0 ? ` (+${more} more)` : ''}`;+ console.log(`⚠️ Preserving worktree for ${agentId} — uncommitted changes detected (${detail}), aborting cleanup to avoid data loss`);+ warnings.push(`Worktree preserved — uncommitted changes detected in ${worktreePath}: ${detail}`);return { merged: false, removed: false, uncommittedSaved: false, warnings };}}diff --git a/server/services/worktreeManager.test.js b/server/services/worktreeManager.test.jsindex ed55feed5e..2eeec148f4 100644--- a/server/services/worktreeManager.test.js+++ b/server/services/worktreeManager.test.js@@ -669,6 +669,30 @@ describe('removeWorktree branch preservation for resume (#3167)', () => {// The resume gate never consulted the merged check for THIS branch.expect(isBranchMergedIntoMock).not.toHaveBeenCalledWith('/repo', 'cos/task-1/agent-x', 'main');});++ // The bare "uncommitted changes detected" message left the user unable to tell+ // real abandoned work from a transient read of a worktree already being removed+ // — and the worktree is gone by the time anyone looks. Name the paths.+ it('NAMES the dirty paths in the preserved-worktree warning', async () => {+ scriptGit({ porcelain: ' M server/services/foo.js\n?? notes.md' });++ const result = await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x', { merge: false });++ expect(result.removed).toBe(false);+ expect(result.warnings.join(' ')).toContain('server/services/foo.js');+ expect(result.warnings.join(' ')).toContain('notes.md');+ });++ it('caps the named paths so a broad sweep cannot flood the notification', async () => {+ scriptGit({ porcelain: Array.from({ length: 9 }, (_, i) => ` M src/f${i}.js`).join('\n') });++ const result = await removeWorktree('agent-x', '/repo', 'cos/task-1/agent-x', { merge: false });++ const warning = result.warnings.join(' ');+ expect(warning).toContain('src/f0.js');+ expect(warning).toContain('(+4 more)');+ expect(warning).not.toContain('src/f8.js');+ });});describe('adoptWorktree — resuming an interrupted run in its own worktree', () => {