From 42bd23597fa93c0a23c5a468e29e3796ed593a8f Mon Sep 17 00:00:00 2001 From: Bruno Guidolim Date: Sun, 1 Nov 2026 00:24:14 +0100 Subject: [PATCH 1/2] 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 --- CLAUDE.md | 2 +- hooks/kb-gate.mts | 73 ++++++++++++++++++++++++++++++++---- tests/kb-gate.test.mts | 53 +++++++++++++++++++++++++- tests/sync-memories.test.mts | 4 +- 4 files changed, 121 insertions(+), 11 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 8db4f25..1560773 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -40,7 +40,7 @@ Two harness details are load-bearing rather than incidental: **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. -**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. +**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. **Edits are checked against the memories that name the file.** A Write, Edit or NotebookEdit outside `memories/` scans every memory for the file's project-relative path, matched as a whole path, or for its name without the extension, matched as a whole word when the name has two or more words (`HermesManager`, `user_service`, `kb-gate`). Memories name types more often than paths, and one-word names like `index` occur in prose everywhere. There is no qmd call, since that would put a model on every edit. A hit produces a note asking for a KB search on that path or name, with a `vec` line giving the edit's reason, because the search ranks relevance better than any text match. Only a KB search whose text contains the path or the name silences it, for the rest of the session: its results stay in context across turns. A compaction summarizes them away, so a `SessionStart` registration with matcher `compact` stores the `.queries` file's row count in `.kb-gate/.compacted`, and only searches after that row count. Reading one of the memories does not silence it, because a file can be named in many memories and one broad read would hide the rest. The note never denies, in `warn` or `enforce`; `observe` only logs. A path is noted once per turn, at most three notes per turn, and edits outside the project root are skipped. diff --git a/hooks/kb-gate.mts b/hooks/kb-gate.mts index 1bd6d3f..70f18c6 100755 --- a/hooks/kb-gate.mts +++ b/hooks/kb-gate.mts @@ -27,6 +27,19 @@ const FILE_WRITE_TOOLS = ["Write", "Edit", "NotebookEdit"]; const MAX_MEMORY_WRITE_DENIALS_PER_TURN = 3; const MAX_LINKED_NOTES_PER_TURN = 3; const MEMORY_DELETE = /(?:^|[^\w-])(?:rm|unlink|mv)(?=\s)/; +const MEMORY_PATH = /\.claude\/memories(?![\w.-])|(?:^|[\s'"=])memories\//; +// An allowlist of reads, because a script can write a file in more ways than a denylist could name. +const READ_COMMANDS = new Set( + "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( + " ", + ), +); +const WRITE_FLAGS: Record = { + sed: /^-[a-zA-Z]*i|^--in-place/, + sort: /^-o|^--output/, + find: /^-(?:delete|exec|execdir|ok|okdir|fprint0?|fprintf|fls)$/, +}; +const GIT_READS = new Set(["log", "show", "diff", "status", "blame", "grep", "ls-files", "rev-parse", "cat-file"]); const SLASH_SKILL = new RegExp(`(?:^|[\\s>])/(?:[\\w-]+:)?(${Object.keys(MEMORY_SKILL_SCOPES).join("|")})\\b`, "g"); const RETRIEVAL_TOOLS = ["mcp__memory-loop__get", "mcp__memory-loop__multi_get", "Read"]; // qmd heads every returned document with this line, which is the only place a docid or glob resolves to a file. @@ -57,6 +70,38 @@ function escapeRegExp(text: string): string { return text.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); } +function gitSubcommand(args: string[]): string { + for (let index = 0; index < args.length; index++) { + const arg = args[index] ?? ""; + if (arg === "-C" || arg === "-c") index++; + else if (!arg.startsWith("-")) return arg; + } + return ""; +} + +function isReadOnly(command: string): boolean { + if (/\$\(|`|<&\d+|\d*>\s*\/dev\/null/g, " "); + if (plain.includes(">")) return false; + return plain.split(/&&|\|\||[;&|\n]/).every(segment => { + const words = segment.trim().split(/\s+/).filter(Boolean); + while (/^\w+=/.test(words[0] ?? "")) words.shift(); + const [name, ...args] = words; + if (name === undefined) return true; + if (name === "git") return GIT_READS.has(gitSubcommand(args)); + const flag = WRITE_FLAGS[name]; + return READ_COMMANDS.has(name) && !(flag && args.some(arg => flag.test(arg))); + }); +} + +function mentionsDirectory(command: string, directory: string): boolean { + if (!directory) return false; + for (let at = command.indexOf(directory); at >= 0; at = command.indexOf(directory, at + 1)) { + if (!/[\w.-]/.test(command[at + directory.length] ?? "")) return true; + } + return false; +} + function readIfExists(file: string): string | undefined { return existsSync(file) ? attempt(() => read(file)) : ""; } @@ -140,12 +185,23 @@ function gate(): void { const target = payload.tool_input?.file_path || payload.tool_input?.notebook_path || ""; if (target && !isFileWrite && !mentionsMemories(target)) return; const command = String(payload.tool_input?.command ?? ""); - const isMemoryDelete = - event === "PreToolUse" && payload.tool_name === "Bash" && command.includes("memories") && MEMORY_DELETE.test(command); - if (event === "PreToolUse" && payload.tool_name === "Bash" && !isMemoryDelete) return; + const isBash = event === "PreToolUse" && payload.tool_name === "Bash"; + if (isBash && isReadOnly(command)) return; const root = projectRoot(); const memories = `${root}/.claude/memories`; + let bashPhase: "memory_write" | "memory_delete" | undefined; + if (isBash) { + // The symlink's target is what a command shows once the path was resolved, and it may be named anything. + const resolved = attempt(() => realpathSync(memories)); + const fromRoot = resolved && relative(attempt(() => realpathSync(root)) ?? root, resolved); + const touchesMemories = + MEMORY_PATH.test(command) || + (!!resolved && mentionsDirectory(command, resolved)) || + (!!fromRoot && !fromRoot.startsWith("..") && mentionsDirectory(command, fromRoot)); + if (!touchesMemories) return; + bashPhase = MEMORY_DELETE.test(command) ? "memory_delete" : "memory_write"; + } const usage = `${memories}/.usage.tsv`; const state = `${root}/.claude/.kb-gate`; const log = `${root}/.claude/.kb-gate.log`; @@ -366,8 +422,8 @@ mcp__memory-loop__query. return; } - if (isMemoryWrite || isMemoryDelete) { - const phase = isMemoryWrite ? "memory_write" : "memory_delete"; + if (isMemoryWrite || bashPhase) { + const phase = bashPhase ?? "memory_write"; const subject = isMemoryWrite ? realPath(resolve(root, target)) : command.slice(0, 200); function logMemory(decision: string, extra = {}): void { logEvent({ phase, tool: payload.tool_name, target: subject, agent_type: agentType, decision, ...extra }); @@ -381,7 +437,8 @@ mcp__memory-loop__query. }); return; } - const skill = activeMemorySkill(isMemoryWrite); + // A Bash write has no single target and bypasses the skill's Edit-based checks, so no skill authorizes it. + const skill = bashPhase === "memory_write" ? undefined : activeMemorySkill(isMemoryWrite); if (skill) { logMemory("allow", { skill }); return; @@ -401,7 +458,9 @@ mcp__memory-loop__query. permissionDecision: "deny", permissionDecisionReason: isMemoryWrite ? "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." - : "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).", + : bashPhase === "memory_write" + ? "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." + : "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).", }); return; } diff --git a/tests/kb-gate.test.mts b/tests/kb-gate.test.mts index 865e148..c8042bb 100644 --- a/tests/kb-gate.test.mts +++ b/tests/kb-gate.test.mts @@ -264,7 +264,7 @@ test("deleting or moving memories through Bash needs memory-audit", t => { f.skill(); assert.match(denied(f.bash("rm .claude/memories/learning_x.md")).permissionDecisionReason, /memory-audit/); assert.equal(f.lastLog().phase, "memory_delete"); - denied(f.bash("git -C .claude/.memories-repo rm -- memories/learning_x.md")); + denied(f.bash("git -C ../shared rm -- memories/learning_x.md")); denied(f.bash("mv .claude/memories/a.md .claude/memories/b.md")); f.turn(); f.skill("memory-audit"); @@ -273,6 +273,48 @@ test("deleting or moving memories through Bash needs memory-audit", t => { assert.equal(f.lastLog().skill, "memory-audit"); }); +test("Bash writes to memories are denied even under a memory skill, until the budget releases one", t => { + const f = gateFixture(t); + f.turn(); + f.skill(); + f.skill("memory-audit"); + for (const command of [ + "python3 - <<'EOF'\nopen('.claude/memories/learning_x.md', 'w').write('x')\nEOF", + "echo x > .claude/memories/learning_x.md", + "cat a.md > .claude/memories/learning_x.md", + "printf x | tee .claude/memories/learning_x.md", + "sed -i '' 's/a/b/' .claude/memories/learning_x.md", + 'ls .claude/memories; node -e \'require("fs").writeFileSync("x", "")\'', + "git -C ../shared checkout -- memories/learning_x.md", + "cat .claude/memories/a.md & cp b.md .claude/memories/a.md", + ]) { + f.turn(); + assert.match(denied(f.bash(command)).permissionDecisionReason, /Edit or Write/); + assert.equal(f.lastLog().phase, "memory_write"); + } + for (let i = 0; i < 2; i++) denied(f.bash("echo x >> .claude/memories/learning_x.md")); + assert.equal(f.bash("echo x >> .claude/memories/learning_x.md"), ""); + assert.equal(f.lastLog().skip_reason, "budget_turn"); + denied(f.bash("echo x > .claude/memories/learning_x.md", "agent-3")); + assert.equal(f.lastLog().skip_reason, "subagent"); +}); + +test("Bash commands naming a symlinked memories dir by its target are gated", t => { + const f = gateFixture(t); + rmSync(`${f.project}/.claude/memories`, { recursive: true }); + mkdirSync(`${f.project}/.claude/shared/kb`, { recursive: true }); + symlinkSync(`${f.project}/.claude/shared/kb`, `${f.project}/.claude/memories`); + f.turn(); + denied(f.bash(`echo x > ${f.project}/.claude/shared/kb/learning_x.md`)); + assert.equal(f.lastLog().phase, "memory_write"); + denied(f.bash("rm .claude/shared/kb/learning_x.md")); + assert.equal(f.lastLog().phase, "memory_delete"); + const before = readFileSync(f.log, "utf8"); + assert.equal(f.bash("echo x > .claude/shared/kb2/notes.md"), ""); + assert.equal(f.bash("cat .claude/shared/kb/learning_x.md"), ""); + assert.equal(readFileSync(f.log, "utf8"), before); +}); + test("unrelated Bash commands pass without evaluation", t => { const f = gateFixture(t); f.turn(); @@ -283,6 +325,15 @@ test("unrelated Bash commands pass without evaluation", t => { "docker run --rm memories-image", "grep -rn memories . | wc -l", "cat .claude/memories/a.md | grep rm", + 'grep -rn "rm " skills/ | grep memories', + "git commit -m 'Gate Bash writes to memories'", + "echo x > notes/memories.md", + "sed -n '1,20p' .claude/memories/a.md", + "git -C ../shared log --oneline -- memories/a.md", + "git -C .claude/memories rev-parse --show-toplevel", + "find .claude/memories -name '*.md' | sort", + "jq . .claude/memories/x.json 2>/dev/null", + "grep -E 'a|b>c' .claude/memories/a.md 2>&1 | head -5", ]) { assert.equal(f.bash(command), ""); } diff --git a/tests/sync-memories.test.mts b/tests/sync-memories.test.mts index 1af4171..41617cf 100644 --- a/tests/sync-memories.test.mts +++ b/tests/sync-memories.test.mts @@ -33,8 +33,8 @@ for (const linked of [false, true]) { const f = indexer(t); if (linked) { rmSync(`${f.project}/.claude/memories`, { recursive: true }); - mkdirSync(`${f.project}/.claude/.memories-repo/memories`, { recursive: true }); - symlinkSync(".memories-repo/memories", `${f.project}/.claude/memories`); + mkdirSync(`${f.project}/.claude/shared/kb`, { recursive: true }); + symlinkSync("shared/kb", `${f.project}/.claude/memories`); } for (let i = 0; i < 2; i++) { const calls = f.run(); From 00eb67000f4a88d5d088e9752929e1b4634bb0dc Mon Sep 17 00:00:00 2001 From: Bruno Guidolim Date: Sun, 1 Nov 2026 00:47:36 +0100 Subject: [PATCH 2/2] Simplify the Bash memory gate after review - Match the resolved memories dir with escapeRegExp and under() instead of a hand-rolled scan - Skip symlink resolution when the command already names .claude/memories - Key deny reasons by kind and drop a duplicated sub-agent assertion --- hooks/kb-gate.mts | 47 +++++++++++++++++++----------------------- tests/kb-gate.test.mts | 4 +--- 2 files changed, 22 insertions(+), 29 deletions(-) diff --git a/hooks/kb-gate.mts b/hooks/kb-gate.mts index 70f18c6..77a8d39 100755 --- a/hooks/kb-gate.mts +++ b/hooks/kb-gate.mts @@ -39,6 +39,14 @@ const WRITE_FLAGS: Record = { sort: /^-o|^--output/, find: /^-(?:delete|exec|execdir|ok|okdir|fprint0?|fprintf|fls)$/, }; +const MEMORY_DENY_REASONS = { + file_write: + "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.", + bash_write: + "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.", + delete: + "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).", +}; const GIT_READS = new Set(["log", "show", "diff", "status", "blame", "grep", "ls-files", "rev-parse", "cat-file"]); const SLASH_SKILL = new RegExp(`(?:^|[\\s>])/(?:[\\w-]+:)?(${Object.keys(MEMORY_SKILL_SCOPES).join("|")})\\b`, "g"); const RETRIEVAL_TOOLS = ["mcp__memory-loop__get", "mcp__memory-loop__multi_get", "Read"]; @@ -94,14 +102,6 @@ function isReadOnly(command: string): boolean { }); } -function mentionsDirectory(command: string, directory: string): boolean { - if (!directory) return false; - for (let at = command.indexOf(directory); at >= 0; at = command.indexOf(directory, at + 1)) { - if (!/[\w.-]/.test(command[at + directory.length] ?? "")) return true; - } - return false; -} - function readIfExists(file: string): string | undefined { return existsSync(file) ? attempt(() => read(file)) : ""; } @@ -190,17 +190,15 @@ function gate(): void { const root = projectRoot(); const memories = `${root}/.claude/memories`; - let bashPhase: "memory_write" | "memory_delete" | undefined; + let bashKind: "bash_write" | "delete" | undefined; if (isBash) { - // The symlink's target is what a command shows once the path was resolved, and it may be named anything. - const resolved = attempt(() => realpathSync(memories)); - const fromRoot = resolved && relative(attempt(() => realpathSync(root)) ?? root, resolved); - const touchesMemories = - MEMORY_PATH.test(command) || - (!!resolved && mentionsDirectory(command, resolved)) || - (!!fromRoot && !fromRoot.startsWith("..") && mentionsDirectory(command, fromRoot)); - if (!touchesMemories) return; - bashPhase = MEMORY_DELETE.test(command) ? "memory_delete" : "memory_write"; + if (!MEMORY_PATH.test(command)) { + // The symlink's target is what a command shows once the path was resolved, and it may be named anything. + const resolved = attempt(() => realpathSync(memories)); + const spellings = resolved ? [resolved, under(root, resolved)] : []; + if (!spellings.some(dir => dir && new RegExp(`${escapeRegExp(dir)}(?![\\w.-])`).test(command))) return; + } + bashKind = MEMORY_DELETE.test(command) ? "delete" : "bash_write"; } const usage = `${memories}/.usage.tsv`; const state = `${root}/.claude/.kb-gate`; @@ -422,8 +420,9 @@ mcp__memory-loop__query. return; } - if (isMemoryWrite || bashPhase) { - const phase = bashPhase ?? "memory_write"; + const memoryKind = isMemoryWrite ? "file_write" : bashKind; + if (memoryKind) { + const phase = memoryKind === "delete" ? "memory_delete" : "memory_write"; const subject = isMemoryWrite ? realPath(resolve(root, target)) : command.slice(0, 200); function logMemory(decision: string, extra = {}): void { logEvent({ phase, tool: payload.tool_name, target: subject, agent_type: agentType, decision, ...extra }); @@ -438,7 +437,7 @@ mcp__memory-loop__query. return; } // A Bash write has no single target and bypasses the skill's Edit-based checks, so no skill authorizes it. - const skill = bashPhase === "memory_write" ? undefined : activeMemorySkill(isMemoryWrite); + const skill = memoryKind === "bash_write" ? undefined : activeMemorySkill(isMemoryWrite); if (skill) { logMemory("allow", { skill }); return; @@ -456,11 +455,7 @@ mcp__memory-loop__query. logMemory("deny", { denials_turn: spent.length + 1 }); output({ permissionDecision: "deny", - permissionDecisionReason: isMemoryWrite - ? "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." - : bashPhase === "memory_write" - ? "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." - : "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).", + permissionDecisionReason: MEMORY_DENY_REASONS[memoryKind], }); return; } diff --git a/tests/kb-gate.test.mts b/tests/kb-gate.test.mts index c8042bb..6e56392 100644 --- a/tests/kb-gate.test.mts +++ b/tests/kb-gate.test.mts @@ -295,8 +295,6 @@ test("Bash writes to memories are denied even under a memory skill, until the bu for (let i = 0; i < 2; i++) denied(f.bash("echo x >> .claude/memories/learning_x.md")); assert.equal(f.bash("echo x >> .claude/memories/learning_x.md"), ""); assert.equal(f.lastLog().skip_reason, "budget_turn"); - denied(f.bash("echo x > .claude/memories/learning_x.md", "agent-3")); - assert.equal(f.lastLog().skip_reason, "subagent"); }); test("Bash commands naming a symlinked memories dir by its target are gated", t => { @@ -329,7 +327,7 @@ test("unrelated Bash commands pass without evaluation", t => { "git commit -m 'Gate Bash writes to memories'", "echo x > notes/memories.md", "sed -n '1,20p' .claude/memories/a.md", - "git -C ../shared log --oneline -- memories/a.md", + "git -c core.pager=cat log --oneline -- memories/a.md", "git -C .claude/memories rev-parse --show-toplevel", "find .claude/memories -name '*.md' | sort", "jq . .claude/memories/x.json 2>/dev/null",