How to Build Codex Automation: A Workflow Guide to AGENTS.md, Hooks, Automations, and Playwright MCP

A walkthrough of what AGENTS.md, Hooks, Automations, and Playwright MCP each do, and how to combine them into a Codex automation workflow that is controlled, auditable, and reversible.

12 min read
How to Build Codex Automation: A Workflow Guide to AGENTS.md, Hooks, Automations, and Playwright MCP

AI Code With · Codex Automation Architecture and Security Practices

Once Codex becomes part of your daily work, you quickly run into four features: AGENTS.md, Hooks, Automations, and Playwright MCP.

They all sound like "automation," but they sit at different layers. AGENTS.md holds long-term project rules. A Hook runs a deterministic script when a lifecycle event fires. An Automation decides when a task runs in the background. Playwright MCP extends what Codex can execute into the browser.

Mix the four without a plan and the usual results show up: rules keep growing, Hooks run twice, a scheduled task edits local files while nobody is watching, and a browser automation uses a logged-in session to click all the way through to "Publish." The right move is to assign each layer its job first, then add risk step by step.

Mature automation isn't about having more features. It's about being able to explain the boundaries of your rules, triggers, execution, and external actions.

1. Understand the Four Layers: They Don't Solve the Same Problem

LayerToolResponsibilityTypical Question
Rules layerAGENTS.mdGives Codex long-term project constraints, plus testing and delivery requirements"What must I follow every time I work in this repo?"
Lifecycle layerHooksRuns a deterministic script when a specific event occurs"Log audit info after every tool call"
Scheduling layerAutomations / Scheduled tasksRuns tasks in the background on a schedule or on supported events"Check for blockers in the project every day at 9:30"
External execution layerPlaywright MCPLets Codex operate browser pages"Read a web page, fill out a form, save a draft"

The four layers can be combined, but you don't have to use all of them. A repo that only needs long-term project conventions is fine with just AGENTS.md. A simple scheduled summary may need only an Automation. Bring in Playwright MCP only when a task truly requires browser actions.

2. AGENTS.md: Write Long-Term Rules as Things You Can Verify

AGENTS.md works like a project manual for Codex. Good rules aren't "please write high-quality code." They are observable, enforceable, and able to fail.

# Project instructions

## Tests

- After changing Python files, run: python3 -m unittest discover -s tests -v

- If tests can't run, explain why. Never write "tests passed"

## Editing

- Do not modify the generated/ directory

- Preserve the user's existing uncommitted changes

## Response

- When done, list the modified files, the test commands, and the actual results

Rules like these let you tell directly whether they took effect. Whether you're in a manual session, a scheduled task, or a more complex automation, you won't have to re-explain the basics in every prompt.

AGENTS.md Precedence: Only One File Per Directory

According to the current OpenAI docs, Codex Home defaults to ~/.codex. At the global level, if AGENTS.override.md exists, it takes priority. Otherwise, Codex reads AGENTS.md.

At the project level, Codex walks from the project root down to the current working directory. In each directory it looks in this order: AGENTS.override.md, then AGENTS.md, then any custom fallback filenames. At most one file is loaded per directory.

repo/

├── AGENTS.md

└── frontend/

├── AGENTS.override.md

└── src/

The root directory can hold repo-wide testing requirements, while an override under frontend holds frontend-specific ones. The closer a rule is to the current working directory, the more specific it is, and it can override conflicting rules from higher levels.

32 KiB Is the Combined Default Limit, Not a Per-File Limit

The current docs are explicit: once the merged project instructions reach project_doc_max_bytes, Codex stops adding more. The default is 32 KiB.

So don't turn AGENTS.md into a second employee handbook. When rules keep growing, do three things first: remove duplicates, push subdirectory rules down into their own directories, and turn one-off procedures into a Skill.

How to Verify AGENTS.md Is Actually Being Read

In a temporary project, add a very obvious but harmless test rule, such as "the first line of your answer must be PROJECT_RULE_ACTIVE." Give the subdirectory override a different marker. Then send read-only requests from the root directory and from the subdirectory.

When you're done, delete the test markers. Don't leave rules that exist only for testing in a real repo.

If a rule doesn't take effect, check these first: whether the current working directory is the one you think it is, whether a closer override exists, and whether the total rule size is too large or the rules contradict each other.

3. Hooks: Not a Timer, but a Script That Runs When a Lifecycle Event Fires

Hooks are well suited to deterministic tasks: recording audit info, checking a tool call, writing state when a session ends. They are also one of the worst features to copy-paste into production, because a Hook really does execute a script.

The current OpenAI Hooks docs list the common locations clearly:

• ~/.codex/hooks.json

• ~/.codex/config.toml

• <repo>/.codex/hooks.json

• <repo>/.codex/config.toml

If a single layer has both hooks.json and an inline [hooks] section in config.toml, Codex merges them and shows a warning at startup. For your first setup, pick just one style.

What Many People Miss Isn't the Config, but Trust

Unmanaged Hooks currently have to be reviewed and trusted first. Codex records trust state against the hash of the Hook's current definition. If the Hook changes, you need to review it again.

