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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: retire legacy held checkouts through scoped merge review
[._.]/ Adam Eivyf4058aa9782c
diff --git a/client/src/components/cos/tabs/schedule/BranchReconcileOutcome.jsx b/client/src/components/cos/tabs/schedule/BranchReconcileOutcome.jsxindex b057e6079e..edf86e6c9f 100644--- a/client/src/components/cos/tabs/schedule/BranchReconcileOutcome.jsx+++ b/client/src/components/cos/tabs/schedule/BranchReconcileOutcome.jsx@@ -1,6 +1,6 @@-import { useState } from 'react';+import { useId, useState } from 'react';import { formatCount, formatDateTime } from '../../../../utils/formatters';-import { retireBranchReconcileCheckout } from '../../../../services/api';+import { retireBranchReconcileCheckout, reviewBranchReconcileCheckout } from '../../../../services/api';const STATUS_LABELS = { drained: 'No remaining work in last scan', incomplete: 'Incomplete', running: 'Sweep running' };@@ -15,11 +15,25 @@ const NONE = new Set();function RetireCheckout({ appId, entry, onRetired }) {const [state, setState] = useState('idle');const [error, setError] = useState(null);+ const [prUrl, setPrUrl] = useState('');+ const [review, setReview] = useState(null);+ const [acceptSuperseded, setAcceptSuperseded] = useState(false);+ const inputId = useId();+ const needsReview = entry.reason === 'pr-completion-review-required';+ const release = { appId, path: entry.path, head: entry.head, branch: entry.branch ?? null, locked: entry.locked, lockReason: entry.lockReason ?? null };+ const prepareReview = async () => {+ setState('preparing'); setError(null); setReview(null); setAcceptSuperseded(false);+ const result = await reviewBranchReconcileCheckout({ ...release, prUrl }, { silent: true })+ .catch(err => { setError(err?.message || 'Checkout review failed'); return null; });+ if (result && !result.review) setError('Checkout review returned no comparison; checkout kept.');+ setReview(result?.review || null); setState('confirming');+ };const retire = async () => {setState('pending');setError(null);const result = await retireBranchReconcileCheckout({- appId, path: entry.path, head: entry.head, branch: entry.branch ?? null, locked: entry.locked, lockReason: entry.lockReason ?? null,+ ...release,+ ...(needsReview ? { review: { prUrl: review.forge.prUrl, digest: review.digest, acceptSuperseded } } : {}),}, { silent: true }).catch(err => {setError(err?.message || 'Checkout retirement failed');return null;@@ -44,9 +58,24 @@ function RetireCheckout({ appId, entry, onRetired }) {Release this exact checkout{entry.locked ? ' and its lock' : ''}? Tracked edits, untracked and ignored files are archived first{entry.branch ? `, then the checkout and branch ${entry.branch} are removed` : ', then the checkout is removed'}. A changed lock, HEAD or a live owner keeps everything in place.</p>+ {needsReview && <div className="space-y-2">+ <label htmlFor={inputId}>Merged pull request URL</label>+ <input id={inputId} value={prUrl} onChange={event => { setPrUrl(event.target.value); setReview(null); }} disabled={state === 'pending' || state === 'preparing'} className="w-full rounded border border-port-border bg-port-bg p-1" />+ <button type="button" onClick={prepareReview} disabled={!prUrl || state === 'pending' || state === 'preparing'} className="rounded border border-port-border px-2 py-1">{state === 'preparing' ? 'Preparing comparison…' : 'Review merged work'}</button>+ {review && <>+ <p>Compared with {review.forge.defaultBranch} at {review.forge.defaultHead}. Original work and its differences from the current default branch are shown below.</p>+ <details><summary>Original changes</summary><pre className="max-h-64 overflow-auto whitespace-pre-wrap break-all">{review.comparison.localPatch || 'No original changes.'}</pre></details>+ <details><summary>Differences from current default</summary><pre className="max-h-64 overflow-auto whitespace-pre-wrap break-all">{review.comparison.difference || 'No differences in the affected files.'}</pre></details>+ {review.comparison.disposition === 'review-supersession' && <label htmlFor={`${inputId}-superseded`} className="flex gap-2">+ <input id={`${inputId}-superseded`} type="checkbox" checked={acceptSuperseded} onChange={event => setAcceptSuperseded(event.target.checked)} />+ I reviewed these differences and confirm the current implementation supersedes this original work.+ </label>}+ </>}+ </div>}+ {error && <p role="alert" className="break-words text-port-error">{error}</p>}<div className="flex gap-2">- <button type="button" className="rounded border border-port-border px-2 py-1" disabled={state === 'pending'} onClick={() => setState('idle')}>Cancel</button>- <button type="button" className="rounded bg-port-error/80 px-2 py-1 text-white disabled:opacity-50" disabled={state === 'pending'} onClick={retire}>+ <button type="button" className="rounded border border-port-border px-2 py-1" disabled={state === 'pending' || state === 'preparing'} onClick={() => setState('idle')}>Cancel</button>+ <button type="button" className="rounded bg-port-error/80 px-2 py-1 text-white disabled:opacity-50" disabled={state === 'pending' || state === 'preparing' || (needsReview && (!review || (review.comparison.disposition === 'review-supersession' && !acceptSuperseded)))} onClick={retire}>{state === 'pending' ? 'Archiving…' : 'Yes, archive and retire'}</button></div>@@ -89,7 +118,7 @@ export default function BranchReconcileOutcome({ outcomes, apps }) {{entry.head && <p className="break-all">HEAD: {entry.head}</p>}{entry.locked && <p>Lock: {entry.lockReason || 'No reason recorded'}</p>}{entry.managed === false && <p>Outside managed worktree roots</p>}- {appId !== 'null' && isInventoriedCheckout(entry) && <RetireCheckout appId={appId} entry={entry} onRetired={markRetired} />}+ {appId !== 'null' && isInventoriedCheckout(entry) && <RetireCheckout key={JSON.stringify([appId, entry.path, entry.head, entry.branch, entry.locked, entry.lockReason, entry.reason])} appId={appId} entry={entry} onRetired={markRetired} />}</li>))}</ul>diff --git a/client/src/components/cos/tabs/schedule/BranchReconcileOutcome.test.jsx b/client/src/components/cos/tabs/schedule/BranchReconcileOutcome.test.jsxindex aaba42e319..c338afd872 100644--- a/client/src/components/cos/tabs/schedule/BranchReconcileOutcome.test.jsx+++ b/client/src/components/cos/tabs/schedule/BranchReconcileOutcome.test.jsx@@ -2,7 +2,8 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';import { render, screen, fireEvent, waitFor } from '@testing-library/react';const retire = vi.hoisted(() => vi.fn());-vi.mock('../../../../services/api', () => ({ retireBranchReconcileCheckout: retire }));+const prepare = vi.hoisted(() => vi.fn());+vi.mock('../../../../services/api', () => ({ retireBranchReconcileCheckout: retire, reviewBranchReconcileCheckout: prepare }));import BranchReconcileOutcome from './BranchReconcileOutcome';@@ -20,7 +21,7 @@ function open() {}describe('BranchReconcileOutcome checkout retirement', () => {- beforeEach(() => { retire.mockReset(); });+ beforeEach(() => { retire.mockReset(); prepare.mockReset(); });it('sends the exact inventory row as the scoped release and hides the row until a fresh inventory arrives', async () => {retire.mockResolvedValue({ ok: true, archiveDir: '/example/archive', branchDeleted: true });@@ -49,4 +50,46 @@ describe('BranchReconcileOutcome checkout retirement', () => {expect(screen.getByText('/example/held')).toBeVisible();expect(screen.getByRole('button', { name: 'Archive and retire checkout…' })).toBeVisible();});++ it('keeps confirmation disabled when preparation returns no review', async () => {+ prepare.mockResolvedValue({ ok: true, review: null });+ render(<BranchReconcileOutcome outcomes={{ 'app-1': { status: 'incomplete', remaining: [{ ...held, reason: 'pr-completion-review-required' }] } }} apps={[]} />);+ fireEvent.click(screen.getByRole('button', { name: 'Archive and retire checkout…' }));+ fireEvent.change(screen.getByLabelText('Merged pull request URL'), { target: { value: 'https://github.com/example/repo/pull/42' } });+ fireEvent.click(screen.getByRole('button', { name: 'Review merged work' }));+ await waitFor(() => expect(screen.getByRole('button', { name: 'Review merged work' })).toBeEnabled());+ expect(screen.getByRole('button', { name: 'Yes, archive and retire' })).toBeDisabled();+ expect(retire).not.toHaveBeenCalled();+ });++ it('requires review and explicit supersession acceptance, discarding review when the inventory changes', async () => {+ const legacy = { ...held, reason: 'pr-completion-review-required' };+ const review = { digest: 'd'.repeat(64), forge: { prUrl: 'https://github.com/example/repo/pull/42', defaultBranch: 'main', defaultHead: 'b'.repeat(40) },+ comparison: { localPatch: 'original change', difference: 'strengthened replacement', disposition: 'review-supersession' } };+ let resolveReview;+ prepare.mockImplementation(() => new Promise(resolve => { resolveReview = resolve; }));+ retire.mockRejectedValue(new Error('Checkout kept: retirement-review-changed'));+ const props = { outcomes: { 'app-1': { status: 'incomplete', remaining: [legacy] } }, apps: [] };+ const { rerender } = render(<BranchReconcileOutcome {...props} />);+ fireEvent.click(screen.getByRole('button', { name: 'Archive and retire checkout…' }));+ expect(screen.getByRole('button', { name: 'Yes, archive and retire' })).toBeDisabled();+ fireEvent.change(screen.getByLabelText('Merged pull request URL'), { target: { value: review.forge.prUrl } });+ fireEvent.click(screen.getByRole('button', { name: 'Review merged work' }));+ expect(screen.getByRole('button', { name: 'Preparing comparison…' })).toBeDisabled();+ expect(screen.getByRole('button', { name: 'Yes, archive and retire' })).toBeDisabled();+ resolveReview({ ok: true, review });+ expect(await screen.findByText('strengthened replacement')).toBeInTheDocument();+ expect(retire).not.toHaveBeenCalled();+ expect(screen.getByRole('button', { name: 'Yes, archive and retire' })).toBeDisabled();+ fireEvent.click(screen.getByRole('checkbox'));+ fireEvent.click(screen.getByRole('button', { name: 'Yes, archive and retire' }));+ await waitFor(() => expect(retire).toHaveBeenCalledWith(expect.objectContaining({+ review: { prUrl: review.forge.prUrl, digest: review.digest, acceptSuperseded: true },+ }), { silent: true }));+ expect(await screen.findByRole('alert')).toHaveTextContent('retirement-review-changed');+ rerender(<BranchReconcileOutcome {...props} outcomes={{ 'app-1': { status: 'incomplete', remaining: [{ ...legacy, head: 'c'.repeat(40) }] } }} />);+ fireEvent.click(screen.getByRole('button', { name: 'Archive and retire checkout…' }));+ expect(screen.queryByText('strengthened replacement')).toBeNull();+ expect(screen.getByRole('button', { name: 'Yes, archive and retire' })).toBeDisabled();+ });});diff --git a/client/src/services/apiAgents.js b/client/src/services/apiAgents.jsindex 6a62e81714..885d75e0a9 100644--- a/client/src/services/apiAgents.js+++ b/client/src/services/apiAgents.js@@ -397,12 +397,16 @@ export const triggerCosOnDemandTask = (taskType, appId = null, options = {}) =>...options});// Archive and retire one held checkout named exactly as the last branch-reconcile inventory reported it.-export const retireBranchReconcileCheckout = ({ appId, path, head, branch = null, locked, lockReason = null }, options = {}) => request('/cos/schedule/branch-reconcile/checkouts/retire', {+export const retireBranchReconcileCheckout = ({ appId, path, head, branch = null, locked, lockReason = null, review }, options = {}) => request('/cos/schedule/branch-reconcile/checkouts/retire', {method: 'POST',- body: JSON.stringify({ appId, path, head, branch, locked, lockReason }),+ body: JSON.stringify({ appId, path, head, branch, locked, lockReason, review }),...options});+export const reviewBranchReconcileCheckout = (body, options = {}) => request('/cos/schedule/branch-reconcile/checkouts/review', {+ method: 'POST', body: JSON.stringify(body), ...options+});+// Autonomous Jobsexport const getCosJobs = (options = {}) => request('/cos/jobs', options);export const getCosJob = (id, options = {}) => request(`/cos/jobs/${id}`, options);diff --git a/server/lib/hostControlRoutes.js b/server/lib/hostControlRoutes.jsindex 78dd47432d..f53ac795f1 100644--- a/server/lib/hostControlRoutes.js+++ b/server/lib/hostControlRoutes.js@@ -387,6 +387,7 @@ export const HOST_CONTROL_ROUTES = Object.freeze(['POST /api/cos/schedule/trigger',// Archives and removes a checkout and its merged branch under a scoped release.'POST /api/cos/schedule/branch-reconcile/checkouts/retire',+ 'POST /api/cos/schedule/branch-reconcile/checkouts/review','POST /api/cos/schedule/maintenance-runs',// Editing a pending stage changes the provider used by deferred host work.'PATCH /api/cos/schedule/maintenance-runs/:id/steps/:stepId',diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 2209e5232d..21d5ac4246 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -2841,7 +2841,13 @@ export const heldCheckoutRetireBodySchema = z.object({branch: z.string().min(1).nullable(),locked: z.boolean(),lockReason: z.string().nullable(),+ review: z.object({+ prUrl: z.string().url(),+ digest: z.string().regex(/^[a-f0-9]{64}$/),+ acceptSuperseded: z.boolean(),+ }).optional(),});+export const heldCheckoutReviewBodySchema = heldCheckoutRetireBodySchema.omit({ review: true }).extend({ prUrl: z.string().url() });// Per-app task-type overrides (routes/apps/taskTypes.js)export const appTaskTypeToggleBodySchema = z.object({ enabled: z.boolean() });diff --git a/server/routes/cosScheduleRoutes.js b/server/routes/cosScheduleRoutes.jsindex 5eac1776e8..d159ce588b 100644--- a/server/routes/cosScheduleRoutes.js+++ b/server/routes/cosScheduleRoutes.js@@ -9,7 +9,7 @@ import { z } from 'zod';import * as taskSchedule from '../services/taskSchedule.js';import { logCosScheduleUpdate } from '../services/userActionScheduleLog.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';-import { sanitizeTaskMetadata, taskDataInputsSchema, validateRequest, parsePagination, cosScheduleTargetBodySchema, heldCheckoutRetireBodySchema } from '../lib/validation.js';+import { sanitizeTaskMetadata, taskDataInputsSchema, validateRequest, parsePagination, cosScheduleTargetBodySchema, heldCheckoutRetireBodySchema, heldCheckoutReviewBodySchema } from '../lib/validation.js';import { promptSourceSchema, PROMPT_SOURCES, scheduleExecutionFieldsSchema } from '../lib/cosValidation.js';import { EFFORT_LEVELS } from '../lib/providerModels.js';import { INTERVAL_TYPES, decodeIntervalType, isCronExpression, isKnownIntervalType } from '../services/taskScheduleConstants.js';@@ -289,12 +289,23 @@ router.post('/schedule/trigger', asyncHandler(async (req, res) => {res.json({ success: true, request });}));+// Prepare evidence only; the separate confirmation binds its digest to fresh facts.+router.post('/schedule/branch-reconcile/checkouts/review', asyncHandler(async (req, res) => {+ const { appId, prUrl, ...release } = validateRequest(heldCheckoutReviewBodySchema, req.body);+ const { prepareInventoriedCheckoutRetirement } = await import('../services/heldCheckoutRecovery.js');+ const result = await prepareInventoriedCheckoutRetirement({ appId, release, prUrl });+ if (!result.ok) throw new ServerError(`Checkout review refused: ${result.reason}`, {+ status: 409, code: 'CHECKOUT_REVIEW_REFUSED', context: { reason: result.reason },+ });+ res.json(result);+}));+// POST /api/cos/schedule/branch-reconcile/checkouts/retire - Archive and retire// one held checkout from the last branch-reconcile inventory (#12002)router.post('/schedule/branch-reconcile/checkouts/retire', asyncHandler(async (req, res) => {- const { appId, ...release } = validateRequest(heldCheckoutRetireBodySchema, req.body);+ const { appId, review, ...release } = validateRequest(heldCheckoutRetireBodySchema, req.body);const { retireInventoriedCheckout } = await import('../services/heldCheckoutRecovery.js');- const result = await retireInventoriedCheckout({ appId, release });+ const result = await retireInventoriedCheckout({ appId, release, review });if (!result.ok) {throw new ServerError(`Checkout kept: ${result.reason}${result.detail ? ` (${result.detail})` : ''}`, {status: result.reason === 'app-not-found' ? 404 : 409, code: 'CHECKOUT_RETIREMENT_REFUSED', context: { reason: result.reason },diff --git a/server/routes/cosScheduleRoutes.test.js b/server/routes/cosScheduleRoutes.test.jsindex 60f56d30b8..f4961af284 100644--- a/server/routes/cosScheduleRoutes.test.js+++ b/server/routes/cosScheduleRoutes.test.js@@ -7,6 +7,8 @@ const recordUserAction = vi.hoisted(() => vi.fn(async () => ({ id: 'evt' })));vi.mock('../services/userActions.js', () => ({ recordUserAction }));const maintenance = vi.hoisted(() => ({ updateMaintenanceStep: vi.fn(), listMaintenanceRuns: vi.fn(), startMaintenanceRun: vi.fn(), stopMaintenanceRun: vi.fn(), resumeMaintenanceRun: vi.fn() }));vi.mock('../services/maintenanceRun.js', () => maintenance);+const recovery = vi.hoisted(() => ({ prepareInventoriedCheckoutRetirement: vi.fn(), retireInventoriedCheckout: vi.fn() }));+vi.mock('../services/heldCheckoutRecovery.js', () => recovery);vi.mock('../services/taskSchedule.js', () => ({getScheduleStatus: vi.fn(),@@ -42,6 +44,23 @@ describe('CoS Schedule Routes', () => {vi.clearAllMocks();});+ it('validates and forwards separate retirement review evidence without including it in checkout identity', async () => {+ const tuple = { path: '/synthetic/checkout', head: 'a'.repeat(40), branch: 'claim/42', locked: false, lockReason: null };+ const prUrl = 'https://github.com/example/repo/pull/42';+ recovery.prepareInventoriedCheckoutRetirement.mockResolvedValue({ ok: true, review: { digest: 'b'.repeat(64) } });+ const prepared = await request(app).post('/api/cos/schedule/branch-reconcile/checkouts/review').send({ appId: 'app-1', ...tuple, prUrl });+ expect(prepared.status).toBe(200);+ expect(recovery.prepareInventoriedCheckoutRetirement).toHaveBeenCalledWith({ appId: 'app-1', release: tuple, prUrl });+ const review = { prUrl, digest: 'b'.repeat(64), acceptSuperseded: true };+ recovery.retireInventoriedCheckout.mockResolvedValue({ ok: false, reason: 'retirement-review-changed' });+ const kept = await request(app).post('/api/cos/schedule/branch-reconcile/checkouts/retire').send({ appId: 'app-1', ...tuple, review });+ expect(kept.status).toBe(409);+ expect(recovery.retireInventoriedCheckout).toHaveBeenCalledWith({ appId: 'app-1', release: tuple, review });+ recovery.retireInventoriedCheckout.mockClear();+ expect((await request(app).post('/api/cos/schedule/branch-reconcile/checkouts/retire').send({ appId: 'app-1', ...tuple, review: { ...review, digest: 'wrong' } })).status).toBe(400);+ expect(recovery.retireInventoriedCheckout).not.toHaveBeenCalled();+ });+describe('GET /api/cos/schedule', () => {it('surfaces unavailable schedule inputs as errors and recovers on the next read', async () => {taskSchedule.getScheduleStatusdiff --git a/server/services/README.md b/server/services/README.mdindex ac0161f208..df4e36173b 100644--- a/server/services/README.md+++ b/server/services/README.md@@ -7,6 +7,8 @@ image-generation paths below are useful entry points when tracing render jobs.| Module | Responsibility || --- | --- || `branchReconcileCompletion.js` | Runs ownership-checked merged and superseded cleanup on coordinator completion, independent of perpetual scheduling. |+| `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. |+| `heldCheckoutRecovery.js` | Prepares scoped retirement reviews and preserves checkout content, empty gitlinks and private Git administration before ownership-checked removal and expected-head local ref deletion. || `branchCompletionPolicy.js` | Retains explicit registered PR completion policy through agent archives. `readBranchCompletionHold` gates reconciliation by exact repository/branch/PR identity; human handoffs and configured review stay held, explicit releases require a fresh matching forge head, and verified merged retirement is a separate action. || `databaseCutoverHandshake.js` | Narrow fenced-boot path for the ordinary server: at `verifying`/`verified` prove this process's own pool reaches the recorded target, publish a per-pid proof, and wait for admission release before the app graph loads. || `databaseMaintenanceCutover.js` | Internal cutover worker body (transfer → forward-only `.env` mode commit → server restart with target proof → release → CoS restart) and `recoverDatabaseCutover(id)` same-operation recovery for the CLI/API. |diff --git a/server/services/branchCompletionPolicy.js b/server/services/branchCompletionPolicy.jsindex de34356608..b7bb0384f9 100644--- a/server/services/branchCompletionPolicy.js+++ b/server/services/branchCompletionPolicy.js@@ -23,15 +23,15 @@ const unavailableBecause = cause => new Error(unavailable, { cause });* rejection into the same per-branch reason. Any other failure is wrapped as* the unavailable reason with that failure as its cause.*/-export async function readBranchCompletionPolicies() {- return readPolicies().catch(error => {+export async function readBranchCompletionPolicies({ repairIndex = true } = {}) {+ return readPolicies(repairIndex).catch(error => {const cause = error.cause ?? error;console.warn(`⚠️ Branch completion policy unavailable: ${cause.code ? `${cause.code} ` : ''}${cause.message}`);throw error.message === unavailable ? error : unavailableBecause(error);});}-async function readPolicies() {+async function readPolicies(repairIndex) {const { readAgentsStateForSafetyCheck } = await import('./cosState.js');const snapshot = await readAgentsStateForSafetyCheck();if (!snapshot.trusted || !isPlainObject(snapshot.agents)) throw unavailableBecause(new Error('live agent state is untrusted'));@@ -67,7 +67,7 @@ async function readPolicies() {agents.set(id, agent);}));}- if (dangling.length) dropDanglingIndexRows(dangling);+ if (repairIndex && dangling.length) dropDanglingIndexRows(dangling);return [...agents.values()];}@@ -115,13 +115,31 @@ function completionDecision({ repoPath, branch, prUrl, tip, agents }) {policies.sort((a, b) => b.time - a.time);const handoff = policies.find(policy => policy.completion === PR_COMPLETIONS.LEAVE_OPEN);const obligation = policies.find(policy => [PR_COMPLETIONS.LEAVE_OPEN, PR_COMPLETIONS.REVIEW_THEN_MERGE].includes(policy.completion));- if (!obligation) return { reason: null };+ if (!obligation) return { reason: null, policies };const release = policies.find(policy => policy.time > obligation.time&& policy.agent.status === 'completed' && policy.agent.result?.success === true&& policy.completion === PR_COMPLETIONS.MERGE_ON_GREEN&& policy.prUrl && policy.prUrl === obligation.prUrl && (!prUrl || policy.prUrl === prUrl)&& policy.tip && policy.tip === tip);- return { release, obligation, reason: handoff ? held : 'pr-completion-review-required' };+ return { release, obligation, policies, reason: handoff ? held : 'pr-completion-review-required' };+}++/** A new operator review may settle completed legacy review obligations only.+ * This is evidence for the scoped retirement caller, never unattended consent.+ */+export function reviewedRetirementPolicy(input) {+ const decision = completionDecision(input);+ if (decision.reason === unavailable || decision.reason === held) return { reason: decision.reason };+ const policies = decision.policies || [];+ if (policies.some(p => p.agent.status !== 'completed' || p.agent.result?.success !== true+ || p.completion !== PR_COMPLETIONS.REVIEW_THEN_MERGE || p.prUrl)) {+ return { reason: 'retirement-policy-not-legacy-completed' };+ }+ return { reason: null, policies: policies.map(p => ({+ id: p.agent.id || p.agent.agentId, startedAt: p.agent.startedAt,+ completedAt: p.agent.completedAt, status: p.agent.status, success: p.agent.result.success,+ branch: p.branch, completion: p.completion,+ })).sort((a, b) => String(a.id).localeCompare(String(b.id))) };}export async function readBranchCompletionHold(input, deps = {}) {diff --git a/server/services/branchCompletionPolicy.test.js b/server/services/branchCompletionPolicy.test.jsindex 6ee2b0d0aa..dfe68e6b0c 100644--- a/server/services/branchCompletionPolicy.test.js+++ b/server/services/branchCompletionPolicy.test.js@@ -40,7 +40,7 @@ vi.mock('./worktreeManager.js', () => ({ listWorktrees: async () => [], classifyimport { spawnReviewLoopFollowUp } from './agentWorktreeCleanup.js';import { buildAgentRegistration } from '../lib/agentRegistrationRecord.js';-import { readBranchCompletionHold, readBranchCompletionPolicies, recordBranchCompletionPolicy } from './branchCompletionPolicy.js';+import { reviewedRetirementPolicy, readBranchCompletionHold, readBranchCompletionPolicies, recordBranchCompletionPolicy } from './branchCompletionPolicy.js';import { gatherBranchState, classifyBranches, filterActionable, formatInFlightForPrompt } from './branchReconcile.js';import { checkReconcileOwnership } from './cosClaimOwnership.js';import { removeDanglingAgentIndexEntries } from './cosAgentIndex.js';@@ -222,3 +222,26 @@ describe('completion policy across lifecycle and reconciliation boundaries', ()expect(await recheck()).toEqual({ admitted: false, reason: 'pr-completion-human-handoff' });});});++describe('scoped legacy retirement policy', () => {+ it.each(['running', 'paused', 'failed', 'leave-open', 'merge-on-green', 'known-pr'])('retains %s obligations', change => {+ register('agent-legacy', 'review-then-merge');+ const agent = runtime.agents['agent-legacy'];+ if (['running', 'paused'].includes(change)) agent.status = change;+ if (change === 'failed') agent.result.success = false;+ if (['leave-open', 'merge-on-green'].includes(change)) agent.metadata.prCompletionPolicy = change;+ if (change === 'known-pr') agent.metadata.branchCompletionPolicy = { branch, completion: 'review-then-merge', prUrl };+ expect(reviewedRetirementPolicy({ repoPath, branch, agents: [agent] }).reason).toBeTruthy();+ });++ it('reads archived obligations without repairing index state for operator review', async () => {+ register('agent-legacy', 'review-then-merge');+ await mkdir(join(runtime.dir, 'agents'), { recursive: true });+ await writeFile(join(runtime.dir, 'agents', 'index.json'), JSON.stringify({ 'agent-gone': '2026-02-01' }));+ removeDanglingAgentIndexEntries.mockClear();+ const agents = await readBranchCompletionPolicies({ repairIndex: false });+ expect(reviewedRetirementPolicy({ repoPath, branch, agents })).toMatchObject({ reason: null, policies: [{ id: 'agent-legacy' }] });+ expect(removeDanglingAgentIndexEntries).not.toHaveBeenCalled();+ expect(await snapshotHold(agents)).toBe('pr-completion-review-required');+ });+});diff --git a/server/services/heldCheckoutRecovery.js b/server/services/heldCheckoutRecovery.jsindex 5fbee9f20e..8f7768506f 100644--- a/server/services/heldCheckoutRecovery.js+++ b/server/services/heldCheckoutRecovery.js@@ -10,8 +10,7 @@* release: a changed lock, HEAD or branch is an ownership change and refuses.** Before any mutation every unique byte is archived under- * `data/cos/held-checkout-archives/`: a bundle of commits not on the default- * branch, the staged and unstaged diffs, raw bytes of tracked files that differ+ * `data/cos/held-checkout-archives/`: a standalone bundle of the original commit history, the staged and unstaged diffs, raw bytes of tracked files that differ* from their index blob, and verbatim copies of untracked AND ignored files* (symlinks as recorded targets). The archive is verified by hash against the* checkout, and the checkout's content hashes must not move between archive and@@ -20,7 +19,7 @@*/import { createReadStream } from 'node:fs';-import { lstat, readlink } from 'node:fs/promises';+import { lstat, readlink, readdir, chmod } from 'node:fs/promises';import { createHash } from 'node:crypto';import { dirname, join } from 'node:path';import { atomicWrite, copyFileGuarded, ensureDir, PATHS, rmGuarded, sha256File, writeFileGuarded } from '../lib/fileUtils.js';@@ -29,7 +28,7 @@ import { PROTECTED_BRANCHES } from '../lib/gitArgs.js';import { claimCheckoutOwnerReason } from '../lib/claimContinuation.js';import { backupSlug } from './supersededBackup.js';import { listWorktrees, forceRemoveWorktreeDir } from './worktreeManager.js';-import { getDefaultBranch, hasBranchMergeEvidence, deleteBranch } from './git.js';+import { getDefaultBranch, hasBranchMergeEvidence } from './git.js';import { withClaimOwnershipLock, readClaimOwnershipAgents } from './cosClaimOwnership.js';export const heldCheckoutArchiveRoot = (cosDir = PATHS.cos) => join(cosDir, 'held-checkout-archives');@@ -46,6 +45,67 @@ const shortBranch = (ref) => (ref ? String(ref).replace(/^refs\/heads\//, '') :const zLines = (stdout) => (stdout || '').split('\0').filter(Boolean);const git = (args, cwd) => execGit(args, cwd, { maxBuffer: GIT_OUTPUT_BYTES }).then(r => r.stdout || '');+/** Preserve worktree-private Git evidence, never follow its links into the+ * common repository. The lock is archived but matched separately by release.+ */+async function snapshotAdministration(path) {+ const root = (await git(['rev-parse', '--absolute-git-dir'], path)).trim();+ const files = [];+ const symlinks = [];+ let bytes = 0;+ const visit = async (source, rel) => {+ const info = await lstat(source);+ if (info.isSymbolicLink()) { symlinks.push({ path: rel, target: await readlink(source) }); return; }+ if (info.isDirectory()) {+ for (const name of (await readdir(source)).sort()) await visit(join(source, name), rel ? `${rel}/${name}` : name);+ return;+ }+ if (!info.isFile() || info.size > MAX_FILE_BYTES || (bytes += info.size) > MAX_TOTAL_BYTES) throw new Error('administration cannot be archived');+ files.push({ path: rel, source, bytes: info.size, sha256: await sha256File(source) });+ };+ await visit(root, 'gitdir');+ const pointer = join(path, '.git');+ if (!(await lstat(pointer)).isFile()) throw new Error('checkout git indirection is not a file');+ await visit(pointer, 'git-indirection');+ const fingerprint = createHash('sha256').update(JSON.stringify({+ files: files.filter(file => file.path !== 'gitdir/locked').map(({ source: _source, ...file }) => file), symlinks,+ })).digest('hex');+ return { files, symlinks, fingerprint };+}++async function retirementPolicy(repoPath, branch, opts) {+ const { readBranchCompletionPolicies, reviewedRetirementPolicy } = await import('./branchCompletionPolicy.js');+ const policies = await (opts.readPolicies || (() => readBranchCompletionPolicies({ repairIndex: false })))().catch(() => null);+ return reviewedRetirementPolicy({ repoPath, branch, agents: policies });+}++async function reviewCurrentCheckout({ repoPath, release, prUrl, unlocked = false }, opts = {}) {+ if (!release.branch || PROTECTED_BRANCHES.includes(release.branch)) return { ok: false, reason: 'protected-branch' };+ const matched = await matchRelease(repoPath, unlocked ? { ...release, locked: false, lockReason: null } : release);+ if (!matched.tree) return { ok: false, reason: matched.reason };+ const owner = await ownerReason({ repoPath, tree: matched.tree, branch: release.branch,+ readAgents: opts.readAgents || readClaimOwnershipAgents, reviewed: true });+ if (owner) return { ok: false, reason: owner };+ const policy = await retirementPolicy(repoPath, release.branch, opts);+ if (policy.reason) return { ok: false, reason: policy.reason };+ const { buildCheckoutRetirementReview } = await import('./heldCheckoutReview.js');+ return Promise.all([snapshotContent(release.path), snapshotAdministration(release.path)])+ .then(([content, administration]) => buildCheckoutRetirementReview({ repoPath, release, prUrl,+ contentFingerprint: content.fingerprint, administrationFingerprint: administration.fingerprint, policy }, opts))+ .then(review => ({ ok: true, review }), error => ({ ok: false,+ reason: /^retirement-[a-z-]+$/.test(error.message) ? error.message : 'retirement-local-evidence-unavailable' }));+}++/** Read-only, host-control-gated review of exactly one current inventory row. */+export async function prepareInventoriedCheckoutRetirement({ appId, release, prUrl }, opts = {}) {+ const [{ getAppById }, { getBranchReconcileOutcome }] = await Promise.all([import('./apps.js'), import('./taskSchedule.js')]);+ const app = await getAppById(appId);+ if (!app?.repoPath) return { ok: false, reason: 'app-not-found' };+ const outcome = await getBranchReconcileOutcome(appId);+ if (!outcome?.remaining?.some(entry => sameRelease(entry, release))) return { ok: false, reason: 'release-not-in-inventory' };+ return withClaimOwnershipLock(() => reviewCurrentCheckout({ repoPath: app.repoPath, release, prUrl }, { ...opts, forgeAccount: app.forgeAccount ?? null }));+}+/** Git's object id for raw bytes, with no clean filter or line-ending conversion. */async function rawBlobId(source, size, format) {const hash = createHash(format).update(`blob ${size}\0`);@@ -65,8 +125,15 @@ async function rawBlobId(source, size, format) {async function snapshotContent(path) {if ((await git(['ls-files', '-u', '-z'], path)).length) throw new Error('unmerged index entries cannot be archived');const stage = zLines(await git(['ls-files', '--stage', '-z'], path));- // A submodule's files and commits live in its own repository; its gitlink is not its content.- if (stage.some(line => line.startsWith('160000 '))) throw new Error('submodules cannot be archived');+ const gitlinks = [];+ for (const line of stage.filter(row => row.startsWith('160000 '))) {+ const tab = line.indexOf('\t');+ const header = line.slice(0, tab);+ const rel = line.slice(tab + 1);+ const info = await lstat(join(path, rel)).catch(error => { if (error.code === 'ENOENT') return null; throw error; });+ if (info && (!info.isDirectory() || (await readdir(join(path, rel))).length)) throw new Error('retirement-submodule-not-uninitialized');+ gitlinks.push({ path: rel, commit: header.split(' ')[1], state: info ? 'empty' : 'missing' });+ }// Assume-unchanged (lowercase tag) and skip-worktree (S) entries hide edits from diff.const hidden = zLines(await git(['ls-files', '-v', '-z'], path)).find(line => /^[a-zS]/.test(line));if (hidden) throw new Error(`${hidden.slice(2)} hides working-tree changes from Git`);@@ -102,8 +169,8 @@ async function snapshotContent(path) {else throw new Error(`${rel} is not a regular file`);}const fingerprint = createHash('sha256').update(indexDiff).update('\0').update(worktreeDiff).update('\0')- .update(JSON.stringify({ files, symlinks })).digest('hex');- return { indexDiff, worktreeDiff, files, symlinks, fingerprint };+ .update(JSON.stringify({ files, symlinks, gitlinks })).digest('hex');+ return { indexDiff, worktreeDiff, files, symlinks, gitlinks, fingerprint };}/**@@ -120,21 +187,27 @@ async function archiveCheckout(input) {});}-async function writeArchive(dir, { repoPath, tree, branch, defaultBranch, release }) {+async function writeArchive(dir, { repoPath, tree, branch, defaultBranch, release, review }) {const snapshot = await snapshotContent(tree.path);await ensureDir(dir);+ await chmod(dir, 0o700);+ const administration = await snapshotAdministration(tree.path);// A bundle keeps the original commit objects, merges included, which a// squash-merged branch would otherwise lose to garbage collection.- const unique = Number((await git(['rev-list', '--count', `${defaultBranch}..${tree.head}`], repoPath)).trim());- if (!Number.isInteger(unique)) throw new Error('could not count commits outside the default branch');const bundle = join(dir, 'commits.bundle');- if (unique > 0) {- await git(['bundle', 'create', bundle, 'HEAD', `^${defaultBranch}`], tree.path);- await git(['bundle', 'verify', bundle], repoPath);- const heads = await git(['bundle', 'list-heads', bundle], repoPath);- if (!heads.startsWith(`${tree.head} `)) throw new Error('commit bundle does not hold the checkout HEAD');+ await git(['bundle', 'create', bundle, 'HEAD'], tree.path);+ await git(['bundle', 'verify', bundle], repoPath);+ if (!(await git(['bundle', 'list-heads', bundle], repoPath)).startsWith(`${tree.head} `)) throw new Error('bundle head mismatch');+ await chmod(bundle, 0o600);+ for (const file of administration.files) {+ const destination = join(dir, 'administration', file.path);+ await ensureDir(dirname(destination));+ await copyFileGuarded(file.source, destination);+ await chmod(destination, 0o600);+ if (await sha256File(destination) !== file.sha256) throw new Error('administration archive mismatch');}+ if ((await snapshotAdministration(tree.path)).fingerprint !== administration.fingerprint) throw new Error('administration changed while archiving');if (snapshot.indexDiff) await writeFileGuarded(join(dir, 'index.diff'), snapshot.indexDiff);if (snapshot.worktreeDiff) await writeFileGuarded(join(dir, 'worktree.diff'), snapshot.worktreeDiff);@@ -149,10 +222,10 @@ async function writeArchive(dir, { repoPath, tree, branch, defaultBranch, releasawait atomicWrite(join(dir, 'manifest.json'), {repoPath, defaultBranch, path: tree.path, head: tree.head, branch,- release, archivedAt: new Date().toISOString(),- captured: { commitBundle: unique > 0, indexDiff: Boolean(snapshot.indexDiff), worktreeDiff: Boolean(snapshot.worktreeDiff), files, symlinks },+ release, review, administration: { ...administration, files: administration.files.map(({ source: _source, ...file }) => file) }, archivedAt: new Date().toISOString(),+ captured: { commitBundle: true, gitlinks: snapshot.gitlinks, indexDiff: Boolean(snapshot.indexDiff), worktreeDiff: Boolean(snapshot.worktreeDiff), files, symlinks },restore: [- unique > 0 ? 'git -C <repo> fetch commits.bundle HEAD:refs/heads/<restored-branch>' : null,+ 'git -C <repo> fetch commits.bundle HEAD:refs/heads/<restored-branch>',`git -C <repo> worktree add <checkout> ${tree.head}`,snapshot.indexDiff ? 'git -C <checkout> apply --index index.diff' : null,snapshot.worktreeDiff ? 'git -C <checkout> apply worktree.diff' : null,@@ -161,13 +234,14 @@ async function writeArchive(dir, { repoPath, tree, branch, defaultBranch, releassymlinks.length ? 'recreate manifest.captured.symlinks with ln -s' : null,].filter(Boolean),});- return { dir, fingerprint: snapshot.fingerprint };+ await chmod(join(dir, 'manifest.json'), 0o600);+ return { dir, fingerprint: snapshot.fingerprint, administrationFingerprint: administration.fingerprint };}const isAncestor = (repoPath, sha, ref) => execGit(['merge-base', '--is-ancestor', sha, ref], repoPath, { ignoreExitCode: true }).then(r => r.exitCode === 0, () => false);-async function ownerReason({ repoPath, tree, branch, readAgents }) {+async function ownerReason({ repoPath, tree, branch, readAgents, reviewed = false }) {const agents = await readAgents().catch(() => null);if (!Array.isArray(agents)) return 'claim-ownership-unreadable';const claim = claimCheckoutOwnerReason({ branchName: branch || 'HEAD', holderPath: tree.path, sourceWorkspace: repoPath, agents });@@ -179,7 +253,7 @@ async function ownerReason({ repoPath, tree, branch, readAgents }) {// release above, and a NEW lock is caught by the registration recheck.const live = resolveLiveOwnerReason({ branch, path: tree.path, locked: false, activeAgentIds: buildActiveOwnerIds(getActiveAgentIds(), agents) });if (live) return live;- if (!branch) return null;+ if (!branch || reviewed) return null;const { readBranchCompletionHold } = await import('./branchCompletionPolicy.js');return readBranchCompletionHold({ repoPath, branch, retirement: true }).catch(() => 'pr-completion-policy-unavailable');}@@ -208,7 +282,8 @@ async function matchRelease(repoPath, release) {* @param {{ cosDir?: string, readAgents?: () => Promise<object[]|null> }} [opts]* @returns {Promise<{ ok: true, archiveDir: string, branchDeleted: boolean, branchRetainedReason?: string } | { ok: false, reason: string, detail?: string, archiveDir?: string }>}*/-async function retireHeldCheckout({ repoPath, release }, { cosDir = PATHS.cos, readAgents = readClaimOwnershipAgents } = {}) {+async function retireHeldCheckout({ repoPath, release, review }, opts = {}) {+ const { cosDir = PATHS.cos, readAgents = readClaimOwnershipAgents } = opts;const branch = release.branch ?? null;if (branch && PROTECTED_BRANCHES.includes(branch)) return { ok: false, reason: 'protected-branch' };const defaultBranch = await getDefaultBranch(repoPath, { allowRemote: false, strict: true }).catch(() => null);@@ -216,17 +291,21 @@ async function retireHeldCheckout({ repoPath, release }, { cosDir = PATHS.cos, rif (branch === defaultBranch) return { ok: false, reason: 'protected-branch' };return withClaimOwnershipLock(async () => {+ if (opts.inventoryCurrent && !await opts.inventoryCurrent()) return { ok: false, reason: 'release-not-in-inventory' };const first = await matchRelease(repoPath, release);if (!first.tree) return { ok: false, reason: first.reason };const { tree } = first;const merged = branch? await hasBranchMergeEvidence(repoPath, branch, defaultBranch).catch(() => false): await isAncestor(repoPath, tree.head, defaultBranch);- if (!merged) return { ok: false, reason: 'not-merged-on-recheck' };- const owner = await ownerReason({ repoPath, tree, branch, readAgents });+ if (!merged && !review) return { ok: false, reason: 'not-merged-on-recheck' };+ const reviewed = review ? await reviewCurrentCheckout({ repoPath, release, prUrl: review.prUrl }, opts) : null;+ if (reviewed && (!reviewed.ok || reviewed.review.digest !== review.digest)) return { ok: false, reason: reviewed.reason || 'retirement-review-changed' };+ if (reviewed?.review.comparison.disposition === 'review-supersession' && review.acceptSuperseded !== true) return { ok: false, reason: 'retirement-supersession-not-accepted' };+ const owner = await ownerReason({ repoPath, tree, branch, readAgents, reviewed: Boolean(review) });if (owner) return { ok: false, reason: owner };- const archive = await archiveCheckout({ repoPath, tree, branch, defaultBranch, release, cosDir })+ const archive = await archiveCheckout({ repoPath, tree, branch, defaultBranch, release, cosDir, review: reviewed?.review }).catch(error => ({ error }));if (archive.error) {console.error(`❌ held-checkout recovery: archive failed for ${tree.path}, checkout kept: ${archive.error.message}`);@@ -242,7 +321,13 @@ async function retireHeldCheckout({ repoPath, release }, { cosDir = PATHS.cos, r}const verifyRemoval = async (holder) => {if (!holder || holder.head !== tree.head || shortBranch(holder.branch) !== branch) return 'worktree-holder-changed';- const reason = await ownerReason({ repoPath, tree, branch, readAgents });+ if (opts.inventoryCurrent && !await opts.inventoryCurrent()) return 'release-not-in-inventory';+ const reason = await ownerReason({ repoPath, tree, branch, readAgents, reviewed: Boolean(review) });+ if (review) {+ const fresh = await reviewCurrentCheckout({ repoPath, release, prUrl: review.prUrl, unlocked: release.locked }, opts);+ if (!fresh.ok || fresh.review.digest !== review.digest) return fresh.reason || 'retirement-review-changed';+ }+ if ((await snapshotAdministration(tree.path)).fingerprint !== archive.administrationFingerprint) return 'checkout-administration-changed';if (reason) return reason;const current = await snapshotContent(tree.path).catch(() => null);return current?.fingerprint === archive.fingerprint ? null : 'checkout-content-changed';@@ -262,11 +347,21 @@ async function retireHeldCheckout({ repoPath, release }, { cosDir = PATHS.cos, rconsole.log(`🧹 held-checkout recovery: retired ${tree.path} (archive: ${archive.dir})`);if (!branch) return { ok: true, archiveDir: archive.dir, branchDeleted: false };- const hold = await ownerReason({ repoPath, tree: { ...tree, path: null }, branch, readAgents });+ const hold = await ownerReason({ repoPath, tree: { ...tree, path: null }, branch, readAgents, reviewed: Boolean(review) });if (hold) return { ok: true, archiveDir: archive.dir, branchDeleted: false, branchRetainedReason: hold };- const deleted = await deleteBranch(repoPath, branch, { local: true }).catch(err => ({ error: err.message }));- const failure = deleted?.error || (deleted?.results?.local?.startsWith?.('failed') ? deleted.results.local : null);- if (failure) return { ok: true, archiveDir: archive.dir, branchDeleted: false, branchRetainedReason: `delete-failed: ${failure}` };+ if (review) {+ const { readRetirementForgeEvidence } = await import('./heldCheckoutReview.js');+ const policy = await retirementPolicy(repoPath, branch, opts);+ const forge = await (opts.readForge || readRetirementForgeEvidence)(repoPath, branch, review.prUrl, { forgeAccount: opts.forgeAccount }).catch(() => null);+ if (JSON.stringify(policy) !== JSON.stringify(reviewed.review.policy) || JSON.stringify(forge) !== JSON.stringify(reviewed.review.forge)) {+ return { ok: true, archiveDir: archive.dir, branchDeleted: false, branchRetainedReason: 'retirement-evidence-changed' };+ }+ }+ // 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 execGit(['update-ref', '-d', `refs/heads/${branch}`, release.head], repoPath, { ignoreExitCode: true }).catch(() => null);+ if (!deleted || deleted.exitCode !== 0) return { ok: true, archiveDir: archive.dir, branchDeleted: false, branchRetainedReason: 'branch-ref-changed-or-delete-failed' };return { ok: true, archiveDir: archive.dir, branchDeleted: true };});}@@ -279,13 +374,14 @@ const sameRelease = (entry, release) => entry.path === release.path && entry.hea* The Schedule view's entry point: the release must name a row of the app's* last persisted inventory exactly, so it binds to evidence the operator saw.*/-export async function retireInventoriedCheckout({ appId, release }, opts) {+export async function retireInventoriedCheckout({ appId, release, review }, opts) {const [{ getAppById }, taskSchedule] = await Promise.all([import('./apps.js'), import('./taskSchedule.js')]);const app = await getAppById(appId);if (!app?.repoPath) return { ok: false, reason: 'app-not-found' };const outcome = await taskSchedule.getBranchReconcileOutcome(appId);if (!outcome?.remaining?.some?.(entry => sameRelease(entry, release))) return { ok: false, reason: 'release-not-in-inventory' };- const result = await retireHeldCheckout({ repoPath: app.repoPath, release }, opts);+ const inventoryCurrent = async () => (await taskSchedule.getBranchReconcileOutcome(appId))?.remaining?.some(entry => sameRelease(entry, release)) === true;+ const result = await retireHeldCheckout({ repoPath: app.repoPath, release, review }, { ...opts, inventoryCurrent, forgeAccount: app.forgeAccount ?? null });if (result.ok) {await taskSchedule.recordHeldCheckoutRetirement(appId, {path: release.path, branch: release.branch ?? null, head: release.head, branchDeleted: result.branchDeleted, archiveDir: result.archiveDir,diff --git a/server/services/heldCheckoutRecovery.test.js b/server/services/heldCheckoutRecovery.test.jsindex 617e304d51..b74dc259f3 100644--- a/server/services/heldCheckoutRecovery.test.js+++ b/server/services/heldCheckoutRecovery.test.js@@ -17,7 +17,7 @@ const injected = vi.hoisted(() => ({ policies: [], schedule: null, app: null }))vi.mock('./branchCompletionPolicy.js', async (importOriginal) => {const actual = await importOriginal();- return { ...actual, readBranchCompletionHold: input => actual.readBranchCompletionHold(input, {+ return { ...actual, readBranchCompletionPolicies: async () => injected.policies, readBranchCompletionHold: input => actual.readBranchCompletionHold(input, {readPolicies: async () => injected.policies,}) };});@@ -28,7 +28,7 @@ vi.mock('./taskScheduleStore.js', async (importOriginal) => ({}));vi.mock('./apps.js', () => ({ getAppById: async (id) => (injected.app?.id === id ? injected.app : null) }));-const { retireInventoriedCheckout, heldCheckoutArchiveRoot } = await import('./heldCheckoutRecovery.js');+const { retireInventoriedCheckout, prepareInventoriedCheckoutRetirement, heldCheckoutArchiveRoot } = await import('./heldCheckoutRecovery.js');const { recordBranchReconcileOutcome, getBranchReconcileOutcome } = await import('./taskSchedule.js');describe.skipIf(SKIP_HEAVY_INTEGRATION)('held checkout recovery (real git)', () => {@@ -225,4 +225,141 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('held checkout recovery (real git)', ()expect(existsSync(handoff.path)).toBe(true);expect(await archives()).toEqual([]);});+ async function reviewedCheckout(name, { superseded = false, gitlink = false, normalMerge = false, featurePath = 'feature.txt', multipleCommits = false } = {}) {+ let firstCommit;+ let changeBase;+ const { path, release } = await heldCheckout(name, { branch: `feature/${name}`, beforeLock: async tree => {+ await writeFile(join(tree, featurePath), 'original feature\n');+ await execGit(['--literal-pathspecs', 'add', featurePath], tree);+ if (gitlink) {+ const commit = (await execGit(['rev-parse', 'HEAD'], tree)).stdout.trim();+ await execGit(['update-index', '--add', '--cacheinfo', `160000,${commit},vendor`], tree);+ await mkdir(join(tree, 'vendor'));+ }+ changeBase = (await execGit(['rev-parse', 'HEAD'], tree)).stdout.trim();+ await execGit(['commit', '-m', 'original feature'], tree);+ firstCommit = (await execGit(['rev-parse', 'HEAD'], tree)).stdout.trim();+ if (multipleCommits) {+ await writeFile(join(tree, 'second.txt'), 'second original change\n');+ await execGit(['add', 'second.txt'], tree);+ await execGit(['commit', '-m', 'second original change'], tree);+ }+ if (normalMerge) await execGit(['merge', '--ff-only', `feature/${name}`], repo);+ else {+ await execGit(['merge', '--squash', `feature/${name}`], repo);+ await execGit(['commit', '-m', 'shipped feature'], repo);+ }+ if (superseded) {+ await writeFile(join(repo, featurePath), 'strengthened replacement\n');+ await execGit(['commit', '-am', 'strengthen implementation'], repo);+ }+ } });+ const main = (await execGit(['rev-parse', 'main'], repo)).stdout.trim();+ const admin = (await execGit(['rev-parse', '--absolute-git-dir'], path)).stdout.trim();+ await writeFile(join(admin, 'portos-review-status'), 'private synthetic review marker');+ injected.policies = [{ id: 'agent-legacy', status: 'completed', result: { success: true },+ metadata: { workspacePath: repo, claimBranches: [release.branch], prCompletionPolicy: 'review-then-merge' } }];+ await recordBranchReconcileOutcome('app-1', { status: 'incomplete', remaining: [{ ...release, reason: 'pr-completion-review-required' }] });+ const forge = { changedPaths: [featurePath, ...(gitlink ? ['vendor'] : []), ...(multipleCommits ? ['second.txt'] : [])], changeBase, firstCommit, repository: 'github.com/example/repo', prUrl: 'https://github.com/example/repo/pull/42', prHead: release.head,+ mergeCommit: main, defaultBranch: 'main', defaultHead: main, remoteHead: null };+ const opts = { cosDir, readAgents: noOwners, readForge: async () => forge };+ const prepare = () => prepareInventoriedCheckoutRetirement({ appId: 'app-1', release, prUrl: forge.prUrl }, opts);+ const confirm = (review, more = {}) => retireInventoriedCheckout({ appId: 'app-1', release,+ review: { prUrl: forge.prUrl, digest: review.digest, acceptSuperseded: superseded } }, { ...opts, ...more });+ return { path, release, admin, opts, forge, prepare, confirm };+ }++ it('reviews original changes after an ancestral merged tip is later changed', 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');+ });++ it('compares pathspec-magic filenames literally', async () => {+ const c = await reviewedCheckout('literal', { featurePath: ':(exclude)*', superseded: true });+ const prepared = await c.prepare();+ expect(prepared.ok).toBe(true);+ expect(prepared.review.comparison.disposition).toBe('review-supersession');+ expect(prepared.review.comparison.difference).toContain('+strengthened replacement');+ });++ it('retains all original changes in a multi-commit squash review', async () => {+ const c = await reviewedCheckout('multi', { multipleCommits: true });+ const prepared = await c.prepare();+ expect(prepared.ok).toBe(true);+ expect(prepared.review.comparison.localPatch).toContain('+original feature');+ expect(prepared.review.comparison.localPatch).toContain('+second original change');+ expect(prepared.review.comparison.disposition).toBe('integrated');+ });++ it.each([false, true])('requires a new scoped review for completed legacy owners, superseded=%s', async superseded => {+ const c = await reviewedCheckout('legacy', { superseded, gitlink: true });+ if (!superseded) expect(await retireInventoriedCheckout({ appId: 'app-1', release: c.release }, c.opts))+ .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');+ if (superseded) 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' });+ const result = await c.confirm(prepared.review);+ expect(result).toMatchObject({ ok: true, branchDeleted: true });+ const manifest = JSON.parse(await readFile(join(result.archiveDir, 'manifest.json'), 'utf8'));+ expect(manifest.review.digest).toBe(prepared.review.digest);+ expect(manifest.captured.gitlinks).toMatchObject([{ path: 'vendor', state: 'empty' }]);+ expect(await readFile(join(result.archiveDir, 'administration/gitdir/portos-review-status'), 'utf8')).toBe('private synthetic review marker');+ expect(await readFile(join(result.archiveDir, 'files/ignored.txt'), 'utf8')).toBe('ignored work\n');+ await execGit(['fetch', join(result.archiveDir, 'commits.bundle'), 'HEAD:refs/heads/restored-legacy'], repo);+ expect((await execGit(['rev-parse', 'restored-legacy'], repo)).stdout.trim()).toBe(c.release.head);+ expect(injected.policies[0].metadata.branchCompletionPolicy).toBeUndefined();+ });++ 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();+ expect(prepared.ok).toBe(true);+ if (change === 'content') await writeFile(join(c.path, 'ignored.txt'), 'new evidence');+ if (change === 'index') { await writeFile(join(c.path, 'staged.txt'), 'new index'); await execGit(['add', 'staged.txt'], c.path); }+ if (change === 'administration') await writeFile(join(c.admin, 'portos-review-status'), 'new review');+ if (change === 'default') {+ await writeFile(join(repo, 'later.txt'), 'later default');+ await execGit(['add', 'later.txt'], repo); await execGit(['commit', '-m', 'later default'], repo);+ c.forge.defaultHead = (await execGit(['rev-parse', 'HEAD'], repo)).stdout.trim();+ }+ if (change === 'pr-head') c.forge.prHead = c.forge.defaultHead;+ if (change === 'unreadable-policy') injected.policies = null;+ if (change === 'forge') c.forge.remoteHead = c.release.head;+ if (change === 'policy') injected.policies[0].metadata.prCompletionPolicy = 'leave-open';+ if (change === 'submodule') await writeFile(join(c.path, 'vendor', 'unique.txt'), 'submodule work');+ if (change === 'inventory') injected.schedule.executions = {};+ const result = await c.confirm(prepared.review);+ expect(result.ok).toBe(false);+ expect(await registered(c.release.path)).toBe(true);+ expect(await lockText(c.release.path)).toBe(c.release.lockReason);+ expect(await archives()).toEqual([]);+ });++ it.each(['running', 'paused'])('refuses a %s owner that arrives after preparation', async status => {+ const c = await reviewedCheckout('owner-review');+ const prepared = await c.prepare();+ const result = await c.confirm(prepared.review, { readAgents: async () => [{ id: 'agent-live', status,+ metadata: { workspacePath: repo, claimBranches: [c.release.branch] } }] });+ expect(result).toMatchObject({ ok: false, reason: 'claim-owner-active' });+ expect(await registered(c.release.path)).toBe(true);+ });++ it('preserves archive and checkout when fresh forge evidence changes after archiving', async () => {+ const c = await reviewedCheckout('late-forge');+ const prepared = await c.prepare();+ let reads = 0;+ const result = await c.confirm(prepared.review, { readForge: async () => ({ ...c.forge, remoteHead: ++reads === 1 ? null : c.release.head }) });+ expect(result).toMatchObject({ ok: false, reason: 'retirement-review-changed', archiveDir: expect.any(String) });+ expect(await readFile(join(result.archiveDir, 'files/ignored.txt'), 'utf8')).toBe('ignored work\n');+ expect(await registered(c.release.path)).toBe(true);+ expect(await lockText(c.release.path)).toBe(c.release.lockReason);+ });+});diff --git a/server/services/heldCheckoutReview.js b/server/services/heldCheckoutReview.jsnew file mode 100644index 0000000000..66583dea32--- /dev/null+++ b/server/services/heldCheckoutReview.js@@ -0,0 +1,101 @@+/** Fresh forge facts for an operator's checkout-retirement review. No fetch,+ * policy write or saved grant: missing local objects require a separate fetch.+ */+import { createHash } from 'node:crypto';+import { execGit } from '../lib/execGit.js';+import { getOriginInfo } from '../lib/gitRemote.js';+import { parsePullRequestUrl } from '../lib/gitForge.js';++const oid = value => typeof value === 'string' && /^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(value);+const safePath = value => typeof value === 'string' && value.length > 0 && !value.includes('\0') && !value.startsWith('/') && !value.split('/').some(part => part === '..' || part === '.');+const git = (args, cwd) => execGit(args, cwd, { maxBuffer: 4 * 1024 * 1024 }).then(r => r.stdout);++export async function readRetirementForgeEvidence(repoPath, branch, prUrl, { forgeAccount = null } = {}) {+ const origin = await getOriginInfo(repoPath);+ const parsed = parsePullRequestUrl(prUrl);+ if (!origin || !parsed || parsed.host !== origin.host || `${parsed.owner}/${parsed.repo}` !== origin.fullName) {+ throw new Error('retirement-pr-repository-mismatch');+ }+ const [{ execGh }, { resolveForgeExecOptions }] = await Promise.all([import('./github.js'), import('./forgeExecOptions.js')]);+ const options = await resolveForgeExecOptions(repoPath, { forgeAccount });+ const read = args => execGh(args, undefined, options).then(JSON.parse).catch(() => { throw new Error('retirement-forge-unavailable'); });+ const api = path => read(['api', '--hostname', origin.host, path]);+ const remote = await read(['pr', 'view', prUrl, '--json', 'url,state,headRefName,headRefOid,isCrossRepository,mergeCommit,baseRefName']);+ const repository = await api(`repos/${origin.fullName}`);+ const defaultBranch = repository.default_branch;+ if (remote.url !== prUrl || remote.state !== 'MERGED' || remote.headRefName !== branch+ || remote.isCrossRepository !== false || remote.baseRefName !== defaultBranch || !oid(remote.headRefOid) || !oid(remote.mergeCommit?.oid)) {+ throw new Error('retirement-pr-not-matching-merged');+ }+ // A current-main merge base loses the original scope after a normal merge.+ // Use complete original PR metadata, and refuse API caps or ambiguous roots.+ const pullPath = `repos/${origin.fullName}/pulls/${parsed.number}`;+ const detail = await api(pullPath);+ if (detail.head?.sha !== remote.headRefOid || detail.base?.ref !== defaultBranch || detail.merged !== true+ || !Number.isInteger(detail.changed_files) || detail.changed_files < 1 || detail.changed_files > 3000+ || !Number.isInteger(detail.commits) || detail.commits < 1 || detail.commits > 250) {+ throw new Error('retirement-original-scope-unavailable');+ }+ const pages = async suffix => {+ const value = await read(['api', '--hostname', origin.host, '--paginate', '--slurp', `${pullPath}/${suffix}?per_page=100`]);+ if (!Array.isArray(value) || !value.every(Array.isArray)) throw new Error('retirement-original-scope-unavailable');+ return value.flat();+ };+ const files = await pages('files');+ const commits = await pages('commits');+ if (files.length !== detail.changed_files || commits.length !== detail.commits+ || new Set(files.map(file => file.filename)).size !== files.length+ || new Set(commits.map(commit => commit.sha)).size !== commits.length+ || !commits.every(commit => oid(commit.sha)) || commits.at(-1)?.sha !== remote.headRefOid+ || commits[0]?.parents?.length !== 1 || !oid(commits[0].parents[0].sha)+ || files.some(file => !safePath(file.filename) || (file.status === 'renamed' && !safePath(file.previous_filename)))) {+ throw new Error('retirement-original-scope-unavailable');+ }+ const changedPaths = [...new Set(files.flatMap(file => file.status === 'renamed' ? [file.filename, file.previous_filename] : [file.filename]))].sort();+ const changeBase = commits[0].parents[0].sha;+ const firstCommit = commits[0].sha;+ const target = await api(`repos/${origin.fullName}/git/ref/heads/${encodeURIComponent(defaultBranch)}`);+ if (!oid(target.object?.sha)) throw new Error('retirement-default-unreadable');+ // ls-remote returns an empty successful result only for actual ref absence.+ const remoteHead = (await git(['ls-remote', '--heads', 'origin', `refs/heads/${branch}`], repoPath)+ .catch(() => { throw new Error('retirement-remote-ref-unreadable'); })).trim();+ if (remoteHead && remoteHead !== `${remote.headRefOid}\trefs/heads/${branch}`) throw new Error('retirement-remote-head-changed');+ return { repository: `${origin.host}/${origin.fullName}`, prUrl, prHead: remote.headRefOid,+ mergeCommit: remote.mergeCommit.oid, changedPaths, changeBase, firstCommit, defaultBranch, defaultHead: target.object.sha, remoteHead: remoteHead || null };+}++/** Returned differences are review material, not executable instructions or an+ * automated supersession verdict. Every byte and identity participates in digest.+ */+export async function buildCheckoutRetirementReview({ repoPath, release, prUrl, contentFingerprint, administrationFingerprint, policy }, {+ readForge = readRetirementForgeEvidence, forgeAccount = null,+} = {}) {+ const forge = await readForge(repoPath, release.branch, prUrl, { forgeAccount });+ if (!forge || !oid(forge.prHead) || !oid(forge.mergeCommit) || !oid(forge.defaultHead)) throw new Error('retirement-forge-unreadable');+ if (release.branch === forge.defaultBranch) throw new Error('protected-branch');+ if (!oid(forge.changeBase) || !oid(forge.firstCommit) || !Array.isArray(forge.changedPaths)+ || !forge.changedPaths.length || !forge.changedPaths.every(safePath)) throw new Error('retirement-original-scope-unavailable');+ for (const head of [forge.prHead, forge.mergeCommit, forge.defaultHead, forge.changeBase, forge.firstCommit]) {+ await git(['cat-file', '-e', `${head}^{commit}`], repoPath).catch(() => { throw new Error('retirement-local-objects-missing'); });+ }+ await git(['merge-base', '--is-ancestor', forge.mergeCommit, forge.defaultHead], repoPath)+ .catch(() => { throw new Error('retirement-merge-not-in-default'); });+ const parent = (await git(['rev-list', '--parents', '-n', '1', forge.firstCommit], repoPath)).trim().split(/\s+/);+ if (parent.length !== 2 || parent[1] !== forge.changeBase) throw new Error('retirement-original-scope-unavailable');+ await git(['merge-base', '--is-ancestor', forge.firstCommit, forge.prHead], repoPath)+ .catch(() => { throw new Error('retirement-original-scope-unavailable'); });+ const base = (await git(['merge-base', release.head, forge.changeBase], repoPath)).trim();+ if (base === release.head) throw new Error('retirement-original-scope-unavailable');+ const localPaths = (await git(['diff', '--name-only', '-z', base, release.head], repoPath)).split('\0').filter(Boolean);+ const paths = [...new Set([...forge.changedPaths, ...localPaths])].sort();+ const localPatch = await git(['diff', '--binary', '--no-ext-diff', '--no-textconv', base, release.head], repoPath);+ 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 === '';+ const evidence = { repoPath, release, forge, contentFingerprint, administrationFingerprint, policy,+ comparison: { base, paths, localPatch, difference, disposition: mechanicallyEquivalent ? 'integrated' : 'review-supersession' } };+ return { digest: createHash('sha256').update(JSON.stringify(evidence)).digest('hex'), ...evidence };+}diff --git a/server/services/heldCheckoutReview.test.js b/server/services/heldCheckoutReview.test.jsnew file mode 100644index 0000000000..a090170261--- /dev/null+++ b/server/services/heldCheckoutReview.test.js@@ -0,0 +1,80 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++const mock = vi.hoisted(() => ({ gh: vi.fn(), git: vi.fn(), options: vi.fn() }));+vi.mock('./github.js', () => ({ execGh: mock.gh }));+vi.mock('./forgeExecOptions.js', () => ({ resolveForgeExecOptions: mock.options }));+vi.mock('../lib/execGit.js', () => ({ execGit: mock.git }));+vi.mock('../lib/gitRemote.js', () => ({ getOriginInfo: async () => ({ host: 'github.com', fullName: 'example/repo' }) }));+import { readRetirementForgeEvidence } from './heldCheckoutReview.js';++describe('retirement forge verification', () => {+ const prUrl = 'https://github.com/example/repo/pull/42';+ let pr;+ let detail;+ let files;+ let commits;+ beforeEach(() => {+ vi.clearAllMocks();+ pr = { url: prUrl, state: 'MERGED', headRefName: 'claim/42', headRefOid: 'a'.repeat(40),+ mergeCommit: { oid: 'b'.repeat(40) }, isCrossRepository: false, baseRefName: 'main' };+ detail = { merged: true, head: { sha: 'a'.repeat(40) }, base: { ref: 'main' }, changed_files: 1, commits: 1 };+ files = [[{ filename: 'feature.txt', status: 'modified' }]];+ commits = [[{ sha: 'a'.repeat(40), parents: [{ sha: 'd'.repeat(40) }] }]];+ mock.options.mockResolvedValue({ cwd: '/synthetic/repo', env: {} });+ mock.git.mockResolvedValue({ stdout: '', exitCode: 0 });+ mock.gh.mockImplementation(async args => JSON.stringify(args[0] === 'pr' ? pr+ : args.at(-1).includes('/files?') ? files : args.at(-1).includes('/commits?') ? commits+ : args.at(-1).includes('/pulls/') ? detail+ : args.at(-1).includes('/git/ref/') ? { object: { sha: 'c'.repeat(40) } } : { default_branch: 'main' }));+ });++ it('binds the actual repository/default/PR refs and uses the managed app account', async () => {+ expect(await readRetirementForgeEvidence('/synthetic/repo', 'claim/42', prUrl, { forgeAccount: 'configured-owner' }))+ .toEqual({ repository: 'github.com/example/repo', prUrl, prHead: 'a'.repeat(40), mergeCommit: 'b'.repeat(40),+ changedPaths: ['feature.txt'], firstCommit: 'a'.repeat(40), changeBase: 'd'.repeat(40),+ defaultBranch: 'main', defaultHead: 'c'.repeat(40), remoteHead: null });+ expect(mock.options).toHaveBeenCalledWith('/synthetic/repo', { forgeAccount: 'configured-owner' });+ });++ it.each([+ { state: 'OPEN' }, { state: 'CLOSED' }, { headRefName: 'another-claim' },+ { isCrossRepository: true }, { baseRefName: 'release' }, { mergeCommit: null },+ ])('refuses a nonmatching merged PR: %j', async change => {+ Object.assign(pr, change);+ await expect(readRetirementForgeEvidence('/synthetic/repo', 'claim/42', prUrl)).rejects.toThrow('retirement-pr-not-matching-merged');+ });++ it('includes renamed previous paths and complete paginated file scope literally', async () => {+ detail.changed_files = 2;+ files = [[{ filename: ':(exclude)*', previous_filename: 'old.txt', status: 'renamed' }], [{ filename: 'new.txt', status: 'added' }]];+ const result = await readRetirementForgeEvidence('/synthetic/repo', 'claim/42', prUrl);+ expect(result.changedPaths).toEqual([':(exclude)*', 'new.txt', 'old.txt']);+ expect(mock.gh).toHaveBeenCalledWith(expect.arrayContaining(['--paginate', '--slurp']), undefined, expect.any(Object));+ });++ it.each(['file-count', 'commit-count', 'duplicate', 'missing-previous', 'ambiguous-base', 'wrong-tip', 'cap', 'bad-path', 'unpaginated'])('refuses incomplete or ambiguous original scope: %s', async change => {+ if (change === 'file-count') detail.changed_files = 2;+ if (change === 'commit-count') detail.commits = 2;+ if (change === 'duplicate') { detail.changed_files = 2; files[0].push(files[0][0]); }+ if (change === 'missing-previous') files[0][0].status = 'renamed';+ if (change === 'ambiguous-base') commits[0][0].parents.push({ sha: 'e'.repeat(40) });+ if (change === 'wrong-tip') commits[0][0].sha = 'e'.repeat(40);+ if (change === 'cap') detail.commits = 251;+ if (change === 'bad-path') files[0][0].filename = '../escape';+ if (change === 'unpaginated') files = files[0];+ await expect(readRetirementForgeEvidence('/synthetic/repo', 'claim/42', prUrl)).rejects.toThrow('retirement-original-scope-unavailable');+ });++ it('refuses a different repository before sending a forge request', async () => {+ await expect(readRetirementForgeEvidence('/synthetic/repo', 'claim/42', 'https://github.com/other/repo/pull/42'))+ .rejects.toThrow('retirement-pr-repository-mismatch');+ expect(mock.gh).not.toHaveBeenCalled();+ });++ it('distinguishes failed remote lookup and advanced remote head from absence', async () => {+ mock.git.mockRejectedValueOnce(new Error('synthetic unavailable'));+ await expect(readRetirementForgeEvidence('/synthetic/repo', 'claim/42', prUrl)).rejects.toThrow('retirement-remote-ref-unreadable');+ mock.git.mockResolvedValueOnce({ stdout: `${'d'.repeat(40)}\trefs/heads/claim/42\n`, exitCode: 0 });+ await expect(readRetirementForgeEvidence('/synthetic/repo', 'claim/42', prUrl)).rejects.toThrow('retirement-remote-head-changed');+ });+});