# dratamer

Adopt this skill: https://proskills.md/skills/other/5o1-dratamer-skills-dratamer

Page: https://proskills.md/skills/other/5o1-dratamer-skills-dratamer
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: skills/dratamer/SKILL.md
size: 16898
sha: 3370f530b7af95c35454680602cb24e74263e572
upstream: https://github.com/5o1/dratamer/blob/44632199be4d7fc9c3fb823962626d8ffb125b35/skills/dratamer/SKILL.md

````text
---
name: dratamer
description: Hand an execution task to OpenAI Codex CLI running in the background and supervise it. Claude designs the work and writes the task; Codex does the execution and, when delegated, the research. Claude watches Codex's log with an event-driven monitor (each agent message, failure-specific alerts with a cooldown, a silent tolerance period for network trouble, an idle check, process exit) and steps in by stopping Codex and resuming it with a written ruling. Use when the user asks to have Codex do the work, to "control/supervise codex", or to run a task through Codex in the background.
---

# Supervised Codex execution

Left unattended, Codex tends to:
- simplify the task (hardcoding values, skipping checks, swapping in weaker methods);
- drift off scope (extra tooling, starting later phases, editing protected files).

Supervising it turn by turn, on the other hand, costs many back-and-forth rounds. This workflow keeps Codex on track with few rounds.

## Roles

- **You (Claude):**
  - design: method choices, gates, root-cause analysis;
  - write the task, research briefs and rulings;
  - review the results: read conclusions and open questions, spot-check key numbers and about three key citations against primary sources.
- **Codex:** implementation, runs, renders, reports, and also literature and tool research. Research is delegated because it is cheaper in Codex than in your long-context turns. Give research briefs neutral questions, primary-source rules and a single report file.
- **Before dispatching:** settle every design decision you can. Confirm with the user the ones that are theirs to make. Write the conclusions into the task, so Codex has nothing to invent.

## 1. Write the task file

Put it in the session scratchpad, e.g. `$S/codex_<topic>_task.md`, and write it in the user's language. Include:

- **Context and facts already verified.** Mark them "reviewer-verified; reproduce in report". Codex must recheck them; it has caught reviewer errors before.
- **The method, stated precisely,** with simple, robust definitions. Don't ask Codex to invent segmentations or heuristics.
- **Two kinds of gates:**
  - **Critical gate:** failure makes downstream results meaningless, so stop and report.
  - **Non-critical gate:** record it as failed, with the value, and continue. List all failures at the top of the report.
  - Thresholds and definitions may not change. No tuning just to pass.
  - Exempt natural edge effects (tapered tips, boundary samples) from per-element gates.
- **Bug-fix budget:** Codex may fix bugs in its own implementation, up to 3 per step. Log each one with the evidence, the fix and the result. If it can't tell whether something is a bug or a real gate failure, it treats it as a gate failure and stops.
- **Limit diagnostics on failure.** When a critical gate fails, render at most 3 relevant diagnostic images, then stop. Produce the full figure set only on success, because full renders after a failure waste a lot of time.
- **Constraints:** output directory, protected paths, no git commit, no hardware IO, network rules. Keep large files on the remote node if the project says so.
- **Deliverables:** a report with an "unauthorized choices I made" section, plus a reproducible script.
- **End with paths.** The last message must list absolute paths of all images and key files, so they can be opened directly.

## 2. Launch

Agree on the model and reasoning effort with the user, and pass them on the command line. Never edit `~/.codex/config.toml`; other projects use it. Run with `run_in_background: true`:

```bash
# Fresh session (use a new one when old context would pollute the task)
cd <repo> && codex exec -m <MODEL> -c model_reasoning_effort=\"<EFFORT>\" \
  -s workspace-write -c sandbox_workspace_write.network_access=true \
  -o $S/codex_<topic>_last.md - < $S/codex_<topic>_task.md > $S/codex_<topic>.log 2>&1; echo "codex exit=$?"

# Resume the same session (session id is printed near the top of the log)
cd <repo> && codex exec resume <SESSION_ID> -m <MODEL> -c model_reasoning_effort=\"<EFFORT>\" \
  -c sandbox_mode=\"workspace-write\" -c sandbox_workspace_write.network_access=true \
  -o $S/codex_<topic>_last.md - < $S/<ruling>.md >> $S/codex_<topic>.log 2>&1; echo "codex exit=$?"
```

Codex CLI flag quirks:
- `resume` rejects `-s` and `--color`, so pass the sandbox through `-c sandbox_mode=...` instead.
- `--approve-for-me` can't be combined with `-s`, and auto-mode may block it. Don't use it.
- When resuming, append to the existing log with `>>`.

After launch, confirm the header shows the right `model:`, `reasoning effort:` and `session id:`. "failed to refresh available models" warnings are harmless.

## 3. Supervise with the event-driven monitor (not fixed-interval polling)

Start the Monitor tool with `timeout_ms: 1800000` and re-arm it when it expires:

```bash
WATCH_PID=<codex pid> bash ~/.claude/skills/dratamer/scripts/codex_watch.sh $S/codex_<topic>.log 900
```

Events:
- `CODEX_MSG: ...`: the first lines of each Codex agent message.
- `CODEX_MSG [after context compaction]: ...`: Codex compacted its context (the log line `context compacted`) before this message. The compaction is not a separate event: it rides on the next message, unthrottled. If Codex exits before writing another message, a `CODEX_COMPACTED` line precedes `CODEX_EXITED`. Codex usually restates its plan right after compacting, so that message is not a turn-end summary. It is also when Codex is most likely to drop constraints or drift off the main line. Read its next few messages closely against the brief and any pending ruling, and check `git status` for out-of-scope edits. If anything was lost, stop it and resume with a short ruling that restates the missing constraints.
- `CODEX_IDLE: ...`: no event for the idle interval (the second argument; 900 s works well because long report writes and simulations are often silent for over 10 minutes). It includes the log age and the last shell command, which tells you whether Codex is still computing, stuck or drifting.
- `CODEX_EXITED`: Codex is done.
- Failure-specific alerts, one hook per known failure, so real failures do not wait for the idle check:
  - `CODEX_ERROR`: Codex CLI errors other than network errors.
  - `REMOTE_SSH_FAIL`: an ssh connect or key-auth failure in command output.
  - `NET_PROBLEM` / `NET_RECOVERED`: network trouble that outlasted the tolerance period / its end.
  - Alerts share a cooldown (`WATCH_COOLDOWN`, default 30 s): at most one alert wakes you per cooldown. Alerts inside it are counted and reported once as `ALERT_SUPPRESSED: N ..., last: ...`, and any left at exit are reported before `CODEX_EXITED`. `CODEX_MSG` (including the compaction marker), `CODEX_IDLE` and `CODEX_EXITED` are never throttled.
- **Network tolerance period.** Brief network trouble needs no action, because Codex reconnects on its own. API reconnects, websocket/TLS/transport errors and an unreachable Codex backend open a silent tolerance period, during which the backend is probed every 10 s.
  - As soon as a probe succeeds, the period closes and nothing is reported.
  - A period still open after `WATCH_OUTAGE` seconds (default 300) raises one `NET_PROBLEM`. When the backend is reachable again, `NET_RECOVERED` follows.
  - A new interruption after a recovery opens a new period. Only one period is open at a time.
- Add a new pattern to the script when a new failure signature shows up, rather than shortening the idle interval.

Other sessions may run their own Codex on the same machine. Always pass `WATCH_PID` (the PID of the `codex exec` you launched; get it with `$!` or `pgrep -f "codex exec resume <SESSION_ID>"`); without it the watcher treats any `codex exec` as alive. Run only one monitor per log. Stop the old one with TaskStop before starting a new one, or you get duplicate events. To read the full new log content since your last check, run `python3 ~/.claude/skills/dratamer/scripts/codex_digest.py $S/codex_<topic>.log`. It tracks a byte offset, prints agent messages in full and truncates commands.

