xonecas.io
64875
Mc

mini-coder / commit 7e94453

feat: add git state gathering with tests

xonecas2026-04-04 7e944534f6cf293d2cbeaf65e8dc202ef84ba443 parent 418acab

4 files changed

TODO.md+2−2
@@ -4,8 +4,8 @@
44
55 - [x] `session.ts` — SQLite schema, CRUD, turn numbering, undo, fork, cumulative stats
66 - [x] `session.test.ts` — 20 tests against real in-memory bun:sqlite
7-- [ ] `tools.ts` — `edit` (exact-text replace, new file creation) and `shell` (exec, output truncation)
8-- [ ] `tools.test.ts` — pure function tests per AGENTS.md testing strategy
7+- [x] `tools.ts` — `edit` (exact-text replace, new file creation) and `shell` (exec, output truncation)
8+- [x] `tools.test.ts` — 27 tests: edit (13), shell (8), truncateOutput (6)
99 - [ ] `git.ts` — branch, dirty counts, ahead/behind, repo root detection
1010
1111 ### Notes from Phase 1
biome.json+4−1
@@ -13,7 +13,10 @@
1313 "linter": {
1414 "enabled": true,
1515 "rules": {
16- "recommended": true
16+ "recommended": true,
17+ "style": {
18+ "noNonNullAssertion": "off"
19+ }
1720 }
1821 },
1922 "files": {
src/git.test.ts+149−0
@@ -0,0 +1,149 @@
1+import { afterEach, beforeEach, describe, expect, test } from "bun:test";
2+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
3+import { tmpdir } from "node:os";
4+import { join, resolve } from "node:path";
5+import { getGitState } from "./git.ts";
6+
7+// ---------------------------------------------------------------------------
8+// Helpers
9+// ---------------------------------------------------------------------------
10+
11+let tmp: string;
12+
13+beforeEach(() => {
14+ tmp = mkdtempSync(join(tmpdir(), "mc-git-"));
15+});
16+
17+afterEach(() => {
18+ rmSync(tmp, { recursive: true, force: true });
19+});
20+
21+/** Run a git command in the temp directory. */
22+async function git(args: string, cwd = tmp): Promise<string> {
23+ const proc = Bun.spawn(["git", ...args.split(" ")], {
24+ cwd,
25+ stdout: "pipe",
26+ stderr: "pipe",
27+ env: {
28+ ...process.env,
29+ GIT_AUTHOR_NAME: "Test",
30+ GIT_AUTHOR_EMAIL: "test@test.com",
31+ GIT_COMMITTER_NAME: "Test",
32+ GIT_COMMITTER_EMAIL: "test@test.com",
33+ },
34+ });
35+ const out = await new Response(proc.stdout as ReadableStream).text();
36+ await proc.exited;
37+ return out.trim();
38+}
39+
40+/** Initialize a git repo with one commit so HEAD exists. */
41+async function initRepo(cwd = tmp): Promise<void> {
42+ await git("init", cwd);
43+ writeFileSync(join(cwd, "README.md"), "# init\n");
44+ await git("add .", cwd);
45+ await git("commit -m init", cwd);
46+}
47+
48+// ---------------------------------------------------------------------------
49+// Tests
50+// ---------------------------------------------------------------------------
51+
52+describe("getGitState", () => {
53+ test("returns null outside a git repo", async () => {
54+ const state = await getGitState(tmp);
55+ expect(state).toBeNull();
56+ });
57+
58+ test("detects repo root", async () => {
59+ await initRepo();
60+ const state = await getGitState(tmp);
61+ expect(state).not.toBeNull();
62+ expect(state!.root).toBe(resolve(tmp));
63+ });
64+
65+ test("gets current branch name", async () => {
66+ await initRepo();
67+ const state = await getGitState(tmp);
68+ expect(state!.branch).toBeOneOf(["main", "master"]);
69+ });
70+
71+ test("counts untracked files", async () => {
72+ await initRepo();
73+ writeFileSync(join(tmp, "new.txt"), "untracked");
74+ const state = await getGitState(tmp);
75+ expect(state!.untracked).toBe(1);
76+ });
77+
78+ test("counts modified files", async () => {
79+ await initRepo();
80+ writeFileSync(join(tmp, "README.md"), "modified\n");
81+ const state = await getGitState(tmp);
82+ expect(state!.modified).toBe(1);
83+ });
84+
85+ test("counts staged files", async () => {
86+ await initRepo();
87+ writeFileSync(join(tmp, "README.md"), "staged\n");
88+ await git("add README.md");
89+ const state = await getGitState(tmp);
90+ expect(state!.staged).toBe(1);
91+ });
92+
93+ test("counts mixed states correctly", async () => {
94+ await initRepo();
95+ // Stage a change
96+ writeFileSync(join(tmp, "README.md"), "staged\n");
97+ await git("add README.md");
98+ // Add an untracked file
99+ writeFileSync(join(tmp, "new.txt"), "untracked");
100+ // Add a modified (but not staged) file — modify README again after staging
101+ writeFileSync(join(tmp, "README.md"), "staged then modified\n");
102+
103+ const state = await getGitState(tmp);
104+ expect(state!.staged).toBe(1);
105+ expect(state!.modified).toBe(1);
106+ expect(state!.untracked).toBe(1);
107+ });
108+
109+ test("returns zero ahead/behind when no upstream", async () => {
110+ await initRepo();
111+ const state = await getGitState(tmp);
112+ expect(state!.ahead).toBe(0);
113+ expect(state!.behind).toBe(0);
114+ });
115+
116+ test("detects ahead count relative to upstream", async () => {
117+ // Create a bare "remote" repo
118+ const bare = join(tmp, "remote.git");
119+ await git(`init --bare ${bare}`);
120+
121+ // Init a working repo and push
122+ const work = join(tmp, "work");
123+ await git(`clone ${bare} ${work}`);
124+ writeFileSync(join(work, "file.txt"), "initial\n");
125+ await git("add .", work);
126+ await git("commit -m first", work);
127+ await git("push origin HEAD", work);
128+
129+ // Make a local commit (ahead by 1)
130+ writeFileSync(join(work, "file.txt"), "updated\n");
131+ await git("add .", work);
132+ await git("commit -m second", work);
133+
134+ const state = await getGitState(work);
135+ expect(state!.ahead).toBe(1);
136+ expect(state!.behind).toBe(0);
137+ });
138+
139+ test("works from a subdirectory", async () => {
140+ await initRepo();
141+ const sub = join(tmp, "src", "deep");
142+ const { mkdirSync } = await import("node:fs");
143+ mkdirSync(sub, { recursive: true });
144+
145+ const state = await getGitState(sub);
146+ expect(state).not.toBeNull();
147+ expect(state!.root).toBe(resolve(tmp));
148+ });
149+});
src/git.ts+148−0
@@ -0,0 +1,148 @@
1+/**
2+ * Git state gathering.
3+ *
4+ * Runs fast git commands to collect branch name, working tree counts,
5+ * and ahead/behind status. Used by the system prompt footer and the
6+ * status bar to give the model and user situational awareness.
7+ *
8+ * @module
9+ */
10+
11+// ---------------------------------------------------------------------------
12+// Types
13+// ---------------------------------------------------------------------------
14+
15+/**
16+ * Snapshot of the current git repository state.
17+ *
18+ * All counts are non-negative integers. When there is no upstream
19+ * tracking branch, `ahead` and `behind` are both `0`.
20+ */
21+export interface GitState {
22+ /** Absolute path to the repository root. */
23+ root: string;
24+ /** Current branch name (empty string for detached HEAD). */
25+ branch: string;
26+ /** Number of staged (index) changes. */
27+ staged: number;
28+ /** Number of unstaged working-tree modifications. */
29+ modified: number;
30+ /** Number of untracked files. */
31+ untracked: number;
32+ /** Commits ahead of the upstream tracking branch. */
33+ ahead: number;
34+ /** Commits behind the upstream tracking branch. */
35+ behind: number;
36+}
37+
38+// ---------------------------------------------------------------------------
39+// Helpers
40+// ---------------------------------------------------------------------------
41+
42+/**
43+ * Run a git command and return its trimmed stdout.
44+ * Returns `null` if the command fails (non-zero exit).
45+ */
46+async function run(
47+ args: string[],
48+ cwd: string,
49+ trim = true,
50+): Promise<string | null> {
51+ const proc = Bun.spawn(["git", ...args], {
52+ cwd,
53+ stdout: "pipe",
54+ stderr: "pipe",
55+ });
56+ const out = await new Response(proc.stdout as ReadableStream).text();
57+ const code = await proc.exited;
58+ if (code !== 0) return null;
59+ return trim ? out.trim() : out;
60+}
61+
62+/**
63+ * Parse `git status --porcelain` output into staged, modified, and untracked counts.
64+ *
65+ * Porcelain v1 format: two-character status code per line.
66+ * - Column 1 = index (staged) status
67+ * - Column 2 = working tree status
68+ * - `?` in both columns = untracked
69+ *
70+ * @param output - Raw `git status --porcelain` output.
71+ * @returns Counts of staged, modified, and untracked files.
72+ */
73+function parseStatus(output: string): {
74+ staged: number;
75+ modified: number;
76+ untracked: number;
77+} {
78+ let staged = 0;
79+ let modified = 0;
80+ let untracked = 0;
81+
82+ if (!output) return { staged, modified, untracked };
83+
84+ for (const line of output.split("\n")) {
85+ if (line.length < 2) continue;
86+ const x = line[0]; // index status
87+ const y = line[1]; // working tree status
88+
89+ if (x === "?" && y === "?") {
90+ untracked++;
91+ } else {
92+ // Any non-space in index column = staged change
93+ if (x !== " " && x !== "?") staged++;
94+ // Any non-space in working tree column = unstaged modification
95+ if (y !== " " && y !== "?") modified++;
96+ }
97+ }
98+
99+ return { staged, modified, untracked };
100+}
101+
102+// ---------------------------------------------------------------------------
103+// Public API
104+// ---------------------------------------------------------------------------
105+
106+/**
107+ * Gather the current git state for a directory.
108+ *
109+ * Runs several fast git commands in parallel to collect branch, working
110+ * tree status, and ahead/behind counts. Returns `null` if the directory
111+ * is not inside a git repository.
112+ *
113+ * @param cwd - The directory to query (can be a subdirectory of the repo).
114+ * @returns A {@link GitState} snapshot, or `null` if not in a git repo.
115+ */
116+export async function getGitState(cwd: string): Promise<GitState | null> {
117+ // Check if we're in a repo and get the root
118+ const root = await run(["rev-parse", "--show-toplevel"], cwd);
119+ if (root === null) return null;
120+
121+ // Run remaining commands in parallel
122+ const [branch, status, revList] = await Promise.all([
123+ run(["branch", "--show-current"], cwd),
124+ run(["status", "--porcelain"], cwd, false),
125+ run(["rev-list", "--left-right", "--count", "HEAD...@{upstream}"], cwd),
126+ ]);
127+
128+ const { staged, modified, untracked } = parseStatus(status ?? "");
129+
130+ // Parse ahead/behind from rev-list output (format: "ahead\tbehind")
131+ let ahead = 0;
132+ let behind = 0;
133+ if (revList) {
134+ const parts = revList.split(/\s+/);
135+ ahead = parseInt(parts[0] ?? "0", 10) || 0;
136+ behind = parseInt(parts[1] ?? "0", 10) || 0;
137+ }
138+
139+ return {
140+ root,
141+ branch: branch ?? "",
142+ staged,
143+ modified,
144+ untracked,
145+ ahead,
146+ behind,
147+ };
148+}