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 generic CoS PR delivery acquire verified merge admission (#11435)
[._.]/ Adam Eivyca4190962c93
diff --git a/docs/features/chief-of-staff.md b/docs/features/chief-of-staff.mdindex fce505745d..61f81bb40b 100644--- a/docs/features/chief-of-staff.md+++ b/docs/features/chief-of-staff.md@@ -26,19 +26,45 @@ Autonomous agent manager that watches task files, spawns sub-agents, and maintai## Repository merge admission-Self-managed claim parents and the deterministic pending-merge sweep share one-repository-scoped merge-instant lease (`server/services/cosMergeAdmission.js`).-The host-control-gated `POST /api/cos/merge-admission` accepts the registered-parent agent ID and `acquire`, `check`, or `release`; check/release require the-returned token, and release records one of `merged`, `leave-open` or `resync`-in the parent's `lastMergeAdmission`. Repository identity comes from that-parent's registered source checkout and normalized origin host/repository, not-its child worktree path.+Every CoS run that lands its own pull request, plus the deterministic+pending-merge sweep, shares one repository-scoped merge-instant lease+(`server/services/cosMergeAdmission.js`). The host-control-gated+`POST /api/cos/merge-admission` accepts the registered parent agent ID and+`acquire`, `check`, or `release`; check/release require the returned token, and+release records one of `merged`, `leave-open` or `resync` in the parent's+`lastMergeAdmission`. Repository identity comes from that parent's registered+source checkout and normalized origin host/repository, not its child worktree+path, and never from the request.++Acquire and check admit only a live (`running`) registered agent that is one of+these participants; anything else is refused with `claim-owner-unverified`:++- **Claim parent** — its registered claim binding (`claimBranch` or+ `claimPicksOwnBranch`; see [Claim branch ownership](#claim-branch-ownership)).+- **Review-loop coordinator** — an internal review/merge follow-up whose+ registered `reviewLoopMergeTarget` still matches its live task's PR URL,+ number and branch, and whose worktree is on that branch of this repository.+- **Generic PR delivery** (#11435) — an operator-configured task whose prompt+ told it to open and merge its own PR from the worktree PortOS provisioned+ (`/do:pr` plus the CI merge gate, or the inline `git`/forge lifecycle). The+ spawner stamps `prDeliveryTarget` — that worktree path and head branch — from+ the same decision that put the admission section in the prompt. Admission+ then requires the agent record to still name that worktree and branch with+ agent-owned PR delivery, the live task to still be unfinished with `openPR`+ on and a completion policy that merges (not leave-open, a JIRA handoff, a+ review follow-up or a fork head), and the worktree's origin and checked-out+ branch to match. The PR target is the one whose head is that registered+ branch in this repository. A generic run never gains claim authority, and its+ `/do:pr` runs with `--no-merge` so no saved slashdo default merges outside+ the lease.++Release needs only the owned token, so a lease cannot strand after the merge+deletes or switches the checkout.The lease spans only the final verify-and-merge (#10803). Base sync, pregate,-push and the required-CI wait run concurrently across claim runs and across-every PR in a swarm, without admission. Once required CI is green on the exact-pushed head, the parent acquires, re-reads the PR, and:+push and the required-CI wait run concurrently across participating runs and+across every PR in a swarm, without admission. Once required CI is green on the+exact pushed head, the parent acquires, re-reads the PR, and:- merges pinned to that CI-verified head (`gh pr merge --match-head-commit`,GitLab `glab mr merge --sha`) when the forge reports it mergeable (`CLEAN`),@@ -52,8 +78,8 @@ CI run: the forge's merge check is authoritative, as it is for manual merges.The remaining exposure is a semantic conflict between two individually greenPRs, which post-merge default-branch CI catches — the same exposure manual andcross-install merges already carry. A refused acquire retries every 5 seconds-and reports progress every minute; after 10 minutes the reviewed PR and claim-are left open. Sweep deferrals preserve their retry budget; the sweep already+and reports progress every minute; after 10 minutes the reviewed PR (and any+claim) is left open — a refusal is never permission to merge without admission. Sweep deferrals preserve their retry budget; the sweep alreadyholds the lease only around its own read → assess → pinned merge.Leases extend the existing machine-local CoS runtime ownership indiff --git a/server/lib/agentRegistrationRecord.js b/server/lib/agentRegistrationRecord.jsindex 8c39269cd5..b30557d9e6 100644--- a/server/lib/agentRegistrationRecord.js+++ b/server/lib/agentRegistrationRecord.js@@ -55,6 +55,7 @@ export function buildAgentRegistration({localPromptBudget,leanMode,prOpenedBy,+ mergesOwnPr = false,claimFlowTask,selectedModel,effort = null,@@ -284,6 +285,13 @@ export function buildAgentRegistration({&& !isTruthyMeta(task.metadata?.reviewLoopLeaveOpen)? { url: task.metadata.reviewLoopPRUrl, branch: task.metadata.reviewLoopPRBranch }: null,+ // Generic PR delivery (#11435): the worktree PortOS just provisioned and its+ // head branch, stamped only when this run's prompt carries the merge+ // admission section for its own PR. Admission re-verifies the live task and+ // checkout against it; neither the request nor PR prose can supply it.+ prDeliveryTarget: mergesOwnPr && worktreeInfo?.branchName && workspacePath+ ? { branch: worktreeInfo.branchName, workspacePath }+ : 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 98d4873651..6fbdb39b68 100644--- a/server/services/agentPromptBuilder.js+++ b/server/services/agentPromptBuilder.js@@ -18,7 +18,7 @@ import { loadSlashdoFile, loadSlashdoLib, writeResolvedSlashdoBody } from '../liimport { DEFAULT_REVIEWER, isToolFreeReviewer, isCliReviewer, hasRequiredReviewer, resolveReviewerConfig, resolveReviewPolicy } from '../lib/validation.js';import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';import { doneSentinelName } from '../lib/agentSentinel.js';-import { canTypeSlashCommands, SLASHDO_INLINE_BUDGET_CHARS } from '../lib/slashdoInvocation.js';+import { canTypeSlashCommands, PR_OPENED_BY, SLASHDO_INLINE_BUDGET_CHARS } from '../lib/slashdoInvocation.js';import { getDigitalTwinForPrompt } from './digital-twin.js';import { TASK_PROMPT_KEY, taskContextBlock } from '../lib/cosTaskPrompt.js';import { injectReconcileAgentId } from '../lib/claimContinuation.js';@@ -63,6 +63,7 @@ import {inlinePrLifecycleSection,isPrBranchWorktree,portosMergesBranchOnExit,+ promptOpensOwnPr,worktreeCommitGuidance,} from './promptSections/completion.js';import { buildLocalReviewLoopSection, buildReviewLoopFollowUpSection, isMergeOnlyFollowUp, prepareLocalReviewLoopBody, prepareSandboxedReviewLoopBody } from './promptSections/reviewLifecycle.js';@@ -91,6 +92,8 @@ export { buildReviewLoopFollowUpSection } from './promptSections/reviewLifecycleexport { createJiraTicketForTask, generateJiraTitle, getAppDataForTask, getAppWorkspace } from './promptSections/appContext.js';const AGENTS_DIR = PATHS.cosAgents;+// Completion modes whose generic section can hand the agent its own PR's merge.+const AGENT_PR_DELIVERY_MODES = new Set([COMPLETION_MODES.TUI, COMPLETION_MODES.TUI_SLASHDO_FREE, COMPLETION_MODES.WORKTREE_NO_PUSH]);// These scheduled audits inspect a running web UI. Keep their runtime contract// in the builder rather than only in the default prompt bodies so customized@@ -432,7 +435,7 @@ export async function buildAgentPrompt(task, config, workspaceDir, worktreeInfoif (LIGHT_CONTEXT_PROVIDER_TYPES.has(providerType)) {const forgeCli = await resolveManualForgeCli(workspaceDir, worktreeInfo, task);- const lightOptions = { isTui, providerId, providerCommand, providerModel, leanMode, agentId, defaultReviewers, codeReviewDefaults, localAgentLoopBody: localAgentLoopBodyForInline, localAgentLoopBodyPath, forgeCli };+ const lightOptions = { isTui, providerId, providerCommand, providerModel, leanMode, agentId, defaultReviewers, codeReviewDefaults, localAgentLoopBody: localAgentLoopBodyForInline, localAgentLoopBodyPath, forgeCli, promptTrace: options.promptTrace || null };return withDeepAudit(options.split === true? buildLightContextPromptParts(task, workspaceDir, worktreeInfo, lightOptions): buildLightContextPrompt(task, workspaceDir, worktreeInfo, lightOptions));@@ -938,7 +941,7 @@ This run must leave its changes in a DRAFT pull request for human review. This oconst BEGIN_WORKING_LINE = 'Begin working on the task now.';-function buildLightContextSections(task, workspaceDir, worktreeInfo, { isTui = true, providerId = null, providerCommand = null, providerModel = null, leanMode = false, agentId = null, defaultReviewers, codeReviewDefaults, localAgentLoopBody = null, localAgentLoopBodyPath = null, forgeCli = null } = {}) {+function buildLightContextSections(task, workspaceDir, worktreeInfo, { isTui = true, providerId = null, providerCommand = null, providerModel = null, leanMode = false, agentId = null, defaultReviewers, codeReviewDefaults, localAgentLoopBody = null, localAgentLoopBodyPath = null, forgeCli = null, promptTrace = null } = {}) {// Idempotent with the reconcile in buildAgentPrompt; also protects the// directly-exported buildLightContextPrompt/Parts entry points.task = reconcileSplitContext(task);@@ -991,6 +994,15 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, { isTui = tproviderId, providerCommand, leanMode, worktreeInfo,});const rendersInlinePrLifecycle = inlineSection !== null;+ // A generic worktree run whose section below tells it to open AND merge its+ // own PR (`/do:pr` plus the CI merge gate, or the inline lifecycle). It+ // merges inside repository merge admission (#11435), and the spawner stamps+ // the matching ownership binding from this same decision via `promptTrace`.+ const mergesOwnPr = AGENT_PR_DELIVERY_MODES.has(completionMode) && promptOpensOwnPr(task, {+ providerType: isTui ? PROVIDER_TYPES.TUI : PROVIDER_TYPES.CLI,+ providerId, providerCommand, leanMode, worktreeInfo,+ }) !== PR_OPENED_BY.PORTOS;+ if (promptTrace) promptTrace.mergesOwnPr = mergesOwnPr;// Slashdo already partitions reviewers. Plain-git completion prompts need the// same split spelled out: local CLIs/local LLMs inspect the committed branch// before it is public; Copilot and @login reviewers can only run after a PR.@@ -1093,9 +1105,12 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, { isTui = tbaseBranch: worktreeInfo?.baseBranch || null,leavePrOpen: leavesPrForHuman(task),reviewPolicy,- forgeCli: resolvedForgeCli, localReviewSection, localReviewRequired, postPrReview: rendersInlinePrLifecycle ? runsPrSideReviewLoop : null+ forgeCli: resolvedForgeCli, localReviewSection, localReviewRequired, postPrReview: rendersInlinePrLifecycle ? runsPrSideReviewLoop : null,+ mergeAdmission: mergesOwnPr,}));- 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 }));+ 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));({[COMPLETION_MODES.TOOL_FREE]: () => contractSections.push(buildToolFreeReasoningCompletionSection()),diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.jsindex 84c7cde574..24581ec3e0 100644--- a/server/services/agentPromptBuilder.test.js+++ b/server/services/agentPromptBuilder.test.js@@ -468,6 +468,61 @@ describe('draft review delivery', () => {});});+describe('generic own-PR delivery merges inside repository admission (#11435)', () => {+ const worktree = { worktreePath: '/worktree', branchName: 'cos/task-1/agent-1', baseBranch: 'main' };+ const ADMISSION = '## Repository merge admission';++ it.each([+ ['slashdo TUI', { isTui: true, providerId: 'claude-code-tui', providerCommand: 'claude' }, true],+ ['slashdo CLI', { isTui: false, providerId: 'claude-code', providerCommand: 'claude' }, true],+ ['inline harness', { isTui: true, providerId: 'codex-tui', providerCommand: 'codex' }, false],+ ])('a %s run that merges its own PR gets admission and reports the binding decision', (_label, provider, slashdo) => {+ const promptTrace = {};+ const prompt = buildLightContextPrompt(makeTask({ metadata: { openPR: true } }), '/repo', worktree,+ { ...provider, agentId: 'agent-1', promptTrace });+ expect(promptTrace.mergesOwnPr).toBe(true);+ expect(prompt).toContain(ADMISSION);+ expect(prompt).toContain('/api/cos/merge-admission');+ expect(prompt).toContain('agent-1');+ expect(prompt).toContain('--match-head-commit <sha>');+ expect(prompt).toMatch(/gh pr merge "[^"]+" --merge --delete-branch/);+ // Read before the workflow whose TUI form ends on the sentinel write.+ expect(prompt.indexOf(ADMISSION)).toBeLessThan(prompt.search(/^## Completion/m));+ // A saved slashdo merge default must not land the PR outside the lease.+ if (slashdo) expect(prompt).toContain('/do:pr --review-with none --no-merge');+ });++ it.each([+ ['a leave-open policy', { openPR: true, prCompletion: 'leave-open' }, worktree],+ ['a JIRA human handoff', { openPR: true, jiraTicketId: 'EX-1' }, worktree],+ ['a PortOS-merged branch', { openPR: false }, worktree],+ ['a run without a worktree', { openPR: true }, null],+ ])('%s neither acquires admission nor binds generic delivery', (_label, metadata, worktreeInfo) => {+ const promptTrace = {};+ const prompt = buildLightContextPrompt(makeTask({ metadata }), '/repo', worktreeInfo,+ { isTui: true, providerId: 'claude-code-tui', providerCommand: 'claude', agentId: 'agent-1', promptTrace });+ expect(promptTrace.mergesOwnPr).toBe(false);+ expect(prompt).not.toContain(ADMISSION);+ });++ it('keeps the claim flow on its own claim admission rather than the generic binding', () => {+ const promptTrace = {};+ const prompt = buildLightContextPrompt(makeTask({ metadata: { analysisType: 'claim-issue', claimFlow: true, useWorktree: false, openPR: false } }),+ '/repo', null, { isTui: true, providerId: 'claude-code-tui', providerCommand: 'claude', agentId: 'agent-1', promptTrace });+ expect(promptTrace.mergesOwnPr).toBe(false);+ expect(prompt.split(ADMISSION)).toHaveLength(2);+ expect(prompt).toContain('## Claim ownership binding');+ });++ 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,+ { providerType: 'api', agentId: 'agent-1', promptTrace });+ expect(promptTrace.mergesOwnPr).not.toBe(true);+ expect(prompt).not.toContain(ADMISSION);+ });+});+describe('claim-flow completion handoff', () => {it.each([true, false])('honors leave-open on the %s light/full claim path', async (light) => {const task = makeTask({ metadata: { analysisType: 'claim-issue', claimFlow: true, useWorktree: false, openPR: false, prCompletion: 'leave-open' } });@@ -988,7 +1043,7 @@ describe('buildLightContextPrompt', () => {{ isTui: true });expect(prompt).toMatch(/## Completion Workflow/);expect(prompt).toMatch(/`\/simplify`/);- expect(prompt).toMatch(/`\/do:pr --review-with none`/);+ expect(prompt).toMatch(/`\/do:pr --review-with none --no-merge`/);expect(prompt).toMatch(/external review is disabled/i);expect(prompt).not.toMatch(/Copilot review loop/i);expect(prompt).toMatch(/\.agent-done/);@@ -1668,7 +1723,8 @@ describe('buildLightContextPrompt', () => {// #9837 adds remote-state-first recovery and managed-cleanup ownership.// Keep bounded headroom for that safety prose while the explicit recipe// omission above and this ceiling still reject inlining the 40KB recipe.- expect(prompt.replace(MANDATORY_DISPATCH_HINT_GUIDANCE, '').length).toBeLessThan(29_000);+ // #11435 adds the repository merge admission contract to own-PR runs.+ expect(prompt.replace(MANDATORY_DISPATCH_HINT_GUIDANCE, '').length).toBeLessThan(30_000);});it('quotes a hostile branch ref inert in the PR-create command line', () => {@@ -1740,7 +1796,7 @@ describe('buildLightContextPrompt', () => {'/r',{ branchName: 'b', worktreePath: '/tmp/wt' },{ isTui: true, providerId: 'claude-code-tui', providerCommand: 'claude' });- expect(prompt).toMatch(/`\/do:pr --review-with none`/);+ expect(prompt).toMatch(/`\/do:pr --review-with none --no-merge`/);expect(prompt).toMatch(/external review is disabled/i);expect(prompt).not.toMatch(/gh pr create/);});@@ -1883,7 +1939,7 @@ describe('buildLightContextPrompt', () => {'/r',{ branchName: 'b', worktreePath: '/tmp/wt' },{ isTui: false, providerId: 'claude-code' });- expect(prompt).toMatch(/`\/do:pr --review-with none`/);+ expect(prompt).toMatch(/`\/do:pr --review-with none --no-merge`/);expect(prompt).toMatch(/external review disabled/i);expect(prompt).not.toMatch(/Copilot review loop/i);// No review loop means nothing else merges the PR — the agent gates on CI.@@ -2514,7 +2570,7 @@ describe('buildLightContextPrompt', () => {'/r',{ branchName: 'feat', worktreePath: '/tmp/wt' },{ isTui: true });- expect(prompt).toMatch(/`\/do:pr --review-with antigravity`/);+ expect(prompt).toMatch(/`\/do:pr --review-with antigravity --no-merge`/);});it('allows merging on `partial` in the completion merge step when a stop-mode is set', () => {@@ -3372,7 +3428,7 @@ describe('buildAgentPrompt — reviewer resolution honors Code Review Defaults (it('threads a configured default reviewer list into --review-with when the task pins none', async () => {vi.mocked(getCodeReviewDefaults).mockResolvedValueOnce({ reviewers: ['claude', 'codex'] });const prompt = await buildAgentPrompt(reviewLoopTask(), {}, '/r', { branchName: 'b', worktreePath: '/tmp/wt' }, claudeCliOpts);- expect(prompt).toMatch(/`\/do:pr --review-with claude,codex`/);+ expect(prompt).toMatch(/`\/do:pr --review-with claude,codex --no-merge`/);// The stalling copilot default must not leak in.expect(prompt).not.toMatch(/--review-with copilot/);});@@ -3390,7 +3446,7 @@ describe('buildAgentPrompt — reviewer resolution honors Code Review Defaults (vi.mocked(getCodeReviewDefaults).mockResolvedValueOnce({ reviewers: ['claude', 'codex'] });const task = makeTask({ metadata: { openPR: true, reviewLoop: true, simplify: false, reviewers: ['grok'] } });const prompt = await buildAgentPrompt(task, {}, '/r', { branchName: 'b', worktreePath: '/tmp/wt' }, claudeCliOpts);- expect(prompt).toMatch(/`\/do:pr --review-with grok`/);+ expect(prompt).toMatch(/`\/do:pr --review-with grok --no-merge`/);expect(prompt).not.toMatch(/--review-with claude/);});diff --git a/server/services/agentSpawnDispatch.js b/server/services/agentSpawnDispatch.jsindex 2e51d7ef67..47b209cd6b 100644--- a/server/services/agentSpawnDispatch.js+++ b/server/services/agentSpawnDispatch.js@@ -222,6 +222,8 @@ export async function dispatchAgentRun(context, { spawnViaRunner } = {}) {localPromptBudget,leanMode,prOpenedBy,+ // Same decision that put merge admission in the prompt (#11435).+ mergesOwnPr: promptTrace.mergesOwnPr === true,claimFlowTask,selectedModel,effort: taskEffort,diff --git a/server/services/cosMergeAdmission.js b/server/services/cosMergeAdmission.jsindex bc09fa6fed..e75f21fcbd 100644--- a/server/services/cosMergeAdmission.js+++ b/server/services/cosMergeAdmission.js@@ -8,6 +8,7 @@ import { getOriginInfo } from '../lib/gitRemote.js';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';const retryAfterMs = 5000;export const ADMISSION_QUEUE_TIMEOUT_MS = 15_000;@@ -140,16 +141,32 @@ async function admit(state, save, repository, owner, measure) {return { admitted: true, token: lease.token, repository };}+const TERMINAL_TASK_STATUSES = ['completed', 'failed', 'cancelled'];++// The persisted task this live agent runs, or null once it is absent or final.+async function liveTask(agent) {+ const { getTaskById } = await import('./cosTaskStore.js');+ const task = await getTaskById(agent.taskId).catch(() => null);+ return task?.id === agent.taskId && !TERMINAL_TASK_STATUSES.includes(task.status) ? task : null;+}++// The registered checkout must still name this repository and have the+// assigned branch checked out; an unreadable checkout is not a match.+async function checkoutOnBranch(workspace, branch, repository) {+ 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() === branch;+}+// 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 task = await liveTask(agent);const meta = task?.metadata;- if (task?.id !== agent.taskId || task.taskType !== 'internal'- || ['completed', 'failed', 'cancelled'].includes(task.status)+ if (!task || task.taskType !== 'internal'|| !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;@@ -157,11 +174,39 @@ async function verifiedReviewCoordinator(agent, repository) {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;+ return checkoutOnBranch(agent.metadata.workspacePath, target.branch, repository);+}++// Generic PR delivery (#11435): an operator-configured task whose prompt told+// it to open AND merge its own PR from the worktree PortOS provisioned. The+// target is the spawn-time binding (that worktree and its head branch), never+// the request; the live task must still grant agent-owned delivery, and the+// checkout must still be that branch of this repository. A generic run cannot+// promote itself to claim authority: it admits only its own registered branch.+async function verifiedWorktreeDelivery(agent, repository) {+ const meta = agent.metadata;+ const target = meta?.prDeliveryTarget;+ if (!isPlainObject(target) || typeof target.branch !== 'string' || !target.branch+ || typeof target.workspacePath !== 'string' || !target.workspacePath) return false;+ const { PR_OPENED_BY } = await import('../lib/slashdoInvocation.js');+ if (meta.isWorktree !== true || meta.configOpenPR !== true || meta.configClaimFlow+ || ![PR_OPENED_BY.AGENT_SLASHDO, PR_OPENED_BY.AGENT_INLINE].includes(meta.prOpenedBy)+ || meta.prCompletionPolicy === PR_COMPLETIONS.LEAVE_OPEN+ || meta.worktreeBranch !== target.branch || meta.workspacePath !== target.workspacePath+ || !meta.sourceWorkspace || meta.sourceWorkspace === target.workspacePath) return false;+ const task = await liveTask(agent);+ const taskMeta = task?.metadata;+ if (!task || !isTruthyMeta(taskMeta?.openPR) || resolvePrCompletion(taskMeta) === PR_COMPLETIONS.LEAVE_OPEN+ || leavesPrForHuman(task) || isTruthyMeta(taskMeta?.reviewLoopFollowUp) || isTruthyMeta(taskMeta?.readOnly)+ || taskMeta?.forkHead) return false;+ return checkoutOnBranch(target.workspacePath, target.branch, 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) {+ if (isTruthyMeta(agent.metadata?.claimPicksOwnBranch) || agent.metadata?.claimBranch) return true;+ return await verifiedReviewCoordinator(agent, repository) || verifiedWorktreeDelivery(agent, repository);}/** The ID is the registered parent, never a worker-child ID or a cwd PID. */@@ -176,8 +221,9 @@ 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' && !(isTruthyMeta(agent.metadata?.claimPicksOwnBranch) || agent.metadata?.claimBranch)- && !await measure('origin', () => verifiedReviewCoordinator(agent, repository))) return refuse('claim-owner-unverified');+ if (action !== 'release' && !await measure('origin', () => verifiedParticipant(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.worktreeDelivery.test.js b/server/services/cosMergeAdmission.worktreeDelivery.test.jsnew file mode 100644index 0000000000..2aca0f770a--- /dev/null+++ b/server/services/cosMergeAdmission.worktreeDelivery.test.js@@ -0,0 +1,114 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';+import { generateTasksMarkdown, parseTasksMarkdown } from '../lib/taskParser.js';++// Generic, operator-configured CoS PR delivery (#11435): a live worktree run+// whose prompt told it to open and merge its own PR participates in repository+// merge admission through its spawn-time binding, never a caller claim.+const f = vi.hoisted(() => ({ state: null, disk: null, tasks: {}, branch: 'cos/task-1/agent-1', 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('./cosTaskStore.js', () => ({ getTaskById: async id => f.tasks[id] ?? null }));+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 }) }));+import { buildAgentRegistration } from '../lib/agentRegistrationRecord.js';+import { registerAgent } from './cosAgentLifecycle.js';+import { claimMergeAdmission, withPendingMergeAdmission } from './cosMergeAdmission.js';++const BRANCH = 'cos/task-1/agent-1';+const admission = (action, token, extra = {}) => claimMergeAdmission({ agentId: 'agent-1', action, token, ...extra });+const persist = () => { f.disk = structuredClone(f.state); };++// The task round-trips through TASKS.md like a real queue entry, so metadata+// arrives with the string scalars admission must still interpret correctly.+async function launch({ metadata = {}, mergesOwnPr = true, prOpenedBy = 'agent-slashdo' } = {}) {+ const [task] = parseTasksMarkdown(generateTasksMarkdown([{ id: 'task-1', status: 'in_progress', priority: 'MEDIUM',+ description: 'Fix the example', metadata: { openPR: true, prCompletion: 'merge-on-green', ...metadata } }]));+ f.tasks[task.id] = { ...task, taskType: 'user' };+ await registerAgent('agent-1', task.id, buildAgentRegistration({ task: f.tasks[task.id], provider: { id: 'test' }, modelSelection: {},+ sourceWorkspace: '/repos/source', workspacePath: '/repos/worktree', worktreeInfo: { branchName: BRANCH },+ prOpenedBy, mergesOwnPr }));+ return f.tasks[task.id];+}++beforeEach(() => {+ f.state = { agents: {}, mergeAdmissions: {}, stats: { agentsSpawned: 0 } };+ f.tasks = {}; f.branch = BRANCH; f.workspaceRepo = 'example/repo'; persist();+});++describe('generic worktree PR delivery merge admission', () => {+ it.each(['agent-slashdo', 'agent-inline'])('an authorized %s run acquires, checks and releases admission for its own PR', async prOpenedBy => {+ await launch({ prOpenedBy });+ const agent = f.state.agents['agent-1'];+ expect(agent.metadata.prDeliveryTarget).toEqual({ branch: BRANCH, workspacePath: '/repos/worktree' });+ expect(agent.metadata.claimBranch).toBeUndefined();+ 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({});+ // Admission never promoted the generic run to claim authority.+ expect(f.state.agents['agent-1'].metadata.claimPicksOwnBranch).toBeUndefined();+ });++ it('excludes and is excluded by active claim and sweep leases', 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 generic = await admission('acquire');+ expect(generic.admitted).toBe(true);+ expect((await claimMergeAdmission({ agentId: 'claim', action: 'acquire' })).admitted).toBe(false);+ expect((await withPendingMergeAdmission({ host: 'github.com', fullName: 'example/repo' }, vi.fn())).admitted).toBe(false);+ });++ it('refuses a check after the run has stopped verifying, even with its own token', async () => {+ const task = await launch();+ const lease = await admission('acquire');+ task.status = 'completed';+ expect(await admission('check', lease.token)).toMatchObject({ admitted: false, reason: 'claim-owner-unverified' });+ // Releasing an owned token stays possible so the lease cannot strand.+ expect(await admission('release', lease.token, { outcome: 'leave-open' })).toMatchObject({ released: true });+ });++ it.each([+ 'absent-agent', 'completed-agent', 'absent-task', 'completed-task', 'other-task', 'unbound', 'portos-owned',+ 'open-pr-revoked', 'leave-open', 'human-handoff', 'review-follow-up', 'fork', 'changed-registration',+ 'moved-workspace', 'source-as-worktree', 'unrelated-workspace', 'changed-checkout', 'unreadable-checkout',+ ])('refuses %s despite caller-supplied repository and branch claims', async mode => {+ const task = await launch(mode === 'unbound' ? { mergesOwnPr: false } : mode === 'portos-owned' ? { prOpenedBy: 'portos' } : {});+ const agent = f.state.agents['agent-1'];+ if (mode === 'absent-agent') delete f.state.agents['agent-1'];+ 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 === 'other-task') agent.taskId = 'task-2';+ if (mode === 'open-pr-revoked') task.metadata.openPR = 'false';+ if (mode === 'leave-open') task.metadata.prCompletion = 'leave-open';+ if (mode === 'human-handoff') task.metadata.jiraTicketId = 'EX-1';+ if (mode === 'review-follow-up') task.metadata.reviewLoopFollowUp = true;+ if (mode === 'fork') task.metadata.forkHead = { owner: 'contributor', repo: 'repo', branch: BRANCH };+ if (mode === 'changed-registration') agent.metadata.worktreeBranch = 'another/branch';+ if (mode === 'moved-workspace') agent.metadata.workspacePath = '/repos/elsewhere';+ if (mode === 'source-as-worktree') agent.metadata.sourceWorkspace = '/repos/worktree';+ if (mode === 'unrelated-workspace') f.workspaceRepo = 'example/other';+ if (mode === 'changed-checkout') f.branch = 'another/branch';+ if (mode === 'unreadable-checkout') f.branch = '';+ persist();+ expect(await admission('acquire', undefined, { repository: 'github.com/example/repo', branch: BRANCH, prUrl: 'https://github.com/example/repo/pull/1' }))+ .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 033e7d85dd..3117ac020b 100644--- a/server/services/promptSections/completion.js+++ b/server/services/promptSections/completion.js@@ -601,9 +601,9 @@ 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 claim intact. 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 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 the claim prompt lists. 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.',+ '- 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' }), '```','- Otherwise (head changed, a required check is not green, or the PR is `DIRTY`/conflicting, `BEHIND` where branch rules require an up-to-date head, `BLOCKED`, or still `UNKNOWN` after a few re-reads): release with outcome resync. Then, OUTSIDE the lease, sync onto the latest default branch, rerun pregate and the affected required reviews, push, wait for required CI on the new head, and acquire again. After three resync rounds without a merge, record leave-open instead.','Verify the remote state is exactly MERGED, then release with outcome merged before worktree cleanup. On a recorded failure or leave-open handoff, release with outcome leave-open. Require released:true; report a failed release without deleting or overwriting ownership state:',@@ -728,7 +728,7 @@ export function worktreeCommitGuidance({ isTui, mode = null, canTypeSlashCommand* `prCompletion` selects the review gate or CI-only merge gate. Leave-open* callers do not invoke this helper.*/-function buildPostPRMergeSteps(startStep, { prCompletion = PR_COMPLETIONS.REVIEW_THEN_MERGE, reviewPolicy, forgeCli = 'gh' }) {+function buildPostPRMergeSteps(startStep, { prCompletion = PR_COMPLETIONS.REVIEW_THEN_MERGE, reviewPolicy, forgeCli = 'gh', mergeAdmission = false }) {const { reviewers, optionalReviewers, reviewStopMode } = reviewPolicy;const usernames = normalizeReviewUsernames(reviewPolicy.forgeReviewerUsernames);const mergeGateForge = forgeCli === 'glab' ? 'gitlab' : 'github';@@ -736,7 +736,8 @@ function buildPostPRMergeSteps(startStep, { prCompletion = PR_COMPLETIONS.REVIEW// the manual-TUI workflow and the merge follow-up agent also use. The PR URL// isn't known when this prompt is written, hence the placeholder.if (prCompletion === PR_COMPLETIONS.MERGE_ON_GREEN) {- const gate = buildCiMergeGateSteps(startStep, { prRef: '"<PR_URL>"', forge: 'unknown' });+ // Under merge admission `/do:pr` runs with --no-merge, so no saved default merges it.+ const gate = buildCiMergeGateSteps(startStep, { prRef: '"<PR_URL>"', forge: 'unknown', ...(mergeAdmission ? { alreadyMergedHint: '' } : {}) });return {lines: [' **No review loop is configured for this task, so nothing and nobody else will merge this PR** — `/do:pr` opens it and exits. Capture the PR URL it printed, then:',@@ -866,7 +867,7 @@ function localReviewCompletionInstruction(localReviewRequired = true) {* this IS a Claude session, so `/simplify` and `/do:pr` are both safe to emit* without a second provider check.*/-export function buildTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLETIONS.MERGE_ON_GREEN, simplifyEnabled, sentinelPath, mode = COMPLETION_MODES.TUI, rendersInlinePrLifecycle = false, portosMergesBranch = false, branchName = null, baseBranch = null, leavePrOpen = false, reviewPolicy, forgeCli = 'gh', noChangeSuccess = false, localReviewSection = '', localReviewRequired = true, postPrReview = null }) {+export function buildTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLETIONS.MERGE_ON_GREEN, simplifyEnabled, sentinelPath, mode = COMPLETION_MODES.TUI, rendersInlinePrLifecycle = false, portosMergesBranch = false, branchName = null, baseBranch = null, leavePrOpen = false, reviewPolicy, forgeCli = 'gh', noChangeSuccess = false, localReviewSection = '', localReviewRequired = true, postPrReview = null, mergeAdmission = false }) {const policyLeavesOpen = prCompletion === PR_COMPLETIONS.LEAVE_OPEN;const runsReviewLoop = prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE;if (mode === COMPLETION_MODES.TUI_SLASHDO_FREE) {@@ -883,8 +884,9 @@ export function buildTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLEconst { reviewers } = reviewPolicy;// A saved slashdo `merge: true` default would otherwise merge a PR that must// stay open — dropping our own merge steps isn't enough, `/do:pr` has to be- // told not to merge (see lib/prDisposition.js).- const mergeArg = (willOpenPR && (leavePrOpen || policyLeavesOpen)) ? ' --no-merge' : '';+ // told not to merge (see lib/prDisposition.js). Under merge admission the+ // gate below merges inside the lease, so `/do:pr` must not merge first.+ const mergeArg = (willOpenPR && (leavePrOpen || policyLeavesOpen || mergeAdmission)) ? ' --no-merge' : '';const reviewerArg = (reviewArgs ? ` ${reviewArgs}` : '') + mergeArg;const copilotOnly = reviewers.length === 1 && reviewers[0] === DEFAULT_REVIEWER && reviewUsernames.length === 0;const reviewerListLabel = [...reviewers, ...reviewUsernames.map(u => `@${u}`)].join(', ');@@ -913,7 +915,7 @@ export function buildTuiCompletionSection({ willOpenPR, prCompletion = PR_COMPLE// alone when it doesn't (nothing else merges a no-review-loop PR). The one// exception is a PR a human lands (JIRA-tracked; see lib/prDisposition.js).const merge = (willOpenPR && !leavePrOpen && !policyLeavesOpen)- ? buildPostPRMergeSteps(3, { prCompletion, reviewPolicy, forgeCli })+ ? buildPostPRMergeSteps(3, { prCompletion, reviewPolicy, forgeCli, mergeAdmission }): { lines: (leavePrOpen || policyLeavesOpen) && willOpenPR ? [LEAVE_PR_OPEN_STEP(3, leavePrOpen)] : [], nextStep: (leavePrOpen || policyLeavesOpen) && willOpenPR ? 4 : 3 };const sentinelStep = merge.nextStep;@@ -1256,7 +1258,7 @@ export function buildInlineReviewLoopSection({* (`lib/agentCompletionMode.js`) rather than re-testing `worktreeInfo` /* `willOpenPR` — the caller already resolved those into `mode`.*/-export function buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletion = PR_COMPLETIONS.MERGE_ON_GREEN, mode = null, canTypeSlashCommands = false, rendersInlinePrLifecycle = false, simplifyEnabled = false, leavePrOpen = false, reviewPolicy, forgeCli = 'gh', noChangeSuccess = false, localReviewSection = '', localReviewRequired = true, postPrReview = null }) {+export function buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletion = PR_COMPLETIONS.MERGE_ON_GREEN, mode = null, canTypeSlashCommands = false, rendersInlinePrLifecycle = false, simplifyEnabled = false, leavePrOpen = false, reviewPolicy, forgeCli = 'gh', noChangeSuccess = false, localReviewSection = '', localReviewRequired = true, postPrReview = null, mergeAdmission = false }) {const policyLeavesOpen = prCompletion === PR_COMPLETIONS.LEAVE_OPEN;const runsReviewLoop = postPrReview ?? (prCompletion === PR_COMPLETIONS.REVIEW_THEN_MERGE);if (canTypeSlashCommands && mode === COMPLETION_MODES.WORKTREE_NO_PUSH) {@@ -1268,8 +1270,9 @@ export function buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompleticonst { reviewUsernames, reviewArgs, effortNote } = resolveReviewInvocation({ willOpenPR, runsReviewLoop, reviewPolicy });const { reviewers } = reviewPolicy;// `--no-merge` overrides a saved slashdo `merge: true` default, which would- // otherwise merge a PR this task must leave open (see lib/prDisposition.js).- const reviewerArg = (reviewArgs ? ` ${reviewArgs}` : '') + ((leavePrOpen || policyLeavesOpen) ? ' --no-merge' : '');+ // otherwise merge a PR this task must leave open (see lib/prDisposition.js)+ // or merge outside the admission lease the merge steps below acquire.+ const reviewerArg = (reviewArgs ? ` ${reviewArgs}` : '') + ((leavePrOpen || policyLeavesOpen || mergeAdmission) ? ' --no-merge' : '');const completionNote = runsReviewLoop? ((reviewers.length === 1 && reviewers[0] === DEFAULT_REVIEWER && reviewUsernames.length === 0)? 'and drives the Copilot review loop until clean.'@@ -1288,7 +1291,7 @@ export function buildCliCompletionSection({ worktreeInfo, willOpenPR, prCompletiif (leavePrOpen || policyLeavesOpen) {lines.push(LEAVE_PR_OPEN_STEP(step, leavePrOpen));} else {- const merge = buildPostPRMergeSteps(step, { prCompletion, reviewPolicy, forgeCli });+ const merge = buildPostPRMergeSteps(step, { prCompletion, reviewPolicy, forgeCli, mergeAdmission });lines.push(...merge.lines);}return lines.join('\n');