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: stop generated merge attempts after uncertain outcomes (#12273)
[._.]/ Adam Eivycfea51a3d9ee
diff --git a/server/lib/README.md b/server/lib/README.mdindex ffd1b75f90..29e5540792 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -732,7 +732,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `orchestrationProfile.js` | Orchestrated CoS execution (#5992) — `ORCHESTRATION_MODES` / `ORCHESTRATION_ROLES` (architect, implementer, reviewer), `normalizeOrchestrationProfile` / `normalizeOrchestrationMode`, `isOrchestratedTask` / `roleAssignment` (both inert on a `direct` task, so a stored profile stays opt-in), the six-part `SPEC_PARTS` contract a delegated context-free lane needs, plus `parseReasoningDirective` / `resolveStepEffort` (spec rung → role default → run effort; an unsupported rung is an error, never a silent downgrade). || `apiToolResource.js` | Builds the minimized semantic tool resource served at `/api/api-docs/tools.min.json` — only `x-portos-tool`-annotated operations, flattened to provider-neutral tool records with an HTTP binding and a shared error vocabulary. || `asyncApiSpec.js` | Builds the AsyncAPI 3 Socket.IO document from the generated event catalog with direction-aware operations and explicit modeled/generated payload status. |-| `mergeGateContract.js` | `MANAGED_WORKTREE_CLEANUP_CONTRACT` and its `MANAGED_WORKTREE_COMPLETION_HANDOFF` share head-pinned, checkout-preserving merge and archive/ownership-gated explicit cleanup instructions. `mergeGateOwed({taskOpenPR, rendersInlinePrLifecycle, leaveOpen})` decides whether a completing run actually owed its own PR merge — only the INLINE (`git`/`gh`) prompt renders a Merge Gate section, so a `/do:pr` run is inert here; `resolveMergeGateVerdict({prProbe, summary})` classifies a run that did (`merged` / `auto-merge-enabled` / `merge-handoff-queued` / `no-pr-action` / `leave-open-stated` / `needs-reprompt`) from the PR's live state and the agent's own sentinel text; `summaryStatesLeaveOpen` and `buildMergeGateReprompt` are its text-matching and corrective-prompt helpers. `buildAutoMergeHandoffInstructions(prRef)` shares the verified GitHub pending-CI handoff across generated merge workflows. `hasHealthyAutoMergeRequest(pr, now?)` bounds pending handoffs to one hour with readable, non-failed CI; `prProbe` also verifies the local head matches GitHub before accepting `autoMergeEnabled` or a pending-merge receipt (`mergeHandoffQueued`). Pure — the PR lookup lives in `../services/prProbe.js`, the re-prompt delivery in `agentTuiSpawning.js`. |+| `mergeGateContract.js` | `buildManagedGithubMergeScript()` emits the shared claim merge block with verified allowed-method selection, fresh head/check/admission gates and fail-closed mutation readback. `MANAGED_WORKTREE_CLEANUP_CONTRACT` and its `MANAGED_WORKTREE_COMPLETION_HANDOFF` share head-pinned, checkout-preserving merge and archive/ownership-gated explicit cleanup instructions. `mergeGateOwed({taskOpenPR, rendersInlinePrLifecycle, leaveOpen})` decides whether a completing run actually owed its own PR merge — only the INLINE (`git`/`gh`) prompt renders a Merge Gate section, so a `/do:pr` run is inert here; `resolveMergeGateVerdict({prProbe, summary})` classifies a run that did (`merged` / `auto-merge-enabled` / `merge-handoff-queued` / `no-pr-action` / `leave-open-stated` / `needs-reprompt`) from the PR's live state and the agent's own sentinel text; `summaryStatesLeaveOpen` and `buildMergeGateReprompt` are its text-matching and corrective-prompt helpers. `buildAutoMergeHandoffInstructions(prRef)` shares the verified GitHub pending-CI handoff across generated merge workflows. `hasHealthyAutoMergeRequest(pr, now?)` bounds pending handoffs to one hour with readable, non-failed CI; `prProbe` also verifies the local head matches GitHub before accepting `autoMergeEnabled` or a pending-merge receipt (`mergeHandoffQueued`). Pure — the PR lookup lives in `../services/prProbe.js`, the re-prompt delivery in `agentTuiSpawning.js`. || `preflightPlan.js` | The programmatic phase of a user-triggered pipeline run, as renderable data. `preflightStepPlan(taskType)` is the step list (generic queued/prepare/dispatch, plus pr-reviewer's own cadence → list-PRs → in-flight → hidden-Unicode/prompt-injection screening → snapshot); `createPreflightState` opens it, `applyPreflightStep` advances one step and closes every earlier unfinished one, `finalizePreflight` closes it `handed-off`/`programmatic`/`nothing-to-do`/`failed`/`interrupted` (first close wins), and `preflightHeadline` names where the run is. Persisted onto a task card by `services/preflightTaskCard.js` and rendered by the Tasks page, so a Run Now is visible before any agent exists. Pure. || `prDisposition.js` | `PR_MISSING_CATEGORY` shares the missing-PR verdict between finalization and cleanup. `resolvePrCompletion(metadata)` resolves the explicit `review-then-merge` / `merge-on-green` / `leave-open` policy, with legacy `reviewLoop` fallback; `explicitPrCompletion(task)` retains only explicit authority (defaults never release a handoff); `leavesPrForHuman(task)` + `PR_STAYS_OPEN_TASK_TYPES` keep JIRA hand-offs open. Shared by the agent prompt builder and `agentWorktreeCleanup` so both halves agree. `resolvePrCreation({taskOpenPR, agentOpensOwnPr, prClaimVerified})` → a `PR_CREATION` tri-state (`never` / `if-missing` / `always`) naming who opens the change request for a completing worktree agent, so the runner, TUI, and direct-CLI completion paths cannot drift into double-firing `gh pr create`. || `recoveryMergeTarget.js` | `repositoryCleanupMergeTarget(task)` → the `{ url, branch }` parent PR a repository-cleanup recovery was filed to land, or null (#12251). A claimed target only: merge admission also requires the completed parent's server-written backlink to that exact task, branch and PR. |diff --git a/server/lib/mergeGateContract.js b/server/lib/mergeGateContract.jsindex 9fc2fbd067..f88bd3a185 100644--- a/server/lib/mergeGateContract.js+++ b/server/lib/mergeGateContract.js@@ -143,8 +143,52 @@ export function buildAutoMergeHandoffInstructions(prRef) {export const MANAGED_WORKTREE_CLEANUP_CONTRACT = `**Managed-worktree preservation and explicit cleanup:** Merge commands must preserve local checkouts and branches on every GitHub CLI version; do not ask gh to delete branches at merge time. Keep every merge-method attempt pinned to the CI-verified head. The parent owns merge admission for swarm children too. First verify remote state is exactly MERGED, then release any owned merge-admission lease and require released:true. Only afterwards begin cleanup.Recheck live claim/worktree ownership, the exact checkout path and holder branch, the exact local branch tip, and the exact remote head ref on its verified remote. Limit all mutations to this task's allowlisted branch and checkout; refuse the default branch. A late unpublished commit or any changed ownership/ref invalidates cleanup: keep the checkout and refs intact and leave a tracked handoff. A missing remote ref (including repository auto-deletion) proves neither local preservation nor archive completion; a failed lookup is not proof of absence.Inventory and preserve ALL unique tracked, untracked AND ignored content outside the checkout, including test results and scratch artifacts; do not follow dependency symlinks into shared installations. Verify the archive manifest and copied bytes before removal, and recheck ownership, local tip and inventory again after archiving. Archive failure or an ownership/ref/inventory change keeps the checkout and branch intact; record the owner, blocker and next step in the owning tracker. Never infer preservation from a clean git status.-After those proofs, when this workflow owns remote cleanup, delete an existing remote head only with an exact-ref compare-and-delete: \`git push --force-with-lease=refs/heads/<branch>:<verified-head> <verified-remote> :refs/heads/<branch>\`. A lease rejection preserves the advanced ref and stops cleanup. Verify that exact remote ref is absent. Then remove only the authorized worktree and ancestry-gate the explicitly named local branch with \`git branch -d <branch>\`; never force local branch deletion. Do not checkout or pull the default branch. A refusal leaves the surviving checkout/ref for reconciliation. Managed review/completion agents that hand teardown to PortOS must leave the local checkout and branch intact for that owner to apply these same gates.`;+After those proofs, when this workflow owns remote cleanup, delete an existing remote head only with an exact-ref compare-and-delete: \`git push --force-with-lease=refs/heads/<branch>:<verified-head> <verified-remote> :refs/heads/<branch>\`. A lease rejection preserves the advanced ref and stops cleanup. Verify that exact remote ref is absent. Fetch the verified remote’s intended default branch explicitly and require \`git merge-base --is-ancestor <exact-local-tip> <fetched-intended-default>\` before local removal; an upstream or a squash/rebase merge alone is not ancestry proof. If ancestry is unproven, preserve both checkout and branch for reconciliation. Then remove only the authorized worktree and delete the explicitly named local branch with \`git branch -d <branch>\`; never force local branch deletion. Do not checkout or pull the default branch. A refusal leaves the surviving checkout/ref for reconciliation. Managed review/completion agents that hand teardown to PortOS must leave the local checkout and branch intact for that owner to apply these same gates.`;/** Review/completion agents hand teardown to PortOS rather than removing it. */export const MANAGED_WORKTREE_COMPLETION_HANDOFF = '**Managed-worktree cleanup handoff:** Verify remote MERGED, release admission (released:true), then recheck ownership and exact local/remote refs. Verify preservation of all unique tracked, untracked and ignored bytes before cleanup. Archive failure or changed ownership/refs preserves the checkout and branch with a tracked handoff. Remote auto-deletion proves no archive. Leave local teardown to PortOS. Any authorized remote deletion must compare-and-delete only the exact ref at the CI-verified head; no default-branch checkout/pull or forced local deletion.';++/** Executable GitHub claim merge phase; admission is supplied by its registered parent. */+export function buildManagedGithubMergeScript() {+ return [+ '# CI_VERIFIED_HEAD is the exact head whose required checks and configured reviews passed.',+ ': "${CI_VERIFIED_HEAD:?Missing CI-verified head}"',+ '[ "$(git rev-parse HEAD)" = "$CI_VERIFIED_HEAD" ] || exit 1',+ 'PR_URL=$(gh pr view --json url -q .url) || exit 1',+ 'case "$PR_URL" in https://*/pull/[0-9]*) BASE_REPO_URL="${PR_URL%/pull/*}" ;; *) exit 1 ;; esac',+ 'portos_read_merge_state() {',+ ' PR_SNAPSHOT=$(gh pr view "$PR_URL" --json state,headRefOid,mergeStateStatus,isDraft,reviewDecision) || return 1',+ ` printf '%s' "$PR_SNAPSHOT" | node -e 'const fs = require("node:fs"); const p = JSON.parse(fs.readFileSync(0, "utf8")); if (p.headRefOid !== process.argv[1] || !["OPEN", "MERGED"].includes(p.state)) process.exit(1); if (p.state === "OPEN" && (p.isDraft !== false || !["CLEAN", "UNSTABLE", "HAS_HOOKS"].includes(p.mergeStateStatus) || ![null, "", "APPROVED"].includes(p.reviewDecision))) process.exit(1); process.stdout.write(p.state);' "$CI_VERIFIED_HEAD"`,+ '}',+ 'STATE=$(portos_read_merge_state) || exit 1',+ 'if [ "$STATE" != "MERGED" ]; then',+ ' for MERGE_METHOD in merge squash rebase; do',+ ' case "$MERGE_METHOD" in',+ ' merge) CAPABILITY=mergeCommitAllowed ;;',+ ' squash) CAPABILITY=squashMergeAllowed ;;',+ ' rebase) CAPABILITY=rebaseMergeAllowed ;;',+ ' esac',+ ' ALLOWED=$(gh repo view "$BASE_REPO_URL" --json "$CAPABILITY" -q ".$CAPABILITY") || exit 1',+ ' [ "$ALLOWED" = "false" ] && continue',+ ' [ "$ALLOWED" = "true" ] || exit 1',+ ' [ "$(git rev-parse HEAD)" = "$CI_VERIFIED_HEAD" ] || exit 1',+ ' STATE=$(portos_read_merge_state) || exit 1',+ ' [ "$STATE" = "MERGED" ] && break',+ ' gh pr checks "$PR_URL" --required || exit 1',+ ' # Source the registered parent’s check function from Repository merge admission first.',+ ' command -v portos_check_merge_admission >/dev/null || { echo "Missing registered merge-admission check" >&2; exit 1; }',+ ' portos_check_merge_admission || exit 1',+ ' STATE=$(portos_read_merge_state) || exit 1',+ ' [ "$STATE" = "MERGED" ] && break',+ ' if gh pr merge "$PR_URL" "--$MERGE_METHOD" --match-head-commit "$CI_VERIFIED_HEAD"; then MERGE_EXIT=0; else MERGE_EXIT=$?; fi',+ ' STATE=$(portos_read_merge_state) || exit 1',+ ' [ "$STATE" = "MERGED" ] && break',+ ' # An attempted mutation has no verified success: never try another method.',+ ' [ "$MERGE_EXIT" = "0" ] || exit "$MERGE_EXIT"',+ ' echo "Expected MERGED, got $STATE" >&2; exit 1',+ ' done',+ 'fi',+ '[ "$STATE" = "MERGED" ] || { echo "No verified merge" >&2; exit 1; }',+ ].join('\n');+}diff --git a/server/services/managedMergeGuard.test.js b/server/services/managedMergeGuard.test.jsnew file mode 100644index 0000000000..1fd9fcb8b9--- /dev/null+++ b/server/services/managedMergeGuard.test.js@@ -0,0 +1,141 @@+import { afterEach, describe, expect, it } from 'vitest';+import { mkdtempSync, readFileSync, rmSync, writeFileSync, existsSync } from 'node:fs';+import { execFileSync, spawnSync } from 'node:child_process';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { DEFAULT_TASK_PROMPTS } from './taskPromptDefaults.js';+import { buildClaimFlowCompletionSection } from './promptSections/completion.js';++let scratch;+afterEach(() => {+ if (scratch) rmSync(scratch, { recursive: true, force: true });+ scratch = null;+});++// The emitted bash is the boundary: functions stand in for forge/loopback+// commands, while its JSON validation and real Git head check execute normally.+const fakeCommands = String.raw`+ curl() {+ printf 'admission\n' >> "$EVENTS"+ case " $* " in *' --fail '*) ;; *) return 99 ;; esac+ while [ "$#" -gt 0 ]; do+ if [ "$1" = --data-binary ]; then shift; REQUEST="$1"; break; fi+ shift+ done+ printf '%s' "$REQUEST" | node -e 'const r=JSON.parse(require("node:fs").readFileSync(0,"utf8")); if(r.agentId!=="parent-example" || r.action!=="check" || r.token!==process.env.MERGE_ADMISSION_TOKEN) process.exit(1)' || return+ [ "$SCENARIO" != changed-after-admission ] || printf changed > "$HEAD_CHANGED"+ case "$SCENARIO" in+ stale-admission) printf '{"admitted":false,"reason":"lease-expired"}' ;;+ malformed-admission) printf 'unreadable' ;;+ transport-admission) return 7 ;;+ *) printf '{"admitted":true}' ;;+ esac+ }+ gh() {+ case "$1 $2" in+ 'repo view')+ printf 'capability %s\n' "$*" >> "$EVENTS"+ case "$SCENARIO:$*" in+ unsupported:*mergeCommitAllowed*) printf false ;;+ unknown-capability:*) printf null ;;+ *) printf true ;;+ esac ;;+ 'pr checks')+ printf 'checks\n' >> "$EVENTS"+ [ "$SCENARIO" != failed-checks ] ;;+ 'pr view')+ case "$*" in *--json\ url*) printf 'https://github.com/example/base/pull/42'; return ;; esac+ COUNT=$(cat "$READ_COUNT"); COUNT=$((COUNT + 1)); printf '%s' "$COUNT" > "$READ_COUNT"+ printf 'read\n' >> "$EVENTS"+ [ "$SCENARIO" != unreadable-before ] || return 7+ if [ "$SCENARIO" = malformed-state ]; then printf unreadable; return; fi+ if [ "$SCENARIO" = unreadable-after ] && [ -s "$MUTATIONS" ]; then return 7; fi+ HEAD_SHA="$CI_VERIFIED_HEAD"+ if [ "$SCENARIO" = changed-head ] && [ "$COUNT" -gt 1 ]; then HEAD_SHA=ffffffffffffffffffffffffffffffffffffffff; fi+ if [ -f "$HEAD_CHANGED" ]; then HEAD_SHA=ffffffffffffffffffffffffffffffffffffffff; fi+ STATE=$(cat "$PR_STATE")+ case "$*" in+ *--json\ state\ -q*) printf '%s' "$STATE" ;;+ *) printf '{"state":"%s","headRefOid":"%s","mergeStateStatus":"CLEAN","isDraft":false,"reviewDecision":"APPROVED"}' "$STATE" "$HEAD_SHA" ;;+ esac ;;+ 'pr merge')+ printf 'merge\n' >> "$EVENTS"+ printf '%s\n' "$*" >> "$MUTATIONS"+ case "$*" in *--match-head-commit\ "$CI_VERIFIED_HEAD"*) ;; *) return 99 ;; esac+ case "$SCENARIO" in+ unknown-ack|unreadable-after) return 1 ;;+ queued) return 0 ;;+ lost-ack-merged) printf MERGED > "$PR_STATE"; return 1 ;;+ *) printf MERGED > "$PR_STATE" ;;+ esac ;;+ *) return 98 ;;+ esac+ }+`;++function runMerge(scenario, key = 'claim-issue', { registered = true, token = true } = {}) {+ scratch = mkdtempSync(join(tmpdir(), 'managed-merge-guard-'));+ const git = (...args) => execFileSync('git', args, { cwd: scratch, encoding: 'utf8' }).trim();+ git('init', '-q');+ git('-c', 'user.name=Example', '-c', '[email protected]', 'commit', '-q', '--allow-empty', '-m', 'reviewed');+ const head = git('rev-parse', 'HEAD');+ const completion = buildClaimFlowCompletionSection({ agentId: registered ? 'parent-example' : null });+ const admission = completion.match(/portos_check_merge_admission\(\) \{[\s\S]*?\n\}/)?.[0] || '';+ const block = [...DEFAULT_TASK_PROMPTS[key].matchAll(/```bash\n([\s\S]*?)```/g)]+ .find(([, body]) => body.includes('# CI_VERIFIED_HEAD'))[1];+ const paths = Object.fromEntries(['EVENTS', 'MUTATIONS', 'READ_COUNT', 'PR_STATE', 'HEAD_CHANGED'].map(name => [name, join(scratch, name)]));+ writeFileSync(paths.READ_COUNT, '0');+ writeFileSync(paths.PR_STATE, scenario === 'already-merged' ? 'MERGED' : 'OPEN');+ const result = spawnSync('bash', ['-eu', '-c', `${fakeCommands}\n${admission}\n${block}`], {+ cwd: scratch, encoding: 'utf8', timeout: 10_000,+ env: { ...process.env, ...paths, SCENARIO: scenario, CI_VERIFIED_HEAD: head, MERGE_ADMISSION_TOKEN: token ? '00000000-0000-4000-8000-000000000001' : '' },+ });+ const lines = path => existsSync(path) ? readFileSync(path, 'utf8').trim().split('\n').filter(Boolean) : [];+ return { ...result, head, completion, events: lines(paths.EVENTS), mutations: lines(paths.MUTATIONS) };+}++// Windows is covered by renderer guards; this execution contract requires bash,+// matching managedMergePreservation.test.js's platform boundary.+describe.skipIf(process.platform === 'win32')('generated claim merge mutation guard (#12273)', () => {+ it.each(['plan-task', 'plan-task-claim', 'claim-issue'])('checks real rendered admission before a pinned %s merge', (key) => {+ const result = runMerge('success', key);+ expect(result.status, result.stderr).toBe(0);+ expect(result.mutations).toEqual([`pr merge https://github.com/example/base/pull/42 --merge --match-head-commit ${result.head}`]);+ expect(result.events.slice(-5)).toEqual(['checks', 'admission', 'read', 'merge', 'read']);+ });++ it.each(['unreadable-before', 'malformed-state', 'changed-head', 'changed-after-admission', 'failed-checks', 'stale-admission', 'malformed-admission', 'transport-admission', 'unknown-capability'])('refuses %s before any mutation', (scenario) => {+ const result = runMerge(scenario);+ expect(result.status).not.toBe(0);+ expect(result.mutations).toEqual([]);+ });++ it.each(['unreadable-after', 'unknown-ack', 'queued'])('never falls back after %s', (scenario) => {+ const result = runMerge(scenario);+ expect(result.status).not.toBe(0);+ expect(result.mutations).toHaveLength(1);+ expect(result.events.at(-1)).toBe('read');+ });++ it.each(['already-merged', 'lost-ack-merged'])('accepts only confirmed MERGED after %s', (scenario) => {+ const result = runMerge(scenario);+ expect(result.status, result.stderr).toBe(0);+ expect(result.mutations).toHaveLength(scenario === 'already-merged' ? 0 : 1);+ });++ it('selects the next verified allowed method without writing the disallowed method', () => {+ const result = runMerge('unsupported');+ expect(result.status, result.stderr).toBe(0);+ expect(result.mutations).toHaveLength(1);+ expect(result.mutations[0]).toContain('--squash --match-head-commit');+ expect(result.events.filter(event => event.startsWith('capability'))).toHaveLength(2);+ expect(result.events.slice(-5)).toEqual(['checks', 'admission', 'read', 'merge', 'read']);+ });++ it.each([{ registered: false }, { token: false }])('preserves a claim with missing admission context %j', (context) => {+ const result = runMerge('success', 'claim-issue', context);+ expect(result.status).not.toBe(0);+ expect(result.mutations).toEqual([]);+ if (context.registered === false) expect(result.completion).toContain('requires a registered parent agent ID');+ });+});diff --git a/server/services/managedMergePreservation.test.js b/server/services/managedMergePreservation.test.jsindex 852355b1ce..5658787b5c 100644--- a/server/services/managedMergePreservation.test.js+++ b/server/services/managedMergePreservation.test.js@@ -1,7 +1,7 @@import { afterEach, describe, expect, it } from 'vitest';import { writeFile, readFile, access } from 'node:fs/promises';import { join } from 'node:path';-import { execFileSync } from 'node:child_process';+import { spawnSync } from 'node:child_process';import { makeGitSandbox, destroyGitSandbox } from '../lib/gitTestRepo.js';import { execGit } from '../lib/execGit.js';import { DEFAULT_TASK_PROMPTS } from './taskPromptDefaults.js';@@ -67,17 +67,22 @@ describe.skipIf(process.platform === 'win32')('managed merge shell preservation// Use a shell function rather than a PATH binary so the fake cannot leak// into another concurrent test or invoke the installed gh accidentally.const fakeGh = `+ portos_check_merge_admission() { return 0; }gh() {+ if [ "$1" = repo ]; then+ case "$*" in *rebaseMergeAllowed*) printf true ;; *) printf false ;; esac+ return+ fi+ if [ "$2" = checks ]; then return 0; fiif [ "$2" = view ]; thencase "$*" in*--json\\ url*) printf '%s' 'https://github.com/example/repo/pull/42' ;;- *) cat "$MERGE_STATE" ;;+ *) printf '{"state":"%s","headRefOid":"%s","mergeStateStatus":"CLEAN","isDraft":false,"reviewDecision":"APPROVED"}' "$(cat "$MERGE_STATE")" "$CI_VERIFIED_HEAD" ;;esacreturnfiprintf '%s\\n' "$*" >> "$MERGE_CALLS"case "$*" in *--match-head-commit\\ "$CI_VERIFIED_HEAD"*) ;; *) return 99 ;; esac- case "$*" in *--rebase*) ;; *) return 1 ;; esacgit --git-dir="$FAKE_ORIGIN" update-ref refs/heads/main "$CI_VERIFIED_HEAD" || returncase "$*" in*--delete-branch*)@@ -88,13 +93,14 @@ describe.skipIf(process.platform === 'win32')('managed merge shell preservation}`;const prompt = DEFAULT_TASK_PROMPTS['claim-issue'];- const mergeBlock = prompt.slice(prompt.indexOf(' # CI_VERIFIED_HEAD'), prompt.indexOf(' ```', prompt.indexOf(' # CI_VERIFIED_HEAD')));- execFileSync('bash', ['-eu', '-c', `${fakeGh}\n${mergeBlock}`], {- cwd: repo,+ const mergeBlock = [...prompt.matchAll(/```bash\n([\s\S]*?)```/g)].find(([, body]) => body.includes('# CI_VERIFIED_HEAD'))[1];+ const result = spawnSync('bash', ['-eu', '-c', `${fakeGh}\n${mergeBlock}`], {+ cwd: checkout,env: { ...process.env, CI_VERIFIED_HEAD: verifiedHead, MERGE_STATE: state, MERGE_CALLS: calls, FAKE_ORIGIN: origin, CLAIM_CHECKOUT: checkout },});- expect(await readFile(state, 'utf8')).toBe('MERGED');- expect((await readFile(calls, 'utf8')).trim().split('\n')).toHaveLength(3);+ expect(result.status).toBe(lateCommit ? 1 : 0);+ expect(await readFile(state, 'utf8')).toBe(lateCommit ? 'OPEN' : 'MERGED');+ if (!lateCommit) expect((await readFile(calls, 'utf8')).trim().split('\n')).toHaveLength(1);expect(await readFile(sentinel, 'utf8')).toBe('unique test evidence');expect((await execGit(['rev-parse', branch], repo)).stdout.trim()).toBe(localHead);await access(join(checkout, '.git'));diff --git a/server/services/promptSections/completion.js b/server/services/promptSections/completion.jsindex e648d72460..878555907e 100644--- a/server/services/promptSections/completion.js+++ b/server/services/promptSections/completion.js@@ -616,7 +616,8 @@ function buildPendingMergeHandoffLines(agentId) {*/export function buildMergeAdmissionSection(agentId) {if (!agentId) return 'Merge admission requires a registered parent agent ID. If none was supplied, leave the reviewed PR open and report this missing ownership binding; do not merge.';- const command = (action, extra = {}) => agentApiCurl({ apiBase: localApiBaseUrl(), path: '/api/cos/merge-admission',+ const endpoint = { apiBase: localApiBaseUrl(), path: '/api/cos/merge-admission' };+ const command = (action, extra = {}) => agentApiCurl({ ...endpoint,payload: JSON.stringify({ agentId, action, ...extra }) });return ['## Repository merge admission',@@ -628,7 +629,15 @@ export function buildMergeAdmissionSection(agentId) {'If an acquire/check refusal names lease-head-changed, release your token with outcome resync before acquiring again. If admitted:false with retryable:false, release any owned token with outcome leave-open, stop retrying, report the reason and message, and leave the PR/worktree intact. Otherwise, if admitted:false, report the reason and wait retryAfterMs (5 seconds), with a progress update at least every minute. Retry for at most 10 minutes, then record a leave-open outcome and finish with the PR (and any claim) intact. A refusal is never a reason to merge without admission. An HTTP/auth/transport error, unreadable JSON, or missing admission is a refusal, never permission to proceed. Do not modify another owner’s branch, checkout or lease.','Inside the lease, re-read the PR (head SHA, merge state, required check rollup; on GitHub `gh pr view --json headRefOid,mergeStateStatus,statusCheckRollup`):','- If the head still equals the CI-verified head, every required check is green on it, and the forge reports the PR mergeable (`CLEAN`, or `UNSTABLE`/`HAS_HOOKS` with every required check green): check admission (replace TOKEN with the returned token; require admitted:true), then merge pinned to the CI-verified head — add `--match-head-commit <sha>` (GitLab: `--sha <sha>`) to every merge-method attempt your workflow lists; replace any verified-head placeholder with that SHA and retain the pin on every fallback. Managed GitHub merges must preserve local checkouts and branches; this overrides delegated merge instructions that request implicit branch deletion. 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' }), '```',+ 'Keep the acquired token in the private shell variable MERGE_ADMISSION_TOKEN. Before executing a generated GitHub claim merge block, define this parent-bound check in that same shell; every attempted mutation invokes it freshly. Missing registration, token, transport, readable JSON, or admitted:true stops the merge:',+ '```bash',+ 'portos_check_merge_admission() {',+ ' [ -n "${MERGE_ADMISSION_TOKEN:-}" ] || return 1',+ ` ADMISSION_REQUEST=$(node -e 'process.stdout.write(JSON.stringify({agentId:process.argv[2],action:"check",token:process.argv[1]}))' "$MERGE_ADMISSION_TOKEN" ${shellQuote(agentId)}) || return 1`,+ ` ADMISSION_RESPONSE=$(${agentApiCurl(endpoint)} --fail --data-binary "$ADMISSION_REQUEST") || return 1`,+ ` printf '%s' "$ADMISSION_RESPONSE" | node -e 'const fs = require("node:fs"); const response = JSON.parse(fs.readFileSync(0,"utf8")); process.exit(response.admitted === true ? 0 : 1);'`,+ '}',+ '```','- 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' }), '```',diff --git a/server/services/promptSections/completion.test.js b/server/services/promptSections/completion.test.jsindex f26cf083da..4bc6c2df86 100644--- a/server/services/promptSections/completion.test.js+++ b/server/services/promptSections/completion.test.js@@ -23,6 +23,7 @@ describe('review-enabled completion merge gate', () => {const section = render();expect(section).toContain('4. **Wait for CI to finish**');+ expect(section).not.toContain('portos_check_merge_admission');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('gh pr merge "<PR_URL>" --merge --match-head-commit <verified-head>');@@ -76,7 +77,7 @@ describe('claim parent merge admission instructions', () => {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:"check"');expect(prompt).toContain('"action":"release"');expect(prompt).toContain('Authorization: Bearer');expect(prompt).toContain('never a fan-out child');diff --git a/server/services/taskPromptDefaults.test.js b/server/services/taskPromptDefaults.test.jsindex c46f49a568..099cbacff3 100644--- a/server/services/taskPromptDefaults.test.js+++ b/server/services/taskPromptDefaults.test.js@@ -302,13 +302,13 @@ describe('taskPromptDefaults integrity snapshot', () => {const prompt = DEFAULT_TASK_PROMPTS[key];expect(prompt.toLowerCase()).not.toContain('copilot');expect(prompt).not.toMatch(/^\s*gh pr merge[^\n]*--auto/m);- expect(prompt).toContain('--json state -q .state');+ expect(prompt).toContain('--json state,headRefOid,mergeStateStatus,isDraft,reviewDecision');expect(prompt).toContain('[ "$STATE" = "MERGED" ]');- expect(prompt).toContain('--squash --match-head-commit "$CI_VERIFIED_HEAD"');+ expect(prompt).toContain('for MERGE_METHOD in merge squash rebase');expect(prompt).not.toContain('--delete-branch');expect(prompt).toContain('Archive failure');expect(prompt).toContain('untracked AND ignored');- expect(prompt).toContain('--rebase --match-head-commit "$CI_VERIFIED_HEAD"');+ expect(prompt).toContain('"--$MERGE_METHOD" --match-head-commit "$CI_VERIFIED_HEAD"');expect(prompt).toContain('Never force-delete with `-D`');}@@ -333,7 +333,7 @@ describe('taskPromptDefaults integrity snapshot', () => {const current = DEFAULT_TASK_PROMPTS['plan-task'];const claimFlow = DEFAULT_TASK_PROMPTS['plan-task-claim'];- expect(PROMPT_VERSIONS['plan-task']).toBe(22);+ expect(PROMPT_VERSIONS['plan-task']).toBe(23);expect(current).not.toContain('## Phase 6 — Review locally');expect(current).not.toContain('{reviewers}');expect(current).not.toContain('LOCAL reviewers');@@ -951,7 +951,7 @@ describe('taskPromptDefaults integrity snapshot', () => {it('claim-issue v25 leaves the same volunteer-claim state the issue-watcher leaves', () => {const current = DEFAULT_TASK_PROMPTS['claim-issue'];- expect(PROMPT_VERSIONS['claim-issue']).toBe(42);+ expect(PROMPT_VERSIONS['claim-issue']).toBe(43);expect(current).toContain('**a volunteer claim IS a claim**');for (const command of formatVolunteerClaimCommands('"${CANDIDATE}"')) {expect(current).toContain(command);@@ -978,7 +978,7 @@ describe('taskPromptDefaults integrity snapshot', () => {);it('publishes claim work when a required local review is unavailable, but leaves it unmerged and silent', () => {- const cases = [['claim-issue', 42], ['claim-issue-gitlab', 37], ['claim-issue-jira', 24]];+ const cases = [['claim-issue', 43], ['claim-issue-gitlab', 37], ['claim-issue-jira', 24]];for (const [key, version] of cases) {const current = DEFAULT_TASK_PROMPTS[key];diff --git a/server/services/taskPromptDefaults/integrity.snapshot.json b/server/services/taskPromptDefaults/integrity.snapshot.jsonindex 372999fab6..e9f019f899 100644--- a/server/services/taskPromptDefaults/integrity.snapshot.json+++ b/server/services/taskPromptDefaults/integrity.snapshot.json@@ -12,7 +12,7 @@"better-test-quality": "8e305f986e9c9066da5db2aee76fc024","branch-cleanup": "8fdeb4acc2749816a47ca318b6602721","branch-reconcile": "90acf7a56c0de2147cf7463ba338a099",- "claim-issue": "2ca300b6dc35b8e73bc2d0908e87168e",+ "claim-issue": "2b5bbc559ecec8eafc7c01372540de15","claim-issue-gitlab": "29f025187d20a8583292bb53bb974c06","claim-issue-jira": "d0df766dd9ef326c8578efe2953af13e","code-quality": "175fab48fc713b71b4f0574b7cc5fe0b",@@ -41,8 +41,8 @@"observability": "243e58bcfae2759f82caf3ff6c8fc9c5","performance": "4f8ddada54d7c6f31b7fb35aeb0f29db","plan-feature": "7f859397ff16889ffc0cf5a8ba6bddab",- "plan-task": "2f3de862cf9962e684202b9312b78292",- "plan-task-claim": "796baac684589dec9a170c42e6df951a",+ "plan-task": "256a254c3e0624d21604e5c7404886ad",+ "plan-task-claim": "c139d86a9c67559dc07dac18058c4bf2","pr-reviewer": "de9c295018df7c403a722a9ac2e780af","pr-reviewer-eligibility": "a5652f7bcb7e2e50b1cfb9a54a6fabe0","pr-reviewer-review": "511b26a376439cc6cb268a736897fefd",@@ -77,7 +77,7 @@"better-structural-drift": 2,"better-test-quality": 2,"branch-reconcile": 8,- "claim-issue": 42,+ "claim-issue": 43,"claim-issue-gitlab": 37,"claim-issue-jira": 24,"code-quality": 6,@@ -106,7 +106,7 @@"observability": 2,"performance": 6,"plan-feature": 6,- "plan-task": 22,+ "plan-task": 23,"pr-reviewer": 5,"pr-watcher": 2,"privacy": 2,@@ -220,7 +220,8 @@"2663933c28056e0e23caf42acb1b41d0","9e51f8f382774585728c2c642e88539b","34557a99689bd2e089b0e1e634ce1ff3",- "cea12f4209a3f20ebe1a5ad8cc7b38b5"+ "cea12f4209a3f20ebe1a5ad8cc7b38b5",+ "2ca300b6dc35b8e73bc2d0908e87168e"],"claim-issue-gitlab": ["fae92c45c89c65455930b4b06a1b88c4",@@ -423,7 +424,8 @@"910802d67f3b5a785f068f4d90178543","b85fe92999aa4ee4a8910320457c4242","8a53a518714cc4029d751fdad92f9b05",- "5dd527c47e736094949c4605cfb2d973"+ "5dd527c47e736094949c4605cfb2d973",+ "2f3de862cf9962e684202b9312b78292"],"pr-reviewer": ["679680b3b382aeb6786df01c4d1a90c6",diff --git a/server/services/taskPromptDefaults/prompts.js b/server/services/taskPromptDefaults/prompts.jsindex 27a571f576..1b4ea5c8e0 100644--- a/server/services/taskPromptDefaults/prompts.js+++ b/server/services/taskPromptDefaults/prompts.js@@ -10,7 +10,7 @@*/// PORTOS_API_URL is interpolated into the jira-status-report default prompt below.-import { MANAGED_WORKTREE_CLEANUP_CONTRACT } from '../../lib/mergeGateContract.js';+import { MANAGED_WORKTREE_CLEANUP_CONTRACT, buildManagedGithubMergeScript } from '../../lib/mergeGateContract.js';import { APP_LAUNCH_VIDEO_PROMPT } from './appLaunchVideo.js';import { CONTRIBUTION_SECURITY_POLICY } from '../../lib/contributionSecurityPolicy.js';import { PORTOS_API_URL } from '../../lib/portosUrls.js';@@ -2849,19 +2849,9 @@ Use \`feat:\` / \`fix:\` / \`refactor:\` / \`chore:\` / etc. (The bracketed-scop1. Push the branch: \`git push -u origin claim/<slug>\`.2. Open the PR with \`gh pr create\` — title MUST encode the slug: \`<type>([<slug>]): <description>\`. Body should summarize what shipped + test plan.3. **Wait for required CI before merging.** Run \`gh pr checks <num> --required --watch --fail-fast\` — REQUIRED checks only, so optional jobs cannot stall the merge. If a required check stays red, comment on the PR naming the failure, remove only the worktree, and leave the branch and PR for reconciliation.-4. **Merge immediately via \`gh pr merge\`** — NEVER a local merge and NEVER \`--auto\`. Prefer a true merge commit so Git retains the branch tip, but fall back when the repository disallows that method:+4. **Merge immediately via \`gh pr merge\`** — NEVER a local merge and NEVER \`--auto\`. Select merge, squash or rebase only from verified allowed repository methods. An unreadable state or unconfirmed mutation stops this phase; no write is retried with another method:\`\`\`bash- # CI_VERIFIED_HEAD is the SHA recorded when required CI and configured reviews passed.- # Re-read the forge head and checks, and check merge admission before each attempt.- : "\${CI_VERIFIED_HEAD:?Missing CI-verified head}"- PR_URL=$(gh pr view --json url -q .url) # no number: resolves the PR from the checked-out branch- gh pr merge "$PR_URL" --merge --match-head-commit "$CI_VERIFIED_HEAD" || {- [ "$(gh pr view "$PR_URL" --json state -q .state)" = "MERGED" ] || \- gh pr merge "$PR_URL" --squash --match-head-commit "$CI_VERIFIED_HEAD" || \- gh pr merge "$PR_URL" --rebase --match-head-commit "$CI_VERIFIED_HEAD"- }- STATE=$(gh pr view "$PR_URL" --json state -q .state)- [ "$STATE" = "MERGED" ] || { echo "Expected MERGED, got $STATE" >&2; exit 1; }+${buildManagedGithubMergeScript()}\`\`\`The exact comparison must succeed. Investigate and retry on \`OPEN\`; \`CLOSED\` is not success. Do not enter Phase 7 until remote state is exactly \`MERGED\`.@@ -3036,17 +3026,9 @@ The configured reviewers for this task, in order, are \`{reviewers}\`. Split the4a. Read the review status back — shell variables do not survive between calls, so run \`REVIEW_STATUS_FILE="$(git rev-parse --git-path portos-review-status)"\` and source it. If \`REVIEW_STATUS=review-blocked\` from a required reviewer, preserve the claim branch, leave the PR open, and stop before the PR-side review, CI, or merge steps. ${REVIEW_UNAVAILABLE_REPORTING_NOTE} If all configured reviewers were optional (~opt), REVIEW_STATUS must not block the merge.5. **Satisfy the PR-SIDE reviewers and CI before merging.** Request each \`@<login>\` (\`gh pr edit <num> --add-reviewer <login>\`, drop the \`@\`), poll every 5–15s, and address the findings — push fixes, capped at 3 rounds each; their approval gates the merge. Wait out any auto-requested review bot the same way, then let required CI finish (\`gh pr checks <num> --required --watch --fail-fast\` — REQUIRED checks only, so an optional job can't stall the merge). If a reviewer stays unsatisfied or a required check stays red, comment on the PR naming the failure, remove only the worktree, and leave the branch and PR for reconciliation.-6. **Merge immediately via \`gh pr merge\`** — NEVER a local merge and NEVER \`--auto\`. Prefer a true merge commit so Git retains the branch tip, but fall back when the repository disallows that method:+6. **Merge immediately via \`gh pr merge\`** — NEVER a local merge and NEVER \`--auto\`. Select merge, squash or rebase only from verified allowed repository methods. An unreadable state or unconfirmed mutation stops this phase; no write is retried with another method:\`\`\`bash- # CI_VERIFIED_HEAD is the SHA recorded when required CI and configured reviews passed.- # Re-read the forge head and checks, and check merge admission before each attempt.- : "\${CI_VERIFIED_HEAD:?Missing CI-verified head}"- PR_URL=$(gh pr view --json url -q .url) # no number: resolves the PR from the checked-out branch- gh pr merge "$PR_URL" --merge --match-head-commit "$CI_VERIFIED_HEAD" || {- [ "$(gh pr view "$PR_URL" --json state -q .state)" = "MERGED" ] || gh pr merge "$PR_URL" --squash --match-head-commit "$CI_VERIFIED_HEAD" || gh pr merge "$PR_URL" --rebase --match-head-commit "$CI_VERIFIED_HEAD"- }- STATE=$(gh pr view "$PR_URL" --json state -q .state)- [ "$STATE" = "MERGED" ] || { echo "Expected MERGED, got $STATE" >&2; exit 1; }+${buildManagedGithubMergeScript()}\`\`\`The exact comparison must succeed. Investigate and retry on \`OPEN\`; \`CLOSED\` is not success. Do not enter Phase 7 until remote state is exactly \`MERGED\`.@@ -3302,19 +3284,9 @@ Every local reviewer's fixes are already committed, so the PR opens against fini**Review-stuck cleanup** (a PR-side reviewer still unsatisfied after 3 rounds): post one summarizing PR comment (\`gh pr comment\`), then run the worktree-only cleanup (\`cd {repoPath} && git worktree remove "\${WORKTREE}"\`). Leave the local branch, the open PR, the assignee, and the \`in-progress\` label in place so the human picks up cold. Do NOT run Phase 7.4. **Let required CI finish and go green** — \`gh pr checks <pr-number> --required --watch --fail-fast\` (scope the wait to REQUIRED checks so an optional job can't stall a merge branch protection would allow). A red required check is not merge-eligible: fix it and re-push (same 3-round cap), or, if it stays red, stop exactly as the review-stuck cleanup above does.-5. **Merge immediately via \`gh pr merge\`** — NEVER a local \`git merge\` and NEVER \`--auto\`, which can return successfully while leaving the PR queued and OPEN. Prefer a true merge commit, with squash/rebase fallbacks for repositories that disallow it:+5. **Merge immediately via \`gh pr merge\`** — NEVER a local \`git merge\` and NEVER \`--auto\`, which can return successfully while leaving the PR queued and OPEN. Select merge, squash or rebase only from verified allowed repository methods. An unreadable state or unconfirmed mutation stops this phase; no write is retried with another method:\`\`\`bash- # CI_VERIFIED_HEAD is the SHA recorded when required CI and configured reviews passed.- # Re-read the forge head and checks, and check merge admission before each attempt.- : "\${CI_VERIFIED_HEAD:?Missing CI-verified head}"- PR_URL=$(gh pr view --json url -q .url) # no number: resolves the PR from the checked-out branch- gh pr merge "$PR_URL" --merge --match-head-commit "$CI_VERIFIED_HEAD" || {- [ "$(gh pr view "$PR_URL" --json state -q .state)" = "MERGED" ] || \- gh pr merge "$PR_URL" --squash --match-head-commit "$CI_VERIFIED_HEAD" || \- gh pr merge "$PR_URL" --rebase --match-head-commit "$CI_VERIFIED_HEAD"- }- STATE=$(gh pr view "$PR_URL" --json state -q .state)- [ "$STATE" = "MERGED" ] || { echo "Expected MERGED, got $STATE" >&2; exit 1; }+${buildManagedGithubMergeScript()}\`\`\`The exact comparison MUST succeed. \`OPEN\` means CI, review, or branch protection still blocks the merge; investigate, fix, and retry. \`CLOSED\` is also not success. Do not enter Phase 7 until remote GitHub state is exactly \`MERGED\`.diff --git a/server/services/taskPromptDefaults/versions.js b/server/services/taskPromptDefaults/versions.jsindex aef69f9515..25edfbf2cf 100644--- a/server/services/taskPromptDefaults/versions.js+++ b/server/services/taskPromptDefaults/versions.js@@ -111,7 +111,7 @@ export const PROMPT_VERSIONS = {// Code review isolation is a preference; supported headless reviewers remain usable.// v39 (claim-issue) / v35 (gitlab) / v22 (jira): an optional reviewer (~opt) failure/timeout/provider error never sets review-blocked and does not prevent merge.// Revalidate current need and project alignment before claims, contributor handoff or epic splits.-PROMPT_VERSIONS['claim-issue'] = 42; // Preserve managed checkouts through merge until explicit verified cleanup (#12133).+PROMPT_VERSIONS['claim-issue'] = 43; // Guard each merge attempt and stop on uncertain readback (#12273).PROMPT_VERSIONS['claim-issue-gitlab'] = 37;// Accepted review findings require resolution regardless of severity.PROMPT_VERSIONS['claim-issue-jira'] = 24;@@ -130,5 +130,5 @@ PROMPT_VERSIONS['claim-issue-jira'] = 24;// matches the prompt's behavior and then advance this anchor in the same change. See issue #734.export const REFERENCE_WATCH_AUDITED_VERSION = 4;-// Managed GitHub merges preserve linked checkouts on every method fallback (#12133).-PROMPT_VERSIONS['plan-task'] = 22;+// Guard generated GitHub merges with fresh state/head/admission and confirmed readback (#12273).+PROMPT_VERSIONS['plan-task'] = 23;