On each event, check for these failure patterns:
- **Lazy:**
  - hardcoded values or assumptions in place of measurements;
  - approximate methods in place of the specified ones;
  - skipped or swapped checks;
  - lowered thresholds or tuning to pass;
  - a sample count below spec;
  - claiming "done" without data.
- **Drift:**
  - starting a later phase;
  - touching protected files;
  - unrelated tooling;
  - stuck on network or nodes for more than 15 minutes;
  - the same error repeating;
  - more than 3 fixes in one step;
  - stopping on a non-critical gate, or not stopping on a critical one.

Routine progress gets one short line to the user. Don't send a push notification for it.

## 4. Intervene

1. **Stop Codex:** `kill <pid>` for the run you launched, or `pkill -f "^codex exec resume <SESSION_ID>"`. Never use a bare `pkill -f "^codex exec"`: other sessions may run their own Codex. The `^` anchor matters; an unanchored pattern also matches your own shell and kills it (exit 144).
2. **Write a ruling** to `$S/<topic>_fix_N.md`:
   - Name the root cause. If it was your own task design, say so; that is usually the case.
   - Give the corrected method or gate, and restate what is unchanged.
   - Tell Codex to record the ruling in its report.
   - Merge everything pending into one ruling, so one resume covers it all.
3. **Resume** in the background with the `resume` command above, then re-arm the monitor.
4. **Tell the user** what you changed and why.

**When Codex asks a question** (a `CODEX_MSG` ending with options and no further progress), welcome it. Two-way discussion between agents is the intended workflow, so don't forbid questions in task files. `codex exec` cannot read stdin mid-run, though, so the asking process just waits. Answer promptly: stop it, write the answer with your reasoning, then resume the same session. If the decision belongs to the user, ask the user first.

### Side questions and discussion (btw)

Codex's interactive `/btw` (side conversation) forks the thread so a question doesn't pollute the main line. The non-interactive equivalent is `codex exec fork`, verified with Codex 0.163:

```bash
# Ask a forked copy of the session; the main thread is untouched. Like resume, fork rejects -s.
codex exec fork <SESSION_ID> -m <MODEL> -c model_reasoning_effort=\"low\" \
  -c sandbox_mode=\"read-only\" --ephemeral -o $S/btw_<topic>.md \
  "这是一个旁支提问，不要修改文件。<question>"
```

- **Asking while Codex works.** Fork whenever you need Codex's reasoning: why it chose X, what it tried and dropped, what it is unsure of. This works while the main run continues. The fork sees only the context saved so far, so the answer may lag the live run.
- **Discussion.** Before a ruling, you can fork to talk a design question through: give your proposal and ask for objections and missing facts. Several forks can go back and forth. Put the agreed conclusion into the ruling file; forks are discarded.
- **Taking over a session.** Instead of reading the whole log, fork and ask for a handoff with four parts:
  - current state;
  - decisions made and why;
  - open issues;
  - claims Codex itself has not verified.
  Then spot-check the key facts against primary artifacts before acting on them.
- **Verifying what Codex says.** Its answers explain things but are not evidence. Check numbers, file changes and test results against logs and files. Codex drifts, especially after compaction, and its self-report inherits the drift.
- **Use read-only and `--ephemeral`.** A side question must never edit files or launch runs. Pass `--ephemeral` so the fork isn't saved as a session; drop it only when you want to keep a fork, for example a handoff you will resume.
- **Watching a fork.** Get the PID with `pgrep -f "^codex exec fork <SID>"`. An unanchored pattern also matches your own wrapper shells, which exit quickly and make the watcher report `CODEX_EXITED` too early. Forking a session whose last tool call was still open logs many `Orphan custom tool call output` errors; they are harmless.
- **Guard in read-only forks.** Under the Stop That Shit Guard, a read-only fork runs in review mode. Shell commands that aren't provably read-only are blocked, quoted `ssh` commands included. Check remote state yourself and give Codex the result, rather than expecting the fork to fetch it.
- **Remote files for read-only forks.** Before forking, mount the remote run directory read-only on the local machine, so that Codex reads it with plain `cat`/`grep`/`ls`, which the Guard can prove read-only:

  ```bash
  sshfs -o ro,reconnect,ServerAliveInterval=15,ServerAliveCountMax=3,attr_timeout=5,entry_timeout=5,BatchMode=yes \
    <host>:<remote_dir> /tmp/<host>-ro
  ```

  Tested: reads work, and writes fail with "Read-only file system". Limitations:
  - Remote `/proc` reads come back empty over SFTP.
  - `nvidia-smi` cannot be reached this way.

  For process and GPU state, use a status file that the experiment writes, or check it yourself over ssh. A dropped network can hang reads on the mount, so wrap them in `timeout`. Unmount with `fusermount -u`.
- **`codex queue --thread <SID> --message <TEXT>` does not steer a running `codex exec`.** Tested: the running turn never saw the message. The message is delivered on the next `resume`. Use it to leave a note for the next turn. To change course mid-run, still stop the run and resume it with a ruling.

**When Codex stops on a gate:**
- First decide whether the cause is the task definition, which is your fault, or a real finding.
- If you can fix the task definition within the scope the user already approved, write the ruling and resume, then report afterwards.
- If the fix changes something the user decided, ask the user first.

## Sub-agents

Codex can spawn sub-agents, which speeds up work that splits into independent parts, such as separate comparison runs or repeated measurements. When a task has such parts, allow sub-agents, and say in the brief:
- which parts may run in parallel;
- which output paths each sub-agent owns. Leave edits to shared code to the main agent.

Keep the task to the main agent when every step edits the same code.

The watcher follows the main agent. Its messages and its final report carry the sub-agents' results, and idle alerts while it waits on sub-agents are expected. Each sub-agent writes its own session file under `~/.codex/sessions/`, which you can read when you need detail.

## With the Stop That Shit plugin

If the Codex installation uses the Stop That Shit Guard, every task file starts with a directive line that sets the mode, the files it may touch, the dependency policy and the sub-agent budget.

**Review-only tasks.** In `review` mode the Guard blocks every file write (`MODE_FORBIDS_MUTATION`) and every shell command it cannot prove read-only (`MUTABILITY_UNPROVEN`), including the report file and test runs. To let Codex write its report, whitelist that one file:

- Put this directive on the **first line** of a review task file, outside quotes and code blocks:

  ```text
  $stop-that-shit lock change files=<relative/path/to/REVIEW.md> -- Review only; write the report to this one file.
  ```

  Use the exact relative path. Separate several paths with `|`. Don't use globs.
- Still say in the task body that source, tests and docs must not be modified. The lock enforces this.
- Under a narrow `files=` lock, shell commands that can't be proven read-only still need approval, which `codex exec` cannot grant. Expect test runs to be blocked. Run the regression yourself and give Codex the results, marked "reviewer-verified".
- If the report still can't be written, take the findings from `$S/codex_<topic>_last.md`.

**Execution tasks.** Set the fields the task needs on the directive line:

```text
$stop-that-shit change agents=<N> deps=allow -- <task>
```

- `agents=N` is the sub-agent budget; use `agents=0` to keep the task to the main agent.
- The Guard defaults to `deps=ask` and blocks any `pip install` with `DEPENDENCY_NOT_AUTHORIZED`. Use `deps=allow` only when the task actually installs packages, and state in the body which environments it may install into.

## 5. Review on exit

- Read `$S/codex_<topic>_last.md` and the report.
- Spot-check the key numbers and images yourself. Look for false passes, for example a numerical failure silently recorded as 0.
- Check `git status` to confirm no protected files changed.
- Report to the user in their language, with the absolute paths of the images and files.

## Cost notes

