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
import { mkdir } from "node:fs/promises";
import { basename, resolve } from "node:path";
import { styleText } from "node:util";
import { defaultAgent } from "../agents/index.js";
import { sessionIdentity } from "../author.js";
import {
cogitIgnored,
ensureCogitGitignore,
ensureGitignore,
findGitRoot,
type GitPolicy,
refreshCogitGitignore,
} from "../git.js";
import { installGitHooks } from "../git-hooks.js";
import { CliError, type Io } from "../io.js";
import { addRecordRefspec } from "../record-sync.js";
import { readJson } from "../store/fs.js";
import { migrateProject } from "../store/migrate.js";
import { globalPaths, projectPaths } from "../store/paths.js";
import {
loadConfig,
loadProject,
updateConfig,
updateProject,
updateRegistry,
} from "../store/stores.js";
const agent = defaultAgent();
export interface InitOptions {
name?: string;
git?: GitPolicy;
language?: string;
/** Days, or "keep" to leave Claude Code's setting alone. */
retention?: number | "keep";
/** Allow the lineage skill in Claude Code's user settings; undefined asks. */
allowSkill?: boolean;
/** Enable the plugin and the guard in the project's shared settings; undefined asks. */
projectSettings?: boolean;
}
/** Below this, init offers to raise Claude Code's transcript retention. */
const RETENTION_FLOOR = 90;
async function bestEffort(io: Io, what: string, fn: () => Promise<unknown>): Promise<boolean> {
try {
await fn();
return true;
} catch (err) {
io.warn(`${what}: ${(err as Error).message}`);
return false;
}
}
/**
* Whether the team sees the record. This one decides what leaves the machine — the
* record holds titles, summaries, decisions and open items — so it is asked with a
* note, in a colour that stands apart from the routine questions. No answer keeps
* the record here: nothing is ever published by default.
*/
async function askGitPolicy(io: Io): Promise<GitPolicy> {
const paint = (text: string): string =>
process.stdout.isTTY === true ? styleText("yellow", text) : text;
io.out(
paint("⚠ Session records carry your messages' titles, summaries, decisions and open items."),
);
io.out(paint(" Sharing sends them with every `git push` to anyone who can read this"));
io.out(paint(" repository. If it is public, that means everyone."));
return io.prompt.select<GitPolicy>(
"Share the session records with your team?",
[
{ value: "ignore", name: "No — keep them on this machine" },
{ value: "share", name: "Yes — send them with `git push`" },
],
"ignore",
);
}
async function askRetention(io: Io, opts: InitOptions): Promise<void> {
const current = await agent.readRetention(io.env);
if (current === undefined) {
io.warn("could not read Claude Code settings; transcript retention left unchanged");
return;
}
let choice = opts.retention;
if (choice === undefined) {
if (current >= RETENTION_FLOOR) {
io.out(`Claude Code keeps transcripts for ${current} days.`);
return;
}
const picked = await io.prompt.select(
`Claude Code deletes transcripts after ${current} days${current === agent.defaultRetention ? " (its default)" : ""}. ` +
"Older sessions can then no longer be resumed or backfilled. Keep them longer?",
[
{ value: "keep", name: `Keep ${current} days` },
{ value: "90", name: "90 days" },
{ value: "365", name: "1 year" },
{ value: "3650", name: "10 years" },
],
"keep",
);
choice = picked === "keep" ? "keep" : Number(picked);
}
if (choice === "keep" || choice === current) return;
const { file, backup } = await agent.setRetention(choice, io.env, io.now());
io.out(`Set cleanupPeriodDays to ${choice} in ${file}${backup ? ` (backup: ${backup})` : ""}.`);
}
async function askSkillPermission(io: Io, opts: InitOptions): Promise<void> {
const allowed = await agent.readSkillAllowed(io.env);
if (allowed === undefined) {
io.warn(
`could not read Claude Code permissions; add ${agent.skillRule} to permissions.allow yourself`,
);
return;
}
if (allowed) return;
// Recording is what the plugin is for: allow the skill unless asked not to.
if (opts.allowSkill === false) {
io.out(`Claude Code will ask before each cogit update; allow ${agent.skillRule} to stop that.`);
return;
}
const { file, backup } = await agent.allowSkill(io.env, io.now());
io.out(`Allowed ${agent.skillRule} in ${file}${backup ? ` (backup: ${backup})` : ""}.`);
}
async function askProjectSettings(io: Io, root: string, opts: InitOptions): Promise<void> {
const done = await agent.readProjectSetup(root);
if (done === undefined) {
io.warn("could not read the project's Claude Code settings; leaving them unchanged");
return;
}
if (done) return;
// On by default: the project's settings are what tells a teammate's session
// to load the plugin at all.
if (opts.projectSettings === false) return;
await bestEffort(io, "could not update the project's Claude Code settings", async () => {
const { file } = await agent.writeProjectSetup(root);
io.out(`Enabled the plugin and the missing-plugin guard in ${file}.`);
});
}
async function askLanguage(io: Io, opts: InitOptions): Promise<void> {
const firstRun = !(await readJson(globalPaths(io.env).config)).found;
if (!firstRun && opts.language === undefined) return;
// The conversation's own language is the default; `--language` overrides it.
await bestEffort(io, "could not save global config", () =>
updateConfig((c) => ({ ...c, language: opts.language ?? "auto" }), io.env),
);
}
export async function register(io: Io, root: string, name: string): Promise<void> {
await bestEffort(io, "could not register the project in the global panel", () =>
updateRegistry(
(r) =>
r.projects.some((p) => p.path === root)
? r
: { ...r, projects: [...r.projects, { path: root, name, addedAt: io.now() }] },
io.env,
),
);
}
/**
* Applies a policy to the two ignore files and installs the git hooks that link
* commits to messages and send the record (Stories 9.3, 9.4). 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): 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),
);
// Every policy: the trailer links commits locally; sending follows the policy.
await bestEffort(io, "could not install the git hooks", () => installGitHooks(root));
if (policy === "share")
await bestEffort(io, "could not set up fetching the records", () =>
addRecordRefspec(root, io.env),
);
}
/**
* Brings an already initialized project up to date: every repository gets the
* hooks, a shared one also the current `.cogit/.gitignore`, without changing the
* policy the project chose at setup. A teammate's first `init` in a clone lands here.
*/
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 () => {
await installGitHooks(root);
if (await cogitIgnored(root)) return;
await refreshCogitGitignore(root);
await addRecordRefspec(root, io.env);
});
}
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
// pre-rename project is recognized instead of initialized a second time.
await migrateProject(root);
const existing = await loadProject(root);
if (existing.found) {
if (!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);
// `cogit doctor` suggests `init --retention 90` for a set-up project too.
if (opts.retention !== undefined) await askRetention(io, opts);
if (opts.projectSettings !== undefined) await askProjectSettings(io, root, opts);
await bestEffort(io, "could not refresh the project's Claude Code settings", async () => {
const file = await agent.refreshProjectSetup(root);
if (file) io.out(`Updated the cogit guard and marketplace in ${file}.`);
});
await refreshGitIntegration(io, root);
io.out(`Already initialized: ${existing.data.name} (${root})`);
return;
}
// 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`,
);
// A session is credited to the git identity (Story 9.3); without an email,
// two teammates with one name would read as one person.
if ((await sessionIdentity(root, io.env)).authorEmail === undefined)
io.warn(
"git has no user.email here; cogit tells people's sessions apart by it, so set one: " +
"git config --global user.email [email protected]",
);
// The directory names the project; --name overrides it.
const name = opts.name ?? basename(root);
const config = await loadConfig(io.env);
const policy: GitPolicy = opts.git ?? (await askGitPolicy(io));
await askRetention(io, opts);
await askSkillPermission(io, opts);
await askProjectSettings(io, root, opts);
await askLanguage(io, opts);
await updateProject(root, (cur) => cur ?? { schema: 1, name });
await mkdir(projectPaths(root).sessions, { recursive: true });
await applyGitPolicy(io, root, policy);
await register(io, root, name);
if (policy === "share") {
io.out("Session records will be sent with `git push` to whoever can read this repository.");
io.out(
"Commit .cogit/.gitignore and .cogit/project.json so your team's clones share them too.",
);
}
io.out(
policy === "share" && config.shareConversations
? "Conversations are stored in .cogit/conversations/ (sent too: shareConversations is on)."
: "Conversations are stored in .cogit/conversations/ and stay on this machine.",
);
io.out(`Initialized ${name} in ${projectPaths(root).base}`);
const installed = await agent.readPluginInstalled(io.env).catch(() => undefined);
io.out(
installed
? "Next: work with Claude Code here, then run `cogit open` to see the map."
: `Next: install the Claude Code plugin (\`${agent.installCommand}\`), then run \`cogit open\` after a session.`,
);
}