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(server): serve the map from a local live-refreshing server
Erenccde03531c55
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ef5e73a..ea4f083 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+- Live map server: `codelineage open` makes sure one background server per user runs on `127.0.0.1:<serverPort>` (new setting `serverPort`, default 4747) and opens the map or the panel through it, returning at once. A served page refreshes its data when the map is rebuilt without losing open topics, selection, zoom or scroll, and the panel's links point at those live maps; over `file://` nothing changes. The server serves only registered projects' maps and the panel, rejects a foreign `Host` header (DNS rebinding), binds loopback only and exits after 30 idle minutes. When the port is taken or the server cannot start, `open` opens the file as before and prints one line saying so.- Live map: the `Stop` hook rebuilds `lineage.html` after every turn, detached like the SessionEnd catch-up and skipped while a build or the session's write holds its lock (a new `build` lock in `build`, `codelineage build --quiet` for the child). The build draws the user messages the record does not hold yet as cards titled with their first words, marked "not summarized yet" and sitting in a "New" topic at the end of the session, so the newest message is on the map before the agent summarizes it; "left off here" marks the newest of them and their drill-down shows the conversation from the transcript.## [0.5.0] - 2026-10-23diff --git a/packages/cli/src/commands/open.ts b/packages/cli/src/commands/open.tsindex b1fd7c8..5db8456 100644--- a/packages/cli/src/commands/open.ts+++ b/packages/cli/src/commands/open.ts@@ -1,5 +1,6 @@import { type SpawnOptions, spawn } from "node:child_process";import type { Io } from "../io.js";+import { ensureServer, mapPageUrl } from "../server.js";import { globalPaths, projectPaths } from "../store/paths.js";import { resolveProjectRoot } from "../store/root.js";import { buildPanel } from "../view/panel.js";@@ -10,7 +11,18 @@ export interface OpenOptions {/** Tests inject a minimal page instead of the bundled template. */templateHtml?: string;/** Tests replace the OS opener; resolves false when none is available. */- launch?: (file: string) => Promise<boolean>;+ launch?: (target: string) => Promise<boolean>;+ /** Tests replace the local map server; resolves the URL base or null. */+ server?: (env: NodeJS.ProcessEnv) => Promise<string | null>;+}++/** Any failure here means "no server", never a failed `open`. */+export async function defaultServer(env: NodeJS.ProcessEnv): Promise<string | null> {+ try {+ return await ensureServer(env);+ } catch {+ return null;+ }}export interface OpenProjectOptions extends OpenOptions {@@ -53,19 +65,23 @@ export function launchFile(file: string, spawnFn: SpawnLike = systemSpawn): Prom});}-/** Hands a built page to the OS opener, or prints its path when none exists. */-async function openFile(file: string, opts: OpenOptions): Promise<void> {+/** Hands a page URL or file to the OS opener, or prints it when none exists. */+async function openTarget(target: string, opts: OpenOptions): Promise<void> {const { io } = opts;- const opened = await (opts.launch ?? launchFile)(file);+ const opened = await (opts.launch ?? launchFile)(target);if (opened) {- io.out(`Opened ${file}`);+ io.out(`Opened ${target}`);return;}- io.out(file);- io.warn("no application opener found; open the file manually");+ io.out(target);+ io.warn("no application opener found; open it manually");}-/** Rebuilds the map, then hands `lineage.html` to the OS opener. */+/**+ * Rebuilds the map, then opens it through the local map server so the page can+ * refresh itself. The file remains the fallback: when no server can run (port+ * taken, spawn failed) `open` still shows the map, just without live updates.+ */export async function openProject(opts: OpenProjectOptions): Promise<void> {const { io } = opts;const { root } = await resolveProjectRoot(opts.dir);@@ -74,15 +90,27 @@ export async function openProject(opts: OpenProjectOptions): Promise<void> {io,...(opts.templateHtml === undefined ? {} : { templateHtml: opts.templateHtml }),});- await openFile(projectPaths(root).html, opts);+ const base = await (opts.server ?? defaultServer)(io.env);+ if (base) {+ await openTarget(mapPageUrl(base, root), opts);+ return;+ }+ io.warn("could not start the local map server; opened the file instead");+ await openTarget(projectPaths(root).html, opts);}-/** Rebuilds the global panel, then hands `panel.html` to the OS opener. */+/** Rebuilds the global panel, then opens it through the local map server. */export async function openPanel(opts: OpenOptions): Promise<void> {await buildPanel({env: opts.io.env,io: opts.io,...(opts.templateHtml === undefined ? {} : { templateHtml: opts.templateHtml }),});- await openFile(globalPaths(opts.io.env).panel, opts);+ const base = await (opts.server ?? defaultServer)(opts.io.env);+ if (base) {+ await openTarget(`${base}/`, opts);+ return;+ }+ opts.io.warn("could not start the local map server; opened the file instead");+ await openTarget(globalPaths(opts.io.env).panel, opts);}diff --git a/packages/cli/src/program.ts b/packages/cli/src/program.tsindex 46c2bcf..24470cf 100644--- a/packages/cli/src/program.ts+++ b/packages/cli/src/program.ts@@ -15,12 +15,16 @@ import { openPanel, openProject } from "./commands/open.js";import { readStdin, sessionShow, sessionWrite } from "./commands/session.js";import { runHook } from "./hooks/run.js";import { CliError, type Io, processIo } from "./io.js";+import { startMapServer } from "./server.js";+import { loadConfig } from "./store/stores.js";export type IoFactory = (interactive: boolean) => Io;/** Test seams for effects that would leave this process (opening a browser). */export interface ProgramDeps {- launch?: (file: string) => Promise<boolean>;+ launch?: (target: string) => Promise<boolean>;+ /** Replaces the local map server; resolves its base URL, or null. */+ server?: (env: NodeJS.ProcessEnv) => Promise<string | null>;/** Reads a hook's JSON input; tests pass it directly. */stdin?: () => Promise<string>;}@@ -91,11 +95,32 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =run(async (dir?: string) => {const io = makeIo(false);const launch = deps.launch === undefined ? {} : { launch: deps.launch };+ const server = deps.server === undefined ? {} : { server: deps.server };if (dir === undefined) {- await openPanel({ io, ...launch });+ await openPanel({ io, ...launch, ...server });return;}- await openProject({ dir, io, ...launch });+ await openProject({ dir, io, ...launch, ...server });+ }),+ );++ // Started detached by `open`; also useful on its own when the port is known.+ program+ .command("serve", { hidden: true })+ .description("run the local map server that `open` uses")+ .option("--port <port>", "port to bind (default: serverPort from config)")+ .action(+ run(async (opts: { port?: string }) => {+ const io = makeIo(false);+ const port =+ opts.port === undefined ? (await loadConfig(io.env)).serverPort : Number(opts.port);+ if (!Number.isInteger(port) || port < 1 || port > 65535)+ throw new CliError(`invalid port: ${String(opts.port)}`);+ try {+ await startMapServer({ env: io.env, port });+ } catch (err) {+ throw new CliError(`could not start the map server: ${(err as Error).message}`);+ }}),);diff --git a/packages/cli/src/schema/config.ts b/packages/cli/src/schema/config.tsindex cc58438..8cb6905 100644--- a/packages/cli/src/schema/config.ts+++ b/packages/cli/src/schema/config.ts@@ -11,6 +11,8 @@ export const Config = z.object({sessionEndCatchUp: z.boolean().default(true),/** Model for the headless catch-up (SessionEnd) and, later, backfill. */catchUpModel: z.string().trim().min(1).max(64).default("haiku"),+ /** Port the local map server binds on `127.0.0.1`. */+ serverPort: z.int().min(1).max(65535).default(4747),/** 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"]),diff --git a/packages/cli/src/server.ts b/packages/cli/src/server.tsnew file mode 100644index 0000000..51aefea--- /dev/null+++ b/packages/cli/src/server.ts@@ -0,0 +1,360 @@+import { type SpawnOptions, spawn } from "node:child_process";+import { type FSWatcher, watch } from "node:fs";+import { readFile } from "node:fs/promises";+import {+ createServer as createHttpServer,+ type IncomingMessage,+ type ServerResponse,+} from "node:http";+import type { AddressInfo } from "node:net";+import { basename, resolve } from "node:path";+import { fileURLToPath } from "node:url";+import { globalPaths, projectPaths } from "./store/paths.js";+import { loadConfig, loadRegistry } from "./store/stores.js";+import { LIVE_META_NAME } from "./view/model.js";++/** A page nobody is looking at is a dead server after this long. */+export const DEFAULT_IDLE_MS = 30 * 60 * 1000;++/** How long `open` waits for a freshly spawned server to answer. */+export const START_WAIT_MS = 1500;++const HOST = "127.0.0.1";+const LIVE_META = `<meta name="${LIVE_META_NAME}" content="1">`;++/**+ * Marks a page as served by the local server. The page only subscribes to+ * rebuild events when this tag is present, so `file://` pages (and the Vite dev+ * server) stay silent.+ */+export function injectLiveMeta(html: string): string {+ if (html.includes(LIVE_META)) return html;+ return html.replace(/<head(\s[^>]*)?>/i, (head) => `${head}${LIVE_META}`);+}++export interface MapServerOptions {+ env?: NodeJS.ProcessEnv;+ /** 0 lets the OS pick a free port (tests). */+ port: number;+ hostname?: string;+ /** Exit after this long without a connected page (tests use a short one). */+ idleMs?: number;+}++export interface MapServer {+ port: number;+ host: string;+ /** `http://127.0.0.1:<port>`; pages live under `/map` and `/panel`. */+ url: string;+ close: () => Promise<void>;+ /** Resolves once the server has closed (including the idle exit). */+ closed: Promise<void>;+}++interface PageTarget {+ /** The HTML file served for the page and watched for rebuilds. */+ file: string;+ /** Directory to watch: atomic writes replace the file, the directory keeps its name. */+ dir: string;+}++interface WatchedPage {+ watcher?: FSWatcher;+ clients: Set<ServerResponse>;+ timer: NodeJS.Timeout | null;+}++function hostAllowed(host: string | undefined, port: number): boolean {+ return host === `${HOST}:${port}` || host === `localhost:${port}`;+}++function respond(res: ServerResponse, status: number, body: string): void {+ // A stream that already started (the event endpoint) can only be ended.+ if (!res.headersSent) res.writeHead(status, { "content-type": "text/plain; charset=utf-8" });+ res.end(body);+}++/** The root of a registered project, or null when the request names another path. */+async function registeredRoot(env: NodeJS.ProcessEnv, dir: string): Promise<string | null> {+ const requested = resolve(dir);+ const registry = await loadRegistry(env);+ if (!registry.found || !registry.ok) return null;+ return registry.data.projects.some((entry) => resolve(entry.path) === requested)+ ? requested+ : null;+}++/**+ * What a request may see: the panel, or the map of a project in the registry.+ * Nothing else in the filesystem is reachable, which is what keeps this server+ * a viewer and not a file server.+ */+async function pageTarget(env: NodeJS.ProcessEnv, url: URL): Promise<PageTarget | null> {+ const panel = (): PageTarget => {+ const paths = globalPaths(env);+ return { file: paths.panel, dir: paths.base };+ };+ if (url.pathname === "/") return panel();+ if (url.pathname === "/map" || url.pathname === "/events") {+ const raw = url.searchParams.get("dir");+ // The panel's event stream lives at /events without a directory.+ if (!raw) return url.pathname === "/events" ? panel() : null;+ const root = await registeredRoot(env, raw);+ if (!root) return null;+ const paths = projectPaths(root);+ return { file: paths.html, dir: paths.base };+ }+ return null;+}++/** URL of a project's map on a running server. */+export function mapPageUrl(base: string, root: string): string {+ return `${base}/map?dir=${encodeURIComponent(root)}`;+}++/**+ * Starts the local map server. It serves the panel and the maps of registered+ * projects, tells connected pages when one is rebuilt and exits after `idleMs`+ * without a connected page. It binds `127.0.0.1` only and rejects a `Host`+ * header that names any other host (DNS rebinding).+ */+export async function startMapServer(opts: MapServerOptions): Promise<MapServer> {+ const env = opts.env ?? process.env;+ const hostname = opts.hostname ?? HOST;+ const idleMs = opts.idleMs ?? DEFAULT_IDLE_MS;+ const pages = new Map<string, WatchedPage>();+ let openPages = 0;+ let idleTimer: NodeJS.Timeout | null = null;+ let closing: Promise<void> | null = null;+ let resolveClosed: () => void = () => {};+ const closed = new Promise<void>((done) => {+ resolveClosed = done;+ });++ function clearIdle(): void {+ if (idleTimer !== null) clearTimeout(idleTimer);+ idleTimer = null;+ }++ function scheduleIdle(ms: number): void {+ clearIdle();+ idleTimer = setTimeout(() => {+ idleTimer = null;+ void close();+ }, ms);+ }++ function broadcast(page: WatchedPage): void {+ for (const client of page.clients) {+ if (client.writableEnded) continue;+ client.write("event: change\ndata: rebuilt\n\n");+ }+ }++ function watched(file: string, dir: string): WatchedPage {+ const existing = pages.get(file);+ if (existing) return existing;+ const page: WatchedPage = { clients: new Set(), timer: null };+ try {+ page.watcher = watch(dir, { persistent: false }, (_event, name) => {+ // A null name means "something in here changed" on some platforms.+ if (name !== null && name.toString() !== basename(file)) return;+ if (page.timer !== null) clearTimeout(page.timer);+ // One rebuild emits several events; tell the page once.+ page.timer = setTimeout(() => {+ page.timer = null;+ broadcast(page);+ }, 50);+ });+ } catch {+ // The page can still be viewed; it just will not refresh by itself.+ }+ pages.set(file, page);+ return page;+ }++ function release(file: string, page: WatchedPage): void {+ if (page.clients.size > 0) return;+ page.watcher?.close();+ if (page.timer !== null) clearTimeout(page.timer);+ pages.delete(file);+ }++ const server = createHttpServer((req, res) => {+ // A broken registry or an unexpected error must not take the server down.+ void handle(req, res).catch(() => respond(res, 500, "internal error"));+ });++ async function handle(req: IncomingMessage, res: ServerResponse): Promise<void> {+ const port = (server.address() as AddressInfo | null)?.port ?? opts.port;+ if (req.method !== "GET" && req.method !== "HEAD") {+ respond(res, 405, "method not allowed");+ return;+ }+ if (!hostAllowed(req.headers.host, port)) {+ respond(res, 403, "forbidden");+ return;+ }+ const url = new URL(req.url ?? "/", `http://${HOST}:${port}`);+ if (url.pathname === "/health") {+ res.writeHead(200, {+ "content-type": "application/json",+ "cache-control": "no-store",+ });+ res.end(JSON.stringify({ ok: true, name: "codelineage", home: globalPaths(env).base }));+ return;+ }+ const target = await pageTarget(env, url);+ if (!target) {+ respond(res, 404, "not found");+ return;+ }++ if (url.pathname === "/events") {+ res.writeHead(200, {+ "content-type": "text/event-stream",+ "cache-control": "no-cache",+ connection: "keep-alive",+ });+ res.write("retry: 1000\n\n");+ const page = watched(target.file, target.dir);+ page.clients.add(res);+ res.on("error", () => page.clients.delete(res));+ openPages += 1;+ clearIdle();+ req.on("close", () => {+ page.clients.delete(res);+ release(target.file, page);+ openPages = Math.max(0, openPages - 1);+ if (openPages === 0) scheduleIdle(idleMs);+ });+ return;+ }++ let html: string;+ try {+ html = await readFile(target.file, "utf8");+ } catch {+ respond(res, 404, "not found");+ return;+ }+ res.writeHead(200, {+ "content-type": "text/html; charset=utf-8",+ "cache-control": "no-store",+ });+ res.end(req.method === "HEAD" ? undefined : injectLiveMeta(html));+ }++ await new Promise<void>((done, fail) => {+ const onError = (err: Error): void => fail(err);+ server.once("error", onError);+ server.listen(opts.port, hostname, () => {+ server.off("error", onError);+ done();+ });+ });++ const port = (server.address() as AddressInfo).port;+ const url = `http://${hostname}:${port}`;++ function close(): Promise<void> {+ if (closing) return closing;+ closing = (async () => {+ clearIdle();+ for (const page of pages.values()) {+ page.watcher?.close();+ if (page.timer !== null) clearTimeout(page.timer);+ for (const client of page.clients) client.end();+ page.clients.clear();+ }+ pages.clear();+ await new Promise<void>((done) => server.close(() => done()));+ resolveClosed();+ })();+ return closing;+ }++ // Nothing may look at the page in the first moments after `open` spawns the+ // server; the same idle rule covers that start.+ scheduleIdle(idleMs);++ return { port, host: hostname, url, close, closed };+}++interface HealthBody {+ name?: unknown;+ home?: unknown;+}++/**+ * True when a codelineage server for this user's home answers on the port. The+ * home check keeps two users (or two `CODELINEAGE_HOME`s) apart on one port.+ */+export async function checkHealth(url: string, env: NodeJS.ProcessEnv): Promise<boolean> {+ try {+ const response = await fetch(`${url}/health`, { signal: AbortSignal.timeout(500) });+ if (!response.ok) return false;+ const body = (await response.json()) as HealthBody;+ return body.name === "codelineage" && body.home === globalPaths(env).base;+ } catch {+ return false;+ }+}++type SpawnFn = (command: string, args: string[], options: SpawnOptions) => { unref: () => void };++const systemSpawn: SpawnFn = (command, args, options) => spawn(command, args, options);++/** Starts `node <cli> serve --port <port>` detached, with hooks silenced in the child. */+export function spawnServerProcess(+ cli: string,+ port: number,+ env: NodeJS.ProcessEnv,+ spawnFn: SpawnFn = systemSpawn,+): void {+ spawnFn(process.execPath, [cli, "serve", "--port", String(port)], {+ detached: true,+ stdio: "ignore",+ env: { ...env, CODELINEAGE_DISABLE: "1" },+ }).unref();+}++export interface EnsureServerDeps {+ /** The CLI file the detached server runs; defaults to the running script. */+ cli?: string;+ /** Starts the detached server; tests observe instead of spawning. */+ spawn?: (cli: string, port: number, env: NodeJS.ProcessEnv) => void;+ /** Health probe; tests replace the network with a function. */+ health?: (url: string, env: NodeJS.ProcessEnv) => Promise<boolean>;+ /** How long to wait for a spawned server before giving up. */+ waitMs?: number;+}++function delay(ms: number): Promise<void> {+ return new Promise((done) => setTimeout(done, ms));+}++/**+ * Returns the base URL of a running map server for this user, starting one+ * detached when needed. Null means "cannot have a server" (the port answers as+ * something else, or the child never came up): the caller opens the file.+ */+export async function ensureServer(+ env: NodeJS.ProcessEnv,+ deps: EnsureServerDeps = {},+): Promise<string | null> {+ const { serverPort } = await loadConfig(env);+ const base = `http://${HOST}:${serverPort}`;+ const health = deps.health ?? checkHealth;+ if (await health(base, env)) return base;++ const cli = deps.cli ?? process.argv[1] ?? fileURLToPath(import.meta.url);+ (deps.spawn ?? spawnServerProcess)(cli, serverPort, env);++ const deadline = Date.now() + (deps.waitMs ?? START_WAIT_MS);+ while (Date.now() < deadline) {+ await delay(50);+ if (await health(base, env)) return base;+ }+ return null;+}diff --git a/packages/cli/src/view/model.ts b/packages/cli/src/view/model.tsindex c1b0459..f995df5 100644--- a/packages/cli/src/view/model.ts+++ b/packages/cli/src/view/model.ts@@ -10,6 +10,13 @@ import type { NodeKind } from "../schema/session.js";/** Id of the `<script type="application/json">` that carries the model. */export const DATA_ELEMENT_ID = "codelineage-data";+/**+ * Meta tag the local map server injects into the pages it serves. The page+ * subscribes to rebuild events only when it is present, so a `file://` page or+ * the Vite dev server never tries to reach a server that is not there.+ */+export const LIVE_META_NAME = "codelineage-live";+/** Version of the serialized view model (not the session schema). */export const VIEW_SCHEMA = 1;diff --git a/packages/cli/test/open.test.ts b/packages/cli/test/open.test.tsindex 77cbe60..1cf81d3 100644--- a/packages/cli/test/open.test.ts+++ b/packages/cli/test/open.test.ts@@ -1,9 +1,15 @@import { EventEmitter } from "node:events";-import { mkdir } from "node:fs/promises";+import { mkdir, rm } from "node:fs/promises";import { join } from "node:path";import { beforeEach, describe, expect, it } from "vitest";import { init } from "../src/commands/init.js";-import { launchFile, openerCommand, openPanel, openProject } from "../src/commands/open.js";+import {+ defaultServer,+ launchFile,+ openerCommand,+ openPanel,+ openProject,+} from "../src/commands/open.js";import { globalPaths, projectPaths } from "../src/store/paths.js";import { DATA_ELEMENT_ID } from "../src/view/model.js";import { envFor, type FakeIo, fakeIo, tempDir } from "./helpers.js";@@ -69,15 +75,45 @@ describe("launchFile", () => {});});+const NO_SERVER = async () => null;++describe("defaultServer", () => {+ it("turns a broken config into 'no server' instead of failing open", async () => {+ // A directory where config.json should be makes the config read throw.+ await rm(globalPaths(io.env).config, { force: true });+ await mkdir(globalPaths(io.env).config, { recursive: true });+ expect(await defaultServer(io.env)).toBeNull();+ });+});+describe("openProject", () => {- it("builds the map and opens it with the OS opener", async () => {+ it("builds the map and opens it through the local server", async () => {const launched: string[] = [];await openProject({dir: root,io,templateHtml: TEMPLATE,- launch: async (file) => {- launched.push(file);+ server: async () => "http://127.0.0.1:4747",+ launch: async (target) => {+ launched.push(target);+ return true;+ },+ });+ const url = `http://127.0.0.1:4747/map?dir=${encodeURIComponent(root)}`;+ expect(launched).toEqual([url]);+ expect(io.lines).toEqual([`Wrote ${projectPaths(root).html}`, `Opened ${url}`]);+ expect(io.warnings).toEqual([]);+ });++ it("falls back to the file when no server can start", async () => {+ const launched: string[] = [];+ await openProject({+ dir: root,+ io,+ templateHtml: TEMPLATE,+ server: NO_SERVER,+ launch: async (target) => {+ launched.push(target);return true;},});@@ -86,33 +122,63 @@ describe("openProject", () => {`Wrote ${projectPaths(root).html}`,`Opened ${projectPaths(root).html}`,]);+ expect(io.warnings).toEqual(["could not start the local map server; opened the file instead"]);});it("prints the path when no opener is available", async () => {- await openProject({ dir: root, io, templateHtml: TEMPLATE, launch: async () => false });+ await openProject({+ dir: root,+ io,+ templateHtml: TEMPLATE,+ server: NO_SERVER,+ launch: async () => false,+ });expect(io.lines.at(-1)).toBe(projectPaths(root).html);- expect(io.warnings).toEqual(["no application opener found; open the file manually"]);+ expect(io.warnings).toEqual([+ "could not start the local map server; opened the file instead",+ "no application opener found; open it manually",+ ]);});});describe("openPanel", () => {- it("builds the panel and opens it with the OS opener", async () => {+ it("builds the panel and opens it through the local server", async () => {const launched: string[] = [];await openPanel({io,templateHtml: TEMPLATE,- launch: async (file) => {- launched.push(file);+ server: async () => "http://127.0.0.1:4747",+ launch: async (target) => {+ launched.push(target);+ return true;+ },+ });+ expect(launched).toEqual(["http://127.0.0.1:4747/"]);+ expect(io.lines).toEqual(["Opened http://127.0.0.1:4747/"]);+ });++ it("falls back to the panel file when no server can start", async () => {+ const launched: string[] = [];+ await openPanel({+ io,+ templateHtml: TEMPLATE,+ server: NO_SERVER,+ launch: async (target) => {+ launched.push(target);return true;},});expect(launched).toEqual([globalPaths(io.env).panel]);expect(io.lines).toEqual([`Opened ${globalPaths(io.env).panel}`]);+ expect(io.warnings).toEqual(["could not start the local map server; opened the file instead"]);});it("prints the panel path when no opener is available", async () => {- await openPanel({ io, templateHtml: TEMPLATE, launch: async () => false });+ await openPanel({ io, templateHtml: TEMPLATE, server: NO_SERVER, launch: async () => false });expect(io.lines.at(-1)).toBe(globalPaths(io.env).panel);- expect(io.warnings).toEqual(["no application opener found; open the file manually"]);+ expect(io.warnings).toEqual([+ "could not start the local map server; opened the file instead",+ "no application opener found; open it manually",+ ]);});});diff --git a/packages/cli/test/program-commands.test.ts b/packages/cli/test/program-commands.test.tsindex 43738cf..09a224b 100644--- a/packages/cli/test/program-commands.test.ts+++ b/packages/cli/test/program-commands.test.ts@@ -1,5 +1,6 @@import { existsSync } from "node:fs";import { mkdir, rm, writeFile } from "node:fs/promises";+import { type AddressInfo, createServer as createNetServer } from "node:net";import { join } from "node:path";import { beforeEach, describe, expect, it } from "vitest";import { readSkillAllowed } from "../src/claude-settings.js";@@ -13,6 +14,7 @@ let root: string;let io: FakeIo;let interactive: boolean[];let launched: string[];+let serverUrl: string | null = null;let stdin = "";beforeEach(async () => {@@ -22,6 +24,7 @@ beforeEach(async () => {io = fakeIo(envFor(dir));interactive = [];launched = [];+ serverUrl = null;});async function cli(...args: string[]): Promise<string> {@@ -36,6 +39,7 @@ async function cli(...args: string[]): Promise<string> {launched.push(file);return true;},+ server: async () => serverUrl,stdin: async () => stdin,},);@@ -139,6 +143,27 @@ describe("commands through the CLI", () => {expect(io.lines.at(-1)).toMatch(/^Opened .*panel\.html$/);});+ it("open uses the local server when one is running", async () => {+ await cli("init", root, "--yes", "--retention", "keep");+ serverUrl = "http://127.0.0.1:4747";+ await cli("open", root);+ expect(launched.at(-1)).toBe(`http://127.0.0.1:4747/map?dir=${encodeURIComponent(root)}`);+ });++ it("serve refuses an invalid port and reports a taken one", async () => {+ expect(await cli("serve", "--port", "0")).toMatch(/invalid port: 0/);+ const taken = createNetServer();+ await new Promise<void>((done) => taken.listen(0, "127.0.0.1", done));+ const port = (taken.address() as AddressInfo).port;+ try {+ expect(await cli("serve", "--port", String(port))).toMatch(+ /could not start the map server: .*EADDRINUSE/,+ );+ } finally {+ await new Promise<void>((done) => taken.close(() => done()));+ }+ });+it("prunes projects whose directory is gone, honouring --dry-run", async () => {await cli("init", root, "--yes", "--retention", "keep");const gone = join(dir, "gone");diff --git a/packages/cli/test/server.test.ts b/packages/cli/test/server.test.tsnew file mode 100644index 0000000..c7c8e7c--- /dev/null+++ b/packages/cli/test/server.test.ts@@ -0,0 +1,312 @@+import { mkdir, rm } from "node:fs/promises";+import {+ type ClientRequest,+ createServer as createHttpServer,+ get as httpGet,+ type IncomingHttpHeaders,+ type IncomingMessage,+} from "node:http";+import { type AddressInfo, createServer as createNetServer } from "node:net";+import { join } from "node:path";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { buildProject } from "../src/commands/build.js";+import { init } from "../src/commands/init.js";+import {+ ensureServer,+ injectLiveMeta,+ type MapServer,+ mapPageUrl,+ spawnServerProcess,+ startMapServer,+} from "../src/server.js";+import { atomicWrite } from "../src/store/fs.js";+import { globalPaths, projectPaths } from "../src/store/paths.js";+import { updateConfig } from "../src/store/stores.js";+import { DATA_ELEMENT_ID, LIVE_META_NAME } from "../src/view/model.js";+import { envFor, fakeIo, tempDir } from "./helpers.js";++const TEMPLATE = `<!doctype html><html><head><title>codelineage</title></head><body><div id="root"></div>+<script id="${DATA_ELEMENT_ID}" type="application/json"></script></body></html>`;++const servers: MapServer[] = [];+let dir: string;+let root: string;+let env: NodeJS.ProcessEnv;++beforeEach(async () => {+ dir = await tempDir();+ root = join(dir, "proj");+ await mkdir(root);+ env = envFor(dir);+ await init(root, { name: "proj", retention: "keep", language: "auto" }, fakeIo(env));+ await buildProject({ dir: root, io: fakeIo(env), templateHtml: TEMPLATE });+});++afterEach(async () => {+ await Promise.all(servers.splice(0).map((server) => server.close()));+});++async function start(idleMs = 5000): Promise<MapServer> {+ const server = await startMapServer({ env, port: 0, idleMs });+ servers.push(server);+ return server;+}++interface Reply {+ status: number;+ body: string;+ headers: IncomingHttpHeaders;+}++function request(+ url: string,+ headers: Record<string, string> = {},+ method = "GET",+): Promise<Reply> {+ return new Promise((done, fail) => {+ const req = httpGet(url, { headers, method }, (res: IncomingMessage) => {+ const chunks: Buffer[] = [];+ res.on("data", (chunk: Buffer) => chunks.push(chunk));+ res.on("end", () =>+ done({+ status: res.statusCode ?? 0,+ body: Buffer.concat(chunks).toString("utf8"),+ headers: res.headers,+ }),+ );+ });+ req.on("error", fail);+ });+}++function openEvents(url: string): {+ waitFor: (needle: string, ms?: number) => Promise<boolean>;+ close: () => void;+} {+ let text = "";+ const req: ClientRequest = httpGet(url, (res) => {+ res.setEncoding("utf8");+ res.on("data", (chunk: string) => {+ text += chunk;+ });+ });+ req.on("error", () => {});+ const delay = (ms: number): Promise<void> => new Promise((done) => setTimeout(done, ms));+ return {+ waitFor: async (needle, ms = 3000) => {+ const deadline = Date.now() + ms;+ while (Date.now() < deadline) {+ if (text.includes(needle)) return true;+ await delay(20);+ }+ return false;+ },+ close: () => req.destroy(),+ };+}++function delay(ms: number): Promise<void> {+ return new Promise((done) => setTimeout(done, ms));+}++async function listen(server: ReturnType<typeof createHttpServer>): Promise<number> {+ await new Promise<void>((done) => server.listen(0, "127.0.0.1", done));+ return (server.address() as AddressInfo).port;+}++async function freePort(): Promise<number> {+ const probe = createNetServer();+ await new Promise<void>((done) => probe.listen(0, "127.0.0.1", done));+ const port = (probe.address() as AddressInfo).port;+ await new Promise<void>((done) => probe.close(() => done()));+ return port;+}++describe("injectLiveMeta", () => {+ it("marks the page once, after <head>", () => {+ const once = injectLiveMeta(TEMPLATE);+ expect(once).toContain(`<meta name="${LIVE_META_NAME}" content="1">`);+ expect(injectLiveMeta(once)).toBe(once);+ });++ it("leaves a page without a head tag alone", () => {+ expect(injectLiveMeta("<p>x</p>")).toBe("<p>x</p>");+ });+});++describe("map server", () => {+ it("serves the map of a registered project", async () => {+ const server = await start();+ const reply = await request(mapPageUrl(server.url, root));+ expect(reply.status).toBe(200);+ expect(reply.headers["content-type"]).toContain("text/html");+ expect(reply.body).toContain(LIVE_META_NAME);+ expect(reply.body).toContain("proj");+ });++ it("serves the panel at the root", async () => {+ const server = await start();+ const reply = await request(`${server.url}/`);+ expect(reply.status).toBe(200);+ expect(reply.body).toContain(LIVE_META_NAME);+ expect(reply.body).toContain("proj");+ });++ it("serves nothing else", async () => {+ const server = await start();+ expect((await request(`${server.url}/map`)).status).toBe(404);+ expect((await request(`${server.url}/map?dir=${encodeURIComponent(dir)}`)).status).toBe(404);+ expect((await request(`${server.url}/etc/passwd`)).status).toBe(404);+ });++ it("answers HEAD without a body and refuses other methods", async () => {+ const server = await start();+ const head = await request(mapPageUrl(server.url, root), {}, "HEAD");+ expect(head.status).toBe(200);+ expect(head.body).toBe("");+ expect((await request(server.url, {}, "POST")).status).toBe(405);+ });++ it("404s a registered project whose map was never built", async () => {+ const server = await start();+ await rm(projectPaths(root).html, { force: true });+ expect((await request(mapPageUrl(server.url, root))).status).toBe(404);+ });++ it("answers 500 instead of crashing when the registry cannot be read", async () => {+ const server = await start();+ const registry = globalPaths(env).registry;+ await rm(registry, { force: true });+ await mkdir(registry, { recursive: true });+ expect((await request(mapPageUrl(server.url, root))).status).toBe(500);+ });++ it("answers its health with this home", async () => {+ const server = await start();+ const reply = await request(`${server.url}/health`);+ expect(reply.status).toBe(200);+ expect(JSON.parse(reply.body)).toEqual({+ ok: true,+ name: "codelineage",+ home: globalPaths(env).base,+ });+ });++ it("rejects a foreign Host header", async () => {+ const server = await start();+ const reply = await request(`${server.url}/health`, { host: "evil.example:4747" });+ expect(reply.status).toBe(403);+ });++ it("tells a connected page when the map is rebuilt", async () => {+ const server = await start();+ const events = openEvents(`${server.url}/events?dir=${encodeURIComponent(root)}`);+ try {+ expect(await events.waitFor("retry: 1000")).toBe(true);+ await atomicWrite(projectPaths(root).html, "replaced");+ expect(await events.waitFor("event: change")).toBe(true);+ } finally {+ events.close();+ }+ });++ it("exits by itself when no page is connected", async () => {+ const server = await start(120);+ await server.closed;+ await expect(request(server.url)).rejects.toThrow();+ });++ it("stays up while a page is connected and exits after it leaves", async () => {+ const server = await start(300);+ const events = openEvents(`${server.url}/events?dir=${encodeURIComponent(root)}`);+ try {+ expect(await events.waitFor("retry: 1000")).toBe(true);+ await delay(500);+ const state = await Promise.race([+ server.closed.then(() => "closed"),+ delay(50).then(() => "open"),+ ]);+ expect(state).toBe("open");+ } finally {+ events.close();+ }+ await server.closed;+ });+});++describe("spawnServerProcess", () => {+ it("runs the CLI detached with hooks silenced", () => {+ const calls: unknown[][] = [];+ spawnServerProcess(+ "/cli.js",+ 4747,+ { XDG_CONFIG_HOME: "/home/x" },+ (command, args, options) => {+ calls.push([command, args, options]);+ return { unref: () => {} };+ },+ );+ expect(calls[0]?.[0]).toBe(process.execPath);+ expect(calls[0]?.[1]).toEqual(["/cli.js", "serve", "--port", "4747"]);+ expect(calls[0]?.[2]).toMatchObject({+ detached: true,+ stdio: "ignore",+ env: { XDG_CONFIG_HOME: "/home/x", CODELINEAGE_DISABLE: "1" },+ });+ });+});++describe("ensureServer", () => {+ it("reuses a server already running for this home", async () => {+ const server = await start();+ await updateConfig((config) => ({ ...config, serverPort: server.port }), env);+ let spawned = 0;+ const base = await ensureServer(env, {+ spawn: () => {+ spawned += 1;+ },+ waitMs: 200,+ });+ expect(base).toBe(server.url);+ expect(spawned).toBe(0);+ });++ it("gives up when the port answers as something else", async () => {+ const other = createHttpServer((_req, res) => {+ res.writeHead(404);+ res.end("not codelineage");+ });+ const port = await listen(other);+ await updateConfig((config) => ({ ...config, serverPort: port }), env);+ let spawned = 0;+ try {+ const base = await ensureServer(env, {+ spawn: () => {+ spawned += 1;+ },+ waitMs: 150,+ });+ expect(base).toBeNull();+ expect(spawned).toBe(1);+ } finally {+ await new Promise<void>((done) => other.close(() => done()));+ }+ });++ it("starts one when nothing is listening", async () => {+ const port = await freePort();+ await updateConfig((config) => ({ ...config, serverPort: port }), env);+ let started: MapServer | undefined;+ const base = await ensureServer(env, {+ spawn: () => {+ void startMapServer({ env, port }).then((server) => {+ started = server;+ servers.push(server);+ });+ },+ waitMs: 2000,+ });+ expect(base).toBe(`http://127.0.0.1:${port}`);+ expect(started?.port).toBe(port);+ });+});diff --git a/packages/template/src/Panel.tsx b/packages/template/src/Panel.tsxindex 94c3c0c..5207ab7 100644--- a/packages/template/src/Panel.tsx+++ b/packages/template/src/Panel.tsx@@ -1,4 +1,5 @@-import type { PanelSettings, PanelViewModel } from "../../cli/src/view/model.js";+import type { PanelProject, PanelSettings, PanelViewModel } from "../../cli/src/view/model.js";+import { isLivePage } from "./data.js";import { formatTime } from "./format.js";const SETTING_LABELS: [keyof PanelSettings, string][] = [@@ -9,6 +10,15 @@ const SETTING_LABELS: [keyof PanelSettings, string][] = [["agents", "Agents"],];+/**+ * From the local server, maps open as pages of that server so they refresh too;+ * the standalone panel file keeps its `file://` links.+ */+function mapHref(project: PanelProject): string | null {+ if (!project.lineageUrl) return null;+ return isLivePage() ? `/map?dir=${encodeURIComponent(project.path)}` : project.lineageUrl;+}+function settingText(value: PanelSettings[keyof PanelSettings]): string {if (Array.isArray(value)) return value.length > 0 ? value.join(", ") : "—";if (typeof value === "boolean") return value ? "yes" : "no";@@ -35,30 +45,33 @@ export function Panel({ model }: { model: PanelViewModel }) {<p className="empty">No projects registered yet. Run `codelineage init` in a project.</p>) : (<ul className="panel-grid">- {model.projects.map((project) => (- <li key={project.path} className={project.missing ? "card missing" : "card"}>- <div className="card-head">- <h2>{project.name}</h2>- {project.missing ? <span className="badge">missing</span> : null}- </div>- <p className="muted path">{project.path}</p>- <dl className="card-facts">- <div>- <dt>Last activity</dt>- <dd>{formatTime(project.lastActivity)}</dd>+ {model.projects.map((project) => {+ const href = mapHref(project);+ return (+ <li key={project.path} className={project.missing ? "card missing" : "card"}>+ <div className="card-head">+ <h2>{project.name}</h2>+ {project.missing ? <span className="badge">missing</span> : null}</div>- <div>- <dt>Waiting on you</dt>- <dd>{project.needsUserCount}</dd>- </div>- </dl>- {project.lineageUrl ? (- <a href={project.lineageUrl}>Open the map →</a>- ) : (- <p className="empty">Directory not found.</p>- )}- </li>- ))}+ <p className="muted path">{project.path}</p>+ <dl className="card-facts">+ <div>+ <dt>Last activity</dt>+ <dd>{formatTime(project.lastActivity)}</dd>+ </div>+ <div>+ <dt>Waiting on you</dt>+ <dd>{project.needsUserCount}</dd>+ </div>+ </dl>+ {href ? (+ <a href={href}>Open the map →</a>+ ) : (+ <p className="empty">Directory not found.</p>+ )}+ </li>+ );+ })}</ul>)}diff --git a/packages/template/src/data.ts b/packages/template/src/data.tsindex b221e65..097a6e3 100644--- a/packages/template/src/data.ts+++ b/packages/template/src/data.ts@@ -1,6 +1,7 @@-import { DATA_ELEMENT_ID, type PageModel } from "../../cli/src/view/model.js";+import { DATA_ELEMENT_ID, LIVE_META_NAME, type PageModel } from "../../cli/src/view/model.js";-function parse(text: string): PageModel {+/** Parses and checks the JSON contract; throws when the shape is not a page. */+export function parseViewModel(text: string): PageModel {let value: unknown;try {value = JSON.parse(text);@@ -22,10 +23,18 @@ function parse(text: string): PageModel {*/export async function loadViewModel(doc: Document = document): Promise<PageModel> {const raw = doc.getElementById(DATA_ELEMENT_ID)?.textContent?.trim();- if (raw) return parse(raw);+ if (raw) return parseViewModel(raw);if (import.meta.env.DEV) {const { fixture } = await import("./fixture.js");return fixture;}throw new Error("No codelineage data in this page. Run `codelineage build`.");}++/**+ * True only for a page the local map server served. `file://` pages and the+ * Vite dev server must not subscribe: nothing would answer.+ */+export function isLivePage(doc: Document = document): boolean {+ return doc.querySelector(`meta[name="${LIVE_META_NAME}"]`) !== null;+}diff --git a/packages/template/src/main.tsx b/packages/template/src/main.tsxindex 8950210..d7e5322 100644--- a/packages/template/src/main.tsx+++ b/packages/template/src/main.tsx@@ -1,10 +1,46 @@-import { StrictMode } from "react";+import { StrictMode, useEffect, useState } from "react";import { createRoot } from "react-dom/client";+import { DATA_ELEMENT_ID, type PageModel } from "../../cli/src/view/model.js";import { App } from "./App.js";-import { loadViewModel } from "./data.js";+import { isLivePage, loadViewModel, parseViewModel } from "./data.js";import { Panel } from "./Panel.js";import "./styles.css";+/** Re-reads the served page and takes its embedded model; null on any failure. */+async function fetchLatestModel(): Promise<PageModel | null> {+ try {+ const response = await fetch(location.href, { cache: "no-store" });+ if (!response.ok) return null;+ const doc = new DOMParser().parseFromString(await response.text(), "text/html");+ const raw = doc.getElementById(DATA_ELEMENT_ID)?.textContent?.trim();+ return raw ? parseViewModel(raw) : null;+ } catch {+ return null;+ }+}++/**+ * On the local server the page follows rebuilds: swapping the model in place+ * keeps the graph's open topics, selection and viewport, which a reload would+ * lose. Over `file://` there is no server to ask, so nothing is subscribed.+ */+function Page({ initial }: { initial: PageModel }) {+ const [model, setModel] = useState(initial);++ useEffect(() => {+ if (!isLivePage()) return;+ const source = new EventSource(`/events${location.search}`);+ source.addEventListener("change", () => {+ void fetchLatestModel().then((next) => {+ if (next) setModel(next);+ });+ });+ return () => source.close();+ }, []);++ return model.kind === "lineage" ? <App model={model} /> : <Panel model={model} />;+}+const root = document.getElementById("root");if (!root) throw new Error("missing #root");@@ -12,7 +48,7 @@ loadViewModel().then((model) => {createRoot(root).render(<StrictMode>- {model.kind === "lineage" ? <App model={model} /> : <Panel model={model} />}+ <Page initial={model} /></StrictMode>,);})