Skip to content

armgit / Ix

Public Imported from GitHub
0

Understand any codebase instantly. System intelligence for codebases, built for humans and AI.

feat(context): add recent commits and co-changed files from git history

KageBinarye12aa92b86cf
diff --git a/ix-cli/src/cli/__tests__/history.test.ts b/ix-cli/src/cli/__tests__/history.test.ts
new file mode 100644
index 00000000..f6049741
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/history.test.ts
@@ -0,0 +1,140 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { execFileSync } from "node:child_process";
+import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+import { afterEach, describe, expect, it } from "vitest";
+
+import { buildBundle, clampBudgets } from "../commands/context.js";
+import type { ContextFacts } from "../explain/facts.js";
+import { coChangedFiles, gitRunner, recentCommits, type GitRunner } from "../explain/history.js";
+
+/** A `git log` that answers from a fixed list of commits, newest first. */
+function fakeGit(commits: Array<{ sha: string; date: string; subject: string; files: string[] }>): GitRunner {
+ return (args) => {
+ const path = args[args.indexOf("--") + 1];
+ const depth = Number((args.find((a) => /^-\d+$/.test(a)) ?? "-1000").slice(1));
+ const touching = commits.filter((c) => c.files.includes(path)).slice(0, depth);
+ if (args.includes("--full-diff")) {
+ return touching.map((c) => `@${c.sha}\n\n${c.files.join("\n")}\n`).join("");
+ }
+ return touching.map((c) => `${c.sha}\t${c.date}\t${c.subject}`).join("\n");
+ };
+}
+
+describe("recentCommits", () => {
+ it("keeps the newest two, adds the newest fixes, and stays newest first", () => {
+ // inventory.ts before the rank fix: the fix to the same bug next door was
+ // behind three feature commits.
+ const git = fakeGit([
+ { sha: "d4ed26f", date: "2026-06-04", subject: "Path 2: separate-ingest stitcher (#246)", files: ["inventory.ts"] },
+ { sha: "7ab9034", date: "2026-06-02", subject: "Multi-repo co-ingest (#234)", files: ["inventory.ts"] },
+ { sha: "19db830", date: "2026-06-02", subject: "feat(cli): Tier 2 --format llm renderers (#233)", files: ["inventory.ts"] },
+ { sha: "bee214b", date: "2026-06-02", subject: "fix(inventory): send --path as server-side scope (#229)", files: ["inventory.ts"] },
+ { sha: "97d66ff", date: "2026-05-30", subject: "fix: inventory uses listByKind", files: ["inventory.ts"] },
+ { sha: "0000001", date: "2026-05-01", subject: "fix: an older fix", files: ["inventory.ts"] },
+ ]);
+ expect(recentCommits(git, "inventory.ts").map((c) => c.sha)).toEqual(["d4ed26f", "7ab9034", "bee214b", "97d66ff"]);
+ });
+
+ it("does not repeat a commit that is both newest and a fix", () => {
+ const git = fakeGit([
+ { sha: "a", date: "d", subject: "fix(cli): fail unresolved graph commands (#547)", files: ["resolve.ts"] },
+ { sha: "b", date: "d", subject: "perf: cut ix read", files: ["resolve.ts"] },
+ { sha: "c", date: "d", subject: "fix(mcp): close leaks", files: ["resolve.ts"] },
+ ]);
+ expect(recentCommits(git, "resolve.ts").map((c) => c.sha)).toEqual(["a", "b", "c"]);
+ });
+
+ it("is empty when git cannot answer", () => {
+ expect(recentCommits(() => undefined, "x.ts")).toEqual([]);
+ });
+});
+
+describe("coChangedFiles", () => {
+ it("ranks files that changed with the target, discounting sweeps", () => {
+ const sweep = Array.from({ length: 25 }, (_, i) => `f${i}.ts`);
+ const git = fakeGit([
+ { sha: "1", date: "d", subject: "s", files: ["inventory.ts", "rank.ts", "api.ts"] },
+ { sha: "2", date: "d", subject: "s", files: ["inventory.ts", "rank.ts"] },
+ { sha: "3", date: "d", subject: "s", files: ["inventory.ts", "api.ts", "a.ts", "b.ts", "c.ts", "d.ts"] },
+ { sha: "4", date: "d", subject: "s", files: ["inventory.ts", "once.ts"] },
+ { sha: "5", date: "d", subject: "sweep", files: ["inventory.ts", ...sweep] },
+ { sha: "6", date: "d", subject: "sweep", files: ["inventory.ts", ...sweep] },
+ ]);
+ const found = coChangedFiles(git, "inventory.ts", new Set());
+ expect(found.map((c) => c.path)).toEqual(["rank.ts", "api.ts"]);
+ expect(found[0]).toMatchObject({ commits: 2 });
+ });
+
+ it("skips files the bundle has, and tests unless the target is one", () => {
+ const git = fakeGit([
+ { sha: "1", date: "d", subject: "s", files: ["a.ts", "b.ts", "src/__tests__/a.test.ts"] },
+ { sha: "2", date: "d", subject: "s", files: ["a.ts", "b.ts", "src/__tests__/a.test.ts"] },
+ ]);
+ expect(coChangedFiles(git, "a.ts", new Set(["b.ts"]))).toEqual([]);
+ expect(coChangedFiles(git, "src/__tests__/a.test.ts", new Set()).map((c) => c.path)).toEqual(["a.ts", "b.ts"]);
+ });
+});
+
+describe("gitRunner", () => {
+ let dir: string | undefined;
+ afterEach(() => {
+ if (dir) rmSync(dir, { recursive: true, force: true });
+ dir = undefined;
+ });
+
+ it("reads a real repository's log, and returns undefined outside one", () => {
+ dir = mkdtempSync(join(tmpdir(), "ix-history-"));
+ expect(gitRunner(dir)(["log", "-1"])).toBeUndefined();
+ const git = (...args: string[]) => execFileSync("git", args, { cwd: dir, stdio: "ignore" });
+ git("init", "-q");
+ git("config", "user.email", "[email protected]");
+ git("config", "user.name", "t");
+ for (const [i, subject] of ["feat: add a", "fix: a handles b"].entries()) {
+ writeFileSync(join(dir, "a.ts"), `// ${i}\n`);
+ writeFileSync(join(dir, "b.ts"), `// ${i}\n`);
+ git("add", ".");
+ git("commit", "-q", "-m", subject);
+ }
+ const run = gitRunner(dir);
+ expect(recentCommits(run, "a.ts").map((c) => c.subject)).toEqual(["fix: a handles b", "feat: add a"]);
+ expect(coChangedFiles(run, "a.ts", new Set()).map((c) => [c.path, c.commits])).toEqual([["b.ts", 2]]);
+ });
+});
+
+describe("recent commits in a bundle", () => {
+ it("is one provenance row naming each commit, right after the related files", () => {
+ const facts: ContextFacts = {
+ id: "f", name: "resolve.ts", kind: "file", path: "ix-cli/src/cli/resolve.ts",
+ members: [], memberCount: 0, callerCount: 0, calleeCount: 0, dependentCount: 0, importerCount: 0,
+ topCallers: [], topDependents: [], historyLength: 1, introducedRev: 1, stale: false, diagnostics: [],
+ relatedRefs: [{ id: "r", name: "locate.ts", kind: "file", path: "src/locate.ts", score: 1, reason: "x", via: [] }],
+ importRefs: [{ id: "i", name: "ui.ts", kind: "file", path: "src/ui.ts" }],
+ recentCommits: [
+ { sha: "df30296", date: "2026-09-06", subject: "fix(cli): fail unresolved graph commands (#547)" },
+ { sha: "958d679", date: "2026-08-23", subject: "perf: cut ix read (#494)" },
+ ],
+ };
+ const bundle = buildBundle({
+ resolved: { id: "f", name: "resolve.ts", kind: "file", resolutionMode: "exact" },
+ facts,
+ context: {
+ claims: [], conflicts: [], decisions: [], intents: [], nodes: [], edges: [],
+ metadata: { query: "", seedEntities: [], hopsExpanded: 1, asOfRev: 1 },
+ } as never,
+ provenance: {},
+ budgets: clampBudgets({}),
+ isStale: () => false,
+ });
+ const titles = bundle.evidence.map((e) => e.title);
+ const at = titles.findIndex((t) => t.startsWith("recent commits to resolve.ts:"));
+ expect(titles[at]).toBe(
+ "recent commits to resolve.ts: df30296 fix(cli): fail unresolved graph commands (#547); 958d679 perf: cut ix read (#494)");
+ expect(bundle.evidence[at].kind).toBe("provenance");
+ expect(titles[at - 1]).toMatch(/^related files:/);
+ expect(titles[at + 1]).toBe("imports ui.ts");
+ });
+});
diff --git a/ix-cli/src/cli/commands/context.ts b/ix-cli/src/cli/commands/context.ts
index e78ad839..06b87289 100644
--- a/ix-cli/src/cli/commands/context.ts
+++ b/ix-cli/src/cli/commands/context.ts
@@ -22,6 +22,7 @@ import { getEndpoint, resolveWorkspaceRoot } from "../config.js";
import { collectFacts, type ContextFacts, type EntityLocation } from "../explain/facts.js";
import { collectRelatedFiles, MAX_RELATED, type RelatedRef } from "../explain/related-files.js";
import { collectTextReferences, gitRepoAccess, type TextSource } from "../explain/text-references.js";
+import { coChangedFiles, gitRunner, recentCommits, type CommitRef } from "../explain/history.js";
import { llmLine, llmShortId, printLlmLines } from "../llm.js";
import { parseBudgetOption, parsePickOption, parseRevisionOption } from "../options.js";
import { activeReadScope, resolveFileOrReport } from "../resolve.js";
@@ -1459,11 +1460,56 @@ async function collectContextFacts(
const facts = await collectFacts(client, resolved.id, resolved.name, resolved.kind, "context");
const graphRefs = await collectRelatedFiles(client, resolved, facts).catch(() => []);
const textRefs = await collectTextRelated(client, facts, graphRefs).catch(() => []);
+ const history = await collectHistory(client, facts, [...graphRefs, ...textRefs]).catch(() => undefined);
// Added to the graph's files, not ranked against them. Put first and sharing
// the eight slots, they displaced graph finds the benchmark needed
// (`main.ts` for `mcp/runner.ts`) with mentions that led nowhere.
- const relatedRefs = [...graphRefs.slice(0, MAX_RELATED), ...textRefs];
- return relatedRefs.length > 0 ? { ...facts, relatedRefs } : facts;
+ const relatedRefs = [...graphRefs.slice(0, MAX_RELATED), ...textRefs, ...(history?.coChanged ?? [])];
+ return {
+ ...facts,
+ ...(relatedRefs.length > 0 ? { relatedRefs } : {}),
+ ...(history?.recent.length ? { recentCommits: history.recent } : {}),
+ };
+}
+
+/**
+ * The target file's recent commits, and the files that changed with it. From
+ * the working tree's git, so absent outside a checkout. See `explain/history.ts`.
+ */
+async function collectHistory(
+ client: IxClient,
+ facts: ContextFacts,
+ related: RelatedRef[],
+): Promise<{ recent: CommitRef[]; coChanged: RelatedRef[] } | undefined> {
+ if (!facts.path) return undefined;
+ const git = gitRunner(resolveWorkspaceRoot());
+ const known = new Set<string>([facts.path]);
+ for (const ref of [
+ ...(facts.importRefs ?? []), ...(facts.calleeRefs ?? []), ...(facts.topCallerRefs ?? []),
+ ...(facts.topDependentRefs ?? []), ...(facts.neighbourRefs ?? []), ...related,
+ ]) {
+ if (ref.path) known.add(ref.path);
+ }
+ const recent = recentCommits(git, facts.path);
+ const coChanged = await Promise.all(coChangedFiles(git, facts.path, known).map(async (c) => {
+ const name = c.path.split("/").pop()!;
+ const id = await fileNodeId(client, c.path);
+ const named = `changed with the target in ${c.commits} commits`;
+ return { id, name, kind: "file", path: c.path, score: c.score, reason: named, via: [], named };
+ }));
+ return { recent, coChanged };
+}
+
+/**
+ * A file's graph node id, for an entity the rest of the bundle can refer to.
+ * Scoped: a backend holding two checkouts of one repository has two. Falls
+ * back to a synthetic id rather than dropping a file the graph has not seen.
+ */
+async function fileNodeId(client: IxClient, path: string): Promise<string> {
+ const name = path.split("/").pop()!;
+ const nodes = await client.search(name, { kind: "file", nameOnly: true, limit: 10, ...activeReadScope() })
+ .catch(() => []);
+ return nodes.find((n) => relativePath(n.provenance?.sourceUri) === path)?.id ?? `file:${path}`;
}
/** Imported files whose text is read for names, after the target's own. */
@@ -1498,19 +1544,10 @@ async function collectTextRelated(
if (ref.path) known.add(ref.path);
}
const found = collectTextReferences(repo, sources, known);
- const scope = activeReadScope();
- return Promise.all(found.map(async (ref): Promise<RelatedRef> => {
- const name = ref.path.split("/").pop()!;
- // The file's node, for an entity id the rest of the bundle can refer to.
- // Scoped: a backend holding two checkouts of one repository has two.
- const nodes = await client.search(name, { kind: "file", nameOnly: true, limit: 10, ...scope })
- .catch(() => []);
- const node = nodes.find((n) => relativePath(n.provenance?.sourceUri) === ref.path);
- return {
- id: node?.id ?? `file:${ref.path}`, name, kind: "file", path: ref.path,
- score: ref.score, reason: ref.reason, via: [], named: ref.reason,
- };
- }));
+ return Promise.all(found.map(async (ref): Promise<RelatedRef> => ({
+ id: await fileNodeId(client, ref.path), name: ref.path.split("/").pop()!, kind: "file", path: ref.path,
+ score: ref.score, reason: ref.reason, via: [], named: ref.reason,
+ })));
}
export function buildBundle(input: BuildInput): ContextBundle {
@@ -1846,6 +1883,19 @@ function rankEvidence(input: {
refs: relatedRefs.map((ref) => ref.id),
});
}
+ // What happened to the target's file lately. The subjects carry what a
+ // one-hop bundle cannot: that the sibling commands were already fixed for
+ // the same condition, or that the same bug was fixed next door.
+ const commits = input.facts.recentCommits ?? [];
+ if (commits.length > 0) {
+ const file = (input.facts.path ?? "").split("/").pop();
+ structural.push({
+ id: "recent-commits", source: "git.history",
+ title: `recent commits to ${file}: ${commits.map((c) => `${c.sha} ${c.subject}`).join("; ")}`,
+ reason: `newest first (${commits.map((c) => c.date).join(", ")}); \`git show <sha>\` for the change`,
+ refs: [],
+ });
+ }
// Then outward. The file an answer lives in is most often one the target
// imports: measured on the benchmark task set, 6 of 19 tasks' answers are a
// direct import of their entry point, and none were in the bundle. These go
@@ -1886,7 +1936,9 @@ function rankEvidence(input: {
}
pushMembers(leadingMembers.slice(MEMBERS_BEFORE_OUTWARD));
structural.forEach((item, index) => {
- items.push({ ...item, kind: "structural", score: 10 + index });
+ // Recent commits are provenance -- where the file's current shape came
+ // from -- and keep to the stable kinds consumers already route on.
+ items.push({ ...item, kind: item.source === "git.history" ? "provenance" : "structural", score: 10 + index });
});
for (const scored of input.context.claims) {
@@ -2065,6 +2117,7 @@ const CUT_LABELS: Record<string, string> = {
"facts.callees": "call",
"facts.neighbours": "neighbouring definition",
"facts.related": "related file",
+ "git.history": "recent commits",
"facts.callers": "caller",
"facts.dependents": "dependent",
"context.claims": "claim",
diff --git a/ix-cli/src/cli/explain/facts.ts b/ix-cli/src/cli/explain/facts.ts
index feb31ef8..178717f8 100644
--- a/ix-cli/src/cli/explain/facts.ts
+++ b/ix-cli/src/cli/explain/facts.ts
@@ -7,6 +7,7 @@ import { isRawId } from "../resolve.js";
import { isFileStale } from "../stale.js";
import { buildDependencyTree } from "../commands/depends.js";
import { getSystemPath } from "../hierarchy.js";
+import type { CommitRef } from "./history.js";
import type { RelatedRef } from "./related-files.js";
/** A related entity and where it is defined. */
@@ -75,6 +76,8 @@ export interface EntityFacts {
* only: the walk costs a second round of requests that `explain` does not need.
*/
relatedRefs?: RelatedRef[];
+ /** The target file's latest commits, newest first. `ix context` only. */
+ recentCommits?: CommitRef[];
/**
* What the target itself reaches: the files it imports and the functions it
diff --git a/ix-cli/src/cli/explain/history.ts b/ix-cli/src/cli/explain/history.ts
new file mode 100644
index 00000000..872f371f
--- /dev/null
+++ b/ix-cli/src/cli/explain/history.ts
@@ -0,0 +1,123 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { execFileSync } from "node:child_process";
+
+import { isTestPath } from "./related-files.js";
+
+/**
+ * What git remembers about a context target's file.
+ *
+ * Bundles carried no history: the `provenance` row counts graph patch
+ * revisions, not commits. On ix-bench's historical-bug tasks the clue was in
+ * the log all along. The last commit to touch `resolve.ts` before the
+ * `locate` exit-code fix is "fix(cli): fail unresolved graph commands
+ * (#547)", which changed every sibling command but `locate`; the history of
+ * `inventory.ts` holds "send --path as server-side scope (#229)", the same bug
+ * fixed in the command next to the one the rank task asks about.
+ *
+ * Two things are read, both from the working tree's git, both best-effort:
+ *
+ * - the target file's most recent commits (hash, date, subject);
+ * - files that changed together with it. A commit's weight is split across
+ * the files it touched, so a sweeping refactor says little about any one
+ * pair; commits touching more than `MAX_COMMIT_FILES` files count nothing,
+ * and a file must have changed with the target at least twice. On 253
+ * held-out co-change samples, mined strictly from history before each
+ * commit, the top three raised bundle recall from 0.701 to 0.764.
+ */
+
+export interface CommitRef {
+ sha: string;
+ date: string;
+ subject: string;
+}
+
+export interface CoChange {
+ path: string;
+ /** Commits that changed both files. */
+ commits: number;
+ /** Sum over those commits of 1 / (files the commit touched). */
+ score: number;
+}
+
+/** Runs `git <args>` in the repository and returns stdout, or undefined. */
+export type GitRunner = (args: string[]) => string | undefined;
+
+/** Newest commits shown, whatever they are. */
+export const RECENT_COMMITS = 2;
+/** Newest fixes shown besides them. */
+export const RECENT_FIXES = 2;
+/** Commits the newest ones and the fixes are chosen from. */
+const RECENT_WINDOW = 10;
+/** A conventional `fix:` / `fix(scope):`, or a subject that says fix, bug or revert. */
+const FIX_SUBJECT = /^(?:fix|bugfix|hotfix|revert)\b|\b(?:fix(?:es|ed)?|bug|regression)\b/i;
+export const MAX_CO_CHANGES = 3;
+/** Commits of the target's file read for co-change. */
+const HISTORY_DEPTH = 100;
+/** A commit touching more files than this is a sweep, not a pairing. */
+const MAX_COMMIT_FILES = 20;
+/** Times a file must have changed with the target to count. */
+const MIN_CO_CHANGES = 2;
+
+/**
+ * The newest commits to `path`, plus its newest fixes, newest first.
+ *
+ * The newest alone missed the clue on ix-bench's rank task: the fix to the
+ * same bug in `inventory.ts` (#229) was that file's fifth commit, behind
+ * three features. A fix is where a file's bug knowledge lives.
+ */
+export function recentCommits(git: GitRunner, path: string): CommitRef[] {
+ const out = git(["log", `-${RECENT_WINDOW}`, "--format=%h%x09%ad%x09%s", "--date=short", "--", path]);
+ if (!out) return [];
+ const all = out.split("\n").filter(Boolean).map((line) => {
+ const [sha, date, ...subject] = line.split("\t");
+ return { sha, date, subject: subject.join("\t") };
+ });
+ const chosen = new Set([
+ ...all.slice(0, RECENT_COMMITS),
+ ...all.filter((c) => FIX_SUBJECT.test(c.subject)).slice(0, RECENT_FIXES),
+ ]);
+ return all.filter((c) => chosen.has(c));
+}
+
+export function coChangedFiles(
+ git: GitRunner,
+ path: string,
+ exclude: ReadonlySet<string>,
+ limit = MAX_CO_CHANGES,
+): CoChange[] {
+ // --full-diff lists every file each commit touched, not only `path`: one
+ // call instead of one `git show` per commit.
+ const out = git(["log", `-${HISTORY_DEPTH}`, "--format=@%h", "--name-only", "--full-diff", "--", path]);
+ if (!out) return [];
+ const targetIsTest = isTestPath(path);
+ const tally = new Map<string, CoChange>();
+ for (const block of out.split("@").slice(1)) {
+ const files = [...new Set(block.split("\n").slice(1).map((l) => l.trim()).filter(Boolean))];
+ if (files.length > MAX_COMMIT_FILES || !files.includes(path)) continue;
+ for (const file of files) {
+ if (file === path || exclude.has(file) || (!targetIsTest && isTestPath(file))) continue;
+ const c = tally.get(file) ?? { path: file, commits: 0, score: 0 };
+ c.commits += 1;
+ c.score += 1 / files.length;
+ tally.set(file, c);
+ }
+ }
+ return [...tally.values()]
+ .filter((c) => c.commits >= MIN_CO_CHANGES)
+ .sort((a, b) => b.score - a.score || (a.path < b.path ? -1 : a.path > b.path ? 1 : 0))
+ .slice(0, limit);
+}
+
+/** `git` in `root`, or undefined when it fails (not a checkout, no history). */
+export function gitRunner(root: string): GitRunner {
+ return (args) => {
+ try {
+ return execFileSync("git", args, {
+ cwd: root, encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 16 * 1024 * 1024,
+ });
+ } catch {
+ return undefined;
+ }
+ };
+}