Skip to content

armgit / cogit

Public Imported from GitHub
0

Git for the intent behind agent-written code. Records what your coding agent decided and why, and links every commit to it.

feat(captures): distil leftover work into a curated list

Eren98592a4194d0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 525bfc9..3a1947a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
## [Unreleased]
+### Added
+- Captured work is a curated list now: when a session ends, the side model drafts at most three user-level items from what the record left undone, and you accept, dismiss or close each one on the map or with `cogit captures accept|dismiss|done <id>`. `cogit captures distill [--session <id> | --all] [--dry-run]` backfills older sessions; the list lives in `.cogit/state/captures.json`, local and never committed.
+- 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
+- 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-31
### Added
diff --git a/README.md b/README.md
index 53925bf..605ab0c 100644
--- a/README.md
+++ b/README.md
@@ -25,8 +25,8 @@ Claude Code today.
- **Intent, Shape, Code**: a message that landed commits shows why it happened, a small
picture of what the change does (a diagram, a before/after or interface table, an example
or plain steps), and the diff, in one place.
-- **Captured work**: what the sessions left open — pending items and open branch lines —
- gathered from the record into one read-only list (`cogit captures`, and on the map).
+- **Captured work**: when a session ends, a small model drafts a few user-level items from
+ what it left undone; you accept, dismiss or close them (`cogit captures`, and on the map).
- **Pull request descriptions with the decisions**: `cogit pr` writes the goal, the
decisions and the rejected options, never the raw chat.
- **Teams share the record through git**: after a pull, your teammates' sessions are on the
diff --git a/docs/guide/map.md b/docs/guide/map.md
index 16309bf..7050627 100644
--- a/docs/guide/map.md
+++ b/docs/guide/map.md
@@ -130,19 +130,26 @@ the map. In the terminal: `cogit log --file <path>` and `cogit why <path>`.
## Captured work
Working with an agent is improvised: things that would have been a plan's items get done,
-half-done or dropped along the way. The **Captured** button lists what the sessions left open,
-gathered from the record: each session's pending items and each branch summary's open line,
-with the session, the message that named it, who recorded it and when. Items waiting for you
-come first and are marked "your call"; clicking a row opens its message on the map. In the
-terminal: `cogit captures` (`--session <id>`, `--json`).
-
-It is not a task board. The list is derived from the record on every build and cannot be
-edited: no checkboxes, no status, no assignee. cogit keeps no planning state; what becomes a
-real piece of work, and who owns it, is decided in your team's own tracker. The same text in two
-sessions stays two rows, because where it came from is the point.
-
-Known limit: when the agent removes a pending item from its record, it leaves the list too; the
-record keeps no history of pending items.
+half-done or dropped along the way. The **Captured** list is a short, curated one. When a
+session ends, the side model reads what its record left open — pending items, open branch
+lines, the last messages — and drafts at most three **user-level** items: something you asked
+for or the session left undone, as a short imperative in the conversation's language. It never
+drafts a commit step, a test run, a release chore or a status fact, and a session with nothing
+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).
+
+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** button
+appears only while the setting is on and something waits or is open; with the setting off
+(`cogit config set captures false`) nothing is drafted, the button hides, and items already in
+the store are kept, not deleted.
## Search
diff --git a/docs/guide/reading-the-lineage.md b/docs/guide/reading-the-lineage.md
index 0285f2b..69423e1 100644
--- a/docs/guide/reading-the-lineage.md
+++ b/docs/guide/reading-the-lineage.md
@@ -14,11 +14,15 @@ cogit why src/auth.ts # what earlier messages decided about this file, a
cogit why src/auth.ts:42 # only the thought behind line 42
cogit why src/auth.ts --line 42 # the same lookup
cogit search "refresh token" # titles, decisions, summaries and the stored conversation
-cogit captures # what the sessions left open (pending items, open branch lines)
+cogit captures # the curated list: to review, open and done
+cogit captures accept <id> # accept a suggestion (also: dismiss, done)
+cogit captures distill # draft items from a session's leftover work by hand
```
-`log` and `search` take `-n <count>` and `--session <id>`; `captures` takes `--session <id>`
-too; `log`, `show`, `search` and `captures` take `--json`; `show --no-chat` leaves out the conversation turn.
+`log` and `search` take `-n <count>` and `--session <id>`; `log`, `show`, `search` and
+`captures` take `--json` (the store's `{ schema, items }`); `show --no-chat` leaves out the
+conversation turn. `captures distill` takes `--session <id>`, `--all` or `--dry-run`; with no
+flag it distils the newest session. Ids are the `c…` shown at the start of each line.
## Addressing a message
diff --git a/docs/guide/settings.md b/docs/guide/settings.md
index 64bf578..e64fd16 100644
--- a/docs/guide/settings.md
+++ b/docs/guide/settings.md
@@ -56,6 +56,14 @@ Before the agent edits a file, it hears which options earlier thoughts tried and
For every message that landed commits, a small representation of what the change does: numbered plain-language steps or a Mermaid diagram. It sits between the record's intent (the decision, reason and rejected options) and the code (the diff), so a reviewer sees why, what and how in one place. The recorder writes it, not you; it costs one small model call per such message. Off, the map says so and nothing is written.
+### Captured work
+
+`captures` · default `true`
+
+**A short list of what each session left undone, drafted by the side model.**
+
+When a session ends, the side model reads what its record left open and drafts at most three things a person would ask for, in the conversation's language. The list is yours: accept, dismiss or close each item. Sessions with nothing open cost no model call; the map's Captured button appears only while something waits or is open. Off, nothing is drafted and the list already in the store is kept, not deleted.
+
### Language
`language` · default `auto`
diff --git a/docs/schema/config.json b/docs/schema/config.json
index 15953d3..6d2a5d3 100644
--- a/docs/schema/config.json
+++ b/docs/schema/config.json
@@ -56,6 +56,10 @@
"default": true,
"type": "boolean"
},
+ "captures": {
+ "default": true,
+ "type": "boolean"
+ },
"startupContext": {
"default": true,
"type": "boolean"
@@ -142,6 +146,7 @@
"sideEveryTurns",
"messageSummaries",
"shapes",
+ "captures",
"startupContext",
"recordHeadless",
"serverPort",
diff --git a/packages/cli/src/captures.ts b/packages/cli/src/captures.ts
new file mode 100644
index 0000000..100c27b
--- /dev/null
+++ b/packages/cli/src/captures.ts
@@ -0,0 +1,269 @@
+import { agentRecord, resultText, runClaude } from "./commands/backfill.js";
+import { buildProject } from "./commands/build.js";
+import type { Io } from "./io.js";
+import type { Session } from "./schema/session.js";
+import { addCaptureSuggestions, type CaptureItem, readCaptures } from "./store/captures.js";
+import { LockBusyError, withLock } from "./store/lock.js";
+import { projectPaths } from "./store/paths.js";
+import { loadConfig } from "./store/stores.js";
+import { type CaptureInput, captureInput, hasOpenWork } from "./view/captures.js";
+import { buildMessages } from "./view/lineage.js";
+
+/**
+ * The captured-work distiller (Story 15.1): one headless side-model call over a
+ * session's leftover work, turning the record's raw pending lines and open
+ * branch lines into at most three user-level items the user then accepts,
+ * dismisses or closes. The model's result enters the store as `suggested`; the
+ * model never closes, reopens or rewrites an item the user already saw.
+ *
+ * The pass runs at session end from the close pass, behind a per-session lock,
+ * and can be run by hand (`cogit captures distill`) for existing sessions.
+ */
+
+/** One item the model proposes, with the recorded message it came from. */
+export interface CaptureDraftItem {
+ text: string;
+ messageId: string;
+}
+
+export interface DistillAnswer {
+ items: CaptureDraftItem[];
+ duplicateOf: string[];
+}
+
+/** At most this many items per session: the list is meant to stay short. */
+export const DISTILL_LIMIT = 3;
+
+function clip(text: string, limit: number): string {
+ const flat = text.replace(/\s+/g, " ").trim();
+ return flat.length > limit ? `${flat.slice(0, limit)}…` : flat;
+}
+
+/** An existing item the model may name as the session's continuing subject. */
+export interface ExistingCapture {
+ id: string;
+ text: string;
+}
+
+/**
+ * The prompt of the captured-work pass: the session's leftover lines and last
+ * message titles, plus the project's current open and suggested items so
+ * nothing is drafted twice.
+ */
+export function distillPrompt(
+ input: CaptureInput,
+ existing: readonly ExistingCapture[],
+ language: string,
+): string {
+ const writing = language === "auto" ? "the conversation's language" : language;
+ const pending = input.pending.map(
+ (item) => `- ${item.needsUser ? "(needs the user) " : ""}${clip(item.text, 300)}`,
+ );
+ const branches = input.branches.map(
+ (item) => `- ${item.label ?? item.messageId ?? "?"}: ${clip(item.text, 300)}`,
+ );
+ const messages = input.lastMessages.map(
+ (message) => `- ${message.label ?? message.id}: ${clip(message.title, 200)}`,
+ );
+ const current =
+ existing.length === 0
+ ? []
+ : [
+ "The project's current captured items (open or suggested):",
+ ...existing.map((item) => `- ${item.id}: ${clip(item.text, 300)}`),
+ 'If this session is still about one of them, name its id in "duplicateOf" and do not draft it again.',
+ "",
+ ];
+ return [
+ "You distil the work a coding session left undone into a few items its user would recognize.",
+ "The session below lists what its record says is still open: pending items, the open line of each branch summary, and the titles of its last messages.",
+ "",
+ "Rules:",
+ `- 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, …).",
+ "- Existing captured items are the user's list: never rephrase, merge or close them. Only put an id in `duplicateOf`.",
+ "",
+ ...current,
+ `Session ${input.sessionId} "${clip(input.title, 200)}"`,
+ ...(pending.length === 0 ? [] : ["Pending items:", ...pending]),
+ ...(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": []}`,
+ ].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.
+ */
+export function parseDistillAnswer(text: string): DistillAnswer {
+ const answer = agentRecord(text);
+ const rawItems = Array.isArray(answer.items) ? answer.items : [];
+ 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 flat = itemText.replace(/\s+/g, " ").trim();
+ if (flat === "") continue;
+ items.push({ text: flat, messageId: messageId.trim() });
+ if (items.length >= DISTILL_LIMIT) break;
+ }
+ const rawDuplicates = Array.isArray(answer.duplicateOf) ? answer.duplicateOf : [];
+ const duplicateOf = rawDuplicates.filter(
+ (id): id is string => typeof id === "string" && id.trim() !== "",
+ );
+ 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;
+ sessionTitle: string;
+ items: CaptureDraftItem[];
+ duplicateOf: string[];
+ /** Empty in a dry run. */
+ added: CaptureItem[];
+}
+
+export interface DistillResult {
+ proposal: CaptureProposal;
+ /** False when nothing was written (a dry run, or everything was a duplicate). */
+ written: boolean;
+}
+
+export interface DistillOptions {
+ io: Io;
+ /** Print the proposals and write nothing. */
+ dryRun?: boolean | undefined;
+ /** Stamp for the store; tests pin it. */
+ now?: string | undefined;
+}
+
+/** The input a recorded session gives the pass. */
+export function sessionInput(record: Session): CaptureInput {
+ return captureInput({
+ sessionId: record.sessionId,
+ title: record.title,
+ updatedAt: record.updatedAt,
+ status: record.status,
+ messages: buildMessages(record.nodes),
+ });
+}
+
+/**
+ * Runs the pass over one session and writes the result as `suggested` items.
+ * The session must actually have something open, and the setting must be on;
+ * otherwise no model call happens and the result is undefined.
+ */
+export async function distillSessionInput(
+ root: string,
+ input: CaptureInput,
+ opts: DistillOptions,
+): Promise<DistillResult | undefined> {
+ const config = await loadConfig(opts.io.env);
+ if (!config.captures || !hasOpenWork(input)) return undefined;
+ const store = await readCaptures(root, opts.io.warn);
+ const existing = store.items
+ .filter((item) => item.state === "open" || item.state === "suggested")
+ .map((item): ExistingCapture => ({ id: item.id, text: item.text }));
+ const prompt = distillPrompt(input, existing, config.language);
+ 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 known = new Set(existing.map((item) => item.id));
+ const duplicateOf = answer.duplicateOf.filter((id) => known.has(id));
+ const now = opts.now ?? opts.io.now();
+ const added =
+ opts.dryRun === true
+ ? []
+ : await addCaptureSuggestions(root, input.sessionId, items, { now, duplicateOf });
+ return {
+ proposal: {
+ sessionId: input.sessionId,
+ sessionTitle: input.title,
+ items,
+ duplicateOf,
+ added,
+ },
+ written: opts.dryRun !== true && (added.length > 0 || duplicateOf.length > 0),
+ };
+}
+
+/**
+ * The session-end pass: one call over the just-closed record, behind the
+ * session's own lock so two closures never distil the same session twice. A
+ * busy lock and a broken model answer are skipped, never fatal: the close pass
+ * has already written the record. With `captures` off, or in agent-only mode
+ * where there is no side pass, nothing happens.
+ */
+export async function distillAtClose(
+ root: string,
+ record: Session,
+ io: Io,
+): Promise<DistillResult | undefined> {
+ const config = await loadConfig(io.env);
+ if (!config.captures || config.recorder === "agent") return undefined;
+ const input = sessionInput(record);
+ if (!hasOpenWork(input)) return undefined;
+ let result: DistillResult | undefined;
+ try {
+ result = await withLock(
+ projectPaths(root).lock(`captures-${record.sessionId}`),
+ () => distillSessionInput(root, input, { io }),
+ { timeoutMs: 0 },
+ );
+ } catch (err) {
+ if (err instanceof LockBusyError) return undefined;
+ io.warn(`could not distil captured work: ${(err as Error).message}`);
+ return undefined;
+ }
+ if ((result?.proposal.added.length ?? 0) > 0) {
+ // The map is a snapshot of the store: write a fresh one so the Captured
+ // button appears without waiting for the next session.
+ try {
+ await buildProject({ dir: root, io, quiet: true });
+ } catch {
+ // The next build picks the list up; a failed rebuild is not this pass's error.
+ }
+ }
+ return result;
+}
+
+/** A dry run's proposals as plain lines. */
+export function formatProposal(proposal: CaptureProposal): string[] {
+ const head = `Session ${proposal.sessionId} "${proposal.sessionTitle}":`;
+ if (proposal.items.length === 0) return [`${head} nothing to draft`];
+ return [
+ head,
+ ...proposal.items.map((item) => ` + ${item.text} (${item.messageId})`),
+ ...(proposal.duplicateOf.length === 0
+ ? []
+ : [` still about: ${proposal.duplicateOf.join(", ")}`]),
+ ];
+}
diff --git a/packages/cli/src/commands/build.ts b/packages/cli/src/commands/build.ts
index 6f73be3..c80c7ca 100644
--- a/packages/cli/src/commands/build.ts
+++ b/packages/cli/src/commands/build.ts
@@ -22,6 +22,7 @@ import {
import { redactDeep } from "../redact.js";
import { Slug } from "../schema/common.js";
import { SESSION_SCHEMA, type Session } from "../schema/session.js";
+import { readCaptures } from "../store/captures.js";
import { readProjectChanges } from "../store/changes.js";
import {
appendConversationHashes,
@@ -36,7 +37,6 @@ import { projectPaths } from "../store/paths.js";
import { resolveProjectRoot } from "../store/root.js";
import { loadAllSessions, loadConfig, loadProject } from "../store/stores.js";
import { attachThoughtTrailers, earliestSessionStart, readThoughtTrailers } from "../thought.js";
-import { buildCaptures } from "../view/captures.js";
import { attachChanges } from "../view/change.js";
import { buildFileHistory, modelSessions } from "../view/files.js";
import { buildViewModel, embedViewModel, markBuiltBy } from "../view/lineage.js";
@@ -378,8 +378,9 @@ export async function buildProject(opts: BuildOptions): Promise<LineageViewModel
// 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);
- // Story 14.1: what the sessions left open, read from the same records.
- built.captures = buildCaptures(built.sessions);
+ // Story 15.1: the curated captured-work list, from the local store the
+ // distiller and the CLI write. A corrupt or missing file is an empty list.
+ built.captures = (await readCaptures(root, io.warn)).items;
// The skill already avoids secrets; this is the safety net before rendering.
const redacted = redactDeep(built);
if (redacted.count > 0)
diff --git a/packages/cli/src/commands/captures.ts b/packages/cli/src/commands/captures.ts
index dae9a04..cf2e2c7 100644
--- a/packages/cli/src/commands/captures.ts
+++ b/packages/cli/src/commands/captures.ts
@@ -1,20 +1,36 @@
-import type { Io } from "../io.js";
-import { buildCaptures } from "../view/captures.js";
+import { distillSessionInput, formatProposal } from "../captures.js";
+import { CliError, type Io } from "../io.js";
+import {
+ type CaptureItem,
+ type CaptureState,
+ type Captures,
+ CaptureTransitionError,
+ readCaptures,
+ setCaptureState,
+ UnknownCaptureError,
+} from "../store/captures.js";
+import { loadAllSessions, loadConfig } from "../store/stores.js";
+import { captureInput, hasOpenWork } from "../view/captures.js";
import { timeSince } from "../view/inbox.js";
-import type { ViewCapture } from "../view/model.js";
-import { loadEffectiveSessions, openProject, selectSessions } from "./log.js";
+import { buildMessages } from "../view/lineage.js";
+import {
+ type EffectiveSession,
+ loadEffectiveSessions,
+ openProject,
+ selectSessions,
+} from "./log.js";
/**
- * `cogit captures [dir]` (Story 14.1): what the sessions left open, gathered
- * from the records — the same rows the map's Captured list shows. Read-only:
- * cogit keeps no planning state, so there is nothing to tick off here.
+ * `cogit captures` (Story 15.1): the curated list the side model drafts and the
+ * user curates. The map shows the same store, so the two never disagree.
+ * Accepting, dismissing or closing an item is the user's act; distilling by
+ * hand (`cogit captures distill`) backfills sessions that ended before the
+ * setting was on or ran without a side pass.
*/
export interface CapturesOptions {
dir: string;
io: Io;
- /** Only this session (id or unambiguous prefix). */
- session?: string | undefined;
json?: boolean | undefined;
/** The reference time for "how old"; tests pin it. */
now?: string | undefined;
@@ -24,41 +40,181 @@ function oneLine(text: string): string {
return text.replace(/\s+/g, " ").trim();
}
-/** One line per row: the text, then where it came from, who and how old. */
-export function formatCaptures(rows: readonly ViewCapture[], now: string): string[] {
- if (rows.length === 0) return ["No captured work in this project."];
- return rows.map((row) => {
- const marker = row.needsUser ? "! " : " ";
- const source = row.label === undefined ? row.sessionId : `${row.sessionId} ${row.label}`;
- const age = timeSince(row.updatedAt, now);
- const meta = [source, row.author, age === "" ? undefined : `${age} ago`]
- .filter((part) => part !== undefined)
- .join(" · ");
- return `${marker}${oneLine(row.text)} (${meta})`;
+/** `sessionId:messageId` → the message's `mN` label, from the records. */
+async function messageLabels(
+ root: string,
+ warn: (message: string) => void,
+): Promise<Map<string, string>> {
+ const labels = 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);
+ }
+ }
+ return labels;
+}
+
+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(" ");
+ const age = timeSince(item.updatedAt, now);
+ const meta = age === "" ? source : `${source} · ${age} ago`;
+ return `${item.id} ${oneLine(item.text)} (${meta})`;
+}
+
+/**
+ * The list in three sections: suggestions waiting for the user, accepted items,
+ * and the last ten that were done. Dismissed items are closed and stay out of
+ * the reading view.
+ */
+export function formatCaptures(
+ store: Captures,
+ labels: 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)}`)];
+ const lines = [
+ ...section("To review", of("suggested")),
+ ...section("Open", of("open")),
+ ...section("Done", of("done").slice(0, 10)),
+ ];
+ return lines.length === 0 ? ["No captured work."] : lines;
+}
+
+/** `cogit captures`; returns the store for tests and JSON callers. */
+export async function captures(opts: CapturesOptions): Promise<Captures> {
+ const root = await openProject(opts.dir);
+ const store = await readCaptures(root, opts.io.warn);
+ if (opts.json === true) {
+ 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);
+ return store;
+}
+
+/** The state each verb moves an item to. */
+export const CAPTURE_VERBS = {
+ accept: "open",
+ dismiss: "dismissed",
+ done: "done",
+} as const;
+
+export type CaptureVerb = keyof typeof CAPTURE_VERBS;
+
+/** What the confirmation says: "accepted", "dismissed", "closed". */
+const CAPTURE_DONE: Readonly<Record<CaptureVerb, string>> = {
+ accept: "accepted",
+ dismiss: "dismissed",
+ done: "closed",
+};
+
+/** `cogit captures accept|dismiss|done <id>`: the user's own change to the list. */
+export async function setCapture(
+ dir: string,
+ verb: CaptureVerb,
+ id: string,
+ io: Io,
+): Promise<CaptureItem> {
+ const root = await openProject(dir);
+ try {
+ const item = await setCaptureState(root, id, CAPTURE_VERBS[verb], io.now());
+ io.out(`${CAPTURE_DONE[verb]} ${item.id}: ${oneLine(item.text)}`);
+ return item;
+ } catch (err) {
+ if (err instanceof UnknownCaptureError) throw new CliError(`no captured item ${id}`);
+ if (err instanceof CaptureTransitionError)
+ throw new CliError(`a ${err.from} item cannot become ${err.to}`);
+ throw err;
+ }
+}
+
+export interface DistillOptions {
+ dir: string;
+ io: Io;
+ /** Only this session (id or unambiguous prefix). */
+ session?: string | undefined;
+ /** Every session with something left open; the default is the newest one. */
+ all?: boolean | undefined;
+ /** Print the proposals and write nothing. */
+ dryRun?: boolean | undefined;
+ now?: string | undefined;
+}
+
+/** The pass over one effective session, reusing the records already read. */
+async function distillOne(
+ root: string,
+ entry: EffectiveSession,
+ opts: DistillOptions,
+): Promise<void> {
+ const input = captureInput({
+ sessionId: entry.session.sessionId,
+ title: entry.session.title,
+ updatedAt: entry.session.updatedAt,
+ status: entry.session.status,
+ messages: entry.messages,
+ });
+ if (!hasOpenWork(input)) {
+ opts.io.out(`session ${entry.session.sessionId} has nothing left open to distil`);
+ return;
+ }
+ const result = await distillSessionInput(root, input, {
+ io: opts.io,
+ ...(opts.dryRun === undefined ? {} : { dryRun: opts.dryRun }),
+ ...(opts.now === undefined ? {} : { now: opts.now }),
});
+ if (result === undefined) return;
+ if (opts.dryRun === true) {
+ for (const line of formatProposal(result.proposal)) opts.io.out(line);
+ return;
+ }
+ const added = result.proposal.added;
+ if (added.length === 0) {
+ opts.io.out(`nothing new for session ${entry.session.sessionId}`);
+ return;
+ }
+ opts.io.out(
+ `drafted ${added.length} item${added.length === 1 ? "" : "s"} from session ${entry.session.sessionId}`,
+ );
+ for (const item of added) opts.io.out(` ${item.id} ${item.text}`);
}
-/** `cogit captures`; returns the rows for tests and JSON callers. */
-export async function captures(opts: CapturesOptions): Promise<ViewCapture[]> {
+/**
+ * `cogit captures distill`: runs the same pass by hand. One selected session,
+ * every session with something open, or the newest session by default. With
+ * `--dry-run` nothing is written.
+ */
+export async function distill(opts: DistillOptions): Promise<void> {
const root = await openProject(opts.dir);
+ const config = await loadConfig(opts.io.env);
+ if (!config.captures) {
+ throw new CliError("captured work is off; turn it on with `cogit config set captures true`");
+ }
const sessions = await loadEffectiveSessions(root, opts.io);
- const selected = opts.session === undefined ? sessions : selectSessions(sessions, opts.session);
- const rows = buildCaptures(
- selected.map(({ session, messages }) => ({
- sessionId: session.sessionId,
- title: session.title,
- author: session.author,
- authorEmail: session.authorEmail,
- updatedAt: session.updatedAt,
- status: session.status,
- messages,
- })),
- );
- if (opts.json === true) {
- opts.io.out(JSON.stringify(rows, null, 2));
- return rows;
+ if (opts.session !== undefined) {
+ const selected = selectSessions(sessions, opts.session);
+ for (const entry of selected) await distillOne(root, entry, opts);
+ return;
+ }
+ if (opts.all === true) {
+ for (const entry of sessions) await distillOne(root, entry, opts);
+ return;
+ }
+ const newest = [...sessions].sort((a, b) =>
+ b.session.updatedAt.localeCompare(a.session.updatedAt),
+ )[0];
+ if (newest === undefined) {
+ opts.io.out("this project has no recorded session to distil");
+ return;
}
- for (const line of formatCaptures(rows, opts.now ?? new Date().toISOString())) opts.io.out(line);
- if (rows.some((row) => row.needsUser)) opts.io.out("! = waiting for you");
- return rows;
+ await distillOne(root, newest, opts);
}
diff --git a/packages/cli/src/commands/close.ts b/packages/cli/src/commands/close.ts
index 2baf353..7cca15b 100644
--- a/packages/cli/src/commands/close.ts
+++ b/packages/cli/src/commands/close.ts
@@ -1,4 +1,5 @@
import { type ChatTurn, defaultAgent } from "../agents/index.js";
+import { distillAtClose } from "../captures.js";
import type { Io } from "../io.js";
import { hashTurns, upgradeSessionIds } from "../messages.js";
import { parseMessageRef } from "../schema/common.js";
@@ -295,4 +296,8 @@ export async function closeSession(root: string, sessionId: string, io: Io): Pro
const answer = agentRecord(resultText(await runClaude(prompt, config.sideModel, io.env)));
const payload = closePayload(answer, closing, record, { status });
await sessionWrite({ dir: root, by: "side" }, io, async () => JSON.stringify(payload));
+ // Story 15.1: one more side call distils what the session left open. It reads
+ // the record as just written, so it needs the close pass to have landed.
+ const closed = await loadSession(root, sessionId);
+ if (closed.found && closed.ok) await distillAtClose(root, closed.data, io);
}
diff --git a/packages/cli/src/program.ts b/packages/cli/src/program.ts
index e6e49e6..6ed9068 100644
--- a/packages/cli/src/program.ts
+++ b/packages/cli/src/program.ts
@@ -3,7 +3,7 @@ import pkg from "../package.json" with { type: "json" };
import { backfillTail } from "./commands/backfill.js";
import { blame } from "./commands/blame.js";
import { buildProject } from "./commands/build.js";
-import { captures } from "./commands/captures.js";
+import { captures, distill, setCapture } from "./commands/captures.js";
import {
configGet,
configGit,
@@ -198,26 +198,78 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =
),
);
- program
+ const capturesCommand = program
.command("captures")
- .description("list what the sessions left open, gathered from the record (not a plan)")
+ .description("the curated list of work the sessions left open (not a plan)")
.helpGroup("Read:")
.argument("[dir]", "project directory", ".")
.option("-C, --dir <dir>", "project directory (same as the positional)")
- .option("--session <id>", "only this session (id or prefix)")
- .option("--json", "print JSON instead of text")
- .addHelpText("after", examples("cogit captures", "cogit captures --session 9c32ab18"))
+ .option("--json", "print the store as JSON")
+ .addHelpText(
+ "after",
+ examples(
+ "cogit captures",
+ "cogit captures accept c1a2b3c4",
+ "cogit captures distill --dry-run",
+ "cogit captures distill --all",
+ ),
+ )
.action(
- run(async (dir: string, opts: { dir?: string; session?: string; json?: boolean }) => {
- await captures({
- dir: opts.dir ?? dir,
- io: makeIo(false),
- session: opts.session,
- json: opts.json === true,
- });
+ run(async (dir: string, opts: { dir?: string; json?: boolean }) => {
+ await captures({ dir: opts.dir ?? dir, io: makeIo(false), json: opts.json === true });
}),
);
+ for (const verb of ["accept", "dismiss", "done"] as const) {
+ capturesCommand
+ .command(verb)
+ .description(
+ verb === "accept"
+ ? "accept a suggested item and keep it open"
+ : verb === "dismiss"
+ ? "dismiss a suggested item; it leaves the list"
+ : "close an open item",
+ )
+ .argument("<id>", "the item's id (c…, as `cogit captures` prints it)")
+ .option("-C, --dir <dir>", "project directory")
+ .action(
+ run(async (id: string, opts: { dir?: string }, command: Command) => {
+ // Commander hands a `--dir` that the parent also defines to the
+ // parent's opts, so both are read.
+ await setCapture(
+ opts.dir ?? command.parent?.opts<{ dir?: string }>().dir ?? ".",
+ verb,
+ id,
+ makeIo(false),
+ );
+ }),
+ );
+ }
+
+ capturesCommand
+ .command("distill")
+ .description("draft items from a session's leftover work, by hand")
+ .option("-C, --dir <dir>", "project directory")
+ .option("--session <id>", "only this session (id or prefix)")
+ .option("--all", "every session with something left open")
+ .option("--dry-run", "print the proposals and write nothing")
+ .action(
+ run(
+ async (
+ opts: { dir?: string; session?: string; all?: boolean; dryRun?: boolean },
+ command: Command,
+ ) => {
+ await distill({
+ dir: opts.dir ?? command.parent?.opts<{ dir?: string }>().dir ?? ".",
+ io: makeIo(false),
+ session: opts.session,
+ all: opts.all === true,
+ dryRun: opts.dryRun === true,
+ });
+ },
+ ),
+ );
+
program
.command("search")
.description("find recorded messages, branch summaries and conversation text")
diff --git a/packages/cli/src/schema/config.ts b/packages/cli/src/schema/config.ts
index e241ffe..967931f 100644
--- a/packages/cli/src/schema/config.ts
+++ b/packages/cli/src/schema/config.ts
@@ -41,6 +41,12 @@ export const Config = z.object({
* records. Off writes nothing; the map then says so.
*/
shapes: z.boolean().default(true),
+ /**
+ * Whether the side model distils each session's leftover work into a short
+ * curated list (Story 15.1). Off writes nothing; items already in the store
+ * are kept and come back when it is turned on again.
+ */
+ captures: z.boolean().default(true),
/**
* Whether SessionStart hands the agent the lineage of the previous session and
* how to read the record (`log` / `show`). On by default; costs only tokens.
diff --git a/packages/cli/src/server.ts b/packages/cli/src/server.ts
index ca769bf..5e75f4b 100644
--- a/packages/cli/src/server.ts
+++ b/packages/cli/src/server.ts
@@ -19,6 +19,12 @@ import { diffTooLarge, isDiffSha, readCommitDiff } from "./diff.js";
import { defaultsPrompter, type Io } from "./io.js";
import { Config } from "./schema/config.js";
import { refreshShareConversations } from "./share.js";
+import {
+ CAPTURE_ID,
+ CaptureTransitionError,
+ setCaptureState,
+ UnknownCaptureError,
+} from "./store/captures.js";
import { dismissInboxSession } from "./store/inbox-state.js";
import { LockBusyError } from "./store/lock.js";
import { MAX_OPEN, readMapView, setOpenSessions, setRowWidth } from "./store/map-view.js";
@@ -748,6 +754,90 @@ export async function startMapServer(opts: MapServerOptions): Promise<MapServer>
res.end(JSON.stringify({ ok: true, sessionId, at }));
}
+ /**
+ * `POST /api/captures/state` { dir, id, state } (Story 15.1): the map's
+ * Accept, Dismiss and Done buttons. Only the user's own transitions are
+ * allowed (`suggested` → `open`|`dismissed`, `open` → `done`); an unknown id
+ * is a 404 and an impossible transition a 409. Same Host, Origin,
+ * content-type and token checks as an inbox dismissal, and `dir` must be a
+ * registered project. The open maps are rebuilt so the list follows.
+ */
+ async function writeCaptureState(
+ 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, state } = parsed as Record<string, unknown>;
+ if (typeof dir !== "string" || typeof id !== "string" || typeof state !== "string") {
+ respond(res, 400, "expected { dir, id, state }");
+ return;
+ }
+ if (!CAPTURE_ID.test(id)) {
+ respond(res, 400, "id is not a captured item id");
+ return;
+ }
+ if (state !== "open" && state !== "dismissed" && state !== "done") {
+ respond(res, 400, "state must be open, dismissed or done");
+ return;
+ }
+ const root = await registeredRoot(env, dir);
+ if (root === null) {
+ respond(res, 403, "not a registered project");
+ return;
+ }
+ try {
+ await setCaptureState(root, id, state, new Date().toISOString());
+ } catch (err) {
+ if (err instanceof UnknownCaptureError) {
+ respond(res, 404, err.message);
+ return;
+ }
+ if (err instanceof CaptureTransitionError) {
+ respond(res, 409, err.message);
+ return;
+ }
+ respond(res, 500, "could not write the captured list");
+ return;
+ }
+ res.writeHead(200, {
+ "content-type": "application/json",
+ "cache-control": "no-store",
+ });
+ res.end(JSON.stringify({ ok: true, id, state }));
+ void queueRebuild();
+ }
+
/**
* The checks every map-view write shares: Origin and token, a JSON object body
* within the size cap, and a registered `dir`. Answers the request itself and
@@ -894,6 +984,10 @@ export async function startMapServer(opts: MapServerOptions): Promise<MapServer>
await writeInboxDismiss(req, res, port);
return;
}
+ if (url.pathname === "/api/captures/state") {
+ await writeCaptureState(req, res, port);
+ return;
+ }
if (url.pathname === "/api/row-width") {
await writeRowWidth(req, res, port);
return;
diff --git a/packages/cli/src/store/captures.ts b/packages/cli/src/store/captures.ts
new file mode 100644
index 0000000..326480b
--- /dev/null
+++ b/packages/cli/src/store/captures.ts
@@ -0,0 +1,223 @@
+import { randomBytes } from "node:crypto";
+import { z } from "zod";
+import { IsoDate } from "../schema/common.js";
+import { atomicWriteJson, readJson } from "./fs.js";
+import { withLock } from "./lock.js";
+import { projectPaths } from "./paths.js";
+
+/**
+ * The curated captured-work list (Story 15.1). A side model distils a session's
+ * leftover work into a few user-level items; the user accepts, dismisses or
+ * closes them. The store is local to the machine (`.cogit/state/captures.json`,
+ * never committed) and is not a plan: cogit keeps no tracker state.
+ *
+ * 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.
+ */
+
+export const CAPTURES_SCHEMA = 1;
+
+const SESSION_ID = /^[A-Za-z0-9._:-]{1,128}$/;
+/** A random `c` followed by eight hex characters. */
+export const CAPTURE_ID = /^c[0-9a-f]{8}$/;
+/** One item is a line, not a paragraph. */
+export const CAPTURE_TEXT_MAX = 300;
+
+export const CaptureState = z.enum(["suggested", "open", "dismissed", "done"]);
+export type CaptureState = z.infer<typeof CaptureState>;
+
+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. */
+ source: z.object({
+ sessionId: z.string().regex(SESSION_ID),
+ messageId: z.string().min(1).max(128),
+ }),
+ createdAt: IsoDate,
+ updatedAt: IsoDate,
+ /** Set when the item became `done`; absent otherwise. */
+ closedAt: IsoDate.optional(),
+});
+export type CaptureItem = z.infer<typeof CaptureItem>;
+
+export const Captures = z.object({
+ schema: z.literal(CAPTURES_SCHEMA),
+ items: z.array(CaptureItem).default([]),
+});
+export type Captures = z.infer<typeof Captures>;
+
+/** A missing file is an empty list, not an error. */
+export function emptyCaptures(): Captures {
+ return { schema: CAPTURES_SCHEMA, items: [] };
+}
+
+/** An id no item in `taken` uses; the model never picks one. */
+export function newCaptureId(taken: ReadonlySet<string> = new Set()): string {
+ for (;;) {
+ const id = `c${randomBytes(4).toString("hex")}`;
+ if (!taken.has(id)) return id;
+ }
+}
+
+/**
+ * What the user may do with an item: a suggestion is accepted or dismissed, an
+ * open item is closed. A dismissed or done item stays as it is — the model never
+ * reopens what the user already saw.
+ */
+export const CAPTURE_TRANSITIONS: Readonly<Record<CaptureState, readonly CaptureState[]>> = {
+ suggested: ["open", "dismissed"],
+ open: ["done"],
+ dismissed: [],
+ done: [],
+};
+
+export function canTransition(from: CaptureState, to: CaptureState): boolean {
+ return CAPTURE_TRANSITIONS[from].includes(to);
+}
+
+export class UnknownCaptureError extends Error {
+ constructor(readonly id: string) {
+ super(`no captured item ${id}`);
+ }
+}
+
+export class CaptureTransitionError extends Error {
+ constructor(
+ readonly id: string,
+ readonly from: CaptureState,
+ readonly to: CaptureState,
+ ) {
+ super(`a ${from} item cannot become ${to}`);
+ }
+}
+
+function oneLine(text: string): string {
+ return text.replace(/\s+/g, " ").trim();
+}
+
+function sameText(a: string, b: string): boolean {
+ return oneLine(a).toLocaleLowerCase() === oneLine(b).toLocaleLowerCase();
+}
+
+/**
+ * The store as it is now. A missing file is empty; a corrupt one is replaced
+ * with an empty store after a warning — the list is local state and must never
+ * fail a build or a command.
+ */
+export async function readCaptures(
+ root: string,
+ warn?: (message: string) => void,
+): Promise<Captures> {
+ const file = projectPaths(root).captures;
+ 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;
+}
+
+/** A rephrase from the model for one recorded message. */
+export interface CaptureDraft {
+ text: string;
+ messageId: string;
+}
+
+export interface AddCapturesOptions {
+ /** The time to stamp on new and touched items. */
+ now: string;
+ /** Existing items the session is still about; only their `updatedAt` moves. */
+ duplicateOf?: readonly string[] | undefined;
+}
+
+/**
+ * Drafts suggestions from one session's leftover work. A text the store already
+ * holds as `suggested` or `open` is not added twice; `duplicateOf` items are
+ * left untouched except for `updatedAt`. Returns only the items it added.
+ */
+export async function addCaptureSuggestions(
+ root: string,
+ sessionId: string,
+ drafts: readonly CaptureDraft[],
+ opts: AddCapturesOptions,
+): Promise<CaptureItem[]> {
+ if (!SESSION_ID.test(sessionId)) throw new Error(`not a session id: ${sessionId}`);
+ const paths = projectPaths(root);
+ return withLock(
+ paths.lock("captures"),
+ async () => {
+ const store = await readCaptures(root);
+ const items = [...store.items];
+ const byId = new Map(items.map((item) => [item.id, item]));
+ const touched = new Set<string>();
+ for (const id of opts.duplicateOf ?? []) {
+ const item = byId.get(id);
+ if (item === undefined || (item.state !== "suggested" && item.state !== "open")) continue;
+ item.updatedAt = opts.now;
+ touched.add(id);
+ }
+ const known = items
+ .filter((item) => item.state === "suggested" || item.state === "open")
+ .map((item) => item.text);
+ const taken = new Set(items.map((item) => item.id));
+ const added: CaptureItem[] = [];
+ for (const draft of drafts) {
+ const text = oneLine(draft.text).slice(0, CAPTURE_TEXT_MAX);
+ if (text === "" || known.some((seen) => sameText(seen, text))) continue;
+ const id = newCaptureId(taken);
+ taken.add(id);
+ known.push(text);
+ const item: CaptureItem = {
+ id,
+ text,
+ state: "suggested",
+ source: { sessionId, messageId: draft.messageId },
+ createdAt: opts.now,
+ updatedAt: opts.now,
+ };
+ items.push(item);
+ added.push(item);
+ }
+ if (added.length === 0 && touched.size === 0) return [];
+ await atomicWriteJson(paths.captures, { schema: CAPTURES_SCHEMA, items });
+ return added;
+ },
+ { timeoutMs: 5000 },
+ );
+}
+
+/**
+ * Sets one item's state. Only the transitions in `CAPTURE_TRANSITIONS` are
+ * allowed; `done` records `closedAt`.
+ */
+export async function setCaptureState(
+ root: string,
+ id: string,
+ state: CaptureState,
+ now: string,
+): Promise<CaptureItem> {
+ const paths = projectPaths(root);
+ return withLock(
+ paths.lock("captures"),
+ async () => {
+ const store = await readCaptures(root);
+ const items = store.items.map((item) => ({ ...item }));
+ const item = items.find((candidate) => candidate.id === id);
+ if (item === undefined) throw new UnknownCaptureError(id);
+ if (!canTransition(item.state, state))
+ throw new CaptureTransitionError(id, item.state, state);
+ item.state = state;
+ item.updatedAt = now;
+ if (state === "done") item.closedAt = now;
+ await atomicWriteJson(paths.captures, { schema: CAPTURES_SCHEMA, items });
+ return item;
+ },
+ { timeoutMs: 5000 },
+ );
+}
diff --git a/packages/cli/src/store/paths.ts b/packages/cli/src/store/paths.ts
index 4292ced..4927cbe 100644
--- a/packages/cli/src/store/paths.ts
+++ b/packages/cli/src/store/paths.ts
@@ -36,6 +36,8 @@ export function projectPaths(root: string) {
inboxState: join(base, "state", "inbox.json"),
/** How the user left the map: open sessions and dragged row widths; also local. */
mapView: join(base, "state", "map.json"),
+ /** The curated captured-work list (Story 15.1); local, never committed. */
+ captures: join(base, "state", "captures.json"),
/** What the detached hook children (build, side run) printed; local, capped. */
detachedLog: join(base, "state", "detached.log"),
/** Commits waiting for their message's record before a Shape; local. */
diff --git a/packages/cli/src/view/captures.ts b/packages/cli/src/view/captures.ts
index 3393875..40505e2 100644
--- a/packages/cli/src/view/captures.ts
+++ b/packages/cli/src/view/captures.ts
@@ -1,91 +1,110 @@
-import type { ViewCapture, ViewNode, ViewPendingItem } from "./model.js";
-import { personLabel } from "./people.js";
+import type { ViewNode, ViewPendingItem } from "./model.js";
/**
- * Captured work (Story 14.1): what the sessions left open, gathered from the
- * record after the fact. One read-only derivation — no stored state, no model
- * call — that `cogit captures` and the map's Captured list both read, so the
- * two can never disagree. It is not a plan: nothing here can be ticked off,
- * assigned or edited. Kept free of Node imports because the template imports it.
+ * The input the captured-work distiller reads (Story 15.1). The record is the
+ * only source: a session's pending items and its branch summaries' open lines,
+ * next to the titles of its last messages so the model can tell what the session
+ * was really about. The map and the CLI show the curated store, never these rows.
+ *
+ * Kept free of Node imports, like the rest of `view/`.
*/
-/** The part of a session the derivation needs; a `ViewSession` fits as is. */
+/** The part of a session the distiller needs; an effective session fits as is. */
export interface CaptureSourceSession {
sessionId: string;
title: string;
- author?: string | undefined;
- authorEmail?: string | undefined;
updatedAt: string;
status: { pending: readonly ViewPendingItem[] };
- messages: readonly Pick<ViewNode, "id" | "label" | "branch" | "unsummarized">[];
+ messages: readonly Pick<ViewNode, "id" | "label" | "title" | "branch" | "unsummarized">[];
}
-/** Parsed time, with `-Infinity` for an absent or rejected value. */
-function timeOf(at: string): number {
- const time = Date.parse(at);
- return Number.isNaN(time) ? Number.NEGATIVE_INFINITY : time;
+/** One line the record left open, pointing at the message that named it. */
+export interface CaptureLine {
+ text: string;
+ messageId?: string | undefined;
+ label?: string | undefined;
}
-/**
- * `needsUser` first, then the newest session first. The sort is stable, so a
- * tie keeps the record's order: pending items, then branches in message order.
- */
-function byOrder(a: ViewCapture, b: ViewCapture): number {
- return Number(b.needsUser) - Number(a.needsUser) || timeOf(b.updatedAt) - timeOf(a.updatedAt);
+/** A pending item: the session as a whole left it open. */
+export interface CapturePendingLine extends CaptureLine {
+ needsUser: boolean;
}
-/** Every open line the records hold, one row per source, sorted for reading. */
-export function buildCaptures(sessions: readonly CaptureSourceSession[]): ViewCapture[] {
- const rows: ViewCapture[] = [];
- for (const session of sessions) {
- const sessionTitle = session.title.trim() === "" ? session.sessionId : session.title;
- const person = personLabel(session);
- const base = {
- sessionId: session.sessionId,
- sessionTitle,
- ...(person === undefined ? {} : { author: person }),
- updatedAt: session.updatedAt,
- };
+/** A message title, so the model knows what the session was about. */
+export interface CaptureMessageTitle {
+ id: string;
+ label?: string | undefined;
+ title: string;
+}
- // A pending item belongs to the session as a whole; it points at the
- // newest message the record holds, where the session left off.
- const recorded = session.messages.filter((message) => message.unsummarized !== true);
- const newest = recorded[recorded.length - 1];
- const seenPending = new Set<string>();
- session.status.pending.forEach((item, index) => {
- const text = item.text.trim();
- if (text === "" || seenPending.has(text)) return;
- seenPending.add(text);
- rows.push({
- key: `${session.sessionId}#p${index}`,
- text,
- source: "pending",
- ...base,
- ...(newest === undefined
- ? {}
- : {
- messageId: newest.id,
- ...(newest.label === undefined ? {} : { label: newest.label }),
- }),
- needsUser: item.needsUser,
- });
- });
+export interface CaptureInput {
+ sessionId: string;
+ title: string;
+ pending: CapturePendingLine[];
+ /** A branch summary's `open` line, on the branch's first message. */
+ branches: CaptureLine[];
+ /** The last recorded messages, oldest first. */
+ lastMessages: CaptureMessageTitle[];
+}
+
+/** How many recent messages the prompt carries: enough for the topic, not the chat. */
+export const LAST_MESSAGE_LIMIT = 5;
- // A branch summary's open line sits on the branch's first message.
- for (const message of session.messages) {
- const text = message.branch?.open.trim() ?? "";
- if (text === "") continue;
- rows.push({
- key: `${session.sessionId}#${message.id}`,
- text,
- source: "branch",
- ...base,
- messageId: message.id,
- ...(message.label === undefined ? {} : { label: message.label }),
- ...(message.branch === undefined ? {} : { branch: message.branch.title }),
- needsUser: false,
- });
- }
+function line(text: string, message: { id: string; label?: string | undefined }): CaptureLine {
+ return {
+ text: text.replace(/\s+/g, " ").trim(),
+ messageId: message.id,
+ ...(message.label === undefined ? {} : { label: message.label }),
+ };
+}
+
+/** What one session left open, in the record's own words. */
+export function captureInput(
+ session: CaptureSourceSession,
+ lastMessageLimit = LAST_MESSAGE_LIMIT,
+): CaptureInput {
+ const recorded = session.messages.filter((message) => message.unsummarized !== true);
+ // A pending item belongs to the session as a whole; it points at the newest
+ // recorded message, where the session left off.
+ const newest = recorded[recorded.length - 1];
+ const seen = new Set<string>();
+ const pending: CapturePendingLine[] = [];
+ for (const item of session.status.pending) {
+ const text = item.text.replace(/\s+/g, " ").trim();
+ if (text === "" || seen.has(text)) continue;
+ seen.add(text);
+ pending.push({
+ text,
+ needsUser: item.needsUser,
+ ...(newest === undefined ? {} : line(text, newest)),
+ });
+ }
+ const branches: CaptureLine[] = [];
+ for (const message of session.messages) {
+ const text = message.branch?.open.replace(/\s+/g, " ").trim() ?? "";
+ if (text === "") continue;
+ branches.push(line(text, message));
}
- return rows.sort(byOrder);
+ const lastMessages = recorded.slice(-Math.max(0, lastMessageLimit)).map(
+ (message): CaptureMessageTitle => ({
+ id: message.id,
+ ...(message.label === undefined ? {} : { label: message.label }),
+ title: message.title,
+ }),
+ );
+ return {
+ sessionId: session.sessionId,
+ title: session.title === "" ? session.sessionId : session.title,
+ pending,
+ branches,
+ lastMessages,
+ };
+}
+
+/**
+ * Whether the session is worth a model call at all: with no pending item (a
+ * `needsUser` item is one) and no open branch line, most sessions cost nothing.
+ */
+export function hasOpenWork(input: CaptureInput): boolean {
+ return input.pending.length > 0 || input.branches.length > 0;
}
diff --git a/packages/cli/src/view/model.ts b/packages/cli/src/view/model.ts
index b6322bf..d381b6e 100644
--- a/packages/cli/src/view/model.ts
+++ b/packages/cli/src/view/model.ts
@@ -39,6 +39,7 @@ export const PANEL_EDITABLE_KEYS = [
"recordHeadless",
"tryBeforeNotes",
"shapes",
+ "captures",
"language",
"shareConversations",
"recordCommit",
@@ -348,37 +349,31 @@ export interface LineageViewModel {
*/
inbox?: ViewInboxRow[];
/**
- * Captured work (Story 14.1): what the sessions left open, derived from the
- * records at build time. Absent on pages built before it.
+ * The curated captured-work list (Story 15.1), read from the local store at
+ * build time. Absent on pages built before it.
*/
captures?: ViewCapture[];
}
/**
- * One line of captured work (Story 14.1): something a session left open, read
- * from its record — a `status.pending` item or a branch summary's `open` line.
- * Derived on every build, never stored, never edited; it is not a plan.
+ * One item of the curated captured-work list (Story 15.1), read from
+ * `.cogit/state/captures.json` at build time. A side model drafts it from a
+ * session's leftover work; the user accepts, dismisses or closes it. The store
+ * is local and never committed, and it is not a plan: no assignment, no
+ * priority, no tracker state.
*/
export interface ViewCapture {
- /** `<sessionId>#p<n>` for a pending item, `<sessionId>#<messageId>` for a branch. */
- key: string;
+ /** `c` + eight hex characters, minted once; never derived from the text. */
+ id: string;
text: string;
- /** Where the record holds it: the session's pending list or a branch summary. */
- source: "pending" | "branch";
- sessionId: string;
- /** The session's title, or its id when the record has none yet. */
- sessionTitle: string;
- /** The message that named it: the newest one for pending, the branch's first for an open line. */
- messageId?: string;
- /** That message's `mN` label. */
- label?: string;
- /** The branch summary's title, for an open line. */
- branch?: string;
- /** Who recorded the session (name, else email); absent on older records. */
- author?: string;
- /** The session's last update: how old the line is. */
+ /** `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 };
+ createdAt: string;
updatedAt: string;
- needsUser: boolean;
+ /** Set when the item became `done`. */
+ closedAt?: string | undefined;
}
/**
@@ -454,6 +449,11 @@ export interface PanelSettings {
* plain-language or diagram view of what the change does.
*/
shapes: boolean;
+ /**
+ * Whether the side model distils each session's leftover work into a short
+ * curated list (Story 15.1).
+ */
+ captures: boolean;
shareConversations: boolean;
recordCommit: "ask" | "auto" | "off";
gitPolicy: "ignore" | "commit";
diff --git a/packages/cli/src/view/panel.ts b/packages/cli/src/view/panel.ts
index 59b331d..a56378d 100644
--- a/packages/cli/src/view/panel.ts
+++ b/packages/cli/src/view/panel.ts
@@ -66,6 +66,7 @@ export function panelSettings(config: Config): PanelSettings {
recordHeadless: config.recordHeadless,
tryBeforeNotes: config.tryBeforeNotes,
shapes: config.shapes,
+ captures: config.captures,
shareConversations: config.shareConversations,
recordCommit: config.recordCommit,
gitPolicy: config.gitPolicy,
diff --git a/packages/cli/src/view/settings.ts b/packages/cli/src/view/settings.ts
index 1efa067..1d5b796 100644
--- a/packages/cli/src/view/settings.ts
+++ b/packages/cli/src/view/settings.ts
@@ -118,6 +118,18 @@ const EDITABLE: FieldSpec[] = [
"model call per such message. Off, the map says so and nothing is written.",
kind: "boolean",
},
+ {
+ key: "captures",
+ label: "Captured work",
+ help: "A short list of what each session left undone, drafted by the side model.",
+ details:
+ "When a session ends, the side model reads what its record left open and drafts at " +
+ "most three things a person would ask for, in the conversation's language. The list " +
+ "is yours: accept, dismiss or close each item. Sessions with nothing open cost no " +
+ "model call; the map's Captured button appears only while something waits or is open. " +
+ "Off, nothing is drafted and the list already in the store is kept, not deleted.",
+ kind: "boolean",
+ },
{
key: "language",
label: "Language",
@@ -283,6 +295,7 @@ export const DEFAULT_SETTINGS: PanelSettings = {
recordHeadless: false,
tryBeforeNotes: true,
shapes: true,
+ captures: true,
shareConversations: false,
recordCommit: "ask",
gitPolicy: "commit",
@@ -303,6 +316,7 @@ export function editableSettings(settings: PanelSettings): PanelEditableSettings
recordHeadless: settings.recordHeadless,
tryBeforeNotes: settings.tryBeforeNotes,
shapes: settings.shapes,
+ captures: settings.captures,
language: settings.language,
shareConversations: settings.shareConversations,
recordCommit: settings.recordCommit,
diff --git a/packages/cli/test/captures.test.ts b/packages/cli/test/captures.test.ts
index d741673..c7c49fd 100644
--- a/packages/cli/test/captures.test.ts
+++ b/packages/cli/test/captures.test.ts
@@ -1,20 +1,40 @@
-import { mkdir, writeFile } from "node:fs/promises";
+import { chmod, mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { beforeEach, describe, expect, it } from "vitest";
+import {
+ distillAtClose,
+ distillPrompt,
+ distillSessionInput,
+ parseDistillAnswer,
+ resolveMessageId,
+ sessionInput,
+} from "../src/captures.js";
import { buildProject } from "../src/commands/build.js";
-import { captures, formatCaptures } from "../src/commands/captures.js";
+import { captures, distill, formatCaptures, setCapture } from "../src/commands/captures.js";
+import { closeSession } from "../src/commands/close.js";
+import { configSet } from "../src/commands/config.js";
import { init } from "../src/commands/init.js";
+import { sessionWrite } from "../src/commands/session.js";
import { createProgram } from "../src/program.js";
import type { Session } from "../src/schema/session.js";
+import {
+ addCaptureSuggestions,
+ CAPTURES_SCHEMA,
+ type CaptureItem,
+ canTransition,
+ readCaptures,
+ setCaptureState,
+} from "../src/store/captures.js";
+import { withLock } from "../src/store/lock.js";
import { projectPaths } from "../src/store/paths.js";
-import { buildCaptures, type CaptureSourceSession } from "../src/view/captures.js";
+import { type CaptureSourceSession, captureInput, hasOpenWork } from "../src/view/captures.js";
import { DATA_ELEMENT_ID } from "../src/view/model.js";
import { envFor, type FakeIo, fakeIo, T0, tempDir } from "./helpers.js";
const TEMPLATE = `<!doctype html><html><body><div id="root"></div>
<script id="${DATA_ELEMENT_ID}" type="application/json"></script></body></html>`;
-const branch = (open: string) => ({ title: "Parser", asked: "build it", outcome: "built", open });
+const NOW = "2026-10-21T10:00:00.000Z";
function source(over: Partial<CaptureSourceSession> & { sessionId: string }): CaptureSourceSession {
return {
@@ -26,19 +46,14 @@ function source(over: Partial<CaptureSourceSession> & { sessionId: string }): Ca
};
}
-describe("buildCaptures", () => {
- it("is empty for a project with no sessions or nothing open", () => {
- expect(buildCaptures([])).toEqual([]);
- expect(buildCaptures([source({ sessionId: "s1" })])).toEqual([]);
- });
+const branch = (open: string) => ({ title: "Parser", asked: "build it", outcome: "built", open });
- it("takes pending items and branch open lines, dropping blanks and in-source repeats", () => {
- const rows = buildCaptures([
+describe("the distiller's input", () => {
+ it("takes pending items and branch open lines, dropping blanks and repeats", () => {
+ const input = captureInput(
source({
sessionId: "s1",
title: "Ship it",
- author: "Ada",
- authorEmail: "[email protected]",
status: {
pending: [
{ text: "write the docs", needsUser: false },
@@ -47,71 +62,213 @@ describe("buildCaptures", () => {
],
},
messages: [
- { id: "h1", label: "m1", branch: branch("handle empty input") },
- { id: "h2", label: "m2", branch: branch(" ") },
- { id: "h3", label: "m3" },
- { id: "h4", label: "m4", unsummarized: true },
+ { id: "m1", label: "m1", title: "Build", branch: branch("handle empty input") },
+ { id: "m2", label: "m2", title: "More", branch: branch(" ") },
+ { id: "m3", label: "m3", title: "Done" },
+ { id: "h4", label: "m4", title: "Tail", unsummarized: true },
],
}),
+ );
+ expect(input.pending).toEqual([
+ { text: "write the docs", needsUser: false, messageId: "m3", label: "m3" },
]);
- expect(rows).toEqual([
- {
- key: "s1#p0",
- text: "write the docs",
- source: "pending",
+ expect(input.branches).toEqual([{ text: "handle empty input", messageId: "m1", label: "m1" }]);
+ expect(input.lastMessages.map((message) => message.id)).toEqual(["m1", "m2", "m3"]);
+ expect(hasOpenWork(input)).toBe(true);
+ });
+
+ it("has nothing to do for a session with nothing open", () => {
+ const input = captureInput(source({ sessionId: "s1", messages: [] }));
+ expect(hasOpenWork(input)).toBe(false);
+ expect(input.pending).toEqual([]);
+ expect(input.branches).toEqual([]);
+ });
+});
+
+describe("the distiller's prompt and answer", () => {
+ const input = captureInput(
+ source({
+ sessionId: "s9",
+ title: "Parser work",
+ status: { pending: [{ text: "decide the error format", needsUser: true }] },
+ messages: [
+ { id: "m1", label: "m1", title: "Build the parser" },
+ { id: "m2", label: "m2", title: "Handle input" },
+ ],
+ }),
+ );
+
+ it("names the leftover lines, the messages and the current list", () => {
+ const prompt = distillPrompt(input, [{ id: "c1a2b3c4", text: "old item" }], "auto");
+ expect(prompt).toContain("decide the error format");
+ expect(prompt).toContain("Handle input");
+ expect(prompt).toContain("c1a2b3c4: old item");
+ 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"}]');
+ });
+
+ 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" },
+ ],
+ duplicateOf: ["c11111111", 7],
+ });
+ expect(parseDistillAnswer(`\`\`\`json\n${answer}\n\`\`\``)).toEqual({
+ items: [
+ { text: "write the docs", messageId: "m1" },
+ { text: "fix the parser", messageId: "m2" },
+ ],
+ duplicateOf: ["c11111111"],
+ });
+ });
+
+ it("keeps a named message, a numeric one, or falls back to the newest", () => {
+ const withMessage = captureInput(
+ source({
sessionId: "s1",
- sessionTitle: "Ship it",
- author: "Ada",
- updatedAt: T0,
- // The newest recorded message, not the unsummarized tail.
- messageId: "h3",
- label: "m3",
- needsUser: false,
- },
+ 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", () => {
+ let dir: string;
+ let root: string;
+
+ beforeEach(async () => {
+ dir = await tempDir();
+ root = join(dir, "proj");
+ await mkdir(root);
+ await init(root, { name: "proj", retention: "keep", language: "auto" }, fakeIo(envFor(dir)));
+ });
+
+ 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 },
+ );
+ 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" }],
{
- key: "s1#h1",
- text: "handle empty input",
- source: "branch",
- sessionId: "s1",
- sessionTitle: "Ship it",
- author: "Ada",
- updatedAt: T0,
- messageId: "h1",
- label: "m1",
- branch: "Parser",
- needsUser: false,
+ now: later,
+ duplicateOf: [open.id],
},
- ]);
+ );
+ expect(added).toEqual([]);
+ const store = await readCaptures(root);
+ expect(store.items).toHaveLength(1);
+ expect(store.items[0]).toMatchObject({ id: open.id, state: "open", updatedAt: later });
});
- it("puts needsUser first, then the newest session, and keeps one row per source", () => {
- const rows = buildCaptures([
- source({
- sessionId: "old",
- updatedAt: "2026-10-01T00:00:00.000Z",
- status: { pending: [{ text: "pick a name", needsUser: true }] },
- }),
- source({
- sessionId: "a",
- updatedAt: "2026-10-10T00:00:00.000Z",
- status: { pending: [{ text: "same text", needsUser: false }] },
- }),
- source({
- sessionId: "b",
- updatedAt: "2026-10-20T00:00:00.000Z",
- status: { pending: [{ text: "same text", needsUser: false }] },
- }),
- ]);
- expect(rows.map((row) => row.key)).toEqual(["old#p0", "b#p0", "a#p0"]);
- // A session without a title falls back to its id; no message means no link.
- expect(rows[0]?.sessionTitle).toBe("old");
- expect(rows[0]?.messageId).toBeUndefined();
+ it("records closedAt on done and refuses an impossible transition", async () => {
+ const [item] = await addCaptureSuggestions(root, "s1", [{ text: "x", messageId: "m1" }], {
+ now: T0,
+ });
+ await expect(setCaptureState(root, item?.id as string, "done", T0)).rejects.toThrow(
+ "cannot become done",
+ );
+ await setCaptureState(root, item?.id as string, "open", T0);
+ const done = await setCaptureState(root, item?.id as string, "done", NOW);
+ expect(done.closedAt).toBe(NOW);
+ await expect(setCaptureState(root, "c00000000", "open", T0)).rejects.toThrow(
+ "no captured item",
+ );
+ expect(canTransition("suggested", "dismissed")).toBe(true);
+ expect(canTransition("done", "open")).toBe(false);
+ });
+
+ it("replaces a corrupt file with an empty one and warns", async () => {
+ await mkdir(join(root, ".cogit", "state"), { recursive: true });
+ await writeFile(projectPaths(root).captures, "{not json");
+ const warnings: string[] = [];
+ const store = await readCaptures(root, (line) => warnings.push(line));
+ expect(store).toEqual({ schema: CAPTURES_SCHEMA, items: [] });
+ expect(warnings[0]).toContain("corrupt");
+ expect(JSON.parse(await readFile(projectPaths(root).captures, "utf8"))).toEqual({
+ schema: CAPTURES_SCHEMA,
+ items: [],
+ });
});
});
describe("formatCaptures", () => {
- it("says so plainly when there is nothing", () => {
- expect(formatCaptures([], T0)).toEqual(["No captured work in this project."]);
+ const item = (
+ over: Partial<CaptureItem> & { id: string; state: CaptureItem["state"] },
+ ): CaptureItem => ({
+ text: "text",
+ source: { sessionId: "s1", messageId: "m3" },
+ createdAt: NOW,
+ updatedAt: NOW,
+ ...over,
+ });
+
+ it("groups the list into the three sections and leaves dismissed items out", () => {
+ const lines = formatCaptures(
+ {
+ schema: CAPTURES_SCHEMA,
+ items: [
+ // Same time: the id keeps the order stable.
+ item({ id: "c00000005", state: "suggested", text: "review me" }),
+ item({ id: "c00000001", state: "suggested", text: "same time", updatedAt: NOW }),
+ item({ id: "c00000002", state: "open", text: "accepted" }),
+ item({ id: "c00000003", state: "done", text: "closed" }),
+ item({ id: "c00000004", state: "dismissed", text: "gone" }),
+ ],
+ },
+ new Map([["s1:m3", "m3"]]),
+ NOW,
+ );
+ expect(lines).toEqual([
+ "To review",
+ " c00000001 same time (s1 m3 · under a minute ago)",
+ " c00000005 review me (s1 m3 · under a minute ago)",
+ "Open",
+ " c00000002 accepted (s1 m3 · under a minute ago)",
+ "Done",
+ " c00000003 closed (s1 m3 · under a minute ago)",
+ ]);
+ });
+
+ it("says so plainly when nothing was ever drafted", () => {
+ expect(formatCaptures({ schema: CAPTURES_SCHEMA, items: [] })).toEqual(["No captured work."]);
});
});
@@ -142,7 +299,6 @@ describe("cogit captures", () => {
const s1 = session({
sessionId: "s1",
title: "Parser",
- author: "Ada",
updatedAt: "2026-10-21T08:00:00.000Z",
status: {
goal: "",
@@ -150,49 +306,240 @@ describe("cogit captures", () => {
pending: [{ text: "decide the error format", needsUser: true }],
next: "",
},
- nodes: [
- {
- id: "h111111111111",
- parent: null,
- kind: "message",
- title: "Build the parser",
- at: "2026-10-21T07:00:00.000Z",
- branch: branch("unicode input untested"),
- },
- ],
+ nodes: [{ id: "m1", parent: null, kind: "message", title: "Build the parser", at: T0 }],
});
- const s2 = session({
- sessionId: "s2",
- title: "Docs",
- updatedAt: "2026-10-21T09:00:00.000Z",
- status: {
- goal: "",
- done: [],
- pending: [{ text: "decide the error format", needsUser: false }],
- next: "",
+ 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",
},
+ );
+ 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("2 h ago");
+ });
+
+ it("prints the store as JSON", async () => {
+ await addCaptureSuggestions(root, "s1", [{ text: "one", messageId: "m1" }], { 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" }], {
+ now: NOW,
});
- await writeFile(projectPaths(root).session("s1"), JSON.stringify(s1));
+ await setCapture(root, "accept", item?.id as string, io);
+ expect((await readCaptures(root)).items[0]?.state).toBe("open");
+ await setCapture(root, "done", item?.id as string, io);
+ expect((await readCaptures(root)).items[0]?.state).toBe("done");
+ await expect(setCapture(root, "dismiss", "c00000000", fakeIo(envFor(dir)))).rejects.toThrow(
+ "no captured item",
+ );
+ const [fresh] = await addCaptureSuggestions(root, "s1", [{ text: "two", messageId: "m1" }], {
+ now: NOW,
+ });
+ await expect(setCapture(root, "done", fresh?.id as string, io)).rejects.toThrow(
+ "cannot become done",
+ );
+ });
+
+ it("lets an unreadable store's own error through", async () => {
+ await addCaptureSuggestions(root, "s1", [{ text: "one", messageId: "m1" }], { 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 });
+ 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);
+ });
+});
+
+describe("distilling with the side model", () => {
+ let dir: string;
+ let root: string;
+ let bin: string;
+ let io: FakeIo;
+ let env: NodeJS.ProcessEnv;
+
+ /** A fake `claude` that answers with one fixed result. */
+ async function fakeClaude(answer: unknown): Promise<void> {
+ bin = join(dir, "bin");
+ await mkdir(bin, { recursive: true });
+ const file = join(bin, "claude");
+ await writeFile(
+ file,
+ `#!/usr/bin/env node
+let input = "";
+process.stdin.setEncoding("utf8");
+process.stdin.on("data", (c) => { input += c; });
+process.stdin.on("end", async () => {
+ const fs = await import("node:fs");
+ fs.writeFileSync(${JSON.stringify(join(dir, "prompt.txt"))}, input);
+ process.stdout.write(JSON.stringify({ result: ${JSON.stringify(JSON.stringify(answer))} }));
+});
+`,
+ );
+ await chmod(file, 0o755);
+ env = { ...envFor(dir), PATH: `${bin}:${process.env.PATH ?? ""}` };
+ io = fakeIo(env);
+ }
+
+ const s1 = (): Session => ({
+ schema: 1,
+ sessionId: "s1",
+ agent: "claude-code",
+ title: "Parser",
+ startedAt: T0,
+ updatedAt: T0,
+ status: {
+ goal: "",
+ done: [],
+ pending: [{ text: "write the docs", needsUser: false }],
+ next: "",
+ },
+ nodes: [
+ { id: "m1", parent: null, kind: "message", title: "Build the parser", at: T0 },
+ { id: "m2", parent: "m1", kind: "message", title: "More", at: T0 },
+ ],
+ });
+
+ beforeEach(async () => {
+ dir = await tempDir();
+ root = join(dir, "proj");
+ await mkdir(root);
+ await fakeClaude({ items: [{ text: "write the docs", messageId: "m2" }], 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.
+ const s2 = {
+ ...s1(),
+ sessionId: "s2",
+ title: "Quiet",
+ status: { goal: "", done: [], pending: [], next: "" },
+ };
await writeFile(projectPaths(root).session("s2"), JSON.stringify(s2));
});
- it("prints one line per row with source, author and age", async () => {
- const rows = await captures({ dir: root, io, now: T0 });
- // The same text in two sessions stays two rows.
- expect(rows.map((row) => row.key)).toEqual(["s1#p0", "s2#p0", "s1#h111111111111"]);
- expect(io.lines).toEqual([
- "! decide the error format (s1 m1 · Ada · 2 h ago)",
- " decide the error format (s2 · 1 h ago)",
- " unicode input untested (s1 m1 · Ada · 2 h ago)",
- "! = waiting for you",
- ]);
+ it("writes the answer as a suggested item with its source message", async () => {
+ const result = await distillSessionInput(root, sessionInput(s1()), { io });
+ expect(result?.proposal.items).toEqual([{ text: "write the docs", messageId: "m2" }]);
+ 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" },
+ });
+ });
+
+ it("returns nothing for a session with nothing open and calls no model", async () => {
+ const quiet = { ...s1(), status: { goal: "", done: [], pending: [], next: "" } };
+ const result = await distillSessionInput(root, sessionInput(quiet), { io });
+ expect(result).toBeUndefined();
+ expect((await readCaptures(root)).items).toEqual([]);
+ });
+
+ it("does nothing with captures turned off", async () => {
+ await configSet("captures", "false", fakeIo(env));
+ const result = await distillSessionInput(root, sessionInput(s1()), { io });
+ expect(result).toBeUndefined();
+ });
+
+ it("writes nothing in a dry run", async () => {
+ const result = await distillSessionInput(root, sessionInput(s1()), { io, dryRun: true });
+ expect(result?.proposal.items).toHaveLength(1);
+ expect((await readCaptures(root)).items).toEqual([]);
+ });
+
+ it("runs by hand and respects --dry-run", async () => {
+ await distill({ dir: root, io, dryRun: true });
+ expect(io.lines[0]).toContain('Session s1 "Parser"');
+ expect((await readCaptures(root)).items).toEqual([]);
+ await distill({ dir: root, io });
+ expect((await readCaptures(root)).items[0]?.state).toBe("suggested");
});
- it("prints JSON and limits to one session", async () => {
- await captures({ dir: root, io, json: true, session: "s2" });
- const rows = JSON.parse(io.lines.join("\n"));
- expect(rows).toHaveLength(1);
- expect(rows[0]).toMatchObject({ sessionId: "s2", text: "decide the error format" });
+ 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 },
+ );
+ await setCaptureState(root, existing?.id as string, "open", T0);
+ await fakeClaude({
+ items: [{ text: "write the docs", messageId: "m2" }],
+ duplicateOf: [existing?.id, "c00000000"],
+ });
+ const later = "2026-10-22T00:00:00.000Z";
+ const result = await distillSessionInput(root, sessionInput(s1()), { io, now: later });
+ // An unknown id in duplicateOf is dropped; the known one is kept as is.
+ expect(result?.proposal.duplicateOf).toEqual([existing?.id]);
+ expect(result?.proposal.added).toEqual([]);
+ const store = await readCaptures(root);
+ expect(store.items).toHaveLength(1);
+ 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: [] });
+ const record = { ...s1(), nodes: [] };
+ const result = await distillSessionInput(root, sessionInput(record), { io });
+ expect(result?.proposal.items).toEqual([]);
+ expect((await readCaptures(root)).items).toEqual([]);
+ });
+
+ it("refuses a hand-run pass with captures off", async () => {
+ await configSet("captures", "false", fakeIo(env));
+ await expect(distill({ dir: root, io })).rejects.toThrow("captured work is off");
+ });
+
+ it("skips a session whose lock is busy and warns when the pass fails", async () => {
+ await withLock(
+ projectPaths(root).lock("captures-s1"),
+ async () => {
+ expect(await distillAtClose(root, s1(), io)).toBeUndefined();
+ },
+ { timeoutMs: 0 },
+ );
+ // No `claude` on PATH: the failure lands in the warning, never in the close pass.
+ const broken = fakeIo({ ...env, PATH: join(dir, "missing") });
+ expect(await distillAtClose(root, s1(), broken)).toBeUndefined();
+ expect(broken.warnings[0]).toContain("could not distil captured work");
+ });
+
+ it("takes --session and --all, and says when nothing is new or left open", async () => {
+ await distill({ dir: root, io, session: "s1" });
+ expect((await readCaptures(root)).items).toHaveLength(1);
+ io.lines.length = 0;
+ // The same answer again is not drafted twice; the quiet session costs nothing.
+ await distill({ dir: root, io, all: true });
+ expect(io.lines.join("\n")).toContain("nothing new for session s1");
+ expect(io.lines.join("\n")).toContain("session s2 has nothing left open to distil");
+ });
+
+ it("says when a project has no session at all", async () => {
+ const empty = join(dir, "empty");
+ await mkdir(empty);
+ await init(empty, { name: "empty", retention: "keep", language: "auto" }, fakeIo(env));
+ await distill({ dir: empty, io });
+ expect(io.lines).toContain("this project has no recorded session to distil");
});
it("runs through the command line", async () => {
@@ -201,12 +548,83 @@ describe("cogit captures", () => {
server: async () => null,
stdin: async () => "",
});
- await program.parseAsync(["captures", root, "--session", "s2", "--json"], { from: "user" });
- expect(JSON.parse(io.lines.join("\n"))).toHaveLength(1);
+ await program.parseAsync(["captures", root, "--json"], { from: "user" });
+ expect(JSON.parse(io.lines.join("\n")).items).toEqual([]);
+ io.lines.length = 0;
+ await program.parseAsync(["captures", "distill", "--dry-run", "--dir", root], {
+ from: "user",
+ });
+ expect(io.lines.join("\n")).toContain('Session s1 "Parser"');
+ const [item] = await addCaptureSuggestions(
+ root,
+ "s1",
+ [{ text: "cli item", messageId: "m1" }],
+ {
+ now: T0,
+ },
+ );
+ await program.parseAsync(["captures", "accept", item?.id as string, "--dir", root], {
+ from: "user",
+ });
+ expect((await readCaptures(root)).items.find((row) => row.id === item?.id)?.state).toBe("open");
});
+});
- it("is carried in the map's page model", async () => {
- const model = await buildProject({ dir: root, io, templateHtml: TEMPLATE, quiet: true });
- expect(model.captures?.map((row) => row.key)).toEqual(["s1#p0", "s2#p0", "s1#h111111111111"]);
+describe("the session-end pass", () => {
+ it("leaves a suggested item after a session closes", async () => {
+ const dir = await tempDir();
+ const root = join(dir, "proj");
+ await mkdir(root);
+ const bin = join(dir, "bin");
+ await mkdir(bin, { recursive: true });
+ await writeFile(
+ join(bin, "claude"),
+ `#!/usr/bin/env node
+let input = "";
+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({
+ threads: [{ name: "Work", messages: "m1-m2", from: null, asked: "a", outcome: "o", open: "docs unwritten" }],
+ leftOff: "The docs are unwritten",
+ });
+ process.stdout.write(JSON.stringify({ result: answer }));
+});
+`,
+ );
+ await chmod(join(bin, "claude"), 0o755);
+ const env = { ...envFor(dir), PATH: `${bin}:${process.env.PATH ?? ""}` };
+ await init(root, { name: "proj", retention: "keep", language: "auto" }, fakeIo(env));
+ const folder = join(envFor(dir).CLAUDE_CONFIG_DIR ?? "", "projects", "proj");
+ await mkdir(folder, { recursive: true });
+ const at = (m: number) => `2026-10-23T10:0${m}:00.000Z`;
+ const typed = (m: number) => ({
+ type: "user",
+ timestamp: at(m),
+ message: { role: "user", content: `message ${m}` },
+ });
+ await writeFile(
+ join(folder, "s1.jsonl"),
+ `${[1, 2].map((m) => JSON.stringify(typed(m))).join("\n")}\n`,
+ );
+ await sessionWrite({ dir: root, by: "side" }, fakeIo(env), async () =>
+ JSON.stringify({
+ sessionId: "s1",
+ nodes: [1, 2].map((m) => ({
+ id: `m${m}`,
+ kind: "message",
+ title: `T${m}`,
+ parent: m === 1 ? null : `m${m - 1}`,
+ })),
+ }),
+ );
+
+ await closeSession(root, "s1", fakeIo(env));
+ const store = await readCaptures(root);
+ expect(store.items).toHaveLength(1);
+ expect(store.items[0]).toMatchObject({ text: "write the docs", state: "suggested" });
+ expect(store.items[0]?.source.sessionId).toBe("s1");
});
});
diff --git a/packages/cli/test/close.test.ts b/packages/cli/test/close.test.ts
index 736059a..cb01434 100644
--- a/packages/cli/test/close.test.ts
+++ b/packages/cli/test/close.test.ts
@@ -251,7 +251,7 @@ describe("backfill --tail --close", () => {
let input = "";
process.stdin.on("data", (c) => { input += c; });
process.stdin.on("end", async () => {
- (await import("node:fs")).writeFileSync(${JSON.stringify(join(dir, "prompt.txt"))}, input);
+ (await import("node:fs")).appendFileSync(${JSON.stringify(join(dir, "prompt.txt"))}, input + "\\n");
process.stdout.write(JSON.stringify({ result: ${JSON.stringify(answer)} }));
});
`,
diff --git a/packages/cli/test/panel.test.ts b/packages/cli/test/panel.test.ts
index 601f1cf..29a9f1a 100644
--- a/packages/cli/test/panel.test.ts
+++ b/packages/cli/test/panel.test.ts
@@ -92,6 +92,7 @@ describe("buildPanel", () => {
recordHeadless: false,
tryBeforeNotes: true,
shapes: true,
+ captures: true,
shareConversations: false,
recordCommit: "ask",
gitPolicy: "commit",
diff --git a/packages/cli/test/server.test.ts b/packages/cli/test/server.test.ts
index f06de4c..42513b6 100644
--- a/packages/cli/test/server.test.ts
+++ b/packages/cli/test/server.test.ts
@@ -29,6 +29,7 @@ import {
startMapServer,
stopStaleServer,
} from "../src/server.js";
+import { addCaptureSuggestions, readCaptures } from "../src/store/captures.js";
import { atomicWrite } from "../src/store/fs.js";
import { readInboxDismissed } from "../src/store/inbox-state.js";
import { readMapView } from "../src/store/map-view.js";
@@ -587,6 +588,7 @@ describe("settings read", () => {
recordHeadless: false,
tryBeforeNotes: true,
shapes: true,
+ captures: true,
language: "auto",
shareConversations: false,
recordCommit: "ask",
@@ -977,6 +979,108 @@ describe("inbox dismiss endpoint (Story 11.1)", () => {
});
});
+describe("captures state endpoint (Story 15.1)", () => {
+ function stateWrite(
+ server: MapServer,
+ token: string,
+ payload: unknown,
+ overrides: Record<string, string> = {},
+ ): Promise<Reply> {
+ return postConfig(`${server.url}/api/captures/state`, JSON.stringify(payload), {
+ origin: `http://127.0.0.1:${server.port}`,
+ [CONFIG_TOKEN_HEADER]: token,
+ ...overrides,
+ });
+ }
+
+ async function suggested(): Promise<string> {
+ const [item] = await addCaptureSuggestions(
+ root,
+ "s1",
+ [{ text: "write the docs", messageId: "m1" }],
+ { now: T0 },
+ );
+ return item?.id as string;
+ }
+
+ it("accepts a suggestion and closes an open item", async () => {
+ const id = await suggested();
+ const server = await start();
+ const token = await panelToken(server);
+ const accept = await stateWrite(server, token, { dir: root, id, state: "open" });
+ expect(accept.status).toBe(200);
+ expect(JSON.parse(accept.body)).toEqual({ ok: true, id, state: "open" });
+ expect((await readCaptures(root)).items[0]?.state).toBe("open");
+ const done = await stateWrite(server, token, { dir: root, id, state: "done" });
+ expect(done.status).toBe(200);
+ expect((await readCaptures(root)).items[0]?.closedAt).toBeTruthy();
+ });
+
+ it("refuses an unknown id, an impossible jump, a foreign project, a bad token and a bad body", async () => {
+ const id = await suggested();
+ const server = await start();
+ const token = await panelToken(server);
+ expect(
+ (await stateWrite(server, token, { dir: root, id: "c00000000", state: "open" })).status,
+ ).toBe(404);
+ expect((await stateWrite(server, token, { dir: root, id, state: "done" })).status).toBe(409);
+ expect((await stateWrite(server, token, { dir: root, id, state: "suggested" })).status).toBe(
+ 400,
+ );
+ expect(
+ (await stateWrite(server, token, { dir: join(dir, "elsewhere"), id, state: "open" })).status,
+ ).toBe(403);
+ expect((await stateWrite(server, "nope", { dir: root, id, state: "open" })).status).toBe(403);
+ expect((await stateWrite(server, token, { dir: root, id: "nope", state: "open" })).status).toBe(
+ 400,
+ );
+ expect((await stateWrite(server, token, { dir: root, state: "open" })).status).toBe(400);
+ expect(
+ (
+ await stateWrite(
+ server,
+ token,
+ { dir: root, id, state: "open" },
+ { "content-type": "text/plain" },
+ )
+ ).status,
+ ).toBe(415);
+ expect(
+ (
+ await stateWrite(
+ server,
+ token,
+ { dir: root, id, state: "open" },
+ { origin: "http://evil.example" },
+ )
+ ).status,
+ ).toBe(403);
+ });
+
+ it("refuses an oversized or malformed body, and answers 500 when the write fails", async () => {
+ const id = await suggested();
+ const server = await start();
+ const token = await panelToken(server);
+ expect(
+ (await stateWrite(server, token, { dir: root, id, state: "open", pad: "x".repeat(5000) }))
+ .status,
+ ).toBe(413);
+ expect(
+ (
+ await postConfig(`${server.url}/api/captures/state`, "{oops", {
+ origin: `http://127.0.0.1:${server.port}`,
+ [CONFIG_TOKEN_HEADER]: token,
+ })
+ ).status,
+ ).toBe(400);
+ expect((await stateWrite(server, token, [])).status).toBe(400);
+ // A directory where the store should be: the read fails, the route must not crash.
+ await rm(projectPaths(root).captures, { force: true });
+ await mkdir(projectPaths(root).captures, { recursive: true });
+ expect((await stateWrite(server, token, { dir: root, id, state: "open" })).status).toBe(500);
+ });
+});
+
describe("row width endpoint", () => {
const SESSION = "3f2b1c4d-0000-4000-8000-000000000001";
diff --git a/packages/cli/test/settings.test.ts b/packages/cli/test/settings.test.ts
index 61b567c..9c80b83 100644
--- a/packages/cli/test/settings.test.ts
+++ b/packages/cli/test/settings.test.ts
@@ -26,6 +26,7 @@ describe("settings model", () => {
recordHeadless: parsed.recordHeadless,
tryBeforeNotes: parsed.tryBeforeNotes,
shapes: parsed.shapes,
+ captures: parsed.captures,
shareConversations: parsed.shareConversations,
recordCommit: parsed.recordCommit,
gitPolicy: parsed.gitPolicy,
@@ -72,6 +73,7 @@ describe("settings model", () => {
recordHeadless: false,
tryBeforeNotes: true,
shapes: true,
+ captures: true,
language: "tr",
shareConversations: false,
recordCommit: "ask",
diff --git a/packages/template/src/CapturesView.tsx b/packages/template/src/CapturesView.tsx
index 5586e44..9845d0a 100644
--- a/packages/template/src/CapturesView.tsx
+++ b/packages/template/src/CapturesView.tsx
@@ -1,33 +1,136 @@
-import type { ViewCapture } from "../../cli/src/view/model.js";
+import { type ReactNode, useEffect, useState } from "react";
+import { timeSince } from "../../cli/src/view/inbox.js";
+import type { ViewCapture, ViewSession } from "../../cli/src/view/model.js";
+import { pageToken, saveCaptureState } from "./data.js";
import type { FilesTarget } from "./FilesView.js";
import { formatStamp } from "./format.js";
/**
- * Captured work (Story 14.1): what the sessions left open, read from the
- * record (`pending` items and branch summaries' open lines). A read-only list,
- * not a plan: no checkboxes, no status, no assignee. Clicking a row opens the
+ * Captured work (Story 15.1): a short list a side model drafted from what the
+ * 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.
*/
+
+type CaptureState = ViewCapture["state"];
+/** The states the user can set; `suggested` is only ever written by the distiller. */
+type CaptureTarget = "open" | "dismissed" | "done";
+
+/**
+ * Whether the map shows the Captured button: only while the setting is on and
+ * something waits or is open. A store of only done items has no button and no
+ * empty list, and the setting off hides it.
+ */
+export function capturesButtonVisible(
+ captures: readonly ViewCapture[] | undefined,
+ setting: boolean | undefined,
+): boolean {
+ return (
+ setting !== false &&
+ (captures ?? []).some((item) => item.state === "suggested" || item.state === "open")
+ );
+}
+
+function stateTarget(captures: readonly ViewCapture[], state: CaptureState) {
+ return captures.filter((item) => item.state === state);
+}
+
+function byNewest(a: ViewCapture, b: ViewCapture): number {
+ return b.updatedAt.localeCompare(a.updatedAt);
+}
+
export function CapturesView({
captures,
+ sessions,
+ dir,
active,
onSelect,
onClose,
}: {
captures: readonly ViewCapture[] | undefined;
+ /** The project's sessions, for the title of each item's source message. */
+ sessions: readonly ViewSession[];
+ /** The project's path, for the state write. */
+ dir: string;
/** The message the map has selected, if any. */
active: FilesTarget | null;
onSelect: (target: FilesTarget) => void;
onClose: () => void;
}) {
- const all = captures ?? [];
+ // The page is a snapshot; a state change is shown at once and the live page
+ // swaps in the rebuilt model a moment later.
+ const [items, setItems] = useState<readonly ViewCapture[]>(captures ?? []);
+ const [error, setError] = useState<string | null>(null);
+ 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) {
+ setError("This is a saved page; open it with `cogit open` to change the list.");
+ return;
+ }
+ const previous = items;
+ setError(null);
+ setItems(items.map((row) => (row.id === item.id ? { ...row, state } : row)));
+ void saveCaptureState(dir, item.id, state, token).catch((err: unknown) => {
+ setItems(previous);
+ setError(err instanceof Error ? err.message : String(err));
+ });
+ }
+
+ const review = stateTarget(items, "suggested").sort(byNewest);
+ const open = stateTarget(items, "open").sort(byNewest);
+ 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 age = timeSince(item.updatedAt, now);
+ const selected =
+ active?.sessionId === item.source.sessionId && active.messageId === item.source.messageId;
+ return (
+ <li key={item.id}>
+ <div className={`capture-row${selected ? " is-active" : ""}`}>
+ <button
+ type="button"
+ className="capture-open"
+ title={formatStamp(item.updatedAt)}
+ onClick={() =>
+ onSelect({ sessionId: item.source.sessionId, messageId: item.source.messageId })
+ }
+ >
+ <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>
+ {age === "" ? null : <span className="capture-time">{age} ago</span>}
+ </span>
+ </button>
+ <span className="capture-actions">{actions}</span>
+ </div>
+ </li>
+ );
+ }
+
+ const empty = review.length === 0 && open.length === 0 && done.length === 0;
+
return (
<nav className="outline capture-view" aria-label="Captured work">
<header className="outline-head capture-head">
- <span className="outline-title capture-title">
- Captured work — what the sessions left open
- </span>
- <span className="outline-badge capture-badge">{all.length}</span>
+ <span className="outline-title capture-title">Captured work</span>
+ <span className="outline-badge capture-badge">{review.length + open.length}</span>
<button
type="button"
className="drilldown-close"
@@ -37,65 +140,67 @@ export function CapturesView({
×
</button>
</header>
- <p className="capture-note">
- Derived from the record on every build. Not a plan: cogit keeps no planning state.
- </p>
+ <p className="capture-note">A list you curate, not a plan cogit keeps.</p>
+ {error === null ? null : <p className="muted capture-error">{error}</p>}
<div className="outline-scroll">
- {all.length === 0 ? (
- <p className="empty">No captured work in this project.</p>
+ {empty ? (
+ <p className="empty">No captured work.</p>
) : (
- <ul className="capture-list">
- {all.map((row) => {
- const messageId = row.messageId;
- const selected =
- messageId !== undefined &&
- active?.sessionId === row.sessionId &&
- active.messageId === messageId;
- const body = (
- <>
- <span className="capture-line">
- <span className="capture-chip">
- {row.source === "pending" ? "pending" : "branch"}
- </span>
- {row.needsUser ? (
- <span className="capture-needs" title="Waiting for you">
- your call
- </span>
- ) : null}
- <span className="capture-text">{row.text}</span>
- </span>
- <span className="capture-meta">
- <span className="capture-session">{row.sessionTitle}</span>
- {row.label === undefined ? null : (
- <span className="capture-label">{row.label}</span>
- )}
- {row.branch === undefined ? null : (
- <span className="capture-branch">╭ {row.branch}</span>
- )}
- {row.author === undefined ? null : (
- <span className="capture-author">{row.author}</span>
- )}
- <span className="capture-time">{formatStamp(row.updatedAt)}</span>
- </span>
- </>
- );
- return (
- <li key={row.key}>
- {messageId === undefined ? (
- <div className="capture-row">{body}</div>
- ) : (
- <button
- type="button"
- className={`capture-row${selected ? " is-active" : ""}`}
- onClick={() => onSelect({ sessionId: row.sessionId, messageId })}
- >
- {body}
- </button>
+ <>
+ {review.length === 0 ? null : (
+ <section className="capture-section">
+ <h3 className="capture-heading">To review</h3>
+ <ul className="capture-list">
+ {review.map((item) =>
+ row(
+ item,
+ <>
+ <button
+ type="button"
+ className="capture-action is-accept"
+ onClick={() => change(item, "open")}
+ >
+ Accept
+ </button>
+ <button
+ type="button"
+ className="capture-action"
+ onClick={() => change(item, "dismissed")}
+ >
+ Dismiss
+ </button>
+ </>,
+ ),
+ )}
+ </ul>
+ </section>
+ )}
+ {open.length === 0 ? null : (
+ <section className="capture-section">
+ <h3 className="capture-heading">Open</h3>
+ <ul className="capture-list">
+ {open.map((item) =>
+ row(
+ item,
+ <button
+ type="button"
+ className="capture-action"
+ onClick={() => change(item, "done")}
+ >
+ Done
+ </button>,
+ ),
)}
- </li>
- );
- })}
- </ul>
+ </ul>
+ </section>
+ )}
+ {done.length === 0 ? null : (
+ <details className="capture-section capture-done">
+ <summary className="capture-heading">Done (last 10)</summary>
+ <ul className="capture-list">{done.map((item) => row(item, null))}</ul>
+ </details>
+ )}
+ </>
)}
</div>
</nav>
diff --git a/packages/template/src/Graph.tsx b/packages/template/src/Graph.tsx
index 5305e97..02f14ed 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 } from "./CapturesView.js";
+import { CapturesView, capturesButtonVisible } from "./CapturesView.js";
import { loadMapView, pageToken, saveOpenSessions, saveRowWidth } from "./data.js";
import { type FilesTarget, FilesView } from "./FilesView.js";
import { useFullscreen } from "./fullscreen.js";
@@ -335,6 +335,9 @@ function Flow({ model, search }: { model: LineageViewModel; search: MapSearchSta
const personOptions = useMemo(() => people.options(), [people]);
const { expanded: fullscreen, toggle: toggleFullscreen } = useFullscreen();
const bigChangeLines = model.settings?.bigChangeLines ?? 300;
+ // The Captured button is only there while the setting is on and something
+ // waits or is open; a store of only done items has no button and no empty list.
+ const capturesVisible = capturesButtonVisible(model.captures, model.settings?.captures);
const [focusedId, setFocusedId] = useState<string | null>(() => {
if (initial === null) return null;
if (initial.messageId === undefined) return `session:${initial.sessionId}`;
@@ -777,24 +780,28 @@ function Flow({ model, search }: { model: LineageViewModel; search: MapSearchSta
>
{showFiles ? "Hide files" : "Files"}
</button>
- <button
- type="button"
- className="outline-button capture-button"
- aria-pressed={showCaptures}
- title="What the sessions left open, read from the record"
- onClick={() => {
- setShowCaptures((value) => !value);
- setShowFiles(false);
- setShowOutline(false);
- }}
- >
- {showCaptures ? "Hide captured" : "Captured"}
- </button>
+ {capturesVisible ? (
+ <button
+ type="button"
+ className="outline-button capture-button"
+ aria-pressed={showCaptures}
+ title="A list you curate: what the sessions left undone"
+ onClick={() => {
+ setShowCaptures((value) => !value);
+ setShowFiles(false);
+ setShowOutline(false);
+ }}
+ >
+ {showCaptures ? "Hide captured" : "Captured"}
+ </button>
+ ) : null}
</div>
<div className="graph-wrap">
{showCaptures ? (
<CapturesView
captures={model.captures}
+ sessions={model.sessions}
+ dir={model.project.path}
active={
selection?.type === "node"
? { sessionId: selection.sessionId, messageId: selection.nodeId }
diff --git a/packages/template/src/data.ts b/packages/template/src/data.ts
index fe4fc8a..a049436 100644
--- a/packages/template/src/data.ts
+++ b/packages/template/src/data.ts
@@ -158,6 +158,28 @@ export async function saveDismiss(
}
}
+/**
+ * Moves one captured item to a state the user chose (Story 15.1). The list is
+ * local to the project, so this needs the local server; over `file://` the row
+ * only says so. The server allows only the user's transitions.
+ */
+export async function saveCaptureState(
+ dir: string,
+ id: string,
+ state: "open" | "dismissed" | "done",
+ token: string,
+): Promise<void> {
+ const response = await fetch("/api/captures/state", {
+ method: "POST",
+ headers: { "content-type": "application/json", "x-cogit-token": token },
+ body: JSON.stringify({ dir, id, state }),
+ });
+ if (!response.ok) {
+ const text = (await response.text()).trim();
+ throw new Error(text || `could not save the item (HTTP ${response.status})`);
+ }
+}
+
/**
* One commit's patch for the message details (Story 10.5). Only the local
* server answers this; over `file://` the diff rows do not expand.
diff --git a/packages/template/src/fixture.ts b/packages/template/src/fixture.ts
index c27c32d..c80a504 100644
--- a/packages/template/src/fixture.ts
+++ b/packages/template/src/fixture.ts
@@ -61,6 +61,7 @@ export const fixture: LineageViewModel = {
recordHeadless: false,
tryBeforeNotes: true,
shapes: true,
+ captures: true,
shareConversations: false,
recordCommit: "ask",
gitPolicy: "ignore",
diff --git a/packages/template/src/styles.css b/packages/template/src/styles.css
index 3fb2f99..f1d2536 100644
--- a/packages/template/src/styles.css
+++ b/packages/template/src/styles.css
@@ -1165,7 +1165,7 @@ body:has(.map-shell.is-expanded) {
font-family: var(--mono, ui-monospace, SFMono-Regular, Menlo, monospace);
}
-/* Captured work (Story 14.1): a read-only list, visibly not a message row. */
+/* Captured work (Story 15.1): a short list the user curates, not a plan. */
.capture-view {
width: 340px;
}
@@ -1201,28 +1201,35 @@ body:has(.map-shell.is-expanded) {
list-style: none;
}
+.capture-section {
+ padding: 2px 2px 4px;
+}
+
+.capture-heading {
+ margin: 6px 4px 2px;
+ color: var(--muted);
+ font-size: 11px;
+ font-weight: 600;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+}
+
+.capture-done > summary.capture-heading {
+ cursor: pointer;
+}
+
.capture-row {
display: flex;
- flex-direction: column;
- gap: 3px;
- width: 100%;
+ align-items: flex-start;
+ gap: 6px;
margin: 2px 0;
padding: 6px 8px;
- color: var(--text);
- background: transparent;
- border: 0;
border-left: 2px solid var(--capture);
border-radius: 0 5px 5px 0;
- font: inherit;
font-size: 12px;
- text-align: left;
-}
-
-button.capture-row {
- cursor: pointer;
}
-button.capture-row:hover {
+.capture-row:hover {
background: var(--hover);
}
@@ -1231,27 +1238,53 @@ button.capture-row:hover {
outline: 1px solid var(--capture);
}
-.capture-line {
+.capture-open {
display: flex;
- align-items: baseline;
- gap: 6px;
+ flex: 1;
+ flex-direction: column;
+ gap: 3px;
min-width: 0;
+ padding: 0;
+ color: var(--text);
+ background: none;
+ border: 0;
+ font: inherit;
+ font-size: 12px;
+ text-align: left;
+ cursor: pointer;
}
-.capture-chip,
-.capture-needs {
+.capture-actions {
+ display: flex;
flex: none;
- padding: 0 5px;
- border: 1px solid var(--capture);
- border-radius: 8px;
+ gap: 4px;
+}
+
+.capture-action {
+ padding: 1px 6px;
+ color: var(--muted);
+ background: transparent;
+ border: 1px solid var(--line);
+ border-radius: 6px;
+ font: inherit;
+ font-size: 11px;
+ cursor: pointer;
+}
+
+.capture-action:hover {
+ color: var(--text);
+ border-color: var(--capture);
+}
+
+.capture-action.is-accept {
color: var(--capture);
- font-size: 10px;
- line-height: 15px;
+ border-color: var(--capture);
}
-.capture-needs {
- background: var(--capture);
- color: var(--bg);
+.capture-error {
+ margin: 0;
+ padding: 2px 10px 6px;
+ font-size: 11px;
}
.capture-text {
@@ -1266,8 +1299,7 @@ button.capture-row:hover {
font-size: 11px;
}
-.capture-label,
-.capture-branch {
+.capture-label {
font-family: var(--mono, ui-monospace, SFMono-Regular, Menlo, monospace);
}
diff --git a/packages/template/test/captures-view.test.tsx b/packages/template/test/captures-view.test.tsx
index dea35c2..bed04be 100644
--- a/packages/template/test/captures-view.test.tsx
+++ b/packages/template/test/captures-view.test.tsx
@@ -1,62 +1,81 @@
import { createElement } from "react";
import { renderToStaticMarkup } from "react-dom/server";
import { describe, expect, it } from "vitest";
-import type { ViewCapture } from "../../cli/src/view/model.js";
-import { CapturesView } from "../src/CapturesView.js";
+import type { ViewCapture, ViewSession } from "../../cli/src/view/model.js";
+import { CapturesView, capturesButtonVisible } from "../src/CapturesView.js";
const T0 = "2026-10-26T10:00:00.000Z";
-const rows: ViewCapture[] = [
+const sessions = [
{
- key: "s1#p0",
- text: "decide the error format",
- source: "pending",
sessionId: "s1",
- sessionTitle: "Parser work",
- messageId: "h3",
- label: "m3",
- author: "Ada",
- updatedAt: T0,
- needsUser: true,
- },
- {
- key: "s1#h1",
- text: "unicode input untested",
- source: "branch",
- sessionId: "s1",
- sessionTitle: "Parser work",
- messageId: "h1",
- label: "m1",
- branch: "Parser",
- updatedAt: T0,
- needsUser: false,
+ title: "Parser work",
+ messages: [{ id: "m3", label: "m3", title: "Build it" }],
},
+] as unknown as ViewSession[];
+
+const item = (
+ over: Partial<ViewCapture> & { id: string; state: ViewCapture["state"] },
+): ViewCapture => ({
+ text: "some work",
+ source: { sessionId: "s1", messageId: "m3" },
+ createdAt: T0,
+ updatedAt: T0,
+ ...over,
+});
+
+const items: ViewCapture[] = [
+ item({ id: "c00000001", state: "suggested", text: "decide the error format" }),
+ item({ id: "c00000002", state: "open", text: "write the docs" }),
+ item({ id: "c00000003", state: "done", text: "close the release" }),
+ item({ id: "c00000004", state: "dismissed", text: "gone" }),
];
function render(captures: ViewCapture[] | undefined): string {
return renderToStaticMarkup(
- createElement(CapturesView, { captures, active: null, onSelect: () => {}, onClose: () => {} }),
+ createElement(CapturesView, {
+ captures,
+ sessions,
+ dir: "/p",
+ active: null,
+ onSelect: () => {},
+ onClose: () => {},
+ }),
);
}
describe("CapturesView", () => {
- it("lists each row with its source and the muted not-a-plan note", () => {
- const html = render(rows);
- expect(html).toContain("Captured work — what the sessions left open");
- expect(html).toContain('class="capture-note"');
- expect(html).toContain("Not a plan");
+ it("shows the three sections with their buttons", () => {
+ const html = render(items);
+ expect(html).toContain("Captured work");
+ expect(html).toContain("A list you curate, not a plan cogit keeps.");
+ expect(html).toContain("To review");
+ expect(html).toContain("Open");
+ expect(html).toContain("Done (last 10)");
expect(html).toContain("decide the error format");
- expect(html).toContain("unicode input untested");
+ expect(html).toContain("write the docs");
+ expect(html).toContain(">Accept<");
+ expect(html).toContain(">Dismiss<");
+ expect(html).toContain(">Done<");
expect(html).toContain("Parser work");
expect(html).toContain("m3");
- expect(html).toContain("╭ Parser");
- expect(html).toContain("your call");
- // Read-only: nothing to tick.
- expect(html).not.toContain('type="checkbox"');
+ // A dismissed item is closed and stays out of the list.
+ expect(html).not.toContain("gone");
+ });
+
+ it("is empty when nothing was drafted", () => {
+ expect(render(undefined)).toContain("No captured work.");
+ expect(render([item({ id: "c00000009", state: "dismissed" })])).toContain("No captured work.");
});
+});
- it("shows a plain empty state", () => {
- expect(render(undefined)).toContain("No captured work in this project.");
- expect(render([])).toContain("No captured work in this project.");
+describe("the Captured button", () => {
+ it("shows only while the setting is on and something waits or is open", () => {
+ expect(capturesButtonVisible(items, true)).toBe(true);
+ expect(capturesButtonVisible(items, undefined)).toBe(true);
+ expect(capturesButtonVisible(items, false)).toBe(false);
+ expect(capturesButtonVisible([item({ id: "c00000009", state: "done" })], true)).toBe(false);
+ expect(capturesButtonVisible([], true)).toBe(false);
+ expect(capturesButtonVisible(undefined, true)).toBe(false);
});
});