Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: finalize merged jobs with deterministic checkout cleanup (#13543)

picodot8c1f0b425b13
diff --git a/docs/features/branch-reconciliation.md b/docs/features/branch-reconciliation.md
index de138dd943..a4b8128a1f 100644
--- a/docs/features/branch-reconciliation.md
+++ b/docs/features/branch-reconciliation.md
@@ -164,6 +164,23 @@ for that exact checkout generation or recover the original data from backup, the
retry reconciliation. Failure never fabricates a retirement receipt or authorizes
deletion of a checkout, branch or archive.
+## Completing a merged job
+
+Normal merged-work cleanup belongs to the completing job. After durable signal
+ingestion and exact checkout capture, the server stops that job's finished
+writer, releases its execution binding, and awaits deterministic retirement and
+receipt verification. An already merged exact head does not create a cognitive
+review or cleanup job. A genuine delivery follow-up wakes its original parent
+directly when it completes; duplicate observations coalesce, and a pre-release
+audit cannot substitute its stale owner-active result for the post-release
+check. Scheduled reconciliation is a crash/restart and legacy fallback.
+
+Cognitive investigation is reserved for actual unexplained failures. Its contract
+includes resolving the affected work within original authority and budgets,
+repairing demonstrated root code defects with regression coverage and normal PR
+delivery, and reusing active fixes. External permission and transient causes are
+recorded accurately rather than turned into invented code defects.
+
## Explicit initialized-checkout retirement
Automatic cleanup continues to retain initialized submodules. The separate
@@ -183,9 +200,13 @@ Git layouts fail closed. It does not deinitialize a module.
`git worktree remove --force`. If that fails, it removes the directory only
when `rev-parse --show-toplevel` resolves to the release path, then deletes
the local branch with the same exact-head lease as other completed branches.
- Any other disposition, including accepted supersession, returns
- `not-merged-on-recheck` and leaves the checkout. No transaction directory is
- created.
+ An exact merged PR head is integrated once freshly verified default history
+ contains the actual merge commit, even when later commits changed shared files.
+ This is deterministic delivery evidence and needs no manual supersession
+ acceptance or update of the primary checkout. It never covers a newer local
+ tip, replacement delivery or missing merge evidence. Other dispositions
+ return `not-merged-on-recheck` and leave the checkout. No transaction directory
+ is created.
Journals already stored under `data/cos/initialized-checkout-retirements/` keep
the historical quarantine restore path below. Setup migration 442 deletes that
diff --git a/scripts/lib/vitestStaleRunRoots.js b/scripts/lib/vitestStaleRunRoots.js
index 3cf9d2edfe..cee996b2ca 100644
--- a/scripts/lib/vitestStaleRunRoots.js
+++ b/scripts/lib/vitestStaleRunRoots.js
@@ -247,6 +247,14 @@ export function killTestProcessesUnder(root, { read = readTestProcesses, probe =
const current = read(pending.map(item => item.record.pid));
for (const item of pending) {
if (item.settlement !== 'terminated') item.settlement = testProcessSettlement(item.record, current, probePid);
+ // A transient inspection failure can withhold the first signal. Retry
+ // only after fresh incarnation, ancestry and root proof; an attempted
+ // signal (including a permission failure) is never blindly repeated.
+ if (item.settlement !== 'terminated' && item.signal === 'not-attempted'
+ && stillOwned(item.record, snapshot, parent, prefix, read)) {
+ try { kill(item.record.pid, 'SIGKILL'); item.signal = 'delivered'; }
+ catch { item.signal = 'failed'; }
+ }
}
if (pending.every(item => item.settlement === 'terminated') || now() >= deadline) break;
wait(Math.min(25, deadline - now()));
diff --git a/scripts/testOwnedProcessRecovery.test.js b/scripts/testOwnedProcessRecovery.test.js
index 55c97c71e1..7736a18bb2 100644
--- a/scripts/testOwnedProcessRecovery.test.js
+++ b/scripts/testOwnedProcessRecovery.test.js
@@ -101,6 +101,37 @@ describe('test process ownership boundaries', () => {
} finally { rmSync(host, { recursive: true, force: true }); }
});
+ it.each(['recovered', 'changed-root', 'reused', 'unreadable'])(
+ 'rechecks withheld cleanup after a transient inspection without signaling changed ownership: %s', mode => {
+ const host = mkdtempSync(join(tmpdir(), 'recovery-transient-'));
+ const root = join(host, 'pvt-owned'); mkdirSync(root);
+ writeFileSync(join(root, '.owner.pid'), '999999 0\n');
+ const ancestors = [{ pid: process.pid, ppid: process.ppid }, { pid: process.ppid, ppid: 1 }];
+ const child = { pid: 900001, ppid: 1, start: 'original', args: ['node'],
+ env: { NODE_ENV: 'test', PORTOS_TEST_TEMP_ROOT: root } };
+ let reads = 0;
+ let time = 0;
+ let signaled = false;
+ const read = () => {
+ reads++;
+ if (reads === 1) return [...ancestors, child];
+ if (reads === 2) return [...ancestors, { ...child, env: {} }];
+ if (mode === 'unreadable') return null;
+ if (signaled) return ancestors;
+ return [...ancestors, { ...child,
+ start: mode === 'reused' ? 'replacement' : child.start,
+ env: mode === 'changed-root' ? { ...child.env, PORTOS_TEST_TEMP_ROOT: join(host, 'pvt-other') } : child.env }];
+ };
+ const kill = vi.fn(() => { signaled = true; });
+ try {
+ const result = killTestProcessesUnder(root, { read, probe: () => false, probePid: () => !signaled,
+ kill, now: () => time, wait: ms => { time += ms; }, settlementMs: 50 });
+ expect(result).toBe(mode === 'recovered' ? 1 : 0);
+ if (mode === 'recovered') expect(kill).toHaveBeenCalledExactlyOnceWith(child.pid, 'SIGKILL');
+ else expect(kill).not.toHaveBeenCalled();
+ } finally { rmSync(host, { recursive: true, force: true }); }
+ });
+
it.each(['live', 'gone'])('requires terminal proof before ignoring an incomplete %s process row', mode => {
const host = mkdtempSync(join(tmpdir(), 'recovery-unrelated-'));
const dead = join(host, 'pvt-dead');
diff --git a/server/lib/retirementCheckoutObservation.js b/server/lib/retirementCheckoutObservation.js
index d601f0e146..88107b1e45 100644
--- a/server/lib/retirementCheckoutObservation.js
+++ b/server/lib/retirementCheckoutObservation.js
@@ -4,10 +4,17 @@ import { join } from 'node:path';
import { createHash } from 'node:crypto';
import { execGit } from './execGit.js';
+/** Same identity from a server-captured pointer, after the checkout is gone. */
+export function retirementCheckoutIdentityFromPointer(pointer) {
+ const values = [pointer?.dev, pointer?.ino, pointer?.birthtimeNs];
+ return values.every(value => typeof value === 'string' && /^\d+$/.test(value))
+ ? createHash('sha256').update(JSON.stringify(values)).digest('hex') : null;
+}
+
export async function readRetirementCheckoutIdentity(path) {
const info = await lstat(join(path, '.git'), { bigint: true }).catch(() => null);
if (!info || (!info.isFile() && !info.isDirectory())) return null;
- return createHash('sha256').update(JSON.stringify([String(info.dev), String(info.ino), String(info.birthtimeNs)])).digest('hex');
+ return retirementCheckoutIdentityFromPointer({ dev: String(info.dev), ino: String(info.ino), birthtimeNs: String(info.birthtimeNs) });
}
/** Read-only admission; neither a stale inventory nor a pathname grants a new obligation. */
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.js
index aa3318869f..ac9b546c2e 100644
--- a/server/services/agentCliSpawning.js
+++ b/server/services/agentCliSpawning.js
@@ -873,7 +873,7 @@ export async function spawnDirectly({
unregisterSpawnedAgent(agentData?.pid || claudeProcess.pid);
activeAgents.delete(agentId);
- void import('./agentRepoStateVerification.js').then(module => module.resumeAgentCompletionRetirement(agentId))
+ await import('./agentRepoStateVerification.js').then(module => module.resumeAgentCompletionRetirement(agentId))
.catch(error => emitLog('warn', `Completion retirement deferred for ${agentId}: ${error.message}`, { agentId }));
}
maintenance.finishResource('agent', agentId);
diff --git a/server/services/agentErrorAnalysis.js b/server/services/agentErrorAnalysis.js
index acb0641973..c4393e3268 100644
--- a/server/services/agentErrorAnalysis.js
+++ b/server/services/agentErrorAnalysis.js
@@ -1381,7 +1381,7 @@ async function doCreateInvestigationTask(agentId, originalTask, errorAnalysis) {
`## Why this is held for you\n${LOOP_REASON_PROSE[loopReason]}`
].join('\n\n')
: systemRecovery
- ? `## What to do\nInvestigate and repair the machine cause with required review and CI. Preserve original work, approvals and retry/spawn budgets. Do not requeue or mark the original task complete by hand.\n\n${remedy}`
+ ? `## What to do\nResolve the affected work and investigate its root cause. Repair demonstrated code defects with regression tests, required PR review, CI and merge delivery; reuse an active fix rather than duplicate it. Record external permission or transient causes accurately without inventing a code defect. Preserve original work, approvals and retry/spawn budgets. Do not requeue or mark the original task complete by hand.\n\n${remedy}`
: `## What to do\nNo approval needed — this investigation runs unattended. Diagnose the failure above, apply the fix, and leave the task's findings in your summary. Do NOT un-block the original task by hand; completing this one does it.\n\n${remedy}`;
// Completing this task revives every blocked task in `affectedTasks`
diff --git a/server/services/agentErrorAnalysis.test.js b/server/services/agentErrorAnalysis.test.js
index 383d98e32f..b98eb90a09 100644
--- a/server/services/agentErrorAnalysis.test.js
+++ b/server/services/agentErrorAnalysis.test.js
@@ -1003,7 +1003,13 @@ describe('createInvestigationTask approval wiring (#3714)', () => {
{ ...analysis, blockedSystemRecovery: true });
expect(addTask.mock.calls[0][0]).toMatchObject({ targetInstanceId: 'fixture-local',
metadata: { preserveOriginalBudget: true, blockedSystemRecovery: true } });
- expect(addTask.mock.calls[0][0].description).toContain('existing');
+ const body = addTask.mock.calls[0][0].description;
+ expect(body).toContain('Resolve the affected work');
+ expect(body).toContain('regression tests');
+ expect(body).toContain('PR review, CI and merge delivery');
+ expect(body).toContain('reuse an active fix');
+ expect(body).toContain('without inventing a code defect');
+ expect(body).toContain('original work, approvals and retry/spawn budgets');
});
it('defers repeated system diagnosis instead of creating another blocked approval card', async () => {
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 572a94d5a0..5e2622965e 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -506,15 +506,21 @@ export async function handleAgentCompletion(agentId, exitCode, success, duration
if (completingAgents.has(agentId)) return;
// Claim before admission's first await: the process may already be gone.
completingAgents.add(agentId);
+ let retirementEligible = false;
try {
return await maintenance.withResource('agent', agentId, async () => {
+ // Capture before the pause router consumes its map entry. A paused job's
+ // checkout still belongs to its future resume, not completion retirement.
+ retirementEligible = !pausedAgents.has(agentId);
try { return await handleAdmittedAgentCompletion(agentId, exitCode, success, duration); }
catch (err) { maintenance.markResourceUnsettled('agent', agentId); throw err; }
});
} finally {
completingAgents.delete(agentId);
- void import('./agentRepoStateVerification.js').then(module => module.resumeAgentCompletionRetirement(agentId))
- .catch(error => emitLog('warn', `Completion retirement deferred for ${agentId}: ${error.message}`, { agentId }));
+ if (retirementEligible) {
+ await import('./agentRepoStateVerification.js').then(module => module.resumeAgentCompletionRetirement(agentId))
+ .catch(error => emitLog('warn', `Completion retirement deferred for ${agentId}: ${error.message}`, { agentId }));
+ }
}
}
diff --git a/server/services/agentRepoStateVerification.js b/server/services/agentRepoStateVerification.js
index 6db27c9a89..ce0e57e9e2 100644
--- a/server/services/agentRepoStateVerification.js
+++ b/server/services/agentRepoStateVerification.js
@@ -1,3 +1,5 @@
+import { retirementCheckoutIdentityFromPointer } from '../lib/retirementCheckoutObservation.js';
+import { createSingleFlight } from '../lib/singleFlight.js';
import { readGitCommonDirectory } from '../lib/gitRepositoryIdentity.js';
import { recoverCompletionTaskHandoff } from './agentCompletionTaskHandoff.js';
import { withDeliveryActivity, COMPLETION_RECOVERY_BATCH_SIZE } from './agentDeliveryActivity.js';
@@ -362,7 +364,15 @@ export async function verifyAgentRepoState(input) {
/** Wake only this terminal job after its execution entry was released. The
* periodic bounded sweep remains the durable fallback if the process exits. */
-export async function resumeAgentCompletionRetirement(agentId) {
+const releasedCompletionRuns = createSingleFlight();
+export function resumeAgentCompletionRetirement(agentId) {
+ return releasedCompletionRuns.run(agentId, () => resumeReleasedCompletion(agentId));
+}
+
+async function resumeReleasedCompletion(agentId) {
+ // A pre-release audit may still be settling an owner-active observation.
+ // Wait for it, then start a fresh verification instead of joining its stale result.
+ await verificationRuns.get(agentId)?.catch(() => {});
const { getAgentRecord } = await import('./cosAgentLifecycle.js');
const agent = await getAgentRecord(agentId);
if (agent?.status !== 'completed' || agent.result?.cleanupPending !== true
@@ -373,10 +383,39 @@ export async function resumeAgentCompletionRetirement(agentId) {
const { replayAgentCompletionCleanup } = await import('./agentCompletionCleanup.js');
await replayAgentCompletionCleanup(agent);
const current = await getAgentRecord(agentId);
- await verifyAgentRepoState({ agentId, agentState: current, task,
+ const result = await verifyAgentRepoState({ agentId, agentState: current, task,
success: current.result?.success === true, prExpected: isTruthyMeta(task.metadata?.openPR) });
const settled = await getAgentRecord(agentId);
await replayAgentCompletionCleanup(settled);
+ return result;
+}
+
+/** A completed delivery follow-up settles its original job immediately. No
+ * schedule, provider, retry reset or fabricated completion is involved. */
+const completedDeliveryParents = createSingleFlight();
+async function resumeCompletedDeliveryParent(task) {
+ const m = task?.metadata;
+ if (task?.status !== 'completed' || !isTruthyMeta(m?.reviewLoopFollowUp)
+ || typeof m.sourceAgentId !== 'string' || !m.sourceAgentId || typeof m.sourceTaskId !== 'string') return;
+ return completedDeliveryParents.run(JSON.stringify([m.sourceAgentId, m.sourceTaskId]), async () => {
+ const { getAgentRecord } = await import('./cosAgentLifecycle.js');
+ const { getInstanceId, UNKNOWN_INSTANCE_ID } = await import('./instanceIdentity.js');
+ const [parent, instanceId] = await Promise.all([getAgentRecord(m.sourceAgentId), getInstanceId()]);
+ if (parent?.taskId !== m.sourceTaskId || !instanceId || instanceId === UNKNOWN_INSTANCE_ID
+ || parent.metadata?.instanceId !== instanceId) return;
+ return resumeAgentCompletionRetirement(m.sourceAgentId);
+ });
+}
+
+/** Bind the deterministic receipt handoff, including duplicate completion replay. */
+export function bindCompletionRetirementEvents(events) {
+ const onChange = data => {
+ if (data?.task?.status !== 'completed' || !data.task.metadata?.reviewLoopFollowUp) return;
+ return resumeCompletedDeliveryParent(data.task)
+ .catch(error => emitLog('warn', `Parent completion deferred after delivery follow-up: ${error.message}`, { taskId: data.task.id }));
+ };
+ events.on('tasks:changed', onChange);
+ return () => events.off('tasks:changed', onChange);
}
let completionSweep = null;
@@ -633,7 +672,7 @@ async function settleAbsentCheckout({ agentId, agentState, metadata, app, source
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,
+ const integrated = forge && (await execGit(['merge-base', '--is-ancestor', forge.mergeCommit, forge.defaultHead], sourceWorkspace,
{ ignoreExitCode: true, env: { ...process.env, GIT_OPTIONAL_LOCKS: '0', GIT_NO_LAZY_FETCH: '1' } }).catch(() => null))?.exitCode === 0;
const completed = metadata.completedCheckouts?.find(row => [1, 2].includes(row.version) && row.agentId === agentId
&& row.startedAt === agentState.startedAt
@@ -645,8 +684,9 @@ async function settleAbsentCheckout({ agentId, agentState, metadata, app, source
}
if (!staysOpen && integrated && completed && completed.head === forge.prHead && observed.remoteBranchPresent === false) {
const { findMissingCheckoutPreservation } = await import('./heldCheckoutRecovery.js');
+ const checkoutIdentity = retirementCheckoutIdentityFromPointer(completed.incarnation?.pointer);
const release = { branch: branchName, path: worktreePath, head: completed.head,
- locked: false, lockReason: null, createdAt: completed.capturedAt };
+ locked: false, lockReason: null, createdAt: completed.capturedAt, ...(checkoutIdentity && { checkoutIdentity }) };
const proof = await findMissingCheckoutPreservation({ repoPath: sourceWorkspace, release }).catch(() => null);
if (proof) {
const { withClaimOwnershipLock } = await import('./cosClaimOwnership.js');
diff --git a/server/services/agentRepoStateVerification.test.js b/server/services/agentRepoStateVerification.test.js
index 5fc02fc94d..cb70a252c9 100644
--- a/server/services/agentRepoStateVerification.test.js
+++ b/server/services/agentRepoStateVerification.test.js
@@ -1,4 +1,6 @@
+vi.mock('./instanceIdentity.js', () => ({ getInstanceId: vi.fn(async () => 'fixture-local'), UNKNOWN_INSTANCE_ID: 'unknown' }));
vi.mock('../lib/gitRepositoryIdentity.js', () => ({ readGitCommonDirectory: vi.fn(async () => '/repo/.git') }));
+import { EventEmitter } from 'node:events';
import { readGitCommonDirectory } from '../lib/gitRepositoryIdentity.js';
vi.mock('./branchCompletionPolicy.js', async () => ({
...await vi.importActual('./branchCompletionPolicy.js'),
@@ -28,7 +30,7 @@ vi.mock('./repoCleanupRecovery.js', () => ({ inspectOrQueueCompletedReview: vi.f
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('./heldCheckoutReview.js', () => ({ readRetirementForgeEvidence: vi.fn(async () => ({ prHead: '1'.repeat(40), mergeCommit: '3'.repeat(40), defaultHead: '2'.repeat(40) })) }));
vi.mock('./completedCheckoutEvidence.js', async original => ({ ...await original(), readCompletedCheckoutIdentity: vi.fn() }));
vi.mock('./cos.js', () => ({}));
vi.mock('./agentCompletionCleanup.js', () => ({ replayAgentCompletionCleanup: vi.fn(async () => {}) }));
@@ -82,7 +84,7 @@ import { readLocalBranchPresence, readCheckoutPathPresence } from './repoCleanup
import { readCompletedCheckoutIdentity } from './completedCheckoutEvidence.js';
import { readClaimOwnershipAgents } from './cosClaimOwnership.js';
import { retryCompletionCheckoutCapture, getAgentRecord, recordCleanupOutcome, reserveRepoCleanupRecovery, recordRepoStateRecovery, recordRepoStateVerification } from './cosAgentLifecycle.js';
-import { verifyAgentRepoState, sweepRepoStateVerifications, REPO_STATE_REMEDIATIONS } from './agentRepoStateVerification.js';
+import { verifyAgentRepoState, sweepRepoStateVerifications, bindCompletionRetirementEvents, REPO_STATE_REMEDIATIONS } from './agentRepoStateVerification.js';
import { readBranchCompletionPolicies } from './branchCompletionPolicy.js';
import { releaseRetryHold } from './agentWorktreeCleanup.js';
import { getTaskById, updateTask } from './cosTaskStore.js';
@@ -138,6 +140,13 @@ const openView = (patch = {}) => JSON.stringify({ number: 9, state: 'OPEN', isDr
/** The `{user, cos}` shape `getAllTasks` really returns. Follow-ups land in `cos`. */
const queuedTasks = (tasks) => getAllTasks.mockResolvedValue({ user: { tasks: [] }, cos: { tasks } });
+const observeCompletedTask = async task => {
+ const events = new EventEmitter();
+ const unbind = bindCompletionRetirementEvents(events);
+ try { return await events.listeners('tasks:changed')[0]({ task }); }
+ finally { unbind(); }
+};
+
const run = (overrides = {}) => verifyAgentRepoState({
agentId: 'agent-1',
task: task(),
@@ -241,6 +250,71 @@ describe('verifyAgentRepoState — clean runs', () => {
expect(addTask).not.toHaveBeenCalled();
});
+ it('immediately finalizes a receipt-retired squash delivery when its follow-up completes, including duplicate observations', async () => {
+ const completed = { version: 1, agentId: 'agent-1', repoPath: '/repo', branch: BRANCH, path: WORKTREE, head: HEAD,
+ startedAt: CREATED_AT, capturedAt: CREATED_AT, incarnation: { pointer: { dev: '1', ino: '2', birthtimeNs: '3' } } };
+ const state = { ...agentState({ instanceId: 'fixture-local', completedCheckouts: [completed],
+ reviewLoopMergeTarget: { url: 'https://github.com/example/repo/pull/7' }, repoStateVerification: { status: 'pending' },
+ completionCleanup: { version: 1 } }), id: 'agent-1', taskId: 'task-1', status: 'completed',
+ result: { success: false, executionSuccess: true, cleanupPending: true } };
+ getAgentRecord.mockResolvedValue(state);
+ findMissingCheckoutPreservation.mockResolvedValue({ archiveDir: null, evidenceDigest: 'a'.repeat(64), recheck: async () => true });
+ // The old source SHA is not an ancestor after squash; only the actual merge is.
+ execGit.mockImplementation(async args => ({ exitCode: args[0] === 'merge-base' ? (args[2] === '3'.repeat(40) ? 0 : 1) : 1, stdout: '' }));
+ const followUp = { id: 'delivery-follow-up', status: 'completed', metadata: { reviewLoopFollowUp: 'true',
+ sourceAgentId: 'agent-1', sourceTaskId: 'task-1', reviewLoopPRBranch: BRANCH } };
+ queuedTasks([followUp]);
+ const events = new EventEmitter();
+ const unbind = bindCompletionRetirementEvents(events);
+ events.emit('tasks:changed', { type: 'internal', task: followUp, previousStatus: 'in_progress' });
+ events.emit('tasks:changed', { type: 'internal', task: followUp, previousStatus: 'completed' });
+ await vi.waitFor(() => expect(recordRepoStateVerification).toHaveBeenLastCalledWith('agent-1', expect.objectContaining({ status: 'completed' })));
+ unbind();
+ expect(updateTask).toHaveBeenCalledOnce();
+ expect(updateTask).toHaveBeenLastCalledWith('task-1', expect.objectContaining({ status: 'completed' }), 'user', expect.any(Object));
+ expect(recordRepoStateVerification).toHaveBeenLastCalledWith('agent-1', expect.objectContaining({ status: 'completed' }));
+ expect(addTask).not.toHaveBeenCalled();
+ expect(inspectOrQueueCompletedReview).not.toHaveBeenCalled();
+ expect(retireInventoriedCheckout).not.toHaveBeenCalled();
+ expect(findMissingCheckoutPreservation).toHaveBeenCalledWith(expect.objectContaining({ release: expect.objectContaining({ checkoutIdentity: expect.stringMatching(/^[a-f0-9]{64}$/) }) }));
+ expect(state.result).toEqual({ success: false, executionSuccess: true, cleanupPending: true });
+ });
+
+ it('waits out a pre-release owner-active audit and immediately verifies again after release', async () => {
+ const completed = { version: 1, agentId: 'agent-1', repoPath: '/repo', branch: BRANCH, path: WORKTREE, head: HEAD,
+ startedAt: CREATED_AT, capturedAt: CREATED_AT };
+ const state = { ...agentState({ instanceId: 'fixture-local', completedCheckouts: [completed],
+ reviewLoopMergeTarget: { url: 'https://github.com/example/repo/pull/7' }, repoStateVerification: { status: 'pending' } }),
+ id: 'agent-1', taskId: 'task-1', status: 'completed', result: { success: false, cleanupPending: true } };
+ getAgentRecord.mockResolvedValue(state);
+ findMissingCheckoutPreservation.mockResolvedValue({ archiveDir: null, evidenceDigest: 'a'.repeat(64), recheck: async () => true });
+ const followUp = { id: 'follow-up', status: 'completed', metadata: { reviewLoopFollowUp: true,
+ sourceAgentId: 'agent-1', sourceTaskId: 'task-1', reviewLoopPRBranch: BRANCH } };
+ queuedTasks([followUp]);
+ let releaseFirst, entered;
+ const reached = new Promise(resolve => { entered = resolve; });
+ getAllTasks.mockImplementationOnce(() => { entered(); return new Promise(resolve => { releaseFirst = resolve; }); });
+ const preRelease = run({ agentState: state, success: false });
+ await reached;
+ const afterRelease = observeCompletedTask(followUp);
+ releaseFirst({ user: { tasks: [] }, cos: { tasks: [{ ...followUp, status: 'pending', metadata: { ...followUp.metadata, app: 'demo-app' } }] } });
+ expect(await preRelease).toMatchObject({ skipReason: 'follow-up-pending' });
+ expect(await afterRelease).toMatchObject({ verified: true });
+ expect(updateTask).toHaveBeenCalledOnce();
+ expect(addTask).not.toHaveBeenCalled();
+ });
+
+ it('does not wake a different task or another instance from follow-up metadata', async () => {
+ const followUp = { status: 'completed', metadata: { reviewLoopFollowUp: true, sourceAgentId: 'agent-1', sourceTaskId: 'task-1' } };
+ for (const state of [{ taskId: 'another-task', metadata: { instanceId: 'fixture-local' } },
+ { taskId: 'task-1', metadata: { instanceId: 'another-instance' } }]) {
+ getAgentRecord.mockResolvedValue(state);
+ await observeCompletedTask(followUp);
+ }
+ expect(updateTask).not.toHaveBeenCalled();
+ expect(addTask).not.toHaveBeenCalled();
+ });
+
it('ignores the exact cleanup task itself while preserving a different pending owner', async () => {
const own = { ...task(), status: 'in_progress', metadata: { ...task().metadata,
existingBranch: BRANCH, deliveryRecovery: 'cleanup', deliveryRecoveryAgentId: 'agent-1' } };
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index e625e9375a..7328006cd9 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -403,10 +403,10 @@ export async function spawnTuiAgent({
updateAgent,
appendRunEvent,
readRunRecord: () => activeAgents.get(agentId),
- releaseRunRecord: (pid) => {
+ releaseRunRecord: async (pid) => {
if (pid) unregisterSpawnedAgent(pid);
activeAgents.delete(agentId);
- void import('./agentRepoStateVerification.js').then(module => module.resumeAgentCompletionRetirement(agentId))
+ await import('./agentRepoStateVerification.js').then(module => module.resumeAgentCompletionRetirement(agentId))
.catch(error => emitLog('warn', `Completion retirement deferred for ${agentId}: ${error.message}`, { agentId }));
maintenanceCleaned = true;
settleMaintenance();
diff --git a/server/services/agentTuiSpawning/sessionController.js b/server/services/agentTuiSpawning/sessionController.js
index 91eea231ca..26d4f918fc 100644
--- a/server/services/agentTuiSpawning/sessionController.js
+++ b/server/services/agentTuiSpawning/sessionController.js
@@ -948,8 +948,10 @@ export function createTuiSessionController({
});
}
- persistence.releaseRunRecord(agentData?.pid ?? null);
- if (sessionId && session.isAlive(sessionId)) session.kill(sessionId);
+ // Stop this finished writer before releasing its execution binding. The
+ // adapter then awaits deterministic retirement; no scheduled wake is owed.
+ if (sessionId && session.isAlive(sessionId)) await session.kill(sessionId);
+ await persistence.releaseRunRecord(agentData?.pid ?? null);
};
/**
@@ -1131,7 +1133,7 @@ export function createTuiSessionController({
errorExecutionFallback: `TUI agent ended: ${reason}`,
});
- if (finalizeOutcome.outcome === 'paused') { persistence.releaseRunRecord(agentData?.pid ?? null); return; }
+ if (finalizeOutcome.outcome === 'paused') { await persistence.releaseRunRecord(agentData?.pid ?? null); return; }
if (finalizeOutcome.outcome === 'abandoned') {
await abandonForHostShutdown();
diff --git a/server/services/agentTuiSpawning/sessionController.test.js b/server/services/agentTuiSpawning/sessionController.test.js
index 4b4d78b6c4..a18fafe682 100644
--- a/server/services/agentTuiSpawning/sessionController.test.js
+++ b/server/services/agentTuiSpawning/sessionController.test.js
@@ -155,6 +155,23 @@ describe('TUI session controller — teardown owns its own machinery (#8021)', (
expect(releaseRunRecord).toHaveBeenCalledWith(null);
});
+ it('does not finish until post-release retirement settles, after stopping its own writer', async () => {
+ const { controller, releaseRunRecord, kill } = makeController();
+ let release;
+ releaseRunRecord.mockImplementation(() => new Promise(resolve => { release = resolve; }));
+ controller.attachSession({ sessionId: 'session-abcdef12', pid: 4242 });
+ let settled = false;
+ const finishing = controller.handleExit({ exitCode: 0, killed: false }).then(() => { settled = true; });
+ await vi.advanceTimersByTimeAsync(0);
+ expect(kill).toHaveBeenCalledWith('session-abcdef12');
+ expect(releaseRunRecord).toHaveBeenCalledOnce();
+ expect(kill.mock.invocationCallOrder[0]).toBeLessThan(releaseRunRecord.mock.invocationCallOrder[0]);
+ expect(settled).toBe(false);
+ release();
+ await finishing;
+ expect(controller.isTerminal()).toBe(true);
+ });
+
it.each([
['drainLines', 'parsed output'],
['drainRaw', 'raw PTY spool'],
diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.js
index 4adf295679..b5d0b48fa8 100644
--- a/server/services/agentWorktreeCleanup.js
+++ b/server/services/agentWorktreeCleanup.js
@@ -170,6 +170,7 @@ const WORKTREE_DISPOSITIONS = Object.freeze({
'stand-down': Object.freeze({}),
'stand-down-uncertain': Object.freeze({}),
'stranded-pr-handoff': Object.freeze({}),
+ 'delivered-pr': Object.freeze({ merge: false }),
'merge-or-preserve': Object.freeze({}),
});
@@ -182,6 +183,8 @@ export function resolveWorktreeDisposition({ isWorktree, success, prCreation, di
if (success) {
if (prClaimVerdict?.category === PR_MISSING_CATEGORY) name = 'open-pr';
else name = prClaimWasVerified(prClaimVerdict) ? 'stand-down' : 'stand-down-uncertain';
+ } else if (prClaimVerdict?.mergedExactHead === true) {
+ name = 'delivered-pr';
} else if (prClaimVerdict?.status === 'found' && prClaimVerdict.url) {
name = 'stranded-pr-handoff';
}
@@ -234,8 +237,15 @@ async function probeWorktreePr(context, success) {
const { findPullRequestForBranch } = await import('./github.js');
const forge = await git.resolveForgeForRepo(worktreePath).catch(() => null);
if (!forge) return { status: 'unavailable' };
- return findPullRequestForBranch(worktreeBranch, { cwd: worktreePath, env: forge.env || null })
+ const found = await findPullRequestForBranch(worktreeBranch, { cwd: worktreePath, env: forge.env || null })
.catch(() => ({ status: 'unavailable' }));
+ if (found.status === 'found' && String(found.detail).toUpperCase() === 'MERGED' && found.headRefOid
+ && !leavesPrForHuman(context.originalTask)) {
+ const tip = await execGit(['rev-parse', '--verify', `refs/heads/${worktreeBranch}`], context.sourceWorkspace,
+ { ignoreExitCode: true }).catch(() => null);
+ if (tip?.exitCode === 0 && tip.stdout.trim() === found.headRefOid) return { ...found, mergedExactHead: true };
+ }
+ return found;
}
async function runCleanupAgentWorktree(agentId, success, options = {}) {
@@ -259,6 +269,9 @@ async function runCleanupAgentWorktree(agentId, success, options = {}) {
return discardAgentWorktree(context);
case 'open-pr':
return openWorktreePullRequest(context);
+ case 'delivered-pr':
+ await mergeOrPreserveWorktree({ ...context, skipMerge: true }, disposition);
+ break;
case 'stranded-pr-handoff': {
const released = await mergeOrPreserveWorktree(context, disposition);
if (released?.cleanupIncomplete) {
diff --git a/server/services/blockedSystemInvestigation.js b/server/services/blockedSystemInvestigation.js
index 5e3741d89a..10d3f69bb1 100644
--- a/server/services/blockedSystemInvestigation.js
+++ b/server/services/blockedSystemInvestigation.js
@@ -32,7 +32,7 @@ const analysisFor = task => ({
snippet: task.metadata.blockedReason || task.metadata.taskOutcome?.reason,
blockedSystemRecovery: true,
preserveOriginalBudget: true,
- escalation: 'Re-read the original task, current owners and delivery evidence first. Reuse active fixes. Diagnose and repair the underlying machine/product failure in an isolated checkout with required review, CI and merge admission. Preserve unfinished work and original failure/spawn budgets. Do not requeue, reset, or mark the original task completed by hand; its existing verifier and budget rules own continuation. Do not retry denied operations, change credentials, spend limits or permissions, or bypass a genuine human approval. Report actual human-required boundaries on the original record; machine-recoverable failures must not create personal Brain/todo actions.',
+ escalation: 'Re-read the original task, current owners and delivery evidence first. Reuse active fixes. Resolve the affected work within its original authority and budgets. Diagnose the underlying machine/product cause; repair a demonstrated code defect in an isolated checkout with a regression test, required review, CI, merge admission and own-checkout cleanup. Reuse and link an existing active fix instead of duplicating it. Do not invent code defects for external permission failures or transient causes; record those accurately. Preserve unfinished work and original failure/spawn budgets. Do not requeue, reset, or mark the original task completed by hand; its existing verifier and budget rules own continuation. Do not retry denied operations, change credentials, spend limits or permissions, or bypass a genuine human approval. Report actual human-required boundaries on the original record; machine-recoverable failures must not create personal Brain/todo actions.',
});
const phaseFor = task => task.status === 'in_progress' ? 'investigating'
: task.status === 'completed' ? 'diagnosed'
diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.js
index 40d3a1316d..74368bb4a8 100644
--- a/server/services/cleanupAgentWorktree.test.js
+++ b/server/services/cleanupAgentWorktree.test.js
@@ -353,6 +353,21 @@ describe('cleanupAgentWorktree - PR-creation path', () => {
);
});
+ it('cleans an already merged exact head after a cleanup-only incomplete result without a cognitive follow-up', async () => {
+ findPullRequestForBranchMock.mockResolvedValue({ status: 'found', detail: 'MERGED',
+ headRefOid: '1'.repeat(40), url: 'https://github.com/test/repo/pull/78' });
+ execGitMock.mockResolvedValue({ exitCode: 0, stdout: `${'1'.repeat(40)}\n`, stderr: '' });
+ removeWorktree.mockResolvedValue({ removed: true, merged: false, warnings: [] });
+ const warnings = await cleanupAgentWorktree('agent-1', false, { prCreation: 'if-missing',
+ originalTask: { id: 'original', metadata: { prCompletion: 'review-then-merge' } } });
+ expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'cos/task-abc123', { merge: false });
+ expect(addTask).not.toHaveBeenCalled();
+ expect(forceSpawnTask).not.toHaveBeenCalled();
+ expect(warnings).toEqual([]);
+ findPullRequestForBranchMock.mockReset().mockResolvedValue({ status: 'unavailable' });
+ execGitMock.mockReset().mockResolvedValue({ exitCode: 128, stdout: '', stderr: '' });
+ });
+
it.each([true, false])('verifies a server-created draft before completing cleanup: %s', async ok => {
git.push.mockResolvedValue(undefined);
git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/1' });
diff --git a/server/services/cos.js b/server/services/cos.js
index d75d098dbb..8b0d7b25f0 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -1637,6 +1637,12 @@ export async function init() {
}
});
+ // A delivery follow-up owns a parent continuation, not a new cron obligation.
+ // Replay of the same completed observation is safe: the parent verifier binds
+ // its exact cleanup owner and receipt, and coalesces concurrent wake-ups.
+ const { bindCompletionRetirementEvents } = await import('./agentRepoStateVerification.js');
+ bindCompletionRetirementEvents(cosEvents);
+
// Contributor remediation retains its forge hand-back when blocked. Ordinary
// merge follow-ups stay in automated recovery rather than the human inbox.
cosEvents.on('tasks:changed', (data) => {
diff --git a/server/services/heldCheckoutRecovery.js b/server/services/heldCheckoutRecovery.js
index cdc5c6cecb..ef6cc01762 100644
--- a/server/services/heldCheckoutRecovery.js
+++ b/server/services/heldCheckoutRecovery.js
@@ -1,3 +1,4 @@
+import { matchingRetirementReceipts } from '../lib/reconcileRetirementEvidence.js';
import { readRetirementCheckoutIdentity } from '../lib/retirementCheckoutObservation.js';
/**
* Operator-scoped retirement of a merged checkout that branch reconciliation
@@ -307,6 +308,34 @@ async function historicalCheckoutAbsent(release, trees) {
return !present && trees.length > 0 && !trees.some(tree => tree.path === release.path || (release.branch && shortBranch(tree.branch) === release.branch));
}
+/** Read existing no-archive service receipts, scoped to the original repository
+ * and physical checkout generation. Never infer removal from absence alone. */
+async function completedServiceRetirement(repoPath, release) {
+ if (!/^[a-f0-9]{64}$/.test(release.checkoutIdentity || '')) return null;
+ const [{ loadSchedule }, { getAppById }] = await Promise.all([
+ import('./taskScheduleStore.js'), import('./apps.js'),
+ ]);
+ const schedule = await loadSchedule();
+ const root = await realpath(repoPath).catch(() => null);
+ if (!root) return null;
+ const found = new Map();
+ for (const [appId, record] of Object.entries(schedule.executions?.['task:branch-reconcile']?.perApp || {})) {
+ const receipts = matchingRetirementReceipts(record.branchReconcileOutcome, release).filter(row => row.archiveDir == null
+ && row.checkoutIdentity === release.checkoutIdentity && Date.parse(row.retiredAt) >= Date.parse(release.createdAt));
+ if (!receipts.length) continue;
+ const app = await getAppById(appId);
+ if (!app?.repoPath || await realpath(app.repoPath).catch(() => null) !== root) continue;
+ for (const row of receipts) {
+ const key = JSON.stringify([row.branch, row.path, row.head, row.checkoutIdentity, row.retiredAt, row.branchDeleted]);
+ found.set(key, row);
+ }
+ }
+ if (found.size !== 1) return null;
+ const [key, receipt] = [...found][0];
+ return { kind: 'service-retirement-receipt', archiveDir: null, receipt,
+ evidenceDigest: createHash('sha256').update(key).digest('hex') };
+}
+
/** Completion audits have a server-captured checkout generation, but may never
* have entered the scheduled retirement queue. Reuse its archive verifier
* without creating an obligation or inventing a branch-deletion receipt.
@@ -320,6 +349,12 @@ export async function findMissingCheckoutPreservation({ repoPath, release }, opt
return ref.exitCode === 1 && await historicalCheckoutAbsent(release, trees);
};
if (!await absent()) return null;
+ const receipt = await completedServiceRetirement(repoPath, release).catch(() => null);
+ if (receipt) return { ...receipt, recheck: async () => {
+ if (!await absent()) return false;
+ const fresh = await completedServiceRetirement(repoPath, release).catch(() => null);
+ return fresh?.evidenceDigest === receipt.evidenceDigest;
+ } };
const root = heldCheckoutArchiveRoot(opts.cosDir);
const info = await lstat(root).catch(error => { if (error.code === 'ENOENT') return null; throw error; });
if (!info?.isDirectory()) return null;
diff --git a/server/services/heldCheckoutRecovery.test.js b/server/services/heldCheckoutRecovery.test.js
index 67b8a4f5e8..eae394fdce 100644
--- a/server/services/heldCheckoutRecovery.test.js
+++ b/server/services/heldCheckoutRecovery.test.js
@@ -1161,6 +1161,60 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('held checkout recovery (real git)', ()
return { path, release, admin, opts, forge, prepare, confirm };
}
+ it('settles an absent original generation from its existing service receipt without any checkout archive', async () => {
+ const c = await reviewedCheckout('receipt-no-archive');
+ const checkoutIdentity = await readRetirementCheckoutIdentity(c.path);
+ const release = { ...c.release, checkoutIdentity, createdAt: new Date(Date.now() - 1000).toISOString() };
+ const prepared = await c.prepare();
+ expect(await c.confirm(prepared.review)).toMatchObject({ ok: true, branchDeleted: true });
+ expect(await archives()).toEqual([]);
+ const proof = await findMissingCheckoutPreservation({ repoPath: repo, release });
+ expect(proof).toMatchObject({ kind: 'service-retirement-receipt', archiveDir: null,
+ receipt: { branchDeleted: true, checkoutIdentity }, evidenceDigest: expect.stringMatching(/^[a-f0-9]{64}$/) });
+ expect(await proof.recheck()).toBe(true);
+ expect(await findMissingCheckoutPreservation({ repoPath: repo, release: { ...release, checkoutIdentity: '0'.repeat(64) } })).toBeNull();
+ expect(await findMissingCheckoutPreservation({ repoPath: repo, release: { ...release, createdAt: new Date(Date.now() + 1000).toISOString() } })).toBeNull();
+ await mkdir(c.path);
+ expect(await proof.recheck()).toBe(false);
+ });
+
+ it.each(['delivered', 'unpublished-tip', 'lagging-local-default', 'merge-not-in-default'])(
+ 'keeps exact squash delivery retirement scoped when shared files change: %s', async scenario => {
+ const c = await reviewedCheckout(`exact-squash-${scenario}`, { multipleCommits: true, superseded: true });
+ if (scenario === 'unpublished-tip') {
+ await writeFile(join(c.path, 'unpublished.txt'), 'still wanted local work\n');
+ await execGit(['add', 'unpublished.txt'], c.path);
+ await execGit(['commit', '-m', 'unpublished local continuation'], c.path);
+ c.release.head = (await execGit(['rev-parse', 'HEAD'], c.path)).stdout.trim();
+ await recordBranchReconcileOutcome('app-1', { status: 'incomplete', remaining: [{ ...c.release, reason: 'pr-completion-review-required' }] });
+ }
+ if (scenario === 'lagging-local-default') {
+ await execGit(['checkout', '--detach', 'main'], repo);
+ await execGit(['branch', '-f', 'main', c.forge.changeBase], repo);
+ }
+ if (scenario === 'merge-not-in-default') c.forge.defaultHead = c.forge.changeBase;
+ const prepared = await c.prepare();
+ if (scenario === 'merge-not-in-default') {
+ expect(prepared).toMatchObject({ ok: false, reason: 'retirement-merge-not-in-default' });
+ expect(await registered(c.path)).toBe(true);
+ expect(existsSync(c.path)).toBe(true);
+ return;
+ }
+ expect(prepared).toMatchObject({ ok: true, review: { comparison: { disposition: scenario === 'unpublished-tip' ? 'review-supersession' : 'integrated' } } });
+ const result = await retireInventoriedCheckout({ appId: 'app-1', release: c.release,
+ review: { prUrl: c.forge.prUrl, digest: prepared.review.digest, acceptSuperseded: false } }, c.opts);
+ if (scenario !== 'unpublished-tip') {
+ expect(result).toMatchObject({ ok: true, branchDeleted: true });
+ expect(await registered(c.path)).toBe(false);
+ expect(existsSync(c.path)).toBe(false);
+ expect(await archives()).toEqual([]);
+ } else {
+ expect(result.ok).toBe(false);
+ expect(await registered(c.path)).toBe(true);
+ expect(existsSync(c.path)).toBe(true);
+ if (scenario === 'unpublished-tip') expect(await readFile(join(c.path, 'unpublished.txt'), 'utf8')).toBe('still wanted local work\n');
+ }
+ });
it.each(['snapshot', 'forge'])('keeps unrelated ownership admission available while preview %s work is pending', async phase => {
const c = await reviewedCheckout(`preview-queue-${phase}`);
let paused;
@@ -1257,16 +1311,11 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('held checkout recovery (real git)', ()
await recordBranchReconcileOutcome('app-1', { status: 'incomplete', remaining: [{ ...c.release, reason: 'pr-completion-review-required' }] });
const prepared = await c.prepare();
expect(prepared).toMatchObject({ ok: true, review: { comparison: { paths: ['feature.txt'],
- disposition: scenario === 'changed-delivery' ? 'review-supersession' : 'integrated' } } });
+ disposition: 'integrated' } } });
const result = await c.confirm(prepared.review);
- if (scenario === 'changed-delivery') {
- expect(result).toMatchObject({ ok: false, reason: 'retirement-supersession-not-accepted' });
- expect(await registered(c.path)).toBe(true);
- } else {
- expect(result).toMatchObject({ ok: true, branchDeleted: true });
- expect(await registered(c.path)).toBe(false);
- expect(await archives()).toEqual([]);
- }
+ expect(result).toMatchObject({ ok: true, branchDeleted: true });
+ expect(await registered(c.path)).toBe(false);
+ expect(await archives()).toEqual([]);
expect(await readFile(join(repo, scenario === 'changed-delivery' ? 'feature.txt' : 'upstream.txt'), 'utf8')).toBe('later upstream change\n');
});
@@ -1675,7 +1724,7 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('held checkout recovery (real git)', ()
expect(await archives()).toEqual([]);
});
- it.each(['head', 'supersession'])('preserves a receipt checkout when merged evidence has changed: %s', async change => {
+ it.each(['head', 'supersession'])('binds receipt cleanup to the exact merged head despite later edits: %s', async change => {
const c = await receiptCheckout('receipt-evidence', {
superseded: change === 'supersession', multipleCommits: change === 'head',
});
@@ -1685,9 +1734,10 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('held checkout recovery (real git)', ()
c.forge.prHead = c.forge.firstCommit;
c.forge.changedPaths = ['feature.txt'];
}
- expect(await c.retireReceipt()).toMatchObject({ ok: false,
- reason: change === 'head' ? 'receipt-pr-head-changed' : 'retirement-supersession-not-accepted' });
- expect(await registered(c.release.path)).toBe(true);
+ const result = await c.retireReceipt();
+ expect(result).toMatchObject(change === 'head' ? { ok: false, reason: 'receipt-pr-head-changed' }
+ : { ok: true, branchDeleted: true });
+ expect(await registered(c.release.path)).toBe(change === 'head');
expect(await archives()).toEqual([]);
});
@@ -1792,19 +1842,14 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('held checkout recovery (real git)', ()
expect(agent.result).toEqual(originalResult);
});
- it('requires supersession acceptance after an ancestral merged tip is later changed', async () => {
+ it('does not require manual supersession acceptance for an exact delivered head after later edits', async () => {
const c = await reviewedCheckout('ancestral', { normalMerge: true, superseded: true });
const prepared = await c.prepare();
- expect(prepared.ok).toBe(true);
- expect(prepared.review.comparison.disposition).toBe('review-supersession');
- expect(prepared.review.comparison.localPatch).toContain('+original feature');
- expect(prepared.review.comparison.difference).toContain('+strengthened replacement');
+ expect(prepared).toMatchObject({ ok: true, review: { comparison: { disposition: 'integrated', exactMergedDelivery: true } } });
+ expect(prepared.review.comparison.difference).toContain('strengthened replacement');
expect(await retireInventoriedCheckout({ appId: 'app-1', release: c.release,
review: { prUrl: c.forge.prUrl, digest: prepared.review.digest, acceptSuperseded: false } }, c.opts))
- .toMatchObject({ ok: false, reason: 'retirement-supersession-not-accepted' });
- expect(await registered(c.path)).toBe(true);
- expect(await lockText(c.path)).toBe(c.release.lockReason);
- expect(await archives()).toEqual([]);
+ .toMatchObject({ ok: true, branchDeleted: true });
});
it('compares pathspec glob filenames literally', async () => {
@@ -1815,7 +1860,8 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('held checkout recovery (real git)', ()
c.forge.defaultHead = (await execGit(['rev-parse', 'HEAD'], repo)).stdout.trim();
const prepared = await c.prepare();
expect(prepared.ok).toBe(true);
- expect(prepared.review.comparison.disposition).toBe('review-supersession');
+ expect(prepared.review.comparison.disposition).toBe('integrated');
+ expect(prepared.review.comparison.exactMergedDelivery).toBe(true);
expect(prepared.review.comparison.difference).toContain('+strengthened replacement');
expect(prepared.review.comparison.difference).not.toContain('unrelated glob match');
});
@@ -1835,7 +1881,7 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('held checkout recovery (real git)', ()
.toMatchObject({ ok: false, reason: 'pr-completion-review-required' });
const prepared = await c.prepare();
expect(prepared.ok).toBe(true);
- expect(prepared.review.comparison.disposition).toBe(superseded ? 'review-supersession' : 'integrated');
+ expect(prepared.review.comparison.disposition).toBe('integrated');
const result = await c.confirm(prepared.review);
expect(result).toMatchObject({ ok: true, branchDeleted: true });
expect(result.archiveDir).toBeUndefined();
diff --git a/server/services/heldCheckoutReview.js b/server/services/heldCheckoutReview.js
index b1e376e843..81ee3ae72e 100644
--- a/server/services/heldCheckoutReview.js
+++ b/server/services/heldCheckoutReview.js
@@ -168,13 +168,12 @@ export async function buildCheckoutRetirementReview({ repoPath, release, prUrl,
const paths = [...new Set(release.head === forge.prHead && !kind
? forge.changedPaths : [...forge.changedPaths, ...localPaths])].sort();
const difference = paths.length ? await git(['--literal-pathspecs', 'diff', '--binary', '--no-ext-diff', '--no-textconv', release.head, forge.defaultHead, '--', ...paths], repoPath) : '';
- // Historical ancestry/cherry equivalence does not establish that current
- // code still implements the original work (it may have been strengthened or
- // reverted). Exact affected-file equality is the mechanical case; differences
- // require the operator's explicit supersession judgment on the displayed diff.
- const mechanicallyEquivalent = difference === '' && kind !== 'source-supersession';
+ // Exact delivered PR heads remain delivered after later changes to shared
+ // files. Older/replacement heads still need content equivalence or review.
+ const exactMergedDelivery = !kind && release.head === forge.prHead;
+ const mechanicallyEquivalent = (difference === '' || exactMergedDelivery) && kind !== 'source-supersession';
const evidence = { repoPath, release, forge, contentFingerprint, administrationFingerprint, policy,
...(kind && { kind }),
- comparison: { base, paths, localPatch, difference, disposition: mechanicallyEquivalent ? 'integrated' : 'review-supersession' } };
+ comparison: { base, paths, localPatch, difference, exactMergedDelivery, disposition: mechanicallyEquivalent ? 'integrated' : 'review-supersession' } };
return { digest: createHash('sha256').update(JSON.stringify(evidence)).digest('hex'), ...evidence };
}
diff --git a/server/services/usageInteractiveScan.js b/server/services/usageInteractiveScan.js
index a691fbd0a7..c91ff8e25c 100644
--- a/server/services/usageInteractiveScan.js
+++ b/server/services/usageInteractiveScan.js
@@ -246,7 +246,7 @@ async function parseSession(family, session, from, to, byCwd, seen, regionsOf =
return results;
}
-const isSidechainPath = (path) => path.includes('/subagents/');
+const isSidechainPath = (path) => /[\\/]subagents[\\/]/.test(path);
/**
* One-time repair for Claude runs reconciled before the run path read subagent