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(pr): describe a branch from the thoughts behind it
Eren0b0faab7a248
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a276fb6..d85cdfb 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,9 @@ 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]+### Added+- `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.+### Changed- The panel uses the map's centred 8-of-12 column, and every page names the product: "cogit" with its slogan "Cogito, ergo commit." opens the top bar, and on a served map it leads back to the panel.- A calmer map head: the top bar holds only "cogit", the search and Settings; the project switcher (recent projects and Ctrl/Cmd+K, its button now "Switch project") sits under the project's name and path. On the panel a click anywhere on a project's card opens its map.diff --git a/packages/cli/skills/record/SKILL.md b/packages/cli/skills/record/SKILL.mdindex a5585a1..7860ce4 100644--- a/packages/cli/skills/record/SKILL.md+++ b/packages/cli/skills/record/SKILL.md@@ -23,6 +23,13 @@ A word rather than a hash: `node "${CLAUDE_PLUGIN_ROOT}/dist/cli.js" search "<tescans titles, branch summaries, decisions and stored conversations, newest first (`--json`,`-n`, `--session`); hashes go to `show`.+## A pull request description++When the user asks for a PR description, run+`node "${CLAUDE_PLUGIN_ROOT}/dist/cli.js" pr -C "${CLAUDE_PROJECT_DIR}"` and hand its output+over as it is; do not write one yourself. Only when the user uses `gh`, follow it with+`gh pr create --body "$(node "${CLAUDE_PLUGIN_ROOT}/dist/cli.js" pr -C "${CLAUDE_PROJECT_DIR}")"`.+## Send only what is new or changedOne JSON object:diff --git a/packages/cli/src/commands/pr.ts b/packages/cli/src/commands/pr.tsnew file mode 100644index 0000000..1e0e677--- /dev/null+++ b/packages/cli/src/commands/pr.ts@@ -0,0 +1,573 @@+import { execFile, spawn } from "node:child_process";+import { promisify } from "node:util";+import { cogitIgnored, findGitRoot, readCommitFiles } from "../git.js";+import { CliError, type Io } from "../io.js";+import { earliestSessionStart, readThoughtTrailers } from "../thought.js";+import type { ViewNode } from "../view/model.js";+import {+ type EffectiveSession,+ loadEffectiveSessions,+ openProject,+ shortHash,+ stamp,+} from "./log.js";++const exec = promisify(execFile);++/**+ * `cogit pr` (Story 10.1): a review-ready description of a branch, built from+ * the thoughts the `Thought:` trailers point at. A reviewer sees the goal, the+ * decisions and the rejected options instead of asking for them in comments.+ * Only the record's own fields are read — never the conversation text or the+ * user's raw prompt, because the PR may be public.+ */++/** GitHub's body limit is 65 536 characters; leave a little room. */+export const PR_CHAR_CAP = 60_000;++export interface PrBase {+ /** The ref the user asked for, or `@{upstream}` / `main` / `master`. */+ ref: string;+ /** The full hash of the merge base `base..HEAD` starts from. */+ commit: string;+}++/** One commit of the branch, with the record's thought and the files it changed. */+export interface PrCommit {+ full: string;+ short: string;+ at: string;+ subject: string;+ /** The `Thought:` trailer value, when the commit carries one. */+ thought?: string;+ /** Repository-relative paths; empty when git no longer has the commit. */+ files: string[];+}++/** A commit no recorded thought explains. */+export interface PrUnlinkedCommit {+ full: string;+ short: string;+ subject: string;+ /** Set when the trailer names a thought the record does not hold yet. */+ thought?: string;+}++export interface PrGoal {+ text: string;+ sessionId: string;+ sessionTitle: string;+}++/** One session the branch's thoughts come from, with the label range it covers. */+export interface PrSessionLine {+ sessionId: string;+ shortId: string;+ title: string;+ startedAt: string;+ updatedAt: string;+ /** Message labels of the thoughts from this session in the branch. */+ from: string;+ to: string;+ thoughtCount: number;+ commitCount: number;+}++/** One thought with everything the description says about it. */+export interface PrThought {+ id: string;+ shortId: string;+ label: string;+ sessionId: string;+ shortSessionId: string;+ sessionTitle: string;+ title: string;+ summary?: string;+ why?: string;+ decidedBy?: "user" | "agent" | "agreed";+ alternatives: { option: string; why: string }[];+ agentDecisions: {+ title: string;+ why: string;+ alternatives: { option: string; why: string }[];+ }[];+ commits: PrCommit[];+}++export interface PrModel {+ base: PrBase;+ head: string;+ /** What the project does with its record: it travels, or it stays local. */+ policy: "commit" | "ignore";+ goals: PrGoal[];+ sessions: PrSessionLine[];+ thoughts: PrThought[];+ unlinked: PrUnlinkedCommit[];+}++/** `git log` for a branch, oldest first: `%H%x00%h%x00%cI%x00%s` per line. */+export function parsePrCommits(stdout: string): Omit<PrCommit, "files" | "thought">[] {+ const out: Omit<PrCommit, "files" | "thought">[] = [];+ for (const line of stdout.split("\n")) {+ const [full, short, at, subject] = line.split("\0");+ if (full === undefined || !/^[0-9a-f]{40}$/.test(full)) continue;+ if (short === undefined || short === "") continue;+ out.push({ full, short, at: at ?? "", subject: subject ?? "" });+ }+ return out;+}++/** Git with `-C`, or undefined when the command fails (an unknown ref, no git). */+async function git(+ root: string,+ args: string[],+ env: NodeJS.ProcessEnv,+): Promise<string | undefined> {+ try {+ const { stdout } = await exec("git", ["-C", root, ...args], { env });+ return String(stdout).trim();+ } catch {+ return undefined;+ }+}++/** The full hash a ref names, or undefined when it does not resolve. */+async function revParse(+ root: string,+ ref: string,+ env: NodeJS.ProcessEnv,+): Promise<string | undefined> {+ const out = await git(root, ["rev-parse", "--verify", "--quiet", `${ref}^{commit}`], env);+ return out !== undefined && /^[0-9a-f]{40}$/.test(out) ? out : undefined;+}++/**+ * The base of the review (Story 10.1): the upstream's merge base, else `main`,+ * else `master`; an explicit base wins. A branch with none of these is a user+ * error naming the command that fixes it.+ */+export async function resolvePrBase(+ root: string,+ requested: string | undefined,+ env: NodeJS.ProcessEnv,+): Promise<PrBase> {+ if (requested !== undefined) {+ const commit = await revParse(root, requested, env);+ if (commit === undefined) throw new CliError(`unknown base "${requested}"`);+ return { ref: requested, commit };+ }+ const upstream = await revParse(root, "@{upstream}", env);+ if (upstream !== undefined) {+ const mergeBase = await git(root, ["merge-base", "HEAD", upstream], env);+ if (mergeBase !== undefined && /^[0-9a-f]{40}$/.test(mergeBase))+ return { ref: "@{upstream}", commit: mergeBase };+ }+ for (const branch of ["main", "master"]) {+ const commit = await revParse(root, `refs/heads/${branch}`, env);+ if (commit !== undefined) return { ref: branch, commit };+ }+ throw new CliError(+ "cannot find a base: no upstream and neither main nor master; pass one, e.g. `cogit pr main`",+ );+}++/** The commits of `base..HEAD`, oldest first — the order a reviewer reads them. */+async function readPrCommits(+ root: string,+ base: string,+ head: string,+ env: NodeJS.ProcessEnv,+): Promise<Omit<PrCommit, "files" | "thought">[]> {+ const stdout = await git(+ root,+ ["log", "--reverse", "--format=%H%x00%h%x00%cI%x00%s", `${base}..${head}`],+ env,+ );+ return parsePrCommits(stdout ?? "");+}++function oneLine(text: string): string {+ return text.replace(/\s+/g, " ").trim();+}++function titleOf(sessionId: string, title: string): string {+ return title.trim() === "" ? sessionId : oneLine(title);+}++function labelIndex(label: string): number | undefined {+ const match = /^m([1-9][0-9]*)$/.exec(label);+ return match === null ? undefined : Number(match[1]);+}++export interface BuildPrInput {+ base: PrBase;+ head: string;+ commits: readonly PrCommit[];+ sessions: readonly EffectiveSession[];+ policy: "commit" | "ignore";+}++/**+ * Groups the branch's commits by the thought their trailer names, in commit+ * order (Story 10.1). A commit without a trailer, or whose thought the record+ * does not hold yet, goes to `unlinked` with the trailer value for the reader.+ */+export function buildPrModel(input: BuildPrInput): PrModel {+ const index = new Map<string, { entry: EffectiveSession; message: ViewNode }>();+ for (const entry of input.sessions)+ for (const message of entry.messages)+ if (!index.has(message.id)) index.set(message.id, { entry, message });++ const thoughts = new Map<string, PrThought>();+ const unlinked: PrUnlinkedCommit[] = [];+ const sessionOrder: string[] = [];+ const entries = new Map<string, EffectiveSession>();+ const labels = new Map<string, number[]>();+ const thoughtCounts = new Map<string, number>();+ const commitCounts = new Map<string, number>();++ for (const commit of input.commits) {+ const id = commit.thought;+ const hit = id === undefined ? undefined : index.get(id);+ if (id === undefined || hit === undefined) {+ unlinked.push({+ full: commit.full,+ short: commit.short,+ subject: commit.subject,+ ...(id === undefined ? {} : { thought: id }),+ });+ continue;+ }+ const { session } = hit.entry;+ let thought = thoughts.get(id);+ if (thought === undefined) {+ const message = hit.message;+ thought = {+ id,+ shortId: shortHash(id),+ label: message.label ?? id,+ sessionId: session.sessionId,+ shortSessionId: session.sessionId.slice(0, 8),+ sessionTitle: titleOf(session.sessionId, session.title),+ title: message.title,+ ...(message.summary === undefined ? {} : { summary: message.summary }),+ ...(message.why === undefined ? {} : { why: message.why }),+ ...(message.decidedBy === undefined ? {} : { decidedBy: message.decidedBy }),+ alternatives: message.alternatives ?? [],+ agentDecisions: (message.agentDecisions ?? []).map((decision) => ({+ title: decision.title,+ why: decision.why,+ alternatives: decision.alternatives ?? [],+ })),+ commits: [],+ };+ thoughts.set(id, thought);+ if (!entries.has(session.sessionId)) {+ sessionOrder.push(session.sessionId);+ entries.set(session.sessionId, hit.entry);+ labels.set(session.sessionId, []);+ thoughtCounts.set(session.sessionId, 0);+ commitCounts.set(session.sessionId, 0);+ }+ thoughtCounts.set(session.sessionId, (thoughtCounts.get(session.sessionId) ?? 0) + 1);+ }+ thought.commits.push(commit);+ labels.get(session.sessionId)?.push(labelIndex(thought.label) ?? 0);+ commitCounts.set(session.sessionId, (commitCounts.get(session.sessionId) ?? 0) + 1);+ }++ const goals: PrGoal[] = [];+ const seenGoals = new Set<string>();+ const sessions: PrSessionLine[] = [];+ for (const sessionId of sessionOrder) {+ const entry = entries.get(sessionId);+ if (entry === undefined) continue;+ const session = entry.session;+ const title = titleOf(sessionId, session.title);+ const goal = oneLine(session.status.goal);+ if (goal !== "" && !seenGoals.has(goal)) {+ seenGoals.add(goal);+ goals.push({ text: goal, sessionId, sessionTitle: title });+ }+ const numbers = labels.get(sessionId) ?? [];+ sessions.push({+ sessionId,+ shortId: sessionId.slice(0, 8),+ title,+ startedAt: session.startedAt,+ updatedAt: session.updatedAt,+ from: numbers.length === 0 ? "—" : `m${Math.min(...numbers)}`,+ to: numbers.length === 0 ? "—" : `m${Math.max(...numbers)}`,+ thoughtCount: thoughtCounts.get(sessionId) ?? 0,+ commitCount: commitCounts.get(sessionId) ?? 0,+ });+ }++ return {+ base: input.base,+ head: input.head,+ policy: input.policy,+ goals,+ sessions,+ thoughts: [...thoughts.values()],+ unlinked,+ };+}++export interface PrFormatOptions {+ includeFiles: boolean;+ includeSummaries: boolean;+ /** What the size cap dropped, said at the end of the description. */+ dropped?: ("files" | "summaries")[];+}++function alternativeLine(alt: { option: string; why: string }, indent = ""): string {+ const why = alt.why.trim() === "" ? "" : ` — ${oneLine(alt.why)}`;+ return `${indent}- considered and rejected: ${oneLine(alt.option)}${why}`;+}++function decisionLines(thought: PrThought): string[] {+ const lines: string[] = [];+ if (thought.why !== undefined && thought.why.trim() !== "")+ lines.push(`- Why: ${oneLine(thought.why)}`);+ if (thought.decidedBy !== undefined) lines.push(`- Decided by: ${thought.decidedBy}`);+ for (const alt of thought.alternatives) lines.push(alternativeLine(alt));+ for (const decision of thought.agentDecisions) {+ const why = decision.why.trim() === "" ? "" : ` — ${oneLine(decision.why)}`;+ lines.push(`- agent decision: ${oneLine(decision.title)}${why}`);+ for (const alt of decision.alternatives) lines.push(alternativeLine(alt, " "));+ }+ return lines;+}++/** The Markdown body of the PR, in the order Story 10.1 fixes. */+export function formatPr(model: PrModel, opts: PrFormatOptions): string {+ const lines: string[] = ["## Goal"];+ if (model.goals.length === 0) {+ lines.push("_No session goal was recorded._");+ } else {+ for (const goal of model.goals)+ lines.push(`- ${oneLine(goal.text)} — ${goal.sessionTitle} (${goal.sessionId.slice(0, 8)})`);+ }++ lines.push("", "## Sessions");+ if (model.sessions.length === 0) {+ lines.push("_No recorded session is behind these commits._");+ } else {+ lines.push("Open a whole session with `cogit log --session <id>` or the map.");+ for (const session of model.sessions) {+ const range = session.from === session.to ? session.from : `${session.from}–${session.to}`;+ lines.push(+ `- ${session.title} (${session.shortId}) · ${range} · ` ++ `${stamp(session.startedAt)} → ${stamp(session.updatedAt)}`,+ );+ }+ }++ lines.push("", "## Thoughts");+ if (model.thoughts.length === 0) {+ lines.push("_No recorded thought is behind these commits._");+ } else {+ for (const thought of model.thoughts) {+ lines.push(+ "",+ `### \`${thought.shortId}\` ${thought.shortSessionId}:${thought.label} — ` ++ `${oneLine(thought.title)}`,+ );+ if (opts.includeSummaries && thought.summary !== undefined && thought.summary.trim() !== "")+ lines.push("", oneLine(thought.summary));+ const decisions = decisionLines(thought);+ if (decisions.length > 0) lines.push("", ...decisions);+ lines.push("", "Commits:");+ for (const commit of thought.commits) {+ lines.push(`- \`${commit.short}\` ${oneLine(commit.subject)}`);+ if (opts.includeFiles) for (const file of commit.files) lines.push(` - \`${file}\``);+ }+ }+ }++ lines.push("", "## Commits without a recorded thought");+ if (model.unlinked.length === 0) {+ lines.push("_None: every commit carries a recorded thought._");+ } else {+ for (const commit of model.unlinked) {+ const thought =+ commit.thought === undefined ? "" : ` — thought \`${commit.thought}\` not recorded yet`;+ lines.push(`- \`${commit.short}\` ${oneLine(commit.subject)}${thought}`);+ }+ }++ lines.push("", "## Dig deeper");+ lines.push(+ "- `cogit show <message-hash>` opens a thought: its decisions, the options it rejected, " ++ "and the conversation turn for whoever has it locally.",+ "- `cogit show <sha>` opens the thought behind a commit.",+ model.policy === "ignore"+ ? "- This project keeps its record out of git, so these hashes resolve only on the " ++ "author's machine; ask the author to run `cogit show`."+ : "- This branch commits its record, so a reviewer who checks it out gets the same " ++ "`cogit show` output.",+ );++ const dropped = opts.dropped ?? [];+ if (dropped.length > 0) {+ const names = dropped.map((item) => (item === "files" ? "file lists" : "summaries"));+ const text = names.length === 1 ? names[0] : `${names[0]} and ${names[1]}`;+ lines.push("", `_Left out to stay under the size cap: ${text}._`);+ }+ return lines.join("\n");+}++export interface PrRendered {+ text: string;+ dropped: ("files" | "summaries")[];+ truncated: boolean;+}++/**+ * Fits the description under the cap by dropping the file lists first, then the+ * summaries (Story 10.1), and says what was left out. A description still over+ * the cap after both is cut, so GitHub never refuses the body.+ */+export function renderPr(model: PrModel, cap = PR_CHAR_CAP): PrRendered {+ const levels: {+ includeFiles: boolean;+ includeSummaries: boolean;+ dropped: ("files" | "summaries")[];+ }[] = [+ { includeFiles: true, includeSummaries: true, dropped: [] },+ { includeFiles: false, includeSummaries: true, dropped: ["files"] },+ { includeFiles: false, includeSummaries: false, dropped: ["files", "summaries"] },+ ];+ for (const level of levels) {+ const text = formatPr(model, level);+ if (text.length <= cap) return { text, dropped: level.dropped, truncated: false };+ }+ const full = formatPr(model, levels[2] as (typeof levels)[number]);+ const note =+ "\n\n_Truncated to fit the size cap; file lists and summaries were left out. " ++ "Open a thought with `cogit show` for the rest._";+ if (note.length >= cap)+ return { text: note.slice(0, cap), dropped: ["files", "summaries"], truncated: true };+ return {+ text: full.slice(0, cap - note.length) + note,+ dropped: ["files", "summaries"],+ truncated: true,+ };+}++const CLIPBOARD_TOOLS: [string, string[]][] = [+ ["wl-copy", []],+ ["xclip", ["-selection", "clipboard"]],+ ["pbcopy", []],+ ["clip", []],+];++/** Pipes text into a process, resolving false when it is missing or fails. */+function pipe(+ command: string,+ args: string[],+ text: string,+ env: NodeJS.ProcessEnv,+): Promise<boolean> {+ return new Promise((resolve) => {+ let settled = false;+ const done = (ok: boolean): void => {+ if (settled) return;+ settled = true;+ resolve(ok);+ };+ const child = spawn(command, args, { env, stdio: ["pipe", "ignore", "ignore"] });+ child.on("error", () => done(false));+ child.on("close", (code) => done(code === 0));+ child.stdin.on("error", () => done(false));+ child.stdin.end(text);+ });+}++/** Copies with the first clipboard tool that exists; false when there is none. */+export async function copyToClipboard(+ text: string,+ env: NodeJS.ProcessEnv = process.env,+): Promise<boolean> {+ for (const [command, args] of CLIPBOARD_TOOLS) {+ if (await pipe(command, args, text, env)) return true;+ }+ return false;+}++export interface PrOptions {+ dir: string;+ /** Base ref; default: the upstream's merge base, else main, else master. */+ base?: string | undefined;+ io: Io;+ json?: boolean;+ copy?: boolean;+ /** Size cap for tests; defaults to `PR_CHAR_CAP`. */+ cap?: number;+}++/** `cogit pr [base]`: reads the record and the branch, prints the description. */+export async function pr(opts: PrOptions): Promise<PrModel> {+ const root = await openProject(opts.dir);+ const gitRoot = await findGitRoot(root);+ if (gitRoot === undefined) throw new CliError("not in a git repository");+ const env = opts.io.env;++ const head = await revParse(gitRoot, "HEAD", env);+ if (head === undefined) throw new CliError("HEAD has no commits yet");+ const base = await resolvePrBase(gitRoot, opts.base, env);+ const commits = await readPrCommits(gitRoot, base.commit, head, env);+ const sessions = await loadEffectiveSessions(root, opts.io);+ const trailers =+ commits.length === 0+ ? new Map<string, string>()+ : await readThoughtTrailers(gitRoot, {+ env,+ since: earliestSessionStart(sessions.map((entry) => entry.session)),+ });+ const files =+ commits.length === 0+ ? new Map<string, string[]>()+ : await readCommitFiles(+ gitRoot,+ commits.map((commit) => commit.full),+ );++ const model = buildPrModel({+ base,+ head,+ policy: (await cogitIgnored(root)) ? "ignore" : "commit",+ sessions,+ commits: commits.map((commit) => {+ const thought = trailers.get(commit.full);+ return {+ ...commit,+ files: files.get(commit.full) ?? [],+ ...(thought === undefined ? {} : { thought }),+ };+ }),+ });++ const rendered = renderPr(model, opts.cap ?? PR_CHAR_CAP);+ if (opts.copy === true && !(await copyToClipboard(rendered.text, env))) {+ opts.io.warn(+ "could not copy: no clipboard tool found (wl-copy, xclip, pbcopy or clip); the Markdown is on stdout",+ );+ }+ if (opts.json === true) {+ opts.io.out(+ JSON.stringify(+ {+ ...model,+ rendered: { dropped: rendered.dropped, truncated: rendered.truncated },+ },+ null,+ 2,+ ),+ );+ return model;+ }+ for (const line of rendered.text.split("\n")) opts.io.out(line);+ return model;+}diff --git a/packages/cli/src/program.ts b/packages/cli/src/program.tsindex 1937d22..eb34e82 100644--- a/packages/cli/src/program.ts+++ b/packages/cli/src/program.ts@@ -17,6 +17,7 @@ import { type InitOptions, init } from "./commands/init.js";import { formatShow, log, logFile, show } from "./commands/log.js";import { migrateIds } from "./commands/migrate.js";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 { isGitHookEvent, runGitHook } from "./git-hooks.js";@@ -212,6 +213,36 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =),);+ program+ .command("pr")+ .description("print a review-ready description of a branch from the thoughts behind it")+ .argument("[base]", "base ref; default: the upstream's merge base, else main, else master")+ .option("-C, --dir <dir>", "project directory", ".")+ .option("--json", "print JSON instead of Markdown")+ .option("--copy", "also copy the Markdown to the clipboard")+ .addHelpText(+ "after",+ "\nExamples:\n" ++ " $ cogit pr\n" ++ " $ cogit pr main --copy\n" ++ " $ cogit pr origin/main --json\n\n" ++ "Prints only the record's titles, summaries and decisions — never the conversation\n" ++ "text or your raw prompts, because the PR may be public.\n",+ )+ .action(+ run(+ async (base: string | undefined, opts: { dir: string; json?: boolean; copy?: boolean }) => {+ await pr({+ dir: opts.dir,+ base,+ io: makeIo(false),+ json: opts.json === true,+ copy: opts.copy === true,+ });+ },+ ),+ );+program.command("open").description("build and open a project map, or the global panel without a directory")diff --git a/packages/cli/test/pr.test.ts b/packages/cli/test/pr.test.tsnew file mode 100644index 0000000..f430dfa--- /dev/null+++ b/packages/cli/test/pr.test.ts@@ -0,0 +1,422 @@+import { execFile } from "node:child_process";+import { access, chmod, mkdir, readFile, symlink, writeFile } from "node:fs/promises";+import { dirname, join } from "node:path";+import { promisify } from "node:util";+import { beforeEach, describe, expect, it } from "vitest";+import { init } from "../src/commands/init.js";+import { shortHash } from "../src/commands/log.js";+import {+ copyToClipboard,+ formatPr,+ type PrModel,+ parsePrCommits,+ pr,+ renderPr,+ resolvePrBase,+} from "../src/commands/pr.js";+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";++const run = promisify(execFile);++/** The thought behind the parser work, and another one of the same session. */+const A = "h111111111111";+const D = "h444444444444";+/** A trailer value the record does not hold. */+const C = "h333333333333";+const SECRET = "the user's private words that must never reach a public PR";++function 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: "Ship the parser without losing data",+ done: [],+ pending: [],+ next: "",+ },+ nodes: [+ {+ id: A,+ parent: null,+ kind: "message",+ title: "Start the parser",+ summary: "Shipped the parser.",+ at: "2026-10-20T09:00:00.000Z",+ decidedBy: "user",+ 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: D,+ parent: A,+ kind: "message",+ title: "Share the token",+ at: "2026-10-20T10:00:00.000Z",+ },+ ],+ };+}++async function findExecutable(name: string): Promise<string> {+ for (const dir of (process.env.PATH ?? "").split(":")) {+ const path = join(dir, name);+ if (+ await access(path).then(+ () => true,+ () => false,+ )+ )+ return path;+ }+ throw new Error(`no ${name} on PATH`);+}++describe("cogit pr (Story 10.1)", () => {+ let dir: string;+ let root: string;+ let env: NodeJS.ProcessEnv;+ let io: FakeIo;+ let commitHashes: string[];++ const git = async (...args: string[]): Promise<string> =>+ (await run("git", ["-C", root, ...args], { env })).stdout.trim();++ const commit = async (+ files: Record<string, string>,+ subject: string,+ thought?: string,+ ): Promise<void> => {+ for (const [name, content] of Object.entries(files)) {+ await mkdir(dirname(join(root, name)), { recursive: true });+ await writeFile(join(root, name), content);+ }+ await git("add", ...Object.keys(files));+ const args = ["commit", "-q", "-m", subject];+ if (thought !== undefined) args.push("-m", `Thought: ${thought}`);+ await git(...args);+ commitHashes.push(await git("rev-parse", "HEAD"));+ };++ beforeEach(async () => {+ dir = await tempDir();+ root = join(dir, "proj");+ await mkdir(root);+ env = {+ ...envFor(dir),+ HOME: dir,+ GIT_CONFIG_NOSYSTEM: "1",+ PATH: process.env.PATH ?? "/usr/bin:/bin",+ };+ io = fakeIo(env);+ commitHashes = [];++ await run("git", ["-C", root, "init", "-q", "-b", "master"], { env });+ await git("config", "user.email", "[email protected]");+ await git("config", "user.name", "Tester");+ await writeFile(join(root, "base.txt"), "base\n");+ await git("add", "base.txt");+ await git("commit", "-q", "-m", "base");+ // A PR branch: main stays at the base commit while the work lands on master.+ await git("branch", "main");+ await init(+ root,+ { name: "proj", git: "commit", retention: "keep", language: "auto" },+ fakeIo(env),+ );+ await writeFile(projectPaths(root).session("s1"), JSON.stringify(session()));+ // The stored conversation is readable but its text must never reach the PR.+ await appendConversationTurns(root, "s1", [+ {+ id: "m1",+ uuid: "u1",+ hash: A,+ at: "2026-10-20T09:00:00.000Z",+ text: SECRET,+ replies: [],+ tools: { commands: 0, files: [], other: 0 },+ },+ ]);++ await commit({ "src/one.ts": "one\n" }, "feat(parser): read the first token", A);+ await commit({ "src/two.ts": "two\n" }, "refactor(parser): share the token", D);+ await commit({ "src/three.ts": "three\n" }, "fix(parser): stop the loop eating a line", A);+ await commit({ "docs.md": "docs\n" }, "docs: describe the parser", C);+ await commit({ "notes.txt": "notes\n" }, "chore: tidy notes");+ });++ it("groups the branch's commits by thought, in commit order", async () => {+ const model = await pr({ dir: root, io });+ expect(model.base.ref).toBe("main");+ expect(model.thoughts.map((thought) => thought.id)).toEqual([A, D]);+ expect(model.thoughts[0]?.commits.map((entry) => entry.subject)).toEqual([+ "feat(parser): read the first token",+ "fix(parser): stop the loop eating a line",+ ]);+ expect(model.thoughts[1]?.commits.map((entry) => entry.subject)).toEqual([+ "refactor(parser): share the token",+ ]);+ expect(model.thoughts[0]?.commits[1]?.files).toEqual(["src/three.ts"]);+ expect(model.unlinked.map((entry) => entry.subject)).toEqual([+ "docs: describe the parser",+ "chore: tidy notes",+ ]);+ expect(model.unlinked[0]?.thought).toBe(C);+ expect(model.unlinked[1]?.thought).toBeUndefined();+ expect(model.sessions[0]).toMatchObject({+ from: "m1",+ to: "m2",+ thoughtCount: 2,+ commitCount: 3,+ });++ const text = io.lines.join("\n");+ expect(text).toContain("## Goal");+ expect(text).toContain("- Ship the parser without losing data — Ship the parser (s1)");+ expect(text).toContain("## Sessions");+ expect(text).toContain("· m1–m2 ·");+ expect(text).toContain("`cogit log --session <id>`");+ expect(text).toContain(`### \`${shortHash(A)}\` s1:m1 — Start the parser`);+ expect(text).toContain("Shipped the parser.");+ expect(text).toContain("- Why: The old loop ate one line.");+ expect(text).toContain("- Decided by: user");+ expect(text).toContain("- considered and rejected: Keep the loop — It loses data.");+ expect(text).toContain("- agent decision: Kept the parser — It works.");+ expect(text).toContain(" - considered and rejected: Rewrite — Too slow.");+ expect(text).toContain("- `src/three.ts`");+ expect(text).toContain(+ `- \`${commitHashes[3]?.slice(0, 7)}\` docs: describe the parser — thought \`${C}\` not recorded yet`,+ );+ expect(text).toContain("## Dig deeper");+ expect(text).toContain("a reviewer who checks it out");+ expect(text).not.toContain(SECRET);+ expect(text).not.toContain("Conversation:");+ });++ it("prints the same content as JSON for other tools", async () => {+ const model = await pr({ dir: root, io, json: true });+ expect(model.thoughts[0]?.id).toBe(A);+ const data = JSON.parse(io.lines.at(-1) ?? "");+ expect(data.base.ref).toBe("main");+ expect(data.thoughts[0]).toMatchObject({+ id: A,+ shortId: shortHash(A),+ label: "m1",+ sessionId: "s1",+ });+ expect(data.thoughts[0].commits[1].files).toEqual(["src/three.ts"]);+ expect(data.unlinked[0].thought).toBe(C);+ expect(data.rendered).toEqual({ dropped: [], truncated: false });+ expect(io.lines.join("\n")).not.toContain(SECRET);+ });++ it("resolves the upstream's merge base before main", async () => {+ const base = await git("rev-parse", "HEAD~5");+ await git("branch", "--set-upstream-to=main");+ const resolved = await resolvePrBase(root, undefined, env);+ expect(resolved).toEqual({ ref: "@{upstream}", commit: base });+ const model = await pr({ dir: root, io });+ expect(model.base.ref).toBe("@{upstream}");+ expect(model.thoughts).toHaveLength(2);+ });++ it("falls back to main, takes an explicit base, and reports an unknown one", async () => {+ expect((await resolvePrBase(root, undefined, env)).ref).toBe("main");+ const explicit = await pr({ dir: root, base: "HEAD~2", io });+ expect(explicit.base.ref).toBe("HEAD~2");+ expect(explicit.unlinked.map((entry) => entry.subject)).toEqual([+ "docs: describe the parser",+ "chore: tidy notes",+ ]);+ await expect(pr({ dir: root, base: "nope", io })).rejects.toThrow(/unknown base "nope"/);+ });++ it("says plainly when no base can be found", async () => {+ await git("branch", "-D", "main");+ await git("branch", "-M", "trunk");+ await expect(pr({ dir: root, io })).rejects.toThrow(/cannot find a base/);+ });++ it("says when HEAD has no commits yet, or the directory is not a git repository", async () => {+ const empty = join(dir, "empty");+ await mkdir(empty);+ await run("git", ["-C", empty, "init", "-q"], { env });+ await init(+ empty,+ { name: "empty", git: "commit", retention: "keep", language: "auto" },+ fakeIo(env),+ );+ 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));+ await expect(pr({ dir: plain, io })).rejects.toThrow(/not in a git repository/);+ });++ it("keeps its sections and says so when the branch has no commits", async () => {+ const model = await pr({ dir: root, base: "HEAD", io });+ expect(model.thoughts).toEqual([]);+ const text = io.lines.join("\n");+ expect(text).toContain("_No session goal was recorded._");+ expect(text).toContain("_No recorded session is behind these commits._");+ expect(text).toContain("_No recorded thought is behind these commits._");+ expect(text).toContain("_None: every commit carries a recorded thought._");+ });++ it("switches the record policy sentence for the ignore policy", async () => {+ await writeFile(join(root, ".gitignore"), "# cogit\n/.cogit/\n");+ const model = await pr({ dir: root, io });+ expect(model.policy).toBe("ignore");+ expect(io.lines.join("\n")).toContain("resolve only on the author's machine");+ });++ it("drops the file lists first, then the summaries, and says what was left out", () => {+ const model: PrModel = {+ base: { ref: "main", commit: "0".repeat(40) },+ head: "1".repeat(40),+ policy: "commit",+ goals: [{ text: "A goal", sessionId: "s1", sessionTitle: "Session" }],+ sessions: [+ {+ sessionId: "s1",+ shortId: "s1",+ title: "Session",+ startedAt: T0,+ updatedAt: T0,+ from: "m1",+ to: "m1",+ thoughtCount: 1,+ commitCount: 1,+ },+ ],+ thoughts: [+ {+ id: A,+ shortId: shortHash(A),+ label: "m1",+ sessionId: "s1",+ shortSessionId: "s1",+ sessionTitle: "Session",+ title: "A thought",+ summary: "A summary that is dropped last.",+ alternatives: [],+ agentDecisions: [],+ commits: [+ {+ full: "2".repeat(40),+ short: "2222222",+ at: T0,+ subject: "feat: a change",+ files: ["src/a-very-long-file-name.ts", "src/another-long-file-name.ts"],+ },+ ],+ },+ ],+ unlinked: [],+ };++ const full = renderPr(model, 1_000_000);+ expect(full.dropped).toEqual([]);+ expect(full.text).toContain("src/a-very-long-file-name.ts");+ expect(full.text).toContain("A summary that is dropped last.");++ const withoutFiles = formatPr(model, {+ includeFiles: false,+ includeSummaries: true,+ dropped: ["files"],+ });+ const filesDropped = renderPr(model, withoutFiles.length);+ expect(filesDropped.dropped).toEqual(["files"]);+ expect(filesDropped.text).not.toContain("src/a-very-long-file-name.ts");+ expect(filesDropped.text).toContain("A summary that is dropped last.");+ expect(filesDropped.text).toContain("Left out to stay under the size cap: file lists.");++ const withoutBoth = formatPr(model, {+ includeFiles: false,+ includeSummaries: false,+ dropped: ["files", "summaries"],+ });+ const summariesDropped = renderPr(model, withoutBoth.length);+ expect(summariesDropped.dropped).toEqual(["files", "summaries"]);+ expect(summariesDropped.text).not.toContain("A summary that is dropped last.");+ expect(summariesDropped.text).toContain("file lists and summaries");++ const truncated = renderPr(model, 80);+ expect(truncated.truncated).toBe(true);+ expect(truncated.text.length).toBeLessThanOrEqual(80);++ const capped = renderPr(model, 200);+ expect(capped.truncated).toBe(true);+ expect(capped.text.length).toBeLessThanOrEqual(200);+ expect(capped.text).toContain("Truncated to fit the size cap");+ });++ it("runs through the CLI", async () => {+ const cliIo = fakeIo(env);+ const program = createProgram(() => cliIo);+ await program.parseAsync(["pr", "-C", root], { from: "user" });+ expect(cliIo.lines.join("\n")).toContain("## Goal");+ expect(cliIo.lines.join("\n")).toContain("Session");+ });++ it("copies with the first clipboard tool that exists", async () => {+ const bin = join(dir, "bin");+ const empty = join(dir, "empty-bin");+ await mkdir(bin);+ await mkdir(empty);+ const out = join(dir, "clipboard.txt");+ const wlCopy = join(bin, "wl-copy");+ await writeFile(wlCopy, `#!/bin/sh\ncat > "${out}"\n`);+ await chmod(wlCopy, 0o755);++ expect(await copyToClipboard("hello", { ...env, PATH: `${bin}:${env.PATH}` })).toBe(true);+ expect(await readFile(out, "utf8")).toBe("hello");+ expect(await copyToClipboard("hello", { ...env, PATH: empty })).toBe(false);+ });++ it("copies through pr and warns plainly when there is no clipboard tool", async () => {+ const bin = join(dir, "bin");+ await mkdir(bin);+ const out = join(dir, "clipboard.txt");+ const wlCopy = join(bin, "wl-copy");+ await writeFile(wlCopy, `#!/bin/sh\ncat > "${out}"\n`);+ await chmod(wlCopy, 0o755);++ const copied = fakeIo({ ...env, PATH: `${bin}:${env.PATH}` });+ await pr({ dir: root, io: copied, copy: true });+ expect(await readFile(out, "utf8")).toContain("## Goal");+ expect(copied.warnings).toEqual([]);++ const gitOnly = join(dir, "git-only");+ await mkdir(gitOnly);+ await symlink(await findExecutable("git"), join(gitOnly, "git"));+ const bare = fakeIo({ ...env, PATH: gitOnly });+ await pr({ dir: root, io: bare, copy: true });+ expect(bare.warnings.join("\n")).toContain("no clipboard tool found");+ });++ it("parses only well-formed commit lines", () => {+ const line = ["a".repeat(40), "aaaaaaa", T0, "feat: a"].join("\0");+ const emptyShort = ["b".repeat(40), "", T0, "feat: b"].join("\0");+ expect(parsePrCommits(`not a commit\n${line}\n${emptyShort}`)).toEqual([+ { full: "a".repeat(40), short: "aaaaaaa", at: T0, subject: "feat: a" },+ ]);+ });+});