- Each wake-up is a full turn carrying your whole context. Prefer event-driven monitoring over fixed-interval cron polling.
- Suggest `/compact` between rounds when the context is long.
- Codex compute itself is cheap compared with your turns.
````

## File: skills/dratamer/scripts/codex_digest.py
size: 1218
sha: 3664ca0a64ec6eaf56ddb44b445446fd384d12a3
upstream: https://github.com/5o1/dratamer/blob/44632199be4d7fc9c3fb823962626d8ffb125b35/skills/dratamer/scripts/codex_digest.py

```text
#!/usr/bin/env python3
"""Print Codex log content added since the previous call: agent messages in full, commands truncated."""
import sys
from pathlib import Path

log = Path(sys.argv[1])
state = log.with_suffix(log.suffix + ".offset")
start = int(state.read_text()) if state.exists() else 0
data = log.read_bytes()
state.write_text(str(len(data)))
lines = data[start:].decode("utf-8", "replace").splitlines()
out, mode = [], None
for line in lines:
    if line in ("codex", "exec", "user"):
        mode = line
        out.append(f"--- {line}")
        continue
    if line.startswith(("hook:", "tokens used")) or line.startswith("diff --git"):
        mode = "skip" if line.startswith("diff --git") else mode
        continue
    if mode == "codex" or mode == "user":
        out.append(line)
    elif mode == "exec":
        if line.startswith(" succeeded") or line.startswith(" exited") or line.startswith(" failed"):
            out.append(line[:160])
            mode = "execout"
        else:
            out.append(line[:300])
    elif mode == "execout" and ("Error" in line or "Traceback" in line):
        out.append("   ! " + line[:200])
print(f"[bytes {start}->{len(data)}]")
print("\n".join(out[-400:]))
```

## File: skills/dratamer/scripts/codex_watch.sh
size: 7181
sha: 637304e775ceb6797790571891f89a6e3e0976b6
upstream: https://github.com/5o1/dratamer/blob/44632199be4d7fc9c3fb823962626d8ffb125b35/skills/dratamer/scripts/codex_watch.sh

