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: admit registered detached review coordinators

[._.]/ Adam Eivy19b3b7aebda6
diff --git a/server/lib/agentRegistrationRecord.js b/server/lib/agentRegistrationRecord.js
index 6bec608dfc..eae283e2f3 100644
--- a/server/lib/agentRegistrationRecord.js
+++ b/server/lib/agentRegistrationRecord.js
@@ -285,6 +285,10 @@ export function buildAgentRegistration({
&& isTruthyMeta(task.metadata?.reviewLoopFollowUp)
&& !isTruthyMeta(task.metadata?.reviewLoopLeaveOpen)
? { url: task.metadata.reviewLoopPRUrl, branch: task.metadata.reviewLoopPRBranch,
+ ...(worktreeInfo?.detached === true && !task.metadata.forkHead ? {
+ workspacePath,
+ detached: { version: 1, headSha: worktreeInfo.headSha },
+ } : {}),
...(task.metadata.forkHead ? {
workspacePath,
fork: task.metadata.reviewLoopForkTarget ? structuredClone(task.metadata.reviewLoopForkTarget) : null,
diff --git a/server/services/cosMergeAdmission.detached.test.js b/server/services/cosMergeAdmission.detached.test.js
new file mode 100644
index 0000000000..3a5e314dac
--- /dev/null
+++ b/server/services/cosMergeAdmission.detached.test.js
@@ -0,0 +1,59 @@
+import { afterAll, expect, it, vi } from 'vitest';
+import { createFileWriteQueue } from '../lib/fileWriteQueue.js';
+import { mockPathsDataRoot, mockTestIdentity } from '../lib/mockPathsDataRoot.js';
+import { destroyGitSandbox, makeGitSandbox, SKIP_HEAVY_INTEGRATION } from '../lib/gitTestRepo.js';
+import { execGit } from '../lib/execGit.js';
+
+const f = vi.hoisted(() => ({ state: { agents: {}, mergeAdmissions: {} }, disk: null, task: null, pr: null }));
+const { makeProxy, cleanup } = mockPathsDataRoot({ prefix: 'portos-detached-admission-' });
+vi.mock('../lib/fileUtils.js', async importOriginal => makeProxy(await importOriginal()));
+vi.mock('./instanceIdentity.js', () => mockTestIdentity());
+vi.mock('./cosState.js', () => ({
+ withStateLock: createFileWriteQueue(), loadState: async () => f.state,
+ saveState: async state => { f.state = state; f.disk = structuredClone(state); },
+ readMergeAdmissionStateForSafetyCheck: async () => ({ trusted: true, ...structuredClone(f.disk) }),
+}));
+vi.mock('../lib/gitRemote.js', async importOriginal => ({ ...(await importOriginal()),
+ getOriginInfo: async () => ({ host: 'github.com', fullName: 'example/repo' }),
+}));
+vi.mock('./github.js', () => ({ execGh: async () => JSON.stringify(f.pr) }));
+vi.mock('./forgeExecOptions.js', () => ({ resolveForgeExecOptions: async cwd => ({ cwd, env: {} }) }));
+vi.mock('./cosTaskStore.js', () => ({ getTaskById: async () => f.task }));
+const { createWorktree } = await import('./worktreeManager.js');
+const { claimMergeAdmission } = await import('./cosMergeAdmission.js');
+const { buildAgentRegistration } = await import('../lib/agentRegistrationRecord.js');
+afterAll(cleanup);
+
+it.skipIf(SKIP_HEAVY_INTEGRATION)('admits a real detached default-head checkout without switching the primary branch, and refuses a moved head', async () => {
+ const sandbox = await makeGitSandbox({ origin: true, prefix: 'portos-detached-merge-' });
+ try {
+ await execGit(['push', 'origin', 'main'], sandbox.repo);
+ const head = (await execGit(['rev-parse', 'HEAD'], sandbox.repo)).stdout.trim();
+ const info = await createWorktree('agent-review', sandbox.repo, 'task-review', { existingBranch: 'main' });
+ expect(info).toMatchObject({ detached: true, headIsDefaultBranch: true, headSha: head });
+ f.task = { id: 'task-review', taskType: 'internal', status: 'in_progress', metadata: {
+ reviewLoopFollowUp: true, reviewLoopPRUrl: 'https://github.com/example/repo/pull/42',
+ reviewLoopPRBranch: 'main', reviewLoopPRNumber: 42, reviewLoopPRHost: 'github.com',
+ reviewLoopPROwner: 'example', reviewLoopPRRepo: 'repo', prCompletion: 'review-then-merge',
+ } };
+ const metadata = buildAgentRegistration({ task: f.task, provider: { id: 'test' }, modelSelection: {},
+ sourceWorkspace: sandbox.repo, workspacePath: info.worktreePath, worktreeInfo: info });
+ f.state.agents['agent-review'] = { id: 'agent-review', taskId: f.task.id, status: 'running',
+ startedAt: new Date().toISOString(), metadata };
+ f.disk = structuredClone(f.state);
+ f.pr = { url: f.task.metadata.reviewLoopPRUrl, number: 42, state: 'OPEN', headRefName: 'main',
+ headRefOid: head, isCrossRepository: false };
+ const admission = (action, token, outcome) => claimMergeAdmission({ agentId: 'agent-review', action, token, outcome });
+ const lease = await admission('acquire');
+ expect(lease).toMatchObject({ admitted: true });
+ expect(await admission('check', lease.token)).toMatchObject({ admitted: true });
+ await execGit(['-c', 'user.name=Test', '-c', '[email protected]', 'commit', '--allow-empty', '-m', 'Moved head'], info.worktreePath);
+ expect(await admission('check', lease.token)).toMatchObject({ admitted: false, retryable: false,
+ reason: 'detached-review-target-unverified' });
+ expect(await admission('release', lease.token, 'resync')).toMatchObject({ released: true });
+ expect((await execGit(['symbolic-ref', '--short', 'HEAD'], sandbox.repo)).stdout.trim()).toBe('main');
+ expect((await execGit(['rev-parse', 'HEAD'], sandbox.repo)).stdout.trim()).toBe(head);
+ } finally {
+ await destroyGitSandbox(sandbox.scratch);
+ }
+});
diff --git a/server/services/cosMergeAdmission.js b/server/services/cosMergeAdmission.js
index 29db677788..d0923d52f4 100644
--- a/server/services/cosMergeAdmission.js
+++ b/server/services/cosMergeAdmission.js
@@ -213,6 +213,14 @@ async function verifiedReviewCoordinator(agent, repository) {
if (!pr || repositoryKey({ host: pr.host, fullName: `${pr.owner}/${pr.repo}` }) !== repository
|| String(meta.reviewLoopPRNumber) !== String(pr.number)
|| meta.reviewLoopPRHost !== pr.host || meta.reviewLoopPROwner !== pr.owner || meta.reviewLoopPRRepo !== pr.repo) return false;
+ if (target.detached) {
+ if (meta.forkHead || meta.reviewLoopForkTarget || target.fork || agent.metadata.isWorktree !== true
+ || repositoryKey(await getOriginInfo(agent.metadata.workspacePath).catch(() => null)) !== repository) return false;
+ const { verifyDetachedReviewMergeTarget } = await import('./detachedReviewMergeTarget.js');
+ const headSha = await verifyDetachedReviewMergeTarget({ target,
+ workspacePath: agent.metadata.workspacePath, sourceWorkspace: agent.metadata.sourceWorkspace });
+ return headSha ? { headSha } : false;
+ }
if (!await checkoutOnBranch(agent.metadata.workspacePath, resolveTaskTargetBranch(meta), repository)) return false;
if (!meta.forkHead && !meta.reviewLoopForkTarget && !target.fork && !target.workspacePath) return true;
if (target.workspacePath !== agent.metadata.workspacePath || !agent.metadata.sourceWorkspace
@@ -343,7 +351,7 @@ export async function resolveMergeHandoffOwner(agentId) {
const { ownsClaimBranch } = await import('../lib/claimContinuation.js');
return { ...owner, owns: (branch) => ownsClaimBranch(agent, branch), workspacePath: null };
}
- if (await verifiedReviewCoordinator(agent, repository) === true) {
+ if (await verifiedReviewCoordinator(agent, repository)) {
return { ...owner, owns: (branch) => branch === meta.reviewLoopMergeTarget.branch, workspacePath: meta.workspacePath };
}
if (await verifiedWorktreeDelivery(agent, repository)) {
@@ -421,6 +429,10 @@ export async function claimMergeAdmission({ agentId, action, token, outcome }) {
return { admitted: false, reason: 'fork-review-target-unverified', retryable: false,
message: 'Leave the PR/worktree intact. Verify the live PR head, base, fork remote and upstream; old or changed targets require a fresh supported follow-up.' };
}
+ if (agent.metadata?.reviewLoopMergeTarget?.detached) {
+ return { admitted: false, reason: 'detached-review-target-unverified', retryable: false,
+ message: 'Leave the PR/worktree intact. A detached review checkout must match its registered launch head and live PR; create a fresh supported follow-up for a changed target.' };
+ }
return refuse('claim-owner-unverified');
}
if (action === 'acquire') {
diff --git a/server/services/cosMergeAdmission.reviewCoordinator.test.js b/server/services/cosMergeAdmission.reviewCoordinator.test.js
index c44e80ae44..8fd5ae467f 100644
--- a/server/services/cosMergeAdmission.reviewCoordinator.test.js
+++ b/server/services/cosMergeAdmission.reviewCoordinator.test.js
@@ -5,7 +5,7 @@ import { generateTasksMarkdown, parseTasksMarkdown } from '../lib/taskParser.js'
import { forkLocalBranch } from '../lib/forkHead.js';
import { parsePullRequestUrl } from '../lib/gitForge.js';
-const f = vi.hoisted(() => ({ state: null, disk: null, tasks: {}, branch: 'feature/fix', workspaceRepo: 'example/repo', originHost: 'github.com', row: null, head: null, upstream: null, remote: null, pushRemote: null }));
+const f = vi.hoisted(() => ({ state: null, disk: null, tasks: {}, branch: 'feature/fix', workspaceRepo: 'example/repo', originHost: 'github.com', row: null, head: null, upstream: null, remote: null, pushRemote: null, detached: false }));
vi.mock('./cosState.js', () => ({
AGENTS_DIR: '/synthetic/agents',
withStateLock: createFileWriteQueue(),
@@ -32,6 +32,7 @@ vi.mock('../lib/spawnCwd.js', async importOriginal => ({ ...(await importOrigina
vi.mock('./taskConflict.js', () => ({ detectConflicts: vi.fn() }));
vi.mock('../lib/execGit.js', () => ({ execGit: async args => {
let stdout;
+ if (args[0] === 'symbolic-ref' && f.branch === null) return { stdout: '', exitCode: 1 };
if (args[0] === 'symbolic-ref') stdout = f.branch;
if (args[0] === 'rev-parse') stdout = args.includes('--is-inside-work-tree') ? 'true' : f.head;
if (args[0] === 'remote') stdout = args.includes('--push') ? f.pushRemote : f.remote;
@@ -42,7 +43,8 @@ vi.mock('../lib/execGit.js', () => ({ execGit: async args => {
vi.mock('./git.js', () => ({ parsePullRequestUrl, isRepo: async () => true, getRepoBranches: async () => ({ baseBranch: 'main' }) }));
vi.mock('./worktreeManager.js', () => ({ removeWorktree: vi.fn(), classifyWorktreeDirt: vi.fn(),
listWorktrees: async () => [], findAdoptableWorktreeForBranch: async () => null, releaseIdleSiblingNextHolder: async () => null,
- createWorktree: vi.fn(async (_agent, _workspace, _task, options) => ({ worktreePath: '/repos/worktree', branchName: forkLocalBranch(options.existingBranch, options.forkHead) })),
+ createWorktree: vi.fn(async (_agent, _workspace, _task, options) => ({ worktreePath: '/repos/worktree', branchName: forkLocalBranch(options.existingBranch, options.forkHead),
+ ...(f.detached ? { detached: true, headSha: f.head } : {}) })),
}));
import { prepareAgentWorkspace } from './agentWorkspacePrep.js';
import { createWorktree } from './worktreeManager.js';
@@ -71,7 +73,7 @@ const persist = () => { f.disk = structuredClone(f.state); };
beforeEach(() => {
f.state = { agents: {}, mergeAdmissions: {}, stats: { agentsSpawned: 0 } };
vi.clearAllMocks();
- f.tasks = {}; f.branch = 'feature/fix'; f.workspaceRepo = 'example/repo'; f.originHost = 'github.com';
+ f.tasks = {}; f.branch = 'feature/fix'; f.workspaceRepo = 'example/repo'; f.originHost = 'github.com'; f.detached = false;
f.head = 'a'.repeat(40); f.remote = forkHead.remoteUrl; f.pushRemote = f.remote;
f.upstream = { remote: 'fork-contributor', merge: 'refs/heads/feature/fix' };
f.row = { url: 'https://github.com/example/repo/pull/42', number: 42, state: 'OPEN', headRefName: f.branch,
@@ -139,6 +141,51 @@ describe('registered review-loop merge coordinator', () => {
});
});
+describe('registered detached review checkout', () => {
+ async function detachedLaunch() {
+ f.detached = true;
+ f.row.isCrossRepository = false;
+ const task = await launch();
+ f.branch = null;
+ return task;
+ }
+
+ it('admits the registered launch head and preserves release after the checkout or PR changes', async () => {
+ await detachedLaunch();
+ const lease = await admission('acquire');
+ expect(lease).toMatchObject({ admitted: true });
+ expect(f.disk.mergeAdmissions[lease.repository].headSha).toBe(f.head);
+ expect(await admission('check', lease.token)).toMatchObject({ admitted: true });
+ f.row.headRefOid = 'b'.repeat(40);
+ expect(await admission('check', lease.token)).toMatchObject({ admitted: false, retryable: false });
+ expect(await admission('release', lease.token, { outcome: 'resync' })).toMatchObject({ released: true });
+ expect(f.disk.mergeAdmissions).toEqual({});
+ });
+
+ it.each(['unregistered', 'changed-workspace', 'changed-origin', 'attached', 'local-head', 'remote-head',
+ 'wrong-pr', 'closed', 'fork', 'leave-open', 'task-changed', 'unreadable'])('refuses %s without retrying a permanent binding failure', async mode => {
+ const task = await detachedLaunch();
+ const agent = f.state.agents['review-agent'];
+ if (mode === 'unregistered') delete agent.metadata.reviewLoopMergeTarget.detached;
+ if (mode === 'changed-workspace') agent.metadata.workspacePath = '/repos/other';
+ if (mode === 'changed-origin') f.workspaceRepo = 'example/other';
+ if (mode === 'attached') f.branch = 'feature/fix';
+ if (mode === 'local-head') f.head = 'b'.repeat(40);
+ if (mode === 'remote-head') f.row.headRefOid = 'b'.repeat(40);
+ if (mode === 'wrong-pr') f.row.url = 'https://github.com/example/repo/pull/43';
+ if (mode === 'closed') f.row.state = 'CLOSED';
+ if (mode === 'fork') f.row.isCrossRepository = true;
+ if (mode === 'leave-open') task.metadata.reviewLoopLeaveOpen = true;
+ if (mode === 'task-changed') task.metadata.reviewLoopPRBranch = 'other';
+ if (mode === 'unreadable') f.row = null;
+ persist();
+ const result = await admission('acquire', undefined, { headSha: f.head });
+ expect(result.admitted).toBe(false);
+ if (mode !== 'unregistered') expect(result).toMatchObject({ retryable: false, reason: 'detached-review-target-unverified' });
+ expect(f.disk.mergeAdmissions).toEqual({});
+ });
+});
+
describe('fork follow-up creation through workspace, registration and admission', () => {
it('admits the verified fork exact head under the base repository and excludes a same-repository coordinator', async () => {
await launch({ forkHead });
diff --git a/server/services/detachedReviewMergeTarget.js b/server/services/detachedReviewMergeTarget.js
new file mode 100644
index 0000000000..e667878cc8
--- /dev/null
+++ b/server/services/detachedReviewMergeTarget.js
@@ -0,0 +1,29 @@
+/** Admission for a review checkout PortOS detached to preserve an occupied branch. */
+import { execGit } from '../lib/execGit.js';
+import { detectForgeCli, parsePullRequestUrl } from '../lib/gitForge.js';
+import { safeJSONParse } from '../lib/jsonIo.js';
+
+/** The launch head is immutable: a moved PR needs a freshly provisioned follow-up. */
+export async function verifyDetachedReviewMergeTarget({ target, workspacePath, sourceWorkspace }) {
+ if (target.detached?.version !== 1 || !/^[a-f0-9]{40}$/i.test(target.detached.headSha || '')
+ || target.workspacePath !== workspacePath || !sourceWorkspace || sourceWorkspace === workspacePath) return null;
+ const pr = parsePullRequestUrl(target.url);
+ if (!pr || detectForgeCli(pr.host) !== 'gh') return null;
+ const [symbolic, head] = await Promise.all([
+ execGit(['symbolic-ref', '--quiet', '--short', 'HEAD'], workspacePath, { ignoreExitCode: true, timeout: 10000 }).catch(() => null),
+ execGit(['rev-parse', '--verify', 'HEAD'], workspacePath, { timeout: 10000 }).catch(() => null),
+ ]);
+ if (symbolic?.exitCode !== 1 || head?.stdout?.trim() !== target.detached.headSha) return null;
+ const [{ execGh }, { resolveForgeExecOptions }] = await Promise.all([
+ import('./github.js'), import('./forgeExecOptions.js'),
+ ]);
+ const options = await resolveForgeExecOptions(sourceWorkspace);
+ const raw = await execGh(['pr', 'view', String(pr.number), '--repo', `${pr.host}/${pr.owner}/${pr.repo}`,
+ '--json', 'url,number,state,headRefName,headRefOid,isCrossRepository'], 10000, options).catch(() => null);
+ const live = safeJSONParse(raw, null);
+ const actual = parsePullRequestUrl(live?.url);
+ if (!actual || actual.host !== pr.host || actual.owner !== pr.owner || actual.repo !== pr.repo || actual.number !== pr.number
+ || live.number !== pr.number || live.state !== 'OPEN' || live.isCrossRepository !== false
+ || live.headRefName !== target.branch || live.headRefOid !== target.detached.headSha) return null;
+ return target.detached.headSha;
+}