Skip to content

armgit / cogit

Public Imported from GitHub
0

Git for the intent behind agent-written code. Records what your coding agent decided and why, and links every commit to it.

feat(why): note what was tried before the agent edits a file

Eren027d138fb7b6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index c7ff75f..c275613 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 why <file>` follows file → the commits that touched it → their `Thought:` messages → the decisions and rejected alternatives those thoughts recorded, newest first, each with its message hash and date. A Claude Code `PreToolUse` hook on Edit/Write/MultiEdit adds the same information to the agent's context before it writes a file: once per file per session, at most five options and about 600 characters, the rest pointing at `cogit why`; the note never blocks or changes the call, and any failure is silent (`tryBeforeNotes`, on by default, off in Settings). The lookup is exact; the wording is the record's summary.
- The map shows how much code landed after a message: each row with linked commits carries a `+1 240 −80 · 14 files` chip from `git diff --numstat` (the `Thought:` trailer union with the recorded commits, a commit counted once), the details panel states the same numbers and offers a read toggle, and rows you have not marked read above `bigChangeLines` (default 300) get a quiet highlight. The map head gains an "Unread" filter listing unread messages most code first, `cogit log --unread` prints the same list, and the panel card counts a project's unread big changes. The marks live in `.cogit/state/read.json` (local, never committed or shared) and are written by the local map server; nothing reads or classifies message text.
- `cogit pr [base]` turns a branch into a review-ready Markdown description from the thoughts behind its commits: the sessions' goals, each thought's title, summary, decisions and rejected options, its commits and changed files, and the commits with no recorded thought (`thought h… not recorded yet` when the record has not caught up). The base is the upstream's merge base, else `main`, else `master`, with a clear error when none resolves; `--json` prints the same content as data and `--copy` puts the Markdown on the clipboard. It reads only the record — never the conversation text or the user's prompts — and stays under GitHub's body limit by dropping file lists first, then summaries, saying what was left out. The record skill hands its output over instead of writing a PR description itself.
diff --git a/README.md b/README.md
index b8bda03..0e67c43 100644
--- a/README.md
+++ b/README.md
@@ -71,6 +71,7 @@ cogit log --branches # only the branch summaries
cogit log --file src/auth.ts # the thoughts that touched this file
cogit show h3f9c2a1b4d6e # one message: the turn, what came of it, its commits
cogit blame src/auth.ts:42 # which recorded message produced this line
+cogit why src/auth.ts # what earlier thoughts decided about this file, and rejected
cogit search "refresh token" # titles, summaries, decisions and the stored conversation
```
@@ -78,6 +79,14 @@ Each takes `[dir]` (or `-C <dir>`), the list verbs take `-n <count>` and `--json
addressed by its hash (`h` plus 12 hex), `<session-id-prefix>:mN`, or — for `show` — a commit
hash with a `Thought:` trailer.
+`cogit why <file>` runs the chain backwards: file → the commits that touched it → their
+`Thought:` messages → the decisions and rejected alternatives those messages recorded, newest
+first, each with its message hash and date. The lookup is exact, but the wording is the agent's
+summary from the record, so it is only as good as the record. The Claude Code plugin also uses
+it before an edit: when the file has rejected alternatives and the session has not been told
+about that file yet, the agent gets a short "earlier, for this file" note (at most five options,
+`tryBeforeNotes`). It is information, not a rule — the note never blocks the edit.
+
## Review a PR with cogit
On the branch, before opening the pull request:
@@ -159,6 +168,7 @@ under `gitPolicy: ignore` the description says the hashes resolve only on the au
| `catchUpModel` | `haiku` | Model for the session-end catch-up |
| `messageSummaries` | `false` | A summary on every message, not just every branch |
| `startupContext` | `true` | Hand the agent the previous session's lineage at session start |
+| `tryBeforeNotes` | `true` | Tell the agent, before an edit, what earlier thoughts rejected for that file |
| `gitPolicy` | `commit` | Whether new projects commit the record |
| `shareConversations` | `false` | Commit the raw conversation too |
| `recordCommit` | `ask` | What to do with messages after the last code commit |
diff --git a/docs/schema/config.json b/docs/schema/config.json
index 23f644d..a1b4b4c 100644
--- a/docs/schema/config.json
+++ b/docs/schema/config.json
@@ -75,6 +75,10 @@
"minimum": 1,
"maximum": 1000000
},
+ "tryBeforeNotes": {
+ "default": true,
+ "type": "boolean"
+ },
"agents": {
"default": [
"claude-code"
@@ -108,6 +112,7 @@
"recordCommit",
"trailerMaxAgeHours",
"bigChangeLines",
+ "tryBeforeNotes",
"agents",
"setupHintOff"
],
diff --git a/docs/schema/hook-state.json b/docs/schema/hook-state.json
index ed9df2f..31ec6c5 100644
--- a/docs/schema/hook-state.json
+++ b/docs/schema/hook-state.json
@@ -30,13 +30,23 @@
"type": "null"
}
]
+ },
+ "notedFiles": {
+ "default": [],
+ "type": "array",
+ "items": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 500
+ }
}
},
"required": [
"schema",
"turns",
"turnsSinceUpdate",
- "recordUpdatedAt"
+ "recordUpdatedAt",
+ "notedFiles"
],
"additionalProperties": false
}
diff --git a/packages/cli/hooks/hooks.json b/packages/cli/hooks/hooks.json
index 767729d..e2b3809 100644
--- a/packages/cli/hooks/hooks.json
+++ b/packages/cli/hooks/hooks.json
@@ -47,6 +47,19 @@
}
]
}
+ ],
+ "PreToolUse": [
+ {
+ "matcher": "Edit|Write|MultiEdit",
+ "hooks": [
+ {
+ "type": "command",
+ "command": "node",
+ "args": ["${CLAUDE_PLUGIN_ROOT}/dist/cli.js", "hook", "pretooluse"],
+ "timeout": 10
+ }
+ ]
+ }
]
}
}
diff --git a/packages/cli/src/agents/claude/hooks.ts b/packages/cli/src/agents/claude/hooks.ts
index ac08fcd..1e06c6a 100644
--- a/packages/cli/src/agents/claude/hooks.ts
+++ b/packages/cli/src/agents/claude/hooks.ts
@@ -15,6 +15,9 @@ export const ClaudeHookInput = z.looseObject({
stop_hook_active: z.boolean().optional(),
/** SessionStart only: `startup`, `resume`, `clear` or `compact`. */
source: z.string().optional(),
+ /** PreToolUse only: the tool and its arguments (`file_path` on the write tools). */
+ tool_name: z.string().optional(),
+ tool_input: z.looseObject({}).optional(),
});
/** Parses a hook's stdin; undefined when it is not Claude Code's payload. */
diff --git a/packages/cli/src/agents/types.ts b/packages/cli/src/agents/types.ts
index 034f49c..7280d6d 100644
--- a/packages/cli/src/agents/types.ts
+++ b/packages/cli/src/agents/types.ts
@@ -52,6 +52,13 @@ export interface HookInput {
stop_hook_active?: boolean | undefined;
/** SessionStart only: `startup`, `resume`, `clear` or `compact`. */
source?: string | undefined;
+ /** PreToolUse only: the tool about to run (`Edit`, `Write`, `MultiEdit`, …). */
+ tool_name?: string | undefined;
+ /**
+ * PreToolUse only: the tool's arguments. `file_path` names the file for the
+ * write tools; other tools pass whatever they take.
+ */
+ tool_input?: Record<string, unknown> | undefined;
}
/** A file cogit changed and the backup it left first. */
diff --git a/packages/cli/src/commands/why.ts b/packages/cli/src/commands/why.ts
new file mode 100644
index 0000000..2890966
--- /dev/null
+++ b/packages/cli/src/commands/why.ts
@@ -0,0 +1,287 @@
+import { stat } from "node:fs/promises";
+import { isAbsolute, relative, resolve, sep } from "node:path";
+import { blameCommitHashes, findGitRoot } from "../git.js";
+import { CliError, type Io } from "../io.js";
+import { resolveProjectRoot } from "../store/root.js";
+import { loadAllSessions, loadProject } from "../store/stores.js";
+import { attachThoughtTrailers, earliestSessionStart, readThoughtTrailers } from "../thought.js";
+import { buildMessages } from "../view/lineage.js";
+import type { ViewNode } from "../view/model.js";
+import { shortHash, stamp } from "./log.js";
+
+/**
+ * `cogit why <file>` (Story 10.4): the decisions and rejected alternatives of
+ * the thoughts behind a file. The chain is deterministic — file → commits that
+ * touched it (the same index `blame` uses) → their `Thought:` messages → the
+ * record's "considered and rejected" options — so the answer is exact, though
+ * each summary is only as good as the record the agent wrote. No message text
+ * is read or classified.
+ */
+
+/** An option the record says was considered and not taken, with the reason. */
+export interface WhyAlternative {
+ option: string;
+ why: string;
+}
+
+/** One decision behind the file, as the record holds it. */
+export interface WhyDecision {
+ title: string;
+ why: string;
+ alternatives: WhyAlternative[];
+}
+
+/** One thought behind the file, with the decisions it recorded. */
+export interface WhyHit {
+ sessionId: string;
+ sessionTitle: string;
+ /** The message hash `cogit show` takes. */
+ messageId: string;
+ /** The `mN` label the map shows. */
+ label: string;
+ /** The message time (its session's start when the record has none). */
+ at: string;
+ title: string;
+ decisions: WhyDecision[];
+}
+
+const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
+
+/** `26 Oct`, the short date the note shows; an unparseable value stays as it is. */
+export function dayStamp(iso: string): string {
+ const date = new Date(iso);
+ if (Number.isNaN(date.getTime())) return iso;
+ return `${date.getDate()} ${MONTHS[date.getMonth()]}`;
+}
+
+function oneLine(text: string): string {
+ return text.replace(/\s+/g, " ").trim();
+}
+
+/** A repo-relative path, or undefined when the file sits outside the repository. */
+function repositoryPath(gitRoot: string, root: string, file: string): string | undefined {
+ const rel = relative(gitRoot, resolve(root, file));
+ if (rel === "" || rel.startsWith("..") || isAbsolute(rel)) return undefined;
+ return rel.split(sep).join("/");
+}
+
+/** A recorded short hash may name a full hash git printed, or the reverse. */
+function sameCommit(recorded: string, blamed: string): boolean {
+ return blamed.startsWith(recorded) || recorded.startsWith(blamed);
+}
+
+/**
+ * The decisions a message recorded: its own (a user-level choice with a `why`,
+ * or rejected options) and the agent's decisions along the way. A message with
+ * neither is left out: the lookup is about what was considered, not every file
+ * a thought touched.
+ */
+function decisionsOf(message: ViewNode): WhyDecision[] {
+ const decisions: WhyDecision[] = [];
+ const alternatives = message.alternatives ?? [];
+ if (alternatives.length > 0 || (message.why ?? "").trim() !== "") {
+ decisions.push({ title: message.title, why: message.why ?? "", alternatives });
+ }
+ for (const decision of message.agentDecisions ?? []) {
+ decisions.push({
+ title: decision.title,
+ why: decision.why,
+ alternatives: decision.alternatives ?? [],
+ });
+ }
+ return decisions;
+}
+
+/**
+ * The decisions of the thoughts behind `file`, newest first. `file` is relative
+ * to the project root. Any unreadable part (no repository, no history, no
+ * record) is "nothing known": a hook may call this on every edit.
+ */
+export async function collectWhy(
+ root: string,
+ file: string,
+ env?: NodeJS.ProcessEnv,
+): Promise<WhyHit[]> {
+ const gitRoot = await findGitRoot(root);
+ if (gitRoot === undefined) return [];
+ const repoPath = repositoryPath(gitRoot, root, file);
+ if (repoPath === undefined) return [];
+
+ let commits: string[];
+ try {
+ commits = await blameCommitHashes(gitRoot, repoPath);
+ } catch {
+ return [];
+ }
+ if (commits.length === 0) return [];
+
+ const sessions = await loadAllSessions(root, () => {});
+ const trailers = await readThoughtTrailers(root, {
+ ...(env === undefined ? {} : { env }),
+ since: earliestSessionStart(sessions),
+ });
+ const attached = attachThoughtTrailers(sessions, trailers);
+ const hits: WhyHit[] = [];
+
+ for (const session of attached) {
+ const sessionTitle = session.title.trim() === "" ? session.sessionId : session.title;
+ for (const message of buildMessages(session.nodes)) {
+ const linked = (message.commits ?? []).some((hash) =>
+ commits.some((commit) => sameCommit(hash, commit)),
+ );
+ if (!linked) continue;
+ const decisions = decisionsOf(message);
+ if (decisions.length === 0) continue;
+ hits.push({
+ sessionId: session.sessionId,
+ sessionTitle,
+ messageId: message.id,
+ label: message.label ?? message.id,
+ at: message.at ?? session.startedAt,
+ title: message.title,
+ decisions,
+ });
+ }
+ }
+
+ const time = (hit: WhyHit): number => {
+ const parsed = Date.parse(hit.at);
+ return Number.isNaN(parsed) ? Number.NEGATIVE_INFINITY : parsed;
+ };
+ return hits.sort(
+ (a, b) =>
+ time(b) - time(a) ||
+ a.sessionId.localeCompare(b.sessionId) ||
+ a.messageId.localeCompare(b.messageId),
+ );
+}
+
+/** The plain-text `why`: each thought with its decisions, newest first. */
+export function formatWhy(hits: readonly WhyHit[]): string[] {
+ const lines: string[] = [];
+ for (const hit of hits) {
+ if (lines.length > 0) lines.push("");
+ lines.push(
+ `${shortHash(hit.messageId)} ${hit.label} ${stamp(hit.at)} · ${oneLine(hit.title)}`,
+ );
+ lines.push(` ${oneLine(hit.sessionTitle)} (${hit.sessionId})`);
+ for (const decision of hit.decisions) {
+ const why = oneLine(decision.why);
+ lines.push(` decision: ${oneLine(decision.title)}${why === "" ? "" : ` — ${why}`}`);
+ for (const alt of decision.alternatives) {
+ const reason = oneLine(alt.why);
+ lines.push(` not: ${oneLine(alt.option)}${reason === "" ? "" : ` — ${reason}`}`);
+ }
+ }
+ }
+ return lines;
+}
+
+export interface WhyOptions {
+ dir: string;
+ /** A file, relative to the project or absolute. */
+ file: string;
+ io: Io;
+}
+
+/**
+ * Prints the decisions and rejected alternatives of the thoughts behind a file,
+ * each with its message hash and date.
+ */
+export async function why(opts: WhyOptions): Promise<WhyHit[]> {
+ const { io } = opts;
+ const { root } = await resolveProjectRoot(opts.dir);
+ const project = await loadProject(root);
+ if (!project.found) throw new CliError(`${root} is not initialized; run \`cogit init\` first`);
+ if (!project.ok) throw new CliError(project.error);
+ if ((await findGitRoot(root)) === undefined)
+ throw new CliError(`${root} is not inside a git repository; why needs one`);
+
+ const exists = await stat(resolve(root, opts.file)).then(
+ (info) => info.isFile(),
+ () => false,
+ );
+ if (!exists) throw new CliError(`${opts.file} does not exist`);
+
+ const hits = await collectWhy(root, opts.file, io.env);
+ if (hits.length === 0) {
+ io.out(`No decisions or rejected alternatives recorded for ${opts.file}.`);
+ return hits;
+ }
+ for (const line of formatWhy(hits)) io.out(line);
+ io.out("");
+ io.out("`cogit show <hash>` opens the thought; the record is the agent's summary.");
+ return hits;
+}
+
+/** How many rejected options one PreToolUse note carries. */
+export const TRY_BEFORE_MAX_ITEMS = 5;
+
+/** Roughly how long the note may be; the rest is left to `cogit why`. */
+export const TRY_BEFORE_MAX_CHARS = 600;
+
+interface RejectedItem extends WhyAlternative {
+ messageId: string;
+ at: string;
+}
+
+/** Every rejected option behind the file, in the hits' (newest-first) order. */
+export function rejectedItems(hits: readonly WhyHit[]): RejectedItem[] {
+ const items: RejectedItem[] = [];
+ for (const hit of hits) {
+ for (const decision of hit.decisions) {
+ for (const alt of decision.alternatives) {
+ items.push({ ...alt, messageId: hit.messageId, at: hit.at });
+ }
+ }
+ }
+ return items;
+}
+
+/**
+ * The note a PreToolUse hook adds when the agent is about to edit a file whose
+ * earlier thoughts rejected some options. A fact from the record, not a rule:
+ * the agent and the user decide what to do with it. At most five options and
+ * about {@link TRY_BEFORE_MAX_CHARS} characters; the rest points at
+ * `cogit why <file>`. Undefined when there is nothing to say.
+ */
+export function tryBeforeNote(file: string, hits: readonly WhyHit[]): string | undefined {
+ const items = rejectedItems(hits);
+ if (items.length === 0) return undefined;
+
+ const header = "Earlier, for this file:";
+ const footer = "Decide knowingly.";
+ const more = `See \`cogit why ${file}\` for more.`;
+ const lines: string[] = [];
+ for (const item of items.slice(0, TRY_BEFORE_MAX_ITEMS)) {
+ const reason = oneLine(item.why) === "" ? "no reason recorded" : oneLine(item.why);
+ const line =
+ `- "${oneLine(item.option)}" was considered and rejected ` +
+ `(${shortHash(item.messageId)}, ${dayStamp(item.at)}): ${reason}`;
+ const truncated = lines.length + 1 < items.length;
+ const total = [header, ...lines, line, footer, ...(truncated ? [more] : [])].join("\n");
+ if (total.length <= TRY_BEFORE_MAX_CHARS) {
+ lines.push(line);
+ continue;
+ }
+ // No room left. Count and character caps both end in the same "more" line.
+ break;
+ }
+ if (lines.length === 0) {
+ // One option's own reason can be long (the schema allows 200 + 500 chars):
+ // keep the header, footer and pointer, and clip only the option line.
+ const first = items[0];
+ if (first === undefined) return undefined;
+ const reason = oneLine(first.why) === "" ? "no reason recorded" : oneLine(first.why);
+ const full =
+ `- "${oneLine(first.option)}" was considered and rejected ` +
+ `(${shortHash(first.messageId)}, ${dayStamp(first.at)}): ${reason}`;
+ const tail = [footer, ...(items.length > 1 ? [more] : [])].join("\n");
+ const room = TRY_BEFORE_MAX_CHARS - header.length - tail.length - 3;
+ if (room < 40) return undefined;
+ lines.push(full.length <= room ? full : `${full.slice(0, room - 1).trimEnd()}…`);
+ }
+
+ const truncated = lines.length < items.length;
+ return [header, ...lines, footer, ...(truncated ? [more] : [])].join("\n");
+}
diff --git a/packages/cli/src/hooks/pretooluse.ts b/packages/cli/src/hooks/pretooluse.ts
new file mode 100644
index 0000000..dfcb529
--- /dev/null
+++ b/packages/cli/src/hooks/pretooluse.ts
@@ -0,0 +1,62 @@
+import { isAbsolute, relative, resolve, sep } from "node:path";
+import { collectWhy, tryBeforeNote } from "../commands/why.js";
+import { type HookState, STATE_SCHEMA } from "../schema/state.js";
+import { loadConfig, updateState } from "../store/stores.js";
+import type { HookContext, HookOutput } from "./run.js";
+
+/**
+ * PreToolUse on Edit/Write/MultiEdit (Story 10.4): before the agent writes a
+ * file, tell it — once per file per session — about the options earlier
+ * thoughts considered and rejected for that file. The note is information from
+ * the record, never a rule, and the hook never blocks or changes the call: any
+ * failure ends in silence and exit 0 (`hooks/run.ts`).
+ */
+
+/** The tools that write a file; their input names it in `file_path`. */
+const WRITE_TOOLS = new Set(["Edit", "Write", "MultiEdit"]);
+
+export async function onPreToolUse(ctx: HookContext): Promise<HookOutput | undefined> {
+ const tool = ctx.input.tool_name;
+ if (tool === undefined || !WRITE_TOOLS.has(tool)) return undefined;
+ const filePath = ctx.input.tool_input?.file_path;
+ if (typeof filePath !== "string" || filePath.trim() === "") return undefined;
+
+ const config = await loadConfig(ctx.env);
+ if (!config.tryBeforeNotes) return undefined;
+
+ // The agent passes an absolute path; a relative one is relative to its cwd.
+ const absolute = isAbsolute(filePath) ? filePath : resolve(ctx.input.cwd ?? ctx.root, filePath);
+ const rel = relative(ctx.root, absolute);
+ if (rel === "" || rel.startsWith("..") || isAbsolute(rel)) return undefined;
+ const key = rel.split(sep).join("/");
+
+ // Claim the file first: one state update decides both "already told?" and
+ // "remember that it was looked at", so two quick edits cannot both answer.
+ let firstLook = false;
+ await updateState(
+ ctx.root,
+ ctx.sessionId,
+ (cur) => {
+ const noted = cur?.notedFiles ?? [];
+ if (noted.includes(key)) return cur ?? emptyState();
+ firstLook = true;
+ return { ...(cur ?? emptyState()), notedFiles: [...noted, key].sort() };
+ },
+ { timeoutMs: 1500 },
+ );
+ if (!firstLook) return undefined;
+
+ const hits = await collectWhy(ctx.root, key, ctx.env);
+ const note = tryBeforeNote(key, hits);
+ return note === undefined ? undefined : ctx.agent.additionalContext("PreToolUse", note);
+}
+
+function emptyState(): HookState {
+ return {
+ schema: STATE_SCHEMA,
+ turns: 0,
+ turnsSinceUpdate: 0,
+ recordUpdatedAt: null,
+ notedFiles: [],
+ };
+}
diff --git a/packages/cli/src/hooks/run.ts b/packages/cli/src/hooks/run.ts
index 01d60f5..e8d7249 100644
--- a/packages/cli/src/hooks/run.ts
+++ b/packages/cli/src/hooks/run.ts
@@ -5,6 +5,7 @@ import { type AgentAdapter, defaultAgent, type HookInput } from "../agents/index
import { Slug } from "../schema/common.js";
import { captureDisabled, projectPaths } from "../store/paths.js";
import { resolveProjectRoot } from "../store/root.js";
+import { onPreToolUse } from "./pretooluse.js";
import { onPromptSubmit } from "./promptsubmit.js";
import { onSessionEnd } from "./sessionend.js";
import { onSessionStart } from "./sessionstart.js";
@@ -40,6 +41,7 @@ const HANDLERS: Record<string, (ctx: HookContext) => Promise<HookOutput | undefi
sessionstart: onSessionStart,
sessionend: onSessionEnd,
promptsubmit: onPromptSubmit,
+ pretooluse: onPreToolUse,
};
export const HOOK_EVENTS = Object.keys(HANDLERS);
diff --git a/packages/cli/src/hooks/stop.ts b/packages/cli/src/hooks/stop.ts
index fd6f8be..2ef273c 100644
--- a/packages/cli/src/hooks/stop.ts
+++ b/packages/cli/src/hooks/stop.ts
@@ -28,6 +28,7 @@ export function countTurn(
turns: 0,
turnsSinceUpdate: 0,
recordUpdatedAt,
+ notedFiles: [],
};
// The record changed since the last Stop (the skill ran), so count from here.
const since = cur.recordUpdatedAt === recordUpdatedAt ? cur.turnsSinceUpdate : 0;
diff --git a/packages/cli/src/program.ts b/packages/cli/src/program.ts
index 314fdef..eaf0c06 100644
--- a/packages/cli/src/program.ts
+++ b/packages/cli/src/program.ts
@@ -20,6 +20,7 @@ import { openPanel, openProject } from "./commands/open.js";
import { pr } from "./commands/pr.js";
import { search } from "./commands/search.js";
import { readStdin, sessionShow, sessionWrite } from "./commands/session.js";
+import { why } from "./commands/why.js";
import { isGitHookEvent, runGitHook } from "./git-hooks.js";
import { runHook } from "./hooks/run.js";
import { CliError, type Io, processIo } from "./io.js";
@@ -91,6 +92,20 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =
}),
);
+ program
+ .command("why")
+ .description("show the decisions and rejected options behind a file")
+ .helpGroup("Read:")
+ .argument("<file>", "file to look up, relative to the project")
+ .argument("[dir]", "project directory", ".")
+ .option("-C, --dir <dir>", "project directory (same as the positional)")
+ .addHelpText("after", examples("cogit why src/auth.ts", "cogit why src/auth.ts ../my-app"))
+ .action(
+ run(async (file: string, dir: string, opts: { dir?: string }) => {
+ await why({ dir: opts.dir ?? dir, file, io: makeIo(false) });
+ }),
+ );
+
program
.command("log")
.description("print the recorded lineage, newest first")
diff --git a/packages/cli/src/schema/config.ts b/packages/cli/src/schema/config.ts
index bb82e43..eaeb280 100644
--- a/packages/cli/src/schema/config.ts
+++ b/packages/cli/src/schema/config.ts
@@ -46,6 +46,12 @@ export const Config = z.object({
* not a judgement: it never hides or ranks anything by itself.
*/
bigChangeLines: z.int().min(1).max(1_000_000).default(300),
+ /**
+ * Whether the agent is told, before editing a file, about options earlier
+ * thoughts considered and rejected for that file (Story 10.4). A note from
+ * the record, never a rule; off means silence.
+ */
+ tryBeforeNotes: z.boolean().default(true),
agents: z.array(z.string().min(1)).default(["claude-code"]),
/** Project roots ("don't ask again" in this project) where the setup hint stays silent. */
setupHintOff: z.array(z.string().min(1)).default([]),
diff --git a/packages/cli/src/schema/state.ts b/packages/cli/src/schema/state.ts
index bf78a55..3dd756b 100644
--- a/packages/cli/src/schema/state.ts
+++ b/packages/cli/src/schema/state.ts
@@ -15,6 +15,13 @@ export const HookState = z.object({
turnsSinceUpdate: z.number().int().min(0).default(0),
/** The record's `updatedAt` when the hook last looked; a change resets the count. */
recordUpdatedAt: IsoDate.nullable().default(null),
+ /**
+ * Project-relative files the PreToolUse hook has already told this session
+ * about (Story 10.4): the "tried before" note is once per file per session,
+ * and a file with nothing to say is remembered too, so every edit does not
+ * walk the history again.
+ */
+ notedFiles: z.array(z.string().min(1).max(500)).default([]),
});
export type HookState = z.infer<typeof HookState>;
diff --git a/packages/cli/src/view/model.ts b/packages/cli/src/view/model.ts
index 9f54b7c..2460aff 100644
--- a/packages/cli/src/view/model.ts
+++ b/packages/cli/src/view/model.ts
@@ -32,6 +32,7 @@ export const TOKEN_META_NAME = "cogit-token";
export const PANEL_EDITABLE_KEYS = [
"messageSummaries",
"startupContext",
+ "tryBeforeNotes",
"language",
"updateEveryTurns",
"sessionEndCatchUp",
@@ -335,6 +336,11 @@ export interface PanelSettings {
catchUpModel: string;
messageSummaries: boolean;
startupContext: boolean;
+ /**
+ * Whether the agent is told before editing a file about options earlier
+ * thoughts considered and rejected (Story 10.4).
+ */
+ tryBeforeNotes: boolean;
shareConversations: boolean;
recordCommit: "ask" | "auto" | "off";
gitPolicy: "ignore" | "commit";
diff --git a/packages/cli/src/view/panel.ts b/packages/cli/src/view/panel.ts
index 3bf1749..5d106be 100644
--- a/packages/cli/src/view/panel.ts
+++ b/packages/cli/src/view/panel.ts
@@ -51,6 +51,7 @@ export function panelSettings(config: Config): PanelSettings {
catchUpModel: config.catchUpModel,
messageSummaries: config.messageSummaries,
startupContext: config.startupContext,
+ tryBeforeNotes: config.tryBeforeNotes,
shareConversations: config.shareConversations,
recordCommit: config.recordCommit,
gitPolicy: config.gitPolicy,
diff --git a/packages/cli/src/view/settings.ts b/packages/cli/src/view/settings.ts
index 8631578..bda64d0 100644
--- a/packages/cli/src/view/settings.ts
+++ b/packages/cli/src/view/settings.ts
@@ -45,6 +45,12 @@ const EDITABLE: FieldSpec[] = [
help: "Hand the agent the previous session's lineage when a chat starts.",
kind: "boolean",
},
+ {
+ key: "tryBeforeNotes",
+ label: "Tried-before notes",
+ help: "Before the agent edits a file, tell it which options earlier thoughts rejected for it.",
+ kind: "boolean",
+ },
{
key: "language",
label: "Language",
@@ -126,6 +132,7 @@ export const DEFAULT_SETTINGS: PanelSettings = {
catchUpModel: "haiku",
messageSummaries: false,
startupContext: true,
+ tryBeforeNotes: true,
shareConversations: false,
recordCommit: "ask",
gitPolicy: "commit",
@@ -142,6 +149,7 @@ export function editableSettings(settings: PanelSettings): PanelEditableSettings
return {
messageSummaries: settings.messageSummaries,
startupContext: settings.startupContext,
+ tryBeforeNotes: settings.tryBeforeNotes,
language: settings.language,
updateEveryTurns: settings.updateEveryTurns,
sessionEndCatchUp: settings.sessionEndCatchUp,
diff --git a/packages/cli/test/panel.test.ts b/packages/cli/test/panel.test.ts
index 8f20c2e..e4754b8 100644
--- a/packages/cli/test/panel.test.ts
+++ b/packages/cli/test/panel.test.ts
@@ -87,6 +87,7 @@ describe("buildPanel", () => {
catchUpModel: "haiku",
messageSummaries: false,
startupContext: true,
+ tryBeforeNotes: true,
shareConversations: false,
recordCommit: "ask",
gitPolicy: "commit",
diff --git a/packages/cli/test/program-commands.test.ts b/packages/cli/test/program-commands.test.ts
index 924660d..490194c 100644
--- a/packages/cli/test/program-commands.test.ts
+++ b/packages/cli/test/program-commands.test.ts
@@ -88,6 +88,44 @@ describe("commands through the CLI", () => {
expect(io.lines.at(-1)).toBe("Added epoch e1: First");
});
+ it("runs why from the CLI", async () => {
+ 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 git("config", "user.email", "[email protected]");
+ await git("config", "user.name", "Tester");
+ await writeFile(join(root, "a.txt"), "one\n");
+ await git("add", "a.txt");
+ await git("commit", "-q", "-m", "feat: add a", "-m", "Thought: h111111111111");
+ const record = {
+ schema: 1,
+ sessionId: "s1",
+ agent: "claude-code",
+ title: "CLI session",
+ epoch: null,
+ startedAt: T0,
+ updatedAt: T0,
+ status: { goal: "", done: [], pending: [], next: "" },
+ nodes: [
+ {
+ id: "h111111111111",
+ parent: null,
+ kind: "message",
+ title: "Add a",
+ at: T0,
+ alternatives: [{ option: "Keep the loop", why: "It loses data." }],
+ },
+ ],
+ };
+ await writeFile(join(root, ".cogit", "sessions", "s1.json"), JSON.stringify(record));
+ await cli("why", "a.txt", "-C", root);
+ expect(io.lines.join("\n")).toContain("not: Keep the loop — It loses data.");
+ });
+
it("runs config hint-off and hint-on", async () => {
await cli("config", "hint-off", root);
expect(io.lines.at(-1)).toBe(`Setup hint off in ${root}`);
diff --git a/packages/cli/test/program.test.ts b/packages/cli/test/program.test.ts
index 9fa0df8..4f979e7 100644
--- a/packages/cli/test/program.test.ts
+++ b/packages/cli/test/program.test.ts
@@ -45,6 +45,7 @@ describe("createProgram", () => {
"init",
"build",
"blame",
+ "why",
"log",
"show",
"search",
diff --git a/packages/cli/test/server.test.ts b/packages/cli/test/server.test.ts
index 4673226..2629817 100644
--- a/packages/cli/test/server.test.ts
+++ b/packages/cli/test/server.test.ts
@@ -546,6 +546,7 @@ describe("settings read", () => {
settings: {
messageSummaries: false,
startupContext: true,
+ tryBeforeNotes: true,
language: "auto",
updateEveryTurns: 5,
sessionEndCatchUp: true,
diff --git a/packages/cli/test/settings.test.ts b/packages/cli/test/settings.test.ts
index 5ec2fe8..fecb514 100644
--- a/packages/cli/test/settings.test.ts
+++ b/packages/cli/test/settings.test.ts
@@ -19,6 +19,7 @@ describe("settings model", () => {
catchUpModel: parsed.catchUpModel,
messageSummaries: parsed.messageSummaries,
startupContext: parsed.startupContext,
+ tryBeforeNotes: parsed.tryBeforeNotes,
shareConversations: parsed.shareConversations,
recordCommit: parsed.recordCommit,
gitPolicy: parsed.gitPolicy,
@@ -63,6 +64,7 @@ describe("settings model", () => {
expect(editableSettings(settings)).toEqual({
messageSummaries: false,
startupContext: true,
+ tryBeforeNotes: true,
language: "tr",
updateEveryTurns: 8,
sessionEndCatchUp: true,
diff --git a/packages/cli/test/why.test.ts b/packages/cli/test/why.test.ts
new file mode 100644
index 0000000..6cbf23f
--- /dev/null
+++ b/packages/cli/test/why.test.ts
@@ -0,0 +1,318 @@
+import { execFile } from "node:child_process";
+import { mkdir, readFile, writeFile } from "node:fs/promises";
+import { join } from "node:path";
+import { promisify } from "node:util";
+import { beforeEach, describe, expect, it } from "vitest";
+import { configSet } from "../src/commands/config.js";
+import { init } from "../src/commands/init.js";
+import {
+ collectWhy,
+ formatWhy,
+ rejectedItems,
+ TRY_BEFORE_MAX_CHARS,
+ TRY_BEFORE_MAX_ITEMS,
+ tryBeforeNote,
+ type WhyHit,
+ why,
+} from "../src/commands/why.js";
+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";
+
+const run = promisify(execFile);
+
+const A = "h111111111111";
+const B = "h222222222222";
+
+function session(over: Partial<Session> = {}): Session {
+ return {
+ schema: 1,
+ sessionId: "s1",
+ agent: "claude-code",
+ title: "Ship the parser",
+ epoch: null,
+ startedAt: "2026-10-20T09:00:00.000Z",
+ updatedAt: "2026-10-20T10:00:00.000Z",
+ status: { goal: "", done: [], pending: [], next: "" },
+ nodes: [],
+ ...over,
+ };
+}
+
+function hit(over: Partial<WhyHit> = {}): WhyHit {
+ return {
+ sessionId: "s1",
+ sessionTitle: "Ship the parser",
+ messageId: A,
+ label: "m1",
+ at: "2026-10-20T09:00:00.000Z",
+ title: "Parse the file",
+ decisions: [
+ {
+ title: "Parse the file",
+ why: "",
+ alternatives: [{ option: "Keep the loop", why: "It loses data." }],
+ },
+ ],
+ ...over,
+ };
+}
+
+describe("cogit why", () => {
+ let dir: string;
+ let root: string;
+ let env: NodeJS.ProcessEnv;
+ let secondCommit: string;
+ const git = async (...args: string[]) => run("git", ["-C", root, ...args]);
+
+ const edit = (extra: Record<string, unknown> = {}) =>
+ runHook(
+ "pretooluse",
+ JSON.stringify({
+ session_id: "s1",
+ cwd: root,
+ tool_name: "Edit",
+ tool_input: { file_path: join(root, "a.txt") },
+ ...extra,
+ }),
+ env,
+ T0,
+ () => {},
+ );
+
+ beforeEach(async () => {
+ dir = await tempDir();
+ root = join(dir, "proj");
+ env = envFor(dir);
+ await mkdir(root);
+ await init(root, { name: "proj", retention: "keep", language: "auto" }, fakeIo(env));
+ await git("init", "-q");
+ await git("config", "user.email", "[email protected]");
+ await git("config", "user.name", "T");
+
+ await writeFile(join(root, "a.txt"), "one\n");
+ await git("add", "a.txt");
+ // The first commit names its message only through the trailer (Story 9.4).
+ await git("commit", "-q", "-m", "feat: add a", "-m", `Thought: ${A}`);
+
+ await writeFile(join(root, "a.txt"), "one\ntwo\n");
+ await git("add", "a.txt");
+ await git("commit", "-q", "-m", "feat: extend a", "-m", `Thought: ${B}`);
+ secondCommit = (await git("rev-parse", "--short", "HEAD")).stdout.trim();
+
+ const record = session({
+ nodes: [
+ {
+ id: A,
+ parent: null,
+ kind: "message",
+ title: "Parse the file",
+ at: "2026-10-20T09:00:00.000Z",
+ // No `commits`: only the trailer links this message to the commit.
+ why: "The old loop ate one line.",
+ alternatives: [{ option: "Keep the loop", why: "It loses data." }],
+ agentDecisions: [
+ {
+ title: "Kept the parser",
+ why: "It works.",
+ alternatives: [{ option: "Rewrite", why: "Too slow." }],
+ },
+ ],
+ },
+ {
+ id: B,
+ parent: A,
+ kind: "message",
+ title: "Extend the parser",
+ at: "2026-10-20T10:00:00.000Z",
+ commits: [secondCommit],
+ alternatives: [{ option: "Split the module", why: "Extra files." }],
+ },
+ ],
+ });
+ await writeFile(projectPaths(root).session("s1"), JSON.stringify(record));
+ });
+
+ it("follows a trailer-linked commit to its thought, newest first", async () => {
+ const hits = await collectWhy(root, "a.txt", env);
+ expect(hits.map((entry) => entry.messageId)).toEqual([B, A]);
+ const older = hits[1];
+ expect(older).toMatchObject({ label: "m1", title: "Parse the file" });
+ expect(older?.decisions.flatMap((decision) => decision.alternatives)).toEqual([
+ { option: "Keep the loop", why: "It loses data." },
+ { option: "Rewrite", why: "Too slow." },
+ ]);
+ expect(older?.decisions.map((decision) => decision.title)).toEqual([
+ "Parse the file",
+ "Kept the parser",
+ ]);
+ // Without an env the lookup still runs (git uses the process environment).
+ expect(await collectWhy(root, "a.txt")).toHaveLength(2);
+ });
+
+ it("prints each thought with its hash, label, date and rejected options", async () => {
+ const lines = formatWhy(await collectWhy(root, "a.txt", env));
+ expect(lines[0]).toContain("h2222222 m2");
+ expect(lines[0]).toContain("Extend the parser");
+ expect(lines.join("\n")).toContain("not: Split the module — Extra files.");
+ expect(lines.join("\n")).toContain("h1111111 m1");
+ expect(lines.join("\n")).toContain("not: Keep the loop — It loses data.");
+ expect(lines.join("\n")).toContain("decision: Parse the file — The old loop ate one line.");
+ expect(lines.join("\n")).toContain("decision: Kept the parser — It works.");
+ });
+
+ it("prints the lookup, or a plain line when nothing was recorded", async () => {
+ const io = fakeIo(env);
+ const hits = await why({ dir: root, file: "a.txt", io });
+ expect(hits).toHaveLength(2);
+ const text = io.lines.join("\n");
+ expect(text).toContain("h2222222 m2");
+ expect(text).toContain("not: Split the module — Extra files.");
+ expect(text).toContain(
+ "`cogit show <hash>` opens the thought; the record is the agent's summary.",
+ );
+
+ await writeFile(join(root, "loose.txt"), "x\n");
+ const none = fakeIo(env);
+ await why({ dir: root, file: "loose.txt", io: none });
+ expect(none.lines).toEqual(["No decisions or rejected alternatives recorded for loose.txt."]);
+ });
+
+ it("refuses an uninitialized project, a non-repository and a missing file", async () => {
+ const bare = join(dir, "bare");
+ await mkdir(bare);
+ await expect(why({ dir: bare, file: "a.txt", io: fakeIo(env) })).rejects.toThrow(
+ /not initialized/,
+ );
+
+ const plain = join(dir, "plain");
+ await mkdir(plain);
+ await init(plain, { name: "plain", retention: "keep", language: "auto" }, fakeIo(env));
+ await expect(why({ dir: plain, file: "a.txt", io: fakeIo(env) })).rejects.toThrow(
+ /not inside a git repository/,
+ );
+ await expect(why({ dir: root, file: "missing.txt", io: fakeIo(env) })).rejects.toThrow(
+ /does not exist/,
+ );
+ });
+
+ it("treats a repository with no commits as nothing known", async () => {
+ const empty = join(dir, "empty");
+ await mkdir(empty);
+ await init(empty, { name: "empty", retention: "keep", language: "auto" }, fakeIo(env));
+ await run("git", ["-C", empty, "init", "-q"]);
+ await writeFile(join(empty, "a.txt"), "x\n");
+ expect(await collectWhy(empty, "a.txt", env)).toEqual([]);
+ });
+
+ it("says plainly when the thoughts recorded no decisions", async () => {
+ const record = session({
+ nodes: [
+ {
+ id: A,
+ parent: null,
+ kind: "message",
+ title: "Parse the file",
+ at: "2026-10-20T09:00:00.000Z",
+ },
+ ],
+ });
+ await writeFile(projectPaths(root).session("s1"), JSON.stringify(record));
+ expect(await collectWhy(root, "a.txt", env)).toEqual([]);
+ expect(tryBeforeNote("a.txt", [])).toBeUndefined();
+ });
+
+ it("ignores a file no thought links to a commit", async () => {
+ await writeFile(join(root, "other.txt"), "x\n");
+ await git("add", "other.txt");
+ await git("commit", "-q", "-m", "chore: other");
+ expect(await collectWhy(root, "other.txt", env)).toEqual([]);
+ // Outside the project, or a file that never existed.
+ expect(await collectWhy(root, "../outside.txt", env)).toEqual([]);
+ expect(await collectWhy(root, "missing.txt", env)).toEqual([]);
+ });
+
+ it("writes one note per file per session and then stays quiet", async () => {
+ const first = await edit();
+ expect(first).toBeDefined();
+ const text = (JSON.parse(first ?? "") as { hookSpecificOutput: { additionalContext: string } })
+ .hookSpecificOutput.additionalContext;
+ expect(text).toContain("Earlier, for this file:");
+ expect(text).toContain('"Keep the loop" was considered and rejected (h1111111,');
+ expect(text).toContain("It loses data.");
+ expect(text).toContain("Decide knowingly.");
+ // A second edit of the same file in the same session: no second note.
+ expect(await edit()).toBeUndefined();
+ expect(JSON.parse(await readFile(projectPaths(root).state("s1"), "utf8"))).toMatchObject({
+ notedFiles: ["a.txt"],
+ });
+ });
+
+ it("does not note a file with nothing to say, and remembers the lookup", async () => {
+ await writeFile(join(root, "other.txt"), "x\n");
+ await git("add", "other.txt");
+ await git("commit", "-q", "-m", "chore: other");
+ expect(await edit({ tool_input: { file_path: join(root, "other.txt") } })).toBeUndefined();
+ expect(JSON.parse(await readFile(projectPaths(root).state("s1"), "utf8"))).toMatchObject({
+ notedFiles: ["other.txt"],
+ });
+ });
+
+ it("stays quiet when the setting is off, for other tools, and outside the project", async () => {
+ await configSet("tryBeforeNotes", "false", fakeIo(env));
+ expect(await edit()).toBeUndefined();
+ await configSet("tryBeforeNotes", "true", fakeIo(env));
+ expect(await edit({ tool_name: "Bash", tool_input: { command: "ls" } })).toBeUndefined();
+ expect(await edit({ tool_input: { file_path: join(dir, "outside.txt") } })).toBeUndefined();
+ // Nothing was claimed by the skipped calls.
+ expect(await edit()).toBeDefined();
+ });
+
+ it("keeps the note within five items and 600 characters", () => {
+ const many: WhyHit[] = Array.from({ length: 9 }, (_, index) =>
+ hit({
+ messageId: `h${String(index + 1).repeat(12)}`,
+ decisions: [
+ {
+ title: "d",
+ why: "",
+ alternatives: [{ option: `Option ${index}`, why: "it did not fit" }],
+ },
+ ],
+ }),
+ );
+ const note = tryBeforeNote("a.txt", many);
+ expect(note).toBeDefined();
+ expect(note?.length).toBeLessThanOrEqual(TRY_BEFORE_MAX_CHARS);
+ expect(note?.split("\n").filter((line) => line.startsWith("- "))).toHaveLength(
+ TRY_BEFORE_MAX_ITEMS,
+ );
+ expect(note).toContain("`cogit why a.txt` for more.");
+
+ const oneLong = tryBeforeNote("a.txt", [
+ hit({
+ decisions: [
+ {
+ title: "d",
+ why: "",
+ alternatives: [{ option: "A very long option", why: "y".repeat(500) }],
+ },
+ ],
+ }),
+ ]);
+ expect(oneLong).toBeDefined();
+ expect(oneLong?.length).toBeLessThanOrEqual(TRY_BEFORE_MAX_CHARS);
+ expect(oneLong).toContain("Decide knowingly.");
+ });
+
+ it("counts every rejected option once", () => {
+ expect(rejectedItems([hit(), hit()])).toHaveLength(2);
+ });
+
+ it("never throws when the hook's state cannot be written", async () => {
+ // A regular file where the state directory belongs makes the state write fail.
+ await writeFile(join(projectPaths(root).base, "state"), "not a directory");
+ await expect(edit()).resolves.toBeUndefined();
+ });
+});
diff --git a/packages/template/src/fixture.ts b/packages/template/src/fixture.ts
index a2382a3..1285f08 100644
--- a/packages/template/src/fixture.ts
+++ b/packages/template/src/fixture.ts
@@ -58,6 +58,7 @@ export const fixture: LineageViewModel = {
catchUpModel: "haiku",
messageSummaries: false,
startupContext: true,
+ tryBeforeNotes: true,
shareConversations: false,
recordCommit: "ask",
gitPolicy: "ignore",