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 verified review coordinators admit repository merges (#11314)
[._.]/ Adam Eivy9f3de745e664
diff --git a/server/lib/agentRegistrationRecord.js b/server/lib/agentRegistrationRecord.jsindex d20d2405cd..534041746f 100644--- a/server/lib/agentRegistrationRecord.js+++ b/server/lib/agentRegistrationRecord.js@@ -273,6 +273,13 @@ export function buildAgentRegistration({// agent, so `workspacePath` never names it; a later relaunch of that claim// reads these at launch to see that a live owner holds the checkout....claimOwnershipBinding(task),+ // Snapshot the assigned follow-up target at registration. Admission also+ // checks the persisted internal task and checkout; a prompt is never a grant.+ reviewLoopMergeTarget: task.taskType === 'internal'+ && isTruthyMeta(task.metadata?.reviewLoopFollowUp)+ && !isTruthyMeta(task.metadata?.reviewLoopLeaveOpen)+ ? { url: task.metadata.reviewLoopPRUrl, branch: task.metadata.reviewLoopPRBranch }+ : null,configSimplify: isTruthyMeta(task.metadata?.simplify),configReviewLoop: isTruthyMeta(task.metadata?.reviewLoop),configReviewers: normalizeReviewers(task.metadata),diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.jsindex 43c3f12c8f..c869832fc7 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -41,6 +41,7 @@ import {buildActionOutputCompletionSection,buildAuditOutputCompletionSection,buildClaimFlowCompletionSection,+ buildMergeAdmissionSection,buildClaimResumeOverride,claimResumeContext,buildReleaseFlowCompletionSection,@@ -750,6 +751,7 @@ After your task completes, the system will spawn a follow-up agent that runs the// top of buildAgentPrompt under the same reviewLoopFollowUp guard — reuse it// rather than re-reading the lib a second time.reviewLoopFollowUpSection = buildReviewLoopFollowUpSection(task.metadata || {}, { verbose: true, rprBody, localAgentLoopBody });+ if (!isTruthyMeta(task.metadata?.reviewLoopLeaveOpen)) reviewLoopFollowUpSection += '\n\n' + buildMergeAdmissionSection(agentId);if (isTui) {const sentinelPath = resolveSentinelPath(worktreeInfo, workspaceDir, agentId);const branchName = worktreeInfo?.branchName || task.metadata?.reviewLoopPRBranch || null;@@ -1110,6 +1112,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, { isTui = t[COMPLETION_MODES.READ_ONLY]: () => contractSections.push(buildReadOnlyCompletionSection({ isTui, sentinelPath: lightSentinelPath() })),[COMPLETION_MODES.REVIEW_LOOP_FOLLOW_UP]: () => {contractSections.push(buildReviewLoopFollowUpSection(task.metadata || {}, { verbose: false, localAgentLoopBody, forgeCli: resolvedForgeCli }));+ if (!isTruthyMeta(task.metadata?.reviewLoopLeaveOpen)) contractSections.push(buildMergeAdmissionSection(agentId));if (!isTui) return;const branchName = worktreeInfo?.branchName || task.metadata?.reviewLoopPRBranch || null;const sentinelTail = branchName ? ` ## Branch\n ${branchName}` : ' ## Branch\n <branch name>';diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex 827e49ee1e..2ac0f4954f 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -1130,6 +1130,7 @@ describe('buildLightContextPrompt', () => {'/r',{ branchName: 'b', worktreePath: '/tmp/wt' });expect(prompt).toMatch(/## Review-Loop Follow-up/);+ expect(prompt).not.toContain('## Repository merge admission');// The review still runs — only the merge is withheld.expect(prompt).toMatch(/codex/);expect(prompt).toMatch(/leave the PR open/i);@@ -1953,8 +1954,11 @@ describe('buildLightContextPrompt', () => {}}),'/r',{ branchName: 'b', worktreePath: '/tmp/wt' },- { defaultReviewers: ['copilot'] });+ { defaultReviewers: ['copilot'], agentId: 'registered-coordinator' });expect(prompt).toMatch(/## Review-Loop Follow-up/);+ expect(prompt).toContain('## Repository merge admission');+ expect(prompt).toContain('--match-head-commit <sha>');+ expect(prompt).toContain('/api/cos/merge-admission');expect(prompt).toMatch(/task-src-1/);expect(prompt).toMatch(/gh pr merge "https:\/\/github\.com\/o\/r\/pull\/9" --merge --delete-branch/);// --auto must NOT appear inside any `gh pr merge` invocation — it defersdiff --git a/server/services/cosMergeAdmission.js b/server/services/cosMergeAdmission.jsindex 386634705f..bc09fa6fed 100644--- a/server/services/cosMergeAdmission.js+++ b/server/services/cosMergeAdmission.js@@ -6,6 +6,7 @@import { randomUUID } from 'node:crypto';import { getOriginInfo } from '../lib/gitRemote.js';import { isPlainObject } from '../lib/objects.js';+import { parsePullRequestUrl } from '../lib/gitForge.js';import { isTruthyMeta } from '../lib/metadataFlags.js';const retryAfterMs = 5000;@@ -139,17 +140,44 @@ async function admit(state, save, repository, owner, measure) {return { admitted: true, token: lease.token, repository };}+// Review-loop authority comes from the registered launch AND its live internal+// task. Never accept a repository/branch from the admission request or PR prose.+async function verifiedReviewCoordinator(agent, repository) {+ const target = agent.metadata?.reviewLoopMergeTarget;+ if (!isPlainObject(target) || typeof target.branch !== 'string' || !target.branch) return false;+ const { getTaskById } = await import('./cosTaskStore.js');+ const task = await getTaskById(agent.taskId).catch(() => null);+ const meta = task?.metadata;+ if (task?.id !== agent.taskId || task.taskType !== 'internal'+ || ['completed', 'failed', 'cancelled'].includes(task.status)+ || !isTruthyMeta(meta?.reviewLoopFollowUp) || isTruthyMeta(meta?.reviewLoopLeaveOpen)+ || meta?.forkHead || 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;+ const workspace = agent.metadata.workspacePath;+ if (repositoryKey(await getOriginInfo(workspace).catch(() => null)) !== repository) return false;+ const { execGit } = await import('../lib/execGit.js');+ const checkout = await execGit(['symbolic-ref', '--quiet', '--short', 'HEAD'], workspace).catch(() => null);+ return checkout?.stdout?.trim() === target.branch;+}+/** The ID is the registered parent, never a worker-child ID or a cwd PID. */export async function claimMergeAdmission({ agentId, action, token, outcome }) {return transaction(async (state, save, measure) => {const agent = state.agents[agentId];- if (!agent || agent.id !== agentId || agent.status !== 'running' || !agent.startedAt || !agent.taskId- || !(isTruthyMeta(agent.metadata?.claimPicksOwnBranch) || agent.metadata?.claimBranch)) {+ if (!agent || agent.id !== agentId || agent.status !== 'running' || !agent.startedAt || !agent.taskId) {return refuse('claim-owner-unverified');}if (!ownerPath(agent)) return refuse('repository-unreadable');const repository = repositoryKey(await measure('origin', () => getOriginInfo(ownerPath(agent)).catch(() => null)));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' && !(isTruthyMeta(agent.metadata?.claimPicksOwnBranch) || agent.metadata?.claimBranch)+ && !await measure('origin', () => verifiedReviewCoordinator(agent, repository))) return refuse('claim-owner-unverified');if (action === 'acquire') {if (Object.entries(state.mergeAdmissions).some(([key, held]) =>!validLease(held, key) || (held.agentId === agentId && (!sameAgent(held, agent) || key !== repository)))) {diff --git a/server/services/cosMergeAdmission.reviewCoordinator.test.js b/server/services/cosMergeAdmission.reviewCoordinator.test.jsnew file mode 100644index 0000000000..4ea79c8947--- /dev/null+++ b/server/services/cosMergeAdmission.reviewCoordinator.test.js@@ -0,0 +1,101 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+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' }));+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('./cosEvents.js', () => ({ cosEvents: { emit: vi.fn() }, emitLog: vi.fn() }));+vi.mock('./cos.js', () => ({+ addTask: async task => { f.tasks[task.id] = { ...parseTasksMarkdown(generateTasksMarkdown([task]))[0], taskType: 'internal' }; return task; },+ 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() }));+import { spawnReviewLoopFollowUp } from './agentWorktreeCleanup.js';+import { buildAgentRegistration } from '../lib/agentRegistrationRecord.js';+import { registerAgent } from './cosAgentLifecycle.js';+import { claimMergeAdmission, withPendingMergeAdmission } from './cosMergeAdmission.js';++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' },+ prUrl: 'https://github.com/example/repo/pull/42', prBranch: 'feature/fix',+ sourceWorkspace: '/repos/source', reviewers: [], ...overrides });+ const persisted = f.tasks[task.id];+ const metadata = buildAgentRegistration({ task: persisted, provider: { id: 'test' }, modelSelection: {},+ sourceWorkspace: '/repos/source', workspacePath: '/repos/worktree', worktreeInfo: { branchName: 'feature/fix' } });+ await registerAgent('review-agent', task.id, metadata);+ return persisted;+}+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();+});++describe('registered review-loop merge coordinator', () => {+ it('creates and registers a non-claim follow-up that acquires, checks and releases repository admission', async () => {+ await launch();+ expect(f.state.agents['review-agent'].metadata.claimPicksOwnBranch).not.toBe(true);+ const lease = await admission('acquire');+ expect(lease).toMatchObject({ admitted: true, repository: 'github.com/example/repo' });+ expect(await admission('check', lease.token)).toMatchObject({ admitted: true });+ f.branch = 'main'; // gh may switch away after deleting the merged branch.+ expect(await admission('release', lease.token, { outcome: 'merged' })).toMatchObject({ released: true });+ expect(f.disk.mergeAdmissions).toEqual({});+ });++ it('preserves active claim and sweep lease exclusion in both directions', async () => {+ await launch();+ 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' });+ await withPendingMergeAdmission({ host: 'github.com', fullName: 'example/repo' }, async () => {+ expect(await admission('acquire')).toMatchObject({ admitted: false, reason: 'owner-active-or-unverified' });+ });+ const review = await admission('acquire');+ expect((await claimMergeAdmission({ agentId: 'claim', action: 'acquire' })).admitted).toBe(false);+ expect((await withPendingMergeAdmission({ host: 'github.com', fullName: 'example/repo' }, vi.fn())).admitted).toBe(false);+ 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();+ 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' };+ persist();+ expect(await admission('acquire', undefined, { repository: 'github.com/example/repo', branch: 'feature/fix' }))+ .toMatchObject({ admitted: false, reason: 'claim-owner-unverified' });+ expect(f.disk.mergeAdmissions).toEqual({});+ });+});diff --git a/server/services/promptSections/completion.js b/server/services/promptSections/completion.jsindex aede181669..ce891bdb9b 100644--- a/server/services/promptSections/completion.js+++ b/server/services/promptSections/completion.js@@ -592,7 +592,7 @@ function buildClaimOwnershipSection(agentId) {* Only the registered parent acquires, and only around the final verify-and-merge:* sync, pregate, push and CI run concurrently across runs (#10803).*/-function buildMergeAdmissionSection(agentId) {+export function buildMergeAdmissionSection(agentId) {if (!agentId) return 'Merge admission requires a registered parent agent ID. If none was supplied, leave the reviewed PR open and report this missing ownership binding; do not merge.';const command = (action, extra = {}) => agentApiCurl({ apiBase: localApiBaseUrl(), path: '/api/cos/merge-admission',payload: JSON.stringify({ agentId, action, ...extra }) });