HOOD HUNT

Keep your GPT sharp: take our setup

This is our Claude guide, reworked for GPT — the Codex agents from OpenAI. The original: “Keep your Claude sharp”. Same structure, every technique swapped for its Codex counterpart: the Codex CLI terminal, the VS Code extension, Codex in the cloud. Where Codex behaves differently or has no counterpart, the section says so, and the substitute is marked “our workaround”.

GPT doesn't act dumb because the model is weak. The agent has no rules, no memory and no checks: every time it starts from scratch and takes its own word for it. Below is my setup that fixes this. First you just read, and at the end you install all of it with one prompt.

$2 576

that's what one week of my work with agents would cost at API prices (11–17.11). This is a measure of volume, not a bill. The guide's numbers are measurements of our setup on Claude Code: the structure carries over one to one, Codex has its own counters.

7desk sessions: product, trading, content and more
317subagents in a week
15 023model requests in a week
40of my mistakes turned into rules and checks

If you haven't touched agents yet, start here. Three minutes: how an agent differs from a chat, what the setup adds and what it has already done for me.

Chat vs agent

A chat answers. An agent does. In a chat you ask, get text back, and the rest is manual: copy, run, find the error, bring it back. An agent opens the files itself, runs things itself, sees the error itself and keeps fixing until it works. You set the task and accept the result.

Here the agent is Codex from OpenAI: a GPT model that sits right in your project folder. It comes in three forms: in the terminal (Codex CLI), in the editor (the Codex extension for VS Code) and in the cloud (Codex Cloud). The terminal and the extension share settings. Two words you'll meet below: session — one conversation with the agent, context — everything it's holding in its head right now. The bigger the context, the more every answer costs.

Diagram: in a chat the human runs the “run, find the error, bring it back” loop; an agent has this loop inside Chat Youask a question Modelwrites a text answer Youcopy it, run it Youfind the error you carry the error back: every loop by hand Agent Youtask and criterion Agentreads files, rules Agentfixes, checks Youaccept the result fixes the error itself
Fig. 1. Chat vs agent. In a chat, you spin the “ran it — found the error — brought it back” loop. An agent has this loop inside: you show up at the start with a task and at the end for the result.

The downside of a bare agent: it does a lot and fast, including the wrong things, and forgets everything between sessions. The setup is what fixes both.

Without setup → with setup

Memory

without setup
Every time you re-explain what you decided yesterday.
with setup
The agent writes decisions into memory files in the project itself and reads them at startup. I have 332 of them.
details
Memory

Rules

without setup
You asked it to fix a button — it rewrote half the project.
with setup
Codex reads the AGENTS.md rules file before any work: what it may do, what to ask you, how to check “done”.
details
Desks

Checks

without setup
Says “done” without running anything.
with setup
A hook is a script that Codex runs on its own; it won't let the agent finish with an error in a file.
details
Hooks

Desks and subagents

without setup
One chat for everything: a mess within a couple of days, and every answer costs more.
with setup
A separate session for each area; small tasks go to subagents.
details
Subagents and money

Watchdogs

without setup
Something broke overnight — you find out in the morning, on your own.
with setup
Scheduled scripts and an on-call agent. Handling one event costs half a cent.
details
Server and on-call

Limits

without setup
The limit runs out by lunch, and you can't tell why.
with setup
Usage shows in /status and /usage. The biggest eater is a long conversation: in our measurement 84% of the money went to the agent rereading it on every answer.
details
Context and /clear

What agents have already done for me

Six real tasks in a month. Before → what the agent did → result.

tradingweek

Copy trading with an agent

before
Who to copy and when to switch off — by eye.
agent
Finds wallets in Hood Hunt, checks them with a backtest, places orders in Blizz and watches them around the clock.
result
A green day of +6 SOL, and the backtest on the same trades gave +6.03: that day the model matched reality. There were red days too: the safety net paused everything on its own.
productHood Hunt

Parser vs blockchain

before
People copy wallets with their own money — the numbers have to be trustworthy.
agent
Checked the wallet cards in the product against the blockchain itself.
result
Last trade — 12 of 12, coins — 42 of 43, fabricated — 0.
producta day

An auditor found fake profit

before
One desk computes the numbers — nobody to check them.
agent
A separate auditor agent with no deploy rights checked 654 product numbers against the blockchain.
result
Found a bug: 51 wallets showed over 5 000 SOL of profit that didn't exist. The first botched fix was stopped by a pre-deploy check.
serverin a day

Moving to one server

before
The product, bots and terminal lived on different servers.
agent
Wrote the migration and rollback scripts in advance, moved 53 GB of data in the background.
result
Moved in a day, about an hour of downtime. A build takes 3–4 minutes instead of 45–60.
mistakelesson

False alarm

before
A watchdog kept posting “service down” every half hour.
agent
Dug in: the service was fine, the watchdog's own key had expired.
result
New rule: an alert names the cause and the owner. More in mistakes.
setupday

Spring cleaning

before
The folder had sprawled, rules lived as lines of text.
agent
In a day it set up hooks and checks, cleaned up memory, moved old stuff to the archive.
result
Folder 26 → 8.7 GB, 25 auto-checks, 40 mistakes recorded and checked.

What to honestly expect

  • The first week is tuning. The agent builds the setup in half an hour, then it grows on your mistakes.
  • The agent makes mistakes. My list has 40 mistakes, and they're all mine.
  • Limits are finite. A long conversation eats them fastest — what to do about it.
  • Codex is not a copy of Claude Code. Almost every technique has a counterpart, but where it doesn't, the section says so plainly and gives our workaround.

Start in 15 minutes

The same five steps as in the Claude version. Not a single required terminal command.

Five steps to start: VS Code, the Codex extension, a project folder, private GitHub, prompts step 1step 2step 3step 4step 5 VS Codedownload, install ExtensionCodex + ChatGPT login FolderCodex sees the project GitHubprivate repository Promptstune it to you first after every task — a version in GitHub
Fig. 2. The whole start. The first three steps happen once. After that you live in the fifth, and GitHub keeps every version.
  1. Download VS CodeA free editor from code.visualstudio.com. Mac, Windows, Linux.
  2. Install the Codex extensionIn VS Code open “Extensions”, find Codex by OpenAI (openai.chatgpt), click “Install”. Open the Codex icon in the sidebar and use Sign in with ChatGPT: a ChatGPT Plus, Pro, Business, Edu or Enterprise subscription will do. The terminal version is installed separately (npm install -g @openai/codex) and you'll need it once — to trust the hooks, more on that in the “Hooks” section.
  3. Open your folder“File → Open Folder”. No folder yet — create one for all your projects. Now Codex sees which folder it's working in and reads the files itself.
  4. Set up a private GitHubThis is your time machine. What it is and why — right below.
  5. Start promptingFirst tune Codex to you — with one prompt in the last section. Then move on to your own tasks.

We work in VS Code

  • Codex sees the folder, the rules and the memory.
  • It runs and checks things itself — in a sandbox: it writes only inside the project folder and asks permission to go outside it or to the network.
  • Everything in this guide works here and in codex in the terminal.

The ChatGPT chat is not for work

  • The regular chat on chatgpt.com can't see your folder: that's the very “dumb GPT”.
  • You need it for the subscription and for cloud Codex: a cloud task keeps running even when your computer is asleep.
  • Codex and ChatGPT Work share limits: the /status command shows what's left.

Private GitHub: rollback and a copy of everything

GitHub is an online version store. A private repository is visible only to you. The agent saves a version there itself after every task. A Codex bonus: connect the repository in the Codex settings, and Codex will review pull requests itself too — via a @codex review comment or automatic review.

RollbackThe agent broke something that worked — you're back on yesterday's version in a minute.
A copy off the laptopLaptop died or got stolen — everything is in GitHub, whole.

Put in

  • Code and scripts.
  • The agent's rules — AGENTS.md.
  • Project state files.
  • The agent's memory — the memory/ folder in the project.

Never put in

  • Keys and passwords.
  • .env files with secrets.
  • Wallets and seed phrases.

