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(map): show how much code landed per message, and what you have read
Erencf07cc33cc7c
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0f61411..c7ff75f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]### Added+- The map shows how much code landed after a message: each row with linked commits carries a `+1 240 −80 · 14 files` chip from `git diff --numstat` (the `Thought:` trailer union with the recorded commits, a commit counted once), the details panel states the same numbers and offers a read toggle, and rows you have not marked read above `bigChangeLines` (default 300) get a quiet highlight. The map head gains an "Unread" filter listing unread messages most code first, `cogit log --unread` prints the same list, and the panel card counts a project's unread big changes. The marks live in `.cogit/state/read.json` (local, never committed or shared) and are written by the local map server; nothing reads or classifies message text.- `cogit pr [base]` turns a branch into a review-ready Markdown description from the thoughts behind its commits: the sessions' goals, each thought's title, summary, decisions and rejected options, its commits and changed files, and the commits with no recorded thought (`thought h… not recorded yet` when the record has not caught up). The base is the upstream's merge base, else `main`, else `master`, with a clear error when none resolves; `--json` prints the same content as data and `--copy` puts the Markdown on the clipboard. It reads only the record — never the conversation text or the user's prompts — and stays under GitHub's body limit by dropping file lists first, then summaries, saying what was left out. The record skill hands its output over instead of writing a PR description itself.### Changeddiff --git a/docs/schema/config.json b/docs/schema/config.jsonindex 1962db2..23f644d 100644--- a/docs/schema/config.json+++ b/docs/schema/config.json@@ -69,6 +69,12 @@"minimum": 1,"maximum": 8760},+ "bigChangeLines": {+ "default": 300,+ "type": "integer",+ "minimum": 1,+ "maximum": 1000000+ },"agents": {"default": ["claude-code"@@ -101,6 +107,7 @@"shareConversations","recordCommit","trailerMaxAgeHours",+ "bigChangeLines","agents","setupHintOff"],diff --git a/docs/schema/session.json b/docs/schema/session.jsonindex 4fc4d45..9a4de0b 100644--- a/docs/schema/session.json+++ b/docs/schema/session.json@@ -308,6 +308,32 @@"type": "string","format": "date-time","pattern": "^(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))T(?:(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d(?:\\.\\d+)?(?:Z|([+-](?:[01]\\d|2[0-3]):[0-5]\\d)))$"+ },+ "change": {+ "type": "object",+ "properties": {+ "added": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ },+ "removed": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ },+ "files": {+ "type": "integer",+ "minimum": 0,+ "maximum": 9007199254740991+ }+ },+ "required": [+ "added",+ "removed",+ "files"+ ],+ "additionalProperties": false}},"required": [diff --git a/packages/cli/src/commands/build.ts b/packages/cli/src/commands/build.tsindex 756cb16..988e07d 100644--- a/packages/cli/src/commands/build.ts+++ b/packages/cli/src/commands/build.ts@@ -1,5 +1,6 @@import { type ChatTurn, defaultAgent } from "../agents/index.js";import {+ type CommitChange,findGitRoot,projectFiles,readCommitFiles,@@ -16,6 +17,7 @@ import {} from "../messages.js";import { redactDeep } from "../redact.js";import type { Session } from "../schema/session.js";+import { readProjectChanges } from "../store/changes.js";import {appendConversationHashes,appendConversationTurns,@@ -25,9 +27,11 @@ import { applyEvents, readEvents } from "../store/events.js";import { atomicWrite } from "../store/fs.js";import { withLock } from "../store/lock.js";import { projectPaths } from "../store/paths.js";+import { readReadState } from "../store/read-state.js";import { resolveProjectRoot } from "../store/root.js";import { loadAllSessions, loadConfig, loadProject } from "../store/stores.js";import { attachThoughtTrailers, earliestSessionStart, readThoughtTrailers } from "../thought.js";+import { attachChanges } from "../view/change.js";import { buildFileHistory, modelSessions } from "../view/files.js";import { buildViewModel, embedViewModel } from "../view/lineage.js";import type { LineageViewModel, ViewChatTurn, ViewPendingMessage } from "../view/model.js";@@ -204,6 +208,8 @@ interface CommitInfo {subjects: Map<string, string>;/** Project-relative files per recorded hash, for the file history (Story 8.15). */files: Map<string, string[]>;+ /** Numstat totals per recorded hash, for "how much code landed" (Story 10.3). */+ changes: Map<string, CommitChange>;}/**@@ -218,14 +224,15 @@ async function commitInfo(root: string, sessions: Session[]): Promise<CommitInfofor (const hash of node.commits ?? []) hashes.add(hash);}}- if (hashes.size === 0) return { subjects: new Map(), files: new Map() };+ if (hashes.size === 0) return { subjects: new Map(), files: new Map(), changes: new Map() };const gitRoot = await findGitRoot(root);- if (gitRoot === undefined) return { subjects: new Map(), files: new Map() };- const [subjects, files] = await Promise.all([+ if (gitRoot === undefined) return { subjects: new Map(), files: new Map(), changes: new Map() };+ const [subjects, files, changes] = await Promise.all([readCommitSubjects(gitRoot, hashes),readCommitFiles(gitRoot, hashes),+ readProjectChanges(root, hashes),]);- return { subjects, files: projectFiles(gitRoot, root, files) };+ return { subjects, files: projectFiles(gitRoot, root, files), changes };}/**@@ -278,9 +285,13 @@ export async function buildProject(opts: BuildOptions): Promise<LineageViewModel});const withThoughts = attachThoughtTrailers(views.sessions, trailers);const commits = await commitInfo(root, withThoughts);+ // Story 10.3: each message carries the numstat totals of its linked+ // commits. A project outside git simply has no numbers to show.+ const withChanges = attachChanges(withThoughts, commits.changes);+ const read = await readReadState(root);const built = buildViewModel({project: project.data,- sessions: withThoughts,+ sessions: withChanges,path: root,generatedAt,transcripts: new Set(transcripts.keys()),@@ -295,6 +306,7 @@ export async function buildProject(opts: BuildOptions): Promise<LineageViewModelunrecorded: config.sessionEndCatchUp ? undefined : views.unrecorded,});built.switcher = switcher;+ built.read = [...read].sort();// The files view (8.15) unions each message's own files with the files of// its commits, so a message the agent listed no paths for still lands.built.files = buildFileHistory(modelSessions(built), commits.files);diff --git a/packages/cli/src/commands/log.ts b/packages/cli/src/commands/log.tsindex 5afefe2..b13aed9 100644--- a/packages/cli/src/commands/log.ts+++ b/packages/cli/src/commands/log.ts@@ -2,7 +2,9 @@ import { findGitRoot, projectFiles, readCommitFiles, readCommitSubjects } from "import { CliError, type Io } from "../io.js";import { readSessionMessages, type SessionMessage, upgradeSessionIds } from "../messages.js";import type { LineageNode, Session } from "../schema/session.js";+import { readProjectChanges } from "../store/changes.js";import { applyEvents, readEvents } from "../store/events.js";+import { readReadState } from "../store/read-state.js";import { resolveProjectRoot } from "../store/root.js";import { loadAllSessions, loadProject } from "../store/stores.js";import {@@ -11,6 +13,7 @@ import {readCommitThought,readThoughtTrailers,} from "../thought.js";+import { formatChange, messageChange, type UnreadMessage, unreadMessages } from "../view/change.js";import { buildFileHistory, type FileSourceSession } from "../view/files.js";import { buildMessages } from "../view/lineage.js";import type { ViewFile, ViewNode } from "../view/model.js";@@ -718,6 +721,59 @@ export async function log(opts: LogCommandOptions): Promise<LogModel> {return model;}+export interface UnreadLogOptions {+ dir: string;+ io: Io;+ json?: boolean;+}++/**+ * `cogit log --unread` (Story 10.3): every unread message whose commits resolve+ * in git, most code first, with the same numstat numbers the map shows. The+ * mark is the user's own (`cogit open` toggles it); nothing here reads message+ * text to guess whether a message was "really" understood.+ */+export async function logUnread(opts: UnreadLogOptions): Promise<UnreadMessage[]> {+ const root = await openProject(opts.dir);+ const sessions = await loadEffectiveSessions(root, opts.io);+ const hashes = new Set(+ sessions.flatMap((entry) => entry.messages.flatMap((message) => message.commits ?? [])),+ );+ const changes = hashes.size === 0 ? new Map() : await readProjectChanges(root, hashes);+ const read = await readReadState(root);+ const unread = unreadMessages(+ sessions.map(({ session, messages }) => ({+ sessionId: session.sessionId,+ title: session.title,+ startedAt: session.startedAt,+ nodes: messages.map((message) => ({+ ...message,+ change: messageChange(message.commits, changes),+ })),+ })),+ read,+ );+ if (opts.json === true) {+ opts.io.out(JSON.stringify(unread, null, 2));+ return unread;+ }+ for (const line of formatUnread(unread)) opts.io.out(line);+ return unread;+}++/** The plain-text `--unread` list, one line per message, most code first. */+export function formatUnread(messages: readonly UnreadMessage[]): string[] {+ if (messages.length === 0) return ["No unread messages with linked commits."];+ return messages.map((message) => {+ const parts = [+ ` ${shortHash(message.messageId)} ${message.label} ${clock(message.at)} ` ++ `${formatChange(message.change)} ${oneLine(message.title)}`,+ ];+ parts.push(` · ${oneLine(message.sessionTitle)}`);+ return parts.join("");+ });+}+/*** `./src\a.ts` and `src/a.ts` name the same file; the model stores forward-slash* paths without a leading `./` (Story 8.15).diff --git a/packages/cli/src/git.ts b/packages/cli/src/git.tsindex 5a033f1..7d2fe14 100644--- a/packages/cli/src/git.ts+++ b/packages/cli/src/git.ts@@ -273,6 +273,111 @@ export async function readCommitFiles(return out;}+/** A commit with its numstat totals and the files it changed. */+export interface CommitChange {+ /** The full hash, so two recorded hashes of one commit count once. */+ full: string;+ added: number;+ removed: number;+ /** Repository-relative paths, in git's order (a binary file counts as one). */+ files: string[];+}++interface ChangeSection {+ full: string;+ added: number;+ removed: number;+ files: string[];+}++/**+ * Parses `%x00%H` + `--numstat` output: a NUL-prefixed hash line starts a+ * commit, `added\tremoved\tpath` lines follow until the next hash. A binary file+ * prints `-` for both counts; it still counts as a file touched.+ */+function parseChangeSections(stdout: string): ChangeSection[] {+ const out: ChangeSection[] = [];+ let current: ChangeSection | null = null;+ for (const line of stdout.split("\n")) {+ if (line.startsWith("\0")) {+ const full = line.slice(1).trim();+ current = /^[0-9a-f]{40}$/.test(full) ? { full, added: 0, removed: 0, files: [] } : null;+ if (current) out.push(current);+ continue;+ }+ if (current === null) continue;+ const parts = line.split("\t");+ if (parts.length < 3) continue;+ const [added, removed, ...rest] = parts;+ const path = rest.join("\t").trim();+ if (path === "") continue;+ current.added += Number.parseInt(added ?? "", 10) || 0;+ current.removed += Number.parseInt(removed ?? "", 10) || 0;+ current.files.push(path);+ }+ return out;+}++/**+ * Lines added and removed, plus the files changed, for each given commit+ * (Story 10.3: how much code landed after a message). Keyed by the hash the+ * record holds; a commit git no longer knows is left out, never an error —+ * same policy as `readCommitSubjects` and `readCommitFiles`.+ */+export async function readCommitChanges(+ root: string,+ hashes: Iterable<string>,+): Promise<Map<string, CommitChange>> {+ const wanted = [...new Set(hashes)];+ const out = new Map<string, CommitChange>();+ if (wanted.length === 0) return out;++ const remember = (entries: ChangeSection[]): void => {+ for (const hash of wanted) {+ const commit = entries.find(+ (entry) => entry.full.startsWith(hash) || hash.startsWith(entry.full.slice(0, 7)),+ );+ if (commit && !out.has(hash))+ out.set(hash, {+ full: commit.full,+ added: commit.added,+ removed: commit.removed,+ files: commit.files,+ });+ }+ };++ try {+ const { stdout } = await exec("git", [+ "-C",+ root,+ "log",+ "--no-walk=unsorted",+ "--format=%x00%H",+ "--numstat",+ ...wanted,+ ]);+ remember(parseChangeSections(stdout));+ } catch {+ for (const hash of wanted) {+ try {+ const { stdout } = await exec("git", [+ "-C",+ root,+ "show",+ "--format=%x00%H",+ "--numstat",+ hash,+ ]);+ remember(parseChangeSections(stdout));+ } catch {+ // gone from this repository (rebased away, or another checkout)+ }+ }+ }+ return out;+}+/** A commit's short hash, computed when git printed only the full one. */function commitShort(commit: CommitFiles): string {return commit.short === "" ? commit.full.slice(0, 7) : commit.short;diff --git a/packages/cli/src/program.ts b/packages/cli/src/program.tsindex ec8f634..314fdef 100644--- a/packages/cli/src/program.ts+++ b/packages/cli/src/program.ts@@ -14,7 +14,7 @@ import {import { epochAdd } from "./commands/epoch.js";import { hooksInstall, hooksUninstall } from "./commands/hooks.js";import { type InitOptions, init } from "./commands/init.js";-import { formatShow, log, logFile, show } from "./commands/log.js";+import { formatShow, log, logFile, logUnread, show } from "./commands/log.js";import { migrateIds } from "./commands/migrate.js";import { openPanel, openProject } from "./commands/open.js";import { pr } from "./commands/pr.js";@@ -101,8 +101,12 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =.option("-n, --number <count>", "at most this many messages", positiveCount).option("--branches", "only the branch summaries (the compressed view)").option("--file <path>", "only messages that touched this file (its history)")+ .option("--unread", "unread messages with commits, most code first").option("--json", "print JSON instead of text")- .addHelpText("after", examples("cogit log -n 10", "cogit log --file src/auth.ts"))+ .addHelpText(+ "after",+ examples("cogit log -n 10", "cogit log --file src/auth.ts", "cogit log --unread"),+ ).action(run(async (@@ -113,10 +117,15 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =number?: number;branches?: boolean;file?: string;+ unread?: boolean;json?: boolean;},) => {const target = opts.dir ?? dir;+ if (opts.unread === true) {+ await logUnread({ dir: target, io: makeIo(false), json: opts.json === true });+ return;+ }if (opts.file !== undefined) {await logFile({dir: target,diff --git a/packages/cli/src/schema/config.ts b/packages/cli/src/schema/config.tsindex 96b3e11..bb82e43 100644--- a/packages/cli/src/schema/config.ts+++ b/packages/cli/src/schema/config.ts@@ -40,6 +40,12 @@ export const Config = z.object({* A commit made hours after the last message is probably not that message.*/trailerMaxAgeHours: z.int().min(1).max(8760).default(6),+ /**+ * An unread message whose commits changed at least this many lines gets the+ * quiet "a lot landed here" highlight on the map (Story 10.3). A threshold,+ * not a judgement: it never hides or ranks anything by itself.+ */+ bigChangeLines: z.int().min(1).max(1_000_000).default(300),agents: z.array(z.string().min(1)).default(["claude-code"]),/** Project roots ("don't ask again" in this project) where the setup hint stays silent. */setupHintOff: z.array(z.string().min(1)).default([]),diff --git a/packages/cli/src/schema/session.ts b/packages/cli/src/schema/session.tsindex 30eeb5a..e0e678b 100644--- a/packages/cli/src/schema/session.ts+++ b/packages/cli/src/schema/session.ts@@ -77,6 +77,18 @@ export const LineageNode = z.object({addedAt: IsoDate.optional(),/** When `session write` last added or changed this node; set by the CLI, never by the agent. */touchedAt: IsoDate.optional(),+ /**+ * Numstat totals of the node's commits, attached at read time from git+ * (Story 10.3). Never stored in the record: it is derived, so the record+ * stays small and the numbers stay current after a rebase.+ */+ change: z+ .object({+ added: z.number().int().min(0),+ removed: z.number().int().min(0),+ files: z.number().int().min(0),+ })+ .optional(),});export const PendingItem = z.object({@@ -111,7 +123,11 @@ export const Session = z.object({});/** In input, a missing parent keeps the stored one (null for a new node). */-export const LineageNodeInput = LineageNode.omit({ addedAt: true, touchedAt: true }).extend({+export const LineageNodeInput = LineageNode.omit({+ addedAt: true,+ touchedAt: true,+ change: true,+}).extend({parent: MessageRef.nullable().optional(),});diff --git a/packages/cli/src/server.ts b/packages/cli/src/server.tsindex 22b6378..698857e 100644--- a/packages/cli/src/server.ts+++ b/packages/cli/src/server.ts@@ -18,6 +18,7 @@ import { Config } from "./schema/config.js";import { refreshShareConversations } from "./share.js";import { LockBusyError } from "./store/lock.js";import { globalPaths, projectPaths } from "./store/paths.js";+import { setMessageRead } from "./store/read-state.js";import { loadConfig, loadRegistry, updateConfig } from "./store/stores.js";import { isPanelEditableKey, LIVE_META_NAME, TOKEN_META_NAME } from "./view/model.js";import { buildPanel, panelSettings } from "./view/panel.js";@@ -461,6 +462,71 @@ export async function startMapServer(opts: MapServerOptions): Promise<MapServer>void refreshOpenPages();}+ /**+ * `POST /api/read` { dir, id, read } (Story 10.3): the map's read toggle. It+ * writes only the project's local state file; the page updates itself, and+ * the next rebuild embeds the new list. Same Host, Origin, content-type and+ * token checks as a settings write, and `dir` must be a registered project.+ */+ async function writeRead(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 { dir, id, read } = parsed as Record<string, unknown>;+ if (typeof dir !== "string" || typeof id !== "string" || typeof read !== "boolean") {+ respond(res, 400, "expected { dir, id, read }");+ return;+ }+ if (!/^h[0-9a-f]{12}$/.test(id)) {+ respond(res, 400, "id must be a message id (h plus 12 hex)");+ return;+ }+ const root = await registeredRoot(env, dir);+ if (root === null) {+ respond(res, 403, "not a registered project");+ return;+ }+ try {+ await setMessageRead(root, id, read);+ } catch {+ respond(res, 500, "could not write the read state");+ return;+ }+ res.writeHead(200, {+ "content-type": "application/json",+ "cache-control": "no-store",+ });+ res.end(JSON.stringify({ ok: true, id, read }));+ }+async function handle(req: IncomingMessage, res: ServerResponse): Promise<void> {const port = (server.address() as AddressInfo | null)?.port ?? opts.port;if (req.method === "POST") {@@ -480,6 +546,10 @@ export async function startMapServer(opts: MapServerOptions): Promise<MapServer>void close();return;}+ if (url.pathname === "/api/read") {+ await writeRead(req, res, port);+ return;+ }if (url.pathname !== "/api/config") {respond(res, 405, "method not allowed");return;diff --git a/packages/cli/src/store/changes.ts b/packages/cli/src/store/changes.tsnew file mode 100644index 0000000..86e6863--- /dev/null+++ b/packages/cli/src/store/changes.ts@@ -0,0 +1,30 @@+import { type CommitChange, findGitRoot, projectFiles, readCommitChanges } from "../git.js";++/**+ * Numstat totals per commit, with file paths rebased onto the project (Story+ * 10.3). A project inside a larger repository must not count files outside its+ * own directory, so the paths go through the same projection the file history+ * uses. A commit whose files all sit outside the project keeps its line counts+ * but no files — it changed nothing here.+ */+export async function readProjectChanges(+ root: string,+ hashes: Iterable<string>,+): Promise<Map<string, CommitChange>> {+ const wanted = [...new Set(hashes)];+ if (wanted.length === 0) return new Map();+ const gitRoot = await findGitRoot(root);+ if (gitRoot === undefined) return new Map();+ const raw = await readCommitChanges(gitRoot, wanted);+ if (gitRoot === root) return raw;+ const files = projectFiles(+ gitRoot,+ root,+ new Map([...raw].map(([hash, change]) => [hash, change.files])),+ );+ const out = new Map<string, CommitChange>();+ for (const [hash, change] of raw) {+ out.set(hash, { ...change, files: files.get(hash) ?? [] });+ }+ return out;+}diff --git a/packages/cli/src/store/paths.ts b/packages/cli/src/store/paths.tsindex d16d81e..db0e867 100644--- a/packages/cli/src/store/paths.ts+++ b/packages/cli/src/store/paths.ts@@ -32,6 +32,12 @@ export function projectPaths(root: string) {conversations: join(base, "conversations"),conversation: (id: string) => join(base, "conversations", `${id}.jsonl.gz`),state: (id: string) => join(base, "state", `${id}.json`),+ /**+ * Which messages this user has marked read (Story 10.3). Local per-user+ * state: never committed, never shared (`state/` stays ignored by both+ * policies).+ */+ readState: join(base, "state", "read.json"),locks: join(base, "locks"),/** Where the skill drops session JSON for `session write --file`. */inbox: (id: string) => join(base, "inbox", `${id}.json`),diff --git a/packages/cli/src/store/read-state.ts b/packages/cli/src/store/read-state.tsnew file mode 100644index 0000000..a6572ad--- /dev/null+++ b/packages/cli/src/store/read-state.ts@@ -0,0 +1,54 @@+import { z } from "zod";+import { atomicWriteJson, readJson } from "./fs.js";+import { withLock } from "./lock.js";+import { projectPaths } from "./paths.js";++/**+ * Which messages the user has read (Story 10.3). The mark is a fact the user+ * states, not something cogit infers: no message text is read or classified.+ * It is local per-user state under `.cogit/state/`, never committed and never+ * shared, so one person's reading never marks a teammate's map.+ */++export const READ_STATE_SCHEMA = 1;++const MESSAGE_ID = /^h[0-9a-f]{12}$/;++export const ReadState = z.object({+ schema: z.literal(READ_STATE_SCHEMA),+ /** Read message ids (`h` plus 12 hex). */+ read: z.array(z.string().regex(MESSAGE_ID)).default([]),+});++export type ReadState = z.infer<typeof ReadState>;++/** The ids marked read. A missing or unreadable file is "nothing read yet". */+export async function readReadState(root: string): Promise<Set<string>> {+ const read = await readJson(projectPaths(root).readState);+ if (!read.found || "error" in read) return new Set();+ const parsed = ReadState.safeParse(read.value);+ return new Set(parsed.success ? parsed.data.read : []);+}++/**+ * Marks one message read or unread. The file is derived state: an unreadable+ * one is replaced rather than blocking the toggle, and the list is sorted so+ * two toggles never reorder the file into a noisy diff (it stays ignored).+ */+export async function setMessageRead(root: string, id: string, read: boolean): Promise<void> {+ if (!MESSAGE_ID.test(id)) throw new Error(`not a message id: ${id}`);+ const p = projectPaths(root);+ await withLock(+ p.lock("read-state"),+ async () => {+ const ids = await readReadState(root);+ if (read) ids.add(id);+ else ids.delete(id);+ await atomicWriteJson(p.readState, {+ schema: READ_STATE_SCHEMA,+ read: [...ids].sort(),+ });+ },+ { timeoutMs: 2000 },+ );+}diff --git a/packages/cli/src/view/change.ts b/packages/cli/src/view/change.tsnew file mode 100644index 0000000..1191025--- /dev/null+++ b/packages/cli/src/view/change.ts@@ -0,0 +1,171 @@+import type { CommitChange } from "../git.js";+import type { ViewChange } from "./model.js";++/**+ * How much code landed after a message (Story 10.3), deterministic and pure:+ * the commits linked to the message — the `Thought:` trailer union with the+ * commits the record lists — and git's numstat totals for them. Cogit never+ * reads the message text, so a long sentence and "go on" are treated alike.+ * The numbers are facts for the reader to judge; nothing here calls them risky.+ */++/** The subset of a record/view node this module needs; both shapes fit. */+export interface ChangeNode {+ id: string;+ kind: string;+ title: string;+ label?: string | undefined;+ at?: string | undefined;+ commits?: string[] | undefined;+ change?: ViewChange | undefined;+}++export interface ChangeSession {+ sessionId: string;+ title: string;+ startedAt: string;+ nodes: readonly ChangeNode[];+}++/**+ * One message's totals: the union of its linked commits, each commit counted+ * once (its full hash decides), files deduped across commits. Undefined when no+ * linked commit resolves in git — the map then shows nothing, not "0".+ */+export function messageChange(+ commits: readonly string[] | undefined,+ changes: ReadonlyMap<string, CommitChange>,+): ViewChange | undefined {+ if (commits === undefined || commits.length === 0) return undefined;+ const seen = new Set<string>();+ const files = new Set<string>();+ let added = 0;+ let removed = 0;+ for (const hash of commits) {+ const change = changes.get(hash);+ if (change === undefined || seen.has(change.full)) continue;+ seen.add(change.full);+ added += change.added;+ removed += change.removed;+ for (const file of change.files) files.add(file);+ }+ if (seen.size === 0) return undefined;+ return { added, removed, files: files.size };+}++/** The record with a `change` on every message whose commits git resolves. */+export function attachChanges<N extends ChangeNode, S extends { nodes: readonly N[] }>(+ sessions: readonly S[],+ changes: ReadonlyMap<string, CommitChange>,+): S[] {+ if (changes.size === 0) return sessions.map((session) => session);+ return sessions.map((session) => {+ let changed = false;+ const nodes = session.nodes.map((node) => {+ if (node.kind !== "message") return node;+ const change = messageChange(node.commits, changes);+ if (change === undefined) {+ if (node.change === undefined) return node;+ changed = true;+ const { change: _dropped, ...rest } = node;+ return rest as N;+ }+ changed = true;+ return { ...node, change } as N;+ });+ return (changed ? { ...session, nodes } : session) as S;+ });+}++/** One unread message with code behind it, as the map view and `log --unread` list it. */+export interface UnreadMessage {+ sessionId: string;+ sessionTitle: string;+ sessionStartedAt: string;+ messageId: string;+ label: string;+ title: string;+ at?: string | undefined;+ change: ViewChange;+}++/** Total lines a change touched; the sort key ("most code first"). */+export function changeLines(change: ViewChange): number {+ return change.added + change.removed;+}++/** True for a message the user has not read whose code crossed the threshold. */+export function isBigChange(change: ViewChange, threshold: number): boolean {+ return changeLines(change) >= threshold;+}++/** Messages with commits that are not marked read, most code first. */+export function unreadMessages(+ sessions: readonly ChangeSession[],+ read: ReadonlySet<string>,+): UnreadMessage[] {+ const out: UnreadMessage[] = [];+ for (const session of sessions) {+ for (const node of session.nodes) {+ if (node.kind !== "message" || node.change === undefined) continue;+ if (read.has(node.id)) continue;+ out.push({+ sessionId: session.sessionId,+ sessionTitle: session.title,+ sessionStartedAt: session.startedAt,+ messageId: node.id,+ label: node.label ?? node.id,+ title: node.title,+ ...(node.at === undefined ? {} : { at: node.at }),+ change: node.change,+ });+ }+ }+ return out.sort(+ (a, b) =>+ changeLines(b.change) - changeLines(a.change) ||+ b.change.files - a.change.files ||+ a.title.localeCompare(b.title) ||+ a.messageId.localeCompare(b.messageId),+ );+}++/** The page's shape: `ViewSession` carries `messages` rather than `nodes`. */+export interface ViewChangeSession {+ sessionId: string;+ title: string;+ startedAt: string;+ messages: readonly ChangeNode[];+}++/** `unreadMessages` over the page model, which names its nodes `messages`. */+export function unreadViewMessages(+ sessions: readonly ViewChangeSession[],+ read: ReadonlySet<string>,+): UnreadMessage[] {+ return unreadMessages(+ sessions.map((session) => ({ ...session, nodes: session.messages })),+ read,+ );+}++/** How many unread messages crossed the threshold (the panel card's number). */+export function countBigUnread(+ sessions: readonly ChangeSession[],+ read: ReadonlySet<string>,+ threshold: number,+): number {+ return unreadMessages(sessions, read).filter((message) => isBigChange(message.change, threshold))+ .length;+}++/** `1240` → `1 240`: thousands separated by a thin space, no locale dependency. */+export function grouped(value: number): string {+ return String(Math.max(0, Math.trunc(value))).replace(/\B(?=(\d{3})+(?!\d))/g, " ");+}++/** `+1 240 −80 · 14 files` — the chip on a row and the CLI line's numbers. */+export function formatChange(change: ViewChange): string {+ const files = `${change.files} file${change.files === 1 ? "" : "s"}`;+ return `+${grouped(change.added)} −${grouped(change.removed)} · ${files}`;+}diff --git a/packages/cli/src/view/lineage.ts b/packages/cli/src/view/lineage.tsindex 6dde98a..a6d0c37 100644--- a/packages/cli/src/view/lineage.ts+++ b/packages/cli/src/view/lineage.ts@@ -103,6 +103,8 @@ export function buildMessages(...(node.decidedBy === undefined ? {} : { decidedBy: node.decidedBy }),...(node.alternatives?.length ? { alternatives: node.alternatives } : {}),...(node.commits?.length ? { commits: node.commits } : {}),+ // Story 10.3: the numstat totals the build attached to the record node.+ ...(node.change === undefined ? {} : { change: node.change }),...(node.commits?.length? {commitTags: node.commits.map((hash) => {diff --git a/packages/cli/src/view/model.ts b/packages/cli/src/view/model.tsindex 73d967a..9f54b7c 100644--- a/packages/cli/src/view/model.ts+++ b/packages/cli/src/view/model.ts@@ -57,6 +57,17 @@ export interface ViewCommit {subject?: string;}+/**+ * The code a message landed, from git (Story 10.3): lines added and removed+ * plus the number of distinct files its commits touched. Facts only — cogit+ * never reads the message to decide whether it looks big.+ */+export interface ViewChange {+ added: number;+ removed: number;+ files: number;+}+export interface ViewNode {/** Stable id (`h…`); the key of the node, never shown to the user. */id: string;@@ -86,6 +97,12 @@ export interface ViewNode {decidedBy?: "user" | "agent" | "agreed";alternatives?: { option: string; why: string }[];commits?: string[];+ /**+ * How much code landed after this message (Story 10.3), read from git's+ * numstat for the commits linked to it. Absent when no commit is linked: the+ * map shows nothing rather than a misleading zero.+ */+ change?: ViewChange;/*** `commits` with their subjects (Story 8.8); the map draws them as small tag* chips. A tag without a subject is a commit git no longer has, drawn greyed.@@ -249,6 +266,12 @@ export interface LineageViewModel {* instead. Absent on pages built before 8.13.*/settings?: PanelSettings;+ /**+ * Message ids the user marked read (Story 10.3), from `.cogit/state/read.json`+ * at build time. Local state: the page toggles it through the local server and+ * a rebuild embeds the new list.+ */+ read?: string[];}/**@@ -293,6 +316,11 @@ export interface PanelProject {needsUserCount: number;/** `file://` URL of the project's map; null when the directory is gone. */lineageUrl: string | null;+ /**+ * Unread messages whose commits crossed `bigChangeLines` (Story 10.3), the+ * same number the map's unread view lists. Absent on pages built before 10.3.+ */+ unreadBigCount?: number;}/**@@ -311,6 +339,8 @@ export interface PanelSettings {recordCommit: "ask" | "auto" | "off";gitPolicy: "ignore" | "commit";agents: string[];+ /** A message whose linked commits crossed this many lines counts as big (10.3). */+ bigChangeLines: number;}/**diff --git a/packages/cli/src/view/panel.ts b/packages/cli/src/view/panel.tsindex 7dcc355..3bf1749 100644--- a/packages/cli/src/view/panel.ts+++ b/packages/cli/src/view/panel.ts@@ -3,9 +3,13 @@ import type { Io } from "../io.js";import { redactDeep } from "../redact.js";import type { Config, RegistryEntry } from "../schema/config.js";import type { Session } from "../schema/session.js";+import { readProjectChanges } from "../store/changes.js";import { atomicWrite, isDirectory } from "../store/fs.js";import { globalPaths, projectPaths } from "../store/paths.js";+import { readReadState } from "../store/read-state.js";import { loadAllSessions, loadConfig, loadRegistry } from "../store/stores.js";+import { attachThoughtTrailers, earliestSessionStart, readThoughtTrailers } from "../thought.js";+import { countBigUnread } from "./change.js";import { embedViewModel, lastActive, statusCard } from "./lineage.js";import { type PanelSettings, type PanelViewModel, VIEW_SCHEMA } from "./model.js";import type { SwitcherSource } from "./switcher.js";@@ -51,9 +55,49 @@ export function panelSettings(config: Config): PanelSettings {recordCommit: config.recordCommit,gitPolicy: config.gitPolicy,agents: config.agents,+ bigChangeLines: config.bigChangeLines,};}+/** The schema default, for callers that collect cards without a config. */+const DEFAULT_BIG_CHANGE_LINES = 300;++/**+ * How many unread messages in this project crossed the threshold (Story 10.3).+ * The card count never fails a panel build: a missing git, a broken record or+ * an unreadable state file simply counts zero.+ */+async function unreadBigCount(+ root: string,+ sessions: Session[],+ threshold: number,+): Promise<number> {+ try {+ const trailers = await readThoughtTrailers(root, {+ since: earliestSessionStart(sessions),+ });+ const withThoughts = attachThoughtTrailers(sessions, trailers);+ const hashes = new Set(+ withThoughts.flatMap((session) => session.nodes.flatMap((node) => node.commits ?? [])),+ );+ if (hashes.size === 0) return 0;+ const changes = await readProjectChanges(root, hashes);+ const read = await readReadState(root);+ return countBigUnread(+ withThoughts.map((session) => ({+ sessionId: session.sessionId,+ title: session.title,+ startedAt: session.startedAt,+ nodes: session.nodes,+ })),+ read,+ threshold,+ );+ } catch {+ return 0;+ }+}+/** The title of the newest message in a session, in send order. */function lastMessageTitle(session: Session): string {const messages = session.nodes.filter((node) => node.kind === "message");@@ -82,6 +126,7 @@ export async function collectPanelProjects(generatedAt: string,warn: (line: string) => void,quietPath?: string,+ bigChangeLines = DEFAULT_BIG_CHANGE_LINES,): Promise<CollectedProject[]> {const projects: CollectedProject[] = [];for (const entry of entries) {@@ -94,6 +139,7 @@ export async function collectPanelProjects(needsUserCount: 0,lineageUrl: null,leftOff: "",+ unreadBigCount: 0,});continue;}@@ -109,6 +155,7 @@ export async function collectPanelProjects(needsUserCount: card.pending.filter((item) => item.needsUser).length,lineageUrl: pathToFileURL(projectPaths(entry.path).html).href,leftOff: leftOffLine(sessions),+ unreadBigCount: await unreadBigCount(entry.path, sessions, bigChangeLines),});} catch (err) {warn(`skipping project ${entry.path}: ${(err as Error).message}`);@@ -120,6 +167,7 @@ export async function collectPanelProjects(needsUserCount: 0,lineageUrl: pathToFileURL(projectPaths(entry.path).html).href,leftOff: "",+ unreadBigCount: 0,});}}@@ -146,7 +194,14 @@ export async function collectRegistryProjects(for (const warning of registry.warnings) warn(warning);}if (!registry.found || !registry.ok) return [];- return await collectPanelProjects(registry.data.projects, generatedAt, warn, quietPath);+ const config = await loadConfig(env);+ return await collectPanelProjects(+ registry.data.projects,+ generatedAt,+ warn,+ quietPath,+ config.bigChangeLines,+ );}/**diff --git a/packages/cli/src/view/settings.ts b/packages/cli/src/view/settings.tsindex 841fdc2..8631578 100644--- a/packages/cli/src/view/settings.ts+++ b/packages/cli/src/view/settings.ts@@ -130,6 +130,7 @@ export const DEFAULT_SETTINGS: PanelSettings = {recordCommit: "ask",gitPolicy: "commit",agents: ["claude-code"],+ bigChangeLines: 300,};export function withDefaults(settings: Partial<PanelSettings> | undefined): PanelSettings {diff --git a/packages/cli/test/panel.test.ts b/packages/cli/test/panel.test.tsindex 32d895b..8f20c2e 100644--- a/packages/cli/test/panel.test.ts+++ b/packages/cli/test/panel.test.ts@@ -91,6 +91,7 @@ describe("buildPanel", () => {recordCommit: "ask",gitPolicy: "commit",agents: ["claude-code"],+ bigChangeLines: 300,},projects: [{@@ -100,6 +101,7 @@ describe("buildPanel", () => {lastActivity: T0,needsUserCount: 1,lineageUrl: pathToFileURL(projectPaths(alpha).html).href,+ unreadBigCount: 0,},{name: "beta",@@ -108,6 +110,7 @@ describe("buildPanel", () => {lastActivity: null,needsUserCount: 0,lineageUrl: null,+ unreadBigCount: 0,},],});@@ -144,6 +147,7 @@ describe("buildPanel", () => {lastActivity: null,needsUserCount: 0,lineageUrl: pathToFileURL(projectPaths(root).html).href,+ unreadBigCount: 0,},]);expect(io.warnings.join("\n")).toMatch(/^skipping project .*ENOTDIR/);@@ -196,3 +200,44 @@ describe("panel refresh from build", () => {expect(io.warnings.join("\n")).toMatch(/could not build panel\.html/);});});++describe("panel card unread count (10.3)", () => {+ it("keeps the card at zero when the read state cannot be read", async () => {+ const dir = await tempDir();+ const env = envFor(dir);+ const root = join(dir, "proj");+ const paths = projectPaths(root);+ const session = {+ schema: 1,+ sessionId: "s1",+ agent: "claude-code",+ title: "t",+ epoch: null,+ startedAt: T0,+ updatedAt: T0,+ status: { goal: "", done: [], pending: [], next: "" },+ nodes: [+ {+ id: "h111111111111",+ parent: null,+ kind: "message",+ title: "Big",+ at: T0,+ commits: ["abcdef1"],+ },+ ],+ };+ await mkdir(paths.sessions, { recursive: true });+ await writeFile(paths.project, JSON.stringify({ schema: 1, name: "proj", epochs: [] }));+ await writeFile(paths.session("s1"), JSON.stringify(session));+ // A directory where read.json belongs: reading it is an error, not "empty".+ await mkdir(paths.readState, { recursive: true });+ await write(+ globalPaths(env).registry,+ JSON.stringify({ schema: 1, projects: [{ path: root, name: "proj", addedAt: T0 }] }),+ );++ const model = await buildPanel({ env, io: fakeIo(env), templateHtml: TEMPLATE });+ expect(model.projects[0]?.unreadBigCount).toBe(0);+ });+});diff --git a/packages/cli/test/server.test.ts b/packages/cli/test/server.test.tsindex 2618508..4673226 100644--- a/packages/cli/test/server.test.ts+++ b/packages/cli/test/server.test.ts@@ -27,6 +27,7 @@ import {} from "../src/server.js";import { atomicWrite } from "../src/store/fs.js";import { globalPaths, projectPaths } from "../src/store/paths.js";+import { readReadState } from "../src/store/read-state.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";@@ -723,3 +724,87 @@ describe("ensureServer", () => {expect(started?.port).toBe(port);});});++describe("read marks (10.3)", () => {+ const ID = "h111111111111";++ function readWrite(+ server: MapServer,+ token: string,+ payload: unknown,+ overrides: Record<string, string> = {},+ ): Promise<Reply> {+ return postConfig(`${server.url}/api/read`, JSON.stringify(payload), {+ origin: `http://127.0.0.1:${server.port}`,+ [CONFIG_TOKEN_HEADER]: token,+ ...overrides,+ });+ }++ it("writes a read mark for a registered project and clears it", async () => {+ const server = await start();+ const token = await panelToken(server);+ const marked = await readWrite(server, token, { dir: root, id: ID, read: true });+ expect(marked.status).toBe(200);+ expect(JSON.parse(marked.body)).toEqual({ ok: true, id: ID, read: true });+ expect([...(await readReadState(root))]).toEqual([ID]);++ const cleared = await readWrite(server, token, { dir: root, id: ID, read: false });+ expect(cleared.status).toBe(200);+ expect([...(await readReadState(root))]).toEqual([]);+ });++ it("refuses a foreign project, a bad id, a bad body and a bad token", async () => {+ const server = await start();+ const token = await panelToken(server);+ expect(+ (await readWrite(server, token, { dir: join(dir, "elsewhere"), id: ID, read: true })).status,+ ).toBe(403);+ expect((await readWrite(server, token, { dir: root, id: "m1", read: true })).status).toBe(400);+ expect((await readWrite(server, token, { dir: root, id: ID })).status).toBe(400);+ expect((await readWrite(server, token, { id: ID, read: true })).status).toBe(400);+ expect((await readWrite(server, "nope", { dir: root, id: ID, read: true })).status).toBe(403);+ expect(+ (+ await readWrite(+ server,+ token,+ { dir: root, id: ID, read: true },+ {+ "content-type": "text/plain",+ },+ )+ ).status,+ ).toBe(415);+ expect((await readWrite(server, token, { dir: root, id: ID, read: true }, {})).status).toBe(+ 200,+ );+ const raw = await postConfig(`${server.url}/api/read`, "{oops", {+ origin: `http://127.0.0.1:${server.port}`,+ [CONFIG_TOKEN_HEADER]: token,+ });+ expect(raw.status).toBe(400);+ const huge = await readWrite(server, token, {+ dir: root,+ id: ID,+ read: true,+ pad: "x".repeat(5000),+ });+ expect(huge.status).toBe(413);++ const array = await postConfig(`${server.url}/api/read`, "[]", {+ origin: `http://127.0.0.1:${server.port}`,+ [CONFIG_TOKEN_HEADER]: token,+ });+ expect(array.status).toBe(400);+ });++ it("answers 500 instead of crashing when the state cannot be written", async () => {+ const server = await start();+ const token = await panelToken(server);+ // A directory where the state file belongs makes the write fail.+ await mkdir(projectPaths(root).readState, { recursive: true });+ const reply = await readWrite(server, token, { dir: root, id: ID, read: true });+ expect(reply.status).toBe(500);+ });+});diff --git a/packages/cli/test/settings.test.ts b/packages/cli/test/settings.test.tsindex 13e3163..5ec2fe8 100644--- a/packages/cli/test/settings.test.ts+++ b/packages/cli/test/settings.test.ts@@ -23,6 +23,7 @@ describe("settings model", () => {recordCommit: parsed.recordCommit,gitPolicy: parsed.gitPolicy,agents: parsed.agents,+ bigChangeLines: parsed.bigChangeLines,});});diff --git a/packages/cli/test/unread.test.ts b/packages/cli/test/unread.test.tsnew file mode 100644index 0000000..fe30100--- /dev/null+++ b/packages/cli/test/unread.test.ts@@ -0,0 +1,323 @@+import { execFile } from "node:child_process";+import { mkdir, readFile, writeFile } from "node:fs/promises";+import { join } from "node:path";+import { promisify } from "node:util";+import { beforeEach, describe, expect, it } from "vitest";+import { buildProject } from "../src/commands/build.js";+import { formatUnread, logUnread } from "../src/commands/log.js";+import { createProgram } from "../src/program.js";+import type { Session } from "../src/schema/session.js";+import { readProjectChanges } from "../src/store/changes.js";+import { projectPaths } from "../src/store/paths.js";+import { readReadState, setMessageRead } from "../src/store/read-state.js";+import { projectJson } from "../src/store/stores.js";+import {+ attachChanges,+ countBigUnread,+ messageChange,+ unreadMessages,+ unreadViewMessages,+} from "../src/view/change.js";+import { DATA_ELEMENT_ID } from "../src/view/model.js";+import { envFor, type FakeIo, fakeIo, T0, tempDir } from "./helpers.js";++const run = promisify(execFile);++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">`;++const A = "h111111111111";+const B = "h222222222222";+const C = "h333333333333";++function session(nodes: Session["nodes"]): Session {+ return {+ schema: 1,+ sessionId: "s1",+ agent: "claude-code",+ title: "Ship the parser",+ epoch: null,+ startedAt: T0,+ updatedAt: T0,+ status: { goal: "Parse the file", done: [], pending: [], next: "" },+ nodes,+ };+}++function message(id: string, title: string, commits?: string[]): Session["nodes"][number] {+ return {+ id,+ parent: null,+ kind: "message",+ title,+ at: T0,+ ...(commits === undefined ? {} : { commits }),+ };+}++interface Embedded {+ unassigned: {+ messages: {+ id: string;+ change?: { added: number; removed: number; files: number };+ commits?: string[];+ }[];+ }[];+ read?: string[];+}++function embedded(html: string): Embedded {+ const start = html.indexOf(DATA_PREFIX);+ const end = html.indexOf("</script>", start);+ return JSON.parse(html.slice(start + DATA_PREFIX.length, end));+}++describe("how much code landed per message (10.3)", () => {+ let dir: string;+ let root: string;+ let env: NodeJS.ProcessEnv;+ let io: FakeIo;++ const git = async (...args: string[]): Promise<string> =>+ (await run("git", ["-C", root, ...args])).stdout;++ const writeProject = async (nodes: Session["nodes"]): Promise<void> => {+ const paths = projectPaths(root);+ await mkdir(paths.sessions, { recursive: true });+ await writeFile(paths.project, projectJson({ schema: 1, name: "proj", epochs: [] }));+ await writeFile(paths.session("s1"), JSON.stringify(session(nodes)));+ };++ beforeEach(async () => {+ dir = await tempDir();+ root = join(dir, "proj");+ await mkdir(root);+ env = envFor(dir);+ io = fakeIo(env);+ await git("init", "-q");+ await git("config", "user.email", "[email protected]");+ await git("config", "user.name", "Tester");+ await writeFile(join(root, "base.txt"), "base\n");+ await git("add", "base.txt");+ await git("commit", "-q", "-m", "chore: base");+ });++ /** Creates the three commits this suite reads, with thoughts for A. */+ const createCommits = async (): Promise<{ first: string; second: string; third: string }> => {+ await mkdir(join(root, "src"));+ await writeFile(join(root, "src", "one.ts"), "a\nb\nc\nd\n");+ await git("add", "src/one.ts");+ await git("commit", "-q", "-m", "feat: one", "--trailer", `Thought: ${A}`);+ const first = (await git("rev-parse", "HEAD")).trim();++ await writeFile(join(root, "src", "one.ts"), "a\nB\nc\nd\n");+ await git("add", "src/one.ts");+ await git("commit", "-q", "-m", "fix: one", "--trailer", `Thought: ${A}`);+ const second = (await git("rev-parse", "HEAD")).trim();+ const secondShort = (await git("rev-parse", "--short", "HEAD")).trim();++ await writeFile(join(root, "src", "two.ts"), "1\n2\n3\n4\n5\n");+ await git("add", "src/two.ts");+ await git("commit", "-q", "-m", "feat: two");+ const third = (await git("rev-parse", "HEAD")).trim();++ // The record lists the second commit twice (short and full): the union is a+ // set of commits, so its lines count once.+ await writeProject([+ message(A, "Write the parser", [secondShort, second, second]),+ message(B, "Add the second file", [third]),+ message(C, "Write the docs"),+ ]);+ expect(first).toHaveLength(40);+ return { first, second, third };+ };++ it("sums numstat per message and counts a commit linked twice once", async () => {+ await createCommits();+ await buildProject({ dir: root, io, templateHtml: TEMPLATE });+ const html = await readFile(projectPaths(root).html, "utf8");+ const messages = embedded(html).unassigned[0]?.messages ?? [];+ const a = messages.find((node) => node.id === A);+ const b = messages.find((node) => node.id === B);+ const c = messages.find((node) => node.id === C);++ // A: the trailer-only commit (4 added, 1 file) plus the recorded commit+ // (1 added, 1 removed, same file) — the duplicate hash adds nothing.+ expect(a?.change).toEqual({ added: 5, removed: 1, files: 1 });+ expect(b?.change).toEqual({ added: 5, removed: 0, files: 1 });+ // No commits: nothing shown, not a misleading zero.+ expect(c?.change).toBeUndefined();+ });++ it("counts one commit once even when the record lists it twice", () => {+ const full = "a".repeat(40);+ const changes = new Map([+ [full.slice(0, 7), { full, added: 7, removed: 3, files: ["src/one.ts"] }],+ [full, { full, added: 7, removed: 3, files: ["src/one.ts"] }],+ ]);+ expect(messageChange([full.slice(0, 7), full], changes)).toEqual({+ added: 7,+ removed: 3,+ files: 1,+ });+ // A commit git does not know leaves no numbers at all.+ expect(messageChange(["deadbee"], changes)).toBeUndefined();+ expect(messageChange(undefined, changes)).toBeUndefined();+ });++ it("round-trips the read mark and embeds it in the map", async () => {+ await createCommits();+ expect([...(await readReadState(root))]).toEqual([]);+ await setMessageRead(root, A, true);+ expect([...(await readReadState(root))]).toEqual([A]);++ await buildProject({ dir: root, io, templateHtml: TEMPLATE });+ const html = await readFile(projectPaths(root).html, "utf8");+ expect(embedded(html).read).toEqual([A]);++ await setMessageRead(root, A, false);+ expect([...(await readReadState(root))]).toEqual([]);+ });++ it("replaces an unreadable state file instead of blocking the toggle", async () => {+ await mkdir(join(projectPaths(root).base, "state"), { recursive: true });+ await writeFile(projectPaths(root).readState, "{not json");+ await setMessageRead(root, B, true);+ expect([...(await readReadState(root))]).toEqual([B]);+ await expect(setMessageRead(root, "not-a-message", true)).rejects.toThrow("not a message id");+ });++ it("lists unread messages most code first, and the threshold counts only big ones", () => {+ const sessions = [+ {+ sessionId: "s1",+ title: "Ship the parser",+ startedAt: T0,+ nodes: [+ {+ id: A,+ kind: "message",+ title: "Write the parser",+ change: { added: 900, removed: 100, files: 3 },+ },+ {+ id: B,+ kind: "message",+ title: "Add the second file",+ change: { added: 10, removed: 0, files: 1 },+ },+ { id: C, kind: "message", title: "No commits" },+ ],+ },+ ];+ const ordered = unreadMessages(sessions, new Set());+ expect(ordered.map((entry) => entry.messageId)).toEqual([A, B]);+ expect(countBigUnread(sessions, new Set(), 300)).toBe(1);+ expect(countBigUnread(sessions, new Set([A]), 300)).toBe(0);+ expect(unreadMessages(sessions, new Set([A, B])).map((entry) => entry.messageId)).toEqual([]);+ });++ it("prints `log --unread` most code first and drops a message once read", async () => {+ await createCommits();+ const unread = await logUnread({ dir: root, io });+ expect(unread.map((entry) => entry.messageId)).toEqual([A, B]);+ const lines = formatUnread(unread);+ expect(lines[0]).toContain("+5 −1 · 1 file");+ expect(lines[0]).toContain("Write the parser");+ expect(lines[1]).toContain("+5 −0 · 1 file");+ expect(io.lines).toEqual(lines);++ await setMessageRead(root, A, true);+ const after = await logUnread({ dir: root, io, json: true });+ expect(after.map((entry) => entry.messageId)).toEqual([B]);+ expect(JSON.parse(io.lines.at(-1) ?? "[]")).toHaveLength(1);++ // Nothing unread: one plain line, no invented numbers.+ await setMessageRead(root, B, true);+ const none = await logUnread({ dir: root, io });+ expect(none).toEqual([]);+ expect(io.lines.at(-1)).toBe("No unread messages with linked commits.");+ });+ it("drops a stale number when its commit no longer resolves", () => {+ const sessions = [+ {+ sessionId: "s1",+ title: "t",+ startedAt: T0,+ nodes: [+ { id: A, kind: "message", title: "Changed", change: { added: 9, removed: 9, files: 2 } },+ ],+ },+ ];+ // No changes at all: the records pass through untouched.+ expect(attachChanges(sessions, new Map())[0]?.nodes[0]?.change).toEqual({+ added: 9,+ removed: 9,+ files: 2,+ });+ const stale = attachChanges(+ sessions,+ new Map([["deadbee", { full: "f".repeat(40), added: 1, removed: 1, files: ["x"] }]]),+ );+ expect(stale[0]?.nodes[0]?.change).toBeUndefined();+ expect(+ unreadViewMessages(+ [{ sessionId: "s1", title: "t", startedAt: T0, messages: stale[0]?.nodes ?? [] }],+ new Set(),+ ),+ ).toHaveLength(0);+ expect(+ unreadViewMessages(+ [+ {+ sessionId: "s1",+ title: "t",+ startedAt: T0,+ messages: [+ {+ id: A,+ kind: "message",+ title: "Changed",+ change: { added: 4, removed: 0, files: 1 },+ },+ ],+ },+ ],+ new Set(),+ ).map((entry) => entry.messageId),+ ).toEqual([A]);+ });++ it("projects numstat paths onto a project inside a larger repository", async () => {+ const sub = join(root, "sub");+ await mkdir(sub);+ await writeFile(join(sub, "a.txt"), "a\nb\n");+ await writeFile(join(root, "outside.txt"), "x\ny\nz\n");+ await git("add", "sub/a.txt", "outside.txt");+ await git("commit", "-q", "-m", "feat: inside and outside");+ const full = (await git("rev-parse", "HEAD")).trim();++ const inside = await readProjectChanges(sub, [full]);+ expect(inside.get(full)).toEqual({+ full,+ added: 5,+ removed: 0,+ files: ["a.txt"],+ });++ // Empty input and a directory outside git resolve to nothing, never an error.+ expect(await readProjectChanges(sub, [])).toEqual(new Map());+ expect(await readProjectChanges(dir, [full])).toEqual(new Map());+ });++ it("is reachable as `cogit log --unread`", async () => {+ await createCommits();+ const program = createProgram(() => io);+ program.exitOverride();+ for (const command of program.commands) command.exitOverride();+ await program.parseAsync(["log", "--unread", "-C", root], { from: "user" });+ expect(io.lines.join("\n")).toContain("+5 −1 · 1 file");+ expect(io.lines.join("\n")).toContain("Write the parser");+ });+});diff --git a/packages/template/src/GitGraph.tsx b/packages/template/src/GitGraph.tsxindex a008313..c0431e0 100644--- a/packages/template/src/GitGraph.tsx+++ b/packages/template/src/GitGraph.tsx@@ -1,4 +1,5 @@import { type MouseEvent, type ReactElement, useMemo } from "react";+import { formatChange, isBigChange } from "../../cli/src/view/change.js";import type { ViewNode } from "../../cli/src/view/model.js";import { formatStamp } from "./format.js";import {@@ -46,6 +47,8 @@ function Row({branchSelected,searchHit,searchActive,+ read,+ bigChangeLines,onSelect,onUnfold,onContinue,@@ -58,6 +61,10 @@ function Row({searchHit: boolean;/** The hit the ↑/↓ counter is on. */searchActive: boolean;+ /** The user marked this message read (Story 10.3). */+ read: boolean;+ /** Unread messages at or above this many lines get the quiet highlight. */+ bigChangeLines: number;onSelect: (row: GitMessageRow) => void;onUnfold: (segmentId: string) => void;onContinue: (continues: NonNullable<ViewNode["continues"]>) => void;@@ -89,12 +96,17 @@ function Row({}const message = row.message;+ // A fact, not a verdict: the row is only quiet-highlighted when the user has+ // not read it and its commits changed at least `bigChangeLines` lines.+ const unreadBig =+ message.change !== undefined && !read && isBigChange(message.change, bigChangeLines);const className = ["git-row",selected ? "is-selected" : "",branchSelected ? "in-branch" : "",searchHit ? "is-search-hit" : "",searchActive ? "is-search-active" : "",+ unreadBig ? "is-unread-big" : "",].filter(Boolean).join(" ");@@ -140,6 +152,14 @@ function Row({))}</span>) : null}+ {message.change ? (+ <span+ className="git-change"+ title={`The commits linked to this message changed ${message.change.added} lines added, ${message.change.removed} removed${read ? " (read)" : ""}`}+ >+ {formatChange(message.change)}+ </span>+ ) : null}{message.continues ? (<spanclassName="git-continues"@@ -166,6 +186,8 @@ export function GitGraph({activeSegmentId,highlightIds,activeHitId,+ readIds,+ bigChangeLines,onSelect,onUnfold,onContinue,@@ -179,6 +201,10 @@ export function GitGraph({highlightIds: ReadonlySet<string> | undefined;/** The search hit the counter is on, if it belongs to this session. */activeHitId: string | null;+ /** Messages the user marked read (Story 10.3). */+ readIds: ReadonlySet<string>;+ /** Unread messages at or above this many lines get the quiet highlight. */+ bigChangeLines: number;onSelect: (row: GitMessageRow) => void;onUnfold: (segmentId: string) => void;/** Opens the earlier session this message continues, at that message. */@@ -288,6 +314,8 @@ export function GitGraph({branchSelected={activeSegmentId !== null && row.segmentId === activeSegmentId}searchHit={messageId !== null && highlightIds?.has(messageId) === true}searchActive={messageId !== null && activeHitId !== null && messageId === activeHitId}+ read={messageId !== null && readIds.has(messageId)}+ bigChangeLines={bigChangeLines}onSelect={onSelect}onUnfold={onUnfold}onContinue={onContinue}diff --git a/packages/template/src/Graph.tsx b/packages/template/src/Graph.tsxindex d999fcc..59a2e22 100644--- a/packages/template/src/Graph.tsx+++ b/packages/template/src/Graph.tsx@@ -11,8 +11,10 @@ import {} from "@xyflow/react";import "@xyflow/react/dist/style.css";import { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react";+import { unreadViewMessages } from "../../cli/src/view/change.js";import type { LineageViewModel, ViewSession } from "../../cli/src/view/model.js";import { hitMessageIds, hitSessionIds } from "../../cli/src/view/search.js";+import { pageToken, saveRead } from "./data.js";import { type FilesTarget, FilesView } from "./FilesView.js";import { useFullscreen } from "./fullscreen.js";import { GitGraph } from "./GitGraph.js";@@ -24,6 +26,7 @@ import { OPEN_LINK_DROP, SessionMap } from "./SessionMap.js";import { DrillDown, type Selection } from "./SidePanel.js";import { usePageWheel } from "./scroll.js";import { layoutSessionGraph, type SessionGraph } from "./sessionLayout.js";+import { UnreadView } from "./UnreadView.js";/*** The project map (Story 8.7). The sessions are a git graph, one dot each;@@ -42,6 +45,10 @@ const OPEN_EMPTY = 36;const GraphActions = createContext<{selection: Selection | null;openIds: ReadonlySet<string>;+ /** Message ids the user marked read (Story 10.3). */+ readIds: ReadonlySet<string>;+ /** Unread messages at or above this many lines get the quiet highlight. */+ bigChangeLines: number;openSession: (sessionId: string) => void;openNode: (sessionId: string, messageId: string, branchId?: string) => void;openContinue: (sessionId: string, messageId: string) => void;@@ -49,6 +56,8 @@ const GraphActions = createContext<{}>({selection: null,openIds: new Set(),+ readIds: new Set(),+ bigChangeLines: 300,openSession: () => {},openNode: () => {},openContinue: () => {},@@ -83,7 +92,8 @@ function SessionMessages({highlights: ReadonlySet<string> | undefined;activeHitId: string | null;}) {- const { selection, openNode, openContinue, unfold } = useContext(GraphActions);+ const { selection, readIds, bigChangeLines, openNode, openContinue, unfold } =+ useContext(GraphActions);const own = selection?.sessionId === session.sessionId;if (git.rows.length === 0)return <p className="graph-status empty">No messages recorded in this session yet.</p>;@@ -94,6 +104,8 @@ function SessionMessages({activeSegmentId={selection?.type === "node" && own ? (selection.branchId ?? null) : null}highlightIds={highlights}activeHitId={activeHitId}+ readIds={readIds}+ bigChangeLines={bigChangeLines}onSelect={(row) => openNode(session.sessionId, row.message.id, row.segmentId)}onUnfold={unfold}onContinue={(continues) => openContinue(continues.sessionId, continues.id)}@@ -216,9 +228,56 @@ function Flow({ model, search }: { model: LineageViewModel; search: MapSearchStaconst [unfolded, setUnfolded] = useState<Set<string>>(() => new Set());const [openAll, setOpenAll] = useState(false);const [showOutline, setShowOutline] = useState(true);- // The files view and the outline share the left column, so only one shows.+ // The files, unread and outline views share the left column; only one shows.const [showFiles, setShowFiles] = useState(false);+ const [showUnread, setShowUnread] = useState(false);const { expanded: fullscreen, toggle: toggleFullscreen } = useFullscreen();+ // Story 10.3: the read marks the page was built with. A live rebuild refreshes+ // them; the toggle updates this set at once so the row answers the click.+ const [readIds, setReadIds] = useState<ReadonlySet<string>>(() => new Set(model.read ?? []));+ const [readError, setReadError] = useState<string | null>(null);+ useEffect(() => {+ setReadIds(new Set(model.read ?? []));+ }, [model]);+ const bigChangeLines = model.settings?.bigChangeLines ?? 300;+ const toggleRead = useCallback(+ (id: string, next: boolean) => {+ setReadError(null);+ setReadIds((previous) => {+ const copy = new Set(previous);+ if (next) copy.add(id);+ else copy.delete(id);+ return copy;+ });+ // Over `file://` there is no server to write to; the mark lasts for this+ // open page only, which is what the toggle's title says.+ const token = pageToken();+ if (token === null) return;+ void saveRead(model.project.path, id, next, token).catch((err: unknown) => {+ setReadError(err instanceof Error ? err.message : String(err));+ setReadIds((previous) => {+ const copy = new Set(previous);+ if (next) copy.delete(id);+ else copy.add(id);+ return copy;+ });+ });+ },+ [model.project.path],+ );+ const unread = useMemo(+ () =>+ unreadViewMessages(+ [...model.epochs.flatMap((epoch) => epoch.sessions), ...model.unassigned],+ readIds,+ ),+ [model, readIds],+ );+ const unreadBig = useMemo(+ () =>+ unread.filter((message) => message.change.added + message.change.removed >= bigChangeLines),+ [unread, bigChangeLines],+ );const [focusedId, setFocusedId] = useState<string | null>(() => {if (initial === null) return null;if (initial.messageId === undefined) return `session:${initial.sessionId}`;@@ -497,8 +556,17 @@ function Flow({ model, search }: { model: LineageViewModel; search: MapSearchSta);const actions = useMemo(- () => ({ selection, openIds, openSession: toggleSession, openNode, openContinue, unfold }),- [selection, openIds, toggleSession, openNode, openContinue, unfold],+ () => ({+ selection,+ openIds,+ readIds,+ bigChangeLines,+ openSession: toggleSession,+ openNode,+ openContinue,+ unfold,+ }),+ [selection, openIds, readIds, bigChangeLines, toggleSession, openNode, openContinue, unfold],);const nodes = useMemo<MapFlowNode[]>(() => {@@ -599,13 +667,41 @@ function Flow({ model, search }: { model: LineageViewModel; search: MapSearchStaonClick={() => {setShowFiles((value) => !value);setShowOutline(false);+ setShowUnread(false);}}>{showFiles ? "Hide files" : "Files"}</button>+ <button+ type="button"+ className="outline-button"+ aria-pressed={showUnread}+ title="Unread messages with commits, most code first"+ onClick={() => {+ setShowUnread((value) => !value);+ setShowOutline(false);+ setShowFiles(false);+ }}+ >+ {showUnread+ ? "Hide unread"+ : `Unread${unreadBig.length > 0 ? ` (${unreadBig.length})` : ""}`}+ </button></div><div className="graph-wrap">- {showFiles ? (+ {showUnread ? (+ <UnreadView+ messages={unread}+ bigChangeLines={bigChangeLines}+ active={+ selection?.type === "node"+ ? { sessionId: selection.sessionId, messageId: selection.nodeId }+ : null+ }+ onSelect={selectFromFiles}+ onClose={() => setShowUnread(false)}+ />+ ) : showFiles ? (<FilesViewfiles={model.files}active={@@ -642,6 +738,10 @@ function Flow({ model, search }: { model: LineageViewModel; search: MapSearchStaselection={selection}onClose={() => setSelection(null)}onNavigate={selectFromOutline}+ read={selection?.type === "node" ? readIds.has(selection.nodeId) : false}+ onToggleRead={toggleRead}+ bigChangeLines={bigChangeLines}+ readError={readError}/></div></div>diff --git a/packages/template/src/Panel.tsx b/packages/template/src/Panel.tsxindex 1a31cbe..1b5b4b4 100644--- a/packages/template/src/Panel.tsx+++ b/packages/template/src/Panel.tsx@@ -10,7 +10,9 @@ import { SettingsButton } from "./SettingsModal.js";*/function mapHref(project: PanelProject): string | null {if (!project.lineageUrl) return null;- return isLivePage() ? `/map?dir=${encodeURIComponent(project.path)}` : project.lineageUrl;+ return typeof document !== "undefined" && isLivePage()+ ? `/map?dir=${encodeURIComponent(project.path)}`+ : project.lineageUrl;}export function Panel({ model }: { model: PanelViewModel }) {@@ -57,6 +59,14 @@ export function Panel({ model }: { model: PanelViewModel }) {<dt>Waiting on you</dt><dd>{project.needsUserCount}</dd></div>+ {project.unreadBigCount === undefined ? null : (+ <div>+ <dt title="Unread messages whose commits changed at least the big-change threshold of lines">+ Unread big changes+ </dt>+ <dd>{project.unreadBigCount}</dd>+ </div>+ )}</dl>{href ? (<a className="card-open" href={href}>diff --git a/packages/template/src/SidePanel.tsx b/packages/template/src/SidePanel.tsxindex aac1314..c0e09dd 100644--- a/packages/template/src/SidePanel.tsx+++ b/packages/template/src/SidePanel.tsx@@ -1,4 +1,5 @@import { type ReactNode, useEffect, useRef, useState } from "react";+import { formatChange, isBigChange } from "../../cli/src/view/change.js";import type {LineageViewModel,ViewChatTurn,@@ -7,6 +8,7 @@ import type {} from "../../cli/src/view/model.js";import { resumeCommand } from "../../cli/src/view/resume.js";import { parseSubject, splitPath, typeColour } from "./codeRefs.js";+import { isLivePage } from "./data.js";import { formatTime, kindLabel } from "./format.js";import { layoutGitGraph } from "./gitLayout.js";import {@@ -392,11 +394,21 @@ function NodeDetails({node,branchId,onNavigate,+ read,+ onToggleRead,+ bigChangeLines,+ readError,}: {model: LineageViewModel;node: NodeDetail;branchId?: string | undefined;onNavigate: ((target: OutlineTarget) => void) | undefined;+ /** The user marked this message read (Story 10.3). */+ read: boolean;+ onToggleRead: ((id: string, read: boolean) => void) | undefined;+ bigChangeLines: number;+ /** A failed write of the read mark, shown and not swallowed. */+ readError: string | null;}) {const session = findSession(model, node.sessionId);return (@@ -405,6 +417,36 @@ function NodeDetails({{node.kind === "message" && isMessageHash(node.nodeId) ? (<MessageHash value={node.nodeId} />) : null}+ {node.kind === "message" && node.change ? (+ <section>+ <h3>Code landed</h3>+ <p>+ <span+ className={`git-change${+ !read && isBigChange(node.change, bigChangeLines) ? " is-big" : ""+ }`}+ >+ {formatChange(node.change)}+ </span>{" "}+ after this message.+ </p>+ <button+ type="button"+ className="read-toggle"+ aria-pressed={read}+ disabled={onToggleRead === undefined}+ onClick={() => onToggleRead?.(node.nodeId, !read)}+ >+ {read ? "Mark as unread" : "Mark as read"}+ </button>+ {typeof document !== "undefined" && isLivePage() ? null : (+ <p className="muted">+ Saved under .cogit/state by `cogit open`; this page keeps it only while open.+ </p>+ )}+ {readError === null ? null : <p className="error">{readError}</p>}+ </section>+ ) : null}{session ? <BranchDetails session={session} branchId={branchId} /> : null}{node.summary ? (<section>@@ -620,12 +662,21 @@ export function DrillDown({selection,onClose,onNavigate,+ read = false,+ onToggleRead,+ bigChangeLines = 300,+ readError = null,}: {model: LineageViewModel;selection: Selection | null;onClose: () => void;/** Moves the selection to another node and reveals it on the map. */onNavigate?: (target: OutlineTarget) => void;+ /** Whether the selected message is marked read (Story 10.3). */+ read?: boolean;+ onToggleRead?: ((id: string, read: boolean) => void) | undefined;+ bigChangeLines?: number;+ readError?: string | null;}) {useEffect(() => {if (!selection) return;@@ -680,6 +731,10 @@ export function DrillDown({node={node}branchId={selection.branchId}onNavigate={onNavigate}+ read={read}+ onToggleRead={onToggleRead}+ bigChangeLines={bigChangeLines}+ readError={readError}/></div></aside>diff --git a/packages/template/src/UnreadView.tsx b/packages/template/src/UnreadView.tsxnew file mode 100644index 0000000..c8b04b6--- /dev/null+++ b/packages/template/src/UnreadView.tsx@@ -0,0 +1,82 @@+import { formatChange, isBigChange, type UnreadMessage } from "../../cli/src/view/change.js";+import { formatStamp } from "./format.js";++/**+ * The map's unread filter (Story 10.3): messages the user has not marked read+ * that have commits behind them, most code first. It is a list, not a verdict:+ * the numbers come from git, and a message lands here simply because nobody has+ * looked at it yet. Clicking a row opens that message on the graph, exactly as+ * its dot does.+ */+export function UnreadView({+ messages,+ bigChangeLines,+ active,+ onSelect,+ onClose,+}: {+ messages: readonly UnreadMessage[];+ /** The highlight threshold; big rows get a quiet mark. */+ bigChangeLines: number;+ active: { sessionId: string; messageId: string } | null;+ onSelect: (target: { sessionId: string; messageId: string }) => void;+ onClose: () => void;+}) {+ return (+ <nav className="outline unread-view" aria-label="Unread messages, most code first">+ <header className="outline-head">+ <span className="outline-title">Unread, most code first</span>+ <span className="outline-badge">{messages.length}</span>+ <button+ type="button"+ className="drilldown-close"+ aria-label="Hide unread"+ onClick={onClose}+ >+ ×+ </button>+ </header>+ <div className="outline-scroll">+ {messages.length === 0 ? (+ <p className="empty">+ No unread messages with commits. A message appears here once a commit carries it and you+ have not marked it read.+ </p>+ ) : (+ <ul className="outline-list">+ {messages.map((message) => {+ const big = isBigChange(message.change, bigChangeLines);+ const current =+ active?.sessionId === message.sessionId && active.messageId === message.messageId;+ return (+ <li key={message.messageId}>+ <button+ type="button"+ className={`outline-item unread-row${current ? " is-active" : ""}${+ big ? " is-big" : ""+ }`}+ title={`${message.title} — ${message.sessionTitle}`}+ onClick={() =>+ onSelect({+ sessionId: message.sessionId,+ messageId: message.messageId,+ })+ }+ >+ <span className="git-change">{formatChange(message.change)}</span>+ <span className="unread-label">{message.label}</span>+ <span className="unread-title">{message.title}</span>+ <span className="muted unread-session">{message.sessionTitle}</span>+ <span className="muted unread-when">+ {message.at === undefined ? "" : formatStamp(message.at)}+ </span>+ </button>+ </li>+ );+ })}+ </ul>+ )}+ </div>+ </nav>+ );+}diff --git a/packages/template/src/data.ts b/packages/template/src/data.tsindex a1e7742..cf4242d 100644--- a/packages/template/src/data.ts+++ b/packages/template/src/data.ts@@ -76,6 +76,28 @@ export async function loadSettings(token: string): Promise<Partial<PanelSettingsreturn body.settings ?? {};}+/**+ * Marks one message read or unread (Story 10.3). The state lives in the+ * project's `.cogit/state/`, so this needs the local server; over `file://` the+ * page has no token and the toggle stays local to the open page.+ */+export async function saveRead(+ dir: string,+ id: string,+ read: boolean,+ token: string,+): Promise<void> {+ const response = await fetch("/api/read", {+ method: "POST",+ headers: { "content-type": "application/json", "x-cogit-token": token },+ body: JSON.stringify({ dir, id, read }),+ });+ if (!response.ok) {+ const text = (await response.text()).trim();+ throw new Error(text || `could not save the read mark (HTTP ${response.status})`);+ }+}+/** One settings write; the server validates the key, the value and the token. */export async function saveSetting(key: string,diff --git a/packages/template/src/fixture.ts b/packages/template/src/fixture.tsindex 6ece598..a2382a3 100644--- a/packages/template/src/fixture.ts+++ b/packages/template/src/fixture.ts@@ -62,6 +62,7 @@ export const fixture: LineageViewModel = {recordCommit: "ask",gitPolicy: "ignore",agents: ["claude-code"],+ bigChangeLines: 300,},epochs: [{diff --git a/packages/template/src/gitLayout.ts b/packages/template/src/gitLayout.tsindex 24594d9..ec08fff 100644--- a/packages/template/src/gitLayout.ts+++ b/packages/template/src/gitLayout.ts@@ -29,6 +29,8 @@ export interface GitNode {continues?: ViewNode["continues"];commits?: string[] | undefined;commitTags?: ViewNode["commitTags"];+ /** Numstat totals of the linked commits (Story 10.3). */+ change?: ViewNode["change"];unsummarized?: true | undefined;/*** When the item stops occupying its lane, as a timestamp. Session level only:diff --git a/packages/template/src/graph.ts b/packages/template/src/graph.tsindex 3f29df9..1c4916f 100644--- a/packages/template/src/graph.ts+++ b/packages/template/src/graph.ts@@ -17,6 +17,8 @@ export type NodeDetail = {alternatives?: ViewNode["alternatives"];commits?: string[];commitTags?: ViewNode["commitTags"];+ /** Numstat totals of the linked commits (Story 10.3). */+ change?: ViewNode["change"];files?: string[];work?: ViewNode["work"];agentDecisions?: ViewNode["agentDecisions"];diff --git a/packages/template/src/styles.css b/packages/template/src/styles.cssindex 84755df..b0742f1 100644--- a/packages/template/src/styles.css+++ b/packages/template/src/styles.css@@ -1888,3 +1888,77 @@ time {.session-row.is-open {background: color-mix(in srgb, var(--accent) 8%, transparent);}++/* Story 10.3: how much code landed after a message. Facts from git only. */+.git-change {+ flex: none;+ padding: 0 4px;+ white-space: nowrap;+ color: var(--muted);+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 10px;+ line-height: 15px;+ background: var(--chip-bg);+ border: 1px solid var(--chip-line);+ border-radius: 3px;+}++/* Unread and above the threshold: a quiet mark, not an alarm. */+.git-row.is-unread-big {+ box-shadow: inset 2px 0 0 color-mix(in srgb, var(--warn) 55%, transparent);+}++.git-change.is-big {+ color: var(--warn);+ border-color: color-mix(in srgb, var(--warn) 45%, transparent);+}++.unread-view .unread-row {+ display: flex;+ flex-wrap: wrap;+ align-items: baseline;+ gap: 6px;+}++.unread-view .unread-label {+ color: var(--muted);+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;+ font-size: 11px;+}++.unread-view .unread-title {+ flex: 1 1 140px;+ min-width: 0;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.unread-view .unread-session,+.unread-view .unread-when {+ flex: 0 1 auto;+ font-size: 10px;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.unread-view .unread-row.is-big {+ box-shadow: inset 2px 0 0 color-mix(in srgb, var(--warn) 55%, transparent);+}++.read-toggle {+ padding: 3px 10px;+ color: var(--text);+ font: inherit;+ font-size: 12px;+ background: var(--chip-bg);+ border: 1px solid var(--chip-line);+ border-radius: 4px;+ cursor: pointer;+}++.read-toggle[aria-pressed="true"] {+ color: var(--muted);+ border-style: dashed;+}diff --git a/packages/template/test/unread.test.ts b/packages/template/test/unread.test.tsnew file mode 100644index 0000000..5d549b8--- /dev/null+++ b/packages/template/test/unread.test.ts@@ -0,0 +1,234 @@+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { describe, expect, it } from "vitest";+import type {+ LineageViewModel,+ PanelViewModel,+ ViewNode,+ ViewSession,+} from "../../cli/src/view/model.js";+import { GitGraph } from "../src/GitGraph.js";+import { layoutGitGraph } from "../src/gitLayout.js";+import { Panel } from "../src/Panel.js";+import { DrillDown } from "../src/SidePanel.js";+import { UnreadView } from "../src/UnreadView.js";++const T0 = "2026-10-26T10:00:00.000Z";++const BIG = { added: 1200, removed: 40, files: 14 };+const SMALL = { added: 6, removed: 2, files: 1 };++function message(id: string, extra: Partial<ViewNode> = {}): ViewNode {+ return {+ id,+ label: id === "h1" ? "m1" : "m2",+ kind: "message",+ title: `Message ${id}`,+ at: T0,+ parent: null,+ ...extra,+ };+}++const session: ViewSession = {+ sessionId: "s1",+ agent: "claude-code",+ title: "Session one",+ epoch: null,+ startedAt: T0,+ updatedAt: T0,+ status: { goal: "", done: [], pending: [], next: "" },+ messages: [+ message("h1", { change: BIG, commits: ["a".repeat(40)] }),+ message("h2", { change: SMALL, commits: ["b".repeat(40)] }),+ message("h3"),+ ],+ transcriptAvailable: false,+};++function modelOf(current: ViewSession): LineageViewModel {+ return {+ kind: "lineage",+ schema: 1,+ project: { name: "p", path: "/p", generatedAt: T0 },+ status: { goal: "", done: [], pending: [], next: "", lastActivity: T0 },+ epochs: [{ id: "e1", title: "E", createdAt: T0, sessions: [current] }],+ unassigned: [],+ read: [],+ settings: {+ language: "auto",+ updateEveryTurns: 5,+ sessionEndCatchUp: true,+ catchUpModel: "haiku",+ messageSummaries: false,+ startupContext: true,+ shareConversations: false,+ recordCommit: "ask",+ gitPolicy: "ignore",+ agents: ["claude-code"],+ bigChangeLines: 300,+ },+ };+}++function renderGraph(readIds: ReadonlySet<string>): string {+ return renderToStaticMarkup(+ createElement(GitGraph, {+ git: layoutGitGraph(session.messages),+ selectedId: null,+ activeSegmentId: null,+ highlightIds: undefined,+ activeHitId: null,+ readIds,+ bigChangeLines: 300,+ onSelect: () => {},+ onUnfold: () => {},+ onContinue: () => {},+ }),+ );+}++describe("how much code landed on the map (10.3)", () => {+ it("puts a numstat chip on rows that have commits", () => {+ const html = renderGraph(new Set());+ expect(html).toContain('class="git-change"');+ expect(html).toContain("+1 200 −40 · 14 files");+ expect(html).toContain("+6 −2 · 1 file");+ // No commits: no chip, not a zero.+ expect(html.match(/class="git-change"/g)).toHaveLength(2);+ });++ it("marks an unread row above the threshold, and drops it once read", () => {+ expect(renderGraph(new Set())).toContain("is-unread-big");+ // The small unread message is not big; a read big one is no longer marked.+ const readBig = renderGraph(new Set(["h1"]));+ expect(readBig).not.toContain("is-unread-big");+ });++ it("keeps the threshold a setting, not a verdict", () => {+ const html = renderToStaticMarkup(+ createElement(GitGraph, {+ git: layoutGitGraph(session.messages),+ selectedId: null,+ activeSegmentId: null,+ highlightIds: undefined,+ activeHitId: null,+ readIds: new Set(),+ bigChangeLines: 10_000,+ onSelect: () => {},+ onUnfold: () => {},+ onContinue: () => {},+ }),+ );+ expect(html).not.toContain("is-unread-big");+ });++ it("lists unread messages with their numbers and the big mark", () => {+ const html = renderToStaticMarkup(+ createElement(UnreadView, {+ messages: [+ {+ sessionId: "s1",+ sessionTitle: "Session one",+ sessionStartedAt: T0,+ messageId: "h1",+ label: "m1",+ title: "Message h1",+ at: T0,+ change: BIG,+ },+ {+ sessionId: "s1",+ sessionTitle: "Session one",+ sessionStartedAt: T0,+ messageId: "h2",+ label: "m2",+ title: "Message h2",+ change: SMALL,+ },+ ],+ bigChangeLines: 300,+ active: { sessionId: "s1", messageId: "h2" },+ onSelect: () => {},+ onClose: () => {},+ }),+ );+ expect(html).toContain("Unread, most code first");+ expect(html).toContain("+1 200 −40 · 14 files");+ expect(html).toContain("is-active");+ expect((html.match(/is-big/g) ?? []).length).toBeGreaterThan(0);+ // The small row is active but not big.+ expect(html).toContain("unread-row is-active");+ });++ it("says plainly when nothing is unread", () => {+ const html = renderToStaticMarkup(+ createElement(UnreadView, {+ messages: [],+ bigChangeLines: 300,+ active: null,+ onSelect: () => {},+ onClose: () => {},+ }),+ );+ expect(html).toContain("No unread messages with commits");+ });++ it("shows the numbers and a read toggle in the drill-down", () => {+ const model = modelOf(session);+ const unread = renderToStaticMarkup(+ createElement(DrillDown, {+ model,+ selection: { type: "node", sessionId: "s1", nodeId: "h1" },+ onClose: () => {},+ read: false,+ onToggleRead: () => {},+ bigChangeLines: 300,+ readError: null,+ }),+ );+ expect(unread).toContain("Code landed");+ expect(unread).toContain("+1 200 −40 · 14 files");+ expect(unread).toContain("Mark as read");+ expect(unread).toContain("after this message");+ expect(unread).toContain("is-big");++ const read = renderToStaticMarkup(+ createElement(DrillDown, {+ model,+ selection: { type: "node", sessionId: "s1", nodeId: "h1" },+ onClose: () => {},+ read: true,+ onToggleRead: () => {},+ bigChangeLines: 300,+ readError: "could not write",+ }),+ );+ expect(read).toContain("Mark as unread");+ expect(read).toContain("could not write");+ expect(read).not.toContain("is-big");+ });++ it("shows the card count on the panel", () => {+ const model: PanelViewModel = {+ kind: "panel",+ schema: 1,+ generatedAt: T0,+ settings: modelOf(session).settings as PanelViewModel["settings"],+ projects: [+ {+ name: "p",+ path: "/p",+ missing: false,+ lastActivity: T0,+ needsUserCount: 0,+ lineageUrl: "file:///p/.cogit/map.html",+ unreadBigCount: 3,+ },+ ],+ };+ const html = renderToStaticMarkup(createElement(Panel, { model }));+ expect(html).toContain("Unread big changes");+ expect(html).toContain("<dd>3</dd>");+ });+});