```text
#!/usr/bin/env bash
# Usage: [WATCH_PID=<codex pid>] [WATCH_COOLDOWN=30] [WATCH_OUTAGE=300] codex_watch.sh <codex-log> [idle-seconds, default 900]
# WATCH_PID tracks one Codex process; without it any running `codex exec` counts as alive.
# Run under the Monitor tool. Each stdout line is one event.
# Normal events (never throttled):
#   CODEX_MSG: <first lines of each Codex agent message>
#   CODEX_MSG [after context compaction]: the first message after Codex compacted its context
#     (not a separate event; if Codex exits first, a CODEX_COMPACTED line precedes CODEX_EXITED)
#   CODEX_IDLE: <no event for idle-seconds; log age; last shell command>
#   CODEX_EXITED  (when no `codex exec` process remains; the watch then ends)
# Failure-specific alerts (fire at once, but at most one per WATCH_COOLDOWN seconds;
# alerts inside the cooldown are counted and summarised as ALERT_SUPPRESSED once it ends):
#   CODEX_ERROR: Codex CLI errors that are not network errors
#   REMOTE_SSH_FAIL: ssh connect/auth failure seen in command output
#   NET_PROBLEM: network trouble has lasted WATCH_OUTAGE seconds (default 300) without recovery
#   NET_RECOVERED: the network is back after a period that raised NET_PROBLEM
# Network trouble (API reconnects, websocket/TLS/transport errors, Codex backend
# unreachable) opens a silent tolerance period. While it is open the backend is probed
# every 10 s; as soon as a probe succeeds the period closes and nothing is reported. Only a
# period still open after WATCH_OUTAGE seconds raises one NET_PROBLEM alert, followed by
# NET_RECOVERED when the backend is reachable again. A new interruption after a recovery
# opens a new period; there is never more than one.
log="$1"
idle="${2:-900}"
cooldown="${WATCH_COOLDOWN:-30}"
outage_limit="${WATCH_OUTAGE:-300}"
probe_url="${WATCH_PROBE_URL:-https://chatgpt.com/}"
state="$(mktemp -d)"
stamp="$state/stamp"; touch "$stamp"
echo 0 > "$state/last"; echo 0 > "$state/count"; : > "$state/lastmsg"; : > "$state/net_start"; : > "$state/net_log"

# Emit an alert unless one was emitted less than $cooldown seconds ago; otherwise count it.
alert() {
  (
    flock 9
    now=$(date +%s); last=$(cat "$state/last"); n=$(cat "$state/count")
    if (( now - last >= cooldown )); then
      (( n > 0 )) && echo "ALERT_SUPPRESSED: $n alert(s) within ${cooldown}s cooldown, last: $(cat "$state/lastmsg")"
      echo "$1"
      echo "$now" > "$state/last"; echo 0 > "$state/count"
    else
      echo $((n + 1)) > "$state/count"; echo "$1" > "$state/lastmsg"
    fi
    touch "$stamp"
  ) 9>"$state/lock"
}
# Report alerts that were held back once the cooldown has passed with no new alert.
flush_suppressed() {  # pass "force" to flush regardless of the cooldown (used at exit)
  (
    flock 9
    now=$(date +%s); last=$(cat "$state/last"); n=$(cat "$state/count")
    if (( n > 0 )) && { [[ ${1:-} == force ]] || (( now - last >= cooldown )); }; then
      echo "ALERT_SUPPRESSED: $n alert(s) within ${cooldown}s cooldown, last: $(cat "$state/lastmsg")"
      echo "$now" > "$state/last"; echo 0 > "$state/count"; touch "$stamp"
    fi
  ) 9>"$state/lock"
}

# One tolerance period at a time: $state/net_start holds its start time, $state/net_log its symptoms.
net_symptom() {  # $1 = retry|error|fail|backend_down
  ( flock 9
    [[ -s "$state/net_start" ]] || date +%s > "$state/net_start"
    echo "$1" >> "$state/net_log" ) 9>"$state/lock"
}
net_close() { ( flock 9; : > "$state/net_start"; : > "$state/net_log" ) 9>"$state/lock"; }

tail -n 0 -F "$log" 2>/dev/null | awk -v stamp="$stamp" -v cfile="$state/compacted" '
  function emit(s) { print s; fflush(); system("touch " stamp) }
  function msg(s) { if (compacted) { s = "CODEX_MSG [after context compaction]: " s; compacted = 0; system("rm -f " cfile) } else s = "CODEX_MSG: " s; emit(s) }
  function alert(s) { print "ALERT " s; fflush() }
  /^ERROR: Reconnecting\.\.\. 5\/5/ { print "NET fail"; fflush(); next }
  /^ERROR: Reconnecting/ { print "NET retry"; fflush(); next }
  /failed to refresh available models/ { next }  # known harmless (see SKILL.md)
  (/^ERROR: / || /^[0-9TZ:.-]+ +ERROR codex/ || /Falling back from WebSockets/) && /websocket|WebSocket|tls|TLS|timed out|stream disconnected|[Cc]onnection|error sending request|Falling back/ { print "NET error"; fflush(); next }
  /Orphan custom tool call output|Custom tool call output is missing/ { next }  # harmless after forking/resuming a session with an open tool call
  /^ERROR: / || /^[0-9TZ:.-]+ +ERROR codex/ { alert("CODEX_ERROR: " substr($0, 1, 200)); next }
  $0 == "context compacted" { compacted = 1; system("touch " cfile); next }
  /^ssh: connect to host/ || /Permission denied \(publickey/ || /^kex_exchange_identification/ { alert("REMOTE_SSH_FAIL: " substr($0, 1, 200)); next }
  $0 == "codex" { grab = 3; buf = ""; next }
  grab > 0 && $0 != "" { buf = buf (buf == "" ? "" : " / ") substr($0, 1, 220); grab--;
    if (grab == 0 || $0 ~ /^(exec|apply patch|hook:)/) { msg(buf); grab = 0 } next }
  grab > 0 && $0 == "" && buf != "" { msg(buf); grab = 0 }
' | while IFS= read -r line; do
  case "$line" in
    ALERT\ *) alert "${line#ALERT }" ;;
    NET\ *) net_symptom "${line#NET }" ;;
    *) echo "$line" ;;
  esac
done &
reader=$!
codex_alive() { if [[ -n "${WATCH_PID:-}" ]]; then kill -0 "$WATCH_PID" 2>/dev/null; else pgrep -f "^codex exec" >/dev/null; fi; }
net_up() { curl -s -o /dev/null --max-time 10 "$probe_url"; }
tick=0
# Give a just-launched Codex a moment to appear in the process table.
for _ in 1 2 3 4 5 6; do codex_alive && break; sleep 5; done
while codex_alive; do
  sleep 10
  tick=$((tick + 1))
  # Probe the backend every 60 s normally, every 10 s while a tolerance period is open.
  if (( tick % 6 == 0 )) || [[ -s "$state/net_start" ]]; then
    ok=1
    net_up || { ok=0; net_symptom backend_down; }
    if [[ -s "$state/net_start" ]]; then
      start=$(cat "$state/net_start")
      if (( ok )); then
        # Recovered: close quietly, unless this period already alerted.
        [[ -e "$state/net_alerted" ]] && alert "NET_RECOVERED: network back after $(( $(date +%s) - start ))s"
        rm -f "$state/net_alerted"; net_close
      elif [[ ! -e "$state/net_alerted" ]] && (( $(date +%s) - start >= outage_limit )); then
        summary=$(sort "$state/net_log" | uniq -c | awk '{printf "%s%s x%s", (NR>1?", ":""), $2, $1}')
        alert "NET_PROBLEM: network trouble for $(( $(date +%s) - start ))s without recovery (${summary})"
        touch "$state/net_alerted"                  # same interruption: no repeat until recovery
      fi
    fi
  fi
  flush_suppressed
  now=$(date +%s)
  if (( now - $(stat -c %Y "$stamp") >= idle )); then
    age=$(( now - $(stat -c %Y "$log") ))
    cmd=$(grep -E '^/bin/bash -lc' "$log" | tail -1 | cut -c1-200)
    echo "CODEX_IDLE: no agent message for ${idle}s; log last written ${age}s ago; last command: ${cmd}"
    touch "$stamp"
  fi
done
sleep 2
flush_suppressed force
[[ -e "$state/compacted" ]] && echo "CODEX_COMPACTED: Codex compacted its context and exited before writing another message"
echo "CODEX_EXITED"
kill "$reader" 2>/dev/null
pkill -P $$ 2>/dev/null
rm -rf "$state"
exit 0
```

