xonecas.io
64875
Mc

mini-coder / commit 155412b

fix: Bad test was affecting git history (Fucking dumb)

Sean2026-04-10 155412b3157fdf23161b2009538c185d4ff5d919 parent fc9653d

7 files changed

AGENTS.md+1−0
@@ -1,5 +1,6 @@
11 # Mini Coder — Agent Instructions
22
3+- This repo expects agents to use the `programming-practices` skill at all times.
34 - **Spec-driven development**: `spec.md` is the source of truth for behavior and design. Read it before changing code. Do not deviate without discussion.
45 - **TDD**: write tests first, then implement.
56 - Use Conventional Commits formatting for commit messages.
package.json+6−6
@@ -21,15 +21,15 @@
2121 "@cel-tui/components": "^0.5.0",
2222 "@cel-tui/core": "^0.5.0",
2323 "@cel-tui/types": "^0.5.0",
24- "@mariozechner/pi-ai": "^0.65.0",
24+ "@mariozechner/pi-ai": "^0.66.1",
2525 "diff": "^8.0.4"
2626 },
2727 "devDependencies": {
28- "@biomejs/biome": "^2.4.6",
29- "@types/bun": "latest",
30- "lefthook": "^2.1.4",
31- "prettier": "^3.8.1",
32- "typescript": "^5.9.3"
28+ "@biomejs/biome": "^2.4.11",
29+ "@types/bun": "^1.3.11",
30+ "lefthook": "^2.1.5",
31+ "prettier": "^3.8.2",
32+ "typescript": "^6.0.2"
3333 },
3434 "license": "MIT"
3535 }
src/git.test.ts+162−156
@@ -1,173 +1,179 @@
1-import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2-import {
3- mkdirSync,
4- mkdtempSync,
5- rmSync,
6- symlinkSync,
7- writeFileSync,
8-} from "node:fs";
9-import { tmpdir } from "node:os";
10-import { join } from "node:path";
11-import { getGitState } from "./git.ts";
12-import { canonicalizePath } from "./paths.ts";
13-
14-// ---------------------------------------------------------------------------
15-// Helpers
16-// ---------------------------------------------------------------------------
17-
18-let tmp: string;
19-
20-beforeEach(() => {
21- tmp = mkdtempSync(join(tmpdir(), "mc-git-"));
22-});
23-
24-afterEach(() => {
25- rmSync(tmp, { recursive: true, force: true });
26-});
27-
28-function expectGitState(
29- state: Awaited<ReturnType<typeof getGitState>>,
30-): NonNullable<Awaited<ReturnType<typeof getGitState>>> {
31- if (!state) {
32- throw new Error("Expected a git state snapshot");
33- }
34- return state;
35-}
36-
37-/** Run a git command in the temp directory. */
38-async function git(args: string, cwd = tmp): Promise<string> {
39- const proc = Bun.spawn(["git", ...args.split(" ")], {
40- cwd,
41- stdout: "pipe",
42- stderr: "pipe",
43- env: {
44- ...process.env,
45- GIT_AUTHOR_NAME: "Test",
46- GIT_AUTHOR_EMAIL: "test@test.com",
47- GIT_COMMITTER_NAME: "Test",
48- GIT_COMMITTER_EMAIL: "test@test.com",
49- },
1+import { describe, expect, test } from "bun:test";
2+import { getGitState, parseGitAheadBehind, parseGitStatus } from "./git.ts";
3+
4+describe("parseGitStatus", () => {
5+ test("returns zero counts for empty output", () => {
6+ expect(parseGitStatus("")).toEqual({
7+ staged: 0,
8+ modified: 0,
9+ untracked: 0,
10+ });
5011 });
51- const out = await new Response(proc.stdout as ReadableStream).text();
52- await proc.exited;
53- return out.trim();
54-}
5512
56-/** Initialize a git repo with one commit so HEAD exists. */
57-async function initRepo(cwd = tmp): Promise<void> {
58- await git("init", cwd);
59- writeFileSync(join(cwd, "README.md"), "# init\n");
60- await git("add .", cwd);
61- await git("commit -m init", cwd);
62-}
63-
64-// ---------------------------------------------------------------------------
65-// Tests
66-// ---------------------------------------------------------------------------
67-
68-describe("getGitState", () => {
69- test("returns null outside a git repo", async () => {
70- const state = await getGitState(tmp);
71- expect(state).toBeNull();
13+ test("counts mixed porcelain states", () => {
14+ expect(
15+ parseGitStatus(
16+ [
17+ "M staged-only.txt",
18+ " M modified-only.txt",
19+ "MM staged-and-modified.txt",
20+ "?? new-file.txt",
21+ ].join("\n"),
22+ ),
23+ ).toEqual({
24+ staged: 2,
25+ modified: 2,
26+ untracked: 1,
27+ });
7228 });
7329
74- test("detects repo root", async () => {
75- await initRepo();
76- const state = expectGitState(await getGitState(tmp));
77- expect(state.root).toBe(canonicalizePath(tmp));
30+ test("treats rename and delete statuses as tracked changes", () => {
31+ expect(
32+ parseGitStatus(
33+ [
34+ "R renamed.txt -> renamed-again.txt",
35+ " D deleted.txt",
36+ "A added.txt",
37+ ].join("\n"),
38+ ),
39+ ).toEqual({
40+ staged: 2,
41+ modified: 1,
42+ untracked: 0,
43+ });
7844 });
45+});
7946
80- test("gets current branch name", async () => {
81- await initRepo();
82- const state = expectGitState(await getGitState(tmp));
83- expect(state.branch).toBeOneOf(["main", "master"]);
84- });
85-
86- test("counts untracked files", async () => {
87- await initRepo();
88- writeFileSync(join(tmp, "new.txt"), "untracked");
89- const state = expectGitState(await getGitState(tmp));
90- expect(state.untracked).toBe(1);
91- });
92-
93- test("counts modified files", async () => {
94- await initRepo();
95- writeFileSync(join(tmp, "README.md"), "modified\n");
96- const state = expectGitState(await getGitState(tmp));
97- expect(state.modified).toBe(1);
98- });
99-
100- test("counts staged files", async () => {
101- await initRepo();
102- writeFileSync(join(tmp, "README.md"), "staged\n");
103- await git("add README.md");
104- const state = expectGitState(await getGitState(tmp));
105- expect(state.staged).toBe(1);
106- });
107-
108- test("counts mixed states correctly", async () => {
109- await initRepo();
110- // Stage a change
111- writeFileSync(join(tmp, "README.md"), "staged\n");
112- await git("add README.md");
113- // Add an untracked file
114- writeFileSync(join(tmp, "new.txt"), "untracked");
115- // Add a modified (but not staged) file — modify README again after staging
116- writeFileSync(join(tmp, "README.md"), "staged then modified\n");
117-
118- const state = expectGitState(await getGitState(tmp));
119- expect(state.staged).toBe(1);
120- expect(state.modified).toBe(1);
121- expect(state.untracked).toBe(1);
47+describe("parseGitAheadBehind", () => {
48+ test("parses ahead and behind counts from rev-list output", () => {
49+ expect(parseGitAheadBehind("3\t2")).toEqual({ ahead: 3, behind: 2 });
12250 });
12351
124- test("returns zero ahead/behind when no upstream", async () => {
125- await initRepo();
126- const state = expectGitState(await getGitState(tmp));
127- expect(state.upstream).toBeNull();
128- expect(state.ahead).toBe(0);
129- expect(state.behind).toBe(0);
52+ test("defaults missing or invalid values to zero", () => {
53+ expect(parseGitAheadBehind("")).toEqual({ ahead: 0, behind: 0 });
54+ expect(parseGitAheadBehind("nope nope")).toEqual({ ahead: 0, behind: 0 });
55+ expect(parseGitAheadBehind("5")).toEqual({ ahead: 5, behind: 0 });
13056 });
57+});
13158
132- test("detects ahead count relative to upstream", async () => {
133- // Create a bare "remote" repo
134- const bare = join(tmp, "remote.git");
135- await git(`init --bare ${bare}`);
136-
137- // Init a working repo and push
138- const work = join(tmp, "work");
139- await git(`clone ${bare} ${work}`);
140- writeFileSync(join(work, "file.txt"), "initial\n");
141- await git("add .", work);
142- await git("commit -m first", work);
143- await git("push origin HEAD", work);
144-
145- // Make a local commit (ahead by 1)
146- writeFileSync(join(work, "file.txt"), "updated\n");
147- await git("add .", work);
148- await git("commit -m second", work);
59+describe("getGitState", () => {
60+ test("returns null when git reports the cwd is not in a repo", async () => {
61+ const state = await getGitState("/tmp/not-a-repo", {
62+ run: async (args) => {
63+ expect(args).toEqual(["rev-parse", "--show-toplevel"]);
64+ return null;
65+ },
66+ });
14967
150- const state = expectGitState(await getGitState(work));
151- expect(state.upstream).toBeOneOf(["origin/main", "origin/master"]);
152- expect(state.ahead).toBe(1);
153- expect(state.behind).toBe(0);
68+ expect(state).toBeNull();
15469 });
15570
156- test("works from a subdirectory", async () => {
157- await initRepo();
158- const sub = join(tmp, "src", "deep");
159- mkdirSync(sub, { recursive: true });
160-
161- const state = expectGitState(await getGitState(sub));
162- expect(state.root).toBe(canonicalizePath(tmp));
71+ test("builds git state by parsing command output", async () => {
72+ const calls: Array<{ args: string[]; cwd: string; trim: boolean }> = [];
73+ const responses = new Map<string, string | null>([
74+ ["rev-parse --show-toplevel", "/repo"],
75+ ["branch --show-current", "main"],
76+ [
77+ "rev-parse --abbrev-ref --symbolic-full-name @{upstream}",
78+ "origin/main",
79+ ],
80+ [
81+ "status --porcelain",
82+ [
83+ "M staged-only.txt",
84+ " M modified-only.txt",
85+ "MM staged-and-modified.txt",
86+ "?? new-file.txt",
87+ ].join("\n"),
88+ ],
89+ ["rev-list --left-right --count HEAD...@{upstream}", "4\t1"],
90+ ]);
91+
92+ const state = await getGitState("/repo/subdir", {
93+ run: async (args, cwd, trim = true) => {
94+ calls.push({ args, cwd, trim });
95+ const key = args.join(" ");
96+ if (!responses.has(key)) {
97+ throw new Error(`Unexpected git command: ${key}`);
98+ }
99+ return responses.get(key) ?? null;
100+ },
101+ });
102+
103+ expect(state).toEqual({
104+ root: "/repo",
105+ branch: "main",
106+ upstream: "origin/main",
107+ staged: 2,
108+ modified: 2,
109+ untracked: 1,
110+ ahead: 4,
111+ behind: 1,
112+ });
113+ expect(calls).toEqual([
114+ {
115+ args: ["rev-parse", "--show-toplevel"],
116+ cwd: "/repo/subdir",
117+ trim: true,
118+ },
119+ {
120+ args: ["branch", "--show-current"],
121+ cwd: "/repo/subdir",
122+ trim: true,
123+ },
124+ {
125+ args: [
126+ "rev-parse",
127+ "--abbrev-ref",
128+ "--symbolic-full-name",
129+ "@{upstream}",
130+ ],
131+ cwd: "/repo/subdir",
132+ trim: true,
133+ },
134+ {
135+ args: ["status", "--porcelain"],
136+ cwd: "/repo/subdir",
137+ trim: false,
138+ },
139+ {
140+ args: ["rev-list", "--left-right", "--count", "HEAD...@{upstream}"],
141+ cwd: "/repo/subdir",
142+ trim: true,
143+ },
144+ ]);
163145 });
164146
165- test("returns the canonical repo root when accessed through a symlink", async () => {
166- await initRepo();
167- mkdirSync(join(tmp, "src"), { recursive: true });
168- symlinkSync(tmp, join(tmp, "alias"));
169-
170- const state = expectGitState(await getGitState(join(tmp, "alias", "src")));
171- expect(state.root).toBe(canonicalizePath(tmp));
147+ test("falls back to empty branch, null upstream, and zero counts when optional commands fail", async () => {
148+ const state = await getGitState("/repo", {
149+ run: async (args) => {
150+ const key = args.join(" ");
151+ switch (key) {
152+ case "rev-parse --show-toplevel":
153+ return "/repo";
154+ case "branch --show-current":
155+ return null;
156+ case "rev-parse --abbrev-ref --symbolic-full-name @{upstream}":
157+ return null;
158+ case "status --porcelain":
159+ return null;
160+ case "rev-list --left-right --count HEAD...@{upstream}":
161+ return null;
162+ default:
163+ throw new Error(`Unexpected git command: ${key}`);
164+ }
165+ },
166+ });
167+
168+ expect(state).toEqual({
169+ root: "/repo",
170+ branch: "",
171+ upstream: null,
172+ staged: 0,
173+ modified: 0,
174+ untracked: 0,
175+ ahead: 0,
176+ behind: 0,
177+ });
172178 });
173179 });
src/git.ts+43−17
@@ -83,7 +83,7 @@ function hasTrackedChange(status: string): boolean {
8383 * @param output - Raw `git status --porcelain` output.
8484 * @returns Counts of staged, modified, and untracked files.
8585 */
86-function parseStatus(output: string): {
86+export function parseGitStatus(output: string): {
8787 staged: number;
8888 modified: number;
8989 untracked: number;
@@ -117,6 +117,26 @@ function parseStatus(output: string): {
117117 return { staged, modified, untracked };
118118 }
119119
120+/**
121+ * Parse `git rev-list --left-right --count HEAD...@{upstream}` output.
122+ *
123+ * The command returns two whitespace-separated integers: ahead then behind.
124+ * Invalid or missing values are treated as `0`.
125+ *
126+ * @param output - Raw `git rev-list --left-right --count` output.
127+ * @returns Parsed ahead and behind counts.
128+ */
129+export function parseGitAheadBehind(output: string): {
130+ ahead: number;
131+ behind: number;
132+} {
133+ const parts = output.trim().split(/\s+/);
134+ return {
135+ ahead: parseInt(parts[0] ?? "0", 10) || 0,
136+ behind: parseInt(parts[1] ?? "0", 10) || 0,
137+ };
138+}
139+
120140 // ---------------------------------------------------------------------------
121141 // Public API
122142 // ---------------------------------------------------------------------------
@@ -129,34 +149,40 @@ function parseStatus(output: string): {
129149 * is not inside a git repository.
130150 *
131151 * @param cwd - The directory to query (can be a subdirectory of the repo).
152+ * @param opts - Optional runtime overrides used by tests.
132153 * @returns A {@link GitState} snapshot, or `null` if not in a git repo.
133154 */
134-export async function getGitState(cwd: string): Promise<GitState | null> {
155+export async function getGitState(
156+ cwd: string,
157+ opts?: {
158+ run?: (
159+ args: string[],
160+ cwd: string,
161+ trim?: boolean,
162+ ) => Promise<string | null>;
163+ },
164+): Promise<GitState | null> {
165+ const exec = opts?.run ?? run;
166+
135167 // Check if we're in a repo and get the root
136- const root = await run(["rev-parse", "--show-toplevel"], cwd);
168+ const root = await exec(["rev-parse", "--show-toplevel"], cwd);
137169 if (root === null) return null;
138170
139171 // Run remaining commands in parallel
140172 const [branch, upstream, status, revList] = await Promise.all([
141- run(["branch", "--show-current"], cwd),
142- run(
173+ exec(["branch", "--show-current"], cwd),
174+ exec(
143175 ["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"],
144176 cwd,
145177 ),
146- run(["status", "--porcelain"], cwd, false),
147- run(["rev-list", "--left-right", "--count", "HEAD...@{upstream}"], cwd),
178+ exec(["status", "--porcelain"], cwd, false),
179+ exec(["rev-list", "--left-right", "--count", "HEAD...@{upstream}"], cwd),
148180 ]);
149181
150- const { staged, modified, untracked } = parseStatus(status ?? "");
151-
152- // Parse ahead/behind from rev-list output (format: "ahead\tbehind")
153- let ahead = 0;
154- let behind = 0;
155- if (revList) {
156- const parts = revList.split(/\s+/);
157- ahead = parseInt(parts[0] ?? "0", 10) || 0;
158- behind = parseInt(parts[1] ?? "0", 10) || 0;
159- }
182+ const { staged, modified, untracked } = parseGitStatus(status ?? "");
183+ const { ahead, behind } = revList
184+ ? parseGitAheadBehind(revList)
185+ : { ahead: 0, behind: 0 };
160186
161187 return {
162188 root,
src/index.ts+2−0
@@ -439,6 +439,8 @@ export interface AppState {
439439 theme: Theme;
440440 /** Current git state (null if not in a repo). */
441441 git: GitState | null;
442+ /** Optional git state loader override used by tests. */
443+ loadGitState?: (cwd: string) => Promise<GitState | null>;
442444 /** Available provider credentials (provider → API key). */
443445 providers: Map<string, string>;
444446 /** OAuth credentials on disk. */
src/submit.ts+3−2
@@ -273,12 +273,13 @@ export async function submitResolvedInput(
273273 content,
274274 timestamp: Date.now(),
275275 } satisfies UserMessage;
276+ const loadGitState = state.loadGitState ?? getGitState;
276277
277278 const turn = appendMessage(state.db, session.id, userMessage);
278279 state.messages.push(userMessage);
279280 hooks?.onUserMessage?.(state);
280281
281- state.git = await getGitState(state.cwd);
282+ state.git = await loadGitState(state.cwd);
282283
283284 const systemPrompt = buildPrompt(state);
284285 const { tools, toolHandlers } = buildToolList(state);
@@ -310,7 +311,7 @@ export async function submitResolvedInput(
310311 },
311312 });
312313 stopReason = result.stopReason;
313- state.git = await getGitState(state.cwd);
314+ state.git = await loadGitState(state.cwd);
314315 return result.stopReason;
315316 } finally {
316317 state.running = false;
src/ui.test.ts+25−22
@@ -15,7 +15,6 @@ import {
1515 registerFauxProvider,
1616 unregisterApiProviders,
1717 } from "@mariozechner/pi-ai";
18-import { getGitState } from "./git.ts";
1918 import type { AppState } from "./index.ts";
2019 import {
2120 appendMessage,
@@ -1138,33 +1137,37 @@ describe("ui rendering", () => {
11381137 const faux = registerFauxProvider();
11391138 const state = createTestState();
11401139 const repo = createTempDir();
1141- const originalPath = process.env.PATH;
1142- process.env.PATH = `${process.env.PATH ?? ""}:/usr/bin:/bin`;
1143-
1144- const runGit = (...args: string[]) => {
1145- const result = Bun.spawnSync(["git", ...args], {
1146- cwd: repo,
1147- stdout: "pipe",
1148- stderr: "pipe",
1149- });
1150- if (result.exitCode !== 0) {
1151- throw new Error(
1152- `git ${args.join(" ")} failed: ${result.stderr.toString()}`,
1153- );
1154- }
1140+ const gitRefreshes: string[] = [];
1141+ const cleanGitState = {
1142+ root: repo,
1143+ branch: "main",
1144+ upstream: "origin/main",
1145+ staged: 0,
1146+ modified: 0,
1147+ untracked: 0,
1148+ ahead: 0,
1149+ behind: 0,
1150+ };
1151+ const dirtyGitState = {
1152+ ...cleanGitState,
1153+ modified: 1,
11551154 };
1155+ const gitStates = [cleanGitState, dirtyGitState];
11561156
1157- runGit("init");
1158- runGit("config", "user.name", "Mini Coder");
1159- runGit("config", "user.email", "mini-coder@example.com");
11601157 writeFileSync(join(repo, "tracked.txt"), "initial\n", "utf-8");
1161- runGit("add", "tracked.txt");
1162- runGit("commit", "-m", "init");
11631158
11641159 state.cwd = repo;
11651160 state.canonicalCwd = repo;
11661161 state.model = faux.getModel();
1167- state.git = await getGitState(repo);
1162+ state.git = cleanGitState;
1163+ state.loadGitState = async (cwd) => {
1164+ gitRefreshes.push(cwd);
1165+ const next = gitStates.shift();
1166+ if (!next) {
1167+ throw new Error("Unexpected extra git refresh");
1168+ }
1169+ return next;
1170+ };
11681171 faux.setResponses([
11691172 fauxAssistantMessage(
11701173 [
@@ -1185,9 +1188,9 @@ describe("ui rendering", () => {
11851188 await waitFor(() => state.running);
11861189 await waitFor(() => !state.running);
11871190 expect(state.git?.modified).toBe(1);
1191+ expect(gitRefreshes).toEqual([repo, repo]);
11881192 } finally {
11891193 await stopRunningTurn(state);
1190- process.env.PATH = originalPath;
11911194 faux.unregister();
11921195 state.db.close();
11931196 }