Skip to content

Commit 7346806

Browse files
committed
Deny Bash writes to memory files unless the command only reads
- Gate any Bash command naming a memories path, including a symlinked dir's target, not only deletes - Match memory paths instead of the bare word, so read-only commands mentioning it pass - Drop the shared-memories layout from tests and document the rule in CLAUDE.md
1 parent 05d6c02 commit 7346806

4 files changed

Lines changed: 122 additions & 12 deletions

File tree

‎CLAUDE.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -40,7 +40,7 @@ Two harness details are load-bearing rather than incidental:
4040

4141
**One dispatcher, several registrations.** `hooks/kb-gate.mts` is registered in `techpack.yaml` at most once per event and installed file, and branches on `hook_event_name`, then on `tool_name`. mcs keys a registration on its command string, so a second component on the same event and destination overwrites the first in `settings.json`; `hookEventExists` stays green and doctor only warns about the lost matcher. Tools on one event therefore share a matcher, and a registration that needs different hook settings installs the same source under another name. A contract test asserts the pairs are unique. Matchers are broad on purpose; which agent types count as "discovery" is decided in exactly one place, `GATED_AGENTS`, and which skills authorize memory writes, and for how long, in `MEMORY_SKILL_SCOPES`. `hooks/sync-memories.mts` is likewise registered twice, on SessionStart and UserPromptSubmit.
4242

43-
**Memory writes are gated by skill, per turn.** A file-tool write into `.claude/memories/` is denied unless a memory skill authorizes it. A Bash `rm`, `unlink`, `mv` or `git rm` whose command mentions `memories` is denied unless memory-audit ran, because only the audit deletes, and only after per-batch approval. That check exists for auto mode, where no permission prompt would stop the command. It matches the whole command rather than parsing arguments, since variables, globs and `cd` make parsing easy to evade. The scope is the turn for capture because a session that loaded the skill turns earlier edits from a stale copy and skips its checks. A typed skill command produces no `Skill` tool call, only prompt text, which is why the `UserPromptSubmit` branch scans the prompt as well. This gate ignores `KB_GATE_MODE` except `off`, so its own per-turn denial budget is what keeps a broken `Skill` record from blocking writes forever.
43+
**Memory writes are gated by skill, per turn.** A file-tool write into `.claude/memories/` is denied unless a memory skill authorizes it. A Bash command counts when it names a memories path: `.claude/memories`, a relative `memories/`, or the directory a symlinked `.claude/memories` resolves to. Under that test, `rm`, `unlink`, `mv` or `git rm` is denied unless memory-audit ran, because only the audit deletes, and only after per-batch approval. Any other command is denied outright, whatever skill ran, unless every segment is an allowlisted read with no redirect, heredoc or command substitution: a script can write a file in more ways than a denylist could name, and memory edits belong to Edit/Write under a skill. These checks exist for auto mode, where no permission prompt would stop the command. They match the whole command rather than parsing arguments, since variables, globs and `cd` make parsing easy to evade; the per-turn budget releases a misread command. The path test never names how a team shares memories. The scope is the turn for capture because a session that loaded the skill turns earlier edits from a stale copy and skips its checks. A typed skill command produces no `Skill` tool call, only prompt text, which is why the `UserPromptSubmit` branch scans the prompt as well. This gate ignores `KB_GATE_MODE` except `off`, so its own per-turn denial budget is what keeps a broken `Skill` record from blocking writes forever.
4444

4545
**Both hooks fail open.** Unexpected filesystem or payload errors exit 0 without output. The gate never exits 2, never calls qmd, and logs every evaluation except when disabled or when an uninteresting sub-agent starts. Preserve the append-only query and denial files, monotonic turn counter, and separate per-state/per-turn denial budgets. Gate state is compatible with previous shell installs.
4646

‎hooks/kb-gate.mts‎

Lines changed: 67 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import {
1111
statSync,
1212
writeFileSync,
1313
} from "node:fs";
14-
import { basename, dirname, join, resolve } from "node:path";
14+
import { basename, dirname, join, relative, resolve } from "node:path";
1515
import { attempt, isDirectory, projectRoot, read } from "./shared.mts";
1616

