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

Reserve cleanup agents for genuine review and repair

[._.]/ Adam Eivy5b719d7a6b0d
diff --git a/client/src/components/cos/AgentResultLine.jsx b/client/src/components/cos/AgentResultLine.jsx
index d3a05318e2..23c09341b3 100644
--- a/client/src/components/cos/AgentResultLine.jsx
+++ b/client/src/components/cos/AgentResultLine.jsx
@@ -28,7 +28,10 @@ export default function AgentResultLine({ agent, className = '' }) {
const interruption = agent.metadata?.executionInterruption || agent.result.executionInterruption;
const scanner = agent.metadata?.securityScan;
const scanIncomplete = scanner && scanner.status !== 'completed';
- const incomplete = interruption || scanIncomplete || assessmentUnverified || validationFailed || publicationIncomplete;
+ const cleanup = agent.metadata?.cleanupOutcome;
+ const cleanupRecovery = agent.metadata?.recoveryOrigin?.subsystem === 'repository-cleanup';
+ const cleanupPending = (cleanupRecovery || cleanup) && cleanup?.status !== 'verified';
+ const incomplete = cleanupPending || interruption || scanIncomplete || assessmentUnverified || validationFailed || publicationIncomplete;
const tone = handoff ? 'text-port-accent' : agent.result.success ? incomplete ? 'text-port-warning' : 'text-port-success' : 'text-port-error';
return (
@@ -43,6 +46,7 @@ export default function AgentResultLine({ agent, className = '' }) {
)}
</span>
{interruption && <div>Execution interrupted: {interruption.category === 'content-refusal' ? 'provider safety refusal; automatic retry stopped' : interruption.category}</div>}
+ {cleanupPending && <div>Cleanup {cleanup?.status === 'already-absent' ? 'already absent; preservation unverified' : cleanup?.status === 'blocked' ? 'blocked' : 'unverified/pending'}{cleanup?.reason ? `: ${cleanup.reason}` : ''}</div>}
<SecurityScanEvidence scanner={scanner} control={agent.metadata?.securityScanControl} />
{!handoff && assessment && <div>{assessment.status === 'recorded' ? 'Assessment saved' : assessment.status === 'persistence-failed' ? 'Assessment could not be saved' : assessment.status === 'not-attempted' ? 'Assessment not attempted' : 'Assessment not verified as saved'}</div>}
{!handoff && validationFailed && <div>Delivery validation failed</div>}
diff --git a/client/src/components/cos/AgentResultLine.test.jsx b/client/src/components/cos/AgentResultLine.test.jsx
index c1bc3039c1..ee244c0bee 100644
--- a/client/src/components/cos/AgentResultLine.test.jsx
+++ b/client/src/components/cos/AgentResultLine.test.jsx
@@ -100,3 +100,17 @@ it('keeps input rejection history visible after a corrected scanner execution co
expect(screen.queryByText('Input rejected before scanner launch')).not.toBeInTheDocument();
expect(screen.getByText('Input rejections: 1 · Last: paths item 3 — path-not-found')).toBeInTheDocument();
});
+
+
+it('does not promote historical cleanup process success to verified cleanup', () => {
+ const agent = { result: { success: true }, metadata: { recoveryOrigin: { subsystem: 'repository-cleanup' } } };
+ const view = render(<AgentResultLine agent={agent} />);
+ expect(screen.getByText('Execution completed')).toBeInTheDocument();
+ expect(screen.getByText('Cleanup unverified/pending')).toBeInTheDocument();
+ expect(screen.queryByText('Completed successfully')).not.toBeInTheDocument();
+ view.rerender(<AgentResultLine agent={{ ...agent, metadata: { ...agent.metadata, cleanupOutcome: { status: 'already-absent', reason: 'already-absent-preservation-unverified' } } }} />);
+ expect(screen.getByText(/Cleanup already absent; preservation unverified/)).toBeInTheDocument();
+ expect(screen.queryByText('Completed successfully')).not.toBeInTheDocument();
+ view.rerender(<AgentResultLine agent={{ ...agent, metadata: { ...agent.metadata, cleanupOutcome: { status: 'verified' } } }} />);
+ expect(screen.getByText('Completed successfully')).toBeInTheDocument();
+});
diff --git a/server/services/README.md b/server/services/README.md
index 2a14242662..3ebd91707b 100644
--- a/server/services/README.md
+++ b/server/services/README.md
@@ -6,7 +6,9 @@ image-generation paths below are useful entry points when tracing render jobs.
| Module | Responsibility |
| --- | --- |
-| `branchReconcileRetirement.js` | Prepares exact, owner-checked historical review obligations and API-only review/retirement instructions; no inferred approval or deletion. |
+| `branchReconcileRetirement.js` | Retires exact-head, integrated checkouts through fresh fenced archive proof; reserves bounded cognitive review only for source/history differences. |
+| `repoCleanupRecovery.js` | Reserves one bounded exact-owner review or code-repair obligation, rechecks policy and delivery evidence before publication, and never queues a provider for routine holds. |
+| `repoCleanupObservation.js` | Read-only exact-ref presence/absence accounting; malformed, changing or unsupported metadata remains unknown. |
| `branchReconcileCompletion.js` | Runs ownership-checked merged and superseded cleanup on coordinator completion, independent of perpetual scheduling. |
| `initializedCheckoutRecovery.js` | Explicit macOS private-module checkout archive, standalone recovery proof, durable reservation, reversible whole-directory quarantine and transaction-bound branch finalization/receipt replay; automatic module cleanup remains blocked. |
| `heldCheckoutReview.js` | Computes fresh forge identity, merged PR/default refs and exact code comparisons for a digest-bound operator retirement; no saved consent or policy rewrites. |
diff --git a/server/services/agentRepoStateVerification.js b/server/services/agentRepoStateVerification.js
index 0f8f5cf3da..1d9d3f4bc0 100644
--- a/server/services/agentRepoStateVerification.js
+++ b/server/services/agentRepoStateVerification.js
@@ -31,13 +31,13 @@ import { sameRetirementCheckout } from '../lib/reconcileRetirementEvidence.js';
* so a live sibling agent is structurally invisible to it.
*/
-import { existsSync } from 'fs';
+import { readLocalBranchPresence, readCheckoutPathPresence, inspectOpenDeliveryRepair } from './repoCleanupObservation.js';
import { join, resolve } from 'path';
import { emitLog } from './cosEvents.js';
import { addTask } from './cos.js';
import * as git from './git.js';
import { listWorktrees } from './worktreeManager.js';
-import { listRemoteHeads, driveToMerge, cleanupMerged } from './branchReconcile.js';
+import { listRemoteHeads, driveToMerge } from './branchReconcile.js';
import { readAllTasksFlat } from './investigationTaskProducer.js';
import { execGit } from '../lib/execGit.js';
import { PATHS } from '../lib/fileUtils.js';
@@ -45,7 +45,7 @@ import { isTruthyMeta } from './agentState.js';
import { RECOVERY_TASK_PREFIX } from './recoveryTasks.js';
import { resolveTaskTargetBranch } from '../lib/taskTargetBranch.js';
import { leavesPrForHuman, resolvePrCompletion, PR_COMPLETIONS } from '../lib/prDisposition.js';
-import { probePrForBranch } from './prProbe.js';
+import { probePrForBranch, probeChangeRequestState } from './prProbe.js';
import { parsePullRequestUrl } from '../lib/gitForge.js';
import { ensureTaskThread } from './brainTaskThreads.js';
import {
@@ -138,26 +138,23 @@ async function probeBranchMerged(repoPath, branch, target) {
* @param {boolean} params.prExpected - gates the forge lookup
* @returns {Promise<{worktreePresent: boolean|null, localBranchPresent: boolean|null, remoteBranchPresent: boolean|null, branchMerged: boolean|null, prState: string|null, prUrl: string|null, defaultBranch: string|null}>}
*/
-async function probeRepoState({ sourceWorkspace, branchName, worktreePath, branchShouldBeGone, prExpected }) {
+async function probeRepoState({ sourceWorkspace, branchName, worktreePath, branchShouldBeGone, prExpected, originalPrUrl }) {
// A worktree counts as present if the directory survived on disk OR git still
// tracks it. Either alone is a leak: an unregistered directory is the full
// checkout `removeWorktree` believed it deleted, and a registered-but-deleted
// tree wedges the next `git worktree add` for that path. The cheap disk check
// first, so the common leaked-directory case skips the `git worktree list` spawn.
const probeWorktree = async () => {
- if (worktreePath && existsSync(worktreePath)) return true;
+ const present = worktreePath ? await readCheckoutPathPresence(worktreePath) : null;
+ if (present !== false) return present;
const worktrees = await listWorktrees(sourceWorkspace).catch(() => null);
if (!worktrees) return null;
return worktrees.some(wt =>
- wt.branch?.replace(/^refs\/heads\//, '') === branchName || wt.path === worktreePath
+ wt.path === worktreePath
);
};
- const probeLocalBranch = () => execGit(
- ['show-ref', '--verify', '--quiet', `refs/heads/${branchName}`],
- sourceWorkspace,
- { ignoreExitCode: true }
- ).then(r => r.exitCode === 0).catch(() => null);
+ const probeLocalBranch = () => readLocalBranchPresence(sourceWorkspace, branchName);
// `listRemoteHeads` is branch-reconcile's single answer to "what is on origin
// right now", already carrying the null-means-could-not-ask contract. It reads
@@ -173,6 +170,14 @@ async function probeRepoState({ sourceWorkspace, branchName, worktreePath, branc
// one", so there is nothing here to report and nothing missing on a `none`
// answer.
const probePr = async () => {
+ if (originalPrUrl && branchShouldBeGone) {
+ const parsed = parsePullRequestUrl(originalPrUrl);
+ const { getOriginInfo } = await import('../lib/gitRemote.js');
+ const origin = await getOriginInfo(sourceWorkspace);
+ if (!parsed || origin?.host !== parsed.host || origin?.fullName !== `${parsed.owner}/${parsed.repo}`) return { readable: false, prState: null, prUrl: null };
+ const probe = await probeChangeRequestState(sourceWorkspace, { number: parsed.number, branch: branchName });
+ return { ...probe, prUrl: originalPrUrl, prNumber: parsed.number };
+ }
if (!prExpected || !branchShouldBeGone) return { prState: null, prUrl: null, prNumber: null, cli: null, readable: true };
return probePrForBranch(sourceWorkspace, branchName);
};
@@ -292,7 +297,7 @@ async function resumeCompletionAudits() {
continue;
}
await verifyAgentRepoState({ agentId: agent.id || agent.agentId, agentState: agent, task,
- success: agent.result?.success === true, prExpected: isTruthyMeta(task.metadata?.openPR) })
+ success: agent.result?.success === true, prExpected: isTruthyMeta(task.metadata?.openPR) || !!task.metadata?.reviewLoopPRUrl || !!agent.metadata?.reviewLoopMergeTarget?.url })
.catch(error => emitLog('warn', `Completion recovery deferred for ${agent.id}: ${error.message}`, { agentId: agent.id }));
checked++;
}
@@ -318,15 +323,23 @@ async function verifyRunBranches(input) {
const agents = await readClaimOwnershipAgents().catch(() => null);
const owner = claimCheckoutOwnerReason({ branchName: branch, sourceWorkspace, agents });
if (owner) {
+ const { recordCleanupOutcome } = await import('./cosAgentLifecycle.js');
+ await recordCleanupOutcome(input.agentId, { branch, status: 'blocked', reason: owner });
results.push({ branch, verified: false, skipReason: owner, issues: [], recoveryTaskId: null });
continue;
}
- // Scope only to server-recorded bindings, never branches parsed from prose.
- // Resolve the holder from Git; the claim agent's workspace is the primary.
- const holder = trees.find(tree => tree.branch === `refs/heads/${branch}`);
+ // A current branch holder is not evidence of the old claim's checkout.
+ // Only the server's completion capture names its original incarnation.
+ const original = meta.completedCheckouts?.find(row => row.branch === branch);
+ if (!original?.path) {
+ const { recordCleanupOutcome } = await import('./cosAgentLifecycle.js');
+ await recordCleanupOutcome(input.agentId, { branch, status: 'blocked', reason: 'claim-checkout-identity-unverified' });
+ results.push({ branch, verified: false, skipReason: 'claim-checkout-identity-unverified', issues: [], recoveryTaskId: null });
+ continue;
+ }
results.push({ branch, ...await verifyAgentBranchState({ ...input, prExpected: true,
agentState: { ...input.agentState, metadata: { ...meta, isWorktree: true,
- worktreeBranch: branch, sourceWorkspace, workspacePath: holder?.path || null } },
+ worktreeBranch: branch, sourceWorkspace, workspacePath: original.path } },
}) });
}
return { verified: results.every(result => result.verified), branches: results,
@@ -370,27 +383,73 @@ 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 domain = async (status, reason, extra = {}) => {
+ const { recordCleanupOutcome } = await import('./cosAgentLifecycle.js');
+ await recordCleanupOutcome(agentId, { status, reason, branch: branchName, path: worktreePath, ...extra });
+ };
const enabled = repoStateVerificationEnabled(app);
const owned = enabled ? await branchHasPendingOwner(branchName, app).catch(() => null) : false;
- if (owned === null) return skipped(REPO_STATE_SKIPS.GATE_UNREADABLE);
+ if (owned === null) { await domain('blocked', 'ownership-unreadable'); return skipped(REPO_STATE_SKIPS.GATE_UNREADABLE); }
+ if (owned) await domain('pending', 'existing-completion-owner');
- const expectation = resolveRepoStateExpectation({ ...structural, enabled, followUpPending: owned });
+ const originalPrUrl = [metadata.reviewLoopMergeTarget?.url, metadata.recoveryMergeTarget?.url,
+ task?.metadata?.reviewLoopPRUrl, task?.metadata?.recoveryMergeTarget?.url].find(value => parsePullRequestUrl(value));
+ const expectation = resolveRepoStateExpectation({ ...structural, prExpected: prExpected || !!originalPrUrl, enabled, followUpPending: owned });
if (!expectation.verify) return skipped(expectation.skipReason);
- const worktreePath = isTruthyMeta(metadata.claimPicksOwnBranch) ? metadata.workspacePath : metadata.workspacePath || join(PATHS.worktrees, agentId);
+ // A reused branch is not the old checkout. No model is needed to identify a
+ // different holder, and its live work must never become this parent's target.
+ const inventory = await listWorktrees(sourceWorkspace).catch(() => null);
+ if (!inventory) { await domain('blocked', 'checkout-inventory-unavailable'); return skipped('checkout-inventory-unavailable'); }
+ const holders = inventory.filter(tree => tree.branch?.replace(/^refs\/heads\//, '') === branchName);
+ const pathHolder = inventory.find(tree => tree.path === worktreePath);
+ if (holders.some(tree => tree.path !== worktreePath)
+ || (pathHolder && pathHolder.branch?.replace(/^refs\/heads\//, '') !== branchName)) {
+ await domain('blocked', 'checkout-incarnation-changed');
+ return skipped('checkout-incarnation-changed');
+ }
+ const completed = metadata.completedCheckouts?.find(row => row.branch === branchName && resolve(row.path) === resolve(worktreePath));
+ if (completed && pathHolder) {
+ const { readCompletedCheckoutIdentity } = await import('./completedCheckoutEvidence.js');
+ const identity = await readCompletedCheckoutIdentity({ repoPath: sourceWorkspace, branch: branchName,
+ path: worktreePath, head: pathHolder.head }).catch(() => null);
+ if (!identity || identity.head !== completed.head || JSON.stringify(identity.incarnation) !== JSON.stringify(completed.incarnation)) {
+ await domain('blocked', 'checkout-incarnation-changed');
+ return skipped('checkout-incarnation-changed');
+ }
+ }
+ const { readClaimOwnershipAgents } = await import('./cosClaimOwnership.js');
+ const { claimCheckoutOwnerReason } = await import('../lib/claimContinuation.js');
+ const owner = claimCheckoutOwnerReason({ branchName, sourceWorkspace,
+ agents: await readClaimOwnershipAgents().catch(() => null) });
+ if (owner) { await domain('blocked', owner); return skipped(owner); }
const observed = await probeRepoState({
sourceWorkspace,
branchName,
worktreePath,
branchShouldBeGone: !expectation.staysOpen,
- prExpected: expectation.prExpected,
+ prExpected: expectation.prExpected, originalPrUrl,
}).catch(err => {
emitLog('warn', `🔎 Repo-state probe failed for ${agentId}: ${err.message}`, { agentId, branchName });
return null;
});
- if (!observed) return skipped(REPO_STATE_SKIPS.PROBE_INCOMPLETE);
-
+ if (!observed) { await domain('blocked', 'probe-incomplete'); return skipped(REPO_STATE_SKIPS.PROBE_INCOMPLETE); }
+
+ // Missing originals are an accounting gap, not a reason to hire an agent
+ // to rediscover absence. Never invent a preservation receipt.
+ if (observed.worktreePresent === false && observed.localBranchPresent === false) {
+ const { readRetirementForgeEvidence } = await import('./heldCheckoutReview.js');
+ const proofUrl = originalPrUrl || observed.prUrl;
+ const forge = proofUrl && observed.prState === 'MERGED' ? await readRetirementForgeEvidence(sourceWorkspace, branchName, proofUrl,
+ { forgeAccount: app?.forgeAccount ?? null }).catch(() => null) : null;
+ const integrated = forge && (await execGit(['merge-base', '--is-ancestor', forge.prHead, forge.defaultHead], sourceWorkspace,
+ { ignoreExitCode: true, env: { ...process.env, GIT_OPTIONAL_LOCKS: '0', GIT_NO_LAZY_FETCH: '1' } }).catch(() => null))?.exitCode === 0;
+ const reason = integrated ? 'already-absent-preservation-unverified' : 'absent-checkout-integration-unverified';
+ await domain(integrated ? 'already-absent' : 'blocked', reason, { prUrl: originalPrUrl, committedIntegrationVerified: !!integrated });
+ return skipped(reason);
+ }
const issues = classifyRepoStateIssues(expectation, { ...observed, branchName });
if (issues.length === 0) {
// A run where some probe could not be read has not been verified — it has been
@@ -398,6 +457,7 @@ async function verifyAgentBranchState({ agentId, task, agentState, success, prEx
// repo. Findings still stand on their own: what WAS readable is fact, so a
// divergence below is reported even alongside an unreadable probe.
if (observed.unreadable.length > 0) {
+ await domain('blocked', 'probe-incomplete');
emitLog('info', `🔎 Repo state only partly readable for ${agentId} (${branchName}) — could not check: ${observed.unreadable.join(', ')}`, { agentId, branchName });
return { verified: false, skipReason: REPO_STATE_SKIPS.PROBE_INCOMPLETE, issues: [], observed, recoveryTaskId: null };
}
@@ -410,41 +470,54 @@ async function verifyAgentBranchState({ agentId, task, agentState, success, prEx
return { verified: false, skipReason: null, issues, observed, recoveryTaskId: null };
}
- // A merged branch with no remote ref is safe for the deterministic reaper to
- // retire. Do this before creating another agent task: the common failure is
- // simply that the completing agent exited before its worktree teardown ran.
- // `cleanupMerged` repeats merge evidence and the clean-worktree/protection
- // gates at action time, so an unsafe or racing state falls through to the
- // existing evidence-backed recovery task.
- const cleanupOnly = observed.branchMerged === true
- && observed.remoteBranchPresent === false
- && !issues.some(issue => issue.code === REPO_STATE_ISSUES.PR_UNMERGED);
- if (cleanupOnly) {
- const retired = await cleanupMerged(sourceWorkspace, observed.defaultBranch, [{
- branch: branchName,
- upstreamGone: true,
- }]).catch(() => ({ cleaned: [] }));
- if (retired.cleaned.includes(branchName)) {
- // Record the proven cleanup outcome, never infer it from an agent summary.
- await import('./cosAgentLifecycle.js').then(({ updateAgent }) => updateAgent(agentId, {
- metadata: { maintenanceOutcome: 'deterministic-cleanup' },
- })).catch(error => emitLog('warn', `Could not record deterministic cleanup outcome: ${error.message}`, { agentId }));
- emitLog('info', `🔎 Deterministic cleanup retired merged branch ${branchName} for ${agentId}`, { agentId, branchName });
- return { verified: true, skipReason: null, issues: [], observed, recoveryTaskId: null };
- }
- }
-
let retirement = null;
if (observed.prState === 'MERGED' && (observed.worktreePresent || observed.localBranchPresent)) {
const prepared = await prepareRecoveryRetirement({ app, sourceWorkspace, branchName, worktreePath, observed })
.catch(() => ({ reason: 'retirement-review-unavailable' }));
if (!prepared.retirement) {
+ await domain('blocked', prepared.reason);
emitLog('warn', `Repo-state retirement retained ${branchName}: ${prepared.reason}`, { agentId, branchName });
return { verified: false, skipReason: prepared.reason, issues, observed, recoveryTaskId: null };
}
retirement = prepared.retirement;
+ if (prepared.integrated) {
+ const { retireInventoriedCheckout } = await import('./heldCheckoutRecovery.js');
+ const { assertAutomaticRetirementAllowed } = await import('./branchReconcileRetirement.js');
+ const result = await retireInventoriedCheckout({ appId, release: retirement.release,
+ review: { prUrl: retirement.prUrl, digest: retirement.digest, acceptSuperseded: false } }, { beforeMutation: assertAutomaticRetirementAllowed }).catch(error => ({ reason: ['daemon-stopped', 'automatic-retirement-disabled'].includes(error.message) ? error.message : 'retirement-outcome-uncertain' }));
+ const verified = result.ok && result.archiveDir && result.branchDeleted === true;
+ await domain(verified ? 'verified' : 'blocked', verified ? 'retirement-receipt-verified' : result.reason || 'retirement-receipt-unverified');
+ return { verified: !!verified, skipReason: verified ? null : result.reason || 'retirement-receipt-unverified', issues: verified ? [] : issues, observed, recoveryTaskId: null };
+ }
}
+ // Cleanup bookkeeping/unknown forge/CI waits remain deterministic. Only
+ // source/history judgment or an actual undelivered branch needs cognition.
+ if (!retirement && !issues.some(issue => issue.code === REPO_STATE_ISSUES.BRANCH_UNMERGED
+ || issue.code === REPO_STATE_ISSUES.PR_UNMERGED)) {
+ await domain('blocked', 'deterministic-cleanup-pending');
+ return { verified: false, skipReason: 'deterministic-cleanup-pending', issues, observed, recoveryTaskId: null };
+ }
+ if (!retirement && (!observed.prState || observed.unreadable.length)) {
+ await domain('blocked', 'delivery-evidence-unavailable');
+ return { verified: false, skipReason: 'delivery-evidence-unavailable', issues, observed, recoveryTaskId: null };
+ }
+ if (!retirement) {
+ const delivery = observed.prState === 'OPEN' ? await inspectOpenDeliveryRepair(sourceWorkspace, branchName, observed.prUrl, { forgeAccount: app?.forgeAccount ?? null }).catch(() => ({ reason: 'delivery-evidence-unavailable' })) : { reason: 'delivery-not-open' };
+ let review = null;
+ if (delivery.headSha) {
+ const { inspectOrQueueCompletedReview } = await import('./repoCleanupRecovery.js');
+ review = await inspectOrQueueCompletedReview({ agentId, repoPath: sourceWorkspace, branch: branchName,
+ prUrl: observed.prUrl, headSha: delivery.headSha, worktreePath, forgeAccount: app?.forgeAccount ?? null, repairEvidence: delivery.evidence }).catch(() => ({ disposition: 'held', reason: 'completed-review-inspection-unavailable' }));
+ }
+ if (review?.disposition === 'queued-review') {
+ await domain('pending', review.reason, { taskId: review.taskId });
+ return { verified: false, skipReason: review.reason, issues, observed, recoveryTaskId: review.taskId };
+ }
+ const reason = review?.reason || delivery.reason || 'completed-review-target-unverified';
+ await domain('blocked', reason);
+ return { verified: false, skipReason: reason, issues, observed, recoveryTaskId: null };
+ }
emitLog('warn', `🔎 Repo state diverged after ${agentId}: ${issues.map(i => i.code).join(', ')}`, { agentId, branchName, taskId: task?.id });
const recoveryTaskId = await fileRepoStateRecoveryTask({
@@ -499,7 +572,11 @@ async function prepareRecoveryRetirement({ app, sourceWorkspace, branchName, wor
nextAction: 'Retain the checkout and obligation; retry a fresh preview after the reported hold resolves.' });
return { reason: prepared.reason };
}
- return { retirement: { release, createdAt: obligation.createdAt, prUrl: observed.prUrl, digest: prepared.review.digest } };
+ if (!['integrated', 'review-supersession'].includes(prepared.review?.comparison?.disposition)
+ || typeof prepared.review.comparison.localPatch !== 'string' || typeof prepared.review.comparison.difference !== 'string') return { reason: 'retirement-comparison-unavailable' };
+ return { integrated: prepared.review.forge?.prHead === release.head && prepared.review.comparison?.disposition === 'integrated' && prepared.review.comparison.difference === '',
+ retirement: { release, createdAt: obligation.createdAt, prUrl: observed.prUrl, digest: prepared.review.digest,
+ cognition: (await import('./branchReconcileRetirement.js')).retirementCognitiveIdentity(prepared.review, release, observed.prUrl) } };
}
/**
@@ -573,9 +650,23 @@ async function fileRepoStateRecoveryTask({ agentId, task, branchName, sourceWork
+ `Do not switch branches in ${sourceWorkspace} itself.`,
].join('\n');
- const observation = processAuditFingerprint({ codes: issues.map(issue => issue.code).sort(),
- merged: observed.branchMerged, remotePresent: observed.remoteBranchPresent, prState: observed.prState });
- const previous = task?.metadata?.recoveryOrigin;
+ const head = await execGit(['rev-parse', '--verify', `refs/heads/${branchName}`], sourceWorkspace)
+ .then(result => result.exitCode === 0 ? result.stdout.trim() : null).catch(() => null);
+ if (!/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(head || '')
+ || (retirement && retirement.release.head !== head)) return null;
+ const observation = retirement?.cognition?.observation || processAuditFingerprint({ branchName, worktreePath, head, prUrl: observed.prUrl,
+ codes: issues.map(issue => issue.code).sort(), merged: observed.branchMerged,
+ remotePresent: observed.remoteBranchPresent, prState: observed.prState, deliveryRepair: observed.deliveryRepair,
+ // Stable observation: periodic checks alone do not create new work.
+ work: 'delivery-repair' });
+ const { reserveRepoCleanupRecovery, recordRepoCleanupRecovery, recordCleanupOutcome } = await import('./cosAgentLifecycle.js');
+ const recoveryOwner = retirement?.cognition?.ownerAgentId || agentId;
+ const reservation = await reserveRepoCleanupRecovery(recoveryOwner, branchName, observation);
+ if (!reservation?.admitted) {
+ await recordCleanupOutcome(agentId, { status: 'blocked', reason: reservation?.reason || 'cleanup-observation-unavailable', branch: branchName, path: worktreePath });
+ return null;
+ }
+
// The PR this recovery may land under merge admission (#12251): the forge's
// own answer for this branch, never the agent's report or the task prose.
const mergeTarget = issues.some(issue => issue.code === REPO_STATE_ISSUES.PR_UNMERGED) && parsePullRequestUrl(observed.prUrl)
@@ -586,14 +677,16 @@ async function fileRepoStateRecoveryTask({ agentId, task, branchName, sourceWork
app: appId || undefined,
isRecovery: true,
metadata: { recoveryOrigin: { parentAgentId: agentId, parentTaskId: task?.id || null,
- subsystem: 'repository-cleanup', attempt: Math.min(1000, (previous?.attempt || 0) + 1),
- observation, noProgress: previous?.observation === observation },
+ subsystem: 'repository-cleanup', attempt: reservation.attempt,
+ observation, noProgress: false },
...(mergeTarget ? { recoveryMergeTarget: mergeTarget } : {}),
...(retirement ? { retirementReview: { appId, release: retirement.release, createdAt: retirement.createdAt } } : {}) },
context,
useWorktree: false,
}, 'user');
+ await recordRepoCleanupRecovery(recoveryOwner, branchName, observation, { phase: created?.id ? 'dispatched' : 'blocked', taskId: created?.id || null });
+ await recordCleanupOutcome(agentId, { status: 'pending', reason: 'cognitive-review-pending', branch: branchName, path: worktreePath, taskId: created?.id || null });
if (created?.duplicate) {
emitLog('info', `🔎 Repo-state recovery for ${branchName} already queued as ${created.id}`, { agentId, branchName });
// Repair an interruption between task creation and backlink persistence,
diff --git a/server/services/agentRepoStateVerification.test.js b/server/services/agentRepoStateVerification.test.js
index 6683005f62..53fba90bca 100644
--- a/server/services/agentRepoStateVerification.test.js
+++ b/server/services/agentRepoStateVerification.test.js
@@ -21,11 +21,18 @@ vi.mock('./branchCompletionPolicy.js', async () => ({
import { describe, it, expect, beforeEach, vi } from 'vitest';
-vi.mock('./cosAgentLifecycle.js', () => ({ updateAgent: vi.fn().mockResolvedValue({}), recordRepoStateRecovery: vi.fn().mockResolvedValue(true), recordRepoStateVerification: vi.fn().mockResolvedValue(true) }));
+vi.mock('./repoCleanupRecovery.js', () => ({ inspectOrQueueCompletedReview: vi.fn(async () => ({ disposition: 'held', reason: 'delivery-ci-or-review-pending' })) }));
+vi.mock('./repoCleanupObservation.js', async original => ({ ...await original(), readCheckoutPathPresence: vi.fn(async () => false), readLocalBranchPresence: vi.fn(async () => false) }));
+vi.mock('../lib/gitRemote.js', () => ({ getOriginInfo: vi.fn(async () => ({ host: 'github.com', fullName: 'example/repo', isGithub: true })) }));
+vi.mock('./forgeExecOptions.js', () => ({ resolveForgeExecOptions: vi.fn(async () => ({})) }));
+vi.mock('./heldCheckoutReview.js', () => ({ readRetirementForgeEvidence: vi.fn(async () => ({ prHead: '1'.repeat(40), defaultHead: '2'.repeat(40) })) }));
+vi.mock('./completedCheckoutEvidence.js', () => ({ readCompletedCheckoutIdentity: vi.fn() }));
+vi.mock('./cosAgentLifecycle.js', () => ({ reserveRepoCleanupRecovery: vi.fn(async () => ({ admitted: true, attempt: 1 })), recordRepoCleanupRecovery: vi.fn(async () => true), recordCleanupOutcome: vi.fn(async () => true), updateAgent: vi.fn().mockResolvedValue({}), recordRepoStateRecovery: vi.fn().mockResolvedValue(true), recordRepoStateVerification: vi.fn().mockResolvedValue(true) }));
vi.mock('./cosClaimOwnership.js', () => ({ readClaimOwnershipAgents: vi.fn().mockResolvedValue([]) }));
vi.mock('./cosTaskStore.js', () => ({ getTaskById: vi.fn().mockResolvedValue(null) }));
vi.mock('./taskSchedule.js', () => ({ recordBranchReconcileOutcome: vi.fn().mockResolvedValue({}) }));
vi.mock('./heldCheckoutRecovery.js', () => ({
+ retireInventoriedCheckout: vi.fn(async () => ({ ok: true, archiveDir: '/private/archive', branchDeleted: true })),
prepareInventoriedCheckoutRetirement: vi.fn().mockResolvedValue({ ok: true, review: { digest: 'a'.repeat(64) } }),
}));
vi.mock('./cosEvents.js', () => ({ emitLog: vi.fn() }));
@@ -46,6 +53,7 @@ vi.mock('./git.js', () => ({
resolveForgeForRepo: vi.fn().mockResolvedValue({ cli: 'gh', env: null }),
}));
vi.mock('./github.js', () => ({
+ execGh: vi.fn(), getPullRequestState: vi.fn(async () => ({ status: 'known', state: 'MERGED' })),
findPullRequestForBranch: vi.fn().mockResolvedValue({ status: 'none', url: null, detail: null }),
}));
vi.mock('./gitlab.js', () => ({
@@ -62,18 +70,22 @@ vi.mock('./brainTaskThreads.js', () => ({ ensureTaskThread: vi.fn().mockResolved
vi.mock('../lib/execGit.js', () => ({ execGit: vi.fn() }));
vi.mock('fs', () => ({ existsSync: vi.fn().mockReturnValue(false) }));
-import { updateAgent, recordRepoStateRecovery, recordRepoStateVerification } from './cosAgentLifecycle.js';
+import { inspectOrQueueCompletedReview } from './repoCleanupRecovery.js';
+import { readLocalBranchPresence, readCheckoutPathPresence } from './repoCleanupObservation.js';
+import { readCompletedCheckoutIdentity } from './completedCheckoutEvidence.js';
+import { readClaimOwnershipAgents } from './cosClaimOwnership.js';
+import { recordCleanupOutcome, reserveRepoCleanupRecovery, recordRepoStateRecovery, recordRepoStateVerification } from './cosAgentLifecycle.js';
import { verifyAgentRepoState, sweepRepoStateVerifications, REPO_STATE_REMEDIATIONS } from './agentRepoStateVerification.js';
import { readBranchCompletionPolicies } from './branchCompletionPolicy.js';
import { getTaskById } from './cosTaskStore.js';
import { recordBranchReconcileOutcome } from './taskSchedule.js';
-import { prepareInventoriedCheckoutRetirement } from './heldCheckoutRecovery.js';
+import { prepareInventoriedCheckoutRetirement, retireInventoriedCheckout } from './heldCheckoutRecovery.js';
import { addTask, getAllTasks } from './cos.js';
import { ensureTaskThread } from './brainTaskThreads.js';
import { listWorktrees } from './worktreeManager.js';
import { listRemoteHeads, cleanupMerged } from './branchReconcile.js';
import { hasBranchMergeEvidence, resolveForgeForRepo } from './git.js';
-import { findPullRequestForBranch } from './github.js';
+import { findPullRequestForBranch, execGh, getPullRequestState } from './github.js';
import { findMergeRequestForBranch } from './gitlab.js';
import { getAppById } from './apps.js';
import { addNotification, exists as notificationExists } from './notifications.js';
@@ -105,7 +117,13 @@ const task = (metadata = {}) => ({
});
/** `git show-ref --verify refs/heads/<branch>` — exit 0 means the branch is present. */
-const localBranch = (present) => execGit.mockResolvedValue({ exitCode: present ? 0 : 1, stdout: '', stderr: '' });
+const localBranch = present => {
+ readLocalBranchPresence.mockResolvedValue(present);
+ execGit.mockImplementation(async args => ({ exitCode: args[0] === 'merge-base' || present ? 0 : 1, stdout: args[0] === 'rev-parse' ? `${HEAD}\n` : '', stderr: '' }));
+};
+const review = () => ({ digest: 'a'.repeat(64), policy: { policies: [{ id: 'agent-1', startedAt: CREATED_AT }] },
+ comparison: { disposition: 'review-supersession', localPatch: '+old behavior', difference: '+new behavior' }, forge: { prHead: HEAD } });
+const openView = (patch = {}) => JSON.stringify({ number: 9, state: 'OPEN', isDraft: false, isCrossRepository: false, headRefName: BRANCH, headRefOid: HEAD, mergeable: 'MERGEABLE', reviewDecision: '', statusCheckRollup: [{ name: 'CI', status: 'QUEUED' }], ...patch });
/** The `{user, cos}` shape `getAllTasks` really returns. Follow-ups land in `cos`. */
const queuedTasks = (tasks) => getAllTasks.mockResolvedValue({ user: { tasks: [] }, cos: { tasks } });
@@ -121,14 +139,20 @@ const run = (overrides = {}) => verifyAgentRepoState({
beforeEach(() => {
vi.clearAllMocks();
+ inspectOrQueueCompletedReview.mockResolvedValue({ disposition: 'held', reason: 'delivery-ci-or-review-pending' });
readBranchCompletionPolicies.mockResolvedValue([]);
getTaskById.mockResolvedValue(null);
recordBranchReconcileOutcome.mockResolvedValue({ retirementObligations: [{ ...RELEASE, createdAt: CREATED_AT }] });
- prepareInventoriedCheckoutRetirement.mockResolvedValue({ ok: true, review: { digest: 'a'.repeat(64) } });
+ prepareInventoriedCheckoutRetirement.mockResolvedValue({ ok: true, review: review() });
+ retireInventoriedCheckout.mockResolvedValue({ ok: true, archiveDir: '/private/archive', branchDeleted: true });
+ execGh.mockResolvedValue(openView());
+ readClaimOwnershipAgents.mockResolvedValue([]);
+ reserveRepoCleanupRecovery.mockResolvedValue({ admitted: true, attempt: 1 });
listWorktrees.mockResolvedValue([]);
listRemoteHeads.mockResolvedValue(new Map());
cleanupMerged.mockResolvedValue({ cleaned: [] });
existsSync.mockReturnValue(false);
+ readCheckoutPathPresence.mockImplementation(async () => existsSync());
hasBranchMergeEvidence.mockResolvedValue(true);
queuedTasks([]);
getAppById.mockResolvedValue({ id: 'demo-app', name: 'Demo App', repoPath: '/repo' });
@@ -142,19 +166,63 @@ beforeEach(() => {
});
describe('verifyAgentRepoState — clean runs', () => {
+ it.each([['broken leaf symlink', true], ['unreadable EACCES leaf', null]])('never treats %s as absent or verified cleanup', async (_name, presence) => {
+ readCheckoutPathPresence.mockResolvedValue(presence);
+ const result = await run();
+ expect(result.verified).toBe(false);
+ expect(result.observed?.worktreePresent).toBe(presence);
+ expect(result.skipReason).not.toBe('already-absent-preservation-unverified');
+ expect(addTask).not.toHaveBeenCalled();
+ });
+
+ it('keeps a reused branch with a different checkout out of recovery across owner completion', async () => {
+ listWorktrees.mockResolvedValue([{ ...RELEASE, path: '/repo/new-owner' }]);
+ readClaimOwnershipAgents.mockResolvedValue([{ id: 'new-owner', status: 'running' }]);
+ for (let i = 0; i < 70; i++) expect(await run()).toMatchObject({ skipReason: 'checkout-incarnation-changed', recoveryTaskId: null });
+ readClaimOwnershipAgents.mockResolvedValue([{ id: 'new-owner', status: 'completed', result: { success: true } }]);
+ expect(await run()).toMatchObject({ skipReason: 'checkout-incarnation-changed', recoveryTaskId: null });
+ expect(addTask).not.toHaveBeenCalled();
+ expect(prepareInventoriedCheckoutRetirement).not.toHaveBeenCalled();
+ });
+
+ it('retains a recreated same-path checkout despite identical branch and head', async () => {
+ listWorktrees.mockResolvedValue([RELEASE]);
+ readCompletedCheckoutIdentity.mockResolvedValue({ head: HEAD, incarnation: { pointer: { ino: 'new' } } });
+ expect(await run({ agentState: agentState({ completedCheckouts: [{ ...RELEASE, incarnation: { pointer: { ino: 'old' } } }] }) })).toMatchObject({ skipReason: 'checkout-incarnation-changed' });
+ expect(addTask).not.toHaveBeenCalled();
+ });
+
+ it('keeps missing checkout/ref integration separate from unavailable private content preservation', async () => {
+ const state = agentState({ reviewLoopMergeTarget: { url: 'https://github.com/example/repo/pull/7' } });
+ for (let i = 0; i < 70; i++) expect(await run({ agentState: state })).toMatchObject({ verified: false, skipReason: 'already-absent-preservation-unverified' });
+ expect(recordCleanupOutcome).toHaveBeenLastCalledWith('agent-1', expect.objectContaining({ status: 'already-absent', committedIntegrationVerified: true }));
+ expect(addTask).not.toHaveBeenCalled();
+ expect(retireInventoriedCheckout).not.toHaveBeenCalled();
+ });
+
+ it('does not associate a stored foreign-repository PR number with this repository', async () => {
+ localBranch(true);
+ existsSync.mockReturnValue(true);
+ await run({ agentState: agentState({ reviewLoopMergeTarget: { url: 'https://github.com/foreign/repo/pull/7' } }) });
+ expect(getPullRequestState).not.toHaveBeenCalled();
+ expect(addTask).not.toHaveBeenCalled();
+ });
+
it('files nothing when the worktree, branch and PR all landed', async () => {
- findPullRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://example.com/pr/1', detail: 'MERGED' });
+ findPullRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://github.com/example/repo/pull/1', detail: 'MERGED' });
const result = await run();
- expect(result.verified).toBe(true);
+ expect(result.verified).toBe(false);
+ expect(result.skipReason).toBe('already-absent-preservation-unverified');
expect(result.issues).toEqual([]);
expect(addTask).not.toHaveBeenCalled();
expect(addNotification).not.toHaveBeenCalled();
});
it('reads the PR state from the list call rather than a second forge round trip', async () => {
- findPullRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://example.com/pr/1', detail: 'merged' });
+ findPullRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://github.com/example/repo/pull/1', detail: 'merged' });
+ localBranch(true);
const result = await run();
expect(result.observed.prState).toBe('MERGED');
expect(findPullRequestForBranch).toHaveBeenCalledTimes(1);
@@ -165,15 +233,16 @@ describe('verifyAgentRepoState — divergent runs', () => {
it('retires a clean merged branch deterministically instead of queuing an agent', async () => {
existsSync.mockReturnValue(true);
localBranch(true);
- findPullRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://example.com/pr/1', detail: 'MERGED' });
- cleanupMerged.mockResolvedValue({ cleaned: [BRANCH], skipped: [] });
+ findPullRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://github.com/example/repo/pull/1', detail: 'MERGED' });
+ listWorktrees.mockResolvedValue([RELEASE]);
+ prepareInventoriedCheckoutRetirement.mockResolvedValue({ ok: true, review: { ...review(), comparison: { disposition: 'integrated', localPatch: '', difference: '' } } });
const result = await run();
expect(result).toMatchObject({ verified: true, recoveryTaskId: null });
- expect(cleanupMerged).toHaveBeenCalledWith('/repo', 'main', [{ branch: BRANCH, upstreamGone: true }]);
+ expect(retireInventoriedCheckout).toHaveBeenCalledWith(expect.objectContaining({ review: expect.objectContaining({ acceptSuperseded: false }) }), expect.objectContaining({ beforeMutation: expect.any(Function) }));
expect(addTask).not.toHaveBeenCalled();
- expect(updateAgent).toHaveBeenCalledWith('agent-1', { metadata: { maintenanceOutcome: 'deterministic-cleanup' } });
+ expect(recordCleanupOutcome).toHaveBeenCalledWith('agent-1', expect.objectContaining({ status: 'verified', reason: 'retirement-receipt-verified' }));
});
it('files ONE recovery task for a leftover worktree and branch after a merged PR', async () => {
@@ -182,7 +251,7 @@ describe('verifyAgentRepoState — divergent runs', () => {
existsSync.mockReturnValue(true);
localBranch(true);
listWorktrees.mockResolvedValue([{ ...RELEASE, branch: `refs/heads/${BRANCH}` }]);
- findPullRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://example.com/pr/1', detail: 'MERGED' });
+ findPullRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://github.com/example/repo/pull/1', detail: 'MERGED' });
const result = await run();
@@ -227,12 +296,12 @@ describe('verifyAgentRepoState — divergent runs', () => {
existsSync.mockReturnValue(true);
localBranch(true);
listWorktrees.mockResolvedValue([{ ...RELEASE, branch: `refs/heads/${BRANCH}` }]);
- findPullRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://example.com/pr/1', detail: 'MERGED' });
+ findPullRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://github.com/example/repo/pull/1', detail: 'MERGED' });
prepareInventoriedCheckoutRetirement.mockResolvedValue({ ok: false, reason: 'active-agent-owner' });
expect(await run()).toMatchObject({ verified: false, skipReason: 'active-agent-owner', recoveryTaskId: null });
expect(addTask).not.toHaveBeenCalled();
expect(recordBranchReconcileOutcome).toHaveBeenCalledWith('demo-app', expect.objectContaining({ reason: 'active-agent-owner' }));
- prepareInventoriedCheckoutRetirement.mockResolvedValue({ ok: true, review: { digest: 'b'.repeat(64) } });
+ prepareInventoriedCheckoutRetirement.mockResolvedValue({ ok: true, review: { ...review(), digest: 'b'.repeat(64) } });
expect(await run()).toMatchObject({ verified: false, recoveryTaskId: 'task-recovery-1' });
expect(prepareInventoriedCheckoutRetirement).toHaveBeenCalledTimes(2);
});
@@ -240,7 +309,7 @@ describe('verifyAgentRepoState — divergent runs', () => {
it.each(['locked', 'persistence-failed', 'obligation-missing', 'inventory-missing'])('preserves %s cleanup without shell fallback', async cause => {
existsSync.mockReturnValue(true);
localBranch(true);
- findPullRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://example.com/pr/1', detail: 'MERGED' });
+ findPullRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://github.com/example/repo/pull/1', detail: 'MERGED' });
listWorktrees.mockResolvedValue(cause === 'inventory-missing' ? [] : [{ ...RELEASE, locked: cause === 'locked', branch: `refs/heads/${BRANCH}` }]);
if (cause === 'persistence-failed') recordBranchReconcileOutcome.mockRejectedValue(new Error('write refused'));
if (cause === 'obligation-missing') recordBranchReconcileOutcome.mockResolvedValue({});
@@ -257,36 +326,40 @@ describe('verifyAgentRepoState — divergent runs', () => {
expect(result.issues.map(i => i.code)).toEqual([REPO_STATE_ISSUES.WORKTREE_PRESENT]);
});
- it('files recovery when GitHub auto-merge has no durable completion owner', async () => {
+ it('holds an orphan OPEN PR waiting for CI through 70 scans without cognitive work', async () => {
localBranch(true);
hasBranchMergeEvidence.mockResolvedValue(false);
- listRemoteHeads.mockResolvedValue(new Map([[BRANCH, 'abc123']]));
- execGit.mockImplementation(async (args) => ({ exitCode: 0, stdout: args[0] === 'rev-parse' ? 'abc123\n' : '' }));
- findPullRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://example.com/pr/9', detail: 'OPEN', autoMergeEnabled: true, headRefOid: 'abc123' });
- const result = await run();
- expect(result.issues.map(issue => issue.code)).toContain(REPO_STATE_ISSUES.PR_UNMERGED);
- expect(result.observed).toMatchObject({ prState: 'OPEN', autoMergeEnabled: true });
- expect(addTask).toHaveBeenCalled();
+ findPullRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://github.com/example/repo/pull/9', detail: 'OPEN', autoMergeEnabled: true, headRefOid: HEAD });
+ for (let i = 0; i < 70; i++) expect(await run()).toMatchObject({ verified: false, skipReason: 'delivery-ci-or-review-pending', recoveryTaskId: null });
+ expect(addTask).not.toHaveBeenCalled();
+ expect(reserveRepoCleanupRecovery).not.toHaveBeenCalled();
});
- it.each([
- ['failed CI', false, 'abc123'],
- ['unpublished local head', true, 'different-head'],
- ])('retains recovery for an auto-merge request with %s', async (_name, autoMergeEnabled, headRefOid) => {
+ it.each(['CONFLICTING', 'FAILURE'])('admits genuine exact-head code repair after %s evidence', async failure => {
localBranch(true);
hasBranchMergeEvidence.mockResolvedValue(false);
- execGit.mockImplementation(async (args) => ({ exitCode: 0, stdout: args[0] === 'rev-parse' ? 'abc123\n' : '' }));
- findPullRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://example.com/pr/9', detail: 'OPEN', autoMergeEnabled, headRefOid });
- const result = await run();
- expect(result.issues.map(issue => issue.code)).toContain(REPO_STATE_ISSUES.PR_UNMERGED);
- expect(addTask).toHaveBeenCalled();
+ findPullRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://github.com/example/repo/pull/9', detail: 'OPEN', headRefOid: HEAD });
+ execGh.mockResolvedValue(openView(failure === 'CONFLICTING' ? { mergeable: failure } : { statusCheckRollup: [{ name: 'CI', conclusion: failure }] }));
+ inspectOrQueueCompletedReview.mockResolvedValue({ disposition: 'queued-review', reason: 'code-repair-queued', taskId: 'review-1' });
+ expect(await run()).toMatchObject({ recoveryTaskId: 'review-1' });
+ expect(inspectOrQueueCompletedReview).toHaveBeenCalledWith(expect.objectContaining({ agentId: 'agent-1', branch: BRANCH, headSha: HEAD, worktreePath: WORKTREE, repairEvidence: expect.objectContaining({ head: HEAD }) }));
+ expect(addTask).not.toHaveBeenCalled();
+ });
+
+ it('does not send changed/unpublished head or malformed forge data to code recovery', async () => {
+ localBranch(true);
+ hasBranchMergeEvidence.mockResolvedValue(false);
+ findPullRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://github.com/example/repo/pull/9', detail: 'OPEN' });
+ execGh.mockResolvedValue(openView({ headRefOid: '3'.repeat(40), mergeable: 'CONFLICTING' }));
+ expect(await run()).toMatchObject({ skipReason: 'delivery-head-unverified', recoveryTaskId: null });
+ expect(addTask).not.toHaveBeenCalled();
});
it('reports an unmerged PR the agent left open', async () => {
localBranch(true);
hasBranchMergeEvidence.mockResolvedValue(false);
listRemoteHeads.mockResolvedValue(new Map([[BRANCH, 'abc123']]));
- findPullRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://example.com/pr/9', detail: 'OPEN' });
+ findPullRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://github.com/example/repo/pull/9', detail: 'OPEN' });
const result = await run();
@@ -296,7 +369,8 @@ describe('verifyAgentRepoState — divergent runs', () => {
REPO_STATE_ISSUES.BRANCH_UNMERGED,
REPO_STATE_ISSUES.PR_UNMERGED,
]);
- expect(addTask.mock.calls[0][0].context).toContain('https://example.com/pr/9');
+ expect(result.skipReason).toBe('delivery-ci-or-review-pending');
+ expect(addTask).not.toHaveBeenCalled();
});
it('does not re-file when a recovery task for the branch already exists', async () => {
@@ -309,11 +383,11 @@ describe('verifyAgentRepoState — divergent runs', () => {
expect(result.recoveryTaskId).toBeNull();
});
- it('still ensures the existing recovery task has a Brain thread', async () => {
+ it('does not create a Brain recovery thread for routine retained content', async () => {
existsSync.mockReturnValue(true);
await run({ prExpected: false });
- expect(ensureTaskThread).toHaveBeenCalledWith(expect.objectContaining({ taskId: 'task-recovery-1' }));
+ expect(ensureTaskThread).not.toHaveBeenCalled();
});
});
@@ -359,7 +433,7 @@ describe('verifyAgentRepoState — never fires', () => {
// The merge-on-green GitHub path never spawns a follow-up TASK — it queues the
// PR on the app record for the next watcher tick. Reading only the task queue
// would call every one of those branches leaked.
- readPendingMergePrs.mockReturnValue([{ prBranch: BRANCH, prUrl: 'https://example.com/pr/2' }]);
+ readPendingMergePrs.mockReturnValue([{ prBranch: BRANCH, prUrl: 'https://github.com/example/repo/pull/2' }]);
existsSync.mockReturnValue(true);
const result = await run();
@@ -393,7 +467,7 @@ describe('verifyAgentRepoState — never fires', () => {
const result = await run();
- expect(result.skipReason).toBe(REPO_STATE_SKIPS.PROBE_INCOMPLETE);
+ expect(result.skipReason).toBe('checkout-inventory-unavailable');
expect(result.verified).toBe(false);
expect(addTask).not.toHaveBeenCalled();
});
@@ -406,8 +480,7 @@ describe('verifyAgentRepoState — never fires', () => {
const result = await run();
- expect(result.skipReason).toBe(REPO_STATE_SKIPS.PROBE_INCOMPLETE);
- expect(result.observed.unreadable).toContain('pull-request');
+ expect(result.skipReason).toBe('absent-checkout-integration-unverified');
expect(addTask).not.toHaveBeenCalled();
});
@@ -419,7 +492,7 @@ describe('verifyAgentRepoState — never fires', () => {
const result = await run();
expect(result.issues.map(i => i.code)).toContain(REPO_STATE_ISSUES.WORKTREE_PRESENT);
- expect(addTask).toHaveBeenCalledTimes(1);
+ expect(addTask).not.toHaveBeenCalled();
});
it('fails closed when the app record cannot be read', async () => {
@@ -460,24 +533,23 @@ describe('verifyAgentRepoState — never fires', () => {
it('reports an unmerged GitLab merge request', async () => {
// GitLab is probed too — leaving it unasked would silently pass an open MR as
// a clean repo. States come back lowercase from glab.
+ localBranch(true);
resolveForgeForRepo.mockResolvedValue({ cli: 'glab', env: null });
findMergeRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://gitlab.example.com/mr/4', number: 4, detail: 'opened' });
const result = await run();
expect(findPullRequestForBranch).not.toHaveBeenCalled();
- expect(result.issues.map(i => i.code)).toEqual([REPO_STATE_ISSUES.PR_UNMERGED]);
- // The remediation must speak glab — a `gh pr merge` line is unrunnable there.
- // The real IID, not a `<iid>` placeholder the recovery agent cannot run.
- expect(addTask.mock.calls[0][0].context).toContain('glab mr merge 4 --yes');
- expect(addTask.mock.calls[0][0].context).not.toContain('--remove-source-branch');
- expect(addTask.mock.calls[0][0].context).not.toContain('gh pr merge');
+ expect(result.issues.map(i => i.code)).toContain(REPO_STATE_ISSUES.PR_UNMERGED);
+ expect(addTask).not.toHaveBeenCalled();
+ expect(result.verified).toBe(false);
});
it('does not claim unmerged work when the merge check could not be answered', async () => {
// `hasBranchMergeEvidence` fails CLOSED (`false`, not a throw) when it cannot read
// a ref — right for its original caller, inverted into a false finding here.
// An unresolvable ref must read as unknown, not as "carries unmerged commits".
+ readLocalBranchPresence.mockResolvedValue(true);
execGit.mockImplementation((args) => {
if (args[0] === 'show-ref') return Promise.resolve({ exitCode: 0, stdout: '', stderr: '' });
// rev-parse --verify fails => the ref could not be resolved
@@ -497,7 +569,8 @@ describe('verifyAgentRepoState — never fires', () => {
resolveForgeForRepo.mockResolvedValue({ cli: 'glab', env: null });
findMergeRequestForBranch.mockResolvedValue({ status: 'found', url: 'https://gitlab.example.com/mr/4', detail: 'merged' });
const result = await run();
- expect(result.verified).toBe(true);
+ expect(result.verified).toBe(false);
+ expect(result.skipReason).toBe('already-absent-preservation-unverified');
});
});
@@ -509,7 +582,7 @@ describe('remediation coverage', () => {
});
it('renders each remediation from the branch, worktree and PR in hand', () => {
- const ctx = { branchName: BRANCH, base: 'main', prUrl: 'https://example.com/pr/1', worktreePath: WORKTREE };
+ const ctx = { branchName: BRANCH, base: 'main', prUrl: 'https://github.com/example/repo/pull/1', worktreePath: WORKTREE };
for (const [code, render] of Object.entries(REPO_STATE_REMEDIATIONS)) {
const text = render(ctx);
expect(text, code).toBeTypeOf('string');
@@ -530,7 +603,7 @@ it.each(['draft', 'leave-open'])('reports divergence without cleanup or recovery
});
describe('claim-swarm completion', () => {
- it('recovers every recorded branch and preserves its independent merge backlink', async () => {
+ it('retains each missing claim checkout without spawning bookkeeping agents', async () => {
const branches = ['claim/issue-11', 'claim/issue-12'];
findPullRequestForBranch.mockImplementation(async branch => ({ status: 'found', detail: 'OPEN', number: branches.indexOf(branch) + 11,
url: `https://github.com/example/repo/pull/${branches.indexOf(branch) + 11}` }));
@@ -538,9 +611,8 @@ describe('claim-swarm completion', () => {
claimBranches: [branches[0]], claimReleasedBranches: branches });
const result = await run({ agentState: state });
expect(result.branches.map(item => item.branch)).toEqual(branches);
- expect(addTask).toHaveBeenCalledTimes(2);
- for (const branch of branches) expect(recordRepoStateRecovery).toHaveBeenCalledWith('agent-1',
- expect.objectContaining({ branch, taskId: 'task-recovery-1' }), { claimRun: true });
+ expect(addTask).not.toHaveBeenCalled();
+ for (const branch of branches) expect(recordCleanupOutcome).toHaveBeenCalledWith('agent-1', expect.objectContaining({ branch, status: 'blocked' }));
expect(cleanupMerged).not.toHaveBeenCalled();
});
it('does not infer branches from output or override manual handoffs and failed retries', async () => {
@@ -563,7 +635,7 @@ describe('durable completion replay', () => {
getTaskById.mockResolvedValue(task());
findPullRequestForBranch.mockResolvedValue({ status: 'found', detail: 'MERGED', url: 'https://github.com/example/repo/pull/7' });
expect(await sweepRepoStateVerifications()).toMatchObject({ checked: 1 });
- expect(recordRepoStateVerification).toHaveBeenCalledWith('agent-1', expect.objectContaining({ status: 'completed' }));
+ expect(recordRepoStateVerification).toHaveBeenCalledWith('agent-1', expect.objectContaining({ status: 'pending' }));
expect(addTask).not.toHaveBeenCalled();
});
it('keeps missing policy pending with an updated retry time rather than granting authority or starving other audits', async () => {
@@ -572,16 +644,13 @@ describe('durable completion replay', () => {
expect(recordRepoStateVerification).toHaveBeenCalledWith('agent-1', expect.objectContaining({ status: 'pending', reasons: ['task-unavailable'], checkedAt: expect.any(String) }));
expect(addTask).not.toHaveBeenCalled();
});
- it('repairs a lost backlink only for the exact duplicate task and parent', async () => {
+ it('uses the exact successor result without creating an unrelated generic recovery task', async () => {
+ localBranch(true);
+ execGh.mockResolvedValue(openView({ number: 7, mergeable: 'CONFLICTING' }));
findPullRequestForBranch.mockResolvedValue({ status: 'found', detail: 'OPEN', url: 'https://github.com/example/repo/pull/7' });
- addTask.mockResolvedValue({ id: 'existing', duplicate: true });
- getTaskById.mockResolvedValue({ metadata: { recoveryOrigin: { parentAgentId: 'agent-1', parentTaskId: 'task-1', subsystem: 'repository-cleanup' },
- recoveryMergeTarget: { url: 'https://github.com/example/repo/pull/7', branch: BRANCH } } });
- await run();
- expect(recordRepoStateRecovery).toHaveBeenCalledWith('agent-1', { taskId: 'existing', url: 'https://github.com/example/repo/pull/7', branch: BRANCH }, { claimRun: false });
- recordRepoStateRecovery.mockClear();
- getTaskById.mockResolvedValue({ metadata: { recoveryOrigin: { parentAgentId: 'someone-else' } } });
- await run();
+ inspectOrQueueCompletedReview.mockResolvedValue({ disposition: 'join-existing', reason: 'review-successor-exists', taskId: 'existing' });
+ expect(await run()).toMatchObject({ skipReason: 'review-successor-exists' });
+ expect(addTask).not.toHaveBeenCalled();
expect(recordRepoStateRecovery).not.toHaveBeenCalled();
});
});
diff --git a/server/services/agentSpawnDispatch.dispatching.test.js b/server/services/agentSpawnDispatch.dispatching.test.js
index 5d93f31aaf..0d230b5b17 100644
--- a/server/services/agentSpawnDispatch.dispatching.test.js
+++ b/server/services/agentSpawnDispatch.dispatching.test.js
@@ -3,13 +3,13 @@
*/
import { beforeEach, describe, expect, it, vi } from 'vitest';
-const f = vi.hoisted(() => ({ registerGate: null, prep: null, publicationActive: false, refusePublication: false }));
+const f = vi.hoisted(() => ({ registerGate: null, prep: null, publicationActive: false, refusePublication: false, updateResult: { ok: true } }));
vi.mock('../lib/checkoutRetirementAdmission.js', () => ({ withCheckoutPublication: vi.fn(async (_repo, work) => {
if (f.refusePublication) throw new Error('checkout-retirement-reserved');
f.publicationActive = true;
try { return await work(); } finally { f.publicationActive = false; }
}) }));
-vi.mock('./cos.js', () => ({ getConfig: async () => ({}), updateTask: async () => ({ ok: true }) }));
+vi.mock('./cos.js', () => ({ getConfig: async () => ({}), updateTask: vi.fn(async () => f.updateResult) }));
vi.mock('./cosAgentLifecycle.js', () => ({
registerAgent: vi.fn(() => f.registerGate),
updateAgent: vi.fn(),
@@ -55,6 +55,7 @@ import { dispatchAgentRun } from './agentSpawnDispatch.js';
import { getActiveAgentIds, protectedAgentIds, setUseRunner } from './agentState.js';
import { spawnDirectly } from './agentCliSpawning.js';
import { prepareAgentWorkspace } from './agentWorkspacePrep.js';
+import { updateTask } from './cos.js';
import { registerAgent } from './cosAgentLifecycle.js';
import { withCheckoutPublication } from '../lib/checkoutRetirementAdmission.js';
@@ -71,6 +72,7 @@ beforeEach(() => {
setUseRunner(false);
f.publicationActive = f.refusePublication = false;
f.registerGate = Promise.resolve();
+ f.updateResult = { ok: true };
f.prep = { outcome: 'ready', workspacePath: '/repos/example', worktreeInfo: null };
});
@@ -113,6 +115,19 @@ describe('dispatchAgentRun ownership window', () => {
expect(getActiveAgentIds()).not.toContain('agent-x');
});
+ it.each([{ error: 'write refused' }, { statusChanged: true }])('never starts a recovered reviewer when its initial pin consumption was not persisted: %j', async result => {
+ f.updateResult = result;
+ f.prep.cleanupReviewPinConsumed = true;
+ const context = newContext();
+ context.task = { ...task, metadata: { cleanupReviewTarget: undefined, cleanupReviewLaunchEvidence: { headSha: 'a'.repeat(40) }, totalSpawnCount: '2' } };
+ expect(await dispatchAgentRun(context)).toBeNull();
+ expect(registerAgent).toHaveBeenCalledOnce();
+ expect(updateTask).toHaveBeenCalledWith(task.id, expect.objectContaining({ metadata: expect.objectContaining({ totalSpawnCount: 3, cleanupReviewTarget: undefined }) }), 'user');
+ expect(spawnDirectly).not.toHaveBeenCalled();
+ expect(context.cleanupOnError).toHaveBeenCalledWith(expect.stringContaining('Failed to persist reviewed-head launch admission'));
+ expect(f.publicationActive).toBe(false);
+ });
+
it('releases the agent when workspace prep blocks the dispatch', async () => {
f.prep = { outcome: 'blocked', reason: 'no workspace' };
const context = newContext();
diff --git a/server/services/agentSpawnDispatch.js b/server/services/agentSpawnDispatch.js
index b1d88b1044..6f2b4df148 100644
--- a/server/services/agentSpawnDispatch.js
+++ b/server/services/agentSpawnDispatch.js
@@ -270,6 +270,10 @@ async function runAgentDispatch(context, { spawnViaRunner } = {}) {
if (updateResult?.error) {
emitLog('warn', `⚠️ in_progress claim for task ${task.id} returned an error (taskType=${task.taskType}): ${updateResult.error}`, { taskId: task.id, error: updateResult.error });
}
+ if (prep.cleanupReviewPinConsumed && (updateResult?.error || updateResult?.statusChanged)) {
+ await context.cleanupOnError('Failed to persist reviewed-head launch admission; retained checkout requires revalidation');
+ return null;
+ }
if (!updateResult) {
await context.cleanupOnError('Failed to update task status');
return null;
diff --git a/server/services/agentWorkspacePrep.js b/server/services/agentWorkspacePrep.js
index 20c60da282..35dbea83bd 100644
--- a/server/services/agentWorkspacePrep.js
+++ b/server/services/agentWorkspacePrep.js
@@ -45,6 +45,7 @@ import { getAppWorkspace, getAppDataForTask } from './agentAppWorkspace.js';
import { createJiraTicketForTask } from './promptSections/appContext.js';
import { INVESTIGATION_TASK_DELIVERY, isInvestigationTask } from '../lib/investigationTasks.js';
import { isNonCommittingCoordinatorTask, resolveTaskHookType } from './taskTypeHooks.js';
+import { leavesPrForHuman, resolvePrCompletion, PR_COMPLETIONS } from '../lib/prDisposition.js';
import { claimBranchAdmission, claimContinuationAdmission, claimContinuationWorkspace } from '../lib/claimContinuation.js';
const ROOT_DIR = PATHS.root;
@@ -110,7 +111,7 @@ export { resolveTaskTargetBranch as resolveTaskExistingBranch } from '../lib/tas
*
* @returns {Promise<{ worktreeInfo: object, adoptedFrom: string }|{ refused: string }|null>}
*/
-async function adoptWorktreeHoldingBranch({ agentId, workspacePath, branchName, preferredPath = null, taskId, allowLiveClaim = false, deepResume = false, adopt = true }) {
+async function adoptWorktreeHoldingBranch({ agentId, workspacePath, branchName, preferredPath = null, taskId, allowLiveClaim = false, deepResume = false, adopt = true, reviewTarget = null }) {
// Fail CLOSED on an unreadable agent list: an empty protected set would read as
// "nothing is running", which is the one wrong answer here — it would move a
// live run's directory. The caller's timed pause is the safe outcome instead.
@@ -146,6 +147,11 @@ async function adoptWorktreeHoldingBranch({ agentId, workspacePath, branchName,
return null;
}
+ if (reviewTarget) {
+ const { validateCleanupReviewTarget } = await import('./cosMergeHandoff.js');
+ const refused = await validateCleanupReviewTarget({ target: reviewTarget, workspacePath: holder.path, requireCheckout: true, launchTaskId: taskId });
+ if (refused) return { refused };
+ }
const worktreeInfo = await adoptWorktree(agentId, workspacePath, holder.path, branchName, ...(deepResume ? [{ deepResume: true }] : [])).catch(err => {
if (err.code === 'DEEP_RESUME_PRESERVED') return { refused: err.message };
emitLog('warn', `🌳 Could not adopt ${holder.path} holding ${branchName} for task ${taskId}: ${err.message}`, { taskId });
@@ -203,6 +209,7 @@ async function prepareRequestedWorktree({
await blockTask(task, reason, 'worktree-failed');
return { outcome: 'blocked', reason };
}
+ const reviewTarget = task.metadata?.cleanupReviewTarget;
const pinnedHead = existingBranch ? resolveTaskPinnedHead(task.metadata) : null;
if (pinnedHead === '') {
return refusePinnedAttach(task, workspacePath, `Task ${task.id} must attach at a reviewed head commit but records none; refusing to check out ${existingBranch}`);
@@ -237,6 +244,7 @@ async function prepareRequestedWorktree({
// its remote tip are proven to be the reviewed commit; only a fresh attach
// can prove both. Releasing an idle sibling holder in place stays allowed.
adopt: !pinnedHead,
+ reviewTarget,
})
: Promise.resolve(null);
@@ -276,7 +284,7 @@ async function prepareRequestedWorktree({
...(task.metadata?.existingBranch && task.metadata?.resumedFromAgentId ? { resumeBranch: existingBranch } : {}),
// Fork coordinates select the remote head, independent of the local branch name.
forkHead: forkHead || undefined,
- expectedHeadSha: pinnedHead || undefined,
+ expectedHeadSha: pinnedHead || reviewTarget?.headSha || undefined,
planId: task.metadata?.planId || undefined,
linkDependencies: !isolateDependencies,
}).catch(err => {
@@ -465,9 +473,26 @@ export async function prepareAgentWorkspace({ agentId, task, onPrepared = result
return onPrepared({ outcome: 'blocked', reason });
}
- const prepareAndRegister = async () => onPrepared(await prepareResolvedWorkspace({
- agentId, task, workspacePath, resolvedApp, resolvedAppName, isReadOnly,
- }));
+ const prepareAndRegister = async () => {
+ const result = await prepareResolvedWorkspace({ agentId, task, workspacePath, resolvedApp, resolvedAppName, isReadOnly });
+ if (result.outcome === 'ready' && task.metadata?.cleanupReviewTarget) {
+ const { validateCleanupReviewTarget } = await import('./cosMergeHandoff.js');
+ const refused = await validateCleanupReviewTarget({ target: task.metadata.cleanupReviewTarget, workspacePath: result.workspacePath, requireCheckout: true, launchTaskId: task.id });
+ if (refused) {
+ await blockTask(task, refused, 'pr-head-moved');
+ return onPrepared({ outcome: 'blocked', reason: refused });
+ }
+ // This is an initial-launch pin. Dispatch registers the owner, then saves
+ // this metadata before starting the provider. A pre-registration failure
+ // leaves the persisted pin intact; a registered coordinator may fix code
+ // and resume under its existing ownership/budget without the initial SHA
+ // blocking its own new commits. Keep the admission as historical evidence.
+ task.metadata.cleanupReviewLaunchEvidence = task.metadata.cleanupReviewTarget;
+ task.metadata.cleanupReviewTarget = undefined;
+ result.cleanupReviewPinConsumed = true;
+ }
+ return onPrepared(result);
+ };
// Resolve once, then admit the entire preparation → registration → spawn
// lifetime. A create/adopt helper's shorter permit cannot protect dependency
// changes or an owner which has not yet been durably registered.
@@ -481,6 +506,17 @@ export async function prepareAgentWorkspace({ agentId, task, onPrepared = result
}
async function prepareResolvedWorkspace({ agentId, task, workspacePath, resolvedApp, resolvedAppName, isReadOnly }) {
+ const recoveryTarget = task.metadata?.cleanupReviewTarget;
+ if (recoveryTarget) {
+ const { validateCleanupReviewTarget } = await import('./cosMergeHandoff.js');
+ const refused = recoveryTarget.repoPath !== workspacePath || resolveTaskTargetBranch(task.metadata) !== recoveryTarget.branch || isReadOnly || leavesPrForHuman(task)
+ || resolvePrCompletion(task.metadata) === PR_COMPLETIONS.LEAVE_OPEN || isTruthyMeta(task.metadata?.reviewLoopLeaveOpen)
+ ? 'review-target-task-changed' : await validateCleanupReviewTarget({ target: recoveryTarget, workspacePath, launchTaskId: task.id });
+ if (refused) {
+ await blockTask(task, refused, 'pr-head-moved');
+ return { outcome: 'blocked', reason: refused };
+ }
+ }
const remediationPin = resolveTaskPinnedHead(task.metadata);
if (remediationPin !== null && (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/i.test(remediationPin)
|| !resolveTaskRemoteBranch(task.metadata))) {
diff --git a/server/services/agentWorkspacePrep.test.js b/server/services/agentWorkspacePrep.test.js
index 7125f20f4c..08586ac603 100644
--- a/server/services/agentWorkspacePrep.test.js
+++ b/server/services/agentWorkspacePrep.test.js
@@ -11,6 +11,8 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
+const recoveryCheck = vi.hoisted(() => vi.fn(async () => null));
+vi.mock('./cosMergeHandoff.js', () => ({ validateCleanupReviewTarget: (...args) => recoveryCheck(...args) }));
const publication = vi.hoisted(() => ({ active: false, refuse: false }));
vi.mock('../lib/checkoutRetirementAdmission.js', () => ({ withCheckoutPublication: vi.fn(async (_repo, work) => {
if (publication.refuse) throw new Error('checkout-retirement-reserved');
@@ -89,7 +91,7 @@ import { PINNED_HEAD_MOVED, createWorktree, adoptWorktree, findAdoptableWorktree
import { ensureDir, PATHS } from '../lib/fileUtils.js';
import { creativeDirectorScratchCwd } from '../lib/spawnCwd.js';
-beforeEach(() => { vi.clearAllMocks(); listWorktrees.mockResolvedValue([]); publication.active = publication.refuse = false; });
+beforeEach(() => { vi.clearAllMocks(); recoveryCheck.mockReset().mockResolvedValue(null); listWorktrees.mockResolvedValue([]); publication.active = publication.refuse = false; });
describe('prepareAgentWorkspace — Creative Director scratch cwd (#4650)', () => {
it('pins a CD no-worktree task to an isolated scratch dir and skips the git pull', async () => {
@@ -748,6 +750,37 @@ describe('prepareAgentWorkspace — the branch is checked out in another worktre
expect(updateTask).not.toHaveBeenCalled();
});
+ it('checks a recovered head before adoption and consumes only its initial-launch pin before registration', async () => {
+ const target = { version: 1, repoPath: PATHS.root, branch: 'cos/task-x/agent-y', headSha: 'a'.repeat(40) };
+ const task = followUpTask({ cleanupReviewTarget: target });
+ findAdoptableWorktreeForBranch.mockResolvedValue({ path: '/mock/worktrees/agent-y', agentId: 'agent-y' });
+ adoptWorktree.mockResolvedValue({ worktreePath: '/mock/worktrees/agent-new', branchName: target.branch, adopted: true });
+ const registered = vi.fn(async result => {
+ expect(task.metadata.cleanupReviewTarget).toBeUndefined();
+ expect(Object.hasOwn(task.metadata, 'cleanupReviewTarget')).toBe(true);
+ expect(task.metadata.cleanupReviewLaunchEvidence).toEqual(target);
+ return result;
+ });
+ expect((await prepareAgentWorkspace({ agentId: 'agent-new', task, onPrepared: registered })).outcome).toBe('ready');
+ expect(recoveryCheck.mock.calls.map(([call]) => call.workspacePath)).toEqual([PATHS.root, '/mock/worktrees/agent-y', '/mock/worktrees/agent-new']);
+ expect(registered).toHaveBeenCalledOnce();
+ // Its own later fixes are governed by the registered coordinator's normal
+ // continuation, not a stale initial-head pin that recursively spawns work.
+ recoveryCheck.mockClear();
+ await prepareAgentWorkspace({ agentId: 'agent-new', task });
+ expect(recoveryCheck).not.toHaveBeenCalled();
+ });
+
+ it('preserves the pin and holder when target drift is detected before adoption', async () => {
+ const target = { version: 1, repoPath: PATHS.root, branch: 'cos/task-x/agent-y', headSha: 'a'.repeat(40) };
+ const task = followUpTask({ cleanupReviewTarget: target });
+ findAdoptableWorktreeForBranch.mockResolvedValue({ path: '/mock/worktrees/agent-y', agentId: 'agent-y' });
+ recoveryCheck.mockResolvedValueOnce(null).mockResolvedValueOnce('review-head-moved');
+ expect((await prepareAgentWorkspace({ agentId: 'agent-new', task })).outcome).toBe('blocked');
+ expect(adoptWorktree).not.toHaveBeenCalled();
+ expect(task.metadata.cleanupReviewTarget).toEqual(target);
+ });
+
// A resolve-and-merge follow-up's whole purpose is landing THIS branch, so the
// user's own trigger is the signal to take over whatever a `/do:next` claim
// left checked out on it — instead of retrying against it until the task gives
diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.js
index 0b5989b07a..e9931ff393 100644
--- a/server/services/agentWorktreeCleanup.js
+++ b/server/services/agentWorktreeCleanup.js
@@ -1103,15 +1103,23 @@ export async function releaseRetryHold({ agentId, task, success, agentMetadata }
* whether an agent actually started or the task is still waiting (no slots,
* daemon stopped, …) rather than guessing.
*/
-export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, prUrl, prBranch, forkHead = null, sourceWorkspace, prCompletion = PR_COMPLETIONS.REVIEW_THEN_MERGE, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewerMaxRounds = {}, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false, reviewerModels = null, reviewerEfforts = null, leaveOpen = false, selfReview = false, dispatch = 'queue' }) {
+export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, prUrl, prBranch, forkHead = null, sourceWorkspace, prCompletion = PR_COMPLETIONS.REVIEW_THEN_MERGE, reviewers = DEFAULT_REVIEWERS, usernames = [], optionalReviewers = [], reviewerMaxRounds = {}, reviewStopMode = DEFAULT_REVIEW_STOP_MODE, reviewerApplies = false, reviewerModels = null, reviewerEfforts = null, leaveOpen = false, selfReview = false, dispatch = 'queue', reviewTarget = null }) {
if (!prUrl || !prBranch) return null;
if (prCompletion === PR_COMPLETIONS.LEAVE_OPEN) return null;
+ if (reviewTarget) {
+ const { validateCleanupReviewTarget } = await import('./cosMergeHandoff.js');
+ if (reviewTarget.prUrl !== prUrl || reviewTarget.branch !== prBranch
+ || reviewTarget.ownerTaskId !== originalTask?.id || reviewTarget.ownerId !== originalAgentId) return { blocked: 'Review recovery identity changed' };
+ const refused = await validateCleanupReviewTarget({ target: reviewTarget, workspacePath: sourceWorkspace });
+ if (refused) return { blocked: refused };
+ }
+
// Recovery belongs to the same durable task. A fresh sys-rl task resets the
// spawn budget on every CI/conflict handoff and recursively nests its title.
// The id hint also recovers receipts written before the marker was retained.
if (isTruthyMeta(originalTask?.metadata?.reviewLoopFollowUp) || originalTask?.id?.startsWith('sys-rl-')) {
- return resumeReviewLoopCoordinator(originalTask.id, prUrl, prBranch);
+ return resumeReviewLoopCoordinator(originalTask.id, prUrl, prBranch, reviewTarget);
}
const parsedPr = git.parsePullRequestUrl(prUrl);
@@ -1254,6 +1262,7 @@ export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, p
simplify: false,
// Marker flags consumed by the agent prompt + completion handler
reviewLoopFollowUp: true,
+ ...(reviewTarget ? { cleanupReviewTarget: reviewTarget, resumeWorktreePath: reviewTarget.worktreePath } : {}),
prCompletion,
// Merge-only run: no reviewers, the prompt is a CI-gate-and-merge procedure.
reviewLoopMergeOnly: mergeOnly,
@@ -1346,7 +1355,7 @@ export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, p
return { ...followUpTask, dispatch: { started: true, reason: null } };
}
-async function resumeReviewLoopCoordinator(taskId, prUrl, prBranch) {
+async function resumeReviewLoopCoordinator(taskId, prUrl, prBranch, reviewTarget = null) {
const { getTaskById } = await import('./cos.js');
const task = await getTaskById(taskId);
if (!task || task.taskType !== 'internal' || !isTruthyMeta(task.metadata?.reviewLoopFollowUp)
@@ -1376,12 +1385,13 @@ async function resumeReviewLoopCoordinator(taskId, prUrl, prBranch) {
}
const result = await updateTask(taskId, {
status: 'pending',
- metadata: { reviewLoopRecoveryReason: 'The handed-off PR needs fresh validation, review or conflict resolution' },
+ metadata: { reviewLoopRecoveryReason: 'The handed-off PR needs fresh validation, review or conflict resolution',
+ ...(reviewTarget ? { cleanupReviewTarget: reviewTarget, resumeWorktreePath: reviewTarget.worktreePath } : {}) },
}, 'internal', {
expectedStatus: 'completed',
expectedMetadata: Object.fromEntries([
'totalSpawnCount', 'reviewLoopFollowUp', 'reviewLoopPRUrl', 'reviewLoopPRBranch',
- 'prCompletion', 'reviewLoopLeaveOpen', 'readOnly', 'jiraTicketId', 'analysisType',
+ 'prCompletion', 'reviewLoopLeaveOpen', 'readOnly', 'jiraTicketId', 'analysisType', 'updatedAt',
].map(key => [key, task.metadata[key]])),
});
if (result?.error) throw new Error(result.error);
diff --git a/server/services/branchReconcileCompletion.js b/server/services/branchReconcileCompletion.js
index d76ba4a61e..7f12c9c439 100644
--- a/server/services/branchReconcileCompletion.js
+++ b/server/services/branchReconcileCompletion.js
@@ -29,6 +29,16 @@ export async function settleBranchReconcileRun(agent) {
});
const { getBranchReconcileOutcome, recordBranchReconcileOutcome } = await import('./taskSchedule.js');
const outcome = await getBranchReconcileOutcome(app.id);
+ const { recordRepoCleanupRecovery, recordCleanupOutcome } = await import('./cosAgentLifecycle.js');
+ for (const target of task.metadata.reconcileRetirements || []) {
+ if (target.cognition?.ownerAgentId && target.cognition.observation) {
+ await recordRepoCleanupRecovery(target.cognition.ownerAgentId, target.release.branch, target.cognition.observation,
+ { phase: 'completed', taskId: task.id });
+ }
+ const verified = hasRetirementReceipt(outcome, { ...target.release, createdAt: target.createdAt });
+ await recordCleanupOutcome(agent.id, { ...target.release, status: verified ? 'verified' : 'blocked',
+ reason: verified ? 'retirement-receipt-verified' : 'retirement-receipt-unverified' });
+ }
const unverifiedRetirements = unresolvedRetirements(outcome,
(task.metadata.reconcileRetirements || []).map(({ release, createdAt }) => ({ ...release, createdAt, reason: 'retirement-review-pending' })));
if (task.metadata.reconcileRetirements?.length) {
@@ -64,10 +74,18 @@ export async function settleRetirementReviewRun(agent) {
if (agent?.metadata?.recoveryOrigin?.subsystem !== 'repository-cleanup') return null;
const task = await getTaskById(agent.taskId);
const target = task?.metadata?.retirementReview;
- if (!target?.appId || !target.release?.branch || !target.release.path || !target.release.head) return null;
+ const { recordCleanupOutcome } = await import('./cosAgentLifecycle.js');
+ if (!target?.appId || !target.release?.branch || !target.release.path || !target.release.head) {
+ await recordCleanupOutcome(agent.id, { status: 'blocked', reason: 'legacy-cleanup-receipt-unverified' });
+ return { verified: false };
+ }
const { getBranchReconcileOutcome, recordBranchReconcileOutcome } = await import('./taskSchedule.js');
const outcome = await getBranchReconcileOutcome(target.appId);
- if (hasRetirementReceipt(outcome, { ...target.release, createdAt: target.createdAt })) return { verified: true };
+ if (hasRetirementReceipt(outcome, { ...target.release, createdAt: target.createdAt })) {
+ await recordCleanupOutcome(agent.id, { status: 'verified', reason: 'retirement-receipt-verified', ...target.release });
+ return { verified: true };
+ }
+ await recordCleanupOutcome(agent.id, { status: 'blocked', reason: 'retirement-receipt-unverified', ...target.release });
await recordBranchReconcileOutcome(target.appId, {
status: 'incomplete', reason: 'retirement-receipt-unverified',
retirementObligations: [{ ...target.release, reason: 'retirement-receipt-unverified' }],
diff --git a/server/services/branchReconcileCompletion.test.js b/server/services/branchReconcileCompletion.test.js
index aa49728056..f73c25f336 100644
--- a/server/services/branchReconcileCompletion.test.js
+++ b/server/services/branchReconcileCompletion.test.js
@@ -1,4 +1,5 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
+vi.mock('./cosAgentLifecycle.js', () => ({ recordCleanupOutcome: vi.fn(async () => true), recordRepoCleanupRecovery: vi.fn(async () => true) }));
vi.mock('./apps.js', () => ({ getAppById: vi.fn() }));
vi.mock('./cosTaskStore.js', () => ({ getTaskById: vi.fn() }));
vi.mock('./agentState.js', () => ({ getActiveAgentIds: vi.fn(() => new Set(['active'])) }));
@@ -10,6 +11,7 @@ vi.mock('./branchReconcile.js', async (importOriginal) => ({
vi.mock('./taskSchedule.js', () => ({ getBranchReconcileOutcome: vi.fn(), recordBranchReconcileOutcome: vi.fn() }));
vi.mock('./cosEvents.js', () => ({ emitLog: vi.fn() }));
vi.mock('./prWatcher.js', () => ({ readPendingMergePrs: vi.fn(() => [{ prBranch: 'claim/queued' }]) }));
+import { recordCleanupOutcome, recordRepoCleanupRecovery } from './cosAgentLifecycle.js';
import { getAppById } from './apps.js';
import { getTaskById } from './cosTaskStore.js';
import { readClaimOwnershipAgents } from './cosClaimOwnership.js';
@@ -18,12 +20,12 @@ import { emitLog } from './cosEvents.js';
import { getBranchReconcileOutcome, recordBranchReconcileOutcome } from './taskSchedule.js';
import { settleBranchReconcileRun, settleRetirementReviewRun } from './branchReconcileCompletion.js';
-const agent = { taskId: 'task-example', metadata: { taskAnalysisType: 'branch-reconcile', taskApp: 'example' } };
+const agent = { id: 'agent-reconcile', taskId: 'task-example', metadata: { taskAnalysisType: 'branch-reconcile', taskApp: 'example' } };
describe('branch reconciliation completion', () => {
beforeEach(() => {
vi.clearAllMocks();
getBranchReconcileOutcome.mockResolvedValue(null);
- getTaskById.mockResolvedValue({ metadata: { perpetual: false } });
+ getTaskById.mockResolvedValue({ id: 'task-example', metadata: { perpetual: false } });
getAppById.mockResolvedValue({ id: 'example', repoPath: '/example/repo', forgeAccount: 'example-account' });
readClaimOwnershipAgents.mockResolvedValue([]);
reconcile.mockResolvedValue({ cleaned: ['merged'], reapedSuperseded: ['superseded'], inFlight: [], skipped: [], worktreeInventory: [], orphanRemotes: { reported: [] } });
@@ -37,7 +39,7 @@ describe('branch reconciliation completion', () => {
});
it('requires an exact persisted archive receipt after the review task reports success', async () => {
const release = { branch: 'claim/issue-42', path: '/example/checkout', head: 'a'.repeat(40) };
- getTaskById.mockResolvedValue({ metadata: { reconcileRetirements: [{ release, createdAt: '2026-10-20T00:00:00Z', prUrl: 'https://github.com/example/repo/pull/42' }] } });
+ getTaskById.mockResolvedValue({ id: 'task-example', metadata: { reconcileRetirements: [{ release, cognition: { ownerAgentId: 'original-owner', observation: 'exact-observation' }, createdAt: '2026-10-20T00:00:00Z', prUrl: 'https://github.com/example/repo/pull/42' }] } });
getBranchReconcileOutcome.mockResolvedValue({ retired: [{ ...release, branchDeleted: true }] });
await settleBranchReconcileRun({ ...agent, result: { success: true } });
expect(recordBranchReconcileOutcome).toHaveBeenCalledWith('example', expect.objectContaining({ status: 'incomplete', reason: 'retirement-receipt-unverified' }));
@@ -46,6 +48,7 @@ describe('branch reconciliation completion', () => {
getBranchReconcileOutcome.mockResolvedValue({ retired: [{ ...release, branchDeleted: true, archiveDir: '/example/archive', retiredAt: '2026-10-20T00:01:00Z' }] });
await settleBranchReconcileRun({ ...agent, result: { success: true } });
expect(recordBranchReconcileOutcome).not.toHaveBeenCalled();
+ expect(recordRepoCleanupRecovery).toHaveBeenCalledWith('original-owner', release.branch, 'exact-observation', { phase: 'completed', taskId: 'task-example' });
});
it('reports inventory-only protected and detached worktrees plus retained claims', async () => {
@@ -140,7 +143,8 @@ describe('scoped retirement recovery completion', () => {
expect(await settleRetirementReviewRun(recovery)).toEqual({ verified: true });
expect(recordBranchReconcileOutcome).not.toHaveBeenCalled();
getTaskById.mockResolvedValue({ metadata: {} });
- expect(await settleRetirementReviewRun(recovery)).toBeNull();
+ expect(await settleRetirementReviewRun(recovery)).toEqual({ verified: false });
+ expect(recordCleanupOutcome).toHaveBeenLastCalledWith(recovery.id, expect.objectContaining({ status: 'blocked', reason: 'legacy-cleanup-receipt-unverified' }));
expect(recordBranchReconcileOutcome).not.toHaveBeenCalled();
});
});
diff --git a/server/services/branchReconcileRetirement.js b/server/services/branchReconcileRetirement.js
index 05f81b2c53..ec5f8ff454 100644
--- a/server/services/branchReconcileRetirement.js
+++ b/server/services/branchReconcileRetirement.js
@@ -1,4 +1,5 @@
/** Review work is dispatchable; a review hold is never deletion authority. */
+import { processAuditFingerprint } from '../lib/persistentMindProcessAudit.js';
import { agentApiCurl } from '../lib/agentApiToken.js';
import { localApiBaseUrl } from '../lib/networkExposure.js';
import { parsePullRequestUrl } from '../lib/gitForge.js';
@@ -44,6 +45,7 @@ async function mergedPrUrl(app, branch, tip) {
export async function prepareReconcileRetirements(app, result, deps = {}) {
const candidates = [];
const held = [];
+ const retired = [];
const readPr = deps.readPr || mergedPrUrl;
const prepare = deps.prepare || (await import('./heldCheckoutRecovery.js')).prepareInventoriedCheckoutRetirement;
for (const branch of result.wip || []) {
@@ -59,14 +61,60 @@ export async function prepareReconcileRetirements(app, result, deps = {}) {
// The preview's policy gate requires completed successful legacy review
// owners. An empty policy set after a concurrent change is not that proof.
if (!prepared.review?.policy?.policies?.length) { held.push({ ...release, reason: 'retirement-policy-changed' }); continue; }
- candidates.push({ ...branch, state: 'REVIEW_RETIREMENT', retirement: { release, prUrl, digest: prepared.review.digest } });
+ if (!['integrated', 'review-supersession'].includes(prepared.review.comparison?.disposition)
+ || typeof prepared.review.comparison.localPatch !== 'string' || typeof prepared.review.comparison.difference !== 'string') {
+ held.push({ ...release, reason: 'retirement-comparison-unavailable' }); continue;
+ }
+ // Exact affected-file equality plus exact published head requires no
+ // cognitive judgment. The service repeats all guards and archive checks.
+ if (prepared.review.forge?.prHead === release.head
+ && prepared.review.comparison?.disposition === 'integrated'
+ && prepared.review.comparison.difference === '') {
+ const retire = deps.retire || (await import('./heldCheckoutRecovery.js')).retireInventoriedCheckout;
+ const result = await retire({ appId: app.id, release,
+ review: { prUrl, digest: prepared.review.digest, acceptSuperseded: false } }, { beforeMutation: assertAutomaticRetirementAllowed });
+ if (result.ok && result.archiveDir && result.branchDeleted === true) retired.push(release);
+ else held.push({ ...release, reason: result.reason || 'retirement-receipt-unverified' });
+ continue;
+ }
+ candidates.push({ ...branch, state: 'REVIEW_RETIREMENT', retirement: { release, prUrl, digest: prepared.review.digest,
+ cognition: retirementCognitiveIdentity(prepared.review, release, prUrl) } });
} catch (error) {
- const reason = ['retirement-pr-ambiguous', 'retirement-forge-unsupported'].includes(error.message)
+ const reason = ['retirement-pr-ambiguous', 'retirement-forge-unsupported', 'daemon-stopped', 'automatic-retirement-disabled'].includes(error.message)
? error.message : 'retirement-review-unavailable';
held.push({ ...release, reason });
}
}
- return { candidates, held };
+ return { candidates, held, retired };
+}
+
+/** Re-read daemon authority at each automatic mutation boundary. Manual API
+ * callers keep their existing operator-authorized contract.
+ */
+export async function assertAutomaticRetirementAllowed() {
+ const [{ isDaemonRunning, loadState }, { getDomainMode }] = await Promise.all([
+ import('./cosState.js'), import('../lib/domainAutonomy.js'),
+ ]);
+ if (!isDaemonRunning()) throw new Error('daemon-stopped');
+ const state = await loadState();
+ if (state.paused || getDomainMode(state.config, 'cos') !== 'execute') throw new Error('automatic-retirement-disabled');
+}
+
+/** The review's relevant source/history, not timestamp/default-ref churn. */
+export function retirementCognitiveIdentity(review, release, prUrl) {
+ const owners = [...(review.policy?.policies || [])].sort((a, b) => String(b.startedAt).localeCompare(String(a.startedAt)) || String(a.id).localeCompare(String(b.id)));
+ return { ownerAgentId: owners[0]?.id || null, observation: processAuditFingerprint({
+ release: { branch: release.branch, path: release.path, head: release.head }, prUrl,
+ localPatch: review.comparison?.localPatch, difference: review.comparison?.difference,
+ disposition: review.comparison?.disposition,
+ }) };
+}
+
+export async function reserveRetirementReview(branch) {
+ const identity = branch.retirement?.cognition;
+ if (!identity?.ownerAgentId || !identity.observation) return { admitted: false };
+ const { reserveRepoCleanupRecovery } = await import('./cosAgentLifecycle.js');
+ return reserveRepoCleanupRecovery(identity.ownerAgentId, branch.branch, identity.observation);
}
export function retirementReviewInstructions(branch, appId) {
diff --git a/server/services/branchReconcileRetirement.test.js b/server/services/branchReconcileRetirement.test.js
index 76da4aa242..3a01fde0e5 100644
--- a/server/services/branchReconcileRetirement.test.js
+++ b/server/services/branchReconcileRetirement.test.js
@@ -1,5 +1,5 @@
import { describe, expect, it, vi } from 'vitest';
-import { prepareReconcileRetirements, retirementReviewInstructions } from './branchReconcileRetirement.js';
+import { prepareReconcileRetirements, retirementReviewInstructions, retirementCognitiveIdentity } from './branchReconcileRetirement.js';
const forge = vi.hoisted(() => ({ read: vi.fn() }));
vi.mock('./github.js', () => ({ execGh: forge.read }));
@@ -14,10 +14,42 @@ const tree = { branch: branch.branch, path: branch.worktreePath, head, managed:
const scan = (b = {}, t = {}) => ({ wip: [{ ...branch, ...b }], worktreeInventory: [{ ...tree, ...t }] });
const setup = () => ({
readPr: vi.fn(async () => 'https://github.com/example/repo/pull/42'),
- prepare: vi.fn(async () => ({ ok: true, review: { digest: 'd'.repeat(64), policy: { policies: [{ id: 'old-owner', status: 'completed', success: true }] } } })),
+ prepare: vi.fn(async () => ({ ok: true, review: { digest: 'd'.repeat(64), policy: { policies: [{ id: 'old-owner', status: 'completed', success: true }] }, comparison: { disposition: 'review-supersession', localPatch: '+old', difference: '+new' }, forge: { prHead: head } } })),
});
describe('historical completed-checkout review obligations', () => {
+ it('retires integrated exact-head work without cognitive dispatch through the fenced service', async () => {
+ const deps = setup();
+ const prepared = await deps.prepare();
+ prepared.review.comparison = { disposition: 'integrated', localPatch: '', difference: '' };
+ deps.prepare.mockResolvedValue(prepared);
+ deps.retire = vi.fn(async () => ({ ok: true, branchDeleted: true, archiveDir: '/private/verified-archive' }));
+ const result = await prepareReconcileRetirements(app, scan(), deps);
+ expect(result.candidates).toEqual([]);
+ expect(result.retired).toEqual([expect.objectContaining({ branch: branch.branch, head })]);
+ expect(deps.retire).toHaveBeenCalledWith(expect.objectContaining({ release: expect.objectContaining({ head }),
+ review: { prUrl: 'https://github.com/example/repo/pull/42', digest: 'd'.repeat(64), acceptSuperseded: false } }),
+ { beforeMutation: expect.any(Function) });
+ });
+
+ it('retains a missing archive receipt across repeated deterministic attempts without dispatch', async () => {
+ const deps = setup();
+ const prepared = await deps.prepare();
+ prepared.review.comparison = { disposition: 'integrated', localPatch: '', difference: '' };
+ deps.prepare.mockResolvedValue(prepared);
+ deps.retire = vi.fn(async () => ({ ok: true, branchDeleted: true }));
+ for (let n = 0; n < 70; n++) expect(await prepareReconcileRetirements(app, scan(), deps)).toMatchObject({
+ candidates: [], retired: [], held: [{ reason: 'retirement-receipt-unverified' }],
+ });
+ });
+
+ it('does not wake cognitive review for an unrelated default advance, timestamp or digest change', () => {
+ const review = { policy: { policies: [{ id: 'original-owner' }] }, comparison: { disposition: 'superseded', localPatch: '+local', difference: '+replacement' }, digest: 'old', forge: { defaultHead: 'a' } };
+ const first = retirementCognitiveIdentity(review, tree, 'https://github.com/example/repo/pull/42');
+ expect(retirementCognitiveIdentity({ ...review, digest: 'new', observedAt: 'later', forge: { defaultHead: 'b' } }, tree, 'https://github.com/example/repo/pull/42')).toEqual(first);
+ expect(retirementCognitiveIdentity({ ...review, comparison: { ...review.comparison, difference: '+changed source' } }, tree, 'https://github.com/example/repo/pull/42')).not.toEqual(first);
+ });
+
it('dispatches a scoped obligation only after the live preview accepts the exact release', async () => {
const deps = setup();
const result = await prepareReconcileRetirements(app, scan(), deps);
diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.js
index 2b817cef3f..5cf01f7141 100644
--- a/server/services/cleanupAgentWorktree.test.js
+++ b/server/services/cleanupAgentWorktree.test.js
@@ -1,3 +1,5 @@
+const recoveryCheck = vi.hoisted(() => vi.fn(async () => null));
+vi.mock('./cosMergeHandoff.js', () => ({ validateCleanupReviewTarget: (...args) => recoveryCheck(...args) }));
vi.mock('./branchCompletionPolicy.js', () => ({ recordBranchCompletionPolicy: vi.fn() }));
vi.mock('./cosClaimOwnership.js', () => ({ readClaimOwnershipAgents: vi.fn() }));
import { readClaimOwnershipAgents } from './cosClaimOwnership.js';
@@ -1878,6 +1880,17 @@ describe('spawnReviewLoopFollowUp', () => {
readClaimOwnershipAgents.mockResolvedValue([]);
});
+ it('pins a missing-review followup to its inspected owner and head without resetting the task budget', async () => {
+ const originalTask = { id: 'task-owner', metadata: { app: 'example' } };
+ const reviewTarget = { ownerId: 'owner', ownerTaskId: originalTask.id, prUrl: 'https://github.com/o/r/pull/7', branch: 'feature', headSha: 'a'.repeat(40), worktreePath: '/worktree' };
+ const request = { originalAgentId: 'owner', originalTask, prUrl: reviewTarget.prUrl, prBranch: 'feature', sourceWorkspace: '/repo', reviewTarget, reviewers: ['codex'] };
+ const task = await spawnReviewLoopFollowUp(request);
+ expect(task.metadata).toMatchObject({ cleanupReviewTarget: reviewTarget, resumeWorktreePath: '/worktree', reviewLoopMergeOnly: false });
+ recoveryCheck.mockResolvedValueOnce('review-head-moved');
+ expect(await spawnReviewLoopFollowUp(request)).toEqual({ blocked: 'review-head-moved' });
+ expect(addTask).toHaveBeenCalledOnce();
+ });
+
it('resumes a persisted coordinator without resetting its budget or creating a descendant', async () => {
const task = { id: 'sys-rl-original', taskType: 'internal', status: 'completed', metadata: {
reviewLoopFollowUp: 'true', reviewLoopPRUrl: 'https://github.com/o/r/pull/7',
diff --git a/server/services/completedCheckoutEvidence.js b/server/services/completedCheckoutEvidence.js
index d28508b5af..0069eb2a41 100644
--- a/server/services/completedCheckoutEvidence.js
+++ b/server/services/completedCheckoutEvidence.js
@@ -19,7 +19,7 @@ async function filesystemIdentity(path, type) {
return { dev: String(stat.dev), ino: String(stat.ino), birthtimeNs: String(stat.birthtimeNs) };
}
-async function readCheckoutIdentity({ repoPath, branch, path, head }) {
+export async function readCompletedCheckoutIdentity({ repoPath, branch, path, head }) {
const { listWorktrees } = await import('./worktreeManager.js');
const repository = await realpath(repoPath);
const checkout = await realpath(path);
@@ -49,19 +49,21 @@ async function readCheckoutIdentity({ repoPath, branch, path, head }) {
export async function captureCompletedCheckouts(agent, { success } = {}) {
const meta = agent?.metadata;
if (success !== true || !['running', 'paused'].includes(agent?.status) || !agent.id
- || !Number.isFinite(Date.parse(agent.startedAt)) || !isTruthyMeta(meta?.claimPicksOwnBranch)
- || typeof meta.sourceWorkspace !== 'string' || !Array.isArray(meta.claimBranches)) return [];
+ || !Number.isFinite(Date.parse(agent.startedAt)) || typeof meta?.sourceWorkspace !== 'string') return [];
+ const claim = isTruthyMeta(meta.claimPicksOwnBranch);
+ const branches = claim ? meta.claimBranches : meta.isWorktree === true && meta.worktreeBranch ? [meta.worktreeBranch] : null;
+ if (!Array.isArray(branches)) return [];
const { listWorktrees } = await import('./worktreeManager.js');
const trees = await listWorktrees(meta.sourceWorkspace).catch(() => null);
if (!trees) return [];
const receipts = [];
- for (const branch of new Set(meta.claimBranches)) {
+ for (const branch of new Set(branches)) {
if (typeof branch !== 'string' || !branch) continue;
const holders = trees.filter(tree => shortBranch(tree.branch) === branch);
- if (holders.length !== 1) continue;
+ if (holders.length !== 1 || (!claim && resolve(holders[0].path) !== resolve(meta.workspacePath || ''))) continue;
const target = { repoPath: meta.sourceWorkspace, branch, path: holders[0].path, head: holders[0].head };
- const first = await readCheckoutIdentity(target).catch(() => null);
- if (!first || !same(first, await readCheckoutIdentity(target).catch(() => null))) continue;
+ const first = await readCompletedCheckoutIdentity(target).catch(() => null);
+ if (!first || !same(first, await readCompletedCheckoutIdentity(target).catch(() => null))) continue;
receipts.push({ version: 1, agentId: agent.id, startedAt: agent.startedAt, capturedAt: new Date().toISOString(), ...first });
}
return receipts;
@@ -72,7 +74,7 @@ export async function captureCompletedCheckouts(agent, { success } = {}) {
*/
export async function hasCompletedCheckoutEvidence(records, target) {
if (!Array.isArray(records)) return false;
- const current = await readCheckoutIdentity(target).catch(() => null);
+ const current = await readCompletedCheckoutIdentity(target).catch(() => null);
if (!current) return false;
const scoped = (await Promise.all(records.map(async agent => {
const meta = agent?.metadata;
diff --git a/server/services/completedCheckoutEvidence.test.js b/server/services/completedCheckoutEvidence.test.js
index 8609fb43f4..fb8fdc10f2 100644
--- a/server/services/completedCheckoutEvidence.test.js
+++ b/server/services/completedCheckoutEvidence.test.js
@@ -28,6 +28,15 @@ describe('completed claim checkout evidence', () => {
});
afterEach(async () => { await rm(scratch, { recursive: true, force: true, maxRetries: 3 }); });
+ it('captures the exact ordinary checkout before completion without granting claim authority', async () => {
+ agent.metadata = { isWorktree: true, sourceWorkspace: repoPath, workspacePath: path, worktreeBranch: branch };
+ const receipts = await captureCompletedCheckouts(agent, { success: true });
+ expect(receipts).toHaveLength(1);
+ expect(receipts[0]).toMatchObject({ branch, head, incarnation: { pointer: { ino: expect.any(String) } } });
+ expect(await hasCompletedCheckoutEvidence([completed(receipts)], target())).toBe(false);
+ expect(await captureCompletedCheckouts({ ...agent, metadata: { ...agent.metadata, workspacePath: repoPath } }, { success: true })).toEqual([]);
+ });
+
it('rejects a new checkout reusing the completed branch, path and exact head', async () => {
const receipts = await captureCompletedCheckouts(agent, { success: true });
expect(receipts).toHaveLength(1);
diff --git a/server/services/cosAgentLifecycle.js b/server/services/cosAgentLifecycle.js
index 03a76904f8..59b3cd627a 100644
--- a/server/services/cosAgentLifecycle.js
+++ b/server/services/cosAgentLifecycle.js
@@ -146,7 +146,67 @@ async function archiveCompletedAgent(agentId, agent) {
* lock serializes live updates and archive rewrites; no transcript is loaded.
*/
export function recordRepoStateVerification(agentId, verification) {
- return updateCompletionReceipt(agentId, metadata => ({ ...metadata, repoStateVerification: verification }));
+ return updateCompletionReceipt(agentId, metadata => ({ ...metadata, repoStateVerification: { ...metadata.repoStateVerification, ...verification } }));
+}
+
+/** Reserve a cognitive recovery once per exact observation on its original run.
+ * Persist before dispatch: an interrupted publication stays held, never launches
+ * another agent just because the old task completed or the server restarted.
+ */
+export async function reserveRepoCleanupRecovery(agentId, branch, observation) {
+ let reservation = null;
+ const saved = await updateCompletionReceipt(agentId, async metadata => {
+ const prior = metadata.repoCleanupRecoveries?.[branch];
+ const history = prior?.observations || (prior?.observation ? [prior.observation] : []);
+ const refuse = reason => { reservation = { ...prior, admitted: false, reason }; return metadata; };
+ // A changed observation never steals an active/uncertain successor's work.
+ if (prior?.phase === 'reserved' && !prior.taskId) return refuse('cleanup-publication-unverified');
+ if (prior?.taskId) {
+ const { getTaskById } = await import('./cosTaskStore.js');
+ const task = await getTaskById(prior.taskId).catch(() => null);
+ if (!task || task.status !== 'completed') return refuse('cleanup-successor-owned');
+ }
+ if (history.includes(observation)) return refuse('cleanup-observation-already-attempted');
+ // Three meaningful observations on the same original run/branch are enough
+ // to establish a persistent issue. Further scans retain the evidence gap.
+ if ((prior?.attempt || 0) >= 3) return refuse('cleanup-cognitive-budget-exhausted');
+ const attempt = (prior?.attempt || 0) + 1;
+ const entry = { observation, observations: [...history, observation], attempt, phase: 'reserved', at: new Date().toISOString() };
+ reservation = { admitted: true, ...entry };
+ return { ...metadata, repoCleanupRecoveries: { ...metadata.repoCleanupRecoveries, [branch]: entry } };
+ });
+ return saved ? reservation : null;
+}
+
+export async function recordRepoCleanupRecovery(agentId, branch, observation, patch) {
+ return updateCompletionReceipt(agentId, metadata => {
+ const prior = metadata.repoCleanupRecoveries?.[branch];
+ if (prior?.observation !== observation) return metadata;
+ // A definitive refusal before publication did not spend cognitive work.
+ // Release only this reserved observation, retaining every actual attempt.
+ const deferred = prior.phase === 'reserved' && !prior.taskId
+ && patch.phase === 'blocked-before-dispatch' && patch.taskId === null;
+ const entry = { ...prior, ...patch, observation, attempt: deferred ? Math.max(0, prior.attempt - 1) : prior.attempt,
+ ...(deferred ? { observations: (prior.observations || []).filter(value => value !== observation) } : {}) };
+ return { ...metadata, repoCleanupRecoveries: { ...metadata.repoCleanupRecoveries, [branch]: entry } };
+ });
+}
+
+/** Domain outcome is independent of whether the provider process exited cleanly. */
+export function recordCleanupOutcome(agentId, outcome) {
+ return updateCompletionReceipt(agentId, metadata => {
+ const key = JSON.stringify([outcome.branch || null, outcome.path || null]);
+ const prior = { ...metadata.cleanupOutcomes };
+ // A branch-only hold is provisional, not a separate checkout. Resolving
+ // its original path replaces that placeholder, never another known path.
+ if (outcome.branch && outcome.path) delete prior[JSON.stringify([outcome.branch, null])];
+ const cleanupOutcomes = { ...prior, [key]: { ...outcome, observedAt: new Date().toISOString() } };
+ const rows = Object.values(cleanupOutcomes);
+ const incomplete = rows.filter(row => row.status !== 'verified');
+ const aggregate = incomplete.find(row => row.status === 'blocked') || incomplete[0] || rows[0];
+ return { ...metadata, cleanupOutcomes, cleanupOutcome: { ...aggregate,
+ status: incomplete.length ? aggregate.status : 'verified', total: rows.length, unresolved: incomplete.length } };
+ });
}
/** Server-only recovery backlink; works after the parent leaves live retention. */
@@ -167,7 +227,10 @@ async function updateCompletionReceipt(agentId, update) {
agent = JSON.parse(content);
}
if (!agent || (agent.id || agent.agentId) !== agentId || agent.status !== 'completed') return false;
- const updated = { ...agent, metadata: update(agent.metadata || {}) };
+ const metadata = agent.metadata || {};
+ const nextMetadata = await update(metadata);
+ if (nextMetadata === metadata) return true;
+ const updated = { ...agent, metadata: nextMetadata };
// Never synthesize a bucket before archiveCompletedAgent moved the flat
// directory: its retry treats an existing bucket as the completed move.
if (date && (!state.agents[agentId] || await tryReadFile(join(getAgentDir(agentId, date), 'metadata.json')))) {
@@ -222,7 +285,7 @@ export async function completeAgent(agentId, result = {}) {
// A later audit must never turn an old branch name into checkout authority.
const agent = state.agents[agentId];
let completedCheckouts;
- if (agent.metadata?.claimPicksOwnBranch) {
+ if (agent.metadata?.claimPicksOwnBranch || agent.metadata?.isWorktree) {
completedCheckouts = [];
if (result.success === true) {
const { captureCompletedCheckouts } = await import('./completedCheckoutEvidence.js');
diff --git a/server/services/cosAgentLifecycle.test.js b/server/services/cosAgentLifecycle.test.js
index 458b6e5db5..cb2b567418 100644
--- a/server/services/cosAgentLifecycle.test.js
+++ b/server/services/cosAgentLifecycle.test.js
@@ -25,6 +25,9 @@ vi.mock('./cosState.js', () => ({
readAgentsStateForSafetyCheck: vi.fn(async () => ({ trusted: true, agents: mockCosState.state?.agents ?? {} })),
}));
+const recoveryTasks = vi.hoisted(() => new Map());
+vi.mock('./cosTaskStore.js', () => ({ getTaskById: vi.fn(async id => recoveryTasks.get(id) || null) }));
+
vi.mock('./domainUsage.js', () => ({
recordDomainUsage: vi.fn(async () => {})
}));
@@ -90,7 +93,7 @@ vi.mock('../lib/paths.js', async (importOriginal) => makePathsProxy(await import
dataRoot: () => lazyTempDataRoot('portos-cos-lifecycle-'),
}));
-import { getAgent, getAgentPrompt, createAgentOutputBatcher, completeAgent, recordRepoStateVerification, updateAgent, registerAgent, cleanupZombieAgents, filterLiveAgentIds, readAgentRecordOrUnreadable, deleteAgent, AGENT_RECORD_UNREADABLE, AGENT_OUTPUT_TAIL_LINES } from './cosAgentLifecycle.js';
+import { getAgent, getAgentPrompt, createAgentOutputBatcher, completeAgent, recordRepoStateVerification, reserveRepoCleanupRecovery, recordRepoCleanupRecovery, recordCleanupOutcome, updateAgent, registerAgent, cleanupZombieAgents, filterLiveAgentIds, readAgentRecordOrUnreadable, deleteAgent, AGENT_RECORD_UNREADABLE, AGENT_OUTPUT_TAIL_LINES } from './cosAgentLifecycle.js';
import { saveState, loadState, readAgentsStateForSafetyCheck } from './cosState.js';
import { recordDomainUsage } from './domainUsage.js';
import { cosEvents } from './cosEvents.js';
@@ -116,6 +119,71 @@ describe('cosAgentLifecycle', () => {
await rm(mockCosState.agentsDir, { recursive: true, force: true });
});
+ it('bounds original-parent recoveries across 70 scans, evidence cycles, active ownership and restart', async () => {
+ const id = 'agent-recovery-history';
+ mockCosState.state.agents[id] = { id, status: 'completed', completedAt: '2026-01-01T00:00:00Z', metadata: {} };
+ expect(await reserveRepoCleanupRecovery(id, 'claim/one', 'A')).toMatchObject({ admitted: true, attempt: 1 });
+ for (let i = 0; i < 70; i++) expect(await reserveRepoCleanupRecovery(id, 'claim/one', 'B')).toMatchObject({ admitted: false, reason: 'cleanup-publication-unverified' });
+ await recordRepoCleanupRecovery(id, 'claim/one', 'A', { phase: 'dispatched', taskId: 'successor-1' });
+ recoveryTasks.set('successor-1', { status: 'in_progress' });
+ expect(await reserveRepoCleanupRecovery(id, 'claim/one', 'B')).toMatchObject({ admitted: false, reason: 'cleanup-successor-owned' });
+ recoveryTasks.set('successor-1', { status: 'completed' });
+ expect(await reserveRepoCleanupRecovery(id, 'claim/one', 'B')).toMatchObject({ admitted: true, attempt: 2 });
+ await recordRepoCleanupRecovery(id, 'claim/one', 'B', { phase: 'dispatched', taskId: 'successor-2' });
+ recoveryTasks.set('successor-2', { status: 'completed' });
+ // Reconstruct persisted state; neither the old parent's empty recoveryOrigin
+ // nor a process restart resets this history or the total attempt budget.
+ mockCosState.state = JSON.parse(JSON.stringify(mockCosState.state));
+ for (let i = 0; i < 70; i++) expect(await reserveRepoCleanupRecovery(id, 'claim/one', 'A')).toMatchObject({ admitted: false, reason: 'cleanup-observation-already-attempted' });
+ expect(await reserveRepoCleanupRecovery(id, 'claim/one', 'C')).toMatchObject({ admitted: true, attempt: 3 });
+ await recordRepoCleanupRecovery(id, 'claim/one', 'C', { phase: 'dispatched', taskId: 'successor-3' });
+ recoveryTasks.set('successor-3', { status: 'completed' });
+ expect(await reserveRepoCleanupRecovery(id, 'claim/one', 'D')).toMatchObject({ admitted: false, reason: 'cleanup-cognitive-budget-exhausted' });
+ expect(mockCosState.state.agents[id].metadata.repoCleanupRecoveries['claim/one'].observations).toEqual(['A', 'B', 'C']);
+ });
+
+ it.each(['automatic-retirement-paused', 'review-obligation-changed'])('resumes known-unexecuted %s deferrals without resetting real attempts', async reason => {
+ const id = 'agent-deferred-review';
+ mockCosState.state.agents[id] = { id, status: 'completed', metadata: {} };
+ expect(await reserveRepoCleanupRecovery(id, 'fix/work', 'prior')).toMatchObject({ admitted: true, attempt: 1 });
+ await recordRepoCleanupRecovery(id, 'fix/work', 'prior', { phase: 'dispatched', taskId: 'completed-review' });
+ recoveryTasks.set('completed-review', { status: 'completed' });
+ for (let i = 0; i < 70; i++) {
+ expect(await reserveRepoCleanupRecovery(id, 'fix/work', 'current')).toMatchObject({ admitted: true, attempt: 2 });
+ await recordRepoCleanupRecovery(id, 'fix/work', 'current', { phase: 'blocked-before-dispatch', taskId: null, reason });
+ mockCosState.state = JSON.parse(JSON.stringify(mockCosState.state));
+ }
+ expect(mockCosState.state.agents[id].metadata.repoCleanupRecoveries['fix/work']).toMatchObject({ attempt: 1, observations: ['prior'] });
+ expect(await reserveRepoCleanupRecovery(id, 'fix/work', 'prior')).toMatchObject({ admitted: false, reason: 'cleanup-observation-already-attempted' });
+ expect(await reserveRepoCleanupRecovery(id, 'fix/work', 'current')).toMatchObject({ admitted: true, attempt: 2 });
+ await recordRepoCleanupRecovery(id, 'fix/work', 'current', { phase: 'dispatched', taskId: 'active-review' });
+ recoveryTasks.set('active-review', { status: 'in_progress' });
+ expect(await reserveRepoCleanupRecovery(id, 'fix/work', 'changed')).toMatchObject({ admitted: false, reason: 'cleanup-successor-owned' });
+ });
+
+ it('replaces provisional owner holds when the original checkout completes without hiding other paths', async () => {
+ const id = 'agent-owner-completion';
+ mockCosState.state.agents[id] = { id, status: 'completed', metadata: {} };
+ await recordCleanupOutcome(id, { branch: 'claim/one', status: 'blocked', reason: 'owner-active' });
+ await recordCleanupOutcome(id, { branch: 'claim/other', path: '/example/other', status: 'blocked', reason: 'archive-unavailable' });
+ await recordCleanupOutcome(id, { branch: 'claim/one', path: '/example/original', status: 'verified', reason: 'retirement-receipt-verified' });
+ expect(mockCosState.state.agents[id].metadata.cleanupOutcome).toMatchObject({ status: 'blocked', total: 2, unresolved: 1, branch: 'claim/other' });
+ await recordCleanupOutcome(id, { branch: 'claim/other', path: '/example/new-incarnation', status: 'verified', reason: 'retirement-receipt-verified' });
+ expect(mockCosState.state.agents[id].metadata.cleanupOutcome).toMatchObject({ status: 'blocked', total: 3, unresolved: 1 });
+ await recordCleanupOutcome(id, { branch: 'claim/other', path: '/example/other', status: 'verified', reason: 'retirement-receipt-verified' });
+ expect(mockCosState.state.agents[id].metadata.cleanupOutcome).toMatchObject({ status: 'verified', unresolved: 0 });
+ });
+
+ it.each([true, false])('aggregates every branch outcome independently of update order (%s)', async reversed => {
+ const id = 'agent-swarm-outcome';
+ mockCosState.state.agents[id] = { id, status: 'completed', metadata: {} };
+ const rows = [{ branch: 'claim/blocked', path: '/example/blocked', status: 'blocked', reason: 'checkout-incarnation-changed' },
+ { branch: 'claim/verified', path: '/example/verified', status: 'verified', reason: 'retirement-receipt-verified' }];
+ for (const row of reversed ? rows.reverse() : rows) await recordCleanupOutcome(id, row);
+ expect(mockCosState.state.agents[id].metadata.cleanupOutcome).toMatchObject({ status: 'blocked', unresolved: 1, total: 2 });
+ expect(Object.values(mockCosState.state.agents[id].metadata.cleanupOutcomes)).toHaveLength(2);
+ });
+
it('archives interrupted audit findings before removing their workspace and reloads them after live retention', async () => {
const { settleAuditFindings } = await import('./auditFindings.js');
const workspace = join(mockCosState.agentsDir, 'audit-workspace');
diff --git a/server/services/cosMergeHandoff.completedOwner.test.js b/server/services/cosMergeHandoff.completedOwner.test.js
new file mode 100644
index 0000000000..dccac9a385
--- /dev/null
+++ b/server/services/cosMergeHandoff.completedOwner.test.js
@@ -0,0 +1,104 @@
+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdtemp, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+const f = vi.hoisted(() => ({ agents: [], tasks: {}, queue: [], live: [], pr: {}, head: '', dirty: '', roster: {}, pending: [], hold: null, duringForge: null }));
+vi.mock('./branchCompletionPolicy.js', () => ({
+ readBranchCompletionPolicies: async () => f.agents,
+ readBranchCompletionHold: async () => f.hold,
+}));
+vi.mock('./cosTaskStore.js', () => ({ getTaskById: async id => f.tasks[id], getTaskView: async () => ({ user: { tasks: [] }, cos: { tasks: f.queue } }) }));
+vi.mock('./cosClaimOwnership.js', () => ({ readClaimOwnershipAgents: async () => f.live }));
+vi.mock('./cosMergeAdmission.js', () => ({ repositoryKey: origin => origin ? `${origin.host}/${origin.fullName}`.toLowerCase() : null }));
+vi.mock('../lib/gitRemote.js', () => ({ getOriginInfo: async () => ({ host: 'github.com', fullName: 'example/repo' }) }));
+vi.mock('../lib/execGit.js', () => ({ execGit: async (args, cwd) => ({ stdout: args.includes('--git-path') ? join(cwd, 'review-status')
+ : args[0] === 'symbolic-ref' ? 'feature' : args[0] === 'status' ? f.dirty : f.head }) }));
+vi.mock('./github.js', () => ({ execGh: async () => { f.duringForge?.(); return JSON.stringify(f.pr); } }));
+vi.mock('./forgeExecOptions.js', () => ({ resolveForgeExecOptions: async cwd => ({ cwd, env: {} }) }));
+vi.mock('./apps.js', () => ({ getAppById: async () => ({ id: 'app', repoPath: '/repo' }), getActiveApps: async () => [{ id: 'app', repoPath: '/repo' }] }));
+vi.mock('./prWatcher.js', () => ({ readPendingMergePrs: () => f.pending }));
+vi.mock('./codeReview.js', () => ({ resolveReviewLoopOptions: async () => f.roster }));
+import { inspectCompletedOwnerReview, validateCleanupReviewTarget } from './cosMergeHandoff.js';
+const head = 'a'.repeat(40);
+const prUrl = 'https://github.com/example/repo/pull/7';
+let workspace;
+const inspect = overrides => inspectCompletedOwnerReview({ repoPath: '/repo', branch: 'feature', prUrl, headSha: head, worktreePath: workspace, ...overrides });
+beforeAll(async () => { workspace = await mkdtemp(join(tmpdir(), 'completed-review-')); });
+afterAll(async () => { await rm(workspace, { recursive: true, force: true }); });
+beforeEach(async () => {
+ f.agents = [{ id: 'owner', taskId: 'task', status: 'completed', startedAt: '2026-01-01T00:00:00Z', completedAt: '2026-01-01T01:00:00Z',
+ metadata: { sourceWorkspace: '/repo', workspacePath: workspace, worktreeBranch: 'feature', prCompletionPolicy: 'review-then-merge' } }];
+ f.tasks = { task: { id: 'task', status: 'completed', metadata: { app: 'app', prCompletion: 'review-then-merge' } } };
+ f.duringForge = null; f.queue = []; f.live = []; f.pending = []; f.head = head; f.dirty = ''; f.hold = 'pr-completion-review-required';
+ f.roster = { reviewers: ['codex'], optionalReviewers: [], usernames: [], reviewerMaxRounds: {}, reviewerModels: { codex: 'pinned' } };
+ f.pr = { number: 7, state: 'OPEN', isDraft: false, isCrossRepository: false, headRefName: 'feature', headRefOid: head };
+ await rm(join(workspace, 'review-status'), { force: true });
+});
+describe('completed owner required review inspection', () => {
+ it('establishes a missing nonoptional review without creating merge admission or changing backlog policy', async () => {
+ const result = await inspect();
+ expect(result).toMatchObject({ disposition: 'review-required', agentId: 'owner', originalTask: { id: 'task' },
+ roster: { reviewers: ['codex'], reviewerModels: { codex: 'pinned' } }, reviewTarget: { ownerId: 'owner', headSha: head, worktreePath: workspace } });
+ expect(f.pending).toEqual([]);
+ await writeFile(join(workspace, 'review-status'), `REVIEW_STATUS=clean\nREVIEW_HEAD=${head}\n`);
+ expect(await inspect()).toMatchObject({ disposition: 'held', reason: 'review-recorded-handoff-missing' });
+ });
+ it('uses an exact claim branch binding when its completed swarm parent registered the source checkout', async () => {
+ f.agents[0].metadata = { ...f.agents[0].metadata, workspacePath: '/repo', worktreeBranch: undefined, claimPicksOwnBranch: true, claimBranches: ['feature'] };
+ expect(await inspect()).toMatchObject({ disposition: 'review-required', agentId: 'owner' });
+ f.agents[0].metadata.claimBranches = ['another-branch'];
+ expect((await inspect()).reason).toBe('review-owner-ambiguous');
+ });
+ it('does not turn optional or disabled reviews into a new code review', async () => {
+ f.roster.optionalReviewers = ['codex'];
+ expect(await inspect()).toMatchObject({ disposition: 'held', reason: 'review-required-roster-unproven' });
+ f.tasks.task.metadata.prCompletion = 'merge-on-green'; f.hold = null;
+ expect(await inspect()).toMatchObject({ disposition: 'held', reason: 'review-not-required', reviewTarget: { headSha: head } });
+ });
+ it('preserves ambiguous owners, live holders, task holds and draft PRs', async () => {
+ f.agents.push({ ...f.agents[0], id: 'second' });
+ expect((await inspect()).reason).toBe('review-owner-ambiguous'); f.agents.pop();
+ f.live = [{ id: 'active', status: 'running', workspacePath: workspace }];
+ expect((await inspect()).reason).toBe('claim-owner-active'); f.live = [];
+ f.agents[0].metadata.prCompletionPolicy = 'leave-open';
+ expect((await inspect()).reason).toBe('review-policy-held'); f.agents[0].metadata.prCompletionPolicy = 'review-then-merge';
+ f.tasks.task.metadata.prCompletion = 'leave-open';
+ expect((await inspect()).reason).toBe('review-policy-held'); f.tasks.task.metadata.prCompletion = 'review-then-merge';
+ f.pr.isDraft = true;
+ expect((await inspect()).reason).toBe('review-pr-held');
+ });
+ it('rejects moved heads, dirty contents and unreadable review status', async () => {
+ f.pr.headRefOid = 'b'.repeat(40);
+ expect((await inspect()).reason).toBe('review-head-moved'); f.pr.headRefOid = head;
+ f.dirty = '?? retained.txt';
+ expect((await inspect()).reason).toBe('review-checkout-dirty'); f.dirty = '';
+ await writeFile(join(workspace, 'review-status'), 'not a review');
+ expect((await inspect()).reason).toBe('review-evidence-unreadable');
+ });
+ it('joins an exact persisted successor after an interrupted acknowledgement without adopting an unrelated task', async () => {
+ const { reviewTarget } = await inspect();
+ f.queue = [{ id: 'review', status: 'pending', metadata: { cleanupReviewTarget: reviewTarget } }];
+ expect(await inspect()).toMatchObject({ disposition: 'join-existing', taskId: 'review', agentId: 'owner' });
+ f.queue[0].metadata.cleanupReviewTarget = { ...reviewTarget, headSha: 'b'.repeat(40) };
+ expect(await inspect()).toEqual({ disposition: 'held', reason: 'review-successor-exists' });
+ });
+ it('rechecks queued successor policy and target after slow workspace preparation', async () => {
+ const { reviewTarget } = await inspect();
+ f.tasks.review = { id: 'review', status: 'pending', metadata: { cleanupReviewTarget: reviewTarget, prCompletion: 'review-then-merge' } };
+ const input = { target: reviewTarget, workspacePath: workspace, launchTaskId: 'review' };
+ expect(await validateCleanupReviewTarget(input)).toBeNull();
+ f.duringForge = () => { f.tasks.review.metadata.readOnly = true; };
+ expect(await validateCleanupReviewTarget(input)).toBe('review-launch-task-changed');
+ f.duringForge = null;
+ f.tasks.review.metadata.readOnly = false;
+ f.tasks.review.metadata.cleanupReviewTarget = { ...reviewTarget, headSha: 'b'.repeat(40) };
+ expect(await validateCleanupReviewTarget(input)).toBe('review-launch-task-changed');
+ });
+ it('joins an existing exact-head handoff and preserves current task policy at launch', async () => {
+ const { reviewTarget } = await inspect();
+ f.pending = [{ prUrl, prBranch: 'feature', handoff: { headSha: head, agentId: 'owner', taskId: 'task', startedAt: f.agents[0].startedAt, repository: 'github.com/example/repo', receiptId: 'receipt' } }];
+ expect(await inspect()).toMatchObject({ disposition: 'join-existing', appId: 'app' });
+ f.tasks.task.metadata.readOnly = true;
+ expect(await validateCleanupReviewTarget({ target: reviewTarget, workspacePath: workspace })).toBe('review-policy-held');
+ });
+});
diff --git a/server/services/cosMergeHandoff.js b/server/services/cosMergeHandoff.js
index a2493848ff..5c6d6ad613 100644
--- a/server/services/cosMergeHandoff.js
+++ b/server/services/cosMergeHandoff.js
@@ -90,13 +90,155 @@ async function followUpRoster(task, policy) {
const [{ resolveReviewLoopOptions }, { normalizeReviewers }] = await Promise.all([
import('./codeReview.js'), import('../lib/validation.js'),
]);
- const options = await resolveReviewLoopOptions(task.metadata, { normalize: normalizeReviewers });
+ const metadata = { ...task.metadata };
+ if (isTruthyMeta(metadata.reviewLoopFollowUp)) {
+ for (const [key, saved] of Object.entries({ reviewers: 'reviewLoopReviewers', usernames: 'reviewLoopReviewerUsernames',
+ optionalReviewers: 'reviewLoopOptionalReviewers', reviewerMaxRounds: 'reviewLoopReviewerMaxRounds',
+ reviewStopMode: 'reviewLoopStopMode', reviewerModels: 'reviewLoopReviewerModels', reviewerEfforts: 'reviewLoopReviewerEfforts' })) {
+ if (Object.hasOwn(metadata, saved)) metadata[key] = metadata[saved];
+ }
+ }
+ const options = await resolveReviewLoopOptions(metadata, { normalize: normalizeReviewers });
return {
reviewers: options.reviewers, usernames: options.usernames,
optionalReviewers: options.optionalReviewers, reviewerMaxRounds: options.reviewerMaxRounds,
+ reviewStopMode: options.reviewStopMode, reviewerModels: options.reviewerModels, reviewerEfforts: options.reviewerEfforts,
};
}
+/** Read-only target check shared by orphan review and its eventual workspace launch.
+ * This is permission to inspect one head, never merge admission or proof of review.
+ */
+export async function validateCleanupReviewTarget({ target, workspacePath, requireCheckout = false, launchTaskId = null }) {
+ if (!isPlainObject(target) || target.version !== 1 || !SHA_PATTERN.test(target.headSha || '')
+ || !target.branch || !target.repoPath || !target.repository) return 'review-target-invalid';
+ const pr = parsePullRequestUrl(target.prUrl);
+ const { repositoryKey } = await import('./cosMergeAdmission.js');
+ if (!pr || repositoryKey({ host: pr.host, fullName: `${pr.owner}/${pr.repo}` }) !== target.repository
+ || repositoryKey(await getOriginInfo(workspacePath).catch(() => null)) !== target.repository) return 'review-repository-changed';
+ const local = await execGit(['rev-parse', '--verify', `refs/heads/${target.branch}^{commit}`], workspacePath).catch(() => null);
+ if (local?.stdout?.trim() !== target.headSha) return 'review-head-moved';
+ const repoSpec = githubRepoSpec({ host: pr.host, fullName: `${pr.owner}/${pr.repo}` });
+ if (!repoSpec) return 'review-forge-unsupported';
+ const { getTaskById } = await import('./cosTaskStore.js');
+ const ownerTask = await getTaskById(target.ownerTaskId).catch(() => null);
+ if (!ownerTask || leavesPrForHuman(ownerTask) || isTruthyMeta(ownerTask.metadata?.readOnly)
+ || isTruthyMeta(ownerTask.metadata?.reviewLoopLeaveOpen)
+ || resolvePrCompletion(ownerTask.metadata) === PR_COMPLETIONS.LEAVE_OPEN
+ || resolvePrCompletion(ownerTask.metadata) !== target.prCompletion) return 'review-policy-held';
+ if (ownerTask.status !== 'completed' && !(ownerTask.id === launchTaskId && ['pending', 'in_progress'].includes(ownerTask.status))) return 'review-task-not-completed';
+ const { getAppById } = await import('./apps.js');
+ const app = ownerTask.metadata?.app ? await getAppById(ownerTask.metadata.app).catch(() => null) : null;
+ if (ownerTask.metadata?.app && (!app || !samePath(app.repoPath, target.repoPath))) return 'review-app-changed';
+ const options = await resolveForgeExecOptions(target.repoPath, { forgeAccount: app?.forgeAccount });
+ const raw = await execGh(['pr', 'view', String(pr.number), '--repo', repoSpec,
+ '--json', 'number,state,isDraft,isCrossRepository,headRefName,headRefOid'], undefined,
+ { cwd: options.cwd, env: options.env }).catch(() => null);
+ const view = safeJSONParse(raw, null);
+ if (!isPlainObject(view) || view.number !== pr.number) return 'review-pr-unreadable';
+ if (view.state !== 'OPEN' || view.isDraft !== false || view.isCrossRepository !== false) return 'review-pr-held';
+ if (view.headRefName !== target.branch || view.headRefOid !== target.headSha) return 'review-head-moved';
+ if (requireCheckout) {
+ if (!await checkoutAtHead(workspacePath, target.branch, target.headSha, target.repository, repositoryKey)) return 'review-checkout-changed';
+ const status = await execGit(['status', '--porcelain=v1', '--untracked-files=all'], workspacePath).catch(() => null);
+ if (!status || status.stdout.trim()) return 'review-checkout-dirty';
+ }
+ // Policy is checked after the potentially slow forge/checkout reads as well:
+ // an operator hold arriving while those reads run must win before dispatch.
+ const currentOwnerTask = await getTaskById(target.ownerTaskId).catch(() => null);
+ if (!currentOwnerTask || currentOwnerTask.status !== ownerTask.status || currentOwnerTask.metadata?.app !== ownerTask.metadata?.app
+ || leavesPrForHuman(currentOwnerTask) || isTruthyMeta(currentOwnerTask.metadata?.readOnly)
+ || isTruthyMeta(currentOwnerTask.metadata?.reviewLoopLeaveOpen)
+ || resolvePrCompletion(currentOwnerTask.metadata) !== target.prCompletion) return 'review-policy-held';
+ if (launchTaskId) {
+ const launchTask = await getTaskById(launchTaskId).catch(() => null);
+ const saved = launchTask?.metadata?.cleanupReviewTarget;
+ if (!launchTask || !['pending', 'in_progress'].includes(launchTask.status) || leavesPrForHuman(launchTask)
+ || isTruthyMeta(launchTask.metadata?.readOnly) || isTruthyMeta(launchTask.metadata?.reviewLoopLeaveOpen)
+ || resolvePrCompletion(launchTask.metadata) === PR_COMPLETIONS.LEAVE_OPEN
+ || !isPlainObject(saved) || Object.keys(target).some(key => saved[key] !== target[key])) return 'review-launch-task-changed';
+ }
+ return null;
+}
+
+/** Resolve a genuinely missing required review without adopting a completed
+ * owner into merge admission. Ambiguous history and optional/no-review policies
+ * retain the branch; pending CI by itself never creates cognitive work.
+ */
+export async function inspectCompletedOwnerReview({ agentId = null, repoPath, branch, prUrl, headSha, worktreePath }) {
+ const held = reason => ({ disposition: 'held', reason });
+ const { readBranchCompletionPolicies, readBranchCompletionHold } = await import('./branchCompletionPolicy.js');
+ const agents = await readBranchCompletionPolicies({ repairIndex: false }).catch(() => null);
+ if (!agents) return held('review-ownership-unreadable');
+ const scopes = agent => {
+ const m = agent.metadata || {};
+ return [m.worktreeBranch, m.jiraBranch, m.claimBranch, m.branchCompletionPolicy?.branch,
+ ...(Array.isArray(m.claimBranches) ? m.claimBranches : []), ...(Array.isArray(m.claimReleasedBranches) ? m.claimReleasedBranches : [])];
+ };
+ const owners = agents.filter(agent => samePath(agent.metadata?.sourceWorkspace || agent.metadata?.workspacePath, repoPath) && scopes(agent).includes(branch));
+ if (owners.length !== 1 || (agentId && owners[0].id !== agentId)) return held('review-owner-ambiguous');
+ const agent = owners[0];
+ if (agent.status !== 'completed' || !agent.id || !agent.taskId || !Number.isFinite(Date.parse(agent.startedAt))
+ || !(Date.parse(agent.completedAt) >= Date.parse(agent.startedAt))) return held('review-owner-not-completed');
+ const { getTaskById, getTaskView } = await import('./cosTaskStore.js');
+ const task = await getTaskById(agent.taskId).catch(() => null);
+ if (!task || task.id !== agent.taskId || task.status !== 'completed') return held('review-task-not-completed');
+ const policy = resolvePrCompletion(task.metadata);
+ if (agent.metadata?.prCompletionPolicy === PR_COMPLETIONS.LEAVE_OPEN) return held('review-policy-held');
+ if (![PR_COMPLETIONS.REVIEW_THEN_MERGE, PR_COMPLETIONS.MERGE_ON_GREEN].includes(policy) || leavesPrForHuman(task)
+ || isTruthyMeta(task.metadata?.readOnly) || isTruthyMeta(task.metadata?.reviewLoopLeaveOpen)) return held('review-policy-held');
+ const policyHold = await readBranchCompletionHold({ repoPath, branch, prUrl, tip: headSha, agents });
+ if (policyHold !== (policy === PR_COMPLETIONS.REVIEW_THEN_MERGE ? 'pr-completion-review-required' : null)) return held('review-policy-unproven');
+ const { repositoryKey } = await import('./cosMergeAdmission.js');
+ const repository = repositoryKey(await getOriginInfo(repoPath).catch(() => null));
+ const app = await resolveHandoffApp(task, agent, repository, repositoryKey);
+ if (!app) return held('review-app-unresolved');
+ const recordedWorkspace = agent.metadata?.workspacePath || agent.workspacePath;
+ const claimCutsCheckout = isTruthyMeta(agent.metadata?.claimPicksOwnBranch) || Boolean(agent.metadata?.claimBranch);
+ // Claim/swarm parents register the source workspace, then bind their child
+ // branches. That source path is not a claim checkout ownership receipt.
+ if (!worktreePath || samePath(worktreePath, repoPath)) return held('review-checkout-not-private');
+ if (recordedWorkspace && !samePath(recordedWorkspace, worktreePath)
+ && !(claimCutsCheckout && samePath(recordedWorkspace, repoPath))) return held('review-checkout-owner-mismatch');
+ const recordedPr = agent.metadata?.branchCompletionPolicy?.prUrl || agent.metadata?.reviewLoopMergeTarget?.url;
+ if (recordedPr && prIdentity(recordedPr) !== prIdentity(prUrl)) return held('review-owner-pr-mismatch');
+ const target = { version: 1, repository, repoPath, branch, prUrl, headSha, worktreePath,
+ ownerId: agent.id, ownerStartedAt: agent.startedAt, ownerTaskId: task.id, prCompletion: policy };
+ const invalid = await validateCleanupReviewTarget({ target, workspacePath: worktreePath, requireCheckout: true });
+ if (invalid) return held(invalid);
+ const { readClaimOwnershipAgents } = await import('./cosClaimOwnership.js');
+ const { claimCheckoutOwnerReason } = await import('../lib/claimContinuation.js');
+ const live = await readClaimOwnershipAgents().catch(() => null);
+ const ownerReason = claimCheckoutOwnerReason({ branchName: branch, holderPath: worktreePath, sourceWorkspace: repoPath, agents: live });
+ if (ownerReason) return held(ownerReason);
+ const queue = await getTaskView({ kind: 'queue' }).catch(() => null);
+ if (!queue || !Array.isArray(queue.user?.tasks) || !Array.isArray(queue.cos?.tasks)) return held('review-successors-unreadable');
+ const successor = [...queue.user.tasks, ...queue.cos.tasks].find(row => row.id !== task.id && row.status !== 'completed'
+ && (prIdentity(row.metadata?.reviewLoopPRUrl) === prIdentity(prUrl)
+ || prIdentity(row.metadata?.cleanupReviewTarget?.prUrl) === prIdentity(prUrl)));
+ if (successor) {
+ const bound = successor.metadata?.cleanupReviewTarget;
+ if (isPlainObject(bound) && Object.keys(target).every(key => bound[key] === target[key])
+ && ['pending', 'in_progress'].includes(successor.status)) {
+ return { disposition: 'join-existing', reason: 'review-successor-exists', taskId: successor.id, agentId: agent.id, reviewTarget: target };
+ }
+ return held('review-successor-exists');
+ }
+ const { readPendingMergePrs } = await import('./prWatcher.js');
+ const handoff = readPendingMergePrs(app).find(entry => prIdentity(entry.prUrl) === prIdentity(prUrl) && entry.prBranch === branch
+ && entry.handoff?.headSha === headSha && entry.handoff?.agentId === agent.id && entry.handoff?.taskId === task.id
+ && entry.handoff?.startedAt === agent.startedAt && entry.handoff?.repository === repository && entry.handoff?.receiptId);
+ if (handoff) return { disposition: 'join-existing', reason: 'review-handoff-exists', appId: app.id };
+ if (policy === PR_COMPLETIONS.MERGE_ON_GREEN) return { ...held('review-not-required'), agentId: agent.id, originalTask: task,
+ roster: await followUpRoster(task, policy), reviewTarget: target };
+ const roster = await followUpRoster(task, PR_COMPLETIONS.REVIEW_THEN_MERGE);
+ if (!roster.reviewers?.some(reviewer => !roster.optionalReviewers?.includes(reviewer))) return held('review-required-roster-unproven');
+ const review = await readReviewEvidence(worktreePath);
+ if (review.status === 'unreadable') return held('review-evidence-unreadable');
+ if (reviewEvidenceAccepted(review, headSha, PR_COMPLETIONS.REVIEW_THEN_MERGE, roster)) return { ...held('review-recorded-handoff-missing'), agentId: agent.id, originalTask: task, roster, reviewTarget: target };
+ return { disposition: 'review-required', reason: 'required-review-missing', agentId: agent.id, originalTask: task, roster, reviewTarget: target };
+}
+
/**
* @param {{ agentId: string, prUrl: string, headSha: string, worktreePath?: string }} input
* @returns {Promise<{ queued: true, receipt: object }|{ queued: false, reason: string, retryable: boolean }>}
diff --git a/server/services/cosTaskPreStepBlocks.compose.test.js b/server/services/cosTaskPreStepBlocks.compose.test.js
index 08dbea9e99..54c25a6db1 100644
--- a/server/services/cosTaskPreStepBlocks.compose.test.js
+++ b/server/services/cosTaskPreStepBlocks.compose.test.js
@@ -74,12 +74,16 @@ vi.mock('./taskLearning.js', async (importActual) => ({
// The reconcile scan is the git/gh-touching half; the classification helpers it
// feeds stay REAL so the block the prompt receives is the real rendering.
+vi.mock('./repoCleanupRecovery.js', () => ({ inspectOrQueueCompletedReview: vi.fn(async () => ({ disposition: 'held', reason: 'review-recorded-handoff-missing' })) }));
+vi.mock('./repoCleanupObservation.js', () => ({ inspectOpenDeliveryRepair: vi.fn(async () => ({ reason: 'delivery-ci-or-review-pending' })) }));
const prepareRetirement = vi.fn();
-vi.mock('./heldCheckoutRecovery.js', () => ({ prepareInventoriedCheckoutRetirement: (...args) => prepareRetirement(...args) }));
+const retireCheckout = vi.fn();
+const reserveReview = vi.fn(async () => ({ admitted: true }));
+vi.mock('./heldCheckoutRecovery.js', () => ({ retireInventoriedCheckout: (...args) => retireCheckout(...args), prepareInventoriedCheckoutRetirement: (...args) => prepareRetirement(...args) }));
const mergedPrRead = vi.fn();
vi.mock('./branchReconcileRetirement.js', async (original) => {
const real = await original();
- return { ...real, prepareReconcileRetirements: (app, result) => real.prepareReconcileRetirements(app, result, { readPr: mergedPrRead }) };
+ return { ...real, reserveRetirementReview: (...args) => reserveReview(...args), prepareReconcileRetirements: (app, result) => real.prepareReconcileRetirements(app, result, { readPr: mergedPrRead }) };
});
const reconcileMock = vi.fn();
vi.mock('./branchReconcile.js', async (importActual) => ({
@@ -105,6 +109,8 @@ vi.mock('./cosState.js', () => ({
readAgentsStateForSafetyCheck: vi.fn(async () => ({ trusted: true, agents: {} })),
}));
+import { inspectOpenDeliveryRepair } from './repoCleanupObservation.js';
+import { inspectOrQueueCompletedReview } from './repoCleanupRecovery.js';
import { generateManagedAppImprovementTaskForType } from './cosTaskGenerator.js';
import { getTaskInterval, getBranchReconcileOutcome, recordBranchReconcileOutcome } from './taskSchedule.js';
import { applyPerpetualDrainCap } from './cosTaskPreStepBlocks.js';
@@ -129,6 +135,10 @@ const generate = () =>
describe('generateManagedAppImprovementTaskForType composes the extracted pre-step layer', () => {
beforeEach(() => {
vi.clearAllMocks();
+ inspectOpenDeliveryRepair.mockResolvedValue({ reason: 'delivery-ci-or-review-pending' });
+ inspectOrQueueCompletedReview.mockResolvedValue({ disposition: 'held', reason: 'review-recorded-handoff-missing' });
+ reserveReview.mockResolvedValue({ admitted: true });
+ retireCheckout.mockResolvedValue({ ok: true, archiveDir: '/private/archive', branchDeleted: true });
getBranchReconcileOutcome.mockResolvedValue(null);
recordBranchReconcileOutcome.mockImplementation(async (_appId, update) => ({ ...update, retirementObligations: retainRetirementObligations(null, update.remaining || [], '2026-10-20T00:00:00Z') }));
parkPerpetual.mockReset().mockResolvedValue();
@@ -146,7 +156,7 @@ describe('generateManagedAppImprovementTaskForType composes the extracted pre-st
branch: row.branch, path: row.worktreePath, head: row.tip, managed: true, locked: false, lockReason: null,
})) }));
mergedPrRead.mockImplementation(async (_app, name) => `https://github.com/example/repo/pull/${name.split('-').at(-1)}`);
- prepareRetirement.mockResolvedValue({ ok: true, review: { digest: 'd'.repeat(64), policy: { policies: [{ id: 'completed-owner' }] } } });
+ 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 generateManagedAppImprovementTaskForType('branch-reconcile', APP, STATE, { skipPreconditions: true, onDemand: true });
expect(task).not.toBeNull();
expect(task.metadata.reconcileRetirements).toHaveLength(3);
@@ -159,6 +169,60 @@ describe('generateManagedAppImprovementTaskForType composes the extracted pre-st
}));
});
+ 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();
+ expect(recordPerpetualDispatch).not.toHaveBeenCalled();
+ expect(recordBranchReconcileOutcome).toHaveBeenLastCalledWith(APP.id, expect.objectContaining({ remaining: expect.arrayContaining([
+ expect.objectContaining({ branch: 'fix/waiting', reason: 'delivery-ci-or-review-pending' }),
+ ]) }));
+ });
+
+ it.each([false, true])('does not grant merge-capable review work with autoMerge disabled (resolveConflicts=%s)', async resolveConflicts => {
+ getTaskInterval.mockResolvedValue({ type: 'on-demand', taskMetadata: { autoMerge: false, resolveConflicts } });
+ const branch = 'fix/no-auto-merge';
+ const path = '/example/checkouts/held';
+ reconcileMock.mockResolvedValue(scan({ inFlight: [], wip: [{ branch, worktreePath: path, completionPolicyReason: 'pr-completion-review-required', openPr: { url: 'https://github.com/example/repo/pull/9', isDraft: false } }],
+ worktreeInventory: [{ branch, path, head: 'a'.repeat(40), locked: false, managed: true }] }));
+ inspectOpenDeliveryRepair.mockResolvedValue({ headSha: 'a'.repeat(40), evidence: { head: 'a'.repeat(40), conflicts: true } });
+ expect(await generate()).toBeNull();
+ expect(inspectOrQueueCompletedReview).not.toHaveBeenCalled();
+ expect(recordPerpetualDispatch).not.toHaveBeenCalled();
+ expect(recordBranchReconcileOutcome).toHaveBeenLastCalledWith(APP.id, expect.objectContaining({ remaining: expect.arrayContaining([
+ expect.objectContaining({ branch, reason: 'auto-merge-disabled' }),
+ ]) }));
+ });
+
+ it('routes a genuine missing-review obligation through the pinned review loop without a generic reconcile agent', async () => {
+ const branch = 'fix/needs-review';
+ const path = '/example/checkouts/review';
+ const head = 'a'.repeat(40);
+ reconcileMock.mockResolvedValue(scan({ inFlight: [{ branch, worktreePath: path, state: 'IN_REVIEW', openPr: { url: 'https://github.com/example/repo/pull/9', isDraft: false } }],
+ worktreeInventory: [{ branch, path, head, locked: false, managed: true }] }));
+ inspectOpenDeliveryRepair.mockResolvedValue({ headSha: head, reason: 'delivery-ci-or-review-pending' });
+ inspectOrQueueCompletedReview.mockResolvedValue({ disposition: 'queued-review', reason: 'required-code-review-queued', taskId: 'exact-review' });
+ expect(await generate()).toBeNull();
+ expect(inspectOrQueueCompletedReview).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ repoPath: APP.repoPath, branch, worktreePath: path, headSha: head }));
+ expect(recordPerpetualDispatch).not.toHaveBeenCalled();
+ expect(recordBranchReconcileOutcome).toHaveBeenLastCalledWith(APP.id, expect.objectContaining({ remaining: expect.arrayContaining([
+ expect.objectContaining({ branch, reason: 'required-code-review-queued' }),
+ ]) }));
+ });
+
+ it('a normal user reconcile drains machine-proven retirement without generating an agent', async () => {
+ const release = { branch: 'claim/issue-1', path: '/example/checkouts/1', head: 'a'.repeat(40), managed: true, locked: false };
+ reconcileMock.mockResolvedValue(scan({ inFlight: [], wip: [{ branch: release.branch, worktreePath: release.path, tip: release.head,
+ completionPolicyReason: 'pr-completion-review-required' }], worktreeInventory: [release] }));
+ mergedPrRead.mockResolvedValue('https://github.com/example/repo/pull/1');
+ prepareRetirement.mockResolvedValue({ ok: true, review: { digest: 'd'.repeat(64), policy: { policies: [{ id: 'completed-owner' }] },
+ forge: { prHead: release.head }, comparison: { disposition: 'integrated', localPatch: '', difference: '' } } });
+ expect(await generateManagedAppImprovementTaskForType('branch-reconcile', APP, STATE, { skipPreconditions: true, onDemand: true })).toBeNull();
+ expect(retireCheckout).toHaveBeenCalledOnce();
+ expect(retireCheckout.mock.calls[0][0].review.acceptSuperseded).toBe(false);
+ expect(reserveReview).not.toHaveBeenCalled();
+ expect(recordPerpetualDispatch).not.toHaveBeenCalled();
+ });
+
it('keeps an unresolved retirement visible after the checkout disappears on a later refill', async () => {
const release = { branch: 'claim/issue-42', path: '/example/missing', head: 'a'.repeat(40), createdAt: '2026-10-20T00:00:00Z', reason: 'retirement-receipt-unverified' };
getBranchReconcileOutcome.mockResolvedValue({ retirementObligations: [release], remaining: [] });
@@ -218,7 +282,7 @@ describe('generateManagedAppImprovementTaskForType composes the extracted pre-st
expect(recordPerpetualDispatch).not.toHaveBeenCalled();
});
it('reaches later branches across a cap and manual retry, then parks the exhausted sweep', async () => {
- const branches = ['__proto__', 'b', 'c', 'd'].map(name => ({ branch: name === '__proto__' ? name : `fix/${name}`, state: 'IN_REVIEW', tip: 'head-1', openPr: { number: 1 } }));
+ const branches = ['__proto__', 'b', 'c', 'd'].map(name => ({ branch: name === '__proto__' ? name : `fix/${name}`, state: 'NEEDS_PR', tip: 'head-1', openPr: null }));
let persisted = { signature: null, dispatchCount: 0 };
getPerpetualDrainState.mockImplementation(async () => JSON.parse(JSON.stringify(persisted)));
recordPerpetualDispatch.mockImplementation(async (_type, _app, signature, { branchAttempts }) => {
@@ -256,18 +320,18 @@ describe('generateManagedAppImprovementTaskForType composes the extracted pre-st
it('retries a changed revision without retrying an unchanged blocked prefix', async () => {
getPerpetualDrainState.mockResolvedValue({
- signature: 'fix/a:IN_REVIEW:1:old-head', dispatchCount: 1,
- branchAttempts: { 'fix/a': 'fix/a:IN_REVIEW:1:old-head', 'fix/b': 'fix/b:IN_REVIEW:2:same-head', removed: 'stale' }
+ signature: 'fix/a:NEEDS_PR:none:old-head', dispatchCount: 1,
+ branchAttempts: { 'fix/a': 'fix/a:NEEDS_PR:none:old-head', 'fix/b': 'fix/b:NEEDS_PR:none:same-head', removed: 'stale' }
});
reconcileMock.mockResolvedValue(scan({ inFlight: [
- { branch: 'fix/a', state: 'IN_REVIEW', openPr: { number: 1 }, tip: 'new-head' },
- { branch: 'fix/b', state: 'IN_REVIEW', openPr: { number: 2 }, tip: 'same-head' }
+ { branch: 'fix/a', state: 'NEEDS_PR', openPr: null, tip: 'new-head' },
+ { branch: 'fix/b', state: 'NEEDS_PR', openPr: null, tip: 'same-head' }
] }));
const task = await generate();
expect(task.description).toContain('fix/a');
expect(task.description).not.toContain('fix/b');
expect(recordPerpetualDispatch).toHaveBeenLastCalledWith('branch-reconcile', APP.id, expect.stringContaining('new-head'), {
- branchAttempts: { 'fix/a': 'fix/a:IN_REVIEW:1:new-head', 'fix/b': 'fix/b:IN_REVIEW:2:same-head' }
+ branchAttempts: { 'fix/a': 'fix/a:NEEDS_PR:none:new-head', 'fix/b': 'fix/b:NEEDS_PR:none:same-head' }
});
});
diff --git a/server/services/cosTaskPreStepBlocks.js b/server/services/cosTaskPreStepBlocks.js
index 4e39a47fb2..0c9cd53823 100644
--- a/server/services/cosTaskPreStepBlocks.js
+++ b/server/services/cosTaskPreStepBlocks.js
@@ -541,13 +541,48 @@ export async function resolveBranchReconcileBlock(app, taskType, metadata, taskS
const { prepareReconcileRetirements } = await import('./branchReconcileRetirement.js');
retirementReviews = await prepareReconcileRetirements(app, result);
}
- const allActionable = filterActionable([...result.inFlight, ...retirementReviews.candidates], actions);
+ const retiredNames = new Set((retirementReviews.retired || []).map(row => row.branch));
+ if (retiredNames.size) {
+ result.wip = result.wip.filter(row => !retiredNames.has(row.branch));
+ result.worktreeInventory = result.worktreeInventory.filter(row => !retiredNames.has(row.branch));
+ result.cleaned.push(...retiredNames);
+ }
+ // 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.
+ const routineDeliveryHolds = [];
+ const cognitiveInFlight = [];
+ const { inspectOpenDeliveryRepair } = await import('./repoCleanupObservation.js');
+ const { inspectOrQueueCompletedReview } = await import('./repoCleanupRecovery.js');
+ const reviewHeldOpen = (result.wip || []).filter(branch => branch.openPr && !branch.openPr.isDraft
+ && branch.completionPolicyReason === 'pr-completion-review-required' && !branch.liveOwnerReason
+ && !branch.worktreeDirty && !branch.worktreeStatusUnavailable);
+ for (const branch of [...result.inFlight, ...reviewHeldOpen]) {
+ if (branch.state !== 'IN_REVIEW' && !reviewHeldOpen.includes(branch)) { cognitiveInFlight.push(branch); continue; }
+ // The existing review-loop can merge. A resolve-only schedule cannot grant
+ // that authority by entering this earlier deterministic dispatch path.
+ if (actions.autoMerge === false) {
+ routineDeliveryHolds.push({ branch: branch.branch, reason: 'auto-merge-disabled' });
+ continue;
+ }
+ const delivery = await inspectOpenDeliveryRepair(app.repoPath, branch.branch, branch.openPr?.url, { forgeAccount: app.forgeAccount ?? null })
+ .catch(() => ({ reason: 'delivery-evidence-unavailable' }));
+ if (delivery.evidence?.conflicts && actions.resolveConflicts === false) {
+ routineDeliveryHolds.push({ branch: branch.branch, reason: 'conflict-resolution-disabled' });
+ continue;
+ }
+ const tree = result.worktreeInventory?.find(row => row.branch === branch.branch && row.path === branch.worktreePath);
+ const review = delivery.headSha && tree?.locked === false ? await inspectOrQueueCompletedReview({ repoPath: app.repoPath,
+ branch: branch.branch, prUrl: branch.openPr.url, headSha: delivery.headSha, worktreePath: tree.path, forgeAccount: app.forgeAccount ?? null, repairEvidence: delivery.evidence })
+ .catch(() => ({ reason: 'completed-review-inspection-unavailable' })) : null;
+ routineDeliveryHolds.push({ branch: branch.branch, reason: review?.reason || delivery.reason || 'completed-review-target-unverified' });
+ }
+ const allActionable = filterActionable([...cognitiveInFlight, ...retirementReviews.candidates], actions);
const actionableNames = new Set(allActionable.map(branch => branch.branch));
- const idlePark = describeIdleReconcilePark([...(result.skipped || []), ...retirementReviews.held, ...absentObligations], heldLive, {
- wip: result.wip?.filter(branch => !actionableNames.has(branch.branch) && !retirementReviews.held.some(held => held.branch === branch.branch)), detachedWorktrees: result.detachedWorktrees, superseded: result.superseded,
+ const idlePark = describeIdleReconcilePark([...(result.skipped || []), ...retirementReviews.held, ...absentObligations, ...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,
- gated: result.inFlight.filter(branch => !allActionable.includes(branch))
+ gated: cognitiveInFlight.filter(branch => !allActionable.includes(branch))
});
// This is a scan outcome, not the coordinator's success flag or a claim that
// the repository contains only its default branch. Keep known holds visible.
@@ -590,7 +625,7 @@ export async function resolveBranchReconcileBlock(app, taskType, metadata, taskS
const signature = actionableSignature([branch]);
if (drain.branchAttempts?.[branch.branch] === signature) branchAttempts[branch.branch] = signature;
}
- const actionable = limitBranchesForAgent(
+ let actionable = limitBranchesForAgent(
allActionable.filter(b => !Object.hasOwn(branchAttempts, b.branch)), metadata.branchesPerAgent
);
if (!actionable.length) {
@@ -598,9 +633,8 @@ export async function resolveBranchReconcileBlock(app, taskType, metadata, taskS
reason: 'no-progress', actionableCount: allActionable.length, signature: null, branchAttempts: null,
counts: { ...idlePark.counts, unchangedBranches: allActionable.length },
skipCauses: { ...idlePark.skipCauses, 'unchanged-after-attempt': allActionable.length },
- notLaterThan: idlePark.notLaterThan
+ notLaterThan: idlePark.notLaterThan,
});
- emitLog('info', `🔀 branch-reconcile parked for ${app.name}: all ${allActionable.length} branch(es) were attempted without further progress`, { appId: app.id });
return { skip: true };
}
for (const branch of actionable) branchAttempts[branch.branch] = actionableSignature([branch]);
@@ -614,6 +648,23 @@ export async function resolveBranchReconcileBlock(app, taskType, metadata, taskS
branchAttempts
});
if (!dispatch) return { skip: true };
+ const { reserveRetirementReview } = await import('./branchReconcileRetirement.js');
+ const admitted = [];
+ for (const branch of actionable) {
+ if (!branch.retirement || (await reserveRetirementReview(branch))?.admitted) admitted.push(branch);
+ else branchAttempts[branch.branch] = actionableSignature([branch]);
+ }
+ actionable = admitted;
+ if (!actionable.length) {
+ await taskSchedule.parkPerpetual(taskType, app.id, {
+ reason: 'no-progress', actionableCount: allActionable.length, signature: null, branchAttempts: null,
+ counts: { ...idlePark.counts, unchangedBranches: allActionable.length },
+ skipCauses: { ...idlePark.skipCauses, 'unchanged-after-attempt': allActionable.length },
+ notLaterThan: idlePark.notLaterThan
+ });
+ emitLog('info', `🔀 branch-reconcile parked for ${app.name}: all ${allActionable.length} branch(es) were attempted without further progress`, { appId: app.id });
+ return { skip: true };
+ }
metadata.perpetual = true;
metadata.reconcileRetirements = actionable.filter(branch => branch.retirement).map(branch => ({
...branch.retirement,
diff --git a/server/services/heldCheckoutRecovery.js b/server/services/heldCheckoutRecovery.js
index 49ac7258de..91f30a1401 100644
--- a/server/services/heldCheckoutRecovery.js
+++ b/server/services/heldCheckoutRecovery.js
@@ -476,6 +476,7 @@ async function retireHeldCheckout({ repoPath, release, review }, opts = {}) {
return withClaimOwnershipLock(async () => {
if (opts.inventoryCurrent && !await opts.inventoryCurrent()) return { ok: false, reason: 'release-not-in-inventory' };
+ await opts.beforeMutation?.();
const first = await matchRelease(repoPath, release);
if (!first.tree) return { ok: false, reason: first.reason };
const { tree } = first;
@@ -499,6 +500,7 @@ async function retireHeldCheckout({ repoPath, release, review }, opts = {}) {
// Archiving takes time; never unlock a lock that changed hands meanwhile.
const second = await matchRelease(repoPath, release);
if (!second.tree) return { ok: false, reason: second.reason, archiveDir: archive.dir };
+ await opts.beforeMutation?.();
if (release.locked) {
const unlocked = await execGit(['worktree', 'unlock', tree.path], repoPath).then(() => true, () => false);
if (!unlocked) return { ok: false, reason: 'worktree-unlock-failed', archiveDir: archive.dir };
@@ -518,7 +520,7 @@ async function retireHeldCheckout({ repoPath, release, review }, opts = {}) {
return current?.fingerprint === archive.fingerprint ? null : 'checkout-content-changed';
};
const removal = await forceRemoveWorktreeDir(repoPath, tree.path, {
- label: '🧹 held-checkout recovery: remove checkout', log: 'all', verifyRemoval,
+ label: '🧹 held-checkout recovery: remove checkout', log: 'all', verifyRemoval, beforeMutation: opts.beforeMutation,
});
if (!removal.removed) {
// Hand the lock back exactly as released. A lock someone took in the
@@ -545,7 +547,7 @@ async function retireHeldCheckout({ repoPath, release, review }, opts = {}) {
// A new checkout/commit cannot be deleted by a stale name-only operation.
const holders = await listWorktrees(repoPath).catch(() => null);
if (!holders || holders.some(holder => shortBranch(holder.branch) === branch)) return { ok: true, archiveDir: archive.dir, branchDeleted: false, branchRetainedReason: 'branch-has-new-holder' };
- const deleted = await deleteCompletedLocalBranch(repoPath, branch, release.head);
+ const deleted = await deleteCompletedLocalBranch(repoPath, branch, release.head, { beforeMutation: opts.beforeMutation });
if (!deleted) return { ok: true, archiveDir: archive.dir, branchDeleted: false, branchRetainedReason: 'branch-ref-changed-or-delete-failed' };
return { ok: true, archiveDir: archive.dir, branchDeleted: true };
});
diff --git a/server/services/repoCleanupObservation.js b/server/services/repoCleanupObservation.js
new file mode 100644
index 0000000000..4439385791
--- /dev/null
+++ b/server/services/repoCleanupObservation.js
@@ -0,0 +1,107 @@
+import { constants } from 'fs';
+import { lstat, open } from 'fs/promises';
+import { join } from 'path';
+import { parsePullRequestUrl } from '../lib/gitForge.js';
+import { execGit } from '../lib/execGit.js';
+
+/** Only ENOENT means absent. A broken symlink or non-directory still occupies
+ * the requested path and cannot establish successful cleanup.
+ */
+export async function readCheckoutPathPresence(path) {
+ return lstat(path).then(() => true).catch(error => error.code === 'ENOENT' ? false : null);
+}
+
+/** A failed Git lookup alone cannot prove absence: malformed loose/packed
+ * metadata can also return exit 1. Read the bounded files backend before
+ * reporting absent; unsupported stores and occupied/unreadable paths are unknown.
+ */
+export async function readLocalBranchPresence(repoPath, branch) {
+ const env = { ...process.env, GIT_OPTIONAL_LOCKS: '0', GIT_NO_LAZY_FETCH: '1' };
+ const run = args => execGit(args, repoPath, { ignoreExitCode: true, env });
+ const identity = stat => stat ? [stat.dev, stat.ino, stat.mode, stat.size, stat.mtimeNs, stat.ctimeNs].map(String) : null;
+ const info = path => lstat(path, { bigint: true }).catch(error => { if (error.code === 'ENOENT') return null; throw error; });
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
+ try {
+ const ref = `refs/heads/${branch}`;
+ if ((await run(['check-ref-format', ref])).exitCode !== 0) return null;
+ const lookup = await run(['show-ref', '--verify', '--quiet', ref]);
+ if (lookup.exitCode === 0) return true;
+ if (lookup.exitCode !== 1) return null;
+ const storage = await run(['config', '--get', 'extensions.refStorage']);
+ if (storage.exitCode !== 1 && (storage.exitCode !== 0 || storage.stdout.trim() !== 'files')) return null;
+ const common = await run(['rev-parse', '--path-format=absolute', '--git-common-dir']);
+ if (common.exitCode !== 0 || !common.stdout.trim()) return null;
+ const root = common.stdout.trim();
+ const inspectLoose = async () => {
+ const rows = [];
+ let cursor = root;
+ for (const part of ref.split('/')) {
+ cursor = join(cursor, part);
+ const stat = await info(cursor);
+ rows.push([cursor, identity(stat)]);
+ if (!stat) return rows;
+ if (cursor === join(root, ref) || !stat.isDirectory() || stat.isSymbolicLink()) return null;
+ }
+ return null;
+ };
+ const looseBefore = await inspectLoose();
+ if (!looseBefore) return null;
+ const packedPath = join(root, 'packed-refs');
+ const packedBefore = identity(await info(packedPath));
+ const packed = await open(packedPath, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK)
+ .catch(error => { if (error.code === 'ENOENT') return null; throw error; });
+ if (packed) {
+ try {
+ const stat = await packed.stat({ bigint: true });
+ if (!same(identity(stat), packedBefore) || !stat.isFile() || stat.size > 16n * 1024n * 1024n) return null;
+ const bytes = Buffer.alloc(Number(stat.size) + 1);
+ let length = 0;
+ while (length < bytes.length) {
+ const read = await packed.read(bytes, length, bytes.length - length, length);
+ if (!read.bytesRead) break;
+ length += read.bytesRead;
+ }
+ if (BigInt(length) !== stat.size) return null;
+ const text = bytes.subarray(0, length).toString('utf8');
+ for (const line of text.split('\n')) {
+ if (!line || line.startsWith('#')) continue;
+ if (/^\^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(line)) continue;
+ const row = /^([a-f0-9]{40}(?:[a-f0-9]{24})?) (refs\/[^\s]+)$/.exec(line);
+ if (!row || row[2] === ref) return null;
+ }
+ if (!same(identity(await packed.stat({ bigint: true })), packedBefore)) return null;
+ } finally { await packed.close(); }
+ }
+ if ((await run(['show-ref', '--verify', '--quiet', ref])).exitCode !== 1) return null;
+ if (!same(identity(await info(packedPath)), packedBefore) || !same(await inspectLoose(), looseBefore)) return null;
+ return false;
+ } catch { return null; }
+}
+
+
+/** A known open PR is not, by itself, a request for cognitive work. */
+export async function inspectOpenDeliveryRepair(repoPath, branch, prUrl, { forgeAccount = null } = {}) {
+ const target = parsePullRequestUrl(prUrl);
+ const { getOriginInfo } = await import('../lib/gitRemote.js');
+ const origin = await getOriginInfo(repoPath);
+ if (!target || target.host !== origin?.host || `${target.owner}/${target.repo}` !== origin?.fullName) return { reason: 'delivery-repository-unverified' };
+ const { execGh } = await import('./github.js');
+ const { resolveForgeExecOptions } = await import('./forgeExecOptions.js');
+ const { githubRepoSpec } = await import('../lib/workTracker.js');
+ const spec = githubRepoSpec(origin);
+ if (!spec) return { reason: 'delivery-forge-unsupported' };
+ const options = await resolveForgeExecOptions(repoPath, { forgeAccount });
+ const view = JSON.parse(await execGh(['pr', 'view', String(target.number), '--repo', spec,
+ '--json', 'number,state,isDraft,isCrossRepository,headRefName,headRefOid,mergeable,reviewDecision,statusCheckRollup'], undefined, options));
+ const local = await execGit(['rev-parse', '--verify', `refs/heads/${branch}`], repoPath,
+ { env: { ...process.env, GIT_OPTIONAL_LOCKS: '0', GIT_NO_LAZY_FETCH: '1' } });
+ if (view.number !== target.number || view.state !== 'OPEN' || view.isCrossRepository !== false
+ || view.headRefName !== branch || !/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(view.headRefOid || '')
+ || view.headRefOid !== local.stdout.trim()) return { reason: 'delivery-head-unverified' };
+ if (view.isDraft !== false) return { reason: 'delivery-draft-held' };
+ const failed = (view.statusCheckRollup || []).filter(check => ['FAILURE', 'ERROR', 'TIMED_OUT', 'ACTION_REQUIRED'].includes(check.conclusion || check.state));
+ const actionable = view.mergeable === 'CONFLICTING' || view.reviewDecision === 'CHANGES_REQUESTED' || failed.length > 0;
+ return actionable ? { actionable: true, headSha: view.headRefOid, evidence: { head: view.headRefOid, conflicts: view.mergeable === 'CONFLICTING',
+ changesRequested: view.reviewDecision === 'CHANGES_REQUESTED', checks: failed.map(check => ({ name: check.name || check.context, conclusion: check.conclusion || check.state })).sort((a,b) => String(a.name).localeCompare(String(b.name))) } }
+ : { headSha: view.headRefOid, reason: 'delivery-ci-or-review-pending' };
+}
diff --git a/server/services/repoCleanupObservation.test.js b/server/services/repoCleanupObservation.test.js
new file mode 100644
index 0000000000..39fee616ee
--- /dev/null
+++ b/server/services/repoCleanupObservation.test.js
@@ -0,0 +1,58 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { mkdir, mkdtemp, rm, writeFile, symlink } from 'node:fs/promises';
+import { join } from 'node:path';
+import { tmpdir } from 'node:os';
+import { materializeGitRepo } from '../lib/gitTestRepo.js';
+import { readLocalBranchPresence, readCheckoutPathPresence } from './repoCleanupObservation.js';
+
+const races = vi.hoisted(() => ({ afterLookup: null }));
+vi.mock('../lib/execGit.js', async importOriginal => {
+ const actual = await importOriginal();
+ return { ...actual, execGit: async (...args) => {
+ const result = await actual.execGit(...args);
+ if (args[0][0] === 'show-ref' && races.afterLookup) await races.afterLookup();
+ return result;
+ } };
+});
+
+describe('exact local branch absence accounting', () => {
+ let root;
+ beforeEach(async () => {
+ races.afterLookup = null;
+ root = await mkdtemp(join(tmpdir(), 'portos-ref-observation-'));
+ await materializeGitRepo(root, { identity: { name: 'Test', email: '[email protected]' } });
+ });
+ afterEach(async () => { await rm(root, { recursive: true, force: true, maxRetries: 3 }); });
+ it('recognizes a broken leaf symlink as occupied rather than removed', async () => {
+ const link = join(root, 'vanished-checkout');
+ await symlink(join(root, 'missing-target'), link, process.platform === 'win32' ? 'junction' : 'dir');
+ expect(await readCheckoutPathPresence(link)).toBe(true);
+ expect(await readCheckoutPathPresence(join(root, 'absent'))).toBe(false);
+ });
+
+ it('distinguishes occupied, absent and malformed loose references without repairing them', async () => {
+ expect(await readLocalBranchPresence(root, 'main')).toBe(true);
+ expect(await readLocalBranchPresence(root, 'claim/absent')).toBe(false);
+ await mkdir(join(root, '.git', 'refs', 'heads', 'claim'), { recursive: true });
+ await writeFile(join(root, '.git', 'refs', 'heads', 'claim', 'absent'), 'invalid occupied ref\n');
+ expect(await readLocalBranchPresence(root, 'claim/absent')).toBe(null);
+ });
+ it.each(['loose', 'packed'])('withholds absence if %s metadata changes during the final observation', async kind => {
+ let count = 0;
+ races.afterLookup = async () => {
+ if (++count !== 2) return;
+ if (kind === 'loose') {
+ await mkdir(join(root, '.git', 'refs', 'heads', 'claim'), { recursive: true });
+ await writeFile(join(root, '.git', 'refs', 'heads', 'claim', 'absent'), 'malformed late ref\n');
+ } else await writeFile(join(root, '.git', 'packed-refs'), `${'a'.repeat(40)} refs/heads/claim/absent trailing-token\n`);
+ };
+ expect(await readLocalBranchPresence(root, 'claim/absent')).toBe(null);
+ expect(count).toBe(2);
+ });
+ it('refuses malformed packed metadata and unknown repository errors as absence proof', async () => {
+ await writeFile(join(root, '.git', 'packed-refs'), `${'a'.repeat(40)} refs/heads/claim/absent trailing-token\n`);
+ expect(await readLocalBranchPresence(root, 'claim/absent')).toBe(null);
+ expect(await readLocalBranchPresence(join(root, 'missing'), 'claim/absent')).toBe(null);
+ expect(await readLocalBranchPresence(root, '../bad')).toBe(null);
+ });
+});
diff --git a/server/services/repoCleanupRecovery.js b/server/services/repoCleanupRecovery.js
new file mode 100644
index 0000000000..8af5c3e955
--- /dev/null
+++ b/server/services/repoCleanupRecovery.js
@@ -0,0 +1,66 @@
+import { processAuditFingerprint } from '../lib/persistentMindProcessAudit.js';
+import { resolvePrCompletion } from '../lib/prDisposition.js';
+
+const purposeFor = (inspection, repair) => {
+ if (inspection?.disposition === 'review-required') return 'required-review';
+ if (inspection?.disposition !== 'held' || !['review-not-required', 'review-recorded-handoff-missing'].includes(inspection.reason)
+ || !inspection.reviewTarget || repair?.head !== inspection.reviewTarget.headSha) return null;
+ return repair.conflicts === true || repair.changesRequested === true || repair.checks?.length > 0 ? 'code-repair' : null;
+};
+const observationFor = (inspection, purpose, repair) => processAuditFingerprint({ kind: purpose,
+ target: inspection.reviewTarget, roster: inspection.roster, policy: resolvePrCompletion(inspection.originalTask?.metadata),
+ ...(purpose === 'code-repair' ? { repair } : {}),
+});
+
+/** Queue genuine required review or exact-head code repair, never a CI wait.
+ * Uses the existing review-loop owner and budget, without merge admission bypass.
+ */
+export async function inspectOrQueueCompletedReview(input, deps = {}) {
+ const inspect = deps.inspect || (await import('./cosMergeHandoff.js')).inspectCompletedOwnerReview;
+ const inspected = await inspect(input);
+ const purpose = purposeFor(inspected, input.repairEvidence);
+ if (!purpose) return inspected;
+ const target = inspected.reviewTarget;
+ if (!target || !inspected.agentId || !inspected.originalTask || !inspected.roster) return { disposition: 'held', reason: 'review-obligation-unverified' };
+ const permitted = deps.permitted || (await import('./branchReconcileRetirement.js')).assertAutomaticRetirementAllowed;
+ try { await permitted(); } catch (error) { return { disposition: 'held', reason: error.message }; }
+ const observation = observationFor(inspected, purpose, input.repairEvidence);
+ const lifecycle = deps.lifecycle || await import('./cosAgentLifecycle.js');
+ const reservation = await lifecycle.reserveRepoCleanupRecovery(inspected.agentId, target.branch, observation);
+ if (!reservation?.admitted) return { disposition: 'held', reason: reservation?.reason || 'review-reservation-unavailable' };
+ // Reservation may wait behind another state writer. Re-prove the same
+ // obligation and current authority after that await, before task publication.
+ const fresh = await inspect(input).catch(() => null);
+ let freshRepair = input.repairEvidence;
+ if (purpose === 'code-repair') {
+ const readDelivery = deps.readDelivery || (await import('./repoCleanupObservation.js')).inspectOpenDeliveryRepair;
+ const delivery = await readDelivery(target.repoPath, target.branch, target.prUrl, { forgeAccount: input.forgeAccount ?? null }).catch(() => null);
+ freshRepair = delivery?.actionable ? delivery.evidence : null;
+ }
+ const unchanged = fresh?.agentId === inspected.agentId && purposeFor(fresh, freshRepair) === purpose
+ && observationFor(fresh, purpose, freshRepair) === observation;
+ let refusal = unchanged ? null : 'review-obligation-changed';
+ if (!refusal) { try { await permitted(); } catch (error) { refusal = error.message; } }
+ if (refusal) {
+ await lifecycle.recordRepoCleanupRecovery(inspected.agentId, target.branch, observation,
+ { phase: 'blocked-before-dispatch', taskId: null, reason: refusal });
+ return { disposition: 'held', reason: refusal };
+ }
+ const spawn = deps.spawn || (await import('./agentWorktreeCleanup.js')).spawnReviewLoopFollowUp;
+ let task;
+ try {
+ task = await spawn({ originalAgentId: inspected.agentId, originalTask: inspected.originalTask,
+ sourceWorkspace: target.repoPath, prUrl: target.prUrl, prBranch: target.branch,
+ prCompletion: resolvePrCompletion(inspected.originalTask.metadata), ...inspected.roster, reviewTarget: target });
+ } catch {
+ // Publication may already have committed. Retain uncertainty until an exact
+ // successor can be identified, never reset its budget or blindly redispatch.
+ return { disposition: 'held', reason: 'cleanup-publication-unverified' };
+ }
+ const reason = task?.id ? (purpose === 'code-repair' ? 'code-repair-queued' : 'required-code-review-queued') : 'required-code-review-held';
+ await lifecycle.recordRepoCleanupRecovery(inspected.agentId, target.branch, observation,
+ { phase: task?.id ? 'dispatched' : 'blocked', taskId: task?.id || null });
+ await lifecycle.recordCleanupOutcome(inspected.agentId, { branch: target.branch, path: target.worktreePath,
+ status: task?.id ? 'pending' : 'blocked', reason, taskId: task?.id || null });
+ return { disposition: task?.id ? 'queued-review' : 'held', reason, taskId: task?.id || null };
+}
diff --git a/server/services/repoCleanupRecovery.test.js b/server/services/repoCleanupRecovery.test.js
new file mode 100644
index 0000000000..e16ab1de9c
--- /dev/null
+++ b/server/services/repoCleanupRecovery.test.js
@@ -0,0 +1,92 @@
+import { describe, expect, it, vi } from 'vitest';
+import { inspectOrQueueCompletedReview } from './repoCleanupRecovery.js';
+
+const target = { version: 1, repository: 'example/repo', repoPath: '/repo', branch: 'fix/work', prUrl: 'https://github.com/example/repo/pull/7', headSha: 'a'.repeat(40), worktreePath: '/repo-work', ownerId: 'owner', ownerStartedAt: '2026-01-01T00:00:00Z', ownerTaskId: 'original' };
+const required = () => ({ disposition: 'review-required', reason: 'required-review-missing', agentId: 'owner', reviewTarget: target,
+ originalTask: { id: 'original', metadata: { prCompletion: 'review-then-merge' } }, roster: { reviewers: ['codex'], optionalReviewers: [], usernames: [] } });
+const input = { repoPath: '/repo', branch: target.branch, prUrl: target.prUrl, headSha: target.headSha, worktreePath: target.worktreePath };
+function harness(inspection = required()) {
+ let reservation = null;
+ const lifecycle = {
+ reserveRepoCleanupRecovery: vi.fn(async (_owner, _branch, observation) => {
+ if (reservation) return { admitted: false, reason: 'cleanup-successor-owned' };
+ reservation = { observation, phase: 'reserved' }; return { admitted: true };
+ }),
+ recordRepoCleanupRecovery: vi.fn(async (_owner, _branch, observation, patch) => {
+ if (reservation?.observation === observation) Object.assign(reservation, patch);
+ return true;
+ }),
+ recordCleanupOutcome: vi.fn(async () => true),
+ };
+ return { inspect: vi.fn(async () => inspection), permitted: vi.fn(async () => {}), lifecycle, spawn: vi.fn(async () => ({ id: 'review-1' })), reservation: () => reservation };
+}
+
+describe('completed cleanup review dispatch', () => {
+ it('creates one exact configured review owner across 70 scans and joins existing successors without reserving', async () => {
+ const deps = harness();
+ expect(await inspectOrQueueCompletedReview(input, deps)).toMatchObject({ disposition: 'queued-review', taskId: 'review-1' });
+ for (let i = 0; i < 70; i++) expect(await inspectOrQueueCompletedReview(input, deps)).toMatchObject({ disposition: 'held' });
+ expect(deps.spawn).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ originalAgentId: 'owner', reviewTarget: target, reviewers: ['codex'] }));
+ expect(deps.reservation()).toMatchObject({ phase: 'dispatched', taskId: 'review-1' });
+ const joined = harness({ disposition: 'join-existing', reason: 'review-successor-exists', taskId: 'review-1' });
+ expect(await inspectOrQueueCompletedReview(input, joined)).toMatchObject({ disposition: 'join-existing', taskId: 'review-1' });
+ expect(joined.lifecycle.reserveRepoCleanupRecovery).not.toHaveBeenCalled();
+ expect(joined.spawn).not.toHaveBeenCalled();
+ });
+
+ it.each(['owner', 'head', 'policy', 'roster', 'paused'])('retains the reservation without dispatch when %s changes during durable admission', async change => {
+ const deps = harness();
+ const fresh = structuredClone(required());
+ if (change === 'owner') fresh.agentId = 'replacement';
+ if (change === 'head') fresh.reviewTarget.headSha = 'b'.repeat(40);
+ if (change === 'policy') fresh.originalTask.metadata.prCompletion = 'merge-on-green';
+ if (change === 'roster') fresh.roster.reviewers = ['claude'];
+ deps.inspect.mockResolvedValueOnce(required()).mockResolvedValue(fresh);
+ if (change === 'paused') deps.permitted.mockResolvedValueOnce().mockRejectedValue(new Error('automatic-retirement-paused'));
+ expect(await inspectOrQueueCompletedReview(input, deps)).toMatchObject({ disposition: 'held', reason: change === 'paused' ? 'automatic-retirement-paused' : 'review-obligation-changed' });
+ expect(deps.reservation()).toMatchObject({ phase: 'blocked-before-dispatch', taskId: null });
+ expect(deps.spawn).not.toHaveBeenCalled();
+ });
+
+ it('keeps uncertain publication owned instead of retrying a potentially committed task', async () => {
+ const deps = harness();
+ deps.spawn.mockRejectedValue(new Error('response lost after publication'));
+ expect(await inspectOrQueueCompletedReview(input, deps)).toMatchObject({ reason: 'cleanup-publication-unverified' });
+ for (let i = 0; i < 70; i++) await inspectOrQueueCompletedReview(input, deps);
+ expect(deps.spawn).toHaveBeenCalledOnce();
+ expect(deps.reservation()).toMatchObject({ phase: 'reserved' });
+ expect(deps.lifecycle.recordCleanupOutcome).not.toHaveBeenCalled();
+ });
+
+ it('does not reserve when authority is already paused or CI alone is pending', async () => {
+ const deps = harness();
+ deps.permitted.mockRejectedValue(new Error('automatic-retirement-paused'));
+ expect(await inspectOrQueueCompletedReview(input, deps)).toMatchObject({ reason: 'automatic-retirement-paused' });
+ expect(deps.lifecycle.reserveRepoCleanupRecovery).not.toHaveBeenCalled();
+ const waiting = harness({ ...required(), disposition: 'held', reason: 'review-recorded-handoff-missing' });
+ for (let i = 0; i < 70; i++) await inspectOrQueueCompletedReview(input, waiting);
+ expect(waiting.spawn).not.toHaveBeenCalled();
+ expect(waiting.lifecycle.reserveRepoCleanupRecovery).not.toHaveBeenCalled();
+ });
+
+ it('does not launch stale code repair when CI turns green while reservation is persisted', async () => {
+ const deps = harness({ ...required(), disposition: 'held', reason: 'review-recorded-handoff-missing' });
+ deps.readDelivery = vi.fn(async () => ({ headSha: target.headSha, reason: 'delivery-ci-or-review-pending' }));
+ expect(await inspectOrQueueCompletedReview({ ...input, repairEvidence: { head: target.headSha, checks: [{ name: 'CI', conclusion: 'FAILURE' }] } }, deps))
+ .toMatchObject({ disposition: 'held', reason: 'review-obligation-changed' });
+ expect(deps.spawn).not.toHaveBeenCalled();
+ expect(deps.reservation()).toMatchObject({ phase: 'blocked-before-dispatch' });
+ });
+
+ it('routes actual same-head CI failure into the configured review loop without changing merge policy', async () => {
+ const inspection = { ...required(), disposition: 'held', reason: 'review-not-required', originalTask: { id: 'original', metadata: { prCompletion: 'merge-on-green' } }, roster: { reviewers: [], optionalReviewers: [], usernames: [] } };
+ const deps = harness(inspection);
+ const repairEvidence = { head: target.headSha, checks: [{ name: 'CI', conclusion: 'FAILURE' }] };
+ deps.readDelivery = vi.fn(async () => ({ actionable: true, evidence: repairEvidence }));
+ expect(await inspectOrQueueCompletedReview({ ...input, repairEvidence }, deps)).toMatchObject({ reason: 'code-repair-queued' });
+ expect(deps.spawn).toHaveBeenCalledWith(expect.objectContaining({ prCompletion: 'merge-on-green', reviewers: [], reviewTarget: target }));
+ const changed = harness(inspection);
+ await inspectOrQueueCompletedReview({ ...input, repairEvidence: { ...repairEvidence, head: 'b'.repeat(40) } }, changed);
+ expect(changed.spawn).not.toHaveBeenCalled();
+ });
+});