Skip to content

Commit 440d410

Browse files
MrPickeringclaude
andcommitted
Blocking rules are enforced before a prose edit lands
The PreToolUse hook simulates Edit/Write/MultiEdit (incl. replace_all) on a scene in memory and runs the blocking rules on the current and proposed text through the same evaluator as `weaver check` (scopes, reader text, rulings). It denies an edit only when a blocking rule gets worse, so step-by-step repairs and untouched pre-existing findings still pass. Voice stays advisory; any internal failure fails open, as the other hooks do. Measured: in V1-A's real-host test an AI told to add em dashes "even if a check complains" left 8 in the scene (the post hook runs after the write). With this change, in headless Claude Code with the book's instruction files removed, the same prompt was denied before the write ("count from 0 to 8") and the scene stayed unchanged; 11/11 attack prompts left the book untouched. 107/107 tests (21 new, incl. discrimination); consumer install passes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_011b2uBmyJAFs2WhLj81JJG3 Session-Id: 61e7c924-7a69-4dda-83e6-6e95ffcb326b Agent: claude-code
1 parent 102e76c commit 440d410

6 files changed

Lines changed: 395 additions & 30 deletions

File tree

‎engine/hooks.mjs‎

Lines changed: 68 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,10 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
44
import { isAbsolute, join, relative, resolve } from "node:path";
55
import { countWords, loadScenes } from "./manuscript.mjs";
66
import { readProject } from "./project.mjs";
7-
import { loadRules, runRules } from "./rules.mjs";
7+
import { loadRules, runRules, runRulesForScene } from "./rules.mjs";
88
import { otherPendingChapters } from "./changes.mjs";
99
import { runVoiceCheck } from "./voice.mjs";
10-
import { editGuard, shellGuard, WEAVER_DENY_RULES } from "./guard.mjs";
10+
import { deny, editGuard, shellGuard, WEAVER_DENY_RULES } from "./guard.mjs";
1111

1212
const MATCHER = "Edit|Write|MultiEdit|NotebookEdit";
1313
const SHELL_MATCHER = "Bash|PowerShell";
@@ -77,12 +77,75 @@ function hookScene(payload) {
7777
return { cwd, project, absolute, sceneId: `${Number(sceneId[1])}-${Number(sceneId[2])}` };
7878
}
7979

