Git for the intent behind agent-written code. Records what your coding agent decided and why, and links every commit to it.
JavaScript ai-codingclaudeclaude-codeclaude-code-pluginclicoding-agentsdeveloper-toolsgitllmtypescript
feat(git): carry the session record with code commits
Eren89571c1c2426
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7af97b8..31f99a3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,9 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).## [Unreleased]+### Added+- The record travels with the repo: `init` now answers **yes** to committing the session records, which puts `.cogit/sessions/` and `project.json` in git while a generated `.cogit/.gitignore` keeps the local state (conversations, hooks state, locks, inbox, map, `HEAD`, backups) out; `cogit config git commit|ignore` switches an existing project without deleting anything. A git `pre-commit` hook stages the current session's record files (`.cogit/HEAD`, written by a new `UserPromptSubmit` hook) with the next code commit, but never creates a record-only commit and works with `git commit -a` and `git commit <paths>`. Each session gets an `author` (git `user.name`, else the OS user) on its first write, shown on the map's session row and in `log`, and `project.json` is written with sorted keys and one epoch per line so git merges it. New settings `shareConversations` (commit the raw chat too, off by default) and `recordCommit` (`ask`, `auto` or `off`: what to do with the messages recorded after the last code commit) are in Settings → Recording; a clone without the chat says "This conversation is not on this machine".+### Changed- Map layout and readability: the head and the map share a centred 8-of-12 content column (full width with 16 px gutters below 1100 px), the page itself no longer scrolls so the head stays put and the map fills the rest of the window, and a wheel anywhere on the page — gutters and head included — pans the map (Ctrl+wheel still zooms, Shift+wheel pans horizontally). A message title keeps a minimum width, so the branch and "continues" chips truncate with an ellipsis instead of squeezing it into a one-letter column. Small text (dates, `mN`, counts, "not summarized yet") now reaches WCAG AA contrast, and the map has a light theme for browsers that ask for one.- Renamed the product to **cogit** (*Cogito, ergo commit.*): the npm package and `cogit` bin, the Claude Code plugin and its `cogit:record` skill, the project dir `.cogit/`, the global dir `~/.config/cogit`, the env vars `COGIT_HOME` / `COGIT_DISABLE` (the old names still work for one minor version), the map file `map.html` and the page titles. The first cogit command or hook migrates silently: it renames an existing `.codelineage/`, moves `~/.config/codelineage` and fixes the `.gitignore` lines, or leaves both in place and warns once when both directories exist.diff --git a/README.md b/README.mdindex c3474e8..b643ab8 100644--- a/README.md+++ b/README.md@@ -18,17 +18,30 @@ cogit open # open the map in the browser`init` also installs the Claude Code side: the lineage skill updates the record asyou work, the hooks rebuild the map after each turn and at the end of a session.-## Privacy+## Privacy and what travels with the repo- The skill records decisions and rationale, never raw chat; session files holdtitles and summaries only.+- `init` asks whether to commit the session records and now answers **yes** by+ default: `.cogit/sessions/` and `project.json` travel with a clone, while+ `.cogit/.gitignore` keeps local state (`conversations/`, `state/`, `locks/`,+ `inbox/`, `map.html`, `HEAD`, backups) out. Switch an existing project with+ `cogit config git commit|ignore`.+- A git `pre-commit` hook stages the current session's record with the code+ commit, so a clone keeps the "why". It never creates a record-only commit.- The map's Conversation panel needs the real turns, so `build` reads them fromClaude Code's local transcript and keeps a copy in`.cogit/conversations/<sessionId>.jsonl.gz`. This store lets the panel keepworking after Claude Code deletes the transcript.-- That copy never goes into git: `init` writes `.cogit/.gitignore` with- `conversations/`, even when you chose to commit `.cogit/`, and every build- makes sure the line is there.+- That copy stays on this machine by default. Turn on `shareConversations`+ (Settings → Recording, or `cogit config set shareConversations true`) to commit+ it too; a clone without it says "This conversation is not on this machine".+- Each session records its author (git `user.name`, else the OS user) on its+ first write, shown on the map and in `cogit log`.+- `recordCommit` controls the last messages after the last code commit: `ask`+ (default) offers a `chore(cogit): record <title>` commit at the next session+ start, `auto` commits exactly the record paths at session end, `off` does+ nothing. Both settings are in Settings → Recording.- Both the page and the conversation store go through the same redaction pass(common key and token patterns) before anything is written.- Claude Code deletes transcripts after `cleanupPeriodDays` (30 days by default).diff --git a/packages/cli/hooks/hooks.json b/packages/cli/hooks/hooks.jsonindex 06431f3..767729d 100644--- a/packages/cli/hooks/hooks.json+++ b/packages/cli/hooks/hooks.json@@ -35,6 +35,18 @@}]}+ ],+ "UserPromptSubmit": [+ {+ "hooks": [+ {+ "type": "command",+ "command": "node",+ "args": ["${CLAUDE_PLUGIN_ROOT}/dist/cli.js", "hook", "promptsubmit"],+ "timeout": 5+ }+ ]+ }]}}diff --git a/packages/cli/src/commands/backfill.ts b/packages/cli/src/commands/backfill.tsindex 0bf6f3f..720b1cb 100644--- a/packages/cli/src/commands/backfill.ts+++ b/packages/cli/src/commands/backfill.ts@@ -2,6 +2,7 @@ import { spawn } from "node:child_process";import { CliError, type Io } from "../io.js";import { hashTurns, isRecorded, type SessionMessage, upgradeSessionIds } from "../messages.js";import type { Session } from "../schema/session.js";+import { maybeAutoCommit } from "../session-git.js";import { applyEvents, readEvents } from "../store/events.js";import { LockBusyError, withLock } from "../store/lock.js";import { projectPaths } from "../store/paths.js";@@ -210,6 +211,8 @@ export async function backfillTail(dir: string, sessionId: string, io: Io): Prom}if (turns.length === 0) {io.out(`session ${sessionId} has nothing to catch up`);+ // Story 9.3: `recordCommit: auto` still commits what an earlier update wrote.+ await maybeAutoCommit(root, sessionId, io.env);return;}@@ -220,4 +223,7 @@ export async function backfillTail(dir: string, sessionId: string, io: Io): Promconst stdout = await runClaude(prompt, config.catchUpModel, io.env);const payload = { ...agentRecord(resultText(stdout)), sessionId };await sessionWrite({ dir: root }, io, async () => JSON.stringify(payload));+ // The session end wrote the last messages after the last code commit; auto+ // mode commits exactly those record files now (Story 9.3).+ await maybeAutoCommit(root, sessionId, io.env);}diff --git a/packages/cli/src/commands/build.ts b/packages/cli/src/commands/build.tsindex d9879ff..c5ce126 100644--- a/packages/cli/src/commands/build.ts+++ b/packages/cli/src/commands/build.ts@@ -1,9 +1,9 @@import {- ensureConversationGitignore,findGitRoot,projectFiles,readCommitFiles,readCommitSubjects,+ refreshCogitGitignore,} from "../git.js";import { CliError, type Io } from "../io.js";import {@@ -241,10 +241,11 @@ export async function buildProject(opts: BuildOptions): Promise<LineageViewModelfor (const warning of project.warnings) io.warn(warning);const paths = projectPaths(root);- // Projects initialized before the conversation store get the privacy line on+ const config = await loadConfig(io.env);+ // Projects initialized before the conversation store get the privacy rules on// their next build; an unwritable record must never fail the map.try {- await ensureConversationGitignore(root);+ await refreshCogitGitignore(root, config.shareConversations);} catch (err) {io.warn(`could not update .cogit/.gitignore: ${(err as Error).message}`);}@@ -266,7 +267,6 @@ export async function buildProject(opts: BuildOptions): Promise<LineageViewModelasync () => {const sessions = await loadAllSessions(root, io.warn);const transcripts = await collectTranscripts(io.env);- const config = await loadConfig(io.env);const views = await readTranscriptViews(sessions, transcripts, root, io);const commits = await commitInfo(root, views.sessions);const built = buildViewModel({diff --git a/packages/cli/src/commands/config.ts b/packages/cli/src/commands/config.tsindex 042be7c..319a7b1 100644--- a/packages/cli/src/commands/config.ts+++ b/packages/cli/src/commands/config.ts@@ -1,8 +1,17 @@+import { ensureCogitGitignore, ensureGitignore, findGitRoot, type GitPolicy } from "../git.js";+import { installGitHook } from "../git-hooks.js";import { CliError, type Io } from "../io.js";import { Config, type RegistryEntry } from "../schema/config.js";+import { refreshShareConversations } from "../share.js";import { isDirectory } from "../store/fs.js";import { resolveProjectRoot } from "../store/root.js";-import { loadConfig, loadRegistry, updateConfig, updateRegistry } from "../store/stores.js";+import {+ loadConfig,+ loadProject,+ loadRegistry,+ updateConfig,+ updateRegistry,+} from "../store/stores.js";export const CONFIG_KEYS = Object.keys(Config.shape).filter((k) => k !== "schema") as Exclude<keyof Config,@@ -48,9 +57,33 @@ export async function configSet(key: string, raw: string, io: Io): Promise<void>throw new CliError(`invalid value for ${key}: ${next.error.issues[0]?.message ?? "rejected"}`);}await updateConfig((c) => ({ ...c, [key]: next.data[key] }), io.env);+ // Sharing the raw chat changes the project ignore files, not just the config.+ if (key === "shareConversations")+ await refreshShareConversations(io.env, next.data.shareConversations);io.out(`${key} = ${JSON.stringify(next.data[key])}`);}+/**+ * `cogit config git commit|ignore` (Story 9.3): switches an existing project.+ * Both ignore files are edited; no record file is ever deleted, so switching to+ * `ignore` leaves what git already tracks alone.+ */+export async function configGit(dir: string, policy: GitPolicy, io: Io): Promise<void> {+ const { root } = await resolveProjectRoot(dir);+ const project = await loadProject(root);+ if (!project.found) throw new CliError(`${root} is not initialized; run \`cogit init\` first`);+ if (!project.ok) throw new CliError(project.error);+ if ((await findGitRoot(root)) === undefined)+ throw new CliError(`${root} is not in a git repository`);++ const added = await ensureGitignore(root, policy);+ const config = await loadConfig(io.env);+ await ensureCogitGitignore(root, policy, config.shareConversations);+ if (policy === "commit") await installGitHook(root, "pre-commit");+ io.out(`Git policy for ${project.data.name}: ${policy}`);+ if (added.length > 0) io.out(`Added to .gitignore: ${added.join(", ")}`);+}+/*** Stops the SessionStart setup hint in a project ("don't ask again"). The list is* keyed by the main checkout's root, so a linked worktree is silenced with it.diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.tsindex bf54c90..571f2fc 100644--- a/packages/cli/src/commands/init.ts+++ b/packages/cli/src/commands/init.ts@@ -9,11 +9,14 @@ import {setRetention,} from "../claude-settings.js";import {- ensureConversationGitignore,+ cogitIgnored,+ ensureCogitGitignore,ensureGitignore,findGitRoot,type GitPolicy,+ refreshCogitGitignore,} from "../git.js";+import { installGitHook } from "../git-hooks.js";import { CliError, type Io } from "../io.js";import { readJson } from "../store/fs.js";import { migrateProject } from "../store/migrate.js";@@ -136,6 +139,46 @@ export async function register(io: Io, root: string, name: string): Promise<void);}+/**+ * Applies a policy to the two ignore files and, under `commit`, installs the git+ * pre-commit hook that carries the current session's record (Story 9.3). Each+ * step is best-effort: a read-only `.gitignore` or a repository git will not+ * report hooks for must never fail setup.+ */+async function applyGitPolicy(+ io: Io,+ root: string,+ policy: GitPolicy,+ shareConversations: boolean,+): Promise<void> {+ const added: string[] = [];+ await bestEffort(io, "could not update .gitignore", async () => {+ added.push(...(await ensureGitignore(root, policy)));+ });+ if (added.length > 0) io.out(`Added to .gitignore: ${added.join(", ")}`);+ await bestEffort(io, "could not write .cogit/.gitignore", () =>+ ensureCogitGitignore(root, policy, shareConversations),+ );+ if (policy === "commit")+ await bestEffort(io, "could not install the pre-commit hook", () =>+ installGitHook(root, "pre-commit"),+ );+}++/**+ * Brings an already initialized project up to date: a repository that commits+ * its records gets the new `.cogit/.gitignore` and the hook, without changing the+ * policy the user chose at setup.+ */+async function refreshGitIntegration(io: Io, root: string): Promise<void> {+ if ((await findGitRoot(root)) === undefined) return;+ await bestEffort(io, "could not refresh the git integration", async () => {+ if (await cogitIgnored(root)) return;+ await refreshCogitGitignore(root, (await loadConfig(io.env)).shareConversations);+ await installGitHook(root, "pre-commit");+ });+}+export async function init(dir: string, opts: InitOptions, io: Io): Promise<void> {const root = resolve(dir);// `init` does not go through `resolveProjectRoot`; migrate here so a@@ -146,27 +189,28 @@ export async function init(dir: string, opts: InitOptions, io: Io): Promise<voidif (!existing.ok) throw new CliError(`${projectPaths(root).project}: ${existing.error}`);await register(io, root, existing.data.name);if (opts.allowSkill !== undefined) await askSkillPermission(io, opts);+ await refreshGitIntegration(io, root);io.out(`Already initialized: ${existing.data.name} (${root})`);return;}const name = opts.name ?? (await io.prompt.input("Project name?", basename(root)));+ const config = await loadConfig(io.env);const gitRoot = await findGitRoot(root);+ let policy: GitPolicy | undefined;if (gitRoot) {- const fallback = (await loadConfig(io.env)).gitPolicy;- const policy =+ // Story 9.3: the record travels with the repository by default.+ policy =opts.git ??(await io.prompt.select<GitPolicy>(- "This is a git repository. Commit the lineage records?",+ "This is a git repository. Commit the session records?",[- { value: "ignore", name: "No, keep .cogit/ out of git (private)" },{ value: "commit", name: "Yes, commit session records (local state stays ignored)" },+ { value: "ignore", name: "No, keep .cogit/ out of git (private)" },],- fallback,+ config.gitPolicy,));- const added = await ensureGitignore(root, policy);- if (added.length > 0) io.out(`Added to .gitignore: ${added.join(", ")}`);}await askRetention(io, opts);@@ -175,13 +219,13 @@ export async function init(dir: string, opts: InitOptions, io: Io): Promise<voidawait updateProject(root, (cur) => cur ?? { schema: 1, name, epochs: [] });await mkdir(projectPaths(root).sessions, { recursive: true });- await bestEffort(io, "could not write .cogit/.gitignore", () =>- ensureConversationGitignore(root),- );+ if (policy !== undefined) await applyGitPolicy(io, root, policy, config.shareConversations);await register(io, root, name);io.out(- "Conversations are stored in .cogit/conversations/ (kept out of git, even with the commit policy).",+ config.shareConversations+ ? "Conversations are stored in .cogit/conversations/ (shared through git: shareConversations is on)."+ : "Conversations are stored in .cogit/conversations/ (kept out of git; turn on shareConversations to share them).",);io.out(`Initialized ${name} in ${projectPaths(root).base}`);io.out("Next: install the Claude Code plugin, then run `cogit open` after a session.");diff --git a/packages/cli/src/commands/log.ts b/packages/cli/src/commands/log.tsindex 2329fb5..90c22f8 100644--- a/packages/cli/src/commands/log.ts+++ b/packages/cli/src/commands/log.ts@@ -123,6 +123,8 @@ export interface LogMessage {export interface LogSession {sessionId: string;title: string;+ /** Who recorded the session (Story 9.3); absent on older records. */+ author?: string;epoch: string | null;startedAt: string;updatedAt: string;@@ -184,6 +186,7 @@ function toLogSession(effective: EffectiveSession): LogSession {return {sessionId: session.sessionId,title: session.title,+ ...(session.author === undefined ? {} : { author: session.author }),epoch: session.epoch,startedAt: session.startedAt,updatedAt: session.updatedAt,@@ -258,8 +261,9 @@ export function buildLog(sessions: EffectiveSession[], opts: LogOptions = {}): Lfunction sessionHeading(session: LogSession): string {const title = session.title.trim() === "" ? session.sessionId : oneLine(session.title);+ const author = session.author === undefined ? "" : ` · by ${session.author}`;return (- `## ${title} (${session.sessionId}) · ${session.epoch ?? "unassigned"} · ` ++ `## ${title} (${session.sessionId})${author} · ${session.epoch ?? "unassigned"} · ` +`${stamp(session.startedAt)} → ${stamp(session.updatedAt)}`);}diff --git a/packages/cli/src/commands/session.ts b/packages/cli/src/commands/session.tsindex 28f2f33..fca99e0 100644--- a/packages/cli/src/commands/session.ts+++ b/packages/cli/src/commands/session.ts@@ -1,5 +1,7 @@import { readFile, rm } from "node:fs/promises";+import { userInfo } from "node:os";import { resolve } from "node:path";+import { findGitRoot, gitUserName } from "../git.js";import { CliError, type Io } from "../io.js";import {hashesToLabels,@@ -35,6 +37,25 @@ export async function readStdin(stream: NodeJS.ReadableStream = process.stdin):return Buffer.concat(chunks).toString("utf8");}+/**+ * Who gets credited for a session (Story 9.3): the git name this repository+ * commits with, else the OS user. Recorded once, on the first write; a record+ * made on another machine keeps its own author.+ */+export async function sessionAuthor(+ root: string,+ env: NodeJS.ProcessEnv = process.env,+): Promise<string | undefined> {+ const gitRoot = await findGitRoot(root);+ const fromGit = gitRoot === undefined ? undefined : await gitUserName(gitRoot, env);+ if (fromGit !== undefined) return fromGit;+ try {+ return userInfo().username || undefined;+ } catch {+ return env.USER ?? env.USERNAME ?? undefined;+ }+}+export interface SessionWriteOptions {dir: string;/** Read JSON from this file instead of stdin. */@@ -88,6 +109,10 @@ export async function sessionWrite(// merge; `startedAt` is the current session's own start.const current = await loadSession(root, input.sessionId);const startedAt = current.found && current.ok ? current.data.startedAt : io.now();+ const author =+ current.found && current.ok && current.data.author+ ? current.data.author+ : await sessionAuthor(root, io.env);const crossTargets = await crossSessionTargets(root, input.sessionId, startedAt, input, io.env);let warnings: string[] = [];const saved = await updateSession(root, input.sessionId, async (cur) => {@@ -111,7 +136,9 @@ export async function sessionWrite(: [];await appendEvents(root, input.sessionId, [...seed, ...changes]);// A write from the main checkout (e.g. after a resume) keeps the stored worktree.- return worktree ? { ...merged.session, worktree } : merged.session;+ const stored = worktree ? { ...merged.session, worktree } : merged.session;+ // Story 9.3: the first write stamps who recorded the session.+ return stored.author === undefined && author !== undefined ? { ...stored, author } : stored;});for (const w of warnings) io.warn(w);if (opts.file && opts.consume) await rm(opts.file, { force: true });diff --git a/packages/cli/src/git-hooks.ts b/packages/cli/src/git-hooks.tsnew file mode 100644index 0000000..6b01013--- /dev/null+++ b/packages/cli/src/git-hooks.ts@@ -0,0 +1,86 @@+import { chmod, mkdir, readFile, stat } from "node:fs/promises";+import { join } from "node:path";+import { findGitRoot, gitHooksDir } from "./git.js";+import { stageSessionFiles } from "./session-git.js";+import { atomicWrite } from "./store/fs.js";++/**+ * Git hook installation (Story 9.3). cogit never owns a hook file: it adds a+ * marked block that calls back into the CLI, leaves whatever the user (or Husky)+ * put there alone, and a failure never blocks `init` or a commit.+ */++export const BLOCK_START = "# >>> cogit";+export const BLOCK_END = "# <<< cogit";++/** The block `init` adds to a hook; `"$@"` passes git's arguments through. */+export function hookBlock(event: string, projectRoot: string): string {+ return [+ BLOCK_START,+ `cogit hook ${event} --dir ${shellQuote(projectRoot)} "$@" || true`,+ BLOCK_END,+ ].join("\n");+}++/** Single quotes for the shell, with the embedded single quote escaped. */+function shellQuote(value: string): string {+ return `'${value.replaceAll("'", `'\\''`)}'`;+}++/** Replaces an existing cogit block, or appends one, keeping the file's own content. */+export function withHookBlock(text: string, block: string): string {+ const pattern = /# >>> cogit[\s\S]*?# <<< cogit/g;+ if (pattern.test(text)) return text.replace(pattern, block);+ // An empty file still has to be runnable: git execs the hook directly.+ if (text === "") return `#!/bin/sh\n\n${block}\n`;+ const sep = text.endsWith("\n") ? "" : "\n";+ return `${text}${sep}\n${block}\n`;+}++/**+ * Installs the block into the hook file git actually uses. Returns true when the+ * file changed, false when the block was already current or the repository does+ * not expose a hooks directory (a bare `.git` directory in tests, a non-repo).+ */+export async function installGitHook(root: string, event: string): Promise<boolean> {+ const gitRoot = await findGitRoot(root);+ if (gitRoot === undefined) return false;+ const dir = await gitHooksDir(gitRoot);+ if (dir === undefined) return false;+ await mkdir(dir, { recursive: true });+ const file = join(dir, event);+ const exists = await stat(file).then(+ () => true,+ () => false,+ );+ const current = exists ? await readFile(file, "utf8") : "";+ const block = hookBlock(event, root);+ const next = exists ? withHookBlock(current, block) : `#!/bin/sh\n\n${block}\n`;+ if (exists && next === current) return false;+ await atomicWrite(file, next);+ await chmod(file, 0o755);+ return true;+}++/**+ * The git-side events cogit answers (Story 9.3). A git hook's stdin is not the+ * Claude Code hook JSON, so these never go through `runHook`.+ */+export const GIT_HOOK_EVENTS = ["pre-commit"] as const;+export type GitHookEvent = (typeof GIT_HOOK_EVENTS)[number];++export function isGitHookEvent(event: string): event is GitHookEvent {+ return (GIT_HOOK_EVENTS as readonly string[]).includes(event);+}++/**+ * Runs one git hook. A git hook that fails would block the user's commit, so the+ * CLI calls this inside its own silence: nothing here throws or prints.+ */+export async function runGitHook(+ event: GitHookEvent,+ dir: string,+ env: NodeJS.ProcessEnv = process.env,+): Promise<void> {+ if (event === "pre-commit") await stageSessionFiles(dir, env);+}diff --git a/packages/cli/src/git.ts b/packages/cli/src/git.tsindex 9f8519c..1f12d0c 100644--- a/packages/cli/src/git.ts+++ b/packages/cli/src/git.ts@@ -24,17 +24,32 @@ export async function findGitRoot(dir: string): Promise<string | undefined> {const HEADER = "# cogit";-/** Machine-local data that must never be committed, whatever the policy. */-const ALWAYS = ["/.cogit/state/", "/.cogit/locks/", "/.cogit/inbox/", "/.cogit/map.html"];+/** The root line that keeps the whole `.cogit/` out under the ignore policy. */+const IGNORE_ALL = "/.cogit/";+/**+ * What the root `.gitignore` needs for a policy (Story 9.3). Under `commit` the+ * root lists nothing: the project's own `.cogit/.gitignore` keeps local state out+ * and lets the session records travel. Under `ignore` a single line hides it all.+ */export function gitignoreLines(policy: GitPolicy): string[] {- return policy === "ignore" ? ["/.cogit/"] : ALWAYS;+ return policy === "ignore" ? [IGNORE_ALL] : [];}-/** Appends the policy's lines to `<root>/.gitignore`, skipping lines already there. */+/**+ * Applies the policy to `<root>/.gitignore`: adds the ignore line, or removes the+ * one an older init wrote when the project switches to `commit`. User lines are+ * never touched. Returns the lines added (none when switching to commit).+ */export async function ensureGitignore(root: string, policy: GitPolicy): Promise<string[]> {const file = join(root, ".gitignore");const text = await readFile(file, "utf8").catch(() => "");+ if (policy === "commit") {+ const lines = text.split(/\r?\n/);+ const kept = lines.filter((line) => line.trim() !== IGNORE_ALL);+ if (kept.length !== lines.length) await atomicWrite(file, kept.join("\n"));+ return [];+ }const present = new Set(text.split(/\r?\n/).map((l) => l.trim()));const missing = gitignoreLines(policy).filter((l) => !present.has(l));if (missing.length === 0) return [];@@ -44,21 +59,65 @@ export async function ensureGitignore(root: string, policy: GitPolicy): Promise<return missing;}+/** True when the root `.gitignore` hides all of `.cogit/` (the ignore policy). */+export async function cogitIgnored(root: string): Promise<boolean> {+ const text = await readFile(join(root, ".gitignore"), "utf8").catch(() => "");+ return text.split(/\r?\n/).some((line) => line.trim() === IGNORE_ALL);+}++/**+ * The `.cogit/.gitignore` the commit policy writes (Story 9.3): everything in the+ * directory stays local except the session records, `project.json` and these+ * rules themselves. The file has to travel: without it a clone would not ignore+ * the conversation store and one `git add -A` would publish the raw chat. The+ * list has no timestamps and a stable order, so switching a setting rewrites it+ * once and later builds leave it alone.+ */+export function cogitGitignore(shareConversations: boolean): string {+ return [+ HEADER,+ "*",+ "!.gitignore",+ "!sessions/",+ "!sessions/**",+ "!project.json",+ ...(shareConversations ? ["!conversations/", "!conversations/**"] : []),+ "",+ ].join("\n");+}+/**- * `.cogit/.gitignore` keeps the conversation store out of git, even when- * the user chose to commit `.cogit/`: the raw chat stays on this machine.- * Returns true when the line had to be added; a second call changes nothing.+ * Writes `.cogit/.gitignore` for the commit policy; a no-op under `ignore`+ * (the root already hides everything). Returns true when the file changed.*/-export async function ensureConversationGitignore(root: string): Promise<boolean> {+export async function ensureCogitGitignore(+ root: string,+ policy: GitPolicy,+ shareConversations: boolean,+): Promise<boolean> {+ if (policy !== "commit") return false;const file = join(root, ".cogit", ".gitignore");- const text = await readFile(file, "utf8").catch(() => "");- const present = new Set(text.split(/\r?\n/).map((l) => l.trim()));- if (present.has("conversations/")) return false;- const sep = text === "" || text.endsWith("\n") ? "" : "\n";- await atomicWrite(file, `${text}${sep}conversations/\n`);+ const content = cogitGitignore(shareConversations);+ const current = await readFile(file, "utf8").catch(() => undefined);+ if (current === content) return false;+ await atomicWrite(file, content);return true;}+/**+ * Keeps an existing project's `.cogit/.gitignore` in step with the settings+ * (Story 9.3): reads the policy from the root ignore file, so a project that+ * committed its records before this story gets the new rules on its next build.+ */+export async function refreshCogitGitignore(+ root: string,+ shareConversations: boolean,+): Promise<boolean> {+ if ((await findGitRoot(root)) === undefined) return false;+ if (await cogitIgnored(root)) return false;+ return ensureCogitGitignore(root, "commit", shareConversations);+}+interface CommitLine {full: string;short: string;@@ -246,8 +305,7 @@ export function projectFiles(* Full hashes git blames for `file`; `file:line` asks about one line and a bare* file means every commit that touched it (Story 8.8). `file` is relative to* `root`, the repository's worktree.- */-export async function blameCommitHashes(+ */ export async function blameCommitHashes(root: string,file: string,line?: number,@@ -267,3 +325,29 @@ export async function blameCommitHashes(}return [...out];}++/** The name a commit in this repository would carry; undefined outside git or unset. */+export async function gitUserName(+ root: string,+ env: NodeJS.ProcessEnv = process.env,+): Promise<string | undefined> {+ try {+ const { stdout } = await exec("git", ["-C", root, "config", "user.name"], { env });+ const name = stdout.trim();+ return name === "" ? undefined : name;+ } catch {+ return undefined;+ }+}++/** The hooks directory git really uses here: `core.hooksPath`, Husky and worktrees included. */+export async function gitHooksDir(root: string): Promise<string | undefined> {+ try {+ const { stdout } = await exec("git", ["-C", root, "rev-parse", "--git-path", "hooks"]);+ const path = stdout.trim();+ if (path === "") return undefined;+ return isAbsolute(path) ? path : join(root, path);+ } catch {+ return undefined;+ }+}diff --git a/packages/cli/src/hooks/promptsubmit.ts b/packages/cli/src/hooks/promptsubmit.tsnew file mode 100644index 0000000..a0d15ee--- /dev/null+++ b/packages/cli/src/hooks/promptsubmit.ts@@ -0,0 +1,21 @@+import { atomicWriteJson } from "../store/fs.js";+import { projectPaths } from "../store/paths.js";+import type { HookContext } from "./run.js";++/**+ * UserPromptSubmit hook (Story 9.3). Records which session this working tree is+ * in, so the git pre-commit hook can carry its record with the next code commit.+ * The file is local state (`.cogit/.gitignore` keeps it out) and is rewritten on+ * every message: a resumed or new session replaces the previous one.+ */+export async function onPromptSubmit(ctx: HookContext): Promise<undefined> {+ if (!ctx.initialized) return undefined;+ await atomicWriteJson(projectPaths(ctx.root).head, {+ sessionId: ctx.sessionId,+ ...(ctx.input.transcript_path === undefined+ ? {}+ : { transcriptPath: ctx.input.transcript_path }),+ at: ctx.now,+ });+ return undefined;+}diff --git a/packages/cli/src/hooks/run.ts b/packages/cli/src/hooks/run.tsindex 5f1de69..095be58 100644--- a/packages/cli/src/hooks/run.ts+++ b/packages/cli/src/hooks/run.ts@@ -5,6 +5,7 @@ import { z } from "zod";import { Slug } from "../schema/common.js";import { captureDisabled, projectPaths } from "../store/paths.js";import { resolveProjectRoot } from "../store/root.js";+import { onPromptSubmit } from "./promptsubmit.js";import { onSessionEnd } from "./sessionend.js";import { onSessionStart } from "./sessionstart.js";import { onStop } from "./stop.js";@@ -13,6 +14,8 @@ import { onStop } from "./stop.js";export const HookInput = z.looseObject({session_id: z.string(),cwd: z.string().optional(),+ /** Where Claude Code keeps the session's transcript (UserPromptSubmit and friends). */+ transcript_path: z.string().optional(),stop_hook_active: z.boolean().optional(),/** SessionStart only: `startup`, `resume`, `clear` or `compact`. */source: z.string().optional(),@@ -46,6 +49,7 @@ const HANDLERS: Record<string, (ctx: HookContext) => Promise<HookOutput | undefistop: onStop,sessionstart: onSessionStart,sessionend: onSessionEnd,+ promptsubmit: onPromptSubmit,};export const HOOK_EVENTS = Object.keys(HANDLERS);diff --git a/packages/cli/src/hooks/sessionend.ts b/packages/cli/src/hooks/sessionend.tsindex 93f521a..350488f 100644--- a/packages/cli/src/hooks/sessionend.ts+++ b/packages/cli/src/hooks/sessionend.ts@@ -8,13 +8,27 @@ import type { HookContext } from "./run.js";* 1.5 s budget, so this only starts the detached catch-up and returns. The tail* is not stored: the catch-up reads whatever messages still have no node, so a* child that dies is retried when the session is opened next.+ *+ * With `recordCommit: auto` (Story 9.3) the last record is committed detached as+ * well; the catch-up does that itself once it has written, so this only starts a+ * commit when there is nothing to catch up (or the catch-up is off).*/export async function onSessionEnd(ctx: HookContext): Promise<undefined> {if (!ctx.initialized) return undefined;const config = await loadConfig(ctx.env);- if (!config.sessionEndCatchUp) return undefined;+ const autoCommit = config.recordCommit === "auto";+ const commitOnly = (): void => {+ if (autoCommit) ctx.spawnDetached(["record-commit", ctx.sessionId, "-C", ctx.root]);+ };+ if (!config.sessionEndCatchUp) {+ commitOnly();+ return undefined;+ }const messages = await readSessionMessages(ctx.root, ctx.sessionId, ctx.env);- if (!messages || messages.length === 0) return undefined;+ if (!messages || messages.length === 0) {+ commitOnly();+ return undefined;+ }const record = await loadSession(ctx.root, ctx.sessionId);let recorded = new Set<string>();if (record.found && record.ok) {@@ -22,7 +36,10 @@ export async function onSessionEnd(ctx: HookContext): Promise<undefined> {const events = await readEvents(ctx.root, ctx.sessionId);recorded = new Set(applyEvents(upgraded.nodes, events).map((node) => node.id));}- if (messages.every((message) => isRecorded(recorded, message))) return undefined;+ if (messages.every((message) => isRecorded(recorded, message))) {+ commitOnly();+ return undefined;+ }ctx.spawnDetached(["backfill", ctx.sessionId, "--tail", "-C", ctx.root]);return undefined;}diff --git a/packages/cli/src/hooks/sessionstart.ts b/packages/cli/src/hooks/sessionstart.tsindex cc2985a..199c5f3 100644--- a/packages/cli/src/hooks/sessionstart.ts+++ b/packages/cli/src/hooks/sessionstart.ts@@ -1,6 +1,7 @@import { branchesOf, type LogBranch } from "../commands/log.js";import { isRecorded, readSessionMessages, upgradeSessionIds } from "../messages.js";import type { Session } from "../schema/session.js";+import { uncommittedSession } from "../session-git.js";import { applyEvents, readEvents } from "../store/events.js";import { loadAllSessions, loadConfig, loadSession } from "../store/stores.js";import { buildMessages } from "../view/lineage.js";@@ -70,7 +71,7 @@ export async function onSessionStart(ctx: HookContext): Promise<HookOutput | undconst config = await loadConfig(ctx.env);// SessionStart runs inside the chat's startup budget: opt out and it is silent.if (!config.startupContext) return undefined;- return additionalContext(await startupContext(ctx));+ return additionalContext(await startupContext(ctx, config.recordCommit));}function additionalContext(text: string): HookOutput {@@ -103,9 +104,11 @@ function clip(text: string, max: number): string {/*** What the agent needs to continue the project: where the lineage lives, how to- * read it, and the compressed view of the last session before this one.+ * read it, and the compressed view of the last session before this one. Under+ * `recordCommit: ask` (Story 9.3) it also says when that session's record is+ * still uncommitted, so the agent can offer to commit it.*/-async function startupContext(ctx: HookContext): Promise<string> {+async function startupContext(ctx: HookContext, recordCommit: string): Promise<string> {const command = cli(ctx);const header =`cogit records this project's lineage (one node per user message, hanging from the ` +@@ -122,7 +125,26 @@ async function startupContext(ctx: HookContext): Promise<string> {const events = await readEvents(ctx.root, previous.sessionId);const messages = buildMessages(applyEvents(previous.nodes, events));- return composeStartupContext(header, previous, branchesOf(previous.sessionId, messages));+ const recordLine =+ recordCommit === "ask" && (await uncommittedSession(ctx.root, previous.sessionId, ctx.env))+ ? recordCommitLine(previous)+ : "";+ return composeStartupContext(+ header,+ previous,+ branchesOf(previous.sessionId, messages),+ recordLine,+ );+}++/** The offer the agent makes for a record the last code commit did not carry. */+export function recordCommitLine(session: Session): string {+ const title = session.title.trim() === "" ? session.sessionId : clip(oneLine(session.title), 120);+ return (+ "The last session's record is not committed. Offer to commit it with the message " ++ `\`chore(cogit): record ${title}\`, only the .cogit/sessions/ paths (never other staged ` ++ "changes), and run it only if the user agrees."+ );}/** The session with the newest activity, ignoring this one. */@@ -145,8 +167,14 @@ export function composeStartupContext(header: string,session: Session,branches: readonly LogBranch[],+ recordLine = "",): string {- const head = [header, "", ...statusLines(session)];+ const head = [+ header,+ ...(recordLine === "" ? [] : ["", recordLine]),+ "",+ ...statusLines(session),+ ];const blocks = branches.map(branchLines);const cutNote = (cut: number): string[] =>cut === 0diff --git a/packages/cli/src/program.ts b/packages/cli/src/program.tsindex 3ede126..e1f40de 100644--- a/packages/cli/src/program.ts+++ b/packages/cli/src/program.ts@@ -5,6 +5,7 @@ import { blame } from "./commands/blame.js";import { buildProject } from "./commands/build.js";import {configGet,+ configGit,configHintOff,configHintOn,configPrune,@@ -17,9 +18,11 @@ 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 { isGitHookEvent, runGitHook } from "./git-hooks.js";import { runHook } from "./hooks/run.js";import { CliError, type Io, processIo } from "./io.js";import { startMapServer } from "./server.js";+import { maybeAutoCommit } from "./session-git.js";import { takeMigrationWarnings } from "./store/migrate.js";import { loadConfig } from "./store/stores.js";@@ -254,6 +257,18 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =.argument("<key>").argument("<value>").action(run(async (key: string, value: string) => configSet(key, value, makeIo(false))));+ config+ .command("git")+ .description("commit or ignore this project's session records (story 9.3)")+ .argument("<policy>", "commit or ignore")+ .argument("[dir]", "project directory", ".")+ .action(+ run(async (policy: string, dir: string) => {+ if (policy !== "commit" && policy !== "ignore")+ throw new CliError(`invalid git policy "${policy}"; use commit or ignore`);+ await configGit(dir, policy, makeIo(false));+ }),+ );config.command("hint-off").description("stop the SessionStart setup hint in a project")@@ -345,12 +360,34 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =run(async (id: string, opts: { dir: string }) => sessionShow(opts.dir, id, makeIo(false))),);- // Called by the plugin's hooks.json with the hook input on stdin. Never fails.+ // Started detached by the SessionEnd hook when `recordCommit` is `auto`.+ program+ .command("record-commit", { hidden: true })+ .description("commit the session record files without touching other staged changes")+ .argument("<session-id>", "session id")+ .option("-C, --dir <dir>", "project directory", ".")+ .action(+ run(async (sessionId: string, opts: { dir: string }) => {+ await maybeAutoCommit(opts.dir, sessionId, makeIo(false).env);+ }),+ );++ // Called by the plugin's hooks.json with the hook input on stdin, and by the+ // git hooks cogit installs (Story 9.3) with git's arguments. Never fails.program.command("hook", { hidden: true })- .argument("<event>", "hook event, e.g. stop or sessionstart")- .action(async (event: string) => {+ .argument("<event>", "hook event, e.g. stop, sessionstart, pre-commit")+ .option("-C, --dir <dir>", "project directory (git hooks pass theirs)")+ .action(async (event: string, opts: { dir?: string }) => {const io = makeIo(false);+ if (isGitHookEvent(event)) {+ try {+ await runGitHook(event, opts.dir ?? process.cwd(), io.env);+ } catch {+ // A hook must never block the commit or the session.+ }+ return;+ }const input = await (deps.stdin ?? readStdin)();const out = await runHook(event, input, io.env, io.now(), io.warn);if (out !== undefined) io.out(out);diff --git a/packages/cli/src/schema/config.ts b/packages/cli/src/schema/config.tsindex 64c42d8..0776dae 100644--- a/packages/cli/src/schema/config.ts+++ b/packages/cli/src/schema/config.ts@@ -23,8 +23,18 @@ export const Config = z.object({startupContext: z.boolean().default(true),/** Port the local map server binds on `127.0.0.1`. */serverPort: z.int().min(1).max(65535).default(4747),- /** Default for new projects; `init` asks per repo. */- gitPolicy: z.enum(["ignore", "commit"]).default("ignore"),+ /** Default for new projects; `init` asks per repo. Story 9.3: the record travels. */+ gitPolicy: z.enum(["ignore", "commit"]).default("commit"),+ /**+ * Whether `.cogit/conversations/` (the raw chat text) travels too. Off by+ * default: the session record can be committed while the chat stays local.+ */+ shareConversations: z.boolean().default(false),+ /**+ * What happens to the session files the last code commit left behind: ask the+ * user at the next session start, commit them at session end, or do nothing.+ */+ recordCommit: z.enum(["ask", "auto", "off"]).default("ask"),agents: z.array(z.string().min(1)).default(["claude-code"]),/** Project roots ("don't ask again" in this project) where the setup hint stays silent. */setupHintOff: z.array(z.string().min(1)).default([]),diff --git a/packages/cli/src/schema/session.ts b/packages/cli/src/schema/session.tsindex cefb255..30eeb5a 100644--- a/packages/cli/src/schema/session.ts+++ b/packages/cli/src/schema/session.ts@@ -103,6 +103,11 @@ export const Session = z.object({nodes: z.array(LineageNode).default([]),/** The linked git worktree the session ran in; set by the CLI, never by the agent. */worktree: z.object({ path: z.string().min(1), branch: z.string().min(1).nullable() }).optional(),+ /**+ * Who recorded the session (git `user.name`, else the OS user); set by the CLI+ * on the first write (Story 9.3). Old records have none.+ */+ author: z.string().min(1).max(200).optional(),});/** In input, a missing parent keeps the stored one (null for a new node). */diff --git a/packages/cli/src/server.ts b/packages/cli/src/server.tsindex 03be558..1b92a4c 100644--- a/packages/cli/src/server.ts+++ b/packages/cli/src/server.ts@@ -13,6 +13,7 @@ import { fileURLToPath } from "node:url";import { buildProject } from "./commands/build.js";import { defaultsPrompter, type Io } from "./io.js";import { Config } from "./schema/config.js";+import { refreshShareConversations } from "./share.js";import { LockBusyError } from "./store/lock.js";import { globalPaths, projectPaths } from "./store/paths.js";import { loadConfig, loadRegistry, updateConfig } from "./store/stores.js";@@ -367,6 +368,9 @@ export async function startMapServer(opts: MapServerOptions): Promise<MapServer>respond(res, err instanceof LockBusyError ? 409 : 500, "could not write the config");return;}+ // Story 9.3: un-ignore (or hide) the conversation store in every project.+ if (key === "shareConversations")+ await refreshShareConversations(env, next.data.shareConversations);res.writeHead(200, {"content-type": "application/json","cache-control": "no-store",diff --git a/packages/cli/src/session-git.ts b/packages/cli/src/session-git.tsnew file mode 100644index 0000000..66ac21f--- /dev/null+++ b/packages/cli/src/session-git.ts@@ -0,0 +1,160 @@+import { execFile } from "node:child_process";+import { existsSync } from "node:fs";+import { relative, sep } from "node:path";+import { promisify } from "node:util";+import { z } from "zod";+import { findGitRoot } from "./git.js";+import { Slug } from "./schema/common.js";+import { readJson } from "./store/fs.js";+import { projectPaths } from "./store/paths.js";+import { loadConfig, loadSession } from "./store/stores.js";++const exec = promisify(execFile);++/**+ * What the UserPromptSubmit hook leaves in `.cogit/HEAD` (Story 9.3): the session+ * a code commit in this working tree carries, and where its transcript is.+ */+export const SessionHead = z.object({+ sessionId: Slug,+ transcriptPath: z.string().optional(),+ at: z.string().optional(),+});+export type SessionHead = z.infer<typeof SessionHead>;++export async function readSessionHead(root: string): Promise<SessionHead | undefined> {+ const read = await readJson(projectPaths(root).head);+ if (!read.found || "error" in read) return undefined;+ const parsed = SessionHead.safeParse(read.value);+ return parsed.success ? parsed.data : undefined;+}++interface GitResult {+ code: number;+ stdout: string;+}++/** Git with `-C`, never throwing: the exit code and stdout are what callers need. */+async function git(+ root: string,+ args: string[],+ env: NodeJS.ProcessEnv = process.env,+): Promise<GitResult> {+ try {+ const { stdout } = await exec("git", ["-C", root, ...args], { env });+ return { code: 0, stdout };+ } catch (err) {+ const failure = err as { code?: number | string; stdout?: string };+ return {+ code: typeof failure.code === "number" ? failure.code : 1,+ stdout: failure.stdout ?? "",+ };+ }+}++/**+ * The current session's files as paths git understands, relative to the git+ * root. A project inside a repository subdirectory keeps its own prefix, so the+ * hook stages what it actually wrote. Missing files are left out: a session that+ * recorded nothing has nothing to carry.+ */+async function sessionPaths(gitRoot: string, root: string, sessionId: string): Promise<string[]> {+ const paths = projectPaths(root);+ return [paths.session(sessionId), paths.events(sessionId)]+ .filter((file) => existsSync(file))+ .map((file) => relative(gitRoot, file).split(sep).join("/"))+ .filter((file) => file !== "" && !file.startsWith(".."));+}++/** True when the ignore policy keeps these paths out of git: staging would fail. */+async function ignored(gitRoot: string, path: string, env: NodeJS.ProcessEnv): Promise<boolean> {+ return (await git(gitRoot, ["check-ignore", "-q", "--", path], env)).code === 0;+}++/**+ * Something other than the session files is already staged. The pre-commit hook+ * must never create a record-only commit, so with an empty index it does nothing.+ * An initial commit (no HEAD yet) counts as staged: the user is committing.+ */+async function hasStagedChanges(gitRoot: string, env: NodeJS.ProcessEnv): Promise<boolean> {+ return (await git(gitRoot, ["diff", "--cached", "--quiet", "--exit-code"], env)).code !== 0;+}++/** True when this session's files differ from HEAD (or are untracked). */+export async function uncommittedSession(+ root: string,+ sessionId: string,+ env: NodeJS.ProcessEnv = process.env,+): Promise<boolean> {+ const gitRoot = await findGitRoot(root);+ if (gitRoot === undefined) return false;+ const paths = await sessionPaths(gitRoot, root, sessionId);+ if (paths.length === 0) return false;+ if (await ignored(gitRoot, paths[0] as string, env)) return false;+ return (await git(gitRoot, ["status", "--porcelain", "--", ...paths], env)).stdout.trim() !== "";+}++/**+ * Git pre-commit hook (Story 9.3): stage the current session's record so a code+ * commit carries its "why". The session comes from `.cogit/HEAD`, written by the+ * UserPromptSubmit hook. Everything is best-effort: a missing HEAD, an ignored+ * project, an empty index or a failing git all end quietly and the commit runs.+ */+export async function stageSessionFiles(+ root: string,+ env: NodeJS.ProcessEnv = process.env,+): Promise<boolean> {+ const head = await readSessionHead(root);+ if (head === undefined) return false;+ const gitRoot = await findGitRoot(root);+ if (gitRoot === undefined) return false;+ const paths = await sessionPaths(gitRoot, root, head.sessionId);+ if (paths.length === 0) return false;+ if (await ignored(gitRoot, paths[0] as string, env)) return false;+ if (!(await hasStagedChanges(gitRoot, env))) return false;+ return (await git(gitRoot, ["add", "--", ...paths], env)).code === 0;+}++/** The message an `auto` record commit carries; the title is kept to one short line. */+export function recordMessage(title: string, sessionId: string): string {+ const clean = title.replace(/\s+/g, " ").trim() || sessionId;+ return `chore(cogit): record ${clean.length > 120 ? `${clean.slice(0, 119)}…` : clean}`;+}++/**+ * Commits exactly this session's record files (Story 9.3, `recordCommit: auto`).+ * Other staged changes stay staged: the commit is restricted to these paths. A+ * missing git, an ignored project or nothing to commit is not an error.+ */+export async function commitSessionFiles(+ root: string,+ sessionId: string,+ title: string,+ env: NodeJS.ProcessEnv = process.env,+): Promise<boolean> {+ const gitRoot = await findGitRoot(root);+ if (gitRoot === undefined) return false;+ const paths = await sessionPaths(gitRoot, root, sessionId);+ if (paths.length === 0) return false;+ if (await ignored(gitRoot, paths[0] as string, env)) return false;+ if ((await git(gitRoot, ["status", "--porcelain", "--", ...paths], env)).stdout.trim() === "")+ return false;+ if ((await git(gitRoot, ["add", "--", ...paths], env)).code !== 0) return false;+ // --no-verify: the record commit must not set off the hooks it is part of.+ const message = recordMessage(title, sessionId);+ return (+ (await git(gitRoot, ["commit", "--no-verify", "-m", message, "--", ...paths], env)).code === 0+ );+}++/** The `recordCommit` setting applied at session end: only `auto` commits here. */+export async function maybeAutoCommit(+ root: string,+ sessionId: string,+ env: NodeJS.ProcessEnv,+): Promise<boolean> {+ if ((await loadConfig(env)).recordCommit !== "auto") return false;+ const loaded = await loadSession(root, sessionId);+ const title = loaded.found && loaded.ok ? loaded.data.title : "";+ return commitSessionFiles(root, sessionId, title, env);+}diff --git a/packages/cli/src/share.ts b/packages/cli/src/share.tsnew file mode 100644index 0000000..b5ab1a7--- /dev/null+++ b/packages/cli/src/share.ts@@ -0,0 +1,25 @@+import { refreshCogitGitignore } from "./git.js";+import { isDirectory } from "./store/fs.js";+import { loadRegistry } from "./store/stores.js";++/**+ * Applies a change of `shareConversations` to every registered project (Story+ * 9.3): a project that commits its records gets `conversations/` un-ignored (or+ * hidden again) right away, not only on its next build. Missing directories and+ * unwritable ignore files are skipped in silence; this is derived state.+ */+export async function refreshShareConversations(+ env: NodeJS.ProcessEnv,+ share: boolean,+): Promise<void> {+ const registry = await loadRegistry(env);+ if (!registry.found || !registry.ok) return;+ for (const entry of registry.data.projects) {+ if (!(await isDirectory(entry.path))) continue;+ try {+ await refreshCogitGitignore(entry.path, share);+ } catch {+ // A read-only project keeps its previous rules; the next build retries.+ }+ }+}diff --git a/packages/cli/src/store/paths.ts b/packages/cli/src/store/paths.tsindex b787efa..d16d81e 100644--- a/packages/cli/src/store/paths.ts+++ b/packages/cli/src/store/paths.ts@@ -37,6 +37,13 @@ export function projectPaths(root: string) {inbox: (id: string) => join(base, "inbox", `${id}.json`),lock: (name: string) => join(base, "locks", `${name}.lock`),html: join(base, "map.html"),+ /**+ * The session whose next code commit carries its record (Story 9.3), written+ * by the UserPromptSubmit hook. Local state, never committed.+ */+ head: join(base, "HEAD"),+ /** The project-scoped ignore rules that keep local state out of git. */+ gitignore: join(base, ".gitignore"),};}diff --git a/packages/cli/src/store/stores.ts b/packages/cli/src/store/stores.tsindex 7f33a9d..cca5f0c 100644--- a/packages/cli/src/store/stores.ts+++ b/packages/cli/src/store/stores.ts@@ -6,7 +6,7 @@ import { PROJECT_SCHEMA, Project } from "../schema/project.js";import { SESSION_SCHEMA, Session } from "../schema/session.js";import { HookState, STATE_SCHEMA } from "../schema/state.js";import { type Parsed, parseVersioned } from "../schema/versioned.js";-import { atomicWriteJson, readJson } from "./fs.js";+import { atomicWrite, atomicWriteJson, readJson } from "./fs.js";import { type LockOptions, withLock } from "./lock.js";import { globalPaths, projectPaths } from "./paths.js";@@ -53,12 +53,56 @@ async function update<S extends z.ZodType, R extends z.infer<S>>(export const loadProject = (root: string) =>load(projectPaths(root).project, Project, PROJECT_SCHEMA);-export const updateProject = (+/** One object on one line, its keys sorted, so diffs stay line-sized. */+function stableInline(value: object): string {+ const entries = Object.entries(value).sort(([a], [b]) => a.localeCompare(b));+ return `{${entries.map(([key, v]) => `${JSON.stringify(key)}: ${JSON.stringify(v)}`).join(", ")}}`;+}++/**+ * `project.json` as git should see it (Story 9.3): sorted keys and one epoch per+ * line, so two people adding different epochs merge without a conflict. Epochs+ * are the only array that grows; everything else is a single line.+ */+export function projectJson(project: {+ schema: number;+ name: string;+ epochs: readonly object[];+}): string {+ const epochs =+ project.epochs.length === 0+ ? ' "epochs": [],'+ : [+ ' "epochs": [',+ project.epochs.map((epoch) => ` ${stableInline(epoch)}`).join(",\n"),+ " ],",+ ].join("\n");+ return `${[+ "{",+ epochs,+ ` "name": ${JSON.stringify(project.name)},`,+ ` "schema": ${project.schema}`,+ "}",+ ].join("\n")}\n`;+}++/**+ * Locked read → update → write for `project.json`, through `projectJson` so the+ * file stays merge-friendly. The generic store writer keeps the familiar+ * indented format for every other file.+ */+export const updateProject = async (root: string,fn: (cur: Project | undefined) => Project | Promise<Project>,-) => {+): Promise<Project> => {const p = projectPaths(root);- return update(p.project, p.lock("project"), Project, PROJECT_SCHEMA, fn);+ return withLock(p.lock("project"), async () => {+ const cur = await loadProject(root);+ if (cur.found && !cur.ok) throw new Error(`${p.project}: ${cur.error}`);+ const next = Project.parse(await fn(cur.found && cur.ok ? cur.data : undefined));+ await atomicWrite(p.project, projectJson(next));+ return next;+ });};export const loadSession = (root: string, id: string) =>diff --git a/packages/cli/src/view/lineage.ts b/packages/cli/src/view/lineage.tsindex f1fc0cc..3e3ca3d 100644--- a/packages/cli/src/view/lineage.ts+++ b/packages/cli/src/view/lineage.ts@@ -202,6 +202,7 @@ function toViewSession(sessionId: session.sessionId,agent: session.agent,title: session.title,+ ...(session.author === undefined ? {} : { author: session.author }),epoch: session.epoch,startedAt: session.startedAt,updatedAt: session.updatedAt,diff --git a/packages/cli/src/view/model.ts b/packages/cli/src/view/model.tsindex ff7031d..eec7e1e 100644--- a/packages/cli/src/view/model.ts+++ b/packages/cli/src/view/model.ts@@ -36,6 +36,8 @@ export const PANEL_EDITABLE_KEYS = ["updateEveryTurns","sessionEndCatchUp","catchUpModel",+ "shareConversations",+ "recordCommit",] as const;export type PanelEditableKey = (typeof PANEL_EDITABLE_KEYS)[number];@@ -165,6 +167,8 @@ export interface ViewSession {sessionId: string;agent: string;title: string;+ /** Who recorded the session (Story 9.3); absent on records written before it. */+ author?: string;epoch: string | null;startedAt: string;updatedAt: string;@@ -303,6 +307,8 @@ export interface PanelSettings {catchUpModel: string;messageSummaries: boolean;startupContext: boolean;+ shareConversations: boolean;+ recordCommit: "ask" | "auto" | "off";gitPolicy: "ignore" | "commit";agents: string[];}diff --git a/packages/cli/src/view/panel.ts b/packages/cli/src/view/panel.tsindex f0e68b3..436f6ec 100644--- a/packages/cli/src/view/panel.ts+++ b/packages/cli/src/view/panel.ts@@ -47,6 +47,8 @@ export function panelSettings(config: Config): PanelSettings {catchUpModel: config.catchUpModel,messageSummaries: config.messageSummaries,startupContext: config.startupContext,+ shareConversations: config.shareConversations,+ recordCommit: config.recordCommit,gitPolicy: config.gitPolicy,agents: config.agents,};diff --git a/packages/cli/src/view/settings.ts b/packages/cli/src/view/settings.tsindex a4d26c8..5f51353 100644--- a/packages/cli/src/view/settings.ts+++ b/packages/cli/src/view/settings.ts@@ -69,13 +69,25 @@ const EDITABLE: FieldSpec[] = [help: "Model the catch-up and backfill use to summarize.",kind: "text",},+ {+ key: "shareConversations",+ label: "Share conversations",+ help: "Commit the raw chat text too, not only the session record (off: chat stays local).",+ kind: "boolean",+ },+ {+ key: "recordCommit",+ label: "Commit the record",+ help: "ask, auto or off: what to do with the last messages after the last code commit.",+ kind: "text",+ },];const READ_ONLY: FieldSpec[] = [{key: "gitPolicy",label: "Git policy",- help: "Whether captures are committed to git; change it per project with `cogit config set`.",+ help: "Whether captures are committed to git; change it per project with `cogit config git`.",kind: "text",},{@@ -114,7 +126,9 @@ export const DEFAULT_SETTINGS: PanelSettings = {catchUpModel: "haiku",messageSummaries: false,startupContext: true,- gitPolicy: "ignore",+ shareConversations: false,+ recordCommit: "ask",+ gitPolicy: "commit",agents: ["claude-code"],};@@ -131,6 +145,8 @@ export function editableSettings(settings: PanelSettings): PanelEditableSettingsupdateEveryTurns: settings.updateEveryTurns,sessionEndCatchUp: settings.sessionEndCatchUp,catchUpModel: settings.catchUpModel,+ shareConversations: settings.shareConversations,+ recordCommit: settings.recordCommit,};}diff --git a/packages/cli/test/build.test.ts b/packages/cli/test/build.test.tsindex e1074fb..a114410 100644--- a/packages/cli/test/build.test.ts+++ b/packages/cli/test/build.test.ts@@ -10,6 +10,7 @@ import { configSet } from "../src/commands/config.js";import { epochAdd } from "../src/commands/epoch.js";import { init } from "../src/commands/init.js";import { sessionWrite } from "../src/commands/session.js";+import { cogitGitignore } from "../src/git.js";import { messageHash } from "../src/messages.js";import type { LineageNode, Session } from "../src/schema/session.js";import { readConversationStore } from "../src/store/conversations.js";@@ -558,7 +559,9 @@ describe("cogit build", () => {messageSummaries: true,startupContext: true,updateEveryTurns: 5,- gitPolicy: "ignore",+ shareConversations: false,+ recordCommit: "ask",+ gitPolicy: "commit",agents: ["claude-code"],});expect(embedded(await readFile(paths().html, "utf8"))).toEqual(model);@@ -783,14 +786,15 @@ describe("cogit build", () => {expect(second.epochs[0]?.sessions[0]?.messages[0]?.unsummarized).toBeUndefined();});- it("adds the conversation gitignore line once, also in an existing project", async () => {+ it("writes the project ignore rules once, also in an existing project", async () => {const ignore = join(paths().base, ".gitignore");- // An older project has no inner .gitignore; the next build writes it.+ // A commit-policy project: a git dir and no root rule hiding .cogit/.+ await mkdir(join(root, ".git"));await rm(ignore, { force: true });await buildProject({ dir: root, io, templateHtml: TEMPLATE, quiet: true });- expect(await readFile(ignore, "utf8")).toBe("conversations/\n");+ expect(await readFile(ignore, "utf8")).toBe(cogitGitignore(false));await buildProject({ dir: root, io, templateHtml: TEMPLATE, quiet: true });- expect(await readFile(ignore, "utf8")).toBe("conversations/\n");+ expect(await readFile(ignore, "utf8")).toBe(cogitGitignore(false));});it("keeps the map when the conversation store cannot be written", async () => {@@ -821,6 +825,7 @@ describe("cogit build", () => {it("warns but still builds when the inner gitignore cannot be written", async () => {const ignore = join(paths().base, ".gitignore");+ await mkdir(join(root, ".git"));await rm(ignore, { force: true });await mkdir(ignore);const model = await buildProject({ dir: root, io, templateHtml: TEMPLATE, quiet: true });diff --git a/packages/cli/test/config-epoch.test.ts b/packages/cli/test/config-epoch.test.tsindex fa2ae7f..99e3d9e 100644--- a/packages/cli/test/config-epoch.test.ts+++ b/packages/cli/test/config-epoch.test.ts@@ -25,7 +25,7 @@ describe("config", () => {expect(io.lines).toContain("messageSummaries = false");expect(io.lines).toContain("startupContext = true");await configGet("gitPolicy", io);- expect(io.lines.at(-1)).toBe('"ignore"');+ expect(io.lines.at(-1)).toBe('"commit"');});it("sets numbers, booleans, strings and agent lists", async () => {diff --git a/packages/cli/test/hooks.test.ts b/packages/cli/test/hooks.test.tsindex 49f6249..bff92c5 100644--- a/packages/cli/test/hooks.test.ts+++ b/packages/cli/test/hooks.test.ts@@ -441,6 +441,36 @@ describe("runHook", () => {expect(spawned).toEqual([]);});+ it("commits the record at session end in auto mode, even with the catch-up off", async () => {+ await initialized(2);+ await configSet("recordCommit", "auto", fakeIo(env));+ // Nothing to catch up: the last update still leaves files to commit.+ expect(await sessionEnd()).toBeUndefined();+ expect(spawned).toEqual([["/plugin/dist/cli.js", "record-commit", "s1", "-C", root]]);++ spawned = [];+ await transcript([typed("first", 1)]);+ await configSet("sessionEndCatchUp", "false", fakeIo(env));+ expect(await sessionEnd()).toBeUndefined();+ expect(spawned).toEqual([["/plugin/dist/cli.js", "record-commit", "s1", "-C", root]]);+ });++ it("records the current session for the next code commit", async () => {+ await initialized(2);+ await runHook(+ "promptsubmit",+ JSON.stringify({ session_id: "s1", cwd: root, transcript_path: "/t/s1.jsonl" }),+ env,+ T0,+ () => {},+ );+ expect(JSON.parse(await readFile(join(root, ".cogit", "HEAD"), "utf8"))).toEqual({+ sessionId: "s1",+ transcriptPath: "/t/s1.jsonl",+ at: T0,+ });+ });+it("stays quiet at session end without a readable transcript or before init", async () => {await initialized(2);expect(await sessionEnd()).toBeUndefined();diff --git a/packages/cli/test/init.test.ts b/packages/cli/test/init.test.tsindex 268fe61..c27915b 100644--- a/packages/cli/test/init.test.ts+++ b/packages/cli/test/init.test.ts@@ -1,6 +1,8 @@+import { execFile } from "node:child_process";import { existsSync } from "node:fs";-import { mkdir, readdir, readFile, writeFile } from "node:fs/promises";+import { mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";import { basename, join } from "node:path";+import { promisify } from "node:util";import { beforeEach, describe, expect, it } from "vitest";import {allowSkill,@@ -10,7 +12,7 @@ import {setRetention,} from "../src/claude-settings.js";import { init } from "../src/commands/init.js";-import { ensureConversationGitignore, ensureGitignore, findGitRoot } from "../src/git.js";+import { cogitGitignore, ensureCogitGitignore, ensureGitignore, findGitRoot } from "../src/git.js";import { loadConfig, loadProject, loadRegistry } from "../src/store/stores.js";import { envFor, fakeIo, T0, tempDir } from "./helpers.js";@@ -57,18 +59,21 @@ describe("init", () => {expect(io.asked).toHaveLength(4);expect(await readSkillAllowed(env)).toBe(true);expect(io.lines.at(-2)).toMatch(/^Initialized proj/);- // The conversation store stays out of git even when records are committed.- expect(await readText(join(root, ".cogit", ".gitignore"))).toBe("conversations/\n");+ // Outside a git repository there is nothing to ignore and no hook to install.+ expect(existsSync(join(root, ".cogit", ".gitignore"))).toBe(false);expect(io.lines).toContain(- "Conversations are stored in .cogit/conversations/ (kept out of git, even with the commit policy).",+ "Conversations are stored in .cogit/conversations/ (kept out of git; turn on shareConversations to share them).",);});- it("adds the conversation ignore line once", async () => {+ it("writes the project ignore file once for the commit policy", async () => {await mkdir(join(root, ".cogit"));- expect(await ensureConversationGitignore(root)).toBe(true);- expect(await ensureConversationGitignore(root)).toBe(false);- expect(await readText(join(root, ".cogit", ".gitignore"))).toBe("conversations/\n");+ expect(await ensureCogitGitignore(root, "commit", false)).toBe(true);+ expect(await ensureCogitGitignore(root, "commit", false)).toBe(false);+ expect(await readText(join(root, ".cogit", ".gitignore"))).toBe(cogitGitignore(false));+ // Sharing the conversation store un-ignores it in the same file.+ expect(await ensureCogitGitignore(root, "commit", true)).toBe(true);+ expect(await readText(join(root, ".cogit", ".gitignore"))).toContain("!conversations/");});it("asks nothing when every answer is given as an option", async () => {@@ -80,7 +85,9 @@ describe("init", () => {io,);expect((await loadConfig(env)).language).toBe("Turkish");- expect(await readText(join(root, ".gitignore"))).toContain("/.cogit/state/");+ // Commit policy: the root file stays untouched, the project writes its own rules.+ expect(existsSync(join(root, ".gitignore"))).toBe(false);+ expect(await readText(join(root, ".cogit", ".gitignore"))).toBe(cogitGitignore(false));});it("asks for the git policy in a repo and writes .gitignore", async () => {@@ -237,17 +244,57 @@ describe("git helpers", () => {expect(await findGitRoot("/")).toBeUndefined();});- it("appends only missing lines and keeps existing content", async () => {+ it("adds the ignore line under the ignore policy and removes it when switching", async () => {const gi = join(root, ".gitignore");await writeFile(gi, "node_modules/");- expect(await ensureGitignore(root, "commit")).toHaveLength(4);expect(await ensureGitignore(root, "commit")).toEqual([]);+ expect(await readText(gi)).toBe("node_modules/");expect(await ensureGitignore(root, "ignore")).toEqual(["/.cogit/"]);+ expect(await ensureGitignore(root, "ignore")).toEqual([]);const text = await readText(gi);- expect(text.startsWith("node_modules/\n# cogit\n")).toBe(true);+ expect(text).toBe("node_modules/\n# cogit\n/.cogit/\n");expect(text.match(/# cogit/g)).toHaveLength(1);+ // Switching back removes only our line, never the user's.+ expect(await ensureGitignore(root, "commit")).toEqual([]);+ expect(await readText(gi)).toBe("node_modules/\n# cogit\n");expect(basename(gi)).toBe(".gitignore");});++ it("restores the record hook when init runs again on a commit project", async () => {+ const run = promisify(execFile);+ const git = (...args: string[]) => run("git", ["-C", root, ...args]);+ await git("init", "-q");+ await git("config", "user.email", "[email protected]");+ await git("config", "user.name", "Tester");+ await init(+ root,+ { name: "P", git: "commit", retention: "keep", allowSkill: false, language: "auto" },+ fakeIo(env),+ );+ const hook = join(root, ".git", "hooks", "pre-commit");+ expect(existsSync(hook)).toBe(true);+ await rm(hook);+ const io = fakeIo(env);+ await init(root, { retention: "keep" }, io);+ expect(io.lines[0]).toMatch(/^Already initialized: P/);+ expect(existsSync(hook)).toBe(true);+ });++ it("warns about an unwritable root ignore file and still initializes", async () => {+ // A directory where .gitignore belongs makes the write fail.+ await mkdir(join(root, ".git"));+ await mkdir(join(root, ".gitignore"));+ const io = fakeIo(env);+ await init(+ root,+ { name: "P", git: "ignore", retention: "keep", allowSkill: false, language: "auto" },+ io,+ );+ expect(io.warnings).toEqual(+ expect.arrayContaining([expect.stringMatching(/^could not update \.gitignore: /)]),+ );+ expect(await loadProject(root)).toMatchObject({ ok: true });+ });});describe("setRetention", () => {diff --git a/packages/cli/test/log.test.ts b/packages/cli/test/log.test.tsindex 55290a3..6644e8d 100644--- a/packages/cli/test/log.test.ts+++ b/packages/cli/test/log.test.ts@@ -55,6 +55,7 @@ describe("cogit log and show", () => {const s1 = session({sessionId: "s1",title: "Ship the parser",+ author: "Eren",epoch: "e8",startedAt: "2026-10-20T09:00:00.000Z",updatedAt: "2026-10-20T10:00:00.000Z",@@ -208,6 +209,8 @@ describe("cogit log and show", () => {const model = await log({ dir: root, io });const lines = formatLog(model);expect(lines[0]).toContain("## Later chat (s2) · unassigned");+ const byAuthor = lines.find((line) => line.startsWith("## Ship the parser"));+ expect(byAuthor).toContain("· by Eren ·");expect(lines[0]).toContain(stamp("2026-10-21T10:00:00.000Z"));expect(lines[1]).toContain(shortHash(D));expect(lines[1]).toContain("m1");diff --git a/packages/cli/test/panel.test.ts b/packages/cli/test/panel.test.tsindex 92e2f62..32d895b 100644--- a/packages/cli/test/panel.test.ts+++ b/packages/cli/test/panel.test.ts@@ -87,7 +87,9 @@ describe("buildPanel", () => {catchUpModel: "haiku",messageSummaries: false,startupContext: true,- gitPolicy: "ignore",+ shareConversations: false,+ recordCommit: "ask",+ gitPolicy: "commit",agents: ["claude-code"],},projects: [diff --git a/packages/cli/test/program-commands.test.ts b/packages/cli/test/program-commands.test.tsindex b394f26..de09062 100644--- a/packages/cli/test/program-commands.test.ts+++ b/packages/cli/test/program-commands.test.ts@@ -1,13 +1,15 @@+import { execFile } from "node:child_process";import { existsSync } from "node:fs";-import { mkdir, rm, writeFile } from "node:fs/promises";+import { mkdir, readFile, rm, writeFile } from "node:fs/promises";import { type AddressInfo, createServer as createNetServer } from "node:net";import { join } from "node:path";+import { promisify } from "node:util";import { beforeEach, describe, expect, it } from "vitest";import { readSkillAllowed } from "../src/claude-settings.js";import { createProgram } from "../src/program.js";import { globalPaths } from "../src/store/paths.js";import { loadConfig, loadProject } from "../src/store/stores.js";-import { envFor, type FakeIo, fakeIo, tempDir } from "./helpers.js";+import { envFor, type FakeIo, fakeIo, T0, tempDir } from "./helpers.js";let dir: string;let root: string;@@ -185,6 +187,67 @@ describe("commands through the CLI", () => {expect(io.lines.at(-1)).toMatch(new RegExp(`^Removed .+ \\(${gone}\\)$`));});+ it("runs the git hook and the detached record commit through the CLI", async () => {+ const run = promisify(execFile);+ const git = async (...args: string[]): Promise<string> =>+ (await run("git", ["-C", root, ...args])).stdout;+ await git("init", "-q");+ await git("config", "user.email", "[email protected]");+ await git("config", "user.name", "Tester");+ await writeFile(join(root, "a.txt"), "one\n");+ await git("add", "a.txt");+ await git("commit", "-q", "-m", "feat: base");++ await cli(+ "init",+ root,+ "--yes",+ "--git",+ "commit",+ "--name",+ "P",+ "--retention",+ "keep",+ "--language",+ "auto",+ );+ expect(await readFile(join(root, ".git", "hooks", "pre-commit"), "utf8")).toContain(+ "cogit hook pre-commit",+ );++ const session = {+ schema: 1,+ sessionId: "s1",+ agent: "claude-code",+ title: "CLI session",+ epoch: null,+ startedAt: T0,+ updatedAt: T0,+ status: { goal: "", done: [], pending: [], next: "" },+ nodes: [],+ };+ await mkdir(join(root, ".cogit", "sessions"), { recursive: true });+ await writeFile(join(root, ".cogit", "sessions", "s1.json"), JSON.stringify(session));+ await writeFile(join(root, ".cogit", "HEAD"), JSON.stringify({ sessionId: "s1", at: T0 }));+ await writeFile(join(root, "a.txt"), "two\n");+ await git("add", "a.txt");+ await cli("hook", "pre-commit", "--dir", root);+ expect(await git("diff", "--cached", "--name-only")).toContain(".cogit/sessions/s1.json");++ await cli("config", "set", "recordCommit", "auto");+ await cli("record-commit", "s1", "-C", root);+ expect((await git("log", "-1", "--format=%s")).trim()).toBe("chore(cogit): record CLI session");++ expect(await cli("config", "git", "nope")).toMatch(/^error: invalid git policy "nope"/);+ expect(await cli("config", "git", "ignore", root)).toBe("");+ expect(await readFile(join(root, ".gitignore"), "utf8")).toBe("# cogit\n/.cogit/\n");+ });++ it("refuses config git outside a git repository", async () => {+ await cli("init", root, "--yes", "--retention", "keep");+ expect(await cli("config", "git", "commit", root)).toMatch(/not in a git repository/);+ });+it("prints user errors as one line", async () => {expect(await cli("config", "get", "nope")).toMatch(/^error: unknown key "nope"/);});diff --git a/packages/cli/test/schema.test.ts b/packages/cli/test/schema.test.tsindex 1d803d7..600821e 100644--- a/packages/cli/test/schema.test.ts+++ b/packages/cli/test/schema.test.ts@@ -110,7 +110,9 @@ describe("Project and Config schemas", () => {language: "auto",updateEveryTurns: 5,sessionEndCatchUp: true,- gitPolicy: "ignore",+ gitPolicy: "commit",+ shareConversations: false,+ recordCommit: "ask",});});});diff --git a/packages/cli/test/server.test.ts b/packages/cli/test/server.test.tsindex 8c176c6..48c1ff5 100644--- a/packages/cli/test/server.test.ts+++ b/packages/cli/test/server.test.ts@@ -348,6 +348,22 @@ describe("settings write", () => {expect(html).toContain('"messageSummaries":true');});+ it("accepts the Story 9.3 settings and validates their values", async () => {+ const server = await start();+ const token = await panelToken(server);+ expect(+ (await configWrite(server, token, { key: "shareConversations", value: true })).status,+ ).toBe(200);+ expect((await configWrite(server, token, { key: "recordCommit", value: "auto" })).status).toBe(+ 200,+ );+ expect((await loadConfig(env)).shareConversations).toBe(true);+ expect((await loadConfig(env)).recordCommit).toBe("auto");+ expect(+ (await configWrite(server, token, { key: "recordCommit", value: "sometimes" })).status,+ ).toBe(400);+ });+it("rebuilds an open map so the page picks the new setting up", async () => {const server = await start();const events = openEvents(`${server.url}/events?dir=${encodeURIComponent(root)}`);@@ -418,7 +434,7 @@ describe("settings write", () => {expect((await configWrite(server, token, { key: "messageSummaries", value: "true" })).status,).toBe(400);- expect((await loadConfig(env)).gitPolicy).toBe("ignore");+ expect((await loadConfig(env)).gitPolicy).toBe("commit");expect((await loadConfig(env)).messageSummaries).toBe(false);});@@ -488,6 +504,8 @@ describe("settings read", () => {updateEveryTurns: 5,sessionEndCatchUp: true,catchUpModel: "haiku",+ shareConversations: false,+ recordCommit: "ask",},});});diff --git a/packages/cli/test/session-author.test.ts b/packages/cli/test/session-author.test.tsnew file mode 100644index 0000000..e3439cd--- /dev/null+++ b/packages/cli/test/session-author.test.ts@@ -0,0 +1,28 @@+import { mkdir } from "node:fs/promises";+import { join } from "node:path";+import { describe, expect, it, vi } from "vitest";++// A machine without a passwd entry for the running user: `userInfo` throws.+vi.mock("node:os", async (importOriginal) => {+ const actual = await importOriginal<typeof import("node:os")>();+ return {+ ...actual,+ userInfo: () => {+ throw new Error("no user entry");+ },+ };+});++import { sessionAuthor } from "../src/commands/session.js";+import { tempDir } from "./helpers.js";++describe("session author fallback", () => {+ it("uses the environment's user when the OS has none", async () => {+ const dir = await tempDir();+ const root = join(dir, "proj");+ await mkdir(root);+ expect(await sessionAuthor(root, { USER: "from-env" })).toBe("from-env");+ expect(await sessionAuthor(root, { USERNAME: "windows-user" })).toBe("windows-user");+ expect(await sessionAuthor(root, {})).toBeUndefined();+ });+});diff --git a/packages/cli/test/session-git.test.ts b/packages/cli/test/session-git.test.tsnew file mode 100644index 0000000..78dd832--- /dev/null+++ b/packages/cli/test/session-git.test.ts@@ -0,0 +1,335 @@+import { execFile } from "node:child_process";+import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";+import { userInfo } from "node:os";+import { join } from "node:path";+import { promisify } from "node:util";+import { beforeEach, describe, expect, it } from "vitest";+import { configGit, configSet } from "../src/commands/config.js";+import { sessionAuthor, sessionWrite } from "../src/commands/session.js";+import { cogitGitignore, ensureGitignore, refreshCogitGitignore } from "../src/git.js";+import { hookBlock, installGitHook, withHookBlock } from "../src/git-hooks.js";+import { runHook } from "../src/hooks/run.js";+import type { Session } from "../src/schema/session.js";+import {+ commitSessionFiles,+ maybeAutoCommit,+ readSessionHead,+ recordMessage,+ stageSessionFiles,+ uncommittedSession,+} from "../src/session-git.js";+import { projectPaths } from "../src/store/paths.js";+import { loadSession, projectJson } from "../src/store/stores.js";+import { envFor, fakeIo, T0, tempDir } from "./helpers.js";++const run = promisify(execFile);++describe("the record travels with the repo (Story 9.3)", () => {+ let dir: string;+ let root: string;+ let env: NodeJS.ProcessEnv;++ const git = async (...args: string[]): Promise<string> => {+ const { stdout } = await run("git", ["-C", root, ...args], {+ env: { ...process.env, GIT_CONFIG_NOSYSTEM: "1", HOME: dir },+ });+ return stdout;+ };++ const gitEnv = async (extra: NodeJS.ProcessEnv, ...args: string[]): Promise<string> => {+ const { stdout } = await run("git", ["-C", root, ...args], {+ env: { ...process.env, GIT_CONFIG_NOSYSTEM: "1", HOME: dir, ...extra },+ });+ return stdout;+ };++ const session = (id: string, title: string): Session => ({+ schema: 1,+ sessionId: id,+ agent: "claude-code",+ title,+ epoch: null,+ startedAt: T0,+ updatedAt: T0,+ status: { goal: "", done: [], pending: [], next: "" },+ nodes: [],+ });++ /** A `.cogit/` a repository could carry: project, one session and its events. */+ const makeProject = async (): Promise<void> => {+ const paths = projectPaths(root);+ await mkdir(paths.sessions, { recursive: true });+ await writeFile(paths.project, projectJson({ schema: 1, name: "proj", epochs: [] }));+ await writeFile(paths.session("s1"), JSON.stringify(session("s1", "My session")));+ await writeFile(paths.events("s1"), "");+ };++ beforeEach(async () => {+ dir = await tempDir();+ root = join(dir, "proj");+ await mkdir(root);+ env = envFor(dir);+ await git("init", "-q");+ await git("config", "user.email", "[email protected]");+ await git("config", "user.name", "Tester");+ await writeFile(join(root, "a.txt"), "one\n");+ await git("add", "a.txt");+ await git("commit", "-q", "-m", "feat: base");+ });++ it("parses and rejects the session HEAD", async () => {+ expect(await readSessionHead(root)).toBeUndefined();+ await makeProject();+ await writeFile(projectPaths(root).head, JSON.stringify({ sessionId: "s1", at: T0 }));+ expect(await readSessionHead(root)).toEqual({ sessionId: "s1", at: T0 });+ await writeFile(projectPaths(root).head, "{not json");+ expect(await readSessionHead(root)).toBeUndefined();+ });++ it("stages the current session only when something else is already staged", async () => {+ await makeProject();+ await writeFile(projectPaths(root).head, JSON.stringify({ sessionId: "s1", at: T0 }));+ // Nothing staged: the hook must not create a record-only commit.+ expect(await stageSessionFiles(root)).toBe(false);+ expect((await git("diff", "--cached", "--name-only")).trim()).toBe("");++ await writeFile(join(root, "a.txt"), "two\n");+ await git("add", "a.txt");+ expect(await stageSessionFiles(root)).toBe(true);+ const staged = (await git("diff", "--cached", "--name-only")).trim().split("\n");+ expect(staged).toContain(".cogit/sessions/s1.json");+ expect(staged).toContain(".cogit/sessions/s1.events.jsonl");+ });++ it("stages into the temporary index of git commit <paths>", async () => {+ await makeProject();+ await writeFile(projectPaths(root).head, JSON.stringify({ sessionId: "s1", at: T0 }));+ // git commit <paths> builds a temporary index; its path arrives as GIT_INDEX_FILE.+ const tempEnv = { GIT_INDEX_FILE: join(dir, "temp-index") };+ await gitEnv(tempEnv, "read-tree", "HEAD");+ expect(await stageSessionFiles(root, { ...process.env, ...tempEnv })).toBe(false);+ await writeFile(join(root, "a.txt"), "three\n");+ await gitEnv(tempEnv, "add", "a.txt");+ expect(await stageSessionFiles(root, { ...process.env, ...tempEnv })).toBe(true);+ const temp = (await gitEnv(tempEnv, "diff", "--cached", "--name-only")).trim();+ expect(temp).toContain(".cogit/sessions/s1.json");+ // The real index is untouched by the temporary one.+ expect((await git("diff", "--cached", "--name-only")).trim()).toBe("");+ });++ it("does nothing when the ignore policy hides the record", async () => {+ await makeProject();+ await writeFile(projectPaths(root).head, JSON.stringify({ sessionId: "s1", at: T0 }));+ await writeFile(join(root, ".gitignore"), "/.cogit/\n");+ await writeFile(join(root, "a.txt"), "two\n");+ await git("add", "a.txt");+ expect(await stageSessionFiles(root)).toBe(false);+ expect(await uncommittedSession(root, "s1")).toBe(false);+ expect((await git("diff", "--cached", "--name-only")).trim()).toBe("a.txt");+ });++ it("commits exactly the record files, leaving other staged changes alone", async () => {+ await makeProject();+ await writeFile(join(root, "a.txt"), "two\n");+ await git("add", "a.txt");+ expect(await commitSessionFiles(root, "s1", "My session")).toBe(true);+ expect((await git("log", "-1", "--format=%s")).trim()).toBe("chore(cogit): record My session");+ const files = (await git("show", "--name-only", "--format=")).trim().split("\n");+ expect(files).toContain(".cogit/sessions/s1.json");+ expect(files).not.toContain("a.txt");+ expect((await git("diff", "--cached", "--name-only")).trim()).toBe("a.txt");+ expect(await uncommittedSession(root, "s1")).toBe(false);+ });++ it("commits at session end only in auto mode", async () => {+ await makeProject();+ const io = fakeIo(env);+ await configSet("recordCommit", "off", io);+ expect(await maybeAutoCommit(root, "s1", env)).toBe(false);+ expect((await git("log", "--format=%s")).trim().split("\n")).toEqual(["feat: base"]);++ await configSet("recordCommit", "auto", io);+ expect(await maybeAutoCommit(root, "s1", env)).toBe(true);+ expect((await git("log", "-1", "--format=%s")).trim()).toBe("chore(cogit): record My session");+ // Nothing left to commit is a quiet no-op, not an error.+ expect(await commitSessionFiles(root, "s1", "My session")).toBe(false);+ // Changing the sharing setting also walks the registry's ignore files.+ await configSet("shareConversations", "true", io);+ });++ it("keeps the record commit message to one short line", () => {+ expect(recordMessage(" Multi\nline title ", "s1")).toBe(+ "chore(cogit): record Multi line title",+ );+ expect(recordMessage("", "s1")).toBe("chore(cogit): record s1");+ expect(recordMessage("x".repeat(200), "s1")).toHaveLength("chore(cogit): record ".length + 120);+ });++ it("stamps the author from git on the first write, else the OS user", async () => {+ await makeProject();+ expect(await sessionAuthor(root, env)).toBe("Tester");++ await sessionWrite({ dir: root }, fakeIo(env), async () =>+ JSON.stringify({ sessionId: "s9", title: "Authored" }),+ );+ expect((await loadSession(root, "s9")).found).toBe(true);+ const saved = await loadSession(root, "s9");+ expect(saved.found && saved.ok ? saved.data.author : undefined).toBe("Tester");++ // No git name anywhere: the OS user is the fallback.+ const noName = {+ ...env,+ GIT_CONFIG_GLOBAL: join(dir, "no-global-config"),+ GIT_CONFIG_SYSTEM: "/dev/null",+ };+ await git("config", "--unset", "user.name");+ expect(await sessionAuthor(root, noName)).toBe(userInfo().username);+ });++ it("writes stable project.json with one epoch per line", () => {+ expect(projectJson({ schema: 1, name: "p", epochs: [] })).toBe(+ '{\n "epochs": [],\n "name": "p",\n "schema": 1\n}\n',+ );+ const text = projectJson({+ schema: 1,+ name: "p",+ epochs: [{ id: "e1", title: "One", createdAt: T0 }],+ });+ expect(text).toBe(+ `{\n "epochs": [\n {"createdAt": ${JSON.stringify(T0)}, "id": "e1", "title": "One"}\n ],\n "name": "p",\n "schema": 1\n}\n`,+ );+ // Each epoch is its own line, so two people add different ones without a conflict.+ expect(text.split("\n").filter((line) => line.includes('"id"'))).toHaveLength(1);+ });+});++describe("ignore files and git hooks", () => {+ let dir: string;+ let root: string;+ let env: NodeJS.ProcessEnv;++ const git = async (...args: string[]): Promise<string> => {+ const { stdout } = await run("git", ["-C", root, ...args], {+ env: { ...process.env, GIT_CONFIG_NOSYSTEM: "1", HOME: dir },+ });+ return stdout;+ };++ beforeEach(async () => {+ dir = await tempDir();+ root = join(dir, "proj");+ await mkdir(root);+ env = envFor(dir);+ await git("init", "-q");+ await git("config", "user.email", "[email protected]");+ await git("config", "user.name", "Tester");+ await mkdir(projectPaths(root).base, { recursive: true });+ await writeFile(+ projectPaths(root).project,+ projectJson({ schema: 1, name: "proj", epochs: [] }),+ );+ });++ it("adds and removes the root ignore line with the policy", async () => {+ await ensureGitignore(root, "ignore");+ await expect(readFile(join(root, ".gitignore"), "utf8")).resolves.toBe("# cogit\n/.cogit/\n");+ await ensureGitignore(root, "commit");+ await expect(refreshCogitGitignore(root, false)).resolves.toBe(true);+ await expect(readFile(projectPaths(root).gitignore, "utf8")).resolves.toBe(+ cogitGitignore(false),+ );+ // A project that still ignores .cogit/ keeps no inner file.+ await ensureGitignore(root, "ignore");+ await expect(refreshCogitGitignore(root, true)).resolves.toBe(false);+ });++ it("switches an existing project between commit and ignore", async () => {+ const io = fakeIo(env);+ await configGit(root, "commit", io);+ await expect(readFile(projectPaths(root).gitignore, "utf8")).resolves.toBe(+ cogitGitignore(false),+ );+ const hook = await readFile(join(root, ".git", "hooks", "pre-commit"), "utf8");+ expect(hook).toContain("# >>> cogit");+ expect(hook).toContain("cogit hook pre-commit --dir");+ expect(await readFile(projectPaths(root).project, "utf8")).toContain('"proj"');++ await configGit(root, "ignore", io);+ await expect(readFile(join(root, ".gitignore"), "utf8")).resolves.toBe("# cogit\n/.cogit/\n");+ // Switching policy never deletes a record.+ await expect(readFile(projectPaths(root).project, "utf8")).resolves.toContain('"proj"');+ });++ it("keeps an existing hook and installs once", async () => {+ const file = join(root, ".git", "hooks", "pre-commit");+ await writeFile(file, "#!/bin/sh\necho user-hook\n");+ await chmod(file, 0o755);+ expect(await installGitHook(root, "pre-commit")).toBe(true);+ const text = await readFile(file, "utf8");+ expect(text.startsWith("#!/bin/sh\necho user-hook\n")).toBe(true);+ expect(text).toContain(hookBlock("pre-commit", root));+ expect(await installGitHook(root, "pre-commit")).toBe(false);+ });++ it("installs into the hooks directory git uses with core.hooksPath", async () => {+ await git("config", "core.hooksPath", ".husky");+ expect(await installGitHook(root, "pre-commit")).toBe(true);+ const text = await readFile(join(root, ".husky", "pre-commit"), "utf8");+ expect(text).toContain("cogit hook pre-commit");+ });++ it("replaces an old cogit block in place", () => {+ const old = "#!/bin/sh\n# >>> cogit\ncogit hook pre-commit || true\n# <<< cogit\n";+ const next = withHookBlock(old, hookBlock("pre-commit", "/p"));+ expect(next.match(/# >>> cogit/g)).toHaveLength(1);+ expect(next).not.toContain("cogit hook pre-commit || true");+ expect(next).toContain("--dir '/p'");+ });++ it("offers the uncommitted record at session start only in ask mode", async () => {+ const paths = projectPaths(root);+ await mkdir(paths.sessions, { recursive: true });+ const earlier: Session = {+ schema: 1,+ sessionId: "s0",+ agent: "claude-code",+ title: "Earlier work",+ epoch: null,+ startedAt: T0,+ updatedAt: T0,+ status: { goal: "", done: [], pending: [], next: "" },+ nodes: [],+ };+ await writeFile(paths.session("s0"), JSON.stringify(earlier));+ await writeFile(paths.events("s0"), "");+ const io = fakeIo(env);+ await configSet("recordCommit", "ask", io);++ const start = async (): Promise<string> => {+ const out = await runHook(+ "sessionstart",+ JSON.stringify({ session_id: "s1", cwd: root, source: "startup" }),+ env,+ T0,+ () => {},+ );+ return (+ (JSON.parse(out ?? "{}") as { hookSpecificOutput?: { additionalContext?: string } })+ .hookSpecificOutput?.additionalContext ?? ""+ );+ };++ expect(await start()).toContain("The last session's record is not committed");+ expect(await start()).toContain("chore(cogit): record Earlier work");++ await git("add", "-A");+ await git("commit", "-q", "-m", "chore(cogit): record Earlier work");+ expect(await start()).not.toContain("The last session's record is not committed");++ // `off` and `auto` never ask the agent.+ await configSet("recordCommit", "auto", io);+ await writeFile(paths.head, JSON.stringify({ sessionId: "s0", at: T0 }));+ await writeFile(paths.session("s0"), JSON.stringify({ ...earlier, title: "Changed" }));+ expect(await start()).not.toContain("The last session's record is not committed");+ });+});diff --git a/packages/cli/test/settings.test.ts b/packages/cli/test/settings.test.tsindex e3d18b2..13e3163 100644--- a/packages/cli/test/settings.test.ts+++ b/packages/cli/test/settings.test.ts@@ -19,6 +19,8 @@ describe("settings model", () => {catchUpModel: parsed.catchUpModel,messageSummaries: parsed.messageSummaries,startupContext: parsed.startupContext,+ shareConversations: parsed.shareConversations,+ recordCommit: parsed.recordCommit,gitPolicy: parsed.gitPolicy,agents: parsed.agents,});@@ -64,6 +66,8 @@ describe("settings model", () => {updateEveryTurns: 8,sessionEndCatchUp: true,catchUpModel: "haiku",+ shareConversations: false,+ recordCommit: "ask",});expect(Object.keys(editableSettings(settings)).sort()).toEqual([...PANEL_EDITABLE_KEYS].sort());});diff --git a/packages/template/src/SessionMap.tsx b/packages/template/src/SessionMap.tsxindex 8011903..931b5b0 100644--- a/packages/template/src/SessionMap.tsx+++ b/packages/template/src/SessionMap.tsx@@ -88,6 +88,11 @@ function SessionRow({</span>) : null}<span className="git-title">{session.title || session.sessionId}</span>+ {session.author ? (+ <span className="muted session-author" title={`Recorded by ${session.author}`}>+ {session.author}+ </span>+ ) : null}<span className="muted session-count">{count} message{count === 1 ? "" : "s"}</span>diff --git a/packages/template/src/SidePanel.tsx b/packages/template/src/SidePanel.tsxindex 0c2d52c..d1cfbe5 100644--- a/packages/template/src/SidePanel.tsx+++ b/packages/template/src/SidePanel.tsx@@ -195,6 +195,7 @@ function SessionSummary({ model, session }: { model: LineageViewModel; session:<><dl className="drilldown-meta"><Field label="Agent">{session.agent}</Field>+ {session.author ? <Field label="Recorded by">{session.author}</Field> : null}<Field label="Session"><code>{session.sessionId}</code></Field>@@ -277,10 +278,11 @@ function Conversation({ session, id }: { session: ViewSession | undefined; id: s</>);} else if (!session.transcriptAvailable) {+ // A clone has the session record (it travels with the repo) but usually not+ // the raw chat: conversations stay local unless `shareConversations` is on.body = (<p className="muted">- The conversation is gone: Claude Code has deleted this session's transcript. The summary- above is what remains.+ This conversation is not on this machine. The summary above is what remains.</p>);} else {diff --git a/packages/template/src/fixture.ts b/packages/template/src/fixture.tsindex 904790a..6ece598 100644--- a/packages/template/src/fixture.ts+++ b/packages/template/src/fixture.ts@@ -58,6 +58,8 @@ export const fixture: LineageViewModel = {catchUpModel: "haiku",messageSummaries: false,startupContext: true,+ shareConversations: false,+ recordCommit: "ask",gitPolicy: "ignore",agents: ["claude-code"],},diff --git a/packages/template/src/styles.css b/packages/template/src/styles.cssindex 1cbf8d2..dd64f41 100644--- a/packages/template/src/styles.css+++ b/packages/template/src/styles.css@@ -936,6 +936,16 @@ body:has(.map-shell.is-expanded) {white-space: nowrap;}+/* Who recorded the session (Story 9.3); never squeezes the title out. */+.session-author {+ flex: 0 1 auto;+ min-width: 0;+ max-width: 14ch;+ overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}+/* An epoch is a tag on a session dot, not a box around sessions. */.epoch-tag {display: inline-flex;diff --git a/packages/template/test/panel.test.ts b/packages/template/test/panel.test.tsindex 1329822..6b63990 100644--- a/packages/template/test/panel.test.ts+++ b/packages/template/test/panel.test.ts@@ -15,6 +15,8 @@ const model: PanelViewModel = {catchUpModel: "haiku",messageSummaries: false,startupContext: true,+ shareConversations: false,+ recordCommit: "ask",gitPolicy: "ignore",agents: ["claude-code"],},diff --git a/packages/template/test/session-git.test.ts b/packages/template/test/session-git.test.tsnew file mode 100644index 0000000..78fdba5--- /dev/null+++ b/packages/template/test/session-git.test.ts@@ -0,0 +1,64 @@+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { describe, expect, it } from "vitest";+import type { LineageViewModel, ViewSession } from "../../cli/src/view/model.js";+import { SessionMap } from "../src/SessionMap.js";+import { DrillDown } from "../src/SidePanel.js";+import { layoutSessionGraph } from "../src/sessionLayout.js";++const T0 = "2026-10-26T10:00:00.000Z";++const session: ViewSession = {+ sessionId: "s1",+ agent: "claude-code",+ title: "Session one",+ author: "Eren",+ epoch: "e1",+ startedAt: T0,+ updatedAt: T0,+ status: { goal: "", done: [], pending: [], next: "" },+ messages: [{ id: "h1", label: "m1", kind: "message", title: "A message", at: T0, parent: null }],+ // A clone has the record but not the raw chat.+ transcriptAvailable: false,+};++function modelOf(current: ViewSession): LineageViewModel {+ return {+ kind: "lineage",+ schema: 1,+ project: { name: "p", path: "/p", generatedAt: T0 },+ status: { goal: "", done: [], pending: [], next: "", lastActivity: T0 },+ epochs: [{ id: "e1", title: "E", createdAt: T0, sessions: [current] }],+ unassigned: [],+ };+}++describe("Story 9.3 on the map", () => {+ it("shows the author on the session row", () => {+ const model = modelOf(session);+ const html = renderToStaticMarkup(+ createElement(SessionMap, {+ model,+ graph: layoutSessionGraph(model),+ selectedSessionId: null,+ openIds: new Set<string>(),+ highlightSessionIds: new Set<string>(),+ onOpen: () => {},+ onContinue: () => {},+ }),+ );+ expect(html).toContain('class="muted session-author"');+ expect(html).toContain("Eren");+ });++ it("says a missing conversation lives on another machine", () => {+ const html = renderToStaticMarkup(+ createElement(DrillDown, {+ model: modelOf(session),+ selection: { type: "node", sessionId: "s1", nodeId: "h1" },+ onClose: () => {},+ }),+ );+ expect(html).toContain("This conversation is not on this machine");+ });+});