/hooks

Use /hooks to see sources, pending reviews, trust status, and disabled entries. An article that only says "it runs automatically once configured" skips the most important step.

Your First Hook: Just Write a Harmless Timestamp

For the first one, don't auto-format, don't run git commit, and don't touch production files. Start with a script that only writes a timestamp to the system temp directory:

• It reads no credentials.

• It makes no network calls.

• It doesn't modify the project.

• It doesn't run Git.

• It returns an explicit exit code.

First confirm the event fires, then make the script fail on purpose once and see how Codex reports it. That's how you really learn a Hook's events, inputs, and error propagation.

Multiple Hooks May Run Concurrently, So Don't Assume an Order

The current official docs are explicit: multiple matching command hooks on the same event may start concurrently, and background Hooks may finish in a different order.

So don't create implicit dependencies like this: Hook A generates a file, and Hook B reads it right away. Unless you implement synchronization yourself, that order isn't guaranteed.

4. Automations: Start with Read-Only Checks, Not Auto-Editing Code on Day One

Scheduled tasks are good for pushing repetitive work into the background, but the first task should be as boring as possible. You need to verify that it runs on time, where its context comes from, where the output ends up, and whether its permissions stay in bounds.

Every weekday at 09:30, check the current project:

1. Read the git status and the most recent test results;

2. Do not modify files, do not commit, and do not send external messages;

3. Output uncommitted changes, failing tests, and items that need manual attention;

4. If nothing is wrong, write "No new blockers";

5. On failure, keep an error summary and do not retry automatically in a loop.

OpenAI's current docs recommend testing the prompt by hand in a regular Chat first, then moving it into Scheduled. Check the first few runs manually too, to confirm the scope is right and the output can be reviewed.

Web, desktop local projects, and CLI / IDE are not the same way of running

The Scheduled management interface currently lives mainly in ChatGPT Web and the desktop app. The CLI and IDE extension can help you get a prompt, Skill, or project change working first, but they don't have the same Scheduled management interface.

Web tasks can use uploaded content, connected tools, Skills, and Plugins, but they do not keep the local directories on your computer between runs.

If a Scheduled task needs to read a project on your machine, the machine has to stay powered on, the desktop app has to keep running, and the project path has to still exist at execution time.

When a task might change code, a worktree is safer than touching your local checkout directly

A Scheduled task in a Git project can run in the local project or in a separate worktree. The value of a worktree is that it keeps the automated task's changes apart from the code you are editing right now.

Read-only inspections don't need a worktree just for the sake of form. Once a task might change code, I'd rather isolate it first. For frequent tasks, also remember to clean up unused worktrees and old runs.

5. How AGENTS.md, Hooks, and Automations fit together

They are not a strict pipeline, but they can form a clear division of labor:

JobBetter place for itWhere not to put it
Long-term testing / editing rulesAGENTS.mdDon't repeat it in every scheduled prompt
Run a task at a certain timeAutomationDon't use a Hook to fake a timer
Record state / run deterministic checks after a tool callHookDon't let the model improvise script logic
One-off complex workflowSkillDon't let AGENTS.md bloat endlessly

If the same local execution environment loads both project rules and Hooks, whether a running task actually read the expected rules and triggered the expected Hooks should be verified through run history, /hooks status, and real logs, rather than assuming that being configured means everything is wired together.

6. Playwright MCP: add it only when the task really needs a browser

The browser is the layer where automation risk rises sharply. Reading a public page, filling in a form in an admin panel, publishing content, and deleting records can't all be lumped together under the label "browser automation."

The command the official Microsoft Playwright MCP currently gives for adding it to Codex is:

codex mcp add playwright npx "@playwright/mcp@latest"

You can also configure it like this:

[mcp_servers.playwright]

command = "npx"

args = ["@playwright/mcp@latest"]

For the first run, do just one boring little thing: open a public page, read the title, and return the URL. Prove that the server starts, the browser can navigate, and the result makes it back to Codex before you talk about logging in to an admin panel.

Playwright MCP is not a security boundary

The Microsoft README states clearly that Playwright MCP itself is not a security boundary. Parameters such as allowed-origins and blocked-origins are guardrails, but they can't replace real isolation, and they don't cover every risk, such as redirects.

By default, file access is limited to the workspace roots or the current directory, and turning on unrestricted file access widens that scope. Browser login state and stored data may also contain cookies, account information, and internal data.

Split browser tasks into three stages: read, prepare, submit

StageActionAutomation advice
ReadOpen pages, read informationCan be automated, read-only preferred
PrepareFill forms, upload, generate draftsEditing allowed, but don't trigger the final action
SubmitPublish, pay, send, delete, change permissionsConfirm separately, and have a human do it when necessary

"Just run the whole process for me" is too broad for a browser. A better prompt spells out the allowed domains, the page scope, the data it may enter, the buttons it must not click, and what evidence to return when the task is done.

7. A complete real-world example: inspect content every day and fill qualified articles into CMS drafts

