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: preserve reconciliation archives and exact retirement evidence

[._.]/ Adam Eivyda6983db66d7
diff --git a/server/lib/reconcileRetirementEvidence.js b/server/lib/reconcileRetirementEvidence.js
index 926b71939c..3de922923b 100644
--- a/server/lib/reconcileRetirementEvidence.js
+++ b/server/lib/reconcileRetirementEvidence.js
@@ -8,7 +8,7 @@ export const isRetirementObligation = row => ['retirement-review-pending', 'reti
'retirement-provenance-unverified'].includes(row?.reason);
export const matchingRetirementReceipts = (outcome, release) => [...(outcome?.retired || []), ...Object.values(outcome?.retirementReceiptEvidence || {})].filter(row =>
- (sameRetirementCheckout(row, release) || (!release.head && !release.path && release.branch && row.branch === release.branch)) && row.branchDeleted === true
+ sameRetirementCheckout(row, release) && row.branchDeleted === true
&& typeof row.archiveDir === 'string' && row.archiveDir.length > 0
&& Number.isFinite(Date.parse(row.retiredAt)));
diff --git a/server/services/branchReconcile.test.js b/server/services/branchReconcile.test.js
index cb4b6df0c1..b7b4cae62a 100644
--- a/server/services/branchReconcile.test.js
+++ b/server/services/branchReconcile.test.js
@@ -2977,11 +2977,14 @@ describe('describeIdleReconcilePark', () => {
expect(out).toEqual({ reason: 'branches-blocked', heldBackMerged: [], counts: { heldBranches: 3, heldDetached: 0 }, skipCauses: { 'cleanup-disabled': 1, 'not-merged-on-recheck': 1, 'branch-delete-failed': 1 }, remaining: [{ branch: 'a', reason: 'cleanup-disabled' }, { branch: 'b', reason: 'not-merged-on-recheck' }, { branch: 'c', reason: 'branch-delete-failed' }], notLaterThan: null });
});
- it('includes bounded archive capacity evidence in the remaining checkout status', () => {
+ it('preserves archive capacity and generation evidence in the remaining checkout status', () => {
const archiveLimit = { scope: 'content', kind: 'total', limitBytes: 250 * 1024 * 1024, observedBytes: 264 * 1024 * 1024 };
- const out = describeIdleReconcilePark([{ branch: 'feature/example', reason: 'retirement-archive-limit-exceeded', archiveLimit }]);
+ const row = { branch: 'feature/example', reason: 'retirement-archive-limit-exceeded', archiveLimit,
+ createdAt: '2026-10-24T00:00:00Z', checkoutIdentity: 'identity', checkoutIncarnation: { pointer: 'original' },
+ preservationReceipt: { archiveDir: '/archive' }, preservationEvidence: { status: 'unresolved' }, checkoutMissing: true, branchMissing: true };
+ const out = describeIdleReconcilePark([row]);
expect(out.skipCauses).toEqual({ 'retirement-archive-limit-exceeded': 1 });
- expect(out.remaining).toEqual([{ branch: 'feature/example', reason: 'retirement-archive-limit-exceeded', archiveLimit }]);
+ expect(out.remaining).toEqual([row]);
});
it('ignores an unreadable retryAt rather than parking on NaN', () => {
diff --git a/server/services/branchReconcileCompletion.js b/server/services/branchReconcileCompletion.js
index 6d816efe1f..2f0dc3d045 100644
--- a/server/services/branchReconcileCompletion.js
+++ b/server/services/branchReconcileCompletion.js
@@ -78,10 +78,6 @@ export async function settleBranchReconcileRun(agent) {
emitLog(uncertain ? 'warn' : 'info',
`Branch reconciliation completion: cleaned ${result.cleaned.length}, superseded ${result.reapedSuperseded?.length || 0}, remaining ${remaining}${uncertain ? '; scan incomplete' : ''}`,
{ appId: app.id, analysisType: type, counts: holds.counts, skipCauses: holds.skipCauses });
- const { settleAndPruneBranchReconcileArchives } = await import('./branchReconcileRefresh.js');
- await settleAndPruneBranchReconcileArchives(app.id, app.repoPath, {
- defaultBranch: result.defaultBranch, worktreeInventory: result.worktreeInventory,
- }).catch(() => null);
return result;
}
diff --git a/server/services/branchReconcileRefresh.js b/server/services/branchReconcileRefresh.js
index aefd733982..3bf5d0b693 100644
--- a/server/services/branchReconcileRefresh.js
+++ b/server/services/branchReconcileRefresh.js
@@ -1,4 +1,3 @@
-import { join } from 'path';
import { ServerError } from '../lib/errorHandler.js';
import { getAppById } from './apps.js';
import { getActiveAgentIds } from './agentState.js';
@@ -7,139 +6,6 @@ import { reconcile, buildActiveOwnerIds, describeIdleReconcilePark } from './bra
import { recordBranchReconcileOutcome, getBranchReconcileInventory } from './taskSchedule.js';
import { cosEvents } from './cosEvents.js';
-/**
- * Programmatically settle completed/integrated obligations and prune unneeded archives.
- */
-export async function settleAndPruneBranchReconcileArchives(appId, repoPath, { defaultBranch = 'main', worktreeInventory = [] } = {}) {
- const [{ getBranchReconcileOutcome, recordBranchReconcileOutcome: recordOutcome }, { execGit }, { hasBranchMergeEvidence }, { PATHS }, { readdir, readFile, rm }] = await Promise.all([
- import('./taskSchedule.js'),
- import('../lib/execGit.js'),
- import('./git.js'),
- import('../lib/paths.js'),
- import('fs/promises'),
- ]);
-
- const outcome = await getBranchReconcileOutcome(appId);
- if (!outcome || !Array.isArray(outcome.retirementObligations) || !outcome.retirementObligations.length) {
- return outcome;
- }
-
- const roots = [
- join(PATHS.cos, 'held-checkout-archives'),
- join(PATHS.cos, 'branch-retirement-archives'),
- ];
- const diskArchives = [];
- for (const root of roots) {
- const names = await readdir(root, { withFileTypes: true }).catch(() => []);
- for (const d of names) {
- if (!d.isDirectory()) continue;
- const dir = join(root, d.name);
- try {
- const manifest = JSON.parse(await readFile(join(dir, 'manifest.json'), 'utf8'));
- if (manifest.repoPath === repoPath) {
- diskArchives.push({ dir, root, ...manifest });
- }
- } catch {}
- }
- }
-
- const existingLocalRefs = await execGit(['show-ref', '--heads'], repoPath)
- .then(r => r.stdout.split('\n').map(l => l.split(' ')[1]).filter(Boolean))
- .catch(() => []);
- const localRefNames = new Set(existingLocalRefs.map(ref => ref.replace(/^refs\/heads\//, '')));
-
- const survivingObligations = [];
- const settledReceipts = [];
-
- for (const obligation of outcome.retirementObligations) {
- const branchPresent = obligation.branch && localRefNames.has(obligation.branch);
- const checkoutPresent = obligation.path && worktreeInventory?.some(t => t.path === obligation.path);
-
- if (branchPresent || checkoutPresent) {
- survivingObligations.push(obligation);
- continue;
- }
-
- const alreadyReceipted = [...(outcome.retired || []), ...Object.values(outcome.retirementReceiptEvidence || {}), ...(outcome.recoveredPreservations || [])].some(r =>
- (obligation.branch && r.branch === obligation.branch) || (obligation.path && r.path === obligation.path) || (obligation.head && r.head === obligation.head)
- );
- if (alreadyReceipted) {
- settledReceipts.push(obligation);
- continue;
- }
-
- const matchingArchive = diskArchives.find(a =>
- (obligation.branch && a.branch === obligation.branch)
- || (obligation.path && a.path === obligation.path)
- || (obligation.head && (a.head === obligation.head || a.expectedHead === obligation.head))
- );
- if (matchingArchive) {
- settledReceipts.push(obligation);
- continue;
- }
-
- if (!obligation.head && !obligation.path) {
- settledReceipts.push(obligation);
- continue;
- }
-
- if (obligation.head && /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(obligation.head)) {
- const commitExists = await execGit(['cat-file', '-e', `${obligation.head}^{commit}`], repoPath).then(() => true, () => false);
- if (commitExists) {
- const merged = await hasBranchMergeEvidence(repoPath, obligation.head, defaultBranch).catch(() => false);
- if (merged) {
- settledReceipts.push(obligation);
- continue;
- }
- }
- }
-
- survivingObligations.push(obligation);
- }
-
- if (settledReceipts.length > 0) {
- const { recordHeldCheckoutRetirement } = await import('./taskSchedule.js');
- for (const settled of settledReceipts) {
- const archiveDir = settled.archiveDir
- || settled.preservationReceipt?.archiveDir
- || diskArchives.find(a => (settled.branch && a.branch === settled.branch) || (settled.path && a.path === settled.path))?.dir
- || null;
- await recordHeldCheckoutRetirement(appId, {
- path: settled.path,
- branch: settled.branch,
- head: settled.head,
- branchDeleted: true,
- archiveDir,
- checkoutIdentity: settled.checkoutIdentity,
- }).catch(() => null);
- }
- const current = await getBranchReconcileOutcome(appId);
- if (current && (!current.remaining || !current.remaining.length) && (!current.retirementObligations || !current.retirementObligations.length)) {
- await recordOutcome(appId, {
- status: 'drained',
- reason: 'no-remaining-holds',
- retirementObligations: [],
- remaining: [],
- nextAction: null,
- });
- }
- }
-
- const survivingRefs = new Set();
- for (const ob of survivingObligations) {
- if (ob.preservationReceipt?.archiveDir) survivingRefs.add(ob.preservationReceipt.archiveDir);
- for (const a of ob.preservationEvidence?.archives || []) {
- if (a.archiveDir) survivingRefs.add(a.archiveDir);
- }
- }
-
- for (const archive of diskArchives) {
- if (!survivingRefs.has(archive.dir)) {
- await rm(archive.dir, { recursive: true, force: true }).catch(() => null);
- }
- }
-}
-
/** Refresh evidence only: no cleanup, provider dispatch, or delivery recovery. */
export async function refreshBranchReconcileInventory(appId) {
const app = await getAppById(appId);
@@ -170,9 +36,6 @@ export async function refreshBranchReconcileInventory(appId) {
remoteInventory: result.orphanRemotes ?? { reaped: [], reported: [] },
nextAction: inventory.remaining.length ? 'Resolve the listed local holds, then refresh inventory.' : null,
});
- await settleAndPruneBranchReconcileArchives(appId, app.repoPath, {
- defaultBranch: result.defaultBranch, worktreeInventory: result.worktreeInventory,
- });
const outcome = await getBranchReconcileInventory(appId);
cosEvents.emit('schedule:changed', { taskType: 'branch-reconcile', appId });
return { appId, outcome };
diff --git a/server/services/branchReconcileRefresh.test.js b/server/services/branchReconcileRefresh.test.js
index ffbe8c08d1..3a7bed8e2e 100644
--- a/server/services/branchReconcileRefresh.test.js
+++ b/server/services/branchReconcileRefresh.test.js
@@ -71,23 +71,29 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('branch reconciliation inventory refresh
await expect(refreshBranchReconcileInventory('missing')).rejects.toMatchObject({ status: 404 });
});
- it('programmatically settles already-integrated obligations and prunes unneeded archives', async () => {
+ it('retains merged missing-source obligations and every archive until preservation is verified', async () => {
getApp.mockImplementation(async id => ['example', 'settled-app'].includes(id) ? { id, repoPath } : null);
await execGit(['branch', '-D', 'fix/current'], repoPath).catch(() => null);
const head = (await execGit(['rev-parse', 'HEAD'], repoPath)).stdout.trim();
const settledArchiveDir = join(PATHS.cos, 'held-checkout-archives', 'test-settled-archive');
await mkdir(settledArchiveDir, { recursive: true });
await writeFile(join(settledArchiveDir, 'manifest.json'), JSON.stringify({ repoPath, branch: 'claim/issue-settled', head }));
+ await writeFile(join(settledArchiveDir, 'ignored.txt'), 'only preserved copy');
+ const unrelatedArchiveDir = join(PATHS.cos, 'held-checkout-archives', 'unrelated-archive');
+ await mkdir(unrelatedArchiveDir, { recursive: true });
+ await writeFile(join(unrelatedArchiveDir, 'manifest.json'), JSON.stringify({ repoPath, branch: 'claim/other', head }));
+ await writeFile(join(unrelatedArchiveDir, 'ignored.txt'), 'unrelated preserved copy');
const integrated = { branch: 'claim/issue-settled', path: join(scratch, 'integrated'), head, locked: false, lockReason: null, reason: 'checkout-retained' };
await recordBranchReconcileOutcome('settled-app', { status: 'incomplete', remaining: [integrated] });
const result = await refreshBranchReconcileInventory('settled-app');
- expect(result.outcome.retirementObligations || []).toEqual([]);
- expect(result.outcome.remaining || []).toEqual([]);
- expect(result.outcome.status).toBe('drained');
-
- const { existsSync } = await import('fs');
- expect(existsSync(settledArchiveDir)).toBe(false);
+ expect(result.outcome).toMatchObject({ status: 'incomplete',
+ retirementObligations: [{ ...integrated, reason: 'retirement-provenance-unverified' }],
+ remaining: [{ ...integrated, reason: 'retirement-provenance-unverified' }],
+ });
+ expect(result.outcome.retired || []).toEqual([]);
+ expect(await readFile(join(settledArchiveDir, 'ignored.txt'), 'utf8')).toBe('only preserved copy');
+ expect(await readFile(join(unrelatedArchiveDir, 'ignored.txt'), 'utf8')).toBe('unrelated preserved copy');
});
});
diff --git a/server/services/cosTaskPreStepBlocks.js b/server/services/cosTaskPreStepBlocks.js
index 2888a7fa5b..e2c548821e 100644
--- a/server/services/cosTaskPreStepBlocks.js
+++ b/server/services/cosTaskPreStepBlocks.js
@@ -558,7 +558,6 @@ export async function resolveBranchReconcileBlock(app, taskType, metadata, taskS
result.skipped = result.skipped.filter(row => !retiredNames.has(row.branch));
result.worktreeInventory = result.worktreeInventory.filter(row => !retiredNames.has(row.branch));
result.cleaned.push(...retiredNames);
- latestAbsentObligations = latestAbsentObligations.filter(release => !retiredNames.has(release.branch));
}
// CI waiting and an open PR alone do not require a provider. Existing local
// receipts were nudged above; only current exact-head code repair is cognitive.
@@ -617,10 +616,6 @@ export async function resolveBranchReconcileBlock(app, taskType, metadata, taskS
nextAction: 'Continue the bounded sweep and rescan after the final batch.',
});
if (allActionable.length === 0) {
- const { settleAndPruneBranchReconcileArchives } = await import('./branchReconcileRefresh.js');
- await settleAndPruneBranchReconcileArchives(app.id, app.repoPath, {
- defaultBranch: result.defaultBranch, worktreeInventory: result.worktreeInventory,
- }).catch(() => null);
// Definitive idle: nothing in-flight to drive. Park on the recheck cadence,
// clearing the progress signature so a fresh set later dispatches and zeroing the
// dispatch budget — this drain converged, so the next one gets a full one.
@@ -705,7 +700,7 @@ export async function resolveBranchReconcileBlock(app, taskType, metadata, taskS
metadata.perpetual = true;
metadata.reconcileRetirements = actionable.filter(branch => branch.retirement).map(branch => ({
...branch.retirement,
- createdAt: dispatchedOutcome.retirementObligations?.find(row => sameRetirementObservation(row, branch.retirement.release) || sameRetirementCheckout(row, branch.retirement.release))?.createdAt,
+ createdAt: dispatchedOutcome.retirementObligations?.find(row => sameRetirementObservation(row, branch.retirement.release))?.createdAt,
}));
const supersededBlock = formatSupersededForPrompt(result.superseded || []);
const block = [
diff --git a/server/services/heldCheckoutRecovery.js b/server/services/heldCheckoutRecovery.js
index e97ac64817..393e76aea8 100644
--- a/server/services/heldCheckoutRecovery.js
+++ b/server/services/heldCheckoutRecovery.js
@@ -884,13 +884,17 @@ async function archiveSnapshots(tree, repoPath, missingRoot, work = archiveWork(
*/
export async function preserveMergedCheckout(repoPath, tree, defaultBranch, { cosDir, signal } = {}) {
if (!tree?.head || (!tree.branch && tree.detached !== true) || tree.locked) throw new Error('checkout-identity-unavailable');
+ const checkoutIdentity = await readRetirementCheckoutIdentity(tree.path);
const branch = shortBranch(tree.branch);
const missingRoot = await missingCheckoutAdministration(repoPath, tree.path);
const archive = await archiveCheckout({ repoPath, tree, branch, defaultBranch, cosDir, missingRoot, work: archiveWork(signal) });
return {
archiveDir: archive.dir,
+ checkoutIdentity,
async verify(holder) {
if (!holder || holder.head !== tree.head || holder.branch !== tree.branch || Boolean(holder.detached) !== Boolean(tree.detached)) return 'worktree-holder-changed';
+ // Missing-root recovery archives Git administration without a live pointer.
+ if (checkoutIdentity && await readRetirementCheckoutIdentity(tree.path) !== checkoutIdentity) return 'checkout-identity-changed';
const [content, administration] = await archiveSnapshots(tree, repoPath, missingRoot, archiveWork(signal));
return content.fingerprint === archive.fingerprint && administration.fingerprint === archive.administrationFingerprint
? null : 'checkout-content-changed';
@@ -1413,7 +1417,7 @@ export async function retirePendingMergeCheckout({ repoPath, release, prUrl, exp
await recordWorkspaceCheckoutRetirement(repoPath, {
path: release.path, branch: release.branch ?? null, head: release.head,
branchDeleted: result.branchDeleted, archiveDir: result.archiveDir, checkoutIdentity: result.checkoutIdentity,
- }).catch(() => null);
+ });
}
return result;
}
diff --git a/server/services/taskSchedule.js b/server/services/taskSchedule.js
index d734592478..2e06af6e3b 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -1005,9 +1005,7 @@ export async function recordHeldCheckoutRetirement(appId, { path, branch, branch
remaining: Array.isArray(outcome.remaining)
? outcome.remaining.filter(entry => retirementObligations.some(row => sameRetirementObservation(row, entry))
|| !(sameRetirementObservation(entry, receipt)
- || (!entry.checkoutIdentity && sameRetirementCheckout(entry, receipt))
- || (!isObligationRow(entry) && ((path && entry.path === path)
- || (branchDeleted && branch && entry.branch === branch && (!entry.path || !path || entry.path === path))))))
+ || (!entry.checkoutIdentity && sameRetirementCheckout(entry, receipt))))
: outcome.remaining ?? null,
retired,
};
@@ -1016,12 +1014,12 @@ export async function recordHeldCheckoutRetirement(appId, { path, branch, branch
}
/**
- * Record a checkout retirement across any matching app for a workspace path or branch.
+ * Record a checkout retirement across apps observing the exact checkout tuple.
* Settles stale inventory rows left behind when an active run finishes and removes its worktree.
*/
export async function recordWorkspaceCheckoutRetirement(repoPath, receipt) {
if (!repoPath || (!receipt?.path && !receipt?.branch)) return null;
- const schedule = await loadSchedule().catch(() => null);
+ const schedule = await loadSchedule();
const perApp = schedule?.executions?.['task:branch-reconcile']?.perApp;
if (!perApp || typeof perApp !== 'object') return null;
let updated = null;
@@ -1029,7 +1027,7 @@ export async function recordWorkspaceCheckoutRetirement(repoPath, receipt) {
const outcome = record?.branchReconcileOutcome;
if (!outcome) continue;
const rows = [...(outcome.remaining || []), ...(outcome.retirementObligations || [])];
- if (!rows.some(row => (receipt.path && row.path === receipt.path) || (receipt.branch && row.branch === receipt.branch))) continue;
+ if (!rows.some(row => sameRetirementCheckout(row, receipt))) continue;
const app = await getAppById(appId).catch(() => null);
if (app?.repoPath !== repoPath) continue;
updated = await recordHeldCheckoutRetirement(appId, receipt);
diff --git a/server/services/taskSchedule.test.js b/server/services/taskSchedule.test.js
index 5c46affc3a..547807fb0f 100644
--- a/server/services/taskSchedule.test.js
+++ b/server/services/taskSchedule.test.js
@@ -158,6 +158,7 @@ import {
getBranchReconcileOutcome,
recordInitializedRetirementRecovery,
recordHeldCheckoutRetirement,
+ recordWorkspaceCheckoutRetirement,
applyOnDemandRunResets,
queuePerpetualRefill,
isRefillRequest,
@@ -3435,6 +3436,48 @@ describe('taskSchedule', () => {
vi.useRealTimers();
});
+ it('retains an unidentified obligation instead of borrowing a branch-name receipt', async () => {
+ let saved = { version: 2, tasks: {}, executions: {}, templates: [] };
+ readJSONFile.mockImplementation(async () => structuredClone(saved));
+ writeFile.mockImplementation(async (_path, contents) => { saved = JSON.parse(contents); });
+ const row = { branch: 'fix/example', createdAt: '2026-01-01T00:00:00Z', reason: 'retirement-review-pending' };
+ await recordHeldCheckoutRetirement('app-1', { branch: row.branch, path: '/example/checkout', head: 'a'.repeat(40),
+ branchDeleted: true, archiveDir: '/example/archive' });
+ const result = await recordBranchReconcileOutcome('app-1', { status: 'incomplete', retirementObligations: [row] });
+ expect(result.retirementObligations).toEqual([{ ...row, reason: 'retirement-receipt-unverified' }]);
+ });
+
+ it('routes workspace retirement only to the matching repository and exact checkout tuple', async () => {
+ let saved = { version: 2, tasks: {}, executions: {}, templates: [] };
+ readJSONFile.mockImplementation(async () => structuredClone(saved));
+ writeFile.mockImplementation(async (_path, contents) => { saved = JSON.parse(contents); });
+ const row = { branch: 'fix/example', path: '/example/checkout', head: 'a'.repeat(40),
+ checkoutIdentity: 'original', reason: 'worktree-locked' };
+ await recordBranchReconcileOutcome('matching', { status: 'incomplete', remaining: [row] });
+ await recordBranchReconcileOutcome('different-head', { status: 'incomplete', remaining: [{ ...row, head: 'b'.repeat(40) }] });
+ await recordBranchReconcileOutcome('different-repo', { status: 'incomplete', remaining: [row] });
+ getAppById.mockImplementation(async id => ({ repoPath: id === 'different-repo' ? '/other/repo' : '/example/repo' }));
+ await recordWorkspaceCheckoutRetirement('/example/repo', { ...row, branchDeleted: true, archiveDir: '/example/archive' });
+ const perApp = saved.executions['task:branch-reconcile'].perApp;
+ expect(perApp.matching.branchReconcileOutcome.remaining).toEqual([]);
+ expect(perApp['different-head'].branchReconcileOutcome).toMatchObject({ remaining: [{ ...row, head: 'b'.repeat(40) }] });
+ expect(perApp['different-head'].branchReconcileOutcome.retired).toBeUndefined();
+ expect(perApp['different-repo'].branchReconcileOutcome.remaining).toEqual([row]);
+ expect(perApp['different-repo'].branchReconcileOutcome.retired).toBeUndefined();
+ });
+
+ it('keeps a current inventory observation when a different-head retirement arrives at the same path', async () => {
+ let saved = { version: 2, tasks: {}, executions: {}, templates: [] };
+ readJSONFile.mockImplementation(async () => structuredClone(saved));
+ writeFile.mockImplementation(async (_path, contents) => { saved = JSON.parse(contents); });
+ const current = { branch: 'fix/example', path: '/example/checkout', head: 'b'.repeat(40),
+ checkoutIdentity: 'recreated', reason: 'worktree-locked' };
+ await recordBranchReconcileOutcome('app-1', { status: 'incomplete', remaining: [current] });
+ const result = await recordHeldCheckoutRetirement('app-1', { ...current, head: 'a'.repeat(40),
+ checkoutIdentity: 'original', branchDeleted: true, archiveDir: '/example/archive' });
+ expect(result.remaining).toEqual([current]);
+ });
+
it('keeps both incarnations when recreation is observed before the original receipt arrives', async () => {
let saved = { version: 2, tasks: {}, executions: {}, templates: [] };
readJSONFile.mockImplementation(async () => structuredClone(saved));
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.js
index f6797f4cfb..18590fdef8 100644
--- a/server/services/worktreeManager.js
+++ b/server/services/worktreeManager.js
@@ -1596,7 +1596,7 @@ async function removeWorktreeNow(agentId, sourceWorkspace, branchName, options,
const hold = await checkHold(tree.head);
if (hold) throw new Error(hold);
const archive = await preserveMergedCheckout(sourceWorkspace, tree, null);
- return { ...archive, head: tree.head,
+ return { ...archive, head: tree.head, path: tree.path, branch: detached ? null : branchName,
verify: async holder => await checkHold(tree.head) || await archive.verify(holder) };
};
// One archive between two critical sections. `admit` (under the lock, after the
@@ -1833,10 +1833,13 @@ async function removeWorktreeNow(agentId, sourceWorkspace, branchName, options,
if (branchCleaned) console.log(`🌳 Removed worktree for ${agentId}${merged ? ' (merged)' : ''}`);
if (preservation.archiveDir) {
const { recordWorkspaceCheckoutRetirement } = await import('./taskSchedule.js');
+ // A completed cleanup attempt may retain a moved or newly held branch.
+ const ref = preservation.branch && await execGit(['show-ref', '--verify', '--quiet', `refs/heads/${preservation.branch}`],
+ sourceWorkspace, { ignoreExitCode: true }).catch(() => null);
await recordWorkspaceCheckoutRetirement(sourceWorkspace, {
- path: worktreePath, branch: branchName, head: preservation.head,
- branchDeleted: Boolean(branchCleaned), archiveDir: preservation.archiveDir,
- }).catch(() => null);
+ path: preservation.path, branch: preservation.branch, head: preservation.head,
+ branchDeleted: ref?.exitCode === 1, archiveDir: preservation.archiveDir, checkoutIdentity: preservation.checkoutIdentity,
+ }).catch(error => { warnings.push(`Retirement receipt not recorded: ${error.message}`); });
}
return { merged, removed: true, uncommittedSaved: false, warnings };
},
@@ -2396,9 +2399,9 @@ async function cleanupExternalRepoWorktrees(readActiveIds, alreadyHandled, readO
if (ok && preservation?.archiveDir) {
const { recordWorkspaceCheckoutRetirement } = await import('./taskSchedule.js');
await recordWorkspaceCheckoutRetirement(parentRepo, {
- path: worktreePath, branch: branchName, head: wt.head,
- branchDeleted: Boolean(deleted), archiveDir: preservation.archiveDir,
- }).catch(() => null);
+ path: wt.path, branch: branchName, head: wt.head,
+ branchDeleted: Boolean(deleted), archiveDir: preservation.archiveDir, checkoutIdentity: preservation.checkoutIdentity,
+ });
}
return ok;
},
diff --git a/server/services/worktreeManager.test.js b/server/services/worktreeManager.test.js
index e7f3ae03f7..6e2620bce4 100644
--- a/server/services/worktreeManager.test.js
+++ b/server/services/worktreeManager.test.js
@@ -11,6 +11,8 @@ const preservedBranch = () => ({ archiveDir: '/branch-archive', verify: async ()
const preserveBranchMock = vi.fn(async () => preservedBranch());
vi.mock('../lib/branchRetirementArchive.js', () => ({ preserveBranchRetirement: (...args) => preserveBranchMock(...args) }));
vi.mock('./heldCheckoutRecovery.js', () => ({ preserveMergedCheckout: (...args) => preserveCheckoutMock(...args) }));
+const retirementReceiptMock = vi.hoisted(() => vi.fn(async () => null));
+vi.mock('./taskSchedule.js', () => ({ recordWorkspaceCheckoutRetirement: retirementReceiptMock }));
const completionOwnersMock = vi.fn(async () => []);
vi.mock('./cosClaimOwnershipState.js', async importOriginal => ({ ...await importOriginal(), readClaimOwnershipAgents: (...args) => completionOwnersMock(...args) }));
const completionHoldMock = vi.fn(async () => null);
@@ -834,7 +836,8 @@ describe('removeWorktree identity, dirt and branch preservation', () => {
execGitMock.mock.calls.some(([args]) => JSON.stringify(args) === JSON.stringify(subcommandArgs));
beforeEach(() => {
- preserveCheckoutMock.mockReset().mockResolvedValue({ archiveDir: '/archive', verify: async () => null });
+ preserveCheckoutMock.mockReset().mockResolvedValue({ archiveDir: '/archive', checkoutIdentity: 'original', verify: async () => null });
+ retirementReceiptMock.mockClear();
completionHoldMock.mockReset().mockResolvedValue(null);
completionOwnersMock.mockReset().mockResolvedValue([]);
getDefaultBranchMock.mockResolvedValue('main');
@@ -1470,6 +1473,10 @@ describe('removeWorktree identity, dirt and branch preservation', () => {
expect(result.removed).toBe(true);
expect(result.warnings).toEqual([]);
+ expect(retirementReceiptMock).toHaveBeenCalledWith('/repo', {
+ path: join(PATHS.worktrees, 'agent-x'), branch: 'cos/task-1/agent-x', head: 'a'.repeat(40),
+ archiveDir: '/archive', checkoutIdentity: 'original', branchDeleted: false,
+ });
});
it('removes a completed worktree whose only dirt is the consumed sentinel', async () => {