Skip to content

Commit b070bc1

Browse files
committed
Send Claude back once when a turn ends with unverified code
Two Claude Code hooks in .claude/settings.json run scripts/guard.mjs. When a turn starts, it records a hash of every file. When Claude stops, it compares: if the turn changed code (not only docs) that pnpm verify hasn't passed, it sends Claude back once, naming the files. The second stop goes through, so Claude can stop on purpose and say what is not verified. Turns that changed nothing, changed only docs, or undid their edits pass. Any error lets the turn through with a message. The same file has ask rules for git push, gh pr merge, and --no-verify, so Claude Code asks before it pushes or merges, also in auto mode. - The guard relies on its own record for "once", not on stop_hook_active, which any Stop hook sets. - Records live in the shared git folder, one per session, with the checkout the turn started in. - scripts/guard.test.mjs runs copies of the guard in throwaway repositories. The helpers moved from verify.test.mjs to test-repo.mjs; no test changed. - Proven in headless Claude Code sessions: an unverified edit was sent back once, and push and merge were refused even when allowed.
1 parent 9ad77e7 commit b070bc1

8 files changed

Lines changed: 439 additions & 58 deletions

File tree

‎.claude/settings.json‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
{
2+
"$schema": "https://json.schemastore.org/claude-code-settings.json",
3+
"permissions": {
4+
"ask": [
5+
"Bash(git push *)",
6+
"Bash(gh pr merge *)",
7+
"Bash(* --no-verify)",
8+
"Bash(* --no-verify *)"
9+
]
10+
},
11+
"hooks": {
12+
"UserPromptSubmit": [
13+
{
14+
"hooks": [
15+
{
16+
"type": "command",
17+
"command": "node \"$CLAUDE_PROJECT_DIR/scripts/guard.mjs\" turn-start",
18+
"timeout": 10
19+
}
20+
]
21+
}
22+
],
23+
"Stop": [
24+
{
25+
"hooks": [
26+
{
27+
"type": "command",
28+
"command": "node \"$CLAUDE_PROJECT_DIR/scripts/guard.mjs\" turn-end",
29+
"timeout": 30
30+
}
31+
]
32+
}
33+
]
34+
}
35+
}

‎CLAUDE.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,9 @@ pnpm tauri build --bundles app # src-tauri/target/release/bundle/macos/Undert
3030
change depends on them, check it in `pnpm tauri dev`, or say it is not verified.
3131
- Never weaken a check to pass it: no skipped or deleted tests, no loosened assertions. If a
3232
check is wrong, stop and say why.
33+
- At the end of a turn that changed code `pnpm verify` hasn't passed, a hook sends you back
34+
once. Run it, or say what is not verified and stop. `git push` and `gh pr merge` ask the
35+
owner first.
3336
- Report what ran, what it showed, and what you did not verify. How this works:
3437
`docs/agents.md`.
3538

‎docs/agents.md‎

Lines changed: 53 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,20 +10,70 @@ is proof; "I read the code" is not.
1010

1111
1. **`pnpm verify`** runs every check, in about 10 seconds, and records the tree when they all
1212
pass.
13-
2. **CI** runs `pnpm verify` on GitHub for every push to `main` and every pull request.
14-
3. **`CLAUDE.md`** tells every agent session what done means and to run `pnpm verify`.
13+
2. **The end-of-turn gate** sends Claude back once when a turn changed code that `pnpm verify`
14+
hasn't passed.
15+
3. **Ask first:** Claude Code asks you before it pushes or merges.
16+
4. **CI** runs `pnpm verify` on GitHub for every push to `main` and every pull request.
17+
5. **`CLAUDE.md`** tells every agent session what done means and to run `pnpm verify`.
1518

1619
## Rules, and what holds them
1720

