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(plugin): add the lineage skill with session show and inbox writes

Eren1916ecbce963
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f38b450..b7492ac 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
- Claude Code plugin skeleton: the `codelineage` npm package is also the plugin (`.claude-plugin/plugin.json`, bundled `dist/cli.js`), and the repository root carries a `codelineage` marketplace that installs it from npm.
+- `/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.
+- `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/`.
+
### Changed
- `commander`, `zod` and `@inquirer/prompts` moved to `devDependencies`: they are bundled into `dist/cli.js`, so installing the package pulls in no runtime dependencies.
diff --git a/biome.json b/biome.json
index 42175d7..1cd63a3 100644
--- a/biome.json
+++ b/biome.json
@@ -1,7 +1,7 @@
{
"$schema": "./node_modules/@biomejs/biome/configuration_schema.json",
"files": {
- "includes": ["packages/**", "*.json", "*.ts", "!**/dist", "!**/coverage"]
+ "includes": ["packages/**", "*.json", "*.ts", "!**/dist", "!**/coverage", "!**/*.md"]
},
"formatter": { "indentStyle": "space", "indentWidth": 2, "lineWidth": 100 },
"linter": { "rules": { "preset": "none" } }
diff --git a/packages/cli/package.json b/packages/cli/package.json
index c884d23..9aed334 100644
--- a/packages/cli/package.json
+++ b/packages/cli/package.json
@@ -9,7 +9,8 @@
},
"files": [
"dist",
- ".claude-plugin"
+ ".claude-plugin",
+ "skills"
],
"engines": {
"node": ">=22.13.0"
diff --git a/packages/cli/skills/lineage/SKILL.md b/packages/cli/skills/lineage/SKILL.md
new file mode 100644
index 0000000..3ca846d
--- /dev/null
+++ b/packages/cli/skills/lineage/SKILL.md
@@ -0,0 +1,66 @@
+---
+name: lineage
+description: Record or update this session's lineage for codelineage, covering the goal, the decisions and their reasons, the steps, open questions and what comes next. Use it when the user asks to record the session or its lineage, or when a codelineage hook asks for an update.
+allowed-tools: Bash(node "${CLAUDE_PLUGIN_ROOT}/dist/cli.js" *) Edit(/${CLAUDE_PROJECT_DIR}/.codelineage/inbox/**)
+---
+
+# Record this session's lineage
+
+This is the current record for this session (the output of `codelineage session show`):
+
+!`node "${CLAUDE_PLUGIN_ROOT}/dist/cli.js" session show "${CLAUDE_SESSION_ID}" -C "${CLAUDE_PROJECT_DIR}"`
+
+## First, check the record
+
+- If `initialized` is `false`, reply with exactly this line and stop:
+ "codelineage is not set up in this project yet; run `npx codelineage init` here first."
+- If `sessionError` is set, tell the user the session record is unreadable and
+ quote the error. Then stop. Never write over it.
+- If nothing meaningful happened since the record was last updated, reply
+ "Lineage is up to date." and stop.
+
+## Then send only what is new or changed
+
+Build one JSON object:
+
+- `sessionId`: always `"${CLAUDE_SESSION_ID}"`.
+- `title`: a few words naming what this session is about. Send it on the first
+ write, or when the session's focus changed.
+- `epoch`: the `id` of the epoch (feature or epic) from `epochs` that this work
+ belongs to. If none fits and the work is a distinct feature, first run
+ `node "${CLAUDE_PLUGIN_ROOT}/dist/cli.js" epoch add <id> "<title>" -C "<dir>"`
+ with a short lowercase id. Leave it out when unsure.
+- `status`: replaces the stored status, so send all four fields every time:
+ - `goal`: one sentence.
+ - `done`: short items finished in this session so far.
+ - `pending`: `{ "text": "…", "needsUser": true }` for anything waiting on the
+ user, and `needsUser: false` for work that is simply not done yet.
+ - `next`: the next concrete step.
+- `nodes`: only new nodes, or existing ones whose title, summary or reason
+ changed. Nodes you leave out are kept, and so are fields you leave out.
+ - `id`: a short, stable slug. Reuse an existing id to change that node.
+ - `kind`: `phase` (a stretch of work), `step` (a concrete action within a
+ phase), `decision` (a choice that was made, with the reason in `why`) or
+ `question` (an open question).
+ - `parent`: the id of the phase the node belongs to, or `null` for a phase.
+ - `title`: up to about ten words. `summary` and `why`: one or two sentences.
+
+Write titles and text in the conversation's language when `language` is `"auto"`,
+and in that language otherwise. JSON keys stay in English.
+
+Record decisions and their reasons, not raw content. Never include secrets,
+tokens, passwords, credentials, personal data, file contents or command output.
+
+## Write it in two steps
+
+1. Use the Write tool to save the JSON object to the `inbox` path from the record.
+ Do not pass JSON through the shell: heredocs and `echo` with JSON are blocked.
+2. Run exactly this command:
+
+```bash
+node "${CLAUDE_PLUGIN_ROOT}/dist/cli.js" session write -C "<dir from the record>" --file "<inbox path>" --consume
+```
+
+If it fails, fix the JSON file according to the error and run the command again.
+Then reply with one short line, for example "Lineage updated (3 nodes)". Do not
+repeat the JSON.
diff --git a/packages/cli/src/commands/session.ts b/packages/cli/src/commands/session.ts
index 7f57e96..9756dc4 100644
--- a/packages/cli/src/commands/session.ts
+++ b/packages/cli/src/commands/session.ts
@@ -1,10 +1,12 @@
-import { readFile } from "node:fs/promises";
+import { readFile, rm } from "node:fs/promises";
import { resolve } from "node:path";
import { CliError, type Io } from "../io.js";
import { redactDeep } from "../redact.js";
+import { Slug } from "../schema/common.js";
import { mergeSession } from "../schema/merge.js";
import { SessionInput } from "../schema/session.js";
-import { loadProject, updateSession } from "../store/stores.js";
+import { projectPaths } from "../store/paths.js";
+import { loadConfig, loadProject, loadSession, updateSession } from "../store/stores.js";
import { buildProject } from "./build.js";
export async function readStdin(stream: NodeJS.ReadableStream = process.stdin): Promise<string> {
@@ -17,6 +19,8 @@ export interface SessionWriteOptions {
dir: string;
/** Read JSON from this file instead of stdin. */
file?: string;
+ /** Delete `file` once the record is saved; a failed write keeps it for a retry. */
+ consume?: boolean;
}
/**
@@ -64,6 +68,7 @@ export async function sessionWrite(
return merged.session;
});
for (const w of warnings) io.warn(w);
+ if (opts.file && opts.consume) await rm(opts.file, { force: true });
io.out(`Saved session ${saved.sessionId} (${saved.nodes.length} nodes)`);
// Keep the map fresh without making a failed render fail the write.
@@ -73,3 +78,46 @@ export async function sessionWrite(
io.warn(`could not build lineage.html: ${(err as Error).message}`);
}
}
+
+/**
+ * What the skill injects before the agent updates its record: the project's
+ * epochs, the summary language and a compact view of this session (node ids,
+ * parents, kinds and titles, without summaries, which merging keeps anyway).
+ * Always exits 0 for an uninitialized project or an unreadable record, because a
+ * failing injected command aborts the whole skill; the JSON says what is wrong.
+ */
+export async function sessionShow(dir: string, sessionId: string, io: Io): Promise<void> {
+ if (!Slug.safeParse(sessionId).success) throw new CliError(`invalid session id: ${sessionId}`);
+ const root = resolve(dir);
+ const project = await loadProject(root);
+ if (!project.found || !project.ok) {
+ const error = project.found && !project.ok ? project.error : undefined;
+ io.out(JSON.stringify({ initialized: false, dir: root, ...(error ? { error } : {}) }));
+ return;
+ }
+
+ const config = await loadConfig(io.env);
+ const loaded = await loadSession(root, sessionId);
+ const view: Record<string, unknown> = {
+ initialized: true,
+ dir: root,
+ project: project.data.name,
+ language: config.language,
+ epochs: project.data.epochs.map(({ id, title }) => ({ id, title })),
+ session: null,
+ };
+ if (loaded.found && loaded.ok) {
+ const { title, epoch, status, nodes } = loaded.data;
+ view.session = {
+ sessionId,
+ title,
+ epoch,
+ status,
+ nodes: nodes.map(({ id, parent, kind, title }) => ({ id, parent, kind, title })),
+ };
+ } else if (loaded.found) {
+ view.sessionError = loaded.error;
+ }
+ view.inbox = projectPaths(root).inbox(sessionId);
+ io.out(JSON.stringify(view, null, 2));
+}
diff --git a/packages/cli/src/git.ts b/packages/cli/src/git.ts
index b350eed..cabd72f 100644
--- a/packages/cli/src/git.ts
+++ b/packages/cli/src/git.ts
@@ -25,6 +25,7 @@ const ALWAYS = [
"/.codelineage/state/",
"/.codelineage/snapshots/",
"/.codelineage/locks/",
+ "/.codelineage/inbox/",
"/.codelineage/lineage.html",
];
diff --git a/packages/cli/src/program.ts b/packages/cli/src/program.ts
index 441b0f6..13dbdd3 100644
--- a/packages/cli/src/program.ts
+++ b/packages/cli/src/program.ts
@@ -5,7 +5,7 @@ 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 { sessionWrite } from "./commands/session.js";
+import { sessionShow, sessionWrite } from "./commands/session.js";
import { CliError, type Io, processIo } from "./io.js";
export type IoFactory = (interactive: boolean) => Io;
@@ -124,7 +124,20 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =
.description("merge session JSON from stdin into .codelineage/sessions/")
.option("-C, --dir <dir>", "project directory", ".")
.option("-f, --file <file>", "read JSON from a file instead of stdin")
- .action(run(async (opts: { dir: string; file?: string }) => sessionWrite(opts, makeIo(false))));
+ .option("--consume", "delete the file once the record is saved")
+ .action(
+ run(async (opts: { dir: string; file?: string; consume?: boolean }) =>
+ sessionWrite(opts, makeIo(false)),
+ ),
+ );
+ session
+ .command("show")
+ .description("print the compact record the agent skill updates, as JSON")
+ .argument("<id>", "session id")
+ .option("-C, --dir <dir>", "project directory", ".")
+ .action(
+ run(async (id: string, opts: { dir: string }) => sessionShow(opts.dir, id, makeIo(false))),
+ );
return program;
}
diff --git a/packages/cli/src/store/paths.ts b/packages/cli/src/store/paths.ts
index 5528b86..64b7e7e 100644
--- a/packages/cli/src/store/paths.ts
+++ b/packages/cli/src/store/paths.ts
@@ -13,6 +13,8 @@ export function projectPaths(root: string) {
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`),
lock: (name: string) => join(base, "locks", `${name}.lock`),
html: join(base, "lineage.html"),
};
diff --git a/packages/cli/test/init.test.ts b/packages/cli/test/init.test.ts
index 5c56797..72e6db8 100644
--- a/packages/cli/test/init.test.ts
+++ b/packages/cli/test/init.test.ts
@@ -143,7 +143,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(4);
+ expect(await ensureGitignore(root, "commit")).toHaveLength(5);
expect(await ensureGitignore(root, "commit")).toEqual([]);
expect(await ensureGitignore(root, "ignore")).toEqual(["/.codelineage/"]);
const text = await readText(gi);
diff --git a/packages/cli/test/plugin-manifest.test.ts b/packages/cli/test/plugin-manifest.test.ts
index 3039d98..3cffabb 100644
--- a/packages/cli/test/plugin-manifest.test.ts
+++ b/packages/cli/test/plugin-manifest.test.ts
@@ -11,7 +11,7 @@ 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"]));
+ expect(pkg.files).toEqual(expect.arrayContaining(["dist", ".claude-plugin", "skills"]));
});
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.ts
index 946d46f..b88c599 100644
--- a/packages/cli/test/program-commands.test.ts
+++ b/packages/cli/test/program-commands.test.ts
@@ -80,6 +80,12 @@ describe("commands through the CLI", () => {
expect(io.lines.at(-1)).toBe("Saved session s1 (0 nodes)");
});
+ it("runs session show for the skill", async () => {
+ await cli("init", root, "--yes", "--retention", "keep");
+ await cli("session", "show", "s1", "-C", root);
+ expect(JSON.parse(io.lines.at(-1) ?? "")).toMatchObject({ initialized: true, session: null });
+ });
+
it("builds the map through the CLI", async () => {
await cli("init", root, "--yes", "--retention", "keep");
await cli("build", root);
diff --git a/packages/cli/test/session.test.ts b/packages/cli/test/session.test.ts
index 5f41fc8..0c783dd 100644
--- a/packages/cli/test/session.test.ts
+++ b/packages/cli/test/session.test.ts
@@ -1,10 +1,11 @@
+import { existsSync } from "node:fs";
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Readable } from "node:stream";
import { beforeEach, describe, expect, it } from "vitest";
import { epochAdd } from "../src/commands/epoch.js";
import { init } from "../src/commands/init.js";
-import { readStdin, sessionWrite } from "../src/commands/session.js";
+import { readStdin, sessionShow, sessionWrite } from "../src/commands/session.js";
import { redactDeep, redactText } from "../src/redact.js";
import { loadSession } from "../src/store/stores.js";
import { envFor, type FakeIo, fakeIo, tempDir } from "./helpers.js";
@@ -126,3 +127,85 @@ describe("session write", () => {
expect(await readStdin(Readable.from([Buffer.from('{"a":'), "1}"]))).toBe('{"a":1}');
});
});
+
+describe("session show", () => {
+ let dir: string;
+ let root: string;
+ let io: FakeIo;
+ const shown = () => JSON.parse(io.lines.at(-1) ?? "") as Record<string, unknown>;
+
+ beforeEach(async () => {
+ dir = await tempDir();
+ root = join(dir, "proj");
+ await mkdir(root);
+ io = fakeIo(envFor(dir));
+ });
+
+ it("reports an uninitialized project without failing", async () => {
+ await sessionShow(root, "s1", io);
+ expect(shown()).toEqual({ initialized: false, dir: root });
+ });
+
+ it("reports a corrupt project.json without failing", async () => {
+ await mkdir(join(root, ".codelineage"));
+ await writeFile(join(root, ".codelineage", "project.json"), "{nope");
+ await sessionShow(root, "s1", io);
+ expect(shown()).toMatchObject({ initialized: false, error: expect.stringMatching(/JSON/) });
+ });
+
+ it("shows epochs, language and a compact record without summaries", async () => {
+ await init(root, { name: "p", retention: "keep", language: "tr" }, fakeIo(envFor(dir)));
+ await epochAdd(root, "e2e", "E2E", fakeIo(envFor(dir)));
+ await sessionShow(root, "s1", io);
+ expect(shown()).toEqual({
+ initialized: true,
+ dir: root,
+ project: "p",
+ language: "tr",
+ epochs: [{ id: "e2e", title: "E2E" }],
+ session: null,
+ inbox: join(root, ".codelineage", "inbox", "s1.json"),
+ });
+
+ await sessionWrite({ dir: root }, fakeIo(envFor(dir)), async () =>
+ JSON.stringify({
+ sessionId: "s1",
+ title: "t",
+ epoch: "e2e",
+ status: { goal: "g" },
+ nodes: [{ id: "a", kind: "phase", title: "A", summary: "long text", why: "because" }],
+ }),
+ );
+ await sessionShow(root, "s1", io);
+ expect(shown().session).toEqual({
+ sessionId: "s1",
+ title: "t",
+ epoch: "e2e",
+ status: { goal: "g", done: [], pending: [], next: "" },
+ nodes: [{ id: "a", parent: null, kind: "phase", title: "A" }],
+ });
+ });
+
+ 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");
+ await sessionShow(root, "s1", io);
+ expect(shown()).toMatchObject({ session: null, sessionError: expect.stringMatching(/JSON/) });
+ });
+
+ it("consumes the inbox file after a successful write and keeps it after a failed one", async () => {
+ await init(root, { name: "p", retention: "keep", language: "auto" }, fakeIo(envFor(dir)));
+ const file = join(root, ".codelineage", "inbox", "s1.json");
+ await mkdir(join(root, ".codelineage", "inbox"));
+ await writeFile(file, "{nope");
+ await expect(sessionWrite({ dir: root, file, consume: true }, io)).rejects.toThrow(/JSON/);
+ expect(existsSync(file)).toBe(true);
+ await writeFile(file, '{"sessionId":"s1"}');
+ await sessionWrite({ dir: root, file, consume: true }, io);
+ expect(existsSync(file)).toBe(false);
+ });
+
+ it("rejects an id that is not a slug", async () => {
+ await expect(sessionShow(root, "../x", io)).rejects.toThrow(/invalid session id/);
+ });
+});
diff --git a/specs/codelineage-mvp.md b/specs/codelineage-mvp.md
index a11414a..57de25a 100644
--- a/specs/codelineage-mvp.md
+++ b/specs/codelineage-mvp.md
@@ -81,10 +81,12 @@ Session file (schema v1, sketch):
The agent picks an existing epoch or adds one through the CLI (`codelineage epoch add`),
which does a locked, atomic write.
-**Writes go through the CLI.** The agent never writes JSON files directly. It pipes
-its JSON to `codelineage session write`, which validates against the schema, runs the
-redaction pass, merges with the existing file and writes atomically, then runs
-`build` quietly.
+**Writes go through the CLI.** The agent never writes session files directly. It
+saves its JSON to `.codelineage/inbox/<session-id>.json` with the Write tool and runs
+`codelineage session write --file <inbox> --consume`, which validates against the
+schema, runs the redaction pass, merges with the existing file and writes atomically,
+deletes the inbox file, then runs `build` quietly. JSON is not piped through the shell,
+because Claude Code's command checks block heredocs that contain JSON.
**Concurrency:**
- One file per session, so parallel agents in the same project never write the same
@@ -110,9 +112,14 @@ npm-sourced plugin without one resolves to version `unknown` and never updates.
Behavior verified against the Claude Code hooks docs (2026-10-21):
- **Skill `/codelineage:lineage`:** writes or updates this session's record. The skill
- gets its session ID from `${CLAUDE_SESSION_ID}` and injects the current session file
- with `` !`command` ``, so the agent updates the record instead of rewriting it.
- The user can call it at any time.
+ gets its session ID from `${CLAUDE_SESSION_ID}` and injects a compact view of the
+ record with `` !`codelineage session show` ``, so the agent sends only what is new
+ or changed instead of rewriting it. The injected command never fails (an
+ uninitialized project is reported in its JSON), because a failing injection aborts
+ the whole skill. `allowed-tools` pre-approves exactly the CLI and writes under
+ `.codelineage/inbox/`, so the skill runs without prompts. The user can call it at
+ any time. Verified end to end with Claude Code 2.1.300: first write, "up to date"
+ with no change, and the hint in an uninitialized directory.
- **Stop hook (the main path):** counts turns per session in `state/`. Every N turns
(`updateEveryTurns`, default 5) it asks the agent to run the skill, using
`hookSpecificOutput.additionalContext` (shown as "Stop hook feedback", not as an
@@ -167,7 +174,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) |
| `codelineage epoch add <id> <title>` | Adds an epoch (locked write) |
| `codelineage config get/set <key> [value]` | Reads or changes settings |
-| `codelineage session write` | Reads session JSON from stdin, validates, redacts, merges and writes it under the session lock, then builds. Used by the skill. |
+| `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`. |
| `codelineage backfill <session-id> --tail` | Summarizes only the unrecorded turns of one session. Started by the SessionEnd hook. |