Git for the intent behind agent-written code. Records what your coding agent decided and why, and links every commit to it.
JavaScript ai-codingclaudeclaude-codeclaude-code-pluginclicoding-agentsdeveloper-toolsgitllmtypescript
feat(plugin): add the Stop hook that asks for lineage updates every N turns
Erend4caa9bc4e19
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b7492ac..447821d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- `/codelineage:lineage` skill: injects this session's compact record and the project's epochs, asks the agent for only what is new or changed, and has it save the JSON with the Write tool and run `session write --file … --consume` (JSON piped through a shell heredoc is blocked by Claude Code's command checks). It is pre-approved for exactly those two actions and answers "up to date" when nothing changed.- `codelineage session show <id> [-C dir]`: prints the compact record the skill updates (epochs, summary language, title, epoch, status and node ids/parents/kinds/titles, plus the inbox path) as JSON, and reports an uninitialized project or an unreadable record in that JSON instead of failing.+- Stop hook (`hooks/hooks.json`, `codelineage hook stop`): counts completed turns per session in `.codelineage/state/<id>.json` and, every `updateEveryTurns` turns since the record last changed, asks the agent to run `/codelineage:lineage` through `additionalContext` ("Stop hook feedback", not an error). Turns a stop hook continued are not counted; before `init`, with `CODELINEAGE_DISABLE=1`, on a busy lock or on any error it does nothing, and an unreadable state file is replaced.- `codelineage session write --consume`: deletes the `--file` input once the record is saved and keeps it when the write fails. `gitPolicy=commit` now also ignores `.codelineage/inbox/`.### Changeddiff --git a/packages/cli/hooks/hooks.json b/packages/cli/hooks/hooks.jsonnew file mode 100644index 0000000..8b0179c--- /dev/null+++ b/packages/cli/hooks/hooks.json@@ -0,0 +1,16 @@+{+ "hooks": {+ "Stop": [+ {+ "hooks": [+ {+ "type": "command",+ "command": "node",+ "args": ["${CLAUDE_PLUGIN_ROOT}/dist/cli.js", "hook", "stop"],+ "timeout": 10+ }+ ]+ }+ ]+ }+}diff --git a/packages/cli/package.json b/packages/cli/package.jsonindex 9aed334..92c733c 100644--- a/packages/cli/package.json+++ b/packages/cli/package.json@@ -10,7 +10,8 @@"files": ["dist",".claude-plugin",- "skills"+ "skills",+ "hooks"],"engines": {"node": ">=22.13.0"diff --git a/packages/cli/src/hooks/run.ts b/packages/cli/src/hooks/run.tsnew file mode 100644index 0000000..48125fd--- /dev/null+++ b/packages/cli/src/hooks/run.ts@@ -0,0 +1,60 @@+import { existsSync } from "node:fs";+import { resolve } from "node:path";+import { z } from "zod";+import { Slug } from "../schema/common.js";+import { projectPaths } from "../store/paths.js";+import { onStop } from "./stop.js";++/** The common fields of a Claude Code hook input we rely on. */+export const HookInput = z.looseObject({+ session_id: z.string(),+ cwd: z.string().optional(),+ stop_hook_active: z.boolean().optional(),+});+export type HookInput = z.infer<typeof HookInput>;++export interface HookContext {+ input: HookInput;+ sessionId: string;+ /** The project root: `CLAUDE_PROJECT_DIR`, else the hook's `cwd`. */+ root: string;+ env: NodeJS.ProcessEnv;+ now: string;+}++export type HookOutput = Record<string, unknown>;++const HANDLERS: Record<string, (ctx: HookContext) => Promise<HookOutput | undefined>> = {+ stop: onStop,+};++export const HOOK_EVENTS = Object.keys(HANDLERS);++/**+ * Runs one hook and returns what to print on stdout, if anything. A hook must+ * never break the user's session, so every failure ends in silence; the reason+ * goes to `debug` (stderr, which Claude Code shows only in debug output).+ */+export async function runHook(+ event: string,+ stdin: string,+ env: NodeJS.ProcessEnv,+ now: string,+ debug: (line: string) => void,+): Promise<string | undefined> {+ try {+ if (env.CODELINEAGE_DISABLE === "1") return undefined;+ const handler = HANDLERS[event];+ if (!handler) return undefined;+ const input = HookInput.parse(JSON.parse(stdin));+ if (!Slug.safeParse(input.session_id).success) return undefined;+ const root = resolve(env.CLAUDE_PROJECT_DIR ?? input.cwd ?? ".");+ // Before `init` every hook is a no-op; projects are never registered here.+ if (!existsSync(projectPaths(root).project)) return undefined;+ const out = await handler({ input, sessionId: input.session_id, root, env, now });+ return out === undefined ? undefined : JSON.stringify(out);+ } catch (err) {+ debug(`codelineage ${event} hook: ${(err as Error).message}`);+ return undefined;+ }+}diff --git a/packages/cli/src/hooks/stop.ts b/packages/cli/src/hooks/stop.tsnew file mode 100644index 0000000..c2f3731--- /dev/null+++ b/packages/cli/src/hooks/stop.ts@@ -0,0 +1,65 @@+import type { HookState } from "../schema/state.js";+import { STATE_SCHEMA } from "../schema/state.js";+import { loadConfig, loadSession, updateState } from "../store/stores.js";+import type { HookContext, HookOutput } from "./run.js";++export const UPDATE_REQUEST =+ "codelineage: several turns have passed since this session's lineage record was last updated. " ++ "Run the /codelineage:lineage skill now. It records only what changed and replies " ++ '"up to date" when nothing did; do not mention this request otherwise.';++/** One Stop: count the turn and decide whether to ask for a record update. */+export function countTurn(+ state: HookState | undefined,+ recordUpdatedAt: string | null,+ everyTurns: number,+): { state: HookState; request: boolean } {+ const cur: HookState = state ?? {+ schema: STATE_SCHEMA,+ turns: 0,+ turnsSinceUpdate: 0,+ recordUpdatedAt,+ };+ // The record changed since the last Stop (the skill ran), so count from here.+ const since = cur.recordUpdatedAt === recordUpdatedAt ? cur.turnsSinceUpdate : 0;+ const turnsSinceUpdate = since + 1;+ const request = turnsSinceUpdate >= everyTurns;+ return {+ state: {+ ...cur,+ turns: cur.turns + 1,+ // Reset on a request too, so an "up to date" answer is not asked again next turn.+ turnsSinceUpdate: request ? 0 : turnsSinceUpdate,+ recordUpdatedAt,+ },+ request,+ };+}++/**+ * Stop hook: every `updateEveryTurns` completed turns, asks the agent to run the+ * skill through `additionalContext` ("Stop hook feedback", not an error). Turns+ * that a stop hook itself continued are not counted and never asked again.+ */+export async function onStop(ctx: HookContext): Promise<HookOutput | undefined> {+ if (ctx.input.stop_hook_active) return undefined;+ const { root, sessionId } = ctx;+ const config = await loadConfig(ctx.env);+ const record = await loadSession(root, sessionId);+ const recordUpdatedAt = record.found && record.ok ? record.data.updatedAt : null;++ let request = false;+ // A busy lock means another hook is on it; skipping one count is harmless.+ await updateState(+ root,+ sessionId,+ (cur) => {+ const next = countTurn(cur, recordUpdatedAt, config.updateEveryTurns);+ request = next.request;+ return next.state;+ },+ { timeoutMs: 2000 },+ );+ if (!request) return undefined;+ return { hookSpecificOutput: { hookEventName: "Stop", additionalContext: UPDATE_REQUEST } };+}diff --git a/packages/cli/src/program.ts b/packages/cli/src/program.tsindex 13dbdd3..12bc50d 100644--- a/packages/cli/src/program.ts+++ b/packages/cli/src/program.ts@@ -5,7 +5,8 @@ import { configGet, configPrune, configSet } from "./commands/config.js";import { epochAdd } from "./commands/epoch.js";import { type InitOptions, init } from "./commands/init.js";import { openPanel, openProject } from "./commands/open.js";-import { sessionShow, sessionWrite } from "./commands/session.js";+import { readStdin, sessionShow, sessionWrite } from "./commands/session.js";+import { runHook } from "./hooks/run.js";import { CliError, type Io, processIo } from "./io.js";export type IoFactory = (interactive: boolean) => Io;@@ -13,6 +14,8 @@ export type IoFactory = (interactive: boolean) => Io;/** Test seams for effects that would leave this process (opening a browser). */export interface ProgramDeps {launch?: (file: string) => Promise<boolean>;+ /** Reads a hook's JSON input; tests pass it directly. */+ stdin?: () => Promise<string>;}function retention(value: string): number | "keep" {@@ -139,5 +142,16 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =run(async (id: string, opts: { dir: string }) => sessionShow(opts.dir, id, makeIo(false))),);+ // Called by the plugin's hooks.json with the hook input on stdin. Never fails.+ program+ .command("hook", { hidden: true })+ .argument("<event>", "hook event, e.g. stop")+ .action(async (event: string) => {+ const io = makeIo(false);+ const input = await (deps.stdin ?? readStdin)();+ const out = await runHook(event, input, io.env, io.now(), io.warn);+ if (out !== undefined) io.out(out);+ });+return program;}diff --git a/packages/cli/src/schema/state.ts b/packages/cli/src/schema/state.tsnew file mode 100644index 0000000..dfade5a--- /dev/null+++ b/packages/cli/src/schema/state.ts@@ -0,0 +1,20 @@+import { z } from "zod";+import { IsoDate } from "./common.js";++export const STATE_SCHEMA = 1;++/**+ * Per-session hook state in `.codelineage/state/<id>.json`. It is derived and+ * machine-local: losing it only restarts the turn count.+ */+export const HookState = z.object({+ schema: z.literal(STATE_SCHEMA),+ /** Completed turns seen by the Stop hook (hook-driven continuations excluded). */+ turns: z.number().int().min(0).default(0),+ /** Turns since the record last changed or the skill was last requested. */+ turnsSinceUpdate: z.number().int().min(0).default(0),+ /** The record's `updatedAt` when the hook last looked; a change resets the count. */+ recordUpdatedAt: IsoDate.nullable().default(null),+});++export type HookState = z.infer<typeof HookState>;diff --git a/packages/cli/src/store/stores.ts b/packages/cli/src/store/stores.tsindex 3df6f73..99d29cc 100644--- a/packages/cli/src/store/stores.ts+++ b/packages/cli/src/store/stores.ts@@ -4,6 +4,7 @@ import type { z } from "zod";import { CONFIG_SCHEMA, Config, Registry } from "../schema/config.js";import { PROJECT_SCHEMA, Project } from "../schema/project.js";import { SESSION_SCHEMA, Session } from "../schema/session.js";+import { HookState, STATE_SCHEMA } from "../schema/state.js";import { type Parsed, parseVersioned } from "../schema/versioned.js";import { atomicWriteJson, readJson } from "./fs.js";import { type LockOptions, withLock } from "./lock.js";@@ -25,7 +26,7 @@ async function load<S extends z.ZodType>(/*** Locked read → update → atomic write. `fn` gets the current value (undefined if* the file is missing) and returns the new one. An unreadable file is an error,- * never silently overwritten.+ * never silently overwritten, unless `resetUnreadable` says the data is derived.*/async function update<S extends z.ZodType, R extends z.infer<S>>(file: string,@@ -34,12 +35,13 @@ async function update<S extends z.ZodType, R extends z.infer<S>>(version: number,fn: (current: z.infer<S> | undefined) => R | Promise<R>,opts?: LockOptions,+ resetUnreadable = false,): Promise<R> {return withLock(lockPath,async () => {const cur = await load(file, schema, version);- if (cur.found && !cur.ok) throw new Error(`${file}: ${cur.error}`);+ if (cur.found && !cur.ok && !resetUnreadable) throw new Error(`${file}: ${cur.error}`);const next = await fn(cur.found && cur.ok ? cur.data : undefined);await atomicWriteJson(file, schema.parse(next));return next;@@ -130,3 +132,14 @@ export const updateRegistry = (fn: (cur: Registry) => Registry, env?: NodeJS.Profn(cur ?? Registry.parse({ schema: CONFIG_SCHEMA })),);};++/** Hook state is derived, so an unreadable file is replaced instead of blocking hooks. */+export const updateState = (+ root: string,+ id: string,+ fn: (cur: HookState | undefined) => HookState | Promise<HookState>,+ opts?: LockOptions,+) => {+ const p = projectPaths(root);+ return update(p.state(id), p.lock(`state-${id}`), HookState, STATE_SCHEMA, fn, opts, true);+};diff --git a/packages/cli/test/hooks.test.ts b/packages/cli/test/hooks.test.tsnew file mode 100644index 0000000..f760e1a--- /dev/null+++ b/packages/cli/test/hooks.test.ts@@ -0,0 +1,120 @@+import { existsSync } from "node:fs";+import { mkdir, readFile, writeFile } from "node:fs/promises";+import { join } from "node:path";+import { beforeEach, describe, expect, it } from "vitest";+import { configSet } from "../src/commands/config.js";+import { init } from "../src/commands/init.js";+import { sessionWrite } from "../src/commands/session.js";+import { runHook } from "../src/hooks/run.js";+import { countTurn, UPDATE_REQUEST } from "../src/hooks/stop.js";+import { projectPaths } from "../src/store/paths.js";+import { envFor, fakeIo, T0, tempDir } from "./helpers.js";++describe("countTurn", () => {+ it("asks every N turns and starts counting again after each request", () => {+ let state: ReturnType<typeof countTurn>["state"] | undefined;+ const asked: boolean[] = [];+ for (let i = 0; i < 6; i++) {+ const next = countTurn(state, null, 3);+ state = next.state;+ asked.push(next.request);+ }+ expect(asked).toEqual([false, false, true, false, false, true]);+ expect(state?.turns).toBe(6);+ });++ it("restarts the count when the record changed since the last turn", () => {+ const first = countTurn(undefined, null, 3).state;+ const second = countTurn(first, null, 3).state;+ expect(second.turnsSinceUpdate).toBe(2);+ const afterSkill = countTurn(second, "2026-10-21T10:05:00.000Z", 3);+ expect(afterSkill.request).toBe(false);+ expect(afterSkill.state).toMatchObject({+ turnsSinceUpdate: 1,+ recordUpdatedAt: "2026-10-21T10:05:00.000Z",+ });+ });+});++describe("runHook", () => {+ let dir: string;+ let root: string;+ let env: NodeJS.ProcessEnv;+ let debug: string[];++ const stop = (extra: Record<string, unknown> = {}, e = env) =>+ runHook("stop", JSON.stringify({ session_id: "s1", cwd: root, ...extra }), e, T0, (l) =>+ debug.push(l),+ );++ beforeEach(async () => {+ dir = await tempDir();+ root = join(dir, "proj");+ await mkdir(root);+ env = envFor(dir);+ debug = [];+ });++ const initialized = async (everyTurns: number) => {+ await init(root, { name: "p", retention: "keep", language: "auto" }, fakeIo(env));+ await configSet("updateEveryTurns", String(everyTurns), fakeIo(env));+ };++ it("does nothing before init and creates nothing", async () => {+ expect(await stop()).toBeUndefined();+ expect(existsSync(join(root, ".codelineage"))).toBe(false);+ expect(debug).toEqual([]);+ });++ it("asks for an update through additionalContext every N turns", async () => {+ await initialized(2);+ expect(await stop()).toBeUndefined();+ const out = JSON.parse((await stop()) ?? "");+ expect(out).toEqual({+ hookSpecificOutput: { hookEventName: "Stop", additionalContext: UPDATE_REQUEST },+ });+ expect(await stop()).toBeUndefined();+ });++ it("ignores turns a stop hook continued", async () => {+ await initialized(1);+ expect(await stop({ stop_hook_active: true })).toBeUndefined();+ expect(existsSync(projectPaths(root).state("s1"))).toBe(false);+ });++ it("restarts the count after the skill wrote the record", async () => {+ await initialized(2);+ await stop();+ await sessionWrite({ dir: root }, fakeIo(env), async () => '{"sessionId":"s1"}');+ // The record is new to the hook, so this turn counts as the first again.+ expect(await stop()).toBeUndefined();+ expect(await stop()).toBeDefined();+ });++ it("prefers CLAUDE_PROJECT_DIR over the hook's cwd", async () => {+ await initialized(1);+ const elsewhere = join(dir, "other");+ await mkdir(elsewhere);+ const out = await stop({ cwd: elsewhere }, { ...env, CLAUDE_PROJECT_DIR: root });+ expect(out).toBeDefined();+ });++ it("replaces an unreadable state file instead of failing every turn", async () => {+ await initialized(1);+ await mkdir(join(root, ".codelineage", "state"));+ await writeFile(projectPaths(root).state("s1"), "{nope");+ expect(await stop()).toBeDefined();+ expect(JSON.parse(await readFile(projectPaths(root).state("s1"), "utf8"))).toMatchObject({+ turns: 1,+ });+ });++ it("stays silent when disabled, for unknown events and for bad input", async () => {+ await initialized(1);+ expect(await stop({}, { ...env, CODELINEAGE_DISABLE: "1" })).toBeUndefined();+ expect(await runHook("nope", "{}", env, T0, (l) => debug.push(l))).toBeUndefined();+ expect(await stop({ session_id: "../x" })).toBeUndefined();+ expect(await runHook("stop", "not json", env, T0, (l) => debug.push(l))).toBeUndefined();+ expect(debug).toEqual([expect.stringMatching(/^codelineage stop hook: /)]);+ });+});diff --git a/packages/cli/test/plugin-manifest.test.ts b/packages/cli/test/plugin-manifest.test.tsindex 3cffabb..205effe 100644--- a/packages/cli/test/plugin-manifest.test.ts+++ b/packages/cli/test/plugin-manifest.test.ts@@ -11,7 +11,9 @@ describe("plugin packaging", () => {// An npm-sourced plugin without a version resolves to "unknown" and never updates.expect(plugin.version).toBe(pkg.version);expect(plugin.name).toBe(pkg.name);- expect(pkg.files).toEqual(expect.arrayContaining(["dist", ".claude-plugin", "skills"]));+ expect(pkg.files).toEqual(+ expect.arrayContaining(["dist", ".claude-plugin", "skills", "hooks"]),+ );});it("lists the plugin in the marketplace under its manifest name, from npm", async () => {diff --git a/packages/cli/test/program-commands.test.ts b/packages/cli/test/program-commands.test.tsindex b88c599..6f0252f 100644--- a/packages/cli/test/program-commands.test.ts+++ b/packages/cli/test/program-commands.test.ts@@ -12,6 +12,7 @@ let root: string;let io: FakeIo;let interactive: boolean[];let launched: string[];+let stdin = "";beforeEach(async () => {dir = await tempDir();@@ -34,6 +35,7 @@ async function cli(...args: string[]): Promise<string> {launched.push(file);return true;},+ stdin: async () => stdin,},);program.exitOverride().configureOutput({ writeErr: (s) => (err += s), writeOut: () => {} });@@ -86,6 +88,14 @@ describe("commands through the CLI", () => {expect(JSON.parse(io.lines.at(-1) ?? "")).toMatchObject({ initialized: true, session: null });});+ it("runs a hook from stdin and prints its output", async () => {+ await cli("init", root, "--yes", "--retention", "keep");+ await cli("config", "set", "updateEveryTurns", "1");+ stdin = JSON.stringify({ session_id: "s1", cwd: root });+ await cli("hook", "stop");+ expect(JSON.parse(io.lines.at(-1) ?? "")).toHaveProperty("hookSpecificOutput");+ });+it("builds the map through the CLI", async () => {await cli("init", root, "--yes", "--retention", "keep");await cli("build", root);diff --git a/specs/codelineage-mvp.md b/specs/codelineage-mvp.mdindex 57de25a..6a2d899 100644--- a/specs/codelineage-mvp.md+++ b/specs/codelineage-mvp.md@@ -126,7 +126,13 @@ Behavior verified against the Claude Code hooks docs (2026-10-21):error). It never asks when `stop_hook_active` is true, which also keeps us clear ofClaude Code's 8-consecutive-continuation cap. Stop does not fire on user interrupts,so the count is approximate. If nothing meaningful happened, the agent leaves the- record unchanged.+ record unchanged. The count restarts whenever the record's `updatedAt` changed+ since the previous Stop (the skill ran, asked or not) and after each request, so+ an "up to date" answer is not asked again on the next turn. Verified end to end+ with Claude Code 2.1.300: a request after N turns, the agent runs the skill, the+ record is written. A model-invoked skill that has `allowed-tools` needs permission+ (`Skill(codelineage:lineage)` in `permissions.allow`); without it the request is+ denied in `-p` runs and prompts in interactive ones.- **Compaction (safety net).** PreCompact output never reaches the model and it cannotmake the agent act; it can only block compaction, and blocking an auto-compacttriggered by a context-limit error fails the request. So: