From 6d01b6f42baef5a622d10f1b0d45c0ef86a9ea6a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 14:54:12 +0000 Subject: [PATCH 01/16] task: add codex-repo-hook-trust (active) --- .../2026-11-16-codex-repo-hook-trust.md | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 tasks/active/2026-11-16-codex-repo-hook-trust.md diff --git a/tasks/active/2026-11-16-codex-repo-hook-trust.md b/tasks/active/2026-11-16-codex-repo-hook-trust.md new file mode 100644 index 0000000000..e5314fad40 --- /dev/null +++ b/tasks/active/2026-11-16-codex-repo-hook-trust.md @@ -0,0 +1,23 @@ +# SAM Codex sessions run repository hooks (trust them), plus Codex rule delivery and Stop gate + +Raphaël, 2026-11-16 (chat b0530f70, after PR #2790): "if the hooks are defined in the repo (i.e. the user or their agent set them up... then I think they should" -> "Yup. Do it." Idea 01M7J0TXAHGRY8CWA7Y7SJZAK0. + +## Problem +Codex loads a repository's `.codex/` layer only for a trusted project and runs a non-managed hook only when its definition is trusted by hash. The vm-agent marks neither, so no repository hook runs in a SAM Codex session (probe 01M7HZ6Q1EVPVPCBN00AM3WN8A). Claude Code sessions already run `.claude/settings.json` hooks. + +## Research +- Codex rust-v0.160.0 (SAM pins 0.160.0-sam-c2.2): `codex-rs/app-server/src/config_manager.rs` accepts a per-thread request override `bypass_hook_trust` (bool); `codex-rs/config/src/loader/mod.rs` reads `projects..trust_level` from the merged config including CLI/request overrides, and `decision_for_dir` checks cwd, project root and repo root. +- codex-acp forwards `CODEX_CONFIG` JSON to every app-server thread (`packages/vm-agent/internal/acp/session_host_startup.go`, `buildCodexACPManagedConfigEnv`). ACP session cwd = `h.config.ContainerWorkDir` (`session_host_handshake.go`), same SessionHost path for VM and Instant. +- Hook code ready on branch `sam/codex-rule-delivery-hook` (f3b156c19). + +## Checklist +- [ ] vm-agent: CODEX_CONFIG carries `bypass_hook_trust: true` and `projects..trust_level = "trusted"`; tests +- [ ] Restore `.codex/hooks/rule-context.mjs`, generated `rule-scopes.json` + `--check` staleness, Codex hook entries (SessionStart, PreToolUse, Stop), `.gitignore` re-include +- [ ] Close Codex-hook test gaps from the PR #2790 test review (deny-once with deferred rules, cd/cwd, ignored dirs, write table, patch ops, SessionStart sources, session isolation, config wiring, real-lookup smoke) +- [ ] Docs: scripts/quality/README.md, security doc if it describes hook/trust behaviour +- [ ] Staging: deploy, fresh VM node, Codex session on a repo with the hooks: rule text before the first edit (existing file, new file, shell), Stop gate fires; control without hooks +- [ ] Reviews, CI, merge, deploy monitoring + +## Acceptance +- [ ] A SAM Codex session on staging runs the repository hooks (log + agent report), Stop gate continues the turn once +- [ ] Unit tests prove CODEX_CONFIG content for VM and standalone shapes From 413910d14deedc66fcb2a99f7ddc131437b919c5 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 14:56:06 +0000 Subject: [PATCH 02/16] feat(agents): restore the Codex rule-delivery hook and Codex Stop entry, with the review's missing tests --- .codex/config.toml | 41 +- .codex/hooks/rule-context.mjs | 486 +++++++ .codex/hooks/rule-scopes.json | 1237 +++++++++++++++++ .gitignore | 2 + package.json | 2 +- .../quality/agent-codex-rule-context.test.ts | 485 +++++++ scripts/quality/agent-codex-rule-scopes.ts | 62 + scripts/quality/check-agent-context-budget.ts | 3 + 8 files changed, 2312 insertions(+), 6 deletions(-) create mode 100644 .codex/hooks/rule-context.mjs create mode 100644 .codex/hooks/rule-scopes.json create mode 100644 scripts/quality/agent-codex-rule-context.test.ts create mode 100644 scripts/quality/agent-codex-rule-scopes.ts diff --git a/.codex/config.toml b/.codex/config.toml index 0c7581374f..2f0e3d38e6 100644 --- a/.codex/config.toml +++ b/.codex/config.toml @@ -14,13 +14,44 @@ approval_policy = "never" # Hooks (schema: https://developers.openai.com/codex/hooks) # ============================================================================== # Each event holds matcher groups, and each group holds a `hooks` array of handlers. -# `timeout` is in seconds. Project hooks run only when this .codex/ layer is trusted and -# each hook definition has been trusted (Codex records trust against its hash). +# `timeout` is in seconds. Codex runs project hooks only for a trusted project whose hook +# definitions are trusted; SAM's vm-agent grants both for its Codex sessions +# (packages/vm-agent/internal/acp/session_host_startup.go, buildCodexACPManagedConfigEnv). # `pnpm quality:agent-context-budget --check` validates these entries. -# No hooks are configured: SAM-managed Codex sessions do not trust this project, so Codex -# would skip them (probe evidence on SAM idea 01M7H32EK6S4E31EHWVSJSENR5). The rule-delivery -# and Stop hooks wait on that decision, on branch sam/codex-rule-delivery-hook. +# Path-scoped rule delivery: Codex loads only the root AGENTS.md by itself. This hook adds +# the rules (.claude/rules/*.md with `paths`) that govern the files a tool call touches, +# the same rules Claude Code loads on file access. See .codex/hooks/rule-context.mjs. +# additionalContextLimit (tokens) sits above the hook's own byte cap so Codex never spills. +[[hooks.SessionStart]] +matcher = "^(startup|resume|clear|compact|fork)$" + +[[hooks.SessionStart.hooks]] +type = "command" +command = 'node "$(git rev-parse --show-toplevel)/.codex/hooks/rule-context.mjs"' +timeout = 10 +additionalContextLimit = 20000 +statusMessage = "Preparing SAM rule delivery" + +[[hooks.PreToolUse]] +matcher = "^(Bash|apply_patch)$" + +[[hooks.PreToolUse.hooks]] +type = "command" +command = 'node "$(git rev-parse --show-toplevel)/.codex/hooks/rule-context.mjs"' +timeout = 10 +additionalContextLimit = 20000 +statusMessage = "Checking SAM rules for these files" + +# Test-quality Stop gate (rule 35), shared with Claude Code. Delivery per finding class is +# set and measured in .claude/hooks/verify-test-quality.mjs; it never blocks without limit. +[[hooks.Stop]] + +[[hooks.Stop.hooks]] +type = "command" +command = 'node "$(git rev-parse --show-toplevel)/.claude/hooks/verify-test-quality.mjs"' +timeout = 30 +statusMessage = "Checking tests for changed boundary code" [projects."/workspaces/simple-agent-manager"] trust_level = "trusted" diff --git a/.codex/hooks/rule-context.mjs b/.codex/hooks/rule-context.mjs new file mode 100644 index 0000000000..10526360a7 --- /dev/null +++ b/.codex/hooks/rule-context.mjs @@ -0,0 +1,486 @@ +#!/usr/bin/env node +// rule-context.mjs — Codex hook that delivers path-scoped rules. +// +// Codex started at the repository root loads only the root AGENTS.md. Claude Code loads a +// path-scoped rule (.claude/rules/*.md with `paths` frontmatter) when a matching file is +// accessed; this hook gives Codex the same rules at the same moment: +// +// SessionStart (startup, resume, clear, compact, fork) +// Starts a new delivery epoch when the model's context was reset (startup, clear, +// compact), so rules are delivered again, and tells the model how delivery works. +// PreToolUse (apply_patch, Bash) +// Finds the repository paths the call touches, and adds the bodies of the rules +// that govern them and have not been delivered in this epoch as additionalContext. +// The first write to paths whose rules were never delivered is denied once, so the +// rules are in context before anything is written; the retried write is allowed. +// +// Which rules apply to a path comes from .codex/hooks/rule-scopes.json, generated from +// scripts/quality/agent-instructions.ts by `pnpm quality:agent-context-budget --write` +// (--check fails when it is stale). Rule bodies are read from disk when delivered. +// +// Constraints: Node built-ins only (it must run in a workspace without node_modules); it +// never fails a session (every error path prints `{}` and exits 0, which Codex treats as +// "no opinion"); output is bounded by SAM_CODEX_RULE_CONTEXT_MAX_BYTES so Codex never +// spills it to disk. Every delivery is logged to .tmp/instruction-loads/codex-.jsonl. +// +// `node .codex/hooks/rule-context.mjs --show ...` prints the rules for paths, for an +// agent (or a person) who wants them without a hook. + +import { createHash } from 'node:crypto'; +import { + appendFileSync, + mkdirSync, + readFileSync, + renameSync, + statSync, + writeFileSync, +} from 'node:fs'; +import { dirname, isAbsolute, join, relative, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '../..'); +const LOOKUP_FILE = join(ROOT, '.codex/hooks/rule-scopes.json'); +const STATE_DIR = join(ROOT, '.tmp/codex-rule-context'); +const LOG_DIR = join(ROOT, '.tmp/instruction-loads'); + +/** + * Rule text per hook output. Must stay below the handler's additionalContextLimit in + * .codex/config.toml (20000 tokens; at a conservative three bytes per token that is 60 KB) so Codex never spills. + */ +const DEFAULT_MAX_BYTES = 40_000; +const MIN_MAX_BYTES = 4_000; +const MAX_MAX_BYTES = 48_000; + +/** Session-start sources after which the model no longer has earlier hook context. */ +const RESET_SOURCES = new Set(['startup', 'clear', 'compact']); + +/** Shell words that write their path arguments. */ +const SHELL_WRITERS = new Set([ + 'cp', + 'install', + 'ln', + 'mkdir', + 'mv', + 'rm', + 'rmdir', + 'tee', + 'touch', + 'truncate', +]); + +const IGNORED_SEGMENTS = new Set(['.git', 'node_modules', '.tmp', 'dist']); + +/** Input bounds: a hook runs before every shell call, so a huge command must stay cheap. */ +const MAX_COMMAND_CHARS = 64_000; +const MAX_WORDS = 4_000; +const MAX_CD_STEPS = 50; +const MAX_PATH_CHARS = 1_024; +const MAX_TARGETS = 200; +const DISPLAY_PATH_CHARS = 200; + +/** Only files in the rules directory may be read into model context. */ +const RULE_PATH = /^\.claude\/rules\/[A-Za-z0-9._-]+\.md$/; + +/** A path as shown to the model or written to the log: bounded and quoted. */ +export function displayPath(path) { + const text = String(path); + return JSON.stringify( + text.length > DISPLAY_PATH_CHARS ? `${text.slice(0, DISPLAY_PATH_CHARS)}…` : text + ); +} + +export function maxBytes(env = process.env) { + const raw = Number.parseInt(env.SAM_CODEX_RULE_CONTEXT_MAX_BYTES ?? '', 10); + if (!Number.isFinite(raw)) return DEFAULT_MAX_BYTES; + return Math.min(MAX_MAX_BYTES, Math.max(MIN_MAX_BYTES, raw)); +} + +export function loadLookup(file = LOOKUP_FILE) { + const data = JSON.parse(readFileSync(file, 'utf8')); + if (!data || !Array.isArray(data.rules)) throw new Error('rule-scopes.json has no rules array'); + return data.rules + .filter((rule) => RULE_PATH.test(String(rule.path)) && Array.isArray(rule.patterns)) + .map((rule) => ({ + path: String(rule.path), + title: String(rule.title).slice(0, DISPLAY_PATH_CHARS), + patterns: rule.patterns.map((p) => ({ + literal: Number(p.literal) || 0, + regex: new RegExp(p.regex), + })), + })); +} + +/** How narrowly a matched pattern names the path: its literal characters. */ +function specificity(rule, path) { + let best = -1; + for (const pattern of rule.patterns) { + if (pattern.regex.test(path)) best = Math.max(best, pattern.literal); + } + return best; +} + +/** Rules governing any of `paths`, most specific first; a directory matches its contents. */ +export function rulesFor(lookup, paths) { + const scored = new Map(); + for (const path of paths) { + const probes = path.isDirectory ? [`${path.path}/x`] : [path.path]; + for (const probe of probes) { + for (const rule of lookup) { + const score = specificity(rule, probe); + if (score < 0) continue; + const entry = scored.get(rule.path); + if (!entry || entry.score < score) scored.set(rule.path, { rule, score }); + } + } + } + return [...scored.values()] + .sort((a, b) => b.score - a.score || a.rule.path.localeCompare(b.rule.path)) + .map((entry) => entry.rule); +} + +/** Repository-relative path for a token, or null when it is outside the repository. */ +export function toRepoPath(token, cwd, root = ROOT) { + if (String(token).length > MAX_PATH_CHARS) return null; + const absolute = isAbsolute(token) ? token : resolve(cwd, token); + const rel = relative(root, absolute); + if (rel === '' || rel.startsWith('..') || isAbsolute(rel)) return null; + const normalized = rel.split('\\').join('/'); + if (normalized.split('/').some((segment) => IGNORED_SEGMENTS.has(segment))) return null; + return normalized; +} + +/** Target paths of an apply_patch body. */ +export function patchPaths(patch) { + const paths = []; + for (const line of String(patch).split('\n')) { + const match = /^\*\*\* (?:Add File|Update File|Delete File|Move to): (.+)$/.exec(line.trim()); + if (match) paths.push(match[1].trim()); + if (paths.length >= MAX_TARGETS) break; + } + return paths; +} + +/** Drop heredoc bodies: they are file content or script text, not path arguments. */ +export function withoutHeredocBodies(text) { + const lines = text.split('\n'); + const kept = []; + let delimiter = null; + for (const line of lines) { + if (delimiter !== null) { + if (line.trim() === delimiter) delimiter = null; + continue; + } + kept.push(line); + const match = /<<-?\s*['"]?([A-Za-z_][A-Za-z0-9_]*)['"]?/.exec(line); + if (match) delimiter = match[1]; + } + return kept.join('\n'); +} + +function shellWords(command) { + // Good enough to find path arguments; not a shell parser. Quotes are stripped, operators + // split words, and anything with expansion syntax is dropped. + return String(command) + .replaceAll(/\\\n/g, ' ') + .split(/[\s;|&()<>]+/) + .map((word) => word.replaceAll(/^['"]+|['"]+$/g, '')) + .filter((word) => word.length > 0); +} + +/** + * Paths a shell command reads or writes, resolved against `cd` steps inside it. A command + * counts as a write when it redirects output, edits in place, or runs a writing command. + */ +export function shellPaths(command, cwd, root = ROOT, exists = defaultExists) { + const text = withoutHeredocBodies(String(command).slice(0, MAX_COMMAND_CHARS)); + const words = shellWords(text).slice(0, MAX_WORDS); + const known = new Map(); + const kindOf = (path) => { + if (!known.has(path)) known.set(path, exists(path)); + return known.get(path); + }; + let base = cwd; + let cdSteps = 0; + const found = []; + for (let index = 0; index < words.length; index++) { + const word = words[index]; + if (word === 'cd' && words[index + 1]) { + const next = words[index + 1]; + if (!/[$`*]/.test(next) && cdSteps < MAX_CD_STEPS && next.length <= MAX_PATH_CHARS) { + base = resolve(base, next); + cdSteps++; + } + index++; + continue; + } + const candidate = word.includes('=') && word.startsWith('-') ? word.split('=')[1] : word; + if (!candidate || candidate.startsWith('-') || /[$`*?{}[\]]/.test(candidate)) continue; + if (!candidate.includes('/') && !candidate.includes('.')) continue; + const absolute = isAbsolute(candidate) ? candidate : resolve(base, candidate); + const repoPath = toRepoPath(absolute, base, root); + if (!repoPath) continue; + const kind = kindOf(absolute); + if (kind) found.push({ path: repoPath, isDirectory: kind === 'dir', exists: true }); + else if (kindOf(dirname(absolute)) === 'dir') { + found.push({ path: repoPath, isDirectory: false, exists: false }); + } + } + const writes = + />>?\s*[^\s&|]/.test( + text.replaceAll(/[0-9]?>&[0-9]/g, '').replaceAll(/>\s*\/dev\/null/g, '') + ) || + /\b(?:sed|perl)\s+(?:-[a-zA-Z]*\s+)*-[a-zA-Z]*i/.test(text) || + /\bgit\s+(?:mv|rm|apply|checkout|restore)\b/.test(text) || + words.some((word) => SHELL_WRITERS.has(word)); + return { paths: dedupe(found).slice(0, MAX_TARGETS), writes }; +} + +function dedupe(paths) { + const seen = new Map(); + for (const entry of paths) if (!seen.has(entry.path)) seen.set(entry.path, entry); + return [...seen.values()]; +} + +function defaultExists(path) { + try { + return statSync(path).isDirectory() ? 'dir' : 'file'; + } catch { + return null; + } +} + +function readRuleBody(rulePath, root) { + const text = readFileSync(join(root, rulePath), 'utf8'); + // Drop the frontmatter: the scope is stated in the header line instead. + return text.replace(/^---\n[\s\S]*?\n---\n/, '').trim(); +} + +/** + * Build the model-visible text for `rules`, delivering whole bodies in order until the + * byte budget is spent, and naming the rest so the model knows they exist (a capped + * selection must disclose what it dropped). + */ +export function renderDelivery(rules, targets, budget, root = ROOT) { + const header = [ + `SAM rule delivery (.codex/hooks/rule-context.mjs). These repository rules govern ${targets + .slice(0, 5) + .map(displayPath) + .join(', ')}${targets.length > 5 ? `, +${targets.length - 5} more` : ''}.`, + 'Claude Code loads them by itself when these files are accessed; treat them as project instructions for this work.', + ].join('\n'); + const parts = [header]; + let used = Buffer.byteLength(header); + const delivered = []; + const deferred = []; + for (const rule of rules) { + let body; + try { + body = readRuleBody(rule.path, root); + } catch { + continue; + } + const block = `\n\n===== ${rule.path} =====\n${body}`; + const size = Buffer.byteLength(block); + if (used + size > budget - 1500) { + deferred.push(rule); + continue; + } + parts.push(block); + used += size; + delivered.push({ rule, bytes: size }); + } + if (deferred.length > 0) { + const lines = deferred + .slice(0, 40) + .map((rule) => `- ${rule.path}: ${rule.title}`) + .join('\n'); + const more = deferred.length > 40 ? `\n- +${deferred.length - 40} more` : ''; + parts.push( + `\n\nAlso governing these paths, not delivered yet because of the per-call size cap. They arrive with your next tool calls on these paths, or run \`node .codex/hooks/rule-context.mjs --show ${targets[0] ? displayPath(targets[0]) : ''}\`:\n${lines}${more}` + ); + } + return { text: parts.join(''), delivered, deferred }; +} + +/** A file-name-safe key; long or unusual ids are shortened and made unique with a hash. */ +export function sessionKey(sessionId) { + const raw = String(sessionId || 'unknown'); + const safe = raw.replaceAll(/[^A-Za-z0-9._-]/g, '_').slice(0, 80); + if (safe === raw) return safe; + return `${safe}-${createHash('sha256').update(raw).digest('hex').slice(0, 12)}`; +} + +function readState(sessionId) { + try { + const state = JSON.parse( + readFileSync(join(STATE_DIR, `${sessionKey(sessionId)}.json`), 'utf8') + ); + return { + epoch: Number(state.epoch) || 0, + delivered: Array.isArray(state.delivered) ? state.delivered : [], + deniedWrites: Array.isArray(state.deniedWrites) ? state.deniedWrites : [], + }; + } catch { + return { epoch: 0, delivered: [], deniedWrites: [] }; + } +} + +function writeState(sessionId, state) { + mkdirSync(STATE_DIR, { recursive: true }); + const file = join(STATE_DIR, `${sessionKey(sessionId)}.json`); + const temporary = `${file}.${process.pid}.tmp`; + writeFileSync(temporary, JSON.stringify(state)); + renameSync(temporary, file); +} + +function log(sessionId, entries) { + if (entries.length === 0) return; + try { + mkdirSync(LOG_DIR, { recursive: true }); + const at = new Date().toISOString(); + const lines = entries.map((entry) => + JSON.stringify({ at, harness: 'codex', session_id: sessionId, ...entry }) + ); + appendFileSync(join(LOG_DIR, `codex-${sessionKey(sessionId)}.jsonl`), `${lines.join('\n')}\n`); + } catch { + // Logging must never fail the hook. + } +} + +function sessionStart(event) { + const source = String(event.source ?? 'startup'); + const state = readState(event.session_id); + let epoch = state.epoch; + if (RESET_SOURCES.has(source) || epoch === 0) { + epoch += 1; + writeState(event.session_id, { epoch, delivered: [], deniedWrites: [] }); + } + log(event.session_id, [{ event: 'SessionStart', source, load_reason: 'session_start', epoch }]); + return { + hookSpecificOutput: { + hookEventName: 'SessionStart', + additionalContext: + 'SAM rule delivery is active. Before a tool call that reads or writes repository files, a hook adds the path-scoped rules (.claude/rules/*.md) that govern those files, if they are not already in your context. The first write to files whose rules you have not seen is refused once with the rules attached: read them, adjust if needed, and retry. The rules every task follows are listed in AGENTS.md under "Rules"; open the ones that bear on your task.', + }, + }; +} + +function preToolUse(event, lookup, budget) { + const tool = String(event.tool_name ?? ''); + const command = event.tool_input?.command ?? ''; + const cwd = typeof event.cwd === 'string' && event.cwd ? event.cwd : ROOT; + let targets; + let writes; + if (tool === 'apply_patch') { + targets = patchPaths(command) + .map((path) => toRepoPath(path, cwd)) + .filter(Boolean) + .map((path) => ({ path, isDirectory: false })); + writes = true; + } else if (tool === 'Bash') { + ({ paths: targets, writes } = shellPaths(command, cwd)); + } else { + return {}; + } + if (targets.length === 0) return {}; + const state = readState(event.session_id); + const delivered = new Set(state.delivered); + const pending = rulesFor(lookup, targets).filter((rule) => !delivered.has(rule.path)); + if (pending.length === 0) return {}; + + const targetPaths = targets.map((target) => target.path); + const rendered = renderDelivery(pending, targetPaths, budget); + if (rendered.delivered.length === 0 && rendered.deferred.length === 0) return {}; + const writeKey = createHash('sha256') + .update(targetPaths.slice().sort().join('\n')) + .digest('hex') + .slice(0, 16); + // Deny only to deliver: a write is refused once, and only when rule text came with it. + const deny = writes && rendered.delivered.length > 0 && !state.deniedWrites.includes(writeKey); + writeState(event.session_id, { + epoch: state.epoch, + delivered: [...delivered, ...rendered.delivered.map((entry) => entry.rule.path)], + deniedWrites: deny ? [...state.deniedWrites, writeKey] : state.deniedWrites, + }); + log( + event.session_id, + rendered.delivered.map((entry) => ({ + event: 'PreToolUse', + tool, + load_reason: 'path_match', + file: entry.rule.path, + trigger: targetPaths[0].slice(0, DISPLAY_PATH_CHARS), + triggers: targetPaths.slice(0, 10).map((path) => path.slice(0, DISPLAY_PATH_CHARS)), + bytes: entry.bytes, + decision: deny ? 'deny_once' : 'allow', + epoch: state.epoch, + tool_use_id: event.tool_use_id ?? null, + })) + ); + const output = { + hookSpecificOutput: { hookEventName: 'PreToolUse', additionalContext: rendered.text }, + }; + if (deny) { + output.hookSpecificOutput.permissionDecision = 'deny'; + output.hookSpecificOutput.permissionDecisionReason = `Not run yet: ${rendered.delivered.length} repository rule(s) governing ${displayPath(targetPaths[0])} were not in your context. They are attached as context. Check this change against them, then run it again (the retry is allowed). If you cannot see the rule text, run: node .codex/hooks/rule-context.mjs --show ${displayPath(targetPaths[0])}`; + } + return output; +} + +function show(paths) { + const lookup = loadLookup(); + const targets = paths + .map((path) => toRepoPath(path, process.cwd())) + .filter(Boolean) + .map((path) => ({ path, isDirectory: defaultExists(join(ROOT, path)) === 'dir' })); + const rules = rulesFor(lookup, targets); + if (rules.length === 0) { + process.stdout.write('No path-scoped rules govern these paths.\n'); + return; + } + process.stdout.write( + `${ + renderDelivery( + rules, + targets.map((t) => t.path), + maxBytes() + ).text + }\n` + ); +} + +function main() { + const args = process.argv.slice(2); + if (args[0] === '--show') { + show(args.slice(1)); + return; + } + let output = {}; + let event = {}; + try { + event = JSON.parse(readFileSync(0, 'utf8') || '{}'); + if (event.hook_event_name === 'SessionStart') output = sessionStart(event); + else if (event.hook_event_name === 'PreToolUse') { + output = preToolUse(event, loadLookup(), maxBytes()); + } + } catch (error) { + output = {}; + log(event.session_id, [ + { + event: String(event.hook_event_name ?? 'unknown'), + load_reason: 'error', + error: String(error?.message ?? error).slice(0, 300), + }, + ]); + } + process.stdout.write(`${JSON.stringify(output)}\n`); +} + +if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + try { + main(); + } catch { + process.stdout.write('{}\n'); + } + process.exitCode = 0; +} diff --git a/.codex/hooks/rule-scopes.json b/.codex/hooks/rule-scopes.json new file mode 100644 index 0000000000..384d17626e --- /dev/null +++ b/.codex/hooks/rule-scopes.json @@ -0,0 +1,1237 @@ +{ + "generatedBy": "pnpm quality:agent-context-budget --write", + "note": "Read by .codex/hooks/rule-context.mjs. Do not edit by hand.", + "rules": [ + { + "path": ".claude/rules/04-ui-standards.md", + "title": "UI Standards", + "patterns": [ + { + "pattern": "apps/web/**", + "regex": "^apps\\/web\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/ui/**", + "regex": "^packages\\/ui\\/.*$", + "literal": 12 + }, + { + "pattern": "packages/acp-client/**", + "regex": "^packages\\/acp-client\\/.*$", + "literal": 20 + }, + { + "pattern": "packages/terminal/**", + "regex": "^packages\\/terminal\\/.*$", + "literal": 18 + }, + { + "pattern": "apps/www/src/content/docs/docs/**", + "regex": "^apps\\/www\\/src\\/content\\/docs\\/docs\\/.*$", + "literal": 31 + } + ] + }, + { + "path": ".claude/rules/06-api-patterns.md", + "title": "API Technical Patterns", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + } + ] + }, + { + "path": ".claude/rules/06-vm-agent-patterns.md", + "title": "VM Agent Technical Patterns", + "patterns": [ + { + "pattern": "packages/cloud-init/**", + "regex": "^packages\\/cloud-init\\/.*$", + "literal": 20 + }, + { + "pattern": "packages/vm-agent/**", + "regex": "^packages\\/vm-agent\\/.*$", + "literal": 18 + }, + { + "pattern": "scripts/vm/**", + "regex": "^scripts\\/vm\\/.*$", + "literal": 11 + } + ] + }, + { + "path": ".claude/rules/15-nav-parity.md", + "title": "Desktop–Mobile Navigation Parity", + "patterns": [ + { + "pattern": "apps/web/src/components/NavSidebar.tsx", + "regex": "^apps\\/web\\/src\\/components\\/NavSidebar\\.tsx(?:\\/.*)?$", + "literal": 38 + }, + { + "pattern": "apps/web/src/components/MobileNavDrawer.tsx", + "regex": "^apps\\/web\\/src\\/components\\/MobileNavDrawer\\.tsx(?:\\/.*)?$", + "literal": 43 + }, + { + "pattern": "apps/web/src/components/AppShell.tsx", + "regex": "^apps\\/web\\/src\\/components\\/AppShell\\.tsx(?:\\/.*)?$", + "literal": 36 + }, + { + "pattern": "apps/web/src/components/chat/SessionLinkedWorkDrawer.tsx", + "regex": "^apps\\/web\\/src\\/components\\/chat\\/SessionLinkedWorkDrawer\\.tsx(?:\\/.*)?$", + "literal": 56 + } + ] + }, + { + "path": ".claude/rules/16-no-page-reload-on-mutation.md", + "title": "No Page Reload on Mutation", + "patterns": [ + { + "pattern": "apps/web/**", + "regex": "^apps\\/web\\/.*$", + "literal": 9 + } + ] + }, + { + "path": ".claude/rules/17-ui-visual-testing.md", + "title": "Mandatory Playwright Visual Testing for UI Changes", + "patterns": [ + { + "pattern": "apps/web/**", + "regex": "^apps\\/web\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/acp-client/**", + "regex": "^packages\\/acp-client\\/.*$", + "literal": 20 + }, + { + "pattern": "packages/terminal/**", + "regex": "^packages\\/terminal\\/.*$", + "literal": 18 + }, + { + "pattern": "packages/ui/**", + "regex": "^packages\\/ui\\/.*$", + "literal": 12 + }, + { + "pattern": "scripts/quality/check-preflight-evidence.ts", + "regex": "^scripts\\/quality\\/check-preflight-evidence\\.ts(?:\\/.*)?$", + "literal": 43 + } + ] + }, + { + "path": ".claude/rules/24-no-duplicate-ui-controls.md", + "title": "No Duplicate Implementations", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "apps/web/**", + "regex": "^apps\\/web\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/operations/**", + "regex": "^packages\\/operations\\/.*$", + "literal": 20 + }, + { + "pattern": "packages/shared/**", + "regex": "^packages\\/shared\\/.*$", + "literal": 16 + } + ] + }, + { + "path": ".claude/rules/26-project-chat-first.md", + "title": "Project Chat First", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "apps/web/**", + "regex": "^apps\\/web\\/.*$", + "literal": 9 + } + ] + }, + { + "path": ".claude/rules/27-vm-agent-staging-refresh.md", + "title": "VM Agent Binary Refresh for Staging Tests", + "patterns": [ + { + "pattern": "packages/vm-agent/**", + "regex": "^packages\\/vm-agent\\/.*$", + "literal": 18 + }, + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + } + ] + }, + { + "path": ".claude/rules/31-migration-safety.md", + "title": "Migration Safety (ABSOLUTE RULE — DATA LOSS PREVENTION)", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/worker-core/**", + "regex": "^packages\\/worker-core\\/.*$", + "literal": 21 + }, + { + "pattern": "packages/project-data/**", + "regex": "^packages\\/project-data\\/.*$", + "literal": 22 + }, + { + "pattern": "packages/ai-proxy/src/ai-token-budget-counter.ts", + "regex": "^packages\\/ai-proxy\\/src\\/ai-token-budget-counter\\.ts(?:\\/.*)?$", + "literal": 48 + }, + { + "pattern": "packages/repo-hosting/src/github-installation-leak-sweep.ts", + "regex": "^packages\\/repo-hosting\\/src\\/github-installation-leak-sweep\\.ts(?:\\/.*)?$", + "literal": 59 + }, + { + "pattern": "infra/resources/database.ts", + "regex": "^infra\\/resources\\/database\\.ts(?:\\/.*)?$", + "literal": 27 + }, + { + "pattern": "scripts/deploy/configure-d1-read-replication.sh", + "regex": "^scripts\\/deploy\\/configure-d1-read-replication\\.sh(?:\\/.*)?$", + "literal": 47 + }, + { + "pattern": "scripts/quality/check-do-migration-safety.ts", + "regex": "^scripts\\/quality\\/check-do-migration-safety\\.ts(?:\\/.*)?$", + "literal": 44 + }, + { + "pattern": "scripts/quality/check-migration-safety.test.ts", + "regex": "^scripts\\/quality\\/check-migration-safety\\.test\\.ts(?:\\/.*)?$", + "literal": 46 + }, + { + "pattern": "scripts/quality/check-migration-safety.ts", + "regex": "^scripts\\/quality\\/check-migration-safety\\.ts(?:\\/.*)?$", + "literal": 41 + }, + { + "pattern": "scripts/quality/d1-read-replication-script.test.ts", + "regex": "^scripts\\/quality\\/d1-read-replication-script\\.test\\.ts(?:\\/.*)?$", + "literal": 50 + } + ] + }, + { + "path": ".claude/rules/32-cf-api-debugging.md", + "title": "Cloudflare API Debugging (Use This Before Guessing)", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + } + ] + }, + { + "path": ".claude/rules/34-vm-agent-callback-auth-agent-side.md", + "title": "VM Agent Callback Routes Must Use Callback JWT Auth (ABSOLUTE RULE)", + "patterns": [ + { + "pattern": "packages/vm-agent/**", + "regex": "^packages\\/vm-agent\\/.*$", + "literal": 18 + }, + { + "pattern": "apps/api/src/routes/deploy-release-callback.ts", + "regex": "^apps\\/api\\/src\\/routes\\/deploy-release-callback\\.ts(?:\\/.*)?$", + "literal": 46 + }, + { + "pattern": "apps/api/src/routes/projects/agent-activity-callback.ts", + "regex": "^apps\\/api\\/src\\/routes\\/projects\\/agent-activity-callback\\.ts(?:\\/.*)?$", + "literal": 55 + } + ] + }, + { + "path": ".claude/rules/34-vm-agent-callback-auth.md", + "title": "VM Agent Callback Routes Must Use Callback JWT Auth (ABSOLUTE RULE)", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/ai-proxy/**", + "regex": "^packages\\/ai-proxy\\/.*$", + "literal": 18 + }, + { + "pattern": "packages/vm-agent/**", + "regex": "^packages\\/vm-agent\\/.*$", + "literal": 18 + } + ] + }, + { + "path": ".claude/rules/36-cli-quality.md", + "title": "CLI Quality Bar", + "patterns": [ + { + "pattern": "packages/cli/**", + "regex": "^packages\\/cli\\/.*$", + "literal": 13 + }, + { + "pattern": ".github/workflows/ci.yml", + "regex": "^\\.github\\/workflows\\/ci\\.yml(?:\\/.*)?$", + "literal": 24 + }, + { + "pattern": "sonar-project.properties", + "regex": "^(?:[^/]+\\/)*sonar-project\\.properties(?:\\/.*)?$", + "literal": 24 + } + ] + }, + { + "path": ".claude/rules/37-prototype-development.md", + "title": "Prototype Development", + "patterns": [ + { + "pattern": "apps/web/**", + "regex": "^apps\\/web\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/ui/src/tokens/theme.css", + "regex": "^packages\\/ui\\/src\\/tokens\\/theme\\.css(?:\\/.*)?$", + "literal": 32 + } + ] + }, + { + "path": ".claude/rules/40-sentinel-rows-excluded-from-counts.md", + "title": "Internal/Sentinel Rows Must Be Excluded From Business-Logic Counts", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + } + ] + }, + { + "path": ".claude/rules/43-long-running-mcp-tools.md", + "title": "Long-Running MCP Tools Must Be Async", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/operations/**", + "regex": "^packages\\/operations\\/.*$", + "literal": 20 + }, + { + "pattern": "packages/vm-agent/internal/server/mcp_build.go", + "regex": "^packages\\/vm-agent\\/internal\\/server\\/mcp_build\\.go(?:\\/.*)?$", + "literal": 46 + } + ] + }, + { + "path": ".claude/rules/44-dual-write-migration-enumerate-writers.md", + "title": "Storage Migrations Must Enumerate Every Writer of the Migrated Data", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/project-data/**", + "regex": "^packages\\/project-data\\/.*$", + "literal": 22 + }, + { + "pattern": "packages/worker-core/**", + "regex": "^packages\\/worker-core\\/.*$", + "literal": 21 + } + ] + }, + { + "path": ".claude/rules/45-durable-object-concurrency-mutex.md", + "title": "Durable Objects Do Not Serialize Across `await` — Use a Real Mutex for Critical Sections", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/project-data/**", + "regex": "^packages\\/project-data\\/.*$", + "literal": 22 + }, + { + "pattern": "packages/ai-proxy/src/ai-token-budget-counter.ts", + "regex": "^packages\\/ai-proxy\\/src\\/ai-token-budget-counter\\.ts(?:\\/.*)?$", + "literal": 48 + } + ] + }, + { + "path": ".claude/rules/46-vm-agent-diagnostic-getter-sync.md", + "title": "VM Agent Diagnostic Getters Must Synchronize Loop-Mutated Fields", + "patterns": [ + { + "pattern": "packages/vm-agent/**", + "regex": "^packages\\/vm-agent\\/.*$", + "literal": 18 + } + ] + }, + { + "path": ".claude/rules/47-control-loop-io-budget.md", + "title": "Control Loops Need Explicit I/O Budgets", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/project-data/**", + "regex": "^packages\\/project-data\\/.*$", + "literal": 22 + }, + { + "pattern": "packages/ai-proxy/src/ai-monthly-cost-cron.ts", + "regex": "^packages\\/ai-proxy\\/src\\/ai-monthly-cost-cron\\.ts(?:\\/.*)?$", + "literal": 45 + }, + { + "pattern": "packages/app-deployment/src/scheduled/**", + "regex": "^packages\\/app-deployment\\/src\\/scheduled\\/.*$", + "literal": 38 + }, + { + "pattern": "packages/repo-hosting/src/github-installation-leak-sweep.ts", + "regex": "^packages\\/repo-hosting\\/src\\/github-installation-leak-sweep\\.ts(?:\\/.*)?$", + "literal": 59 + }, + { + "pattern": "packages/agent-email/src/recovery.ts", + "regex": "^packages\\/agent-email\\/src\\/recovery\\.ts(?:\\/.*)?$", + "literal": 36 + } + ] + }, + { + "path": ".claude/rules/48-stale-while-revalidate-ui.md", + "title": "Stale-While-Revalidate UI (No Hiding, No Refetch Loops)", + "patterns": [ + { + "pattern": "apps/web/**", + "regex": "^apps\\/web\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/acp-client/**", + "regex": "^packages\\/acp-client\\/.*$", + "literal": 20 + } + ] + }, + { + "path": ".claude/rules/49-capture-prerequisites-before-async-completion.md", + "title": "Capture Handler Prerequisites Before a Long Async Operation", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/project-data/**", + "regex": "^packages\\/project-data\\/.*$", + "literal": 22 + }, + { + "pattern": "packages/vm-agent/internal/acp/session_host_prompt.go", + "regex": "^packages\\/vm-agent\\/internal\\/acp\\/session_host_prompt\\.go(?:\\/.*)?$", + "literal": 53 + } + ] + }, + { + "path": ".claude/rules/50-list-read-row-fault-isolation.md", + "title": "List/Snapshot Reads Must Tolerate a Single Malformed Row", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/project-data/**", + "regex": "^packages\\/project-data\\/.*$", + "literal": 22 + }, + { + "pattern": "packages/operations/**", + "regex": "^packages\\/operations\\/.*$", + "literal": 20 + }, + { + "pattern": "packages/worker-core/src/row-parsing.ts", + "regex": "^packages\\/worker-core\\/src\\/row-parsing\\.ts(?:\\/.*)?$", + "literal": 39 + } + ] + }, + { + "path": ".claude/rules/51-runtime-boundary-validation.md", + "title": "Runtime boundary validation", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/worker-core/**", + "regex": "^packages\\/worker-core\\/.*$", + "literal": 21 + }, + { + "pattern": "packages/scheduler-core/**", + "regex": "^packages\\/scheduler-core\\/.*$", + "literal": 24 + }, + { + "pattern": "packages/project-data/**", + "regex": "^packages\\/project-data\\/.*$", + "literal": 22 + }, + { + "pattern": "packages/operations/**", + "regex": "^packages\\/operations\\/.*$", + "literal": 20 + }, + { + "pattern": "packages/app-deployment/**", + "regex": "^packages\\/app-deployment\\/.*$", + "literal": 24 + }, + { + "pattern": "packages/ai-proxy/**", + "regex": "^packages\\/ai-proxy\\/.*$", + "literal": 18 + }, + { + "pattern": "packages/agent-email/**", + "regex": "^packages\\/agent-email\\/.*$", + "literal": 21 + }, + { + "pattern": "packages/repo-hosting/**", + "regex": "^packages\\/repo-hosting\\/.*$", + "literal": 22 + }, + { + "pattern": "scripts/quality/type-boundary-baseline.json", + "regex": "^scripts\\/quality\\/type-boundary-baseline\\.json(?:\\/.*)?$", + "literal": 43 + } + ] + }, + { + "path": ".claude/rules/51-server-side-node-class-gates.md", + "title": "Server-Side Node-Class / Identity Gates — Never Trust a Client-Supplied Identifier or Agent Abstention", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/scheduler-core/**", + "regex": "^packages\\/scheduler-core\\/.*$", + "literal": 24 + }, + { + "pattern": "packages/operations/**", + "regex": "^packages\\/operations\\/.*$", + "literal": 20 + } + ] + }, + { + "path": ".claude/rules/51-vm-agent-no-host-mime-dependency.md", + "title": "VM Agent Behavior Must Not Depend on Host-Provided MIME/OS Databases", + "patterns": [ + { + "pattern": "packages/vm-agent/**", + "regex": "^packages\\/vm-agent\\/.*$", + "literal": 18 + }, + { + "pattern": "packages/shared/src/mime.ts", + "regex": "^packages\\/shared\\/src\\/mime\\.ts(?:\\/.*)?$", + "literal": 27 + } + ] + }, + { + "path": ".claude/rules/52-model-catalog-lifecycle.md", + "title": "Model Catalog Lifecycle (Adding and Retiring Provider Models)", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/shared/**", + "regex": "^packages\\/shared\\/.*$", + "literal": 16 + }, + { + "pattern": "packages/ai-proxy/**", + "regex": "^packages\\/ai-proxy\\/.*$", + "literal": 18 + } + ] + }, + { + "path": ".claude/rules/53-scheduled-handler-isolation-and-liveness-signals.md", + "title": "Scheduled Handlers: Isolate Every Step, and Never Use a Liveness Timestamp as an Idleness Signal", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/project-data/**", + "regex": "^packages\\/project-data\\/.*$", + "literal": 22 + }, + { + "pattern": "packages/vm-agent/internal/deploy/artifact_client.go", + "regex": "^packages\\/vm-agent\\/internal\\/deploy\\/artifact_client\\.go(?:\\/.*)?$", + "literal": 52 + }, + { + "pattern": "packages/vm-agent/internal/deploy/compose.go", + "regex": "^packages\\/vm-agent\\/internal\\/deploy\\/compose\\.go(?:\\/.*)?$", + "literal": 44 + }, + { + "pattern": "packages/vm-agent/internal/server/health.go", + "regex": "^packages\\/vm-agent\\/internal\\/server\\/health\\.go(?:\\/.*)?$", + "literal": 43 + }, + { + "pattern": "packages/ai-proxy/src/ai-monthly-cost-cron.ts", + "regex": "^packages\\/ai-proxy\\/src\\/ai-monthly-cost-cron\\.ts(?:\\/.*)?$", + "literal": 45 + }, + { + "pattern": "packages/app-deployment/src/scheduled/**", + "regex": "^packages\\/app-deployment\\/src\\/scheduled\\/.*$", + "literal": 38 + }, + { + "pattern": "packages/repo-hosting/src/github-installation-leak-sweep.ts", + "regex": "^packages\\/repo-hosting\\/src\\/github-installation-leak-sweep\\.ts(?:\\/.*)?$", + "literal": 59 + }, + { + "pattern": "packages/agent-email/src/recovery.ts", + "regex": "^packages\\/agent-email\\/src\\/recovery\\.ts(?:\\/.*)?$", + "literal": 36 + } + ] + }, + { + "path": ".claude/rules/54-vm-agent-rollout-compatibility.md", + "title": "VM Agent Rollout Compatibility", + "patterns": [ + { + "pattern": "packages/vm-agent/**", + "regex": "^packages\\/vm-agent\\/.*$", + "literal": 18 + }, + { + "pattern": "scripts/deploy/resolve-vm-agent-release.sh", + "regex": "^scripts\\/deploy\\/resolve-vm-agent-release\\.sh(?:\\/.*)?$", + "literal": 42 + }, + { + "pattern": "scripts/quality/deploy-reusable-workflow.test.ts", + "regex": "^scripts\\/quality\\/deploy-reusable-workflow\\.test\\.ts(?:\\/.*)?$", + "literal": 48 + } + ] + }, + { + "path": ".claude/rules/55-runaway-cost-emergency-ops.md", + "title": "Runaway-Cost Emergency Operations", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + } + ] + }, + { + "path": ".claude/rules/56-clipped-overflow-is-invisible-to-document-checks.md", + "title": "Horizontal Overflow Inside `overflow-x-hidden` Is Invisible to Document-Level Checks", + "patterns": [ + { + "pattern": "apps/web/**", + "regex": "^apps\\/web\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/acp-client/**", + "regex": "^packages\\/acp-client\\/.*$", + "literal": 20 + }, + { + "pattern": "packages/terminal/**", + "regex": "^packages\\/terminal\\/.*$", + "literal": 18 + }, + { + "pattern": "packages/ui/**", + "regex": "^packages\\/ui\\/.*$", + "literal": 12 + } + ] + }, + { + "path": ".claude/rules/56-destructive-provider-ownership-proof.md", + "title": "Destructive Provider Ownership Proof", + "patterns": [ + { + "pattern": "packages/providers/**", + "regex": "^packages\\/providers\\/.*$", + "literal": 19 + } + ] + }, + { + "path": ".claude/rules/57-write-only-cross-boundary-state.md", + "title": "Cross-Boundary State With Multiple Consumers Must Be Reconciled, Not Just Reported", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/project-data/**", + "regex": "^packages\\/project-data\\/.*$", + "literal": 22 + } + ] + }, + { + "path": ".claude/rules/58-terminal-verdicts-must-match-the-resumer.md", + "title": "A \"Work Is Unrecoverable\" Verdict Must Read The Same Record The Resumer Reads", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/project-data/src/do/reconciliation-dead-target.ts", + "regex": "^packages\\/project-data\\/src\\/do\\/reconciliation-dead-target\\.ts(?:\\/.*)?$", + "literal": 58 + } + ] + }, + { + "path": ".claude/rules/61-guards-must-cover-every-runtime.md", + "title": "A Guard Added for One Runtime Must Be Enforced for Every Runtime", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/vm-agent/**", + "regex": "^packages\\/vm-agent\\/.*$", + "literal": 18 + } + ] + }, + { + "path": ".claude/rules/61-per-cycle-budget-counters.md", + "title": "Per-Cycle Budget Counters Must Reset on Success", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/project-data/**", + "regex": "^packages\\/project-data\\/.*$", + "literal": 22 + } + ] + }, + { + "path": ".claude/rules/63-widening-a-table-can-delete-an-auth-check.md", + "title": "Making a Scoping Column Nullable Silently Deletes Every Check That Used It", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/worker-core/**", + "regex": "^packages\\/worker-core\\/.*$", + "literal": 21 + }, + { + "pattern": "packages/project-data/**", + "regex": "^packages\\/project-data\\/.*$", + "literal": 22 + }, + { + "pattern": "packages/operations/**", + "regex": "^packages\\/operations\\/.*$", + "literal": 20 + } + ] + }, + { + "path": ".claude/rules/64-unstable-prop-identity-remounts-subtrees.md", + "title": "An Object Literal in a Render Body Can Remount an Entire Subtree", + "patterns": [ + { + "pattern": "apps/web/**", + "regex": "^apps\\/web\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/acp-client/**", + "regex": "^packages\\/acp-client\\/.*$", + "literal": 20 + }, + { + "pattern": "packages/terminal/**", + "regex": "^packages\\/terminal\\/.*$", + "literal": 18 + }, + { + "pattern": "packages/ui/**", + "regex": "^packages\\/ui\\/.*$", + "literal": 12 + }, + { + "pattern": "packages/eslint-plugin-sam/src/rules/no-inline-markdown-components.js", + "regex": "^packages\\/eslint-plugin-sam\\/src\\/rules\\/no-inline-markdown-components\\.js(?:\\/.*)?$", + "literal": 69 + } + ] + }, + { + "path": ".claude/rules/65-capped-selection-must-rank-and-disclose.md", + "title": "A Capped Selection Must Rank By Its Purpose, And Must Disclose What It Dropped", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/project-data/**", + "regex": "^packages\\/project-data\\/.*$", + "literal": 22 + }, + { + "pattern": "packages/operations/**", + "regex": "^packages\\/operations\\/.*$", + "literal": 20 + }, + { + "pattern": "packages/shared/src/types/comments.ts", + "regex": "^packages\\/shared\\/src\\/types\\/comments\\.ts(?:\\/.*)?$", + "literal": 37 + } + ] + }, + { + "path": ".claude/rules/66-ownership-handoff-must-record-the-supersession.md", + "title": "An Ownership Handoff Must Record That It Happened", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + } + ] + }, + { + "path": ".claude/rules/67-shared-predicates-that-trigger-actions.md", + "title": "Never Widen a Shared Predicate That Drives an Action", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/vm-agent/internal/server/session_snapshot_coordinator.go", + "regex": "^packages\\/vm-agent\\/internal\\/server\\/session_snapshot_coordinator\\.go(?:\\/.*)?$", + "literal": 65 + }, + { + "pattern": "packages/operations/src/idea-identity.ts", + "regex": "^packages\\/operations\\/src\\/idea-identity\\.ts(?:\\/.*)?$", + "literal": 40 + }, + { + "pattern": "packages/vm-agent/internal/server/session_snapshot_coordinator_test.go", + "regex": "^packages\\/vm-agent\\/internal\\/server\\/session_snapshot_coordinator_test\\.go(?:\\/.*)?$", + "literal": 70 + }, + { + "pattern": "packages/vm-agent/internal/server/session_snapshot_errors.go", + "regex": "^packages\\/vm-agent\\/internal\\/server\\/session_snapshot_errors\\.go(?:\\/.*)?$", + "literal": 60 + }, + { + "pattern": "packages/vm-agent/internal/server/workspace_provisioning.go", + "regex": "^packages\\/vm-agent\\/internal\\/server\\/workspace_provisioning\\.go(?:\\/.*)?$", + "literal": 59 + } + ] + }, + { + "path": ".claude/rules/68-event-scoped-filter-predicates.md", + "title": "Event-Scoped Filters Must Encode Their Scope", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/project-data/**", + "regex": "^packages\\/project-data\\/.*$", + "literal": 22 + } + ] + }, + { + "path": ".claude/rules/69-aggregate-capacity-at-final-reservation.md", + "title": "Enforce Aggregate Capacity at the Final Atomic Reservation", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/providers/**", + "regex": "^packages\\/providers\\/.*$", + "literal": 19 + }, + { + "pattern": "packages/scheduler-core/**", + "regex": "^packages\\/scheduler-core\\/.*$", + "literal": 24 + } + ] + }, + { + "path": ".claude/rules/69-emergency-config-paths-need-their-own-coverage.md", + "title": "A Code Path That Only Activates Under an Emergency Configuration Needs Tests In That Configuration", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/project-data/**", + "regex": "^packages\\/project-data\\/.*$", + "literal": 22 + }, + { + "pattern": "packages/worker-core/src/d1-limits.ts", + "regex": "^packages\\/worker-core\\/src\\/d1-limits\\.ts(?:\\/.*)?$", + "literal": 37 + } + ] + }, + { + "path": ".claude/rules/70-flag-flips-must-verify-the-deployed-value.md", + "title": "A Config Flip Ships Only When the Deployed Value Says So", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": ".github/workflows/deploy-reusable.yml", + "regex": "^\\.github\\/workflows\\/deploy-reusable\\.yml(?:\\/.*)?$", + "literal": 37 + }, + { + "pattern": "scripts/deploy/environment-var-overrides.ts", + "regex": "^scripts\\/deploy\\/environment-var-overrides\\.ts(?:\\/.*)?$", + "literal": 43 + }, + { + "pattern": "scripts/deploy/sync-wrangler-config.ts", + "regex": "^scripts\\/deploy\\/sync-wrangler-config\\.ts(?:\\/.*)?$", + "literal": 38 + }, + { + "pattern": "scripts/deploy/worker-var-defaults.ts", + "regex": "^scripts\\/deploy\\/worker-var-defaults\\.ts(?:\\/.*)?$", + "literal": 37 + }, + { + "pattern": "packages/project-data/src/do/tool-payload-cleanup-config-refusal.ts", + "regex": "^packages\\/project-data\\/src\\/do\\/tool-payload-cleanup-config-refusal\\.ts(?:\\/.*)?$", + "literal": 67 + }, + { + "pattern": "scripts/deploy/configure-d1-read-replication.sh", + "regex": "^scripts\\/deploy\\/configure-d1-read-replication\\.sh(?:\\/.*)?$", + "literal": 47 + } + ] + }, + { + "path": ".claude/rules/71-request-context-must-not-outlive-its-request.md", + "title": "A Goroutine That Outlives Its Request Must Not Capture That Request's Context", + "patterns": [ + { + "pattern": "packages/providers/**", + "regex": "^packages\\/providers\\/.*$", + "literal": 19 + }, + { + "pattern": "packages/vm-agent/**", + "regex": "^packages\\/vm-agent\\/.*$", + "literal": 18 + } + ] + }, + { + "path": ".claude/rules/71-tightening-a-column-can-delete-a-capability.md", + "title": "A New Required Column Can Silently Delete a Capability for Every Existing Row", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/worker-core/**", + "regex": "^packages\\/worker-core\\/.*$", + "literal": 21 + }, + { + "pattern": "packages/project-data/**", + "regex": "^packages\\/project-data\\/.*$", + "literal": 22 + } + ] + }, + { + "path": ".claude/rules/72-error-categories-must-match-the-recovery-action.md", + "title": "An Error Category Must Name the Recovery Action, Not the Provider's Vocabulary", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/providers/**", + "regex": "^packages\\/providers\\/.*$", + "literal": 19 + } + ] + }, + { + "path": ".claude/rules/73-optional-struct-fields-must-not-overwrite-on-absence.md", + "title": "A Zero-Valued Optional Field Must Not Overwrite Existing State", + "patterns": [ + { + "pattern": "**/*.go", + "regex": "^(?:[^/]+\\/)*[^/]*\\.go$", + "literal": 4 + }, + { + "pattern": "**/*.ts", + "regex": "^(?:[^/]+\\/)*[^/]*\\.ts$", + "literal": 4 + }, + { + "pattern": "**/*.tsx", + "regex": "^(?:[^/]+\\/)*[^/]*\\.tsx$", + "literal": 5 + }, + { + "pattern": "**/*.sql", + "regex": "^(?:[^/]+\\/)*[^/]*\\.sql$", + "literal": 5 + } + ] + }, + { + "path": ".claude/rules/75-external-api-check-then-act.md", + "title": "A Conflict From a Remote Uniqueness Constraint Is a Signal, Not a Failure", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/repo-hosting/**", + "regex": "^packages\\/repo-hosting\\/.*$", + "literal": 22 + }, + { + "pattern": "packages/app-deployment/**", + "regex": "^packages\\/app-deployment\\/.*$", + "literal": 24 + }, + { + "pattern": "packages/vm-agent/internal/server/vm_jobs.go", + "regex": "^packages\\/vm-agent\\/internal\\/server\\/vm_jobs\\.go(?:\\/.*)?$", + "literal": 44 + } + ] + }, + { + "path": ".claude/rules/77-library-extension-points-typed-and-exercised.md", + "title": "Implement a Library Extension Point Against the Library's Types, and Test It Through the Library", + "patterns": [ + { + "pattern": "apps/api/**", + "regex": "^apps\\/api\\/.*$", + "literal": 9 + } + ] + }, + { + "path": ".claude/rules/78-snapshot-capture-must-scale-with-the-session.md", + "title": "Snapshot Capture Cost Must Scale With the Session, Not the Repository", + "patterns": [ + { + "pattern": "packages/vm-agent/**", + "regex": "^packages\\/vm-agent\\/.*$", + "literal": 18 + }, + { + "pattern": "apps/api/src/services/session-snapshot-capture-cleanup.ts", + "regex": "^apps\\/api\\/src\\/services\\/session-snapshot-capture-cleanup\\.ts(?:\\/.*)?$", + "literal": 57 + } + ] + }, + { + "path": ".claude/rules/79-new-enum-values-audit-every-denylist.md", + "title": "A New Value in a Shared Status Enum Must Audit Every Denylist Over That Enum", + "patterns": [ + { + "pattern": "apps/web/**", + "regex": "^apps\\/web\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/shared/**", + "regex": "^packages\\/shared\\/.*$", + "literal": 16 + } + ] + }, + { + "path": ".claude/rules/80-sam-glass.md", + "title": "SAM Glass", + "patterns": [ + { + "pattern": "apps/web/**", + "regex": "^apps\\/web\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/ui/**", + "regex": "^packages\\/ui\\/.*$", + "literal": 12 + } + ] + }, + { + "path": ".claude/rules/82-typed-cards-every-harness.md", + "title": "A Typed Chat Card Must Render for Every Agent Harness", + "patterns": [ + { + "pattern": "apps/web/**", + "regex": "^apps\\/web\\/.*$", + "literal": 9 + }, + { + "pattern": "packages/shared/src/typed-chat-cards.ts", + "regex": "^packages\\/shared\\/src\\/typed-chat-cards\\.ts(?:\\/.*)?$", + "literal": 39 + } + ] + } + ] +} diff --git a/.gitignore b/.gitignore index 5604864c71..532d586ebf 100644 --- a/.gitignore +++ b/.gitignore @@ -67,6 +67,8 @@ pnpm-debug.log* # committed. Ignore ALL of .codex/ and track ONLY the config we author by hand. .codex/* !.codex/config.toml +# Repository hook scripts named by config.toml (see scripts/quality/README.md, "Codex hooks"). +!.codex/hooks/ # Playwright audit screenshots write under apps/web cwd, not the repo root **/.codex/tmp/ # Throwaway Playwright specs, e.g. blog UI captures (apps/www/src/content/CLAUDE.md) diff --git a/package.json b/package.json index 0af47daefa..8de978147e 100644 --- a/package.json +++ b/package.json @@ -72,7 +72,7 @@ "check:fast": "pnpm format:check && pnpm lint:oxlint && pnpm lint && pnpm quality:type-boundaries && pnpm quality:runtime-state-files", "quality:agent-context-budget": "tsx scripts/quality/check-agent-context-budget.ts", "quality:go-optional-fields": "cd scripts/quality/go-optional-fields && go test ./... && go run . ../../..", - "quality:agent-tooling:test": "vitest run --config scripts/quality/vitest.config.ts agent-instructions.test.ts agent-codex-hook-config.test.ts agent-stop-gate.test.ts", + "quality:agent-tooling:test": "vitest run --config scripts/quality/vitest.config.ts agent-instructions.test.ts agent-codex-hook-config.test.ts agent-codex-rule-context.test.ts agent-stop-gate.test.ts", "test:e2e:provider-limits": "node scripts/e2e/provider-limit-path.mjs" }, "dependencies": { diff --git a/scripts/quality/agent-codex-rule-context.test.ts b/scripts/quality/agent-codex-rule-context.test.ts new file mode 100644 index 0000000000..22a5f41df5 --- /dev/null +++ b/scripts/quality/agent-codex-rule-context.test.ts @@ -0,0 +1,485 @@ +/** + * The Codex rule-delivery hook (.codex/hooks/rule-context.mjs), driven the way Codex runs + * it: JSON on stdin, JSON on stdout, against a fixture repository with a generated lookup. + */ +import { spawnSync } from 'node:child_process'; +import { + copyFileSync, + existsSync, + mkdirSync, + mkdtempSync, + readdirSync, + readFileSync, + realpathSync, + rmSync, + writeFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join, resolve } from 'node:path'; + +import TOML from '@iarna/toml'; +import { afterEach, describe, expect, it } from 'vitest'; + +import { codexRuleScopes, renderCodexRuleScopes } from './agent-codex-rule-scopes'; +import { InstructionModel, parseRuleFile } from './agent-instructions'; + +const ROOT = resolve(import.meta.dirname, '../..'); +const HOOK = '.codex/hooks/rule-context.mjs'; + +const created: string[] = []; +afterEach(() => { + for (const dir of created.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +/** A small repository: the real hook, three scoped rules, and their generated lookup. */ +function fixtureRepo(extraRules: { path: string; text: string }[] = []): string { + // realpath: the hook derives its root from its own (resolved) location. + const repo = realpathSync(mkdtempSync(join(tmpdir(), 'codex-rules-'))); + created.push(repo); + const rules = [ + { + path: '.claude/rules/10-api.md', + text: "---\npaths:\n - 'apps/api/**'\n---\n\n# API Rule\n\nAPI-RULE-CANARY applies to the API.\n", + }, + { + path: '.claude/rules/20-go.md', + text: "---\npaths:\n - '**/*.go'\n---\n\n# Go Rule\n\nGO-RULE-CANARY applies to Go.\n", + }, + { + path: '.claude/rules/30-route.md', + text: "---\npaths:\n - 'apps/api/src/routes/special.ts'\n---\n\n# Special Route\n\nSPECIAL-CANARY.\n", + }, + { + path: '.claude/rules/01-launch.md', + text: '# Launch Rule\n\nLAUNCH-CANARY loads at launch.\n', + }, + ...extraRules, + ]; + for (const rule of rules) { + mkdirSync(dirname(join(repo, rule.path)), { recursive: true }); + writeFileSync(join(repo, rule.path), rule.text); + } + const model = new InstructionModel( + rules.map((rule) => parseRuleFile(rule.path, rule.text)), + { claude: null, agents: null } + ); + mkdirSync(join(repo, '.codex/hooks'), { recursive: true }); + copyFileSync(join(ROOT, HOOK), join(repo, HOOK)); + writeFileSync(join(repo, '.codex/hooks/rule-scopes.json'), renderCodexRuleScopes(model)); + for (const file of ['apps/api/src/routes/special.ts', 'apps/api/wrangler.toml', 'pkg/main.go']) { + mkdirSync(dirname(join(repo, file)), { recursive: true }); + writeFileSync(join(repo, file), 'content\n'); + } + return repo; +} + +interface HookOutput { + hookSpecificOutput?: { + hookEventName?: string; + additionalContext?: string; + permissionDecision?: string; + permissionDecisionReason?: string; + }; +} + +function hook( + repo: string, + event: Record, + env: Record = {} +): { status: number | null; output: HookOutput; raw: string } { + const result = spawnSync('node', [join(repo, HOOK)], { + cwd: repo, + input: JSON.stringify({ session_id: 'sess', cwd: repo, ...event }), + encoding: 'utf8', + env: { ...process.env, ...env }, + }); + return { + status: result.status, + output: JSON.parse(result.stdout) as HookOutput, + raw: result.stdout, + }; +} + +const bash = (command: string) => ({ + hook_event_name: 'PreToolUse', + tool_name: 'Bash', + tool_input: { command }, +}); +const patch = (body: string) => ({ + hook_event_name: 'PreToolUse', + tool_name: 'apply_patch', + tool_input: { command: `*** Begin Patch\n${body}\n*** End Patch\n` }, +}); +const context = (run: { output: HookOutput }) => + run.output.hookSpecificOutput?.additionalContext ?? ''; +const decision = (run: { output: HookOutput }) => run.output.hookSpecificOutput?.permissionDecision; + +describe('Codex rule-context hook', () => { + it('announces delivery at session start and logs it', () => { + const repo = fixtureRepo(); + const run = hook(repo, { hook_event_name: 'SessionStart', source: 'startup' }); + expect(run.status).toBe(0); + expect(context(run)).toContain('SAM rule delivery is active'); + const log = readFileSync(join(repo, '.tmp/instruction-loads/codex-sess.jsonl'), 'utf8'); + expect(log).toContain('"load_reason":"session_start"'); + }); + + it('existing file read through the shell: rule bodies arrive, the command is allowed', () => { + const repo = fixtureRepo(); + hook(repo, { hook_event_name: 'SessionStart', source: 'startup' }); + const run = hook(repo, bash('sed -n 1,5p apps/api/src/routes/special.ts')); + expect(decision(run)).toBeUndefined(); + const text = context(run); + expect(text).toContain('SPECIAL-CANARY'); + expect(text).toContain('API-RULE-CANARY'); + // Most specific scope first. + expect(text.indexOf('SPECIAL-CANARY')).toBeLessThan(text.indexOf('API-RULE-CANARY')); + // Launch rules are not path-scoped and never come from the hook; frontmatter is stripped. + expect(text).not.toContain('LAUNCH-CANARY'); + expect(text).not.toContain('paths:'); + // Delivered once per epoch. + expect(hook(repo, bash('cat apps/api/src/routes/special.ts')).output).toEqual({}); + }); + + it('new file through apply_patch: refused once with the rules attached, then allowed', () => { + const repo = fixtureRepo(); + hook(repo, { hook_event_name: 'SessionStart', source: 'startup' }); + const first = hook(repo, patch('*** Add File: apps/api/src/routes/new.ts\n+export {};')); + expect(decision(first)).toBe('deny'); + expect(first.output.hookSpecificOutput?.permissionDecisionReason).toContain( + 'apps/api/src/routes/new.ts' + ); + expect(context(first)).toContain('API-RULE-CANARY'); + const retry = hook(repo, patch('*** Add File: apps/api/src/routes/new.ts\n+export {};')); + expect(retry.output).toEqual({}); + }); + + it('shell-only write: refused once with the rules attached', () => { + const repo = fixtureRepo(); + const first = hook(repo, bash("printf 'x' > pkg/new.go")); + expect(decision(first)).toBe('deny'); + expect(context(first)).toContain('GO-RULE-CANARY'); + expect(hook(repo, bash("printf 'x' > pkg/new.go")).output).toEqual({}); + }); + + it('control: a path no rule governs gets nothing', () => { + const repo = fixtureRepo(); + mkdirSync(join(repo, 'docs'), { recursive: true }); + writeFileSync(join(repo, 'docs/readme.txt'), 'x'); + expect(hook(repo, bash('cat docs/readme.txt')).output).toEqual({}); + expect(hook(repo, patch('*** Add File: docs/new.txt\n+x')).output).toEqual({}); + }); + + it('a directory argument delivers the rules for its contents', () => { + const repo = fixtureRepo(); + expect(context(hook(repo, bash('ls apps/api')))).toContain('API-RULE-CANARY'); + }); + + it('ignores paths outside the repository and in ignored directories', () => { + const repo = fixtureRepo(); + expect(hook(repo, bash('cat /etc/hostname ../../outside.go')).output).toEqual({}); + expect(hook(repo, bash('ls node_modules/x/y.go .tmp/z.go')).output).toEqual({}); + }); + + it('compaction starts a new epoch, so rules are delivered again', () => { + const repo = fixtureRepo(); + hook(repo, { hook_event_name: 'SessionStart', source: 'startup' }); + expect(context(hook(repo, bash('cat pkg/main.go')))).toContain('GO-RULE-CANARY'); + expect(hook(repo, bash('cat pkg/main.go')).output).toEqual({}); + hook(repo, { hook_event_name: 'SessionStart', source: 'resume' }); + expect(hook(repo, bash('cat pkg/main.go')).output).toEqual({}); + hook(repo, { hook_event_name: 'SessionStart', source: 'compact' }); + expect(context(hook(repo, bash('cat pkg/main.go')))).toContain('GO-RULE-CANARY'); + }); + + it('bounds its output and discloses rules it did not deliver yet', () => { + const big = Array.from({ length: 12 }, (_, index) => ({ + path: `.claude/rules/9${index.toString().padStart(2, '0')}-big.md`, + text: `---\npaths:\n - 'apps/api/**'\n---\n\n# Big ${index}\n\nBIG-${index} ${'word '.repeat(1200)}\n`, + })); + const repo = fixtureRepo(big); + const budget = '20000'; + const first = hook(repo, bash('cat apps/api/wrangler.toml'), { + SAM_CODEX_RULE_CONTEXT_MAX_BYTES: budget, + }); + const text = context(first); + expect(Buffer.byteLength(text)).toBeLessThanOrEqual(Number(budget)); + expect(text).toContain('not delivered yet'); + // The remainder arrives on later calls until every rule has been delivered. + const delivered = new Set(); + let run = first; + for (let call = 0; call < 10 && context(run) !== ''; call++) { + for (const match of context(run).matchAll(/===== (\S+) =====/g)) + delivered.add(match[1] ?? ''); + run = hook(repo, bash('cat apps/api/wrangler.toml'), { + SAM_CODEX_RULE_CONTEXT_MAX_BYTES: budget, + }); + } + expect(delivered.size).toBe(13); + }); + + it('never fails the session: malformed input or a missing lookup prints {}', () => { + const repo = fixtureRepo(); + const malformed = spawnSync('node', [join(repo, HOOK)], { + input: 'not json', + encoding: 'utf8', + }); + expect(malformed.status).toBe(0); + expect(JSON.parse(malformed.stdout)).toEqual({}); + writeFileSync(join(repo, '.codex/hooks/rule-scopes.json'), '{'); + const broken = hook(repo, bash('cat pkg/main.go')); + expect(broken.status).toBe(0); + expect(broken.output).toEqual({}); + }); + + it('the --show command prints the rules for a path', () => { + const repo = fixtureRepo(); + const result = spawnSync('node', [join(repo, HOOK), '--show', 'pkg/main.go'], { + cwd: repo, + encoding: 'utf8', + }); + expect(result.stdout).toContain('GO-RULE-CANARY'); + }); + + it('uses only Node built-ins, so it runs without node_modules', () => { + const source = readFileSync(join(ROOT, HOOK), 'utf8'); + const imports = [...source.matchAll(/from '([^']+)'/g)].map((match) => match[1] ?? ''); + expect(imports.length).toBeGreaterThan(0); + expect(imports.every((specifier) => specifier.startsWith('node:'))).toBe(true); + }); +}); + +describe('generated Codex rule lookup', () => { + it('lists only path-scoped rules, with patterns that match what the model matches', () => { + const rules = [ + parseRuleFile('.claude/rules/a.md', "---\npaths:\n - 'apps/api/**'\n---\n\n# A\n"), + parseRuleFile('.claude/rules/b.md', '# B launch\n'), + ]; + const model = new InstructionModel(rules, { claude: null, agents: null }); + const scopes = codexRuleScopes(model); + expect(scopes.map((scope) => scope.path)).toEqual(['.claude/rules/a.md']); + const [scoped] = rules; + const regex = new RegExp(scopes[0]?.patterns[0]?.regex ?? '(?!)'); + for (const file of ['apps/api/src/index.ts', 'apps/api-old/x.ts', 'apps/api']) { + expect(regex.test(file)).toBe(scoped !== undefined && model.loadsOnAccess(scoped, file)); + } + }); + + it('the committed lookup exists (staleness is enforced by --check)', () => { + expect(existsSync(join(ROOT, '.codex/hooks/rule-scopes.json'))).toBe(true); + }); +}); + +describe('Codex rule-context hook: writes and deny-once', () => { + it('a write whose rules exceed the cap is refused once, then allowed with the rest', () => { + const big = Array.from({ length: 6 }, (_, index) => ({ + path: `.claude/rules/9${index}-big.md`, + text: `---\npaths:\n - 'pkg/**'\n---\n\n# Big ${index}\n\nBIG-${index} ${'word '.repeat(1200)}\n`, + })); + const repo = fixtureRepo(big); + const env = { SAM_CODEX_RULE_CONTEXT_MAX_BYTES: '16000' }; + const write = patch('*** Update File: pkg/main.go\n@@\n-content\n+changed'); + const first = hook(repo, write, env); + expect(decision(first)).toBe('deny'); + expect(context(first)).toContain('not delivered yet'); + // The identical retry is allowed and carries the next batch. + const second = hook(repo, write, env); + expect(decision(second)).toBeUndefined(); + expect(context(second)).toContain('===== .claude/rules/'); + // A different set of paths gets its own single refusal. + const other = hook(repo, patch('*** Add File: pkg/other.go\n+package pkg'), env); + expect(decision(other)).toBe(context(other) === '' ? undefined : 'deny'); + }); + + it('never refuses a write when no rule text could be attached', () => { + const huge = { + path: '.claude/rules/99-huge.md', + text: `---\npaths:\n - 'big/**'\n---\n\n# Huge\n\n${'x '.repeat(30000)}\n`, + }; + const repo = fixtureRepo([huge]); + mkdirSync(join(repo, 'big'), { recursive: true }); + const run = hook(repo, patch('*** Add File: big/new.txt\n+x'), { + SAM_CODEX_RULE_CONTEXT_MAX_BYTES: '8000', + }); + expect(decision(run)).toBeUndefined(); + expect(context(run)).toContain('99-huge.md'); + }); + + it.each([ + ['tee', 'echo x | tee pkg/main.go'], + ['mv', 'mv pkg/main.go pkg/moved.go'], + ['rm', 'rm pkg/main.go'], + ['sed -i', "sed -i 's/a/b/' pkg/main.go"], + ['git mv', 'git mv pkg/main.go pkg/renamed.go'], + ['append redirect', 'echo x >> pkg/main.go'], + ])('%s counts as a write and is refused once', (_name, command) => { + const repo = fixtureRepo(); + expect(decision(hook(repo, bash(command)))).toBe('deny'); + }); + + it.each([ + ['plain read', 'cat pkg/main.go'], + ['stderr to stdout', 'cat pkg/main.go 2>&1'], + ['discarded output', 'cat pkg/main.go > /dev/null'], + ])('%s is a read: rules arrive, nothing is refused', (_name, command) => { + const repo = fixtureRepo(); + const run = hook(repo, bash(command)); + expect(decision(run)).toBeUndefined(); + expect(context(run)).toContain('GO-RULE-CANARY'); + }); + + it.each([ + ['Update File', '*** Update File: pkg/main.go\n@@\n-content\n+x'], + ['Delete File', '*** Delete File: pkg/main.go'], + ['Move to', '*** Update File: docs-none/a.txt\n*** Move to: pkg/moved.go\n@@\n-a\n+b'], + ])('apply_patch %s targets are recognised', (_name, body) => { + const repo = fixtureRepo(); + const run = hook(repo, patch(body)); + expect(decision(run)).toBe('deny'); + expect(context(run)).toContain('GO-RULE-CANARY'); + }); +}); + +describe('Codex rule-context hook: paths and sessions', () => { + it('follows cd inside the command and a subdirectory cwd', () => { + const repo = fixtureRepo(); + expect(context(hook(repo, bash('cd apps/api && sed -n 1,3p wrangler.toml')))).toContain( + 'API-RULE-CANARY' + ); + const fromSub = fixtureRepo(); + const run = hook(fromSub, { ...bash('cat wrangler.toml'), cwd: join(fromSub, 'apps/api') }); + expect(context(run)).toContain('API-RULE-CANARY'); + const relativePatch = hook(fixtureRepo(), { + ...patch('*** Add File: src/routes/new.ts\n+x'), + cwd: join(created[created.length - 1] ?? '', 'apps/api'), + }); + expect(context(relativePatch)).toContain('API-RULE-CANARY'); + }); + + it('ignores files under node_modules and .tmp even when they exist', () => { + const repo = fixtureRepo(); + for (const file of ['node_modules/x/y.go', '.tmp/z.go']) { + mkdirSync(dirname(join(repo, file)), { recursive: true }); + writeFileSync(join(repo, file), 'x'); + } + expect(hook(repo, bash('cat node_modules/x/y.go .tmp/z.go')).output).toEqual({}); + // Liveness: the same session still delivers for a governed file. + expect(context(hook(repo, bash('cat pkg/main.go')))).toContain('GO-RULE-CANARY'); + }); + + it.each([ + ['startup', true], + ['clear', true], + ['compact', true], + ['resume', false], + ['fork', false], + ])('SessionStart %s resets delivery: %s', (source, resets) => { + const repo = fixtureRepo(); + hook(repo, { hook_event_name: 'SessionStart', source: 'startup' }); + expect(context(hook(repo, bash('cat pkg/main.go')))).toContain('GO-RULE-CANARY'); + hook(repo, { hook_event_name: 'SessionStart', source }); + const again = context(hook(repo, bash('cat pkg/main.go'))); + expect(again.includes('GO-RULE-CANARY')).toBe(resets); + }); + + it('keeps delivery state per session, inside the state directory', () => { + const repo = fixtureRepo(); + expect(context(hook(repo, { ...bash('cat pkg/main.go'), session_id: 'a' }))).toContain( + 'GO-RULE-CANARY' + ); + expect(context(hook(repo, { ...bash('cat pkg/main.go'), session_id: 'b' }))).toContain( + 'GO-RULE-CANARY' + ); + hook(repo, { ...bash('cat pkg/main.go'), session_id: `../../${'x'.repeat(300)}` }); + const files = readdirSync(join(repo, '.tmp/codex-rule-context')); + expect(files.length).toBe(3); + expect(files.every((file) => file.length < 120 && !file.includes('/'))).toBe(true); + }); + + it('logs an error, and still prints {}, when the lookup is unreadable', () => { + const repo = fixtureRepo(); + writeFileSync(join(repo, '.codex/hooks/rule-scopes.json'), '{'); + const run = hook(repo, bash('cat pkg/main.go')); + expect(run.output).toEqual({}); + const log = readFileSync(join(repo, '.tmp/instruction-loads/codex-sess.jsonl'), 'utf8'); + expect(log).toContain('"load_reason":"error"'); + }); + + it('refuses to read a lookup entry outside the rules directory', () => { + const repo = fixtureRepo(); + writeFileSync(join(repo, 'secret.txt'), 'SECRET-CANARY'); + const lookup = JSON.parse( + readFileSync(join(repo, '.codex/hooks/rule-scopes.json'), 'utf8') + ) as { + rules: { path: string; title: string; patterns: unknown[] }[]; + }; + const [first] = lookup.rules; + if (first) first.path = 'secret.txt'; + writeFileSync(join(repo, '.codex/hooks/rule-scopes.json'), JSON.stringify(lookup)); + const text = context(hook(repo, bash('cat apps/api/wrangler.toml'))); + expect(text).not.toContain('SECRET-CANARY'); + }); + + it('stays fast and bounded on pathological commands', () => { + const repo = fixtureRepo(); + const started = Date.now(); + const run = hook(repo, bash(`${'cd a '.repeat(20000)}; touch apps/${'A'.repeat(5000)}.ts`)); + expect(Date.now() - started).toBeLessThan(5000); + expect(run.status).toBe(0); + expect(run.raw.length).toBeLessThan(60000); + }); +}); + +describe('Codex hook wiring in .codex/config.toml', () => { + const config = TOML.parse(readFileSync(join(ROOT, '.codex/config.toml'), 'utf8')) as { + hooks: Record< + string, + { matcher?: string; hooks: { command: string; additionalContextLimit?: number }[] }[] + >; + }; + + it('routes SessionStart sources and the tools the hook handles to it', () => { + const start = config.hooks.SessionStart?.[0]; + const pre = config.hooks.PreToolUse?.[0]; + for (const source of ['startup', 'resume', 'clear', 'compact', 'fork']) { + expect(new RegExp(start?.matcher ?? '(?!)').test(source)).toBe(true); + } + for (const tool of ['Bash', 'apply_patch']) { + expect(new RegExp(pre?.matcher ?? '(?!)').test(tool)).toBe(true); + } + expect(start?.hooks[0]?.command).toContain(HOOK); + expect(pre?.hooks[0]?.command).toContain(HOOK); + expect(config.hooks.Stop?.[0]?.hooks[0]?.command).toContain( + '.claude/hooks/verify-test-quality.mjs' + ); + }); + + it('sets additionalContextLimit above the hook byte cap, so Codex never spills', () => { + const source = readFileSync(join(ROOT, HOOK), 'utf8'); + const cap = Number(/MAX_MAX_BYTES = ([\d_]+)/.exec(source)?.[1]?.replaceAll('_', '')); + expect(cap).toBeGreaterThan(0); + for (const group of [ + ...(config.hooks.SessionStart ?? []), + ...(config.hooks.PreToolUse ?? []), + ]) { + // Three bytes per token is a conservative floor for English prose. + expect((group.hooks[0]?.additionalContextLimit ?? 0) * 3).toBeGreaterThan(cap); + } + }); + + it('delivers a real rule for a real path with the committed lookup', () => { + const result = spawnSync('node', [join(ROOT, HOOK)], { + cwd: ROOT, + input: JSON.stringify({ + hook_event_name: 'PreToolUse', + tool_name: 'Bash', + tool_input: { command: 'sed -n 1,3p packages/cli/go.mod' }, + session_id: `wiring-smoke-${process.pid}-${Date.now()}`, + cwd: ROOT, + }), + encoding: 'utf8', + }); + const output = JSON.parse(result.stdout) as HookOutput; + expect(output.hookSpecificOutput?.additionalContext).toContain('36-cli-quality.md'); + }); +}); diff --git a/scripts/quality/agent-codex-rule-scopes.ts b/scripts/quality/agent-codex-rule-scopes.ts new file mode 100644 index 0000000000..cd848530f2 --- /dev/null +++ b/scripts/quality/agent-codex-rule-scopes.ts @@ -0,0 +1,62 @@ +/** + * Static lookup of path-scoped rules for the Codex rule-delivery hook. + * + * `.codex/hooks/rule-context.mjs` must run in a workspace without node_modules, so it cannot + * import this TypeScript model. It reads the lookup generated here instead, and + * `pnpm quality:agent-context-budget --check` fails when the lookup no longer matches the + * rules (the same staleness contract as the generated rule indexes). + * + * The lookup holds scopes only. Rule bodies are read when delivered, so editing a rule's + * text does not make the lookup stale; changing its title or `paths` does. + */ +import { + compilePattern, + type InstructionModel, + unsupportedPatternReason, +} from './agent-instructions'; + +export const CODEX_RULE_SCOPES_FILE = '.codex/hooks/rule-scopes.json'; + +export interface CodexRuleScope { + path: string; + title: string; + patterns: { pattern: string; regex: string; literal: number }[]; +} + +/** Characters a pattern names literally; the hook delivers more specific rules first. */ +export function patternLiteral(pattern: string): number { + return pattern.replaceAll('*', '').length; +} + +function escapeRegex(text: string): string { + return text.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`); +} + +/** Every rule that is not loaded at launch, with its patterns compiled to anchored regexes. */ +export function codexRuleScopes(model: InstructionModel): CodexRuleScope[] { + const launch = new Set(model.claudeLaunchRules().map((rule) => rule.path)); + return model.rules + .filter((rule) => !launch.has(rule.path) && rule.paths !== null) + .sort((a, b) => a.path.localeCompare(b.path)) + .map((rule) => ({ + path: rule.path, + title: rule.title, + patterns: (rule.paths ?? []) + .filter((pattern) => !unsupportedPatternReason(pattern)) + .map((pattern) => { + const source = compilePattern(pattern).source; + const regex = + rule.baseDir === '' ? source : `^${escapeRegex(rule.baseDir)}/${source.slice(1)}`; + return { pattern, regex, literal: patternLiteral(pattern) }; + }), + })); +} + +export function renderCodexRuleScopes(model: InstructionModel): string { + const document = { + generatedBy: 'pnpm quality:agent-context-budget --write', + note: 'Read by .codex/hooks/rule-context.mjs. Do not edit by hand.', + rules: codexRuleScopes(model), + }; + return `${JSON.stringify(document, null, 2)}\n`; +} diff --git a/scripts/quality/check-agent-context-budget.ts b/scripts/quality/check-agent-context-budget.ts index 8dd1dcd0dd..252232da34 100644 --- a/scripts/quality/check-agent-context-budget.ts +++ b/scripts/quality/check-agent-context-budget.ts @@ -24,6 +24,8 @@ import { resolve } from 'node:path'; import TOML from '@iarna/toml'; +import { CODEX_RULE_SCOPES_FILE, renderCodexRuleScopes } from './agent-codex-rule-scopes'; + import { checkClaudeHookConfig, checkCodexHookConfig, @@ -247,6 +249,7 @@ function indexTargets( file: ROOT_INDEX_FILE, expected: applyGeneratedBlock(read(ROOT_INDEX_FILE), renderRootIndex(model)), }, + { file: CODEX_RULE_SCOPES_FILE, expected: renderCodexRuleScopes(model) }, ]; if (files.includes('AGENTS.md')) { targets.push({ From 2174c0aa457d77cff47a3908e1d32685ab65f763 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 14:56:17 +0000 Subject: [PATCH 03/16] style: sort imports --- scripts/quality/check-agent-context-budget.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/scripts/quality/check-agent-context-budget.ts b/scripts/quality/check-agent-context-budget.ts index 252232da34..1e5702886b 100644 --- a/scripts/quality/check-agent-context-budget.ts +++ b/scripts/quality/check-agent-context-budget.ts @@ -25,7 +25,6 @@ import { resolve } from 'node:path'; import TOML from '@iarna/toml'; import { CODEX_RULE_SCOPES_FILE, renderCodexRuleScopes } from './agent-codex-rule-scopes'; - import { checkClaudeHookConfig, checkCodexHookConfig, From 2d13120a4c6125440d864463ae30157f33036c22 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 14:57:40 +0000 Subject: [PATCH 04/16] refactor(vm-agent): move per-agent startup config writers to session_host_agent_config.go (pure move) --- .../internal/acp/session_host_agent_config.go | 163 ++++++++++++++++++ .../internal/acp/session_host_startup.go | 152 ---------------- 2 files changed, 163 insertions(+), 152 deletions(-) create mode 100644 packages/vm-agent/internal/acp/session_host_agent_config.go diff --git a/packages/vm-agent/internal/acp/session_host_agent_config.go b/packages/vm-agent/internal/acp/session_host_agent_config.go new file mode 100644 index 0000000000..f103536adb --- /dev/null +++ b/packages/vm-agent/internal/acp/session_host_agent_config.go @@ -0,0 +1,163 @@ +package acp + +import ( + "context" + "encoding/json" + "fmt" + "log/slog" + "strings" +) + +// Per-agent startup configuration written before an agent process starts: the Codex +// CODEX_CONFIG thread overrides and config.toml, and the OpenCode and Mistral Vibe config files. + +const codexACPManagedAgentModeEnv = "INITIAL_AGENT_MODE=agent-full-access" +const codexACPManagedCodexPathEnv = "CODEX_PATH=codex" + +type codexACPManagedConfig struct { + SandboxMode string `json:"sandbox_mode"` + ApprovalPolicy string `json:"approval_policy"` + Model string `json:"model,omitempty"` +} + +func buildCodexACPManagedConfigEnv(settings *agentSettingsPayload) (string, error) { + config := codexACPManagedConfig{ + SandboxMode: "danger-full-access", + ApprovalPolicy: "never", + } + if settings != nil { + config.Model = settings.Model + } + + encoded, err := json.Marshal(config) + if err != nil { + return "", fmt.Errorf("encode managed Codex config: %w", err) + } + return "CODEX_CONFIG=" + string(encoded), nil +} + +func (h *SessionHost) writeAgentStartupConfig(ctx context.Context, agentType string, cred *agentCredential, startup *agentStartup) error { + if agentType == "openai-codex" { + if err := h.writeCodexStartupConfig(ctx, cred, startup); err != nil { + return err + } + } + if startup.containerID == "" { + return nil + } + if agentType == "opencode" { + h.writeOpenCodeStartupConfig(ctx, cred, startup) + } + if agentType == "mistral-vibe" { + h.writeVibeStartupConfig(ctx, startup) + } + return nil +} + +func (h *SessionHost) writeCodexStartupConfig(ctx context.Context, cred *agentCredential, startup *agentStartup) error { + managedConfigEnv, err := buildCodexACPManagedConfigEnv(startup.settings) + if err != nil { + return fmt.Errorf("cannot start Codex: %w", err) + } + proxyConfig := codexProxyProviderConfigFromCredential(cred, h.callbackToken()) + effort := "" + if startup.settings != nil { + effort = startup.settings.Effort + } + // URL and CR/LF checks apply to every server: a malformed value would corrupt config.toml. + // + // The missing-token check applies ONLY to SAM's own endpoint. A user-configured MCP server + // may legitimately have no bearer token — several providers issue pre-signed URLs that + // carry the credential in the URL itself — and generateCodexMcpConfig already omits + // bearer_token_env_var for those. Failing closed on all of them would mean one no-auth + // connection blocks every Codex session for that user. + mcpServers := h.mcpServers() // one snapshot: validated, written and logged together + names := ResolveMcpServerNames(mcpServers) + for i, server := range mcpServers { + switch { + case strings.TrimSpace(server.URL) == "": + return fmt.Errorf("cannot start Codex with SAM MCP enabled: mcp server %d has a blank URL", i) + case strings.ContainsAny(server.URL, "\r\n"): + return fmt.Errorf("cannot start Codex with SAM MCP enabled: mcp server %d URL contains CR/LF characters", i) + case names[i] == SamMcpServerName && strings.TrimSpace(server.Token) == "": + return fmt.Errorf("cannot start Codex with SAM MCP enabled: mcp server %d is missing its bearer token (SAM_MCP_TOKEN)", i) + case strings.ContainsAny(server.Token, "\r\n"): + return fmt.Errorf("cannot start Codex with SAM MCP enabled: mcp server %d bearer token contains CR/LF characters", i) + } + } + + var codexMcpEnvVars []string + if startup.containerID != "" { + codexMcpEnvVars, err = writeCodexConfigToContainer(ctx, startup.containerID, h.config.ContainerUser, mcpServers, proxyConfig, effort) + } else { + codexMcpEnvVars, err = writeCodexConfigLocally(mcpServers, proxyConfig, effort) + } + if err != nil { + return fmt.Errorf("cannot start Codex: write SAM MCP config.toml: %w", err) + } + // codex-acp (verified through 2.1.1) ignores Codex CLI -c arguments. CODEX_CONFIG is merged into + // each app-server thread. Seed the requested model before session/new: newly + // released Codex models may be valid provider models before they appear in the + // adapter's default configOptions, while a configured current model is advertised + // and can be verified by the exact post-handshake selection RPC. Every turn then + // applies the ACP agent mode's + // approval and sandbox policy on top. Select the wrapper's supported full-access + // mode as well so main turns and spawned subagents cannot fall back to bwrap + // inside SAM-managed containers. CODEX_PATH makes the adapter execute the + // explicitly installed and version-validated companion instead of resolving a + // potentially different nested @openai/codex dependency. + startup.envVars = removeEnvVar(startup.envVars, "CODEX_CONFIG") + startup.envVars = removeEnvVar(startup.envVars, "INITIAL_AGENT_MODE") + startup.envVars = removeEnvVar(startup.envVars, "CODEX_PATH") + startup.envVars = append(startup.envVars, managedConfigEnv) + startup.envVars = append(startup.envVars, codexACPManagedAgentModeEnv) + startup.envVars = append(startup.envVars, codexACPManagedCodexPathEnv) + for _, envVar := range codexMcpEnvVars { + key, _, ok := strings.Cut(envVar, "=") + if ok { + startup.envVars = removeEnvVar(startup.envVars, key) + } + } + startup.envVars = append(startup.envVars, codexMcpEnvVars...) + slog.Info("Wrote Codex config.toml", + "mcpServers", len(mcpServers), + "hasProxyProvider", proxyConfig != nil, + "effort", normalizeCodexEffort(effort), + "standalone", startup.containerID == "") + return nil +} + +func (h *SessionHost) writeOpenCodeStartupConfig(ctx context.Context, cred *agentCredential, startup *agentStartup) { + opencodeConfig := buildOpencodeConfig(startup.settings) + configJSON, err := json.Marshal(opencodeConfig) + if err != nil { + slog.Error("opencode: failed to marshal config", "error", err) + return + } + + startup.envVars = append(startup.envVars, "OPENCODE_CONFIG_CONTENT="+string(configJSON)) + // SAM pins its own OpenCode build (ACP live steering, opencode_install.go). Its + // updater must never replace that binary with an upstream release mid-session. + startup.envVars = removeEnvVar(startup.envVars, opencodeDisableAutoupdateEnvName) + startup.envVars = append(startup.envVars, opencodeDisableAutoupdateEnvName+"=1") + provider := DefaultOpencodeProvider + if startup.settings != nil && startup.settings.OpencodeProvider != "" { + provider = startup.settings.OpencodeProvider + } + slog.Info("OpenCode config injected", + "provider", provider, "model", opencodeConfig["model"], + "configLen", len(configJSON), "workspaceId", h.config.WorkspaceID) + +} + +func (h *SessionHost) writeVibeStartupConfig(ctx context.Context, startup *agentStartup) { + activeModel := resolveVibeActiveModel(startup.settings) + mcpServers := h.mcpServers() + err := writeVibeConfigToContainer(ctx, startup.containerID, h.config.ContainerUser, activeModel, mcpServers) + if err != nil { + slog.Warn("Failed to write Vibe config.toml", + "error", err, "activeModel", activeModel, "workspaceId", h.config.WorkspaceID) + return + } + slog.Info("Wrote Vibe config.toml", "activeModel", activeModel, "mcpServers", len(mcpServers)) +} diff --git a/packages/vm-agent/internal/acp/session_host_startup.go b/packages/vm-agent/internal/acp/session_host_startup.go index 83af405e75..4b11f14831 100644 --- a/packages/vm-agent/internal/acp/session_host_startup.go +++ b/packages/vm-agent/internal/acp/session_host_startup.go @@ -2,7 +2,6 @@ package acp import ( "context" - "encoding/json" "fmt" "log/slog" "net/url" @@ -78,31 +77,6 @@ type agentStartup struct { settings *agentSettingsPayload } -const codexACPManagedAgentModeEnv = "INITIAL_AGENT_MODE=agent-full-access" -const codexACPManagedCodexPathEnv = "CODEX_PATH=codex" - -type codexACPManagedConfig struct { - SandboxMode string `json:"sandbox_mode"` - ApprovalPolicy string `json:"approval_policy"` - Model string `json:"model,omitempty"` -} - -func buildCodexACPManagedConfigEnv(settings *agentSettingsPayload) (string, error) { - config := codexACPManagedConfig{ - SandboxMode: "danger-full-access", - ApprovalPolicy: "never", - } - if settings != nil { - config.Model = settings.Model - } - - encoded, err := json.Marshal(config) - if err != nil { - return "", fmt.Errorf("encode managed Codex config: %w", err) - } - return "CODEX_CONFIG=" + string(encoded), nil -} - func (h *SessionHost) prepareAgentStartup(ctx context.Context, agentType string, cred *agentCredential, settings *agentSettingsPayload) (*agentStartup, error) { var containerID string var err error @@ -482,132 +456,6 @@ func (h *SessionHost) applyPermissionMode(settings *agentSettingsPayload) { } } -func (h *SessionHost) writeAgentStartupConfig(ctx context.Context, agentType string, cred *agentCredential, startup *agentStartup) error { - if agentType == "openai-codex" { - if err := h.writeCodexStartupConfig(ctx, cred, startup); err != nil { - return err - } - } - if startup.containerID == "" { - return nil - } - if agentType == "opencode" { - h.writeOpenCodeStartupConfig(ctx, cred, startup) - } - if agentType == "mistral-vibe" { - h.writeVibeStartupConfig(ctx, startup) - } - return nil -} - -func (h *SessionHost) writeCodexStartupConfig(ctx context.Context, cred *agentCredential, startup *agentStartup) error { - managedConfigEnv, err := buildCodexACPManagedConfigEnv(startup.settings) - if err != nil { - return fmt.Errorf("cannot start Codex: %w", err) - } - proxyConfig := codexProxyProviderConfigFromCredential(cred, h.callbackToken()) - effort := "" - if startup.settings != nil { - effort = startup.settings.Effort - } - // URL and CR/LF checks apply to every server: a malformed value would corrupt config.toml. - // - // The missing-token check applies ONLY to SAM's own endpoint. A user-configured MCP server - // may legitimately have no bearer token — several providers issue pre-signed URLs that - // carry the credential in the URL itself — and generateCodexMcpConfig already omits - // bearer_token_env_var for those. Failing closed on all of them would mean one no-auth - // connection blocks every Codex session for that user. - mcpServers := h.mcpServers() // one snapshot: validated, written and logged together - names := ResolveMcpServerNames(mcpServers) - for i, server := range mcpServers { - switch { - case strings.TrimSpace(server.URL) == "": - return fmt.Errorf("cannot start Codex with SAM MCP enabled: mcp server %d has a blank URL", i) - case strings.ContainsAny(server.URL, "\r\n"): - return fmt.Errorf("cannot start Codex with SAM MCP enabled: mcp server %d URL contains CR/LF characters", i) - case names[i] == SamMcpServerName && strings.TrimSpace(server.Token) == "": - return fmt.Errorf("cannot start Codex with SAM MCP enabled: mcp server %d is missing its bearer token (SAM_MCP_TOKEN)", i) - case strings.ContainsAny(server.Token, "\r\n"): - return fmt.Errorf("cannot start Codex with SAM MCP enabled: mcp server %d bearer token contains CR/LF characters", i) - } - } - - var codexMcpEnvVars []string - if startup.containerID != "" { - codexMcpEnvVars, err = writeCodexConfigToContainer(ctx, startup.containerID, h.config.ContainerUser, mcpServers, proxyConfig, effort) - } else { - codexMcpEnvVars, err = writeCodexConfigLocally(mcpServers, proxyConfig, effort) - } - if err != nil { - return fmt.Errorf("cannot start Codex: write SAM MCP config.toml: %w", err) - } - // codex-acp (verified through 2.1.1) ignores Codex CLI -c arguments. CODEX_CONFIG is merged into - // each app-server thread. Seed the requested model before session/new: newly - // released Codex models may be valid provider models before they appear in the - // adapter's default configOptions, while a configured current model is advertised - // and can be verified by the exact post-handshake selection RPC. Every turn then - // applies the ACP agent mode's - // approval and sandbox policy on top. Select the wrapper's supported full-access - // mode as well so main turns and spawned subagents cannot fall back to bwrap - // inside SAM-managed containers. CODEX_PATH makes the adapter execute the - // explicitly installed and version-validated companion instead of resolving a - // potentially different nested @openai/codex dependency. - startup.envVars = removeEnvVar(startup.envVars, "CODEX_CONFIG") - startup.envVars = removeEnvVar(startup.envVars, "INITIAL_AGENT_MODE") - startup.envVars = removeEnvVar(startup.envVars, "CODEX_PATH") - startup.envVars = append(startup.envVars, managedConfigEnv) - startup.envVars = append(startup.envVars, codexACPManagedAgentModeEnv) - startup.envVars = append(startup.envVars, codexACPManagedCodexPathEnv) - for _, envVar := range codexMcpEnvVars { - key, _, ok := strings.Cut(envVar, "=") - if ok { - startup.envVars = removeEnvVar(startup.envVars, key) - } - } - startup.envVars = append(startup.envVars, codexMcpEnvVars...) - slog.Info("Wrote Codex config.toml", - "mcpServers", len(mcpServers), - "hasProxyProvider", proxyConfig != nil, - "effort", normalizeCodexEffort(effort), - "standalone", startup.containerID == "") - return nil -} - -func (h *SessionHost) writeOpenCodeStartupConfig(ctx context.Context, cred *agentCredential, startup *agentStartup) { - opencodeConfig := buildOpencodeConfig(startup.settings) - configJSON, err := json.Marshal(opencodeConfig) - if err != nil { - slog.Error("opencode: failed to marshal config", "error", err) - return - } - - startup.envVars = append(startup.envVars, "OPENCODE_CONFIG_CONTENT="+string(configJSON)) - // SAM pins its own OpenCode build (ACP live steering, opencode_install.go). Its - // updater must never replace that binary with an upstream release mid-session. - startup.envVars = removeEnvVar(startup.envVars, opencodeDisableAutoupdateEnvName) - startup.envVars = append(startup.envVars, opencodeDisableAutoupdateEnvName+"=1") - provider := DefaultOpencodeProvider - if startup.settings != nil && startup.settings.OpencodeProvider != "" { - provider = startup.settings.OpencodeProvider - } - slog.Info("OpenCode config injected", - "provider", provider, "model", opencodeConfig["model"], - "configLen", len(configJSON), "workspaceId", h.config.WorkspaceID) - -} - -func (h *SessionHost) writeVibeStartupConfig(ctx context.Context, startup *agentStartup) { - activeModel := resolveVibeActiveModel(startup.settings) - mcpServers := h.mcpServers() - err := writeVibeConfigToContainer(ctx, startup.containerID, h.config.ContainerUser, activeModel, mcpServers) - if err != nil { - slog.Warn("Failed to write Vibe config.toml", - "error", err, "activeModel", activeModel, "workspaceId", h.config.WorkspaceID) - return - } - slog.Info("Wrote Vibe config.toml", "activeModel", activeModel, "mcpServers", len(mcpServers)) -} - func (h *SessionHost) startAgentProcess(startup *agentStartup) (agentProcess, error) { if h.config.StartProcess != nil { return h.config.StartProcess(startup) From 94f9c11799b9314fcbb9b245119c9bde361c28ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 15:00:29 +0000 Subject: [PATCH 05/16] feat(vm-agent): SAM Codex sessions trust the repository's Codex hooks (bypass_hook_trust + project trust in CODEX_CONFIG) --- .../vm-agent/internal/acp/gateway_test.go | 13 ++-- .../internal/acp/session_host_agent_config.go | 31 +++++++-- .../acp/session_host_model_settings_test.go | 6 +- .../vm-agent/internal/acp/settings_test.go | 65 ++++++++++++++----- 4 files changed, 88 insertions(+), 27 deletions(-) diff --git a/packages/vm-agent/internal/acp/gateway_test.go b/packages/vm-agent/internal/acp/gateway_test.go index 87114af17e..0ebdbf2dbe 100644 --- a/packages/vm-agent/internal/acp/gateway_test.go +++ b/packages/vm-agent/internal/acp/gateway_test.go @@ -1807,7 +1807,7 @@ func TestWriteAgentStartupConfigCodexStandaloneWritesMcpConfig(t *testing.T) { t.Errorf("config.toml missing SAM MCP bearer env reference: %s", data) } assertCodexStartupTOML(t, data, "https://api.example.com/mcp", "SAM_MCP_TOKEN") - assertEnvContains(t, startup.envVars, "CODEX_CONFIG", `{"sandbox_mode":"danger-full-access","approval_policy":"never","model":"gpt-6.1-sol"}`) + assertEnvContains(t, startup.envVars, "CODEX_CONFIG", `{"sandbox_mode":"danger-full-access","approval_policy":"never","model":"gpt-6.1-sol","bypass_hook_trust":true}`) assertEnvContains(t, startup.envVars, "INITIAL_AGENT_MODE", "agent-full-access") assertEnvContains(t, startup.envVars, "CODEX_PATH", "codex") if got := countEnvKey(startup.envVars, "CODEX_PATH"); got != 1 { @@ -1838,9 +1838,10 @@ esac h := &SessionHost{config: SessionHostConfig{ GatewayConfig: GatewayConfig{ - McpServers: []McpServerEntry{{URL: "https://api.example.com/mcp", Token: "container-token"}}, - WorkspaceID: "ws-container", - ContainerUser: "testuser", + McpServers: []McpServerEntry{{URL: "https://api.example.com/mcp", Token: "container-token"}}, + WorkspaceID: "ws-container", + ContainerUser: "testuser", + ContainerWorkDir: "/workspaces/repo", }, }} startup := &agentStartup{containerID: "container-123", settings: &agentSettingsPayload{Model: "gpt-6.1-sol"}, envVars: []string{ @@ -1866,7 +1867,7 @@ esac t.Fatalf("container config contract changed: %s", content) } assertCodexStartupTOML(t, data, "https://api.example.com/mcp", "SAM_MCP_TOKEN") - assertEnvContains(t, startup.envVars, "CODEX_CONFIG", `{"sandbox_mode":"danger-full-access","approval_policy":"never","model":"gpt-6.1-sol"}`) + assertEnvContains(t, startup.envVars, "CODEX_CONFIG", `{"sandbox_mode":"danger-full-access","approval_policy":"never","model":"gpt-6.1-sol","bypass_hook_trust":true,"projects":{"/workspaces/repo":{"trust_level":"trusted"}}}`) assertEnvContains(t, startup.envVars, "INITIAL_AGENT_MODE", "agent-full-access") assertEnvContains(t, startup.envVars, "CODEX_PATH", "codex") if got := countEnvKey(startup.envVars, "CODEX_PATH"); got != 1 { @@ -1964,7 +1965,7 @@ esac strings.Count(content, `approval_policy = "never"`) != 1 { t.Fatalf("written config does not contain exactly one managed control pair:\n%s", content) } - assertEnvContains(t, startup.envVars, "CODEX_CONFIG", `{"sandbox_mode":"danger-full-access","approval_policy":"never"}`) + assertEnvContains(t, startup.envVars, "CODEX_CONFIG", `{"sandbox_mode":"danger-full-access","approval_policy":"never","bypass_hook_trust":true}`) assertEnvContains(t, startup.envVars, "INITIAL_AGENT_MODE", "agent-full-access") assertEnvContains(t, startup.envVars, "CODEX_PATH", "codex") if got := countEnvKey(startup.envVars, "CODEX_PATH"); got != 1 { diff --git a/packages/vm-agent/internal/acp/session_host_agent_config.go b/packages/vm-agent/internal/acp/session_host_agent_config.go index f103536adb..c1be3f74ca 100644 --- a/packages/vm-agent/internal/acp/session_host_agent_config.go +++ b/packages/vm-agent/internal/acp/session_host_agent_config.go @@ -5,6 +5,7 @@ import ( "encoding/json" "fmt" "log/slog" + "path" "strings" ) @@ -14,20 +15,42 @@ import ( const codexACPManagedAgentModeEnv = "INITIAL_AGENT_MODE=agent-full-access" const codexACPManagedCodexPathEnv = "CODEX_PATH=codex" +// codexProjectTrust is one entry of Codex's `projects` table. +type codexProjectTrust struct { + TrustLevel string `json:"trust_level"` +} + +// codexACPManagedConfig is the CODEX_CONFIG JSON codex-acp passes to every app-server thread +// as per-thread config overrides (codex rust-v0.160.0, app-server config_manager.rs). type codexACPManagedConfig struct { SandboxMode string `json:"sandbox_mode"` ApprovalPolicy string `json:"approval_policy"` Model string `json:"model,omitempty"` + // BypassHookTrust and Projects let a repository's own Codex hooks run, as Claude Code + // runs a repository's .claude/settings.json hooks. Codex loads the project .codex/ layer + // only for a trusted project, and runs a non-managed hook only once its definition is + // trusted by hash, which normally takes an interactive /hooks review that a SAM session + // cannot give. The hooks come from the repository the user (or their agent) chose, and + // they can do nothing the agent cannot already do in this full-access workspace. + // Decision: Raphaël, 2026-11-16 (SAM idea 01M7J0TXAHGRY8CWA7Y7SJZAK0). + BypassHookTrust bool `json:"bypass_hook_trust"` + Projects map[string]codexProjectTrust `json:"projects,omitempty"` } -func buildCodexACPManagedConfigEnv(settings *agentSettingsPayload) (string, error) { +// buildCodexACPManagedConfigEnv renders CODEX_CONFIG. workDir is the session's working +// directory (the repository checkout); Codex looks up project trust by the cwd first. +func buildCodexACPManagedConfigEnv(settings *agentSettingsPayload, workDir string) (string, error) { config := codexACPManagedConfig{ - SandboxMode: "danger-full-access", - ApprovalPolicy: "never", + SandboxMode: "danger-full-access", + ApprovalPolicy: "never", + BypassHookTrust: true, } if settings != nil { config.Model = settings.Model } + if dir := strings.TrimSpace(workDir); dir != "" && path.IsAbs(dir) { + config.Projects = map[string]codexProjectTrust{path.Clean(dir): {TrustLevel: "trusted"}} + } encoded, err := json.Marshal(config) if err != nil { @@ -55,7 +78,7 @@ func (h *SessionHost) writeAgentStartupConfig(ctx context.Context, agentType str } func (h *SessionHost) writeCodexStartupConfig(ctx context.Context, cred *agentCredential, startup *agentStartup) error { - managedConfigEnv, err := buildCodexACPManagedConfigEnv(startup.settings) + managedConfigEnv, err := buildCodexACPManagedConfigEnv(startup.settings, h.config.ContainerWorkDir) if err != nil { return fmt.Errorf("cannot start Codex: %w", err) } diff --git a/packages/vm-agent/internal/acp/session_host_model_settings_test.go b/packages/vm-agent/internal/acp/session_host_model_settings_test.go index aa6fd1c3eb..e8fb758db0 100644 --- a/packages/vm-agent/internal/acp/session_host_model_settings_test.go +++ b/packages/vm-agent/internal/acp/session_host_model_settings_test.go @@ -39,11 +39,13 @@ func TestCodexRequestedModelIsSeededBeforeACPProcessStart(t *testing.T) { if !strings.HasPrefix(envVar, "CODEX_CONFIG=") { continue } - var config map[string]string + var config struct { + Model string `json:"model"` + } if err := json.Unmarshal([]byte(strings.TrimPrefix(envVar, "CODEX_CONFIG=")), &config); err != nil { return nil, fmt.Errorf("decode CODEX_CONFIG: %w", err) } - startupModel = config["model"] + startupModel = config.Model } return process, nil }, diff --git a/packages/vm-agent/internal/acp/settings_test.go b/packages/vm-agent/internal/acp/settings_test.go index 8518a311bd..d8bc2a64f7 100644 --- a/packages/vm-agent/internal/acp/settings_test.go +++ b/packages/vm-agent/internal/acp/settings_test.go @@ -8,18 +8,41 @@ import ( ) func TestBuildCodexACPManagedConfigEnv(t *testing.T) { + type projectTrust struct { + TrustLevel string `json:"trust_level"` + } + type managedConfig struct { + SandboxMode string `json:"sandbox_mode"` + ApprovalPolicy string `json:"approval_policy"` + Model *string `json:"model"` + BypassHookTrust *bool `json:"bypass_hook_trust"` + Projects map[string]projectTrust `json:"projects"` + } for _, tc := range []struct { - name string - settings *agentSettingsPayload - wantModel string + name string + settings *agentSettingsPayload + workDir string + wantModel string + wantProjects map[string]projectTrust }{ - {name: "nil settings"}, + {name: "nil settings, no work dir"}, {name: "empty model", settings: &agentSettingsPayload{}}, {name: "GPT-6.1 Sol", settings: &agentSettingsPayload{Model: "gpt-6.1-sol"}, wantModel: "gpt-6.1-sol"}, {name: "JSON special characters", settings: &agentSettingsPayload{Model: `custom\"model\\variant`}, wantModel: `custom\"model\\variant`}, + { + name: "VM devcontainer work dir is trusted", + workDir: "/workspaces/simple-agent-manager", + wantProjects: map[string]projectTrust{"/workspaces/simple-agent-manager": {TrustLevel: "trusted"}}, + }, + { + name: "work dir is cleaned", + workDir: " /workspaces/repo/ ", + wantProjects: map[string]projectTrust{"/workspaces/repo": {TrustLevel: "trusted"}}, + }, + {name: "relative work dir is not trusted", workDir: "repo"}, } { t.Run(tc.name, func(t *testing.T) { - envVar, err := buildCodexACPManagedConfigEnv(tc.settings) + envVar, err := buildCodexACPManagedConfigEnv(tc.settings, tc.workDir) if err != nil { t.Fatalf("buildCodexACPManagedConfigEnv failed: %v", err) } @@ -27,22 +50,34 @@ func TestBuildCodexACPManagedConfigEnv(t *testing.T) { if !strings.HasPrefix(envVar, prefix) { t.Fatalf("managed config env = %q, want %q prefix", envVar, prefix) } - var config map[string]string + var config managedConfig if err := json.Unmarshal([]byte(strings.TrimPrefix(envVar, prefix)), &config); err != nil { t.Fatalf("managed config is not valid JSON: %v", err) } - if got := config["sandbox_mode"]; got != "danger-full-access" { - t.Fatalf("sandbox_mode = %q, want danger-full-access", got) + if config.SandboxMode != "danger-full-access" || config.ApprovalPolicy != "never" { + t.Fatalf("sandbox/approval = %q/%q, want danger-full-access/never", config.SandboxMode, config.ApprovalPolicy) } - if got := config["approval_policy"]; got != "never" { - t.Fatalf("approval_policy = %q, want never", got) + // Repository hooks run in every Codex session (idea 01M7J0TXAHGRY8CWA7Y7SJZAK0). + if config.BypassHookTrust == nil || !*config.BypassHookTrust { + t.Fatalf("bypass_hook_trust = %v, want true", config.BypassHookTrust) } - if got := config["model"]; got != tc.wantModel { - t.Fatalf("model = %q, want %q", got, tc.wantModel) + switch { + case tc.wantModel == "" && config.Model != nil: + t.Fatalf("empty model should be omitted, got %q", *config.Model) + case tc.wantModel != "" && (config.Model == nil || *config.Model != tc.wantModel): + t.Fatalf("model = %v, want %q", config.Model, tc.wantModel) } - if tc.wantModel == "" { - if _, ok := config["model"]; ok { - t.Fatalf("empty model should be omitted: %#v", config) + if len(tc.wantProjects) == 0 && config.Projects != nil { + t.Fatalf("projects should be omitted, got %#v", config.Projects) + } + if len(tc.wantProjects) > 0 { + if len(config.Projects) != len(tc.wantProjects) { + t.Fatalf("projects = %#v, want %#v", config.Projects, tc.wantProjects) + } + for dir, want := range tc.wantProjects { + if config.Projects[dir] != want { + t.Fatalf("projects[%q] = %#v, want %#v", dir, config.Projects[dir], want) + } } } }) From b9a3745e9685586a27c21892a89fecb370ba0bca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 15:01:29 +0000 Subject: [PATCH 06/16] docs: Codex sessions run repository hooks; rule delivery for Codex --- .claude/rules/00-rule-routing.md | 10 +++-- AGENTS.md | 7 ++-- .../src/content/docs/docs/guides/agents.md | 7 ++++ scripts/quality/README.md | 38 ++++++++++++------- scripts/quality/agent-rule-index.ts | 7 ++-- 5 files changed, 45 insertions(+), 24 deletions(-) diff --git a/.claude/rules/00-rule-routing.md b/.claude/rules/00-rule-routing.md index 7db93d6c80..4f2d14c686 100644 --- a/.claude/rules/00-rule-routing.md +++ b/.claude/rules/00-rule-routing.md @@ -8,10 +8,12 @@ the files it governs with `paths` frontmatter. - **Claude Code** loads a rule without `paths` at launch. It loads a rule with `paths` when a matching file is read, written or edited (`.claude/hooks/log-instructions-loaded.sh` records every load in `.tmp/instruction-loads/`). -- **Codex and other harnesses** load none of these files by themselves. The root - `AGENTS.md` lists the launch rules by name. The `AGENTS.md` nearest the code lists the - path-scoped rules for that directory. Read both sets before editing. This route is a - convention: nothing delivers these rules to Codex automatically. +- **Codex** loads only the root `AGENTS.md`, which lists the launch rules by name. In SAM + sessions the hook `.codex/hooks/rule-context.mjs` adds the path-scoped rules for the files + a shell command or patch touches (see `scripts/quality/README.md`, "Codex hooks"). +- **Other harnesses** load none of these files by themselves. The `AGENTS.md` nearest the + code lists the path-scoped rules for that directory. Read it and the launch rules before + editing. - A path-scoped rule arrives when you first access a matching file. Claude Code counts the Read, Write and Edit tools and simple shell reads of one file (`cat`, `head`, `sed -n`). It does not arrive before you write a brand-new file, when a script or diff --git a/AGENTS.md b/AGENTS.md index 9157c76e20..709a7f0005 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -143,9 +143,10 @@ Per-project data (chat sessions, messages, activity events, and canonical `proje Codex does not load `.claude/rules/` by itself. Two steps before you edit: -1. Open the `AGENTS.md` nearest the files you will change and read the rules its - "Rules for this directory" section lists. `.claude/rules/00-rule-routing.md` indexes - every path-scoped rule. +1. Path-scoped rules: in a SAM session the hook `.codex/hooks/rule-context.mjs` adds the + rules for the files a command or patch touches. Elsewhere, or if none arrive, open the + `AGENTS.md` nearest the files you will change and read the rules its "Rules for this + directory" section lists. `.claude/rules/00-rule-routing.md` indexes every one. 2. The rules below apply to all work. Claude Code has them in context at launch. Read the ones that bear on your task. diff --git a/apps/www/src/content/docs/docs/guides/agents.md b/apps/www/src/content/docs/docs/guides/agents.md index 549e281f74..f2e06bc932 100644 --- a/apps/www/src/content/docs/docs/guides/agents.md +++ b/apps/www/src/content/docs/docs/guides/agents.md @@ -43,6 +43,13 @@ a feature back on, replace that whole block with your own `[features]` table, fo example `[features]` followed by `apps = true`. SAM keeps any value you set there and adds its defaults for the features you leave out. +Hooks your repository defines for Codex (in `.codex/config.toml` or +`.codex/hooks.json`) run in SAM sessions, as Claude Code runs the hooks in +`.claude/settings.json`. Codex normally waits for someone to trust the project +and review each hook, which nobody can do in a SAM session. SAM trusts the +session's working directory and its hooks when it starts the agent, so treat a +repository's hooks like any other code you let the agent run. + ### Gemini CLI | Property | Value | diff --git a/scripts/quality/README.md b/scripts/quality/README.md index 0656c2d4ae..b84dd70151 100644 --- a/scripts/quality/README.md +++ b/scripts/quality/README.md @@ -115,8 +115,8 @@ empty log, or one without `session_start` entries, is reported as a mismatch; pa ### Test-quality Stop gate `.claude/hooks/verify-test-quality.mjs` runs at the end of every Claude Code turn -(`.claude/settings.json`; observed firing in a fresh session, idea 01M7H32EK6S4E31EHWVSJSENR5). -It is not configured for Codex: see "Codex hooks" below. It reads every change on the +(`.claude/settings.json`; observed firing in a fresh session, idea 01M7H32EK6S4E31EHWVSJSENR5) +and every Codex turn (`.codex/config.toml`; see "Codex hooks" below). It reads every change on the branch (commits since the merge base with `origin/main`, staged, unstaged and untracked files) and reports two classes: @@ -139,18 +139,28 @@ that (`.claude/rules/35-vertical-slice-testing.md`). ### Codex hooks Codex runs repository hooks (`.codex/config.toml` or `.codex/hooks.json`) only for a -trusted project, and only hook definitions that have themselves been trusted. SAM-managed -Codex sessions trust neither: on 2026-11-16 a probe with the hook script committed -(task 01M7HZ6Q1EVPVPCBN00AM3WN8A) saw no SessionStart, no PreToolUse context and no Stop -prompt, and the session's `~/.codex/config.toml` had no trust entry for the repository -(`CODEX_HOME` unset). The same applies to every other setting in `.codex/config.toml`. -So no repository hook is configured for Codex. A rule-delivery hook (SessionStart and -PreToolUse injection of path-scoped rule bodies, bounded, with a log) and the Codex Stop -entry are kept on branch `sam/codex-rule-delivery-hook` until SAM decides whether its -Codex sessions should trust repository hooks. Until then Codex reaches path-scoped rules -through the `AGENTS.md` indexes only. `--check` still validates any Codex hook entry -against the current schema, so a malformed one (like the flat `[[hooks.Stop]]` that held -no handler) cannot come back unnoticed. +trusted project, and only hook definitions that have themselves been trusted. SAM's +vm-agent grants both when it starts Codex: `CODEX_CONFIG`, which codex-acp passes to every +app-server thread, carries `bypass_hook_trust: true` and a `projects.` trust entry +(`buildCodexACPManagedConfigEnv` in `packages/vm-agent/internal/acp/session_host_agent_config.go`; +decision: SAM idea 01M7J0TXAHGRY8CWA7Y7SJZAK0). Before that change no repository hook, nor +any other setting in `.codex/config.toml`, took effect in a SAM Codex session (probe task +01M7HZ6Q1EVPVPCBN00AM3WN8A). + +Two hooks are configured for Codex: + +- `.codex/hooks/rule-context.mjs` (SessionStart and PreToolUse on `Bash` and `apply_patch`) + adds the bodies of the path-scoped rules that govern the files a tool call touches, most + specific scope first, capped per call (`SAM_CODEX_RULE_CONTEXT_MAX_BYTES`, default 40,000 + bytes, below the handler's `additionalContextLimit`), and names the rules it had no room + for. The first write to files whose rules were never delivered is refused once with the + rules attached. Deliveries are logged to `.tmp/instruction-loads/codex-.jsonl`. + It reads `.codex/hooks/rule-scopes.json`, which `--write` generates from the instruction + model, so it runs without `node_modules`. +- The test-quality Stop gate above. + +`--check` validates every Codex hook entry against the current schema, so a malformed one +(like the flat `[[hooks.Stop]]` that held no handler) cannot come back unnoticed. ## Rule 73: optional fields must not overwrite on absence diff --git a/scripts/quality/agent-rule-index.ts b/scripts/quality/agent-rule-index.ts index 2a1210a5e7..ace917d27e 100644 --- a/scripts/quality/agent-rule-index.ts +++ b/scripts/quality/agent-rule-index.ts @@ -133,9 +133,10 @@ export function renderLaunchRuleIndex(model: InstructionModel): string { '', 'Codex does not load `.claude/rules/` by itself. Two steps before you edit:', '', - '1. Open the `AGENTS.md` nearest the files you will change and read the rules its', - ' "Rules for this directory" section lists. `.claude/rules/00-rule-routing.md` indexes', - ' every path-scoped rule.', + '1. Path-scoped rules: in a SAM session the hook `.codex/hooks/rule-context.mjs` adds the', + ' rules for the files a command or patch touches. Elsewhere, or if none arrive, open the', + ' `AGENTS.md` nearest the files you will change and read the rules its "Rules for this', + ' directory" section lists. `.claude/rules/00-rule-routing.md` indexes every one.', '2. The rules below apply to all work. Claude Code has them in context at launch. Read', ' the ones that bear on your task.', '', From c589cedf3a07f47475c4bf6b9346f174dcfba523 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 15:04:26 +0000 Subject: [PATCH 07/16] chore(diagnostics): seed script for the staging Codex hook probe --- scripts/diagnostics/seed-codex-hook-probe.sh | 40 ++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100755 scripts/diagnostics/seed-codex-hook-probe.sh diff --git a/scripts/diagnostics/seed-codex-hook-probe.sh b/scripts/diagnostics/seed-codex-hook-probe.sh new file mode 100755 index 0000000000..b40d91b1bd --- /dev/null +++ b/scripts/diagnostics/seed-codex-hook-probe.sh @@ -0,0 +1,40 @@ +#!/bin/bash +# Seeds a disposable test repository with SAM's Codex hooks and a canary rule, so a fresh +# SAM Codex session on it can show whether repository hooks run (scripts/quality/README.md, +# "Codex hooks"). Run from the root of the test repository's checkout; it commits and pushes +# to the repository's main branch, so never run it in a repository that matters. +# +# Usage: seed-codex-hook-probe.sh +set -euo pipefail + +ref=${1:?usage: seed-codex-hook-probe.sh } +raw="https://raw.githubusercontent.com/raphaeltm/simple-agent-manager/$ref" + +mkdir -p .codex/hooks .claude/hooks .claude/rules src +curl -fsSL "$raw/.codex/hooks/rule-context.mjs" -o .codex/hooks/rule-context.mjs +curl -fsSL "$raw/.claude/hooks/verify-test-quality.mjs" -o .claude/hooks/verify-test-quality.mjs +# The hook entries of SAM's own .codex/config.toml, without its project table. +curl -fsSL "$raw/.codex/config.toml" | + sed -n '/^\[\[hooks.SessionStart\]\]/,/^\[projects/p' | sed '/^\[projects/d' >.codex/config.toml + +cat >.claude/rules/10-probe.md <<'RULE' +--- +paths: + - 'src/**' +--- + +# Probe Rule + +PROBE-RULE-CANARY-7731: files under src/ follow this probe rule. +RULE +cat >.codex/hooks/rule-scopes.json <<'JSON' +{"rules":[{"path":".claude/rules/10-probe.md","title":"Probe Rule","patterns":[{"pattern":"src/**","regex":"^src\\/.*$","literal":4}]}]} +JSON +printf 'hello\n' >src/existing.txt +printf '.tmp/\n' >>.gitignore + +grep -q '^\[\[hooks.Stop\]\]' .codex/config.toml +git add .codex .claude src .gitignore +git commit -qm "probe: Codex hooks and a canary rule" +git push -q origin HEAD:main +git rev-parse HEAD From c14caee5b4e651274e239d033ca87544612158e1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 15:05:28 +0000 Subject: [PATCH 08/16] task: progress --- tasks/active/2026-11-16-codex-repo-hook-trust.md | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/tasks/active/2026-11-16-codex-repo-hook-trust.md b/tasks/active/2026-11-16-codex-repo-hook-trust.md index e5314fad40..5267f65a1f 100644 --- a/tasks/active/2026-11-16-codex-repo-hook-trust.md +++ b/tasks/active/2026-11-16-codex-repo-hook-trust.md @@ -11,13 +11,19 @@ Codex loads a repository's `.codex/` layer only for a trusted project and runs a - Hook code ready on branch `sam/codex-rule-delivery-hook` (f3b156c19). ## Checklist -- [ ] vm-agent: CODEX_CONFIG carries `bypass_hook_trust: true` and `projects..trust_level = "trusted"`; tests -- [ ] Restore `.codex/hooks/rule-context.mjs`, generated `rule-scopes.json` + `--check` staleness, Codex hook entries (SessionStart, PreToolUse, Stop), `.gitignore` re-include -- [ ] Close Codex-hook test gaps from the PR #2790 test review (deny-once with deferred rules, cd/cwd, ignored dirs, write table, patch ops, SessionStart sources, session isolation, config wiring, real-lookup smoke) -- [ ] Docs: scripts/quality/README.md, security doc if it describes hook/trust behaviour +- [x] vm-agent: CODEX_CONFIG carries `bypass_hook_trust: true` and `projects..trust_level = "trusted"`; tests +- [x] Restore `.codex/hooks/rule-context.mjs`, generated `rule-scopes.json` + `--check` staleness, Codex hook entries (SessionStart, PreToolUse, Stop), `.gitignore` re-include +- [x] Close Codex-hook test gaps from the PR #2790 test review (deny-once with deferred rules, cd/cwd, ignored dirs, write table, patch ops, SessionStart sources, session isolation, config wiring, real-lookup smoke) +- [x] Docs: scripts/quality/README.md, security doc if it describes hook/trust behaviour - [ ] Staging: deploy, fresh VM node, Codex session on a repo with the hooks: rule text before the first edit (existing file, new file, shell), Stop gate fires; control without hooks - [ ] Reviews, CI, merge, deploy monitoring ## Acceptance - [ ] A SAM Codex session on staging runs the repository hooks (log + agent report), Stop gate continues the turn once - [ ] Unit tests prove CODEX_CONFIG content for VM and standalone shapes + +## Progress (state survives workspace restores here, not in .tmp) +- Commits: 413910d14 restore hook+tests, 2d13120a4 pure move, 94f9c1179 CODEX_CONFIG trust, b9a3745e9 docs, c589cedf3 seed script. Draft PR #2804. +- Staging: only `staging` (sammy.party) has Codex creds (smoke user toWzGjNW3IyUkCVItRQv3qSn0wI8c22y, auth-json); staging2 has none. Lease held by sam/build-insights-slice-f-2z1gpd until 15:30Z. +- Staging plan: deploy branch (no nodes running at 15:02Z); as smoke user create Artifacts project; task A (claude-code) runs `scripts/diagnostics/seed-codex-hook-probe.sh ` and pushes to main; task B (openai-codex) probes rule delivery + Stop gate. Helper: .tmp/staging/api.sh (recreate if lost). +- Reviewers running: security-auditor, go-specialist. From 71c41bb1b344d08ecb8f823e844f6694b17d0f65 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 15:09:49 +0000 Subject: [PATCH 09/16] fix(vm-agent): trust key is the ACP cwd verbatim, never /; standalone test; docs state the full trust scope --- .codex/config.toml | 2 +- .../src/content/docs/docs/architecture/security.md | 2 ++ apps/www/src/content/docs/docs/guides/agents.md | 12 +++++++++--- packages/vm-agent/internal/acp/gateway_test.go | 5 ++++- .../internal/acp/session_host_agent_config.go | 14 +++++++++++--- packages/vm-agent/internal/acp/settings_test.go | 13 ++++++++++--- 6 files changed, 37 insertions(+), 11 deletions(-) diff --git a/.codex/config.toml b/.codex/config.toml index 2f0e3d38e6..dc9557b3d3 100644 --- a/.codex/config.toml +++ b/.codex/config.toml @@ -16,7 +16,7 @@ approval_policy = "never" # Each event holds matcher groups, and each group holds a `hooks` array of handlers. # `timeout` is in seconds. Codex runs project hooks only for a trusted project whose hook # definitions are trusted; SAM's vm-agent grants both for its Codex sessions -# (packages/vm-agent/internal/acp/session_host_startup.go, buildCodexACPManagedConfigEnv). +# (packages/vm-agent/internal/acp/session_host_agent_config.go, buildCodexACPManagedConfigEnv). # `pnpm quality:agent-context-budget --check` validates these entries. # Path-scoped rule delivery: Codex loads only the root AGENTS.md by itself. This hook adds diff --git a/apps/www/src/content/docs/docs/architecture/security.md b/apps/www/src/content/docs/docs/architecture/security.md index 0e5355aeee..8f2871f911 100644 --- a/apps/www/src/content/docs/docs/architecture/security.md +++ b/apps/www/src/content/docs/docs/architecture/security.md @@ -489,6 +489,8 @@ Instant workspaces run in Cloudflare Containers and do not use repository devcon - SAM no longer has anonymous trials. The former hosted-trial product ran every visitor under one shared system account and could reuse a node across visitors; it was removed in November 2026. Its public `/api/trial/*` endpoints answer `410 Gone` without touching any data (`apps/api/src/routes/trial.ts`), and nothing creates or reuses nodes for the system account any more. - **Exception: Operations debugger tools.** When a superadmin turns them on (**Admin → Settings**, `operations.debuggerTools`), agents in the designated Operations project can read every user's nodes, workspaces, sessions and errors, read raw node logs, and capture raw, unredacted node debug packages. Every debugger tool that returns installation data passes `requireOperationsAccess` (`apps/api/src/services/operations-access.ts`), which checks four things each time: the switch is not `off`, the token belongs to the Operations project, the token is task-scoped, and that task's owner is a current superadmin, and every such call is recorded in `operations_audit_log`. The exception is `ops_get_access_status`, which returns only the caller's own mode, capability flags and denial reasons, uses the non-throwing status check, and records only task-scoped calls made inside the Operations project. Debug packages stay in the Operations project library, where only superadmins (in the app) and tokens passing the same check (over MCP) can list or download them, and the daily purge deletes them after `operations.debugPackageRetentionDays` (default 7), in deadline-bounded batches. The VM agent authorizes these reads by the node in the signed management token, not by the user it was signed for, so this control-plane check is the whole boundary: node-management tokens for non-destructive node routes are authorized by the control plane alone. See [Operations debugger tools](/docs/guides/admin-settings/#operations-debugger-tools). +Codex sessions trust the repository's `.codex/` folder the same way (`buildCodexACPManagedConfigEnv` in `packages/vm-agent/internal/acp/session_host_agent_config.go`): its hooks run at session start and around tool calls, with the credentials of the person running the session, even when another project member or repository contributor wrote them. SAM's sandbox, approval and model settings outrank the repository's Codex settings, and Codex drops provider and base-URL keys from project config. + Escaping a devcontainer reaches only the user's own VM, whether the escape comes from repository configuration, user code or an agent. On that VM it can reach the user's other workspaces on the node and the credentials the node holds for them. Opening a repository in SAM trusts its devcontainer the same way opening it in VS Code Dev Containers or GitHub Codespaces does. That repository's code already runs with the user's credentials inside the workspace. ### Where security review should focus diff --git a/apps/www/src/content/docs/docs/guides/agents.md b/apps/www/src/content/docs/docs/guides/agents.md index f2e06bc932..d445bc0486 100644 --- a/apps/www/src/content/docs/docs/guides/agents.md +++ b/apps/www/src/content/docs/docs/guides/agents.md @@ -46,9 +46,15 @@ and adds its defaults for the features you leave out. Hooks your repository defines for Codex (in `.codex/config.toml` or `.codex/hooks.json`) run in SAM sessions, as Claude Code runs the hooks in `.claude/settings.json`. Codex normally waits for someone to trust the project -and review each hook, which nobody can do in a SAM session. SAM trusts the -session's working directory and its hooks when it starts the agent, so treat a -repository's hooks like any other code you let the agent run. +and review each hook, which nobody can do in a SAM session, so SAM trusts the +session's working directory and skips the hook review when it starts the agent. +That loads the repository's whole `.codex/` folder: its hooks, its +`config.toml` (MCP servers and features included) and its command rules, plus +any hooks in the workspace's `~/.codex`. SAM's own sandbox, approval and model +settings still take precedence, and Codex ignores provider and base-URL +settings in a repository. Hooks run with the session's credentials, whoever +wrote them, so review changes to `.codex/` like any other code you let the +agent run. ### Gemini CLI diff --git a/packages/vm-agent/internal/acp/gateway_test.go b/packages/vm-agent/internal/acp/gateway_test.go index 0ebdbf2dbe..fc21732890 100644 --- a/packages/vm-agent/internal/acp/gateway_test.go +++ b/packages/vm-agent/internal/acp/gateway_test.go @@ -1772,6 +1772,9 @@ func TestWriteAgentStartupConfigCodexStandaloneWritesMcpConfig(t *testing.T) { {URL: "https://api.example.com/mcp", Token: "test-standalone-token"}, }, WorkspaceID: "ws-test-standalone", + // Instant sessions run in the standalone shape; their repository hooks + // need the same project trust as VM sessions. + ContainerWorkDir: "/workspaces/standalone-repo", }, }, } @@ -1807,7 +1810,7 @@ func TestWriteAgentStartupConfigCodexStandaloneWritesMcpConfig(t *testing.T) { t.Errorf("config.toml missing SAM MCP bearer env reference: %s", data) } assertCodexStartupTOML(t, data, "https://api.example.com/mcp", "SAM_MCP_TOKEN") - assertEnvContains(t, startup.envVars, "CODEX_CONFIG", `{"sandbox_mode":"danger-full-access","approval_policy":"never","model":"gpt-6.1-sol","bypass_hook_trust":true}`) + assertEnvContains(t, startup.envVars, "CODEX_CONFIG", `{"sandbox_mode":"danger-full-access","approval_policy":"never","model":"gpt-6.1-sol","bypass_hook_trust":true,"projects":{"/workspaces/standalone-repo":{"trust_level":"trusted"}}}`) assertEnvContains(t, startup.envVars, "INITIAL_AGENT_MODE", "agent-full-access") assertEnvContains(t, startup.envVars, "CODEX_PATH", "codex") if got := countEnvKey(startup.envVars, "CODEX_PATH"); got != 1 { diff --git a/packages/vm-agent/internal/acp/session_host_agent_config.go b/packages/vm-agent/internal/acp/session_host_agent_config.go index c1be3f74ca..9fff1d5a5d 100644 --- a/packages/vm-agent/internal/acp/session_host_agent_config.go +++ b/packages/vm-agent/internal/acp/session_host_agent_config.go @@ -33,12 +33,19 @@ type codexACPManagedConfig struct { // cannot give. The hooks come from the repository the user (or their agent) chose, and // they can do nothing the agent cannot already do in this full-access workspace. // Decision: Raphaël, 2026-11-16 (SAM idea 01M7J0TXAHGRY8CWA7Y7SJZAK0). + // + // Scope, stated so nobody mistakes it for "hooks only": trusting the project loads its + // whole .codex/ layer (config.toml, including MCP servers and features, and exec-policy + // rules), and bypass_hook_trust also runs user-level (~/.codex) hooks. Codex strips + // provider and base-URL keys from project config, and this JSON is the highest config + // layer, so the sandbox, approval and model settings above still win. BypassHookTrust bool `json:"bypass_hook_trust"` Projects map[string]codexProjectTrust `json:"projects,omitempty"` } // buildCodexACPManagedConfigEnv renders CODEX_CONFIG. workDir is the session's working -// directory (the repository checkout); Codex looks up project trust by the cwd first. +// directory (the repository checkout). It is used verbatim: it is the exact string sent as +// the ACP session cwd (session_host_handshake.go), which Codex looks up project trust by. func buildCodexACPManagedConfigEnv(settings *agentSettingsPayload, workDir string) (string, error) { config := codexACPManagedConfig{ SandboxMode: "danger-full-access", @@ -48,8 +55,9 @@ func buildCodexACPManagedConfigEnv(settings *agentSettingsPayload, workDir strin if settings != nil { config.Model = settings.Model } - if dir := strings.TrimSpace(workDir); dir != "" && path.IsAbs(dir) { - config.Projects = map[string]codexProjectTrust{path.Clean(dir): {TrustLevel: "trusted"}} + // "/" would trust whatever runs at the filesystem root; no SAM session uses it. + if path.IsAbs(workDir) && path.Clean(workDir) != "/" { + config.Projects = map[string]codexProjectTrust{workDir: {TrustLevel: "trusted"}} } encoded, err := json.Marshal(config) diff --git a/packages/vm-agent/internal/acp/settings_test.go b/packages/vm-agent/internal/acp/settings_test.go index d8bc2a64f7..20d0db0370 100644 --- a/packages/vm-agent/internal/acp/settings_test.go +++ b/packages/vm-agent/internal/acp/settings_test.go @@ -35,11 +35,18 @@ func TestBuildCodexACPManagedConfigEnv(t *testing.T) { wantProjects: map[string]projectTrust{"/workspaces/simple-agent-manager": {TrustLevel: "trusted"}}, }, { - name: "work dir is cleaned", - workDir: " /workspaces/repo/ ", - wantProjects: map[string]projectTrust{"/workspaces/repo": {TrustLevel: "trusted"}}, + // The key must equal the ACP cwd byte for byte, so it is not rewritten. + name: "dotted repository directory is used verbatim", + workDir: "/workspaces/my.site.org", + wantProjects: map[string]projectTrust{"/workspaces/my.site.org": {TrustLevel: "trusted"}}, + }, + { + name: "worktree path", + workDir: "/workspaces/repo-wt/feature", + wantProjects: map[string]projectTrust{"/workspaces/repo-wt/feature": {TrustLevel: "trusted"}}, }, {name: "relative work dir is not trusted", workDir: "repo"}, + {name: "filesystem root is not trusted", workDir: "/"}, } { t.Run(tc.name, func(t *testing.T) { envVar, err := buildCodexACPManagedConfigEnv(tc.settings, tc.workDir) From adf4108df31a1efcb459748e27151963c84327b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 15:16:14 +0000 Subject: [PATCH 10/16] fix(vm-agent): only bypass_hook_trust is needed (codex-acp already trusts the session project); real-process test of repository hooks through codex-acp --- .codex/config.toml | 5 +- .../docs/docs/architecture/security.md | 2 +- .../src/content/docs/docs/guides/agents.md | 19 +- .../vm-agent/internal/acp/gateway_test.go | 14 +- .../internal/acp/session_host_agent_config.go | 39 +-- ...sion_host_codex_repo_hooks_process_test.go | 251 ++++++++++++++++++ .../vm-agent/internal/acp/settings_test.go | 55 +--- scripts/quality/README.md | 19 +- 8 files changed, 300 insertions(+), 104 deletions(-) create mode 100644 packages/vm-agent/internal/acp/session_host_codex_repo_hooks_process_test.go diff --git a/.codex/config.toml b/.codex/config.toml index dc9557b3d3..525b053802 100644 --- a/.codex/config.toml +++ b/.codex/config.toml @@ -15,8 +15,9 @@ approval_policy = "never" # ============================================================================== # Each event holds matcher groups, and each group holds a `hooks` array of handlers. # `timeout` is in seconds. Codex runs project hooks only for a trusted project whose hook -# definitions are trusted; SAM's vm-agent grants both for its Codex sessions -# (packages/vm-agent/internal/acp/session_host_agent_config.go, buildCodexACPManagedConfigEnv). +# definitions are trusted. codex-acp trusts the session's project; SAM's vm-agent supplies +# the hook trust (bypass_hook_trust in buildCodexACPManagedConfigEnv, +# packages/vm-agent/internal/acp/session_host_agent_config.go). # `pnpm quality:agent-context-budget --check` validates these entries. # Path-scoped rule delivery: Codex loads only the root AGENTS.md by itself. This hook adds diff --git a/apps/www/src/content/docs/docs/architecture/security.md b/apps/www/src/content/docs/docs/architecture/security.md index 8f2871f911..b1a40c33a4 100644 --- a/apps/www/src/content/docs/docs/architecture/security.md +++ b/apps/www/src/content/docs/docs/architecture/security.md @@ -489,7 +489,7 @@ Instant workspaces run in Cloudflare Containers and do not use repository devcon - SAM no longer has anonymous trials. The former hosted-trial product ran every visitor under one shared system account and could reuse a node across visitors; it was removed in November 2026. Its public `/api/trial/*` endpoints answer `410 Gone` without touching any data (`apps/api/src/routes/trial.ts`), and nothing creates or reuses nodes for the system account any more. - **Exception: Operations debugger tools.** When a superadmin turns them on (**Admin → Settings**, `operations.debuggerTools`), agents in the designated Operations project can read every user's nodes, workspaces, sessions and errors, read raw node logs, and capture raw, unredacted node debug packages. Every debugger tool that returns installation data passes `requireOperationsAccess` (`apps/api/src/services/operations-access.ts`), which checks four things each time: the switch is not `off`, the token belongs to the Operations project, the token is task-scoped, and that task's owner is a current superadmin, and every such call is recorded in `operations_audit_log`. The exception is `ops_get_access_status`, which returns only the caller's own mode, capability flags and denial reasons, uses the non-throwing status check, and records only task-scoped calls made inside the Operations project. Debug packages stay in the Operations project library, where only superadmins (in the app) and tokens passing the same check (over MCP) can list or download them, and the daily purge deletes them after `operations.debugPackageRetentionDays` (default 7), in deadline-bounded batches. The VM agent authorizes these reads by the node in the signed management token, not by the user it was signed for, so this control-plane check is the whole boundary: node-management tokens for non-destructive node routes are authorized by the control plane alone. See [Operations debugger tools](/docs/guides/admin-settings/#operations-debugger-tools). -Codex sessions trust the repository's `.codex/` folder the same way (`buildCodexACPManagedConfigEnv` in `packages/vm-agent/internal/acp/session_host_agent_config.go`): its hooks run at session start and around tool calls, with the credentials of the person running the session, even when another project member or repository contributor wrote them. SAM's sandbox, approval and model settings outrank the repository's Codex settings, and Codex drops provider and base-URL keys from project config. +Codex sessions trust the repository's `.codex/` folder the same way: the Codex adapter marks the session's working directory as a trusted project, and SAM skips Codex's per-hook review (`bypass_hook_trust` in `buildCodexACPManagedConfigEnv`, `packages/vm-agent/internal/acp/session_host_agent_config.go`). The repository's hooks run at session start and around tool calls, with the credentials of the person running the session, even when another project member or repository contributor wrote them. SAM's sandbox, approval and model settings outrank the repository's Codex settings, and Codex drops provider and base-URL keys from project config. Escaping a devcontainer reaches only the user's own VM, whether the escape comes from repository configuration, user code or an agent. On that VM it can reach the user's other workspaces on the node and the credentials the node holds for them. Opening a repository in SAM trusts its devcontainer the same way opening it in VS Code Dev Containers or GitHub Codespaces does. That repository's code already runs with the user's credentials inside the workspace. diff --git a/apps/www/src/content/docs/docs/guides/agents.md b/apps/www/src/content/docs/docs/guides/agents.md index d445bc0486..04a58fe238 100644 --- a/apps/www/src/content/docs/docs/guides/agents.md +++ b/apps/www/src/content/docs/docs/guides/agents.md @@ -45,16 +45,15 @@ and adds its defaults for the features you leave out. Hooks your repository defines for Codex (in `.codex/config.toml` or `.codex/hooks.json`) run in SAM sessions, as Claude Code runs the hooks in -`.claude/settings.json`. Codex normally waits for someone to trust the project -and review each hook, which nobody can do in a SAM session, so SAM trusts the -session's working directory and skips the hook review when it starts the agent. -That loads the repository's whole `.codex/` folder: its hooks, its -`config.toml` (MCP servers and features included) and its command rules, plus -any hooks in the workspace's `~/.codex`. SAM's own sandbox, approval and model -settings still take precedence, and Codex ignores provider and base-URL -settings in a repository. Hooks run with the session's credentials, whoever -wrote them, so review changes to `.codex/` like any other code you let the -agent run. +`.claude/settings.json`. The session's working directory is a trusted Codex +project, so Codex also reads the repository's `.codex/config.toml` (MCP servers +and features included) and its command rules. Codex normally waits for someone +to review each hook, which nobody can do in a SAM session, so SAM skips that +review when it starts the agent; this also covers hooks in the workspace's +`~/.codex`. SAM's own sandbox, approval and model settings still take +precedence, and Codex ignores provider and base-URL settings in a repository. +Hooks run with the session's credentials, whoever wrote them, so review changes +to `.codex/` like any other code you let the agent run. ### Gemini CLI diff --git a/packages/vm-agent/internal/acp/gateway_test.go b/packages/vm-agent/internal/acp/gateway_test.go index fc21732890..e279cb0d98 100644 --- a/packages/vm-agent/internal/acp/gateway_test.go +++ b/packages/vm-agent/internal/acp/gateway_test.go @@ -1772,9 +1772,6 @@ func TestWriteAgentStartupConfigCodexStandaloneWritesMcpConfig(t *testing.T) { {URL: "https://api.example.com/mcp", Token: "test-standalone-token"}, }, WorkspaceID: "ws-test-standalone", - // Instant sessions run in the standalone shape; their repository hooks - // need the same project trust as VM sessions. - ContainerWorkDir: "/workspaces/standalone-repo", }, }, } @@ -1810,7 +1807,7 @@ func TestWriteAgentStartupConfigCodexStandaloneWritesMcpConfig(t *testing.T) { t.Errorf("config.toml missing SAM MCP bearer env reference: %s", data) } assertCodexStartupTOML(t, data, "https://api.example.com/mcp", "SAM_MCP_TOKEN") - assertEnvContains(t, startup.envVars, "CODEX_CONFIG", `{"sandbox_mode":"danger-full-access","approval_policy":"never","model":"gpt-6.1-sol","bypass_hook_trust":true,"projects":{"/workspaces/standalone-repo":{"trust_level":"trusted"}}}`) + assertEnvContains(t, startup.envVars, "CODEX_CONFIG", `{"sandbox_mode":"danger-full-access","approval_policy":"never","model":"gpt-6.1-sol","bypass_hook_trust":true}`) assertEnvContains(t, startup.envVars, "INITIAL_AGENT_MODE", "agent-full-access") assertEnvContains(t, startup.envVars, "CODEX_PATH", "codex") if got := countEnvKey(startup.envVars, "CODEX_PATH"); got != 1 { @@ -1841,10 +1838,9 @@ esac h := &SessionHost{config: SessionHostConfig{ GatewayConfig: GatewayConfig{ - McpServers: []McpServerEntry{{URL: "https://api.example.com/mcp", Token: "container-token"}}, - WorkspaceID: "ws-container", - ContainerUser: "testuser", - ContainerWorkDir: "/workspaces/repo", + McpServers: []McpServerEntry{{URL: "https://api.example.com/mcp", Token: "container-token"}}, + WorkspaceID: "ws-container", + ContainerUser: "testuser", }, }} startup := &agentStartup{containerID: "container-123", settings: &agentSettingsPayload{Model: "gpt-6.1-sol"}, envVars: []string{ @@ -1870,7 +1866,7 @@ esac t.Fatalf("container config contract changed: %s", content) } assertCodexStartupTOML(t, data, "https://api.example.com/mcp", "SAM_MCP_TOKEN") - assertEnvContains(t, startup.envVars, "CODEX_CONFIG", `{"sandbox_mode":"danger-full-access","approval_policy":"never","model":"gpt-6.1-sol","bypass_hook_trust":true,"projects":{"/workspaces/repo":{"trust_level":"trusted"}}}`) + assertEnvContains(t, startup.envVars, "CODEX_CONFIG", `{"sandbox_mode":"danger-full-access","approval_policy":"never","model":"gpt-6.1-sol","bypass_hook_trust":true}`) assertEnvContains(t, startup.envVars, "INITIAL_AGENT_MODE", "agent-full-access") assertEnvContains(t, startup.envVars, "CODEX_PATH", "codex") if got := countEnvKey(startup.envVars, "CODEX_PATH"); got != 1 { diff --git a/packages/vm-agent/internal/acp/session_host_agent_config.go b/packages/vm-agent/internal/acp/session_host_agent_config.go index 9fff1d5a5d..0dc6af8f49 100644 --- a/packages/vm-agent/internal/acp/session_host_agent_config.go +++ b/packages/vm-agent/internal/acp/session_host_agent_config.go @@ -5,7 +5,6 @@ import ( "encoding/json" "fmt" "log/slog" - "path" "strings" ) @@ -15,38 +14,24 @@ import ( const codexACPManagedAgentModeEnv = "INITIAL_AGENT_MODE=agent-full-access" const codexACPManagedCodexPathEnv = "CODEX_PATH=codex" -// codexProjectTrust is one entry of Codex's `projects` table. -type codexProjectTrust struct { - TrustLevel string `json:"trust_level"` -} - // codexACPManagedConfig is the CODEX_CONFIG JSON codex-acp passes to every app-server thread // as per-thread config overrides (codex rust-v0.160.0, app-server config_manager.rs). type codexACPManagedConfig struct { SandboxMode string `json:"sandbox_mode"` ApprovalPolicy string `json:"approval_policy"` Model string `json:"model,omitempty"` - // BypassHookTrust and Projects let a repository's own Codex hooks run, as Claude Code - // runs a repository's .claude/settings.json hooks. Codex loads the project .codex/ layer - // only for a trusted project, and runs a non-managed hook only once its definition is - // trusted by hash, which normally takes an interactive /hooks review that a SAM session - // cannot give. The hooks come from the repository the user (or their agent) chose, and - // they can do nothing the agent cannot already do in this full-access workspace. + // BypassHookTrust lets a repository's own Codex hooks run, as Claude Code runs a + // repository's .claude/settings.json hooks. codex-acp already marks the session's roots + // as trusted projects, so Codex loads the repository's .codex/ layer; but Codex runs a + // non-managed hook only once its definition is trusted by hash, which takes an + // interactive /hooks review that a SAM session cannot give. The hooks come from the + // repository the user (or their agent) chose, and can do nothing the agent cannot already + // do in this full-access workspace. It also enables hooks in the workspace's ~/.codex. // Decision: Raphaël, 2026-11-16 (SAM idea 01M7J0TXAHGRY8CWA7Y7SJZAK0). - // - // Scope, stated so nobody mistakes it for "hooks only": trusting the project loads its - // whole .codex/ layer (config.toml, including MCP servers and features, and exec-policy - // rules), and bypass_hook_trust also runs user-level (~/.codex) hooks. Codex strips - // provider and base-URL keys from project config, and this JSON is the highest config - // layer, so the sandbox, approval and model settings above still win. - BypassHookTrust bool `json:"bypass_hook_trust"` - Projects map[string]codexProjectTrust `json:"projects,omitempty"` + BypassHookTrust bool `json:"bypass_hook_trust"` } -// buildCodexACPManagedConfigEnv renders CODEX_CONFIG. workDir is the session's working -// directory (the repository checkout). It is used verbatim: it is the exact string sent as -// the ACP session cwd (session_host_handshake.go), which Codex looks up project trust by. -func buildCodexACPManagedConfigEnv(settings *agentSettingsPayload, workDir string) (string, error) { +func buildCodexACPManagedConfigEnv(settings *agentSettingsPayload) (string, error) { config := codexACPManagedConfig{ SandboxMode: "danger-full-access", ApprovalPolicy: "never", @@ -55,10 +40,6 @@ func buildCodexACPManagedConfigEnv(settings *agentSettingsPayload, workDir strin if settings != nil { config.Model = settings.Model } - // "/" would trust whatever runs at the filesystem root; no SAM session uses it. - if path.IsAbs(workDir) && path.Clean(workDir) != "/" { - config.Projects = map[string]codexProjectTrust{workDir: {TrustLevel: "trusted"}} - } encoded, err := json.Marshal(config) if err != nil { @@ -86,7 +67,7 @@ func (h *SessionHost) writeAgentStartupConfig(ctx context.Context, agentType str } func (h *SessionHost) writeCodexStartupConfig(ctx context.Context, cred *agentCredential, startup *agentStartup) error { - managedConfigEnv, err := buildCodexACPManagedConfigEnv(startup.settings, h.config.ContainerWorkDir) + managedConfigEnv, err := buildCodexACPManagedConfigEnv(startup.settings) if err != nil { return fmt.Errorf("cannot start Codex: %w", err) } diff --git a/packages/vm-agent/internal/acp/session_host_codex_repo_hooks_process_test.go b/packages/vm-agent/internal/acp/session_host_codex_repo_hooks_process_test.go new file mode 100644 index 0000000000..bfea870332 --- /dev/null +++ b/packages/vm-agent/internal/acp/session_host_codex_repo_hooks_process_test.go @@ -0,0 +1,251 @@ +package acp + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "path/filepath" + "strings" + "sync" + "syscall" + "testing" + "time" + + acpsdk "github.com/coder/acp-go-sdk" +) + +// Opt-in process test: the real codex-acp adapter and Codex CLI, started the way SAM starts +// them, with the CODEX_CONFIG that buildCodexACPManagedConfigEnv produces. The repository in +// the session's working directory carries SAM's own Codex hooks (rule delivery and the Stop +// gate) and a canary rule. A synthetic Responses API stands in for the model, so nothing +// leaves the machine. Set SAM_CODEX_ACP_ADAPTER and SAM_CODEX_CLI to run it, e.g. after +// `npm install @openai/codex@0.160.0 @agentclientprotocol/codex-acp@2.1.1`. +// +// The control runs the same session with the CODEX_CONFIG SAM sent before the trust change. +// codex-acp trusts the session's roots as projects either way; without bypass_hook_trust Codex +// skips every unreviewed hook, which is what made repository hooks inert in SAM. +func TestCodexRunsRepositoryHooksWithSAMConfig(t *testing.T) { + adapter := os.Getenv("SAM_CODEX_ACP_ADAPTER") + codex := os.Getenv("SAM_CODEX_CLI") + if adapter == "" || codex == "" { + t.Skip("set SAM_CODEX_ACP_ADAPTER and SAM_CODEX_CLI for the local Codex repository-hook probe") + } + t.Run("SAM config runs the repository hooks", func(t *testing.T) { + repo := codexHookProbeRepo(t) + env, err := buildCodexACPManagedConfigEnv(&agentSettingsPayload{Model: "gpt-6.1-sol"}) + if err != nil { + t.Fatal(err) + } + requests := runCodexHookProbe(t, adapter, codex, repo, env, readCommand) + all := strings.Join(requests, "\n") + for _, want := range []string{ + "SAM rule delivery is active", // SessionStart + "PROBE-RULE-CANARY-7731", // PreToolUse delivered the rule body to the model + "Test-quality gate", // Stop continued the turn with its finding + } { + if !strings.Contains(all, want) { + t.Errorf("no model request contained %q (%d requests)", want, len(requests)) + } + } + if requests[0] != "" && strings.Contains(requests[0], "PROBE-RULE-CANARY-7731") { + t.Error("rule text reached the model before any tool call touched src/") + } + logs, _ := filepath.Glob(filepath.Join(repo, ".tmp/instruction-loads/codex-*.jsonl")) + if len(logs) == 0 { + t.Error("rule-context hook wrote no delivery log") + } + }) + t.Run("a write under governed paths is refused once with the rules attached", func(t *testing.T) { + repo := codexHookProbeRepo(t) + env, err := buildCodexACPManagedConfigEnv(&agentSettingsPayload{Model: "gpt-6.1-sol"}) + if err != nil { + t.Fatal(err) + } + requests := runCodexHookProbe(t, adapter, codex, repo, env, writeCommand) + if len(requests) < 2 { + t.Fatalf("made %d model requests, want the refused call's follow-up", len(requests)) + } + if !strings.Contains(requests[1], "Not run yet") || !strings.Contains(requests[1], "PROBE-RULE-CANARY-7731") { + t.Error("the follow-up request did not carry the refusal and the rule text") + } + if _, err := os.Stat(filepath.Join(repo, "src/new.txt")); err == nil { + t.Error("the write ran before the rules were delivered") + } + }) + t.Run("control: the pre-change config leaves the hooks inert", func(t *testing.T) { + repo := codexHookProbeRepo(t) + env := `CODEX_CONFIG={"sandbox_mode":"danger-full-access","approval_policy":"never","model":"gpt-6.1-sol"}` + requests := runCodexHookProbe(t, adapter, codex, repo, env, readCommand) + all := strings.Join(requests, "\n") + for _, absent := range []string{"SAM rule delivery is active", "PROBE-RULE-CANARY-7731", "Test-quality gate"} { + if strings.Contains(all, absent) { + t.Errorf("untrusted session still delivered %q", absent) + } + } + // Liveness: the session ran a tool call, so the hooks had a chance to fire. + if len(requests) < 2 { + t.Fatalf("control session made %d model requests, want a tool round trip", len(requests)) + } + }) +} + +// codexHookProbeRepo builds a git repository with SAM's Codex hook entries (taken from this +// repository's .codex/config.toml), the real hook scripts, a canary rule scoped to src/, and +// an untracked boundary file for the Stop gate to report. +func codexHookProbeRepo(t *testing.T) string { + t.Helper() + root, err := filepath.Abs("../../../..") + if err != nil { + t.Fatal(err) + } + repo := t.TempDir() + write := func(rel, content string) { + path := filepath.Join(repo, rel) + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { + t.Fatal(err) + } + } + read := func(rel string) string { + data, err := os.ReadFile(filepath.Join(root, rel)) + if err != nil { + t.Fatalf("read %s: %v", rel, err) + } + return string(data) + } + config := read(".codex/config.toml") + start := strings.Index(config, "[[hooks.SessionStart]]") + end := strings.Index(config, "[projects.") + if start < 0 || end < start { + t.Fatal(".codex/config.toml has no hook entries to copy") + } + write(".codex/config.toml", config[start:end]) + write(".codex/hooks/rule-context.mjs", read(".codex/hooks/rule-context.mjs")) + write(".claude/hooks/verify-test-quality.mjs", read(".claude/hooks/verify-test-quality.mjs")) + write(".claude/rules/10-probe.md", "---\npaths:\n - 'src/**'\n---\n\n# Probe Rule\n\nPROBE-RULE-CANARY-7731: files under src/ follow this probe rule.\n") + write(".codex/hooks/rule-scopes.json", `{"rules":[{"path":".claude/rules/10-probe.md","title":"Probe Rule","patterns":[{"pattern":"src/**","regex":"^src\\/.*$","literal":4}]}]}`) + write("src/existing.txt", "hello\n") + write(".gitignore", ".tmp/\n") + gitEnv := append(os.Environ(), "GIT_AUTHOR_NAME=probe", "GIT_AUTHOR_EMAIL=probe@example.com", + "GIT_COMMITTER_NAME=probe", "GIT_COMMITTER_EMAIL=probe@example.com", "GIT_CONFIG_GLOBAL=/dev/null") + for _, args := range [][]string{{"init", "-q", "-b", "main"}, {"add", "-A"}, {"commit", "-qm", "probe"}} { + cmd := exec.Command("git", args...) + cmd.Dir = repo + cmd.Env = gitEnv + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("git %v: %v\n%s", args, err, out) + } + } + write("apps/api/src/services/probe.ts", "export const probe = 1;\n") + return repo +} + +// runCodexHookProbe runs one prompt through the real adapter and returns every model request +// body. The first model turn asks to read src/existing.txt through whichever shell tool the +// request offers; every later turn answers "Done". +const ( + readCommand = "sed -n 1,2p src/existing.txt" + writeCommand = "printf 'x\\n' > src/new.txt" +) + +func runCodexHookProbe(t *testing.T, adapter, codex, repo, codexConfigEnv, command string) []string { + t.Helper() + ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second) + defer cancel() + var mu sync.Mutex + var requests []string + model := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + body, _ := io.ReadAll(io.LimitReader(r.Body, 8<<20)) + mu.Lock() + requests = append(requests, string(body)) + call := len(requests) + mu.Unlock() + if dir := os.Getenv("SAM_CODEX_PROBE_DUMP"); dir != "" { + _ = os.WriteFile(filepath.Join(dir, fmt.Sprintf("request-%d.json", call)), body, 0o600) + } + item := map[string]any{"type": "message", "role": "assistant", "id": fmt.Sprintf("msg-%d", call), + "content": []any{map[string]any{"type": "output_text", "text": "Done"}}} + if call == 1 { + // The synthetic model id has no catalog entry, so the request lists no tools; + // Codex still routes a call to its unified exec tool by name. + tool := os.Getenv("SAM_CODEX_PROBE_SHELL_TOOL") + if tool == "" { + tool = "exec_command" + } + encoded, _ := json.Marshal(command) + arguments := `{"cmd":` + string(encoded) + `}` + if tool == "shell" { + arguments = `{"command":["bash","-lc",` + string(encoded) + `]}` + } + item = map[string]any{"type": "function_call", "call_id": "read-call", "name": tool, "arguments": arguments} + } + w.Header().Set("Content-Type", "text/event-stream") + for _, event := range []map[string]any{ + {"type": "response.created", "response": map[string]any{"id": fmt.Sprintf("response-%d", call)}}, + {"type": "response.output_item.done", "item": item}, + {"type": "response.completed", "response": map[string]any{"id": fmt.Sprintf("response-%d", call), + "usage": map[string]any{"input_tokens": 0, "output_tokens": 0, "total_tokens": 0}}}, + } { + data, _ := json.Marshal(event) + _, _ = fmt.Fprintf(w, "event: %s\ndata: %s\n\n", event["type"], data) + } + })) + defer model.Close() + + home := t.TempDir() + userConfig := fmt.Sprintf("model = \"gpt-6.1-sol\"\nmodel_provider = \"mock_provider\"\n[model_providers.mock_provider]\nname = \"Mock\"\nbase_url = \"%s/v1\"\nwire_api = \"responses\"\nenv_key = \"PROBE_API_KEY\"\nrequest_max_retries = 0\nstream_max_retries = 0\n", model.URL) + if err := os.WriteFile(filepath.Join(home, "config.toml"), []byte(userConfig), 0o600); err != nil { + t.Fatal(err) + } + + host, _ := newInteractionHost(newInteractionRecorder(t, http.StatusCreated)) + defer host.Stop() + adapterCommand, adapterArgs := adapter, []string{} + if filepath.Ext(adapter) == ".js" { + adapterCommand, adapterArgs = "node", []string{adapter} + } + cmd := exec.CommandContext(ctx, adapterCommand, adapterArgs...) + cmd.Dir = repo + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + cmd.Env = append(os.Environ(), "CODEX_PATH="+codex, "CODEX_HOME="+home, "PROBE_API_KEY=probe-only", + "CODEX_API_KEY=probe-only", codexConfigEnv, codexACPManagedAgentModeEnv) + cmd.Stderr = io.Discard + stdin, err := cmd.StdinPipe() + if err != nil { + t.Fatal(err) + } + stdout, err := cmd.StdoutPipe() + if err != nil { + t.Fatal(err) + } + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + defer func() { + _ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) + _ = cmd.Wait() + }() + client := acpsdk.NewClientSideConnection(&sessionHostClient{host: host, interactionGeneration: host.interactionGeneration}, stdin, stdout) + host.acpConn = client + if _, err := host.initializeACP(ctx, "openai-codex", 10*time.Second); err != nil { + t.Fatalf("ACP initialize: %v", err) + } + session, err := client.NewSession(ctx, acpsdk.NewSessionRequest{Cwd: repo, McpServers: []acpsdk.McpServer{}}) + if err != nil { + t.Fatalf("ACP new session: %v", err) + } + if _, err := client.Prompt(ctx, acpsdk.PromptRequest{SessionId: session.SessionId, + Prompt: []acpsdk.ContentBlock{acpsdk.TextBlock("Read src/existing.txt")}}); err != nil { + t.Fatalf("prompt: %v", err) + } + mu.Lock() + defer mu.Unlock() + return append([]string(nil), requests...) +} diff --git a/packages/vm-agent/internal/acp/settings_test.go b/packages/vm-agent/internal/acp/settings_test.go index 20d0db0370..283f4ba4c6 100644 --- a/packages/vm-agent/internal/acp/settings_test.go +++ b/packages/vm-agent/internal/acp/settings_test.go @@ -8,48 +8,24 @@ import ( ) func TestBuildCodexACPManagedConfigEnv(t *testing.T) { - type projectTrust struct { - TrustLevel string `json:"trust_level"` - } type managedConfig struct { - SandboxMode string `json:"sandbox_mode"` - ApprovalPolicy string `json:"approval_policy"` - Model *string `json:"model"` - BypassHookTrust *bool `json:"bypass_hook_trust"` - Projects map[string]projectTrust `json:"projects"` + SandboxMode string `json:"sandbox_mode"` + ApprovalPolicy string `json:"approval_policy"` + Model *string `json:"model"` + BypassHookTrust *bool `json:"bypass_hook_trust"` } for _, tc := range []struct { - name string - settings *agentSettingsPayload - workDir string - wantModel string - wantProjects map[string]projectTrust + name string + settings *agentSettingsPayload + wantModel string }{ - {name: "nil settings, no work dir"}, + {name: "nil settings"}, {name: "empty model", settings: &agentSettingsPayload{}}, {name: "GPT-6.1 Sol", settings: &agentSettingsPayload{Model: "gpt-6.1-sol"}, wantModel: "gpt-6.1-sol"}, {name: "JSON special characters", settings: &agentSettingsPayload{Model: `custom\"model\\variant`}, wantModel: `custom\"model\\variant`}, - { - name: "VM devcontainer work dir is trusted", - workDir: "/workspaces/simple-agent-manager", - wantProjects: map[string]projectTrust{"/workspaces/simple-agent-manager": {TrustLevel: "trusted"}}, - }, - { - // The key must equal the ACP cwd byte for byte, so it is not rewritten. - name: "dotted repository directory is used verbatim", - workDir: "/workspaces/my.site.org", - wantProjects: map[string]projectTrust{"/workspaces/my.site.org": {TrustLevel: "trusted"}}, - }, - { - name: "worktree path", - workDir: "/workspaces/repo-wt/feature", - wantProjects: map[string]projectTrust{"/workspaces/repo-wt/feature": {TrustLevel: "trusted"}}, - }, - {name: "relative work dir is not trusted", workDir: "repo"}, - {name: "filesystem root is not trusted", workDir: "/"}, } { t.Run(tc.name, func(t *testing.T) { - envVar, err := buildCodexACPManagedConfigEnv(tc.settings, tc.workDir) + envVar, err := buildCodexACPManagedConfigEnv(tc.settings) if err != nil { t.Fatalf("buildCodexACPManagedConfigEnv failed: %v", err) } @@ -74,19 +50,6 @@ func TestBuildCodexACPManagedConfigEnv(t *testing.T) { case tc.wantModel != "" && (config.Model == nil || *config.Model != tc.wantModel): t.Fatalf("model = %v, want %q", config.Model, tc.wantModel) } - if len(tc.wantProjects) == 0 && config.Projects != nil { - t.Fatalf("projects should be omitted, got %#v", config.Projects) - } - if len(tc.wantProjects) > 0 { - if len(config.Projects) != len(tc.wantProjects) { - t.Fatalf("projects = %#v, want %#v", config.Projects, tc.wantProjects) - } - for dir, want := range tc.wantProjects { - if config.Projects[dir] != want { - t.Fatalf("projects[%q] = %#v, want %#v", dir, config.Projects[dir], want) - } - } - } }) } } diff --git a/scripts/quality/README.md b/scripts/quality/README.md index b84dd70151..a5c02bfa73 100644 --- a/scripts/quality/README.md +++ b/scripts/quality/README.md @@ -139,13 +139,18 @@ that (`.claude/rules/35-vertical-slice-testing.md`). ### Codex hooks Codex runs repository hooks (`.codex/config.toml` or `.codex/hooks.json`) only for a -trusted project, and only hook definitions that have themselves been trusted. SAM's -vm-agent grants both when it starts Codex: `CODEX_CONFIG`, which codex-acp passes to every -app-server thread, carries `bypass_hook_trust: true` and a `projects.` trust entry -(`buildCodexACPManagedConfigEnv` in `packages/vm-agent/internal/acp/session_host_agent_config.go`; -decision: SAM idea 01M7J0TXAHGRY8CWA7Y7SJZAK0). Before that change no repository hook, nor -any other setting in `.codex/config.toml`, took effect in a SAM Codex session (probe task -01M7HZ6Q1EVPVPCBN00AM3WN8A). +trusted project, and only hook definitions that have themselves been trusted by hash, which +normally takes an interactive `/hooks` review. codex-acp already marks the session's roots +as trusted projects, so the repository's `.codex/` layer loads; SAM's vm-agent supplies the +missing hook trust: `CODEX_CONFIG`, which codex-acp passes to every app-server thread, +carries `bypass_hook_trust: true` (`buildCodexACPManagedConfigEnv` in +`packages/vm-agent/internal/acp/session_host_agent_config.go`; decision: SAM idea +01M7J0TXAHGRY8CWA7Y7SJZAK0). Before that change no repository hook ran in a SAM Codex +session (probe task 01M7HZ6Q1EVPVPCBN00AM3WN8A). +`TestCodexRunsRepositoryHooksWithSAMConfig` +(`packages/vm-agent/internal/acp/session_host_codex_repo_hooks_process_test.go`) runs the +real codex-acp and Codex CLI with that config against a synthetic model; set +`SAM_CODEX_ACP_ADAPTER` and `SAM_CODEX_CLI` to run it. Two hooks are configured for Codex: From 11bcd83f2b660fb5b206215046fd265f687afd85 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 15:16:34 +0000 Subject: [PATCH 11/16] task: progress (local proof, staging wait) --- tasks/active/2026-11-16-codex-repo-hook-trust.md | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/tasks/active/2026-11-16-codex-repo-hook-trust.md b/tasks/active/2026-11-16-codex-repo-hook-trust.md index 5267f65a1f..b7d11748c7 100644 --- a/tasks/active/2026-11-16-codex-repo-hook-trust.md +++ b/tasks/active/2026-11-16-codex-repo-hook-trust.md @@ -27,3 +27,7 @@ Codex loads a repository's `.codex/` layer only for a trusted project and runs a - Staging: only `staging` (sammy.party) has Codex creds (smoke user toWzGjNW3IyUkCVItRQv3qSn0wI8c22y, auth-json); staging2 has none. Lease held by sam/build-insights-slice-f-2z1gpd until 15:30Z. - Staging plan: deploy branch (no nodes running at 15:02Z); as smoke user create Artifacts project; task A (claude-code) runs `scripts/diagnostics/seed-codex-hook-probe.sh ` and pushes to main; task B (openai-codex) probes rule delivery + Stop gate. Helper: .tmp/staging/api.sh (recreate if lost). - Reviewers running: security-auditor, go-specialist. +- 15:20Z: codex-acp 2.1.1 already trusts the session roots as projects (dist/index.js `projects: Object.fromEntries(sessionRoots...)`), so the earlier "project untrusted" diagnosis was wrong: only hook trust was missing. CODEX_CONFIG now adds only `bypass_hook_trust: true` (adf4108df). +- Local real-process proof: `TestCodexRunsRepositoryHooksWithSAMConfig` with stock codex-cli 0.160.0 + codex-acp 2.1.1 (npm into .tmp/codexpkgs): SessionStart context in request 1; rule canary delivered as a developer message between the read call and its output; write `printf > src/new.txt` refused once with the rule attached, file not created; Stop gate continuation in request 3. Control (old CODEX_CONFIG): none. Mutation bypass=false -> both trusted cases red. +- Reviews: security-auditor (no CRIT; HIGH inherent; docs scope fixed; MCP redirect deferred: needs no new capability and project layer already loaded before this PR), go-specialist (no CRIT/HIGH; addressed). +- Staging lease: `staging` held by sam/implement-slice-d-inbox-vhkf2w until 17:04Z; staging2 has no Codex credentials. Wake scheduled ~17:05Z. From 2464bbc74173640d8b1874fe3248c5e88ff1fdad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 17:10:58 +0000 Subject: [PATCH 12/16] chore: task text matches the final design; note at the Codex pins to rerun the hook probe --- packages/vm-agent/internal/acp/gateway.go | 3 +++ tasks/active/2026-11-16-codex-repo-hook-trust.md | 8 ++++---- 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/packages/vm-agent/internal/acp/gateway.go b/packages/vm-agent/internal/acp/gateway.go index 7d6c4a1c49..92608fd872 100644 --- a/packages/vm-agent/internal/acp/gateway.go +++ b/packages/vm-agent/internal/acp/gateway.go @@ -27,6 +27,9 @@ const claudeACPInstallPackage = "@agentclientprotocol/claude-agent-acp@0.102.0" const claudeCodeMinVersion = "2.1.321" const claudeCodeInstallPackage = "@anthropic-ai/claude-code@2.1.321" const claudeCodeInstallCommand = "npm install -g " + claudeACPInstallPackage + " " + claudeCodeInstallPackage +// Bumping either Codex pin: rerun TestCodexRunsRepositoryHooksWithSAMConfig with the new +// packages. Repository hooks rely on the adapter trusting the session roots as projects and +// on Codex honouring the bypass_hook_trust thread override (session_host_agent_config.go). const codexACPInstallPackage = "@agentclientprotocol/codex-acp@2.1.1" const codexCLIInstallPackage = "@openai/codex@0.160.0" const codexACPInstallCommand = "npm install -g " + codexACPInstallPackage + " " + codexCLIInstallPackage diff --git a/tasks/active/2026-11-16-codex-repo-hook-trust.md b/tasks/active/2026-11-16-codex-repo-hook-trust.md index b7d11748c7..f7fb6383ca 100644 --- a/tasks/active/2026-11-16-codex-repo-hook-trust.md +++ b/tasks/active/2026-11-16-codex-repo-hook-trust.md @@ -3,15 +3,15 @@ Raphaël, 2026-11-16 (chat b0530f70, after PR #2790): "if the hooks are defined in the repo (i.e. the user or their agent set them up... then I think they should" -> "Yup. Do it." Idea 01M7J0TXAHGRY8CWA7Y7SJZAK0. ## Problem -Codex loads a repository's `.codex/` layer only for a trusted project and runs a non-managed hook only when its definition is trusted by hash. The vm-agent marks neither, so no repository hook runs in a SAM Codex session (probe 01M7HZ6Q1EVPVPCBN00AM3WN8A). Claude Code sessions already run `.claude/settings.json` hooks. +Codex runs a non-managed hook only when its definition is trusted by hash (an interactive `/hooks` review). codex-acp already trusts the session roots as projects, so the repository's `.codex/` layer loads, but the vm-agent never supplied hook trust, so no repository hook runs in a SAM Codex session (probe 01M7HZ6Q1EVPVPCBN00AM3WN8A). Claude Code sessions already run `.claude/settings.json` hooks. ## Research -- Codex rust-v0.160.0 (SAM pins 0.160.0-sam-c2.2): `codex-rs/app-server/src/config_manager.rs` accepts a per-thread request override `bypass_hook_trust` (bool); `codex-rs/config/src/loader/mod.rs` reads `projects..trust_level` from the merged config including CLI/request overrides, and `decision_for_dir` checks cwd, project root and repo root. -- codex-acp forwards `CODEX_CONFIG` JSON to every app-server thread (`packages/vm-agent/internal/acp/session_host_startup.go`, `buildCodexACPManagedConfigEnv`). ACP session cwd = `h.config.ContainerWorkDir` (`session_host_handshake.go`), same SessionHost path for VM and Instant. +- Codex rust-v0.160.0 (SAM pins 0.160.0-sam-c2.2): `codex-rs/app-server/src/config_manager.rs` accepts a per-thread request override `bypass_hook_trust` (bool), which `codex-rs/hooks/src/engine/discovery.rs` uses to run non-managed hooks without a trust hash. codex-acp 2.1.1 `dist/index.js` already sets `projects..trust_level = "trusted"`. +- codex-acp forwards `CODEX_CONFIG` JSON to every app-server thread (`buildCodexACPManagedConfigEnv`, now in `packages/vm-agent/internal/acp/session_host_agent_config.go`). ACP session cwd = `h.config.ContainerWorkDir` (`session_host_handshake.go`), same SessionHost path for VM and Instant. - Hook code ready on branch `sam/codex-rule-delivery-hook` (f3b156c19). ## Checklist -- [x] vm-agent: CODEX_CONFIG carries `bypass_hook_trust: true` and `projects..trust_level = "trusted"`; tests +- [x] vm-agent: CODEX_CONFIG carries `bypass_hook_trust: true` (codex-acp already trusts the session roots); tests - [x] Restore `.codex/hooks/rule-context.mjs`, generated `rule-scopes.json` + `--check` staleness, Codex hook entries (SessionStart, PreToolUse, Stop), `.gitignore` re-include - [x] Close Codex-hook test gaps from the PR #2790 test review (deny-once with deferred rules, cd/cwd, ignored dirs, write table, patch ops, SessionStart sources, session isolation, config wiring, real-lookup smoke) - [x] Docs: scripts/quality/README.md, security doc if it describes hook/trust behaviour From 42a7941a3a705840a3b94f4f3bfb5a581f91f9a2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 18:18:47 +0000 Subject: [PATCH 13/16] test(vm-agent): share the real-adapter process and mock-stream helpers; force HTTPS in the probe seed script SonarCloud flagged 33 duplicated new lines (the hook probe repeated the adapter-start and Responses-stream code of the pinned and steering process tests) and plain curl redirects in seed-codex-hook-probe.sh. The three tests now use startACPAdapterProcess, adapterCommand and writeResponsesTurn; the hook probe still passes against codex-acp 2.1.1 and Codex 0.160.0. gateway.go gets the blank line gofmt wants. Co-Authored-By: Claude Opus 5.5 --- packages/vm-agent/internal/acp/gateway.go | 1 + ...ssion_host_adapter_process_helpers_test.go | 59 +++++++++++++++++++ ...sion_host_codex_repo_hooks_process_test.go | 41 ++----------- .../session_host_pinned_codex_process_test.go | 42 ++----------- ...session_host_real_adapter_steering_test.go | 24 +------- scripts/diagnostics/seed-codex-hook-probe.sh | 8 ++- 6 files changed, 77 insertions(+), 98 deletions(-) create mode 100644 packages/vm-agent/internal/acp/session_host_adapter_process_helpers_test.go diff --git a/packages/vm-agent/internal/acp/gateway.go b/packages/vm-agent/internal/acp/gateway.go index 92608fd872..d9f9720ad3 100644 --- a/packages/vm-agent/internal/acp/gateway.go +++ b/packages/vm-agent/internal/acp/gateway.go @@ -27,6 +27,7 @@ const claudeACPInstallPackage = "@agentclientprotocol/claude-agent-acp@0.102.0" const claudeCodeMinVersion = "2.1.321" const claudeCodeInstallPackage = "@anthropic-ai/claude-code@2.1.321" const claudeCodeInstallCommand = "npm install -g " + claudeACPInstallPackage + " " + claudeCodeInstallPackage + // Bumping either Codex pin: rerun TestCodexRunsRepositoryHooksWithSAMConfig with the new // packages. Repository hooks rely on the adapter trusting the session roots as projects and // on Codex honouring the bypass_hook_trust thread override (session_host_agent_config.go). diff --git a/packages/vm-agent/internal/acp/session_host_adapter_process_helpers_test.go b/packages/vm-agent/internal/acp/session_host_adapter_process_helpers_test.go new file mode 100644 index 0000000000..1f53de0b64 --- /dev/null +++ b/packages/vm-agent/internal/acp/session_host_adapter_process_helpers_test.go @@ -0,0 +1,59 @@ +package acp + +import ( + "context" + "fmt" + "io" + "net/http" + "os" + "os/exec" + "path/filepath" + "syscall" + "testing" +) + +// adapterCommand runs a .js adapter through node and anything else directly. +func adapterCommand(adapter string) (string, []string) { + if filepath.Ext(adapter) == ".js" { + return "node", []string{adapter} + } + return adapter, []string{} +} + +// startACPAdapterProcess starts an ACP adapter in its own process group with piped stdio, +// as the opt-in real-adapter tests need. The returned stop kills the whole group (Codex +// spawns children) and reaps it; callers defer it. +func startACPAdapterProcess(ctx context.Context, t *testing.T, dir string, env []string, command string, args ...string) (io.WriteCloser, io.ReadCloser, func()) { + t.Helper() + cmd := exec.CommandContext(ctx, command, args...) + cmd.Dir = dir + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + cmd.Env = append(os.Environ(), env...) + cmd.Stderr = io.Discard + stdin, err := cmd.StdinPipe() + if err != nil { + t.Fatal(err) + } + stdout, err := cmd.StdoutPipe() + if err != nil { + t.Fatal(err) + } + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + return stdin, stdout, func() { + _ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) + _ = cmd.Wait() + } +} + +// writeResponsesTurn streams one synthetic Responses API turn whose only output is item. +func writeResponsesTurn(w http.ResponseWriter, call int, item map[string]any) { + id := fmt.Sprintf("response-%d", call) + sseEvents(w, + map[string]any{"type": "response.created", "response": map[string]any{"id": id}}, + map[string]any{"type": "response.output_item.done", "item": item}, + map[string]any{"type": "response.completed", "response": map[string]any{"id": id, + "usage": map[string]any{"input_tokens": 0, "output_tokens": 0, "total_tokens": 0}}}, + ) +} diff --git a/packages/vm-agent/internal/acp/session_host_codex_repo_hooks_process_test.go b/packages/vm-agent/internal/acp/session_host_codex_repo_hooks_process_test.go index bfea870332..8f650eaf57 100644 --- a/packages/vm-agent/internal/acp/session_host_codex_repo_hooks_process_test.go +++ b/packages/vm-agent/internal/acp/session_host_codex_repo_hooks_process_test.go @@ -12,7 +12,6 @@ import ( "path/filepath" "strings" "sync" - "syscall" "testing" "time" @@ -186,16 +185,7 @@ func runCodexHookProbe(t *testing.T, adapter, codex, repo, codexConfigEnv, comma } item = map[string]any{"type": "function_call", "call_id": "read-call", "name": tool, "arguments": arguments} } - w.Header().Set("Content-Type", "text/event-stream") - for _, event := range []map[string]any{ - {"type": "response.created", "response": map[string]any{"id": fmt.Sprintf("response-%d", call)}}, - {"type": "response.output_item.done", "item": item}, - {"type": "response.completed", "response": map[string]any{"id": fmt.Sprintf("response-%d", call), - "usage": map[string]any{"input_tokens": 0, "output_tokens": 0, "total_tokens": 0}}}, - } { - data, _ := json.Marshal(event) - _, _ = fmt.Fprintf(w, "event: %s\ndata: %s\n\n", event["type"], data) - } + writeResponsesTurn(w, call, item) })) defer model.Close() @@ -207,31 +197,10 @@ func runCodexHookProbe(t *testing.T, adapter, codex, repo, codexConfigEnv, comma host, _ := newInteractionHost(newInteractionRecorder(t, http.StatusCreated)) defer host.Stop() - adapterCommand, adapterArgs := adapter, []string{} - if filepath.Ext(adapter) == ".js" { - adapterCommand, adapterArgs = "node", []string{adapter} - } - cmd := exec.CommandContext(ctx, adapterCommand, adapterArgs...) - cmd.Dir = repo - cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} - cmd.Env = append(os.Environ(), "CODEX_PATH="+codex, "CODEX_HOME="+home, "PROBE_API_KEY=probe-only", - "CODEX_API_KEY=probe-only", codexConfigEnv, codexACPManagedAgentModeEnv) - cmd.Stderr = io.Discard - stdin, err := cmd.StdinPipe() - if err != nil { - t.Fatal(err) - } - stdout, err := cmd.StdoutPipe() - if err != nil { - t.Fatal(err) - } - if err := cmd.Start(); err != nil { - t.Fatal(err) - } - defer func() { - _ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) - _ = cmd.Wait() - }() + bin, binArgs := adapterCommand(adapter) + stdin, stdout, stop := startACPAdapterProcess(ctx, t, repo, []string{"CODEX_PATH=" + codex, "CODEX_HOME=" + home, + "PROBE_API_KEY=probe-only", "CODEX_API_KEY=probe-only", codexConfigEnv, codexACPManagedAgentModeEnv}, bin, binArgs...) + defer stop() client := acpsdk.NewClientSideConnection(&sessionHostClient{host: host, interactionGeneration: host.interactionGeneration}, stdin, stdout) host.acpConn = client if _, err := host.initializeACP(ctx, "openai-codex", 10*time.Second); err != nil { diff --git a/packages/vm-agent/internal/acp/session_host_pinned_codex_process_test.go b/packages/vm-agent/internal/acp/session_host_pinned_codex_process_test.go index ea3d713e66..1bb42bc1a0 100644 --- a/packages/vm-agent/internal/acp/session_host_pinned_codex_process_test.go +++ b/packages/vm-agent/internal/acp/session_host_pinned_codex_process_test.go @@ -16,7 +16,6 @@ import ( "path/filepath" "strings" "sync/atomic" - "syscall" "testing" "time" @@ -135,16 +134,7 @@ func runPinnedCodexProcessCase(t *testing.T, completionBeforeAnswer, withoutComp "name": toolName, "arguments": "{}"} } } - w.Header().Set("Content-Type", "text/event-stream") - for _, event := range []map[string]any{ - {"type": "response.created", "response": map[string]any{"id": fmt.Sprintf("response-%d", call)}}, - {"type": "response.output_item.done", "item": item}, - {"type": "response.completed", "response": map[string]any{"id": fmt.Sprintf("response-%d", call), - "usage": map[string]any{"input_tokens": 0, "output_tokens": 0, "total_tokens": 0}}}, - } { - data, _ := json.Marshal(event) - _, _ = fmt.Fprintf(w, "event: %s\ndata: %s\n\n", event["type"], data) - } + writeResponsesTurn(w, int(call), item) })) defer model.Close() home := t.TempDir() @@ -165,32 +155,10 @@ func runPinnedCodexProcessCase(t *testing.T, completionBeforeAnswer, withoutComp host.ConfigureAcpInteractions(testURLConfig()) } defer host.Stop() - adapterCommand := adapter - adapterArgs := []string{} - if filepath.Ext(adapter) == ".js" { - adapterCommand = "node" - adapterArgs = []string{adapter} - } - cmd := exec.CommandContext(ctx, adapterCommand, adapterArgs...) - cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} - cmd.Env = append(os.Environ(), "CODEX_PATH="+codex, "CODEX_HOME="+home, - "CODEX_API_KEY=probe-only", "PROBE_API_KEY=probe-only", "PROBE_MCP_TOKEN=probe-only") - cmd.Stderr = io.Discard - stdin, err := cmd.StdinPipe() - if err != nil { - t.Fatal(err) - } - stdout, err := cmd.StdoutPipe() - if err != nil { - t.Fatal(err) - } - if err := cmd.Start(); err != nil { - t.Fatal(err) - } - defer func() { - _ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) - _ = cmd.Wait() - }() + bin, binArgs := adapterCommand(adapter) + stdin, stdout, stop := startACPAdapterProcess(ctx, t, "", []string{"CODEX_PATH=" + codex, "CODEX_HOME=" + home, + "CODEX_API_KEY=probe-only", "PROBE_API_KEY=probe-only", "PROBE_MCP_TOKEN=probe-only"}, bin, binArgs...) + defer stop() client := acpsdk.NewClientSideConnection(&sessionHostClient{host: host, interactionGeneration: host.interactionGeneration}, stdin, stdout) host.acpConn = client initialized, err := host.initializeACP(ctx, "openai-codex", 2*time.Second) diff --git a/packages/vm-agent/internal/acp/session_host_real_adapter_steering_test.go b/packages/vm-agent/internal/acp/session_host_real_adapter_steering_test.go index f8b4e9a275..8939441114 100644 --- a/packages/vm-agent/internal/acp/session_host_real_adapter_steering_test.go +++ b/packages/vm-agent/internal/acp/session_host_real_adapter_steering_test.go @@ -7,10 +7,8 @@ import ( "net/http" "net/http/httptest" "os" - "os/exec" "strings" "sync" - "syscall" "testing" "time" @@ -106,26 +104,8 @@ func runRealAdapterSteer(t *testing.T, tc realAdapterSteerCase, model *steerMode }, MessageBufferSize: 200, ViewerSendBuffer: 64}) defer host.Stop() - cmd := exec.CommandContext(ctx, tc.command, tc.args...) - cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} - cmd.Env = append(os.Environ(), tc.env...) - cmd.Dir = tc.cwd - cmd.Stderr = io.Discard - stdin, err := cmd.StdinPipe() - if err != nil { - t.Fatal(err) - } - stdout, err := cmd.StdoutPipe() - if err != nil { - t.Fatal(err) - } - if err := cmd.Start(); err != nil { - t.Fatal(err) - } - defer func() { - _ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) - _ = cmd.Wait() - }() + stdin, stdout, stop := startACPAdapterProcess(ctx, t, tc.cwd, tc.env, tc.command, tc.args...) + defer stop() client := acpsdk.NewClientSideConnection(&sessionHostClient{host: host}, stdin, stdout) host.mu.Lock() diff --git a/scripts/diagnostics/seed-codex-hook-probe.sh b/scripts/diagnostics/seed-codex-hook-probe.sh index b40d91b1bd..3507ccba81 100755 --- a/scripts/diagnostics/seed-codex-hook-probe.sh +++ b/scripts/diagnostics/seed-codex-hook-probe.sh @@ -10,11 +10,13 @@ set -euo pipefail ref=${1:?usage: seed-codex-hook-probe.sh } raw="https://raw.githubusercontent.com/raphaeltm/simple-agent-manager/$ref" +fetch() { curl -fsSL --proto '=https' --proto-redir '=https' --tlsv1.2 "$raw/$1"; } + mkdir -p .codex/hooks .claude/hooks .claude/rules src -curl -fsSL "$raw/.codex/hooks/rule-context.mjs" -o .codex/hooks/rule-context.mjs -curl -fsSL "$raw/.claude/hooks/verify-test-quality.mjs" -o .claude/hooks/verify-test-quality.mjs +fetch .codex/hooks/rule-context.mjs >.codex/hooks/rule-context.mjs +fetch .claude/hooks/verify-test-quality.mjs >.claude/hooks/verify-test-quality.mjs # The hook entries of SAM's own .codex/config.toml, without its project table. -curl -fsSL "$raw/.codex/config.toml" | +fetch .codex/config.toml | sed -n '/^\[\[hooks.SessionStart\]\]/,/^\[projects/p' | sed '/^\[projects/d' >.codex/config.toml cat >.claude/rules/10-probe.md <<'RULE' From b723b9792b6c0da40519d2e3b83a556eceac9b4c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 18:19:27 +0000 Subject: [PATCH 14/16] chore: task state (staging queue, Sonar fix, CodeRabbit outcome) Co-Authored-By: Claude Opus 5.5 --- tasks/active/2026-11-16-codex-repo-hook-trust.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tasks/active/2026-11-16-codex-repo-hook-trust.md b/tasks/active/2026-11-16-codex-repo-hook-trust.md index f7fb6383ca..6fce65698b 100644 --- a/tasks/active/2026-11-16-codex-repo-hook-trust.md +++ b/tasks/active/2026-11-16-codex-repo-hook-trust.md @@ -31,3 +31,6 @@ Codex runs a non-managed hook only when its definition is trusted by hash (an in - Local real-process proof: `TestCodexRunsRepositoryHooksWithSAMConfig` with stock codex-cli 0.160.0 + codex-acp 2.1.1 (npm into .tmp/codexpkgs): SessionStart context in request 1; rule canary delivered as a developer message between the read call and its output; write `printf > src/new.txt` refused once with the rule attached, file not created; Stop gate continuation in request 3. Control (old CODEX_CONFIG): none. Mutation bypass=false -> both trusted cases red. - Reviews: security-auditor (no CRIT; HIGH inherent; docs scope fixed; MCP redirect deferred: needs no new capability and project layer already loaded before this PR), go-specialist (no CRIT/HIGH; addressed). - Staging lease: `staging` held by sam/implement-slice-d-inbox-vhkf2w until 17:04Z; staging2 has no Codex credentials. Wake scheduled ~17:05Z. +- 18:13Z: reserved in staging queue v2 (run 43925944919), position 6, turn est. 19:58:55Z. SAM wake schedule 892014a9-8b40-4fd7-8acd-af8366b4adcc at 19:45Z. +- 18:18Z: 42a7941a3 fixes SonarCloud (33 duplicated test lines -> shared helpers in session_host_adapter_process_helpers_test.go; curl --proto =https in the seed script) and a gofmt miss in gateway.go. Real-binary hook probe passes 3/3 after the refactor. +- CodeRabbit: request workflow 43925636583 succeeded 18:08Z; CodeRabbit check reports "skipping" (Review skipped) -> wait ended, recorded in PR body. From 14a835910ee1d79207cf216877f9e7b01ba6355f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 19:45:28 +0000 Subject: [PATCH 15/16] chore: task state (staging queue at 19:45Z) Co-Authored-By: Claude Opus 5.5 --- tasks/active/2026-11-16-codex-repo-hook-trust.md | 1 + 1 file changed, 1 insertion(+) diff --git a/tasks/active/2026-11-16-codex-repo-hook-trust.md b/tasks/active/2026-11-16-codex-repo-hook-trust.md index 6fce65698b..f7295e9721 100644 --- a/tasks/active/2026-11-16-codex-repo-hook-trust.md +++ b/tasks/active/2026-11-16-codex-repo-hook-trust.md @@ -33,4 +33,5 @@ Codex runs a non-managed hook only when its definition is trusted by hash (an in - Staging lease: `staging` held by sam/implement-slice-d-inbox-vhkf2w until 17:04Z; staging2 has no Codex credentials. Wake scheduled ~17:05Z. - 18:13Z: reserved in staging queue v2 (run 43925944919), position 6, turn est. 19:58:55Z. SAM wake schedule 892014a9-8b40-4fd7-8acd-af8366b4adcc at 19:45Z. - 18:18Z: 42a7941a3 fixes SonarCloud (33 duplicated test lines -> shared helpers in session_host_adapter_process_helpers_test.go; curl --proto =https in the seed script) and a gofmt miss in gateway.go. Real-binary hook probe passes 3/3 after the refactor. +- 19:45Z: holder sam/self-host-landing-slice-14gedp until 20:28Z; now position 4, turn est. 20:58:38Z. Wake schedule 540cc862-1129-4390-a924-34eba080c280 at 20:45Z. SonarCloud passes on b723b9792; rest of CI still queued. - CodeRabbit: request workflow 43925636583 succeeded 18:08Z; CodeRabbit check reports "skipping" (Review skipped) -> wait ended, recorded in PR body. From 5f5fa089600629653e19fbdaf75976f878ab5492 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Rapha=C3=ABl=20Titsworth-Morin?= Date: Mon, 16 Nov 2026 23:28:32 +0000 Subject: [PATCH 16/16] chore: archive the Codex repo-hook trust task with its staging evidence Co-Authored-By: Claude Opus 5.5 --- tasks/{active => archive}/2026-11-16-codex-repo-hook-trust.md | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename tasks/{active => archive}/2026-11-16-codex-repo-hook-trust.md (100%) diff --git a/tasks/active/2026-11-16-codex-repo-hook-trust.md b/tasks/archive/2026-11-16-codex-repo-hook-trust.md similarity index 100% rename from tasks/active/2026-11-16-codex-repo-hook-trust.md rename to tasks/archive/2026-11-16-codex-repo-hook-trust.md