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(schema): add v1 schemas, versioned parsing and session merge
Eren4cb0da5c78d7
diff --git a/package-lock.json b/package-lock.jsonindex 48e87ae..c46d6cf 100644--- a/package-lock.json+++ b/package-lock.json@@ -3276,12 +3276,22 @@"node": ">=20.11"}},+ "node_modules/zod": {+ "version": "4.6.7",+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.7.tgz",+ "integrity": "sha512-g8W2D2kU6a8untc053fX1uVBKzM7yqAxW/3zwk83+6RyF2+SKOuV+c0wBDhUwzV1PaGapmZH+rmcUzPf+3CGwg==",+ "license": "MIT",+ "funding": {+ "url": "https://github.com/sponsors/colinhacks"+ }+ },"packages/cli": {"name": "codelineage","version": "0.1.0","license": "MIT","dependencies": {- "commander": "^15.0.0"+ "commander": "^15.0.0",+ "zod": "^4.6.7"},"bin": {"codelineage": "dist/cli.js"diff --git a/packages/cli/package.json b/packages/cli/package.jsonindex 2527c36..d36fa56 100644--- a/packages/cli/package.json+++ b/packages/cli/package.json@@ -20,6 +20,7 @@"tsup": "^9.0.0"},"dependencies": {- "commander": "^15.0.0"+ "commander": "^15.0.0",+ "zod": "^4.6.7"}}diff --git a/packages/cli/src/schema/common.ts b/packages/cli/src/schema/common.tsnew file mode 100644index 0000000..9cd3587--- /dev/null+++ b/packages/cli/src/schema/common.ts@@ -0,0 +1,8 @@+import { z } from "zod";++/** Ids end up in file names and HTML, so keep them to a safe slug. */+export const Slug = z+ .string()+ .regex(/^[A-Za-z0-9][A-Za-z0-9_.-]{0,127}$/, "must be a slug: letters, digits, _ . -");++export const IsoDate = z.iso.datetime({ offset: true });diff --git a/packages/cli/src/schema/config.ts b/packages/cli/src/schema/config.tsnew file mode 100644index 0000000..6b40e99--- /dev/null+++ b/packages/cli/src/schema/config.ts@@ -0,0 +1,29 @@+import { z } from "zod";+import { IsoDate } from "./common.js";++export const CONFIG_SCHEMA = 1;++export const Config = z.object({+ schema: z.literal(CONFIG_SCHEMA),+ /** "auto" = the conversation's language, otherwise a fixed language name or code. */+ language: z.string().min(1).max(32).default("auto"),+ updateEveryTurns: z.int().min(1).max(100).default(5),+ sessionEndCatchUp: z.boolean().default(true),+ /** 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"]),+});++export const RegistryEntry = z.object({+ path: z.string().min(1),+ name: z.string().min(1).max(200),+ addedAt: IsoDate,+});++export const Registry = z.object({+ schema: z.literal(CONFIG_SCHEMA),+ projects: z.array(RegistryEntry).default([]),+});++export type Config = z.infer<typeof Config>;+export type Registry = z.infer<typeof Registry>;diff --git a/packages/cli/src/schema/merge.ts b/packages/cli/src/schema/merge.tsnew file mode 100644index 0000000..a385666--- /dev/null+++ b/packages/cli/src/schema/merge.ts@@ -0,0 +1,79 @@+import { type LineageNode, SESSION_SCHEMA, type Session, type SessionInput } from "./session.js";++export interface MergeResult {+ session: Session;+ warnings: string[];+}++/**+ * Merges agent input into the stored session. Nodes are upserted by id and never+ * removed; status is replaced when sent; other fields change only when sent.+ */+export function mergeSession(+ existing: Session | undefined,+ input: SessionInput,+ now: string,+): MergeResult {+ if (existing && existing.sessionId !== input.sessionId) {+ throw new Error(`session id mismatch: ${existing.sessionId} vs ${input.sessionId}`);+ }+ const base: Session = existing ?? {+ schema: SESSION_SCHEMA,+ sessionId: input.sessionId,+ agent: "claude-code",+ title: "",+ epoch: null,+ startedAt: now,+ updatedAt: now,+ status: { goal: "", done: [], pending: [], next: "" },+ nodes: [],+ };++ const nodes = new Map<string, LineageNode>(base.nodes.map((n) => [n.id, n]));+ for (const { parent, ...n } of input.nodes ?? []) {+ const prev = nodes.get(n.id);+ nodes.set(n.id, {+ ...prev,+ ...n,+ parent: parent === undefined ? (prev?.parent ?? null) : parent,+ });+ }++ const merged: Session = {+ ...base,+ agent: input.agent ?? base.agent,+ title: input.title ?? base.title,+ epoch: input.epoch === undefined ? base.epoch : input.epoch,+ status: input.status ?? base.status,+ nodes: [...nodes.values()],+ updatedAt: now,+ };+ const warnings = repairTree(merged.nodes);+ return { session: merged, warnings };+}++/** Re-roots nodes whose parent is missing or that sit on a cycle. Mutates in place. */+export function repairTree(nodes: LineageNode[]): string[] {+ const warnings: string[] = [];+ const byId = new Map(nodes.map((n) => [n.id, n]));+ for (const n of nodes) {+ if (n.parent !== null && !byId.has(n.parent)) {+ warnings.push(`node ${n.id}: parent ${n.parent} not found, moved to root`);+ n.parent = null;+ }+ }+ for (const n of nodes) {+ const seen = new Set<string>([n.id]);+ let cur = n.parent;+ while (cur !== null) {+ if (seen.has(cur)) {+ warnings.push(`node ${n.id}: parent cycle, moved to root`);+ n.parent = null;+ break;+ }+ seen.add(cur);+ cur = byId.get(cur)?.parent ?? null;+ }+ }+ return warnings;+}diff --git a/packages/cli/src/schema/project.ts b/packages/cli/src/schema/project.tsnew file mode 100644index 0000000..40a6182--- /dev/null+++ b/packages/cli/src/schema/project.ts@@ -0,0 +1,19 @@+import { z } from "zod";+import { IsoDate, Slug } from "./common.js";++export const PROJECT_SCHEMA = 1;++export const Epoch = z.object({+ id: Slug,+ title: z.string().min(1).max(200),+ createdAt: IsoDate,+});++export const Project = z.object({+ schema: z.literal(PROJECT_SCHEMA),+ name: z.string().min(1).max(200),+ epochs: z.array(Epoch).default([]),+});++export type Epoch = z.infer<typeof Epoch>;+export type Project = z.infer<typeof Project>;diff --git a/packages/cli/src/schema/session.ts b/packages/cli/src/schema/session.tsnew file mode 100644index 0000000..2f285d8--- /dev/null+++ b/packages/cli/src/schema/session.ts@@ -0,0 +1,66 @@+import { z } from "zod";+import { IsoDate, Slug } from "./common.js";++export const SESSION_SCHEMA = 1;++export const NodeKind = z.enum(["phase", "step", "decision", "question"]);++export const LineageNode = z.object({+ id: Slug,+ parent: Slug.nullable().default(null),+ kind: NodeKind,+ title: z.string().min(1).max(200),+ summary: z.string().max(2000).optional(),+ why: z.string().max(2000).optional(),+ at: IsoDate.optional(),+});++export const PendingItem = z.object({+ text: z.string().min(1).max(500),+ needsUser: z.boolean().default(false),+});++export const Status = z.object({+ goal: z.string().max(500).default(""),+ done: z.array(z.string().min(1).max(500)).default([]),+ pending: z.array(PendingItem).default([]),+ next: z.string().max(500).default(""),+});++export const Session = z.object({+ schema: z.literal(SESSION_SCHEMA),+ sessionId: Slug,+ agent: z.string().min(1).max(64).default("claude-code"),+ title: z.string().max(200).default(""),+ epoch: Slug.nullable().default(null),+ startedAt: IsoDate,+ updatedAt: IsoDate,+ status: Status.default({ goal: "", done: [], pending: [], next: "" }),+ nodes: z.array(LineageNode).default([]),+});++/** In input, a missing parent keeps the stored one (null for a new node). */+export const LineageNodeInput = LineageNode.extend({ parent: Slug.nullable().optional() });++/**+ * What the agent sends to `session write`. Everything but the id is optional;+ * the CLI owns `schema`, `startedAt` and `updatedAt`.+ */+export const SessionInput = z.object({+ sessionId: Slug,+ agent: z.string().min(1).max(64).optional(),+ title: z.string().max(200).optional(),+ epoch: Slug.nullable().optional(),+ status: Status.optional(),+ nodes: z.array(LineageNodeInput).optional(),+});++export type LineageNode = z.infer<typeof LineageNode>;+export type Status = z.infer<typeof Status>;+export type Session = z.infer<typeof Session>;+export type SessionInput = z.infer<typeof SessionInput>;++/** JSON Schema of the agent input, embedded in the /lineage skill. */+export function sessionInputJsonSchema(): object {+ return z.toJSONSchema(SessionInput, { io: "input" });+}diff --git a/packages/cli/src/schema/versioned.ts b/packages/cli/src/schema/versioned.tsnew file mode 100644index 0000000..f48c07e--- /dev/null+++ b/packages/cli/src/schema/versioned.ts@@ -0,0 +1,45 @@+import type { z } from "zod";++export type Parsed<T> =+ | { ok: true; data: T; warnings: string[] }+ | { ok: false; error: string; warnings: string[] };++type Migration = (raw: Record<string, unknown>) => Record<string, unknown>;++/**+ * Parses a versioned JSON document. Older versions are migrated step by step;+ * a newer version is parsed best-effort with a warning.+ */+export function parseVersioned<S extends z.ZodType>(+ raw: unknown,+ schema: S,+ current: number,+ migrations: Record<number, Migration> = {},+): Parsed<z.infer<S>> {+ const warnings: string[] = [];+ if (typeof raw !== "object" || raw === null || Array.isArray(raw)) {+ return { ok: false, error: "not a JSON object", warnings };+ }+ let doc = raw as Record<string, unknown>;+ const version = doc.schema;+ if (typeof version !== "number" || !Number.isInteger(version) || version < 1) {+ return { ok: false, error: "missing or invalid schema version", warnings };+ }+ if (version > current) {+ warnings.push(`schema v${version} is newer than supported v${current}; reading best-effort`);+ doc = { ...doc, schema: current };+ }+ for (let v = version; v < current; v++) {+ const step = migrations[v];+ if (!step) return { ok: false, error: `no migration from schema v${v}`, warnings };+ doc = { ...step(doc), schema: v + 1 };+ }+ const result = schema.safeParse(doc);+ if (!result.success) {+ const issues = result.error.issues+ .slice(0, 5)+ .map((i) => `${i.path.join(".") || "(root)"}: ${i.message}`);+ return { ok: false, error: issues.join("; "), warnings };+ }+ return { ok: true, data: result.data, warnings };+}diff --git a/packages/cli/test/schema.test.ts b/packages/cli/test/schema.test.tsnew file mode 100644index 0000000..02fe167--- /dev/null+++ b/packages/cli/test/schema.test.ts@@ -0,0 +1,173 @@+import { describe, expect, it } from "vitest";+import { z } from "zod";+import { Config } from "../src/schema/config.js";+import { mergeSession, repairTree } from "../src/schema/merge.js";+import { Project } from "../src/schema/project.js";+import {+ type LineageNode,+ Session,+ SessionInput,+ sessionInputJsonSchema,+} from "../src/schema/session.js";+import { parseVersioned } from "../src/schema/versioned.js";++const T0 = "2026-10-21T10:00:00.000Z";+const T1 = "2026-10-21T11:00:00.000Z";++const input = (v: unknown) => SessionInput.parse(v);+const node = (id: string, parent: string | null, title = id): LineageNode => ({+ id,+ parent,+ kind: "step",+ title,+});++describe("Session schema", () => {+ it("fills defaults for a minimal session", () => {+ const s = Session.parse({ schema: 1, sessionId: "abc", startedAt: T0, updatedAt: T0 });+ expect(s.agent).toBe("claude-code");+ expect(s.epoch).toBeNull();+ expect(s.status).toEqual({ goal: "", done: [], pending: [], next: "" });+ expect(s.nodes).toEqual([]);+ });++ it("rejects ids that are not safe slugs", () => {+ for (const sessionId of ["../etc", "a/b", "", ".hidden"]) {+ expect(SessionInput.safeParse({ sessionId }).success).toBe(false);+ }+ });++ it("rejects unknown node kinds", () => {+ const r = SessionInput.safeParse({+ sessionId: "a",+ nodes: [{ id: "n1", kind: "rant", title: "x" }],+ });+ expect(r.success).toBe(false);+ });++ it("exports a JSON Schema for the agent input", () => {+ const js = sessionInputJsonSchema() as { required?: string[]; properties?: object };+ expect(js.required).toEqual(["sessionId"]);+ expect(Object.keys(js.properties ?? {})).toContain("nodes");+ });+});++describe("Project and Config schemas", () => {+ it("defaults epochs and settings", () => {+ expect(Project.parse({ schema: 1, name: "p" }).epochs).toEqual([]);+ expect(Config.parse({ schema: 1 })).toMatchObject({+ language: "auto",+ updateEveryTurns: 5,+ sessionEndCatchUp: true,+ gitPolicy: "ignore",+ });+ });+});++describe("parseVersioned", () => {+ it("rejects non-objects and missing versions", () => {+ expect(parseVersioned([], Project, 1)).toMatchObject({ ok: false, error: "not a JSON object" });+ expect(parseVersioned({ name: "p" }, Project, 1)).toMatchObject({ ok: false });+ });++ it("migrates older documents step by step", () => {+ const ProjectV2 = Project.extend({ schema: z.literal(2) });+ const r = parseVersioned({ schema: 1, title: "p" }, ProjectV2, 2, {+ 1: ({ title, ...rest }) => ({ ...rest, name: title }),+ });+ expect(r).toMatchObject({ ok: true, data: { schema: 2, name: "p" } });+ });++ it("fails when a migration step is missing", () => {+ const r = parseVersioned({ schema: 1, name: "p" }, Project, 2);+ expect(r).toMatchObject({ ok: false, error: "no migration from schema v1" });+ });++ it("reads newer documents best-effort with a warning", () => {+ const r = parseVersioned({ schema: 9, name: "p", extra: true }, Project, 1);+ expect(r.ok).toBe(true);+ expect(r.warnings[0]).toMatch(/newer/);+ });++ it("reports schema issues with their path", () => {+ const r = parseVersioned({ schema: 1, name: "" }, Project, 1);+ expect(r).toMatchObject({ ok: false });+ if (!r.ok) expect(r.error).toMatch(/^name:/);+ });+});++describe("mergeSession", () => {+ it("creates a new session owned by the CLI timestamps", () => {+ const { session } = mergeSession(undefined, input({ sessionId: "s1", title: "x" }), T0);+ expect(session).toMatchObject({ schema: 1, startedAt: T0, updatedAt: T0, title: "x" });+ });++ it("upserts nodes by id and never removes them", () => {+ const first = mergeSession(+ undefined,+ input({+ sessionId: "s1",+ nodes: [+ { id: "n1", kind: "phase", title: "a", summary: "keep" },+ { id: "n2", parent: "n1", kind: "step", title: "b" },+ ],+ }),+ T0,+ ).session;+ const { session } = mergeSession(+ first,+ input({+ sessionId: "s1",+ nodes: [+ { id: "n2", kind: "step", title: "b2" },+ { id: "n3", kind: "decision", title: "c", why: "because" },+ ],+ }),+ T1,+ );+ expect(session.nodes.map((n) => n.id)).toEqual(["n1", "n2", "n3"]);+ expect(session.nodes[0]?.summary).toBe("keep");+ expect(session.nodes[1]).toMatchObject({ title: "b2", parent: "n1" });+ expect(session.nodes[2]?.parent).toBeNull();+ expect(session).toMatchObject({ startedAt: T0, updatedAt: T1 });+ });++ it("replaces status when sent and keeps fields that were not sent", () => {+ const first = mergeSession(+ undefined,+ input({ sessionId: "s1", title: "t", epoch: "e2e", status: { goal: "g", done: ["a"] } }),+ T0,+ ).session;+ const kept = mergeSession(first, input({ sessionId: "s1" }), T1).session;+ expect(kept).toMatchObject({ title: "t", epoch: "e2e" });+ expect(kept.status.done).toEqual(["a"]);++ const replaced = mergeSession(+ first,+ input({ sessionId: "s1", epoch: null, status: { goal: "g2" } }),+ T1,+ ).session;+ expect(replaced.epoch).toBeNull();+ expect(replaced.status).toEqual({ goal: "g2", done: [], pending: [], next: "" });+ });++ it("refuses to merge a different session", () => {+ const first = mergeSession(undefined, input({ sessionId: "s1" }), T0).session;+ expect(() => mergeSession(first, input({ sessionId: "s2" }), T1)).toThrow(/mismatch/);+ });+});++describe("repairTree", () => {+ it("re-roots nodes with a missing parent", () => {+ const nodes = [node("a", "ghost")];+ expect(repairTree(nodes)).toEqual(["node a: parent ghost not found, moved to root"]);+ expect(nodes[0]?.parent).toBeNull();+ });++ it("breaks parent cycles", () => {+ const nodes = [node("a", "b"), node("b", "a"), node("c", "a")];+ const warnings = repairTree(nodes);+ expect(warnings).toHaveLength(1);+ expect(nodes.filter((n) => n.parent === null)).toHaveLength(1);+ });+});