Skip to content

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

fix: coordinate final merges across concurrent claim runs (#10058)

[._.]/ Adam Eivy355def9ebb49
diff --git a/docs/features/chief-of-staff.md b/docs/features/chief-of-staff.md
index eeadf6dbe8..c704999930 100644
--- a/docs/features/chief-of-staff.md
+++ b/docs/features/chief-of-staff.md
@@ -24,6 +24,39 @@ Autonomous agent manager that watches task files, spawns sub-agents, and maintai
9. **Durable Agent Feedback**: Completion notifications accept quick ratings, while the Agents tab keeps a filterable queue of loaded runs that still need feedback after a notification expires. Recent unrated completed runs are also surfaced as a CoS insight that links directly to the URL-backed review filter. Feedback details can be attached to helpful, unhelpful, or neutral ratings so learning has actionable context. The Learning tab aggregates ratings from both live state and date-bucketed agent archives, de-duplicating runs that are still present in both stores so historical feedback remains visible for the archive retention window.
10. **Learning-Aligned ETAs**: Pending tasks and active agents resolve their estimates from the same metadata-first task-learning bucket that records outcomes, including archived scheduled-agent metadata, instead of inferring a potentially different category from task text.
+## Repository merge admission
+
+Self-managed claim parents and the deterministic pending-merge sweep share one
+repository-scoped final-merge 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. 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.
+
+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 compatible
+with 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.
+
+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.
+
## Task File Format
```markdown
diff --git a/server/lib/hostControlRoutes.js b/server/lib/hostControlRoutes.js
index 1125e7b6cc..14bcd4db6e 100644
--- a/server/lib/hostControlRoutes.js
+++ b/server/lib/hostControlRoutes.js
@@ -166,6 +166,7 @@ export const HOST_CONTROL_ROUTES = Object.freeze([
// CoS: queue, release or steer an agent that runs shell commands in a
// worktree, or a job that runs a shell command directly.
+ 'POST /api/cos/merge-admission',
'POST /api/cos/start',
'POST /api/cos/resume',
'POST /api/cos/evaluate',
diff --git a/server/routes/cosAgentRoutes.js b/server/routes/cosAgentRoutes.js
index 6e72f71b7b..d0042f246a 100644
--- a/server/routes/cosAgentRoutes.js
+++ b/server/routes/cosAgentRoutes.js
@@ -13,6 +13,18 @@ import { validateRequest, resumeCosAgentSchema, relaunchCosAgentSchema, cosAgent
const router = Router();
+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(),
+});
+router.post('/merge-admission', asyncHandler(async (req, res) => {
+ const input = validateRequest(mergeAdmissionSchema, req.body ?? {});
+ const { claimMergeAdmission } = await import('../services/cosMergeAdmission.js');
+ res.json(await claimMergeAdmission(input));
+}));
+
// `reason` is persisted into task metadata + interpolated into logs; guard the
// shape so a non-string body can't store `[object Object]`.
const pauseBodySchema = z.object({ reason: z.string().max(500).optional() });
diff --git a/server/services/agentPromptBuilder.js b/server/services/agentPromptBuilder.js
index b0050ea66e..00fb73ed9b 100644
--- a/server/services/agentPromptBuilder.js
+++ b/server/services/agentPromptBuilder.js
@@ -550,6 +550,7 @@ ${buildResumeSection(task, worktreeInfo)}` : '';
leavePrOpen: resolvePrCompletion(task.metadata) === PR_COMPLETIONS.LEAVE_OPEN || leavesPrForHuman(task),
prCompletion: task.metadata?.prCompletion || null,
claimResume: claimResumeContext(task, worktreeInfo),
+ agentId,
}),
[COMPLETION_MODES.AUDIT_FLOW]: () => buildAuditFlowCompletionSection({ isTui, sentinelPath }),
[COMPLETION_MODES.RECONCILE_FLOW]: () => buildReconcileFlowCompletionSection({ sentinelPath }),
@@ -1059,6 +1060,7 @@ function buildLightContextSections(task, workspaceDir, worktreeInfo, { isTui = t
leavePrOpen: resolvePrCompletion(task.metadata) === PR_COMPLETIONS.LEAVE_OPEN || leavesPrForHuman(task),
prCompletion: task.metadata?.prCompletion || null,
claimResume: claimResumeContext(task, worktreeInfo),
+ agentId,
})),
[COMPLETION_MODES.READ_ONLY]: () => contractSections.push(buildReadOnlyCompletionSection({ isTui, sentinelPath: lightSentinelPath() })),
[COMPLETION_MODES.REVIEW_LOOP_FOLLOW_UP]: () => {
diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.js
index b6e1b00e59..52f45c3d92 100644
--- a/server/services/agentPromptBuilder.test.js
+++ b/server/services/agentPromptBuilder.test.js
@@ -522,7 +522,7 @@ describe('claim-flow completion handoff', () => {
const lightPrompt = buildLightContextPrompt(
makeTask({ metadata: { claimFlow: true, useWorktree: false, openPR: false, prCompletion: 'merge-on-green' } }),
'/repo', null,
- { isTui: true, providerId: 'codex-tui', providerCommand: 'codex' },
+ { isTui: true, providerId: 'codex-tui', providerCommand: 'codex', agentId: 'parent-example' },
);
expect(lightPrompt).toMatch(/## Claim Workflow Handoff/);
@@ -532,13 +532,17 @@ describe('claim-flow completion handoff', () => {
const apiPrompt = await buildAgentPrompt(
makeTask({ metadata: { claimFlow: true, useWorktree: false, openPR: false, prCompletion: 'merge-on-green' } }),
- {}, '/repo', null, { providerType: 'api' },
+ {}, '/repo', null, { providerType: 'api', agentId: 'parent-example' },
);
expect(apiPrompt).toMatch(/## Claim Workflow Handoff/);
expect(apiPrompt).toContain('PR completion policy: MERGE ON GREEN (no code review)');
expect(apiPrompt).not.toContain('## Reviewer pin');
expect(apiPrompt).not.toContain('Required-review publication rule');
+ for (const prompt of [lightPrompt, apiPrompt]) {
+ expect(prompt).toContain('"agentId":"parent-example","action":"acquire"');
+ expect(prompt).toContain('never a fan-out child');
+ }
});
it('keeps the full API no-change prompt coupled to the normal change workflow', async () => {
diff --git a/server/services/cosMergeAdmission.js b/server/services/cosMergeAdmission.js
new file mode 100644
index 0000000000..8e87cefcaf
--- /dev/null
+++ b/server/services/cosMergeAdmission.js
@@ -0,0 +1,134 @@
+/** Repository-wide final-merge admission for participating runs on this install. */
+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 serverOwner = randomUUID();
+const sweepTokens = new Set();
+const refuse = (reason) => ({ admitted: false, reason, retryAfterMs });
+const repositoryKey = (origin) => origin?.host && origin?.fullName
+ ? `${origin.host.replace(/^ssh\.github\.com$/i, 'github.com')}/${origin.fullName}`.toLowerCase()
+ : null;
+const ownerPath = (agent) => agent?.metadata?.sourceWorkspace || agent?.sourceWorkspace
+ || agent?.metadata?.workspacePath || agent?.workspacePath;
+const binding = (agent) => ({ agentId: agent.id, startedAt: agent.startedAt, taskId: agent.taskId });
+const sameAgent = (lease, agent) => agent?.id === lease.agentId && agent?.startedAt === lease.startedAt
+ && agent?.taskId === lease.taskId;
+const validLease = (lease, repository) => isPlainObject(lease) && lease.repository === repository
+ && typeof lease.token === 'string' && lease.token.length > 0 && Number.isFinite(Date.parse(lease.acquiredAt))
+ && (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);
+
+async function transaction(work) {
+ // Lazy: almost every task-generator suite reaches prWatcher, even when no
+ // pending merge exists. Admission needs runtime state only on the merge path.
+ const { withStateLock, readMergeAdmissionStateForSafetyCheck, loadState, saveState } = await import('./cosState.js');
+ return withStateLock(async () => {
+ const snapshot = await readMergeAdmissionStateForSafetyCheck().catch(() => null);
+ if (!snapshot?.trusted || !isPlainObject(snapshot.agents) || !isPlainObject(snapshot.mergeAdmissions)) {
+ return refuse('ownership-unreadable');
+ }
+ const state = await loadState();
+ // A recovered/defaulted or externally replaced state is not proof of an
+ // empty ownership set. Do not let the cache overwrite contradictory disk.
+ if (JSON.stringify(state.agents) !== JSON.stringify(snapshot.agents)
+ || JSON.stringify(state.mergeAdmissions ?? {}) !== JSON.stringify(snapshot.mergeAdmissions)) {
+ return refuse('ownership-stale');
+ }
+ // Copy before mutation: a failed atomic write must not admit from a cache
+ // that falsely remembers a successful grant/release.
+ const next = { ...state, agents: { ...state.agents }, mergeAdmissions: { ...snapshot.mergeAdmissions } };
+ return work(next, saveState);
+ });
+}
+
+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.
+ try { process.kill(lease.pid, 0); return false; }
+ catch (err) { return err.code === 'ESRCH'; }
+ }
+ let owner = state.agents[lease.agentId];
+ if (!owner) {
+ const { readAgentRecordOrUnreadable } = await import('./cosAgentLifecycle.js');
+ owner = await readAgentRecordOrUnreadable(lease.agentId);
+ }
+ return sameAgent(lease, owner) && owner.status === 'completed' && Number.isFinite(Date.parse(owner.completedAt));
+}
+
+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) {
+ return { admitted: true, token: held.token, repository };
+ }
+ if (!await inactive(held, state)) return refuse('owner-active-or-unverified');
+ }
+ const lease = { ...owner, repository, token: randomUUID(), acquiredAt: new Date().toISOString() };
+ state.mergeAdmissions[repository] = lease;
+ if (owner.kind === 'sweep') sweepTokens.add(lease.token);
+ await save(state);
+ return { admitted: true, token: lease.token, repository };
+}
+
+/** 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) => {
+ const agent = state.agents[agentId];
+ if (!agent || agent.id !== agentId || agent.status !== 'running' || !agent.startedAt || !agent.taskId
+ || !(isTruthyMeta(agent.metadata?.claimPicksOwnBranch) || agent.metadata?.claimBranch)) {
+ return refuse('claim-owner-unverified');
+ }
+ if (!ownerPath(agent)) return refuse('repository-unreadable');
+ const repository = repositoryKey(await getOriginInfo(ownerPath(agent)).catch(() => null));
+ if (!repository) return refuse('repository-unreadable');
+ if (action === 'acquire') {
+ if (Object.entries(state.mergeAdmissions).some(([key, held]) =>
+ !validLease(held, key) || (held.agentId === agentId && (!sameAgent(held, agent) || key !== repository)))) {
+ return refuse('lease-owner-mismatch');
+ }
+ return admit(state, save, repository, { kind: 'agent', ...binding(agent) });
+ }
+ const lease = state.mergeAdmissions[repository];
+ 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');
+ delete state.mergeAdmissions[repository];
+ state.agents[agentId] = { ...agent, metadata: { ...agent.metadata,
+ lastMergeAdmission: { repository, outcome, releasedAt: new Date().toISOString() },
+ } };
+ await save(state);
+ return { admitted: false, released: true, outcome };
+ });
+}
+
+/** A sweep holds admission only around its final read/assessment/merge attempt. */
+export async function withPendingMergeAdmission(origin, work) {
+ const repository = repositoryKey(origin);
+ if (!repository) return refuse('repository-unreadable');
+ const admission = await transaction((state, save) => admit(state, save, repository, {
+ kind: 'sweep', serverOwner, pid: process.pid,
+ }));
+ if (!admission.admitted) return admission;
+ try {
+ return { admitted: true, result: await work() };
+ } finally {
+ const released = await transaction(async (state, save) => {
+ const lease = state.mergeAdmissions[repository];
+ if (!validLease(lease, repository) || lease.token !== admission.token) return refuse('lease-owner-mismatch');
+ delete state.mergeAdmissions[repository];
+ await save(state);
+ return { released: true };
+ });
+ if (released.released) sweepTokens.delete(admission.token);
+ else console.error(`❌ Pending merge admission release withheld: ${released.reason}`);
+ }
+}
diff --git a/server/services/cosMergeAdmission.test.js b/server/services/cosMergeAdmission.test.js
new file mode 100644
index 0000000000..bc81ff01cd
--- /dev/null
+++ b/server/services/cosMergeAdmission.test.js
@@ -0,0 +1,129 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
+
+const fixture = vi.hoisted(() => ({ state: null, disk: null, trusted: true, archived: null }));
+vi.mock('./cosState.js', () => ({
+ withStateLock: createFileWriteQueue(),
+ loadState: async () => fixture.state,
+ readMergeAdmissionStateForSafetyCheck: async () => ({ trusted: fixture.trusted, ...structuredClone(fixture.disk) }),
+ saveState: async (state) => { fixture.disk = structuredClone(state); fixture.state = state; },
+}));
+vi.mock('../lib/gitRemote.js', () => ({
+ getOriginInfo: async (path) => ({ host: path === '/repos/alias' ? 'ssh.github.com' : 'github.com',
+ fullName: path === '/repos/other' ? 'example/other' : 'Example/Repo' }),
+}));
+vi.mock('./cosAgentLifecycle.js', () => ({ readAgentRecordOrUnreadable: async () => fixture.archived }));
+import { 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 } });
+const acquire = (agentId) => claimMergeAdmission({ agentId, action: 'acquire' });
+const release = (agentId, token, outcome = 'merged') => claimMergeAdmission({ agentId, token, action: 'release', outcome });
+const persist = () => { fixture.disk = structuredClone(fixture.state); };
+beforeEach(() => {
+ fixture.trusted = true;
+ fixture.archived = null;
+ fixture.state = { agents: { a: parent('a'), b: parent('b', '/repos/alias'), c: parent('c', '/repos/other') }, mergeAdmissions: {} };
+ persist();
+});
+
+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;
+
+ 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(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(await release('a', a.token)).toMatchObject({ released: true });
+ expect((await acquire('b')).admitted).toBe(true);
+ });
+
+ it('holds the sweep through async merge and permits another repository concurrently', async () => {
+ let finish;
+ let entered;
+ const started = new Promise(resolve => { entered = resolve; });
+ const done = new Promise(resolve => { finish = resolve; });
+ const sweep = withPendingMergeAdmission(origin, async () => { entered(); await done; return 'merged'; });
+ await started;
+ expect((await acquire('a')).admitted).toBe(false);
+ expect((await acquire('c')).admitted).toBe(true);
+ finish();
+ expect(await sweep).toEqual({ admitted: true, result: 'merged' });
+ expect((await acquire('a')).admitted).toBe(true);
+ });
+
+ it('recovers only a matching finalized parent and preserves all authored metadata', async () => {
+ await acquire('a');
+ fixture.state.agents.a.status = 'paused'; persist();
+ expect((await acquire('b')).admitted).toBe(false);
+ fixture.archived = { ...fixture.state.agents.a, status: 'completed', completedAt: '2026-01-02T00:00:00Z' };
+ delete fixture.state.agents.a; persist();
+ expect((await acquire('b')).admitted).toBe(true);
+ expect(fixture.archived.metadata.sourceWorkspace).toBe('/repos/example');
+ });
+
+ it.each(['unreadable', 'stale', 'missing-owner', 'mismatched-owner', 'malformed-lease'])('fails closed on %s without invoking merge', async (mode) => {
+ await acquire('a');
+ if (mode === 'unreadable') fixture.trusted = false;
+ if (mode === 'stale') fixture.disk.agents.a.status = 'completed';
+ if (mode === 'missing-owner') { delete fixture.state.agents.a; persist(); }
+ if (mode === 'mismatched-owner') { fixture.state.agents.a.startedAt = '2026-02-01T00:00:00Z'; persist(); }
+ if (mode === 'malformed-lease') { fixture.state.mergeAdmissions['github.com/example/repo'] = null; persist(); }
+ const work = vi.fn();
+ expect((await withPendingMergeAdmission(origin, work)).admitted).toBe(false);
+ expect(work).not.toHaveBeenCalled();
+ });
+
+ it('refuses a changed parent repository and foreign/stale release tokens', async () => {
+ const a = await acquire('a');
+ expect((await acquire('a')).token).toBe(a.token);
+ expect((await release('b', a.token)).released).not.toBe(true);
+ expect((await release('a', 'wrong-token')).released).not.toBe(true);
+ fixture.state.agents.a.metadata.sourceWorkspace = '/repos/other'; persist();
+ expect((await acquire('a')).admitted).toBe(false);
+ fixture.state.agents.a.metadata.sourceWorkspace = '/repos/example'; persist();
+ expect(await release('a', a.token, 'leave-open')).toMatchObject({ released: true });
+ const next = await acquire('a');
+ 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');
+ });
+
+ it('recovers a crashed sweep only when its process is proven absent', async () => {
+ fixture.state.mergeAdmissions['github.com/example/repo'] = {
+ kind: 'sweep', serverOwner: 'previous-server', pid: 123456,
+ repository: 'github.com/example/repo', token: 'previous-token', acquiredAt: '2020-01-01',
+ };
+ persist();
+ const probe = vi.spyOn(process, 'kill').mockImplementation(() => { throw Object.assign(new Error('denied'), { code: 'EPERM' }); });
+ try {
+ expect((await acquire('a')).admitted).toBe(false);
+ probe.mockImplementation(() => { throw Object.assign(new Error('gone'), { code: 'ESRCH' }); });
+ expect((await acquire('a')).admitted).toBe(true);
+ } finally { probe.mockRestore(); }
+ });
+
+ it('releases a failed sweep without swallowing its error', async () => {
+ await expect(withPendingMergeAdmission(origin, async () => { throw new Error('forge unavailable'); })).rejects.toThrow('forge unavailable');
+ expect((await acquire('a')).admitted).toBe(true);
+ });
+});
diff --git a/server/services/cosState.js b/server/services/cosState.js
index 58bd4b80cc..d89a23103d 100644
--- a/server/services/cosState.js
+++ b/server/services/cosState.js
@@ -430,6 +430,13 @@ async function readStateForSafetyCheck() {
return { trusted: true, state };
}
+// Merge admission shares the runtime ownership store and its write queue.
+// Missing leases are legacy empty state; malformed leases are never defaulted.
+export async function readMergeAdmissionStateForSafetyCheck() {
+ const { trusted, state } = await readStateForSafetyCheck();
+ return { trusted, agents: state?.agents ?? null, mergeAdmissions: state && Object.hasOwn(state, 'mergeAdmissions') ? state.mergeAdmissions : {} };
+}
+
// The Persistent Mind slice, for the update route's image-work gate.
export async function readPersistentMindStateForSafetyCheck() {
const { trusted, state } = await readStateForSafetyCheck();
diff --git a/server/services/cosState.test.js b/server/services/cosState.test.js
index e5bd741457..8057378fd9 100644
--- a/server/services/cosState.test.js
+++ b/server/services/cosState.test.js
@@ -102,6 +102,21 @@ describe('cosState persistence', () => {
});
});
+ it('preserves durable merge leases across reloads and does not default malformed ownership', async () => {
+ const lease = { kind: 'agent', agentId: 'parent', repository: 'github.com/example/repo', token: 'example-token' };
+ writeState({ agents: {}, mergeAdmissions: { [lease.repository]: lease } });
+ let store = await freshModule();
+ await store.saveState(await store.loadState());
+ store = await freshModule();
+ expect(await store.readMergeAdmissionStateForSafetyCheck()).toEqual({
+ trusted: true, agents: {}, mergeAdmissions: { [lease.repository]: lease },
+ });
+ writeState({ agents: {}, mergeAdmissions: null });
+ expect((await store.readMergeAdmissionStateForSafetyCheck()).mergeAdmissions).toBeNull();
+ writeFileSync(STATE_PATH, 'broken');
+ expect((await store.readMergeAdmissionStateForSafetyCheck()).trusted).toBe(false);
+ });
+
// The split's version of what the sidecar used to buy: config lives in its
// own file, so an unreadable state.json cannot take the settings with it.
it('keeps config when state.json becomes unreadable', async () => {
diff --git a/server/services/cosTaskPreStepBlocks.js b/server/services/cosTaskPreStepBlocks.js
index 4d1c0c2a05..c3844107d7 100644
--- a/server/services/cosTaskPreStepBlocks.js
+++ b/server/services/cosTaskPreStepBlocks.js
@@ -288,7 +288,7 @@ ${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. 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.
+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.
**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/prWatcher.js b/server/services/prWatcher.js
index 807d2485e2..71c514025b 100644
--- a/server/services/prWatcher.js
+++ b/server/services/prWatcher.js
@@ -405,23 +405,35 @@ export async function processPendingMergePrs(app) {
let withheldReason = null;
if (isPendingMergeReady(prView)) {
- const { assessPullRequestForAction } = await import('./prReviewerSecurity.js');
- const readDiff = () => execGh(['pr', 'diff', String(entry.prNumber), '--repo', repoSpec],
- undefined, { ...forgeExec, backoffKey: repoSpec }).catch(() => null);
- const assessment = await assessPullRequestForAction({
- pr: prView, diff: await readDiff(), repoFullName: origin.fullName,
- readPr: () => readPendingPullRequest(repoSpec, entry.prNumber, forgeExec),
- readDiff,
- readIssue: async (number) => safeJSONParse(await execGh([
- 'api', '--hostname', githubApiHost(origin.host), `repos/${origin.fullName}/issues/${number}`,
- ], undefined, { ...forgeExec, backoffKey: repoSpec }).catch(() => null), null),
- }).catch(() => ({ ok: false }));
- withheldReason = assessment.ok ? null : 'the complete current contribution assessment was unavailable or withheld';
- const merge = assessment.ok
- ? await git.mergePR(app.repoPath, entry.prNumber, {
- forgeAccount: app?.forgeAccount || null, expectedHeadSha: prView.headRefOid,
- }).catch((err) => ({ success: false, error: err.message }))
- : { success: false, error: withheldReason };
+ const { withPendingMergeAdmission } = await import('./cosMergeAdmission.js');
+ const admitted = await withPendingMergeAdmission(origin, async () => {
+ const currentPr = await readPendingPullRequest(repoSpec, entry.prNumber, forgeExec);
+ if (!currentPr || !isPendingMergeReady(currentPr)) return { success: false, error: 'Current head is not merge-ready' };
+ const { assessPullRequestForAction } = await import('./prReviewerSecurity.js');
+ const readDiff = () => execGh(['pr', 'diff', String(entry.prNumber), '--repo', repoSpec],
+ undefined, { ...forgeExec, backoffKey: repoSpec }).catch(() => null);
+ const assessment = await assessPullRequestForAction({
+ pr: currentPr, diff: await readDiff(), repoFullName: origin.fullName,
+ readPr: () => readPendingPullRequest(repoSpec, entry.prNumber, forgeExec),
+ readDiff,
+ readIssue: async (number) => safeJSONParse(await execGh([
+ 'api', '--hostname', githubApiHost(origin.host), `repos/${origin.fullName}/issues/${number}`,
+ ], undefined, { ...forgeExec, backoffKey: repoSpec }).catch(() => null), null),
+ }).catch(() => ({ ok: false }));
+ withheldReason = assessment.ok ? null : 'the complete current contribution assessment was unavailable or withheld';
+ return assessment.ok
+ ? await git.mergePR(app.repoPath, entry.prNumber, {
+ forgeAccount: app?.forgeAccount || null, expectedHeadSha: currentPr.headRefOid,
+ }).catch((err) => ({ success: false, error: err.message }))
+ : { success: false, error: withheldReason };
+ });
+ if (!admitted.admitted) {
+ result.waiting = (result.waiting || 0) + 1;
+ outcomes.set(key, entry);
+ console.log(`⏳ Pending merge deferred for PR #${entry.prNumber}: ${admitted.reason}`);
+ continue;
+ }
+ const merge = admitted.result;
if (merge.success) {
outcomes.set(key, null);
result.merged += 1;
diff --git a/server/services/prWatcher.test.js b/server/services/prWatcher.test.js
index aa6923865b..4b9ad78193 100644
--- a/server/services/prWatcher.test.js
+++ b/server/services/prWatcher.test.js
@@ -1,5 +1,17 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
+// Real admission logic over a serialized synthetic runtime store.
+const admissionState = vi.hoisted(() => ({ state: { agents: {}, mergeAdmissions: {} } }));
+vi.mock('./cosState.js', async () => {
+ const { createFileWriteQueue } = await import('../lib/fileWriteQueue.js');
+ return {
+ withStateLock: createFileWriteQueue(),
+ loadState: async () => admissionState.state,
+ saveState: async state => { admissionState.state = state; },
+ readMergeAdmissionStateForSafetyCheck: async () => ({ trusted: true, ...structuredClone(admissionState.state) }),
+ };
+});
+
// ─── mocks (must precede the import under test) ──────────────────────────────
const execGhMock = vi.fn();
@@ -215,6 +227,7 @@ function installPendingEvidence() {
describe('merge-only PR watcher', () => {
beforeEach(() => {
+ admissionState.state = { agents: {}, mergeAdmissions: {} };
getOriginInfoMock.mockResolvedValue({ hasOrigin: true, isGithub: true, host: 'github.com', fullName: 'o/r' });
});
@@ -240,6 +253,23 @@ describe('merge-only PR watcher', () => {
})).toBe(false);
});
+ it('defers a pending merge without consuming retries while a live parent holds admission', async () => {
+ const { claimMergeAdmission } = await import('./cosMergeAdmission.js');
+ admissionState.state.agents.parent = { id: 'parent', taskId: 'task-parent', startedAt: '2026-01-01', status: 'running',
+ metadata: { sourceWorkspace: '/repos/app1', claimPicksOwnBranch: true } };
+ const lease = await claimMergeAdmission({ agentId: 'parent', action: 'acquire' });
+ expect(lease.admitted).toBe(true);
+ const app = pendingApp();
+ mockApps.set(app.id, app);
+ installPendingEvidence();
+ expect(await processPendingMergePrs(app)).toMatchObject({ waiting: 1, merged: 0 });
+ expect(mergePrMock).not.toHaveBeenCalled();
+ expect(readPendingMergePrs(mockApps.get(app.id))[0].ticks).toBe(0);
+ await claimMergeAdmission({ agentId: 'parent', action: 'release', token: lease.token, outcome: 'leave-open' });
+ mergePrMock.mockResolvedValue({ success: true });
+ expect(await processPendingMergePrs(app)).toMatchObject({ merged: 1 });
+ });
+
it('merges a green pending PR without spawning a follow-up agent', async () => {
const app = pendingApp();
mockApps.set(app.id, app);
diff --git a/server/services/promptSections/completion.js b/server/services/promptSections/completion.js
index c0ff079974..af90b893fe 100644
--- a/server/services/promptSections/completion.js
+++ b/server/services/promptSections/completion.js
@@ -13,6 +13,9 @@ import { PR_COMPLETIONS, leavesPrForHuman, resolvePrCompletion } from '../../lib
import { LIGHT_CONTEXT_PROVIDER_TYPES, SIMPLIFY_INLINE_REVIEW } from './constants.js';
import { buildCiMergeGateSteps, buildReviewLoopFollowUpSection, reviewPolicyToLoopMetadata, LEAVE_PR_OPEN_STEP } from './reviewLifecycle.js';
+import { localApiBaseUrl } from '../../lib/networkExposure.js';
+import { agentApiCurl } from '../../lib/agentApiToken.js';
+
import { isTruthyMeta } from '../../lib/metadataFlags.js';
export const NO_CHANGE_AUDIT_GUIDANCE = 'This audit may legitimately conclude that no change is needed. First verify the data this audit owns against authoritative sources. If the audited data is current, leave the worktree clean and do not run the commit, push, PR, or review steps below; write the completion sentinel when this provider uses one, or exit without committing when it does not. If a change is needed, continue through the normal workflow below.';
@@ -547,13 +550,34 @@ export function buildClaimResumeOverride({ priorAgentId, branchName, worktreePat
].join('\n');
}
-export function buildClaimFlowCompletionSection({ isTui = false, sentinelPath = null, reviewersCsv = '', leavePrOpen = false, prCompletion = null, claimResume = null } = {}) {
+/** Only the registered parent acquires; swarm workers keep authoring in parallel. */
+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 }) });
+ return [
+ '## Repository merge admission',
+ 'After local review and PR publication, the parent orchestrator (never a fan-out child) must acquire admission immediately BEFORE the final base sync, pregate/push, current-head CI wait and merge. This applies to a single issue and separately to each ready PR in a swarm. Implementation/review and initial PR publication 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:',
+ '```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.',
+ 'Keep admission through final sync, pregate, push, CI, merge and cleanup. Replace TOKEN below with the returned token; check admission before each push or merge, and require admitted:true:',
+ '```bash', command('check', { token: 'TOKEN' }), '```',
+ 'Admission coordinates participating runs on this install only. Manual merges and other installs can still advance the base: re-read the live default-branch SHA before merging; if it moved, sync again, rerun pregate and require fresh CI on the resulting head. Never bypass CI, infer success from absent checks, or treat auto-merge/queued as MERGED.',
+ 'After a verified remote MERGED result and cleanup, release with outcome merged. On a recorded failure or leave-open handoff, release with outcome leave-open instead. 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.',
+ ].join('\n');
+}
+
+export function buildClaimFlowCompletionSection({ isTui = false, sentinelPath = null, reviewersCsv = '', leavePrOpen = false, prCompletion = null, claimResume = null, agentId = null } = {}) {
const isMergeOnGreen = prCompletion === PR_COMPLETIONS.MERGE_ON_GREEN;
const pin = isMergeOnGreen ? '' : buildReviewerPinNote(reviewersCsv);
const resumeOverride = buildClaimResumeOverride(claimResume || {});
const lines = [
...(resumeOverride ? [resumeOverride, ''] : []),
...(pin ? [pin, ''] : []),
+ ...(!leavePrOpen ? [buildMergeAdmissionSection(agentId), ''] : []),
'## Claim Workflow Handoff',
...(leavePrOpen ? [
'PR completion policy: LEAVE OPEN for further human review. This overrides any merge, auto-merge, issue-close, or merged-branch cleanup instruction in the claim prompt and delegated slashdo commands. Do not pass --merge, enable auto-merge, merge the PR/MR, or close the issue/ticket.',
diff --git a/server/services/promptSections/completion.test.js b/server/services/promptSections/completion.test.js
index ba3721d6e1..fd333b92f1 100644
--- a/server/services/promptSections/completion.test.js
+++ b/server/services/promptSections/completion.test.js
@@ -2,7 +2,7 @@ import { describe, expect, it } from 'vitest';
import { COMPLETION_MODES } from '../../lib/agentCompletionMode.js';
import { PR_COMPLETIONS } from '../../lib/prDisposition.js';
import { resolveReviewPolicy } from '../../lib/reviewerConfig.js';
-import { buildTuiCompletionSection } from './completion.js';
+import { buildTuiCompletionSection, buildClaimFlowCompletionSection } from './completion.js';
const render = (forgeCli = 'gh', reviewers = ['copilot']) => buildTuiCompletionSection({
willOpenPR: true,
@@ -41,3 +41,21 @@ describe('review-enabled completion merge gate', () => {
expect(section).toContain('If `LOCAL_OVERALL_STATUS=review-blocked`, do NOT run this merge path');
});
});
+
+
+describe('claim parent merge admission instructions', () => {
+ it('binds the parent through CI, requires resync on external base movement and releases on either outcome', () => {
+ 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('if it moved, sync again, rerun pregate and require fresh CI');
+ expect(prompt).toContain('outcome leave-open');
+ expect(prompt).toContain('never permission to proceed');
+ expect(buildClaimFlowCompletionSection()).toContain('do not merge');
+ expect(buildClaimFlowCompletionSection({ agentId: 'parent-example', leavePrOpen: true })).not.toContain('/merge-admission');
+ });
+});