Skip to content

Edit hook: show a file's lessons before every edit, in Claude Code and Codex, instead of asking the agent to call precheck_file #37

Closed

Description

@bigfree

The instructions ask agents to call precheck_file before modifying a file. In practice they rarely do, and when they do it is mostly for nothing. I went through two months of Claude Code transcripts on one project: about 800 transcripts including subagents, with 8,355 Edit/Write/MultiEdit calls on files in the repository (.projectmem/ and docs/ excluded).

8,355 edits: was there a precheck_file on the file earlier in the transcript?

with precheck     ██▋                      11%
without precheck  █████████████████████▍   89%

Main sessions 9%, subagents 11%.

1,433 precheck_file results

"No warnings. Safe to modify."  ████████████▊            53%
something to say                ███████████▎             47%

63 edits touched a file that already had a failed or partial attempt; 22 of them had no precheck before.

So the agent spends a tool call per check, about half of them to hear that there is nothing, and still skips nine edits in ten. The check is cheap and mechanical, which makes it a better fit for a hook than for an instruction. The existing pre-commit precheck warns at commit time, after the edits are made; this moves the same knowledge to the moment before the edit.

Proposal

A stdlib-only module, projectmem.edit_hook (console script pjm-edit-hook), registered as a PreToolUse hook. It reads the tool call from stdin, finds the edited files, and adds their lessons as additionalContext, only when there is something to say:

projectmem lessons for src/auth.py:
  Open issues on this file:
    - #0042 token refresh race under parallel requests
  Earlier attempts (1 failed, 1 partial), newest first:
    ~ retry halves the failures (#0042, 2026-10-30)
    x wrapped refresh in a lock (#0042, 2026-09-28)
  Decisions on this file:
    - refresh tokens are rotated per user, never shared (2026-09-12)

Claude Code and Codex CLI both run PreToolUse hooks with the same contract (JSON on stdin, hookSpecificOutput.additionalContext on stdout), so one module serves both:

Claude Code Codex CLI
Config ~/.claude/settings.json or the project's .claude/settings*.json ~/.codex/hooks.json or the project's .codex/hooks.json (same shape)
Matcher Edit|Write|MultiEdit apply_patch
Edited path tool_input.file_path, absolute *** Update File: / Add File: / Delete File: / Move to: lines in tool_input.command, relative to cwd; one patch can touch several files
Takes effect next session next session, after the user trusts the hook

The hook finds the project by walking up from each edited file to .projectmem/events.jsonl, so it can be installed once at user level and serve every project. Clients without hooks (Cursor and others) keep the instruction to call precheck_file.

An installer could extend the existing command, for example pjm hooks install --agent claude-code|codex, writing the entry with the absolute path of pjm-edit-hook so it works under pipx or uv tool without projectmem on the system Python.

Rules

  • Silent when clean. No output, so no tokens, for a file without lessons or outside any project.
  • Once per file per agent, unless the lessons change. An agent edits the same file many times in a row; the same lesson is useful once. If an attempt is logged mid-session, the next edit shows the updated block. A subagent shares its parent's session_id but not its context, so the key includes agent_id. After compaction the lessons may be gone from the summary, so the same command registered on SessionStart (matcher compact) in Claude Code or PostCompact in Codex forgets what the session was shown (covered by tests, not yet tried live).
  • Bounded. At most three entries per section, each clipped to 160 characters; the rest of each section collapses into one line (... and 8 more, from #0042 (get_issue)), so a file with a long history costs no more than one with three entries. Issue ids are printed only when they look like ids.
  • Lessons only. Open issues, failed and partial attempts, and decisions that are not superseded. High churn and possibly-stale memories stay out: before an edit they are noise, and they are the part of _analyze_files that calls git log.
  • Worktrees. Claude Code worktrees live under .claude/worktrees/<name>/. events.jsonl is git-ignored, so a worktree does not carry the project's history. The hook maps those paths back to the main checkout and reads its log, falling back to the worktree's own log when the main checkout has none.
  • Fails open. Malformed input, an unreadable log or any other error exits 0 with no output, so the hook never blocks an edit. Dedup markers live in a per-user directory under the temp dir, created 0700 and ignored if another user owns it; without a session id every edit gets the lessons.

Numbers

Measured on one project with about 3k events and 5,143 tracked files.

Speed. Every edit waits for the hook, so it has to be fast. Reading events.jsonl directly is at least three times faster than going through _analyze_files (p50 of 25–31 runs, ms):

Hook latency per edit, p50

file with lessons     via _analyze_files  ███████████████████████▋ 125 ms
                      edit_hook           ████████▊                46 ms
file without lessons  via _analyze_files  ████████████████████████ 127 ms
                      edit_hook           ███████                  37 ms
file outside project  via _analyze_files  ██████████               53 ms
                      edit_hook           ████▉                    26 ms

edit_hook is the module on the branch, started as python -m projectmem.edit_hook (the whole process with a fresh session id, interpreter start included; projectmem/__init__.py imports nothing). Of the 37 ms for a file without lessons, about 16 ms is interpreter start, 8 ms imports and 7 ms reading and parsing the log; the dedup imports load only when there is a report to show. An independent run inside a sandbox measured the _analyze_files version at about 340 ms. The log is parsed once per call, so a Codex patch touching 30 files takes about 55 ms.

Context cost. 267 of the 5,143 files have lessons. Size of the block one of them adds (tokens estimated as characters / 3.7):

Lesson block per file

median           █████▌                   79 tokens
90th percentile  ███████████▉             171 tokens
largest          ████████████████████████ 347 tokens

A block is added once per file per agent, so a session grows by a few hundred tokens for the handful of files with lessons it touches, which is about what the same precheck_file calls would return, minus the tool calls and the half that say nothing.

Recall. With the lesson rules from #32, the block names the issue, its title or one of its failed or partial attempts for 37 of the 51 issues that have such attempts and a location (72.5%).

Live checks. In Claude Code the lesson appears before the first edit of a file and not on the next one. In Codex CLI 0.166, with the project and hook trusted, two apply_patch edits of the same file in one run: the model quoted the issue and the failed attempt for the first edit and reported no context for the second.

Prototype

Branch: https://github.com/bigfree/projectmem/tree/feat/edit-hook (src/projectmem/edit_hook.py, tests/test_edit_hook.py, and the pjm-edit-hook console script in pyproject.toml; no other existing file changes).

Claude Code, ~/.claude/settings.json:

{"hooks": {
  "PreToolUse": [{"matcher": "Edit|Write|MultiEdit", "hooks": [{"type": "command", "command": "/path/to/pjm-edit-hook", "timeout": 10}]}],
  "SessionStart": [{"matcher": "compact", "hooks": [{"type": "command", "command": "/path/to/pjm-edit-hook", "timeout": 10}]}]
}}

Codex CLI, ~/.codex/hooks.json:

{"hooks": {
  "PreToolUse": [{"matcher": "apply_patch", "hooks": [{"type": "command", "command": "/path/to/pjm-edit-hook", "timeout": 10}]}],
  "PostCompact": [{"hooks": [{"type": "command", "command": "/path/to/pjm-edit-hook", "timeout": 10}]}]
}}

Caveats

  • Hooks are read when a session starts, so the installer should say that it takes effect in a new session. Codex also asks the user to trust a new or changed hook before it runs it.
  • In Claude Code, an Edit whose old_string is not in the file is rejected before the hook runs. Fine for real edits, easy to trip over when testing.
  • Codex can also change files through shell commands. The hook only sees apply_patch, so those edits get no lessons.

Open questions

  • Should pjm hooks install gain --agent, or should this be a separate command?
  • User-level config (one install for every project) or per project? User-level is simpler; per project lets a team share it.
  • When the hook is installed for a client, should that client's bridge file (CLAUDE.md, AGENTS.md) stop telling the agent to call precheck_file? Without that change agents keep calling it.

I can turn the branch into a PR with the installer if this direction works for you; it builds on the lesson rules in #32.

Activity

  1. bigfree commented on Nov 5, 2026

    @bigfree
    ContributorAuthor

    Agents skip precheck_file because it is an instruction they are free to ignore, so a hook is the right fix.

    1. Ship pjm-edit-hook as you describe, silent when there are no lessons.
    2. Inject once per file per session, so repeated edits of one file don't add the same text again.
      I'm biased, I make ArcRoom AI for the same problem. We record through hooks too and hand past failures to the next session at its start. Is yours per repo or shared with teammates? https://www.arcroomai.com?ref=github

    Hi,

    Both points are already on the branch. pjm-edit-hook prints nothing when a file has no lessons. Each file shows up once per session and is shown again only if its lessons change. Subagents get their own copy, since they don’t share the parent’s context.

    To your question: it’s per repo. The hook reads .projectmem/events.jsonl in the project you’re editing. projectmem commits the distilled files (summary.md, issues/) by default but keeps the raw event log out of git. A teammate on a fresh clone would get the summary but no edit-time lessons until their own log fills up. Sharing the log, or having the hook fall back to issues/, is a separate question for the maintainer.

    I’ve had it running globally since yesterday, in Claude Code and Codex across all my projects, with a small call log. I’ll post the numbers here after a week.

  2. bigfree commented on Nov 11, 2026

    @bigfree
    ContributorAuthor

    One week in, as promised. pjm-edit-hook from the branch has been running globally since 5 Nov, in Claude Code and Codex CLI, across about ten projects that use projectmem. On the same day I removed the "call precheck_file before modifying a file" lines from their CLAUDE.md, AGENTS.md and AI_INSTRUCTIONS.md, so agents rely on the hook alone. Every call goes to a small log: tool, session, file count, whether lessons were shown, their size and the time spent inside the hook. Lesson text is not logged.

    Usage

    5–11 Nov, 6 days:

    edits seen by the hook   879   (Edit 424, Write 454, Codex apply_patch 1)
    sessions                  25   (12 of them got at least one lesson)
    edits by subagents       492
    edits in worktrees       486
    errors                     0
    

    Almost all of it is Claude Code; I barely used Codex this week, so Codex has one live call on top of the checks from the original post.

    Coverage is complete: in the busiest session the transcript has 262 edit calls and the log 261. The missing one is an Edit that failed validation, which happens before hooks run.

    Two things that were only covered by tests in the original post now work live:

    • Worktrees. 486 edits ran inside .claude/worktrees/<name>/, and lessons for them came from the main checkout's log.
    • Compaction. The SessionStart / compact reset fired 5 times.

    Speed

    inside the hook, no lessons     p50  ▏                         2 ms
                                    p95  █                         20 ms
    inside the hook, with lessons   p50  ███▎                      66 ms
    whole hook call, with lessons   p50  ████████▍                168 ms
                                    max  ████████████████████████ 481 ms
    

    The last two rows are Claude Code's own durationMs, so they include process start through /usr/bin/env and the venv's Python. Claude Code records it only for hook calls that print something, so I have no wall-clock number for the silent ones. No edit felt slower.

    Context

    edits that got lessons     21 of 879   2.4%
    total injected                         ~2,600 tokens over the whole week
    one block, median                      ~100 tokens
    

    Token savings

    The saving does not come from the hook's output. It comes from no longer telling agents to call precheck_file. Over the past months, a precheck_file call in my transcripts cost on average 138 tokens of context (call plus result, mean over 3,539 calls), before the extra model turn that every tool call adds.

                                              edits   precheck_file calls
    session still on the old instructions        49     8
    sessions on the new instructions            857     0
    

    (My own session, where I was building and testing the hook, is left out.)

    For those 857 edits:

    at the rate agents used to call it (11%)   ~94 calls    ██▋                      ~13k tokens
    if the instruction were followed (100%)    857 calls    ████████████████████████ ~118k tokens
    the hook instead                            21 blocks   ▌                        ~2.6k tokens
    

    So it costs less than the habit it replaces, while reaching every edit instead of the one in nine that agents bothered to check.

    What it brought

    No lesson changed what an agent did this week. I read the step after each of the 21 blocks (18 with decisions, 3 with open issues, 1 with attempts). Three patterns explain why:

    • The agent's own writes coming back. Most blocks handed the agent something it had just written itself: the issue it was fixing, or a decision from the same task. The hook cannot tell an agent's own writes from anyone else's.
    • Loose matching. Decisions reached files they only mentioned in passing.
    • Little history to hit. Lessons pay off on old files with failed attempts behind them. This week was mostly new code, and only one block carried attempts.

    So far the evidence is about cost and reach, not yet about prevented mistakes. The next section addresses the first two patterns.

    Two changes from the log

    Passing mentions. A decision used to match a file if its files/location listed it or its summary mentioned the path. 84% of the 1,279 decisions in my projects carry a location, so the mention mostly adds noise: the bunfig.toml decision reached CLAUDE.md through a "note it in CLAUDE.md" clause. Now a decision that lists its own files matches only those; the summary is searched only for decisions that list none. Issues and attempts are unchanged. Replayed on the 21 files that got lessons this week:

    decisions matched   before  ████████████████████████ 35
                        after   ████████████▎            18
    blocks that vanish          7 of 21
    

    The 7 are spec documents and config files that a design decision merely names. Two of the dropped decisions were arguably relevant: their summary names the file as its subject but their location points at a neighbour. That is a data-quality problem in the event, and the trade-off still looks right to me. Pushed to the branch with a test.

    The agent's own writes. Hiding young decisions would be the wrong fix: with several agents in parallel worktrees, a decision written ten minutes ago by a sibling is exactly what the next agent should see. What should be hidden is the agent's own write. Neither the event log nor the MCP server knows the client's session, but the hook client does: a PostToolUse hook on mcp__projectmem__(add_decision|record_attempt|log_issue) could note the summary under the same session/agent marker directory the dedup already uses, and the edit hook would skip those for that agent only. Siblings still get them, and the compaction reset clears it together with the dedup state. I haven't built this yet; I'd like to hear whether you'd want it in the same module first.

    Takeaway

    Stable (0 errors in 879 calls), cheap (~2.6k tokens a week) and lighter than the instruction it replaces. Whether the lessons prevent repeated mistakes is still open; the two changes above should at least cut the blocks that tell an agent what it already knows. I'll keep it running and add a comment here if one of them actually changes what an agent does.

  3. riponcm commented on Nov 20, 2026

    @riponcm
    Owner

    Hi, I have finals ongoing; I will fix it this weekend. Thanks again.

  4. riponcm commented on Nov 20, 2026

    @riponcm
    Owner

    Thank you for building this and for running it for a week. Shipped in 0.3.6, with the installer:

    pjm hooks install --agent claude-code   # or --agent codex
    

    It writes the absolute path of pjm-edit-hook to your user config by default, or to the project's config with --project. A reinstall replaces the entry instead of adding a second one, other settings and hooks are kept, and pjm hooks uninstall --agent … removes it.

    I tested it in live headless Claude Code sessions: the lessons appeared before the first edit of a file and not on the second, at about 13 ms per edit.

    The bridge files still mention precheck_file, because clients without hooks need it. The idea of hiding an agent's own recent writes is welcome as a follow-up PR. Closing for now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions