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(search): find the lineage from the CLI and the map (Ctrl+F)

Erenaf568f9def79
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f76f1ff..ded75c1 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,6 +6,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
+- Lineage search: `codelineage search <text> [dir]` scans message titles, notes and decisions, branch summaries, session titles and status, and the stored conversation (never tool output) with a case- and accent-insensitive matcher that folds Turkish letters both ways (`I`, `İ` and `ı` all match; `ş`, `ğ`, `ç`, `ö`, `ü` match their plain forms). Each hit prints its short hash, `mN`, time, session, where it matched (title / branch / conversation / session) and a one-line excerpt, newest first; `-n <count>`, `--session <id|prefix>` and `--json` are there too. The map gets a search box in the page head: Ctrl/Cmd+F focuses it (a second press opens the browser's own find), matching messages are highlighted and their sessions open, a `3 / 12` counter with ↑/↓ (Enter / Shift+Enter) steps through the hits, Esc clears, and pasting a message hash (or a unique `h…` prefix) jumps to it like `show`. The session-start context and the lineage skill now point at `search` for "where did we discuss…".
- Settings modal on every page: a ⚙ Settings button in the top bar of both the project map and the panel opens the same dialog (close with ×, Esc or a click outside; focus moves into the dialog and back to the button), with one help line per setting and a "Saved" line per change. The panel's old settings box at the bottom is gone. The dialog reads the current values with `GET /api/config` (same Host / Origin / token checks as the write, and only the editable keys), and the local server now puts its per-start token in map pages too, so a map built before a change still shows the current value; over `file://` it shows the values embedded at build time read-only with a hint to use `codelineage open` or `codelineage config set`.
### Changed
diff --git a/packages/cli/skills/lineage/SKILL.md b/packages/cli/skills/lineage/SKILL.md
index 1f74dd6..34daec7 100644
--- a/packages/cli/skills/lineage/SKILL.md
+++ b/packages/cli/skills/lineage/SKILL.md
@@ -19,6 +19,16 @@ This is the current record for this session (the output of `codelineage session
- If `newMessages` is empty and nothing else changed since the record was last
updated, reply "Lineage is up to date." and stop.
+## Looking 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`.
+
## Then send only what is new or changed
Build one JSON object:
diff --git a/packages/cli/src/commands/log.ts b/packages/cli/src/commands/log.ts
index cfed2fe..6fad674 100644
--- a/packages/cli/src/commands/log.ts
+++ b/packages/cli/src/commands/log.ts
@@ -22,6 +22,12 @@ export interface EffectiveSession {
session: Session;
/** buildMessages output: labels, parents and links already normalised. */
messages: ViewNode[];
+ /**
+ * The user messages with their stable ids and conversation text, or null when
+ * neither the transcript nor the conversation store is readable. Search reads
+ * this (Story 8.14); the read verbs do not need it.
+ */
+ turns: SessionMessage[] | null;
}
/** Every valid session of the project, with the ids and structure the map draws. */
@@ -35,7 +41,7 @@ export async function loadEffectiveSessions(root: string, io: Io): Promise<Effec
const upgraded = turns ? upgradeSessionIds(session, turns) : session;
const events = await readEvents(root, session.sessionId);
const effective: Session = { ...upgraded, nodes: applyEvents(upgraded.nodes, events) };
- out.push({ session: effective, messages: buildMessages(effective.nodes) });
+ out.push({ session: effective, messages: buildMessages(effective.nodes), turns });
}
return out.sort(
(a, b) =>
@@ -195,26 +201,33 @@ export interface LogOptions {
branchesOnly?: boolean;
}
+/**
+ * The sessions a `--session` selector names: an exact id wins, otherwise an
+ * unambiguous prefix. An unknown or ambiguous selector is a user error.
+ */
+export function selectSessions(
+ sessions: readonly EffectiveSession[],
+ prefix: string,
+): EffectiveSession[] {
+ const exact = sessions.filter((entry) => entry.session.sessionId === prefix);
+ const matches =
+ exact.length > 0
+ ? exact
+ : sessions.filter((entry) => entry.session.sessionId.startsWith(prefix));
+ if (matches.length === 0) throw new CliError(`no session matches ${prefix}`);
+ if (matches.length > 1) {
+ const ids = matches.map((entry) => entry.session.sessionId).join(", ");
+ throw new CliError(`"${prefix}" matches ${matches.length} sessions: ${ids}`);
+ }
+ return matches;
+}
+
/**
* The log model: sessions newest first, their messages newest first. `--session`
* takes an exact id or an unambiguous prefix.
*/
export function buildLog(sessions: EffectiveSession[], opts: LogOptions = {}): LogModel {
- let selected = sessions;
- if (opts.session !== undefined) {
- const prefix = opts.session;
- const exact = sessions.filter((entry) => entry.session.sessionId === prefix);
- const matches =
- exact.length > 0
- ? exact
- : sessions.filter((entry) => entry.session.sessionId.startsWith(prefix));
- if (matches.length === 0) throw new CliError(`no session matches ${prefix}`);
- if (matches.length > 1) {
- const ids = matches.map((entry) => entry.session.sessionId).join(", ");
- throw new CliError(`"${prefix}" matches ${matches.length} sessions: ${ids}`);
- }
- selected = matches;
- }
+ const selected = opts.session === undefined ? sessions : selectSessions(sessions, opts.session);
const ordered = [...selected].sort(
(a, b) =>
diff --git a/packages/cli/src/commands/search.ts b/packages/cli/src/commands/search.ts
new file mode 100644
index 0000000..ed7cb39
--- /dev/null
+++ b/packages/cli/src/commands/search.ts
@@ -0,0 +1,89 @@
+import { CliError, type Io } from "../io.js";
+import {
+ normalizeQuery,
+ type SearchHit,
+ type SearchSource,
+ searchSources,
+} from "../view/search.js";
+import { loadEffectiveSessions, openProject, selectSessions, shortHash, stamp } from "./log.js";
+
+/**
+ * `codelineage search <text>` (Story 8.14): a linear, case- and accent-sensitive
+ * scan over the records and the stored conversation. No model and no index
+ * file; the same matcher backs the map's search box (`view/search.ts`).
+ */
+
+export interface SearchModel {
+ query: string;
+ hits: SearchHit[];
+}
+
+export interface SearchOptions {
+ dir: string;
+ io: Io;
+ text: string;
+ /** Only this session (id or unambiguous prefix). */
+ session?: string | undefined;
+ /** Maximum hits. */
+ limit?: number | undefined;
+ json?: boolean | undefined;
+}
+
+function oneLine(text: string): string {
+ return text.replace(/\s+/g, " ").trim();
+}
+
+/** `search` prints one line per hit and its excerpt, newest first. */
+export function formatSearch(model: SearchModel): string[] {
+ if (model.hits.length === 0) return [`No matches for "${model.query}".`];
+ return model.hits.flatMap((hit) => {
+ const title = oneLine(hit.sessionTitle) || hit.sessionId;
+ const hash = hit.messageId === null ? "(session)" : shortHash(hit.messageId);
+ return [
+ `${hash} ${(hit.label ?? "—").padEnd(4)} ${stamp(hit.at ?? undefined)} ${hit.field} ${title}`,
+ ` ${hit.excerpt}`,
+ ];
+ });
+}
+
+/** `codelineage search [dir]`; returns the model for tests and JSON callers. */
+export async function search(opts: SearchOptions): Promise<SearchModel> {
+ const query = opts.text.replace(/\s+/g, " ").trim();
+ if (normalizeQuery(opts.text) === "")
+ throw new CliError(
+ 'search needs some text, e.g. `codelineage search "where did we discuss X"`',
+ );
+ const root = await openProject(opts.dir);
+ const sessions = await loadEffectiveSessions(root, opts.io);
+ const selected = opts.session === undefined ? sessions : selectSessions(sessions, opts.session);
+ const sources: SearchSource[] = selected.map(({ session, messages, turns }) => ({
+ sessionId: session.sessionId,
+ title: session.title,
+ status: session.status,
+ startedAt: session.startedAt,
+ updatedAt: session.updatedAt,
+ messages,
+ ...(turns === null
+ ? {}
+ : {
+ chat: turns.map((turn) => ({
+ id: turn.hash,
+ ...(turn.label === undefined ? {} : { label: turn.label }),
+ at: turn.at,
+ text: turn.text,
+ replies: turn.replies,
+ tools: turn.tools,
+ })),
+ }),
+ }));
+
+ const all = searchSources(sources, opts.text);
+ const hits = opts.limit === undefined ? all : all.slice(0, opts.limit);
+ const model: SearchModel = { query, hits };
+ if (opts.json === true) {
+ opts.io.out(JSON.stringify(model, null, 2));
+ return model;
+ }
+ for (const line of formatSearch(model)) opts.io.out(line);
+ return model;
+}
diff --git a/packages/cli/src/hooks/sessionstart.ts b/packages/cli/src/hooks/sessionstart.ts
index 881e95a..e4d2b6d 100644
--- a/packages/cli/src/hooks/sessionstart.ts
+++ b/packages/cli/src/hooks/sessionstart.ts
@@ -110,7 +110,8 @@ async function startupContext(ctx: HookContext): Promise<string> {
const header =
`codelineage records this project's lineage (one node per user message, hanging from the ` +
`message it reacts to, grouped in sessions with branch summaries). Read it with ` +
- `\`${command} log -C "${ctx.root}"\` and one message with ` +
+ `\`${command} log -C "${ctx.root}"\`, find where something was discussed with ` +
+ `\`${command} search "<text>" -C "${ctx.root}"\`, and one message with ` +
`\`${command} show <ref> -C "${ctx.root}"\` (a ref is a message hash, an h+hex prefix of ` +
`six or more characters, or <session-id>:mN). When the user mentions a message hash or ` +
`another session's mN, run show before answering.`;
diff --git a/packages/cli/src/program.ts b/packages/cli/src/program.ts
index 8b9e637..1ccc691 100644
--- a/packages/cli/src/program.ts
+++ b/packages/cli/src/program.ts
@@ -15,6 +15,7 @@ import { type InitOptions, init } from "./commands/init.js";
import { formatShow, log, show } from "./commands/log.js";
import { migrateIds } from "./commands/migrate.js";
import { openPanel, openProject } from "./commands/open.js";
+import { search } from "./commands/search.js";
import { readStdin, sessionShow, sessionWrite } from "./commands/session.js";
import { runHook } from "./hooks/run.js";
import { CliError, type Io, processIo } from "./io.js";
@@ -165,6 +166,34 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =
),
);
+ program
+ .command("search")
+ .description("find recorded messages, branch summaries and conversation text")
+ .argument("<text>", "text to look for")
+ .argument("[dir]", "project directory", ".")
+ .option("-C, --dir <dir>", "project directory (same as the positional)")
+ .option("--session <id>", "only this session (id or prefix)")
+ .option("-n, --number <count>", "at most this many hits", positiveCount)
+ .option("--json", "print JSON instead of text")
+ .action(
+ run(
+ async (
+ text: string,
+ dir: string,
+ opts: { dir?: string; session?: string; number?: number; json?: boolean },
+ ) => {
+ await search({
+ dir: opts.dir ?? dir,
+ io: makeIo(false),
+ text,
+ session: opts.session,
+ limit: opts.number,
+ json: opts.json === true,
+ });
+ },
+ ),
+ );
+
program
.command("open")
.description("build and open a project map, or the global panel without a directory")
diff --git a/packages/cli/src/view/search.ts b/packages/cli/src/view/search.ts
new file mode 100644
index 0000000..cf8e0c3
--- /dev/null
+++ b/packages/cli/src/view/search.ts
@@ -0,0 +1,316 @@
+import type { LineageViewModel, ViewChatTurn, ViewNode, ViewStatus } from "./model.js";
+
+/**
+ * Lineage search (Story 8.14). The CLI and the map read the same data and use
+ * this one matcher, so `codelineage search <text>` and the map's search box
+ * return the same hits in the same order. No index file and no model: a linear
+ * scan over the records and the stored conversation is enough at this size.
+ *
+ * Matching is case- and accent-insensitive with Turkish letters folded the way
+ * a Turkish keyboard user expects: `I`, `İ` and `ı` all match each other, and
+ * `ş`, `ğ`, `ç`, `ö`, `ü` match their plain forms.
+ */
+
+export type SearchField = "title" | "branch" | "conversation" | "session";
+
+/** One session as the matcher sees it; the CLI and the map both build these. */
+export interface SearchSource {
+ sessionId: string;
+ title: string;
+ status?: ViewStatus;
+ startedAt?: string;
+ updatedAt?: string;
+ messages: readonly ViewNode[];
+ /** The stored conversation, when there is one (never tool output). */
+ chat?: readonly ViewChatTurn[];
+}
+
+export interface SearchHit {
+ sessionId: string;
+ sessionTitle: string;
+ /** The matching message; null when the session's title or status matched. */
+ messageId: string | null;
+ label: string | null;
+ /** The message's time, or the session's last activity for a session hit. */
+ at: string | null;
+ field: SearchField;
+ /** One line around the match, whitespace collapsed. */
+ excerpt: string;
+}
+
+/**
+ * Folds a character to its lowercase, unaccented form. Turkish `İ` decomposes
+ * to `I` plus a combining dot; `I` and `ı` are mapped to `i` explicitly, so all
+ * three forms match each other. Other accents fall out with the combining marks.
+ */
+function foldChar(ch: string): string {
+ return ch
+ .normalize("NFKD")
+ .replace(/\p{M}+/gu, "")
+ .replace(/[Iı]/g, "i")
+ .toLowerCase();
+}
+
+/** The case- and accent-insensitive form used for matching. */
+export function fold(text: string): string {
+ return foldChar(text.normalize("NFC"));
+}
+
+/** The query as the matcher compares it: folded and with runs of space collapsed. */
+export function normalizeQuery(query: string): string {
+ return fold(query).replace(/\s+/g, " ").trim();
+}
+
+/** Where in `text` the folded character at `index` starts; code units, like `slice`. */
+function originalIndex(text: string, index: number): number {
+ let folded = 0;
+ let offset = 0;
+ for (const ch of text) {
+ if (folded >= index) return offset;
+ folded += foldChar(ch).length;
+ offset += ch.length;
+ }
+ return text.length;
+}
+
+/** One line around the first match of the already-folded `needle`, or null. */
+export function excerptFor(text: string, needle: string, max = 120): string | null {
+ if (needle === "") return null;
+ const at = fold(text).indexOf(needle);
+ if (at < 0) return null;
+ const start = originalIndex(text, at);
+ const end = originalIndex(text, at + needle.length);
+ const before = Math.min(start, 40);
+ const after = Math.max(0, max - before - (end - start));
+ const left = start - before;
+ const right = Math.min(text.length, end + after);
+ const oneLine = text.slice(left, right).replace(/\s+/g, " ").trim();
+ return `${left > 0 ? "…" : ""}${oneLine}${right < text.length ? "…" : ""}`;
+}
+
+const NO_HIT = Symbol("no-hit");
+type FieldHit = { field: SearchField; excerpt: string } | typeof NO_HIT;
+
+/** Tries one string and returns either the hit or the marker for "try the next one". */
+function matchText(text: string | undefined, needle: string, field: SearchField): FieldHit {
+ if (text === undefined || text === "") return NO_HIT;
+ const excerpt = excerptFor(text, needle);
+ return excerpt === null ? NO_HIT : { field, excerpt };
+}
+
+/** The message's own text: title, notes and decisions — shown in the same panel. */
+function messageHit(message: ViewNode, needle: string): FieldHit {
+ for (const text of [
+ message.title,
+ message.summary,
+ message.why,
+ ...(message.alternatives ?? []).flatMap((alt) => [alt.option, alt.why]),
+ ...(message.work ?? []),
+ ...(message.agentDecisions ?? []).flatMap((decision) => [
+ decision.title,
+ decision.why,
+ ...(decision.alternatives ?? []).flatMap((alt) => [alt.option, alt.why]),
+ ]),
+ ]) {
+ const hit = matchText(text, needle, "title");
+ if (hit !== NO_HIT) return hit;
+ }
+ return NO_HIT;
+}
+
+/** The branch summary that starts on this message. */
+function branchHit(message: ViewNode, needle: string): FieldHit {
+ if (message.branch === undefined) return NO_HIT;
+ for (const text of [
+ message.branch.title,
+ message.branch.asked,
+ message.branch.outcome,
+ message.branch.open,
+ ]) {
+ const hit = matchText(text, needle, "branch");
+ if (hit !== NO_HIT) return hit;
+ }
+ return NO_HIT;
+}
+
+/** The stored conversation turn: the user's text first, then the agent's replies. */
+function conversationHit(turn: ViewChatTurn | undefined, needle: string): FieldHit {
+ if (turn === undefined) return NO_HIT;
+ const hit = matchText(turn.text, needle, "conversation");
+ if (hit !== NO_HIT) return hit;
+ for (const reply of turn.replies) {
+ const replyHit = matchText(reply, needle, "conversation");
+ if (replyHit !== NO_HIT) return replyHit;
+ }
+ return NO_HIT;
+}
+
+function turnOf(
+ chat: readonly ViewChatTurn[] | undefined,
+ message: ViewNode,
+): ViewChatTurn | undefined {
+ return chat?.find(
+ (turn) => turn.id === message.id || (turn.label !== undefined && turn.label === message.label),
+ );
+}
+
+/** The first matching group of a message, in reading order. */
+function hitOf(
+ message: ViewNode,
+ chat: readonly ViewChatTurn[] | undefined,
+ needle: string,
+): FieldHit {
+ const own = messageHit(message, needle);
+ if (own !== NO_HIT) return own;
+ const branch = branchHit(message, needle);
+ if (branch !== NO_HIT) return branch;
+ return conversationHit(turnOf(chat, message), needle);
+}
+
+/** Session title and status, as one "session" hit. */
+function sessionHit(source: SearchSource, needle: string): FieldHit {
+ const status = source.status;
+ const statusTexts =
+ status === undefined
+ ? []
+ : [status.goal, ...status.done, ...status.pending.map((item) => item.text), status.next];
+ for (const text of [source.title, ...statusTexts]) {
+ const hit = matchText(text, needle, "session");
+ if (hit !== NO_HIT) return hit;
+ }
+ return NO_HIT;
+}
+
+function timeOf(value: string | null | undefined): number {
+ if (value === null || value === undefined) return Number.NEGATIVE_INFINITY;
+ const at = Date.parse(value);
+ return Number.isNaN(at) ? Number.NEGATIVE_INFINITY : at;
+}
+
+/** `m12` → 12, so equal times still order newest message first. */
+function labelNumber(label: string | null): number {
+ const match = label === null ? null : /^m([1-9][0-9]*)$/.exec(label);
+ return match === null ? -1 : Number(match[1]);
+}
+
+/**
+ * Every hit, newest first. One hit per message: the first matching field wins
+ * (the message's own text, then its branch summary, then its conversation), so
+ * a message that says "search" twice is still one row of the counter.
+ */
+export function searchSources(sources: readonly SearchSource[], query: string): SearchHit[] {
+ const needle = normalizeQuery(query);
+ if (needle === "") return [];
+ const hits: SearchHit[] = [];
+
+ for (const source of sources) {
+ const sessionLevel = sessionHit(source, needle);
+ if (sessionLevel !== NO_HIT) {
+ const newest = source.messages[source.messages.length - 1];
+ hits.push({
+ sessionId: source.sessionId,
+ sessionTitle: source.title,
+ messageId: null,
+ label: null,
+ at: source.updatedAt ?? source.startedAt ?? newest?.at ?? null,
+ field: sessionLevel.field,
+ excerpt: sessionLevel.excerpt,
+ });
+ }
+
+ for (const message of source.messages) {
+ const hit = hitOf(message, source.chat, needle);
+ if (hit === NO_HIT) continue;
+ hits.push({
+ sessionId: source.sessionId,
+ sessionTitle: source.title,
+ messageId: message.id,
+ label: message.label ?? null,
+ at: message.at ?? null,
+ field: hit.field,
+ excerpt: hit.excerpt,
+ });
+ }
+ }
+
+ return hits.sort(
+ (a, b) =>
+ timeOf(b.at) - timeOf(a.at) ||
+ a.sessionId.localeCompare(b.sessionId) ||
+ labelNumber(b.label) - labelNumber(a.label),
+ );
+}
+
+/** The sessions a hit list points at, in first-seen order. */
+export function hitSessionIds(hits: readonly SearchHit[]): string[] {
+ return [...new Set(hits.map((hit) => hit.sessionId))];
+}
+
+/** Moves the active hit by `delta`, clamped to the list: the ↑/↓ counter (8.14). */
+export function stepHitIndex(active: number, count: number, delta: number): number {
+ if (count === 0) return 0;
+ return Math.min(Math.max(active + delta, 0), count - 1);
+}
+
+/**
+ * The message ids to highlight, by session. A session-level hit has no message
+ * to highlight, so it contributes nothing here.
+ */
+export function hitMessageIds(hits: readonly SearchHit[]): Map<string, Set<string>> {
+ const out = new Map<string, Set<string>>();
+ for (const hit of hits) {
+ if (hit.messageId === null) continue;
+ const ids = out.get(hit.sessionId) ?? new Set<string>();
+ ids.add(hit.messageId);
+ out.set(hit.sessionId, ids);
+ }
+ return out;
+}
+
+/** True for a message reference the map can try: `h` plus 6..12 hex characters. */
+export function isHashQuery(text: string): boolean {
+ return /^h[0-9a-f]{6,12}$/.test(text.trim().toLowerCase());
+}
+
+export type HashRefResult =
+ | { kind: "ok"; sessionId: string; messageId: string; label: string | null; title: string }
+ | { kind: "ambiguous"; count: number }
+ | { kind: "none" };
+
+/** A pasted hash (or a unique prefix) as the map resolves it, like `show`. */
+export function resolveHashPrefix(model: LineageViewModel, ref: string): HashRefResult {
+ const prefix = ref.trim().toLowerCase();
+ const found = [...model.epochs.flatMap((epoch) => epoch.sessions), ...model.unassigned].flatMap(
+ (session) =>
+ session.messages
+ .filter((message) => message.id.startsWith(prefix))
+ .map((message) => ({ session, message })),
+ );
+ if (found.length === 0) return { kind: "none" };
+ if (found.length > 1) return { kind: "ambiguous", count: found.length };
+ const hit = found[0] as { session: { sessionId: string }; message: ViewNode };
+ return {
+ kind: "ok",
+ sessionId: hit.session.sessionId,
+ messageId: hit.message.id,
+ label: hit.message.label ?? null,
+ title: hit.message.title,
+ };
+}
+
+/** The map's search: every session of the page as a source, in page order. */
+export function searchLineage(model: LineageViewModel, query: string): SearchHit[] {
+ const sessions = [...model.epochs.flatMap((epoch) => epoch.sessions), ...model.unassigned];
+ return searchSources(
+ sessions.map((session) => ({
+ sessionId: session.sessionId,
+ title: session.title,
+ status: session.status,
+ startedAt: session.startedAt,
+ updatedAt: session.updatedAt,
+ messages: session.messages,
+ ...(session.chat === undefined ? {} : { chat: session.chat }),
+ })),
+ query,
+ );
+}
diff --git a/packages/cli/test/search.test.ts b/packages/cli/test/search.test.ts
new file mode 100644
index 0000000..649511b
--- /dev/null
+++ b/packages/cli/test/search.test.ts
@@ -0,0 +1,439 @@
+import { mkdir, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { beforeEach, describe, expect, it } from "vitest";
+import { init } from "../src/commands/init.js";
+import { shortHash, stamp } from "../src/commands/log.js";
+import { formatSearch, search } from "../src/commands/search.js";
+import { createProgram } from "../src/program.js";
+import type { Session } from "../src/schema/session.js";
+import { appendConversationTurns } from "../src/store/conversations.js";
+import { projectPaths } from "../src/store/paths.js";
+import type { LineageViewModel, ViewNode } from "../src/view/model.js";
+import {
+ excerptFor,
+ fold,
+ hitMessageIds,
+ hitSessionIds,
+ isHashQuery,
+ normalizeQuery,
+ resolveHashPrefix,
+ type SearchSource,
+ searchLineage,
+ searchSources,
+ stepHitIndex,
+} from "../src/view/search.js";
+import { envFor, type FakeIo, fakeIo, T0, tempDir } from "./helpers.js";
+
+const A = "h111111111111";
+const B = "h111111222222";
+const C = "h222222222222";
+
+function session(over: Partial<Session> & { sessionId: string }): Session {
+ return {
+ schema: 1,
+ agent: "claude-code",
+ title: "",
+ epoch: null,
+ startedAt: T0,
+ updatedAt: T0,
+ status: { goal: "", done: [], pending: [], next: "" },
+ nodes: [],
+ ...over,
+ };
+}
+
+const turn = (hash: string, label: string, at: string, text: string, replies: string[] = []) => ({
+ id: hash,
+ label,
+ at,
+ text,
+ replies,
+ tools: { commands: 0, files: [], other: 0 },
+});
+
+function message(over: Partial<ViewNode> & { id: string; title: string }): ViewNode {
+ return { kind: "message", ...over };
+}
+
+describe("search folding", () => {
+ it("folds Turkish letters both ways", () => {
+ expect(fold("Işık")).toBe("isik");
+ expect(fold("İSTANBUL")).toBe("istanbul");
+ expect(fold("Şişli ĞÇÖÜ")).toBe("sisli gcou");
+ expect(fold("I")).toBe(fold("ı"));
+ expect(normalizeQuery(" Çok Önemli ")).toBe("cok onemli");
+ });
+
+ it("keeps one line of context around the match", () => {
+ expect(excerptFor("Fix the loop", "loop")).toBe("Fix the loop");
+ const long = `${"a".repeat(100)} needle ${"b".repeat(100)}`;
+ const excerpt = excerptFor(long, "needle");
+ expect(excerpt).toContain("needle");
+ expect(excerpt?.startsWith("…")).toBe(true);
+ expect(excerpt?.endsWith("…")).toBe(true);
+ expect(excerptFor("nothing here", "needle")).toBeNull();
+ });
+});
+
+describe("searchSources", () => {
+ const sources: SearchSource[] = [
+ {
+ sessionId: "s1",
+ title: "Parser work",
+ startedAt: "2026-10-20T09:00:00.000Z",
+ updatedAt: "2026-10-20T10:00:00.000Z",
+ messages: [
+ message({ id: A, title: "Start the parser", at: "2026-10-20T09:00:00.000Z", label: "m1" }),
+ message({
+ id: B,
+ title: "Fix the loop",
+ label: "m2",
+ at: "2026-10-20T09:30:00.000Z",
+ why: "The loop ate one line.",
+ branch: {
+ title: "Reading files",
+ asked: "How do we read a file?",
+ outcome: "One reader.",
+ open: "",
+ },
+ }),
+ message({
+ id: C,
+ title: "Işık testi",
+ label: "m3",
+ at: "2026-10-20T10:00:00.000Z",
+ alternatives: [{ option: "Use a lamp", why: "Cheaper than the sun" }],
+ agentDecisions: [
+ {
+ title: "Kept the switch",
+ why: "It works.",
+ alternatives: [{ option: "Replace it", why: "Too slow." }],
+ },
+ ],
+ }),
+ ],
+ chat: [
+ turn(A, "m1", "2026-10-20T09:00:00.000Z", "Start the parser", [
+ "The reader lives in src/app.ts.",
+ ]),
+ turn(B, "m2", "2026-10-20T09:30:00.000Z", "Fix the loop"),
+ turn(C, "m3", "2026-10-20T10:00:00.000Z", "Işık testi"),
+ ],
+ },
+ {
+ sessionId: "s2",
+ title: "Other chat",
+ status: {
+ goal: "A goal about deployment",
+ done: ["Shipped search docs"],
+ pending: [{ text: "Write the tests", needsUser: false }],
+ next: "Test it",
+ },
+ startedAt: "2026-10-21T09:00:00.000Z",
+ updatedAt: "2026-10-21T09:10:00.000Z",
+ messages: [
+ message({ id: "h333333333333", title: "Unrelated", at: "2026-10-21T09:10:00.000Z" }),
+ ],
+ },
+ ];
+
+ it("reports where the match is and keeps one hit per message", () => {
+ const hits = searchSources(sources, "parser");
+ // The session title and the message title are separate rows; the message's
+ // conversation repeats "parser" and does not add a third row for it.
+ expect(hits).toHaveLength(2);
+ const messageHit = hits.find((hit) => hit.messageId === A);
+ expect(messageHit?.field).toBe("title");
+ expect(messageHit?.label).toBe("m1");
+ const sessionHit = hits.find((hit) => hit.messageId === null);
+ expect(sessionHit?.field).toBe("session");
+ expect(sessionHit?.excerpt).toContain("Parser work");
+ });
+
+ it("matches branches and the stored conversation, newest first", () => {
+ const branch = searchSources(sources, "read a file");
+ expect(branch).toHaveLength(1);
+ expect(branch[0]?.field).toBe("branch");
+ expect(branch[0]?.messageId).toBe(B);
+
+ const conversation = searchSources(sources, "src/app.ts");
+ expect(conversation).toHaveLength(1);
+ expect(conversation[0]?.field).toBe("conversation");
+ expect(conversation[0]?.excerpt).toContain("src/app.ts");
+
+ const hits = searchSources(sources, "the");
+ const times = hits.map((hit) => Date.parse(hit.at ?? ""));
+ expect(times).toEqual([...times].sort((a, b) => b - a));
+ });
+
+ it("finds Turkish words typed without their accents", () => {
+ const hits = searchSources(sources, "isik");
+ expect(hits).toHaveLength(1);
+ expect(hits[0]?.messageId).toBe(C);
+ expect(hits[0]?.field).toBe("title");
+ });
+
+ it("matches a session's status and returns no hits for an empty query", () => {
+ const hits = searchSources(sources, "deployment");
+ expect(hits).toHaveLength(1);
+ expect(hits[0]?.messageId).toBeNull();
+ expect(hits[0]?.field).toBe("session");
+ expect(searchSources(sources, "search docs")[0]?.messageId).toBeNull();
+ expect(searchSources(sources, "the tests")[0]?.messageId).toBeNull();
+ expect(searchSources(sources, " ")).toEqual([]);
+ });
+
+ it("reads alternatives and the agent's own decisions", () => {
+ expect(searchSources(sources, "lamp")[0]?.field).toBe("title");
+ expect(searchSources(sources, "kept the switch")[0]?.messageId).toBe(C);
+ expect(searchSources(sources, "replace it")[0]?.messageId).toBe(C);
+ });
+
+ it("orders equal times by message label, newest message first", () => {
+ const at = "2026-10-20T11:00:00.000Z";
+ const tied: SearchSource[] = [
+ {
+ sessionId: "s9",
+ title: "Equal",
+ startedAt: at,
+ updatedAt: at,
+ messages: [
+ message({ id: "haaaaaaaa0001", title: "tie one", label: "m1", at }),
+ message({ id: "haaaaaaaa0002", title: "tie two", label: "m2", at }),
+ // No label (a record older than 8.5) sorts last at the same time.
+ message({ id: "haaaaaaaa0003", title: "tie three", at }),
+ ],
+ },
+ ];
+ expect(searchSources(tied, "tie").map((hit) => hit.label)).toEqual(["m2", "m1", null]);
+ });
+
+ it("feeds the map: which sessions open and which messages highlight", () => {
+ const hits = searchSources(sources, "parser");
+ expect(hitSessionIds(hits)).toEqual(["s1"]);
+ expect([...hitMessageIds(hits).keys()]).toEqual(["s1"]);
+ expect([...(hitMessageIds(hits).get("s1") ?? [])]).toEqual([A]);
+ });
+
+ it("steps the counter within the list", () => {
+ expect(stepHitIndex(0, 12, 1)).toBe(1);
+ expect(stepHitIndex(11, 12, 1)).toBe(11);
+ expect(stepHitIndex(0, 12, -1)).toBe(0);
+ expect(stepHitIndex(0, 0, 1)).toBe(0);
+ });
+});
+
+describe("hash jump", () => {
+ const model: LineageViewModel = {
+ kind: "lineage",
+ schema: 1,
+ project: { name: "p", path: "/tmp/p", generatedAt: T0 },
+ status: { goal: "", done: [], pending: [], next: "", lastActivity: null },
+ epochs: [
+ {
+ id: "e1",
+ title: "Epoch one",
+ createdAt: T0,
+ sessions: [
+ {
+ sessionId: "s1",
+ agent: "claude-code",
+ title: "One",
+ epoch: "e1",
+ startedAt: T0,
+ updatedAt: T0,
+ status: { goal: "", done: [], pending: [], next: "" },
+ messages: [
+ message({ id: A, title: "First", at: T0, label: "m1" }),
+ message({ id: B, title: "Second", at: T0, label: "m2" }),
+ message({ id: C, title: "Third", at: T0, label: "m3" }),
+ ],
+ transcriptAvailable: true,
+ },
+ ],
+ },
+ ],
+ unassigned: [],
+ };
+
+ it("recognises a hash and resolves only a unique prefix", () => {
+ expect(isHashQuery(A)).toBe(true);
+ expect(isHashQuery("h111111")).toBe(true);
+ expect(isHashQuery("h11111")).toBe(false);
+ expect(isHashQuery("start")).toBe(false);
+
+ expect(resolveHashPrefix(model, "h222222")).toEqual({
+ kind: "ok",
+ sessionId: "s1",
+ messageId: C,
+ label: "m3",
+ title: "Third",
+ });
+ expect(resolveHashPrefix(model, "h111111")).toEqual({ kind: "ambiguous", count: 2 });
+ expect(resolveHashPrefix(model, "h999999")).toEqual({ kind: "none" });
+ });
+
+ it("searches the whole page model through the same matcher", () => {
+ const hits = searchLineage(model, "second");
+ expect(hits).toHaveLength(1);
+ expect(hits[0]?.messageId).toBe(B);
+ expect(hits[0]?.sessionTitle).toBe("One");
+ });
+});
+
+describe("codelineage search", () => {
+ let dir: string;
+ let root: string;
+ let io: FakeIo;
+
+ /** Runs the command through Commander, as the user's shell does. */
+ async function cli(...args: string[]): Promise<string> {
+ let err = "";
+ const program = createProgram(() => io, {
+ launch: async () => true,
+ server: async () => null,
+ stdin: async () => "",
+ });
+ program.exitOverride().configureOutput({ writeErr: (s) => (err += s), writeOut: () => {} });
+ for (const c of program.commands)
+ c.exitOverride().configureOutput({ writeErr: (s) => (err += s) });
+ try {
+ await program.parseAsync(args, { from: "user" });
+ } catch (e) {
+ if (!err) throw e;
+ }
+ return err;
+ }
+
+ beforeEach(async () => {
+ dir = await tempDir();
+ root = join(dir, "proj");
+ await mkdir(root);
+ io = fakeIo(envFor(dir));
+ await init(root, { name: "proj", retention: "keep", language: "auto" }, fakeIo(envFor(dir)));
+
+ const s1 = session({
+ sessionId: "s1",
+ title: "Ship the parser",
+ epoch: "e8",
+ startedAt: "2026-10-20T09:00:00.000Z",
+ updatedAt: "2026-10-20T10:00:00.000Z",
+ nodes: [
+ {
+ id: A,
+ parent: null,
+ kind: "message",
+ title: "Start the parser",
+ at: "2026-10-20T09:00:00.000Z",
+ },
+ {
+ id: B,
+ parent: A,
+ kind: "message",
+ title: "Işık testi",
+ at: "2026-10-20T09:30:00.000Z",
+ },
+ ],
+ });
+ const s2 = session({
+ sessionId: "s2",
+ title: "Later chat",
+ startedAt: "2026-10-21T10:00:00.000Z",
+ updatedAt: "2026-10-21T10:10:00.000Z",
+ nodes: [
+ {
+ id: C,
+ parent: "s1:h111111111111",
+ kind: "message",
+ title: "Continue the parser",
+ at: "2026-10-21T10:00:00.000Z",
+ },
+ ],
+ });
+ await writeFile(projectPaths(root).session("s1"), JSON.stringify(s1));
+ await writeFile(projectPaths(root).session("s2"), JSON.stringify(s2));
+ await appendConversationTurns(root, "s1", [
+ {
+ id: "m1",
+ uuid: "u1",
+ hash: A,
+ at: "2026-10-20T09:00:00.000Z",
+ text: "Start the parser",
+ replies: ["The reader lives in src/app.ts."],
+ tools: { commands: 0, files: [], other: 0 },
+ },
+ {
+ id: "m2",
+ uuid: "u2",
+ hash: B,
+ at: "2026-10-20T09:30:00.000Z",
+ text: "Işık testi",
+ replies: [],
+ tools: { commands: 0, files: [], other: 0 },
+ },
+ ]);
+ });
+
+ it("prints hash, label, time, where and an excerpt, newest first", async () => {
+ const model = await search({ dir: root, io, text: "parser" });
+ // C is the newest message; s1's session-title hit carries its updatedAt,
+ // which is newer than the first message it also matches.
+ expect(model.hits.map((hit) => hit.messageId)).toEqual([C, null, A]);
+ expect(io.lines[0]).toBe(
+ `${shortHash(C)} m1 ${stamp("2026-10-21T10:00:00.000Z")} title Later chat`,
+ );
+ expect(io.lines[3]).toContain("Ship the parser");
+ expect(io.lines[5]).toContain("Start the parser");
+ expect(formatSearch(model)[0]).toContain("Later chat");
+ });
+
+ it("finds stored conversation text and Turkish without accents", async () => {
+ const conversation = await search({ dir: root, io: fakeIo(envFor(dir)), text: "src/app.ts" });
+ expect(conversation.hits).toHaveLength(1);
+ expect(conversation.hits[0]?.field).toBe("conversation");
+
+ const turkish = await search({ dir: root, io: fakeIo(envFor(dir)), text: "isik" });
+ expect(turkish.hits.map((hit) => hit.messageId)).toContain(B);
+ });
+
+ it("limits, filters by session and prints JSON", async () => {
+ const limited = await search({ dir: root, io: fakeIo(envFor(dir)), text: "parser", limit: 1 });
+ expect(limited.hits).toHaveLength(1);
+
+ const onlySession = await search({
+ dir: root,
+ io: fakeIo(envFor(dir)),
+ text: "parser",
+ session: "s2",
+ });
+ expect(onlySession.hits.every((hit) => hit.sessionId === "s2")).toBe(true);
+
+ const jsonIo = fakeIo(envFor(dir));
+ await search({ dir: root, io: jsonIo, text: "parser", json: true });
+ const parsed = JSON.parse(jsonIo.lines.join("\n")) as {
+ query: string;
+ hits: { sessionId: string; messageId: string | null; field: string; excerpt: string }[];
+ };
+ expect(parsed.query).toBe("parser");
+ expect(parsed.hits[0]).toMatchObject({
+ sessionId: "s2",
+ messageId: C,
+ field: "title",
+ });
+ expect(parsed.hits[0]?.excerpt).toContain("parser");
+ });
+
+ it("refuses an empty query and an unknown session", async () => {
+ await expect(search({ dir: root, io, text: " " })).rejects.toThrow(/needs some text/);
+ await expect(search({ dir: root, io, text: "parser", session: "nope" })).rejects.toThrow(
+ /no session matches/,
+ );
+ });
+
+ it("runs through the program with -n and --json", async () => {
+ const err = await cli("search", "parser", root, "-n", "1", "--json");
+ expect(err).toBe("");
+ const parsed = JSON.parse(io.lines.join("\n")) as { hits: unknown[] };
+ expect(parsed.hits).toHaveLength(1);
+ });
+});
diff --git a/packages/template/src/App.tsx b/packages/template/src/App.tsx
index 4036ed0..4832e08 100644
--- a/packages/template/src/App.tsx
+++ b/packages/template/src/App.tsx
@@ -1,6 +1,15 @@
+import { useDeferredValue, useMemo, useState } from "react";
import type { LineageViewModel } from "../../cli/src/view/model.js";
+import {
+ type HashRefResult,
+ isHashQuery,
+ resolveHashPrefix,
+ searchLineage,
+ stepHitIndex,
+} from "../../cli/src/view/search.js";
import { formatTime } from "./format.js";
import { Graph } from "./Graph.js";
+import { type MapSearchState, SearchBox } from "./MapSearch.js";
import { ProjectSwitcher } from "./ProjectSwitcher.js";
import { SettingsButton } from "./SettingsModal.js";
@@ -8,11 +17,44 @@ export function App({ model }: { model: LineageViewModel }) {
const sessionCount =
model.epochs.reduce((sum, epoch) => sum + epoch.sessions.length, 0) + model.unassigned.length;
+ // The search state lives here because the box sits in the page head and the
+ // map needs the hits; `useDeferredValue` keeps typing responsive while the
+ // scan runs over every message and conversation.
+ const [query, setQuery] = useState("");
+ const [active, setActive] = useState(0);
+ const [step, setStep] = useState(0);
+ const deferred = useDeferredValue(query);
+ const hash: HashRefResult | null = useMemo(
+ () => (isHashQuery(deferred) ? resolveHashPrefix(model, deferred) : null),
+ [model, deferred],
+ );
+ const hits = useMemo(
+ () => (hash === null ? searchLineage(model, deferred) : []),
+ [model, deferred, hash],
+ );
+ const search: MapSearchState = { hits, active, step, hash };
+
+ function change(next: string): void {
+ setQuery(next);
+ setActive(0);
+ setStep((value) => value + 1);
+ }
+ function move(delta: number): void {
+ setActive((index) => stepHitIndex(index, hits.length, delta));
+ setStep((value) => value + 1);
+ }
+ function clear(): void {
+ setQuery("");
+ setActive(0);
+ setStep(0);
+ }
+
return (
<main>
<div className="page-head">
<div className="page-bar">
<ProjectSwitcher model={model} />
+ <SearchBox value={query} state={search} onQuery={change} onStep={move} onClear={clear} />
<SettingsButton settings={model.settings} />
</div>
@@ -30,7 +72,7 @@ export function App({ model }: { model: LineageViewModel }) {
</header>
</div>
- <Graph model={model} />
+ <Graph model={model} search={search} />
</main>
);
}
diff --git a/packages/template/src/GitGraph.tsx b/packages/template/src/GitGraph.tsx
index 0573cc5..a008313 100644
--- a/packages/template/src/GitGraph.tsx
+++ b/packages/template/src/GitGraph.tsx
@@ -44,6 +44,8 @@ function Row({
branchTitle,
selected,
branchSelected,
+ searchHit,
+ searchActive,
onSelect,
onUnfold,
onContinue,
@@ -52,6 +54,10 @@ function Row({
branchTitle: string;
selected: boolean;
branchSelected: boolean;
+ /** The message matches the search (Story 8.14). */
+ searchHit: boolean;
+ /** The hit the ↑/↓ counter is on. */
+ searchActive: boolean;
onSelect: (row: GitMessageRow) => void;
onUnfold: (segmentId: string) => void;
onContinue: (continues: NonNullable<ViewNode["continues"]>) => void;
@@ -83,10 +89,19 @@ function Row({
}
const message = row.message;
+ const className = [
+ "git-row",
+ selected ? "is-selected" : "",
+ branchSelected ? "in-branch" : "",
+ searchHit ? "is-search-hit" : "",
+ searchActive ? "is-search-active" : "",
+ ]
+ .filter(Boolean)
+ .join(" ");
return (
<button
type="button"
- className={`git-row${selected ? " is-selected" : ""}${branchSelected ? " in-branch" : ""}`}
+ className={className}
style={style}
data-message={message.id}
onClick={(event: MouseEvent) => {
@@ -149,6 +164,8 @@ export function GitGraph({
git,
selectedId,
activeSegmentId,
+ highlightIds,
+ activeHitId,
onSelect,
onUnfold,
onContinue,
@@ -158,6 +175,10 @@ export function GitGraph({
selectedId: string | null;
/** Branch the drill-down belongs to. */
activeSegmentId: string | null;
+ /** Messages that match the map search (Story 8.14); undefined when none. */
+ highlightIds: ReadonlySet<string> | undefined;
+ /** The search hit the counter is on, if it belongs to this session. */
+ activeHitId: string | null;
onSelect: (row: GitMessageRow) => void;
onUnfold: (segmentId: string) => void;
/** Opens the earlier session this message continues, at that message. */
@@ -257,15 +278,16 @@ export function GitGraph({
<div className="git-rows" style={{ left: git.graphWidth + 8, width: git.rowWidth }}>
{git.rows.map((row) => {
const branch = branches.get(row.segmentId);
+ const messageId = row.kind === "message" ? row.message.id : null;
return (
<Row
key={row.kind === "more" ? `${row.segmentId}-more` : row.message.id}
row={row}
branchTitle={branch?.branch.title ?? ""}
- selected={
- row.kind === "message" && selectedId !== null && row.message.id === selectedId
- }
+ selected={messageId !== null && selectedId !== null && messageId === selectedId}
branchSelected={activeSegmentId !== null && row.segmentId === activeSegmentId}
+ searchHit={messageId !== null && highlightIds?.has(messageId) === true}
+ searchActive={messageId !== null && activeHitId !== null && messageId === activeHitId}
onSelect={onSelect}
onUnfold={onUnfold}
onContinue={onContinue}
diff --git a/packages/template/src/Graph.tsx b/packages/template/src/Graph.tsx
index 1c40838..0991b8b 100644
--- a/packages/template/src/Graph.tsx
+++ b/packages/template/src/Graph.tsx
@@ -12,10 +12,12 @@ import {
import "@xyflow/react/dist/style.css";
import { createContext, useCallback, useContext, useEffect, useMemo, useState } from "react";
import type { LineageViewModel, ViewSession } from "../../cli/src/view/model.js";
+import { hitMessageIds, hitSessionIds } from "../../cli/src/view/search.js";
import { useFullscreen } from "./fullscreen.js";
import { GitGraph } from "./GitGraph.js";
import { type GitLayout, layoutGitGraph } from "./gitLayout.js";
import { headOf } from "./graph.js";
+import type { MapSearchState } from "./MapSearch.js";
import { Outline, type OutlineTarget } from "./Outline.js";
import { OPEN_LINK_DROP, SessionMap } from "./SessionMap.js";
import { DrillDown, type Selection } from "./SidePanel.js";
@@ -53,12 +55,32 @@ const GraphActions = createContext<{
/** An opened session: its message graph and where it sits on the canvas. */
type Opening = { session: ViewSession; git: GitLayout; top: number; left: number };
-type ProjectData = { model: LineageViewModel; graph: SessionGraph; openings: Opening[] };
+type ProjectData = {
+ model: LineageViewModel;
+ graph: SessionGraph;
+ openings: Opening[];
+ /** Message ids to highlight, by session (Story 8.14). */
+ highlights: Map<string, Set<string>>;
+ /** Sessions whose title or status matched; their row is marked. */
+ sessionHits: ReadonlySet<string>;
+ /** The hit the user is on (or a pasted hash), if any. */
+ activeHit: { sessionId: string; messageId: string | null } | null;
+};
type ProjectFlowNode = Node<ProjectData, "project">;
type MapFlowNode = ProjectFlowNode;
-function SessionMessages({ session, git }: { session: ViewSession; git: GitLayout }) {
+function SessionMessages({
+ session,
+ git,
+ highlights,
+ activeHitId,
+}: {
+ session: ViewSession;
+ git: GitLayout;
+ highlights: ReadonlySet<string> | undefined;
+ activeHitId: string | null;
+}) {
const { selection, openNode, openContinue, unfold } = useContext(GraphActions);
const own = selection?.sessionId === session.sessionId;
if (git.rows.length === 0)
@@ -68,6 +90,8 @@ function SessionMessages({ session, git }: { session: ViewSession; git: GitLayou
git={git}
selectedId={selection?.type === "node" && own ? selection.nodeId : null}
activeSegmentId={selection?.type === "node" && own ? (selection.branchId ?? null) : null}
+ highlightIds={highlights}
+ activeHitId={activeHitId}
onSelect={(row) => openNode(session.sessionId, row.message.id, row.segmentId)}
onUnfold={unfold}
onContinue={(continues) => openContinue(continues.sessionId, continues.id)}
@@ -84,18 +108,29 @@ function ProjectBox({ data }: NodeProps<ProjectFlowNode>) {
graph={data.graph}
selectedSessionId={selection?.sessionId ?? null}
openIds={openIds}
+ highlightSessionIds={data.sessionHits}
onOpen={openSession}
onContinue={openContinue}
/>
- {data.openings.map((opening) => (
- <div
- key={opening.session.sessionId}
- className="session-open"
- style={{ top: opening.top, left: opening.left }}
- >
- <SessionMessages session={opening.session} git={opening.git} />
- </div>
- ))}
+ {data.openings.map((opening) => {
+ const active = data.activeHit;
+ return (
+ <div
+ key={opening.session.sessionId}
+ className="session-open"
+ style={{ top: opening.top, left: opening.left }}
+ >
+ <SessionMessages
+ session={opening.session}
+ git={opening.git}
+ highlights={data.highlights.get(opening.session.sessionId)}
+ activeHitId={
+ active?.sessionId === opening.session.sessionId ? active.messageId : null
+ }
+ />
+ </div>
+ );
+ })}
</div>
);
}
@@ -158,7 +193,7 @@ function findSession(model: LineageViewModel, id: string): ViewSession | undefin
return model.unassigned.find((session) => session.sessionId === id);
}
-function Flow({ model }: { model: LineageViewModel }) {
+function Flow({ model, search }: { model: LineageViewModel; search: MapSearchState }) {
// Read once: a live data swap must not move the page back to the hash target.
const [initial] = useState(() => readTarget(model));
useEffect(() => {
@@ -186,6 +221,44 @@ function Flow({ model }: { model: LineageViewModel }) {
const head = headOf(model);
+ // Search (Story 8.14): highlight matching messages, open their sessions and
+ // centre the active hit. A pasted hash resolves to one message and shows it
+ // like `show`; a session-level hit centres the session's row instead.
+ const hashHit = search.hash?.kind === "ok" ? search.hash : null;
+ // A live data swap can shrink the hit list under the cursor; clamp instead of
+ // pointing at a row that is no longer there.
+ const activeHit = search.hits[Math.min(search.active, search.hits.length - 1)] ?? null;
+ const searchTarget = useMemo(
+ () =>
+ hashHit !== null
+ ? { sessionId: hashHit.sessionId, messageId: hashHit.messageId }
+ : activeHit === null
+ ? null
+ : { sessionId: activeHit.sessionId, messageId: activeHit.messageId },
+ [hashHit?.sessionId, hashHit?.messageId, activeHit?.sessionId, activeHit?.messageId],
+ );
+ const highlights = useMemo(() => hitMessageIds(search.hits), [search.hits]);
+ const sessionHits = useMemo(
+ () => new Set(search.hits.flatMap((hit) => (hit.messageId === null ? [hit.sessionId] : []))),
+ [search.hits],
+ );
+ const hitSessions = useMemo(() => hitSessionIds(search.hits), [search.hits]);
+
+ // Opening the accordion for every match is what makes the highlights visible.
+ useEffect(() => {
+ if (hitSessions.length === 0) return;
+ setOpenIds((previous) => {
+ let changed = false;
+ const next = new Set(previous);
+ for (const id of hitSessions) {
+ if (next.has(id)) continue;
+ next.add(id);
+ changed = true;
+ }
+ return changed ? next : previous;
+ });
+ }, [hitSessions]);
+
/** The open drill-down's message, if any. */
const target = selection?.type === "node" ? selection : null;
@@ -195,11 +268,21 @@ function Flow({ model }: { model: LineageViewModel }) {
for (const sessionId of openIds) {
const session = findSession(model, sessionId);
if (!session) continue;
- const options = {
+ let options = {
unfolded,
openAll,
headId: head?.sessionId === sessionId ? head.messageId : null,
};
+ // A search hit inside a folded branch must be visible to be highlighted,
+ // so every branch that holds a hit of this session opens.
+ const hitIds = highlights.get(sessionId);
+ if (hitIds !== undefined && hitIds.size > 0) {
+ const folded = layoutGitGraph(session.messages, options);
+ const extra = folded.segments
+ .filter((segment) => segment.ids.some((id) => hitIds.has(id)))
+ .map((segment) => segment.id);
+ if (extra.length > 0) options = { ...options, unfolded: new Set([...unfolded, ...extra]) };
+ }
let layout = layoutGitGraph(session.messages, options);
const targetId = target?.sessionId === sessionId ? target.nodeId : null;
if (
@@ -223,6 +306,7 @@ function Flow({ model }: { model: LineageViewModel }) {
openIds,
unfolded,
openAll,
+ highlights,
head?.sessionId,
head?.messageId,
target?.sessionId,
@@ -273,6 +357,18 @@ function Flow({ model }: { model: LineageViewModel }) {
[openings],
);
+ /** A search hit's point: its message, or the session's row for a session hit. */
+ const pointOfHit = useCallback(
+ (hit: { sessionId: string; messageId: string | null }) => {
+ if (hit.messageId !== null) return pointOf(hit.sessionId, hit.messageId);
+ const row = sessionGraph.git.rows.find(
+ (candidate) => candidate.kind === "message" && candidate.message.id === hit.sessionId,
+ );
+ return row === undefined ? null : { x: sessionGraph.git.graphWidth / 2, y: row.y };
+ },
+ [pointOf, sessionGraph],
+ );
+
/** Where the view centres on load: the target message, else the whole map. */
const focusRow = useMemo(
() => (initial === null ? null : pointOf(initial.sessionId, initial.messageId)),
@@ -292,6 +388,21 @@ function Flow({ model }: { model: LineageViewModel }) {
[jumps, leftOff, pointOf],
);
+ /**
+ * A search move: the step counter changes on every keystroke and on ↑/↓, and
+ * the point may only resolve once the hit's session has opened, so the canvas
+ * waits for both.
+ */
+ const searchPoint = useMemo(
+ () => (searchTarget === null ? null : pointOfHit(searchTarget)),
+ [searchTarget, pointOfHit],
+ );
+ const searchJump = useMemo(
+ () =>
+ search.step === 0 || searchPoint === null ? null : { key: search.step, point: searchPoint },
+ [search.step, searchPoint],
+ );
+
const ensureOpen = useCallback((sessionId: string) => {
setOpenIds((previous) =>
previous.has(sessionId) ? previous : new Set([...previous, sessionId]),
@@ -330,6 +441,12 @@ function Flow({ model }: { model: LineageViewModel }) {
(sessionId: string, messageId: string) => openNode(sessionId, messageId),
[openNode],
);
+
+ // A pasted hash opens the message the way clicking it would (`show` for the map).
+ useEffect(() => {
+ if (hashHit === null) return;
+ openNode(hashHit.sessionId, hashHit.messageId);
+ }, [hashHit?.sessionId, hashHit?.messageId, openNode]);
const unfold = useCallback((segmentId: string) => {
setUnfolded((previous) => {
const next = new Set(previous);
@@ -367,10 +484,17 @@ function Flow({ model }: { model: LineageViewModel }) {
draggable: false,
connectable: false,
selectable: false,
- data: { model, graph: sessionGraph, openings },
+ data: {
+ model,
+ graph: sessionGraph,
+ openings,
+ highlights,
+ sessionHits,
+ activeHit: searchTarget,
+ },
},
];
- }, [model, sessionGraph, openings]);
+ }, [model, sessionGraph, openings, highlights, sessionHits, searchTarget]);
return (
<GraphActions.Provider value={actions}>
@@ -445,7 +569,13 @@ function Flow({ model }: { model: LineageViewModel }) {
{sessionGraph.git.rows.length === 0 ? (
<p className="graph-status empty">No sessions recorded yet.</p>
) : (
- <MapCanvas nodes={nodes} focusRow={focusRow} jump={jump} fit={fits} />
+ <MapCanvas
+ nodes={nodes}
+ focusRow={focusRow}
+ jump={jump}
+ searchJump={searchJump}
+ fit={fits}
+ />
)}
<DrillDown
model={model}
@@ -469,6 +599,7 @@ function MapCanvas({
nodes,
focusRow,
jump,
+ searchJump,
fit,
}: {
nodes: MapFlowNode[];
@@ -476,11 +607,28 @@ function MapCanvas({
focusRow: { x: number; y: number } | null;
/** A user request to centre on a point; a new `key` moves the view again. */
jump: { key: number; point: { x: number; y: number } | null } | null;
+ /** A search move: the active hit or a pasted hash (Story 8.14). */
+ searchJump: { key: number; point: { x: number; y: number } } | null;
/** A new value frames the whole map again (after "Fold all"). */
fit: number;
}) {
const { fitView, setViewport } = useReactFlow();
+ /** Centres the view on a canvas point; does nothing before the canvas exists. */
+ function centre(point: { x: number; y: number }): void {
+ const canvas = document.querySelector(".react-flow")?.getBoundingClientRect();
+ if (!canvas) return;
+ const zoom = 0.9;
+ void setViewport(
+ {
+ zoom,
+ x: canvas.width / 2 - point.x * zoom,
+ y: canvas.height / 2 - point.y * zoom,
+ },
+ { duration: 300 },
+ );
+ }
+
useEffect(() => {
if (fit === 0) return;
// Wait a frame so React Flow has the smaller, closed map before framing it.
@@ -492,20 +640,22 @@ function MapCanvas({
}, [fit]);
const jumpKey = jump?.key ?? 0;
- const jumpX = jump?.point?.x;
- const jumpY = jump?.point?.y;
+ const jumpPoint = jump?.point ?? null;
useEffect(() => {
- if (jumpKey === 0 || jumpX === undefined || jumpY === undefined) return;
- const canvas = document.querySelector(".react-flow")?.getBoundingClientRect();
- if (!canvas) return;
- const zoom = 0.9;
- void setViewport(
- { zoom, x: canvas.width / 2 - jumpX * zoom, y: canvas.height / 2 - jumpY * zoom },
- { duration: 300 },
- );
+ if (jumpKey === 0 || jumpPoint === null) return;
+ centre(jumpPoint);
// Only a new click moves the view; a live data swap must not.
}, [jumpKey]);
+ // A search step also re-centres when its point only resolves after the hit's
+ // session has opened (`searchJump.key` stays the same in that case).
+ const searchKey = searchJump?.key ?? 0;
+ const searchPoint = searchJump?.point ?? null;
+ useEffect(() => {
+ if (searchKey === 0 || searchPoint === null) return;
+ centre(searchPoint);
+ }, [searchKey, searchPoint]);
+
useEffect(() => {
const timer = window.setTimeout(() => {
const canvas = document.querySelector(".react-flow")?.getBoundingClientRect();
@@ -546,11 +696,11 @@ function MapCanvas({
}
/** The project map: sessions at the top, a session's messages in place. */
-export function Graph({ model }: { model: LineageViewModel }) {
+export function Graph({ model, search }: { model: LineageViewModel; search: MapSearchState }) {
return (
<section className="lineage-map" aria-label="Project lineage graph">
<ReactFlowProvider>
- <Flow model={model} />
+ <Flow model={model} search={search} />
</ReactFlowProvider>
</section>
);
diff --git a/packages/template/src/MapSearch.tsx b/packages/template/src/MapSearch.tsx
new file mode 100644
index 0000000..99c1dfb
--- /dev/null
+++ b/packages/template/src/MapSearch.tsx
@@ -0,0 +1,133 @@
+import { type KeyboardEvent as ReactKeyboardEvent, useEffect, useRef } from "react";
+import type { HashRefResult, SearchHit } from "../../cli/src/view/search.js";
+
+/**
+ * The map's search box (Story 8.14): Ctrl/Cmd+F focuses it while the map has the
+ * page (a second press lets the browser's own find through), matching messages
+ * are highlighted and their sessions open, ↑/↓ (or Enter / Shift+Enter) step
+ * through the hits, Esc clears. A pasted message hash jumps like `show`.
+ */
+
+/** What App passes down to Graph: the hits and where the user is in them. */
+export interface MapSearchState {
+ hits: SearchHit[];
+ /** Index of the active hit in `hits`. */
+ active: number;
+ /** Bumped whenever the view should move to the active hit (or the hash). */
+ step: number;
+ /** A hash the query resolved to, when the query looks like one. */
+ hash: HashRefResult | null;
+}
+
+export function SearchBox({
+ value,
+ state,
+ onQuery,
+ onStep,
+ onClear,
+}: {
+ /** The text in the box; the hits in `state` may lag behind it while scanning. */
+ value: string;
+ state: MapSearchState;
+ onQuery: (query: string) => void;
+ onStep: (delta: number) => void;
+ onClear: () => void;
+}) {
+ const inputRef = useRef<HTMLInputElement>(null);
+
+ // Ctrl/Cmd+F focuses the box; while it is focused the browser keeps its own
+ // find, so a second press still offers the page's native search.
+ useEffect(() => {
+ function onKey(event: KeyboardEvent): void {
+ if (!(event.metaKey || event.ctrlKey) || event.key.toLowerCase() !== "f") return;
+ if (document.activeElement === inputRef.current) return;
+ event.preventDefault();
+ inputRef.current?.focus();
+ inputRef.current?.select();
+ }
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, []);
+
+ function onKeyDown(event: ReactKeyboardEvent<HTMLInputElement>): void {
+ if (event.key === "Escape") {
+ event.preventDefault();
+ onClear();
+ inputRef.current?.blur();
+ return;
+ }
+ if (state.hash !== null) return;
+ if (event.key === "Enter") {
+ event.preventDefault();
+ onStep(event.shiftKey ? -1 : 1);
+ }
+ }
+
+ const count = state.hits.length;
+ const index = Math.min(state.active, count - 1);
+ const status =
+ state.hash !== null
+ ? state.hash.kind === "ok"
+ ? "1 / 1"
+ : state.hash.kind === "ambiguous"
+ ? `${state.hash.count} matches`
+ : "no match"
+ : value.trim() === ""
+ ? ""
+ : count === 0
+ ? "0 hits"
+ : `${index + 1} / ${count}`;
+ const hint =
+ state.hash !== null
+ ? state.hash.kind === "ok"
+ ? `→ ${state.hash.label ?? state.hash.messageId} · ${state.hash.title}`
+ : state.hash.kind === "ambiguous"
+ ? "several messages match — type more of the hash"
+ : "no recorded message has that hash"
+ : count === 0 && value.trim() !== ""
+ ? "no matches"
+ : null;
+
+ return (
+ <div className="map-search" role="search">
+ <div className="map-search-row">
+ <input
+ ref={inputRef}
+ type="search"
+ className="map-search-input"
+ placeholder="Search the lineage"
+ aria-label="Search the lineage"
+ value={value}
+ onChange={(event) => onQuery(event.target.value)}
+ onKeyDown={onKeyDown}
+ />
+ {status === "" ? null : <span className="map-search-count">{status}</span>}
+ {state.hash === null && count > 0 ? (
+ <>
+ <button
+ type="button"
+ className="map-search-step"
+ aria-label="Previous hit"
+ title="Previous hit (Shift+Enter)"
+ disabled={index <= 0}
+ onClick={() => onStep(-1)}
+ >
+ ↑
+ </button>
+ <button
+ type="button"
+ className="map-search-step"
+ aria-label="Next hit"
+ title="Next hit (Enter)"
+ disabled={index >= count - 1}
+ onClick={() => onStep(1)}
+ >
+ ↓
+ </button>
+ </>
+ ) : null}
+ </div>
+ {hint === null ? null : <p className="map-search-hint">{hint}</p>}
+ </div>
+ );
+}
diff --git a/packages/template/src/SessionMap.tsx b/packages/template/src/SessionMap.tsx
index b29f5fc..8011903 100644
--- a/packages/template/src/SessionMap.tsx
+++ b/packages/template/src/SessionMap.tsx
@@ -39,6 +39,7 @@ function SessionRow({
epochTitle,
selected,
open,
+ searchHit,
onOpen,
onContinue,
}: {
@@ -48,16 +49,26 @@ function SessionRow({
selected: boolean;
/** Its messages are open below the row. */
open: boolean;
+ /** The session's title or status matches the search (Story 8.14). */
+ searchHit: boolean;
onOpen: (sessionId: string) => void;
onContinue: (continues: NonNullable<ViewSession["messages"][number]["continues"]>) => void;
}) {
const continues = session.messages[0]?.continues;
const style = { top: row.y - row.height / 2, height: row.height };
const count = session.messages.length;
+ const className = [
+ "git-row session-row",
+ selected ? "is-selected" : "",
+ open ? "is-open" : "",
+ searchHit ? "is-search-hit" : "",
+ ]
+ .filter(Boolean)
+ .join(" ");
return (
<button
type="button"
- className={`git-row session-row${selected ? " is-selected" : ""}${open ? " is-open" : ""}`}
+ className={className}
style={style}
aria-expanded={open}
onClick={(event: MouseEvent) => {
@@ -107,6 +118,7 @@ export function SessionMap({
graph,
selectedSessionId,
openIds,
+ highlightSessionIds,
onOpen,
onContinue,
}: {
@@ -115,6 +127,8 @@ export function SessionMap({
selectedSessionId: string | null;
/** Sessions whose messages are open below their rows. */
openIds: ReadonlySet<string>;
+ /** Sessions whose title or status matched the map search. */
+ highlightSessionIds: ReadonlySet<string>;
onOpen: (sessionId: string) => void;
onContinue: (sessionId: string, messageId: string) => void;
}) {
@@ -213,6 +227,7 @@ export function SessionMap({
epochTitle={epochTitle}
selected={selectedSessionId === session.sessionId}
open={openIds.has(session.sessionId)}
+ searchHit={highlightSessionIds.has(session.sessionId)}
onOpen={onOpen}
onContinue={(continues) => onContinue(continues.sessionId, continues.id)}
/>
diff --git a/packages/template/src/styles.css b/packages/template/src/styles.css
index 97afc76..165878e 100644
--- a/packages/template/src/styles.css
+++ b/packages/template/src/styles.css
@@ -54,6 +54,76 @@ main {
min-width: 0;
}
+/* Map search (Story 8.14): in the page head, beside the project switcher. */
+.map-search {
+ flex: none;
+ width: 250px;
+}
+
+.map-search-row {
+ display: flex;
+ align-items: center;
+ gap: 6px;
+}
+
+.map-search-input {
+ flex: 1 1 auto;
+ min-width: 0;
+ padding: 5px 10px;
+ color: var(--text);
+ font: inherit;
+ font-size: 13px;
+ background: #1a1e27;
+ border: 1px solid var(--line);
+ border-radius: 7px;
+}
+
+.map-search-input:focus {
+ outline: 1px solid var(--accent);
+}
+
+.map-search-count {
+ flex: none;
+ color: var(--muted);
+ font-size: 12px;
+ font-variant-numeric: tabular-nums;
+ white-space: nowrap;
+}
+
+.map-search-step {
+ flex: none;
+ width: 24px;
+ height: 26px;
+ padding: 0;
+ color: var(--muted);
+ font: inherit;
+ font-size: 12px;
+ background: #1a1e27;
+ border: 1px solid var(--line);
+ border-radius: 6px;
+ cursor: pointer;
+}
+
+.map-search-step:hover:not(:disabled) {
+ color: var(--text);
+ border-color: var(--accent);
+}
+
+.map-search-step:disabled {
+ cursor: default;
+ opacity: 0.4;
+}
+
+.map-search-hint {
+ margin: 4px 0 0;
+ overflow: hidden;
+ color: var(--muted);
+ font-size: 11px;
+ text-align: right;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
.page-actions {
display: flex;
flex-direction: column;
@@ -1177,6 +1247,17 @@ time {
outline: 1px solid var(--accent);
}
+/* Search hits (Story 8.14): every match is marked, the active one more so. */
+.git-row.is-search-hit {
+ background: rgba(224, 175, 104, 0.12);
+ box-shadow: inset 2px 0 0 var(--warn);
+}
+
+.git-row.is-search-active {
+ background: rgba(224, 175, 104, 0.24);
+ outline: 1px solid var(--warn);
+}
+
.git-more {
color: var(--muted);
font-style: italic;
diff --git a/packages/template/test/search.test.ts b/packages/template/test/search.test.ts
new file mode 100644
index 0000000..6cde79c
--- /dev/null
+++ b/packages/template/test/search.test.ts
@@ -0,0 +1,83 @@
+import { createElement } from "react";
+import { renderToStaticMarkup } from "react-dom/server";
+import { describe, expect, it } from "vitest";
+import type { SearchHit } from "../../cli/src/view/search.js";
+import { type MapSearchState, SearchBox } from "../src/MapSearch.js";
+
+const hit = (index: number): SearchHit => ({
+ sessionId: "s1",
+ sessionTitle: "One",
+ messageId: `h${String(index).padStart(12, "0")}`,
+ label: `m${index + 1}`,
+ at: "2026-10-21T10:00:00.000Z",
+ field: "title",
+ excerpt: `hit ${index}`,
+});
+
+function state(over: Partial<MapSearchState> = {}): MapSearchState {
+ return { hits: [], active: 0, step: 0, hash: null, ...over };
+}
+
+function render(model: MapSearchState, value = "parser"): string {
+ return renderToStaticMarkup(
+ createElement(SearchBox, {
+ value,
+ state: model,
+ onQuery: () => {},
+ onStep: () => {},
+ onClear: () => {},
+ }),
+ );
+}
+
+describe("SearchBox", () => {
+ it("shows the position in the hit list and its buttons", () => {
+ const html = render(state({ hits: [hit(0), hit(1), hit(2), hit(3), hit(4)], active: 2 }));
+ expect(html).toContain("3 / 5");
+ expect(html).toContain('aria-label="Previous hit"');
+ expect(html).toContain('aria-label="Next hit"');
+ expect(html).not.toContain("disabled");
+ });
+
+ it("disables the arrows at the ends and reports no hits", () => {
+ const first = render(state({ hits: [hit(0), hit(1)], active: 0 }));
+ expect(first).toMatch(/<button[^>]*aria-label="Previous hit"[^>]*disabled/);
+ expect(first).not.toMatch(/<button[^>]*aria-label="Next hit"[^>]*disabled/);
+
+ const none = render(state({ hits: [] }));
+ expect(none).toContain("0 hits");
+ expect(none).toContain("no matches");
+ expect(none).not.toContain('aria-label="Next hit"');
+ });
+
+ it("shows a pasted hash and says when it is ambiguous or unknown", () => {
+ const ok = render(
+ state({
+ hash: {
+ kind: "ok",
+ sessionId: "s1",
+ messageId: "h222222222222",
+ label: "m3",
+ title: "Third",
+ },
+ }),
+ );
+ expect(ok).toContain("1 / 1");
+ expect(ok).toContain("→ m3 · Third");
+ // A hash jump needs no arrows, even though the counter is shown.
+ expect(ok).not.toContain('aria-label="Next hit"');
+
+ const ambiguous = render(state({ hash: { kind: "ambiguous", count: 2 } }), "h111111");
+ expect(ambiguous).toContain("2 matches");
+ expect(ambiguous).toContain("type more of the hash");
+
+ const none = render(state({ hash: { kind: "none" } }), "h999999");
+ expect(none).toContain("no recorded message has that hash");
+ });
+
+ it("stays quiet with an empty query", () => {
+ const html = render(state(), "");
+ expect(html).not.toContain("map-search-count");
+ expect(html).not.toContain("map-search-hint");
+ });
+});