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: check merged-tree guards before managed merges (#13224)
[._.]/ Adam Eivya52355dfb0ff
diff --git a/AGENTS.md b/AGENTS.mdindex eac481a3f1..e542403205 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -261,7 +261,7 @@ This policy governs code comments, not user-facing guides or product copy.- **main**: active development. **release**: push `main` to `release` to trigger the GitHub Release workflow.- **Before pushing**: inspect branch/upstream and working-tree state, preserve unrelated changes, and commit the intended work. Fetch the workflow's intended base explicitly for comparison; a feature branch's tracking branch is not necessarily the default branch. Integrate it only when needed under the merge policy below. Run `npm run pregate` on the resulting commits, then push. Re-run it after any subsequent rebase; do not blindly pull with autostash.-- **Merge ready branches without chasing `main`.** A branch that is behind the default branch may merge when it is conflict-free, required checks pass for its current head, and configured reviews are satisfied. Default-branch movement alone does not invalidate those results or require a rebase, branch update, or another CI run. Rebase only for actual conflicts, an enforced up-to-date branch policy, or evidenced integration risk (including semantic overlap without textual conflicts); after changing the head, rerun affected validation and required reviews/checks. Keep implementation, review, and CI concurrent; hold repository merge admission only for the final live-state check, merge attempt, and readback, releasing it before recovery or further CI waits. Never bypass required checks or confuse a queued merge with `MERGED`. This policy overrides mandatory base-sync instructions in delegated slashdo workflows.+- **Merge ready branches without chasing `main`.** A branch that is behind the default branch may merge when it is conflict-free, required checks pass for its current head, and configured reviews are satisfied. Default-branch movement alone does not invalidate those results or require a rebase, branch update, or another CI run. Before every managed merge (including `/do:next` single-issue and swarm Phase C, `/do:pr --merge`, and CoS claims), fetch the default branch and run `node scripts/pregate.js --guards-only --merged-with origin/<default>` against the committed head and that fetched base. This runs only the planner’s always-run and diff-selected structural guards on the combined tree, with test-memo reuse disabled; it does not replace head CI or write an attestation receipt. Run it outside repository merge admission. Retain the checked head and base SHAs; inside admission, re-read the live base as well as the PR head. If either changed, release admission and repeat the guard check outside the lease before retrying. A failed guard leaves the PR open with the failing test named; do not merge. These instructions are the repository pre-merge hook for the bundled slashdo `lib/merge-gate.md` and override any direct-merge fallback in that shared procedure. Rebase only for actual conflicts, an enforced up-to-date branch policy, or evidenced integration risk (including semantic overlap without textual conflicts); after changing the head, rerun affected validation and required reviews/checks. Keep implementation, review, and CI concurrent; hold repository merge admission only for the final live-state check, merge attempt, and readback, releasing it before recovery or further CI waits. Never bypass required checks or confuse a queued merge with `MERGED`. This policy overrides mandatory base-sync instructions in delegated slashdo workflows.- **Finish authorized merges and teardown before reporting success.** When merge is authorized, finish review and required checks, merge, and verify the merge completed. Managed GitHub merges never pass `--delete-branch` to `gh pr merge`, including method fallbacks: it can remove another linked checkout before preservation. Pin every attempt to the CI-verified head, verify remote `MERGED`, and release merge admission before cleanup. Archive unique content, including untracked and ignored files, and verify preservation before deleting a checkout. Delete only the authorized exact remote ref with an expected-head lease; an advanced ref or archive failure leaves the checkout/ref intact with a tracked handoff. Recheck live ownership, release only this task's locks on its completed work, remove its worktree, and delete its explicitly named local branch; never infer the branch to delete from its upstream. Preserve other owners' locks and explicit manual handoffs. If work must remain, name its owner, blocker, and next step in the handoff.- **No per-branch changelog entries.** PRs do not write a changelog file or fragment — commit messages are the record, and `/do:release` synthesizes the release notes from the commit log since the last tag into `.changelog/v{version}.md`. **Write commit subjects/bodies for a human release-note reader** (see "Git commits and PRs" in the global instructions). Rationale: `.changelog/README.md`.- **Release quality snapshot**: before a release, run `npm run quality:snapshot` on the install holding PortOS audit evidence. It publishes numeric local assessments only (no provider calls, no private run prose) into the repo-root `.quality.json` through an immediately-merged pull request; with no local evidence it commits nothing and says so.diff --git a/scripts/ci-test-plan.js b/scripts/ci-test-plan.jsindex e00d4b46a9..de5a95e866 100644--- a/scripts/ci-test-plan.js+++ b/scripts/ci-test-plan.js@@ -454,6 +454,9 @@ export const ALWAYS_RUN_TESTS = [// walkers (#8723): the offending file is never imported by the guard, so// impact selection only reaches them when the guard itself changes.'server/lib/apiRouteGraph.test.js',+ // Route inventories and write-back scans depend on independently changed files (#13224).+ 'server/lib/hostControlRoutes.test.js',+ 'server/jsonWritebackConventions.test.js',// Whole-tree scanner (#9982): any server module can start taking backup// admission with no import edge back to the owner inventory it must join.'server/lib/backupAssetOwners.test.js',diff --git a/scripts/pregate.js b/scripts/pregate.jsindex 5fbbc40f30..1e564f02e7 100644--- a/scripts/pregate.js+++ b/scripts/pregate.js@@ -22,6 +22,8 @@* node scripts/pregate.js [--base <ref>] [--full] [--skip-lint] [--plan-only]* [--skip-db] [--skip-browser] [--skip-build] [--skip-smoke]*+ * --guards-only [--merged-with <ref>] run tree-wide guards on HEAD or a temporary merged tree+ ** --base <ref> compare against <ref> instead of the remote default branch* --full actually run the complete suite when the plan demands it* (without this, a full plan runs the always-run guards only@@ -49,11 +51,11 @@*/import { spawn, spawnSync } from 'child_process';-import { writeSync } from 'fs';-import { constants } from 'os';+import { existsSync, mkdirSync, mkdtempSync, rmSync, symlinkSync, writeSync } from 'fs';+import { constants, tmpdir } from 'os';import { setTimeout as delay } from 'timers/promises';import { execFileSync } from 'child_process';-import { dirname, join } from 'path';+import { dirname, join, resolve } from 'path';import { fileURLToPath } from 'url';import { prepareWindowsSafeSpawn, resolveWindowsExecutable } from '../server/lib/aiToolkit/internal/windowsSafeSpawn.js';import { ALWAYS_RUN_TESTS, structuralTestsFor } from './ci-test-plan.js';@@ -371,9 +373,61 @@ function defaultBaseRef() {return resolved || 'origin/main';}+/** Validate committed merge inputs without registering a worktree or writing to the caller's Git state. */+export async function withMergedPregateTree(repoRoot, mergedWith, run) {+ const readGit = (args, cwd = repoRoot) => execFileSync('git', args, {+ cwd, encoding: 'utf8', env: { ...process.env, GIT_OPTIONAL_LOCKS: '0' }, stdio: ['ignore', 'pipe', 'pipe'],+ }).trim();+ if (readGit(['status', '--porcelain=v1', '--untracked-files=all'])) {+ throw new Error('--merged-with requires a clean committed checkout; commit the intended changes first.');+ }+ const head = readGit(['rev-parse', '--verify', 'HEAD^{commit}']);+ const base = readGit(['rev-parse', '--verify', `${mergedWith}^{commit}`]);+ const scratch = mkdtempSync(join(tmpdir(), 'portos-merged-guards-'));+ try {+ // All new merge objects, refs, index entries and generated files live in this disposable clone.+ readGit(['clone', '--quiet', '--shared', '--no-checkout', '--', repoRoot, scratch]);+ let tree;+ try {+ tree = readGit(['merge-tree', '--write-tree', base, head], scratch).split('\n')[0];+ } catch (error) {+ throw new Error(`Cannot construct merged guard tree (resolve conflicts before merging): ${error.stdout || error.stderr || error.message}`);+ }+ const commit = execFileSync('git', ['-c', 'user.name=Pregate', '-c', '[email protected]',+ 'commit-tree', tree, '-p', base, ...(head === base ? [] : ['-p', head])], {+ cwd: scratch, encoding: 'utf8', input: 'Temporary merged-tree guard validation\n',+ }).trim();+ readGit(['checkout', '--quiet', '--detach', commit], scratch);+ // Submodule bytes must match the merged gitlink too; use existing local objects, never the network.+ const primary = resolve(repoRoot, readGit(['rev-parse', '--git-common-dir']), '..');+ for (const entry of readGit(['ls-tree', '-r', '-z', commit], scratch).split('\0')) {+ if (!entry.startsWith('160000 ')) continue;+ const [metadata, path] = entry.split('\t');+ const sha = metadata.split(' ')[2];+ const source = [join(repoRoot, path), join(primary, path)].find(dir => existsSync(join(dir, '.git')));+ if (!source) throw new Error(`Initialize submodule ${path} before running merged-tree guards.`);+ readGit(['clone', '--quiet', '--shared', '--no-checkout', '--', source, join(scratch, path)]);+ readGit(['checkout', '--quiet', '--detach', sha], join(scratch, path));+ }+ for (const workspace of ['', 'server', 'client', 'autofixer']) {+ const source = join(repoRoot, workspace, 'node_modules');+ if (!existsSync(source)) continue;+ mkdirSync(join(scratch, workspace), { recursive: true });+ symlinkSync(source, join(scratch, workspace, 'node_modules'), process.platform === 'win32' ? 'junction' : 'dir');+ }+ console.log(`🌳 Merged-tree guards: HEAD ${head.slice(0, 12)} + base ${base.slice(0, 12)} = tree ${tree.slice(0, 12)}.`);+ const comparisonBase = readGit(['merge-base', head, base], scratch);+ return await run({ root: scratch, base, head, tree, comparisonBase });+ } finally {+ rmSync(scratch, { recursive: true, force: true });+ }+}+export const USAGE = `Usage: node scripts/pregate.js [--base <ref>] [--full] [--skip-lint] [--plan-only][--skip-db] [--skip-browser] [--skip-build] [--skip-smoke]+ --guards-only run only always-run and diff-selected structural guards (no attestation receipt)+ --merged-with <ref> validate HEAD merged with this fetched ref in an isolated temporary repository--base <ref> compare against <ref> instead of the remote default branch--full run the complete suite when the plan demands it--skip-lint skip linting in both client and server workspaces@@ -389,12 +443,19 @@ const SKIP_FLAGS = { '--skip-db': 'skipDb', '--skip-browser': 'skipBrowser', '--/** Parse argv before doing any Git inspection or starting a child process. */export function parseArgs(argv) {const options = {- base: null, full: false, skipLint: false, planOnly: false, help: false,+ base: null, full: false, skipLint: false, planOnly: false, help: false, guardsOnly: false, mergedWith: null,skipDb: false, skipBrowser: false, skipBuild: false, skipSmoke: false,};for (let index = 0; index < argv.length; index += 1) {const flag = argv[index];switch (flag) {+ case '--guards-only': options.guardsOnly = true; break;+ case '--merged-with': {+ const value = argv[++index];+ if (!value || value.startsWith('-')) throw new Error('--merged-with requires a value.');+ options.mergedWith ??= value;+ break;+ }case '--base': {const value = argv[index + 1];if (!value || value.startsWith('-')) throw new Error('--base requires a value.');@@ -412,12 +473,17 @@ export function parseArgs(argv) {throw new Error(`Unknown option: ${flag}.`);}}+ if (options.mergedWith && !options.guardsOnly) throw new Error('--merged-with requires --guards-only.');+ if (options.guardsOnly && (options.full || options.skipLint || options.skipDb || options.skipBrowser || options.skipBuild || options.skipSmoke)) {+ throw new Error('--guards-only cannot be combined with --full or --skip-* options.');+ }+ if (options.mergedWith && options.base) throw new Error('--merged-with cannot be combined with --base.');return options;}/** Spawn target for a stage: a repo script under node, or npm itself. */-function stageSpawn(stage, env) {- if (!stage.npm) return { command: process.execPath, args: [join(REPO_ROOT, 'scripts', stage.script), ...stage.args] };+function stageSpawn(stage, env, repoRoot = REPO_ROOT) {+ if (!stage.npm) return { command: process.execPath, args: [join(repoRoot, 'scripts', stage.script), ...stage.args] };// A bare `npm` is a `.cmd` shim on Windows; resolve and wrap it the way every// other npm spawn in this tree does (server/lib/bufferedSpawn.js).return prepareWindowsSafeSpawn(resolveWindowsExecutable('npm', IS_WIN32, env) || 'npm', stage.npm, IS_WIN32);@@ -511,11 +577,11 @@ async function sweepStageGroup(pgid) {}/** Run one stage; an owner signal during it resolves only after the stage group settled. */-async function runStage(stage, owner) {+async function runStage(stage, owner, { repoRoot = REPO_ROOT } = {}) {const env = stageSpawnEnv(process.env, stage.env);- const { command, args } = stageSpawn(stage, env);+ const { command, args } = stageSpawn(stage, env, repoRoot);const child = spawn(command, args, {- cwd: REPO_ROOT,+ cwd: repoRoot,stdio: 'inherit',env,// A separate group lets cancellation reach only this stage's descendants.@@ -589,6 +655,25 @@ async function main() {assertNodeVersion();+ if (options.mergedWith) {+ const status = await withMergedPregateTree(REPO_ROOT, options.mergedWith, async ({ root, comparisonBase }) => {+ const owner = installOwnerCancellation();+ try {+ const outcome = await runStage({ name: 'merged-tree guards', script: 'pregate.js',+ args: ['--guards-only', '--base', comparisonBase, ...(options.planOnly ? ['--plan-only'] : [])],+ env: { PORTOS_TEST_MEMO: 'off' },+ }, owner, { repoRoot: root });+ if (outcome.error || outcome.unsettled) throw new Error(outcome.error?.message || outcome.unsettled);+ const signal = outcome.interrupted || outcome.signal;+ return signal ? 128 + constants.signals[signal] : (outcome.status ?? 1);+ } finally {+ owner.release();+ }+ });+ process.exitCode = status;+ return;+ }+const unmerged = spawnSync('git', ['ls-files', '-u', '-z'], { cwd: REPO_ROOT, encoding: 'utf8' });if (unmerged.status !== 0) {console.error(`❌ Cannot inspect the Git index for unresolved conflicts: ${unmerged.stderr || 'git ls-files failed'}`);@@ -655,7 +740,11 @@ async function main() {};console.log(`📋 ${raw.changed_files.length} changed file(s) — ${plan.reason}.`);- const downgraded = plan.full && !options.full;+ const downgraded = plan.full && !options.full && !options.guardsOnly;+ if (options.guardsOnly) {+ plan = downgradeFullPlan(plan, git(['ls-files', '-z']).split('\0').filter(Boolean), changedFiles);+ Object.assign(plan, { lint: { mode: 'skip', files: [] }, browser: { files: [] }, db: false, windows: false, build: false, smoke: false, promptHistory: false, linuxContainment: false, supercolliderLive: false, dockerContainmentLive: false });+ }if (downgraded) {plan = downgradeFullPlan(plan, git(['ls-files']).split('\n').filter(Boolean), changedFiles);console.log('⚠️ CI will run the FULL suite for this diff — running always-run and diff-selected structural guards only. Pass --full to run everything, including the build, smoke, browser and DB suites.');@@ -668,7 +757,12 @@ async function main() {const uncovered = uncoveredSuites(plan, { options, downgraded, prerequisites });announceUncovered(uncovered);const skip = Object.fromEntries(uncovered.map(({ suite }) => [suite, true]));- return { uncovered, stages: resolvePlanStages(plan, { skipLint: options.skipLint, baseSha, skip, databaseEnv }) };+ const stages = resolvePlanStages(plan, { skipLint: options.skipLint, baseSha, skip, databaseEnv });+ return { uncovered, stages: options.guardsOnly+ ? stages.filter(stage => stage.suite === 'server' || stage.suite === 'client')+ .map(stage => ({ ...stage, env: { ...stage.env, PORTOS_TEST_MEMO: 'off' } }))+ : stages };+};if (options.planOnly) {@@ -804,13 +898,13 @@ async function main() {startedAt,finishedAt: new Date().toISOString(),});- writePregateReport(REPO_ROOT, report);+ if (!options.guardsOnly) writePregateReport(REPO_ROOT, report);// Synchronous: a piped stderr is written asynchronously, and the self-signal// below would drop these lines before they flush.if (tree !== null && !report.treeStable) {writeSync(2, `⚠️ The working tree changed while pregate ran (${tree.slice(0, 12)} → ${treeAfterRun?.slice(0, 12) ?? 'unhashable'}); the receipt covers the tree it started with.\n`);}- if (failure) writeSync(2, `${failure}\n📄 Receipt: ${PREGATE_REPORT_PATH}\n`);+ if (failure) writeSync(2, `${failure}\n${options.guardsOnly ? '' : `📄 Receipt: ${PREGATE_REPORT_PATH}\n`}`);else if (owner.signal) writeSync(2, `⚠️ Received ${owner.signal} after every stage passed; the receipt records that completed run.\n`);owner.release();@@ -824,7 +918,7 @@ async function main() {if (uncovered.length > 0) {console.log(`⚠️ Not run here (CI still proves them): ${uncovered.map(({ suite, reason }) => `${suite} (${reason})`).join(', ')}.`);}- console.log(`📄 Receipt: ${PREGATE_REPORT_PATH}`);+ if (!options.guardsOnly) console.log(`📄 Receipt: ${PREGATE_REPORT_PATH}`);}if (isDirectlyInvoked(import.meta.url)) {diff --git a/scripts/pregate.test.js b/scripts/pregate.test.jsindex a6837a097d..6a7440cf12 100644--- a/scripts/pregate.test.js+++ b/scripts/pregate.test.js@@ -61,7 +61,7 @@ const planWith = (overrides = {}) => ({});const DEFAULT_OPTIONS = {- base: null, full: false, skipLint: false, planOnly: false, help: false,+ base: null, full: false, skipLint: false, planOnly: false, help: false, guardsOnly: false, mergedWith: null,skipDb: false, skipBrowser: false, skipBuild: false, skipSmoke: false,};@@ -199,6 +199,88 @@ describe('pregate hidden-content invocation', () => {if (template?.scratch) await destroyGitSandbox(template.scratch);});+ // A branch and base can each be green while their combined route inventory fails.+ it('runs guards on the exact merged tree, propagates failure, and preserves caller state and receipt', () => {+ mkdirSync(join(root, 'server/routes'), { recursive: true });+ write('server/routes/universe-builder.js', 'export const mutation = false;\n');+ write('server/lib/strict.js', 'export const strict = false;\n');+ write('server/lib/hostControlRoutes.test.js', `+ import { readFileSync } from 'fs';+ import { strict } from './strict.js';+ if (strict && readFileSync('server/routes/universe-builder.js', 'utf8').includes('mutation = true')) {+ throw new Error('hostControlRoutes.test.js: unclassified Universe Builder mutation');+ }+ `);+ write('scripts/run-ci-tests.js', `+ import { resolve } from 'path';+ import { pathToFileURL } from 'url';+ if (process.env.PORTOS_TEST_MEMO !== 'off') throw new Error('merged guards reused memo');+ for (const file of JSON.parse(process.env.CI_TEST_FILES)) {+ if (file.endsWith('hostControlRoutes.test.js')) await import(pathToFileURL(resolve(file)));+ }+ `);+ git('add', '--all');+ git('commit', '-qm', 'green common guard');+ const common = git('rev-parse', 'HEAD');+ git('checkout', '-qb', 'new-base');+ write('docs/tracked note.md', '# Unrelated base move\n');+ git('add', '--all'); git('commit', '-qm', 'base move');+ const movedBase = git('rev-parse', 'HEAD');+ git('checkout', '-qb', 'feature', common);+ const invoke = (...flags) => spawnSync(process.execPath, ['scripts/pregate.js', ...flags], {+ cwd: root, encoding: 'utf8', env: { ...process.env, PORTOS_TEST_MEMO: 'on' },+ });+ mkdirSync(join(root, '.cache/pregate'), { recursive: true });+ write(PREGATE_REPORT_PATH, 'original attestation receipt');+ const original = { ...snapshot(), refs: git('show-ref'), worktrees: git('worktree', 'list', '--porcelain') };+ const green = invoke('--guards-only', '--merged-with', movedBase);+ expect(green.status, green.stderr).toBe(0);+ expect(green.stdout).toContain('Merged-tree guards: HEAD');+ expect(green.stdout).not.toContain('hidden-content scan');+ expect(green.stdout).not.toContain('client/server lint');+ expect({ ...snapshot(), refs: git('show-ref'), worktrees: git('worktree', 'list', '--porcelain') }).toEqual(original);+ expect(readFileSync(join(root, PREGATE_REPORT_PATH), 'utf8')).toBe('original attestation receipt');++ // The base tightens its guard independently; feature remains green in its own tree.+ write('server/routes/universe-builder.js', 'export const mutation = true;\n');+ git('add', '--all'); git('commit', '-qm', 'feature mutation before stricter guard');+ const branchOnly = invoke('--guards-only', '--base', common);+ expect(branchOnly.status, branchOnly.stderr).toBe(0);+ // The stricter base policy and feature route change do not conflict textually.+ git('checkout', 'new-base');+ write('server/lib/strict.js', 'export const strict = true;\n');+ git('add', '--all'); git('commit', '-qm', 'strict inventory');+ const strictBase = git('rev-parse', 'HEAD');+ git('checkout', 'feature');+ const before = { ...snapshot(), refs: git('show-ref'), worktrees: git('worktree', 'list', '--porcelain') };+ const failed = invoke('--guards-only', '--merged-with', strictBase);+ expect(failed.status).not.toBe(0);+ expect(failed.stderr).toContain('hostControlRoutes.test.js: unclassified Universe Builder mutation');+ expect(failed.stdout).not.toContain('Pregate passed');+ expect({ ...snapshot(), refs: git('show-ref'), worktrees: git('worktree', 'list', '--porcelain') }).toEqual(before);+ expect(readFileSync(join(root, PREGATE_REPORT_PATH), 'utf8')).toBe('original attestation receipt');++ write('docs/tracked note.md', '# Pending local work\n');+ const dirty = snapshot();+ const refused = invoke('--guards-only', '--merged-with', strictBase);+ expect(refused.status).not.toBe(0);+ expect(refused.stderr).toContain('requires a clean committed checkout');+ expect(snapshot()).toEqual(dirty);+ write('docs/tracked note.md', '# Example\n');++ git('checkout', 'new-base');+ write('server/routes/universe-builder.js', 'export const mutation = "conflicting";\n');+ git('add', '--all'); git('commit', '-qm', 'conflicting mutation');+ const conflictBase = git('rev-parse', 'HEAD');+ git('checkout', 'feature');+ const preConflict = snapshot();+ const conflict = invoke('--guards-only', '--merged-with', conflictBase);+ expect(conflict.status).not.toBe(0);+ expect(conflict.stderr).toContain('Cannot construct merged guard tree');+ expect(conflict.stdout).not.toContain('Pregate passed');+ expect(snapshot()).toEqual(preConflict);+ });+// This regression catches stale inherited packages before any lint/test child// can produce a misleading product failure or repair the shared source tree.it.each(['matching', 'stale', 'missing-package', 'unreadable-package', 'dangling'])(@@ -621,6 +703,15 @@ describe('parseArgs', () => {});});+ it('accepts guard-only merged validation and rejects combinations that can skip it', () => {+ expect(parseArgs(['--guards-only', '--merged-with', 'origin/main'])).toMatchObject({ guardsOnly: true, mergedWith: 'origin/main' });+ expect(() => parseArgs(['--merged-with', 'origin/main'])).toThrow('requires --guards-only');+ expect(() => parseArgs(['--guards-only', '--merged-with'])).toThrow('requires a value');+ expect(() => parseArgs(['--guards-only', '--full'])).toThrow('cannot be combined');+ expect(() => parseArgs(['--guards-only', '--skip-lint'])).toThrow('cannot be combined');+ expect(() => parseArgs(['--guards-only', '--merged-with', 'origin/main', '--base', 'HEAD'])).toThrow('cannot be combined');+ });+it('accepts one skip flag per resource suite', () => {expect(parseArgs(['--skip-db', '--skip-browser', '--skip-build', '--skip-smoke'])).toEqual({...DEFAULT_OPTIONS, skipDb: true, skipBrowser: true, skipBuild: true, skipSmoke: true,diff --git a/server/services/promptSections/completion.js b/server/services/promptSections/completion.jsindex 1fde30f12b..3d6f79b8a4 100644--- a/server/services/promptSections/completion.js+++ b/server/services/promptSections/completion.js@@ -631,7 +631,7 @@ export function buildMergeAdmissionSection(agentId) {'```bash', command('acquire'), '```','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.',+ '- 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, but PortOS merged-tree guards must pass before merging. Before acquiring admission, fetch the default branch and run `node scripts/pregate.js --guards-only --merged-with origin/<default>` in the PR checkout, recording the checked head and base SHAs. This applies to single-issue claims and each swarm Phase C merge. A failing guard leaves the PR open with its failing test named. Inside admission, re-read the live default-branch SHA and PR head; if either differs from the guard inputs, release with outcome resync and repeat the guard check OUTSIDE the lease (no rebase or fresh head CI solely for a moved base). Never run guards while holding admission or merge an unchecked combined tree.','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() {',diff --git a/server/services/promptSections/completion.test.js b/server/services/promptSections/completion.test.jsindex 79921cece7..c2408285bb 100644--- a/server/services/promptSections/completion.test.js+++ b/server/services/promptSections/completion.test.js@@ -84,6 +84,9 @@ describe('claim parent merge admission instructions', () => {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('node scripts/pregate.js --guards-only --merged-with origin/<default>');+ expect(prompt).toContain('single-issue claims and each swarm Phase C merge');+ expect(prompt).toContain('if either differs from the guard inputs');expect(prompt).toContain('release with outcome resync');expect(prompt).toContain('OUTSIDE the lease');expect(prompt).toContain('at most 10 minutes');