Run Codex from a script: codex exec, structured output and CI
The non-interactive mode turns Codex into a pipeline step. Here's a CI gate that fails the build on a verdict from the agent, the flags that make runs repeatable, and one warning that matters a lot.

Codex isn’t only a terminal app you sit in front of. codex exec runs it without the interactive interface, so it can be a step in a script, a scheduled job or a CI pipeline. The non-interactive mode docs
lay out the behaviour, and the defaults tell you how OpenAI expects you to use it.
This piece covers the defaults, then builds one useful thing with them: a CI step that asks Codex to triage a failed build and fails the job when the verdict is bad.
What you get by default
codex exec streams progress to stderr and prints only the final message to stdout. That split is what makes it pipeable: the answer goes down the pipe, the chatter doesn’t. It runs in a read-only sandbox, so by default it can read your repo and report, not change anything. It also expects to be inside a Git repository, unless you pass --skip-git-repo-check.
codex exec "summarize the repo structure"
Feed it context by piping, either as extra context for an instruction or as the whole prompt:
cat build.log | codex exec "find the first real error in this log and say which file to look at"
cat prompt.txt | codex exec -
Letting it edit
To allow changes, opt in to a writable sandbox. The docs recommend the explicit flag in new scripts:
codex exec --sandbox workspace-write "add missing unit tests for src/parse.ts"
danger-full-access exists for broader access and the docs say to use it only in controlled environments. In a CI runner you’d normally reach for it never.
Structured output is what makes it scriptable
Free text is fine for a human and poor for a script. Two flags help. --output-schema takes a path to a JSON Schema and constrains the final response to it. -o (or --output-last-message) writes that final message to a file.
A small schema for a triage job:
{
"type": "object",
"properties": {
"severity": { "type": "string", "enum": ["low", "medium", "high"] },
"summary": { "type": "string" }
},
"required": ["severity", "summary"],
"additionalProperties": false
}
Save it as triage.schema.json. With the schema in place, the output is a file your script can parse without scraping prose.
A CI gate that reads the verdict
Here’s the whole step as a script. It asks Codex to triage ci.log and writes the answer to triage.json. Then a few lines of Python turn the verdict into an exit code:
#!/usr/bin/env bash
set -euo pipefail
codex exec --sandbox read-only --ephemeral --ignore-user-config \
--output-schema triage.schema.json -o triage.json \
"Triage the failures in ci.log. Do not edit anything."
python3 - <<'PY'
import json, sys
r = json.load(open("triage.json"))
print(f"triage: {r['severity']}: {r['summary']}")
sys.exit(1 if r["severity"] == "high" else 0)
PY
A read-only sandbox, no saved session files, and no dependence on anyone’s local config. The agent can look at the repository and the log and say something about them. It can’t change anything.
The plumbing can be tested with codex replaced by a small stub that writes a canned answer to whatever file -o names. That checks the schema file, the output path, the parsing and the exit codes, and it does not check what Codex would say. With a low-severity answer:
triage: low: One flaky snapshot test.
exit=0
and with a high-severity one:
triage: high: Migration 0042 fails on a clean database.
exit=1
The flags themselves are all listed in codex exec --help on codex-cli 0.154.0: --output-schema, -o, --ephemeral, --ignore-user-config, --ignore-rules, --skip-git-repo-check and --json. The script hasn’t been run against a live model, so run it on a real failed build before you wire it to anything that blocks a merge.
Put the rubric in the prompt
“Triage the failures” leaves the model to decide what high means, and it will decide differently on different days. Write the rubric down once, in a file you can review in a pull request. Adjust this one to what hurts on your team:
You are triaging a failed CI run. Read the log below and answer with the schema.
high: the build cannot ship. A migration, build or deploy step failed, a test
for a core path failed deterministically, or data could be lost.
medium: a real test failed, but it is outside the core path or looks flaky.
low: lint, formatting, a known flaky test, or an infrastructure blip.
Summarize in one sentence naming the file or step. If you cannot tell, say so
in the summary and choose medium.
Then feed the rubric and the tail of the log in as one prompt, using the stdin-as-prompt form from earlier:
{ cat triage-rubric.md; echo; echo '--- ci.log ---'; tail -n 300 ci.log; } |
codex exec --sandbox read-only --ephemeral --ignore-user-config \
--output-schema triage.schema.json -o triage.json -
The tail is deliberate. The error is usually near the end, and a smaller log is cheaper and gives the model less irrelevant text to chew on. The “if you cannot tell” line gives the model a way out other than guessing, which is what you want from a gate.
Tell people, don’t only fail the job
A red job with a one-line verdict in the logs gets ignored. The GitHub CLI can post a comment from a file with gh pr comment <number> --body-file triage.md, where -F is the short form of --body-file. Write triage.md from the same JSON (severity, summary), and the person who opened the pull request sees it where they’re already looking. The flag exists in gh 2.92, but the comment step hasn’t been run in a workflow, so test it on a throwaway pull request first.
Where to put it in a pipeline
Make the first version non-blocking. Run it only when the build has already failed, upload triage.json as an artifact, and look at a week of its answers next to what actually broke. A low that was really a broken migration tells you the prompt needs work, and you’d rather learn that while nobody depends on it.
When it’s trustworthy, gate on high only, as the script does. Gating on every non-low result turns a language model’s judgement call into a reason to block your team.
Two details help it stay useful. Give it the failing log explicitly instead of letting it hunt for one: the prompt above names ci.log. And keep the schema small. Two fields are easy to check by eye, while ten invite plausible nonsense.
Richer plumbing
--json turns stdout into a JSON Lines stream of every event, including types like thread.started, turn.completed, item.* and error. Use it when you want to log what the agent did, not just what it concluded. A multi-stage job can also continue the same session:
codex exec resume --last "now write the fix"
codex exec resume <SESSION_ID>
Make runs reproducible
CI wants determinism. The docs list flags for that: --ephemeral skips saving session files, --ignore-user-config skips $CODEX_HOME/config.toml, and --ignore-rules skips user and project execpolicy rule files. A run that ignores your laptop’s config behaves the same on a runner. The gate above uses the first two. Add --ignore-rules if you want the project’s execpolicy rules out of the picture too, and know what you’re giving up before you do.
The docs also point to the Codex GitHub Action for workflows, and say it’s the safer route for credential handling than installing the CLI by hand. Its inputs aren’t covered here, so check its README before copying a workflow from somewhere else.
The warning to read twice
For authentication, the docs show setting CODEX_API_KEY inline for a single run:
CODEX_API_KEY=<api-key> codex exec --json "triage open bug reports"
Then comes the caution. Never set OPENAI_API_KEY or CODEX_API_KEY as job-level environment variables when repository-controlled code runs in the same job. If a test script, install hook or build step from the repo can read the job’s environment, so can anyone who can open a pull request. Scope the key to the single step that needs it.
That matters more for the gate than for most scripts, because the whole point is to run on failed builds, and failed builds are often builds of someone else’s branch.
One more behaviour to know
If you configure an MCP server with required = true and it fails to start, codex exec exits with an error instead of carrying on without it. For a gate, that’s what you want: a failure to load the tools is a failure, and not a silent downgrade.
Try it before lunch
- Save the schema and the script above in a throwaway branch.
- Break a test on purpose and capture the output to
ci.log. - Run the script locally. Read
triage.jsonand decide whether the verdict was right. - Add it to CI as a non-blocking job that only runs when the build failed. Look at a week of results before it gates anything.