Skip to content

armgit / Ix

Public Imported from GitHub
0

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

feat(cli): callers, callees and impact say when the graph is degraded

KageBinary7e5c568e7485
diff --git a/ix-cli/src/cli/__tests__/graph-health-edges.test.ts b/ix-cli/src/cli/__tests__/graph-health-edges.test.ts
new file mode 100644
index 00000000..9c4691b9
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/graph-health-edges.test.ts
@@ -0,0 +1,63 @@
+// Copyright 2026 Ix Infrastructure Inc.
+
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { withheldOnDegraded } from "../commands/impact.js";
+import { formatEdgeResults, renderEdgeResultsLlm, sliceEdgeResults, type Diagnostic } from "../format.js";
+import { assessGraphStats, graphHealthJson, graphHealthProse } from "../graph-health.js";
+import { inferRiskSemantics } from "../impact/risk-semantics.js";
+
+/**
+ * `ix callers`, `ix callees` and `ix impact` on a hollowed graph: an empty
+ * edge list there is lost edges, not "no callers", and "low risk" is "no
+ * edges left", not "safe to change". Each says so instead.
+ */
+
+const DEGRADED = assessGraphStats({
+ nodes: { total: 9243, byKind: [{ kind: "file", count: 333 }, { kind: "function", count: 8910 }] },
+ edges: { total: 387, byPredicate: [{ predicate: "CONTAINS", count: 38 }, { predicate: "CALLS", count: 222 }] },
+});
+const DIAG: Diagnostic[] = [{ code: "graph_degraded", message: graphHealthProse(DEGRADED) }];
+
+afterEach(() => vi.restoreAllMocks());
+
+describe("edge results on a degraded graph", () => {
+ it("llm: the degraded diagnostic replaces a bare no_edges", () => {
+ const lines = renderEdgeResultsLlm(sliceEdgeResults([], 50), "callers", "parseBudgetOption", "graph", DIAG);
+ expect(lines.some((l) => l.startsWith("diagnostic code=graph_degraded"))).toBe(true);
+ expect(lines.some((l) => l.includes("code=no_edges"))).toBe(false);
+ });
+
+ it("json: carries the diagnostic, not no_edges", () => {
+ const out: string[] = [];
+ vi.spyOn(console, "log").mockImplementation((s: string) => { out.push(s); });
+ formatEdgeResults(sliceEdgeResults([], 50), "callees", "budgetParser", "json", undefined, "graph", DIAG);
+ const parsed = JSON.parse(out.join("\n"));
+ expect(parsed.diagnostics.map((d: Diagnostic) => d.code)).toEqual(["graph_degraded"]);
+ });
+
+ it("text: an empty result gives the degraded reason, once", () => {
+ const out: string[] = [];
+ vi.spyOn(console, "log").mockImplementation((s: string) => { out.push(s); });
+ formatEdgeResults(sliceEdgeResults([], 50), "callees", "budgetParser", "text", undefined, "graph", DIAG);
+ expect(out).toEqual([graphHealthProse(DEGRADED)]);
+ });
+});
+
+describe("impact risk on a degraded graph", () => {
+ const risk = inferRiskSemantics({
+ name: "parseBudgetOption", kind: "function", path: "ix-cli/src/cli/options.ts",
+ members: 0, callers: 0, callees: 0, directImporters: 0, directDependents: 0, memberLevelCallers: 0,
+ propagationBuckets: [], topCallerNames: [],
+ });
+
+ it("is withheld as unknown", () => {
+ const withheld = withheldOnDegraded(risk, graphHealthJson(DEGRADED));
+ expect(withheld.riskLevel as string).toBe("unknown");
+ expect(withheld.riskSummary).toMatch(/^Unknown: this workspace's graph is missing/);
+ });
+
+ it("is unchanged on a healthy graph", () => {
+ expect(withheldOnDegraded(risk, undefined)).toBe(risk);
+ });
+});
diff --git a/ix-cli/src/cli/commands/callers.ts b/ix-cli/src/cli/commands/callers.ts
index 96d90e00..29142ff0 100644
--- a/ix-cli/src/cli/commands/callers.ts
+++ b/ix-cli/src/cli/commands/callers.ts
@@ -6,14 +6,32 @@ import type { Command } from "commander";
import chalk from "chalk";
import { IxClient } from "../../client/api.js";
import { getEndpoint, resolveWorkspaceRoot } from "../config.js";
-import { formatEdgeResults, printJson, relativePath, sliceEdgeResults } from "../format.js";
+import { formatEdgeResults, printJson, relativePath, sliceEdgeResults, type Diagnostic } from "../format.js";
+import { checkGraphHealth, graphHealthProse, isUnhealthy, type GraphHealth } from "../graph-health.js";
import { parsePickOption } from "../options.js";
-import { resolveFileOrReport, printResolved } from "../resolve.js";
+import { activeReadScope, resolveFileOrReport, printResolved } from "../resolve.js";
import { stderr } from "../stderr.js";
import { llmLine } from "../llm.js";
+import { renderWarning } from "../ui.js";
const execFileAsync = promisify(execFile);
+/**
+ * The graph's health, as edge-result diagnostics. On a hollowed graph "no
+ * callers" is a count of lost edges, not an answer. llm and json carry a
+ * `graph_degraded` diagnostic; text shows it as the reason for an empty result
+ * (formatEdgeResults) or, over rows, as a banner (`bannerOverRows`).
+ */
+async function healthDiagnostics(health: Promise<GraphHealth>): Promise<{ diagnostics?: Diagnostic[]; fix?: string }> {
+ const h = await health;
+ if (!isUnhealthy(h)) return {};
+ return { diagnostics: [{ code: "graph_degraded", message: graphHealthProse(h) }], fix: h.fix };
+}
+
+function bannerOverRows(health: { diagnostics?: Diagnostic[] }, format: string, rows: number): void {
+ if (format === "text" && rows > 0 && health.diagnostics) renderWarning(health.diagnostics[0].message);
+}
+
export function registerCallersCommand(program: Command): void {
program
.command("callers <symbol>")
@@ -31,11 +49,17 @@ export function registerCallersCommand(program: Command): void {
const target = await resolveFileOrReport(client, symbol, resolveOpts, opts.format);
if (!target) return;
if (opts.format === "text") printResolved(target);
+ const healthCheck = checkGraphHealth(client, activeReadScope());
// Use expand by entity ID to avoid aggregating results across all same-named entities
const result = await client.expand(target.id, {
direction: "in",
predicates: ["CALLS", "REFERENCES"],
});
+ const health = await healthDiagnostics(healthCheck);
+ bannerOverRows(health, opts.format, result.nodes.length);
+ // `ix ingest --force` does not bring a hollowed graph's edges back; the
+ // health check names what does.
+ const remedy = health.fix ?? "ix ingest --force --recursive .";
if (result.nodes.length === 0) {
// Fallback to text search
@@ -78,6 +102,9 @@ export function registerCallersCommand(program: Command): void {
["code", "text_fallback_used"],
["message", "No graph-backed CALLS/REFERENCES edges; showing text matches."],
]));
+ for (const d of health.diagnostics ?? []) {
+ console.log(llmLine("diagnostic", [["code", d.code], ["message", d.message]]));
+ }
for (const r of textResults) {
console.log(llmLine("ref", [["path", r.path], ["line", r.line], ["snippet", r.attrs?.snippet ?? ""]]));
}
@@ -94,12 +121,13 @@ export function registerCallersCommand(program: Command): void {
},
diagnostics: [{
code: "text_fallback_used",
- message: "No graph-backed CALLS/REFERENCES edges found. If files were ingested before extraction was added, run: ix ingest --force --recursive .",
- }],
+ message: `No graph-backed CALLS/REFERENCES edges found. If files were ingested before extraction was added, run: ${remedy}`,
+ }, ...(health.diagnostics ?? [])],
});
} else {
+ bannerOverRows(health, opts.format, textResults.length);
stderr(chalk.dim("No graph-backed CALLS/REFERENCES edges found. Showing text-based candidate usages."));
- stderr(chalk.dim("Tip: if files were ingested before CALLS extraction, run: ix ingest --force --recursive .\n"));
+ stderr(chalk.dim(`Tip: if files were ingested before CALLS extraction, run: ${remedy}\n`));
for (const r of textResults) {
const snippet = r.attrs?.snippet ?? "";
console.log(` ${chalk.dim(r.name)} ${snippet}`);
@@ -113,9 +141,9 @@ export function registerCallersCommand(program: Command): void {
} catch { /* ripgrep not available or no matches */ }
// Both graph and text empty
- formatEdgeResults(sliceEdgeResults([], limit), "callers", target.name, opts.format, target, "graph");
+ formatEdgeResults(sliceEdgeResults([], limit), "callers", target.name, opts.format, target, "graph", health.diagnostics);
} else {
- formatEdgeResults(sliceEdgeResults(result.nodes, limit), "callers", target.name, opts.format, target, "graph");
+ formatEdgeResults(sliceEdgeResults(result.nodes, limit), "callers", target.name, opts.format, target, "graph", health.diagnostics);
}
});
@@ -135,11 +163,14 @@ export function registerCallersCommand(program: Command): void {
const target = await resolveFileOrReport(client, symbol, resolveOpts, opts.format);
if (!target) return;
if (opts.format === "text") printResolved(target);
+ const healthCheck = checkGraphHealth(client, activeReadScope());
// Use expand by entity ID to avoid aggregating results across all same-named entities
const result = await client.expand(target.id, {
direction: "out",
predicates: ["CALLS", "REFERENCES"],
});
- formatEdgeResults(sliceEdgeResults(result.nodes, calleeLimit), "callees", target.name, opts.format, target, "graph");
+ const health = await healthDiagnostics(healthCheck);
+ bannerOverRows(health, opts.format, result.nodes.length);
+ formatEdgeResults(sliceEdgeResults(result.nodes, calleeLimit), "callees", target.name, opts.format, target, "graph", health.diagnostics);
});
}
diff --git a/ix-cli/src/cli/commands/impact.ts b/ix-cli/src/cli/commands/impact.ts
index a4a23285..cbefe786 100644
--- a/ix-cli/src/cli/commands/impact.ts
+++ b/ix-cli/src/cli/commands/impact.ts
@@ -2,10 +2,11 @@
import type { Command } from "commander";
import chalk from "chalk";
-import { renderSection, renderKeyValue, renderNote, renderResolvedHeader, colorizeKind } from "../ui.js";
+import { renderSection, renderKeyValue, renderNote, renderResolvedHeader, renderWarning, colorizeKind } from "../ui.js";
import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
-import { resolveFileOrReport, printResolved } from "../resolve.js";
+import { activeReadScope, resolveFileOrReport, printResolved } from "../resolve.js";
+import { checkGraphHealth, graphHealthJson, graphHealthLlmFields, graphHealthProse, isUnhealthy } from "../graph-health.js";
import { bucketByHierarchy, getSystemPath, formatSystemPath, hasMapData, type SystemPath } from "../hierarchy.js";
import { inferRiskSemantics, humanizeLabel, type ImpactFacts, type RiskSemantics } from "../impact/risk-semantics.js";
import { lineSpan, printJson, rowLocation, stripNulls } from "../format.js";
@@ -43,15 +44,38 @@ export function registerImpactCommand(program: Command): void {
if (opts.format === "text") printResolved(target);
+ // A hollowed graph reports "low risk, no dependents" for anything:
+ // the answer is only as good as the edges it counts. Said first, in
+ // every format, before the counts it undermines.
+ const health = await checkGraphHealth(client, activeReadScope());
+ const graph = isUnhealthy(health) ? graphHealthJson(health) : undefined;
+ if (graph && opts.format === "llm") console.log(llmLine("graph", graphHealthLlmFields(health)));
+ if (graph && opts.format === "text") renderWarning(graphHealthProse(health));
+
if (CONTAINER_KINDS.has(target.kind)) {
- await containerImpact(client, target, limit, depth, opts.format);
+ await containerImpact(client, target, limit, depth, opts.format, graph);
} else {
- await leafImpact(client, target, depth, opts.format);
+ await leafImpact(client, target, depth, opts.format, graph);
}
}
);
}
+/**
+ * The risk a hollowed graph would report is drawn from edges it has lost, so
+ * "low risk" there means "no edges left", not "safe to change". Withheld as
+ * `unknown` -- a level the type does not hold on purpose, as `ix explain`
+ * does for importance: nothing downstream may mistake it for a real `low`.
+ */
+export function withheldOnDegraded(risk: RiskSemantics, graph: Record<string, unknown> | undefined): RiskSemantics {
+ if (!graph) return risk;
+ return {
+ ...risk,
+ riskLevel: "unknown" as unknown as RiskSemantics["riskLevel"],
+ riskSummary: "Unknown: this workspace's graph is missing its call and import edges, so what a change reaches cannot be counted.",
+ };
+}
+
// ── Risk level coloring ──────────────────────────────────────────────────────
function riskColor(level: string): typeof chalk {
@@ -265,7 +289,8 @@ async function containerImpact(
target: { id: string; kind: string; name: string; resolutionMode: string },
limit: number,
depth: number,
- format: string
+ format: string,
+ graph?: Record<string, unknown>,
): Promise<void> {
const isJson = format === "json";
const diagnostics: string[] = [];
@@ -366,12 +391,13 @@ async function containerImpact(
count: b.members.length,
})),
};
- const risk = inferRiskSemantics(riskFacts);
+ const risk = withheldOnDegraded(inferRiskSemantics(riskFacts), graph);
if (isJson) {
printJson(
stripNulls({
resolvedTarget: { kind: target.kind, name: target.name },
+ graph,
depth,
systemPath: systemPathMapped.length > 0 ? systemPathMapped : undefined,
riskSummary: risk.riskSummary,
@@ -454,7 +480,8 @@ async function leafImpact(
client: IxClient,
target: { id: string; kind: string; name: string; resolutionMode: string },
depth: number,
- format: string
+ format: string,
+ graph?: Record<string, unknown>,
): Promise<void> {
const isJson = format === "json";
const [callersResult, calleesResult, systemPath, decisionsResult, tasksResult, bugsResult] = await Promise.all([
@@ -507,12 +534,13 @@ async function leafImpact(
})),
topCallerNames: callerNames.slice(0, 3),
};
- const risk = inferRiskSemantics(riskFacts);
+ const risk = withheldOnDegraded(inferRiskSemantics(riskFacts), graph);
if (isJson) {
printJson(
stripNulls({
resolvedTarget: { kind: target.kind, name: target.name },
+ graph,
depth,
systemPath: systemPathMapped.length > 0 ? systemPathMapped : undefined,
riskSummary: risk.riskSummary,