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
fix: isolate scanner inputs and preserve runner evidence in PRs
atomantic57d038e7e35c
diff --git a/client/src/components/cos/AgentResultLine.jsx b/client/src/components/cos/AgentResultLine.jsxindex 476f054c64..d3a05318e2 100644--- a/client/src/components/cos/AgentResultLine.jsx+++ b/client/src/components/cos/AgentResultLine.jsx@@ -57,6 +57,7 @@ export function SecurityScanEvidence({ scanner, control }) {<div className="mt-1 break-words"><div>Security scanner ({scanner.source === 'runner' ? 'runner observed' : 'agent reported'}): {control?.status || scanner.status}{control && ' (runner connection lost)'}</div>{scanner.status === 'invalid-input' && <div>Input rejected before scanner launch</div>}+ {scanner.baseline && <div>Committed baseline: {scanner.baseline.commit} · Tree: {scanner.baseline.tree}. Uncommitted files and submodules excluded; symlinks read as link text. Subsequent repairs are not certified.</div>}{scanner.preflight && <div>Input rejections: {formatCount(scanner.preflight.rejectedRequests)} · Last: {scanner.preflight.lastError.field} item {formatCount(scanner.preflight.lastError.index + 1)} — {scanner.preflight.lastError.code}</div>}<div>Model: {scanner.model ?? 'unknown'} · Effort: {scanner.effort ?? 'unknown'} · Auth: {scanner.auth}</div><div>Estimated baseline: {scanner.estimatedCostUsd == null ? 'unknown' : formatUsd(scanner.estimatedCostUsd, { maximumFractionDigits: 4 })} · Estimate cap: {scanner.maxCostUsd == null ? 'unknown' : scanner.maxCostUsd === 'unlimited' ? 'none (no estimate cap)' : formatUsd(scanner.maxCostUsd, { maximumFractionDigits: 4 })} (API-equivalent USD)</div>diff --git a/client/src/components/cos/AgentResultLine.test.jsx b/client/src/components/cos/AgentResultLine.test.jsxindex 9d081ba757..c1bc3039c1 100644--- a/client/src/components/cos/AgentResultLine.test.jsx+++ b/client/src/components/cos/AgentResultLine.test.jsx@@ -58,6 +58,15 @@ it('shows runner observations during execution without requiring an agent compleexpect(screen.queryByText('Completed successfully')).not.toBeInTheDocument();});+it('shows the committed scanner baseline separately from later audit success', () => {+ render(<AgentResultLine agent={{ result: { success: true }, metadata: { securityScan: {+ source: 'runner', status: 'completed', baseline: { commit: 'a'.repeat(40), tree: 'b'.repeat(40) },+ } } }} />);+ expect(screen.getByText(/Committed baseline:/)).toHaveTextContent('a'.repeat(40));+ expect(screen.getByText(/Committed baseline:/)).toHaveTextContent('Uncommitted files and submodules excluded');+ expect(screen.getByText(/Committed baseline:/)).toHaveTextContent('Subsequent repairs are not certified');+});+it('distinguishes explicit unlimited grants from unknown, zero and saved bounded limits', () => {const scanner = { source: 'runner', status: 'running', auth: 'chatgpt', maxCostUsd: 'unlimited', timeLimitSeconds: 'unlimited' };const view = render(<SecurityScanEvidence scanner={scanner} />);diff --git a/docs/features/self-improvement-audits.md b/docs/features/self-improvement-audits.mdindex 4689f5074d..7db4d78767 100644--- a/docs/features/self-improvement-audits.md+++ b/docs/features/self-improvement-audits.md@@ -42,6 +42,29 @@ and writes the usual quality assessment and completion sentinel. Scannercoverage and unresolved areas remain evidence to inspect, not a clean bill ofhealth for the repository.+The runner scans a private standalone snapshot of **committed HEAD**, with every+selected source and knowledge-base path mapped into that snapshot. Ordinary+remediation edits and later commits in the agent worktree cannot change the scan+target. Evidence records the exact commit and tree. Uncommitted, untracked and+ignored files are excluded; submodules are excluded without initialization, and+symlinks are read as their recorded link text. A selected input absent from the+commit or inside a submodule stops preparation before any provider launch.+Findings must be checked against current source before remediation; a completed+baseline scan does not certify later repairs.++Snapshot preparation and scanning share the runner's supervised process group,+durable reservation and Stop/recovery cleanup. A typed input rejection permits+explicit correction only before provider launch and after confirmed preparation+cleanup; other preparation failures remain terminal. New grants explicitly use ChatGPT auth and resolved model/+effort, with no PortOS estimate cap or elapsed-time deadline; provider limits+and terminal refusals still apply. Older saved grants retain their original limits.++Server-generated PR descriptions place validated runner scanner evidence before+the assistant summary. This section survives summary truncation and distinguishes+scanner completion, artifacts, cleanup and revision coverage from delivery or+quality-assessment success. Cost estimates are API-equivalent estimates, not+proof of billing or subscription consumption.+## The lanes`Mode` is the shipped default. `Isolated` marks lanes whose remediation must rundiff --git a/server/cos-runner/securityScan.js b/server/cos-runner/securityScan.jsindex 884a1330f9..c2c82d5d79 100644--- a/server/cos-runner/securityScan.js+++ b/server/cos-runner/securityScan.js@@ -51,7 +51,7 @@ async function scopePaths(cwd, values, field) {if (rel === '..' || rel.startsWith(`..${process.platform === 'win32' ? '\\' : '/'}`) || isAbsolute(rel)) {throw invalid('outside-workspace');}- return path;+ return resolve(root, value);}));}@@ -142,6 +142,8 @@ export function createSecurityScanManager({ agentsDir, getAgent, emitEvidence, tlet forceTimer;let deadline;let drainTimer;+ let owner;+ let finished = false;let invalidInput = false;try {const [paths, knowledgeBase, cli] = await Promise.all([@@ -156,12 +158,6 @@ export function createSecurityScanManager({ agentsDir, getAgent, emitEvidence, tawait writeFileGuarded(promptFile, request.prompt, { mode: 0o600 });await ensureDir(outputDir);await chmod(outputDir, 0o700);- const args = [...cli.args, 'scan', agent.workspacePath, '--mode', 'standard', '--auth', 'chatgpt', '--headless', '--json',- '--model', entry.grant.model, '--effort', entry.grant.effort,- // codex-security documents omission as no cap; 0/null are not CLI limits.- ...(typeof entry.grant.maxCostUsd === 'number' ? ['--max-cost', String(entry.grant.maxCostUsd)] : []),- '--output-dir', outputDir, '--scan-prompt-file', promptFile,- ...paths.flatMap(path => ['--path', path]), ...knowledgeBase.flatMap(path => ['--knowledge-base', path])];const env = Object.fromEntries(Object.entries(environment).filter(([key]) => ENV_KEYS.has(key)));env.CODEX_SECURITY_STATE_DIR = join(directory, 'state');env.PORTOS_SECURITY_SCAN_OWNER = randomUUID();@@ -182,10 +178,10 @@ export function createSecurityScanManager({ agentsDir, getAgent, emitEvidence, tlet logError;const logPath = join(directory, 'scan.log');const child = spawnProcess(process.execPath, [CHILD, outputDir], {- cwd: agent.workspacePath, env, detached: process.platform !== 'win32', stdio: ['ignore', 'pipe', 'pipe', 'ipc'],+ cwd: directory, env, detached: process.platform !== 'win32', stdio: ['ignore', 'pipe', 'pipe', 'ipc'],});entry.child = child;- entry.owner = { pid: child.pid, startedAt: Date.now(), marker: env.PORTOS_SECURITY_SCAN_OWNER, outputDir };+ owner = { pid: child.pid, startedAt: Date.now(), marker: env.PORTOS_SECURITY_SCAN_OWNER, outputDir };// Private ownership receipt allows restart cleanup to verify identity,// including descendants whose group leader exited. Never signal by a// persisted PID alone.@@ -198,7 +194,7 @@ export function createSecurityScanManager({ agentsDir, getAgent, emitEvidence, t// Independent of the outer agent map and of child.killed. A wrapper// may exit before descendants; the process-group escalation survives.forceTimer = setTimeout(() => {- exitCleanup = cleanupGroup(entry.owner).catch(() => false);+ exitCleanup = cleanupGroup(owner).catch(() => false);// Do not wait forever for inherited pipes or a missing close event.exitCleanup.then(() => resolveExit({ code: null, failed: true }));}, graceMs);@@ -243,8 +239,9 @@ export function createSecurityScanManager({ agentsDir, getAgent, emitEvidence, tresolveExit = resolve;child.once('error', () => resolveExit({ code: null, failed: true }));child.once('exit', (code, signal) => {+ if (finished) return;clearTimeout(deadline);- exitCleanup = cleanupGroup(entry.owner).catch(() => false);+ exitCleanup = cleanupGroup(owner).catch(() => false);// Exit can precede the last stderr refusal. Drain both streams,// bounded for a descendant holding inherited pipes open.drainTimer = setTimeout(() => resolveExit({ code, signal }), graceMs);@@ -256,15 +253,36 @@ export function createSecurityScanManager({ agentsDir, getAgent, emitEvidence, t}if (entry.stopReason) cancel();});- await atomicWrite(join(agentsDir, id, 'security-scan-process.json'), entry.owner);+ await atomicWrite(join(agentsDir, id, 'security-scan-process.json'), owner);if (!entry.stopReason) {- await new Promise((resolve, reject) => child.send({ command: cli.command, args }, err => err ? reject(err) : resolve()));+ // Preparation belongs to the same durable process-group reservation.+ // Stop/IPC loss/recovery retire Git too, before any provider launch.+ const prepared = new Promise((resolve, reject) => {+ child.once('message', message => {+ if (message.snapshotError) reject(Object.assign(new Error('Snapshot unavailable'), message.snapshotError));+ else resolve(message.snapshot);+ });+ child.send({ prepare: { source: agent.workspacePath, directory, paths, knowledgeBase } }, err => { if (err) reject(err); });+ });+ const snapshot = await Promise.race([prepared, exitPromise.then(() => { throw failure('Snapshot preparation stopped'); })]);+ entry.evidence.baseline = snapshot.baseline;+ await persist(id, entry);+ const args = [...cli.args, 'scan', snapshot.repository, '--mode', 'standard', '--auth', 'chatgpt', '--headless', '--json',+ '--model', entry.grant.model, '--effort', entry.grant.effort,+ // Omission means no cap; 0/null are not CLI limits.+ ...(typeof entry.grant.maxCostUsd === 'number' ? ['--max-cost', String(entry.grant.maxCostUsd)] : []),+ '--output-dir', outputDir, '--scan-prompt-file', promptFile,+ ...snapshot.paths.flatMap(path => ['--path', path]), ...snapshot.knowledgeBase.flatMap(path => ['--knowledge-base', path])];+ if (!entry.stopReason) {+ entry.providerLaunched = true;+ await new Promise((resolve, reject) => child.send({ command: cli.command, args, cwd: snapshot.repository }, err => err ? reject(err) : resolve()));+ }}const exit = await exitPromise;clearTimeout(deadline);// Retire a still-owned group even on normal wrapper exit. Never leave// a scanner worker consuming quota after its CLI's completion.- entry.evidence.cleanup = await (exitCleanup || cleanupGroup(entry.owner).catch(() => false)) ? 'confirmed' : 'unconfirmed';+ entry.evidence.cleanup = await (exitCleanup || cleanupGroup(owner).catch(() => false)) ? 'confirmed' : 'unconfirmed';clearTimeout(forceTimer);entry.evidence.exitCode = exit.code ?? (exit.signal === 'SIGTERM' ? 143 : exit.signal === 'SIGKILL' ? 137 : null);entry.evidence.status = entry.stopReason || (exit.code === 0 && !exit.failed && entry.evidence.cleanup === 'confirmed' ? 'completed' : 'failed');@@ -282,11 +300,11 @@ export function createSecurityScanManager({ agentsDir, getAgent, emitEvidence, tif (logError) throw logError;} catch (err) {if (entry.child) {- const confirmed = await cleanupGroup(entry.owner).catch(() => false);+ const confirmed = await cleanupGroup(owner).catch(() => false);entry.evidence.cleanup = confirmed ? 'confirmed' : 'unconfirmed';}- invalidInput = Boolean(err.preflight && !entry.attempted);- if (invalidInput) {+ invalidInput = Boolean(err.preflight && (!entry.attempted || (!entry.providerLaunched && entry.evidence.cleanup === 'confirmed')));+ if (err.preflight) {entry.evidence.preflight = {rejectedRequests: (entry.evidence.preflight?.rejectedRequests || 0) + 1,lastError: err.preflight,@@ -296,6 +314,7 @@ export function createSecurityScanManager({ agentsDir, getAgent, emitEvidence, t// No provider text, paths or credentials in shared logs.console.warn(`⚠️ Security scanner ${id} could not complete (${err.preflight?.code || err.code || 'runtime-error'})`);} finally {+ finished = true;clearTimeout(forceTimer);clearTimeout(deadline);clearTimeout(drainTimer);@@ -315,7 +334,12 @@ export function createSecurityScanManager({ agentsDir, getAgent, emitEvidence, tentry.terminal = true;await persist(id, entry);}- if (invalidInput && !entry.stopReason) entry.promise = null;+ if (invalidInput && !entry.stopReason) {+ entry.child = null;+ entry.attempted = false;+ entry.cancelling = false;+ entry.promise = null;+ }}finally {// A disk failure must never prevent stopping a refused outer request.diff --git a/server/cos-runner/securityScan.process.test.js b/server/cos-runner/securityScan.process.test.jsindex f524fba8e6..c503fbe214 100644--- a/server/cos-runner/securityScan.process.test.js+++ b/server/cos-runner/securityScan.process.test.js@@ -4,13 +4,16 @@ import { join } from 'path';import { tmpdir } from 'os';import { fileURLToPath } from 'url';import { randomUUID } from 'crypto';-import { spawn } from '../lib/childProcess.js';+import { execFileSync, spawn } from '../lib/childProcess.js';import { createSecurityScanManager } from './securityScan.js';import { cleanupSecurityScanGroup } from './securityScanRecovery.js';let root;const owners = [];-beforeEach(async () => { root = await mkdtemp(join(tmpdir(), 'scanner-process-test-')); await mkdir(join(root, 'repo')); });+beforeEach(async () => { root = await mkdtemp(join(tmpdir(), 'scanner-process-test-')); await mkdir(join(root, 'repo'));+ execFileSync('git', ['init', '--template='], { cwd: join(root, 'repo') });+ execFileSync('git', ['-c', 'user.name=Fixture', '-c', '[email protected]', 'commit', '--allow-empty', '-m', 'Synthetic baseline'], { cwd: join(root, 'repo') });+});afterEach(async () => {for (const owner of owners.splice(0)) await cleanupSecurityScanGroup(owner);await rm(root, { recursive: true, force: true });diff --git a/server/cos-runner/securityScan.snapshot.test.js b/server/cos-runner/securityScan.snapshot.test.jsnew file mode 100644index 0000000000..bc62d4a592--- /dev/null+++ b/server/cos-runner/securityScan.snapshot.test.js@@ -0,0 +1,143 @@+import { beforeEach, afterEach, describe, expect, it, vi } from 'vitest';+import { mkdtemp, mkdir, writeFile, readFile, rm, realpath, symlink, lstat, chmod } from 'fs/promises';+import { tmpdir } from 'os';+import { join } from 'path';+import { execFileSync } from '../lib/childProcess.js';+import { createSecurityScanManager } from './securityScan.js';+import { cleanupSecurityScanGroup } from './securityScanRecovery.js';++let root, source;+const managers = [];+const git = (...args) => execFileSync('git', args, { cwd: source, encoding: 'utf8', env: { ...process.env,+ GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null' } }).trim();+const commit = () => { git('add', '.'); return git('-c', 'user.name=Fixture', '-c', '[email protected]', 'commit', '-m', 'Synthetic baseline'); };+const grant = { model: 'example-model', effort: 'medium', auth: 'chatgpt', maxCostUsd: 'unlimited', timeLimitSeconds: 'unlimited' };++beforeEach(async () => {+ root = await realpath(await mkdtemp(join(tmpdir(), 'scanner-snapshot-test-')));+ source = join(root, 'source');+ await mkdir(source);+ git('init', '--template=');+ await writeFile(join(source, 'boundary.js'), 'committed boundary');+ await writeFile(join(source, 'context.md'), 'committed knowledge');+ commit();+});+afterEach(async () => {+ for (const manager of managers.splice(0)) await manager.stop('agent-fixture').catch(() => {});+ const owner = await readFile(join(root, 'agents/agent-fixture/security-scan-process.json'), 'utf8').then(JSON.parse).catch(() => null);+ await cleanupSecurityScanGroup(owner);+ await rm(root, { recursive: true, force: true });+});++async function setup(options = {}) {+ const fixture = join(root, 'scanner.cjs');+ // A synthetic process only: captures the received scope, without any network+ // or provider code. The real runner/supervisor/Git ownership path is exercised.+ await writeFile(fixture, `const fs=require('node:fs');+ fs.writeFileSync(${JSON.stringify(join(root, 'launched.json'))},JSON.stringify({args:process.argv.slice(2),cwd:process.cwd()}));+ console.log(JSON.stringify({cost:{estimatedUsd:0}}));`);+ const manager = createSecurityScanManager({ agentsDir: join(root, 'agents'), tempRoot: root,+ getAgent: () => ({ workspacePath: source }),+ resolveCli: async () => ({ command: process.execPath, args: [fixture] }), ...options });+ managers.push(manager);+ await manager.register('agent-fixture', grant);+ return manager;+}++describe.skipIf(process.platform === 'win32')('scanner committed snapshot boundary', () => {+ it('pins all inputs to independent objects and preserves the baseline through live edits and commits', async () => {+ const initialCommit = git('rev-parse', 'HEAD');+ const initialTree = git('rev-parse', 'HEAD^{tree}');+ await writeFile(join(source, 'boundary.js'), 'dirty content excluded');+ await writeFile(join(source, 'untracked.txt'), 'untracked content excluded');+ const manager = await setup({ emitEvidence: async (_id, evidence) => {+ if (evidence.status === 'running' && evidence.baseline) {+ await writeFile(join(source, 'boundary.js'), 'later repair');+ commit();+ }+ } });+ const result = await manager.start('agent-fixture', { prompt: 'Synthetic audit', paths: ['boundary.js'], knowledgeBase: ['context.md'] });+ expect(result.evidence).toMatchObject({ status: 'completed', exitCode: 0, cleanup: 'confirmed', baseline: {+ commit: initialCommit, tree: initialTree, kind: 'git-commit', uncommitted: 'excluded', submodules: 'excluded', symlinks: 'link-text',+ } });+ const launch = JSON.parse(await readFile(join(root, 'launched.json'), 'utf8'));+ expect(launch.cwd).not.toBe(source);+ expect(launch.args[1]).toBe(launch.cwd);+ expect(launch.args[launch.args.indexOf('--path') + 1]).toBe(join(launch.cwd, 'boundary.js'));+ expect(launch.args[launch.args.indexOf('--knowledge-base') + 1]).toBe(join(launch.cwd, 'context.md'));+ expect(await readFile(join(launch.cwd, 'boundary.js'), 'utf8')).toBe('committed boundary');+ expect(await lstat(join(launch.cwd, 'untracked.txt')).catch(() => null)).toBeNull();+ expect(git('rev-parse', 'HEAD')).not.toBe(initialCommit);+ expect(await readFile(join(launch.cwd, '.git/objects/info/alternates')).catch(() => null)).toBeNull();+ expect(await readFile(join(launch.cwd, '.git/config'), 'utf8')).not.toContain('[remote');+ expect(await manager.start('agent-fixture', { prompt: 'Again', paths: ['.'] })).toEqual(result);+ });++ it('does not execute source filters/hooks or follow symlinks and reports submodule exclusions', async () => {+ await symlink(join(root, 'outside'), join(source, 'link'));+ await writeFile(join(source, '.gitattributes'), 'boundary.js filter=fixture\n');+ commit();+ git('update-index', '--add', '--cacheinfo', `160000,${git('rev-parse', 'HEAD')},vendor`);+ git('-c', 'user.name=Fixture', '-c', '[email protected]', 'commit', '-m', 'Synthetic gitlink');+ await mkdir(join(source, 'vendor'));+ const marker = join(root, 'hook-ran');+ git('config', 'filter.fixture.smudge', `touch ${marker}`);+ git('config', 'uploadpack.packObjectsHook', `touch ${marker}`);+ const hooks = join(root, 'hooks'); await mkdir(hooks);+ await writeFile(join(hooks, 'post-checkout'), `#!/bin/sh\ntouch '${marker}'\n`); await chmod(join(hooks, 'post-checkout'), 0o700);+ git('config', 'core.hooksPath', hooks);+ const manager = await setup();+ const result = await manager.start('agent-fixture', { prompt: 'Synthetic audit', paths: ['.'] });+ expect(result.evidence.status).toBe('completed');+ const launch = JSON.parse(await readFile(join(root, 'launched.json'), 'utf8'));+ expect((await lstat(join(launch.cwd, 'link'))).isSymbolicLink()).toBe(false);+ expect(await readFile(join(launch.cwd, 'link'), 'utf8')).toBe(join(root, 'outside'));+ expect(await readFile(join(launch.cwd, 'boundary.js'), 'utf8')).toBe('committed boundary');+ expect(await lstat(marker).catch(() => null)).toBeNull();+ expect(execFileSync('git', ['status', '--porcelain'], { cwd: launch.cwd, encoding: 'utf8' }).trim()).toBe('');+ });++ it.each(['uncommitted', 'submodule', 'git-metadata'])('rejects %s selected context before provider launch and permits an explicit correction after cleanup', async kind => {+ const path = kind === 'uncommitted' ? 'draft.md' : kind === 'submodule' ? 'vendor' : '.git/config';+ if (kind === 'uncommitted') await writeFile(join(source, path), 'not in commit');+ else if (kind === 'submodule') {+ git('update-index', '--add', '--cacheinfo', `160000,${git('rev-parse', 'HEAD')},vendor`);+ git('-c', 'user.name=Fixture', '-c', '[email protected]', 'commit', '-m', 'Synthetic gitlink');+ await mkdir(join(source, path));+ }+ const manager = await setup();+ const result = await manager.start('agent-fixture', { prompt: 'Synthetic audit', paths: ['.'], knowledgeBase: [path] });+ expect(result.evidence).toMatchObject({ status: 'invalid-input', cleanup: 'confirmed', preflight: { lastError: {+ field: 'knowledgeBase', code: kind === 'submodule' ? 'submodule-excluded' : 'not-in-commit',+ } } });+ expect(await lstat(join(root, 'launched.json')).catch(() => null)).toBeNull();+ const corrected = await manager.start('agent-fixture', { prompt: 'Corrected input', paths: ['.'] });+ expect(corrected.evidence).toMatchObject({ status: 'completed', preflight: result.evidence.preflight });+ expect(await manager.start('agent-fixture', { prompt: 'Again', paths: ['.'] })).toEqual(corrected);+ });++ it('stops owned Git preparation and never launches the scanner after Stop', async () => {+ const bin = join(root, 'bin'); await mkdir(bin);+ const marker = join(root, 'git-worker');+ await writeFile(join(bin, 'git'), `#!/bin/sh\necho $$ > '${marker}'\nexec sleep 300\n`);+ await chmod(join(bin, 'git'), 0o700);+ const manager = await setup({ environment: { ...process.env, PATH: `${bin}:${process.env.PATH}` }, graceMs: 100 });+ const run = manager.start('agent-fixture', { prompt: 'Synthetic audit', paths: ['.'] });+ await vi.waitFor(async () => expect(Number(await readFile(marker, 'utf8'))).toBeGreaterThan(1));+ const pid = Number(await readFile(marker, 'utf8'));+ expect((await manager.stop('agent-fixture')).status).toBe('interrupted');+ expect((await run).evidence.cleanup).toBe('confirmed');+ expect(() => process.kill(pid, 0)).toThrow();+ expect(await lstat(join(root, 'launched.json')).catch(() => null)).toBeNull();+ });++ it('fails closed if committed baseline evidence cannot be persisted before launch', async () => {+ const manager = await setup({ emitEvidence: async (_id, evidence) => {+ if (evidence.baseline) throw new Error('Synthetic persistence failure');+ } });+ const run = manager.start('agent-fixture', { prompt: 'Synthetic audit', paths: ['.'] });+ await expect(run).rejects.toThrow('Synthetic persistence failure');+ expect(manager.start('agent-fixture', { prompt: 'Again', paths: ['.'] })).toBe(run);+ expect(await lstat(join(root, 'launched.json')).catch(() => null)).toBeNull();+ });+});diff --git a/server/cos-runner/securityScan.test.js b/server/cos-runner/securityScan.test.jsindex d95c4b3443..b69effbe30 100644--- a/server/cos-runner/securityScan.test.js+++ b/server/cos-runner/securityScan.test.js@@ -15,7 +15,7 @@ const outerAgents = [];beforeEach(async () => { root = await mkdtemp(join(tmpdir(), 'scanner-runtime-test-')); await mkdir(join(root, 'repo')); });afterEach(async () => { for (const agent of outerAgents.splice(0)) clearTimeout(agent.killTimer); vi.useRealTimers(); await rm(root, { recursive: true, force: true }); });-function setup({ finish, ...overrides } = {}) {+function setup({ finish, prepareError, ...overrides } = {}) {let child;let onSpawn;const spawned = new Promise(resolve => { onSpawn = resolve; });@@ -24,8 +24,20 @@ function setup({ finish, ...overrides } = {}) {const evidence = [];const spawnProcess = vi.fn((command, args, options) => {const outputDirectoryMode = statSync(args[1]).mode & 0o777;- child = Object.assign(new EventEmitter(), { pid: 99999999, stdout: new PassThrough(), stderr: new PassThrough() });- child.send = ({ command: scannerCommand, args: scannerArgs }, done) => {+ child = Object.assign(new EventEmitter(), { pid: 99999999 + spawnProcess.mock.calls.length, stdout: new PassThrough(), stderr: new PassThrough() });+ child.send = ({ command: scannerCommand, args: scannerArgs, prepare, cwd }, done) => {+ if (prepare) {+ done();+ if (prepareError && spawnProcess.mock.calls.length === 1) {+ setImmediate(() => child.emit('message', { snapshotError: { preflight: { field: 'paths', index: 0, code: 'not-in-commit' } } }));+ return;+ }+ setImmediate(() => child.emit('message', { snapshot: { repository: join(root, 'snapshot'),+ paths: [join(root, 'snapshot')], knowledgeBase: [],+ baseline: { kind: 'git-commit', commit: 'a'.repeat(40), tree: 'b'.repeat(40), uncommitted: 'excluded', submodules: 'excluded', symlinks: 'link-text' } } }));+ return;+ }+ options.scannerCwd = cwd;onSpawn({ child, command: scannerCommand, args: scannerArgs, options, outputDirectoryMode });done();if (finish) setImmediate(() => finish(child, scannerArgs));@@ -48,6 +60,23 @@ function setup({ finish, ...overrides } = {}) {const input = { prompt: 'Report-only source audit of the selected boundary.', paths: ['.'], knowledgeBase: [] };describe.skipIf(process.platform === 'win32')('runner-owned scanner lifecycle', () => {+ it('keeps delayed exit cleanup bound to the rejected preparation after corrected input starts', async () => {+ const cleanupGroup = vi.fn(async () => true);+ const h = setup({ prepareError: true, cleanupGroup });+ await h.manager.register('agent-example', grant);+ expect((await h.manager.start('agent-example', input)).evidence.status).toBe('invalid-input');+ const oldChild = h.spawnProcess.mock.results[0].value;+ const corrected = h.manager.start('agent-example', input);+ const { child } = await h.spawned;+ cleanupGroup.mockClear();+ oldChild.emit('exit', 1, null);+ await new Promise(resolve => setImmediate(resolve));+ expect(cleanupGroup).not.toHaveBeenCalled();+ expect(cleanupGroup).not.toHaveBeenCalledWith(expect.objectContaining({ pid: child.pid }));+ child.emit('close', 0, null);+ expect((await corrected).evidence.status).toBe('completed');+ });+it('makes the results directory owner-only before spawning with a normal umask', async () => {const previousUmask = process.umask(0o022);try {@@ -77,7 +106,7 @@ describe.skipIf(process.platform === 'win32')('runner-owned scanner lifecycle',const completed = await run;expect(completed.evidence).toMatchObject({ status: 'completed', preflight: rejected.evidence.preflight });expect(rejected.evidence.status).toBe('invalid-input');- expect(h.evidence.map(e => e.status)).toEqual(['not-run', 'invalid-input', 'running', 'completed']);+ expect(h.evidence.map(e => e.status)).toEqual(['not-run', 'invalid-input', 'running', 'running', 'completed']);expect(h.spawnProcess).toHaveBeenCalledOnce();expect(await h.manager.start('agent-example', input)).toEqual(completed);});@@ -236,7 +265,7 @@ describe.skipIf(process.platform === 'win32')('runner-owned scanner lifecycle',expect(result.evidence).toMatchObject({ source: 'runner', status: 'completed', model: 'example-model', effort: 'medium',maxCostUsd: launchGrant.maxCostUsd, timeLimitSeconds: launchGrant.timeLimitSeconds, estimatedCostUsd: 0.25, exitCode: 0, artifacts: { findings: true, coverage: true } });expect(JSON.parse(await readFile(join(root, 'agents/agent-example/security-scan.json'), 'utf8'))).toEqual(result.evidence);- expect(h.evidence.map(e => e.status)).toEqual(['not-run', 'running', 'completed']);+ expect(h.evidence.map(e => e.status)).toEqual(['not-run', 'running', 'running', 'completed']);});it.each([diff --git a/server/cos-runner/securityScanChild.js b/server/cos-runner/securityScanChild.jsindex c6d431c034..bf40c56654 100644--- a/server/cos-runner/securityScanChild.js+++ b/server/cos-runner/securityScanChild.js@@ -1,4 +1,5 @@import { spawn } from '../lib/childProcess.js';+import { withSpawnCwdEnv } from '../lib/spawnCwd.js';// The runner first persists this supervisor's identity, then releases exactly// one launch over its private IPC channel. A crash before that cannot start a@@ -9,10 +10,22 @@ const killOwnedGroup = () => {catch { process.exit(1); }};process.once('disconnect', killOwnedGroup);-process.once('message', ({ command, args }) => {- const child = spawn(command, args, { stdio: ['ignore', 'inherit', 'inherit'] });+const launch = ({ command, args, cwd }) => {+ const child = spawn(command, args, { cwd, env: withSpawnCwdEnv(process.env, cwd || process.cwd()), stdio: ['ignore', 'inherit', 'inherit'] });child.once('error', () => process.exit(1));child.once('exit', (code, signal) => {process.exit(code ?? (signal === 'SIGTERM' ? 143 : signal === 'SIGKILL' ? 137 : 1));});+};+process.once('message', async message => {+ if (!message.prepare) return launch(message);+ try {+ const { prepareSecurityScanSnapshot } = await import('./securityScanSnapshot.js');+ const snapshot = await prepareSecurityScanSnapshot(message.prepare);+ process.once('message', launch);+ process.send({ snapshot }, err => { if (err) killOwnedGroup(); });+ } catch (err) {+ // The runner owns public evidence; never forward Git stderr or local paths.+ process.send({ snapshotError: { code: 'snapshot-unavailable', preflight: err.preflight } }, err => { if (err) killOwnedGroup(); });+ }});diff --git a/server/cos-runner/securityScanSnapshot.js b/server/cos-runner/securityScanSnapshot.jsnew file mode 100644index 0000000000..a17879e9ea--- /dev/null+++ b/server/cos-runner/securityScanSnapshot.js@@ -0,0 +1,64 @@+import { mkdir, readFile, realpath, stat } from 'fs/promises';+import { join, relative, resolve, isAbsolute } from 'path';+import { promisify } from 'util';+import { execFile } from '../lib/childProcess.js';++const exec = promisify(execFile);+const oid = value => {+ const hash = value.trim();+ if (!/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(hash)) throw new Error('Invalid snapshot object');+ return hash;+};++// Runs only inside the scanner's owned supervisor/process group. Its IPC-loss+// and Stop cleanup cover Git preparation as well as the eventual provider.+export async function prepareSecurityScanSnapshot({ source, directory, paths, knowledgeBase }) {+ const root = await realpath(source);+ let repository = join(directory, 'repository');+ const empty = join(directory, 'empty');+ await mkdir(empty, { mode: 0o700 });+ // These overrides propagate to local upload-pack too. Never read global Git+ // config, inherit GIT_* routing, run templates/hooks, or fetch over a network.+ const config = {+ 'core.hooksPath': empty, 'core.fsmonitor': 'false', 'core.symlinks': 'false',+ 'core.autocrlf': 'false', 'gc.auto': '0', 'maintenance.auto': 'false',+ 'protocol.allow': 'never', 'protocol.file.allow': 'always',+ 'uploadpack.packObjectsHook': '', 'fetch.recurseSubmodules': 'false',+ };+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) =>+ ['PATH', 'HOME', 'USERPROFILE', 'SystemRoot', 'SYSTEMROOT', 'TMPDIR', 'TEMP', 'TMP', 'PORTOS_SECURITY_SCAN_OWNER'].includes(key)));+ Object.assign(env, { GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null', GIT_NO_REPLACE_OBJECTS: '1',+ GIT_TERMINAL_PROMPT: '0', GIT_CONFIG_COUNT: String(Object.keys(config).length) });+ Object.entries(config).forEach(([key, value], i) => { env[`GIT_CONFIG_KEY_${i}`] = key; env[`GIT_CONFIG_VALUE_${i}`] = value; });+ const git = async (cwd, args) => (await exec('git', args, { cwd, env, maxBuffer: 16 * 1024 * 1024 })).stdout;+ const commit = oid(await git(root, ['rev-parse', '--verify', 'HEAD^{commit}']));+ const tree = oid(await git(root, ['rev-parse', '--verify', `${commit}^{tree}`]));+ await git(directory, ['init', '--template=', `--object-format=${commit.length === 64 ? 'sha256' : 'sha1'}`, repository]);+ repository = await realpath(repository);+ await git(repository, ['config', 'core.symlinks', 'false']);+ await git(repository, ['config', 'core.autocrlf', 'false']);+ await git(repository, ['fetch', '--no-tags', '--depth=1', '--no-recurse-submodules', '--no-write-fetch-head', root, commit]);+ if (oid(await git(repository, ['rev-parse', '--verify', `${commit}^{tree}`])) !== tree) throw new Error('Snapshot binding changed');+ await git(repository, ['checkout', '--detach', '--force', commit]);+ // No remote or alternates survive: every object needed by this shallow+ // revision is owned by the snapshot. Later live edits/commits cannot alter it.+ if (await readFile(join(repository, '.git/objects/info/alternates'), 'utf8').catch(() => '')) throw new Error('Shared snapshot objects');+ const entries = (await git(repository, ['ls-tree', '-rz', commit])).split('\0');+ const tracked = entries.filter(Boolean).map(line => line.slice(line.indexOf('\t') + 1));+ const submodules = entries.filter(line => line.startsWith('160000 ')).map(line => line.slice(line.indexOf('\t') + 1));+ const mapPaths = async (values, field) => Promise.all(values.map(async (path, index) => {+ const rel = relative(root, resolve(root, path));+ const invalid = code => Object.assign(new Error('Invalid committed scanner input'), { preflight: { field, index, code } });+ if (rel === '..' || rel.startsWith('../') || isAbsolute(rel)) throw invalid('outside-workspace');+ if (submodules.some(p => rel === p || rel.startsWith(`${p}/`))) throw invalid('submodule-excluded');+ if (rel && !tracked.some(p => p === rel || p.startsWith(`${rel}/`))) throw invalid('not-in-commit');+ const target = resolve(repository, rel);+ if (!(await stat(target).catch(() => null))) throw invalid('not-in-commit');+ const actual = await realpath(target);+ const mapped = relative(repository, actual);+ if (mapped === '..' || mapped.startsWith('../') || isAbsolute(mapped)) throw invalid('outside-workspace');+ return target;+ }));+ return { repository, paths: await mapPaths(paths, 'paths'), knowledgeBase: await mapPaths(knowledgeBase, 'knowledgeBase'),+ baseline: { kind: 'git-commit', commit, tree, uncommitted: 'excluded', submodules: 'excluded', symlinks: 'link-text' } };+}diff --git a/server/lib/README.md b/server/lib/README.mdindex e1fe52e70f..8ad9745b1c 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -372,7 +372,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `pm2Jlist.js` | Sole owner of the strict `pm2 jlist` stdout parser: `parsePm2JlistStdout(stdout)` returns the parsed process array (incl. `[]` for a genuine empty read) or `null` when the read effectively failed (empty/garbage/non-array stdout) — the absent-vs-empty contract from issue #968, consolidated by #8164. Zero imports so `autofixer/shared.js` can use it without the server dependency graph. `services/pm2.js` re-exports it as `parseJlistStdout` for compatibility; `services/pm2.js#listProcessesStrict` and `autofixer/shared.js` are the only non-test callers permitted to execute raw `pm2 jlist`. || `secretText.js` | `scrubSecretTokens(text)` — replace credential-SHAPED substrings (prefixed API keys, GitHub/Slack tokens, JWTs, AWS key ids, pasted Bearer headers, 48+-char hex) with `[REDACTED]` in free text bound for an LLM provider or a world-readable artifact; `scrubSecretTokensDeep(value)` walks arrays/plain objects and scrubs every string value. Value-side counterpart to the operator-action ledger's key-based `redactPayload` and `commandSecurity.js#redactOutput`'s JSON patterns; conservative so prose, 40-hex git SHAs, and short ids survive. || `securityAuditLog.js` | `logSecurityEvent(event, { refused, ...fields })` — one-line `🔐`/`⛔ Security [event] key=value` audit trail for sign-ins, password/session/agent-key changes and refused host-control or browser-relay requests. Flattens control characters and truncates values so a caller-controlled path/Host can't forge a log line; refusals use `console.warn`. |-| `securityScanEvidence.js` | Strict scanner evidence/request/grant schemas; `securityScanGrantFromArgs` resolves actual Codex launch pins, `parseRunnerSecurityScanEvidence` preserves ordered runner observations, and `parseSecurityScanEvidence` retains legacy agent reports. |+| `securityScanEvidence.js` | Strict scanner evidence/request/grant schemas with committed snapshot provenance; `securityScanGrantFromArgs` resolves actual Codex launch pins, `parseRunnerSecurityScanEvidence` preserves ordered runner observations, `securityScanPRDisclosure` publishes bounded runner evidence independently of assistant summary truncation, and `parseSecurityScanEvidence` retains legacy agent reports. || `homePath.js` | `scrubHomePath(value)` — replace the running user's home-directory prefix with `~` anywhere in a string, so `/Users/<name>/…` never embeds the OS username in anything a user pastes into a bug report. Non-strings pass through; a root-user container reporting `/` as home is left alone (substituting on it would rewrite every separator in every path). Zero-dependency by design: `agentRunEvents.js` re-exports it for the CoS ledger, and `scripts/doctor.js` imports it statically because it must load from a bare checkout with no `node_modules` (`scripts/pre-install-entrypoints.test.js` enforces that). || `jsonIo.js` | JSON/JSONL parsing and file IO, strict read sentinels, append/read/write helpers, and `createCachedStore` — a TTL-cached mutable JSON document with serialized `save`/`mutate`; its `load()` is strict (#4115) so a corrupt file rejects instead of being overwritten by the next `mutate`. || `settingsStore.js` | `createSettingsStore(filePath | () => filePath, defaults, { normalize? })` → `{ get, update, path }` — the one owner of a flat per-feature settings document with shipped defaults (`journal-settings.json`, `activity-digest-settings.json`, `goal-scorecard-settings.json`, …). `get()` reads strict (#4115: a corrupt file rejects rather than reading as the defaults, because `update` writes it back), merges the file over `defaults`, then runs `normalize`; `update(patch)` is a serialized `get → apply → atomicWrite` that skips `undefined` values and writes `null` as an explicit clear. Filter client-settable keys BEFORE calling `update`. Reach for `createCachedStore` for an in-place-edited document and `createCollectionStore` for per-record collections. |diff --git a/server/lib/securityScanEvidence.js b/server/lib/securityScanEvidence.jsindex 70659119a9..9825316f6c 100644--- a/server/lib/securityScanEvidence.js+++ b/server/lib/securityScanEvidence.js@@ -18,12 +18,18 @@ export const securityScanEvidenceSchema = z.object({exitCode: z.number().int().nullable(),artifacts: z.object({ findings: z.boolean().nullable(), coverage: z.boolean().nullable() }).strict(),cleanup: z.enum(['not-needed', 'confirmed', 'unconfirmed']).optional(),+ baseline: z.object({+ kind: z.literal('git-commit'),+ commit: z.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),+ tree: z.string().regex(/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/),+ uncommitted: z.literal('excluded'), submodules: z.literal('excluded'), symlinks: z.literal('link-text'),+ }).strict().optional(),preflight: z.object({rejectedRequests: z.number().int().positive().max(Number.MAX_SAFE_INTEGER),lastError: z.object({field: z.enum(['paths', 'knowledgeBase']),index: z.number().int().min(0).max(99),- code: z.enum(['path-not-found', 'outside-workspace', 'invalid-path']),+ code: z.enum(['path-not-found', 'outside-workspace', 'invalid-path', 'not-in-commit', 'submodule-excluded']),}).strict(),}).strict().optional(),}).strict().refine(value => value.status !== 'completed' || value.exitCode === 0);@@ -69,6 +75,27 @@ export function parseRunnerSecurityScanEvidence(value) {return parsed.success ? { ...parsed.data, source, sequence } : null;}+/** Fixed-size public disclosure, independent of the bounded assistant summary. */+export function securityScanPRDisclosure(value, control) {+ if (value == null && control == null) return '';+ const scan = parseRunnerSecurityScanEvidence(value);+ if (!scan) return '## Security scanner\n\nRunner evidence unavailable; audit delivery does not establish scanner completion.\n\n';+ const known = value => value ?? 'unknown';+ const artifact = value => value == null ? 'unknown' : value ? 'saved' : 'absent';+ const limit = value => value === 'unlimited' ? 'none' : known(value);+ return [+ '## Security scanner (runner observed)', '',+ `Status: **${scan.status}**. Audit delivery and assessment success are separate from scanner completion.`,+ ...(control?.status === 'interrupted' ? ['Runner connection lost: interrupted; process cleanup unconfirmed. The status above is the last runner observation.'] : []),+ `Model: ${known(scan.model)}; effort: ${known(scan.effort)}; auth: ${scan.auth}.`,+ `API-equivalent estimated USD: ${known(scan.estimatedCostUsd)}; estimate cap: ${limit(scan.maxCostUsd)}; time limit (seconds): ${limit(scan.timeLimitSeconds)}. These estimates do not establish billed charges or subscription usage.`,+ `Exit: ${known(scan.exitCode)}; process cleanup: ${known(scan.cleanup)}; findings artifact: ${artifact(scan.artifacts.findings)}; coverage artifact: ${artifact(scan.artifacts.coverage)}. Artifact presence does not establish a clean scan.`,+ scan.baseline ? `Baseline commit: \`${scan.baseline.commit}\`; tree: \`${scan.baseline.tree}\`. Uncommitted files and submodules excluded; symlinks represented as link text. This does not certify subsequent repairs.` : 'Scanned revision: unknown.',+ ...(scan.preflight ? [`Input rejections: ${scan.preflight.rejectedRequests}; last: ${scan.preflight.lastError.field} item ${scan.preflight.lastError.index + 1}, ${scan.preflight.lastError.code}.`] : []),+ '', '',+ ].join('\n');+}+/** Invalid/absent evidence stays unreported; delivery success cannot fill it in. */export function parseSecurityScanEvidence(summary) {if (typeof summary !== 'string') return null;diff --git a/server/services/agentCompletionCleanup.js b/server/services/agentCompletionCleanup.jsindex 87f1ab23ba..62baf3f166 100644--- a/server/services/agentCompletionCleanup.js+++ b/server/services/agentCompletionCleanup.js@@ -414,7 +414,7 @@ async function completeJiraHandOff({ agentId, task, agentState, effectiveSuccess});const prUrl = jiraCreatePR === false ? null : await createJiraPullRequest({- agentId, task, workspace, jiraTicketId, jiraTicketRef, jiraBranch, outputBuffer,+ agentId, task, workspace, jiraTicketId, jiraTicketRef, jiraBranch, outputBuffer, scannerMetadata: agentState?.metadata,});if (jiraInstanceId) {@@ -447,11 +447,11 @@ async function resolveJiraTicketRef({ jiraTicketId, jiraTicketUrl, jiraInstanceIreturn ticketUrl ? `[${jiraTicketId}](${ticketUrl})` : jiraTicketId;}-async function createJiraPullRequest({ agentId, task, workspace, jiraTicketId, jiraTicketRef, jiraBranch, outputBuffer }) {+async function createJiraPullRequest({ agentId, task, workspace, jiraTicketId, jiraTicketRef, jiraBranch, outputBuffer, scannerMetadata }) {const { baseBranch, devBranch } = await git.getRepoBranches(workspace).catch(() => ({ baseBranch: null, devBranch: null }));const targetBranch = devBranch || baseBranch || 'main';- const jiraPrBody = await git.generatePRDescription(workspace, targetBranch, jiraBranch, outputBuffer);+ const jiraPrBody = await git.generatePRDescription(workspace, targetBranch, jiraBranch, outputBuffer, scannerMetadata?.securityScan, scannerMetadata?.securityScanControl);const jiraPrBodyWithRef = `Resolves ${jiraTicketRef}\n\n${jiraPrBody}`;const baseTitle = await git.suggestPRTitle(workspace, targetBranch, jiraBranch, task.description);diff --git a/server/services/agentCompletionCleanup.test.js b/server/services/agentCompletionCleanup.test.jsindex f82b203931..b96b8f13ac 100644--- a/server/services/agentCompletionCleanup.test.js+++ b/server/services/agentCompletionCleanup.test.js@@ -751,7 +751,11 @@ describe.each(['runner', 'spawner'])('%s completion side effects', (path) => {});it('hands a successful JIRA branch to its PR and ticket, skips generic cleanup, and releases the hold', async () => {+ const securityScan = { source: 'runner', sequence: 4, status: 'failed', exitCode: 2 };+ const securityScanControl = { status: 'interrupted', cleanup: 'unconfirmed' };+ getAgent.mockResolvedValue({ status: 'completed', metadata: { workspacePath: workspace, securityScan, securityScanControl }, result: { success: true } });await complete({ jiraTicketId: 'EXAMPLE-1', jiraBranch: 'feature/EXAMPLE-1', jiraInstanceId: 'example' });+ expect(git.generatePRDescription).toHaveBeenCalledWith(workspace, 'develop', 'feature/EXAMPLE-1', 'Implemented the example', securityScan, securityScanControl);expect(git.push).toHaveBeenCalledWith(workspace, 'feature/EXAMPLE-1');expect(git.createPR).toHaveBeenCalledWith(workspace, {title: 'EXAMPLE-1: Fix example',diff --git a/server/services/agentWorktreeCleanup.js b/server/services/agentWorktreeCleanup.jsindex 77a430b9af..e7778caca0 100644--- a/server/services/agentWorktreeCleanup.js+++ b/server/services/agentWorktreeCleanup.js@@ -188,6 +188,8 @@ async function worktreeCleanupContext(agentId, options) {discardWorktree: isTruthyMeta(normalized.originalTask?.metadata?.discardWorktree),worktreePath: metadata.workspacePath || join(PATHS.worktrees, agentId),publicationValidation: publicationHolds.get(agentId) || metadata.publicationValidation,+ securityScan: metadata.securityScan,+ securityScanControl: metadata.securityScanControl,warnings: [],};}@@ -334,7 +336,7 @@ async function openWorktreePullRequest(context) {}const prTitle = await git.suggestPRTitle(worktreePath, targetBranch, worktreeBranch, description);- const prBody = await git.generatePRDescription(worktreePath, targetBranch, worktreeBranch, agentOutput);+ const prBody = await git.generatePRDescription(worktreePath, targetBranch, worktreeBranch, agentOutput, context.securityScan, context.securityScanControl);const prResult = await git.createPR(worktreePath, {title: prTitle,diff --git a/server/services/cleanupAgentWorktree.test.js b/server/services/cleanupAgentWorktree.test.jsindex 266d59953b..280038b954 100644--- a/server/services/cleanupAgentWorktree.test.js+++ b/server/services/cleanupAgentWorktree.test.js@@ -353,6 +353,17 @@ describe('cleanupAgentWorktree - PR-creation path', () => {expect(removeWorktree).toHaveBeenCalledWith('agent-1', '/mock/workspace', 'cos/task-abc123', { merge: false });});+ it('passes saved scanner observations independently of a truncated successful audit summary', async () => {+ const securityScan = { source: 'runner', sequence: 4, status: 'failed', exitCode: 2 };+ const securityScanControl = { status: 'interrupted', cleanup: 'unconfirmed' };+ getAgent.mockResolvedValue(mockWorktreeAgent({ securityScan, securityScanControl }));+ git.push.mockResolvedValue(undefined);+ git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/1' });+ const agentOutput = 'Summary '.repeat(512) + '\n…[truncated]';+ await cleanupAgentWorktree('agent-1', true, { prCreation: 'always', agentOutput });+ expect(git.generatePRDescription).toHaveBeenCalledWith(expect.any(String), 'main', 'cos/task-abc123', agentOutput, securityScan, securityScanControl);+ });+it('should call removeWorktree with merge: false after successful push and PR', async () => {git.push.mockResolvedValue(undefined);git.createPR.mockResolvedValue({ success: true, url: 'https://github.com/test/repo/pull/2' });diff --git a/server/services/git.generatePRDescription.test.js b/server/services/git.generatePRDescription.test.jsindex b95631a7fb..86ff27cca2 100644--- a/server/services/git.generatePRDescription.test.js+++ b/server/services/git.generatePRDescription.test.js@@ -3,6 +3,8 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';vi.mock('../lib/execGit.js', () => ({ execGit: vi.fn(), execGitSafe: vi.fn() }));import { execGit } from '../lib/execGit.js';import { generatePRDescription } from './git.js';+import { initialSecurityScanEvidence } from '../lib/securityScanEvidence.js';+import { SENTINEL_COMPLETION_MARKER } from '../lib/agentOutputMarkers.js';const report = ['## Summary',@@ -43,6 +45,38 @@ beforeEach(() => {const generate = output => generatePRDescription('/synthetic/repo', 'main', 'feature', output);describe('generatePRDescription', () => {+ const scan = { ...initialSecurityScanEvidence({ model: 'example-model', effort: 'medium', auth: 'chatgpt', maxCostUsd: 'unlimited', timeLimitSeconds: 'unlimited' }),+ status: 'failed', exitCode: 2, sequence: 3, estimatedCostUsd: 0, artifacts: { findings: true, coverage: null }, cleanup: 'confirmed',+ baseline: { kind: 'git-commit', commit: 'a'.repeat(40), tree: 'b'.repeat(40), uncommitted: 'excluded', submodules: 'excluded', symlinks: 'link-text' } };++ it('preserves bounded runner evidence before a truncated final report and separates delivery from coverage', async () => {+ const output = SENTINEL_COMPLETION_MARKER + '\n' + `## Summary\n${'Synthetic completed audit.\n'.repeat(200)}`.slice(0, 4096) + '\n…[truncated]';+ const body = await generatePRDescription('/synthetic/repo', 'main', 'feature', output, scan);+ expect(body.indexOf('Security scanner (runner observed)')).toBeLessThan(body.indexOf('## Summary'));+ expect(body).toContain('Status: **failed**');+ expect(body).toContain('Audit delivery and assessment success are separate');+ expect(body).toContain('estimated USD: 0; estimate cap: none; time limit (seconds): none');+ expect(body).toContain('Exit: 2; process cleanup: confirmed; findings artifact: saved; coverage artifact: unknown');+ expect(body).toContain(`Baseline commit: \`${'a'.repeat(40)}\``);+ expect(body).toContain('does not certify subsequent repairs');+ expect(body.length).toBeLessThan(6000);+ });++ it.each([{ ...scan, source: 'agent-report' }, { ...scan, prompt: 'private injected field' }])('does not publish untrusted or malformed metadata as runner evidence', async evidence => {+ const body = await generatePRDescription('/synthetic/repo', 'main', 'feature', report, evidence);+ expect(body).toContain('Runner evidence unavailable');+ expect(body).not.toContain('Status: **failed**');+ expect(body).not.toContain('private injected field');+ });++ it('preserves unknown legacy scope and a connection interruption independently of the last runner observation', async () => {+ const { baseline: _baseline, ...legacy } = scan;+ const body = await generatePRDescription('/synthetic/repo', 'main', 'feature', '', { ...legacy, status: 'running', exitCode: null }, { status: 'interrupted', cleanup: 'unconfirmed' });+ expect(body).toContain('Status: **running**');+ expect(body).toContain('Runner connection lost: interrupted; process cleanup unconfirmed');+ expect(body).toContain('Scanned revision: unknown');+ });+it('keeps the report after raw diff output and token accounting, including Markdown', async () => {expect(await generate(`${diff}\ntokens used\n1,234\n\n${report}`)).toBe(body);expect(execGit).not.toHaveBeenCalled();diff --git a/server/services/git.js b/server/services/git.jsindex 1395e20f8e..6e8a0d6297 100644--- a/server/services/git.js+++ b/server/services/git.js@@ -23,6 +23,7 @@ import {} from '../lib/gitForge.js';import { PROTECTED_BRANCHES, validateFilePaths, toLiteralPathspec, assertSafeRef } from '../lib/gitArgs.js';import { ServerError } from '../lib/errorHandler.js';+import { securityScanPRDisclosure } from '../lib/securityScanEvidence.js';// Re-export so callers that used to import from services/git.js keep working.export { execGit, execGitSafe };@@ -527,21 +528,22 @@ export async function requestCopilotReview(dir, prUrl) {* @param {string} agentOutput - Raw agent output text* @returns {Promise<string>} Formatted PR body*/-export async function generatePRDescription(dir, baseBranch, headBranch, agentOutput) {+export async function generatePRDescription(dir, baseBranch, headBranch, agentOutput, securityScan, securityScanControl) {const summary = extractAgentSummary(agentOutput);+ const prefix = `Automated PR created by PortOS Chief of Staff.\n\n${securityScanPRDisclosure(securityScan, securityScanControl)}`;if (summary) {- return `Automated PR created by PortOS Chief of Staff.\n\n## Summary\n\n${summary}`;+ return `${prefix}## Summary\n\n${summary}`;}// Fallback: build from commit messages when no usable agent outputconst comparison = await getBranchComparison(dir, baseBranch, headBranch).catch(() => null);if (comparison?.commits?.length) {const commitLines = comparison.commits.map(c => `- ${c.message}`).join('\n');- return `Automated PR created by PortOS Chief of Staff.\n\n## Changes\n\n${commitLines}`;+ return `${prefix}## Changes\n\n${commitLines}`;}- return 'Automated PR created by PortOS Chief of Staff.';+ return prefix.trimEnd();}/**diff --git a/server/services/promptSections/securityAudit.js b/server/services/promptSections/securityAudit.jsindex 5f5bc8fada..eac7a6cb31 100644--- a/server/services/promptSections/securityAudit.js+++ b/server/services/promptSections/securityAudit.js@@ -18,7 +18,7 @@ export function buildSecurityAuditRuntimeSection(task, { providerId, providerComreturn `## Codex Security Audit RuntimeAfter reading the target threat model and completing repository-wide discovery, request the scanner phase through the PortOS runner. Write a private JSON request file containing only:{ "prompt": "The actual threat model, selected audit area and report-only restrictions", "paths": ["relative/source/path"], "knowledgeBase": ["AGENTS.md"] }-Choose real workspace-relative files; include available architecture/security documents in knowledgeBase. Keep outer issue-filing and completion commands out of the scanner prompt.+Choose real workspace-relative files present in committed HEAD; include committed architecture/security documents in knowledgeBase. The runner scans a private standalone snapshot of that commit: uncommitted, untracked and ignored files and submodules are excluded; symlinks are represented as recorded link text. Every scanner input is mapped into that snapshot, so ordinary worktree edits cannot change its target. Keep outer issue-filing and completion commands out of the scanner prompt.Request one scanner execution: \`${command} --max-time 0 --data-binary @<private-request-file>\`.The runner owns the installed Codex Security CLI and enforces this run's saved grant: resolved model and effort, subscription ChatGPT authentication, saved limits. New grants explicitly record unlimited for both maxCostUsd and timeLimitSeconds: no PortOS estimate cap or elapsed-time deadline. Read the actual limits from runner evidence; saved grants retain their original limits. Unknown or absent evidence is not proof of unlimited execution. Provider quota, rate and safety limits still apply. Those settings cannot be changed in the request. Wait for the single request to finish; a quiet response does not authorize another execution. No installation, API-key fallback, additional workers, patching or publication is permitted. Do not invoke a separate CLI, SDK or cloud scan: an unavailable runner/installation/model is a visible limitation, not permission for a different execution path.@@ -27,6 +27,6 @@ The response contains trusted runner evidence plus a private artifactDirectory.A cybersecurity/content-policy refusal is terminal for this request: stop clearly. Do not continue, retry, rephrase to evade a refusal, or switch providers. This overrides recovery guidance below. The runner also stops the outer request on a scanner refusal.-Report scanner execution separately from delivery and quality assessment. Runner-observed model/effort/auth, limits, exit and artifact evidence are authoritative; a saved assessment or successful outer task does not make an interrupted scan successful. Short-context estimates are API-equivalent usage, not billed charges or ChatGPT subscription quota. Do not claim unknown evidence as zero or success. Complete the normal sentinel and exactly one QUALITY_AUDIT_JSON assessment for work actually performed, with partial/unavailable coverage when warranted. SCANNER_STATUS_JSON is a legacy agent-report format; it cannot override runner evidence.+Report scanner execution separately from delivery and quality assessment. Runner-observed model/effort/auth, limits, baseline commit/tree, exit and artifact evidence are authoritative; a saved assessment or successful outer task does not make an interrupted scan successful. Revalidate findings against current source before remediation; scanning the baseline does not certify subsequent repairs. Short-context estimates are API-equivalent usage, not billed charges or ChatGPT subscription quota. Do not claim unknown evidence as zero or success. Complete the normal sentinel and exactly one QUALITY_AUDIT_JSON assessment for work actually performed, with partial/unavailable coverage when warranted. SCANNER_STATUS_JSON is a legacy agent-report format; it cannot override runner evidence.`;}