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: let a repository-cleanup recovery land its parent PR through merge admission (#12251)
[._.]/ Adam Eivy95d4da8dd20f
diff --git a/server/lib/README.md b/server/lib/README.mdindex adfdccc210..2cfa38dc64 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -735,6 +735,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `mergeGateContract.js` | `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` / `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` evidence. 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`. |+| `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. || `prReviewReport.js` | Owns the structured PR-decision contract end to end: `PR_REVIEW_DECISION_CONTRACT` is the envelope both review producers (pr-reviewer stage 3, issue-watcher reasoning pass) interpolate into their prompts, `normalizeReviewReport` bounds what comes back, `reviewReportText` hands every model-authored string to the abuse scan, and `renderReviewBody`/`renderFinding` turn it into the markdown a human reads on the PR page — verdict banner, scope line, blocking/non-blocking index anchored to `path:line`, test-evidence bullets (`TEST_EVIDENCE_STATUSES` keeps `fail` for "the change is broken", with `expected-fail` and `blocked` for the non-zero exits that say nothing about it), notes, collapsed verified-claims list, and inline comments with an optional GitHub suggestion block. Bounded by `MAX_REVIEW_BODY_CHARS`, dropping whole low-priority sections instead of truncating mid-sentence. Pure. |diff --git a/server/lib/agentRegistrationRecord.js b/server/lib/agentRegistrationRecord.jsindex 3a57459603..4880674ed7 100644--- a/server/lib/agentRegistrationRecord.js+++ b/server/lib/agentRegistrationRecord.js@@ -26,6 +26,7 @@ import { normalizeReviewers } from './reviewerConfig.js';import { quotaBurnAgentMetadata } from './quotaBurnOrigin.js';import { claimOwnershipBinding } from './claimContinuation.js';import { explicitPrCompletion } from './prDisposition.js';+import { repositoryCleanupMergeTarget } from './recoveryMergeTarget.js';/*** How this run is dispatched, as one closed vocabulary rather than the nested@@ -296,6 +297,9 @@ export function buildAgentRegistration({prDeliveryTarget: mergesOwnPr && worktreeInfo?.branchName && workspacePath? { branch: worktreeInfo.branchName, workspacePath }: null,+ // Repository-cleanup recovery (#12251): the parent PR this run was filed to+ // land, snapshotted so a later task edit reads as a changed target.+ recoveryMergeTarget: repositoryCleanupMergeTarget(task),configSimplify: isTruthyMeta(task.metadata?.simplify),configReviewLoop: isTruthyMeta(task.metadata?.reviewLoop),configReviewers: normalizeReviewers(task.metadata),diff --git a/server/lib/index.js b/server/lib/index.jsindex 85040e9171..61be47efaa 100644--- a/server/lib/index.js+++ b/server/lib/index.js@@ -706,6 +706,7 @@ export * from './apiToolResource.js';export * from './mergeGateContract.js';export * from './preflightPlan.js';export * from './prDisposition.js';+export * from './recoveryMergeTarget.js';export * from './prHandbackPolicy.js';export * from './prReviewContent.js';export * from './prReviewReport.js';diff --git a/server/lib/recoveryMergeTarget.js b/server/lib/recoveryMergeTarget.jsnew file mode 100644index 0000000000..cf3586692a--- /dev/null+++ b/server/lib/recoveryMergeTarget.js@@ -0,0 +1,21 @@+import { isPlainObject } from './objects.js';+import { isTruthyMeta } from './metadataFlags.js';+import { parsePullRequestUrl } from './gitForge.js';+import { PR_COMPLETIONS, explicitPrCompletion } from './prDisposition.js';+import { processAuditRecoveryOriginSchema } from './persistentMindProcessAudit.js';++/**+ * The parent pull request a repository-cleanup recovery was filed to land+ * (#12251), or null. Task metadata is writable through the task API, so this is+ * only the claimed target: merge admission grants it solely when the completed+ * parent carries the server's backlink to this exact task, branch and PR.+ */+export function repositoryCleanupMergeTarget(task) {+ const meta = task?.metadata;+ const target = meta?.recoveryMergeTarget;+ const origin = processAuditRecoveryOriginSchema.safeParse(meta?.recoveryOrigin).data;+ if (!isTruthyMeta(meta?.isRecovery) || origin?.subsystem !== 'repository-cleanup' || !isPlainObject(target)+ || typeof target.branch !== 'string' || !target.branch || !parsePullRequestUrl(target.url)+ || explicitPrCompletion(task) === PR_COMPLETIONS.LEAVE_OPEN) return null;+ return { url: target.url, branch: target.branch };+}diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex 6fbdb39b68..a03b85de62 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -23,6 +23,7 @@ import { getDigitalTwinForPrompt } from './digital-twin.js';import { TASK_PROMPT_KEY, taskContextBlock } from '../lib/cosTaskPrompt.js';import { injectReconcileAgentId } from '../lib/claimContinuation.js';import { PR_COMPLETIONS, leavesPrForHuman, resolvePrCompletion } from '../lib/prDisposition.js';+import { repositoryCleanupMergeTarget } from '../lib/recoveryMergeTarget.js';// Shared with cosTaskGenerator.js, which stamps the same set as metadata.claimFlow.import { isClaimFlowDispatch, resolveTaskHookType } from './taskTypeHooks.js';import { getCodeReviewDefaults } from './codeReview.js';@@ -770,6 +771,9 @@ After your task completes, the system will spawn a follow-up agent that runs the...buildSentinelWriteSteps(1, sentinelPath, sentinelTail)].join('\n');}+ } else if (repositoryCleanupMergeTarget(task)) {+ // A repository-cleanup recovery lands its parent PR under the same lease (#12251).+ reviewLoopFollowUpSection = buildMergeAdmissionSection(agentId);}// Build JIRA context section if applicable@@ -1110,7 +1114,8 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, { isTui = t}));const pushCliCompletion = () => contractSections.push(buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletion, mode: completionMode, canTypeSlashCommands: canTypeSlash, rendersInlinePrLifecycle, simplifyEnabled, noChangeSuccess, leavePrOpen: leavesPrForHuman(task), reviewPolicy, forgeCli: resolvedForgeCli, localReviewSection, localReviewRequired, postPrReview: rendersInlinePrLifecycle ? runsPrSideReviewLoop : null, mergeAdmission: mergesOwnPr }));// Ahead of the completion workflow, whose TUI form ends on the sentinel write.- if (mergesOwnPr) contractSections.push(buildMergeAdmissionSection(agentId));+ // A repository-cleanup recovery lands its parent PR under the same lease (#12251).+ if (mergesOwnPr || repositoryCleanupMergeTarget(task)) contractSections.push(buildMergeAdmissionSection(agentId));({[COMPLETION_MODES.TOOL_FREE]: () => contractSections.push(buildToolFreeReasoningCompletionSection()),diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex acfd735733..296bf67665 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -513,6 +513,20 @@ describe('generic own-PR delivery merges inside repository admission (#11435)',expect(prompt).toContain('## Claim ownership binding');});+ it.each([true, false])('gives a repository-cleanup recovery with a parent PR target admission on the %s light/full path (#12251)', async (light) => {+ const recoveryOrigin = { parentAgentId: 'agent-0', parentTaskId: 'task-0', subsystem: 'repository-cleanup', attempt: 1, observation: 'a'.repeat(64), noProgress: false };+ const target = { url: 'https://github.com/example/repo/pull/7', branch: 'cos/task-0/agent-0' };+ const build = (metadata) => light+ ? buildLightContextPrompt(makeTask({ metadata }), '/repo', null, { isTui: true, providerId: 'claude-code-tui', providerCommand: 'claude', agentId: 'agent-1' })+ : buildAgentPrompt(makeTask({ metadata }), {}, '/repo', null, { providerType: 'api', agentId: 'agent-1' });+ const prompt = await build({ isRecovery: true, recoveryOrigin, recoveryMergeTarget: target });+ expect(prompt.split(ADMISSION)).toHaveLength(2);+ expect(prompt).toContain('--match-head-commit <sha>');+ // Copied prose or a target without the recovery lineage grants nothing.+ expect(await build({ recoveryMergeTarget: target })).not.toContain(ADMISSION);+ expect(await build({ isRecovery: true, recoveryOrigin })).not.toContain(ADMISSION);+ });+it('leaves an API run, whose PR PortOS opens and a follow-up merges, unbound', async () => {const promptTrace = {};const prompt = await buildAgentPrompt(makeTask({ metadata: { openPR: true } }), {}, '/repo', worktree,diff --git a/server/services/agentRepoStateVerification.js b/server/services/agentRepoStateVerification.jsindex 3e14eada0e..e5f1f4a798 100644--- a/server/services/agentRepoStateVerification.js+++ b/server/services/agentRepoStateVerification.js@@ -46,6 +46,7 @@ import { RECOVERY_TASK_PREFIX } from './recoveryTasks.js';import { resolveTaskTargetBranch } from '../lib/taskTargetBranch.js';import { leavesPrForHuman, resolvePrCompletion, PR_COMPLETIONS } from '../lib/prDisposition.js';import { probePrForBranch } from './prProbe.js';+import { parsePullRequestUrl } from '../lib/gitForge.js';import { ensureTaskThread } from './brainTaskThreads.js';import {REPO_STATE_ISSUES,@@ -433,6 +434,10 @@ async function fileRepoStateRecoveryTask({ agentId, task, branchName, sourceWorkconst observation = processAuditFingerprint({ codes: issues.map(issue => issue.code).sort(),merged: observed.branchMerged, remotePresent: observed.remoteBranchPresent, prState: observed.prState });const previous = task?.metadata?.recoveryOrigin;+ // The PR this recovery may land under merge admission (#12251): the forge's+ // own answer for this branch, never the agent's report or the task prose.+ const mergeTarget = issues.some(issue => issue.code === REPO_STATE_ISSUES.PR_UNMERGED) && parsePullRequestUrl(observed.prUrl)+ ? { url: observed.prUrl, branch: branchName } : null;const created = await addTask({description: `${RECOVERY_TASK_PREFIX} Finish incomplete cleanup for branch ${branchName} in ${appName}`,priority: 'HIGH',@@ -440,7 +445,8 @@ async function fileRepoStateRecoveryTask({ agentId, task, branchName, sourceWorkisRecovery: true,metadata: { recoveryOrigin: { parentAgentId: agentId, parentTaskId: task?.id || null,subsystem: 'repository-cleanup', attempt: Math.min(1000, (previous?.attempt || 0) + 1),- observation, noProgress: previous?.observation === observation } },+ observation, noProgress: previous?.observation === observation },+ ...(mergeTarget ? { recoveryMergeTarget: mergeTarget } : {}) },context,useWorktree: false,}, 'user');@@ -449,6 +455,14 @@ async function fileRepoStateRecoveryTask({ agentId, task, branchName, sourceWorkemitLog('info', `🔎 Repo-state recovery for ${branchName} already queued as ${created.id}`, { agentId, branchName });return null;}+ if (mergeTarget && created?.id) {+ // Admission's trust anchor: task metadata is API-writable, so only this+ // server-written backlink on the parent names which task may land its PR.+ const { updateAgent } = await import('./cosAgentLifecycle.js');+ const bound = await updateAgent(agentId, { metadata: { repoStateRecovery: { taskId: created.id, ...mergeTarget } } })+ .catch(error => { emitLog('warn', `Could not bind repo-state recovery to ${agentId}: ${error.message}`, { agentId, branchName }); return null; });+ if (!bound) emitLog('warn', `Repo-state recovery ${created.id} cannot merge ${branchName}: parent ${agentId} was not bound`, { agentId, branchName });+ }emitLog('info', `🔧 Filed repo-state recovery task for ${branchName} (${issues.length} issue(s))`, { agentId, branchName, appName });return created?.id || null;}diff --git a/server/services/cosMergeAdmission.cleanupRecovery.test.js b/server/services/cosMergeAdmission.cleanupRecovery.test.jsnew file mode 100644index 0000000000..ca29b09dfb--- /dev/null+++ b/server/services/cosMergeAdmission.cleanupRecovery.test.js@@ -0,0 +1,187 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';+import { generateTasksMarkdown, parseTasksMarkdown } from '../lib/taskParser.js';++// Repository-cleanup recovery (#12251): the post-completion audit files a+// recovery for a parent whose PR is still open; that recovery lands the PR+// inside repository merge admission. Authority comes from the audit's own+// forge observation and its backlink on the parent, never a caller claim.+const f = vi.hoisted(() => ({ state: null, disk: null, tasks: {}, archive: {} }));+vi.mock('./cosState.js', () => ({+ AGENTS_DIR: '/synthetic/agents',+ withStateLock: createFileWriteQueue(),+ loadState: async () => f.state,+ saveState: async state => { f.state = state; f.disk = structuredClone(state); },+ readMergeAdmissionStateForSafetyCheck: async () => ({ trusted: true, ...structuredClone(f.disk) }),+}));+vi.mock('../lib/fileUtils.js', async () => ({+ ...await vi.importActual('../lib/fileUtils.js'),+ atomicWrite: async (path, value) => { f.archive[path] = JSON.stringify(value); },+ tryReadFile: async path => f.archive[path] ?? null,+}));+vi.mock('./cosAgentIndex.js', async () => ({+ ...await vi.importActual('./cosAgentIndex.js'),+ loadAgentIndex: async () => new Map([['parent-1', '2026-01-01']]),+}));+vi.mock('./cosEvents.js', () => ({ cosEvents: { emit: vi.fn() }, emitLog: vi.fn() }));+vi.mock('./cosTaskStore.js', () => ({ getTaskById: async id => f.tasks[id] ?? null }));+vi.mock('./cos.js', () => ({+ addTask: vi.fn(async () => ({ id: 'task-recovery-1' })),+ getAllTasks: vi.fn(async () => ({ user: { tasks: [] }, cos: { tasks: [] } })),+}));+vi.mock('./prWatcher.js', () => ({ readPendingMergePrs: () => [] }));+vi.mock('./worktreeManager.js', () => ({ listWorktrees: async () => [] }));+vi.mock('./branchReconcile.js', () => ({+ listRemoteHeads: async () => new Map([[BRANCH, 'abc']]),+ cleanupMerged: async () => ({ cleaned: [] }),+ driveToMerge: pr => `merge ${pr} with --match-head-commit <verified-head>`,+}));+vi.mock('./git.js', () => ({+ getDefaultBranch: async () => 'main',+ hasBranchMergeEvidence: async () => false,+ resolveForgeForRepo: async () => ({ cli: 'gh', env: null }),+}));+vi.mock('./github.js', () => ({ findPullRequestForBranch: vi.fn() }));+vi.mock('./apps.js', () => ({ getAppById: async () => ({ id: 'example-app', name: 'Example App' }) }));+vi.mock('./brainTaskThreads.js', () => ({ ensureTaskThread: async () => ({}) }));+// The parent's worktree and local branch are already gone.+vi.mock('../lib/execGit.js', () => ({ execGit: async () => ({ exitCode: 1, stdout: '', stderr: '' }) }));+vi.mock('fs', async () => ({ ...await vi.importActual('fs'), existsSync: () => false }));+vi.mock('../lib/gitRemote.js', () => ({ getOriginInfo: async path => ({ host: 'github.com', fullName: path === '/repos/other' ? 'example/other' : 'example/repo' }) }));++const BRANCH = vi.hoisted(() => 'cos/task-parent/parent-1');+const PR_URL = 'https://github.com/example/repo/pull/7';+const REPOSITORY = 'github.com/example/repo';++import { addTask } from './cos.js';+import { findPullRequestForBranch } from './github.js';+import { buildTaskMetadata } from './cosTaskIntake.js';+import { buildAgentRegistration } from '../lib/agentRegistrationRecord.js';+import { registerAgent } from './cosAgentLifecycle.js';+import { verifyAgentRepoState } from './agentRepoStateVerification.js';+import { claimMergeAdmission, withPendingMergeAdmission } from './cosMergeAdmission.js';++const persist = () => { f.disk = structuredClone(f.state); };+const admission = (action, token, extra = {}) => claimMergeAdmission({ agentId: 'recovery-1', action, token, ...extra });+const parentTask = { id: 'task-parent', description: 'Fix the example', metadata: { app: 'example-app', openPR: true, prCompletion: 'merge-on-green' } };++// Queue entries round-trip through TASKS.md, so scalars arrive as strings.+const queue = (id, taskData) => {+ const [task] = parseTasksMarkdown(generateTasksMarkdown([{ id, status: 'in_progress', priority: 'HIGH',+ description: taskData.description, metadata: buildTaskMetadata(taskData, 'user') }]));+ f.tasks[id] = { ...task, taskType: 'user' };+ return f.tasks[id];+};+const register = (agentId, task) => registerAgent(agentId, task.id, buildAgentRegistration({ task, provider: { id: 'test' },+ modelSelection: {}, sourceWorkspace: '/repos/source', workspacePath: '/repos/source' }));++// The real audit files the recovery for the completed parent; the real+// intake, registration and admission then run on what it produced.+async function fileAndLaunch() {+ const audit = await verifyAgentRepoState({ agentId: 'parent-1', task: parentTask, agentState: f.state.agents['parent-1'], success: true, prExpected: true });+ expect(audit.recoveryTaskId).toBe('task-recovery-1');+ const task = queue('task-recovery-1', addTask.mock.calls.at(-1)[0]);+ await register('recovery-1', task);+ return task;+}++beforeEach(() => {+ addTask.mockClear();+ findPullRequestForBranch.mockResolvedValue({ status: 'found', url: PR_URL, number: 7, detail: 'OPEN' });+ f.tasks = {}; f.archive = {};+ f.state = { agents: { 'parent-1': { id: 'parent-1', taskId: 'task-parent', status: 'completed', startedAt: '2026-01-01T00:00:00Z',+ completedAt: '2026-01-01T01:00:00Z', metadata: { isWorktree: true, sourceWorkspace: '/repos/source', worktreeBranch: BRANCH,+ workspacePath: '/repos/source/data/cos/worktrees/parent-1', prOpenedBy: 'agent-slashdo' } } }, mergeAdmissions: {}, stats: { agentsSpawned: 0 } };+ persist();+});++describe('repository-cleanup recovery merge admission', () => {+ it('lands the registered parent PR with no parent checkout, from creation through release', async () => {+ await fileAndLaunch();+ expect(addTask.mock.calls[0][0].metadata.recoveryMergeTarget).toEqual({ url: PR_URL, branch: BRANCH });+ expect(f.state.agents['recovery-1'].metadata.recoveryMergeTarget).toEqual({ url: PR_URL, branch: BRANCH });+ const backlink = { taskId: 'task-recovery-1', url: PR_URL, branch: BRANCH };+ expect(f.state.agents['parent-1'].metadata.repoStateRecovery).toEqual(backlink);+ const lease = await admission('acquire');+ expect(lease).toMatchObject({ admitted: true, repository: REPOSITORY });+ expect(await admission('check', lease.token)).toMatchObject({ admitted: true });+ expect(await admission('release', lease.token, { outcome: 'merged' })).toMatchObject({ released: true });+ expect(f.disk.mergeAdmissions).toEqual({});+ expect(f.state.agents['recovery-1'].metadata.claimPicksOwnBranch).toBeUndefined();+ });++ it('verifies a parent already archived out of live state through its persisted backlink', async () => {+ await fileAndLaunch();+ delete f.state.agents['parent-1']; persist();+ const lease = await admission('acquire');+ expect(lease).toMatchObject({ admitted: true, repository: REPOSITORY });+ expect(await admission('release', lease.token, { outcome: 'merged' })).toMatchObject({ released: true });+ });++ it('keeps the repository-wide lease exclusive against claim runs and the sweep', async () => {+ await fileAndLaunch();+ f.state.agents.claim = { id: 'claim', taskId: 'claim-task', status: 'running', startedAt: new Date().toISOString(),+ metadata: { claimPicksOwnBranch: true, sourceWorkspace: '/repos/source' } }; persist();+ const claim = await claimMergeAdmission({ agentId: 'claim', action: 'acquire' });+ expect(await admission('acquire')).toMatchObject({ admitted: false, reason: 'owner-active-or-unverified' });+ await claimMergeAdmission({ agentId: 'claim', action: 'release', token: claim.token, outcome: 'merged' });+ const lease = await admission('acquire');+ expect(lease.admitted).toBe(true);+ expect((await withPendingMergeAdmission({ host: 'github.com', fullName: 'example/repo' }, vi.fn())).admitted).toBe(false);+ });++ it.each([+ 'changed-task-target', 'changed-registration', 'leave-open', 'human-handoff', 'parent-leave-open', 'parent-running',+ 'parent-other-task', 'parent-other-branch', 'parent-unbound', 'backlink-other-task', 'parent-other-repository',+ 'other-lineage', 'completed-task',+ ])('refuses %s with a non-retryable blocker', async mode => {+ const task = await fileAndLaunch();+ const agent = f.state.agents['recovery-1'];+ const parent = f.state.agents['parent-1'];+ if (mode === 'changed-task-target') task.metadata.recoveryMergeTarget = { url: 'https://github.com/example/repo/pull/8', branch: BRANCH };+ if (mode === 'changed-registration') agent.metadata.recoveryMergeTarget = { url: PR_URL, branch: 'another/branch' };+ if (mode === 'leave-open') task.metadata.prCompletion = 'leave-open';+ if (mode === 'human-handoff') task.metadata.jiraTicketId = 'EX-1';+ if (mode === 'parent-leave-open') parent.metadata.prCompletionPolicy = 'leave-open';+ if (mode === 'parent-running') parent.status = 'running';+ if (mode === 'parent-other-task') parent.taskId = 'task-other';+ if (mode === 'parent-other-branch') parent.metadata.worktreeBranch = 'another/branch';+ if (mode === 'parent-unbound') delete parent.metadata.repoStateRecovery;+ if (mode === 'backlink-other-task') parent.metadata.repoStateRecovery.taskId = 'task-other';+ if (mode === 'parent-other-repository') parent.metadata.sourceWorkspace = '/repos/other';+ if (mode === 'other-lineage') task.metadata.recoveryOrigin = { ...task.metadata.recoveryOrigin, parentAgentId: 'parent-2' };+ if (mode === 'completed-task') task.status = 'completed';+ persist();+ expect(await admission('acquire')).toMatchObject({ admitted: false, reason: 'recovery-merge-target-unverified', retryable: false });+ expect(f.disk.mergeAdmissions).toEqual({});+ });++ it('refuses a copied recovery the parent never named, and copied prose alone', async () => {+ const original = await fileAndLaunch();+ const payload = addTask.mock.calls[0][0];+ // Identical lineage and target written through the task API: no backlink.+ await register('copy-1', queue('task-copy', payload));+ expect(await claimMergeAdmission({ agentId: 'copy-1', action: 'acquire' }))+ .toMatchObject({ admitted: false, reason: 'recovery-merge-target-unverified', retryable: false });+ // The same remediation prose without the trusted lineage is an ordinary run.+ await register('prose-1', queue('task-prose', { description: original.description, context: payload.context }));+ expect(await claimMergeAdmission({ agentId: 'prose-1', action: 'acquire' }))+ .toMatchObject({ admitted: false, reason: 'claim-owner-unverified' });+ expect(f.disk.mergeAdmissions).toEqual({});+ });++ it('refuses completed and unregistered callers', async () => {+ await fileAndLaunch();+ expect(await claimMergeAdmission({ agentId: 'missing', action: 'acquire' })).toMatchObject({ admitted: false, reason: 'claim-owner-unverified' });+ f.state.agents['recovery-1'].status = 'completed'; persist();+ expect(await admission('acquire')).toMatchObject({ admitted: false, reason: 'claim-owner-unverified' });+ });++ it('files no merge authority when the forge reported no PR, and reports that blocker', async () => {+ findPullRequestForBranch.mockResolvedValue({ status: 'none', url: null, detail: null });+ await fileAndLaunch();+ expect(addTask.mock.calls[0][0].metadata.recoveryMergeTarget).toBeUndefined();+ expect(f.state.agents['parent-1'].metadata.repoStateRecovery).toBeUndefined();+ expect(await admission('acquire')).toMatchObject({ admitted: false, reason: 'recovery-merge-target-unverified', retryable: false });+ });+});diff --git a/server/services/cosMergeAdmission.js b/server/services/cosMergeAdmission.jsindex cf9bf82025..5d661c98fd 100644--- a/server/services/cosMergeAdmission.js+++ b/server/services/cosMergeAdmission.js@@ -9,6 +9,7 @@ import { isPlainObject } from '../lib/objects.js';import { parsePullRequestUrl } from '../lib/gitForge.js';import { isTruthyMeta } from '../lib/metadataFlags.js';import { PR_COMPLETIONS, leavesPrForHuman, resolvePrCompletion } from '../lib/prDisposition.js';+import { repositoryCleanupMergeTarget } from '../lib/recoveryMergeTarget.js';const retryAfterMs = 5000;export const ADMISSION_QUEUE_TIMEOUT_MS = 15_000;@@ -211,10 +212,43 @@ async function verifiedWorktreeDelivery(agent, repository) {return checkoutOnBranch(target.workspacePath, target.branch, repository);}+const isCleanupRecovery = (agent) => agent.metadata?.isRecovery === true+ && agent.metadata?.recoveryOrigin?.subsystem === 'repository-cleanup';++// Repository-cleanup recovery (#12251): lands the PR of the completed parent+// whose audit filed it. Its registered target must match the live task, and+// the parent must carry the server-written backlink to this task, branch and+// PR. Needs no checkout: the parent's worktree is usually already gone.+async function verifiedCleanupRecovery(agent, repository, agents) {+ const meta = agent.metadata;+ const target = meta.recoveryMergeTarget;+ const { parentAgentId, parentTaskId } = meta.recoveryOrigin;+ if (!isPlainObject(target) || !parentTaskId || meta.prCompletionPolicy === PR_COMPLETIONS.LEAVE_OPEN) return false;+ const task = await liveTask(agent);+ const live = repositoryCleanupMergeTarget(task);+ if (!live || live.url !== target.url || live.branch !== target.branch || leavesPrForHuman(task)+ || isTruthyMeta(task.metadata.readOnly) || task.metadata.recoveryOrigin.parentAgentId !== parentAgentId+ || task.metadata.recoveryOrigin.parentTaskId !== parentTaskId) return false;+ const pr = parsePullRequestUrl(target.url);+ if (repositoryKey({ host: pr.host, fullName: `${pr.owner}/${pr.repo}` }) !== repository) return false;+ let parent = agents[parentAgentId];+ if (!parent) {+ const { readAgentRecordOrUnreadable } = await import('./cosAgentLifecycle.js');+ parent = await readAgentRecordOrUnreadable(parentAgentId);+ }+ const link = parent?.metadata?.repoStateRecovery;+ if (!isPlainObject(parent) || parent.id !== parentAgentId || parent.taskId !== parentTaskId || parent.status !== 'completed'+ || parent.metadata.worktreeBranch !== target.branch || parent.metadata.prCompletionPolicy === PR_COMPLETIONS.LEAVE_OPEN+ || !isPlainObject(link) || link.taskId !== agent.taskId || link.url !== target.url || link.branch !== target.branch+ || !parent.metadata.sourceWorkspace) return false;+ return repositoryKey(await getOriginInfo(parent.metadata.sourceWorkspace).catch(() => null)) === repository;+}+// Claim parents carry their registered claim binding; every other participant// must prove its registered target against live task and checkout state.-async function verifiedParticipant(agent, repository) {+async function verifiedParticipant(agent, repository, agents) {if (isTruthyMeta(agent.metadata?.claimPicksOwnBranch) || agent.metadata?.claimBranch) return true;+ if (isCleanupRecovery(agent)) return verifiedCleanupRecovery(agent, repository, agents);return await verifiedReviewCoordinator(agent, repository) || verifiedWorktreeDelivery(agent, repository);}@@ -265,7 +299,11 @@ export async function claimMergeAdmission({ agentId, action, token, outcome }) {if (!repository) return refuse('repository-unreadable');// Releasing an owned token must remain possible after merge deletes or// switches the checkout. Acquire/check still require the assigned target.- const participant = action === 'release' ? true : await measure('origin', () => verifiedParticipant(agent, repository));+ const participant = action === 'release' ? true : await measure('origin', () => verifiedParticipant(agent, repository, state.agents));+ if (!participant && isCleanupRecovery(agent)) {+ return { admitted: false, reason: 'recovery-merge-target-unverified', retryable: false,+ message: 'Leave the PR and branch intact and report this blocker: this recovery has no verified registered parent PR target. Retrying cannot change that; only a freshly filed recovery can.' };+ }if (!participant) {const task = await liveTask(agent);if (agent.metadata?.reviewLoopMergeTarget?.fork || (task?.taskType === 'internal'