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: fence external merge admission against the live base ref

[._.]/ Adam Eivybf90ebbb8667
diff --git a/docs/AGENT_API_KEY.md b/docs/AGENT_API_KEY.md
index d3b4564dc6..93887854ac 100644
--- a/docs/AGENT_API_KEY.md
+++ b/docs/AGENT_API_KEY.md
@@ -109,7 +109,11 @@ node <portos-root>/scripts/portos-api.js post /api/cos/merge-admission/external
The app must already exist in the local app registry. The server verifies its
origin and the checkout's real Git common directory, separate linked checkout,
branch, identity, local review receipt, live same-repository open PR, head and
-base branch/SHA. An active/uncertain CoS owner, checkout lock, retirement fence, changed
+base branch/SHA. The base SHA is the live `refs/heads/<baseBranch>` commit,
+not GitHub's historical PR `baseRefOid`. Acquire and check read that ref with
+the PR's repository, base branch and head through the app's authorized forge
+transport; a moved or missing ref withholds admission until guards are rerun.
+An active/uncertain CoS owner, checkout lock, retirement fence, changed
proof or unreadable state withholds admission. Fork PRs and detached/primary
checkouts are outside this bounded flow. Repository keys are shared with CoS
parents and the pending-merge sweep, so all three contend on the same lease;
diff --git a/server/routes/cosExternalMergeAdmission.test.js b/server/routes/cosExternalMergeAdmission.test.js
index 1a024443a0..04e185765a 100644
--- a/server/routes/cosExternalMergeAdmission.test.js
+++ b/server/routes/cosExternalMergeAdmission.test.js
@@ -9,7 +9,7 @@ import { request } from '../lib/testHelper.js';
import { errorMiddleware } from '../lib/errorHandler.js';
import { DEV_PROXY_CLIENT_ADDRESS_HEADER } from '../../lib/portosAuthCore.js';
-const fixture = vi.hoisted(() => ({ state: null, disk: null, trusted: true, failSave: false, apps: {}, prs: {}, peers: [], beforeForge: null }));
+const fixture = vi.hoisted(() => ({ state: null, disk: null, trusted: true, failSave: false, apps: {}, prs: {}, refs: {}, peers: [], beforeForge: null }));
const { tempRoot, makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'portos-external-admission-' });
vi.mock('../lib/fileUtils.js', async () => makeProxy(await vi.importActual('../lib/fileUtils.js')));
vi.mock('../services/cosState.js', () => ({
@@ -23,8 +23,14 @@ vi.mock('../services/cosState.js', () => ({
}));
vi.mock('../services/apps.js', () => ({ getAppById: async id => fixture.apps[id] ?? null }));
vi.mock('../services/github.js', () => ({ execGh: async args => {
- await fixture.beforeForge?.(args[args.indexOf('--repo') + 1]);
- return JSON.stringify(fixture.prs[args[args.indexOf('--repo') + 1]] ?? null);
+ const fields = Object.fromEntries(args.filter((_, index) => ['-f', '-F'].includes(args[index - 1]))
+ .map(field => { const split = field.indexOf('='); return [field.slice(0, split), field.slice(split + 1)]; }));
+ const repository = `${args[args.indexOf('--hostname') + 1]}/${fields.owner}/${fields.name}`;
+ await fixture.beforeForge?.(repository);
+ const ref = fixture.refs[repository];
+ return JSON.stringify({ data: { repository: { nameWithOwner: `${fields.owner}/${fields.name}`,
+ pullRequest: Number(fields.number) === 7 ? fixture.prs[repository] : null,
+ ref: ref && `${ref.prefix}${ref.name}` === fields.baseRef ? ref : null } } });
} }));
vi.mock('../services/forgeExecOptions.js', () => ({ resolveForgeExecOptions: async cwd => ({ cwd, env: {} }) }));
vi.mock('../services/instanceIdentity.js', () => ({ loadData: async () => ({ peers: fixture.peers }) }));
@@ -88,17 +94,42 @@ afterAll(cleanup);
beforeEach(async () => {
fixture.trusted = true; fixture.failSave = false; fixture.peers = []; fixture.beforeForge = null;
fixture.state = { agents: {}, mergeAdmissions: {} }; persist();
- fixture.apps = {}; fixture.prs = {};
+ fixture.apps = {}; fixture.prs = {}; fixture.refs = {};
for (const repo of [example, other]) {
const { input } = repo;
fixture.apps[input.appId] = { id: input.appId, repoPath: repo.repoPath };
fixture.prs[repo.key] = { url: input.prUrl, number: 7, state: 'OPEN', isDraft: false, isCrossRepository: false,
- headRefName: 'feature', headRefOid: input.headSha, baseRefName: 'main', baseRefOid: input.baseSha };
+ headRefName: 'feature', headRefOid: input.headSha, baseRefName: 'main', baseRefOid: 'a'.repeat(40) };
+ fixture.refs[repo.key] = { prefix: 'refs/heads/', name: 'main', target: { __typename: 'Commit', oid: input.baseSha } };
await writeFile(repo.reviewFile, `REVIEW_STATUS=clean\nREVIEW_HEAD=${input.headSha}\n`);
}
});
describe('outside merge admission through the authenticated HTTP boundary', () => {
+ it('fences the checked live base independently of the historical PR base on acquire and check', async () => {
+ const historicalBase = fixture.prs[example.key].baseRefOid;
+ expect(historicalBase).not.toBe(example.input.baseSha);
+ expect((await acquire({ ...example, input: { ...example.input, baseSha: historicalBase } })).body)
+ .toMatchObject({ admitted: false, reason: 'external-pr-changed' });
+ expect(fixture.state.mergeAdmissions).toEqual({});
+ const { body: granted } = await acquire();
+ expect(granted).toMatchObject({ admitted: true, baseSha: example.input.baseSha, baseBranch: 'main' });
+ expect((await check(granted.token)).body.admitted).toBe(true);
+ fixture.refs[example.key].target.oid = 'f'.repeat(40);
+ expect((await check(granted.token)).body).toMatchObject({ admitted: false, reason: 'external-pr-changed' });
+ expect((await release(granted.token)).body.released).toBe(true);
+ expect((await acquire()).body).toMatchObject({ admitted: false, reason: 'external-pr-changed' });
+ });
+
+ it.each(['deleted-ref', 'non-commit', 'head', 'repository'])('refuses acquisition with a %s forge target', async mode => {
+ if (mode === 'deleted-ref') fixture.refs[example.key] = null;
+ if (mode === 'non-commit') fixture.refs[example.key].target.__typename = 'Tag';
+ if (mode === 'head') fixture.prs[example.key].headRefOid = 'f'.repeat(40);
+ if (mode === 'repository') fixture.prs[example.key].url = other.input.prUrl;
+ expect((await acquire()).body).toMatchObject({ admitted: false, reason: 'external-pr-changed' });
+ expect(fixture.state.mergeAdmissions).toEqual({});
+ });
+
it('binds a real operator credential and separate run secret without creating CoS agents', async () => {
const granted = await acquire();
expect(granted.status).toBe(200);
@@ -157,7 +188,7 @@ describe('outside merge admission through the authenticated HTTP boundary', () =
const { body: granted } = await acquire();
expect(granted.admitted).toBe(true);
if (mode === 'head') fixture.prs[example.key].headRefOid = 'f'.repeat(40);
- if (mode === 'base') fixture.prs[example.key].baseRefOid = 'f'.repeat(40);
+ if (mode === 'base') fixture.refs[example.key].target.oid = 'f'.repeat(40);
if (mode === 'base-branch') fixture.prs[example.key].baseRefName = 'release';
if (mode === 'repository') fixture.apps.repo.repoPath = other.repoPath;
if (mode === 'review') await writeFile(example.reviewFile, `REVIEW_STATUS=clean\nREVIEW_HEAD=${'f'.repeat(40)}\n`);
diff --git a/server/services/externalMergeTarget.js b/server/services/externalMergeTarget.js
index e8f3b00fd5..81768ea5f4 100644
--- a/server/services/externalMergeTarget.js
+++ b/server/services/externalMergeTarget.js
@@ -11,6 +11,13 @@ import { readReviewEvidence } from './mergeReviewEvidence.js';
const refused = reason => ({ reason });
const canonical = path => typeof path === 'string' && isAbsolute(path) ? realpath(path).catch(() => null) : null;
const gitValue = async (path, args) => (await execGit(args, path, { timeout: 10000 }).catch(() => null))?.stdout?.trim();
+const EXTERNAL_MERGE_QUERY = `query($owner:String!,$name:String!,$number:Int!,$baseRef:String!){
+ repository(owner:$owner,name:$name){
+ nameWithOwner
+ pullRequest(number:$number){url number state isDraft isCrossRepository headRefName headRefOid baseRefName}
+ ref(qualifiedName:$baseRef){prefix name target{__typename oid}}
+ }
+}`;
export async function inspectExternalMergeCheckout(input, agents) {
const [{ getAppById }, { repositoryKey }] = await Promise.all([import('./apps.js'), import('./cosMergeAdmission.js')]);
@@ -86,15 +93,25 @@ export async function inspectExternalMergeTarget(input, agents) {
const pr = parsePullRequestUrl(input.prUrl);
const [{ execGh }, { resolveForgeExecOptions }] = await Promise.all([import('./github.js'), import('./forgeExecOptions.js')]);
const options = await resolveForgeExecOptions(repoPath, { forgeAccount: app.forgeAccount });
- const raw = await execGh(['pr', 'view', String(pr.number), '--repo', `${pr.host}/${pr.owner}/${pr.repo}`,
- '--json', 'url,number,state,isDraft,isCrossRepository,headRefName,headRefOid,baseRefName,baseRefOid'],
+ // baseRefOid is the PR's historical base, not the branch guards checked.
+ // Read the exact base ref alongside the PR identity on every acquire/check.
+ const raw = await execGh(['api', 'graphql', '--hostname', pr.host,
+ '-f', `query=${EXTERNAL_MERGE_QUERY}`, '-f', `owner=${pr.owner}`, '-f', `name=${pr.repo}`,
+ '-F', `number=${pr.number}`, '-f', `baseRef=refs/heads/${input.baseBranch}`],
10000, options).catch(() => null);
- const live = safeJSONParse(raw, null);
+ const response = safeJSONParse(raw, null);
+ const repo = response?.data?.repository;
+ const live = repo?.pullRequest;
+ const base = repo?.ref;
const actual = parsePullRequestUrl(live?.url);
- if (!actual || repositoryKey({ host: actual.host, fullName: `${actual.owner}/${actual.repo}` }) !== repository
+ if (response?.errors?.length || !actual
+ || repositoryKey({ host: pr.host, fullName: repo?.nameWithOwner }) !== repository
+ || repositoryKey({ host: actual.host, fullName: `${actual.owner}/${actual.repo}` }) !== repository
|| actual.number !== pr.number || live.number !== pr.number || live.state !== 'OPEN'
|| live.isDraft !== false || live.isCrossRepository !== false || live.headRefName !== branch
- || live.headRefOid !== head || live.baseRefOid !== input.baseSha || live.baseRefName !== input.baseBranch || live.baseRefName === branch) {
+ || live.headRefOid !== head || live.baseRefName !== input.baseBranch || live.baseRefName === branch
+ || base?.prefix !== 'refs/heads/' || base.name !== live.baseRefName
+ || base.target?.__typename !== 'Commit' || base.target.oid !== input.baseSha) {
return refused('external-pr-changed');
}
return { repository, target: { ...target, prUrl: live.url } };