Skip to content

armgit / Ix

Public Imported from GitHub
0

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

feat: strict agent-safe CLI output — no dangling refs, structured diagnostics

riley022781d712e3c3df
diff --git a/AGENTS.md b/AGENTS.md
new file mode 100644
index 00000000..22a5f000
--- /dev/null
+++ b/AGENTS.md
@@ -0,0 +1,106 @@
+# Ix CLI — Agent Usage Guide
+
+This file tells automated agents (Codex, Claude, etc.) how to use the `ix` CLI effectively.
+
+## Interface
+
+Use the `ix` CLI exclusively. All commands support `--format json` for machine-readable output.
+
+**Do NOT use MCP tools** — the CLI is the canonical agent interface.
+
+## JSON Mode
+
+Always use `--format json` when chaining commands or parsing results programmatically.
+
+JSON output is strict — no text preamble or postamble. The output is a single JSON object.
+
+### Standard JSON fields
+
+| Field | Description |
+|-------|-------------|
+| `resolvedTarget` | The entity that was resolved (`{id, kind, name}`) |
+| `resolutionMode` | How the entity was resolved: `exact`, `preferred-kind`, `ambiguous`, `heuristic` |
+| `resultSource` | Where results came from: `graph`, `text`, `graph+text`, `heuristic` |
+| `results` | Array of result entities |
+| `summary` | Counts and aggregates |
+| `diagnostics` | Array of `{code, message}` explaining empty or weak results |
+| `warning` | Human-readable warning string |
+
+### Diagnostic codes
+
+| Code | Meaning |
+|------|---------|
+| `no_edges` | Entity resolved but no graph edges of the requested type exist |
+| `unresolved_call_target` | A callee/caller could not be resolved to a named entity |
+| `dangling_reference_filtered` | Some results had unresolvable IDs |
+| `ambiguous_resolution` | Multiple entities matched; specify `--kind` or use entity ID |
+| `text_fallback_used` | Graph had no results; text search was used instead |
+| `parser_gap_suspected` | Results suggest the parser did not fully index this area |
+
+## Result entities
+
+Each result entity in `results` includes:
+
+- `name` — human-readable name (present when `resolved: true`)
+- `kind` — entity kind (function, method, class, etc.)
+- `id` — resolvable entity ID (present when `resolved: true`)
+- `resolved` — boolean indicating whether this entity can be followed up
+- `path` — source file path (when available)
+- `suggestedCommand` — a follow-up `ix` command to get more details
+- `rawId` — raw graph ID (only present when `resolved: false`)
+
+**Rule:** Only use `id` fields from entities where `resolved: true`. Do not attempt `ix entity <rawId>` on unresolved references.
+
+## Command routing
+
+### Finding code
+```
+ix search <term> --format json --limit 10
+ix text <term> --format json --language python
+ix locate <symbol> --format json
+ix read <file:lines>
+```
+
+### Understanding entities
+```
+ix explain <symbol> --format json
+ix entity <id> --format json
+```
+
+### Navigating relationships
+```
+ix callers <symbol> --format json
+ix callees <symbol> --format json
+ix contains <symbol> --format json
+ix imports <symbol> --format json
+ix imported-by <symbol> --format json
+ix depends <symbol> --format json
+```
+
+### History and decisions
+```
+ix decisions --format json
+ix history <id> --format json
+ix diff <from> <to> --format json
+```
+
+## Chaining pattern
+
+1. Search: `ix search MyClass --format json --limit 5`
+2. Pick the result with `resolved: true` and extract `id`
+3. Drill in: `ix explain MyClass --format json` or `ix entity <id> --format json`
+4. Navigate: `ix callers MyClass --format json`
+
+## Handling unresolved references
+
+When a result has `resolved: false`:
+- Do NOT follow the `rawId` with `ix entity`
+- Instead, use `ix text "<name>"` or `ix read <file>` to locate it
+- Check `suggestedCommand` if present
+
+## Handling empty results
+
+Check `diagnostics` in the JSON response:
+- `no_edges` — entity exists but has no edges of this type. Try `ix text` instead.
+- `text_fallback_used` — graph traversal was empty; text matches shown instead.
+- `ambiguous_resolution` — re-run with `--kind <kind>` to disambiguate.
diff --git a/ix-cli/src/cli/commands/callers.ts b/ix-cli/src/cli/commands/callers.ts
index d155ec29..e4ca1996 100644
--- a/ix-cli/src/cli/commands/callers.ts
+++ b/ix-cli/src/cli/commands/callers.ts
@@ -22,7 +22,7 @@ export function registerCallersCommand(program: Command): void {
const limit = parseInt(opts.limit, 10);
const target = await resolveEntity(client, symbol, ["method", "function"], opts);
if (!target) return;
- printResolved(target);
+ if (opts.format !== "json") printResolved(target);
// Use expandByName for cross-file resolution
const result = await client.expandByName(target.name, {
direction: "in",
@@ -93,7 +93,7 @@ export function registerCallersCommand(program: Command): void {
const calleeLimit = parseInt(opts.limit, 10);
const target = await resolveEntity(client, symbol, ["method", "function"], opts);
if (!target) return;
- printResolved(target);
+ if (opts.format !== "json") printResolved(target);
// Use expandByName for cross-file resolution
const result = await client.expandByName(target.name, {
direction: "out",
diff --git a/ix-cli/src/cli/commands/contains.ts b/ix-cli/src/cli/commands/contains.ts
index 7a351873..335b4390 100644
--- a/ix-cli/src/cli/commands/contains.ts
+++ b/ix-cli/src/cli/commands/contains.ts
@@ -17,7 +17,7 @@ export function registerContainsCommand(program: Command): void {
const limit = parseInt(opts.limit, 10);
const target = await resolveEntity(client, symbol, ["class", "object", "trait", "interface", "module", "file"], opts);
if (!target) return;
- printResolved(target);
+ if (opts.format !== "json") printResolved(target);
const result = await client.expand(target.id, { direction: "out", predicates: ["CONTAINS"] });
const limited = result.nodes.slice(0, limit);
formatEdgeResults(limited, "contains", target.name, opts.format, target, "graph");
diff --git a/ix-cli/src/cli/commands/depends.ts b/ix-cli/src/cli/commands/depends.ts
index 7b9e8a66..c652bb45 100644
--- a/ix-cli/src/cli/commands/depends.ts
+++ b/ix-cli/src/cli/commands/depends.ts
@@ -2,7 +2,7 @@ import type { Command } from "commander";
import chalk from "chalk";
import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
-import { resolveEntity, printResolved } from "../resolve.js";
+import { resolveEntity, printResolved, isRawId } from "../resolve.js";
export function registerDependsCommand(program: Command): void {
program
@@ -49,28 +49,48 @@ export function registerDependsCommand(program: Command): void {
const allDependents = [...callers, ...importers].slice(0, limit);
+ const mapDependent = (d: any) => {
+ const name = d.name || d.attrs?.name || "";
+ const resolved = !!name && !isRawId(name);
+ return {
+ name: resolved ? name : undefined,
+ kind: d.kind,
+ id: resolved ? d.id : undefined,
+ resolved,
+ via: d.via,
+ path: d.provenance?.source_uri ?? d.provenance?.sourceUri ?? d.attrs?.path ?? undefined,
+ ...(resolved ? { suggestedCommand: `ix explain "${name}"` } : { rawId: d.id }),
+ };
+ };
+
if (opts.format === "json") {
- console.log(JSON.stringify({
- resultSource: "graph" as const,
+ const results = allDependents.map(mapDependent);
+ const unresolvedCount = results.filter(r => !r.resolved).length;
+ const output: any = {
resolvedTarget: target,
- directDependents: allDependents.map((d: any) => ({
- id: d.id,
- kind: d.kind,
- name: d.name || d.attrs?.name || d.id,
- via: d.via,
- })),
+ resolutionMode: target.resolutionMode,
+ resultSource: "graph",
+ results,
summary: {
- direct: allDependents.length,
+ total: allDependents.length,
+ resolved: allDependents.length - unresolvedCount,
+ unresolved: unresolvedCount,
viaCalls: callers.length,
viaImports: importers.length,
},
- }, null, 2));
+ };
+ if (allDependents.length === 0) {
+ output.diagnostics = [{ code: "no_edges", message: `No CALLS or IMPORTS edges found pointing to resolved entity.` }];
+ } else if (unresolvedCount > 0) {
+ output.diagnostics = [{ code: "dangling_reference_filtered", message: `${unresolvedCount} dependent(s) could not be resolved to named entities.` }];
+ }
+ console.log(JSON.stringify(output, null, 2));
return;
}
printResolved(target);
if (allDependents.length === 0) {
- console.log(`No dependents found for "${target.name}".`);
+ console.log(`Resolved to ${target.kind} ${target.name}; no CALLS/IMPORTS edges found at current graph state.`);
return;
}
@@ -78,8 +98,12 @@ export function registerDependsCommand(program: Command): void {
console.log(chalk.bold(` via CALLS (${callers.length}):`));
for (const d of callers) {
const shortId = d.id?.slice(0, 8) ?? "";
- const name = d.name || d.attrs?.name || d.id;
- console.log(` ${chalk.cyan((d.kind ?? "").padEnd(10))} ${chalk.dim(shortId)} ${name}`);
+ const name = d.name || d.attrs?.name || "";
+ if (!name || isRawId(name)) {
+ console.log(` ${chalk.cyan((d.kind ?? "").padEnd(10))} ${chalk.dim(shortId)} ${chalk.dim("(unresolved)")}`);
+ } else {
+ console.log(` ${chalk.cyan((d.kind ?? "").padEnd(10))} ${chalk.dim(shortId)} ${name}`);
+ }
}
}
@@ -87,8 +111,12 @@ export function registerDependsCommand(program: Command): void {
console.log(chalk.bold(` via IMPORTS (${importers.length}):`));
for (const d of importers) {
const shortId = d.id?.slice(0, 8) ?? "";
- const name = d.name || d.attrs?.name || d.id;
- console.log(` ${chalk.cyan((d.kind ?? "").padEnd(10))} ${chalk.dim(shortId)} ${name}`);
+ const name = d.name || d.attrs?.name || "";
+ if (!name || isRawId(name)) {
+ console.log(` ${chalk.cyan((d.kind ?? "").padEnd(10))} ${chalk.dim(shortId)} ${chalk.dim("(unresolved)")}`);
+ } else {
+ console.log(` ${chalk.cyan((d.kind ?? "").padEnd(10))} ${chalk.dim(shortId)} ${name}`);
+ }
}
}
diff --git a/ix-cli/src/cli/commands/explain.ts b/ix-cli/src/cli/commands/explain.ts
index d9658681..f249d00d 100644
--- a/ix-cli/src/cli/commands/explain.ts
+++ b/ix-cli/src/cli/commands/explain.ts
@@ -1,8 +1,8 @@
import type { Command } from "commander";
import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
-import { formatExplain, type ExplainResult } from "../format.js";
-import { resolveEntity } from "../resolve.js";
+import { formatExplain, type ExplainResult, type EntityRef, type Diagnostic } from "../format.js";
+import { resolveEntity, isRawId } from "../resolve.js";
export function registerExplainCommand(program: Command): void {
program
@@ -46,19 +46,51 @@ export function registerExplainCommand(program: Command): void {
const signature = node.attrs?.signature || node.attrs?.summary;
const docstring = node.attrs?.docstring || node.attrs?.description;
- // Get actual callee names from outgoing CALLS edges
+ // Get actual callee details from outgoing CALLS edges
const calleeEdges = callEdges.filter((e: any) => e.src === target.id);
- let callList: string[] | undefined;
+ const diagnostics: Diagnostic[] = [];
+ let callList: EntityRef[] | undefined;
if (calleeEdges.length > 0 && calleeEdges.length <= 20) {
- const calleeNames = await Promise.all(
- calleeEdges.map(async (e: any) => {
+ const refs = await Promise.all(
+ calleeEdges.map(async (e: any): Promise<EntityRef> => {
try {
const callee = await client.entity(e.dst);
- return (callee.node as any).name || e.dst;
- } catch { return e.dst; }
+ const calleeNode = callee.node as any;
+ const name = calleeNode.name || calleeNode.attrs?.name || "";
+ if (!name || isRawId(name)) {
+ return {
+ name: name || e.dst,
+ kind: calleeNode.kind,
+ resolved: false,
+ suggestedCommand: `ix text "${e.dst.slice(0, 8)}"`,
+ };
+ }
+ return {
+ name,
+ kind: calleeNode.kind,
+ id: e.dst,
+ resolved: true,
+ path: calleeNode.provenance?.source_uri ?? calleeNode.provenance?.sourceUri,
+ suggestedCommand: `ix explain "${name}"`,
+ };
+ } catch {
+ return {
+ name: e.dst,
+ resolved: false,
+ diagnostic: "unresolved_call_target",
+ suggestedCommand: `ix text "${e.dst.slice(0, 8)}"`,
+ } as EntityRef;
+ }
})
);
- callList = calleeNames;
+ callList = refs;
+ const unresolvedCount = refs.filter(r => !r.resolved).length;
+ if (unresolvedCount > 0) {
+ diagnostics.push({
+ code: "unresolved_call_target",
+ message: `${unresolvedCount} callee(s) could not be resolved to named entities. Use ix text to locate them.`,
+ });
+ }
}
const result: ExplainResult = {
@@ -75,6 +107,7 @@ export function registerExplainCommand(program: Command): void {
signature,
docstring,
callList,
+ diagnostics: diagnostics.length > 0 ? diagnostics : undefined,
};
formatExplain(result, opts.format);
diff --git a/ix-cli/src/cli/commands/imports.ts b/ix-cli/src/cli/commands/imports.ts
index 0fd32e1b..00603b5b 100644
--- a/ix-cli/src/cli/commands/imports.ts
+++ b/ix-cli/src/cli/commands/imports.ts
@@ -17,7 +17,7 @@ export function registerImportsCommand(program: Command): void {
const limit = parseInt(opts.limit, 10);
const target = await resolveEntity(client, symbol, ["file", "module", "class"], opts);
if (!target) return;
- printResolved(target);
+ if (opts.format !== "json") printResolved(target);
const result = await client.expand(target.id, { direction: "out", predicates: ["IMPORTS"] });
formatEdgeResults(result.nodes.slice(0, limit), "imports", target.name, opts.format, target, "graph");
});
@@ -34,7 +34,7 @@ export function registerImportsCommand(program: Command): void {
const limit = parseInt(opts.limit, 10);
const target = await resolveEntity(client, symbol, ["file", "module", "class"], opts);
if (!target) return;
- printResolved(target);
+ if (opts.format !== "json") printResolved(target);
const result = await client.expand(target.id, { direction: "in", predicates: ["IMPORTS"] });
formatEdgeResults(result.nodes.slice(0, limit), "imported-by", target.name, opts.format, target, "graph");
});
diff --git a/ix-cli/src/cli/format.ts b/ix-cli/src/cli/format.ts
index 48c02f64..dd6853e9 100644
--- a/ix-cli/src/cli/format.ts
+++ b/ix-cli/src/cli/format.ts
@@ -313,19 +313,58 @@ export function formatLocateResults(results: LocateResult[], format: string): vo
export function formatEdgeResults(
nodes: any[], relation: string, symbol: string, format: string,
resolvedTarget?: { id: string; kind: string; name: string; resolutionMode?: string },
- source?: ResultSource
+ source?: ResultSource,
+ diagnostics?: Diagnostic[]
): void {
+ // Check for UUID-like names that indicate unresolved references
+ const isRawId = (s: string) =>
+ /^[0-9a-f]{8}-[0-9a-f]{4}-/i.test(s) || /^[0-9a-f]{32,}$/i.test(s);
+
if (format === "json") {
- const output: any = { results: nodes, resultSource: source ?? "graph" };
+ const results = nodes.map((n: any) => {
+ const name = n.name || n.attrs?.name || "";
+ const resolved = !!name && !isRawId(name);
+ const ref: any = {
+ name: resolved ? name : undefined,
+ kind: n.kind ?? undefined,
+ id: resolved ? n.id : undefined,
+ resolved,
+ path: n.provenance?.source_uri ?? n.provenance?.sourceUri ?? n.attrs?.path ?? undefined,
+ };
+ if (!resolved && n.id) {
+ ref.rawId = n.id;
+ ref.diagnostic = "unresolved_call_target";
+ }
+ return ref;
+ });
+
+ const output: any = {
+ results,
+ resultSource: source ?? "graph",
+ };
if (resolvedTarget) {
output.resolvedTarget = resolvedTarget;
output.resolutionMode = resolvedTarget.resolutionMode ?? "exact";
}
+ if (nodes.length === 0) {
+ output.diagnostics = diagnostics ?? [{ code: "no_edges", message: `No ${relation} edges found for resolved entity.` }];
+ } else if (diagnostics && diagnostics.length > 0) {
+ output.diagnostics = diagnostics;
+ }
+ const unresolvedCount = results.filter((r: any) => !r.resolved).length;
+ if (unresolvedCount > 0) {
+ output.diagnostics = [
+ ...(output.diagnostics ?? []),
+ { code: "dangling_reference_filtered", message: `${unresolvedCount} result(s) could not be resolved to named entities.` },
+ ];
+ }
+ output.summary = { total: results.length, resolved: results.length - unresolvedCount, unresolved: unresolvedCount };
console.log(JSON.stringify(output, null, 2));
return;
}
if (nodes.length === 0) {
- console.log(`No ${relation} found for "${symbol}".`);
+ const reason = diagnostics?.[0]?.message ?? `No ${relation} found for "${symbol}".`;
+ console.log(reason);
return;
}
console.log(`${chalk.bold(relation)} of ${chalk.cyan(symbol)}:`);
@@ -333,9 +372,13 @@ export function formatEdgeResults(
console.log(chalk.dim(`Source: ${source}`));
}
for (const n of nodes) {
+ const name = n.name || n.attrs?.name || "";
const shortId = n.id?.slice(0, 8) ?? "";
- const name = n.name || n.attrs?.name || n.id;
- console.log(` ${chalk.cyan((n.kind ?? "").padEnd(10))} ${chalk.dim(shortId)} ${chalk.bold(name)}`);
+ if (!name || isRawId(name)) {
+ console.log(` ${chalk.cyan((n.kind ?? "").padEnd(10))} ${chalk.dim(shortId)} ${chalk.dim("(unresolved)")}`);
+ } else {
+ console.log(` ${chalk.cyan((n.kind ?? "").padEnd(10))} ${chalk.dim(shortId)} ${chalk.bold(name)}`);
+ }
}
}
@@ -355,6 +398,31 @@ export function formatConflicts(conflicts: any[], format: string): void {
}
}
+/** A resolved or unresolved reference to a related entity. */
+export interface EntityRef {
+ name: string;
+ kind?: string;
+ id?: string;
+ resolved: boolean;
+ path?: string;
+ lineStart?: number;
+ lineEnd?: number;
+ suggestedCommand?: string;
+}
+
+export type DiagnosticCode =
+ | "unresolved_call_target"
+ | "parser_gap_suspected"
+ | "dangling_reference_filtered"
+ | "ambiguous_resolution"
+ | "no_edges"
+ | "text_fallback_used";
+
+export interface Diagnostic {
+ code: DiagnosticCode;
+ message: string;
+}
+
export interface ExplainResult {
kind: string;
name: string;
@@ -368,12 +436,36 @@ export interface ExplainResult {
historyLength: number;
signature?: string;
docstring?: string;
- callList?: string[];
+ callList?: EntityRef[];
+ diagnostics?: Diagnostic[];
}
export function formatExplain(result: ExplainResult, format: string): void {
if (format === "json") {
- console.log(JSON.stringify({ ...result, resultSource: "graph" }, null, 2));
+ const output: any = {
+ resolvedTarget: { id: result.id, kind: result.kind, name: result.name },
+ resolutionMode: "exact",
+ resultSource: "graph",
+ result: {
+ kind: result.kind,
+ name: result.name,
+ id: result.id,
+ file: result.file,
+ container: result.container,
+ introducedRev: result.introducedRev,
+ calledBy: result.calledBy,
+ calls: result.calls,
+ contains: result.contains,
+ historyLength: result.historyLength,
+ signature: result.signature,
+ docstring: result.docstring,
+ callList: result.callList,
+ },
+ };
+ if (result.diagnostics && result.diagnostics.length > 0) {
+ output.diagnostics = result.diagnostics;
+ }
+ console.log(JSON.stringify(output, null, 2));
return;
}
const shortId = result.id.slice(0, 8);
@@ -396,11 +488,19 @@ export function formatExplain(result: ExplainResult, format: string): void {
if (result.callList && result.callList.length > 0) {
console.log(` ${chalk.dim("calls:")}`);
for (const c of result.callList) {
- console.log(` ${c}`);
+ const label = c.resolved
+ ? c.name
+ : chalk.dim(`${c.name} (unresolved)`);
+ console.log(` ${label}`);
}
} else if (result.calls > 0) {
console.log(` ${chalk.dim("calls")} ${result.calls} methods`);
}
if (result.contains > 0) console.log(` ${chalk.dim("contains")} ${result.contains} members`);
if (result.historyLength > 0) console.log(` ${chalk.dim("history")} ${result.historyLength} patches`);
+ if (result.diagnostics && result.diagnostics.length > 0) {
+ for (const d of result.diagnostics) {
+ console.log(` ${chalk.dim(`[${d.code}]`)} ${d.message}`);
+ }
+ }
}
diff --git a/ix-cli/src/cli/resolve.ts b/ix-cli/src/cli/resolve.ts
index 8d3f448a..52e3157f 100644
--- a/ix-cli/src/cli/resolve.ts
+++ b/ix-cli/src/cli/resolve.ts
@@ -73,7 +73,8 @@ export async function resolveEntity(
}
/**
- * Print the resolved target before showing results.
+ * Print the resolved target before showing results (text mode only).
+ * Callers should skip this when format === "json" to keep JSON strict.
*/
export function printResolved(target: ResolvedEntity): void {
const shortId = target.id.slice(0, 8);
@@ -82,3 +83,9 @@ export function printResolved(target: ResolvedEntity): void {
: "";
console.log(`${chalk.dim("Resolved:")} ${chalk.cyan(target.kind)} ${chalk.dim(shortId)} ${chalk.bold(target.name)}${modeStr}\n`);
}
+
+/** Check if a string looks like a raw UUID (not a human-readable name). */
+export function isRawId(s: string): boolean {
+ return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i.test(s)
+ || /^[0-9a-f]{32,}$/i.test(s);
+}