1821
| Rule | What holds it | How sure |
1922
| --- | --- | --- |
2023
| Types, tests, web build, and Rust format, lint, and tests pass | `pnpm verify`, then CI | Checked. CI shows a red run, but nothing blocks a push to `main`. |
21-
| Run `pnpm verify` before calling work done | `CLAUDE.md` | Asked |
24+
| Run `pnpm verify` before calling work done | The end-of-turn gate, `CLAUDE.md` | Checked once per turn. Claude may stop the second time, and must say what is not verified. |
25+
| Push or merge only when you say so | Claude Code `ask` rules | Checked for the usual commands. A speed bump, not a lock. |
2226
| Never weaken a check to pass it | `CLAUDE.md` | Asked |
2327
| Say what was not verified | `CLAUDE.md` | Asked |
2428

2529
"Asked" means an agent can forget it. Later steps turn some of these into checks.
2630

31+
## The end-of-turn gate
32+
33+
Two Claude Code hooks in `.claude/settings.json` run `scripts/guard.mjs`:
34+
35+
- When a turn starts, it records a hash of every file, as `pnpm verify` does.
36+
- When Claude stops, it compares the tree with that record. If the turn changed code (anything
37+
but docs) and `pnpm verify` hasn't passed on the tree as it is now, it sends Claude back with
38+
the files it changed and what to do.
39+
- It does this **once per turn**. The second stop goes through, so Claude can stop on purpose.
40+
It then has to say what is not verified. Another Stop hook, such as a loop plugin, doesn't turn
41+
it off.
42+
- Turns that changed nothing, changed only docs, or undid their edits go through.
43+
- A turn that changed only CI files can't be verified on your Mac. The gate asks Claude to say so.
44+
45+
**It fails open.** If the guard breaks, it lets the turn through. Usually it shows a message that
46+
starts with "Undertext guard". If it crashes outright or takes too long, Claude Code shows its own
47+
hook error instead. Either way, the turn was not checked.
48+
49+
**Limits:**
50+
51+
- It sees every change in the turn, also yours: an edit you make in another editor while Claude
52+
works counts.
53+
- It checks the checkout it lives in, or a linked worktree of it that the session is in. Edits in
54+
another repository are not checked. A turn that moves to another checkout is not checked, and
55+
the message says so.
56+
- Two sessions in the same checkout see each other's edits. Each may send its Claude back once for
57+
the other's work.
58+
- Only Claude Code runs it. Codex, Amp, and Cursor are not set up here.
59+
60+
Its records live in `.git/undertext/turns/`, one file per session, shared by every worktree. Files
61+
older than a week are deleted. Its tests, in `scripts/guard.test.mjs`, run copies of the guard in throwaway
62+
repositories.
63+
64+
## Ask first
65+
66+
`.claude/settings.json` has `ask` rules for `git push`, `gh pr merge`, and any command with
67+
`--no-verify`. Claude Code then asks you, even in auto mode, and even inside a longer command such
68+
as `cd x && git push`.
69+
70+
- **It is a speed bump.** It matches the commands Claude usually writes. A different form of the
71+
same thing, such as a script that pushes, gets through.
72+
- `--no-verify` skips git hooks. This repository has none today, so that rule guards nothing yet.
73+
It misses the short form, `git commit -n`.
74+
- The real lock would be branch protection on GitHub. You push to `main` yourself, so there is
75+
none.
76+
2777
## `pnpm verify`
2878

2979
It runs, in order, and prints one line per check:

