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(cli): add build command with embedded lineage template
Eren6ed64ab80b28
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ffbe28e..6144c59 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]### Added- Template workspace (`packages/template`): React 19 + Vite 8 + `vite-plugin-singlefile`, dev fixture and the shared lineage view-model contract (`packages/cli/src/view/model.ts`).+- `codelineage build [dir]`: renders `.codelineage/lineage.html` from `project.json` and `sessions/*.json` (epochs in project order, nested node tree, unassigned sessions grouped), skips unreadable session files with a warning, redacts secrets and embeds the single-file template into the CLI bundle; `session write` rebuilds quietly afterwards.## [0.2.0] - 2026-10-21### Addeddiff --git a/packages/cli/src/commands/build.ts b/packages/cli/src/commands/build.tsnew file mode 100644index 0000000..f673483--- /dev/null+++ b/packages/cli/src/commands/build.ts@@ -0,0 +1,80 @@+import type { Dirent } from "node:fs";+import { readdir } from "node:fs/promises";+import { resolve } from "node:path";+import { CliError, type Io } from "../io.js";+import { redactDeep } from "../redact.js";+import type { Session } from "../schema/session.js";+import { atomicWrite } from "../store/fs.js";+import { projectPaths } from "../store/paths.js";+import { loadProject, loadSession } from "../store/stores.js";+import { buildViewModel, embedViewModel } from "../view/lineage.js";+import type { LineageViewModel } from "../view/model.js";+import { TEMPLATE_HTML } from "../view/template.js";++export interface BuildOptions {+ dir: string;+ io: Io;+ /** Replaces the bundled template; tests inject a minimal page. */+ templateHtml?: string;+ /** `session write` rebuilds without printing a success line. */+ quiet?: boolean;+}++async function listSessions(dir: string): Promise<string[]> {+ let entries: Dirent[];+ try {+ entries = await readdir(dir, { withFileTypes: true });+ } catch (err) {+ if ((err as NodeJS.ErrnoException).code === "ENOENT") return [];+ throw err;+ }+ return entries+ .filter((entry) => entry.isFile() && entry.name.endsWith(".json"))+ .map((entry) => entry.name.slice(0, -".json".length))+ .sort();+}++async function loadAllSessions(root: string, io: Io): Promise<Session[]> {+ const sessions: Session[] = [];+ for (const id of await listSessions(projectPaths(root).sessions)) {+ const loaded = await loadSession(root, id);+ if (!loaded.found) continue;+ if (!loaded.ok) {+ io.warn(`skipping session ${id}: ${loaded.error}`);+ continue;+ }+ for (const warning of loaded.warnings) io.warn(`session ${id}: ${warning}`);+ sessions.push(loaded.data);+ }+ return sessions;+}++/**+ * Rebuilds `.codelineage/lineage.html` from `project.json` and every session file.+ * One unreadable session is a warning, never a failed build.+ */+export async function buildProject(opts: BuildOptions): Promise<LineageViewModel> {+ const { io } = opts;+ const root = resolve(opts.dir);+ const project = await loadProject(root);+ if (!project.found)+ throw new CliError(`${root} is not initialized; run \`codelineage init\` first`);+ if (!project.ok) throw new CliError(project.error);+ for (const warning of project.warnings) io.warn(warning);++ const paths = projectPaths(root);+ const model = buildViewModel({+ project: project.data,+ sessions: await loadAllSessions(root, io),+ path: root,+ generatedAt: io.now(),+ });+ // The skill already avoids secrets; this is the safety net before rendering.+ const redacted = redactDeep(model);+ if (redacted.count > 0) io.warn(`redacted ${redacted.count} secret-looking value(s) in the map`);++ const template = opts.templateHtml ?? TEMPLATE_HTML;+ await atomicWrite(paths.html, embedViewModel(template, redacted.value));+ if (!opts.quiet) io.out(`Wrote ${paths.html}`);+ return redacted.value;+}diff --git a/packages/cli/src/commands/session.ts b/packages/cli/src/commands/session.tsindex 90180e0..7f57e96 100644--- a/packages/cli/src/commands/session.ts+++ b/packages/cli/src/commands/session.ts@@ -5,6 +5,7 @@ import { redactDeep } from "../redact.js";import { mergeSession } from "../schema/merge.js";import { SessionInput } from "../schema/session.js";import { loadProject, updateSession } from "../store/stores.js";+import { buildProject } from "./build.js";export async function readStdin(stream: NodeJS.ReadableStream = process.stdin): Promise<string> {const chunks: Buffer[] = [];@@ -64,4 +65,11 @@ export async function sessionWrite(});for (const w of warnings) io.warn(w);io.out(`Saved session ${saved.sessionId} (${saved.nodes.length} nodes)`);++ // Keep the map fresh without making a failed render fail the write.+ try {+ await buildProject({ dir: root, io, quiet: true });+ } catch (err) {+ io.warn(`could not build lineage.html: ${(err as Error).message}`);+ }}diff --git a/packages/cli/src/program.ts b/packages/cli/src/program.tsindex c2236d8..6be505b 100644--- a/packages/cli/src/program.ts+++ b/packages/cli/src/program.ts@@ -1,5 +1,6 @@import { Command, InvalidArgumentError, Option } from "commander";import pkg from "../package.json" with { type: "json" };+import { buildProject } from "./commands/build.js";import { configGet, configSet } from "./commands/config.js";import { epochAdd } from "./commands/epoch.js";import { type InitOptions, init } from "./commands/init.js";@@ -51,6 +52,16 @@ export function createProgram(makeIo: IoFactory = processIo): Command {}),);+ program+ .command("build")+ .description("regenerate .codelineage/lineage.html")+ .argument("[dir]", "project directory", ".")+ .action(+ run(async (dir: string) => {+ await buildProject({ dir, io: makeIo(false) });+ }),+ );+const config = program.command("config").description("read or change global settings");config.command("get")diff --git a/packages/cli/src/view/html.d.ts b/packages/cli/src/view/html.d.tsnew file mode 100644index 0000000..f2518e9--- /dev/null+++ b/packages/cli/src/view/html.d.ts@@ -0,0 +1,5 @@+/** `.html` imports are bundled as a string by tsup (`loader: { ".html": "text" }`). */+declare module "*.html" {+ const html: string;+ export default html;+}diff --git a/packages/cli/src/view/lineage.ts b/packages/cli/src/view/lineage.tsnew file mode 100644index 0000000..f2174be--- /dev/null+++ b/packages/cli/src/view/lineage.ts@@ -0,0 +1,156 @@+import type { Project } from "../schema/project.js";+import type { LineageNode, Session } from "../schema/session.js";+import {+ DATA_ELEMENT_ID,+ type LineageViewModel,+ type StatusCard,+ VIEW_SCHEMA,+ type ViewEpoch,+ type ViewNode,+ type ViewSession,+} from "./model.js";++/**+ * Turns a session's flat node list into the nested tree the graph draws. Order is+ * preserved. A missing parent, a self-reference or a cycle becomes a root, so no+ * recorded node is ever dropped.+ */+export function buildNodeTree(nodes: LineageNode[]): ViewNode[] {+ const byId = new Map(nodes.map((node) => [node.id, node]));+ const childrenOf = new Map<string, LineageNode[]>();+ const roots: LineageNode[] = [];+ for (const node of nodes) {+ const parent = node.parent === null ? undefined : byId.get(node.parent);+ if (parent && parent.id !== node.id) {+ const list = childrenOf.get(parent.id) ?? [];+ list.push(node);+ childrenOf.set(parent.id, list);+ } else {+ roots.push(node);+ }+ }++ const visited = new Set<string>();+ const build = (node: LineageNode): ViewNode => {+ visited.add(node.id);+ const children = (childrenOf.get(node.id) ?? [])+ .filter((child) => !visited.has(child.id))+ .map(build);+ return {+ id: node.id,+ kind: node.kind,+ title: node.title,+ ...(node.summary === undefined ? {} : { summary: node.summary }),+ ...(node.why === undefined ? {} : { why: node.why }),+ ...(node.at === undefined ? {} : { at: node.at }),+ children,+ };+ };++ const tree = roots.filter((root) => !visited.has(root.id)).map(build);+ // A pure cycle has no root, so break it at the first node not yet emitted.+ for (const node of nodes) if (!visited.has(node.id)) tree.push(build(node));+ return tree;+}++/** The status card comes from the most recently updated session. */+function statusCard(sessions: Session[]): StatusCard {+ let latest: Session | undefined;+ for (const session of sessions) {+ if (!latest || session.updatedAt > latest.updatedAt) latest = session;+ }+ return {+ goal: latest?.status.goal ?? "",+ done: latest?.status.done ?? [],+ pending: latest?.status.pending ?? [],+ next: latest?.status.next ?? "",+ lastActivity: latest?.updatedAt ?? null,+ };+}++function toViewSession(session: Session): ViewSession {+ return {+ sessionId: session.sessionId,+ agent: session.agent,+ title: session.title,+ epoch: session.epoch,+ startedAt: session.startedAt,+ updatedAt: session.updatedAt,+ status: session.status,+ nodes: buildNodeTree(session.nodes),+ // Story 2.5 adds the transcript lookup; a record without one still renders.+ transcriptAvailable: true,+ };+}++/** Sessions in chronological order; the id keeps ties deterministic. */+function byStartedAt(a: Session, b: Session): number {+ return a.startedAt.localeCompare(b.startedAt) || a.sessionId.localeCompare(b.sessionId);+}++export interface ViewModelInput {+ project: Project;+ sessions: Session[];+ /** Absolute project path shown on the page. */+ path: string;+ generatedAt: string;+}++/**+ * Builds the page model: epochs in project order, sessions by `startedAt`, and+ * every session whose epoch is null or unknown in the `unassigned` group.+ */+export function buildViewModel(input: ViewModelInput): LineageViewModel {+ const buckets = new Map<string, ViewSession[]>(+ input.project.epochs.map((epoch) => [epoch.id, []]),+ );+ const unassigned: ViewSession[] = [];+ const sessions = [...input.sessions].sort(byStartedAt);++ for (const session of sessions) {+ const view = toViewSession(session);+ const bucket = session.epoch === null ? undefined : buckets.get(session.epoch);+ (bucket ?? unassigned).push(view);+ }++ const epochs: ViewEpoch[] = input.project.epochs.map((epoch) => ({+ id: epoch.id,+ title: epoch.title,+ createdAt: epoch.createdAt,+ sessions: buckets.get(epoch.id) ?? [],+ }));++ return {+ kind: "lineage",+ schema: VIEW_SCHEMA,+ project: { name: input.project.name, path: input.path, generatedAt: input.generatedAt },+ status: statusCard(sessions),+ epochs,+ unassigned,+ };+}++const EMPTY_DATA_ELEMENT = `<script id="${DATA_ELEMENT_ID}" type="application/json"></script>`;++/**+ * Escapes `<`, `>`, `&`, U+2028 and U+2029 inside the serialized JSON. The+ * escapes stay valid JSON (`<`), so a `</script>` in the data cannot end the+ * element, and the template can stay one file.+ */+export function escapeForScript(json: string): string {+ return json.replace(+ /[<>&\u2028\u2029]/g,+ (char) => `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}`,+ );+}++/** Fills the template's empty data element with the serialized model. */+export function embedViewModel(template: string, model: LineageViewModel): string {+ if (!template.includes(EMPTY_DATA_ELEMENT)) {+ throw new Error(`the template has no empty <script id="${DATA_ELEMENT_ID}"> element`);+ }+ const data = `<script id="${DATA_ELEMENT_ID}" type="application/json">${escapeForScript(+ JSON.stringify(model),+ )}</script>`;+ return template.replace(EMPTY_DATA_ELEMENT, data);+}diff --git a/packages/cli/src/view/template.ts b/packages/cli/src/view/template.tsnew file mode 100644index 0000000..e492008--- /dev/null+++ b/packages/cli/src/view/template.ts@@ -0,0 +1,8 @@+/**+ * The built template is embedded into the CLI bundle as text by tsup's loader+ * (see `tsup.config.ts`), so `codelineage build` needs no asset files next to+ * `dist/cli.js`.+ */+import templateHtml from "../../../template/dist/index.html";++export const TEMPLATE_HTML: string = templateHtml;diff --git a/packages/cli/test/build.test.ts b/packages/cli/test/build.test.tsnew file mode 100644index 0000000..6775554--- /dev/null+++ b/packages/cli/test/build.test.ts@@ -0,0 +1,342 @@+import { existsSync } from "node:fs";+import { mkdir, readFile, rm, writeFile } from "node:fs/promises";+import { join } from "node:path";+import { beforeEach, describe, expect, it } from "vitest";+import { buildProject } from "../src/commands/build.js";+import { epochAdd } from "../src/commands/epoch.js";+import { init } from "../src/commands/init.js";+import { sessionWrite } from "../src/commands/session.js";+import type { LineageNode, Session } from "../src/schema/session.js";+import { projectPaths } from "../src/store/paths.js";+import { buildNodeTree, buildViewModel, embedViewModel } from "../src/view/lineage.js";+import { DATA_ELEMENT_ID } from "../src/view/model.js";+import { envFor, type FakeIo, fakeIo, T0, tempDir } from "./helpers.js";++const TEMPLATE = `<!doctype html><html><body><div id="root"></div>+ <script id="${DATA_ELEMENT_ID}" type="application/json"></script></body></html>`;++const DATA_PREFIX = `<script id="${DATA_ELEMENT_ID}" type="application/json">`;++function embedded(html: string): unknown {+ const start = html.indexOf(DATA_PREFIX);+ expect(start).toBeGreaterThanOrEqual(0);+ const end = html.indexOf("</script>", start);+ return JSON.parse(html.slice(start + DATA_PREFIX.length, end));+}++function node(+ id: string,+ kind: LineageNode["kind"],+ title: string,+ parent: string | null = null,+ extra: Partial<LineageNode> = {},+): LineageNode {+ return { id, parent, kind, title, ...extra };+}++function session(over: Partial<Session> & { sessionId: string }): Session {+ return {+ schema: 1,+ agent: "claude-code",+ title: "",+ epoch: null,+ startedAt: T0,+ updatedAt: T0,+ status: { goal: "", done: [], pending: [], next: "" },+ nodes: [],+ ...over,+ };+}++describe("buildNodeTree", () => {+ it("nests children in order and keeps optional fields only when present", () => {+ const tree = buildNodeTree([+ node("a", "phase", "A", null, { summary: "phase one", at: T0 }),+ node("b", "step", "B", "a"),+ node("c", "decision", "C", "b", { why: "because" }),+ node("d", "question", "D", "a"),+ ]);+ expect(tree).toEqual([+ {+ id: "a",+ kind: "phase",+ title: "A",+ summary: "phase one",+ at: T0,+ children: [+ {+ id: "b",+ kind: "step",+ title: "B",+ children: [{ id: "c", kind: "decision", title: "C", why: "because", children: [] }],+ },+ { id: "d", kind: "question", title: "D", children: [] },+ ],+ },+ ]);+ });++ it("re-roots missing parents, self references and cycles without losing nodes", () => {+ const tree = buildNodeTree([+ node("a", "phase", "A", "ghost"),+ node("b", "step", "B", "b"),+ node("x", "decision", "X", "y"),+ node("y", "step", "Y", "x"),+ ]);+ expect(tree.map((n) => n.id)).toEqual(["a", "b", "x"]);+ expect(tree[2]).toMatchObject({ id: "x", children: [{ id: "y", children: [] }] });+ });+});++describe("buildViewModel", () => {+ it("orders epochs by project order, sessions by startedAt and groups unknown epochs", () => {+ const sessions = [+ session({+ sessionId: "late",+ epoch: "e1",+ startedAt: "2026-01-02T00:00:00.000Z",+ updatedAt: "2026-01-02T00:00:00.000Z",+ }),+ session({+ sessionId: "early",+ epoch: "e1",+ startedAt: "2026-01-01T00:00:00.000Z",+ updatedAt: "2026-01-05T00:00:00.000Z",+ status: {+ goal: "ship",+ done: ["a"],+ pending: [{ text: "decide", needsUser: true }],+ next: "go",+ },+ }),+ session({+ sessionId: "ghost",+ epoch: "nope",+ startedAt: "2026-01-04T00:00:00.000Z",+ updatedAt: "2026-01-04T00:00:00.000Z",+ }),+ session({+ sessionId: "none",+ epoch: null,+ startedAt: "2026-01-03T00:00:00.000Z",+ updatedAt: "2026-01-03T00:00:00.000Z",+ }),+ ];+ const model = buildViewModel({+ project: {+ schema: 1,+ name: "p",+ epochs: [+ { id: "e2", title: "Second", createdAt: T0 },+ { id: "e1", title: "First", createdAt: T0 },+ ],+ },+ sessions,+ path: "/tmp/p",+ generatedAt: T0,+ });++ expect(model.epochs.map((e) => e.id)).toEqual(["e2", "e1"]);+ expect(model.epochs[1]?.sessions.map((s) => s.sessionId)).toEqual(["early", "late"]);+ expect(model.epochs[0]?.sessions).toEqual([]);+ expect(model.unassigned.map((s) => s.sessionId)).toEqual(["none", "ghost"]);+ expect(model.status).toEqual({+ goal: "ship",+ done: ["a"],+ pending: [{ text: "decide", needsUser: true }],+ next: "go",+ lastActivity: "2026-01-05T00:00:00.000Z",+ });+ expect(model.project).toEqual({ name: "p", path: "/tmp/p", generatedAt: T0 });+ });++ it("has an empty status card without sessions", () => {+ const model = buildViewModel({+ project: { schema: 1, name: "p", epochs: [] },+ sessions: [],+ path: "/tmp/p",+ generatedAt: T0,+ });+ expect(model.status).toEqual({ goal: "", done: [], pending: [], next: "", lastActivity: null });+ expect(model.unassigned).toEqual([]);+ });+});++describe("embedViewModel", () => {+ const model = buildViewModel({+ project: { schema: 1, name: "p", epochs: [] },+ sessions: [],+ path: "/tmp/p",+ generatedAt: T0,+ });++ it("fills the data element and round-trips the model", () => {+ const html = embedViewModel(TEMPLATE, model);+ expect(html).toContain('<div id="root">');+ expect(embedded(html)).toEqual(model);+ });++ it("escapes markup and line separators inside the JSON", () => {+ const risky = {+ ...model,+ project: { ...model.project, name: `</script><b>&\u2028\u2029` },+ };+ const html = embedViewModel(TEMPLATE, risky);+ expect(html).not.toContain("</script><b>");+ expect(html).not.toContain("\u2028");+ expect(html).toContain("\\u003c/script\\u003e\\u003cb\\u003e\\u0026\\u2028\\u2029");+ expect(embedded(html)).toEqual(risky);+ });++ it("refuses a template without the data element", () => {+ expect(() => embedViewModel("<html></html>", model)).toThrow(/no empty/);+ });+});++describe("codelineage build", () => {+ let dir: string;+ let root: string;+ let io: FakeIo;+ const paths = () => projectPaths(root);++ const saveSession = (id: string, value: unknown) =>+ writeFile(paths().session(id), JSON.stringify(value));++ beforeEach(async () => {+ dir = await tempDir();+ root = join(dir, "proj");+ await mkdir(root);+ io = fakeIo(envFor(dir));+ await init(root, { name: "proj", retention: "keep", language: "auto" }, fakeIo(envFor(dir)));+ await epochAdd(root, "e1", "First", fakeIo(envFor(dir)));+ });++ it("writes the map, keeping good sessions and warning about bad ones", async () => {+ await saveSession(+ "s1",+ session({+ sessionId: "s1",+ title: "one",+ epoch: "e1",+ startedAt: "2026-01-02T00:00:00.000Z",+ nodes: [+ node("a", "phase", "A"),+ node("b", "step", "B", "a", {+ summary: "token ghp_abcdefghijklmnopqrstuvwxyz0123456789",+ }),+ ],+ }),+ );+ await saveSession(+ "s2",+ session({+ sessionId: "s2",+ title: "two",+ epoch: "e1",+ startedAt: "2026-01-01T00:00:00.000Z",+ }),+ );+ await saveSession(+ "s3",+ session({+ sessionId: "s3",+ epoch: "missing",+ startedAt: "2026-01-05T00:00:00.000Z",+ updatedAt: "2026-12-01T00:00:00.000Z",+ status: {+ goal: "latest",+ done: [],+ pending: [{ text: "ask", needsUser: true }],+ next: "n",+ },+ }),+ );+ await saveSession(+ "s4",+ session({ sessionId: "s4", epoch: null, startedAt: "2026-01-03T00:00:00.000Z" }),+ );+ await writeFile(paths().session("bad"), "{nope");+ await writeFile(paths().session("partial"), '{"schema":1,"sessionId":"p"}');+ await saveSession("newer", {+ ...session({ sessionId: "newer", epoch: "e1" }),+ schema: 2,+ });+ await writeFile(join(paths().sessions, "notes.txt"), "ignored");+ await mkdir(join(paths().sessions, "nested"));+ await writeFile(join(paths().sessions, "nested", "x.json"), "{}");++ const model = await buildProject({ dir: root, io, templateHtml: TEMPLATE });++ expect(io.lines).toEqual([`Wrote ${paths().html}`]);+ expect(io.warnings).toEqual(+ expect.arrayContaining([+ expect.stringMatching(/^skipping session bad: invalid JSON/),+ expect.stringMatching(/^skipping session partial: /),+ expect.stringMatching(/^session newer: schema v2 is newer/),+ "redacted 1 secret-looking value(s) in the map",+ ]),+ );++ expect(model.epochs[0]?.sessions.map((s) => s.sessionId)).toEqual(["s2", "s1", "newer"]);+ expect(model.unassigned.map((s) => s.sessionId)).toEqual(["s4", "s3"]);+ expect(model.epochs[0]?.sessions[1]?.nodes[0]?.children[0]?.summary).toBe("token [REDACTED]");+ expect(model.status.goal).toBe("latest");++ const html = await readFile(paths().html, "utf8");+ expect(embedded(html)).toEqual(model);+ });++ it("builds without printing when quiet and survives a missing sessions directory", async () => {+ await rm(paths().sessions, { recursive: true });+ await buildProject({ dir: root, io, templateHtml: TEMPLATE, quiet: true });+ expect(io.lines).toEqual([]);+ expect(embedded(await readFile(paths().html, "utf8"))).toMatchObject({+ epochs: [{ id: "e1", sessions: [] }],+ unassigned: [],+ });+ });++ it("reports a sessions path that is not a directory", async () => {+ await rm(paths().sessions, { recursive: true });+ await writeFile(paths().sessions, "not a directory");+ await expect(buildProject({ dir: root, io, templateHtml: TEMPLATE })).rejects.toThrow(+ /ENOTDIR/,+ );+ });++ it("warns about a newer project schema and rejects broken projects", async () => {+ const empty = await tempDir();+ await expect(buildProject({ dir: empty, io, templateHtml: TEMPLATE })).rejects.toThrow(+ /not initialized/,+ );+ await mkdir(join(empty, ".codelineage"));+ await writeFile(join(empty, ".codelineage", "project.json"), "{}");+ await expect(buildProject({ dir: empty, io, templateHtml: TEMPLATE })).rejects.toThrow(+ /schema version/,+ );++ await writeFile(paths().project, JSON.stringify({ schema: 2, name: "future", epochs: [] }));+ await buildProject({ dir: root, io, templateHtml: TEMPLATE });+ expect(io.warnings).toContain("schema v2 is newer than supported v1; reading best-effort");+ });++ it("rebuilds quietly after a session write with the bundled template", async () => {+ await sessionWrite({ dir: root }, io, async () =>+ JSON.stringify({ sessionId: "s1", title: "written", epoch: "e1" }),+ );+ expect(io.lines).toEqual(["Saved session s1 (0 nodes)"]);+ const html = await readFile(paths().html, "utf8");+ expect(html).toContain('<div id="root">');+ expect(embedded(html)).toMatchObject({+ epochs: [{ id: "e1", sessions: [{ sessionId: "s1", title: "written" }] }],+ });+ });++ it("turns a failed rebuild into a warning after the session is saved", async () => {+ await mkdir(paths().html);+ await sessionWrite({ dir: root }, io, async () => JSON.stringify({ sessionId: "s1" }));+ expect(io.lines).toEqual(["Saved session s1 (0 nodes)"]);+ expect(io.warnings.join("\n")).toMatch(/could not build lineage\.html/);+ expect(existsSync(paths().session("s1"))).toBe(true);+ });+});diff --git a/packages/cli/test/global-setup.ts b/packages/cli/test/global-setup.tsnew file mode 100644index 0000000..82b2fc0--- /dev/null+++ b/packages/cli/test/global-setup.ts@@ -0,0 +1,18 @@+import { execFileSync } from "node:child_process";+import { existsSync } from "node:fs";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";++const root = join(dirname(fileURLToPath(import.meta.url)), "../../..");++/**+ * The CLI embeds `packages/template/dist/index.html` as text at bundle time, so+ * tests need the template built once. It is gitignored and not guaranteed to+ * exist on a fresh checkout.+ */+export function setup(): void {+ const index = join(root, "packages/template/dist/index.html");+ if (!existsSync(index)) {+ execFileSync("npm", ["run", "build", "-w", "template"], { cwd: root, stdio: "ignore" });+ }+}diff --git a/packages/cli/test/program-commands.test.ts b/packages/cli/test/program-commands.test.tsindex 12494b7..45605d2 100644--- a/packages/cli/test/program-commands.test.ts+++ b/packages/cli/test/program-commands.test.ts@@ -1,3 +1,4 @@+import { existsSync } from "node:fs";import { mkdir, writeFile } from "node:fs/promises";import { join } from "node:path";import { beforeEach, describe, expect, it } from "vitest";@@ -68,6 +69,13 @@ describe("commands through the CLI", () => {expect(io.lines.at(-1)).toBe("Saved session s1 (0 nodes)");});+ it("builds the map through the CLI", async () => {+ await cli("init", root, "--yes", "--retention", "keep");+ await cli("build", root);+ expect(io.lines.at(-1)).toMatch(/^Wrote .*lineage\.html$/);+ expect(existsSync(join(root, ".codelineage", "lineage.html"))).toBe(true);+ });+it("prints user errors as one line", async () => {expect(await cli("config", "get", "nope")).toMatch(/^error: unknown key "nope"/);});diff --git a/packages/cli/tsup.config.ts b/packages/cli/tsup.config.tsindex 6490cee..7026fcf 100644--- a/packages/cli/tsup.config.ts+++ b/packages/cli/tsup.config.ts@@ -8,6 +8,8 @@ export default defineConfig({bundle: true,noExternal: [/.*/],clean: true,+ // The template HTML ships inside the bundle so dist/cli.js is self-contained.+ loader: { ".html": "text" },// CJS deps bundled into ESM still call require() for node builtinsbanner: {js: [diff --git a/vitest.config.ts b/vitest.config.tsindex 8f99b66..aedad4d 100644--- a/vitest.config.ts+++ b/vitest.config.ts@@ -1,8 +1,26 @@+import { readFileSync } from "node:fs";+import type { Plugin } from "vite";import { defineConfig } from "vitest/config";+/**+ * tsup bundles the template with the `text` loader. Vite would hand a `.html`+ * import to its page plugin, so tests load the same file as a string module.+ */+const templateAsText: Plugin = {+ name: "codelineage-template-as-text",+ enforce: "pre",+ load(id) {+ const file = id.split("?")[0] ?? "";+ if (!file.endsWith(".html") || !file.includes("/packages/template/dist/")) return null;+ return `export default ${JSON.stringify(readFileSync(file, "utf8"))};`;+ },+};+export default defineConfig({+ plugins: [templateAsText],test: {include: ["packages/*/test/**/*.test.ts"],+ globalSetup: ["./packages/cli/test/global-setup.ts"],coverage: {provider: "v8",include: ["packages/*/src/**"],