Skip to content

A self-organizing Obsidian vault that gives AI coding agents persistent memory.

refactor: migrate hook and tooling layer from Python to TypeScript (v5) (#43)

Brenno Ferrari0d84773baf2e
diff --git a/.claude/commands/om-humanize.md b/.claude/commands/om-humanize.md
index 989d3a7..39ddd4f 100644
--- a/.claude/commands/om-humanize.md
+++ b/.claude/commands/om-humanize.md
@@ -76,7 +76,7 @@ Don't show unchanged sections. The user can run `git diff` for the full picture.
- This is NOT "remove AI words from a list." It's "make this sound like the same person who wrote the other notes in this vault."
- If the note is already well-written, say so and make minimal changes. Don't edit for the sake of editing.
- Respect the context — a peer review needs to stay professional even after humanizing. A 1:1 note can be loose.
-- If charcount matters (review content in `perf/`), verify limits after editing with `.claude/scripts/charcount.sh`.
+- If charcount matters (review content in `perf/`), verify limits after editing with `node --experimental-strip-types .claude/scripts/charcount.ts`.
Content to edit:
$ARGUMENTS
diff --git a/.claude/commands/om-review-peer.md b/.claude/commands/om-review-peer.md
index 26816c1..637f5fb 100644
--- a/.claude/commands/om-review-peer.md
+++ b/.claude/commands/om-review-peer.md
@@ -39,7 +39,7 @@ Be explicit about this in the review text. Never overclaim visibility.
### 3. Draft
-For each section, draft within your tool's character limit. Use `.claude/scripts/charcount.sh <file> "<section>" "" <limit>` to verify.
+For each section, draft within your tool's character limit. Use `node --experimental-strip-types .claude/scripts/charcount.ts <file> "<section>" "" <limit>` to verify.
**Project feedback** (per project):
- Lead with your relationship to the work ("worked alongside daily" vs "less direct visibility")
@@ -70,7 +70,7 @@ For each section, draft within your tool's character limit. Use `.claude/scripts
Run these before presenting the draft:
-- [ ] All sections within your tool's character limit (use `charcount.sh <file> "<section>" "" <limit>`)
+- [ ] All sections within your tool's character limit (use `node --experimental-strip-types .claude/scripts/charcount.ts <file> "<section>" "" <limit>`)
- [ ] No PR numbers (e.g., #21579) — describe what was done instead
- [ ] No line counts (e.g., +4,743/-3,362) — these look like an audit
- [ ] No "weekend work visible in timestamps" — don't track when people work
diff --git a/.claude/commands/om-self-review.md b/.claude/commands/om-self-review.md
index 3a5263e..4a91e09 100644
--- a/.claude/commands/om-self-review.md
+++ b/.claude/commands/om-self-review.md
@@ -81,7 +81,7 @@ Before finalizing, review the full picture:
### 6. Quality Checks
-- [ ] All sections within your tool's character limit (use `.claude/scripts/charcount.sh <file> "<section>" "" <limit>`)
+- [ ] All sections within your tool's character limit (use `node --experimental-strip-types .claude/scripts/charcount.ts <file> "<section>" "" <limit>`)
- [ ] Watch for special characters (em-dashes, en-dashes) — some review tools count these as multiple characters
- [ ] Every factual claim backed by vault evidence
- [ ] No fabricated decisions ("chose X over Y" when Y was never considered)
diff --git a/.claude/scripts/charcount.sh b/.claude/scripts/charcount.sh
deleted file mode 100755
index 1f9f2e9..0000000
--- a/.claude/scripts/charcount.sh
+++ /dev/null
@@ -1,56 +0,0 @@
-#!/bin/bash
-set -euo pipefail
-# Count characters in a markdown section, optionally validate against a limit.
-# Usage: charcount.sh <file> <section> [subsection] [limit]
-# Examples:
-# charcount.sh review.md "Project Name" → 847
-# charcount.sh review.md "Project Name" "" 1000 → 847/1000 ✓
-# charcount.sh review.md "Project Name" "" 500 → 847/500 ✗ (over by 347)
-# charcount.sh review.md "Competency Name" "Current Level" 1000
-
-FILE="${1:-}"
-SECTION="${2:-}"
-SUB="${3:-}"
-LIMIT="${4:-}"
-
-if [ -z "$FILE" ] || [ -z "$SECTION" ]; then
- echo "Usage: charcount.sh <file> \"Section Header\" [subsection] [limit]"
- echo " subsection: use \"\" to skip when passing a limit"
- exit 1
-fi
-
-if [ ! -f "$FILE" ]; then
- echo "File not found: $FILE"
- exit 1
-fi
-
-if [ -n "$SUB" ]; then
- MARKER="**${SUB}:**"
- COUNT=$(awk -v section="$SECTION" -v marker="$MARKER" '
- index($0, "### " section) { found=1; next }
- found && /^### / { exit }
- found && index($0, marker) { capture=1; next }
- found && capture && /^\*\*/ { exit }
- found && capture && /^### / { exit }
- found && capture && $0 != "" { print }
- ' "$FILE" | tr -d '\n' | wc -m | tr -d ' ')
-else
- COUNT=$(awk -v section="$SECTION" '
- index($0, "### " section) { found=1; next }
- found && /^### / { exit }
- found && /^## / { exit }
- found && $0 != "" { print }
- ' "$FILE" | tr -d '\n' | wc -m | tr -d ' ')
-fi
-
-if [ -n "$LIMIT" ]; then
- if [ "$COUNT" -le "$LIMIT" ]; then
- echo "${COUNT}/${LIMIT} ✓"
- else
- OVER=$((COUNT - LIMIT))
- echo "${COUNT}/${LIMIT} ✗ (over by ${OVER})"
- exit 1
- fi
-else
- echo "$COUNT"
-fi
diff --git a/.claude/scripts/charcount.ts b/.claude/scripts/charcount.ts
new file mode 100644
index 0000000..72d2d00
--- /dev/null
+++ b/.claude/scripts/charcount.ts
@@ -0,0 +1,44 @@
+#!/usr/bin/env node
+/**
+ * CLI for markdown section character counting.
+ *
+ * Usage: node --experimental-strip-types charcount.ts <file> <section> [subsection] [limit]
+ *
+ * Examples:
+ * charcount.ts review.md "Project Name" → 847
+ * charcount.ts review.md "Project Name" "" 1000 → 847/1000 ✓
+ * charcount.ts review.md "Project Name" "" 500 → 847/500 ✗ (over by 347)
+ * charcount.ts review.md "Competency Name" "Current Level" 1000
+ */
+
+import { readFileSync, existsSync } from "node:fs";
+import { countSection, formatResult } from "./lib/charcount.ts";
+
+const [, , file, section, subArg, limitArg] = process.argv;
+
+if (!file || !section) {
+ process.stderr.write(
+ 'Usage: charcount.ts <file> "Section Header" [subsection] [limit]\n',
+ );
+ process.stderr.write(' subsection: use "" to skip when passing a limit\n');
+ process.exit(1);
+}
+
+if (!existsSync(file)) {
+ process.stderr.write(`File not found: ${file}\n`);
+ process.exit(1);
+}
+
+const sub = subArg ? subArg : undefined;
+const limit = limitArg ? Number(limitArg) : undefined;
+
+if (limit !== undefined && (!Number.isFinite(limit) || limit < 0)) {
+ process.stderr.write(`Invalid limit: ${limitArg}\n`);
+ process.exit(1);
+}
+
+const content = readFileSync(file, { encoding: "utf-8" });
+const count = countSection(content, sub ? { section, sub } : { section });
+const result = formatResult(count, limit);
+process.stdout.write(result.output + "\n");
+process.exit(result.ok ? 0 : 1);
diff --git a/.claude/scripts/classify-message.py b/.claude/scripts/classify-message.py
deleted file mode 100755
index e672548..0000000
--- a/.claude/scripts/classify-message.py
+++ /dev/null
@@ -1,208 +0,0 @@
-#!/usr/bin/env python3
-"""Classify user messages and inject routing hints for Claude.
-
-Architecture: data-driven signal matching. Each signal has a list of trigger
-patterns checked via regex with Latin-letter lookarounds (not \\b). Words can
-appear in multiple signals (explicit overlaps) because the cost of a false
-positive hint is ~0 (Claude ignores irrelevant hints) while a false negative
-means missed routing.
-
-Patterns include English, Japanese, Korean, and Simplified Chinese to support
-multilingual users. The Latin-letter lookaround approach allows mixed
-Latin/CJK text without relying on Python word-boundary behavior.
-"""
-import json
-import sys
-import re
-
-
-# Each signal: name, routing message, and trigger patterns.
-# Patterns are checked with Latin-letter lookarounds — safe for CJK/Latin mixed text.
-# Words MAY appear in multiple signals to express natural category overlaps.
-SIGNALS = [
- {
- "name": "DECISION",
- "message": "DECISION detected — consider creating a Decision Record in work/active/ and logging in work/Index.md Decisions Log",
- "patterns": [
- # English
- "decided", "deciding", "decision", "we chose", "agreed to",
- "let's go with", "the call is", "we're going with",
- # Japanese
- "決定した", "決めた", "合意した",
- # Korean
- "결정했어", "결정했습니다", "합의했어",
- # Chinese
- "决定了", "我们决定", "确定了", "同意",
- ],
- },
- {
- "name": "INCIDENT",
- "message": "INCIDENT detected — consider using /om-incident-capture or creating an incident note in work/incidents/",
- "patterns": [
- # English
- "incident", "outage", "pagerduty", "severity",
- "p0", "p1", "p2", "sev1", "sev2", "postmortem", "rca",
- # Japanese
- "インシデント", "障害",
- # Korean
- "인시던트", "장애",
- # Chinese
- "事件", "故障", "事后分析",
- ],
- },
- {
- "name": "1:1 CONTENT",
- "message": "1:1 CONTENT detected — consider creating a 1-on-1 note in work/1-1/ and updating the person note in org/people/",
- "patterns": [
- # English
- "1:1", "1-1", "1-on-1", "one on one", "1on1",
- "catch up with", "sync with",
- # Japanese
- "ワンオンワン",
- # Korean
- "원온원",
- # Chinese
- "一对一", "单独面谈",
- ],
- },
- {
- "name": "WIN",
- "message": "WIN detected — consider adding to perf/Brag Doc.md with a link to the evidence note",
- "patterns": [
- # Delivery — English (shared with PROJECT UPDATE)
- "shipped", "shipping", "ships",
- "launched", "launching", "launches",
- "completed", "completing", "completes",
- "released", "releasing", "releases",
- "deployed", "deploying", "deploys",
- # Achievement — English
- "achieved", "achieving", "won", "promoted", "praised", "win",
- "kudos", "shoutout", "great feedback", "recognized",
- # Japanese
- "出荷した", "リリースした", "達成した", "褒められた",
- # Korean
- "배포했어", "출시했어", "달성했어", "칭찬받았어",
- # Chinese
- "发布了", "上线了", "完成了", "表扬", "认可",
- ],
- },
- {
- "name": "ARCHITECTURE",
- "message": "ARCHITECTURE discussion — consider creating a reference note in reference/ or a decision record",
- "patterns": [
- # English
- "architecture", "system design", "rfc", "tech spec",
- "trade-off", "design doc", "adr",
- # Japanese
- "アーキテクチャ", "システム設計",
- # Korean
- "아키텍처", "시스템 설계",
- # Chinese
- "架构", "系统设计", "技术规范",
- ],
- },
- {
- "name": "PERSON CONTEXT",
- "message": "PERSON CONTEXT detected — consider updating the relevant person note in org/people/ and linking from the conversation note",
- "patterns": [
- # English
- "told me", "said that", "feedback from", "met with",
- "talked to", "spoke with",
- "mentioned that", "mentioned the", "mentioned a",
- # Japanese
- "言ってた", "フィードバック", "話した",
- # Korean
- "말했어", "피드백", "얘기했어", "언급했어",
- # Chinese
- "说了", "提到", "反馈", "提及",
- ],
- },
- {
- "name": "PROJECT UPDATE",
- "message": "PROJECT UPDATE detected — consider updating the active work note in work/active/ and checking if wins should go to brag doc",
- "patterns": [
- # English
- "project update", "sprint", "milestone",
- # Delivery — English (shared with WIN)
- "shipped", "shipping", "ships", "shipped feature",
- "launched", "launching", "launches",
- "completed", "completing", "completes",
- "released", "releasing", "releases",
- "deployed", "deploying", "deploys",
- # Delivery-only — English (not wins on their own)
- "went live", "rolled out", "rolling out",
- "merged", "merging", "merges",
- "cut the release", "release cut",
- # Japanese
- "スプリント", "マイルストーン", "マージした", "リリースしました",
- # Korean
- "스프린트", "마일스톤", "배포", "릴리스", "병합",
- # Chinese (发布了, 上线 shared with WIN)
- "迭代", "里程碑", "发布了", "上线", "合并了",
- ],
- },
-]
-
-
-def _any_word_match(pattern_words: list, text: str) -> bool:
- """Check if any phrase appears as a whole word/phrase in text.
-
- Uses Latin-letter boundaries instead of \\b. Python's \\b treats CJK
- characters as word characters (\\w), so \\bdecision\\b fails to match
- in "のdecisionについて" (no boundary between Hiragana and Latin).
-
- (?<![a-zA-Z]) and (?![a-zA-Z]) ensure English keywords aren't part of
- a larger English word, while allowing CJK adjacency.
- """
- for phrase in pattern_words:
- if re.search(r'(?<![a-zA-Z])' + re.escape(phrase) + r'(?![a-zA-Z])', text):
- return True
- return False
-
-
-def classify(prompt: str) -> list:
- p = prompt.lower()
- signals = []
- for sig in SIGNALS:
- if _any_word_match(sig["patterns"], p):
- signals.append(sig["message"])
- return signals
-
-
-def main():
- try:
- input_data = json.load(sys.stdin)
- except (ValueError, EOFError, OSError):
- sys.exit(0)
-
- prompt = input_data.get("prompt", "")
- if not isinstance(prompt, str) or not prompt:
- sys.exit(0)
-
- try:
- signals = classify(prompt)
- except Exception:
- sys.exit(0)
-
- if signals:
- hints = "\n".join(f"- {s}" for s in signals)
- output = {
- "hookSpecificOutput": {
- "hookEventName": input_data.get("hook_event_name", "UserPromptSubmit"),
- "additionalContext": (
- "Content classification hints (act on these if the user's message contains relevant info):\n"
- + hints
- + "\n\nRemember: use proper templates, add [[wikilinks]], follow CLAUDE.md conventions."
- )
- }
- }
- json.dump(output, sys.stdout)
- sys.stdout.flush()
-
- sys.exit(0)
-
-if __name__ == "__main__":
- try:
- main()
- except Exception:
- sys.exit(0)
diff --git a/.claude/scripts/classify-message.ts b/.claude/scripts/classify-message.ts
new file mode 100644
index 0000000..28e711e
--- /dev/null
+++ b/.claude/scripts/classify-message.ts
@@ -0,0 +1,49 @@
+#!/usr/bin/env node
+/**
+ * UserPromptSubmit hook — classify user messages and inject routing hints.
+ *
+ * Reads the hook JSON payload from stdin, inspects the `prompt` field for
+ * signal patterns (see lib/signals.ts), and emits a hookSpecificOutput
+ * envelope on stdout with one hint per matched signal. Exits 0 silently on
+ * malformed input, missing prompt, or zero matches.
+ */
+
+import { debug, readStdinJson, writeHookOutput } from "./lib/hook-io.ts";
+import { classify } from "./lib/matcher.ts";
+
+type HookInput = {
+ readonly prompt?: unknown;
+ readonly hook_event_name?: unknown;
+};
+
+const input = await readStdinJson<HookInput>();
+if (!input) {
+ debug("classify: null input (bad/empty stdin)");
+ process.exit(0);
+}
+
+const prompt = input.prompt;
+if (typeof prompt !== "string" || !prompt) {
+ debug(`classify: no usable prompt (type=${typeof prompt})`);
+ process.exit(0);
+}
+
+const signals = classify(prompt);
+debug(`classify: matched ${signals.length} signal(s)`);
+
+if (signals.length > 0) {
+ const hints = signals.map((s) => `- ${s}`).join("\n");
+ const additionalContext =
+ "Content classification hints (act on these if the user's message contains relevant info):\n" +
+ hints +
+ "\n\nRemember: use proper templates, add [[wikilinks]], follow CLAUDE.md conventions.";
+
+ const eventName =
+ typeof input.hook_event_name === "string"
+ ? input.hook_event_name
+ : "UserPromptSubmit";
+
+ writeHookOutput(eventName, additionalContext);
+}
+
+process.exit(0);
diff --git a/.claude/scripts/find-python.sh b/.claude/scripts/find-python.sh
deleted file mode 100644
index 9174dda..0000000
--- a/.claude/scripts/find-python.sh
+++ /dev/null
@@ -1,16 +0,0 @@
-#!/usr/bin/env bash
-# Cross-platform Python resolver
-# Windows: skip python3 (Windows Store stub is unreliable), use python directly
-# macOS/Linux: prefer python3, fall back to python
-case "$(uname -s)" in
- MINGW*|MSYS*|CYGWIN*)
- exec python "$@"
- ;;
- *)
- if command -v python3 >/dev/null 2>&1; then
- exec python3 "$@"
- else
- exec python "$@"
- fi
- ;;
-esac
diff --git a/.claude/scripts/lib/charcount.ts b/.claude/scripts/lib/charcount.ts
new file mode 100644
index 0000000..4ee00b1
--- /dev/null
+++ b/.claude/scripts/lib/charcount.ts
@@ -0,0 +1,68 @@
+/**
+ * Markdown section character counting.
+ *
+ * Extracts the body of a `### <section>` heading (optionally scoped to a
+ * `**<sub>:**` marker inside it) and returns the character count with
+ * newlines stripped. Used by review-writing workflows to enforce section
+ * length budgets.
+ *
+ * Section body ends at the next `### ` or `## ` heading. When a sub-marker
+ * is given, capture starts at that marker and ends at the next `**` line
+ * (the next bold marker) or at a heading boundary.
+ */
+
+export type CountArgs = {
+ readonly section: string;
+ readonly sub?: string;
+};
+
+export function countSection(content: string, args: CountArgs): number {
+ const lines = content.split("\n");
+ const sectionHeader = `### ${args.section}`;
+ const marker = args.sub ? `**${args.sub}:**` : null;
+
+ let inSection = false;
+ let capturing = marker === null;
+ const captured: string[] = [];
+
+ for (const line of lines) {
+ if (!inSection) {
+ if (line.includes(sectionHeader)) inSection = true;
+ continue;
+ }
+
+ // Exit on next top-level heading
+ if (line.startsWith("### ")) break;
+ if (marker === null && line.startsWith("## ")) break;
+
+ if (marker !== null) {
+ if (!capturing) {
+ if (line.includes(marker)) capturing = true;
+ continue;
+ }
+ // Capturing under a marker — stop at next bold marker or heading
+ if (line.startsWith("**")) break;
+ if (line.startsWith("### ")) break;
+ }
+
+ if (line !== "") captured.push(line);
+ }
+
+ return captured.join("").length;
+}
+
+export type FormatResult = {
+ readonly ok: boolean;
+ readonly output: string;
+};
+
+export function formatResult(count: number, limit?: number): FormatResult {
+ if (limit === undefined) {
+ return { ok: true, output: String(count) };
+ }
+ if (count <= limit) {
+ return { ok: true, output: `${count}/${limit} ✓` };
+ }
+ const over = count - limit;
+ return { ok: false, output: `${count}/${limit} ✗ (over by ${over})` };
+}
diff --git a/.claude/scripts/lib/frontmatter.ts b/.claude/scripts/lib/frontmatter.ts
new file mode 100644
index 0000000..300146e
--- /dev/null
+++ b/.claude/scripts/lib/frontmatter.ts
@@ -0,0 +1,96 @@
+/**
+ * Validation logic for the validate-write hook: path skip rules, required
+ * frontmatter fields, and wikilink presence on non-trivial notes.
+ */
+
+import { basename } from "node:path";
+import { readFileSync } from "node:fs";
+
+const ROOT_FILES: ReadonlySet<string> = new Set([
+ "README.md",
+ "CHANGELOG.md",
+ "CONTRIBUTING.md",
+ "CLAUDE.md",
+ "AGENTS.md",
+ "GEMINI.md",
+]);
+
+const SKIP_PATH_SEGMENTS: readonly string[] = [
+ ".claude/",
+ ".codex/",
+ ".gemini/",
+ ".github/",
+ ".obsidian/",
+ "templates/",
+ "thinking/",
+];
+
+/**
+ * Return true if the file should be skipped (not validated).
+ * Skips non-markdown, dotfiles, templates, root docs, and translated READMEs.
+ */
+export function shouldSkipFile(filePath: string): boolean {
+ if (!filePath || !filePath.endsWith(".md")) return true;
+
+ const normalized = filePath.replaceAll("\\", "/");
+ const base = basename(normalized);
+
+ if (ROOT_FILES.has(base)) return true;
+
+ if (base.startsWith("README.") && base.endsWith(".md")) return true;
+
+ for (const segment of SKIP_PATH_SEGMENTS) {
+ if (normalized.includes(segment)) return true;
+ }
+
+ return false;
+}
+
+/**
+ * Inspect markdown content and return a list of warnings. Empty list means
+ * the note is valid by our conventions.
+ */
+export function validateContent(content: string): string[] {
+ const warnings: string[] = [];
+
+ if (!content.startsWith("---")) {
+ warnings.push("Missing YAML frontmatter");
+ } else {
+ const parts = content.split("---");
+ if (parts.length >= 3) {
+ const fm = parts[1] ?? "";
+ if (!fm.includes("tags:") && !fm.includes("tags :")) {
+ warnings.push("Missing `tags` in frontmatter");
+ }
+ if (!fm.includes("description:") && !fm.includes("description :")) {
+ warnings.push(
+ "Missing `description` in frontmatter (~150 chars required by vault convention)",
+ );
+ }
+ if (!fm.includes("date:") && !fm.includes("date :")) {
+ warnings.push("Missing `date` in frontmatter");
+ }
+ }
+ }
+
+ if (content.length > 300 && !content.includes("[[")) {
+ warnings.push(
+ "No [[wikilinks]] found — every note must link to at least one other note (vault convention)",
+ );
+ }
+
+ return warnings;
+}
+
+/**
+ * Read a file from disk and validate it. Returns null on read error
+ * (caller should treat null as "skip silently" per hook protocol).
+ */
+export function validateFile(filePath: string): string[] | null {
+ try {
+ const content = readFileSync(filePath, { encoding: "utf-8" });
+ return validateContent(content);
+ } catch {
+ return null;
+ }
+}
diff --git a/.claude/scripts/lib/hook-io.ts b/.claude/scripts/lib/hook-io.ts
new file mode 100644
index 0000000..0d0c45d
--- /dev/null
+++ b/.claude/scripts/lib/hook-io.ts
@@ -0,0 +1,43 @@
+/**
+ * Shared I/O for hook entry points.
+ *
+ * The hook protocol expects exit 0 on failure with no output. readStdinJson
+ * returns null on any error (malformed JSON, non-UTF8, empty stdin) so callers
+ * can `if (!input) process.exit(0)` uniformly.
+ *
+ * Set HOOK_DEBUG=1 in the environment to emit diagnostic stderr lines from
+ * any call site that uses debug(). Useful when a hook is silently failing
+ * and you need to see which path it took.
+ */
+
+export function debug(msg: string): void {
+ if (process.env["HOOK_DEBUG"] === "1") {
+ process.stderr.write(`[hook-debug ${new Date().toISOString()}] ${msg}\n`);
+ }
+}
+
+export async function readStdinJson<T = unknown>(): Promise<T | null> {
+ try {
+ const chunks: Buffer[] = [];
+ for await (const chunk of process.stdin) {
+ chunks.push(typeof chunk === "string" ? Buffer.from(chunk) : chunk);
+ }
+ if (chunks.length === 0) return null;
+ const text = Buffer.concat(chunks).toString("utf-8");
+ if (!text.trim()) return null;
+ return JSON.parse(text) as T;
+ } catch {
+ return null;
+ }
+}
+
+export function writeHookOutput(
+ hookEventName: string,
+ additionalContext: string,
+): void {
+ process.stdout.write(
+ JSON.stringify({
+ hookSpecificOutput: { hookEventName, additionalContext },
+ }),
+ );
+}
diff --git a/.claude/scripts/lib/matcher.ts b/.claude/scripts/lib/matcher.ts
new file mode 100644
index 0000000..77e786d
--- /dev/null
+++ b/.claude/scripts/lib/matcher.ts
@@ -0,0 +1,45 @@
+/**
+ * Regex boundary logic for classify-message.
+ *
+ * Uses Latin-letter lookarounds instead of \b. \b treats CJK characters as word
+ * characters (\w), so \bdecision\b fails to match in "のdecisionについて"
+ * (no boundary between Hiragana and Latin). The (?<![a-zA-Z]) and (?![a-zA-Z])
+ * lookarounds enforce Latin word boundaries while allowing CJK adjacency.
+ */
+
+import { SIGNALS } from "./signals.ts";
+
+function escapeRegex(s: string): string {
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+}
+
+function compileMatcher(phrases: readonly string[]): RegExp {
+ const body = phrases.map(escapeRegex).join("|");
+ return new RegExp(`(?<![a-zA-Z])(?:${body})(?![a-zA-Z])`);
+}
+
+// Precomputed once per process. classify() runs on every UserPromptSubmit, so
+// avoiding per-call regex construction matters — 7 signals × ~20 patterns is
+// ~140 RegExp allocations saved per message.
+const SIGNAL_MATCHERS: ReadonlyArray<{ message: string; regex: RegExp }> =
+ SIGNALS.map((s) => ({
+ message: s.message,
+ regex: compileMatcher(s.patterns),
+ }));
+
+export function anyWordMatch(
+ phrases: readonly string[],
+ text: string,
+): boolean {
+ if (phrases.length === 0) return false;
+ return compileMatcher(phrases).test(text);
+}
+
+export function classify(prompt: string): string[] {
+ const lowered = prompt.toLowerCase();
+ const messages: string[] = [];
+ for (const { message, regex } of SIGNAL_MATCHERS) {
+ if (regex.test(lowered)) messages.push(message);
+ }
+ return messages;
+}
diff --git a/.claude/scripts/lib/read-field.ts b/.claude/scripts/lib/read-field.ts
new file mode 100644
index 0000000..1489989
--- /dev/null
+++ b/.claude/scripts/lib/read-field.ts
@@ -0,0 +1,20 @@
+/**
+ * Tiny bin for shell-invoked JSON field extraction.
+ *
+ * Usage: echo '{"a":1,"b":"x"}' | node --experimental-strip-types read-field.ts a b
+ * Output: `1\tx` (tab-separated, in argv order)
+ *
+ * Left in-tree for any shell script that wants to read a field from
+ * stdin JSON without inlining JSON parsing.
+ */
+
+import { readStdinJson } from "./hook-io.ts";
+
+const input = await readStdinJson<Record<string, unknown>>();
+const fields = process.argv.slice(2);
+const values = fields.map((f) => {
+ const v = input?.[f];
+ if (v === undefined || v === null) return "";
+ return String(v);
+});
+process.stdout.write(values.join("\t"));
diff --git a/.claude/scripts/lib/session-start.ts b/.claude/scripts/lib/session-start.ts
new file mode 100644
index 0000000..e9b1da5
--- /dev/null
+++ b/.claude/scripts/lib/session-start.ts
@@ -0,0 +1,63 @@
+/**
+ * Pure helpers for session-start context assembly — extracted so the
+ * formatting logic is unit-testable without spawning git, reading the file
+ * system, or invoking the Obsidian CLI.
+ */
+
+export function take(stdout: string, n: number): string {
+ return stdout.split("\n").slice(0, n).join("\n");
+}
+
+/**
+ * Local-time date header matching `date +%Y-%m-%d` followed by the weekday
+ * name. Separate from `new Date()` so tests can pass a fixed date.
+ */
+export function formatDateHeader(d: Date): string {
+ const y = d.getFullYear();
+ const m = String(d.getMonth() + 1).padStart(2, "0");
+ const day = String(d.getDate()).padStart(2, "0");
+ const weekday = d.toLocaleDateString("en-US", { weekday: "long" });
+ return `${y}-${m}-${day} (${weekday})`;
+}
+
+/**
+ * Format the "Active Work" section from a list of filenames in work/active.
+ * Strips `.md`, keeps the first `limit`, returns "(none)" for empty input.
+ */
+export function formatActiveWork(
+ filenames: readonly string[],
+ limit: number,
+): string {
+ const names = filenames
+ .filter((f) => f.endsWith(".md"))
+ .map((f) => f.replace(/\.md$/, ""))
+ .slice(0, limit);
+ return names.length > 0 ? names.join("\n") : "(none)";
+}
+
+/**
+ * Format the "Recent Changes" section from raw `git log --oneline` output.
+ * Strips blank lines, keeps the first `limit`, falls back to
+ * "(no git history)" when empty (matching the legacy shell message).
+ */
+export function formatRecentChanges(gitOutput: string, limit: number): string {
+ const lines = gitOutput
+ .split("\n")
+ .filter((l) => l.length > 0)
+ .slice(0, limit);
+ return lines.length > 0 ? lines.join("\n") : "(no git history)";
+}
+
+/**
+ * Return true if a path (relative, using "/" separators) falls under any
+ * of the supplied skip prefixes. A prefix like ".git" matches ".git" and
+ * ".git/anything" but not ".github" (exact segment boundary).
+ */
+export function isSkippedPath(
+ pathRel: string,
+ skipPrefixes: readonly string[],
+): boolean {
+ return skipPrefixes.some(
+ (p) => pathRel === p || pathRel.startsWith(p + "/"),
+ );
+}
diff --git a/.claude/scripts/lib/signals.ts b/.claude/scripts/lib/signals.ts
new file mode 100644
index 0000000..e904942
--- /dev/null
+++ b/.claude/scripts/lib/signals.ts
@@ -0,0 +1,263 @@
+/**
+ * Signal definitions for the classify-message hook.
+ *
+ * Architecture: data-driven signal matching. Each signal has a list of trigger
+ * patterns checked via regex with Latin-letter lookarounds (not \b). Words can
+ * appear in multiple signals (explicit overlaps) because the cost of a false
+ * positive hint is ~0 (the agent ignores irrelevant hints) while a false
+ * negative means missed routing.
+ *
+ * Patterns include English, Japanese, Korean, and Simplified Chinese to support
+ * multilingual users. The Latin-letter lookaround approach allows mixed
+ * Latin/CJK text without relying on word-boundary behavior that treats CJK
+ * characters as word characters.
+ */
+
+export type Signal = {
+ readonly name: string;
+ readonly message: string;
+ readonly patterns: readonly string[];
+};
+
+export const SIGNALS: readonly Signal[] = [
+ {
+ name: "DECISION",
+ message:
+ "DECISION detected — consider creating a Decision Record in work/active/ and logging in work/Index.md Decisions Log",
+ patterns: [
+ // English
+ "decided",
+ "deciding",
+ "decision",
+ "we chose",
+ "agreed to",
+ "let's go with",
+ "the call is",
+ "we're going with",
+ // Japanese
+ "決定した",
+ "決めた",
+ "合意した",
+ // Korean
+ "결정했어",
+ "결정했습니다",
+ "합의했어",
+ // Chinese
+ "决定了",
+ "我们决定",
+ "确定了",
+ "同意",
+ ],
+ },
+ {
+ name: "INCIDENT",
+ message:
+ "INCIDENT detected — consider using /om-incident-capture or creating an incident note in work/incidents/",
+ patterns: [
+ // English
+ "incident",
+ "outage",
+ "pagerduty",
+ "severity",
+ "p0",
+ "p1",
+ "p2",
+ "sev1",
+ "sev2",
+ "postmortem",
+ "rca",
+ // Japanese
+ "インシデント",
+ "障害",
+ // Korean
+ "인시던트",
+ "장애",
+ // Chinese
+ "事件",
+ "故障",
+ "事后分析",
+ ],
+ },
+ {
+ name: "1:1 CONTENT",
+ message:
+ "1:1 CONTENT detected — consider creating a 1-on-1 note in work/1-1/ and updating the person note in org/people/",
+ patterns: [
+ // English
+ "1:1",
+ "1-1",
+ "1-on-1",
+ "one on one",
+ "1on1",
+ "catch up with",
+ "sync with",
+ // Japanese
+ "ワンオンワン",
+ // Korean
+ "원온원",
+ // Chinese
+ "一对一",
+ "单独面谈",
+ ],
+ },
+ {
+ name: "WIN",
+ message:
+ "WIN detected — consider adding to perf/Brag Doc.md with a link to the evidence note",
+ patterns: [
+ // Delivery — English (shared with PROJECT UPDATE)
+ "shipped",
+ "shipping",
+ "ships",
+ "launched",
+ "launching",
+ "launches",
+ "completed",
+ "completing",
+ "completes",
+ "released",
+ "releasing",
+ "releases",
+ "deployed",
+ "deploying",
+ "deploys",
+ // Achievement — English
+ "achieved",
+ "achieving",
+ "won",
+ "promoted",
+ "praised",
+ "win",
+ "kudos",
+ "shoutout",
+ "great feedback",
+ "recognized",
+ // Japanese
+ "出荷した",
+ "リリースした",
+ "達成した",
+ "褒められた",
+ // Korean
+ "배포했어",
+ "출시했어",
+ "달성했어",
+ "칭찬받았어",
+ // Chinese
+ "发布了",
+ "上线了",
+ "完成了",
+ "表扬",
+ "认可",
+ ],
+ },
+ {
+ name: "ARCHITECTURE",
+ message:
+ "ARCHITECTURE discussion — consider creating a reference note in reference/ or a decision record",
+ patterns: [
+ // English
+ "architecture",
+ "system design",
+ "rfc",
+ "tech spec",
+ "trade-off",
+ "design doc",
+ "adr",
+ // Japanese
+ "アーキテクチャ",
+ "システム設計",
+ // Korean
+ "아키텍처",
+ "시스템 설계",
+ // Chinese
+ "架构",
+ "系统设计",
+ "技术规范",
+ ],
+ },
+ {
+ name: "PERSON CONTEXT",
+ message:
+ "PERSON CONTEXT detected — consider updating the relevant person note in org/people/ and linking from the conversation note",
+ patterns: [
+ // English
+ "told me",
+ "said that",
+ "feedback from",
+ "met with",
+ "talked to",
+ "spoke with",
+ "mentioned that",
+ "mentioned the",
+ "mentioned a",
+ // Japanese
+ "言ってた",
+ "フィードバック",
+ "話した",
+ // Korean
+ "말했어",
+ "피드백",
+ "얘기했어",
+ "언급했어",
+ // Chinese
+ "说了",
+ "提到",
+ "反馈",
+ "提及",
+ ],
+ },
+ {
+ name: "PROJECT UPDATE",
+ message:
+ "PROJECT UPDATE detected — consider updating the active work note in work/active/ and checking if wins should go to brag doc",
+ patterns: [
+ // English
+ "project update",
+ "sprint",
+ "milestone",
+ // Delivery — English (shared with WIN)
+ "shipped",
+ "shipping",
+ "ships",
+ "shipped feature",
+ "launched",
+ "launching",
+ "launches",
+ "completed",
+ "completing",
+ "completes",
+ "released",
+ "releasing",
+ "releases",
+ "deployed",
+ "deploying",
+ "deploys",
+ // Delivery-only — English (not wins on their own)
+ "went live",
+ "rolled out",
+ "rolling out",
+ "merged",
+ "merging",
+ "merges",
+ "cut the release",
+ "release cut",
+ // Japanese
+ "スプリント",
+ "マイルストーン",
+ "マージした",
+ "リリースしました",
+ // Korean
+ "스프린트",
+ "마일스톤",
+ "배포",
+ "릴리스",
+ "병합",
+ // Chinese (发布了, 上线 shared with WIN)
+ "迭代",
+ "里程碑",
+ "发布了",
+ "上线",
+ "合并了",
+ ],
+ },
+];
diff --git a/.claude/scripts/package.json b/.claude/scripts/package.json
new file mode 100644
index 0000000..9d5782c
--- /dev/null
+++ b/.claude/scripts/package.json
@@ -0,0 +1,9 @@
+{
+ "private": true,
+ "type": "module",
+ "description": "Hook scripts for obsidian-mind. Runtime has zero dependencies — executed by `node --experimental-strip-types`. This file exists only to mark .ts files as ESM for Node's module resolution and for CI typecheck (devDependencies installed ad hoc via `npm install --no-save typescript @types/node`).",
+ "scripts": {
+ "test": "node --experimental-strip-types --test",
+ "typecheck": "tsc --noEmit"
+ }
+}
diff --git a/.claude/scripts/pre-compact.sh b/.claude/scripts/pre-compact.sh
deleted file mode 100755
index 34251df..0000000
--- a/.claude/scripts/pre-compact.sh
+++ /dev/null
@@ -1,23 +0,0 @@
-#!/bin/bash
-set -euo pipefail
-
-SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
-
-INPUT=$(cat)
-IFS=$'\t' read -r TRANSCRIPT_PATH TRIGGER <<< "$(echo "$INPUT" | bash "$SCRIPT_DIR/find-python.sh" -c "
-import json,sys
-d=json.load(sys.stdin)
-print(d.get('transcript_path','') + '\t' + d.get('trigger','unknown'))
-" 2>/dev/null || printf '\tunknown')"
-
-if [ -n "$TRANSCRIPT_PATH" ] && [ -f "$TRANSCRIPT_PATH" ]; then
- BACKUP_DIR="${CLAUDE_PROJECT_DIR:-$(pwd)}/thinking/session-logs"
- mkdir -p "$BACKUP_DIR"
- TIMESTAMP=$(date +%Y%m%d_%H%M%S)
- cp "$TRANSCRIPT_PATH" "$BACKUP_DIR/session_${TRIGGER}_${TIMESTAMP}.jsonl"
-
- # Keep last 30 backups, prune older ones
- ls -t "$BACKUP_DIR"/session_*.jsonl 2>/dev/null | tail -n +31 | xargs rm -f 2>/dev/null || true
-fi
-
-exit 0
diff --git a/.claude/scripts/pre-compact.ts b/.claude/scripts/pre-compact.ts
new file mode 100644
index 0000000..129734c
--- /dev/null
+++ b/.claude/scripts/pre-compact.ts
@@ -0,0 +1,104 @@
+#!/usr/bin/env node
+/**
+ * PreCompact hook — back up the session transcript before the agent
+ * compacts its context so lost history can be rehydrated from disk if
+ * needed. Keeps the most recent 30 backups; older ones are pruned.
+ *
+ * Backups land in `${CLAUDE_PROJECT_DIR}/thinking/session-logs/` named
+ * `session_<trigger>_<YYYYMMDD_HHMMSS>.jsonl`.
+ */
+
+import {
+ mkdirSync,
+ copyFileSync,
+ readdirSync,
+ statSync,
+ unlinkSync,
+} from "node:fs";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { debug, readStdinJson } from "./lib/hook-io.ts";
+
+type HookInput = {
+ readonly transcript_path?: unknown;
+ readonly trigger?: unknown;
+};
+
+const BACKUP_RETAIN = 30;
+
+export function formatTimestamp(d: Date): string {
+ const pad = (n: number) => String(n).padStart(2, "0");
+ return (
+ `${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}` +
+ `_${pad(d.getHours())}${pad(d.getMinutes())}${pad(d.getSeconds())}`
+ );
+}
+
+export function listBackups(dir: string): string[] {
+ try {
+ return readdirSync(dir)
+ .filter((f) => f.startsWith("session_") && f.endsWith(".jsonl"))
+ .map((f) => ({ name: f, mtime: statSync(join(dir, f)).mtimeMs }))
+ .sort((a, b) => b.mtime - a.mtime)
+ .map((e) => e.name);
+ } catch {
+ return [];
+ }
+}
+
+export function pruneBackups(dir: string, retain: number): void {
+ const ordered = listBackups(dir);
+ for (const name of ordered.slice(retain)) {
+ try {
+ unlinkSync(join(dir, name));
+ } catch {
+ /* best effort — retention is soft */
+ }
+ }
+}
+
+// Only run main when invoked as a script (not when imported by tests).
+// fileURLToPath handles the file:// prefix and any URL-encoded segments;
+// process.argv[1] is already the absolute resolved script path at invocation.
+if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
+ const input = await readStdinJson<HookInput>();
+ if (!input) process.exit(0);
+
+ const transcriptPath =
+ typeof input.transcript_path === "string" ? input.transcript_path : "";
+ const trigger =
+ typeof input.trigger === "string" ? input.trigger : "unknown";
+
+ if (!transcriptPath) {
+ debug("pre-compact: no transcript_path in input");
+ process.exit(0);
+ }
+
+ const projectDir = process.env["CLAUDE_PROJECT_DIR"] ?? process.cwd();
+ const backupDir = join(projectDir, "thinking/session-logs");
+ mkdirSync(backupDir, { recursive: true });
+
+ const dest = join(
+ backupDir,
+ `session_${trigger}_${formatTimestamp(new Date())}.jsonl`,
+ );
+
+ try {
+ copyFileSync(transcriptPath, dest);
+ debug(`pre-compact: backed up ${transcriptPath} → ${dest}`);
+ } catch (err) {
+ // Both "transcript missing" (ENOENT) and any other fs error are non-fatal:
+ // hook protocol requires exit 0. The debug line differentiates so a
+ // missing-transcript scenario isn't logged as a "copy failed" anomaly.
+ const code = (err as NodeJS.ErrnoException).code;
+ if (code === "ENOENT") {
+ debug(`pre-compact: transcript not found (path=${transcriptPath})`);
+ } else {
+ debug(`pre-compact: copy failed: ${(err as Error).message}`);
+ }
+ process.exit(0);
+ }
+
+ pruneBackups(backupDir, BACKUP_RETAIN);
+ process.exit(0);
+}
diff --git a/.claude/scripts/session-start.sh b/.claude/scripts/session-start.sh
deleted file mode 100755
index a5e2ec5..0000000
--- a/.claude/scripts/session-start.sh
+++ /dev/null
@@ -1,58 +0,0 @@
-#!/bin/bash
-set -eo pipefail
-cd "${CLAUDE_PROJECT_DIR:-${CODEX_PROJECT_DIR:-${GEMINI_PROJECT_DIR:-$(pwd)}}}"
-
-# Persist vault path for the session
-if [ -n "${CLAUDE_ENV_FILE:-}" ]; then
- echo "export VAULT_PATH=\"$(pwd)\"" >> "$CLAUDE_ENV_FILE"
-fi
-
-# Incremental QMD re-index (fast, non-blocking if qmd not installed)
-qmd update 2>/dev/null || true
-
-# Helper: run a command with a timeout, fall back to alternative
-run_with_timeout() {
- local timeout_sec=$1; shift
- local fallback_cmd=$1; shift
- if command -v gtimeout &>/dev/null; then
- gtimeout "$timeout_sec" "$@" 2>/dev/null || eval "$fallback_cmd"
- elif command -v timeout &>/dev/null; then
- timeout "$timeout_sec" "$@" 2>/dev/null || eval "$fallback_cmd"
- else
- "$@" 2>/dev/null || eval "$fallback_cmd"
- fi
-}
-
-# Build context summary
-echo "## Session Context"
-echo ""
-echo "### Date"
-echo "$(date +%Y-%m-%d) ($(date +%A))"
-echo ""
-
-echo "### North Star (current goals)"
-if command -v obsidian &>/dev/null; then
- run_with_timeout 5 'cat brain/North\ Star.md 2>/dev/null | head -30' obsidian read file="North Star" | head -30
-else
- cat brain/North\ Star.md 2>/dev/null | head -30 || echo "(not found)"
-fi
-echo ""
-
-echo "### Recent Changes (last 48h)"
-git log --oneline --since="48 hours ago" --no-merges 2>/dev/null | head -15 || echo "(no git history)"
-echo ""
-
-echo "### Open Tasks"
-if command -v obsidian &>/dev/null; then
- run_with_timeout 5 'echo "(CLI timed out)"' obsidian tasks daily todo | head -10
-else
- echo "(Obsidian CLI not available)"
-fi
-echo ""
-
-echo "### Active Work"
-ls work/active/*.md 2>/dev/null | sed 's|work/active/||;s|\.md$||' | head -10 || echo "(none)"
-echo ""
-
-echo "### Vault File Listing"
-find . -name "*.md" -not -path "./.git/*" -not -path "./.obsidian/*" -not -path "./thinking/*" -not -path "./.claude/*" | sort
diff --git a/.claude/scripts/session-start.ts b/.claude/scripts/session-start.ts
new file mode 100644
index 0000000..05c8903
--- /dev/null
+++ b/.claude/scripts/session-start.ts
@@ -0,0 +1,162 @@
+#!/usr/bin/env node
+/**
+ * SessionStart hook — inject vault context into the agent's first turn.
+ *
+ * Emits a markdown block on stdout with: date header, North Star excerpt,
+ * recent git changes (last 48h), open tasks (via Obsidian CLI if available),
+ * active work listing, and a full vault markdown file listing.
+ *
+ * Also persists VAULT_PATH to CLAUDE_ENV_FILE when Claude Code provides it.
+ */
+
+import {
+ readFileSync,
+ appendFileSync,
+ readdirSync,
+ type Dirent,
+} from "node:fs";
+import { spawnSync } from "node:child_process";
+import { join } from "node:path";
+import {
+ take,
+ formatDateHeader,
+ formatActiveWork,
+ formatRecentChanges,
+ isSkippedPath,
+} from "./lib/session-start.ts";
+
+const cwd =
+ process.env["CLAUDE_PROJECT_DIR"] ??
+ process.env["CODEX_PROJECT_DIR"] ??
+ process.env["GEMINI_PROJECT_DIR"] ??
+ process.cwd();
+process.chdir(cwd);
+
+// Persist vault path for any downstream shell consumers (Claude Code feature)
+const envFile = process.env["CLAUDE_ENV_FILE"];
+if (envFile) {
+ try {
+ appendFileSync(envFile, `export VAULT_PATH="${cwd}"\n`);
+ } catch {
+ /* best-effort — session continues even if persistence fails */
+ }
+}
+
+// Incremental QMD re-index. Fire-and-forget; ignore failures (qmd is optional).
+spawnSync("qmd", ["update"], { stdio: "ignore", timeout: 30_000 });
+
+type CmdResult =
+ | { readonly kind: "ok"; readonly stdout: string }
+ | { readonly kind: "missing" }
+ | { readonly kind: "failed" };
+
+function runCmd(
+ cmd: string,
+ args: readonly string[],
+ timeoutMs = 5_000,
+): CmdResult {
+ const r = spawnSync(cmd, args as string[], {
+ encoding: "utf-8",
+ timeout: timeoutMs,
+ });
+ if (
+ r.error &&
+ (r.error as NodeJS.ErrnoException).code === "ENOENT"
+ ) {
+ return { kind: "missing" };
+ }
+ if (r.status !== 0) return { kind: "failed" };
+ return { kind: "ok", stdout: r.stdout ?? "" };
+}
+
+
+function northStar(): string {
+ // Prefer Obsidian CLI when available (authoritative for wikilink resolution)
+ const cli = runCmd("obsidian", ["read", "file=North Star"]);
+ if (cli.kind === "ok") return take(cli.stdout, 30);
+ try {
+ return take(readFileSync("brain/North Star.md", { encoding: "utf-8" }), 30);
+ } catch {
+ return "(not found)";
+ }
+}
+
+function recentChanges(): string {
+ const r = runCmd("git", [
+ "log",
+ "--oneline",
+ "--since=48 hours ago",
+ "--no-merges",
+ ]);
+ if (r.kind !== "ok") return "(no git history)";
+ return formatRecentChanges(r.stdout, 15);
+}
+
+function openTasks(): string {
+ const r = runCmd("obsidian", ["tasks", "daily", "todo"]);
+ if (r.kind === "missing") return "(Obsidian CLI not available)";
+ if (r.kind === "failed") return "(CLI timed out)";
+ return take(r.stdout, 10);
+}
+
+function activeWork(): string {
+ let entries: Dirent[];
+ try {
+ entries = readdirSync("work/active", { withFileTypes: true });
+ } catch {
+ return "(none)";
+ }
+ const files = entries.filter((e) => e.isFile()).map((e) => e.name);
+ return formatActiveWork(files, 10);
+}
+
+const SKIP_PREFIXES: readonly string[] = [
+ ".git",
+ ".obsidian",
+ "thinking",
+ ".claude",
+];
+
+function listMd(): string[] {
+ const results: string[] = [];
+ function walk(dir: string): void {
+ let entries: Dirent[];
+ try {
+ entries = readdirSync(dir, { withFileTypes: true });
+ } catch {
+ return;
+ }
+ for (const e of entries) {
+ const full = dir === "." ? e.name : join(dir, e.name);
+ if (isSkippedPath(full, SKIP_PREFIXES)) continue;
+ if (e.isDirectory()) walk(full);
+ else if (e.isFile() && e.name.endsWith(".md")) results.push(`./${full}`);
+ }
+ }
+ walk(".");
+ return results.sort();
+}
+
+const sections = [
+ "## Session Context",
+ "",
+ "### Date",
+ formatDateHeader(new Date()),
+ "",
+ "### North Star (current goals)",
+ northStar(),
+ "",
+ "### Recent Changes (last 48h)",
+ recentChanges(),
+ "",
+ "### Open Tasks",
+ openTasks(),
+ "",
+ "### Active Work",
+ activeWork(),
+ "",
+ "### Vault File Listing",
+ listMd().join("\n"),
+];
+
+process.stdout.write(sections.join("\n") + "\n");
diff --git a/.claude/scripts/stop-checklist.ts b/.claude/scripts/stop-checklist.ts
new file mode 100644
index 0000000..22ccc2b
--- /dev/null
+++ b/.claude/scripts/stop-checklist.ts
@@ -0,0 +1,27 @@
+#!/usr/bin/env node
+/**
+ * Stop hook — remind the user of session-wrap-up tasks.
+ *
+ * Silently exits when the hook is being re-entered by a secondary agent
+ * (stop_hook_active=true) to avoid recursive reminder output. Otherwise
+ * prints a short vault-hygiene checklist.
+ */
+
+import { readStdinJson } from "./lib/hook-io.ts";
+
+type HookInput = {
+ readonly stop_hook_active?: unknown;
+};
+
+const input = await readStdinJson<HookInput>();
+if (input?.stop_hook_active === true) process.exit(0);
+
+const checklist = [
+ "Session end checklist:",
+ "- Archive completed projects? (work/active/ -> work/archive/YYYY/)",
+ "- Update indexes? (Index.md, Memories.md, People & Context, Brag Doc)",
+ "- New notes linked? (orphans are bugs)",
+ "- Run /om-vault-audit if many notes were created/modified",
+].join("\n");
+
+process.stdout.write(checklist + "\n");
diff --git a/.claude/scripts/test_hooks.py b/.claude/scripts/test_hooks.py
deleted file mode 100644
index 23e9ef4..0000000
--- a/.claude/scripts/test_hooks.py
+++ /dev/null
@@ -1,526 +0,0 @@
-#!/usr/bin/env python3
-"""Test suite for Claude Code hook scripts (classify-message.py, validate-write.py).
-
-Run: python3 .claude/scripts/test_hooks.py
-Verbose: python3 .claude/scripts/test_hooks.py -v
-
-Stdlib only — no external dependencies. Uses unittest with subTest for
-parameterized CJK tests.
-"""
-import importlib
-import json
-import os
-import shutil
-import subprocess
-import sys
-import tempfile
-import unittest
-
-# ---------------------------------------------------------------------------
-# Import hook modules (hyphenated filenames require importlib)
-# ---------------------------------------------------------------------------
-SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
-sys.path.insert(0, SCRIPT_DIR)
-
-classify_mod = importlib.import_module("classify-message")
-classify = classify_mod.classify
-_any_word_match = classify_mod._any_word_match
-SIGNALS = classify_mod.SIGNALS
-
-
-# ---------------------------------------------------------------------------
-# Helpers
-# ---------------------------------------------------------------------------
-def run_script(script_name, stdin_data=None):
- """Run a hook script via subprocess, matching how settings.json invokes it."""
- cmd = [sys.executable, os.path.join(SCRIPT_DIR, script_name)]
- stdin_str = json.dumps(stdin_data) if stdin_data is not None else ""
- proc = subprocess.run(
- cmd, input=stdin_str, capture_output=True, text=True, timeout=10
- )
- return proc.stdout, proc.stderr, proc.returncode
-
-
-def get_signal_names(prompt):
- """Classify a prompt and return sorted list of signal names."""
- messages = classify(prompt)
- names = []
- for msg in messages:
- for sig in SIGNALS:
- if msg == sig["message"]:
- names.append(sig["name"])
- break
- return sorted(names)
-
-
-# ---------------------------------------------------------------------------
-# TestAnyWordMatch — unit tests for the core matching function
-# ---------------------------------------------------------------------------
-class TestAnyWordMatch(unittest.TestCase):
- def test_basic_match(self):
- self.assertTrue(_any_word_match(["hello"], "hello world"))
-
- def test_no_match(self):
- self.assertFalse(_any_word_match(["xyz"], "hello world"))
-
- def test_boundary_prevents_substring(self):
- """'decision' must not match inside 'predecisioned'."""
- self.assertFalse(_any_word_match(["decision"], "predecisioned"))
-
- def test_boundary_prevents_prefix(self):
- """'shipped' must not match inside 'unshipped'."""
- self.assertFalse(_any_word_match(["shipped"], "unshipped items"))
-
- def test_cjk_adjacency(self):
- """English keyword adjacent to CJK characters must match."""
- self.assertTrue(_any_word_match(["decision"], "のdecisionについて"))
-
- def test_multi_word_phrase(self):
- self.assertTrue(_any_word_match(["one on one"], "had a one on one with Alice"))
-
- def test_multi_word_no_partial(self):
- """'one on one' should not match 'one on two'."""
- self.assertFalse(_any_word_match(["one on one"], "one on two"))
-
- def test_cjk_pattern_match(self):
- """CJK patterns should match in CJK text."""
- self.assertTrue(_any_word_match(["決定した"], "チームで決定した"))
-
- def test_case_sensitivity(self):
- """_any_word_match is case-sensitive; classify() lowercases first."""
- self.assertFalse(_any_word_match(["decision"], "DECISION"))
- self.assertTrue(_any_word_match(["decision"], "decision"))
-
-
-# ---------------------------------------------------------------------------
-# TestClassifyEnglish — unit tests for English signal detection
-# ---------------------------------------------------------------------------
-class TestClassifyEnglish(unittest.TestCase):
- def test_decision(self):
- self.assertIn("DECISION", get_signal_names("we decided to use Redis"))
-
- def test_incident(self):
- self.assertIn("INCIDENT", get_signal_names("there was an outage in prod"))
-
- def test_1on1(self):
- self.assertIn("1:1 CONTENT", get_signal_names("had a 1:1 with my manager"))
-
- def test_1on1_hyphen(self):
- self.assertIn("1:1 CONTENT", get_signal_names("1-1 with Sarah today"))
-
- def test_win(self):
- self.assertIn("WIN", get_signal_names("got kudos from the team"))
-
- def test_architecture(self):
- self.assertIn("ARCHITECTURE", get_signal_names("wrote a tech spec for the API"))
-
- def test_person_context(self):
- self.assertIn("PERSON CONTEXT", get_signal_names("Alice told me about the deadline"))
-
- def test_project_update(self):
- self.assertIn("PROJECT UPDATE", get_signal_names("sprint planning for next week"))
-
- def test_overlap_shipped(self):
- names = get_signal_names("we shipped the feature")
- self.assertIn("WIN", names)
- self.assertIn("PROJECT UPDATE", names)
-
- def test_overlap_deployed(self):
- names = get_signal_names("deployed to production")
- self.assertIn("WIN", names)
- self.assertIn("PROJECT UPDATE", names)
-
- def test_multi_signal(self):
- names = get_signal_names("we decided to fix the incident")
- self.assertIn("DECISION", names)
- self.assertIn("INCIDENT", names)
-
- def test_case_insensitivity(self):
- self.assertIn("DECISION", get_signal_names("DECIDED to go with option A"))
-
- def test_return_type(self):
- result = classify("hello world")
- self.assertIsInstance(result, list)
-
- def test_return_items_are_strings(self):
- result = classify("we decided to ship it")
- for item in result:
- self.assertIsInstance(item, str)
-
-
-# ---------------------------------------------------------------------------
-# TestClassifyInflections — English verb form coverage
-# ---------------------------------------------------------------------------
-class TestClassifyInflections(unittest.TestCase):
- def test_deciding(self):
- self.assertIn("DECISION", get_signal_names("we're still deciding on the approach"))
-
- def test_deploying(self):
- names = get_signal_names("deploying the fix right now")
- self.assertIn("WIN", names)
- self.assertIn("PROJECT UPDATE", names)
-
- def test_shipping(self):
- names = get_signal_names("shipping the feature today")
- self.assertIn("WIN", names)
- self.assertIn("PROJECT UPDATE", names)
-
- def test_merging(self):
- self.assertIn("PROJECT UPDATE", get_signal_names("merging the PR this afternoon"))
-
- def test_launching(self):
- names = get_signal_names("launching the new service tomorrow")
- self.assertIn("WIN", names)
- self.assertIn("PROJECT UPDATE", names)
-
- def test_completing(self):
- names = get_signal_names("completing the migration this week")
- self.assertIn("WIN", names)
- self.assertIn("PROJECT UPDATE", names)
-
- def test_releasing(self):
- names = get_signal_names("releasing v2.0 on Friday")
- self.assertIn("WIN", names)
- self.assertIn("PROJECT UPDATE", names)
-
- def test_achieving(self):
- self.assertIn("WIN", get_signal_names("achieving the quarterly target"))
-
- def test_rolling_out(self):
- self.assertIn("PROJECT UPDATE", get_signal_names("rolling out the new config"))
-
- # Present-tense -s/-es forms
- def test_deploys(self):
- names = get_signal_names("she deploys to prod every Friday")
- self.assertIn("WIN", names)
- self.assertIn("PROJECT UPDATE", names)
-
- def test_launches(self):
- names = get_signal_names("he launches the service tomorrow")
- self.assertIn("WIN", names)
- self.assertIn("PROJECT UPDATE", names)
-
- def test_ships(self):
- names = get_signal_names("the team ships fast")
- self.assertIn("WIN", names)
- self.assertIn("PROJECT UPDATE", names)
-
- def test_merges(self):
- self.assertIn("PROJECT UPDATE", get_signal_names("she merges the PR"))
-
- def test_releases(self):
- names = get_signal_names("he releases a new version weekly")
- self.assertIn("WIN", names)
- self.assertIn("PROJECT UPDATE", names)
-
- def test_release_cut(self):
- self.assertIn("PROJECT UPDATE", get_signal_names("did the release cut for v3.4"))
-
-
-# ---------------------------------------------------------------------------
-# TestClassifyCJK — per-language signal detection with subTest
-# ---------------------------------------------------------------------------
-class TestClassifyCJK(unittest.TestCase):
- """Test native CJK patterns for each signal category."""
-
- CJK_CASES = {
- "DECISION": {
- "ja": ("チームで決定した", "決定した"),
- "ko": ("결정했습니다", "결정했습니다"),
- "zh": ("我们决定了这个方案", "决定了"),
- },
- "INCIDENT": {
- "ja": ("インシデントが発生しました", "インシデント"),
- "ko": ("장애가 발생했습니다", "장애"),
- "zh": ("发生了故障需要处理", "故障"),
- },
- "1:1 CONTENT": {
- "ja": ("マネージャーとワンオンワンした", "ワンオンワン"),
- "ko": ("원온원 미팅을 했습니다", "원온원"),
- "zh": ("今天有一对一会议", "一对一"),
- },
- "WIN": {
- "ja": ("新機能をリリースした", "リリースした"),
- "ko": ("서비스를 출시했어", "출시했어"),
- "zh": ("新版本发布了", "发布了"),
- },
- "ARCHITECTURE": {
- "ja": ("アーキテクチャの見直しが必要", "アーキテクチャ"),
- "ko": ("아키텍처 리뷰를 했습니다", "아키텍처"),
- "zh": ("系统架构需要重新设计", "架构"),
- },
- "PERSON CONTEXT": {
- "ja": ("田中さんが言ってた", "言ってた"),
- "ko": ("김 매니저가 말했어", "말했어"),
- "zh": ("他提到了这个问题", "提到"),
- },
- "PROJECT UPDATE": {
- "ja": ("今週のスプリントで完了する", "スプリント"),
- "ko": ("이번 스프린트에서 완료", "스프린트"),
- "zh": ("这个迭代的进展报告", "迭代"),
- },
- }
-
- def test_japanese_signals(self):
- for signal_name, langs in self.CJK_CASES.items():
- prompt, pattern = langs["ja"]
- with self.subTest(signal=signal_name, lang="ja", prompt=prompt):
- self.assertIn(signal_name, get_signal_names(prompt),
- f"Japanese pattern '{pattern}' should trigger {signal_name}")
-
- def test_korean_signals(self):
- for signal_name, langs in self.CJK_CASES.items():
- prompt, pattern = langs["ko"]
- with self.subTest(signal=signal_name, lang="ko", prompt=prompt):
- self.assertIn(signal_name, get_signal_names(prompt),
- f"Korean pattern '{pattern}' should trigger {signal_name}")
-
- def test_chinese_signals(self):
- for signal_name, langs in self.CJK_CASES.items():
- prompt, pattern = langs["zh"]
- with self.subTest(signal=signal_name, lang="zh", prompt=prompt):
- self.assertIn(signal_name, get_signal_names(prompt),
- f"Chinese pattern '{pattern}' should trigger {signal_name}")
-
- def test_mixed_cjk_english_japanese(self):
- self.assertIn("DECISION", get_signal_names("のdecisionについて"))
-
- def test_mixed_cjk_english_chinese(self):
- self.assertIn("DECISION", get_signal_names("我们decided了"))
-
- def test_mixed_cjk_english_korean(self):
- self.assertIn("1:1 CONTENT", get_signal_names("오늘 1:1 미팅"))
-
- def test_cjk_overlap(self):
- """Chinese delivery word triggers both WIN and PROJECT UPDATE."""
- names = get_signal_names("新版本发布了")
- self.assertIn("WIN", names)
- self.assertIn("PROJECT UPDATE", names)
-
- def test_cjk_false_positive_japanese(self):
- self.assertEqual(get_signal_names("普通の会話です"), [])
-
- def test_cjk_false_positive_korean(self):
- self.assertEqual(get_signal_names("코드 리뷰를 합시다"), [])
-
- def test_cjk_false_positive_chinese(self):
- self.assertEqual(get_signal_names("今天天气不错"), [])
-
-
-# ---------------------------------------------------------------------------
-# TestClassifyFalsePositives — must NOT trigger signals
-# ---------------------------------------------------------------------------
-class TestClassifyFalsePositives(unittest.TestCase):
- NO_SIGNAL_CASES = [
- ("downloading the markdown file", "download ≠ any trigger"),
- ("hello world", "generic greeting"),
- ("just reading some code", "generic activity"),
- ("the function returns an error", "generic error"),
- ("I wonder about the implementation", "wonder ≠ won"),
- ("she is predecisioned on this", "predecisioned ≠ decision"),
- ("unshipped items in the backlog", "unshipped ≠ shipped"),
- ("acknowledged the problem", "no trigger words"),
- ]
-
- def test_no_false_positives(self):
- for prompt, reason in self.NO_SIGNAL_CASES:
- with self.subTest(prompt=prompt, reason=reason):
- self.assertEqual(get_signal_names(prompt), [],
- f"Should not trigger: {reason}")
-
- def test_empty_string(self):
- self.assertEqual(classify(""), [])
-
-
-# ---------------------------------------------------------------------------
-# TestClassifyIntegration — subprocess tests for full stdin→stdout pipeline
-# ---------------------------------------------------------------------------
-class TestClassifyIntegration(unittest.TestCase):
- SCRIPT = "classify-message.py"
-
- def test_valid_json_with_signal(self):
- stdout, _, rc = run_script(self.SCRIPT, {"prompt": "we decided to use React"})
- self.assertEqual(rc, 0)
- data = json.loads(stdout)
- self.assertIn("hookSpecificOutput", data)
- self.assertEqual(data["hookSpecificOutput"]["hookEventName"], "UserPromptSubmit")
- self.assertIn("DECISION", data["hookSpecificOutput"]["additionalContext"])
-
- def test_valid_json_no_signal(self):
- stdout, _, rc = run_script(self.SCRIPT, {"prompt": "hello world"})
- self.assertEqual(rc, 0)
- self.assertEqual(stdout.strip(), "")
-
- def test_invalid_json(self):
- cmd = [sys.executable, os.path.join(SCRIPT_DIR, self.SCRIPT)]
- proc = subprocess.run(cmd, input="not json{{", capture_output=True, text=True, timeout=10)
- self.assertEqual(proc.returncode, 0)
-
- def test_missing_prompt(self):
- _, _, rc = run_script(self.SCRIPT, {"foo": "bar"})
- self.assertEqual(rc, 0)
-
- def test_non_string_prompt(self):
- _, _, rc = run_script(self.SCRIPT, {"prompt": 123})
- self.assertEqual(rc, 0)
-
- def test_null_prompt(self):
- _, _, rc = run_script(self.SCRIPT, {"prompt": None})
- self.assertEqual(rc, 0)
-
- def test_empty_stdin(self):
- cmd = [sys.executable, os.path.join(SCRIPT_DIR, self.SCRIPT)]
- proc = subprocess.run(cmd, input="", capture_output=True, text=True, timeout=10)
- self.assertEqual(proc.returncode, 0)
-
- def test_empty_prompt(self):
- _, _, rc = run_script(self.SCRIPT, {"prompt": ""})
- self.assertEqual(rc, 0)
-
-
-# ---------------------------------------------------------------------------
-# TestValidateWriteIntegration — subprocess tests for validate-write.py
-# ---------------------------------------------------------------------------
-class TestValidateWriteIntegration(unittest.TestCase):
- SCRIPT = "validate-write.py"
-
- def setUp(self):
- self.tmpdir = tempfile.mkdtemp()
-
- def tearDown(self):
- shutil.rmtree(self.tmpdir, ignore_errors=True)
-
- def _make_md(self, content, name="test.md"):
- path = os.path.join(self.tmpdir, name)
- with open(path, "w", encoding="utf-8") as f:
- f.write(content)
- return path
-
- def _run(self, file_path):
- return run_script(self.SCRIPT, {"tool_input": {"file_path": file_path}})
-
- # -- Skip rules --
-
- def test_skip_non_markdown(self):
- stdout, _, rc = self._run("/tmp/test.txt")
- self.assertEqual(rc, 0)
- self.assertEqual(stdout.strip(), "")
-
- def test_skip_readme(self):
- stdout, _, rc = self._run("/some/path/README.md")
- self.assertEqual(rc, 0)
- self.assertEqual(stdout.strip(), "")
-
- def test_skip_translated_readmes(self):
- for lang in ["ja", "ko", "zh-CN"]:
- with self.subTest(lang=lang):
- stdout, _, rc = self._run(f"/some/path/README.{lang}.md")
- self.assertEqual(rc, 0)
- self.assertEqual(stdout.strip(), "")
-
- def test_skip_changelog(self):
- stdout, _, rc = self._run("/some/path/CHANGELOG.md")
- self.assertEqual(rc, 0)
- self.assertEqual(stdout.strip(), "")
-
- def test_skip_claude_dir(self):
- stdout, _, rc = self._run("/vault/.claude/commands/foo.md")
- self.assertEqual(rc, 0)
- self.assertEqual(stdout.strip(), "")
-
- def test_skip_templates(self):
- stdout, _, rc = self._run("/vault/templates/Work Note.md")
- self.assertEqual(rc, 0)
- self.assertEqual(stdout.strip(), "")
-
- def test_skip_thinking(self):
- stdout, _, rc = self._run("/vault/thinking/draft.md")
- self.assertEqual(rc, 0)
- self.assertEqual(stdout.strip(), "")
-
- def test_skip_windows_path(self):
- """Backslash paths with .claude\\ should be skipped after normalization."""
- stdout, _, rc = self._run("C:\\vault\\.claude\\commands\\foo.md")
- self.assertEqual(rc, 0)
- self.assertEqual(stdout.strip(), "")
-
- # -- Frontmatter validation --
-
- def test_missing_frontmatter(self):
- path = self._make_md("No frontmatter here\n" + "x" * 300)
- stdout, _, rc = self._run(path)
- self.assertEqual(rc, 0)
- data = json.loads(stdout)
- self.assertEqual(data["hookSpecificOutput"]["hookEventName"], "PostToolUse")
- self.assertIn("Missing YAML frontmatter", data["hookSpecificOutput"]["additionalContext"])
-
- def test_missing_tags(self):
- path = self._make_md("---\ndate: 2026-04-05\ndescription: test\n---\n# Note\n" + "[[Link]] " + "x" * 300)
- stdout, _, rc = self._run(path)
- self.assertEqual(rc, 0)
- self.assertIn("Missing `tags`", stdout)
-
- def test_missing_description(self):
- path = self._make_md("---\ndate: 2026-04-05\ntags:\n - test\n---\n# Note\n" + "[[Link]] " + "x" * 300)
- stdout, _, rc = self._run(path)
- self.assertEqual(rc, 0)
- self.assertIn("Missing `description`", stdout)
-
- def test_missing_date(self):
- path = self._make_md("---\ndescription: test\ntags:\n - test\n---\n# Note\n" + "[[Link]] " + "x" * 300)
- stdout, _, rc = self._run(path)
- self.assertEqual(rc, 0)
- self.assertIn("Missing `date`", stdout)
-
- # -- Wikilink validation --
-
- def test_no_wikilinks_long_note(self):
- path = self._make_md("---\ndate: 2026-04-05\ndescription: test\ntags:\n - test\n---\n# Note\n" + "x" * 300)
- stdout, _, rc = self._run(path)
- self.assertEqual(rc, 0)
- self.assertIn("No [[wikilinks]]", stdout)
-
- def test_short_note_no_wikilink_ok(self):
- path = self._make_md("---\ndate: 2026-04-05\ndescription: test\ntags:\n - test\n---\nShort note.")
- stdout, _, rc = self._run(path)
- self.assertEqual(rc, 0)
- self.assertEqual(stdout.strip(), "")
-
- # -- Valid note --
-
- def test_valid_note_no_warnings(self):
- path = self._make_md(
- "---\ndate: 2026-04-05\ndescription: A valid test note\ntags:\n - test\n---\n"
- "# Note\n\nSome content with [[a wikilink]] and more text.\n" + "x" * 300
- )
- stdout, _, rc = self._run(path)
- self.assertEqual(rc, 0)
- self.assertEqual(stdout.strip(), "")
-
- # -- Type safety --
-
- def test_null_tool_input(self):
- _, _, rc = run_script(self.SCRIPT, {"tool_input": None})
- self.assertEqual(rc, 0)
-
- def test_non_string_file_path(self):
- _, _, rc = run_script(self.SCRIPT, {"tool_input": {"file_path": 123}})
- self.assertEqual(rc, 0)
-
- def test_invalid_json(self):
- cmd = [sys.executable, os.path.join(SCRIPT_DIR, self.SCRIPT)]
- proc = subprocess.run(cmd, input="not json", capture_output=True, text=True, timeout=10)
- self.assertEqual(proc.returncode, 0)
-
- def test_nonexistent_file(self):
- _, _, rc = self._run("/nonexistent/path/note.md")
- self.assertEqual(rc, 0)
-
- def test_empty_object(self):
- _, _, rc = run_script(self.SCRIPT, {})
- self.assertEqual(rc, 0)
-
-
-# ---------------------------------------------------------------------------
-if __name__ == "__main__":
- unittest.main()
diff --git a/.claude/scripts/tests/_helpers.ts b/.claude/scripts/tests/_helpers.ts
new file mode 100644
index 0000000..111c07d
--- /dev/null
+++ b/.claude/scripts/tests/_helpers.ts
@@ -0,0 +1,38 @@
+/**
+ * Shared helpers for hook-entry integration tests.
+ *
+ * runScript spawns the hook entry point the same way settings.json does:
+ * `node --experimental-strip-types <script>` with JSON on stdin. Used by
+ * classify-message.test.ts and validate-write.test.ts to exercise the
+ * full stdin → stdout pipeline under the real runtime.
+ */
+
+import { spawnSync } from "node:child_process";
+
+export type RunResult = {
+ readonly stdout: string;
+ readonly stderr: string;
+ readonly code: number;
+};
+
+export function runScript(
+ scriptPath: string,
+ stdin: string | object | null,
+): RunResult {
+ const input =
+ stdin === null
+ ? ""
+ : typeof stdin === "string"
+ ? stdin
+ : JSON.stringify(stdin);
+ const proc = spawnSync(
+ process.execPath,
+ ["--experimental-strip-types", scriptPath],
+ { input, encoding: "utf-8", timeout: 10_000 },
+ );
+ return {
+ stdout: proc.stdout ?? "",
+ stderr: proc.stderr ?? "",
+ code: proc.status ?? -1,
+ };
+}
diff --git a/.claude/scripts/tests/charcount.test.ts b/.claude/scripts/tests/charcount.test.ts
new file mode 100644
index 0000000..d77920d
--- /dev/null
+++ b/.claude/scripts/tests/charcount.test.ts
@@ -0,0 +1,121 @@
+/**
+ * Unit tests for charcount section extraction and result formatting.
+ */
+
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+import { countSection, formatResult } from "../lib/charcount.ts";
+
+describe("countSection — plain section", () => {
+ const doc = [
+ "# Title",
+ "",
+ "### Intro",
+ "",
+ "Hello world.",
+ "",
+ "### Body",
+ "",
+ "Second section.",
+ "More content.",
+ "",
+ "### Outro",
+ "",
+ "Closing.",
+ "",
+ "## Next top",
+ "should not be included",
+ ].join("\n");
+
+ test("counts the requested section only", () => {
+ assert.equal(countSection(doc, { section: "Intro" }), "Hello world.".length);
+ });
+
+ test("stops at next ### heading", () => {
+ assert.equal(
+ countSection(doc, { section: "Body" }),
+ "Second section.More content.".length,
+ );
+ });
+
+ test("stops at next ## heading", () => {
+ assert.equal(countSection(doc, { section: "Outro" }), "Closing.".length);
+ });
+
+ test("returns 0 for missing section", () => {
+ assert.equal(countSection(doc, { section: "Nope" }), 0);
+ });
+
+ test("empty lines inside a section are skipped", () => {
+ const d = ["### S", "", "a", "", "b", "", "### Other"].join("\n");
+ assert.equal(countSection(d, { section: "S" }), 2);
+ });
+});
+
+describe("countSection — with sub-marker", () => {
+ const doc = [
+ "### Project Name",
+ "",
+ "**Current Level:**",
+ "senior",
+ "engineer",
+ "",
+ "**Next Level:**",
+ "staff",
+ "",
+ "### Other",
+ ].join("\n");
+
+ test("captures only the marker's block", () => {
+ assert.equal(
+ countSection(doc, { section: "Project Name", sub: "Current Level" }),
+ "seniorengineer".length,
+ );
+ });
+
+ test("stops at next bold marker", () => {
+ // Next Level block begins with a bold marker, ending Current Level capture
+ assert.equal(
+ countSection(doc, { section: "Project Name", sub: "Next Level" }),
+ "staff".length,
+ );
+ });
+
+ test("returns 0 when marker absent", () => {
+ assert.equal(
+ countSection(doc, { section: "Project Name", sub: "Missing" }),
+ 0,
+ );
+ });
+
+ test("returns 0 when section absent (even with sub)", () => {
+ assert.equal(
+ countSection(doc, { section: "Nope", sub: "Current Level" }),
+ 0,
+ );
+ });
+});
+
+describe("formatResult", () => {
+ test("no limit — prints bare count", () => {
+ assert.deepEqual(formatResult(847), { ok: true, output: "847" });
+ });
+ test("within limit — prints ✓", () => {
+ assert.deepEqual(formatResult(847, 1000), {
+ ok: true,
+ output: "847/1000 ✓",
+ });
+ });
+ test("exactly at limit — ✓", () => {
+ assert.deepEqual(formatResult(1000, 1000), {
+ ok: true,
+ output: "1000/1000 ✓",
+ });
+ });
+ test("over limit — ✗ with overage", () => {
+ assert.deepEqual(formatResult(847, 500), {
+ ok: false,
+ output: "847/500 ✗ (over by 347)",
+ });
+ });
+});
diff --git a/.claude/scripts/tests/classify-message.test.ts b/.claude/scripts/tests/classify-message.test.ts
new file mode 100644
index 0000000..1f4cfca
--- /dev/null
+++ b/.claude/scripts/tests/classify-message.test.ts
@@ -0,0 +1,391 @@
+/**
+ * Tests for classify-message: English + inflection + CJK + false-positive +
+ * subprocess integration coverage.
+ */
+
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+import { fileURLToPath } from "node:url";
+import { dirname, resolve } from "node:path";
+import { SIGNALS } from "../lib/signals.ts";
+import { classify } from "../lib/matcher.ts";
+import { runScript as spawnHook } from "./_helpers.ts";
+
+const SCRIPT = resolve(
+ dirname(fileURLToPath(import.meta.url)),
+ "../classify-message.ts",
+);
+
+function signalNames(prompt: string): string[] {
+ const messages = classify(prompt);
+ const byMessage = new Map(SIGNALS.map((s) => [s.message, s.name]));
+ return messages
+ .map((m) => byMessage.get(m) ?? "")
+ .filter((n) => n !== "")
+ .sort();
+}
+
+const runScript = (stdin: string | object | null) => spawnHook(SCRIPT, stdin);
+
+// ---------------------------------------------------------------------------
+// English signal detection (TestClassifyEnglish parity)
+// ---------------------------------------------------------------------------
+describe("classify — English signals", () => {
+ test("DECISION", () => {
+ assert.ok(signalNames("we decided to use Redis").includes("DECISION"));
+ });
+ test("INCIDENT", () => {
+ assert.ok(signalNames("there was an outage in prod").includes("INCIDENT"));
+ });
+ test("1:1 CONTENT", () => {
+ assert.ok(signalNames("had a 1:1 with my manager").includes("1:1 CONTENT"));
+ });
+ test("1:1 CONTENT (hyphen form)", () => {
+ assert.ok(signalNames("1-1 with Sarah today").includes("1:1 CONTENT"));
+ });
+ test("WIN", () => {
+ assert.ok(signalNames("got kudos from the team").includes("WIN"));
+ });
+ test("ARCHITECTURE", () => {
+ assert.ok(
+ signalNames("wrote a tech spec for the API").includes("ARCHITECTURE"),
+ );
+ });
+ test("PERSON CONTEXT", () => {
+ assert.ok(
+ signalNames("Alice told me about the deadline").includes(
+ "PERSON CONTEXT",
+ ),
+ );
+ });
+ test("PROJECT UPDATE", () => {
+ assert.ok(
+ signalNames("sprint planning for next week").includes("PROJECT UPDATE"),
+ );
+ });
+
+ test("overlap — 'shipped' triggers WIN and PROJECT UPDATE", () => {
+ const names = signalNames("we shipped the feature");
+ assert.ok(names.includes("WIN"));
+ assert.ok(names.includes("PROJECT UPDATE"));
+ });
+
+ test("overlap — 'deployed' triggers WIN and PROJECT UPDATE", () => {
+ const names = signalNames("deployed to production");
+ assert.ok(names.includes("WIN"));
+ assert.ok(names.includes("PROJECT UPDATE"));
+ });
+
+ test("multi-signal — DECISION + INCIDENT", () => {
+ const names = signalNames("we decided to fix the incident");
+ assert.ok(names.includes("DECISION"));
+ assert.ok(names.includes("INCIDENT"));
+ });
+
+ test("case insensitivity", () => {
+ assert.ok(signalNames("DECIDED to go with option A").includes("DECISION"));
+ });
+
+ test("return type is array", () => {
+ assert.ok(Array.isArray(classify("hello world")));
+ });
+
+ test("return items are strings", () => {
+ for (const item of classify("we decided to ship it")) {
+ assert.equal(typeof item, "string");
+ }
+ });
+});
+
+// ---------------------------------------------------------------------------
+// English inflections (TestClassifyInflections parity)
+// ---------------------------------------------------------------------------
+describe("classify — English inflections", () => {
+ test("deciding", () => {
+ assert.ok(
+ signalNames("we're still deciding on the approach").includes("DECISION"),
+ );
+ });
+ test("deploying", () => {
+ const n = signalNames("deploying the fix right now");
+ assert.ok(n.includes("WIN"));
+ assert.ok(n.includes("PROJECT UPDATE"));
+ });
+ test("shipping", () => {
+ const n = signalNames("shipping the feature today");
+ assert.ok(n.includes("WIN"));
+ assert.ok(n.includes("PROJECT UPDATE"));
+ });
+ test("merging", () => {
+ assert.ok(
+ signalNames("merging the PR this afternoon").includes("PROJECT UPDATE"),
+ );
+ });
+ test("launching", () => {
+ const n = signalNames("launching the new service tomorrow");
+ assert.ok(n.includes("WIN"));
+ assert.ok(n.includes("PROJECT UPDATE"));
+ });
+ test("completing", () => {
+ const n = signalNames("completing the migration this week");
+ assert.ok(n.includes("WIN"));
+ assert.ok(n.includes("PROJECT UPDATE"));
+ });
+ test("releasing", () => {
+ const n = signalNames("releasing v2.0 on Friday");
+ assert.ok(n.includes("WIN"));
+ assert.ok(n.includes("PROJECT UPDATE"));
+ });
+ test("achieving", () => {
+ assert.ok(signalNames("achieving the quarterly target").includes("WIN"));
+ });
+ test("rolling out", () => {
+ assert.ok(
+ signalNames("rolling out the new config").includes("PROJECT UPDATE"),
+ );
+ });
+ test("deploys (present -s)", () => {
+ const n = signalNames("she deploys to prod every Friday");
+ assert.ok(n.includes("WIN"));
+ assert.ok(n.includes("PROJECT UPDATE"));
+ });
+ test("launches", () => {
+ const n = signalNames("he launches the service tomorrow");
+ assert.ok(n.includes("WIN"));
+ assert.ok(n.includes("PROJECT UPDATE"));
+ });
+ test("ships", () => {
+ const n = signalNames("the team ships fast");
+ assert.ok(n.includes("WIN"));
+ assert.ok(n.includes("PROJECT UPDATE"));
+ });
+ test("merges", () => {
+ assert.ok(signalNames("she merges the PR").includes("PROJECT UPDATE"));
+ });
+ test("releases", () => {
+ const n = signalNames("he releases a new version weekly");
+ assert.ok(n.includes("WIN"));
+ assert.ok(n.includes("PROJECT UPDATE"));
+ });
+ test("release cut", () => {
+ assert.ok(
+ signalNames("did the release cut for v3.4").includes("PROJECT UPDATE"),
+ );
+ });
+});
+
+// ---------------------------------------------------------------------------
+// CJK signals (TestClassifyCJK parity with subTest)
+// ---------------------------------------------------------------------------
+type CJKCase = {
+ readonly signal: string;
+ readonly prompt: string;
+ readonly pattern: string;
+};
+
+const CJK_CASES: Readonly<Record<"ja" | "ko" | "zh", readonly CJKCase[]>> = {
+ ja: [
+ { signal: "DECISION", prompt: "チームで決定した", pattern: "決定した" },
+ { signal: "INCIDENT", prompt: "インシデントが発生しました", pattern: "インシデント" },
+ {
+ signal: "1:1 CONTENT",
+ prompt: "マネージャーとワンオンワンした",
+ pattern: "ワンオンワン",
+ },
+ { signal: "WIN", prompt: "新機能をリリースした", pattern: "リリースした" },
+ {
+ signal: "ARCHITECTURE",
+ prompt: "アーキテクチャの見直しが必要",
+ pattern: "アーキテクチャ",
+ },
+ { signal: "PERSON CONTEXT", prompt: "田中さんが言ってた", pattern: "言ってた" },
+ {
+ signal: "PROJECT UPDATE",
+ prompt: "今週のスプリントで完了する",
+ pattern: "スプリント",
+ },
+ ],
+ ko: [
+ { signal: "DECISION", prompt: "결정했습니다", pattern: "결정했습니다" },
+ { signal: "INCIDENT", prompt: "장애가 발생했습니다", pattern: "장애" },
+ { signal: "1:1 CONTENT", prompt: "원온원 미팅을 했습니다", pattern: "원온원" },
+ { signal: "WIN", prompt: "서비스를 출시했어", pattern: "출시했어" },
+ { signal: "ARCHITECTURE", prompt: "아키텍처 리뷰를 했습니다", pattern: "아키텍처" },
+ { signal: "PERSON CONTEXT", prompt: "김 매니저가 말했어", pattern: "말했어" },
+ { signal: "PROJECT UPDATE", prompt: "이번 스프린트에서 완료", pattern: "스프린트" },
+ ],
+ zh: [
+ { signal: "DECISION", prompt: "我们决定了这个方案", pattern: "决定了" },
+ { signal: "INCIDENT", prompt: "发生了故障需要处理", pattern: "故障" },
+ { signal: "1:1 CONTENT", prompt: "今天有一对一会议", pattern: "一对一" },
+ { signal: "WIN", prompt: "新版本发布了", pattern: "发布了" },
+ { signal: "ARCHITECTURE", prompt: "系统架构需要重新设计", pattern: "架构" },
+ { signal: "PERSON CONTEXT", prompt: "他提到了这个问题", pattern: "提到" },
+ { signal: "PROJECT UPDATE", prompt: "这个迭代的进展报告", pattern: "迭代" },
+ ],
+};
+
+describe("classify — CJK signals", () => {
+ for (const lang of ["ja", "ko", "zh"] as const) {
+ for (const c of CJK_CASES[lang]) {
+ test(`${lang}: ${c.pattern} → ${c.signal}`, () => {
+ assert.ok(
+ signalNames(c.prompt).includes(c.signal),
+ `${lang} pattern '${c.pattern}' should trigger ${c.signal}`,
+ );
+ });
+ }
+ }
+
+ test("mixed CJK + English (Japanese hiragana)", () => {
+ assert.ok(signalNames("のdecisionについて").includes("DECISION"));
+ });
+
+ test("mixed CJK + English (Chinese)", () => {
+ assert.ok(signalNames("我们decided了").includes("DECISION"));
+ });
+
+ test("mixed CJK + English (Korean)", () => {
+ assert.ok(signalNames("오늘 1:1 미팅").includes("1:1 CONTENT"));
+ });
+
+ test("CJK overlap — Chinese delivery word triggers WIN and PROJECT UPDATE", () => {
+ const n = signalNames("新版本发布了");
+ assert.ok(n.includes("WIN"));
+ assert.ok(n.includes("PROJECT UPDATE"));
+ });
+
+ test("CJK false positive (Japanese)", () => {
+ assert.deepEqual(signalNames("普通の会話です"), []);
+ });
+
+ test("CJK false positive (Korean)", () => {
+ assert.deepEqual(signalNames("코드 리뷰를 합시다"), []);
+ });
+
+ test("CJK false positive (Chinese)", () => {
+ assert.deepEqual(signalNames("今天天气不错"), []);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// False positives (TestClassifyFalsePositives parity)
+// ---------------------------------------------------------------------------
+describe("classify — no false positives", () => {
+ const NO_SIGNAL_CASES: ReadonlyArray<readonly [string, string]> = [
+ ["downloading the markdown file", "download ≠ any trigger"],
+ ["hello world", "generic greeting"],
+ ["just reading some code", "generic activity"],
+ ["the function returns an error", "generic error"],
+ ["I wonder about the implementation", "wonder ≠ won"],
+ ["she is predecisioned on this", "predecisioned ≠ decision"],
+ ["unshipped items in the backlog", "unshipped ≠ shipped"],
+ ["acknowledged the problem", "no trigger words"],
+ ];
+
+ for (const [prompt, reason] of NO_SIGNAL_CASES) {
+ test(`should not trigger: ${reason}`, () => {
+ assert.deepEqual(signalNames(prompt), [], `Should not trigger: ${reason}`);
+ });
+ }
+
+ test("empty string", () => {
+ assert.deepEqual(classify(""), []);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Subprocess integration (TestClassifyIntegration parity + new edge cases)
+// ---------------------------------------------------------------------------
+describe("classify-message (subprocess)", () => {
+ test("valid JSON with signal", () => {
+ const { stdout, code } = runScript({ prompt: "we decided to use React" });
+ assert.equal(code, 0);
+ const data = JSON.parse(stdout) as {
+ hookSpecificOutput: {
+ hookEventName: string;
+ additionalContext: string;
+ };
+ };
+ assert.equal(data.hookSpecificOutput.hookEventName, "UserPromptSubmit");
+ assert.ok(data.hookSpecificOutput.additionalContext.includes("DECISION"));
+ });
+
+ test("valid JSON no signal", () => {
+ const { stdout, code } = runScript({ prompt: "hello world" });
+ assert.equal(code, 0);
+ assert.equal(stdout.trim(), "");
+ });
+
+ test("invalid JSON", () => {
+ const { code } = runScript("not json{{");
+ assert.equal(code, 0);
+ });
+
+ test("missing prompt", () => {
+ const { code } = runScript({ foo: "bar" });
+ assert.equal(code, 0);
+ });
+
+ test("non-string prompt", () => {
+ const { code } = runScript({ prompt: 123 });
+ assert.equal(code, 0);
+ });
+
+ test("null prompt", () => {
+ const { code } = runScript({ prompt: null });
+ assert.equal(code, 0);
+ });
+
+ test("empty stdin", () => {
+ const { code } = runScript(null);
+ assert.equal(code, 0);
+ });
+
+ test("empty prompt string", () => {
+ const { code } = runScript({ prompt: "" });
+ assert.equal(code, 0);
+ });
+
+ // --- New: edge cases not in Python ---
+
+ test("preserves hook_event_name from input", () => {
+ const { stdout } = runScript({
+ prompt: "we decided",
+ hook_event_name: "SomeCustomEvent",
+ });
+ const data = JSON.parse(stdout) as {
+ hookSpecificOutput: { hookEventName: string };
+ };
+ assert.equal(data.hookSpecificOutput.hookEventName, "SomeCustomEvent");
+ });
+
+ test("handles truncated JSON gracefully", () => {
+ const { code } = runScript('{"prompt":"decide');
+ assert.equal(code, 0);
+ });
+
+ test("handles very large input without crash (500KB)", () => {
+ const big = "x".repeat(500_000) + " we decided";
+ const { code, stdout } = runScript({ prompt: big });
+ assert.equal(code, 0);
+ assert.ok(stdout.includes("DECISION"));
+ });
+});
+
+// ---------------------------------------------------------------------------
+// Perf bound
+// ---------------------------------------------------------------------------
+describe("classify — performance", () => {
+ test("1MB input classifies in under 500ms", () => {
+ const input = "lorem ipsum ".repeat(90_000) + " we decided to ship it";
+ const start = performance.now();
+ const result = classify(input);
+ const elapsed = performance.now() - start;
+ assert.ok(
+ elapsed < 500,
+ `classify took ${elapsed.toFixed(1)}ms on ~1MB input (budget 500ms)`,
+ );
+ assert.ok(result.length > 0);
+ });
+});
diff --git a/.claude/scripts/tests/frontmatter.test.ts b/.claude/scripts/tests/frontmatter.test.ts
new file mode 100644
index 0000000..8c1cbe4
--- /dev/null
+++ b/.claude/scripts/tests/frontmatter.test.ts
@@ -0,0 +1,127 @@
+/**
+ * Unit tests for frontmatter module — skip rules and content validation.
+ * Complements validate-write integration tests by testing the logic directly.
+ */
+
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+import { shouldSkipFile, validateContent } from "../lib/frontmatter.ts";
+
+describe("shouldSkipFile — skip rules", () => {
+ test("skips non-markdown", () => {
+ assert.equal(shouldSkipFile("/tmp/test.txt"), true);
+ });
+ test("skips empty path", () => {
+ assert.equal(shouldSkipFile(""), true);
+ });
+ test("skips README.md", () => {
+ assert.equal(shouldSkipFile("/some/path/README.md"), true);
+ });
+ test("skips translated READMEs", () => {
+ for (const lang of ["ja", "ko", "zh-CN"]) {
+ assert.equal(shouldSkipFile(`/some/path/README.${lang}.md`), true);
+ }
+ });
+ test("skips CHANGELOG.md", () => {
+ assert.equal(shouldSkipFile("/some/path/CHANGELOG.md"), true);
+ });
+ test("skips CLAUDE / AGENTS / GEMINI / CONTRIBUTING", () => {
+ for (const f of ["CLAUDE.md", "AGENTS.md", "GEMINI.md", "CONTRIBUTING.md"]) {
+ assert.equal(shouldSkipFile(`/vault/${f}`), true);
+ }
+ });
+ test("skips .claude/ paths", () => {
+ assert.equal(shouldSkipFile("/vault/.claude/commands/foo.md"), true);
+ });
+ test("skips .codex/ paths", () => {
+ assert.equal(shouldSkipFile("/vault/.codex/hooks.json.md"), true);
+ });
+ test("skips .gemini/ paths", () => {
+ assert.equal(shouldSkipFile("/vault/.gemini/settings.md"), true);
+ });
+ test("skips .github/ paths (PR templates, workflow docs)", () => {
+ assert.equal(shouldSkipFile("/repo/.github/pull_request_template.md"), true);
+ assert.equal(shouldSkipFile("/repo/.github/ISSUE_TEMPLATE/bug.md"), true);
+ });
+ test("skips templates/", () => {
+ assert.equal(shouldSkipFile("/vault/templates/Work Note.md"), true);
+ });
+ test("skips thinking/", () => {
+ assert.equal(shouldSkipFile("/vault/thinking/draft.md"), true);
+ });
+ test("skips Windows backslash path with .claude\\", () => {
+ assert.equal(shouldSkipFile("C:\\vault\\.claude\\commands\\foo.md"), true);
+ });
+ test("does NOT skip a regular vault note", () => {
+ assert.equal(shouldSkipFile("/vault/work/active/project.md"), false);
+ });
+ test("does NOT skip a normal .obsidian-ish name (only the literal segment matters)", () => {
+ // ".obsidianish.md" is a .md file not inside .obsidian/
+ assert.equal(shouldSkipFile("/vault/work/active/.obsidianish.md"), false);
+ });
+});
+
+describe("validateContent — frontmatter + wikilinks", () => {
+ test("missing frontmatter on long note", () => {
+ const warnings = validateContent("No frontmatter here\n" + "x".repeat(300));
+ assert.ok(warnings.includes("Missing YAML frontmatter"));
+ });
+
+ test("missing tags", () => {
+ const c =
+ "---\ndate: 2026-04-05\ndescription: test\n---\n# Note\n" +
+ "[[Link]] " +
+ "x".repeat(300);
+ const warnings = validateContent(c);
+ assert.ok(warnings.some((w) => w.includes("Missing `tags`")));
+ });
+
+ test("missing description", () => {
+ const c =
+ "---\ndate: 2026-04-05\ntags:\n - test\n---\n# Note\n" +
+ "[[Link]] " +
+ "x".repeat(300);
+ const warnings = validateContent(c);
+ assert.ok(warnings.some((w) => w.includes("Missing `description`")));
+ });
+
+ test("missing date", () => {
+ const c =
+ "---\ndescription: test\ntags:\n - test\n---\n# Note\n" +
+ "[[Link]] " +
+ "x".repeat(300);
+ const warnings = validateContent(c);
+ assert.ok(warnings.some((w) => w.includes("Missing `date`")));
+ });
+
+ test("no wikilinks on long note", () => {
+ const c =
+ "---\ndate: 2026-04-05\ndescription: test\ntags:\n - test\n---\n# Note\n" +
+ "x".repeat(300);
+ const warnings = validateContent(c);
+ assert.ok(warnings.some((w) => w.includes("No [[wikilinks]]")));
+ });
+
+ test("short note without wikilink is OK", () => {
+ const c =
+ "---\ndate: 2026-04-05\ndescription: test\ntags:\n - test\n---\nShort note.";
+ assert.deepEqual(validateContent(c), []);
+ });
+
+ test("valid long note with wikilink produces no warnings", () => {
+ const c =
+ "---\ndate: 2026-04-05\ndescription: A valid test note\ntags:\n - test\n---\n" +
+ "# Note\n\nSome content with [[a wikilink]] and more text.\n" +
+ "x".repeat(300);
+ assert.deepEqual(validateContent(c), []);
+ });
+
+ test("tolerates 'tags :' with space (alternate YAML style)", () => {
+ const c =
+ "---\ndate : 2026-04-05\ndescription : test\ntags :\n - test\n---\n# Note\n" +
+ "[[Link]] " +
+ "x".repeat(300);
+ // All three field checks should accept the alternate spacing.
+ assert.deepEqual(validateContent(c), []);
+ });
+});
diff --git a/.claude/scripts/tests/generate-changelog.test.ts b/.claude/scripts/tests/generate-changelog.test.ts
new file mode 100644
index 0000000..c1b8dae
--- /dev/null
+++ b/.claude/scripts/tests/generate-changelog.test.ts
@@ -0,0 +1,120 @@
+/**
+ * Unit tests for the pure functions in .github/scripts/generate-changelog.ts —
+ * commit classification, section generation, version normalization. The file-
+ * system mutations and git invocations are exercised separately by the
+ * release workflow on dry-run tags; these tests lock the parsing logic.
+ */
+
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+import {
+ classifyCommit,
+ generateSection,
+ normalizeVersion,
+} from "../../../.github/scripts/generate-changelog.ts";
+
+describe("classifyCommit", () => {
+ test("feat: → Added", () => {
+ const r = classifyCommit("feat: add new hook");
+ assert.equal(r.category, "Added");
+ assert.equal(r.description, "add new hook");
+ });
+
+ test("fix: → Fixed", () => {
+ const r = classifyCommit("fix: crash on empty input");
+ assert.equal(r.category, "Fixed");
+ assert.equal(r.description, "crash on empty input");
+ });
+
+ test("revert: → Fixed", () => {
+ const r = classifyCommit("revert: broken migration");
+ assert.equal(r.category, "Fixed");
+ });
+
+ test("docs: / refactor: / perf: / chore: / build: / style: → Changed", () => {
+ for (const prefix of ["docs", "refactor", "perf", "chore", "build", "style"]) {
+ const r = classifyCommit(`${prefix}: update something`);
+ assert.equal(r.category, "Changed", `${prefix} should map to Changed`);
+ }
+ });
+
+ test("ci: / test: / release: → null (skipped)", () => {
+ for (const prefix of ["ci", "test", "release"]) {
+ const r = classifyCommit(`${prefix}: noisy change`);
+ assert.equal(r.category, null, `${prefix} should be skipped`);
+ }
+ });
+
+ test("scoped prefix — feat(hooks): → Added", () => {
+ const r = classifyCommit("feat(hooks): add stop-checklist");
+ assert.equal(r.category, "Added");
+ assert.equal(r.description, "add stop-checklist");
+ });
+
+ test("strips PR reference suffix (#25)", () => {
+ const r = classifyCommit("feat: add thing (#25)");
+ assert.equal(r.description, "add thing");
+ });
+
+ test("no prefix — capitalizes and goes to Changed", () => {
+ const r = classifyCommit("some freeform commit");
+ assert.equal(r.category, "Changed");
+ assert.equal(r.description, "Some freeform commit");
+ });
+
+ test("unknown prefix falls through to Changed", () => {
+ const r = classifyCommit("wizardry: mysterious change");
+ assert.equal(r.category, "Changed");
+ });
+});
+
+describe("generateSection", () => {
+ test("groups commits by category in SECTION_ORDER", () => {
+ const out = generateSection("v5.0", [
+ "feat: add A",
+ "fix: fix B",
+ "docs: update C",
+ "feat: add D",
+ ]);
+ // Added section precedes Changed precedes Fixed per SECTION_ORDER
+ const addedIdx = out.indexOf("### Added");
+ const changedIdx = out.indexOf("### Changed");
+ const fixedIdx = out.indexOf("### Fixed");
+ assert.ok(addedIdx >= 0 && changedIdx >= 0 && fixedIdx >= 0);
+ assert.ok(addedIdx < changedIdx);
+ assert.ok(changedIdx < fixedIdx);
+ assert.match(out, /- add A\n/);
+ assert.match(out, /- add D\n/);
+ assert.match(out, /- fix B\n/);
+ assert.match(out, /- update C\n/);
+ });
+
+ test("skipped categories are not emitted", () => {
+ const out = generateSection("v5.0", ["ci: flake fix", "test: coverage"]);
+ assert.doesNotMatch(out, /### Added/);
+ assert.doesNotMatch(out, /### Changed/);
+ assert.doesNotMatch(out, /### Fixed/);
+ });
+
+ test("header carries the version", () => {
+ const out = generateSection("v5.0", ["feat: add thing"]);
+ assert.match(out, /^## v5\.0 — \d{4}-\d{2}-\d{2}/);
+ });
+});
+
+describe("normalizeVersion", () => {
+ // release.yml normalizes bare 'v5' → 'v5.0' before invoking this script,
+ // so the input shape is always vX.Y or vX.Y.Z by contract.
+ test("v5.2 → 5.2.0", () => {
+ assert.equal(normalizeVersion("v5.2"), "5.2.0");
+ });
+ test("v5.2.3 → 5.2.3", () => {
+ assert.equal(normalizeVersion("v5.2.3"), "5.2.3");
+ });
+ test("5.2 (no v) → 5.2.0", () => {
+ assert.equal(normalizeVersion("5.2"), "5.2.0");
+ });
+ test("5.2.3 (no v) → 5.2.3", () => {
+ assert.equal(normalizeVersion("5.2.3"), "5.2.3");
+ });
+});
diff --git a/.claude/scripts/tests/manifest-check.test.ts b/.claude/scripts/tests/manifest-check.test.ts
new file mode 100644
index 0000000..44a48da
--- /dev/null
+++ b/.claude/scripts/tests/manifest-check.test.ts
@@ -0,0 +1,98 @@
+/**
+ * Unit tests for manifest-check pure functions: globToRegex and isCovered.
+ * The filesystem walk and warning emission in the entry point are exercised
+ * live by the workflow; these lock the matching grammar.
+ */
+
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+import {
+ globToRegex,
+ isCovered,
+} from "../../../.github/scripts/manifest-check.ts";
+
+describe("globToRegex", () => {
+ test("exact string (no wildcards)", () => {
+ const r = globToRegex("CLAUDE.md");
+ assert.ok(r.test("CLAUDE.md"));
+ // dots must be escaped — a slash-separator should not match a dot
+ assert.ok(!r.test("CLAUDExmd"));
+ });
+
+ test("double-star matches any depth", () => {
+ const r = globToRegex(".claude/**");
+ assert.ok(r.test(".claude/commands/foo.md"));
+ assert.ok(r.test(".claude/scripts/lib/hook-io.ts"));
+ assert.ok(r.test(".claude/x"));
+ // bare prefix with no suffix should NOT match (preserves the sed-chain's behaviour)
+ assert.ok(!r.test(".claude"));
+ });
+
+ test("single-star is one path segment", () => {
+ const r = globToRegex(".claude/commands/*.md");
+ assert.ok(r.test(".claude/commands/foo.md"));
+ assert.ok(r.test(".claude/commands/a-b-c.md"));
+ // must not cross a slash
+ assert.ok(!r.test(".claude/commands/sub/foo.md"));
+ // must match the expected extension
+ assert.ok(!r.test(".claude/commands/foo.ts"));
+ });
+
+ test("double-star in the middle", () => {
+ const r = globToRegex("a/**/b.md");
+ assert.ok(r.test("a/x/b.md"));
+ assert.ok(r.test("a/x/y/b.md"));
+ });
+
+ test("escapes regex metacharacters in literal segments", () => {
+ const r = globToRegex("brain/Skills.md");
+ assert.ok(r.test("brain/Skills.md"));
+ // without escaping, . would match any character and 'Skillsxmd' would pass
+ assert.ok(!r.test("brain/Skillsxmd"));
+ });
+
+ test("anchors with ^ and $ (no prefix/suffix bleed)", () => {
+ const r = globToRegex("CLAUDE.md");
+ assert.ok(!r.test("xCLAUDE.md"));
+ assert.ok(!r.test("CLAUDE.mdx"));
+ });
+
+ test("plus and other regex specials are escaped", () => {
+ const r = globToRegex("a+b.md");
+ assert.ok(r.test("a+b.md"));
+ assert.ok(!r.test("ab.md"));
+ });
+});
+
+describe("isCovered", () => {
+ const GLOBS = [
+ "CLAUDE.md",
+ ".claude/**",
+ "templates/**",
+ "brain/Skills.md",
+ ];
+
+ test("exact-string glob matches the same string", () => {
+ assert.equal(isCovered("CLAUDE.md", GLOBS), true);
+ assert.equal(isCovered("brain/Skills.md", GLOBS), true);
+ });
+
+ test("wildcard glob matches any descendant", () => {
+ assert.equal(isCovered(".claude/scripts/foo.ts", GLOBS), true);
+ assert.equal(isCovered("templates/Work Note.md", GLOBS), true);
+ });
+
+ test("path outside any glob is not covered", () => {
+ assert.equal(isCovered("work/active/project.md", GLOBS), false);
+ assert.equal(isCovered("README.md", GLOBS), false);
+ });
+
+ test("empty glob list never covers anything", () => {
+ assert.equal(isCovered("anything", []), false);
+ });
+
+ test("exact-string glob does NOT match prefix variants", () => {
+ assert.equal(isCovered("CLAUDE.md.bak", GLOBS), false);
+ assert.equal(isCovered("x/CLAUDE.md", GLOBS), false);
+ });
+});
diff --git a/.claude/scripts/tests/matcher.test.ts b/.claude/scripts/tests/matcher.test.ts
new file mode 100644
index 0000000..b983906
--- /dev/null
+++ b/.claude/scripts/tests/matcher.test.ts
@@ -0,0 +1,68 @@
+/**
+ * Unit tests for the anyWordMatch core matcher: regex-boundary behavior,
+ * CJK adjacency, multi-word phrases, empty-input edge cases.
+ */
+
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+import { anyWordMatch } from "../lib/matcher.ts";
+
+describe("anyWordMatch", () => {
+ test("basic match", () => {
+ assert.equal(anyWordMatch(["hello"], "hello world"), true);
+ });
+
+ test("no match", () => {
+ assert.equal(anyWordMatch(["xyz"], "hello world"), false);
+ });
+
+ test("boundary prevents substring — 'decision' not in 'predecisioned'", () => {
+ assert.equal(anyWordMatch(["decision"], "predecisioned"), false);
+ });
+
+ test("boundary prevents prefix — 'shipped' not in 'unshipped'", () => {
+ assert.equal(anyWordMatch(["shipped"], "unshipped items"), false);
+ });
+
+ test("CJK adjacency — English keyword adjacent to CJK characters matches", () => {
+ assert.equal(anyWordMatch(["decision"], "のdecisionについて"), true);
+ });
+
+ test("multi-word phrase", () => {
+ assert.equal(
+ anyWordMatch(["one on one"], "had a one on one with Alice"),
+ true,
+ );
+ });
+
+ test("multi-word no partial — 'one on one' should not match 'one on two'", () => {
+ assert.equal(anyWordMatch(["one on one"], "one on two"), false);
+ });
+
+ test("CJK pattern match in CJK text", () => {
+ assert.equal(anyWordMatch(["決定した"], "チームで決定した"), true);
+ });
+
+ test("case sensitive (classify() lowercases first)", () => {
+ assert.equal(anyWordMatch(["decision"], "DECISION"), false);
+ assert.equal(anyWordMatch(["decision"], "decision"), true);
+ });
+
+ // --- Additions beyond Python parity ---
+
+ test("regex special chars in phrase are escaped", () => {
+ // '1:1' contains a colon which is not special, but defend against future edits
+ assert.equal(anyWordMatch(["1:1"], "had a 1:1 today"), true);
+ // Phrases with a dot — should match literally, not any-char
+ assert.equal(anyWordMatch(["v1.0"], "released v1.0 today"), true);
+ assert.equal(anyWordMatch(["v1.0"], "released v1x0 today"), false);
+ });
+
+ test("empty phrase list never matches", () => {
+ assert.equal(anyWordMatch([], "anything"), false);
+ });
+
+ test("empty text matches no non-empty phrase", () => {
+ assert.equal(anyWordMatch(["hello"], ""), false);
+ });
+});
diff --git a/.claude/scripts/tests/pre-compact.test.ts b/.claude/scripts/tests/pre-compact.test.ts
new file mode 100644
index 0000000..759a4e6
--- /dev/null
+++ b/.claude/scripts/tests/pre-compact.test.ts
@@ -0,0 +1,81 @@
+/**
+ * Unit tests for pre-compact helpers: timestamp format and retention-based pruning.
+ */
+
+import { test, describe, before, after } from "node:test";
+import assert from "node:assert/strict";
+import { mkdtempSync, writeFileSync, rmSync, readdirSync, utimesSync } from "node:fs";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
+import {
+ formatTimestamp,
+ listBackups,
+ pruneBackups,
+} from "../pre-compact.ts";
+
+describe("formatTimestamp", () => {
+ test("pads single digits (YYYYMMDD_HHMMSS)", () => {
+ const d = new Date(2026, 3, 5, 9, 7, 3); // month is 0-indexed → April
+ assert.equal(formatTimestamp(d), "20260405_090703");
+ });
+ test("two-digit components pass through", () => {
+ const d = new Date(2026, 9, 31, 23, 59, 59); // October 31
+ assert.equal(formatTimestamp(d), "20261031_235959");
+ });
+});
+
+describe("listBackups + pruneBackups", () => {
+ let dir = "";
+
+ before(() => {
+ dir = mkdtempSync(join(tmpdir(), "pre-compact-test-"));
+ });
+
+ after(() => {
+ if (dir) rmSync(dir, { recursive: true, force: true });
+ });
+
+ function makeBackup(name: string, ageSeconds: number): void {
+ const path = join(dir, name);
+ writeFileSync(path, "stub");
+ const t = Date.now() / 1000 - ageSeconds;
+ utimesSync(path, t, t);
+ }
+
+ test("lists only session_*.jsonl, sorted newest-first", () => {
+ makeBackup("session_a_20260101_000000.jsonl", 100);
+ makeBackup("session_b_20260102_000000.jsonl", 50);
+ makeBackup("session_c_20260103_000000.jsonl", 10);
+ writeFileSync(join(dir, "unrelated.txt"), "nope");
+ writeFileSync(join(dir, "session_missing_suffix"), "nope");
+
+ const ordered = listBackups(dir);
+ assert.deepEqual(ordered, [
+ "session_c_20260103_000000.jsonl",
+ "session_b_20260102_000000.jsonl",
+ "session_a_20260101_000000.jsonl",
+ ]);
+ });
+
+ test("prune keeps N newest by mtime", () => {
+ pruneBackups(dir, 2);
+ const remaining = readdirSync(dir)
+ .filter((f) => f.startsWith("session_") && f.endsWith(".jsonl"))
+ .sort();
+ assert.deepEqual(remaining, [
+ "session_b_20260102_000000.jsonl",
+ "session_c_20260103_000000.jsonl",
+ ]);
+ });
+
+ test("prune with retain ≥ count is a no-op", () => {
+ const before = readdirSync(dir).length;
+ pruneBackups(dir, 100);
+ const after = readdirSync(dir).length;
+ assert.equal(before, after);
+ });
+
+ test("listBackups on missing dir returns []", () => {
+ assert.deepEqual(listBackups("/nonexistent/dir/xyz"), []);
+ });
+});
diff --git a/.claude/scripts/tests/session-start.test.ts b/.claude/scripts/tests/session-start.test.ts
new file mode 100644
index 0000000..0240230
--- /dev/null
+++ b/.claude/scripts/tests/session-start.test.ts
@@ -0,0 +1,95 @@
+/**
+ * Unit tests for session-start pure helpers.
+ * The entry point itself (fs walk, git log, Obsidian CLI probe) is exercised
+ * live when the hook fires; these tests lock the deterministic formatting
+ * logic that doesn't need a real environment.
+ */
+
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+import {
+ take,
+ formatDateHeader,
+ formatActiveWork,
+ formatRecentChanges,
+ isSkippedPath,
+} from "../lib/session-start.ts";
+
+describe("take", () => {
+ test("keeps first N lines", () => {
+ assert.equal(take("a\nb\nc\nd", 2), "a\nb");
+ });
+ test("N >= line count is a pass-through", () => {
+ assert.equal(take("a\nb", 10), "a\nb");
+ });
+ test("empty string stays empty", () => {
+ assert.equal(take("", 5), "");
+ });
+});
+
+describe("formatDateHeader", () => {
+ test("pads single-digit month and day; includes weekday", () => {
+ const d = new Date(2026, 3, 5, 12, 0, 0); // April 5, 2026 (Sunday)
+ assert.equal(formatDateHeader(d), "2026-04-05 (Sunday)");
+ });
+ test("double-digit components pass through", () => {
+ const d = new Date(2026, 11, 25, 12, 0, 0); // December 25, 2026 (Friday)
+ assert.equal(formatDateHeader(d), "2026-12-25 (Friday)");
+ });
+});
+
+describe("formatActiveWork", () => {
+ test("strips .md, respects limit, returns sorted input order", () => {
+ const out = formatActiveWork(
+ ["project-a.md", "project-b.md", "project-c.md"],
+ 2,
+ );
+ assert.equal(out, "project-a\nproject-b");
+ });
+ test("filters out non-.md files", () => {
+ const out = formatActiveWork(
+ ["a.md", "b.txt", "c.md", ".DS_Store"],
+ 10,
+ );
+ assert.equal(out, "a\nc");
+ });
+ test("empty input → '(none)'", () => {
+ assert.equal(formatActiveWork([], 10), "(none)");
+ });
+ test("all-filtered-out → '(none)'", () => {
+ assert.equal(formatActiveWork(["not-markdown.txt"], 10), "(none)");
+ });
+});
+
+describe("formatRecentChanges", () => {
+ test("filters blank lines, respects limit", () => {
+ const out = formatRecentChanges("abc123 one\n\ndef456 two\n\nghi789 three", 2);
+ assert.equal(out, "abc123 one\ndef456 two");
+ });
+ test("empty git output → '(no git history)'", () => {
+ assert.equal(formatRecentChanges("", 15), "(no git history)");
+ });
+ test("whitespace-only git output → '(no git history)'", () => {
+ assert.equal(formatRecentChanges("\n\n\n", 15), "(no git history)");
+ });
+});
+
+describe("isSkippedPath", () => {
+ const PREFIXES = [".git", ".obsidian", "thinking", ".claude"];
+
+ test("exact prefix match is skipped", () => {
+ assert.equal(isSkippedPath(".git", PREFIXES), true);
+ });
+ test("child of prefix is skipped", () => {
+ assert.equal(isSkippedPath(".claude/commands/foo.md", PREFIXES), true);
+ });
+ test("segment-boundary enforcement — .github is NOT skipped under .git", () => {
+ assert.equal(isSkippedPath(".github/workflow.md", PREFIXES), false);
+ });
+ test("unrelated path is not skipped", () => {
+ assert.equal(isSkippedPath("work/active/note.md", PREFIXES), false);
+ });
+ test("empty prefix list never skips", () => {
+ assert.equal(isSkippedPath(".git/foo", []), false);
+ });
+});
diff --git a/.claude/scripts/tests/signals.test.ts b/.claude/scripts/tests/signals.test.ts
new file mode 100644
index 0000000..52b67c3
--- /dev/null
+++ b/.claude/scripts/tests/signals.test.ts
@@ -0,0 +1,133 @@
+/**
+ * Data-integrity tests for the SIGNALS table.
+ * New coverage — catches table edits that break invariants the runtime assumes.
+ */
+
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+import { SIGNALS } from "../lib/signals.ts";
+
+describe("SIGNALS table integrity", () => {
+ test("every signal has a non-empty name", () => {
+ for (const s of SIGNALS) {
+ assert.ok(s.name && s.name.length > 0, `signal name empty: ${JSON.stringify(s)}`);
+ }
+ });
+
+ test("signal names are unique", () => {
+ const names = SIGNALS.map((s) => s.name);
+ const unique = new Set(names);
+ assert.equal(unique.size, names.length, `duplicate names in SIGNALS: ${names}`);
+ });
+
+ test("every signal has a non-empty message", () => {
+ for (const s of SIGNALS) {
+ assert.ok(s.message.length > 0, `empty message for ${s.name}`);
+ }
+ });
+
+ test("every signal.message contains the signal.name", () => {
+ for (const s of SIGNALS) {
+ assert.ok(
+ s.message.includes(s.name),
+ `message for ${s.name} does not reference its name: ${s.message}`,
+ );
+ }
+ });
+
+ test("every signal has at least one pattern", () => {
+ for (const s of SIGNALS) {
+ assert.ok(s.patterns.length > 0, `no patterns for ${s.name}`);
+ }
+ });
+
+ test("no pattern is empty or whitespace-only", () => {
+ for (const s of SIGNALS) {
+ for (const p of s.patterns) {
+ assert.ok(p.trim().length > 0, `empty pattern in ${s.name}`);
+ }
+ }
+ });
+
+ test("patterns within a single signal are unique", () => {
+ for (const s of SIGNALS) {
+ const unique = new Set(s.patterns);
+ assert.equal(
+ unique.size,
+ s.patterns.length,
+ `duplicate patterns in ${s.name}`,
+ );
+ }
+ });
+
+ test("known cross-signal overlaps are preserved (WIN ↔ PROJECT UPDATE)", () => {
+ const win = SIGNALS.find((s) => s.name === "WIN");
+ const pu = SIGNALS.find((s) => s.name === "PROJECT UPDATE");
+ assert.ok(win && pu, "WIN and PROJECT UPDATE signals must exist");
+ // Intentional overlap: delivery verbs trigger both categories.
+ const shared = ["shipped", "launched", "deployed", "released", "completed"];
+ for (const verb of shared) {
+ assert.ok(
+ win.patterns.includes(verb),
+ `WIN must include delivery verb ${verb}`,
+ );
+ assert.ok(
+ pu.patterns.includes(verb),
+ `PROJECT UPDATE must include delivery verb ${verb}`,
+ );
+ }
+ });
+
+ test("cross-signal phrase sharing is limited to declared pairs", () => {
+ // Only WIN ↔ PROJECT UPDATE and WIN ↔ PROJECT UPDATE (via Chinese delivery
+ // verbs 发布了/上线了) should share patterns. Any other pair sharing a
+ // phrase is a table bug — patterns leak into unrelated categories.
+ const DECLARED_OVERLAP_PAIRS = new Set([
+ "WIN|PROJECT UPDATE",
+ "PROJECT UPDATE|WIN",
+ ]);
+
+ const phraseToSignals = new Map<string, string[]>();
+ for (const s of SIGNALS) {
+ for (const p of s.patterns) {
+ const list = phraseToSignals.get(p) ?? [];
+ if (!list.includes(s.name)) list.push(s.name);
+ phraseToSignals.set(p, list);
+ }
+ }
+
+ for (const [phrase, names] of phraseToSignals) {
+ if (names.length < 2) continue;
+ // Sort to get canonical pair key
+ const pairs: string[] = [];
+ for (let i = 0; i < names.length; i++) {
+ for (let j = i + 1; j < names.length; j++) {
+ pairs.push(`${names[i]}|${names[j]}`);
+ pairs.push(`${names[j]}|${names[i]}`);
+ }
+ }
+ const allDeclared = pairs.every((p) => DECLARED_OVERLAP_PAIRS.has(p));
+ assert.ok(
+ allDeclared,
+ `Phrase "${phrase}" matches multiple signals ${JSON.stringify(names)}; only WIN↔PROJECT UPDATE sharing is declared.`,
+ );
+ }
+ });
+
+ test("known signal categories are present", () => {
+ // Guards against accidental deletion. Additions do not require a test update.
+ const names = new Set(SIGNALS.map((s) => s.name));
+ const required = [
+ "DECISION",
+ "INCIDENT",
+ "1:1 CONTENT",
+ "WIN",
+ "ARCHITECTURE",
+ "PERSON CONTEXT",
+ "PROJECT UPDATE",
+ ];
+ for (const expected of required) {
+ assert.ok(names.has(expected), `missing signal: ${expected}`);
+ }
+ });
+});
diff --git a/.claude/scripts/tests/stop-checklist.test.ts b/.claude/scripts/tests/stop-checklist.test.ts
new file mode 100644
index 0000000..9446abb
--- /dev/null
+++ b/.claude/scripts/tests/stop-checklist.test.ts
@@ -0,0 +1,54 @@
+/**
+ * Integration tests for the Stop hook entry point.
+ * Locks the stop_hook_active bool-check semantics and the default-print
+ * behavior on malformed or missing input.
+ */
+
+import { test, describe } from "node:test";
+import assert from "node:assert/strict";
+import { fileURLToPath } from "node:url";
+import { dirname, resolve } from "node:path";
+import { runScript as spawnHook } from "./_helpers.ts";
+
+const SCRIPT = resolve(
+ dirname(fileURLToPath(import.meta.url)),
+ "../stop-checklist.ts",
+);
+const runScript = (stdin: string | object | null) => spawnHook(SCRIPT, stdin);
+
+describe("stop-checklist", () => {
+ test("silent when stop_hook_active is strict boolean true", () => {
+ const { stdout, code } = runScript({ stop_hook_active: true });
+ assert.equal(code, 0);
+ assert.equal(stdout.trim(), "");
+ });
+
+ test("prints checklist when stop_hook_active is false", () => {
+ const { stdout, code } = runScript({ stop_hook_active: false });
+ assert.equal(code, 0);
+ assert.match(stdout, /Session end checklist:/);
+ assert.match(stdout, /Archive completed projects/);
+ });
+
+ test("prints checklist when stop_hook_active is string 'true' (not strict)", () => {
+ const { stdout } = runScript({ stop_hook_active: "true" });
+ assert.match(stdout, /Session end checklist:/);
+ });
+
+ test("prints checklist when field is absent", () => {
+ const { stdout } = runScript({});
+ assert.match(stdout, /Session end checklist:/);
+ });
+
+ test("prints checklist on malformed JSON (safe default)", () => {
+ const { stdout, code } = runScript("garbage{{");
+ assert.equal(code, 0);
+ assert.match(stdout, /Session end checklist:/);
+ });
+
+ test("prints checklist on empty stdin", () => {
+ const { stdout, code } = runScript(null);
+ assert.equal(code, 0);
+ assert.match(stdout, /Session end checklist:/);
+ });
+});
diff --git a/.claude/scripts/tests/validate-write.test.ts b/.claude/scripts/tests/validate-write.test.ts
new file mode 100644
index 0000000..6644bda
--- /dev/null
+++ b/.claude/scripts/tests/validate-write.test.ts
@@ -0,0 +1,227 @@
+/**
+ * Subprocess integration tests for validate-write.ts — skip rules,
+ * frontmatter warnings, wikilink heuristic, robustness to bad input.
+ */
+
+import { test, describe, before, after } from "node:test";
+import assert from "node:assert/strict";
+import { fileURLToPath } from "node:url";
+import { dirname, join, resolve } from "node:path";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { runScript as spawnHook } from "./_helpers.ts";
+
+const SCRIPT = resolve(
+ dirname(fileURLToPath(import.meta.url)),
+ "../validate-write.ts",
+);
+
+let TMP_DIR = "";
+
+before(() => {
+ TMP_DIR = mkdtempSync(join(tmpdir(), "validate-write-test-"));
+});
+
+after(() => {
+ if (TMP_DIR) rmSync(TMP_DIR, { recursive: true, force: true });
+});
+
+const runScript = (stdin: string | object | null) => spawnHook(SCRIPT, stdin);
+
+function makeMd(content: string, name = "test.md"): string {
+ const path = join(TMP_DIR, name);
+ writeFileSync(path, content, { encoding: "utf-8" });
+ return path;
+}
+
+function runOn(filePath: string) {
+ return runScript({ tool_input: { file_path: filePath } });
+}
+
+// --- Skip rules ---
+describe("validate-write — skip rules (silent exit, no stdout)", () => {
+ test("skips non-markdown", () => {
+ const { stdout, code } = runOn("/tmp/test.txt");
+ assert.equal(code, 0);
+ assert.equal(stdout.trim(), "");
+ });
+ test("skips README.md", () => {
+ const { stdout, code } = runOn("/some/path/README.md");
+ assert.equal(code, 0);
+ assert.equal(stdout.trim(), "");
+ });
+ test("skips translated READMEs", () => {
+ for (const lang of ["ja", "ko", "zh-CN"]) {
+ const { stdout, code } = runOn(`/some/path/README.${lang}.md`);
+ assert.equal(code, 0);
+ assert.equal(stdout.trim(), "");
+ }
+ });
+ test("skips CHANGELOG.md", () => {
+ const { stdout, code } = runOn("/some/path/CHANGELOG.md");
+ assert.equal(code, 0);
+ assert.equal(stdout.trim(), "");
+ });
+ test("skips .claude/ dir", () => {
+ const { stdout, code } = runOn("/vault/.claude/commands/foo.md");
+ assert.equal(code, 0);
+ assert.equal(stdout.trim(), "");
+ });
+ test("skips templates/", () => {
+ const { stdout, code } = runOn("/vault/templates/Work Note.md");
+ assert.equal(code, 0);
+ assert.equal(stdout.trim(), "");
+ });
+ test("skips thinking/", () => {
+ const { stdout, code } = runOn("/vault/thinking/draft.md");
+ assert.equal(code, 0);
+ assert.equal(stdout.trim(), "");
+ });
+ test("skips Windows backslash path", () => {
+ const { stdout, code } = runOn("C:\\vault\\.claude\\commands\\foo.md");
+ assert.equal(code, 0);
+ assert.equal(stdout.trim(), "");
+ });
+});
+
+// --- Frontmatter validation ---
+describe("validate-write — frontmatter validation", () => {
+ test("missing frontmatter", () => {
+ const path = makeMd("No frontmatter here\n" + "x".repeat(300), "a.md");
+ const { stdout, code } = runOn(path);
+ assert.equal(code, 0);
+ const data = JSON.parse(stdout) as {
+ hookSpecificOutput: {
+ hookEventName: string;
+ additionalContext: string;
+ };
+ };
+ assert.equal(data.hookSpecificOutput.hookEventName, "PostToolUse");
+ assert.ok(
+ data.hookSpecificOutput.additionalContext.includes(
+ "Missing YAML frontmatter",
+ ),
+ );
+ });
+
+ test("missing tags", () => {
+ const path = makeMd(
+ "---\ndate: 2026-04-05\ndescription: test\n---\n# Note\n[[Link]] " +
+ "x".repeat(300),
+ "b.md",
+ );
+ const { stdout, code } = runOn(path);
+ assert.equal(code, 0);
+ assert.ok(stdout.includes("Missing `tags`"));
+ });
+
+ test("missing description", () => {
+ const path = makeMd(
+ "---\ndate: 2026-04-05\ntags:\n - test\n---\n# Note\n[[Link]] " +
+ "x".repeat(300),
+ "c.md",
+ );
+ const { stdout, code } = runOn(path);
+ assert.equal(code, 0);
+ assert.ok(stdout.includes("Missing `description`"));
+ });
+
+ test("missing date", () => {
+ const path = makeMd(
+ "---\ndescription: test\ntags:\n - test\n---\n# Note\n[[Link]] " +
+ "x".repeat(300),
+ "d.md",
+ );
+ const { stdout, code } = runOn(path);
+ assert.equal(code, 0);
+ assert.ok(stdout.includes("Missing `date`"));
+ });
+});
+
+// --- Wikilink validation ---
+describe("validate-write — wikilink validation", () => {
+ test("no wikilinks in long note", () => {
+ const path = makeMd(
+ "---\ndate: 2026-04-05\ndescription: test\ntags:\n - test\n---\n# Note\n" +
+ "x".repeat(300),
+ "e.md",
+ );
+ const { stdout, code } = runOn(path);
+ assert.equal(code, 0);
+ assert.ok(stdout.includes("No [[wikilinks]]"));
+ });
+
+ test("short note without wikilink is OK", () => {
+ const path = makeMd(
+ "---\ndate: 2026-04-05\ndescription: test\ntags:\n - test\n---\nShort note.",
+ "f.md",
+ );
+ const { stdout, code } = runOn(path);
+ assert.equal(code, 0);
+ assert.equal(stdout.trim(), "");
+ });
+});
+
+// --- Valid note ---
+describe("validate-write — valid note produces no warnings", () => {
+ test("fully-formed note", () => {
+ const path = makeMd(
+ "---\ndate: 2026-04-05\ndescription: A valid test note\ntags:\n - test\n---\n" +
+ "# Note\n\nSome content with [[a wikilink]] and more text.\n" +
+ "x".repeat(300),
+ "g.md",
+ );
+ const { stdout, code } = runOn(path);
+ assert.equal(code, 0);
+ assert.equal(stdout.trim(), "");
+ });
+});
+
+// --- Performance ---
+describe("validate-write — performance", () => {
+ test("1MB note validates in under 500ms", () => {
+ const path = join(TMP_DIR, "big.md");
+ const header =
+ "---\ndate: 2026-04-17\ndescription: large note\ntags:\n - test\n---\n[[link]]\n";
+ const body = "lorem ipsum ".repeat(90_000);
+ writeFileSync(path, header + body);
+
+ const start = performance.now();
+ const { code } = runScript({ tool_input: { file_path: path } });
+ const elapsed = performance.now() - start;
+
+ assert.equal(code, 0);
+ assert.ok(
+ elapsed < 1500,
+ `validate-write took ${elapsed.toFixed(1)}ms on ~1MB note (budget 1500ms; includes subprocess spawn)`,
+ );
+ });
+});
+
+// --- Type safety ---
+describe("validate-write — robustness to bad input", () => {
+ test("null tool_input", () => {
+ const { code } = runScript({ tool_input: null });
+ assert.equal(code, 0);
+ });
+ test("non-string file_path", () => {
+ const { code } = runScript({ tool_input: { file_path: 123 } });
+ assert.equal(code, 0);
+ });
+ test("invalid JSON", () => {
+ const { code } = runScript("not json");
+ assert.equal(code, 0);
+ });
+ test("nonexistent file", () => {
+ const { code } = runOn("/nonexistent/path/note.md");
+ assert.equal(code, 0);
+ });
+ test("empty object", () => {
+ const { code } = runScript({});
+ assert.equal(code, 0);
+ });
+ test("empty stdin", () => {
+ const { code } = runScript(null);
+ assert.equal(code, 0);
+ });
+});
diff --git a/.claude/scripts/tsconfig.json b/.claude/scripts/tsconfig.json
new file mode 100644
index 0000000..8c1dec4
--- /dev/null
+++ b/.claude/scripts/tsconfig.json
@@ -0,0 +1,20 @@
+{
+ "compilerOptions": {
+ "target": "es2023",
+ "module": "nodenext",
+ "moduleResolution": "nodenext",
+ "allowImportingTsExtensions": true,
+ "noEmit": true,
+ "strict": true,
+ "noUncheckedIndexedAccess": true,
+ "exactOptionalPropertyTypes": true,
+ "verbatimModuleSyntax": true,
+ "isolatedModules": true,
+ "skipLibCheck": true,
+ "lib": ["es2023"],
+ "types": ["node"],
+ "resolveJsonModule": true
+ },
+ "include": ["**/*.ts", "../../.github/scripts/**/*.ts"],
+ "exclude": ["node_modules"]
+}
diff --git a/.claude/scripts/validate-write.py b/.claude/scripts/validate-write.py
deleted file mode 100755
index d47aeaf..0000000
--- a/.claude/scripts/validate-write.py
+++ /dev/null
@@ -1,81 +0,0 @@
-#!/usr/bin/env python3
-"""Post-write validation for vault notes."""
-import json
-import sys
-import os
-from pathlib import Path
-
-def main():
- try:
- input_data = json.load(sys.stdin)
- except (ValueError, EOFError, OSError):
- sys.exit(0)
-
- tool_input = input_data.get("tool_input")
- if not isinstance(tool_input, dict):
- sys.exit(0)
-
- file_path = tool_input.get("file_path", "")
- if not isinstance(file_path, str) or not file_path:
- sys.exit(0)
-
- # Only validate markdown files in the vault, skip dotfiles and templates
- if not file_path.endswith(".md"):
- sys.exit(0)
- # Normalize path separators for cross-platform matching (Windows uses backslashes)
- normalized = file_path.replace("\\", "/")
- # Skip dotfiles, templates, thinking, and root template files (not vault notes)
- basename = os.path.basename(normalized)
- root_files = {"README.md", "CHANGELOG.md", "CONTRIBUTING.md", "CLAUDE.md", "AGENTS.md", "GEMINI.md"}
- if basename in root_files:
- sys.exit(0)
- # Also skip translated READMEs (README.ja.md, README.zh-CN.md, etc.)
- if basename.startswith("README.") and basename.endswith(".md"):
- sys.exit(0)
- if any(skip in normalized for skip in [".claude/", ".obsidian/", "templates/", "thinking/"]):
- sys.exit(0)
-
- warnings = []
-
- try:
- content = Path(file_path).read_text(encoding="utf-8")
-
- # Check for frontmatter
- if not content.startswith("---"):
- warnings.append("Missing YAML frontmatter")
- else:
- parts = content.split("---", 2)
- if len(parts) >= 3:
- fm = parts[1]
- if "tags:" not in fm and "tags :" not in fm:
- warnings.append("Missing `tags` in frontmatter")
- if "description:" not in fm and "description :" not in fm:
- warnings.append("Missing `description` in frontmatter (~150 chars required by vault convention)")
- if "date:" not in fm and "date :" not in fm:
- warnings.append("Missing `date` in frontmatter")
-
- # Check for wikilinks (skip very short notes)
- if len(content) > 300 and "[[" not in content:
- warnings.append("No [[wikilinks]] found — every note must link to at least one other note (vault convention)")
-
- except Exception:
- sys.exit(0)
-
- if warnings:
- hint_list = "\n".join(f" - {w}" for w in warnings)
- output = {
- "hookSpecificOutput": {
- "hookEventName": input_data.get("hook_event_name", "PostToolUse"),
- "additionalContext": f"Vault hygiene warnings for `{basename}`:\n{hint_list}\nFix these before moving on."
- }
- }
- json.dump(output, sys.stdout)
- sys.stdout.flush()
-
- sys.exit(0)
-
-if __name__ == "__main__":
- try:
- main()
- except Exception:
- sys.exit(0)
diff --git a/.claude/scripts/validate-write.ts b/.claude/scripts/validate-write.ts
new file mode 100644
index 0000000..e84a116
--- /dev/null
+++ b/.claude/scripts/validate-write.ts
@@ -0,0 +1,63 @@
+#!/usr/bin/env node
+/**
+ * PostToolUse hook — validate vault notes after Write/Edit operations.
+ *
+ * Reads the hook JSON payload from stdin, inspects the tool_input.file_path,
+ * skips files outside the vault-note scope (dotfiles, templates, root docs,
+ * translated READMEs, thinking drafts), and emits a hookSpecificOutput with
+ * vault hygiene warnings when frontmatter or wikilinks are missing.
+ */
+
+import { basename } from "node:path";
+import { debug, readStdinJson, writeHookOutput } from "./lib/hook-io.ts";
+import { shouldSkipFile, validateFile } from "./lib/frontmatter.ts";
+
+type HookInput = {
+ readonly tool_input?: unknown;
+ readonly hook_event_name?: unknown;
+};
+
+const input = await readStdinJson<HookInput>();
+if (!input) {
+ debug("validate: null input");
+ process.exit(0);
+}
+
+const toolInput = input.tool_input;
+if (!toolInput || typeof toolInput !== "object") {
+ debug("validate: missing tool_input");
+ process.exit(0);
+}
+
+const filePath = (toolInput as Record<string, unknown>).file_path;
+if (typeof filePath !== "string" || !filePath) {
+ debug("validate: missing file_path");
+ process.exit(0);
+}
+
+if (shouldSkipFile(filePath)) {
+ debug(`validate: skipped ${filePath}`);
+ process.exit(0);
+}
+
+const warnings = validateFile(filePath);
+if (warnings === null) {
+ debug(`validate: could not read ${filePath}`);
+ process.exit(0);
+}
+debug(`validate: ${filePath} — ${warnings.length} warning(s)`);
+
+if (warnings.length > 0) {
+ const hintList = warnings.map((w) => ` - ${w}`).join("\n");
+ const base = basename(filePath.replaceAll("\\", "/"));
+ const additionalContext = `Vault hygiene warnings for \`${base}\`:\n${hintList}\nFix these before moving on.`;
+
+ const eventName =
+ typeof input.hook_event_name === "string"
+ ? input.hook_event_name
+ : "PostToolUse";
+
+ writeHookOutput(eventName, additionalContext);
+}
+
+process.exit(0);
diff --git a/.claude/settings.json b/.claude/settings.json
index 212bec1..8d5b71b 100644
--- a/.claude/settings.json
+++ b/.claude/settings.json
@@ -6,7 +6,7 @@
"hooks": [
{
"type": "command",
- "command": "bash .claude/scripts/session-start.sh",
+ "command": "node --experimental-strip-types .claude/scripts/session-start.ts",
"timeout": 30
}
]
@@ -17,7 +17,7 @@
"hooks": [
{
"type": "command",
- "command": "bash .claude/scripts/find-python.sh .claude/scripts/classify-message.py",
+ "command": "node --experimental-strip-types .claude/scripts/classify-message.ts",
"timeout": 15
}
]
@@ -29,7 +29,7 @@
"hooks": [
{
"type": "command",
- "command": "bash .claude/scripts/find-python.sh .claude/scripts/validate-write.py",
+ "command": "node --experimental-strip-types .claude/scripts/validate-write.ts",
"timeout": 15
}
]
@@ -40,7 +40,7 @@
"hooks": [
{
"type": "command",
- "command": "bash .claude/scripts/pre-compact.sh",
+ "command": "node --experimental-strip-types .claude/scripts/pre-compact.ts",
"timeout": 30
}
]
@@ -51,7 +51,7 @@
"hooks": [
{
"type": "command",
- "command": "bash -c 'INPUT=$(cat); ACTIVE=$(printf \"%s\" \"$INPUT\" | bash .claude/scripts/find-python.sh -c \"import json,sys; print(json.load(sys.stdin).get(\\\"stop_hook_active\\\",False))\" 2>/dev/null || echo False); [ \"$ACTIVE\" = \"True\" ] && exit 0; echo \"Session end checklist:\n- Archive completed projects? (work/active/ -> work/archive/YYYY/)\n- Update indexes? (Index.md, Memories.md, People & Context, Brag Doc)\n- New notes linked? (orphans are bugs)\n- Run /om-vault-audit if many notes were created/modified\"'",
+ "command": "node --experimental-strip-types .claude/scripts/stop-checklist.ts",
"timeout": 5
}
]
diff --git a/.claude/update-skills.sh b/.claude/update-skills.sh
deleted file mode 100755
index 5a13498..0000000
--- a/.claude/update-skills.sh
+++ /dev/null
@@ -1,26 +0,0 @@
-#!/bin/bash
-# Update obsidian-skills from upstream (kepano/obsidian-skills)
-# Run from vault root: .claude/update-skills.sh
-
-set -e
-
-REPO="kepano/obsidian-skills"
-SKILLS_DIR=".claude/skills"
-TEMP_DIR=$(mktemp -d)
-
-echo "Fetching latest obsidian-skills from $REPO..."
-git clone --depth 1 "https://github.com/$REPO.git" "$TEMP_DIR" 2>/dev/null
-
-for skill in "$TEMP_DIR/skills/"*/; do
- skill_name=$(basename "$skill")
- if [ -d "$SKILLS_DIR/$skill_name" ]; then
- echo "Updating $skill_name..."
- cp -R "$skill"* "$SKILLS_DIR/$skill_name/"
- else
- echo "New skill found: $skill_name — copying..."
- cp -R "$skill" "$SKILLS_DIR/$skill_name"
- fi
-done
-
-rm -rf "$TEMP_DIR"
-echo "Done. Skills updated to latest."
diff --git a/.claude/update-skills.ts b/.claude/update-skills.ts
new file mode 100644
index 0000000..a3770ad
--- /dev/null
+++ b/.claude/update-skills.ts
@@ -0,0 +1,57 @@
+#!/usr/bin/env node
+/**
+ * Update obsidian-skills from the kepano/obsidian-skills upstream.
+ *
+ * Run from vault root:
+ * node --experimental-strip-types .claude/update-skills.ts
+ */
+
+import { spawnSync } from "node:child_process";
+import {
+ mkdtempSync,
+ rmSync,
+ cpSync,
+ existsSync,
+ readdirSync,
+} from "node:fs";
+import { join } from "node:path";
+import { tmpdir } from "node:os";
+
+const REPO = "kepano/obsidian-skills";
+const SKILLS_DIR = ".claude/skills";
+
+const tempDir = mkdtempSync(join(tmpdir(), "obsidian-skills-"));
+
+try {
+ console.log(`Fetching latest obsidian-skills from ${REPO}...`);
+ const clone = spawnSync(
+ "git",
+ ["clone", "--depth", "1", `https://github.com/${REPO}.git`, tempDir],
+ { stdio: "inherit" },
+ );
+ if (clone.status !== 0) {
+ console.error(`git clone failed (exit ${clone.status})`);
+ process.exit(1);
+ }
+
+ const sourceSkillsDir = join(tempDir, "skills");
+ const sourceSkills = readdirSync(sourceSkillsDir, { withFileTypes: true })
+ .filter((e) => e.isDirectory())
+ .map((e) => e.name);
+
+ for (const skillName of sourceSkills) {
+ const src = join(sourceSkillsDir, skillName);
+ const dest = join(SKILLS_DIR, skillName);
+ const isUpdate = existsSync(dest);
+ console.log(
+ isUpdate
+ ? `Updating ${skillName}...`
+ : `New skill found: ${skillName} — copying...`,
+ );
+ cpSync(src, dest, { recursive: true });
+ }
+
+ console.log("Done. Skills updated to latest.");
+} finally {
+ rmSync(tempDir, { recursive: true, force: true });
+}
diff --git a/.codex/hooks.json b/.codex/hooks.json
index abd74a7..81bbb03 100644
--- a/.codex/hooks.json
+++ b/.codex/hooks.json
@@ -6,7 +6,7 @@
"hooks": [
{
"type": "command",
- "command": "bash .claude/scripts/session-start.sh",
+ "command": "node --experimental-strip-types .claude/scripts/session-start.ts",
"timeout": 30
}
]
@@ -17,7 +17,7 @@
"hooks": [
{
"type": "command",
- "command": "bash .claude/scripts/find-python.sh .claude/scripts/classify-message.py",
+ "command": "node --experimental-strip-types .claude/scripts/classify-message.ts",
"timeout": 15
}
]
@@ -29,7 +29,7 @@
"hooks": [
{
"type": "command",
- "command": "bash .claude/scripts/find-python.sh .claude/scripts/validate-write.py",
+ "command": "node --experimental-strip-types .claude/scripts/validate-write.ts",
"timeout": 15
}
]
diff --git a/.gemini/settings.json b/.gemini/settings.json
index 9085759..e6affe0 100644
--- a/.gemini/settings.json
+++ b/.gemini/settings.json
@@ -6,7 +6,7 @@
"hooks": [
{
"type": "command",
- "command": "bash .claude/scripts/session-start.sh",
+ "command": "node --experimental-strip-types .claude/scripts/session-start.ts",
"timeout": 30000
}
]
@@ -17,7 +17,7 @@
"hooks": [
{
"type": "command",
- "command": "bash .claude/scripts/find-python.sh .claude/scripts/classify-message.py",
+ "command": "node --experimental-strip-types .claude/scripts/classify-message.ts",
"timeout": 15000
}
]
@@ -29,7 +29,7 @@
"hooks": [
{
"type": "command",
- "command": "bash .claude/scripts/find-python.sh .claude/scripts/validate-write.py",
+ "command": "node --experimental-strip-types .claude/scripts/validate-write.ts",
"timeout": 15000
}
]
@@ -40,7 +40,7 @@
"hooks": [
{
"type": "command",
- "command": "bash .claude/scripts/pre-compact.sh",
+ "command": "node --experimental-strip-types .claude/scripts/pre-compact.ts",
"timeout": 30000
}
]
diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md
index 0bbb699..8e23143 100644
--- a/.github/pull_request_template.md
+++ b/.github/pull_request_template.md
@@ -20,6 +20,6 @@
## Checklist
- [ ] PR title follows `type: description` format
-- [ ] Tests pass (`python .claude/scripts/test_hooks.py`)
+- [ ] Tests pass (`cd .claude/scripts && npm test`)
- [ ] Doc tables updated if adding commands/agents (CLAUDE.md, README, Skills.md, translations)
- [ ] No changes to CHANGELOG.md or vault-manifest.json version (automated by release pipeline)
diff --git a/.github/scripts/generate-changelog.py b/.github/scripts/generate-changelog.py
deleted file mode 100644
index 8ccdb77..0000000
--- a/.github/scripts/generate-changelog.py
+++ /dev/null
@@ -1,185 +0,0 @@
-#!/usr/bin/env python3
-"""Generate a CHANGELOG.md entry from commits since the previous tag.
-
-Usage: generate-changelog.py <version>
- e.g. generate-changelog.py v3.8
-
-Outputs:
- - Prepends new section to CHANGELOG.md (or replaces if version exists)
- - Updates vault-manifest.json version and released date
- - Prints the generated section to stdout (for use as GitHub Release body)
-"""
-
-import json
-import re
-import subprocess
-import sys
-from datetime import datetime, timezone
-
-PREFIX_MAP = {
- "feat": "Added",
- "fix": "Fixed",
- "docs": "Changed",
- "ci": "Changed",
- "refactor": "Changed",
- "perf": "Changed",
- "test": "Changed",
- "chore": "Changed",
- "build": "Changed",
- "style": "Changed",
- "revert": "Fixed",
-}
-
-SKIP_PREFIXES = {"release", "ci", "test"}
-
-SECTION_ORDER = ["Added", "Changed", "Fixed", "Removed"]
-
-
-def run_git(*args):
- result = subprocess.run(
- ["git"] + list(args),
- capture_output=True, text=True
- )
- if result.returncode != 0:
- print(f"git {' '.join(args)} failed: {result.stderr.strip()}", file=sys.stderr)
- sys.exit(1)
- return result.stdout.strip()
-
-
-def get_previous_tag():
- output = run_git("tag", "--sort=-version:refname")
- tags = [t.strip() for t in output.split("\n") if t.strip()]
- if len(tags) >= 2:
- return tags[1]
- return None
-
-
-def get_commits(since_tag):
- if since_tag:
- range_spec = f"{since_tag}..HEAD"
- else:
- range_spec = "HEAD"
-
- output = run_git("log", range_spec, "--pretty=format:%s", "--first-parent")
- return [line.strip() for line in output.split("\n") if line.strip()]
-
-
-def classify_commit(message):
- # Strip PR reference suffix like (#25)
- clean = re.sub(r'\s*\(#\d+\)\s*$', '', message)
-
- # Try prefix match: "feat: description" or "feat(scope): description"
- match = re.match(r'^(\w+)(?:\([^)]*\))?\s*:\s*(.+)$', clean)
- if match:
- prefix = match.group(1).lower()
- description = match.group(2).strip()
- if prefix in SKIP_PREFIXES:
- return None, None
- category = PREFIX_MAP.get(prefix, "Changed")
- return category, description
-
- # No prefix — capitalize first letter, put in Changed
- if not clean:
- return "Changed", clean
- return "Changed", clean[0].upper() + clean[1:]
-
-
-def generate_section(version, commits):
- today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
- grouped = {}
-
- for msg in commits:
- category, description = classify_commit(msg)
- if category is None:
- continue
- if category not in grouped:
- grouped[category] = []
- grouped[category].append(description)
-
- lines = [f"## {version} — {today}", ""]
-
- for section in SECTION_ORDER:
- if section in grouped:
- lines.append(f"### {section}")
- for item in grouped[section]:
- lines.append(f"- {item}")
- lines.append("")
-
- return "\n".join(lines)
-
-
-def prepend_to_changelog(section, version):
- with open("CHANGELOG.md", "r", encoding="utf-8") as f:
- content = f.read()
-
- # Check if this version already exists (idempotent on re-runs)
- version_pattern = rf"(?m)^## {re.escape(version)} — .*$"
- # Match everything from this version header up to the next version header (or end of file)
- existing_pattern = rf"(?ms)^## {re.escape(version)} — .*?(?=\n## [^\n]|\Z)"
- if re.search(version_pattern, content):
- new_content = re.sub(existing_pattern, section.rstrip(), content, count=1)
- else:
- # Insert after the "# Changelog" header
- header = "# Changelog"
- idx = content.find(header)
- if idx == -1:
- new_content = f"{header}\n\n{section}\n{content}"
- else:
- insert_at = idx + len(header)
- while insert_at < len(content) and content[insert_at] in ("\n", "\r"):
- insert_at += 1
- new_content = content[:insert_at] + "\n" + section + "\n" + content[insert_at:]
-
- with open("CHANGELOG.md", "w", encoding="utf-8") as f:
- f.write(new_content)
-
-
-def normalize_version(version):
- match = re.fullmatch(r"v?(\d+)\.(\d+)(?:\.(\d+))?", version)
- if not match:
- print(f"Invalid version '{version}'. Expected vX.Y or vX.Y.Z.", file=sys.stderr)
- sys.exit(1)
- major, minor, patch = match.groups()
- return f"{major}.{minor}.{patch or '0'}"
-
-
-def update_manifest(version):
- with open("vault-manifest.json", "r", encoding="utf-8") as f:
- manifest = json.load(f)
-
- manifest["version"] = normalize_version(version)
- manifest["released"] = datetime.now(timezone.utc).strftime("%Y-%m-%d")
-
- with open("vault-manifest.json", "w", encoding="utf-8") as f:
- json.dump(manifest, f, indent=2, ensure_ascii=False)
- f.write("\n")
-
-
-def main():
- if len(sys.argv) < 2:
- print("Usage: generate-changelog.py <version>", file=sys.stderr)
- sys.exit(1)
-
- version = sys.argv[1]
- prev_tag = get_previous_tag()
- commits = get_commits(prev_tag)
-
- if not commits:
- print("No commits found since previous tag.", file=sys.stderr)
- sys.exit(1)
-
- section = generate_section(version, commits)
-
- if not any(classify_commit(msg)[0] is not None for msg in commits):
- print("All commits were skipped (ci/test/release only). Nothing to changelog.", file=sys.stderr)
- sys.exit(1)
-
- prepend_to_changelog(section, version)
- update_manifest(version)
-
- # Print section for GitHub Release body
- print(section)
-
-
-if __name__ == "__main__":
- main()
diff --git a/.github/scripts/generate-changelog.ts b/.github/scripts/generate-changelog.ts
new file mode 100644
index 0000000..530137b
--- /dev/null
+++ b/.github/scripts/generate-changelog.ts
@@ -0,0 +1,226 @@
+#!/usr/bin/env node
+/**
+ * Generate a CHANGELOG.md entry from commits since the previous tag.
+ *
+ * Usage: node --experimental-strip-types generate-changelog.ts <version>
+ * e.g. generate-changelog.ts v5.0
+ *
+ * Outputs:
+ * - Prepends new section to CHANGELOG.md (or replaces if version exists)
+ * - Updates vault-manifest.json version and released date
+ * - Prints the generated section to stdout (for use as GitHub Release body)
+ */
+
+import { spawnSync } from "node:child_process";
+import { fileURLToPath } from "node:url";
+import { readFileSync, writeFileSync } from "node:fs";
+
+const PREFIX_MAP: Readonly<Record<string, string>> = {
+ feat: "Added",
+ fix: "Fixed",
+ docs: "Changed",
+ ci: "Changed",
+ refactor: "Changed",
+ perf: "Changed",
+ test: "Changed",
+ chore: "Changed",
+ build: "Changed",
+ style: "Changed",
+ revert: "Fixed",
+};
+
+const SKIP_PREFIXES: ReadonlySet<string> = new Set(["release", "ci", "test"]);
+
+const SECTION_ORDER: readonly string[] = ["Added", "Changed", "Fixed", "Removed"];
+
+function runGit(...args: string[]): string {
+ const proc = spawnSync("git", args, { encoding: "utf-8" });
+ if (proc.status !== 0) {
+ process.stderr.write(
+ `git ${args.join(" ")} failed: ${(proc.stderr ?? "").trim()}\n`,
+ );
+ process.exit(1);
+ }
+ return (proc.stdout ?? "").trim();
+}
+
+function getPreviousTag(): string | null {
+ const output = runGit("tag", "--sort=-version:refname");
+ const tags = output
+ .split("\n")
+ .map((t) => t.trim())
+ .filter((t) => t.length > 0);
+ return tags.length >= 2 ? (tags[1] ?? null) : null;
+}
+
+function getCommits(sinceTag: string | null): string[] {
+ const range = sinceTag ? `${sinceTag}..HEAD` : "HEAD";
+ const output = runGit("log", range, "--pretty=format:%s", "--first-parent");
+ return output
+ .split("\n")
+ .map((l) => l.trim())
+ .filter((l) => l.length > 0);
+}
+
+type ClassifiedCommit = {
+ readonly category: string | null;
+ readonly description: string;
+};
+
+export function classifyCommit(message: string): ClassifiedCommit {
+ // Strip PR reference suffix like (#25)
+ const clean = message.replace(/\s*\(#\d+\)\s*$/, "");
+
+ // Prefix match: "feat: desc" or "feat(scope): desc"
+ const match = /^(\w+)(?:\([^)]*\))?\s*:\s*(.+)$/.exec(clean);
+ if (match) {
+ const prefix = (match[1] ?? "").toLowerCase();
+ const description = (match[2] ?? "").trim();
+ if (SKIP_PREFIXES.has(prefix)) return { category: null, description: "" };
+ const category = PREFIX_MAP[prefix] ?? "Changed";
+ return { category, description };
+ }
+
+ if (!clean) return { category: "Changed", description: clean };
+ return {
+ category: "Changed",
+ description: clean[0]!.toUpperCase() + clean.slice(1),
+ };
+}
+
+function todayUTC(): string {
+ const d = new Date();
+ const year = d.getUTCFullYear();
+ const month = String(d.getUTCMonth() + 1).padStart(2, "0");
+ const day = String(d.getUTCDate()).padStart(2, "0");
+ return `${year}-${month}-${day}`;
+}
+
+export function generateSection(version: string, commits: readonly string[]): string {
+ const today = todayUTC();
+ const grouped: Record<string, string[]> = {};
+
+ for (const msg of commits) {
+ const { category, description } = classifyCommit(msg);
+ if (category === null) continue;
+ if (!(category in grouped)) grouped[category] = [];
+ grouped[category]!.push(description);
+ }
+
+ const lines: string[] = [`## ${version} — ${today}`, ""];
+
+ for (const section of SECTION_ORDER) {
+ if (section in grouped) {
+ lines.push(`### ${section}`);
+ for (const item of grouped[section]!) {
+ lines.push(`- ${item}`);
+ }
+ lines.push("");
+ }
+ }
+
+ return lines.join("\n");
+}
+
+function escapeRegex(s: string): string {
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+}
+
+function prependToChangelog(section: string, version: string): void {
+ const content = readFileSync("CHANGELOG.md", { encoding: "utf-8" });
+ const versionPattern = new RegExp(`^## ${escapeRegex(version)} — .*$`, "m");
+ const existingPattern = new RegExp(
+ `^## ${escapeRegex(version)} — [\\s\\S]*?(?=\\n## [^\\n]|$)`,
+ "m",
+ );
+
+ let newContent: string;
+ if (versionPattern.test(content)) {
+ newContent = content.replace(existingPattern, section.trimEnd());
+ } else {
+ const header = "# Changelog";
+ const idx = content.indexOf(header);
+ if (idx === -1) {
+ newContent = `${header}\n\n${section}\n${content}`;
+ } else {
+ let insertAt = idx + header.length;
+ while (
+ insertAt < content.length &&
+ (content[insertAt] === "\n" || content[insertAt] === "\r")
+ ) {
+ insertAt += 1;
+ }
+ newContent =
+ content.slice(0, insertAt) +
+ "\n" +
+ section +
+ "\n" +
+ content.slice(insertAt);
+ }
+ }
+
+ writeFileSync("CHANGELOG.md", newContent, { encoding: "utf-8" });
+}
+
+export function normalizeVersion(version: string): string {
+ const match = /^v?(\d+)\.(\d+)(?:\.(\d+))?$/.exec(version);
+ if (!match) {
+ process.stderr.write(
+ `Invalid version '${version}'. Expected vX.Y or vX.Y.Z.\n`,
+ );
+ process.exit(1);
+ }
+ const [, major, minor, patch] = match;
+ return `${major}.${minor}.${patch ?? "0"}`;
+}
+
+function updateManifest(version: string): void {
+ const content = readFileSync("vault-manifest.json", { encoding: "utf-8" });
+ const manifest = JSON.parse(content) as Record<string, unknown>;
+ manifest["version"] = normalizeVersion(version);
+ manifest["released"] = todayUTC();
+ writeFileSync(
+ "vault-manifest.json",
+ JSON.stringify(manifest, null, 2) + "\n",
+ { encoding: "utf-8" },
+ );
+}
+
+function main(): void {
+ const version = process.argv[2];
+ if (!version) {
+ process.stderr.write(
+ "Usage: generate-changelog.ts <version>\n",
+ );
+ process.exit(1);
+ }
+
+ const prevTag = getPreviousTag();
+ const commits = getCommits(prevTag);
+
+ if (commits.length === 0) {
+ process.stderr.write("No commits found since previous tag.\n");
+ process.exit(1);
+ }
+
+ const section = generateSection(version, commits);
+
+ if (!commits.some((msg) => classifyCommit(msg).category !== null)) {
+ process.stderr.write(
+ "All commits were skipped (ci/test/release only). Nothing to changelog.\n",
+ );
+ process.exit(1);
+ }
+
+ prependToChangelog(section, version);
+ updateManifest(version);
+
+ // Print section for GitHub Release body
+ process.stdout.write(section);
+ if (!section.endsWith("\n")) process.stdout.write("\n");
+}
+
+// Only run main when invoked as a script (not when imported by tests).
+if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
+ main();
+}
diff --git a/.github/scripts/manifest-check.ts b/.github/scripts/manifest-check.ts
new file mode 100644
index 0000000..a50924d
--- /dev/null
+++ b/.github/scripts/manifest-check.ts
@@ -0,0 +1,118 @@
+#!/usr/bin/env node
+/**
+ * PR-time advisory: verify that every tracked template-infrastructure file
+ * is covered by a glob in vault-manifest.json's `infrastructure` array.
+ *
+ * Emits GitHub workflow `::warning::` annotations for uncovered files. Does
+ * not fail the job — this is an informational nudge to keep the manifest in
+ * sync when new template files land.
+ */
+
+import { readFileSync, readdirSync, type Dirent } from "node:fs";
+import { join } from "node:path";
+import { fileURLToPath } from "node:url";
+
+type Manifest = { readonly infrastructure?: readonly string[] };
+
+/**
+ * Convert a glob pattern to a full-match regex.
+ * Grammar: `**` matches any characters (including `/`); `*` matches any
+ * run of non-slash characters; every other character is matched literally
+ * (with regex metacharacters escaped).
+ */
+export function globToRegex(glob: string): RegExp {
+ let pattern = "";
+ for (let i = 0; i < glob.length; i++) {
+ const ch = glob[i];
+ if (ch === "*") {
+ if (glob[i + 1] === "*") {
+ pattern += ".*";
+ i += 1; // consume second *
+ } else {
+ pattern += "[^/]*";
+ }
+ } else if (ch && /[.+^${}()|[\]\\]/.test(ch)) {
+ pattern += "\\" + ch;
+ } else {
+ pattern += ch;
+ }
+ }
+ return new RegExp(`^${pattern}$`);
+}
+
+/**
+ * Return true if `path` is covered by any entry in `globs`. Exact-string
+ * globs (no wildcards) are matched literally; wildcard globs go through
+ * globToRegex.
+ */
+export function isCovered(
+ path: string,
+ globs: readonly string[],
+): boolean {
+ for (const g of globs) {
+ if (g === path) return true;
+ if (g.includes("*") && globToRegex(g).test(path)) return true;
+ }
+ return false;
+}
+
+// ---------------------------------------------------------------------------
+// Main — walks the watched directories and reports uncovered files.
+// ---------------------------------------------------------------------------
+
+// Top-level files in these directories are the "template infrastructure"
+// surface. Matches the hardcoded glob list in the bash predecessor.
+const WATCHED: ReadonlyArray<{
+ readonly dir: string;
+ readonly exts: readonly string[];
+}> = [
+ { dir: ".claude/commands", exts: [".md"] },
+ { dir: ".claude/agents", exts: [".md"] },
+ { dir: ".claude/scripts", exts: [".ts"] },
+ { dir: "templates", exts: [".md"] },
+ { dir: "bases", exts: [".base"] },
+];
+
+function listTopLevelFiles(dir: string, exts: readonly string[]): string[] {
+ let entries: Dirent[];
+ try {
+ entries = readdirSync(dir, { withFileTypes: true });
+ } catch {
+ return [];
+ }
+ return entries
+ .filter((e) => e.isFile() && exts.some((x) => e.name.endsWith(x)))
+ .map((e) => join(dir, e.name));
+}
+
+function main(): void {
+ const manifest = JSON.parse(
+ readFileSync("vault-manifest.json", "utf-8"),
+ ) as Manifest;
+ const globs = manifest.infrastructure ?? [];
+
+ const missing: string[] = [];
+ for (const { dir, exts } of WATCHED) {
+ for (const path of listTopLevelFiles(dir, exts)) {
+ if (!isCovered(path, globs)) missing.push(path);
+ }
+ }
+
+ if (missing.length === 0) return;
+
+ console.log(
+ "::warning::The following files are not covered by vault-manifest.json infrastructure globs:",
+ );
+ for (const f of missing) console.log(` - ${f}`);
+ console.log("");
+ console.log(
+ "If these are template infrastructure files, add them to the 'infrastructure' array in vault-manifest.json.",
+ );
+ console.log(
+ "Also consider adding a version_fingerprints entry if this is a new version-defining file.",
+ );
+}
+
+if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
+ main();
+}
diff --git a/.github/scripts/package.json b/.github/scripts/package.json
new file mode 100644
index 0000000..69a5bbf
--- /dev/null
+++ b/.github/scripts/package.json
@@ -0,0 +1,5 @@
+{
+ "private": true,
+ "type": "module",
+ "description": "Release tooling for obsidian-mind. Executed by `node --experimental-strip-types`. This file marks .ts files as ESM for Node's module resolution and tsc typecheck — no runtime dependencies."
+}
diff --git a/.github/workflows/manifest-check.yml b/.github/workflows/manifest-check.yml
index b323f7b..5884b06 100644
--- a/.github/workflows/manifest-check.yml
+++ b/.github/workflows/manifest-check.yml
@@ -8,56 +8,16 @@ on:
- '.claude/scripts/**'
- 'templates/**'
- 'bases/**'
+ - 'vault-manifest.json'
+ - '.github/scripts/manifest-check.ts'
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
-
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 22
- name: Check manifest coverage
- run: |
- MISSING=()
-
- # Read infrastructure globs from manifest
- GLOBS=$(python3 -c "
- import json
- with open('vault-manifest.json') as f:
- m = json.load(f)
- for g in m.get('infrastructure', []):
- print(g)
- ")
-
- # For each file in watched directories, check if any glob covers it
- for f in .claude/commands/*.md .claude/agents/*.md .claude/scripts/*.py .claude/scripts/*.sh templates/*.md bases/*.base; do
- [ -f "$f" ] || continue
- COVERED=false
- while IFS= read -r glob; do
- # Check exact match
- if [ "$f" = "$glob" ]; then
- COVERED=true
- break
- fi
- # Check glob coverage: ".claude/**" covers ".claude/commands/foo.md"
- # Convert glob to regex: ** → .*, * → [^/]*
- regex=$(echo "$glob" | sed 's|\*\*|__DOUBLESTAR__|g' | sed 's|\*|[^/]*|g' | sed 's|__DOUBLESTAR__|.*|g' | sed 's|\.|\\.|g' | sed 's|\\\.\*|.*|g' | sed 's|\\\[|[|g' | sed 's|\\\]|]|g')
- if echo "$f" | grep -qE "^${regex}$"; then
- COVERED=true
- break
- fi
- done <<< "$GLOBS"
-
- if [ "$COVERED" = false ]; then
- MISSING+=("$f")
- fi
- done
-
- if [ ${#MISSING[@]} -gt 0 ]; then
- echo "::warning::The following files are not covered by vault-manifest.json infrastructure globs:"
- for f in "${MISSING[@]}"; do
- echo " - $f"
- done
- echo ""
- echo "If these are template infrastructure files, add them to the 'infrastructure' array in vault-manifest.json."
- echo "Also consider adding a version_fingerprints entry if this is a new version-defining file."
- fi
+ run: node --experimental-strip-types .github/scripts/manifest-check.ts
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 7534fb7..eb7cafe 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -23,9 +23,9 @@ jobs:
ref: main
fetch-depth: 0
- - uses: actions/setup-python@v5
+ - uses: actions/setup-node@v4
with:
- python-version: '3.12'
+ node-version: 22
- name: Resolve version
env:
@@ -62,18 +62,18 @@ jobs:
git push origin "$VERSION"
- name: Run tests
- run: python3 .claude/scripts/test_hooks.py
+ run: node --experimental-strip-types --test '.claude/scripts/tests/'*.test.ts
- name: Generate changelog
run: |
- python3 .github/scripts/generate-changelog.py "$VERSION" > /tmp/changelog_section.md
+ node --experimental-strip-types .github/scripts/generate-changelog.ts "$VERSION" > /tmp/changelog_section.md
- name: Build release body
run: |
cat > /tmp/release_body.md <<'HEADER'
## Quick Start
- **Requirements:** [Obsidian](https://obsidian.md), [Python 3.8+](https://python.org/downloads), and one of: [Claude Code](https://claude.ai/code) · [Codex CLI](https://github.com/openai/codex) · [Gemini CLI](https://github.com/google-gemini/gemini-cli)
+ **Requirements:** [Obsidian](https://obsidian.md), [Node 22+ LTS](https://nodejs.org), and one of: [Claude Code](https://claude.ai/code) · [Codex CLI](https://github.com/openai/codex) · [Gemini CLI](https://github.com/google-gemini/gemini-cli)
```bash
git clone https://github.com/breferrari/obsidian-mind.git
@@ -107,7 +107,10 @@ jobs:
zip -r "$ZIP_NAME" . \
-x ".git/*" \
-x ".github/*" \
- -x ".claude/scripts/test_hooks.py" \
+ -x ".claude/scripts/tests/*" \
+ -x ".claude/scripts/tsconfig.json" \
+ -x ".claude/scripts/package.json" \
+ -x ".claude/scripts/node_modules/*" \
-x ".DS_Store" \
-x "thinking/session-logs/*"
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index 9662e4f..2ffe946 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -5,17 +5,33 @@ on:
branches: [main]
paths:
- '.claude/scripts/**'
+ - '.github/workflows/test.yml'
pull_request:
paths:
- '.claude/scripts/**'
+ - '.github/workflows/test.yml'
jobs:
test:
- runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ os: [ubuntu-latest, macos-latest, windows-latest]
+ node: [22, 24]
+ runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- - uses: actions/setup-python@v5
+ - uses: actions/setup-node@v4
with:
- python-version: '3.12'
+ node-version: ${{ matrix.node }}
+ - name: Install typecheck deps (CI-only, not shipped)
+ shell: bash
+ run: npm install --no-save --silent --prefix .claude/scripts [email protected] @types/[email protected]
+ - name: Typecheck
+ shell: bash
+ working-directory: .claude/scripts
+ run: npm run typecheck
- name: Run hook tests
- run: python .claude/scripts/test_hooks.py -v
+ working-directory: .claude/scripts
+ run: npm test
+
diff --git a/.gitignore b/.gitignore
index 93fcbc4..ed61f53 100644
--- a/.gitignore
+++ b/.gitignore
@@ -16,3 +16,7 @@
# Session logs (local transcripts)
thinking/session-logs/
+
+# Node typecheck deps (CI + local dev only; runtime is zero-deps)
+node_modules/
+.claude/scripts/node_modules/
diff --git a/AGENTS.md b/AGENTS.md
index 7dd2ee0..f3ad00e 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -6,7 +6,7 @@ This vault is built for [Claude Code](https://claude.ai/code) with a full operat
## Hooks
-The hook scripts in `.claude/scripts/` are agent-agnostic Python and shell — no Claude SDK dependencies. Hook configs are provided for three agents:
+The hook scripts in `.claude/scripts/` are agent-agnostic TypeScript and shell, executed natively by Node via `--experimental-strip-types` — no build step, no runtime dependencies, no Claude SDK. Hook configs are provided for three agents:
| Agent | Config | Status |
|-------|--------|--------|
@@ -16,10 +16,10 @@ The hook scripts in `.claude/scripts/` are agent-agnostic Python and shell — n
| Script | Purpose | Claude event | Codex event | Gemini event |
|--------|---------|--------------|-------------|--------------|
-| `session-start.sh` | Inject vault context at startup | SessionStart | SessionStart | SessionStart |
-| `classify-message.py` | Classify messages, inject routing hints | UserPromptSubmit | UserPromptSubmit | BeforeAgent |
-| `validate-write.py` | Validate frontmatter and wikilinks | PostToolUse | PostToolUse | AfterTool |
-| `pre-compact.sh` | Back up transcript before compaction | PreCompact | — | PreCompress |
+| `session-start.ts` | Inject vault context at startup | SessionStart | SessionStart | SessionStart |
+| `classify-message.ts` | Classify messages, inject routing hints | UserPromptSubmit | UserPromptSubmit | BeforeAgent |
+| `validate-write.ts` | Validate frontmatter and wikilinks | PostToolUse | PostToolUse | AfterTool |
+| `pre-compact.ts` | Back up transcript before compaction | PreCompact | — | PreCompress |
## Commands
diff --git a/CLAUDE.md b/CLAUDE.md
index e901a6f..c057727 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -66,7 +66,7 @@ Defined in `.claude/commands/`. See [[Skills]] for full documentation.
| `templates/` | Obsidian templates | `Work Note.md`, `Decision Record.md`, etc. |
| `.claude/commands/` | 18 slash commands | See command table above |
| `.claude/agents/` | 9 subagents | See subagents table below |
-| `.claude/scripts/` | Hook scripts | `session-start.sh`, `classify-message.py`, `validate-write.py`, `pre-compact.sh` |
+| `.claude/scripts/` | Hook scripts | `session-start.ts`, `classify-message.ts`, `validate-write.ts`, `pre-compact.ts`, `stop-checklist.ts`, `charcount.ts` |
| `.claude/skills/` | Obsidian + QMD skills | Loaded automatically via Skill tool |
## Obsidian CLI
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index fb5b6d0..3b975b8 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -80,13 +80,13 @@ The release pipeline handles these automatically — **do not include in your PR
- [ ] Counts match everywhere (commands, agents) if you added/removed any
- [ ] New command/agent appears in ALL doc tables (CLAUDE.md + README + Skills.md)
- [ ] Translations flagged if you changed README.md (maintainer can handle these)
-- [ ] Tests pass: `python .claude/scripts/test_hooks.py`
+- [ ] Tests pass: `cd .claude/scripts && npm test`
- [ ] Examples use generic dates and names, not specific to any company or person
## Running Tests
```bash
-python .claude/scripts/test_hooks.py -v
+cd .claude/scripts && npm test
```
Tests run automatically on PRs that touch `.claude/scripts/`.
diff --git a/GEMINI.md b/GEMINI.md
index 7dd2ee0..f3ad00e 100644
--- a/GEMINI.md
+++ b/GEMINI.md
@@ -6,7 +6,7 @@ This vault is built for [Claude Code](https://claude.ai/code) with a full operat
## Hooks
-The hook scripts in `.claude/scripts/` are agent-agnostic Python and shell — no Claude SDK dependencies. Hook configs are provided for three agents:
+The hook scripts in `.claude/scripts/` are agent-agnostic TypeScript and shell, executed natively by Node via `--experimental-strip-types` — no build step, no runtime dependencies, no Claude SDK. Hook configs are provided for three agents:
| Agent | Config | Status |
|-------|--------|--------|
@@ -16,10 +16,10 @@ The hook scripts in `.claude/scripts/` are agent-agnostic Python and shell — n
| Script | Purpose | Claude event | Codex event | Gemini event |
|--------|---------|--------------|-------------|--------------|
-| `session-start.sh` | Inject vault context at startup | SessionStart | SessionStart | SessionStart |
-| `classify-message.py` | Classify messages, inject routing hints | UserPromptSubmit | UserPromptSubmit | BeforeAgent |
-| `validate-write.py` | Validate frontmatter and wikilinks | PostToolUse | PostToolUse | AfterTool |
-| `pre-compact.sh` | Back up transcript before compaction | PreCompact | — | PreCompress |
+| `session-start.ts` | Inject vault context at startup | SessionStart | SessionStart | SessionStart |
+| `classify-message.ts` | Classify messages, inject routing hints | UserPromptSubmit | UserPromptSubmit | BeforeAgent |
+| `validate-write.ts` | Validate frontmatter and wikilinks | PostToolUse | PostToolUse | AfterTool |
+| `pre-compact.ts` | Back up transcript before compaction | PreCompact | — | PreCompress |
## Commands
diff --git a/README.ja.md b/README.ja.md
index 4522d0d..7297611 100644
--- a/README.ja.md
+++ b/README.ja.md
@@ -16,7 +16,7 @@
[![Obsidian CLI](https://img.shields.io/badge/obsidian--cli-integrated-E6E6E6)](https://github.com/kepano/obsidian-cli)
[![Obsidian Skills](https://img.shields.io/badge/obsidian--skills-integrated-8B5CF6)](https://github.com/kepano/obsidian-skills)
[![QMD](https://img.shields.io/badge/qmd-semantic%20search-FF6B6B)](https://github.com/tobi/qmd)
-[![Python](https://img.shields.io/badge/python-3.8%2B-3776AB)](https://python.org)
+[![Node](https://img.shields.io/badge/node-22%2B-339933)](https://nodejs.org)
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
> **Claude Codeにすべてを記憶させるObsidianボールト。** セッションを開始して、日々のことを話すだけ — ノート、リンク、インデックス、パフォーマンス管理はClaudeが自動で処理します。すべての会話が前回の続きとして積み重なっていきます。
@@ -123,10 +123,12 @@ qmd update && qmd embed
- [Obsidian](https://obsidian.md) 1.12以上(CLIサポートのため)
- [Claude Code](https://docs.anthropic.com/en/docs/claude-code)
-- Python 3(フックスクリプト用)
+- [Node 22+ LTS](https://nodejs.org)(フックスクリプト用 — Claude Code / Codex / Gemini CLI と一緒に通常インストール済み)
- Git(バージョン履歴用)
- [QMD](https://github.com/tobi/qmd)(オプション、セマンティック検索用)
+> **Node フラグについて。** フックスクリプトは Node の `--experimental-strip-types` フラグで TypeScript を直接実行します。このフラグは Node 22.6+(2024年8月)で安定し、Node 23.6+ ではデフォルトの動作になりました。実験的扱いではあるものの 22 LTS と 24 LTS で挙動は変わっていません。将来の Node リリースでフラグが廃止・改名された場合、`.claude/settings.json`、`.codex/hooks.json`、`.gemini/settings.json` のフックコマンドを1行修正する必要があります。
+
---
## ⚙️ 仕組み
@@ -164,11 +166,11 @@ obsidian-mindはボールト全体をコンテキストに読み込み**ませ
| **トリガー** | PostToolUse検証 | `.md`書き込み後 | ~200トークン |
| **まれ** | ファイル全体の読み込み | 明示的に必要な場合のみ | 可変 |
-SessionStartは**軽量なコンテキスト**を読み込みます — 主要ファイルからの短い抜粋、ファイル名、git概要のみで、ノート全体は読み込みません。エージェントはQMDで意味検索してからファイルを読むため、関連する情報のみを取得します。分類フックはメッセージごとに軽量なPython呼び出し1回です。検証フックはMarkdown書き込み時のみ発火し、除外パスはスキップします。
+SessionStartは**軽量なコンテキスト**を読み込みます — 主要ファイルからの短い抜粋、ファイル名、git概要のみで、ノート全体は読み込みません。エージェントはQMDで意味検索してからファイルを読むため、関連する情報のみを取得します。分類フックはメッセージごとに軽量なNode呼び出し1回です。検証フックはMarkdown書き込み時のみ発火し、除外パスはスキップします。
### 🌐 他のエージェントでの利用
-obsidian-mindはClaude Code、Codex CLI、Gemini CLIで動作します。`CLAUDE.md`のボールト規約、`.claude/scripts/`のフックスクリプト、`.claude/commands/`の18コマンドはすべてエージェント非依存です — 純粋なMarkdown、Python、シェルでSDK依存はありません。
+obsidian-mindはClaude Code、Codex CLI、Gemini CLIで動作します。`CLAUDE.md`のボールト規約、`.claude/scripts/`のフックスクリプト、`.claude/commands/`の18コマンドはすべてエージェント非依存です — 純粋なMarkdown、TypeScript、シェルでSDK依存はありません。
**Claude Code** — フルサポート。フック、コマンド、サブエージェント、メモリシステムがすべてそのまま動作します。
@@ -328,7 +330,7 @@ templates/ YAMLフロントマター付きObsidianテンプレー
.claude/
commands/ 18個のスラッシュコマンド
agents/ 9個のサブエージェント
- scripts/ フックスクリプト + charcount.shユーティリティ
+ scripts/ フックスクリプト + charcount.tsユーティリティ
skills/ Obsidian + QMDスキル
settings.json 5つのフック設定
```
@@ -450,9 +452,7 @@ cd ~/new-vault && claude # または codex、gemini
## 🗺️ ロードマップ
-**PythonからTypeScriptへの移行。** フックスクリプトは将来のリリースでTypeScriptに移行予定です。この移行は、まだ公開していない他の作業と連動しているため、自分自身で進めます。この移行を提案するPRは、感謝の言葉とともにクローズさせていただきます。
-
-**その他のコントリビューションは歓迎です。** 1ファイルを超える変更については、まずIssueを開いてください。特にフック、インストール手順、必要な環境に関わる変更については必須です。マージできないものを作る手間を省けます。
+**コントリビューションは歓迎です。** 1ファイルを超える変更については、まずIssueを開いてください。特にフック、インストール手順、必要な環境に関わる変更については必須です。マージできないものを作る手間を省けます。
---
diff --git a/README.ko.md b/README.ko.md
index 37d5b23..d7a9a4e 100644
--- a/README.ko.md
+++ b/README.ko.md
@@ -16,7 +16,7 @@
[![Obsidian CLI](https://img.shields.io/badge/obsidian--cli-integrated-E6E6E6)](https://github.com/kepano/obsidian-cli)
[![Obsidian Skills](https://img.shields.io/badge/obsidian--skills-integrated-8B5CF6)](https://github.com/kepano/obsidian-skills)
[![QMD](https://img.shields.io/badge/qmd-semantic%20search-FF6B6B)](https://github.com/tobi/qmd)
-[![Python](https://img.shields.io/badge/python-3.8%2B-3776AB)](https://python.org)
+[![Node](https://img.shields.io/badge/node-22%2B-339933)](https://nodejs.org)
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
> **Claude Code가 모든 것을 기억하게 해주는 Obsidian 볼트.** 세션을 시작하고 하루에 대해 이야기하면, Claude가 나머지를 처리합니다 — 노트, 링크, 인덱스, 성과 추적까지. 모든 대화가 이전 대화 위에 쌓입니다.
@@ -123,10 +123,12 @@ qmd update && qmd embed
- [Obsidian](https://obsidian.md) 1.12+ (CLI 지원)
- [Claude Code](https://docs.anthropic.com/en/docs/claude-code)
-- Python 3 (훅 스크립트용)
+- [Node 22+ LTS](https://nodejs.org) (훅 스크립트용 — Claude Code / Codex / Gemini CLI와 함께 이미 설치되어 있을 가능성이 큽니다)
- Git (버전 히스토리용)
- [QMD](https://github.com/tobi/qmd) (선택 사항, 시맨틱 검색용)
+> **Node 플래그에 관한 참고.** 훅 스크립트는 Node의 `--experimental-strip-types` 플래그로 TypeScript를 직접 실행합니다. 이 플래그는 Node 22.6+ (2024년 8월)부터 안정화되었고, Node 23.6+ 에서는 기본 동작이 되었습니다. 실험적(experimental)으로 표시되어 있지만 22 LTS와 24 LTS 전반에서 동작이 변경된 적은 없습니다. 향후 Node 릴리스에서 플래그가 폐지되거나 이름이 변경되면 `.claude/settings.json`, `.codex/hooks.json`, `.gemini/settings.json`의 훅 명령어를 한 줄만 수정하면 됩니다.
+
---
## ⚙️ 작동 원리
@@ -164,11 +166,11 @@ obsidian-mind는 전체 볼트를 컨텍스트에 로드하지 **않습니다**.
| **트리거** | PostToolUse 검증 | `.md` 작성 후 | ~200 토큰 |
| **드물게** | 전체 파일 읽기 | 명시적으로 필요한 경우만 | 가변 |
-SessionStart는 **가벼운 컨텍스트**를 로드합니다 — 주요 파일의 짧은 발췌, 파일명, git 요약만 로드하며 전체 노트 내용은 읽지 않습니다. 에이전트는 QMD를 통해 의미 기반 검색 후 파일을 읽으므로 관련 정보만 가져옵니다. 분류 훅은 메시지당 가벼운 Python 호출 1회입니다. 검증 훅은 마크다운 쓰기 시에만 실행되며 제외된 경로는 건너뜁니다.
+SessionStart는 **가벼운 컨텍스트**를 로드합니다 — 주요 파일의 짧은 발췌, 파일명, git 요약만 로드하며 전체 노트 내용은 읽지 않습니다. 에이전트는 QMD를 통해 의미 기반 검색 후 파일을 읽으므로 관련 정보만 가져옵니다. 분류 훅은 메시지당 가벼운 Node 호출 1회입니다. 검증 훅은 마크다운 쓰기 시에만 실행되며 제외된 경로는 건너뜁니다.
### 🌐 다른 에이전트와 사용하기
-obsidian-mind는 Claude Code, Codex CLI, Gemini CLI에서 작동합니다. `CLAUDE.md`의 볼트 규약, `.claude/scripts/`의 훅 스크립트, `.claude/commands/`의 18개 커맨드는 모두 에이전트 비의존적입니다 — 순수 Markdown, Python, 셸이며 SDK 의존성이 없습니다.
+obsidian-mind는 Claude Code, Codex CLI, Gemini CLI에서 작동합니다. `CLAUDE.md`의 볼트 규약, `.claude/scripts/`의 훅 스크립트, `.claude/commands/`의 18개 커맨드는 모두 에이전트 비의존적입니다 — 순수 Markdown, TypeScript, 셸이며 SDK 의존성이 없습니다.
**Claude Code** — 완전 지원. 훅, 커맨드, 서브에이전트, 메모리 시스템이 모두 기본으로 작동합니다.
@@ -328,7 +330,7 @@ templates/ YAML 프론트매터가 포함된 Obsidian 템플릿
.claude/
commands/ 18개 슬래시 명령어
agents/ 9개 서브에이전트
- scripts/ 훅 스크립트 + charcount.sh 유틸리티
+ scripts/ 훅 스크립트 + charcount.ts 유틸리티
skills/ Obsidian + QMD 스킬
settings.json 5개 훅 설정
```
@@ -450,9 +452,7 @@ cd ~/new-vault && claude # 또는 codex, gemini
## 🗺️ 로드맵
-**Python에서 TypeScript로의 마이그레이션.** 훅 스크립트는 향후 릴리스에서 TypeScript로 이전될 예정입니다. 이 마이그레이션은 아직 공개되지 않은 다른 작업과 연관되어 있어, 직접 진행할 예정입니다. 이 마이그레이션을 제안하는 PR은 감사 인사와 함께 닫히게 됩니다.
-
-**다른 기여는 환영합니다.** 파일 하나를 초과하는 변경 사항은 먼저 이슈를 열어 주세요. 특히 훅, 설치, 또는 설치에 필요한 요구 사항에 관련된 변경은 필수입니다. 머지할 수 없는 것을 만드는 수고를 덜 수 있습니다.
+**기여는 환영합니다.** 파일 하나를 초과하는 변경 사항은 먼저 이슈를 열어 주세요. 특히 훅, 설치, 또는 설치에 필요한 요구 사항에 관련된 변경은 필수입니다. 머지할 수 없는 것을 만드는 수고를 덜 수 있습니다.
---
diff --git a/README.md b/README.md
index 26f052f..333ec8b 100644
--- a/README.md
+++ b/README.md
@@ -13,7 +13,7 @@
[![Obsidian CLI](https://img.shields.io/badge/obsidian--cli-integrated-E6E6E6)](https://github.com/kepano/obsidian-cli)
[![Obsidian Skills](https://img.shields.io/badge/obsidian--skills-integrated-8B5CF6)](https://github.com/kepano/obsidian-skills)
[![QMD](https://img.shields.io/badge/qmd-semantic%20search-FF6B6B)](https://github.com/tobi/qmd)
-[![Python](https://img.shields.io/badge/python-3.8%2B-3776AB)](https://python.org)
+[![Node](https://img.shields.io/badge/node-22%2B-339933)](https://nodejs.org)
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
> **An Obsidian vault that gives AI coding agents persistent memory.** Built for Claude Code, with working hooks for Codex CLI and Gemini CLI. Start a session, talk about your day, and the agent handles the rest — notes, links, indexes, performance tracking. Every conversation builds on the last.
@@ -122,10 +122,12 @@ qmd update && qmd embed
- [Obsidian](https://obsidian.md) 1.12+ (for CLI support)
- An AI coding agent: [Claude Code](https://docs.anthropic.com/en/docs/claude-code) (full support), [Codex CLI](https://github.com/openai/codex), or [Gemini CLI](https://github.com/google-gemini/gemini-cli)
-- [Python 3.8+](https://python.org/downloads) (for hook scripts)
+- [Node 22+ LTS](https://nodejs.org) (for hook scripts — typically already installed alongside Claude Code / Codex / Gemini CLI)
- Git (for version history)
- [QMD](https://github.com/tobi/qmd) (optional, for semantic search)
+> **Note on the Node flag.** Hook scripts execute TypeScript directly via Node's `--experimental-strip-types` flag, stable in Node 22.6+ (Aug 2024) and the default behaviour in Node 23.6+. The flag is marked experimental but has been unchanged across 22 LTS and 24 LTS; if a future Node release retires or renames it, hook commands in `.claude/settings.json`, `.codex/hooks.json`, and `.gemini/settings.json` need a one-line update.
+
---
## ⚙️ How It Works
@@ -163,11 +165,11 @@ obsidian-mind does **not** dump your entire vault into context. It uses tiered l
| **Triggered** | PostToolUse validation | After `.md` writes | ~200 tokens |
| **Rare** | Full file reads | Only when explicitly needed | Variable |
-SessionStart loads **lightweight context** — small excerpts from key files, filenames, and git summary — not full note contents. The agent queries by meaning via QMD before reading files, so it pulls only what's relevant. The classification hook is one lightweight Python call per message. The validation hook only fires on markdown writes and skips excluded paths.
+SessionStart loads **lightweight context** — small excerpts from key files, filenames, and git summary — not full note contents. The agent queries by meaning via QMD before reading files, so it pulls only what's relevant. The classification hook is one lightweight Node call per message. The validation hook only fires on markdown writes and skips excluded paths.
### 🌐 Using with Other Agents
-obsidian-mind works with Claude Code, Codex CLI, and Gemini CLI. The vault conventions in `CLAUDE.md`, the hook scripts in `.claude/scripts/`, and the 18 commands in `.claude/commands/` are all agent-agnostic — pure Markdown, Python, and shell with no SDK dependencies.
+obsidian-mind works with Claude Code, Codex CLI, and Gemini CLI. The vault conventions in `CLAUDE.md`, the hook scripts in `.claude/scripts/`, and the 18 commands in `.claude/commands/` are all agent-agnostic — pure Markdown, TypeScript, and shell with no SDK dependencies.
**Claude Code** — full support. Hooks, commands, subagents, and the memory system all work out of the box.
@@ -327,7 +329,7 @@ templates/ Obsidian templates with YAML frontmatter
.claude/
commands/ 18 slash commands
agents/ 9 subagents
- scripts/ Hook scripts + charcount.sh utility
+ scripts/ Hook scripts + charcount.ts utility
skills/ Obsidian + QMD skills
settings.json 5 hooks configuration
```
@@ -449,9 +451,7 @@ Your old vault is **never modified**. Use `--dry-run` to preview the plan withou
## 🗺️ Roadmap
-**Python to TypeScript migration.** The hook scripts are moving to TypeScript in a future release. I'm doing this one myself because it ties into other work already in motion. PRs that propose this migration will be closed with thanks.
-
-**Other contributions welcome.** Open an issue first for anything bigger than a one-file change. Especially anything that touches the hooks, the install, or what people need installed. Saves you from building something that can't be merged.
+**Contributions welcome.** Open an issue first for anything bigger than a one-file change. Especially anything that touches the hooks, the install, or what people need installed. Saves you from building something that can't be merged.
---
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 90b1045..a40d91c 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -16,7 +16,7 @@
[![Obsidian CLI](https://img.shields.io/badge/obsidian--cli-integrated-E6E6E6)](https://github.com/kepano/obsidian-cli)
[![Obsidian Skills](https://img.shields.io/badge/obsidian--skills-integrated-8B5CF6)](https://github.com/kepano/obsidian-skills)
[![QMD](https://img.shields.io/badge/qmd-semantic%20search-FF6B6B)](https://github.com/tobi/qmd)
-[![Python](https://img.shields.io/badge/python-3.8%2B-3776AB)](https://python.org)
+[![Node](https://img.shields.io/badge/node-22%2B-339933)](https://nodejs.org)
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](LICENSE)
> **一个让 Claude Code 记住一切的 Obsidian 仓库。** 开始一次会话,聊聊你的一天,Claude 会处理剩下的一切——笔记、链接、索引、绩效追踪。每一次对话都建立在上一次的基础之上。
@@ -123,10 +123,12 @@ qmd update && qmd embed
- [Obsidian](https://obsidian.md) 1.12+(支持 CLI)
- [Claude Code](https://docs.anthropic.com/en/docs/claude-code)
-- Python 3(用于钩子脚本)
+- [Node 22+ LTS](https://nodejs.org)(用于钩子脚本 — 通常与 Claude Code / Codex / Gemini CLI 一起已安装)
- Git(用于版本历史)
- [QMD](https://github.com/tobi/qmd)(可选,用于语义搜索)
+> **关于 Node 标志。** 钩子脚本通过 Node 的 `--experimental-strip-types` 标志直接执行 TypeScript。该标志自 Node 22.6+(2024 年 8 月)起稳定,并在 Node 23.6+ 中成为默认行为。虽然被标记为实验性(experimental),但在 22 LTS 和 24 LTS 中行为均未改变。如果未来的 Node 版本废弃或重命名该标志,只需在 `.claude/settings.json`、`.codex/hooks.json` 和 `.gemini/settings.json` 中对钩子命令做一行修改即可。
+
---
## ⚙️ 工作原理
@@ -164,11 +166,11 @@ obsidian-mind **不会**将整个 vault 加载到上下文中。它使用分层
| **触发** | PostToolUse 验证 | `.md` 写入后 | ~200 tokens |
| **罕见** | 完整文件读取 | 仅在明确需要时 | 可变 |
-SessionStart 加载**轻量级上下文** — 关键文件的简短摘要、文件名和 git 摘要,而非完整笔记内容。Agent 通过 QMD 进行语义搜索后再读取文件,因此只获取相关内容。分类钩子每条消息仅执行一次轻量级 Python 调用。验证钩子仅在 markdown 写入时触发,跳过排除的路径。
+SessionStart 加载**轻量级上下文** — 关键文件的简短摘要、文件名和 git 摘要,而非完整笔记内容。Agent 通过 QMD 进行语义搜索后再读取文件,因此只获取相关内容。分类钩子每条消息仅执行一次轻量级 Node 调用。验证钩子仅在 markdown 写入时触发,跳过排除的路径。
### 🌐 与其他 Agent 配合使用
-obsidian-mind 支持 Claude Code、Codex CLI 和 Gemini CLI。`CLAUDE.md` 中的 vault 规约、`.claude/scripts/` 中的钩子脚本、`.claude/commands/` 中的 18 个命令都是 Agent 无关的 — 纯 Markdown、Python 和 Shell,无 SDK 依赖。
+obsidian-mind 支持 Claude Code、Codex CLI 和 Gemini CLI。`CLAUDE.md` 中的 vault 规约、`.claude/scripts/` 中的钩子脚本、`.claude/commands/` 中的 18 个命令都是 Agent 无关的 — 纯 Markdown、TypeScript 和 Shell,无 SDK 依赖。
**Claude Code** — 完整支持。钩子、命令、子代理和记忆系统全部开箱即用。
@@ -328,7 +330,7 @@ templates/ 带有 YAML frontmatter 的 Obsidian 模板
.claude/
commands/ 18 个斜杠命令
agents/ 9 个子代理
- scripts/ 钩子脚本 + charcount.sh 工具
+ scripts/ 钩子脚本 + charcount.ts 工具
skills/ Obsidian + QMD 技能
settings.json 5 个钩子配置
```
@@ -450,9 +452,7 @@ Agent 将会:
## 🗺️ 路线图
-**从 Python 迁移到 TypeScript。** Hook 脚本将在未来的版本中迁移到 TypeScript。这项迁移由我亲自完成,因为它与尚未公开的其他工作相关联。提议进行此迁移的 PR 将会被关闭,感谢你的兴趣。
-
-**欢迎其他贡献。** 对于超过单文件的改动,请先创建 Issue。特别是涉及 Hook、安装流程或运行环境要求的改动。可以避免你做出无法合并的工作。
+**欢迎贡献。** 对于超过单文件的改动,请先创建 Issue。特别是涉及 Hook、安装流程或运行环境要求的改动。可以避免你做出无法合并的工作。
---