Understand any codebase instantly. System intelligence for codebases, built for humans and AI.
TypeScript aiai-memoryclaude-codeclicode-analysiscode-mappingcode-memorycodebase-understandingcodexdeveloper-toolsllmopenclawpersistent-memoryprogram-analysissoftware-architecturesystem-intelligencesystem-mapping
perf(context): keep a BM25 term index for --from-issue under IX_HOME
KageBinary368870ee0c50
diff --git a/ix-cli/src/cli/__tests__/bm25-cache.test.ts b/ix-cli/src/cli/__tests__/bm25-cache.test.tsnew file mode 100644index 00000000..a12125e6--- /dev/null+++ b/ix-cli/src/cli/__tests__/bm25-cache.test.ts@@ -0,0 +1,181 @@+// Copyright 2026 Ix Infrastructure Inc.++import { execFileSync } from "node:child_process";+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { afterEach, beforeEach, describe, expect, it } from "vitest";++import { bm25IndexPath, cachedBm25Ranker, readGitState } from "../explain/bm25-cache.js";+import { bm25Rank, isSourcePath, MAX_BM25_BYTES } from "../explain/issue.js";+import { gitRepoAccess, type RepoAccess } from "../explain/text-references.js";++const QUERIES = [+ "The login page crashes when the password is empty; see `validatePassword`",+ "listByKind returns nothing for a scoped kind -- constructor toString hasOwnProperty",+ "session token refresh races the logout handler",+];++let dir: string;+let home: string;++function write(path: string, text: string) {+ mkdirSync(dirname(join(dir, path)), { recursive: true });+ writeFileSync(join(dir, path), text);+}++function git(...args: string[]) {+ return execFileSync("git", ["-c", "[email protected]", "-c", "user.name=t", ...args], { cwd: dir, encoding: "utf-8" });+}++/** A repo access that counts reads, so a test can tell a hit from a rebuild. */+function counting(repo: RepoAccess): RepoAccess & { reads: string[] } {+ const reads: string[] = [];+ return { ...repo, reads, read: (path) => { reads.push(path); return repo.read(path); } };+}++function sourceFiles(repo: RepoAccess) {+ return repo.files().filter(isSourcePath);+}++beforeEach(() => {+ dir = mkdtempSync(join(tmpdir(), "ix-bm25-cache-"));+ home = mkdtempSync(join(tmpdir(), "ix-bm25-home-"));+ process.env.IX_HOME = home;+ git("init", "-q");+ write("src/auth/login.ts", "export function validatePassword(p: string) { if (!p) throw new Error('empty password'); }\n");+ write("src/auth/session.ts", "export function refreshToken() {}\nexport function logout() { /* session token */ }\n");+ write("src/list.ts", "export function listByKind(kind: string) { return []; } // constructor toString\n");+ write("src/big.ts", `// ${"x".repeat(MAX_BM25_BYTES + 10)}\n`);+ write("src/util/strings.ts", "export const constructor = 1; export function hasOwnProperty() {}\n");+ git("add", ".");+ git("commit", "-q", "-m", "init");+});++afterEach(() => {+ delete process.env.IX_HOME;+ rmSync(dir, { recursive: true, force: true });+ rmSync(home, { recursive: true, force: true });+});++describe("cachedBm25Ranker", () => {+ it("scores exactly as bm25Rank, building the index on the first call and reading it after", async () => {+ const repo = gitRepoAccess(dir)!;+ const files = sourceFiles(repo);+ const rank = cachedBm25Ranker(dir);++ // Cold: builds and stores the index.+ for (const q of QUERIES) expect(rank(repo, files, q)).toEqual(bm25Rank(repo, files, q));+ expect(existsSync(bm25IndexPath(dir))).toBe(true);+ expect(bm25IndexPath(dir).startsWith(home)).toBe(true);++ // Warm: no file is read at all.+ const watched = counting(repo);+ for (const q of QUERIES) {+ expect(rank(watched, files, q)).toEqual(bm25Rank(repo, files, q));+ }+ expect(watched.reads).toEqual([]);+ });++ it("reads a file that differs from HEAD fresh, staged or not, and leaves the rest to the index", async () => {+ const repo = gitRepoAccess(dir)!;+ const files = sourceFiles(repo);+ cachedBm25Ranker(dir)(repo, files, QUERIES[0]); // build at HEAD++ write("src/auth/session.ts", "export function logout() { validatePassword(''); password password }\n");+ write("src/list.ts", "export const nothing = 0;\n");+ git("add", "src/list.ts");++ const watched = counting(repo);+ const cached = cachedBm25Ranker(dir)(watched, files, QUERIES[0]);++ expect(cached).toEqual(bm25Rank(repo, files, QUERIES[0]));+ expect(watched.reads.sort()).toEqual(["src/auth/session.ts", "src/list.ts"]);+ });++ it("does not store a dirty file's text under HEAD", async () => {+ write("src/auth/login.ts", "export const changed = 'nothing about passwords';\n");+ const repo = gitRepoAccess(dir)!;+ const files = sourceFiles(repo);+ cachedBm25Ranker(dir)(repo, files, QUERIES[0]); // build while login.ts is dirty++ git("checkout", "--", "src/auth/login.ts"); // back to HEAD's text+ const cached = cachedBm25Ranker(dir)(repo, files, QUERIES[0]);++ expect(cached).toEqual(bm25Rank(repo, files, QUERIES[0]));+ expect(cached[0].path).toBe("src/auth/login.ts");+ });++ it("rebuilds when HEAD moves", async () => {+ const repo = gitRepoAccess(dir)!;+ cachedBm25Ranker(dir)(repo, sourceFiles(repo), QUERIES[2]);+ const before = JSON.parse(readFileSync(bm25IndexPath(dir), "utf-8")).head;++ write("src/auth/refresh.ts", "export function refreshSessionToken() { /* races logout */ }\n");+ git("add", ".");+ git("commit", "-q", "-m", "more");+ const moved = gitRepoAccess(dir)!;+ const files = sourceFiles(moved);++ expect(cachedBm25Ranker(dir)(moved, files, QUERIES[2])).toEqual(bm25Rank(moved, files, QUERIES[2]));+ expect(JSON.parse(readFileSync(bm25IndexPath(dir), "utf-8")).head).not.toBe(before);+ });++ it("keeps skipping a file too large to score without reading it again", async () => {+ const repo = gitRepoAccess(dir)!;+ const files = sourceFiles(repo);+ const rank = cachedBm25Ranker(dir);+ rank(repo, files, QUERIES[1]);++ const watched = counting(repo);+ rank(watched, files, QUERIES[1]);++ expect(JSON.parse(readFileSync(bm25IndexPath(dir), "utf-8")).skipped).toEqual(["src/big.ts"]);+ expect(watched.reads).toEqual([]);+ });++ it("ignores an index from another version, root or commit, and a corrupt one", async () => {+ const repo = gitRepoAccess(dir)!;+ const files = sourceFiles(repo);+ const rank = cachedBm25Ranker(dir);+ rank(repo, files, QUERIES[0]);+ const path = bm25IndexPath(dir);+ const good = JSON.parse(readFileSync(path, "utf-8"));++ for (const bad of [{ ...good, v: 0 }, { ...good, root: "/elsewhere" }, { ...good, head: "0".repeat(40) }, "{not json"]) {+ writeFileSync(path, typeof bad === "string" ? bad : JSON.stringify(bad));+ const watched = counting(repo);+ expect(rank(watched, files, QUERIES[0])).toEqual(bm25Rank(repo, files, QUERIES[0]));+ expect(watched.reads.length).toBeGreaterThan(0);+ }+ });++ it("falls back to plain BM25 outside a git checkout", async () => {+ const repo = gitRepoAccess(dir)!;+ const files = sourceFiles(repo);+ const rank = cachedBm25Ranker(dir, { state: () => undefined });++ expect(rank(repo, files, QUERIES[0])).toEqual(bm25Rank(repo, files, QUERIES[0]));+ expect(existsSync(bm25IndexPath(dir))).toBe(false);+ });+});++describe("readGitState", () => {+ it("lists paths relative to a subdirectory root, as git ls-files there does", () => {+ write("src/auth/login.ts", "changed\n");+ const sub = join(dir, "src");+ const state = readGitState(sub)!;+ expect([...state.dirty]).toEqual(["auth/login.ts"]);+ expect(gitRepoAccess(sub)!.files()).toContain("auth/login.ts");+ });++ it("is undefined before the first commit", () => {+ const empty = mkdtempSync(join(tmpdir(), "ix-bm25-empty-"));+ try {+ execFileSync("git", ["init", "-q"], { cwd: empty });+ expect(readGitState(empty)).toBeUndefined();+ } finally {+ rmSync(empty, { recursive: true, force: true });+ }+ });+});diff --git a/ix-cli/src/cli/commands/context.ts b/ix-cli/src/cli/commands/context.tsindex c3d4b828..7200f908 100644--- a/ix-cli/src/cli/commands/context.ts+++ b/ix-cli/src/cli/commands/context.ts@@ -35,6 +35,7 @@ import {type SymbolHit,} from "../explain/issue.js";import { collectRelatedFiles, MAX_RELATED, type RelatedRef } from "../explain/related-files.js";+import { cachedBm25Ranker } from "../explain/bm25-cache.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";@@ -1650,8 +1651,10 @@ async function buildIssueBundle(const client = new IxClient(getEndpoint(), undefined, QUERY_CLIENT_OPTIONS);await ensureReadScope(client);const scope = activeReadScope();+ const root = resolveWorkspaceRoot();const plan = await planIssue(text, {- repo: gitRepoAccess(resolveWorkspaceRoot()),+ repo: gitRepoAccess(root),+ rank: cachedBm25Ranker(root),search: async (name) =>(await client.search(name, { limit: ISSUE_SEARCH_LIMIT, nameOnly: true, ...scope })).map(symbolHit),});diff --git a/ix-cli/src/cli/explain/bm25-cache.ts b/ix-cli/src/cli/explain/bm25-cache.tsnew file mode 100644index 00000000..d713279b--- /dev/null+++ b/ix-cli/src/cli/explain/bm25-cache.ts@@ -0,0 +1,215 @@+// Copyright 2026 Ix Infrastructure Inc.++import { execFileSync } from "node:child_process";+import { createHash } from "node:crypto";+import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";+import { dirname, join } from "node:path";++import { ixHome } from "../ix-home.js";+import {+ bm25Doc,+ bm25QueryTerms,+ bm25Rank,+ bm25Score,+ MAX_BM25_BYTES,+ type Bm25Doc,+ type Bm25Hit,+} from "./issue.js";+import type { RepoAccess } from "./text-references.js";++/**+ * A term index of the tracked source files, so `ix context --from-issue` does+ * not read and tokenize every one of them on every call.+ *+ * Without it BM25 opens every tracked source file (up to 200 KB each) per+ * issue: measured at 56 ms on the Ix repository and ~400 ms on apache/dubbo+ * (2,427 files), paid again for the next issue against the same checkout.+ *+ * Keyed by the commit, so the index describes the files AS COMMITTED: it is+ * built from the working tree, but only files that match HEAD are stored, and+ * files that differ from HEAD (`git diff HEAD`, staged or not) are always read+ * fresh. Git decides what is dirty, including the racily-clean case a size and+ * mtime check would miss, so a hit scores exactly the text a fresh read would.+ * One index per workspace root, replaced when HEAD moves.+ *+ * Scores are bit-identical to `bm25Rank`: the same documents go through the+ * same `bm25Score`. Bump INDEX_VERSION whenever `bm25Tokens` or `bm25Doc`+ * changes what a document is, or a stale index would score the old way.+ */+const INDEX_VERSION = 1;++interface Bm25Index {+ v: number;+ root: string;+ head: string;+ maxBytes: number;+ /** Clean files that were scored, and each one's length in words. */+ paths: string[];+ lengths: number[];+ /** Clean files that were not scored (too large or unreadable at HEAD). */+ skipped: string[];+ /** Every word, to a flat list of [document index, count] pairs. */+ postings: Record<string, number[]>;+}++/** What the working tree is, as far as the index is concerned. */+export interface GitState {+ head: string;+ /** Tracked paths (relative to the root, as `git ls-files` prints them) that differ from HEAD. */+ dirty: ReadonlySet<string>;+}++/** Path of the index for one workspace root, under IX_HOME. */+export function bm25IndexPath(root: string): string {+ const key = createHash("sha256").update(root).digest("hex").slice(0, 12);+ return join(ixHome(), "cache", `bm25_${key}.json`);+}++/**+ * HEAD and the files that differ from it, or undefined outside a checkout (or+ * on an unborn branch). `--no-optional-locks` because this runs in whatever+ * checkout the user is in, and a read must not rewrite its index file.+ */+export function readGitState(root: string): GitState | undefined {+ try {+ const run = (args: string[]) => execFileSync("git", ["--no-optional-locks", ...args], {+ cwd: root, encoding: "utf-8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 64 * 1024 * 1024,+ });+ const head = run(["rev-parse", "--verify", "-q", "HEAD"]).trim();+ if (!head) return undefined;+ // --relative: paths relative to `root`, like `git ls-files` run there.+ // --no-renames: a rename lists both of its paths, not only the new one.+ const dirty = run(["diff", "--name-only", "--relative", "--no-renames", "-z", "HEAD", "--"]);+ return { head, dirty: new Set(dirty.split("\0").filter(Boolean)) };+ } catch {+ return undefined;+ }+}++/**+ * A `planIssue` ranker that reads through the index for `root`. Falls back to+ * plain `bm25Rank` when there is no git state to key it by.+ */+export function cachedBm25Ranker(+ root: string,+ opts: { state?: () => GitState | undefined; indexPath?: string } = {},+): (repo: RepoAccess, files: string[], query: string) => Bm25Hit[] {+ return (repo, files, query) => {+ const readState = opts.state ?? (() => readGitState(root));+ const state = readState();+ if (!state) return bm25Rank(repo, files, query);+ const indexPath = opts.indexPath ?? bm25IndexPath(root);+ const terms = bm25QueryTerms(query);+ const index = loadIndex(indexPath, root, state.head);+ if (index) return bm25Score(docsFromIndex(index, repo, files, terms, state.dirty), terms);++ const { docs, built } = buildIndex(repo, files, terms, state, root);+ // Only if nothing moved while the files were being read: a file edited in+ // that window would otherwise be stored as HEAD's text.+ const after = readState();+ if (after && after.head === state.head && sameSet(after.dirty, state.dirty)) saveIndex(indexPath, built);+ return bm25Score(docs, terms);+ };+}++function docsFromIndex(+ index: Bm25Index,+ repo: Pick<RepoAccess, "read">,+ files: string[],+ terms: string[],+ dirty: ReadonlySet<string>,+): Map<string, Bm25Doc> {+ const position = new Map(index.paths.map((path, i) => [path, i]));+ const skipped = new Set(index.skipped);+ // Only the query's words, as bm25Rank counts them.+ const tfs: Array<Map<string, number> | undefined> = new Array(index.paths.length);+ for (const term of terms) {+ if (!Object.hasOwn(index.postings, term)) continue;+ const list = index.postings[term];+ for (let k = 0; k < list.length; k += 2) (tfs[list[k]] ??= new Map()).set(term, list[k + 1]);+ }+ const wanted = new Set(terms);+ const docs = new Map<string, Bm25Doc>();+ for (const path of files) {+ if (!dirty.has(path)) {+ const i = position.get(path);+ if (i !== undefined) {+ docs.set(path, { tf: tfs[i] ?? new Map(), length: index.lengths[i] });+ continue;+ }+ if (skipped.has(path)) continue;+ }+ // Dirty, or (should not happen at one HEAD) a file the index never saw.+ const doc = bm25Doc(path, repo.read(path), wanted);+ if (doc) docs.set(path, doc);+ }+ return docs;+}++function buildIndex(+ repo: Pick<RepoAccess, "read">,+ files: string[],+ terms: string[],+ state: GitState,+ root: string,+): { docs: Map<string, Bm25Doc>; built: Bm25Index } {+ const built: Bm25Index = {+ v: INDEX_VERSION, root, head: state.head, maxBytes: MAX_BM25_BYTES,+ paths: [], lengths: [], skipped: [],+ // No prototype: `constructor` and `tostring` are words too.+ postings: Object.create(null) as Record<string, number[]>,+ };+ const docs = new Map<string, Bm25Doc>();+ for (const path of files) {+ const full = bm25Doc(path, repo.read(path));+ const clean = !state.dirty.has(path);+ if (!full) {+ if (clean) built.skipped.push(path);+ continue;+ }+ if (clean) {+ const i = built.paths.length;+ built.paths.push(path);+ built.lengths.push(full.length);+ for (const [term, count] of full.tf) (built.postings[term] ??= []).push(i, count);+ }+ const tf = new Map<string, number>();+ for (const term of terms) {+ const count = full.tf.get(term);+ if (count) tf.set(term, count);+ }+ docs.set(path, { tf, length: full.length });+ }+ return { docs, built };+}++function loadIndex(path: string, root: string, head: string): Bm25Index | undefined {+ try {+ const data = JSON.parse(readFileSync(path, "utf-8")) as Partial<Bm25Index>;+ if (data.v !== INDEX_VERSION || data.root !== root || data.head !== head || data.maxBytes !== MAX_BM25_BYTES) return undefined;+ if (!Array.isArray(data.paths) || !Array.isArray(data.lengths) || !Array.isArray(data.skipped)) return undefined;+ if (data.paths.length !== data.lengths.length || !data.postings || typeof data.postings !== "object") return undefined;+ return data as Bm25Index;+ } catch {+ return undefined;+ }+}++/** Best-effort: an index that cannot be written only costs the next call a rebuild. */+function saveIndex(path: string, index: Bm25Index): void {+ const tmp = `${path}.${process.pid}.tmp`;+ try {+ mkdirSync(dirname(path), { recursive: true });+ // Via a temp file and rename, so a reader never sees half a file.+ writeFileSync(tmp, JSON.stringify(index));+ renameSync(tmp, path);+ } catch {+ try { rmSync(tmp, { force: true }); } catch { /* non-critical */ }+ }+}++function sameSet(a: ReadonlySet<string>, b: ReadonlySet<string>): boolean {+ if (a.size !== b.size) return false;+ for (const x of a) if (!b.has(x)) return false;+ return true;+}diff --git a/ix-cli/src/cli/explain/issue.ts b/ix-cli/src/cli/explain/issue.tsindex 52a811ad..2105991c 100644--- a/ix-cli/src/cli/explain/issue.ts+++ b/ix-cli/src/cli/explain/issue.ts@@ -266,6 +266,30 @@ export interface Bm25Hit {score: number;}+/** One file as BM25 reads it: how often each counted word occurs, and its length in words. */+export interface Bm25Doc {+ tf: Map<string, number>;+ length: number;+}++/**+ * A file's text as BM25 reads it, or undefined when it is not scored (too+ * large, or unreadable). `wanted` limits the words counted -- see `bm25Rank`;+ * without it every word is, which is what the on-disk index stores.+ */+export function bm25Doc(path: string, text: string | undefined, wanted?: ReadonlySet<string>): Bm25Doc | undefined {+ if (text === undefined || Buffer.byteLength(text, "utf8") > MAX_BM25_BYTES) return undefined;+ const tf = new Map<string, number>();+ const tokens = bm25Tokens(`${path.replace(/\//g, " ")} ${text}`);+ for (const t of tokens) if (!wanted || wanted.has(t)) tf.set(t, (tf.get(t) ?? 0) + 1);+ return { tf, length: tokens.length };+}++/** The query's distinct BM25 words, in the order it first uses them. */+export function bm25QueryTerms(query: string): string[] {+ return [...new Set(bm25Tokens(query))];+}+/*** Okapi BM25 (k1 1.2, b 0.75) of each file against `query`, best first, files* that share no word with it left out. A file's path is part of its text, so@@ -281,17 +305,27 @@ export function bm25Rank(// Only the query's words are counted: BM25 needs no other term frequency,// and a map of every word of every file is most of the memory and a third// of the time on a large repository. A document's length is still every word.- const terms = [...new Set(bm25Tokens(query))];+ const terms = bm25QueryTerms(query);const wanted = new Set(terms);- const docs = new Map<string, { tf: Map<string, number>; length: number }>();+ const docs = new Map<string, Bm25Doc>();for (const path of files) {- const text = repo.read(path);- if (text === undefined || Buffer.byteLength(text, "utf8") > MAX_BM25_BYTES) continue;- const tf = new Map<string, number>();- const tokens = bm25Tokens(`${path.replace(/\//g, " ")} ${text}`);- for (const t of tokens) if (wanted.has(t)) tf.set(t, (tf.get(t) ?? 0) + 1);- docs.set(path, { tf, length: tokens.length });+ const doc = bm25Doc(path, repo.read(path), wanted);+ if (doc) docs.set(path, doc);}+ return bm25Score(docs, terms, k1, b);+}++/**+ * BM25 of already-tokenized files. Split out of `bm25Rank` so the on-disk+ * index (`bm25-cache.ts`) scores through the very same arithmetic: the same+ * documents in, the same scores out, to the last bit.+ */+export function bm25Score(+ docs: ReadonlyMap<string, Bm25Doc>,+ terms: string[],+ k1 = 1.2,+ b = 0.75,+): Bm25Hit[] {if (docs.size === 0) return [];const n = docs.size;let total = 0;@@ -332,10 +366,16 @@ export interface IssuePlan {*/export async function planIssue(text: string,- deps: { repo?: RepoAccess; search: PickDeps["search"] },+ deps: {+ repo?: RepoAccess;+ search: PickDeps["search"];+ /** BM25 over the source files; `bm25Rank` unless the caller has an index. */+ rank?: (repo: RepoAccess, files: string[], query: string) => Bm25Hit[];+ },): Promise<IssuePlan> {const files = deps.repo?.files() ?? [];- const bm25 = deps.repo ? bm25Rank(deps.repo, files.filter(isSourcePath), text) : [];+ const rank = deps.rank ?? bm25Rank;+ const bm25 = deps.repo ? rank(deps.repo, files.filter(isSourcePath), text) : [];const scores = new Map(bm25.map((h) => [h.path, h.score]));const { starts, unresolved } = await pickStartingPoints(text, {files, search: deps.search, fileScore: (p) => scores.get(p) ?? 0,