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
feat: hold merge admission only around the final verify-and-merge (#10803)
Adam Eivy5dd1a722dea1
diff --git a/docs/features/chief-of-staff.md b/docs/features/chief-of-staff.mdindex 86591e1d67..fcd2a3b9a7 100644--- a/docs/features/chief-of-staff.md+++ b/docs/features/chief-of-staff.md@@ -27,35 +27,55 @@ Autonomous agent manager that watches task files, spawns sub-agents, and maintai## Repository merge admissionSelf-managed claim parents and the deterministic pending-merge sweep share one-repository-scoped final-merge lease (`server/services/cosMergeAdmission.js`).+repository-scoped merge-instant lease (`server/services/cosMergeAdmission.js`).The host-control-gated `POST /api/cos/merge-admission` accepts the registeredparent agent ID and `acquire`, `check`, or `release`; check/release require the-returned token. Repository identity comes from that parent's registered source-checkout and normalized origin host/repository, not its child worktree path.--Acquire after local review and PR publication, before final base synchronization,-pregate/push, current-head CI and merge. Keep the lease through verified merge-and cleanup, or release with a recorded `leave-open` outcome. Swarm children-continue implementing and reviewing concurrently; the parent holds admission-while they finish and while CI runs. A waiter reports the refusal reason every-minute, retries at 15-second intervals for at most 30 minutes, then leaves the-reviewed PR and claim intact. Sweep deferrals preserve their retry budget.+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.++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:++- 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`),+ then releases with `merged`;+- releases with `resync` when the head changed or the PR is no longer mergeable+ (`DIRTY`, `BEHIND` under an up-to-date-branch rule, `BLOCKED`), then syncs,+ reruns pregate and waits for CI again outside the lease before re-acquiring.++A base that moved while the PR stays `CLEAN` does not force a resync or a fresh+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 green+PRs, which post-merge default-branch CI catches — the same exposure manual and+cross-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+holds the lease only around its own read → assess → pinned merge.Leases extend the existing machine-local CoS runtime ownership in`data/cos/state.json`, under its existing write queue; there is no new store,seed, migration, or federation payload. Missing lease fields are compatiblewith older state. Unreadable, mismatched or stale ownership refuses admission.-A claim lease can be recovered only from a matching finalized parent record-(including its archive); elapsed time, completed children and absent cwd-processes never release a running/paused parent. A crashed deterministic sweep-is recoverable only after its server process is proven absent. Failed reads and-ambiguous/reused process identities hold admission conservatively.+An agent lease is recoverable from a matching finalized parent record+(including its archive), or by any participant once its 5-minute hold deadline+(`AGENT_LEASE_MAX_HOLD_MS`, measured from `acquiredAt`) has passed even while+its owner is still running. An expired holder's `check` is refused with+`lease-expired`, and because every merge is pinned to the CI-verified head, a+reclaimed holder cannot land an unverified head — the worst case is one+redundant resync. Completed children and absent cwd processes never release a+lease early. A crashed deterministic sweep is recoverable only after its server+process is proven absent. Failed reads and ambiguous/reused process identities+hold admission conservatively.This coordinates participating runs on **one install**. Manual merges, older-prompts and other installs can still move the base. Always re-read the live base-before merge and repeat sync, pregate and fresh current-head CI when it changes.-Admission does not grant permission to adopt another owner's branch or checkout,-does not replace reviews/CI, and does not make queued auto-merge a completed merge.+prompts and other installs can still move the base; the forge's merge state+reflects that at the merge instant. Admission does not grant permission to+adopt another owner's branch or checkout, does not replace reviews/CI, and+does not make queued auto-merge a completed merge.## Claim branch ownershipdiff --git a/server/routes/cosAgentRoutes.js b/server/routes/cosAgentRoutes.jsindex 82687729f5..92a7fd16ca 100644--- a/server/routes/cosAgentRoutes.js+++ b/server/routes/cosAgentRoutes.js@@ -17,7 +17,8 @@ const mergeAdmissionSchema = z.object({agentId: z.string().min(1).max(200),action: z.enum(['acquire', 'check', 'release']),token: z.string().uuid().optional(),- outcome: z.enum(['merged', 'leave-open']).optional(),+ // Mirrors MERGE_ADMISSION_OUTCOMES; the service stays lazily imported.+ outcome: z.enum(['merged', 'leave-open', 'resync']).optional(),});router.post('/merge-admission', asyncHandler(async (req, res) => {const input = validateRequest(mergeAdmissionSchema, req.body ?? {});diff --git a/server/routes/cosAgentRoutes.mergeAdmission.test.js b/server/routes/cosAgentRoutes.mergeAdmission.test.jsnew file mode 100644index 0000000000..3117b63103--- /dev/null+++ b/server/routes/cosAgentRoutes.mergeAdmission.test.js@@ -0,0 +1,37 @@+import { describe, expect, it, vi } from 'vitest';+import express from 'express';+import { request } from '../lib/testHelper.js';+import { errorMiddleware } from '../lib/errorHandler.js';++const claimMergeAdmission = vi.hoisted(() => vi.fn(async ({ outcome }) => ({ admitted: false, released: true, outcome })));+vi.mock('../services/cos.js', () => ({}));+vi.mock('../services/agentOrchestrator.js', () => ({}));+vi.mock('../services/cosMergeAdmission.js', async (importOriginal) => ({+ MERGE_ADMISSION_OUTCOMES: (await importOriginal()).MERGE_ADMISSION_OUTCOMES,+ claimMergeAdmission,+}));++import routes from './cosAgentRoutes.js';+import { MERGE_ADMISSION_OUTCOMES } from '../services/cosMergeAdmission.js';++const app = express();+app.use(express.json());+app.use('/api/cos', routes);+app.use(errorMiddleware);+const token = '00000000-0000-4000-8000-000000000000';+const releaseWith = (outcome) => request(app).post('/api/cos/merge-admission')+ .send({ agentId: 'parent-example', action: 'release', token, outcome });++describe('POST /api/cos/merge-admission outcomes', () => {+ it('accepts every service outcome, including resync, and rejects any other', async () => {+ expect(MERGE_ADMISSION_OUTCOMES).toEqual(['merged', 'leave-open', 'resync']);+ for (const outcome of MERGE_ADMISSION_OUTCOMES) {+ const res = await releaseWith(outcome);+ expect(res.status).toBe(200);+ expect(res.body).toMatchObject({ released: true, outcome });+ }+ claimMergeAdmission.mockClear();+ expect((await releaseWith('abandoned')).status).toBe(400);+ expect(claimMergeAdmission).not.toHaveBeenCalled();+ });+});diff --git a/server/services/cosMergeAdmission.js b/server/services/cosMergeAdmission.jsindex a458390866..588f82d631 100644--- a/server/services/cosMergeAdmission.js+++ b/server/services/cosMergeAdmission.js@@ -1,10 +1,20 @@-/** Repository-wide final-merge admission for participating runs on this install. */+/**+ * Repository-wide merge-instant admission for participating runs on this install.+ * Sync, pregate, push and CI run outside the lease; it spans only the final+ * verify-and-merge, so holds take seconds (#10803).+ */import { randomUUID } from 'node:crypto';import { getOriginInfo } from '../lib/gitRemote.js';import { isPlainObject } from '../lib/objects.js';import { isTruthyMeta } from '../lib/metadataFlags.js';-const retryAfterMs = 15000;+const retryAfterMs = 5000;+// An agent lease covers only verify-and-merge. Past this deadline it is+// reclaimable even from a running owner: that holder's pinned merge+// (--match-head-commit) cannot land an unverified head, so the worst case is+// one redundant resync rather than a repository blocked behind a hung parent.+export const AGENT_LEASE_MAX_HOLD_MS = 5 * 60 * 1000;+export const MERGE_ADMISSION_OUTCOMES = ['merged', 'leave-open', 'resync'];const serverOwner = randomUUID();const sweepTokens = new Set();const refuse = (reason) => ({ admitted: false, reason, retryAfterMs });@@ -21,6 +31,7 @@ const validLease = (lease, repository) => isPlainObject(lease) && lease.reposito&& (lease.kind === 'agent'? typeof lease.agentId === 'string' && typeof lease.startedAt === 'string' && typeof lease.taskId === 'string': lease.kind === 'sweep' && typeof lease.serverOwner === 'string' && Number.isInteger(lease.pid) && lease.pid > 0);+const expired = (lease) => lease.kind === 'agent' && Date.now() - Date.parse(lease.acquiredAt) >= AGENT_LEASE_MAX_HOLD_MS;async function transaction(work) {// Lazy: almost every task-generator suite reaches prWatcher, even when no@@ -48,11 +59,13 @@ async function transaction(work) {async function inactive(lease, state) {if (lease.kind === 'sweep') {if (lease.serverOwner === serverOwner) return !sweepTokens.has(lease.token);- // Never expire on age: a long CI wait is legitimate. A different server- // incarnation is recoverable only once its process is proven absent.+ // Never expire on age: the sweep holds only its own bounded merge attempt.+ // A different server incarnation is recoverable only once its process is+ // proven absent.try { process.kill(lease.pid, 0); return false; }catch (err) { return err.code === 'ESRCH'; }}+ if (expired(lease)) return true;let owner = state.agents[lease.agentId];if (!owner) {const { readAgentRecordOrUnreadable } = await import('./cosAgentLifecycle.js');@@ -65,7 +78,9 @@ async function admit(state, save, repository, owner) {const held = state.mergeAdmissions[repository];if (Object.hasOwn(state.mergeAdmissions, repository)) {if (!validLease(held, repository)) return refuse('lease-unreadable');- if (owner.kind === 'agent' && held.kind === 'agent' && held.agentId === owner.agentId && held.startedAt === owner.startedAt && held.taskId === owner.taskId) {+ // Re-entry keeps a live token; an expired one is voided and re-minted below.+ if (owner.kind === 'agent' && held.kind === 'agent' && held.agentId === owner.agentId && held.startedAt === owner.startedAt+ && held.taskId === owner.taskId && !expired(held)) {return { admitted: true, token: held.token, repository };}if (!await inactive(held, state)) return refuse('owner-active-or-unverified');@@ -99,8 +114,10 @@ export async function claimMergeAdmission({ agentId, action, token, outcome }) {if (!validLease(lease, repository) || lease.kind !== 'agent' || !sameAgent(lease, agent) || lease.token !== token) {return refuse('lease-owner-mismatch');}- if (action === 'check') return { admitted: true, token, repository };- if (action !== 'release' || !['merged', 'leave-open'].includes(outcome)) return refuse('outcome-required');+ // An expired holder must stop and re-acquire before merging; releasing+ // its own still-unclaimed lease stays permitted.+ 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];state.agents[agentId] = { ...agent, metadata: { ...agent.metadata,lastMergeAdmission: { repository, outcome, releasedAt: new Date().toISOString() },diff --git a/server/services/cosMergeAdmission.test.js b/server/services/cosMergeAdmission.test.jsindex ae2ddd5edc..7064febcca 100644--- a/server/services/cosMergeAdmission.test.js+++ b/server/services/cosMergeAdmission.test.js@@ -13,7 +13,7 @@ vi.mock('../lib/gitRemote.js', () => ({fullName: path === '/repos/other' ? 'example/other' : 'Example/Repo' }),}));vi.mock('./cosAgentLifecycle.js', () => ({ readAgentRecordOrUnreadable: async () => fixture.archived }));-import { claimMergeAdmission, withPendingMergeAdmission } from './cosMergeAdmission.js';+import { AGENT_LEASE_MAX_HOLD_MS, claimMergeAdmission, withPendingMergeAdmission } from './cosMergeAdmission.js';const origin = { host: 'github.com', fullName: 'example/repo' };const parent = (id, sourceWorkspace = '/repos/example') => ({ id, taskId: `task-${id}`, status: 'running',startedAt: '2026-01-01T00:00:00Z', metadata: { sourceWorkspace, claimPicksOwnBranch: true } });@@ -29,33 +29,68 @@ beforeEach(() => {});describe('repository final merge workflow', () => {- it('serializes two live parents and a sweep, avoiding an extra base sync during CI', async () => {- let base = 1;- let validations = 0;- const syncAndValidate = () => { validations++; return base; };- // The uncoordinated failure: another merge invalidates A's validated base.- const uncoordinatedHead = syncAndValidate();- base++;- expect(uncoordinatedHead).not.toBe(base);- syncAndValidate();- expect(validations).toBe(2);- base = 1; validations = 0;+ it('validates two parents concurrently and serializes only the pinned merge instant', async () => {+ // Synthetic forge: a pinned merge refuses any head but the verified one.+ const forge = { base: 1, prs: {} };+ const validate = (id) => { forge.prs[id] = { head: `${id}-head-on-${forge.base}`, state: 'CLEAN' }; return forge.prs[id].head; };+ const merge = (id, sha) => {+ if (forge.prs[id].head !== sha) return false;+ forge.base++;+ return true;+ };+ // Sync/pregate/CI never needs the lease, so both parents validate at once.+ const [aHead, bHead] = [validate('a'), validate('b')];+ expect(fixture.state.mergeAdmissions).toEqual({});const [a, b] = await Promise.all([acquire('a'), acquire('b')]);expect(a.admitted).toBe(true);- expect(b.admitted).toBe(false);- const validatedBase = syncAndValidate();- fixture.state.agents.child = { ...parent('child'), status: 'completed', completedAt: '2026-01-01T01:00:00Z' };- persist();- const sweep = vi.fn(() => { base++; });+ expect(b).toMatchObject({ admitted: false, retryAfterMs: 5000 });+ const sweep = vi.fn();expect(await withPendingMergeAdmission(origin, sweep)).toMatchObject({ admitted: false });expect(sweep).not.toHaveBeenCalled();- expect(await acquire('b')).toMatchObject({ admitted: false, retryAfterMs: 15000 });expect(await claimMergeAdmission({ agentId: 'a', action: 'check', token: a.token })).toMatchObject({ admitted: true });- expect(validatedBase).toBe(base);- expect(validations).toBe(1);+ expect(merge('a', aHead)).toBe(true);expect(await release('a', a.token)).toMatchObject({ released: true });- expect((await acquire('b')).admitted).toBe(true);++ // The base moved but B stays CLEAN: it merges its CI-verified head as is.+ const b2 = await acquire('b');+ expect(forge.prs.b.state).toBe('CLEAN');+ expect(merge('b', bHead)).toBe(true);+ expect(await release('b', b2.token)).toMatchObject({ released: true });++ // A DIRTY PR releases with resync and re-validates outside the lease.+ validate('a'); forge.prs.a.state = 'DIRTY';+ const a2 = await acquire('a');+ expect(await release('a', a2.token, 'resync')).toMatchObject({ released: true, outcome: 'resync' });+ expect(fixture.state.agents.a.metadata.lastMergeAdmission.outcome).toBe('resync');+ expect(fixture.state.mergeAdmissions).toEqual({});+ const revalidated = validate('a');+ const a3 = await acquire('a');+ expect(merge('a', revalidated)).toBe(true);+ expect(await release('a', a3.token)).toMatchObject({ released: true });+ });++ it('lets another participant reclaim a running holder past the hold deadline', async () => {+ vi.useFakeTimers({ now: Date.parse('2026-01-01T00:00:00Z') });+ try {+ const stale = await acquire('a');+ vi.advanceTimersByTime(AGENT_LEASE_MAX_HOLD_MS - 1);+ expect((await acquire('b')).admitted).toBe(false);+ vi.advanceTimersByTime(1);+ expect(await claimMergeAdmission({ agentId: 'a', action: 'check', token: stale.token })).toMatchObject({ admitted: false, reason: 'lease-expired' });+ expect(fixture.state.agents.a.status).toBe('running');+ const reclaimed = await acquire('b');+ expect(reclaimed.admitted).toBe(true);+ // The stale token is void; the holder's head-pinned merge (prompt+ // contract) is what keeps a late merge from landing an unverified head.+ expect(await claimMergeAdmission({ agentId: 'a', action: 'check', token: stale.token })).toMatchObject({ admitted: false, reason: 'lease-owner-mismatch' });+ expect((await release('a', stale.token)).released).not.toBe(true);+ // A holder re-acquiring its own expired lease gets a fresh token.+ vi.advanceTimersByTime(AGENT_LEASE_MAX_HOLD_MS);+ const renewed = await acquire('b');+ expect(renewed.token).not.toBe(reclaimed.token);+ expect(await claimMergeAdmission({ agentId: 'b', action: 'check', token: renewed.token })).toMatchObject({ admitted: true });+ } finally { vi.useRealTimers(); }});it('holds the sweep through async merge and permits another repository concurrently', async () => {@@ -107,6 +142,9 @@ describe('repository final merge workflow', () => {expect((await release('a', a.token)).released).not.toBe(true);expect(await release('a', next.token)).toMatchObject({ released: true });expect(fixture.state.agents.a.metadata.lastMergeAdmission.outcome).toBe('merged');+ const last = await acquire('a');+ expect(await release('a', last.token, 'abandoned')).toMatchObject({ admitted: false, reason: 'outcome-required' });+ expect(fixture.state.mergeAdmissions['github.com/example/repo'].token).toBe(last.token);});it('recovers a crashed sweep only when its process is proven absent', async () => {diff --git a/server/services/cosTaskPreStepBlocks.js b/server/services/cosTaskPreStepBlocks.jsindex b28b7ef3a5..d6bd64fb0e 100644--- a/server/services/cosTaskPreStepBlocks.js+++ b/server/services/cosTaskPreStepBlocks.js@@ -225,8 +225,8 @@ export function applyReleaseOptions(promptTemplate, taskType, metadata) {// trailer — which would send the agent off to "correct" a stranger's MR. That is// the #3489 clobbering failure re-created by the check meant to prevent it.const SWARM_FORGE = {- gh: { pr: 'PR', mergeCmd: 'gh pr merge', bodyCmd: 'gh pr view --json body -q .body' },- glab: { pr: 'MR', mergeCmd: 'glab mr merge', bodyCmd: 'glab mr view --output json | jq -r .description' }+ gh: { pr: 'PR', mergeCmd: 'gh pr merge', mergePin: '--match-head-commit <ci-verified-sha>', bodyCmd: 'gh pr view --json body -q .body' },+ glab: { pr: 'MR', mergeCmd: 'glab mr merge', mergePin: '--sha <ci-verified-sha>', bodyCmd: 'glab mr view --output json | jq -r .description' }};/**@@ -263,7 +263,7 @@ export function resolveSwarmBlock(promptTaskType, count) {: promptTaskType === 'claim-issue' ? 'gh': null;if (!forgeKey) return ''; // plan-task / jira have no swarm flow- const { pr, mergeCmd, bodyCmd } = SWARM_FORGE[forgeKey];+ const { pr, mergeCmd, mergePin, bodyCmd } = SWARM_FORGE[forgeKey];return `# ⚡ SWARM MODE — claim and ship up to ${n} independent issues in parallel**This run operates in slashdo \`/do:next --swarm=${n}\` mode.** The single-issue framing in the task body below is your PER-AGENT playbook, not the shape of the whole run: instead of claiming ONE issue, claim up to ${n} *mutually independent* open issues and ship them concurrently, then serialize only the merges. Swarm adds exactly two things over the single-issue flow — a partition step up front and a serialized merge queue at the end; everything in between (claim, worktree, verify, implement, changelog, review gate) is the unchanged single-issue flow run once per agent. Never special-case a swarm agent's claim/ship logic.@@ -286,8 +286,8 @@ ${DISPATCH_HINT_FANOUT_GUIDANCE}**Verify the ${pr} body's issue trailer after create AND after every edit.** The ${pr}-body flow is create-then-edit — the file is written once, then re-read minutes later during the review loop — which is a wide window for a stale or foreign body to land. Belt to the namespacing's braces: immediately after \`create\` and after each body \`edit\`, re-read the published body with \`${bodyCmd}\` — **note it takes no number: both CLIs resolve the ${pr} from your checked-out \`claim/issue-<num>\` branch, and passing an ISSUE number where a ${pr} number belongs is how you end up reading (and then "correcting") someone else's ${pr}** — and confirm the body carries this agent's own trailer. A full-scope ship MUST carry \`Closes #<num>\` for this issue; \`Refs #<num>\` is permitted ONLY for a deliberate partial ship that also records the required \`Done ✓ / Remaining ▢\` reconciliation comment. If it does not, rewrite the body from this agent's own scratch file and re-verify. **Cap this at 2 rewrites:** if the trailer still doesn't match, the scratch file itself is suspect — re-derive the body from your own branch's commits/diff for one final attempt, and if that also fails, STOP, leave the ${pr} open, and say so in the result you hand back. Never loop on it: Phase C waits for every agent to finish, so one agent stuck re-publishing blocks the whole batch's merges. And never assume a zero exit code means the right body was published.-## Phase C — Serialize the merges (orchestrator, after all agents finish)-Merge the ready ${pr}s ONE AT A TIME. The parent orchestrator acquires the repository merge admission described in the Claim Workflow Handoff for each ready ${pr}, before its final base sync, and releases only its own lease after merged cleanup or a recorded leave-open outcome. For each: re-sync onto the latest default branch, gate on **required** CI (one re-run on a flaky required check, then proceed; a real failure or an irreconcilable conflict leaves that ${pr} OPEN and recorded — move to the next), then \`${mergeCmd}\`. After all merges, run Phase 7 cleanup once per merged worktree.+## Phase C — Serialize only the merge instant (orchestrator, after all agents finish)+Bring every ready ${pr} to a CI-verified head CONCURRENTLY, without merge admission: re-sync each onto the latest default branch, run pregate, push, and gate on **required** CI on that exact head (one re-run on a flaky required check, then proceed; a real failure or an irreconcilable conflict leaves that ${pr} OPEN and recorded — move to the next). Then merge them ONE AT A TIME: for each green ${pr}, the parent orchestrator acquires the repository merge admission described in the Claim Workflow Handoff, re-reads the ${pr}, merges with \`${mergeCmd} ${mergePin}\` when the forge still reports it mergeable, and releases its own lease immediately (outcome merged). A ${pr} the forge no longer reports mergeable releases with outcome resync and goes back through the concurrent sync/pregate/CI step outside the lease; a base that moved while the ${pr} stays mergeable needs no resync. After all merges, run Phase 7 cleanup once per merged worktree.**Then — orchestrator only, ALWAYS, even though swarm work ships via ${pr}s with no working-tree change — write the completion sentinel** described in the **Completion Workflow** section below (write it at the EXACT sentinel path that section gives you — the filename carries your agent id — with a short run summary of the issues claimed + their ${pr}s + merge outcomes). Skip the \`/simplify\` and push/${pr} steps of that workflow (each fan-out agent already ran them), but the sentinel write is NOT optional: it is the ONLY signal that marks this CoS task complete and hands the orchestrator's summary back. A swarm run that ends without the sentinel leaves the task hanging as if it never finished.diff --git a/server/services/cosTaskPreStepBlocks.test.js b/server/services/cosTaskPreStepBlocks.test.jsindex 728be27d07..649ea80c32 100644--- a/server/services/cosTaskPreStepBlocks.test.js+++ b/server/services/cosTaskPreStepBlocks.test.js@@ -220,6 +220,18 @@ describe('resolveSwarmBlock', () => {expect(block).toMatch(/Never loop on it/i);});+ it('validates every PR concurrently and holds admission only around each pinned merge', () => {+ const block = resolveSwarmBlock('claim-issue', 3);+ const phaseC = block.slice(block.indexOf('## Phase C'));+ const order = ['CONCURRENTLY, without merge admission', 'required** CI', 'acquires the repository merge admission', 'gh pr merge --match-head-commit <ci-verified-sha>', 'releases its own lease immediately'];+ const positions = order.map((marker) => phaseC.indexOf(marker));+ expect(positions.every((at) => at >= 0)).toBe(true);+ expect(positions).toEqual([...positions].sort((x, y) => x - y));+ expect(phaseC).toContain('outcome resync');+ expect(phaseC).not.toMatch(/before its final base sync/i);+ expect(resolveSwarmBlock('claim-issue-gitlab', 3)).toContain('glab mr merge --sha <ci-verified-sha>');+ });+it('returns a glab/MR swarm directive for the gitlab claim body', () => {const block = resolveSwarmBlock('claim-issue-gitlab', 4);expect(block).toContain('--swarm=4');diff --git a/server/services/promptSections/completion.js b/server/services/promptSections/completion.jsindex 3a881cb444..aede181669 100644--- a/server/services/promptSections/completion.js+++ b/server/services/promptSections/completion.js@@ -588,23 +588,28 @@ function buildClaimOwnershipSection(agentId) {].join('\n');}-/** Only the registered parent acquires; swarm workers keep authoring in parallel. */+/**+ * 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) {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 }) });return ['## Repository merge admission',- 'Complete publication, validation, configured reviews and current-head CI BEFORE acquiring admission. The parent orchestrator (never a fan-out child) must acquire admission only for the final live-state check, merge attempt and remote readback. This applies to a single issue and separately to each ready PR in a swarm. Implementation, review, publication and CI stay concurrent.',- 'Run the following and require a parsed JSON response with admitted:true and a nonempty token; retain that token privately for check/release:',+ '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 (15 seconds), with a progress update at least every minute. Retry for at most 30 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.',- 'Replace TOKEN below with the returned token; check admission immediately before the merge attempt, and require admitted:true:',+ '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.',+ '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.','```bash', command('check', { token: 'TOKEN' }), '```',- 'Admission coordinates participating runs on this install only. Re-read live PR state, head SHA, mergeability and required-check/review results before merging. A conflict-free branch with passing current-head checks and satisfied configured reviews may merge even when it is behind the default branch. Base movement alone does not require a rebase or another CI run. Rebase only for actual conflicts, 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. Never bypass CI, infer success from absent checks, or treat auto-merge/queued as MERGED.',- 'After a verified remote MERGED result, release with outcome merged before cleanup. If a merge attempt requires recovery, a rebase, another push or further CI/review waits, first release with outcome leave-open, complete that work outside admission, rerun affected validation and required reviews/checks on the resulting head, then reacquire for the next merge attempt. On a recorded failure or leave-open handoff, also release with outcome leave-open. Require released:true; report a failed release without deleting or overwriting ownership state:',+ '- 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:','```bash', command('release', { token: 'TOKEN', outcome: 'merged' }), '```',- 'A completed child, empty cwd process list, old timestamp, or CI wait is not proof that the parent has stopped. Only the server may recover a lease after verifying its registered owner completed.',+ 'The server voids an agent lease 5 minutes after acquisition and lets another run reclaim it. A check refused with lease-expired or lease-owner-mismatch means stop: do not merge on that token; acquire again and repeat the re-read. Never bypass CI, infer success from absent checks, merge without the head pin, or treat auto-merge/queued as MERGED. Admission coordinates participating runs on this install only; manual merges and other installs can still move the base, which the forge’s merge state already reflects.',+ 'A completed child, empty cwd process list or CI wait is not proof that the parent has stopped. Only the server may recover a lease, after verifying its registered owner completed or its hold deadline passed.',].join('\n');}diff --git a/server/services/promptSections/completion.test.js b/server/services/promptSections/completion.test.jsindex 22422825ae..b7f1a82960 100644--- a/server/services/promptSections/completion.test.js+++ b/server/services/promptSections/completion.test.js@@ -21,7 +21,6 @@ describe('review-enabled completion merge gate', () => {expect(section).toContain('4. **Wait for CI to finish**');expect(section).toContain('gh pr checks "<PR_URL>" --watch --fail-fast --interval 30');expect(section).toContain('repeat the configured review loop for `copilot` against the new HEAD');- expect(section).toContain('Base movement alone does not require rebasing or restarting CI');expect(section).toContain('gh pr merge "<PR_URL>" --merge --delete-branch');expect(section.indexOf('4. **Wait for CI to finish**')).toBeLessThan(section.indexOf('gh pr merge'));expect(section).toContain('8. Write a short markdown summary');@@ -58,21 +57,29 @@ describe('claim ownership binding instructions (#10089)', () => {});describe('claim parent merge admission instructions', () => {- it('keeps CI concurrent and holds parent admission only for the merge attempt and readback', () => {+ it('acquires only after green CI, merges a CLEAN head pinned and resyncs outside the lease', () => {const prompt = buildClaimFlowCompletionSection({ agentId: 'parent-example' });expect(prompt).toContain('"agentId":"parent-example","action":"acquire"');expect(prompt).toContain('"action":"check"');expect(prompt).toContain('"action":"release"');expect(prompt).toContain('Authorization: Bearer');expect(prompt).toContain('never a fan-out child');- expect(prompt).toContain('at most 30 minutes');- expect(prompt).toContain('current-head CI BEFORE acquiring admission');- expect(prompt).toContain('Base movement alone does not require a rebase or another CI run');- expect(prompt).toContain('first release with outcome leave-open');- expect(prompt).toContain('rerun affected validation and required reviews/checks on the resulting head');- expect(prompt).not.toContain('if it moved, sync again');+ // Ordering: CI-verified head → acquire → final PR re-read → pinned merge.+ const order = ['WITHOUT admission', 'Once required CI is green', '"action":"acquire"', 'Inside the lease, re-read the PR', '--match-head-commit'];+ const positions = order.map((marker) => prompt.indexOf(marker));+ expect(positions.every((at) => at >= 0)).toBe(true);+ expect(positions).toEqual([...positions].sort((x, y) => x - y));+ expect(prompt).toContain('does NOT require a resync or fresh CI');+ expect(prompt).toContain('release with outcome resync');+ expect(prompt).toContain('OUTSIDE the lease');+ expect(prompt).toContain('at most 10 minutes');+ expect(prompt).toContain('lease-expired');+ expect(prompt).toContain('overrides mandatory base-sync instructions in delegated slashdo workflows');expect(prompt).toContain('outcome leave-open');expect(prompt).toContain('never permission to proceed');+ expect(prompt).not.toMatch(/BEFORE the final base sync/i);+ expect(prompt).not.toMatch(/Keep admission through[^.]*CI/i);+ expect(prompt).not.toContain('if it moved, sync again');expect(buildClaimFlowCompletionSection()).toContain('do not merge');expect(buildClaimFlowCompletionSection({ agentId: 'parent-example', leavePrOpen: true })).not.toContain('/merge-admission');});