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: retain server cleanup ownership for pinned claims

Adam Eivy41555f574379
diff --git a/server/lib/README.md b/server/lib/README.md
index 43b1b10952..2048b37113 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -616,7 +616,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `autonomousJobIntervals.js` | Autonomous-job cadence vocabulary (pure). `INTERVAL_OPTIONS` (picker rows, `ms: null` for a cadence with no recurrence), `ON_DEMAND_INTERVAL`, `JOB_INTERVAL_VALUES` (every legal stored cadence, incl. `custom`), `resolveIntervalMs(interval, customMs)` → ms or `null` (the no-interval sentinel — never falls through to `DAY`), and `isOnDemandJob(job)` for the three due/next-fire implementations. Lives here so `cosValidation.js` can validate the cadence without a lib → services import; `services/autonomousJobs/constants.js` re-exports it. Separate vocabulary from the scheduled-CoS-task `INTERVAL_TYPES`. |
| `jobFormFields.js` | A scheduled agent job's own configuration form (pure). `JOB_FORM_FIELD_TYPES` (text/textarea/number/select/checkbox), the `jobFormFieldsSchema` / `jobFormValuesSchema` pair Zod-validates the job payload against, and the prompt projection `formatJobFormValues(fields, values)` / `appendJobFormValues(job, prompt)`. Definitions and values are stored separately so re-aiming a job (a new value) is not an edit to its design (a new field), and the projection iterates DEFINITIONS — a value whose field was deleted is inert. A field the user left blank is omitted rather than passed as an empty line, but a `false` checkbox is a real answer and is kept. Consumed by `services/autonomousJobs/skillTemplates.js`; the values reach the agent as the prompt's `## Run configuration` section. `describeReaimedValues(fields, saved, run)` names the values a manual run changed, as the one-line description suffix that keeps a re-aimed run from colliding with a differently-aimed twin in `addTask`'s first-line dedupe. |
| `capabilityMap.js` | Pure row builders for Setup & Capabilities, including strict network/provider first-run readiness and optional-integration health rollups; fed by `routes/capabilities.js`. |
-| `claimFlowTaskTypes.js` | `hasClaimFlowContract(task)` shares trusted claim identity across registration, completion and resume. `CLAIM_FLOW_TASK_TYPES` — the ONE list of task kinds whose prompts own their own `claim/<item>` worktree and push/PR/MR/review lifecycle (#6613). `services/cosTaskGenerator.js` stamps `metadata.claimFlow` from it (WRITE side); `services/agentPromptBuilder.js` reads it back through `isClaimFlowTask()` to pick a run's claim posture (READ side). It lived as two byte-identical copies, so a new claim type added to one silently split the writer from the reader — no error, just a claim run treated as a plain commit-only handoff; `claimFlowTaskTypes.test.js` fails if a local copy reappears. Imports nothing. |
+| `claimFlowTaskTypes.js` | `hasClaimFlowContract(task)` shares trusted task identity across registration, completion and resume; `isClaimAgentMetadata(metadata)` recognizes both pinned and picker agent registrations for checkout completion. `CLAIM_FLOW_TASK_TYPES` — the ONE list of task kinds whose prompts own their own `claim/<item>` worktree and push/PR/MR/review lifecycle (#6613). `services/cosTaskGenerator.js` stamps `metadata.claimFlow` from it (WRITE side); `services/agentPromptBuilder.js` reads it back through `isClaimFlowTask()` to pick a run's claim posture (READ side). It lived as two byte-identical copies, so a new claim type added to one silently split the writer from the reader — no error, just a claim run treated as a plain commit-only handoff; `claimFlowTaskTypes.test.js` fails if a local copy reappears. |
| `chiptuneRender.js` | Deterministic chiptune score → mono PCM → 16-bit WAV buffer (pure Node, no audio deps); `renderScoreToPcm` / `pcmToWavBuffer` / `renderScoreToWav`. |
| `chiptuneScore.js` | Chiptune score contract (#2911): `chiptuneScoreSchema` (Zod) + `sanitizeChiptuneScore`, `buildScoreEvents` — the pattern/order → absolute-time flatten mirrored by `client/src/lib/chiptunePlayback.js`. |
| `musicVideoLayers.js` | Music Video per-scene visual layers (#8985): `MUSIC_VIDEO_VISUAL_LAYERS` (`footage`/`still`/`card`/`code`), `MUSIC_VIDEO_STILL_MOVES` (`hold`/`push`/`pan`), `STILL_PUSH_ZOOM` / `STILL_PAN_TRAVEL` (shared render/animatic motion amounts), `MUSIC_VIDEO_FRAME_FITS` (`fill`/`still`/`vhs`/`black`: how an off-shape clip fills the frame), `sceneVisualLayer(scene, { layered })` (only a composed render honors a still/card), `sceneHasAuthoredSpan`, and `sceneRenderReady(scene, { layered })`. `clipSpeedRate(scene)` / `clipOffsetSec(scene)` / `clipReversed(scene)` read a footage shot's hand-set `speedFps`, `offsetFrames` and `reverse` on the 24 fps grid (`CLIP_TIMING_FPS`, `CLIP_SPEED_FPS_RANGE`, `CLIP_OFFSET_FRAMES_RANGE`). Pure leaf shared by `services/musicVideo/render.js` and the client board (`client/src/lib/musicVideoLayers.js`). `clipPlaybackWindow(scene, edit, duration)` / `clipLoops` / `clipCanLoop` share source timing and loop eligibility; `clipNeedsMoreFootage` and `COVERAGE_TOLERANCE_SEC` keep held-clip coverage identical in the card and render preflight. |
diff --git a/server/lib/claimFlowTaskTypes.js b/server/lib/claimFlowTaskTypes.js
index f068771bd9..3454b1a2d3 100644
--- a/server/lib/claimFlowTaskTypes.js
+++ b/server/lib/claimFlowTaskTypes.js
@@ -14,6 +14,8 @@
// `metadata.analysisType`.
//
// Pure leaf: shared by prompt selection, registration and resume authority.
+import { isTruthyMeta } from './metadataFlags.js';
+
export const CLAIM_FLOW_TASK_TYPES = new Set([
'plan-task', 'claim-issue', 'claim-issue-gitlab', 'claim-issue-jira', 'claim-work'
]);
@@ -24,3 +26,11 @@ export function hasClaimFlowContract(task) {
return metadata?.claimFlow === true || metadata?.claimFlow === 'true'
|| CLAIM_FLOW_TASK_TYPES.has(metadata?.analysisType || metadata?.taskAnalysisType || task?.taskType);
}
+
+/** Registered claim runs include pinned targets as well as issue pickers.
+ * Concrete checkout authority still requires their bound branches and receipts.
+ */
+export function isClaimAgentMetadata(metadata) {
+ return isTruthyMeta(metadata?.claimPicksOwnBranch)
+ || (typeof metadata?.claimBranch === 'string' && metadata.claimBranch.length > 0);
+}
diff --git a/server/services/agentFinalization.js b/server/services/agentFinalization.js
index fadbfc18fe..89ec4a590d 100644
--- a/server/services/agentFinalization.js
+++ b/server/services/agentFinalization.js
@@ -1279,7 +1279,7 @@ export async function retireDeadAgent({ agent, task, success, exitCode, duration
const savedCleanup = isDeliveryCleanupHeld(task?.metadata) && task.metadata.deliveryRecoveryAgentId === agent.id;
const cleanupAllowed = savedCleanup || (executionSuccess && validationPassed !== false
- && (agent.metadata?.isWorktree === true || isTruthyMeta(agent.metadata?.claimPicksOwnBranch)));
+ && (agent.metadata?.isWorktree === true || isClaimAgentMetadata(agent.metadata)));
const recoveryOutcome = !cleanupAllowed && taskOutcome?.recovery?.mode === 'cleanup' ? { ...taskOutcome, recovery: undefined } : taskOutcome;
const recoveryUpdate = deliveryHeld && !refused && !isPrivateSecurity && task?.id && task.status !== 'completed'
? resolveUndeliveredTaskUpdate(task, recoveryOutcome, agent.id) : null;
diff --git a/server/services/agentFinalization.outputHooks.test.js b/server/services/agentFinalization.outputHooks.test.js
index bca41edcaa..3faad45178 100644
--- a/server/services/agentFinalization.outputHooks.test.js
+++ b/server/services/agentFinalization.outputHooks.test.js
@@ -414,10 +414,11 @@ describe('recovery output-hook dispatch (#3182)', () => {
expect(addTask).not.toHaveBeenCalled();
});
- it('hands cleanup-only work to completion recovery without another agent or success claim', async () => {
+ it.each(['worktree', 'pinned-claim'])('hands %s cleanup-only work to completion recovery without another agent or success claim', async mode => {
const taskOutcome = { status: 'incomplete', reason: 'Verified delivery; owner still holds checkout.', recovery: { mode: 'cleanup' } };
isProgrammaticIoTaskType.mockReturnValue(false);
- persistedAgent.metadata.isWorktree = true;
+ persistedAgent.metadata = mode === 'worktree' ? { isWorktree: true }
+ : { isWorktree: false, claimPicksOwnBranch: false, claimBranch: 'claim/issue-42', claimBranches: ['claim/issue-42'] };
try {
await finalizeAgent({ agentId: 'agent-example', task: { id: TASK.id, taskType: 'user', metadata: {} },
success: true, exitCode: 0, finalSummary: JSON.stringify({ summary: 'Cleanup handed off.', taskOutcome }) });
@@ -428,20 +429,26 @@ describe('recovery output-hook dispatch (#3182)', () => {
} finally { isProgrammaticIoTaskType.mockReturnValue(true); }
});
- it('retains an already persisted cleanup handoff when its run is recovered after a crash', async () => {
+ it.each(['saved', 'pinned-claim'])('retains a %s cleanup handoff when its run is recovered after a crash', async mode => {
const { mkdtemp, writeFile, rm } = await import('node:fs/promises');
const { tmpdir } = await import('node:os');
const workspacePath = await mkdtemp(join(tmpdir(), 'cleanup-restart-'));
+ isProgrammaticIoTaskType.mockReturnValue(false);
const taskOutcome = { status: 'incomplete', reason: 'Only preservation remains.', recovery: { mode: 'cleanup' } };
- const task = { ...TASK, metadata: { ...TASK.metadata, deliveryRecovery: 'cleanup', deliveryRecoveryAgentId: 'agent-example' } };
- persistedAgent.metadata = { workspacePath, isWorktree: true };
+ const task = { ...TASK, metadata: { ...TASK.metadata, ...(mode === 'saved'
+ ? { deliveryRecovery: 'cleanup', deliveryRecoveryAgentId: 'agent-example' } : {}) } };
+ persistedAgent.metadata = { workspacePath, ...(mode === 'saved' ? { isWorktree: true }
+ : { isWorktree: false, claimPicksOwnBranch: false, claimBranch: 'claim/issue-42', claimBranches: ['claim/issue-42'] }) };
try {
await writeFile(join(workspacePath, '.agent-done-agent-example'), JSON.stringify({ taskOutcome }));
- await retireDeadAgent({ agent: persistedAgent, task, success: false, exitCode: 1, duration: 1000 });
+ await retireDeadAgent({ agent: persistedAgent, task, success: mode === 'pinned-claim', exitCode: mode === 'pinned-claim' ? 0 : 1, duration: 1000 });
expect(updateTask).toHaveBeenLastCalledWith(TASK.id, expect.objectContaining({ status: 'in_progress',
metadata: expect.objectContaining({ deliveryRecovery: 'cleanup', deliveryRecoveryAgentId: 'agent-example' }) }), TASK.taskType);
expect(completeAgent).toHaveBeenLastCalledWith('agent-example', expect.objectContaining({ success: false, cleanupPending: true }));
- } finally { await rm(workspacePath, { recursive: true, force: true }); }
+ } finally {
+ isProgrammaticIoTaskType.mockReturnValue(true);
+ await rm(workspacePath, { recursive: true, force: true });
+ }
});
it('stops repeated delivery recovery at the existing budget with concrete choices', async () => {
diff --git a/server/services/agentRepoStateVerification.js b/server/services/agentRepoStateVerification.js
index 4b2155b41f..79eedbd9d9 100644
--- a/server/services/agentRepoStateVerification.js
+++ b/server/services/agentRepoStateVerification.js
@@ -273,7 +273,10 @@ export async function verifyAgentRepoState(input) {
}
input = { ...input, task: current };
}
- return verifyRunBranches({ ...input, success: input.success || cleanupPending });
+ // Cleanup warnings describe the retained checkout this audit must settle.
+ // They cannot suppress the only server-owned cleanup continuation.
+ return verifyRunBranches({ ...input, success: input.success || cleanupPending,
+ ...(cleanupPending ? { cleanupWarnings: [] } : {}) });
};
const run = verify().then(async result => {
if (result.skipReason === 'cleanup-owner-changed' || result.skipReason === 'cleanup-task-unavailable') return result;
@@ -501,7 +504,7 @@ async function verifyAgentBranchState({ agentId, task, agentState, success, prEx
: null;
if (app === UNREADABLE) return skipped(REPO_STATE_SKIPS.GATE_UNREADABLE);
- const worktreePath = isTruthyMeta(metadata.claimPicksOwnBranch) ? metadata.workspacePath : metadata.workspacePath || join(PATHS.worktrees, agentId);
+ const worktreePath = isClaimAgentMetadata(metadata) ? metadata.workspacePath : metadata.workspacePath || join(PATHS.worktrees, agentId);
const { record, blockWith } = branchLedger(agentId, { branch: branchName, path: worktreePath });
const enabled = repoStateVerificationEnabled(app);
const owned = enabled ? await branchHasPendingOwner(branchName, app, agentState?.result?.cleanupPending === true ? { taskId: task.id, agentId } : null).catch(() => null) : false;
@@ -696,7 +699,7 @@ async function fileDivergenceRecovery({ agentId, task, appId, metadata, sourceWo
emitLog('info', `🔎 Repo state diverged after ${agentId}: ${issues.map(i => i.code).join(', ')}`, { agentId, branchName, taskId: task?.id });
const recoveryTaskId = await fileRepoStateRecoveryTask({
- agentId, task, branchName, sourceWorkspace, worktreePath, issues, observed, appId, retirement, claimRun: isTruthyMeta(metadata.claimPicksOwnBranch),
+ agentId, task, branchName, sourceWorkspace, worktreePath, issues, observed, appId, retirement, claimRun: isClaimAgentMetadata(metadata),
}).catch(err => {
emitLog('warn', `Failed to file repo-state recovery task for ${agentId}: ${err.message}`, { agentId, branchName });
return null;
diff --git a/server/services/agentRepoStateVerification.test.js b/server/services/agentRepoStateVerification.test.js
index 014cf9b520..319b554783 100644
--- a/server/services/agentRepoStateVerification.test.js
+++ b/server/services/agentRepoStateVerification.test.js
@@ -231,16 +231,16 @@ describe('verifyAgentRepoState — clean runs', () => {
expect(await run({ success: false, agentState: state, task: own })).toMatchObject({ skipReason: 'follow-up-pending' });
});
- it('settles only the cleanup handoff owned by this run after archive and integration proof', async () => {
+ it.each([[], ['Branch preserved by ordinary cleanup']])('settles its cleanup handoff after archive and integration proof despite warnings %j', async cleanupWarnings => {
const completed = { version: 1, agentId: 'agent-1', repoPath: '/repo', branch: BRANCH, path: WORKTREE, head: HEAD,
startedAt: CREATED_AT, capturedAt: CREATED_AT };
const state = { ...agentState({ completedCheckouts: [completed],
reviewLoopMergeTarget: { url: 'https://github.com/example/repo/pull/7' }, repoStateVerification: { status: 'pending' } }),
result: { success: false, cleanupPending: true } };
- await run({ success: false, agentState: state });
+ await run({ success: false, agentState: state, cleanupWarnings });
expect(updateTask).not.toHaveBeenCalled();
findMissingCheckoutPreservation.mockResolvedValue({ archiveDir: '/example/archive', evidenceDigest: 'a'.repeat(64), recheck: async () => true });
- expect(await run({ success: false, agentState: state })).toMatchObject({ verified: true });
+ expect(await run({ success: false, agentState: state, cleanupWarnings })).toMatchObject({ verified: true });
expect(updateTask).toHaveBeenLastCalledWith('task-1', expect.objectContaining({ status: 'completed' }), 'user', {
expectedStatus: 'in_progress', expectedMetadata: { deliveryRecovery: 'cleanup', deliveryRecoveryAgentId: 'agent-1' },
});
@@ -731,9 +731,10 @@ describe('verifyAgentRepoState — every hold records the reason it returns', ()
expect(recordCleanupOutcome).toHaveBeenLastCalledWith('agent-1', { status: 'pending', reason: 'code-repair-queued', branch: BRANCH, path: WORKTREE, taskId: 'review-1' });
});
- it('records each held swarm branch under the reason it returns', async () => {
+ it.each([false, true])('records each held claim branch under the reason it returns (pinned=%s)', async pinned => {
readClaimOwnershipAgents.mockRejectedValue(new Error('agents unreadable'));
- const state = agentState({ isWorktree: false, worktreeBranch: null, workspacePath: '/repo', claimPicksOwnBranch: true, claimBranches: ['claim/issue-11'] });
+ const state = agentState({ isWorktree: false, worktreeBranch: null, workspacePath: '/repo', claimPicksOwnBranch: !pinned,
+ ...(pinned ? { claimBranch: 'claim/issue-11' } : {}), claimBranches: ['claim/issue-11'] });
expect((await run({ agentState: state })).branches).toEqual([{ branch: 'claim/issue-11', verified: false, skipReason: 'claim-ownership-unreadable', issues: [], recoveryTaskId: null }]);
expect(recordCleanupOutcome).toHaveBeenLastCalledWith('agent-1', { branch: 'claim/issue-11', status: 'blocked', reason: 'claim-ownership-unreadable', owners: [] });
diff --git a/server/services/branchCompletionPolicy.js b/server/services/branchCompletionPolicy.js
index 679eda7115..e6c1fca72e 100644
--- a/server/services/branchCompletionPolicy.js
+++ b/server/services/branchCompletionPolicy.js
@@ -175,11 +175,14 @@ function reviewedIncarnation(input, policies) {
function completedCleanupForRetirement(policy, input) {
const agent = policy.agent;
const result = agent.result;
- return result?.cleanupPending === true && (result.executionSuccess === true || result.cleanupDeliveryVerified === true) && result.validationPassed !== false
+ const integratedLegacyCleanup = result?.executionSuccess === true
+ && input.verifiedPrHead === input.tip && /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(input.integratedCleanupHead || '');
+ return (result?.cleanupPending === true || integratedLegacyCleanup)
+ && (result.executionSuccess === true || result.cleanupDeliveryVerified === true) && result.validationPassed !== false
&& result.taskOutcome?.recovery?.mode === 'cleanup' && input.verifiedPrHead === input.tip && !!input.tip
- && agent.metadata?.completedCheckouts?.some(row => (row.version === 1 || (row.version === 2 && completedCheckoutReceiptValid(agent, row))) && row.agentId === agent.id
+ && (integratedLegacyCleanup || agent.metadata?.completedCheckouts?.some(row => (row.version === 1 || (row.version === 2 && completedCheckoutReceiptValid(agent, row))) && row.agentId === agent.id
&& row.repoPath === input.repoPath && row.branch === input.branch && row.path === input.checkoutPath
- && row.head === input.tip && row.incarnation?.pointer && row.incarnation?.gitdir);
+ && row.head === input.tip && row.incarnation?.pointer && row.incarnation?.gitdir));
}
/** Operator review settles successful completed review obligations. PR-bound
@@ -201,7 +204,7 @@ export function reviewedRetirementPolicy(input) {
|| (incarnation && p.tip && p.tip !== input.tip))) {
return { reason: 'retirement-policy-not-legacy-completed' };
}
- return { reason: null, policies: policies.map(p => ({
+ return { reason: null, ...(input.integratedCleanupHead && { integratedCleanupHead: input.integratedCleanupHead }), policies: policies.map(p => ({
id: p.agent.id || p.agent.agentId, startedAt: p.agent.startedAt,
completedAt: p.agent.completedAt, status: p.agent.status, success: p.agent.result.success,
branch: p.branch, completion: p.completion,
diff --git a/server/services/branchCompletionPolicy.test.js b/server/services/branchCompletionPolicy.test.js
index cdd498fa97..072383fcec 100644
--- a/server/services/branchCompletionPolicy.test.js
+++ b/server/services/branchCompletionPolicy.test.js
@@ -313,6 +313,27 @@ describe('reviewed reused-branch checkout incarnation', () => {
expect(reviewedRetirementPolicy({ ...input(), agents }).reason).toBeTruthy();
});
+ it('settles legacy pinned cleanup outcomes only with fresh exact-head integration evidence', () => {
+ const current = owners()[0];
+ current.metadata.workspacePath = repoPath;
+ current.metadata.reviewLoopMergeTarget = null;
+ current.result = { success: false, executionSuccess: true,
+ taskOutcome: { status: 'incomplete', recovery: { mode: 'cleanup' } } };
+ const integrated = { ...input(), agents: [current], integratedCleanupHead: 'c'.repeat(40) };
+ expect(reviewedRetirementPolicy(integrated).reason).toBeNull();
+ for (const patch of [{ integratedCleanupHead: null }, { verifiedPrHead: 'b'.repeat(40) }]) {
+ expect(reviewedRetirementPolicy({ ...integrated, ...patch }).reason).toBeTruthy();
+ }
+ current.result.validationPassed = false;
+ expect(reviewedRetirementPolicy(integrated).reason).toBeTruthy();
+ current.result.validationPassed = null;
+ current.result.taskOutcome.recovery = undefined;
+ expect(reviewedRetirementPolicy(integrated).reason).toBeTruthy();
+ current.result.taskOutcome.recovery = { mode: 'cleanup' };
+ current.metadata.prCompletionPolicy = 'leave-open';
+ expect(reviewedRetirementPolicy(integrated).reason).toBe('pr-completion-human-handoff');
+ });
+
it('separates explicit prior checkout history only under fresh current PR/head proof', () => {
const agents = owners();
const result = reviewedRetirementPolicy({ ...input(), agents });
diff --git a/server/services/completedCheckoutEvidence.test.js b/server/services/completedCheckoutEvidence.test.js
index e4fa639551..cf94e340ff 100644
--- a/server/services/completedCheckoutEvidence.test.js
+++ b/server/services/completedCheckoutEvidence.test.js
@@ -38,8 +38,8 @@ describe('completed claim checkout evidence', () => {
expect(await captureCompletedCheckouts({ ...agent, metadata: { ...agent.metadata, workspacePath: repoPath } }, { success: true })).toEqual([]);
});
- it.each([true, false])('captures a bound claim run from the source checkout, picker=%s', async picker => {
- agent.metadata = { claimPicksOwnBranch: picker, isWorktree: false, workspacePath: repoPath, claimBranches: [branch] };
+ it.each([false, true])('captures a source-checkout claim without a separate sourceWorkspace (pinned=%s)', async pinned => {
+ agent.metadata = { claimPicksOwnBranch: !pinned, ...(pinned ? { claimBranch: branch } : {}), isWorktree: false, workspacePath: repoPath, claimBranches: [branch] };
const receipts = await captureCompletedCheckouts(agent, { success: true });
expect(receipts).toEqual([expect.objectContaining({ branch, head, path: expect.stringMatching(/claim$/) })]);
expect(await hasCompletedCheckoutEvidence([completed(receipts)], target())).toBe(true);
diff --git a/server/services/cosAgentLifecycle.js b/server/services/cosAgentLifecycle.js
index 174e73c712..00633795fe 100644
--- a/server/services/cosAgentLifecycle.js
+++ b/server/services/cosAgentLifecycle.js
@@ -1,3 +1,4 @@
+import { isClaimAgentMetadata } from '../lib/claimFlowTaskTypes.js';
/**
* CoS Agent Lifecycle Module
*
diff --git a/server/services/cosAgentLifecycle.test.js b/server/services/cosAgentLifecycle.test.js
index a90f4d8309..385476a3f7 100644
--- a/server/services/cosAgentLifecycle.test.js
+++ b/server/services/cosAgentLifecycle.test.js
@@ -550,11 +550,11 @@ describe('completeAgent idempotence (#3384)', () => {
cosEvents.removeAllListeners('agent:completed');
});
- it.each([true, false])('archives checkout evidence before releasing a delivered or cleanup-pending claim (success=%s)', async success => {
+ it.each([{ success: true, pinned: false }, { success: false, pinned: false }, { success: true, pinned: true }, { success: false, pinned: true }])('archives checkout evidence before releasing a delivered or cleanup-pending claim ($success, pinned=$pinned)', async ({ success, pinned }) => {
const agentId = 'claim-completion';
const receipt = { version: 1, agentId, branch: 'claim/issue-1' };
mockCosState.state.agents[agentId] = { id: agentId, status: 'running', startedAt: '2026-01-01T00:00:00Z',
- metadata: { claimPicksOwnBranch: true, claimBranches: [receipt.branch] }, output: [] };
+ metadata: { claimPicksOwnBranch: !pinned, ...(pinned ? { claimBranch: receipt.branch } : {}), claimBranches: [receipt.branch] }, output: [] };
captureCompletedCheckouts.mockImplementationOnce(async agent => {
expect(agent.status).toBe('running');
expect(mockCosState.state.agents[agentId].status).toBe('running');
diff --git a/server/services/heldCheckoutRecovery.js b/server/services/heldCheckoutRecovery.js
index c6553f67af..e67dbb0dd5 100644
--- a/server/services/heldCheckoutRecovery.js
+++ b/server/services/heldCheckoutRecovery.js
@@ -381,6 +381,14 @@ const policyReviewIdentity = (release, prUrl, forge) => ({
verifiedPrHead: forge?.prUrl === prUrl ? forge.prHead : null,
});
+async function integratedPolicyReviewIdentity(repoPath, release, prUrl, forge) {
+ return { ...policyReviewIdentity(release, prUrl, forge),
+ // Older pinned claims missed completion capture. Fresh inclusion of every
+ // commit settles cleanup-only outcomes without manufacturing receipts.
+ integratedCleanupHead: forge?.prHead === release.head && await isAncestor(repoPath, release.head, forge.defaultHead)
+ ? forge.defaultHead : null };
+}
+
async function reviewCurrentCheckout({ repoPath, release, prUrl, unlocked = false }, opts = {}) {
if (!release.branch || PROTECTED_BRANCHES.includes(release.branch)) return { ok: false, reason: 'protected-branch' };
const matched = await matchRelease(repoPath, unlocked ? { ...release, locked: false, lockReason: null } : release);
@@ -392,7 +400,7 @@ async function reviewCurrentCheckout({ repoPath, release, prUrl, unlocked = fals
const forge = await (opts.readForge || readRetirementForgeEvidence)(repoPath, release.branch, prUrl, { forgeAccount: opts.forgeAccount })
.catch(error => ({ error }));
if (forge?.error) return { ok: false, reason: /^retirement-[a-z-]+$/.test(forge.error.message) ? forge.error.message : 'retirement-forge-unavailable' };
- const policy = await retirementPolicy(repoPath, release.branch, opts, policyReviewIdentity(release, prUrl, forge));
+ const policy = await retirementPolicy(repoPath, release.branch, opts, await integratedPolicyReviewIdentity(repoPath, release, prUrl, forge));
if (policy.reason) return { ok: false, reason: policy.reason };
return archiveSnapshots(matched.tree, repoPath)
.then(([content, administration]) => buildCheckoutRetirementReview({ repoPath, release, prUrl,
@@ -995,7 +1003,7 @@ async function finishHeldCheckoutRetirement({ repoPath, release, review, reviewe
if (review) {
const { readRetirementForgeEvidence } = await import('./heldCheckoutReview.js');
const forge = await (opts.readForge || readRetirementForgeEvidence)(repoPath, branch, review.prUrl, { forgeAccount: opts.forgeAccount }).catch(() => null);
- const policy = await retirementPolicy(repoPath, branch, opts, policyReviewIdentity(release, review.prUrl, forge));
+ const policy = await retirementPolicy(repoPath, branch, opts, await integratedPolicyReviewIdentity(repoPath, release, review.prUrl, forge));
if (JSON.stringify(policy) !== JSON.stringify(reviewed.review.policy) || JSON.stringify(forge) !== JSON.stringify(reviewed.review.forge)) {
return { ok: true, archiveDir: archive.dir, branchDeleted: false, branchRetainedReason: 'retirement-evidence-changed' };
}
diff --git a/server/services/heldCheckoutRecovery.test.js b/server/services/heldCheckoutRecovery.test.js
index c9b64bd410..2f3d7e4d03 100644
--- a/server/services/heldCheckoutRecovery.test.js
+++ b/server/services/heldCheckoutRecovery.test.js
@@ -1459,6 +1459,32 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('held checkout recovery (real git)', ()
expect(injected.policies[0].metadata.branchCompletionPolicy).toBeUndefined();
});
+ it('reviews and retires a legacy pinned cleanup handoff against fresh default proof while local main lags', async () => {
+ const c = await reviewedCheckout('pinned-cleanup', { normalMerge: true });
+ injected.policies[0].result = { success: false, executionSuccess: true,
+ taskOutcome: { status: 'incomplete', recovery: { mode: 'cleanup' } } };
+ const shippedDefault = c.forge.defaultHead;
+ await execGit(['reset', '--hard', 'HEAD^'], repo);
+ const localMain = (await execGit(['rev-parse', 'main'], repo)).stdout.trim();
+ c.forge.defaultHead = localMain;
+ expect(await c.prepare()).toMatchObject({ ok: false, reason: 'retirement-policy-not-legacy-completed' });
+ c.forge.defaultHead = shippedDefault;
+ injected.policies[0].result.validationPassed = false;
+ expect(await c.prepare()).toMatchObject({ ok: false, reason: 'retirement-policy-not-legacy-completed' });
+ injected.policies[0].result.validationPassed = null;
+ const prepared = await c.prepare();
+ expect(prepared).toMatchObject({ ok: true, review: { comparison: { disposition: 'integrated', difference: '' },
+ policy: { integratedCleanupHead: shippedDefault } } });
+ const result = await c.confirm(prepared.review);
+ expect(result).toMatchObject({ ok: true, archiveDir: expect.any(String), branchDeleted: true });
+ expect(await registered(c.path)).toBe(false);
+ expect((await execGit(['rev-parse', 'main'], repo)).stdout.trim()).toBe(localMain);
+ expect(await readFile(join(result.archiveDir, 'files/ignored.txt'), 'utf8')).toBe('ignored work\n');
+ expect((await getBranchReconcileOutcome('app-1')).retired).toContainEqual(expect.objectContaining({
+ branch: c.release.branch, head: c.release.head, archiveDir: result.archiveDir, branchDeleted: true,
+ }));
+ });
+
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);