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(init): require a git repository
Eren5ffc6304bedb
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5e694f6..45b7bf8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,8 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).## [Unreleased]+### Changed+- `cogit init` needs a git repository and says to run `git init` first: the record is tied to commits (`Thought:` trailers, `blame`, `why`, `pr`) and travels through git, so outside a repository only half of cogit worked. The setup offer at session start stays quiet outside a repository.## [0.16.0] - 2026-10-27### Addeddiff --git a/packages/cli/src/commands/init.ts b/packages/cli/src/commands/init.tsindex fab4100..6e8a00d 100644--- a/packages/cli/src/commands/init.ts+++ b/packages/cli/src/commands/init.ts@@ -213,24 +213,27 @@ export async function init(dir: string, opts: InitOptions, io: Io): Promise<voidreturn;}+ // The record is tied to commits (trailers, blame, why, pr) and travels through+ // git, so a project outside a repository would get only half of cogit.+ if ((await findGitRoot(root)) === undefined)+ throw new CliError(+ `${root} is not in a git repository; cogit ties its record to your commits, so run \`git init\` first`,+ );+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) {- // 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 session records?",- [- { value: "commit", name: "Yes, commit session records (local state stays ignored)" },- { value: "ignore", name: "No, keep .cogit/ out of git (private)" },- ],- config.gitPolicy,- ));- }+ // Story 9.3: the record travels with the repository by default.+ const policy: GitPolicy =+ opts.git ??+ (await io.prompt.select<GitPolicy>(+ "Commit the session records?",+ [+ { value: "commit", name: "Yes, commit session records (local state stays ignored)" },+ { value: "ignore", name: "No, keep .cogit/ out of git (private)" },+ ],+ config.gitPolicy,+ ));await askRetention(io, opts);await askSkillPermission(io, opts);@@ -239,7 +242,7 @@ 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 });- if (policy !== undefined) await applyGitPolicy(io, root, policy, config.shareConversations);+ await applyGitPolicy(io, root, policy, config.shareConversations);await register(io, root, name);io.out(diff --git a/packages/cli/src/hooks/sessionstart.ts b/packages/cli/src/hooks/sessionstart.tsindex 4cc0320..1d2bda9 100644--- a/packages/cli/src/hooks/sessionstart.ts+++ b/packages/cli/src/hooks/sessionstart.ts@@ -1,5 +1,6 @@import { defaultAgent } from "../agents/index.js";import { branchesOf, type LogBranch } from "../commands/log.js";+import { findGitRoot } from "../git.js";import { isRecorded, readSessionMessages, upgradeSessionIds } from "../messages.js";import type { Session } from "../schema/session.js";import { uncommittedSession } from "../session-git.js";@@ -75,6 +76,8 @@ export async function onSessionStart(ctx: HookContext): Promise<HookOutput | undconst config = await loadConfig(ctx.env);// "Don't ask again in this project" lives outside the project.if (config.setupHintOff.includes(ctx.root)) return undefined;+ // `init` needs a git repository, so outside one there is nothing to offer.+ if ((await findGitRoot(ctx.root)) === undefined) return undefined;return additionalContext(ctx, setupHint(ctx));}const config = await loadConfig(ctx.env);diff --git a/packages/cli/test/blame.test.ts b/packages/cli/test/blame.test.tsindex 850255a..4266fdf 100644--- a/packages/cli/test/blame.test.ts+++ b/packages/cli/test/blame.test.ts@@ -8,7 +8,7 @@ import { init } from "../src/commands/init.js";import { createProgram } from "../src/program.js";import type { Session } from "../src/schema/session.js";import { projectPaths } from "../src/store/paths.js";-import { envFor, type FakeIo, fakeIo, T0, tempDir } from "./helpers.js";+import { envFor, type FakeIo, fakeIo, noGitProject, T0, tempDir } from "./helpers.js";const run = promisify(execFile);@@ -152,9 +152,7 @@ describe("cogit blame", () => {});it("needs a git repository", async () => {- const plain = join(dir, "plain");- await mkdir(plain);- await init(plain, { name: "plain", retention: "keep", language: "auto" }, fakeIo(envFor(dir)));+ const plain = await noGitProject(envFor(dir));await expect(blame({ dir: plain, target: "a.txt", io })).rejects.toThrow(/not inside a git repository/,);diff --git a/packages/cli/test/diff.test.ts b/packages/cli/test/diff.test.tsindex af0eaf6..2e245ac 100644--- a/packages/cli/test/diff.test.ts+++ b/packages/cli/test/diff.test.ts@@ -10,7 +10,7 @@ import {normalizeDiff,readCommitDiff,} from "../src/diff.js";-import { tempDir } from "./helpers.js";+import { noGitDir, tempDir } from "./helpers.js";const run = promisify(execFile);@@ -48,8 +48,7 @@ describe("readCommitDiff", () => {});it("answers no-git outside a repository", async () => {- const plain = join(dir, "plain");- await mkdir(plain);+ const plain = await noGitDir();expect(await readCommitDiff(plain, "abcdef0")).toEqual({ok: false,reason: "no-git",diff --git a/packages/cli/test/global-setup.ts b/packages/cli/test/global-setup.tsindex f594288..edf1399 100644--- a/packages/cli/test/global-setup.ts+++ b/packages/cli/test/global-setup.ts@@ -14,10 +14,18 @@ const root = join(dirname(fileURLToPath(import.meta.url)), "../../..");export function setup(): () => void {// Hooks leave per-session marks in the temp dir; keep tests out of the real one.const tmp = mkdtempSync(join(tmpdir(), "cogit-test-"));+ // `cogit init` needs a git repository; every temp project lives inside this one.+ execFileSync("git", ["init", "-q", tmp]);+ // A test that needs a directory outside any repository makes it here.+ const outside = mkdtempSync(join(tmpdir(), "cogit-nogit-"));+ process.env.COGIT_TEST_NO_GIT = outside;process.env.TMPDIR = tmp;const index = join(root, "packages/template/dist/index.html");if (!existsSync(index)) {execFileSync("npm", ["run", "build", "-w", "template"], { cwd: root, stdio: "ignore" });}- return () => rmSync(tmp, { recursive: true, force: true });+ return () => {+ rmSync(tmp, { recursive: true, force: true });+ rmSync(outside, { recursive: true, force: true });+ };}diff --git a/packages/cli/test/helpers.ts b/packages/cli/test/helpers.tsindex 63151e3..a6a961c 100644--- a/packages/cli/test/helpers.ts+++ b/packages/cli/test/helpers.ts@@ -1,6 +1,7 @@-import { mkdtemp } from "node:fs/promises";+import { mkdir, mkdtemp, rm } from "node:fs/promises";import { tmpdir } from "node:os";import { join } from "node:path";+import { init } from "../src/commands/init.js";import type { Io, Prompter } from "../src/io.js";export const T0 = "2026-10-21T10:00:00.000Z";@@ -9,6 +10,25 @@ export async function tempDir(): Promise<string> {return mkdtemp(join(tmpdir(), "cogit-"));}+/** A directory outside every git repository (the temp dir itself is one; see global-setup). */+export async function noGitDir(): Promise<string> {+ return mkdtemp(join(process.env.COGIT_TEST_NO_GIT ?? tmpdir(), "cogit-"));+}++/**+ * An initialized project whose repository is gone: `init` needs git, so it runs+ * in a repository that is removed afterwards. Covers the no-git answers of the+ * commands that read git.+ */+export async function noGitProject(env: NodeJS.ProcessEnv, name = "plain"): Promise<string> {+ const dir = join(await noGitDir(), name);+ await mkdir(join(dir, ".git"), { recursive: true });+ const options = { name, git: "commit", retention: "keep", language: "auto" } as const;+ await init(dir, { ...options, allowSkill: false, projectSettings: false }, fakeIo(env));+ await rm(join(dir, ".git"), { recursive: true, force: true });+ return dir;+}+export interface FakeIo extends Io {lines: string[];warnings: string[];diff --git a/packages/cli/test/hooks.test.ts b/packages/cli/test/hooks.test.tsindex 25e493e..2bdcfb5 100644--- a/packages/cli/test/hooks.test.ts+++ b/packages/cli/test/hooks.test.ts@@ -20,7 +20,7 @@ import {import { countTurn, UPDATE_REQUEST } from "../src/hooks/stop.js";import type { Session, Status } from "../src/schema/session.js";import { projectPaths } from "../src/store/paths.js";-import { envFor, fakeIo, T0, tempDir } from "./helpers.js";+import { envFor, fakeIo, noGitDir, T0, tempDir } from "./helpers.js";describe("countTurn", () => {it("asks every N turns and starts counting again after each request", () => {@@ -190,6 +190,12 @@ describe("runHook", () => {expect(existsSync(join(root, ".cogit"))).toBe(false);});+ it("offers no setup outside a git repository, where init would refuse", async () => {+ const outside = await noGitDir();+ const input = JSON.stringify({ session_id: "s1", cwd: outside, source: "startup" });+ expect(await runHook("sessionstart", input, env, T0, (l) => debug.push(l))).toBeUndefined();+ });+it("replaces the setup offer with the lineage handoff after init", async () => {await initialized(2);const context = async (source: string) => {diff --git a/packages/cli/test/init.test.ts b/packages/cli/test/init.test.tsindex 964bfcd..89c374b 100644--- a/packages/cli/test/init.test.ts+++ b/packages/cli/test/init.test.ts@@ -1,6 +1,7 @@import { execFile } from "node:child_process";import { existsSync } from "node:fs";-import { mkdir, readdir, readFile, rm, writeFile } from "node:fs/promises";+import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";import { basename, join } from "node:path";import { promisify } from "node:util";import { beforeEach, describe, expect, it } from "vitest";@@ -40,6 +41,13 @@ describe("init", () => {expect(await readText(join(root, ".claude", "settings.json"))).toBe("{ not json");});+ it("refuses a directory outside any git repository, before asking anything", async () => {+ const outside = await mkdtemp(join(process.env.COGIT_TEST_NO_GIT ?? tmpdir(), "p-"));+ const io = fakeIo(env, [], true);+ await expect(init(outside, {}, io)).rejects.toThrow(/not in a git repository.*git init/);+ expect(existsSync(join(outside, ".cogit"))).toBe(false);+ });+it("recognizes a pre-rename .codelineage project and renames it", async () => {await mkdir(join(root, ".codelineage"), { recursive: true });await writeFile(@@ -65,13 +73,13 @@ describe("init", () => {data: { projects: [{ path: root, name: "proj" }] },});expect((await loadConfig(env)).language).toBe("auto");- // not a git repo: name, retention, skill permission, project settings and language- expect(io.asked).toHaveLength(5);+ // name, git policy, retention, skill permission, project settings and language+ expect(io.asked).toHaveLength(6);expect(await readProjectSetup(root)).toBe(true);expect(await readSkillAllowed(env)).toBe(true);expect(io.lines.at(-2)).toMatch(/^Initialized proj/);- // Outside a git repository there is nothing to ignore and no hook to install.- expect(existsSync(join(root, ".cogit", ".gitignore"))).toBe(false);+ // The default commit policy writes the project's own ignore rules.+ expect(await readText(join(root, ".cogit", ".gitignore"))).toBe(cogitGitignore(false));expect(io.lines).toContain("Conversations are stored in .cogit/conversations/ (kept out of git; turn on shareConversations to share them).",);@@ -119,7 +127,7 @@ describe("init", () => {it("raises transcript retention when asked, keeping other settings", async () => {await mkdir(join(dir, "claude"));await writeFile(settingsFile(), JSON.stringify({ model: "x" }));- const io = fakeIo(env, ["proj", "365"]);+ const io = fakeIo(env, ["proj", "commit", "365"]);await init(root, {}, io);expect(JSON.parse(await readText(settingsFile()))).toEqual({model: "x",@@ -143,20 +151,31 @@ describe("init", () => {const io = fakeIo(env);await init(root, {}, io);expect(io.lines).toContain("Claude Code keeps transcripts for 365 days.");- expect(io.asked).toHaveLength(4);+ expect(io.asked).toHaveLength(5);});it("applies a retention option without asking, and skips an unchanged one", async () => {await init(root,- { name: "p", retention: 90, allowSkill: false, projectSettings: false, language: "auto" },+ {+ name: "p",+ git: "commit",+ retention: 90,+ allowSkill: false,+ projectSettings: false,+ language: "auto",+ },fakeIo(env, [], true),);expect(await readRetention(env)).toBe(90);const again = join(dir, "other");await mkdir(again);const io = fakeIo(env, [], true);- await init(again, { name: "o", retention: 90, allowSkill: false, projectSettings: false }, io);+ await init(+ again,+ { name: "o", git: "commit", retention: 90, allowSkill: false, projectSettings: false },+ io,+ );expect(io.lines.some((l) => l.includes("cleanupPeriodDays"))).toBe(false);});@@ -171,7 +190,7 @@ describe("init", () => {});it("asks which fixed language on the first run only", async () => {- await init(root, {}, fakeIo(env, ["proj", "keep", "yes", "yes", "fixed", "Turkish"]));+ await init(root, {}, fakeIo(env, ["proj", "commit", "keep", "yes", "yes", "fixed", "Turkish"]));expect((await loadConfig(env)).language).toBe("Turkish");const second = join(dir, "second");await mkdir(second);@@ -186,7 +205,7 @@ describe("init", () => {settingsFile(),JSON.stringify({ permissions: { allow: ["Bash(ls)"], deny: [] } }),);- const io = fakeIo(env, ["proj", "keep", "yes"]);+ const io = fakeIo(env, ["proj", "commit", "keep", "yes"]);await init(root, {}, io);expect(JSON.parse(await readText(settingsFile())).permissions).toEqual({allow: ["Bash(ls)", SKILL_RULE],@@ -201,7 +220,7 @@ describe("init", () => {});it("leaves permissions alone when declined", async () => {- const io = fakeIo(env, ["proj", "keep", "no"]);+ const io = fakeIo(env, ["proj", "commit", "keep", "no"]);await init(root, {}, io);expect(await readSkillAllowed(env)).toBe(false);expect(io.lines).toContain(diff --git a/packages/cli/test/pr.test.ts b/packages/cli/test/pr.test.tsindex f430dfa..e73d00d 100644--- a/packages/cli/test/pr.test.ts+++ b/packages/cli/test/pr.test.ts@@ -18,7 +18,7 @@ import { createProgram } from "../src/program.js";import type { Session } from "../src/schema/session.js";import { appendConversationTurns } from "../src/store/conversations.js";import { projectPaths } from "../src/store/paths.js";-import { envFor, type FakeIo, fakeIo, T0, tempDir } from "./helpers.js";+import { envFor, type FakeIo, fakeIo, noGitProject, T0, tempDir } from "./helpers.js";const run = promisify(execFile);@@ -264,9 +264,7 @@ describe("cogit pr (Story 10.1)", () => {);await expect(pr({ dir: empty, io })).rejects.toThrow(/HEAD has no commits yet/);- const plain = join(dir, "plain");- await mkdir(plain);- await init(plain, { name: "plain", retention: "keep", language: "auto" }, fakeIo(env));+ const plain = await noGitProject(env);await expect(pr({ dir: plain, io })).rejects.toThrow(/not in a git repository/);});diff --git a/packages/cli/test/program-commands.test.ts b/packages/cli/test/program-commands.test.tsindex 88dc325..7768bef 100644--- a/packages/cli/test/program-commands.test.ts+++ b/packages/cli/test/program-commands.test.ts@@ -9,7 +9,7 @@ import { readSkillAllowed } from "../src/agents/claude/settings.js";import { createProgram } from "../src/program.js";import { globalPaths } from "../src/store/paths.js";import { loadConfig, loadProject, loadSession } from "../src/store/stores.js";-import { envFor, type FakeIo, fakeIo, T0, tempDir } from "./helpers.js";+import { envFor, type FakeIo, fakeIo, noGitDir, noGitProject, T0, tempDir } from "./helpers.js";let dir: string;let root: string;@@ -92,10 +92,8 @@ describe("commands through the CLI", () => {const run = promisify(execFile);const git = async (...args: string[]): Promise<string> =>(await run("git", ["-C", root, ...args])).stdout;- await cli("init", root, "--yes", "--retention", "keep");- expect(await cli("why", "a.txt", "-C", root)).toMatch(/not inside a git repository/);-await git("init", "-q");+ await cli("init", root, "--yes", "--retention", "keep");await git("config", "user.email", "[email protected]");await git("config", "user.name", "Tester");await writeFile(join(root, "a.txt"), "one\n");@@ -304,9 +302,11 @@ describe("commands through the CLI", () => {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("refuses init and config git outside a git repository", async () => {+ const outside = await noGitDir();+ expect(await cli("init", outside, "--yes")).toMatch(/not in a git repository.*git init/);+ const plain = await noGitProject(envFor(dir));+ expect(await cli("config", "git", "commit", plain)).toMatch(/not in a git repository/);});it("prints user errors as one line", async () => {diff --git a/packages/cli/test/server.test.ts b/packages/cli/test/server.test.tsindex f59f934..4e0a41c 100644--- a/packages/cli/test/server.test.ts+++ b/packages/cli/test/server.test.ts@@ -33,7 +33,7 @@ import { globalPaths, projectPaths } from "../src/store/paths.js";import { readReadState } from "../src/store/read-state.js";import { loadConfig, updateConfig } from "../src/store/stores.js";import { DATA_ELEMENT_ID, LIVE_META_NAME, TOKEN_META_NAME } from "../src/view/model.js";-import { envFor, fakeIo, tempDir } from "./helpers.js";+import { envFor, fakeIo, noGitProject, tempDir } from "./helpers.js";const TEMPLATE = `<!doctype html><html><head><title>cogit</title></head><body><div id="root"></div><script id="${DATA_ELEMENT_ID}" type="application/json"></script></body></html>`;@@ -1001,9 +1001,7 @@ describe("commit diff endpoint (Story 10.5)", () => {it("answers not-a-git-repository for a registered project without git", async () => {const server = await start();const token = await panelToken(server);- const plain = join(dir, "plain");- await mkdir(plain);- await init(plain, { name: "plain", retention: "keep", language: "auto" }, fakeIo(env));+ const plain = await noGitProject(env);const reply = await diffRequest(server, token, { dir: plain, commit: "abcdef0" });expect(reply.status).toBe(404);expect(reply.body).toContain("not a git repository");diff --git a/packages/cli/test/session-git.test.ts b/packages/cli/test/session-git.test.tsindex bcfcb3b..93a14d4 100644--- a/packages/cli/test/session-git.test.ts+++ b/packages/cli/test/session-git.test.ts@@ -32,7 +32,7 @@ import {} 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";+import { envFor, fakeIo, noGitDir, T0, tempDir } from "./helpers.js";const run = promisify(execFile);@@ -389,7 +389,7 @@ describe("ignore files and git hooks", () => {"#!/bin/sh\necho mine\n",);expect(await refreshGitHooks(root)).toEqual([]);- expect(await refreshGitHooks(join(dir, "not-a-repo"))).toEqual([]);+ expect(await refreshGitHooks(await noGitDir())).toEqual([]);});it("installs the hooks on request and with the ignore policy", async () => {diff --git a/packages/cli/test/thought.test.ts b/packages/cli/test/thought.test.tsindex fa67aad..dc66bdb 100644--- a/packages/cli/test/thought.test.ts+++ b/packages/cli/test/thought.test.ts@@ -39,7 +39,7 @@ import {} from "../src/thought.js";import { buildMessages } from "../src/view/lineage.js";import { DATA_ELEMENT_ID } from "../src/view/model.js";-import { envFor, type FakeIo, fakeIo, T0, tempDir } from "./helpers.js";+import { envFor, type FakeIo, fakeIo, noGitDir, T0, tempDir } from "./helpers.js";const run = promisify(execFile);@@ -475,7 +475,7 @@ describe("the thought behind a commit (Story 9.4)", () => {expect(await readFile(join(root, ".husky", "pre-commit"), "utf8")).toBe(userHook);// No repository and no block: nothing to do.- expect(await uninstallGitHooks(dir)).toEqual([]);+ expect(await uninstallGitHooks(await noGitDir())).toEqual([]);expect(await uninstallGitHooks(root)).toEqual([]);});diff --git a/packages/cli/test/why.test.ts b/packages/cli/test/why.test.tsindex 6cbf23f..b01d799 100644--- a/packages/cli/test/why.test.ts+++ b/packages/cli/test/why.test.ts@@ -18,7 +18,7 @@ import {import { runHook } from "../src/hooks/run.js";import type { Session } from "../src/schema/session.js";import { projectPaths } from "../src/store/paths.js";-import { envFor, fakeIo, T0, tempDir } from "./helpers.js";+import { envFor, fakeIo, noGitProject, T0, tempDir } from "./helpers.js";const run = promisify(execFile);@@ -186,9 +186,7 @@ describe("cogit why", () => {/not initialized/,);- const plain = join(dir, "plain");- await mkdir(plain);- await init(plain, { name: "plain", retention: "keep", language: "auto" }, fakeIo(env));+ const plain = await noGitProject(env);await expect(why({ dir: plain, file: "a.txt", io: fakeIo(env) })).rejects.toThrow(/not inside a git repository/,);