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(hooks): offer setup in projects without init
Eren6cbc1966d67b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex cf7657b..ac59b4a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]### Added+- SessionStart setup hint: on `startup` or `resume` in a project without `.codelineage/`, the plugin offers setup to the agent (it says codelineage is not set up and sets it up only when the user asks, running the bundled `init` with the answers), and the hint notes that a plugin update reaches a running session only after `/reload-plugins` or a new chat. `codelineage config hint-off [dir]` silences the hint in that project ("don't ask again", kept in the global `setupHintOff` list, keyed by the main checkout so a worktree is covered) and `codelineage config hint-on [dir] [--all]` turns it back on. `CODELINEAGE_DISABLE=1` still silences every hook.- Compaction safety net: SessionStart with `source: "compact"` reads the transcript and, when user messages have no lineage node yet, asks the agent through `additionalContext` to run `/codelineage:lineage` (compaction keeps every transcript line, so nothing is lost and no snapshot is taken). `session show` also adds a `transcriptWarning` when the transcript has user lines but none reads as a message, so a Claude Code format change is noticed instead of silently recording nothing.- The map shows the conversation: a message's drill-down has the message as the user wrote it and the agent's written replies (tool output left out, tool use counted in one line), with buttons to step to the previous or next message across topics. `build` reads it from the Claude Code transcript into `lineage.html` only, which is never committed; session files still hold no raw text. Long entries open folded; a deleted transcript is said so.- The map is the user's messages: each message the user wrote becomes one node (`kind: "message"`, ids `m1`, `m2`, … in transcript order), titled in the user's words with what came of it, grouped under topics and ordered by when it was sent. `session show` reads the session's Claude Code transcript and lists the messages that have no node yet, and `session write` takes their times from it. The agent's own work moves into the node's detail (`work`, `agentDecisions` with reasons and rejected options, `commits`, `files`), "left off here" marks only the last message, and the `/codelineage:lineage` skill is rewritten for this. Older records keep their step, decision and question nodes.diff --git a/packages/cli/src/commands/config.ts b/packages/cli/src/commands/config.tsindex c17e3ff..042be7c 100644--- a/packages/cli/src/commands/config.ts+++ b/packages/cli/src/commands/config.ts@@ -1,6 +1,7 @@import { CliError, type Io } from "../io.js";import { Config, type RegistryEntry } from "../schema/config.js";import { isDirectory } from "../store/fs.js";+import { resolveProjectRoot } from "../store/root.js";import { loadConfig, loadRegistry, updateConfig, updateRegistry } from "../store/stores.js";export const CONFIG_KEYS = Object.keys(Config.shape).filter((k) => k !== "schema") as Exclude<@@ -50,6 +51,38 @@ export async function configSet(key: string, raw: string, io: Io): Promise<void>io.out(`${key} = ${JSON.stringify(next.data[key])}`);}+/**+ * Stops the SessionStart setup hint in a project ("don't ask again"). The list is+ * keyed by the main checkout's root, so a linked worktree is silenced with it.+ */+export async function configHintOff(dir: string, io: Io): Promise<void> {+ const { root } = await resolveProjectRoot(dir);+ let added = false;+ await updateConfig((c) => {+ if (c.setupHintOff.includes(root)) return c;+ added = true;+ return { ...c, setupHintOff: [...c.setupHintOff, root] };+ }, io.env);+ io.out(added ? `Setup hint off in ${root}` : `Setup hint was already off in ${root}`);+}++/** Turns the setup hint back on for one project, or for every project with `--all`. */+export async function configHintOn(dir: string, opts: { all?: boolean }, io: Io): Promise<void> {+ if (opts.all === true) {+ await updateConfig((c) => ({ ...c, setupHintOff: [] }), io.env);+ io.out("Setup hint on in every project");+ return;+ }+ const { root } = await resolveProjectRoot(dir);+ let removed = false;+ await updateConfig((c) => {+ if (!c.setupHintOff.includes(root)) return c;+ removed = true;+ return { ...c, setupHintOff: c.setupHintOff.filter((path) => path !== root) };+ }, io.env);+ io.out(removed ? `Setup hint on in ${root}` : `Setup hint was not off in ${root}`);+}+export interface PruneOptions {/** Lists the entries but leaves `projects.json` untouched. */dryRun?: boolean;diff --git a/packages/cli/src/hooks/run.ts b/packages/cli/src/hooks/run.tsindex 5dab0d9..60ed87a 100644--- a/packages/cli/src/hooks/run.ts+++ b/packages/cli/src/hooks/run.ts@@ -21,6 +21,8 @@ export interface HookContext {sessionId: string;/** Where `.codelineage/` lives: `CLAUDE_PROJECT_DIR`, else the hook's `cwd`, mapped out of a worktree. */root: string;+ /** Whether `.codelineage/project.json` exists; only SessionStart runs without it. */+ initialized: boolean;env: NodeJS.ProcessEnv;now: string;}@@ -54,9 +56,11 @@ export async function runHook(if (!Slug.safeParse(input.session_id).success) return undefined;// In a linked worktree both point at the worktree; the record lives in the main checkout.const { root } = await resolveProjectRoot(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 });+ const initialized = existsSync(projectPaths(root).project);+ // Before `init` every hook is a no-op except SessionStart, which offers setup;+ // projects are never registered here.+ if (!initialized && handler !== onSessionStart) return undefined;+ const out = await handler({ input, sessionId: input.session_id, root, initialized, env, now });return out === undefined ? undefined : JSON.stringify(out);} catch (err) {debug(`codelineage ${event} hook: ${(err as Error).message}`);diff --git a/packages/cli/src/hooks/sessionstart.ts b/packages/cli/src/hooks/sessionstart.tsindex 34ef7cd..5380c0b 100644--- a/packages/cli/src/hooks/sessionstart.ts+++ b/packages/cli/src/hooks/sessionstart.ts@@ -1,4 +1,4 @@-import { loadSession } from "../store/stores.js";+import { loadConfig, loadSession } from "../store/stores.js";import { findTranscript, readUserMessages } from "../transcript.js";import type { HookContext, HookOutput } from "./run.js";@@ -8,15 +8,52 @@ export const COMPACT_REQUEST ="messages that have no node. It records only what is missing and replies " +'"up to date" when nothing is; do not mention this request otherwise.';+/** The bundled CLI, as the agent should spell it in a project without `init`. */+function cli(ctx: HookContext): string {+ return `node "${ctx.env.CLAUDE_PLUGIN_ROOT ?? "${CLAUDE_PLUGIN_ROOT}"}/dist/cli.js"`;+}++/**+ * The setup offer for a project without `.codelineage/`. It only reaches the agent:+ * nothing is set up or registered unless the user asks for it.+ */+export function setupHint(ctx: HookContext): string {+ return (+ "codelineage is not set up in this project, so no lineage map is recorded here. " ++ "Say this once, in one line, and do not repeat it in later turns. If the user asks " ++ "you to set it up, ask the install questions in the chat (whether to commit " ++ ".codelineage/, whether to keep transcripts longer, whether the lineage skill may run " ++ "without asking, and the summary language), then run " ++ `${cli(ctx)} init --yes --git <ignore|commit> --retention <days|keep> --language <lang>` ++ " (add --allow-skill when the user agreed). Never run init or register the project on " ++ `your own. If the user wants no more hints here, run ${cli(ctx)} config hint-off. ` ++ "A plugin update reaches a running session only after /reload-plugins or a new chat."+ );+}+/**- * SessionStart hook for compaction. Compaction keeps every transcript line and the- * message nodes come from the transcript, so nothing is lost; the only risk is a- * record that fell behind. When the user's messages have no node yet, the agent is- * asked to run the skill, which works from the compact summary already in its- * context. Other sources (`startup`, `resume`, `clear`) are handled elsewhere.+ * SessionStart hook. Compaction keeps every transcript line and the message nodes+ * come from the transcript, so nothing is lost; the only risk is a record that fell+ * behind. When the user's messages have no node yet, the agent is asked to run the+ * skill, which works from the compact summary already in its context. On a startup+ * or resume in a project without `init`, the agent gets the setup offer instead.*/export async function onSessionStart(ctx: HookContext): Promise<HookOutput | undefined> {- if (ctx.input.source !== "compact") return undefined;+ if (ctx.input.source === "compact") return compactRequest(ctx);+ if (ctx.input.source !== "startup" && ctx.input.source !== "resume") return undefined;+ if (ctx.initialized) return undefined;+ const config = await loadConfig(ctx.env);+ // "Don't ask again in this project" lives outside the project.+ if (config.setupHintOff.includes(ctx.root)) return undefined;+ return additionalContext(setupHint(ctx));+}++function additionalContext(text: string): HookOutput {+ return { hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: text } };+}++async function compactRequest(ctx: HookContext): Promise<HookOutput | undefined> {+ if (!ctx.initialized) return undefined;const file = await findTranscript(ctx.sessionId, ctx.env);if (!file) return undefined;let messages;@@ -28,10 +65,5 @@ export async function onSessionStart(ctx: HookContext): Promise<HookOutput | undconst record = await loadSession(ctx.root, ctx.sessionId);const recorded = new Set(record.found && record.ok ? record.data.nodes.map((n) => n.id) : []);if (messages.every((m) => recorded.has(m.id))) return undefined;- return {- hookSpecificOutput: {- hookEventName: "SessionStart",- additionalContext: COMPACT_REQUEST,- },- };+ return additionalContext(COMPACT_REQUEST);}diff --git a/packages/cli/src/program.ts b/packages/cli/src/program.tsindex f4cf36a..ae2a98c 100644--- a/packages/cli/src/program.ts+++ b/packages/cli/src/program.ts@@ -1,7 +1,13 @@import { Command, InvalidArgumentError, Option } from "commander";import pkg from "../package.json" with { type: "json" };import { buildProject } from "./commands/build.js";-import { configGet, configPrune, configSet } from "./commands/config.js";+import {+ configGet,+ configHintOff,+ configHintOn,+ 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";@@ -101,6 +107,21 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =.argument("<key>").argument("<value>").action(run(async (key: string, value: string) => configSet(key, value, makeIo(false))));+ config+ .command("hint-off")+ .description("stop the SessionStart setup hint in a project")+ .argument("[dir]", "project directory", ".")+ .action(run(async (dir: string) => configHintOff(dir, makeIo(false))));+ config+ .command("hint-on")+ .description("show the SessionStart setup hint again in a project, or everywhere")+ .argument("[dir]", "project directory", ".")+ .option("--all", "turn the hint back on for every project")+ .action(+ run(async (dir: string, opts: { all?: boolean }) =>+ configHintOn(dir, { all: opts.all === true }, makeIo(false)),+ ),+ );config.command("prune").description("remove registered projects whose directory no longer exists")diff --git a/packages/cli/src/schema/config.ts b/packages/cli/src/schema/config.tsindex be86ec9..61c6fd9 100644--- a/packages/cli/src/schema/config.ts+++ b/packages/cli/src/schema/config.ts@@ -12,6 +12,8 @@ export const Config = z.object({/** Default for new projects; `init` asks per repo. */gitPolicy: z.enum(["ignore", "commit"]).default("ignore"),agents: z.array(z.string().min(1)).default(["claude-code"]),+ /** Project roots ("don't ask again" in this project) where the setup hint stays silent. */+ setupHintOff: z.array(z.string().min(1)).default([]),});export const RegistryEntry = z.object({diff --git a/packages/cli/test/hooks.test.ts b/packages/cli/test/hooks.test.tsindex dc160cc..91220d9 100644--- a/packages/cli/test/hooks.test.ts+++ b/packages/cli/test/hooks.test.ts@@ -2,7 +2,7 @@ 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 { configHintOff, configHintOn, 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";@@ -66,6 +66,58 @@ describe("runHook", () => {await configSet("updateEveryTurns", String(everyTurns), fakeIo(env));};+ it("offers setup before init on startup and resume, but not on clear", async () => {+ const startup = JSON.parse((await sessionStart("startup")) ?? "");+ expect(startup.hookSpecificOutput.hookEventName).toBe("SessionStart");+ expect(startup.hookSpecificOutput.additionalContext).toContain(+ "codelineage is not set up in this project",+ );+ expect(startup.hookSpecificOutput.additionalContext).toContain(+ '"${CLAUDE_PLUGIN_ROOT}/dist/cli.js" init --yes',+ );+ const known = JSON.parse(+ (await sessionStart("resume", { ...env, CLAUDE_PLUGIN_ROOT: "/plugins/codelineage" })) ?? "",+ );+ expect(known.hookSpecificOutput.additionalContext).toContain(+ '"/plugins/codelineage/dist/cli.js" init --yes',+ );+ expect(await sessionStart("clear")).toBeUndefined();+ expect(await sessionStart("startup", { ...env, CODELINEAGE_DISABLE: "1" })).toBeUndefined();+ expect(existsSync(join(root, ".codelineage"))).toBe(false);+ });++ it("stays quiet about setup after init", async () => {+ await initialized(2);+ expect(await sessionStart("startup")).toBeUndefined();+ expect(await sessionStart("resume")).toBeUndefined();+ });++ it("silences the setup hint per project with hint-off and undoes it with hint-on", async () => {+ const off = fakeIo(env);+ await configHintOff(root, off);+ expect(off.lines).toEqual([`Setup hint off in ${root}`]);+ expect(await sessionStart("startup")).toBeUndefined();++ const again = fakeIo(env);+ await configHintOff(root, again);+ expect(again.lines).toEqual([`Setup hint was already off in ${root}`]);++ const on = fakeIo(env);+ await configHintOn(root, {}, on);+ expect(on.lines).toEqual([`Setup hint on in ${root}`]);+ expect(await sessionStart("startup")).toBeDefined();++ const notOff = fakeIo(env);+ await configHintOn(root, {}, notOff);+ expect(notOff.lines).toEqual([`Setup hint was not off in ${root}`]);++ await configHintOff(root, fakeIo(env));+ const all = fakeIo(env);+ await configHintOn(".", { all: true }, all);+ expect(all.lines).toEqual(["Setup hint on in every project"]);+ expect(await sessionStart("startup")).toBeDefined();+ });+it("does nothing before init and creates nothing", async () => {expect(await stop()).toBeUndefined();expect(existsSync(join(root, ".codelineage"))).toBe(false);diff --git a/packages/cli/test/program-commands.test.ts b/packages/cli/test/program-commands.test.tsindex bb9cf12..cbc92cb 100644--- a/packages/cli/test/program-commands.test.ts+++ b/packages/cli/test/program-commands.test.ts@@ -82,6 +82,15 @@ describe("commands through the CLI", () => {expect(io.lines.at(-1)).toBe("Added epoch e1: First");});+ it("runs config hint-off and hint-on", async () => {+ await cli("config", "hint-off", root);+ expect(io.lines.at(-1)).toBe(`Setup hint off in ${root}`);+ expect((await loadConfig(io.env)).setupHintOff).toEqual([root]);+ await cli("config", "hint-on", "--all");+ expect(io.lines.at(-1)).toBe("Setup hint on in every project");+ expect((await loadConfig(io.env)).setupHintOff).toEqual([]);+ });+it("runs session write from a file", async () => {await cli("init", root, "--yes", "--retention", "keep");const f = join(dir, "s.json");diff --git a/specs/codelineage-mvp.md b/specs/codelineage-mvp.mdindex 9395071..168fba5 100644--- a/specs/codelineage-mvp.md+++ b/specs/codelineage-mvp.md@@ -196,8 +196,16 @@ Behavior verified against the Claude Code hooks docs (2026-10-21):`spawn(…, { detached: true, stdio: "ignore" }).unref()` outlives both the hookand Claude Code exiting, and is reparented to the init process.- **Before `init`:** if `.codelineage/` does not exist, all hooks are no-ops, except- that SessionStart injects a one-line hint to run `codelineage init`. Projects are- never registered automatically.+ that SessionStart on `startup` or `resume` injects a one-line offer: the agent says+ codelineage is not set up here and sets it up only when the user asks. Setup happens+ in the chat: the agent asks the install questions and runs the bundled CLI with+ `init --yes --git … --retention … --language …` (`--allow-skill` only when agreed).+ Projects are never registered automatically. `codelineage config hint-off [dir]`+ silences the offer in that project ("don't ask again", stored in the global+ `setupHintOff` list, keyed by the main checkout so a worktree is covered);+ `codelineage config hint-on [dir]` turns it back on, `--all` everywhere. A plugin+ update reaches a running session only after `/reload-plugins` or a new chat, and+ the offer says so.- **Recursion guard:** every headless run started by codelineage (`backfill`,catch-up) sets `CODELINEAGE_DISABLE=1`, and our hooks do nothing when it is set.Users can set it too, to turn capture off for any headless run (for example a@@ -222,6 +230,8 @@ Each update costs agent tokens (the user's subscription or API usage).| `codelineage open [dir]` | Builds, then opens the map (or the panel if no dir is given) through the local map server, starting it in the background if it is not running. The open page refreshes itself whenever the map is rebuilt, keeping open topics, selection and zoom. Falls back to opening the file when the server cannot start. || `codelineage epoch add <id> <title>` | Adds an epoch (locked write) || `codelineage config get/set <key> [value]` | Reads or changes settings |+| `codelineage config hint-off [dir]` | Stops the SessionStart setup offer in that project ("don't ask again") |+| `codelineage config hint-on [dir] [--all]` | Shows the setup offer again in that project, or everywhere with `--all` || `codelineage session show <id>` | Prints the compact record the skill injects (epochs, language, status, node ids/titles, inbox path) as JSON. Never fails for an uninitialized project. || `codelineage session write` | Reads session JSON from stdin or `--file` (the skill uses `--file <inbox> --consume`), validates, redacts, merges and writes it under the session lock, then builds. || `codelineage backfill [dir]` | Summarizes past transcripts of that project by running the agent headless, one session at a time. Estimates cost and asks first. Selection: `--pick` (default: lists sessions with date, first prompt and estimated cost), `--last <n>`, `--since <date>`, `--all`. |@@ -248,7 +258,8 @@ Each update costs agent tokens (the user's subscription or API usage).Settings in `config.json`: `language`, `updateEveryTurns`, `sessionEndCatchUp`,`catchUpModel` (model for the headless catch-up and backfill, default `haiku`),`serverPort` (local map server, default 4747),-`gitPolicy`, `agents`.+`gitPolicy`, `agents`, `setupHintOff` (project roots where the SessionStart setup+offer stays silent).## Privacy