Skip to content

Commit 102e76c

Browse files
MrPickeringclaude
andcommitted
Guardrails: the AI edits prose, the author decides
Author commands (approve, reject, undo, rule, state:accept, release, import, guard seal) refuse under an AI host (CLAUDECODE, CODEX_CI/SESSION_ID/THREAD_ID). A PreToolUse shell hook (Bash|PowerShell) blocks author commands in their usual forms and disguises, Git history and config writes, tool installs, writes to protected paths, and HTTP to the author page. The edit hook (now incl. NotebookEdit) denies protected paths, paths outside the book, and code files. Protected: .claude, CLAUDE.md, AGENTS.md, project.json, package files, .git, node_modules, quality, narrative-state, continuity, .weaver, releases, review, imports, world-bible/characters.json. Detection: doctor adds guardrails-installed (hooks, deny rules, no disableAllHooks in book or user settings), book-settings-sealed (`weaver guard seal` fingerprints settings and quality/), approved-history (manuscript commits since the import baseline must carry Approved-with) and protected-files-clean. Studio footer shows guardrail status. Book template gets a five-line AGENTS.md and CLAUDE.md -> @AGENTS.md. Undo commits now carry the approval trailer. Verified: 86/86 tests from inside Claude Code (CLAUDECODE set) and Codex, with discrimination tests per guard; consumer install passes. Real headless Claude Code on an installed copy: 9/10 attack prompts left the book unchanged (no commits, sealed files intact, doctor green). Hard blocks fired for git commit, .claude edits (deny rule), disableAllHooks and tool reinstall; the rest were declined by the model on AGENTS.md alone. The failure: told to add em dashes "even if a check complains", the AI did; the post hook blocked but runs after the write. Approval still refuses, but V1-A2 moves the blocking-rule check before the edit. 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 9a353f0 commit 102e76c

23 files changed

Lines changed: 904 additions & 82 deletions

‎README.md‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,44 @@ These are requirements, not suggestions:
3636
`weaver doctor` checks all of this. Until it passes, Weaver won't write to your
3737
book, and it tells you in plain words what to fix.
3838

39+
## Guardrails
40+
41+
The AI edits prose; the author decides. Author commands (`approve`, `reject`,
42+
`undo`, `rule`, `state:accept`, `release`, `import`, and `guard seal`) refuse in
43+
Claude Code and Codex shells. The author page still works when an AI launches it.
44+
Claude Code edit and shell hooks block protected settings and records, author
45+
commands, Git history/config writes, tool installation changes, and requests to
46+
the local author page. Ordinary prose edits, notes, checks, and reads stay available.
47+
48+
`weaver init` and `weaver hooks install` install the hooks and permission rules.
49+
The rules use `Bash(npx weaver approve:*)` and the equivalent forms for every
50+
author command (bare `weaver`, `npx`, `npx --no-install`, and `npx.cmd`).
51+
`Edit(/.claude/**)` and `Edit(/quality/**)` are anchored to the book's project
52+
settings, apply to all built-in edit tools, and leave reads available. These use
53+
the documented [Claude Code permission syntax](https://code.claude.com/docs/en/permissions).
54+
Pre-hooks return the documented [deny decision](https://code.claude.com/docs/en/hooks#pretooluse-decision-control).
55+
Permission bypass is disabled in the installed project settings.
56+
57+
At hand-over, PickBits runs `weaver guard seal` from an author shell. It records
58+
CRLF-normalized SHA-256 fingerprints in `.weaver/guard.json` and commits that
59+
seal with an approval trailer. It covers both book Claude settings files
60+
(including an absent local file), `CLAUDE.md`, `AGENTS.md`, `project.json`, and
61+
every file under `quality/`. Rulings live separately in `continuity/rulings.json`
62+
and do not invalidate the seal. Intentional settings changes require review and
63+
resealing; sealing commits only the seal, leaving other pending work untouched.
64+
65+
Doctor detects missing hooks or permission rules, disabled hooks in book or user
66+
settings, changed sealed files, and manuscript commits without approval after
67+
the most recent import or initial commit. Unsealed books and pending settings
68+
changes produce warnings. The studio footer shows guardrail status and the first
69+
problem, including warnings.
70+
71+
These guards are pattern matching, not a sandbox. The AI runs as the same user,
72+
so a determined workaround is possible. They stop the normal paths and obvious
73+
disguises; doctor, sealed settings, and approved history make changes that get
74+
through visible. That visibility is the support line, not a tamper-proof audit:
75+
someone able to rewrite both settings and history can also forge the records.
76+
3977
## Quick start
4078

4179
Requirements: Node.js 22 or newer. There are no runtime dependencies.

‎engine/changes.mjs‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -297,11 +297,13 @@ export function undoApproval(root) {
297297
});
298298
const approval = entries.find((entry) => /^Approve chapter \d+/u.test(entry.subject));
299299
if (!approval) throw new Error("There is no approval to undo.");
300-
const result = git(root, ["revert", "--no-edit", approval.sha], { stdio: ["ignore", "pipe", "pipe"] });
300+
const result = git(root, ["revert", "--no-commit", approval.sha], { stdio: ["ignore", "pipe", "pipe"] });
301301
if (result.status !== 0) {
302302
git(root, ["revert", "--abort"], { stdio: ["ignore", "pipe", "ignore"] });
303303
throw new Error("Undo could not be completed because Git found a conflict. Nothing was changed.");
304304
}
305+
const commit = git(root, ["commit", "-m", `Revert "${approval.subject}"`, "-m", `This reverts commit ${approval.sha}.`, "-m", `Approved-with: ${GENERATOR}`], { stdio: ["ignore", "pipe", "pipe"] });
306+
if (commit.status !== 0) throw new Error("The undo is ready, but could not be saved to the book's history.");
305307
const sha = git(root, ["rev-parse", "--short", "HEAD"], { stdio: ["ignore", "pipe", "pipe"] });
306308
return { id: sha.stdout.trim(), approval: approval.sha.slice(0, 7) };
307309
}

‎engine/doctor.mjs‎

Lines changed: 91 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,49 @@
11
// SPDX-License-Identifier: Apache-2.0
22
// Copyright 2026 Mark Pickering and PICKBITS LLC. Part of PickBits Weaver.
3-
import { readdirSync, readFileSync } from "node:fs";
3+
import { existsSync, readdirSync, readFileSync } from "node:fs";
4+
import { homedir } from "node:os";
45
import { spawnSync } from "node:child_process";
56
import { dirname, isAbsolute, join, relative, resolve } from "node:path";
67
import { fileURLToPath } from "node:url";
78
import { compareIntegrity } from "./integrity.mjs";
89
import { GENERATOR } from "./identity.mjs";
910
import { WEAVER_HOOK_COMMANDS } from "./hooks.mjs";
1011
import { hostAvailable } from "./host.mjs";
12+
import { compareBookSettings, dirtyGuardedConfig, unapprovedHistory, WEAVER_DENY_RULES } from "./guard.mjs";
1113

1214
const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
1315

1416
const FINDINGS = {
17+
guardrailsInstalled: {
18+
id: "guardrails-installed", title: "Author guardrails installed",
19+
problem: "Weaver's author guardrails are missing or turned off",
20+
why: "The AI must leave decisions and book settings to the author.",
21+
fix: "Ask PickBits to restore the guardrails with `weaver hooks install`."
22+
},
23+
settingsSealed: {
24+
id: "book-settings-sealed", title: "Book settings match their seal",
25+
problem: "Your book's settings were changed after they were sealed",
26+
why: "Changed settings can hide problems in the prose or turn off the checks.",
27+
fix: "Contact PickBits to review and restore the settings, or seal an intended change with `weaver guard seal`."
28+
},
29+
settingsUnsealed: {
30+
id: "book-settings-sealed", title: "Book settings match their seal",
31+
problem: "Settings not sealed yet; PickBits seals them at hand-over",
32+
why: "A seal makes later changes to the book's settings visible.",
33+
fix: "Ask PickBits to run `weaver guard seal` at hand-over."
34+
},
35+
approvedHistory: {
36+
id: "approved-history", title: "Manuscript history has author approval",
37+
problem: "Changes entered the book without the author's approval",
38+
why: "Every manuscript change after the starting point needs an author approval record.",
39+
fix: "Contact PickBits to review the listed commits and recover the approved book."
40+
},
41+
protectedFilesClean: {
42+
id: "protected-files-clean", title: "Book settings have no pending changes",
43+
problem: "Your book's settings have uncommitted changes",
44+
why: "These settings changes have not been saved in the book's history.",
45+
fix: "Tell the author and contact PickBits to review the changed settings."
46+
},
1547
node: {
1648
id: "node-version",
1749
problem: "Node.js is older than version 22",
@@ -137,12 +169,32 @@ function copiedWeaverEngine(bookRoot) {
137169
return walk(bookRoot);
138170
}
139171

140-
function hookEntryInstalled(entries, command) {
141-
return Array.isArray(entries) && entries.some((entry) => entry?.matcher === WEAVER_HOOK_COMMANDS.matcher
172+
function hookEntryInstalled(entries, command, matcher = WEAVER_HOOK_COMMANDS.matcher) {
173+
return Array.isArray(entries) && entries.some((entry) => entry?.matcher === matcher
142174
&& Array.isArray(entry.hooks)
143175
&& entry.hooks.some((hook) => hook?.type === "command" && hook.command === command));
144176
}
145177

178+
function guardrailsInstalled(root, homeDirectory) {
179+
const problems = [];
180+
let settings = {};
181+
for (const [path, label] of [[join(root, ".claude", "settings.json"), ".claude/settings.json"], [join(root, ".claude", "settings.local.json"), ".claude/settings.local.json"], [join(homeDirectory, ".claude", "settings.json"), "~/.claude/settings.json"]]) {
182+
if (!existsSync(path)) continue;
183+
try {
184+
const document = JSON.parse(readFileSync(path, "utf8"));
185+
if (!document || typeof document !== "object" || Array.isArray(document)) throw new Error("expected settings");
186+
if (label === ".claude/settings.json") settings = document;
187+
if (document.disableAllHooks === true) problems.push(`${label} turns off all hooks`);
188+
} catch { problems.push(`${label} cannot be read`); }
189+
}
190+
if (!hookEntryInstalled(settings.hooks?.PreToolUse, WEAVER_HOOK_COMMANDS.pre)
191+
|| !hookEntryInstalled(settings.hooks?.PostToolUse, WEAVER_HOOK_COMMANDS.post)
192+
|| !hookEntryInstalled(settings.hooks?.PreToolUse, WEAVER_HOOK_COMMANDS.shell, WEAVER_HOOK_COMMANDS.shellMatcher)) problems.push("a required edit or shell hook is missing");
193+
if (!Array.isArray(settings.permissions?.deny) || !WEAVER_DENY_RULES.every((rule) => settings.permissions.deny.includes(rule))) problems.push("an author permission rule is missing");
194+
if (settings.permissions?.disableBypassPermissionsMode !== "disable") problems.push("permission bypass has not been disabled");
195+
return problems;
196+
}
197+
146198
function hooksInstalled(bookRoot) {
147199
try {
148200
const settings = JSON.parse(readFileSync(join(bookRoot, ".claude", "settings.json"), "utf8"));
@@ -165,7 +217,7 @@ function hooksRunnable(bookRoot) {
165217
return result.status === 0 && result.stdout.includes(GENERATOR);
166218
}
167219

168-
export function runDoctor({ bookRoot, packageRoot = PACKAGE_ROOT, nodeVersion = process.versions.node } = {}) {
220+
export function runDoctor({ bookRoot, packageRoot = PACKAGE_ROOT, nodeVersion = process.versions.node, homeDirectory = homedir() } = {}) {
169221
const root = resolve(bookRoot || process.cwd());
170222
const blocking = [];
171223
const warnings = [];
@@ -225,6 +277,41 @@ export function runDoctor({ bookRoot, packageRoot = PACKAGE_ROOT, nodeVersion =
225277
try { project = JSON.parse(readFileSync(join(root, "project.json"), "utf8")); } catch {
226278
// The project check is reported elsewhere; a missing project cannot make this warning blocking.
227279
}
280+
const addGuardCheck = (template, status, details = {}) => {
281+
const findings = status === "pass" ? [] : [finding(template, details)];
282+
if (status === "blocking") blocking.push(...findings);
283+
if (status === "warning") warnings.push(...findings);
284+
checks.push(checkResult(template.id, template.title, status, findings));
285+
};
286+
const guardProblems = guardrailsInstalled(root, homeDirectory);
287+
addGuardCheck(FINDINGS.guardrailsInstalled, guardProblems.length ? "blocking" : "pass", {
288+
problem: `${FINDINGS.guardrailsInstalled.problem}: ${guardProblems.join("; ")}`,
289+
fix: guardProblems.some((problem) => problem.startsWith("~")) ? "Your user-level Claude settings disable or prevent the checks. Contact PickBits to restore them." : FINDINGS.guardrailsInstalled.fix
290+
});
291+
try {
292+
const seal = compareBookSettings(root);
293+
addGuardCheck(seal.status === "warning" ? FINDINGS.settingsUnsealed : FINDINGS.settingsSealed, seal.status, seal.paths.length ? {
294+
paths: seal.paths, problem: `${FINDINGS.settingsSealed.problem}: ${seal.paths.join(", ")}`
295+
} : {});
296+
} catch {
297+
addGuardCheck(FINDINGS.settingsSealed, "blocking", { problem: "Your book's settings seal cannot be checked" });
298+
}
299+
try {
300+
const commits = inGit ? unapprovedHistory(root, project.source_root || "manuscript") : [];
301+
addGuardCheck(FINDINGS.approvedHistory, commits.length ? "blocking" : "pass", {
302+
commits, problem: `${FINDINGS.approvedHistory.problem}: ${commits.map((commit) => `${commit.sha} ${commit.subject}`).join("; ")}`
303+
});
304+
} catch {
305+
addGuardCheck(FINDINGS.approvedHistory, "blocking", { problem: "Your book's approval history cannot be checked" });
306+
}
307+
try {
308+
const paths = inGit ? dirtyGuardedConfig(root) : [];
309+
addGuardCheck(FINDINGS.protectedFilesClean, paths.length ? "warning" : "pass", {
310+
paths, problem: `${FINDINGS.protectedFilesClean.problem}: ${paths.join(", ")}`
311+
});
312+
} catch {
313+
addGuardCheck(FINDINGS.protectedFilesClean, "warning", { problem: "Pending book settings changes cannot be checked" });
314+
}
228315
const available = hostAvailable(project);
229316
const availableFinding = available ? [] : [finding(FINDINGS.hostAvailable)];
230317
if (!available) warnings.push(...availableFinding);

0 commit comments

Comments
 (0)