Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
chore(claude): add the commit trailer instead of blocking
Elian Doranc3fb83c79e23
diff --git a/.claude/hooks/check-commit-attribution.mjs b/.claude/hooks/check-commit-attribution.mjsindex 090989533c..19a72eefe0 100644--- a/.claude/hooks/check-commit-attribution.mjs+++ b/.claude/hooks/check-commit-attribution.mjs@@ -1,8 +1,16 @@-// A `PreToolUse` hook (see `.claude/settings.json`): blocks a `git commit` or `git commit-tree`-// whose message lacks the `Assisted-by` trailer that CLAUDE.md requires, naming the model.-import { readFileSync } from "node:fs";+// A `PreToolUse` hook (see `.claude/settings.json`) for the `Assisted-by` trailer that CLAUDE.md+// requires on a `git commit` or `git commit-tree`, naming the model. A commit without it gets the+// trailer added through `--trailer`, with the model read from the transcript. A commit crediting+// Claude with `Co-Authored-By`, or one the hook cannot fix, is blocked.+//+// Dry run, which prints what the hook does with a command and runs nothing:+// node .claude/hooks/check-commit-attribution.mjs --dry-run [--model <id>] [--cwd <dir>] -- <command>+// `--model` defaults to `claude-opus-5-5`; an id of another shape, such as `none`, shows the+// commits the hook blocks when it cannot read the model.+import { closeSync, openSync, readFileSync, readSync, statSync } from "node:fs";import { resolve } from "node:path";import { fileURLToPath } from "node:url";+import { parseArgs } from "node:util";/** `git` at the start of a command, with its global options, running `commit` or `commit-tree`. */const COMMIT = /(?:^|[;&|(\n]\s*)git(?:\s+-[cC]\s+\S+|\s+--\S+)*\s+commit(?:-tree)?(?=\s|$)/g;@@ -11,31 +19,107 @@ const MESSAGE_FLAG = /\s(?:-[a-zA-Z]*[mF]|--message|--file)(?=[\s"'=]|$)/;const FILE_FLAG = /\s(?:-F\s*|--file[=\s]\s*)("[^"]+"|'[^']+'|[^\s;&|]+)/g;const TRAILER = /Assisted-by: Claude Code \([^()<>\n"']+\)/;const CO_AUTHOR = /Co-Authored-By: Claude/i;+/** Every `Assisted-by` line, to tell whether the last one is a Claude Code line without a model. */+const ANY_TRAILER = /Assisted-by: [^\n"']*/g;+const STALE_TRAILER = /^Assisted-by: Claude Code(?: \(<[^>]*>\))?\s*$/;/** `NAME=value` at the start of a command, as `S="…" && git commit -F "$S/msg.txt"` sets. */const ASSIGNMENT = /(?:^|[;&|(\n]\s*)(?:export\s+)?([A-Za-z_]\w*)=("[^"]*"|'[^']*'|[^\s;&|]*)/g;const VARIABLE = /\$\{(\w+)\}|\$(\w+)/g;const GIT_DIR = /\s-C\s+("[^"]*"|'[^']*'|\S+)/g;const SEPARATOR = /&&|\|\|?|;|\n/;const HEREDOC = /<<-?\s*(["']?)(\w+)\1/;+/** A model id such as `claude-opus-5-5`, `claude-fable-5-1[1m]` or `claude-haiku-4-5-20251001`. */+const MODEL_ID = /^claude-([a-z]+)-(\d+)(?:-(\d{1,2}))?(?:-\d{8})?(?:\[[^\]]*\])?$/;+/** How much of the end of the transcript is searched for the model of the last reply. */+const TRANSCRIPT_TAIL = 1024 * 1024;const EXPECTED = "Commit messages written with Claude Code end with a trailer naming the model, "+ "e.g. `Assisted-by: Claude Code (Claude Opus 5.5)`, and never credit it with "+ "`Co-Authored-By` (CLAUDE.md, \"Commit messages\"). Add the trailer and commit again.";-/** Returns why `command` must not run, or `null` when it is not a commit with a bad message. */-export function checkCommand(command, cwd) {+/**+ * What the hook does with `command`: `{ action: "pass" }`, `{ action: "block", reason }`, or+ * `{ action: "rewrite", command, trailer }` with `--trailer` added to each commit that needs it.+ * `modelName` is the display name for the trailer, such as `Claude Opus 5.5`, or `null` when the+ * model is unknown, which blocks a commit that needs the trailer.+ */+export function checkCommand(command, cwd, modelName = null) {// Quoted text is masked, so `git commit` or a separator inside an argument such as a search// pattern is not taken for one, while a quoted `git -C` path still reads as a word.const unquoted = command.replace(QUOTED, (quoted) => "_".repeat(quoted.length));+ const trailer = modelName ? `Assisted-by: Claude Code (${modelName})` : null;+ const insertions = [];for (const match of unquoted.matchAll(COMMIT)) {const start = match.index;const commandEnd = start + match[0].length;const variables = readAssignments(command.slice(0, start));const gitCwd = readGitDirectory(command.slice(start, commandEnd), cwd, variables);const end = findCommitEnd(command, unquoted, commandEnd);- const reason = checkCommit(command.slice(start, end), gitCwd, variables);- if (reason) {- return reason;+ const verdict = checkCommit(command.slice(start, end), gitCwd, variables);+ if (verdict.action === "pass") {+ continue;+ }+ if (verdict.action === "block" || !trailer || match[0].endsWith("-tree")) {+ return { action: "block", reason: verdict.reason };+ }+ const gitEnd = start + match[0].indexOf("git") + "git".length;+ insertions.push(+ { at: gitEnd, text: ` -c trailer.ifexists=${verdict.ifExists}` },+ { at: commandEnd, text: ` --trailer "${trailer}"` }+ );+ }+ if (!insertions.length) {+ return { action: "pass" };+ }+ let rewritten = command;+ for (const { at, text } of insertions.toReversed()) {+ rewritten = rewritten.slice(0, at) + text + rewritten.slice(at);+ }+ return { action: "rewrite", command: rewritten, trailer };+}++/**+ * The display name of a model id, `claude-opus-5-5` → `Claude Opus 5.5`, or `null` for an id+ * of another shape.+ */+export function toModelName(modelId) {+ const match = MODEL_ID.exec(modelId ?? "");+ if (!match) {+ return null;+ }+ const [ , family, major, minor ] = match;+ const version = minor === undefined ? major : `${major}.${minor}`;+ return `Claude ${family[0].toUpperCase()}${family.slice(1)} ${version}`;+}++/** The model of the last assistant reply in the transcript at `path`, or `null`. */+export function readTranscriptModel(path) {+ let text;+ try {+ const size = statSync(path).size;+ const length = Math.min(size, TRANSCRIPT_TAIL);+ const buffer = Buffer.alloc(length);+ const fd = openSync(path, "r");+ try {+ readSync(fd, buffer, 0, length, size - length);+ } finally {+ closeSync(fd);+ }+ text = buffer.toString("utf8");+ } catch {+ return null;+ }+ for (const line of text.split("\n").toReversed()) {+ if (!line.includes("\"assistant\"")) {+ continue;+ }+ try {+ const entry = JSON.parse(line);+ if (entry.type === "assistant" && entry.message?.model) {+ return entry.message.model;+ }+ } catch {+ // The first line of the tail is usually cut off.}}return null;@@ -68,13 +152,20 @@ function findCommitEnd(command, unquoted, from) {return body ? from + separator + body.index + body[0].length : command.length;}+/**+ * `{ action: "pass" }` for a commit that carries the trailer or has no message of its own,+ * `{ action: "block", reason }` for one crediting Claude as co-author, and otherwise+ * `{ action: "fix", reason, ifExists }`, where `ifExists` is the `trailer.ifexists` mode that+ * adds the trailer without repeating it.+ */function checkCommit(args, cwd, variables) {if (!MESSAGE_FLAG.test(args)) {// No message of its own, as with `--amend --no-edit`.- return null;+ return { action: "pass" };}const messages = [ args ];+ let unreadablePath = null;for (const [ , quoted ] of args.matchAll(FILE_FLAG)) {const path = unquote(quoted, variables);if (path === "-") {@@ -82,14 +173,26 @@ function checkCommit(args, cwd, variables) {}const text = readMessage(path, cwd);if (text === null) {- return unreadable(path);+ unreadablePath ??= path;+ } else {+ messages.push(text);}- messages.push(text);}- const hasTrailer = messages.some((text) => TRAILER.test(text));- const hasCoAuthor = messages.some((text) => CO_AUTHOR.test(text));- return hasTrailer && !hasCoAuthor ? null : EXPECTED;+ if (messages.some((text) => CO_AUTHOR.test(text))) {+ return { action: "block", reason: EXPECTED };+ }+ if (messages.some((text) => TRAILER.test(text))) {+ return { action: "pass" };+ }+ // `replace` swaps the `Assisted-by` line nearest the end, so it applies only when that line+ // is the Claude Code one; `addIfDifferent` leaves a matching line written to an unread file.+ const lastTrailer = messages.flatMap((text) => text.match(ANY_TRAILER) ?? []).at(-1);+ return {+ action: "fix",+ reason: unreadablePath ? unreadable(unreadablePath) : EXPECTED,+ ifExists: lastTrailer && STALE_TRAILER.test(lastTrailer) ? "replace" : "addIfDifferent"+ };}/**@@ -134,11 +237,49 @@ function toNativePath(path) {return process.platform === "win32" ? path.replace(/^\/([a-zA-Z])\//, "$1:/") : path;}-if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {+/** Prints what the hook does with the command after `--`, for trying a command without running it. */+function dryRun(argv) {+ const { values, positionals } = parseArgs({+ args: argv,+ options: { "dry-run": { type: "boolean" }, model: { type: "string" }, cwd: { type: "string" } },+ allowPositionals: true+ });+ const modelId = values.model ?? "claude-opus-5-5";+ const result = checkCommand(positionals.join(" "), values.cwd ?? process.cwd(), toModelName(modelId));+ if (result.action === "rewrite") {+ process.stdout.write(`rewrite (${result.trailer}):\n${result.command}\n`);+ } else if (result.action === "block") {+ process.stdout.write(`block:\n${result.reason}\n`);+ } else {+ process.stdout.write("pass\n");+ }+}++function runHook() {const input = JSON.parse(readFileSync(0, "utf8"));- const reason = checkCommand(input.tool_input?.command ?? "", input.cwd ?? process.cwd());- if (reason) {- process.stderr.write(`${reason}\n`);+ const modelName = toModelName(readTranscriptModel(input.transcript_path ?? ""));+ const result = checkCommand(input.tool_input?.command ?? "", input.cwd ?? process.cwd(), modelName);+ if (result.action === "block") {+ process.stderr.write(`${result.reason}\n`);process.exit(2);}+ if (result.action === "rewrite") {+ // No `permissionDecision`, so the rewritten command goes through the usual permission rules.+ process.stdout.write(JSON.stringify({+ hookSpecificOutput: {+ hookEventName: "PreToolUse",+ updatedInput: { ...input.tool_input, command: result.command },+ additionalContext: `The commit attribution hook added \`${result.trailer}\` to the `+ + "commit through `--trailer`."+ }+ }));+ }+}++if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {+ if (process.argv.includes("--dry-run")) {+ dryRun(process.argv.slice(2));+ } else {+ runHook();+ }}diff --git a/.claude/hooks/check-commit-attribution.test.mjs b/.claude/hooks/check-commit-attribution.test.mjsindex d2c57f81fa..01418b5f87 100644--- a/.claude/hooks/check-commit-attribution.test.mjs+++ b/.claude/hooks/check-commit-attribution.test.mjs@@ -7,17 +7,25 @@ import { join } from "node:path";import { describe, it } from "node:test";import { fileURLToPath } from "node:url";-import { checkCommand } from "./check-commit-attribution.mjs";+import { checkCommand, readTranscriptModel, toModelName } from "./check-commit-attribution.mjs";const TRAILER = "Assisted-by: Claude Code (Claude Opus 5.5)";const dir = mkdtempSync(join(tmpdir(), "commit-attribution-"));+const PASS = { action: "pass" };++function blockReason(command, modelName = null) {+ const result = checkCommand(command, dir, modelName);+ assert.equal(result.action, "block", command);+ return result.reason;+}+function message(name, text) {writeFileSync(join(dir, name), text);return name;}-describe("checkCommand", () => {+describe("checkCommand without a model", () => {it("passes commands that do not commit, or commit without a message of their own", () => {for (const command of ["git status --short",@@ -27,7 +35,7 @@ describe("checkCommand", () => {"git commit --amend --no-edit","git commit-graph write"]) {- assert.equal(checkCommand(command, dir), null, command);+ assert.deepEqual(checkCommand(command, dir), PASS, command);}});@@ -40,7 +48,7 @@ describe("checkCommand", () => {`git commit -F - <<'EOF'\nfix(x): y\n\n${TRAILER}\nEOF`,`git commit-tree HEAD^{tree} -p HEAD -F ${good}`]) {- assert.equal(checkCommand(command, dir), null, command);+ assert.deepEqual(checkCommand(command, dir), PASS, command);}});@@ -56,7 +64,7 @@ ${TRAILER}"git commit -F \"$COMMIT_ATTRIBUTION_TEST_DIR/good.txt\"",`S="${dir}"; T="$S/good.txt"; git commit -F "$T"`]) {- assert.equal(checkCommand(command, "."), null, command);+ assert.deepEqual(checkCommand(command, "."), PASS, command);}});@@ -69,7 +77,7 @@ ${TRAILER}"git -C sub -C deeper commit --file=in-deeper.txt",`git -C sub -C "${join(dir, "sub", "deeper")}" commit -F in-deeper.txt`]) {- assert.equal(checkCommand(command, dir), null, command);+ assert.deepEqual(checkCommand(command, dir), PASS, command);}});@@ -79,7 +87,7 @@ ${TRAILER}`git commit -F - <<'EOF'\nfix(x): y\n\n${TRAILER}\nEOF\n`+ "git log -1 | grep \"Co-Authored-By: Claude\""]) {- assert.equal(checkCommand(command, dir), null, command);+ assert.deepEqual(checkCommand(command, dir), PASS, command);}for (const command of [`git commit -m wip && echo "${TRAILER}"`,@@ -87,7 +95,7 @@ ${TRAILER}`git commit -m wip | tee log.txt "${TRAILER}"`,`git commit -m wip\necho "${TRAILER}"`]) {- assert.match(checkCommand(command, dir) ?? "", /Assisted-by: Claude Code \(/, command);+ assert.match(blockReason(command), /Assisted-by: Claude Code \(/, command);}});@@ -102,7 +110,7 @@ ${TRAILER}EOFgit commit -F new.txt`]) {- assert.match(checkCommand(command, dir) ?? "", /Could not read the commit message file/, command);+ assert.match(blockReason(command), /Could not read the commit message file/, command);}});@@ -120,23 +128,123 @@ git commit -F new.txt`"cd sub; git commit --message=wip",`git commit -m a -m "${TRAILER}"; git commit -m b`]) {- assert.match(checkCommand(command, dir) ?? "", /Assisted-by: Claude Code \(/, command);+ assert.match(blockReason(command), /Assisted-by: Claude Code \(/, command);+ }+ });+});++describe("checkCommand with a model", () => {+ const MODEL = "Claude Opus 5.5";+ const ADD = `--trailer "${TRAILER}"`;++ it("adds the trailer to a commit without it, or whose message file does not exist yet", () => {+ message("none.txt", "fix(x): y\n");+ for (const [ command, expected ] of [+ [ "git commit -m wip", `git -c trailer.ifexists=addIfDifferent commit ${ADD} -m wip` ],+ [ "git -C sub commit -F none.txt -- a.ts",+ `git -c trailer.ifexists=addIfDifferent -C sub commit ${ADD} -F none.txt -- a.ts` ],+ [ `cd ${dir} && git commit -F none.txt && git push`,+ `cd ${dir} && git -c trailer.ifexists=addIfDifferent commit ${ADD} -F none.txt && git push` ],+ [ "cat > new.txt <<'EOF'\nfix(x): y\nEOF\ngit commit -F new.txt",+ `cat > new.txt <<'EOF'\nfix(x): y\nEOF\ngit -c trailer.ifexists=addIfDifferent commit ${ADD} -F new.txt` ]+ ]) {+ assert.deepEqual(checkCommand(command, dir, MODEL), { action: "rewrite", command: expected, trailer: TRAILER });}});++ it("replaces a Claude Code line without a model only when it is the last `Assisted-by` line", () => {+ const bare = message("bare.txt", "fix(x): y\n\nAssisted-by: DeepSeek V4\nAssisted-by: Claude Code\n");+ const notLast = message("not-last.txt", "fix(x): y\n\nAssisted-by: Claude Code\nAssisted-by: DeepSeek V4\n");+ const modeOf = (command) => /trailer\.ifexists=(\w+)/.exec(checkCommand(command, dir, MODEL).command)?.[1];+ assert.equal(modeOf(`git commit -F ${bare}`), "replace");+ assert.equal(modeOf("git commit -m \"fix(x): y\" -m \"Assisted-by: Claude Code (<model>)\""), "replace");+ assert.equal(modeOf(`git commit -F ${notLast}`), "addIfDifferent");+ });++ it("rewrites each commit that needs it and leaves the others as they are", () => {+ const { command } = checkCommand(`git commit -m a -m "${TRAILER}"; git commit -m b`, dir, MODEL);+ assert.equal(command, `git commit -m a -m "${TRAILER}"; git -c trailer.ifexists=addIfDifferent commit ${ADD} -m b`);+ });++ it("still passes a good commit and blocks a co-author, a `commit-tree` without the trailer, or an unknown model", () => {+ assert.deepEqual(checkCommand(`git commit -m "fix(x): y" -m "${TRAILER}"`, dir, MODEL), PASS);+ assert.match(blockReason(`git commit -m wip -m "Co-Authored-By: Claude <[email protected]>"`, MODEL), /Co-Authored-By/);+ assert.match(blockReason("git commit-tree HEAD^{tree} -p HEAD -m wip", MODEL), /Assisted-by: Claude Code \(/);+ assert.match(blockReason("git commit -m wip"), /Assisted-by: Claude Code \(/);+ });+});++describe("the model", () => {+ it("names a model id as the trailer does", () => {+ assert.equal(toModelName("claude-opus-5-5"), "Claude Opus 5.5");+ assert.equal(toModelName("claude-fable-5-1[1m]"), "Claude Fable 5.1");+ assert.equal(toModelName("claude-haiku-4-5-20251001"), "Claude Haiku 4.5");+ assert.equal(toModelName("claude-opus-4"), "Claude Opus 4");+ assert.equal(toModelName("gpt-5"), null);+ assert.equal(toModelName(null), null);+ });++ it("reads the model of the last reply from the transcript, or `null` without one", () => {+ const transcript = join(dir, "transcript.jsonl");+ writeFileSync(transcript, [+ { type: "assistant", message: { model: "claude-sonnet-5-5" } },+ { type: "user", message: { content: "\"assistant\"" } },+ { type: "assistant", message: { model: "claude-opus-5-5" } },+ { type: "user", message: { content: "next" } }+ ].map((entry) => JSON.stringify(entry)).join("\n"));+ assert.equal(readTranscriptModel(transcript), "claude-opus-5-5");+ assert.equal(readTranscriptModel(join(dir, "missing.jsonl")), null);+ assert.equal(readTranscriptModel(message("empty.jsonl", "")), null);+ });});describe("the hook", () => {const script = fileURLToPath(new URL("./check-commit-attribution.mjs", import.meta.url));- const run = (command) => spawnSync(process.execPath, [ script ], {- input: JSON.stringify({ tool_name: "Bash", tool_input: { command }, cwd: dir }),+ const transcript = join(dir, "hook-transcript.jsonl");+ writeFileSync(transcript, `${JSON.stringify({ type: "assistant", message: { model: "claude-opus-5-5" } })}\n`);+ const run = (command, transcriptPath = transcript) => spawnSync(process.execPath, [ script ], {+ input: JSON.stringify({+ tool_name: "Bash",+ tool_input: { command, description: "Commit" },+ cwd: dir,+ transcript_path: transcriptPath+ }),encoding: "utf8"});- it("exits with 2 and explains a blocked commit, and with 0 otherwise", () => {- const blocked = run("git commit -m wip");+ it("rewrites a commit without the trailer through `updatedInput`, keeping the other fields", () => {+ const result = run("git commit -m wip");+ assert.equal(result.status, 0);+ const { hookSpecificOutput } = JSON.parse(result.stdout);+ assert.equal(hookSpecificOutput.hookEventName, "PreToolUse");+ assert.equal(hookSpecificOutput.permissionDecision, undefined);+ assert.deepEqual(hookSpecificOutput.updatedInput, {+ command: `git -c trailer.ifexists=addIfDifferent commit --trailer "${TRAILER}" -m wip`,+ description: "Commit"+ });+ assert.match(hookSpecificOutput.additionalContext, /Assisted-by: Claude Code \(Claude Opus 5\.5\)/);+ });++ it("exits with 2 and explains a blocked commit, and with 0 and no output otherwise", () => {+ const blocked = run("git commit -m wip", join(dir, "missing.jsonl"));assert.equal(blocked.status, 2);assert.match(blocked.stderr, /Assisted-by/);- assert.equal(run("git status").status, 0);+ const passed = run("git status");+ assert.equal(passed.status, 0);+ assert.equal(passed.stdout, "");+ });++ it("prints what it does with a command in a dry run, and runs nothing", () => {+ const dryRun = (...args) => spawnSync(process.execPath, [ script, "--dry-run", "--cwd", dir, ...args ], {+ encoding: "utf8"+ }).stdout;+ assert.equal(dryRun("--", "git commit -m wip"),+ `rewrite (${TRAILER}):\ngit -c trailer.ifexists=addIfDifferent commit --trailer "${TRAILER}" -m wip\n`);+ assert.equal(dryRun("--model", "claude-fable-5-1", "--", "git commit -m wip"),+ "rewrite (Assisted-by: Claude Code (Claude Fable 5.1)):\n"+ + "git -c trailer.ifexists=addIfDifferent commit --trailer \"Assisted-by: Claude Code (Claude Fable 5.1)\" -m wip\n");+ assert.match(dryRun("--model", "none", "--", "git commit -m wip"), /^block:\n.*Assisted-by/);+ assert.equal(dryRun("--", "git status"), "pass\n");});});