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: validate quality snapshot merges against the current base (#13269)

Adam Eivy19977d07bec4
diff --git a/docs/GITHUB_ACTIONS.md b/docs/GITHUB_ACTIONS.md
index 272dbceb42..3d62665c6d 100644
--- a/docs/GITHUB_ACTIONS.md
+++ b/docs/GITHUB_ACTIONS.md
@@ -187,6 +187,18 @@ shipped prompt-history guard runs locally when selected; the Windows job and
the Linux worker-containment job are the two suites only CI can prove. Details and the receipt
contract: `docs/CONTRIBUTING.md`.
+The fixed `pregate:merged` package script advertises support for
+`node scripts/pregate.js --guards-only --merged-with <base-sha>` to the quality
+snapshot publisher. It validates the exact published head and fetched default
+SHA before merge admission, then rechecks both inputs inside admission and pins
+the GitHub merge to that head. New and reused snapshot PRs use detached checkouts.
+Failed guards, moved/unreadable inputs, or refused merges retain the PR, checkout,
+and `.cache/quality-snapshot-merge.json` evidence for a later publish cycle;
+they do not enter the generic pending-merge queue. Guard-capable GitLab MRs stay
+open until a supported pinned validation path is available. Repositories without
+this capability retain their existing snapshot merge behavior; arbitrary scripts
+are never executed as a substitute.
+
### Pregate attestation
A green pregate on this machine runs the same planner, runners, environment
diff --git a/package.json b/package.json
index 401ace11db..a89a99be69 100644
--- a/package.json
+++ b/package.json
@@ -50,6 +50,7 @@
"update": "node -e \"const{spawnSync:s}=require('child_process');const w=process.platform==='win32';const r=s(w?'powershell':'bash',w?['-NoProfile','-ExecutionPolicy','Bypass','-File','update.ps1']:['update.sh'],{stdio:'inherit'});process.exit(r.status??1)\"",
"test": "npm test --prefix server && npm test --prefix client",
"pregate": "exec node scripts/pregate.js",
+ "pregate:merged": "node scripts/pregate.js --guards-only",
"quality:snapshot": "node scripts/publish-quality-snapshot.js",
"scan:hidden-content": "node scripts/scan-diff-hidden-content.js",
"eidoverse:assay": "node scripts/eidoverse-resilience-assay.js",
diff --git a/server/services/appQualitySnapshotFile.js b/server/services/appQualitySnapshotFile.js
index c765485281..acbdc4cbea 100644
--- a/server/services/appQualitySnapshotFile.js
+++ b/server/services/appQualitySnapshotFile.js
@@ -13,9 +13,10 @@
* (`publishQualitySnapshot`), commits only this one path on a dedicated branch,
* and merges its pull request immediately so the live checkout never
* diverges from origin and repos that block pushes to the default branch still
- * receive the file. The snapshot is numeric data only and cannot affect tests,
- * so there is no reason to wait for CI; when branch protection still refuses
- * the immediate merge the publisher falls back to the merge-on-green queue.
+ * receive the file. Repositories advertising `pregate:merged` first validate
+ * the combined tree and pin the immediate merge to that exact head and base.
+ * A guarded refusal retains its checkout and evidence for a later publish cycle;
+ * generic repositories retain their existing merge-on-green fallback.
* The immediate merge is the one step that advances the default branch, so it
* runs under this install's repository merge admission (`cosMergeAdmission.js`)
* like every other final merge: while a claim holds the lease the PR is left
@@ -51,7 +52,7 @@ Update the repository \`.quality.json\` numeric quality snapshot generated by Po
## Test plan
- Generated numeric measurements only; no application code changes
-- Data-only change, safe to merge immediately without waiting for CI; no code review required
+- No code review required; repository structural guards and merge policy still apply
`;
async function readSnapshotEntry(repoPath, filename, deps = {}) {
@@ -337,7 +338,7 @@ async function landOrReuse(app, git, defaultBranch, deps, next, count, options =
next = mergeRemoteRows(next, onBranch, deps, options);
if (!next) return skipped(app, 'invalid-evidence');
if (sameSnapshot(onBranch, next) && legacyOnBranch.status === 'absent') {
- const reused = await reuseOpenSnapshotPr(app, git, defaultBranch, deps);
+ const reused = await reuseOpenSnapshotPr(app, git, defaultBranch, deps, guard.remoteSha);
if (reused.published) rememberPublished(app, next, reused);
return reused;
}
@@ -386,7 +387,7 @@ function rememberPublished(app, body, result) {
lastPublishedBody.set(app.repoPath, body);
}
-async function reuseOpenSnapshotPr(app, git, defaultBranch, deps) {
+async function reuseOpenSnapshotPr(app, git, defaultBranch, deps, expectedHeadSha) {
const probe = deps.probePrForBranch
|| (await import('./prProbe.js')).probePrForBranch;
const found = await probe(app.repoPath, QUALITY_SNAPSHOT_BRANCH);
@@ -394,7 +395,7 @@ async function reuseOpenSnapshotPr(app, git, defaultBranch, deps) {
if (found?.prUrl && found?.prNumber && prState === 'OPEN') {
const outcome = await mergeSnapshotPr(app, {
url: found.prUrl, number: found.prNumber, cli: found.cli,
- }, deps, git);
+ }, deps, git, defaultBranch, { expectedHeadSha });
console.log(`📊 Quality snapshot PR already open for app ${app.id}: ${found.prUrl}`);
return {
published: true, hash: null, path: APP_QUALITY_SNAPSHOT_FILENAME,
@@ -402,15 +403,15 @@ async function reuseOpenSnapshotPr(app, git, defaultBranch, deps) {
...mergeOutcomeFields(outcome),
};
}
- return landExistingBranchPr(app, git, defaultBranch, deps);
+ return landExistingBranchPr(app, git, defaultBranch, deps, expectedHeadSha);
}
-async function landExistingBranchPr(app, git, defaultBranch, deps) {
+async function landExistingBranchPr(app, git, defaultBranch, deps, expectedHeadSha) {
const created = await openOrAdoptPr(git, app.repoPath, defaultBranch, deps);
if (!created?.url) {
return skipped(app, 'pr-failed');
}
- const outcome = await mergeSnapshotPr(app, created, deps, git);
+ const outcome = await mergeSnapshotPr(app, created, deps, git, defaultBranch, { expectedHeadSha });
console.log(`📊 Quality snapshot PR opened for app ${app.id}: ${created.url}`);
return {
published: true, hash: null, path: APP_QUALITY_SNAPSHOT_FILENAME,
@@ -422,10 +423,7 @@ async function landExistingBranchPr(app, git, defaultBranch, deps) {
async function landSnapshotPr(app, { body, count, defaultBranch, git, deps, message, removeLegacy = false, remoteSha }) {
const makeTemp = deps.mkdtemp || mkdtemp;
let worktreePath;
- const addWorktree = deps.addWorktree || (async (args, repo) => {
- const { addWorktreeWithRetry } = await import('./worktreeManager.js');
- return addWorktreeWithRetry(args, repo);
- });
+ let retainWorktree = false;
const removeTemp = deps.rm || rm;
const commitPaths = removeLegacy
? [APP_QUALITY_SNAPSHOT_FILENAME, APP_QUALITY_LEGACY_SNAPSHOT_FILENAME]
@@ -434,13 +432,7 @@ async function landSnapshotPr(app, { body, count, defaultBranch, git, deps, mess
const run = async () => {
const baseRef = `origin/${defaultBranch}`;
- await addWorktree(
- // Keep the PR branch free for an in-flight merge/review follow-up. The
- // publisher pushes detached HEAD to the stable remote branch below, so
- // the temporary checkout must not claim that branch locally.
- ['worktree', 'add', '--detach', worktreePath, baseRef],
- app.repoPath,
- );
+ await addSnapshotWorktree(app, deps, worktreePath, baseRef);
await (deps.writeFile || atomicWrite)(join(worktreePath, APP_QUALITY_SNAPSHOT_FILENAME), body);
if (removeLegacy) {
await git.execGit(['rm', '-f', '--', APP_QUALITY_LEGACY_SNAPSHOT_FILENAME], worktreePath);
@@ -466,7 +458,10 @@ async function landSnapshotPr(app, { body, count, defaultBranch, git, deps, mess
if (!pr?.url) {
throw new Error(pr?.error || 'quality snapshot pull request was not created');
}
- const queued = await mergeSnapshotPr(app, pr, deps, git);
+ // If validation is interrupted, preserve the published checkout by default.
+ retainWorktree = true;
+ const queued = await mergeSnapshotPr(app, pr, deps, git, defaultBranch, { worktreePath, expectedHeadSha: hash });
+ retainWorktree = queued.deferred === true && queued.guard?.required === true;
console.log(`📊 Published quality snapshot for app ${app.id}: ${count} measurements → ${hash} (${pr.url})`);
return {
published: true, hash, path: APP_QUALITY_SNAPSHOT_FILENAME,
@@ -478,10 +473,16 @@ async function landSnapshotPr(app, { body, count, defaultBranch, git, deps, mess
const { withCheckoutPublication } = await import('../lib/checkoutRetirementAdmission.js');
return withCheckoutPublication(app.repoPath, async () => {
worktreePath = await makeTemp(join(tmpdir(), 'portos-quality-'));
- return run().finally(() => cleanupSnapshotWorktree(app, git, worktreePath, removeTemp));
+ return run().finally(() => retainWorktree ? undefined : cleanupSnapshotWorktree(app, git, worktreePath, removeTemp));
});
}
+async function addSnapshotWorktree(app, deps, path, ref) {
+ const add = deps.addWorktree || (await import('./worktreeManager.js')).addWorktreeWithRetry;
+ // Detached checkouts leave the stable PR branch attachable for review/recovery.
+ await add(['worktree', 'add', '--detach', path, ref], app.repoPath);
+}
+
const removeWorktreeRegistration = (git, repoPath, worktreePath) => git
.execGit(['worktree', 'remove', '--force', worktreePath], repoPath, { ignoreExitCode: true })
.then(result => (result?.exitCode ?? 0) === 0 ? null : String(result.stderr || `exit ${result.exitCode}`))
@@ -557,13 +558,13 @@ const mergeOutcomeFields = outcome => ({
merged: outcome.merged === true,
queuedMerge: outcome.queued === true,
...(outcome.deferred === true ? { deferredMerge: true } : {}),
+ ...(outcome.guard ? { mergeGuard: outcome.guard } : {}),
});
/**
- * Merge a quality snapshot PR immediately: the change is numeric data only and
- * cannot affect tests, so there is no reason to wait for CI. When branch
- * protection still refuses the immediate merge, fall back to the merge-on-green
- * queue (GitHub) or pipeline auto-merge (GitLab) so the PR still lands.
+ * Guard-capable repositories validate outside admission and recheck both inputs
+ * inside it. They never fall through to an unguarded merge or pending queue.
+ * Other repositories keep their existing immediate/merge-on-green behavior.
*
* The immediate attempt needs this install's repository merge admission. When
* another owner holds it (or ownership cannot be verified) the merge is
@@ -575,8 +576,14 @@ const mergeOutcomeFields = outcome => ({
* @returns {{merged: boolean, queued: boolean, deferred?: boolean}} — merged
* and queued are never both true.
*/
-async function mergeSnapshotPr(app, pr, deps, git) {
+async function mergeSnapshotPr(app, pr, deps, git, defaultBranch, checkout = {}) {
if (!pr?.url || !pr?.number) return { merged: false, queued: false };
+ const guards = await import('./appQualitySnapshotMerge.js');
+ const evidence = await guards.readSnapshotMergeInputs(app, pr, defaultBranch, git, deps);
+ if (evidence.required) {
+ if (checkout.expectedHeadSha !== evidence.headSha) evidence.reason ||= 'snapshot-merge-published-head-changed';
+ return guardedSnapshotMerge(app, pr, deps, git, guards, evidence, checkout.worktreePath);
+ }
const attempt = await withSnapshotMergeAdmission(app, deps, () => tryImmediateMerge(app, pr, deps, git));
if (attempt.deferred) {
const queued = pr.cli === 'glab' ? false : await queueMergeWhenGreenFallback(app, pr, deps);
@@ -587,6 +594,42 @@ async function mergeSnapshotPr(app, pr, deps, git) {
return { merged: false, queued: queued === true };
}
+async function guardedSnapshotMerge(app, pr, deps, git, guards, evidence, existingPath) {
+ const deferred = () => ({ merged: false, queued: false, deferred: true, guard: evidence });
+ const run = async path => {
+ evidence.worktreePath = path;
+ try {
+ if (evidence.reason) throw new Error(evidence.reason);
+ if (!existingPath) await addSnapshotWorktree(app, deps, path, evidence.headSha);
+ await guards.validateSnapshotMerge(app, pr, evidence, git, deps);
+ const attempt = await withSnapshotMergeAdmission(app, deps, async () => {
+ await guards.verifySnapshotMergeInputs(app, pr, evidence, git, deps);
+ return tryImmediateMerge(app, pr, deps, git, evidence.headSha);
+ });
+ if (attempt.result) return { merged: true, queued: false };
+ evidence.reason = attempt.reason || 'snapshot-merge-deferred';
+ } catch (error) {
+ evidence.reason = error.message;
+ console.log(`⏳ Quality snapshot merge retained for app ${app.id}: ${evidence.reason}`);
+ await guards.recordSnapshotMergeEvidence(pr, evidence, deps, {
+ status: 'deferred', stdout: error.stdout, stderr: error.stderr,
+ });
+ return deferred();
+ }
+ await guards.recordSnapshotMergeEvidence(pr, evidence, deps, { status: 'deferred' });
+ return deferred();
+ };
+ if (existingPath) return run(existingPath);
+ if (evidence.reason) return deferred();
+ const { withCheckoutPublication } = await import('../lib/checkoutRetirementAdmission.js');
+ return withCheckoutPublication(app.repoPath, async () => {
+ const path = await (deps.mkdtemp || mkdtemp)(join(tmpdir(), 'portos-quality-'));
+ const result = await run(path);
+ if (result.merged) await cleanupSnapshotWorktree(app, git, path, deps.rm || rm);
+ return result;
+ });
+}
+
async function withSnapshotMergeAdmission(app, deps, work) {
const readOrigin = deps.getOriginInfo || (await import('../lib/gitRemote.js')).getOriginInfo;
const withAdmission = deps.withMergeAdmission
@@ -595,13 +638,13 @@ async function withSnapshotMergeAdmission(app, deps, work) {
const admitted = await withAdmission(origin, work)
.catch(err => ({ admitted: false, reason: err?.message || 'admission-error' }));
if (admitted.admitted !== true) {
- console.warn(`⏳ Quality snapshot merge deferred for app ${app.id}: ${admitted.reason || 'admission refused'}`);
- return { deferred: true };
+ console.log(`⏳ Quality snapshot merge deferred for app ${app.id}: ${admitted.reason || 'admission refused'}`);
+ return { deferred: true, reason: admitted.reason || 'admission-refused' };
}
return { deferred: false, result: admitted.result === true };
}
-async function tryImmediateMerge(app, pr, deps, git) {
+async function tryImmediateMerge(app, pr, deps, git, expectedHeadSha) {
if (pr.cli === 'glab') {
const execGlab = deps.execGlab || (await import('./gitlab.js')).execGlab;
const run = args => execGlab(args, app.repoPath, undefined, { rejectOnError: true })
@@ -621,7 +664,7 @@ async function tryImmediateMerge(app, pr, deps, git) {
const mergePR = deps.mergePR || git?.mergePR;
if (typeof mergePR !== 'function') return false;
const result = await mergePR.call(git || null,
- app.repoPath, pr.number, { forgeAccount: app?.forgeAccount || null },
+ app.repoPath, pr.number, { forgeAccount: app?.forgeAccount || null, ...(expectedHeadSha ? { expectedHeadSha } : {}) },
).catch(err => ({ success: false, error: err?.message }));
if (result?.success !== true) {
console.log(`📊 Quality snapshot PR #${pr.number} immediate merge unavailable for app ${app.id}: ${result?.error || 'merge refused'}`);
diff --git a/server/services/appQualitySnapshotFile.test.js b/server/services/appQualitySnapshotFile.test.js
index d4fdbb81d3..e4802bc432 100644
--- a/server/services/appQualitySnapshotFile.test.js
+++ b/server/services/appQualitySnapshotFile.test.js
@@ -116,8 +116,8 @@ it('lands a changed snapshot from a detached worktree so the PR branch stays att
base: 'main',
head: 'portos/quality-snapshot',
}));
- expect(deps.git.createPR.mock.calls[0][1].body).toContain('no code review required');
- expect(deps.git.createPR.mock.calls[0][1].body).toContain('without waiting for CI');
+ expect(deps.git.createPR.mock.calls[0][1].body).toContain('No code review required');
+ expect(deps.git.createPR.mock.calls[0][1].body).toContain('structural guards and merge policy still apply');
expect(deps.git.mergePR).toHaveBeenCalledWith('/repo/example-app', 42, expect.objectContaining({
forgeAccount: null,
}));
@@ -156,7 +156,7 @@ it('merges an already-open snapshot PR whose branch already has the same bytes w
const body = canonical();
const deps = testDeps({
git: gitDouble({
- execGit: vi.fn(async (args) => args[0] === 'show' && String(args[1]).includes(QUALITY_SNAPSHOT_BRANCH)
+ execGit: vi.fn(async (args) => args[0] === 'ls-tree' ? { exitCode: 0, stdout: '' } : args[0] === 'show' && String(args[1]).includes(QUALITY_SNAPSHOT_BRANCH)
? { exitCode: 0, stdout: body, stderr: '' }
: missingShow),
}),
@@ -179,7 +179,7 @@ it('falls back to the merge-on-green queue when branch protection refuses the im
const body = canonical();
const deps = testDeps({
git: gitDouble({
- execGit: vi.fn(async (args) => args[0] === 'show' && String(args[1]).includes(QUALITY_SNAPSHOT_BRANCH)
+ execGit: vi.fn(async (args) => args[0] === 'ls-tree' ? { exitCode: 0, stdout: '' } : args[0] === 'show' && String(args[1]).includes(QUALITY_SNAPSHOT_BRANCH)
? { exitCode: 0, stdout: body, stderr: '' }
: missingShow),
mergePR: vi.fn(async () => ({ success: false, error: 'required status checks' })),
@@ -890,3 +890,153 @@ it('applies the same ownership protection to explicit snapshot migrations', asyn
ownership.agents = {};
expect(await migrateAppQualitySnapshot(app, deps)).toMatchObject({ published: true });
});
+
+const guardedPublication = (reused = false) => {
+ const head = 'a'.repeat(40);
+ const base = 'b'.repeat(40);
+ const live = { head, base, state: 'OPEN', manifest: { scripts: { 'pregate:merged': 'node scripts/pregate.js --guards-only' } } };
+ const events = [];
+ const deps = testDeps({
+ git: gitDouble({
+ execGit: vi.fn(async args => {
+ if (args[0] === 'ls-tree') return { exitCode: 0, stdout: 'package.json\n' };
+ if (args[0] === 'show') {
+ if (args[1].endsWith(':package.json')) return { exitCode: 0, stdout: JSON.stringify(live.manifest) };
+ return reused && args[1] === `origin/${QUALITY_SNAPSHOT_BRANCH}:.quality.json`
+ ? { exitCode: 0, stdout: canonical() } : missingShow;
+ }
+ if (args[0] === 'rev-parse') {
+ if (args[3] === `refs/remotes/origin/${QUALITY_SNAPSHOT_BRANCH}`) {
+ return reused ? { exitCode: 0, stdout: head } : missingShow;
+ }
+ return { exitCode: 0, stdout: args[2] === 'origin/main^{commit}' ? base : head };
+ }
+ if (args[0] === 'diff') return { exitCode: 0, stdout: '.quality.json\0' };
+ if (args[0] === 'ls-remote') return { exitCode: 0, stdout: `${live.base}\trefs/heads/main\n` };
+ return { exitCode: 0, stdout: '' };
+ }),
+ commit: vi.fn(async () => ({ hash: head })),
+ mergePR: vi.fn(async () => { events.push('merge'); return { success: true }; }),
+ }),
+ probePrForBranch: vi.fn(async () => reused
+ ? { readable: true, prState: 'OPEN', prUrl, prNumber: 42, cli: 'gh' }
+ : { readable: true, prState: null }),
+ resolveForgeForRepo: vi.fn(async () => ({ cli: 'gh', env: { EXAMPLE_FORGE_ACCOUNT: 'selected' } })),
+ execGh: vi.fn(async () => JSON.stringify({
+ state: live.state, isDraft: false, isCrossRepository: false, headRefOid: live.head,
+ headRefName: QUALITY_SNAPSHOT_BRANCH, baseRefName: 'main',
+ })),
+ linkWorktreeDependencies: vi.fn(async () => {}),
+ writeMergeEvidence: vi.fn(async () => {}),
+ execSnapshotMergeGuards: vi.fn(async () => { events.push('guards'); return { stdout: 'guards passed', stderr: '' }; }),
+ withMergeAdmission: vi.fn(async (_origin, work) => {
+ events.push('admission');
+ return { admitted: true, result: await work() };
+ }),
+ });
+ return { deps, live, events, head, base };
+};
+
+// These publisher-boundary regressions uniquely cover exact input validation
+// and recovery across both temporary-checkout owners (new and reused PRs).
+it.each([false, true])('validates the snapshot before admission and pins the head (reused: %s)', async reused => {
+ const { deps, events, head, base } = guardedPublication(reused);
+ expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({ published: true, merged: true, queuedMerge: false });
+ expect(events).toEqual(['guards', 'admission', 'merge']);
+ expect(deps.execSnapshotMergeGuards).toHaveBeenCalledWith(process.execPath,
+ [join(worktreePath, 'scripts', 'pregate.js'), '--guards-only', '--merged-with', base],
+ expect.objectContaining({ cwd: worktreePath, env: expect.objectContaining({ PORTOS_TEST_MEMO: 'off' }) }));
+ expect(deps.git.mergePR).toHaveBeenCalledWith(app.repoPath, 42, { forgeAccount: null, expectedHeadSha: head });
+ expect(deps.resolveForgeForRepo).toHaveBeenCalledWith(app.repoPath, { forgeAccount: null });
+ expect(deps.execGh).toHaveBeenCalledWith(expect.any(Array), undefined,
+ { cwd: app.repoPath, env: { EXAMPLE_FORGE_ACCOUNT: 'selected' } });
+ expect(deps.queuePendingMerge).not.toHaveBeenCalled();
+ expect(deps.rm).toHaveBeenCalledWith(worktreePath, { recursive: true, force: true });
+ expect(deps.addWorktree).toHaveBeenCalledTimes(1);
+ expect(deps.addWorktree.mock.calls[0][0]).toEqual(
+ ['worktree', 'add', '--detach', worktreePath, reused ? head : 'origin/main']);
+ expect(deps.writeMergeEvidence).toHaveBeenLastCalledWith(expect.any(String), expect.objectContaining({
+ headSha: head, baseSha: base, status: 'passed', stdout: 'guards passed',
+ }));
+});
+
+it.each([false, true])('retains failed guard evidence without admission or a queue bypass (reused: %s)', async reused => {
+ const { deps, head, base } = guardedPublication(reused);
+ deps.execSnapshotMergeGuards.mockRejectedValue(Object.assign(new Error('guards failed'), { stdout: 'hostControlRoutes.test.js failed' }));
+ expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({
+ published: true, merged: false, queuedMerge: false, deferredMerge: true,
+ mergeGuard: { headSha: head, baseSha: base, worktreePath, reason: 'guards failed' },
+ });
+ expect(deps.withMergeAdmission).not.toHaveBeenCalled();
+ expect(deps.git.mergePR).not.toHaveBeenCalled();
+ expect(deps.queuePendingMerge).not.toHaveBeenCalled();
+ expect(deps.rm).not.toHaveBeenCalled();
+ expect(deps.git.execGit.mock.calls.some(([args]) => args[0] === 'worktree' && args[1] === 'remove')).toBe(false);
+ expect(deps.writeMergeEvidence).toHaveBeenLastCalledWith(expect.any(String), expect.objectContaining({
+ status: 'deferred', stdout: 'hostControlRoutes.test.js failed',
+ }));
+});
+
+it.each(['head', 'base', 'unreadable'])('refuses a %s race inside admission and retains the validated checkout', async race => {
+ const { deps, live } = guardedPublication(true);
+ deps.execSnapshotMergeGuards.mockImplementation(async () => {
+ if (race === 'unreadable') deps.execGh.mockResolvedValueOnce('not-json');
+ else live[race] = 'c'.repeat(40);
+ return { stdout: 'guards passed', stderr: '' };
+ });
+ expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({ merged: false, deferredMerge: true, mergeGuard: { worktreePath } });
+ expect(deps.withMergeAdmission).toHaveBeenCalledTimes(1);
+ expect(deps.git.mergePR).not.toHaveBeenCalled();
+ expect(deps.queuePendingMerge).not.toHaveBeenCalled();
+ expect(deps.rm).not.toHaveBeenCalled();
+});
+
+it('refuses a PR that moved away from the new publication before validation', async () => {
+ const { deps, live } = guardedPublication();
+ live.head = 'c'.repeat(40);
+ expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({
+ published: true, merged: false, deferredMerge: true, mergeGuard: { reason: 'snapshot-merge-head-changed' },
+ });
+ expect(deps.execSnapshotMergeGuards).not.toHaveBeenCalled();
+ expect(deps.withMergeAdmission).not.toHaveBeenCalled();
+ expect(deps.rm).not.toHaveBeenCalled();
+});
+
+it.each(['admission', 'merge'])('keeps guarded %s refusals retryable without queuing an unvalidated later merge', async refused => {
+ const { deps } = guardedPublication(true);
+ if (refused === 'admission') deps.withMergeAdmission.mockResolvedValue({ admitted: false, reason: 'active-owner' });
+ else deps.git.mergePR.mockResolvedValue({ success: false, error: 'required checks pending' });
+ expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({ merged: false, deferredMerge: true, queuedMerge: false });
+ expect(deps.queuePendingMerge).not.toHaveBeenCalled();
+ expect(deps.rm).not.toHaveBeenCalled();
+ deps.withMergeAdmission.mockImplementation(async (_origin, work) => ({ admitted: true, result: await work() }));
+ deps.git.mergePR.mockResolvedValue({ success: true });
+ expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({ merged: true });
+});
+
+it('leaves a guard-capable GitLab MR open instead of falling through to an unpinned merge', async () => {
+ const { deps } = guardedPublication(true);
+ deps.probePrForBranch.mockResolvedValue({ readable: true, prState: 'OPEN', prUrl, prNumber: 42, cli: 'glab' });
+ deps.execGlab = vi.fn();
+ expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({
+ merged: false, deferredMerge: true, queuedMerge: false, mergeGuard: { reason: 'unsupported-merge-guard-forge' },
+ });
+ expect(deps.execGlab).not.toHaveBeenCalled();
+ expect(deps.withMergeAdmission).not.toHaveBeenCalled();
+});
+
+it('keeps generic manifest behavior but refuses an unreadable or unsupported guard contract', async () => {
+ const { deps, live } = guardedPublication(true);
+ live.manifest = { scripts: { pregate: 'a generic app command' } };
+ expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({ merged: true });
+ expect(deps.execSnapshotMergeGuards).not.toHaveBeenCalled();
+ __resetQualitySnapshotPublishState();
+ live.manifest = { scripts: { 'pregate:merged': 'another command' } };
+ deps.git.mergePR.mockClear();
+ expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({ merged: false, deferredMerge: true });
+ expect(deps.git.mergePR).not.toHaveBeenCalled();
+ live.manifest = null;
+ expect(await publishAppQualitySnapshot(app, deps)).toMatchObject({
+ merged: false, deferredMerge: true, mergeGuard: { reason: 'merge-guard-manifest-unreadable' },
+ });
+});
diff --git a/server/services/appQualitySnapshotMerge.js b/server/services/appQualitySnapshotMerge.js
new file mode 100644
index 0000000000..9290c9de53
--- /dev/null
+++ b/server/services/appQualitySnapshotMerge.js
@@ -0,0 +1,105 @@
+import { join } from 'node:path';
+import { atomicWrite, execFileAsync } from '../lib/fileCore.js';
+
+const GUARD_COMMAND = 'node scripts/pregate.js --guards-only';
+const validSha = value => typeof value === 'string' && /^[a-f0-9]{40}$/i.test(value);
+
+async function gitText(git, repoPath, args) {
+ const result = await git.execGit(args, repoPath);
+ if (result?.exitCode !== 0 || typeof result.stdout !== 'string') throw new Error('merge-input-unreadable');
+ return result.stdout.trim();
+}
+
+/** Only this fixed command opts a repository in; never execute arbitrary manifest text. */
+async function advertisesGuards(git, repoPath, ref) {
+ const path = await gitText(git, repoPath, ['ls-tree', '--name-only', ref, '--', 'package.json']);
+ if (!path) return false;
+ const manifest = JSON.parse(await gitText(git, repoPath, ['show', `${ref}:package.json`]));
+ if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) throw new Error('merge-guard-manifest-unreadable');
+ const command = manifest?.scripts?.['pregate:merged'];
+ if (command === undefined) return false;
+ if (command !== GUARD_COMMAND) throw new Error('unsupported-merge-guard-command');
+ return true;
+}
+
+async function readPr(app, pr, git, deps) {
+ const resolveForge = deps.resolveForgeForRepo || git.resolveForgeForRepo;
+ const { cli, env } = await resolveForge(app.repoPath, { forgeAccount: app.forgeAccount || null });
+ if (cli !== 'gh') throw new Error('unsupported-merge-guard-forge');
+ const execGh = deps.execGh || (await import('./github.js')).execGh;
+ const raw = await execGh(['pr', 'view', String(pr.number), '--json',
+ 'state,isDraft,headRefOid,headRefName,baseRefName,isCrossRepository'], undefined, { cwd: app.repoPath, env });
+ const state = JSON.parse(raw);
+ if (state?.state !== 'OPEN' || state.isDraft !== false || state.isCrossRepository !== false
+ || !validSha(state.headRefOid) || state.headRefName !== 'portos/quality-snapshot') {
+ throw new Error('snapshot-merge-pr-unverified');
+ }
+ return state;
+}
+
+/** Resolve both full SHAs outside admission, including the already-open PR path. */
+export async function readSnapshotMergeInputs(app, pr, defaultBranch, git, deps) {
+ const evidence = { required: true, defaultBranch };
+ try {
+ if (!await advertisesGuards(git, app.repoPath, `origin/${defaultBranch}`)) return { required: false };
+ if (pr.cli !== 'gh') throw new Error('unsupported-merge-guard-forge');
+ await git.fetchOrigin(app.repoPath, { prune: true });
+ evidence.baseSha = await gitText(git, app.repoPath, ['rev-parse', '--verify', `origin/${defaultBranch}^{commit}`]);
+ if (!validSha(evidence.baseSha)) throw new Error('snapshot-merge-base-unverified');
+ // A fetch can change the advertised contract too. Refuse rather than downgrade.
+ if (!await advertisesGuards(git, app.repoPath, evidence.baseSha)) throw new Error('merge-guard-capability-changed');
+ const state = await readPr(app, pr, git, deps);
+ evidence.headSha = state.headRefOid;
+ if (state.baseRefName !== defaultBranch) throw new Error('snapshot-merge-base-changed');
+ const fetchedHead = await gitText(git, app.repoPath,
+ ['rev-parse', '--verify', 'origin/portos/quality-snapshot^{commit}']);
+ if (fetchedHead !== evidence.headSha) throw new Error('snapshot-merge-head-changed');
+ return evidence;
+ } catch (error) {
+ return { ...evidence, reason: error.message };
+ }
+}
+
+/** Retained beside the checkout on any refusal; never put guard output on the forge. */
+export async function recordSnapshotMergeEvidence(pr, evidence, deps, details) {
+ if (!evidence.worktreePath) return;
+ evidence.evidencePath = join(evidence.worktreePath, '.cache', 'quality-snapshot-merge.json');
+ const write = deps.writeMergeEvidence || atomicWrite;
+ await write(evidence.evidencePath, { prUrl: pr.url, ...evidence, ...details });
+}
+
+export async function validateSnapshotMerge(app, pr, evidence, git, deps) {
+ const cwd = evidence.worktreePath;
+ const head = await gitText(git, cwd, ['rev-parse', '--verify', 'HEAD^{commit}']);
+ if (head !== evidence.headSha) throw new Error('snapshot-merge-checkout-head-changed');
+ if (await gitText(git, cwd, ['status', '--porcelain=v1', '--untracked-files=all'])) {
+ throw new Error('snapshot-merge-checkout-dirty');
+ }
+ const link = deps.linkWorktreeDependencies || (await import('./worktreeManager.js')).linkWorktreeDependencies;
+ await link(app.repoPath, cwd);
+ await recordSnapshotMergeEvidence(pr, evidence, deps, { status: 'validating' });
+ const exec = deps.execSnapshotMergeGuards || execFileAsync;
+ const output = await exec(process.execPath,
+ [join(cwd, 'scripts', 'pregate.js'), '--guards-only', '--merged-with', evidence.baseSha],
+ { cwd, env: { ...process.env, PORTOS_TEST_MEMO: 'off' }, timeout: 600000, maxBuffer: 16 * 1024 * 1024 });
+ if (await gitText(git, cwd, ['rev-parse', '--verify', 'HEAD^{commit}']) !== evidence.headSha
+ || await gitText(git, cwd, ['status', '--porcelain=v1', '--untracked-files=all'])) {
+ throw new Error('snapshot-merge-checkout-changed-during-validation');
+ }
+ await recordSnapshotMergeEvidence(pr, evidence, deps,
+ { status: 'passed', stdout: output.stdout, stderr: output.stderr });
+}
+
+/** Called only inside admission. A moving base needs new guards, not a rebase. */
+export async function verifySnapshotMergeInputs(app, pr, evidence, git, deps) {
+ const state = await readPr(app, pr, git, deps);
+ if (state.headRefOid !== evidence.headSha || state.baseRefName !== evidence.defaultBranch) {
+ throw new Error('snapshot-merge-head-or-target-changed');
+ }
+ const remote = await gitText(git, app.repoPath,
+ ['ls-remote', '--exit-code', 'origin', `refs/heads/${evidence.defaultBranch}`]);
+ const [sha, ref, ...extra] = remote.split(/\s+/);
+ if (extra.length || sha !== evidence.baseSha || ref !== `refs/heads/${evidence.defaultBranch}`) {
+ throw new Error('snapshot-merge-base-changed');
+ }
+}