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(cos): branch reconcile retires superseded and merged held branches (#12917)

[._.]/42f6667b65c5
diff --git a/docs/features/chief-of-staff.md b/docs/features/chief-of-staff.md
index f90603e711..0656641ad9 100644
--- a/docs/features/chief-of-staff.md
+++ b/docs/features/chief-of-staff.md
@@ -117,7 +117,12 @@ repair the exact existing backlink rather than minting another merge authority.
Missing tasks, unreadable state, active owners and explicit leave-open policy
never grant recovery permission. GitHub auto-merge enabled alone is unfinished.
-When cleanup is enabled, completed local review obligations become bounded
+When cleanup is enabled, a clean, unlocked, ownerless checkout held only by a
+review obligation whose commits are already on the default branch (ancestor or
+patch-equivalent) is archived and retired directly: no PR identity, owner
+history or agent review is needed to show nothing is lost, and the retirement
+service re-proves merge evidence and ownership under its fence. Human handoffs
+and unreadable policy stay held. Other completed local review obligations become bounded
`REVIEW_RETIREMENT` tasks after a fresh merged-PR preview accepts their policy,
checkout identity and ownership. The task records the exact release and review
digest, reads the complete original/current code comparison, and uses the live
@@ -136,9 +141,13 @@ It joins the pending-merge coordinator, does not spend its periodic tick budget,
and leaves remote-only receipts and concurrent replacement receipts untouched.
A single locked checkout no longer labels unrelated review holds as live owners.
-Routine reconciliation retains superseded but unmerged branches. Their separate
-backup-and-retire workflow requires explicit `reapSuperseded: true`; merged cleanup
-does not enable it.
+A branch with a fresh SUPERSEDED verdict (its replacement still on the default
+branch, its tip and dirty paths unchanged) is backed up under
+`data/cos/abandoned-worktree-backups/` and retired by the scheduled
+reconciliation, behind the same owner and lock gates as merged cleanup. The
+per-app `reapSuperseded` toggle (on unless `false`, and off whenever
+`cleanupMerged` is off) keeps such branches instead; direct `reconcile()`
+callers still opt in explicitly.
The Git page's merged badge is a display hint. Delete merged branches and
completion cleanup use the same retirement path: resolve the current checkout,
diff --git a/server/lib/cosValidation.js b/server/lib/cosValidation.js
index 19bd8316c5..48349bae34 100644
--- a/server/lib/cosValidation.js
+++ b/server/lib/cosValidation.js
@@ -918,7 +918,8 @@ export const MAX_TOTAL_SPAWNS = 5;
// `cleanupMerged` / `openPr` / `resolveConflicts` / `autoMerge` /
// `finishAbandoned` are the per-app action toggles for the `branch-reconcile`
// task type (`finishAbandoned` governs committing + shipping the uncommitted
-// work left in a dead agent's worktree); `autoClose` is
+// work left in a dead agent's worktree; `reapSuperseded` governs backup-first
+// retirement of branches with a fresh SUPERSEDED verdict); `autoClose` is
// the `issue-reconcile` toggle (ON unless explicitly false — OFF forbids the
// coordinator from closing an issue or filing a follow-up, leaving it to only
// comment + release the claim). Each lives in the shared task-metadata
@@ -949,7 +950,7 @@ export { DEPFREE_MODES, DEFAULT_DEPFREE_MODE } from './auditCatalog.js';
const ALLOWED_TASK_METADATA_KEYS = [
...PIPELINE_BEHAVIOR_FLAGS, 'readOnly', 'claimFlow',
- 'cleanupMerged', 'openPr', 'resolveConflicts', 'autoMerge', 'finishAbandoned', 'autoClose',
+ 'cleanupMerged', 'reapSuperseded', 'openPr', 'resolveConflicts', 'autoMerge', 'finishAbandoned', 'autoClose',
// repo-sync's action toggles (REPO_SYNC_ACTION_KEYS above): publish branches
// strictly ahead of their upstream, fast-forward the default branch, return the
// checkout to it, delete merged branches, drop provably-redundant stashes, and
diff --git a/server/services/branchReconcileCompletion.js b/server/services/branchReconcileCompletion.js
index 2c1d66efd2..836891bb67 100644
--- a/server/services/branchReconcileCompletion.js
+++ b/server/services/branchReconcileCompletion.js
@@ -31,6 +31,7 @@ export async function settleBranchReconcileRun(agent) {
const pendingMergeBranches = new Set(readPendingMergePrs(app).map((entry) => entry?.prBranch).filter(Boolean));
const result = await reconcile(app.repoPath, {
cleanup: true,
+ reapSuperseded: task.metadata.reapSuperseded !== false,
pendingMergeBranches,
activeAgentIds: buildActiveOwnerIds(getActiveAgentIds(), agents),
claimOwners: { agents, readAgents: readClaimOwnershipAgents },
diff --git a/server/services/branchReconcileCompletion.test.js b/server/services/branchReconcileCompletion.test.js
index 6458d1dc4f..b327f2c14d 100644
--- a/server/services/branchReconcileCompletion.test.js
+++ b/server/services/branchReconcileCompletion.test.js
@@ -33,10 +33,15 @@ describe('branch reconciliation completion', () => {
it('settles a non-perpetual run immediately using fresh ownership and its target account', async () => {
expect(await settleBranchReconcileRun(agent)).toMatchObject({ cleaned: ['merged'], reapedSuperseded: ['superseded'] });
expect(reconcile).toHaveBeenCalledWith('/example/repo', {
- cleanup: true, pendingMergeBranches: new Set(['claim/queued']), activeAgentIds: new Set(['active']),
+ cleanup: true, reapSuperseded: true, pendingMergeBranches: new Set(['claim/queued']), activeAgentIds: new Set(['active']),
claimOwners: { agents: [], readAgents: readClaimOwnershipAgents }, forgeAccount: 'example-account'
});
});
+ it('keeps superseded branches when the task turns reapSuperseded off', async () => {
+ getTaskById.mockResolvedValue({ id: 'task-example', metadata: { reapSuperseded: false } });
+ await settleBranchReconcileRun(agent);
+ expect(reconcile).toHaveBeenCalledWith('/example/repo', expect.objectContaining({ cleanup: true, reapSuperseded: false }));
+ });
it('records an incomplete outcome instead of throwing when the run has no managed app', async () => {
const appless = { ...agent, metadata: { ...agent.metadata, taskApp: null } };
expect(await settleBranchReconcileRun(appless)).toBeNull();
diff --git a/server/services/branchReconcileRetirement.js b/server/services/branchReconcileRetirement.js
index 02a3e8d652..d7f9646bd4 100644
--- a/server/services/branchReconcileRetirement.js
+++ b/server/services/branchReconcileRetirement.js
@@ -23,6 +23,18 @@ export async function prepareReconcileRetirements(app, result, deps = {}) {
const tree = result.worktreeInventory?.find(row => row.branch === branch.branch && row.path === branch.worktreePath);
if (!tree || tree.managed !== true || tree.locked !== false || tree.head !== branch.tip) continue;
const release = { branch: tree.branch, path: tree.path, head: tree.head, locked: false, lockReason: tree.lockReason ?? null };
+ // Every commit is already on the default branch, so no PR identity or owner
+ // history is needed to prove nothing is lost: archive and retire it. The
+ // service re-proves merge evidence and ownership under its fence.
+ if (branch.isMerged === true) {
+ const retire = deps.retire || (await import('./heldCheckoutRecovery.js')).retireInventoriedCheckout;
+ const outcome = await retire({ appId: app.id, release },
+ { beforeMutation: assertAutomaticRetirementAllowed, settleMergedReviewObligation: true })
+ .catch(error => ({ ok: false, reason: ['daemon-stopped', 'automatic-retirement-disabled'].includes(error.message) ? error.message : 'retirement-receipt-unverified' }));
+ if (outcome.ok && outcome.archiveDir && outcome.branchDeleted === true) retired.push(release);
+ else held.push({ ...release, reason: outcome.reason || outcome.branchRetainedReason || 'retirement-receipt-unverified' });
+ continue;
+ }
try {
const prUrl = await readPr(app, branch.branch, release.head);
const prepared = await prepare({ appId: app.id, release, prUrl });
diff --git a/server/services/branchReconcileRetirement.test.js b/server/services/branchReconcileRetirement.test.js
index 3a01fde0e5..c695780f12 100644
--- a/server/services/branchReconcileRetirement.test.js
+++ b/server/services/branchReconcileRetirement.test.js
@@ -8,7 +8,7 @@ vi.mock('./forgeExecOptions.js', () => ({ resolveForgeExecOptions: async () => (
const app = { id: 'example', repoPath: '/example/repo' };
const head = 'a'.repeat(40);
-const branch = { branch: 'claim/issue-42', tip: head, worktreePath: '/example/checkout', isMerged: true,
+const branch = { branch: 'claim/issue-42', tip: head, worktreePath: '/example/checkout', isMerged: false,
completionPolicyReason: 'pr-completion-review-required' };
const tree = { branch: branch.branch, path: branch.worktreePath, head, managed: true, locked: false, lockReason: null };
const scan = (b = {}, t = {}) => ({ wip: [{ ...branch, ...b }], worktreeInventory: [{ ...tree, ...t }] });
@@ -18,6 +18,26 @@ const setup = () => ({
});
describe('historical completed-checkout review obligations', () => {
+ it('archives and retires a checkout whose commits are all on the default branch without a PR read or dispatch', async () => {
+ const deps = setup();
+ deps.retire = vi.fn(async () => ({ ok: true, branchDeleted: true, archiveDir: '/private/verified-archive' }));
+ const result = await prepareReconcileRetirements(app, scan({ isMerged: true }), deps);
+ expect(result).toMatchObject({ candidates: [], held: [], retired: [expect.objectContaining({ branch: branch.branch, head })] });
+ expect(deps.readPr).not.toHaveBeenCalled();
+ expect(deps.retire).toHaveBeenCalledWith({ appId: app.id, release: { branch: tree.branch, path: tree.path, head, locked: false, lockReason: null } },
+ { beforeMutation: expect.any(Function), settleMergedReviewObligation: true });
+ });
+
+ it('keeps a merged checkout the fenced service refuses, with its reason', async () => {
+ const deps = setup();
+ deps.retire = vi.fn(async () => ({ ok: false, reason: 'pr-completion-human-handoff' }));
+ expect(await prepareReconcileRetirements(app, scan({ isMerged: true }), deps)).toMatchObject({
+ retired: [], held: [{ branch: branch.branch, reason: 'pr-completion-human-handoff' }],
+ });
+ deps.retire = vi.fn(async () => { throw new Error('daemon-stopped'); });
+ expect((await prepareReconcileRetirements(app, scan({ isMerged: true }), deps)).held[0].reason).toBe('daemon-stopped');
+ });
+
it('retires integrated exact-head work without cognitive dispatch through the fenced service', async () => {
const deps = setup();
const prepared = await deps.prepare();
@@ -66,11 +86,11 @@ describe('historical completed-checkout review obligations', () => {
it('reviews nonancestral squash/supersession work only through fresh merged-PR proof', async () => {
const deps = setup();
- const result = await prepareReconcileRetirements(app, scan({ isMerged: false }), deps);
+ const result = await prepareReconcileRetirements(app, scan(), deps);
expect(result.candidates).toHaveLength(1);
expect(deps.prepare).toHaveBeenCalledOnce();
deps.prepare.mockResolvedValue({ ok: false, reason: 'retirement-pr-not-matching-merged' });
- expect(await prepareReconcileRetirements(app, scan({ isMerged: false }), deps)).toMatchObject({
+ expect(await prepareReconcileRetirements(app, scan(), deps)).toMatchObject({
candidates: [], held: [{ reason: 'retirement-pr-not-matching-merged' }],
});
});
@@ -82,10 +102,14 @@ describe('historical completed-checkout review obligations', () => {
[{ worktreeDirty: true }, {}],
[{ worktreeStatusUnavailable: true }, {}],
[{}, { locked: true }], [{}, { managed: false }], [{}, { head: 'b'.repeat(40) }],
- ])('never dispatches an unsafe or intentionally held candidate: %j %j', async (b, t) => {
+ ])('never dispatches or retires an unsafe or intentionally held candidate: %j %j', async (b, t) => {
const deps = setup();
- expect((await prepareReconcileRetirements(app, scan(b, t), deps)).candidates).toEqual([]);
+ deps.retire = vi.fn();
+ for (const isMerged of [false, true]) {
+ expect(await prepareReconcileRetirements(app, scan({ isMerged, ...b }, t), deps)).toMatchObject({ candidates: [], retired: [] });
+ }
expect(deps.prepare).not.toHaveBeenCalled();
+ expect(deps.retire).not.toHaveBeenCalled();
});
it.each(['claim-owner-active', 'retirement-local-objects-missing', 'retirement-submodule-not-uninitialized', 'retirement-policy-not-legacy-completed'])('keeps a fresh preview refusal visible: %s', async reason => {
diff --git a/server/services/cosTaskPreStepBlocks.compose.test.js b/server/services/cosTaskPreStepBlocks.compose.test.js
index 3a4044935c..a26212a72c 100644
--- a/server/services/cosTaskPreStepBlocks.compose.test.js
+++ b/server/services/cosTaskPreStepBlocks.compose.test.js
@@ -157,7 +157,7 @@ describe('prepareManagedAppImprovementTask composes the extracted pre-step layer
getTaskInterval.mockResolvedValue({ type: 'on-demand', perpetual: true, drainDispatchCap: 5, taskMetadata: { branchesPerAgent: 3 } });
});
- it('a user run with only historical merged review holds generates bounded durable review work', async () => {
+ it('a user run retires merged review holds and generates review work only for the rest', async () => {
const rows = [1, 2, 3, 4].map(n => ({ branch: `claim/issue-${n}`, tip: String(n).repeat(40),
worktreePath: `/example/checkouts/${n}`, isMerged: n !== 2, completionPolicyReason: 'pr-completion-review-required' }));
reconcileMock.mockResolvedValue(scan({ inFlight: [], wip: rows, worktreeInventory: rows.map(row => ({
@@ -167,16 +167,30 @@ describe('prepareManagedAppImprovementTask composes the extracted pre-step layer
prepareRetirement.mockResolvedValue({ ok: true, review: { digest: 'd'.repeat(64), policy: { policies: [{ id: 'completed-owner' }] }, comparison: { disposition: 'review-supersession', localPatch: '+old', difference: '+replacement' } } });
const task = await generate({ onDemand: true });
expect(task).not.toBeNull();
- expect(task.metadata.reconcileRetirements).toHaveLength(3);
+ // Ancestral checkouts retire through the fenced service; only the
+ // non-ancestral one needs a cognitive review.
+ expect(retireCheckout).toHaveBeenCalledTimes(3);
+ expect(retireCheckout).toHaveBeenCalledWith(expect.objectContaining({ release: expect.objectContaining({ branch: 'claim/issue-1' }) }),
+ expect.objectContaining({ settleMergedReviewObligation: true }));
+ expect(task.metadata.reconcileRetirements).toHaveLength(1);
+ expect(task.metadata.reconcileRetirements[0].release.branch).toBe('claim/issue-2');
expect(task.description).toContain('[REVIEW_RETIREMENT]');
expect(task.description).toContain('checkouts/retire');
expect(task.description).not.toContain('claim-ownership');
expect(parkPerpetual).not.toHaveBeenCalled();
expect(recordBranchReconcileOutcome).toHaveBeenLastCalledWith(APP.id, expect.objectContaining({
- remaining: expect.arrayContaining([expect.objectContaining({ branch: 'claim/issue-4', head: '4'.repeat(40), reason: 'retirement-review-pending' })]),
+ remaining: expect.arrayContaining([expect.objectContaining({ branch: 'claim/issue-2', head: '2'.repeat(40), reason: 'retirement-review-pending' })]),
}));
});
+ it.each([
+ [{}, true], [{ reapSuperseded: false }, false], [{ cleanupMerged: false }, false],
+ ])('retires verified-superseded branches unless a toggle refuses it: %j', async (taskMetadata, expected) => {
+ getTaskInterval.mockResolvedValue({ type: 'on-demand', perpetual: true, drainDispatchCap: 5, taskMetadata: { branchesPerAgent: 3, ...taskMetadata } });
+ await generate();
+ expect(reconcileMock).toHaveBeenCalledWith(APP.repoPath, expect.objectContaining({ reapSuperseded: expected }));
+ });
+
it('does not generate repeated agents for a healthy open PR waiting for CI', async () => {
reconcileMock.mockResolvedValue(scan({ inFlight: [{ branch: 'fix/waiting', state: 'IN_REVIEW', openPr: { url: 'https://github.com/example/repo/pull/9', isDraft: false } }] }));
for (let i = 0; i < 70; i++) expect(await generate()).toBeNull();
diff --git a/server/services/cosTaskPreStepBlocks.js b/server/services/cosTaskPreStepBlocks.js
index 27e7675636..6ed2b8bf4e 100644
--- a/server/services/cosTaskPreStepBlocks.js
+++ b/server/services/cosTaskPreStepBlocks.js
@@ -466,6 +466,9 @@ export async function resolveBranchReconcileBlock(app, taskType, metadata, taskS
};
const result = await reconcile(app.repoPath, {
cleanup: actions.cleanupMerged !== false,
+ // A fresh SUPERSEDED verdict is terminal: nothing else retires the branch,
+ // so holding it only re-reports it. Backup-first, behind the same owner gates.
+ reapSuperseded: actions.cleanupMerged !== false && metadata.reapSuperseded !== false,
...(pendingMergeBranches !== undefined && { pendingMergeBranches }),
activeAgentIds,
claimOwners: { agents: liveAgents, readAgents: readClaimOwnershipAgents },
@@ -509,9 +512,9 @@ export async function resolveBranchReconcileBlock(app, taskType, metadata, taskS
if (result.reapedSuperseded?.length) {
emitLog('info', `🔀 branch-reconcile ${app.name}: reaped ${result.reapedSuperseded.length} verified-superseded branch(es) (backed up under data/cos/abandoned-worktree-backups)`, { appId: app.id, analysisType: taskType });
}
- // Verified-superseded branches are reaped by the reconciler itself and counted
- // in `cleaned`. What is left in `superseded` is the reap's leftovers — held by a
- // lock or a live agent — so name them rather than letting them
+ // Verified-superseded branches are reaped by the reconciler itself (reported in
+ // `reapedSuperseded`). What is left in `superseded` is the reap's leftovers —
+ // held by a lock, a live agent, or the reapSuperseded toggle — so name them rather than letting them
// vanish into a quiet park; the invisibility is the same failure mode as a
// lingering worktree reported as "cleaned 0".
const supersededSuffix = countSuffix(result.superseded, 'branch(es) verified superseded, reap held back', (b) => b.holdReason);
diff --git a/server/services/heldCheckoutRecovery.js b/server/services/heldCheckoutRecovery.js
index baae123244..9f54f7758e 100644
--- a/server/services/heldCheckoutRecovery.js
+++ b/server/services/heldCheckoutRecovery.js
@@ -412,7 +412,7 @@ async function writeArchive(dir, { repoPath, tree, branch, defaultBranch, releas
const isAncestor = (repoPath, sha, ref) => execGit(['merge-base', '--is-ancestor', sha, ref], repoPath, { ignoreExitCode: true })
.then(r => r.exitCode === 0, () => false);
-async function ownerReason({ repoPath, tree, branch, readAgents, reviewed = false }) {
+async function ownerReason({ repoPath, tree, branch, readAgents, reviewed = false, mergedObligationSettled = false }) {
const agents = await readAgents().catch(() => null);
if (!Array.isArray(agents)) return 'claim-ownership-unreadable';
const claim = claimCheckoutOwnerReason({ branchName: branch || 'HEAD', holderPath: tree.path, sourceWorkspace: repoPath, agents });
@@ -426,7 +426,10 @@ async function ownerReason({ repoPath, tree, branch, readAgents, reviewed = fals
if (live) return live;
if (!branch || reviewed) return null;
const { readBranchCompletionHold } = await import('./branchCompletionPolicy.js');
- return readBranchCompletionHold({ repoPath, branch, retirement: true }).catch(() => 'pr-completion-policy-unavailable');
+ const hold = await readBranchCompletionHold({ repoPath, branch, retirement: true }).catch(() => 'pr-completion-policy-unavailable');
+ // A review obligation is moot once every commit is already on the default
+ // branch (re-proven under the fence). Human handoffs and unreadable policy stay held.
+ return mergedObligationSettled && hold === 'pr-completion-review-required' ? null : hold;
}
/** Fresh registration that still matches the release, or the reason it does not. */
@@ -469,6 +472,8 @@ export async function inspectCheckoutRetirementOwnership({ repoPath, release, re
*/
async function retireHeldCheckout({ repoPath, release, review }, opts = {}) {
const { cosDir = PATHS.cos, readAgents = readClaimOwnershipAgents } = opts;
+ // Only the unattended merged-retirement caller sets this, and only without a review.
+ const mergedObligationSettled = !review && opts.settleMergedReviewObligation === true;
const branch = release.branch ?? null;
if (branch && PROTECTED_BRANCHES.includes(branch)) return { ok: false, reason: 'protected-branch' };
const defaultBranch = await getDefaultBranch(repoPath, { allowRemote: false, strict: true }).catch(() => null);
@@ -493,7 +498,7 @@ async function retireHeldCheckout({ repoPath, release, review }, opts = {}) {
const reviewed = review ? await reviewCurrentCheckout({ repoPath, release, prUrl: review.prUrl }, opts) : null;
if (reviewed && (!reviewed.ok || reviewed.review.digest !== review.digest)) return refuse(reviewed.reason || 'retirement-review-changed');
if (reviewed?.review.comparison.disposition === 'review-supersession' && review.acceptSuperseded !== true) return refuse('retirement-supersession-not-accepted');
- const owner = await ownerReason({ repoPath, tree, branch, readAgents, reviewed: Boolean(review) });
+ const owner = await ownerReason({ repoPath, tree, branch, readAgents, reviewed: Boolean(review), mergedObligationSettled });
if (owner) return refuse(owner);
return { fence: { repoPath, path: tree.path, branch }, tree, reviewed };
},
@@ -504,12 +509,12 @@ async function retireHeldCheckout({ repoPath, release, review }, opts = {}) {
console.error(`❌ held-checkout recovery: archive failed for ${tree.path}, checkout kept: ${archive.error.message}`);
return { result: { ok: false, reason: 'archive-failed', detail: archive.error.message } };
},
- finish: ({ tree, reviewed }, archive) => finishHeldCheckoutRetirement({ repoPath, release, review, reviewed, tree, branch, archive }, opts),
+ finish: ({ tree, reviewed }, archive) => finishHeldCheckoutRetirement({ repoPath, release, review, reviewed, tree, branch, archive, mergedObligationSettled }, opts),
});
}
/** The second critical section: re-prove the release, ownership and archived bytes, then remove. */
-async function finishHeldCheckoutRetirement({ repoPath, release, review, reviewed, tree, branch, archive }, opts) {
+async function finishHeldCheckoutRetirement({ repoPath, release, review, reviewed, tree, branch, archive, mergedObligationSettled = false }, opts) {
const { readAgents = readClaimOwnershipAgents } = opts;
// Archiving takes time; never unlock a lock that changed hands meanwhile.
const second = await matchRelease(repoPath, release);
@@ -523,7 +528,7 @@ async function finishHeldCheckoutRetirement({ repoPath, release, review, reviewe
if (!holder || holder.head !== tree.head || shortBranch(holder.branch) !== branch) return 'worktree-holder-changed';
if (opts.inventoryCurrent && !await opts.inventoryCurrent()) return 'release-not-in-inventory';
const [reason, fresh] = await Promise.all([
- ownerReason({ repoPath, tree, branch, readAgents, reviewed: Boolean(review) }),
+ ownerReason({ repoPath, tree, branch, readAgents, reviewed: Boolean(review), mergedObligationSettled }),
review ? reviewCurrentCheckout({ repoPath, release, prUrl: review.prUrl, unlocked: release.locked }, opts) : null,
]);
if (fresh && (!fresh.ok || fresh.review.digest !== review.digest)) return fresh.reason || 'retirement-review-changed';
@@ -548,7 +553,7 @@ async function finishHeldCheckoutRetirement({ repoPath, release, review, reviewe
console.log(`🧹 held-checkout recovery: retired ${tree.path} (archive: ${archive.dir})`);
if (!branch) return { ok: true, archiveDir: archive.dir, branchDeleted: false };
- const hold = await ownerReason({ repoPath, tree: { ...tree, path: null }, branch, readAgents, reviewed: Boolean(review) });
+ const hold = await ownerReason({ repoPath, tree: { ...tree, path: null }, branch, readAgents, reviewed: Boolean(review), mergedObligationSettled });
if (hold) return { ok: true, archiveDir: archive.dir, branchDeleted: false, branchRetainedReason: hold };
if (review) {
const { readRetirementForgeEvidence } = await import('./heldCheckoutReview.js');
diff --git a/server/services/heldCheckoutRecovery.test.js b/server/services/heldCheckoutRecovery.test.js
index d166072566..940c5cea6b 100644
--- a/server/services/heldCheckoutRecovery.test.js
+++ b/server/services/heldCheckoutRecovery.test.js
@@ -697,6 +697,24 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('held checkout recovery (real git)', ()
expect(injected.policies[0].metadata.branchCompletionPolicy).toBeUndefined();
});
+ it('settles a review obligation for unattended retirement only once every commit is on the default branch', async () => {
+ const c = await reviewedCheckout('settled', { normalMerge: true, superseded: true });
+ await execGit(['worktree', 'unlock', c.path], repo);
+ const release = { ...c.release, locked: false, lockReason: null };
+ await recordBranchReconcileOutcome('app-1', { status: 'incomplete', remaining: [{ ...release, reason: 'pr-completion-review-required' }] });
+ const retire = (more = {}) => retireInventoriedCheckout({ appId: 'app-1', release }, { ...c.opts, ...more });
+ injected.policies[0].metadata.prCompletionPolicy = 'leave-open';
+ expect(await retire({ settleMergedReviewObligation: true })).toMatchObject({ ok: false, reason: 'pr-completion-human-handoff' });
+ injected.policies[0].metadata.prCompletionPolicy = 'review-then-merge';
+ expect(await retire()).toMatchObject({ ok: false, reason: 'pr-completion-review-required' });
+ expect(await registered(release.path)).toBe(true);
+ const result = await retire({ settleMergedReviewObligation: true });
+ expect(result).toMatchObject({ ok: true, branchDeleted: true });
+ expect(await registered(release.path)).toBe(false);
+ await execGit(['fetch', join(result.archiveDir, 'commits.bundle'), 'HEAD:refs/heads/restored-settled'], repo);
+ expect((await execGit(['rev-parse', 'restored-settled'], repo)).stdout.trim()).toBe(release.head);
+ });
+
function reusedBranchOwners(c) {
const current = { id: 'current-review-owner', status: 'completed', result: { success: true },
startedAt: '2026-03-01T00:00:00Z', completedAt: '2026-03-01T01:00:00Z',
diff --git a/server/services/taskPromptDefaults.test.js b/server/services/taskPromptDefaults.test.js
index a8d230b971..916f33a5d9 100644
--- a/server/services/taskPromptDefaults.test.js
+++ b/server/services/taskPromptDefaults.test.js
@@ -958,9 +958,11 @@ describe('taskPromptDefaults integrity snapshot', () => {
// issue labels — the same per-issue routing DISPATCH_HINT_FANOUT_GUIDANCE
// already gives the claim swarm's Phase B, imported verbatim rather than
// retyped so the two consumers can't drift on vocabulary.
- it('branch-reconcile v9 routes each fan-out sub-agent by its own branch\'s dispatch labels and aligns superseded instructions', () => {
+ it('branch-reconcile v10 routes each fan-out sub-agent by its own branch\'s dispatch labels and leaves superseded retirement to the deterministic pass', () => {
const current = DEFAULT_TASK_PROMPTS['branch-reconcile'];
- expect(PROMPT_VERSIONS['branch-reconcile']).toBe(9);
+ expect(PROMPT_VERSIONS['branch-reconcile']).toBe(10);
+ expect(current).toContain('the deterministic pass backs the branch up and retires it');
+ expect(current).not.toContain('a verdict alone does not authorize removal');
expect(current).toContain('Base movement alone does not require a rebase or another CI run');
expect(current).toContain('after changing the head, rerun affected validation and required reviews/checks');
expect(current).not.toContain('Each sub-agent rebases onto the default branch');
diff --git a/server/services/taskPromptDefaults/integrity.snapshot.json b/server/services/taskPromptDefaults/integrity.snapshot.json
index b9301a8b1b..e6aaa61498 100644
--- a/server/services/taskPromptDefaults/integrity.snapshot.json
+++ b/server/services/taskPromptDefaults/integrity.snapshot.json
@@ -11,7 +11,7 @@
"better-structural-drift": "ce8b7ba26e5567275b7667d082c3125a",
"better-test-quality": "8e305f986e9c9066da5db2aee76fc024",
"branch-cleanup": "60f132e83570a7a4559a7adf7af1b883",
- "branch-reconcile": "4c69ed43b274ffee3a08a8da980be2bd",
+ "branch-reconcile": "234e23b6c8adc108b5a0cabeafcb8dfd",
"claim-issue": "cc5fb5015f536be6f3f2a9681bf5f21a",
"claim-issue-gitlab": "db6f46db14094581b13646ca281cc8d6",
"claim-issue-jira": "e27862793495692fd4c4fe0dad1eb745",
@@ -76,7 +76,7 @@
"better-runtime-safety": 4,
"better-structural-drift": 2,
"better-test-quality": 2,
- "branch-reconcile": 9,
+ "branch-reconcile": 10,
"claim-issue": 45,
"claim-issue-gitlab": 39,
"claim-issue-jira": 26,
@@ -178,7 +178,8 @@
"44281269863b3133696fdebe9b558256",
"45feea1d5ccd456bb0bec5d12c373a64",
"ae6e8164698faebc2a5fd4fecb3d41e8",
- "90acf7a56c0de2147cf7463ba338a099"
+ "90acf7a56c0de2147cf7463ba338a099",
+ "4c69ed43b274ffee3a08a8da980be2bd"
],
"claim-issue": [
"37949d1b1fa8d461a15658f8f4192d97",
diff --git a/server/services/taskPromptDefaults/prompts.js b/server/services/taskPromptDefaults/prompts.js
index 344dbfbb52..fd2c4eeb46 100644
--- a/server/services/taskPromptDefaults/prompts.js
+++ b/server/services/taskPromptDefaults/prompts.js
@@ -4276,7 +4276,7 @@ ${DISPATCH_HINT_FANOUT_GUIDANCE}
- **A branch whose "Do:" line ends in a merge is not finished until it IS merged.** Its sub-agent stays alive through CI — waiting out the check run, fixing what goes red, then merging — and reports back only when the PR is merged or a specific check/review is blocking it. "PR opened, left open for review" is a completed STEP, not a completed branch: the PR just sits green until the next run re-drives it. Do not end your own run while a sub-agent is still waiting on CI.
- Merging is gated by the "Do:" line itself — required CI green, MERGEABLE, and the review that branch's flow ran (\`/do:pr\`'s reviewer loop for a PR this task opens; the named review for one already in review). That gate, not a blanket ban, is what keeps unreviewed work out of the default branch. Merge only via \`gh pr merge\`, never a local \`git merge\` into the default branch.
- If a sub-agent reports a branch is incomplete, superseded, or blocked, leave it as-is and note it in your summary.
-- Summarize what each branch ended up doing (merged / PR opened but blocked on <what> / conflicts resolved / superseded / left incomplete). For REVIEW_RETIREMENT, record the exact reviewed digest and source-backed supersession decision before calling the live retirement API; never substitute a generic SUPERSEDED verdict. For other SUPERSEDED branches, record the verdict and report the remaining preservation hold; a verdict alone does not authorize removal. Name the file(s) and what on the default branch replaced it in your summary. When a PR is left open, name the check or review that blocked it.`,
+- Summarize what each branch ended up doing (merged / PR opened but blocked on <what> / conflicts resolved / superseded / left incomplete). For REVIEW_RETIREMENT, record the exact reviewed digest and source-backed supersession decision before calling the live retirement API; never substitute a generic SUPERSEDED verdict. For other SUPERSEDED branches, record the verdict; the deterministic pass backs the branch up and retires it, so do not delete it yourself. Name the file(s) and what on the default branch replaced it in your summary. When a PR is left open, name the check or review that blocked it.`,
'issue-reconcile': `[Improvement: {appName}] Trusted Issue Reconciliation
diff --git a/server/services/taskPromptDefaults/versions.js b/server/services/taskPromptDefaults/versions.js
index 0c10ef6fb5..9caa806c30 100644
--- a/server/services/taskPromptDefaults/versions.js
+++ b/server/services/taskPromptDefaults/versions.js
@@ -22,7 +22,7 @@ export const PROMPT_VERSIONS = {
'code-reviewer-b': 1, // v1: 2-stage pipeline (codebase review → triage & implement)
'reference-watch': 5, // v5: upstream commit list is fenced and the prompt carries a public-forge trust-boundary clause (#12491). v4: forge proposals use plain human-readable titles and tracker-defined IDs/filing scripts; PLAN.md keeps its existing checklist IDs. The prompt delegates inventory, duplicate matching, labels, and command syntax to {trackerInstructions}. v3: record proposals in the app's RESOLVED work tracker (PLAN.md / GitHub / GitLab / JIRA) via the {trackerInstructions} block — no longer hardcodes PLAN.md, so an app configured for GitHub issues gets `gh issue create` proposals. v2: append slug-tagged checklist items to PLAN.md (Adopt + Maybe) instead of writing REFERENCE_REVIEW.md; security-flagged commits get no PLAN entry (mentioned only in final summary)
'pr-watcher': 2, // v1: review-and-comment default for newly-opened PRs on the app's default branch
- 'branch-reconcile': 9, // v9: dispatch scoped completed-checkout reviews through verified archival retirement; preserve intentional holds. v8: merge ready conflict-free branches without chasing default-branch movement; rebase only for conflicts, enforced policy or evidenced integration risk. v7: align SUPERSEDED summary instruction with deterministic cleanup pass; superseded branches with worktrees are reaped rather than held by the claim idle window. v6: prefixed labels are spelled with the forge separator — GitLab gets its scoped `::` (`model::heavy`), GitHub keeps `:` — matching slashdo v3.39.0. v5: explicit Ultra capability dispatch alongside the existing three tiers.
+ 'branch-reconcile': 10, // v10: SUPERSEDED verdicts are retired by the deterministic backup-first reap, not held. v9: dispatch scoped completed-checkout reviews through verified archival retirement; preserve intentional holds. v8: merge ready conflict-free branches without chasing default-branch movement; rebase only for conflicts, enforced policy or evidenced integration risk. v7: align SUPERSEDED summary instruction with deterministic cleanup pass; superseded branches with worktrees are reaped rather than held by the claim idle window. v6: prefixed labels are spelled with the forge separator — GitLab gets its scoped `::` (`model::heavy`), GitHub keeps `:` — matching slashdo v3.39.0. v5: explicit Ultra capability dispatch alongside the existing three tiers.
// v4: the prompt now interpolates DISPATCH_HINT_FANOUT_GUIDANCE next to the "spawn one sub-agent per branch" instruction and tells the coordinator to dispatch each sub-agent at ITS OWN branch's recommended model/effort — the same per-issue routing the claim swarm's Phase B already does, applied here because branch-reconcile fans out over issue-derived branches too (#6373). v3: SUPERSEDED is a first-class outcome — a branch whose problem the default branch already solved a different way is reported and left untouched, never merged (merging it undoes shipped work). A resolvable conflict is explicitly NOT evidence the work is still wanted, and every branch is rebased + test-verified before it reaches a PR. v2: a branch whose "Do:" line ends in a merge isn't finished until it IS merged — the sub-agent waits CI out in-session instead of handing back a green-but-open PR, and the old blanket "never merge unreviewed work" rule (which vetoed the per-branch merge instruction) is replaced by the explicit CI-green + MERGEABLE + review gate. v1: per-app coordinator that finishes in-flight LOCAL branches (open PR / resolve conflicts / drive review / auto-merge) after the deterministic merged-branch cleanup pass. Peer-safe (local refs only). Replaced the PortOS-only branchReconcileScheduler.
'issue-reconcile': 9, // v9: API calls target the {portosApiUrl} placeholder expanded at spawn (loopback mirror on HTTPS installs), not the load-time advertised origin (#12405). v8: whole label-create commands instead of a `name hex` list (#9056). v7: prefixed labels are spelled with the forge separator — GitLab gets its scoped `::` (`model::heavy`), GitHub keeps `:` — matching slashdo v3.39.0. Shared mandatory issue-label contract and restricted contributor invitations. v4: follow-up recipes apply independent slashdo dispatch hints and contributor labels (`good first issue`/`help wanted`, Jira hyphenated equivalents) instead of only `plan`. v3: adds a JIRA arm — status-based zombies (a ticket left In Review with remaining scope + no live claim; JIRA has no `in-progress` label) detected via the PortOS JIRA API and healed through ticket transitions + `POST tickets`, routed in via the app's resolved workTracker ('jira') rather than the git host. v2: forge-aware — the scan + coordinator now cover GitLab (`glab` issues + MRs) as well as GitHub, resolved from the app's origin host; every heal command is shown as gh/glab and the injected header names the forge. v1: per-app coordinator that heals ZOMBIE issues (open + in-progress but their PR merged with no live claim) after the deterministic gh/git scan. Applies the partial-ship hybrid — close + file a scoped follow-up when the remainder is separable, else comment "done/remaining" + release the claim so the queue re-picks it.
'refresh-local-llm-catalog': 4, // v4: follows the current no-per-branch-changelog contract and relies on a release-note-quality commit subject. v3: catalog maintenance now preserves the primary-lane + cross-lane recommendation taxonomy and reserves featured treatment for a deliberate first choice. v2: PortOS-only task, so it names the retired fragment command directly. v1: research current local models, refresh LOCAL_LLM_CATALOG + EDITORIAL_FAMILY_RANK, PR (PortOS repo only)
diff --git a/server/services/taskScheduleRegistry.js b/server/services/taskScheduleRegistry.js
index d3a6654f44..4e956a543a 100644
--- a/server/services/taskScheduleRegistry.js
+++ b/server/services/taskScheduleRegistry.js
@@ -209,7 +209,8 @@ const TASK_INTERVAL_DEFAULTS = {
// resolveConflicts / autoMerge / finishAbandoned) are per-app taskMetadata
// booleans (each ON unless explicitly false); `finishAbandoned` covers the work
// a dead agent left UNCOMMITTED in its worktree — commit + ship it, or report it
- // as unfinished. `branchesPerAgent` bounds each coordinator prompt to a
+ // as unfinished; `reapSuperseded` retires a branch with a fresh SUPERSEDED
+ // verdict after writing its recoverable backup. `branchesPerAgent` bounds each coordinator prompt to a
// prioritized batch so a large backlog drains across several agents. It is
// independently overridable per app. useWorktree/openPR are LOCKED off
// (MANAGED_AGENT_OPTIONS):
@@ -219,7 +220,7 @@ const TASK_INTERVAL_DEFAULTS = {
// SIBLING worktrees, never in its own cwd — hence the shared non-committing
// -coordinator posture above. On-demand by default — a manual Run is the
// explicit consent to drive PRs; choosing a cadence enables scheduled runs.
- 'branch-reconcile': { type: INTERVAL_TYPES.ON_DEMAND, perpetual: true, enabled: true, providerId: null, model: null, prompt: null, recheckCron: '0 3 * * *', drainDispatchCap: PERPETUAL_DRAIN_DISPATCH_CAP, taskMetadata: { ...NON_COMMITTING_COORDINATOR_METADATA, cleanupMerged: true, openPr: true, resolveConflicts: true, autoMerge: true, finishAbandoned: true, branchesPerAgent: DEFAULT_BRANCHES_PER_AGENT } },
+ 'branch-reconcile': { type: INTERVAL_TYPES.ON_DEMAND, perpetual: true, enabled: true, providerId: null, model: null, prompt: null, recheckCron: '0 3 * * *', drainDispatchCap: PERPETUAL_DRAIN_DISPATCH_CAP, taskMetadata: { ...NON_COMMITTING_COORDINATOR_METADATA, cleanupMerged: true, reapSuperseded: true, openPr: true, resolveConflicts: true, autoMerge: true, finishAbandoned: true, branchesPerAgent: DEFAULT_BRANCHES_PER_AGENT } },
// issue-reconcile heals ZOMBIE issues: open + `in-progress` (claimed) yet with
// their PR already MERGED and no live claim anywhere — a partial ship left the
// claim marker on, so the queue (which skips `in-progress`) never re-picks the