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(map): keep the map live and read activity from messages

Erend0705892e2e2
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 670f63d..081ce52 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -5,6 +5,9 @@ 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]
+### Changed
+- Activity is message time everywhere: the map's session lanes and the project switcher's last-activity date follow the newest message a session holds, so editing an old record no longer makes it look like it ran until now. The local map server watches Claude Code's transcripts while a map page is open (one recursive, debounced watcher) and rebuilds the map itself, so the page is live without the plugin's Stop hook; the watch closes when the last tab does. The `commitBetween` hint asks git for a commit that actually landed in this repository between the two messages instead of trusting a `git commit` line in the transcript, `blame` takes a `[dir]` positional like `log` and `show`, and `session show` gained `--full` for every recorded message and the parent candidates (the default stays compact). The record-update skill text is about half its former size, cutting the fixed cost of every update.
+
### Added
- The link from code back to the thought: a git `prepare-commit-msg` hook adds a `Thought: h…` trailer naming the newest message of the session in `.cogit/HEAD` (written by the `UserPromptSubmit` hook), so every commit carries the message it came out of. It skips merges and squashes, a `.cogit/HEAD` older than the new `trailerMaxAgeHours` setting (6 hours by default), a project whose records stay out of git and an unreadable transcript, keeps a trailer an `--amend` already had, and never blocks a commit. Build, `log`, `blame` and the Files view read the trailers back with `git log` and attach those commits to their message nodes (a trailer wins over a hash the agent listed elsewhere); `cogit show <commit-sha>` opens the thought behind a commit. `init` and `cogit config git commit` install both hooks into the directory git really uses, and `cogit hooks uninstall` removes only cogit's marked block, leaving the user's own hook lines untouched.
- The record travels with the repo: `init` now answers **yes** to committing the session records, which puts `.cogit/sessions/` and `project.json` in git while a generated `.cogit/.gitignore` keeps the local state (conversations, hooks state, locks, inbox, map, `HEAD`, backups) out; `cogit config git commit|ignore` switches an existing project without deleting anything. A git `pre-commit` hook stages the current session's record files (`.cogit/HEAD`, written by a new `UserPromptSubmit` hook) with the next code commit, but never creates a record-only commit and works with `git commit -a` and `git commit <paths>`. Each session gets an `author` (git `user.name`, else the OS user) on its first write, shown on the map's session row and in `log`, and `project.json` is written with sorted keys and one epoch per line so git merges it. New settings `shareConversations` (commit the raw chat too, off by default) and `recordCommit` (`ask`, `auto` or `off`: what to do with the messages recorded after the last code commit) are in Settings → Recording; a clone without the chat says "This conversation is not on this machine".
diff --git a/packages/cli/skills/record/SKILL.md b/packages/cli/skills/record/SKILL.md
index 57e6658..a5585a1 100644
--- a/packages/cli/skills/record/SKILL.md
+++ b/packages/cli/skills/record/SKILL.md
@@ -1,167 +1,89 @@
---
name: record
-description: Record or update this session's lineage for cogit, one node per user message with what came of it, each hanging from the earlier message it reacts to, with a summary at each branch start, plus the goal, open items and what comes next. Use it when the user asks to record the session or its lineage, or when a cogit hook asks for an update.
+description: Record or update this session's cogit lineage: one node per user message with what came of it and its parent, branch summaries, and the goal, open items and next step. Use when the user asks to record the session or its lineage, or when a cogit hook asks for an update.
allowed-tools: Bash(node "${CLAUDE_PLUGIN_ROOT}/dist/cli.js" *) Edit(/${CLAUDE_PROJECT_DIR}/.cogit/inbox/**)
---
# Record this session's lineage
-This is the current record for this session (the output of `cogit session show`):
+The current record (`cogit session show`):
!`node "${CLAUDE_PLUGIN_ROOT}/dist/cli.js" session show "${CLAUDE_SESSION_ID}" -C "${CLAUDE_PROJECT_DIR}"`
-## First, check the record
+## Check first
-- If `initialized` is `false`, reply with exactly this line and stop:
- "cogit is not set up in this project yet; run `npx cogit init` here first."
-- If `sessionError` is set, tell the user the session record is unreadable and
- quote the error. Then stop. Never write over it.
-- If `newMessages` is empty and nothing else changed since the record was last
- updated, reply "Lineage is up to date." and stop.
+- `initialized: false`: reply exactly "cogit is not set up in this project yet; run
+ `npx cogit init` here first." and stop.
+- `sessionError`: quote it and stop; never write over the record.
+- Nothing new or changed (`newMessages` empty): reply "Lineage is up to date." and stop.
-## Looking something up
+## Look something up
-When the user asks where something was discussed or decided, or gives a word
-rather than a hash, do not guess: run
-`node "${CLAUDE_PLUGIN_ROOT}/dist/cli.js" search "<text>" -C "${CLAUDE_PROJECT_DIR}"`.
-It scans message titles, branch summaries, decisions and the stored conversation,
-newest first, with the same matcher as the map's search box. Add `--json` for
-fields, `-n <count>` to limit and `--session <id|prefix>` to narrow. A message
-hash goes to `show`, not `search`.
+A word rather than a hash: `node "${CLAUDE_PLUGIN_ROOT}/dist/cli.js" search "<text>" -C "<dir>"`
+scans titles, branch summaries, decisions and stored conversations, newest first (`--json`,
+`-n`, `--session`); hashes go to `show`.
-## Then send only what is new or changed
+## Send only what is new or changed
-Build one JSON object:
+One JSON object:
- `sessionId`: always `"${CLAUDE_SESSION_ID}"`.
-- `title`: a few words naming what this session is about. Send it on the first
- write, or when the session's focus changed.
-- `epoch`: the `id` of the epoch (feature or epic) from `epochs` that this work
- belongs to. If none fits and the work is a distinct feature, first run
- `node "${CLAUDE_PLUGIN_ROOT}/dist/cli.js" epoch add <id> "<title>" -C "<dir>"`
- with a short lowercase id. Leave it out when unsure.
-- `status`: replaces the stored status, so send all four fields every time:
- - `goal`: one sentence.
- - `done`: short items finished in this session so far.
- - `pending`: `{ "text": "…", "needsUser": true }` for anything waiting on the
- user, and `needsUser: false` for work that is simply not done yet.
- - `next`: the next concrete step.
-- `nodes`: only new nodes, or existing ones whose fields changed. Nodes you
- leave out are kept, and so are fields you leave out.
-
-## The map is the user's messages
-
-Each message the user wrote is one node on the map. `newMessages` in the record
-lists the user's messages that have no node yet, in order, each with a stable
-`id` (`h…`), the `label` the user reads (`m1`, `m2`, …), its time and the start
-of its text. Send one `message` node for every one of them; skip none, even a
-short "ok" or "go on".
-
-- `id`: the message's `id` from `newMessages`. The `label` (`m1`) is accepted
- too, and so is either form for a parent or link: the CLI maps it to the stable
- id. The stable id never changes when a parent is corrected.
-- `kind`: `"message"`.
-- `parent`: the id (or label) of the earlier message it reacts to (see below),
- or `null` for a new root.
-- `title`: the message in a few words, in the user's own wording where possible
- ("Continue with Epic 4", "Why does auto mode keep stopping?"). Never copy a
- long paste; name what it is.
-- `summary`: one or two sentences on what came of it: the answer, the result or
- the state it left. Write it ONLY when `messageSummaries` in the record is
- `true`; while it is `false` (the default) leave `summary` out, like most git
- commits: a subject line, no body. `decidedBy`, `why` and `alternatives` are
- written either way.
-- When the message itself made a decision (the user asked for something, picked
- an option or approved a proposal): `decidedBy` (`"user"` or `"agreed"`), the
- reason in `why`, and the options not taken in `alternatives`, each as
- `{ "option": "…", "why": "…" }`.
-- Your own work goes inside the message node that caused it, never in nodes of
- its own:
- - `work`: short items for what you did (looked up, changed, tested).
- - `agentDecisions`: choices you made on your own while doing it, each as
- `{ "title": "…", "why": "…", "alternatives": [ … ] }`.
- - `commits`: short hashes of the commits that carry it out; `files`: the main
- files it touched, relative to the project (a few, not every file).
-- Work that continued over several messages belongs to the message where it
- ended up; update an earlier message node only to correct it.
-
-If `newMessages` is `null`, the transcript could not be read. Then record only
-`status` and leave the nodes alone.
-
-## Hang each message from the one it reacts to
-
-The map is a git-like graph of the user's messages: every message grows from an
-earlier one, and a thread that starts something new is a root.
-
-- Default: `parent` is the previous message. Most messages react to the last
- answer.
-- `parent: null` only when the message would make sense as the first message of
- a new chat and does not rely on the previous answer.
-- An explicit return to an older thread ("back to the representation question"):
- set `parent` to that thread's message and put the previous message in `links`.
-- The FIRST message of a session that continues earlier work hangs from the
- message it continues: write `parent` as `<sessionId>:<stable id>`. `candidates`
- in the record lists the last messages of the most recent other sessions for
- this. Usually that is the last message of the previous session, or the one that
- asked for a prompt for the next chat. A first message that starts something new
- is a root. The target must be a message of an earlier session of this project.
-- When unsure, use the previous message. A wrong "continue" only hides a branch;
- a wrong branch breaks the chain.
-- `links`: up to 5 earlier messages of this session that this one returns to or
- builds on besides its parent. They show as dashed arrows. The CLI drops a
- link or parent that is not an earlier message, so a mistyped one is not fatal.
-- Correcting a parent or a link later is safe and is recorded as a new fact: the
- message keeps its id and its notes. Send the node again with the new `parent`
- or `links`; resending an unchanged node writes nothing.
-- `newMessages` hints help, but are hints, not rules: `gapMinutes` since the
- previous message, `resumed` (a `/clear`, a resume or a new process came in
- between), `commitBetween` (this session committed between them). The wording
- decides. `lastMessages` lists the last recorded messages with their stable
- `id`, `label` and parent.
-- For a session's first message, `candidates` names the message it may continue
- (with its session and stable `id`) and `continuesHint` is set when the message
- says so ("devam", "kaldığımız yerden", "continue") or the transcript read a
- handoff file. A hint only: an unrelated first message stays a root.
-
-## Summarize each branch
-
-A branch starts at a root or where a message gets a second child. Its first
-message carries a `branch` object, short, in the conversation's language:
-
-```json
-{
- "title": "What this thread is about, in a few words",
- "asked": "What the user set out to do in this thread",
- "outcome": "What came of it, so far",
- "open": "What is still open; may be empty"
-}
-```
-
-- Write or update it when the branch ends (a new branch or root starts, or a
- message returns to an older thread) or when you update the session status at
- the end — not on every turn, to keep the update cheap.
-- Only the first message of a branch carries a `branch`.
-
-New records send no `phase` nodes: topics are no longer the skeleton. Old
-records that still have `phase`, `step`, `decision` and `question` nodes keep
-rendering; leave them as they are and do not add new ones.
-
-Write titles and text in the conversation's language when `language` is `"auto"`,
-and in that language otherwise. JSON keys stay in English.
-
-Record decisions and their reasons, not raw content. Never include secrets,
-tokens, passwords, credentials, personal data, file contents or command output.
+- `title`: a few words; on the first write or when the focus changed.
+- `epoch`: an `epochs` id that fits; a distinct new feature first gets
+ `node "${CLAUDE_PLUGIN_ROOT}/dist/cli.js" epoch add <id> "<title>" -C "<dir>"`. Omit when unsure.
+- `status`: replaces all four fields, so send each: `goal` (one sentence), `done`, `pending`
+ (`{ "text", "needsUser": true }` when it waits on the user), `next` (concrete step).
+- `nodes`: only new nodes or changed fields; the rest is kept.
+
+## One node per user message
+
+`newMessages` lists unrecorded messages in order with stable `id`, display `label`, time and
+text start. Send one `message` node for every one, even "ok"; skip none. If it is `null`, the
+transcript is unreadable: send only `status`.
+
+- `id`: the message's `id`; the `label` works too, and a parent or link accepts either.
+ `kind`: `"message"`.
+- `title`: a few words in the user's wording; never copy a long paste.
+- `summary`: what came of it, ONLY when `messageSummaries` is true; otherwise leave it out,
+ like a commit with a subject and no body.
+- A decision: `decidedBy` (`"user"` or `"agreed"`), `why`, `alternatives`
+ (`{ "option", "why" }`).
+- Your work belongs to the message that caused it: `work`, `agentDecisions`
+ (`{ "title", "why", "alternatives" }`), `commits` (short hashes), `files` (a few paths).
+ Work spanning messages goes on the one it ended in; update an earlier node only to correct it.
+
+## Parents
+
+Every message grows from an earlier one; a thread that starts something new is a root.
+
+- Default: the previous message. `parent: null` only if it would work as a new chat's first
+ message. Back to an older thread: that message is the parent, the previous one goes in `links`.
+- A first message continuing earlier work: `parent` is `<sessionId>:<stable id>`;
+ `candidates` lists the last messages of the most recent other sessions. The target must be
+ a message of an earlier session of this project.
+- Unsure: use the previous message. A wrong "continue" hides a branch; a wrong branch breaks
+ the chain.
+- `links`: up to 5 earlier messages it builds on besides the parent.
+- Correcting is safe: resend the node with the new parent or links; its id and notes stay,
+ and an unchanged resend writes nothing.
+- Hints, not rules: `gapMinutes`, `resumed`, `commitBetween` (a real commit landed in this
+ repo between them), `lastMessages`, and for a first message `candidates`/`continuesHint`.
+
+## Branch summary
+
+A branch starts at a root or where a message gets a second child. Its first message carries a
+short `branch`: `{ "title", "asked", "outcome", "open" }`. Write it when the branch ends or
+with the status at session end, not every turn. New records send no `phase`, `step`,
+`decision` or `question` nodes; old ones keep rendering, leave them alone.
+
+Write titles and text in the conversation's language (`language: "auto"` means it); JSON keys
+stay English. Record decisions and reasons, never secrets, tokens, passwords, credentials,
+personal data, file contents or command output.
## Write it in two steps
-1. Use the Write tool to save the JSON object to the `inbox` path from the record.
- Do not pass JSON through the shell: heredocs and `echo` with JSON are blocked.
-2. Run exactly this command:
+1. Write the JSON to the `inbox` path with the Write tool (no heredoc or `echo`).
+2. `node "${CLAUDE_PLUGIN_ROOT}/dist/cli.js" session write -C "<dir from the record>" --file "<inbox path>" --consume`
-```bash
-node "${CLAUDE_PLUGIN_ROOT}/dist/cli.js" session write -C "<dir from the record>" --file "<inbox path>" --consume
-```
-
-If it fails, fix the JSON file according to the error and run the command again.
-Then reply with one short line, for example "Lineage updated (3 nodes)". Do not
-repeat the JSON.
+If it fails, fix the JSON according to the error and run it again. Then reply with one short
+line, e.g. "Lineage updated (3 nodes)"; never repeat the JSON.
diff --git a/packages/cli/src/commands/session.ts b/packages/cli/src/commands/session.ts
index fca99e0..8f66f6d 100644
--- a/packages/cli/src/commands/session.ts
+++ b/packages/cli/src/commands/session.ts
@@ -1,7 +1,7 @@
import { readFile, rm } from "node:fs/promises";
import { userInfo } from "node:os";
import { resolve } from "node:path";
-import { findGitRoot, gitUserName } from "../git.js";
+import { commitBetween, findGitRoot, gitUserName } from "../git.js";
import { CliError, type Io } from "../io.js";
import {
hashesToLabels,
@@ -278,8 +278,18 @@ function structureChanges(
* worktree that is the worktree, so writes still learn which worktree they came
* from, while `store` names the main checkout that holds the record. The inbox
* stays under `dir`, where the skill's edit permission points.
+ *
+ * The output is compact by default, because the skill pays for it on every
+ * update: `lastMessages` keeps the last five and `candidates` only appear while
+ * the first message has no node. `--full` (Story 9.5) asks for every recorded
+ * message and the candidates every time.
*/
-export async function sessionShow(dir: string, sessionId: string, io: Io): Promise<void> {
+export async function sessionShow(
+ dir: string,
+ sessionId: string,
+ io: Io,
+ opts: { full?: boolean } = {},
+): Promise<void> {
if (!Slug.safeParse(sessionId).success) throw new CliError(`invalid session id: ${sessionId}`);
const given = resolve(dir);
const { root } = await resolveProjectRoot(given);
@@ -326,17 +336,24 @@ export async function sessionShow(dir: string, sessionId: string, io: Io): Promi
const recorded = recordedIdsOf(effective);
if (messages) {
view.messageCount = messages.length;
- view.newMessages = newMessages(messages, recorded, labels);
- // Only the session's first message can continue an earlier session (8.6).
+ view.newMessages = await newMessages(messages, recorded, labels, root, io.env);
+ // Only the session's first message can continue an earlier session (8.6), so
+ // the expensive other-session scan only runs while that message is unrecorded
+ // (`--full` asks for it every time, for debugging and backfill).
+ const first = messages[0];
const candidates =
- messages.length > 0 && !isRecorded(recorded, messages[0] as SessionMessage)
- ? await parentCandidates(root, sessionId, messages[0] as SessionMessage, io)
+ first !== undefined && (opts.full === true || !isRecorded(recorded, first))
+ ? await parentCandidates(root, sessionId, first, io)
: null;
if (candidates) view.candidates = candidates;
} else {
view.newMessages = null;
}
- view.lastMessages = lastMessages(effective, labels);
+ view.lastMessages = lastMessages(
+ effective,
+ labels,
+ opts.full === true ? Number.POSITIVE_INFINITY : LAST_MESSAGES,
+ );
// A format change would otherwise look like "nothing written yet" forever.
if (messages && messages.length === 0) {
const file = await findTranscript(sessionId, io.env);
@@ -376,32 +393,44 @@ const LAST_MESSAGES = 5;
/**
* The user's messages with no node yet, with the cheap hints the agent uses to
* decide a parent: the gap since the previous message, a `/clear` or resume in
- * between, and a commit this session made between them. Hints, not rules. `id`
- * is the stable id the record keeps; `label` is the `m1` the user reads.
+ * between, and a commit made in this repository between them. Hints, not rules.
+ * `id` is the stable id the record keeps; `label` is the `m1` the user reads.
+ *
+ * `commitBetween` asks git, not the transcript: the transcript only shows that a
+ * `git commit` command ran, which was true even when it failed or committed in
+ * another repository (Story 9.5).
*/
-function newMessages(
+async function newMessages(
messages: SessionMessage[],
recorded: ReadonlySet<string>,
labels: ReadonlyMap<string, string>,
-): Record<string, unknown>[] {
- return messages
- .map((message, i) => {
- const previous = i > 0 ? messages[i - 1] : undefined;
- const gapMinutes = previous
- ? Math.max(0, Math.round((Date.parse(message.at) - Date.parse(previous.at)) / 60_000))
- : undefined;
- return { message, gapMinutes };
- })
- .filter(({ message }) => !isRecorded(recorded, message))
- .map(({ message, gapMinutes }) => ({
+ root: string,
+ env: NodeJS.ProcessEnv,
+): Promise<Record<string, unknown>[]> {
+ const gitRoot = await findGitRoot(root);
+ const out: Record<string, unknown>[] = [];
+ for (const [i, message] of messages.entries()) {
+ if (isRecorded(recorded, message)) continue;
+ const previous = i > 0 ? messages[i - 1] : undefined;
+ const gapMinutes =
+ previous === undefined
+ ? undefined
+ : Math.max(0, Math.round((Date.parse(message.at) - Date.parse(previous.at)) / 60_000));
+ const committed =
+ previous !== undefined &&
+ gitRoot !== undefined &&
+ (await commitBetween(gitRoot, previous.at, message.at, env));
+ out.push({
id: message.hash,
label: labels.get(message.hash) ?? message.label,
at: message.at,
text: excerpt(message.text),
...(gapMinutes === undefined ? {} : { gapMinutes }),
...(message.resumed ? { resumed: true } : {}),
- ...(message.commitBetween ? { commitBetween: true } : {}),
- }));
+ ...(committed ? { commitBetween: true } : {}),
+ });
+ }
+ return out;
}
/** How many earlier sessions and messages `session show` offers for a parent. */
@@ -480,6 +509,7 @@ async function parentCandidates(
function lastMessages(
session: Session | null,
labels: ReadonlyMap<string, string>,
+ limit: number,
): { id: string; label?: string; title: string; parent: string | null }[] {
if (!session) return [];
/** Send-order position from the label; a node without one keeps its stored place. */
@@ -490,7 +520,7 @@ function lastMessages(
const messages = session.nodes
.filter((n) => n.kind === "message")
.sort((a, b) => position(a.id) - position(b.id))
- .slice(-LAST_MESSAGES);
+ .slice(-limit);
return messages.map(({ id, title, parent }) => {
const label = labels.get(id);
return { id, ...(label === undefined ? {} : { label }), title, parent };
diff --git a/packages/cli/src/git.ts b/packages/cli/src/git.ts
index 1f12d0c..5a033f1 100644
--- a/packages/cli/src/git.ts
+++ b/packages/cli/src/git.ts
@@ -340,6 +340,31 @@ export async function gitUserName(
}
}
+/**
+ * True when this repository has a commit made between two moments (Story 9.5).
+ * The transcript only shows that a `git commit` command ran; this asks git
+ * whether one actually landed here, so a failed or other-repository commit is
+ * not a hint. A missing git, an uninitialized repository or bad dates are all
+ * "no commit": a hint must never fail the command it decorates.
+ */
+export async function commitBetween(
+ root: string,
+ from: string,
+ to: string,
+ env: NodeJS.ProcessEnv = process.env,
+): Promise<boolean> {
+ try {
+ const { stdout } = await exec(
+ "git",
+ ["-C", root, "log", "--max-count=1", "--format=%H", `--since=${from}`, `--until=${to}`],
+ { env },
+ );
+ return stdout.trim() !== "";
+ } catch {
+ return false;
+ }
+}
+
/** The hooks directory git really uses here: `core.hooksPath`, Husky and worktrees included. */
export async function gitHooksDir(root: string): Promise<string | undefined> {
try {
diff --git a/packages/cli/src/program.ts b/packages/cli/src/program.ts
index ef20545..aa02ca6 100644
--- a/packages/cli/src/program.ts
+++ b/packages/cli/src/program.ts
@@ -108,10 +108,11 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =
.command("blame")
.description("show which recorded messages produced the code in a file or line")
.argument("<target>", "file, or file:line")
- .option("-C, --dir <dir>", "project directory", ".")
+ .argument("[dir]", "project directory", ".")
+ .option("-C, --dir <dir>", "project directory (same as the positional)")
.action(
- run(async (target: string, opts: { dir: string }) => {
- await blame({ dir: opts.dir, target, io: makeIo(false) });
+ run(async (target: string, dir: string, opts: { dir?: string }) => {
+ await blame({ dir: opts.dir ?? dir, target, io: makeIo(false) });
}),
);
@@ -357,8 +358,11 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =
.description("print the compact record the agent skill updates, as JSON")
.argument("<id>", "session id")
.option("-C, --dir <dir>", "project directory", ".")
+ .option("--full", "print every recorded message and the parent candidates")
.action(
- run(async (id: string, opts: { dir: string }) => sessionShow(opts.dir, id, makeIo(false))),
+ run(async (id: string, opts: { dir: string; full?: boolean }) =>
+ sessionShow(opts.dir, id, makeIo(false), { full: opts.full === true }),
+ ),
);
// Started detached by the SessionEnd hook when `recordCommit` is `auto`.
diff --git a/packages/cli/src/server.ts b/packages/cli/src/server.ts
index 1b92a4c..03a180a 100644
--- a/packages/cli/src/server.ts
+++ b/packages/cli/src/server.ts
@@ -8,7 +8,7 @@ import {
type ServerResponse,
} from "node:http";
import type { AddressInfo } from "node:net";
-import { basename, resolve } from "node:path";
+import { basename, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
import { buildProject } from "./commands/build.js";
import { defaultsPrompter, type Io } from "./io.js";
@@ -20,6 +20,7 @@ import { loadConfig, loadRegistry, updateConfig } from "./store/stores.js";
import { isPanelEditableKey, LIVE_META_NAME, TOKEN_META_NAME } from "./view/model.js";
import { buildPanel, panelSettings } from "./view/panel.js";
import { editableSettings } from "./view/settings.js";
+import { claudeConfigDir } from "./view/transcripts.js";
/** A page nobody is looking at is a dead server after this long. */
export const DEFAULT_IDLE_MS = 30 * 60 * 1000;
@@ -64,6 +65,8 @@ export interface MapServerOptions {
hostname?: string;
/** Exit after this long without a connected page (tests use a short one). */
idleMs?: number;
+ /** Quiet time after the last transcript write before a map rebuild (tests use a short one). */
+ transcriptDebounceMs?: number;
}
export interface MapServer {
@@ -81,12 +84,16 @@ interface PageTarget {
file: string;
/** Directory to watch: atomic writes replace the file, the directory keeps its name. */
dir: string;
+ /** The registered project the map belongs to; absent for the panel. */
+ root?: string;
}
interface WatchedPage {
watcher?: FSWatcher;
clients: Set<ServerResponse>;
timer: NodeJS.Timeout | null;
+ /** The project to rebuild while this page has a transcript write (Story 9.5). */
+ root?: string;
}
function hostAllowed(host: string | undefined, port: number): boolean {
@@ -127,7 +134,7 @@ async function pageTarget(env: NodeJS.ProcessEnv, url: URL): Promise<PageTarget
const root = await registeredRoot(env, raw);
if (!root) return null;
const paths = projectPaths(root);
- return { file: paths.html, dir: paths.base };
+ return { file: paths.html, dir: paths.base, root };
}
return null;
}
@@ -147,7 +154,21 @@ export async function startMapServer(opts: MapServerOptions): Promise<MapServer>
const env = opts.env ?? process.env;
const hostname = opts.hostname ?? HOST;
const idleMs = opts.idleMs ?? DEFAULT_IDLE_MS;
+ const transcriptDebounceMs = opts.transcriptDebounceMs ?? 1000;
const pages = new Map<string, WatchedPage>();
+ /** A quiet build IO: rebuilds a page without printing to a terminal nobody watches. */
+ const buildIo: Io = {
+ prompt: defaultsPrompter,
+ out: () => {},
+ warn: () => {},
+ env,
+ now: () => new Date().toISOString(),
+ };
+ /** Watches Claude Code's transcripts while somebody has a map open (9.5). */
+ let transcriptWatcher: FSWatcher | undefined;
+ let transcriptTimer: NodeJS.Timeout | null = null;
+ /** Rebuilds run one after another, so a write during a build is never dropped. */
+ let rebuildQueue: Promise<void> = Promise.resolve();
/** One random token per server start; the panel page carries it into a write. */
const token = randomBytes(24).toString("hex");
let openPages = 0;
@@ -178,10 +199,14 @@ export async function startMapServer(opts: MapServerOptions): Promise<MapServer>
}
}
- function watched(file: string, dir: string): WatchedPage {
+ function watched(file: string, dir: string, root?: string): WatchedPage {
const existing = pages.get(file);
if (existing) return existing;
- const page: WatchedPage = { clients: new Set(), timer: null };
+ const page: WatchedPage = {
+ clients: new Set(),
+ timer: null,
+ ...(root === undefined ? {} : { root }),
+ };
try {
page.watcher = watch(dir, { persistent: false }, (_event, name) => {
// A null name means "something in here changed" on some platforms.
@@ -207,6 +232,66 @@ export async function startMapServer(opts: MapServerOptions): Promise<MapServer>
pages.delete(file);
}
+ /**
+ * Rebuilds every map somebody is looking at, from the records and the
+ * transcripts. The write itself reaches the page through the page watcher; a
+ * failing project is skipped so one broken record never stops the others.
+ */
+ async function rebuildOpenMaps(): Promise<void> {
+ const roots = new Set<string>();
+ for (const page of pages.values()) {
+ if (page.root !== undefined && page.clients.size > 0) roots.add(page.root);
+ }
+ for (const root of roots) {
+ try {
+ await buildProject({ dir: root, io: buildIo, quiet: true });
+ } catch {
+ // Already a warning where the project is read; keep the page up.
+ }
+ }
+ }
+
+ /** Queues a rebuild behind any running one; the debounce already collapsed the burst. */
+ function queueRebuild(): void {
+ rebuildQueue = rebuildQueue.then(() => rebuildOpenMaps());
+ }
+
+ /**
+ * Follows Claude Code's transcripts while a map page is open (Story 9.5), so
+ * the map is live without the plugin's Stop hook. One recursive watcher over
+ * the Claude projects directory covers every registered project, and a turn's
+ * many writes collapse into one debounced rebuild. No page, no watch.
+ */
+ function startTranscriptWatch(): void {
+ if (transcriptWatcher !== undefined) return;
+ const dir = join(claudeConfigDir(env), "projects");
+ try {
+ transcriptWatcher = watch(dir, { persistent: false, recursive: true }, (_event, name) => {
+ if (name === null || !name.toString().endsWith(".jsonl")) return;
+ if (transcriptTimer !== null) clearTimeout(transcriptTimer);
+ transcriptTimer = setTimeout(() => {
+ transcriptTimer = null;
+ queueRebuild();
+ }, transcriptDebounceMs);
+ });
+ } catch {
+ // No Claude home (or no recursive watch here): the Stop hook still rebuilds.
+ transcriptWatcher = undefined;
+ }
+ }
+
+ function stopTranscriptWatch(): void {
+ transcriptWatcher?.close();
+ transcriptWatcher = undefined;
+ if (transcriptTimer !== null) clearTimeout(transcriptTimer);
+ transcriptTimer = null;
+ }
+
+ /** Whether any project map (not just the panel) still has a viewer. */
+ function mapPagesOpen(): boolean {
+ return [...pages.values()].some((page) => page.root !== undefined && page.clients.size > 0);
+ }
+
const server = createHttpServer((req, res) => {
// A broken registry or an unexpected error must not take the server down.
void handle(req, res).catch(() => respond(res, 500, "internal error"));
@@ -254,13 +339,6 @@ export async function startMapServer(opts: MapServerOptions): Promise<MapServer>
* write already landed, so a failed rebuild must not fail the request.
*/
async function refreshOpenPages(): Promise<void> {
- const io: Io = {
- prompt: defaultsPrompter,
- out: () => {},
- warn: () => {},
- env,
- now: () => new Date().toISOString(),
- };
let rebuiltMap = false;
const registry = await loadRegistry(env);
if (registry.found && registry.ok) {
@@ -268,7 +346,7 @@ export async function startMapServer(opts: MapServerOptions): Promise<MapServer>
const page = pages.get(projectPaths(entry.path).html);
if (!page || page.clients.size === 0) continue;
try {
- await buildProject({ dir: entry.path, io, quiet: true });
+ await buildProject({ dir: entry.path, io: buildIo, quiet: true });
rebuiltMap = true;
} catch {
// A broken project is already a warning elsewhere; keep serving.
@@ -278,7 +356,7 @@ export async function startMapServer(opts: MapServerOptions): Promise<MapServer>
if (rebuiltMap) return;
try {
// `buildProject` rebuilds the panel too; without an open map, do it here.
- await buildPanel({ env, io });
+ await buildPanel({ env, io: buildIo });
} catch {
// An unwritable global directory leaves the old page in place.
}
@@ -432,15 +510,18 @@ export async function startMapServer(opts: MapServerOptions): Promise<MapServer>
connection: "keep-alive",
});
res.write("retry: 1000\n\n");
- const page = watched(target.file, target.dir);
+ const page = watched(target.file, target.dir, target.root);
page.clients.add(res);
res.on("error", () => page.clients.delete(res));
openPages += 1;
clearIdle();
+ // The panel does not need the transcripts; a map page does (Story 9.5).
+ if (target.root !== undefined) startTranscriptWatch();
req.on("close", () => {
page.clients.delete(res);
release(target.file, page);
openPages = Math.max(0, openPages - 1);
+ if (!mapPagesOpen()) stopTranscriptWatch();
if (openPages === 0) scheduleIdle(idleMs);
});
return;
@@ -476,6 +557,7 @@ export async function startMapServer(opts: MapServerOptions): Promise<MapServer>
if (closing) return closing;
closing = (async () => {
clearIdle();
+ stopTranscriptWatch();
for (const page of pages.values()) {
page.watcher?.close();
if (page.timer !== null) clearTimeout(page.timer);
diff --git a/packages/cli/src/transcript.ts b/packages/cli/src/transcript.ts
index e26da48..2df5f4a 100644
--- a/packages/cli/src/transcript.ts
+++ b/packages/cli/src/transcript.ts
@@ -13,8 +13,6 @@ export interface UserMessage {
text: string;
/** A `/clear`, a resume or a new process came between this message and the previous one. */
resumed?: boolean;
- /** The agent ran `git commit` between the previous message and this one. */
- commitBetween?: boolean;
}
/**
@@ -145,12 +143,6 @@ export function displayTurn(turn: ChatTurn, roots: string[]): ChatTurn {
const EDIT_TOOLS = new Set(["Edit", "Write", "MultiEdit", "NotebookEdit"]);
-/**
- * `git commit`, also behind options like `-C dir`. A hint, not a decision: a
- * command that merely mentions a commit (`git log --grep commit`) may match.
- */
-const GIT_COMMIT = /(?:^|[\s;&|])git(?:\s+[^\s;&|]+)*\s+commit\b/;
-
/** A `/clear` written by the user or by the CLI as a local command. */
const CLEAR = /<command-name>\s*\/clear\s*<\/command-name>/;
@@ -186,7 +178,6 @@ export async function readConversation(file: string): Promise<ChatTurn[]> {
/** Uuids already read, to notice a chain that starts again (a resumed process). */
const seen = new Set<string>();
let pendingResume = false;
- let pendingCommit = false;
const lines = createInterface({ input: createReadStream(file, "utf8"), crlfDelay: Infinity });
for await (const raw of lines) {
// A /clear line is a local command, not a message, but it breaks the thread.
@@ -218,7 +209,6 @@ export async function readConversation(file: string): Promise<ChatTurn[]> {
const current = turns.at(-1);
if (line.type === "assistant") {
if (current) addAssistant(current, line);
- if (current && hasCommit(line)) pendingCommit = true;
continue;
}
const text = messageText(line);
@@ -232,28 +222,12 @@ export async function readConversation(file: string): Promise<ChatTurn[]> {
replies: [],
tools: { commands: 0, files: [], other: 0 },
...(!first && pendingResume ? { resumed: true } : {}),
- ...(!first && pendingCommit ? { commitBetween: true } : {}),
});
pendingResume = false;
- pendingCommit = false;
}
return turns;
}
-/** Whether an assistant line ran a `git commit`. */
-function hasCommit(line: Record<string, unknown>): boolean {
- if (line.isSidechain) return false;
- const content = (line.message as { content?: unknown } | undefined)?.content;
- if (!Array.isArray(content)) return false;
- return content.some(
- (block) =>
- block?.type === "tool_use" &&
- block.name === "Bash" &&
- typeof block.input?.command === "string" &&
- GIT_COMMIT.test(block.input.command),
- );
-}
-
/**
* Whether the transcript shows the agent reading a handoff file (Story 8.6): a
* cheap hint that this session continues earlier work. A tool-use line names the
@@ -272,12 +246,11 @@ export async function readsHandoff(file: string): Promise<boolean> {
/** Reads the user's messages from a transcript, in order. */
export async function readUserMessages(file: string): Promise<UserMessage[]> {
- return (await readConversation(file)).map(({ id, at, text, resumed, commitBetween }) => ({
+ return (await readConversation(file)).map(({ id, at, text, resumed }) => ({
id,
at,
text,
...(resumed ? { resumed: true } : {}),
- ...(commitBetween ? { commitBetween: true } : {}),
}));
}
diff --git a/packages/cli/src/view/lineage.ts b/packages/cli/src/view/lineage.ts
index 3e3ca3d..6dde98a 100644
--- a/packages/cli/src/view/lineage.ts
+++ b/packages/cli/src/view/lineage.ts
@@ -147,6 +147,36 @@ function byUpdatedAt(a: Session, b: Session): number {
return timestamp(b.updatedAt) - timestamp(a.updatedAt) || a.sessionId.localeCompare(b.sessionId);
}
+/** The timestamp the session was last active at, and that value as stored. */
+interface Activity {
+ value: string;
+ time: number;
+}
+
+/**
+ * Activity is message time, not record time (Story 9.5): fixing an old record
+ * touches its `updatedAt`, which must not make the session look like it ran
+ * until now. A session with no timed message falls back to `updatedAt`.
+ */
+function lastActivityOf(session: Session): Activity {
+ let value = session.updatedAt;
+ let time = Number.NEGATIVE_INFINITY;
+ for (const node of session.nodes) {
+ if (node.kind !== "message" || node.at === undefined) continue;
+ const at = timestamp(node.at);
+ if (at > time) {
+ time = at;
+ value = node.at;
+ }
+ }
+ return { value, time: time === Number.NEGATIVE_INFINITY ? timestamp(value) : time };
+}
+
+/** When the session was last active; the newest message's time, else `updatedAt`. */
+export function lastActive(session: Session): number {
+ return lastActivityOf(session).time;
+}
+
function hasStatus(session: Session): boolean {
const { goal, done, pending, next } = session.status;
return goal !== "" || next !== "" || done.length > 0 || pending.length > 0;
@@ -157,12 +187,11 @@ function hasStatus(session: Session): boolean {
* updated session that recorded a status, so a newer session without one does not
* blank the card; `needsUser` items are merged from every other session active
* within `ACTIVE_WINDOW_DAYS`, newest first and deduplicated by text. Last
- * activity is the newest session overall. `now` is the build time the window is
- * measured against.
+ * activity is the newest message time across every session (Story 9.5), not the
+ * newest `updatedAt`. `now` is the build time the window is measured against.
*/
export function statusCard(sessions: Session[], now: string): StatusCard {
const ordered = [...sessions].sort(byUpdatedAt);
- const newest = ordered[0];
const latest = ordered.find(hasStatus);
const pending = (latest?.status.pending ?? []).map((item) => ({ ...item }));
@@ -177,12 +206,19 @@ export function statusCard(sessions: Session[], now: string): StatusCard {
}
}
+ const activity = ordered
+ .map(lastActivityOf)
+ .reduce<Activity | null>(
+ (best, current) => (best === null || current.time > best.time ? current : best),
+ null,
+ );
+
return {
goal: latest?.status.goal ?? "",
done: latest?.status.done ?? [],
pending,
next: latest?.status.next ?? "",
- lastActivity: newest?.updatedAt ?? null,
+ lastActivity: activity?.value ?? null,
};
}
diff --git a/packages/cli/src/view/model.ts b/packages/cli/src/view/model.ts
index eec7e1e..73d967a 100644
--- a/packages/cli/src/view/model.ts
+++ b/packages/cli/src/view/model.ts
@@ -133,7 +133,7 @@ export interface ViewStatus {
/** Status card at the top of the map (merged across sessions). */
export interface StatusCard extends ViewStatus {
- /** `updatedAt` of the most recently updated session, or null with no sessions. */
+ /** Time of the newest message across sessions, or null with no sessions. */
lastActivity: string | null;
}
@@ -209,7 +209,7 @@ export interface ViewEpoch {
export interface ViewSwitcherProject {
name: string;
path: string;
- /** `updatedAt` of the project's most recently updated session. */
+ /** Time of the project's newest message across its sessions. */
lastActivity: string | null;
/** The newest session's `next`, or its last message title when `next` is empty. */
leftOff: string;
diff --git a/packages/cli/src/view/panel.ts b/packages/cli/src/view/panel.ts
index 436f6ec..7dcc355 100644
--- a/packages/cli/src/view/panel.ts
+++ b/packages/cli/src/view/panel.ts
@@ -6,7 +6,7 @@ import type { Session } from "../schema/session.js";
import { atomicWrite, isDirectory } from "../store/fs.js";
import { globalPaths, projectPaths } from "../store/paths.js";
import { loadAllSessions, loadConfig, loadRegistry } from "../store/stores.js";
-import { embedViewModel, statusCard } from "./lineage.js";
+import { embedViewModel, lastActive, statusCard } from "./lineage.js";
import { type PanelSettings, type PanelViewModel, VIEW_SCHEMA } from "./model.js";
import type { SwitcherSource } from "./switcher.js";
import { TEMPLATE_HTML } from "./template.js";
@@ -60,19 +60,6 @@ function lastMessageTitle(session: Session): string {
return messages[messages.length - 1]?.title ?? "";
}
-/** When the session's newest message was sent; its `updatedAt` when no message has a time. */
-function lastActive(session: Session): number {
- let last = Number.NEGATIVE_INFINITY;
- for (const node of session.nodes) {
- if (node.kind !== "message" || node.at === undefined) continue;
- const at = Date.parse(node.at);
- if (!Number.isNaN(at) && at > last) last = at;
- }
- if (last !== Number.NEGATIVE_INFINITY) return last;
- const updated = Date.parse(session.updatedAt);
- return Number.isNaN(updated) ? Number.NEGATIVE_INFINITY : updated;
-}
-
/**
* Where the work left off: the `next` step of the session with the newest
* message (not the most recently updated record — fixing an old record must
diff --git a/packages/cli/test/blame.test.ts b/packages/cli/test/blame.test.ts
index e07160c..850255a 100644
--- a/packages/cli/test/blame.test.ts
+++ b/packages/cli/test/blame.test.ts
@@ -106,6 +106,12 @@ describe("cogit blame", () => {
expect(io.lines[0]).toContain("Parse the file");
});
+ it("takes the project directory as a positional, like log and show (9.5)", async () => {
+ const program = createProgram(() => io);
+ await program.parseAsync(["blame", "a.txt:1", root], { from: "user" });
+ expect(io.lines[0]).toContain("Parse the file");
+ });
+
it("accepts a file without a line and searches every commit that touched it", async () => {
const hits = await blame({ dir: root, target: "a.txt", io });
expect(hits.map((hit) => hit.title)).toEqual(["Parse the file"]);
diff --git a/packages/cli/test/build.test.ts b/packages/cli/test/build.test.ts
index a114410..391ca41 100644
--- a/packages/cli/test/build.test.ts
+++ b/packages/cli/test/build.test.ts
@@ -360,6 +360,23 @@ describe("statusCard", () => {
expect(statusCard(sessions, "also-broken").pending).toEqual([]);
});
+ it("takes last activity from the newest message, not an edited record's updatedAt", () => {
+ const sessions = [
+ // The old record was edited after this session ran; its messages are old.
+ session({
+ sessionId: "edited-old",
+ updatedAt: "2026-10-21T00:00:00.000Z",
+ nodes: [node("h1", "message", "Old", null, { at: "2026-09-01T00:00:00.000Z" })],
+ }),
+ session({
+ sessionId: "current",
+ updatedAt: "2026-10-19T00:00:00.000Z",
+ nodes: [node("h1", "message", "New", null, { at: "2026-10-20T00:00:00.000Z" })],
+ }),
+ ];
+ expect(statusCard(sessions, NOW).lastActivity).toBe("2026-10-20T00:00:00.000Z");
+ });
+
it("skips a newer session without a status but keeps its time as last activity", () => {
const sessions = [
session({
diff --git a/packages/cli/test/program-commands.test.ts b/packages/cli/test/program-commands.test.ts
index de09062..c28ef5a 100644
--- a/packages/cli/test/program-commands.test.ts
+++ b/packages/cli/test/program-commands.test.ts
@@ -120,10 +120,12 @@ describe("commands through the CLI", () => {
);
});
- it("runs session show for the skill", async () => {
+ it("runs session show for the skill, with --full for the long output", async () => {
await cli("init", root, "--yes", "--retention", "keep");
await cli("session", "show", "s1", "-C", root);
expect(JSON.parse(io.lines.at(-1) ?? "")).toMatchObject({ initialized: true, session: null });
+ await cli("session", "show", "s1", "--full", "-C", root);
+ expect(JSON.parse(io.lines.at(-1) ?? "")).toMatchObject({ initialized: true, session: null });
});
it("runs a hook from stdin and prints its output", async () => {
diff --git a/packages/cli/test/server.test.ts b/packages/cli/test/server.test.ts
index 48c1ff5..5b8fd59 100644
--- a/packages/cli/test/server.test.ts
+++ b/packages/cli/test/server.test.ts
@@ -49,8 +49,13 @@ afterEach(async () => {
await Promise.all(servers.splice(0).map((server) => server.close()));
});
-async function start(idleMs = 5000): Promise<MapServer> {
- const server = await startMapServer({ env, port: 0, idleMs });
+async function start(idleMs = 5000, transcriptDebounceMs?: number): Promise<MapServer> {
+ const server = await startMapServer({
+ env,
+ port: 0,
+ idleMs,
+ ...(transcriptDebounceMs === undefined ? {} : { transcriptDebounceMs }),
+ });
servers.push(server);
return server;
}
@@ -290,6 +295,29 @@ describe("map server", () => {
}
});
+ it("rebuilds an open map when Claude Code writes a transcript (9.5)", async () => {
+ const folder = join(env.CLAUDE_CONFIG_DIR as string, "projects", "-proj");
+ await mkdir(folder, { recursive: true });
+ const server = await start(5000, 20);
+ const events = openEvents(`${server.url}/events?dir=${encodeURIComponent(root)}`);
+ try {
+ expect(await events.waitFor("retry: 1000")).toBe(true);
+ // The write is in the Claude home, not in `.cogit/`, so only the new
+ // transcript watch can produce the rebuild that reaches the page.
+ await writeFile(
+ join(folder, "s1.jsonl"),
+ `${JSON.stringify({
+ type: "user",
+ timestamp: "2026-10-24T10:00:00.000Z",
+ message: { role: "user", content: "hello" },
+ })}\n`,
+ );
+ expect(await events.waitFor("event: change")).toBe(true);
+ } finally {
+ events.close();
+ }
+ });
+
it("exits by itself when no page is connected", async () => {
const server = await start(120);
await server.closed;
diff --git a/packages/cli/test/session-git.test.ts b/packages/cli/test/session-git.test.ts
index 78dd832..378afea 100644
--- a/packages/cli/test/session-git.test.ts
+++ b/packages/cli/test/session-git.test.ts
@@ -6,7 +6,12 @@ import { promisify } from "node:util";
import { beforeEach, describe, expect, it } from "vitest";
import { configGit, configSet } from "../src/commands/config.js";
import { sessionAuthor, sessionWrite } from "../src/commands/session.js";
-import { cogitGitignore, ensureGitignore, refreshCogitGitignore } from "../src/git.js";
+import {
+ cogitGitignore,
+ commitBetween,
+ ensureGitignore,
+ refreshCogitGitignore,
+} from "../src/git.js";
import { hookBlock, installGitHook, withHookBlock } from "../src/git-hooks.js";
import { runHook } from "../src/hooks/run.js";
import type { Session } from "../src/schema/session.js";
@@ -77,6 +82,10 @@ describe("the record travels with the repo (Story 9.3)", () => {
await git("commit", "-q", "-m", "feat: base");
});
+ it("treats a missing repository as no commit between two messages (9.5)", async () => {
+ await expect(commitBetween(join(dir, "not-a-repo"), T0, T0)).resolves.toBe(false);
+ });
+
it("parses and rejects the session HEAD", async () => {
expect(await readSessionHead(root)).toBeUndefined();
await makeProject();
diff --git a/packages/cli/test/session.test.ts b/packages/cli/test/session.test.ts
index 73d67bd..12fa33b 100644
--- a/packages/cli/test/session.test.ts
+++ b/packages/cli/test/session.test.ts
@@ -1,7 +1,9 @@
+import { execFile } from "node:child_process";
import { existsSync } from "node:fs";
import { mkdir, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { Readable } from "node:stream";
+import { promisify } from "node:util";
import { beforeEach, describe, expect, it } from "vitest";
import { configSet } from "../src/commands/config.js";
import { epochAdd } from "../src/commands/epoch.js";
@@ -12,6 +14,8 @@ import { redactDeep, redactText } from "../src/redact.js";
import { loadSession } from "../src/store/stores.js";
import { envFor, type FakeIo, fakeIo, T0, tempDir } from "./helpers.js";
+const run = promisify(execFile);
+
describe("redactText", () => {
it.each([
["key sk-ant-api03-abcdefghijklmnopqrstuvwxyz0123", "key [REDACTED]"],
@@ -352,10 +356,33 @@ ${line("second", 2)}
]);
});
- it("hints the gap, a /clear and this session's commits for each new message", async () => {
+ it("hints the gap, a /clear and a real commit between two messages", async () => {
await init(root, { name: "p", retention: "keep", language: "auto" }, fakeIo(envFor(dir)));
const folder = join(dir, "claude", "projects", "-p");
await mkdir(folder, { recursive: true });
+ // The hint asks git, not the transcript (Story 9.5): a commit that only
+ // mentions `git commit` (or one that failed) is not a commit.
+ const git = async (at: string, ...args: string[]) =>
+ run("git", ["-C", root, ...args], {
+ env: {
+ ...process.env,
+ HOME: dir,
+ GIT_AUTHOR_DATE: at,
+ GIT_COMMITTER_DATE: at,
+ },
+ });
+ await git("2026-10-23T09:00:00.000Z", "init", "-q");
+ await git("2026-10-23T09:00:00.000Z", "config", "user.email", "[email protected]");
+ await git("2026-10-23T09:00:00.000Z", "config", "user.name", "T");
+ await writeFile(join(root, "note.txt"), "x\n");
+ await git("2026-10-23T09:00:00.000Z", "add", "note.txt");
+ await git("2026-10-23T09:00:00.000Z", "commit", "-q", "-m", "chore: initial");
+ // One commit lands between the second and third message, none between the
+ // first and second — although the transcript shows a `git commit` there.
+ await writeFile(join(root, "note.txt"), "y\n");
+ await git("2026-10-23T10:45:00.000Z", "add", "note.txt");
+ await git("2026-10-23T10:45:00.000Z", "commit", "-q", "-m", "feat: between");
+
const user = (text: string, at: string) =>
JSON.stringify({
type: "user",
@@ -396,7 +423,6 @@ ${line("second", 2)}
at: "2026-10-23T10:30:00.000Z",
text: "second",
gapMinutes: 30,
- commitBetween: true,
},
{
id: hash("2026-10-23T11:00:00.000Z", "third"),
@@ -405,10 +431,53 @@ ${line("second", 2)}
text: "third",
gapMinutes: 30,
resumed: true,
+ commitBetween: true,
},
]);
});
+ it("is compact by default and prints everything with --full", async () => {
+ await init(root, { name: "p", retention: "keep", language: "auto" }, fakeIo(envFor(dir)));
+ // An earlier session to hang the first message from, so `candidates` has content.
+ await sessionWrite({ dir: root }, fakeIo(envFor(dir)), async () =>
+ JSON.stringify({
+ sessionId: "s1",
+ title: "Earlier",
+ nodes: [{ id: "m1", kind: "message", title: "Earlier message" }],
+ }),
+ );
+ const folder = join(dir, "claude", "projects", "-p");
+ await mkdir(folder, { recursive: true });
+ const lines = Array.from({ length: 7 }, (_, i) =>
+ JSON.stringify({
+ type: "user",
+ timestamp: `2026-10-23T10:0${i + 1}:00.000Z`,
+ message: { role: "user", content: `message ${i + 1}` },
+ }),
+ );
+ await writeFile(join(folder, "s2.jsonl"), `${lines.join("\n")}\n`);
+ await sessionWrite({ dir: root }, fakeIo(envFor(dir)), async () =>
+ JSON.stringify({
+ sessionId: "s2",
+ title: "Long session",
+ nodes: Array.from({ length: 7 }, (_, i) => ({
+ id: `m${i + 1}`,
+ kind: "message",
+ title: `Message ${i + 1}`,
+ })),
+ }),
+ );
+
+ await sessionShow(root, "s2", io);
+ expect(shown().lastMessages).toHaveLength(5);
+ expect(shown()).not.toHaveProperty("candidates");
+
+ io.lines.length = 0;
+ await sessionShow(root, "s2", io, { full: true });
+ expect(shown().lastMessages).toHaveLength(7);
+ expect(shown().candidates).toMatchObject({ forMessage: { label: "m1" } });
+ });
+
it("treats an unreadable transcript as none and warns about a message id it cannot use", async () => {
await init(root, { name: "p", retention: "keep", language: "auto" }, fakeIo(envFor(dir)));
// A directory where the transcript should be: found, but reading it fails.
diff --git a/packages/template/src/sessionLayout.ts b/packages/template/src/sessionLayout.ts
index b9af99e..04580f3 100644
--- a/packages/template/src/sessionLayout.ts
+++ b/packages/template/src/sessionLayout.ts
@@ -19,6 +19,25 @@ function time(value: string | undefined): number {
return Number.isNaN(at) ? Number.NEGATIVE_INFINITY : at;
}
+/**
+ * When the session was last active: its newest message's time, not the record's
+ * `updatedAt` (Story 9.5). Editing an old record must not stretch its lane, and
+ * so its parallel with the sessions that ran alongside it, to now.
+ */
+export function lastMessageTime(session: ViewSession): string {
+ let latest: string | undefined;
+ let at = Number.NEGATIVE_INFINITY;
+ for (const message of session.messages) {
+ if (message.at === undefined) continue;
+ const sent = time(message.at);
+ if (sent > at) {
+ at = sent;
+ latest = message.at;
+ }
+ }
+ return latest ?? session.updatedAt;
+}
+
/** The session a session hangs from: the one its first message continues. */
export function sessionParentOf(session: ViewSession, known: ReadonlySet<string>): string | null {
const other = session.messages[0]?.continues?.sessionId;
@@ -64,7 +83,7 @@ export function layoutSessionGraph(
id: session.sessionId,
title: session.title || session.sessionId,
at: session.startedAt,
- until: session.updatedAt,
+ until: lastMessageTime(session),
parent,
};
});
diff --git a/packages/template/test/sessionLayout.test.ts b/packages/template/test/sessionLayout.test.ts
index be073e6..2ce0ca3 100644
--- a/packages/template/test/sessionLayout.test.ts
+++ b/packages/template/test/sessionLayout.test.ts
@@ -7,12 +7,12 @@ function at(minutes: number): string {
return new Date(Date.UTC(2026, 9, 24, 10, minutes)).toISOString();
}
-function message(id: string, continues?: ViewNode["continues"]): ViewNode {
+function message(id: string, minutes: number, continues?: ViewNode["continues"]): ViewNode {
return {
id,
kind: "message",
title: id,
- at: at(0),
+ at: at(minutes),
...(continues ? { parent: null, continues } : {}),
};
}
@@ -34,6 +34,7 @@ function session(
messages: [
message(
"h1",
+ updatedAt,
continues
? {
sessionId: continues.sessionId,
@@ -120,6 +121,18 @@ describe("layoutSessionGraph", () => {
expect(graph.git.rows.every((row) => row.kind === "message")).toBe(true);
});
+ it("ends a lane at its newest message, not at an edited record's updatedAt", () => {
+ // a's record was touched at minute 200, but its only message was sent at 10.
+ const edited: ViewSession = {
+ ...session("a", 0, 200),
+ messages: [message("h1", 10)],
+ };
+ const graph = layoutSessionGraph(modelOf([edited, session("b", 30, 60)]));
+ // b started while a was still running only if the lane ran to 200; with the
+ // message time the lane ends at 10 and b reuses it.
+ expect(graph.git.segments.map((segment) => segment.lane)).toEqual([0, 0]);
+ });
+
it("marks the most recently updated session as HEAD", () => {
const graph = layoutSessionGraph(modelOf([session("a", 0, 200), session("b", 60, 90)]));
expect(graph.git.headId).toBe("a");