Skip to content

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

fix: retain exact checkout incarnation through retirement admission

[._.]/ Adam Eivy497099a9ab2d
diff --cc server/services/agentFinalization.js
index 156e4f35a8,c1202f9c8f..fadbfc18fe
--- a/server/services/agentFinalization.js
+++ b/server/services/agentFinalization.js
@@@ -1,6 -1,4 +1,7 @@@
+import { storeCompletionData, completionReplayInput } from './agentCompletionData.js';
+import { prepareCompletionTaskHandoff, recoverCompletionTaskHandoff } from './agentCompletionTaskHandoff.js';
+import { hasClaimCheckoutBindings } from './completedCheckoutEvidence.js';
+ import { hasClaimFlowContract } from '../lib/claimFlowTaskTypes.js';
import { isLegacyDeepAudit } from '../lib/auditWorkflow.js';
import { retryHoldMetadata, isDeliveryCleanupHeld } from '../lib/taskRetryHold.js';
import { PR_COMPLETIONS, resolvePrCompletion, PR_MISSING_CATEGORY, prClaimWasVerified } from '../lib/prDisposition.js';
@@@ -1969,22 -1987,10 +1990,23 @@@ export async function finalizeAgent(
// completeAgentRun writes its own runs/<id>/metadata.json (separate lock),
// so its place in the chain is purely about progress reporting on partial
// failure.
- await completeAgent(agentId, { ...completionRecord({
+ await stampLiExecutionVerdict(taskUpdate, task, { success: deliverySuccess, validationPassed, errorAnalysis: deliveryVerdict.errorAnalysis });
+ const priorCleanup = cleanupOwner?.metadata?.completionCleanup;
+ const settledCleanup = ['completed', 'failed', 'abandoned'].includes(priorCleanup?.status);
+ const replay = priorCleanup?.replay || (!settledCleanup && cleanupOwner?.startedAt ? await storeCompletionData(cleanupOwner, 'replay', completionReplayInput({ task,
+ effectiveSuccess: deliverySuccess, outputBuffer,
+ prClaimVerified: prClaimWasVerified(prEvidence.cleanupEvidence), branchProvenEmpty: prEvidence.branchProvenEmpty })) : undefined);
+ await updateAgent(agentId, { metadata: { completionCleanup: { ...cleanupOwner?.metadata?.completionCleanup,
+ version: 1, status: priorCleanup?.status || 'pending', stages: priorCleanup?.stages || {}, replay, context: undefined } } });
+ if (cleanupEligible) await prepareCompletionTaskHandoff(await getAgentRecord(agentId),
+ Object.fromEntries(Object.entries(taskUpdate.metadata || {}).filter(([key, value]) =>
+ key !== 'privateSecurityScope' && JSON.stringify(value) !== JSON.stringify(preHookTask.metadata?.[key]))));
+ const completedAgent = await completeAgent(agentId, { ...completionRecord({
task, verdict: deliveryVerdict, hookResult, fidelity, executionInterruption, exitCode, duration, outputBuffer, validationPassed,
}), executionSuccess, taskOutcome,
+ requireCheckoutSettlement: deliverySuccess && taskUpdate.status === 'completed' && cleanupEligible
+ && resolvePrCompletion(task.metadata) === PR_COMPLETIONS.REVIEW_THEN_MERGE,
+ ...(claimDisposition ? { claimDisposition } : {}),
...(['task-approval', 'task-recovery-exhausted'].includes(taskUpdate.metadata?.blockedCategory)
|| taskUpdate.metadata?.retryPendingCleanup === agentId || taskUpdate.metadata?.deliveryRecoveryAgentId === agentId
? { deliveryRecoveryOwned: true } : {}),
diff --cc server/services/agentFinalization.outputHooks.test.js
index 7598dc75ed,05c625375d..bca41edcaa
--- a/server/services/agentFinalization.outputHooks.test.js
+++ b/server/services/agentFinalization.outputHooks.test.js
@@@ -1,6 -1,5 +1,8 @@@
+import { makePathsProxy, lazyTempDataRoot, cleanupTempDataRoots } from '../lib/mockPathsDataRoot.js';
+vi.mock('../lib/paths.js', async original => makePathsProxy(await original(), { dataRoot: () => lazyTempDataRoot('portos-finalization-output-') }));
+afterAll(cleanupTempDataRoots);
+ const claimVerifier = vi.hoisted(() => ({ verifyClaimDisposition: vi.fn() }));
+ vi.mock('./claimDisposition.js', () => claimVerifier);
vi.mock('../lib/fileUtils.js', async importOriginal => {
const actual = await importOriginal();
return { ...actual, tryReadFile: vi.fn(actual.tryReadFile) };
diff --cc server/services/heldCheckoutRecovery.js
index b869905430,b1c96f2844..2496291d71
--- a/server/services/heldCheckoutRecovery.js
+++ b/server/services/heldCheckoutRecovery.js
@@@ -812,6 -819,6 +819,17 @@@ async function ownerReason({ repoPath,
return mergedObligationSettled && hold === 'pr-completion-review-required' ? null : hold;
}
++/** Optional server inventory identity binds private administration as well as
++ * the pointer file. Callers have already checked the exact released lock under
++ * the retirement fence; allowing a fact-read does not authorize unlocking it. */
++async function matchesObservedCheckoutIncarnation(repoPath, release, worktrees = null) {
++ if (!release.checkoutIncarnation) return true;
++ const { readCompletedCheckoutIdentity } = await import('./completedCheckoutEvidence.js');
++ const current = await readCompletedCheckoutIdentity({ repoPath, ...release, worktrees,
++ allowLocked: release.locked === true }).catch(() => null);
++ return current && JSON.stringify(current.incarnation) === JSON.stringify(release.checkoutIncarnation);
++}
++
/** Fresh registration that still matches the release, or the reason it does not. */
async function matchRelease(repoPath, release) {
const trees = await listWorktrees(repoPath).catch(() => null);
@@@ -826,6 -833,6 +844,7 @@@
if (Boolean(tree.locked) !== release.locked || (tree.lockReason ?? null) !== (release.lockReason ?? null)) {
return { reason: 'checkout-lock-changed' };
}
++ if (!await matchesObservedCheckoutIncarnation(repoPath, release, trees)) return { reason: 'checkout-identity-changed' };
return { tree };
}
@@@ -914,6 -921,6 +933,7 @@@ async function finishHeldCheckoutRetire
}
const verifyRemoval = async (holder) => {
if (!holder || holder.head !== tree.head || shortBranch(holder.branch) !== branch) return 'worktree-holder-changed';
++ if (!await matchesObservedCheckoutIncarnation(repoPath, release)) return 'checkout-identity-changed';
if (await readRetirementCheckoutIdentity(tree.path) !== checkoutIdentity) return 'checkout-identity-changed';
if (opts.inventoryCurrent && !await opts.inventoryCurrent()) return 'release-not-in-inventory';
const [reason, fresh] = await Promise.all([
@@@ -973,7 -980,7 +993,8 @@@ function bindInventoriedRelease(outcome
if (!entry) return null;
return { path: release.path, head: release.head, branch: release.branch ?? null,
locked: release.locked, lockReason: release.lockReason ?? null,
-- ...(entry.checkoutIdentity && { checkoutIdentity: entry.checkoutIdentity }) };
++ ...(entry.checkoutIdentity && { checkoutIdentity: entry.checkoutIdentity }),
++ ...(entry.checkoutIncarnation && { checkoutIncarnation: entry.checkoutIncarnation }) };
}
// Preview and receipt paths may acquire exact server-verified proof commits
diff --cc server/services/heldCheckoutRecovery.test.js
index cf13a0cd1b,8cbecc83fc..e5c21100aa
--- a/server/services/heldCheckoutRecovery.test.js
+++ b/server/services/heldCheckoutRecovery.test.js
@@@ -1476,6 -1534,6 +1534,45 @@@ describe.skipIf(SKIP_HEAVY_INTEGRATION)
expect(await archives()).toEqual([]);
});
++ it('preserves the checkout and inventory when private administration is recreated behind an unchanged Git pointer', async () => {
++ const c = await reviewedCheckout('replaced-administration');
++ const { readCompletedCheckoutIdentity } = await import('./completedCheckoutEvidence.js');
++ const identity = await readCompletedCheckoutIdentity({ repoPath: repo, ...c.release, allowLocked: true });
++ expect(identity).not.toBeNull();
++ const checkoutIdentity = await readRetirementCheckoutIdentity(c.path);
++ await recordBranchReconcileOutcome('app-1', { status: 'incomplete', remaining: [{ ...c.release,
++ checkoutIdentity, checkoutIncarnation: identity.incarnation, reason: 'retirement-review-pending' }] });
++ const before = await getBranchReconcileOutcome('app-1');
++ const prepared = await c.prepare();
++ expect(prepared.ok).toBe(true); // Tuple-only clients use the stored full identity.
++ const pointer = await readFile(join(c.path, '.git'));
++ const index = await readFile(join(c.admin, 'index'));
++ const tracked = await readFile(join(c.path, 'initial.txt'));
++ const preserved = join(scratch, 'preserved-administration');
++ await rename(c.admin, preserved);
++ await cp(preserved, c.admin, { recursive: true });
++ expect((await execGit(['worktree', 'list', '--porcelain'], repo)).stdout.split('\n')
++ .filter(line => line === `branch refs/heads/${c.release.branch}`)).toHaveLength(1);
++ expect(await readRetirementCheckoutIdentity(c.path)).toBe(checkoutIdentity);
++ expect(await c.prepare()).toMatchObject({ ok: false, reason: 'checkout-identity-changed' });
++ expect(await c.confirm(prepared.review)).toMatchObject({ ok: false, reason: 'checkout-identity-changed' });
++ expect(await readFile(join(c.path, '.git'))).toEqual(pointer);
++ expect(await readFile(join(c.admin, 'index'))).toEqual(index);
++ expect(await readFile(join(c.path, 'initial.txt'))).toEqual(tracked);
++ expect(await readFile(join(preserved, 'index'))).toEqual(index);
++ expect(await readFile(join(c.admin, 'portos-review-status'), 'utf8')).toBe('private synthetic review marker');
++ expect(await readFile(join(c.path, 'ignored.txt'), 'utf8')).toBe('ignored work\n');
++ expect(await readFile(join(c.path, 'untracked.txt'), 'utf8')).toBe('untracked work\n');
++ expect(await lockText(c.path)).toBe(c.release.lockReason);
++ expect((await execGit(['rev-parse', `refs/heads/${c.release.branch}`], repo)).stdout.trim()).toBe(c.release.head);
++ expect(await registered(c.path)).toBe(true);
++ expect(await archives()).toEqual([]);
++ const after = await getBranchReconcileOutcome('app-1');
++ expect(after.remaining).toEqual(before.remaining);
++ expect(after.retired).toEqual(before.retired);
++ expect(after.retirementObligations).toEqual(before.retirementObligations);
++ });
++
it.each(['content', 'index', 'administration', 'default', 'pr-head', 'forge', 'policy', 'unreadable-policy', 'submodule', 'inventory'])('refuses changed %s evidence between review and confirmation', async change => {
const c = await reviewedCheckout('changed-review', { gitlink: true });
const prepared = await c.prepare();