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.

fix(why): find the project from any directory inside it and exit quietly on a closed pipe

Eren504e5ac22dd5
diff --git a/docs/guide/reading-the-lineage.md b/docs/guide/reading-the-lineage.md
index e6d2772..18f8eea 100644
--- a/docs/guide/reading-the-lineage.md
+++ b/docs/guide/reading-the-lineage.md
@@ -34,6 +34,9 @@ each with its message hash and date.
The lookup is exact, but the wording is the record's summary, so it is only as good as the
record.
+Like git, it works from any directory inside the project: the path is relative to where you
+are, so `cd src && cogit why auth.ts` is the same lookup.
+
## How the agent uses it
The agent reads the same commands:
diff --git a/packages/cli/src/cli.ts b/packages/cli/src/cli.ts
index 5f4ccaf..52f9432 100644
--- a/packages/cli/src/cli.ts
+++ b/packages/cli/src/cli.ts
@@ -1,3 +1,4 @@
+import { exitOnClosedPipe } from "./io.js";
import { createProgram } from "./program.js";
import { migrateGlobal, takeMigrationWarnings } from "./store/migrate.js";
@@ -5,4 +6,5 @@ import { migrateGlobal, takeMigrationWarnings } from "./store/migrate.js";
await migrateGlobal();
for (const line of takeMigrationWarnings()) process.stderr.write(`warning: ${line}\n`);
+exitOnClosedPipe();
await createProgram().parseAsync(process.argv);
diff --git a/packages/cli/src/commands/why.ts b/packages/cli/src/commands/why.ts
index 2890966..905174d 100644
--- a/packages/cli/src/commands/why.ts
+++ b/packages/cli/src/commands/why.ts
@@ -1,7 +1,9 @@
+import { existsSync } from "node:fs";
import { stat } from "node:fs/promises";
-import { isAbsolute, relative, resolve, sep } from "node:path";
+import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
import { blameCommitHashes, findGitRoot } from "../git.js";
import { CliError, type Io } from "../io.js";
+import { projectPaths } from "../store/paths.js";
import { resolveProjectRoot } from "../store/root.js";
import { loadAllSessions, loadProject } from "../store/stores.js";
import { attachThoughtTrailers, earliestSessionStart, readThoughtTrailers } from "../thought.js";
@@ -178,32 +180,56 @@ export function formatWhy(hits: readonly WhyHit[]): string[] {
}
export interface WhyOptions {
- dir: string;
- /** A file, relative to the project or absolute. */
+ /** The project; `file` is relative to it. */
+ dir?: string;
+ /**
+ * Instead of `dir`, the directory the user is in: the project is the nearest
+ * one above it and `file` is relative to it, as with git.
+ */
+ cwd?: string;
+ /** A file, relative to the project (or to `cwd`) or absolute. */
file: string;
io: Io;
}
+/**
+ * The nearest directory at or above `start` that holds a cogit project or a
+ * repository's top; the walk stops there so a worktree never reaches the main
+ * checkout's `.cogit/` (resolveProjectRoot decides that). Undefined when none.
+ */
+export async function nearestProjectDir(start: string): Promise<string | undefined> {
+ for (let dir = resolve(start); ; dir = dirname(dir)) {
+ if (existsSync(projectPaths(dir).project) || existsSync(join(dir, ".git"))) return dir;
+ if (dirname(dir) === dir) return undefined;
+ }
+}
+
/**
* 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);
+ let start = opts.dir ?? ".";
+ let file = opts.file;
+ if (opts.cwd !== undefined) {
+ start = (await nearestProjectDir(opts.cwd)) ?? opts.cwd;
+ file = relative(start, resolve(opts.cwd, opts.file));
+ }
+ const { root } = await resolveProjectRoot(start);
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(
+ const exists = await stat(resolve(root, 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);
+ const hits = await collectWhy(root, file, io.env);
if (hits.length === 0) {
io.out(`No decisions or rejected alternatives recorded for ${opts.file}.`);
return hits;
diff --git a/packages/cli/src/io.ts b/packages/cli/src/io.ts
index 665e089..9c81a4e 100644
--- a/packages/cli/src/io.ts
+++ b/packages/cli/src/io.ts
@@ -44,3 +44,17 @@ export function processIo(interactive: boolean): Io {
now: () => new Date().toISOString(),
};
}
+
+/**
+ * Ends the process quietly when the reader of stdout goes away (`cogit log | head`),
+ * the way git does, instead of printing Node's EPIPE stack.
+ */
+export function exitOnClosedPipe(
+ stream: NodeJS.EventEmitter = process.stdout,
+ exit: (code: number) => void = process.exit,
+): void {
+ stream.on("error", (err: NodeJS.ErrnoException) => {
+ if (err.code === "EPIPE") exit(0);
+ else throw err;
+ });
+}
diff --git a/packages/cli/src/program.ts b/packages/cli/src/program.ts
index eb1827b..3a9899e 100644
--- a/packages/cli/src/program.ts
+++ b/packages/cli/src/program.ts
@@ -98,13 +98,18 @@ export function createProgram(makeIo: IoFactory = processIo, deps: ProgramDeps =
.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", ".")
+ .argument("<file>", "file to look up, relative to where you are (or to [dir])")
+ .argument("[dir]", "project directory; by default the nearest one above you")
.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) });
+ run(async (file: string, dir: string | undefined, opts: { dir?: string }) => {
+ const project = opts.dir ?? dir;
+ await why({
+ ...(project === undefined ? { cwd: process.cwd() } : { dir: project }),
+ file,
+ io: makeIo(false),
+ });
}),
);
diff --git a/packages/cli/test/io.test.ts b/packages/cli/test/io.test.ts
index db7e292..60320ce 100644
--- a/packages/cli/test/io.test.ts
+++ b/packages/cli/test/io.test.ts
@@ -38,3 +38,18 @@ describe("processIo", () => {
expect(io.now()).toMatch(/^\d{4}-\d\d-\d\dT/);
});
});
+
+describe("exitOnClosedPipe", () => {
+ it("exits quietly on EPIPE and rethrows any other stream error", async () => {
+ const { EventEmitter } = await import("node:events");
+ const { exitOnClosedPipe } = await import("../src/io.js");
+ const stream = new EventEmitter();
+ const exit = vi.fn();
+ exitOnClosedPipe(stream, exit);
+ stream.emit("error", Object.assign(new Error("write EPIPE"), { code: "EPIPE" }));
+ expect(exit).toHaveBeenCalledWith(0);
+ expect(() => stream.emit("error", Object.assign(new Error("boom"), { code: "EIO" }))).toThrow(
+ "boom",
+ );
+ });
+});
diff --git a/packages/cli/test/why.test.ts b/packages/cli/test/why.test.ts
index b01d799..862adfe 100644
--- a/packages/cli/test/why.test.ts
+++ b/packages/cli/test/why.test.ts
@@ -8,6 +8,7 @@ import { init } from "../src/commands/init.js";
import {
collectWhy,
formatWhy,
+ nearestProjectDir,
rejectedItems,
TRY_BEFORE_MAX_CHARS,
TRY_BEFORE_MAX_ITEMS,
@@ -18,7 +19,7 @@ import {
import { runHook } from "../src/hooks/run.js";
import type { Session } from "../src/schema/session.js";
import { projectPaths } from "../src/store/paths.js";
-import { envFor, fakeIo, noGitProject, T0, tempDir } from "./helpers.js";
+import { envFor, fakeIo, noGitDir, noGitProject, T0, tempDir } from "./helpers.js";
const run = promisify(execFile);
@@ -179,6 +180,20 @@ describe("cogit why", () => {
expect(none.lines).toEqual(["No decisions or rejected alternatives recorded for loose.txt."]);
});
+ it("finds the project above the directory you are in, with the file relative to it", async () => {
+ const sub = join(root, "sub", "deeper");
+ await mkdir(sub, { recursive: true });
+ const io = fakeIo(env);
+ expect(await why({ cwd: sub, file: "../../a.txt", io })).toHaveLength(2);
+ expect(await why({ cwd: root, file: "a.txt", io: fakeIo(env) })).toHaveLength(2);
+ expect(await nearestProjectDir(sub)).toBe(root);
+ const outside = await noGitDir();
+ expect(await nearestProjectDir(outside)).toBeUndefined();
+ await expect(why({ cwd: outside, file: "a.txt", io: fakeIo(env) })).rejects.toThrow(
+ /not initialized/,
+ );
+ });
+
it("refuses an uninitialized project, a non-repository and a missing file", async () => {
const bare = join(dir, "bare");
await mkdir(bare);