Skip to content

Compress tool outputs, logs, files, and RAG chunks before they reach the LLM. 20% fewer tokens for coding agents, 60-95% fewer tokens for JSON, same answers. Library, proxy, MCP server.

[codex] Simulate Codex read maturation risk (#1395)

panamarob30-jpg3f5067022f88
diff --git a/headroom/audit/__init__.py b/headroom/audit/__init__.py
index 2ef7578cb..032d63d41 100644
--- a/headroom/audit/__init__.py
+++ b/headroom/audit/__init__.py
@@ -1,7 +1,12 @@
"""Offline traffic audits — measure opportunity sizes before tuning defaults."""
from .codex import CodexAuditReport, audit_codex, render_codex_text
-from .maturation import MaturationSimReport, render_sim_text, simulate_maturation
+from .maturation import (
+ MaturationSimReport,
+ render_sim_text,
+ simulate_codex_maturation,
+ simulate_maturation,
+)
from .reads import ReadAuditReport, audit_reads, render_text
__all__ = [
@@ -13,5 +18,6 @@ __all__ = [
"render_codex_text",
"render_sim_text",
"render_text",
+ "simulate_codex_maturation",
"simulate_maturation",
]
diff --git a/headroom/audit/codex.py b/headroom/audit/codex.py
index d887d5376..934b085b3 100644
--- a/headroom/audit/codex.py
+++ b/headroom/audit/codex.py
@@ -28,6 +28,8 @@ _READ_PROGS = frozenset({"cat", "sed", "head", "tail", "nl", "bat", "more", "rea
_SEARCH_PROGS = frozenset({"rg", "grep", "ugrep", "ag", "fd", "find"})
_BUILD_PROGS = frozenset({"python", "python3", "pytest", "cargo", "npm", "make", "uv", "ruff"})
_RANGE_RE = re.compile(r"^\d+([,:-]\d+)?p?$")
+_PATCH_FILE_RE = re.compile(r"^\*\*\* (?:Add|Update|Delete) File: (.+)$", re.MULTILINE)
+_REDIRECT_RE = re.compile(r"(?:^|\s)(?:>|>>)\s*([^\s;&|]+)")
MATURE_FLOOR = 2048 # ReadMaturationConfig.min_size_bytes
@@ -68,34 +70,82 @@ def strip_wrappers(cmd: str) -> str:
return c
+def _resolve_path(path: str | None, workdir: str = "") -> str | None:
+ if not path:
+ return None
+ p = path.strip().strip("'\"")
+ if not p or p in {"-", "&1", "&2"}:
+ return None
+ if workdir and not p.startswith("/"):
+ return f"{workdir.rstrip('/')}/{p}"
+ return p
+
+
+def _path_candidates(tokens: list[str]) -> list[str]:
+ return [
+ t
+ for t in tokens
+ if not t.startswith("-")
+ and not _RANGE_RE.match(t.strip("'\""))
+ and ("/" in t or "." in t.rsplit("/", 1)[-1])
+ ]
+
+
+def _extract_edit_path(cmd: str, tokens: list[str], workdir: str = "") -> str | None:
+ patch_match = _PATCH_FILE_RE.search(cmd)
+ if patch_match:
+ return _resolve_path(patch_match.group(1), workdir)
+
+ redirect_match = _REDIRECT_RE.search(cmd)
+ if redirect_match:
+ return _resolve_path(redirect_match.group(1), workdir)
+
+ parts = re.split(r"&&|\|", cmd)
+ for part in parts:
+ try:
+ ptoks = shlex.split(part.strip())
+ except ValueError:
+ ptoks = part.strip().split()
+ if not ptoks:
+ continue
+ prog = ptoks[0].rsplit("/", 1)[-1]
+ if prog == "tee":
+ paths = _path_candidates(ptoks[1:])
+ if paths:
+ return _resolve_path(paths[0], workdir)
+
+ if tokens:
+ prog = tokens[0].rsplit("/", 1)[-1]
+ if prog == "sed" and any(t == "-i" or t.startswith("-i") for t in tokens[1:]):
+ paths = _path_candidates(tokens[1:])
+ if paths:
+ return _resolve_path(paths[-1], workdir)
+ return None
+
+
def classify_command(cmd: str, workdir: str = "") -> tuple[str, str | None, bool]:
"""Classify a shell command: (category, file_path|None, is_partial).
Categories: read, search, git, edit, build/test, compound, other.
- For reads, the path is resolved against ``workdir`` when relative.
+ For reads and edits, the path is resolved against ``workdir`` when relative.
"""
c = strip_wrappers(cmd)
- if "apply_patch" in c:
- return "edit", None, False
try:
toks = shlex.split(c)
except ValueError:
toks = c.split()
if not toks:
return "other", None, False
+
+ edit_path = _extract_edit_path(c, toks, workdir)
+ if edit_path or "apply_patch" in c:
+ return "edit", edit_path, False
+
prog = toks[0].rsplit("/", 1)[-1]
if prog in _READ_PROGS:
- candidates = [
- t
- for t in toks[1:]
- if not t.startswith("-") and ("/" in t or "." in t.rsplit("/", 1)[-1])
- ]
- # Range tokens like 1,200p (sed) are not paths.
- candidates = [t for t in candidates if not _RANGE_RE.match(t.strip("'\""))]
- fpath = candidates[0] if candidates else None
- if fpath and workdir and not fpath.startswith("/"):
- fpath = f"{workdir.rstrip('/')}/{fpath}"
+ candidates = _path_candidates(toks[1:])
+ fpath = _resolve_path(candidates[0], workdir) if candidates else None
partial = (
prog in ("sed", "head", "tail")
or any(_RANGE_RE.match(t.strip("'\"")) for t in toks[1:])
diff --git a/headroom/audit/maturation.py b/headroom/audit/maturation.py
index ccf4be20d..e21b4cad3 100644
--- a/headroom/audit/maturation.py
+++ b/headroom/audit/maturation.py
@@ -166,6 +166,117 @@ def simulate_maturation(root: Path) -> MaturationSimReport:
return r
+def _codex_output_text(payload: dict) -> str:
+ out = payload.get("output", "")
+ if isinstance(out, dict):
+ out = out.get("output", "") or str(out)
+ return str(out)
+
+
+def simulate_codex_maturation(root: Path) -> MaturationSimReport:
+ """Run the maturation simulation over Codex shell-based transcripts.
+
+ Codex has no structured ``Read`` tool. It reads files through
+ ``exec_command`` calls such as ``cat``, ``sed -n``, and ``rtk read``.
+ This mirrors ``simulate_maturation`` with the Codex command classifier
+ so ``headroom audit-reads --codex --simulate-maturation`` sizes the
+ same read-maturation policy from Codex traffic instead of returning an
+ all-zero Claude-only simulation.
+ """
+ from headroom.audit.codex import classify_command
+
+ r = MaturationSimReport()
+ next_touch_gaps: list[int] = []
+ at_risk = dict.fromkeys(QUIESCE_CANDIDATES, 0)
+
+ for path in sorted(root.glob("**/*.jsonl")):
+ pending: dict[str, tuple[str, str | None, bool, int]] = {}
+ timeline: dict[str, list[tuple[int, str, int]]] = defaultdict(list)
+ session_reads: list[tuple[str, int, int]] = []
+ seen_files: set[str] = set()
+ turn = 0
+ try:
+ with path.open(errors="replace") as f:
+ for raw in f:
+ try:
+ line = json.loads(raw)
+ except json.JSONDecodeError:
+ continue
+ pl = line.get("payload") or {}
+ t = pl.get("type")
+ if t == "function_call" and pl.get("name") == "exec_command":
+ turn += 1
+ try:
+ args = json.loads(pl.get("arguments", "{}"))
+ except (json.JSONDecodeError, TypeError):
+ args = {}
+ cat, fpath, partial = classify_command(
+ args.get("cmd", ""), args.get("workdir", "")
+ )
+ pending[pl.get("call_id", "")] = (cat, fpath, partial, turn)
+ if cat == "read" and fpath:
+ r.read_calls += 1
+ if fpath in seen_files:
+ r.rereads_any += 1
+ if partial:
+ r.rereads_partial += 1
+ seen_files.add(fpath)
+ timeline[fpath].append((turn, "read", 0))
+ elif cat == "edit" and fpath:
+ timeline[fpath].append((turn, "edit", 0))
+ elif t == "function_call_output":
+ cat, fpath, _partial, call_turn = pending.get(
+ pl.get("call_id", ""), ("", None, False, turn)
+ )
+ if cat != "read" or not fpath:
+ continue
+ text = _codex_output_text(pl)
+ size = len(text.encode("utf-8", errors="replace"))
+ session_reads.append((fpath, call_turn, size))
+ except OSError:
+ continue
+
+ for ops in timeline.values():
+ ops.sort(key=lambda item: item[0])
+ for op_turn, kind, _size in ops:
+ if kind != "edit":
+ continue
+ previous = [(t, k) for t, k, _ in ops if t < op_turn]
+ if not any(k == "read" for _t, k in previous):
+ r.edits_without_prior_read += 1
+ continue
+ r.edits_with_prior_read += 1
+ gap = op_turn - max(t for t, _k in previous)
+ for n in QUIESCE_CANDIDATES:
+ if gap > n:
+ at_risk[n] += 1
+
+ for fpath, read_turn, size in session_reads:
+ if size < MATURE_FLOOR:
+ continue
+ r.big_reads += 1
+ r.big_read_bytes += size
+ later = [t for t, _, _ in timeline[fpath] if t > read_turn]
+ if later:
+ next_touch_gaps.append(min(later) - read_turn)
+ else:
+ r.never_touched_again += 1
+
+ def pct(xs: list[int], p: float) -> int:
+ return sorted(xs)[int(len(xs) * p)] if xs else 0
+
+ r.next_touch_p50 = pct(next_touch_gaps, 0.5)
+ r.next_touch_p90 = pct(next_touch_gaps, 0.9)
+ r.next_touch_p95 = pct(next_touch_gaps, 0.95)
+ if next_touch_gaps:
+ r.next_touch_within = {
+ n: round(100 * sum(1 for gap in next_touch_gaps if gap <= n) / len(next_touch_gaps), 1)
+ for n in QUIESCE_CANDIDATES
+ }
+ r.at_risk_edits = at_risk
+ return r
+
+
def render_sim_text(r: MaturationSimReport) -> str:
"""Human-readable simulation summary."""
out: list[str] = []
diff --git a/headroom/cli/audit.py b/headroom/cli/audit.py
index e1cfa5998..26d2b7329 100644
--- a/headroom/cli/audit.py
+++ b/headroom/cli/audit.py
@@ -71,10 +71,21 @@ def audit_reads_cmd(
codex_report = audit_codex(root)
if codex_report.sessions == 0:
raise click.ClickException(f"no *.jsonl transcripts found under {root}")
+ sim = None
+ if simulate_maturation:
+ from headroom.audit.maturation import render_sim_text, simulate_codex_maturation
+
+ sim = simulate_codex_maturation(root)
if output_format == "json":
- click.echo(_json.dumps(codex_report.to_dict(), indent=2, sort_keys=True))
+ data = codex_report.to_dict()
+ if sim is not None:
+ data["maturation_simulation"] = sim.to_dict()
+ click.echo(_json.dumps(data, indent=2, sort_keys=True))
else:
click.echo(render_codex_text(codex_report))
+ if sim is not None:
+ click.echo()
+ click.echo(render_sim_text(sim))
return
if root is None:
diff --git a/tests/test_audit_codex.py b/tests/test_audit_codex.py
index 66d036e08..826a0bbaf 100644
--- a/tests/test_audit_codex.py
+++ b/tests/test_audit_codex.py
@@ -52,6 +52,24 @@ class TestClassifier:
assert cat == "read"
assert path == "/r/foo.py"
+ @pytest.mark.parametrize(
+ ("cmd", "expected"),
+ [
+ (
+ "apply_patch <<'PATCH'\n*** Begin Patch\n*** Update File: src/foo.py\n@@\n*** End Patch\nPATCH",
+ "/repo/src/foo.py",
+ ),
+ ("sed -i 's/old/new/' src/foo.py", "/repo/src/foo.py"),
+ ("printf 'x' | tee src/foo.py", "/repo/src/foo.py"),
+ ("cat <<'EOF' > src/foo.py\nx\nEOF", "/repo/src/foo.py"),
+ ],
+ )
+ def test_edit_path_extraction(self, cmd, expected):
+ cat, path, partial = classify_command(cmd, workdir="/repo")
+ assert cat == "edit"
+ assert path == expected
+ assert partial is False
+
def _call(call_id: str, cmd: str, workdir: str = "/repo") -> str:
return json.dumps(
@@ -113,6 +131,77 @@ class TestAuditCodex:
assert audit_codex(tmp_path).sessions == 0
+class TestCodexMaturationSim:
+ def test_metrics(self, codex_dir):
+ from headroom.audit.maturation import simulate_codex_maturation
+
+ r = simulate_codex_maturation(codex_dir)
+ assert r.read_calls == 3
+ assert r.rereads_any == 1
+ assert r.rereads_partial == 1
+ assert r.big_reads == 1
+ assert r.never_touched_again == 0
+ assert r.next_touch_p50 == 1
+
+ def test_cli_codex_simulate_maturation(self, codex_dir):
+ from click.testing import CliRunner
+
+ from headroom.cli.main import main
+
+ runner = CliRunner()
+ res = runner.invoke(
+ main, ["audit-reads", "--codex", "--path", str(codex_dir), "--simulate-maturation"]
+ )
+ assert res.exit_code == 0, res.output
+ assert "codex read-pattern audit" in res.output
+ assert "maturation simulation" in res.output
+ assert "re-reads: 1/3" in res.output
+
+ res = runner.invoke(
+ main,
+ [
+ "audit-reads",
+ "--codex",
+ "--path",
+ str(codex_dir),
+ "--simulate-maturation",
+ "--format",
+ "json",
+ ],
+ )
+ assert res.exit_code == 0, res.output
+ data = json.loads(res.output)
+ assert data["read_calls"] == 3
+ assert data["maturation_simulation"]["read_calls"] == 3
+ assert data["maturation_simulation"]["rereads_any"] == 1
+
+ def test_edit_risk_metrics_from_codex_mutations(self, tmp_path):
+ from headroom.audit.maturation import simulate_codex_maturation
+
+ lines = [
+ _call("c1", "cat src/foo.py"),
+ _output("c1", "line\n" * 600),
+ _call("c2", "rg -n TODO src"),
+ _output("c2", "src/foo.py:1:TODO"),
+ _call("c3", "sed -i 's/TODO/done/' src/foo.py"),
+ _output("c3", ""),
+ _call(
+ "c4",
+ "apply_patch <<'PATCH'\n*** Begin Patch\n*** Update File: src/bar.py\n@@\n*** End Patch\nPATCH",
+ ),
+ _output("c4", "Done!"),
+ ]
+ sessions = tmp_path / "sessions"
+ sessions.mkdir()
+ (sessions / "rollout.jsonl").write_text("\n".join(lines))
+
+ r = simulate_codex_maturation(sessions)
+ assert r.edits_with_prior_read == 1
+ assert r.edits_without_prior_read == 1
+ assert r.at_risk_edits[1] == 1
+ assert r.at_risk_edits[2] == 0
+
+
class TestCli:
def test_cli_codex_mode(self, codex_dir):
from click.testing import CliRunner