Skip to content

armgit / Ix

Public Imported from GitHub
0

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

feat: chalk-based terminal UI with colored confidence and tree view

riley0227c3f19a9340cc
diff --git a/ix-cli/src/cli/__tests__/format.test.ts b/ix-cli/src/cli/__tests__/format.test.ts
new file mode 100644
index 00000000..2c6c2088
--- /dev/null
+++ b/ix-cli/src/cli/__tests__/format.test.ts
@@ -0,0 +1,246 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from "vitest";
+import {
+ formatContext,
+ formatIntents,
+ formatConflicts,
+ confidenceColor,
+} from "../format.js";
+
+// Strip ANSI escape codes for clean assertions
+function stripAnsi(s: string): string {
+ return s.replace(/\u001b\[[0-9;]*m/g, "");
+}
+
+// Capture console.log output
+function captureLog(fn: () => void): string {
+ const lines: string[] = [];
+ const origLog = console.log;
+ console.log = (...args: unknown[]) => {
+ lines.push(args.map(String).join(" "));
+ };
+ try {
+ fn();
+ } finally {
+ console.log = origLog;
+ }
+ return lines.join("\n");
+}
+
+describe("confidenceColor", () => {
+ it("returns green for high confidence (>= 0.8)", () => {
+ const color = confidenceColor(0.9);
+ const result = color("test");
+ // chalk.green wraps text; stripped should still have the text
+ expect(stripAnsi(result)).toBe("test");
+ // The raw output should contain ANSI codes (or not, if chalk level is 0)
+ // Either way, the function should return a function
+ expect(typeof confidenceColor(0.8)).toBe("function");
+ });
+
+ it("returns yellow for medium confidence (0.5–0.79)", () => {
+ const color = confidenceColor(0.6);
+ const result = color("test");
+ expect(stripAnsi(result)).toBe("test");
+ expect(typeof confidenceColor(0.5)).toBe("function");
+ });
+
+ it("returns red for low confidence (< 0.5)", () => {
+ const color = confidenceColor(0.3);
+ const result = color("test");
+ expect(stripAnsi(result)).toBe("test");
+ expect(typeof confidenceColor(0.0)).toBe("function");
+ });
+
+ it("boundary: 0.8 is green, 0.79 is yellow, 0.49 is red", () => {
+ // 0.8 should be green
+ const green = confidenceColor(0.8);
+ // 0.79 should be yellow
+ const yellow = confidenceColor(0.79);
+ // 0.49 should be red
+ const red = confidenceColor(0.49);
+
+ // All should be functions
+ expect(typeof green).toBe("function");
+ expect(typeof yellow).toBe("function");
+ expect(typeof red).toBe("function");
+
+ // They should all produce the text content
+ expect(stripAnsi(green("x"))).toBe("x");
+ expect(stripAnsi(yellow("x"))).toBe("x");
+ expect(stripAnsi(red("x"))).toBe("x");
+ });
+});
+
+describe("formatContext", () => {
+ it("outputs JSON when format is json", () => {
+ const result = {
+ claims: [],
+ conflicts: [],
+ decisions: [],
+ intents: [],
+ metadata: {
+ query: "test",
+ seedEntities: [],
+ hopsExpanded: 1,
+ asOfRev: 5,
+ },
+ };
+ const output = captureLog(() => formatContext(result, "json"));
+ const parsed = JSON.parse(output);
+ expect(parsed.metadata.query).toBe("test");
+ expect(parsed.metadata.asOfRev).toBe(5);
+ });
+
+ it("produces expected text output structure", () => {
+ const result = {
+ claims: [
+ {
+ claim: { statement: "Claim A" },
+ finalScore: 0.95,
+ },
+ {
+ claim: { statement: "Claim B" },
+ finalScore: 0.4,
+ },
+ ],
+ conflicts: [{ reason: "Contradiction", recommendation: "Resolve it" }],
+ decisions: [{ title: "Use X", rationale: "Because Y" }],
+ intents: [{ statement: "Build feature", status: "active" }],
+ metadata: {
+ query: "project alpha",
+ seedEntities: ["e1", "e2"],
+ hopsExpanded: 2,
+ asOfRev: 10,
+ },
+ };
+
+ const output = captureLog(() => formatContext(result, "text"));
+ const plain = stripAnsi(output);
+
+ // Header
+ expect(plain).toContain('--- Ix Context: "project alpha" ---');
+ // Metadata
+ expect(plain).toContain("Seeds: 2 | Hops: 2 | Rev: 10");
+ // Claims section
+ expect(plain).toContain("Claims (2):");
+ expect(plain).toContain("[95%]");
+ expect(plain).toContain("Claim A");
+ expect(plain).toContain("[40%]");
+ expect(plain).toContain("Claim B");
+ // Conflicts
+ expect(plain).toContain("Conflicts (1):");
+ expect(plain).toContain("! Contradiction: Resolve it");
+ // Decisions
+ expect(plain).toContain("Decisions (1):");
+ expect(plain).toContain("* Use X: Because Y");
+ // Intents
+ expect(plain).toContain("Intents (1):");
+ expect(plain).toContain("> Build feature [active]");
+ });
+
+ it("shows truncation message when more than 10 claims", () => {
+ const claims = Array.from({ length: 15 }, (_, i) => ({
+ claim: { statement: `Claim ${i}` },
+ finalScore: 0.5,
+ }));
+ const result = {
+ claims,
+ conflicts: [],
+ decisions: [],
+ intents: [],
+ metadata: {
+ query: "big",
+ seedEntities: [],
+ hopsExpanded: 1,
+ asOfRev: 1,
+ },
+ };
+
+ const output = captureLog(() => formatContext(result, "text"));
+ const plain = stripAnsi(output);
+ expect(plain).toContain("... and 5 more");
+ });
+});
+
+describe("formatIntents", () => {
+ it("outputs JSON when format is json", () => {
+ const intents = [{ id: "i1", statement: "Do X", status: "active", confidence: 0.9 }];
+ const output = captureLog(() => formatIntents(intents, "json"));
+ const parsed = JSON.parse(output);
+ expect(parsed).toHaveLength(1);
+ expect(parsed[0].statement).toBe("Do X");
+ });
+
+ it("handles empty list", () => {
+ const output = captureLog(() => formatIntents([], "text"));
+ expect(output).toContain("No intents found.");
+ });
+
+ it("builds parent-child tree", () => {
+ const intents = [
+ { id: "root1", statement: "Root intent", status: "active", confidence: 0.85 },
+ { id: "child1", statement: "Child intent", status: "pending", confidence: 0.6, parentIntent: "root1" },
+ { id: "root2", statement: "Another root", status: "done", confidence: 0.3 },
+ ];
+
+ const output = captureLog(() => formatIntents(intents, "text"));
+ const plain = stripAnsi(output);
+
+ // Root intents should appear with ">" prefix
+ expect(plain).toContain("> Root intent [active]");
+ expect(plain).toContain("> Another root [done]");
+
+ // Children should appear indented with tree connector
+ expect(plain).toContain("\u2514\u2500 Child intent [pending]");
+
+ // Confidence percentages should appear
+ expect(plain).toContain("(85%)");
+ expect(plain).toContain("(60%)");
+ expect(plain).toContain("(30%)");
+ });
+
+ it("handles intents with no confidence field", () => {
+ const intents = [
+ { id: "i1", statement: "No conf", status: "active" },
+ ];
+ const output = captureLog(() => formatIntents(intents, "text"));
+ const plain = stripAnsi(output);
+ expect(plain).toContain("(0%)");
+ });
+});
+
+describe("formatConflicts", () => {
+ it("outputs JSON when format is json", () => {
+ const conflicts = [
+ { id: "c1", reason: "Contradiction", recommendation: "Fix it", claimA: "A", claimB: "B" },
+ ];
+ const output = captureLog(() => formatConflicts(conflicts, "json"));
+ const parsed = JSON.parse(output);
+ expect(parsed).toHaveLength(1);
+ expect(parsed[0].reason).toBe("Contradiction");
+ });
+
+ it("handles empty list", () => {
+ const output = captureLog(() => formatConflicts([], "text"));
+ expect(output).toContain("No conflicts detected.");
+ });
+
+ it("formats conflict details", () => {
+ const conflicts = [
+ {
+ id: "c1",
+ reason: "Data contradicts policy",
+ recommendation: "Review the source",
+ claimA: "claim-aaa",
+ claimB: "claim-bbb",
+ },
+ ];
+
+ const output = captureLog(() => formatConflicts(conflicts, "text"));
+ const plain = stripAnsi(output);
+
+ expect(plain).toContain("! Data contradicts policy");
+ expect(plain).toContain("Review the source");
+ expect(plain).toContain("Claims: claim-aaa vs claim-bbb");
+ });
+});
diff --git a/ix-cli/src/cli/commands/conflicts.ts b/ix-cli/src/cli/commands/conflicts.ts
index 75e217ef..99a322eb 100644
--- a/ix-cli/src/cli/commands/conflicts.ts
+++ b/ix-cli/src/cli/commands/conflicts.ts
@@ -1,6 +1,7 @@
import type { Command } from "commander";
import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
+import { formatConflicts } from "../format.js";
export function registerConflictsCommand(program: Command): void {
program
@@ -10,14 +11,6 @@ export function registerConflictsCommand(program: Command): void {
.action(async (opts: { format: string }) => {
const client = new IxClient(getEndpoint());
const conflicts = await client.conflicts();
- if (opts.format === "json") {
- console.log(JSON.stringify(conflicts, null, 2));
- } else {
- if ((conflicts as unknown[]).length === 0) {
- console.log("No conflicts detected.");
- } else {
- console.log(JSON.stringify(conflicts, null, 2));
- }
- }
+ formatConflicts(conflicts as any[], opts.format);
});
}
diff --git a/ix-cli/src/cli/commands/truth.ts b/ix-cli/src/cli/commands/truth.ts
index 914d3fa7..aac51b09 100644
--- a/ix-cli/src/cli/commands/truth.ts
+++ b/ix-cli/src/cli/commands/truth.ts
@@ -1,7 +1,7 @@
import type { Command } from "commander";
import { IxClient } from "../../client/api.js";
import { getEndpoint } from "../config.js";
-import { formatNodes } from "../format.js";
+import { formatIntents } from "../format.js";
export function registerTruthCommand(program: Command): void {
const truth = program
@@ -15,7 +15,7 @@ export function registerTruthCommand(program: Command): void {
.action(async (opts: { format: string }) => {
const client = new IxClient(getEndpoint());
const intents = await client.listTruth();
- formatNodes(intents, opts.format);
+ formatIntents(intents, opts.format);
});
truth
diff --git a/ix-cli/src/cli/format.ts b/ix-cli/src/cli/format.ts
index 6dcf01ac..0d2044ab 100644
--- a/ix-cli/src/cli/format.ts
+++ b/ix-cli/src/cli/format.ts
@@ -1,3 +1,11 @@
+import chalk from "chalk";
+
+export function confidenceColor(score: number): (text: string) => string {
+ if (score >= 0.8) return chalk.green;
+ if (score >= 0.5) return chalk.yellow;
+ return chalk.red;
+}
+
export function formatContext(result: any, format: string): void {
if (format === "json") {
console.log(JSON.stringify(result, null, 2));
@@ -7,36 +15,49 @@ export function formatContext(result: any, format: string): void {
// Text format
const { claims, conflicts, decisions, intents, metadata } = result;
- console.log(`\n--- Ix Context: "${metadata.query}" ---`);
- console.log(`Seeds: ${metadata.seedEntities.length} | Hops: ${metadata.hopsExpanded} | Rev: ${metadata.asOfRev}`);
+ console.log(
+ "\n" + chalk.bold.cyan(`--- Ix Context: "${metadata.query}" ---`)
+ );
+ console.log(
+ chalk.dim(
+ `Seeds: ${metadata.seedEntities.length} | Hops: ${metadata.hopsExpanded} | Rev: ${metadata.asOfRev}`
+ )
+ );
if (claims && claims.length > 0) {
console.log(`\nClaims (${claims.length}):`);
for (const sc of claims.slice(0, 10)) {
- const conf = (sc.finalScore * 100).toFixed(0);
- console.log(` [${conf}%] ${sc.claim.statement}`);
+ const pct = sc.finalScore * 100;
+ const conf = pct.toFixed(0);
+ const color = confidenceColor(sc.finalScore);
+ console.log(` ${color(`[${conf}%]`)} ${sc.claim.statement}`);
}
- if (claims.length > 10) console.log(` ... and ${claims.length - 10} more`);
+ if (claims.length > 10)
+ console.log(chalk.dim(` ... and ${claims.length - 10} more`));
}
if (conflicts && conflicts.length > 0) {
console.log(`\nConflicts (${conflicts.length}):`);
for (const c of conflicts) {
- console.log(` ! ${c.reason}: ${c.recommendation}`);
+ console.log(
+ ` ${chalk.red.bold("!")} ${c.reason}: ${c.recommendation}`
+ );
}
}
if (decisions && decisions.length > 0) {
console.log(`\nDecisions (${decisions.length}):`);
for (const d of decisions) {
- console.log(` * ${d.title}: ${d.rationale}`);
+ console.log(` ${chalk.blue("*")} ${d.title}: ${d.rationale}`);
}
}
if (intents && intents.length > 0) {
console.log(`\nIntents (${intents.length}):`);
for (const i of intents) {
- console.log(` > ${i.statement} [${i.status}]`);
+ console.log(
+ ` ${chalk.magenta(">")} ${i.statement} [${i.status}]`
+ );
}
}
console.log();
@@ -52,7 +73,10 @@ export function formatNodes(nodes: any[], format: string): void {
return;
}
for (const n of nodes) {
- console.log(` ${n.kind} ${n.id} attrs: ${JSON.stringify(n.attrs)}`);
+ const shortId = n.id.length > 8 ? n.id.slice(0, 8) : n.id;
+ console.log(
+ ` ${chalk.cyan(n.kind)} ${chalk.dim(shortId)} attrs: ${chalk.gray(JSON.stringify(n.attrs))}`
+ );
}
}
@@ -66,6 +90,75 @@ export function formatPatches(patches: any[], format: string): void {
return;
}
for (const p of patches) {
- console.log(` rev ${p.rev} ${p.patch_id} ${p.intent || "(no intent)"}`);
+ const shortPatchId =
+ p.patch_id.length > 8 ? p.patch_id.slice(0, 8) : p.patch_id;
+ const intentPart = p.intent
+ ? chalk.white(p.intent)
+ : chalk.dim("(no intent)");
+ console.log(
+ ` rev ${chalk.cyan.bold(String(p.rev))} ${chalk.dim(shortPatchId)} ${intentPart}`
+ );
+ }
+}
+
+export function formatIntents(intents: any[], format: string): void {
+ if (format === "json") {
+ console.log(JSON.stringify(intents, null, 2));
+ return;
+ }
+ if (intents.length === 0) {
+ console.log("No intents found.");
+ return;
+ }
+
+ // Build parent-child map
+ const childrenMap = new Map<string, any[]>();
+ const roots: any[] = [];
+
+ for (const intent of intents) {
+ if (intent.parentIntent) {
+ const siblings = childrenMap.get(intent.parentIntent) || [];
+ siblings.push(intent);
+ childrenMap.set(intent.parentIntent, siblings);
+ } else {
+ roots.push(intent);
+ }
+ }
+
+ function printIntent(intent: any, indent: string, isChild: boolean): void {
+ const prefix = isChild
+ ? `${indent}${chalk.dim("\u2514\u2500")} `
+ : `${indent}${chalk.magenta(">")} `;
+ const conf = intent.confidence ?? 0;
+ const pctStr = `(${(conf * 100).toFixed(0)}%)`;
+ const color = confidenceColor(conf);
+ console.log(
+ `${prefix}${intent.statement} [${intent.status}] ${color(pctStr)}`
+ );
+
+ const children = childrenMap.get(intent.id) || [];
+ for (const child of children) {
+ printIntent(child, indent + " ", true);
+ }
+ }
+
+ for (const root of roots) {
+ printIntent(root, " ", false);
+ }
+}
+
+export function formatConflicts(conflicts: any[], format: string): void {
+ if (format === "json") {
+ console.log(JSON.stringify(conflicts, null, 2));
+ return;
+ }
+ if (conflicts.length === 0) {
+ console.log("No conflicts detected.");
+ return;
+ }
+ for (const c of conflicts) {
+ console.log(` ${chalk.red.bold("!")} ${c.reason}`);
+ console.log(` ${chalk.yellow(c.recommendation)}`);
+ console.log(` Claims: ${c.claimA} vs ${c.claimB}`);
}
}