Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(distill): Codex CLI rewrite support + repowise corrections (#391)

Raghav Chamadiyac51dab652387
diff --git a/docs/CLI_REFERENCE.md b/docs/CLI_REFERENCE.md
index 3b8451120..59c121385 100644
--- a/docs/CLI_REFERENCE.md
+++ b/docs/CLI_REFERENCE.md
@@ -412,6 +412,27 @@ repowise saved --since 2026-06-01
---
+### `repowise corrections [PATH]`
+
+Mine local agent transcripts for recurring command fumbles — consecutive runs
+of the same base command where the first failed and a later variant succeeded
+(wrong tool, wrong path, unknown flag, missing argument). Report-only by
+default; entirely local. See [DISTILL.md](DISTILL.md#repowise-corrections--recurring-command-fumbles).
+
+| Flag | Description |
+|------|-------------|
+| `--days` | Transcript window for the scan (default 30) |
+| `--write` | Maintain the "Known command corrections" managed block in `.claude/CLAUDE.md` / `AGENTS.md` (opt-in) |
+| `--min-count` | Occurrences a rule needs before `--write` includes it (default 2) |
+
+```bash
+repowise corrections # report recurring fumbles
+repowise corrections --days 60
+repowise corrections --write # seed the agent guidance block
+```
+
+---
+
### `repowise costs`
Show LLM spend tracking.
@@ -509,26 +530,35 @@ See [Auto-Sync](AUTO_SYNC.md) for all sync methods (hooks, file watcher, webhook
### `repowise hook rewrite install|uninstall|status`
-Manage the Distill command-rewrite hook (Claude Code PreToolUse). When
-installed, noisy agent commands (tests, builds, git status/log/diff, searches,
-listings) are rewritten to `repowise distill <command>` — pending your
-approval by default — so the agent sees a compact, errors-first rendering.
+Manage the Distill command-rewrite hooks (Claude Code + Codex PreToolUse).
+When installed, noisy agent commands (tests, builds, git status/log/diff,
+searches, listings) are rewritten to `repowise distill <command>` — pending
+your approval by default — so the agent sees a compact, errors-first
+rendering.
```bash
repowise hook rewrite install # writes ~/.claude/settings.json (idempotent)
repowise hook rewrite install -w # also re-enable every workspace repo
repowise hook rewrite status
-repowise hook rewrite uninstall # removes only the repowise entry
+repowise hook rewrite uninstall # removes only the repowise entries
```
`install` also re-enables the target's `distill.commands` config if a prior
`repowise init` opt-out had gated it off — the target repo by default, or
every workspace repo with `--workspace`/`-w` (accepts an optional `PATH` and
-`--no-workspace`, like `repowise hook install`). `uninstall` is global
-(settings.json) and leaves per-repo config untouched. Per-repo posture
-(`permission: ask | allow`, per-family overrides) lives under
-`distill.commands` in `.repowise/config.yaml` — see
-[DISTILL.md](DISTILL.md#configuration).
+`--no-workspace`, like `repowise hook install`). `uninstall` removes the
+global hook entries plus the repo's AGENTS.md awareness section and leaves
+per-repo config untouched. Per-repo posture (`permission: ask | allow`,
+per-family overrides) lives under `distill.commands` in
+`.repowise/config.yaml` — see [DISTILL.md](DISTILL.md#configuration).
+
+When `~/.codex` exists, `install` also writes a Codex hook entry to
+`~/.codex/hooks.json` (Codex ≥ 0.137 only — older builds can't apply a
+rewrite) and maintains an "Output Distillation" section in the repo's
+`AGENTS.md` that works without any hook. Codex cannot show a rewritten
+command for approval, so there rewrites fire only for families set to
+`permission: allow`; `status` reports exactly what your build supports. See
+[DISTILL.md](DISTILL.md#3-the-command-rewrite-hook-claude-code--codex).
---
diff --git a/docs/DISTILL.md b/docs/DISTILL.md
index 9c6e21aa8..2aaf88ed8 100644
--- a/docs/DISTILL.md
+++ b/docs/DISTILL.md
@@ -69,7 +69,7 @@ Looks in the current repo's store first, then the user-level fallback store.
MCP clients without a shell can resolve the same refs through
`get_symbol("repowise#<ref>")` — see [MCP](#5-mcp-response-budget--_metaomitted).
-### 3. The command-rewrite hook (Claude Code)
+### 3. The command-rewrite hook (Claude Code + Codex)
Opt-in. A PreToolUse hook rewrites noisy agent commands —
`pytest -x` → `repowise distill pytest -x` — **pending your approval**: the
@@ -79,13 +79,35 @@ running it. Install:
```bash
repowise hook rewrite install # or opt in during `repowise init`
repowise hook rewrite status
-repowise hook rewrite uninstall # removes only the repowise entry
+repowise hook rewrite uninstall # removes only the repowise entries
```
The hook covers both Claude Code shell tools — Bash and, on Windows,
PowerShell. Existing installs are widened automatically on the next
`install`/`init`.
+**Codex.** When `~/.codex` exists, `install` also covers the Codex CLI, with
+two honest caveats its hook protocol imposes:
+
+- Codex applies a PreToolUse command rewrite only from **version 0.137**;
+ on older builds the hook entry is skipped (a rewrite response would error
+ on every shell call). `repowise hook rewrite status` reports what your
+ build can do.
+- Codex has **no ask-with-mutation** — a rewrite can only be auto-allowed,
+ never shown for approval. So under Codex, rewrites fire **only for command
+ families you set to `permission: allow`** in `.repowise/config.yaml`;
+ `ask` families always pass through unchanged. We never silently mutate a
+ command you didn't opt into.
+
+The hook entry lands in `~/.codex/hooks.json` (one install covers every
+repo); Codex requires new hooks to be reviewed — run `/hooks` inside Codex to
+trust it. Independently of any hook, `install` maintains a marker-managed
+**"Output Distillation" section in the repo's `AGENTS.md`** teaching the
+agent to run `repowise distill <cmd>` voluntarily and to `repowise expand`
+markers instead of re-running commands — this works on every Codex version,
+including ones with no usable rewrite hook. `uninstall` removes the section
+and restores your AGENTS.md byte-for-byte.
+
The hook is deliberately conservative. It never rewrites:
- pipes, redirections, compound commands (`|`, `>`, `&&`, `;`, backticks, `$()`)
@@ -243,6 +265,47 @@ stat sourced from the same local scan.
---
+## `repowise corrections` — recurring command fumbles
+
+The same transcript reader, pointed at a different waste: commands the agent
+got *wrong* and then fixed. The scan finds consecutive runs of the same base
+command where the first failed (the transcript records a real exit code) and
+a later variant succeeded, classifies the fumble, and aggregates the
+recurring rules:
+
+```bash
+repowise corrections # report-only (default window: 30 days)
+repowise corrections --days 60
+repowise corrections --write # maintain the managed guidance block
+```
+
+| Kind | Example rule |
+|---|---|
+| wrong tool | use `.venv\Scripts\python.exe` instead of bare `python` |
+| wrong path | `pytest`: use `tests/unit/cli/`, not `../../tests/unit/cli/` |
+| unknown flag | `pytest` does not support `--looponfail` |
+| missing arg | `tool` needs `--required-thing` |
+
+Classification is deliberately precision-first: apart from the structural
+wrong-tool case, a rule only forms when the error text corroborates it (the
+dropped flag or path is actually named by the error) — a red-green dev loop
+re-running tests with different selections never becomes a "correction".
+Wrong-path rules consult the symbol index when available and note where the
+corrected target actually lives.
+
+`--write` (strictly opt-in) maintains a short **"Known command corrections"**
+managed block — most-frequent rules first, at least 2 occurrences each,
+capped at 10 lines — between `REPOWISE_CORRECTIONS` markers in the repo's
+`.claude/CLAUDE.md` (and `AGENTS.md` when one exists), so the next agent
+session is told up front. Re-running `--write` refreshes the block in place;
+when no rule clears the threshold anymore, the block is removed. Content
+outside the markers is never touched.
+
+The same privacy contract as the missed scan applies: read-only, best-effort,
+entirely local.
+
+---
+
## Measured savings
On a public OSS repository (microdot), one run per command, tokens estimated
@@ -297,7 +360,7 @@ and whether the rewrite hook is installed.
| Risk | Mitigation |
|---|---|
| A filter eats a critical line | errors-first invariant + fixture tests + `expand` recovery + fallback-to-raw |
-| Silent permission escalation | rewrites default to `ask`; the user sees the modified command |
+| Silent permission escalation | rewrites default to `ask`; the user sees the modified command. Codex has no ask primitive, so only families explicitly set to `allow` rewrite there |
| Marker with nothing behind it | content stored *before* the marker renders; store failure ⇒ raw output |
| Compound-command semantics | pipes/redirects/`&&` are never rewritten |
| Unindexed or stale repo | filters work index-free; index only improves ranking |
diff --git a/packages/cli/src/repowise/cli/agent_adapters/base.py b/packages/cli/src/repowise/cli/agent_adapters/base.py
index 4e2bde960..cb79b7f46 100644
--- a/packages/cli/src/repowise/cli/agent_adapters/base.py
+++ b/packages/cli/src/repowise/cli/agent_adapters/base.py
@@ -59,6 +59,13 @@ class AgentAdapter(ABC):
#: Stable adapter identifier (e.g. ``"claude-code"``).
name: ClassVar[str]
+ #: Permission postures this agent's hook protocol can actually honor for
+ #: a rewritten command. Claude Code supports ask-with-mutation; an agent
+ #: that can only allow-with-mutation (Codex) narrows this to
+ #: ``{"allow"}`` and the hook passes ``ask`` decisions through untouched
+ #: rather than silently escalating them to an unprompted rewrite.
+ rewrite_permissions: ClassVar[frozenset[str]] = frozenset({"ask", "allow"})
+
@abstractmethod
def detect(self) -> bool:
"""True when this agent appears to be installed for the current user."""
diff --git a/packages/cli/src/repowise/cli/agent_adapters/codex.py b/packages/cli/src/repowise/cli/agent_adapters/codex.py
new file mode 100644
index 000000000..304626448
--- /dev/null
+++ b/packages/cli/src/repowise/cli/agent_adapters/codex.py
@@ -0,0 +1,102 @@
+"""Codex CLI adapter — PreToolUse payloads and ``hookSpecificOutput`` responses.
+
+Protocol reference (Codex hooks, developers.openai.com/codex/hooks): hooks
+load from ``~/.codex/hooks.json`` (or a repo-local ``.codex/hooks.json``); a
+PreToolUse hook receives JSON on stdin with snake_case
+``hook_event_name``/``tool_name``/``tool_input``/``cwd`` — the shell tool is
+named ``Bash`` and ``tool_input.command`` is a string — and answers with
+camelCase ``hookSpecificOutput`` JSON on stdout.
+
+Two protocol limits shape this adapter's honesty posture:
+
+ - ``permissionDecision`` supports only ``"allow"`` and ``"deny"`` —
+ ``"ask"`` is parsed but **not honored**, and ``updatedInput`` is only
+ applied with ``"allow"``. There is no ask-with-mutation primitive, so
+ rewrites fire **only** for command families the user explicitly set to
+ ``permission: allow``; ``ask`` families pass through untouched
+ (:attr:`rewrite_permissions`). A silently mutated command would be a
+ permission escalation, and we don't do that.
+ - ``updatedInput`` rewriting requires Codex >= 0.137 (older builds reject
+ it at runtime as unsupported). Install is version-gated in
+ :mod:`repowise.cli.editor_integrations.codex_config`.
+"""
+
+from __future__ import annotations
+
+import json
+import os.path
+from typing import TYPE_CHECKING, ClassVar
+
+from repowise.cli.agent_adapters.base import AgentAdapter, RewriteRequest, RewriteResult
+
+if TYPE_CHECKING:
+ from pathlib import Path
+
+
+class CodexAdapter(AgentAdapter):
+ name: ClassVar[str] = "codex"
+
+ #: No ask-with-mutation in the Codex hook protocol — see module docstring.
+ rewrite_permissions: ClassVar[frozenset[str]] = frozenset({"allow"})
+
+ def detect(self) -> bool:
+ return os.path.isdir(os.path.expanduser("~/.codex"))
+
+ def parse_hook_payload(self, raw: str) -> RewriteRequest | None:
+ try:
+ payload = json.loads(raw)
+ except (json.JSONDecodeError, TypeError):
+ return None
+ if not isinstance(payload, dict):
+ return None
+ if payload.get("hook_event_name") != "PreToolUse":
+ return None
+ # Codex's shell tool is named "Bash" (there is no separate
+ # PowerShell tool); the command is always a string.
+ if payload.get("tool_name") != "Bash":
+ return None
+ tool_input = payload.get("tool_input")
+ command = tool_input.get("command") if isinstance(tool_input, dict) else None
+ if not isinstance(command, str) or not command.strip():
+ return None
+ cwd = payload.get("cwd")
+ return RewriteRequest(
+ command=command,
+ cwd=cwd if isinstance(cwd, str) else "",
+ shell="posix",
+ )
+
+ def render_response(self, result: RewriteResult) -> str:
+ # Only called for permissions in ``rewrite_permissions`` — i.e.
+ # "allow". Rendering "ask" here would make Codex error the hook.
+ return json.dumps(
+ {
+ "hookSpecificOutput": {
+ "hookEventName": "PreToolUse",
+ "permissionDecision": result.permission,
+ "permissionDecisionReason": result.reason,
+ "updatedInput": {"command": result.command},
+ }
+ }
+ )
+
+ def install_rewrite_hook(self) -> Path | None:
+ from repowise.cli.editor_integrations.codex_config import (
+ install_codex_rewrite_hook,
+ )
+
+ return install_codex_rewrite_hook()
+
+ def uninstall_rewrite_hook(self) -> bool:
+ from repowise.cli.editor_integrations.codex_config import (
+ uninstall_codex_rewrite_hook,
+ )
+
+ return uninstall_codex_rewrite_hook()
+
+ def rewrite_hook_installed(self) -> bool:
+ from repowise.cli.editor_integrations.codex_config import (
+ codex_rewrite_hook_installed,
+ )
+
+ return codex_rewrite_hook_installed()
diff --git a/packages/cli/src/repowise/cli/commands/corrections_cmd.py b/packages/cli/src/repowise/cli/commands/corrections_cmd.py
new file mode 100644
index 000000000..ee36b7ea7
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/corrections_cmd.py
@@ -0,0 +1,145 @@
+"""``repowise corrections`` — fail→fixed command pairs the agent keeps hitting.
+
+Mines local agent transcripts (the same reader as ``repowise saved --missed``)
+for shell commands that failed and were re-run successfully in a corrected
+form, classifies each fumble (wrong tool, wrong path, unknown flag, missing
+argument), and reports the recurring rules. Report-only by default;
+``--write`` additionally maintains a short "Known command corrections"
+managed block in the repo's CLAUDE.md/AGENTS.md so the next session doesn't
+repeat the fumble.
+"""
+
+from __future__ import annotations
+
+from pathlib import Path
+
+import click
+from rich.table import Table
+
+from repowise.cli.helpers import console
+
+_KIND_LABELS = {
+ "wrong_tool": "wrong tool",
+ "wrong_path": "wrong path",
+ "unknown_flag": "unknown flag",
+ "missing_arg": "missing arg",
+}
+
+
[email protected]("corrections")
[email protected]("path", required=False, default=None)
+ "--days",
+ type=click.FloatRange(min=0.1),
+ default=30.0,
+ show_default=True,
+ metavar="DAYS",
+ help="Transcript window for the scan.",
+)
+ "--write",
+ "write_block",
+ is_flag=True,
+ help=(
+ "Maintain the 'Known command corrections' managed block in the "
+ "repo's CLAUDE.md/AGENTS.md (strictly opt-in; report-only otherwise)."
+ ),
+)
+ "--min-count",
+ type=click.IntRange(min=1),
+ default=2,
+ show_default=True,
+ help="Occurrences a rule needs before --write includes it.",
+)
+def corrections_command(path: str | None, days: float, write_block: bool, min_count: int) -> None:
+ """Show recurring command fumbles mined from local agent transcripts.
+
+ PATH defaults to the current directory's enclosing repowise repo. The
+ scan is read-only and stays entirely local — commands are read from your
+ own Claude Code transcript directory; nothing leaves this machine.
+ """
+ from repowise.cli.helpers import find_repowise_repo_root
+ from repowise.core.distill.corrections import scan_corrections
+
+ start = Path(path).resolve() if path else Path.cwd()
+ repo_root = find_repowise_repo_root(start) or start
+ report = scan_corrections(repo_root, days=days)
+
+ if not report["rules"]:
+ console.print(
+ f"[yellow]No command corrections found in the last {days:g} days.[/yellow] "
+ "Either the agent isn't fumbling commands here, or no transcripts "
+ "cover this repo."
+ )
+ return
+
+ table = Table(
+ title=f"Command corrections - last {days:g} days",
+ border_style="dim",
+ caption=(
+ "Fail->fixed pairs mined from local Claude Code transcripts; "
+ "nothing leaves this machine."
+ ),
+ )
+ table.add_column("Count", justify="right")
+ table.add_column("Kind", style="cyan")
+ table.add_column("Wrong", overflow="fold", max_width=40)
+ table.add_column("Fixed", overflow="fold", max_width=40)
+ for rule in report["rules"]:
+ fixed = rule["fixed"]
+ if rule.get("hint"):
+ fixed += f"\n[dim]{rule['hint']}[/dim]"
+ table.add_row(
+ f"{rule['count']}x",
+ _KIND_LABELS.get(rule["kind"], rule["kind"]),
+ rule["wrong"],
+ fixed,
+ )
+
+ console.print()
+ console.print(table)
+ example = report["rules"][0]["example"]
+ console.print(f" [dim]e.g. {example['failed'][:100]}[/dim]")
+ console.print(f" [dim] -> {example['fixed'][:100]}[/dim]")
+
+ if write_block:
+ _write_managed_blocks(repo_root, report["rules"], min_count)
+ else:
+ qualifying = sum(1 for r in report["rules"] if r["count"] >= min_count)
+ if qualifying:
+ console.print(
+ f" [dim]repowise corrections --write adds the top {qualifying} "
+ "rule(s) to CLAUDE.md/AGENTS.md as agent guidance.[/dim]"
+ )
+ console.print()
+
+
+def _write_managed_blocks(repo_root: Path, rules: list[dict], min_count: int) -> None:
+ """Upsert the managed block into CLAUDE.md/AGENTS.md (or prune it)."""
+ from repowise.core.distill.corrections import (
+ render_corrections_block,
+ update_corrections_block,
+ )
+
+ block = render_corrections_block(rules, min_count=min_count)
+ claude_md = repo_root / ".claude" / "CLAUDE.md"
+ agents_md = repo_root / "AGENTS.md"
+
+ # CLAUDE.md is created when absent (the primary agent surface); AGENTS.md
+ # is only updated when the user already maintains one.
+ targets = [claude_md] + ([agents_md] if agents_md.exists() else [])
+ if block is None:
+ console.print(
+ f" [yellow]No rule seen {min_count}+ times - managed block "
+ "removed where present.[/yellow]"
+ )
+ for target in targets:
+ try:
+ changed = update_corrections_block(target, block)
+ except OSError:
+ console.print(f" [yellow]Could not update {target}[/yellow]")
+ continue
+ if changed:
+ verb = "updated" if block is not None else "removed"
+ console.print(f" [green]✓[/green] Known-corrections block {verb} ({target})")
diff --git a/packages/cli/src/repowise/cli/commands/doctor_cmd.py b/packages/cli/src/repowise/cli/commands/doctor_cmd.py
index ce5a9779d..6361dcadf 100644
--- a/packages/cli/src/repowise/cli/commands/doctor_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/doctor_cmd.py
@@ -512,12 +512,19 @@ def _distill_checks(repo_path: _DoctorPath) -> list[tuple[str, str, str]]:
# Rewrite hook (advisory: strictly opt-in).
try:
from repowise.cli.agent_adapters.claude_code import ClaudeCodeAdapter
-
- installed = ClaudeCodeAdapter().rewrite_hook_installed()
- if installed:
+ from repowise.cli.agent_adapters.codex import CodexAdapter
+
+ surfaces = [("claude-code", ClaudeCodeAdapter())]
+ codex = CodexAdapter()
+ if codex.detect():
+ surfaces.append(("codex", codex))
+ installed_names = [name for name, a in surfaces if a.rewrite_hook_installed()]
+ if installed_names:
commands_cfg = distill_cfg.get("commands") if isinstance(distill_cfg, dict) else None
opted_out = isinstance(commands_cfg, dict) and commands_cfg.get("enabled") is False
- detail = "installed (this repo opted out)" if opted_out else "installed"
+ detail = ", ".join(installed_names)
+ detail += " (this repo opted out)" if opted_out else ""
+ detail = f"installed: {detail}"
else:
detail = "not installed (opt-in: repowise hook rewrite install)"
checks.append(_check("Distill rewrite hook", True, detail))
diff --git a/packages/cli/src/repowise/cli/commands/hook_cmd.py b/packages/cli/src/repowise/cli/commands/hook_cmd.py
index 8d1135c6a..28564c052 100644
--- a/packages/cli/src/repowise/cli/commands/hook_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/hook_cmd.py
@@ -98,16 +98,54 @@ def hook_uninstall(path: str | None, workspace: bool, no_workspace: bool) -> Non
@hook_group.group("rewrite")
def rewrite_group() -> None:
- """Manage the distill command-rewrite hook (Claude Code PreToolUse).
+ """Manage the distill command-rewrite hook (Claude Code + Codex).
When installed, noisy commands an agent runs (tests, builds, git
status/log/diff, searches, listings) are rewritten to
``repowise distill <command>`` — pending your approval — so the agent
sees a compact, errors-first rendering. Raw output stays recoverable
via ``repowise expand <ref>``.
+
+ Claude Code gets the full ask-posture rewrite. Codex hooks cannot show
+ a rewritten command for approval, so there rewrites apply only to
+ command families set to ``permission: allow``; every Codex install also
+ maintains an AGENTS.md awareness section that works without any hook.
"""
+def _target_repo_paths(target) -> list:
+ """The repo paths a hook subcommand should act on (repowise repos only)."""
+ if target.is_workspace:
+ assert target.ws_root is not None and target.ws_config is not None
+ return [
+ (target.ws_root / entry.path).resolve()
+ for entry in target.ws_config.repos
+ if ((target.ws_root / entry.path).resolve() / ".repowise").is_dir()
+ ]
+ assert target.repo_path is not None
+ return [target.repo_path] if (target.repo_path / ".repowise").is_dir() else []
+
+
+def _codex_capability_note(version, supports) -> str:
+ """One honest line about what the local Codex build can actually do."""
+ from repowise.cli.editor_integrations.codex_config import CODEX_REWRITE_MIN_VERSION
+
+ min_str = ".".join(str(v) for v in CODEX_REWRITE_MIN_VERSION)
+ if supports is None:
+ return "Codex CLI not found on PATH — rewrite support unknown"
+ ver_str = ".".join(str(v) for v in version)
+ if not supports:
+ return (
+ f"Codex {ver_str} cannot rewrite commands (needs >= {min_str}); "
+ "AGENTS.md awareness section only"
+ )
+ return (
+ f"Codex {ver_str}: rewrites apply only to families set to "
+ "`permission: allow` — Codex cannot ask-with-rewrite, `ask` families "
+ "pass through"
+ )
+
+
@rewrite_group.command("install")
@click.argument("path", required=False, default=None)
@click.option(
@@ -198,20 +236,114 @@ def rewrite_install(
if (target.repo_path / ".repowise").is_dir():
save_distill_commands_enabled(target.repo_path, enabled=True)
+ _install_codex_surfaces(target)
+
+
+def _install_codex_surfaces(target) -> None:
+ """Codex side of ``rewrite install``: version-gated hook + awareness section.
+
+ Skipped silently when the user doesn't use Codex (no ``~/.codex``). The
+ hooks.json entry installs only on a build that honors ``updatedInput``
+ rewrites; the AGENTS.md awareness section installs regardless, because it
+ needs no hook support at all.
+ """
+ from repowise.cli.agent_adapters.codex import CodexAdapter
+
+ codex = CodexAdapter()
+ if not codex.detect():
+ return
+
+ from repowise.cli.editor_integrations.codex_config import (
+ codex_cli_version,
+ codex_supports_rewrite,
+ install_agents_md_distill_section,
+ )
+
+ version = codex_cli_version()
+ supports = codex_supports_rewrite(version)
+ if supports:
+ codex_path = codex.install_rewrite_hook()
+ if codex_path:
+ console.print(f"Codex rewrite hook: [green]installed[/green] ({codex_path})")
+ console.print(f" [dim]{_codex_capability_note(version, supports)}.[/dim]")
+ console.print(
+ " [dim]Codex requires new hooks to be reviewed — run /hooks "
+ "inside Codex to trust it.[/dim]"
+ )
+ else:
+ console.print("Codex rewrite hook: [red]install failed[/red]")
+ else:
+ console.print(
+ f"Codex rewrite hook: [yellow]skipped[/yellow] — "
+ f"{_codex_capability_note(version, supports)}."
+ )
+
+ for repo_path in _target_repo_paths(target):
+ agents_path = install_agents_md_distill_section(repo_path)
+ if agents_path:
+ console.print(f" [green]✓[/green] AGENTS.md distill section ({agents_path})")
+ else:
+ console.print(f" [yellow]AGENTS.md distill section failed ({repo_path})[/yellow]")
+
@rewrite_group.command("uninstall")
-def rewrite_uninstall() -> None:
- """Remove the rewrite hook from ~/.claude/settings.json."""
[email protected]("path", required=False, default=None)
+ "--workspace",
+ "-w",
+ is_flag=True,
+ default=False,
+ help="Force workspace mode (remove the AGENTS.md section from every repo).",
+)
+ "--no-workspace",
+ is_flag=True,
+ default=False,
+ help="Force single-repo mode even when invoked from a workspace.",
+)
+def rewrite_uninstall(path: str | None, workspace: bool, no_workspace: bool) -> None:
+ """Remove the rewrite hooks and the AGENTS.md awareness section."""
from repowise.cli.agent_adapters.claude_code import ClaudeCodeAdapter
+ from repowise.cli.agent_adapters.codex import CodexAdapter
removed = ClaudeCodeAdapter().uninstall_rewrite_hook()
console.print(f"Rewrite hook: {'[green]removed[/green]' if removed else 'not installed'}")
+ codex = CodexAdapter()
+ if codex.detect():
+ codex_removed = codex.uninstall_rewrite_hook()
+ console.print(
+ f"Codex rewrite hook: {'[green]removed[/green]' if codex_removed else 'not installed'}"
+ )
+ from repowise.cli.editor_integrations.codex_config import (
+ remove_agents_md_distill_section,
+ )
+
+ target = _hook_target(path, workspace, no_workspace)
+ for repo_path in _target_repo_paths(target):
+ if remove_agents_md_distill_section(repo_path):
+ console.print(f" [green]✓[/green] AGENTS.md distill section removed ({repo_path})")
+
@rewrite_group.command("status")
-def rewrite_status() -> None:
- """Check whether the rewrite hook is installed."""
[email protected]("path", required=False, default=None)
+ "--workspace",
+ "-w",
+ is_flag=True,
+ default=False,
+ help="Force workspace mode (report the AGENTS.md section for every repo).",
+)
+ "--no-workspace",
+ is_flag=True,
+ default=False,
+ help="Force single-repo mode even when invoked from a workspace.",
+)
+def rewrite_status(path: str | None, workspace: bool, no_workspace: bool) -> None:
+ """Check the rewrite hooks and what each agent can actually do."""
from repowise.cli.agent_adapters.claude_code import ClaudeCodeAdapter
+ from repowise.cli.agent_adapters.codex import CodexAdapter
installed = ClaudeCodeAdapter().rewrite_hook_installed()
icon = "[green]✓[/green]" if installed else "[dim]✗[/dim]"
@@ -219,6 +351,33 @@ def rewrite_status() -> None:
f" {icon} claude-code rewrite hook: {'installed' if installed else 'not installed'}"
)
+ codex = CodexAdapter()
+ if not codex.detect():
+ console.print(" [dim]✗[/dim] codex: not detected (no ~/.codex)")
+ return
+
+ from repowise.cli.editor_integrations.codex_config import (
+ agents_md_distill_section_installed,
+ codex_cli_version,
+ codex_supports_rewrite,
+ )
+
+ version = codex_cli_version()
+ supports = codex_supports_rewrite(version)
+ codex_installed = codex.rewrite_hook_installed()
+ icon = "[green]✓[/green]" if codex_installed else "[dim]✗[/dim]"
+ console.print(
+ f" {icon} codex rewrite hook: {'installed' if codex_installed else 'not installed'}"
+ )
+ console.print(f" [dim]{_codex_capability_note(version, supports)}[/dim]")
+
+ target = _hook_target(path, workspace, no_workspace)
+ for repo_path in _target_repo_paths(target):
+ section = agents_md_distill_section_installed(repo_path)
+ icon = "[green]✓[/green]" if section else "[dim]✗[/dim]"
+ state = "installed" if section else "not installed"
+ console.print(f" {icon} AGENTS.md distill section: {state} ({repo_path})")
+
@hook_group.command("status")
@click.argument("path", required=False, default=None)
diff --git a/packages/cli/src/repowise/cli/editor_integrations/codex_config.py b/packages/cli/src/repowise/cli/editor_integrations/codex_config.py
new file mode 100644
index 000000000..3718b5078
--- /dev/null
+++ b/packages/cli/src/repowise/cli/editor_integrations/codex_config.py
@@ -0,0 +1,283 @@
+"""Codex CLI rewrite-hook config and the AGENTS.md distill awareness section.
+
+Two surfaces, both managed here so ``hook rewrite install/uninstall/status``
+has one place to look:
+
+ - **User-level hooks.json** (``~/.codex/hooks.json``): the opt-in distill
+ PreToolUse rewrite entry — one install covers every repo, per-repo
+ behavior stays gated by ``distill.commands`` in ``.repowise/config.yaml``
+ (the hook script checks it at decide time). Install is version-gated:
+ Codex applies a PreToolUse ``updatedInput`` rewrite only from
+ :data:`CODEX_REWRITE_MIN_VERSION`; older builds reject it at runtime, so
+ installing there would break every shell call.
+ - **AGENTS.md awareness section** (repo root, ``REPOWISE_DISTILL``
+ markers): teaches the agent to run ``repowise distill <cmd>`` voluntarily
+ and to ``repowise expand`` markers instead of re-running commands. Works
+ with zero hook support, on any Codex version. Strictly marker-managed —
+ install/uninstall round-trips user content byte-for-byte.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+import subprocess
+from pathlib import Path
+
+#: First Codex release whose PreToolUse hooks honor an ``updatedInput``
+#: command rewrite; earlier builds report it as an unsupported hook output.
+CODEX_REWRITE_MIN_VERSION: tuple[int, int] = (0, 137)
+
+_REWRITE_HOOK_COMMAND = "repowise-rewrite"
+
+_REWRITE_HOOK_ENTRY = {
+ "matcher": "Bash",
+ "hooks": [
+ {
+ "type": "command",
+ "command": f"{_REWRITE_HOOK_COMMAND} --agent codex",
+ "timeout": 5,
+ "statusMessage": "Distilling command output...",
+ }
+ ],
+}
+
+
+def _codex_hooks_path() -> Path:
+ """The user-level Codex hooks file (~/.codex/hooks.json)."""
+ return Path.home() / ".codex" / "hooks.json"
+
+
+# ---------------------------------------------------------------------------
+# Version gate
+# ---------------------------------------------------------------------------
+
+
+def codex_cli_version() -> tuple[int, ...] | None:
+ """Parse ``codex --version`` into a tuple, or None when unavailable."""
+ from repowise.cli.mcp_config import resolve_codex_executable
+
+ codex_cmd = resolve_codex_executable()
+ if not codex_cmd:
+ return None
+ try:
+ result = subprocess.run(
+ [codex_cmd, "--version"],
+ capture_output=True,
+ text=True,
+ timeout=5,
+ )
+ except (OSError, subprocess.TimeoutExpired):
+ return None
+ if result.returncode != 0:
+ return None
+ match = re.search(r"(\d+(?:\.\d+)+)", result.stdout or "")
+ if not match:
+ return None
+ return tuple(int(part) for part in match.group(1).split("."))
+
+
+def codex_supports_rewrite(version: tuple[int, ...] | None = None) -> bool | None:
+ """True/False when the Codex version is known; None when it isn't."""
+ resolved = version if version is not None else codex_cli_version()
+ if resolved is None:
+ return None
+ return resolved >= CODEX_REWRITE_MIN_VERSION
+
+
+# ---------------------------------------------------------------------------
+# hooks.json install / uninstall — same merge discipline as the Claude Code
+# settings.json writer: idempotent, additive, user hooks untouched.
+# ---------------------------------------------------------------------------
+
+
+def install_codex_rewrite_hook() -> Path | None:
+ """Register the distill PreToolUse rewrite entry in ~/.codex/hooks.json."""
+ from repowise.cli.mcp_config import load_existing_config
+
+ hooks_path = _codex_hooks_path()
+ try:
+ if hooks_path.exists():
+ existing = load_existing_config(hooks_path)
+ else:
+ hooks_path.parent.mkdir(parents=True, exist_ok=True)
+ existing = {}
+
+ hooks = existing.setdefault("hooks", {})
+ pre_hooks = hooks.setdefault("PreToolUse", [])
+ if not _has_rewrite_hook(pre_hooks):
+ pre_hooks.append(json.loads(json.dumps(_REWRITE_HOOK_ENTRY)))
+ hooks_path.write_text(json.dumps(existing, indent=2) + "\n", encoding="utf-8")
+ return hooks_path
+ except Exception:
+ # OSError on write, ClickException from load_existing_config on a
+ # malformed existing file — either way, install reports failure.
+ return None
+
+
+def uninstall_codex_rewrite_hook() -> bool:
+ """Remove the distill rewrite entry; True when something was removed."""
+ from repowise.cli.mcp_config import load_existing_config
+
+ hooks_path = _codex_hooks_path()
+ if not hooks_path.exists():
+ return False
+ try:
+ existing = load_existing_config(hooks_path)
+ except Exception:
+ return False
+
+ hooks = existing.get("hooks")
+ if not isinstance(hooks, dict):
+ return False
+ pre_hooks = hooks.get("PreToolUse")
+ if not isinstance(pre_hooks, list):
+ return False
+
+ changed = False
+ for entry in list(pre_hooks):
+ kept = [h for h in entry.get("hooks", []) if not _is_rewrite_hook(h)]
+ if len(kept) != len(entry.get("hooks", [])):
+ changed = True
+ if kept:
+ entry["hooks"] = kept
+ else:
+ pre_hooks.remove(entry)
+ if not changed:
+ return False
+ if not pre_hooks:
+ hooks.pop("PreToolUse", None)
+
+ try:
+ hooks_path.write_text(json.dumps(existing, indent=2) + "\n", encoding="utf-8")
+ except OSError:
+ return False
+ return True
+
+
+def codex_rewrite_hook_installed() -> bool:
+ """True when the distill rewrite entry is registered in hooks.json."""
+ from repowise.cli.mcp_config import load_existing_config
+
+ hooks_path = _codex_hooks_path()
+ if not hooks_path.exists():
+ return False
+ try:
+ existing = load_existing_config(hooks_path)
+ except Exception:
+ return False
+ hooks = existing.get("hooks")
+ if not isinstance(hooks, dict):
+ return False
+ pre_hooks = hooks.get("PreToolUse")
+ return isinstance(pre_hooks, list) and _has_rewrite_hook(pre_hooks)
+
+
+def _is_rewrite_hook(hook: dict) -> bool:
+ return _REWRITE_HOOK_COMMAND in hook.get("command", "")
+
+
+def _has_rewrite_hook(hook_list: list) -> bool:
+ return any(_is_rewrite_hook(h) for entry in hook_list for h in entry.get("hooks", []))
+
+
+# ---------------------------------------------------------------------------
+# AGENTS.md awareness section — marker-managed, mirrors the CLAUDE.md
+# "Output Distillation" block.
+# ---------------------------------------------------------------------------
+
+_DISTILL_MARKER_START = (
+ "<!-- REPOWISE_DISTILL:START — Do not edit below this line. Auto-generated by Repowise. -->"
+)
+_DISTILL_MARKER_END = "<!-- REPOWISE_DISTILL:END -->"
+
+_DISTILL_SECTION_HEADING = "### Output Distillation"
+
+_DISTILL_SECTION = f"""{_DISTILL_SECTION_HEADING}
+
+- Prefer `repowise distill <cmd>` for noisy commands — test runs, builds, `git status`/`log`/`diff`, searches, file listings. It runs the command unchanged (exit code preserved) and prints a compact, errors-first rendering; every error line survives.
+- Output may contain a marker like `[repowise#a1b2c3d4e5f6: 230 lines omitted (~6.1k tokens); restore: repowise expand a1b2c3d4e5f6]`. The omitted content is fully preserved — run `repowise expand <ref>` to retrieve it, or `repowise expand <ref> -q <regex>` for just the matching lines.
+- Never re-run a command to see omitted output; expand the marker instead.
+- For structure-level questions about a large indexed file ("what's in here", "which function handles X"), `get_context(["path"], include=["skeleton"])` returns the file with bodies elided — every signature plus the bodies of the most central symbols — at a fraction of the cost of a full Read."""
+
+_NEW_FILE_PLACEHOLDER = (
+ "# AGENTS.md\n\n"
+ "<!-- Add your project instructions above or below the Repowise section. "
+ "Repowise only updates the managed section between markers. -->\n"
+)
+
+
+def _agents_md_path(repo_path: Path) -> Path:
+ return Path(repo_path) / "AGENTS.md"
+
+
+def install_agents_md_distill_section(repo_path: Path) -> Path | None:
+ """Ensure AGENTS.md carries the distill awareness section.
+
+ Idempotent: an existing marker block is refreshed in place; a file that
+ already teaches distillation elsewhere (e.g. a future indexed-template
+ section) is left untouched; otherwise the block is appended. Returns the
+ AGENTS.md path, or None on write failure.
+ """
+ target = _agents_md_path(repo_path)
+ wrapped = f"{_DISTILL_MARKER_START}\n{_DISTILL_SECTION}\n{_DISTILL_MARKER_END}"
+ try:
+ if not target.exists():
+ content = f"{_NEW_FILE_PLACEHOLDER}\n{wrapped}\n"
+ else:
+ existing = target.read_text(encoding="utf-8")
+ if _DISTILL_MARKER_START in existing:
+ pattern = re.escape(_DISTILL_MARKER_START) + r".*?" + re.escape(_DISTILL_MARKER_END)
+ content = re.sub(pattern, wrapped, existing, flags=re.DOTALL)
+ elif _DISTILL_SECTION_HEADING in existing:
+ return target # already taught elsewhere in the file
+ else:
+ content = existing.rstrip() + "\n\n" + wrapped + "\n"
+ target.write_text(content, encoding="utf-8", newline="\n")
+ return target
+ except OSError:
+ return None
+
+
+def remove_agents_md_distill_section(repo_path: Path) -> bool:
+ """Remove the marker-managed section; True when something was removed.
+
+ If nothing but the install-time placeholder remains afterwards, the file
+ is deleted entirely so install→uninstall round-trips to "no AGENTS.md".
+ User content is never touched.
+ """
+ target = _agents_md_path(repo_path)
+ if not target.exists():
+ return False
+ try:
+ existing = target.read_text(encoding="utf-8")
+ except OSError:
+ return False
+ if _DISTILL_MARKER_START not in existing:
+ return False
+
+ pattern = (
+ r"\n*" + re.escape(_DISTILL_MARKER_START) + r".*?" + re.escape(_DISTILL_MARKER_END) + r"\n?"
+ )
+ remaining = re.sub(pattern, "", existing, flags=re.DOTALL)
+ if remaining and not remaining.endswith("\n"):
+ # Install rstrips before appending the block; restore the trailing
+ # newline that strip consumed so removal is a true inverse.
+ remaining += "\n"
+ try:
+ if remaining.strip() in ("", _NEW_FILE_PLACEHOLDER.strip()):
+ target.unlink()
+ else:
+ target.write_text(remaining, encoding="utf-8", newline="\n")
+ except OSError:
+ return False
+ return True
+
+
+def agents_md_distill_section_installed(repo_path: Path) -> bool:
+ """True when AGENTS.md carries the marker-managed awareness section."""
+ target = _agents_md_path(repo_path)
+ try:
+ return target.exists() and _DISTILL_MARKER_START in target.read_text(encoding="utf-8")
+ except OSError:
+ return False
diff --git a/packages/cli/src/repowise/cli/main.py b/packages/cli/src/repowise/cli/main.py
index cd60db17a..228a2dbc2 100644
--- a/packages/cli/src/repowise/cli/main.py
+++ b/packages/cli/src/repowise/cli/main.py
@@ -7,6 +7,7 @@ import click
from repowise.cli import __version__
from repowise.cli.commands.augment_cmd import augment_command
from repowise.cli.commands.claude_md_cmd import claude_md_command
+from repowise.cli.commands.corrections_cmd import corrections_command
from repowise.cli.commands.costs_cmd import costs_command
from repowise.cli.commands.dead_code_cmd import dead_code_command
from repowise.cli.commands.decision_cmd import decision_group
@@ -67,6 +68,7 @@ register_command(search_command)
register_command(distill_command)
register_command(expand_command)
register_command(saved_command)
+register_command(corrections_command)
register_command(export_command)
register_command(hook_group)
register_command(status_command)
diff --git a/packages/cli/src/repowise/cli/rewrite_hook.py b/packages/cli/src/repowise/cli/rewrite_hook.py
index e6fb70faf..1a7767d69 100644
--- a/packages/cli/src/repowise/cli/rewrite_hook.py
+++ b/packages/cli/src/repowise/cli/rewrite_hook.py
@@ -281,8 +281,14 @@ _PS_ALIAS_TOKENS = frozenset(
)
-def decide(command: str, cwd: str, shell: str = "posix") -> RewriteResult | None:
- """Full decision: classification + bailouts + per-repo permission config."""
+def decide(
+ command: str, cwd: str, shell: str = "posix", source: str | None = None
+) -> RewriteResult | None:
+ """Full decision: classification + bailouts + per-repo permission config.
+
+ *source* overrides the ledger tag for agents with their own surface
+ (``hook-codex``); by default it derives from the shell dialect.
+ """
family = classify(command)
if family is None:
return None
@@ -309,7 +315,8 @@ def decide(command: str, cwd: str, shell: str = "posix") -> RewriteResult | None
# The --source tag lands in the savings ledger so `repowise saved
# --by source` can tell hook surfaces apart from direct CLI use.
- source = "hook-powershell" if shell == "powershell" else "hook-bash"
+ if source is None:
+ source = "hook-powershell" if shell == "powershell" else "hook-bash"
return RewriteResult(
command=f"repowise distill --source {source} {command.strip()}",
permission=permission,
@@ -320,15 +327,39 @@ def decide(command: str, cwd: str, shell: str = "posix") -> RewriteResult | None
)
+def _select_adapter(argv: list[str]):
+ """Pick the adapter from ``--agent <name>`` argv; Claude Code by default.
+
+ Each agent's hook config registers its own flavor (Codex hooks run
+ ``repowise-rewrite --agent codex``) — the payloads are near-identical
+ JSON, so argv is the only reliable discriminator.
+ """
+ agent = ""
+ for i, arg in enumerate(argv):
+ if arg == "--agent" and i + 1 < len(argv):
+ agent = argv[i + 1]
+ elif arg.startswith("--agent="):
+ agent = arg.split("=", 1)[1]
+ if agent == "codex":
+ from repowise.cli.agent_adapters.codex import CodexAdapter
+
+ return CodexAdapter()
+ from repowise.cli.agent_adapters.claude_code import ClaudeCodeAdapter
+
+ return ClaudeCodeAdapter()
+
+
def main() -> None:
try:
- from repowise.cli.agent_adapters.claude_code import ClaudeCodeAdapter
-
- adapter = ClaudeCodeAdapter()
+ adapter = _select_adapter(sys.argv[1:])
request = adapter.parse_hook_payload(sys.stdin.read())
if request is not None:
- result = decide(request.command, request.cwd, request.shell)
- if result is not None:
+ source = "hook-codex" if adapter.name == "codex" else None
+ result = decide(request.command, request.cwd, request.shell, source=source)
+ # An agent that can't honor the decided posture gets a
+ # passthrough, never a silently escalated rewrite (Codex has no
+ # ask-with-mutation — only families set to `allow` rewrite).
+ if result is not None and result.permission in adapter.rewrite_permissions:
sys.stdout.write(adapter.render_response(result))
sys.stdout.flush()
except (SystemExit, KeyboardInterrupt):
diff --git a/packages/core/src/repowise/core/distill/corrections.py b/packages/core/src/repowise/core/distill/corrections.py
new file mode 100644
index 000000000..d6def7cf1
--- /dev/null
+++ b/packages/core/src/repowise/core/distill/corrections.py
@@ -0,0 +1,493 @@
+"""Correction mining — fail→fixed command pairs from agent transcripts.
+
+Scans the same Claude Code transcript directory as the missed-savings scan
+(:mod:`repowise.core.distill.missed`) for shell commands that failed and were
+then re-run successfully in a corrected form — the agent fumbling a flag, a
+path, or the tool itself (the recurring bare ``python`` vs
+``.venv\\Scripts\\python.exe`` case). The aggregated rules feed a report and,
+strictly opt-in, a short managed block in CLAUDE.md/AGENTS.md so the next
+session doesn't repeat the fumble.
+
+Failure detection is grounded in real transcript payloads, not guesswork:
+a failed shell call's ``toolUseResult`` is a **string** starting with
+``Error: Exit code N`` (and the tool_result block carries ``is_error``);
+a successful call's is a dict with ``stdout``/``stderr``. Harness-level
+errors — cancelled parallel calls, user rejections, permission denials —
+are strings too but are *not* command failures and are skipped entirely.
+
+Read-only and best-effort by the same contract as the missed scan: malformed
+lines, unreadable files, or an absent transcript directory produce an empty
+report, never an error. Everything stays local.
+"""
+
+from __future__ import annotations
+
+import json
+import re
+import time
+from pathlib import Path
+from typing import Any
+
+from repowise.core.distill.missed import _parse_ts, transcript_dir_for
+
+#: Default scan window, in days. Corrections are rarer than missed savings,
+#: so the default window is wider.
+DEFAULT_WINDOW_DAYS = 30.0
+
+#: How many subsequent shell commands to search for the corrected re-run.
+_LOOKAHEAD = 6
+
+#: Minimum occurrences for a rule to make the managed --write block.
+WRITE_MIN_COUNT = 2
+
+#: Managed-block budget: most-frequent rules first, hard-capped.
+WRITE_MAX_RULES = 10
+
+_SHELL_TOOLS = ("Bash", "PowerShell")
+
+#: The one true command-failure shape in real transcripts. Everything else
+#: stringly (cancellations, rejections, permission denials, harness errors)
+#: is not a command failure.
+_EXIT_CODE_RE = re.compile(r"^Error: Exit code (\d+)")
+
+#: Leading segments that position the shell rather than run the command:
+#: directory changes, env assignments, console setup, the PS call operator.
+_PREAMBLE_RES = (
+ re.compile(r"^\s*(?:Set-Location|cd|pushd)\s+(?:\"[^\"]*\"|'[^']*'|[^;&|]+?)\s*(?:;|&&)\s*"),
+ re.compile(r"^\s*\$env:\w+\s*=\s*(?:\"[^\"]*\"|'[^']*'|[^;]+?)\s*;\s*"),
+ re.compile(r"^\s*\$\w+\s*=\s*(?:\"[^\"]*\"|'[^']*'|[^;]+?)\s*;\s*"),
+ re.compile(r"^\s*\[[^\]]+\]::[^;]+;\s*"),
+ re.compile(r"^\s*\w+=\S+\s+"),
+ re.compile(r"^\s*&\s+"),
+)
+
+_FLAG_ERROR_RE = re.compile(
+ r"unrecognized (?:option|argument)|unknown (?:option|flag)|no such option"
+ r"|unexpected argument|invalid option|is not a valid option",
+ re.IGNORECASE,
+)
+_PATH_ERROR_RE = re.compile(
+ r"no such file or directory|cannot find (?:path|the path)|does not exist"
+ r"|couldn't find|path not found|(?:file|directory) not found|not found:",
+ re.IGNORECASE,
+)
+
+#: Chaining/grouping syntax after which a token-level diff stops meaning
+#: anything; classification only ever looks at the first command segment.
+_SEGMENT_SPLIT_RE = re.compile(r"\s*(?:&&|\|\||[|;])\s*")
+
+
+def strip_preamble(command: str) -> str:
+ """Drop leading cd/env/console-setup segments so the real command leads."""
+ cmd = command.strip()
+ for _ in range(8):
+ previous = cmd
+ for pattern in _PREAMBLE_RES:
+ cmd = pattern.sub("", cmd, count=1)
+ if cmd == previous:
+ break
+ return cmd
+
+
+def _basename(token: str) -> str:
+ """Lowercased executable identity of a token: path and .exe stripped."""
+ token = token.strip("\"'")
+ token = token.replace("\\", "/").rstrip("/").rsplit("/", 1)[-1]
+ if token.lower().endswith(".exe"):
+ token = token[:-4]
+ return token.lower()
+
+
+def command_anchor(command: str) -> str:
+ """The stable identity token two variants of "the same command" share.
+
+ Path- and extension-insensitive, so bare ``python`` and
+ ``.venv\\Scripts\\python.exe`` anchor identically; ``python -m <mod>``
+ anchors on the module so a runner-form change still pairs.
+ """
+ tokens = strip_preamble(command).split()
+ if not tokens:
+ return ""
+ tool = _basename(tokens[0])
+ if tool in ("python", "python3", "py") and len(tokens) >= 3 and tokens[1] == "-m":
+ return _basename(tokens[2])
+ return tool
+
+
+def empty_report(days: float = DEFAULT_WINDOW_DAYS) -> dict[str, Any]:
+ return {"rules": [], "pairs": 0, "window_days": days}
+
+
+def scan_corrections(
+ repo_root: Path,
+ *,
+ days: float = DEFAULT_WINDOW_DAYS,
+ now: float | None = None,
+ projects_root: Path | None = None,
+) -> dict[str, Any]:
+ """Mine fail→fixed pairs from recent transcripts into aggregated rules.
+
+ Returns ``{"rules": [...], "pairs": N, "window_days": D}`` where each
+ rule has ``kind``/``wrong``/``fixed``/``count``/``example`` (and
+ optionally ``hint``), sorted most-frequent first. Any failure degrades
+ to an empty report.
+ """
+ try:
+ return _scan(Path(repo_root).resolve(), days, now, projects_root)
+ except Exception:
+ return empty_report(days)
+
+
+def _scan(
+ repo_root: Path, days: float, now: float | None, projects_root: Path | None
+) -> dict[str, Any]:
+ transcripts = transcript_dir_for(repo_root, projects_root)
+ report = empty_report(days)
+ if not transcripts.is_dir():
+ return report
+
+ cutoff = (now if now is not None else time.time()) - days * 86400.0
+ repo_prefix = str(repo_root).lower().rstrip("\\/")
+
+ rules: dict[tuple[str, str, str], dict[str, Any]] = {}
+ pairs = 0
+ for path in sorted(transcripts.glob("*.jsonl")):
+ try:
+ if path.stat().st_mtime < cutoff:
+ continue
+ events = _session_events(path, cutoff, repo_prefix)
+ except OSError:
+ continue
+ pairs += _pair_events(events, rules)
+
+ ordered = sorted(rules.values(), key=lambda r: (-r["count"], r["kind"]))
+ _attach_index_hints(repo_root, ordered)
+ report["rules"] = ordered
+ report["pairs"] = pairs
+ return report
+
+
+# ---------------------------------------------------------------------------
+# Transcript walking — one session file to an ordered list of shell events
+# ---------------------------------------------------------------------------
+
+
+def _session_events(path: Path, cutoff: float, repo_prefix: str) -> list[dict[str, Any]]:
+ """Ordered shell events: ``{"command", "failed", "error"}`` per call."""
+ events: list[dict[str, Any]] = []
+ pending: dict[str, str] = {}
+ with path.open(encoding="utf-8", errors="replace") as fh:
+ for raw in fh:
+ if '"tool_use"' in raw and '"command"' in raw:
+ _collect_tool_use(raw, cutoff, repo_prefix, pending)
+ elif pending and '"toolUseResult"' in raw:
+ _collect_result(raw, pending, events)
+ return events
+
+
+def _collect_tool_use(raw: str, cutoff: float, repo_prefix: str, pending: dict[str, str]) -> None:
+ try:
+ entry = json.loads(raw)
+ except ValueError:
+ return
+ if entry.get("type") != "assistant":
+ return
+ ts = _parse_ts(entry.get("timestamp"))
+ if ts is not None and ts < cutoff:
+ return
+ cwd = str(entry.get("cwd") or "").lower().rstrip("\\/")
+ if not cwd.startswith(repo_prefix):
+ return
+ content = (entry.get("message") or {}).get("content")
+ if not isinstance(content, list):
+ return
+ for block in content:
+ if not isinstance(block, dict) or block.get("type") != "tool_use":
+ continue
+ if block.get("name") not in _SHELL_TOOLS:
+ continue
+ command = str((block.get("input") or {}).get("command") or "")
+ if not command:
+ continue
+ block_id = block.get("id")
+ if isinstance(block_id, str):
+ pending[block_id] = command
+
+
+def _collect_result(raw: str, pending: dict[str, str], events: list[dict[str, Any]]) -> None:
+ try:
+ entry = json.loads(raw)
+ except ValueError:
+ return
+ content = (entry.get("message") or {}).get("content")
+ if not isinstance(content, list):
+ return
+ block_id = next(
+ (
+ b.get("tool_use_id")
+ for b in content
+ if isinstance(b, dict) and b.get("type") == "tool_result"
+ ),
+ None,
+ )
+ command = pending.pop(block_id, None) if isinstance(block_id, str) else None
+ if command is None:
+ return
+
+ result = entry.get("toolUseResult")
+ if isinstance(result, dict):
+ # Real success shape: stdout/stderr/interrupted dict.
+ events.append({"command": command, "failed": False, "error": ""})
+ elif isinstance(result, str) and _EXIT_CODE_RE.match(result):
+ # Only the exit-code string shape is a command failure; cancellations,
+ # rejections, and harness errors are neither failure nor success.
+ events.append({"command": command, "failed": True, "error": result})
+
+
+# ---------------------------------------------------------------------------
+# Pairing + classification
+# ---------------------------------------------------------------------------
+
+
+def _pair_events(events: list[dict[str, Any]], rules: dict[tuple, dict[str, Any]]) -> int:
+ """Match each failure to the next same-anchor success; aggregate rules."""
+ paired = 0
+ for i, event in enumerate(events):
+ if not event["failed"]:
+ continue
+ anchor = command_anchor(event["command"])
+ if not anchor or anchor in _IGNORED_ANCHORS:
+ continue
+ for later in events[i + 1 : i + 1 + _LOOKAHEAD]:
+ if later["failed"] or command_anchor(later["command"]) != anchor:
+ continue
+ classified = _classify(event["command"], later["command"], event["error"])
+ if classified is None:
+ break # same command succeeded on retry → flaky, not a fumble
+ kind, wrong, fixed = classified
+ rule = rules.setdefault(
+ (kind, wrong.lower(), fixed.lower()),
+ {
+ "kind": kind,
+ "anchor": anchor,
+ "wrong": wrong,
+ "fixed": fixed,
+ "count": 0,
+ "example": {"failed": "", "fixed": ""},
+ },
+ )
+ rule["count"] += 1
+ rule["example"] = {
+ "failed": strip_preamble(event["command"]),
+ "fixed": strip_preamble(later["command"]),
+ }
+ paired += 1
+ break
+ return paired
+
+
+def _first_segment(command: str) -> str:
+ """The first line's first pipeline/chain segment, ``2>&1`` dropped."""
+ segment = _SEGMENT_SPLIT_RE.split(command.split("\n", 1)[0], maxsplit=1)[0]
+ return re.sub(r"\s*2>&1\s*$", "", segment).strip()
+
+
+#: Leads whose "corrections" are just the agent saying something different.
+_IGNORED_ANCHORS = frozenset({"echo", "printf", "write-output", "write-host"})
+
+
+def _path_like(token: str) -> bool:
+ """Heuristic: does *token* plausibly name a file or directory?"""
+ bare = token.strip("\"'")
+ return "/" in bare or "\\" in bare or re.search(r"\.\w{1,4}$", bare) is not None
+
+
+_MISSING_ARG_ERROR_RE = re.compile(
+ r"required|missing|expected (?:an? )?(?:argument|value|path)", re.IGNORECASE
+)
+
+
+def _classify(failed_cmd: str, fixed_cmd: str, error: str) -> tuple[str, str, str] | None:
+ """(kind, wrong, fixed) for a fail→fixed pair, or None when unclassified.
+
+ Deliberately precision-first: a red-green dev loop re-runs the same test
+ command with different selections as code changes — those exit-1 runs
+ are not command fumbles. Apart from the structural wrong-tool case,
+ every kind therefore requires corroborating error text.
+ """
+ failed_full = strip_preamble(failed_cmd)
+ fixed_full = strip_preamble(fixed_cmd)
+ if failed_full == fixed_full:
+ return None
+
+ # Diff only the first command segment: in `pytest bad/path | tail -5`,
+ # the correction lives before the pipe; across `a && b; c` chains a
+ # whole-string token diff produces garbage rules.
+ failed_core = _first_segment(failed_full)
+ fixed_core = _first_segment(fixed_full)
+
+ failed_tokens = failed_core.split()
+ fixed_tokens = fixed_core.split()
+ if not failed_tokens or not fixed_tokens:
+ return None
+
+ # Wrong tool: same anchor (path/exe-insensitive) but a different leading
+ # token — bare `python` fixed to `.venv\Scripts\python.exe` and kin.
+ # Checked before the heredoc bail: the leading token is meaningful even
+ # when the command body is a multi-line script.
+ if failed_tokens[0].lower() != fixed_tokens[0].lower():
+ return ("wrong_tool", failed_tokens[0], fixed_tokens[0])
+
+ # Heredocs and multi-line scripts token-diff into noise — skip outright.
+ if any("<<" in c or "\n" in c for c in (failed_full, fixed_full)):
+ return None
+ if failed_core == fixed_core:
+ return None
+
+ removed = [t for t in failed_tokens[1:] if t not in fixed_tokens]
+ added = [t for t in fixed_tokens[1:] if t not in failed_tokens]
+ if not removed and not added:
+ return None # token-identical modulo order/whitespace → retry
+
+ # Unknown flag: the dropped flag itself must be named by the error —
+ # otherwise a re-run with different options is just a strategy change.
+ removed_flags = [t for t in removed if t.startswith("-")]
+ if removed_flags and _FLAG_ERROR_RE.search(error):
+ named = [f for f in removed_flags if f in error]
+ if named:
+ return ("unknown_flag", " ".join(named), " ".join(added) or "(removed)")
+
+ # Wrong path: the dropped argument must look like a path AND be named
+ # by the error text. Both gates matter — without them, every red-green
+ # loop that re-runs with a different selection becomes a "correction".
+ removed_args = [t for t in removed if not t.startswith("-")]
+ added_args = [t for t in added if not t.startswith("-")]
+ if removed_args and added_args and _PATH_ERROR_RE.search(error):
+ named = [a for a in removed_args if _path_like(a) and a.strip("\"'") in error]
+ if named and any(_path_like(a) for a in added_args):
+ return ("wrong_path", " ".join(named), " ".join(added_args))
+
+ if added and not removed and _MISSING_ARG_ERROR_RE.search(error):
+ return ("missing_arg", "(missing)", " ".join(added))
+
+ return None
+
+
+# ---------------------------------------------------------------------------
+# The managed "Known command corrections" block (strictly opt-in --write)
+# ---------------------------------------------------------------------------
+
+CORRECTIONS_MARKER_START = (
+ "<!-- REPOWISE_CORRECTIONS:START — Do not edit below this line. Auto-generated by Repowise. -->"
+)
+CORRECTIONS_MARKER_END = "<!-- REPOWISE_CORRECTIONS:END -->"
+
+_BLOCK_HEADING = "### Known command corrections"
+
+
+def _clip(text: str, limit: int = 80) -> str:
+ return text if len(text) <= limit else text[: limit - 1] + "…"
+
+
+def rule_line(rule: dict[str, Any]) -> str:
+ """One markdown bullet for a correction rule."""
+ kind = rule["kind"]
+ wrong, fixed = _clip(rule["wrong"]), _clip(rule["fixed"])
+ if kind == "wrong_tool":
+ text = f"Use `{fixed}` instead of `{wrong}`"
+ elif kind == "wrong_path":
+ text = f"`{rule['anchor']}`: use `{fixed}`, not `{wrong}`"
+ if rule.get("hint"):
+ text += f" ({rule['hint']})"
+ elif kind == "unknown_flag":
+ text = f"`{rule['anchor']}` does not support `{wrong}`"
+ else: # missing_arg
+ text = f"`{rule['anchor']}` needs `{fixed}`"
+ return f"- {text} (corrected {rule['count']}x)"
+
+
+def render_corrections_block(
+ rules: list[dict[str, Any]],
+ *,
+ min_count: int = WRITE_MIN_COUNT,
+ max_rules: int = WRITE_MAX_RULES,
+) -> str | None:
+ """The managed block body, or None when no rule clears the threshold."""
+ qualifying = [r for r in rules if r["count"] >= min_count][:max_rules]
+ if not qualifying:
+ return None
+ lines = [_BLOCK_HEADING, ""]
+ lines.extend(rule_line(r) for r in qualifying)
+ return "\n".join(lines)
+
+
+def update_corrections_block(target: Path, block: str | None) -> bool:
+ """Upsert (or, with ``block=None``, remove) the managed block in *target*.
+
+ Only ever touches content between the REPOWISE_CORRECTIONS markers; a
+ file without markers gets the block appended. Returns True when the file
+ changed. Never creates a file just to remove a block.
+ """
+ exists = target.exists()
+ if not exists and block is None:
+ return False
+ existing = target.read_text(encoding="utf-8") if exists else ""
+
+ pattern = re.escape(CORRECTIONS_MARKER_START) + r".*?" + re.escape(CORRECTIONS_MARKER_END)
+ if block is None:
+ removal = r"\n*" + pattern + r"\n?"
+ content = re.sub(removal, "", existing, flags=re.DOTALL)
+ if content == existing:
+ return False
+ if content and not content.endswith("\n"):
+ content += "\n"
+ else:
+ wrapped = f"{CORRECTIONS_MARKER_START}\n{block}\n{CORRECTIONS_MARKER_END}"
+ if CORRECTIONS_MARKER_START in existing:
+ # Lambda replacement: rule text carries Windows paths whose
+ # backslashes re.sub would otherwise parse as escapes.
+ content = re.sub(pattern, lambda _: wrapped, existing, flags=re.DOTALL)
+ elif existing:
+ content = existing.rstrip() + "\n\n" + wrapped + "\n"
+ else:
+ content = wrapped + "\n"
+ if content == existing:
+ return False
+
+ target.parent.mkdir(parents=True, exist_ok=True)
+ target.write_text(content, encoding="utf-8", newline="\n")
+ return True
+
+
+# ---------------------------------------------------------------------------
+# Index-aware hints — where does the corrected path actually live?
+# ---------------------------------------------------------------------------
+
+
+def _attach_index_hints(repo_root: Path, rules: list[dict[str, Any]]) -> None:
+ """Best-effort: annotate wrong_path rules with the indexed location.
+
+ A plain sqlite3 read of the wiki sidecar (no engine, no ORM) — the hint
+ is decoration, so any failure leaves the rules untouched.
+ """
+ targets = [r for r in rules if r["kind"] == "wrong_path"]
+ db_path = repo_root / ".repowise" / "wiki.db"
+ if not targets or not db_path.exists():
+ return
+ try:
+ import sqlite3
+
+ with sqlite3.connect(f"file:{db_path.as_posix()}?mode=ro", uri=True, timeout=1.0) as conn:
+ for rule in targets:
+ first_fixed = rule["fixed"].split()[0] if rule["fixed"].split() else ""
+ basename = first_fixed.replace("\\", "/").rstrip("/").rsplit("/", 1)[-1]
+ if not basename or len(basename) < 3:
+ continue
+ row = conn.execute(
+ "SELECT DISTINCT file_path FROM wiki_symbols WHERE file_path LIKE ? LIMIT 2",
+ (f"%{basename}",),
+ ).fetchall()
+ if len(row) == 1:
+ rule["hint"] = f"indexed at {row[0][0]}"
+ except Exception:
+ return
diff --git a/tests/unit/distill/test_agent_adapters.py b/tests/unit/distill/test_agent_adapters.py
index ca6fbe246..f1a8b3bcb 100644
--- a/tests/unit/distill/test_agent_adapters.py
+++ b/tests/unit/distill/test_agent_adapters.py
@@ -13,7 +13,8 @@ import pytest
from repowise.cli.agent_adapters.base import RewriteResult
from repowise.cli.agent_adapters.claude_code import ClaudeCodeAdapter
-from repowise.cli.editor_integrations import claude_config
+from repowise.cli.agent_adapters.codex import CodexAdapter
+from repowise.cli.editor_integrations import claude_config, codex_config
from repowise.cli.editor_integrations.claude_config import (
claude_code_rewrite_hook_installed,
install_claude_code_hooks,
@@ -21,6 +22,15 @@ from repowise.cli.editor_integrations.claude_config import (
migrate_claude_code_hooks,
uninstall_claude_code_rewrite_hook,
)
+from repowise.cli.editor_integrations.codex_config import (
+ agents_md_distill_section_installed,
+ codex_rewrite_hook_installed,
+ codex_supports_rewrite,
+ install_agents_md_distill_section,
+ install_codex_rewrite_hook,
+ remove_agents_md_distill_section,
+ uninstall_codex_rewrite_hook,
+)
@pytest.fixture
@@ -254,3 +264,223 @@ class TestAdapterDelegation:
assert adapter.rewrite_hook_installed() is True
assert adapter.uninstall_rewrite_hook() is True
assert adapter.rewrite_hook_installed() is False
+
+
+# ---------------------------------------------------------------------------
+# Codex adapter — payload parsing, rendering, posture limits
+# ---------------------------------------------------------------------------
+
+
+def codex_adapter() -> CodexAdapter:
+ return CodexAdapter()
+
+
+class TestCodexParsePayload:
+ def test_valid_bash_payload(self, codex_adapter) -> None:
+ raw = json.dumps(
+ {
+ "hook_event_name": "PreToolUse",
+ "tool_name": "Bash",
+ "tool_input": {"command": "pytest -x"},
+ "cwd": "/repo",
+ }
+ )
+ req = codex_adapter.parse_hook_payload(raw)
+ assert req is not None
+ assert req.command == "pytest -x"
+ assert req.cwd == "/repo"
+ assert req.shell == "posix"
+
+ @pytest.mark.parametrize(
+ "mutation",
+ [
+ {"hook_event_name": "PostToolUse"},
+ {"tool_name": "PowerShell"}, # Codex has no PowerShell tool
+ {"tool_name": "apply_patch"},
+ {"tool_input": {}},
+ {"tool_input": {"command": " "}},
+ {"tool_input": "pytest"},
+ ],
+ )
+ def test_rejects_wrong_shapes(self, codex_adapter, mutation) -> None:
+ payload = {
+ "hook_event_name": "PreToolUse",
+ "tool_name": "Bash",
+ "tool_input": {"command": "pytest"},
+ "cwd": "/repo",
+ }
+ payload.update(mutation)
+ assert codex_adapter.parse_hook_payload(json.dumps(payload)) is None
+
+ @pytest.mark.parametrize("raw", ["", "not json", "[1, 2]", "null"])
+ def test_malformed_input_never_raises(self, codex_adapter, raw) -> None:
+ assert codex_adapter.parse_hook_payload(raw) is None
+
+
+class TestCodexRenderResponse:
+ def test_shape(self, codex_adapter) -> None:
+ result = RewriteResult(
+ command="repowise distill --source hook-codex pytest -x",
+ permission="allow",
+ reason="why",
+ )
+ rendered = json.loads(codex_adapter.render_response(result))
+ assert rendered["hookSpecificOutput"] == {
+ "hookEventName": "PreToolUse",
+ "permissionDecision": "allow",
+ "permissionDecisionReason": "why",
+ "updatedInput": {"command": "repowise distill --source hook-codex pytest -x"},
+ }
+
+
+class TestRewritePermissions:
+ """The capability contract the hook entry point filters on."""
+
+ def test_claude_code_supports_ask_with_mutation(self, adapter) -> None:
+ assert adapter.rewrite_permissions == frozenset({"ask", "allow"})
+
+ def test_codex_is_allow_only(self, codex_adapter) -> None:
+ assert codex_adapter.rewrite_permissions == frozenset({"allow"})
+
+
+class TestCodexVersionGate:
+ @pytest.mark.parametrize(
+ ("version", "expected"),
+ [
+ ((0, 136), False),
+ ((0, 136, 9), False),
+ ((0, 137), True),
+ ((0, 137, 0), True),
+ ((1, 0), True),
+ ],
+ )
+ def test_supports_rewrite_by_version(self, version, expected) -> None:
+ assert codex_supports_rewrite(version) is expected
+
+ def test_unknown_version_is_none(self, monkeypatch) -> None:
+ monkeypatch.setattr(codex_config, "codex_cli_version", lambda: None)
+ assert codex_supports_rewrite() is None
+
+
+# ---------------------------------------------------------------------------
+# ~/.codex/hooks.json install / uninstall
+# ---------------------------------------------------------------------------
+
+
+def codex_hooks_path(tmp_path, monkeypatch):
+ path = tmp_path / ".codex" / "hooks.json"
+ monkeypatch.setattr(codex_config, "_codex_hooks_path", lambda: path)
+ return path
+
+
+def _codex_pre_hooks(hooks_path) -> list:
+ data = json.loads(hooks_path.read_text(encoding="utf-8"))
+ return data.get("hooks", {}).get("PreToolUse", [])
+
+
+class TestCodexHooksInstall:
+ def test_fresh_install(self, codex_hooks_path) -> None:
+ assert install_codex_rewrite_hook() == codex_hooks_path
+ entries = _codex_pre_hooks(codex_hooks_path)
+ assert len(entries) == 1
+ assert entries[0]["matcher"] == "Bash"
+ hook = entries[0]["hooks"][0]
+ assert hook["command"] == "repowise-rewrite --agent codex"
+ assert codex_rewrite_hook_installed() is True
+
+ def test_idempotent(self, codex_hooks_path) -> None:
+ install_codex_rewrite_hook()
+ install_codex_rewrite_hook()
+ assert len(_codex_pre_hooks(codex_hooks_path)) == 1
+
+ def test_preserves_user_hooks(self, codex_hooks_path) -> None:
+ codex_hooks_path.parent.mkdir(parents=True, exist_ok=True)
+ user_entry = {"matcher": "Bash", "hooks": [{"type": "command", "command": "my-validator"}]}
+ codex_hooks_path.write_text(
+ json.dumps({"hooks": {"PreToolUse": [user_entry]}}), encoding="utf-8"
+ )
+ install_codex_rewrite_hook()
+ entries = _codex_pre_hooks(codex_hooks_path)
+ assert len(entries) == 2
+ assert entries[0]["hooks"][0]["command"] == "my-validator"
+
+ def test_uninstall_removes_and_keeps_user_hooks(self, codex_hooks_path) -> None:
+ codex_hooks_path.parent.mkdir(parents=True, exist_ok=True)
+ user_entry = {"matcher": "Bash", "hooks": [{"type": "command", "command": "my-validator"}]}
+ codex_hooks_path.write_text(
+ json.dumps({"hooks": {"PreToolUse": [user_entry]}}), encoding="utf-8"
+ )
+ install_codex_rewrite_hook()
+ assert uninstall_codex_rewrite_hook() is True
+ entries = _codex_pre_hooks(codex_hooks_path)
+ assert len(entries) == 1
+ assert entries[0]["hooks"][0]["command"] == "my-validator"
+ assert codex_rewrite_hook_installed() is False
+
+ def test_uninstall_drops_empty_bucket(self, codex_hooks_path) -> None:
+ install_codex_rewrite_hook()
+ assert uninstall_codex_rewrite_hook() is True
+ data = json.loads(codex_hooks_path.read_text(encoding="utf-8"))
+ assert "PreToolUse" not in data.get("hooks", {})
+
+ def test_uninstall_when_absent(self, codex_hooks_path) -> None:
+ assert uninstall_codex_rewrite_hook() is False
+
+
+# ---------------------------------------------------------------------------
+# AGENTS.md awareness section — install/uninstall must round-trip cleanly
+# ---------------------------------------------------------------------------
+
+
+class TestAgentsMdDistillSection:
+ def test_install_creates_file_and_uninstall_deletes_it(self, tmp_path) -> None:
+ target = install_agents_md_distill_section(tmp_path)
+ assert target == tmp_path / "AGENTS.md"
+ content = target.read_text(encoding="utf-8")
+ assert "REPOWISE_DISTILL:START" in content
+ assert "repowise distill <cmd>" in content
+ assert agents_md_distill_section_installed(tmp_path) is True
+
+ assert remove_agents_md_distill_section(tmp_path) is True
+ assert not target.exists() # nothing but our placeholder remained
+
+ def test_round_trips_user_content_byte_for_byte(self, tmp_path) -> None:
+ original = "# AGENTS.md\n\nMy own rules.\n\n- never push to main\n"
+ (tmp_path / "AGENTS.md").write_text(original, encoding="utf-8", newline="\n")
+
+ install_agents_md_distill_section(tmp_path)
+ appended = (tmp_path / "AGENTS.md").read_text(encoding="utf-8")
+ assert appended.startswith("# AGENTS.md\n\nMy own rules.")
+ assert "### Output Distillation" in appended
+
+ assert remove_agents_md_distill_section(tmp_path) is True
+ assert (tmp_path / "AGENTS.md").read_text(encoding="utf-8") == original
+
+ def test_install_is_idempotent(self, tmp_path) -> None:
+ install_agents_md_distill_section(tmp_path)
+ install_agents_md_distill_section(tmp_path)
+ content = (tmp_path / "AGENTS.md").read_text(encoding="utf-8")
+ assert content.count("REPOWISE_DISTILL:START") == 1
+
+ def test_install_refreshes_stale_block_in_place(self, tmp_path) -> None:
+ install_agents_md_distill_section(tmp_path)
+ target = tmp_path / "AGENTS.md"
+ stale = target.read_text(encoding="utf-8").replace("repowise expand", "repowise old-expand")
+ target.write_text(stale, encoding="utf-8", newline="\n")
+
+ install_agents_md_distill_section(tmp_path)
+ refreshed = target.read_text(encoding="utf-8")
+ assert "repowise old-expand" not in refreshed
+ assert refreshed.count("REPOWISE_DISTILL:START") == 1
+
+ def test_skips_when_section_already_taught_elsewhere(self, tmp_path) -> None:
+ original = "# AGENTS.md\n\n### Output Distillation\n\nAlready covered.\n"
+ (tmp_path / "AGENTS.md").write_text(original, encoding="utf-8", newline="\n")
+ install_agents_md_distill_section(tmp_path)
+ assert (tmp_path / "AGENTS.md").read_text(encoding="utf-8") == original
+
+ def test_remove_when_absent(self, tmp_path) -> None:
+ assert remove_agents_md_distill_section(tmp_path) is False
+ assert agents_md_distill_section_installed(tmp_path) is False
diff --git a/tests/unit/distill/test_cli.py b/tests/unit/distill/test_cli.py
index b22a8f7b7..644b02d0c 100644
--- a/tests/unit/distill/test_cli.py
+++ b/tests/unit/distill/test_cli.py
@@ -116,6 +116,25 @@ def test_distill_source_flag_tags_the_ledger(repo_cwd: Path) -> None:
assert [r["group"] for r in rows] == ["hook-powershell"]
+def test_distill_expand_roundtrip_from_codex_surface(repo_cwd: Path) -> None:
+ """The omission store and `expand` are agent-agnostic — a marker produced
+ under the Codex hook's source tag restores exactly like any other."""
+ runner = CliRunner()
+ noisy = "import sys; sys.stdout.write('x.py:1:1: E501 line too long\\n' * 80)"
+ result = runner.invoke(distill_command, ["--source", "hook-codex", *_py(noisy)])
+ assert result.exit_code == 0
+ (ref,) = parse_marker_refs(result.output)
+
+ expanded = CliRunner().invoke(expand_command, [ref])
+ assert expanded.exit_code == 0
+ assert expanded.output.count("E501 line too long") == 80
+
+ store = OmissionStore(repo_cwd / ".repowise" / "omissions" / "omissions.db")
+ rows = store.savings_rollup(by="source")
+ store.close()
+ assert [r["group"] for r in rows] == ["hook-codex"]
+
+
def test_distill_does_not_eat_the_wrapped_commands_source_flag(repo_cwd: Path) -> None:
"""--source after the command belongs to the command, not to distill."""
result = CliRunner().invoke(
diff --git a/tests/unit/distill/test_config_and_doctor.py b/tests/unit/distill/test_config_and_doctor.py
index c2d5bd866..49d41472a 100644
--- a/tests/unit/distill/test_config_and_doctor.py
+++ b/tests/unit/distill/test_config_and_doctor.py
@@ -129,6 +129,18 @@ def repo(tmp_path: Path) -> Path:
return tmp_path
[email protected](autouse=True)
+def _isolate_codex(monkeypatch):
+ """Never let these flows see the developer's real ~/.codex.
+
+ Individual tests re-patch ``detect`` to True when exercising the Codex
+ surfaces explicitly (against patched paths).
+ """
+ from repowise.cli.agent_adapters.codex import CodexAdapter
+
+ monkeypatch.setattr(CodexAdapter, "detect", lambda self: False)
+
+
@pytest.fixture
def no_real_hook(monkeypatch):
"""Keep doctor away from the developer's real ~/.claude/settings.json."""
@@ -191,7 +203,18 @@ def test_doctor_hook_installed_with_repo_opt_out(repo: Path, monkeypatch) -> Non
"distill:\n commands:\n enabled: false\n", encoding="utf-8"
)
rows = _rows(repo)
- assert rows["Distill rewrite hook"][1] == "installed (this repo opted out)"
+ assert rows["Distill rewrite hook"][1] == "installed: claude-code (this repo opted out)"
+
+
+def test_doctor_reports_codex_surface_when_installed(repo: Path, monkeypatch) -> None:
+ from repowise.cli.agent_adapters.claude_code import ClaudeCodeAdapter
+ from repowise.cli.agent_adapters.codex import CodexAdapter
+
+ monkeypatch.setattr(ClaudeCodeAdapter, "rewrite_hook_installed", lambda self: True)
+ monkeypatch.setattr(CodexAdapter, "detect", lambda self: True)
+ monkeypatch.setattr(CodexAdapter, "rewrite_hook_installed", lambda self: True)
+ rows = _rows(repo)
+ assert rows["Distill rewrite hook"][1] == "installed: claude-code, codex"
# ---------------------------------------------------------------------------
@@ -276,3 +299,112 @@ def test_uninstall_removes_hook_but_leaves_repo_config(
# later reinstall does not need to re-discover repo preferences.
cfg = load_repo_config(repo)
assert cfg["distill"]["commands"]["enabled"] is True
+
+
+# ---------------------------------------------------------------------------
+# hook rewrite — the Codex surfaces (hooks.json + AGENTS.md awareness section)
+# ---------------------------------------------------------------------------
+
+
+def codex_env(tmp_path, monkeypatch):
+ """A detected Codex whose hooks.json lands in tmp, version patchable."""
+ from repowise.cli.agent_adapters.codex import CodexAdapter
+ from repowise.cli.editor_integrations import codex_config
+
+ hooks_path = tmp_path / ".codex" / "hooks.json"
+ monkeypatch.setattr(CodexAdapter, "detect", lambda self: True)
+ monkeypatch.setattr(codex_config, "_codex_hooks_path", lambda: hooks_path)
+ return hooks_path
+
+
+def _make_repo(tmp_path, monkeypatch) -> Path:
+ repo = tmp_path / "repo"
+ (repo / ".repowise").mkdir(parents=True)
+ monkeypatch.chdir(repo)
+ return repo
+
+
+def test_install_with_supported_codex_writes_hook_and_agents_md(
+ tmp_path: Path, settings_path: Path, codex_env: Path, monkeypatch
+) -> None:
+ from repowise.cli.editor_integrations import codex_config
+
+ monkeypatch.setattr(codex_config, "codex_cli_version", lambda: (0, 137, 0))
+ repo = _make_repo(tmp_path, monkeypatch)
+
+ result = CliRunner().invoke(rewrite_install, [])
+ assert result.exit_code == 0
+ assert "Codex rewrite hook: installed" in result.output
+ assert "ask-with-rewrite" in result.output # the honesty note
+ data = json.loads(codex_env.read_text(encoding="utf-8"))
+ commands = [h["command"] for e in data["hooks"]["PreToolUse"] for h in e["hooks"]]
+ assert commands == ["repowise-rewrite --agent codex"]
+ assert "REPOWISE_DISTILL" in (repo / "AGENTS.md").read_text(encoding="utf-8")
+
+
+def test_install_with_old_codex_is_awareness_only(
+ tmp_path: Path, settings_path: Path, codex_env: Path, monkeypatch
+) -> None:
+ from repowise.cli.editor_integrations import codex_config
+
+ monkeypatch.setattr(codex_config, "codex_cli_version", lambda: (0, 120, 0))
+ repo = _make_repo(tmp_path, monkeypatch)
+
+ result = CliRunner().invoke(rewrite_install, [])
+ assert result.exit_code == 0
+ # Honest, no implied parity: skipped + the minimum version named.
+ assert "Codex rewrite hook: skipped" in result.output
+ assert "0.137" in result.output
+ assert not codex_env.exists() # no hook entry on a build that rejects rewrites
+ assert "REPOWISE_DISTILL" in (repo / "AGENTS.md").read_text(encoding="utf-8")
+
+
+def test_uninstall_removes_codex_hook_and_agents_md_section(
+ tmp_path: Path, settings_path: Path, codex_env: Path, monkeypatch
+) -> None:
+ from repowise.cli.editor_integrations import codex_config
+
+ monkeypatch.setattr(codex_config, "codex_cli_version", lambda: (0, 137, 0))
+ repo = _make_repo(tmp_path, monkeypatch)
+
+ CliRunner().invoke(rewrite_install, [])
+ result = CliRunner().invoke(rewrite_uninstall, [])
+ assert result.exit_code == 0
+ assert "Codex rewrite hook: removed" in result.output
+ data = json.loads(codex_env.read_text(encoding="utf-8"))
+ assert not data.get("hooks", {}).get("PreToolUse")
+ assert not (repo / "AGENTS.md").exists() # awareness section round-tripped away
+
+
+def test_status_is_honest_about_codex_capability(
+ tmp_path: Path, settings_path: Path, codex_env: Path, monkeypatch
+) -> None:
+ from repowise.cli.commands.hook_cmd import rewrite_status
+ from repowise.cli.editor_integrations import codex_config
+
+ monkeypatch.setattr(codex_config, "codex_cli_version", lambda: (0, 120, 0))
+ _make_repo(tmp_path, monkeypatch)
+
+ result = CliRunner().invoke(rewrite_status, [])
+ assert result.exit_code == 0
+ assert "codex rewrite hook: not installed" in result.output
+ assert "0.137" in result.output # names the version it would need
+ assert "AGENTS.md distill section: not installed" in result.output
+
+
+def test_status_notes_allow_only_posture_on_supported_codex(
+ tmp_path: Path, settings_path: Path, codex_env: Path, monkeypatch
+) -> None:
+ from repowise.cli.commands.hook_cmd import rewrite_status
+ from repowise.cli.editor_integrations import codex_config
+
+ monkeypatch.setattr(codex_config, "codex_cli_version", lambda: (0, 137, 0))
+ _make_repo(tmp_path, monkeypatch)
+
+ CliRunner().invoke(rewrite_install, [])
+ result = CliRunner().invoke(rewrite_status, [])
+ assert result.exit_code == 0
+ assert "codex rewrite hook: installed" in result.output
+ assert "ask-with-rewrite" in result.output
+ assert "AGENTS.md distill section: installed" in result.output
diff --git a/tests/unit/distill/test_corrections.py b/tests/unit/distill/test_corrections.py
new file mode 100644
index 000000000..f1f4dd232
--- /dev/null
+++ b/tests/unit/distill/test_corrections.py
@@ -0,0 +1,488 @@
+"""Correction mining — fail→fixed pairing, classification, the managed block.
+
+Transcript lines follow the Claude Code JSONL shapes captured from real
+sessions on this machine: a *successful* shell call's ``toolUseResult`` is a
+dict with ``stdout``/``stderr``; a *failed* call's is a **string** starting
+``Error: Exit code N`` (cancellations, rejections, and permission denials are
+strings too but are not command failures).
+"""
+
+from __future__ import annotations
+
+import json
+import sqlite3
+import time
+from datetime import UTC, datetime
+from pathlib import Path
+
+import pytest
+from click.testing import CliRunner
+
+from repowise.cli.commands.corrections_cmd import corrections_command
+from repowise.core.distill.corrections import (
+ CORRECTIONS_MARKER_START,
+ command_anchor,
+ render_corrections_block,
+ scan_corrections,
+ strip_preamble,
+ update_corrections_block,
+)
+from repowise.core.distill.missed import transcript_dir_for
+
+NOW = time.time()
+
+
+def _iso(ts: float) -> str:
+ return datetime.fromtimestamp(ts, tz=UTC).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
+
+
+def _shell_call(
+ command: str,
+ result,
+ *,
+ cwd: str,
+ block_id: str,
+ ts: float = NOW,
+ tool: str = "PowerShell",
+) -> list[dict]:
+ """One tool_use + tool_result pair in the real transcript shape."""
+ return [
+ {
+ "type": "assistant",
+ "cwd": cwd,
+ "timestamp": _iso(ts),
+ "message": {
+ "role": "assistant",
+ "content": [
+ {
+ "type": "tool_use",
+ "id": block_id,
+ "name": tool,
+ "input": {"command": command},
+ }
+ ],
+ },
+ },
+ {
+ "type": "user",
+ "cwd": cwd,
+ "timestamp": _iso(ts + 1),
+ "message": {
+ "role": "user",
+ "content": [{"type": "tool_result", "tool_use_id": block_id, "content": "..."}],
+ },
+ "toolUseResult": result,
+ },
+ ]
+
+
+def _fail(command: str, error_tail: str = "", *, cwd: str, block_id: str, ts: float = NOW):
+ return _shell_call(
+ command, f"Error: Exit code 1\n{error_tail}", cwd=cwd, block_id=block_id, ts=ts
+ )
+
+
+def _ok(command: str, *, cwd: str, block_id: str, ts: float = NOW):
+ return _shell_call(
+ command,
+ {"stdout": "fine", "stderr": "", "interrupted": False},
+ cwd=cwd,
+ block_id=block_id,
+ ts=ts,
+ )
+
+
+def repo(tmp_path: Path) -> Path:
+ root = tmp_path / "myrepo"
+ (root / ".repowise").mkdir(parents=True)
+ return root
+
+
+def projects(tmp_path: Path, repo: Path) -> Path:
+ root = tmp_path / "projects"
+ transcript_dir_for(repo, root).mkdir(parents=True)
+ return root
+
+
+def _write_session(projects: Path, repo: Path, entries: list[dict], name: str = "s1") -> Path:
+ path = transcript_dir_for(repo, projects) / f"{name}.jsonl"
+ path.write_text("\n".join(json.dumps(e) for e in entries) + "\n", encoding="utf-8")
+ return path
+
+
+def _scan(repo: Path, projects: Path, **kwargs):
+ return scan_corrections(repo, projects_root=projects, **kwargs)
+
+
+# ---------------------------------------------------------------------------
+# The exit-criteria case: bare python fixed to the venv interpreter
+# ---------------------------------------------------------------------------
+
+
+class TestWrongTool:
+ def test_bare_python_fixed_to_venv_python(self, repo: Path, projects: Path) -> None:
+ entries = [
+ *_fail(
+ "python -m pytest tests/unit -q",
+ "ModuleNotFoundError: No module named 'repowise'",
+ cwd=str(repo),
+ block_id="t1",
+ ),
+ *_ok(r".venv\Scripts\python.exe -m pytest tests/unit -q", cwd=str(repo), block_id="t2"),
+ ]
+ _write_session(projects, repo, entries)
+ report = _scan(repo, projects)
+ assert report["pairs"] == 1
+ (rule,) = report["rules"]
+ assert rule["kind"] == "wrong_tool"
+ assert rule["wrong"] == "python"
+ assert rule["fixed"] == r".venv\Scripts\python.exe"
+ assert rule["example"]["failed"].startswith("python -m pytest")
+
+ def test_preamble_and_runner_form_still_pair(self, repo: Path, projects: Path) -> None:
+ # Real shape: env preamble + module runner on one side, plain exe on
+ # the other. The anchor must survive both differences.
+ entries = [
+ *_fail("pytest tests/unit -q", "errors", cwd=str(repo), block_id="t1"),
+ *_ok(
+ r'$env:PYTHONPATH="C:\x"; C:\repo\.venv\Scripts\python.exe -m pytest tests/unit -q',
+ cwd=str(repo),
+ block_id="t2",
+ ),
+ ]
+ _write_session(projects, repo, entries)
+ report = _scan(repo, projects)
+ assert report["pairs"] == 1
+ assert report["rules"][0]["kind"] == "wrong_tool"
+
+ def test_multiline_command_still_classifies_wrong_tool(
+ self, repo: Path, projects: Path
+ ) -> None:
+ entries = [
+ *_fail(
+ "python - <<'PY'\nimport repowise\nPY",
+ "No module named 'repowise'",
+ cwd=str(repo),
+ block_id="t1",
+ ),
+ *_ok(
+ ".venv/Scripts/python.exe - <<'PY'\nimport repowise\nPY",
+ cwd=str(repo),
+ block_id="t2",
+ ),
+ ]
+ _write_session(projects, repo, entries)
+ report = _scan(repo, projects)
+ assert report["pairs"] == 1
+ assert report["rules"][0]["kind"] == "wrong_tool"
+
+
+# ---------------------------------------------------------------------------
+# Precision: things that must NOT become corrections
+# ---------------------------------------------------------------------------
+
+
+class TestPrecisionGuards:
+ def test_identical_retry_is_flaky_not_a_correction(self, repo: Path, projects: Path) -> None:
+ entries = [
+ *_fail("pytest tests/unit -q", "1 failed", cwd=str(repo), block_id="t1"),
+ *_ok("pytest tests/unit -q", cwd=str(repo), block_id="t2"),
+ ]
+ _write_session(projects, repo, entries)
+ assert _scan(repo, projects)["pairs"] == 0
+
+ def test_red_green_loop_is_not_a_correction(self, repo: Path, projects: Path) -> None:
+ # Failing tests, then a re-run with a different selection once the
+ # code was fixed — exit 1 came from the tests, not the command.
+ entries = [
+ *_fail(
+ "pytest tests/unit/test_a.py -q",
+ "FAILED tests/unit/test_a.py::test_x - AssertionError",
+ cwd=str(repo),
+ block_id="t1",
+ ),
+ *_ok(
+ "pytest tests/unit/test_a.py tests/unit/test_b.py -q", cwd=str(repo), block_id="t2"
+ ),
+ ]
+ _write_session(projects, repo, entries)
+ assert _scan(repo, projects)["pairs"] == 0
+
+ def test_cancelled_and_rejected_results_are_not_failures(
+ self, repo: Path, projects: Path
+ ) -> None:
+ entries = [
+ *_shell_call(
+ "pytest -q", "Cancelled: parallel tool call Bash(x)", cwd=str(repo), block_id="t1"
+ ),
+ *_shell_call("pytest -q", "User rejected tool use", cwd=str(repo), block_id="t2"),
+ *_ok(".venv/Scripts/pytest.exe -q", cwd=str(repo), block_id="t3"),
+ ]
+ _write_session(projects, repo, entries)
+ assert _scan(repo, projects)["pairs"] == 0
+
+ def test_different_anchor_never_pairs(self, repo: Path, projects: Path) -> None:
+ entries = [
+ *_fail("pytest tests -q", "boom", cwd=str(repo), block_id="t1"),
+ *_ok("git status", cwd=str(repo), block_id="t2"),
+ ]
+ _write_session(projects, repo, entries)
+ assert _scan(repo, projects)["pairs"] == 0
+
+ def test_echo_strategy_changes_are_ignored(self, repo: Path, projects: Path) -> None:
+ entries = [
+ *_fail("echo recovered; exit 1", "recovered", cwd=str(repo), block_id="t1"),
+ *_ok("echo alive", cwd=str(repo), block_id="t2"),
+ ]
+ _write_session(projects, repo, entries)
+ assert _scan(repo, projects)["pairs"] == 0
+
+ def test_outside_repo_cwd_is_skipped(self, repo: Path, projects: Path, tmp_path: Path) -> None:
+ other = str(tmp_path / "elsewhere")
+ entries = [
+ *_fail("python x.py", "No module named x", cwd=other, block_id="t1"),
+ *_ok(".venv/Scripts/python.exe x.py", cwd=other, block_id="t2"),
+ ]
+ _write_session(projects, repo, entries)
+ assert _scan(repo, projects)["pairs"] == 0
+
+ def test_old_events_age_out_of_the_window(self, repo: Path, projects: Path) -> None:
+ old = NOW - 90 * 86400
+ entries = [
+ *_fail("python x.py", "No module named x", cwd=str(repo), block_id="t1", ts=old),
+ *_ok(".venv/Scripts/python.exe x.py", cwd=str(repo), block_id="t2", ts=old + 2),
+ ]
+ path = _write_session(projects, repo, entries)
+ # The mtime prefilter alone would skip the file; pin mtime to now so
+ # the per-entry timestamp cutoff is what's exercised.
+ import os
+
+ os.utime(path, (NOW, NOW))
+ assert _scan(repo, projects, days=30)["pairs"] == 0
+
+
+# ---------------------------------------------------------------------------
+# The other kinds — error-corroborated classification
+# ---------------------------------------------------------------------------
+
+
+class TestKinds:
+ def test_wrong_path_requires_error_naming_the_path(self, repo: Path, projects: Path) -> None:
+ entries = [
+ *_fail(
+ "pytest ../../tests/unit/cli/ -x -q",
+ "ERROR: file or directory not found: ../../tests/unit/cli/",
+ cwd=str(repo),
+ block_id="t1",
+ ),
+ *_ok("pytest tests/unit/cli/ -x -q", cwd=str(repo), block_id="t2"),
+ ]
+ _write_session(projects, repo, entries)
+ report = _scan(repo, projects)
+ assert report["pairs"] == 1
+ (rule,) = report["rules"]
+ assert rule["kind"] == "wrong_path"
+ assert rule["wrong"] == "../../tests/unit/cli/"
+ assert rule["fixed"] == "tests/unit/cli/"
+
+ def test_unknown_flag_requires_error_naming_the_flag(self, repo: Path, projects: Path) -> None:
+ entries = [
+ *_fail(
+ "pytest tests -q --looponfail",
+ "ERROR: unrecognized arguments: --looponfail",
+ cwd=str(repo),
+ block_id="t1",
+ ),
+ *_ok("pytest tests -q", cwd=str(repo), block_id="t2"),
+ ]
+ _write_session(projects, repo, entries)
+ report = _scan(repo, projects)
+ assert report["pairs"] == 1
+ (rule,) = report["rules"]
+ assert rule["kind"] == "unknown_flag"
+ assert rule["wrong"] == "--looponfail"
+
+ def test_repeated_fumbles_aggregate_by_count(self, repo: Path, projects: Path) -> None:
+ entries = []
+ for i in range(3):
+ entries += _fail(
+ "python -m pytest tests -q",
+ "No module named 'pytest'",
+ cwd=str(repo),
+ block_id=f"f{i}",
+ )
+ entries += _ok(
+ r".venv\Scripts\python.exe -m pytest tests -q", cwd=str(repo), block_id=f"s{i}"
+ )
+ _write_session(projects, repo, entries)
+ report = _scan(repo, projects)
+ assert report["pairs"] == 3
+ assert report["rules"][0]["count"] == 3
+
+ def test_wrong_path_hint_consults_the_index(self, repo: Path, projects: Path) -> None:
+ db = repo / ".repowise" / "wiki.db"
+ with sqlite3.connect(db) as conn:
+ conn.execute("CREATE TABLE wiki_symbols (file_path TEXT)")
+ conn.execute(
+ "INSERT INTO wiki_symbols VALUES ('tests/unit/health/test_coverage_parsers.py')"
+ )
+ entries = [
+ *_fail(
+ "pytest ../../tests/unit/health/test_coverage_parsers.py -q",
+ "ERROR: file or directory not found: ../../tests/unit/health/test_coverage_parsers.py",
+ cwd=str(repo),
+ block_id="t1",
+ ),
+ *_ok(
+ "pytest tests/unit/health/test_coverage_parsers.py -q", cwd=str(repo), block_id="t2"
+ ),
+ ]
+ _write_session(projects, repo, entries)
+ (rule,) = _scan(repo, projects)["rules"]
+ assert rule["hint"] == "indexed at tests/unit/health/test_coverage_parsers.py"
+
+
+# ---------------------------------------------------------------------------
+# Robustness contract
+# ---------------------------------------------------------------------------
+
+
+class TestBestEffort:
+ def test_missing_transcript_dir_is_empty_report(self, repo: Path, tmp_path: Path) -> None:
+ report = scan_corrections(repo, projects_root=tmp_path / "nope")
+ assert report == {"rules": [], "pairs": 0, "window_days": 30.0}
+
+ def test_malformed_lines_are_tolerated(self, repo: Path, projects: Path) -> None:
+ path = transcript_dir_for(repo, projects) / "bad.jsonl"
+ path.write_text('{"tool_use" "command" broken\nnot json\n', encoding="utf-8")
+ assert _scan(repo, projects)["pairs"] == 0
+
+
+# ---------------------------------------------------------------------------
+# Helpers
+# ---------------------------------------------------------------------------
+
+
+class TestHelpers:
+ @pytest.mark.parametrize(
+ ("command", "anchor"),
+ [
+ ("python -m pytest tests -q", "pytest"),
+ (r"C:\repo\.venv\Scripts\python.exe -m pytest tests", "pytest"),
+ ("python script.py", "python"),
+ (r'$env:X="1"; & "C:\tools\rg.exe" TODO', "rg"),
+ ("Set-Location C:\\repo; git status", "git"),
+ ("cd /tmp && ls -la", "ls"),
+ ("", ""),
+ ],
+ )
+ def test_command_anchor(self, command: str, anchor: str) -> None:
+ assert command_anchor(command) == anchor
+
+ def test_strip_preamble_keeps_the_real_command(self) -> None:
+ cmd = '$env:PYTHONIOENCODING="utf-8"; [Console]::OutputEncoding = [System.Text.Encoding]::UTF8; pytest -q'
+ assert strip_preamble(cmd) == "pytest -q"
+
+
+# ---------------------------------------------------------------------------
+# The managed --write block
+# ---------------------------------------------------------------------------
+
+
+def _rule(count: int = 3) -> dict:
+ return {
+ "kind": "wrong_tool",
+ "anchor": "pytest",
+ "wrong": "python",
+ "fixed": r".venv\Scripts\python.exe",
+ "count": count,
+ "example": {"failed": "python -m pytest", "fixed": r".venv\Scripts\python.exe -m pytest"},
+ }
+
+
+class TestManagedBlock:
+ def test_render_respects_threshold_and_cap(self) -> None:
+ rules = [_rule(5), _rule(1)]
+ block = render_corrections_block(rules, min_count=2)
+ assert block is not None
+ assert block.count("\n- ") == 1
+ assert "instead of `python`" in block
+ assert render_corrections_block([_rule(1)], min_count=2) is None
+
+ def test_update_round_trips_user_content(self, tmp_path: Path) -> None:
+ target = tmp_path / "CLAUDE.md"
+ original = "# CLAUDE.md\n\nMy rules.\n"
+ target.write_text(original, encoding="utf-8", newline="\n")
+
+ block = render_corrections_block([_rule()])
+ assert update_corrections_block(target, block) is True
+ content = target.read_text(encoding="utf-8")
+ assert content.startswith("# CLAUDE.md\n\nMy rules.")
+ assert CORRECTIONS_MARKER_START in content
+
+ # Refresh in place, no duplication.
+ assert update_corrections_block(target, block) is False
+ assert target.read_text(encoding="utf-8").count(CORRECTIONS_MARKER_START) == 1
+
+ # Removal restores the original bytes.
+ assert update_corrections_block(target, None) is True
+ assert target.read_text(encoding="utf-8") == original
+
+ def test_remove_never_creates_a_file(self, tmp_path: Path) -> None:
+ target = tmp_path / "CLAUDE.md"
+ assert update_corrections_block(target, None) is False
+ assert not target.exists()
+
+
+# ---------------------------------------------------------------------------
+# CLI surface
+# ---------------------------------------------------------------------------
+
+
+class TestCli:
+ @pytest.fixture(autouse=True)
+ def _redirect_transcripts(self, projects: Path, monkeypatch) -> None:
+ from repowise.core.distill import corrections as core
+
+ monkeypatch.setattr(
+ core, "transcript_dir_for", lambda root, _=None: transcript_dir_for(root, projects)
+ )
+
+ def test_report_only_by_default(self, repo: Path, projects: Path, monkeypatch) -> None:
+ entries = [
+ *_fail("python -m pytest -q", "No module named 'pytest'", cwd=str(repo), block_id="t1"),
+ *_ok(r".venv\Scripts\python.exe -m pytest -q", cwd=str(repo), block_id="t2"),
+ ]
+ _write_session(projects, repo, entries)
+ monkeypatch.chdir(repo)
+ result = CliRunner().invoke(corrections_command, [])
+ assert result.exit_code == 0
+ assert "wrong tool" in result.output
+ assert not (repo / ".claude" / "CLAUDE.md").exists() # report-only
+
+ def test_write_maintains_block_in_claude_md(
+ self, repo: Path, projects: Path, monkeypatch
+ ) -> None:
+ entries = []
+ for i in range(2):
+ entries += _fail(
+ "python -m pytest -q", "No module named 'pytest'", cwd=str(repo), block_id=f"f{i}"
+ )
+ entries += _ok(
+ r".venv\Scripts\python.exe -m pytest -q", cwd=str(repo), block_id=f"s{i}"
+ )
+ _write_session(projects, repo, entries)
+ monkeypatch.chdir(repo)
+ result = CliRunner().invoke(corrections_command, ["--write"])
+ assert result.exit_code == 0
+ content = (repo / ".claude" / "CLAUDE.md").read_text(encoding="utf-8")
+ assert "Known command corrections" in content
+ assert r".venv\Scripts\python.exe" in content
+
+ def test_no_findings_message(self, repo: Path, projects: Path, monkeypatch) -> None:
+ monkeypatch.chdir(repo)
+ result = CliRunner().invoke(corrections_command, [])
+ assert result.exit_code == 0
+ assert "No command corrections" in result.output
diff --git a/tests/unit/distill/test_rewrite_hook.py b/tests/unit/distill/test_rewrite_hook.py
index dca8f0d50..81d88f1a3 100644
--- a/tests/unit/distill/test_rewrite_hook.py
+++ b/tests/unit/distill/test_rewrite_hook.py
@@ -280,11 +280,12 @@ class TestDecidePowerShell:
# ---------------------------------------------------------------------------
-def _run_main(monkeypatch, payload) -> str:
+def _run_main(monkeypatch, payload, argv: list[str] | None = None) -> str:
stdin = io.StringIO(payload if isinstance(payload, str) else json.dumps(payload))
stdout = io.StringIO()
monkeypatch.setattr(sys, "stdin", stdin)
monkeypatch.setattr(sys, "stdout", stdout)
+ monkeypatch.setattr(sys, "argv", ["repowise-rewrite", *(argv or [])])
with pytest.raises(SystemExit) as exc:
rewrite_hook.main()
assert exc.value.code == 0
@@ -340,3 +341,40 @@ class TestMain:
def test_empty_stdin_is_silent(self, monkeypatch) -> None:
assert _run_main(monkeypatch, "") == ""
+
+
+class TestMainCodex:
+ """--agent codex: rewrite only what Codex's protocol can honor.
+
+ Codex PreToolUse hooks honor ``updatedInput`` only with
+ ``permissionDecision: "allow"`` — there is no ask-with-mutation. An
+ ``ask`` decision therefore passes through instead of silently escalating.
+ """
+
+ def test_ask_family_passes_through(self, monkeypatch, repo) -> None:
+ # Default posture is ask → Codex gets nothing, command runs raw.
+ out = _run_main(monkeypatch, _payload("pytest -x", str(repo)), argv=["--agent", "codex"])
+ assert out == ""
+
+ def test_allow_family_rewrites(self, monkeypatch, repo) -> None:
+ _write_config(repo, {"commands": {"families": {"test_output": "allow"}}})
+ out = _run_main(monkeypatch, _payload("pytest -x", str(repo)), argv=["--agent", "codex"])
+ hso = json.loads(out)["hookSpecificOutput"]
+ assert hso["permissionDecision"] == "allow"
+ assert hso["updatedInput"] == {"command": "repowise distill --source hook-codex pytest -x"}
+
+ def test_agent_equals_form(self, monkeypatch, repo) -> None:
+ _write_config(repo, {"commands": {"permission": "allow"}})
+ out = _run_main(monkeypatch, _payload("git status", str(repo)), argv=["--agent=codex"])
+ hso = json.loads(out)["hookSpecificOutput"]
+ assert hso["updatedInput"] == {"command": "repowise distill --source hook-codex git status"}
+
+ def test_powershell_tool_name_rejected(self, monkeypatch, repo) -> None:
+ # Codex has no PowerShell tool; a payload claiming one is malformed.
+ _write_config(repo, {"commands": {"permission": "allow"}})
+ payload = _payload("git status", str(repo), tool_name="PowerShell")
+ assert _run_main(monkeypatch, payload, argv=["--agent", "codex"]) == ""
+
+ def test_unknown_agent_falls_back_to_claude_code(self, monkeypatch, repo) -> None:
+ out = _run_main(monkeypatch, _payload("pytest -x", str(repo)), argv=["--agent", "weird"])
+ assert json.loads(out)["hookSpecificOutput"]["permissionDecision"] == "ask"