Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<session>.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.

Expand Down
72 changes: 63 additions & 9 deletions hooks/kb-gate.mts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,27 @@ 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<string, RegExp> = {
sed: /^-[a-zA-Z]*i|^--in-place/,
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"];
// qmd heads every returned document with this line, which is the only place a docid or glob resolves to a file.
Expand Down Expand Up @@ -57,6 +78,30 @@ 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 (/\$\(|`|<</.test(command)) return false;
const plain = command.replace(/'[^']*'|"(?:[^"\\]|\\.)*"/g, "''").replace(/\d*>&\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 readIfExists(file: string): string | undefined {
return existsSync(file) ? attempt(() => read(file)) : "";
}
Expand Down Expand Up @@ -140,12 +185,21 @@ 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 bashKind: "bash_write" | "delete" | undefined;
if (isBash) {
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`;
const log = `${root}/.claude/.kb-gate.log`;
Expand Down Expand Up @@ -366,8 +420,9 @@ mcp__memory-loop__query.
return;
}

if (isMemoryWrite || isMemoryDelete) {
const phase = isMemoryWrite ? "memory_write" : "memory_delete";
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 });
Expand All @@ -381,7 +436,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 = memoryKind === "bash_write" ? undefined : activeMemorySkill(isMemoryWrite);
if (skill) {
logMemory("allow", { skill });
return;
Expand All @@ -399,9 +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."
: "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;
}
Expand Down
51 changes: 50 additions & 1 deletion tests/kb-gate.test.mts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand All @@ -273,6 +273,46 @@ 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");
});

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();
Expand All @@ -283,6 +323,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 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",
"grep -E 'a|b>c' .claude/memories/a.md 2>&1 | head -5",
]) {
assert.equal(f.bash(command), "");
}
Expand Down
4 changes: 2 additions & 2 deletions tests/sync-memories.test.mts
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand Down
Loading