7.4 billion tokens per month. 34 free LLM providers. 635 free model endpoints. All behind one /v1 endpoint, plus any custom OpenAI-compatible endpoint. Smart routing, automatic failover, encrypted keys. Personal experimentation only.
TypeScript
feat(contributing): optional commit checklist hook for Claude Code (#860)
OhOkThisIsFine30480ed975ce
diff --git a/.claude/hooks/contributing-check.mjs b/.claude/hooks/contributing-check.mjsnew file mode 100644index 00000000..ae6c7f07--- /dev/null+++ b/.claude/hooks/contributing-check.mjs@@ -0,0 +1,292 @@+#!/usr/bin/env node+// Optional Claude Code hook. Off unless you wire it up yourself — see the+// "Commit checklist hook" section of CONTRIBUTING.md.+//+// When wired as a PreToolUse hook on Bash and the agent is about to run+// `git commit` or `git push`, this reads CONTRIBUTING.md, extracts the rules+// that bear on a diff, and injects them into the agent's context with an+// instruction to verify them. It does not block the command.+//+// CONTRIBUTING.md is parsed at fire time, so the checklist is whatever the+// file says right now — nothing to regenerate, nothing to go stale.+//+// See what the agent would be told, without wiring anything up:+// node .claude/hooks/contributing-check.mjs --preview++import { readFileSync } from 'node:fs';+import { dirname, join, resolve } from 'node:path';+import { fileURLToPath } from 'node:url';++const repoRoot = join(dirname(fileURLToPath(import.meta.url)), '..', '..');+const sourcePath = join(repoRoot, 'CONTRIBUTING.md');++// Sections describing what to do *after* a change is written are the ones+// worth quoting at commit time. Anything else is excluded by name; a section+// added to CONTRIBUTING.md later is picked up automatically.+//+// "Commit checklist hook" documents this file. Without it here, the hook would+// quote its own setup instructions back at the agent as if they were rules.+export const EXCLUDED_SECTIONS = new Set([+ 'Reporting issues',+ 'Related community work',+ 'Commit checklist hook',+]);++// A paragraph counts as a rule if it is phrased as one.+const DIRECTIVE = /\b(must|should|do not|don't|never|always|before opening a pr|run\b.*\bbefore)\b/i;++// Commands worth re-running before a commit — setup commands (`npm install`,+// `npm run dev`) are not.+const VERIFICATION_COMMAND = /\b(test|build|check:|lint|migration)\b/;++const WATCHED_SUBCOMMANDS = new Set(['commit', 'push']);++// Global git options that consume the following token, so `git -C <dir> push`+// is not read as the subcommand being `<dir>`.+const VALUE_OPTIONS = new Set(['-C', '-c', '--git-dir', '--work-tree', '--namespace', '--exec-path']);++// --- command matching -------------------------------------------------------++// Finds `git commit` / `git push` anywhere in the command line, including+// behind `git -C <dir>`, `&&`, or a leading `cd`. `--dry-run` still counts:+// the checklist is cheap and a dry run usually precedes the real thing.+export function watchedSubcommand(command) {+ const tokens = command.split(/\s+/).filter(Boolean);+ for (let i = 0; i < tokens.length; i++) {+ if (tokens[i].replace(/^["']/, '') !== 'git') continue;+ for (let j = i + 1; j < tokens.length; j++) {+ const token = tokens[j];+ if (VALUE_OPTIONS.has(token)) {+ j++; // skip the option's value+ continue;+ }+ if (token.startsWith('-')) continue;+ if (WATCHED_SUBCOMMANDS.has(token)) return token;+ break; // some other subcommand — not our business+ }+ }+ return null;+}++// --- CONTRIBUTING.md extraction ---------------------------------------------++function stripMarkdown(text) {+ return text+ .replace(/\[([^\]]+)\]\(([^)]+)\)/g, '$1 ($2)') // links keep their target+ .replace(/\*\*([^*]+)\*\*/g, '$1')+ .replace(/(^|\s)\*([^*]+)\*/g, '$1$2')+ .replace(/\s+/g, ' ')+ .trim();+}++function parseSections(markdown) {+ const sections = [];+ let current = { title: null, lines: [] };+ for (const line of markdown.split(/\r?\n/)) {+ const heading = /^##\s+(.*\S)\s*$/.exec(line);+ if (heading) {+ sections.push(current);+ current = { title: heading[1], lines: [] };+ continue;+ }+ current.lines.push(line);+ }+ sections.push(current);+ return sections.filter((section) => section.title !== null);+}++// Splits a section body into fenced code blocks and everything else, so a+// bullet inside a fence is never mistaken for a rule.+function splitFences(lines) {+ const prose = [];+ const fences = [];+ let inFence = false;+ for (const line of lines) {+ if (/^\s*```/.test(line)) {+ inFence = !inFence;+ continue;+ }+ (inFence ? fences : prose).push(line);+ }+ return { prose, fences };+}++// Both extractors carry the prose-line index of each item so the two lists can+// be merged back into document order.+function extractBullets(prose) {+ const bullets = [];+ prose.forEach((line, index) => {+ const bullet = /^\s*[-*]\s+(.*)$/.exec(line);+ if (bullet) {+ bullets.push({ index, text: bullet[1] });+ return;+ }+ // Continuation of the previous bullet: indented, non-empty, mid-list.+ if (bullets.length && /^\s+\S/.test(line)) {+ bullets[bullets.length - 1].text += ' ' + line.trim();+ }+ });+ return bullets+ .map(({ index, text }) => ({ index, text: stripMarkdown(text) }))+ .filter(({ text }) => text);+}++function extractDirectiveParagraphs(prose) {+ const paragraphs = [];+ let buffer = [];+ let start = 0;+ const flush = () => {+ if (buffer.length) paragraphs.push({ index: start, text: buffer.join(' ') });+ buffer = [];+ };+ prose.forEach((line, index) => {+ if (!line.trim() || /^\s*[-*]\s+/.test(line)) return flush();+ if (!buffer.length) start = index;+ buffer.push(line.trim());+ });+ flush();+ return (+ paragraphs+ .map(({ index, text }) => ({ index, text: stripMarkdown(text) }))+ // A paragraph ending in ':' introduces the list that follows; the bullets+ // are the rules, the lead-in is not one.+ .filter(({ text }) => text && !text.endsWith(':') && DIRECTIVE.test(text))+ );+}++// CONTRIBUTING.md documents `db:migration:create` with a sample name. Keep the+// command, drop the sample so it does not read as something to run verbatim.+function normalizeCommand(command) {+ return command+ .replace(/\s+#.*$/, '')+ .replace(/--name=\S+/, '--name=<name>')+ .trim();+}++function extractCommands({ prose, fences }) {+ const commands = new Set();+ for (const line of fences) {+ const command = line.trim();+ if (!command || command.startsWith('#')) continue;+ if (VERIFICATION_COMMAND.test(command)) commands.add(normalizeCommand(command));+ }+ // Commands named inline in prose, e.g. "run `npm run check:i18n` before ...".+ for (const line of prose) {+ for (const [, inline] of line.matchAll(/`([^`]+)`/g)) {+ if (/^(npm|npx|node|\.\/|\.\\)/.test(inline) && VERIFICATION_COMMAND.test(inline)) {+ commands.add(normalizeCommand(inline));+ }+ }+ }+ return [...commands];+}++export function extract(markdown) {+ const rules = [];+ const commands = new Set();++ for (const section of parseSections(markdown)) {+ if (EXCLUDED_SECTIONS.has(section.title)) continue;++ const { prose, fences } = splitFences(section.lines);+ const items = [...extractDirectiveParagraphs(prose), ...extractBullets(prose)].sort(+ (a, b) => a.index - b.index,+ );+ for (const { text } of items) rules.push({ section: section.title, text });+ for (const command of extractCommands({ prose, fences })) commands.add(command);+ }++ return { rules, commands: [...commands] };+}++// --- context construction ---------------------------------------------------++export function buildContext(action, { rules, commands }) {+ // Extraction yielding nothing means CONTRIBUTING.md was restructured past+ // what this parser understands. Say so — silence would read as "all clear".+ if (!rules.length) {+ return `Could not extract any rules from CONTRIBUTING.md before this \`git ${action}\`. Read CONTRIBUTING.md directly and verify the change against it, and mention that .claude/hooks/contributing-check.mjs needs its parser updated.`;+ }++ const bySection = new Map();+ for (const rule of rules) {+ if (!bySection.has(rule.section)) bySection.set(rule.section, []);+ bySection.get(rule.section).push(rule.text);+ }++ const lines = [+ `Before this \`git ${action}\`, verify the repo's own contribution rules have been followed.`,+ 'These are extracted verbatim from CONTRIBUTING.md — treat each one as a check against the actual diff, not a formality.',+ '',+ ];+ for (const [section, texts] of bySection) {+ lines.push(`${section}:`);+ for (const text of texts) lines.push(` - ${text}`);+ lines.push('');+ }+ if (commands.length) {+ lines.push('Verification commands named in CONTRIBUTING.md:');+ for (const command of commands) lines.push(` ${command}`);+ lines.push('');+ }+ lines.push(+ 'Check the staged/committed diff against each rule. If a rule applies and is unmet — no test for a behavior change, unrelated reformatting in the diff, an unverified provider limit or model id, a translation key added to en.json only, an edit to an already-applied migration — fix it or say so explicitly before proceeding. If every applicable rule is satisfied, continue without comment.',+ );+ return lines.join('\n');+}++// --- entry point ------------------------------------------------------------++function readContributing() {+ try {+ return readFileSync(sourcePath, 'utf8');+ } catch {+ return null; // no CONTRIBUTING.md, nothing to enforce+ }+}++function main(argv) {+ if (argv.includes('--preview')) {+ const markdown = readContributing();+ if (markdown === null) {+ console.error(`No CONTRIBUTING.md at ${sourcePath}`);+ return 1;+ }+ const extracted = extract(markdown);+ console.log(buildContext('commit', extracted));+ console.error(+ `\n[${extracted.rules.length} rules, ${extracted.commands.length} commands, ` ++ `${new Set(extracted.rules.map((r) => r.section)).size} sections]`,+ );+ return 0;+ }++ let command = '';+ try {+ command = JSON.parse(readFileSync(0, 'utf8'))?.tool_input?.command ?? '';+ } catch {+ command = ''; // not hook input, or no stdin — nothing to check+ }++ const action = watchedSubcommand(command);+ if (!action) return 0;++ const markdown = readContributing();+ if (markdown === null) return 0;++ process.stdout.write(+ JSON.stringify({+ suppressOutput: true,+ hookSpecificOutput: {+ hookEventName: 'PreToolUse',+ additionalContext: buildContext(action, extract(markdown)),+ },+ }),+ );+ return 0;+}++// Only run when executed directly, so the test can import the parts above.+if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {+ process.exit(main(process.argv.slice(2)));+}diff --git a/.claude/hooks/contributing-check.test.mjs b/.claude/hooks/contributing-check.test.mjsnew file mode 100644index 00000000..b91d47dd--- /dev/null+++ b/.claude/hooks/contributing-check.test.mjs@@ -0,0 +1,133 @@+import assert from 'node:assert/strict';+import { execFileSync } from 'node:child_process';+import { readFileSync } from 'node:fs';+import { dirname, join } from 'node:path';+import { test } from 'node:test';+import { fileURLToPath } from 'node:url';++import { buildContext, extract, watchedSubcommand } from './contributing-check.mjs';++const hookPath = join(dirname(fileURLToPath(import.meta.url)), 'contributing-check.mjs');++test('watchedSubcommand matches the git writes we care about', () => {+ assert.equal(watchedSubcommand('git commit -m x'), 'commit');+ assert.equal(watchedSubcommand('git push origin HEAD'), 'push');+ assert.equal(watchedSubcommand('git commit --amend --no-edit'), 'commit');+ // Chained and prefixed forms: git is not the first token.+ assert.equal(watchedSubcommand('npm test && git push'), 'push');+ assert.equal(watchedSubcommand('cd server; git commit'), 'commit');+ // Global options, including the ones that swallow the next token.+ assert.equal(watchedSubcommand('git -C /repo push'), 'push');+ assert.equal(watchedSubcommand('git -c user.name=x commit'), 'commit');+ assert.equal(watchedSubcommand('git --git-dir=/tmp/x commit'), 'commit');+});++test('watchedSubcommand ignores reads and lookalikes', () => {+ assert.equal(watchedSubcommand('git status'), null);+ assert.equal(watchedSubcommand('git log --grep=commit'), null);+ assert.equal(watchedSubcommand('git diff --stat'), null);+ assert.equal(watchedSubcommand('echo push'), null);+ assert.equal(watchedSubcommand('npm run commit-helper'), null);+ assert.equal(watchedSubcommand(''), null);+});++const FIXTURE = `# Contributing++Intro prose that is not a rule.++## Development loop++\`\`\`bash+npm install+npm test+\`\`\`++Every PR should:++- Include a test, and keep the existing suite green (\`npm test\`).+- Stay scoped to one change.++## Database migrations++Schema changes must use file-per-migration files under+\`server/src/db/migrations/\`.++## Reporting issues++- Include your version and the provider involved.+`;++test('extract pulls bullets, directive paragraphs and commands', () => {+ const { rules, commands } = extract(FIXTURE);+ const texts = rules.map((rule) => rule.text);++ assert.ok(texts.includes('Include a test, and keep the existing suite green (`npm test`).'));+ assert.ok(texts.includes('Stay scoped to one change.'));+ // Multi-line paragraph is joined into one rule.+ assert.ok(+ texts.includes(+ 'Schema changes must use file-per-migration files under `server/src/db/migrations/`.',+ ),+ );+ assert.ok(commands.includes('npm test'));+ // Setup commands are not verification commands.+ assert.ok(!commands.includes('npm install'));+});++test('extract drops excluded sections, lead-ins and non-directive prose', () => {+ const { rules } = extract(FIXTURE);+ const texts = rules.map((rule) => rule.text);++ assert.ok(!rules.some((rule) => rule.section === 'Reporting issues'));+ // "Every PR should:" introduces the list; the bullets are the rules.+ assert.ok(!texts.includes('Every PR should:'));+ assert.ok(!texts.includes('Intro prose that is not a rule.'));+});++test('rules keep document order within a section', () => {+ const order = extract(FIXTURE)+ .rules.filter((rule) => rule.section === 'Development loop')+ .map((rule) => rule.text);+ assert.deepEqual(order, [+ 'Include a test, and keep the existing suite green (`npm test`).',+ 'Stay scoped to one change.',+ ]);+});++test('buildContext says so loudly when nothing could be extracted', () => {+ const context = buildContext('commit', { rules: [], commands: [] });+ assert.match(context, /Could not extract any rules/);+ assert.match(context, /needs its parser updated/);+});++test('the real CONTRIBUTING.md still yields the rules that matter', () => {+ const { rules, commands } = extract(+ readFileSync(join(dirname(hookPath), '..', '..', 'CONTRIBUTING.md'), 'utf8'),+ );+ assert.ok(rules.length > 0, 'expected rules from the repo CONTRIBUTING.md');+ assert.ok(rules.some((rule) => /Include a test/.test(rule.text)));+ assert.ok(commands.includes('npm test'));+ // This file documents the hook; quoting it back at the agent would be noise.+ assert.ok(!rules.some((rule) => rule.section === 'Commit checklist hook'));+});++test('run as a hook, it emits PreToolUse context only for a watched command', () => {+ const run = (command) =>+ execFileSync(process.execPath, [hookPath], {+ input: JSON.stringify({ tool_name: 'Bash', tool_input: { command } }),+ encoding: 'utf8',+ });++ const fired = JSON.parse(run('git commit -m x'));+ assert.equal(fired.hookSpecificOutput.hookEventName, 'PreToolUse');+ assert.match(fired.hookSpecificOutput.additionalContext, /Before this `git commit`/);+ assert.equal(fired.suppressOutput, true);++ assert.equal(run('git status'), '', 'reads must produce no output');+ assert.equal(run('ls'), '', 'non-git commands must produce no output');+});++test('malformed hook input is ignored rather than throwing', () => {+ const output = execFileSync(process.execPath, [hookPath], { input: 'not json', encoding: 'utf8' });+ assert.equal(output, '');+});diff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex e2110477..59d37bff 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -51,6 +51,41 @@ its keys, so run `npm run check:i18n` from `client/` before opening a PR. See[docs/translating.md](docs/translating.md) for the full rules and the settled Chineseterminology.+## Commit checklist hook++Optional, and off by default. If you use [Claude Code](https://claude.com/claude-code), the repo+ships a hook that reads this file and reminds the agent to check its diff against the rules above+before it runs `git commit` or `git push`. It reminds; it does not block.++See what it would say without enabling anything:++```bash+node .claude/hooks/contributing-check.mjs --preview+```++To turn it on, add this to your own `.claude/settings.local.json` — nothing is wired up for you:++```json+{+ "hooks": {+ "PreToolUse": [+ {+ "matcher": "Bash",+ "hooks": [+ {+ "type": "command",+ "command": "node \"${CLAUDE_PROJECT_DIR:-.}/.claude/hooks/contributing-check.mjs\""+ }+ ]+ }+ ]+ }+}+```++This file is parsed when the hook fires, so editing the rules above changes what the agent is told+with no regeneration step.+## AI and LLM-assisted contributionsLLM-assisted PRs are welcome. A lot of this codebase is itself built that way, so there is no stigma here. The bar is the same as for any other PR: you are responsible for what you submit.diff --git a/package.json b/package.jsonindex 3b6ce45f..010c776d 100644--- a/package.json+++ b/package.json@@ -10,8 +10,9 @@"scripts": {"dev": "concurrently --kill-others-on-fail --names server,client \"npm run dev -w server\" \"npm run dev -w client\"","dev:lan": "concurrently --kill-others-on-fail --names server,client \"npm run dev -w server\" \"npm run dev -w client -- --host\"",- "test": "npm run test:bootstrap && npm run test -w server && npm run test -w cli && npm run test -w client --if-present",+ "test": "npm run test:bootstrap && npm run test:hooks && npm run test -w server && npm run test -w cli && npm run test -w client --if-present","test:bootstrap": "node --test scripts/dev-bootstrap.test.mjs",+ "test:hooks": "node --test .claude/hooks/contributing-check.test.mjs","build": "npm run build -w server && npm run build -w cli && npm run build -w client","build:server": "npm run build -w server","test:migrations": "npm run test:migrations -w server",