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(doctor): add cogit doctor for an empty map
Eren1e9aa2a42a91
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex da9f227..e04da5f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -6,6 +6,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]### Added+- `cogit doctor` explains why the map may stay empty: read-only checks for Node, the Claude Code plugin and its version, git identity, the project and its hooks, the skill permission, transcripts and their retention, recorded sessions and the unrecorded tail, the map server and the close-pass log. Each line says `ok`, `warn` or `fail` with the command that fixes it; `--json` prints the report, and a failed check exits 1.- `cogit init` warns when git has no `user.email`, since sessions are now told apart by it.- The map tells your sessions from your teammates': a teammate's session always shows their name and yours never needs to, the side panel marks yours "(you)", and a new Everyone / You / teammate choice in the toolbar fades the other people's sessions.diff --git a/README.md b/README.mdindex a006c6c..8094618 100644--- a/README.md+++ b/README.md@@ -56,6 +56,8 @@ Then, in Claude Code:To get plugin updates on their own, turn on auto-update once: `/plugin` → Marketplaces →cogit → Enable auto-update. Claude Code leaves it off for marketplaces outside its own.+If the map stays empty, run `cogit doctor`.+## Quick start```bashdiff --git a/docs/guide/troubleshooting.md b/docs/guide/troubleshooting.mdindex 7914d5a..80a4c60 100644--- a/docs/guide/troubleshooting.md+++ b/docs/guide/troubleshooting.md@@ -1,5 +1,20 @@# Troubleshooting+## Run `cogit doctor` first++When the map stays empty, `cogit doctor` checks everything recording depends on: Node, the+Claude Code plugin and its version, your git identity, the project and its git hooks, the+skill permission, the transcripts and how long Claude Code keeps them, the recorded sessions+and the newest unrecorded tail, the local map server, and the log of the last close pass.++It changes nothing. Every check prints one line — `ok`, `warn` or `fail`, the reason, and the+command that fixes it — and it exits 1 when a check fails, so it can also guard a script.++```bash+cogit doctor+cogit doctor --json+```+## `cogit init` says the directory is not in a git repositorycogit ties its record to commits, so it needs git. Run `git init` (or work in a clone), thendiff --git a/packages/cli/src/agents/claude/index.ts b/packages/cli/src/agents/claude/index.tsindex e610540..b6fc765 100644--- a/packages/cli/src/agents/claude/index.ts+++ b/packages/cli/src/agents/claude/index.ts@@ -5,7 +5,9 @@ import {CLAUDE_DEFAULT_RETENTION,INSTALL_COMMAND,markLive,+ readPluginEnabled,readPluginInstalled,+ readPluginVersion,readProjectSetup,readRetention,readSkillAllowed,@@ -63,6 +65,8 @@ export const claude: AgentAdapter = {readRetention,readPluginInstalled,+ readPluginVersion,+ readPluginEnabled,readSkillAllowed,setRetention,allowSkill,diff --git a/packages/cli/src/agents/claude/settings.ts b/packages/cli/src/agents/claude/settings.tsindex f9e0b07..ee0fe55 100644--- a/packages/cli/src/agents/claude/settings.ts+++ b/packages/cli/src/agents/claude/settings.ts@@ -112,18 +112,56 @@ export const MARKETPLACE = "cogit";export const MARKETPLACE_REPO = "erensrtky/cogit";export const INSTALL_COMMAND = `claude plugin install cogit --marketplace ${MARKETPLACE_REPO}`;-/**- * Whether Claude Code lists the plugin as installed, in any scope; undefined when its- * plugin list cannot be read (missing or another shape), so the caller says nothing either way.- */-export async function readPluginInstalled(env: NodeJS.ProcessEnv): Promise<boolean | undefined> {+/** The installed-plugin entries for cogit, one per scope; undefined when the list is unreadable. */+async function installedEntries(env: NodeJS.ProcessEnv): Promise<unknown[] | undefined> {const base = env.CLAUDE_CONFIG_DIR ?? join(homedir(), ".claude");const read = await readJson(join(base, "plugins", "installed_plugins.json"));if (!read.found || "error" in read) return undefined;const plugins = isObject(read.value) ? read.value.plugins : undefined;if (!isObject(plugins)) return undefined;+ // A readable list without our key (or with a broken entry) means "not installed".const entries = plugins[PLUGIN_ID];- return Array.isArray(entries) && entries.length > 0;+ return Array.isArray(entries) ? entries : [];+}++/**+ * Whether Claude Code lists the plugin as installed, in any scope; undefined when its+ * plugin list cannot be read (missing or another shape), so the caller says nothing either way.+ */+export async function readPluginInstalled(env: NodeJS.ProcessEnv): Promise<boolean | undefined> {+ const entries = await installedEntries(env);+ return entries === undefined ? undefined : entries.length > 0;+}++/** The installed plugin's version; undefined when it is not installed or names none. */+export async function readPluginVersion(env: NodeJS.ProcessEnv): Promise<string | undefined> {+ const entries = await installedEntries(env);+ for (const entry of entries ?? []) {+ const version = isObject(entry) ? entry.version : undefined;+ if (typeof version === "string" && version !== "") return version;+ }+ return undefined;+}++function pluginEnabledIn(settings: Record<string, unknown>): boolean {+ const plugins = isObject(settings.enabledPlugins) ? settings.enabledPlugins : undefined;+ return plugins?.[PLUGIN_ID] === true;+}++/**+ * Whether Claude Code has the plugin enabled, in the user's own settings or in+ * the project's shared ones; undefined when the user's settings cannot be read.+ */+export async function readPluginEnabled(+ env: NodeJS.ProcessEnv,+ root?: string,+): Promise<boolean | undefined> {+ const settings = await readSettings(claudeSettingsPath(env));+ if (!settings) return undefined;+ if (pluginEnabledIn(settings)) return true;+ if (root === undefined) return false;+ const project = await readSettings(projectSettingsPath(root));+ return project !== undefined && pluginEnabledIn(project);}/** Where a session's SessionStart leaves its mark; the guard reads the same path. */diff --git a/packages/cli/src/agents/types.ts b/packages/cli/src/agents/types.tsindex a81afb6..a3f22c3 100644--- a/packages/cli/src/agents/types.ts+++ b/packages/cli/src/agents/types.ts@@ -169,6 +169,13 @@ export interface AgentAdapter {readRetention(env: NodeJS.ProcessEnv): Promise<number | undefined>;/** Whether the agent lists the plugin as installed; undefined when unreadable. */readPluginInstalled(env: NodeJS.ProcessEnv): Promise<boolean | undefined>;+ /** The installed plugin's version; undefined when it is not installed or names none. */+ readPluginVersion(env: NodeJS.ProcessEnv): Promise<string | undefined>;+ /**+ * Whether the plugin is enabled, in the user's settings or (with `root`)+ * the project's; undefined when the user's settings cannot be read.+ */+ readPluginEnabled(env: NodeJS.ProcessEnv, root?: string): Promise<boolean | undefined>;/** Whether the record skill is already allowed; undefined when unreadable. */readSkillAllowed(env: NodeJS.ProcessEnv): Promise<boolean | undefined>;/** Sets the transcript retention in the agent's settings. */diff --git a/packages/cli/src/commands/doctor.ts b/packages/cli/src/commands/doctor.tsnew file mode 100644index 0000000..c6957b3--- /dev/null+++ b/packages/cli/src/commands/doctor.ts@@ -0,0 +1,498 @@+import { readFile, stat } from "node:fs/promises";+import { basename, dirname, join } from "node:path";+import pkg from "../../package.json" with { type: "json" };+import type { AgentAdapter } from "../agents/index.js";+import { defaultAgent } from "../agents/index.js";+import { compareVersions, versionNotice } from "../cli-version.js";+import { cogitIgnored, findGitRoot, gitHooksDir, gitUserEmail, gitUserName } from "../git.js";+import { BLOCK_START, hookBlock } from "../git-hooks.js";+import type { Io } from "../io.js";+import { hashTurns, isRecorded, upgradeSessionIds } from "../messages.js";+import type { Session } from "../schema/session.js";+import { checkHealth } from "../server.js";+import { applyEvents, readEvents } from "../store/events.js";+import { projectPaths } from "../store/paths.js";+import { resolveProjectRoot } from "../store/root.js";+import { loadAllSessions, loadConfig, loadProject, loadSession } from "../store/stores.js";++/**+ * `cogit doctor` (Story 13.1): the one command to hand a user whose map stays+ * empty. Every check is read-only, runs in a fixed order and never stops the+ * others; one line says `ok`, `warn` or `fail`, the reason, and the fix.+ */++export type CheckStatus = "ok" | "warn" | "fail";++export interface DoctorCheck {+ /** Stable key for `--json`. */+ id: string;+ status: CheckStatus;+ /** Short reason, one line. */+ message: string;+ /** The exact command (or setting) that fixes a warn or fail. */+ fix?: string;+}++export interface DoctorReport {+ /** False when any check failed: the CLI exits 1. */+ ok: boolean;+ checks: DoctorCheck[];+}++export interface DoctorOptions {+ dir: string;+ io: Io;+ /** Print the report as JSON instead of lines. */+ json?: boolean;+}++/** The lowest Node this project supports, from `engines`. */+const MIN_NODE = "22.13.0";+/** Below this, old transcripts are gone before a record can be backfilled. */+const RETENTION_FLOOR = 90;++/** A promise computed once, shared by the checks that need the same read. */+function once<T>(fn: () => Promise<T>): () => Promise<T> {+ let cached: Promise<T> | undefined;+ return () => (cached ??= fn());+}++interface DoctorContext {+ root: string;+ env: NodeJS.ProcessEnv;+ agent: AgentAdapter;+ gitRoot: () => Promise<string | undefined>;+ project: () => Promise<Awaited<ReturnType<typeof loadProject>>>;+ sessions: () => Promise<Session[]>;+ transcripts: () => Promise<Map<string, string>>;+ config: () => Promise<Awaited<ReturnType<typeof loadConfig>>>;+}++interface CheckSpec {+ id: string;+ run: (ctx: DoctorContext) => Promise<DoctorCheck>;+}++/** Claude Code's folder for a working directory: every non-alphanumeric becomes `-`. */+export function transcriptDirName(dir: string): string {+ return dir.replace(/[^a-zA-Z0-9]/g, "-");+}++/** This project's transcripts, by session id (the main checkout and a linked worktree). */+export async function projectTranscripts(+ root: string,+ worktree: string | undefined,+ agent: AgentAdapter,+ env: NodeJS.ProcessEnv,+): Promise<Map<string, string>> {+ const names = new Set([transcriptDirName(root)]);+ if (worktree !== undefined) names.add(transcriptDirName(worktree));+ const all = await agent.collectTranscripts(env);+ return new Map([...all].filter(([, file]) => names.has(basename(dirname(file)))));+}++/** The transcript with the latest modification time, if there is one. */+async function newestTranscript(+ transcripts: ReadonlyMap<string, string>,+): Promise<{ id: string; file: string } | undefined> {+ let newest: { id: string; file: string; mtime: number } | undefined;+ for (const [id, file] of transcripts) {+ const info = await stat(file).catch(() => undefined);+ if (info === undefined) continue;+ if (newest === undefined || info.mtimeMs > newest.mtime)+ newest = { id, file, mtime: info.mtimeMs };+ }+ return newest === undefined ? undefined : { id: newest.id, file: newest.file };+}++/** The user messages in this transcript that the record has no node for. */+async function unrecordedTail(+ root: string,+ sessionId: string,+ file: string,+ agent: AgentAdapter,+): Promise<number> {+ const turns = hashTurns(sessionId, await agent.readConversation(file));+ const loaded = await loadSession(root, sessionId);+ let recorded = new Set<string>();+ if (loaded.found && loaded.ok) {+ const upgraded = upgradeSessionIds(loaded.data, turns);+ const events = await readEvents(root, sessionId);+ recorded = new Set(applyEvents(upgraded.nodes, events).map((node) => node.id));+ }+ return turns.filter((turn) => !isRecorded(recorded, turn)).length;+}++/** The one line a check prints; the fix rides on the same line. */+export function formatCheck(check: DoctorCheck): string {+ const head = `${check.status.padEnd(5)}${check.message}`;+ return check.fix === undefined ? head : `${head} · fix: ${check.fix}`;+}++/** A detached-log section header and the lines under it. */+interface LogSection {+ header: string;+ body: string[];+}++/**+ * The last error from a close pass in the detached log, if any. The pass runs+ * as `backfill <id> --tail --close`; only its own last section matters, since a+ * build after it says nothing about the recording.+ */+export function closePassError(log: string): { sessionId?: string; line: string } | undefined {+ const sections: LogSection[] = [];+ for (const line of log.split("\n")) {+ if (line.startsWith("--- ")) sections.push({ header: line.slice(4), body: [] });+ else sections.at(-1)?.body.push(line);+ }+ const passes = sections.filter((section) => /\bbackfill\b/.test(section.header));+ const last = passes.at(-1);+ if (last === undefined) return undefined;+ const line = last.body.find((text) => /^\s*error:/i.test(text));+ if (line === undefined) return undefined;+ const id = last.header.split(/\s+/)[2];+ return { ...(id === undefined ? {} : { sessionId: id }), line: line.trim() };+}++/** Reads the bounded tail of the detached log; a missing log is an empty one. */+async function readDetachedLog(root: string): Promise<string> {+ const text = await readFile(projectPaths(root).detachedLog, "utf8").catch(() => "");+ return text.slice(-64 * 1024);+}++/** The Node check, pure so its too-old branch is testable on any machine. */+export function nodeCheck(node: string = process.versions.node): DoctorCheck {+ if (compareVersions(node, MIN_NODE) < 0)+ return {+ id: "node",+ status: "fail",+ message: `Node ${node} is older than ${MIN_NODE}`,+ fix: `install Node ${MIN_NODE} or newer (https://nodejs.org)`,+ };+ return { id: "node", status: "ok", message: `Node ${node}, cogit ${pkg.version}` };+}++const CHECK_SPECS: CheckSpec[] = [+ { id: "node", run: async () => nodeCheck() },++ {+ id: "plugin",+ run: async (ctx) => {+ const installed = await ctx.agent.readPluginInstalled(ctx.env);+ if (installed !== true)+ return {+ id: "plugin",+ status: "fail",+ message: "the Claude Code plugin is not installed, so nothing is recorded",+ fix: ctx.agent.installCommand,+ };+ const enabled = await ctx.agent.readPluginEnabled(ctx.env, ctx.root);+ if (enabled === undefined)+ return {+ id: "plugin",+ status: "warn",+ message: "could not read Claude Code's settings to see whether the plugin is enabled",+ fix: "check ~/.claude/settings.json is a valid JSON object",+ };+ if (!enabled)+ return {+ id: "plugin",+ status: "warn",+ message: "the plugin is installed but not enabled, so sessions here record nothing",+ fix: "cogit init --project-settings",+ };+ const version = await ctx.agent.readPluginVersion(ctx.env);+ if (version === undefined)+ return {+ id: "plugin",+ status: "warn",+ message: "the plugin is installed and enabled, but its version is unknown",+ fix: "claude plugin update cogit@cogit",+ };+ const notice = versionNotice(version, pkg.version);+ if (notice !== undefined) return { id: "plugin", status: "warn", message: notice };+ return {+ id: "plugin",+ status: "ok",+ message: `the plugin is installed, enabled and at the CLI's version (${version})`,+ };+ },+ },++ {+ id: "git",+ run: async (ctx) => {+ const gitRoot = await ctx.gitRoot();+ if (gitRoot === undefined)+ return {+ id: "git",+ status: "fail",+ message: `${ctx.root} is not inside a git repository`,+ fix: "git init",+ };+ const name = await gitUserName(ctx.root, ctx.env);+ const email = await gitUserEmail(ctx.root, ctx.env);+ if (name !== undefined && email !== undefined)+ return {+ id: "git",+ status: "ok",+ message: `git identity: ${name} <${email}>`,+ };+ const missing = [+ name === undefined ? "user.name" : "",+ email === undefined ? "user.email" : "",+ ]+ .filter((key) => key !== "")+ .join(" and ");+ const fix =+ (name === undefined ? 'git config --global user.name "Your Name"' : "") ++ (name === undefined && email === undefined ? " && " : "") ++ (email === undefined ? "git config --global user.email [email protected]" : "");+ return {+ id: "git",+ status: "warn",+ message: `git has no ${missing}; sessions are credited to the OS user and two people with one name read as one`,+ fix,+ };+ },+ },++ {+ id: "project",+ run: async (ctx) => {+ const project = await ctx.project();+ if (!project.found)+ return {+ id: "project",+ status: "fail",+ message: `${projectPaths(ctx.root).project} is missing`,+ fix: "cogit init",+ };+ if (!project.ok)+ return {+ id: "project",+ status: "fail",+ message: `${projectPaths(ctx.root).project}: ${project.error}`,+ fix: "fix or remove the file, then run `cogit init`",+ };+ const hooks = await hookProblems(ctx);+ if (hooks.length > 0)+ return {+ id: "project",+ status: "warn",+ message: `initialized, but ${hooks.join(", ")}`,+ fix: "cogit init",+ };+ return {+ id: "project",+ status: "ok",+ message: `initialized as "${project.data.name}"; the git hooks are current`,+ };+ },+ },++ {+ id: "skill",+ run: async (ctx) => {+ const allowed = await ctx.agent.readSkillAllowed(ctx.env);+ if (allowed === undefined)+ return {+ id: "skill",+ status: "warn",+ message: "could not read Claude Code's permissions",+ fix: `check ~/.claude/settings.json is valid, or add ${ctx.agent.skillRule} to permissions.allow`,+ };+ if (!allowed)+ return {+ id: "skill",+ status: "warn",+ message: `${ctx.agent.skillRule} is not allowed, so the agent asks before each record update`,+ fix: "cogit init --allow-skill",+ };+ return {+ id: "skill",+ status: "ok",+ message: `${ctx.agent.skillRule} is allowed`,+ };+ },+ },++ {+ id: "transcripts",+ run: async (ctx) => {+ const transcripts = await ctx.transcripts();+ const retention = await ctx.agent.readRetention(ctx.env);+ if (transcripts.size === 0)+ return {+ id: "transcripts",+ status: "warn",+ message: "no Claude Code transcripts for this project; start a session here",+ fix: "claude",+ };+ if (retention === undefined)+ return {+ id: "transcripts",+ status: "warn",+ message: `${transcripts.size} transcript(s) found, but Claude Code's retention could not be read`,+ fix: "cogit init --retention 90",+ };+ if (retention < RETENTION_FLOOR)+ return {+ id: "transcripts",+ status: "warn",+ message: `${transcripts.size} transcript(s) found; Claude Code deletes them after ${retention} days`,+ fix: "cogit init --retention 90",+ };+ return {+ id: "transcripts",+ status: "ok",+ message: `${transcripts.size} transcript(s) found; Claude Code keeps them ${retention} days`,+ };+ },+ },++ {+ id: "sessions",+ run: async (ctx) => {+ const sessions = await ctx.sessions();+ const transcripts = await ctx.transcripts();+ const newest = await newestTranscript(transcripts);+ const tail =+ newest === undefined+ ? undefined+ : await unrecordedTail(ctx.root, newest.id, newest.file, ctx.agent);+ const pending = newest !== undefined && tail !== undefined && tail > 0 ? newest : undefined;+ if (sessions.length === 0)+ return {+ id: "sessions",+ status: "warn",+ message:+ pending === undefined+ ? "no session recorded yet"+ : `no session recorded yet; transcript ${pending.id} has ${tail} message(s) with no node`,+ ...(pending === undefined ? {} : { fix: `cogit backfill ${pending.id} --tail` }),+ };+ const latest = sessions.reduce((a, b) => (a.updatedAt >= b.updatedAt ? a : b));+ if (pending !== undefined)+ return {+ id: "sessions",+ status: "warn",+ message: `${sessions.length} session(s) recorded, newest ${latest.updatedAt}; the newest transcript has ${tail} message(s) with no node yet`,+ fix: `cogit backfill ${pending.id} --tail`,+ };+ return {+ id: "sessions",+ status: "ok",+ message: `${sessions.length} session(s) recorded, newest ${latest.updatedAt}; the newest transcript is fully recorded`,+ };+ },+ },++ {+ id: "server",+ run: async (ctx) => {+ const port = (await ctx.config()).serverPort;+ const url = `http://127.0.0.1:${port}`;+ if (await checkHealth(url, ctx.env))+ return {+ id: "server",+ status: "ok",+ message: `the map server answers on ${url}`,+ };+ return {+ id: "server",+ status: "warn",+ message: `no map server on ${url} (the saved map file still opens)`,+ fix: "cogit open .",+ };+ },+ },++ {+ id: "detached",+ run: async (ctx) => {+ const error = closePassError(await readDetachedLog(ctx.root));+ if (error === undefined)+ return {+ id: "detached",+ status: "ok",+ message: "the last close pass left no error",+ };+ return {+ id: "detached",+ status: "warn",+ message: `the last close pass wrote: ${error.line}`,+ fix:+ error.sessionId === undefined+ ? "cogit backfill <session-id> --tail --close"+ : `cogit backfill ${error.sessionId} --tail --close`,+ };+ },+ },+];++/** Hook files that are missing or carry a block an earlier CLI wrote. */+async function hookProblems(ctx: DoctorContext): Promise<string[]> {+ const gitRoot = await ctx.gitRoot();+ if (gitRoot === undefined) return ["the git hooks are not installed"];+ const dir = await gitHooksDir(gitRoot);+ if (dir === undefined) return ["the git hooks directory could not be found"];+ const problems: string[] = [];+ for (const event of ["prepare-commit-msg", "pre-commit"] as const) {+ const text = await readFile(join(dir, event), "utf8").catch(() => undefined);+ if (text === undefined || !text.includes(BLOCK_START)) {+ problems.push(`the ${event} hook is missing`);+ continue;+ }+ const block = /# >>> cogit[\s\S]*?# <<< cogit/.exec(text)?.[0];+ if (block !== hookBlock(event, ctx.root)) problems.push(`the ${event} hook is outdated`);+ }+ return problems;+}++/**+ * Runs every check in order and prints one line each (or the JSON report).+ * Returns the report; the caller sets the exit code from `ok`.+ */+export async function doctor(opts: DoctorOptions): Promise<DoctorReport> {+ const { io } = opts;+ const agent = defaultAgent();+ const resolved = await resolveProjectRoot(opts.dir);+ const root = resolved.root;++ const ctx: DoctorContext = {+ root,+ env: io.env,+ agent,+ gitRoot: once(() => findGitRoot(root)),+ project: once(() => loadProject(root)),+ sessions: once(() => loadAllSessions(root, io.warn)),+ transcripts: once(() => projectTranscripts(root, resolved.worktree?.path, agent, io.env)),+ config: once(() => loadConfig(io.env)),+ };++ const checks: DoctorCheck[] = [];+ for (const spec of CHECK_SPECS) {+ try {+ checks.push(await spec.run(ctx));+ } catch (err) {+ checks.push({+ id: spec.id,+ status: "fail",+ message: `the check could not run: ${(err as Error).message}`,+ });+ }+ }++ const report: DoctorReport = {+ ok: checks.every((check) => check.status !== "fail"),+ checks,+ };+ if (opts.json === true) {+ io.out(JSON.stringify(report, null, 2));+ } else {+ for (const check of checks) io.out(formatCheck(check));+ }+ return report;+}diff --git a/packages/cli/src/program.ts b/packages/cli/src/program.tsindex 8ea2792..1d3aabf 100644--- a/packages/cli/src/program.ts+++ b/packages/cli/src/program.ts@@ -12,6 +12,7 @@ import {configPrune,configSet,} from "./commands/config.js";+import { doctor } from "./commands/doctor.js";import { hooksInstall, hooksUninstall } from "./commands/hooks.js";import { type InitOptions, init } from "./commands/init.js";import { formatShow, log, logFile, logUnread, show } from "./commands/log.js";@@ -39,6 +40,8 @@ export interface ProgramDeps {server?: (env: NodeJS.ProcessEnv) => Promise<string | null>;/** Reads a hook's JSON input; tests pass it directly. */stdin?: () => Promise<string>;+ /** Sets the process exit code; tests observe it. */+ exitCode?: (code: number) => void;}function retention(value: string): number | "keep" {@@ -307,6 +310,30 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =}),);+ program+ .command("doctor")+ .description("check why the map may be empty; one line per check, with the fix")+ .helpGroup("Set up:")+ .argument("[dir]", "project directory", ".")+ .option("-C, --dir <dir>", "project directory (same as the positional)")+ .option("--json", "print the checks as JSON")+ .addHelpText("after", examples("cogit doctor", "cogit doctor ../my-app --json"))+ .action(async (dir: string, opts: { dir?: string; json?: boolean }) => {+ const report = await doctor({+ dir: opts.dir ?? dir,+ io: makeIo(false),+ json: opts.json === true,+ });+ if (!report.ok) {+ const setCode =+ deps.exitCode ??+ ((code: number) => {+ process.exitCode = code;+ });+ setCode(1);+ }+ });+program.command("build").description("regenerate .cogit/map.html")diff --git a/packages/cli/test/doctor.test.ts b/packages/cli/test/doctor.test.tsnew file mode 100644index 0000000..b726b12--- /dev/null+++ b/packages/cli/test/doctor.test.ts@@ -0,0 +1,364 @@+import { execFile } from "node:child_process";+import { mkdir, rm, writeFile } from "node:fs/promises";+import { join } from "node:path";+import { promisify } from "node:util";+import { beforeEach, describe, expect, it } from "vitest";+import pkg from "../package.json" with { type: "json" };+import { SKILL_RULE } from "../src/agents/claude/settings.js";+import { defaultAgent } from "../src/agents/index.js";+import {+ closePassError,+ type DoctorCheck,+ doctor,+ formatCheck,+ nodeCheck,+ transcriptDirName,+} from "../src/commands/doctor.js";+import { init } from "../src/commands/init.js";+import { hashTurns } from "../src/messages.js";+import { createProgram } from "../src/program.js";+import { startMapServer } from "../src/server.js";+import { updateConfig } from "../src/store/stores.js";+import { envFor, type FakeIo, fakeIo, noGitDir, T0, tempDir } from "./helpers.js";++const run = promisify(execFile);++let dir: string;+let env: NodeJS.ProcessEnv;+let io: FakeIo;+beforeEach(async () => {+ dir = await tempDir();+ env = envFor(dir);+ io = fakeIo(env);+});++const claudeDir = () => join(dir, "claude");+const settingsFile = () => join(claudeDir(), "settings.json");++/** An initialized project in its own git repository, so its hooks are isolated. */+async function project(name = "proj"): Promise<string> {+ const root = join(dir, name);+ await mkdir(root);+ await run("git", ["init", "-q", root]);+ await init(+ root,+ {+ name,+ git: "commit",+ retention: "keep",+ allowSkill: false,+ projectSettings: false,+ language: "auto",+ },+ fakeIo(env),+ );+ return root;+}++async function settings(value: Record<string, unknown>): Promise<void> {+ await mkdir(claudeDir(), { recursive: true });+ await writeFile(settingsFile(), JSON.stringify(value));+}++/** Claude Code's plugin list, as `claude plugin install` writes it. */+async function installPlugin(version: string): Promise<void> {+ await mkdir(join(claudeDir(), "plugins"), { recursive: true });+ await writeFile(+ join(claudeDir(), "plugins", "installed_plugins.json"),+ JSON.stringify({ version: 2, plugins: { "cogit@cogit": [{ scope: "user", version }] } }),+ );+}++const at = (m: number) => `2026-10-23T10:${String(m).padStart(2, "0")}:00.000Z`;++/** One transcript for this project; returns its path. */+async function transcript(root: string, id = "s1", texts = ["first"]): Promise<string> {+ const folder = join(claudeDir(), "projects", transcriptDirName(root));+ await mkdir(folder, { recursive: true });+ const file = join(folder, `${id}.jsonl`);+ const lines = texts.map((text, index) =>+ JSON.stringify({+ type: "user",+ timestamp: at(index + 1),+ message: { role: "user", content: text },+ origin: { kind: "human" },+ }),+ );+ await writeFile(file, `${lines.join("\n")}\n`);+ return file;+}++/** A session record whose nodes are the given message hashes. */+async function record(root: string, id: string, hashes: string[]): Promise<void> {+ await writeFile(+ join(root, ".cogit", "sessions", `${id}.json`),+ JSON.stringify({+ schema: 1,+ sessionId: id,+ agent: "claude-code",+ title: "Recorded",+ startedAt: T0,+ updatedAt: T0,+ status: { goal: "", done: [], pending: [], next: "" },+ nodes: hashes.map((hash) => ({+ id: hash,+ parent: null,+ kind: "message",+ title: "One",+ at: T0,+ })),+ }),+ );+}++async function check(root: string, id: string): Promise<DoctorCheck> {+ const report = await doctor({ dir: root, io: fakeIo(env) });+ const found = report.checks.find((entry) => entry.id === id);+ if (found === undefined) throw new Error(`no check ${id}`);+ return found;+}++describe("doctor's building blocks", () => {+ it("names a project's transcript folder the way Claude Code does", () => {+ expect(transcriptDirName("/home/me/my.app")).toBe("-home-me-my-app");+ expect(transcriptDirName("/home/me/.claude/worktrees/x")).toBe("-home-me--claude-worktrees-x");+ });++ it("prints the status, the reason and the fix on one line", () => {+ expect(formatCheck({ id: "x", status: "ok", message: "fine" })).toBe("ok fine");+ expect(formatCheck({ id: "x", status: "fail", message: "bad", fix: "cogit init" })).toBe(+ "fail bad · fix: cogit init",+ );+ });++ it("finds an error only in the last close pass", () => {+ const log = [+ "--- 2026-10-30T10:00:00.000Z backfill s1 --tail -C /p",+ "error: could not run claude: not found",+ "--- 2026-10-30T10:01:00.000Z backfill s1 --tail -C /p",+ "Saved session s1 (2 nodes)",+ "--- 2026-10-30T10:02:00.000Z build /p --quiet",+ "",+ ].join("\n");+ expect(closePassError(log)).toBeUndefined();+ expect(closePassError("--- t backfill s9 --tail\nerror: boom\n")).toEqual({+ sessionId: "s9",+ line: "error: boom",+ });+ expect(closePassError("")).toBeUndefined();+ });+});++describe("doctor", () => {+ it("passes the Node and CLI version check", async () => {+ const root = await project();+ const result = await check(root, "node");+ expect(result.status).toBe("ok");+ expect(result.message).toContain(pkg.version);+ expect(nodeCheck("22.12.0").status).toBe("fail");+ expect(nodeCheck("22.12.0").fix).toContain("22.13");+ });++ it("fails when the plugin is not installed and passes when it is enabled", async () => {+ const root = await project();+ expect((await check(root, "plugin")).status).toBe("fail");++ await installPlugin(pkg.version);+ expect((await check(root, "plugin")).status).toBe("warn");++ await settings({ enabledPlugins: { "cogit@cogit": true } });+ const ok = await check(root, "plugin");+ expect(ok.status).toBe("ok");+ expect(ok.message).toContain(pkg.version);+ });++ it("warns when the plugin's version is unknown or Claude Code's settings are unreadable", async () => {+ const root = await project();+ await mkdir(join(claudeDir(), "plugins"), { recursive: true });+ await writeFile(+ join(claudeDir(), "plugins", "installed_plugins.json"),+ JSON.stringify({ plugins: { "cogit@cogit": [{ scope: "user" }] } }),+ );+ await settings({ enabledPlugins: { "cogit@cogit": true } });+ expect((await check(root, "plugin")).status).toBe("warn");++ await transcript(root);+ await writeFile(settingsFile(), "{ not json");+ expect((await check(root, "plugin")).message).toContain("could not read");+ expect((await check(root, "skill")).message).toContain("could not read");+ expect((await check(root, "transcripts")).message).toContain("retention could not be read");+ });++ it("warns when the plugin and the CLI are at different versions", async () => {+ const root = await project();+ await installPlugin("0.0.9");+ await settings({ enabledPlugins: { "cogit@cogit": true } });+ const result = await check(root, "plugin");+ expect(result.status).toBe("warn");+ expect(result.message).toContain("claude plugin update cogit@cogit");+ });++ it("fails outside git and warns without a git email", async () => {+ const outside = await noGitDir();+ expect((await check(outside, "git")).status).toBe("fail");++ const root = await project();+ await run("git", ["-C", root, "config", "user.email", ""]);+ const warn = await check(root, "git");+ expect(warn.status).toBe("warn");+ expect(warn.fix).toContain("git config --global user.email");++ await run("git", ["-C", root, "config", "user.email", "[email protected]"]);+ await run("git", ["-C", root, "config", "user.name", "Me"]);+ const ok = await check(root, "git");+ expect(ok.status).toBe("ok");+ expect(ok.message).toContain("[email protected]");+ });++ it("fails an uninitialized project and warns about hooks that are missing or outdated", async () => {+ const plain = join(dir, "plain");+ await mkdir(plain);+ await run("git", ["init", "-q", plain]);+ expect((await check(plain, "project")).status).toBe("fail");++ const root = await project();+ expect((await check(root, "project")).status).toBe("ok");++ await rm(join(root, ".git", "hooks", "prepare-commit-msg"));+ expect((await check(root, "project")).message).toContain("prepare-commit-msg hook is missing");++ await writeFile(+ join(root, ".git", "hooks", "prepare-commit-msg"),+ "#!/bin/sh\n\n# >>> cogit\ncogit hook prepare-commit-msg\n# <<< cogit\n",+ );+ const stale = await check(root, "project");+ expect(stale.status).toBe("warn");+ expect(stale.message).toContain("prepare-commit-msg hook is outdated");++ await writeFile(join(root, ".cogit", "project.json"), "{ not json");+ const broken = await check(root, "project");+ expect(broken.status).toBe("fail");+ expect(broken.message).toContain("invalid JSON");+ });++ it("warns until the record skill is allowed", async () => {+ const root = await project();+ expect((await check(root, "skill")).status).toBe("warn");+ await settings({ permissions: { allow: [SKILL_RULE] } });+ expect((await check(root, "skill")).status).toBe("ok");+ });++ it("warns without a transcript and when retention is short", async () => {+ const root = await project();+ expect((await check(root, "transcripts")).status).toBe("warn");++ await transcript(root);+ expect((await check(root, "transcripts")).status).toBe("warn"); // no settings: 30 days++ await settings({ cleanupPeriodDays: 120 });+ const ok = await check(root, "transcripts");+ expect(ok.status).toBe("ok");+ expect(ok.message).toContain("120 days");+ });++ it("reports the recorded sessions and the unrecorded tail", async () => {+ const root = await project();+ const file = await transcript(root);+ expect((await check(root, "sessions")).status).toBe("warn");++ const turns = hashTurns("s1", await defaultAgent().readConversation(file));+ await record(root, "s1", [turns[0]?.hash ?? ""]);+ const ok = await check(root, "sessions");+ expect(ok.status).toBe("ok");+ expect(ok.message).toContain("1 session(s) recorded");++ await transcript(root, "s2", ["new one"]);+ const newer = await check(root, "sessions");+ expect(newer.status).toBe("warn");+ expect(newer.fix).toBe("cogit backfill s2 --tail");+ });++ it("warns when the map server is down and passes when it answers", async () => {+ const root = await project();+ expect((await check(root, "server")).status).toBe("warn");++ const server = await startMapServer({ env, port: 0 });+ try {+ await updateConfig((config) => ({ ...config, serverPort: server.port }), env);+ const ok = await check(root, "server");+ expect(ok.status).toBe("ok");+ expect(ok.message).toContain(String(server.port));+ } finally {+ await server.close();+ }+ });++ it("turns a check that cannot read its data into a failure, not a crash", async () => {+ const root = await project();+ await rm(join(root, ".cogit", "sessions"), { recursive: true, force: true });+ await writeFile(join(root, ".cogit", "sessions"), "not a directory");+ const result = await check(root, "sessions");+ expect(result.status).toBe("fail");+ expect(result.message).toContain("the check could not run");+ });++ it("reports an error the last close pass wrote", async () => {+ const root = await project();+ expect((await check(root, "detached")).status).toBe("ok");+ await mkdir(join(root, ".cogit", "state"), { recursive: true });+ await writeFile(+ join(root, ".cogit", "state", "detached.log"),+ "--- 2026-10-30T10:00:00.000Z backfill s7 --tail --close -C /p\nerror: could not run claude\n",+ );+ const warn = await check(root, "detached");+ expect(warn.status).toBe("warn");+ expect(warn.fix).toBe("cogit backfill s7 --tail --close");+ });++ it("runs end to end from the CLI, prints one line per check and exits 1 on a failure", async () => {+ const root = join(dir, "empty");+ await mkdir(root);+ await run("git", ["init", "-q", root]);+ const lines = fakeIo(env);+ let code: number | undefined;+ const program = createProgram(() => lines, {+ exitCode: (value) => {+ code = value;+ },+ });+ program.exitOverride().configureOutput({ writeErr: () => {}, writeOut: () => {} });+ for (const command of program.commands) command.exitOverride();+ await program.parseAsync(["doctor", root], { from: "user" });++ expect(lines.lines.length).toBeGreaterThanOrEqual(9);+ expect(lines.lines.every((line) => /^(ok |warn |fail )/.test(line))).toBe(true);+ expect(lines.lines.join("\n")).toMatch(/fail .*project\.json is missing/);+ expect(code).toBe(1);++ // Without the test seam the command sets the process exit code itself.+ const before = process.exitCode;+ try {+ const bare = createProgram(() => fakeIo(env));+ bare.exitOverride();+ await bare.parseAsync(["doctor", root], { from: "user" });+ expect(process.exitCode).toBe(1);+ } finally {+ process.exitCode = before;+ }++ const json = fakeIo(env);+ const report = await doctor({ dir: root, io: json, json: true });+ expect(JSON.parse(json.lines.at(-1) ?? "{}")).toMatchObject({ ok: false });+ expect(report.checks.map((entry) => entry.id)).toEqual([+ "node",+ "plugin",+ "git",+ "project",+ "skill",+ "transcripts",+ "sessions",+ "server",+ "detached",+ ]);+ });+});