Skip to content

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

Authorize verified fork review coordinators through merge admission (#11555)

[._.]/45825b356c90
diff --git a/server/lib/agentRegistrationRecord.js b/server/lib/agentRegistrationRecord.js
index b30557d9e6..3a57459603 100644
--- a/server/lib/agentRegistrationRecord.js
+++ b/server/lib/agentRegistrationRecord.js
@@ -283,7 +283,11 @@ export function buildAgentRegistration({
reviewLoopMergeTarget: task.taskType === 'internal'
&& isTruthyMeta(task.metadata?.reviewLoopFollowUp)
&& !isTruthyMeta(task.metadata?.reviewLoopLeaveOpen)
- ? { url: task.metadata.reviewLoopPRUrl, branch: task.metadata.reviewLoopPRBranch }
+ ? { url: task.metadata.reviewLoopPRUrl, branch: task.metadata.reviewLoopPRBranch,
+ ...(task.metadata.forkHead ? {
+ workspacePath,
+ fork: task.metadata.reviewLoopForkTarget ? structuredClone(task.metadata.reviewLoopForkTarget) : null,
+ } : {}) }
: null,
// Generic PR delivery (#11435): the worktree PortOS just provisioned and its
// head branch, stamped only when this run's prompt carries the merge
diff --git a/server/services/README.md b/server/services/README.md
index bbcaabdcc5..a475e870ee 100644
--- a/server/services/README.md
+++ b/server/services/README.md
@@ -29,3 +29,4 @@ image-generation paths below are useful entry points when tracing render jobs.
| `fableLoom/production.js` | FableLoom production render planning and enqueueing. |
| `appProcessTypes.js` | Dependency-free managed-app process-type vocabulary and PM2/desktop predicates. |
| `appProcessStatus.js` | PM2-backed managed-app status projections, expected-exit policy, and custom PM2 home resolution. |
+| `forkReviewMergeTarget.js` | Captures a fresh fork review target from the base repository’s live PR; admission verifies the registered target, live task, exact checkout head, fork remote/upstream and live forge identity. |
diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.js
index fe88fdbac1..71becf7b9b 100644
--- a/server/services/agentWorktreeCleanup.js
+++ b/server/services/agentWorktreeCleanup.js
@@ -1187,6 +1187,10 @@ export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, p
const firstLine = sourceTaskDesc.split(/[\r\n]/).find(l => l.trim()) || sourceTaskDesc;
const followUpTitle = `[${kind.title}] ${firstLine.trim().substring(0, 80)} (${prUrl})`;
+ const reviewLoopForkTarget = forkHead && !leaveOpen
+ ? await (await import('./forkReviewMergeTarget.js')).captureForkReviewMergeTarget({ prUrl, prBranch, forkHead, sourceWorkspace })
+ : null;
+
const followUpTaskId = `sys-rl-${Date.now().toString(36)}`;
const followUpTask = {
id: followUpTaskId,
@@ -1223,6 +1227,7 @@ export async function spawnReviewLoopFollowUp({ originalAgentId, originalTask, p
// shared reader is `resolveTaskForkHead`, so this key is the generic
// `forkHead` rather than a review-loop-specific one.
forkHead: normalizeForkHead(forkHead),
+ reviewLoopForkTarget,
reviewLoopPRNumber: parsedPr?.number ?? null,
reviewLoopPRHost: parsedPr?.host ?? null,
reviewLoopPROwner: parsedPr?.owner ?? null,
diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.js
index 574d29c9e9..be510606c4 100644
--- a/server/services/cleanupAgentWorktree.test.js
+++ b/server/services/cleanupAgentWorktree.test.js
@@ -1994,24 +1994,6 @@ describe('spawnReviewLoopFollowUp', () => {
expect(addTask.mock.calls[0][0].metadata.app).toBe('example-app');
});
- it('persists fork coordinates so the follow-up can attach a worktree to a fork PR head (#6064)', async () => {
- // A fork head has no `origin/<branch>`, so without these the follow-up is
- // queued and then blocked at workspace prep. The key is the generic
- // `forkHead` that `resolveTaskForkHead` reads for every producer.
- await spawnReviewLoopFollowUp({
- originalAgentId: 'agent-1',
- originalTask: { id: 'task-1', metadata: {}, description: 'X' },
- prUrl: 'https://github.com/o/r/pull/9',
- prBranch: 'contributor/fix-thing',
- forkHead: { remoteUrl: 'https://github.com/contributor/r.git', ownerLogin: 'contributor' },
- sourceWorkspace: '/ws',
- });
- expect(addTask.mock.calls[0][0].metadata).toMatchObject({
- reviewLoopPRBranch: 'contributor/fix-thing',
- forkHead: { remoteUrl: 'https://github.com/contributor/r.git', ownerLogin: 'contributor' },
- });
- });
-
it('stores null fork coordinates for a same-repo PR branch', async () => {
await spawnReviewLoopFollowUp({
originalAgentId: 'agent-1',
diff --git a/server/services/cosMergeAdmission.js b/server/services/cosMergeAdmission.js
index e75f21fcbd..0dda82ffb6 100644
--- a/server/services/cosMergeAdmission.js
+++ b/server/services/cosMergeAdmission.js
@@ -168,13 +168,22 @@ async function verifiedReviewCoordinator(agent, repository) {
const meta = task?.metadata;
if (!task || task.taskType !== 'internal'
|| !isTruthyMeta(meta?.reviewLoopFollowUp) || isTruthyMeta(meta?.reviewLoopLeaveOpen)
- || meta?.forkHead || target.url !== meta?.reviewLoopPRUrl || target.branch !== meta?.reviewLoopPRBranch
+ || resolvePrCompletion(meta) === PR_COMPLETIONS.LEAVE_OPEN || agent.metadata?.prCompletionPolicy === PR_COMPLETIONS.LEAVE_OPEN
+ || target.url !== meta?.reviewLoopPRUrl || target.branch !== meta?.reviewLoopPRBranch
|| agent.metadata?.worktreeBranch !== target.branch || !agent.metadata?.workspacePath) return false;
const pr = parsePullRequestUrl(target.url);
if (!pr || repositoryKey({ host: pr.host, fullName: `${pr.owner}/${pr.repo}` }) !== repository
|| String(meta.reviewLoopPRNumber) !== String(pr.number)
|| meta.reviewLoopPRHost !== pr.host || meta.reviewLoopPROwner !== pr.owner || meta.reviewLoopPRRepo !== pr.repo) return false;
- return checkoutOnBranch(agent.metadata.workspacePath, target.branch, repository);
+ if (!await checkoutOnBranch(agent.metadata.workspacePath, target.branch, repository)) return false;
+ if (!meta.forkHead && !meta.reviewLoopForkTarget && !target.fork && !target.workspacePath) return true;
+ if (target.workspacePath !== agent.metadata.workspacePath || !agent.metadata.sourceWorkspace
+ || agent.metadata.sourceWorkspace === target.workspacePath || target.fork?.url !== target.url) return false;
+ const { verifyForkReviewMergeTarget } = await import('./forkReviewMergeTarget.js');
+ const headSha = await verifyForkReviewMergeTarget({ target: target.fork, taskTarget: meta.reviewLoopForkTarget,
+ forkHead: meta.forkHead, sourceWorkspace: agent.metadata.sourceWorkspace,
+ workspacePath: target.workspacePath, branch: target.branch });
+ return headSha ? { headSha } : false;
}
// Generic PR delivery (#11435): an operator-configured task whose prompt told
@@ -221,7 +230,14 @@ 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.
- if (action !== 'release' && !await measure('origin', () => verifiedParticipant(agent, repository))) {
+ const participant = action === 'release' ? true : await measure('origin', () => verifiedParticipant(agent, repository));
+ if (!participant) {
+ const task = await liveTask(agent);
+ if (agent.metadata?.reviewLoopMergeTarget?.fork || (task?.taskType === 'internal'
+ && isTruthyMeta(task.metadata?.reviewLoopFollowUp) && task.metadata?.forkHead)) {
+ return { admitted: false, reason: 'fork-review-target-unverified', retryable: false,
+ message: 'Leave the PR/worktree intact. Verify the live PR head, base, fork remote and upstream; old or changed targets require a fresh supported follow-up.' };
+ }
return refuse('claim-owner-unverified');
}
if (action === 'acquire') {
@@ -229,7 +245,10 @@ export async function claimMergeAdmission({ agentId, action, token, outcome }) {
!validLease(held, key) || (held.agentId === agentId && (!sameAgent(held, agent) || key !== repository)))) {
return refuse('lease-owner-mismatch');
}
- return admit(state, save, repository, { kind: 'agent', ...binding(agent) }, measure);
+ const held = state.mergeAdmissions[repository];
+ if (participant.headSha && held?.agentId === agentId && !expired(held) && held.headSha !== participant.headSha) return refuse('lease-head-changed');
+ return admit(state, save, repository, { kind: 'agent', ...binding(agent),
+ ...(participant.headSha ? { headSha: participant.headSha } : {}) }, measure);
}
const lease = state.mergeAdmissions[repository];
if (!validLease(lease, repository) || lease.kind !== 'agent' || !sameAgent(lease, agent) || lease.token !== token) {
@@ -237,6 +256,7 @@ export async function claimMergeAdmission({ agentId, action, token, outcome }) {
}
// An expired holder must stop and re-acquire before merging; releasing
// its own still-unclaimed lease stays permitted.
+ if (action === 'check' && participant.headSha && lease.headSha !== participant.headSha) return refuse('lease-head-changed');
if (action === 'check') return expired(lease) ? refuse('lease-expired') : { admitted: true, token, repository };
if (action !== 'release' || !MERGE_ADMISSION_OUTCOMES.includes(outcome)) return refuse('outcome-required');
delete state.mergeAdmissions[repository];
diff --git a/server/services/cosMergeAdmission.reviewCoordinator.test.js b/server/services/cosMergeAdmission.reviewCoordinator.test.js
index 4ea79c8947..bb892ac585 100644
--- a/server/services/cosMergeAdmission.reviewCoordinator.test.js
+++ b/server/services/cosMergeAdmission.reviewCoordinator.test.js
@@ -3,7 +3,7 @@ import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
import { generateTasksMarkdown, parseTasksMarkdown } from '../lib/taskParser.js';
import { parsePullRequestUrl } from '../lib/gitForge.js';
-const f = vi.hoisted(() => ({ state: null, disk: null, tasks: {}, branch: 'feature/fix', workspaceRepo: 'example/repo' }));
+const f = vi.hoisted(() => ({ state: null, disk: null, tasks: {}, branch: 'feature/fix', workspaceRepo: 'example/repo', originHost: 'github.com', row: null, head: null, upstream: null, remote: null, pushRemote: null }));
vi.mock('./cosState.js', () => ({
AGENTS_DIR: '/synthetic/agents',
withStateLock: createFileWriteQueue(),
@@ -17,10 +17,31 @@ vi.mock('./cos.js', () => ({
forceSpawnTask: vi.fn(), getAgents: async () => [], updateTask: vi.fn(),
}));
vi.mock('./cosTaskStore.js', () => ({ getTaskById: async id => f.tasks[id] }));
-vi.mock('../lib/gitRemote.js', () => ({ getOriginInfo: async path => ({ host: 'github.com', fullName: path === '/repos/worktree' ? f.workspaceRepo : 'example/repo' }) }));
-vi.mock('../lib/execGit.js', () => ({ execGit: async () => ({ stdout: f.branch, exitCode: 0 }) }));
-vi.mock('./git.js', () => ({ parsePullRequestUrl }));
-vi.mock('./worktreeManager.js', () => ({ removeWorktree: vi.fn(), classifyWorktreeDirt: vi.fn(), listWorktrees: vi.fn() }));
+vi.mock('../lib/gitRemote.js', async importOriginal => ({ ...(await importOriginal()),
+ getOriginInfo: async path => ({ host: f.originHost, fullName: path === '/repos/worktree' ? f.workspaceRepo : 'example/repo' }) }));
+vi.mock('./github.js', () => ({ execGh: vi.fn(async () => JSON.stringify(f.row)) }));
+vi.mock('./forgeExecOptions.js', () => ({ resolveForgeExecOptions: async () => ({ cwd: '/repos/source', env: {} }) }));
+vi.mock('./apps.js', () => ({ getAppById: async () => null }));
+vi.mock('./agentAppWorkspace.js', () => ({ getAppWorkspace: async () => '/repos/source', getAppDataForTask: async () => null }));
+vi.mock('../lib/spawnCwd.js', async importOriginal => ({ ...(await importOriginal()), resolveSpawnCwd: path => path }));
+vi.mock('./taskConflict.js', () => ({ detectConflicts: vi.fn() }));
+vi.mock('../lib/execGit.js', () => ({ execGit: async args => {
+ let stdout;
+ if (args[0] === 'symbolic-ref') stdout = f.branch;
+ if (args[0] === 'rev-parse') stdout = f.head;
+ if (args[0] === 'remote') stdout = args.includes('--push') ? f.pushRemote : f.remote;
+ if (args[0] === 'config') stdout = args[2].endsWith('.remote') ? f.upstream.remote : f.upstream.merge;
+ if (typeof stdout !== 'string') throw new Error('unreadable git fixture');
+ return { stdout, exitCode: 0 };
+} }));
+vi.mock('./git.js', () => ({ parsePullRequestUrl, getRepoBranches: async () => ({ baseBranch: 'main' }) }));
+vi.mock('./worktreeManager.js', () => ({ removeWorktree: vi.fn(), classifyWorktreeDirt: vi.fn(),
+ listWorktrees: async () => [], findAdoptableWorktreeForBranch: async () => null, releaseIdleSiblingNextHolder: async () => null,
+ createWorktree: vi.fn(async (_agent, _workspace, _task, options) => ({ worktreePath: '/repos/worktree', branchName: options.existingBranch })),
+}));
+import { prepareAgentWorkspace } from './agentWorkspacePrep.js';
+import { createWorktree } from './worktreeManager.js';
+import { execGh } from './github.js';
import { spawnReviewLoopFollowUp } from './agentWorktreeCleanup.js';
import { buildAgentRegistration } from '../lib/agentRegistrationRecord.js';
import { registerAgent } from './cosAgentLifecycle.js';
@@ -28,19 +49,29 @@ import { claimMergeAdmission, withPendingMergeAdmission } from './cosMergeAdmiss
const admission = (action, token, extra = {}) => claimMergeAdmission({ agentId: 'review-agent', action, token, ...extra });
async function launch(overrides = {}) {
- const task = await spawnReviewLoopFollowUp({ originalAgentId: 'original', originalTask: { id: 'original-task' },
+ const task = await spawnReviewLoopFollowUp({ originalAgentId: 'original', originalTask: { id: 'original-task', metadata: { app: 'synthetic-app' } },
prUrl: 'https://github.com/example/repo/pull/42', prBranch: 'feature/fix',
sourceWorkspace: '/repos/source', reviewers: [], ...overrides });
const persisted = f.tasks[task.id];
+ const workspace = await prepareAgentWorkspace({ agentId: 'review-agent', task: persisted });
+ expect(workspace.outcome).toBe('ready');
const metadata = buildAgentRegistration({ task: persisted, provider: { id: 'test' }, modelSelection: {},
- sourceWorkspace: '/repos/source', workspacePath: '/repos/worktree', worktreeInfo: { branchName: 'feature/fix' } });
+ sourceWorkspace: '/repos/source', workspacePath: workspace.workspacePath, worktreeInfo: workspace.worktreeInfo });
await registerAgent('review-agent', task.id, metadata);
return persisted;
}
+const forkHead = { remoteUrl: 'https://github.com/contributor/repo.git', ownerLogin: 'contributor' };
const persist = () => { f.disk = structuredClone(f.state); };
beforeEach(() => {
f.state = { agents: {}, mergeAdmissions: {}, stats: { agentsSpawned: 0 } };
- f.tasks = {}; f.branch = 'feature/fix'; f.workspaceRepo = 'example/repo'; persist();
+ vi.clearAllMocks();
+ f.tasks = {}; f.branch = 'feature/fix'; f.workspaceRepo = 'example/repo'; f.originHost = 'github.com';
+ f.head = 'a'.repeat(40); f.remote = forkHead.remoteUrl; f.pushRemote = f.remote;
+ f.upstream = { remote: 'fork-contributor', merge: 'refs/heads/feature/fix' };
+ f.row = { url: 'https://github.com/example/repo/pull/42', number: 42, state: 'OPEN', headRefName: f.branch,
+ headRefOid: f.head, baseRefName: 'main', isCrossRepository: true,
+ headRepository: { id: 'fork-id', nameWithOwner: 'contributor/repo', name: 'repo' }, headRepositoryOwner: { login: 'contributor' } };
+ persist();
});
describe('registered review-loop merge coordinator', () => {
@@ -55,8 +86,8 @@ describe('registered review-loop merge coordinator', () => {
expect(f.disk.mergeAdmissions).toEqual({});
});
- it('preserves active claim and sweep lease exclusion in both directions', async () => {
- await launch();
+ it.each([null, forkHead])('preserves active claim and sweep lease exclusion for %j', async forkHead => {
+ await launch({ forkHead });
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' });
@@ -71,31 +102,116 @@ describe('registered review-loop merge coordinator', () => {
await admission('release', review.token, { outcome: 'merged' });
});
- it.each(['absent-agent', 'completed-agent', 'absent-task', 'completed-task', 'user-task', 'unregistered-target',
- 'changed-target', 'unrelated-pr', 'unrelated-workspace', 'changed-checkout', 'changed-registration', 'leave-open', 'fork'])
- ('refuses %s despite caller-supplied repository and branch claims', async mode => {
- const task = await launch();
+ describe.each([null, forkHead])('participant liveness and binding with fork %j', forkHead => {
+ it.each(['absent-agent', 'completed-agent', 'absent-task', 'completed-task', 'user-task', 'unregistered-target',
+ 'changed-target', 'unrelated-pr', 'unrelated-workspace', 'changed-checkout', 'changed-registration', 'leave-open', 'leave-open-policy'])
+ ('refuses %s despite caller-supplied repository and branch claims', async mode => {
+ const task = await launch({ forkHead });
+ const agent = f.state.agents['review-agent'];
+ if (mode === 'absent-agent') delete f.state.agents['review-agent'];
+ if (mode === 'completed-agent') agent.status = 'completed';
+ if (mode === 'absent-task') delete f.tasks[task.id];
+ if (mode === 'completed-task') task.status = 'completed';
+ if (mode === 'user-task') task.taskType = 'user';
+ if (mode === 'unregistered-target') delete agent.metadata.reviewLoopMergeTarget;
+ if (mode === 'changed-target') task.metadata.reviewLoopPRBranch = 'other';
+ if (mode === 'unrelated-pr') {
+ task.metadata.reviewLoopPRUrl = 'https://github.com/example/other/pull/42';
+ task.metadata.reviewLoopPRRepo = 'other';
+ agent.metadata.reviewLoopMergeTarget.url = task.metadata.reviewLoopPRUrl;
+ }
+ if (mode === 'unrelated-workspace') f.workspaceRepo = 'example/other';
+ if (mode === 'changed-checkout') f.branch = 'another/branch';
+ if (mode === 'changed-registration') agent.metadata.worktreeBranch = 'another/branch';
+ if (mode === 'leave-open') task.metadata.reviewLoopLeaveOpen = true;
+ if (mode === 'leave-open-policy') task.metadata.prCompletion = 'leave-open';
+ persist();
+ expect(await admission('acquire', undefined, { repository: 'github.com/example/repo', branch: 'feature/fix' }))
+ .toMatchObject({ admitted: false });
+ expect(f.disk.mergeAdmissions).toEqual({});
+ });
+ });
+});
+
+describe('fork follow-up creation through workspace, registration and admission', () => {
+ it('admits the verified fork exact head under the base repository and excludes a same-repository coordinator', async () => {
+ await launch({ forkHead });
+ expect(createWorktree).toHaveBeenCalledWith('review-agent', '/repos/source', expect.any(String), expect.objectContaining({ forkHead, existingBranch: 'feature/fix' }));
+ const forkLease = await admission('acquire');
+ expect(forkLease).toMatchObject({ admitted: true, repository: 'github.com/example/repo' });
+ expect(f.disk.mergeAdmissions[forkLease.repository].headSha).toBe(f.head);
+ expect(await admission('check', forkLease.token)).toMatchObject({ admitted: true });
+ // Another same-repository coordinator cannot enter while the fork holds.
+ const same = structuredClone(f.state.agents['review-agent']);
+ same.id = 'same'; same.taskId = 'same-task';
+ same.metadata.reviewLoopMergeTarget = { url: f.row.url, branch: f.branch };
+ const sameTask = structuredClone(f.tasks[f.state.agents['review-agent'].taskId]);
+ sameTask.id = same.taskId; delete sameTask.metadata.forkHead; delete sameTask.metadata.reviewLoopForkTarget;
+ f.tasks[sameTask.id] = sameTask; f.state.agents.same = same; persist();
+ expect((await claimMergeAdmission({ agentId: 'same', action: 'acquire' })).admitted).toBe(false);
+ await admission('release', forkLease.token, { outcome: 'merged' });
+ const sameLease = await claimMergeAdmission({ agentId: 'same', action: 'acquire' });
+ expect(sameLease.admitted).toBe(true);
+ expect((await admission('acquire')).admitted).toBe(false);
+ expect(execGh).toHaveBeenCalledWith(expect.arrayContaining(['--repo', 'github.com/example/repo']), 10000, expect.objectContaining({ cwd: '/repos/source' }));
+ });
+
+ it('accepts the alternate GitHub SSH endpoint for both source and worktree origins', async () => {
+ f.originHost = 'ssh.github.com';
+ f.remote = f.pushRemote = 'ssh://[email protected]:443/contributor/repo.git';
+ await launch({ forkHead });
+ const lease = await admission('acquire');
+ expect(lease).toMatchObject({ admitted: true, repository: 'github.com/example/repo' });
+ expect(await admission('check', lease.token)).toMatchObject({ admitted: true });
+ await admission('release', lease.token, { outcome: 'merged' });
+ });
+
+ it('allows a reviewed remediation head, but requires releasing a lease when its head changes', async () => {
+ await launch({ forkHead });
+ f.head = f.row.headRefOid = 'b'.repeat(40);
+ const lease = await admission('acquire');
+ expect(lease.admitted).toBe(true);
+ f.head = f.row.headRefOid = 'c'.repeat(40);
+ expect(await admission('check', lease.token)).toMatchObject({ admitted: false, reason: 'lease-head-changed' });
+ expect(await admission('acquire')).toMatchObject({ admitted: false, reason: 'lease-head-changed' });
+ await admission('release', lease.token, { outcome: 'resync' });
+ const renewed = await admission('acquire');
+ expect(renewed.admitted).toBe(true);
+ f.branch = 'main'; f.row = null;
+ expect(await admission('release', renewed.token, { outcome: 'merged' })).toMatchObject({ released: true });
+ });
+
+ it.each(['legacy', 'missing-registration', 'changed-task-fork', 'changed-base', 'changed-fork', 'recreated-fork', 'wrong-pr', 'closed-pr',
+ 'wrong-head', 'wrong-upstream', 'wrong-fetch-remote', 'wrong-push-remote', 'multiple-remotes', 'unreadable-forge', 'changed-workspace'])
+ ('refuses %s without granting a lease and reports an actionable stop', async mode => {
+ const task = await launch({ forkHead });
const agent = f.state.agents['review-agent'];
- if (mode === 'absent-agent') delete f.state.agents['review-agent'];
- if (mode === 'completed-agent') agent.status = 'completed';
- if (mode === 'absent-task') delete f.tasks[task.id];
- if (mode === 'completed-task') task.status = 'completed';
- if (mode === 'user-task') task.taskType = 'user';
- if (mode === 'unregistered-target') delete agent.metadata.reviewLoopMergeTarget;
- if (mode === 'changed-target') task.metadata.reviewLoopPRBranch = 'other';
- if (mode === 'unrelated-pr') {
- task.metadata.reviewLoopPRUrl = 'https://github.com/example/other/pull/42';
- task.metadata.reviewLoopPRRepo = 'other';
- agent.metadata.reviewLoopMergeTarget.url = task.metadata.reviewLoopPRUrl;
- }
- if (mode === 'unrelated-workspace') f.workspaceRepo = 'example/other';
- if (mode === 'changed-checkout') f.branch = 'another/branch';
- if (mode === 'changed-registration') agent.metadata.worktreeBranch = 'another/branch';
- if (mode === 'leave-open') task.metadata.reviewLoopLeaveOpen = true;
- if (mode === 'fork') task.metadata.forkHead = { owner: 'contributor', repo: 'repo', branch: 'feature/fix' };
+ if (mode === 'legacy') delete agent.metadata.reviewLoopMergeTarget.fork;
+ if (mode === 'missing-registration') delete agent.metadata.reviewLoopMergeTarget;
+ if (mode === 'changed-task-fork') task.metadata.forkHead.remoteUrl = 'https://github.com/other/repo.git';
+ if (mode === 'changed-base') f.row.baseRefName = 'release';
+ if (mode === 'changed-fork') f.row.headRepository.nameWithOwner = 'other/repo';
+ if (mode === 'recreated-fork') f.row.headRepository.id = 'replacement-id';
+ if (mode === 'wrong-pr') f.row.url = 'https://github.com/example/other/pull/42';
+ if (mode === 'closed-pr') f.row.state = 'CLOSED';
+ if (mode === 'wrong-head') f.head = 'b'.repeat(40);
+ if (mode === 'wrong-upstream') f.upstream.merge = 'refs/heads/main';
+ if (mode === 'wrong-fetch-remote') f.remote = 'https://github.com/other/repo.git';
+ if (mode === 'wrong-push-remote') f.pushRemote = 'https://github.com/example/repo.git';
+ if (mode === 'multiple-remotes') f.pushRemote += '\nhttps://github.com/other/repo.git';
+ if (mode === 'unreadable-forge') f.row = null;
+ if (mode === 'changed-workspace') agent.metadata.workspacePath = '/repos/other';
persist();
- expect(await admission('acquire', undefined, { repository: 'github.com/example/repo', branch: 'feature/fix' }))
- .toMatchObject({ admitted: false, reason: 'claim-owner-unverified' });
+ expect(await admission('acquire', undefined, { forkHead, headSha: f.head }))
+ .toMatchObject({ admitted: false, retryable: false, reason: 'fork-review-target-unverified', message: expect.stringContaining('fresh supported follow-up') });
+ expect(f.disk.mergeAdmissions).toEqual({});
+ });
+
+ it('does not create a task from invalid fork coordinates or an unrelated live PR', async () => {
+ await expect(launch({ forkHead: { remoteUrl: 'https://github.com/other/repo.git', ownerLogin: 'other' } })).rejects.toThrow('could not be verified');
+ f.row.url = 'https://github.com/example/other/pull/42';
+ await expect(launch({ forkHead })).rejects.toThrow('could not be verified');
+ expect(f.tasks).toEqual({});
expect(f.disk.mergeAdmissions).toEqual({});
});
});
diff --git a/server/services/forkReviewMergeTarget.js b/server/services/forkReviewMergeTarget.js
new file mode 100644
index 0000000000..691ab0896c
--- /dev/null
+++ b/server/services/forkReviewMergeTarget.js
@@ -0,0 +1,80 @@
+/** Fork review authority is captured from the forge, then rechecked at admission. */
+import { getOriginInfo, parseGitRemoteUrl } from '../lib/gitRemote.js';
+import { detectForgeCli, parsePullRequestUrl } from '../lib/gitForge.js';
+import { forkHeadFromGithubPr, forkRemoteName, normalizeForkHead } from '../lib/forkHead.js';
+import { execGit } from '../lib/execGit.js';
+import { readBranchUpstream } from '../lib/branchUpstreamGuard.js';
+import { safeJSONParse } from '../lib/jsonIo.js';
+
+const sha = value => typeof value === 'string' && /^[a-f0-9]{40}$/i.test(value);
+const repoKey = ({ host, owner, repo }) => `${host.replace(/^ssh\.github\.com$/i, 'github.com')}/${owner}/${repo}`.toLowerCase();
+const remoteKey = value => {
+ if (typeof value !== 'string' || !/^(https?:\/\/|ssh:\/\/|[\w.-]+@)/.test(value)) return null;
+ const parsed = parseGitRemoteUrl(value);
+ return parsed ? repoKey(parsed) : null;
+};
+const coordinatesMatch = (left, right) => {
+ const a = normalizeForkHead(left), b = normalizeForkHead(right);
+ return !!a && !!b && !!remoteKey(a.remoteUrl) && remoteKey(a.remoteUrl) === remoteKey(b.remoteUrl)
+ && a.ownerLogin.toLowerCase() === b.ownerLogin.toLowerCase();
+};
+
+async function readTarget(url, sourceWorkspace) {
+ const pr = parsePullRequestUrl(url);
+ if (!pr || detectForgeCli(pr.host) !== 'gh' || typeof sourceWorkspace !== 'string' || !sourceWorkspace) return null;
+ const origin = await getOriginInfo(sourceWorkspace).catch(() => null);
+ if (!origin?.host || `${origin.host.replace(/^ssh\.github\.com$/i, 'github.com')}/${origin.fullName}`.toLowerCase() !== repoKey(pr)) return null;
+ const [{ execGh }, { resolveForgeExecOptions }] = await Promise.all([
+ import('./github.js'), import('./forgeExecOptions.js'),
+ ]);
+ const options = await resolveForgeExecOptions(sourceWorkspace);
+ const raw = await execGh(['pr', 'view', String(pr.number), '--repo', `${pr.host}/${pr.owner}/${pr.repo}`,
+ '--json', 'url,number,state,headRefName,headRefOid,baseRefName,isCrossRepository,headRepository,headRepositoryOwner'], 10000, options).catch(() => null);
+ const row = safeJSONParse(raw, null);
+ const actual = parsePullRequestUrl(row?.url);
+ const forkHead = forkHeadFromGithubPr(row);
+ const fork = parseGitRemoteUrl(forkHead?.remoteUrl);
+ if (!actual || repoKey(actual) !== repoKey(pr) || actual.number !== pr.number || row.number !== pr.number
+ || row.state !== 'OPEN' || !fork || fork.host !== pr.host || repoKey(fork) === repoKey(pr)
+ || fork.owner.toLowerCase() !== forkHead.ownerLogin.toLowerCase()
+ || typeof row.headRepository?.id !== 'string' || !row.headRepository.id
+ || !sha(row.headRefOid) || typeof row.headRefName !== 'string' || !row.headRefName
+ || typeof row.baseRefName !== 'string' || !row.baseRefName) return null;
+ return { version: 1, url, branch: row.headRefName, baseBranch: row.baseRefName,
+ forkHead, headRepositoryId: row.headRepository.id, headSha: row.headRefOid };
+}
+
+/** Only fresh supported follow-ups receive this server-read target; never retrofit old runs. */
+export async function captureForkReviewMergeTarget({ prUrl, prBranch, forkHead, sourceWorkspace }) {
+ const target = await readTarget(prUrl, sourceWorkspace);
+ if (!target || target.branch !== prBranch || !coordinatesMatch(target.forkHead, forkHead)) {
+ throw new Error('Fork review merge target could not be verified against the base repository and live PR. Leave the PR/worktree intact and create a fresh follow-up after correcting its fork coordinates.');
+ }
+ // The head may advance during remediation. Admission re-reads it; only the
+ // repository, base branch and fork identity remain fixed for this follow-up.
+ const { headSha, ...binding } = target;
+ return binding;
+}
+
+/** Returns the live exact head only when task, registration, checkout and forge agree. */
+export async function verifyForkReviewMergeTarget({ target, taskTarget, forkHead, sourceWorkspace, workspacePath, branch }) {
+ if (!target || target.version !== 1 || JSON.stringify(target) !== JSON.stringify(taskTarget)
+ || target.branch !== branch || !coordinatesMatch(target.forkHead, forkHead)) return null;
+ const live = await readTarget(target.url, sourceWorkspace);
+ if (!live || live.branch !== branch || live.baseBranch !== target.baseBranch
+ || live.headRepositoryId !== target.headRepositoryId || !coordinatesMatch(live.forkHead, target.forkHead)) return null;
+ const upstream = await readBranchUpstream(workspacePath, branch);
+ const remote = forkRemoteName(target.forkHead.ownerLogin);
+ if (!remote || upstream.remote !== remote || upstream.merge !== `refs/heads/${branch}`) return null;
+ const read = args => execGit(args, workspacePath, { timeout: 10000 }).then(r => r.stdout.trim()).catch(() => null);
+ const [fetchUrl, pushUrl, head] = await Promise.all([
+ read(['remote', 'get-url', '--all', remote]), read(['remote', 'get-url', '--push', '--all', remote]),
+ read(['rev-parse', '--verify', 'HEAD']),
+ ]);
+ // Multiple URLs are ambiguous; each resolved fetch/push remote must name the
+ // registered fork. Never repair config or fetch inside the admission lease.
+ if (fetchUrl?.includes('\n') || pushUrl?.includes('\n')
+ || remoteKey(fetchUrl) !== remoteKey(target.forkHead.remoteUrl)
+ || remoteKey(pushUrl) !== remoteKey(target.forkHead.remoteUrl) || head !== live.headSha) return null;
+ return head;
+}
diff --git a/server/services/promptSections/completion.js b/server/services/promptSections/completion.js
index 3117ac020b..84de842958 100644
--- a/server/services/promptSections/completion.js
+++ b/server/services/promptSections/completion.js
@@ -601,7 +601,7 @@ export function buildMergeAdmissionSection(agentId) {
'Admission serializes only the merge instant. The parent orchestrator (never a fan-out child) completes publication, validation, configured reviews and required CI on its own head WITHOUT admission — other runs and every PR in a swarm do this concurrently. Never hold admission while syncing, running pregate, pushing or waiting for CI/reviews. Do not chase the default branch: rebase only for an actual conflict, an enforced up-to-date branch policy, or evidenced integration risk (inspect semantic overlap as well as textual conflicts). This overrides mandatory base-sync instructions in delegated slashdo workflows.',
'Once required CI is green on the exact head you pushed (record that SHA as the CI-verified head) and configured reviews are satisfied, acquire admission. Require a parsed JSON response with admitted:true and a nonempty token; retain that token privately for check/release:',
'```bash', command('acquire'), '```',
- 'If admitted:false, report the reason and wait retryAfterMs (5 seconds), with a progress update at least every minute. Retry for at most 10 minutes, then record a leave-open outcome and finish with the PR (and any claim) intact. A refusal is never a reason to merge without admission. An HTTP/auth/transport error, unreadable JSON, or missing admission is a refusal, never permission to proceed. Do not modify another owner’s branch, checkout or lease.',
+ 'If an acquire/check refusal names lease-head-changed, release your token with outcome resync before acquiring again. If admitted:false with retryable:false, release any owned token with outcome leave-open, stop retrying, report the reason and message, and leave the PR/worktree intact. Otherwise, if admitted:false, report the reason and wait retryAfterMs (5 seconds), with a progress update at least every minute. Retry for at most 10 minutes, then record a leave-open outcome and finish with the PR (and any claim) intact. A refusal is never a reason to merge without admission. An HTTP/auth/transport error, unreadable JSON, or missing admission is a refusal, never permission to proceed. Do not modify another owner’s branch, checkout or lease.',
'Inside the lease, re-read the PR (head SHA, merge state, required check rollup; on GitHub `gh pr view --json headRefOid,mergeStateStatus,statusCheckRollup`):',
'- If the head still equals the CI-verified head, every required check is green on it, and the forge reports the PR mergeable (`CLEAN`, or `UNSTABLE`/`HAS_HOOKS` with every required check green): check admission (replace TOKEN with the returned token; require admitted:true), then merge pinned to the CI-verified head — add `--match-head-commit <sha>` (GitLab: `--sha <sha>`) to every merge-method attempt your workflow lists; this pin is the one addition to a merge command that says to use exactly its flags. A base that moved while the PR stays `CLEAN` does NOT require a resync or fresh CI: the forge’s own merge check is authoritative, and post-merge default-branch CI catches semantic conflicts between two individually green PRs.',
'```bash', command('check', { token: 'TOKEN' }), '```',