Skip to content

armgit / cogit

Public Imported from GitHub
0

Git for the intent behind agent-written code. Records what your coding agent decided and why, and links every commit to it.

feat(hooks): ask for a record update after compaction

Eren6377e515643b
diff --git a/CHANGELOG.md b/CHANGELOG.md
index cc3907f..cf7657b 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
+- 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.
- Git worktree support: a Claude Code session in a linked worktree (`claude -w`) now records into the main checkout's `.codelineage/` when it is git-ignored (a worktree with its own committed copy keeps it), found by reading `.git` files without running git. Hooks, `session write/show`, `epoch add`, `build` and `open` all resolve it; the session keeps the worktree path and branch, and the map's drill-down shows them.
diff --git a/packages/cli/hooks/hooks.json b/packages/cli/hooks/hooks.json
index 8b0179c..e7701fa 100644
--- a/packages/cli/hooks/hooks.json
+++ b/packages/cli/hooks/hooks.json
@@ -11,6 +11,18 @@
}
]
}
+ ],
+ "SessionStart": [
+ {
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node",
+ "args": ["${CLAUDE_PLUGIN_ROOT}/dist/cli.js", "hook", "sessionstart"],
+ "timeout": 10
+ }
+ ]
+ }
]
}
}
diff --git a/packages/cli/src/commands/session.ts b/packages/cli/src/commands/session.ts
index 30092e4..621d568 100644
--- a/packages/cli/src/commands/session.ts
+++ b/packages/cli/src/commands/session.ts
@@ -8,7 +8,13 @@ import { MESSAGE_ID, SessionInput } from "../schema/session.js";
import { projectPaths } from "../store/paths.js";
import { resolveProjectRoot } from "../store/root.js";
import { loadConfig, loadProject, loadSession, updateSession } from "../store/stores.js";
-import { excerpt, findTranscript, readUserMessages, type UserMessage } from "../transcript.js";
+import {
+ countUserLines,
+ excerpt,
+ findTranscript,
+ readUserMessages,
+ type UserMessage,
+} from "../transcript.js";
import { buildProject } from "./build.js";
export async function readStdin(stream: NodeJS.ReadableStream = process.stdin): Promise<string> {
@@ -83,20 +89,28 @@ export async function sessionWrite(
}
}
-/** The session's user messages, or null when its transcript cannot be read. */
-async function userMessages(
+/** The session's transcript file and user messages, or null when it cannot be read. */
+async function transcriptMessages(
sessionId: string,
env: NodeJS.ProcessEnv,
-): Promise<UserMessage[] | null> {
+): Promise<{ file: string; messages: UserMessage[] } | null> {
const file = await findTranscript(sessionId, env);
if (!file) return null;
try {
- return await readUserMessages(file);
+ return { file, messages: await readUserMessages(file) };
} catch {
return null;
}
}
+/** The session's user messages, or null when its transcript cannot be read. */
+async function userMessages(
+ sessionId: string,
+ env: NodeJS.ProcessEnv,
+): Promise<UserMessage[] | null> {
+ return (await transcriptMessages(sessionId, env))?.messages ?? null;
+}
+
/**
* Message nodes take their time from the transcript, so their order on the map
* is the order the user wrote them, whatever the agent sent. Without a
@@ -176,7 +190,8 @@ export async function sessionShow(dir: string, sessionId: string, io: Io): Promi
} else if (loaded.found) {
view.sessionError = loaded.error;
}
- const messages = await userMessages(sessionId, io.env);
+ const transcript = await transcriptMessages(sessionId, io.env);
+ const messages = transcript?.messages ?? null;
if (messages) {
const recorded = new Set(loaded.found && loaded.ok ? loaded.data.nodes.map((n) => n.id) : []);
view.messageCount = messages.length;
@@ -186,6 +201,14 @@ export async function sessionShow(dir: string, sessionId: string, io: Io): Promi
} else {
view.newMessages = null;
}
+ // A format change would otherwise look like "nothing written yet" forever.
+ if (transcript && transcript.messages.length === 0) {
+ const userLines = await countUserLines(transcript.file).catch(() => 0);
+ if (userLines > 0)
+ view.transcriptWarning =
+ `the transcript has ${userLines} user line(s) but none read as a message; ` +
+ "Claude Code's transcript format may have changed";
+ }
view.inbox = projectPaths(given).inbox(sessionId);
io.out(JSON.stringify(view, null, 2));
}
diff --git a/packages/cli/src/git.ts b/packages/cli/src/git.ts
index cabd72f..902bc39 100644
--- a/packages/cli/src/git.ts
+++ b/packages/cli/src/git.ts
@@ -23,7 +23,6 @@ const HEADER = "# codelineage";
/** Machine-local data that must never be committed, whatever the policy. */
const ALWAYS = [
"/.codelineage/state/",
- "/.codelineage/snapshots/",
"/.codelineage/locks/",
"/.codelineage/inbox/",
"/.codelineage/lineage.html",
diff --git a/packages/cli/src/hooks/run.ts b/packages/cli/src/hooks/run.ts
index e0d0952..5dab0d9 100644
--- a/packages/cli/src/hooks/run.ts
+++ b/packages/cli/src/hooks/run.ts
@@ -3,6 +3,7 @@ import { z } from "zod";
import { Slug } from "../schema/common.js";
import { projectPaths } from "../store/paths.js";
import { resolveProjectRoot } from "../store/root.js";
+import { onSessionStart } from "./sessionstart.js";
import { onStop } from "./stop.js";
/** The common fields of a Claude Code hook input we rely on. */
@@ -10,6 +11,8 @@ export const HookInput = z.looseObject({
session_id: z.string(),
cwd: z.string().optional(),
stop_hook_active: z.boolean().optional(),
+ /** SessionStart only: `startup`, `resume`, `clear` or `compact`. */
+ source: z.string().optional(),
});
export type HookInput = z.infer<typeof HookInput>;
@@ -26,6 +29,7 @@ export type HookOutput = Record<string, unknown>;
const HANDLERS: Record<string, (ctx: HookContext) => Promise<HookOutput | undefined>> = {
stop: onStop,
+ sessionstart: onSessionStart,
};
export const HOOK_EVENTS = Object.keys(HANDLERS);
diff --git a/packages/cli/src/hooks/sessionstart.ts b/packages/cli/src/hooks/sessionstart.ts
new file mode 100644
index 0000000..34ef7cd
--- /dev/null
+++ b/packages/cli/src/hooks/sessionstart.ts
@@ -0,0 +1,37 @@
+import { loadSession } from "../store/stores.js";
+import { findTranscript, readUserMessages } from "../transcript.js";
+import type { HookContext, HookOutput } from "./run.js";
+
+export const COMPACT_REQUEST =
+ "codelineage: this session was compacted and some of its user messages are not in the " +
+ "lineage record yet. Run the /codelineage:lineage skill now; `session show` lists the " +
+ "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.';
+
+/**
+ * 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.
+ */
+export async function onSessionStart(ctx: HookContext): Promise<HookOutput | undefined> {
+ if (ctx.input.source !== "compact") return undefined;
+ const file = await findTranscript(ctx.sessionId, ctx.env);
+ if (!file) return undefined;
+ let messages;
+ try {
+ messages = await readUserMessages(file);
+ } catch {
+ return undefined;
+ }
+ const 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,
+ },
+ };
+}
diff --git a/packages/cli/src/program.ts b/packages/cli/src/program.ts
index 5fedb20..f4cf36a 100644
--- a/packages/cli/src/program.ts
+++ b/packages/cli/src/program.ts
@@ -149,7 +149,7 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =
// 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")
+ .argument("<event>", "hook event, e.g. stop or sessionstart")
.action(async (event: string) => {
const io = makeIo(false);
const input = await (deps.stdin ?? readStdin)();
diff --git a/packages/cli/src/store/paths.ts b/packages/cli/src/store/paths.ts
index 64b7e7e..78419ac 100644
--- a/packages/cli/src/store/paths.ts
+++ b/packages/cli/src/store/paths.ts
@@ -11,7 +11,6 @@ export function projectPaths(root: string) {
sessions: join(base, "sessions"),
session: (id: string) => join(base, "sessions", `${id}.json`),
state: (id: string) => join(base, "state", `${id}.json`),
- snapshots: join(base, "snapshots"),
locks: join(base, "locks"),
/** Where the skill drops session JSON for `session write --file`. */
inbox: (id: string) => join(base, "inbox", `${id}.json`),
diff --git a/packages/cli/src/transcript.ts b/packages/cli/src/transcript.ts
index 4a0559c..1669181 100644
--- a/packages/cli/src/transcript.ts
+++ b/packages/cli/src/transcript.ts
@@ -191,6 +191,24 @@ export async function readUserMessages(file: string): Promise<UserMessage[]> {
return (await readConversation(file)).map(({ id, at, text }) => ({ id, at, text }));
}
+/**
+ * Counts `type: "user"` lines in a transcript, whether or not they are messages
+ * (tool results, injected text and shell lines are user lines too). When this is
+ * above zero and `readUserMessages` finds none, Claude Code's format changed under
+ * us rather than the user having written nothing.
+ */
+export async function countUserLines(file: string): Promise<number> {
+ let count = 0;
+ const lines = createInterface({ input: createReadStream(file, "utf8"), crlfDelay: Infinity });
+ for await (const raw of lines) {
+ if (!raw.includes('"type":"user"')) continue;
+ try {
+ if ((JSON.parse(raw) as { type?: unknown }).type === "user") count += 1;
+ } catch {}
+ }
+ return count;
+}
+
/** Up to this many characters of a message go to the agent. */
export const EXCERPT_LENGTH = 300;
diff --git a/packages/cli/test/hooks.test.ts b/packages/cli/test/hooks.test.ts
index f760e1a..dc160cc 100644
--- a/packages/cli/test/hooks.test.ts
+++ b/packages/cli/test/hooks.test.ts
@@ -6,6 +6,7 @@ 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 { COMPACT_REQUEST } from "../src/hooks/sessionstart.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";
@@ -47,6 +48,11 @@ describe("runHook", () => {
debug.push(l),
);
+ const sessionStart = (source: string, e = env) =>
+ runHook("sessionstart", JSON.stringify({ session_id: "s1", cwd: root, source }), e, T0, (l) =>
+ debug.push(l),
+ );
+
beforeEach(async () => {
dir = await tempDir();
root = join(dir, "proj");
@@ -109,6 +115,75 @@ describe("runHook", () => {
});
});
+ const transcript = async (lines: unknown[]) => {
+ const folder = join(env.CLAUDE_CONFIG_DIR ?? "", "projects", "proj");
+ await mkdir(folder, { recursive: true });
+ await writeFile(
+ join(folder, "s1.jsonl"),
+ `${lines.map((l) => JSON.stringify(l)).join("\n")}\n`,
+ );
+ };
+
+ const typed = (text: string, m: number) => ({
+ type: "user",
+ timestamp: `2026-10-23T10:0${m}:00.000Z`,
+ message: { role: "user", content: text },
+ });
+
+ it("asks for an update after compaction when messages have no node", async () => {
+ await initialized(2);
+ await transcript([typed("first", 1), typed("second", 2)]);
+ expect(JSON.parse((await sessionStart("compact")) ?? "")).toEqual({
+ hookSpecificOutput: { hookEventName: "SessionStart", additionalContext: COMPACT_REQUEST },
+ });
+ });
+
+ it("stays quiet after compaction when every message has a node", async () => {
+ await initialized(2);
+ await transcript([typed("first", 1)]);
+ await sessionWrite({ dir: root }, fakeIo(env), async () =>
+ JSON.stringify({ sessionId: "s1", nodes: [{ id: "m1", kind: "message", title: "First" }] }),
+ );
+ expect(await sessionStart("compact")).toBeUndefined();
+ });
+
+ it("stays quiet for other sources, without a transcript and when disabled", async () => {
+ await initialized(2);
+ expect(await sessionStart("compact")).toBeUndefined();
+ await transcript([typed("first", 1)]);
+ expect(await sessionStart("startup")).toBeUndefined();
+ expect(await sessionStart("resume")).toBeUndefined();
+ expect(await sessionStart("clear")).toBeUndefined();
+ expect(await sessionStart("compact", { ...env, CODELINEAGE_DISABLE: "1" })).toBeUndefined();
+ });
+
+ it("stays quiet when the transcript cannot be read", async () => {
+ await initialized(2);
+ // A directory where the transcript should be: found, but reading it fails.
+ await mkdir(join(env.CLAUDE_CONFIG_DIR ?? "", "projects", "proj", "s1.jsonl"), {
+ recursive: true,
+ });
+ expect(await sessionStart("compact")).toBeUndefined();
+ });
+
+ it("stays quiet before init even when the transcript has unrecorded messages", async () => {
+ await transcript([typed("first", 1)]);
+ expect(await sessionStart("compact")).toBeUndefined();
+ expect(existsSync(join(root, ".codelineage"))).toBe(false);
+ });
+
+ it("ignores transcript lines that are not messages", async () => {
+ await initialized(2);
+ await transcript([
+ {
+ type: "user",
+ timestamp: "2026-10-23T10:01:00.000Z",
+ message: { role: "user", content: [{ type: "tool_result", content: "out" }] },
+ },
+ ]);
+ expect(await sessionStart("compact")).toBeUndefined();
+ });
+
it("stays silent when disabled, for unknown events and for bad input", async () => {
await initialized(1);
expect(await stop({}, { ...env, CODELINEAGE_DISABLE: "1" })).toBeUndefined();
diff --git a/packages/cli/test/init.test.ts b/packages/cli/test/init.test.ts
index 8a44bdb..cb057d3 100644
--- a/packages/cli/test/init.test.ts
+++ b/packages/cli/test/init.test.ts
@@ -52,7 +52,7 @@ describe("init", () => {
io,
);
expect((await loadConfig(env)).language).toBe("Turkish");
- expect(await readText(join(root, ".gitignore"))).toContain("/.codelineage/snapshots/");
+ expect(await readText(join(root, ".gitignore"))).toContain("/.codelineage/state/");
});
it("asks for the git policy in a repo and writes .gitignore", async () => {
@@ -214,7 +214,7 @@ describe("git helpers", () => {
it("appends only missing lines and keeps existing content", async () => {
const gi = join(root, ".gitignore");
await writeFile(gi, "node_modules/");
- expect(await ensureGitignore(root, "commit")).toHaveLength(5);
+ expect(await ensureGitignore(root, "commit")).toHaveLength(4);
expect(await ensureGitignore(root, "commit")).toEqual([]);
expect(await ensureGitignore(root, "ignore")).toEqual(["/.codelineage/"]);
const text = await readText(gi);
diff --git a/packages/cli/test/session.test.ts b/packages/cli/test/session.test.ts
index 0be6a12..2c3001e 100644
--- a/packages/cli/test/session.test.ts
+++ b/packages/cli/test/session.test.ts
@@ -252,6 +252,26 @@ ${line("second", 2)}
]);
});
+ it("warns when the transcript has user lines but none reads as a message", async () => {
+ await init(root, { name: "p", retention: "keep", language: "auto" }, fakeIo(envFor(dir)));
+ const folder = join(dir, "claude", "projects", "-p");
+ await mkdir(folder, { recursive: true });
+ await writeFile(
+ join(folder, "s1.jsonl"),
+ `${JSON.stringify({
+ type: "user",
+ timestamp: "2026-10-23T10:01:00.000Z",
+ message: { role: "user", content: { changed: "shape" } },
+ })}\n`,
+ );
+ await sessionShow(root, "s1", io);
+ expect(shown()).toMatchObject({
+ messageCount: 0,
+ newMessages: [],
+ transcriptWarning: expect.stringMatching(/format may have changed/),
+ });
+ });
+
it("flags an unreadable record instead of hiding it", async () => {
await init(root, { name: "p", retention: "keep", language: "auto" }, fakeIo(envFor(dir)));
await writeFile(join(root, ".codelineage", "sessions", "s1.json"), "{nope");
diff --git a/packages/cli/test/store.test.ts b/packages/cli/test/store.test.ts
index 40df64a..97266be 100644
--- a/packages/cli/test/store.test.ts
+++ b/packages/cli/test/store.test.ts
@@ -37,10 +37,7 @@ describe("paths", () => {
expect(p.session("s1")).toBe("/r/.codelineage/sessions/s1.json");
expect(p.state("s1")).toBe("/r/.codelineage/state/s1.json");
expect(p.lock("project")).toBe("/r/.codelineage/locks/project.lock");
- expect([p.snapshots, p.html]).toEqual([
- "/r/.codelineage/snapshots",
- "/r/.codelineage/lineage.html",
- ]);
+ expect(p.html).toBe("/r/.codelineage/lineage.html");
});
});