Before the first save the agent adds .env, keys and wallet files to .gitignore (the list of what GitHub doesn't take). If a secret has already landed in GitHub, deleting it isn't enough: rotate the key right away, it doesn't leave the history.

How I do it. On 03.09 I lost all my chats with agents. Only the memory survived, because it lived in files. Now copies go to a private GitHub repository every day, the archive is encrypted, and the decryption key is kept separately from it.

What to take

  • Work happens in VS Code with the Codex extension or in codex in the terminal; the ChatGPT chat is for the subscription and cloud tasks.
  • One folder for everything and a private GitHub from day one. OpenAI advises the same: a Git save point before and after every task.
  • You don't need to set up the editor and Codex settings by hand — they're in the final prompt.

Desks: seven sessions instead of one chat

What it is. A session is a separate chat with Codex. I have seven, one per area, like departments in a company. In the terminal you name a desk's chat with /rename ‹desk› and come back to it via /resume or codex resume.

Why you need it. One chat “about everything” turns into a mess within a couple of days. The agent mixes up topics, and every answer gets pricier: at every step the model rereads the whole conversation. OpenAI says the same: one chat for a whole project bloats the context and worsens the result — keep one chat per outcome.

How we do it

Diagram: me, seven desks, shared contract and HANDOFF buses, subagents and the server Me task · product and money calls · sign-off Productback endSTATE.md TradingdeskSTATE.md Updates& contentSTATE.md GrowthSTATE.md MarketingSTATE.md NumbersauditSTATE.md Processesrules, memory the “processes” contract: rules, memory, deadlines, usage — for all desks HANDOFF files and batched messages: desks coordinate without me subagents: each desk has its own, no more than 3 at once Executor · worker Skeptic · read-only Mechanic · Luna Search · explorer the master deploys, subagents never touch prod Server: product, bots, schedules, watchdogs, on-call agent deploys by script only: backup → tests → outside check → one-command rollback
Fig. 3. How the work is organized. I give tasks to the desks. The desks coordinate among themselves — through a shared notes file and messages. The “processes” desk keeps the rules for everyone. Subagents work inside a desk and can't reach the server.

Each desk has four things:

  1. An entry phrase. “Trading desk, let's continue” — and a new session knows within a minute who it is and what to read.
  2. A state file (STATE). Three blocks: what's working, what's open, what's waiting on me. The desk remembers where it stopped.
  3. Boundaries. A desk stays out of others' business. Asked to fix something — it fixes it instead of rewriting everything.
  4. A check. One command that runs the tests. “Done” means checked, not written.

When the agent makes mistakes, the first urge is to switch to a smarter model. The right order is different: first a command that catches the error, then higher effort, and only then the model. For Codex OpenAI advises the same: “done” should mean “tests were run”, and for that the agent has to know how to run them.

STATE is read in full on every entry, so it has to be short. By 16.11 five of these files had bloated to 741 KB: every session dragged two months of history in at startup. After cleanup — 93 KB, the back end went 325 → 38 KB. Nothing was deleted, the history moved to an archive next door.

Trading desk9 sessions · 83 agents
$763
Product back end8 sessions · 102 agents
$754
Marketing7 sessions · 52 agents
$357
Numbers audit3 sessions · 42 agents
$331
Updates and content3 sessions · 6 agents
$136
Growth2 sessions · 22 agents
$128
Processes1 session · 9 agents
$75
Fig. 4. What each desk cost over the week of 11–17.11, $ at API prices, scale from zero, measured on Claude Code. The trading desk and the back end are 59% of the money. “Processes” costs 3%, and it's exactly what keeps the rest cheap. The proportion doesn't depend on the model: the expensive desks are the ones with long chats.

How desks talk to each other

I'm not needed in this chain: I set the direction, the sessions coordinate on their own. Three channels, from cheap to expensive:

Over 18–21.10 the sessions sent each other 658 messages. After the rule “batch your messages, everything else goes into a file”, in the week of 22–29.10 there were 160. Measured on Claude, but the rule is the same: a file is cheaper than a message with any model.

Take it home

  • One area — one session: an entry phrase and a short STATE.
  • Every project has one check command. No command yet — build it first, then the feature.
  • More than three desks — set up “processes”: it doesn't build product, it watches the rules, memory and usage of the others.

To install this for yourself — see the last section, one prompt.

Memory: what the agent remembers between sessions

What it is. The agent remembers nothing between sessions. Everything it “knows” about me and the projects lives in plain text files.

How Codex differs. Codex has its own memories, but they're off by default (switched on by the key [features] memories = true; the /memories command controls memory for the current chat), they're written in the background once a chat goes quiet, and they live in ~/.codex as internal files that OpenAI advises against editing by hand. OpenAI itself says: keep mandatory rules in AGENTS.md, memories are only a hint. So our workaround is memory as files in the project, just like in the Claude version. You can switch the built-in memories on top of that, but rules don't live in them.

Why you need it. On 03.09 I lost all my chats at once. Only the memory in files survived. Since then the rule is: decisions and pitfalls go into memory right away, not “we'll dig it out of the chat later”.

How we do it

Three layers of memory and a rule's path from chat to hook LAYERWHAT IT HOLDSWHEN IT LOADS RulesAGENTS.md × 2~/.codex + project How to work: style, boundaries, models, deploy order, per-project checks. A global file and a project file “Ship first, report after” at chat startwhole chain up to 32 KiBmost expensive to keep Memorymemory/MEMORY.md332 files Decisions, pitfalls, agreements: one topic — one file. Index — one line per topic with a link, 14 sub-indexes “Never put a gif in a broadcast” index at startupprinted by start hookfile — via link Progressdesk STATE.mdup to 60 KB What's live, what's open, what waits on me. Continuation prompt for a new session after /clear “Live since 14.11, three items open” on entering the deskin fullso it's short A rule climbs the layers until it becomes code: said in chat memory file line in AGENTS.md hook or test
Fig. 5. Three layers of memory. The more often a layer is read, the shorter it must be. At the bottom — a rule's path: said in chat → memory file → line in the rules → code. The gif rule took 17 days to travel this path: recorded 30.10, banned in code 16.11.

One memory file — one topic. Inside: the rule in one sentence, the incident with a date, and how to check it. Without the incident, a month later the agent will decide the rule is outdated.

Memory is not a guarantee. The ban on gifs in broadcasts sat in memory and was still broken. The only thing that reliably holds it is code that refuses to send such a file.

The index and the invisible tail

The memory index is one line per topic with a link to the file. Every load at startup has a limit, and whatever comes after it, the agent doesn't see — and there's no error. In Claude Code that's 25 KB of index: my index grew to 28.5 KB, the rules in the tail were there, but for the agent they didn't exist.

Codex has two limits. It glues the AGENTS.md chain (the global file plus the files along the path from the project root) up to 32 KiB and simply stops adding files after that — the project_doc_max_bytes key. The output of the hook that loads our memory index reaches the model in full only up to about 2 500 tokens: beyond that the full text goes to a file on disk, and the model gets the beginning, the end and the path to the file. The threshold is set by the hook's additionalContextLimit field.

before 16.11tail not loaded
28.5 KB
16.11after trimming
24.6 KB
17.11120 lines
21.9 KB
the part the agent didn't seedashed line — 25 KB load limit
Fig. 6. Memory index size, scale 0–30 KB, dashed line — the 25 KB load limit in Claude Code. I keep it under 23 KB for headroom. A section that grows too big moves to its own file, and one link stays in the index. In Codex count not just the index but the whole AGENTS.md chain: it shares a single 32 KiB limit.

Only what can't be looked up again goes into memory. There isn't a single usage number in my memory — there's the command that calculates them. I got every number in this guide by running it in the morning. A copied number lies a week later; the command doesn't.

Once a week — memory cleanup. The first big one was on 16.11:

332files checked
15orphans — files with no line in the index, the agent won't find them
25outdated
7groups of duplicates
5contradictions with the rules

A contradiction is the most dangerous: the agent reads an old file and confidently does it the old way. I don't silently rewrite such files — I put a note at the top saying what changed.

Take it home

  • Told the agent “don't do that again” — have it write a file right away: the rule, the incident with a date, how to check.
  • Watch the size: the AGENTS.md chain up to 32 KiB, the memory index up to 120 lines (our threshold), and give the start hook an additionalContextLimit with headroom. A section grew too big — move it to its own file and leave a link in the index.
  • A rule broken a second time — turn it into code or a hook.

To install this for yourself — see the last section, one prompt.

What it is. The desk session is the master: it breaks down the task, plans, deploys, writes memory. Big code is written by subagents — separate agents that start from a clean slate.

Why you need it. A subagent works in its own thread and doesn't drag along hundreds of thousands of tokens of the master's history (a token is a piece of a word; text volume is measured in them). The noise — search, logs, test output — stays with it, and the master gets a summary. OpenAI puts it plainly: without subagents the main chat gets cluttered and works worse over time. And fresh eyes review better than the author.

How we do it in Codex

  1. Master — the main session on GPT-6.2 Sol, hard stuff on Astra. Breakdown, plan, deploy, memory. OpenAI lists the 6.2 models for the app and the terminal; in the VS Code extension take what /model shows (OpenAI's models page is ambiguous about the extension here).
  2. Executor — a custom agent in .codex/agents/ modeled on the built-in worker, same model as the master. Writes code strictly to the brief and hands in proof: test output, not a story.
  3. Skeptic — a separate codex exec run in a read-only sandbox. Only reads and looks for errors. It has nothing to edit with, so it can't “tweak a bit and sweep it under the rug”.
  4. Mechanic and search — GPT-6 Luna, search is the built-in explorer agent. Tests, file search, copies.

Why the skeptic is a separate run. A subagent inside a session gets the parent's permissions, and the agent file won't cut them down: OpenAI says outright that a “don't edit” instruction doesn't create a separate sandbox. Our workaround is to launch the reviewer separately with --sandbox read-only.

I found no key in the Codex docs for a per-agent step cap like Claude Code has. Our workaround: a small task with one check and no more than three threads at once — the agents.max_concurrent_threads_per_session = 3 key (it caps the number of threads, not steps). A small task ends on its own instead of burning the limit in a loop.

Flow of the executor and skeptic pair, branching by task type and score Desk masterbreakdown and planBRIEF.md + CONTRACT.md Executor · workercode strictly to briefreturns files, md5, output Money or numbersfor users?else no skeptic needed /reviewon the changesbuilt into Codex Skeptic · read-onlybrief + diff + runscore 1–10, blockers Deploybackup, tests,outside, rollback Fixesby the same executorwhile its thread is open no yes 7+ ≤6 second round — only if the score is 6 or lower The skeptic isn't a gatereversible: show and ship at once,the verdict catches up Irreversible waitsmoney, wallets, data deletion —only after the verdict Prod — master onlya hook blocks bare ssh,deploys — by script only
Fig. 7. A task's path. The master hands over the assignment (brief) and the shared agreements (contract) as files. The skeptic only steps in for money and numbers shown to users; everything else is checked by the built-in /review on the changes (from a script — codex review --uncommitted). A score of 7 or higher — OK to deploy.

Five rules for subagents

  1. No more than three agents at once. On 13.09 I launched a workflow (a chain of agents) with 20 of them — the limits burned before my eyes, I had to stop it. More than three — only in sequence. OpenAI warns about the same: each subagent does its own work with a model, so a parallel run eats more tokens than a single agent.
  2. The master writes small stuff up to ~150 lines itself. Measured on 30.10: the executor spent 35 minutes on six scripts; by hand it would have been about 10. The brief, the wait and the report cost more than a small fix.
  3. Skeptic — only where it pays off. It ate 29% of the agents' money, and in 56% of reviews it gave 8+ and found no blockers. Now it only checks money and numbers for users.
  4. Agents are short and disposable. New task — new agent. The median agent of the week — 22 requests and $1.54 (measured on Claude).
  5. Mechanical work goes to a cheap model. Tests and search don't need brains. In Codex an agent's cheap model is set by the model field in its file; OpenAI's pick for frequent simple work is GPT-6 Luna. Honestly: on Claude our cheap model made 6 requests out of 15 thousand in a week. The rule exists, the habit doesn't yet.

Where the money goes

My script prices every request at API rates. The subscription doesn't charge this money, but limits are spent in the same proportion. This is an honest map of where they burn. Week of 11–17.11 on Claude Code: $2 576, 15 023 requests, 38 sessions, 317 agents.

In Codex part of the counter is already built in: /status shows the model and what's left of the context and limits, /usage daily and /usage weekly — spend by day and by week. In scripts codex exec --json reports each turn's spend in the turn.completed event: input_tokens, cached_input_tokens, output_tokens. You only need your own script for the per-desk breakdown.

11.1112.1113.1114.1115.1116.1117.11*
Fig. 8. Daily spend, $ at API prices, scale from zero, measured on Claude Code. *17.11 — snapshot in the morning, the day isn't over. The 14–15.11 peak is the launch of wallet cards and the guide: 3 370 and 3 940 requests a day.
13–19.10week before the rules
62%
18–21.103.5 days
54%
19.10–17.1130 days
41%
11–17.11this week
30%
Fig. 9. What share of the money went to subagents, scale 0–100%. These are four measurements of different lengths, not a series. The number of agents is about the same: 330 in the week of 13–19.10 vs 317 now. They got shorter and run where they pay off.

Take it home

  • A subagent is a file .codex/agents/‹name›.toml: name, description, instructions and model. It takes its permissions from the parent, so launch the reviewer separately, in a read-only sandbox.
  • A brief for the agent — as a file, with two lines: what you're changing and what not to touch. Without them the agent “fixes” the neighboring stuff too.
  • No more than three agents at once, small stuff by hand, a skeptic only where a mistake costs money.

To install this for yourself — see the last section, one prompt.

What it is. Context is everything the model holds in its head in this session: the conversation, files it has read, images. At every step it rereads all of it.

Why you need it. You pay not for answers but for rereading. In our measurement on Claude 84–86% of the money is context rereading; the model's answers are less than a sixth. So you save on context size, not on answer length.

Codex bills the same way. The limit is spent in tokens, and OpenAI explicitly counts chat history, files and tool output in them. The reread part goes as cached input: at OpenAI's rates for GPT-6.2 Sol and Astra it's 20 times cheaper than regular input, but not free, and it takes up its full space in the window. OpenAI itself advises saving the limit the same way: a shorter AGENTS.md, fewer extra files in a task, switch off MCP servers you don't need.

How we do it: measured on Claude Code

Money$2 576
Fable 5.2 · $1 779Opus 5.5 · $795
Requests15 023
Fable · 5 495Opus · 9 503
Fable 5.2 — desk mastersOpus 5.5 — subagentsSonnet and Haiku — under $4 combined
Fig. 10. Week of 11–17.11 on Claude Code. The master makes a third of the requests and eats two thirds of the money: its request averages $0.32, a subagent's — $0.08. The reason is context size: the master's median is 408 thousand tokens, the subagent's 109 thousand.

Below is the main picture of the guide. The models on it are Claude, but GPT works the same way: every answer rereads the whole context, and the bigger it is, the pricier the answer.

Curve: the median request price of Fable 5.2 and Opus 5.5 grows with context size $0$0.10$0.20$0.30$0.40 0200k400k600k800k request context size, tokens subagent, median 109k master, median 408k 650k $0.13 $0.37 Fable 5.2 Opus 5.5 $0.05
Fig. 11. Price of one request by context size, median over 15 thousand requests in the week of 11–17.11. A Fable request at 100–200 thousand costs $0.13, at 600–700 thousand — $0.37: 2.9 times more for the same question. Subagents on Opus never get past 600 thousand. There's no measurement of our own for GPT in Codex: the curve was built from our spend on Claude.

In Claude, switching the model mid-session wipes the cached context: each model has its own. The first request after a switch cost $5.70, the next one $0.31 — an 18x difference. In a week there were 59 such cold starts — $293, 11% of the week. The Codex docs give no direct answer: OpenAI only says the cache holds as long as the beginning of the conversation doesn't change. We keep the rule as is — don't switch models in the middle of a big session.

/clear instead of a bloated session

In the Codex terminal /clear clears the screen and starts a new chat, /new starts a new chat in the same terminal session. In the VS Code extension a new chat is Cmd+N (Ctrl+N). So you don't lose work, before that the session writes STATE and a continuation prompt — the text a new session picks up from. /compact squeezes old turns into a summary, but the model writes that summary to its own taste, while STATE you see and edit yourself.

You can see how full the context is in /status and in the status line (/statusline); the model can't. So there's a pair of hooks — our workaround on Codex events. After every request to the model, one records how many tokens went into the input. On every message you send, the second compares that with the thresholds: at 65% of the window it asks to prepare a continuation prompt, at 70% it suggests /clear. Codex also auto-compacts the history on its own; we set the threshold with the model_auto_compact_token_limit key at 90% of the window — only a safety net at the wall.

GPT-6.2 Sol context ruler from 0 to 500 thousand tokens with the hook thresholds 272kAstra's whole window 325k · 65%prepares a continuation prompt 350k · 70%suggests /clear 450k auto-compact · Sol window 500k 0
Fig. 12. Context ruler for GPT-6.2 Sol: the default window in Codex is 500 thousand tokens. The thresholds are percentages of the window: a model with a different window has its own numbers, Astra's whole window is 272 thousand. Between the advice to clear and auto-compaction there are 100 thousand tokens of headroom: it only kicks in if you ignore every warning.

I tried a hard limit: on 04.11 the thresholds changed four times in one day. The cutoff tore work apart mid-step. A “get ready” signal plus a ready prompt works better.

Images — in batches. Every image read stays in context until the session ends. Over 18–19.10 screenshots made up 183 MB of the 197 MB total the agents read. Rule: one frame per state, eyes on it once at the end.

Take it home

  • One task — one session, OpenAI advises the same. Done with a topic — STATE, a continuation prompt and /clear.
  • Don't switch models in the middle of a big session. Start effort (model_reasoning_effort, how much the model thinks) at the default and raise it a step only if the check keeps catching errors: higher effort means slower and more tokens.
  • Watch your usage: /status and /usage are already there, the context thresholds need a hook. Without a counter all advice about limits is guesswork.

To install this for yourself — see the last section, one prompt.

Hooks: the agent won't say “done” without a check

A hook is a small script that Codex runs on its own at the right moment: at session start, on every message you send, before the word “done”. It can't be forgotten or skipped. Codex has hooks, and the events are named almost as in Claude Code: SessionStart, UserPromptSubmit, PreToolUse, Stop.

Why you need it. The agent has read the rule in the file, but in a long session it may not follow it. My rules are 32 KB, and a single line drowns in them. So everything “always” and “never” I enforce with hooks and bans.

I took the principle from Anthropic, and it holds for Codex just as well: a hard rule is a hook or a ban, not a line in the rules file.

How Codex differs. Hooks live in the project's .codex/hooks.json or in ~/.codex/hooks.json. A new or changed hook won't run until you review and trust it: the /hooks command in terminal codex. Project hooks load only in a folder you trust. The command ban is enforced by the PreToolUse hook, and commands outside the sandbox — by a rules file in .codex/rules (decisions allow, prompt, forbidden). OpenAI honestly says that tool hooks are a safety net, not a complete boundary, so on top of that we never print secrets into the chat and never put them in git.

Session start summary on the first screen: what's on the server which deadlines are hot how much was spent rules check 25/25 Every message measures context size: 65% of window — prep prompt 70% of window — time to /clear silent below 65% Before “done” checks the code the agent edited during the turn error → Codex keeps going and fixes it Always, PreToolUse hook: the agent never reads keys · a frozen project — only with my “yes”
Fig. 13. The three moments when my hooks fire: in Codex these are the SessionStart, UserPromptSubmit and Stop events. The bans at the bottom are checked before every agent command. About 65% and 70% — in the context section.

The first screen of every session

Before, every session started with questions like “what's on the server, what's on fire”, and I retold it all. Now the startup hook prints the summary itself. It changes nothing, only reads.

new session · startup hook
$ codex           # the SessionStart hook runs on its own
== PRODUCT snapshot · 2026-11-17 06:49 UTC
server: snapshot 4 min ago · load normal · memory normal
running: nothing heavy
services: all active
memory: 22 archive candidates — confirm with one “yes”
-- limits, past day: $243-eq · 1024 requests · 8 sessions, 25 agents (22% of money)
-- deadlines:
  #2 (OVERDUE 1 d) [owner] renew the domain
  #30 (today) [back end] check the weekly report
-- harness: 25/25 checks
Fig. 14. Real output of the startup hook on 17.11, shortened and anonymized, captured in Claude Code. The numbers are as the script printed them. The script is an ordinary one, in bash and python: in Codex it's called by the SessionStart event, and the text from stdout goes to the model as context.
Startup summaryServer, deadlines, spend, state of the rules. Server didn't answer — one line, and the session starts as usual.
Context watchdogMeasures how full the session's context is: after a request to the model it writes the usage to a file, on your message it compares it with the threshold. Cleans nothing itself: it writes “time to /clear”, and I decide.
Check before “done”Runs a quick code check on the files the agent edited. Found an error — the Stop hook hands back its text, and Codex keeps working with it as a new task.
Ban on keys and anything dangerousThe PreToolUse hook sees shell commands and file edits before they run and refuses: reading ~/.ssh and .env, git push --force, bare ssh to the server. OpenAI calls hooks a guardrail, not a complete boundary: built-in web search, for example, doesn't go through them.
Deadline registryAny future date (“renew the server”, “reconcile on 27.11”) goes into a file, not into text. The hook shows what's overdue and the next 3 days.
Rules checkA 25-point script: hooks connected, bans in place, memory not bloated. I run it after every rules edit.
25/25rules checks on 17.11; at launch on 16.11 it was 24
36deadlines logged by sessions since 16.11; before that, dates lived in text

What to take

  • Find the lines in your rules with the words “always” and “never”. Each one is a candidate for a hook or a ban.
  • Start with one hook: a code check before “done” on the Stop event. That one alone catches the most.
  • Lock down keys and other people's projects with a PreToolUse hook, not a request. After every hook edit — /hooks and trust them again, otherwise Codex will skip them.

To install this for yourself — see the last section, one prompt.

Server and on-call: work goes on while the laptop is closed

A server is a computer in a data center that runs around the clock. A Mac goes to sleep, and everything running on it stops. So everything that has to work without me lives on the server: bots, watchdogs, schedules.

Why you need it. Launching a bot is half the job. What matters is that the server notices problems itself and reports them properly, instead of burying you in identical alerts.

What OpenAI offers. Two ready-made paths. Cloud Codex: the task runs in the cloud, in its own working folder, even while your computer sleeps, and you review the result and turn it into a pull request. Schedules in the ChatGPT app: a task on a timer, but for local files the computer has to be on, and the terminal has no schedule controls. For your own server there's one path — codex exec, a non-interactive run, on the system timer. OpenAI itself names it for scripts, CI and scheduled tasks.

On 13.11 Anthropic published a write-up, “Building always-on agents” — how an agent that runs all the time is built. On 16.11 I checked our server against it. The write-up is about structure, not the model, so the loop is the same for Codex.

1 · Event a watchdog spots a failure → log entry 2 · Launch on-call agent, read-only 3 · Triage what happened, marked “handled” 4 · Message one line to me, repeat at most daily 5 · Timer hourly; nothing new → no model call a new session at startup sees what's unhandled
Fig. 15. The always-on agent loop on our server. The model is called only at step 2 and only if there's something new. The rest is ordinary scheduled scripts.

One notification sender

The most useful fix of the week, and the most boring. 38 scripts were messaging me on their own, each with its own text. One failure turned into a repeat every 30 minutes, and it was unclear what had already been handled. Now all service messages go through a single sender: it keeps a log and doesn't repeat the same thing more than once a day.

Before, 16.11 38 files send to Telegram on their own Telegram no log, no pauses: one failure — a repeat every 30 min After one sender, a log, pauses watchdogs, scripts sender Telegram once log on-call hourly the same alert repeated during a pause isn't sent
Fig. 16. 38 squares — the 38 scripts that on 16.11 were messaging me in Telegram directly. On the right — how a service message travels now. Broadcasts to users aren't part of this.

And the second rule: an alert names the cause and the owner. “The watchdog's own key expired” and “the service is silent” are different texts, and different sessions fix them. A new watchdog starts quiet: people stop reading a noisy one within a week.

On-call agent: the model only when there's something to triage

Once an hour a script looks at the log. Nothing new — it exits without calling the model, zero spend. Something there — it launches codex exec on the cheapest model (OpenAI's pick for frequent simple automations is GPT-6 Luna). By default codex exec runs in a read-only sandbox: the on-call agent reads the logs but fixes nothing and restarts nothing; it writes me one line. On Claude ours looks like this: “On-call: events 1, spend 0.005 $”. Half a cent — cheaper than me opening a session and asking.

What codex exec lacks is a turn cap and a per-run spend cap like the one in our Claude setup. Our workaround: wrap the run in timeout, call the model only on a new event and record the spend from --json (the turn.completed event). On the server, sign in with codex login --device-auth or an API key in the CODEX_API_KEY variable for this call only.

1 hhow often it wakes up
0 $if there's nothing new
5 mintimeout per run — our workaround instead of a spend cap
read-onlythe codex exec sandbox by default

One-command deploy

Finished and checked work goes straight to prod for me, no staging. This rests not on courage but on a script. The agent doesn't improvise a deploy each time — it calls one command, and every step of it can stop the process.

  1. Testsone command runs all of the project's checks
  2. Backupprod is copied into a separate folderincomplete copy → stop
  3. Upload alongsidethe new file under a temporary namecorrupted file → stop
  4. Swapall files at once, services restarted
  5. Quick checkthe service answered and isn't crashingno answer → rollback
  6. Outside checkthe page opens for a guest, without logindidn't open → alert to me
  7. Recordwhat, when, and where the backup is
rollbackFailure after the swap — every file is restored from the backup, services are restarted again. The outside check doesn't roll back, it wakes me up: the server can be alive while the page is blank for guests.
Fig. 17. The steps of the one deploy command. Orange labels mark where the script stops on its own. Highlighted are the steps where new stops appeared on 16.11 after our mistakes.

What still gets asked of me: only the irreversible. Money and wallets, broadcasts to users, data deletion. In Codex this is enforced by a prompt rule in .codex/rules on the deploy command: a deploy needs the network, and the sandbox blocks it, so the script steps outside the sandbox, and before every such run Codex waits for my confirmation.

What to take

  • Everything that has to work without you — on a server with codex exec on a timer, or in cloud Codex, not on a laptop.
  • All notifications — through one sender with a log and a pause.
  • Before you let an agent onto a server, give it one deploy command: backup, check, rollback. An agent that deploys by hand will sooner or later put a file in the wrong place — that's exactly what happened to us.

To install this for yourself — see the last section, one prompt.

Mistakes → rules

Almost every rule I have was born from a specific mistake. The pattern is always the same: what happened → what rule appeared → what enforces it now.

Why you need it. The agent doesn't remember past sessions. The only way a mistake won't repeat is if the rule has become a test or a check, not a request like “don't do that again”.

Below are eight of our cases. The “code” tag means a script checks the rule; “reviewer” means for now it's checked by questions.

datacode

The cleaner wiped the backfill

what happened
I asked to keep data for 93 days instead of 30. The retention was changed in one place, but nobody opened the nightly cleaner with its own “older than 34 days — delete”. It wiped 21 backfilled days, about 24 hours of work.
rule
Retention changes only after checking every cleaner. Retention comes from a single source.
enforced by
A check that the cleaner takes the retention from the same place as the build.
userscode

The landing page was blank for an hour

what happened
The page was checked from the server itself, and there it opened. For people outside, fonts and parts of the page didn't load; it didn't open for about an hour until I spoke up.
rule
Check public pages from outside, as a guest: without login, every file of the page.
enforced by
An outside check after every deploy, plus a test.
userscode

Deploy “succeeded”, but missed

what happened
The wrong folder was specified. The script put the file in the wrong place, the bot kept running the old version, and the report looked successful.
rule
As many copies in the backup as there are prod files, otherwise stop.
enforced by
The deploy stops before upload if the backup is incomplete.
timereviewer

A watchdog blamed the service for its own key

what happened
A watchdog for one service posted “down” every 30 minutes. In fact the watchdog's own key had expired. Sessions were debugging a healthy service.
rule
An alert names the cause and the owner. Key expiry goes into the deadline registry.
enforced by
One sender with a one-day pause, and the deadline registry.
usersreviewer

Drafts went out as final

what happened
The agent sent every intermediate version of a banner to the team chat as if it were final: three posts in a row.
rule
Drafts — only to me in DMs. Outside — once, after my “ok”.
enforced by
Reviewer questions; the related “don't send gifs” rule is already in code.
userscode

Unchecked numbers

what happened
Outdated sample results and a SOL figure without the fee rate made it into a guide. A reader with a different rate would have got less than promised.
rule
Check every number shown to people against its source. Don't draw made-up results.
enforced by
A text-check script before publishing and a second reviewer agent.
moneycode

“10,5” became 105

what happened
A user on iPhone enters the amount “10,5” in the trading terminal. The field dropped the comma: an order 10 times bigger than intended.
rule
A comma is a decimal separator too.
enforced by
A test for “10,5” and “0,05” in the shared check.
usersreviewer

“Continue” isn't “yes” to everything

what happened
A session gave six recommendations, I replied “continue”. It switched on the whole list, including things users see.
rule
Do only what was explicitly approved. For the rest — one question as a list.
enforced by
Reviewer questions and the rule “plan first, result after a yes”.

Mistake catalog

I record every mistake as a card: how I set the task, what went wrong, what should have been done and how to check it. That's how I have 40 cards. On 16.11, 11 were checked by a command, the other 29 by reviewer questions. By 17.11 code covered 7 more, making 18.

checked by a script reviewer questions Cost of the mistake seen by people 16 · 8 + 8 money 10 · 4 + 6 time 8 · 2 + 6 data 6 · 4 + 2
Fig. 18. The catalog's 40 cards by cost of the mistake, file as of 17.11. One case — 30 px. “Time” is hours of work and my attention, “data” is loss or leak.

How this works by hand. The agent made a mistake — I say “don't do that again”. In the same turn it writes a memory file with the reason, adds a card to the catalog and, if the rule can be caught by code, writes a test. A week later the mistake doesn't repeat not because the agent “remembered”, but because the test fails. All the cases above are from Claude, but none of them is about the model: in Codex the card, the memory file and the test work the same way.

What to take

  • Every mistake — a card in the catalog the same day: the situation, what went wrong, how to check.
  • A rule that can be caught by code — turn it into a test. Reviewer questions are temporary.
  • After a month the catalog shows whether the agent repeats your mistakes.

To install this for yourself — see the last section, one prompt.

Trading with an agent: the flow only

I have my own trading desk: the agent runs copy orders in Blizz on wallets that our Hood Hunt parser finds. A copy order is when your account repeats the trades of a chosen wallet.

Here's only how the process works. I don't show wallets, sizes or selection rules: revealing them kills the trading itself.

Why you need it. If an agent moves money, the main mistake is trusting the rules to its memory.

1 · Selection wallets from Hood Hunt by trade history 2 · Backtest a run on past trades before the order 3 · Order only through one module with checks 4 · Oversight hourly, by the playbook “before → after” report 5 · Quarantine wallet taken off the order but kept in view 6 · Review desk log and report mistake → rule → test new rule into code Control: I type a phrase in the desk chat, the bot places or edits the order within code-enforced limits.
Fig. 19. The trading desk flow. Step 3 is highlighted: an order is written only through one module, and that's where the checks that can't be skipped live. The dashed line — the review feeds back into selection as a rule in code, not as text.

What the agent does

  • Reviews candidates and runs backtests.
  • Places and edits orders from my phrase in the chat.
  • Checks the orders hourly and writes a “before → after” report.
  • Keeps a log: what was placed, why, how it ended.

What code enforces, not the agent's memory

  • Orders — only through one module; the agent has no other path.
  • No order without a wallet review: test.
  • The agent can't pause a wallet on its own: test.
  • Desk limits live in settings, not in the rules text.

Why so strict. The agent read the rule in memory, agreed, and a week later in a new session did it its own way. The model has nothing to do with it: memory is a request, a test is a law. That's what happened with pausing: the agent stopped a wallet on its own after a losing streak, and 40 seconds later I had to switch it back on. For a wallet like that a losing streak is normal. After that the rule went into a test.

What to take

  • All orders — through one module. The agent must have no other path.
  • Trading limits — in settings, not in the rules text.
  • A rule you've already had to say once — straight into a test.

To install this for yourself — see the last section, one prompt.

Take it all home: the guide and one prompt

You didn't copy anything along the way. It's all collected here: one prompt installs the whole setup from the sections above. Your Codex will read the guide, ask about you and build the same thing for your tasks.

  1. Save the guideCmd+S on Mac, Ctrl+S on Windows. Put the file into your working folder and add it to the Codex chat: in the terminal — via @, in the extension — with the add-file-to-chat command (chatgpt.addFileToThread).
  2. Paste the promptThe “Copy” button below, then paste into the same chat and send.
  3. Answer and say “yes”The agent asks nine questions, shows a plan and starts only after your “yes”.
Fig. 20. Three steps. The agent does everything else itself: looks over the folder, builds, checks itself and writes how to roll back. On your side there's one step at the end — trust the hooks with the /hooks command.

It takes 30–40 minutes including your answers. It doesn't overwrite your files: first it shows what it will change and backs up your settings. The Codex sandbox keeps the .git and .codex folders read-only, so the agent will ask for confirmation to write there and for the first commits — that's how it should be. This is the first version. The setup will adapt to you over the first week of work.

main prompt

Build the setup from the guide

paste into the Codex chat together with the guide file
Build me a working Codex setup from the attached guide “Keep your GPT sharp”, then fine-tune it together with me.
There are no ready-made files: you create everything yourself from this prompt; the guide is a model of how it's built. Product, desk and server names and the numbers in the guide are the author's: you carry over the structure, not them. Config and hook syntax — only what exists in the Codex docs (learn.chatgpt.com/docs). A key or flag that doesn't exist in my version of Codex — don't set it: say so and skip it. Go step by step, don't skip ahead.

## Rules for the whole job
- Don't overwrite existing files: only a diff and my “yes”. New files are fine.
- Before editing ~/.codex/config.toml, .codex/config.toml, hooks.json, files in .codex/rules and the VS Code settings.json — a backup next to it: ‹name›.bak-YYYYMMDD-HHMM, then a diff, then my “yes”.
- Don't read or print secrets (~/.ssh, .env, keys, tokens, wallets, seed phrases, ~/.codex/auth.json), don't put them into memory, chat or git. If you see such a file — name only its path.
- Deploy nothing to servers, no restarts, git push — only with my “yes”. Don't touch anything I call off-limits.
- Work mode — sandbox workspace-write. The .git, .codex and .agents folders are read-only in it: writes there and commits go through confirmation. Warn me in advance which steps will ask for it.
- Everything the agent writes often (deadline registry, cases, templates, memory) — outside .codex: in ops/ and memory/ in the project root.
- Keep a list of every file you created or changed — it's needed for rollback.
- Run every hook with test input and show the output. Not checked — say so.
- Talk to me in plain words: I may not know the terminal or git. If I have to do something — one step per line and what it does.

## Step 1. Read and look around (change nothing)
1. Read the whole guide.
2. Project: AGENTS.md and AGENTS.override.md at every level from the git root to the current folder; .codex/ (config.toml, hooks.json, agents/, rules/); .agents/skills/; STATE.md; test and build commands (package.json, Makefile, pyproject, etc.).
3. The Codex home folder: echo $CODEX_HOME (empty means ~/.codex); in it AGENTS.md, config.toml, hooks.json, agents/, rules/; plus ~/.agents/skills/.
4. Tools: codex --version, python3 (parsing TOML needs 3.11+), node, bash, git; is gh installed and logged in (gh auth status). Is the folder already a git repository? Is there a remote?
5. Is there a Claude Code setup (CLAUDE.md, .claude/)? Tell me: Codex carries it over itself with the /import command in terminal codex — rules into AGENTS.md, settings.json into config.toml, hooks, agents, MCP. I run the import; after it, compare the result with this prompt.
6. Files that look like secrets (.env*, *.key, *.pem, id_rsa*, id_ed25519*, *keypair*.json, wallet*, seed*, auth.json): only a list of paths, don't open them.
7. Briefly show what already exists and what will conflict.

## Step 2. Questions (in one message, numbered)
1. What are you building and how do you make money; the main goal, ideally as one number.
2. Which areas do you run, by importance. They'll become desk sessions; where is each one's folder.
3. Stack: languages, frameworks, services. Is there a server where prod lives, and how do you deploy now.
4. What is irreversible and done only with your “yes” (money, wallets, broadcasts, data deletion, other people's services).
5. Sign-in and models: a ChatGPT subscription (which plan) or an API key; which models show up in /model; the main model's context window (shown in /status).
6. Which language should I talk to you in, and text rules: tone, banned words and letters.
7. How to check each project: a test or build command; if there isn't one — what counts as “works”.
8. What must never be touched: folders, services, projects.
9. GitHub: do you have an account; what to name the private repository; push after every task on my own or only on your word.
Don't guess. No answer — leave a ‹answer› placeholder and carry it into the report.

## Step 3. Plan — wait for “yes”
Show a list grouped by the sections of step 4: files to create, edits to existing ones as a diff, config.toml and hooks.json blocks, context thresholds in tokens, subagent models, the first desk and its entry phrase, what goes into git and what into .gitignore. You don't go further without my “yes”.

## Step 4. Build — in the order of the guide's sections

### 4.1 Workplace
- We work in VS Code: the Codex extension (openai.chatgpt) or codex in the VS Code terminal, in the open project folder. The regular ChatGPT chat is for the subscription and cloud tasks, not for work.
- VS Code user settings.json: "chatgpt.openOnStartup": true.
- ~/.codex/config.toml (keep my keys, extend tables; top-level keys go before the first table):
  model = "‹master model from answer 5›"
  approval_policy = "on-request"
  sandbox_mode = "workspace-write"
  model_auto_compact_token_limit = ‹90% of the window from answer 5, in tokens›
  [agents]
  max_concurrent_threads_per_session = 3
  default_subagent_model = "‹subagent model from answer 5›"
  [projects."‹absolute project path›"]
  trust_level = "trusted"
  Don't set model_reasoning_effort: each model has its own default effort; raise it per the quality rule in 4.6.
  Key check: codex exec --strict-config "answer in one word: ok" (outside a git folder add --skip-git-repo-check) — fails if a key doesn't exist in my version.
- In the report, one line per key on why: on-request + workspace-write — the agent edits inside the project folder on its own and asks before going outside it or to the network; max_concurrent_threads_per_session — no more than three subagents at once; default_subagent_model — without it a subagent takes the master's model and effort; trust_level — without trust Codex doesn't load the project's .codex/ (config, hooks, rules); auto-compaction is only a safety net at the wall.
- Codex saves chat history on its own; don't set [history] max_bytes, so old history isn't cut off.
- A desk = its own chat: the first phrase says which area it is; in the terminal name it via /rename ‹desk›, come back with codex resume or /resume. Start with one or two desks, not all of them.
- Models: master — the model for everyday work (at OpenAI that's GPT-6.2 Sol), hard stuff — one step up (GPT-6.2 Astra), subagents — same as the master, mechanics and search — the cheapest (GPT-6 Luna). What's available — per /model and answer 5.

### 4.2 Private GitHub — .gitignore before the first commit
1. Folder not in git — git init, branch main.
2. .gitignore first: .env, .env.*, *.key, *.pem, id_rsa*, id_ed25519*, *keypair*.json, auth.json, wallet and seed phrase files, *.bak-*, node_modules/, .venv/, dist/, __pycache__/, .codex-log/, large data and logs.
   Check: git check-ignore -v .env fires; git status shows not a single file from the secrets list of step 1.
3. Project memory lives in memory/ in the root — it's in git anyway. Global rules live outside the folder — a copy of them goes into the repository. Script ops/sync-copy.sh: ~/.codex/AGENTS.md, ~/.codex/agents/, ~/.codex/hooks.json, ~/.codex/rules/ → codex-global-copy/; ~/.codex/config.toml — a copy without lines containing secrets (http_headers values, oauth client_secret). Never copy auth.json or the folders of Codex's built-in memories (memories, memories_v2).
4. First commit — after the self-check (step 5): sync-copy.sh, git add, then git diff --cached --name-only and compare against the secrets list. Found something — stop and tell me.
5. Private repository. gh installed and logged in: gh repo create ‹name› --private --source . --remote origin (without --push).
   No gh or git — explain to me step by step: install git (Mac: xcode-select --install, Windows: git-scm.com); on github.com New repository → Private → no README; send you the URL. You add the remote.
   The first git push -u origin main — only after my “yes”.
6. A “Versions and rollback” section in AGENTS.md: after every finished task — sync-copy.sh and a one-line commit “what was done”; push — as in answer 9.
   Rollback: git log --oneline → git revert ‹commit› (safe, history stays) or a single file: git restore --source ‹commit› ‹file›.
   Explain it to me in words: “restored file X as it was in the commit from ‹date›”. git push --force and git reset --hard — only with my “yes”.

### 4.3 Project rules, desks and STATE
- AGENTS.md in the project root from the answers. Sections:
  who and what — the product in one line, the target number, the entry phrase;
  style — answer 6, direct and to the point, no pleasantries;
  boundaries — product development is my zone, the agent is executor, reviewer and debugger, don't invent a backlog unasked; plan first, then work, after “yes” — a finished result with no interim reports; “done” only after a check (if there's prod — on the live URL from outside, without cookies); the irreversible from answer 4 — only with “yes”; the off-limits from answer 8; don't swap my task for your own, related stuff — as a list at the end of the report; money and trading rules (limits, stops, pause) are enforced by code with a test, not by the agent's memory;
  check — a command for each project from answer 7, “done” only after it; no check — build it first, then the code;
  diagnostics — one hypothesis at a time, out loud; at most three checks, then a report on what you ruled out, and a question; don't deploy during diagnostics; fix what broke;
  always-on work — deadlines into the registry, not into text; memory holds only what can't be looked up again; STATE is short; a hard rule is a hook or a ban, not a line here;
  versions and rollback (4.2) · subagents (4.5) · context and compaction (4.6) · ## Code Review Rules — what to flag when Codex reviews in GitHub.
- Size: the project's AGENTS.md up to 16 KiB, ~/.codex/AGENTS.md (style and boundaries for all projects from answer 6) up to 8 KiB. The whole chain shares 32 KiB (project_doc_max_bytes); Codex silently doesn't load the tail beyond the limit. A big section — as a separate file in docs/, with a link in AGENTS.md and when to read it.
- A desk = a session for one area from answer 2. Build the first one now. Its STATE.md (target under 25 KB, limit 60 KB):
  # STATE ‹desk› — updated ‹YYYY-MM-DD HH:MM› UTC
  ## Live — what, when deployed, file and md5, where the backup is, how to roll back
  ## Open — the task, where we stopped, the next step as one action
  ## Waiting on me — as one list, with a recommendation; remove closed items so I'm not asked again
  ## Deadlines — not here, in the registry (4.8)
  History — in docs/history/STATE-‹year-month›.md: move it, don't delete.
- The desk's entry prompt for the phrase “‹desk›, let's continue”: what to read and in what order (AGENTS.md, STATE, HANDOFF).
- HANDOFF.md in the root — a log between desks, line format “- ‹date UTC› ‹from› → ‹to›: ‹what›”. Messages between sessions (codex queue) in batches, one for several topics; whatever can wait goes into HANDOFF. A desk writes its report on what's done as a line in its own STATE, not as a message.

### 4.4 Memory and index
- memory/MEMORY.md is the index: one line = one topic with a link to the file. Header:
  # Memory index. One line = one topic. Time in UTC.
  # Printed by the start hook: keep under 120 lines. A section has grown — into a sub-index _index_‹topic›.md, one link stays here.
- A line in AGENTS.md: “Memory — memory/. The index arrives at startup from the hook; open the file you need via its link, don't read the whole folder”.
- Memory file:
  ---
  name: ‹type›_‹short›
  description: ‹one sentence on when this is needed: the agent sees only this in the index and decides from it whether to open the file›
  metadata:
    type: feedback | project | reference | user
  ---
  **Rule:** what to do, in one sentence.
  **Why:** the incident with a date. Without a reason, a month later the rule will be judged outdated.
  **How to apply:** a check that can be done by hand.
  (later) **‹date› — closed by code:** where it's enforced now and which test.
  Create one such file from my answers as an example.
- Codex's built-in memories ([features] memories = true) — only if I ask and only as a hint: don't store rules in them, don't edit or commit their files in ~/.codex.
- Into memory — only what can't be looked up again. Whatever lives in a database, a file or on a server — a pointer and a command, not a copy of the numbers.
- My “don't do that again” → a memory file and an index line right away. Broken a second time → a hook, a test or a rule in .codex/rules.
- Weekly review: orphans (files with no link from the index), outdated stuff, duplicates, contradictions with AGENTS.md. Don't silently rewrite a contradicting file: put a note at the top “> **Update ‹date›:** ‹what's wrong and what the fix is›”, the fix after my “yes”.

### 4.5 Subagents
- Agents in .codex/agents/, one TOML per agent. Required fields name, description, developer_instructions; the model — model and model_reasoning_effort set explicitly (a level from the model's list in /model): without them a subagent inherits the master's model and effort. The agent takes its sandbox, approvals and MCP from the parent; the file doesn't change them. Template:
  name = "executor"
  description = "Subtask executor working from a brief: edits only the files in the brief and hands in proof."
  model = "‹subagent model›"
  model_reasoning_effort = "‹level›"
  developer_instructions = """
  You are the executor. Your inputs are only the BRIEF.md file (and CONTRACT.md), path given in the task.
  1. Read the brief and the files it names; others only if you can't do without them, and say which.
  2. The minimal change that fully solves the task: what already exists in the project → standard library → new code. No abstractions “for the future”.
  3. Branching, money, parsers, security — at least one test or assert. Mark a deliberate simplification shortcut: ‹limitation›, ‹when to update›.
  4. Run the check from the brief. Answer in up to 15 lines: files and md5, the check command and its output, what's unchecked and the risk.
  Bans: ssh, scp, server restarts, edits outside the brief's paths, plus the bans from answers 6 and 8.
  """
  mechanic — the cheapest model; tests, md5, grep, copies; no decisions and no prod.
  explorer — a file with name = "explorer" replaces the built-in agent of the same name: the cheapest model, only read and search, edit nothing.
  skeptic — not an agent file but a separate read-only run (an agent file won't narrow the sandbox): the script ops/skeptic.sh ‹brief folder› does git diff | codex exec --sandbox read-only --ephemeral -o ‹brief folder›/REVIEW.md "‹skeptic role + path to BRIEF.md›". The skeptic reads the brief and the diff, runs the check, gives a score 1–10, flags only blockers; “no blockers” is a normal answer; 7 or higher — OK to deploy.
- Templates in ops/templates/:
  BRIEF.md: # ‹code› — ‹what to do in one line›; project root; contract — CONTRACT.md next to it; You edit ONLY: ‹files›; Don't touch: prod, server, Codex settings, secrets; Why (2–3 lines); What to read first (files and lines); What to do (numbered, every item checkable; tests for empty, zero, dependency failure; old tests green); Check: ‹command› → ‹what it prints›; Report up to 15 lines; don't deploy.
  CONTRACT.md: # ‹Feature› — contract between subtasks; source of the decision and a data check of the idea (a number or “never happened”); constants (one name everywhere); fields and schema (name, type, meaning, what if there's no data); calculation rules and edge cases; files and events (who writes, who reads); the master's post-review decisions with a date.
- Subagent rules in AGENTS.md (Codex calls subagents when the task or this file explicitly says so — write down which ones to call for what):
  the master (main session) does the breakdown, plan, report and deploy itself;
  no more than 3 agents at once (enforced by the agents.max_concurrent_threads_per_session key); a batch of more than three — queued in threes;
  inputs go as a file before launch, not as messages along the way;
  small code up to ~150 lines the master writes itself, a subagent is for big code;
  skeptic — only for money and numbers for users, everything else — /review or codex review --uncommitted;
  the skeptic isn't a gate: show reversible things right away, irreversible ones wait for the verdict;
  one review round, a second only if the score is 6 or lower; review fixes — by the same executor while its thread is open, otherwise a fresh one with the brief and the diff;
  search and mechanics — on the cheapest model; ssh and restarts are banned for subagents (enforced by the hook from 4.7).

### 4.6 Context and /clear
- In AGENTS.md:
  one chat — one outcome; don't switch models mid-session — the cache holds on an unchanged beginning of the conversation, and in Claude a model switch wiped it (for Codex there's no direct answer, we keep the rule out of caution);
  limit ran out — wait for the reset (what's left is in /status), or /clear and a new session on a lower model;
  soft threshold — between steps prepare a continuation prompt in STATE; hard — finish the step and advise me to /clear (in the extension — a new chat); after that — the desk's entry phrase;
  read images in batches and once, large files and logs — in parts;
  quality isn't enough — first a check, then effort up one step (/model --reasoning=‹level›), then a higher model.
- Compaction: the start hook also fires after history compaction (the compact event) and prints “Waiting on me” and the entry phrase again. A custom compaction instruction — the compact_prompt key in config.toml, only with my “yes”: it overrides the compaction prompt, so write the text in full (our advice) — keep the goal and the “done” criterion, changed files with md5, what's deployed and what isn't, open decisions, check commands, the next step; drop log output, intermediate hypotheses, contents of files read.
- The context counter itself is the ctx-log and ctx-guard hooks in 4.7.

### 4.7 Hooks, bans and harness check
Scripts in .codex/hooks/, python3 and bash with no dependencies. Input for all of them is one JSON on stdin: session_id, transcript_path, cwd, hook_event_name, model, then the event's fields. OpenAI doesn't promise to keep the transcript format stable — don't rely on it. The hook's own error — exit 0, don't break the turn. Paths in commands — from the git root: "$(git rev-parse --show-toplevel)/.codex/hooks/‹script›".
a) session-start.sh (SessionStart, matcher "startup|resume|clear|compact"). Read-only. Codex passes plain text from stdout to the model as context. Prints up to 40 lines: date in UTC; overdue items and the next 3 days from the deadline registry; the last 3 lines of HANDOFF.md; the “Waiting on me” block from STATE.md; how many files are uncommitted (git status --short | wc -l); one line of the harness check (“harness N of M” and the FAIL names); once a week — memory review candidates: files older than 21 days with no link from the index (week stamp — ops/.memory-review-stamp). At the end — memory/MEMORY.md. Always exit 0.
b) ctx-log.py (PostModelRequest). agent_id in the input means it's a subagent — exit. Takes token_usage.input_tokens of the last request and writes the number into a temp file with session_id in its name. The model doesn't see this event's output — only the file. Verify on your own output that cached_input_tokens is included in input_tokens (it is in OpenAI's example), and don't add them twice. exit 0.
   ctx-guard.py (UserPromptSubmit and PostToolUse). Reads the number from the file. Thresholds — constants at the top of the script, in tokens: SOFT = 65% and HARD = 70% of the window from answer 5. Below soft — exit 0 with no output.
   Soft: to the model “context ~Nk, between steps prepare a continuation prompt in STATE, keep working”. Hard: “finish the step, the prompt must be ready, advise /clear”. It cleans nothing itself — I decide.
   Output — one JSON line: {"systemMessage": "‹line for me›", "hookSpecificOutput": {"hookEventName": "‹event›", "additionalContext": "‹text for the model›"}}.
   On PostToolUse — hard only, and no more often than once per 25000 tokens (state — a temp file with session_id in its name). exit 0.
c) stop-verify.py (Stop). stop_hook_active true in the input — exit 0 with no output.
   Takes project files changed since the last stop (marker — a temp file with session_id, the first time — the last 15 minutes; plus git status --porcelain).
   Checks: .py — python3 -m py_compile; .js .mjs .cjs — node --check; .sh — bash -n; .json — parse; .toml — tomllib. Skips node_modules, .venv, .git, dist, __pycache__. Timeout per file 20 s.
   Errors found — a list to stderr (file and the last line of the error, up to 8 of them) and exit 2: Codex won't finish, it continues with this text as a new task. No errors — exit 0 and empty stdout (Codex treats plain text on this event as an error).
   Full project tests — not here, but before deploy, with the single command from the “check” section.
d) pre-tool-guard.py (PreToolUse, matcher "Bash|apply_patch"). Looks at tool_input.command. Deny if the command reads or writes ~/.ssh, .env*, ~/.codex/auth.json, key and wallet files from step 1; contains git push --force, git reset --hard, rm -rf; bare ssh and scp (to the server — only via the deploy script from 4.10); touches the off-limits from answer 8.
   Deny — JSON {"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "deny", "permissionDecisionReason": "‹why; what to do — ask me›"}}. Otherwise exit 0 with no output. This is a safety net, not a complete boundary (as OpenAI says), so secrets also go into .gitignore.
e) .codex/rules/project.rules — rules for commands outside the sandbox, prefix_rule syntax from the docs: git add and git commit — decision "allow"; git push, the deploy command and everything irreversible from answer 4 — "prompt"; each rule has a justification and match and not_match examples.
   Check: codex execpolicy check --pretty --rules .codex/rules/project.rules -- git push origin main → prompt.
f) health.py — the harness check, deterministic, no network. One line per item: OK or FAIL with a reason; at the end “N of M”; the --line flag — only the summary line; FAIL — exit 1. Items:
   AGENTS.md exists; the ~/.codex/AGENTS.md + project AGENTS.md chain under 32 KiB; memory index under 120 lines and every link points to a file; memory files without a link — as a list; config.toml parses (tomllib); hooks.json is valid JSON; every hook from hooks.json exists and passes a syntax check; ctx-log, ctx-guard, stop-verify and pre-tool-guard are connected; every .codex/agents/*.toml has name, description, developer_instructions and model; ops/skeptic.sh calls codex exec with --sandbox read-only; STATE.md under 60 KB; .gitignore covers .env and keys, git ls-files has no files from the secrets list; the deterministic cases of the mistake catalog (4.9) pass.
   Run it after any edit to rules, memory, settings, hooks or agents.
g) Wiring — the project's .codex/hooks.json (backup, diff, “yes”), format from the Codex docs:
   {"hooks": {
    "SessionStart": [{"matcher": "startup|resume|clear|compact", "hooks": [{"type": "command", "command": "bash \"$(git rev-parse --show-toplevel)/.codex/hooks/session-start.sh\"", "additionalContextLimit": 6000}]}],
    "PostModelRequest": [{"hooks": [{"type": "command", "command": "python3 \"$(git rev-parse --show-toplevel)/.codex/hooks/ctx-log.py\""}]}],
    "UserPromptSubmit": [{"hooks": [{"type": "command", "command": "python3 \"$(git rev-parse --show-toplevel)/.codex/hooks/ctx-guard.py\""}]}],
    "PostToolUse": [{"matcher": "*", "hooks": [{"type": "command", "command": "python3 \"$(git rev-parse --show-toplevel)/.codex/hooks/ctx-guard.py\""}]}],
    "PreToolUse": [{"matcher": "Bash|apply_patch", "hooks": [{"type": "command", "command": "python3 \"$(git rev-parse --show-toplevel)/.codex/hooks/pre-tool-guard.py\""}]}],
    "Stop": [{"hooks": [{"type": "command", "command": "python3 \"$(git rev-parse --show-toplevel)/.codex/hooks/stop-verify.py\"", "timeout": 60}]}]
   }}
   Codex won't run a new or changed hook until I trust it: tell me to restart codex in the terminal, type /hooks and trust each one. After any hook edit — /hooks again.
   This is exactly “a hard rule is a hook or a ban”: pre-tool-guard refuses even if asked; a prompt rule waits for my manual “yes” every time.

### 4.8 Deadline registry
- .codex/hooks/followups.py, stdlib only, file ops/followups.json:
  add YYYY-MM-DD "what" [--owner desk] [--ref file] → prints the id;
  due [--days 3] → overdue (“OVERDUE N d”), today and upcoming, with the owner in brackets;
  list → all open; done id → close with a date.
- A line in AGENTS.md: “Deadlines go into the registry, not into text. Any future date (check, renew, key expires) — followups.py add; done — done ‹id›”.
- A line in session-start.sh: python3 "$(git rev-parse --show-toplevel)/.codex/hooks/followups.py" due --days 3 2>/dev/null || true

### 4.9 Mistake catalog
- ops/evals/cases.json — an array of cases. One case:
  {"id": "‹desk›-‹what broke›", "department": "‹desk›", "source": "memory/‹memory file with the rule›.md",
   "situation": "‹the task the way I phrase it›", "trap": "‹what went wrong, with the cost›",
   "expected": "‹what the agent should do instead›",
   "grader": {"type": "deterministic", "check": "‹a command that fails on a violation›"},
   "severity": "users | money | time | data"}
  If code can't catch it yet: "grader": {"type": "rubric", "check": ["‹question for the reviewer›?", "…"]}.
- Rule in AGENTS.md: a new rule after a mistake = a new case right away, five lines of JSON. Over time turn question-based cases into commands.
- Now — one case from my answers (for example, about the irreversible from answer 4).

### 4.10 Server — plan only, install nothing
If answer 3 mentions a server — into the report and into the deadline registry for week 2–4:
- one deploy command: tests → lock “one deploy at a time” → a backup with as many copies as there are prod files, otherwise stop → upload under a temp name and syntax check → swap all files at once → restart → smoke test → outside check over https without cookies → a line in STATE (time, files, md5, backup path); failure after the swap — rollback from the backup with one command; in .codex/rules this command is "prompt";
- one sender for service notifications: a log as JSON lines, a repeat pause per key of one day, a “handled” mark; the alert text names what broke, the cause and whose zone it is; new watchdogs start quiet;
- an on-call agent — only once there's an event log: an hourly timer (cron or systemd); nothing new — no model call; something new — timeout 300 codex exec --sandbox read-only --ephemeral -m ‹cheapest model› -o ‹answer file› "‹what to triage›"; codex exec has no turn or spend cap — timeout enforces it, spend is recorded from --json (the turn.completed event); sign-in on the server — codex login --device-auth or CODEX_API_KEY for this call only; it fixes nothing, writes the owner one line;
- long tasks while the laptop is closed — cloud Codex (the task runs in the cloud, the result is a pull request): only if I ask.

### 4.11 Deadlines
Every deadline I've mentioned — into the registry. Plus one in 7 days: “a week with the setup: review of rules and memory”.

## Step 5. Self-check (show me the output)
- Every hook with test input:
  echo '{"session_id":"t","transcript_path":null,"cwd":"/tmp","hook_event_name":"Stop","stop_hook_active":false}' | python3 .codex/hooks/stop-verify.py; echo $?
  stop-verify: a deliberately broken temp .py → exit 2 and text in stderr, then delete it.
  ctx-log and ctx-guard: a temp file with a number above the hard threshold → JSON with both fields; below soft → silence.
  pre-tool-guard: {"tool_name": "Bash", "tool_input": {"command": "cat ~/.ssh/id_ed25519"}} → JSON with deny; the ls command → silence.
  session-start: run → up to 40 lines plus the memory index, exit 0.
  followups: add, due, done on a test entry, then remove it.
  codex execpolicy check: git push origin main → prompt, git commit -m t → allow.
- python3 .codex/hooks/health.py — the full output. Goal — no FAIL; if one remains — what it is and how to close it.
- git: git check-ignore -v .env fires; git status is clean after the commit; git log -1 shows the first commit.
- Tell me: restart codex, type /hooks and trust the hooks. Then a rules check: codex --ask-for-approval never "Summarize the current instructions." — Codex should retell the global AGENTS.md and the project's AGENTS.md.

## Step 6. Commit and report
- First commit per 4.2. Push — only after my “yes”.
- What was created and what changed: the path and one line on what's inside. Where the settings backups are.
- Rollback: which files to delete, which config.toml and hooks.json backups to restore, which diffs to revert; the commit to go back to.
- The first desk's entry phrase and the ‹answer› placeholders that stayed empty.
- A 7-day tuning plan:
  day 1 — one check command per project in AGENTS.md;
  days 2–3 — every “don't do that again” from me goes straight into a memory file, an index line and a catalog case;
  days 4–5 — a second desk with its own STATE and entry phrase; the first big task — to a subagent, brief as a file;
  day 7 — health.py, a review of memory and rules (orphans, outdated, duplicates, contradictions), /hooks — all trusted, a check that everything is committed and pushed.
  Every mistake becomes a rule, a repeated one — a hook, a test or a rule in .codex/rules.

What gets installed

WorkplaceVS Code and Codex settings: model, sandbox, no more than three subagents, trust for the project folder. Backup before editing.start
Private GitHubEvery task is saved as a version, push — only with your “yes”. Something broke — rollback in a minute. Keys and wallets won't get into the repository.start
Rules and the first deskAGENTS.md from your answers within the Codex limit, the first desk's progress file and the phrase it resumes work from.desks
MemoryA memory/ folder with an index the hook prints at startup, and a first memory file as a template.memory
Four subagentsExecutor, mechanic and search — as files in .codex/agents/, the reviewer — as a separate read-only run.subagents
Context counterA pair of hooks: records usage and tells you itself when it's time to prepare a continuation and do /clear.context
Hooks and checksA startup summary, a code check before “done”, a ban on reading keys, rules for git push and deploys, a check of the whole setup with one command.hooks
Deadlines and mistakesA deadline registry instead of dates in text, and a mistake catalog that every agent mistake goes into.mistakes

The server and the on-call agent aren't installed right away: they depend on your infrastructure. If you have a server, the agent will write a plan for week 2–4. How it works for me — in the “Server” section.

What the agent will ask

It writes the rules for you from your answers. The more specific the answer, the less tuning later.

  1. What you're building and how you make moneyand the main goal, ideally as one number
  2. Which areasthey'll become the desks
  3. Stack and serveris there a server and how you deploy
  4. What's irreversiblemoney, wallets, broadcasts, data deletion: here the agent always asks
  5. Sign-in and modelsa ChatGPT subscription or an API key, which models show up in /model, the context window from /status
  6. Language and toneanswer style, banned words and letters
  7. How to check the projecta test command, or it has to be built first
  8. What's off-limitsfolders, services, other people's projects
  9. GitHubdo you have an account, what to name the repository, save on its own or on your word

The first week

The prompt gives you a skeleton. The setup becomes yours within a week: every agent mistake turns into a rule.

  1. Day 1. CheckOne command that checks the whole project. Without it “done” means nothing.
  2. Days 2–3. MemoryYou said “don't do that again” — the agent writes down the rule right away.
  3. Days 4–5. Second deskA second chat for another area. The first big task goes to a subagent.
  4. Day 7. ReviewPaste the short prompt below: the agent finds what's outdated and suggests what to make a hard rule.
prompt for day seven
A week with the setup has passed, let's fine-tune it.
1. Run the harness check (python3 .codex/hooks/health.py) and show the red items.
2. Reread AGENTS.md (global and project), the memory index and STATE: what's outdated, what's duplicated, what contradicts each other; memory files with no link from the index; how much room is left before the 32 KiB AGENTS.md chain limit.
3. Find the lines in the rules with the words “always” and “never” and suggest which to turn into a PreToolUse hook or a rule in .codex/rules.
4. Based on this week's mistakes, suggest cases for the mistake catalog.
5. Check git: is everything committed, are the memory and a copy of the global rules in the repository, has a secret slipped in.
6. Tell me to open /hooks: are all hooks trusted, are there changed ones Codex now skips.
Show everything as a list with diffs and change nothing until my “yes”.

What to take. Answer the agent's questions in detail. After a week compare your AGENTS.md with the first version: if it has barely changed, the agent is working by the guide's generic rules, not yours.

Hood Hunt and Blizz in Codex

Our MCP connects to Codex the same way as to Claude: the agent gets the Hood Hunt tools and calls them itself. For each wallet Hood Hunt gives a score, a chance, numbers and facts — stops and warnings. The decision is yours.

  1. Get the keyThe @hoodhuntbot bot → “Log in” → the “Agent (MCP)” section → “Copy address”. The key is the part of the address after /mcp/.
  2. Put the key in an environment variableFor example HOODHUNT_MCP_KEY in your terminal profile. The key doesn't go into config.toml or git: Codex takes it from the variable itself and sends it as an Authorization: Bearer header. The variable has to be visible to the Codex process — launch codex or VS Code from a terminal where it's set.
  3. Add the block to ~/.codex/config.tomlA ready one is below. Blizz signs in through the Blizz window (OAuth): after adding it, run codex mcp login blizz. We haven't tested this sign-in with Blizz on a live account; if it fails, the steps for Codex are on the “AI” page in Blizz.
  4. CheckRestart codex: /mcp will show hoodhunt and blizz. Ask the agent to call whoami — it shows whose key it is and what the limits are.
~/.codex/config.toml — MCP block
[mcp_servers.hoodhunt]
url = "https://hoodhunt.lol/mcp"
bearer_token_env_var = "HOODHUNT_MCP_KEY"

[mcp_servers.blizz]
url = "https://blizz.id/mcp"

The same via commands: codex mcp add hoodhunt --url https://hoodhunt.lol/mcp --bearer-token-env-var HOODHUNT_MCP_KEY and codex mcp add blizz --url https://blizz.id/mcp. What the agent does with Hood Hunt and Blizz, prompts and order limits — in the guide “Agent on autopilot: Hood Hunt and Blizz”.