Skip to content

armgit / Ix

Public Imported from GitHub
0

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

feat: polish ix impact semantics and refactor ix locate to pure position command

Tanner Kocherfeee1ee8abd6
diff --git a/ix-cli/src/cli/__tests__/impact-schema.test.ts b/ix-cli/src/cli/__tests__/impact-schema.test.ts
index 871890c1..8f4ab10d 100644
--- a/ix-cli/src/cli/__tests__/impact-schema.test.ts
+++ b/ix-cli/src/cli/__tests__/impact-schema.test.ts
@@ -1,4 +1,5 @@
import { describe, it, expect } from "vitest";
+import { inferRiskSemantics, humanizeLabel, type ImpactFacts } from "../impact/risk-semantics.js";
/**
* These tests verify the normalized JSON schema contract for ix impact.
@@ -9,10 +10,18 @@ const REQUIRED_TOP_LEVEL_KEYS = [
"resolvedTarget",
"resolutionMode",
"resultSource",
+ "systemPath",
+ "riskSummary",
+ "riskLevel",
+ "riskCategory",
+ "atRiskBehavior",
+ "nextStep",
+ "flowPropagation",
"summary",
"callerList",
"calleeList",
"topImpactedMembers",
+ "propagationBuckets",
"decisions",
"tasks",
"bugs",
@@ -35,6 +44,13 @@ describe("impact JSON schema normalization", () => {
resolvedTarget: { id: "abc", kind: "class", name: "MyClass" },
resolutionMode: "exact",
resultSource: "graph",
+ systemPath: [{ name: "CLI", kind: "subsystem" }, { name: "Commands", kind: "module" }],
+ riskSummary: "Medium risk — widely shared dependency affecting the CLI layer.",
+ riskLevel: "medium",
+ riskCategory: "shared",
+ atRiskBehavior: ["Multiple callers across different subsystems"],
+ nextStep: null,
+ flowPropagation: null,
summary: {
members: 5,
callers: 0,
@@ -46,6 +62,7 @@ describe("impact JSON schema normalization", () => {
callerList: [],
calleeList: [],
topImpactedMembers: [{ name: "foo", kind: "method", id: "m1", callerCount: 3 }],
+ propagationBuckets: [{ region: "Commands", regionKind: "module", count: 2, members: [{ name: "fn1", kind: "function" }] }],
decisions: [],
tasks: [],
bugs: [],
@@ -65,6 +82,11 @@ describe("impact JSON schema normalization", () => {
expect(Array.isArray(containerOutput.decisions)).toBe(true);
expect(Array.isArray(containerOutput.tasks)).toBe(true);
expect(Array.isArray(containerOutput.bugs)).toBe(true);
+ // Risk fields
+ expect(typeof containerOutput.riskSummary).toBe("string");
+ expect(typeof containerOutput.riskLevel).toBe("string");
+ expect(typeof containerOutput.riskCategory).toBe("string");
+ expect(Array.isArray(containerOutput.atRiskBehavior)).toBe(true);
});
it("leaf impact shape has all required keys", () => {
@@ -73,6 +95,13 @@ describe("impact JSON schema normalization", () => {
resolvedTarget: { id: "xyz", kind: "function", name: "verify_token" },
resolutionMode: "exact",
resultSource: "graph",
+ systemPath: [{ name: "file.ts", kind: "file" }],
+ riskSummary: "Low risk — localized impact with limited propagation.",
+ riskLevel: "low",
+ riskCategory: "localized",
+ atRiskBehavior: ["Limited to immediate callers"],
+ nextStep: null,
+ flowPropagation: null,
summary: {
members: 0,
callers: 3,
@@ -84,6 +113,7 @@ describe("impact JSON schema normalization", () => {
callerList: [{ id: "c1", kind: "method", name: "login" }],
calleeList: [{ id: "c2", kind: "function", name: "decode_jwt" }],
topImpactedMembers: [],
+ propagationBuckets: [],
decisions: [],
tasks: [],
bugs: [],
@@ -118,3 +148,365 @@ describe("impact JSON schema normalization", () => {
expect(containerSummaryKeys).toEqual(leafSummaryKeys);
});
});
+
+// ── Risk semantics inference ────────────────────────────────────────────────
+
+function makeFacts(overrides: Partial<ImpactFacts> = {}): ImpactFacts {
+ return {
+ name: "SomeEntity",
+ kind: "function",
+ members: 0,
+ callers: 2,
+ callees: 1,
+ directImporters: 0,
+ directDependents: 0,
+ memberLevelCallers: 0,
+ propagationBuckets: [],
+ ...overrides,
+ };
+}
+
+describe("inferRiskSemantics: boundary class", () => {
+ it("IxClient-like class: risk summary mentions backend-facing CLI operations / client boundary", () => {
+ const facts = makeFacts({
+ name: "IxClient",
+ kind: "class",
+ members: 15,
+ callers: 0,
+ directImporters: 8,
+ directDependents: 20,
+ memberLevelCallers: 66,
+ systemPath: [
+ { name: "Cli", kind: "system" },
+ { name: "Cli / Client", kind: "subsystem" },
+ { name: "api.ts", kind: "file" },
+ ],
+ propagationBuckets: [
+ { region: "Cli / Client", regionKind: "subsystem", count: 34 },
+ { region: "Commands", regionKind: "module", count: 18 },
+ { region: "Explain", regionKind: "module", count: 6 },
+ ],
+ });
+ const risk = inferRiskSemantics(facts);
+ expect(risk.category).toBe("boundary");
+ expect(risk.riskLevel).toBe("critical");
+ expect(risk.riskSummary.toLowerCase()).toContain("backend-facing");
+ expect(risk.riskSummary.toLowerCase()).toContain("boundary");
+ });
+
+ it("IxClient-like class: at-risk behavior is operational, not just counts", () => {
+ const facts = makeFacts({
+ name: "IxClient",
+ kind: "class",
+ members: 15,
+ directImporters: 8,
+ directDependents: 20,
+ memberLevelCallers: 66,
+ propagationBuckets: [
+ { region: "Cli / Client", regionKind: "subsystem", count: 34 },
+ ],
+ });
+ const risk = inferRiskSemantics(facts);
+ expect(risk.behaviorAtRisk.length).toBeGreaterThan(0);
+ const joined = risk.behaviorAtRisk.join(" ").toLowerCase();
+ expect(joined).toContain("command");
+ expect(joined).not.toMatch(/^\d+$/); // Not just numbers
+ });
+});
+
+describe("inferRiskSemantics: flow function", () => {
+ it("pickBest-like function: risk summary mentions candidate selection / resolution flow", () => {
+ const facts = makeFacts({
+ name: "pickBest",
+ kind: "function",
+ path: "ix-cli/src/cli/resolve.ts",
+ callers: 1,
+ callees: 4,
+ propagationBuckets: [
+ { region: "Resolution", regionKind: "subsystem", count: 14 },
+ ],
+ });
+ const risk = inferRiskSemantics(facts);
+ expect(risk.category).toBe("flow");
+ expect(risk.riskSummary.toLowerCase()).toContain("candidate selection");
+ expect(risk.riskSummary.toLowerCase()).toContain("resolution flow");
+ // Should not lead with "callers: 1, callees: 4"
+ expect(risk.riskSummary).not.toMatch(/callers?:\s*\d/);
+ });
+
+ it("pickBest-like function: at-risk behavior mentions selection/resolution", () => {
+ const facts = makeFacts({
+ name: "pickBest",
+ kind: "function",
+ path: "ix-cli/src/cli/resolve.ts",
+ callers: 1,
+ callees: 4,
+ });
+ const risk = inferRiskSemantics(facts);
+ const joined = risk.behaviorAtRisk.join(" ").toLowerCase();
+ expect(joined).toContain("selection");
+ });
+});
+
+describe("inferRiskSemantics: conflict-resolution method", () => {
+ it("resolve-like method: risk summary mentions conflict-resolution behavior", () => {
+ const facts = makeFacts({
+ name: "resolveConflict",
+ kind: "method",
+ path: "src/conflict.ts",
+ container: { kind: "class", name: "ConflictService" },
+ callers: 3,
+ callees: 2,
+ systemPath: [
+ { name: "CLI", kind: "system" },
+ { name: "Conflict", kind: "subsystem" },
+ { name: "conflict.ts", kind: "file" },
+ ],
+ propagationBuckets: [
+ { region: "Conflict", regionKind: "subsystem", count: 5 },
+ ],
+ });
+ const risk = inferRiskSemantics(facts);
+ expect(risk.category).toBe("flow");
+ expect(risk.riskSummary.toLowerCase()).toContain("conflict");
+ });
+
+ it("resolve-like method: propagation mentions conflict flow", () => {
+ const facts = makeFacts({
+ name: "resolveConflict",
+ kind: "method",
+ path: "src/conflict.ts",
+ container: { kind: "class", name: "ConflictService" },
+ callers: 3,
+ callees: 2,
+ systemPath: [
+ { name: "CLI", kind: "system" },
+ { name: "Conflict", kind: "subsystem" },
+ ],
+ });
+ const risk = inferRiskSemantics(facts);
+ const joined = risk.behaviorAtRisk.join(" ").toLowerCase();
+ expect(joined).toContain("conflict");
+ });
+});
+
+describe("inferRiskSemantics: foundational shared type", () => {
+ it("NodeKind-like enum: risk summary mentions shared node interpretation / model-parser consistency", () => {
+ const facts = makeFacts({
+ name: "NodeKind",
+ kind: "enum",
+ members: 24,
+ callers: 0,
+ directImporters: 8,
+ directDependents: 12,
+ memberLevelCallers: 0,
+ systemPath: [
+ { name: "IX Memory", kind: "system" },
+ { name: "Model", kind: "subsystem" },
+ { name: "graph.ts", kind: "file" },
+ ],
+ propagationBuckets: [
+ { region: "Ingestion / Parsers", regionKind: "subsystem", count: 8 },
+ { region: "Model / Db", regionKind: "subsystem", count: 3 },
+ { region: "Context", regionKind: "module", count: 2 },
+ ],
+ });
+ const risk = inferRiskSemantics(facts);
+ expect(risk.category).toBe("foundation");
+ expect(risk.riskLevel).toBe("critical");
+ expect(risk.riskSummary.toLowerCase()).toContain("node");
+ expect(risk.riskSummary.toLowerCase()).toContain("risk");
+ });
+
+ it("NodeKind-like enum: at-risk behavior mentions classification and interpretation", () => {
+ const facts = makeFacts({
+ name: "NodeKind",
+ kind: "enum",
+ members: 24,
+ directImporters: 8,
+ directDependents: 12,
+ propagationBuckets: [
+ { region: "Ingestion / Parsers", regionKind: "subsystem", count: 8 },
+ ],
+ });
+ const risk = inferRiskSemantics(facts);
+ expect(risk.behaviorAtRisk.length).toBeGreaterThan(0);
+ const joined = risk.behaviorAtRisk.join(" ").toLowerCase();
+ expect(joined).toContain("classification");
+ expect(joined).toContain("interpretation");
+ });
+
+ it("NodeKind-like enum: propagation uses hierarchy buckets", () => {
+ const facts = makeFacts({
+ name: "NodeKind",
+ kind: "enum",
+ directImporters: 8,
+ propagationBuckets: [
+ { region: "Ingestion / Parsers", regionKind: "subsystem", count: 8 },
+ { region: "Model / Db", regionKind: "subsystem", count: 3 },
+ ],
+ });
+ const risk = inferRiskSemantics(facts);
+ // Risk summary should reference layers, not raw IDs
+ expect(risk.riskSummary.toLowerCase()).not.toContain("id:");
+ expect(risk.riskSummary).toContain("layer");
+ });
+});
+
+describe("inferRiskSemantics: localized entity", () => {
+ it("low-connectivity function gets low risk", () => {
+ const facts = makeFacts({
+ name: "trimWhitespace",
+ kind: "function",
+ callers: 1,
+ callees: 0,
+ });
+ const risk = inferRiskSemantics(facts);
+ expect(risk.riskLevel).toBe("low");
+ expect(risk.category).toBe("localized");
+ });
+});
+
+describe("inferRiskSemantics: shared dependency", () => {
+ it("widely-called function gets shared category", () => {
+ const facts = makeFacts({
+ name: "formatOutput",
+ kind: "function",
+ callers: 8,
+ callees: 2,
+ propagationBuckets: [
+ { region: "Commands", regionKind: "module", count: 5 },
+ { region: "Explain", regionKind: "module", count: 3 },
+ ],
+ });
+ const risk = inferRiskSemantics(facts);
+ expect(risk.category).toBe("shared");
+ expect(risk.riskLevel).not.toBe("low");
+ });
+});
+
+// ── humanizeLabel ───────────────────────────────────────────────────────────
+
+describe("humanizeLabel", () => {
+ it("Cli / Client → CLI client layer", () => {
+ expect(humanizeLabel("Cli / Client")).toBe("CLI client layer");
+ });
+
+ it("Api → API layer", () => {
+ expect(humanizeLabel("Api")).toBe("API layer");
+ });
+
+ it("Model / Db → model and database layer", () => {
+ expect(humanizeLabel("Model / Db")).toBe("model and database layer");
+ });
+
+ it("Ingestion / Parsers → ingestion and parser layer", () => {
+ expect(humanizeLabel("Ingestion / Parsers")).toBe("ingestion and parser layer");
+ });
+
+ it("Context → context layer", () => {
+ expect(humanizeLabel("Context")).toBe("context layer");
+ });
+});
+
+// ── Flow-specific risk summary ──────────────────────────────────────────────
+
+describe("inferRiskSemantics: flow-specific risk summary", () => {
+ it("pickBest summary contains 'candidate selection' and 'resolution flow'", () => {
+ const facts = makeFacts({
+ name: "pickBest",
+ kind: "function",
+ path: "ix-cli/src/cli/resolve.ts",
+ callers: 1,
+ callees: 4,
+ propagationBuckets: [
+ { region: "Resolution", regionKind: "subsystem", count: 14 },
+ ],
+ });
+ const risk = inferRiskSemantics(facts);
+ expect(risk.riskSummary.toLowerCase()).toContain("candidate selection");
+ expect(risk.riskSummary.toLowerCase()).toContain("resolution flow");
+ });
+});
+
+// ── Flow-aware most-affected ────────────────────────────────────────────────
+
+describe("inferRiskSemantics: flow-aware most-affected", () => {
+ it("pickBest with topCallerNames mentions the caller and selection", () => {
+ const facts = makeFacts({
+ name: "pickBest",
+ kind: "function",
+ path: "ix-cli/src/cli/resolve.ts",
+ callers: 1,
+ callees: 4,
+ topCallerNames: ["resolveEntityFull"],
+ propagationBuckets: [
+ { region: "Resolution", regionKind: "subsystem", count: 14 },
+ ],
+ });
+ const risk = inferRiskSemantics(facts);
+ expect(risk.mostAffectedHint).toContain("resolveEntityFull");
+ expect(risk.mostAffectedHint!.toLowerCase()).toContain("selection");
+ });
+});
+
+// ── Foundation importer spread ──────────────────────────────────────────────
+
+describe("inferRiskSemantics: foundation importer spread", () => {
+ it("NodeKind-like with directImporters=8: summary or behavior mentions 'contract' or 'imported'", () => {
+ const facts = makeFacts({
+ name: "NodeKind",
+ kind: "enum",
+ members: 24,
+ directImporters: 8,
+ directDependents: 12,
+ propagationBuckets: [
+ { region: "Ingestion / Parsers", regionKind: "subsystem", count: 8 },
+ { region: "Model / Db", regionKind: "subsystem", count: 3 },
+ ],
+ });
+ const risk = inferRiskSemantics(facts);
+ const allText = [risk.riskSummary, ...risk.behaviorAtRisk].join(" ").toLowerCase();
+ expect(allText).toContain("contract");
+ expect(allText).toContain("imported");
+ });
+});
+
+// ── Next-step guidance ──────────────────────────────────────────────────────
+
+describe("inferRiskSemantics: next-step guidance", () => {
+ it("foundation with high importers → nextStep contains 'ix explain'", () => {
+ const facts = makeFacts({
+ name: "NodeKind",
+ kind: "enum",
+ members: 24,
+ directImporters: 8,
+ directDependents: 12,
+ });
+ const risk = inferRiskSemantics(facts);
+ expect(risk.nextStep).toContain("ix explain");
+ });
+
+ it("flow with callers → nextStep contains 'ix depends'", () => {
+ const facts = makeFacts({
+ name: "pickBest",
+ kind: "function",
+ path: "ix-cli/src/cli/resolve.ts",
+ callers: 1,
+ callees: 4,
+ });
+ const risk = inferRiskSemantics(facts);
+ expect(risk.nextStep).toContain("ix depends");
+ });
+
+ it("localized → nextStep is undefined", () => {
+ const facts = makeFacts({
+ name: "trimWhitespace",
+ kind: "function",
+ callers: 1,
+ callees: 0,
+ });
+ const risk = inferRiskSemantics(facts);
+ expect(risk.nextStep).toBeUndefined();
+ });
+});
diff --git a/ix-cli/src/cli/__tests__/locate-output.test.ts b/ix-cli/src/cli/__tests__/locate-output.test.ts
new file mode 100644
index 00000000..8deafec7
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/locate-output.test.ts
@@ -0,0 +1,148 @@
+import { describe, it, expect } from "vitest";
+
+/**
+ * Tests for ix locate output structure.
+ *
+ * These verify that the JSON output contract is purely positional:
+ * file, line range, containment, system path — no structural/risk/explanatory content.
+ */
+
+// Simulates the JSON output shape from locate for a symbol target
+function makeSymbolOutput() {
+ return {
+ resolvedTarget: {
+ id: "abc-123",
+ kind: "class",
+ name: "IxClient",
+ path: "src/client/api.ts",
+ },
+ resolutionMode: "exact",
+ lineRange: { start: 12, end: 206 },
+ container: { kind: "file", name: "api.ts", id: "file-1" },
+ systemPath: [
+ { name: "CLI", kind: "system" },
+ { name: "Client Layer", kind: "subsystem" },
+ { name: "api.ts", kind: "file" },
+ { name: "IxClient", kind: "class" },
+ ],
+ diagnostics: [],
+ };
+}
+
+// Simulates the JSON output shape from locate for a file target
+function makeFileOutput() {
+ return {
+ resolvedTarget: {
+ id: "file-abc",
+ kind: "file",
+ name: "Node.scala",
+ path: "memory-layer/src/main/scala/ix/memory/model/Node.scala",
+ },
+ resolutionMode: "exact",
+ systemPath: [
+ { name: "API", kind: "system" },
+ { name: "Model / Db", kind: "subsystem" },
+ { name: "Node.scala", kind: "file" },
+ ],
+ diagnostics: [],
+ };
+}
+
+describe("locate: symbol target output", () => {
+ it("contains file path", () => {
+ const output = makeSymbolOutput();
+ expect(output.resolvedTarget.path).toBe("src/client/api.ts");
+ });
+
+ it("contains line range", () => {
+ const output = makeSymbolOutput();
+ expect(output.lineRange).toEqual({ start: 12, end: 206 });
+ });
+
+ it("contains system path with multiple nodes", () => {
+ const output = makeSymbolOutput();
+ expect(output.systemPath.length).toBeGreaterThan(1);
+ expect(output.systemPath[0]).toEqual({ name: "CLI", kind: "system" });
+ });
+
+ it("contains container", () => {
+ const output = makeSymbolOutput();
+ expect(output.container).toBeDefined();
+ expect(output.container!.name).toBe("api.ts");
+ });
+});
+
+describe("locate: file target output", () => {
+ it("contains file path", () => {
+ const output = makeFileOutput();
+ expect(output.resolvedTarget.path).toContain("Node.scala");
+ });
+
+ it("contains system path", () => {
+ const output = makeFileOutput();
+ expect(output.systemPath.length).toBeGreaterThan(1);
+ });
+
+ it("has no container for file targets", () => {
+ const output = makeFileOutput();
+ expect((output as any).container).toBeUndefined();
+ });
+
+ it("has no lineRange for file targets", () => {
+ const output = makeFileOutput();
+ expect((output as any).lineRange).toBeUndefined();
+ });
+});
+
+describe("locate: no-overlap regression", () => {
+ const symbolOutput = makeSymbolOutput();
+ const fileOutput = makeFileOutput();
+ const allKeys = [
+ ...Object.keys(symbolOutput),
+ ...Object.keys(fileOutput),
+ ];
+
+ it("does not include callers", () => {
+ expect(allKeys).not.toContain("callers");
+ expect(allKeys).not.toContain("callerList");
+ });
+
+ it("does not include dependents", () => {
+ expect(allKeys).not.toContain("dependents");
+ expect(allKeys).not.toContain("directDependents");
+ expect(allKeys).not.toContain("directImporters");
+ });
+
+ it("does not include members", () => {
+ expect(allKeys).not.toContain("members");
+ expect(allKeys).not.toContain("topImpactedMembers");
+ });
+
+ it("does not include risk or explanation fields", () => {
+ expect(allKeys).not.toContain("riskSummary");
+ expect(allKeys).not.toContain("riskLevel");
+ expect(allKeys).not.toContain("riskCategory");
+ expect(allKeys).not.toContain("atRiskBehavior");
+ expect(allKeys).not.toContain("behaviorAtRisk");
+ expect(allKeys).not.toContain("mostAffectedHint");
+ expect(allKeys).not.toContain("nextStep");
+ });
+});
+
+describe("locate: ambiguity handling", () => {
+ it("null resolution produces diagnostics", () => {
+ const output = {
+ resolvedTarget: null,
+ resolutionMode: "none",
+ systemPath: null,
+ diagnostics: ["No graph entity found."],
+ };
+ expect(output.resolvedTarget).toBeNull();
+ expect(output.diagnostics.length).toBeGreaterThan(0);
+ });
+
+ it("resolution mode is preserved", () => {
+ const output = makeSymbolOutput();
+ expect(output.resolutionMode).toBe("exact");
+ });
+});
diff --git a/ix-cli/src/cli/commands/impact.ts b/ix-cli/src/cli/commands/impact.ts
index bfd31e3d..52193724 100644
--- a/ix-cli/src/cli/commands/impact.ts
+++ b/ix-cli/src/cli/commands/impact.ts
@@ -3,13 +3,15 @@ import chalk from "chalk";
import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
import { resolveFileOrEntity, printResolved } from "../resolve.js";
+import { bucketByHierarchy, getSystemPath, formatSystemPath, hasMapData, type SystemPath } from "../hierarchy.js";
+import { inferRiskSemantics, humanizeLabel, type ImpactFacts, type RiskSemantics } from "../impact/risk-semantics.js";
const CONTAINER_KINDS = new Set(["class", "module", "file", "object", "trait", "interface"]);
export function registerImpactCommand(program: Command): void {
program
.command("impact <target>")
- .description("Aggregated impact analysis — who depends on this symbol and its members")
+ .description("System risk analysis — what behavior is at risk if this changes")
.option("--kind <kind>", "Filter target entity by kind")
.option("--pick <n>", "Pick Nth candidate from ambiguous results (1-based)")
.option("--depth <n>", "Expansion depth for callers/importers (default 1, max 3)", "1")
@@ -44,6 +46,151 @@ export function registerImpactCommand(program: Command): void {
);
}
+// ── Risk level coloring ──────────────────────────────────────────────────────
+
+function riskColor(level: string): typeof chalk {
+ if (level === "critical") return chalk.red.bold;
+ if (level === "high") return chalk.red;
+ if (level === "medium") return chalk.yellow;
+ return chalk.dim;
+}
+
+// ── Shared text rendering ────────────────────────────────────────────────────
+
+function renderRiskHeader(
+ target: { kind: string; name: string },
+ risk: RiskSemantics,
+ systemPath: SystemPath,
+): void {
+ console.log(chalk.bold(`Target: ${target.kind} ${target.name}\n`));
+
+ if (systemPath.length > 1 && hasMapData(systemPath)) {
+ console.log(` System path: ${chalk.dim(formatSystemPath(systemPath))}`);
+ }
+
+ // Risk summary — the lead section
+ const color = riskColor(risk.riskLevel);
+ console.log(chalk.bold("\nRisk summary"));
+ console.log(` ${color(risk.riskSummary)}`);
+
+ // At-risk behavior
+ if (risk.behaviorAtRisk.length > 0) {
+ console.log(chalk.bold("\nAt-risk behavior"));
+ for (const b of risk.behaviorAtRisk) {
+ console.log(` ${chalk.white("•")} ${b}`);
+ }
+ }
+}
+
+function renderPropagationBuckets(
+ propagationBuckets: Array<{ region: { name: string; kind: string }; members: Array<{ name: string; kind: string }> }>,
+ flowPropagation?: { flowName: string; count: number },
+): void {
+ if (propagationBuckets.length === 0 && !flowPropagation) return;
+ console.log(chalk.bold("\nPropagation"));
+
+ // Flow propagation line first
+ if (flowPropagation) {
+ const flowLabel = capitalize(flowPropagation.flowName) + " flow";
+ console.log(` ${chalk.cyan(flowLabel.padEnd(30))} ${flowPropagation.count} downstream dependents`);
+ }
+
+ const sorted = [...propagationBuckets].sort((a, b) => b.members.length - a.members.length);
+ for (const bucket of sorted) {
+ const regionLabel = humanizeLabel(bucket.region.name);
+ console.log(` ${chalk.cyan(regionLabel.padEnd(30))} ${bucket.members.length} dependents`);
+ }
+}
+
+function renderMostAffected(
+ risk: RiskSemantics,
+ topMembers: Array<{ name: string; kind: string; callerCount: number }>,
+ callerNames?: string[],
+ calleeNames?: string[],
+): void {
+ const items: string[] = [];
+
+ if (topMembers.length > 0) {
+ const names = topMembers.slice(0, 3).map((m) => m.name);
+ const suffix = topMembers.length > 3 ? ` and ${topMembers.length - 3} more` : "";
+ items.push(`${names.join(", ")}${suffix} in the ${risk.category === "boundary" ? "client boundary" : "container"}`);
+ }
+
+ if (risk.mostAffectedHint) {
+ // For flow hints with ";", split into separate items
+ const hintParts = risk.mostAffectedHint.split("; ");
+ for (const part of hintParts) {
+ if (items.length < 3) items.push(part);
+ }
+ }
+
+ if (callerNames && callerNames.length > 0 && items.length < 3) {
+ const shown = callerNames.slice(0, 2).join(", ");
+ const more = callerNames.length > 2 ? ` and ${callerNames.length - 2} more` : "";
+ items.push(`Callers: ${shown}${more}`);
+ }
+
+ if (items.length > 0) {
+ console.log(chalk.bold("\nMost affected"));
+ for (const item of items.slice(0, 3)) {
+ console.log(` ${chalk.white("•")} ${item}`);
+ }
+ }
+}
+
+function renderNextStep(risk: RiskSemantics): void {
+ if (risk.nextStep) {
+ console.log(chalk.bold("\nNext"));
+ console.log(` ${chalk.dim(risk.nextStep)}`);
+ }
+}
+
+function renderSupportingContext(
+ counts: Record<string, number>,
+): void {
+ const entries = Object.entries(counts).filter(([, v]) => v > 0);
+ if (entries.length === 0) return;
+ console.log(chalk.bold("\nSupporting context"));
+ for (const [label, value] of entries) {
+ console.log(` ${chalk.dim(label.padEnd(24))} ${value}`);
+ }
+}
+
+function renderDecisionsTasksBugs(
+ decisions: Array<{ name: string }>,
+ tasks: Array<{ name: string; status: string }>,
+ bugs: Array<{ name: string; status: string; severity: string }>,
+): void {
+ if (decisions.length > 0) {
+ console.log(chalk.bold("\nDecisions:"));
+ for (const d of decisions) {
+ console.log(` ${chalk.yellow(d.name)}`);
+ }
+ }
+
+ if (tasks.length > 0) {
+ console.log(chalk.bold("\nTasks:"));
+ for (const t of tasks) {
+ const icon = t.status === "done" ? "✓" : "○";
+ console.log(` ${icon} [${t.status}] ${t.name}`);
+ }
+ }
+
+ if (bugs.length > 0) {
+ console.log(chalk.bold("\nBugs:"));
+ for (const b of bugs) {
+ const icon = b.status === "closed" || b.status === "resolved" ? "✓" : "○";
+ console.log(` ${icon} [${b.status}] ${chalk.red(b.severity)} ${b.name}`);
+ }
+ }
+}
+
+function capitalize(s: string): string {
+ return s.charAt(0).toUpperCase() + s.slice(1);
+}
+
+// ── Container impact ─────────────────────────────────────────────────────────
+
async function containerImpact(
client: IxClient,
target: { id: string; kind: string; name: string; resolutionMode: string },
@@ -53,15 +200,16 @@ async function containerImpact(
): Promise<void> {
const diagnostics: string[] = [];
- // 1. Get contained members, importers, dependents, and developer-cycle context in parallel
- const [containsResult, importersResult, dependentsResult, decisionsResult, tasksResult, bugsResult] = await Promise.all([
+ const [containsResult, importersResult, dependentsResult, systemPath, decisionsResult, tasksResult, bugsResult] = await Promise.all([
client.expand(target.id, { direction: "out", predicates: ["CONTAINS"] }),
client.expand(target.id, { direction: "in", predicates: ["IMPORTS"], hops: depth }),
client.expand(target.id, { direction: "in", predicates: ["CALLS", "REFERENCES"], hops: depth }),
+ getSystemPath(client, target.id),
client.expand(target.id, { direction: "in", predicates: ["DECISION_AFFECTS"] }),
client.expand(target.id, { direction: "in", predicates: ["TASK_AFFECTS"] }),
client.expand(target.id, { direction: "in", predicates: ["BUG_AFFECTS"] }),
]);
+
const members = containsResult.nodes;
const directImporters = importersResult.nodes;
const directDependents = dependentsResult.nodes;
@@ -76,7 +224,7 @@ async function containerImpact(
id: n.id, name: n.name || n.attrs?.name || "(unnamed)", status: String(n.attrs?.status ?? "open"), severity: String(n.attrs?.severity ?? "medium"),
}));
- // 4. For each member (up to 20), get inbound callers
+ // For each member (up to 20), get inbound callers
const membersToCheck = members.slice(0, 20);
const memberCallerCounts: { name: string; kind: string; id: string; callerCount: number }[] = [];
let totalMemberCallers = 0;
@@ -110,10 +258,41 @@ async function containerImpact(
totalMemberCallers += r.callerCount;
}
- // 5. Rank by caller count, top N
memberCallerCounts.sort((a, b) => b.callerCount - a.callerCount);
const topMembers = memberCallerCounts.filter((m) => m.callerCount > 0).slice(0, limit);
+ // Bucket all dependents by hierarchy
+ const allDependentIds = [
+ ...directImporters.map((n: any) => n.id),
+ ...directDependents.map((n: any) => n.id),
+ ];
+ const uniqueDependentIds = [...new Set(allDependentIds)];
+ const propagationBuckets = uniqueDependentIds.length > 0
+ ? await bucketByHierarchy(client, uniqueDependentIds)
+ : [];
+
+ const systemPathMapped = systemPath.map((n) => ({ name: n.name, kind: n.kind }));
+
+ // Infer risk semantics
+ const riskFacts: ImpactFacts = {
+ name: target.name,
+ kind: target.kind,
+ container: undefined,
+ systemPath: systemPathMapped,
+ members: members.length,
+ callers: 0,
+ callees: 0,
+ directImporters: directImporters.length,
+ directDependents: directDependents.length,
+ memberLevelCallers: totalMemberCallers,
+ propagationBuckets: propagationBuckets.map((b) => ({
+ region: b.region.name,
+ regionKind: b.region.kind,
+ count: b.members.length,
+ })),
+ };
+ const risk = inferRiskSemantics(riskFacts);
+
if (isJson) {
console.log(
JSON.stringify(
@@ -122,6 +301,13 @@ async function containerImpact(
resolutionMode: target.resolutionMode,
resultSource: "graph",
depth,
+ systemPath: systemPathMapped,
+ riskSummary: risk.riskSummary,
+ riskLevel: risk.riskLevel,
+ riskCategory: risk.category,
+ atRiskBehavior: risk.behaviorAtRisk,
+ nextStep: risk.nextStep ?? null,
+ flowPropagation: risk.flowPropagation ?? null,
summary: {
members: members.length,
callers: 0,
@@ -133,6 +319,12 @@ async function containerImpact(
callerList: [],
calleeList: [],
topImpactedMembers: topMembers,
+ propagationBuckets: propagationBuckets.map((b) => ({
+ region: b.region.name,
+ regionKind: b.region.kind,
+ count: b.members.length,
+ members: b.members.slice(0, 5).map((m) => ({ name: m.name, kind: m.kind })),
+ })),
decisions,
tasks,
bugs,
@@ -143,47 +335,28 @@ async function containerImpact(
)
);
} else {
- const depthNote = depth > 1 ? chalk.dim(` (depth ${depth})`) : "";
- console.log(chalk.bold(`Target: ${target.kind} ${target.name}\n`));
- console.log(chalk.bold("Impact summary:") + depthNote);
- console.log(` members: ${members.length}`);
- console.log(` importers: ${directImporters.length}`);
- console.log(` dependents: ${directDependents.length}`);
- console.log(` member-level callers: ${totalMemberCallers}`);
-
- if (topMembers.length > 0) {
- console.log(chalk.bold("\nTop impacted members:"));
- for (const m of topMembers) {
- const kindStr = chalk.cyan(m.kind.padEnd(10));
- const nameStr = chalk.white(m.name.padEnd(20));
- console.log(` ${kindStr} ${nameStr} ${m.callerCount} callers`);
- }
- } else {
- console.log(chalk.dim("\nNo member-level callers found."));
- }
+ // 1. Risk summary + At-risk behavior
+ renderRiskHeader(target, risk, systemPath);
- if (decisions.length > 0) {
- console.log(chalk.bold("\nDecisions:"));
- for (const d of decisions) {
- console.log(` ${chalk.yellow(d.name)}`);
- }
- }
+ // 2. Propagation
+ renderPropagationBuckets(propagationBuckets, risk.flowPropagation);
- if (tasks.length > 0) {
- console.log(chalk.bold("\nTasks:"));
- for (const t of tasks) {
- const icon = t.status === "done" ? "✓" : "○";
- console.log(` ${icon} [${t.status}] ${t.name}`);
- }
- }
+ // 3. Most affected
+ renderMostAffected(risk, topMembers);
- if (bugs.length > 0) {
- console.log(chalk.bold("\nBugs:"));
- for (const b of bugs) {
- const icon = b.status === "closed" || b.status === "resolved" ? "✓" : "○";
- console.log(` ${icon} [${b.status}] ${chalk.red(b.severity)} ${b.name}`);
- }
- }
+ // 4. Supporting context
+ renderSupportingContext({
+ "Members:": members.length,
+ "Importers:": directImporters.length,
+ "Direct dependents:": directDependents.length,
+ "Member-level callers:": totalMemberCallers,
+ });
+
+ // 5. Next step
+ renderNextStep(risk);
+
+ // 6. Decisions / Tasks / Bugs
+ renderDecisionsTasksBugs(decisions, tasks, bugs);
if (diagnostics.length > 0) {
console.log(chalk.dim(`\nDiagnostics: ${diagnostics.join("; ")}`));
@@ -191,16 +364,18 @@ async function containerImpact(
}
}
+// ── Leaf impact ──────────────────────────────────────────────────────────────
+
async function leafImpact(
client: IxClient,
target: { id: string; kind: string; name: string; resolutionMode: string },
depth: number,
isJson: boolean
): Promise<void> {
- // Fetch callers, callees, and developer-cycle context in parallel
- const [callersResult, calleesResult, decisionsResult, tasksResult, bugsResult] = await Promise.all([
+ const [callersResult, calleesResult, systemPath, decisionsResult, tasksResult, bugsResult] = await Promise.all([
client.expand(target.id, { direction: "in", predicates: ["CALLS", "REFERENCES"], hops: depth }),
client.expand(target.id, { direction: "out", predicates: ["CALLS", "REFERENCES"] }),
+ getSystemPath(client, target.id),
client.expand(target.id, { direction: "in", predicates: ["DECISION_AFFECTS"] }),
client.expand(target.id, { direction: "in", predicates: ["TASK_AFFECTS"] }),
client.expand(target.id, { direction: "in", predicates: ["BUG_AFFECTS"] }),
@@ -216,6 +391,39 @@ async function leafImpact(
id: n.id, name: n.name || n.attrs?.name || "(unnamed)", status: String(n.attrs?.status ?? "open"), severity: String(n.attrs?.severity ?? "medium"),
}));
+ // Bucket callers by hierarchy
+ const callerIds = callersResult.nodes.map((n: any) => n.id);
+ const propagationBuckets = callerIds.length > 0
+ ? await bucketByHierarchy(client, callerIds)
+ : [];
+
+ const systemPathMapped = systemPath.map((n) => ({ name: n.name, kind: n.kind }));
+
+ // Extract caller/callee names for rendering
+ const callerNames = callersResult.nodes.map((n: any) => n.name || n.attrs?.name || "(unnamed)");
+ const calleeNames = calleesResult.nodes.map((n: any) => n.name || n.attrs?.name || "(unnamed)");
+
+ // Infer risk semantics
+ const riskFacts: ImpactFacts = {
+ name: target.name,
+ kind: target.kind,
+ container: undefined,
+ systemPath: systemPathMapped,
+ members: 0,
+ callers: callersResult.nodes.length,
+ callees: calleesResult.nodes.length,
+ directImporters: 0,
+ directDependents: 0,
+ memberLevelCallers: 0,
+ propagationBuckets: propagationBuckets.map((b) => ({
+ region: b.region.name,
+ regionKind: b.region.kind,
+ count: b.members.length,
+ })),
+ topCallerNames: callerNames.slice(0, 3),
+ };
+ const risk = inferRiskSemantics(riskFacts);
+
if (isJson) {
console.log(
JSON.stringify(
@@ -224,6 +432,13 @@ async function leafImpact(
resolutionMode: target.resolutionMode,
resultSource: "graph",
depth,
+ systemPath: systemPathMapped,
+ riskSummary: risk.riskSummary,
+ riskLevel: risk.riskLevel,
+ riskCategory: risk.category,
+ atRiskBehavior: risk.behaviorAtRisk,
+ nextStep: risk.nextStep ?? null,
+ flowPropagation: risk.flowPropagation ?? null,
summary: {
members: 0,
callers: callersResult.nodes.length,
@@ -243,6 +458,12 @@ async function leafImpact(
name: n.name || n.attrs?.name || "(unnamed)",
})),
topImpactedMembers: [],
+ propagationBuckets: propagationBuckets.map((b) => ({
+ region: b.region.name,
+ regionKind: b.region.kind,
+ count: b.members.length,
+ members: b.members.slice(0, 5).map((m) => ({ name: m.name, kind: m.kind })),
+ })),
decisions,
tasks,
bugs,
@@ -253,53 +474,35 @@ async function leafImpact(
)
);
} else {
- const depthNote = depth > 1 ? chalk.dim(` (depth ${depth})`) : "";
- console.log(chalk.bold(`Target: ${target.kind} ${target.name}\n`));
- console.log(chalk.bold("Impact summary:") + depthNote);
- console.log(` callers: ${callersResult.nodes.length}`);
- console.log(` callees: ${calleesResult.nodes.length}`);
-
- if (callersResult.nodes.length > 0) {
- console.log(chalk.bold("\nCallers:"));
- for (const n of callersResult.nodes) {
- const node = n as any;
- const kindStr = chalk.cyan((node.kind || "").padEnd(10));
- const name = node.name || node.attrs?.name || "(unnamed)";
- console.log(` ${kindStr} ${name}`);
- }
- }
+ // 1. Risk summary + At-risk behavior
+ renderRiskHeader(target, risk, systemPath);
+
+ // 2. Propagation
+ renderPropagationBuckets(propagationBuckets, risk.flowPropagation);
+
+ // 3. Most affected
+ renderMostAffected(risk, [], callerNames, calleeNames);
+ // 4. Supporting context
+ renderSupportingContext({
+ "Direct callers:": callersResult.nodes.length,
+ "Direct callees:": calleesResult.nodes.length,
+ });
+
+ // 5. Next step
+ renderNextStep(risk);
+
+ // 6. Callees (as supporting detail)
if (calleesResult.nodes.length > 0) {
- console.log(chalk.bold("\nCallees:"));
+ console.log(chalk.bold("\nCalls:"));
for (const n of calleesResult.nodes) {
const node = n as any;
- const kindStr = chalk.cyan((node.kind || "").padEnd(10));
const name = node.name || node.attrs?.name || "(unnamed)";
- console.log(` ${kindStr} ${name}`);
- }
- }
-
- if (decisions.length > 0) {
- console.log(chalk.bold("\nDecisions:"));
- for (const d of decisions) {
- console.log(` ${chalk.yellow(d.name)}`);
+ console.log(` ${chalk.dim((node.kind || "").padEnd(10))} ${name}`);
}
}
- if (tasks.length > 0) {
- console.log(chalk.bold("\nTasks:"));
- for (const t of tasks) {
- const icon = t.status === "done" ? "✓" : "○";
- console.log(` ${icon} [${t.status}] ${t.name}`);
- }
- }
-
- if (bugs.length > 0) {
- console.log(chalk.bold("\nBugs:"));
- for (const b of bugs) {
- const icon = b.status === "closed" || b.status === "resolved" ? "✓" : "○";
- console.log(` ${icon} [${b.status}] ${chalk.red(b.severity)} ${b.name}`);
- }
- }
+ // 7. Decisions / Tasks / Bugs
+ renderDecisionsTasksBugs(decisions, tasks, bugs);
}
}
diff --git a/ix-cli/src/cli/commands/locate.ts b/ix-cli/src/cli/commands/locate.ts
index 0af7d767..dc83e250 100644
--- a/ix-cli/src/cli/commands/locate.ts
+++ b/ix-cli/src/cli/commands/locate.ts
@@ -1,82 +1,51 @@
-import { execFile } from "node:child_process";
-import { promisify } from "node:util";
import type { Command } from "commander";
import chalk from "chalk";
import { IxClient } from "../../client/api.js";
-import { getEndpoint, resolveWorkspaceRoot } from "../config.js";
+import { getEndpoint } from "../config.js";
import { resolveFileOrEntity, printResolved } from "../resolve.js";
import { isFileStale } from "../stale.js";
import { stderr } from "../stderr.js";
-
-const execFileAsync = promisify(execFile);
+import { getSystemPath, hasMapData } from "../hierarchy.js";
const CONTAINER_KINDS = new Set(["class", "module", "file", "trait", "object", "interface"]);
-interface RelatedItem {
- name: string;
- kind: string;
- id?: string;
- relationship: "contains" | "contained-by" | "depends-on" | "imported-by" | "calls" | "called-by" | "referenced-by";
-}
-
-interface TextMatch {
- path: string;
- line: number;
-}
-
interface LocateOutput {
resolvedTarget: { id: string; kind: string; name: string; path?: string } | null;
resolutionMode: string;
- structuralContext: {
- container?: { kind: string; name: string; id?: string };
- members?: Array<{ name: string; kind: string; id?: string }>;
- signature?: string;
- };
- relationships: RelatedItem[];
- textMatches: TextMatch[];
- resultSource: "graph" | "text" | "graph+text";
+ lineRange?: { start: number; end: number };
+ container?: { kind: string; name: string; id?: string };
+ systemPath: Array<{ name: string; kind: string }> | null;
+ hasMapData?: boolean;
stale?: boolean;
- warning?: string;
diagnostics: string[];
}
export function registerLocateCommand(program: Command): void {
program
.command("locate <symbol>")
- .description("Resolve a symbol to its definition, show structural and relationship context")
- .option("--limit <n>", "Max text hits to check", "10")
+ .description("Resolve a symbol to its position in the codebase and system hierarchy")
.option("--kind <kind>", "Filter target entity by kind")
.option("--path <path>", "Prefer results 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")
- .option("--root <dir>", "Workspace root directory")
.addHelpText("after", `\nExamples:
ix locate IngestionService
ix locate verify_token --kind function
ix locate ArangoClient --format json
ix locate scoreCandidate --pick 2`)
- .action(async (symbol: string, opts: { limit: string; kind?: string; path?: string; pick?: string; format: string; root?: string }) => {
+ .action(async (symbol: string, opts: { kind?: string; path?: string; pick?: string; format: string }) => {
const client = new IxClient(getEndpoint());
- const limit = parseInt(opts.limit, 10);
- const root = resolveWorkspaceRoot(opts.root);
const diagnostics: string[] = [];
- // --- Step 1: Resolve the target entity ---
- // Prefer structural container kinds — locate wants real definitions, not incidental helpers
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) {
- // Fall back to text-only search
- const textMatches = await runRipgrep(symbol, root, limit);
const output: LocateOutput = {
resolvedTarget: null,
resolutionMode: "none",
- structuralContext: {},
- relationships: [],
- textMatches,
- resultSource: "text",
- diagnostics: ["No graph entity found; showing text matches only."],
+ systemPath: null,
+ diagnostics: ["No graph entity found."],
};
outputLocate(output, symbol, opts.format);
return;
@@ -84,32 +53,26 @@ export function registerLocateCommand(program: Command): void {
if (opts.format !== "json") printResolved(target);
- // --- Step 2: Fetch structural context and relationships in parallel ---
const isContainer = CONTAINER_KINDS.has(target.kind);
- const [
- details,
- containsResult, // members (for containers) or container (for callables)
- callersResult,
- calleesResult,
- importsResult,
- importedByResult,
- referencedByResult,
- ] = await Promise.all([
- client.entity(target.id),
+ // Parallel fetch: system path, parent container (for non-containers), entity details
+ const [systemPath, containsResult, details] = await Promise.all([
+ getSystemPath(client, target.id),
isContainer
- ? client.expand(target.id, { direction: "out", predicates: ["CONTAINS"] })
+ ? Promise.resolve({ nodes: [] })
: client.expand(target.id, { direction: "in", predicates: ["CONTAINS"] }),
- client.expand(target.id, { direction: "in", predicates: ["CALLS"] }),
- client.expand(target.id, { direction: "out", predicates: ["CALLS"] }),
- client.expand(target.id, { direction: "out", predicates: ["IMPORTS"] }),
- client.expand(target.id, { direction: "in", predicates: ["IMPORTS"] }),
- client.expand(target.id, { direction: "in", predicates: ["REFERENCES"] }),
+ client.entity(target.id),
]);
const node = details.node as any;
const nodePath = node.provenance?.source_uri ?? node.provenance?.sourceUri ?? undefined;
- const signature = node.attrs?.signature ?? undefined;
+
+ // Extract line range from attrs
+ const lineStart = node.attrs?.line_start ?? node.attrs?.lineStart;
+ const lineEnd = node.attrs?.line_end ?? node.attrs?.lineEnd;
+ const lineRange = lineStart != null && lineEnd != null
+ ? { start: Number(lineStart), end: Number(lineEnd) }
+ : undefined;
// Check staleness
let stale = false;
@@ -117,71 +80,23 @@ export function registerLocateCommand(program: Command): void {
try { stale = await isFileStale(client, nodePath); } catch {}
}
- // Build structural context
- const structuralContext: LocateOutput["structuralContext"] = {};
- if (signature) structuralContext.signature = signature;
-
- if (isContainer) {
- // Members
- const members = containsResult.nodes.slice(0, 10).map((n: any) => ({
- name: n.name || n.attrs?.name || "(unnamed)",
- kind: n.kind || "unknown",
- id: n.id,
- }));
- if (members.length > 0) structuralContext.members = members;
- } else {
- // Container (parent class/file)
- if (containsResult.nodes.length > 0) {
- const c = containsResult.nodes[0] as any;
- structuralContext.container = {
- kind: c.kind || "unknown",
- name: c.name || c.attrs?.name || "(unknown)",
- id: c.id,
- };
- }
- }
-
- // Build relationships
- const relationships: RelatedItem[] = [];
-
- for (const n of callersResult.nodes) {
- relationships.push(nodeToRelated(n, "called-by"));
- }
- for (const n of calleesResult.nodes) {
- relationships.push(nodeToRelated(n, "calls"));
- }
- for (const n of importsResult.nodes) {
- relationships.push(nodeToRelated(n, "depends-on"));
- }
- for (const n of importedByResult.nodes) {
- relationships.push(nodeToRelated(n, "imported-by"));
- }
- for (const n of referencedByResult.nodes) {
- relationships.push(nodeToRelated(n, "referenced-by"));
+ // Container context (parent for callables)
+ let container: LocateOutput["container"];
+ if (!isContainer && containsResult.nodes.length > 0) {
+ const c = containsResult.nodes[0] as any;
+ container = {
+ kind: c.kind || "unknown",
+ name: c.name || c.attrs?.name || "(unknown)",
+ id: c.id,
+ };
}
- // If container, show contained members as relationships too
- if (isContainer) {
- for (const n of containsResult.nodes.slice(0, 10)) {
- relationships.push(nodeToRelated(n, "contains"));
- }
- } else if (structuralContext.container) {
- relationships.push({
- name: structuralContext.container.name,
- kind: structuralContext.container.kind,
- id: structuralContext.container.id,
- relationship: "contained-by",
- });
+ // Diagnostic for missing map data
+ if (!hasMapData(systemPath)) {
+ diagnostics.push("No system map. Run `ix map` to see hierarchy.");
}
- // --- Step 3: Text matches (secondary) ---
- const textMatches = await runRipgrep(symbol, root, limit);
-
- // Filter out text matches from the same file as the resolved entity
- const filteredTextMatches = textMatches.filter(tm => tm.path !== nodePath);
-
- const resultSource: LocateOutput["resultSource"] =
- filteredTextMatches.length > 0 ? "graph+text" : "graph";
+ const hasMap = hasMapData(systemPath);
const output: LocateOutput = {
resolvedTarget: {
@@ -191,63 +106,20 @@ export function registerLocateCommand(program: Command): void {
path: nodePath,
},
resolutionMode: target.resolutionMode,
- structuralContext,
- relationships,
- textMatches: filteredTextMatches,
- resultSource,
+ lineRange,
+ container,
+ systemPath: systemPath.map((n) => ({ name: n.name, kind: n.kind })),
+ hasMapData: hasMap,
diagnostics,
};
if (stale) {
output.stale = true;
- output.warning = "Results may be stale; files have changed since last ingest.";
}
outputLocate(output, symbol, opts.format);
});
}
-function nodeToRelated(n: any, rel: RelatedItem["relationship"]): RelatedItem {
- return {
- name: n.name || n.attrs?.name || "(unnamed)",
- kind: n.kind || "unknown",
- id: n.id,
- relationship: rel,
- };
-}
-
-async function runRipgrep(symbol: string, root: string, limit: number): Promise<TextMatch[]> {
- const hits: TextMatch[] = [];
- try {
- const rgArgs = [
- "--json", "--max-count", String(limit),
- "--no-heading", "--word-regexp",
- symbol, root,
- ];
- const { stdout } = await execFileAsync("rg", rgArgs, { maxBuffer: 10 * 1024 * 1024 });
- const seenPaths = new Set<string>();
- for (const line of stdout.split("\n")) {
- if (!line.trim()) continue;
- try {
- const parsed = JSON.parse(line);
- if (parsed.type === "match") {
- const p = parsed.data.path?.text ?? "";
- if (!seenPaths.has(p)) {
- seenPaths.add(p);
- hits.push({ path: p, line: parsed.data.line_number ?? 0 });
- }
- }
- } catch { /* skip */ }
- }
- } catch (err: any) {
- if (err.code === "ENOENT") {
- stderr(chalk.yellow("⚠ ripgrep (rg) is not installed — text fallback skipped. Install it: https://github.com/BurntSushi/ripgrep#installation"));
- } else if (err.code !== 1 && err.status !== 1) {
- throw err;
- }
- }
- return hits.slice(0, 10);
-}
-
function outputLocate(output: LocateOutput, symbol: string, format: string): void {
if (format === "json") {
console.log(JSON.stringify(output, null, 2));
@@ -258,77 +130,36 @@ function outputLocate(output: LocateOutput, symbol: string, format: string): voi
if (!output.resolvedTarget) {
stderr(`No graph entity found for "${symbol}".`);
- if (output.textMatches.length > 0) {
- console.log(chalk.dim("\nText matches:"));
- for (const tm of output.textMatches) {
- console.log(` ${chalk.dim(tm.path)}${chalk.cyan(`:${tm.line}`)}`);
- }
- } else {
- console.log("No matches found.");
- }
+ console.log("No matches found.");
return;
}
const t = output.resolvedTarget;
- if (t.path) console.log(chalk.dim(` ${t.path}`));
- // Structural context
- const ctx = output.structuralContext;
- if (ctx.signature) console.log(` ${chalk.green(ctx.signature)}`);
- if (ctx.container) console.log(` ${chalk.dim("in")} ${chalk.cyan(ctx.container.kind)} ${ctx.container.name}`);
- if (ctx.members && ctx.members.length > 0) {
- console.log(chalk.dim("\nMembers:"));
- for (const m of ctx.members) {
- console.log(` ${chalk.cyan(m.kind.padEnd(10))} ${m.name}`);
+ // Location section
+ const hasLocation = t.path || output.lineRange || output.container;
+ if (hasLocation) {
+ console.log(chalk.bold("\nLocation"));
+ if (t.path) {
+ console.log(` ${chalk.dim("File:".padEnd(16))}${t.path}`);
}
- }
-
- // Relationships grouped by type
- const relGroups = new Map<string, RelatedItem[]>();
- for (const r of output.relationships) {
- const group = relGroups.get(r.relationship) || [];
- group.push(r);
- relGroups.set(r.relationship, group);
- }
-
- const relOrder: RelatedItem["relationship"][] = [
- "contained-by", "contains", "called-by", "calls", "imported-by", "depends-on",
- ];
-
- const LABELS: Record<string, string> = {
- "contained-by": "Contained by",
- "contains": "Contains",
- "called-by": "Called by",
- "calls": "Calls",
- "imported-by": "Imported by",
- "depends-on": "Depends on",
- };
-
- let hasRelationships = false;
- for (const rel of relOrder) {
- const items = relGroups.get(rel);
- if (!items || items.length === 0) continue;
- if (!hasRelationships) {
- console.log(chalk.dim("\nRelationships:"));
- hasRelationships = true;
- }
- console.log(` ${chalk.bold(LABELS[rel])} (${items.length}):`);
- for (const item of items.slice(0, 5)) {
- console.log(` ${chalk.cyan(item.kind.padEnd(10))} ${item.name}`);
+ if (output.lineRange) {
+ console.log(` ${chalk.dim("Lines:".padEnd(16))}${output.lineRange.start}-${output.lineRange.end}`);
}
- if (items.length > 5) {
- console.log(chalk.dim(` ... and ${items.length - 5} more`));
+ if (output.container) {
+ console.log(` ${chalk.dim("Contained in:".padEnd(16))}${output.container.name}`);
}
}
- // Text matches (secondary)
- if (output.textMatches.length > 0) {
- console.log(chalk.dim("\nText matches (other files):"));
- for (const tm of output.textMatches.slice(0, 5)) {
- console.log(` ${chalk.dim(tm.path)}${chalk.cyan(`:${tm.line}`)}`);
- }
- if (output.textMatches.length > 5) {
- console.log(chalk.dim(` ... and ${output.textMatches.length - 5} more`));
- }
+ // System path section
+ if (output.systemPath && output.systemPath.length > 1 && output.hasMapData) {
+ const breadcrumb = output.systemPath.map((n) => n.name).join(" → ");
+ console.log(chalk.bold("\nSystem path"));
+ console.log(` ${breadcrumb}`);
+ }
+
+ // Diagnostics
+ for (const d of output.diagnostics) {
+ stderr(chalk.dim(` ${d}`));
}
}
diff --git a/ix-cli/src/cli/impact/risk-semantics.ts b/ix-cli/src/cli/impact/risk-semantics.ts
new file mode 100644
index 00000000..358365b7
--- /dev/null
+++ b/ix-cli/src/cli/impact/risk-semantics.ts
@@ -0,0 +1,559 @@
+/**
+ * Risk-semantics inference for ix impact.
+ *
+ * Categorizes a target entity as foundation / flow / boundary / shared / localized / unknown
+ * and produces risk-level, at-risk-behavior, and risk-summary language that the
+ * impact command renders at the top of its output.
+ */
+
+export type RiskCategory =
+ | "foundation"
+ | "flow"
+ | "boundary"
+ | "localized"
+ | "shared"
+ | "unknown";
+
+export type RiskLevel = "low" | "medium" | "high" | "critical";
+
+export interface RiskSemantics {
+ category: RiskCategory;
+ riskLevel: RiskLevel;
+ /** One-sentence risk summary for the top of impact output. */
+ riskSummary: string;
+ /** 1–3 concrete behaviors/use-cases at risk. */
+ behaviorAtRisk: string[];
+ /** Free-form contextual label for the "most affected" section. */
+ mostAffectedHint?: string;
+ reasons: string[];
+ /** Specific role phrase for flow-category entities. */
+ flowRole?: string;
+ /** Flow-centric propagation aggregate for methods/functions. */
+ flowPropagation?: { flowName: string; count: number };
+ /** Suggested next command for the user. */
+ nextStep?: string;
+}
+
+// ── Input shape (subset of what impact.ts already collects) ──────────────────
+
+export interface ImpactFacts {
+ name: string;
+ kind: string;
+ path?: string;
+
+ // Container (class/module name wrapping this entity)
+ container?: { kind: string; name: string };
+
+ // System hierarchy path (root-first)
+ systemPath?: Array<{ name: string; kind: string }>;
+
+ // Counts
+ members: number;
+ callers: number;
+ callees: number;
+ directImporters: number;
+ directDependents: number;
+ memberLevelCallers: number;
+
+ // Propagation buckets (already computed by impact.ts)
+ propagationBuckets: Array<{ region: string; regionKind: string; count: number }>;
+
+ // Top caller names (populated by leaf impact)
+ topCallerNames?: string[];
+}
+
+// ── Token helpers ────────────────────────────────────────────────────────────
+
+function splitTokens(s: string): string[] {
+ return s
+ .replace(/([a-z])([A-Z])/g, "$1 $2")
+ .replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2")
+ .split(/[\s_\-./]+/)
+ .map((t) => t.toLowerCase())
+ .filter(Boolean);
+}
+
+function fileBaseName(path?: string): string {
+ if (!path) return "";
+ const base = path.split("/").pop() ?? "";
+ return base.replace(/\.[^.]+$/, "");
+}
+
+function allTokens(facts: ImpactFacts): string[] {
+ const out: string[] = [];
+ out.push(...splitTokens(facts.name));
+ if (facts.path) out.push(...splitTokens(fileBaseName(facts.path)));
+ if (facts.container) out.push(...splitTokens(facts.container.name));
+ if (facts.systemPath) {
+ for (const n of facts.systemPath) {
+ out.push(...splitTokens(n.name));
+ }
+ }
+ return out;
+}
+
+function humanSubsystems(facts: ImpactFacts): string[] {
+ if (!facts.systemPath) return [];
+ return facts.systemPath
+ .filter((n) => ["subsystem", "module", "region"].includes(n.kind))
+ .map((n) => n.name);
+}
+
+// ── Humanize labels ─────────────────────────────────────────────────────────
+
+const ABBREVIATIONS: Record<string, string> = {
+ cli: "CLI",
+ api: "API",
+ db: "database",
+ github: "GitHub",
+};
+
+const SUBSYSTEM_MAPPINGS: Record<string, string> = {
+ explain: "explanation",
+ impact: "impact analysis",
+ resolve: "resolution",
+ resolution: "resolution",
+ conflict: "conflict-resolution",
+ ingestion: "ingestion",
+ parsers: "parser",
+};
+
+function humanizePart(part: string): string {
+ const trimmed = part.trim();
+ const lower = trimmed.toLowerCase();
+
+ // Check subsystem mappings first
+ if (SUBSYSTEM_MAPPINGS[lower]) return SUBSYSTEM_MAPPINGS[lower];
+
+ // Check abbreviations
+ if (ABBREVIATIONS[lower]) return ABBREVIATIONS[lower];
+
+ // Default: lowercase
+ return lower;
+}
+
+export function humanizeLabel(raw: string): string {
+ // Strip trailing parenthetical suffixes like " (2f)", " (region)"
+ const stripped = raw.replace(/\s*\([^)]*\)\s*$/, "");
+
+ // Split on " / "
+ const parts = stripped.split(" / ").map(humanizePart);
+
+ if (parts.length >= 2) {
+ // When first part is an abbreviation (CLI, API), it acts as a modifier → space-join
+ const first = parts[0];
+ const isAbbrev = first === first.toUpperCase() && first.length >= 2 && first.length <= 4;
+ const joiner = isAbbrev ? " " : " and ";
+ return `${parts.join(joiner)} layer`;
+ }
+
+ return `${parts[0]} layer`;
+}
+
+// ── Kind sets ────────────────────────────────────────────────────────────────
+
+const TYPE_KINDS = new Set([
+ "interface", "type", "type_alias", "enum", "sealed_trait",
+ "trait", "abstract_class",
+]);
+
+const CONTAINER_KINDS = new Set([
+ "class", "module", "file", "object", "trait", "interface",
+]);
+
+const CALLABLE_KINDS = new Set([
+ "function", "method", "def", "fun", "constructor",
+]);
+
+// ── Flow detection (reuses token patterns from flow-semantics.ts) ────────────
+
+interface FlowMatch {
+ flowName: string;
+ behaviorDomain: string;
+}
+
+const FLOW_PATTERNS: Array<{ triggers: string[]; flowName: string; behaviorDomain: string }> = [
+ { triggers: ["conflict", "merge", "conflicts"], flowName: "conflict-resolution", behaviorDomain: "conflict handling" },
+ { triggers: ["resolve", "resolution", "match", "select", "pick", "lookup", "resolver", "matcher", "selector"], flowName: "resolution", behaviorDomain: "entity resolution" },
+ { triggers: ["parse", "decode", "read", "tokenize", "lex", "parser", "decoder", "reader", "lexer"], flowName: "parsing", behaviorDomain: "input parsing" },
+ { triggers: ["impact"], flowName: "impact analysis", behaviorDomain: "impact analysis" },
+ { triggers: ["explain", "render"], flowName: "explanation", behaviorDomain: "explanation generation" },
+ { triggers: ["ingest", "store", "persist", "save", "ingestion"], flowName: "ingestion", behaviorDomain: "file ingestion" },
+ { triggers: ["score", "rank", "weight", "evaluate"], flowName: "scoring", behaviorDomain: "candidate scoring" },
+];
+
+function detectFlow(tokens: string[]): FlowMatch | undefined {
+ for (const p of FLOW_PATTERNS) {
+ if (p.triggers.some((t) => tokens.includes(t))) {
+ return { flowName: p.flowName, behaviorDomain: p.behaviorDomain };
+ }
+ }
+ return undefined;
+}
+
+// ── Flow role inference ──────────────────────────────────────────────────────
+
+const FLOW_ROLE_PATTERNS: Array<{ triggers: string[]; role: string }> = [
+ { triggers: ["pick", "select", "best", "filter", "choose"], role: "candidate selection" },
+ { triggers: ["resolve", "lookup", "match"], role: "reference resolution" },
+ { triggers: ["conflict", "merge"], role: "conflict resolution" },
+ { triggers: ["score", "rank", "evaluate"], role: "candidate scoring" },
+ { triggers: ["parse", "decode", "tokenize"], role: "input parsing" },
+ { triggers: ["render"], role: "output rendering" },
+ { triggers: ["infer"], role: "semantic inference" },
+ { triggers: ["ingest", "store", "persist"], role: "data ingestion" },
+];
+
+function inferFlowRole(tokens: string[], flow?: FlowMatch): string | undefined {
+ for (const p of FLOW_ROLE_PATTERNS) {
+ if (p.triggers.some((t) => tokens.includes(t))) {
+ return p.role;
+ }
+ }
+ return flow?.behaviorDomain;
+}
+
+// ── Model/API signals ────────────────────────────────────────────────────────
+
+function hasModelSignal(tokens: string[]): boolean {
+ return tokens.some((t) => ["model", "models", "schema", "db", "database", "entity", "entities", "domain"].includes(t));
+}
+
+// ── Domain noun (mirrors system-meaning.ts) ──────────────────────────────────
+
+function inferDomainNoun(name: string): string {
+ const tokens = splitTokens(name);
+ if (tokens.includes("node")) return "node";
+ if (tokens.includes("edge")) return "edge";
+ if (tokens.includes("graph")) return "graph";
+ if (tokens.includes("parse") || tokens.includes("parser")) return "parse result";
+ if (tokens.includes("context")) return "context";
+ if (tokens.includes("entity")) return "entity";
+ if (tokens.includes("patch")) return "patch";
+ if (tokens.includes("query")) return "query";
+ if (tokens.includes("config")) return "configuration";
+ if (tokens.includes("user")) return "user";
+ return "domain";
+}
+
+// ── Propagation layer names ──────────────────────────────────────────────────
+
+function propagationLayerPhrase(facts: ImpactFacts): string {
+ const subs = humanSubsystems(facts);
+ if (subs.length >= 2) {
+ const humanized = subs.slice(0, 2).map((s) => humanizeLabel(s));
+ return `the ${humanized.join(" and ")}`;
+ }
+ if (subs.length === 1) return `the ${humanizeLabel(subs[0])}`;
+
+ // Fall back to propagation buckets
+ const regions = facts.propagationBuckets
+ .filter((b) => b.region !== "(unmapped)")
+ .sort((a, b) => b.count - a.count)
+ .slice(0, 2)
+ .map((b) => humanizeLabel(b.region));
+ if (regions.length >= 2) return `the ${regions[0]} and ${regions[1]}`;
+ if (regions.length === 1) return `the ${regions[0]}`;
+ return "dependent subsystems";
+}
+
+// ── Category detection ───────────────────────────────────────────────────────
+
+function detectCategory(facts: ImpactFacts): { category: RiskCategory; reasons: string[] } {
+ const kind = facts.kind.toLowerCase();
+ const tokens = allTokens(facts);
+
+ // Foundation: type definitions, enums, interfaces, shared model files
+ if (TYPE_KINDS.has(kind)) {
+ return { category: "foundation", reasons: [`kind "${kind}" is a type-level construct`] };
+ }
+ if (kind === "file" && hasModelSignal(tokens) && facts.members > 0) {
+ return { category: "foundation", reasons: ["model file containing type definitions"] };
+ }
+
+ // Boundary: classes/objects named *Client, *Adapter, or in client/api paths
+ if (CONTAINER_KINDS.has(kind)) {
+ const nameTokens = splitTokens(facts.name);
+ if (nameTokens.includes("client") || nameTokens.includes("adapter")) {
+ return { category: "boundary", reasons: [`name "${facts.name}" indicates a boundary component`] };
+ }
+ if (tokens.some((t) => ["client", "api", "backend"].includes(t)) &&
+ (facts.callers > 5 || facts.memberLevelCallers > 10)) {
+ return { category: "boundary", reasons: ["high-caller class in client/API path"] };
+ }
+ }
+
+ // Flow: callable entities or service classes in flow-related paths
+ const flow = detectFlow(tokens);
+ if (flow && (CALLABLE_KINDS.has(kind) || kind === "method")) {
+ return { category: "flow", reasons: [`callable in ${flow.flowName} flow`] };
+ }
+ if (flow && CONTAINER_KINDS.has(kind) && tokens.some((t) => ["service"].includes(t))) {
+ return { category: "flow", reasons: [`service class in ${flow.flowName} flow`] };
+ }
+
+ // Shared: high fan-in containers that aren't boundary
+ if (CONTAINER_KINDS.has(kind) && (facts.directImporters >= 5 || facts.directDependents >= 8 || facts.memberLevelCallers >= 20)) {
+ return { category: "shared", reasons: ["high fan-in container"] };
+ }
+
+ // Shared: high fan-in callables
+ if (CALLABLE_KINDS.has(kind) && facts.callers >= 5) {
+ return { category: "shared", reasons: ["widely-called function"] };
+ }
+
+ // Localized: low connectivity
+ const totalFanIn = facts.callers + facts.directImporters + facts.directDependents;
+ if (totalFanIn <= 2) {
+ return { category: "localized", reasons: ["limited inbound connections"] };
+ }
+
+ return { category: "unknown", reasons: ["no strong category signals"] };
+}
+
+// ── Risk level ───────────────────────────────────────────────────────────────
+
+function computeRiskLevel(facts: ImpactFacts, category: RiskCategory): RiskLevel {
+ const totalDependents = facts.directImporters + facts.directDependents + facts.memberLevelCallers;
+ const bucketCount = facts.propagationBuckets.filter((b) => b.region !== "(unmapped)").length;
+
+ if (category === "foundation") {
+ if (facts.directImporters >= 5 || totalDependents >= 10) return "critical";
+ if (facts.directImporters >= 2 || totalDependents >= 4) return "high";
+ return "medium";
+ }
+
+ if (category === "boundary") {
+ if (facts.memberLevelCallers >= 30 || bucketCount >= 3) return "critical";
+ if (facts.memberLevelCallers >= 10 || totalDependents >= 10) return "high";
+ return "medium";
+ }
+
+ if (category === "flow") {
+ if (facts.callers >= 5 || totalDependents >= 10) return "high";
+ if (facts.callers >= 2) return "medium";
+ // Even single-caller flow nodes can be medium if they're choke points
+ if (facts.callees >= 3) return "medium";
+ return "low";
+ }
+
+ if (category === "shared") {
+ if (totalDependents >= 15 || bucketCount >= 3) return "high";
+ if (totalDependents >= 5) return "medium";
+ return "medium";
+ }
+
+ if (category === "localized") return "low";
+
+ // unknown
+ if (totalDependents >= 10) return "medium";
+ return "low";
+}
+
+// ── Risk summary sentence ────────────────────────────────────────────────────
+
+function buildRiskSummary(facts: ImpactFacts, category: RiskCategory, riskLevel: RiskLevel): string {
+ const level = riskLevel === "critical" ? "High" : capitalize(riskLevel);
+ const tokens = allTokens(facts);
+ const domain = inferDomainNoun(facts.name);
+ const layers = propagationLayerPhrase(facts);
+
+ switch (category) {
+ case "foundation": {
+ const noun = domain === "domain" ? "shared type" : `shared ${domain}`;
+ let summary = `${level} risk to ${noun} interpretation across ${layers}.`;
+ if (facts.directImporters >= 5) {
+ summary = summary.replace(/\.$/, `, imported as a shared contract by ${facts.directImporters} modules.`);
+ }
+ return summary;
+ }
+ case "boundary":
+ return `${level} risk to backend-facing CLI operations through the ${facts.name} boundary.`;
+ case "flow": {
+ const flow = detectFlow(tokens);
+ const flowRole = inferFlowRole(splitTokens(facts.name), flow);
+ const flowName = flow?.flowName ?? "pipeline";
+ if (flowRole) {
+ return `${level} risk to ${flowRole} in the ${flowName} flow.`;
+ }
+ const flowLabel = flow ? flow.behaviorDomain : "pipeline processing";
+ return `${level} risk to ${flowLabel} in the ${flowName} flow.`;
+ }
+ case "shared":
+ return `${level} risk — widely shared dependency affecting ${layers}.`;
+ case "localized":
+ return `${level} risk — localized impact with limited propagation.`;
+ default:
+ return `${level} risk to dependent code.`;
+ }
+}
+
+function capitalize(s: string): string {
+ return s.charAt(0).toUpperCase() + s.slice(1);
+}
+
+// ── At-risk behavior ─────────────────────────────────────────────────────────
+
+function buildBehaviorAtRisk(facts: ImpactFacts, category: RiskCategory): string[] {
+ const tokens = allTokens(facts);
+ const domain = inferDomainNoun(facts.name);
+ const flow = detectFlow(tokens);
+
+ switch (category) {
+ case "foundation": {
+ const behaviors: string[] = [];
+ const domainLabel = domain === "domain" ? "type" : domain;
+ behaviors.push(`${capitalize(domainLabel)} classification and interpretation`);
+ if (facts.directImporters >= 3) {
+ behaviors.push(`Widely imported (${facts.directImporters} modules) as a shared ${domainLabel} contract`);
+ } else if (facts.directImporters >= 2) {
+ behaviors.push(`Cross-module consistency for ${domainLabel} contracts`);
+ }
+ if (facts.members > 0) {
+ behaviors.push(`Downstream services that depend on ${domainLabel} type definitions`);
+ } else {
+ behaviors.push(`Downstream code relying on shared ${domainLabel} representation`);
+ }
+ return behaviors;
+ }
+
+ case "boundary": {
+ const behaviors: string[] = [];
+ behaviors.push("Backend-facing CLI commands");
+ behaviors.push("Command-to-service communication");
+ if (facts.members > 5) {
+ behaviors.push(`API request behavior across ${facts.members} client methods`);
+ } else {
+ behaviors.push("API request behavior across the client layer");
+ }
+ return behaviors;
+ }
+
+ case "flow": {
+ const behaviors: string[] = [];
+ const flowLabel = flow?.behaviorDomain ?? "processing";
+ if (tokens.some((t) => ["pick", "select", "best", "filter", "choose"].includes(t))) {
+ behaviors.push(`Candidate selection during ${flowLabel}`);
+ } else if (tokens.some((t) => ["resolve", "lookup", "match"].includes(t))) {
+ behaviors.push(`Reference resolution during ${flowLabel}`);
+ } else if (tokens.some((t) => ["conflict", "merge"].includes(t))) {
+ behaviors.push(`Conflict handling logic`);
+ } else {
+ behaviors.push(`${capitalize(flowLabel)} outcomes`);
+ }
+ const flowName = flow?.flowName ?? "pipeline";
+ behaviors.push(`Downstream ${flowName} steps`);
+ if (facts.callers > 0) {
+ behaviors.push(`Upstream callers that depend on ${flowLabel} results`);
+ }
+ return behaviors;
+ }
+
+ case "shared": {
+ const behaviors: string[] = [];
+ behaviors.push("Multiple callers across different subsystems");
+ if (facts.callees > 0) {
+ behaviors.push("Downstream operations coordinated by this component");
+ }
+ behaviors.push("Cross-module behavior consistency");
+ return behaviors;
+ }
+
+ case "localized":
+ return ["Limited to immediate callers"];
+
+ default:
+ return ["Dependent code behavior"];
+ }
+}
+
+// ── Most-affected hint ───────────────────────────────────────────────────────
+
+function buildMostAffectedHint(facts: ImpactFacts, category: RiskCategory): string | undefined {
+ const domain = inferDomainNoun(facts.name);
+ const tokens = allTokens(facts);
+
+ switch (category) {
+ case "foundation":
+ if (domain !== "domain") {
+ return `model types and parsers that depend on ${domain} classification`;
+ }
+ return "modules that import shared type contracts";
+ case "boundary":
+ return "command handlers that depend on client access";
+ case "flow": {
+ const flow = detectFlow(tokens);
+ const flowName = flow?.flowName ?? "processing";
+ const flowRole = inferFlowRole(splitTokens(facts.name), flow);
+ const hints: string[] = [];
+ if (facts.topCallerNames && facts.topCallerNames.length > 0) {
+ hints.push(`${flowName} entrypoints like ${facts.topCallerNames[0]}`);
+ } else {
+ hints.push(`upstream callers in the ${flowName} flow`);
+ }
+ hints.push(`downstream ${flowRole ?? flowName} stages`);
+ return hints.join("; ");
+ }
+ case "shared":
+ return "callers across multiple subsystems";
+ default:
+ return undefined;
+ }
+}
+
+// ── Next step ────────────────────────────────────────────────────────────────
+
+function buildNextStep(facts: ImpactFacts, category: RiskCategory): string | undefined {
+ if ((category === "foundation" || category === "shared") && facts.directImporters >= 3) {
+ return `Understand its system role: ix explain ${facts.name}`;
+ }
+ if (category === "boundary" && facts.memberLevelCallers >= 10) {
+ return `Trace propagation: ix depends ${facts.name} --depth 2`;
+ }
+ if (category === "flow" && facts.callers >= 1) {
+ return `Trace flow propagation: ix depends ${facts.name} --depth 2`;
+ }
+ return undefined;
+}
+
+// ── Flow propagation ─────────────────────────────────────────────────────────
+
+function buildFlowPropagation(
+ facts: ImpactFacts,
+ category: RiskCategory,
+ tokens: string[],
+): { flowName: string; count: number } | undefined {
+ if (category !== "flow") return undefined;
+ const flow = detectFlow(tokens);
+ if (!flow) return undefined;
+ const totalCount = facts.propagationBuckets.reduce((sum, b) => sum + b.count, 0);
+ if (totalCount === 0) return undefined;
+ return { flowName: flow.flowName, count: totalCount };
+}
+
+// ── Main entry ───────────────────────────────────────────────────────────────
+
+export function inferRiskSemantics(facts: ImpactFacts): RiskSemantics {
+ const { category, reasons } = detectCategory(facts);
+ const riskLevel = computeRiskLevel(facts, category);
+ const riskSummary = buildRiskSummary(facts, category, riskLevel);
+ const behaviorAtRisk = buildBehaviorAtRisk(facts, category);
+ const mostAffectedHint = buildMostAffectedHint(facts, category);
+ const tokens = allTokens(facts);
+ const flow = detectFlow(tokens);
+ const flowRole = category === "flow" ? inferFlowRole(splitTokens(facts.name), flow) : undefined;
+ const flowPropagation = buildFlowPropagation(facts, category, tokens);
+ const nextStep = buildNextStep(facts, category);
+
+ return {
+ category,
+ riskLevel,
+ riskSummary,
+ behaviorAtRisk,
+ mostAffectedHint,
+ reasons,
+ flowRole,
+ flowPropagation,
+ nextStep,
+ };
+}