1717
const MODE: string = "__KB_GATE_MODE__";
@@ -26,6 +26,19 @@ const MEMORY_SKILL_SCOPES: Record<string, "turn" | "session"> = { "continuous-le
2626
const MEMORY_WRITE_TOOLS = ["Write", "Edit", "NotebookEdit"];
2727
const MAX_MEMORY_WRITE_DENIALS_PER_TURN = 3;
2828
const MEMORY_DELETE = /(?:^|[^\w-])(?:rm|unlink|mv)(?=\s)/;
29+
const MEMORY_PATH = /\.claude\/memories(?![\w.-])|(?:^|[\s'"=])memories\//;
30+
// An allowlist of reads, because a script can write a file in more ways than a denylist could name.
31+
const READ_COMMANDS = new Set(
32+
"cat head tail less grep egrep rg ugrep ls tree wc stat file diff cmp jq cut tr sort uniq nl column echo printf pwd cd test [ basename dirname realpath readlink shasum md5 sed find".split(
33+
" ",
34+
),
35+
);
36+
const WRITE_FLAGS: Record<string, RegExp> = {
37+
sed: /^-[a-zA-Z]*i|^--in-place/,
38+
sort: /^-o|^--output/,
39+
find: /^-(?:delete|exec|execdir|ok|okdir|fprint0?|fprintf|fls)$/,
40+
};
41+
const GIT_READS = new Set(["log", "show", "diff", "status", "blame", "grep", "ls-files", "rev-parse", "cat-file"]);
2942
const SLASH_SKILL = new RegExp(`(?:^|[\\s>])/(?:[\\w-]+:)?(${Object.keys(MEMORY_SKILL_SCOPES).join("|")})\\b`, "g");
3043
const RETRIEVAL_TOOLS = ["mcp__memory-loop__get", "mcp__memory-loop__multi_get", "Read"];
3144
// qmd heads every returned document with this line, which is the only place a docid or glob resolves to a file.
@@ -52,6 +65,38 @@ function mentionsMemories(path: string): boolean {
5265
return lexical.includes("memories") || realPath(lexical).includes("memories");
5366
}
5467

68+
function gitSubcommand(args: string[]): string {
69+
for (let index = 0; index < args.length; index++) {
70+
const arg = args[index] ?? "";
71+
if (arg === "-C" || arg === "-c") index++;
72+
else if (!arg.startsWith("-")) return arg;
73+
}
74+
return "";
75+
}
76+
77+
function isReadOnly(command: string): boolean {
78+
if (/\$\(|`|<</.test(command)) return false;
79+
const plain = command.replace(/'[^']*'|"(?:[^"\\]|\\.)*"/g, "''").replace(/\d*>&\d+|\d*>\s*\/dev\/null/g, " ");
80+
if (plain.includes(">")) return false;
81+
return plain.split(/&&|\|\||[;&|\n]/).every(segment => {
82+
const words = segment.trim().split(/\s+/).filter(Boolean);
83+
while (/^\w+=/.test(words[0] ?? "")) words.shift();
84+
const [name, ...args] = words;
85+
if (name === undefined) return true;
86+
if (name === "git") return GIT_READS.has(gitSubcommand(args));
87+
const flag = WRITE_FLAGS[name];
88+
return READ_COMMANDS.has(name) && !(flag && args.some(arg => flag.test(arg)));
89+
});
90+
}
91+
92+
function mentionsDirectory(command: string, directory: string): boolean {
93+
if (!directory) return false;
94+
for (let at = command.indexOf(directory); at >= 0; at = command.indexOf(directory, at + 1)) {
95+
if (!/[\w.-]/.test(command[at + directory.length] ?? "")) return true;
96+
}
97+
return false;
98+
}
99+
55100
function readIfExists(file: string): string | undefined {
56101
return existsSync(file) ? attempt(() => read(file)) : "";
57102
}
@@ -134,12 +179,23 @@ function gate(): void {
134179
const target = payload.tool_input?.file_path || payload.tool_input?.notebook_path || "";
135180
if (target && !mentionsMemories(target)) return;
136181
const command = String(payload.tool_input?.command ?? "");
137-
const isMemoryDelete =
138-
event === "PreToolUse" && payload.tool_name === "Bash" && command.includes("memories") && MEMORY_DELETE.test(command);
139-
if (event === "PreToolUse" && payload.tool_name === "Bash" && !isMemoryDelete) return;
182+
const isBash = event === "PreToolUse" && payload.tool_name === "Bash";
183+
if (isBash && isReadOnly(command)) return;
140184

141185
const root = projectRoot();
142186
const memories = `${root}/.claude/memories`;
187+
let bashPhase: "memory_write" | "memory_delete" | undefined;
188+
if (isBash) {
189+
// The symlink's target is what a command shows once the path was resolved, and it may be named anything.
190+
const resolved = attempt(() => realpathSync(memories));
191+
const fromRoot = resolved && relative(attempt(() => realpathSync(root)) ?? root, resolved);
192+
const touchesMemories =
193+
MEMORY_PATH.test(command) ||
194+
(!!resolved && mentionsDirectory(command, resolved)) ||
195+
(!!fromRoot && !fromRoot.startsWith("..") && mentionsDirectory(command, fromRoot));
196+
if (!touchesMemories) return;
197+
bashPhase = MEMORY_DELETE.test(command) ? "memory_delete" : "memory_write";
198+
}
143199
const usage = `${memories}/.usage.tsv`;
144200
const state = `${root}/.claude/.kb-gate`;
145201
const log = `${root}/.claude/.kb-gate.log`;
@@ -282,8 +338,8 @@ mcp__memory-loop__query.
282338
return;
283339
}
284340

285-
if (isMemoryWrite || isMemoryDelete) {
286-
const phase = isMemoryWrite ? "memory_write" : "memory_delete";
341+
if (isMemoryWrite || bashPhase) {
342+
const phase = bashPhase ?? "memory_write";
287343
let subject = command.slice(0, 200);
288344
if (isMemoryWrite) {
289345
subject = realPath(resolve(root, target));
@@ -301,7 +357,8 @@ mcp__memory-loop__query.
301357
});
302358
return;
303359
}
304-
const skill = activeMemorySkill(isMemoryWrite);
360+
// A Bash write has no single target and bypasses the skill's Edit-based checks, so no skill authorizes it.
361+
const skill = bashPhase === "memory_write" ? undefined : activeMemorySkill(isMemoryWrite);
305362
if (skill) {
306363
logMemory("allow", { skill });
307364
return;
@@ -321,7 +378,9 @@ mcp__memory-loop__query.
321378
permissionDecision: "deny",
322379
permissionDecisionReason: isMemoryWrite
323380
? "Memory files are written only through the continuous-learning or memory-audit skill, and continuous-learning has not been invoked in this turn. Invoke Skill(continuous-learning) now and run its search and pre-write checks before retrying. Working from a copy loaded in an earlier turn is what skips them."
324-
: "Memory files are deleted or moved only by the memory-audit skill, after the user approves the batch. Run Skill(memory-audit) and follow its approval step before retrying; to correct a memory instead, edit it through Skill(continuous-learning).",
381+
: bashPhase === "memory_write"
382+
? "Memory files are changed only with Edit or Write, through Skill(continuous-learning) or Skill(memory-audit); a Bash command that may write to .claude/memories/ is denied even when one of them is active. If this command only reads, use the Read tool, or a plain read command (cat, head, grep, ls, sed -n, find, jq, read-only git) with no redirect, heredoc or command substitution."
383+
: "Memory files are deleted or moved only by the memory-audit skill, after the user approves the batch. Run Skill(memory-audit) and follow its approval step before retrying; to correct a memory instead, edit it through Skill(continuous-learning).",
325384
});
326385
return;
327386
}

‎tests/kb-gate.test.mts‎

Lines changed: 52 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -264,7 +264,7 @@ test("deleting or moving memories through Bash needs memory-audit", t => {
264264
f.skill();
265265
assert.match(denied(f.bash("rm .claude/memories/learning_x.md")).permissionDecisionReason, /memory-audit/);
266266
assert.equal(f.lastLog().phase, "memory_delete");
267-
denied(f.bash("git -C .claude/.memories-repo rm -- memories/learning_x.md"));
267+
denied(f.bash("git -C ../shared rm -- memories/learning_x.md"));
268268
denied(f.bash("mv .claude/memories/a.md .claude/memories/b.md"));
269269
f.turn();
270270
f.skill("memory-audit");
@@ -273,6 +273,48 @@ test("deleting or moving memories through Bash needs memory-audit", t => {
273273
assert.equal(f.lastLog().skill, "memory-audit");
274274
});
275275

276+
test("Bash writes to memories are denied even under a memory skill, until the budget releases one", t => {
277+
const f = gateFixture(t);
278+
f.turn();
279+
f.skill();
280+
f.skill("memory-audit");
281+
for (const command of [
282+
"python3 - <<'EOF'\nopen('.claude/memories/learning_x.md', 'w').write('x')\nEOF",
283+
"echo x > .claude/memories/learning_x.md",
284+
"cat a.md > .claude/memories/learning_x.md",
285+
"printf x | tee .claude/memories/learning_x.md",
286+
"sed -i '' 's/a/b/' .claude/memories/learning_x.md",
287+
'ls .claude/memories; node -e \'require("fs").writeFileSync("x", "")\'',
288+
"git -C ../shared checkout -- memories/learning_x.md",
289+
"cat .claude/memories/a.md & cp b.md .claude/memories/a.md",
290+
]) {
291+
f.turn();
292+
assert.match(denied(f.bash(command)).permissionDecisionReason, /Edit or Write/);
293+
assert.equal(f.lastLog().phase, "memory_write");
294+
}
295+
for (let i = 0; i < 2; i++) denied(f.bash("echo x >> .claude/memories/learning_x.md"));
296+
assert.equal(f.bash("echo x >> .claude/memories/learning_x.md"), "");
297+
assert.equal(f.lastLog().skip_reason, "budget_turn");
298+
denied(f.bash("echo x > .claude/memories/learning_x.md", "agent-3"));
299+
assert.equal(f.lastLog().skip_reason, "subagent");
300+
});
301+
302+
test("Bash commands naming a symlinked memories dir by its target are gated", t => {
303+
const f = gateFixture(t);
304+
rmSync(`${f.project}/.claude/memories`, { recursive: true });
305+
mkdirSync(`${f.project}/.claude/shared/kb`, { recursive: true });
306+
symlinkSync(`${f.project}/.claude/shared/kb`, `${f.project}/.claude/memories`);
307+
f.turn();
308+
denied(f.bash(`echo x > ${f.project}/.claude/shared/kb/learning_x.md`));
309+
assert.equal(f.lastLog().phase, "memory_write");
310+
denied(f.bash("rm .claude/shared/kb/learning_x.md"));
311+
assert.equal(f.lastLog().phase, "memory_delete");
312+
const before = readFileSync(f.log, "utf8");
313+
assert.equal(f.bash("echo x > .claude/shared/kb2/notes.md"), "");
314+
assert.equal(f.bash("cat .claude/shared/kb/learning_x.md"), "");
315+
assert.equal(readFileSync(f.log, "utf8"), before);
316+
});
317+
276318
test("unrelated Bash commands pass without evaluation", t => {
277319
const f = gateFixture(t);
278320
f.turn();
@@ -283,6 +325,15 @@ test("unrelated Bash commands pass without evaluation", t => {
283325
"docker run --rm memories-image",
284326
"grep -rn memories . | wc -l",
285327
"cat .claude/memories/a.md | grep rm",
328+
'grep -rn "rm " skills/ | grep memories',
329+
"git commit -m 'Gate Bash writes to memories'",
330+
"echo x > notes/memories.md",
331+
"sed -n '1,20p' .claude/memories/a.md",
332+
"git -C ../shared log --oneline -- memories/a.md",
333+
"git -C .claude/memories rev-parse --show-toplevel",
334+
"find .claude/memories -name '*.md' | sort",
335+
"jq . .claude/memories/x.json 2>/dev/null",
336+
"grep -E 'a|b>c' .claude/memories/a.md 2>&1 | head -5",
286337
]) {
287338
assert.equal(f.bash(command), "");
288339
}

‎tests/sync-memories.test.mts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,8 +33,8 @@ for (const linked of [false, true]) {
3333
const f = indexer(t);
3434
if (linked) {
3535
rmSync(`${f.project}/.claude/memories`, { recursive: true });
36-
mkdirSync(`${f.project}/.claude/.memories-repo/memories`, { recursive: true });
37-
symlinkSync(".memories-repo/memories", `${f.project}/.claude/memories`);
36+
mkdirSync(`${f.project}/.claude/shared/kb`, { recursive: true });
37+
symlinkSync("shared/kb", `${f.project}/.claude/memories`);
3838
}
3939
for (let i = 0; i < 2; i++) {
4040
const calls = f.run();

0 commit comments

Comments
 (0)