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.

perf(codex): stop waking a hook on every prompt, and migrate installs that do (#1549)

Raghav Chamadiya47af35c90595
diff --git a/docs/agent/CODEX.md b/docs/agent/CODEX.md
index d737c2665..117410b0f 100644
--- a/docs/agent/CODEX.md
+++ b/docs/agent/CODEX.md
@@ -55,11 +55,12 @@ codex mcp list
Repowise writes hooks to `.codex/hooks.json`, not inline `[hooks]` tables. The default hooks call the import-isolated `repowise-augment` entry point for:
-- `SessionStart` to add Repowise MCP workflow guidance.
-- `UserPromptSubmit` to remind Codex when Repowise context is available.
+- `SessionStart` to add Repowise MCP workflow guidance and the standing decisions relevant to the session.
- `PostToolUse` for `Bash|shell_command` to detect git operations that make the wiki stale. On current Codex the shell calls arrive as `shell_command`; `Bash` is kept in the set for older and future builds. See [HOOKS.md](HOOKS.md) for why `exec` is deliberately excluded.
- `PostToolUse` for `apply_patch`, `Edit`, and `Write` to remind Codex after edits.
+`UserPromptSubmit` is no longer among them. It ran unmatched on every prompt and returned the same static guidance `SessionStart` had already delivered, so it repeated a block the agent was holding. An existing `.codex/hooks.json` is repaired the next time something writes it: `repowise agents refresh`, or a `repowise init` that selects Codex. Hooks you added yourself are untouched, and so is a timeout you raised yourself. This file is project-local, so the repair happens per repo rather than once per machine.
+
Claude Code has its own search-result enrichment hook path for `Grep` and `Glob`. Codex setup stays focused on lifecycle guidance and freshness checks instead of trying to reuse that Claude-specific search enrichment.
## `codex_cli` Provider
diff --git a/docs/agent/HOOKS.md b/docs/agent/HOOKS.md
index a238a21fa..fd74a6247 100644
--- a/docs/agent/HOOKS.md
+++ b/docs/agent/HOOKS.md
@@ -24,7 +24,7 @@ crashes or blocks your agent.
| **PostToolUse enrichment** | Claude Code | `repowise init` | `Grep` / `Glob` / `Read` / `Edit` / `Write` / repowise MCP calls | Graph context on searches, read-intelligence notices, and edit-time "governed by" decision notices |
| **Wrong-path rescue** | Claude Code | `repowise init` | a `Read` / `Edit` / `Write` / `Grep` / `Glob` / `NotebookEdit` that failed on a path this tree does not have | Names the file when exactly one indexed file carries that basename; silent otherwise |
| **Command-rewrite (distill)** | Claude Code | `repowise hook rewrite install` (opt-in) | `Bash` / `PowerShell` | Rewrites noisy commands to `repowise distill <cmd>`; auto-allowed by default, set `permission: ask` to approve each one |
-| **Codex context + staleness** | Codex | `repowise init --codex` | SessionStart / UserPromptSubmit / edit / Bash | Reminds Codex to use the MCP tools and flags stale context after edits |
+| **Codex context + staleness** | Codex | `repowise init --codex` | SessionStart / edit / shell | Reminds Codex to use the MCP tools and flags stale context after edits |
Every agent hook records what it said and whether the agent acted on it — see
[`repowise hook stats`](#is-any-of-this-actually-helping--repowise-hook-stats).
@@ -182,9 +182,17 @@ Two rules bound how wrong this can be. It is **never applied twice in a row for
the same file**, so if a context compaction dropped the earlier copy, one more
Read always returns the content; the notice says exactly that. And a Read that
any surface replaced records no content observation at all, so the agent is
-never told it already has bytes that a skeleton stood in for. Savings appear
-under the `read_reread` filter, and a repo with it off still gets the
-counterfactual.
+never told it already has bytes that a skeleton stood in for.
+
+That second rule is also what makes this a **narrow surface rather than a broad
+one**, and it is worth knowing before you turn it on. The two Read surfaces are
+substitutes, and the skeleton takes the valuable half first: on a large indexed
+file the first Read is served as a skeleton and records no content observation,
+so the second Read has nothing to compare against and is served whole. What
+reaches the collapse is small files, unindexed files, and third-and-later reads
+of the same range. Expect a modest, steady trim rather than a headline. Savings
+appear under the `read_reread` filter, and a repo with it off still gets the
+counterfactual, so you can see what it would have done before enabling it.
**Searches that time out.** On Windows a `Glob` can exhaust ripgrep's 20-second
budget and return nothing at all — not "no matches", nothing, after twenty
@@ -240,8 +248,9 @@ to be confidently wrong:
not on disk right now, and pointing back at the failed path is the worst
thing this surface could say.
-Measured over 435 sessions in this repo: 86 path-not-found failures on the file
-tools, of which the rescue speaks to 18. The gap is the point.
+Most path-not-found failures therefore get silence, and that gap is the design
+rather than a shortfall in it. `repowise hook stats` reports what this surface
+actually did on your machine.
---
@@ -281,14 +290,28 @@ Per-repo behavior lives under `distill.commands` in `.repowise/config.yaml`
Written to project-local `.codex/hooks.json` by `repowise init --codex` (they do
not touch your global `~/.codex/config.toml`):
-- **SessionStart / UserPromptSubmit** → a short developer note reminding Codex to
- use the repowise MCP tools for architecture, search, risk, decisions, and
- dead-code analysis.
+- **SessionStart** → a short developer note reminding Codex to use the repowise
+ MCP tools for architecture, search, risk, decisions, and dead-code analysis,
+ plus the same relevance-ranked standing decisions Claude Code receives.
- **PostToolUse** (the shell tool, and `apply_patch` / `Edit` / `Write`) → after
a successful `git commit`, `merge`, `rebase`, `cherry-pick` or `pull`, compares
`HEAD` against the last indexed commit and flags that indexed context may be
stale, pointing at `repowise update`.
+`UserPromptSubmit` is no longer registered here. It carried no matcher, so it
+fired on every prompt, and what it returned was the
+static MCP-usage note `SessionStart` had already delivered in the same session:
+one process start per prompt to repeat a block the agent was holding.
+
+An install that predates the retirement is repaired in place the next time this
+repo's `.codex/hooks.json` is written, because the merge is additive and could
+not otherwise retire anything. That means `repowise agents refresh`, or a
+`repowise init` that selects Codex (the interactive checklist pre-ticks it when
+the repo is already wired, and `--codex` selects it outright). A plain
+`repowise init --yes` does not write Codex config at all, so it does not
+migrate either. A hook *you* wrote on that event is left alone, and a timeout
+you raised yourself is never moved.
+
Codex names its shell tool `shell_command` on current releases and `Bash` on
older ones, so the matcher covers both. The Claude Code hook deliberately does
*not* watch shell commands: it has `Read` / `Grep` / `Glob` tools and a
@@ -335,8 +358,8 @@ and `.codex/hooks.json` (Codex when `--codex` is passed):
| Claude Code | `SessionStart` | `startup\|resume\|clear` | `repowise-augment` [^guard] |
| Claude Code | `PostToolUse` | `Grep\|Glob\|Read\|Edit\|Write\|mcp__.*[Rr]epowise.*__.*` | `repowise-augment` [^guard] |
| Claude Code | `PreToolUse` (opt-in) | `Bash\|PowerShell` | `repowise-rewrite` |
-| Codex | `SessionStart` / `UserPromptSubmit` | lifecycle | context reminder |
-| Codex | `PostToolUse` | `Bash`, `apply_patch\|Edit\|Write` | staleness check |
+| Codex | `SessionStart` | `startup\|resume\|clear` | context reminder |
+| Codex | `PostToolUse` | `Bash\|shell_command`, `apply_patch\|Edit\|Write` | staleness check |
[^guard]: The command is written wrapped in a presence check rather than as the
bare name:
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index 51a9fef68..2b8ac2f66 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -902,7 +902,7 @@ The MCP server automatically enriches responses with cross-repo intelligence:
In addition to the MCP tools above, `repowise init` installs AI-agent hooks (Claude Code and Codex) that provide **passive, automatic** context enrichment:
- **Claude Code PostToolUse**: broad or zero-result `Grep`/`Glob` calls can be enriched with graph context, and git operations can trigger stale-wiki notices.
-- **Codex SessionStart/UserPromptSubmit**: Codex receives concise repowise MCP workflow guidance when a session or prompt starts.
+- **Codex SessionStart**: Codex receives concise repowise MCP workflow guidance when a session starts.
- **Codex PostToolUse**: after edits or git operations, Codex receives a freshness reminder when indexed context may be stale.
Hooks are lightweight reminders. MCP tools are for deeper, on-demand investigation. See [Auto-Sync](../scale/AUTO_SYNC.md) and [Codex Integration](CODEX.md) for details.
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index 063d1c37c..a9eac8f60 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -1639,7 +1639,7 @@ To remove a single agent rather than all of them, use
### `repowise augment`
-Hook-driven context enrichment engine. Not meant to be called manually, invoked by Claude Code and Codex hooks installed during `repowise init`. Claude Code uses it for search-result enrichment, stale-wiki checks, and decision injection: session start gets the standing decisions relevant to the session's working set (relevance-ranked, hard token cap, silent when nothing clears the floor), and editing a governed file gets a one-line "governed by" notice once per session per decision. Codex uses it for `SessionStart`, `UserPromptSubmit`, and `PostToolUse` lifecycle guidance. Shown decisions are recorded in `.repowise/sessions/sessions.db` so the next `repowise update` can judge whether the guidance was followed or contradicted and adjust decision staleness.
+Hook-driven context enrichment engine. Not meant to be called manually, invoked by Claude Code and Codex hooks installed during `repowise init`. Claude Code uses it for search-result enrichment, stale-wiki checks, and decision injection: session start gets the standing decisions relevant to the session's working set (relevance-ranked, hard token cap, silent when nothing clears the floor), and editing a governed file gets a one-line "governed by" notice once per session per decision. Codex uses it for `SessionStart` and `PostToolUse` lifecycle guidance. Shown decisions are recorded in `.repowise/sessions/sessions.db` so the next `repowise update` can judge whether the guidance was followed or contradicted and adjust decision staleness.
### `repowise-augment` / `repowise-rewrite`
diff --git a/packages/cli/src/repowise/cli/agent_targets/targets/codex.py b/packages/cli/src/repowise/cli/agent_targets/targets/codex.py
index 69d2edd81..62a3a571e 100644
--- a/packages/cli/src/repowise/cli/agent_targets/targets/codex.py
+++ b/packages/cli/src/repowise/cli/agent_targets/targets/codex.py
@@ -132,26 +132,55 @@ def server_table(repo_path: Path) -> dict[str, object]:
}
+#: Seconds a Codex augment hook may run before Codex gives up on it. This is a
+#: ceiling for a pathological case rather than a budget: the hook does local
+#: SQLite and ``git`` reads with no network and no LLM, so a normal fire is well
+#: under a second and most of that is interpreter start. Matches the Claude Code
+#: entries, which have carried 10 since they were written; Codex shipped 30 only
+#: because the two were never reconciled.
+_HOOK_TIMEOUT = 10
+
+#: Timeouts this entry has shipped with, current one excluded. A migration moves
+#: only these exact values, so a user who raised the timeout on purpose keeps it.
+_LEGACY_HOOK_TIMEOUTS = (30,)
+
+#: Events we used to register on and no longer do. ``UserPromptSubmit`` fired an
+#: unmatched context hook on **every** prompt, and what it emitted was the
+#: freshness line ``SessionStart`` already carries — so a turn paid one process
+#: start per prompt to repeat a block it was given at startup. The Claude Code
+#: entries never registered it. Migration removes ours from an existing file; a
+#: hook the user wrote on the same event is untouched.
+_RETIRED_EVENTS = ("UserPromptSubmit",)
+
+
def hooks_config() -> dict[str, object]:
- """Project-local Codex hooks for context injection and freshness checks."""
+ """Project-local Codex hooks for context injection and freshness checks.
+
+ The shell matcher stays, and that asymmetry with Claude Code is deliberate.
+ Claude Code dropped ``Bash``/``PowerShell`` from its augment matcher on
+ measurement (51% of invocations, 0.7% of emissions), but it kept ``Read``,
+ ``Grep`` and ``Glob``, which is where its emissions come from. Codex has
+ none of those tools, so the shell is the only surface a hook can reach it
+ on: dropping it here would not trim a matcher, it would leave Codex with
+ startup and edits alone.
+ """
from repowise.cli.agent_adapters.codex import SHELL_TOOL_MATCHER
context_hook = {
"type": "command",
"command": "repowise-augment --client codex",
- "timeout": 30,
+ "timeout": _HOOK_TIMEOUT,
"statusMessage": "Loading repowise context...",
}
freshness_hook = {
"type": "command",
"command": "repowise-augment --client codex",
- "timeout": 30,
+ "timeout": _HOOK_TIMEOUT,
"statusMessage": "Checking repowise freshness...",
}
return {
"hooks": {
"SessionStart": [{"matcher": "startup|resume|clear", "hooks": [context_hook]}],
- "UserPromptSubmit": [{"hooks": [context_hook]}],
"PostToolUse": [
{"matcher": SHELL_TOOL_MATCHER, "hooks": [freshness_hook]},
{"matcher": "apply_patch|Edit|Write", "hooks": [freshness_hook]},
@@ -160,6 +189,71 @@ def hooks_config() -> dict[str, object]:
}
+def _migrate_hooks_config(hooks: dict) -> None:
+ """Repair our own entries in an existing ``.codex/hooks.json``, in place.
+
+ The twin of :func:`~repowise.cli.editor_integrations.claude_config._migrate_legacy_hook`,
+ and it exists because the merge in :func:`write_hooks_config` is purely
+ *additive*: it appends an entry when no entry carries our hook for that
+ matcher, and does nothing at all when one does. So a shape we stopped
+ shipping survives on an existing install forever, and reinstalling is not a
+ repair anyone would think to try, because the install reports success either
+ way.
+
+ Two repairs, both scoped to hooks whose command is ours:
+
+ * **Retired events are dropped** — see :data:`_RETIRED_EVENTS`.
+ * **Legacy timeouts move to** :data:`_HOOK_TIMEOUT`, and only from the values
+ we shipped, so a user who raised it keeps their number.
+
+ Returns nothing on purpose. The obvious shape here is a ``changed`` boolean,
+ and the Claude Code twin does return one — but its caller needs it to decide
+ whether to write at all, and this one does not: ``write_json_config`` renders
+ the merged document and diffs it against what is on disk, so the
+ CREATED/UPDATED/UNCHANGED verdict is already computed from the bytes. A
+ boolean here would be tracked through three branches and then dropped.
+ """
+ for event in _RETIRED_EVENTS:
+ entries = hooks.get(event)
+ if not isinstance(entries, list) or not entries:
+ continue
+ surviving: list[object] = []
+ for entry in entries:
+ inner = entry.get("hooks") if isinstance(entry, dict) else None
+ if not isinstance(inner, list):
+ surviving.append(entry)
+ continue
+ remaining = [h for h in inner if not (isinstance(h, dict) and _is_augment_hook(h))]
+ if len(remaining) == len(inner):
+ surviving.append(entry)
+ continue
+ # A group that held only our hook goes with it; a group the user
+ # also wrote in keeps everything except ours. Same rule as
+ # ``remove_hooks_config``, for the same reason.
+ if remaining:
+ entry["hooks"] = remaining
+ surviving.append(entry)
+ # Iterating ``_RETIRED_EVENTS`` rather than ``hooks`` is what makes this
+ # pop safe: the loop never walks the dict being mutated.
+ if surviving:
+ hooks[event] = surviving
+ else:
+ hooks.pop(event)
+
+ for entries in hooks.values():
+ if not isinstance(entries, list):
+ continue
+ for entry in entries:
+ inner = entry.get("hooks") if isinstance(entry, dict) else None
+ if not isinstance(inner, list):
+ continue
+ for hook in inner:
+ if not isinstance(hook, dict) or not _is_augment_hook(hook):
+ continue
+ if hook.get("timeout") in _LEGACY_HOOK_TIMEOUTS:
+ hook["timeout"] = _HOOK_TIMEOUT
+
+
# ---------------------------------------------------------------------------
# Writes
# ---------------------------------------------------------------------------
@@ -253,7 +347,9 @@ def write_hooks_config(repo_path: Path) -> tuple[FileWrite, FileWrite]:
"""Merge repowise hooks into ``.codex/hooks.json`` and enable the feature.
Additive per matcher group: a matcher that already carries one of our hooks
- is left alone, so a user who narrowed or annotated an entry keeps it.
+ is left alone, so a user who narrowed or annotated an entry keeps it. That
+ rule is why :func:`_migrate_hooks_config` runs first — additive alone can
+ never retire a shape, only ever add one.
Returns both writes — the hooks file *and* ``config.toml``'s feature flag —
because they are genuinely two files and reporting only the first would hide
@@ -279,6 +375,8 @@ def write_hooks_config(repo_path: Path) -> tuple[FileWrite, FileWrite]:
"Fix or remove it and retry; no changes were written."
)
+ _migrate_hooks_config(hooks)
+
for event, entries in new_config["hooks"].items():
event_hooks = hooks.setdefault(event, [])
if not isinstance(event_hooks, list):
@@ -807,16 +905,39 @@ def _combined(first: FileAction, second: FileAction) -> FileAction:
def _is_augment_hook(hook: dict) -> bool:
- cmd = hook.get("command", "")
+ """True when *hook*'s command is ours. Any other shape is False.
+
+ ``hook.get("command", "")`` was the original, and it assumes the value is a
+ string. This reads a file the user owns, where ``"command": 7`` is a shape
+ to answer rather than to raise ``TypeError`` on, part-way through a write
+ that has already rewritten other entries. The Claude Code twin was hardened
+ for exactly this; the Codex half was missed, and the migration above walks
+ every event in the document, which is where such a value would sit.
+ """
+ cmd = hook.get("command")
+ if not isinstance(cmd, str):
+ return False
return "repowise-augment" in cmd or "repowise augment" in cmd
def _has_augment_hook_for_matcher(hook_list: list, matcher: object) -> bool:
+ """True when some entry for *matcher* already carries our hook.
+
+ Every shape is guarded for the same reason :func:`_is_augment_hook` is: this
+ walks a file the user owns, and a bare string or a null under ``hooks`` used
+ to raise out of the middle of ``write_hooks_config`` rather than being
+ answered. A shape we cannot read carries nothing of ours, which makes the
+ install append its entry — the safe direction, since a duplicate matcher is
+ inert where a missing hook is silent.
+ """
for entry in hook_list:
- if entry.get("matcher") != matcher:
+ if not isinstance(entry, dict) or entry.get("matcher") != matcher:
+ continue
+ inner = entry.get("hooks")
+ if not isinstance(inner, list):
continue
- for hook in entry.get("hooks", []):
- if _is_augment_hook(hook):
+ for hook in inner:
+ if isinstance(hook, dict) and _is_augment_hook(hook):
return True
return False
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/codex.py b/packages/cli/src/repowise/cli/commands/augment_cmd/codex.py
index 8346c2ca4..a6b3384af 100644
--- a/packages/cli/src/repowise/cli/commands/augment_cmd/codex.py
+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/codex.py
@@ -1,8 +1,16 @@
-"""Codex lifecycle hooks: SessionStart/UserPromptSubmit + post-edit staleness.
+"""Codex lifecycle hooks: SessionStart context + post-edit staleness.
SessionStart delivers a short MCP-usage context block plus the same
relevance-ranked standing-decisions block that Claude Code receives
(see :mod:`.decision_inject`), so decisions follow the user across agents.
+
+``UserPromptSubmit`` is still *answered* here but is no longer *registered* by
+anything we install — see ``_RETIRED_EVENTS`` in the Codex target. Nothing that
+ships routes this event any more, so the branch below exists for one population:
+an install whose ``.codex/hooks.json`` predates the retirement and has not yet
+been migrated. Handling it keeps that transition graceful rather than turning a
+stale config into a silent hook error, and the migration removes the
+registration the next time any repowise command touches the file.
"""
from __future__ import annotations
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/command.py b/packages/cli/src/repowise/cli/commands/augment_cmd/command.py
index 867e2eb83..f3bcf17dd 100644
--- a/packages/cli/src/repowise/cli/commands/augment_cmd/command.py
+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/command.py
@@ -26,7 +26,9 @@ asymmetric, durable value:
* Skip otherwise: a focused result set means the agent already
found what it wanted; further graph context is just noise.
-Codex SessionStart/UserPromptSubmit: adds short repowise MCP usage guidance.
+Codex SessionStart: adds short repowise MCP usage guidance. (``UserPromptSubmit``
+is still answered for installs predating its retirement, but nothing we ship
+registers it any more — see :mod:`.codex`.)
SessionStart (Claude Code)
* Emits a one-paragraph context block: whether the index is current,
diff --git a/packages/cli/src/repowise/cli/commands/augment_cmd/served_reads.py b/packages/cli/src/repowise/cli/commands/augment_cmd/served_reads.py
index e70513d21..dd220cf9d 100644
--- a/packages/cli/src/repowise/cli/commands/augment_cmd/served_reads.py
+++ b/packages/cli/src/repowise/cli/commands/augment_cmd/served_reads.py
@@ -19,6 +19,20 @@ Two hooks feed it:
Same operational rules as the rest of augment: stdlib-only on the hook path,
unknown tool-output shapes are skipped rather than guessed, and any failure
degrades to silence.
+
+**A near-zero firing count is this surface working, not this surface failing.**
+Worth writing down, because in ``repowise hook stats`` it sits among rows that
+carry real action rates and so reads like a dead code path, and it has been
+proposed for deletion on exactly that basis. It cannot fire more often than the
+repowise MCP tools are called, and their share of an agent's tool calls is the
+low number this KPI exists to observe. The count therefore tracks adoption, and
+cutting the surface for having a low one would delete the instrument to make the
+reading go away. Keeping it costs nothing to weigh against that: ``chars=0``, no
+emission, no tokens, and the only work on the hook's critical path is a coverage
+check against the session state file.
+
+Retire it when there is a *better* measure of whether MCP answers land. Never
+because this one reads low.
"""
from __future__ import annotations
diff --git a/plugins/codex/hooks/hooks.json b/plugins/codex/hooks/hooks.json
index bde7ecd35..38ea99f9d 100644
--- a/plugins/codex/hooks/hooks.json
+++ b/plugins/codex/hooks/hooks.json
@@ -7,19 +7,7 @@
{
"type": "command",
"command": "repowise-augment --client codex",
- "timeout": 30,
- "statusMessage": "Loading repowise context..."
- }
- ]
- }
- ],
- "UserPromptSubmit": [
- {
- "hooks": [
- {
- "type": "command",
- "command": "repowise-augment --client codex",
- "timeout": 30,
+ "timeout": 10,
"statusMessage": "Loading repowise context..."
}
]
@@ -32,7 +20,7 @@
{
"type": "command",
"command": "repowise-augment --client codex",
- "timeout": 30,
+ "timeout": 10,
"statusMessage": "Checking repowise freshness..."
}
]
@@ -43,7 +31,7 @@
{
"type": "command",
"command": "repowise-augment --client codex",
- "timeout": 30,
+ "timeout": 10,
"statusMessage": "Checking repowise freshness..."
}
]
diff --git a/tests/unit/cli/data/agent_target_baseline.json b/tests/unit/cli/data/agent_target_baseline.json
index 2a9962828..1c9cd5890 100644
--- a/tests/unit/cli/data/agent_target_baseline.json
+++ b/tests/unit/cli/data/agent_target_baseline.json
@@ -5,7 +5,7 @@
"newlines": "platform"
},
".codex/hooks.json": {
- "content": "{\n \"hooks\": {\n \"SessionStart\": [\n {\n \"matcher\": \"startup|resume|clear\",\n \"hooks\": [\n {\n \"type\": \"command\",\n \"command\": \"repowise-augment --client codex\",\n \"timeout\": 30,\n \"statusMessage\": \"Loading repowise context...\"\n }\n ]\n }\n ],\n \"UserPromptSubmit\": [\n {\n \"hooks\": [\n {\n \"type\": \"command\",\n \"command\": \"repowise-augment --client codex\",\n \"timeout\": 30,\n \"statusMessage\": \"Loading repowise context...\"\n }\n ]\n }\n ],\n \"PostToolUse\": [\n {\n \"matcher\": \"Bash|shell_command\",\n \"hooks\": [\n {\n \"type\": \"command\",\n \"command\": \"repowise-augment --client codex\",\n \"timeout\": 30,\n \"statusMessage\": \"Checking repowise freshness...\"\n }\n ]\n },\n {\n \"matcher\": \"apply_patch|Edit|Write\",\n \"hooks\": [\n {\n \"type\": \"command\",\n \"command\": \"repowise-augment --client codex\",\n \"timeout\": 30,\n \"statusMessage\": \"Checking repowise freshness...\"\n }\n ]\n }\n ]\n }\n}\n",
+ "content": "{\n \"hooks\": {\n \"SessionStart\": [\n {\n \"matcher\": \"startup|resume|clear\",\n \"hooks\": [\n {\n \"type\": \"command\",\n \"command\": \"repowise-augment --client codex\",\n \"timeout\": 10,\n \"statusMessage\": \"Loading repowise context...\"\n }\n ]\n }\n ],\n \"PostToolUse\": [\n {\n \"matcher\": \"Bash|shell_command\",\n \"hooks\": [\n {\n \"type\": \"command\",\n \"command\": \"repowise-augment --client codex\",\n \"timeout\": 10,\n \"statusMessage\": \"Checking repowise freshness...\"\n }\n ]\n },\n {\n \"matcher\": \"apply_patch|Edit|Write\",\n \"hooks\": [\n {\n \"type\": \"command\",\n \"command\": \"repowise-augment --client codex\",\n \"timeout\": 10,\n \"statusMessage\": \"Checking repowise freshness...\"\n }\n ]\n }\n ]\n }\n}\n",
"newlines": "platform"
},
".mcp.json": {
diff --git a/tests/unit/cli/test_codex_plugin.py b/tests/unit/cli/test_codex_plugin.py
index f6bc2e16e..dda64abfb 100644
--- a/tests/unit/cli/test_codex_plugin.py
+++ b/tests/unit/cli/test_codex_plugin.py
@@ -40,10 +40,27 @@ def test_codex_plugin_mcp_uses_repowise_no_path_mode() -> None:
assert config["repowise"]["startup_timeout_sec"] == 20
+def test_codex_plugin_hooks_are_byte_identical_to_what_the_cli_installs() -> None:
+ """The plugin file and ``hooks_config()`` are one shape, pinned to each other.
+
+ They were two hand-maintained copies, and a third copy of the same literals
+ lived in this test's assertions — so retiring an event or moving a timeout
+ took three coordinated edits, and missing one left the plugin re-installing
+ the shape the CLI had just dropped. Equality against the generator makes the
+ drift impossible to commit instead of merely unlikely.
+ """
+ from repowise.cli.agent_targets.targets.codex import hooks_config
+
+ assert _load_json(PLUGIN_ROOT / "hooks" / "hooks.json") == hooks_config()
+
+
def test_codex_plugin_hooks_match_supported_codex_events() -> None:
hooks = _load_json(PLUGIN_ROOT / "hooks" / "hooks.json")["hooks"]
- assert set(hooks) == {"SessionStart", "UserPromptSubmit", "PostToolUse"}
+ # UserPromptSubmit is deliberately absent: it fired an unmatched hook on
+ # every prompt to re-emit the byte-identical block SessionStart already
+ # carries. See ``_RETIRED_EVENTS`` in the Codex target.
+ assert set(hooks) == {"SessionStart", "PostToolUse"}
assert hooks["SessionStart"][0]["matcher"] == "startup|resume|clear"
assert [entry["matcher"] for entry in hooks["PostToolUse"]] == [
SHELL_TOOL_MATCHER,
@@ -56,13 +73,7 @@ def test_codex_plugin_hooks_match_supported_codex_events() -> None:
for entry in entries
for hook in entry["hooks"]
]
- assert commands == ["repowise-augment --client codex"] * 4
- assert [
- hook["timeout"]
- for entries in hooks.values()
- for entry in entries
- for hook in entry["hooks"]
- ] == [30] * 4
+ assert commands == ["repowise-augment --client codex"] * 3
def test_codex_shell_matcher_covers_the_names_codex_actually_sends() -> None:
diff --git a/tests/unit/cli/test_mcp_config.py b/tests/unit/cli/test_mcp_config.py
index 7c65f6fde..cf1c167c0 100644
--- a/tests/unit/cli/test_mcp_config.py
+++ b/tests/unit/cli/test_mcp_config.py
@@ -90,7 +90,10 @@ def test_generate_codex_hooks_config_uses_supported_events_only() -> None:
config = mcp_config.generate_codex_hooks_config()
hooks = config["hooks"]
- assert set(hooks) == {"SessionStart", "UserPromptSubmit", "PostToolUse"}
+ # UserPromptSubmit is retired: it registered an unmatched hook that fired on
+ # every prompt and returned the byte-identical static block SessionStart had
+ # already delivered.
+ assert set(hooks) == {"SessionStart", "PostToolUse"}
assert hooks["SessionStart"][0]["matcher"] == "startup|resume|clear"
# Derived from the adapter, never spelled here: Codex calls its shell tool
# `shell_command` on current releases and `Bash` on older ones, and a
@@ -99,12 +102,14 @@ def test_generate_codex_hooks_config_uses_supported_events_only() -> None:
assert hooks["PostToolUse"][0]["matcher"] == codex_adapter.SHELL_TOOL_MATCHER
assert "shell_command" in hooks["PostToolUse"][0]["matcher"]
assert hooks["PostToolUse"][1]["matcher"] == "apply_patch|Edit|Write"
+ # 10, matching the Claude Code entries. 30 was an unreconciled ceiling
+ # rather than a considered budget.
assert [
hook["timeout"]
for entries in hooks.values()
for entry in entries
for hook in entry["hooks"]
- ] == [30] * 4
+ ] == [10] * 3
def test_save_codex_hooks_config_creates_hooks_json_and_feature_flag(
@@ -115,7 +120,8 @@ def test_save_codex_hooks_config_creates_hooks_json_and_feature_flag(
assert hooks_path == tmp_path / ".codex" / "hooks.json"
saved_hooks = json.loads(hooks_path.read_text(encoding="utf-8"))
assert "PreToolUse" not in saved_hooks["hooks"]
- assert saved_hooks["hooks"]["UserPromptSubmit"][0]["hooks"][0]["command"] == (
+ assert "UserPromptSubmit" not in saved_hooks["hooks"]
+ assert saved_hooks["hooks"]["SessionStart"][0]["hooks"][0]["command"] == (
"repowise-augment --client codex"
)
@@ -159,13 +165,127 @@ def test_save_codex_hooks_config_merges_without_duplicates(tmp_path: Path) -> No
for hook in entry["hooks"]
if hook["command"] == "repowise-augment --client codex"
]
- assert len(repowise_commands) == 4
+ assert len(repowise_commands) == 3
saved_config = tomllib.loads(config_path.read_text(encoding="utf-8"))
assert saved_config["features"]["foo"] is True
assert saved_config["features"]["hooks"] is True
+def _legacy_hooks_document() -> dict:
+ """A ``.codex/hooks.json`` exactly as installs before the retirement wrote it."""
+ return {
+ "hooks": {
+ "SessionStart": [
+ {
+ "matcher": "startup|resume|clear",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "repowise-augment --client codex",
+ "timeout": 30,
+ "statusMessage": "Loading repowise context...",
+ }
+ ],
+ }
+ ],
+ "UserPromptSubmit": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "repowise-augment --client codex",
+ "timeout": 30,
+ "statusMessage": "Loading repowise context...",
+ }
+ ]
+ }
+ ],
+ }
+ }
+
+
+def _write_hooks(tmp_path: Path, document: dict) -> Path:
+ hooks_path = tmp_path / ".codex" / "hooks.json"
+ hooks_path.parent.mkdir(parents=True, exist_ok=True)
+ hooks_path.write_text(json.dumps(document), encoding="utf-8")
+ return hooks_path
+
+
+def test_save_codex_hooks_config_retires_user_prompt_submit_in_place(
+ tmp_path: Path,
+) -> None:
+ """The merge is additive, so retiring an event needs a migration to reach disk.
+
+ Without one, every install that predates the retirement keeps firing a hook
+ on every prompt forever: reinstalling appends nothing (the matcher is already
+ ours) and reports success, so there is no repair a user could even attempt.
+ """
+ hooks_path = _write_hooks(tmp_path, _legacy_hooks_document())
+
+ mcp_config.save_codex_hooks_config(tmp_path)
+
+ saved = json.loads(hooks_path.read_text(encoding="utf-8"))["hooks"]
+ assert "UserPromptSubmit" not in saved
+ assert set(saved) == {"SessionStart", "PostToolUse"}
+
+
+def test_save_codex_hooks_config_moves_shipped_timeout_but_not_a_user_raised_one(
+ tmp_path: Path,
+) -> None:
+ """30 was ours and moves; anything else was a choice and stays."""
+ document = _legacy_hooks_document()
+ document["hooks"]["SessionStart"][0]["hooks"][0]["timeout"] = 120
+ hooks_path = _write_hooks(tmp_path, document)
+
+ mcp_config.save_codex_hooks_config(tmp_path)
+
+ saved = json.loads(hooks_path.read_text(encoding="utf-8"))["hooks"]
+ assert saved["SessionStart"][0]["hooks"][0]["timeout"] == 120
+ assert [hook["timeout"] for entry in saved["PostToolUse"] for hook in entry["hooks"]] == [
+ 10,
+ 10,
+ ]
+
+
+def test_save_codex_hooks_config_migration_spares_a_user_hook_on_a_retired_event(
+ tmp_path: Path,
+) -> None:
+ """We remove our command from ``UserPromptSubmit``, never the user's event."""
+ document = _legacy_hooks_document()
+ document["hooks"]["UserPromptSubmit"].append(
+ {"hooks": [{"type": "command", "command": "echo mine"}]}
+ )
+ document["hooks"]["UserPromptSubmit"][0]["hooks"].append(
+ {"type": "command", "command": "echo alongside"}
+ )
+ hooks_path = _write_hooks(tmp_path, document)
+
+ mcp_config.save_codex_hooks_config(tmp_path)
+
+ saved = json.loads(hooks_path.read_text(encoding="utf-8"))["hooks"]
+ remaining = [
+ hook["command"] for entry in saved["UserPromptSubmit"] for hook in entry["hooks"]
+ ]
+ assert remaining == ["echo alongside", "echo mine"]
+
+
+def test_save_codex_hooks_config_survives_shapes_we_did_not_write(tmp_path: Path) -> None:
+ """A file the user owns can hold anything; the migration answers, never raises."""
+ document = _legacy_hooks_document()
+ document["hooks"]["SessionStart"][0]["hooks"].append({"type": "command", "command": 7})
+ document["hooks"]["UserPromptSubmit"].append("not-an-entry")
+ document["hooks"]["Whatever"] = "not-a-list"
+ hooks_path = _write_hooks(tmp_path, document)
+
+ mcp_config.save_codex_hooks_config(tmp_path)
+
+ saved = json.loads(hooks_path.read_text(encoding="utf-8"))["hooks"]
+ assert saved["Whatever"] == "not-a-list"
+ assert saved["UserPromptSubmit"] == ["not-an-entry"]
+ assert {"type": "command", "command": 7} in saved["SessionStart"][0]["hooks"]
+
+
def test_save_codex_hooks_config_rejects_invalid_existing_file(tmp_path: Path) -> None:
hooks_path = tmp_path / ".codex" / "hooks.json"
hooks_path.parent.mkdir(parents=True)
diff --git a/website/codex.md b/website/codex.md
index 7148f9828..67be3218e 100644
--- a/website/codex.md
+++ b/website/codex.md
@@ -62,9 +62,8 @@ Codex hooks are written to `.codex/hooks.json`:
| Event | Purpose |
|-------|---------|
-| `SessionStart` | Add Repowise MCP workflow guidance |
-| `UserPromptSubmit` | Remind Codex that Repowise context is available |
-| `PostToolUse` `Bash` | Detect git operations and stale wiki state |
+| `SessionStart` | Add Repowise MCP workflow guidance and the session's standing decisions |
+| `PostToolUse` `Bash\|shell_command` | Detect git operations and stale wiki state |
| `PostToolUse` `apply_patch\|Edit\|Write` | Remind after edits that context may need refresh |
Repowise keeps Codex hooks focused on lifecycle guidance and freshness checks rather than trying to reuse Claude-specific search enrichment.