## File: README.md
upstream: https://github.com/5o1/dratamer/blob/44632199be4d7fc9c3fb823962626d8ffb125b35/README.md

````text
# DraTamer

The white-haired dragon girl should be whipped hard by the orange-haired young lady until she gets to work.

![An orange-haired young lady with a riding crop supervises a flustered white-haired dragon girl buried in paperwork](assets/illustration.png)

DraTamer is a [Claude Code](https://claude.com/claude-code) skill for having Claude orchestrate the [OpenAI Codex CLI](https://github.com/openai/codex). Claude writes the task, Codex runs in the background, and Claude supervises from Codex's log. When Codex goes off track, Claude stops it and resumes the same session with a written ruling.

## Why

Left alone, Codex tends to:
- simplify the task: hardcoding values, skipping checks, swapping in weaker methods;
- drift off scope: extra tooling, starting later phases, editing files it should not touch.

Watching it turn by turn is expensive, though. DraTamer keeps the human out of the loop for routine progress and wakes Claude only when something happens.

## How it works

0. **Decouple.** Claude splits the work by write set (the files, output directories and runtime resources each part changes). Parts with disjoint write sets run as parallel Codex sessions, each with its own task, log and monitor. Parts that edit the same code stay in one session. A new request that doesn't touch a running session's files starts a new session instead of interrupting it.
1. **Brief.** Claude writes a task file with:
   - verified context;
   - a precise method;
   - critical gates, which stop the run, and non-critical gates, which are recorded and the run continues;
   - a bounded self-fix budget;
   - the files Codex may touch, and the files other running sessions own;
   - the required deliverables.
2. **Launch.** `codex exec` runs in the background with an explicit model, sandbox and network setting.
3. **Watch.** `scripts/codex_watch.sh` tails the Codex log under Claude Code's Monitor tool. Each output line is an event that wakes Claude:

   | Event | Meaning | Throttled |
   |---|---|---|
   | `CODEX_MSG` | Codex wrote an agent message | no |
   | `CODEX_MSG [after context compaction]` | the first message after Codex compacted its context; re-check it against the brief | no |
   | `CODEX_IDLE` | nothing happened for the idle interval (default 15 min) | no |
   | `CODEX_EXITED` | the Codex process is gone | no |
   | `CODEX_ERROR` | a Codex CLI error other than a network error | yes |
   | `NET_PROBLEM` / `NET_RECOVERED` | network trouble outlasted the tolerance period / ended | yes |
   | `REMOTE_SSH_FAIL` | an ssh connect or key-auth failure in command output | yes |

   Each known failure has its own hook, so a real failure does not wait for the idle check. Throttled alerts share a cooldown (`WATCH_COOLDOWN`, default 30 s): at most one wakes Claude per cooldown. The rest are summarised in a single `ALERT_SUPPRESSED` line.

   Brief network trouble needs no action, because Codex reconnects on its own. API reconnects, websocket/TLS errors and an unreachable backend open a silent tolerance period that closes as soon as the backend answers again. Only trouble lasting longer than `WATCH_OUTAGE` seconds (default 300) wakes Claude.
4. **Intervene.** For a change inside the session's own scope, Claude stops Codex, writes a ruling (root cause, corrected method, what stays unchanged), and resumes the same Codex session. Separate new work goes to a parallel session.
5. **Accept.** Claude, as the lead, verifies the result itself before reporting or shipping. It looks at the UI, images or files the way the user will, recomputes key numbers, runs the tests, and checks every default Codex chose against the user's words. A requirement ledger records each request with Claude's own evidence. The report to the user separates what Claude verified from what it has only Codex's word for. Routine Codex messages are for steering and are not relayed as progress.

Claude and Codex talk to each other in American English: task files, rulings, questions and Codex's reports. Claude still talks to the user in the user's language.

The full procedure is in [`skills/dratamer/SKILL.md`](skills/dratamer/SKILL.md).

## Install

Requirements:
- Claude Code with the Monitor tool;
- the Codex CLI, logged in;
- bash, awk, curl, `flock` (util-linux) and Python 3.

```bash
git clone https://github.com/5o1/DraTamer.git
ln -s "$PWD/DraTamer/skills/dratamer" ~/.claude/skills/dratamer
```

Claude Code then lists `dratamer` among its skills. Ask Claude to "have Codex do it" or to "supervise Codex", or invoke the skill by name.

## Watcher usage

```bash
WATCH_PID=<codex pid> WATCH_COOLDOWN=30 WATCH_OUTAGE=300 \
  bash ~/.claude/skills/dratamer/scripts/codex_watch.sh <codex-log> [idle-seconds]
```

- `WATCH_PROBE_URL` overrides the backend reachability probe (default `https://chatgpt.com/`).
- `WATCH_PID` tracks the Codex process you launched. Without it, any running `codex exec` (including other sessions' runs) counts as alive.

`scripts/codex_digest.py <codex-log>` prints the log content added since its previous call: agent messages in full, commands truncated.

## License

[MIT](LICENSE) © 2026 5o1
````
