Codex command rules: write prefix_rule entries and check them with execpolicy
Draft prefix_rule entries, model each command's decision offline, then check the strictest decision with codex execpolicy check.
Set the boundary: what rules cover and what they do not · Write a rules draft · How a pattern matches, and which rule wins when several hit
At a glance
When you turn a batch of commands into allow, prompt or forbid rules, three things usually go wrong: pattern is only an exact prefix, a rule that omits decision becomes allow, and a compound command wrapped in bash -lc takes one of two different decision paths depending on whether Codex can split it. This guide uses the official Codex Rules page to write a three-rule prefix_rule draft, models each command's decision with an offline script, and then lays out the codex execpolicy check steps. The docs mark rules as experimental. For this batch I did not install Codex, run codex execpolicy or load any rules file, so I did not test any of the behavior, and the script's output cannot replace real product behavior.
Runtime and applicability
- Article type
- Spec file
- Verified
- Applies to
- Codex Applies to Codex command rules (.rules files). The page marks rules as experimental and subject to change, gives no version floor, and warns against assuming Work Cloud setups read local rule files.
- Tools
File locations
| Path | Scope | How it is read |
|---|---|---|
~/.codex/rules/default.rules | User-layer rules file; Codex writes here when you add a command to the allow list in the TUI. | Scanned when Codex starts; restart Codex after adding or changing rules. |
<repo>/.codex/rules/ | Project-local rules, kept in .rules files under the rules/ folder. | Loaded only when the project's .codex/ layer is trusted. |
rules/ (Team Config locations) | The rules/ folder inside Team Config locations. | The page lists it among the places scanned at startup and does not name the directory. |
requirements.toml ([rules] table) | Restrictive rules enforced by admins; decision must be prompt or forbidden. | Merged with regular .rules files, and the most restrictive decision still wins; the field shapes are on the Managed configuration page. |
When to use
- You have a batch of commands you want to allow, prompt for or forbid outside the sandbox, and need to write
prefix_ruleentries and check every command's decision offline before shipping them. - A tool sends several commands wrapped in
bash -lcand you need to judge whether one allow rule can be borrowed.
When not to use
- You need to adjust
sandbox_mode,approval_policyor the command network proxy. Those are a different layer of configuration, and a rules file does not replace them. - You use Codex in Work Cloud containers or with Local computer access with Work Cloud. The local
.rulesinstructions on this page do not apply there, managed command rules use therulesTOML field in Agent Security, and this guide only touches on it in therequirements.tomlsection.
Set the boundary: what rules cover and what they do not
Codex command rules answer one question: when a command asks to run outside the sandbox, should Codex allow it, ask you first, or refuse it. The official page describes rules as controlling which commands Codex can run outside the sandbox, and it says up front that rules are experimental and may change. How sandbox mode and approval policy combine is a separate question that another guide on this site covers; this one is only about writing a rules file and checking it offline.
One batch of commands runs through the whole guide. The goal: ask before viewing a PR, allow staging files without a prompt, refuse commands that start with rm, and make sure a compound command wrapped in bash -lc cannot slip past on the strength of one allow rule. The input is the five commands below. The deliverable is a rules draft with match and not_match examples, plus a checklist that records, for each command, how many sub-commands it splits into, which rule each one hits and the final decision.
gh pr view 7888 --json title,body,comments: ask every time.git add src/app.ts: allow without a prompt.rm -rf /tmp/build: refuse.bash -lc 'git add . && rm -rf /': one allowed part plus one refused part, so the whole must be refused.bash -lc 'git add . > added.log': has a redirection, so it must not be allowed just becausegit addis allowed.
Prerequisites and scope. A rules file is a .rules file inside a rules/ folder next to an active config layer, for example ~/.codex/rules/default.rules. At startup Codex scans rules/ under every active config layer, including Team Config locations and the user layer ~/.codex/rules/. Project rules under <repo>/.codex/rules/ load only when that project's .codex/ layer is trusted. Restart Codex after adding or changing a rule. The .rules instructions on this page apply to Codex, and the docs warn against assuming that Local computer access with Work Cloud reads local rule files. Managed command rules for that setup use the rules TOML field in Agent Security, and Work cloud containers keep using the existing Work Cloud policies.
Write a rules draft
The draft below is original to this guide and uses only the fields the official page describes: three prefix_rule entries covering prompt, allow and forbidden. Each carries match and not_match examples, which act as inline unit tests: the docs say Codex validates them when it loads your rules, so you catch mistakes before a rule takes effect. I used Python's parser only to confirm the syntax is valid. I did not use a Starlark parser, and Codex never read this file.
# Draft for ~/.codex/rules/default.rules (Codex has not read this file)
# Ask before reading pull requests outside the sandbox.
prefix_rule(
pattern = ["gh", "pr", ["view", "list"]],
decision = "prompt",
justification = "Viewing PRs is allowed with approval",
match = [
"gh pr view 7888",
"gh pr view 7888 --json title,body,comments",
"gh pr list --repo openai/codex",
],
not_match = [
# The pattern must be an exact prefix: --repo sits between pr and view.
"gh pr --repo openai/codex view 7888",
],
)
# Staging files runs without a prompt.
prefix_rule(
pattern = ["git", "add"],
decision = "allow",
match = ["git add .", "git add src/app.ts"],
not_match = ["git commit -m wip"],
)
# Deleting files is refused, and the justification names an alternative.
prefix_rule(
pattern = ["rm"],
decision = "forbidden",
justification = "Do not delete files directly; ask the user to remove them.",
match = ["rm notes.txt", "rm -rf /tmp/build"],
not_match = ["rmdir build"],
)
The third element of the first pattern is ["view", "list"], the union form the docs describe: it matches view or list at that argument position. The docs also say decision defaults to allow, so a rule that omits decision allows the command; the draft writes it out on every rule. justification is optional. The draft sets it on the prompt and forbidden rules, and the forbidden one also names an alternative, which the docs recommend doing when appropriate.
| Field | Required and default | What the docs say | Use in the draft |
|---|---|---|---|
pattern | Required | A non-empty list; each element is a literal string or a union of alternative literals for that argument position | gh pr [view|list], git add, rm |
decision | Optional, default allow | allow runs outside the sandbox without a prompt; prompt asks before each matching invocation; forbidden blocks without asking | Set explicitly on all three rules, no reliance on the default |
justification | Optional, non-empty | A human-readable reason that may appear in approval prompts or rejection messages | Set on the prompt and forbidden rules |
match / not_match | Optional, default [] | Examples validated when the rules load, to catch mistakes early | Each rule lists commands that should and should not match |
How a pattern matches, and which rule wins when several hit
- Codex treats the command it is about to run as a list of arguments (like what
execvp(3)receives) and compares it topattern. patternmust be an exact prefix. In the official example,gh pr --repo openai/codex view 7888does not match[gh, pr, view], because--reposits betweenprandview.- A union replaces only the argument position it sits in and leaves the other positions alone.
- When several rules match, the most restrictive decision applies:
forbiddenoverprompt,promptoverallow. Adding aforbiddenrule for a command therefore always outweighs an existingallow. - Editorial inference, not an official statement: since matching compares whole arguments, the first argument of
rmdir buildisrmdirand does not hit[rm], which is why the draft uses it innot_match. The page does not spell this out, so confirm it through load-time validation orcheck. - What happens when no rule matches is not stated on the page.
Compound commands wrapped in bash -lc
Some tools wrap several shell commands in a single invocation, for example ["bash", "-lc", "git add . && rm -rf /"]. The docs say Codex treats bash -lc, bash -c and their zsh and sh equivalents specially, because one string can hide more than one action.
When Codex can split: the script is a linear chain of plain words (no variable expansion, no VAR=..., $FOO, * and so on) joined only by &&, ||, ; or |. Codex parses it with tree-sitter, splits it into individual commands, applies your rules to each, and the most restrictive result wins. So even if you allow git add, git add . && rm -rf / is not allowed automatically, because rm -rf / is evaluated separately.
When Codex does not split: if the script uses redirection (>, >>, <), substitution ($(...) and backticks), environment variables (FOO=bar), wildcards (*, ?) or control flow (if, for and similar), Codex does not try to interpret or split it, and the whole invocation is treated as one call, ["bash", "-lc", "<full script>"], for rule matching. By a literal reading of prefix matching, that whole call starts with bash and does not hit [git, add], so the allow on the inner [git, add] does not carry over to the whole call. The whole call is matched on its own as [bash, -lc, script], and a prefix written for that wrapper invocation can still hit it; the docs say nothing more.
| bash -lc script | Feature | Handling the docs describe |
|---|---|---|
git add . && rm -rf / | Linear chain, only && | Split into [git, add, .] and [rm, -rf, /], each evaluated, the most restrictive wins |
git add . > added.log | Redirection | Not split; the whole script is evaluated as [bash, -lc, script] |
git add *.md | Wildcard | Not split, same as above |
FOO=1 git add . | Environment variable assignment | Not split, same as above |
for f in *.md; do git add $f; done | Control flow, wildcard and variable | Not split, same as above |
Model each command's decision with a script
The script below models the three rules offline: per-argument prefix and union matching, the most restrictive decision, and the bash -lc split decision. It approximates the "does not split" features the docs list with regular expressions and is not a tree-sitter parser. For quotes, braces, background operators or newlines the docs do not say what happens, so the script labels them unmodeled before any other check and gives no verdict; a > inside quotes is therefore never read as a redirection. Parentheses and subshells are also labeled unmodeled before the whole-script features are checked; only a non-nested $(...) substitution is set aside first and then stays a whole-script case as the docs list it, so mixing parentheses with a substitution does not slip past this step. It also adds an editorial rule that is not official behavior: a command counts as released only when every part matched a rule and the most restrictive decision is allow; a part that matched no rule is never treated as released.
import assert from "node:assert/strict";
// The three rules from the draft file; a pattern element is a string or a list of alternatives.
const rules = [
{ pattern: ["gh", "pr", ["view", "list"]], decision: "prompt" },
{ pattern: ["git", "add"], decision: "allow" },
{ pattern: ["rm"], decision: "forbidden" },
];
const RANK = { allow: 0, prompt: 1, forbidden: 2 };
const strictest = (list) => list.reduce((a, b) => (RANK[b] > RANK[a] ? b : a));
// One argument list: strictest decision of the matching rules, or null when none match.
const one = (argv) => {
const hits = rules.filter(({ pattern }) => argv.length >= pattern.length &&
pattern.every((p, i) => (Array.isArray(p) ? p.includes(argv[i]) : p === argv[i])));
return hits.length ? strictest(hits.map((r) => r.decision)) : null;
};
const WRAPPED = /^(?:bash|zsh|sh)$/;
const WHOLE = /[<>$`*?]|(?:^|\s)\w+=|\b(?:if|for|while|case|until)\b/; // docs: redirection, substitution, variables, wildcards, control flow
export function check(argv) {
const wrapped = WRAPPED.test(argv[0]) && ["-lc", "-c"].includes(argv[1]) && argv.length === 3;
if (!wrapped) return { mode: "plain", parts: [one(argv)] };
const script = argv[2];
// The docs do not say how quotes, braces, background operators or newlines are handled: no verdict, checked first.
if (/["'{}\n]|&(?!&)/.test(script.replaceAll("&&", ""))) return { mode: "unmodeled", parts: [] };
// Parentheses and subshells are not modeled either, checked before the whole-script features;
// only a plain, non-nested $(...) substitution is taken out first.
if (/[()]/.test(script.replace(/\$\([^()]*\)/g, ""))) return { mode: "unmodeled", parts: [] };
if (WHOLE.test(script)) return { mode: "whole-script", parts: [one(argv)] };
const parts = argv[2].split(/&&|\|\||;|\|/).map((s) => one(s.trim().split(/\s+/)));
return { mode: "split", parts };
}
// Editorial rule: release only when every part matched and the strictest decision is allow.
export function verdict(argv) {
const { mode, parts } = check(argv);
if (mode === "unmodeled") return { mode, decision: "unmodeled", released: false };
const known = parts.filter(Boolean);
const decision = known.length ? strictest(known) : "none";
return { mode, parts: parts.map((p) => p ?? "none"), decision, released: known.length === parts.length && decision === "allow" };
}
const line = (argv) => { const v = verdict(argv); console.log(argv.join(" "), "=>", JSON.stringify(v)); return v; };
// Inline tests for the draft rules (whitespace-split examples only).
const test = (cmd) => one(cmd.split(/\s+/));
assert.equal(test("gh pr view 7888"), "prompt");
assert.equal(test("gh pr list --repo openai/codex"), "prompt");
assert.equal(test("gh pr --repo openai/codex view 7888"), null);
assert.equal(test("rmdir build"), null);
assert.equal(test("rm -rf /tmp/build"), "forbidden");
assert.equal(line(["gh", "pr", "view", "7888", "--json", "title,body,comments"]).decision, "prompt");
assert.equal(line(["git", "add", "src/app.ts"]).released, true);
assert.equal(line(["bash", "-lc", "git add . && rm -rf /"]).decision, "forbidden");
assert.equal(line(["bash", "-lc", "git add . && gh pr view 7888"]).decision, "prompt");
assert.deepEqual(line(["bash", "-lc", "git add . > added.log"]).mode, "whole-script");
assert.equal(line(["bash", "-lc", "git add *.md"]).released, false);
assert.equal(line(["bash", "-lc", "FOO=1 git add ."]).released, false);
assert.equal(line(["bash", "-lc", "git add . && make test"]).released, false);
assert.equal(line(["rm", "-rf", "/tmp/build"]).decision, "forbidden");
assert.equal(line(["bash", "-lc", "git add 'a>b'"]).decision, "unmodeled");
assert.equal(line(["bash", "-lc", "git add . && echo $(date)"]).mode, "whole-script");
assert.equal(line(["bash", "-lc", "(git add .)"]).decision, "unmodeled");
assert.equal(line(["bash", "-lc", "(git add . > added.log)"]).decision, "unmodeled");
assert.equal(line(["bash", "-lc", "(git add .) && echo $(date)"]).decision, "unmodeled");
console.log("prefix rule model: all assertions passed");
Save the script as an .mjs file and run it with node. I ran it with Node and every assertion passed. The table organizes its output. It is the script model's result, not codex execpolicy output, and it cannot stand in for real product behavior.
| Command | Sub-commands | Hit per part | Strictest decision | Released |
|---|---|---|---|---|
gh pr view 7888 --json title,body,comments | 1 (no shell wrapper) | prompt | prompt | No, asks first |
git add src/app.ts | 1 (no shell wrapper) | allow | allow | Yes |
rm -rf /tmp/build | 1 (no shell wrapper) | forbidden | forbidden | No, refused |
bash -lc 'git add . && rm -rf /' | 2 | allow, forbidden | forbidden | No |
bash -lc 'git add . && gh pr view 7888' | 2 | allow, prompt | prompt | No, asks first |
bash -lc 'git add . > added.log' | 1 (whole script, redirection) | No rule hit | None | No |
bash -lc 'git add *.md' | 1 (whole script, wildcard) | No rule hit | None | No |
bash -lc 'FOO=1 git add .' | 1 (whole script, variable assignment) | No rule hit | None | No |
bash -lc 'git add . && make test' | 2 | allow, no rule hit | allow (matched part only) | No, make test has no rule |
bash -lc "git add 'a>b'" | Not modeled (quotes) | unmodeled | No verdict | No |
The row for bash -lc 'git add . && make test' is easy to misread: the strictest decision looks like allow, but make test has no rule, so the script does not treat the whole command as released. The docs do not say how a sub-command with no matching rule combines with an allow, so do not assume the whole command is released.
Check it with codex execpolicy check in a real setup
codex execpolicy check tests how your rules apply to a command. The docs say it emits JSON showing the strictest decision and any matching rules, including the justification values of matched rules. Repeat --rules to combine files, and add --pretty to format the output. The page does not list the JSON field names, so the checklist records three items, the strictest decision, the matching rules and the justification, without assuming field names.
RULES=~/.codex/rules/default.rules
codex execpolicy check --pretty --rules "$RULES" -- gh pr view 7888 --json title,body,comments
codex execpolicy check --pretty --rules "$RULES" -- git add src/app.ts
codex execpolicy check --pretty --rules "$RULES" -- rm -rf /tmp/build
codex execpolicy check --pretty --rules "$RULES" -- bash -lc 'git add . && rm -rf /'
codex execpolicy check --pretty --rules "$RULES" -- bash -lc 'git add . > added.log'
The page only demonstrates --rules ~/.codex/rules/default.rules. It does not say whether other paths work, or whether check splits bash -lc the same way, so the results of the last two compound commands are open items only, neither known conclusions nor acceptance criteria.
- Save the draft as
~/.codex/rules/default.rules. If the file already has content, back it up and merge instead of overwriting it. Check: the file sits under arules/folder and ends in.rules. - Run
checkonce for each command in the table above and record the strictest decision, the matching rules and thejustification. Check: the three commands withoutbash -lcmatch the table, meaninggh pr viewhits the prompt rule and shows its reason,git addhits the allow rule, andrmhits the forbidden rule and shows the alternative. - Pass each compound command to
checkas the whole[bash, -lc, script]and record only the strictest decision and the matching rules it prints. The docs do not say whetherchecksplits such scripts or what happens when no rule matches, so this step has no pass criterion and the model table above is not its expected answer. Record any difference from the model table as an open item, do not use it to judge the rule right or wrong, and do not treat those commands as released. - Restart Codex so the rules load. Codex validates
matchandnot_matchat load time, and the page does not say what a validation failure looks like, so after the restart confirm the rule is live with a harmless command that should trigger a prompt, such asgh pr view. - Hand over and keep the record: the rules file, the checklist (sub-command count, matching rules, final decision and
justificationfor each command) and the stop conditions in the next section.
Which layers supply rules, and who changes them
| Source | Location | What the docs say |
|---|---|---|
| User layer | ~/.codex/rules/default.rules | The official example location; when you add a command to the allow list in the TUI, Codex writes to this file so later runs can skip the prompt |
| Project layer | <repo>/.codex/rules/ | Loads only when the project's .codex/ layer is trusted |
| Team Config | rules/ next to an active config layer | The page lists Team Config locations among the places scanned at startup; it does not name the directory |
requirements.toml | The [rules] table in Global requirements.toml | Admins enforce restrictive rules; they merge with regular .rules files and the most restrictive decision still wins; decision is required and must be prompt or forbidden, never allow; pattern elements are written as tables such as { token = "rm" } or { any_of = [...] }, unlike the plain strings in .rules |
When Smart approvals are on, which is the default, Codex may propose a prefix_rule during an escalation request, and the docs advise reviewing the suggested prefix carefully before accepting it. By the definition of prefix matching, a short prefix such as [git] hits every command that starts with git, so check how short the prefix is and whether decision is allow.
The TUI allow list writes to the user-layer file, so your default.rules may contain rules you did not write by hand. check evaluates the files you pass with --rules, and repeating the flag combines several files. The page does not say whether it merges other layers automatically, or whether it can read requirements.toml or reproduce the full effect of managed rules. So use check only on the .rules files you have; confirm managed requirements.toml rules separately against the Managed configuration page and record them as an open item.
What is not covered, stop conditions and the deliverable
The following are not stated on the official pages, and this guide does not infer them:
- How a command is handled when no rule matches.
- The exact JSON fields
checkemits, and whether it splitsbash -lcthe way Codex does. - How quotes, parentheses, background operators or newlines inside a bash -lc script are split.
- Any restriction on
.rulesfile names (the page only usesdefault.rulesas its example), and which paths--rulesaccepts. - What a
matchornot_matchvalidation failure looks like. - Starlark language details: the page only says the syntax resembles Python, that the rules engine runs without side effects, and links to the language spec.
- The exact directory of Team Config locations.
- Whether
checkcan readrequirements.tomlor reproduce the full effect of managed rules.
Stop conditions: if any of the following holds, do not ship the rules and do not treat the command as released.
- A script has a redirection, substitution, variable, wildcard or control flow but you rely on an inner allow such as
[git, add]to release it (that allow does not carry over to the whole call). - For the three commands without
bash -lc, thecheckoutput differs from the checklist's expectation. - An
allowrule'spatternis only one common command name. - A
forbiddenrule refuses a command that has an appropriate alternative, yet the alternative is not written down (the docs only suggest including one when appropriate, not require it; this gate is this guide's own). - The rules are meant for a Work Cloud setup but exist only as local
.rules.
This guide relies on two official pages: the Rules page, and the "Enforce command rules from requirements" section of the Managed configuration page, both read on 2026-11-24. I did not install Codex, run codex execpolicy, load any rules file or allow a command in any environment, so I did not test any of this behavior; the script is only an offline model of the documented description. The docs mark rules as experimental and subject to change, so recheck against the current version before you ship.
Sources
All links are official pages; verification dates are listed per source, and links point to the version checked.