‎scripts/guard.mjs‎

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
// The end-of-turn gate for Claude Code, run by the hooks in .claude/settings.json with the hook's
2+
// JSON on stdin. `turn-start` (UserPromptSubmit) records the tree. `turn-end` (Stop) sends Claude
3+
// back once when the turn changed code that `pnpm verify` hasn't passed. On any error it lets the
4+
// turn through and says why.
5+
import { mkdirSync, readdirSync, readFileSync, realpathSync, rmSync, statSync, writeFileSync } from "node:fs";
6+
import { dirname, join, resolve } from "node:path";
7+
import { fileURLToPath } from "node:url";
8+
9+
const own = realpathSync(resolve(dirname(fileURLToPath(import.meta.url)), ".."));
10+
const WEEK = 7 * 24 * 60 * 60 * 1000;
11+
const list = (paths) => (paths.length > 5 ? `${paths.slice(0, 5).join(", ")} and ${paths.length - 5} more` : paths.join(", "));
12+
13+
/** The checkout this script lives in, or a linked worktree of it that Claude is in. Never another repository. */
14+
function checkout(git, cwd) {
15+
if (!cwd) return own;
16+
try {
17+
const top = realpathSync(git(cwd, "rev-parse", "--show-toplevel").trim());
18+
const common = (dir) => realpathSync(resolve(dir, git(dir, "rev-parse", "--git-common-dir").trim()));
19+
return common(top) === common(own) ? top : own;
20+
} catch {
21+
return own;
22+
}
23+
}
24+
25+
function turnStart({ git, snapshot }, input, file) {
26+
rmSync(file, { force: true }); // if the snapshot fails, turn-end finds no record and says so
27+
mkdirSync(dirname(file), { recursive: true });
28+
for (const name of readdirSync(dirname(file))) {
29+
const path = join(dirname(file), name);
30+
try {
31+
if (Date.now() - statSync(path).mtimeMs > WEEK) rmSync(path, { force: true });
32+
} catch {
33+
// another session removed it first
34+
}
35+
}
36+
const root = checkout(git, input.cwd);
37+
writeFileSync(file, JSON.stringify({ root, ...snapshot(root) }));
38+
return null;
39+
}
40+
41+
function turnEnd({ changedPaths, git, isCiOnly, isDoc, readPass, snapshot }, input, file) {
42+
let start;
43+
try {
44+
start = JSON.parse(readFileSync(file, "utf8"));
45+
} catch {
46+
return { systemMessage: "Undertext guard: no record of this turn's start, so this turn was not checked." };
47+
}
48+
// Once per turn: the second stop goes through, so Claude can stop on purpose and say what's
49+
// unfinished. Not `stop_hook_active`: any Stop hook sets that, and it would turn the gate off.
50+
if (start.blocked) return null;
51+
const root = checkout(git, input.cwd);
52+
if (start.root && root !== start.root) {
53+
return { systemMessage: `Undertext guard: this turn moved from ${start.root} to ${root}, so it was not checked.` };
54+
}
55+
const now = snapshot(root);
56+
const touched = changedPaths(start.files, now.files).filter((path) => !isDoc(path));
57+
if (touched.length === 0) return null; // nothing changed, only docs, or the edits were undone
58+
const pass = readPass(root);
59+
const unverified = pass ? changedPaths(pass.files, now.files).filter((path) => !isDoc(path)) : touched;
60+
if (unverified.length === 0) return null;
61+
62+
writeFileSync(file, JSON.stringify({ ...start, blocked: true }));
63+
const reason = touched.every(isCiOnly)
64+
? `This turn changed CI files (${list(touched)}). Local checks can't see them. Say they are not verified until CI runs, then stop.`
65+
: `This turn changed code that \`pnpm verify\` hasn't passed: ${list(touched)}. Run \`pnpm verify\` and fix what fails. If you are stopping on purpose, say what is not verified, then stop again.`;
66+
return { decision: "block", reason, systemMessage: "Undertext guard: sent Claude back to verify this turn's changes." };
67+
}
68+
69+
try {
70+
// Imported here, so that a broken tree.mjs still ends in the message below.
71+
const tree = await import("./tree.mjs");
72+
const input = JSON.parse(readFileSync(0, "utf8") || "{}");
73+
const event = process.argv[2];
74+
if (event !== "turn-start" && event !== "turn-end") throw new Error(`unknown event "${event}"`);
75+
// One folder for every checkout of this repository, so a session's record is found wherever it ends.
76+
const turns = join(realpathSync(resolve(own, tree.git(own, "rev-parse", "--git-common-dir").trim())), "undertext/turns");
77+
const file = join(turns, `${String(input.session_id ?? "unknown").replace(/[^\w-]/g, "_")}.json`);
78+
const out = event === "turn-start" ? turnStart(tree, input, file) : turnEnd(tree, input, file);
79+
if (out) process.stdout.write(JSON.stringify(out));
80+
} catch (error) {
81+
process.stdout.write(JSON.stringify({ systemMessage: `Undertext guard failed, so it let this turn through: ${error.message}` }));
82+
}

0 commit comments

Comments
 (0)