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: discover global Codex Security installs before audit investigation

Adam Eivyafc9e3578c24
diff --git a/docs/SECURITY_SCANNER_RUNTIME.md b/docs/SECURITY_SCANNER_RUNTIME.md
index 3647a3d2e0..3b275110d2 100644
--- a/docs/SECURITY_SCANNER_RUNTIME.md
+++ b/docs/SECURITY_SCANNER_RUNTIME.md
@@ -7,6 +7,29 @@ base paths. The runner resolves paths inside the assigned workspace and launches
an already installed `@openai/codex-security` CLI. It never installs a package or
selects another provider after a failure.
+CLI discovery checks the project dependency first, then global npm executables
+on the runner's absolute `PATH` entries, then existing npm execution-cache
+installs. A PATH executable must resolve to the declared bin of an
+`@openai/codex-security` package; arbitrary launchers are not executed to probe
+availability. This supports global installations without downloading anything
+or running `npm`/`npx` during an audit.
+
+Dispatch directs the outer Codex agent to read instructions and threat-model
+documents, establish scope, then call the scanner **before vulnerability
+discovery or active testing**. Repository-wide audits use `paths: ["."]`;
+explicitly scoped audits retain their requested boundary. The scanner performs
+the initial investigation, and the outer agent validates its evidence and
+handles the task's tracker/remediation delivery afterwards.
+
+Installing the CLI or plugin does not change the outer agent's cyber access.
+Provider safety refusals remain terminal in both phases. Broader approved access
+requires [Trusted Access/Daybreak](https://learn.chatgpt.com/docs/cyber-safety)
+for the actual account, model and surface; selecting a scanner or changing a
+local permission setting does not grant that access. Suspected false positives
+can be reported through Codex `/feedback`. See the
+[official scan guidance](https://learn.chatgpt.com/docs/security/plugin/scans)
+for threat-model context and coverage interpretation.
+
Before execution, missing, malformed or out-of-workspace context paths produce
`invalid-input` evidence. This records a rejection count and the last field,
zero-based item index and bounded error code, without publishing paths or raw
diff --git a/docs/features/self-improvement-audits.md b/docs/features/self-improvement-audits.md
index ddc24f7835..49e9d5be99 100644
--- a/docs/features/self-improvement-audits.md
+++ b/docs/features/self-improvement-audits.md
@@ -27,20 +27,27 @@ missions. Selection follows the provider executable (with the shipped provider
id as a fallback), rather than the model name. Other providers and the separate
local-inference-only private assessment keep their existing workflows.
-The agent uses an available Codex Security scanner or the official
-[`@openai/codex-security` CLI](https://learn.chatgpt.com/docs/security/cli) in
-report-only, unattended mode, with private artifacts outside the checkout.
+The agent reads instructions and the documented threat model, establishes scope,
+then requests the runner's installed
+[`@openai/codex-security` CLI](https://learn.chatgpt.com/docs/security/cli)
+before vulnerability discovery or active testing. The runner discovers project,
+global PATH and cached npm installs without installing or invoking a launcher.
+The scan runs in report-only, unattended mode, with private artifacts outside
+the checkout.
Existing authentication, configured model/effort, quota and spending limits
still apply. This routing does not install a hook, patch code, create a PR,
publish findings, or authorize a different provider account. The audit's
file-issues/remediation contract remains responsible for delivery.
-Unavailable access or a refused action must be recorded without interactive
-login or repeated attempts through another tool. The agent preserves completed
-evidence, continues independently permitted review, delivers supported findings,
-and writes the usual quality assessment and completion sentinel. Scanner
-coverage and unresolved areas remain evidence to inspect, not a clean bill of
-health for the repository.
+Unavailable access must be recorded without interactive login or repeated
+attempts through another tool. The agent preserves completed evidence, continues
+independently permitted review, delivers supported findings, and writes the usual
+quality assessment and completion sentinel. A cybersecurity/content-policy
+refusal stops the scanner and outer request; it never authorizes continuation,
+retry, rephrasing or provider fallback. Installing the scanner does not grant
+broader [Trusted Access/Daybreak](https://learn.chatgpt.com/docs/cyber-safety).
+Scanner coverage and unresolved areas remain evidence to inspect, not a clean
+bill of health 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
diff --git a/server/cos-runner/securityScan.js b/server/cos-runner/securityScan.js
index c2c82d5d79..4663a9b46e 100644
--- a/server/cos-runner/securityScan.js
+++ b/server/cos-runner/securityScan.js
@@ -1,6 +1,6 @@
-import { mkdtemp, readFile, readdir, realpath, stat, chmod } from 'fs/promises';
+import { mkdtemp, readFile, readdir, realpath, chmod } from 'fs/promises';
import { join, relative, isAbsolute, resolve } from 'path';
-import { homedir, tmpdir } from 'os';
+import { tmpdir } from 'os';
import { randomUUID } from 'crypto';
import { fileURLToPath } from 'url';
import { spawn } from '../lib/childProcess.js';
@@ -10,31 +10,13 @@ import { createContentRefusalDetector, isContentRefusalError } from '../lib/aiTo
import { initialSecurityScanEvidence, securityScanGrantSchema, securityScanRequestSchema } from '../lib/securityScanEvidence.js';
import { armForceKill } from './forceKill.js';
import { cleanupSecurityScanGroup } from './securityScanRecovery.js';
+import { resolveInstalledSecurityScanner } from './securityScanCli.js';
const CHILD = fileURLToPath(new URL('./securityScanChild.js', import.meta.url));
const AGENT_ID = /^[a-zA-Z0-9_-]{1,200}$/;
const ENV_KEYS = new Set(['PATH', 'HOME', 'USERPROFILE', 'APPDATA', 'LOCALAPPDATA', 'SystemRoot', 'SYSTEMROOT', 'TEMP', 'TMP', 'TMPDIR', 'LANG', 'LC_ALL', 'CODEX_HOME']);
const failure = (message, status = 409) => Object.assign(new Error(message), { status });
-// Read installed package metadata only. Never run npx, download a package, or
-// consult the registry while deciding whether a scan can be started.
-async function resolveInstalledSecurityScanner({ home = homedir(), root = process.cwd() } = {}) {
- const candidates = [join(root, 'node_modules/@openai/codex-security')];
- const cache = join(home, '.npm/_npx');
- for (const name of (await readdir(cache).catch(() => [])).sort()) {
- if (/^[a-f0-9]+$/.test(name)) candidates.push(join(cache, name, 'node_modules/@openai/codex-security'));
- }
- for (const directory of candidates) {
- const pkg = await readFile(join(directory, 'package.json'), 'utf8').then(JSON.parse).catch(() => null);
- const bin = pkg?.bin?.['codex-security'];
- if (pkg?.name !== '@openai/codex-security' || typeof bin !== 'string') continue;
- const path = resolve(directory, bin);
- if (relative(directory, path).startsWith('..') || !(await stat(path).catch(() => null))?.isFile()) continue;
- return { command: process.execPath, args: [path], version: pkg.version };
- }
- return null;
-}
-
async function scopePaths(cwd, values, field) {
const root = await realpath(cwd);
return Promise.all(values.map(async (value, index) => {
@@ -147,7 +129,7 @@ export function createSecurityScanManager({ agentsDir, getAgent, emitEvidence, t
let invalidInput = false;
try {
const [paths, knowledgeBase, cli] = await Promise.all([
- scopePaths(agent.workspacePath, request.paths, 'paths'), scopePaths(agent.workspacePath, request.knowledgeBase, 'knowledgeBase'), resolveCli(),
+ scopePaths(agent.workspacePath, request.paths, 'paths'), scopePaths(agent.workspacePath, request.knowledgeBase, 'knowledgeBase'), resolveCli({ environment }),
]);
if (entry.stopReason) { entry.evidence.status = entry.stopReason; return { evidence: entry.evidence, artifactDirectory: null }; }
if (!cli || !entry.grant.model || !entry.grant.effort || process.platform === 'win32') { entry.evidence.status = 'unavailable'; return { evidence: entry.evidence, artifactDirectory: null }; }
diff --git a/server/cos-runner/securityScanCli.js b/server/cos-runner/securityScanCli.js
new file mode 100644
index 0000000000..d3269f1590
--- /dev/null
+++ b/server/cos-runner/securityScanCli.js
@@ -0,0 +1,45 @@
+import { readFile, readdir, realpath, stat } from 'fs/promises';
+import { delimiter, dirname, isAbsolute, join, resolve } from 'path';
+import { homedir } from 'os';
+import { isPathAtOrInsideDir } from '../lib/pathContainment.js';
+
+async function packageCli(directory, expectedEntry) {
+ const pkg = await readFile(join(directory, 'package.json'), 'utf8').then(JSON.parse).catch(() => null);
+ const bin = pkg?.bin?.['codex-security'];
+ if (pkg?.name !== '@openai/codex-security' || typeof bin !== 'string') return null;
+ if (!isPathAtOrInsideDir(directory, resolve(directory, bin))) return null;
+ const [packageRoot, entry] = await Promise.all([
+ realpath(directory).catch(() => null), realpath(resolve(directory, bin)).catch(() => null),
+ ]);
+ if (!packageRoot || !entry || !isPathAtOrInsideDir(packageRoot, entry) || (expectedEntry && entry !== expectedEntry)) return null;
+ if (!(await stat(entry).catch(() => null))?.isFile()) return null;
+ return { command: process.execPath, args: [entry], version: pkg.version };
+}
+
+// Inspect metadata without invoking npm, a PATH launcher, or the scanner.
+// Global npm installs expose a symlink to the package's declared bin entry.
+export async function resolveInstalledSecurityScanner({ home = homedir(), root = process.cwd(), environment = process.env } = {}) {
+ const local = await packageCli(join(root, 'node_modules/@openai/codex-security'));
+ if (local) return local;
+
+ for (const directory of new Set((environment.PATH || '').split(delimiter).filter(isAbsolute))) {
+ const entry = await realpath(join(directory, 'codex-security')).catch(() => null);
+ if (!entry) continue;
+ let parent = dirname(entry);
+ while (true) {
+ const cli = await packageCli(parent, entry);
+ if (cli) return cli;
+ const next = dirname(parent);
+ if (next === parent) break;
+ parent = next;
+ }
+ }
+
+ const cache = join(home, '.npm/_npx');
+ for (const name of (await readdir(cache).catch(() => [])).sort()) {
+ if (!/^[a-f0-9]+$/.test(name)) continue;
+ const cli = await packageCli(join(cache, name, 'node_modules/@openai/codex-security'));
+ if (cli) return cli;
+ }
+ return null;
+}
diff --git a/server/cos-runner/securityScanCli.test.js b/server/cos-runner/securityScanCli.test.js
new file mode 100644
index 0000000000..439f7bf1e9
--- /dev/null
+++ b/server/cos-runner/securityScanCli.test.js
@@ -0,0 +1,68 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+import { mkdtemp, mkdir, realpath, rm, symlink, writeFile } from 'fs/promises';
+import { delimiter, dirname, join, resolve } from 'path';
+import { tmpdir } from 'os';
+import { resolveInstalledSecurityScanner } from './securityScanCli.js';
+
+let root;
+let options;
+beforeEach(async () => {
+ root = await realpath(await mkdtemp(join(tmpdir(), 'scanner-cli-test-')));
+ options = { home: join(root, 'home'), root: join(root, 'repo'), environment: { PATH: join(root, 'bin') } };
+});
+afterEach(async () => { await rm(root, { recursive: true, force: true }); });
+
+async function install(directory, { name = '@openai/codex-security', bin = './bin/codex-security.mjs' } = {}) {
+ await mkdir(join(directory, 'bin'), { recursive: true });
+ await writeFile(join(directory, 'package.json'), JSON.stringify({ name, version: '0.2.0', bin: { 'codex-security': bin } }));
+ const entry = join(directory, 'bin/codex-security.mjs');
+ await writeFile(entry, 'throw new Error("Discovery must never execute a scanner");');
+ const declaredEntry = resolve(directory, bin);
+ if (declaredEntry !== entry) {
+ await mkdir(dirname(declaredEntry), { recursive: true });
+ await writeFile(declaredEntry, 'throw new Error("Discovery must never execute a different entry");');
+ }
+ return entry;
+}
+
+async function globalInstall(metadata) {
+ const directory = join(root, 'global/lib/node_modules/@openai/codex-security');
+ const entry = await install(directory, metadata);
+ await mkdir(options.environment.PATH, { recursive: true });
+ await symlink(entry, join(options.environment.PATH, 'codex-security'));
+ return entry;
+}
+
+describe.skipIf(process.platform === 'win32')('installed security scanner discovery', () => {
+ it('finds a global npm executable on PATH without invoking npm or the scanner', async () => {
+ const entry = await globalInstall();
+ options.environment.PATH = `${join(root, 'missing')}${delimiter}${options.environment.PATH}`;
+ expect(await resolveInstalledSecurityScanner(options)).toEqual({ command: process.execPath, args: [entry], version: '0.2.0' });
+ });
+
+ it('prefers the local install, then PATH, while retaining the cached-install fallback', async () => {
+ const local = join(options.root, 'node_modules/@openai/codex-security');
+ const cached = join(options.home, '.npm/_npx/abcd/node_modules/@openai/codex-security');
+ const localEntry = await install(local);
+ const cachedEntry = await install(cached);
+ const globalEntry = await globalInstall();
+ expect((await resolveInstalledSecurityScanner(options)).args).toEqual([localEntry]);
+ await rm(local, { recursive: true });
+ expect((await resolveInstalledSecurityScanner(options)).args).toEqual([globalEntry]);
+ options.environment.PATH = '';
+ expect((await resolveInstalledSecurityScanner(options)).args).toEqual([cachedEntry]);
+ });
+
+ it.each([
+ { name: 'unrelated-package' },
+ { bin: '../../outside.mjs' },
+ { bin: './bin/other-entry.mjs' },
+ ])('rejects a PATH executable that does not match the official package bin: %j', async metadata => {
+ await globalInstall(metadata);
+ expect(await resolveInstalledSecurityScanner(options)).toBeNull();
+ });
+
+ it('reports a missing installation without using ambient PATH or installing anything', async () => {
+ expect(await resolveInstalledSecurityScanner(options)).toBeNull();
+ });
+});
diff --git a/server/services/agentPromptBuilder.test.js b/server/services/agentPromptBuilder.test.js
index 6d406e17ba..e2042fd6d0 100644
--- a/server/services/agentPromptBuilder.test.js
+++ b/server/services/agentPromptBuilder.test.js
@@ -818,6 +818,9 @@ describe('buildLightContextPrompt', () => {
expect(prompt.userPrompt).toContain('Custom security mission');
expect(prompt.systemPrompt).toContain('## Codex Security Audit Runtime');
+ expect(prompt.systemPrompt).toContain('Before vulnerability discovery or active testing');
+ expect(prompt.systemPrompt).toContain('"paths": ["."]');
+ expect(prompt.systemPrompt).not.toContain('completing repository-wide discovery, request the scanner');
expect(prompt.systemPrompt).toContain('/security-scan');
expect(prompt.systemPrompt).toContain('subscription ChatGPT authentication');
expect(prompt.systemPrompt).toContain('saved grants retain their original limits');
diff --git a/server/services/promptSections/securityAudit.js b/server/services/promptSections/securityAudit.js
index eac7a6cb31..f202c41689 100644
--- a/server/services/promptSections/securityAudit.js
+++ b/server/services/promptSections/securityAudit.js
@@ -16,9 +16,9 @@ export function buildSecurityAuditRuntimeSection(task, { providerId, providerCom
const endpoint = `/api/cos/agents/${encodeURIComponent(agentId || '<agent-id>')}/security-scan`;
const command = agentApiCurl({ apiBase: localApiBaseUrl(), path: endpoint });
return `## Codex Security Audit Runtime
-After 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 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.
+Before vulnerability discovery or active testing, read the repository instructions and documented threat model, enumerate the files needed to establish scope, then request the scanner phase through the PortOS runner. Codex Security performs the initial vulnerability investigation; the outer agent coordinates the scan and validates its evidence afterwards. This ordering takes precedence over the mission's discovery/investigation steps. Write a private JSON request file containing only:
+{ "prompt": "The actual threat model, selected audit area and report-only restrictions", "paths": ["."], "knowledgeBase": ["AGENTS.md"] }
+Use paths ["."] for a repository-wide audit, or committed workspace-relative paths when the task explicitly limits scope. Include only existing committed instructions and architecture/security documents in knowledgeBase; use [] when none exist. The runner scans a private standalone snapshot of committed HEAD: 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. Installing Codex Security does not grant broader cyber access or exempt either phase from provider safeguards.
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.