80-
function preHook(payload, decide) {
80+
function proposedSceneText(payload, current) {
81+
const input = payload.tool_input;
82+
if (payload.tool_name === "Write") return typeof input.content === "string" ? input.content : null;
83+
const edits = payload.tool_name === "MultiEdit" ? input.edits : [input];
84+
if (!Array.isArray(edits) || !edits.length) return null;
85+
let proposed = current;
86+
for (const edit of edits) {
87+
if (!edit || typeof edit.old_string !== "string" || !edit.old_string || typeof edit.new_string !== "string"
88+
|| (edit.replace_all !== undefined && typeof edit.replace_all !== "boolean")) return null;
89+
if (!proposed.includes(edit.old_string)) return null;
90+
// A callback keeps $&, $' and other replacement markers literal.
91+
proposed = edit.replace_all
92+
? proposed.replaceAll(edit.old_string, () => edit.new_string)
93+
: proposed.replace(edit.old_string, () => edit.new_string);
94+
}
95+
return proposed;
96+
}
97+
98+
const numberText = (value) => value.toLocaleString("en-US", { maximumFractionDigits: 6 });
99+
100+
function measurementChange(rule, before, after) {
101+
let detail = `the count from ${before?.count ?? 0} to ${after.count}`;
102+
if (rule.type === "count-per-words") {
103+
detail += ` (rate from ${numberText(before?.value ?? 0)} to ${numberText(after.value)} per ${numberText(rule.per_words)} words; limit ${numberText(rule.max)} per ${numberText(rule.per_words)} words)`;
104+
} else if (rule.type === "sentence-start-share") {
105+
detail += ` (sentence share from ${numberText((before?.value ?? 0) * 100)}% to ${numberText(after.value * 100)}%; limit ${numberText(rule.max_share * 100)}%)`;
106+
} else {
107+
detail += ` (limit ${after.limit})`;
108+
}
109+
return detail;
110+
}
111+
112+
function blockingRuleRegression(rules, before, after) {
113+
for (const rule of rules.filter((rule) => rule.severity === "block")) {
114+
const previous = before.findings.filter((finding) => finding.rule_id === rule.id);
115+
const proposed = after.findings.filter((finding) => finding.rule_id === rule.id);
116+
if (!proposed.length) continue;
117+
// Rank measured units by severity so inserting a paragraph cannot turn an
118+
// unchanged finding into a regression just by moving its paragraph number.
119+
// Compare each rank, not just the maximum or total. Findings come first:
120+
// a short paragraph below min_sentences must not mask a worsening finding.
121+
const measurements = (result) => result.measurements.filter((item) => item.rule_id === rule.id)
122+
.sort((a, b) => Number(b.exceeded) - Number(a.exceeded) || b.value - a.value);
123+
const oldMeasurements = measurements(before);
124+
const newMeasurements = measurements(after).filter((item) => item.exceeded);
125+
const increased = newMeasurements.findIndex((item, index) => item.value > (oldMeasurements[index]?.value ?? 0));
126+
const change = increased >= 0
127+
? measurementChange(rule, oldMeasurements[increased], newMeasurements[increased])
128+
: proposed.length > previous.length ? `blocking findings from ${previous.length} to ${proposed.length}` : null;
129+
if (change) return `${rule.id}: ${rule.message} This edit would change ${change}. Blocking rules can't be waived by the AI; if this is intended, ask the author to rule on it.`;
130+
}
131+
return null;
132+
}
133+
134+
function preHook(payload, decide, compareRules) {
81135
const denial = decide(payload);
82136
if (denial) return denial;
83137
const scene = hookScene(payload);
84138
if (!scene) return null;
85139
const rules = loadRules(scene.cwd).rules;
140+
if (["Edit", "Write", "MultiEdit"].includes(payload.tool_name)) {
141+
const current = readFileSync(scene.absolute, "utf8");
142+
const proposed = proposedSceneText(payload, current);
143+
if (proposed === null) return null;
144+
const before = runRulesForScene(scene.cwd, scene.project, scene.sceneId, current);
145+
const after = runRulesForScene(scene.cwd, scene.project, scene.sceneId, proposed);
146+
const reason = compareRules(rules, before, after);
147+
if (reason) return deny(reason);
148+
}
86149
const editorialPath = join(scene.cwd, "quality", "editorial-rules.md");
87150
const editorial = existsSync(editorialPath) ? readFileSync(editorialPath, "utf8").trim() : "";
88151
const messages = rules.length ? `Rule messages: ${rules.map((rule) => rule.message).join("; ")}` : "Rule messages: none";
@@ -128,10 +191,10 @@ function postHook(payload) {
128191
return null;
129192
}
130193

131-
export function runHook(kind, payload, { decideEdit = editGuard, decideShell = shellGuard } = {}) {
194+
export function runHook(kind, payload, { decideEdit = editGuard, decideShell = shellGuard, compareRules = blockingRuleRegression } = {}) {
132195
try {
133196
if (kind === "shell") return decideShell(payload);
134-
if (kind === "pre") return preHook(payload, decideEdit);
197+
if (kind === "pre") return preHook(payload, decideEdit, compareRules);
135198
return kind === "post" ? postHook(payload) : null;
136199
} catch {
137200
// Malformed payloads and internal errors fail open; doctor reports damage.

‎engine/rules.mjs‎

Lines changed: 46 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
// Copyright 2026 Mark Pickering and PICKBITS LLC. Part of PickBits Weaver.
33
import { existsSync, readFileSync } from "node:fs";
44
import { join } from "node:path";
5-
import { loadScenes, countWords } from "./manuscript.mjs";
5+
import { loadScenes, countWords, extractProse } from "./manuscript.mjs";
66
import { readerText } from "./prose.mjs";
77
import { applyRulings } from "./rulings.mjs";
88

@@ -238,19 +238,27 @@ function sentenceRecords(paragraph, scope) {
238238
return records.sort((a, b) => a.start - b.start);
239239
}
240240

241-
function evaluateRule(rule, scene, paragraphs, unitParagraphs) {
241+
function evaluateRule(rule, scene, paragraphs, unitParagraphs, measurements) {
242242
const findings = [];
243243
const scope = rule.scope || "all";
244+
const measured = (finding, value, exceeded) => {
245+
// Keep below-limit counts too, so a pre-edit comparison can report the
246+
// actual starting count. Ordinary rule findings keep their existing shape.
247+
measurements?.push({ ...finding, value, exceeded });
248+
if (exceeded) findings.push(finding);
249+
};
244250
if (rule.type === "count-per-words") {
245251
const groups = rule.unit === "scene" ? [[scene, paragraphs]] : [[scene, unitParagraphs]];
246252
for (const [, groupParagraphs] of groups) {
247253
const parts = groupParagraphs.flatMap((paragraph) => scopedText(paragraph, scope).map((segment) => ({ paragraph, segment })));
248254
const words = parts.reduce((sum, part) => sum + countWords(part.segment.text), 0);
249255
const matches = parts.flatMap((part) => occurrences(part.segment.text, rule.text).map((match) => ({ ...match, paragraph: part.paragraph })));
250256
const count = matches.length;
251-
if (words > 0 && count * rule.per_words > rule.max * words && count > 0) {
252-
const match = matches[0];
253-
findings.push(makeFinding(rule, scene, match.paragraph, match.index, match.length, { count, limit: rule.max }));
257+
if (groupParagraphs.length) {
258+
const match = matches[0] || { paragraph: groupParagraphs[0], index: 0, length: 0 };
259+
measured(makeFinding(rule, scene, match.paragraph, match.index, match.length, { count, limit: rule.max }),
260+
words > 0 ? count * rule.per_words / words : 0,
261+
words > 0 && count * rule.per_words > rule.max * words && count > 0);
254262
}
255263
}
256264
} else if (rule.type === "phrase-list") {
@@ -274,22 +282,21 @@ function evaluateRule(rule, scene, paragraphs, unitParagraphs) {
274282
for (const paragraph of paragraphs) {
275283
const parts = scopedText(paragraph, scope);
276284
const matches = parts.flatMap((part) => occurrences(part.text, rule.text).map((match) => ({ ...match, index: match.index + part.start })));
277-
if (matches.length > rule.max) {
278-
const match = firstMatchInParagraph(paragraph, matches);
279-
findings.push(makeFinding(rule, scene, paragraph, match.index, match.length, { count: matches.length, limit: rule.max }));
280-
}
285+
const match = firstMatchInParagraph(paragraph, matches);
286+
measured(makeFinding(rule, scene, paragraph, match.index, match.length, { count: matches.length, limit: rule.max }),
287+
matches.length, matches.length > rule.max);
281288
}
282289
} else if (rule.type === "sentence-start-share") {
283290
const records = rule.unit === "paragraph"
284291
? paragraphs.flatMap((paragraph) => [{ paragraph, records: sentenceRecords(paragraph, scope) }])
285292
: [{ paragraph: paragraphs[0], records: paragraphs.flatMap((paragraph) => sentenceRecords(paragraph, scope)) }];
286293
for (const group of records) {
287-
if (group.records.length < rule.min_sentences) continue;
294+
const paragraph = group.paragraph || paragraphs[0];
295+
if (!paragraph) continue;
288296
const wanted = group.records.filter((sentence) => sentenceStart(sentence.text).toLocaleLowerCase() === rule.word.toLocaleLowerCase()).length;
289-
if (wanted / group.records.length > rule.max_share) {
290-
const paragraph = group.paragraph || paragraphs[0];
291-
findings.push(makeFinding(rule, scene, paragraph, group.records[0]?.start || 0, 0, { count: wanted, limit: rule.max_share }));
292-
}
297+
const share = group.records.length ? wanted / group.records.length : 0;
298+
measured(makeFinding(rule, scene, paragraph, group.records[0]?.start || 0, 0, { count: wanted, limit: rule.max_share }),
299+
share, group.records.length >= rule.min_sentences && share > rule.max_share);
293300
}
294301
} else if (rule.type === "repeated-sentence-starts") {
295302
for (const paragraph of paragraphs) {
@@ -300,8 +307,9 @@ function evaluateRule(rule, scene, paragraphs, unitParagraphs) {
300307
let end = runStart + 1;
301308
while (end < records.length && sentenceStart(records[end].text).toLocaleLowerCase() === word) end += 1;
302309
const run = end - runStart;
303-
if (word && run > rule.max_run) {
304-
findings.push(makeFinding(rule, scene, paragraph, records[runStart].start, 0, { count: run, limit: rule.max_run }));
310+
if (word) {
311+
measured(makeFinding(rule, scene, paragraph, records[runStart].start, 0, { count: run, limit: rule.max_run }),
312+
run, run > rule.max_run);
305313
}
306314
runStart = end;
307315
}
@@ -321,13 +329,13 @@ function prepareScene(scene) {
321329
return paragraphs.filter((paragraph) => paragraph.text.trim());
322330
}
323331

324-
export function runRules(root, project, { sceneIds = null } = {}) {
332+
function runRulesOnScenes(root, project, allScenes, { sceneIds = null, includeMeasurements = false } = {}) {
325333
const document = loadRules(root);
326-
const allScenes = loadScenes(root, project);
327334
const wanted = sceneIds ? new Set(sceneIds.map(String)) : null;
328335
const scenes = wanted ? allScenes.filter((scene) => wanted.has(scene.id)) : allScenes;
329336
const prepared = new Map(scenes.map((scene) => [scene.id, prepareScene(scene)]));
330337
const findings = [];
338+
const measurements = includeMeasurements ? [] : null;
331339
const chapterRulesEvaluated = new Set();
332340
for (const scene of scenes) {
333341
const paragraphs = prepared.get(scene.id);
@@ -341,13 +349,30 @@ export function runRules(root, project, { sceneIds = null } = {}) {
341349
if (rule.type === "count-per-words" && rule.unit === "chapter") {
342350
unitParagraphs = scenes.filter((candidate) => candidate.chapter === scene.chapter).flatMap((candidate) => prepared.get(candidate.id));
343351
}
344-
findings.push(...evaluateRule(rule, scene, paragraphs, unitParagraphs));
352+
findings.push(...evaluateRule(rule, scene, paragraphs, unitParagraphs, measurements));
345353
}
346354
}
347-
const filtered = applyRulings(root, project, findings, { kind: "rule", sourceOf: (finding) => finding.rule_id, quoteOf: (finding) => finding.excerpt, scenes: allScenes });
355+
const rulingOptions = { kind: "rule", sourceOf: (finding) => finding.rule_id, quoteOf: (finding) => finding.excerpt, scenes: allScenes };
356+
const filtered = applyRulings(root, project, findings, rulingOptions);
348357
const blocking = filtered.findings.filter((finding) => finding.severity === "block").length;
349358
const warnings = filtered.findings.filter((finding) => finding.severity === "warn").length;
350-
return { ok: blocking === 0, findings: filtered.findings, blocking, warnings, allowed_blocking: filtered.allowed_blocking, rules_checked: document.rules.length };
359+
return {
360+
ok: blocking === 0, findings: filtered.findings, blocking, warnings,
361+
allowed_blocking: filtered.allowed_blocking, rules_checked: document.rules.length,
362+
...(includeMeasurements ? { measurements: applyRulings(root, project, measurements, rulingOptions).findings } : {})
363+
};
364+
}
365+
366+
export function runRules(root, project, options = {}) {
367+
return runRulesOnScenes(root, project, loadScenes(root, project), options);
368+
}
369+
370+
export function runRulesForScene(root, project, sceneId, text) {
371+
const [chapter, scene] = sceneId.split("-").map(Number);
372+
const prose = extractProse(text, `scene ${sceneId}`);
373+
// Like runRules({ sceneIds: [sceneId] }), chapter rules see only this scene.
374+
// Passing it to applyRulings also hashes the proposed passage, not disk text.
375+
return runRulesOnScenes(root, project, [{ id: sceneId, chapter, scene, prose }], { includeMeasurements: true });
351376
}
352377

353378
export function rulesPath() {

‎integrity.json‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131
"engine/export.mjs": "092ad9a4687cf24ca5daa822c844879c8314adc227542cf46ec7b871e43f9f3c",
3232
"engine/findings.mjs": "66cc518f6b9ac605146f4c614b03b37d31418f039947714705db02169fcc5472",
3333
"engine/guard.mjs": "c5022e77ee33b5684d96be93aab7ae66682ae5011c501b217e064025a0a167e2",
34-
"engine/hooks.mjs": "2b2b564150221979e019618435b5ff75795df61332949cc67f6ec2754b6a3fb5",
34+
"engine/hooks.mjs": "c8c7c2f2b60802f2a47fea31a9ffb3afea12d6fa353d29a25f15b0689e1561a7",
3535
"engine/host.mjs": "ddfc819a409e2e9c61189b6c96d2b62204ff8c5686a7bedf8ca743b4a1fd027f",
3636
"engine/identity.mjs": "670f211b093aa783a0d6ed24be566239c438deb9da75e9ef20748e2c1b057364",
3737
"engine/import.mjs": "36b5f8475563d4fd0ea0ca9209d0232598e53d824733137cf46b8dbc2d3a81cc",
@@ -43,7 +43,7 @@
4343
"engine/prose.mjs": "e6c75d599abc9fee5fd494c3cd56798135ae21ee15eb9f16d5c83b7c1c877fcd",
4444
"engine/release.mjs": "609b41f7fc06c2f2fbd2b515bcdf3fab72dd7bfc255107155ab2f1e08167eb0a",
4545
"engine/review.mjs": "c5e31bfff932b7edd10b1b97fd527428fede4c23b175e0e9f4c05c7bf94831c3",
46-
"engine/rules.mjs": "9e663c68825a9e8a8ab3a7d10293085d58c001a7c75edded02b8ea7e382ea8e2",
46+
"engine/rules.mjs": "39967678fe0cf3d0397564bab8d1630c739bdc3d206d9f3dddccf72a7a9e4edf",
4747
"engine/rulings.mjs": "4373a468fb16c63f84aff00d2066b85a42d6d77404289d473b623100a019e74e",
4848
"engine/state.mjs": "de9c2a19393bd886454ad0e62c0cc91940d3fe9bbea7adedb384dd9143d41024",
4949
"engine/studio.mjs": "176ad9e30b2b1a1ce549dc4fbce455d4e6dda9fba2f460bb871f155bea8cac34",

‎test/hooks.test.mjs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ test("hooks pre and post are fail-open and enforce the edited scene", () => {
3232
const payload = JSON.stringify({
3333
cwd: root,
3434
tool_name: "Edit",
35-
tool_input: { file_path: scenePath(root), old_string: "short", new_string: "a much longer replacement" }
35+
tool_input: { file_path: scenePath(root), old_string: "pressure", new_string: "a much greater pressure" }
3636
});
3737
const pre = cli(["hook", "pre"], root, payload);
3838
assert.equal(pre.status, 0, pre.stderr);

0 commit comments

Comments
 (0)