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: scope pending cleanup owners to their Git repository (#13456)
Adam Eivy029c6b74a861
diff --git a/server/lib/gitRepositoryIdentity.js b/server/lib/gitRepositoryIdentity.jsnew file mode 100644index 0000000000..d52c1f337c--- /dev/null+++ b/server/lib/gitRepositoryIdentity.js@@ -0,0 +1,15 @@+import { realpath } from 'node:fs/promises';+import { resolve } from 'node:path';+import { execGit } from './execGit.js';++/** Fresh canonical identity shared by linked worktrees and filesystem aliases.+ * Unknown evidence is never proof that two repositories are independent.+ */+export async function readGitCommonDirectory(repoPath) {+ if (typeof repoPath !== 'string' || !repoPath.trim()) return null;+ return execGit(['rev-parse', '--git-common-dir'], repoPath)+ .then(result => {+ const common = result.stdout.trim();+ return common ? realpath(resolve(repoPath, common)) : null;+ }).catch(() => null);+}diff --git a/server/lib/gitRepositoryIdentity.test.js b/server/lib/gitRepositoryIdentity.test.jsnew file mode 100644index 0000000000..9407a49df1--- /dev/null+++ b/server/lib/gitRepositoryIdentity.test.js@@ -0,0 +1,32 @@+import { afterEach, describe, expect, it } from 'vitest';+import { symlink } from 'node:fs/promises';+import { join } from 'node:path';+import { execGit } from './execGit.js';+import { makeGitSandbox, destroyGitSandbox } from './gitTestRepo.js';+import { readGitCommonDirectory } from './gitRepositoryIdentity.js';++let scratch;+afterEach(async () => { if (scratch) await destroyGitSandbox(scratch); });++describe('repository ownership identity', () => {+ it('shares identity across aliases and linked checkouts but never independent clones', async () => {+ const sandbox = await makeGitSandbox();+ scratch = sandbox.scratch;+ const { repo } = sandbox;+ const linked = join(scratch, 'linked');+ const clone = join(scratch, 'clone');+ const alias = join(scratch, 'alias');+ await execGit(['worktree', 'add', '--detach', linked, 'HEAD'], repo);+ await execGit(['clone', '--no-local', repo, clone], scratch);+ await symlink(repo, alias, 'junction');+ const identity = await readGitCommonDirectory(repo);+ expect(identity).toBeTruthy();+ expect(await readGitCommonDirectory(alias)).toBe(identity);+ expect(await readGitCommonDirectory(linked)).toBe(identity);+ const independent = await readGitCommonDirectory(clone);+ expect(independent).toBeTruthy();+ expect(independent).not.toBe(identity);+ expect(await readGitCommonDirectory(join(scratch, 'missing'))).toBeNull();+ expect(await readGitCommonDirectory(undefined)).toBeNull();+ });+});diff --git a/server/services/agentRepoStateVerification.js b/server/services/agentRepoStateVerification.jsindex a2ea82a2c1..7c2736c1ea 100644--- a/server/services/agentRepoStateVerification.js+++ b/server/services/agentRepoStateVerification.js@@ -1,3 +1,4 @@+import { readGitCommonDirectory } from '../lib/gitRepositoryIdentity.js';import { recoverCompletionTaskHandoff } from './agentCompletionTaskHandoff.js';import { withDeliveryActivity, COMPLETION_RECOVERY_BATCH_SIZE } from './agentDeliveryActivity.js';import { MANAGED_WORKTREE_CLEANUP_CONTRACT } from '../lib/mergeGateContract.js';@@ -86,7 +87,7 @@ const PENDING_OWNER_STATUSES = new Set(['pending', 'in_progress', 'blocked', 'ch* @param {object|null} app - the managed app record (carries `pendingMergePrs`)* @returns {Promise<boolean>}*/-async function branchHasPendingOwner(branchName, app, cleanupOwner = null) {+async function branchHasPendingOwner(branchName, sourceWorkspace, app, cleanupOwner = null) {// `resolveTaskTargetBranch` is the canonical "which branch does this task own"// reader — matching `reviewLoopPRBranch` by hand here would miss a retry holding// the same branch through `existingBranch`.@@ -97,12 +98,30 @@ async function branchHasPendingOwner(branchName, app, cleanupOwner = null) {// is queued to land.const tasks = await readAllTasksFlat().catch(() => null);if (!tasks) return null;- const claimedByTask = tasks.some(t =>+ const candidates = tasks.filter(t =>!(cleanupOwner && t.id === cleanupOwner.taskId && t.metadata?.deliveryRecovery === 'cleanup'&& t.metadata.deliveryRecoveryAgentId === cleanupOwner.agentId)&& PENDING_OWNER_STATUSES.has(t.status) && resolveTaskTargetBranch(t.metadata) === branchName);- if (claimedByTask) return true;+ if (candidates.length) {+ const common = await readGitCommonDirectory(sourceWorkspace);+ if (!common) return null;+ const { getAppById } = await import('./apps.js');+ // Audit-local only: each candidate app is read once, with no stale identity+ // carried into another audit. Different app IDs are not different repos.+ const identities = new Map();+ for (const candidate of candidates) {+ const appId = candidate.metadata?.app;+ if (!appId) return null;+ if (!identities.has(appId)) {+ const ownerApp = await getAppById(appId).catch(() => null);+ identities.set(appId, await readGitCommonDirectory(ownerApp?.repoPath));+ }+ const ownerCommon = identities.get(appId);+ if (!ownerCommon) return null;+ if (ownerCommon === common) return true;+ }+ }if (!app) return false;const { readPendingMergePrs } = await import('./prWatcher.js');@@ -520,7 +539,7 @@ async function verifyAgentBranchState({ agentId, task, agentState, success, prExconst worktreePath = isTruthyMeta(metadata.claimPicksOwnBranch) ? metadata.workspacePath : metadata.workspacePath || join(PATHS.worktrees, agentId);const { record, blockWith } = branchLedger(agentId, { branch: branchName, path: worktreePath });const enabled = repoStateVerificationEnabled(app);- const owned = enabled ? await branchHasPendingOwner(branchName, app, agentState?.result?.cleanupPending === true ? { taskId: task.id, agentId } : null).catch(() => null) : false;+ const owned = enabled ? await branchHasPendingOwner(branchName, sourceWorkspace, app, agentState?.result?.cleanupPending === true ? { taskId: task.id, agentId } : null).catch(() => null) : false;if (owned === null) return blockWith('ownership-unreadable', { skipReason: REPO_STATE_SKIPS.GATE_UNREADABLE });if (owned) await record('pending', 'existing-completion-owner');diff --git a/server/services/agentRepoStateVerification.test.js b/server/services/agentRepoStateVerification.test.jsindex 1cfcb3e4a9..770d595b20 100644--- a/server/services/agentRepoStateVerification.test.js+++ b/server/services/agentRepoStateVerification.test.js@@ -1,3 +1,5 @@+vi.mock('../lib/gitRepositoryIdentity.js', () => ({ readGitCommonDirectory: vi.fn(async () => '/repo/.git') }));+import { readGitCommonDirectory } from '../lib/gitRepositoryIdentity.js';vi.mock('./branchCompletionPolicy.js', async () => ({...await vi.importActual('./branchCompletionPolicy.js'),readBranchCompletionPolicies: vi.fn(async () => []),@@ -147,6 +149,7 @@ const run = (overrides = {}) => verifyAgentRepoState({beforeEach(() => {vi.clearAllMocks();+ readGitCommonDirectory.mockReset().mockResolvedValue('/repo/.git');retryCompletionCheckoutCapture.mockReset().mockResolvedValue(false);getAgentRecord.mockReset().mockResolvedValue(null);findMissingCheckoutPreservation.mockResolvedValue(null);@@ -248,6 +251,37 @@ describe('verifyAgentRepoState — clean runs', () => {expect(await run({ success: false, agentState: state, task: own })).toMatchObject({ skipReason: 'follow-up-pending' });});+ it('ignores independent repositories with the same branch and deduplicates app reads per audit', async () => {+ getAppById.mockImplementation(async id => ({ id, repoPath: id === 'demo-app' ? '/repo' : '/other' }));+ readGitCommonDirectory.mockImplementation(async path => `${path}/.git`);+ queuedTasks(['first', 'second'].map(id => ({ id, status: 'pending', metadata: { app: 'other-app', existingBranch: BRANCH } })));+ expect((await run()).skipReason).not.toBe(REPO_STATE_SKIPS.FOLLOW_UP_PENDING);+ expect(getAppById.mock.calls.filter(([id]) => id === 'other-app')).toHaveLength(1);+ expect(readGitCommonDirectory).toHaveBeenCalledWith('/other');+ });++ it.each(['/alias', '/linked-worktree'])('preserves another app sharing the common directory through %s', async repoPath => {+ getAppById.mockImplementation(async id => ({ id, repoPath: id === 'demo-app' ? '/repo' : repoPath }));+ queuedTasks([{ status: 'pending', metadata: { app: 'alias-app', existingBranch: BRANCH } }]);+ expect(await run()).toMatchObject({ skipReason: REPO_STATE_SKIPS.FOLLOW_UP_PENDING });+ expect(readGitCommonDirectory).toHaveBeenCalledWith(repoPath);+ });++ it.each(['missing-scope', 'missing-app', 'app-read-failed', 'missing-path', 'unreadable-target', 'unreadable-candidate'])('holds when ownership identity is unknown: %s', async failure => {+ getAppById.mockImplementation(async id => {+ if (id === 'demo-app') return { id, repoPath: '/repo' };+ if (failure === 'app-read-failed') throw new Error('unreadable');+ if (failure === 'missing-app') return null;+ return { id, repoPath: failure === 'missing-path' ? undefined : '/other' };+ });+ readGitCommonDirectory.mockImplementation(async path => !path+ || path === (failure === 'unreadable-target' ? '/repo' : failure === 'unreadable-candidate' ? '/other' : '') ? null : `${path}/.git`);+ queuedTasks([{ status: 'pending', metadata: { app: failure === 'missing-scope' ? undefined : 'other-app', existingBranch: BRANCH } }]);+ expect(await run()).toMatchObject({ skipReason: REPO_STATE_SKIPS.GATE_UNREADABLE });+ expect(retireInventoriedCheckout).not.toHaveBeenCalled();+ expect(addTask).not.toHaveBeenCalled();+ });+it.each([[], ['Branch preserved by ordinary cleanup']])('settles its cleanup handoff after archive and integration proof despite warnings %j', async cleanupWarnings => {const completed = { version: 1, agentId: 'agent-1', repoPath: '/repo', branch: BRANCH, path: WORKTREE, head: HEAD,startedAt: CREATED_AT, capturedAt: CREATED_AT };@@ -559,7 +593,7 @@ describe('verifyAgentRepoState — never fires', () => {});it('defers while a review-loop follow-up still owns the branch', async () => {- queuedTasks([{ status: 'pending', metadata: { reviewLoopFollowUp: true, reviewLoopPRBranch: BRANCH } }]);+ queuedTasks([{ status: 'pending', metadata: { app: 'demo-app', reviewLoopFollowUp: true, reviewLoopPRBranch: BRANCH } }]);existsSync.mockReturnValue(true);const result = await run({ task: task({ prCompletion: 'review-then-merge' }) });@@ -569,7 +603,7 @@ describe('verifyAgentRepoState — never fires', () => {});it('defers while a retry holds the branch as its resume pointer', async () => {- queuedTasks([{ status: 'pending', metadata: { existingBranch: BRANCH } }]);+ queuedTasks([{ status: 'pending', metadata: { app: 'demo-app', existingBranch: BRANCH } }]);existsSync.mockReturnValue(true);const result = await run();expect(result.skipReason).toBe(REPO_STATE_SKIPS.FOLLOW_UP_PENDING);@@ -667,7 +701,7 @@ describe('verifyAgentRepoState — never fires', () => {it('defers while a CHALLENGED task still holds the branch', async () => {// `challenged` is a parked-for-dispute status, not a terminal one: the task// keeps its branch and resumes on it.- queuedTasks([{ status: 'challenged', metadata: { existingBranch: BRANCH } }]);+ queuedTasks([{ status: 'challenged', metadata: { app: 'demo-app', existingBranch: BRANCH } }]);existsSync.mockReturnValue(true);const result = await run();