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(config): optional message summaries and editable panel settings
Erenb041c3979f1a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c6595d4..f9c92ec 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]### Added+- The panel's settings are editable on the page the local map server serves: `messageSummaries`, `language`, `updateEveryTurns`, `sessionEndCatchUp` and `catchUpModel` get a control and a Save button, and the server takes one small `POST /api/config` (same-origin only, a per-server token from the page, JSON body under 4 KB, validated with the config schema). After a write it rebuilds the panel and any open map so the pages refresh; over `file://` the settings stay read-only.+- Message summaries are optional and off by default: the new `messageSummaries` setting (also in `session show` and the catch-up prompt) tells the agent whether to write a message's `summary`; the branch summary remains the outer layer, `decidedBy`/`why`/`alternatives` are written either way, and old summaries keep showing in the drill-down.- Code in the map: a message whose record lists commits shows them as small tag chips (short hash) on its row; `build` reads each commit's subject from git and the drill-down names it, while a commit git no longer has stays listed and is drawn greyed. `codelineage blame <file>[:<line>]` follows git blame (or every commit that touched the file) back to the messages that recorded those commits and prints the commit, session, message, summary and the map URL that opens that message; with no hit it says so plainly. The map page hands a `#s=<session>&m=<message>` URL to the drill-down, so such a URL lands on the message.- The project map's top level is a git graph of sessions: one dot per session, titled with the session, hanging from the session its first message continues, with parallel lanes for sessions that run at the same time without a link and the epoch shown as a tag on the dot. Clicking a dot opens that session's message graph in place (a "← All sessions" control returns), and the session panel shows its status as a "squash message" (goal, done, pending, next). The epoch and session boxes and the `elkjs` layout are gone; both levels use the same layout engine. Live rebuilds keep the open session, selection and viewport.- The conversation store: `build` appends what the drill-down needs for turns not stored yet to `.codelineage/conversations/<sessionId>.jsonl.gz` (one gzip member per append, redacted with the same secret net as the page), reads it before the transcript, and keeps showing a session's conversation after Claude Code deletes the transcript. `init` writes `.codelineage/.gitignore` with `conversations/` even when `.codelineage/` is committed, an existing project gets the line on its next build, and the README explains where the raw chat lives. Stored turns keep the message's stable id, so ids survive the transcript.diff --git a/packages/cli/skills/lineage/SKILL.md b/packages/cli/skills/lineage/SKILL.mdindex d675408..1f74dd6 100644--- a/packages/cli/skills/lineage/SKILL.md+++ b/packages/cli/skills/lineage/SKILL.md@@ -57,8 +57,10 @@ short "ok" or "go on".("Continue with Epic 4", "Why does auto mode keep stopping?"). Never copy along paste; name what it is.- `summary`: one or two sentences on what came of it: the answer, the result or- the state it left. Someone returning days later should understand it without- the conversation.+ the state it left. Write it ONLY when `messageSummaries` in the record is+ `true`; while it is `false` (the default) leave `summary` out, like most git+ commits: a subject line, no body. `decidedBy`, `why` and `alternatives` are+ written either way.- When the message itself made a decision (the user asked for something, pickedan option or approved a proposal): `decidedBy` (`"user"` or `"agreed"`), thereason in `why`, and the options not taken in `alternatives`, each asdiff --git a/packages/cli/src/commands/backfill.ts b/packages/cli/src/commands/backfill.tsindex a2e1234..ea2a90f 100644--- a/packages/cli/src/commands/backfill.ts+++ b/packages/cli/src/commands/backfill.ts@@ -40,12 +40,14 @@ function recordPart(record: Session | undefined): string {return `The record so far (reuse these topic ids):\n${lines.join("\n")}`;}-function rules(language: string): string {+function rules(language: string, messageSummaries: boolean): string {const writing = language === "auto" ? "the conversation's language" : language;return ["Rules (from the codelineage lineage skill):",'- Send one "message" node for every message below, with the id exactly as given; skip none, even a short "ok".',- '- kind is "message". title: a few words in the user\'s own wording. summary: one or two sentences on what came of it.',+ `- kind is "message". title: a few words in the user's own wording.${+ messageSummaries ? " summary: one or two sentences on what came of it." : ""+ }`,'- parent: the id of the topic it belongs to. Reuse a topic id from the record below; otherwise add a "phase" topic with a short slug id and parent null.','- When the message itself made a decision (the user asked for it, picked an option or approved a proposal): decidedBy ("user" or "agreed"), the reason in why, and the options not taken in alternatives [{"option": "...", "why": "..."}].','- The agent\'s work goes inside the message node that caused it, never in nodes of its own: work (short items), agentDecisions ([{"title": "...", "why": "...", "alternatives": [...]}]), commits (short hashes) and files (a few paths).',@@ -65,12 +67,13 @@ export function catchUpPrompt(record: Session | undefined,sessionId: string,language: string,+ messageSummaries = false,): string {return ["You add the missing part of a codelineage lineage record, a map of the user's messages.","Below are the user's messages that have no node yet, each followed by the agent's written replies and a count of its tool calls.","",- rules(language),+ rules(language, messageSummaries),"",recordPart(record),"",@@ -214,7 +217,7 @@ export async function backfillTail(dir: string, sessionId: string, io: Io): Promconst config = await loadConfig(io.env);const loaded = await loadSession(root, sessionId);const record = loaded.found && loaded.ok ? loaded.data : undefined;- const prompt = catchUpPrompt(turns, record, sessionId, config.language);+ const prompt = catchUpPrompt(turns, record, sessionId, config.language, config.messageSummaries);const stdout = await runClaude(prompt, config.catchUpModel, io.env);const payload = { ...agentRecord(resultText(stdout)), sessionId };await sessionWrite({ dir: root }, io, async () => JSON.stringify(payload));diff --git a/packages/cli/src/commands/session.ts b/packages/cli/src/commands/session.tsindex 43d65d5..8f36771 100644--- a/packages/cli/src/commands/session.ts+++ b/packages/cli/src/commands/session.ts@@ -275,6 +275,7 @@ export async function sessionShow(dir: string, sessionId: string, io: Io): Promi...store,project: project.data.name,language: config.language,+ messageSummaries: config.messageSummaries,epochs: project.data.epochs.map(({ id, title }) => ({ id, title })),session: null,};diff --git a/packages/cli/src/schema/config.ts b/packages/cli/src/schema/config.tsindex 8cb6905..4200b93 100644--- a/packages/cli/src/schema/config.ts+++ b/packages/cli/src/schema/config.ts@@ -11,6 +11,11 @@ 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"),+ /**+ * Whether the agent writes a per-message `summary`. Off by default: the branch+ * summary is the outer layer and the drill-down already shows the reply.+ */+ messageSummaries: z.boolean().default(false),/** 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. */diff --git a/packages/cli/src/server.ts b/packages/cli/src/server.tsindex 51aefea..c093bfa 100644--- a/packages/cli/src/server.ts+++ b/packages/cli/src/server.ts@@ -1,4 +1,5 @@import { type SpawnOptions, spawn } from "node:child_process";+import { randomBytes, timingSafeEqual } from "node:crypto";import { type FSWatcher, watch } from "node:fs";import { readFile } from "node:fs/promises";import {@@ -9,9 +10,19 @@ import {import type { AddressInfo } from "node:net";import { basename, resolve } from "node:path";import { fileURLToPath } from "node:url";+import { buildProject } from "./commands/build.js";+import { defaultsPrompter, type Io } from "./io.js";+import { Config } from "./schema/config.js";+import { LockBusyError } from "./store/lock.js";import { globalPaths, projectPaths } from "./store/paths.js";-import { loadConfig, loadRegistry } from "./store/stores.js";-import { LIVE_META_NAME } from "./view/model.js";+import { loadConfig, loadRegistry, updateConfig } from "./store/stores.js";+import {+ isPanelEditableKey,+ LIVE_META_NAME,+ type PanelEditableKey,+ TOKEN_META_NAME,+} from "./view/model.js";+import { buildPanel } from "./view/panel.js";/** A page nobody is looking at is a dead server after this long. */export const DEFAULT_IDLE_MS = 30 * 60 * 1000;@@ -22,6 +33,12 @@ export const START_WAIT_MS = 1500;const HOST = "127.0.0.1";const LIVE_META = `<meta name="${LIVE_META_NAME}" content="1">`;+/** Header a settings write must carry, with the token from the panel page. */+export const CONFIG_TOKEN_HEADER = "x-codelineage-token";++/** A settings write is a tiny JSON object; anything larger is not ours. */+export const CONFIG_BODY_LIMIT = 4096;+/*** 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@@ -32,6 +49,16 @@ export function injectLiveMeta(html: string): string {return html.replace(/<head(\s[^>]*)?>/i, (head) => `${head}${LIVE_META}`);}+/**+ * Carries the per-server token into the served panel page. Only the panel needs+ * it (it is the only page that writes); maps get no token at all.+ */+export function injectTokenMeta(html: string, token: string): string {+ const meta = `<meta name="${TOKEN_META_NAME}" content="${token}">`;+ if (html.includes(meta)) return html;+ return html.replace(/<head(\s[^>]*)?>/i, (head) => `${head}${meta}`);+}+export interface MapServerOptions {env?: NodeJS.ProcessEnv;/** 0 lets the OS pick a free port (tests). */@@ -56,6 +83,8 @@ interface PageTarget {file: string;/** Directory to watch: atomic writes replace the file, the directory keeps its name. */dir: string;+ /** Only the panel page gets the settings token. */+ panel: boolean;}interface WatchedPage {@@ -92,7 +121,7 @@ async function registeredRoot(env: NodeJS.ProcessEnv, dir: string): Promise<striasync function pageTarget(env: NodeJS.ProcessEnv, url: URL): Promise<PageTarget | null> {const panel = (): PageTarget => {const paths = globalPaths(env);- return { file: paths.panel, dir: paths.base };+ return { file: paths.panel, dir: paths.base, panel: true };};if (url.pathname === "/") return panel();if (url.pathname === "/map" || url.pathname === "/events") {@@ -102,7 +131,7 @@ async function pageTarget(env: NodeJS.ProcessEnv, url: URL): Promise<PageTargetconst root = await registeredRoot(env, raw);if (!root) return null;const paths = projectPaths(root);- return { file: paths.html, dir: paths.base };+ return { file: paths.html, dir: paths.base, panel: false };}return null;}@@ -123,6 +152,8 @@ export async function startMapServer(opts: MapServerOptions): Promise<MapServer>const hostname = opts.hostname ?? HOST;const idleMs = opts.idleMs ?? DEFAULT_IDLE_MS;const pages = new Map<string, WatchedPage>();+ /** One random token per server start; the panel page carries it into a write. */+ const token = randomBytes(24).toString("hex");let openPages = 0;let idleTimer: NodeJS.Timeout | null = null;let closing: Promise<void> | null = null;@@ -185,8 +216,152 @@ export async function startMapServer(opts: MapServerOptions): Promise<MapServer>void handle(req, res).catch(() => respond(res, 500, "internal error"));});+ function tokenMatches(given: string | string[] | undefined): boolean {+ const value = Array.isArray(given) ? given[0] : given;+ if (typeof value !== "string") return false;+ const a = Buffer.from(value);+ const b = Buffer.from(token);+ return a.length === b.length && timingSafeEqual(a, b);+ }++ /** Same origin only: a page from another site cannot post even with its own Host. */+ function originAllowed(origin: string | undefined, port: number): boolean {+ return origin === `http://${HOST}:${port}` || origin === `http://localhost:${port}`;+ }++ async function readLimitedBody(req: IncomingMessage): Promise<string | null> {+ const chunks: Buffer[] = [];+ let size = 0;+ for await (const chunk of req) {+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(String(chunk));+ size += buf.length;+ if (size > CONFIG_BODY_LIMIT) {+ req.resume();+ return null;+ }+ chunks.push(buf);+ }+ return Buffer.concat(chunks).toString("utf8");+ }++ /**+ * Rebuilds the data of the pages somebody is looking at, as `build` does, so+ * the open pages get a change event with the new settings. Best effort: the+ * write already landed, so a failed rebuild must not fail the request.+ */+ async function refreshOpenPages(): Promise<void> {+ const io: Io = {+ prompt: defaultsPrompter,+ out: () => {},+ warn: () => {},+ env,+ now: () => new Date().toISOString(),+ };+ let rebuiltMap = false;+ const registry = await loadRegistry(env);+ if (registry.found && registry.ok) {+ for (const entry of registry.data.projects) {+ const page = pages.get(projectPaths(entry.path).html);+ if (!page || page.clients.size === 0) continue;+ try {+ await buildProject({ dir: entry.path, io, quiet: true });+ rebuiltMap = true;+ } catch {+ // A broken project is already a warning elsewhere; keep serving.+ }+ }+ }+ if (rebuiltMap) return;+ try {+ // `buildProject` rebuilds the panel too; without an open map, do it here.+ await buildPanel({ env, io });+ } catch {+ // An unwritable global directory leaves the old page in place.+ }+ }++ /**+ * `POST /api/config` { key, value }: the panel's only write. Host, Origin,+ * content type and token all have to match, the key must be one the panel may+ * change and the value has to pass the config schema. Anything else is a 4xx+ * and the file stays untouched.+ */+ async function writeConfig(+ req: IncomingMessage,+ res: ServerResponse,+ port: number,+ ): Promise<void> {+ if (+ !originAllowed(req.headers.origin, port) ||+ !tokenMatches(req.headers[CONFIG_TOKEN_HEADER])+ ) {+ respond(res, 403, "forbidden");+ return;+ }+ const type = req.headers["content-type"];+ if (+ typeof type !== "string" ||+ type.split(";")[0]?.trim().toLowerCase() !== "application/json"+ ) {+ respond(res, 415, "content-type must be application/json");+ return;+ }+ const body = await readLimitedBody(req);+ if (body === null) {+ respond(res, 413, "request body too large");+ return;+ }+ let parsed: unknown;+ try {+ parsed = JSON.parse(body);+ } catch {+ respond(res, 400, "invalid JSON");+ return;+ }+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {+ respond(res, 400, "expected a JSON object");+ return;+ }+ const { key, value } = parsed as Record<string, unknown>;+ if (typeof key !== "string" || !isPanelEditableKey(key)) {+ respond(res, 400, `unknown or read-only key: ${String(key)}`);+ return;+ }+ const next = Config.safeParse({ ...(await loadConfig(env)), [key]: value });+ if (!next.success) {+ respond(res, 400, `invalid value for ${key}: ${next.error.issues[0]?.message ?? "rejected"}`);+ return;+ }+ try {+ // A page is waiting: give the lock a moment, not the CLI's usual 10 s.+ await updateConfig((c) => ({ ...c, [key]: next.data[key] }), env, { timeoutMs: 500 });+ } catch (err) {+ respond(res, err instanceof LockBusyError ? 409 : 500, "could not write the config");+ return;+ }+ res.writeHead(200, {+ "content-type": "application/json",+ "cache-control": "no-store",+ });+ res.end(JSON.stringify({ ok: true, key, value: next.data[key] }));+ void refreshOpenPages();+ }+async function handle(req: IncomingMessage, res: ServerResponse): Promise<void> {const port = (server.address() as AddressInfo | null)?.port ?? opts.port;+ if (req.method === "POST") {+ if (!hostAllowed(req.headers.host, port)) {+ respond(res, 403, "forbidden");+ return;+ }+ const url = new URL(req.url ?? "/", `http://${HOST}:${port}`);+ if (url.pathname !== "/api/config") {+ respond(res, 405, "method not allowed");+ return;+ }+ await writeConfig(req, res, port);+ return;+ }if (req.method !== "GET" && req.method !== "HEAD") {respond(res, 405, "method not allowed");return;@@ -242,7 +417,13 @@ export async function startMapServer(opts: MapServerOptions): Promise<MapServer>"content-type": "text/html; charset=utf-8","cache-control": "no-store",});- res.end(req.method === "HEAD" ? undefined : injectLiveMeta(html));+ res.end(+ req.method === "HEAD"+ ? undefined+ : target.panel+ ? injectTokenMeta(injectLiveMeta(html), token)+ : injectLiveMeta(html),+ );}await new Promise<void>((done, fail) => {diff --git a/packages/cli/src/store/stores.ts b/packages/cli/src/store/stores.tsindex 99d29cc..7f33a9d 100644--- a/packages/cli/src/store/stores.ts+++ b/packages/cli/src/store/stores.ts@@ -116,10 +116,19 @@ export const loadConfig = async (env?: NodeJS.ProcessEnv): Promise<Config> => {return cur.found && cur.ok ? cur.data : Config.parse({ schema: CONFIG_SCHEMA });};-export const updateConfig = (fn: (cur: Config) => Config, env?: NodeJS.ProcessEnv) => {+export const updateConfig = (+ fn: (cur: Config) => Config,+ env?: NodeJS.ProcessEnv,+ opts?: LockOptions,+) => {const g = globalPaths(env);- return update(g.config, `${g.config}.lock`, Config, CONFIG_SCHEMA, (cur) =>- fn(cur ?? Config.parse({ schema: CONFIG_SCHEMA })),+ return update(+ g.config,+ `${g.config}.lock`,+ Config,+ CONFIG_SCHEMA,+ (cur) => fn(cur ?? Config.parse({ schema: CONFIG_SCHEMA })),+ opts,);};diff --git a/packages/cli/src/view/model.ts b/packages/cli/src/view/model.tsindex ac97ed0..d6fb84c 100644--- a/packages/cli/src/view/model.ts+++ b/packages/cli/src/view/model.ts@@ -17,6 +17,31 @@ export const DATA_ELEMENT_ID = "codelineage-data";*/export const LIVE_META_NAME = "codelineage-live";+/**+ * Meta tag the local map server puts in the panel page: a random token for this+ * server start that a settings write must echo. Other sites cannot read it, so+ * they cannot post a change even when the host check is bypassed.+ */+export const TOKEN_META_NAME = "codelineage-token";++/**+ * Settings the panel may change over the local server (Story 8.9). The rest are+ * setup-time or security-adjacent and stay on `codelineage config set`.+ */+export const PANEL_EDITABLE_KEYS = [+ "messageSummaries",+ "language",+ "updateEveryTurns",+ "sessionEndCatchUp",+ "catchUpModel",+] as const;++export type PanelEditableKey = (typeof PANEL_EDITABLE_KEYS)[number];++export function isPanelEditableKey(key: string): key is PanelEditableKey {+ return (PANEL_EDITABLE_KEYS as readonly string[]).includes(key);+}+/** Version of the serialized view model (not the session schema). */export const VIEW_SCHEMA = 1;@@ -199,11 +224,17 @@ export interface PanelProject {lineageUrl: string | null;}-/** Global settings, shown read-only on the panel. */+/**+ * Global settings on the panel. `gitPolicy` and `agents` are shown read-only;+ * the keys in `PANEL_EDITABLE_KEYS` are editable when the page comes from the+ * local server (over `file://` everything stays read-only).+ */export interface PanelSettings {language: string;updateEveryTurns: number;sessionEndCatchUp: boolean;+ catchUpModel: string;+ messageSummaries: boolean;gitPolicy: "ignore" | "commit";agents: string[];}diff --git a/packages/cli/src/view/panel.ts b/packages/cli/src/view/panel.tsindex 90ddcdd..164a32b 100644--- a/packages/cli/src/view/panel.ts+++ b/packages/cli/src/view/panel.ts@@ -93,6 +93,8 @@ export async function buildPanel(opts: PanelOptions): Promise<PanelViewModel> {language: config.language,updateEveryTurns: config.updateEveryTurns,sessionEndCatchUp: config.sessionEndCatchUp,+ catchUpModel: config.catchUpModel,+ messageSummaries: config.messageSummaries,gitPolicy: config.gitPolicy,agents: config.agents,},diff --git a/packages/cli/test/backfill.test.ts b/packages/cli/test/backfill.test.tsindex 43856bb..5932354 100644--- a/packages/cli/test/backfill.test.ts+++ b/packages/cli/test/backfill.test.ts@@ -97,6 +97,13 @@ describe("catchUpPrompt", () => {expect(prompt).toContain('{"sessionId": "s1", "nodes": [...]');});+ it("asks for a message summary only when the setting says so", () => {+ const off = catchUpPrompt([turn], undefined, "s1", "auto");+ expect(off).not.toContain("summary: one or two sentences");+ const on = catchUpPrompt([turn], undefined, "s1", "auto", true);+ expect(on).toContain("summary: one or two sentences");+ });+it("lists the existing topics, the replies and the tool counts", () => {const prompt = catchUpPrompt([{ ...turn, replies: ["ok"], tools: { commands: 1, files: ["a.ts"], other: 2 } }],diff --git a/packages/cli/test/config-epoch.test.ts b/packages/cli/test/config-epoch.test.tsindex 97bddbb..d1fbbbf 100644--- a/packages/cli/test/config-epoch.test.ts+++ b/packages/cli/test/config-epoch.test.ts@@ -22,6 +22,7 @@ describe("config", () => {await configGet(undefined, io);expect(io.lines).toContain("updateEveryTurns = 5");expect(io.lines).toContain('catchUpModel = "haiku"');+ expect(io.lines).toContain("messageSummaries = false");await configGet("gitPolicy", io);expect(io.lines.at(-1)).toBe('"ignore"');});@@ -32,12 +33,14 @@ describe("config", () => {await configSet("sessionEndCatchUp", "false", io);await configSet("language", "Turkish", io);await configSet("catchUpModel", "sonnet", io);+ await configSet("messageSummaries", "true", io);await configSet("agents", "claude-code, codex", io);expect(await loadConfig(env)).toMatchObject({updateEveryTurns: 3,sessionEndCatchUp: false,language: "Turkish",catchUpModel: "sonnet",+ messageSummaries: true,agents: ["claude-code", "codex"],});await configSet("agents", '["claude-code"]', io);diff --git a/packages/cli/test/panel.test.ts b/packages/cli/test/panel.test.tsindex 7891854..c86b9a2 100644--- a/packages/cli/test/panel.test.ts+++ b/packages/cli/test/panel.test.ts@@ -84,6 +84,8 @@ describe("buildPanel", () => {language: "auto",updateEveryTurns: 7,sessionEndCatchUp: true,+ catchUpModel: "haiku",+ messageSummaries: false,gitPolicy: "ignore",agents: ["claude-code"],},diff --git a/packages/cli/test/plugin-manifest.test.ts b/packages/cli/test/plugin-manifest.test.tsindex f3ed725..e5fe94c 100644--- a/packages/cli/test/plugin-manifest.test.ts+++ b/packages/cli/test/plugin-manifest.test.ts@@ -5,6 +5,14 @@ const read = async (path: string) =>JSON.parse(await readFile(new URL(path, import.meta.url), "utf8")) as Record<string, unknown>;describe("plugin packaging", () => {+ it("writes a message summary only when the setting is on", async () => {+ const skill = await readFile(new URL("../skills/lineage/SKILL.md", import.meta.url), "utf8");+ // Story 8.9: the branch summary is the outer layer; the per-message summary+ // is off unless the user turns it on, and the skill has to say so.+ expect(skill).toContain("`messageSummaries`");+ expect(skill).toMatch(/ONLY when `messageSummaries`/);+ });+it("keeps the plugin manifest in step with the npm package", async () => {const pkg = await read("../package.json");const plugin = await read("../.claude-plugin/plugin.json");diff --git a/packages/cli/test/server.test.ts b/packages/cli/test/server.test.tsindex cdbcda3..2f01869 100644--- a/packages/cli/test/server.test.ts+++ b/packages/cli/test/server.test.ts@@ -1,8 +1,9 @@-import { mkdir, rm } from "node:fs/promises";+import { mkdir, readFile, rm, writeFile } from "node:fs/promises";import {type ClientRequest,createServer as createHttpServer,get as httpGet,+ request as httpRequest,type IncomingHttpHeaders,type IncomingMessage,} from "node:http";@@ -12,8 +13,10 @@ import { afterEach, beforeEach, describe, expect, it } from "vitest";import { buildProject } from "../src/commands/build.js";import { init } from "../src/commands/init.js";import {+ CONFIG_TOKEN_HEADER,ensureServer,injectLiveMeta,+ injectTokenMeta,type MapServer,mapPageUrl,spawnServerProcess,@@ -21,8 +24,8 @@ import {} 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 { loadConfig, updateConfig } from "../src/store/stores.js";+import { DATA_ELEMENT_ID, LIVE_META_NAME, TOKEN_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>@@ -79,6 +82,63 @@ function request(});}+function postConfig(+ url: string,+ body: string,+ headers: Record<string, string> = {},+): Promise<Reply> {+ const target = new URL(url);+ return new Promise((done, fail) => {+ const req = httpRequest(+ {+ hostname: target.hostname,+ port: target.port,+ path: target.pathname,+ method: "POST",+ headers: {+ "content-type": "application/json",+ "content-length": Buffer.byteLength(body),+ ...headers,+ },+ },+ (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);+ req.end(body);+ });+}++/** The token the panel page carries; every settings write needs it. */+async function panelToken(server: MapServer): Promise<string> {+ const page = await request(`${server.url}/`);+ const match = /<meta name="codelineage-token" content="([^"]+)">/.exec(page.body);+ if (!match?.[1]) throw new Error("panel page has no token");+ return match[1];+}++function configWrite(+ server: MapServer,+ token: string,+ payload: unknown,+ overrides: Record<string, string> = {},+): Promise<Reply> {+ return postConfig(`${server.url}/api/config`, JSON.stringify(payload), {+ origin: `http://127.0.0.1:${server.port}`,+ [CONFIG_TOKEN_HEADER]: token,+ ...overrides,+ });+}+function openEvents(url: string): {waitFor: (needle: string, ms?: number) => Promise<boolean>;close: () => void;@@ -134,6 +194,14 @@ describe("injectLiveMeta", () => {});});+describe("injectTokenMeta", () => {+ it("adds the token meta to the head once", () => {+ const once = injectTokenMeta(TEMPLATE, "abc123");+ expect(once).toContain(`<meta name="${TOKEN_META_NAME}" content="abc123">`);+ expect(injectTokenMeta(once, "abc123")).toBe(once);+ });+});+describe("map server", () => {it("serves the map of a registered project", async () => {const server = await start();@@ -236,6 +304,157 @@ describe("map server", () => {});});+describe("settings write", () => {+ it("gives the panel a token and leaves maps without one", async () => {+ const server = await start();+ const panel = await request(`${server.url}/`);+ expect(panel.body).toContain(`name="${TOKEN_META_NAME}"`);+ const map = await request(mapPageUrl(server.url, root));+ expect(map.body).not.toContain(`name="${TOKEN_META_NAME}"`);+ });++ it("accepts a valid write, stores it and refreshes the panel", async () => {+ const server = await start();+ const token = await panelToken(server);+ const reply = await configWrite(server, token, { key: "messageSummaries", value: true });+ expect(reply.status).toBe(200);+ expect(JSON.parse(reply.body)).toEqual({ ok: true, key: "messageSummaries", value: true });+ expect((await loadConfig(env)).messageSummaries).toBe(true);++ const panel = globalPaths(env).panel;+ const deadline = Date.now() + 3000;+ let html = "";+ while (Date.now() < deadline) {+ html = await readFile(panel, "utf8");+ if (html.includes('"messageSummaries":true')) break;+ await delay(25);+ }+ expect(html).toContain('"messageSummaries":true');+ });++ it("rebuilds an open map so the page picks the new setting up", async () => {+ const server = await start();+ const events = openEvents(`${server.url}/events?dir=${encodeURIComponent(root)}`);+ try {+ expect(await events.waitFor("retry: 1000")).toBe(true);+ const token = await panelToken(server);+ const reply = await configWrite(server, token, { key: "sessionEndCatchUp", value: false });+ expect(reply.status).toBe(200);+ expect(await events.waitFor("event: change")).toBe(true);+ } finally {+ events.close();+ }+ });++ it("rejects a wrong or missing token and writes nothing", async () => {+ const server = await start();+ const token = await panelToken(server);+ expect((await configWrite(server, "nope", { key: "language", value: "tr" })).status).toBe(403);+ expect(+ (+ await configWrite(+ server,+ token,+ { key: "language", value: "tr" },+ {+ [CONFIG_TOKEN_HEADER]: "",+ },+ )+ ).status,+ ).toBe(403);+ expect((await loadConfig(env)).language).toBe("auto");+ });++ it("rejects another origin and a foreign Host", async () => {+ const server = await start();+ const token = await panelToken(server);+ const foreign = await configWrite(+ server,+ token,+ { key: "language", value: "tr" },+ {+ origin: "http://evil.example",+ },+ );+ expect(foreign.status).toBe(403);+ const host = await configWrite(+ server,+ token,+ { key: "language", value: "tr" },+ {+ host: "evil.example:4747",+ },+ );+ expect(host.status).toBe(403);+ expect((await loadConfig(env)).language).toBe("auto");+ });++ it("rejects a read-only key, an unknown key and a bad value type", async () => {+ const server = await start();+ const token = await panelToken(server);+ expect((await configWrite(server, token, { key: "gitPolicy", value: "commit" })).status).toBe(+ 400,+ );+ expect((await configWrite(server, token, { key: "nope", value: 1 })).status).toBe(400);+ expect(+ (await configWrite(server, token, { key: "updateEveryTurns", value: "many" })).status,+ ).toBe(400);+ expect(+ (await configWrite(server, token, { key: "messageSummaries", value: "true" })).status,+ ).toBe(400);+ expect((await loadConfig(env)).gitPolicy).toBe("ignore");+ expect((await loadConfig(env)).messageSummaries).toBe(false);+ });++ it("rejects a body that is valid JSON but not an object", async () => {+ const server = await start();+ const token = await panelToken(server);+ const reply = await postConfig(`${server.url}/api/config`, "null", {+ origin: `http://127.0.0.1:${server.port}`,+ [CONFIG_TOKEN_HEADER]: token,+ });+ expect(reply.status).toBe(400);+ });++ it("answers 409 instead of waiting when the config lock is held", async () => {+ const server = await start();+ const token = await panelToken(server);+ const lock = `${globalPaths(env).config}.lock`;+ await mkdir(lock, { recursive: true });+ await writeFile(join(lock, "owner"), String(process.pid));+ try {+ const reply = await configWrite(server, token, { key: "language", value: "tr" });+ expect(reply.status).toBe(409);+ } finally {+ await rm(lock, { recursive: true, force: true });+ }+ expect((await loadConfig(env)).language).toBe("auto");+ });++ it("rejects a non-JSON body, an oversized body and a wrong method", async () => {+ const server = await start();+ const token = await panelToken(server);+ const wrongType = await configWrite(+ server,+ token,+ { key: "language", value: "tr" },+ {+ "content-type": "text/plain",+ },+ );+ expect(wrongType.status).toBe(415);+ const huge = await configWrite(server, token, { key: "language", value: "x".repeat(5000) });+ expect(huge.status).toBe(413);+ const notJson = await postConfig(`${server.url}/api/config`, "not json", {+ origin: `http://127.0.0.1:${server.port}`,+ [CONFIG_TOKEN_HEADER]: token,+ });+ expect(notJson.status).toBe(400);+ expect((await request(`${server.url}/api/config`)).status).toBe(404);+ expect((await loadConfig(env)).language).toBe("auto");+ });+});+describe("spawnServerProcess", () => {it("runs the CLI detached with hooks silenced", () => {const calls: unknown[][] = [];diff --git a/packages/cli/test/session.test.ts b/packages/cli/test/session.test.tsindex 75e4efc..1c520d8 100644--- a/packages/cli/test/session.test.ts+++ b/packages/cli/test/session.test.ts@@ -3,6 +3,7 @@ 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 { configSet } from "../src/commands/config.js";import { epochAdd } from "../src/commands/epoch.js";import { init } from "../src/commands/init.js";import { readStdin, sessionShow, sessionWrite } from "../src/commands/session.js";@@ -249,6 +250,7 @@ describe("session show", () => {dir: root,project: "p",language: "tr",+ messageSummaries: false,epochs: [{ id: "e2e", title: "E2E" }],session: null,newMessages: null,@@ -275,6 +277,16 @@ describe("session show", () => {});});+ it("reports the messageSummaries setting the agent writes by", async () => {+ await init(root, { name: "p", retention: "keep", language: "auto" }, fakeIo(envFor(dir)));+ await sessionShow(root, "s1", io);+ expect(shown().messageSummaries).toBe(false);++ await configSet("messageSummaries", "true", fakeIo(envFor(dir)));+ await sessionShow(root, "s1", io);+ expect(shown().messageSummaries).toBe(true);+ });+it("lists the user's messages that have no node yet, and stamps their time on write", async () => {await init(root, { name: "p", retention: "keep", language: "auto" }, fakeIo(envFor(dir)));const folder = join(dir, "claude", "projects", "-p");diff --git a/packages/template/src/Panel.tsx b/packages/template/src/Panel.tsxindex 5207ab7..50e8297 100644--- a/packages/template/src/Panel.tsx+++ b/packages/template/src/Panel.tsx@@ -1,11 +1,29 @@-import type { PanelProject, PanelSettings, PanelViewModel } from "../../cli/src/view/model.js";-import { isLivePage } from "./data.js";+import { type FormEvent, useEffect, useState } from "react";+import type {+ PanelEditableKey,+ PanelProject,+ PanelSettings,+ PanelViewModel,+} from "../../cli/src/view/model.js";+import { isLivePage, pageToken, saveSetting } from "./data.js";import { formatTime } from "./format.js";-const SETTING_LABELS: [keyof PanelSettings, string][] = [- ["language", "Language"],- ["updateEveryTurns", "Update every turns"],- ["sessionEndCatchUp", "Catch up on session end"],+interface EditableSpec {+ key: PanelEditableKey;+ label: string;+ kind: "text" | "number" | "boolean";+}++/** The keys the panel may change (Story 8.9); the server enforces the same list. */+const EDITABLE: EditableSpec[] = [+ { key: "messageSummaries", label: "Message summaries", kind: "boolean" },+ { key: "language", label: "Language", kind: "text" },+ { key: "updateEveryTurns", label: "Update every turns", kind: "number" },+ { key: "sessionEndCatchUp", label: "Catch up on session end", kind: "boolean" },+ { key: "catchUpModel", label: "Catch-up model", kind: "text" },+];++const READ_ONLY: [keyof PanelSettings, string][] = [["gitPolicy", "Git policy"],["agents", "Agents"],];@@ -25,7 +43,90 @@ function settingText(value: PanelSettings[keyof PanelSettings]): string {return String(value);}+/**+ * One setting with a control and a Save button. The draft follows the model, so+ * a live page swap after a rebuild shows the value the server actually stored.+ */+function EditableSetting({+ spec,+ value,+ token,+}: {+ spec: EditableSpec;+ value: PanelSettings[PanelEditableKey];+ token: string;+}) {+ const [draft, setDraft] = useState(String(value));+ const [checked, setChecked] = useState(Boolean(value));+ const [saving, setSaving] = useState(false);+ const [status, setStatus] = useState<string | null>(null);+ const [error, setError] = useState<string | null>(null);++ useEffect(() => {+ setDraft(String(value));+ setChecked(Boolean(value));+ setSaving(false);+ setStatus(null);+ setError(null);+ }, [value]);++ const dirty = spec.kind === "boolean" ? checked !== Boolean(value) : draft !== String(value);++ async function submit(event: FormEvent): Promise<void> {+ event.preventDefault();+ if (!dirty || saving) return;+ const next = spec.kind === "boolean" ? checked : spec.kind === "number" ? Number(draft) : draft;+ setSaving(true);+ setStatus(null);+ setError(null);+ try {+ await saveSetting(spec.key, next, token);+ setStatus("Saved");+ } catch (err) {+ setError(err instanceof Error ? err.message : String(err));+ } finally {+ setSaving(false);+ }+ }++ const id = `setting-${spec.key}`;+ return (+ <div>+ <dt>+ <label htmlFor={id}>{spec.label}</label>+ </dt>+ <dd>+ <form className="setting-form" onSubmit={submit}>+ {spec.kind === "boolean" ? (+ <input+ id={id}+ type="checkbox"+ checked={checked}+ onChange={(event) => setChecked(event.target.checked)}+ />+ ) : (+ <input+ id={id}+ type={spec.kind === "number" ? "number" : "text"}+ value={draft}+ onChange={(event) => setDraft(event.target.value)}+ />+ )}+ <button type="submit" disabled={!dirty || saving}>+ {saving ? "Saving…" : "Save"}+ </button>+ {status ? <span className="setting-status">{status}</span> : null}+ {error ? <span className="setting-error">{error}</span> : null}+ </form>+ </dd>+ </div>+ );+}+export function Panel({ model }: { model: PanelViewModel }) {+ // No token over `file://`: the page cannot write, so the settings stay text.+ const token = isLivePage() ? pageToken() : null;+return (<main><header className="project">@@ -77,9 +178,28 @@ export function Panel({ model }: { model: PanelViewModel }) {<section className="settings" aria-label="Settings"><h2>Settings</h2>- <p className="muted">Read-only; change them with `codelineage config set`.</p>+ <p className="muted">+ {token+ ? "A change here applies to new builds and chats."+ : "Read-only; change them with `codelineage config set`, or run `codelineage open` to edit them here."}+ </p><dl>- {SETTING_LABELS.map(([key, label]) => (+ {EDITABLE.map((spec) =>+ token ? (+ <EditableSetting+ key={spec.key}+ spec={spec}+ value={model.settings[spec.key]}+ token={token}+ />+ ) : (+ <div key={spec.key}>+ <dt>{spec.label}</dt>+ <dd>{settingText(model.settings[spec.key])}</dd>+ </div>+ ),+ )}+ {READ_ONLY.map(([key, label]) => (<div key={key}><dt>{label}</dt><dd>{settingText(model.settings[key])}</dd>diff --git a/packages/template/src/data.ts b/packages/template/src/data.tsindex 097a6e3..ead572b 100644--- a/packages/template/src/data.ts+++ b/packages/template/src/data.ts@@ -1,4 +1,9 @@-import { DATA_ELEMENT_ID, LIVE_META_NAME, type PageModel } from "../../cli/src/view/model.js";+import {+ DATA_ELEMENT_ID,+ LIVE_META_NAME,+ type PageModel,+ TOKEN_META_NAME,+} from "../../cli/src/view/model.js";/** Parses and checks the JSON contract; throws when the shape is not a page. */export function parseViewModel(text: string): PageModel {@@ -38,3 +43,29 @@ export async function loadViewModel(doc: Document = document): Promise<PageModelexport function isLivePage(doc: Document = document): boolean {return doc.querySelector(`meta[name="${LIVE_META_NAME}"]`) !== null;}++/**+ * The per-server token the local server puts in the panel page. Null over+ * `file://` (and anywhere the page did not come from the server), which is what+ * keeps the settings read-only there.+ */+export function pageToken(doc: Document = document): string | null {+ const content = doc+ .querySelector(`meta[name="${TOKEN_META_NAME}"]`)+ ?.getAttribute("content")+ ?.trim();+ return content ? content : null;+}++/** One settings write; the server validates the key, the value and the token. */+export async function saveSetting(key: string, value: unknown, token: string): Promise<void> {+ const response = await fetch("/api/config", {+ method: "POST",+ headers: { "content-type": "application/json", "x-codelineage-token": token },+ body: JSON.stringify({ key, value }),+ });+ if (!response.ok) {+ const text = (await response.text()).trim();+ throw new Error(text || `could not save (HTTP ${response.status})`);+ }+}diff --git a/packages/template/src/styles.css b/packages/template/src/styles.cssindex b771f3b..ae4269f 100644--- a/packages/template/src/styles.css+++ b/packages/template/src/styles.css@@ -944,3 +944,52 @@ time {color: var(--muted);font-size: 12px;}++/* Settings the panel can change when the local server serves it (Story 8.9). */+.setting-form {+ display: flex;+ align-items: center;+ gap: 8px;+}++.setting-form input[type="text"],+.setting-form input[type="number"] {+ width: 150px;+ padding: 3px 6px;+ color: var(--text);+ background: var(--bg);+ border: 1px solid var(--line);+ border-radius: 6px;+ font: inherit;+ font-size: 13px;+}++.setting-form input[type="checkbox"] {+ margin: 0;+}++.setting-form button {+ padding: 3px 10px;+ color: var(--text);+ background: var(--panel);+ border: 1px solid var(--line);+ border-radius: 6px;+ font: inherit;+ font-size: 13px;+ cursor: pointer;+}++.setting-form button:disabled {+ opacity: 0.45;+ cursor: default;+}++.setting-status {+ color: var(--muted);+ font-size: 12px;+}++.setting-error {+ color: var(--l5);+ font-size: 12px;+}diff --git a/specs/codelineage-mvp.md b/specs/codelineage-mvp.mdindex e14484c..45537bd 100644--- a/specs/codelineage-mvp.md+++ b/specs/codelineage-mvp.md@@ -51,7 +51,9 @@ these records into static HTML:from all active sessions. A session is **active** while its `updatedAt` iswithin 7 days of the build, newest first; duplicate item texts are shown once.- **Panel** (global): every registered project as a small status card, with quick- switching into each project map. Settings are shown read-only.+ switching into each project map. Settings are editable on the page the local+ server serves (`POST /api/config`, same-origin, per-server token) and read-only+ from `file://`.Sessions are not a separate view. A session is a level of the project tree.@@ -269,9 +271,12 @@ Each update costs agent tokens (the user's subscription or API usage).Settings in `config.json`: `language`, `updateEveryTurns`, `sessionEndCatchUp`,`catchUpModel` (model for the headless catch-up and backfill, default `haiku`),+`messageSummaries` (write a per-message summary; default `false`),`serverPort` (local map server, default 4747),`gitPolicy`, `agents`, `setupHintOff` (project roots where the SessionStart setup-offer stays silent).+offer stays silent). The panel may change `language`, `updateEveryTurns`,+`sessionEndCatchUp`, `catchUpModel` and `messageSummaries` over the local server;+everything else stays on `codelineage config set`.## Privacy@@ -333,11 +338,11 @@ offer stays silent).and a local map server as the default way `open` shows a map: one backgroundserver per user on `127.0.0.1`, serving only registered projects' maps and thepanel, refreshing open pages on change, exiting after 30 idle minutes; opening- the file directly is only the fallback when it cannot start.+ the file directly is only the fallback when it cannot start. The panel edits+ the safe settings over the same server.## Later- Codex adapter (its hooks and session retention still need research)-- Editing settings from the panel (needs writes through the local server)- A Herdr usage section in the README- Video or other "explainer" outputs