The example below puts all four layers into one workflow, but each layer keeps its own responsibility.

AGENTS.md

→ Rules: only handle reviewed articles, never skip the test/review flags, and output evidence when done

Automation

→ At a fixed time every weekday, check the "pending publication" directory and summarize new articles in read-only mode

Hook

→ Record the task ID, exit code, and time at key lifecycle points, without automatically changing business content

Playwright MCP

→ Only when an article's status meets the conditions, open the CMS, fill in the title/body/category, and save a draft

Human confirmation

→ After checking the draft page, decide whether to publish for real

This design deliberately leaves "publish" at a human confirmation point. Saving a draft and publishing have different consequences, and automation shouldn't assume the last step must also run unattended just because everything before it succeeded.

8. Once automation calls a model, budget rules belong in the design

When you call a model by hand once a day, cost changes are barely noticeable. If a Scheduled task runs every hour and carries a long context each time, the bill piles up while nobody is watching.

A more durable budget rule describes behavior rather than hardcoding prices:

• Read only the content added in the most recent period each time.

• Retry a single failure a limited number of times at most.

• Don't automatically escalate to a more expensive model on failure.

• Stop and report when the preset budget is exceeded.

• Don't hardcode long-term discounts in AGENTS.md, Hooks, or scheduled prompts.

If this task already calls models through AI Code With , you can treat the model page, the channel page, and real call records as a three-part acceptance check: which model was actually used, which channel it went through, and how many calls and how much cost resulted.

AI Code With is responsible here for API key, model, channel, and usage management. It does not provide Playwright MCP, and it won't decide for Codex whether a local Hook is trustworthy or whether an automated task should publish content.

9. When a Hook or Automation isn't working, troubleshoot layer by layer

ProblemWhat to check firstWhat not to do first
Hook doesn't fire at allWhether the script runs on its own, the event name, the matcher, /hooks trust statusDirectly grant Codex higher permissions
Hooks run in an unexpected orderWhether multiple matching Hooks run concurrentlyAssume A always runs before B
Scheduled task didn't runWhether the task is enabled, the time, the machine, power, the desktop app, the project path, run historyRebuild the task right away
Scheduled task changed the wrong filesLocal project or worktree, AGENTS.md rules, prompt scopeWiden permissions to mask the problem
Playwright can't open the pageServer, browser dependencies, page reachability, rejected tool callsLog in to the production admin panel directly
Browser is in an unknown submission stateCurrent page, last tool call, server logsClick repeatedly and automatically

10. A 14-Item Checklist Before Going Live

□ The rules in AGENTS.md are verifiable, not vague slogans.

□ You understand how AGENTS.override.md and AGENTS.md in the same directory override each other.

□ Project instructions haven't grown without bound, and necessary workflows have been split out into Skills.

□ Hooks use explicit events and matchers.

□ Unmanaged Hooks have been reviewed and trusted via /hooks.

□ Your first Hook doesn't read Secrets, access the network, or modify the repo.

□ Multiple Hooks don't depend on an implicit execution order.

□ The Automation's Prompt has been run manually and verified.

□ Your first Scheduled task starts as a read-only task.

□ Background tasks that might change code have been considered for worktree isolation.

□ Model calls have a retry cap on failure and a budget limit.

□ Playwright MCP only visits public pages the first time.

□ High-risk browser actions like "submit" keep a separate confirmation point.

□ Any automation failure can be traced through logs, Run history, or visible evidence.

11. Finally: Build Automation as Four Layers You Can Turn Off Independently

A Codex automation setup that is truly maintainable shouldn't be just one "big Prompt."

AGENTS.md handles long-term rules. Hooks handle deterministic lifecycle actions. Automations handle scheduling. Playwright MCP handles browser capabilities. They can be combined, but each layer should have its own least privilege, its own way to verify, and its own way to shut it off.

Rules you can explain, triggers you can trace, execution you can audit, and high-risk actions you can pause.

Once you get there, automation is no longer a black box that gets harder to touch over time. It becomes a workflow you can extend layer by layer and roll back layer by layer.

Sources and Verification Notes

This article is a merged rewrite of four original drafts: "How Do You Write Codex AGENTS.md?", "How Do You Configure Codex Hooks?", "How Do You Use Codex Automations?", and "Codex Playwright MCP: Opening a Browser Is Just the First Step." I checked it against the current OpenAI documentation for AGENTS.md, Hooks, and Scheduled tasks, and the Microsoft Playwright MCP documentation. Hooks, Scheduled tasks, and Playwright MCP may all keep changing, so when you roll this out, rely on the docs as of that day, the current client state, and your own real test results.

OpenAI AGENTS.md: https://developers.openai.com/codex/guides/agents-md

OpenAI Hooks: https://developers.openai.com/codex/hooks

OpenAI Scheduled tasks: https://developers.openai.com/codex/automations

Microsoft Playwright MCP: https://github.com/microsoft/playwright-mcp

AI Code With Model List: https://aicodewith.ai/zh/dashboard/pricing

AI Code With Channel Management: https://aicodewith.ai/zh/dashboard/channels