Skip to content

Codex host adapter: exec policy rules, hooks, session context - #5

Open
mths-mcfs wants to merge 18 commits into
mainfrom
feat/host-codex
Open

mths-mcfs wants to merge 18 commits into
mainfrom
feat/host-codex

Conversation

@mths-mcfs

@mths-mcfs mths-mcfs commented Nov 15, 2026 •

Copy link
Copy Markdown
Owner

Summary

Codex CLI 0.169 host adapter (src/hosts/codex/**), following the Codex source at rust-v0.169.0 (commit d32063f96c2d).

CodexContextProvider.resolve      _meta (sessionId, callId, x-codex-turn-metadata) + server cwd
CodexHostAdapter.loadPolicy
  loadCodexConfig                 /etc/codex → $CODEX_HOME → --profile → trusted .codex/ (root..cwd) → -c → managed_config
                                  + requirements.toml, parent argv from /proc (-c -p -s -a --enable/--disable, exec, --yolo)
  parseRulesFile                  rules/*.rules, prefix_rule subset only, match/not_match run at load
  discoverHooks                   hooks.json + inline [hooks] per layer, requirements hooks, plugin hooks
                                  trust: [hooks.state."<src>:pre_tool_use:g:h"].trusted_hash == sha256(sorted JSON identity)
  bashContainment                 read-only → sandbox ro · workspace-write → cwd+writable_roots+tmp · danger → none
checkStatic (pure)
  bash / read / grep / glob       split commands → rules (forbidden>prompt>allow) → forced-rm / untrusted heuristics
  write / edit                    sandbox table (ask outside writable roots and in .git/.agents/.codex/.aws)
authorize
  native shape                    Bash {command} · apply_patch {command: Codex patch} (+ Write|Edit aliases)
  runHooks                        $SHELL -lc, parallel, first non-allow wins, updatedInput mapped back to args

Evidence

  • npm run verify: 149 tests pass (54 new in src/hosts/codex).
  • Real codex exec probe (isolated CODEX_HOME with copied auth, -C <scratch>, --skip-git-repo-check):
    • MCP server process.cwd() equals the -C dir; the parent /proc/<ppid>/cmdline is the codex binary with its full argv; env is HOME,LANG,LOGNAME,PATH,SHELL,USER (+ server env).
    • Before: hooks.json PreToolUse hook without state → the hook did not run.
      After: [hooks.state."<home>/hooks.json:pre_tool_use:0:0"] trusted_hash = <commandHookHash(...)> → the hook ran and received {session_id, turn_id, transcript_path, cwd, hook_event_name, model, permission_mode: "bypassPermissions", tool_name: "Bash", tool_input: {command: "echo hello-probe"}, tool_use_id} and apply_patch {command: "*** Begin Patch\n*** Add File: a.txt\n+abc\n*** End Patch"}.
    • The same hash formula reproduces three existing trusted hashes of another config (SessionStart / UserPromptSubmit hooks with additionalContextLimit).
  • Tests cover: config layering and trust (untrusted project ignored, invalid TOML → load error); rules parser (every token form, positional pattern, self-tests, 19 out-of-subset constructs → error); ls && rm -rf x with rm forbidden → deny, also through $(...), backticks, sh -c, <(...), heredocs, assignments, /bin/rm; apply_patch round-trip (add, 3 hunks, CRLF, no trailing newline, ambiguous context, 2000 random edits with whitespace/Unicode variants); hooks (exit 2, JSON deny, updatedInput, timeout with the child killed, crash, invalid JSON, exit 2 without stderr, ask, allow-only, Write|Edit alias, trust hash match/mismatch/disabled/bypass, deny-only fallback, features.hooks, allow_managed_hooks_only); sandbox mode × tool and containment; exactness (the recorded hook stdin parses and applies to exactly afterContent; bash command equals effect.command); dispatcher integration with a rewrite.

Merge Danger

Door: two-way

Nothing imports src/hosts/codex yet; the runtime still uses the test adapter until integration.

Blast Radius: additive

New dependency smol-toml (no dependencies of its own). src/server/context.ts already has a smaller CodexContextProvider; the integrator picks one.

Decisions

  • Profiles follow Codex 0.169 (--profile X loads $CODEX_HOME/X.config.toml; a profile key in config is an error, as in Codex): not the older [profiles.x] table the brief described.
  • Hooks Codex treats as non-blocking failures deny here (crash, other exit codes, exit 2 without stderr, stdout that is not JSON, invalid JSON, unsupported fields, ask, allow without updatedInput, timeout): not Codex's run-anyway or ignore behavior.
  • Hook matchers follow Rust regex semantics for the subset that translates exactly (\A, \z, leading (?i)/(?s)/(?m), named groups, POSIX classes, \x{..}, \p{..}, quantifiers). A matcher that cannot be translated exactly, or that Rust itself rejects, matches every call (stricter than Codex, which drops an invalid group): not failing the policy load.
  • A broken hooks.json, permission profiles (default_permissions/[permissions]), requirements [rules] / hooks.managed_dir, or an unknown sandbox mode in the turn metadata fail the whole policy (every call denied): not skipped with a warning as Codex does for some of them.
  • Hooks whose trust cannot be checked run in deny-only mode: plugin hooks (their trust includes a plugin content fingerprint), -c session-flag hooks, and all hooks when [hooks.state] cannot be parsed. A deny still denies, a rewrite is refused (stricter than "no-op", since ignoring a rewrite could run the unsanitized call), everything else is ignored. Plugin hooks are read from every cached version of each enabled plugin.
  • Several hooks returning different rewrites deny the call: Codex keeps whichever finished last.
  • MCP-tool hooks matching a call deny it (this server has no MCP client); prompt/agent hooks are skipped like Codex; async hooks are not run (they never change Codex's decision).
  • The exec policy splitter also looks inside substitutions, heredocs, sh -c and subshells, and evaluates any script Codex would not split as plain (comments, braces, escapes, quoted command names, dangling operators, redirections, ...) both per command and as bash -lc <script> like Codex: strictly more matches than Codex. A script it cannot tokenize is denied.
  • Commands behind wrappers are evaluated too: command, builtin, exec, nohup, time, nice, timeout, sudo/doas, env (including -S), stdbuf, xargs, find -exec, eval and trap actions; a forced rm in a trap action asks, like Codex's dangerous-command check. A wrapper option this server does not know asks (deny with approval never). Not covered: parallel, watch, ssh, su -c, which are evaluated only by their own prefix, the same as Codex's own rule evaluation.
  • An exec-policy allow does not lift bash containment (stricter than Codex).
  • Forced rm asks and the untrusted approval policy asks for unmatched commands, as in Codex; with approval never (including codex exec) what Codex would ask is a deny with source rule.
  • In workspace-write, write/edit under .git, .agents, .codex, .aws of a writable root ask, matching Codex's read-only subpaths.
  • read/grep/glob are shown to hooks and rules as cat/sed -n, rg -n ... -e, rg --files -g commands; a hook rewriting those commands denies the call (it cannot be mapped back). grep's maxResults is not in the shown command.
  • apply_patch cannot express a missing final newline or a line ending other than the file's first. When a Write/Edit/apply_patch hook would see such a change, it is denied with unsupported-config (including new files with CRLF or without a trailing newline), so a hook never approves a change different from the one applied; with no such hook the call proceeds. A hook rewrite of a patch must stay a single add/update of the same file; it becomes a whole-content write or edit.
  • Hook processes start as $SHELL -lc <command> (default /bin/sh) in the call's cwd, like Codex; the hook transcript_path is null (Codex does not send it to MCP servers).
  • CODEX_HOME is recovered from the parent's /proc/<ppid>/environ on Linux because Codex drops it from the MCP server env; on macOS the parent argv is read with ps (values with spaces may be mis-split) and CODEX_HOME only from the server env. MDM, cloud and app-server overrides are invisible.
  • Protected paths: **/.codex/**, $CODEX_HOME/**, ~/.codex/**, /etc/codex/**, the state dir, <cwd>/.mcp.json and <project root>/.mcp.json.
  • The context provider's toolUseId holds Codex's callId; hooks get tool_use_id = <callId>/<call id>; cwd source is marked env (the server process cwd).

🤖 Generated with Claude Code

mths-mcfs and others added 4 commits November 15, 2026 02:30
Add the project skeleton (package, TypeScript strict ESM, vitest, CI on
Linux, macOS and Windows, Apache-2.0 LICENSE and NOTICE, CLAUDE.md and
AGENTS.md) and the frozen contracts the sandbox, host adapter, tool and
benchmark parts build against.

The run path is executable end to end with test fakes: MCP tools/call ->
FakeSandbox -> Dispatcher (prepare, static rules, hooks, re-prepare on
updated args, commit) -> StaticHostAdapter -> MemoryToolRuntime, with
mutation ordering, cancellation, transactions with rollback, output caps
with overflow files, and a command hook runner that kills the process
group on timeout.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Commit a dispatcher-owned deep-frozen copy of each prepared call; deep
  freeze now descends into objects that are already frozen.
- Bound every await on adapter and runtime code by the run's abort signal
  or a grace: prepare, PostToolUse (which now receives the signal),
  loadPolicy (the run deadline starts before it), in-flight calls on stop,
  rollback and dispose.
- Kill the command hook's whole process group on every completion path,
  so a backgrounded descendant cannot outlive the hook.
- Send protocol and validation errors through the capped result
  formatter.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Authorize every binding call the way Codex CLI 0.169 authorizes the
equivalent native action: config layers with project trust, exec policy
rules parsed from a safe Starlark subset, sandbox and approval semantics,
and the user's trusted PreToolUse hooks with the native Bash and
apply_patch inputs, fail-closed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…efects

- Hook matchers are Rust regexes: translate the exact subset (\A, \z,
  leading flags, POSIX classes, ...) and let untranslatable matchers
  match every call.
- Scripts that are not plain for Codex (comments, braces, escapes, quoted
  command names, dangling operators) also evaluate as bash -lc <script>.
- Evaluate commands behind wrappers (command, env, sudo, exec, nohup, nice,
  timeout, time, stdbuf, xargs, find -exec, eval) and trap actions; ask
  when a wrapper option is unknown.
- Deny a write/edit whose bytes the apply_patch format cannot show exactly
  when a hook would see the patch.
- Non-JSON hook stdout denies with hook-error.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
mths-mcfs and others added 10 commits November 18, 2026 21:51
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Validate adapter decisions with a schema, reject non-string tool names and
  refresh the call summary after a hook rewrite.
- Keep overflow output out of non-private state directories and off Windows.
- Match path patterns across newlines and treat "..name" as inside a root.
- Run a single deadline from the start of the run, counting policy loading,
  and give the sandbox the time left rounded up.
- Roll back only after queued writes and edits end, report a pending
  rollback, and dispose the journal after the rollback has really finished.
- Make the fake sandbox check its deadline before steps and calls, yield
  between steps, and tie its deadline and sleeps to one signal.
- Describe the placeholder runtime the default server serves, with a
  runnable example.
- Resolve in-memory paths against the session cwd and roots (Windows paths
  included), track file revisions for rollback, and run grep and glob in a
  stoppable worker thread.
- Accept only a single --host option in serve.
- Skip spawning a hook whose run was already cancelled and stop recording
  calls in the default runtime.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Fake runtime: cap concurrent search workers per runtime; extra searches wait in a cancelable queue and a slot is reused only after its worker exits.
- Fake runtime: build the search job after a slot is held, send grep content only for files that pass the name filter, and reject a search that would copy more than the text limit.
- Fake runtime: count edit occurrences and build the diff without per-match or per-line arrays.
- Normalize Windows drive paths in the fake runtime and path patterns, and restore original revisions on rollback.
- Run: check the deadline before opening a transaction and word the pending-rollback warning accurately.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…untime

Network-share (UNC) paths are not supported: POSIX resolution folds their
leading `//` while protected-path patterns keep it, so a protected share
could go unrecognized. The fixed root, seeded files, session cwd and roots,
and call paths now refuse UNC paths before any call is prepared.

Edit and write preparation now size the change from cheap counts first and
refuse, before building the edited text or the diff, an edit with more than
MAX_EDIT_REPLACEMENTS (50,000) replacements or a diff over MAX_DIFF_LINES
(200,000) lines. Changes under the budget produce the same text and diff.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- The session roots are checked for network-share (UNC) paths even when a
  fixed root replaces them, so a UNC session root is refused, not ignored.
- setFile and revision refuse UNC paths like every other path entry point.
- The diff line budget counts the rows the diff actually has: a text that
  ends with a line break no longer counts one extra row. Edit preparation
  works out whether the edited text ends with one from where the replaced
  occurrences sit, still before building the text or the diff, so diffs
  of up to MAX_DIFF_LINES rows are prepared and only larger ones refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Keep POSIX paths with redundant leading slashes local.
Return actionable guidance when an edit exceeds the replacement limit.
Stop glob after its first extra match and skip setup for cancelled searches.
Match local protection patterns and resolved paths with the same leading-slash normalization.
Use one resolved key for in-memory reads, writes and file revisions.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@mths-mcfs
mths-mcfs changed the base branch from feat/scaffold to main November 19, 2026 16:33
@mths-mcfs
mths-mcfs marked this pull request as ready for review November 19, 2026 16:43
@mths-mcfs

Copy link
Copy Markdown
Owner Author

Note for the review: isInside in src/hosts/codex/adapter.ts:65 uses rel.startsWith('..'), so a child such as <root>/..name is treated as outside the root. PR #1 fixed the same pattern in the core during review: only .. or a ../ prefix means outside. The Codex adapter was not part of #1, so it still has the old check.

@mths-mcfs

Copy link
Copy Markdown
Owner Author

NEEDS_HUMAN on 6dfa528317ee6d4ed3e7e7792d3acd51cc6c21d8. A file rewrite needs to keep the destination and file version that the hook evaluated through the second preparation and commit. Preserving that feature requires a change to the shared dispatcher outside this adapter PR. The rewrite blocker is tracked in #15. The hook environment follow-up is #16.

One complete review round, zero corrective commits. Local typecheck and all five GitHub Actions jobs passed on the reviewed commit. The adapter fixes remain open, including the classification of workspace paths beginning with two dots. The diff stayed at 4,573 added lines counted for review (3,751 code, 822 tests, zero docs), plus 13 lockfile lines. CI run

🔐 Check commands inside scripts against execution rules

  • What changes. Execution rules also cover commands the adapter identifies inside scripts and wrapper programs.
  • Who is affected. People who use execution rules with scripts and wrapper programs.
  • When it takes effect. Once the server uses the adapter, a matching rule on an inner command can block the whole call.
  • Where it came from. The adapter chose to inspect more commands than the Codex CLI.
  • How to reverse it. Use the command boundaries of the Codex CLI.

🔐 Keep session isolation when a rule allows a command

  • What changes. An explicit execution rule allows the command within the session limits on filesystem and network access.
  • Who is affected. People who rely on execution rules to grant additional access.
  • When it takes effect. Once the server uses the adapter, a command allowed by a rule still runs within the session limits.
  • Where it came from. The request specifies containment and leaves rule exceptions open.
  • How to reverse it. Honor the extra access the Codex CLI grants through an explicit rule.

🔐 Block actions when hooks return different edits

  • What changes. The adapter blocks an action when trusted hooks propose different changes to it.
  • Who is affected. People who have more than one hook that rewrites an action.
  • When it takes effect. Once the server uses the adapter, an action with conflicting changes produces no effects.
  • Where it came from. The adapter chose how to handle conflicting rewrites.
  • How to reverse it. Use the change from the last hook to finish, as the Codex CLI does.

These choices can be reviewed once the dispatcher blocker is resolved.

The detector also found

Skip background hooks. The standalone adapter skips background hooks, including hooks used for audit logging. Those hooks will receive no events for adapter actions once the server starts using it. This can be reversed by running authorized background hooks on future actions.

Deferred. Rare patch size and line-ending cases, rule example syntax, and compatibility with absent profile files.

Verification scope. The review excluded generated lockfile lines. The current server does not wire in the adapter, so the checks cover the standalone implementation and fixtures.

@mths-mcfs mths-mcfs added the review-loop:needs-human O loop de revisão precisa de uma pessoa para continuar label Nov 19, 2026
@mths-mcfs
mths-mcfs marked this pull request as draft November 19, 2026 22:21
@mths-mcfs

Copy link
Copy Markdown
Owner Author

Decisions recorded for the next review round (the owner reviewed these on 2026-11-19):

A Codex hook rewrites a write or edit against the file content the first
preparation read, but the dispatcher re-prepared the rewritten call and
committed against whatever the disk held then. A change in between let the
commit overwrite a version the hook never saw.

An allow decision with updatedArgs can now carry bindsPreparedFile: true
(validated in DecisionSchema). With it, the re-prepared call must be the
same write/edit tool on the same absPath with the same beforeHash, or the
dispatcher denies it (source hook) and commits nothing. The Codex adapter
binds every write/edit rewrite from an apply_patch; bash rewrites and
unbound rewrites keep today's behavior, so redirects stay possible.

Fixes #15.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@mths-mcfs
mths-mcfs marked this pull request as ready for review November 19, 2026 22:30
@mths-mcfs mths-mcfs removed the review-loop:needs-human O loop de revisão precisa de uma pessoa para continuar label Nov 20, 2026
mths-mcfs and others added 2 commits November 20, 2026 05:54
# Conflicts:
#	package-lock.json
#	package.json
- Compare workspace and patch paths by whole segments, so a child named `..name` stays inside.
- Deny a call matched by a hook whose trust cannot be verified, or whose matcher has no exact translation, before any hook starts.
- Read hook trust from the --profile layer too.
- Start hooks in the session cwd; the tool cwd is still reported in the input.
- Filter hooks by tool name before reading the file or building the patch.
- Refuse `\P{..}` matchers under case folding.
- Check the reparsed patch path against the prepared file; refuse a trailing update chunk without lines.
- Protect the canonical destinations of protected paths, including missing children of linked parents.
- Show the effective read range and the search filters and caps; refuse globs rg reads as exclusions.
- Validate turn metadata and its sandbox mode; the turn can only narrow the sandbox mode.
- List rule files as regular files without following symlinks, propagate listing errors, and fail if a listed rule disappears.
- Apply the managed config to trust and project root discovery, and give managed and required features precedence over --enable/--disable.
- Validate and apply allowed approval policies, require read-only in allowed sandbox modes, and refuse unsupported containment requirements.
- Resolve relative writable roots against the config that set them and --add-dir against the cwd; make each -c override replace its leaf.
- Default an untrusted project to the untrusted approval policy; validate trust levels and root markers; reuse a linked worktree's trust only after checking its commondir; strip only platform separators from trust paths.
- Merge and read only own TOML properties.
- Refuse granular approval policies and invalid recognized settings instead of defaulting.
- Refuse a macOS parent command line that sets permission options, invalid -a/-s values, and --approve-for-me/--full-auto.
- Treat run-time expansion and globs as indeterminate argv when they could reach a rule or the forced-rm check; split only the env -S value; treat command -v/-V as a lookup.
- Resolve executable paths with the platform's path syntax.
- Fail the load when an enabled plugin may define hooks, instead of loading every cached version.
- Accept only PreToolUse hook output and exactly {command} in updatedInput.
- Fail the load when a required hook from requirements.toml cannot be loaded.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Treat a non-directory rules path as invalid config; only a missing folder is empty.
- Mark unquoted tilde words as run-time expanded, for the program and its arguments.
- Clamp a turn-narrowed sandbox mode to one the requirements allow.
- Inherit linked-worktree trust only after the Git registration round trip, and take its hooks from the main checkout like Codex.
- Refuse the real IO when no exact parent Codex argv is available (Linux only); drop the macOS ps heuristic.
- Mark env -S values with vertical tab or form feed as unsure.
- Fold ASCII case and strip executable suffixes for Windows absolute-path rule lookup.
- Fail the load for any enabled plugin instead of guessing from cached versions.
- Refuse --ignore-user-config, --ignore-rules and --trust, options without a value and malformed -c.
- Refuse requirements that set both features and feature_requirements.
- Remove the unused hook source key and environment fields.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@mths-mcfs

Copy link
Copy Markdown
Owner Author

NEEDS_HUMAN on 8950ddcc1358836b1e452a36a12188d619de3800. The incremental episode reached its three-round limit with two blockers and three major findings still open. The adapter can evaluate a search that differs from the prepared operation. The next revision can refuse searches without an exact representation or expand the authorization contract to preserve search support. Shell policy also still misses some arguments whose values are determined at execution. The remaining major findings concern linked-worktree trust and exact session argument parsing.

The base update and corrective commits 8f6a126 and 8950ddc resolved eight blockers, twenty major findings and ten minor findings, including the file rewrite guarantee in #15. Local typecheck and 194 focused tests passed. All five GitHub Actions jobs passed. CI run

The PR grew from 4,753 to 5,099 added lines counted for review (code 3,800 to 3,954, tests 953 to 1,145, docs 0). The first correction exceeded the size cap. The reduction attempt stopped because the review host ran out of temporary space.

🔐 Block operations when a plugin is enabled

  • What changes. When plugin hooks apply, an enabled plugin prevents the adapter from loading its policy, even if the plugin has no hooks.
  • Who is affected. People who keep Codex plugins enabled.
  • When it takes effect. Once the server uses the adapter, those sessions receive a configuration error before any operation.
  • Where it came from. The adapter refuses to authorize operations when it cannot verify the active plugin installation.
  • How to reverse it. Verify the active installation and load the applicable hooks.

🔐 Apply execution rules to the helper that represents the search limit

  • What changes. A rule for the helper used to express a result limit can block a search or listing.
  • Who is affected. People with execution rules that deny the helper or require approval for commands without a rule.
  • When it takes effect. Once the server uses the adapter, those rules can block otherwise permitted searches.
  • Where it came from. The adapter chose to represent the search limit as a separate command.
  • How to reverse it. Evaluate the prepared search and its limit directly.

These cards record the current choices. Once the PR reaches READY, apply review-loop:aprovado to keep them or comment with the requested change and apply review-loop:refazer.

The detector also found

Start with Linux support. The default adapter accepts a session only when it can verify the parent Codex command line. Its initial implementation refuses real sessions on Mac and Windows. A trustworthy session source for those platforms would allow support.

Deferred. A literal tilde can cause an unnecessary approval request. Issue #16 tracks the hook environment, and #19 tracks binding Bash authorization to the executor during integration.

Verification scope. The server does not wire in the adapter yet. The CI matrix covers the standalone implementation and fixtures. The review excluded generated lockfile lines.

@mths-mcfs mths-mcfs added the review-loop:needs-human O loop de revisão precisa de uma pessoa para continuar label Nov 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

review-loop:needs-human O loop de revisão precisa de uma pessoa para continuar

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant