Skip to content

armgit / Ix

Public Imported from GitHub
0

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

fix(resolve): prefer the code definition over imports and non-code matches

KageBinary56b8d187f73e
diff --git a/ix-cli/src/cli/__tests__/resolver-definitions-first.test.ts b/ix-cli/src/cli/__tests__/resolver-definitions-first.test.ts
new file mode 100644
index 00000000..b6d9c8ff
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/resolver-definitions-first.test.ts
@@ -0,0 +1,119 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { describe, expect, it, vi } from "vitest";
+
+import { resolveEntityFull, scoreCandidate } from "../resolve.js";
+
+/**
+ * The resolver behind `ix context` / `ix explain` / `ix locate` must pick the
+ * code definition of a name, not an import of it (a `module` entity located in
+ * the importing file) and not a CSS selector, markdown heading or JSON key
+ * that happens to share the name.
+ */
+
+const ALL_KINDS = ["file", "class", "object", "trait", "interface", "module", "method", "function", "constant"];
+
+function n(id: string, name: string, kind: string, path: string, attrs: Record<string, unknown> = {}) {
+ const ext = path.slice(path.lastIndexOf(".") + 1);
+ const language = ({ js: "javascript", ts: "typescript", css: "css", md: "markdown", json: "json" } as Record<string, string>)[ext];
+ return { id, name, kind, provenance: { sourceUri: path }, attrs: { language, line_start: 1, line_end: 20, ...attrs } };
+}
+
+const imp = (id: string, name: string, path: string) => n(id, name, "module", path, { line_start: 2, line_end: 2 });
+
+/** A fake backend honouring `kind` and `limit`. */
+function client(nodes: ReturnType<typeof n>[]) {
+ return {
+ search: vi.fn(async (_term: string, opts: { limit?: number; kind?: string }) => {
+ const matching = opts.kind ? nodes.filter((x) => x.kind === opts.kind) : nodes;
+ return matching.slice(0, opts.limit);
+ }),
+ workspaceSystem: vi.fn(async () => null),
+ } as any;
+}
+
+async function resolvedId(nodes: ReturnType<typeof n>[], symbol: string): Promise<string | undefined> {
+ const result = await resolveEntityFull(client(nodes), symbol, ALL_KINDS, { format: "json" } as any);
+ return result.resolved ? result.entity.id : undefined;
+}
+
+describe("resolver: definitions over imports", () => {
+ it("resolves to the defining file, not the import in another file (tailwind borderStylesReset)", async () => {
+ expect(await resolvedId([
+ imp("import", "borderStylesReset", "src/lib/generateUtilities.js"),
+ n("file", "borderStylesReset.js", "file", "src/generators/borderStylesReset.js"),
+ ], "borderStylesReset")).toBe("file");
+ });
+
+ it("resolves to a same-named function, not its import", async () => {
+ expect(await resolvedId([
+ imp("import", "parseConfig", "src/cli.ts"),
+ n("fn", "parseConfig", "function", "src/config.ts"),
+ ], "parseConfig")).toBe("fn");
+ });
+
+ it("still prefers a same-named function over a same-stem file", async () => {
+ expect(await resolvedId([
+ n("file", "debounce.js", "file", "src/debounce.js"),
+ n("fn", "debounce", "function", "src/debounce.js"),
+ ], "debounce")).toBe("fn");
+ });
+
+ it("finds the defining file when imports fill the candidate window", async () => {
+ const fake = client([
+ ...Array.from({ length: 40 }, (_, i) => imp(`import-${i}`, "borderStylesReset", `src/lib/user${i}.js`)),
+ n("file", "borderStylesReset.js", "file", "src/generators/borderStylesReset.js"),
+ ]);
+ const result = await resolveEntityFull(fake, "borderStylesReset", ALL_KINDS, { format: "json" } as any);
+ expect(result.resolved && result.entity.id).toBe("file");
+ });
+
+ it("does not look further when a definition is in the window", async () => {
+ const fake = client([
+ n("fn", "parseConfig", "function", "src/config.ts"),
+ ...Array.from({ length: 40 }, (_, i) => imp(`import-${i}`, "parseConfig", `src/user${i}.ts`)),
+ ]);
+ await resolveEntityFull(fake, "parseConfig", ALL_KINDS, { format: "json" } as any);
+ expect(fake.search).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe("resolver: code over non-code", () => {
+ it("resolves a function over a CSS selector of the same name", async () => {
+ expect(await resolvedId([
+ n("css", "flex", "class", "src/css/utilities.css"),
+ n("fn", "flex", "function", "src/plugins/flex.js"),
+ ], "flex")).toBe("fn");
+ });
+
+ it("resolves a class over a markdown heading and a JSON key", async () => {
+ expect(await resolvedId([
+ n("heading", "Prettier", "heading", "CHANGELOG.md"),
+ n("json", "Prettier", "config_entry", "package.json"),
+ n("cls", "Prettier", "class", "src/index.js"),
+ ], "Prettier")).toBe("cls");
+ });
+
+ it("resolves the source definition over a copy in build output", async () => {
+ expect(await resolvedId([
+ n("dist", "createServer", "function", "dist/server.js"),
+ n("src", "createServer", "function", "src/node/server.ts"),
+ ], "createServer")).toBe("src");
+ });
+});
+
+describe("scoreCandidate", () => {
+ it("scores a definition better than an import, and an import better than CSS", () => {
+ const fn = scoreCandidate(n("fn", "flex", "function", "src/flex.js"), "flex");
+ const im = scoreCandidate(imp("import", "flex", "src/other.js"), "flex");
+ const css = scoreCandidate(n("css", "flex", "class", "dist/out.css"), "flex");
+ expect(fn).toBeLessThan(im);
+ expect(im).toBeLessThan(css);
+ });
+
+ it("leaves a multi-line module (a real definition) as a container", () => {
+ const mod = scoreCandidate(n("mod", "Billing", "module", "app/billing.rb", { line_start: 1, line_end: 40 }), "Billing");
+ const fn = scoreCandidate(n("fn", "Billing", "function", "app/other.rb"), "Billing");
+ expect(mod).toBeLessThan(fn);
+ });
+});
diff --git a/ix-cli/src/cli/candidate-origin.ts b/ix-cli/src/cli/candidate-origin.ts
new file mode 100644
index 00000000..08d2a3bc
--- /dev/null
+++ b/ix-cli/src/cli/candidate-origin.ts
@@ -0,0 +1,157 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+/**
+ * Where a name-matched candidate comes from, for ranking a code definition
+ * above everything else that merely shares its name.
+ *
+ * Both `ix search` and the entity resolver behind `context` / `explain` /
+ * `locate` match on names, and a name is shared by far more than its
+ * definition:
+ *
+ * - **import** — every `import x from './x'` becomes a single-line `module`
+ * entity named after the specifier stem, located in the IMPORTING file
+ * (core-ingestion `index.ts`, the `import.source` / `import.name` captures).
+ * It is a reference, not a definition, but as a `module` it used to get the
+ * container boost and outrank the definition itself.
+ * - **non-code** — CSS class/id selectors arrive as `class`, keyframes as
+ * `constant`, markdown headings as `heading`/`section`, JSON/YAML/TOML keys
+ * as `config_entry`/`config`. For a term that looks like a code identifier
+ * these are almost never what the caller meant.
+ * - **generated** — copies of the definition in build output (`dist/`,
+ * `build/`, `*.min.js`, `*-output.*`) and stand-ins in fixtures and samples.
+ *
+ * All three are demoted, never dropped: when nothing better matched they are
+ * still the answer.
+ */
+
+type CandidateOrigin = "definition" | "import" | "non-code" | "generated";
+
+/** `attrs.language` values core-ingestion gives to markup, style and data files. */
+const NON_CODE_LANGUAGES = new Set([
+ "css", "scss", "sass", "less", "markdown", "json", "yaml", "toml",
+ "html", "xml", "latex",
+]);
+
+/** Extensions for the same, for nodes that carry no `language` attribute. */
+const NON_CODE_EXTENSIONS = new Set([
+ ".css", ".scss", ".sass", ".less", ".styl",
+ ".md", ".mdx", ".markdown", ".rst", ".txt", ".adoc",
+ ".json", ".jsonc", ".json5", ".yaml", ".yml", ".toml", ".ini", ".lock",
+ ".html", ".htm", ".xml", ".svg", ".tex",
+]);
+
+/** Kinds core-ingestion emits only for docs and config, never for code. */
+const NON_CODE_KINDS = new Set(["heading", "section", "config_entry", "config"]);
+
+/** Build output and other derived copies of source. */
+const GENERATED_PATH_PATTERNS: RegExp[] = [
+ /(^|\/)(dist|build|generated|__generated__|node_modules)\//,
+ /\.min\.[a-z0-9]+$/,
+ /\.bundle\.[a-z0-9]+$/,
+ /[-_.]output\.[a-z0-9]+$/,
+];
+
+/** Test fixtures and sample/demo code: stand-ins, not the definition. */
+const FIXTURE_PATH_PATTERNS: RegExp[] = [
+ /(^|\/)(fixtures?|__fixtures__|__mocks__|testdata|samples?)\//,
+ /(^|\/)[^/]*fixture[^/]*$/,
+];
+
+/** Roles core-ingestion's role-classifier assigns to derived or stand-in files. */
+const DEMOTED_ROLES = new Set(["generated", "fixture"]);
+
+const IDENTIFIER = /^[A-Za-z_$][\w$]*(?:(?:\.|::|#)[A-Za-z_$][\w$]*)*$/;
+const FILE_NAME = /\.(?:[cm]?[jt]sx?|py|rb|go|rs|java|kts?|scala|cs|php|swift|c|h|cc|cpp|hpp|css|scss|less|md|mdx|json|ya?ml|toml|html?|xml|txt)$/i;
+
+/**
+ * True for a term shaped like a code identifier: `flex`, `borderStylesReset`,
+ * `TypeScript`, `Foo.bar`, `Foo::bar`, `$scope`. A term with a hyphen, a space
+ * or a file extension (`border-solid`, `Getting Started`, `package.json`) is
+ * more likely aimed at a selector, a heading or a file, so non-code matches
+ * are left alone for it.
+ */
+export function looksLikeCodeIdentifier(term: string): boolean {
+ return IDENTIFIER.test(term) && !FILE_NAME.test(term);
+}
+
+/**
+ * True when the caller asked for non-code by name (`--kind heading`,
+ * `--language css`): the demotion would then work against the request.
+ */
+export function requestsNonCode(opts?: { kind?: string; language?: string }): boolean {
+ return (!!opts?.kind && NON_CODE_KINDS.has(opts.kind.toLowerCase()))
+ || (!!opts?.language && (NON_CODE_LANGUAGES.has(opts.language.toLowerCase())
+ || NON_CODE_EXTENSIONS.has(`.${opts.language.toLowerCase().replace(/^\./, "")}`)));
+}
+
+function sourcePath(node: any): string {
+ return String(node?.provenance?.sourceUri ?? node?.provenance?.source_uri ?? node?.attrs?.file_uri ?? "")
+ .toLowerCase()
+ .replace(/\\/g, "/");
+}
+
+function extensionOf(path: string): string {
+ const base = path.slice(path.lastIndexOf("/") + 1);
+ const dot = base.lastIndexOf(".");
+ return dot > 0 ? base.slice(dot) : "";
+}
+
+/**
+ * An import entity: a `module` that spans a single line. A module that is
+ * really defined here (Ruby `module`, Elixir `defmodule`, a TS `namespace`)
+ * spans its body and stays a definition.
+ */
+function isImportEntity(node: any): boolean {
+ if ((node?.kind ?? "").toLowerCase() !== "module") return false;
+ const start = node?.attrs?.line_start;
+ const end = node?.attrs?.line_end;
+ return typeof start === "number" && typeof end === "number" && start === end;
+}
+
+function isNonCodeNode(node: any): boolean {
+ const kind = (node?.kind ?? "").toLowerCase();
+ if (NON_CODE_KINDS.has(kind)) return true;
+ const language = String(node?.attrs?.language ?? "").toLowerCase();
+ if (language) return NON_CODE_LANGUAGES.has(language);
+ return NON_CODE_EXTENSIONS.has(extensionOf(sourcePath(node)));
+}
+
+function isGeneratedOrFixture(node: any): boolean {
+ if (DEMOTED_ROLES.has(String(node?.attrs?.role ?? ""))) return true;
+ const path = sourcePath(node);
+ if (!path) return false;
+ return GENERATED_PATH_PATTERNS.some((p) => p.test(path))
+ || FIXTURE_PATH_PATTERNS.some((p) => p.test(path));
+}
+
+/**
+ * Classify a candidate. Precedence: generated first (a CSS selector in
+ * `tailwind-output.css` is build output before it is CSS), then import, then
+ * non-code.
+ */
+export function candidateOrigin(node: any): CandidateOrigin {
+ if (isGeneratedOrFixture(node)) return "generated";
+ if (isImportEntity(node)) return "import";
+ if (isNonCodeNode(node)) return "non-code";
+ return "definition";
+}
+
+/**
+ * The file-name stem of a `file` node: `borderStylesReset.js` →
+ * `borderstylesreset` (one extension only, so `x.test.js` is not a stem
+ * match for `x`). A module that is one anonymous default export has no
+ * symbol of its own name — its file IS the definition — so a file whose stem
+ * equals the term is a name match, not the partial match the backend scores it
+ * as.
+ */
+function fileStem(node: any): string | undefined {
+ if ((node?.kind ?? "").toLowerCase() !== "file") return undefined;
+ const name = String(node?.name ?? node?.attrs?.name ?? "");
+ const dot = name.lastIndexOf(".");
+ return (dot > 0 ? name.slice(0, dot) : name).toLowerCase() || undefined;
+}
+
+export function isFileStemMatch(node: any, term: string): boolean {
+ const stem = fileStem(node);
+ return stem !== undefined && stem === term.toLowerCase();
+}
diff --git a/ix-cli/src/cli/resolve.ts b/ix-cli/src/cli/resolve.ts
index 434c097d..425528d0 100644
--- a/ix-cli/src/cli/resolve.ts
+++ b/ix-cli/src/cli/resolve.ts
@@ -11,6 +11,9 @@ import { readStitchScope, writeStitchScope } from "./config.js";
import { reportAmbiguousTarget, reportResolutionFailure } from "./ui.js";
import { relativePath } from "./format.js";
import { isQuiet } from "./output-shape.js";
+import {
+ candidateOrigin, isFileStemMatch, looksLikeCodeIdentifier, requestsNonCode,
+} from "./candidate-origin.js";
/**
* The read scope for the current working directory: a co-ingested multi-repo system
@@ -201,16 +204,55 @@ function normalizeForPathMatch(value: string | undefined): string {
// ── Scoring ───────────────────────────────────────────────────────────────
+/**
+ * Score added to a candidate that shares the name but is not the code
+ * definition (see candidate-origin.ts for how each is recognised).
+ *
+ * - An import entity is a single-line `module`: +5 cancels the -3 container
+ * boost it gets as a `module` and leaves it +2 behind a bare exact match, so
+ * a same-named function (-1), class (-3) or defining file (0) all beat it.
+ * - A CSS selector, markdown heading or JSON key (+10, only for a term that
+ * looks like a code identifier and only when the caller did not ask for that
+ * kind or language) and a copy in build output, a fixture or a sample (+10)
+ * land behind the import: an import at least points at the definition. 10
+ * is enough to put even a PascalCase CSS class (-7 with the type boost)
+ * behind a same-named function (-1).
+ *
+ * A demotion, never a filter — when nothing else shares the name these are
+ * still the best (and only) answer.
+ */
+export function originPenalty(
+ node: any,
+ symbol: string,
+ opts?: { kind?: string; language?: string },
+): number {
+ switch (candidateOrigin(node)) {
+ case "import": return 5;
+ case "generated": return 10;
+ case "non-code": return looksLikeCodeIdentifier(symbol) && !requestsNonCode(opts) ? 10 : 0;
+ default: return 0;
+ }
+}
+
/**
* Score a candidate node for resolution.
* Lower is better. Combines:
- * - exact name match (0 vs 10)
+ * - exact name match (0), defining-file stem match (3), prefix (15), other (30)
* - exact kind match when --kind provided (-5)
* - strong path match when --path provided (-4)
* - structural kind boost (-3 for container, -1 for method/function)
- * - penalty for fuzzy/incidental matches (+5)
+ * - penalty for an import / non-code / generated candidate (originPenalty)
*/
export function scoreCandidate(
+ node: any,
+ symbol: string,
+ opts?: { kind?: string; path?: string; language?: string }
+): number {
+ return baseScore(node, symbol, opts) + originPenalty(node, symbol, opts);
+}
+
+/** `scoreCandidate` without the origin penalty: how well the NAME matched. */
+export function baseScore(
node: any,
symbol: string,
opts?: { kind?: string; path?: string }
@@ -225,6 +267,11 @@ export function scoreCandidate(
// ── Name match ──────────────────────────────────────────────────────
if (name === symbolLower) {
score = 0; // exact name match — best tier
+ } else if (isFileStemMatch(node, symbol)) {
+ // `borderStylesReset.js` for `borderStylesReset`: the file is the
+ // definition of an anonymous default export. Behind a same-named symbol
+ // (a function nets -1, this nets 0), ahead of an import of it (+2).
+ score = 3;
} else if (name.startsWith(symbolLower)) {
score = 15; // prefix match — moderate
} else {
@@ -310,14 +357,29 @@ export async function resolveEntityFull(
await ensureReadScope(client); // fold in a Path-2 stitched system (Ix#225 Half B)
const { workspaceId, systemId } = activeScope();
const kindFilter = opts?.kind;
- const nodes = await client.search(symbol, {
- limit: opts?.searchLimit ?? (effectivePath ? 200 : looksTypeLikeSymbol(symbol) ? 50 : 30),
+ const searchLimit = opts?.searchLimit ?? (effectivePath ? 200 : looksTypeLikeSymbol(symbol) ? 50 : 30);
+ let nodes = await client.search(symbol, {
+ limit: searchLimit,
kind: kindFilter,
nameOnly: true,
workspaceId,
systemId,
});
+ // The backend orders its window by weight — every exact name before every
+ // partial one — so when a name is imported in dozens of files, the window is
+ // all imports and the file that DEFINES it (`borderStylesReset.js`, a
+ // partial match for `borderStylesReset`) never arrives. Only when the window
+ // came back full and holds no definition of the name, ask for files by that
+ // name directly: a handful of rows, merged in and scored like the rest.
+ if (nodes.length >= searchLimit && (!kindFilter || kindFilter === "file")
+ && !hasDefinitionOf(nodes, symbol)) {
+ const files = await client.search(symbol, {
+ limit: 20, kind: "file", nameOnly: true, workspaceId, systemId,
+ });
+ nodes = mergeById(nodes, files.filter((n: any) => isFileStemMatch(n, symbol)));
+ }
+
if (nodes.length === 0) {
// Nothing to suggest: the search matched no name, and re-running it without
// `nameOnly` returns the same empty set (measured against a 1.4M-node graph
@@ -352,15 +414,18 @@ export async function resolveEntityFull(
// Prefer case-sensitive exact matches. Fall back to case-insensitive only if none found.
// This prevents e.g. 'Apply' (capital A) from matching lowercase 'apply' module import
// aliases before finding the actual 'Apply' method entities.
+ // A file whose stem is the symbol counts as an exact name: it is the only
+ // definition an anonymous default export has, and scoring then puts it
+ // behind a same-named symbol but ahead of an import of the name.
const exactCaseName = filteredNodes.filter((n: any) => {
const name = (n.name || n.attrs?.name || "");
- return name === symbol;
+ return name === symbol || (isFileStemMatch(n, symbol) && name.startsWith(symbol));
});
const exactName = exactCaseName.length > 0
? exactCaseName
: filteredNodes.filter((n: any) => {
const name = (n.name || n.attrs?.name || "").toLowerCase();
- return name === symbolLower;
+ return name === symbolLower || isFileStemMatch(n, symbol);
});
// Score exact-name candidates
@@ -387,6 +452,20 @@ export async function resolveEntityFull(
return { resolved: false, ambiguous: false, hiddenTestCount, ...(suggestions.length ? { suggestions } : {}) };
}
+/** True when some candidate is a code definition named `symbol` (or its defining file). */
+export function hasDefinitionOf(nodes: any[], symbol: string): boolean {
+ const symbolLower = symbol.toLowerCase();
+ return nodes.some((n: any) => {
+ const name = String(n.name || n.attrs?.name || "").toLowerCase();
+ return (name === symbolLower || isFileStemMatch(n, symbol)) && candidateOrigin(n) === "definition";
+ });
+}
+
+export function mergeById<T extends { id?: unknown }>(base: T[], extra: T[]): T[] {
+ const seen = new Set(base.map((n) => n.id));
+ return [...base, ...extra.filter((n) => !seen.has(n.id))];
+}
+
/**
* Given a candidate set, score them, dedup, and either pick a winner or declare ambiguity.
*/