Skip to content

armgit / Ix

Public Imported from GitHub
0

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

fix: add missing hierarchy/semantics modules; add trace+depends to oss registration and help

Joseph Mikhaild9a360f28d0f
diff --git a/ix-cli/src/cli/explain/flow-semantics.ts b/ix-cli/src/cli/explain/flow-semantics.ts
new file mode 100644
index 00000000..468bec25
--- /dev/null
+++ b/ix-cli/src/cli/explain/flow-semantics.ts
@@ -0,0 +1,103 @@
+import type { EntityFacts } from "./facts.js";
+
+export interface FlowSemantics {
+ confidence: "low" | "medium" | "high";
+ flowName?: string;
+ roleInFlow?: string;
+ upstreamHint?: string;
+ downstreamHint?: string;
+}
+
+interface FlowRule {
+ namePat?: RegExp;
+ pathPat?: RegExp;
+ containerPat?: RegExp;
+ flowName: string;
+ roleInFlow: string;
+ priority: number;
+}
+
+// Rules ordered by priority (higher = checked later, wins ties)
+const FLOW_RULES: FlowRule[] = [
+ { namePat: /parse|tokenize|lex/i, pathPat: /parser/i, flowName: "parsing pipeline", roleInFlow: "parsing step", priority: 1 },
+ { namePat: /parse|tokenize|lex/i, flowName: "parsing pipeline", roleInFlow: "parsing step", priority: 1 },
+ { namePat: /resolve|lookup/i, pathPat: /resolve/i, flowName: "resolution flow", roleInFlow: "resolution step", priority: 2 },
+ { namePat: /pick|select|choose|rank/i, pathPat: /resolve/i, flowName: "resolution flow", roleInFlow: "selection step", priority: 3 },
+ { namePat: /score|weight/i, flowName: "scoring pipeline", roleInFlow: "scoring step", priority: 1 },
+ { namePat: /rank/i, flowName: "ranking pipeline", roleInFlow: "ranking step", priority: 1 },
+ { namePat: /ingest|index/i, flowName: "ingestion pipeline", roleInFlow: "ingestion step", priority: 1 },
+ { namePat: /persist|save|store/i, flowName: "ingestion pipeline", roleInFlow: "persistence step", priority: 1 },
+ { namePat: /render|format|display/i, flowName: "rendering pipeline", roleInFlow: "rendering step", priority: 1 },
+ { namePat: /impact|traverse|walk/i, flowName: "impact pipeline", roleInFlow: "traversal step", priority: 1 },
+ { namePat: /explain|infer|synthesize/i, flowName: "explanation pipeline", roleInFlow: "inference step", priority: 1 },
+ // Container-based rules
+ { containerPat: /IngestionService/i, flowName: "ingestion pipeline", roleInFlow: "ingestion step", priority: 2 },
+ { containerPat: /ConflictService/i, flowName: "conflict-resolution flow", roleInFlow: "conflict resolver", priority: 4 },
+ { containerPat: /Parser/i, flowName: "parsing pipeline", roleInFlow: "parsing step", priority: 2 },
+ { containerPat: /Scorer|Ranker/i, flowName: "scoring pipeline", roleInFlow: "scoring step", priority: 2 },
+ // Path-based for conflict
+ { pathPat: /conflict/i, namePat: /resolve|conflict/i, flowName: "conflict-resolution flow", roleInFlow: "conflict resolver", priority: 5 },
+ { pathPat: /conflict/i, flowName: "conflict-resolution flow", roleInFlow: "conflict resolution step", priority: 3 },
+];
+
+export function inferFlowSemantics(facts: EntityFacts): FlowSemantics {
+ const path = facts.path ?? "";
+ const name = facts.name ?? "";
+ const containerName = facts.container?.name ?? "";
+
+ let best: { rule: FlowRule; score: number } | null = null;
+
+ for (const rule of FLOW_RULES) {
+ let score = 0;
+ let matches = true;
+
+ if (rule.namePat) {
+ if (rule.namePat.test(name)) score += 2;
+ else if (!rule.pathPat && !rule.containerPat) { matches = false; continue; }
+ else if (!rule.pathPat?.test(path) && !rule.containerPat?.test(containerName)) { matches = false; continue; }
+ }
+
+ if (rule.pathPat) {
+ if (rule.pathPat.test(path)) score += 2;
+ else if (!rule.namePat?.test(name) && !rule.containerPat?.test(containerName)) { matches = false; continue; }
+ }
+
+ if (rule.containerPat) {
+ if (rule.containerPat.test(containerName)) score += 3;
+ else if (rule.containerPat && !rule.namePat && !rule.pathPat) { matches = false; continue; }
+ }
+
+ if (!matches || score === 0) continue;
+
+ const totalScore = score + rule.priority;
+ if (!best || totalScore > best.score) {
+ best = { rule, score: totalScore };
+ }
+ }
+
+ if (!best) {
+ return { confidence: "low" };
+ }
+
+ // Determine confidence based on how many signals matched
+ const confidence: "low" | "medium" | "high" = best.score >= 5 ? "high" : best.score >= 3 ? "medium" : "low";
+
+ // Build hints
+ let upstreamHint: string | undefined;
+ let downstreamHint: string | undefined;
+
+ if (facts.topCallers.length > 0) {
+ upstreamHint = `called from ${facts.topCallers[0]}`;
+ }
+ if (facts.downstreamDependents > 0) {
+ downstreamHint = `feeds ${facts.downstreamDependents} downstream dependents`;
+ }
+
+ return {
+ confidence,
+ flowName: best.rule.flowName,
+ roleInFlow: best.rule.roleInFlow,
+ upstreamHint,
+ downstreamHint,
+ };
+}
diff --git a/ix-cli/src/cli/explain/hierarchy-semantics.ts b/ix-cli/src/cli/explain/hierarchy-semantics.ts
new file mode 100644
index 00000000..a3051a2f
--- /dev/null
+++ b/ix-cli/src/cli/explain/hierarchy-semantics.ts
@@ -0,0 +1,135 @@
+import type { EntityFacts } from "./facts.js";
+import type { RoleLabel } from "./role-inference.js";
+
+export interface HierarchySemantics {
+ layerName?: string;
+ flowName?: string;
+ boundaryRole?: string;
+ systemRole?: string;
+ reasons: string[];
+}
+
+// Maps subsystem/path keywords to semantic layer/flow names
+const SUBSYSTEM_FLOW_MAP: Array<{ match: RegExp; flowName?: string; layerName?: string }> = [
+ { match: /resolve/i, flowName: "resolution pipeline", layerName: "resolution pipeline" },
+ { match: /impact/i, flowName: "impact pipeline" },
+ { match: /explain/i, flowName: "explanation pipeline", layerName: "explanation subsystem" },
+ { match: /conflict/i, flowName: "conflict-resolution flow" },
+ { match: /ingest/i, flowName: "ingestion pipeline" },
+ { match: /parse|parser/i, flowName: "parsing pipeline" },
+ { match: /score|scoring/i, flowName: "scoring pipeline" },
+ { match: /rank/i, flowName: "ranking pipeline" },
+ { match: /command|commands/i, layerName: "command layer" },
+ { match: /client/i, layerName: "CLI client layer" },
+];
+
+function matchSubsystem(name: string): { flowName?: string; layerName?: string } | null {
+ for (const entry of SUBSYSTEM_FLOW_MAP) {
+ if (entry.match.test(name)) {
+ return { flowName: entry.flowName, layerName: entry.layerName };
+ }
+ }
+ return null;
+}
+
+export function inferHierarchySemantics(facts: EntityFacts, role: RoleLabel): HierarchySemantics {
+ const reasons: string[] = [];
+ const systemPath = facts.systemPath ?? [];
+
+ if (systemPath.length === 0) {
+ return { reasons };
+ }
+
+ // Extract subsystem name from path
+ const subsystemNode = systemPath.find((n) => n.kind === "subsystem");
+ const moduleNode = systemPath.find((n) => n.kind === "module");
+ const subsystemName = subsystemNode?.name ?? facts.subsystemName;
+ const moduleName = moduleNode?.name ?? facts.moduleName;
+
+ // Try to match subsystem or module name to known flow/layer
+ const searchName = subsystemName ?? moduleName ?? "";
+ const matched = searchName ? matchSubsystem(searchName) : null;
+
+ let layerName: string | undefined;
+ let flowName: string | undefined;
+ let boundaryRole: string | undefined;
+ let systemRole: string | undefined;
+
+ if (matched) {
+ flowName = matched.flowName;
+ layerName = matched.layerName ?? matched.flowName;
+ } else if (subsystemName) {
+ layerName = `${subsystemName} subsystem`;
+ } else if (moduleName) {
+ layerName = `${moduleName} layer`;
+ }
+
+ // Detect boundary roles (API clients, adapters at system edge)
+ if (role === "api-client" && (layerName?.includes("client") || searchName.toLowerCase().includes("client"))) {
+ boundaryRole = "boundary";
+ systemRole = `boundary between the CLI and backend services`;
+ reasons.push(`Located in the CLI client layer`);
+ }
+
+ if (layerName) reasons.push(`Part of the ${layerName}`);
+ if (flowName) reasons.push(`Participates in the ${flowName}`);
+
+ return { layerName, flowName, boundaryRole, systemRole, reasons };
+}
+
+export function synthesizeSystemRole(
+ facts: EntityFacts,
+ role: RoleLabel,
+ sem: HierarchySemantics,
+): string | null {
+ if (!sem.layerName && !sem.flowName) return null;
+
+ // Boundary roles
+ if (sem.boundaryRole === "boundary" && sem.layerName) {
+ return `the ${sem.boundaryRole} of the ${sem.layerName} — the typed boundary between the CLI and backend services`;
+ }
+
+ // Flow-aware roles
+ if (sem.flowName) {
+ switch (role) {
+ case "selection-helper":
+ return `a selection step in the ${sem.flowName}`;
+ case "resolution-helper":
+ return `a resolution step in the ${sem.flowName}`;
+ case "scoring-helper":
+ return `a scoring step in the ${sem.flowName}`;
+ case "orchestrator":
+ return `an orchestrator in the ${sem.flowName}`;
+ case "service-method":
+ return `a method in the ${sem.flowName}`;
+ default:
+ if (sem.layerName) return `a component of the ${sem.layerName}`;
+ return null;
+ }
+ }
+
+ if (sem.layerName) {
+ return `a component of the ${sem.layerName}`;
+ }
+
+ return null;
+}
+
+export function hierarchyImpactPhrase(
+ facts: EntityFacts,
+ sem: HierarchySemantics,
+): string | null {
+ if (!sem.layerName && !sem.flowName) return null;
+
+ const location = sem.flowName ?? sem.layerName!;
+ const count = facts.downstreamDependents;
+
+ if (count > 10) {
+ return `it sits in the ${location} and feeds ${count} downstream dependents, changes propagate widely through the system`;
+ }
+ if (facts.callerCount >= 5) {
+ return `it is called by ${facts.callerCount} entities in the ${location}`;
+ }
+
+ return null;
+}
diff --git a/ix-cli/src/cli/explain/system-meaning.ts b/ix-cli/src/cli/explain/system-meaning.ts
new file mode 100644
index 00000000..6e135788
--- /dev/null
+++ b/ix-cli/src/cli/explain/system-meaning.ts
@@ -0,0 +1,122 @@
+import type { EntityFacts } from "./facts.js";
+import type { RoleLabel } from "./role-inference.js";
+import type { HierarchySemantics } from "./hierarchy-semantics.js";
+import type { ImportanceInference } from "./importance.js";
+
+export interface SystemMeaning {
+ archetype: "foundation" | "boundary" | "flow" | "general";
+ identitySummary: string;
+ responsibility: string;
+ usageSummary?: string;
+ importanceNarrative?: string;
+}
+
+const FOUNDATION_KINDS = new Set(["enum", "interface", "type", "trait", "data_class"]);
+const BOUNDARY_ROLES = new Set<RoleLabel>(["api-client", "adapter"]);
+const FLOW_ROLES = new Set<RoleLabel>([
+ "selection-helper", "resolution-helper", "scoring-helper",
+ "orchestrator", "service-method", "service",
+]);
+
+/** Extract domain noun from entity name (e.g. NodeKind → "node", ParseResult → "parse result"). */
+function domainNounFromName(name: string): string {
+ // camelCase/PascalCase → words
+ const words = name
+ .replace(/([A-Z])/g, " $1")
+ .trim()
+ .toLowerCase()
+ .split(/\s+/);
+ // Drop common suffixes that aren't the domain noun
+ const drop = new Set(["kind", "type", "api", "result", "config", "service", "interface"]);
+ const domainWords = words.filter((w) => !drop.has(w));
+ return domainWords.length > 0 ? domainWords[0] : words[0];
+}
+
+function isModelFile(facts: EntityFacts): boolean {
+ const path = facts.path?.toLowerCase() ?? "";
+ return (
+ facts.kind === "file" &&
+ (path.includes("/model/") || path.includes("model.") || path.includes("/schema/")) &&
+ facts.memberCount > 0
+ );
+}
+
+function isFoundation(facts: EntityFacts, role: RoleLabel): boolean {
+ if (FOUNDATION_KINDS.has(facts.kind)) return true;
+ if (role === "type-definition" && (facts.importerCount >= 3 || facts.dependentCount >= 3)) return true;
+ if (role === "data-model") return true;
+ if (isModelFile(facts)) return true;
+ return false;
+}
+
+function buildFoundationMeaning(facts: EntityFacts, sem: HierarchySemantics, importance: ImportanceInference): SystemMeaning {
+ const noun = domainNounFromName(facts.name);
+ const location = sem.layerName ?? sem.flowName;
+
+ let identitySummary: string;
+ if (isModelFile(facts)) {
+ identitySummary = `a foundational definition file for ${noun}-related types`;
+ } else if (facts.kind === "interface") {
+ identitySummary = `a foundational contract defining the ${noun} interface`;
+ } else if (facts.kind === "enum") {
+ identitySummary = `a foundational ${noun} classification used across the system`;
+ } else {
+ identitySummary = `a foundational ${noun} type`;
+ }
+
+ let responsibility: string;
+ if (facts.importerCount >= 5 || facts.dependentCount >= 8) {
+ responsibility = `Consumed by multiple services and layers — changes affect the entire ${location ?? "system"}.`;
+ } else {
+ responsibility = `Defines the ${noun} contract used in ${location ?? "this subsystem"}.`;
+ }
+
+ let usageSummary: string | undefined;
+ if (facts.topCallers.length > 0) {
+ const names = facts.topCallers.slice(0, 3).join(", ");
+ usageSummary = `Used by ${names}${facts.callerCount > 3 ? ` and ${facts.callerCount - 3} others` : ""}.`;
+ }
+
+ let importanceNarrative: string | undefined;
+ if (importance.level === "high") {
+ const context = location ? `in the ${location}` : "across the system";
+ importanceNarrative = `This is a shared foundational type ${context}. Changes propagate to all importers — run \`ix impact ${facts.name}\` before modifying.`;
+ }
+
+ return { archetype: "foundation", identitySummary, responsibility, usageSummary, importanceNarrative };
+}
+
+function buildBoundaryMeaning(facts: EntityFacts, sem: HierarchySemantics, importance: ImportanceInference): SystemMeaning {
+ const layer = sem.layerName ?? "CLI layer";
+ const identitySummary = `the typed boundary between the CLI and backend services in the ${layer}`;
+ const responsibility = `Provides all graph queries to CLI commands. Changes here affect every command that reads the knowledge graph.`;
+ return { archetype: "boundary", identitySummary, responsibility };
+}
+
+function buildFlowMeaning(facts: EntityFacts, sem: HierarchySemantics, importance: ImportanceInference): SystemMeaning {
+ const flow = sem.flowName ?? sem.layerName ?? "pipeline";
+ const identitySummary = `a component of the ${flow}`;
+ const responsibility = `Participates in the ${flow} — affects how this pipeline processes data.`;
+ return { archetype: "flow", identitySummary, responsibility };
+}
+
+export function inferSystemMeaning(
+ facts: EntityFacts,
+ role: RoleLabel,
+ sem: HierarchySemantics,
+ importance: ImportanceInference,
+): SystemMeaning | null {
+ if (isFoundation(facts, role)) {
+ return buildFoundationMeaning(facts, sem, importance);
+ }
+
+ if (BOUNDARY_ROLES.has(role) && sem.boundaryRole === "boundary") {
+ return buildBoundaryMeaning(facts, sem, importance);
+ }
+
+ if (FLOW_ROLES.has(role) && (sem.flowName || sem.layerName)) {
+ return buildFlowMeaning(facts, sem, importance);
+ }
+
+ return null;
+}
diff --git a/ix-cli/src/cli/help-text.ts b/ix-cli/src/cli/help-text.ts
index 3aa42c56..2f49f700 100644
--- a/ix-cli/src/cli/help-text.ts
+++ b/ix-cli/src/cli/help-text.ts
@@ -14,6 +14,8 @@ Understand:
read <target> Read file content or symbol source code
Explore:
+ trace <symbol> Follow how a symbol connects upstream and downstream
+ depends <symbol> Show upstream dependents of a symbol
inventory List entities by kind
rank Hotspot discovery by metric
history <entityId> Show entity provenance chain
diff --git a/ix-cli/src/cli/hierarchy.ts b/ix-cli/src/cli/hierarchy.ts
new file mode 100644
index 00000000..b9cde020
--- /dev/null
+++ b/ix-cli/src/cli/hierarchy.ts
@@ -0,0 +1,81 @@
+import type { IxClient } from "../client/api.js";
+
+export type SystemPath = Array<{ name: string; kind: string; id?: string }>;
+
+const REGION_KINDS = new Set(["system", "subsystem", "module", "region"]);
+
+/** Traverse IN_REGION edges upward to build the system-hierarchy path for a node. */
+export async function getSystemPath(client: IxClient, nodeId: string): Promise<SystemPath> {
+ try {
+ const result = await client.expand(nodeId, { direction: "out", predicates: ["IN_REGION"], hops: 5 });
+ const nodes = result.nodes as Array<{ id: string; name?: string; attrs?: { name?: string }; kind?: string }>;
+ if (nodes.length === 0) return [];
+ // Sort by region kind: system > subsystem > module > region > file
+ const kindOrder: Record<string, number> = { system: 0, subsystem: 1, module: 2, region: 3, file: 4 };
+ const sorted = [...nodes].sort((a, b) => {
+ const aK = a.kind ?? "";
+ const bK = b.kind ?? "";
+ return (kindOrder[aK] ?? 5) - (kindOrder[bK] ?? 5);
+ });
+ return sorted.map((n) => ({
+ id: n.id,
+ name: (n as any).name || n.attrs?.name || "(unnamed)",
+ kind: (n as any).kind || "region",
+ }));
+ } catch {
+ return [];
+ }
+}
+
+/** Format a system path as "A > B > C". */
+export function formatSystemPath(path: SystemPath): string {
+ return path.map((n) => n.name).join(" > ");
+}
+
+/** Returns true if the path contains at least one region/system node (i.e. map data exists). */
+export function hasMapData(path: SystemPath): boolean {
+ return path.some((n) => REGION_KINDS.has(n.kind));
+}
+
+/** Group a set of node IDs by their containing region (IN_REGION). */
+export async function bucketByHierarchy(
+ client: IxClient,
+ nodeIds: string[],
+): Promise<Array<{ region: { name: string; kind: string }; members: Array<{ name: string; kind: string }> }>> {
+ if (nodeIds.length === 0) return [];
+
+ // For each node, find its immediate region
+ const buckets = new Map<string, { region: { name: string; kind: string }; members: Array<{ name: string; kind: string }> }>();
+
+ await Promise.all(
+ nodeIds.map(async (nodeId) => {
+ try {
+ const nodeDetails = await client.entity(nodeId);
+ const node = nodeDetails.node as any;
+ const memberName = node.name || node.attrs?.name || "(unnamed)";
+ const memberKind = node.kind || "unknown";
+
+ const regionResult = await client.expand(nodeId, { direction: "out", predicates: ["IN_REGION"], hops: 1 });
+ const regionNodes = regionResult.nodes as Array<{ id: string; name?: string; attrs?: { name?: string }; kind?: string }>;
+
+ // Pick the most specific region (lowest in hierarchy)
+ const kindOrder: Record<string, number> = { file: 0, module: 1, region: 1, subsystem: 2, system: 3 };
+ const region = regionNodes.sort((a, b) => (kindOrder[(a as any).kind ?? ""] ?? 4) - (kindOrder[(b as any).kind ?? ""] ?? 4))[0];
+
+ if (region) {
+ const regionName = (region as any).name || region.attrs?.name || "(unnamed)";
+ const regionKind = (region as any).kind || "region";
+ const key = region.id;
+ if (!buckets.has(key)) {
+ buckets.set(key, { region: { name: regionName, kind: regionKind }, members: [] });
+ }
+ buckets.get(key)!.members.push({ name: memberName, kind: memberKind });
+ }
+ } catch {
+ /* skip nodes that can't be expanded */
+ }
+ }),
+ );
+
+ return [...buckets.values()];
+}