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
fix(git): run the hooks without cogit on PATH and link commits in every policy
Erenf15bad165960
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 70d55aa..de45d92 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,12 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).## [Unreleased]+### Fixed+- The git hooks work without a `cogit` on PATH (a plugin-only install): the hook block falls back to the CLI that installed it, run with `node`, and does nothing — no "command not found" — when neither is there; each prompt points an existing block at the current CLI, so a plugin update does not break it. `cogit hooks install` adds or refreshes the blocks by hand.+- The `Thought:` trailer is added in every project, also when the record stays out of git, so `blame` and `show <sha>` follow the exact link locally; only the record staging follows the commit policy. `init`, `cogit config git` and the rename migration install the hooks for both policies.+- The first code commit carries `.cogit/project.json` and `.cogit/.gitignore` with the session record, so a clone gets the project and the local-state rules, not only the sessions.+- `cogit show <sha>` for a commit whose thought is not recorded yet names that thought instead of "no recorded thought"; `cogit open` no longer reuses a map server of another cogit version (the server's health reports its version and an outdated one is asked to stop); the minimap hides on a narrow map instead of covering the messages; the setting reads "Record every N turns".+## [0.12.0] - 2026-10-26### Addeddiff --git a/docs/qa/test-plan.md b/docs/qa/test-plan.mdindex 92b0605..6919e0e 100644--- a/docs/qa/test-plan.md+++ b/docs/qa/test-plan.md@@ -3,3 +3,4 @@| ID | Kova | Notlar / case'ler | Durum ||----|------|-------------------|-------|| 2.6 | unit | `outlinePath`: epoch → epoch, session → epoch, nested node → tam ancestor zinciri, unassigned grubu, bilinmeyen id. Outline UI akışı (toggle, grafik odağı, drill-down, console) `browse` MCP ile `file://` üzerinde elle doğrulandı; template UI için otomatik e2e harness yok. | yazıldı |+| 2026-10-26 fixes | unit | git hook bloğu: PATH'te `cogit` yoksa kurulan CLI `node` ile, ikisi de yoksa sessiz (gerçek `sh` koşumu); `refreshGitHooks` yalnız mevcut bloğu yeniler + UserPromptSubmit çağırır; `hooks install`; ignore politikasında da hook (init, `config git`, migrasyon) ve trailer; pre-commit `project.json` + `.cogit/.gitignore`'ı da ekler; `show <sha>` kaydedilmemiş düşünceyi adlandırır, `readCommitThought`; `/health` sürümü, `/api/stop` (Origin'li POST reddi), `stopStaleServer` + `ensureServer` eski sürümü emekliye ayırır. Minimap gizleme CSS (tarayıcıda elle). | yazıldı |diff --git a/packages/cli/src/commands/config.ts b/packages/cli/src/commands/config.tsindex 3ae43f9..3a31578 100644--- a/packages/cli/src/commands/config.ts+++ b/packages/cli/src/commands/config.ts@@ -79,7 +79,7 @@ export async function configGit(dir: string, policy: GitPolicy, io: Io): Promiseconst added = await ensureGitignore(root, policy);const config = await loadConfig(io.env);await ensureCogitGitignore(root, policy, config.shareConversations);- if (policy === "commit") await installGitHooks(root);+ await installGitHooks(root);io.out(`Git policy for ${project.data.name}: ${policy}`);if (added.length > 0) io.out(`Added to .gitignore: ${added.join(", ")}`);}diff --git a/packages/cli/src/commands/hooks.ts b/packages/cli/src/commands/hooks.tsindex 6d942ec..9cc1e00 100644--- a/packages/cli/src/commands/hooks.ts+++ b/packages/cli/src/commands/hooks.ts@@ -1,18 +1,39 @@-import { uninstallGitHooks } from "../git-hooks.js";+import { installGitHooks, uninstallGitHooks } from "../git-hooks.js";import { CliError, type Io } from "../io.js";import { resolveProjectRoot } from "../store/root.js";import { loadProject } from "../store/stores.js";+/** The project root of an initialized project, or a clear error. */+async function initializedRoot(dir: string): Promise<string> {+ 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);+ return root;+}++/**+ * `cogit hooks install`: adds (or refreshes) cogit's block in the git hooks, for+ * a project set up before the hooks existed or after `hooks uninstall`. The+ * user's own hook lines stay as they are.+ */+export async function hooksInstall(dir: string, io: Io): Promise<void> {+ const root = await initializedRoot(dir);+ const added = await installGitHooks(root);+ io.out(+ added.length === 0+ ? "The cogit hook blocks are already current."+ : `Added the cogit block to: ${added.join(", ")}`,+ );+}+/*** `cogit hooks uninstall` (Story 9.4): removes only the marked block cogit added* to a git hook, so a user who wants their hooks back exactly as they were can* get them without editing files by hand. No record and no setting changes.*/export async function hooksUninstall(dir: string, 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);+ const root = await initializedRoot(dir);const removed = await uninstallGitHooks(root);io.out(removed.length === 0diff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.tsindex ede846a..7e94556 100644--- a/packages/cli/src/commands/init.ts+++ b/packages/cli/src/commands/init.ts@@ -156,20 +156,20 @@ async function applyGitPolicy(await bestEffort(io, "could not write .cogit/.gitignore", () =>ensureCogitGitignore(root, policy, shareConversations),);- if (policy === "commit")- await bestEffort(io, "could not install the git hooks", () => installGitHooks(root));+ // Every policy: the trailer links commits locally; staging follows the policy.+ await bestEffort(io, "could not install the git hooks", () => installGitHooks(root));}/**- * Brings an already initialized project up to date: a repository that commits- * its records gets the new `.cogit/.gitignore` and the hooks, without changing the- * policy the user chose at setup.+ * Brings an already initialized project up to date: every repository gets the+ * hooks, one that commits its records also the new `.cogit/.gitignore`, 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);+ if (!(await cogitIgnored(root)))+ await refreshCogitGitignore(root, (await loadConfig(io.env)).shareConversations);await installGitHooks(root);});}diff --git a/packages/cli/src/commands/log.ts b/packages/cli/src/commands/log.tsindex 4e5bb81..5afefe2 100644--- a/packages/cli/src/commands/log.ts+++ b/packages/cli/src/commands/log.ts@@ -5,7 +5,12 @@ import type { LineageNode, Session } from "../schema/session.js";import { applyEvents, readEvents } from "../store/events.js";import { resolveProjectRoot } from "../store/root.js";import { loadAllSessions, loadProject } from "../store/stores.js";-import { attachThoughtTrailers, earliestSessionStart, readThoughtTrailers } from "../thought.js";+import {+ attachThoughtTrailers,+ earliestSessionStart,+ readCommitThought,+ readThoughtTrailers,+} from "../thought.js";import { buildFileHistory, type FileSourceSession } from "../view/files.js";import { buildMessages } from "../view/lineage.js";import type { ViewFile, ViewNode } from "../view/model.js";@@ -539,7 +544,17 @@ export async function show(opts: ShowOptions): Promise<ShowModel> {const sessions = await loadEffectiveSessions(root, opts.io);const result = resolveRef(sessions, opts.ref);if (result.kind === "invalid") throw new CliError(`invalid ref "${opts.ref}": ${result.reason}`);- if (result.kind === "unknown") throw new CliError(result.reason);+ if (result.kind === "unknown") {+ // The commit names a thought the record has not caught up with yet.+ const thought = COMMIT_REF.test(opts.ref)+ ? await readCommitThought(root, opts.ref, opts.io.env)+ : undefined;+ if (thought !== undefined)+ throw new CliError(+ `commit ${opts.ref} comes from thought ${thought}, which is not recorded yet; it appears after the next record update`,+ );+ throw new CliError(result.reason);+ }if (result.kind === "ambiguous") {for (const candidate of result.candidates) {opts.io.out(diff --git a/packages/cli/src/git-hooks.ts b/packages/cli/src/git-hooks.tsindex 5d3d035..9ed9097 100644--- a/packages/cli/src/git-hooks.ts+++ b/packages/cli/src/git-hooks.ts@@ -1,3 +1,4 @@+import { realpathSync } from "node:fs";import { chmod, mkdir, readFile, rm, stat } from "node:fs/promises";import { join } from "node:path";import { findGitRoot, gitHooksDir } from "./git.js";@@ -14,13 +15,46 @@ import { addThoughtTrailer } from "./thought.js";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 [+/**+ * The CLI that installs the hooks: the fallback when `cogit` is not on PATH, the+ * common case for a plugin-only install. A path that later disappears (a plugin+ * update) is refreshed by the next UserPromptSubmit hook.+ */+export function currentCliPath(): string | undefined {+ const entry = process.argv[1];+ if (entry === undefined || entry === "") return undefined;+ try {+ return realpathSync(entry);+ } catch {+ return undefined;+ }+}++/**+ * The block `init` adds to a hook; `"$@"` passes git's arguments through. A+ * `cogit` on PATH wins; otherwise the CLI that installed the block runs under+ * `node`; with neither, the hook does nothing and the commit goes on.+ */+export function hookBlock(+ event: string,+ projectRoot: string,+ cliPath: string | null = currentCliPath() ?? null,+): string {+ const args = `hook ${event} --dir ${shellQuote(projectRoot)} "$@"`;+ const lines = [BLOCK_START,- `cogit hook ${event} --dir ${shellQuote(projectRoot)} "$@" || true`,- BLOCK_END,- ].join("\n");+ "if command -v cogit >/dev/null 2>&1; then",+ ` cogit ${args} || true`,+ ];+ if (cliPath !== null) {+ const cli = shellQuote(cliPath);+ lines.push(+ `elif command -v node >/dev/null 2>&1 && [ -f ${cli} ]; then`,+ ` node ${cli} ${args} || true`,+ );+ }+ lines.push("fi", BLOCK_END);+ return lines.join("\n");}/** Single quotes for the shell, with the embedded single quote escaped. */@@ -96,6 +130,24 @@ export async function installGitHooks(root: string): Promise<GitHookEvent[]> {return installed;}+/**+ * Rewrites the blocks that are already there, so they point at the CLI running+ * now (a plugin update moves it). Never adds a block to a hook that has none.+ */+export async function refreshGitHooks(root: string): Promise<GitHookEvent[]> {+ const gitRoot = await findGitRoot(root);+ if (gitRoot === undefined) return [];+ const dir = await gitHooksDir(gitRoot);+ if (dir === undefined) return [];+ const refreshed: GitHookEvent[] = [];+ for (const event of GIT_HOOK_EVENTS) {+ const current = await readFile(join(dir, event), "utf8").catch(() => undefined);+ if (current === undefined || !current.includes(BLOCK_START)) continue;+ if (await installGitHook(root, event)) refreshed.push(event);+ }+ return refreshed;+}+/*** Removes only cogit's block from the hooks it installed (Story 9.4): the user's* own lines stay, and a file that held nothing but the shebang cogit wrote isdiff --git a/packages/cli/src/hooks/promptsubmit.ts b/packages/cli/src/hooks/promptsubmit.tsindex a0d15ee..f6da9b9 100644--- a/packages/cli/src/hooks/promptsubmit.ts+++ b/packages/cli/src/hooks/promptsubmit.ts@@ -1,3 +1,4 @@+import { refreshGitHooks } from "../git-hooks.js";import { atomicWriteJson } from "../store/fs.js";import { projectPaths } from "../store/paths.js";import type { HookContext } from "./run.js";@@ -17,5 +18,7 @@ export async function onPromptSubmit(ctx: HookContext): Promise<undefined> {: { transcriptPath: ctx.input.transcript_path }),at: ctx.now,});+ // A plugin update moves the CLI: point the git hooks' blocks at this one.+ await refreshGitHooks(ctx.root).catch(() => undefined);return undefined;}diff --git a/packages/cli/src/program.ts b/packages/cli/src/program.tsindex aa02ca6..1937d22 100644--- a/packages/cli/src/program.ts+++ b/packages/cli/src/program.ts@@ -12,7 +12,7 @@ import {configSet,} from "./commands/config.js";import { epochAdd } from "./commands/epoch.js";-import { hooksUninstall } from "./commands/hooks.js";+import { hooksInstall, hooksUninstall } from "./commands/hooks.js";import { type InitOptions, init } from "./commands/init.js";import { formatShow, log, logFile, show } from "./commands/log.js";import { migrateIds } from "./commands/migrate.js";@@ -380,6 +380,11 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =const hooks = program.command("hooks").description("manage the git hooks cogit adds to a project");+ hooks+ .command("install")+ .description("add or refresh the cogit block in this project's git hooks")+ .argument("[dir]", "project directory", ".")+ .action(run(async (dir: string) => hooksInstall(dir, makeIo(false))));hooks.command("uninstall").description("remove only the cogit block from the git hooks it installed")diff --git a/packages/cli/src/server.ts b/packages/cli/src/server.tsindex 698c1af..22b6378 100644--- a/packages/cli/src/server.ts+++ b/packages/cli/src/server.ts@@ -10,6 +10,7 @@ import {import type { AddressInfo } from "node:net";import { basename, join, resolve } from "node:path";import { fileURLToPath } from "node:url";+import pkg from "../package.json" with { type: "json" };import { defaultAgent } from "./agents/index.js";import { buildProject } from "./commands/build.js";import { defaultsPrompter, type Io } from "./io.js";@@ -22,6 +23,9 @@ import { isPanelEditableKey, LIVE_META_NAME, TOKEN_META_NAME } from "./view/modeimport { buildPanel, panelSettings } from "./view/panel.js";import { editableSettings } from "./view/settings.js";+/** The CLI's version: a server of another version is not reused (see `ensureServer`). */+const VERSION: string = pkg.version;+/** A page nobody is looking at is a dead server after this long. */export const DEFAULT_IDLE_MS = 30 * 60 * 1000;@@ -465,6 +469,17 @@ export async function startMapServer(opts: MapServerOptions): Promise<MapServer>return;}const url = new URL(req.url ?? "/", `http://${HOST}:${port}`);+ // `open` of a newer cogit retires a server of another version. Browsers+ // always send Origin on a POST, so no web page can stop it.+ if (url.pathname === "/api/stop") {+ if (req.headers.origin !== undefined) {+ respond(res, 403, "forbidden");+ return;+ }+ respond(res, 200, "stopping");+ void close();+ return;+ }if (url.pathname !== "/api/config") {respond(res, 405, "method not allowed");return;@@ -494,7 +509,9 @@ export async function startMapServer(opts: MapServerOptions): Promise<MapServer>"content-type": "application/json","cache-control": "no-store",});- res.end(JSON.stringify({ ok: true, name: "cogit", home: globalPaths(env).base }));+ res.end(+ JSON.stringify({ ok: true, name: "cogit", home: globalPaths(env).base, version: VERSION }),+ );return;}const target = await pageTarget(env, url);@@ -581,6 +598,44 @@ export async function startMapServer(opts: MapServerOptions): Promise<MapServer>interface HealthBody {name?: unknown;home?: unknown;+ version?: unknown;+}++/** This user's cogit server on the port, with its version; undefined otherwise. */+async function serverVersion(url: string, env: NodeJS.ProcessEnv): Promise<string | undefined> {+ try {+ const response = await fetch(`${url}/health`, { signal: AbortSignal.timeout(500) });+ if (!response.ok) return undefined;+ const body = (await response.json()) as HealthBody;+ if (body.name !== "cogit" || body.home !== globalPaths(env).base) return undefined;+ return typeof body.version === "string" ? body.version : "";+ } catch {+ return undefined;+ }+}++/**+ * Asks a server of another cogit version (an upgrade left it running) to stop,+ * so `open` does not serve pages with old code. A server too old to know the+ * request keeps running; `open` then falls back to the file.+ */+export async function stopStaleServer(url: string, env: NodeJS.ProcessEnv): Promise<boolean> {+ const version = await serverVersion(url, env);+ if (version === undefined || version === VERSION) return false;+ try {+ const response = await fetch(`${url}/api/stop`, {+ method: "POST",+ signal: AbortSignal.timeout(500),+ });+ if (!response.ok) return false;+ } catch {+ return false;+ }+ for (let i = 0; i < 20; i++) {+ await delay(50);+ if ((await serverVersion(url, env)) === undefined) return true;+ }+ return false;}/**@@ -592,7 +647,7 @@ export async function checkHealth(url: string, env: NodeJS.ProcessEnv): Promise<const response = await fetch(`${url}/health`, { signal: AbortSignal.timeout(500) });if (!response.ok) return false;const body = (await response.json()) as HealthBody;- return body.name === "cogit" && body.home === globalPaths(env).base;+ return body.name === "cogit" && body.home === globalPaths(env).base && body.version === VERSION;} catch {return false;}@@ -623,6 +678,8 @@ export interface EnsureServerDeps {spawn?: (cli: string, port: number, env: NodeJS.ProcessEnv) => void;/** Health probe; tests replace the network with a function. */health?: (url: string, env: NodeJS.ProcessEnv) => Promise<boolean>;+ /** Retires a server of another version before a new one starts. */+ stopStale?: (url: string, env: NodeJS.ProcessEnv) => Promise<boolean>;/** How long to wait for a spawned server before giving up. */waitMs?: number;}@@ -644,6 +701,7 @@ export async function ensureServer(const base = `http://${HOST}:${serverPort}`;const health = deps.health ?? checkHealth;if (await health(base, env)) return base;+ await (deps.stopStale ?? stopStaleServer)(base, env);const cli = deps.cli ?? process.argv[1] ?? fileURLToPath(import.meta.url);(deps.spawn ?? spawnServerProcess)(cli, serverPort, env);diff --git a/packages/cli/src/session-git.ts b/packages/cli/src/session-git.tsindex 66ac21f..b91bbea 100644--- a/packages/cli/src/session-git.ts+++ b/packages/cli/src/session-git.ts@@ -60,8 +60,14 @@ async function git(*/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))+ const session = [paths.session(sessionId), paths.events(sessionId)].filter((file) =>+ existsSync(file),+ );+ if (session.length === 0) return [];+ // The project file and the ignore rules travel with the first record: a clone+ // without them has sessions but no project, and no rules for the local state.+ const shared = [paths.project, paths.gitignore].filter((file) => existsSync(file));+ return [...session, ...shared].map((file) => relative(gitRoot, file).split(sep).join("/")).filter((file) => file !== "" && !file.startsWith(".."));}diff --git a/packages/cli/src/store/migrate.ts b/packages/cli/src/store/migrate.tsindex f667b19..075aa92 100644--- a/packages/cli/src/store/migrate.ts+++ b/packages/cli/src/store/migrate.ts@@ -1,7 +1,6 @@import { existsSync } from "node:fs";import { readFile, rename, stat } from "node:fs/promises";import { join, resolve, sep } from "node:path";-import { cogitIgnored } from "../git.js";import { atomicWrite, atomicWriteJson } from "./fs.js";import {CONFIG_DIR_NAME,@@ -89,13 +88,11 @@ export async function migrateProject(root: string): Promise<boolean> {const next = renameGitignoreLines(text);if (next !== text) await atomicWrite(gitignore, next).catch(() => undefined);}- // A project that commits its record gets the git hooks the rename arrived with- // (Story 9.4: the `Thought:` trailer). Dynamic import keeps this module — which+ // The project gets the git hooks the rename arrived with (Story 9.4: the+ // `Thought:` trailer, in every policy). Dynamic import keeps this module — which// every command loads — free of the hook stack; a failure is silence.- if (!(await cogitIgnored(dir))) {- const { installGitHooks } = await import("../git-hooks.js");- await installGitHooks(dir).catch(() => undefined);- }+ const { installGitHooks } = await import("../git-hooks.js");+ await installGitHooks(dir).catch(() => undefined);return true;}diff --git a/packages/cli/src/thought.ts b/packages/cli/src/thought.tsindex d92e59a..8416556 100644--- a/packages/cli/src/thought.ts+++ b/packages/cli/src/thought.ts@@ -3,7 +3,7 @@ import { access } from "node:fs/promises";import { isAbsolute, resolve } from "node:path";import { promisify } from "node:util";import { defaultAgent } from "./agents/index.js";-import { cogitIgnored, findGitRoot } from "./git.js";+import { findGitRoot } from "./git.js";import { messageHash } from "./messages.js";import type { Session } from "./schema/session.js";import { readSessionHead } from "./session-git.js";@@ -56,8 +56,8 @@ function messagePath(file: string): string {/*** Adds the `Thought:` trailer to the prepared commit message (Story 9.4). Skip- * merges and squashes, a missing or stale `.cogit/HEAD`, an unreadable transcript- * and a project whose records are kept out of git. `--if-exists doNothing` keeps+ * merges and squashes, a missing or stale `.cogit/HEAD` and an unreadable+ * transcript. `--if-exists doNothing` keeps* a trailer an `--amend` already carried. A failure is the caller's to swallow:* this never blocks the commit.*/@@ -65,9 +65,9 @@ export async function addThoughtTrailer(opts: TrailerOptions): Promise<boolean>const env = opts.env ?? process.env;if (captureDisabled(env)) return false;if (opts.source === "merge" || opts.source === "squash") return false;+ // Every policy gets the trailer: with the ignore policy the record stays on this+ // machine, but `blame` and `show <sha>` here still follow the exact link.const root = resolve(opts.dir);- // A record that stays local cannot explain a commit to anyone else.- if (await cogitIgnored(root)) return false;const head = await readSessionHead(root);if (head === undefined || head.at === undefined) return false;@@ -160,6 +160,24 @@ export async function readThoughtTrailers(}}+/** The `Thought:` value of one commit, or undefined (no trailer, no such commit). */+export async function readCommitThought(+ root: string,+ ref: string,+ env?: NodeJS.ProcessEnv,+): Promise<string | undefined> {+ const gitRoot = await findGitRoot(root);+ if (gitRoot === undefined) return undefined;+ const args = ["-C", gitRoot, "log", "-1", "--format=%(trailers:key=Thought,valueonly)", ref];+ try {+ const { stdout } = await exec("git", args, env === undefined ? undefined : { env });+ const value = String(stdout).trim().split("\n")[0]?.trim() ?? "";+ return THOUGHT_VALUE.test(value) ? value : undefined;+ } catch {+ return undefined;+ }+}+/** The earliest session start, so the trailer read stops at the record's horizon. */export function earliestSessionStart(sessions: readonly Session[]): string | undefined {let earliest: string | undefined;diff --git a/packages/cli/src/view/settings.ts b/packages/cli/src/view/settings.tsindex 5f51353..841fdc2 100644--- a/packages/cli/src/view/settings.ts+++ b/packages/cli/src/view/settings.ts@@ -53,7 +53,7 @@ const EDITABLE: FieldSpec[] = [},{key: "updateEveryTurns",- label: "Update every turns",+ label: "Record every N turns",help: "Ask the agent to record after this many turns.",kind: "number",},diff --git a/packages/cli/test/hooks.test.ts b/packages/cli/test/hooks.test.tsindex bff92c5..f034a69 100644--- a/packages/cli/test/hooks.test.ts+++ b/packages/cli/test/hooks.test.ts@@ -1,10 +1,13 @@+import { execFile } from "node:child_process";import { existsSync } from "node:fs";import { mkdir, readFile, rm, writeFile } from "node:fs/promises";import { join } from "node:path";+import { promisify } from "node:util";import { beforeEach, describe, expect, it } from "vitest";import { configHintOff, configHintOn, configSet } from "../src/commands/config.js";import { init } from "../src/commands/init.js";import { sessionWrite } from "../src/commands/session.js";+import { hookBlock } from "../src/git-hooks.js";import { runHook, spawnDetachedProcess } from "../src/hooks/run.js";import {COMPACT_REQUEST,@@ -471,6 +474,21 @@ describe("runHook", () => {});});+ it("points an existing git hook block at the CLI running now", async () => {+ await initialized(2);+ await promisify(execFile)("git", ["-C", root, "init", "-q"]);+ const hook = join(root, ".git", "hooks", "pre-commit");+ await writeFile(hook, "#!/bin/sh\n# >>> cogit\ncogit hook pre-commit || true\n# <<< cogit\n");+ await runHook(+ "promptsubmit",+ JSON.stringify({ session_id: "s1", cwd: root }),+ env,+ T0,+ () => {},+ );+ expect(await readFile(hook, "utf8")).toContain(hookBlock("pre-commit", root));+ });+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 c56ed5c..8dc82a4 100644--- a/packages/cli/test/init.test.ts+++ b/packages/cli/test/init.test.ts@@ -260,6 +260,22 @@ describe("git helpers", () => {expect(basename(gi)).toBe(".gitignore");});+ it("installs the git hooks with the ignore policy too, for the trailer", async () => {+ const run = promisify(execFile);+ await run("git", ["-C", root, "init", "-q"]);+ await init(+ root,+ { name: "P", git: "ignore", retention: "keep", allowSkill: false, language: "auto" },+ fakeIo(env),+ );+ const hook = await readText(join(root, ".git", "hooks", "prepare-commit-msg"));+ expect(hook).toContain("hook prepare-commit-msg --dir");+ // Running init again on the ignore project keeps the hooks current.+ await rm(join(root, ".git", "hooks", "prepare-commit-msg"));+ await init(root, { allowSkill: false }, fakeIo(env));+ expect(existsSync(join(root, ".git", "hooks", "prepare-commit-msg"))).toBe(true);+ });+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]);diff --git a/packages/cli/test/migrate.test.ts b/packages/cli/test/migrate.test.tsindex d49f1d2..545ed16 100644--- a/packages/cli/test/migrate.test.ts+++ b/packages/cli/test/migrate.test.ts@@ -1,6 +1,8 @@+import { execFile } from "node:child_process";import { existsSync } from "node:fs";import { chmod, mkdir, readFile, writeFile } from "node:fs/promises";import { join } from "node:path";+import { promisify } from "node:util";import { describe, expect, it } from "vitest";import { atomicWriteJson } from "../src/store/fs.js";import {@@ -35,6 +37,16 @@ describe("migrateProject", () => {expect(await migrateProject(root)).toBe(false);});+ it("installs the git hooks in a repository that keeps its record out of git", async () => {+ const root = await tempDir();+ await promisify(execFile)("git", ["-C", root, "init", "-q"]);+ await mkdir(join(root, ".codelineage"), { recursive: true });+ await writeFile(join(root, ".gitignore"), "/.codelineage/\n");+ expect(await migrateProject(root)).toBe(true);+ const hook = await readFile(join(root, ".git", "hooks", "prepare-commit-msg"), "utf8");+ expect(hook).toContain("hook prepare-commit-msg --dir");+ });+it("leaves the old dir alone when the filesystem refuses the rename", async () => {const root = await tempDir();await mkdir(join(root, ".codelineage"), { recursive: true });diff --git a/packages/cli/test/program-commands.test.ts b/packages/cli/test/program-commands.test.tsindex 9c8fc8b..924660d 100644--- a/packages/cli/test/program-commands.test.ts+++ b/packages/cli/test/program-commands.test.ts@@ -216,6 +216,8 @@ describe("commands through the CLI", () => {expect(await readFile(join(root, ".git", "hooks", "pre-commit"), "utf8")).toContain("cogit hook pre-commit",);+ await cli("hooks", "install", root);+ expect(io.lines.at(-1)).toBe("The cogit hook blocks are already current.");const session = {schema: 1,diff --git a/packages/cli/test/server.test.ts b/packages/cli/test/server.test.tsindex 5b8fd59..2618508 100644--- a/packages/cli/test/server.test.ts+++ b/packages/cli/test/server.test.ts@@ -10,10 +10,12 @@ import {import { type AddressInfo, createServer as createNetServer } from "node:net";import { join } from "node:path";import { afterEach, beforeEach, describe, expect, it } from "vitest";+import pkg from "../package.json" with { type: "json" };import { buildProject } from "../src/commands/build.js";import { init } from "../src/commands/init.js";import {CONFIG_TOKEN_HEADER,+ checkHealth,ensureServer,injectLiveMeta,injectTokenMeta,@@ -21,6 +23,7 @@ import {mapPageUrl,spawnServerProcess,startMapServer,+ stopStaleServer,} from "../src/server.js";import { atomicWrite } from "../src/store/fs.js";import { globalPaths, projectPaths } from "../src/store/paths.js";@@ -266,7 +269,7 @@ describe("map server", () => {expect((await request(mapPageUrl(server.url, root))).status).toBe(500);});- it("answers its health with this home", async () => {+ it("answers its health with this home and version", async () => {const server = await start();const reply = await request(`${server.url}/health`);expect(reply.status).toBe(200);@@ -274,7 +277,21 @@ describe("map server", () => {ok: true,name: "cogit",home: globalPaths(env).base,+ version: pkg.version,});+ expect(await checkHealth(server.url, env)).toBe(true);+ });++ it("stops on /api/stop from the CLI, never from a page", async () => {+ const server = await start();+ const fromPage = await fetch(`${server.url}/api/stop`, {+ method: "POST",+ headers: { origin: server.url },+ });+ expect(fromPage.status).toBe(403);+ const fromCli = await fetch(`${server.url}/api/stop`, { method: "POST" });+ expect(fromCli.status).toBe(200);+ await server.closed;});it("rejects a foreign Host header", async () => {@@ -630,6 +647,65 @@ describe("ensureServer", () => {}});+ it("retires a server of another version and starts a current one", async () => {+ let stopped = false;+ const stale = createHttpServer((req, res) => {+ if (req.method === "POST" && req.url === "/api/stop") {+ stopped = true;+ res.end("stopping");+ stale.close();+ stale.closeAllConnections();+ return;+ }+ res.writeHead(200, { "content-type": "application/json" });+ res.end(+ JSON.stringify({ ok: true, name: "cogit", home: globalPaths(env).base, version: "0.0.1" }),+ );+ });+ const port = await listen(stale);+ const base = `http://127.0.0.1:${port}`;+ await updateConfig((config) => ({ ...config, serverPort: port }), env);+ expect(await checkHealth(base, env)).toBe(false);+ const url = await ensureServer(env, {+ spawn: () => {+ void startMapServer({ env, port }).then((server) => servers.push(server));+ },+ waitMs: 2000,+ });+ expect(stopped).toBe(true);+ expect(url).toBe(base);+ expect(await checkHealth(base, env)).toBe(true);+ // A current server is left alone.+ expect(await stopStaleServer(base, env)).toBe(false);+ });++ it("leaves an old server that cannot be asked to stop", async () => {+ const reply = (status: number, destroy: boolean) =>+ createHttpServer((req, res) => {+ if (req.method === "POST") {+ if (destroy) {+ req.socket.destroy();+ return;+ }+ res.writeHead(status);+ res.end();+ return;+ }+ res.writeHead(200, { "content-type": "application/json" });+ res.end(JSON.stringify({ ok: true, name: "cogit", home: globalPaths(env).base }));+ });+ // Refuses, drops the request, or says yes and keeps running.+ for (const old of [reply(405, false), reply(200, true), reply(200, false)]) {+ const port = await listen(old);+ try {+ expect(await stopStaleServer(`http://127.0.0.1:${port}`, env)).toBe(false);+ } finally {+ old.closeAllConnections();+ await new Promise<void>((done) => old.close(() => done()));+ }+ }+ });+it("starts one when nothing is listening", async () => {const port = await freePort();await updateConfig((config) => ({ ...config, serverPort: port }), env);diff --git a/packages/cli/test/session-git.test.ts b/packages/cli/test/session-git.test.tsindex 378afea..816eade 100644--- a/packages/cli/test/session-git.test.ts+++ b/packages/cli/test/session-git.test.ts@@ -5,6 +5,7 @@ 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 { hooksInstall, hooksUninstall } from "../src/commands/hooks.js";import { sessionAuthor, sessionWrite } from "../src/commands/session.js";import {cogitGitignore,@@ -12,7 +13,13 @@ import {ensureGitignore,refreshCogitGitignore,} from "../src/git.js";-import { hookBlock, installGitHook, withHookBlock } from "../src/git-hooks.js";+import {+ currentCliPath,+ hookBlock,+ installGitHook,+ refreshGitHooks,+ withHookBlock,+} from "../src/git-hooks.js";import { runHook } from "../src/hooks/run.js";import type { Session } from "../src/schema/session.js";import {@@ -295,6 +302,104 @@ describe("ignore files and git hooks", () => {expect(next).toContain("--dir '/p'");});+ it("carries project.json and the inner ignore file with the first record", async () => {+ await mkdir(projectPaths(root).sessions, { recursive: true });+ await writeFile(projectPaths(root).session("s1"), "{}\n");+ await writeFile(projectPaths(root).gitignore, cogitGitignore(false));+ await writeFile(projectPaths(root).head, JSON.stringify({ sessionId: "s1", at: T0 }));+ 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).toEqual(+ expect.arrayContaining([+ "a.txt",+ ".cogit/sessions/s1.json",+ ".cogit/project.json",+ ".cogit/.gitignore",+ ]),+ );+ });++ it("falls back to the installing CLI under node, else does nothing", () => {+ const withCli = hookBlock("pre-commit", "/p", "/opt/cogit/cli.js");+ expect(withCli).toContain("if command -v cogit >/dev/null 2>&1; then");+ expect(withCli).toContain(` cogit hook pre-commit --dir '/p' "$@" || true`);+ expect(withCli).toContain(` node '/opt/cogit/cli.js' hook pre-commit --dir '/p' "$@" || true`);+ const bare = hookBlock("pre-commit", "/p", null);+ expect(bare).not.toContain("node ");+ expect(bare.endsWith("fi\n# <<< cogit")).toBe(true);+ });++ it("has no fallback CLI path when the entry script is unknown", () => {+ const saved = process.argv[1];+ try {+ process.argv[1] = join(dir, "missing.js");+ expect(currentCliPath()).toBeUndefined();+ process.argv[1] = "";+ expect(currentCliPath()).toBeUndefined();+ } finally {+ process.argv[1] = saved as string;+ }+ });++ it("runs the CLI through node when cogit is not on PATH", async () => {+ // A stand-in CLI that records the arguments the hook passed.+ const marker = join(dir, "called.txt");+ const cli = join(dir, "cli.js");+ await writeFile(+ cli,+ `require("node:fs").writeFileSync(${JSON.stringify(marker)}, process.argv.slice(2).join(" "));\n`,+ );+ const hook = join(dir, "hook.sh");+ await writeFile(hook, `#!/bin/sh\n${hookBlock("pre-commit", root, cli)}\n`);+ const path = `${join(process.execPath, "..")}:/usr/bin:/bin`;+ await run("sh", [hook, "x"], { env: { PATH: path } });+ expect(await readFile(marker, "utf8")).toBe(`hook pre-commit --dir ${root} x`);+ });++ it("stays silent and succeeds with neither cogit nor the CLI", async () => {+ const hook = join(dir, "hook.sh");+ await writeFile(hook, `#!/bin/sh\n${hookBlock("pre-commit", root, join(dir, "gone.js"))}\n`);+ const { stderr } = await run("sh", [hook], { env: { PATH: "/usr/bin:/bin" } });+ expect(stderr).toBe("");+ });++ it("refreshes only the hooks that already carry a cogit block", async () => {+ const hooks = join(root, ".git", "hooks");+ await writeFile(+ join(hooks, "pre-commit"),+ "#!/bin/sh\n# >>> cogit\ncogit hook pre-commit || true\n# <<< cogit\n",+ );+ await writeFile(join(hooks, "prepare-commit-msg"), "#!/bin/sh\necho mine\n");+ expect(await refreshGitHooks(root)).toEqual(["pre-commit"]);+ expect(await readFile(join(hooks, "pre-commit"), "utf8")).toContain(+ hookBlock("pre-commit", root),+ );+ expect(await readFile(join(hooks, "prepare-commit-msg"), "utf8")).toBe(+ "#!/bin/sh\necho mine\n",+ );+ expect(await refreshGitHooks(root)).toEqual([]);+ expect(await refreshGitHooks(join(dir, "not-a-repo"))).toEqual([]);+ });++ it("installs the hooks on request and with the ignore policy", async () => {+ const io = fakeIo(env);+ const other = join(dir, "other");+ await mkdir(other);+ await expect(hooksInstall(other, io)).rejects.toThrow(/not initialized/);+ await hooksInstall(root, io);+ await hooksInstall(root, io);+ expect(io.lines).toEqual([+ "Added the cogit block to: pre-commit, prepare-commit-msg",+ "The cogit hook blocks are already current.",+ ]);+ await hooksUninstall(root, io);+ await configGit(root, "ignore", io);+ const hook = await readFile(join(root, ".git", "hooks", "prepare-commit-msg"), "utf8");+ expect(hook).toContain("hook prepare-commit-msg --dir");+ });+it("offers the uncommitted record at session start only in ask mode", async () => {const paths = projectPaths(root);await mkdir(paths.sessions, { recursive: true });diff --git a/packages/cli/test/thought.test.ts b/packages/cli/test/thought.test.tsindex bff9c5e..bb2468c 100644--- a/packages/cli/test/thought.test.ts+++ b/packages/cli/test/thought.test.ts@@ -34,6 +34,7 @@ import {attachThoughtTrailers,earliestSessionStart,parseThoughtTrailers,+ readCommitThought,readThoughtTrailers,} from "../src/thought.js";import { buildMessages } from "../src/view/lineage.js";@@ -257,7 +258,7 @@ describe("the thought behind a commit (Story 9.4)", () => {expect(await readMessage(file)).toContain(`Thought: ${thoughtOf()}`);});- it("skips an empty transcript and a project that keeps its record out of git", async () => {+ it("skips an empty transcript and a disabled capture, not the ignore policy", async () => {await writeHead();await writeFile(transcript, "");const file = await messageFile();@@ -265,11 +266,13 @@ describe("the thought behind a commit (Story 9.4)", () => {await addThoughtTrailer({ dir: root, messageFile: file, source: "message", env, now: NOW }),).toBe(false);+ // The record stays local, but the link still serves `blame` and `show` here.await writeTranscript();await ensureGitignore(root, "ignore");expect(await addThoughtTrailer({ dir: root, messageFile: file, source: "message", env, now: NOW }),- ).toBe(false);+ ).toBe(true);+ await writeFile(file, "feat: change\n");expect(await addThoughtTrailer({@@ -480,6 +483,29 @@ describe("the thought behind a commit (Story 9.4)", () => {expect(hits.map((hit) => hit.messageId)).toEqual([thought]);});+ it("names the thought behind a commit that is not recorded yet", async () => {+ await writeProject([]);+ const thought = thoughtOf();+ await writeFile(join(root, "a.txt"), "two\n");+ await git("add", "a.txt");+ await git("commit", "-q", "-m", "feat: early", "--trailer", `Thought: ${thought}`);+ const short = (await git("rev-parse", "--short", "HEAD")).trim();+ expect(await readCommitThought(root, short)).toBe(thought);+ await expect(show({ dir: root, ref: short, io, chat: false })).rejects.toThrow(+ `commit ${short} comes from thought ${thought}, which is not recorded yet`,+ );++ // No trailer, an unknown ref or no repository: nothing to name.+ await git("commit", "-q", "--allow-empty", "-m", "chore: plain");+ const plain = (await git("rev-parse", "--short", "HEAD")).trim();+ expect(await readCommitThought(root, plain)).toBeUndefined();+ await expect(show({ dir: root, ref: plain, io, chat: false })).rejects.toThrow(+ `no recorded thought for commit ${plain}`,+ );+ expect(await readCommitThought(root, "f".repeat(7))).toBeUndefined();+ expect(await readCommitThought(dir, plain)).toBeUndefined();+ });+it("resolves a commit ref and reports one it cannot place", () => {const commit = "d".repeat(40);const nodes = buildMessages([diff --git a/packages/template/src/styles.css b/packages/template/src/styles.cssindex dd64f41..00e25c0 100644--- a/packages/template/src/styles.css+++ b/packages/template/src/styles.css@@ -139,6 +139,14 @@ main.map-page {min-height: 0;margin-top: 8px;padding: 0;+ container-type: inline-size;+}++/* On a narrow map the minimap would sit on top of the message text. */+@container (max-width: 900px) {+ .react-flow__minimap {+ display: none;+ }}@media (max-width: 1100px) {