Skip to content

armgit / Ix

Public Imported from GitHub
0

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

feat: deterministic explanation pipeline for ix explain

Tanner Kochereacdd6b0e139
diff --git a/ix-cli/src/cli/__tests__/explain-pipeline.test.ts b/ix-cli/src/cli/__tests__/explain-pipeline.test.ts
new file mode 100644
index 00000000..17cd52e6
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/explain-pipeline.test.ts
@@ -0,0 +1,793 @@
+import { describe, it, expect } from "vitest";
+import { inferRole } from "../explain/role-inference.js";
+import { inferImportance } from "../explain/importance.js";
+import { renderExplanation } from "../explain/render.js";
+import type { EntityFacts } from "../explain/facts.js";
+
+function makeFacts(overrides: Partial<EntityFacts> = {}): EntityFacts {
+ return {
+ id: "test-id-1234",
+ name: "SomeEntity",
+ kind: "function",
+ path: "src/example.ts",
+ signature: undefined,
+ docstring: undefined,
+ container: undefined,
+ members: [],
+ memberCount: 0,
+ callerCount: 2,
+ calleeCount: 1,
+ dependentCount: 3,
+ importerCount: 1,
+ downstreamDependents: 4,
+ downstreamDepth: 2,
+ topCallers: [],
+ topDependents: [],
+ introducedRev: 1,
+ historyLength: 2,
+ callList: undefined,
+ stale: false,
+ diagnostics: [],
+ ...overrides,
+ };
+}
+
+// ── Role inference ──────────────────────────────────────────────────────────
+
+describe("inferRole", () => {
+ it("detects test entities by name", () => {
+ const facts = makeFacts({ name: "AuthServiceTest", path: "src/__tests__/auth.ts" });
+ const result = inferRole(facts);
+ expect(result.role).toBe("test");
+ expect(result.confidence).toBe("high");
+ });
+
+ it("detects test entities by path containing spec", () => {
+ const facts = makeFacts({ name: "describe", path: "src/auth.spec.ts" });
+ const result = inferRole(facts);
+ expect(result.role).toBe("test");
+ });
+
+ it("detects configuration entities", () => {
+ const facts = makeFacts({ kind: "config_entry", name: "databaseConfig" });
+ const result = inferRole(facts);
+ expect(result.role).toBe("configuration");
+ expect(result.confidence).toBe("high");
+ });
+
+ it("detects type definitions", () => {
+ const facts = makeFacts({ kind: "interface", name: "UserProps" });
+ const result = inferRole(facts);
+ expect(result.role).toBe("type-definition");
+ expect(result.confidence).toBe("high");
+ });
+
+ it("detects API client by class name and methods", () => {
+ const facts = makeFacts({
+ kind: "class",
+ name: "IxClient",
+ path: "src/client/api.ts",
+ memberCount: 15,
+ members: ["query", "search", "entity", "expand", "ingest", "post", "get", "patch"],
+ callerCount: 12,
+ calleeCount: 0,
+ dependentCount: 20,
+ });
+ const result = inferRole(facts);
+ expect(result.role).toBe("api-client");
+ expect(result.confidence).toBe("high");
+ });
+
+ it("detects API client even without path signals if methods match", () => {
+ const facts = makeFacts({
+ kind: "class",
+ name: "BackendClient",
+ path: "src/service.ts",
+ memberCount: 5,
+ members: ["get", "post", "delete", "fetch"],
+ callerCount: 4,
+ calleeCount: 2,
+ });
+ const result = inferRole(facts);
+ expect(result.role).toBe("api-client");
+ });
+
+ it("does NOT classify IxClient-like class as data-model", () => {
+ const facts = makeFacts({
+ kind: "class",
+ name: "IxClient",
+ path: "src/client/api.ts",
+ memberCount: 15,
+ members: ["query", "search", "entity", "expand", "ingest", "post", "get"],
+ callerCount: 12,
+ calleeCount: 0,
+ });
+ const result = inferRole(facts);
+ expect(result.role).not.toBe("data-model");
+ });
+
+ it("detects registration functions", () => {
+ const facts = makeFacts({
+ kind: "function",
+ name: "registerExplainCommand",
+ path: "src/cli/commands/explain.ts",
+ callerCount: 1,
+ calleeCount: 2,
+ });
+ const result = inferRole(facts);
+ expect(result.role).toBe("registration-function");
+ expect(result.confidence).toBe("high");
+ });
+
+ it("detects resolution helpers", () => {
+ const facts = makeFacts({
+ kind: "function",
+ name: "resolveFileOrEntity",
+ path: "src/cli/resolve.ts",
+ callerCount: 10,
+ calleeCount: 5,
+ });
+ const result = inferRole(facts);
+ expect(result.role).toBe("resolution-helper");
+ });
+
+ it("detects selection helpers like pickBest", () => {
+ const facts = makeFacts({
+ kind: "function",
+ name: "pickBest",
+ path: "src/cli/resolve.ts",
+ callerCount: 1,
+ calleeCount: 3,
+ downstreamDependents: 25,
+ downstreamDepth: 3,
+ });
+ const result = inferRole(facts);
+ expect(result.role).toBe("selection-helper");
+ expect(result.reasons.some((r) => r.includes("selection"))).toBe(true);
+ });
+
+ it("detects scoring helpers by name", () => {
+ const facts = makeFacts({
+ kind: "function",
+ name: "scoreCandidate",
+ path: "src/cli/importance.ts",
+ callerCount: 2,
+ calleeCount: 1,
+ });
+ const result = inferRole(facts);
+ expect(result.role).toBe("scoring-helper");
+ });
+
+ it("detects scoring helpers by file path", () => {
+ const facts = makeFacts({
+ kind: "function",
+ name: "evaluate",
+ path: "src/ranking/score.ts",
+ callerCount: 3,
+ calleeCount: 1,
+ });
+ const result = inferRole(facts);
+ expect(result.role).toBe("scoring-helper");
+ });
+
+ it("detects services by naming and structure", () => {
+ const facts = makeFacts({
+ kind: "class",
+ name: "IngestionService",
+ memberCount: 5,
+ members: ["ingest", "parse", "validate", "store", "notify"],
+ });
+ const result = inferRole(facts);
+ expect(result.role).toBe("service");
+ expect(result.confidence).toBe("high");
+ });
+
+ it("detects service methods via container context", () => {
+ const facts = makeFacts({
+ kind: "method",
+ name: "processPayment",
+ path: "src/billing.ts",
+ container: { kind: "class", name: "PaymentService" },
+ callerCount: 3,
+ calleeCount: 2,
+ });
+ const result = inferRole(facts);
+ expect(result.role).toBe("service-method");
+ expect(result.confidence).toBe("high");
+ expect(result.reasons.some((r) => r.includes("PaymentService"))).toBe(true);
+ });
+
+ it("detects entry points (no callers, has callees)", () => {
+ const facts = makeFacts({
+ kind: "function",
+ name: "main",
+ callerCount: 0,
+ calleeCount: 3,
+ });
+ const result = inferRole(facts);
+ expect(result.role).toBe("entry-point");
+ expect(result.confidence).toBe("high");
+ });
+
+ it("detects shared utility functions", () => {
+ const facts = makeFacts({
+ kind: "function",
+ name: "formatDate",
+ callerCount: 5,
+ calleeCount: 0,
+ memberCount: 0,
+ });
+ const result = inferRole(facts);
+ expect(result.role).toBe("shared-utility");
+ expect(result.confidence).toBe("medium");
+ });
+
+ it("detects adapters by name", () => {
+ const facts = makeFacts({
+ kind: "class",
+ name: "DatabaseGateway",
+ callerCount: 2,
+ calleeCount: 3,
+ memberCount: 2,
+ });
+ const result = inferRole(facts);
+ expect(result.role).toBe("adapter");
+ });
+
+ it("detects localized helpers", () => {
+ const facts = makeFacts({
+ kind: "function",
+ name: "doStuff",
+ callerCount: 1,
+ calleeCount: 1,
+ memberCount: 0,
+ });
+ const result = inferRole(facts);
+ expect(result.role).toBe("localized-helper");
+ expect(result.confidence).toBe("medium");
+ });
+
+ it("uses container context for unknown-fallback functions", () => {
+ const facts = makeFacts({
+ kind: "function",
+ name: "x",
+ callerCount: 0,
+ calleeCount: 0,
+ memberCount: 0,
+ container: { kind: "class", name: "Foo" },
+ });
+ const result = inferRole(facts);
+ // Should NOT say "role could not be determined"
+ expect(result.reasons.join(" ")).not.toContain("could not be determined");
+ expect(result.reasons.some((r) => r.includes("Foo"))).toBe(true);
+ });
+
+ it("uses file context for unknown-fallback functions", () => {
+ const facts = makeFacts({
+ kind: "function",
+ name: "x",
+ path: "src/cli/helpers.ts",
+ callerCount: 0,
+ calleeCount: 0,
+ memberCount: 0,
+ });
+ const result = inferRole(facts);
+ expect(result.reasons.join(" ")).not.toContain("could not be determined");
+ expect(result.reasons.some((r) => r.includes("helpers"))).toBe(true);
+ });
+
+ it("never says 'role could not be determined' for entities with file context", () => {
+ const facts = makeFacts({
+ kind: "variable",
+ name: "x",
+ callerCount: 0,
+ calleeCount: 0,
+ memberCount: 0,
+ path: "src/utils.ts",
+ });
+ const result = inferRole(facts);
+ expect(result.reasons.join(" ")).not.toContain("could not be determined");
+ });
+});
+
+// ── Importance inference ────────────────────────────────────────────────────
+
+describe("inferImportance", () => {
+ it("marks high importance for many dependents (broad-shared-dependency)", () => {
+ const facts = makeFacts({ dependentCount: 12, callerCount: 8, downstreamDependents: 20 });
+ const result = inferImportance(facts);
+ expect(result.level).toBe("high");
+ expect(result.category).toBe("broad-shared-dependency");
+ expect(result.reasons.some((r) => r.includes("dependents"))).toBe(true);
+ });
+
+ it("marks high importance for many callers", () => {
+ const facts = makeFacts({ callerCount: 10, downstreamDependents: 15 });
+ const result = inferImportance(facts);
+ expect(result.level).toBe("high");
+ expect(result.category).toBe("broad-shared-dependency");
+ });
+
+ it("marks low importance for isolated entities", () => {
+ const facts = makeFacts({
+ dependentCount: 0,
+ callerCount: 0,
+ importerCount: 0,
+ memberCount: 0,
+ downstreamDependents: 0,
+ downstreamDepth: 0,
+ });
+ const result = inferImportance(facts);
+ expect(result.level).toBe("low");
+ });
+
+ it("marks medium importance for moderate connectivity", () => {
+ const facts = makeFacts({
+ dependentCount: 3,
+ callerCount: 2,
+ importerCount: 1,
+ downstreamDependents: 5,
+ });
+ const result = inferImportance(facts);
+ expect(result.level).toBe("medium");
+ expect(result.category).toBe("normal");
+ });
+
+ it("detects pipeline choke point (low callers, high downstream)", () => {
+ const facts = makeFacts({
+ callerCount: 1,
+ dependentCount: 2,
+ importerCount: 0,
+ downstreamDependents: 25,
+ downstreamDepth: 3,
+ });
+ const result = inferImportance(facts);
+ expect(result.level).toBe("high");
+ expect(result.category).toBe("pipeline-choke-point");
+ expect(result.reasons.some((r) => r.includes("downstream dependents"))).toBe(true);
+ });
+
+ it("detects localized helper (low callers, small downstream)", () => {
+ const facts = makeFacts({
+ callerCount: 1,
+ dependentCount: 1,
+ importerCount: 0,
+ memberCount: 0,
+ downstreamDependents: 2,
+ downstreamDepth: 1,
+ });
+ const result = inferImportance(facts);
+ expect(result.category).toBe("localized-helper");
+ });
+
+ it("does NOT mark as choke point if callers are high", () => {
+ const facts = makeFacts({
+ callerCount: 8,
+ downstreamDependents: 30,
+ });
+ const result = inferImportance(facts);
+ expect(result.category).toBe("broad-shared-dependency");
+ expect(result.category).not.toBe("pipeline-choke-point");
+ });
+});
+
+// ── Rendering ───────────────────────────────────────────────────────────────
+
+describe("renderExplanation", () => {
+ it("uses confident language for high-confidence roles", () => {
+ const facts = makeFacts({
+ kind: "class",
+ name: "IxClient",
+ path: "src/client/api.ts",
+ memberCount: 15,
+ members: ["query", "search", "entity", "expand", "ingest", "post", "get", "patch"],
+ callerCount: 12,
+ dependentCount: 20,
+ downstreamDependents: 35,
+ });
+ const role = inferRole(facts);
+ expect(role.confidence).toBe("high");
+ const importance = inferImportance(facts);
+ const rendered = renderExplanation(facts, role, importance);
+ expect(rendered.explanation).toContain("serves as");
+ expect(rendered.explanation).not.toContain("appears to be");
+ });
+
+ it("uses hedged language for low-confidence roles", () => {
+ const facts = makeFacts({
+ kind: "variable",
+ name: "x",
+ callerCount: 0,
+ calleeCount: 0,
+ memberCount: 0,
+ path: "src/utils.ts",
+ });
+ const role = inferRole(facts);
+ const importance = inferImportance(facts);
+ const rendered = renderExplanation(facts, role, importance);
+ expect(rendered.explanation).toContain("appears to be");
+ });
+
+ it("includes container context in explanation for service methods", () => {
+ const facts = makeFacts({
+ kind: "method",
+ name: "resolve",
+ container: { kind: "class", name: "ConflictService" },
+ callerCount: 3,
+ calleeCount: 2,
+ });
+ const role = inferRole(facts);
+ const importance = inferImportance(facts);
+ const rendered = renderExplanation(facts, role, importance);
+ expect(rendered.explanation).toContain("ConflictService");
+ });
+
+ it("includes container context when present", () => {
+ const facts = makeFacts({
+ container: { kind: "class", name: "OrderService" },
+ });
+ const role = inferRole(facts);
+ const importance = inferImportance(facts);
+ const rendered = renderExplanation(facts, role, importance);
+ expect(rendered.context).toContain("Container: class OrderService");
+ });
+
+ it("includes downstream dependents in context", () => {
+ const facts = makeFacts({ downstreamDependents: 15, downstreamDepth: 3 });
+ const role = inferRole(facts);
+ const importance = inferImportance(facts);
+ const rendered = renderExplanation(facts, role, importance);
+ expect(rendered.context).toContain("Downstream dependents: 15");
+ });
+
+ it("renders named usage examples when callers exist", () => {
+ const facts = makeFacts({
+ callerCount: 5,
+ topCallers: ["registerImpactCommand", "registerOverviewCommand", "registerExplainCommand"],
+ });
+ const role = inferRole(facts);
+ const importance = inferImportance(facts);
+ const rendered = renderExplanation(facts, role, importance);
+ expect(rendered.usedBy).not.toBeNull();
+ expect(rendered.usedBy).toContain("registerImpactCommand");
+ expect(rendered.usedBy).toContain("registerOverviewCommand");
+ });
+
+ it("returns null usedBy when no examples available", () => {
+ const facts = makeFacts({ callerCount: 0, topCallers: [], topDependents: [] });
+ const role = inferRole(facts);
+ const importance = inferImportance(facts);
+ const rendered = renderExplanation(facts, role, importance);
+ expect(rendered.usedBy).toBeNull();
+ });
+
+ it("fuses role context into why-it-matters for api-client", () => {
+ const facts = makeFacts({
+ kind: "class",
+ name: "IxClient",
+ path: "src/client/api.ts",
+ memberCount: 15,
+ members: ["query", "search", "entity", "expand", "ingest", "post", "get", "patch"],
+ callerCount: 12,
+ dependentCount: 20,
+ downstreamDependents: 35,
+ });
+ const role = inferRole(facts);
+ const importance = inferImportance(facts);
+ const rendered = renderExplanation(facts, role, importance);
+ expect(rendered.whyItMatters).toContain("central API client");
+ expect(rendered.whyItMatters).toContain("ix impact");
+ });
+
+ it("renders pipeline choke point wording for narrow-but-critical nodes", () => {
+ const facts = makeFacts({
+ name: "pickBest",
+ callerCount: 1,
+ dependentCount: 2,
+ downstreamDependents: 25,
+ downstreamDepth: 3,
+ });
+ const role = inferRole(facts);
+ const importance = inferImportance(facts);
+ expect(importance.category).toBe("pipeline-choke-point");
+ const rendered = renderExplanation(facts, role, importance);
+ expect(rendered.whyItMatters).toContain("only 1 direct caller");
+ expect(rendered.whyItMatters).toContain("25 downstream dependents");
+ expect(rendered.whyItMatters).toContain("structurally important");
+ });
+
+ it("renders localized helper wording for low-impact nodes", () => {
+ const facts = makeFacts({
+ name: "trimWhitespace",
+ callerCount: 1,
+ dependentCount: 1,
+ importerCount: 0,
+ memberCount: 0,
+ downstreamDependents: 2,
+ downstreamDepth: 1,
+ });
+ const role = inferRole(facts);
+ const importance = inferImportance(facts);
+ expect(importance.category).toBe("localized-helper");
+ const rendered = renderExplanation(facts, role, importance);
+ expect(rendered.whyItMatters).toContain("localized");
+ });
+
+ it("cleans unresolved_call_target into human-readable note", () => {
+ const facts = makeFacts({
+ diagnostics: [
+ { code: "unresolved_call_target", message: "3 callee(s) could not be resolved." },
+ ],
+ });
+ const role = inferRole(facts);
+ const importance = inferImportance(facts);
+ const rendered = renderExplanation(facts, role, importance);
+ expect(rendered.notes.length).toBe(1);
+ expect(rendered.notes[0]).not.toContain("[unresolved_call_target]");
+ expect(rendered.notes[0]).toContain("could not be resolved");
+ });
+
+ it("cleans stale_source into human-readable note", () => {
+ const facts = makeFacts({
+ diagnostics: [
+ { code: "stale_source", message: "stale" },
+ ],
+ });
+ const role = inferRole(facts);
+ const importance = inferImportance(facts);
+ const rendered = renderExplanation(facts, role, importance);
+ expect(rendered.notes[0]).toContain("changed since last ingest");
+ expect(rendered.notes[0]).not.toContain("[stale_source]");
+ });
+});
+
+// ── Confidence-to-language tiers ─────────────────────────────────────────────
+
+describe("confidence-to-language mapping", () => {
+ it("high-confidence roles use 'serves as', never 'likely' or 'appears'", () => {
+ const facts = makeFacts({
+ kind: "class",
+ name: "IngestionService",
+ memberCount: 5,
+ members: ["ingest", "parse", "validate", "store", "notify"],
+ });
+ const role = inferRole(facts);
+ expect(role.confidence).toBe("high");
+ const importance = inferImportance(facts);
+ const rendered = renderExplanation(facts, role, importance);
+ expect(rendered.explanation).toContain("serves as");
+ expect(rendered.explanation).not.toContain("is likely");
+ expect(rendered.explanation).not.toContain("appears to be");
+ });
+
+ it("medium-confidence roles use 'is likely'", () => {
+ const facts = makeFacts({
+ kind: "function",
+ name: "formatDate",
+ callerCount: 5,
+ calleeCount: 0,
+ memberCount: 0,
+ });
+ const role = inferRole(facts);
+ expect(role.confidence).toBe("medium");
+ const importance = inferImportance(facts);
+ const rendered = renderExplanation(facts, role, importance);
+ expect(rendered.explanation).toContain("is likely");
+ expect(rendered.explanation).not.toContain("serves as");
+ });
+
+ it("low-confidence roles use 'appears to be'", () => {
+ const facts = makeFacts({
+ kind: "variable",
+ name: "x",
+ callerCount: 0,
+ calleeCount: 0,
+ memberCount: 0,
+ path: "src/utils.ts",
+ });
+ const role = inferRole(facts);
+ expect(role.confidence).toBe("low");
+ const importance = inferImportance(facts);
+ const rendered = renderExplanation(facts, role, importance);
+ expect(rendered.explanation).toContain("appears to be");
+ expect(rendered.explanation).not.toContain("serves as");
+ expect(rendered.explanation).not.toContain("is likely");
+ });
+
+ it("high-confidence broad dependency uses 'will propagate' not 'likely to affect'", () => {
+ const facts = makeFacts({
+ kind: "class",
+ name: "IxClient",
+ path: "src/client/api.ts",
+ memberCount: 15,
+ members: ["query", "search", "entity", "expand", "ingest", "post", "get", "patch"],
+ callerCount: 12,
+ dependentCount: 20,
+ downstreamDependents: 35,
+ });
+ const role = inferRole(facts);
+ expect(role.confidence).toBe("high");
+ const importance = inferImportance(facts);
+ const rendered = renderExplanation(facts, role, importance);
+ expect(rendered.whyItMatters).toContain("will propagate");
+ expect(rendered.whyItMatters).not.toContain("likely to affect");
+ });
+
+ it("medium-confidence broad dependency uses 'may propagate'", () => {
+ // Force medium confidence via a class with client methods but no name/path signals
+ const facts = makeFacts({
+ kind: "class",
+ name: "DataHub",
+ path: "src/core.ts",
+ memberCount: 4,
+ members: ["get", "post", "fetch", "query"],
+ callerCount: 10,
+ calleeCount: 3,
+ dependentCount: 12,
+ downstreamDependents: 20,
+ });
+ const role = inferRole(facts);
+ expect(role.confidence).toBe("medium");
+ const importance = inferImportance(facts);
+ expect(importance.category).toBe("broad-shared-dependency");
+ const rendered = renderExplanation(facts, role, importance);
+ expect(rendered.whyItMatters).toContain("may propagate");
+ });
+
+ it("localized helper uses 'is localized' not 'appears localized'", () => {
+ const facts = makeFacts({
+ name: "trimWhitespace",
+ callerCount: 1,
+ dependentCount: 1,
+ importerCount: 0,
+ memberCount: 0,
+ downstreamDependents: 2,
+ downstreamDepth: 1,
+ });
+ const role = inferRole(facts);
+ const importance = inferImportance(facts);
+ expect(importance.category).toBe("localized-helper");
+ const rendered = renderExplanation(facts, role, importance);
+ expect(rendered.whyItMatters).toContain("is localized");
+ expect(rendered.whyItMatters).not.toContain("appears localized");
+ });
+});
+
+// ── File-based role inference ───────────────────────────────────────────────
+
+describe("file-based role inference", () => {
+ it("inferImportance function in importance.ts → scoring-helper", () => {
+ const facts = makeFacts({
+ kind: "function",
+ name: "inferImportance",
+ path: "src/cli/explain/importance.ts",
+ callerCount: 2,
+ calleeCount: 1,
+ });
+ const result = inferRole(facts);
+ expect(result.role).toBe("scoring-helper");
+ });
+
+ it("resolve in api.ts file stays resolution-helper", () => {
+ const facts = makeFacts({
+ kind: "function",
+ name: "resolvePrefix",
+ path: "src/client/api.ts",
+ callerCount: 3,
+ calleeCount: 2,
+ });
+ const result = inferRole(facts);
+ expect(result.role).toBe("resolution-helper");
+ });
+});
+
+// ── Fixture-like regression tests ───────────────────────────────────────────
+
+describe("fixture regression: IxClient", () => {
+ const ixClientFacts = makeFacts({
+ kind: "class",
+ name: "IxClient",
+ path: "ix-cli/src/client/api.ts",
+ memberCount: 15,
+ members: ["query", "search", "entity", "expand", "ingest", "post", "get", "patch",
+ "decide", "provenance", "listPatches", "stats", "listByKind", "listDecisions", "resolvePrefix"],
+ callerCount: 12,
+ calleeCount: 0,
+ dependentCount: 20,
+ importerCount: 8,
+ downstreamDependents: 35,
+ downstreamDepth: 3,
+ topCallers: ["registerImpactCommand", "registerOverviewCommand", "registerExplainCommand"],
+ });
+
+ it("infers api-client role, not data-model", () => {
+ const role = inferRole(ixClientFacts);
+ expect(role.role).toBe("api-client");
+ expect(role.role).not.toBe("data-model");
+ expect(role.confidence).toBe("high");
+ });
+
+ it("infers high importance as broad shared dependency", () => {
+ const importance = inferImportance(ixClientFacts);
+ expect(importance.level).toBe("high");
+ expect(importance.category).toBe("broad-shared-dependency");
+ });
+
+ it("renders confident explanation with API client and named examples", () => {
+ const role = inferRole(ixClientFacts);
+ const importance = inferImportance(ixClientFacts);
+ const rendered = renderExplanation(ixClientFacts, role, importance);
+ expect(rendered.explanation).toContain("serves as");
+ expect(rendered.explanation).toContain("API client");
+ expect(rendered.whyItMatters).toContain("central API client");
+ expect(rendered.usedBy).toContain("registerImpactCommand");
+ });
+});
+
+describe("fixture regression: pickBest", () => {
+ const pickBestFacts = makeFacts({
+ kind: "function",
+ name: "pickBest",
+ path: "ix-cli/src/cli/resolve.ts",
+ callerCount: 1,
+ calleeCount: 3,
+ dependentCount: 2,
+ importerCount: 0,
+ memberCount: 0,
+ downstreamDependents: 25,
+ downstreamDepth: 3,
+ topCallers: ["resolveFileOrEntity"],
+ });
+
+ it("infers selection-helper role, not unknown", () => {
+ const role = inferRole(pickBestFacts);
+ expect(role.role).toBe("selection-helper");
+ expect(role.role).not.toBe("unknown");
+ });
+
+ it("infers pipeline choke point importance", () => {
+ const importance = inferImportance(pickBestFacts);
+ expect(importance.level).toBe("high");
+ expect(importance.category).toBe("pipeline-choke-point");
+ });
+
+ it("renders choke point wording, not 'moderate impact'", () => {
+ const role = inferRole(pickBestFacts);
+ const importance = inferImportance(pickBestFacts);
+ const rendered = renderExplanation(pickBestFacts, role, importance);
+ expect(rendered.whyItMatters).not.toContain("Moderate impact");
+ expect(rendered.whyItMatters).toContain("downstream dependents");
+ expect(rendered.whyItMatters).toContain("structurally important");
+ });
+
+ it("includes named usage example", () => {
+ const role = inferRole(pickBestFacts);
+ const importance = inferImportance(pickBestFacts);
+ const rendered = renderExplanation(pickBestFacts, role, importance);
+ expect(rendered.usedBy).toContain("resolveFileOrEntity");
+ });
+});
+
+// ── Distinction from overview ───────────────────────────────────────────────
+
+describe("explain vs overview distinction", () => {
+ it("explain output includes role, importance category, and rendered sections that overview lacks", () => {
+ const facts = makeFacts({
+ kind: "class",
+ name: "IngestionService",
+ memberCount: 5,
+ members: ["a", "b", "c", "d", "e"],
+ });
+ const role = inferRole(facts);
+ const importance = inferImportance(facts);
+ const rendered = renderExplanation(facts, role, importance);
+
+ expect(role.role).toBeDefined();
+ expect(role.confidence).toBeDefined();
+ expect(importance.level).toBeDefined();
+ expect(importance.category).toBeDefined();
+ expect(rendered.explanation).toBeDefined();
+ expect(rendered.whyItMatters).toBeDefined();
+ expect(rendered.notes).toBeDefined();
+ });
+});
diff --git a/ix-cli/src/cli/commands/explain.ts b/ix-cli/src/cli/commands/explain.ts
index c3a658f4..8504e118 100644
--- a/ix-cli/src/cli/commands/explain.ts
+++ b/ix-cli/src/cli/commands/explain.ts
@@ -4,153 +4,217 @@ import { getEndpoint } from "../config.js";
import { formatExplain, type ExplainResult, type EntityRef, type Diagnostic } from "../format.js";
import { resolveFileOrEntity, isRawId } from "../resolve.js";
import { isFileStale } from "../stale.js";
+import { collectFacts } from "../explain/facts.js";
+import { inferRole } from "../explain/role-inference.js";
+import { inferImportance } from "../explain/importance.js";
+import { renderExplanation } from "../explain/render.js";
import { stderr } from "../stderr.js";
import chalk from "chalk";
export function registerExplainCommand(program: Command): void {
program
.command("explain <symbol>")
- .description("Explain an entity — shows structure, container, and history")
+ .description("Explain an entity — infers role, importance, and structural context")
.option("--kind <kind>", "Filter target entity by kind")
.option("--path <path>", "Prefer symbols from files matching this path substring")
.option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)")
.option("--format <fmt>", "Output format (text|json)", "text")
- .addHelpText("after", "\nExamples:\n ix explain IngestionService\n ix explain expand --path memory-layer\n ix explain verify_token --kind function --format json")
- .action(async (symbol: string, opts: { kind?: string; path?: string; pick?: string; format: string }) => {
+ .option("--raw", "Show raw metadata dump (legacy format)")
+ .addHelpText("after", "\nExamples:\n ix explain IngestionService\n ix explain expand --path memory-layer\n ix explain verify_token --kind function --format json\n ix explain IxClient --raw")
+ .action(async (symbol: string, opts: { kind?: string; path?: string; pick?: string; format: string; raw?: boolean }) => {
const client = new IxClient(getEndpoint());
const resolveOpts = { kind: opts.kind, path: opts.path, pick: opts.pick ? parseInt(opts.pick, 10) : undefined };
const target = await resolveFileOrEntity(client, symbol, resolveOpts);
if (!target) return;
- const details = await client.entity(target.id);
+ if (opts.raw) {
+ await rawExplain(client, target, opts.format);
+ return;
+ }
- let history: any = { entityId: target.id, chain: [] };
- try {
- history = await client.provenance(target.id);
- } catch { /* no history */ }
+ // New pipeline: collect facts → infer role → infer importance → render
+ const facts = await collectFacts(client, target.id, target.name, target.kind);
+ const role = inferRole(facts);
+ const importance = inferImportance(facts);
+ const rendered = renderExplanation(facts, role, importance);
- const edges = (details.edges ?? []) as any[];
- const containsEdge = edges.find((e: any) =>
- e.predicate === "CONTAINS" && e.dst === target.id
- );
- let container: any = undefined;
- if (containsEdge) {
- try {
- const containerDetails = await client.entity(containsEdge.src);
- container = containerDetails.node;
- } catch { /* no container */ }
- }
+ if (opts.format === "json") {
+ const output = {
+ resolvedTarget: { id: target.id, kind: target.kind, name: target.name },
+ resolutionMode: target.resolutionMode,
+ resultSource: "graph",
+ facts,
+ role,
+ importance,
+ rendered,
+ diagnostics: facts.diagnostics.length > 0 ? facts.diagnostics : undefined,
+ };
+ console.log(JSON.stringify(output, null, 2));
+ } else {
+ if (facts.stale) {
+ stderr(chalk.yellow("⚠ Source has changed since last ingest. Run ix ingest to update.\n"));
+ }
- const callEdges = edges.filter((e: any) => e.predicate === "CALLS");
- const containedEdges = edges.filter((e: any) =>
- e.predicate === "CONTAINS" && e.src === target.id
- );
+ console.log(chalk.bold.underline("\nExplanation"));
+ console.log(` ${rendered.explanation}`);
- const node = details.node as any;
+ console.log(chalk.bold.underline("\nContext"));
+ for (const line of rendered.context.split("\n")) {
+ console.log(` ${line}`);
+ }
- // Check staleness
- let stale = false;
- const sourceUri = node.provenance?.source_uri ?? node.provenance?.sourceUri;
- if (sourceUri) {
- try { stale = await isFileStale(client, sourceUri); } catch {}
- }
+ if (rendered.usedBy) {
+ console.log(chalk.bold.underline("\nUsed by"));
+ console.log(` ${rendered.usedBy}`);
+ }
+
+ console.log(chalk.bold.underline("\nWhy it matters"));
+ console.log(` ${rendered.whyItMatters}`);
- // Extract snippet fields from attrs
- const signature = node.attrs?.signature || node.attrs?.summary;
- const docstring = node.attrs?.docstring || node.attrs?.description;
-
- // Get actual callee details from outgoing CALLS edges
- const calleeEdges = callEdges.filter((e: any) => e.src === target.id);
- const diagnostics: Diagnostic[] = [];
- let callList: EntityRef[] | undefined;
- if (calleeEdges.length > 0 && calleeEdges.length <= 20) {
- const refs = await Promise.all(
- calleeEdges.map(async (e: any): Promise<EntityRef> => {
- try {
- const callee = await client.entity(e.dst);
- const calleeNode = callee.node as any;
- const name = calleeNode.name || calleeNode.attrs?.name || "";
- if (!name || isRawId(name)) {
- return {
- name: name || e.dst,
- kind: calleeNode.kind,
- resolved: false,
- suggestedCommand: `ix text "${e.dst.slice(0, 8)}"`,
- };
- }
- return {
- name,
- kind: calleeNode.kind,
- id: e.dst,
- resolved: true,
- path: calleeNode.provenance?.source_uri ?? calleeNode.provenance?.sourceUri,
- suggestedCommand: `ix explain "${name}"`,
- };
- } catch {
- return {
- name: e.dst,
- resolved: false,
- diagnostic: "unresolved_call_target",
- suggestedCommand: `ix text "${e.dst.slice(0, 8)}"`,
- } as EntityRef;
- }
- })
- );
- callList = refs;
- const unresolvedCount = refs.filter(r => !r.resolved).length;
- if (unresolvedCount > 0) {
- diagnostics.push({
- code: "unresolved_call_target",
- message: `${unresolvedCount} callee(s) could not be resolved to named entities. Use ix text to locate them.`,
- });
+ if (rendered.notes.length > 0) {
+ console.log(chalk.bold.underline("\nNote"));
+ for (const note of rendered.notes) {
+ console.log(` ${chalk.dim(note)}`);
+ }
}
+ console.log();
}
+ });
+}
- if (stale) {
- diagnostics.push({
- code: "stale_source",
- message: "Results may be stale; file has changed since last ingest.",
- });
- }
+/** Legacy raw metadata dump — preserves old behavior behind --raw flag. */
+async function rawExplain(
+ client: IxClient,
+ target: { id: string; kind: string; name: string; resolutionMode: string },
+ format: string,
+): Promise<void> {
+ const details = await client.entity(target.id);
- const result: ExplainResult & { stale?: boolean; warning?: string } = {
- kind: node.kind,
- name: node.name || node.attrs?.name || target.name,
- id: target.id,
- file: sourceUri,
- container: container ? { kind: container.kind, name: container.name || container.attrs?.name || "(unknown)" } : undefined,
- introducedRev: node.createdRev ?? node.created_rev,
- calledBy: callEdges.filter((e: any) => e.dst === target.id).length,
- calls: callEdges.filter((e: any) => e.src === target.id).length,
- contains: containedEdges.length,
- historyLength: (history as any)?.chain?.length ?? 0,
- signature,
- docstring,
- callList,
- diagnostics: diagnostics.length > 0 ? diagnostics : undefined,
- };
-
- if (stale) {
- (result as any).stale = true;
- (result as any).warning = "Results may be stale; file has changed since last ingest.";
- }
+ let history: any = { entityId: target.id, chain: [] };
+ try {
+ history = await client.provenance(target.id);
+ } catch { /* no history */ }
- if (opts.format === "json") {
- // Include resolvedTarget and stale fields in JSON
- const output: any = {
- resolvedTarget: { id: target.id, kind: target.kind, name: target.name },
- resolutionMode: target.resolutionMode,
- resultSource: "graph",
- result,
- };
- if (stale) {
- output.stale = true;
- output.warning = "Results may be stale; file has changed since last ingest.";
+ const edges = (details.edges ?? []) as any[];
+ const containsEdge = edges.find((e: any) =>
+ e.predicate === "CONTAINS" && e.dst === target.id
+ );
+ let container: any = undefined;
+ if (containsEdge) {
+ try {
+ const containerDetails = await client.entity(containsEdge.src);
+ container = containerDetails.node;
+ } catch { /* no container */ }
+ }
+
+ const callEdges = edges.filter((e: any) => e.predicate === "CALLS");
+ const containedEdges = edges.filter((e: any) =>
+ e.predicate === "CONTAINS" && e.src === target.id
+ );
+
+ const node = details.node as any;
+
+ // Check staleness
+ let stale = false;
+ const sourceUri = node.provenance?.source_uri ?? node.provenance?.sourceUri;
+ if (sourceUri) {
+ try { stale = await isFileStale(client, sourceUri); } catch {}
+ }
+
+ // Extract snippet fields from attrs
+ const signature = node.attrs?.signature || node.attrs?.summary;
+ const docstring = node.attrs?.docstring || node.attrs?.description;
+
+ // Get actual callee details from outgoing CALLS edges
+ const calleeEdges = callEdges.filter((e: any) => e.src === target.id);
+ const diagnostics: Diagnostic[] = [];
+ let callList: EntityRef[] | undefined;
+ if (calleeEdges.length > 0 && calleeEdges.length <= 20) {
+ const refs = await Promise.all(
+ calleeEdges.map(async (e: any): Promise<EntityRef> => {
+ try {
+ const callee = await client.entity(e.dst);
+ const calleeNode = callee.node as any;
+ const name = calleeNode.name || calleeNode.attrs?.name || "";
+ if (!name || isRawId(name)) {
+ return {
+ name: name || e.dst,
+ kind: calleeNode.kind,
+ resolved: false,
+ suggestedCommand: `ix text "${e.dst.slice(0, 8)}"`,
+ };
+ }
+ return {
+ name,
+ kind: calleeNode.kind,
+ id: e.dst,
+ resolved: true,
+ path: calleeNode.provenance?.source_uri ?? calleeNode.provenance?.sourceUri,
+ suggestedCommand: `ix explain "${name}"`,
+ };
+ } catch {
+ return {
+ name: e.dst,
+ resolved: false,
+ diagnostic: "unresolved_call_target",
+ suggestedCommand: `ix text "${e.dst.slice(0, 8)}"`,
+ } as EntityRef;
}
- console.log(JSON.stringify(output, null, 2));
- } else {
- if (stale) stderr(chalk.yellow("⚠ Source has changed since last ingest. Run ix ingest to update.\n"));
- formatExplain(result, "text");
- }
+ })
+ );
+ callList = refs;
+ const unresolvedCount = refs.filter(r => !r.resolved).length;
+ if (unresolvedCount > 0) {
+ diagnostics.push({
+ code: "unresolved_call_target",
+ message: `${unresolvedCount} callee(s) could not be resolved to named entities. Use ix text to locate them.`,
+ });
+ }
+ }
+
+ if (stale) {
+ diagnostics.push({
+ code: "stale_source",
+ message: "Results may be stale; file has changed since last ingest.",
});
+ }
+
+ const result: ExplainResult & { stale?: boolean; warning?: string } = {
+ kind: node.kind,
+ name: node.name || node.attrs?.name || target.name,
+ id: target.id,
+ file: sourceUri,
+ container: container ? { kind: container.kind, name: container.name || container.attrs?.name || "(unknown)" } : undefined,
+ introducedRev: node.createdRev ?? node.created_rev,
+ calledBy: callEdges.filter((e: any) => e.dst === target.id).length,
+ calls: callEdges.filter((e: any) => e.src === target.id).length,
+ contains: containedEdges.length,
+ historyLength: (history as any)?.chain?.length ?? 0,
+ signature,
+ docstring,
+ callList,
+ diagnostics: diagnostics.length > 0 ? diagnostics : undefined,
+ };
+
+ if (stale) {
+ (result as any).stale = true;
+ (result as any).warning = "Results may be stale; file has changed since last ingest.";
+ }
+
+ if (format === "json") {
+ const output: any = {
+ resolvedTarget: { id: target.id, kind: target.kind, name: target.name },
+ resolutionMode: target.resolutionMode,
+ resultSource: "graph",
+ result,
+ };
+ if (stale) {
+ output.stale = true;
+ output.warning = "Results may be stale; file has changed since last ingest.";
+ }
+ console.log(JSON.stringify(output, null, 2));
+ } else {
+ if (stale) stderr(chalk.yellow("⚠ Source has changed since last ingest. Run ix ingest to update.\n"));
+ formatExplain(result, "text");
+ }
}
diff --git a/ix-cli/src/cli/explain/facts.ts b/ix-cli/src/cli/explain/facts.ts
new file mode 100644
index 00000000..f25aedd5
--- /dev/null
+++ b/ix-cli/src/cli/explain/facts.ts
@@ -0,0 +1,214 @@
+import type { IxClient } from "../../client/api.js";
+import type { EntityRef, Diagnostic } from "../format.js";
+import { isRawId } from "../resolve.js";
+import { isFileStale } from "../stale.js";
+import { buildDependencyTree } from "../commands/depends.js";
+
+export interface EntityFacts {
+ // Identity
+ id: string;
+ name: string;
+ kind: string;
+ path?: string;
+ signature?: string;
+ docstring?: string;
+
+ // Structural context
+ container?: { kind: string; name: string };
+ members: string[];
+ memberCount: number;
+
+ // Relationship counts
+ callerCount: number;
+ calleeCount: number;
+ dependentCount: number;
+ importerCount: number;
+
+ // Transitive downstream (via dependency tree)
+ downstreamDependents: number;
+ downstreamDepth: number;
+
+ // Named usage examples (up to 3 each)
+ topCallers: string[];
+ topDependents: string[];
+
+ // History
+ introducedRev?: number;
+ historyLength: number;
+
+ // Call details
+ callList?: EntityRef[];
+
+ // Staleness
+ stale: boolean;
+
+ // Diagnostics
+ diagnostics: Diagnostic[];
+}
+
+export async function collectFacts(
+ client: IxClient,
+ targetId: string,
+ targetName: string,
+ targetKind: string,
+): Promise<EntityFacts> {
+ const diagnostics: Diagnostic[] = [];
+
+ // Run parallel graph queries (including bounded downstream tree)
+ const [details, callersResult, calleesResult, dependentsResult, importersResult, membersResult, provenance, downstream] =
+ await Promise.all([
+ client.entity(targetId),
+ client.expand(targetId, { direction: "in", predicates: ["CALLS"] }),
+ client.expand(targetId, { direction: "out", predicates: ["CALLS"] }),
+ client.expand(targetId, { direction: "in", predicates: ["CALLS", "IMPORTS", "REFERENCES"] }),
+ client.expand(targetId, { direction: "in", predicates: ["IMPORTS"] }),
+ client.expand(targetId, { direction: "out", predicates: ["CONTAINS"] }),
+ client.provenance(targetId).catch(() => ({ entityId: targetId, chain: [] })),
+ buildDependencyTree(client, targetId, { maxDepth: 4, maxNodes: 100 }).catch(() => ({
+ tree: [], truncated: false, nodesVisited: 0, maxDepthReached: 0,
+ })),
+ ]);
+
+ const node = details.node as any;
+ const edges = (details.edges ?? []) as any[];
+
+ // Extract path
+ const path = node.provenance?.source_uri ?? node.provenance?.sourceUri ?? undefined;
+
+ // Extract container from CONTAINS edge (where this entity is the dst)
+ const containsEdge = edges.find(
+ (e: any) => e.predicate === "CONTAINS" && e.dst === targetId,
+ );
+ let container: { kind: string; name: string } | undefined;
+ if (containsEdge) {
+ try {
+ const containerDetails = await client.entity(containsEdge.src);
+ const cNode = containerDetails.node as any;
+ container = {
+ kind: cNode.kind || "unknown",
+ name: cNode.name || cNode.attrs?.name || "(unknown)",
+ };
+ } catch {
+ /* no container */
+ }
+ }
+
+ // Deduplicate dependents by node ID
+ const seenIds = new Set<string>();
+ const uniqueDependents = dependentsResult.nodes.filter((n: any) => {
+ if (seenIds.has(n.id)) return false;
+ seenIds.add(n.id);
+ return true;
+ });
+
+ // Members
+ const memberNames = membersResult.nodes.map(
+ (n: any) => n.name || n.attrs?.name || "(unnamed)",
+ );
+
+ // Named usage examples (up to 3 resolved names from callers/dependents)
+ const extractNames = (nodes: any[], limit: number): string[] => {
+ const names: string[] = [];
+ for (const n of nodes) {
+ if (names.length >= limit) break;
+ const name = n.name || n.attrs?.name || "";
+ if (name && !isRawId(name)) names.push(name);
+ }
+ return names;
+ };
+ const topCallers = extractNames(callersResult.nodes, 3);
+ const topDependents = extractNames(uniqueDependents, 3);
+
+ // Build callList from outgoing CALLS edges (reuse logic from explain.ts)
+ const calleeEdges = edges.filter(
+ (e: any) => e.predicate === "CALLS" && e.src === targetId,
+ );
+ let callList: EntityRef[] | undefined;
+ if (calleeEdges.length > 0 && calleeEdges.length <= 20) {
+ const refs = await Promise.all(
+ calleeEdges.map(async (e: any): Promise<EntityRef> => {
+ try {
+ const callee = await client.entity(e.dst);
+ const calleeNode = callee.node as any;
+ const name = calleeNode.name || calleeNode.attrs?.name || "";
+ if (!name || isRawId(name)) {
+ return {
+ name: name || e.dst,
+ kind: calleeNode.kind,
+ resolved: false,
+ suggestedCommand: `ix text "${e.dst.slice(0, 8)}"`,
+ };
+ }
+ return {
+ name,
+ kind: calleeNode.kind,
+ id: e.dst,
+ resolved: true,
+ path: calleeNode.provenance?.source_uri ?? calleeNode.provenance?.sourceUri,
+ suggestedCommand: `ix explain "${name}"`,
+ };
+ } catch {
+ return {
+ name: e.dst,
+ resolved: false,
+ diagnostic: "unresolved_call_target",
+ suggestedCommand: `ix text "${e.dst.slice(0, 8)}"`,
+ } as EntityRef;
+ }
+ }),
+ );
+ callList = refs;
+ const unresolvedCount = refs.filter((r) => !r.resolved).length;
+ if (unresolvedCount > 0) {
+ diagnostics.push({
+ code: "unresolved_call_target",
+ message: `${unresolvedCount} callee(s) could not be resolved to named entities.`,
+ });
+ }
+ }
+
+ // Staleness
+ let stale = false;
+ if (path) {
+ try {
+ stale = await isFileStale(client, path);
+ } catch {
+ /* ignore */
+ }
+ }
+ if (stale) {
+ diagnostics.push({
+ code: "stale_source",
+ message: "Results may be stale; file has changed since last ingest.",
+ });
+ }
+
+ const signature = node.attrs?.signature || node.attrs?.summary || undefined;
+ const docstring = node.attrs?.docstring || node.attrs?.description || undefined;
+ const history = provenance as any;
+
+ return {
+ id: targetId,
+ name: node.name || node.attrs?.name || targetName,
+ kind: node.kind || targetKind,
+ path,
+ signature,
+ docstring,
+ container,
+ members: memberNames,
+ memberCount: membersResult.nodes.length,
+ callerCount: callersResult.nodes.length,
+ calleeCount: calleesResult.nodes.length,
+ dependentCount: uniqueDependents.length,
+ importerCount: importersResult.nodes.length,
+ downstreamDependents: downstream.nodesVisited,
+ downstreamDepth: downstream.maxDepthReached,
+ topCallers,
+ topDependents,
+ introducedRev: node.createdRev ?? node.created_rev,
+ historyLength: history?.chain?.length ?? 0,
+ callList,
+ stale,
+ diagnostics,
+ };
+}
diff --git a/ix-cli/src/cli/explain/importance.ts b/ix-cli/src/cli/explain/importance.ts
new file mode 100644
index 00000000..e1916add
--- /dev/null
+++ b/ix-cli/src/cli/explain/importance.ts
@@ -0,0 +1,103 @@
+import type { EntityFacts } from "./facts.js";
+
+export type ImportanceCategory =
+ | "broad-shared-dependency"
+ | "pipeline-choke-point"
+ | "localized-helper"
+ | "normal";
+
+export interface ImportanceInference {
+ level: "low" | "medium" | "high";
+ category: ImportanceCategory;
+ reasons: string[];
+}
+
+export function inferImportance(facts: EntityFacts): ImportanceInference {
+ const reasons: string[] = [];
+
+ // ── Collect high-level signals ────────────────────────────────────────
+
+ const directlyBroad =
+ facts.callerCount >= 8 ||
+ facts.dependentCount >= 10 ||
+ facts.importerCount >= 5;
+
+ const largeMemberHub =
+ facts.memberCount >= 10 && facts.callerCount >= 3;
+
+ const isHigh = directlyBroad || largeMemberHub;
+
+ const isLow =
+ facts.dependentCount === 0 &&
+ facts.callerCount <= 1 &&
+ facts.importerCount === 0 &&
+ facts.memberCount <= 1 &&
+ facts.downstreamDependents <= 1;
+
+ // Pipeline choke point: few direct callers but large downstream cone
+ const isChokePoint =
+ facts.callerCount <= 2 &&
+ facts.downstreamDependents >= 8;
+
+ // Localized helper: few direct callers, small downstream cone
+ const isLocalizedHelper =
+ facts.callerCount <= 2 &&
+ facts.downstreamDependents <= 3 &&
+ !isHigh;
+
+ // ── Determine level + category ────────────────────────────────────────
+
+ if (isChokePoint) {
+ // Choke points are always at least high importance regardless of direct counts
+ if (facts.dependentCount >= 10) {
+ reasons.push(`${facts.dependentCount} direct dependents — widely depended upon`);
+ }
+ if (facts.callerCount > 0) {
+ reasons.push(`Only ${facts.callerCount} direct caller(s)`);
+ }
+ reasons.push(
+ `${facts.downstreamDependents} downstream dependents across ${facts.downstreamDepth} levels — structurally critical pipeline node`,
+ );
+ return { level: "high", category: "pipeline-choke-point", reasons };
+ }
+
+ if (isHigh) {
+ if (facts.dependentCount >= 10) {
+ reasons.push(`${facts.dependentCount} dependents — widely depended upon`);
+ }
+ if (facts.callerCount >= 8) {
+ reasons.push(`Called by ${facts.callerCount} other entities`);
+ }
+ if (facts.importerCount >= 5) {
+ reasons.push(`Imported by ${facts.importerCount} modules`);
+ }
+ if (largeMemberHub) {
+ reasons.push(`Large entity (${facts.memberCount} members) with ${facts.callerCount} callers`);
+ }
+ return { level: "high", category: "broad-shared-dependency", reasons };
+ }
+
+ if (isLow) {
+ reasons.push("Minimal inbound connections — low impact if changed");
+ const cat: ImportanceCategory = isLocalizedHelper ? "localized-helper" : "normal";
+ return { level: "low", category: cat, reasons };
+ }
+
+ // ── Medium ────────────────────────────────────────────────────────────
+
+ if (facts.callerCount > 0) {
+ reasons.push(`Called by ${facts.callerCount} other entities`);
+ }
+ if (facts.dependentCount > 0) {
+ reasons.push(`${facts.dependentCount} dependents`);
+ }
+ if (facts.importerCount > 0) {
+ reasons.push(`Imported by ${facts.importerCount} modules`);
+ }
+ if (facts.downstreamDependents > 3) {
+ reasons.push(`${facts.downstreamDependents} downstream dependents`);
+ }
+
+ const cat: ImportanceCategory = isLocalizedHelper ? "localized-helper" : "normal";
+ return { level: "medium", category: cat, reasons };
+}
diff --git a/ix-cli/src/cli/explain/render.ts b/ix-cli/src/cli/explain/render.ts
new file mode 100644
index 00000000..88b1753e
--- /dev/null
+++ b/ix-cli/src/cli/explain/render.ts
@@ -0,0 +1,312 @@
+import type { EntityFacts } from "./facts.js";
+import type { RoleInference, RoleLabel } from "./role-inference.js";
+import type { ImportanceInference } from "./importance.js";
+
+export interface ExplanationOutput {
+ explanation: string;
+ context: string;
+ usedBy: string | null;
+ whyItMatters: string;
+ notes: string[];
+}
+
+// ── Role description templates ──────────────────────────────────────────────
+
+/** Build a role description that incorporates container/file context when available. */
+function describeRole(role: RoleLabel, facts: EntityFacts): string {
+ const containerName = facts.container?.name;
+ const file = fileBaseName(facts.path);
+
+ switch (role) {
+ case "test":
+ return "a test or specification";
+ case "configuration":
+ return "a configuration source";
+ case "type-definition":
+ return "a type definition";
+ case "data-model":
+ return "a data model";
+ case "api-client":
+ return "the main backend API client for the CLI";
+ case "entry-point":
+ return "an entry point";
+ case "registration-function":
+ return file
+ ? `a command registration function in ${file}`
+ : "a command registration function";
+ case "service":
+ return "a service coordinating multiple operations";
+ case "service-method":
+ return containerName
+ ? `a method within ${containerName}`
+ : "a service method";
+ case "adapter":
+ return "an adapter bridging external systems";
+ case "orchestrator":
+ return "an orchestrator coordinating multiple downstream operations";
+ case "resolution-helper":
+ return containerName
+ ? `a resolution method inside ${containerName}`
+ : file
+ ? `a shared resolution method in the ${file} pipeline`
+ : "a resolution or lookup helper";
+ case "selection-helper":
+ return containerName
+ ? `a selection helper inside ${containerName}`
+ : file
+ ? `a selection helper in the ${file} pipeline`
+ : "a selection helper that picks or ranks candidates";
+ case "scoring-helper":
+ return file
+ ? `a scoring function used by the ${file} pipeline`
+ : "a scoring or ranking helper";
+ case "container":
+ return `a container module with ${facts.memberCount} members`;
+ case "shared-utility":
+ return "a widely shared utility function";
+ case "localized-helper":
+ if (containerName) return `a helper within ${containerName}`;
+ if (file) return `a localized helper defined in ${file}`;
+ return "a localized internal helper";
+ case "unknown":
+ // Context-aware fallback — never say "role could not be determined"
+ if (containerName) return `a member of ${containerName}`;
+ if (file) return `a localized helper defined in ${file}`;
+ return "a localized internal helper";
+ }
+}
+
+function fileBaseName(path?: string): string {
+ if (!path) return "";
+ const base = path.split("/").pop() ?? "";
+ return base.replace(/\.[^.]+$/, "");
+}
+
+// ── Confidence-to-language mapping ───────────────────────────────────────────
+
+function phrasingForConfidence(confidence: "low" | "medium" | "high"): {
+ roleVerb: string;
+ impactVerb: string;
+} {
+ if (confidence === "high") return { roleVerb: "serves as", impactVerb: "will" };
+ if (confidence === "medium") return { roleVerb: "is likely", impactVerb: "may" };
+ return { roleVerb: "appears to be", impactVerb: "may" };
+}
+
+// ── Main render ─────────────────────────────────────────────────────────────
+
+export function renderExplanation(
+ facts: EntityFacts,
+ role: RoleInference,
+ importance: ImportanceInference,
+): ExplanationOutput {
+ // ── Explanation ────────────────────────────────────────────────────────
+ const roleDesc = describeRole(role.role, facts);
+ const phrasing = phrasingForConfidence(role.confidence);
+ let explanation = `\`${facts.name}\` ${phrasing.roleVerb} ${roleDesc}.`;
+
+ if (facts.signature) {
+ explanation += ` Signature: \`${facts.signature}\`.`;
+ }
+
+ if (facts.docstring) {
+ explanation += ` ${facts.docstring}`;
+ }
+
+ // ── Context ───────────────────────────────────────────────────────────
+ const contextLines: string[] = [];
+
+ if (facts.path) {
+ contextLines.push(`Defined in: ${facts.path}`);
+ }
+
+ if (facts.container) {
+ contextLines.push(`Container: ${facts.container.kind} ${facts.container.name}`);
+ }
+
+ if (facts.callerCount > 0) {
+ contextLines.push(`Called by: ${facts.callerCount} entities`);
+ }
+
+ if (facts.calleeCount > 0) {
+ contextLines.push(`Calls: ${facts.calleeCount} entities`);
+ }
+
+ if (facts.memberCount > 0) {
+ contextLines.push(`Contains: ${facts.memberCount} members`);
+ }
+
+ if (facts.importerCount > 0) {
+ contextLines.push(`Imported by: ${facts.importerCount} modules`);
+ }
+
+ if (facts.downstreamDependents > 0) {
+ contextLines.push(`Downstream dependents: ${facts.downstreamDependents} (depth ${facts.downstreamDepth})`);
+ }
+
+ if (facts.introducedRev !== undefined) {
+ contextLines.push(`First seen: rev ${facts.introducedRev}`);
+ }
+
+ if (facts.historyLength > 0) {
+ contextLines.push(`Patch history: ${facts.historyLength} patches`);
+ }
+
+ const context = contextLines.join("\n");
+
+ // ── Used by (named examples) ──────────────────────────────────────────
+ const usedBy = renderUsedBy(facts);
+
+ // ── Why it matters (role + importance fusion) ─────────────────────────
+ const whyItMatters = renderWhyItMatters(facts, role, importance, phrasing);
+
+ // ── Notes (clean diagnostics) ─────────────────────────────────────────
+ const notes = renderNotes(facts);
+
+ return { explanation, context, usedBy, whyItMatters, notes };
+}
+
+// ── Used by ─────────────────────────────────────────────────────────────────
+
+function renderUsedBy(facts: EntityFacts): string | null {
+ const examples = facts.topCallers.length > 0
+ ? facts.topCallers
+ : facts.topDependents;
+
+ if (examples.length === 0) return null;
+
+ const total = Math.max(facts.callerCount, facts.dependentCount);
+
+ if (examples.length === 1) {
+ if (total > 1) {
+ return `Used by ${examples[0]} and ${total - 1} other${total - 1 === 1 ? "" : "s"}.`;
+ }
+ return `Used by ${examples[0]}.`;
+ }
+
+ const listed = examples.slice(0, 3).join(", ");
+ const remaining = total - examples.length;
+ if (remaining > 0) {
+ return `Used by ${listed}, and ${remaining} other${remaining === 1 ? "" : "s"}.`;
+ }
+ return `Used by ${listed}.`;
+}
+
+// ── Why it matters ──────────────────────────────────────────────────────────
+
+function renderWhyItMatters(
+ facts: EntityFacts,
+ role: RoleInference,
+ importance: ImportanceInference,
+ phrasing: { roleVerb: string; impactVerb: string },
+): string {
+ const { level, category } = importance;
+ const verb = phrasing.impactVerb; // "will" for high confidence, "may" for medium/low
+
+ if (category === "pipeline-choke-point") {
+ const callerPhrase = facts.callerCount === 1
+ ? "only 1 direct caller"
+ : `only ${facts.callerCount} direct callers`;
+ return (
+ `Although it has ${callerPhrase}, it sits in a path with ` +
+ `${facts.downstreamDependents} downstream dependents, making it a ` +
+ `structurally important decision point in the pipeline. ` +
+ `Consider running \`ix impact ${facts.name}\` before modifying.`
+ );
+ }
+
+ if (category === "broad-shared-dependency") {
+ const roleContext = roleFusionPhrase(role.role, facts);
+ if (roleContext) {
+ return (
+ `${roleContext}, changes here ${verb} propagate across the codebase. ` +
+ `Run \`ix impact ${facts.name}\` before modifying.`
+ );
+ }
+ const reasonStr = importance.reasons.length > 0
+ ? importance.reasons[0]
+ : "High connectivity";
+ return (
+ `${reasonStr}. This is a central shared dependency — changes ${verb} propagate broadly. ` +
+ `Run \`ix impact ${facts.name}\` before modifying.`
+ );
+ }
+
+ if (category === "localized-helper") {
+ return (
+ "Its usage is localized, suggesting it is a narrow internal helper " +
+ "with limited system-wide impact."
+ );
+ }
+
+ // normal category
+ if (level === "high") {
+ const roleContext = roleFusionPhrase(role.role, facts);
+ if (roleContext) {
+ return (
+ `${roleContext}, changes here ${verb} have wide impact. ` +
+ `Run \`ix impact ${facts.name}\` before modifying.`
+ );
+ }
+ const reasonStr = importance.reasons.length > 0
+ ? importance.reasons[0]
+ : "This entity has high connectivity";
+ return (
+ `${reasonStr}. Changes here ${verb} have wide impact — run ` +
+ `\`ix impact ${facts.name}\` before modifying.`
+ );
+ }
+
+ if (level === "low") {
+ return (
+ "Minimal inbound connections. " +
+ "Changes are unlikely to affect other parts of the codebase."
+ );
+ }
+
+ // medium / normal
+ const reasonStr = importance.reasons.length > 0
+ ? importance.reasons[0]
+ : "Moderate connectivity";
+ return (
+ `${reasonStr}. ` +
+ "Review callers before making breaking changes."
+ );
+}
+
+/** Generate a role-specific lead phrase for why-it-matters. */
+function roleFusionPhrase(role: RoleLabel, facts: EntityFacts): string | null {
+ switch (role) {
+ case "api-client":
+ return `As the central API client used across ${facts.callerCount > 0 ? facts.callerCount + " commands" : "the codebase"}`;
+ case "service":
+ return `As a core service with ${facts.memberCount} methods`;
+ case "shared-utility":
+ return `As a shared utility called by ${facts.callerCount} entities`;
+ case "resolution-helper":
+ return `As a resolution helper in the matching pipeline`;
+ case "orchestrator":
+ return `As an orchestrator coordinating ${facts.calleeCount} operations`;
+ default:
+ return null;
+ }
+}
+
+// ── Notes (human-readable diagnostics) ──────────────────────────────────────
+
+function renderNotes(facts: EntityFacts): string[] {
+ const notes: string[] = [];
+ for (const d of facts.diagnostics) {
+ switch (d.code) {
+ case "unresolved_call_target":
+ notes.push("Some downstream calls could not be resolved to named entities. Run `ix ingest` to improve coverage.");
+ break;
+ case "stale_source":
+ notes.push("Source file has changed since last ingest — results may be incomplete.");
+ break;
+ default:
+ notes.push(d.message);
+ }
+ }
+ return notes;
+}
diff --git a/ix-cli/src/cli/explain/role-inference.ts b/ix-cli/src/cli/explain/role-inference.ts
new file mode 100644
index 00000000..90ff4b5b
--- /dev/null
+++ b/ix-cli/src/cli/explain/role-inference.ts
@@ -0,0 +1,352 @@
+import type { EntityFacts } from "./facts.js";
+
+export type RoleLabel =
+ | "test"
+ | "configuration"
+ | "type-definition"
+ | "data-model"
+ | "api-client"
+ | "entry-point"
+ | "registration-function"
+ | "service"
+ | "service-method"
+ | "adapter"
+ | "orchestrator"
+ | "resolution-helper"
+ | "selection-helper"
+ | "scoring-helper"
+ | "container"
+ | "shared-utility"
+ | "localized-helper"
+ | "unknown";
+
+export interface RoleInference {
+ role: RoleLabel;
+ confidence: "low" | "medium" | "high";
+ reasons: string[];
+}
+
+/** Split a name into tokens for camelCase, snake_case, and kebab-case. */
+function tokenize(name: string): string[] {
+ return name
+ .split(/(?=[A-Z])|_|-/)
+ .map((t) => t.toLowerCase())
+ .filter(Boolean);
+}
+
+/** Extract file name (without extension) from a path. */
+function fileName(path?: string): string {
+ if (!path) return "";
+ const base = path.split("/").pop() ?? "";
+ return base.replace(/\.[^.]+$/, "").toLowerCase();
+}
+
+function nameOrPathContains(facts: EntityFacts, ...terms: string[]): boolean {
+ const lower = (facts.name ?? "").toLowerCase();
+ const pathLower = (facts.path ?? "").toLowerCase();
+ return terms.some((t) => lower.includes(t) || pathLower.includes(t));
+}
+
+function pathContains(facts: EntityFacts, ...terms: string[]): boolean {
+ const pathLower = (facts.path ?? "").toLowerCase();
+ return terms.some((t) => pathLower.includes(t));
+}
+
+export function inferRole(facts: EntityFacts): RoleInference {
+ const reasons: string[] = [];
+ let role: RoleLabel = "unknown";
+ let confidence: "low" | "medium" | "high" = "low";
+
+ const tokens = tokenize(facts.name);
+ const kind = (facts.kind ?? "").toLowerCase();
+ const file = fileName(facts.path);
+ const fileTokens = tokenize(file);
+ const memberLower = facts.members.map((m) => m.toLowerCase());
+ const containerName = facts.container?.name ?? "";
+ const containerKind = (facts.container?.kind ?? "").toLowerCase();
+ const containerTokens = tokenize(containerName);
+
+ // ── 1. Test ──────────────────────────────────────────────────────────
+ if (
+ nameOrPathContains(facts, "test", "spec", "__tests__") ||
+ tokens.includes("test") ||
+ tokens.includes("spec")
+ ) {
+ role = "test";
+ confidence = "high";
+ reasons.push("Name or path indicates a test file or test entity");
+ }
+
+ // ── 2. Configuration ─────────────────────────────────────────────────
+ if (role === "unknown") {
+ if (
+ kind === "config_entry" ||
+ nameOrPathContains(facts, "config", ".env", ".yaml", ".yml", ".toml")
+ ) {
+ role = "configuration";
+ confidence = "high";
+ reasons.push("Entity kind or naming indicates configuration");
+ }
+ }
+
+ // ── 3. Type definition ───────────────────────────────────────────────
+ if (role === "unknown") {
+ if (
+ kind === "interface" ||
+ kind === "type" ||
+ kind === "type_alias" ||
+ tokens.some((t) => ["type", "props", "schema"].includes(t))
+ ) {
+ role = "type-definition";
+ confidence = "high";
+ reasons.push("Entity is an interface, type alias, or has type-related naming");
+ }
+ }
+
+ // ── 4. API client / backend client ───────────────────────────────────
+ if (role === "unknown") {
+ const apiPathSignals = pathContains(facts, "api", "client", "http");
+ const apiNameSignals = tokens.some((t) =>
+ ["client", "api"].includes(t),
+ );
+ const clientMethodNames = new Set([
+ "get", "post", "put", "delete", "patch", "fetch", "request",
+ "query", "search", "entity", "expand", "ingest",
+ ]);
+ const clientMethodCount = memberLower.filter((m) => clientMethodNames.has(m)).length;
+ const hasClientMethods = clientMethodCount >= 2;
+
+ if (kind === "class" && (apiNameSignals || apiPathSignals) && (hasClientMethods || facts.memberCount > 2)) {
+ role = "api-client";
+ confidence = "high";
+ reasons.push("Class with API/client naming and HTTP-like methods");
+ if (facts.callerCount > 0 || facts.dependentCount > 0) {
+ reasons.push(`Used by ${facts.callerCount} callers / ${facts.dependentCount} dependents`);
+ }
+ } else if (
+ kind === "class" &&
+ hasClientMethods &&
+ facts.memberCount > 3 &&
+ facts.calleeCount > 0
+ ) {
+ role = "api-client";
+ confidence = "medium";
+ reasons.push("Class with multiple HTTP-like methods and outgoing calls");
+ }
+ }
+
+ // ── 5. Registration function ─────────────────────────────────────────
+ if (role === "unknown") {
+ const callableKinds = new Set(["function", "method"]);
+ if (
+ callableKinds.has(kind) &&
+ tokens[0] === "register"
+ ) {
+ role = "registration-function";
+ const bootPath = pathContains(facts, "command", "cli", "bootstrap", "main", "register");
+ confidence = bootPath ? "high" : "medium";
+ reasons.push("Function name starts with 'register'");
+ if (bootPath) reasons.push("Located in a CLI/command registration path");
+ }
+ }
+
+ // ── 6. Selection helper (checked before resolution-helper — more specific) ─
+ if (role === "unknown") {
+ const selectionNames = ["pick", "best", "select", "choose", "rank", "filter"];
+ const hasSelectionName = tokens.some((t) => selectionNames.includes(t));
+ const selectionPathSignals = pathContains(facts, "resolve", "select", "pick", "rank", "match");
+ const callableKinds = new Set(["function", "method"]);
+
+ if (callableKinds.has(kind) && hasSelectionName) {
+ role = "selection-helper";
+ confidence = selectionPathSignals ? "high" : "medium";
+ reasons.push("Name suggests a selection or ranking function");
+ if (selectionPathSignals) reasons.push("Located in a resolution/selection path");
+ }
+ }
+
+ // ── 7. Scoring helper ────────────────────────────────────────────────
+ if (role === "unknown") {
+ const scoringNames = ["score", "weight", "rank", "rate", "evaluate"];
+ const hasScoringName = tokens.some((t) => scoringNames.includes(t));
+ const scoringFilePath = pathContains(facts, "importance", "ranking", "score", "weight");
+ const callableKinds = new Set(["function", "method"]);
+
+ if (callableKinds.has(kind) && (hasScoringName || scoringFilePath)) {
+ role = "scoring-helper";
+ confidence = hasScoringName && scoringFilePath ? "high" : "medium";
+ reasons.push("Name or file path suggests a scoring or ranking function");
+ }
+ }
+
+ // ── 8. Resolution helper ─────────────────────────────────────────────
+ if (role === "unknown") {
+ const resolveNameSignals = tokens.some((t) =>
+ ["resolve", "resolver", "lookup", "match"].includes(t),
+ );
+ const resolvePathSignals = pathContains(facts, "resolve", "resolver", "match", "lookup");
+ const callableKinds = new Set(["function", "method"]);
+
+ if (
+ callableKinds.has(kind) &&
+ (resolveNameSignals || resolvePathSignals) &&
+ facts.calleeCount > 0
+ ) {
+ role = "resolution-helper";
+ confidence = resolveNameSignals && resolvePathSignals ? "high" : "medium";
+ reasons.push("Name/path suggests resolution or lookup behavior");
+ if (facts.calleeCount > 0) reasons.push(`Calls ${facts.calleeCount} downstream entities`);
+ }
+ }
+
+ // ── 9. Data model ────────────────────────────────────────────────────
+ if (role === "unknown") {
+ const modelTerms = ["model", "entity", "record", "dto"];
+ const hasModelName =
+ kind === "class" && tokens.some((t) => modelTerms.includes(t));
+ const isDataClass =
+ kind === "class" && facts.callerCount > 0 && facts.calleeCount === 0 && facts.memberCount <= 2;
+ if (hasModelName || isDataClass) {
+ role = "data-model";
+ confidence = hasModelName ? "high" : "medium";
+ if (hasModelName) reasons.push("Class name suggests a data model");
+ if (isDataClass) reasons.push("Class has callers but makes no outgoing calls and has few members");
+ }
+ }
+
+ // ── 10. Entry point ──────────────────────────────────────────────────
+ if (role === "unknown") {
+ const callableKinds = new Set(["function", "method"]);
+ if (
+ facts.callerCount === 0 &&
+ facts.calleeCount > 0 &&
+ callableKinds.has(kind)
+ ) {
+ role = "entry-point";
+ const entryNames = ["main", "run", "start", "handler", "execute"];
+ const isNamedEntry = tokens.some((t) => entryNames.includes(t));
+ confidence = isNamedEntry ? "high" : "medium";
+ reasons.push("Function has no callers but calls other entities");
+ if (isNamedEntry) reasons.push("Name suggests an entry point");
+ }
+ }
+
+ // ── 11. Service ──────────────────────────────────────────────────────
+ if (role === "unknown") {
+ const containerKindSet = new Set(["class", "object"]);
+ const serviceTerms = ["service", "manager", "provider", "handler", "controller", "coordinator"];
+ if (
+ containerKindSet.has(kind) &&
+ facts.memberCount > 2 &&
+ tokens.some((t) => serviceTerms.includes(t))
+ ) {
+ role = "service";
+ confidence = "high";
+ reasons.push("Class/object with multiple members and service-like naming");
+ }
+ }
+
+ // ── 12. Service method (container-aware) ─────────────────────────────
+ if (role === "unknown") {
+ const callableKinds = new Set(["function", "method"]);
+ const serviceTerms = ["service", "manager", "provider", "handler", "controller", "coordinator"];
+ const containerIsService =
+ containerKind === "class" &&
+ containerTokens.some((t) => serviceTerms.includes(t));
+
+ if (callableKinds.has(kind) && containerIsService) {
+ role = "service-method";
+ confidence = "high";
+ reasons.push(`Method inside ${containerName}`);
+ }
+ }
+
+ // ── 13. Adapter ──────────────────────────────────────────────────────
+ if (role === "unknown") {
+ if (nameOrPathContains(facts, "adapter", "connector", "gateway", "proxy")) {
+ role = "adapter";
+ confidence = "medium";
+ reasons.push("Name or path suggests an adapter or external integration");
+ }
+ }
+
+ // ── 14. Orchestrator ────────────────────────────────────────────────
+ if (role === "unknown") {
+ if (facts.calleeCount >= 5 && facts.callerCount <= 2) {
+ role = "orchestrator";
+ confidence = "medium";
+ reasons.push(`Calls ${facts.calleeCount} entities but has only ${facts.callerCount} callers`);
+ }
+ }
+
+ // ── 15. Container ───────────────────────────────────────────────────
+ if (role === "unknown") {
+ const containerKindSet = new Set(["file", "module"]);
+ if (containerKindSet.has(kind) && facts.memberCount > 0) {
+ role = "container";
+ confidence = "high";
+ reasons.push(`${kind} containing ${facts.memberCount} members`);
+ }
+ }
+
+ // ── 16. Shared utility (many direct callers) ────────────────────────
+ if (role === "unknown") {
+ if (
+ facts.callerCount >= 3 &&
+ facts.memberCount === 0 &&
+ facts.calleeCount <= 2
+ ) {
+ role = "shared-utility";
+ confidence = "medium";
+ reasons.push(`Called by ${facts.callerCount} entities with no members — widely shared utility`);
+ }
+ }
+
+ // ── 17. Localized helper ────────────────────────────────────────────
+ if (role === "unknown") {
+ const callableKinds = new Set(["function", "method"]);
+ if (
+ callableKinds.has(kind) &&
+ facts.callerCount >= 1 &&
+ facts.callerCount <= 2 &&
+ facts.calleeCount > 0
+ ) {
+ role = "localized-helper";
+ confidence = "medium";
+ reasons.push(`Few callers (${facts.callerCount}) with outgoing calls — appears to be a localized helper`);
+ }
+ }
+
+ // ── 18. Context-aware fallback (no more "role could not be determined") ──
+ if (role === "unknown") {
+ const callableKinds = new Set(["function", "method"]);
+
+ if (callableKinds.has(kind) && containerName) {
+ // Method/function inside a known container
+ role = "localized-helper";
+ confidence = "low";
+ reasons.push(`${kind} within ${containerName}`);
+ } else if (callableKinds.has(kind) && facts.path) {
+ // Function in a known file
+ role = "localized-helper";
+ confidence = "low";
+ reasons.push(`${kind} defined in ${fileName(facts.path)}`);
+ } else if (kind === "class" || kind === "object") {
+ role = "localized-helper";
+ confidence = "low";
+ reasons.push(`${kind} with limited structural signals`);
+ } else {
+ // Truly minimal — still avoid "role could not be determined"
+ confidence = "low";
+ if (facts.path) {
+ reasons.push(`Defined in ${fileName(facts.path)}`);
+ } else if (containerName) {
+ reasons.push(`Located within ${containerName}`);
+ } else {
+ reasons.push("Limited structural signals available");
+ }
+ }
+ }
+
+ return { role, confidence, reasons };
+}