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(captures): anchor captured items on their session
Eren581cd3c2cc48
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3a1947a..1e4b734 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- A `captures` setting (on by default, with a **?** in the settings panel) turns the drafting off; items already in the list are kept, not deleted.### Changed+- Captured items belong to their session, not to one message: the store is schema 2 (a schema-1 file is read with its message dropped and written back on the next change), the map marks the session's first message with the number of items it stands for, the message details list them under **Captured here** (read-only), and `cogit captures` names the session as the source.- The map's **Captured** button and `cogit captures` show the curated store instead of rows derived from the record, and the button appears only while the setting is on and something waits or is open.## [0.27.0] - 2026-10-31diff --git a/docs/guide/map.md b/docs/guide/map.mdindex 7050627..8a963d7 100644--- a/docs/guide/map.md+++ b/docs/guide/map.md@@ -139,11 +139,16 @@ open costs no model call.Each drafted item waits in **To review** until you choose: **Accept** keeps it in **Open**,**Dismiss** closes it without doing it. An open item is closed with **Done**. The last ten-closed items stay under **Done (last 10)**. Clicking a row opens the message that named it on-the map. The model never reopens or rewrites an item you already saw; closing is your act. In-the terminal: `cogit captures`, `cogit captures accept|dismiss|done <id>`, and-`cogit captures distill [--session <id> | --all] [--dry-run]` to backfill sessions by hand-(`--dry-run` prints the proposals and writes nothing).+closed items stay under **Done (last 10)**. An item belongs to the whole session it came from,+not to one message: the map anchors it on the session's **first message** and marks that row+with the number of items the session stands for (the session's own row while its messages are+folded away). Clicking a row, the mark or the source line opens that first message, whose details+list the session's items under **Captured here** — read-only, so a stray click cannot close+work; accepting, dismissing and closing stay in the Captured list. A session with no messages+anchors nowhere, and its items show only in the list. The model never reopens or rewrites an+item you already saw; closing is your act. In the terminal: `cogit captures`,+`cogit captures accept|dismiss|done <id>`, and `cogit captures distill [--session <id> | --all]+[--dry-run]` to backfill sessions by hand (`--dry-run` prints the proposals and writes nothing).It is not a task board: no assignment, no priority, no tracker state. The list lives in`.cogit/state/captures.json` on this machine and is never committed. The **Captured** buttondiff --git a/packages/cli/src/captures.ts b/packages/cli/src/captures.tsindex 100c27b..1cfd3c0 100644--- a/packages/cli/src/captures.ts+++ b/packages/cli/src/captures.ts@@ -20,10 +20,9 @@ import { buildMessages } from "./view/lineage.js";* and can be run by hand (`cogit captures distill`) for existing sessions.*/-/** One item the model proposes, with the recorded message it came from. */+/** One item the model proposes: a user-level leftover of the session. */export interface CaptureDraftItem {text: string;- messageId: string;}export interface DistillAnswer {@@ -82,7 +81,7 @@ export function distillPrompt(`- At most ${DISTILL_LIMIT} items. Each one is work a person would ask for, phrased as a short imperative (one line, at most 140 characters) in ${writing}.`,"- Name only work the user asked for and that is still not done, or that the session left undone. A problem a later message fixed, finished or dropped is done, not open.",'- Never draft a commit step, a test run, a release chore, a status fact ("0.24 is unreleased") or a question a later message answered.',- "- Each item carries `messageId`: the reference shown for the message it came from (m1, m2, …).",+ "- Items belong to the session, not to one message: do not name a message.","- Existing captured items are the user's list: never rephrase, merge or close them. Only put an id in `duplicateOf`.","",...current,@@ -91,14 +90,14 @@ export function distillPrompt(...(branches.length === 0 ? [] : ["Open branch lines:", ...branches]),...(messages.length === 0 ? [] : ["Last messages:", ...messages]),"",- `Return only one JSON object, no code fences: {"items": [{"text": "...", "messageId": "m3"}], "duplicateOf": []}`,+ `Return only one JSON object, no code fences: {"items": [{"text": "..."}], "duplicateOf": []}`,].join("\n");}/*** The model's answer, tolerated as an object (a code fence is stripped) with a- * missing or malformed list read as "nothing". Text and message refs are- * flattened and trimmed here; the store validates the rest.+ * missing or malformed list read as "nothing". Text is flattened and trimmed+ * here; the store validates the rest.*/export function parseDistillAnswer(text: string): DistillAnswer {const answer = agentRecord(text);@@ -106,11 +105,11 @@ export function parseDistillAnswer(text: string): DistillAnswer {const items: CaptureDraftItem[] = [];for (const raw of rawItems) {if (typeof raw !== "object" || raw === null) continue;- const { text: itemText, messageId } = raw as Record<string, unknown>;- if (typeof itemText !== "string" || typeof messageId !== "string") continue;+ const { text: itemText } = raw as Record<string, unknown>;+ if (typeof itemText !== "string") continue;const flat = itemText.replace(/\s+/g, " ").trim();if (flat === "") continue;- items.push({ text: flat, messageId: messageId.trim() });+ items.push({ text: flat });if (items.length >= DISTILL_LIMIT) break;}const rawDuplicates = Array.isArray(answer.duplicateOf) ? answer.duplicateOf : [];@@ -120,22 +119,6 @@ export function parseDistillAnswer(text: string): DistillAnswer {return { items, duplicateOf: duplicateOf.map((id) => id.trim()) };}-/** The newest recorded message id, the fallback when the model names none. */-function newestMessageId(input: CaptureInput): string {- return input.lastMessages.at(-1)?.id ?? input.pending[0]?.messageId ?? "";-}--/** The message id the model named, when it is a reference the session could show. */-export function resolveMessageId(input: CaptureInput, raw: string): string {- const ref = raw.trim();- if (ref !== "") {- if (input.lastMessages.some((message) => message.id === ref || message.label === ref))- return ref;- if (/^m[1-9][0-9]*$/.test(ref)) return ref;- }- return newestMessageId(input);-}-/** What one distill pass produced: the model's answer and the rows it added. */export interface CaptureProposal {sessionId: string;@@ -191,11 +174,7 @@ export async function distillSessionInput(const answer = parseDistillAnswer(resultText(await runClaude(prompt, config.sideModel, opts.io.env)),);- // An item with no recorded message to point at could never be opened from- // the map, so it is dropped rather than stored without a source.- const items = answer.items- .map((item) => ({ text: item.text, messageId: resolveMessageId(input, item.messageId) }))- .filter((item) => item.messageId !== "");+ const items = answer.items;const known = new Set(existing.map((item) => item.id));const duplicateOf = answer.duplicateOf.filter((id) => known.has(id));const now = opts.now ?? opts.io.now();@@ -261,7 +240,7 @@ export function formatProposal(proposal: CaptureProposal): string[] {if (proposal.items.length === 0) return [`${head} nothing to draft`];return [head,- ...proposal.items.map((item) => ` + ${item.text} (${item.messageId})`),+ ...proposal.items.map((item) => ` + ${item.text}`),...(proposal.duplicateOf.length === 0? []: [` still about: ${proposal.duplicateOf.join(", ")}`]),diff --git a/packages/cli/src/commands/captures.ts b/packages/cli/src/commands/captures.tsindex cf2e2c7..b531a6e 100644--- a/packages/cli/src/commands/captures.ts+++ b/packages/cli/src/commands/captures.ts@@ -12,7 +12,6 @@ import {import { loadAllSessions, loadConfig } from "../store/stores.js";import { captureInput, hasOpenWork } from "../view/captures.js";import { timeSince } from "../view/inbox.js";-import { buildMessages } from "../view/lineage.js";import {type EffectiveSession,loadEffectiveSessions,@@ -40,28 +39,26 @@ function oneLine(text: string): string {return text.replace(/\s+/g, " ").trim();}-/** `sessionId:messageId` → the message's `mN` label, from the records. */-async function messageLabels(+/** `sessionId` → the session's title, or its id when the record has none yet. */+async function sessionTitles(root: string,warn: (message: string) => void,): Promise<Map<string, string>> {- const labels = new Map<string, string>();+ const titles = new Map<string, string>();for (const session of await loadAllSessions(root, warn)) {- for (const message of buildMessages(session.nodes)) {- if (message.label !== undefined)- labels.set(`${session.sessionId}:${message.id}`, message.label);- }+ titles.set(session.sessionId, session.title || session.sessionId);}- return labels;+ return titles;}function newestFirst(a: CaptureItem, b: CaptureItem): number {return b.updatedAt.localeCompare(a.updatedAt) || a.id.localeCompare(b.id);}-function itemLine(item: CaptureItem, labels: ReadonlyMap<string, string>, now: string): string {- const label = labels.get(`${item.source.sessionId}:${item.source.messageId}`);- const source = [item.source.sessionId, label ?? item.source.messageId].join(" ");+function itemLine(item: CaptureItem, titles: ReadonlyMap<string, string>, now: string): string {+ // An item belongs to its session (Story 15.2): the title is the source, with+ // no message label to point at.+ const source = titles.get(item.source.sessionId) ?? item.source.sessionId;const age = timeSince(item.updatedAt, now);const meta = age === "" ? source : `${source} · ${age} ago`;return `${item.id} ${oneLine(item.text)} (${meta})`;@@ -74,13 +71,13 @@ function itemLine(item: CaptureItem, labels: ReadonlyMap<string, string>, now: s*/export function formatCaptures(store: Captures,- labels: ReadonlyMap<string, string> = new Map(),+ titles: ReadonlyMap<string, string> = new Map(),now = new Date().toISOString(),): string[] {const of = (state: CaptureState): CaptureItem[] =>store.items.filter((item) => item.state === state).sort(newestFirst);const section = (title: string, items: CaptureItem[]): string[] =>- items.length === 0 ? [] : [title, ...items.map((item) => ` ${itemLine(item, labels, now)}`)];+ items.length === 0 ? [] : [title, ...items.map((item) => ` ${itemLine(item, titles, now)}`)];const lines = [...section("To review", of("suggested")),...section("Open", of("open")),@@ -97,8 +94,8 @@ export async function captures(opts: CapturesOptions): Promise<Captures> {opts.io.out(JSON.stringify(store, null, 2));return store;}- const labels = await messageLabels(root, opts.io.warn);- for (const line of formatCaptures(store, labels, opts.now ?? opts.io.now())) opts.io.out(line);+ const titles = await sessionTitles(root, opts.io.warn);+ for (const line of formatCaptures(store, titles, opts.now ?? opts.io.now())) opts.io.out(line);return store;}diff --git a/packages/cli/src/store/captures.ts b/packages/cli/src/store/captures.tsindex 326480b..4732354 100644--- a/packages/cli/src/store/captures.ts+++ b/packages/cli/src/store/captures.ts@@ -13,9 +13,13 @@ import { projectPaths } from "./paths.js";** An item's id is minted once and never derived from its text, because the model* may rephrase a suggestion without it becoming a second row.+ *+ * Story 15.2 made an item belong to a session, not a single message: a leftover+ * is usually the outcome of the whole session, and the model's chosen message+ * was arbitrary. The map anchors each item on the session's first message.*/-export const CAPTURES_SCHEMA = 1;+export const CAPTURES_SCHEMA = 2;const SESSION_ID = /^[A-Za-z0-9._:-]{1,128}$/;/** A random `c` followed by eight hex characters. */@@ -30,10 +34,9 @@ export const CaptureItem = z.object({id: z.string().regex(CAPTURE_ID),text: z.string().trim().min(1).max(CAPTURE_TEXT_MAX),state: CaptureState,- /** The recorded message the item came from. */+ /** The recorded session the item came from. */source: z.object({sessionId: z.string().regex(SESSION_ID),- messageId: z.string().min(1).max(128),}),createdAt: IsoDate,updatedAt: IsoDate,@@ -48,6 +51,38 @@ export const Captures = z.object({});export type Captures = z.infer<typeof Captures>;+/**+ * A schema-1 item pointed at the message the model named (Story 15.1). It is+ * read only to migrate the file: the message is dropped, the rest is kept.+ */+const CaptureItemV1 = CaptureItem.extend({+ source: z.object({+ sessionId: z.string().regex(SESSION_ID),+ messageId: z.string().min(1).max(128),+ }),+});++const CapturesV1 = z.object({+ schema: z.literal(1),+ items: z.array(CaptureItemV1).default([]),+});++/** A schema-1 file becomes the current shape; the next write stores it as 2. */+function migrateV1(store: z.infer<typeof CapturesV1>): Captures {+ return {+ schema: CAPTURES_SCHEMA,+ items: store.items.map((item) => ({+ id: item.id,+ text: item.text,+ state: item.state,+ source: { sessionId: item.source.sessionId },+ createdAt: item.createdAt,+ updatedAt: item.updatedAt,+ ...(item.closedAt === undefined ? {} : { closedAt: item.closedAt }),+ })),+ };+}+/** A missing file is an empty list, not an error. */export function emptyCaptures(): Captures {return { schema: CAPTURES_SCHEMA, items: [] };@@ -114,19 +149,19 @@ export async function readCaptures(const read = await readJson(file);if (!read.found) return emptyCaptures();const parsed = "error" in read ? undefined : Captures.safeParse(read.value);- if (parsed === undefined || !parsed.success) {- warn?.(`ignored a corrupt ${file}; starting with an empty captured list`);- // Replace it so the next read is clean; a failed repair is not fatal either.- await atomicWriteJson(file, emptyCaptures()).catch(() => undefined);- return emptyCaptures();- }- return parsed.data;+ if (parsed !== undefined && parsed.success) return parsed.data;+ // A file from before Story 15.2 keeps its items; only the message is dropped.+ const legacy = "error" in read ? undefined : CapturesV1.safeParse(read.value);+ if (legacy !== undefined && legacy.success) return migrateV1(legacy.data);+ warn?.(`ignored a corrupt ${file}; starting with an empty captured list`);+ // Replace it so the next read is clean; a failed repair is not fatal either.+ await atomicWriteJson(file, emptyCaptures()).catch(() => undefined);+ return emptyCaptures();}-/** A rephrase from the model for one recorded message. */+/** A rephrase from the model for one session. */export interface CaptureDraft {text: string;- messageId: string;}export interface AddCapturesOptions {@@ -177,7 +212,7 @@ export async function addCaptureSuggestions(id,text,state: "suggested",- source: { sessionId, messageId: draft.messageId },+ source: { sessionId },createdAt: opts.now,updatedAt: opts.now,};diff --git a/packages/cli/src/view/model.ts b/packages/cli/src/view/model.tsindex d381b6e..4e0353f 100644--- a/packages/cli/src/view/model.ts+++ b/packages/cli/src/view/model.ts@@ -368,8 +368,11 @@ export interface ViewCapture {text: string;/** `suggested` waits for the user; `open` is accepted; `dismissed` and `done` are closed. */state: "suggested" | "open" | "dismissed" | "done";- /** The recorded message the item came from. */- source: { sessionId: string; messageId: string };+ /**+ * The recorded session the item came from. An item belongs to a whole session+ * (Story 15.2); the map anchors it on the session's first message.+ */+ source: { sessionId: string };createdAt: string;updatedAt: string;/** Set when the item became `done`. */diff --git a/packages/cli/test/captures.test.ts b/packages/cli/test/captures.test.tsindex c7c49fd..5ede343 100644--- a/packages/cli/test/captures.test.ts+++ b/packages/cli/test/captures.test.ts@@ -6,7 +6,6 @@ import {distillPrompt,distillSessionInput,parseDistillAnswer,- resolveMessageId,sessionInput,} from "../src/captures.js";import { buildProject } from "../src/commands/build.js";@@ -106,58 +105,26 @@ describe("the distiller's prompt and answer", () => {expect(prompt).toContain('"duplicateOf"');expect(prompt).toContain("at most 140 characters");expect(prompt).toContain("the conversation's language");- expect(prompt).toContain('{"items": [{"text": "...", "messageId": "m3"}]');+ expect(prompt).toContain("Items belong to the session");+ expect(prompt).toContain('{"items": [{"text": "..."}], "duplicateOf": []}');+ expect(prompt).not.toContain("messageId");});it("reads the answer, flattening the text and dropping malformed rows", () => {const answer = JSON.stringify({items: [{ text: " write the docs ", messageId: "m1" },- { text: "", messageId: "m2" },- { text: "no message" },- { text: "fix the parser", messageId: "m2" },+ { text: "" },+ 7,+ { text: "fix the parser" },],duplicateOf: ["c11111111", 7],});expect(parseDistillAnswer(`\`\`\`json\n${answer}\n\`\`\``)).toEqual({- items: [- { text: "write the docs", messageId: "m1" },- { text: "fix the parser", messageId: "m2" },- ],+ items: [{ text: "write the docs" }, { text: "fix the parser" }],duplicateOf: ["c11111111"],});});-- it("keeps a named message, a numeric one, or falls back to the newest", () => {- const withMessage = captureInput(- source({- sessionId: "s1",- status: { pending: [{ text: "p", needsUser: false }] },- messages: [{ id: "m2", label: "m2", title: "T" }],- }),- );- expect(resolveMessageId(withMessage, "m2")).toBe("m2");- expect(resolveMessageId(withMessage, "m7")).toBe("m7");- expect(resolveMessageId(withMessage, "h123")).toBe("m2");- // A pending line can carry the message it points at even with no titles.- expect(- resolveMessageId(- {- sessionId: "s1",- title: "t",- pending: [{ text: "p", needsUser: false, messageId: "m4" }],- branches: [],- lastMessages: [],- },- "",- ),- ).toBe("m4");- expect(resolveMessageId(withMessage, "")).toBe("m2");- const nothing = captureInput(- source({ sessionId: "s1", status: { pending: [{ text: "p", needsUser: false }] } }),- );- expect(resolveMessageId(nothing, "h9")).toBe("");- });});describe("the captured store", () => {@@ -172,26 +139,18 @@ describe("the captured store", () => {});it("round-trips suggestions and moves only updatedAt for duplicates", async () => {- const first = await addCaptureSuggestions(- root,- "s1",- [{ text: "write the docs", messageId: "m1" }],- { now: T0 },- );+ const first = await addCaptureSuggestions(root, "s1", [{ text: "write the docs" }], {+ now: T0,+ });expect(first).toHaveLength(1);expect(first[0]?.id).toMatch(/^c[0-9a-f]{8}$/);const open = await setCaptureState(root, first[0]?.id as string, "open", T0);expect(open.state).toBe("open");const later = "2026-10-22T00:00:00.000Z";- const added = await addCaptureSuggestions(- root,- "s2",- [{ text: "write the docs", messageId: "m1" }],- {- now: later,- duplicateOf: [open.id],- },- );+ const added = await addCaptureSuggestions(root, "s2", [{ text: "write the docs" }], {+ now: later,+ duplicateOf: [open.id],+ });expect(added).toEqual([]);const store = await readCaptures(root);expect(store.items).toHaveLength(1);@@ -199,7 +158,7 @@ describe("the captured store", () => {});it("records closedAt on done and refuses an impossible transition", async () => {- const [item] = await addCaptureSuggestions(root, "s1", [{ text: "x", messageId: "m1" }], {+ const [item] = await addCaptureSuggestions(root, "s1", [{ text: "x" }], {now: T0,});await expect(setCaptureState(root, item?.id as string, "done", T0)).rejects.toThrow(@@ -227,6 +186,62 @@ describe("the captured store", () => {items: [],});});++ it("reads a schema-1 file by dropping each item's message and keeping the rest", async () => {+ await mkdir(join(root, ".cogit", "state"), { recursive: true });+ await writeFile(+ projectPaths(root).captures,+ JSON.stringify({+ schema: 1,+ items: [+ {+ id: "c00000001",+ text: "one",+ state: "open",+ source: { sessionId: "s1", messageId: "m3" },+ createdAt: NOW,+ updatedAt: NOW,+ },+ {+ id: "c00000002",+ text: "two",+ state: "done",+ source: { sessionId: "s2", messageId: "m9" },+ createdAt: NOW,+ updatedAt: NOW,+ closedAt: NOW,+ },+ ],+ }),+ );+ expect(await readCaptures(root)).toEqual({+ schema: CAPTURES_SCHEMA,+ items: [+ {+ id: "c00000001",+ text: "one",+ state: "open",+ source: { sessionId: "s1" },+ createdAt: NOW,+ updatedAt: NOW,+ },+ {+ id: "c00000002",+ text: "two",+ state: "done",+ source: { sessionId: "s2" },+ createdAt: NOW,+ updatedAt: NOW,+ closedAt: NOW,+ },+ ],+ });+ // The next change writes the migrated shape; the message stays dropped.+ await setCaptureState(root, "c00000001", "done", NOW);+ const file = JSON.parse(await readFile(projectPaths(root).captures, "utf8"));+ expect(file.schema).toBe(CAPTURES_SCHEMA);+ expect(file.items[0].source).toEqual({ sessionId: "s1" });+ });});describe("formatCaptures", () => {@@ -234,7 +249,7 @@ describe("formatCaptures", () => {over: Partial<CaptureItem> & { id: string; state: CaptureItem["state"] },): CaptureItem => ({text: "text",- source: { sessionId: "s1", messageId: "m3" },+ source: { sessionId: "s1" },createdAt: NOW,updatedAt: NOW,...over,@@ -253,17 +268,17 @@ describe("formatCaptures", () => {item({ id: "c00000004", state: "dismissed", text: "gone" }),],},- new Map([["s1:m3", "m3"]]),+ new Map([["s1", "Parser"]]),NOW,);expect(lines).toEqual(["To review",- " c00000001 same time (s1 m3 · under a minute ago)",- " c00000005 review me (s1 m3 · under a minute ago)",+ " c00000001 same time (Parser · under a minute ago)",+ " c00000005 review me (Parser · under a minute ago)","Open",- " c00000002 accepted (s1 m3 · under a minute ago)",+ " c00000002 accepted (Parser · under a minute ago)","Done",- " c00000003 closed (s1 m3 · under a minute ago)",+ " c00000003 closed (Parser · under a minute ago)",]);});@@ -311,33 +326,29 @@ describe("cogit captures", () => {await writeFile(projectPaths(root).session("s1"), JSON.stringify(s1));});- it("prints the sections, with the source label and the age", async () => {- await addCaptureSuggestions(- root,- "s1",- [{ text: "decide the error format", messageId: "m1" }],- {- now: "2026-10-21T08:00:00.000Z",- },- );+ it("prints the sections, with the session title as the source and the age", async () => {+ await addCaptureSuggestions(root, "s1", [{ text: "decide the error format" }], {+ now: "2026-10-21T08:00:00.000Z",+ });const store = await captures({ dir: root, io, now: NOW });expect(store.items).toHaveLength(1);const [header, line] = io.lines;expect(header).toBe("To review");expect(line).toContain("decide the error format");- expect(line).toContain("s1 m1");+ expect(line).toContain("Parser");+ expect(line).not.toContain(" m1");expect(line).toContain("2 h ago");});it("prints the store as JSON", async () => {- await addCaptureSuggestions(root, "s1", [{ text: "one", messageId: "m1" }], { now: NOW });+ await addCaptureSuggestions(root, "s1", [{ text: "one" }], { now: NOW });await captures({ dir: root, io, json: true });const store = JSON.parse(io.lines.join("\n"));expect(store.items[0]).toMatchObject({ text: "one", state: "suggested" });});it("accepts, dismisses and closes an item", async () => {- const [item] = await addCaptureSuggestions(root, "s1", [{ text: "one", messageId: "m1" }], {+ const [item] = await addCaptureSuggestions(root, "s1", [{ text: "one" }], {now: NOW,});await setCapture(root, "accept", item?.id as string, io);@@ -347,7 +358,7 @@ describe("cogit captures", () => {await expect(setCapture(root, "dismiss", "c00000000", fakeIo(envFor(dir)))).rejects.toThrow("no captured item",);- const [fresh] = await addCaptureSuggestions(root, "s1", [{ text: "two", messageId: "m1" }], {+ const [fresh] = await addCaptureSuggestions(root, "s1", [{ text: "two" }], {now: NOW,});await expect(setCapture(root, "done", fresh?.id as string, io)).rejects.toThrow(@@ -356,14 +367,14 @@ describe("cogit captures", () => {});it("lets an unreadable store's own error through", async () => {- await addCaptureSuggestions(root, "s1", [{ text: "one", messageId: "m1" }], { now: NOW });+ await addCaptureSuggestions(root, "s1", [{ text: "one" }], { now: NOW });await rm(projectPaths(root).captures, { force: true });await mkdir(projectPaths(root).captures, { recursive: true });await expect(setCapture(root, "accept", "c00000000", io)).rejects.toThrow(/EISDIR/);});it("is carried in the map's page model", async () => {- await addCaptureSuggestions(root, "s1", [{ text: "one", messageId: "m1" }], { now: NOW });+ await addCaptureSuggestions(root, "s1", [{ text: "one" }], { now: NOW });const model = await buildProject({ dir: root, io, templateHtml: TEMPLATE, quiet: true });expect(model.captures?.map((row) => row.text)).toEqual(["one"]);expect(model.settings?.captures).toBe(true);@@ -423,7 +434,7 @@ process.stdin.on("end", async () => {dir = await tempDir();root = join(dir, "proj");await mkdir(root);- await fakeClaude({ items: [{ text: "write the docs", messageId: "m2" }], duplicateOf: [] });+ await fakeClaude({ items: [{ text: "write the docs" }], duplicateOf: [] });await init(root, { name: "proj", retention: "keep", language: "auto" }, fakeIo(env));await writeFile(projectPaths(root).session("s1"), JSON.stringify(s1()));// A session with nothing left open costs no call; --all passes over it.@@ -436,15 +447,15 @@ process.stdin.on("end", async () => {await writeFile(projectPaths(root).session("s2"), JSON.stringify(s2));});- it("writes the answer as a suggested item with its source message", async () => {+ it("writes the answer as a suggested item that belongs to its session", async () => {const result = await distillSessionInput(root, sessionInput(s1()), { io });- expect(result?.proposal.items).toEqual([{ text: "write the docs", messageId: "m2" }]);+ expect(result?.proposal.items).toEqual([{ text: "write the docs" }]);const store = await readCaptures(root);expect(store.items).toHaveLength(1);expect(store.items[0]).toMatchObject({state: "suggested",text: "write the docs",- source: { sessionId: "s1", messageId: "m2" },+ source: { sessionId: "s1" },});});@@ -476,15 +487,12 @@ process.stdin.on("end", async () => {});it("reads the existing list and keeps an item the session is still about", async () => {- const [existing] = await addCaptureSuggestions(- root,- "s1",- [{ text: "write the docs", messageId: "m2" }],- { now: T0 },- );+ const [existing] = await addCaptureSuggestions(root, "s1", [{ text: "write the docs" }], {+ now: T0,+ });await setCaptureState(root, existing?.id as string, "open", T0);await fakeClaude({- items: [{ text: "write the docs", messageId: "m2" }],+ items: [{ text: "write the docs" }],duplicateOf: [existing?.id, "c00000000"],});const later = "2026-10-22T00:00:00.000Z";@@ -497,12 +505,12 @@ process.stdin.on("end", async () => {expect(store.items[0]).toMatchObject({ id: existing?.id, state: "open", updatedAt: later });});- it("drops an item with no message to point at", async () => {- await fakeClaude({ items: [{ text: "orphan", messageId: "h9" }], duplicateOf: [] });+ it("stores an item for a session with no messages to anchor", async () => {+ await fakeClaude({ items: [{ text: "orphan" }], duplicateOf: [] });const record = { ...s1(), nodes: [] };const result = await distillSessionInput(root, sessionInput(record), { io });- expect(result?.proposal.items).toEqual([]);- expect((await readCaptures(root)).items).toEqual([]);+ expect(result?.proposal.items).toEqual([{ text: "orphan" }]);+ expect((await readCaptures(root)).items[0]?.source).toEqual({ sessionId: "s1" });});it("refuses a hand-run pass with captures off", async () => {@@ -555,14 +563,9 @@ process.stdin.on("end", async () => {from: "user",});expect(io.lines.join("\n")).toContain('Session s1 "Parser"');- const [item] = await addCaptureSuggestions(- root,- "s1",- [{ text: "cli item", messageId: "m1" }],- {- now: T0,- },- );+ const [item] = await addCaptureSuggestions(root, "s1", [{ text: "cli item" }], {+ now: T0,+ });await program.parseAsync(["captures", "accept", item?.id as string, "--dir", root], {from: "user",});@@ -585,7 +588,7 @@ process.stdin.setEncoding("utf8");process.stdin.on("data", (c) => { input += c; });process.stdin.on("end", () => {const answer = input.includes("You distil")- ? JSON.stringify({ items: [{ text: "write the docs", messageId: "m1" }], duplicateOf: [] })+ ? JSON.stringify({ items: [{ text: "write the docs" }], duplicateOf: [] }): JSON.stringify({threads: [{ name: "Work", messages: "m1-m2", from: null, asked: "a", outcome: "o", open: "docs unwritten" }],leftOff: "The docs are unwritten",diff --git a/packages/cli/test/server.test.ts b/packages/cli/test/server.test.tsindex 42513b6..4b8d95d 100644--- a/packages/cli/test/server.test.ts+++ b/packages/cli/test/server.test.ts@@ -994,12 +994,9 @@ describe("captures state endpoint (Story 15.1)", () => {}async function suggested(): Promise<string> {- const [item] = await addCaptureSuggestions(- root,- "s1",- [{ text: "write the docs", messageId: "m1" }],- { now: T0 },- );+ const [item] = await addCaptureSuggestions(root, "s1", [{ text: "write the docs" }], {+ now: T0,+ });return item?.id as string;}diff --git a/packages/template/src/CapturesView.tsx b/packages/template/src/CapturesView.tsxindex 9845d0a..b3b5a7c 100644--- a/packages/template/src/CapturesView.tsx+++ b/packages/template/src/CapturesView.tsx@@ -10,8 +10,9 @@ import { formatStamp } from "./format.js";* sessions left open, and the user curates. "To review" holds the suggestions* (Accept or Dismiss), "Open" the accepted ones (Done), and "Done" the last ten* that were closed. The list is the user's, not a plan cogit keeps: no- * assignment, no priority, no tracker state. Clicking a row's source opens the- * message that named it, the same drill-down the files view gives.+ * assignment, no priority, no tracker state. An item belongs to its session, so+ * clicking a row's source opens the session's first message — where the map+ * anchors its captured work.*/type CaptureState = ViewCapture["state"];@@ -41,6 +42,82 @@ function byNewest(a: ViewCapture, b: ViewCapture): number {return b.updatedAt.localeCompare(a.updatedAt);}+/** Where clicking an item's source takes the map: the session's first message. */+export interface CaptureSource {+ sessionTitle: string;+ /** The first message's `mN` label; absent when the session has no messages. */+ label?: string | undefined;+ /** The message to open; absent when the session has no messages to anchor. */+ target?: { sessionId: string; messageId: string } | undefined;+}++/**+ * An item belongs to its session (Story 15.2). The session's **first message in+ * send order** is the honest anchor — a session has no node of its own in the+ * record — and the map draws it as the session's root, even when the session+ * continues another one. A session with no messages anchors nowhere.+ */+export function captureSource(+ source: { sessionId: string },+ sessions: readonly ViewSession[],+): CaptureSource {+ const session = sessions.find((candidate) => candidate.sessionId === source.sessionId);+ if (session === undefined) return { sessionTitle: source.sessionId };+ const first = session.messages[0];+ const sessionTitle = session.title || session.sessionId;+ if (first === undefined) return { sessionTitle };+ return {+ sessionTitle,+ label: first.label ?? first.id,+ target: { sessionId: session.sessionId, messageId: first.id },+ };+}++/**+ * How many `suggested` + `open` items each session stands for, for the map's+ * capture mark. `done` and `dismissed` items are closed and count nothing, so a+ * store of only done items marks no row, like the Captured button.+ */+export function captureCounts(captures: readonly ViewCapture[] | undefined): Map<string, number> {+ const counts = new Map<string, number>();+ for (const item of captures ?? []) {+ if (item.state !== "suggested" && item.state !== "open") continue;+ counts.set(item.source.sessionId, (counts.get(item.source.sessionId) ?? 0) + 1);+ }+ return counts;+}++/** Where each session's capture mark is drawn. */+export interface CapturePlacements {+ /** The session row, for a session whose anchor message is not drawn. */+ sessions: Map<string, { count: number; messageId: string }>;+ /** The anchor's message row, by message id. */+ messages: Map<string, number>;+}++/**+ * Places each session's mark on the row the map actually draws: the anchored+ * first message when its row is visible, otherwise the session's own row (a+ * closed session, or a first message folded away). `visible` answers whether a+ * message row is on the map right now.+ */+export function capturePlacements(+ captures: readonly ViewCapture[] | undefined,+ sessions: readonly ViewSession[],+ visible: (sessionId: string, messageId: string) => boolean,+): CapturePlacements {+ const counts = captureCounts(captures);+ const placements: CapturePlacements = { sessions: new Map(), messages: new Map() };+ for (const session of sessions) {+ const count = counts.get(session.sessionId);+ const messageId = session.messages[0]?.id;+ if (count === undefined || messageId === undefined) continue;+ if (visible(session.sessionId, messageId)) placements.messages.set(messageId, count);+ else placements.sessions.set(session.sessionId, { count, messageId });+ }+ return placements;+}+export function CapturesView({captures,sessions,@@ -50,7 +127,7 @@ export function CapturesView({onClose,}: {captures: readonly ViewCapture[] | undefined;- /** The project's sessions, for the title of each item's source message. */+ /** The project's sessions, for each item's source title and anchored message. */sessions: readonly ViewSession[];/** The project's path, for the state write. */dir: string;@@ -66,15 +143,6 @@ export function CapturesView({useEffect(() => setItems(captures ?? []), [captures]);const now = new Date().toISOString();- const titles = new Map(- sessions.map((session) => [session.sessionId, session.title || session.sessionId]),- );- const labels = new Map<string, string>();- for (const session of sessions)- for (const message of session.messages)- if (message.label !== undefined)- labels.set(`${session.sessionId}:${message.id}`, message.label);-function change(item: ViewCapture, state: CaptureTarget): void {const token = pageToken();if (token === null) {@@ -95,11 +163,12 @@ export function CapturesView({const done = stateTarget(items, "done").sort(byNewest).slice(0, 10);function row(item: ViewCapture, actions: ReactNode) {- const sessionTitle = titles.get(item.source.sessionId) ?? item.source.sessionId;- const label = labels.get(`${item.source.sessionId}:${item.source.messageId}`);+ const source = captureSource(item.source, sessions);const age = timeSince(item.updatedAt, now);const selected =- active?.sessionId === item.source.sessionId && active.messageId === item.source.messageId;+ source.target !== undefined &&+ active?.sessionId === source.target.sessionId &&+ active.messageId === source.target.messageId;return (<li key={item.id}><div className={`capture-row${selected ? " is-active" : ""}`}>@@ -107,14 +176,17 @@ export function CapturesView({type="button"className="capture-open"title={formatStamp(item.updatedAt)}- onClick={() =>- onSelect({ sessionId: item.source.sessionId, messageId: item.source.messageId })- }+ disabled={source.target === undefined}+ onClick={() => {+ if (source.target !== undefined) onSelect(source.target);+ }}><span className="capture-text">{item.text}</span><span className="capture-meta">- <span className="capture-session">{sessionTitle}</span>- <span className="capture-label">{label ?? item.source.messageId}</span>+ <span className="capture-session">{source.sessionTitle}</span>+ {source.label === undefined ? null : (+ <span className="capture-label">{source.label}</span>+ )}{age === "" ? null : <span className="capture-time">{age} ago</span>}</span></button>diff --git a/packages/template/src/GitGraph.tsx b/packages/template/src/GitGraph.tsxindex cfc7fb3..01309ce 100644--- a/packages/template/src/GitGraph.tsx+++ b/packages/template/src/GitGraph.tsx@@ -33,6 +33,7 @@ function Row({searchHit,searchActive,bigChangeLines,+ captured,onSelect,onUnfold,}: {@@ -46,6 +47,8 @@ function Row({searchActive: boolean;/** A change at or above this many lines gets the quiet highlight. */bigChangeLines: number;+ /** Suggested + open captured items this message anchors (Story 15.2). */+ captured?: number | undefined;onSelect: (row: GitMessageRow) => void;onUnfold: (segmentId: string) => void;}) {@@ -99,6 +102,20 @@ function Row({<span className="git-time">{rowRange(row, sameDay)}</span><span className="git-id">{message.label ?? message.id}</span><span className="git-title">{message.title}</span>+ {captured === undefined ? null : (+ // A span, not a button: the whole row is already a button. The mark is+ // the session's captured work, anchored on its first message.+ <span+ className="capture-mark git-capture"+ title={`${captured} captured item${captured === 1 ? "" : "s"} from this session`}+ onClick={(event: MouseEvent) => {+ event.stopPropagation();+ onSelect(row);+ }}+ >+ {captured}+ </span>+ )}{row.tags.length > 0 ? (<span className="git-tags">{row.tags.map((tag) => (@@ -141,6 +158,7 @@ export function GitGraph({highlightIds,activeHitId,bigChangeLines,+ captured,onSelect,onUnfold,}: {@@ -154,6 +172,8 @@ export function GitGraph({activeHitId: string | null;/** A change at or above this many lines gets the quiet highlight. */bigChangeLines: number;+ /** Suggested + open captured items, by the message id that anchors them. */+ captured?: ReadonlyMap<string, number> | undefined;onSelect: (row: GitMessageRow) => void;onUnfold: (segmentId: string) => void;}) {@@ -246,6 +266,7 @@ export function GitGraph({searchHit={messageId !== null && highlightIds?.has(messageId) === true}searchActive={messageId !== null && activeHitId !== null && messageId === activeHitId}bigChangeLines={bigChangeLines}+ captured={messageId === null ? undefined : captured?.get(messageId)}onSelect={onSelect}onUnfold={onUnfold}/>diff --git a/packages/template/src/Graph.tsx b/packages/template/src/Graph.tsxindex 02f14ed..5030d26 100644--- a/packages/template/src/Graph.tsx+++ b/packages/template/src/Graph.tsx@@ -19,7 +19,7 @@ import {} from "react";import type { LineageViewModel, ViewSession } from "../../cli/src/view/model.js";import { hitMessageIds, hitSessionIds } from "../../cli/src/view/search.js";-import { CapturesView, capturesButtonVisible } from "./CapturesView.js";+import { CapturesView, capturePlacements, capturesButtonVisible } from "./CapturesView.js";import { loadMapView, pageToken, saveOpenSessions, saveRowWidth } from "./data.js";import { type FilesTarget, FilesView } from "./FilesView.js";import { useFullscreen } from "./fullscreen.js";@@ -102,11 +102,14 @@ function SessionMessages({git,highlights,activeHitId,+ captured,}: {session: ViewSession;git: GitLayout;highlights: ReadonlySet<string> | undefined;activeHitId: string | null;+ /** Capture marks for message rows, by the anchor message id (Story 15.2). */+ captured?: ReadonlyMap<string, number> | undefined;}) {const { selection, bigChangeLines, openNode, unfold, resizeRows, storeRowWidth, person, people } =useContext(GraphActions);@@ -122,6 +125,7 @@ function SessionMessages({highlightIds={highlights}activeHitId={activeHitId}bigChangeLines={bigChangeLines}+ captured={captured}onSelect={(row) => openNode(session.sessionId, row.message.id)}onUnfold={unfold}/>@@ -135,7 +139,18 @@ function SessionMessages({}function ProjectBox({ data }: NodeProps<ProjectFlowNode>) {- const { openSession, openContinue, selection, openIds, person } = useContext(GraphActions);+ const { openSession, openNode, openContinue, selection, openIds, person } =+ useContext(GraphActions);+ // A captured-work mark goes on the anchored message row when it is drawn; a+ // session whose first message is not showing (folded away by branch folding,+ // or the session is closed) carries the mark on its own row instead.+ const capture = capturePlacements(data.model.captures, data.model.sessions, (sessionId, id) =>+ data.openings.some(+ (opening) =>+ opening.session.sessionId === sessionId &&+ opening.git.rows.some((row) => row.kind === "message" && row.message.id === id),+ ),+ );return (<div className="map-node"><SessionMap@@ -146,7 +161,9 @@ function ProjectBox({ data }: NodeProps<ProjectFlowNode>) {openIds={openIds}highlightSessionIds={data.sessionHits}person={person}+ captured={capture.sessions}onOpen={openSession}+ onOpenMessage={openNode}onContinue={openContinue}/>{data.openings.map((opening) => {@@ -164,6 +181,7 @@ function ProjectBox({ data }: NodeProps<ProjectFlowNode>) {activeHitId={active?.sessionId === opening.session.sessionId ? active.messageId : null}+ captured={capture.messages}/></div>);diff --git a/packages/template/src/SessionMap.tsx b/packages/template/src/SessionMap.tsxindex 34ec7c9..3b05640 100644--- a/packages/template/src/SessionMap.tsx+++ b/packages/template/src/SessionMap.tsx@@ -27,7 +27,9 @@ function SessionRow({selected,open,searchHit,+ captured,onOpen,+ onOpenMessage,onContinue,}: {row: GitMessageRow;@@ -41,7 +43,11 @@ function SessionRow({open: boolean;/** The session's title or status matches the search (Story 8.14). */searchHit: boolean;+ /** Suggested + open captured items whose anchor is not shown on a message row. */+ captured?: { count: number; messageId: string } | undefined;onOpen: (sessionId: string) => void;+ /** Selects one message and opens its details (the capture mark, Story 15.2). */+ onOpenMessage: (sessionId: string, messageId: string) => void;onContinue: (continues: NonNullable<ViewSession["messages"][number]["continues"]>) => void;}) {const continues = session.messages[0]?.continues;@@ -73,6 +79,18 @@ function SessionRow({</span><span className="git-time">{session.startedAt ? formatStamp(session.startedAt) : ""}</span><span className="git-title">{session.title || session.sessionId}</span>+ {captured === undefined ? null : (+ <span+ className="capture-mark session-capture"+ title={`${captured.count} captured item${captured.count === 1 ? "" : "s"} from this session`}+ onClick={(event: MouseEvent) => {+ event.stopPropagation();+ onOpenMessage(session.sessionId, captured.messageId);+ }}+ >+ {captured.count}+ </span>+ )}{showAuthor && session.author ? (<span className="muted session-author" title={`Recorded by ${session.author}`}>{session.author}@@ -110,7 +128,9 @@ export function SessionMap({openIds,highlightSessionIds,person = null,+ captured,onOpen,+ onOpenMessage,onContinue,}: {model: LineageViewModel;@@ -122,7 +142,10 @@ export function SessionMap({highlightSessionIds: ReadonlySet<string>;/** The person filter: everyone when left out. */person?: PersonFilter;+ /** Captured-work marks, by session id (Story 15.2). */+ captured?: ReadonlyMap<string, { count: number; messageId: string }> | undefined;onOpen: (sessionId: string) => void;+ onOpenMessage: (sessionId: string, messageId: string) => void;onContinue: (sessionId: string, messageId: string) => void;}) {const { git } = graph;@@ -221,7 +244,9 @@ export function SessionMap({selected={selectedSessionId === session.sessionId}open={openIds.has(session.sessionId)}searchHit={highlightSessionIds.has(session.sessionId)}+ captured={captured?.get(session.sessionId)}onOpen={onOpen}+ onOpenMessage={onOpenMessage}onContinue={(continues) => onContinue(continues.sessionId, continues.id)}/>);diff --git a/packages/template/src/SidePanel.tsx b/packages/template/src/SidePanel.tsxindex d2a7d89..17c12cb 100644--- a/packages/template/src/SidePanel.tsx+++ b/packages/template/src/SidePanel.tsx@@ -1,7 +1,9 @@import { type ReactNode, useEffect, useRef, useState } from "react";import { formatChange, isBigChange } from "../../cli/src/view/change.js";+import { timeSince } from "../../cli/src/view/inbox.js";import type {LineageViewModel,+ ViewCapture,ViewChatTurn,ViewNode,ViewSession,@@ -107,6 +109,48 @@ function Field({ label, children }: { label: string; children: React.ReactNode });}+const CAPTURE_STATE_LABEL = {+ suggested: "To review",+ open: "Open",+ done: "Done",+ dismissed: "Dismissed",+} as const;++/**+ * The captured work a whole session stands for (Story 15.2), shown on its first+ * message — the anchor the map marks. Read-only: accepting, dismissing or+ * closing stays in the Captured list, so a stray click here cannot close work.+ */+function CapturedHere({ items }: { items: readonly ViewCapture[] }) {+ // A dismissed item is closed away from the reading view, like in the list.+ const shown = items+ .filter((item) => item.state !== "dismissed")+ .sort((a, b) => b.updatedAt.localeCompare(a.updatedAt));+ if (shown.length === 0) return null;+ const now = new Date().toISOString();+ return (+ <section className="captured-here">+ <h3>+ Captured here <span className="count">{shown.length}</span>+ </h3>+ <ul className="drilldown-list capture-here-list">+ {shown.map((item) => {+ const age = timeSince(item.updatedAt, now);+ return (+ <li key={item.id}>+ <span className={`capture-state is-${item.state}`}>+ {CAPTURE_STATE_LABEL[item.state]}+ </span>{" "}+ {item.text}+ {age === "" ? null : <span className="muted"> · {age} ago</span>}+ </li>+ );+ })}+ </ul>+ </section>+ );+}+/** Where a session ran when it was not the main checkout. */function WorktreeField({ session }: { session: ViewSession }) {const { worktree } = session;@@ -371,6 +415,13 @@ function NodeDetails({{node.decidedBy ? (<p className="decided-by">Decided by: {DECIDED_LABEL[node.decidedBy]}</p>) : null}+ {node.kind === "message" && session?.messages[0]?.id === node.nodeId ? (+ <CapturedHere+ items={(model.captures ?? []).filter(+ (item) => item.source.sessionId === session.sessionId,+ )}+ />+ ) : null}{node.agentDecisions?.length ? (<section><h3>Decided by the agent on its own</h3>diff --git a/packages/template/src/styles.css b/packages/template/src/styles.cssindex f1d2536..370c3f7 100644--- a/packages/template/src/styles.css+++ b/packages/template/src/styles.css@@ -1291,6 +1291,44 @@ body:has(.map-shell.is-expanded) {overflow-wrap: anywhere;}+/* Story 15.2: the mark on the message or session row a session's items anchor on. */+.capture-mark {+ flex: none;+ padding: 0 5px;+ color: var(--capture);+ border: 1px solid var(--capture);+ border-radius: 999px;+ font-size: 10px;+ font-weight: 600;+ line-height: 16px;+ cursor: pointer;+}++.capture-mark:hover {+ color: var(--bg);+ background: var(--capture);+}++.capture-state {+ display: inline-block;+ padding: 0 5px;+ color: var(--muted);+ border: 1px solid var(--line);+ border-radius: 6px;+ font-size: 10px;+ letter-spacing: 0.04em;+ text-transform: uppercase;+}++.capture-state.is-open {+ color: var(--capture);+ border-color: var(--capture);+}++.capture-here-list li {+ margin: 3px 0;+}+.capture-meta {display: flex;flex-wrap: wrap;diff --git a/packages/template/test/captures-view.test.tsx b/packages/template/test/captures-view.test.tsxindex bed04be..f01800f 100644--- a/packages/template/test/captures-view.test.tsx+++ b/packages/template/test/captures-view.test.tsx@@ -2,7 +2,13 @@ import { createElement } from "react";import { renderToStaticMarkup } from "react-dom/server";import { describe, expect, it } from "vitest";import type { ViewCapture, ViewSession } from "../../cli/src/view/model.js";-import { CapturesView, capturesButtonVisible } from "../src/CapturesView.js";+import {+ CapturesView,+ captureCounts,+ capturePlacements,+ captureSource,+ capturesButtonVisible,+} from "../src/CapturesView.js";const T0 = "2026-10-26T10:00:00.000Z";@@ -10,7 +16,10 @@ const sessions = [{sessionId: "s1",title: "Parser work",- messages: [{ id: "m3", label: "m3", title: "Build it" }],+ messages: [+ { id: "m3", label: "m3", title: "Build it" },+ { id: "h4", label: "m4", title: "Then this" },+ ],},] as unknown as ViewSession[];@@ -18,7 +27,7 @@ const item = (over: Partial<ViewCapture> & { id: string; state: ViewCapture["state"] },): ViewCapture => ({text: "some work",- source: { sessionId: "s1", messageId: "m3" },+ source: { sessionId: "s1" },createdAt: T0,updatedAt: T0,...over,@@ -31,11 +40,11 @@ const items: ViewCapture[] = [item({ id: "c00000004", state: "dismissed", text: "gone" }),];-function render(captures: ViewCapture[] | undefined): string {+function render(captures: ViewCapture[] | undefined, sessionsFor = sessions): string {return renderToStaticMarkup(createElement(CapturesView, {captures,- sessions,+ sessions: sessionsFor,dir: "/p",active: null,onSelect: () => {},@@ -67,6 +76,14 @@ describe("CapturesView", () => {expect(render(undefined)).toContain("No captured work.");expect(render([item({ id: "c00000009", state: "dismissed" })])).toContain("No captured work.");});++ it("shows a session with no messages as a source with nothing to open", () => {+ const html = render([item({ id: "c00000001", state: "suggested" })], [+ { sessionId: "s1", title: "Empty", messages: [] },+ ] as unknown as ViewSession[]);+ expect(html).toContain("Empty");+ expect(html).toContain("disabled");+ });});describe("the Captured button", () => {@@ -79,3 +96,96 @@ describe("the Captured button", () => {expect(capturesButtonVisible(undefined, true)).toBe(false);});});++describe("an item's session anchor (Story 15.2)", () => {+ const session = (id: string, messages: { id: string; label?: string }[]): ViewSession =>+ ({+ sessionId: id,+ title: "",+ messages,+ }) as unknown as ViewSession;++ it("anchors on the session's first message in send order", () => {+ expect(+ captureSource({ sessionId: "s1" }, [session("s1", [{ id: "a1" }, { id: "a2" }])]),+ ).toEqual({+ sessionTitle: "s1",+ label: "a1",+ target: { sessionId: "s1", messageId: "a1" },+ });+ });++ it("anchors a session on its own first message even when it continues another", () => {+ const continuing = {+ sessionId: "s2",+ title: "",+ messages: [+ { id: "b1", continues: { sessionId: "s1", id: "a1", sessionTitle: "One" } },+ { id: "b2" },+ ],+ } as unknown as ViewSession;+ expect(captureSource({ sessionId: "s2" }, [session("s1", [{ id: "a1" }]), continuing])).toEqual(+ {+ sessionTitle: "s2",+ label: "b1",+ target: { sessionId: "s2", messageId: "b1" },+ },+ );+ });++ it("anchors nowhere for a session with no messages or no record", () => {+ expect(captureSource({ sessionId: "s1" }, [session("s1", [])])).toEqual({+ sessionTitle: "s1",+ });+ expect(captureSource({ sessionId: "gone" }, [session("s1", [{ id: "a1" }])])).toEqual({+ sessionTitle: "gone",+ });+ });+});++describe("the map's capture mark count", () => {+ it("counts suggested and open items per session, and nothing when only done ones exist", () => {+ const counts = captureCounts([+ item({ id: "c00000001", state: "suggested" }),+ item({ id: "c00000002", state: "open" }),+ item({ id: "c00000003", state: "done" }),+ item({ id: "c00000004", state: "dismissed" }),+ item({ id: "c00000005", state: "open", source: { sessionId: "s2" } }),+ ]);+ expect(counts.get("s1")).toBe(2);+ expect(counts.get("s2")).toBe(1);+ expect(captureCounts([item({ id: "c00000009", state: "done" })]).size).toBe(0);+ expect(captureCounts(undefined).size).toBe(0);+ });++ it("puts the mark on the anchor message when its row is drawn, else on the session row", () => {+ const captures = [+ item({ id: "c00000001", state: "suggested" }),+ item({ id: "c00000002", state: "open" }),+ ];+ const open = capturePlacements(captures, sessions, () => true);+ expect([...open.messages]).toEqual([["m3", 2]]);+ expect(open.sessions.size).toBe(0);++ const folded = capturePlacements(captures, sessions, () => false);+ expect([...folded.sessions]).toEqual([["s1", { count: 2, messageId: "m3" }]]);+ expect(folded.messages.size).toBe(0);++ const none = capturePlacements(+ [item({ id: "c00000009", state: "done" })],+ sessions,+ () => true,+ );+ expect(none.messages.size).toBe(0);+ expect(none.sessions.size).toBe(0);++ // A session with no messages has no row to anchor on.+ const empty = capturePlacements(+ captures,+ [{ ...sessions[0], messages: [] } as ViewSession],+ () => true,+ );+ expect(empty.messages.size).toBe(0);+ expect(empty.sessions.size).toBe(0);+ });+});diff --git a/packages/template/test/map-changes.test.tsx b/packages/template/test/map-changes.test.tsxindex 0d81cda..b94f9a6 100644--- a/packages/template/test/map-changes.test.tsx+++ b/packages/template/test/map-changes.test.tsx@@ -63,7 +63,7 @@ function modelOf(current: ViewSession): LineageViewModel {};}-function renderGraph(bigChangeLines = 300): string {+function renderGraph(bigChangeLines = 300, captured?: ReadonlyMap<string, number>): string {return renderToStaticMarkup(createElement(GitGraph, {git: layoutGitGraph(session.messages),@@ -71,6 +71,7 @@ function renderGraph(bigChangeLines = 300): string {highlightIds: undefined,activeHitId: null,bigChangeLines,+ captured,onSelect: () => {},onUnfold: () => {},onContinue: () => {},@@ -95,6 +96,13 @@ describe("how much code landed on the map (10.3)", () => {expect(renderGraph(10_000)).not.toContain("is-big-change");});+ it("puts the captured-work mark on the anchored message row only", () => {+ const html = renderGraph(300, new Map([["h1", 2]]));+ expect(html.match(/class="capture-mark git-capture"/g)).toHaveLength(1);+ expect(html).toContain('title="2 captured items from this session"');+ expect(renderGraph()).not.toContain("capture-mark");+ });+it("shows the numbers and the big mark in the drill-down", () => {const html = renderToStaticMarkup(createElement(DrillDown, {diff --git a/packages/template/test/session-git.test.ts b/packages/template/test/session-git.test.tsindex 0029489..cfec469 100644--- a/packages/template/test/session-git.test.ts+++ b/packages/template/test/session-git.test.ts@@ -42,6 +42,7 @@ describe("Story 9.3 on the map", () => {openIds: new Set<string>(),highlightSessionIds: new Set<string>(),onOpen: () => {},+ onOpenMessage: () => {},onContinue: () => {},}),);@@ -102,3 +103,95 @@ describe("Story 9.3 on the map", () => {expect(gone.match(/class="resume-button" disabled/g)).toHaveLength(2);});});++describe("captured work on the map (Story 15.2)", () => {+ it("marks the session row with its count while the first message is not drawn", () => {+ const model = modelOf(session);+ const render = (captured: Map<string, { count: number; messageId: string }> | undefined) =>+ renderToStaticMarkup(+ createElement(SessionMap, {+ model,+ graph: layoutSessionGraph(model),+ selectedSessionId: null,+ openIds: new Set<string>(),+ highlightSessionIds: new Set<string>(),+ captured,+ onOpen: () => {},+ onOpenMessage: () => {},+ onContinue: () => {},+ }),+ );+ const html = render(new Map([["s1", { count: 2, messageId: "h1" }]]));+ expect(html).toContain("session-capture");+ expect(html).toContain(">2<");+ expect(render(undefined)).not.toContain("session-capture");+ });++ it("lists the session's items in the first message's details, read-only", () => {+ const model: LineageViewModel = {+ ...modelOf(session),+ captures: [+ {+ id: "c00000001",+ text: "write the docs",+ state: "suggested",+ source: { sessionId: "s1" },+ createdAt: T0,+ updatedAt: T0,+ },+ {+ id: "c00000002",+ text: "ship it",+ state: "open",+ source: { sessionId: "s1" },+ createdAt: T0,+ updatedAt: T0,+ },+ ],+ };+ const html = renderToStaticMarkup(+ createElement(DrillDown, {+ model,+ selection: { type: "node", sessionId: "s1", nodeId: "h1" },+ onClose: () => {},+ }),+ );+ expect(html).toContain("Captured here");+ expect(html).toContain("write the docs");+ expect(html).toContain("To review");+ expect(html).toContain("Open");+ // Actions stay in the Captured list.+ expect(html).not.toContain(">Accept<");+ });++ it("shows the section only on the anchor, not on another message", () => {+ const two = {+ ...session,+ messages: [+ ...session.messages,+ { id: "h2", label: "m2", kind: "message", title: "Later", at: T0, parent: "h1" },+ ],+ } as ViewSession;+ const model: LineageViewModel = {+ ...modelOf(two),+ captures: [+ {+ id: "c00000001",+ text: "write the docs",+ state: "suggested",+ source: { sessionId: "s1" },+ createdAt: T0,+ updatedAt: T0,+ },+ ],+ };+ const html = renderToStaticMarkup(+ createElement(DrillDown, {+ model,+ selection: { type: "node", sessionId: "s1", nodeId: "h2" },+ onClose: () => {},+ }),+ );+ expect(html).not.toContain("Captured here");+ });+});