Skip to content

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

fix: serialize and verify quality snapshot worktree cleanup (#8726)

[._.]/ Adam Eivyca4afb7fbe07
diff --git a/server/services/appQualitySnapshotFile.js b/server/services/appQualitySnapshotFile.js
index 6f14f59094..f6f32de72e 100644
--- a/server/services/appQualitySnapshotFile.js
+++ b/server/services/appQualitySnapshotFile.js
@@ -19,7 +19,7 @@
* Reads never write. A v1 file or historical
* `quality-snapshot.json` is explicit legacy input.
*/
-import { join } from 'node:path';
+import { basename, join } from 'node:path';
import { tmpdir } from 'node:os';
import { mkdtemp, readFile, rm } from 'node:fs/promises';
import { atomicWrite } from '../lib/fileCore.js';
@@ -384,11 +384,38 @@ async function landSnapshotPr(app, { body, count, defaultBranch, git, deps, mess
};
};
- return run().finally(() => Promise.all([
- git.execGit(['worktree', 'remove', '--force', worktreePath], app.repoPath, { ignoreExitCode: true })
- .catch(() => {}),
- removeTemp(worktreePath, { recursive: true, force: true }).catch(() => {}),
- ]));
+ return run().finally(() => cleanupSnapshotWorktree(app, git, worktreePath, removeTemp));
+}
+
+const removeWorktreeRegistration = (git, repoPath, worktreePath) => git
+ .execGit(['worktree', 'remove', '--force', worktreePath], repoPath, { ignoreExitCode: true })
+ .then(result => (result?.exitCode ?? 0) === 0 ? null : String(result.stderr || `exit ${result.exitCode}`))
+ .catch(err => err?.message || String(err));
+
+// Serialized cleanup of the ONE temporary worktree this invocation created
+// (#8726): Git removal first, then the directory, then a retry of the
+// registration removal (Git accepts a missing directory), then a verification
+// against `worktree list`. The mkdtemp basename is unique, so matching on it
+// never touches another worktree and survives /var ↔ /private/var aliasing.
+// Cleanup failure is reported, never thrown — the publication outcome stands.
+async function cleanupSnapshotWorktree(app, git, worktreePath, removeTemp) {
+ const redact = text => String(text || '').split(worktreePath).join('<snapshot-worktree>')
+ .replace(/\s+/g, ' ').trim().slice(0, 200);
+ let gitError = await removeWorktreeRegistration(git, app.repoPath, worktreePath);
+ const rmError = await removeTemp(worktreePath, { recursive: true, force: true })
+ .then(() => null, err => err?.code || err?.message || String(err));
+ if (gitError) gitError = await removeWorktreeRegistration(git, app.repoPath, worktreePath);
+ const listing = await git.execGit(['worktree', 'list', '--porcelain'], app.repoPath, { ignoreExitCode: true })
+ .catch(() => null);
+ const name = basename(worktreePath);
+ const stillRegistered = String(listing?.stdout || '').split('\n')
+ .some(line => line.startsWith('worktree ') && basename(line.slice(9).trim()) === name);
+ if (!stillRegistered && !rmError) return;
+ const reasons = [
+ stillRegistered && `registration remains (${redact(gitError) || 'no error reported'})`,
+ rmError && `directory removal failed (${redact(rmError)})`,
+ ].filter(Boolean).join('; ');
+ console.warn(`⚠️ Quality snapshot worktree cleanup incomplete for app ${app.id}: ${reasons}`);
}
async function pushSnapshotBranch(git, repoPath, worktreePath) {
diff --git a/server/services/appQualitySnapshotFile.test.js b/server/services/appQualitySnapshotFile.test.js
index 4cb412cc2d..10d27b7d1d 100644
--- a/server/services/appQualitySnapshotFile.test.js
+++ b/server/services/appQualitySnapshotFile.test.js
@@ -558,3 +558,47 @@ it('reads v1, v2, and the legacy filename without falling past a canonical file'
expect(unreadable.status).toBe('unreadable');
expect(unreadable.filename).toBe('.quality.json');
});
+
+it('serializes worktree cleanup, retries a failed Git removal, and reports stale metadata without failing publication', async () => {
+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
+ const order = [];
+ let removals = 0;
+ const run = async ({ retrySucceeds }) => {
+ removals = 0;
+ order.length = 0;
+ __resetQualitySnapshotPublishState();
+ const base = gitDouble().execGit;
+ const deps = testDeps({
+ rm: vi.fn(async () => { order.push('rm'); }),
+ git: gitDouble({ execGit: vi.fn(async (args, cwd, opts) => {
+ if (args[0] === 'worktree' && args[1] === 'remove') {
+ order.push('remove');
+ removals += 1;
+ if (removals === 1) return { exitCode: 128, stdout: '', stderr: `fatal: '${worktreePath}' is locked` };
+ if (!retrySucceeds) throw new Error(`cannot remove ${worktreePath}`);
+ return { exitCode: 0, stdout: '', stderr: '' };
+ }
+ if (args[0] === 'worktree' && args[1] === 'list') {
+ const stale = retrySucceeds ? '' : `worktree /private${worktreePath}\ndetached\n\n`;
+ return { exitCode: 0, stdout: `worktree /repo/example-app\nbranch refs/heads/main\n\n${stale}worktree /repo/other\n`, stderr: '' };
+ }
+ return base(args, cwd, opts);
+ }) }),
+ });
+ return publishAppQualitySnapshot(app, deps);
+ };
+
+ const ok = await run({ retrySucceeds: true });
+ expect(ok.published).toBe(true);
+ expect(order).toEqual(['remove', 'rm', 'remove']);
+ expect(warn).not.toHaveBeenCalled();
+
+ const stale = await run({ retrySucceeds: false });
+ expect(stale.published).toBe(true);
+ expect(warn).toHaveBeenCalledTimes(1);
+ const message = warn.mock.calls[0][0];
+ expect(message).toContain('registration remains');
+ expect(message).toContain('<snapshot-worktree>');
+ expect(message).not.toContain(worktreePath);
+ warn.mockRestore();
+});