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(agents): validate PortOS before server-owned PR publication

Adam Eivy8e41732131e7
diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.js
index 3329e68ccd..b53eca7251 100644
--- a/server/services/agentWorktreeCleanup.js
+++ b/server/services/agentWorktreeCleanup.js
@@ -12,6 +12,7 @@
*/
import { existsSync } from 'fs';
+import { PORTOS_APP_ID } from '../lib/appIdentity.js';
import { join } from 'path';
import { emitLog } from './cosEvents.js';
import { addTask, forceSpawnTask, getAgents, updateTask } from './cos.js';
@@ -45,6 +46,10 @@ import { DEFAULT_REVIEWER, DEFAULT_REVIEWERS, DEFAULT_REVIEW_STOP_MODE, MODEL_SE
// already merged). Sanctioned by the Security Model's re-entrancy-guard carve-out:
// this is one actor's duplicate in-flight operation, not two competing humans.
const inFlightCleanups = new Map();
+// Fail closed even when the agent store cannot persist the hold. Normally the
+// persisted metadata owns recovery across restarts; this covers sibling cleanup
+// callbacks in the process where that write failed.
+const publicationHolds = new Map();
/**
@@ -121,6 +126,7 @@ async function auditRepoState(agentId, success, originalTask, warnings) {
// fields and has no use for the run's whole output.txt.
const { getAgentRecord } = await import('./cos.js');
const agentState = await getAgentRecord(agentId).catch(() => null);
+ if (publicationHolds.has(agentId) || ['running', 'blocked'].includes(agentState?.metadata?.publicationValidation?.status)) return;
await verifyAgentRepoState({
agentId,
task: originalTask,
@@ -180,6 +186,7 @@ async function worktreeCleanupContext(agentId, options) {
isWorktree: true, agentId, sourceWorkspace, worktreeBranch,
discardWorktree: isTruthyMeta(normalized.originalTask?.metadata?.discardWorktree),
worktreePath: metadata.workspacePath || join(PATHS.worktrees, agentId),
+ publicationValidation: publicationHolds.get(agentId) || metadata.publicationValidation,
warnings: [],
};
}
@@ -206,6 +213,9 @@ async function probeWorktreePr(context, success) {
async function runCleanupAgentWorktree(agentId, success, options = {}) {
const context = await worktreeCleanupContext(agentId, options);
+ if (['running', 'blocked'].includes(context.publicationValidation?.status)) {
+ return [`Publication validation ${context.publicationValidation.status} for ${context.worktreeBranch}; worktree preserved at ${context.worktreePath}. Resume the task after resolving the validation outcome.`];
+ }
const verdict = await probeWorktreePr(context, success);
const disposition = resolveWorktreeDisposition({ ...context, success, prClaimVerdict: verdict });
reportWorktreeDisposition(context, disposition, verdict);
@@ -283,6 +293,27 @@ async function openWorktreePullRequest(context) {
const { agentId, sourceWorkspace, worktreeBranch, worktreePath, warnings, description, agentOutput } = context;
emitLog('info', `🌳 Opening PR for worktree agent ${agentId} branch ${worktreeBranch}`, { agentId, branchName: worktreeBranch });
+ if (context.originalTask?.metadata?.app === PORTOS_APP_ID) {
+ const { updateAgent } = await import('./cos.js');
+ try {
+ publicationHolds.set(agentId, { status: 'running' });
+ await updateAgent(agentId, { metadata: { publicationValidation: { status: 'running', startedAt: new Date().toISOString() } } });
+ const { validatePublication } = await import('./publicationValidation.js');
+ const validation = await validatePublication(context);
+ publicationHolds.set(agentId, validation);
+ await updateAgent(agentId, { metadata: { publicationValidation: validation } });
+ if (validation.status !== 'passed') {
+ warnings.push(`Publication validation blocked for ${worktreeBranch}: ${validation.reason}. Worktree preserved at ${worktreePath}; resolve validation before resuming the task.`);
+ return warnings;
+ }
+ publicationHolds.delete(agentId);
+ } catch (error) {
+ publicationHolds.set(agentId, { status: 'blocked', reason: 'recording-failed' });
+ warnings.push(`Publication validation could not be recorded for ${worktreeBranch}: ${error.message}. Worktree preserved at ${worktreePath}.`);
+ return warnings;
+ }
+ }
+
const [pushResult, branchInfo] = await Promise.all([
git.push(worktreePath, worktreeBranch).then(() => true).catch(err => {
emitLog('warn', `🌳 Failed to push worktree branch ${worktreeBranch}: ${err.message}`, { agentId });
diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.js
index 868a99b1db..48d93eca57 100644
--- a/server/services/cleanupAgentWorktree.test.js
+++ b/server/services/cleanupAgentWorktree.test.js
@@ -1,5 +1,7 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { cosEvents } from './cosEvents.js';
+vi.mock('./publicationValidation.js', () => ({ validatePublication: vi.fn() }));
+import { validatePublication } from './publicationValidation.js';
// --- Mock every dependency agentWorktreeCleanup.js pulls in transitively ---
@@ -239,7 +241,7 @@ import { existsSync as existsSyncMock } from 'fs';
// They used to be pulled through the `subAgentSpawner.js` barrel, which was
// retired in #3450.
import { cleanupAgentWorktree, resolveWorktreeDisposition, spawnMergeRecoveryTask, spawnReviewLoopFollowUp, resolveResumePointer, resolveTaskResumePatch, recordTaskResumePointer, releaseRetryHold, resumePointerMetadata } from './agentWorktreeCleanup.js';
-import { getAgent, getAgentRecord, getAgents, getTaskById, addTask, forceSpawnTask, updateTask } from './cos.js';
+import { getAgent, getAgentRecord, getAgents, getTaskById, addTask, forceSpawnTask, updateTask, updateAgent } from './cos.js';
import { listWorktrees, removeWorktree } from './worktreeManager.js';
import { PATHS } from '../lib/fileUtils.js';
import * as git from './git.js';
@@ -261,6 +263,47 @@ function mockWorktreeAgent(overrides = {}) {
}
describe('cleanupAgentWorktree - PR-creation path', () => {
+ it('publishes only after PortOS validation succeeds and persists that distinct outcome', async () => {
+ validatePublication.mockResolvedValue({ status: 'passed', head: 'verified-head' });
+ git.push.mockImplementation(async () => {
+ expect(updateAgent).toHaveBeenLastCalledWith('validated-publication', { metadata: { publicationValidation: { status: 'passed', head: 'verified-head' } } });
+ });
+ git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/1' });
+ await cleanupAgentWorktree('validated-publication', true, {
+ prCreation: 'always', prCompletion: 'leave-open', originalTask: { metadata: { app: 'portos-default' } },
+ });
+ expect(git.push).toHaveBeenCalledOnce();
+ expect(git.createPR).toHaveBeenCalledOnce();
+ git.push.mockReset();
+ });
+
+ it('preserves work in sibling cleanup when recording validation cannot start', async () => {
+ updateAgent.mockRejectedValueOnce(new Error('agent store unavailable'));
+ const task = { metadata: { app: 'portos-default' } };
+ const warnings = await cleanupAgentWorktree('unrecordable-publication', true, { prCreation: 'always', originalTask: task });
+ expect(warnings.join(' ')).toContain('could not be recorded');
+ await cleanupAgentWorktree('unrecordable-publication', true, { originalTask: { metadata: { discardWorktree: true } } });
+ expect(git.push).not.toHaveBeenCalled();
+ expect(removeWorktree).not.toHaveBeenCalled();
+ });
+
+ it('preserves a blocked publication across later cleanup attempts without pushing or removing work', async () => {
+ getAgent.mockResolvedValue(mockWorktreeAgent());
+ validatePublication.mockResolvedValue({ status: 'blocked', reason: 'pregate-nonzero', exitCode: 1 });
+ const warnings = await cleanupAgentWorktree('blocked-publication', true, {
+ prCreation: 'always', originalTask: { metadata: { app: 'portos-default' } },
+ });
+ expect(warnings.join(' ')).toContain('pregate-nonzero');
+ expect(updateAgent).toHaveBeenLastCalledWith('blocked-publication', { metadata: { publicationValidation: expect.objectContaining({ status: 'blocked' }) } });
+ expect(git.push).not.toHaveBeenCalled();
+ expect(git.createPR).not.toHaveBeenCalled();
+ expect(removeWorktree).not.toHaveBeenCalled();
+ getAgent.mockResolvedValue(mockWorktreeAgent({ publicationValidation: { status: 'blocked', reason: 'pregate-nonzero' } }));
+ await cleanupAgentWorktree('blocked-publication', true, { originalTask: { metadata: { discardWorktree: true } } });
+ expect(removeWorktree).not.toHaveBeenCalled();
+ expect(validatePublication).toHaveBeenCalledTimes(1);
+ });
+
beforeEach(() => {
vi.clearAllMocks();
queuePendingMergeMock.mockResolvedValue(false);
diff --git a/server/services/publicationValidation.js b/server/services/publicationValidation.js
new file mode 100644
index 0000000000..1e32af0188
--- /dev/null
+++ b/server/services/publicationValidation.js
@@ -0,0 +1,42 @@
+/** Fixed PortOS-only prepublication contract; never guesses commands for other apps. */
+import { realpath, access } from 'node:fs/promises';
+import { join } from 'node:path';
+import { PORTOS_APP_ID } from '../lib/appIdentity.js';
+import { execGit } from '../lib/execGit.js';
+import { bufferedSpawn } from '../lib/bufferedSpawn.js';
+import { doneSentinelCandidateNames } from '../lib/agentSentinel.js';
+import { classifyWorktreeDirt } from './worktreeManager.js';
+
+export async function validatePublication(context, deps = {}) {
+ if (context.originalTask?.metadata?.app !== PORTOS_APP_ID) return { status: 'not-required' };
+ const outcome = (reason, details = {}) => ({ status: 'blocked', reason, ...details, checkedAt: new Date().toISOString() });
+ const git = deps.execGit || execGit;
+ const run = deps.run || bufferedSpawn;
+ let head;
+ try {
+ const getApp = deps.getApp || (await import('./apps.js')).getAppById;
+ const app = await getApp(PORTOS_APP_ID);
+ if (!app?.repoPath || await realpath(app.repoPath) !== await realpath(context.sourceWorkspace)) return outcome('source-mismatch');
+ await access(join(context.worktreePath, 'scripts/pregate.js'));
+ const read = async args => (await git(args, context.worktreePath)).stdout;
+ const clean = async () => classifyWorktreeDirt(await read(['status', '--porcelain']), {
+ ignoredPaths: doneSentinelCandidateNames(context.agentId),
+ }).clean;
+ head = (await read(['rev-parse', 'HEAD'])).trim();
+ if (!await clean()) return outcome('uncommitted-work', { head });
+ const result = await run(process.execPath, ['scripts/pregate.js'], {
+ cwd: context.worktreePath, shell: false, timeoutMs: 30 * 60_000,
+ });
+ const details = { head, exitCode: result.code, signal: result.signal || null,
+ outputTail: `${result.stdout || ''}\n${result.stderr || ''}`.slice(-4000) };
+ if (result.timedOut) return outcome('timeout', details);
+ if (result.error || result.signal || result.code === -1) return outcome('execution-failed', details);
+ // A nonzero pregate may mean lint, setup or a test failed. Do not label it a test failure.
+ if (!result.success) return outcome('pregate-nonzero', details);
+ if ((await read(['rev-parse', 'HEAD'])).trim() !== head) return outcome('head-changed', details);
+ if (!await clean()) return outcome('worktree-changed', details);
+ return { status: 'passed', ...details, checkedAt: new Date().toISOString() };
+ } catch (error) {
+ return outcome('setup-failed', { head: head || null, error: String(error?.message || error).slice(0, 500) });
+ }
+}
diff --git a/server/services/publicationValidation.test.js b/server/services/publicationValidation.test.js
new file mode 100644
index 0000000000..6e3a9a1804
--- /dev/null
+++ b/server/services/publicationValidation.test.js
@@ -0,0 +1,62 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { mkdir, writeFile, rm } from 'node:fs/promises';
+import { join } from 'node:path';
+import { makeGitSandbox } from '../lib/gitTestRepo.js';
+import { execGit } from '../lib/execGit.js';
+import { validatePublication } from './publicationValidation.js';
+
+let scratch;
+afterEach(async () => { if (scratch) await rm(scratch, { recursive: true, force: true }); });
+async function fixture(body = 'process.exit(0)') {
+ const { repo, scratch: root } = await makeGitSandbox();
+ scratch = root;
+ await mkdir(join(repo, 'scripts'), { recursive: true });
+ await writeFile(join(repo, 'scripts/pregate.js'), body);
+ await execGit(['add', '.'], repo);
+ await execGit(['commit', '-m', 'fixture validator'], repo);
+ return { context: { agentId: 'agent-check', worktreePath: repo, sourceWorkspace: repo,
+ originalTask: { metadata: { app: 'portos-default' } } }, deps: { getApp: async () => ({ repoPath: repo }) } };
+}
+
+describe('PortOS publication validation', () => {
+ it('executes the fixed script and accepts a clean unchanged HEAD with its completion sentinel', async () => {
+ const { context, deps } = await fixture();
+ await writeFile(join(context.worktreePath, '.agent-done-agent-check'), 'done');
+ expect(await validatePublication(context, deps)).toMatchObject({ status: 'passed', exitCode: 0 });
+ await writeFile(join(context.worktreePath, 'untracked-work.txt'), 'preserve this');
+ expect(await validatePublication(context, deps)).toMatchObject({ status: 'blocked', reason: 'uncommitted-work' });
+ });
+ it('preserves validation nonzero as a gate result rather than asserting tests failed', async () => {
+ const { context, deps } = await fixture('console.error("lint or setup failure"); process.exit(2)');
+ expect(await validatePublication(context, deps)).toMatchObject({ status: 'blocked', reason: 'pregate-nonzero', exitCode: 2 });
+ });
+ it('blocks validator-created work even when the script reports success', async () => {
+ const { context, deps } = await fixture('require("node:fs").writeFileSync("generated.txt", "changed")');
+ expect(await validatePublication(context, deps)).toMatchObject({ status: 'blocked', reason: 'worktree-changed' });
+ });
+ it('blocks a HEAD changed during validation', async () => {
+ const { context, deps } = await fixture();
+ deps.run = async () => {
+ await execGit(['commit', '--allow-empty', '-m', 'concurrent change'], context.worktreePath);
+ return { success: true, code: 0 };
+ };
+ expect(await validatePublication(context, deps)).toMatchObject({ status: 'blocked', reason: 'head-changed' });
+ });
+ it.each([
+ [{ success: false, timedOut: true, code: -1 }, 'timeout'],
+ [{ success: false, error: new Error('spawn failed'), code: -1 }, 'execution-failed'],
+ ])('distinguishes execution failure from check failure', async (result, reason) => {
+ const { context, deps } = await fixture();
+ deps.run = vi.fn(async () => result);
+ expect(await validatePublication(context, deps)).toMatchObject({ status: 'blocked', reason });
+ expect(deps.run).toHaveBeenCalledWith(process.execPath, ['scripts/pregate.js'], expect.objectContaining({ shell: false, cwd: context.worktreePath }));
+ });
+ it('does not infer a command for other managed apps or run against a mismatched source', async () => {
+ const { context, deps } = await fixture();
+ deps.run = vi.fn();
+ expect(await validatePublication({ ...context, originalTask: { metadata: { app: 'other-app' } } }, deps)).toEqual({ status: 'not-required' });
+ deps.getApp = async () => ({ repoPath: scratch });
+ expect(await validatePublication(context, deps)).toMatchObject({ status: 'blocked', reason: 'source-mismatch' });
+ expect(deps.run).not.toHaveBeenCalled();
+ });
+});