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
feat(cos): admit authenticated outside agents to merge leases (#13385)
[._.]/ Adam Eivyebf7f92348d0
diff --git a/.claude/skills/portos-api/SKILL.md b/.claude/skills/portos-api/SKILL.mdindex 748258b073..50e8bf3163 100644--- a/.claude/skills/portos-api/SKILL.md+++ b/.claude/skills/portos-api/SKILL.md@@ -26,3 +26,5 @@ node scripts/portos-api.js get /api/api-docs/catalog.json # discover endpoints- Public Suno publication and social posting still need the human (root `AGENTS.md`, Security Model).Details: [docs/AGENT_API_KEY.md](../../../docs/AGENT_API_KEY.md).++For an outside terminal agent delivering a reviewed PR, use the supported [external merge-admission flow](../../../docs/AGENT_API_KEY.md#outside-agent-merge-admission). It binds a per-run secret and verified operator identity to the server-validated app, linked checkout and exact PR head/base; do not invent or borrow a CoS `agentId`.diff --git a/AGENTS.md b/AGENTS.mdindex f15fc112b6..aca422f8c0 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -263,7 +263,7 @@ This policy governs code comments, not user-facing guides or product copy.- **Attribute completed local PR reviews.** Follow [PR_REVIEW_ATTRIBUTION.md](docs/PR_REVIEW_ATTRIBUTION.md): add `reviewer:<model>` only from actual pre-publication local code-review execution/model receipts, including optional reviewers. Configured/queued reviewers and requested forge users never qualify. Preserve existing labels; normalize with `normalizePlannerId`. GitLab reviewer labels stay unscoped so several actual models coexist.- **main**: active development. **release**: merge a frozen candidate into `release` to trigger publication. **Release procedure:** [docs/VERSIONING.md](docs/VERSIONING.md#creating-a-release) is canonical and overrides the generic slashdo promotion recipe. Pin current `main` once at release kickoff in an isolated candidate branch, persist its cutoff, and resume that same candidate after interruption. Later merges and unrelated open issues/PRs belong to the next release. Only preparation and evidenced candidate-gating fixes may advance it; never rebase/merge live `main` into it. Promote the validated candidate, then synchronize the published release back to `main` through a normal PR.- **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. Before every managed merge (including `/do:next` single-issue and swarm Phase C, `/do:pr --merge`, and CoS claims), fetch the actual PR base branch and run `node scripts/pregate.js --guards-only --merged-with origin/<base>` against the committed head and that fetched base (`main` for development PRs; `release` for candidate promotion). 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 [merge gate](lib/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.+- **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 actual PR base branch and run `node scripts/pregate.js --guards-only --merged-with origin/<base>` against the committed head and that fetched base (`main` for development PRs; `release` for candidate promotion). 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 [merge gate](lib/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`. Outside terminal agents use the principal-bound [external admission flow](docs/AGENT_API_KEY.md#outside-agent-merge-admission); never invent a CoS parent or borrow another run’s `agentId`. 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**: after publication, 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. This publication goes to the next release; never move or delay the frozen candidate to include it.diff --git a/docs/AGENT_API_KEY.md b/docs/AGENT_API_KEY.mdindex 690f4df53b..39bc153cd0 100644--- a/docs/AGENT_API_KEY.md+++ b/docs/AGENT_API_KEY.md@@ -54,3 +54,94 @@ curl -sS "$(jq -r .url ~/.portos/agent-key.json)/api/cos/tasks" \- Holding the token is the only thing that grants it. Requests are never trusted for arriving on loopback: Tailscale serve and the dev proxy both deliver remote traffic to `127.0.0.1`.- Anything that can read a `0600` file in the host user's home already runs as that user and could mint a session from `data/auth-sessions.json`, so the file widens no boundary. It lives outside `data/` so backups and peer sync never carry the plaintext token (`auth-sessions.json` stores hashes only).- The on/off flag lives under `secrets.agentKey` in `settings.json`, out of reach of the generic settings GET/PUT. `PUT /api/auth/agent-key` and `POST /api/auth/agent-key/rotate` are on the host-control list (`server/lib/hostControlRoutes.js`). `GET /api/auth/agent-key` reports state and never the token.++## Outside-agent merge admission++An outside terminal agent uses `POST /api/cos/merge-admission/external`; it does+not create a CoS agent record or borrow another run's `agentId`. The existing+operator boundary applies: a verified session (including the agent key) when+password protection is on, or a genuine local connection when it is off.+Anonymous remote and scoped peer requests cannot acquire or release admission.++Create one secret for this run and retain it until release is confirmed:++```bash+export PORTOS_ADMISSION_SESSION="$(node -e 'process.stdout.write(require("node:crypto").randomBytes(32).toString("hex"))')"+```++`portos-api.js` sends it as `X-PortOS-Admission-Session` only to the external+admission endpoint. Keep it out of logs, reviewer environments, PRs and shared+files. It separates concurrent terminal runs sharing the same agent-key+credential. The server stores only a hash bound to the verified credential+identity. A different credential or run secret cannot check or release the+handle, even if it knows the lease token. Rotating/revoking the credential+invalidates its authority; an interrupted holder remains reserved until the+five-minute maximum hold elapses. This is the same bounded coordination as CoS+leases, not a forge-side fence against a merge already in flight at expiry.++Before acquiring, finish all configured reviews, required CI for the exact PR+head, and this repository's combined-tree structural guards **outside** the+lease. Keep the checked head and base SHAs. The worktree-private+`portos-review-status` file must name that exact `REVIEW_HEAD` and the workflow's+`REVIEW_STATUS=clean`, or `optional-inconclusive` when all configured reviewers+are optional and unavailable. The latter records an attempted head, never a+clean reviewer verdict. The outside operator remains responsible for satisfying+its configured review policy; admission is coordination, not CI certification.++Write the acquisition request to a private JSON file (mode `0600`). For example:++```json+{+ "action": "acquire",+ "appId": "example-app",+ "worktreePath": "/example/repository-worktree",+ "prUrl": "https://github.com/example/repo/pull/7",+ "headSha": "1111111111111111111111111111111111111111",+ "baseSha": "2222222222222222222222222222222222222222"+}+```++```bash+node <portos-root>/scripts/portos-api.js post /api/cos/merge-admission/external @admission-target.json+```++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. 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;+different repositories remain independent.++Only `admitted: true` grants a lease. Retain its opaque `token` privately. A+repeat acquire by the same credential and run secret for the unchanged target+returns the same token without extending its deadline. Check and release take+no caller-selected target:++```json+{"action":"check","token":"<lease UUID>"}+```++```json+{"action":"release","token":"<lease UUID>","outcome":"merged"}+```++Use the same CLI endpoint and secret for both. Inside admission, perform the+final live PR/required-check read and confirm both the recorded head and base;+`check` also revalidates the stored target. If either SHA changed, release with+`resync`, repeat the relevant validation outside the lease, then acquire again.+Merge with `gh pr merge --match-head-commit <CI-verified-head>` and the repository's+chosen merge method; never use `--delete-branch`, `--admin` or deferred auto-merge.+Read the remote PR back and require `MERGED` at the expected head. Release with+`merged`, or `leave-open` when no merge occurred, and require `released: true`+before any cleanup. Release remains available to the same owner after a merge+or checkout change. Use the supported checkout preservation/retirement service+for cleanup; admission itself never mutates a checkout or Git ref.++A timeout, failed persistence or uncertain response is not proof of release.+Preserve the checkout/ref and handle, resolve the actual outcome, and report a+blocker if it cannot be established. Do not edit the CoS state file, manufacture+a running parent, or borrow another owner's token. After expiry, an old holder+must reacquire and repeat final live checks; its old token cannot release a+successor's lease.diff --git a/scripts/portos-api.js b/scripts/portos-api.jsindex c3575a962e..f25638be3d 100644--- a/scripts/portos-api.js+++ b/scripts/portos-api.js@@ -175,6 +175,10 @@ export const main = async (argv = process.argv.slice(2), env = process.env) => {const body = await resolveBody(parsed.body);const headers = { Accept: 'application/json' };if (token) headers.Authorization = `Bearer ${token}`;+ if (parsed.path === '/api/cos/merge-admission/external' && env.PORTOS_ADMISSION_SESSION) {+ if (!/^[a-f0-9]{64}$/.test(env.PORTOS_ADMISSION_SESSION)) throw new Error('PORTOS_ADMISSION_SESSION must be 32 random bytes encoded as lowercase hex');+ headers['X-PortOS-Admission-Session'] = env.PORTOS_ADMISSION_SESSION;+ }if (body !== null) headers['Content-Type'] = 'application/json';const { status, text } = await requestApi(`${url}${parsed.path}`, { method: parsed.method, headers, body, timeoutMs: parsed.timeoutMs ?? DEFAULT_TIMEOUT_MS }).catch((error) => {diff --git a/scripts/portos-api.test.js b/scripts/portos-api.test.jsindex aa18881017..c0022503c7 100644--- a/scripts/portos-api.test.js+++ b/scripts/portos-api.test.js@@ -113,6 +113,25 @@ describe('API request lifecycle', () => {expect(vi.getTimerCount()).toBe(0);});+ it('sends the per-run secret only to external admission and rejects malformed secrets locally', async () => {+ vi.spyOn(console, 'log').mockImplementation(() => {});+ const seen = [];+ server = createServer((request, response) => {+ seen.push({ path: request.url, secret: request.headers['x-portos-admission-session'] });+ response.end('{}');+ });+ await new Promise(resolve => server.listen(0, '127.0.0.1', resolve));+ const env = { PORTOS_URL: `http://127.0.0.1:${server.address().port}`,+ PORTOS_AGENT_KEY_FILE: join(tmpdir(), 'portos-missing-key.json'), PORTOS_ADMISSION_SESSION: 'a'.repeat(64) };+ await main(['post', '/cos/merge-admission/external', '{}'], env);+ await main(['whoami'], env);+ expect(seen).toEqual([{ path: '/api/cos/merge-admission/external', secret: env.PORTOS_ADMISSION_SESSION },+ { path: '/api/auth/whoami', secret: undefined }]);+ await expect(main(['post', '/cos/merge-admission/external', '{}'], { ...env, PORTOS_ADMISSION_SESSION: 'caller-id' }))+ .rejects.toThrow('PORTOS_ADMISSION_SESSION must be');+ expect(seen).toHaveLength(2);+ });+it('reports a refusal and missing credentials without presenting it as a transport failure', async () => {const error = vi.spyOn(console, 'error').mockImplementation(() => {});server = createServer((_request, response) => {diff --git a/server/lib/hostControlRoutes.js b/server/lib/hostControlRoutes.jsindex f7b4adfa7a..98a4f7e51a 100644--- a/server/lib/hostControlRoutes.js+++ b/server/lib/hostControlRoutes.js@@ -468,6 +468,7 @@ export const HOST_CONTROL_ROUTES = Object.freeze([// CoS: queue, release or steer an agent that runs shell commands in a// worktree, or a job that runs a shell command directly.'POST /api/cos/merge-admission',+ 'POST /api/cos/merge-admission/external','POST /api/cos/merge-handoff','POST /api/cos/claim-ownership','POST /api/cos/start',diff --git a/server/routes/cosAgentRoutes.js b/server/routes/cosAgentRoutes.jsindex 60b009467f..04daa96300 100644--- a/server/routes/cosAgentRoutes.js+++ b/server/routes/cosAgentRoutes.js@@ -39,6 +39,26 @@ router.post('/merge-admission', asyncHandler(async (req, res) => {res.json(await claimMergeAdmission(input));}));+// Outside operators have no CoS agent record. A per-run secret separates+// sessions sharing the agent-key credential; only its principal-bound hash is+// persisted. Neither an agentId nor a PR's prose can select another owner.+const externalMergeAdmissionSchema = z.discriminatedUnion('action', [+ z.object({+ action: z.literal('acquire'), appId: z.string().min(1).max(200),+ worktreePath: z.string().min(1).max(4096), prUrl: z.string().url().max(2048),+ headSha: z.string().regex(/^[a-f0-9]{40}$/), baseSha: z.string().regex(/^[a-f0-9]{40}$/),+ }).strict(),+ z.object({ action: z.literal('check'), token: z.string().uuid() }).strict(),+ z.object({ action: z.literal('release'), token: z.string().uuid(),+ outcome: z.enum(['merged', 'leave-open', 'resync']) }).strict(),+]);+router.post('/merge-admission/external', asyncHandler(async (req, res) => {+ const input = validateRequest(externalMergeAdmissionSchema, req.body ?? {});+ const { externalAdmissionOwner } = await import('../services/externalAdmissionAuth.js');+ const { externalMergeAdmission } = await import('../services/cosMergeAdmission.js');+ res.json(await externalMergeAdmission(input, () => externalAdmissionOwner(req)));+}));+// A registered run hands its published, reviewed head to the server's// pending-merge coordinator instead of waiting for CI itself (#12247). The// repository, branch, checkout and policy come from the run's registration.diff --git a/server/routes/cosExternalMergeAdmission.test.js b/server/routes/cosExternalMergeAdmission.test.jsnew file mode 100644index 0000000000..00e53e128c--- /dev/null+++ b/server/routes/cosExternalMergeAdmission.test.js@@ -0,0 +1,227 @@+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';+import express from 'express';+import { mkdir, writeFile } from 'node:fs/promises';+import { join } from 'node:path';+import { mockPathsDataRoot } from '../lib/mockPathsDataRoot.js';+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';+import { execGit } from '../lib/execGit.js';+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 { 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', () => ({+ withStateLock: createFileWriteQueue(),+ loadState: async () => fixture.state,+ readMergeAdmissionStateForSafetyCheck: async () => ({ trusted: fixture.trusted, ...structuredClone(fixture.disk) }),+ saveState: async state => {+ if (fixture.failSave) throw new Error('synthetic persistence failure');+ fixture.disk = structuredClone(state); fixture.state = state;+ },+}));+vi.mock('../services/apps.js', () => ({ getAppById: async id => fixture.apps[id] ?? null }));+vi.mock('../services/github.js', () => ({ execGh: async args => {+ await fixture.beforeForge?.();+ return JSON.stringify(fixture.prs[args[args.indexOf('--repo') + 1]] ?? null);+} }));+vi.mock('../services/forgeExecOptions.js', () => ({ resolveForgeExecOptions: async cwd => ({ cwd, env: {} }) }));+vi.mock('../services/instanceIdentity.js', () => ({ loadData: async () => ({ peers: fixture.peers }) }));+vi.mock('../services/cosAgentArchive.js', () => ({}));+vi.mock('../services/cosAgentFeedback.js', () => ({}));+vi.mock('../services/cosAgentIndex.js', () => ({}));+vi.mock('../services/cosAgentLifecycle.js', () => ({}));+vi.mock('../services/cosHealthMonitor.js', () => ({}));+vi.mock('../services/agentOrchestrator.js', () => ({}));+vi.mock('../services/instances.js', () => ({ wakePeerProbe: vi.fn() }));++let app, auth, tokenA, tokenB, example, other;+const sessionA = '1'.repeat(64);+const sessionB = '2'.repeat(64);+const persist = () => { fixture.disk = structuredClone(fixture.state); };+const git = async (cwd, ...args) => (await execGit(args, cwd)).stdout.trim();+const post = (body, { token = tokenA, session = sessionA, headers = {} } = {}) => {+ let call = request(app).post('/api/cos/merge-admission/external');+ if (token) call = call.set('Authorization', `Bearer ${token}`);+ if (session) call = call.set('X-PortOS-Admission-Session', session);+ for (const [key, value] of Object.entries(headers)) call = call.set(key, value);+ return call.send(body);+};+const acquire = (repo = example, options) => post({ action: 'acquire', ...repo.input }, options);+const release = (token, options) => post({ action: 'release', token, outcome: 'leave-open' }, options);+const check = (token, options) => post({ action: 'check', token }, options);++async function makeRepository(name) {+ const repoPath = join(tempRoot, name);+ const worktreePath = join(tempRoot, `${name}-worktree`);+ await mkdir(repoPath);+ await git(repoPath, 'init', '--initial-branch=main');+ await git(repoPath, 'config', 'user.name', 'Example');+ await git(repoPath, 'config', 'user.email', '[email protected]');+ await git(repoPath, 'commit', '--allow-empty', '-m', 'Synthetic fixture');+ await git(repoPath, 'remote', 'add', 'origin', `https://github.com/example/${name}.git`);+ await git(repoPath, 'worktree', 'add', '-b', 'feature', worktreePath);+ const headSha = await git(worktreePath, 'rev-parse', 'HEAD');+ const reviewFile = await git(worktreePath, 'rev-parse', '--path-format=absolute', '--git-path', 'portos-review-status');+ const input = { appId: name, worktreePath, prUrl: `https://github.com/example/${name}/pull/7`, headSha, baseSha: headSha };+ return { repoPath, worktreePath, reviewFile, input, key: `github.com/example/${name}` };+}++beforeAll(async () => {+ await writeFile(join(tempRoot, 'settings.json'), '{}');+ await writeFile(join(tempRoot, 'auth-sessions.json'), '{"tokens":[]}');+ auth = await import('../services/auth.js');+ await auth.setPassword({ newPassword: 'synthetic-test-password' });+ tokenA = (await auth.createSession({ label: 'agent-key' })).token;+ tokenB = (await auth.createSession({ label: 'other-operator' })).token;+ example = await makeRepository('repo');+ other = await makeRepository('other');+ const { authGate, hostControlRouteGate } = await import('../services/authGate.js');+ const routes = (await import('./cosAgentRoutes.js')).default;+ app = express();+ app.use(authGate, hostControlRouteGate, express.json());+ app.use('/api/cos', routes);+ app.use(errorMiddleware);+});+afterAll(cleanup);+beforeEach(async () => {+ fixture.trusted = true; fixture.failSave = false; fixture.peers = []; fixture.beforeForge = null;+ fixture.state = { agents: {}, mergeAdmissions: {} }; persist();+ fixture.apps = {}; fixture.prs = {};+ 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 };+ await writeFile(repo.reviewFile, `REVIEW_STATUS=clean\nREVIEW_HEAD=${input.headSha}\n`);+ }+});++describe('outside merge admission through the authenticated HTTP boundary', () => {+ it('binds a real operator credential and separate run secret without creating CoS agents', async () => {+ const granted = await acquire();+ expect(granted.status).toBe(200);+ expect(granted.body).toMatchObject({ admitted: true, repository: example.key, headSha: example.input.headSha });+ const token = granted.body.token;+ expect((await acquire()).body.token).toBe(token);+ expect((await check(token)).body.admitted).toBe(true);+ expect((await check(token, { token: tokenB })).body).toMatchObject({ admitted: false, reason: 'lease-owner-mismatch' });+ expect((await release(token, { session: sessionB })).body).toMatchObject({ admitted: false, reason: 'lease-owner-mismatch' });+ expect(fixture.state.agents).toEqual({});+ expect(JSON.stringify(fixture.disk)).not.toContain(sessionA);+ // An after-merge checkout/head change does not strand the owned release.+ fixture.prs[example.key].state = 'MERGED';+ expect((await release(token)).body.released).toBe(true);+ expect(fixture.state.mergeAdmissions).toEqual({});+ });++ it('refuses anonymous/peer callers, missing secrets and identity injection before admission', async () => {+ expect((await acquire(example, { token: null })).status).toBe(401);+ expect((await acquire(example, { session: null })).status).toBe(403);+ expect((await post({ action: 'acquire', ...example.input, agentId: 'parent-example' })).status).toBe(400);+ const { derivePeerAuthToken, PEER_AUTH_HEADER, PEER_INSTANCE_HEADER } = await import('../lib/peerHttpClient.js');+ const secret = 'synthetic-pair-secret'.repeat(3);+ fixture.peers = [{ id: 'example-peer', instanceId: 'example-instance', syncSecret: secret, enabled: true }];+ const peer = await acquire(example, { token: null, headers: {+ [PEER_AUTH_HEADER]: derivePeerAuthToken(secret, 'example-instance'), [PEER_INSTANCE_HEADER]: 'example-instance',+ } });+ expect(peer.status).toBe(403);+ expect(fixture.state.mergeAdmissions).toEqual({});+ });++ it('serializes outside sessions, CoS claims and the pending sweep on one repository', async () => {+ const { claimMergeAdmission, withPendingMergeAdmission } = await import('../services/cosMergeAdmission.js');+ fixture.state.agents.parent = { id: 'parent', taskId: 'task-parent', startedAt: '2026-01-01T00:00:00Z', status: 'running',+ metadata: { sourceWorkspace: example.repoPath, claimPicksOwnBranch: true, claimBranches: ['claim/issue-99'] } };+ persist();+ const [first, second] = await Promise.all([acquire(), acquire(example, { session: sessionB })]);+ expect([first.body.admitted, second.body.admitted].sort()).toEqual([false, true]);+ expect((await acquire(other)).body.admitted).toBe(true);+ expect((await claimMergeAdmission({ agentId: 'parent', action: 'acquire' })).admitted).toBe(false);+ const merge = vi.fn();+ expect((await withPendingMergeAdmission({ host: 'github.com', fullName: 'example/repo' }, merge)).admitted).toBe(false);+ expect(merge).not.toHaveBeenCalled();+ const winner = first.body.admitted ? first : second;+ await release(winner.body.token, { session: first.body.admitted ? sessionA : sessionB });+ const cos = await claimMergeAdmission({ agentId: 'parent', action: 'acquire' });+ expect(cos.admitted).toBe(true);+ expect((await acquire()).body.admitted).toBe(false);+ await claimMergeAdmission({ agentId: 'parent', action: 'release', token: cos.token, outcome: 'leave-open' });+ await withPendingMergeAdmission({ host: 'github.com', fullName: 'example/repo' }, async () => {+ expect((await acquire()).body.admitted).toBe(false);+ });+ });++ it.each(['head', 'base', 'repository', 'review', 'owner', 'checkout'])('withholds check when the %s proof changes and retains owned release', async mode => {+ 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 === 'repository') fixture.apps.repo.repoPath = other.repoPath;+ if (mode === 'review') await writeFile(example.reviewFile, `REVIEW_STATUS=clean\nREVIEW_HEAD=${'f'.repeat(40)}\n`);+ if (mode === 'checkout') fixture.state.mergeAdmissions[example.key].target.checkoutIdentity = 'different-checkout';+ if (mode === 'owner') fixture.state.agents.parent = { id: 'parent', status: 'running', metadata: { workspacePath: example.worktreePath } };+ persist();+ expect((await check(granted.token)).body.admitted).toBe(false);+ expect((await release(granted.token)).body.released).toBe(true);+ });++ it('recovers an interrupted owner only after the bounded deadline and invalidates its token', async () => {+ const { body: first } = await acquire();+ expect((await acquire(example, { session: sessionB })).body.admitted).toBe(false);+ fixture.state.mergeAdmissions[example.key].acquiredAt = '2000-01-01T00:00:00Z'; persist();+ expect((await check(first.token)).body.reason).toBe('lease-expired');+ const { body: successor } = await acquire(example, { session: sessionB });+ expect(successor.admitted).toBe(true);+ expect(successor.token).not.toBe(first.token);+ expect((await release(first.token)).body.released).not.toBe(true);+ expect((await check(successor.token, { session: sessionB })).body.admitted).toBe(true);+ });++ it.each(['unreadable', 'stale', 'malformed', 'write'])('fails closed on %s state without granting or claiming release', async mode => {+ const { body: granted } = await acquire();+ if (mode === 'unreadable') fixture.trusted = false;+ if (mode === 'stale') fixture.disk.mergeAdmissions = {};+ if (mode === 'malformed') { fixture.state.mergeAdmissions[example.key].target = null; persist(); }+ if (mode === 'write') fixture.failSave = true;+ expect((await release(granted.token)).body.released).not.toBe(true);+ expect(fixture.state.mergeAdmissions[example.key]).toBeDefined();+ expect((await acquire(example, { session: sessionB })).body.admitted).not.toBe(true);+ });++ it('never remembers a grant whose persistence failed and rechecks revoked authority', async () => {+ fixture.failSave = true;+ expect((await acquire()).status).toBe(500);+ expect(fixture.state.mergeAdmissions).toEqual({});+ fixture.failSave = false;+ const ephemeral = (await auth.createSession({ label: 'synthetic-outside-session' })).token;+ const { body: granted } = await acquire(example, { token: ephemeral });+ expect(granted.admitted).toBe(true);+ await auth.revokeSession(ephemeral);+ expect((await check(granted.token, { token: ephemeral })).status).toBe(401);+ expect((await release(granted.token, { token: ephemeral })).status).toBe(401);+ expect(fixture.state.mergeAdmissions[example.key]).toBeDefined();+ });++ it('rechecks authority after asynchronous target proof before committing a grant', async () => {+ const ephemeral = (await auth.createSession({ label: 'synthetic-revoked-during-proof' })).token;+ fixture.beforeForge = () => auth.revokeSession(ephemeral);+ expect((await acquire(example, { token: ephemeral })).status).toBe(403);+ expect(fixture.state.mergeAdmissions).toEqual({});+ });++ it('preserves genuine local authority with auth off and refuses proxy/remote reachability', async () => {+ await auth.clearPassword({ currentPassword: 'synthetic-test-password' });+ try {+ expect((await acquire(example, { token: null, headers: { [DEV_PROXY_CLIENT_ADDRESS_HEADER]: '192.0.2.10' } })).status).toBe(403);+ const { body: granted } = await acquire(example, { token: null });+ expect(granted.admitted).toBe(true);+ expect((await release(granted.token, { token: null })).body.released).toBe(true);+ } finally {+ await auth.setPassword({ newPassword: 'synthetic-test-password' });+ tokenA = (await auth.createSession({ label: 'agent-key' })).token;+ tokenB = (await auth.createSession({ label: 'other-operator' })).token;+ }+ });+});diff --git a/server/services/cosMergeAdmission.js b/server/services/cosMergeAdmission.jsindex d0923d52f4..fcddd05fb4 100644--- a/server/services/cosMergeAdmission.js+++ b/server/services/cosMergeAdmission.js@@ -36,12 +36,17 @@ const ownerPath = (agent) => agent?.metadata?.sourceWorkspace || agent?.sourceWoconst binding = (agent) => ({ agentId: agent.id, startedAt: agent.startedAt, taskId: agent.taskId });const sameAgent = (lease, agent) => agent?.id === lease.agentId && agent?.startedAt === lease.startedAt&& agent?.taskId === lease.taskId;+const validExternalMergeTarget = (target) => isPlainObject(target)+ && ['appId', 'repoPath', 'worktreePath', 'gitDir', 'commonDir', 'checkoutIdentity', 'branch', 'prUrl'].every(key =>+ typeof target[key] === 'string' && target[key].length > 0)+ && /^[a-f0-9]{40}$/.test(target.headSha || '') && /^[a-f0-9]{40}$/.test(target.baseSha || '');const validLease = (lease, repository) => isPlainObject(lease) && lease.repository === repository&& typeof lease.token === 'string' && lease.token.length > 0 && Number.isFinite(Date.parse(lease.acquiredAt))&& (lease.kind === 'agent'? typeof lease.agentId === 'string' && typeof lease.startedAt === 'string' && typeof lease.taskId === 'string'- : lease.kind === 'sweep' && typeof lease.serverOwner === 'string' && Number.isInteger(lease.pid) && lease.pid > 0);-const expired = (lease) => lease.kind === 'agent' && Date.now() - Date.parse(lease.acquiredAt) >= AGENT_LEASE_MAX_HOLD_MS;+ : lease.kind === 'external' ? /^[a-f0-9]{64}$/.test(lease.externalOwner || '') && validExternalMergeTarget(lease.target)+ : lease.kind === 'sweep' && typeof lease.serverOwner === 'string' && Number.isInteger(lease.pid) && lease.pid > 0);+const expired = (lease) => ['agent', 'external'].includes(lease.kind) && Date.now() - Date.parse(lease.acquiredAt) >= AGENT_LEASE_MAX_HOLD_MS;// A settled transaction is logged only at or above this duration; a deadline,// pending or failed one always is. See docs/TROUBLESHOOTING.md for the fields.@@ -152,6 +157,9 @@ async function inactive(lease, state) {catch (err) { return err.code === 'ESRCH'; }}if (expired(lease)) return true;+ // Outside sessions have no CoS lifecycle record. Only the same bounded hold+ // deadline can recover an interrupted session, including across restarts.+ if (lease.kind === 'external') return false;let owner = state.agents[lease.agentId];if (!owner) {const { readAgentRecordOrUnreadable } = await import('./cosAgentLifecycle.js');@@ -473,6 +481,50 @@ export async function claimMergeAdmission({ agentId, action, token, outcome }) {}, ['acquire', 'check', 'release'].includes(action) ? action : 'unknown');}+/** A verified operator session owns only the target validated by the server. */+export async function externalMergeAdmission(input, resolveOwner) {+ return transaction(async (state, save, measure) => {+ const externalOwner = await resolveOwner();+ if (!/^[a-f0-9]{64}$/.test(externalOwner || '')) return refuse('external-owner-unverified');+ // Validate the whole map before looking up an opaque handle: corruption is+ // never evidence that a competing owner disappeared.+ if (Object.entries(state.mergeAdmissions).some(([key, held]) => !validLease(held, key))) {+ return refuse('lease-unreadable');+ }+ const { action, token, outcome } = input;+ const owned = Object.values(state.mergeAdmissions).find(held => held.kind === 'external'+ && held.externalOwner === externalOwner && held.token === token);+ if (action !== 'acquire' && !owned) return refuse('lease-owner-mismatch');+ // Release remains possible after a merge or a changed/deleted checkout.+ if (action === 'release') {+ if (!MERGE_ADMISSION_OUTCOMES.includes(outcome)) return refuse('outcome-required');+ delete state.mergeAdmissions[owned.repository];+ await save(state);+ return { admitted: false, released: true, outcome };+ }+ if (action !== 'acquire' && action !== 'check') return refuse('action-invalid');+ if (owned && expired(owned)) return refuse('lease-expired');+ const { inspectExternalMergeTarget } = await import('./externalMergeTarget.js');+ const proof = await measure('origin', () => inspectExternalMergeTarget(+ action === 'acquire' ? input : owned.target, Object.values(state.agents)));+ if (proof.reason) return refuse(proof.reason);+ if (await resolveOwner() !== externalOwner) return refuse('external-owner-changed');+ if (owned && expired(owned)) return refuse('lease-expired');+ const { repository, target } = proof;+ if (owned && (repository !== owned.repository || JSON.stringify(target) !== JSON.stringify(owned.target))) {+ return refuse('lease-target-changed');+ }+ if (action === 'check') return { admitted: true, token, repository, headSha: target.headSha, baseSha: target.baseSha };+ const held = state.mergeAdmissions[repository];+ if (held?.kind === 'external' && held.externalOwner === externalOwner && !expired(held)) {+ if (JSON.stringify(held.target) !== JSON.stringify(target)) return refuse('lease-target-changed');+ return { admitted: true, token: held.token, repository, headSha: target.headSha, baseSha: target.baseSha };+ }+ const admission = await admit(state, save, repository, { kind: 'external', externalOwner, target }, measure);+ return admission.admitted ? { ...admission, headSha: target.headSha, baseSha: target.baseSha } : admission;+ }, ['acquire', 'check', 'release'].includes(input.action) ? `external-${input.action}` : 'unknown');+}+/** A sweep holds admission only around its final read/assessment/merge attempt. */export async function withPendingMergeAdmission(origin, work) {const repository = repositoryKey(origin);diff --git a/server/services/cosMergeHandoff.js b/server/services/cosMergeHandoff.jsindex 621bd68159..714df07e8c 100644--- a/server/services/cosMergeHandoff.js+++ b/server/services/cosMergeHandoff.js@@ -11,7 +11,7 @@*/import { randomUUID } from 'node:crypto';import { followUpRoster } from './mergeFollowUpPolicy.js';-import { readFile } from 'node:fs/promises';+import { readReviewEvidence } from './mergeReviewEvidence.js';import { resolve } from 'node:path';import { execGh } from './github.js';import { resolveForgeExecOptions } from './forgeExecOptions.js';@@ -55,24 +55,6 @@ async function checkoutAtHead(workspace, branch, head, repository, repositoryKeyreturn ref?.stdout?.trim() === branch && sha?.stdout?.trim().toLowerCase() === head;}-// The worktree-private status the review phase writes: `REVIEW_STATUS=<verdict>`-// plus `REVIEW_HEAD=<sha>`, the commit its final round reviewed. status null =-// no file (no local reviewers ran); 'unreadable' covers an unreadable or empty file.-async function readReviewEvidence(workspace) {- const gitPath = await execGit(['rev-parse', '--git-path', 'portos-review-status'], workspace).catch(() => null);- const relative = gitPath?.stdout?.trim();- if (!relative) return { status: 'unreadable', head: null };- const content = await readFile(resolve(workspace, relative), 'utf-8').catch((err) => (err.code === 'ENOENT' ? null : undefined));- if (content === null) return { status: null, head: null };- const values = (pattern) => [...String(content ?? '').matchAll(pattern)].map((m) => m[1].trim());- const statuses = values(/^REVIEW_STATUS=(.*)$/gm);- const heads = values(/^REVIEW_HEAD=(.*)$/gm);- return {- status: statuses.length === 1 ? statuses[0] : 'unreadable',- head: heads.length === 1 ? heads[0].toLowerCase() : null,- };-}-// A clean verdict counts only for the head it reviewed; merge-on-green runs no// reviewers, so there only a recorded block or unreadable status refuses. When// every local reviewer is optional the in-session merge treats them asdiff --git a/server/services/externalAdmissionAuth.js b/server/services/externalAdmissionAuth.jsnew file mode 100644index 0000000000..3ab37e5c6a--- /dev/null+++ b/server/services/externalAdmissionAuth.js@@ -0,0 +1,23 @@+import { createHash } from 'node:crypto';+import { assertHostControl } from './authGate.js';+import { isAuthEnabled, verifyRequestSessionIdentity } from './auth.js';+import { ServerError } from '../lib/errorHandler.js';++/** Authority is reverified on each request; the supplied secret is not authority. */+export async function externalAdmissionOwner(req) {+ assertHostControl(req);+ const enabled = await isAuthEnabled();+ const identity = await verifyRequestSessionIdentity(req);+ // Preserve the existing genuine-local operator boundary on password-free+ // installs. assertHostControl has already refused remote/relay callers.+ const principal = enabled === req.portosAuthContext?.enabled+ ? enabled ? identity?.sessionId && `session:${identity.sessionId}` : 'local-operator'+ : null;+ const secret = req.headers?.['x-portos-admission-session'];+ if (!principal || typeof secret !== 'string' || !/^[a-f0-9]{64}$/.test(secret)) {+ throw new ServerError('A current operator session and a per-run admission secret are required.', {+ status: 403, code: 'EXTERNAL_ADMISSION_SESSION_REQUIRED',+ });+ }+ return createHash('sha256').update(JSON.stringify([principal, secret])).digest('hex');+}diff --git a/server/services/externalMergeTarget.js b/server/services/externalMergeTarget.jsnew file mode 100644index 0000000000..64986d1ce2--- /dev/null+++ b/server/services/externalMergeTarget.js@@ -0,0 +1,88 @@+/** Read-only proof for an outside operator's linked checkout and reviewed PR. */+import { readFile, realpath, stat } from 'node:fs/promises';+import { isAbsolute, join, resolve } from 'node:path';+import { execGit } from '../lib/execGit.js';+import { getOriginInfo } from '../lib/gitRemote.js';+import { parsePullRequestUrl, detectForgeCli } from '../lib/gitForge.js';+import { safeJSONParse } from '../lib/jsonIo.js';+import { claimCheckoutOwnerReason } from '../lib/claimContinuation.js';+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();++export async function inspectExternalMergeTarget(input, agents) {+ const [{ getAppById }, { repositoryKey }] = await Promise.all([import('./apps.js'), import('./cosMergeAdmission.js')]);+ const app = await getAppById(input.appId).catch(() => null);+ const [repoPath, worktreePath] = await Promise.all([canonical(app?.repoPath), canonical(input.worktreePath)]);+ if (app?.id !== input.appId || !repoPath || !worktreePath || repoPath === worktreePath) return refused('external-checkout-unverified');+ const pr = parsePullRequestUrl(input.prUrl);+ if (!pr || detectForgeCli(pr.host) !== 'gh') return refused('external-forge-unsupported');+ const repository = repositoryKey({ host: pr.host, fullName: `${pr.owner}/${pr.repo}` });+ const [sourceOrigin, checkoutOrigin, top, sourceCommon, checkoutCommon, directory, branch, head] = await Promise.all([+ getOriginInfo(repoPath).catch(() => null), getOriginInfo(worktreePath).catch(() => null),+ gitValue(worktreePath, ['rev-parse', '--show-toplevel']),+ gitValue(repoPath, ['rev-parse', '--path-format=absolute', '--git-common-dir']),+ gitValue(worktreePath, ['rev-parse', '--path-format=absolute', '--git-common-dir']),+ gitValue(worktreePath, ['rev-parse', '--absolute-git-dir']),+ gitValue(worktreePath, ['symbolic-ref', '--quiet', '--short', 'HEAD']),+ gitValue(worktreePath, ['rev-parse', '--verify', 'HEAD^{commit}']),+ ]);+ if (!repository || repositoryKey(sourceOrigin) !== repository || repositoryKey(checkoutOrigin) !== repository) {+ return refused('external-repository-changed');+ }+ const [commonDir, otherCommon, gitDir, root] = await Promise.all([+ canonical(sourceCommon), canonical(checkoutCommon), canonical(directory), canonical(top),+ ]);+ if (!commonDir || commonDir !== otherCommon || !gitDir || gitDir === commonDir || root !== worktreePath+ || !branch || head !== input.headSha) return refused('external-checkout-unverified');+ // The Git registration must point back to this checkout, not a copied .git+ // file borrowing another worktree's private evidence. Relative worktree+ // registrations resolve their backlink from the private Git directory.+ const backlink = await readFile(join(gitDir, 'gitdir'), 'utf8').catch(() => null);+ const [pointer, registeredPointer] = await Promise.all([canonical(join(worktreePath, '.git')),+ backlink?.trim() ? canonical(resolve(gitDir, backlink.trim())) : null]);+ if (!pointer || pointer !== registeredPointer) return refused('external-checkout-unverified');+ const identity = await stat(gitDir).catch(() => null);+ const locked = await stat(join(gitDir, 'locked')).then(() => true, error => error.code !== 'ENOENT');+ if (!identity?.isDirectory() || locked) return refused('external-checkout-unverified');+ // CoS registrations may retain a symlink spelling (for example a platform's+ // temp-directory alias); compare their actual paths with this actual checkout.+ const owners = await Promise.all(agents.map(async agent => {+ if (!agent || !['running', 'paused'].includes(agent.status)) return agent;+ const workspace = agent.workspacePath || agent.metadata?.workspacePath;+ const source = agent.sourceWorkspace || agent.metadata?.sourceWorkspace;+ return { ...agent, workspacePath: await canonical(workspace) || workspace,+ sourceWorkspace: await canonical(source) || source };+ }));+ const ownerReason = claimCheckoutOwnerReason({ branchName: branch, holderPath: worktreePath, sourceWorkspace: repoPath, agents: owners });+ if (ownerReason) return refused(ownerReason);+ const { checkoutRetirementFenceReason } = await import('./cosClaimOwnershipState.js');+ const retirement = checkoutRetirementFenceReason({ repoPath: app.repoPath, branch, path: input.worktreePath })+ || checkoutRetirementFenceReason({ repoPath, branch, path: worktreePath });+ if (retirement) return refused(retirement);++ const review = await readReviewEvidence(worktreePath);+ // The outside operator's worktree-private receipt is local workflow evidence,+ // never a PR comment. Optional-inconclusive records an attempted head, not a+ // successful review; the operator still owns its configured review policy.+ if (review.head !== head || !['clean', 'optional-inconclusive'].includes(review.status)) {+ return refused('review-evidence-incomplete');+ }+ 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'],+ 10000, options).catch(() => null);+ const live = safeJSONParse(raw, null);+ const actual = parsePullRequestUrl(live?.url);+ if (!actual || 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 || live.baseRefName === branch) {+ return refused('external-pr-changed');+ }+ return { repository, target: { appId: app.id, repoPath, worktreePath, gitDir, commonDir,+ checkoutIdentity: `${identity.dev}:${identity.ino}`, branch, prUrl: live.url, headSha: head, baseSha: live.baseRefOid } };+}diff --git a/server/services/mergeReviewEvidence.js b/server/services/mergeReviewEvidence.jsnew file mode 100644index 0000000000..79d38742ff--- /dev/null+++ b/server/services/mergeReviewEvidence.js@@ -0,0 +1,22 @@+import { readFile } from 'node:fs/promises';+import { resolve } from 'node:path';+import { execGit } from '../lib/execGit.js';++// The worktree-private status the review phase writes: `REVIEW_STATUS=<verdict>`+// plus `REVIEW_HEAD=<sha>`, the commit its final round reviewed. status null =+// no file (no local reviewers ran); 'unreadable' covers an unreadable or empty file.+export async function readReviewEvidence(workspace) {+ const gitPath = await execGit(['rev-parse', '--git-path', 'portos-review-status'], workspace).catch(() => null);+ const relative = gitPath?.stdout?.trim();+ if (!relative) return { status: 'unreadable', head: null };+ const content = await readFile(resolve(workspace, relative), 'utf-8').catch((err) => (err.code === 'ENOENT' ? null : undefined));+ if (content === null) return { status: null, head: null };+ const values = (pattern) => [...String(content ?? '').matchAll(pattern)].map((m) => m[1].trim());+ const statuses = values(/^REVIEW_STATUS=(.*)$/gm);+ const heads = values(/^REVIEW_HEAD=(.*)$/gm);+ return {+ status: statuses.length === 1 ? statuses[0] : 'unreadable',+ head: heads.length === 1 ? heads[0].toLowerCase() : null,+ };+}+