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): switch between projects from the map

Eren895abfef4381
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1d4df02..7ab814e 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
+- Project switcher on the map: the most recently active projects as a tab strip, plus a Ctrl/Cmd+K (Cmd+K on macOS) search over every registered project. Each entry shows the project name, its last activity and where it left off (the newest session's next step, or its last message title), and choosing one opens that project's map focused on its own "left off here" — a page of the same local map server when the page is served by it, its `lineage.html` over `file://`. Projects whose directory is gone are left out; the registry is read at build time, with no model calls.
- `codelineage log [dir]` prints the recorded lineage like `git log --graph --oneline`, newest first: per message its short hash, `mN`, time, title, `↩` returns and commit tags, a branch's first message with the branch title, and a header line per session (title, epoch, time span). `--session <id|prefix>` narrows to one session, `-n <count>` limits the messages, `--branches` prints only the branch summaries (title, asked, outcome, open) and `--json` prints the model. `codelineage show <ref> [dir]` prints one message — session, time, parent and children as refs, returns, the branch it sits in with that branch's summary, decisions, agent decisions, work, commits with their git subjects, files and its stored conversation turn (`--no-chat` skips it, `--json` prints the model) — and takes a message hash, a unique prefix of at least six hex characters after the `h`, or `<session-id-prefix>:mN`; an ambiguous prefix lists the candidates and exits non-zero. The map's drill-down shows the message's short hash with a copy button ("Ask your agent: codelineage show <hash>").
- Session start handoff: in an initialized project the `SessionStart` hook (`startup`, `resume`, `clear`) now hands the agent what it needs to continue — that the lineage is recorded and how to read it (`codelineage log|show … -C <dir>`, spelled with the exact bundled CLI path), the rule to run `show <ref>` before answering when the user mentions a message hash or another session's `mN`, and the compressed view of the most recent other session: title, status (goal, pending with items that need the user, next) and branch summaries. The text is cut to ~1,500 tokens, oldest branches first, with a line saying how many were cut. The new `startupContext` setting (default `true`, also editable in the served panel) spends no tokens on it when off, and `log` and `show` now accept `-C <dir>` like `blame`.
diff --git a/packages/cli/src/commands/build.ts b/packages/cli/src/commands/build.ts
index 132bfca..2eb8c86 100644
--- a/packages/cli/src/commands/build.ts
+++ b/packages/cli/src/commands/build.ts
@@ -23,7 +23,8 @@ import { loadAllSessions, loadConfig, loadProject } from "../store/stores.js";
import { type ChatTurn, displayTurn, excerpt, readConversation } from "../transcript.js";
import { buildViewModel, embedViewModel } from "../view/lineage.js";
import type { LineageViewModel, ViewChatTurn, ViewPendingMessage } from "../view/model.js";
-import { buildPanel } from "../view/panel.js";
+import { buildPanel, type CollectedProject, collectRegistryProjects } from "../view/panel.js";
+import { switcherEntries } from "../view/switcher.js";
import { TEMPLATE_HTML } from "../view/template.js";
import { collectTranscripts } from "../view/transcripts.js";
@@ -226,6 +227,17 @@ export async function buildProject(opts: BuildOptions): Promise<LineageViewModel
} catch (err) {
io.warn(`could not update .codelineage/.gitignore: ${(err as Error).message}`);
}
+ // The map's switcher (8.12) and the panel read the same project list; collect
+ // it once. A broken registry is a warning: it must never fail the map.
+ const generatedAt = io.now();
+ let panelProjects: CollectedProject[] = [];
+ try {
+ panelProjects = await collectRegistryProjects(io.env, generatedAt, io.warn, root);
+ } catch (err) {
+ io.warn(`could not read the project list: ${(err as Error).message}`);
+ }
+ const switcher = switcherEntries(panelProjects, root);
+
// The Stop hook skips a turn while this lock is held, and a second build waits
// for the first instead of interleaving reads and writes of the same files.
const model = await withLock(
@@ -240,7 +252,7 @@ export async function buildProject(opts: BuildOptions): Promise<LineageViewModel
project: project.data,
sessions: views.sessions,
path: root,
- generatedAt: io.now(),
+ generatedAt,
transcripts: new Set(transcripts.keys()),
chats: views.chats,
pending: views.pending,
@@ -249,6 +261,7 @@ export async function buildProject(opts: BuildOptions): Promise<LineageViewModel
// count would only be a stale warning about work already scheduled.
unrecorded: config.sessionEndCatchUp ? undefined : views.unrecorded,
});
+ built.switcher = switcher;
// The skill already avoids secrets; this is the safety net before rendering.
const redacted = redactDeep(built);
if (redacted.count > 0)
@@ -269,7 +282,7 @@ export async function buildProject(opts: BuildOptions): Promise<LineageViewModel
env: io.env,
io,
templateHtml: opts.templateHtml ?? TEMPLATE_HTML,
- quietPath: root,
+ projects: panelProjects,
});
} catch (err) {
io.warn(`could not build panel.html: ${(err as Error).message}`);
diff --git a/packages/cli/src/view/model.ts b/packages/cli/src/view/model.ts
index e161968..a950e66 100644
--- a/packages/cli/src/view/model.ts
+++ b/packages/cli/src/view/model.ts
@@ -197,6 +197,23 @@ export interface ViewEpoch {
sessions: ViewSession[];
}
+/**
+ * One entry of the map's project switcher (Story 8.12): a registered project
+ * with the line that says where its work left off.
+ */
+export interface ViewSwitcherProject {
+ name: string;
+ path: string;
+ /** `updatedAt` of the project's most recently updated session. */
+ lastActivity: string | null;
+ /** The newest session's `next`, or its last message title when `next` is empty. */
+ leftOff: string;
+ /** `file://` URL of the project's map. */
+ lineageUrl: string;
+ /** True for the project the page belongs to. */
+ current: boolean;
+}
+
export interface LineageViewModel {
kind: "lineage";
schema: typeof VIEW_SCHEMA;
@@ -209,6 +226,12 @@ export interface LineageViewModel {
epochs: ViewEpoch[];
/** Sessions with no epoch, or with an epoch that no longer exists. */
unassigned: ViewSession[];
+ /**
+ * Every registered project, most recently active first, for the map's
+ * switcher (Story 8.12). Missing directories are left out; older pages simply
+ * have no switcher.
+ */
+ switcher?: ViewSwitcherProject[];
}
/** One project card in the global panel. */
diff --git a/packages/cli/src/view/panel.ts b/packages/cli/src/view/panel.ts
index fb22b29..a81939a 100644
--- a/packages/cli/src/view/panel.ts
+++ b/packages/cli/src/view/panel.ts
@@ -2,11 +2,13 @@ import { pathToFileURL } from "node:url";
import type { Io } from "../io.js";
import { redactDeep } from "../redact.js";
import type { RegistryEntry } from "../schema/config.js";
+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 { type PanelProject, type PanelViewModel, VIEW_SCHEMA } from "./model.js";
+import { type PanelViewModel, VIEW_SCHEMA } from "./model.js";
+import type { SwitcherSource } from "./switcher.js";
import { TEMPLATE_HTML } from "./template.js";
export interface PanelOptions {
@@ -16,10 +18,41 @@ export interface PanelOptions {
templateHtml?: string;
/** A project whose session warnings were already printed by the map build. */
quietPath?: string;
+ /**
+ * Projects the caller already collected (the map build needs the same data for
+ * its switcher); skipped, the panel reads the registry itself.
+ */
+ projects?: CollectedProject[];
}
+/**
+ * A panel card with the one line the map's switcher shows (Story 8.12). The
+ * panel page itself does not embed `leftOff`; the map's switcher does. The
+ * shape lives in `switcher.ts` so the template can import it without this file.
+ */
+export type CollectedProject = SwitcherSource;
+
const PANEL_TITLE = "<title>codelineage — panel</title>";
+/** The title of the newest message in a session, in send order. */
+function lastMessageTitle(session: Session): string {
+ const messages = session.nodes.filter((node) => node.kind === "message");
+ return messages[messages.length - 1]?.title ?? "";
+}
+
+/**
+ * Where the newest session left off: its own `next` step, or the title of its
+ * last message when no next step was recorded.
+ */
+export function leftOffLine(sessions: Session[]): string {
+ const newest = [...sessions].sort((a, b) => {
+ const byTime = Date.parse(b.updatedAt) - Date.parse(a.updatedAt);
+ return Number.isNaN(byTime) ? a.sessionId.localeCompare(b.sessionId) : byTime;
+ })[0];
+ if (!newest) return "";
+ return newest.status.next.trim() || lastMessageTitle(newest);
+}
+
/**
* One card per registry entry. A directory that is gone is marked missing
* instead of failing the panel; one unreadable project is a warning.
@@ -29,8 +62,8 @@ export async function collectPanelProjects(
generatedAt: string,
warn: (line: string) => void,
quietPath?: string,
-): Promise<PanelProject[]> {
- const projects: PanelProject[] = [];
+): Promise<CollectedProject[]> {
+ const projects: CollectedProject[] = [];
for (const entry of entries) {
if (!(await isDirectory(entry.path))) {
projects.push({
@@ -40,12 +73,14 @@ export async function collectPanelProjects(
lastActivity: null,
needsUserCount: 0,
lineageUrl: null,
+ leftOff: "",
});
continue;
}
try {
const sessionWarn = entry.path === quietPath ? () => {} : warn;
- const card = statusCard(await loadAllSessions(entry.path, sessionWarn), generatedAt);
+ const sessions = await loadAllSessions(entry.path, sessionWarn);
+ const card = statusCard(sessions, generatedAt);
projects.push({
name: entry.name,
path: entry.path,
@@ -53,6 +88,7 @@ export async function collectPanelProjects(
lastActivity: card.lastActivity,
needsUserCount: card.pending.filter((item) => item.needsUser).length,
lineageUrl: pathToFileURL(projectPaths(entry.path).html).href,
+ leftOff: leftOffLine(sessions),
});
} catch (err) {
warn(`skipping project ${entry.path}: ${(err as Error).message}`);
@@ -63,12 +99,36 @@ export async function collectPanelProjects(
lastActivity: null,
needsUserCount: 0,
lineageUrl: pathToFileURL(projectPaths(entry.path).html).href,
+ leftOff: "",
});
}
}
return projects;
}
+/**
+ * Reads the registry and collects every project. An unreadable registry is a
+ * warning and no projects, never a failed build: the panel and the map's
+ * switcher are derived state.
+ */
+export async function collectRegistryProjects(
+ env: NodeJS.ProcessEnv,
+ generatedAt: string,
+ warn: (line: string) => void,
+ quietPath?: string,
+): Promise<CollectedProject[]> {
+ const registry = await loadRegistry(env);
+ if (registry.found && !registry.ok) {
+ warn(`registry: ${registry.error}; showing no projects`);
+ return [];
+ }
+ if (registry.found) {
+ for (const warning of registry.warnings) warn(warning);
+ }
+ if (!registry.found || !registry.ok) return [];
+ return await collectPanelProjects(registry.data.projects, generatedAt, warn, quietPath);
+}
+
/**
* Builds the global panel from `projects.json` and `config.json` and writes it
* next to them. The caller decides whether an unwritable global directory is a
@@ -77,13 +137,10 @@ export async function collectPanelProjects(
export async function buildPanel(opts: PanelOptions): Promise<PanelViewModel> {
const { io } = opts;
const generatedAt = io.now();
- const [config, registry] = await Promise.all([loadConfig(opts.env), loadRegistry(opts.env)]);
- if (registry.found && !registry.ok) {
- io.warn(`registry: ${registry.error}; showing no projects`);
- } else if (registry.found) {
- for (const warning of registry.warnings) io.warn(warning);
- }
- const entries = registry.found && registry.ok ? registry.data.projects : [];
+ const config = await loadConfig(opts.env);
+ const projects =
+ opts.projects ??
+ (await collectRegistryProjects(opts.env, generatedAt, io.warn, opts.quietPath));
const model: PanelViewModel = {
kind: "panel",
@@ -99,7 +156,8 @@ export async function buildPanel(opts: PanelOptions): Promise<PanelViewModel> {
gitPolicy: config.gitPolicy,
agents: config.agents,
},
- projects: await collectPanelProjects(entries, generatedAt, io.warn, opts.quietPath),
+ // `leftOff` belongs to the map's switcher; the panel page stays as it was.
+ projects: projects.map(({ leftOff: _leftOff, ...project }) => project),
};
// Same safety net as the map: nothing leaves this process unredacted.
diff --git a/packages/cli/src/view/switcher.ts b/packages/cli/src/view/switcher.ts
new file mode 100644
index 0000000..cf96457
--- /dev/null
+++ b/packages/cli/src/view/switcher.ts
@@ -0,0 +1,72 @@
+import { resolve } from "node:path";
+import type { PanelProject, ViewSwitcherProject } from "./model.js";
+
+/**
+ * What the collection gives the switcher: a panel card plus the line saying
+ * where the project left off. Structural on purpose — this module is imported
+ * by the template too, so it must not pull in the panel builder (and with it
+ * the Node-only store code).
+ */
+export interface SwitcherSource extends PanelProject {
+ leftOff: string;
+}
+
+/**
+ * The map's project switcher (Story 8.12). Pure: it takes the registry projects
+ * the same way the panel collects them and returns what the page's tab strip
+ * and Ctrl/Cmd+K search draw. No disk, no model calls.
+ *
+ * Order is the story's order: most recently active first, a project with no
+ * session after those with one. A project whose directory is gone is left out —
+ * offering a map that cannot be opened is worse than not offering it.
+ */
+export function switcherEntries(
+ projects: SwitcherSource[],
+ currentPath: string,
+): ViewSwitcherProject[] {
+ const current = resolve(currentPath);
+ return projects
+ .filter((project) => !project.missing && project.lineageUrl !== null)
+ .map((project) => ({
+ name: project.name,
+ path: project.path,
+ lastActivity: project.lastActivity,
+ leftOff: project.leftOff,
+ lineageUrl: project.lineageUrl as string,
+ current: resolve(project.path) === current,
+ }))
+ .sort((a, b) => {
+ const byTime = time(b.lastActivity) - time(a.lastActivity);
+ // Two projects with no session have no times to subtract (Infinity - Infinity
+ // is NaN), so they fall through to the name/path order.
+ if (byTime > 0) return 1;
+ if (byTime < 0) return -1;
+ return a.name.localeCompare(b.name) || a.path.localeCompare(b.path);
+ });
+}
+
+/** Tabs drawn in the strip; every other project stays behind the search. */
+export const SWITCHER_RECENT_LIMIT = 6;
+
+/** The tab strip's projects: the list is already most-recently-active first. */
+export function recentSwitcherProjects(projects: ViewSwitcherProject[]): ViewSwitcherProject[] {
+ return projects.slice(0, SWITCHER_RECENT_LIMIT);
+}
+
+/** Case-insensitive search over a project's name, path and "where I left off". */
+export function filterSwitcherProjects(
+ projects: ViewSwitcherProject[],
+ query: string,
+): ViewSwitcherProject[] {
+ const needle = query.trim().toLowerCase();
+ if (needle === "") return projects;
+ return projects.filter((project) =>
+ `${project.name} ${project.path} ${project.leftOff}`.toLowerCase().includes(needle),
+ );
+}
+
+function time(value: string | null): number {
+ if (value === null) return Number.NEGATIVE_INFINITY;
+ const at = Date.parse(value);
+ return Number.isNaN(at) ? Number.NEGATIVE_INFINITY : at;
+}
diff --git a/packages/cli/test/switcher.test.ts b/packages/cli/test/switcher.test.ts
new file mode 100644
index 0000000..2109b1c
--- /dev/null
+++ b/packages/cli/test/switcher.test.ts
@@ -0,0 +1,274 @@
+import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
+import { dirname, join } from "node:path";
+import { pathToFileURL } from "node:url";
+import { beforeEach, describe, expect, it } from "vitest";
+import { buildProject } from "../src/commands/build.js";
+import { init } from "../src/commands/init.js";
+import { Session } from "../src/schema/session.js";
+import { globalPaths, projectPaths } from "../src/store/paths.js";
+import { DATA_ELEMENT_ID, type LineageViewModel } from "../src/view/model.js";
+import { type CollectedProject, leftOffLine } from "../src/view/panel.js";
+import {
+ filterSwitcherProjects,
+ recentSwitcherProjects,
+ SWITCHER_RECENT_LIMIT,
+ switcherEntries,
+} from "../src/view/switcher.js";
+import { envFor, fakeIo, tempDir } from "./helpers.js";
+
+const TEMPLATE = `<!doctype html><html><head><title>codelineage — lineage</title></head><body>
+ <div id="root"></div>
+ <script id="${DATA_ELEMENT_ID}" type="application/json"></script></body></html>`;
+
+const DATA_PREFIX = `<script id="${DATA_ELEMENT_ID}" type="application/json">`;
+
+function embedded(html: string): unknown {
+ const start = html.indexOf(DATA_PREFIX);
+ expect(start).toBeGreaterThanOrEqual(0);
+ const end = html.indexOf("</script>", start);
+ return JSON.parse(html.slice(start + DATA_PREFIX.length, end));
+}
+
+async function write(file: string, data: string): Promise<void> {
+ await mkdir(dirname(file), { recursive: true });
+ await writeFile(file, data);
+}
+
+function collected(overrides: Partial<CollectedProject> & { name: string; path: string }) {
+ const project: CollectedProject = {
+ missing: false,
+ lastActivity: null,
+ needsUserCount: 0,
+ lineageUrl: `file://${overrides.path}/.codelineage/lineage.html`,
+ leftOff: "",
+ ...overrides,
+ };
+ return project;
+}
+
+function session(input: {
+ sessionId: string;
+ updatedAt: string;
+ next?: string;
+ messages?: string[];
+}) {
+ return Session.parse({
+ schema: 1,
+ sessionId: input.sessionId,
+ startedAt: "2026-10-20T00:00:00.000Z",
+ updatedAt: input.updatedAt,
+ status: { goal: "", done: [], pending: [], next: input.next ?? "" },
+ nodes: (input.messages ?? []).map((title, index) => ({
+ id: `m${index + 1}`,
+ kind: "message",
+ title,
+ parent: index === 0 ? null : `m${index}`,
+ at: "2026-10-20T00:00:00.000Z",
+ })),
+ });
+}
+
+describe("switcherEntries", () => {
+ it("orders by last activity, marks the current project and skips missing ones", () => {
+ const projects = [
+ collected({
+ name: "older",
+ path: "/work/older",
+ lastActivity: "2026-10-21T08:00:00.000Z",
+ leftOff: "Older next step.",
+ }),
+ collected({ name: "gone", path: "/work/gone", missing: true, lineageUrl: null }),
+ collected({ name: "never", path: "/work/never", leftOff: "Never ran a session." }),
+ collected({ name: "twin", path: "/work/twin-b" }),
+ collected({ name: "twin", path: "/work/twin-a" }),
+ collected({
+ name: "current",
+ path: "/work/current",
+ lastActivity: "2026-10-24T10:00:00.000Z",
+ leftOff: "Where we left off.",
+ }),
+ ];
+
+ // `resolve` compares the paths, so a trailing slash still marks the page's own project.
+ const entries = switcherEntries(projects, "/work/current/");
+
+ // Projects with no session share the end, ordered by name and then path.
+ expect(entries.map((entry) => entry.name)).toEqual([
+ "current",
+ "older",
+ "never",
+ "twin",
+ "twin",
+ ]);
+ expect(entries.slice(3).map((entry) => entry.path)).toEqual(["/work/twin-a", "/work/twin-b"]);
+ expect(entries[0]).toEqual({
+ name: "current",
+ path: "/work/current",
+ lastActivity: "2026-10-24T10:00:00.000Z",
+ leftOff: "Where we left off.",
+ lineageUrl: "file:///work/current/.codelineage/lineage.html",
+ current: true,
+ });
+ expect(entries[1]?.current).toBe(false);
+ expect(entries[2]?.lastActivity).toBeNull();
+ });
+});
+
+describe("leftOffLine", () => {
+ it("takes the newest session's next step", () => {
+ const sessions = [
+ session({ sessionId: "new", updatedAt: "2026-10-24T10:00:00.000Z", next: "Ship it." }),
+ session({ sessionId: "old", updatedAt: "2026-10-20T10:00:00.000Z", next: "Old step." }),
+ ];
+ expect(leftOffLine(sessions)).toBe("Ship it.");
+ });
+
+ it("falls back to the newest session's last message title, then to empty", () => {
+ const sessions = [
+ session({
+ sessionId: "s1",
+ updatedAt: "2026-10-24T10:00:00.000Z",
+ messages: ["First", "Last message title"],
+ }),
+ ];
+ expect(leftOffLine(sessions)).toBe("Last message title");
+ expect(leftOffLine([])).toBe("");
+ });
+});
+
+describe("filterSwitcherProjects", () => {
+ const projects = switcherEntries(
+ [
+ collected({
+ name: "codelineage",
+ path: "/work/codelineage",
+ lastActivity: "2026-10-24T10:00:00.000Z",
+ leftOff: "Add the project switcher.",
+ }),
+ collected({
+ name: "start-project",
+ path: "/work/start-project",
+ lastActivity: "2026-10-23T10:00:00.000Z",
+ leftOff: "Write the push commands.",
+ }),
+ ],
+ "/work/codelineage",
+ );
+
+ it("matches name, path and the left-off line, case-insensitively", () => {
+ expect(filterSwitcherProjects(projects, "CODE").map((p) => p.name)).toEqual(["codelineage"]);
+ expect(filterSwitcherProjects(projects, "start-project").map((p) => p.name)).toEqual([
+ "start-project",
+ ]);
+ expect(filterSwitcherProjects(projects, "push commands").map((p) => p.name)).toEqual([
+ "start-project",
+ ]);
+ expect(filterSwitcherProjects(projects, "nothing like this")).toEqual([]);
+ });
+
+ it("returns every project for an empty query and limits the tab strip", () => {
+ expect(filterSwitcherProjects(projects, " ")).toHaveLength(2);
+ const many = switcherEntries(
+ Array.from({ length: SWITCHER_RECENT_LIMIT + 3 }, (_value, index) =>
+ collected({ name: `p${index}`, path: `/work/p${index}` }),
+ ),
+ "/work/p0",
+ );
+ expect(recentSwitcherProjects(many)).toHaveLength(SWITCHER_RECENT_LIMIT);
+ expect(recentSwitcherProjects(many)[0]?.name).toBe("p0");
+ });
+});
+
+describe("map build", () => {
+ let dir: string;
+ let env: NodeJS.ProcessEnv;
+
+ beforeEach(async () => {
+ dir = await tempDir();
+ env = envFor(dir);
+ });
+
+ async function initProject(root: string): Promise<void> {
+ await mkdir(root, { recursive: true });
+ await init(root, { retention: "keep", language: "auto" }, fakeIo(env));
+ }
+
+ async function saveSession(root: string, data: unknown): Promise<void> {
+ const id = (data as { sessionId: string }).sessionId;
+ await write(projectPaths(root).session(id), JSON.stringify(data));
+ }
+
+ it("embeds every registered project, most recently active first, at build time", async () => {
+ const alpha = join(dir, "alpha");
+ const beta = join(dir, "beta");
+ const gone = join(dir, "gone");
+ await initProject(alpha);
+ await initProject(beta);
+ await initProject(gone);
+ await saveSession(alpha, {
+ schema: 1,
+ sessionId: "a1",
+ title: "Alpha work",
+ startedAt: "2026-10-20T10:00:00.000Z",
+ updatedAt: "2026-10-24T10:00:00.000Z",
+ status: { goal: "", done: [], pending: [], next: "Ship the switcher." },
+ nodes: [],
+ });
+ await saveSession(beta, {
+ schema: 1,
+ sessionId: "b1",
+ title: "Beta work",
+ startedAt: "2026-10-21T10:00:00.000Z",
+ updatedAt: "2026-10-22T10:00:00.000Z",
+ status: { goal: "", done: [], pending: [], next: "" },
+ nodes: [
+ { id: "m1", kind: "message", title: "First beta message", parent: null },
+ { id: "m2", kind: "message", title: "Where beta left off", parent: "m1" },
+ ],
+ });
+ await rm(gone, { recursive: true });
+
+ const io = fakeIo(env);
+ await buildProject({ dir: alpha, io, templateHtml: TEMPLATE });
+
+ const model = embedded(await readFile(projectPaths(alpha).html, "utf8")) as LineageViewModel;
+ expect(model.switcher).toEqual([
+ {
+ name: "alpha",
+ path: alpha,
+ lastActivity: "2026-10-24T10:00:00.000Z",
+ leftOff: "Ship the switcher.",
+ lineageUrl: pathToFileURL(projectPaths(alpha).html).href,
+ current: true,
+ },
+ {
+ name: "beta",
+ path: beta,
+ lastActivity: "2026-10-22T10:00:00.000Z",
+ leftOff: "Where beta left off",
+ lineageUrl: pathToFileURL(projectPaths(beta).html).href,
+ current: false,
+ },
+ ]);
+
+ // The panel page keeps its card shape; `leftOff` lives only in the map.
+ const panel = embedded(await readFile(globalPaths(env).panel, "utf8")) as {
+ projects: Record<string, unknown>[];
+ };
+ expect(panel.projects.map((project) => project.name)).toEqual(["alpha", "beta", "gone"]);
+ expect(panel.projects[0]).not.toHaveProperty("leftOff");
+ });
+
+ it("keeps the map usable when the registry cannot be read", async () => {
+ const root = join(dir, "solo");
+ await initProject(root);
+ await write(globalPaths(env).registry, "{nope");
+
+ const io = fakeIo(env);
+ await buildProject({ dir: root, io, templateHtml: TEMPLATE });
+
+ const model = embedded(await readFile(projectPaths(root).html, "utf8")) as LineageViewModel;
+ expect(model.switcher).toEqual([]);
+ expect(io.warnings.join("\n")).toMatch(/^registry: invalid JSON/);
+ });
+});
diff --git a/packages/template/src/App.tsx b/packages/template/src/App.tsx
index a95bb59..d44249c 100644
--- a/packages/template/src/App.tsx
+++ b/packages/template/src/App.tsx
@@ -1,6 +1,7 @@
import type { LineageViewModel, StatusCard } from "../../cli/src/view/model.js";
import { formatTime } from "./format.js";
import { Graph } from "./Graph.js";
+import { ProjectSwitcher } from "./ProjectSwitcher.js";
function StatusPanel({ status }: { status: StatusCard }) {
return (
@@ -53,6 +54,8 @@ export function App({ model }: { model: LineageViewModel }) {
return (
<main>
<div className="page-head">
+ <ProjectSwitcher model={model} />
+
<header className="project">
<div>
<h1>{model.project.name}</h1>
diff --git a/packages/template/src/Graph.tsx b/packages/template/src/Graph.tsx
index 31d4ab5..011b6d1 100644
--- a/packages/template/src/Graph.tsx
+++ b/packages/template/src/Graph.tsx
@@ -86,13 +86,22 @@ const nodeTypes: NodeTypes = {
};
/**
- * The message a `#s=<sessionId>&m=<messageId>` URL asks for (Story 8.8:
- * `codelineage blame` prints such a URL). The session opens and the message's
- * drill-down is shown; a message id the record no longer holds opens the session.
+ * The place a URL asks for. `#s=<sessionId>&m=<messageId>` (Story 8.8:
+ * `codelineage blame` prints such a URL) opens that session and message;
+ * `#focus=head` is what the project switcher uses (8.12) — the newest message,
+ * i.e. where the work left off. The session opens and the message's drill-down
+ * is shown; a message id the record no longer holds opens the session.
*/
function readTarget(model: LineageViewModel): { sessionId: string; messageId?: string } | null {
if (typeof window === "undefined") return null;
const params = new URLSearchParams(window.location.hash.replace(/^#/, ""));
+ if (params.get("focus") === "head") {
+ const head = headOf(model);
+ if (head === null) return null;
+ return head.messageId === null
+ ? { sessionId: head.sessionId }
+ : { sessionId: head.sessionId, messageId: head.messageId };
+ }
const sessionId = params.get("s");
if (sessionId === null || sessionId === "") return null;
const session = findSession(model, sessionId);
diff --git a/packages/template/src/ProjectSwitcher.tsx b/packages/template/src/ProjectSwitcher.tsx
new file mode 100644
index 0000000..996b911
--- /dev/null
+++ b/packages/template/src/ProjectSwitcher.tsx
@@ -0,0 +1,173 @@
+import {
+ type KeyboardEvent as ReactKeyboardEvent,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import type { LineageViewModel, ViewSwitcherProject } from "../../cli/src/view/model.js";
+import { filterSwitcherProjects, recentSwitcherProjects } from "../../cli/src/view/switcher.js";
+import { isLivePage } from "./data.js";
+import { formatDate, formatTime } from "./format.js";
+
+/**
+ * The map's project switcher (Story 8.12): the most recently active projects as
+ * a tab strip, and Ctrl/Cmd+K for a search over every registered project. Each
+ * entry carries the line that says where its work left off, and choosing one
+ * opens that project's map at its own "left off here". Ordering and filtering
+ * live in `view/switcher.ts` so they are testable without a DOM.
+ */
+
+/** The map of another project, at its HEAD: the server path when served by it. */
+export function projectMapHref(entry: ViewSwitcherProject): string {
+ const base = isLivePage() ? `/map?dir=${encodeURIComponent(entry.path)}` : entry.lineageUrl;
+ return `${base}#focus=head`;
+}
+
+/** The key label the user expects; the handler accepts both Ctrl and Cmd. */
+function shortcutLabel(): string {
+ return /mac/i.test(navigator.platform) ? "⌘ K" : "Ctrl K";
+}
+
+export function ProjectSwitcher({ model }: { model: LineageViewModel }) {
+ const projects = useMemo(() => model.switcher ?? [], [model.switcher]);
+ const [open, setOpen] = useState(false);
+ const [query, setQuery] = useState("");
+ const [active, setActive] = useState(0);
+ const inputRef = useRef<HTMLInputElement>(null);
+
+ const results = useMemo(() => filterSwitcherProjects(projects, query), [projects, query]);
+ const recent = recentSwitcherProjects(projects);
+
+ // Ctrl/Cmd+K opens (and closes) the search anywhere on the page; Escape closes.
+ useEffect(() => {
+ function onKey(event: KeyboardEvent): void {
+ if ((event.metaKey || event.ctrlKey) && event.key.toLowerCase() === "k") {
+ event.preventDefault();
+ setOpen((value) => !value);
+ setQuery("");
+ setActive(0);
+ } else if (event.key === "Escape") {
+ setOpen(false);
+ }
+ }
+ window.addEventListener("keydown", onKey);
+ return () => window.removeEventListener("keydown", onKey);
+ }, []);
+
+ useEffect(() => {
+ if (open) inputRef.current?.focus();
+ }, [open]);
+
+ if (projects.length === 0) return null;
+
+ function go(entry: ViewSwitcherProject): void {
+ window.location.href = projectMapHref(entry);
+ }
+
+ function onSearchKeyDown(event: ReactKeyboardEvent<HTMLInputElement>): void {
+ if (event.key === "ArrowDown") {
+ event.preventDefault();
+ setActive((index) => Math.min(index + 1, Math.max(results.length - 1, 0)));
+ } else if (event.key === "ArrowUp") {
+ event.preventDefault();
+ setActive((index) => Math.max(index - 1, 0));
+ } else if (event.key === "Enter") {
+ event.preventDefault();
+ const hit = results[active];
+ if (hit) go(hit);
+ }
+ }
+
+ return (
+ <div className="switcher">
+ <nav className="switcher-tabs" aria-label="Recent projects">
+ {recent.map((project) => (
+ <a
+ key={project.path}
+ aria-current={project.current ? "page" : undefined}
+ className={project.current ? "switcher-tab is-current" : "switcher-tab"}
+ href={projectMapHref(project)}
+ title={project.leftOff || project.path}
+ >
+ <span className="switcher-name">{project.name}</span>
+ <span className="switcher-time">{formatDate(project.lastActivity)}</span>
+ </a>
+ ))}
+ <button
+ type="button"
+ className="switcher-more"
+ onClick={() => {
+ setOpen(true);
+ setQuery("");
+ setActive(0);
+ }}
+ aria-haspopup="dialog"
+ >
+ All projects <kbd>{shortcutLabel()}</kbd>
+ </button>
+ </nav>
+
+ {open ? (
+ <div
+ className="switcher-overlay"
+ onMouseDown={(event) => {
+ if (event.target === event.currentTarget) setOpen(false);
+ }}
+ >
+ <div
+ className="switcher-dialog"
+ role="dialog"
+ aria-modal="true"
+ aria-label="Switch project"
+ >
+ <input
+ ref={inputRef}
+ className="switcher-input"
+ role="combobox"
+ aria-expanded="true"
+ aria-controls="switcher-results"
+ aria-activedescendant={results[active] ? `switcher-${active}` : undefined}
+ aria-autocomplete="list"
+ placeholder="Search projects by name, path or where you left off…"
+ value={query}
+ onChange={(event) => {
+ setQuery(event.target.value);
+ setActive(0);
+ }}
+ onKeyDown={onSearchKeyDown}
+ />
+ {results.length === 0 ? (
+ <p className="empty switcher-none">No project matches.</p>
+ ) : (
+ <ul className="switcher-results" id="switcher-results" role="listbox">
+ {results.map((project, index) => (
+ <li
+ key={project.path}
+ id={`switcher-${index}`}
+ role="option"
+ aria-selected={index === active}
+ className={index === active ? "switcher-result is-active" : "switcher-result"}
+ onMouseMove={() => setActive(index)}
+ onClick={() => go(project)}
+ >
+ <span className="switcher-result-head">
+ <span className="switcher-name">{project.name}</span>
+ {project.current ? <span className="badge">current</span> : null}
+ <span className="switcher-time">{formatTime(project.lastActivity)}</span>
+ </span>
+ <span className="switcher-leftoff">
+ {project.leftOff || "Nothing recorded yet."}
+ </span>
+ <span className="switcher-path">{project.path}</span>
+ </li>
+ ))}
+ </ul>
+ )}
+ <p className="switcher-hint">↑↓ to move · Enter to open · Esc to close</p>
+ </div>
+ </div>
+ ) : null}
+ </div>
+ );
+}
diff --git a/packages/template/src/fixture.ts b/packages/template/src/fixture.ts
index 9417cc3..2b91ea3 100644
--- a/packages/template/src/fixture.ts
+++ b/packages/template/src/fixture.ts
@@ -189,4 +189,23 @@ export const fixture: LineageViewModel = {
},
),
],
+ // Story 8.12: the switcher's data, as `build` collects it from the registry.
+ switcher: [
+ {
+ name: "codelineage",
+ path: "/home/dev/codelineage",
+ lastActivity: "2026-10-24T11:42:00.000Z",
+ leftOff: "Render the fixture through the template and check the single-file build.",
+ lineageUrl: "file:///home/dev/codelineage/.codelineage/lineage.html",
+ current: true,
+ },
+ {
+ name: "start-project",
+ path: "/home/dev/start-project",
+ lastActivity: "2026-10-23T18:05:00.000Z",
+ leftOff: "Write the push commands for the release notes.",
+ lineageUrl: "file:///home/dev/start-project/.codelineage/lineage.html",
+ current: false,
+ },
+ ],
};
diff --git a/packages/template/src/styles.css b/packages/template/src/styles.css
index 36b6d99..9d3e8bd 100644
--- a/packages/template/src/styles.css
+++ b/packages/template/src/styles.css
@@ -70,6 +70,181 @@ ul {
padding-left: 20px;
}
+/* Project switcher (Story 8.12): a tab strip of recent projects and a
+ Ctrl/Cmd+K search over every registered one. */
+.switcher {
+ margin-bottom: 18px;
+}
+
+.switcher-tabs {
+ display: flex;
+ align-items: stretch;
+ gap: 6px;
+ overflow-x: auto;
+ padding-bottom: 2px;
+}
+
+.switcher-tab {
+ display: flex;
+ flex: none;
+ align-items: baseline;
+ gap: 8px;
+ max-width: 220px;
+ padding: 6px 12px;
+ color: var(--muted);
+ font-size: 13px;
+ text-decoration: none;
+ background: #151922;
+ border: 1px solid var(--line);
+ border-radius: 8px;
+}
+
+.switcher-tab:hover {
+ color: var(--text);
+ border-color: #3b4557;
+}
+
+.switcher-tab.is-current {
+ color: var(--text);
+ background: #1d2431;
+ border-color: var(--accent);
+}
+
+.switcher-name {
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.switcher-time {
+ flex: none;
+ color: var(--muted);
+ font-size: 11px;
+ white-space: nowrap;
+}
+
+.switcher-more {
+ flex: none;
+ padding: 5px 12px;
+ color: var(--muted);
+ font: inherit;
+ font-size: 13px;
+ background: transparent;
+ border: 1px dashed var(--line);
+ border-radius: 8px;
+ cursor: pointer;
+}
+
+.switcher-more:hover {
+ color: var(--text);
+ border-color: var(--accent);
+}
+
+.switcher-more kbd {
+ padding: 1px 4px;
+ font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
+ font-size: 10px;
+ border: 1px solid var(--line);
+ border-radius: 4px;
+}
+
+.switcher-overlay {
+ position: fixed;
+ inset: 0;
+ z-index: 200;
+ display: flex;
+ align-items: flex-start;
+ justify-content: center;
+ padding: 12vh 16px 32px;
+ background: rgba(5, 7, 10, 0.62);
+}
+
+.switcher-dialog {
+ width: min(640px, 100%);
+ padding: 12px;
+ background: var(--panel);
+ border: 1px solid var(--line);
+ border-radius: 12px;
+ box-shadow: 0 20px 60px rgba(0, 0, 0, 0.5);
+}
+
+.switcher-input {
+ width: 100%;
+ padding: 9px 12px;
+ color: var(--text);
+ font: inherit;
+ background: var(--bg);
+ border: 1px solid var(--line);
+ border-radius: 8px;
+}
+
+.switcher-input:focus {
+ outline: 1px solid var(--accent);
+}
+
+.switcher-results {
+ max-height: 50vh;
+ margin: 8px 0 0;
+ padding: 0;
+ overflow-y: auto;
+ list-style: none;
+}
+
+.switcher-result {
+ padding: 8px 10px;
+ border: 1px solid transparent;
+ border-radius: 8px;
+ cursor: pointer;
+}
+
+.switcher-result.is-active {
+ background: #243040;
+ border-color: var(--accent);
+}
+
+.switcher-result-head {
+ display: flex;
+ align-items: baseline;
+ gap: 8px;
+}
+
+.switcher-result-head .switcher-name {
+ font-size: 14px;
+ font-weight: 600;
+}
+
+.switcher-result-head .switcher-time {
+ margin-left: auto;
+}
+
+.switcher-leftoff {
+ display: -webkit-box;
+ margin-top: 2px;
+ overflow: hidden;
+ font-size: 13px;
+ -webkit-box-orient: vertical;
+ -webkit-line-clamp: 2;
+}
+
+.switcher-path {
+ display: block;
+ overflow: hidden;
+ color: var(--muted);
+ font-size: 11px;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+}
+
+.switcher-hint {
+ margin: 8px 2px 0;
+ color: var(--muted);
+ font-size: 11px;
+}
+
+.switcher-none {
+ padding: 8px 10px;
+}
+
.project {
display: flex;
align-items: flex-end;
@@ -1021,3 +1196,4 @@ time {
color: var(--l5);
font-size: 12px;
}
+
diff --git a/specs/codelineage-mvp.md b/specs/codelineage-mvp.md
index d05bf67..38b7674 100644
--- a/specs/codelineage-mvp.md
+++ b/specs/codelineage-mvp.md
@@ -54,6 +54,13 @@ these records into static HTML:
switching into each project map. Settings are editable on the page the local
server serves (`POST /api/config`, same-origin, per-server token) and read-only
from `file://`.
+- **Project switcher** (on every map): a tab strip of the most recently active
+ projects and a Ctrl/Cmd+K search over every registered project, each entry
+ showing the project name, its last activity and where it left off (the newest
+ session's `next`, or its last message title). Choosing one opens that project's
+ map at its own "left off here" — a page of the same local server over http, the
+ `lineage.html` file over `file://`. A project whose directory is gone is left
+ out. The data comes from the registry at build time; no model calls.
Sessions are not a separate view. A session is a level of the project tree.