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: programmatically settle branch reconcile archives and prevent obligation resurrection

Adam Eivyf518c49c4602
diff --git a/server/lib/reconcileRetirementEvidence.js b/server/lib/reconcileRetirementEvidence.js
index ddb5185594..926b71939c 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) && row.branchDeleted === true
+ (sameRetirementCheckout(row, release) || (!release.head && !release.path && release.branch && row.branch === release.branch)) && row.branchDeleted === true
&& typeof row.archiveDir === 'string' && row.archiveDir.length > 0
&& Number.isFinite(Date.parse(row.retiredAt)));
@@ -66,7 +66,9 @@ export function retainRetirementObligations(outcome, additional, now) {
.filter(entry => sameRetirementCheckout(entry, row))
.map(entry => Date.parse(entry.verifiedAt || entry.archivedAt)),
].filter(Number.isFinite);
- const observed = Number.isFinite(Date.parse(row.observedAt)) ? Date.parse(row.observedAt) : Date.parse(now);
+ const fallbackObserved = row.reason === 'retirement-provenance-unverified' && Number.isFinite(Date.parse(outcome?.observedAt))
+ ? Date.parse(outcome.observedAt) : Date.parse(now);
+ const observed = Number.isFinite(Date.parse(row.observedAt)) ? Date.parse(row.observedAt) : fallbackObserved;
return { ...row, createdAt: new Date(Math.max(observed, ...earlier.map(time => time + 1))).toISOString() };
});
}
diff --git a/server/services/branchReconcile.js b/server/services/branchReconcile.js
index 8cb1c27023..6ce5bac95c 100644
--- a/server/services/branchReconcile.js
+++ b/server/services/branchReconcile.js
@@ -1099,7 +1099,13 @@ export function describeIdleReconcilePark(skipped = [], heldLive = [], { wip = [
...(entry.issue && { issue: entry.issue }),
...((entry.head || entry.tip) && { head: entry.head || entry.tip }),
...(entry.observedAt && { observedAt: entry.observedAt }),
+ ...(entry.createdAt && { createdAt: entry.createdAt }),
...(entry.checkoutIdentity && { checkoutIdentity: entry.checkoutIdentity }),
+ ...(entry.checkoutIncarnation && { checkoutIncarnation: entry.checkoutIncarnation }),
+ ...(entry.preservationReceipt && { preservationReceipt: entry.preservationReceipt }),
+ ...(entry.preservationEvidence && { preservationEvidence: entry.preservationEvidence }),
+ ...(entry.checkoutMissing && { checkoutMissing: true }),
+ ...(entry.branchMissing && { branchMissing: true }),
...(entry.locked !== undefined && { locked: entry.locked, lockReason: entry.lockReason ?? null }),
...(entry.detached && { detached: true }),
...(entry.managed !== undefined && { managed: entry.managed }),
diff --git a/server/services/branchReconcileCompletion.js b/server/services/branchReconcileCompletion.js
index 2f0dc3d045..6d816efe1f 100644
--- a/server/services/branchReconcileCompletion.js
+++ b/server/services/branchReconcileCompletion.js
@@ -78,6 +78,10 @@ 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 3bf5d0b693..aefd733982 100644
--- a/server/services/branchReconcileRefresh.js
+++ b/server/services/branchReconcileRefresh.js
@@ -1,3 +1,4 @@
+import { join } from 'path';
import { ServerError } from '../lib/errorHandler.js';
import { getAppById } from './apps.js';
import { getActiveAgentIds } from './agentState.js';
@@ -6,6 +7,139 @@ 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);
@@ -36,6 +170,9 @@ 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 a1d17be171..ffbe8c08d1 100644
--- a/server/services/branchReconcileRefresh.test.js
+++ b/server/services/branchReconcileRefresh.test.js
@@ -70,4 +70,24 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('branch reconciliation inventory refresh
getApp.mockResolvedValueOnce(null);
await expect(refreshBranchReconcileInventory('missing')).rejects.toMatchObject({ status: 404 });
});
+
+ it('programmatically settles already-integrated obligations and prunes unneeded archives', 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 }));
+
+ 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);
+ });
});
diff --git a/server/services/cosTaskPreStepBlocks.js b/server/services/cosTaskPreStepBlocks.js
index de6c13293e..2888a7fa5b 100644
--- a/server/services/cosTaskPreStepBlocks.js
+++ b/server/services/cosTaskPreStepBlocks.js
@@ -535,17 +535,21 @@ export async function resolveBranchReconcileBlock(app, taskType, metadata, taskS
const absentObligations = unresolved.filter(release => !result.worktreeInventory?.some(tree => sameRetirementCheckout(tree, release)));
let retirementReviews = { candidates: [], held: [] };
const { prepareReconcileRetirements, retainedMergedClaims } = await import('./branchReconcileRetirement.js');
+ let latestAbsentObligations = absentObligations;
if (actions.cleanupMerged !== false && (result.wip?.some(branch => branch.rule === 'completion-policy' && branch.completionPolicyReason === 'pr-completion-review-required')
|| retainedMergedClaims(result).length)) {
const inventory = describeIdleReconcilePark(result.skipped || [], heldLive, {
wip: result.wip, worktreeInventory: result.worktreeInventory,
detachedWorktrees: result.detachedWorktrees, superseded: result.superseded,
});
- await taskSchedule.recordBranchReconcileOutcome(app.id, {
+ const prepOutcome = await taskSchedule.recordBranchReconcileOutcome(app.id, {
status: 'running', reason: 'preparing-retirement-reviews', remaining: [...inventory.remaining, ...absentObligations],
nextAction: 'Review completed local work before verified archival retirement.',
});
retirementReviews = await prepareReconcileRetirements(app, result);
+ const latestOutcome = (await taskSchedule.getBranchReconcileOutcome(app.id)) || prepOutcome || previousOutcome;
+ latestAbsentObligations = unresolvedRetirements(latestOutcome)
+ .filter(release => !result.worktreeInventory?.some(tree => sameRetirementCheckout(tree, release)));
}
const retiredNames = new Set((retirementReviews.retired || []).map(row => row.branch));
if (retiredNames.size) {
@@ -554,6 +558,7 @@ 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.
@@ -586,7 +591,11 @@ export async function resolveBranchReconcileBlock(app, taskType, metadata, taskS
}
const allActionable = filterActionable([...cognitiveInFlight, ...retirementReviews.candidates], actions);
const actionableNames = new Set(allActionable.map(branch => branch.branch));
- const idlePark = describeIdleReconcilePark([...(result.skipped || []), ...retirementReviews.held, ...absentObligations, ...routineDeliveryHolds], heldLive, {
+ const filteredSkipped = (result.skipped || []).filter(row =>
+ !actionableNames.has(row.branch)
+ && !retirementReviews.held.some(held => held.branch === row.branch)
+ && !routineDeliveryHolds.some(held => held.branch === row.branch));
+ const idlePark = describeIdleReconcilePark([...filteredSkipped, ...retirementReviews.held, ...latestAbsentObligations, ...routineDeliveryHolds], heldLive, {
wip: result.wip?.filter(branch => !actionableNames.has(branch.branch) && !retirementReviews.held.some(held => held.branch === branch.branch) && !routineDeliveryHolds.some(held => held.branch === branch.branch)), detachedWorktrees: result.detachedWorktrees, superseded: result.superseded,
claimMarkersHeld: result.claimMarkersHeld,
worktreeInventory: result.worktreeInventory?.filter(tree => !actionableNames.has(tree.branch)) ?? result.worktreeInventory,
@@ -608,6 +617,10 @@ 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.
@@ -692,7 +705,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))?.createdAt,
+ createdAt: dispatchedOutcome.retirementObligations?.find(row => sameRetirementObservation(row, branch.retirement.release) || sameRetirementCheckout(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 5765c9b6b8..e97ac64817 100644
--- a/server/services/heldCheckoutRecovery.js
+++ b/server/services/heldCheckoutRecovery.js
@@ -1405,9 +1405,17 @@ export async function retirePendingMergeCheckout({ repoPath, release, prUrl, exp
if (!prepared.ok) return prepared;
if (prepared.review.forge.prHead !== expectedHeadSha) return { ok: false, reason: 'receipt-pr-head-changed' };
if (prepared.review.comparison.disposition !== 'integrated') return { ok: false, reason: 'retirement-supersession-not-accepted' };
- return retireHeldCheckout({ repoPath, release,
+ const result = await retireHeldCheckout({ repoPath, release,
review: { prUrl, digest: prepared.review.digest, acceptSuperseded: false },
}, receiptOptions);
+ if (result.ok) {
+ const { recordWorkspaceCheckoutRetirement } = await import('./taskSchedule.js');
+ 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 d23bec7d97..d734592478 100644
--- a/server/services/taskSchedule.js
+++ b/server/services/taskSchedule.js
@@ -793,6 +793,7 @@ export async function recordBranchReconcileOutcome(appId, { status, reason, rema
// A fresh empty scan must not erase the last observation of vanished source.
const omitted = remaining === undefined ? [] : (previous?.remaining || [])
.filter(row => !remaining.some(current => sameRetirementCheckout(current, row))
+ && !hasRetirementReceipt(previous, row)
&& !rejected.some(entry => sameRetirementObservation(entry, row)));
const missing = await missingInventoryRows(appId, omitted);
const retirementObligations = retainRetirementObligations(previous,
@@ -858,7 +859,7 @@ export async function recordRecoveredCheckoutPreservations(appId, expected, obse
// diagnosis and let the next sweep establish the aggregate completion state.
const diagnosis = historical
? { status: 'incomplete', reason: 'historical-preservation-unresolved', nextAction: historical.preservationEvidence.nextAction }
- : outcome.reason === 'historical-preservation-unresolved'
+ : ['historical-preservation-unresolved', 'retirement-provenance-unverified'].includes(outcome.reason)
? { status: 'incomplete', reason: remaining.length ? 'remaining-holds' : 'preservation-recovered',
nextAction: remaining.length ? 'Resolve the remaining holds, then run branch reconciliation again.'
: 'Historical preservation verified; run branch reconciliation again to confirm repository completion.' }
@@ -1003,7 +1004,10 @@ export async function recordHeldCheckoutRetirement(appId, { path, branch, branch
updatedAt: retiredAt,
remaining: Array.isArray(outcome.remaining)
? outcome.remaining.filter(entry => retirementObligations.some(row => sameRetirementObservation(row, entry))
- || !(sameRetirementObservation(entry, receipt) || (!entry.checkoutIdentity && sameRetirementCheckout(entry, receipt))))
+ || !(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))))))
: outcome.remaining ?? null,
retired,
};
@@ -1011,6 +1015,28 @@ export async function recordHeldCheckoutRetirement(appId, { path, branch, branch
});
}
+/**
+ * Record a checkout retirement across any matching app for a workspace path or branch.
+ * 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 perApp = schedule?.executions?.['task:branch-reconcile']?.perApp;
+ if (!perApp || typeof perApp !== 'object') return null;
+ let updated = null;
+ for (const [appId, record] of Object.entries(perApp)) {
+ 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;
+ const app = await getAppById(appId).catch(() => null);
+ if (app?.repoPath !== repoPath) continue;
+ updated = await recordHeldCheckoutRetirement(appId, receipt);
+ }
+ return updated;
+}
+
/**
* A perpetual drain's convergence state, read in ONE pass: the actionable
* signature its last dispatch was handed, and how many times it has dispatched
diff --git a/server/services/worktreeManager.js b/server/services/worktreeManager.js
index 2fe0e511b4..f6797f4cfb 100644
--- a/server/services/worktreeManager.js
+++ b/server/services/worktreeManager.js
@@ -1829,7 +1829,15 @@ async function removeWorktreeNow(agentId, sourceWorkspace, branchName, options,
// Merge evidence and completion policy were checked before removal; the
// branch helper checks them again before its leased local deletion.
- if (await detachedCheckout() || await cleanupBranch(preservation.head)) console.log(`🌳 Removed worktree for ${agentId}${merged ? ' (merged)' : ''}`);
+ const branchCleaned = await detachedCheckout() || await cleanupBranch(preservation.head);
+ if (branchCleaned) console.log(`🌳 Removed worktree for ${agentId}${merged ? ' (merged)' : ''}`);
+ if (preservation.archiveDir) {
+ const { recordWorkspaceCheckoutRetirement } = await import('./taskSchedule.js');
+ await recordWorkspaceCheckoutRetirement(sourceWorkspace, {
+ path: worktreePath, branch: branchName, head: preservation.head,
+ branchDeleted: Boolean(branchCleaned), archiveDir: preservation.archiveDir,
+ }).catch(() => null);
+ }
return { merged, removed: true, uncommittedSaved: false, warnings };
},
});
@@ -2381,9 +2389,17 @@ async function cleanupExternalRepoWorktrees(readActiveIds, alreadyHandled, readO
console.warn(`⚠️ Preserved external worktree ${entry.name}: ${err.message}`);
return false;
});
- if (ok && !await deleteCompletedLocalBranch(parentRepo, branchName, wt.head)) {
+ const deleted = ok && await deleteCompletedLocalBranch(parentRepo, branchName, wt.head);
+ if (ok && !deleted) {
console.warn(`⚠️ External branch ${branchName} retained: head changed, new holder, or deletion refused`);
}
+ 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);
+ }
return ok;
},
})).catch(err => {