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(cos): retain durable PR coordination through merge and cleanup
[._.]/ Adam Eivy893d4885f09e
diff --git a/client/src/components/apps/EditAppDrawer.jsx b/client/src/components/apps/EditAppDrawer.jsxindex 2e83d14db5..d827643a1d 100644--- a/client/src/components/apps/EditAppDrawer.jsx+++ b/client/src/components/apps/EditAppDrawer.jsx@@ -714,6 +714,7 @@ export default function EditAppDrawer({ app, onClose, onSave }) {</select><p className="mt-1 text-xs text-gray-500">{prCompletionOption(formData.defaultPrCompletion)?.description}+ {' Automatic merging is managed by PortOS, not GitHub native auto-merge. Per-run choices override this default.'}</p></div><label htmlFor="edit-app-verify-repo-state" className="flex items-center gap-2 cursor-pointer">diff --git a/client/src/components/apps/EditAppDrawer.test.jsx b/client/src/components/apps/EditAppDrawer.test.jsxindex 2402be2beb..dd38ebc025 100644--- a/client/src/components/apps/EditAppDrawer.test.jsx+++ b/client/src/components/apps/EditAppDrawer.test.jsx@@ -211,6 +211,16 @@ describe('EditAppDrawer work tracker selector', () => {await waitFor(() => expect(api.updateApp).toHaveBeenCalled());expect(api.updateApp.mock.calls[0][1].defaultPrCompletion).toBe('leave-open');});+ it('preserves an app draft default when saving another field', async () => {+ renderDrawer({ app: { ...APP, defaultUseWorktree: true, defaultOpenPR: true, defaultPrCompletion: 'draft' } });+ await openTab('Workflow');+ expect(await screen.findByLabelText('Default PR completion')).toHaveValue('draft');+ expect(screen.getByText(/Automatic merging is managed by PortOS, not GitHub native auto-merge/)).toBeInTheDocument();+ fireEvent.click(screen.getByRole('button', { name: 'Save Changes' }));+ await waitFor(() => expect(api.updateApp).toHaveBeenCalled());+ expect(api.updateApp.mock.calls[0][1].defaultPrCompletion).toBe('draft');+ });+it('defaults the repo-state audit ON for an app that has never set it, and saves an opt-out', async () => {// Unset means ON server-side (repoStateVerificationEnabled), so an app record// with no such key must render checked — otherwise the first save of andiff --git a/client/src/components/apps/SlashDoRunDrawer.jsx b/client/src/components/apps/SlashDoRunDrawer.jsxindex d0bf24b9fd..459974ab76 100644--- a/client/src/components/apps/SlashDoRunDrawer.jsx+++ b/client/src/components/apps/SlashDoRunDrawer.jsx@@ -22,9 +22,9 @@ import * as api from '../../services/api';* bare button used to. Reviewer fields are sent ONLY when the user edits them, so* an untouched drawer still resolves the app's configured claim-work reviewers* server-side rather than pinning whatever this form happened to display.- * `prCompletion` is the exception: it is always sent for `/do:next` (seeded- * from the claim-work default when untouched), because the prompt's completion- * policy needs an explicit value.+ * Untouched completion settings also remain inherited: a slow preview must not+ * turn the displayed fallback into an override of an app's draft/leave-open+ * policy. The server pins the resolved policy when it queues the task.** Mount only while open (the parent conditionally renders it): the provider fetch* runs on mount unless the overview supplies its shared agent picker. Task@@ -104,7 +104,7 @@ function SlashDoRunDrawerBody({ open, command, label, appId, appName, onClose, o// being unrendered: only the `next` branch of POST /tasks/slashdo reads these,// so sending them for another command would be a silent no-op....(isNext ? {- prCompletion,+ ...(prCompletionTouched ? { prCompletion } : {}),...(prCompletion === 'review-then-merge' && review ? {reviewers: review.reviewers,usernames: review.usernames,diff --git a/client/src/components/apps/SlashDoRunDrawer.test.jsx b/client/src/components/apps/SlashDoRunDrawer.test.jsxindex ff1afd019e..5c3e4878b1 100644--- a/client/src/components/apps/SlashDoRunDrawer.test.jsx+++ b/client/src/components/apps/SlashDoRunDrawer.test.jsx@@ -285,6 +285,14 @@ describe('SlashDoRunDrawer', () => {expect(settings.reviewers).toBeUndefined();});+ it('inherits server policy when queued before the app completion preview resolves', async () => {+ api.getAppClaimReviewers.mockReturnValue(new Promise(() => {}));+ renderDrawer();+ await userEvent.click(screen.getByRole('button', { name: /Queue \/do:next/ }));+ await waitFor(() => expect(api.createSlashdoTask).toHaveBeenCalled());+ expect(api.createSlashdoTask.mock.calls.at(-1)[2]).not.toHaveProperty('prCompletion');+ });+it('seeds prCompletion from claimReviewers when available', async () => {api.getAppClaimReviewers.mockResolvedValue({source: 'task-override', prCompletion: 'merge-on-green', reviewers: [], usernames: [], optionalReviewers: [],diff --git a/client/src/components/apps/tabs/IssuesTab.jsx b/client/src/components/apps/tabs/IssuesTab.jsxindex 092b96932a..bb565ec4c8 100644--- a/client/src/components/apps/tabs/IssuesTab.jsx+++ b/client/src/components/apps/tabs/IssuesTab.jsx@@ -493,7 +493,7 @@ export default function IssuesTab({ appId, appName }) {},...picker.pin,...(action === 'claim' ? {- prCompletion,+ ...(prCompletionTouched ? { prCompletion } : {}),...(prCompletion === 'review-then-merge' ? reviewOverrides : {}),} : {}),...(trimmedOverrideContext ? { overrideContext: trimmedOverrideContext } : {}),diff --git a/client/src/components/apps/tabs/IssuesTab.test.jsx b/client/src/components/apps/tabs/IssuesTab.test.jsxindex 4618cf2474..f828aa48f1 100644--- a/client/src/components/apps/tabs/IssuesTab.test.jsx+++ b/client/src/components/apps/tabs/IssuesTab.test.jsx@@ -196,6 +196,14 @@ describe('IssuesTab', () => {await waitFor(() => expect(screen.queryByText(/Repro: open the editor/)).not.toBeInTheDocument());});+ it('does not override an unresolved app completion policy when claiming', async () => {+ api.getAppClaimReviewers.mockReturnValue(new Promise(() => {}));+ await renderTab();+ fireEvent.click(await screen.findByRole('button', { name: /Claim/ }));+ await waitFor(() => expect(api.createSlashdoTask).toHaveBeenCalled());+ expect(api.createSlashdoTask.mock.calls.at(-1)[2]).not.toHaveProperty('prCompletion');+ });+it('claims an issue with its prefetched content pinned to the /do:next task', async () => {await renderTab();@@ -209,8 +217,7 @@ describe('IssuesTab', () => {title: 'Crash on save',body: 'Repro: open the editor and hit save.',url: 'https://github.com/acme/widget/issues/42'- },- prCompletion: 'review-then-merge'+ }}, { silent: true }));expect(await screen.findByRole('link', { name: /Queued/ })).toBeInTheDocument();@@ -390,8 +397,7 @@ describe('IssuesTab', () => {},provider: 'claude',model: 'claude-opus-5',- effort: undefined,- prCompletion: 'review-then-merge'+ effort: undefined},{ silent: true }));diff --git a/client/src/components/cos/constants.js b/client/src/components/cos/constants.jsindex 30a899c71e..0f5e57ea5a 100644--- a/client/src/components/cos/constants.js+++ b/client/src/components/cos/constants.js@@ -19,7 +19,7 @@ import { normalizeReviewerSlug, REVIEWER_VALUES } from '../../lib/reviewerPins';import { AVATAR_STYLE_LABELS } from '../../lib/avatarStyles';import { inPlaceClipName } from '../../utils/animationClips';import { getNavPageForPath, getPageNavTabs } from '../../../../server/lib/navManifest.js';-import { PR_REVIEW_MODES, DEFAULT_PR_REVIEW_MODE } from '../../../../server/lib/prDisposition.js';+import { PR_REVIEW_MODES, DEFAULT_PR_REVIEW_MODE, DEFAULT_PR_COMPLETION } from '../../../../server/lib/prDisposition.js';import { buildPageNavTabs } from '../../lib/pageNavTabs.js';// Icon per tab id. The manifest (`tabGroup: 'cos'`) owns id/label/order — this@@ -256,14 +256,15 @@ export const AGENT_OPTIONS = [];export const PR_COMPLETION_OPTIONS = [- { value: 'review-then-merge', label: 'Review then merge', description: 'Run the configured reviewer chain, then merge when it is clean.' },- { value: 'merge-on-green', label: 'Merge on green CI', description: 'Skip external review and merge after required checks pass.' },- { value: 'leave-open', label: 'Leave PR open', description: 'Open the PR and stop so you can inspect and merge it yourself.' }+ { value: 'review-then-merge', label: 'Review then merge', description: 'PortOS automatically merges after configured reviewers and required checks pass for the current PR head. CI waits use the pending-merge coordinator without keeping an agent running.' },+ { value: 'merge-on-green', label: 'Merge on green CI', description: 'PortOS automatically merges after required checks pass for the current PR head, without external review. Repository admission checks still apply.' },+ { value: 'leave-open', label: 'Leave PR open', description: 'Open the PR and stop so you can inspect and merge it yourself.' },+ { value: 'draft', label: 'Leave a draft PR', description: 'Open a draft PR and leave it for you to review and merge.' }];export const prCompletionOption = (value) => PR_COMPLETION_OPTIONS.find(option => option.value === value);-export const DEFAULT_PR_COMPLETION = 'review-then-merge';+export { DEFAULT_PR_COMPLETION };// WHO reviews a PR action's change — orthogonal to `PR_COMPLETION_OPTIONS`// above, which decides whether a review happens at all. The values come from@@ -286,11 +287,9 @@ export const prReviewModeOption = (value) => PR_REVIEW_MODE_OPTIONS.find(optionexport { PR_REVIEW_MODES, DEFAULT_PR_REVIEW_MODE };-// The policy a task falls back to when nothing pins `prCompletion` — mirrors the-// `resolvePrCompletion` fallback in server/lib/prDisposition.js (legacy-// `reviewLoop` records aside). Scheduled tasks inherit their app's-// `defaultPrCompletion` first, so this is only the floor.-export const IMPLICIT_PR_COMPLETION = 'merge-on-green';+// New scheduled PR tasks inherit the managed app's completion policy, falling+// back to reviewed automatic merge when that app has no explicit preference.+export const IMPLICIT_PR_COMPLETION = DEFAULT_PR_COMPLETION;// Which option a stored taskMetadata pins, or '' when nothing does (inherit).// Legacy `reviewLoop` records are the pre-`prCompletion` spelling of@@ -300,7 +299,8 @@ export const IMPLICIT_PR_COMPLETION = 'merge-on-green';// IMPLICIT_PR_COMPLETION floor — that floor is what "inherit" resolves to.export function pinnedPrCompletion(metadata) {if (prCompletionOption(metadata?.prCompletion)) return metadata.prCompletion;- return metadata?.reviewLoop === true || metadata?.reviewLoop === 'true' ? 'review-then-merge' : '';+ if (metadata?.reviewLoop === true || metadata?.reviewLoop === 'true') return 'review-then-merge';+ return metadata?.reviewLoop === false || metadata?.reviewLoop === 'false' ? 'merge-on-green' : '';}// UI copy for each reviewer in the Review Loop picker. `copilot` requests adiff --git a/docs/features/chief-of-staff.md b/docs/features/chief-of-staff.mdindex 44a639c10d..4ae64a6854 100644--- a/docs/features/chief-of-staff.md+++ b/docs/features/chief-of-staff.md@@ -103,11 +103,20 @@ carries a receipt.The pr-watcher pending-merge sweep then merges only the recorded head, underits own admission lease, once the PR is `CLEAN` with every reported checkgreen; GitHub auto-merge is never enabled. A head that moved invalidates the-binding and dispatches a follow-up with the recorded review roster; a failed-check or conflict does the same; an unreadable binding never merges and is+binding and dispatches recovery with the recorded review roster; a failed+check or conflict does the same. Once a review task exists, recovery resumes+that same task, retaining its lifetime spawn budget and target instead of+creating nested `[Review Loop]` descendants. A live owner keeps its receipt+until it releases the branch. Unreadable ownership defers; a changed target,+manual hold or exhausted retry budget remains blocked even if CI later turns+green. A new verified handoff is needed to replace that binding. An unreadable binding never merges and ishanded to the operator by notification; a PR that never settles times out to anotification as before.+Immediately before merging under admission, the coordinator re-reads its owning+task. A new manual hold or changed completion policy blocks the old receipt;+an unreadable owner or queued recovery defers without consuming a worker slot.+The merge-admission prompt section offers this handoff to every participantbefore its CI wait. When a local review round returns clean, the run records`REVIEW_HEAD=$(git rev-parse HEAD)` beside `REVIEW_STATUS` (one line, replacing@@ -143,6 +152,22 @@ poll passes the timer's own gate — daemon running, not paused, CoS auto-run seto `execute` — and is skipped otherwise; stopping the daemon cancels everypoller, and a receipt accepted while the daemon is stopped arms none.+New managed-app PR tasks default to **PortOS auto-merge after review**. The app's+PR completion setting can select automatic merge after checks, leave-open or+draft instead; an explicit per-run choice wins. This does not enable GitHub's+native auto-merge, which cannot acquire PortOS's local merge admission. Existing+explicit app and task policies remain unchanged.++New receipts also retain the verified checkout path. After a confirmed merge,+and after releasing merge admission, the coordinator archives unique contents+and Git metadata before retiring that exact checkout and local branch. A+cleanup refusal remains on the receipt as `cleanup.status`, `reason` and any+`archiveDir`; transient failures retry every 30 minutes, at most 12 times.+Locks, initialized submodules, changed checkout identity and supersession need+explicit recovery and remain held. No worker waits for this cleanup, no lock is+silently released, and no initialized submodule is discarded. Older receipts+without a checkout binding retain the existing branch-reconciliation fallback.+Leases extend the existing machine-local CoS runtime ownership in`data/cos/state.json`, under its existing write queue; there is no new store,seed, migration, or federation payload. Admission waits at most 15 seconds todiff --git a/server/lib/README.md b/server/lib/README.mdindex d3fa347130..5f76e87152 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -735,7 +735,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `asyncApiSpec.js` | Builds the AsyncAPI 3 Socket.IO document from the generated event catalog with direction-aware operations and explicit modeled/generated payload status. || `mergeGateContract.js` | `buildManagedGithubMergeScript()` emits the shared claim merge block with verified allowed-method selection, fresh head/check/admission gates and fail-closed mutation readback. `MANAGED_WORKTREE_CLEANUP_CONTRACT` and its `MANAGED_WORKTREE_COMPLETION_HANDOFF` share head-pinned, checkout-preserving merge and archive/ownership-gated explicit cleanup instructions. `mergeGateOwed({taskOpenPR, rendersInlinePrLifecycle, leaveOpen})` decides whether a completing run actually owed its own PR merge — only the INLINE (`git`/`gh`) prompt renders a Merge Gate section, so a `/do:pr` run is inert here; `resolveMergeGateVerdict({prProbe, summary})` classifies a run that did (`merged` / `auto-merge-enabled` / `merge-handoff-queued` / `no-pr-action` / `leave-open-stated` / `needs-reprompt`) from the PR's live state and the agent's own sentinel text; `summaryStatesLeaveOpen` and `buildMergeGateReprompt` are its text-matching and corrective-prompt helpers. `buildAutoMergeHandoffInstructions(prRef)` shares the verified GitHub pending-CI handoff across generated merge workflows. `hasHealthyAutoMergeRequest(pr, now?)` bounds pending handoffs to one hour with readable, non-failed CI; `prProbe` also verifies the local head matches GitHub before accepting `autoMergeEnabled` or a pending-merge receipt (`mergeHandoffQueued`). Pure — the PR lookup lives in `../services/prProbe.js`, the re-prompt delivery in `agentTuiSpawning.js`. || `preflightPlan.js` | The programmatic phase of a user-triggered pipeline run, as renderable data. `preflightStepPlan(taskType)` is the step list (generic queued/prepare/dispatch, plus pr-reviewer's own cadence → list-PRs → in-flight → hidden-Unicode/prompt-injection screening → snapshot); `createPreflightState` opens it, `applyPreflightStep` advances one step and closes every earlier unfinished one, `finalizePreflight` closes it `handed-off`/`programmatic`/`nothing-to-do`/`failed`/`interrupted` (first close wins), and `preflightHeadline` names where the run is. Persisted onto a task card by `services/preflightTaskCard.js` and rendered by the Tasks page, so a Run Now is visible before any agent exists. Pure. |-| `prDisposition.js` | `PR_MISSING_CATEGORY` shares the missing-PR verdict between finalization and cleanup. `resolvePrCompletion(metadata)` resolves the explicit `review-then-merge` / `merge-on-green` / `leave-open` policy, with legacy `reviewLoop` fallback; `explicitPrCompletion(task)` retains only explicit authority (defaults never release a handoff); `leavesPrForHuman(task)` + `PR_STAYS_OPEN_TASK_TYPES` keep JIRA hand-offs open. Shared by the agent prompt builder and `agentWorktreeCleanup` so both halves agree. `resolvePrCreation({taskOpenPR, agentOpensOwnPr, prClaimVerified})` → a `PR_CREATION` tri-state (`never` / `if-missing` / `always`) naming who opens the change request for a completing worktree agent, so the runner, TUI, and direct-CLI completion paths cannot drift into double-firing `gh pr create`. |+| `prDisposition.js` | `resolveAppPrCompletion(app, metadata)` supplies the reviewed automatic merge default for new tasks while preserving explicit managed-app choices and legacy review toggles. `PR_MISSING_CATEGORY` shares the missing-PR verdict between finalization and cleanup. `resolvePrCompletion(metadata)` resolves the explicit `review-then-merge` / `merge-on-green` / `leave-open` policy, with legacy `reviewLoop` fallback; `explicitPrCompletion(task)` retains only explicit authority (defaults never release a handoff); `leavesPrForHuman(task)` + `PR_STAYS_OPEN_TASK_TYPES` keep JIRA hand-offs open. Shared by the agent prompt builder and `agentWorktreeCleanup` so both halves agree. `resolvePrCreation({taskOpenPR, agentOpensOwnPr, prClaimVerified})` → a `PR_CREATION` tri-state (`never` / `if-missing` / `always`) naming who opens the change request for a completing worktree agent, so the runner, TUI, and direct-CLI completion paths cannot drift into double-firing `gh pr create`. || `recoveryMergeTarget.js` | `repositoryCleanupMergeTarget(task)` → the `{ url, branch }` parent PR a repository-cleanup recovery was filed to land, or null (#12251). A claimed target only: merge admission also requires the completed parent's server-written backlink to that exact task, branch and PR. || `prHandbackPolicy.js` | Whose turn it is on a public PR the pr-reviewer coordinator reviewed but did not merge. `resolvePullRequestWriteAccess(pr)` reads `isCrossRepository`/`maintainerCanModify` into a `PR_WRITE_ACCESS` reason, failing closed on an unknown head-repository relationship; `resolveHandbackDisposition({requestedChanges, notMergeReady, downgraded, deferred, canEdit, remediationExhausted})` returns a `PR_HANDBACK` verdict — `remediate` (PortOS pushes the fixes and lands it), `assign-opener` (the PR goes to its author queue), or `none`. A deferred or unanchorable review never becomes an agent work order. Pure. || `prReviewContent.js` | The one definition of the external pull-request content PortOS screens. `screenedPullRequestContent(pr, diff, commits?)` builds the contributor-authored surface — title, description, commit log, unified diff — and `screenedPullRequestFingerprint(pr, diff, commits?)` hashes it to a stable identity for one head commit, returning null when the commit log is missing rather than matching by omission. Both take the PR row, because the pr-reviewer preflight STAMPS that fingerprint and the coordinator RECOMPUTES it from a fresh forge read before it reviews, rebases, or merges: when the two hand-written field projections drifted apart, every approved review was dropped. Never rebuild either shape at a call site. Pure. |diff --git a/server/lib/prDisposition.js b/server/lib/prDisposition.jsindex 99af6ac1a5..71a1923ddc 100644--- a/server/lib/prDisposition.js+++ b/server/lib/prDisposition.js@@ -32,6 +32,19 @@ export const PR_COMPLETION_VALUES = Object.freeze(Object.values(PR_COMPLETIONS))const PR_COMPLETION_SET = new Set(PR_COMPLETION_VALUES);+// New PR tasks default to PortOS-coordinated review and automatic merge. Stored+// task records retain their legacy resolution below; app defaults never rewrite+// a run's pinned policy or authorize GitHub native auto-merge.+export const DEFAULT_PR_COMPLETION = PR_COMPLETIONS.REVIEW_THEN_MERGE;++export function resolveAppPrCompletion(app, metadata = {}) {+ if (PR_COMPLETION_SET.has(app?.defaultPrCompletion)) return app.defaultPrCompletion;+ // An explicitly configured legacy review toggle retains its behavior. Only+ // genuinely missing settings acquire the new reviewed auto-merge default.+ if ([true, false, 'true', 'false'].includes(metadata?.reviewLoop)) return resolvePrCompletion(metadata);+ return DEFAULT_PR_COMPLETION;+}+/*** WHO performs the code review an action triggers — orthogonal to* `PR_COMPLETIONS` above, which decides whether a review happens at all.diff --git a/server/lib/validation.js b/server/lib/validation.jsindex 21d5ac4246..e02703e857 100644--- a/server/lib/validation.js+++ b/server/lib/validation.js@@ -332,6 +332,8 @@ export const appSchema = z.object({})).optional(), // Per-task overrides: { [taskType]: { enabled, interval, intervalMs, providerId, model, taskMetadata } }defaultUseWorktree: z.boolean().optional(),defaultOpenPR: z.boolean().optional(),+ // Omitted inherits reviewed PortOS auto-merge for new tasks; PATCH must not+ // inject a default over an existing explicit draft/leave-open preference.defaultPrCompletion: z.enum(PR_COMPLETION_VALUES).optional(),// After a CoS agent completes against this app, audit the repo for the state the// task asked for (worktree removed, branch deleted, PR merged) and file a recoverydiff --git a/server/lib/validation.test.js b/server/lib/validation.test.jsindex 5b946779b5..6460e5f8f4 100644--- a/server/lib/validation.test.js+++ b/server/lib/validation.test.js@@ -632,7 +632,10 @@ describe('validation.js', () => {});it('accepts only known app PR completion defaults', () => {- expect(appUpdateSchema.safeParse({ defaultPrCompletion: 'leave-open' }).success).toBe(true);+ for (const policy of ['review-then-merge', 'merge-on-green', 'leave-open', 'draft']) {+ expect(appUpdateSchema.parse({ defaultPrCompletion: policy }).defaultPrCompletion).toBe(policy);+ expect(appSchema.parse({ name: 'Example', repoPath: '/repo', defaultPrCompletion: policy }).defaultPrCompletion).toBe(policy);+ }expect(appUpdateSchema.safeParse({ defaultPrCompletion: 'later' }).success).toBe(false);});diff --git a/server/routes/cosTaskRoutes.js b/server/routes/cosTaskRoutes.jsindex 96de327952..81e50bc0ee 100644--- a/server/routes/cosTaskRoutes.js+++ b/server/routes/cosTaskRoutes.js@@ -14,6 +14,7 @@ import { getAppById, getAppWorkTracker, PORTOS_APP_ID } from '../services/apps.jimport { prepareAppIssueClaim } from '../services/appIssues.js';import { getAssignableInstances } from '../services/instances.js';import { resolveManagedAppIssueTarget } from '../services/managedAppRepositories.js';+import { resolveAppPrCompletion } from '../lib/prDisposition.js';import { workTrackerLabel } from '../lib/workTracker.js';import { runningAgentsByTaskId, settleTaskSourceSpawnWindow } from '../lib/cosSpawnWindow.js';import { getSlashdoWorkflow, slashdoWorkflowAppliesTo, SLASHDO_COMMAND_NAMES } from '../lib/slashdoCatalog.js';@@ -111,10 +112,11 @@ async function assertAssignableInstance(instanceId) {async function assertWorktreeCapableApp(taskData) {if (!taskData.app || !(taskData.useWorktree || taskData.openPR)) return;const app = await getAppById(taskData.app);- if (!app?.repoPath || !existsSync(app.repoPath)) return;+ if (!app?.repoPath || !existsSync(app.repoPath)) return app;if (!(await isRepo(app.repoPath))) {throw new ServerError(notGitRepoMessage(app.name || taskData.app), { status: 400, code: 'NOT_A_GIT_REPO' });}+ return app;}const ISSUE_TRACKERS = new Set(['github', 'gitlab']);@@ -498,7 +500,14 @@ router.post('/tasks', asyncHandler(async (req, res) => {if (!parsed.success) failValidation(parsed);const { type, isInvestigation, ...taskData } = parsed.data;if (taskData.targetInstanceId) await assertAssignableInstance(taskData.targetInstanceId);- await assertWorktreeCapableApp(taskData);+ const app = await assertWorktreeCapableApp(taskData);+ // API callers can omit the UI's previewed value. Resolve against the app at+ // creation, then persist the choice so later configuration changes cannot+ // turn an in-flight draft/human handoff into an automatic merge.+ const opensPr = taskData.openPR === true || (taskData.useWorktree === true && taskData.openPR !== false);+ if (type === 'user' && !taskData.planOnly && !isInvestigation && opensPr && taskData.prCompletion === undefined) {+ taskData.prCompletion = resolveAppPrCompletion(app, taskData);+ }const preparedTask = await preparePlanOnlyTask(taskData);// A UI-queued investigation (#6043) goes through the SAME producer as an// auto-filed one, so it lands with the markers the shared machinery reads —diff --git a/server/routes/cosTaskRoutes.test.js b/server/routes/cosTaskRoutes.test.jsindex ef86b678c2..6ec4243799 100644--- a/server/routes/cosTaskRoutes.test.js+++ b/server/routes/cosTaskRoutes.test.js@@ -195,6 +195,29 @@ describe('CoS task responses after action-ledger failures', () => {});});+describe('POST /api/cos/tasks — managed app completion defaults', () => {+ it.each([undefined, 'draft', 'leave-open', 'merge-on-green'])('inherits %s for a newly queued PR task', async policy => {+ getAppById.mockResolvedValue({ id: 'example-app', defaultPrCompletion: policy });+ const res = await request(buildApp()).post('/api/cos/tasks').send({ description: 'Example fix', app: 'example-app', useWorktree: true });+ expect(res.status).toBe(200);+ expect(cos.addTask.mock.calls[0][0].prCompletion).toBe(policy ?? 'review-then-merge');+ });++ it.each(['draft', 'leave-open'])('preserves explicit %s over app automatic merge', async policy => {+ getAppById.mockResolvedValue({ id: 'example-app', defaultPrCompletion: 'review-then-merge' });+ const res = await request(buildApp()).post('/api/cos/tasks').send({ description: 'Example fix', app: 'example-app', openPR: true, prCompletion: policy });+ expect(res.status).toBe(200);+ expect(cos.addTask.mock.calls[0][0].prCompletion).toBe(policy);+ });++ it('does not add a PR completion policy when the caller explicitly disables PR creation', async () => {+ getAppById.mockResolvedValue({ id: 'example-app', defaultPrCompletion: 'review-then-merge' });+ const res = await request(buildApp()).post('/api/cos/tasks').send({ description: 'Example fix', app: 'example-app', useWorktree: true, openPR: false });+ expect(res.status).toBe(200);+ expect(cos.addTask.mock.calls[0][0]).not.toHaveProperty('prCompletion');+ });+});+describe('POST /api/cos/tasks — targetInstanceId (#4520)', () => {it('passes a registry-known pin through to addTask', async () => {const res = await request(buildApp())diff --git a/server/services/README.md b/server/services/README.mdindex 9641e315dd..e4bb59c1f3 100644--- a/server/services/README.md+++ b/server/services/README.md@@ -8,7 +8,7 @@ image-generation paths below are useful entry points when tracing render jobs.| --- | --- || `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. |+| `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. Pending-merge receipts use `retirePendingMergeCheckout`, which independently verifies the merged head and refuses locks, supersession and initialized submodules. || `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/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.jsindex ee52a6e778..ce8e69155f 100644--- a/server/services/agentWorktreeCleanup.js+++ b/server/services/agentWorktreeCleanup.js@@ -1086,6 +1086,13 @@ export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, pif (!prUrl || !prBranch) return null;if (prCompletion === PR_COMPLETIONS.LEAVE_OPEN) return null;+ // Recovery belongs to the same durable task. A fresh sys-rl task resets the+ // spawn budget on every CI/conflict handoff and recursively nests its title.+ // The id hint also recovers receipts written before the marker was retained.+ if (isTruthyMeta(originalTask?.metadata?.reviewLoopFollowUp) || originalTask?.id?.startsWith('sys-rl-')) {+ return resumeReviewLoopCoordinator(originalTask.id, prUrl, prBranch);+ }+const parsedPr = git.parsePullRequestUrl(prUrl);// Copilot is GitHub-only; CLI-based reviewers (claude/antigravity/codex/grok) work on any// forge because the agent invokes the CLI directly. On a GitLab forge, drop@@ -1318,6 +1325,50 @@ export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, preturn { ...followUpTask, dispatch: { started: true, reason: null } };}+async function resumeReviewLoopCoordinator(taskId, prUrl, prBranch) {+ const { getTaskById } = await import('./cos.js');+ const task = await getTaskById(taskId);+ if (!task || task.taskType !== 'internal' || !isTruthyMeta(task.metadata?.reviewLoopFollowUp)+ || task.metadata.reviewLoopPRUrl !== prUrl || task.metadata.reviewLoopPRBranch !== prBranch) {+ return { id: taskId, blocked: 'Review coordinator identity could not be verified' };+ }+ if (leavesPrForHuman(task) || resolvePrCompletion(task.metadata) === PR_COMPLETIONS.LEAVE_OPEN+ || isTruthyMeta(task.metadata.readOnly) || isTruthyMeta(task.metadata.reviewLoopLeaveOpen)) {+ return { id: taskId, blocked: 'Review coordinator leaves this PR for its human owner' };+ }+ // Finalization can mark the task complete before its worker finishes cleanup.+ // Keep the receipt until that owner releases, including across daemon restarts.+ const { readClaimOwnershipAgents } = await import('./cosClaimOwnership.js');+ const agents = await readClaimOwnershipAgents();+ if (!agents) return { id: taskId, deferred: true };+ if (task.status === 'in_progress' || agents.some(agent => (agent.taskId === taskId+ || agent.metadata?.reviewLoopMergeTarget?.url === prUrl)+ && ['running', 'paused', 'orphaned', 'interrupted'].includes(agent.status))) {+ return { id: taskId, deferred: true };+ }+ if (task.status === 'pending') return { id: taskId, duplicate: true };+ if (task.status !== 'completed') return { id: taskId, blocked: `Review coordinator is ${task.status}` };+ const { MAX_TOTAL_SPAWNS } = await import('../lib/cosValidation.js');+ const count = Number(task.metadata.totalSpawnCount);+ if (!Number.isInteger(count) || count < 1 || count >= MAX_TOTAL_SPAWNS) {+ return { id: taskId, blocked: 'Review coordinator retry budget exhausted or unreadable' };+ }+ const result = await updateTask(taskId, {+ status: 'pending',+ metadata: { reviewLoopRecoveryReason: 'The handed-off PR needs fresh validation, review or conflict resolution' },+ }, 'internal', {+ expectedStatus: 'completed',+ expectedMetadata: Object.fromEntries([+ 'totalSpawnCount', 'reviewLoopFollowUp', 'reviewLoopPRUrl', 'reviewLoopPRBranch',+ 'prCompletion', 'reviewLoopLeaveOpen', 'readOnly', 'jiraTicketId', 'analysisType',+ ].map(key => [key, task.metadata[key]])),+ });+ if (result?.error) throw new Error(result.error);+ if (result?.statusChanged) return { id: taskId, deferred: true };+ emitLog('info', `🔁 Resumed review coordinator ${taskId} for PR ${prUrl} (${count}/${MAX_TOTAL_SPAWNS} runs used)`, { taskId, prUrl });+ return { id: taskId, resumed: true };+}+/*** Auto-create a recovery task when a worktree merge or PR creation fails, so stale* branches don't accumulate in managed app repos and block future agent work.diff --git a/server/services/apps.js b/server/services/apps.jsindex a075dbbe84..a4a326c9d1 100644--- a/server/services/apps.js+++ b/server/services/apps.js@@ -294,6 +294,11 @@ async function createAppUnlocked(appData) {// concrete tracker (PLAN.md / GitHub / GitLab / JIRA) from the git origin// host at dispatch time — see server/lib/workTracker.js.workTracker: appData.workTracker || 'auto',+ // Preserve explicit workflow choices at creation as well as update. Missing+ // fields inherit the current defaults when a new task is queued.+ ...(typeof appData.defaultUseWorktree === 'boolean' ? { defaultUseWorktree: appData.defaultUseWorktree } : {}),+ ...(typeof appData.defaultOpenPR === 'boolean' ? { defaultOpenPR: appData.defaultOpenPR } : {}),+ ...(appData.defaultPrCompletion !== undefined ? { defaultPrCompletion: appData.defaultPrCompletion } : {}),// The gh account this app's repo is driven under. Absent (the default) means// "infer from the repo owner" — see services/forgeAuth.js....(appData.forgeAccount?.trim() ? { forgeAccount: appData.forgeAccount.trim() } : {}),diff --git a/server/services/apps.test.js b/server/services/apps.test.jsindex 51d460d1e8..eeec0ed1ee 100644--- a/server/services/apps.test.js+++ b/server/services/apps.test.js@@ -309,6 +309,29 @@ describe('portless / desktop apps (#2991)', () => {});+describe('managed app PR completion settings', () => {+ beforeEach(() => {+ invalidateCache();+ vi.clearAllMocks();+ readJSONFile.mockResolvedValue({ apps: { [PORTOS_APP_ID]: { name: 'PortOS' } } });+ });++ it.each(['draft', 'leave-open', 'merge-on-green', 'review-then-merge'])('round-trips explicit %s without an unrelated update changing it', async policy => {+ const created = await createApp({ name: 'Example', repoPath: '/repo', defaultUseWorktree: true, defaultOpenPR: true, defaultPrCompletion: policy });+ expect(created).toMatchObject({ defaultUseWorktree: true, defaultOpenPR: true, defaultPrCompletion: policy });+ const updated = await updateApp(created.id, { description: 'Updated description' });+ expect(updated.defaultPrCompletion).toBe(policy);+ expect((await getAllApps()).find(app => app.id === created.id).defaultPrCompletion).toBe(policy);+ expect(atomicWrite.mock.calls.at(-1)[1].apps[created.id].defaultPrCompletion).toBe(policy);+ });++ it('keeps an omitted preference absent and preserves explicit PR/worktree opt-outs', async () => {+ const created = await createApp({ name: 'Example', repoPath: '/repo', defaultUseWorktree: false, defaultOpenPR: false });+ expect(created).not.toHaveProperty('defaultPrCompletion');+ expect(created).toMatchObject({ defaultUseWorktree: false, defaultOpenPR: false });+ });+});+describe('managed app feature overrides', () => {beforeEach(() => {invalidateCache();diff --git a/server/services/branchCompletionPolicy.js b/server/services/branchCompletionPolicy.jsindex b7bb0384f9..a3ea8fa8d5 100644--- a/server/services/branchCompletionPolicy.js+++ b/server/services/branchCompletionPolicy.js@@ -142,6 +142,22 @@ export function reviewedRetirementPolicy(input) {})).sort((a, b) => String(a.id).localeCompare(String(b.id))) };}+/** A verified merged receipt may settle automatic completion obligations, but+ * never a human handoff or an owner that has not finished. The caller separately+ * proves the exact merged head and archives the checkout before retirement.+ */+export function mergedReceiptRetirementPolicy(input) {+ const decision = completionDecision(input);+ if (decision.reason === unavailable || decision.reason === held) return { reason: decision.reason };+ const policies = decision.policies || [];+ if (policies.some(policy => policy.agent.status !== 'completed')) return { reason: 'retirement-policy-owner-active' };+ return { reason: null, receiptHead: input.tip, policies: policies.map(policy => ({+ id: policy.agent.id || policy.agent.agentId, startedAt: policy.agent.startedAt,+ status: policy.agent.status, branch: policy.branch, completion: policy.completion,+ prUrl: policy.prUrl ?? null, tip: policy.tip ?? null,+ })).sort((a, b) => String(a.id).localeCompare(String(b.id))) };+}+export async function readBranchCompletionHold(input, deps = {}) {const readPolicies = deps.readPolicies || readBranchCompletionPolicies;const agents = input.agents ?? await readPolicies().catch(() => null);diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.jsindex 94b9a63dd6..3e386b78c8 100644--- a/server/services/cleanupAgentWorktree.test.js+++ b/server/services/cleanupAgentWorktree.test.js@@ -1,4 +1,6 @@vi.mock('./branchCompletionPolicy.js', () => ({ recordBranchCompletionPolicy: vi.fn() }));+vi.mock('./cosClaimOwnership.js', () => ({ readClaimOwnershipAgents: vi.fn() }));+import { readClaimOwnershipAgents } from './cosClaimOwnership.js';import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';import { cosEvents } from './cosEvents.js';vi.mock('./publicationValidation.js', () => ({ validatePublication: vi.fn() }));@@ -1857,6 +1859,50 @@ describe('spawnReviewLoopFollowUp', () => {vi.clearAllMocks();addTask.mockResolvedValue({ id: 'sys-rl-x' });forceSpawnTask.mockResolvedValue({ success: true });+ readClaimOwnershipAgents.mockResolvedValue([]);+ });++ it('resumes a persisted coordinator without resetting its budget or creating a descendant', async () => {+ const task = { id: 'sys-rl-original', taskType: 'internal', status: 'completed', metadata: {+ reviewLoopFollowUp: 'true', reviewLoopPRUrl: 'https://github.com/o/r/pull/7',+ reviewLoopPRBranch: 'feature', totalSpawnCount: '2',+ } };+ getTaskById.mockResolvedValue(task);+ getAgents.mockResolvedValue([]);+ updateTask.mockImplementationOnce(async (_id, patch) => Object.assign(task, { status: patch.status }));+ // Old persisted receipts omitted the marker; the live task is authoritative.+ const request = { originalTask: { id: task.id }, prUrl: task.metadata.reviewLoopPRUrl, prBranch: 'feature' };+ expect(await spawnReviewLoopFollowUp(request)).toMatchObject({ id: task.id, resumed: true });+ expect(await spawnReviewLoopFollowUp(request)).toMatchObject({ id: task.id, duplicate: true });+ expect(task.metadata.totalSpawnCount).toBe('2');+ expect(updateTask).toHaveBeenCalledTimes(1);+ expect(updateTask.mock.calls[0][3]).toMatchObject({ expectedStatus: 'completed', expectedMetadata: { totalSpawnCount: '2', reviewLoopPRBranch: 'feature' } });+ expect(addTask).not.toHaveBeenCalled();+ });++ it('waits for the live owner and refuses exhausted, mismatched or manually blocked coordinators', async () => {+ const task = { id: 'sys-rl-original', taskType: 'internal', status: 'completed', metadata: {+ reviewLoopFollowUp: true, reviewLoopPRUrl: 'https://github.com/o/r/pull/7',+ reviewLoopPRBranch: 'feature', totalSpawnCount: '1',+ } };+ getTaskById.mockResolvedValue(task);+ const request = { originalTask: { id: task.id }, prUrl: task.metadata.reviewLoopPRUrl, prBranch: 'feature' };+ readClaimOwnershipAgents.mockResolvedValue([{ taskId: task.id, status: 'running' }]);+ expect(await spawnReviewLoopFollowUp(request)).toMatchObject({ deferred: true });+ readClaimOwnershipAgents.mockResolvedValue(null);+ expect(await spawnReviewLoopFollowUp(request)).toMatchObject({ deferred: true });+ readClaimOwnershipAgents.mockResolvedValue([]);+ task.metadata.totalSpawnCount = '5';+ expect(await spawnReviewLoopFollowUp(request)).toMatchObject({ blocked: expect.stringContaining('budget') });+ task.metadata.totalSpawnCount = '1';+ task.status = 'blocked';+ expect(await spawnReviewLoopFollowUp(request)).toMatchObject({ blocked: expect.stringContaining('blocked') });+ expect(await spawnReviewLoopFollowUp({ ...request, prBranch: 'other' })).toMatchObject({ blocked: expect.stringContaining('identity') });+ task.status = 'completed';+ task.metadata.prCompletion = 'leave-open';+ expect(await spawnReviewLoopFollowUp(request)).toMatchObject({ blocked: expect.stringContaining('human owner') });+ expect(addTask).not.toHaveBeenCalled();+ expect(updateTask).not.toHaveBeenCalled();});it('preserves resolved provider pins and explicit clears in the queued review procedure', async () => {diff --git a/server/services/cosMergeHandoff.js b/server/services/cosMergeHandoff.jsindex 31392282f3..9189a353cc 100644--- a/server/services/cosMergeHandoff.js+++ b/server/services/cosMergeHandoff.js@@ -154,11 +154,12 @@ export async function handoffPendingMerge({ agentId, prUrl, headSha, worktreePatmetadata: {app: app.id, provider: task.metadata?.provider, providerId: task.metadata?.providerId,model: task.metadata?.model, effort: task.metadata?.effort,+ reviewLoopFollowUp: isTruthyMeta(task.metadata?.reviewLoopFollowUp),},},handoff: {receiptId: receipt.id, agentId, startedAt: agent.startedAt, taskId: agent.taskId, repository,- headSha: head, prCompletion: policy, reviewStatus: review.status ?? 'not-configured', acceptedAt: receipt.queuedAt,+ headSha: head, worktreePath: workspace, prCompletion: policy, reviewStatus: review.status ?? 'not-configured', acceptedAt: receipt.queuedAt,},followUp: await followUpRoster(task, policy),}).catch((err) => {@@ -171,7 +172,10 @@ export async function handoffPendingMerge({ agentId, prUrl, headSha, worktreePat// merges a head whose CI already settled; a still-pending entry gets the// bounded follow-up poll, and the 30-minute timer owns it after that.followUpHandoffReceipt(app.id, receipt.id);- return { queued: true, receipt };+ return { queued: true, receipt, coordination: {+ ownerTaskId: task.id, status: 'queued-for-merge',+ wake: 'immediate, then 1 minute for five polls, then 2 minutes for up to 45 minutes; 30-minute recovery sweep',+ } };}/**diff --git a/server/services/cosMergeHandoff.test.js b/server/services/cosMergeHandoff.test.jsindex a7483c01b8..80427b1b02 100644--- a/server/services/cosMergeHandoff.test.js+++ b/server/services/cosMergeHandoff.test.js@@ -56,6 +56,8 @@ vi.mock('./notifications.js', () => ({}));const followUpMock = vi.fn(async () => ({ id: 'follow-up-1' }));vi.mock('./agentWorktreeCleanup.js', () => ({ spawnReviewLoopFollowUp: (...args) => followUpMock(...args) }));+const cleanupMock = vi.fn();+vi.mock('./heldCheckoutRecovery.js', () => ({ retirePendingMergeCheckout: (...args) => cleanupMock(...args) }));import { handoffPendingMerge, hasQueuedMergeHandoff } from './cosMergeHandoff.js';import { processPendingMergePrs, readPendingMergePrs } from './prWatcher.js';@@ -84,6 +86,7 @@ beforeAll(async () => { workspace = await mkdtemp(join(tmpdir(), 'merge-handoff-afterAll(async () => { await rm(workspace, { recursive: true, force: true }); });beforeEach(async () => {+ cleanupMock.mockReset().mockResolvedValue({ ok: true, branchDeleted: true, archiveDir: '/archives/example' });f.state = { agents: { 'agent-1': claimAgent('agent-1', 'claim/issue-1'), 'agent-2': claimAgent('agent-2', 'claim/issue-2') }, mergeAdmissions: {} };f.tasks = Object.fromEntries(['agent-1', 'agent-2'].map((id) => [`task-${id}`, {id: `task-${id}`, status: 'in_progress', taskType: 'user', priority: 'MEDIUM', description: 'Example change',@@ -165,6 +168,89 @@ describe('pending-merge handoff', () => {expect(mergePrMock).toHaveBeenCalledWith('/repos/source', 7, { forgeAccount: null, expectedHeadSha: HEAD });});+ it.each(['leave-open', 'draft', 'readOnly', 'blocked'])('honors a live coordinator %s hold after CI turns green', async hold => {+ await handedOff();+ greenChecks();+ // Change the owner during the final contribution read, proving that a+ // policy snapshot taken before remote assessment cannot authorize merge.+ const read = execGhMock.getMockImplementation();+ execGhMock.mockImplementation(async (...args) => {+ if (args[0][0] === 'pr' && args[0][1] === 'diff') {+ const task = f.tasks['task-agent-1'];+ if (hold === 'blocked') task.status = 'blocked';+ else if (hold === 'readOnly') task.metadata.readOnly = true;+ else task.metadata.prCompletion = hold;+ }+ return read(...args);+ });+ await processPendingMergePrs(f.apps.get('app1'));+ expect(mergePrMock).not.toHaveBeenCalled();+ expect(pending()[0].recoveryBlocked).toEqual(expect.any(String));+ await processPendingMergePrs(f.apps.get('app1'));+ expect(notifyMock).toHaveBeenCalledTimes(1);+ expect(followUpMock).not.toHaveBeenCalled();+ });++ it('defers an unreadable coordinating task without losing its receipt or retry budget', async () => {+ await handedOff();+ greenChecks();+ const task = f.tasks['task-agent-1'];+ delete f.tasks['task-agent-1'];+ expect(await processPendingMergePrs(f.apps.get('app1'))).toMatchObject({ waiting: 1, merged: 0 });+ expect(pending()[0]).toMatchObject({ ticks: 0 });+ expect(mergePrMock).not.toHaveBeenCalled();+ f.tasks['task-agent-1'] = task;+ expect(await processPendingMergePrs(f.apps.get('app1'))).toMatchObject({ merged: 1 });+ expect(pending()).toEqual([]);+ });++ it('does not transfer a human-held original claim to a new recovery task after CI fails', async () => {+ await handedOff();+ f.tasks['task-agent-1'].metadata.prCompletion = 'leave-open';+ f.pr.statusCheckRollup = [{ conclusion: 'FAILURE' }];+ await processPendingMergePrs(f.apps.get('app1'));+ expect(followUpMock).not.toHaveBeenCalled();+ expect(pending()[0].recoveryBlocked).toEqual(expect.any(String));+ greenChecks();+ await processPendingMergePrs(f.apps.get('app1'));+ expect(mergePrMock).not.toHaveBeenCalled();+ expect(notifyMock).toHaveBeenCalledTimes(1);+ });++ it('keeps merged cleanup owned and bounded after an archival refusal, without holding merge admission', async () => {+ cleanupMock.mockImplementation(async () => {+ expect(Object.keys(f.state.mergeAdmissions)).toHaveLength(0);+ return { ok: false, reason: 'retirement-forge-unreadable' };+ });+ greenChecks();+ await handedOff();+ expect(pending()[0]).toMatchObject({ cleanup: { status: 'pending', attempts: 1, reason: 'retirement-forge-unreadable' } });+ f.pr.state = 'MERGED';+ await processPendingMergePrs(f.apps.get('app1'));+ expect(cleanupMock).toHaveBeenCalledTimes(1);+ // A process restart retains the retry time and the exact cleanup target.+ vi.resetModules();+ await (await import('./prWatcher.js')).processPendingMergePrs(f.apps.get('app1'));+ expect(cleanupMock).toHaveBeenCalledTimes(1);+ const app = f.apps.get('app1');+ app.pendingMergePrs[0].cleanup.retryAt = 0;+ cleanupMock.mockResolvedValue({ ok: true, branchDeleted: true, archiveDir: '/archives/example' });+ await (await import('./prWatcher.js')).processPendingMergePrs(app);+ expect(pending()).toEqual([]);+ });++ it.each(['pr-completion-human-handoff', 'retirement-submodule-not-uninitialized'])('holds merged cleanup requiring explicit recovery: %s', async reason => {+ cleanupMock.mockResolvedValue({ ok: false, reason });+ greenChecks();+ await handedOff();+ expect(pending()[0].cleanup).toMatchObject({ status: 'held', reason });+ f.pr.state = 'MERGED';+ pending()[0].cleanup.retryAt = 0;+ await processPendingMergePrs(f.apps.get('app1'));+ expect(cleanupMock).toHaveBeenCalledTimes(1);+ expect(pending()).toHaveLength(1);+ });+it('rechecks the queue after an overlapping sweep that read it before the receipt', async () => {greenChecks();let releaseRead;diff --git a/server/services/cosTaskClaimWork.js b/server/services/cosTaskClaimWork.jsindex 7929b17520..f82d40bdff 100644--- a/server/services/cosTaskClaimWork.js+++ b/server/services/cosTaskClaimWork.js@@ -20,7 +20,7 @@import { sanitizeTaskMetadata, resolveClaimReviewerConfig, reviewerConfigMetadata, hasReviewerOverride } from '../lib/validation.js';import { applyAppPlaceholders } from '../lib/appPromptPlaceholders.js';-import { PR_COMPLETIONS } from '../lib/prDisposition.js';+import { resolveAppPrCompletion } from '../lib/prDisposition.js';import { ServerError } from '../lib/errorHandler.js';import { getAppTaskTypeOverrides } from './apps.js';import { getCodeReviewDefaults } from './codeReview.js';@@ -128,7 +128,7 @@ export async function resolveAppClaimReviewers(app) {// lookup: the task metadata layer wins over them anyway.getCodeReviewDefaults().catch(() => null)]);- const prCompletion = metadata?.prCompletion || app?.defaultPrCompletion || PR_COMPLETIONS.REVIEW_THEN_MERGE;+ const prCompletion = metadata?.prCompletion ?? resolveAppPrCompletion(app, metadata);return {...claimReviewersFrom(metadata, codeReviewDefaults, { prCompletion }),prCompletion,@@ -202,11 +202,11 @@ export async function buildClaimWorkTask(app, {);const resolvedAuthorFilter = resolveClaimAuthorFilter(issueAuthorFilter, metadata);- const effectivePrCompletion = prCompletion ?? metadata?.prCompletion ?? app?.defaultPrCompletion;+ const effectivePrCompletion = prCompletion ?? metadata?.prCompletion ?? resolveAppPrCompletion(app, metadata);const claimReviewers = claimReviewersFrom(metadata, codeReviewDefaults, {reviewers, usernames, optionalReviewers, reviewerMaxRounds, reviewerModels, reviewerEfforts,- ...(effectivePrCompletion !== undefined ? { prCompletion: effectivePrCompletion } : {})+ prCompletion: effectivePrCompletion});const {reviewers: reviewersList,@@ -248,7 +248,7 @@ export async function buildClaimWorkTask(app, {// names — the reviewer pin is emitted once from there (#4770).const delegatedMeta = taskSchedule.DEFAULT_TASK_INTERVALS[promptTaskType]?.taskMetadata || {};const taskMetadata = { ...reviewerConfigMetadata(claimReviewers), claimFlow: true };- if (effectivePrCompletion) taskMetadata.prCompletion = effectivePrCompletion;+ taskMetadata.prCompletion = effectivePrCompletion;// The manual `/do:next` path persists this non-raw task through addTask's// metadata allowlist before agentLifecycle sees it. Carry the same count that// rendered the swarm block so Codex can size its session to root + workers.@@ -281,10 +281,8 @@ async function resolveClaimReviewerPrompt(app) {// The app's configured claim-work metadata layers over the Code Review// Defaults through the same claimReviewersFrom the scheduled path uses —// resolving from the defaults alone would silently drop a pinned override.- const effectivePrCompletion = metadata?.prCompletion ?? app?.defaultPrCompletion;- const config = effectivePrCompletion !== undefined- ? claimReviewersFrom(metadata, codeReviewDefaults, { prCompletion: effectivePrCompletion })- : claimReviewersFrom(metadata, codeReviewDefaults);+ const effectivePrCompletion = metadata?.prCompletion ?? resolveAppPrCompletion(app, metadata);+ const config = claimReviewersFrom(metadata, codeReviewDefaults, { prCompletion: effectivePrCompletion });const { reviewers: list, reviewerModels, reviewerEfforts, csv } = config;return {csv,diff --git a/server/services/cosTaskGenerator.auditMode.test.js b/server/services/cosTaskGenerator.auditMode.test.jsindex cfe80a9bb0..2136ad1ec5 100644--- a/server/services/cosTaskGenerator.auditMode.test.js+++ b/server/services/cosTaskGenerator.auditMode.test.js@@ -156,6 +156,19 @@ describe('issues-only audit dispatch never acquires code-shipping instructions (applicability.inapplicable = {};});+ it.each([+ [undefined, 'review-then-merge', 'codex'],+ ['merge-on-green', 'merge-on-green', 'none'],+ ['leave-open', 'leave-open', 'codex'],+ ])('resolves app completion %s before rendering scheduled reviewers', async (appPolicy, expectedPolicy, reviewers) => {+ const { getTaskInterval } = await import('./taskSchedule.js');+ getTaskInterval.mockResolvedValue({ type: 'weekly', taskMetadata: { fileIssues: false, openPR: true, useWorktree: true } });+ promptTemplate.body = 'Reviewers: {reviewers}';+ const task = await generateManagedAppImprovementTaskForType('security', makeApp({ defaultPrCompletion: appPolicy }), STATE, { skipPreconditions: true });+ expect(task.metadata.prCompletion).toBe(expectedPolicy);+ expect(task.description).toContain(`Reviewers: ${reviewers}`);+ });+it.each([true, false])('cognitive-load comment policy survives dispatch with fileIssues=%s', async (fileIssues) => {const { DEFAULT_TASK_PROMPTS } = await import('./taskPromptDefaults.js');const { getTaskInterval } = await import('./taskSchedule.js');diff --git a/server/services/cosTaskGenerator.js b/server/services/cosTaskGenerator.jsindex 82228b8445..9d1822a8d5 100644--- a/server/services/cosTaskGenerator.js+++ b/server/services/cosTaskGenerator.js@@ -62,7 +62,7 @@ import { isRecoveryTask } from './recoveryTasks.js';import { getCodeReviewDefaults } from './codeReview.js';import { getSkipReason } from './cosTaskClaim.js';import { ensureInstanceId } from './instanceIdentity.js';-import { PR_COMPLETIONS, PR_COMPLETION_VALUES } from '../lib/prDisposition.js';+import { PR_COMPLETIONS, resolveAppPrCompletion } from '../lib/prDisposition.js';import { resolveTrackerFilingBlock } from '../lib/workTracker.js';import {isAuditTaskType,@@ -1757,11 +1757,10 @@ export function applyAppWorktreeDefault(metadata, app) {metadata.openPR = false;}- // Legacy apps without this field keep resolving their persisted reviewLoop- // metadata. Once an app explicitly configures a default, stamp it onto new- // PR tasks so the policy survives later app-default changes.- if (finalOpenPR && metadata.prCompletion === undefined && PR_COMPLETION_VALUES.includes(app.defaultPrCompletion)) {- metadata.prCompletion = app.defaultPrCompletion;+ // Pin the policy on new PR tasks so later app-default changes cannot change+ // a running task's authority. Stored legacy tasks are resolved separately.+ if ((finalOpenPR || isTruthyMeta(metadata.claimFlow)) && metadata.prCompletion === undefined) {+ metadata.prCompletion = resolveAppPrCompletion(app, metadata);}}@@ -2731,6 +2730,9 @@ export async function prepareManagedAppImprovementTask(taskType, app, state, {const modeInstructions = isAuditTaskType(taskType)? `${modeContractFor(fileIssues)}\n\n${auditQualityInstructions(taskType)}`: '';+ // Resolve completion before rendering reviewers, including claim flows that+ // own their PR while intentionally disabling CoS worktree provisioning.+ applyAppWorktreeDefault(metadata, app);const baseDescription = await buildImprovementTaskDescription({promptTemplate: applyAuditModeWrapper(applyDepfreeMode(applyReleaseOptions(promptTemplate, promptTaskType, metadata), promptTaskType, metadata), modeInstructions),app, promptTaskType, metadata,@@ -2756,7 +2758,6 @@ export async function prepareManagedAppImprovementTask(taskType, app, state, {metadata);- applyAppWorktreeDefault(metadata, app);// File-issues posture wins over app worktree/PR defaults — the deliverable// is tracker items, so a managed worktree or an implied PR is the wrong shape.if (fileIssues) {diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.jsindex 01064568fe..f9ad539f7d 100644--- a/server/services/cosTaskGenerator.test.js+++ b/server/services/cosTaskGenerator.test.js@@ -520,7 +520,7 @@ describe('{reviewers} interpolation honors Code Review Defaults', () => {// All three claim paths layer claim-work metadata over the defaults via// claimReviewersFrom — including the JIRA play button (#6210). No path may// resolve the defaults alone with a bare `{}`.- expect(CLAIM_SRC).toContain('claimReviewersFrom(metadata, codeReviewDefaults)');+ expect(CLAIM_SRC).toContain('claimReviewersFrom(metadata, codeReviewDefaults, { prCompletion: effectivePrCompletion })');expect(LAYER_SRC).not.toContain('resolveClaimReviewerConfig({}, codeReviewDefaults, codeReviewDefaults?.reviewers)');// No path may resolve one map without the other — or reach past the shared// claim resolver, which wraps `resolveReviewerPins` for all three sites.@@ -2036,6 +2036,19 @@ describe('buildClaimWorkTask reviewer pin', () => {expect(taskMetadata.swarmCount).toBeUndefined();});+ it('pins the missing app default and retains it after the app setting changes', async () => {+ const { taskMetadata } = await buildClaimWorkTask(app);+ expect(taskMetadata.prCompletion).toBe('review-then-merge');+ const changedApp = { ...app, defaultPrCompletion: 'leave-open' };+ expect((await buildClaimWorkTask(changedApp)).taskMetadata.prCompletion).toBe('leave-open');+ expect(taskMetadata.prCompletion).toBe('review-then-merge');+ });++ it.each(['draft', 'leave-open'])('keeps an explicit %s run choice over app auto-merge', async policy => {+ const { taskMetadata } = await buildClaimWorkTask({ ...app, defaultPrCompletion: 'review-then-merge' }, { prCompletion: policy });+ expect(taskMetadata.prCompletion).toBe(policy);+ });+it('persists prCompletion: merge-on-green, replaces reviewers with none, and clears reviewers list', async () => {const { prompt, taskMetadata } = await buildClaimWorkTask(app, { prCompletion: 'merge-on-green' });expect(prompt).toContain('Reviewers: none');diff --git a/server/services/cosTaskStore.test.js b/server/services/cosTaskStore.test.jsindex 780f64e960..7c2a354ce1 100644--- a/server/services/cosTaskStore.test.js+++ b/server/services/cosTaskStore.test.js@@ -92,9 +92,9 @@ vi.mock('../lib/taskParser.js', async (importOriginal) => {};});-vi.mock('./cosState.js', () => ({+vi.mock('./cosState.js', async () => ({loadState: vi.fn(async () => mock.state),- withStateLock: async (fn) => fn(),+ withStateLock: (await import('../lib/fileWriteQueue.js')).createFileWriteQueue(),ROOT_DIR: '/root'}));@@ -1394,6 +1394,21 @@ describe('cosTaskStore.addTask', () => {expect(mock.events.find(e => e.name === 'tasks:changed').payload.action).toBe('updated');});+ it('atomically resumes one completed coordinator and preserves its lifetime spawn budget', async () => {+ const task = await addTask({ id: 'sys-rl-owner', description: 'Review existing PR', metadata: {+ app: 'example', reviewLoopFollowUp: true, reviewLoopPRBranch: 'feature', totalSpawnCount: '2',+ } }, 'internal', { raw: true });+ await updateTask(task.id, { status: 'completed' }, 'internal');+ const current = await getTaskById(task.id);+ const resume = () => updateTask(task.id, { status: 'pending' }, 'internal', {+ expectedStatus: 'completed', expectedMetadata: { totalSpawnCount: current.metadata.totalSpawnCount },+ });+ const results = await Promise.all([resume(), resume()]);+ expect(results.filter(result => result.statusChanged)).toHaveLength(1);+ const resumed = await getTaskById(task.id);+ expect(resumed).toMatchObject({ status: 'pending', metadata: { totalSpawnCount: '2', reviewLoopPRBranch: 'feature' } });+ });+it('emits tasks:changed action "requeued" on an in_progress → pending flip (#3373)', async () => {// The retry-hold release and the orphan sweep both requeue this way, long// after the completion dequeue ran — without a wake signal the retry woulddiff --git a/server/services/heldCheckoutRecovery.js b/server/services/heldCheckoutRecovery.jsindex 8f7768506f..1a63501ee2 100644--- a/server/services/heldCheckoutRecovery.js+++ b/server/services/heldCheckoutRecovery.js@@ -74,8 +74,10 @@ async function snapshotAdministration(path) {}async function retirementPolicy(repoPath, branch, opts) {- const { readBranchCompletionPolicies, reviewedRetirementPolicy } = await import('./branchCompletionPolicy.js');+ const { readBranchCompletionPolicies, reviewedRetirementPolicy, mergedReceiptRetirementPolicy } = await import('./branchCompletionPolicy.js');const policies = await (opts.readPolicies || (() => readBranchCompletionPolicies({ repairIndex: false })))().catch(() => null);+ if (opts.mergedReceipt) return mergedReceiptRetirementPolicy({ repoPath, branch, agents: policies,+ tip: opts.mergedReceipt.expectedHeadSha });return reviewedRetirementPolicy({ repoPath, branch, agents: policies });}@@ -370,6 +372,66 @@ const sameRelease = (entry, release) => entry.path === release.path && entry.hea&& (entry.branch ?? null) === (release.branch ?? null) && Boolean(entry.locked) === release.locked&& (entry.lockReason ?? null) === (release.lockReason ?? null);+// Only the automatic receipt path may acquire missing proof objects. Fetch+// exact server-verified commits into the object store, never a branch or index.+async function fetchReceiptProofObjects(repoPath, release, prUrl, expectedHeadSha, opts) {+ const [{ readRetirementForgeEvidence }, { getOriginInfo }, { resolveForgeExecOptions }] = await Promise.all([+ import('./heldCheckoutReview.js'), import('../lib/gitRemote.js'), import('./forgeExecOptions.js'),+ ]);+ const forge = await (opts.readForge || readRetirementForgeEvidence)(repoPath, release.branch, prUrl, opts).catch(() => null);+ const origin = await getOriginInfo(repoPath).catch(() => null);+ if (!origin || !forge || forge.repository !== `${origin.host}/${origin.fullName}` || forge.prUrl !== prUrl) {+ return { ok: false, reason: 'retirement-pr-repository-mismatch' };+ }+ if (forge.prHead !== expectedHeadSha) return { ok: false, reason: 'receipt-pr-head-changed' };+ const heads = [...new Set([forge.prHead, forge.mergeCommit, forge.defaultHead, forge.changeBase, forge.firstCommit])];+ if (heads.some(head => typeof head !== 'string' || !/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(head))) {+ return { ok: false, reason: 'retirement-forge-unreadable' };+ }+ const missing = [];+ for (const head of heads) {+ if (!await execGit(['cat-file', '-e', `${head}^{commit}`], repoPath).then(() => true, () => false)) missing.push(head);+ }+ if (!missing.length) return { ok: true };+ const { env } = await resolveForgeExecOptions(repoPath, { forgeAccount: opts.forgeAccount });+ const fetched = await execGit(['-c', 'credential.helper=', '-c', 'credential.helper=!gh auth git-credential',+ '-c', 'core.askPass=', 'fetch', '--no-tags', '--no-write-fetch-head', '--no-recurse-submodules',+ '--no-auto-maintenance', '--refmap=', '--', `https://${origin.host}/${origin.fullName}.git`, ...missing], repoPath, {+ timeout: 30_000, maxBuffer: 4 * 1024 * 1024,+ env: { ...env, GIT_TERMINAL_PROMPT: '0', GIT_ASKPASS: '', SSH_ASKPASS: '', GH_PROMPT_DISABLED: '1' },+ }).then(() => true, () => false);+ return fetched ? { ok: true } : { ok: false, reason: 'retirement-proof-fetch-failed' };+}++/** Finish only the checkout named by a trusted pending-merge receipt. Unlike an+ * operator release, this never unlocks a checkout or accepts supersession. Fresh+ * forge evidence must independently prove the exact handed-off head merged and+ * remains integrated. Initialized submodules stay held for explicit recovery.+ */+export async function retirePendingMergeCheckout({ repoPath, release, prUrl, expectedHeadSha }, opts = {}) {+ if (!release || release.locked !== false || release.lockReason !== null) return { ok: false, reason: 'receipt-checkout-locked' };+ if (!release.path || !release.branch || typeof expectedHeadSha !== 'string'+ || !/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/.test(expectedHeadSha) || release.head !== expectedHeadSha) {+ return { ok: false, reason: 'receipt-checkout-head-unverified' };+ }+ const receiptOptions = { ...opts, mergedReceipt: { expectedHeadSha } };+ let prepared = await reviewCurrentCheckout({ repoPath, release, prUrl }, receiptOptions);+ // The read-only preview has already passed identity, ownership, manual policy+ // and archival feasibility gates. Missing remote merge objects are recoverable+ // here without requiring an unrelated repo-sync to advance local branches.+ if (prepared.reason === 'retirement-local-objects-missing') {+ const fetched = await fetchReceiptProofObjects(repoPath, release, prUrl, expectedHeadSha, receiptOptions);+ if (!fetched.ok) return fetched;+ prepared = await reviewCurrentCheckout({ repoPath, release, prUrl }, receiptOptions);+ }+ if (!prepared.ok) return prepared;+ if (prepared.review.forge.prHead !== expectedHeadSha) return { ok: false, reason: 'receipt-pr-head-changed' };+ if (prepared.review.comparison.disposition !== 'integrated') return { ok: false, reason: 'retirement-supersession-not-accepted' };+ return retireHeldCheckout({ repoPath, release,+ review: { prUrl, digest: prepared.review.digest, acceptSuperseded: false },+ }, receiptOptions);+}+/*** 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.diff --git a/server/services/heldCheckoutRecovery.test.js b/server/services/heldCheckoutRecovery.test.jsindex 881ffab312..ecb9d7029e 100644--- a/server/services/heldCheckoutRecovery.test.js+++ b/server/services/heldCheckoutRecovery.test.js@@ -13,7 +13,19 @@ import { execGit } from '../lib/execGit.js';import { materializeGitRepo, SKIP_HEAVY_INTEGRATION } from '../lib/gitTestRepo.js';const SYMLINKS = process.platform !== 'win32';-const injected = vi.hoisted(() => ({ policies: [], schedule: null, app: null }));+const injected = vi.hoisted(() => ({ policies: [], schedule: null, app: null, fetchRemote: null, fetches: [] }));++vi.mock('../lib/execGit.js', async importOriginal => {+ const actual = await importOriginal();+ return { ...actual, execGit: (args, cwd, options) => {+ if (args.includes('credential.helper=!gh auth git-credential') && args.includes('fetch')) {+ injected.fetches.push({ args, options });+ if (injected.fetchRemote) args = args.map(arg => arg === 'https://github.com/example/repo.git' ? injected.fetchRemote : arg);+ }+ return actual.execGit(args, cwd, options);+ } };+});+vi.mock('./forgeExecOptions.js', () => ({ resolveForgeExecOptions: async () => ({ env: { ...process.env, GH_TOKEN: 'synthetic-account-token' } }) }));vi.mock('./branchCompletionPolicy.js', async (importOriginal) => {const actual = await importOriginal();@@ -28,7 +40,7 @@ vi.mock('./taskScheduleStore.js', async (importOriginal) => ({}));vi.mock('./apps.js', () => ({ getAppById: async (id) => (injected.app?.id === id ? injected.app : null) }));-const { retireInventoriedCheckout, prepareInventoriedCheckoutRetirement, heldCheckoutArchiveRoot } = await import('./heldCheckoutRecovery.js');+const { retireInventoriedCheckout, prepareInventoriedCheckoutRetirement, retirePendingMergeCheckout, heldCheckoutArchiveRoot } = await import('./heldCheckoutRecovery.js');const { recordBranchReconcileOutcome, getBranchReconcileOutcome } = await import('./taskSchedule.js');describe.skipIf(SKIP_HEAVY_INTEGRATION)('held checkout recovery (real git)', () => {@@ -39,7 +51,7 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('held checkout recovery (real git)', ()const noOwners = async () => [];beforeEach(async () => {- Object.assign(injected, { policies: [], schedule: { executions: {} }, app: { id: 'app-1', repoPath: null } });+ Object.assign(injected, { policies: [], schedule: { executions: {} }, app: { id: 'app-1', repoPath: null }, fetchRemote: null, fetches: [] });scratch = realpathSync(await mkdtemp(join(tmpdir(), 'portos-held-checkout-')));const safeRepo = join(scratch, 'repo');await mkdir(safeRepo);@@ -269,6 +281,119 @@ describe.skipIf(SKIP_HEAVY_INTEGRATION)('held checkout recovery (real git)', ()return { path, release, admin, opts, forge, prepare, confirm };}+ async function receiptCheckout(name, options) {+ const checkout = await reviewedCheckout(name, options);+ await execGit(['worktree', 'unlock', checkout.path], repo);+ checkout.release = { ...checkout.release, locked: false, lockReason: null };+ // A modern completed owner has a PR policy; no operator inventory grant.+ injected.policies[0].metadata.branchCompletionPolicy = {+ branch: checkout.release.branch, completion: 'review-then-merge',+ prUrl: checkout.forge.prUrl, tip: checkout.release.head,+ };+ injected.schedule.executions = {};+ checkout.retireReceipt = (opts = {}) => retirePendingMergeCheckout({+ repoPath: repo, release: checkout.release, prUrl: checkout.forge.prUrl,+ expectedHeadSha: checkout.release.head,+ }, { ...checkout.opts, ...opts });+ return checkout;+ }++ it('retires a merged receipt checkout without an inventory grant, preserving ignored bytes and original commits', async () => {+ const c = await receiptCheckout('receipt', { gitlink: true });+ const result = await c.retireReceipt();+ expect(result).toMatchObject({ ok: true, branchDeleted: true });+ expect(await registered(c.path)).toBe(false);+ expect(await readFile(join(result.archiveDir, 'files/ignored.txt'), 'utf8')).toBe('ignored work\n');+ const manifest = JSON.parse(await readFile(join(result.archiveDir, 'manifest.json'), 'utf8'));+ expect(manifest.captured.gitlinks).toMatchObject([{ path: 'vendor', state: 'empty' }]);+ expect(manifest.review.policy.receiptHead).toBe(c.release.head);+ await execGit(['fetch', join(result.archiveDir, 'commits.bundle'), 'HEAD:refs/heads/receipt-restored'], repo);+ expect((await execGit(['rev-parse', 'receipt-restored'], repo)).stdout.trim()).toBe(c.release.head);+ });++ it('fetches a remote-only squash commit for receipt proof without advancing any local branch', async () => {+ const base = (await execGit(['rev-parse', 'main'], repo)).stdout.trim();+ const c = await heldCheckout('remote-merge', { branch: 'feature/remote-merge', beforeLock: async tree => {+ await writeFile(join(tree, 'feature.txt'), 'remote feature\n');+ await execGit(['add', 'feature.txt'], tree);+ await execGit(['commit', '-m', 'feature awaiting remote merge'], tree);+ } });+ await execGit(['worktree', 'unlock', c.path], repo);+ const release = { ...c.release, locked: false, lockReason: null };+ const remote = join(scratch, 'remote');+ await execGit(['clone', '--no-hardlinks', repo, remote], scratch);+ await execGit(['config', 'user.email', '[email protected]'], remote);+ await execGit(['config', 'user.name', 'Test'], remote);+ await execGit(['merge', '--squash', 'origin/feature/remote-merge'], remote);+ await execGit(['commit', '-m', 'remote squash merge'], remote);+ const merged = (await execGit(['rev-parse', 'HEAD'], remote)).stdout.trim();+ expect((await execGit(['cat-file', '-e', `${merged}^{commit}`], repo, { ignoreExitCode: true })).exitCode)+ .not.toBe(0);+ await execGit(['remote', 'add', 'origin', 'https://github.com/example/repo.git'], repo);+ injected.fetchRemote = remote;+ const prUrl = 'https://github.com/example/repo/pull/42';+ const forge = { repository: 'github.com/example/repo', prUrl, prHead: release.head,+ mergeCommit: merged, defaultHead: merged, defaultBranch: 'main', remoteHead: null,+ changedPaths: ['feature.txt'], changeBase: base, firstCommit: release.head };+ const result = await retirePendingMergeCheckout({ repoPath: repo, release, prUrl, expectedHeadSha: release.head }, {+ cosDir, readAgents: noOwners, readForge: async () => forge, forgeAccount: 'synthetic-account',+ });+ expect(result).toMatchObject({ ok: true, branchDeleted: true });+ expect((await execGit(['rev-parse', 'main'], repo)).stdout.trim()).toBe(base);+ expect(existsSync(join(repo, '.git', 'FETCH_HEAD'))).toBe(false);+ expect(injected.fetches).toHaveLength(1);+ expect(injected.fetches[0].args).toEqual(expect.arrayContaining([+ '--no-write-fetch-head', '--no-recurse-submodules', '--refmap=', 'https://github.com/example/repo.git', merged,+ ]));+ expect(injected.fetches[0].options).toMatchObject({ timeout: 30_000,+ env: { GH_TOKEN: 'synthetic-account-token', GIT_TERMINAL_PROMPT: '0' } });+ expect(await readFile(join(result.archiveDir, 'files/ignored.txt'), 'utf8')).toBe('ignored work\n');+ });++ it.each(['head', 'supersession'])('preserves a receipt checkout when merged evidence has changed: %s', async change => {+ const c = await receiptCheckout('receipt-evidence', {+ superseded: change === 'supersession', multipleCommits: change === 'head',+ });+ // A different head with valid original ancestry reaches the receipt's+ // exact-head guard; the squash commit has no such ancestry and fails earlier.+ if (change === 'head') {+ 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.path)).toBe(true);+ expect(await archives()).toEqual([]);+ });++ it('retains manual, locked, unreadable and initialized-submodule receipt checkouts', async () => {+ const c = await receiptCheckout('receipt-holds', { gitlink: true });+ injected.policies[0].metadata.branchCompletionPolicy.completion = 'leave-open';+ expect(await c.retireReceipt()).toMatchObject({ ok: false, reason: 'pr-completion-human-handoff' });+ injected.policies[0].metadata.branchCompletionPolicy.completion = 'review-then-merge';+ expect(await c.retireReceipt({ readAgents: async () => null })).toMatchObject({ ok: false, reason: 'claim-ownership-unreadable' });+ expect(await c.retireReceipt({ readPolicies: async () => null })).toMatchObject({ ok: false, reason: 'pr-completion-policy-unavailable' });+ await execGit(['worktree', 'lock', '--reason', 'new owner', c.path], repo);+ expect(await c.retireReceipt()).toMatchObject({ ok: false, reason: 'checkout-lock-changed' });+ await execGit(['worktree', 'unlock', c.path], repo);+ await writeFile(join(c.path, 'vendor', 'unique.txt'), 'submodule work');+ expect(await c.retireReceipt()).toMatchObject({ ok: false, reason: 'retirement-submodule-not-uninitialized' });+ expect(await readFile(join(c.path, 'vendor', 'unique.txt'), 'utf8')).toBe('submodule work');+ expect(await registered(c.path)).toBe(true);+ expect(await archives()).toEqual([]);+ });++ it('preserves a receipt checkout when an owner appears during its archive', async () => {+ const c = await receiptCheckout('receipt-new-owner');+ let reads = 0;+ const result = await c.retireReceipt({ readAgents: async () => (++reads < 4 ? [] : [{+ id: 'agent-live', status: 'running', workspacePath: c.release.path,+ }]) });+ expect(result).toMatchObject({ ok: false, reason: 'claim-owner-active', archiveDir: expect.any(String) });+ expect(await registered(c.path)).toBe(true);+ expect(await readFile(join(result.archiveDir, 'files/ignored.txt'), 'utf8')).toBe('ignored work\n');+ });+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();diff --git a/server/services/prWatcher.js b/server/services/prWatcher.jsindex 716de3b0bc..db8293bfff 100644--- a/server/services/prWatcher.js+++ b/server/services/prWatcher.js@@ -23,7 +23,8 @@ import { createGithubActorTrust } from './forgeActorTrust.js';import { createHash } from 'node:crypto';import { safeJSONParse } from '../lib/fileUtils.js';import { isPlainObject } from '../lib/objects.js';-import { PR_COMPLETIONS } from '../lib/prDisposition.js';+import { PR_COMPLETIONS, leavesPrForHuman, resolvePrCompletion } from '../lib/prDisposition.js';+import { isTruthyMeta } from '../lib/metadataFlags.js';// Bound the gh query. The high-water mark (computePrCheck) advances to the max// open PR number it saw, so it can only correctly drain a backlog it received@@ -333,6 +334,12 @@ async function readPendingPullRequest(repoSpec, prNumber, { cwd, env } = {}) {const HANDOFF_POLICIES = new Set([PR_COMPLETIONS.MERGE_ON_GREEN, PR_COMPLETIONS.REVIEW_THEN_MERGE]);const INVALID_HANDOFF = Symbol('invalid-handoff');+const CLEANUP_REQUIRES_RECOVERY = new Set([+ 'receipt-checkout-locked', 'receipt-checkout-head-unverified', 'receipt-pr-head-changed',+ 'retirement-submodule-not-uninitialized', 'retirement-supersession-not-accepted',+ 'pr-completion-human-handoff', 'checkout-head-changed', 'checkout-branch-changed',+ 'checkout-lock-changed', 'checkout-not-found', 'checkout-primary', 'protected-branch',+]);// An agent handoff (#12247) pins the coordinator to one reviewed head. A legacy// PortOS-opened entry has no binding; a present-but-malformed one never merges.@@ -358,11 +365,28 @@ function followUpPolicy(entry, binding) {};}+async function currentHandoffOwnerPolicy(binding) {+ if (!binding) return null; // Legacy PortOS-opened entries have no task binding.+ const { getTaskById } = await import('./cosTaskStore.js');+ const task = binding.taskId && await getTaskById(binding.taskId).catch(() => null);+ if (!task || task.id !== binding.taskId) return { ownerDeferred: true };+ const metadata = task.metadata || {};+ if (leavesPrForHuman(task) || isTruthyMeta(metadata.readOnly) || isTruthyMeta(metadata.reviewLoopLeaveOpen)+ || resolvePrCompletion(metadata) !== binding.prCompletion) {+ return { ownerBlocked: 'The coordinating task completion policy changed; a fresh verified handoff is required' };+ }+ if (task.status === 'pending') return { ownerDeferred: true };+ if (!['in_progress', 'completed'].includes(task.status)) {+ return { ownerBlocked: `The coordinating task is ${task.status || 'unreadable'}` };+ }+ return null;+}+async function notifyPendingMergeTimeout(app, pending, reason, description = null) {return addNotification({type: NOTIFICATION_TYPES.AGENT_WARNING,priority: PRIORITY_LEVELS.HIGH,- title: `Merge-only PR #${pending.prNumber} needs attention`,+ title: `Pending PR #${pending.prNumber} needs attention`,description: description || `PortOS stopped polling this PR after ${MAX_PENDING_MERGE_TICKS} checks because ${reason}.`,link: pending.prUrl,metadata: { appId: app.id, pendingMergePrNumber: pending.prNumber }@@ -372,6 +396,33 @@ async function notifyPendingMergeTimeout(app, pending, reason, description = nul});}+async function finishMergedReceipt(app, entry, binding) {+ // Legacy queue records did not bind a checkout. Their existing branch+ // reconciliation remains the cleanup owner; never infer a deletion target.+ if (!binding?.worktreePath) return null;+ if (entry.cleanup?.status === 'held' || Date.now() < (entry.cleanup?.retryAt || 0)) return entry;+ const { retirePendingMergeCheckout } = await import('./heldCheckoutRecovery.js');+ const result = await retirePendingMergeCheckout({+ repoPath: app.repoPath, prUrl: entry.prUrl, expectedHeadSha: binding.headSha,+ release: { path: binding.worktreePath, head: binding.headSha, branch: entry.prBranch, locked: false, lockReason: null },+ }, { forgeAccount: app.forgeAccount ?? null }).catch(error => ({ ok: false, reason: error.message }));+ if (result.ok && result.branchDeleted) {+ console.log(`🧹 Pending PR #${entry.prNumber}: merged checkout archived and retired`);+ return null;+ }+ const attempts = (entry.cleanup?.attempts || 0) + 1;+ const reason = result.reason || result.branchRetainedReason || 'branch-retained';+ const requiresRecovery = CLEANUP_REQUIRES_RECOVERY.has(reason);+ const cleanup = { status: requiresRecovery || attempts >= MAX_PENDING_MERGE_TICKS ? 'held' : 'pending',+ reason, attempts, retryAt: Date.now() + PENDING_MERGE_SWEEP_INTERVAL_MS,+ ...(result.archiveDir ? { archiveDir: result.archiveDir } : {}) };+ if (!entry.cleanup || cleanup.status === 'held') {+ await notifyPendingMergeTimeout(app, entry, null,+ `PR #${entry.prNumber} is merged. Its receipt still owns cleanup: ${reason}. The checkout is preserved unless a verified archive is recorded. Pending cleanup retries every 30 minutes, up to ${MAX_PENDING_MERGE_TICKS} attempts; held cleanup requires explicit recovery and will not retry automatically.`);+ }+ return { ...entry, cleanup };+}+/*** Drive merge-only PortOS PRs on the normal pr-watcher cadence. Green PRs are* merged without consuming an agent lane; only a classified CI failure or@@ -421,6 +472,10 @@ async function runPendingMergePrs(app, { spendTicks }) {for (const entry of pending) {const key = pendingMergeKey(entry);+ if (entry.cleanup?.status === 'held' || Date.now() < (entry.cleanup?.retryAt || 0)) {+ outcomes.set(key, entry);+ continue;+ }let binding = readHandoffBinding(entry);if (binding && binding !== INVALID_HANDOFF) {const { repositoryKey } = await import('./cosMergeAdmission.js');@@ -456,7 +511,14 @@ async function runPendingMergePrs(app, { spendTicks }) {result.checked += 1;if (String(prView.state || '').toUpperCase() === 'MERGED') {- outcomes.set(key, null);+ outcomes.set(key, await finishMergedReceipt(app, entry, binding));+ continue;+ }++ // A refused owner/policy or exhausted budget remains refused even if CI+ // later turns green. Only a fresh verified handoff replaces this receipt.+ if (entry.recoveryBlocked) {+ outcomes.set(key, entry);continue;}@@ -466,8 +528,16 @@ async function runPendingMergePrs(app, { spendTicks }) {const failure = headMoved ? 'head-moved' : classifyPrFailure(prView);if (failure) {try {+ const ownerPolicy = await currentHandoffOwnerPolicy(binding);+ if (ownerPolicy) {+ outcomes.set(key, ownerPolicy.ownerBlocked ? { ...entry, recoveryBlocked: ownerPolicy.ownerBlocked } : entry);+ result.waiting = (result.waiting || 0) + 1;+ if (ownerPolicy.ownerBlocked) await notifyPendingMergeTimeout(app, entry, null,+ `PR #${entry.prNumber} remains owned by task ${binding.taskId}: ${ownerPolicy.ownerBlocked}.`);+ continue;+ }const { spawnReviewLoopFollowUp } = await import('./agentWorktreeCleanup.js');- await spawnReviewLoopFollowUp({+ const recovery = await spawnReviewLoopFollowUp({originalAgentId: entry.sourceAgentId || null,originalTask: entry.sourceTask,prUrl: entry.prUrl,@@ -475,8 +545,20 @@ async function runPendingMergePrs(app, { spendTicks }) {sourceWorkspace: app.repoPath,...followUpPolicy(entry, binding),});+ if (recovery?.deferred) {+ outcomes.set(key, entry);+ result.waiting = (result.waiting || 0) + 1;+ continue;+ }+ if (recovery?.blocked) {+ outcomes.set(key, { ...entry, recoveryBlocked: recovery.blocked });+ await notifyPendingMergeTimeout(app, entry, null,+ `PR #${entry.prNumber} remains owned by review task ${recovery.id}: ${recovery.blocked}. Resume that task after resolving the blocker; its worktree and exact-head merge gate are preserved.`);+ continue;+ }outcomes.set(key, null);result.escalated += 1;+ console.log(`🔁 Pending PR #${entry.prNumber}: ${failure}; coordinator ${recovery?.id || 'queued'}${recovery?.resumed ? ' resumed' : ''}`);if (headMoved) {result.invalidated += 1;console.warn(`⚠️ Pending merge handoff for PR #${entry.prNumber} invalidated: head moved from the handed-off commit`);@@ -511,6 +593,11 @@ async function runPendingMergePrs(app, { spendTicks }) {], undefined, { ...forgeExec, backoffKey: repoSpec }).catch(() => null), null),}).catch(() => ({ ok: false }));withheldReason = assessment.ok ? null : 'the complete current contribution assessment was unavailable or withheld';+ // Re-read the durable owner's policy inside admission, after remote+ // assessment and immediately before merge. Waiting CI is not authority+ // to ignore a later manual hold or a changed review requirement.+ const ownerPolicy = await currentHandoffOwnerPolicy(binding);+ if (ownerPolicy) return ownerPolicy;return assessment.ok? await git.mergePR(app.repoPath, entry.prNumber, {forgeAccount: app?.forgeAccount || null, expectedHeadSha,@@ -524,8 +611,16 @@ async function runPendingMergePrs(app, { spendTicks }) {continue;}const merge = admitted.result;+ if (merge.ownerDeferred || merge.ownerBlocked) {+ outcomes.set(key, merge.ownerBlocked ? { ...entry, recoveryBlocked: merge.ownerBlocked } : entry);+ result.waiting = (result.waiting || 0) + 1;+ if (merge.ownerBlocked) await notifyPendingMergeTimeout(app, entry, null,+ `PR #${entry.prNumber} remains owned by task ${binding.taskId}: ${merge.ownerBlocked}.`);+ continue;+ }if (merge.success) {- outcomes.set(key, null);+ // Admission has released before potentially slow archival cleanup.+ outcomes.set(key, await finishMergedReceipt(app, entry, binding));result.merged += 1;continue;}@@ -546,6 +641,10 @@ async function runPendingMergePrs(app, { spendTicks }) {}await mutatePendingMergePrs(app.id, (current) => current.flatMap((entry) => {+ const observed = pending.find(item => pendingMergeKey(item) === pendingMergeKey(entry));+ // A new receipt can arrive while a sweep waits on GitHub or recovery. It+ // owns its new head; an old sweep must not delete or overwrite that work.+ if (!observed || JSON.stringify(observed) !== JSON.stringify(entry)) return [entry];const outcome = outcomes.get(pendingMergeKey(entry));return outcome === undefined ? [entry] : outcome ? [outcome] : [];}));@@ -657,7 +756,8 @@ export function cancelHandoffFollowUps() {async function queuedReceiptIds(appId) {const app = await getAppById(appId);- return new Set(readPendingMergePrs(app).map((entry) => entry?.handoff?.receiptId).filter(Boolean));+ return new Set(readPendingMergePrs(app).filter(entry => !entry.cleanup && !entry.recoveryBlocked)+ .map((entry) => entry?.handoff?.receiptId).filter(Boolean));}async function armHandoffFollowUp(appId, receiptId) {diff --git a/server/services/prWatcher.test.js b/server/services/prWatcher.test.jsindex 9344ebf104..eb112a6c97 100644--- a/server/services/prWatcher.test.js+++ b/server/services/prWatcher.test.js@@ -394,6 +394,38 @@ describe('merge-only PR watcher', () => {expect(spawnReviewLoopFollowUpMock).toHaveBeenCalledTimes(1);});+ it('retains the receipt while its owner is active and records a blocked retry once across sweeps', async () => {+ const app = pendingApp();+ mockApps.set(app.id, app);+ execGhMock.mockResolvedValue(JSON.stringify({ state: 'OPEN', mergeStateStatus: 'DIRTY' }));+ spawnReviewLoopFollowUpMock.mockResolvedValueOnce({ id: 'sys-rl-owner', deferred: true });+ expect(await processPendingMergePrs(app)).toMatchObject({ escalated: 0, waiting: 1 });+ expect(readPendingMergePrs(mockApps.get(app.id))).toHaveLength(1);+ spawnReviewLoopFollowUpMock.mockResolvedValueOnce({ id: 'sys-rl-owner', blocked: 'retry budget exhausted' });+ await processPendingMergePrs(mockApps.get(app.id));+ expect(readPendingMergePrs(mockApps.get(app.id))[0].recoveryBlocked).toBe('retry budget exhausted');+ execGhMock.mockResolvedValue(JSON.stringify({ state: 'OPEN', mergeStateStatus: 'CLEAN', statusCheckRollup: [{ conclusion: 'SUCCESS' }] }));+ await processPendingMergePrs(mockApps.get(app.id));+ expect(spawnReviewLoopFollowUpMock).toHaveBeenCalledTimes(2);+ expect(addNotificationMock).toHaveBeenCalledTimes(1);+ expect(mergePrMock).not.toHaveBeenCalled();+ });++ it('does not erase a newer receipt when an older recovery settles', async () => {+ const app = pendingApp();+ mockApps.set(app.id, app);+ execGhMock.mockResolvedValue(JSON.stringify({ state: 'OPEN', mergeStateStatus: 'DIRTY' }));+ spawnReviewLoopFollowUpMock.mockImplementationOnce(async () => {+ await queuePendingMerge(app.id, { ...app.pendingMergePrs[0], handoff: {+ receiptId: 'new-receipt', headSha: 'b'.repeat(40), repository: 'github.com/o/r',+ agentId: 'new-run', prCompletion: 'review-then-merge',+ } });+ return { id: 'sys-rl-owner', resumed: true };+ });+ await processPendingMergePrs(app);+ expect(readPendingMergePrs(mockApps.get(app.id))[0].handoff.receiptId).toBe('new-receipt');+ });+it('stops polling and notifies after the bounded pending-merge budget', async () => {const app = pendingApp([pendingMerge({ ticks: MAX_PENDING_MERGE_TICKS - 1 })]);mockApps.set(app.id, app);diff --git a/server/services/subAgentSpawner.test.js b/server/services/subAgentSpawner.test.jsindex 8efbde1a91..2a46281598 100644--- a/server/services/subAgentSpawner.test.js+++ b/server/services/subAgentSpawner.test.js@@ -162,18 +162,33 @@ describe('Worktree & metadata flag helpers', () => {expect(metadata).toMatchObject({ useWorktree: true, openPR: true, prCompletion: 'leave-open' });});- it('keeps a task-level PR completion pin over the app default', () => {+ it.each(['merge-on-green', 'leave-open', 'draft'])('keeps a task-level %s pin over the app default', policy => {// The Schedule tab's "After opening PR" select writes this pin into the// interval's taskMetadata — the more specific choice must win.- const metadata = { prCompletion: 'merge-on-green' };+ const metadata = { prCompletion: policy };applyAppWorktreeDefault(metadata, { defaultOpenPR: true, defaultPrCompletion: 'review-then-merge' });- expect(metadata.prCompletion).toBe('merge-on-green');+ expect(metadata.prCompletion).toBe(policy);});- it('does not invent a disposition for a legacy app default', () => {+ it('pins reviewed auto-merge on a new PR task when the app has no completion setting', () => {const metadata = {};applyAppWorktreeDefault(metadata, { defaultOpenPR: true });- expect(metadata.prCompletion).toBeUndefined();+ expect(metadata.prCompletion).toBe('review-then-merge');+ });++ it.each([true, false, 'true', 'false'])('preserves an explicit legacy reviewLoop=%s unless the app pins a policy', reviewLoop => {+ const metadata = { openPR: true, reviewLoop };+ applyAppWorktreeDefault(metadata, {});+ expect(metadata.prCompletion).toBe(reviewLoop === true || reviewLoop === 'true' ? 'review-then-merge' : 'merge-on-green');+ const overridden = { openPR: true, reviewLoop };+ applyAppWorktreeDefault(overridden, { defaultPrCompletion: 'draft' });+ expect(overridden.prCompletion).toBe('draft');+ });++ it('applies app leave-open to self-managed claim PRs without provisioning another worktree', () => {+ const metadata = { claimFlow: true, useWorktree: false, openPR: false };+ applyAppWorktreeDefault(metadata, { defaultPrCompletion: 'leave-open' });+ expect(metadata).toMatchObject({ prCompletion: 'leave-open', useWorktree: false, openPR: false });});it('should not let defaultUseWorktree:false override explicit openPR:true', () => {